Scheduler.cpp 20 KB

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