k_scheduler.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848
  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. void KScheduler::RescheduleCores(KernelCore& kernel, u64 cores_pending_reschedule) {
  26. auto scheduler = kernel.CurrentScheduler();
  27. u32 current_core{0xF};
  28. bool must_context_switch{};
  29. if (scheduler) {
  30. current_core = scheduler->core_id;
  31. // TODO(bunnei): Should be set to true when we deprecate single core
  32. must_context_switch = !kernel.IsPhantomModeForSingleCore();
  33. }
  34. while (cores_pending_reschedule != 0) {
  35. const auto core = static_cast<u32>(std::countr_zero(cores_pending_reschedule));
  36. ASSERT(core < Core::Hardware::NUM_CPU_CORES);
  37. if (!must_context_switch || core != current_core) {
  38. auto& phys_core = kernel.PhysicalCore(core);
  39. phys_core.Interrupt();
  40. }
  41. cores_pending_reschedule &= ~(1ULL << core);
  42. }
  43. for (std::size_t core_id = 0; core_id < Core::Hardware::NUM_CPU_CORES; ++core_id) {
  44. if (kernel.PhysicalCore(core_id).IsInterrupted()) {
  45. KInterruptManager::HandleInterrupt(kernel, static_cast<s32>(core_id));
  46. }
  47. }
  48. if (must_context_switch) {
  49. auto core_scheduler = kernel.CurrentScheduler();
  50. kernel.ExitSVCProfile();
  51. core_scheduler->RescheduleCurrentCore();
  52. kernel.EnterSVCProfile();
  53. }
  54. }
  55. u64 KScheduler::UpdateHighestPriorityThread(KThread* highest_thread) {
  56. KScopedSpinLock lk{guard};
  57. if (KThread* prev_highest_thread = state.highest_priority_thread;
  58. prev_highest_thread != highest_thread) {
  59. if (prev_highest_thread != nullptr) {
  60. IncrementScheduledCount(prev_highest_thread);
  61. prev_highest_thread->SetLastScheduledTick(system.CoreTiming().GetCPUTicks());
  62. }
  63. if (state.should_count_idle) {
  64. if (highest_thread != nullptr) {
  65. if (KProcess* process = highest_thread->GetOwnerProcess(); process != nullptr) {
  66. process->SetRunningThread(core_id, highest_thread, state.idle_count);
  67. }
  68. } else {
  69. state.idle_count++;
  70. }
  71. }
  72. state.highest_priority_thread = highest_thread;
  73. state.needs_scheduling.store(true);
  74. return (1ULL << core_id);
  75. } else {
  76. return 0;
  77. }
  78. }
  79. u64 KScheduler::UpdateHighestPriorityThreadsImpl(KernelCore& kernel) {
  80. ASSERT(kernel.GlobalSchedulerContext().IsLocked());
  81. // Clear that we need to update.
  82. ClearSchedulerUpdateNeeded(kernel);
  83. u64 cores_needing_scheduling = 0, idle_cores = 0;
  84. KThread* top_threads[Core::Hardware::NUM_CPU_CORES];
  85. auto& priority_queue = GetPriorityQueue(kernel);
  86. /// We want to go over all cores, finding the highest priority thread and determining if
  87. /// scheduling is needed for that core.
  88. for (size_t core_id = 0; core_id < Core::Hardware::NUM_CPU_CORES; core_id++) {
  89. KThread* top_thread = priority_queue.GetScheduledFront(static_cast<s32>(core_id));
  90. if (top_thread != nullptr) {
  91. // If the thread has no waiters, we need to check if the process has a thread pinned.
  92. if (top_thread->GetNumKernelWaiters() == 0) {
  93. if (KProcess* parent = top_thread->GetOwnerProcess(); parent != nullptr) {
  94. if (KThread* pinned = parent->GetPinnedThread(static_cast<s32>(core_id));
  95. pinned != nullptr && pinned != top_thread) {
  96. // We prefer our parent's pinned thread if possible. However, we also don't
  97. // want to schedule un-runnable threads.
  98. if (pinned->GetRawState() == ThreadState::Runnable) {
  99. top_thread = pinned;
  100. } else {
  101. top_thread = nullptr;
  102. }
  103. }
  104. }
  105. }
  106. } else {
  107. idle_cores |= (1ULL << core_id);
  108. }
  109. top_threads[core_id] = top_thread;
  110. cores_needing_scheduling |=
  111. kernel.Scheduler(core_id).UpdateHighestPriorityThread(top_threads[core_id]);
  112. }
  113. // Idle cores are bad. We're going to try to migrate threads to each idle core in turn.
  114. while (idle_cores != 0) {
  115. const auto core_id = static_cast<u32>(std::countr_zero(idle_cores));
  116. if (KThread* suggested = priority_queue.GetSuggestedFront(core_id); suggested != nullptr) {
  117. s32 migration_candidates[Core::Hardware::NUM_CPU_CORES];
  118. size_t num_candidates = 0;
  119. // While we have a suggested thread, try to migrate it!
  120. while (suggested != nullptr) {
  121. // Check if the suggested thread is the top thread on its core.
  122. const s32 suggested_core = suggested->GetActiveCore();
  123. if (KThread* top_thread =
  124. (suggested_core >= 0) ? top_threads[suggested_core] : nullptr;
  125. top_thread != suggested) {
  126. // Make sure we're not dealing with threads too high priority for migration.
  127. if (top_thread != nullptr &&
  128. top_thread->GetPriority() < HighestCoreMigrationAllowedPriority) {
  129. break;
  130. }
  131. // The suggested thread isn't bound to its core, so we can migrate it!
  132. suggested->SetActiveCore(core_id);
  133. priority_queue.ChangeCore(suggested_core, suggested);
  134. top_threads[core_id] = suggested;
  135. cores_needing_scheduling |=
  136. kernel.Scheduler(core_id).UpdateHighestPriorityThread(top_threads[core_id]);
  137. break;
  138. }
  139. // Note this core as a candidate for migration.
  140. ASSERT(num_candidates < Core::Hardware::NUM_CPU_CORES);
  141. migration_candidates[num_candidates++] = suggested_core;
  142. suggested = priority_queue.GetSuggestedNext(core_id, suggested);
  143. }
  144. // If suggested is nullptr, we failed to migrate a specific thread. So let's try all our
  145. // candidate cores' top threads.
  146. if (suggested == nullptr) {
  147. for (size_t i = 0; i < num_candidates; i++) {
  148. // Check if there's some other thread that can run on the candidate core.
  149. const s32 candidate_core = migration_candidates[i];
  150. suggested = top_threads[candidate_core];
  151. if (KThread* next_on_candidate_core =
  152. priority_queue.GetScheduledNext(candidate_core, suggested);
  153. next_on_candidate_core != nullptr) {
  154. // The candidate core can run some other thread! We'll migrate its current
  155. // top thread to us.
  156. top_threads[candidate_core] = next_on_candidate_core;
  157. cores_needing_scheduling |=
  158. kernel.Scheduler(candidate_core)
  159. .UpdateHighestPriorityThread(top_threads[candidate_core]);
  160. // Perform the migration.
  161. suggested->SetActiveCore(core_id);
  162. priority_queue.ChangeCore(candidate_core, suggested);
  163. top_threads[core_id] = suggested;
  164. cores_needing_scheduling |=
  165. kernel.Scheduler(core_id).UpdateHighestPriorityThread(
  166. top_threads[core_id]);
  167. break;
  168. }
  169. }
  170. }
  171. }
  172. idle_cores &= ~(1ULL << core_id);
  173. }
  174. return cores_needing_scheduling;
  175. }
  176. void KScheduler::ClearPreviousThread(KernelCore& kernel, KThread* thread) {
  177. ASSERT(kernel.GlobalSchedulerContext().IsLocked());
  178. for (size_t i = 0; i < Core::Hardware::NUM_CPU_CORES; ++i) {
  179. // Get an atomic reference to the core scheduler's previous thread.
  180. std::atomic_ref<KThread*> prev_thread(kernel.Scheduler(static_cast<s32>(i)).prev_thread);
  181. static_assert(std::atomic_ref<KThread*>::is_always_lock_free);
  182. // Atomically clear the previous thread if it's our target.
  183. KThread* compare = thread;
  184. prev_thread.compare_exchange_strong(compare, nullptr);
  185. }
  186. }
  187. void KScheduler::OnThreadStateChanged(KernelCore& kernel, KThread* thread, ThreadState old_state) {
  188. ASSERT(kernel.GlobalSchedulerContext().IsLocked());
  189. // Check if the state has changed, because if it hasn't there's nothing to do.
  190. const auto cur_state = thread->GetRawState();
  191. if (cur_state == old_state) {
  192. return;
  193. }
  194. // Update the priority queues.
  195. if (old_state == ThreadState::Runnable) {
  196. // If we were previously runnable, then we're not runnable now, and we should remove.
  197. GetPriorityQueue(kernel).Remove(thread);
  198. IncrementScheduledCount(thread);
  199. SetSchedulerUpdateNeeded(kernel);
  200. } else if (cur_state == ThreadState::Runnable) {
  201. // If we're now runnable, then we weren't previously, and we should add.
  202. GetPriorityQueue(kernel).PushBack(thread);
  203. IncrementScheduledCount(thread);
  204. SetSchedulerUpdateNeeded(kernel);
  205. }
  206. }
  207. void KScheduler::OnThreadPriorityChanged(KernelCore& kernel, KThread* thread, s32 old_priority) {
  208. ASSERT(kernel.GlobalSchedulerContext().IsLocked());
  209. // If the thread is runnable, we want to change its priority in the queue.
  210. if (thread->GetRawState() == ThreadState::Runnable) {
  211. GetPriorityQueue(kernel).ChangePriority(old_priority,
  212. thread == kernel.GetCurrentEmuThread(), thread);
  213. IncrementScheduledCount(thread);
  214. SetSchedulerUpdateNeeded(kernel);
  215. }
  216. }
  217. void KScheduler::OnThreadAffinityMaskChanged(KernelCore& kernel, KThread* thread,
  218. const KAffinityMask& old_affinity, s32 old_core) {
  219. ASSERT(kernel.GlobalSchedulerContext().IsLocked());
  220. // If the thread is runnable, we want to change its affinity in the queue.
  221. if (thread->GetRawState() == ThreadState::Runnable) {
  222. GetPriorityQueue(kernel).ChangeAffinityMask(old_core, old_affinity, thread);
  223. IncrementScheduledCount(thread);
  224. SetSchedulerUpdateNeeded(kernel);
  225. }
  226. }
  227. void KScheduler::RotateScheduledQueue(s32 cpu_core_id, s32 priority) {
  228. ASSERT(system.GlobalSchedulerContext().IsLocked());
  229. // Get a reference to the priority queue.
  230. auto& kernel = system.Kernel();
  231. auto& priority_queue = GetPriorityQueue(kernel);
  232. // Rotate the front of the queue to the end.
  233. KThread* top_thread = priority_queue.GetScheduledFront(cpu_core_id, priority);
  234. KThread* next_thread = nullptr;
  235. if (top_thread != nullptr) {
  236. next_thread = priority_queue.MoveToScheduledBack(top_thread);
  237. if (next_thread != top_thread) {
  238. IncrementScheduledCount(top_thread);
  239. IncrementScheduledCount(next_thread);
  240. }
  241. }
  242. // While we have a suggested thread, try to migrate it!
  243. {
  244. KThread* suggested = priority_queue.GetSuggestedFront(cpu_core_id, priority);
  245. while (suggested != nullptr) {
  246. // Check if the suggested thread is the top thread on its core.
  247. const s32 suggested_core = suggested->GetActiveCore();
  248. if (KThread* top_on_suggested_core =
  249. (suggested_core >= 0) ? priority_queue.GetScheduledFront(suggested_core)
  250. : nullptr;
  251. top_on_suggested_core != suggested) {
  252. // If the next thread is a new thread that has been waiting longer than our
  253. // suggestion, we prefer it to our suggestion.
  254. if (top_thread != next_thread && next_thread != nullptr &&
  255. next_thread->GetLastScheduledTick() < suggested->GetLastScheduledTick()) {
  256. suggested = nullptr;
  257. break;
  258. }
  259. // If we're allowed to do a migration, do one.
  260. // NOTE: Unlike migrations in UpdateHighestPriorityThread, this moves the suggestion
  261. // to the front of the queue.
  262. if (top_on_suggested_core == nullptr ||
  263. top_on_suggested_core->GetPriority() >= HighestCoreMigrationAllowedPriority) {
  264. suggested->SetActiveCore(cpu_core_id);
  265. priority_queue.ChangeCore(suggested_core, suggested, true);
  266. IncrementScheduledCount(suggested);
  267. break;
  268. }
  269. }
  270. // Get the next suggestion.
  271. suggested = priority_queue.GetSamePriorityNext(cpu_core_id, suggested);
  272. }
  273. }
  274. // Now that we might have migrated a thread with the same priority, check if we can do better.
  275. {
  276. KThread* best_thread = priority_queue.GetScheduledFront(cpu_core_id);
  277. if (best_thread == GetCurrentThreadPointer(kernel)) {
  278. best_thread = priority_queue.GetScheduledNext(cpu_core_id, best_thread);
  279. }
  280. // If the best thread we can choose has a priority the same or worse than ours, try to
  281. // migrate a higher priority thread.
  282. if (best_thread != nullptr && best_thread->GetPriority() >= priority) {
  283. KThread* suggested = priority_queue.GetSuggestedFront(cpu_core_id);
  284. while (suggested != nullptr) {
  285. // If the suggestion's priority is the same as ours, don't bother.
  286. if (suggested->GetPriority() >= best_thread->GetPriority()) {
  287. break;
  288. }
  289. // Check if the suggested thread is the top thread on its core.
  290. const s32 suggested_core = suggested->GetActiveCore();
  291. if (KThread* top_on_suggested_core =
  292. (suggested_core >= 0) ? priority_queue.GetScheduledFront(suggested_core)
  293. : nullptr;
  294. top_on_suggested_core != suggested) {
  295. // If we're allowed to do a migration, do one.
  296. // NOTE: Unlike migrations in UpdateHighestPriorityThread, this moves the
  297. // suggestion to the front of the queue.
  298. if (top_on_suggested_core == nullptr ||
  299. top_on_suggested_core->GetPriority() >=
  300. HighestCoreMigrationAllowedPriority) {
  301. suggested->SetActiveCore(cpu_core_id);
  302. priority_queue.ChangeCore(suggested_core, suggested, true);
  303. IncrementScheduledCount(suggested);
  304. break;
  305. }
  306. }
  307. // Get the next suggestion.
  308. suggested = priority_queue.GetSuggestedNext(cpu_core_id, suggested);
  309. }
  310. }
  311. }
  312. // After a rotation, we need a scheduler update.
  313. SetSchedulerUpdateNeeded(kernel);
  314. }
  315. bool KScheduler::CanSchedule(KernelCore& kernel) {
  316. return kernel.GetCurrentEmuThread()->GetDisableDispatchCount() <= 1;
  317. }
  318. bool KScheduler::IsSchedulerUpdateNeeded(const KernelCore& kernel) {
  319. return kernel.GlobalSchedulerContext().scheduler_update_needed.load(std::memory_order_acquire);
  320. }
  321. void KScheduler::SetSchedulerUpdateNeeded(KernelCore& kernel) {
  322. kernel.GlobalSchedulerContext().scheduler_update_needed.store(true, std::memory_order_release);
  323. }
  324. void KScheduler::ClearSchedulerUpdateNeeded(KernelCore& kernel) {
  325. kernel.GlobalSchedulerContext().scheduler_update_needed.store(false, std::memory_order_release);
  326. }
  327. void KScheduler::DisableScheduling(KernelCore& kernel) {
  328. // If we are shutting down the kernel, none of this is relevant anymore.
  329. if (kernel.IsShuttingDown()) {
  330. return;
  331. }
  332. ASSERT(GetCurrentThreadPointer(kernel)->GetDisableDispatchCount() >= 0);
  333. GetCurrentThreadPointer(kernel)->DisableDispatch();
  334. }
  335. void KScheduler::EnableScheduling(KernelCore& kernel, u64 cores_needing_scheduling) {
  336. // If we are shutting down the kernel, none of this is relevant anymore.
  337. if (kernel.IsShuttingDown()) {
  338. return;
  339. }
  340. auto* current_thread = GetCurrentThreadPointer(kernel);
  341. ASSERT(current_thread->GetDisableDispatchCount() >= 1);
  342. if (current_thread->GetDisableDispatchCount() > 1) {
  343. current_thread->EnableDispatch();
  344. } else {
  345. RescheduleCores(kernel, cores_needing_scheduling);
  346. }
  347. // Special case to ensure dummy threads that are waiting block.
  348. current_thread->IfDummyThreadTryWait();
  349. }
  350. u64 KScheduler::UpdateHighestPriorityThreads(KernelCore& kernel) {
  351. if (IsSchedulerUpdateNeeded(kernel)) {
  352. return UpdateHighestPriorityThreadsImpl(kernel);
  353. } else {
  354. return 0;
  355. }
  356. }
  357. KSchedulerPriorityQueue& KScheduler::GetPriorityQueue(KernelCore& kernel) {
  358. return kernel.GlobalSchedulerContext().priority_queue;
  359. }
  360. void KScheduler::YieldWithoutCoreMigration(KernelCore& kernel) {
  361. // Validate preconditions.
  362. ASSERT(CanSchedule(kernel));
  363. ASSERT(kernel.CurrentProcess() != nullptr);
  364. // Get the current thread and process.
  365. KThread& cur_thread = GetCurrentThread(kernel);
  366. KProcess& cur_process = *kernel.CurrentProcess();
  367. // If the thread's yield count matches, there's nothing for us to do.
  368. if (cur_thread.GetYieldScheduleCount() == cur_process.GetScheduledCount()) {
  369. return;
  370. }
  371. // Get a reference to the priority queue.
  372. auto& priority_queue = GetPriorityQueue(kernel);
  373. // Perform the yield.
  374. {
  375. KScopedSchedulerLock lock(kernel);
  376. const auto cur_state = cur_thread.GetRawState();
  377. if (cur_state == ThreadState::Runnable) {
  378. // Put the current thread at the back of the queue.
  379. KThread* next_thread = priority_queue.MoveToScheduledBack(std::addressof(cur_thread));
  380. IncrementScheduledCount(std::addressof(cur_thread));
  381. // If the next thread is different, we have an update to perform.
  382. if (next_thread != std::addressof(cur_thread)) {
  383. SetSchedulerUpdateNeeded(kernel);
  384. } else {
  385. // Otherwise, set the thread's yield count so that we won't waste work until the
  386. // process is scheduled again.
  387. cur_thread.SetYieldScheduleCount(cur_process.GetScheduledCount());
  388. }
  389. }
  390. }
  391. }
  392. void KScheduler::YieldWithCoreMigration(KernelCore& kernel) {
  393. // Validate preconditions.
  394. ASSERT(CanSchedule(kernel));
  395. ASSERT(kernel.CurrentProcess() != nullptr);
  396. // Get the current thread and process.
  397. KThread& cur_thread = GetCurrentThread(kernel);
  398. KProcess& cur_process = *kernel.CurrentProcess();
  399. // If the thread's yield count matches, there's nothing for us to do.
  400. if (cur_thread.GetYieldScheduleCount() == cur_process.GetScheduledCount()) {
  401. return;
  402. }
  403. // Get a reference to the priority queue.
  404. auto& priority_queue = GetPriorityQueue(kernel);
  405. // Perform the yield.
  406. {
  407. KScopedSchedulerLock lock(kernel);
  408. const auto cur_state = cur_thread.GetRawState();
  409. if (cur_state == ThreadState::Runnable) {
  410. // Get the current active core.
  411. const s32 core_id = cur_thread.GetActiveCore();
  412. // Put the current thread at the back of the queue.
  413. KThread* next_thread = priority_queue.MoveToScheduledBack(std::addressof(cur_thread));
  414. IncrementScheduledCount(std::addressof(cur_thread));
  415. // While we have a suggested thread, try to migrate it!
  416. bool recheck = false;
  417. KThread* suggested = priority_queue.GetSuggestedFront(core_id);
  418. while (suggested != nullptr) {
  419. // Check if the suggested thread is the thread running on its core.
  420. const s32 suggested_core = suggested->GetActiveCore();
  421. if (KThread* running_on_suggested_core =
  422. (suggested_core >= 0)
  423. ? kernel.Scheduler(suggested_core).state.highest_priority_thread
  424. : nullptr;
  425. running_on_suggested_core != suggested) {
  426. // If the current thread's priority is higher than our suggestion's we prefer
  427. // the next thread to the suggestion. We also prefer the next thread when the
  428. // current thread's priority is equal to the suggestions, but the next thread
  429. // has been waiting longer.
  430. if ((suggested->GetPriority() > cur_thread.GetPriority()) ||
  431. (suggested->GetPriority() == cur_thread.GetPriority() &&
  432. next_thread != std::addressof(cur_thread) &&
  433. next_thread->GetLastScheduledTick() < suggested->GetLastScheduledTick())) {
  434. suggested = nullptr;
  435. break;
  436. }
  437. // If we're allowed to do a migration, do one.
  438. // NOTE: Unlike migrations in UpdateHighestPriorityThread, this moves the
  439. // suggestion to the front of the queue.
  440. if (running_on_suggested_core == nullptr ||
  441. running_on_suggested_core->GetPriority() >=
  442. HighestCoreMigrationAllowedPriority) {
  443. suggested->SetActiveCore(core_id);
  444. priority_queue.ChangeCore(suggested_core, suggested, true);
  445. IncrementScheduledCount(suggested);
  446. break;
  447. } else {
  448. // We couldn't perform a migration, but we should check again on a future
  449. // yield.
  450. recheck = true;
  451. }
  452. }
  453. // Get the next suggestion.
  454. suggested = priority_queue.GetSuggestedNext(core_id, suggested);
  455. }
  456. // If we still have a suggestion or the next thread is different, we have an update to
  457. // perform.
  458. if (suggested != nullptr || next_thread != std::addressof(cur_thread)) {
  459. SetSchedulerUpdateNeeded(kernel);
  460. } else if (!recheck) {
  461. // Otherwise if we don't need to re-check, set the thread's yield count so that we
  462. // won't waste work until the process is scheduled again.
  463. cur_thread.SetYieldScheduleCount(cur_process.GetScheduledCount());
  464. }
  465. }
  466. }
  467. }
  468. void KScheduler::YieldToAnyThread(KernelCore& kernel) {
  469. // Validate preconditions.
  470. ASSERT(CanSchedule(kernel));
  471. ASSERT(kernel.CurrentProcess() != nullptr);
  472. // Get the current thread and process.
  473. KThread& cur_thread = GetCurrentThread(kernel);
  474. KProcess& cur_process = *kernel.CurrentProcess();
  475. // If the thread's yield count matches, there's nothing for us to do.
  476. if (cur_thread.GetYieldScheduleCount() == cur_process.GetScheduledCount()) {
  477. return;
  478. }
  479. // Get a reference to the priority queue.
  480. auto& priority_queue = GetPriorityQueue(kernel);
  481. // Perform the yield.
  482. {
  483. KScopedSchedulerLock lock(kernel);
  484. const auto cur_state = cur_thread.GetRawState();
  485. if (cur_state == ThreadState::Runnable) {
  486. // Get the current active core.
  487. const s32 core_id = cur_thread.GetActiveCore();
  488. // Migrate the current thread to core -1.
  489. cur_thread.SetActiveCore(-1);
  490. priority_queue.ChangeCore(core_id, std::addressof(cur_thread));
  491. IncrementScheduledCount(std::addressof(cur_thread));
  492. // If there's nothing scheduled, we can try to perform a migration.
  493. if (priority_queue.GetScheduledFront(core_id) == nullptr) {
  494. // While we have a suggested thread, try to migrate it!
  495. KThread* suggested = priority_queue.GetSuggestedFront(core_id);
  496. while (suggested != nullptr) {
  497. // Check if the suggested thread is the top thread on its core.
  498. const s32 suggested_core = suggested->GetActiveCore();
  499. if (KThread* top_on_suggested_core =
  500. (suggested_core >= 0) ? priority_queue.GetScheduledFront(suggested_core)
  501. : nullptr;
  502. top_on_suggested_core != suggested) {
  503. // If we're allowed to do a migration, do one.
  504. if (top_on_suggested_core == nullptr ||
  505. top_on_suggested_core->GetPriority() >=
  506. HighestCoreMigrationAllowedPriority) {
  507. suggested->SetActiveCore(core_id);
  508. priority_queue.ChangeCore(suggested_core, suggested);
  509. IncrementScheduledCount(suggested);
  510. }
  511. // Regardless of whether we migrated, we had a candidate, so we're done.
  512. break;
  513. }
  514. // Get the next suggestion.
  515. suggested = priority_queue.GetSuggestedNext(core_id, suggested);
  516. }
  517. // If the suggestion is different from the current thread, we need to perform an
  518. // update.
  519. if (suggested != std::addressof(cur_thread)) {
  520. SetSchedulerUpdateNeeded(kernel);
  521. } else {
  522. // Otherwise, set the thread's yield count so that we won't waste work until the
  523. // process is scheduled again.
  524. cur_thread.SetYieldScheduleCount(cur_process.GetScheduledCount());
  525. }
  526. } else {
  527. // Otherwise, we have an update to perform.
  528. SetSchedulerUpdateNeeded(kernel);
  529. }
  530. }
  531. }
  532. }
  533. KScheduler::KScheduler(Core::System& system_, s32 core_id_) : system{system_}, core_id{core_id_} {
  534. switch_fiber = std::make_shared<Common::Fiber>(OnSwitch, this);
  535. state.needs_scheduling.store(true);
  536. state.interrupt_task_thread_runnable = false;
  537. state.should_count_idle = false;
  538. state.idle_count = 0;
  539. state.idle_thread_stack = nullptr;
  540. state.highest_priority_thread = nullptr;
  541. }
  542. void KScheduler::Finalize() {
  543. if (idle_thread) {
  544. idle_thread->Close();
  545. idle_thread = nullptr;
  546. }
  547. }
  548. KScheduler::~KScheduler() {
  549. ASSERT(!idle_thread);
  550. }
  551. KThread* KScheduler::GetSchedulerCurrentThread() const {
  552. if (auto result = current_thread.load(); result) {
  553. return result;
  554. }
  555. return idle_thread;
  556. }
  557. u64 KScheduler::GetLastContextSwitchTicks() const {
  558. return last_context_switch_time;
  559. }
  560. void KScheduler::RescheduleCurrentCore() {
  561. ASSERT(GetCurrentThread(system.Kernel()).GetDisableDispatchCount() == 1);
  562. auto& phys_core = system.Kernel().PhysicalCore(core_id);
  563. if (phys_core.IsInterrupted()) {
  564. phys_core.ClearInterrupt();
  565. }
  566. guard.Lock();
  567. if (state.needs_scheduling.load()) {
  568. Schedule();
  569. } else {
  570. GetCurrentThread(system.Kernel()).EnableDispatch();
  571. guard.Unlock();
  572. }
  573. }
  574. void KScheduler::OnThreadStart() {
  575. SwitchContextStep2();
  576. }
  577. void KScheduler::Unload(KThread* thread) {
  578. ASSERT(thread);
  579. LOG_TRACE(Kernel, "core {}, unload thread {}", core_id, thread ? thread->GetName() : "nullptr");
  580. if (thread->IsCallingSvc()) {
  581. thread->ClearIsCallingSvc();
  582. }
  583. auto& physical_core = system.Kernel().PhysicalCore(core_id);
  584. if (!physical_core.IsInitialized()) {
  585. return;
  586. }
  587. Core::ARM_Interface& cpu_core = physical_core.ArmInterface();
  588. cpu_core.SaveContext(thread->GetContext32());
  589. cpu_core.SaveContext(thread->GetContext64());
  590. // Save the TPIDR_EL0 system register in case it was modified.
  591. thread->SetTPIDR_EL0(cpu_core.GetTPIDR_EL0());
  592. cpu_core.ClearExclusiveState();
  593. if (!thread->IsTerminationRequested() && thread->GetActiveCore() == core_id) {
  594. prev_thread = thread;
  595. } else {
  596. prev_thread = nullptr;
  597. }
  598. thread->context_guard.unlock();
  599. }
  600. void KScheduler::Reload(KThread* thread) {
  601. LOG_TRACE(Kernel, "core {}, reload thread {}", core_id, thread->GetName());
  602. Core::ARM_Interface& cpu_core = system.ArmInterface(core_id);
  603. cpu_core.LoadContext(thread->GetContext32());
  604. cpu_core.LoadContext(thread->GetContext64());
  605. cpu_core.LoadWatchpointArray(thread->GetOwnerProcess()->GetWatchpoints());
  606. cpu_core.SetTlsAddress(thread->GetTLSAddress());
  607. cpu_core.SetTPIDR_EL0(thread->GetTPIDR_EL0());
  608. cpu_core.ClearExclusiveState();
  609. }
  610. void KScheduler::SwitchContextStep2() {
  611. // Load context of new thread
  612. Reload(GetCurrentThreadPointer(system.Kernel()));
  613. RescheduleCurrentCore();
  614. }
  615. void KScheduler::Schedule() {
  616. ASSERT(GetCurrentThread(system.Kernel()).GetDisableDispatchCount() == 1);
  617. this->ScheduleImpl();
  618. }
  619. void KScheduler::ScheduleImpl() {
  620. KThread* previous_thread = GetCurrentThreadPointer(system.Kernel());
  621. KThread* next_thread = state.highest_priority_thread;
  622. state.needs_scheduling.store(false);
  623. // We never want to schedule a null thread, so use the idle thread if we don't have a next.
  624. if (next_thread == nullptr) {
  625. next_thread = idle_thread;
  626. }
  627. if (next_thread->GetCurrentCore() != core_id) {
  628. next_thread->SetCurrentCore(core_id);
  629. }
  630. // We never want to schedule a dummy thread, as these are only used by host threads for locking.
  631. if (next_thread->GetThreadType() == ThreadType::Dummy) {
  632. ASSERT_MSG(false, "Dummy threads should never be scheduled!");
  633. next_thread = idle_thread;
  634. }
  635. // If we're not actually switching thread, there's nothing to do.
  636. if (next_thread == current_thread.load()) {
  637. previous_thread->EnableDispatch();
  638. guard.Unlock();
  639. return;
  640. }
  641. // Update the CPU time tracking variables.
  642. KProcess* const previous_process = system.Kernel().CurrentProcess();
  643. UpdateLastContextSwitchTime(previous_thread, previous_process);
  644. // Save context for previous thread
  645. Unload(previous_thread);
  646. std::shared_ptr<Common::Fiber>* old_context;
  647. old_context = &previous_thread->GetHostContext();
  648. // Set the new thread.
  649. SetCurrentThread(system.Kernel(), next_thread);
  650. current_thread.store(next_thread);
  651. guard.Unlock();
  652. Common::Fiber::YieldTo(*old_context, *switch_fiber);
  653. /// When a thread wakes up, the scheduler may have changed to other in another core.
  654. auto& next_scheduler = *system.Kernel().CurrentScheduler();
  655. next_scheduler.SwitchContextStep2();
  656. }
  657. void KScheduler::OnSwitch(void* this_scheduler) {
  658. KScheduler* sched = static_cast<KScheduler*>(this_scheduler);
  659. sched->SwitchToCurrent();
  660. }
  661. void KScheduler::SwitchToCurrent() {
  662. while (true) {
  663. {
  664. KScopedSpinLock lk{guard};
  665. current_thread.store(state.highest_priority_thread);
  666. state.needs_scheduling.store(false);
  667. }
  668. const auto is_switch_pending = [this] {
  669. KScopedSpinLock lk{guard};
  670. return state.needs_scheduling.load();
  671. };
  672. do {
  673. auto next_thread = current_thread.load();
  674. if (next_thread != nullptr) {
  675. const auto locked = next_thread->context_guard.try_lock();
  676. if (state.needs_scheduling.load()) {
  677. next_thread->context_guard.unlock();
  678. break;
  679. }
  680. if (next_thread->GetActiveCore() != core_id) {
  681. next_thread->context_guard.unlock();
  682. break;
  683. }
  684. if (!locked) {
  685. continue;
  686. }
  687. }
  688. auto thread = next_thread ? next_thread : idle_thread;
  689. SetCurrentThread(system.Kernel(), thread);
  690. Common::Fiber::YieldTo(switch_fiber, *thread->GetHostContext());
  691. } while (!is_switch_pending());
  692. }
  693. }
  694. void KScheduler::UpdateLastContextSwitchTime(KThread* thread, KProcess* process) {
  695. const u64 prev_switch_ticks = last_context_switch_time;
  696. const u64 most_recent_switch_ticks = system.CoreTiming().GetCPUTicks();
  697. const u64 update_ticks = most_recent_switch_ticks - prev_switch_ticks;
  698. if (thread != nullptr) {
  699. thread->AddCpuTime(core_id, update_ticks);
  700. }
  701. if (process != nullptr) {
  702. process->UpdateCPUTimeTicks(update_ticks);
  703. }
  704. last_context_switch_time = most_recent_switch_ticks;
  705. }
  706. void KScheduler::Initialize() {
  707. idle_thread = KThread::Create(system.Kernel());
  708. ASSERT(KThread::InitializeIdleThread(system, idle_thread, core_id).IsSuccess());
  709. idle_thread->SetName(fmt::format("IdleThread:{}", core_id));
  710. idle_thread->EnableDispatch();
  711. }
  712. KScopedSchedulerLock::KScopedSchedulerLock(KernelCore& kernel)
  713. : KScopedLock(kernel.GlobalSchedulerContext().SchedulerLock()) {}
  714. KScopedSchedulerLock::~KScopedSchedulerLock() = default;
  715. } // namespace Kernel