k_scheduler.cpp 31 KB

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