Scheduler.cpp 20 KB

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