k_scheduler.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821
  1. // Copyright 2020 yuzu Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. // This file references various implementation details from Atmosphere, an open-source firmware for
  5. // the Nintendo Switch. Copyright 2018-2020 Atmosphere-NX.
  6. #include <bit>
  7. #include "common/assert.h"
  8. #include "common/bit_util.h"
  9. #include "common/fiber.h"
  10. #include "common/logging/log.h"
  11. #include "core/arm/arm_interface.h"
  12. #include "core/core.h"
  13. #include "core/core_timing.h"
  14. #include "core/cpu_manager.h"
  15. #include "core/hle/kernel/k_process.h"
  16. #include "core/hle/kernel/k_scheduler.h"
  17. #include "core/hle/kernel/k_scoped_scheduler_lock_and_sleep.h"
  18. #include "core/hle/kernel/k_thread.h"
  19. #include "core/hle/kernel/kernel.h"
  20. #include "core/hle/kernel/physical_core.h"
  21. #include "core/hle/kernel/time_manager.h"
  22. namespace Kernel {
  23. static void IncrementScheduledCount(Kernel::KThread* thread) {
  24. if (auto process = thread->GetOwnerProcess(); process) {
  25. process->IncrementScheduledCount();
  26. }
  27. }
  28. void KScheduler::RescheduleCores(KernelCore& kernel, u64 cores_pending_reschedule) {
  29. auto scheduler = kernel.CurrentScheduler();
  30. u32 current_core{0xF};
  31. bool must_context_switch{};
  32. if (scheduler) {
  33. current_core = scheduler->core_id;
  34. // TODO(bunnei): Should be set to true when we deprecate single core
  35. must_context_switch = !kernel.IsPhantomModeForSingleCore();
  36. }
  37. while (cores_pending_reschedule != 0) {
  38. const auto core = static_cast<u32>(std::countr_zero(cores_pending_reschedule));
  39. ASSERT(core < Core::Hardware::NUM_CPU_CORES);
  40. if (!must_context_switch || core != current_core) {
  41. auto& phys_core = kernel.PhysicalCore(core);
  42. phys_core.Interrupt();
  43. } else {
  44. must_context_switch = true;
  45. }
  46. cores_pending_reschedule &= ~(1ULL << core);
  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(
  212. old_priority, thread == kernel.CurrentScheduler()->GetCurrentThread(), 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 == GetCurrentThread()) {
  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.CurrentScheduler()->GetCurrentThread()->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 (auto* scheduler = kernel.CurrentScheduler(); scheduler) {
  329. ASSERT(scheduler->GetCurrentThread()->GetDisableDispatchCount() >= 0);
  330. scheduler->GetCurrentThread()->DisableDispatch();
  331. }
  332. }
  333. void KScheduler::EnableScheduling(KernelCore& kernel, u64 cores_needing_scheduling) {
  334. if (auto* scheduler = kernel.CurrentScheduler(); scheduler) {
  335. ASSERT(scheduler->GetCurrentThread()->GetDisableDispatchCount() >= 1);
  336. if (scheduler->GetCurrentThread()->GetDisableDispatchCount() >= 1) {
  337. scheduler->GetCurrentThread()->EnableDispatch();
  338. }
  339. }
  340. RescheduleCores(kernel, cores_needing_scheduling);
  341. }
  342. u64 KScheduler::UpdateHighestPriorityThreads(KernelCore& kernel) {
  343. if (IsSchedulerUpdateNeeded(kernel)) {
  344. return UpdateHighestPriorityThreadsImpl(kernel);
  345. } else {
  346. return 0;
  347. }
  348. }
  349. KSchedulerPriorityQueue& KScheduler::GetPriorityQueue(KernelCore& kernel) {
  350. return kernel.GlobalSchedulerContext().priority_queue;
  351. }
  352. void KScheduler::YieldWithoutCoreMigration(KernelCore& kernel) {
  353. // Validate preconditions.
  354. ASSERT(CanSchedule(kernel));
  355. ASSERT(kernel.CurrentProcess() != nullptr);
  356. // Get the current thread and process.
  357. KThread& cur_thread = Kernel::GetCurrentThread(kernel);
  358. KProcess& cur_process = *kernel.CurrentProcess();
  359. // If the thread's yield count matches, there's nothing for us to do.
  360. if (cur_thread.GetYieldScheduleCount() == cur_process.GetScheduledCount()) {
  361. return;
  362. }
  363. // Get a reference to the priority queue.
  364. auto& priority_queue = GetPriorityQueue(kernel);
  365. // Perform the yield.
  366. {
  367. KScopedSchedulerLock lock(kernel);
  368. const auto cur_state = cur_thread.GetRawState();
  369. if (cur_state == ThreadState::Runnable) {
  370. // Put the current thread at the back of the queue.
  371. KThread* next_thread = priority_queue.MoveToScheduledBack(std::addressof(cur_thread));
  372. IncrementScheduledCount(std::addressof(cur_thread));
  373. // If the next thread is different, we have an update to perform.
  374. if (next_thread != std::addressof(cur_thread)) {
  375. SetSchedulerUpdateNeeded(kernel);
  376. } else {
  377. // Otherwise, set the thread's yield count so that we won't waste work until the
  378. // process is scheduled again.
  379. cur_thread.SetYieldScheduleCount(cur_process.GetScheduledCount());
  380. }
  381. }
  382. }
  383. }
  384. void KScheduler::YieldWithCoreMigration(KernelCore& kernel) {
  385. // Validate preconditions.
  386. ASSERT(CanSchedule(kernel));
  387. ASSERT(kernel.CurrentProcess() != nullptr);
  388. // Get the current thread and process.
  389. KThread& cur_thread = Kernel::GetCurrentThread(kernel);
  390. KProcess& cur_process = *kernel.CurrentProcess();
  391. // If the thread's yield count matches, there's nothing for us to do.
  392. if (cur_thread.GetYieldScheduleCount() == cur_process.GetScheduledCount()) {
  393. return;
  394. }
  395. // Get a reference to the priority queue.
  396. auto& priority_queue = GetPriorityQueue(kernel);
  397. // Perform the yield.
  398. {
  399. KScopedSchedulerLock lock(kernel);
  400. const auto cur_state = cur_thread.GetRawState();
  401. if (cur_state == ThreadState::Runnable) {
  402. // Get the current active core.
  403. const s32 core_id = cur_thread.GetActiveCore();
  404. // Put the current thread at the back of the queue.
  405. KThread* next_thread = priority_queue.MoveToScheduledBack(std::addressof(cur_thread));
  406. IncrementScheduledCount(std::addressof(cur_thread));
  407. // While we have a suggested thread, try to migrate it!
  408. bool recheck = false;
  409. KThread* suggested = priority_queue.GetSuggestedFront(core_id);
  410. while (suggested != nullptr) {
  411. // Check if the suggested thread is the thread running on its core.
  412. const s32 suggested_core = suggested->GetActiveCore();
  413. if (KThread* running_on_suggested_core =
  414. (suggested_core >= 0)
  415. ? kernel.Scheduler(suggested_core).state.highest_priority_thread
  416. : nullptr;
  417. running_on_suggested_core != suggested) {
  418. // If the current thread's priority is higher than our suggestion's we prefer
  419. // the next thread to the suggestion. We also prefer the next thread when the
  420. // current thread's priority is equal to the suggestions, but the next thread
  421. // has been waiting longer.
  422. if ((suggested->GetPriority() > cur_thread.GetPriority()) ||
  423. (suggested->GetPriority() == cur_thread.GetPriority() &&
  424. next_thread != std::addressof(cur_thread) &&
  425. next_thread->GetLastScheduledTick() < suggested->GetLastScheduledTick())) {
  426. suggested = nullptr;
  427. break;
  428. }
  429. // If we're allowed to do a migration, do one.
  430. // NOTE: Unlike migrations in UpdateHighestPriorityThread, this moves the
  431. // suggestion to the front of the queue.
  432. if (running_on_suggested_core == nullptr ||
  433. running_on_suggested_core->GetPriority() >=
  434. HighestCoreMigrationAllowedPriority) {
  435. suggested->SetActiveCore(core_id);
  436. priority_queue.ChangeCore(suggested_core, suggested, true);
  437. IncrementScheduledCount(suggested);
  438. break;
  439. } else {
  440. // We couldn't perform a migration, but we should check again on a future
  441. // yield.
  442. recheck = true;
  443. }
  444. }
  445. // Get the next suggestion.
  446. suggested = priority_queue.GetSuggestedNext(core_id, suggested);
  447. }
  448. // If we still have a suggestion or the next thread is different, we have an update to
  449. // perform.
  450. if (suggested != nullptr || next_thread != std::addressof(cur_thread)) {
  451. SetSchedulerUpdateNeeded(kernel);
  452. } else if (!recheck) {
  453. // Otherwise if we don't need to re-check, set the thread's yield count so that we
  454. // won't waste work until the process is scheduled again.
  455. cur_thread.SetYieldScheduleCount(cur_process.GetScheduledCount());
  456. }
  457. }
  458. }
  459. }
  460. void KScheduler::YieldToAnyThread(KernelCore& kernel) {
  461. // Validate preconditions.
  462. ASSERT(CanSchedule(kernel));
  463. ASSERT(kernel.CurrentProcess() != nullptr);
  464. // Get the current thread and process.
  465. KThread& cur_thread = Kernel::GetCurrentThread(kernel);
  466. KProcess& cur_process = *kernel.CurrentProcess();
  467. // If the thread's yield count matches, there's nothing for us to do.
  468. if (cur_thread.GetYieldScheduleCount() == cur_process.GetScheduledCount()) {
  469. return;
  470. }
  471. // Get a reference to the priority queue.
  472. auto& priority_queue = GetPriorityQueue(kernel);
  473. // Perform the yield.
  474. {
  475. KScopedSchedulerLock lock(kernel);
  476. const auto cur_state = cur_thread.GetRawState();
  477. if (cur_state == ThreadState::Runnable) {
  478. // Get the current active core.
  479. const s32 core_id = cur_thread.GetActiveCore();
  480. // Migrate the current thread to core -1.
  481. cur_thread.SetActiveCore(-1);
  482. priority_queue.ChangeCore(core_id, std::addressof(cur_thread));
  483. IncrementScheduledCount(std::addressof(cur_thread));
  484. // If there's nothing scheduled, we can try to perform a migration.
  485. if (priority_queue.GetScheduledFront(core_id) == nullptr) {
  486. // While we have a suggested thread, try to migrate it!
  487. KThread* suggested = priority_queue.GetSuggestedFront(core_id);
  488. while (suggested != nullptr) {
  489. // Check if the suggested thread is the top thread on its core.
  490. const s32 suggested_core = suggested->GetActiveCore();
  491. if (KThread* top_on_suggested_core =
  492. (suggested_core >= 0) ? priority_queue.GetScheduledFront(suggested_core)
  493. : nullptr;
  494. top_on_suggested_core != suggested) {
  495. // If we're allowed to do a migration, do one.
  496. if (top_on_suggested_core == nullptr ||
  497. top_on_suggested_core->GetPriority() >=
  498. HighestCoreMigrationAllowedPriority) {
  499. suggested->SetActiveCore(core_id);
  500. priority_queue.ChangeCore(suggested_core, suggested);
  501. IncrementScheduledCount(suggested);
  502. }
  503. // Regardless of whether we migrated, we had a candidate, so we're done.
  504. break;
  505. }
  506. // Get the next suggestion.
  507. suggested = priority_queue.GetSuggestedNext(core_id, suggested);
  508. }
  509. // If the suggestion is different from the current thread, we need to perform an
  510. // update.
  511. if (suggested != std::addressof(cur_thread)) {
  512. SetSchedulerUpdateNeeded(kernel);
  513. } else {
  514. // Otherwise, set the thread's yield count so that we won't waste work until the
  515. // process is scheduled again.
  516. cur_thread.SetYieldScheduleCount(cur_process.GetScheduledCount());
  517. }
  518. } else {
  519. // Otherwise, we have an update to perform.
  520. SetSchedulerUpdateNeeded(kernel);
  521. }
  522. }
  523. }
  524. }
  525. KScheduler::KScheduler(Core::System& system_, s32 core_id_) : system{system_}, core_id{core_id_} {
  526. switch_fiber = std::make_shared<Common::Fiber>(OnSwitch, this);
  527. state.needs_scheduling.store(true);
  528. state.interrupt_task_thread_runnable = false;
  529. state.should_count_idle = false;
  530. state.idle_count = 0;
  531. state.idle_thread_stack = nullptr;
  532. state.highest_priority_thread = nullptr;
  533. }
  534. void KScheduler::Finalize() {
  535. if (idle_thread) {
  536. idle_thread->Close();
  537. idle_thread = nullptr;
  538. }
  539. }
  540. KScheduler::~KScheduler() {
  541. ASSERT(!idle_thread);
  542. }
  543. KThread* KScheduler::GetCurrentThread() const {
  544. if (auto result = current_thread.load(); result) {
  545. return result;
  546. }
  547. return idle_thread;
  548. }
  549. u64 KScheduler::GetLastContextSwitchTicks() const {
  550. return last_context_switch_time;
  551. }
  552. void KScheduler::RescheduleCurrentCore() {
  553. ASSERT(GetCurrentThread()->GetDisableDispatchCount() == 1);
  554. auto& phys_core = system.Kernel().PhysicalCore(core_id);
  555. if (phys_core.IsInterrupted()) {
  556. phys_core.ClearInterrupt();
  557. }
  558. guard.Lock();
  559. if (state.needs_scheduling.load()) {
  560. Schedule();
  561. } else {
  562. GetCurrentThread()->EnableDispatch();
  563. guard.Unlock();
  564. }
  565. }
  566. void KScheduler::OnThreadStart() {
  567. SwitchContextStep2();
  568. }
  569. void KScheduler::Unload(KThread* thread) {
  570. ASSERT(thread);
  571. if (!thread) {
  572. return;
  573. }
  574. LOG_TRACE(Kernel, "core {}, unload thread {}", core_id, thread ? thread->GetName() : "nullptr");
  575. if (thread->IsCallingSvc()) {
  576. thread->ClearIsCallingSvc();
  577. }
  578. auto& physical_core = system.Kernel().PhysicalCore(core_id);
  579. if (!physical_core.IsInitialized()) {
  580. return;
  581. }
  582. Core::ARM_Interface& cpu_core = physical_core.ArmInterface();
  583. cpu_core.SaveContext(thread->GetContext32());
  584. cpu_core.SaveContext(thread->GetContext64());
  585. // Save the TPIDR_EL0 system register in case it was modified.
  586. thread->SetTPIDR_EL0(cpu_core.GetTPIDR_EL0());
  587. cpu_core.ClearExclusiveState();
  588. if (!thread->IsTerminationRequested() && thread->GetActiveCore() == core_id) {
  589. prev_thread = thread;
  590. } else {
  591. prev_thread = nullptr;
  592. }
  593. thread->context_guard.Unlock();
  594. }
  595. void KScheduler::Reload(KThread* thread) {
  596. LOG_TRACE(Kernel, "core {}, reload thread {}", core_id, thread ? thread->GetName() : "nullptr");
  597. if (thread) {
  598. ASSERT_MSG(thread->GetState() == ThreadState::Runnable, "Thread must be runnable.");
  599. Core::ARM_Interface& cpu_core = system.ArmInterface(core_id);
  600. cpu_core.LoadContext(thread->GetContext32());
  601. cpu_core.LoadContext(thread->GetContext64());
  602. cpu_core.SetTlsAddress(thread->GetTLSAddress());
  603. cpu_core.SetTPIDR_EL0(thread->GetTPIDR_EL0());
  604. cpu_core.ClearExclusiveState();
  605. }
  606. }
  607. void KScheduler::SwitchContextStep2() {
  608. // Load context of new thread
  609. Reload(current_thread.load());
  610. RescheduleCurrentCore();
  611. }
  612. void KScheduler::ScheduleImpl() {
  613. KThread* previous_thread = GetCurrentThread();
  614. KThread* next_thread = state.highest_priority_thread;
  615. state.needs_scheduling = false;
  616. // We never want to schedule a null thread, so use the idle thread if we don't have a next.
  617. if (next_thread == nullptr) {
  618. next_thread = idle_thread;
  619. }
  620. // If we're not actually switching thread, there's nothing to do.
  621. if (next_thread == current_thread.load()) {
  622. previous_thread->EnableDispatch();
  623. guard.Unlock();
  624. return;
  625. }
  626. if (next_thread->GetCurrentCore() != core_id) {
  627. next_thread->SetCurrentCore(core_id);
  628. }
  629. current_thread.store(next_thread);
  630. KProcess* const previous_process = system.Kernel().CurrentProcess();
  631. UpdateLastContextSwitchTime(previous_thread, previous_process);
  632. // Save context for previous thread
  633. Unload(previous_thread);
  634. std::shared_ptr<Common::Fiber>* old_context;
  635. old_context = &previous_thread->GetHostContext();
  636. guard.Unlock();
  637. Common::Fiber::YieldTo(*old_context, *switch_fiber);
  638. /// When a thread wakes up, the scheduler may have changed to other in another core.
  639. auto& next_scheduler = *system.Kernel().CurrentScheduler();
  640. next_scheduler.SwitchContextStep2();
  641. }
  642. void KScheduler::OnSwitch(void* this_scheduler) {
  643. KScheduler* sched = static_cast<KScheduler*>(this_scheduler);
  644. sched->SwitchToCurrent();
  645. }
  646. void KScheduler::SwitchToCurrent() {
  647. while (true) {
  648. {
  649. KScopedSpinLock lk{guard};
  650. current_thread.store(state.highest_priority_thread);
  651. state.needs_scheduling.store(false);
  652. }
  653. const auto is_switch_pending = [this] {
  654. KScopedSpinLock lk{guard};
  655. return state.needs_scheduling.load();
  656. };
  657. do {
  658. auto next_thread = current_thread.load();
  659. if (next_thread != nullptr) {
  660. next_thread->context_guard.Lock();
  661. if (next_thread->GetRawState() != ThreadState::Runnable) {
  662. next_thread->context_guard.Unlock();
  663. break;
  664. }
  665. if (next_thread->GetActiveCore() != core_id) {
  666. next_thread->context_guard.Unlock();
  667. break;
  668. }
  669. }
  670. auto thread = next_thread ? next_thread : idle_thread;
  671. Common::Fiber::YieldTo(switch_fiber, *thread->GetHostContext());
  672. } while (!is_switch_pending());
  673. }
  674. }
  675. void KScheduler::UpdateLastContextSwitchTime(KThread* thread, KProcess* process) {
  676. const u64 prev_switch_ticks = last_context_switch_time;
  677. const u64 most_recent_switch_ticks = system.CoreTiming().GetCPUTicks();
  678. const u64 update_ticks = most_recent_switch_ticks - prev_switch_ticks;
  679. if (thread != nullptr) {
  680. thread->AddCpuTime(core_id, update_ticks);
  681. }
  682. if (process != nullptr) {
  683. process->UpdateCPUTimeTicks(update_ticks);
  684. }
  685. last_context_switch_time = most_recent_switch_ticks;
  686. }
  687. void KScheduler::Initialize() {
  688. idle_thread = KThread::Create(system.Kernel());
  689. ASSERT(KThread::InitializeIdleThread(system, idle_thread, core_id).IsSuccess());
  690. idle_thread->SetName(fmt::format("IdleThread:{}", core_id));
  691. }
  692. KScopedSchedulerLock::KScopedSchedulerLock(KernelCore& kernel)
  693. : KScopedLock(kernel.GlobalSchedulerContext().SchedulerLock()) {}
  694. KScopedSchedulerLock::~KScopedSchedulerLock() = default;
  695. } // namespace Kernel