k_scheduler.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814
  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_scheduler.h"
  16. #include "core/hle/kernel/k_scoped_scheduler_lock_and_sleep.h"
  17. #include "core/hle/kernel/k_thread.h"
  18. #include "core/hle/kernel/kernel.h"
  19. #include "core/hle/kernel/physical_core.h"
  20. #include "core/hle/kernel/process.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. std::scoped_lock lock{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 (Process* 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 (Process* 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 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(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(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(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(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(core_id);
  277. if (best_thread == GetCurrentThread()) {
  278. best_thread = priority_queue.GetScheduledNext(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(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(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(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. Process& 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. Process& 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. Process& 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. KScheduler::~KScheduler() = default;
  535. KThread* KScheduler::GetCurrentThread() const {
  536. if (auto result = current_thread.load(); result) {
  537. return result;
  538. }
  539. return idle_thread;
  540. }
  541. u64 KScheduler::GetLastContextSwitchTicks() const {
  542. return last_context_switch_time;
  543. }
  544. void KScheduler::RescheduleCurrentCore() {
  545. ASSERT(GetCurrentThread()->GetDisableDispatchCount() == 1);
  546. auto& phys_core = system.Kernel().PhysicalCore(core_id);
  547. if (phys_core.IsInterrupted()) {
  548. phys_core.ClearInterrupt();
  549. }
  550. guard.lock();
  551. if (state.needs_scheduling.load()) {
  552. Schedule();
  553. } else {
  554. guard.unlock();
  555. }
  556. }
  557. void KScheduler::OnThreadStart() {
  558. SwitchContextStep2();
  559. }
  560. void KScheduler::Unload(KThread* thread) {
  561. LOG_TRACE(Kernel, "core {}, unload thread {}", core_id, thread ? thread->GetName() : "nullptr");
  562. if (thread) {
  563. if (thread->IsCallingSvc()) {
  564. system.ArmInterface(core_id).ExceptionalExit();
  565. thread->ClearIsCallingSvc();
  566. }
  567. if (!thread->IsTerminationRequested()) {
  568. prev_thread = thread;
  569. Core::ARM_Interface& cpu_core = system.ArmInterface(core_id);
  570. cpu_core.SaveContext(thread->GetContext32());
  571. cpu_core.SaveContext(thread->GetContext64());
  572. // Save the TPIDR_EL0 system register in case it was modified.
  573. thread->SetTPIDR_EL0(cpu_core.GetTPIDR_EL0());
  574. cpu_core.ClearExclusiveState();
  575. } else {
  576. prev_thread = nullptr;
  577. }
  578. thread->context_guard.unlock();
  579. }
  580. }
  581. void KScheduler::Reload(KThread* thread) {
  582. LOG_TRACE(Kernel, "core {}, reload thread {}", core_id, thread ? thread->GetName() : "nullptr");
  583. if (thread) {
  584. ASSERT_MSG(thread->GetState() == ThreadState::Runnable, "Thread must be runnable.");
  585. auto* const thread_owner_process = thread->GetOwnerProcess();
  586. if (thread_owner_process != nullptr) {
  587. system.Kernel().MakeCurrentProcess(thread_owner_process);
  588. }
  589. Core::ARM_Interface& cpu_core = system.ArmInterface(core_id);
  590. cpu_core.LoadContext(thread->GetContext32());
  591. cpu_core.LoadContext(thread->GetContext64());
  592. cpu_core.SetTlsAddress(thread->GetTLSAddress());
  593. cpu_core.SetTPIDR_EL0(thread->GetTPIDR_EL0());
  594. cpu_core.ClearExclusiveState();
  595. }
  596. }
  597. void KScheduler::SwitchContextStep2() {
  598. // Load context of new thread
  599. Reload(current_thread.load());
  600. RescheduleCurrentCore();
  601. }
  602. void KScheduler::ScheduleImpl() {
  603. KThread* previous_thread = current_thread.load();
  604. KThread* next_thread = state.highest_priority_thread;
  605. state.needs_scheduling = false;
  606. // We never want to schedule a null thread, so use the idle thread if we don't have a next.
  607. if (next_thread == nullptr) {
  608. next_thread = idle_thread;
  609. }
  610. // If we're not actually switching thread, there's nothing to do.
  611. if (next_thread == current_thread.load()) {
  612. guard.unlock();
  613. return;
  614. }
  615. current_thread.store(next_thread);
  616. Process* const previous_process = system.Kernel().CurrentProcess();
  617. UpdateLastContextSwitchTime(previous_thread, previous_process);
  618. // Save context for previous thread
  619. Unload(previous_thread);
  620. std::shared_ptr<Common::Fiber>* old_context;
  621. if (previous_thread != nullptr) {
  622. old_context = &previous_thread->GetHostContext();
  623. } else {
  624. old_context = &idle_thread->GetHostContext();
  625. }
  626. guard.unlock();
  627. Common::Fiber::YieldTo(*old_context, switch_fiber);
  628. /// When a thread wakes up, the scheduler may have changed to other in another core.
  629. auto& next_scheduler = *system.Kernel().CurrentScheduler();
  630. next_scheduler.SwitchContextStep2();
  631. }
  632. void KScheduler::OnSwitch(void* this_scheduler) {
  633. KScheduler* sched = static_cast<KScheduler*>(this_scheduler);
  634. sched->SwitchToCurrent();
  635. }
  636. void KScheduler::SwitchToCurrent() {
  637. while (true) {
  638. {
  639. std::scoped_lock lock{guard};
  640. current_thread.store(state.highest_priority_thread);
  641. state.needs_scheduling.store(false);
  642. }
  643. const auto is_switch_pending = [this] {
  644. std::scoped_lock lock{guard};
  645. return state.needs_scheduling.load();
  646. };
  647. do {
  648. auto next_thread = current_thread.load();
  649. if (next_thread != nullptr) {
  650. next_thread->context_guard.lock();
  651. if (next_thread->GetRawState() != ThreadState::Runnable) {
  652. next_thread->context_guard.unlock();
  653. break;
  654. }
  655. if (next_thread->GetActiveCore() != core_id) {
  656. next_thread->context_guard.unlock();
  657. break;
  658. }
  659. }
  660. std::shared_ptr<Common::Fiber>* next_context;
  661. if (next_thread != nullptr) {
  662. next_context = &next_thread->GetHostContext();
  663. } else {
  664. next_context = &idle_thread->GetHostContext();
  665. }
  666. Common::Fiber::YieldTo(switch_fiber, *next_context);
  667. } while (!is_switch_pending());
  668. }
  669. }
  670. void KScheduler::UpdateLastContextSwitchTime(KThread* thread, Process* process) {
  671. const u64 prev_switch_ticks = last_context_switch_time;
  672. const u64 most_recent_switch_ticks = system.CoreTiming().GetCPUTicks();
  673. const u64 update_ticks = most_recent_switch_ticks - prev_switch_ticks;
  674. if (thread != nullptr) {
  675. thread->AddCpuTime(core_id, update_ticks);
  676. }
  677. if (process != nullptr) {
  678. process->UpdateCPUTimeTicks(update_ticks);
  679. }
  680. last_context_switch_time = most_recent_switch_ticks;
  681. }
  682. void KScheduler::Initialize() {
  683. std::string name = "Idle Thread Id:" + std::to_string(core_id);
  684. std::function<void(void*)> init_func = Core::CpuManager::GetIdleThreadStartFunc();
  685. void* init_func_parameter = system.GetCpuManager().GetStartFuncParamater();
  686. auto thread_res = KThread::Create(system, ThreadType::Main, name, 0,
  687. KThread::IdleThreadPriority, 0, static_cast<u32>(core_id), 0,
  688. nullptr, std::move(init_func), init_func_parameter);
  689. idle_thread = thread_res.Unwrap().get();
  690. }
  691. KScopedSchedulerLock::KScopedSchedulerLock(KernelCore& kernel)
  692. : KScopedLock(kernel.GlobalSchedulerContext().SchedulerLock()) {}
  693. KScopedSchedulerLock::~KScopedSchedulerLock() = default;
  694. } // namespace Kernel