Scheduler.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636
  1. /*
  2. * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/ScopeGuard.h>
  7. #include <AK/TemporaryChange.h>
  8. #include <AK/Time.h>
  9. #include <Kernel/Arch/x86/InterruptDisabler.h>
  10. #include <Kernel/Arch/x86/TrapFrame.h>
  11. #include <Kernel/Debug.h>
  12. #include <Kernel/Panic.h>
  13. #include <Kernel/PerformanceManager.h>
  14. #include <Kernel/Process.h>
  15. #include <Kernel/RTC.h>
  16. #include <Kernel/Scheduler.h>
  17. #include <Kernel/Sections.h>
  18. #include <Kernel/Time/TimeManagement.h>
  19. #include <Kernel/TimerQueue.h>
  20. // Remove this once SMP is stable and can be enabled by default
  21. #define SCHEDULE_ON_ALL_PROCESSORS 0
  22. namespace Kernel {
  23. class SchedulerPerProcessorData {
  24. AK_MAKE_NONCOPYABLE(SchedulerPerProcessorData);
  25. AK_MAKE_NONMOVABLE(SchedulerPerProcessorData);
  26. public:
  27. SchedulerPerProcessorData() = default;
  28. WeakPtr<Thread> m_pending_beneficiary;
  29. const char* m_pending_donate_reason { nullptr };
  30. bool m_in_scheduler { true };
  31. };
  32. RecursiveSpinLock g_scheduler_lock;
  33. static u32 time_slice_for(const Thread& thread)
  34. {
  35. // One time slice unit == 4ms (assuming 250 ticks/second)
  36. if (thread.is_idle_thread())
  37. return 1;
  38. return 2;
  39. }
  40. READONLY_AFTER_INIT Thread* g_finalizer;
  41. READONLY_AFTER_INIT WaitQueue* g_finalizer_wait_queue;
  42. Atomic<bool> g_finalizer_has_work { false };
  43. READONLY_AFTER_INIT static Process* s_colonel_process;
  44. struct ThreadReadyQueue {
  45. IntrusiveList<Thread, RawPtr<Thread>, &Thread::m_ready_queue_node> thread_list;
  46. };
  47. static SpinLock<u8> g_ready_queues_lock;
  48. static u32 g_ready_queues_mask;
  49. static constexpr u32 g_ready_queue_buckets = sizeof(g_ready_queues_mask) * 8;
  50. READONLY_AFTER_INIT static ThreadReadyQueue* g_ready_queues; // g_ready_queue_buckets entries
  51. static void dump_thread_list();
  52. static inline u32 thread_priority_to_priority_index(u32 thread_priority)
  53. {
  54. // Converts the priority in the range of THREAD_PRIORITY_MIN...THREAD_PRIORITY_MAX
  55. // to a index into g_ready_queues where 0 is the highest priority bucket
  56. VERIFY(thread_priority >= THREAD_PRIORITY_MIN && thread_priority <= THREAD_PRIORITY_MAX);
  57. constexpr u32 thread_priority_count = THREAD_PRIORITY_MAX - THREAD_PRIORITY_MIN + 1;
  58. static_assert(thread_priority_count > 0);
  59. auto priority_bucket = ((thread_priority_count - (thread_priority - THREAD_PRIORITY_MIN)) / thread_priority_count) * (g_ready_queue_buckets - 1);
  60. VERIFY(priority_bucket < g_ready_queue_buckets);
  61. return priority_bucket;
  62. }
  63. Thread& Scheduler::pull_next_runnable_thread()
  64. {
  65. auto affinity_mask = 1u << Processor::current().id();
  66. ScopedSpinLock lock(g_ready_queues_lock);
  67. auto priority_mask = g_ready_queues_mask;
  68. while (priority_mask != 0) {
  69. auto priority = __builtin_ffsl(priority_mask);
  70. VERIFY(priority > 0);
  71. auto& ready_queue = g_ready_queues[--priority];
  72. for (auto& thread : ready_queue.thread_list) {
  73. VERIFY(thread.m_runnable_priority == (int)priority);
  74. if (thread.is_active())
  75. continue;
  76. if (!(thread.affinity() & affinity_mask))
  77. continue;
  78. thread.m_runnable_priority = -1;
  79. ready_queue.thread_list.remove(thread);
  80. if (ready_queue.thread_list.is_empty())
  81. g_ready_queues_mask &= ~(1u << priority);
  82. // Mark it as active because we are using this thread. This is similar
  83. // to comparing it with Processor::current_thread, but when there are
  84. // multiple processors there's no easy way to check whether the thread
  85. // is actually still needed. This prevents accidental finalization when
  86. // a thread is no longer in Running state, but running on another core.
  87. // We need to mark it active here so that this thread won't be
  88. // scheduled on another core if it were to be queued before actually
  89. // switching to it.
  90. // FIXME: Figure out a better way maybe?
  91. thread.set_active(true);
  92. return thread;
  93. }
  94. priority_mask &= ~(1u << priority);
  95. }
  96. return *Processor::idle_thread();
  97. }
  98. bool Scheduler::dequeue_runnable_thread(Thread& thread, bool check_affinity)
  99. {
  100. if (thread.is_idle_thread())
  101. return true;
  102. ScopedSpinLock lock(g_ready_queues_lock);
  103. auto priority = thread.m_runnable_priority;
  104. if (priority < 0) {
  105. VERIFY(!thread.m_ready_queue_node.is_in_list());
  106. return false;
  107. }
  108. if (check_affinity && !(thread.affinity() & (1 << Processor::current().id())))
  109. return false;
  110. VERIFY(g_ready_queues_mask & (1u << priority));
  111. auto& ready_queue = g_ready_queues[priority];
  112. thread.m_runnable_priority = -1;
  113. ready_queue.thread_list.remove(thread);
  114. if (ready_queue.thread_list.is_empty())
  115. g_ready_queues_mask &= ~(1u << priority);
  116. return true;
  117. }
  118. void Scheduler::queue_runnable_thread(Thread& thread)
  119. {
  120. VERIFY(g_scheduler_lock.own_lock());
  121. if (thread.is_idle_thread())
  122. return;
  123. auto priority = thread_priority_to_priority_index(thread.priority());
  124. ScopedSpinLock lock(g_ready_queues_lock);
  125. VERIFY(thread.m_runnable_priority < 0);
  126. thread.m_runnable_priority = (int)priority;
  127. VERIFY(!thread.m_ready_queue_node.is_in_list());
  128. auto& ready_queue = g_ready_queues[priority];
  129. bool was_empty = ready_queue.thread_list.is_empty();
  130. ready_queue.thread_list.append(thread);
  131. if (was_empty)
  132. g_ready_queues_mask |= (1u << priority);
  133. }
  134. UNMAP_AFTER_INIT void Scheduler::start()
  135. {
  136. VERIFY_INTERRUPTS_DISABLED();
  137. // We need to acquire our scheduler lock, which will be released
  138. // by the idle thread once control transferred there
  139. g_scheduler_lock.lock();
  140. auto& processor = Processor::current();
  141. processor.set_scheduler_data(*new SchedulerPerProcessorData());
  142. VERIFY(processor.is_initialized());
  143. auto& idle_thread = *Processor::idle_thread();
  144. VERIFY(processor.current_thread() == &idle_thread);
  145. idle_thread.set_ticks_left(time_slice_for(idle_thread));
  146. idle_thread.did_schedule();
  147. idle_thread.set_initialized(true);
  148. processor.init_context(idle_thread, false);
  149. idle_thread.set_state(Thread::Running);
  150. VERIFY(idle_thread.affinity() == (1u << processor.get_id()));
  151. processor.initialize_context_switching(idle_thread);
  152. VERIFY_NOT_REACHED();
  153. }
  154. bool Scheduler::pick_next()
  155. {
  156. VERIFY_INTERRUPTS_DISABLED();
  157. // Set the m_in_scheduler flag before acquiring the spinlock. This
  158. // prevents a recursive call into Scheduler::invoke_async upon
  159. // leaving the scheduler lock.
  160. ScopedCritical critical;
  161. auto& scheduler_data = Processor::current().get_scheduler_data();
  162. scheduler_data.m_in_scheduler = true;
  163. ScopeGuard guard(
  164. []() {
  165. // We may be on a different processor after we got switched
  166. // back to this thread!
  167. auto& scheduler_data = Processor::current().get_scheduler_data();
  168. VERIFY(scheduler_data.m_in_scheduler);
  169. scheduler_data.m_in_scheduler = false;
  170. });
  171. ScopedSpinLock lock(g_scheduler_lock);
  172. auto current_thread = Thread::current();
  173. if (current_thread->should_die() && current_thread->may_die_immediately()) {
  174. // Ordinarily the thread would die on syscall exit, however if the thread
  175. // doesn't perform any syscalls we still need to mark it for termination here.
  176. current_thread->set_state(Thread::Dying);
  177. }
  178. if constexpr (SCHEDULER_RUNNABLE_DEBUG) {
  179. dump_thread_list();
  180. }
  181. auto pending_beneficiary = scheduler_data.m_pending_beneficiary.strong_ref();
  182. if (pending_beneficiary && dequeue_runnable_thread(*pending_beneficiary, true)) {
  183. // The thread we're supposed to donate to still exists and we can
  184. const char* reason = scheduler_data.m_pending_donate_reason;
  185. scheduler_data.m_pending_beneficiary = nullptr;
  186. scheduler_data.m_pending_donate_reason = nullptr;
  187. // We need to leave our first critical section before switching context,
  188. // but since we're still holding the scheduler lock we're still in a critical section
  189. critical.leave();
  190. dbgln_if(SCHEDULER_DEBUG, "Processing pending donate to {} reason={}", *pending_beneficiary, reason);
  191. return donate_to_and_switch(pending_beneficiary.ptr(), reason);
  192. }
  193. // Either we're not donating or the beneficiary disappeared.
  194. // Either way clear any pending information
  195. scheduler_data.m_pending_beneficiary = nullptr;
  196. scheduler_data.m_pending_donate_reason = nullptr;
  197. auto& thread_to_schedule = pull_next_runnable_thread();
  198. if constexpr (SCHEDULER_DEBUG) {
  199. #if ARCH(I386)
  200. dbgln("Scheduler[{}]: Switch to {} @ {:04x}:{:08x}",
  201. Processor::id(),
  202. thread_to_schedule,
  203. thread_to_schedule.regs().cs, thread_to_schedule.regs().eip);
  204. #else
  205. PANIC("Scheduler::pick_next() not implemented");
  206. #endif
  207. }
  208. // We need to leave our first critical section before switching context,
  209. // but since we're still holding the scheduler lock we're still in a critical section
  210. critical.leave();
  211. thread_to_schedule.set_ticks_left(time_slice_for(thread_to_schedule));
  212. return context_switch(&thread_to_schedule);
  213. }
  214. bool Scheduler::yield()
  215. {
  216. InterruptDisabler disabler;
  217. auto& proc = Processor::current();
  218. auto& scheduler_data = proc.get_scheduler_data();
  219. // Clear any pending beneficiary
  220. scheduler_data.m_pending_beneficiary = nullptr;
  221. scheduler_data.m_pending_donate_reason = nullptr;
  222. auto current_thread = Thread::current();
  223. dbgln_if(SCHEDULER_DEBUG, "Scheduler[{}]: yielding thread {} in_irq={}", proc.get_id(), *current_thread, proc.in_irq());
  224. VERIFY(current_thread != nullptr);
  225. if (proc.in_irq() || proc.in_critical()) {
  226. // If we're handling an IRQ we can't switch context, or we're in
  227. // a critical section where we don't want to switch contexts, then
  228. // delay until exiting the trap or critical section
  229. proc.invoke_scheduler_async();
  230. return false;
  231. }
  232. if (!Scheduler::pick_next())
  233. return false;
  234. if constexpr (SCHEDULER_DEBUG)
  235. dbgln("Scheduler[{}]: yield returns to thread {} in_irq={}", Processor::id(), *current_thread, Processor::current().in_irq());
  236. return true;
  237. }
  238. bool Scheduler::donate_to_and_switch(Thread* beneficiary, [[maybe_unused]] const char* reason)
  239. {
  240. VERIFY(g_scheduler_lock.own_lock());
  241. auto& proc = Processor::current();
  242. VERIFY(proc.in_critical() == 1);
  243. unsigned ticks_left = Thread::current()->ticks_left();
  244. if (!beneficiary || beneficiary->state() != Thread::Runnable || ticks_left <= 1)
  245. return Scheduler::yield();
  246. unsigned ticks_to_donate = min(ticks_left - 1, time_slice_for(*beneficiary));
  247. dbgln_if(SCHEDULER_DEBUG, "Scheduler[{}]: Donating {} ticks to {}, reason={}", proc.get_id(), ticks_to_donate, *beneficiary, reason);
  248. beneficiary->set_ticks_left(ticks_to_donate);
  249. return Scheduler::context_switch(beneficiary);
  250. }
  251. bool Scheduler::donate_to(RefPtr<Thread>& beneficiary, const char* reason)
  252. {
  253. VERIFY(beneficiary);
  254. if (beneficiary == Thread::current())
  255. return Scheduler::yield();
  256. // Set the m_in_scheduler flag before acquiring the spinlock. This
  257. // prevents a recursive call into Scheduler::invoke_async upon
  258. // leaving the scheduler lock.
  259. ScopedCritical critical;
  260. auto& proc = Processor::current();
  261. auto& scheduler_data = proc.get_scheduler_data();
  262. scheduler_data.m_in_scheduler = true;
  263. ScopeGuard guard(
  264. []() {
  265. // We may be on a different processor after we got switched
  266. // back to this thread!
  267. auto& scheduler_data = Processor::current().get_scheduler_data();
  268. VERIFY(scheduler_data.m_in_scheduler);
  269. scheduler_data.m_in_scheduler = false;
  270. });
  271. VERIFY(!proc.in_irq());
  272. if (proc.in_critical() > 1) {
  273. scheduler_data.m_pending_beneficiary = beneficiary; // Save the beneficiary
  274. scheduler_data.m_pending_donate_reason = reason;
  275. proc.invoke_scheduler_async();
  276. return false;
  277. }
  278. ScopedSpinLock lock(g_scheduler_lock);
  279. // "Leave" the critical section before switching context. Since we
  280. // still hold the scheduler lock, we're not actually leaving it.
  281. // Processor::switch_context expects Processor::in_critical() to be 1
  282. critical.leave();
  283. donate_to_and_switch(beneficiary, reason);
  284. return false;
  285. }
  286. bool Scheduler::context_switch(Thread* thread)
  287. {
  288. if (s_mm_lock.own_lock()) {
  289. PANIC("In context switch while holding s_mm_lock");
  290. }
  291. thread->did_schedule();
  292. auto from_thread = Thread::current();
  293. if (from_thread == thread)
  294. return false;
  295. if (from_thread) {
  296. // If the last process hasn't blocked (still marked as running),
  297. // mark it as runnable for the next round.
  298. if (from_thread->state() == Thread::Running)
  299. from_thread->set_state(Thread::Runnable);
  300. #ifdef LOG_EVERY_CONTEXT_SWITCH
  301. # if ARCH(I386)
  302. dbgln("Scheduler[{}]: {} -> {} [prio={}] {:04x}:{:08x}", Processor::id(), from_thread->tid().value(),
  303. thread->tid().value(), thread->priority(), thread->regs().cs, thread->regs().eip);
  304. # else
  305. dbgln("Scheduler[{}]: {} -> {} [prio={}] {:04x}:{:16x}", Processor::id(), from_thread->tid().value(),
  306. thread->tid().value(), thread->priority(), thread->regs().cs, thread->regs().rip);
  307. # endif
  308. #endif
  309. }
  310. auto& proc = Processor::current();
  311. if (!thread->is_initialized()) {
  312. proc.init_context(*thread, false);
  313. thread->set_initialized(true);
  314. }
  315. thread->set_state(Thread::Running);
  316. PerformanceManager::add_context_switch_perf_event(*from_thread, *thread);
  317. proc.switch_context(from_thread, thread);
  318. // NOTE: from_thread at this point reflects the thread we were
  319. // switched from, and thread reflects Thread::current()
  320. enter_current(*from_thread, false);
  321. VERIFY(thread == Thread::current());
  322. if (thread->process().is_user_process()) {
  323. FlatPtr flags;
  324. auto& regs = Thread::current()->get_register_dump_from_stack();
  325. #if ARCH(I386)
  326. flags = regs.eflags;
  327. #else
  328. flags = regs.rflags;
  329. #endif
  330. auto iopl = get_iopl_from_eflags(flags);
  331. if (iopl != 0) {
  332. PANIC("Switched to thread {} with non-zero IOPL={}", Thread::current()->tid().value(), iopl);
  333. }
  334. }
  335. return true;
  336. }
  337. void Scheduler::enter_current(Thread& prev_thread, bool is_first)
  338. {
  339. VERIFY(g_scheduler_lock.own_lock());
  340. prev_thread.set_active(false);
  341. if (prev_thread.state() == Thread::Dying) {
  342. // If the thread we switched from is marked as dying, then notify
  343. // the finalizer. Note that as soon as we leave the scheduler lock
  344. // the finalizer may free from_thread!
  345. notify_finalizer();
  346. } else if (!is_first) {
  347. // Check if we have any signals we should deliver (even if we don't
  348. // end up switching to another thread).
  349. auto current_thread = Thread::current();
  350. if (!current_thread->is_in_block() && current_thread->previous_mode() != Thread::PreviousMode::KernelMode) {
  351. ScopedSpinLock lock(current_thread->get_lock());
  352. if (current_thread->state() == Thread::Running && current_thread->pending_signals_for_state()) {
  353. current_thread->dispatch_one_pending_signal();
  354. }
  355. }
  356. }
  357. }
  358. void Scheduler::leave_on_first_switch(u32 flags)
  359. {
  360. // This is called when a thread is switched into for the first time.
  361. // At this point, enter_current has already be called, but because
  362. // Scheduler::context_switch is not in the call stack we need to
  363. // clean up and release locks manually here
  364. g_scheduler_lock.unlock(flags);
  365. auto& scheduler_data = Processor::current().get_scheduler_data();
  366. VERIFY(scheduler_data.m_in_scheduler);
  367. scheduler_data.m_in_scheduler = false;
  368. }
  369. void Scheduler::prepare_after_exec()
  370. {
  371. // This is called after exec() when doing a context "switch" into
  372. // the new process. This is called from Processor::assume_context
  373. VERIFY(g_scheduler_lock.own_lock());
  374. auto& scheduler_data = Processor::current().get_scheduler_data();
  375. VERIFY(!scheduler_data.m_in_scheduler);
  376. scheduler_data.m_in_scheduler = true;
  377. }
  378. void Scheduler::prepare_for_idle_loop()
  379. {
  380. // This is called when the CPU finished setting up the idle loop
  381. // and is about to run it. We need to acquire he scheduler lock
  382. VERIFY(!g_scheduler_lock.own_lock());
  383. g_scheduler_lock.lock();
  384. auto& scheduler_data = Processor::current().get_scheduler_data();
  385. VERIFY(!scheduler_data.m_in_scheduler);
  386. scheduler_data.m_in_scheduler = true;
  387. }
  388. Process* Scheduler::colonel()
  389. {
  390. VERIFY(s_colonel_process);
  391. return s_colonel_process;
  392. }
  393. UNMAP_AFTER_INIT void Scheduler::initialize()
  394. {
  395. VERIFY(Processor::is_initialized()); // sanity check
  396. RefPtr<Thread> idle_thread;
  397. g_finalizer_wait_queue = new WaitQueue;
  398. g_ready_queues = new ThreadReadyQueue[g_ready_queue_buckets];
  399. g_finalizer_has_work.store(false, AK::MemoryOrder::memory_order_release);
  400. s_colonel_process = Process::create_kernel_process(idle_thread, "colonel", idle_loop, nullptr, 1).leak_ref();
  401. VERIFY(s_colonel_process);
  402. VERIFY(idle_thread);
  403. idle_thread->set_priority(THREAD_PRIORITY_MIN);
  404. idle_thread->set_name(StringView("idle thread #0"));
  405. set_idle_thread(idle_thread);
  406. }
  407. UNMAP_AFTER_INIT void Scheduler::set_idle_thread(Thread* idle_thread)
  408. {
  409. idle_thread->set_idle_thread();
  410. Processor::current().set_idle_thread(*idle_thread);
  411. Processor::current().set_current_thread(*idle_thread);
  412. }
  413. UNMAP_AFTER_INIT Thread* Scheduler::create_ap_idle_thread(u32 cpu)
  414. {
  415. VERIFY(cpu != 0);
  416. // This function is called on the bsp, but creates an idle thread for another AP
  417. VERIFY(Processor::is_bootstrap_processor());
  418. VERIFY(s_colonel_process);
  419. Thread* idle_thread = s_colonel_process->create_kernel_thread(idle_loop, nullptr, THREAD_PRIORITY_MIN, String::formatted("idle thread #{}", cpu), 1 << cpu, false);
  420. VERIFY(idle_thread);
  421. return idle_thread;
  422. }
  423. void Scheduler::timer_tick(const RegisterState& regs)
  424. {
  425. VERIFY_INTERRUPTS_DISABLED();
  426. VERIFY(Processor::current().in_irq());
  427. auto current_thread = Processor::current_thread();
  428. if (!current_thread)
  429. return;
  430. // Sanity checks
  431. VERIFY(current_thread->current_trap());
  432. VERIFY(current_thread->current_trap()->regs == &regs);
  433. #if !SCHEDULE_ON_ALL_PROCESSORS
  434. if (!Processor::is_bootstrap_processor())
  435. return; // TODO: This prevents scheduling on other CPUs!
  436. #endif
  437. if (current_thread->tick())
  438. return;
  439. VERIFY_INTERRUPTS_DISABLED();
  440. VERIFY(Processor::current().in_irq());
  441. Processor::current().invoke_scheduler_async();
  442. }
  443. void Scheduler::invoke_async()
  444. {
  445. VERIFY_INTERRUPTS_DISABLED();
  446. auto& proc = Processor::current();
  447. VERIFY(!proc.in_irq());
  448. // Since this function is called when leaving critical sections (such
  449. // as a SpinLock), we need to check if we're not already doing this
  450. // to prevent recursion
  451. if (!proc.get_scheduler_data().m_in_scheduler)
  452. pick_next();
  453. }
  454. void Scheduler::yield_from_critical()
  455. {
  456. auto& proc = Processor::current();
  457. VERIFY(proc.in_critical());
  458. VERIFY(!proc.in_irq());
  459. yield(); // Flag a context switch
  460. u32 prev_flags;
  461. u32 prev_crit = Processor::current().clear_critical(prev_flags, false);
  462. // Note, we may now be on a different CPU!
  463. Processor::current().restore_critical(prev_crit, prev_flags);
  464. }
  465. void Scheduler::notify_finalizer()
  466. {
  467. if (g_finalizer_has_work.exchange(true, AK::MemoryOrder::memory_order_acq_rel) == false)
  468. g_finalizer_wait_queue->wake_all();
  469. }
  470. void Scheduler::idle_loop(void*)
  471. {
  472. auto& proc = Processor::current();
  473. dbgln("Scheduler[{}]: idle loop running", proc.get_id());
  474. VERIFY(are_interrupts_enabled());
  475. for (;;) {
  476. proc.idle_begin();
  477. asm("hlt");
  478. proc.idle_end();
  479. VERIFY_INTERRUPTS_ENABLED();
  480. #if SCHEDULE_ON_ALL_PROCESSORS
  481. yield();
  482. #else
  483. if (Processor::current().id() == 0)
  484. yield();
  485. #endif
  486. }
  487. }
  488. void Scheduler::dump_scheduler_state()
  489. {
  490. dump_thread_list();
  491. }
  492. bool Scheduler::is_initialized()
  493. {
  494. // The scheduler is initialized iff the idle thread exists
  495. return Processor::idle_thread() != nullptr;
  496. }
  497. void dump_thread_list()
  498. {
  499. dbgln("Scheduler thread list for processor {}:", Processor::id());
  500. auto get_cs = [](Thread& thread) -> u16 {
  501. if (!thread.current_trap())
  502. return thread.regs().cs;
  503. return thread.get_register_dump_from_stack().cs;
  504. };
  505. auto get_eip = [](Thread& thread) -> u32 {
  506. #if ARCH(I386)
  507. if (!thread.current_trap())
  508. return thread.regs().eip;
  509. return thread.get_register_dump_from_stack().eip;
  510. #else
  511. if (!thread.current_trap())
  512. return thread.regs().rip;
  513. return thread.get_register_dump_from_stack().rip;
  514. #endif
  515. };
  516. Thread::for_each([&](Thread& thread) {
  517. switch (thread.state()) {
  518. case Thread::Dying:
  519. dmesgln(" {:14} {:30} @ {:04x}:{:08x} Finalizable: {}, (nsched: {})",
  520. thread.state_string(),
  521. thread,
  522. get_cs(thread),
  523. get_eip(thread),
  524. thread.is_finalizable(),
  525. thread.times_scheduled());
  526. break;
  527. default:
  528. dmesgln(" {:14} Pr:{:2} {:30} @ {:04x}:{:08x} (nsched: {})",
  529. thread.state_string(),
  530. thread.priority(),
  531. thread,
  532. get_cs(thread),
  533. get_eip(thread),
  534. thread.times_scheduled());
  535. break;
  536. }
  537. });
  538. }
  539. }