Scheduler.cpp 18 KB

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