Scheduler.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  1. /*
  2. * Copyright (c) 2018-2022, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/BuiltinWrappers.h>
  7. #include <AK/ScopeGuard.h>
  8. #include <AK/Singleton.h>
  9. #include <AK/Time.h>
  10. #include <Kernel/Arch/InterruptDisabler.h>
  11. #include <Kernel/Arch/x86/TrapFrame.h>
  12. #include <Kernel/Debug.h>
  13. #include <Kernel/Panic.h>
  14. #include <Kernel/PerformanceManager.h>
  15. #include <Kernel/Process.h>
  16. #include <Kernel/Scheduler.h>
  17. #include <Kernel/Sections.h>
  18. #include <Kernel/Time/TimeManagement.h>
  19. #include <Kernel/kstdio.h>
  20. namespace Kernel {
  21. RecursiveSpinlock g_scheduler_lock { LockRank::None };
  22. static u32 time_slice_for(Thread const& thread)
  23. {
  24. // One time slice unit == 4ms (assuming 250 ticks/second)
  25. if (thread.is_idle_thread())
  26. return 1;
  27. return 2;
  28. }
  29. READONLY_AFTER_INIT Thread* g_finalizer;
  30. READONLY_AFTER_INIT WaitQueue* g_finalizer_wait_queue;
  31. Atomic<bool> g_finalizer_has_work { false };
  32. READONLY_AFTER_INIT static Process* s_colonel_process;
  33. struct ThreadReadyQueue {
  34. IntrusiveList<&Thread::m_ready_queue_node> thread_list;
  35. };
  36. struct ThreadReadyQueues {
  37. u32 mask {};
  38. static constexpr size_t count = sizeof(mask) * 8;
  39. Array<ThreadReadyQueue, count> queues;
  40. };
  41. static Singleton<SpinlockProtected<ThreadReadyQueues>> g_ready_queues;
  42. static SpinlockProtected<TotalTimeScheduled> g_total_time_scheduled { LockRank::None };
  43. // The Scheduler::current_time function provides a current time for scheduling purposes,
  44. // which may not necessarily relate to wall time
  45. u64 (*Scheduler::current_time)();
  46. static void dump_thread_list(bool = false);
  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) * (ThreadReadyQueues::count - 1);
  55. VERIFY(priority_bucket < ThreadReadyQueues::count);
  56. return priority_bucket;
  57. }
  58. Thread& Scheduler::pull_next_runnable_thread()
  59. {
  60. auto affinity_mask = 1u << Processor::current_id();
  61. return g_ready_queues->with([&](auto& ready_queues) -> Thread& {
  62. auto priority_mask = ready_queues.mask;
  63. while (priority_mask != 0) {
  64. auto priority = bit_scan_forward(priority_mask);
  65. VERIFY(priority > 0);
  66. auto& ready_queue = ready_queues.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. 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. }
  94. Thread* Scheduler::peek_next_runnable_thread()
  95. {
  96. auto affinity_mask = 1u << Processor::current_id();
  97. return g_ready_queues->with([&](auto& ready_queues) -> Thread* {
  98. auto priority_mask = ready_queues.mask;
  99. while (priority_mask != 0) {
  100. auto priority = bit_scan_forward(priority_mask);
  101. VERIFY(priority > 0);
  102. auto& ready_queue = ready_queues.queues[--priority];
  103. for (auto& thread : ready_queue.thread_list) {
  104. VERIFY(thread.m_runnable_priority == (int)priority);
  105. if (thread.is_active())
  106. continue;
  107. if (!(thread.affinity() & affinity_mask))
  108. continue;
  109. return &thread;
  110. }
  111. priority_mask &= ~(1u << priority);
  112. }
  113. // Unlike in pull_next_runnable_thread() we don't want to fall back to
  114. // the idle thread. We just want to see if we have any other thread ready
  115. // to be scheduled.
  116. return nullptr;
  117. });
  118. }
  119. bool Scheduler::dequeue_runnable_thread(Thread& thread, bool check_affinity)
  120. {
  121. if (thread.is_idle_thread())
  122. return true;
  123. return g_ready_queues->with([&](auto& ready_queues) {
  124. auto priority = thread.m_runnable_priority;
  125. if (priority < 0) {
  126. VERIFY(!thread.m_ready_queue_node.is_in_list());
  127. return false;
  128. }
  129. if (check_affinity && !(thread.affinity() & (1 << Processor::current_id())))
  130. return false;
  131. VERIFY(ready_queues.mask & (1u << priority));
  132. auto& ready_queue = ready_queues.queues[priority];
  133. thread.m_runnable_priority = -1;
  134. ready_queue.thread_list.remove(thread);
  135. if (ready_queue.thread_list.is_empty())
  136. ready_queues.mask &= ~(1u << priority);
  137. return true;
  138. });
  139. }
  140. void Scheduler::enqueue_runnable_thread(Thread& thread)
  141. {
  142. VERIFY(g_scheduler_lock.is_locked_by_current_processor());
  143. if (thread.is_idle_thread())
  144. return;
  145. auto priority = thread_priority_to_priority_index(thread.priority());
  146. g_ready_queues->with([&](auto& ready_queues) {
  147. VERIFY(thread.m_runnable_priority < 0);
  148. thread.m_runnable_priority = (int)priority;
  149. VERIFY(!thread.m_ready_queue_node.is_in_list());
  150. auto& ready_queue = ready_queues.queues[priority];
  151. bool was_empty = ready_queue.thread_list.is_empty();
  152. ready_queue.thread_list.append(thread);
  153. if (was_empty)
  154. ready_queues.mask |= (1u << priority);
  155. });
  156. }
  157. UNMAP_AFTER_INIT void Scheduler::start()
  158. {
  159. VERIFY_INTERRUPTS_DISABLED();
  160. // We need to acquire our scheduler lock, which will be released
  161. // by the idle thread once control transferred there
  162. g_scheduler_lock.lock();
  163. auto& processor = Processor::current();
  164. VERIFY(processor.is_initialized());
  165. auto& idle_thread = *Processor::idle_thread();
  166. VERIFY(processor.current_thread() == &idle_thread);
  167. idle_thread.set_ticks_left(time_slice_for(idle_thread));
  168. idle_thread.did_schedule();
  169. idle_thread.set_initialized(true);
  170. processor.init_context(idle_thread, false);
  171. idle_thread.set_state(Thread::State::Running);
  172. VERIFY(idle_thread.affinity() == (1u << processor.id()));
  173. processor.initialize_context_switching(idle_thread);
  174. VERIFY_NOT_REACHED();
  175. }
  176. void Scheduler::pick_next()
  177. {
  178. VERIFY_INTERRUPTS_DISABLED();
  179. // Set the in_scheduler flag before acquiring the spinlock. This
  180. // prevents a recursive call into Scheduler::invoke_async upon
  181. // leaving the scheduler lock.
  182. ScopedCritical critical;
  183. Processor::set_current_in_scheduler(true);
  184. ScopeGuard guard(
  185. []() {
  186. // We may be on a different processor after we got switched
  187. // back to this thread!
  188. VERIFY(Processor::current_in_scheduler());
  189. Processor::set_current_in_scheduler(false);
  190. });
  191. SpinlockLocker lock(g_scheduler_lock);
  192. if constexpr (SCHEDULER_RUNNABLE_DEBUG) {
  193. dump_thread_list();
  194. }
  195. auto& thread_to_schedule = pull_next_runnable_thread();
  196. if constexpr (SCHEDULER_DEBUG) {
  197. dbgln("Scheduler[{}]: Switch to {} @ {:#04x}:{:p}",
  198. Processor::current_id(),
  199. thread_to_schedule,
  200. thread_to_schedule.regs().cs, thread_to_schedule.regs().ip());
  201. }
  202. // We need to leave our first critical section before switching context,
  203. // but since we're still holding the scheduler lock we're still in a critical section
  204. critical.leave();
  205. thread_to_schedule.set_ticks_left(time_slice_for(thread_to_schedule));
  206. context_switch(&thread_to_schedule);
  207. }
  208. void Scheduler::yield()
  209. {
  210. InterruptDisabler disabler;
  211. auto const* current_thread = Thread::current();
  212. dbgln_if(SCHEDULER_DEBUG, "Scheduler[{}]: yielding thread {} in_irq={}", Processor::current_id(), *current_thread, Processor::current_in_irq());
  213. VERIFY(current_thread != nullptr);
  214. if (Processor::current_in_irq() || Processor::in_critical()) {
  215. // If we're handling an IRQ we can't switch context, or we're in
  216. // a critical section where we don't want to switch contexts, then
  217. // delay until exiting the trap or critical section
  218. Processor::current().invoke_scheduler_async();
  219. return;
  220. }
  221. Scheduler::pick_next();
  222. }
  223. void Scheduler::context_switch(Thread* thread)
  224. {
  225. thread->did_schedule();
  226. auto* from_thread = Thread::current();
  227. VERIFY(from_thread);
  228. if (from_thread == thread)
  229. return;
  230. // If the last process hasn't blocked (still marked as running),
  231. // mark it as runnable for the next round.
  232. if (from_thread->state() == Thread::State::Running)
  233. from_thread->set_state(Thread::State::Runnable);
  234. #ifdef LOG_EVERY_CONTEXT_SWITCH
  235. auto const msg = "Scheduler[{}]: {} -> {} [prio={}] {:#04x}:{:p}";
  236. dbgln(msg,
  237. Processor::current_id(), from_thread->tid().value(),
  238. thread->tid().value(), thread->priority(), thread->regs().cs, thread->regs().ip());
  239. #endif
  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::State::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);
  251. VERIFY(thread == Thread::current());
  252. {
  253. SpinlockLocker lock(thread->get_lock());
  254. thread->dispatch_one_pending_signal();
  255. }
  256. }
  257. void Scheduler::enter_current(Thread& prev_thread)
  258. {
  259. VERIFY(g_scheduler_lock.is_locked_by_current_processor());
  260. // We already recorded the scheduled time when entering the trap, so this merely accounts for the kernel time since then
  261. auto scheduler_time = Scheduler::current_time();
  262. prev_thread.update_time_scheduled(scheduler_time, true, true);
  263. auto* current_thread = Thread::current();
  264. current_thread->update_time_scheduled(scheduler_time, true, false);
  265. // NOTE: When doing an exec(), we will context switch from and to the same thread!
  266. // In that case, we must not mark the previous thread as inactive.
  267. if (&prev_thread != current_thread)
  268. prev_thread.set_active(false);
  269. if (prev_thread.state() == Thread::State::Dying) {
  270. // If the thread we switched from is marked as dying, then notify
  271. // the finalizer. Note that as soon as we leave the scheduler lock
  272. // the finalizer may free from_thread!
  273. notify_finalizer();
  274. }
  275. }
  276. void Scheduler::leave_on_first_switch(InterruptsState previous_interrupts_state)
  277. {
  278. // This is called when a thread is switched into for the first time.
  279. // At this point, enter_current has already be called, but because
  280. // Scheduler::context_switch is not in the call stack we need to
  281. // clean up and release locks manually here
  282. g_scheduler_lock.unlock(previous_interrupts_state);
  283. VERIFY(Processor::current_in_scheduler());
  284. Processor::set_current_in_scheduler(false);
  285. }
  286. void Scheduler::prepare_after_exec()
  287. {
  288. // This is called after exec() when doing a context "switch" into
  289. // the new process. This is called from Processor::assume_context
  290. VERIFY(g_scheduler_lock.is_locked_by_current_processor());
  291. VERIFY(!Processor::current_in_scheduler());
  292. Processor::set_current_in_scheduler(true);
  293. }
  294. void Scheduler::prepare_for_idle_loop()
  295. {
  296. // This is called when the CPU finished setting up the idle loop
  297. // and is about to run it. We need to acquire the scheduler lock
  298. VERIFY(!g_scheduler_lock.is_locked_by_current_processor());
  299. g_scheduler_lock.lock();
  300. VERIFY(!Processor::current_in_scheduler());
  301. Processor::set_current_in_scheduler(true);
  302. }
  303. Process* Scheduler::colonel()
  304. {
  305. VERIFY(s_colonel_process);
  306. return s_colonel_process;
  307. }
  308. static u64 current_time_tsc()
  309. {
  310. return read_tsc();
  311. }
  312. static u64 current_time_monotonic()
  313. {
  314. // We always need a precise timestamp here, we cannot rely on a coarse timestamp
  315. return (u64)TimeManagement::the().monotonic_time(TimePrecision::Precise).to_nanoseconds();
  316. }
  317. UNMAP_AFTER_INIT void Scheduler::initialize()
  318. {
  319. VERIFY(Processor::is_initialized()); // sanity check
  320. // Figure out a good scheduling time source
  321. if (Processor::current().has_feature(CPUFeature::TSC) && Processor::current().has_feature(CPUFeature::CONSTANT_TSC)) {
  322. current_time = current_time_tsc;
  323. } else {
  324. // TODO: Using HPET is rather slow, can we use any other time source that may be faster?
  325. current_time = current_time_monotonic;
  326. }
  327. LockRefPtr<Thread> idle_thread;
  328. g_finalizer_wait_queue = new WaitQueue;
  329. g_finalizer_has_work.store(false, AK::MemoryOrder::memory_order_release);
  330. s_colonel_process = Process::create_kernel_process(idle_thread, KString::must_create("colonel"sv), idle_loop, nullptr, 1, Process::RegisterProcess::No).leak_ref();
  331. VERIFY(s_colonel_process);
  332. VERIFY(idle_thread);
  333. idle_thread->set_priority(THREAD_PRIORITY_MIN);
  334. idle_thread->set_name(KString::must_create("Idle Task #0"sv));
  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::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, MUST(KString::formatted("idle thread #{}", cpu)), 1 << cpu, false);
  350. VERIFY(idle_thread);
  351. return idle_thread;
  352. }
  353. void Scheduler::add_time_scheduled(u64 time_to_add, bool is_kernel)
  354. {
  355. g_total_time_scheduled.with([&](auto& total_time_scheduled) {
  356. total_time_scheduled.total += time_to_add;
  357. if (is_kernel)
  358. total_time_scheduled.total_kernel += time_to_add;
  359. });
  360. }
  361. void Scheduler::timer_tick(RegisterState const& regs)
  362. {
  363. VERIFY_INTERRUPTS_DISABLED();
  364. VERIFY(Processor::current_in_irq());
  365. auto* current_thread = Processor::current_thread();
  366. if (!current_thread)
  367. return;
  368. // Sanity checks
  369. VERIFY(current_thread->current_trap());
  370. VERIFY(current_thread->current_trap()->regs == &regs);
  371. if (current_thread->process().is_kernel_process()) {
  372. // Because the previous mode when entering/exiting kernel threads never changes
  373. // we never update the time scheduled. So we need to update it manually on the
  374. // timer interrupt
  375. current_thread->update_time_scheduled(current_time(), true, false);
  376. }
  377. if (current_thread->previous_mode() == Thread::PreviousMode::UserMode && current_thread->should_die() && !current_thread->is_blocked()) {
  378. SpinlockLocker scheduler_lock(g_scheduler_lock);
  379. dbgln_if(SCHEDULER_DEBUG, "Scheduler[{}]: Terminating user mode thread {}", Processor::current_id(), *current_thread);
  380. current_thread->set_state(Thread::State::Dying);
  381. Processor::current().invoke_scheduler_async();
  382. return;
  383. }
  384. if (current_thread->tick())
  385. return;
  386. if (!current_thread->is_idle_thread() && !peek_next_runnable_thread()) {
  387. // If no other thread is ready to be scheduled we don't need to
  388. // switch to the idle thread. Just give the current thread another
  389. // time slice and let it run!
  390. current_thread->set_ticks_left(time_slice_for(*current_thread));
  391. current_thread->did_schedule();
  392. dbgln_if(SCHEDULER_DEBUG, "Scheduler[{}]: No other threads ready, give {} another timeslice", Processor::current_id(), *current_thread);
  393. return;
  394. }
  395. VERIFY_INTERRUPTS_DISABLED();
  396. VERIFY(Processor::current_in_irq());
  397. Processor::current().invoke_scheduler_async();
  398. }
  399. void Scheduler::invoke_async()
  400. {
  401. VERIFY_INTERRUPTS_DISABLED();
  402. VERIFY(!Processor::current_in_irq());
  403. // Since this function is called when leaving critical sections (such
  404. // as a Spinlock), we need to check if we're not already doing this
  405. // to prevent recursion
  406. if (!Processor::current_in_scheduler())
  407. pick_next();
  408. }
  409. void Scheduler::notify_finalizer()
  410. {
  411. if (!g_finalizer_has_work.exchange(true, AK::MemoryOrder::memory_order_acq_rel))
  412. g_finalizer_wait_queue->wake_all();
  413. }
  414. void Scheduler::idle_loop(void*)
  415. {
  416. auto& proc = Processor::current();
  417. dbgln("Scheduler[{}]: idle loop running", proc.id());
  418. VERIFY(are_interrupts_enabled());
  419. for (;;) {
  420. proc.idle_begin();
  421. asm("hlt");
  422. proc.idle_end();
  423. VERIFY_INTERRUPTS_ENABLED();
  424. yield();
  425. }
  426. }
  427. void Scheduler::dump_scheduler_state(bool with_stack_traces)
  428. {
  429. dump_thread_list(with_stack_traces);
  430. }
  431. bool Scheduler::is_initialized()
  432. {
  433. // The scheduler is initialized iff the idle thread exists
  434. return Processor::idle_thread() != nullptr;
  435. }
  436. TotalTimeScheduled Scheduler::get_total_time_scheduled()
  437. {
  438. return g_total_time_scheduled.with([&](auto& total_time_scheduled) { return total_time_scheduled; });
  439. }
  440. void dump_thread_list(bool with_stack_traces)
  441. {
  442. dbgln("Scheduler thread list for processor {}:", Processor::current_id());
  443. auto get_cs = [](Thread& thread) -> u16 {
  444. if (!thread.current_trap())
  445. return thread.regs().cs;
  446. return thread.get_register_dump_from_stack().cs;
  447. };
  448. auto get_eip = [](Thread& thread) -> u32 {
  449. if (!thread.current_trap())
  450. return thread.regs().ip();
  451. return thread.get_register_dump_from_stack().ip();
  452. };
  453. Thread::for_each([&](Thread& thread) {
  454. auto color = thread.process().is_kernel_process() ? "\x1b[34;1m"sv : "\x1b[33;1m"sv;
  455. switch (thread.state()) {
  456. case Thread::State::Dying:
  457. dmesgln(" {}{:30}\x1b[0m @ {:04x}:{:08x} is {:14} (Finalizable: {}, nsched: {})",
  458. color,
  459. thread,
  460. get_cs(thread),
  461. get_eip(thread),
  462. thread.state_string(),
  463. thread.is_finalizable(),
  464. thread.times_scheduled());
  465. break;
  466. default:
  467. dmesgln(" {}{:30}\x1b[0m @ {:04x}:{:08x} is {:14} (Pr:{:2}, nsched: {})",
  468. color,
  469. thread,
  470. get_cs(thread),
  471. get_eip(thread),
  472. thread.state_string(),
  473. thread.priority(),
  474. thread.times_scheduled());
  475. break;
  476. }
  477. if (thread.state() == Thread::State::Blocked && thread.blocking_mutex()) {
  478. dmesgln(" Blocking on Mutex {:#x} ({})", thread.blocking_mutex(), thread.blocking_mutex()->name());
  479. }
  480. if (thread.state() == Thread::State::Blocked && thread.blocker()) {
  481. dmesgln(" Blocking on Blocker {:#x}", thread.blocker());
  482. }
  483. #if LOCK_DEBUG
  484. thread.for_each_held_lock([](auto const& entry) {
  485. dmesgln(" Holding lock {:#x} ({}) at {}", entry.lock, entry.lock->name(), entry.lock_location);
  486. });
  487. #endif
  488. if (with_stack_traces) {
  489. auto trace_or_error = thread.backtrace();
  490. if (!trace_or_error.is_error()) {
  491. auto trace = trace_or_error.release_value();
  492. dbgln("Backtrace:");
  493. kernelputstr(trace->characters(), trace->length());
  494. }
  495. }
  496. return IterationDecision::Continue;
  497. });
  498. }
  499. }