Scheduler.cpp 18 KB

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