Scheduler.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <AK/QuickSort.h>
  27. #include <AK/TemporaryChange.h>
  28. #include <Kernel/Arch/i386/PIT.h>
  29. #include <Kernel/FileSystem/FileDescription.h>
  30. #include <Kernel/Process.h>
  31. #include <Kernel/Profiling.h>
  32. #include <Kernel/RTC.h>
  33. #include <Kernel/Scheduler.h>
  34. #include <Kernel/TimerQueue.h>
  35. //#define LOG_EVERY_CONTEXT_SWITCH
  36. //#define SCHEDULER_DEBUG
  37. //#define SCHEDULER_RUNNABLE_DEBUG
  38. SchedulerData* g_scheduler_data;
  39. void Scheduler::init_thread(Thread& thread)
  40. {
  41. g_scheduler_data->m_nonrunnable_threads.append(thread);
  42. }
  43. void Scheduler::update_state_for_thread(Thread& thread)
  44. {
  45. ASSERT_INTERRUPTS_DISABLED();
  46. auto& list = g_scheduler_data->thread_list_for_state(thread.state());
  47. if (list.contains(thread))
  48. return;
  49. list.append(thread);
  50. }
  51. static u32 time_slice_for(const Thread& thread)
  52. {
  53. // One time slice unit == 1ms
  54. if (&thread == g_colonel)
  55. return 1;
  56. return 10;
  57. }
  58. Thread* current;
  59. Thread* g_finalizer;
  60. Thread* g_colonel;
  61. WaitQueue* g_finalizer_wait_queue;
  62. bool g_finalizer_has_work;
  63. static Process* s_colonel_process;
  64. u64 g_uptime;
  65. struct TaskRedirectionData {
  66. u16 selector;
  67. TSS32 tss;
  68. };
  69. static TaskRedirectionData s_redirection;
  70. static bool s_active;
  71. bool Scheduler::is_active()
  72. {
  73. return s_active;
  74. }
  75. Thread::JoinBlocker::JoinBlocker(Thread& joinee, void*& joinee_exit_value)
  76. : m_joinee(joinee)
  77. , m_joinee_exit_value(joinee_exit_value)
  78. {
  79. ASSERT(m_joinee.m_joiner == nullptr);
  80. m_joinee.m_joiner = current;
  81. current->m_joinee = &joinee;
  82. }
  83. bool Thread::JoinBlocker::should_unblock(Thread& joiner, time_t, long)
  84. {
  85. return !joiner.m_joinee;
  86. }
  87. Thread::FileDescriptionBlocker::FileDescriptionBlocker(const FileDescription& description)
  88. : m_blocked_description(description)
  89. {
  90. }
  91. const FileDescription& Thread::FileDescriptionBlocker::blocked_description() const
  92. {
  93. return m_blocked_description;
  94. }
  95. Thread::AcceptBlocker::AcceptBlocker(const FileDescription& description)
  96. : FileDescriptionBlocker(description)
  97. {
  98. }
  99. bool Thread::AcceptBlocker::should_unblock(Thread&, time_t, long)
  100. {
  101. auto& socket = *blocked_description().socket();
  102. return socket.can_accept();
  103. }
  104. Thread::ConnectBlocker::ConnectBlocker(const FileDescription& description)
  105. : FileDescriptionBlocker(description)
  106. {
  107. }
  108. bool Thread::ConnectBlocker::should_unblock(Thread&, time_t, long)
  109. {
  110. auto& socket = *blocked_description().socket();
  111. return socket.setup_state() == Socket::SetupState::Completed;
  112. }
  113. Thread::WriteBlocker::WriteBlocker(const FileDescription& description)
  114. : FileDescriptionBlocker(description)
  115. {
  116. if (description.is_socket()) {
  117. auto& socket = *description.socket();
  118. if (socket.has_send_timeout()) {
  119. timeval deadline = kgettimeofday();
  120. deadline.tv_sec += socket.send_timeout().tv_sec;
  121. deadline.tv_usec += socket.send_timeout().tv_usec;
  122. deadline.tv_sec += (socket.send_timeout().tv_usec / 1000000) * 1;
  123. deadline.tv_usec %= 1000000;
  124. m_deadline = deadline;
  125. }
  126. }
  127. }
  128. bool Thread::WriteBlocker::should_unblock(Thread&, time_t now_sec, long now_usec)
  129. {
  130. if (m_deadline.has_value()) {
  131. bool timed_out = now_sec > m_deadline.value().tv_sec || (now_sec == m_deadline.value().tv_sec && now_usec >= m_deadline.value().tv_usec);
  132. return timed_out || blocked_description().can_write();
  133. }
  134. return blocked_description().can_write();
  135. }
  136. Thread::ReadBlocker::ReadBlocker(const FileDescription& description)
  137. : FileDescriptionBlocker(description)
  138. {
  139. if (description.is_socket()) {
  140. auto& socket = *description.socket();
  141. if (socket.has_receive_timeout()) {
  142. timeval deadline = kgettimeofday();
  143. deadline.tv_sec += socket.receive_timeout().tv_sec;
  144. deadline.tv_usec += socket.receive_timeout().tv_usec;
  145. deadline.tv_sec += (socket.receive_timeout().tv_usec / 1000000) * 1;
  146. deadline.tv_usec %= 1000000;
  147. m_deadline = deadline;
  148. }
  149. }
  150. }
  151. bool Thread::ReadBlocker::should_unblock(Thread&, time_t now_sec, long now_usec)
  152. {
  153. if (m_deadline.has_value()) {
  154. bool timed_out = now_sec > m_deadline.value().tv_sec || (now_sec == m_deadline.value().tv_sec && now_usec >= m_deadline.value().tv_usec);
  155. return timed_out || blocked_description().can_read();
  156. }
  157. return blocked_description().can_read();
  158. }
  159. Thread::ConditionBlocker::ConditionBlocker(const char* state_string, Function<bool()>&& condition)
  160. : m_block_until_condition(move(condition))
  161. , m_state_string(state_string)
  162. {
  163. ASSERT(m_block_until_condition);
  164. }
  165. bool Thread::ConditionBlocker::should_unblock(Thread&, time_t, long)
  166. {
  167. return m_block_until_condition();
  168. }
  169. Thread::SleepBlocker::SleepBlocker(u64 wakeup_time)
  170. : m_wakeup_time(wakeup_time)
  171. {
  172. }
  173. bool Thread::SleepBlocker::should_unblock(Thread&, time_t, long)
  174. {
  175. return m_wakeup_time <= g_uptime;
  176. }
  177. Thread::SelectBlocker::SelectBlocker(const timeval& tv, bool select_has_timeout, const FDVector& read_fds, const FDVector& write_fds, const FDVector& except_fds)
  178. : m_select_timeout(tv)
  179. , m_select_has_timeout(select_has_timeout)
  180. , m_select_read_fds(read_fds)
  181. , m_select_write_fds(write_fds)
  182. , m_select_exceptional_fds(except_fds)
  183. {
  184. }
  185. bool Thread::SelectBlocker::should_unblock(Thread& thread, time_t now_sec, long now_usec)
  186. {
  187. if (m_select_has_timeout) {
  188. if (now_sec > m_select_timeout.tv_sec || (now_sec == m_select_timeout.tv_sec && now_usec >= m_select_timeout.tv_usec))
  189. return true;
  190. }
  191. auto& process = thread.process();
  192. for (int fd : m_select_read_fds) {
  193. if (!process.m_fds[fd])
  194. continue;
  195. if (process.m_fds[fd].description->can_read())
  196. return true;
  197. }
  198. for (int fd : m_select_write_fds) {
  199. if (!process.m_fds[fd])
  200. continue;
  201. if (process.m_fds[fd].description->can_write())
  202. return true;
  203. }
  204. return false;
  205. }
  206. Thread::WaitBlocker::WaitBlocker(int wait_options, pid_t& waitee_pid)
  207. : m_wait_options(wait_options)
  208. , m_waitee_pid(waitee_pid)
  209. {
  210. }
  211. bool Thread::WaitBlocker::should_unblock(Thread& thread, time_t, long)
  212. {
  213. bool should_unblock = false;
  214. if (m_waitee_pid != -1) {
  215. auto* peer = Process::from_pid(m_waitee_pid);
  216. if (!peer)
  217. return true;
  218. }
  219. thread.process().for_each_child([&](Process& child) {
  220. if (m_waitee_pid != -1 && m_waitee_pid != child.pid())
  221. return IterationDecision::Continue;
  222. bool child_exited = child.is_dead();
  223. bool child_stopped = child.thread_count() && child.any_thread().state() == Thread::State::Stopped;
  224. bool wait_finished = ((m_wait_options & WEXITED) && child_exited)
  225. || ((m_wait_options & WSTOPPED) && child_stopped);
  226. if (!wait_finished)
  227. return IterationDecision::Continue;
  228. m_waitee_pid = child.pid();
  229. should_unblock = true;
  230. return IterationDecision::Break;
  231. });
  232. return should_unblock;
  233. }
  234. Thread::SemiPermanentBlocker::SemiPermanentBlocker(Reason reason)
  235. : m_reason(reason)
  236. {
  237. }
  238. bool Thread::SemiPermanentBlocker::should_unblock(Thread&, time_t, long)
  239. {
  240. // someone else has to unblock us
  241. return false;
  242. }
  243. // Called by the scheduler on threads that are blocked for some reason.
  244. // Make a decision as to whether to unblock them or not.
  245. void Thread::consider_unblock(time_t now_sec, long now_usec)
  246. {
  247. switch (state()) {
  248. case Thread::Invalid:
  249. case Thread::Runnable:
  250. case Thread::Running:
  251. case Thread::Dead:
  252. case Thread::Stopped:
  253. case Thread::Queued:
  254. case Thread::Dying:
  255. /* don't know, don't care */
  256. return;
  257. case Thread::Blocked:
  258. ASSERT(m_blocker != nullptr);
  259. if (m_blocker->should_unblock(*this, now_sec, now_usec))
  260. unblock();
  261. return;
  262. case Thread::Skip1SchedulerPass:
  263. set_state(Thread::Skip0SchedulerPasses);
  264. return;
  265. case Thread::Skip0SchedulerPasses:
  266. set_state(Thread::Runnable);
  267. return;
  268. }
  269. }
  270. bool Scheduler::pick_next()
  271. {
  272. ASSERT_INTERRUPTS_DISABLED();
  273. ASSERT(!s_active);
  274. TemporaryChange<bool> change(s_active, true);
  275. ASSERT(s_active);
  276. if (!current) {
  277. // XXX: The first ever context_switch() goes to the idle process.
  278. // This to setup a reliable place we can return to.
  279. return context_switch(*g_colonel);
  280. }
  281. struct timeval now;
  282. kgettimeofday(now);
  283. auto now_sec = now.tv_sec;
  284. auto now_usec = now.tv_usec;
  285. // Check and unblock threads whose wait conditions have been met.
  286. Scheduler::for_each_nonrunnable([&](Thread& thread) {
  287. thread.consider_unblock(now_sec, now_usec);
  288. return IterationDecision::Continue;
  289. });
  290. Process::for_each([&](Process& process) {
  291. if (process.is_dead()) {
  292. if (current->pid() != process.pid() && (!process.ppid() || !Process::from_pid(process.ppid()))) {
  293. auto name = process.name();
  294. auto pid = process.pid();
  295. auto exit_status = Process::reap(process);
  296. dbgprintf("reaped unparented process %s(%u), exit status: %u\n", name.characters(), pid, exit_status);
  297. }
  298. return IterationDecision::Continue;
  299. }
  300. if (process.m_alarm_deadline && g_uptime > process.m_alarm_deadline) {
  301. process.m_alarm_deadline = 0;
  302. process.send_signal(SIGALRM, nullptr);
  303. }
  304. return IterationDecision::Continue;
  305. });
  306. // Dispatch any pending signals.
  307. Thread::for_each_living([](Thread& thread) -> IterationDecision {
  308. if (!thread.has_unmasked_pending_signals())
  309. return IterationDecision::Continue;
  310. // FIXME: It would be nice if the Scheduler didn't have to worry about who is "current"
  311. // For now, avoid dispatching signals to "current" and do it in a scheduling pass
  312. // while some other process is interrupted. Otherwise a mess will be made.
  313. if (&thread == current)
  314. return IterationDecision::Continue;
  315. // We know how to interrupt blocked processes, but if they are just executing
  316. // at some random point in the kernel, let them continue.
  317. // Before returning to userspace from a syscall, we will block a thread if it has any
  318. // pending unmasked signals, allowing it to be dispatched then.
  319. if (thread.in_kernel() && !thread.is_blocked() && !thread.is_stopped())
  320. return IterationDecision::Continue;
  321. // NOTE: dispatch_one_pending_signal() may unblock the process.
  322. bool was_blocked = thread.is_blocked();
  323. if (thread.dispatch_one_pending_signal() == ShouldUnblockThread::No)
  324. return IterationDecision::Continue;
  325. if (was_blocked) {
  326. dbgprintf("Unblock %s(%u) due to signal\n", thread.process().name().characters(), thread.pid());
  327. ASSERT(thread.m_blocker != nullptr);
  328. thread.m_blocker->set_interrupted_by_signal();
  329. thread.unblock();
  330. }
  331. return IterationDecision::Continue;
  332. });
  333. #ifdef SCHEDULER_RUNNABLE_DEBUG
  334. dbgprintf("Non-runnables:\n");
  335. Scheduler::for_each_nonrunnable([](Thread& thread) -> IterationDecision {
  336. dbgprintf(" %-12s %s(%u:%u) @ %w:%x\n", thread.state_string(), thread.name().characters(), thread.pid(), thread.tid(), thread.tss().cs, thread.tss().eip);
  337. return IterationDecision::Continue;
  338. });
  339. dbgprintf("Runnables:\n");
  340. Scheduler::for_each_runnable([](Thread& thread) -> IterationDecision {
  341. dbgprintf(" %3u/%2u %-12s %s(%u:%u) @ %w:%x\n", thread.effective_priority(), thread.priority(), thread.state_string(), thread.name().characters(), thread.pid(), thread.tid(), thread.tss().cs, thread.tss().eip);
  342. return IterationDecision::Continue;
  343. });
  344. #endif
  345. Vector<Thread*, 128> sorted_runnables;
  346. for_each_runnable([&sorted_runnables](auto& thread) {
  347. sorted_runnables.append(&thread);
  348. return IterationDecision::Continue;
  349. });
  350. quick_sort(sorted_runnables.begin(), sorted_runnables.end(), [](auto& a, auto& b) { return a->effective_priority() >= b->effective_priority(); });
  351. Thread* thread_to_schedule = nullptr;
  352. for (auto* thread : sorted_runnables) {
  353. if (thread->process().is_being_inspected())
  354. continue;
  355. ASSERT(thread->state() == Thread::Runnable || thread->state() == Thread::Running);
  356. if (!thread_to_schedule) {
  357. thread->m_extra_priority = 0;
  358. thread_to_schedule = thread;
  359. } else {
  360. thread->m_extra_priority++;
  361. }
  362. }
  363. if (!thread_to_schedule)
  364. thread_to_schedule = g_colonel;
  365. #ifdef SCHEDULER_DEBUG
  366. dbgprintf("switch to %s(%u:%u) @ %w:%x\n",
  367. thread_to_schedule->name().characters(),
  368. thread_to_schedule->pid(),
  369. thread_to_schedule->tid(),
  370. thread_to_schedule->tss().cs,
  371. thread_to_schedule->tss().eip);
  372. #endif
  373. return context_switch(*thread_to_schedule);
  374. }
  375. bool Scheduler::donate_to(Thread* beneficiary, const char* reason)
  376. {
  377. InterruptDisabler disabler;
  378. if (!Thread::is_thread(beneficiary))
  379. return false;
  380. (void)reason;
  381. unsigned ticks_left = current->ticks_left();
  382. if (!beneficiary || beneficiary->state() != Thread::Runnable || ticks_left <= 1)
  383. return yield();
  384. unsigned ticks_to_donate = min(ticks_left - 1, time_slice_for(*beneficiary));
  385. #ifdef SCHEDULER_DEBUG
  386. dbgprintf("%s(%u:%u) donating %u ticks to %s(%u:%u), reason=%s\n", current->process().name().characters(), current->pid(), current->tid(), ticks_to_donate, beneficiary->process().name().characters(), beneficiary->pid(), beneficiary->tid(), reason);
  387. #endif
  388. context_switch(*beneficiary);
  389. beneficiary->set_ticks_left(ticks_to_donate);
  390. switch_now();
  391. return false;
  392. }
  393. bool Scheduler::yield()
  394. {
  395. InterruptDisabler disabler;
  396. ASSERT(current);
  397. if (!pick_next())
  398. return false;
  399. switch_now();
  400. return true;
  401. }
  402. void Scheduler::pick_next_and_switch_now()
  403. {
  404. bool someone_wants_to_run = pick_next();
  405. ASSERT(someone_wants_to_run);
  406. switch_now();
  407. }
  408. void Scheduler::switch_now()
  409. {
  410. Descriptor& descriptor = get_gdt_entry(current->selector());
  411. descriptor.type = 9;
  412. asm("sti\n"
  413. "ljmp *(%%eax)\n" ::"a"(&current->far_ptr()));
  414. }
  415. bool Scheduler::context_switch(Thread& thread)
  416. {
  417. thread.set_ticks_left(time_slice_for(thread));
  418. thread.did_schedule();
  419. if (current == &thread)
  420. return false;
  421. if (current) {
  422. // If the last process hasn't blocked (still marked as running),
  423. // mark it as runnable for the next round.
  424. if (current->state() == Thread::Running)
  425. current->set_state(Thread::Runnable);
  426. asm volatile("fxsave %0"
  427. : "=m"(current->fpu_state()));
  428. #ifdef LOG_EVERY_CONTEXT_SWITCH
  429. dbgprintf("Scheduler: %s(%u:%u) -> %s(%u:%u) [%u] %w:%x\n",
  430. current->process().name().characters(), current->process().pid(), current->tid(),
  431. thread.process().name().characters(), thread.process().pid(), thread.tid(),
  432. thread.priority(),
  433. thread.tss().cs, thread.tss().eip);
  434. #endif
  435. }
  436. current = &thread;
  437. thread.set_state(Thread::Running);
  438. asm volatile("fxrstor %0" ::"m"(current->fpu_state()));
  439. if (!thread.selector()) {
  440. thread.set_selector(gdt_alloc_entry());
  441. auto& descriptor = get_gdt_entry(thread.selector());
  442. descriptor.set_base(&thread.tss());
  443. descriptor.set_limit(sizeof(TSS32));
  444. descriptor.dpl = 0;
  445. descriptor.segment_present = 1;
  446. descriptor.granularity = 0;
  447. descriptor.zero = 0;
  448. descriptor.operation_size = 1;
  449. descriptor.descriptor_type = 0;
  450. }
  451. if (!thread.thread_specific_data().is_null()) {
  452. auto& descriptor = thread_specific_descriptor();
  453. descriptor.set_base(thread.thread_specific_data().as_ptr());
  454. descriptor.set_limit(sizeof(ThreadSpecificData*));
  455. }
  456. auto& descriptor = get_gdt_entry(thread.selector());
  457. descriptor.type = 11; // Busy TSS
  458. return true;
  459. }
  460. static void initialize_redirection()
  461. {
  462. auto& descriptor = get_gdt_entry(s_redirection.selector);
  463. descriptor.set_base(&s_redirection.tss);
  464. descriptor.set_limit(sizeof(TSS32));
  465. descriptor.dpl = 0;
  466. descriptor.segment_present = 1;
  467. descriptor.granularity = 0;
  468. descriptor.zero = 0;
  469. descriptor.operation_size = 1;
  470. descriptor.descriptor_type = 0;
  471. descriptor.type = 9;
  472. flush_gdt();
  473. }
  474. void Scheduler::prepare_for_iret_to_new_process()
  475. {
  476. auto& descriptor = get_gdt_entry(s_redirection.selector);
  477. descriptor.type = 9;
  478. s_redirection.tss.backlink = current->selector();
  479. load_task_register(s_redirection.selector);
  480. }
  481. void Scheduler::prepare_to_modify_tss(Thread& thread)
  482. {
  483. // This ensures that a currently running process modifying its own TSS
  484. // in order to yield() and end up somewhere else doesn't just end up
  485. // right after the yield().
  486. if (current == &thread)
  487. load_task_register(s_redirection.selector);
  488. }
  489. Process* Scheduler::colonel()
  490. {
  491. return s_colonel_process;
  492. }
  493. void Scheduler::initialize()
  494. {
  495. g_scheduler_data = new SchedulerData;
  496. g_finalizer_wait_queue = new WaitQueue;
  497. g_finalizer_has_work = false;
  498. s_redirection.selector = gdt_alloc_entry();
  499. initialize_redirection();
  500. s_colonel_process = Process::create_kernel_process(g_colonel, "colonel", nullptr);
  501. g_colonel->set_priority(THREAD_PRIORITY_MIN);
  502. load_task_register(s_redirection.selector);
  503. }
  504. void Scheduler::timer_tick(RegisterDump& regs)
  505. {
  506. if (!current)
  507. return;
  508. ++g_uptime;
  509. timeval tv;
  510. tv.tv_sec = RTC::boot_time() + PIT::seconds_since_boot();
  511. tv.tv_usec = PIT::ticks_this_second() * 1000;
  512. Process::update_info_page_timestamp(tv);
  513. if (current->process().is_profiling()) {
  514. SmapDisabler disabler;
  515. auto backtrace = current->raw_backtrace(regs.ebp);
  516. auto& sample = Profiling::next_sample_slot();
  517. sample.pid = current->pid();
  518. sample.tid = current->tid();
  519. sample.timestamp = g_uptime;
  520. for (size_t i = 0; i < min((size_t)backtrace.size(), Profiling::max_stack_frame_count); ++i) {
  521. sample.frames[i] = backtrace[i];
  522. }
  523. }
  524. TimerQueue::the().fire();
  525. if (current->tick())
  526. return;
  527. auto& outgoing_tss = current->tss();
  528. if (!pick_next())
  529. return;
  530. outgoing_tss.gs = regs.gs;
  531. outgoing_tss.fs = regs.fs;
  532. outgoing_tss.es = regs.es;
  533. outgoing_tss.ds = regs.ds;
  534. outgoing_tss.edi = regs.edi;
  535. outgoing_tss.esi = regs.esi;
  536. outgoing_tss.ebp = regs.ebp;
  537. outgoing_tss.ebx = regs.ebx;
  538. outgoing_tss.edx = regs.edx;
  539. outgoing_tss.ecx = regs.ecx;
  540. outgoing_tss.eax = regs.eax;
  541. outgoing_tss.eip = regs.eip;
  542. outgoing_tss.cs = regs.cs;
  543. outgoing_tss.eflags = regs.eflags;
  544. // Compute process stack pointer.
  545. // Add 16 for CS, EIP, EFLAGS, exception code (interrupt mechanic)
  546. outgoing_tss.esp = regs.esp + 16;
  547. outgoing_tss.ss = regs.ss;
  548. if ((outgoing_tss.cs & 3) != 0) {
  549. outgoing_tss.ss = regs.userspace_ss;
  550. outgoing_tss.esp = regs.userspace_esp;
  551. }
  552. prepare_for_iret_to_new_process();
  553. // Set the NT (nested task) flag.
  554. asm(
  555. "pushf\n"
  556. "orl $0x00004000, (%esp)\n"
  557. "popf\n");
  558. }
  559. static bool s_should_stop_idling = false;
  560. void Scheduler::stop_idling()
  561. {
  562. if (current != g_colonel)
  563. return;
  564. s_should_stop_idling = true;
  565. }
  566. void Scheduler::idle_loop()
  567. {
  568. for (;;) {
  569. asm("hlt");
  570. if (s_should_stop_idling) {
  571. s_should_stop_idling = false;
  572. yield();
  573. }
  574. }
  575. }