Scheduler.cpp 22 KB

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