Scheduler.cpp 20 KB

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