k_scheduler.cpp 34 KB

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