Scheduler.cpp 24 KB

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