Scheduler.cpp 22 KB

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