k_scheduler.cpp 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907
  1. // SPDX-FileCopyrightText: Copyright 2020 yuzu Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #include <bit>
  4. #include "common/assert.h"
  5. #include "common/bit_util.h"
  6. #include "common/fiber.h"
  7. #include "common/logging/log.h"
  8. #include "core/arm/arm_interface.h"
  9. #include "core/core.h"
  10. #include "core/core_timing.h"
  11. #include "core/cpu_manager.h"
  12. #include "core/hle/kernel/k_interrupt_manager.h"
  13. #include "core/hle/kernel/k_process.h"
  14. #include "core/hle/kernel/k_scheduler.h"
  15. #include "core/hle/kernel/k_scoped_scheduler_lock_and_sleep.h"
  16. #include "core/hle/kernel/k_thread.h"
  17. #include "core/hle/kernel/kernel.h"
  18. #include "core/hle/kernel/physical_core.h"
  19. namespace Kernel {
  20. static void IncrementScheduledCount(Kernel::KThread* thread) {
  21. if (auto process = thread->GetOwnerProcess(); process) {
  22. process->IncrementScheduledCount();
  23. }
  24. }
  25. KScheduler::KScheduler(KernelCore& kernel) : m_kernel{kernel} {
  26. m_switch_fiber = std::make_shared<Common::Fiber>([this] {
  27. while (true) {
  28. ScheduleImplFiber();
  29. }
  30. });
  31. m_state.needs_scheduling = true;
  32. }
  33. KScheduler::~KScheduler() = default;
  34. void KScheduler::SetInterruptTaskRunnable() {
  35. m_state.interrupt_task_runnable = true;
  36. m_state.needs_scheduling = true;
  37. }
  38. void KScheduler::RequestScheduleOnInterrupt() {
  39. m_state.needs_scheduling = true;
  40. if (CanSchedule(m_kernel)) {
  41. ScheduleOnInterrupt();
  42. }
  43. }
  44. void KScheduler::DisableScheduling(KernelCore& kernel) {
  45. ASSERT(GetCurrentThread(kernel).GetDisableDispatchCount() >= 0);
  46. GetCurrentThread(kernel).DisableDispatch();
  47. }
  48. void KScheduler::EnableScheduling(KernelCore& kernel, u64 cores_needing_scheduling) {
  49. ASSERT(GetCurrentThread(kernel).GetDisableDispatchCount() >= 1);
  50. auto* scheduler{kernel.CurrentScheduler()};
  51. if (!scheduler || kernel.IsPhantomModeForSingleCore()) {
  52. KScheduler::RescheduleCores(kernel, cores_needing_scheduling);
  53. KScheduler::RescheduleCurrentHLEThread(kernel);
  54. return;
  55. }
  56. scheduler->RescheduleOtherCores(cores_needing_scheduling);
  57. if (GetCurrentThread(kernel).GetDisableDispatchCount() > 1) {
  58. GetCurrentThread(kernel).EnableDispatch();
  59. } else {
  60. scheduler->RescheduleCurrentCore();
  61. }
  62. }
  63. void KScheduler::RescheduleCurrentHLEThread(KernelCore& kernel) {
  64. // HACK: we cannot schedule from this thread, it is not a core thread
  65. ASSERT(GetCurrentThread(kernel).GetDisableDispatchCount() == 1);
  66. // Ensure dummy threads that are waiting block.
  67. GetCurrentThread(kernel).DummyThreadBeginWait();
  68. ASSERT(GetCurrentThread(kernel).GetState() != ThreadState::Waiting);
  69. GetCurrentThread(kernel).EnableDispatch();
  70. }
  71. u64 KScheduler::UpdateHighestPriorityThreads(KernelCore& kernel) {
  72. if (IsSchedulerUpdateNeeded(kernel)) {
  73. return UpdateHighestPriorityThreadsImpl(kernel);
  74. } else {
  75. return 0;
  76. }
  77. }
  78. void KScheduler::Schedule() {
  79. ASSERT(GetCurrentThread(m_kernel).GetDisableDispatchCount() == 1);
  80. ASSERT(m_core_id == GetCurrentCoreId(m_kernel));
  81. ScheduleImpl();
  82. }
  83. void KScheduler::ScheduleOnInterrupt() {
  84. GetCurrentThread(m_kernel).DisableDispatch();
  85. Schedule();
  86. GetCurrentThread(m_kernel).EnableDispatch();
  87. }
  88. void KScheduler::PreemptSingleCore() {
  89. GetCurrentThread(m_kernel).DisableDispatch();
  90. auto* thread = GetCurrentThreadPointer(m_kernel);
  91. auto& previous_scheduler = m_kernel.Scheduler(thread->GetCurrentCore());
  92. previous_scheduler.Unload(thread);
  93. Common::Fiber::YieldTo(thread->GetHostContext(), *m_switch_fiber);
  94. GetCurrentThread(m_kernel).EnableDispatch();
  95. }
  96. void KScheduler::RescheduleCurrentCore() {
  97. ASSERT(!m_kernel.IsPhantomModeForSingleCore());
  98. ASSERT(GetCurrentThread(m_kernel).GetDisableDispatchCount() == 1);
  99. GetCurrentThread(m_kernel).EnableDispatch();
  100. if (m_state.needs_scheduling.load()) {
  101. // Disable interrupts, and then check again if rescheduling is needed.
  102. // KScopedInterruptDisable intr_disable;
  103. m_kernel.CurrentScheduler()->RescheduleCurrentCoreImpl();
  104. }
  105. }
  106. void KScheduler::RescheduleCurrentCoreImpl() {
  107. // Check that scheduling is needed.
  108. if (m_state.needs_scheduling.load()) [[likely]] {
  109. GetCurrentThread(m_kernel).DisableDispatch();
  110. Schedule();
  111. GetCurrentThread(m_kernel).EnableDispatch();
  112. }
  113. }
  114. void KScheduler::Initialize(KThread* main_thread, KThread* idle_thread, s32 core_id) {
  115. // Set core ID/idle thread/interrupt task manager.
  116. m_core_id = core_id;
  117. m_idle_thread = idle_thread;
  118. // m_state.idle_thread_stack = m_idle_thread->GetStackTop();
  119. // m_state.interrupt_task_manager = std::addressof(kernel.GetInterruptTaskManager());
  120. // Insert the main thread into the priority queue.
  121. // {
  122. // KScopedSchedulerLock lk{m_kernel};
  123. // GetPriorityQueue(m_kernel).PushBack(GetCurrentThreadPointer(m_kernel));
  124. // SetSchedulerUpdateNeeded(m_kernel);
  125. // }
  126. // Bind interrupt handler.
  127. // kernel.GetInterruptManager().BindHandler(
  128. // GetSchedulerInterruptHandler(m_kernel), KInterruptName::Scheduler, m_core_id,
  129. // KInterruptController::PriorityLevel::Scheduler, false, false);
  130. // Set the current thread.
  131. m_current_thread = main_thread;
  132. }
  133. void KScheduler::Activate() {
  134. ASSERT(GetCurrentThread(m_kernel).GetDisableDispatchCount() == 1);
  135. // m_state.should_count_idle = KTargetSystem::IsDebugMode();
  136. m_is_active = true;
  137. RescheduleCurrentCore();
  138. }
  139. void KScheduler::OnThreadStart() {
  140. GetCurrentThread(m_kernel).EnableDispatch();
  141. }
  142. u64 KScheduler::UpdateHighestPriorityThread(KThread* highest_thread) {
  143. if (KThread* prev_highest_thread = m_state.highest_priority_thread;
  144. prev_highest_thread != highest_thread) [[likely]] {
  145. if (prev_highest_thread != nullptr) [[likely]] {
  146. IncrementScheduledCount(prev_highest_thread);
  147. prev_highest_thread->SetLastScheduledTick(m_kernel.System().CoreTiming().GetCPUTicks());
  148. }
  149. if (m_state.should_count_idle) {
  150. if (highest_thread != nullptr) [[likely]] {
  151. if (KProcess* process = highest_thread->GetOwnerProcess(); process != nullptr) {
  152. process->SetRunningThread(m_core_id, highest_thread, m_state.idle_count);
  153. }
  154. } else {
  155. m_state.idle_count++;
  156. }
  157. }
  158. m_state.highest_priority_thread = highest_thread;
  159. m_state.needs_scheduling = true;
  160. return (1ULL << m_core_id);
  161. } else {
  162. return 0;
  163. }
  164. }
  165. u64 KScheduler::UpdateHighestPriorityThreadsImpl(KernelCore& kernel) {
  166. ASSERT(IsSchedulerLockedByCurrentThread(kernel));
  167. // Clear that we need to update.
  168. ClearSchedulerUpdateNeeded(kernel);
  169. u64 cores_needing_scheduling = 0, idle_cores = 0;
  170. KThread* top_threads[Core::Hardware::NUM_CPU_CORES];
  171. auto& priority_queue = GetPriorityQueue(kernel);
  172. // We want to go over all cores, finding the highest priority thread and determining if
  173. // scheduling is needed for that core.
  174. for (size_t core_id = 0; core_id < Core::Hardware::NUM_CPU_CORES; core_id++) {
  175. KThread* top_thread = priority_queue.GetScheduledFront(static_cast<s32>(core_id));
  176. if (top_thread != nullptr) {
  177. // We need to check if the thread's process has a pinned thread.
  178. if (KProcess* parent = top_thread->GetOwnerProcess()) {
  179. // Check that there's a pinned thread other than the current top thread.
  180. if (KThread* pinned = parent->GetPinnedThread(static_cast<s32>(core_id));
  181. pinned != nullptr && pinned != top_thread) {
  182. // We need to prefer threads with kernel waiters to the pinned thread.
  183. if (top_thread->GetNumKernelWaiters() ==
  184. 0 /* && top_thread != parent->GetExceptionThread() */) {
  185. // If the pinned thread is runnable, use it.
  186. if (pinned->GetRawState() == ThreadState::Runnable) {
  187. top_thread = pinned;
  188. } else {
  189. top_thread = nullptr;
  190. }
  191. }
  192. }
  193. }
  194. } else {
  195. idle_cores |= (1ULL << core_id);
  196. }
  197. top_threads[core_id] = top_thread;
  198. cores_needing_scheduling |=
  199. kernel.Scheduler(core_id).UpdateHighestPriorityThread(top_threads[core_id]);
  200. }
  201. // Idle cores are bad. We're going to try to migrate threads to each idle core in turn.
  202. while (idle_cores != 0) {
  203. const s32 core_id = static_cast<s32>(std::countr_zero(idle_cores));
  204. if (KThread* suggested = priority_queue.GetSuggestedFront(core_id); suggested != nullptr) {
  205. s32 migration_candidates[Core::Hardware::NUM_CPU_CORES];
  206. size_t num_candidates = 0;
  207. // While we have a suggested thread, try to migrate it!
  208. while (suggested != nullptr) {
  209. // Check if the suggested thread is the top thread on its core.
  210. const s32 suggested_core = suggested->GetActiveCore();
  211. if (KThread* top_thread =
  212. (suggested_core >= 0) ? top_threads[suggested_core] : nullptr;
  213. top_thread != suggested) {
  214. // Make sure we're not dealing with threads too high priority for migration.
  215. if (top_thread != nullptr &&
  216. top_thread->GetPriority() < HighestCoreMigrationAllowedPriority) {
  217. break;
  218. }
  219. // The suggested thread isn't bound to its core, so we can migrate it!
  220. suggested->SetActiveCore(core_id);
  221. priority_queue.ChangeCore(suggested_core, suggested);
  222. top_threads[core_id] = suggested;
  223. cores_needing_scheduling |=
  224. kernel.Scheduler(core_id).UpdateHighestPriorityThread(top_threads[core_id]);
  225. break;
  226. }
  227. // Note this core as a candidate for migration.
  228. ASSERT(num_candidates < Core::Hardware::NUM_CPU_CORES);
  229. migration_candidates[num_candidates++] = suggested_core;
  230. suggested = priority_queue.GetSuggestedNext(core_id, suggested);
  231. }
  232. // If suggested is nullptr, we failed to migrate a specific thread. So let's try all our
  233. // candidate cores' top threads.
  234. if (suggested == nullptr) {
  235. for (size_t i = 0; i < num_candidates; i++) {
  236. // Check if there's some other thread that can run on the candidate core.
  237. const s32 candidate_core = migration_candidates[i];
  238. suggested = top_threads[candidate_core];
  239. if (KThread* next_on_candidate_core =
  240. priority_queue.GetScheduledNext(candidate_core, suggested);
  241. next_on_candidate_core != nullptr) {
  242. // The candidate core can run some other thread! We'll migrate its current
  243. // top thread to us.
  244. top_threads[candidate_core] = next_on_candidate_core;
  245. cores_needing_scheduling |=
  246. kernel.Scheduler(candidate_core)
  247. .UpdateHighestPriorityThread(top_threads[candidate_core]);
  248. // Perform the migration.
  249. suggested->SetActiveCore(core_id);
  250. priority_queue.ChangeCore(candidate_core, suggested);
  251. top_threads[core_id] = suggested;
  252. cores_needing_scheduling |=
  253. kernel.Scheduler(core_id).UpdateHighestPriorityThread(
  254. top_threads[core_id]);
  255. break;
  256. }
  257. }
  258. }
  259. }
  260. idle_cores &= ~(1ULL << core_id);
  261. }
  262. // HACK: any waiting dummy threads can wake up now.
  263. kernel.GlobalSchedulerContext().WakeupWaitingDummyThreads();
  264. // HACK: if we are a dummy thread, and we need to go sleep, indicate
  265. // that for when the lock is released.
  266. KThread* const cur_thread = GetCurrentThreadPointer(kernel);
  267. if (cur_thread->IsDummyThread() && cur_thread->GetState() != ThreadState::Runnable) {
  268. cur_thread->RequestDummyThreadWait();
  269. }
  270. return cores_needing_scheduling;
  271. }
  272. void KScheduler::SwitchThread(KThread* next_thread) {
  273. KProcess* const cur_process = GetCurrentProcessPointer(m_kernel);
  274. KThread* const cur_thread = GetCurrentThreadPointer(m_kernel);
  275. // We never want to schedule a null thread, so use the idle thread if we don't have a next.
  276. if (next_thread == nullptr) {
  277. next_thread = m_idle_thread;
  278. }
  279. if (next_thread->GetCurrentCore() != m_core_id) {
  280. next_thread->SetCurrentCore(m_core_id);
  281. }
  282. // If we're not actually switching thread, there's nothing to do.
  283. if (next_thread == cur_thread) {
  284. return;
  285. }
  286. // Next thread is now known not to be nullptr, and must not be dispatchable.
  287. ASSERT(next_thread->GetDisableDispatchCount() == 1);
  288. ASSERT(!next_thread->IsDummyThread());
  289. // Update the CPU time tracking variables.
  290. const s64 prev_tick = m_last_context_switch_time;
  291. const s64 cur_tick = m_kernel.System().CoreTiming().GetCPUTicks();
  292. const s64 tick_diff = cur_tick - prev_tick;
  293. cur_thread->AddCpuTime(m_core_id, tick_diff);
  294. if (cur_process != nullptr) {
  295. cur_process->UpdateCPUTimeTicks(tick_diff);
  296. }
  297. m_last_context_switch_time = cur_tick;
  298. // Update our previous thread.
  299. if (cur_process != nullptr) {
  300. if (!cur_thread->IsTerminationRequested() && cur_thread->GetActiveCore() == m_core_id)
  301. [[likely]] {
  302. m_state.prev_thread = cur_thread;
  303. } else {
  304. m_state.prev_thread = nullptr;
  305. }
  306. }
  307. // Switch the current process, if we're switching processes.
  308. // if (KProcess *next_process = next_thread->GetOwnerProcess(); next_process != cur_process) {
  309. // KProcess::Switch(cur_process, next_process);
  310. // }
  311. // Set the new thread.
  312. SetCurrentThread(m_kernel, next_thread);
  313. m_current_thread = next_thread;
  314. // Set the new Thread Local region.
  315. // cpu::SwitchThreadLocalRegion(GetInteger(next_thread->GetThreadLocalRegionAddress()));
  316. }
  317. void KScheduler::ScheduleImpl() {
  318. // First, clear the needs scheduling bool.
  319. m_state.needs_scheduling.store(false, std::memory_order_relaxed);
  320. std::atomic_thread_fence(std::memory_order_seq_cst);
  321. // Load the appropriate thread pointers for scheduling.
  322. KThread* const cur_thread{GetCurrentThreadPointer(m_kernel)};
  323. KThread* highest_priority_thread{m_state.highest_priority_thread};
  324. // Check whether there are runnable interrupt tasks.
  325. if (m_state.interrupt_task_runnable) {
  326. // The interrupt task is runnable.
  327. // We want to switch to the interrupt task/idle thread.
  328. highest_priority_thread = nullptr;
  329. }
  330. // If there aren't, we want to check if the highest priority thread is the same as the current
  331. // thread.
  332. if (highest_priority_thread == cur_thread) {
  333. // If they're the same, then we can just issue a memory barrier and return.
  334. std::atomic_thread_fence(std::memory_order_seq_cst);
  335. return;
  336. }
  337. // The highest priority thread is not the same as the current thread.
  338. // Jump to the switcher and continue executing from there.
  339. m_switch_cur_thread = cur_thread;
  340. m_switch_highest_priority_thread = highest_priority_thread;
  341. m_switch_from_schedule = true;
  342. Common::Fiber::YieldTo(cur_thread->m_host_context, *m_switch_fiber);
  343. // Returning from ScheduleImpl occurs after this thread has been scheduled again.
  344. }
  345. void KScheduler::ScheduleImplFiber() {
  346. KThread* const cur_thread{m_switch_cur_thread};
  347. KThread* highest_priority_thread{m_switch_highest_priority_thread};
  348. // If we're not coming from scheduling (i.e., we came from SC preemption),
  349. // we should restart the scheduling loop directly. Not accurate to HOS.
  350. if (!m_switch_from_schedule) {
  351. goto retry;
  352. }
  353. // Mark that we are not coming from scheduling anymore.
  354. m_switch_from_schedule = false;
  355. // Save the original thread context.
  356. Unload(cur_thread);
  357. // The current thread's context has been entirely taken care of.
  358. // Now we want to loop until we successfully switch the thread context.
  359. while (true) {
  360. // We're starting to try to do the context switch.
  361. // Check if the highest priority thread is null.
  362. if (!highest_priority_thread) {
  363. // The next thread is nullptr!
  364. // Switch to the idle thread. Note: HOS treats idling as a special case for
  365. // performance. This is not *required* for yuzu's purposes, and for singlecore
  366. // compatibility, we can just move the logic that would go here into the execution
  367. // of the idle thread. If we ever remove singlecore, we should implement this
  368. // accurately to HOS.
  369. highest_priority_thread = m_idle_thread;
  370. }
  371. // We want to try to lock the highest priority thread's context.
  372. // Try to take it.
  373. while (!highest_priority_thread->m_context_guard.try_lock()) {
  374. // The highest priority thread's context is already locked.
  375. // Check if we need scheduling. If we don't, we can retry directly.
  376. if (m_state.needs_scheduling.load(std::memory_order_seq_cst)) {
  377. // If we do, another core is interfering, and we must start again.
  378. goto retry;
  379. }
  380. }
  381. // It's time to switch the thread.
  382. // Switch to the highest priority thread.
  383. SwitchThread(highest_priority_thread);
  384. // Check if we need scheduling. If we do, then we can't complete the switch and should
  385. // retry.
  386. if (m_state.needs_scheduling.load(std::memory_order_seq_cst)) {
  387. // Our switch failed.
  388. // We should unlock the thread context, and then retry.
  389. highest_priority_thread->m_context_guard.unlock();
  390. goto retry;
  391. } else {
  392. break;
  393. }
  394. retry:
  395. // We failed to successfully do the context switch, and need to retry.
  396. // Clear needs_scheduling.
  397. m_state.needs_scheduling.store(false, std::memory_order_relaxed);
  398. std::atomic_thread_fence(std::memory_order_seq_cst);
  399. // Refresh the highest priority thread.
  400. highest_priority_thread = m_state.highest_priority_thread;
  401. }
  402. // Reload the guest thread context.
  403. Reload(highest_priority_thread);
  404. // Reload the host thread.
  405. Common::Fiber::YieldTo(m_switch_fiber, *highest_priority_thread->m_host_context);
  406. }
  407. void KScheduler::Unload(KThread* thread) {
  408. auto& cpu_core = m_kernel.System().ArmInterface(m_core_id);
  409. cpu_core.SaveContext(thread->GetContext32());
  410. cpu_core.SaveContext(thread->GetContext64());
  411. // Save the TPIDR_EL0 system register in case it was modified.
  412. thread->SetTpidrEl0(cpu_core.GetTPIDR_EL0());
  413. cpu_core.ClearExclusiveState();
  414. // Check if the thread is terminated by checking the DPC flags.
  415. if ((thread->GetStackParameters().dpc_flags & static_cast<u32>(DpcFlag::Terminated)) == 0) {
  416. // The thread isn't terminated, so we want to unlock it.
  417. thread->m_context_guard.unlock();
  418. }
  419. }
  420. void KScheduler::Reload(KThread* thread) {
  421. auto& cpu_core = m_kernel.System().ArmInterface(m_core_id);
  422. cpu_core.LoadContext(thread->GetContext32());
  423. cpu_core.LoadContext(thread->GetContext64());
  424. cpu_core.SetTlsAddress(GetInteger(thread->GetTlsAddress()));
  425. cpu_core.SetTPIDR_EL0(thread->GetTpidrEl0());
  426. cpu_core.LoadWatchpointArray(thread->GetOwnerProcess()->GetWatchpoints());
  427. cpu_core.ClearExclusiveState();
  428. }
  429. void KScheduler::ClearPreviousThread(KernelCore& kernel, KThread* thread) {
  430. ASSERT(IsSchedulerLockedByCurrentThread(kernel));
  431. for (size_t i = 0; i < Core::Hardware::NUM_CPU_CORES; ++i) {
  432. // Get an atomic reference to the core scheduler's previous thread.
  433. auto& prev_thread{kernel.Scheduler(i).m_state.prev_thread};
  434. // Atomically clear the previous thread if it's our target.
  435. KThread* compare = thread;
  436. prev_thread.compare_exchange_strong(compare, nullptr, std::memory_order_seq_cst);
  437. }
  438. }
  439. void KScheduler::OnThreadStateChanged(KernelCore& kernel, KThread* thread, ThreadState old_state) {
  440. ASSERT(IsSchedulerLockedByCurrentThread(kernel));
  441. // Check if the state has changed, because if it hasn't there's nothing to do.
  442. const ThreadState cur_state = thread->GetRawState();
  443. if (cur_state == old_state) {
  444. return;
  445. }
  446. // Update the priority queues.
  447. if (old_state == ThreadState::Runnable) {
  448. // If we were previously runnable, then we're not runnable now, and we should remove.
  449. GetPriorityQueue(kernel).Remove(thread);
  450. IncrementScheduledCount(thread);
  451. SetSchedulerUpdateNeeded(kernel);
  452. if (thread->IsDummyThread()) {
  453. // HACK: if this is a dummy thread, it should no longer wake up when the
  454. // scheduler lock is released.
  455. kernel.GlobalSchedulerContext().UnregisterDummyThreadForWakeup(thread);
  456. }
  457. } else if (cur_state == ThreadState::Runnable) {
  458. // If we're now runnable, then we weren't previously, and we should add.
  459. GetPriorityQueue(kernel).PushBack(thread);
  460. IncrementScheduledCount(thread);
  461. SetSchedulerUpdateNeeded(kernel);
  462. if (thread->IsDummyThread()) {
  463. // HACK: if this is a dummy thread, it should wake up when the scheduler
  464. // lock is released.
  465. kernel.GlobalSchedulerContext().RegisterDummyThreadForWakeup(thread);
  466. }
  467. }
  468. }
  469. void KScheduler::OnThreadPriorityChanged(KernelCore& kernel, KThread* thread, s32 old_priority) {
  470. ASSERT(IsSchedulerLockedByCurrentThread(kernel));
  471. // If the thread is runnable, we want to change its priority in the queue.
  472. if (thread->GetRawState() == ThreadState::Runnable) {
  473. GetPriorityQueue(kernel).ChangePriority(old_priority,
  474. thread == GetCurrentThreadPointer(kernel), thread);
  475. IncrementScheduledCount(thread);
  476. SetSchedulerUpdateNeeded(kernel);
  477. }
  478. }
  479. void KScheduler::OnThreadAffinityMaskChanged(KernelCore& kernel, KThread* thread,
  480. const KAffinityMask& old_affinity, s32 old_core) {
  481. ASSERT(IsSchedulerLockedByCurrentThread(kernel));
  482. // If the thread is runnable, we want to change its affinity in the queue.
  483. if (thread->GetRawState() == ThreadState::Runnable) {
  484. GetPriorityQueue(kernel).ChangeAffinityMask(old_core, old_affinity, thread);
  485. IncrementScheduledCount(thread);
  486. SetSchedulerUpdateNeeded(kernel);
  487. }
  488. }
  489. void KScheduler::RotateScheduledQueue(KernelCore& kernel, s32 core_id, s32 priority) {
  490. ASSERT(IsSchedulerLockedByCurrentThread(kernel));
  491. // Get a reference to the priority queue.
  492. auto& priority_queue = GetPriorityQueue(kernel);
  493. // Rotate the front of the queue to the end.
  494. KThread* top_thread = priority_queue.GetScheduledFront(core_id, priority);
  495. KThread* next_thread = nullptr;
  496. if (top_thread != nullptr) {
  497. next_thread = priority_queue.MoveToScheduledBack(top_thread);
  498. if (next_thread != top_thread) {
  499. IncrementScheduledCount(top_thread);
  500. IncrementScheduledCount(next_thread);
  501. }
  502. }
  503. // While we have a suggested thread, try to migrate it!
  504. {
  505. KThread* suggested = priority_queue.GetSuggestedFront(core_id, priority);
  506. while (suggested != nullptr) {
  507. // Check if the suggested thread is the top thread on its core.
  508. const s32 suggested_core = suggested->GetActiveCore();
  509. if (KThread* top_on_suggested_core =
  510. (suggested_core >= 0) ? priority_queue.GetScheduledFront(suggested_core)
  511. : nullptr;
  512. top_on_suggested_core != suggested) {
  513. // If the next thread is a new thread that has been waiting longer than our
  514. // suggestion, we prefer it to our suggestion.
  515. if (top_thread != next_thread && next_thread != nullptr &&
  516. next_thread->GetLastScheduledTick() < suggested->GetLastScheduledTick()) {
  517. suggested = nullptr;
  518. break;
  519. }
  520. // If we're allowed to do a migration, do one.
  521. // NOTE: Unlike migrations in UpdateHighestPriorityThread, this moves the suggestion
  522. // to the front of the queue.
  523. if (top_on_suggested_core == nullptr ||
  524. top_on_suggested_core->GetPriority() >= HighestCoreMigrationAllowedPriority) {
  525. suggested->SetActiveCore(core_id);
  526. priority_queue.ChangeCore(suggested_core, suggested, true);
  527. IncrementScheduledCount(suggested);
  528. break;
  529. }
  530. }
  531. // Get the next suggestion.
  532. suggested = priority_queue.GetSamePriorityNext(core_id, suggested);
  533. }
  534. }
  535. // Now that we might have migrated a thread with the same priority, check if we can do better.
  536. {
  537. KThread* best_thread = priority_queue.GetScheduledFront(core_id);
  538. if (best_thread == GetCurrentThreadPointer(kernel)) {
  539. best_thread = priority_queue.GetScheduledNext(core_id, best_thread);
  540. }
  541. // If the best thread we can choose has a priority the same or worse than ours, try to
  542. // migrate a higher priority thread.
  543. if (best_thread != nullptr && best_thread->GetPriority() >= priority) {
  544. KThread* suggested = priority_queue.GetSuggestedFront(core_id);
  545. while (suggested != nullptr) {
  546. // If the suggestion's priority is the same as ours, don't bother.
  547. if (suggested->GetPriority() >= best_thread->GetPriority()) {
  548. break;
  549. }
  550. // Check if the suggested thread is the top thread on its core.
  551. const s32 suggested_core = suggested->GetActiveCore();
  552. if (KThread* top_on_suggested_core =
  553. (suggested_core >= 0) ? priority_queue.GetScheduledFront(suggested_core)
  554. : nullptr;
  555. top_on_suggested_core != suggested) {
  556. // If we're allowed to do a migration, do one.
  557. // NOTE: Unlike migrations in UpdateHighestPriorityThread, this moves the
  558. // suggestion to the front of the queue.
  559. if (top_on_suggested_core == nullptr ||
  560. top_on_suggested_core->GetPriority() >=
  561. HighestCoreMigrationAllowedPriority) {
  562. suggested->SetActiveCore(core_id);
  563. priority_queue.ChangeCore(suggested_core, suggested, true);
  564. IncrementScheduledCount(suggested);
  565. break;
  566. }
  567. }
  568. // Get the next suggestion.
  569. suggested = priority_queue.GetSuggestedNext(core_id, suggested);
  570. }
  571. }
  572. }
  573. // After a rotation, we need a scheduler update.
  574. SetSchedulerUpdateNeeded(kernel);
  575. }
  576. void KScheduler::YieldWithoutCoreMigration(KernelCore& kernel) {
  577. // Validate preconditions.
  578. ASSERT(CanSchedule(kernel));
  579. ASSERT(GetCurrentProcessPointer(kernel) != nullptr);
  580. // Get the current thread and process.
  581. KThread& cur_thread = GetCurrentThread(kernel);
  582. KProcess& cur_process = GetCurrentProcess(kernel);
  583. // If the thread's yield count matches, there's nothing for us to do.
  584. if (cur_thread.GetYieldScheduleCount() == cur_process.GetScheduledCount()) {
  585. return;
  586. }
  587. // Get a reference to the priority queue.
  588. auto& priority_queue = GetPriorityQueue(kernel);
  589. // Perform the yield.
  590. {
  591. KScopedSchedulerLock sl{kernel};
  592. const auto cur_state = cur_thread.GetRawState();
  593. if (cur_state == ThreadState::Runnable) {
  594. // Put the current thread at the back of the queue.
  595. KThread* next_thread = priority_queue.MoveToScheduledBack(std::addressof(cur_thread));
  596. IncrementScheduledCount(std::addressof(cur_thread));
  597. // If the next thread is different, we have an update to perform.
  598. if (next_thread != std::addressof(cur_thread)) {
  599. SetSchedulerUpdateNeeded(kernel);
  600. } else {
  601. // Otherwise, set the thread's yield count so that we won't waste work until the
  602. // process is scheduled again.
  603. cur_thread.SetYieldScheduleCount(cur_process.GetScheduledCount());
  604. }
  605. }
  606. }
  607. }
  608. void KScheduler::YieldWithCoreMigration(KernelCore& kernel) {
  609. // Validate preconditions.
  610. ASSERT(CanSchedule(kernel));
  611. ASSERT(GetCurrentProcessPointer(kernel) != nullptr);
  612. // Get the current thread and process.
  613. KThread& cur_thread = GetCurrentThread(kernel);
  614. KProcess& cur_process = GetCurrentProcess(kernel);
  615. // If the thread's yield count matches, there's nothing for us to do.
  616. if (cur_thread.GetYieldScheduleCount() == cur_process.GetScheduledCount()) {
  617. return;
  618. }
  619. // Get a reference to the priority queue.
  620. auto& priority_queue = GetPriorityQueue(kernel);
  621. // Perform the yield.
  622. {
  623. KScopedSchedulerLock sl{kernel};
  624. const auto cur_state = cur_thread.GetRawState();
  625. if (cur_state == ThreadState::Runnable) {
  626. // Get the current active core.
  627. const s32 core_id = cur_thread.GetActiveCore();
  628. // Put the current thread at the back of the queue.
  629. KThread* next_thread = priority_queue.MoveToScheduledBack(std::addressof(cur_thread));
  630. IncrementScheduledCount(std::addressof(cur_thread));
  631. // While we have a suggested thread, try to migrate it!
  632. bool recheck = false;
  633. KThread* suggested = priority_queue.GetSuggestedFront(core_id);
  634. while (suggested != nullptr) {
  635. // Check if the suggested thread is the thread running on its core.
  636. const s32 suggested_core = suggested->GetActiveCore();
  637. if (KThread* running_on_suggested_core =
  638. (suggested_core >= 0)
  639. ? kernel.Scheduler(suggested_core).m_state.highest_priority_thread
  640. : nullptr;
  641. running_on_suggested_core != suggested) {
  642. // If the current thread's priority is higher than our suggestion's we prefer
  643. // the next thread to the suggestion. We also prefer the next thread when the
  644. // current thread's priority is equal to the suggestions, but the next thread
  645. // has been waiting longer.
  646. if ((suggested->GetPriority() > cur_thread.GetPriority()) ||
  647. (suggested->GetPriority() == cur_thread.GetPriority() &&
  648. next_thread != std::addressof(cur_thread) &&
  649. next_thread->GetLastScheduledTick() < suggested->GetLastScheduledTick())) {
  650. suggested = nullptr;
  651. break;
  652. }
  653. // If we're allowed to do a migration, do one.
  654. // NOTE: Unlike migrations in UpdateHighestPriorityThread, this moves the
  655. // suggestion to the front of the queue.
  656. if (running_on_suggested_core == nullptr ||
  657. running_on_suggested_core->GetPriority() >=
  658. HighestCoreMigrationAllowedPriority) {
  659. suggested->SetActiveCore(core_id);
  660. priority_queue.ChangeCore(suggested_core, suggested, true);
  661. IncrementScheduledCount(suggested);
  662. break;
  663. } else {
  664. // We couldn't perform a migration, but we should check again on a future
  665. // yield.
  666. recheck = true;
  667. }
  668. }
  669. // Get the next suggestion.
  670. suggested = priority_queue.GetSuggestedNext(core_id, suggested);
  671. }
  672. // If we still have a suggestion or the next thread is different, we have an update to
  673. // perform.
  674. if (suggested != nullptr || next_thread != std::addressof(cur_thread)) {
  675. SetSchedulerUpdateNeeded(kernel);
  676. } else if (!recheck) {
  677. // Otherwise if we don't need to re-check, set the thread's yield count so that we
  678. // won't waste work until the process is scheduled again.
  679. cur_thread.SetYieldScheduleCount(cur_process.GetScheduledCount());
  680. }
  681. }
  682. }
  683. }
  684. void KScheduler::YieldToAnyThread(KernelCore& kernel) {
  685. // Validate preconditions.
  686. ASSERT(CanSchedule(kernel));
  687. ASSERT(GetCurrentProcessPointer(kernel) != nullptr);
  688. // Get the current thread and process.
  689. KThread& cur_thread = GetCurrentThread(kernel);
  690. KProcess& cur_process = GetCurrentProcess(kernel);
  691. // If the thread's yield count matches, there's nothing for us to do.
  692. if (cur_thread.GetYieldScheduleCount() == cur_process.GetScheduledCount()) {
  693. return;
  694. }
  695. // Get a reference to the priority queue.
  696. auto& priority_queue = GetPriorityQueue(kernel);
  697. // Perform the yield.
  698. {
  699. KScopedSchedulerLock sl{kernel};
  700. const auto cur_state = cur_thread.GetRawState();
  701. if (cur_state == ThreadState::Runnable) {
  702. // Get the current active core.
  703. const s32 core_id = cur_thread.GetActiveCore();
  704. // Migrate the current thread to core -1.
  705. cur_thread.SetActiveCore(-1);
  706. priority_queue.ChangeCore(core_id, std::addressof(cur_thread));
  707. IncrementScheduledCount(std::addressof(cur_thread));
  708. // If there's nothing scheduled, we can try to perform a migration.
  709. if (priority_queue.GetScheduledFront(core_id) == nullptr) {
  710. // While we have a suggested thread, try to migrate it!
  711. KThread* suggested = priority_queue.GetSuggestedFront(core_id);
  712. while (suggested != nullptr) {
  713. // Check if the suggested thread is the top thread on its core.
  714. const s32 suggested_core = suggested->GetActiveCore();
  715. if (KThread* top_on_suggested_core =
  716. (suggested_core >= 0) ? priority_queue.GetScheduledFront(suggested_core)
  717. : nullptr;
  718. top_on_suggested_core != suggested) {
  719. // If we're allowed to do a migration, do one.
  720. if (top_on_suggested_core == nullptr ||
  721. top_on_suggested_core->GetPriority() >=
  722. HighestCoreMigrationAllowedPriority) {
  723. suggested->SetActiveCore(core_id);
  724. priority_queue.ChangeCore(suggested_core, suggested);
  725. IncrementScheduledCount(suggested);
  726. }
  727. // Regardless of whether we migrated, we had a candidate, so we're done.
  728. break;
  729. }
  730. // Get the next suggestion.
  731. suggested = priority_queue.GetSuggestedNext(core_id, suggested);
  732. }
  733. // If the suggestion is different from the current thread, we need to perform an
  734. // update.
  735. if (suggested != std::addressof(cur_thread)) {
  736. SetSchedulerUpdateNeeded(kernel);
  737. } else {
  738. // Otherwise, set the thread's yield count so that we won't waste work until the
  739. // process is scheduled again.
  740. cur_thread.SetYieldScheduleCount(cur_process.GetScheduledCount());
  741. }
  742. } else {
  743. // Otherwise, we have an update to perform.
  744. SetSchedulerUpdateNeeded(kernel);
  745. }
  746. }
  747. }
  748. }
  749. void KScheduler::RescheduleOtherCores(u64 cores_needing_scheduling) {
  750. if (const u64 core_mask = cores_needing_scheduling & ~(1ULL << m_core_id); core_mask != 0) {
  751. RescheduleCores(m_kernel, core_mask);
  752. }
  753. }
  754. void KScheduler::RescheduleCores(KernelCore& kernel, u64 core_mask) {
  755. // Send IPI
  756. for (size_t i = 0; i < Core::Hardware::NUM_CPU_CORES; i++) {
  757. if (core_mask & (1ULL << i)) {
  758. kernel.PhysicalCore(i).Interrupt();
  759. }
  760. }
  761. }
  762. } // namespace Kernel