scheduler.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  1. // Copyright 2018 yuzu emulator team
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. //
  5. // SelectThreads, Yield functions originally by TuxSH.
  6. // licensed under GPLv2 or later under exception provided by the author.
  7. #include <algorithm>
  8. #include <set>
  9. #include <unordered_set>
  10. #include <utility>
  11. #include "common/assert.h"
  12. #include "common/logging/log.h"
  13. #include "core/arm/arm_interface.h"
  14. #include "core/core.h"
  15. #include "core/core_cpu.h"
  16. #include "core/core_timing.h"
  17. #include "core/hle/kernel/kernel.h"
  18. #include "core/hle/kernel/process.h"
  19. #include "core/hle/kernel/scheduler.h"
  20. namespace Kernel {
  21. GlobalScheduler::GlobalScheduler(Core::System& system) : system{system} {
  22. is_reselection_pending = false;
  23. }
  24. void GlobalScheduler::AddThread(SharedPtr<Thread> thread) {
  25. thread_list.push_back(std::move(thread));
  26. }
  27. void GlobalScheduler::RemoveThread(const Thread* thread) {
  28. thread_list.erase(std::remove(thread_list.begin(), thread_list.end(), thread),
  29. thread_list.end());
  30. }
  31. /*
  32. * UnloadThread selects a core and forces it to unload its current thread's context
  33. */
  34. void GlobalScheduler::UnloadThread(s32 core) {
  35. Scheduler& sched = system.Scheduler(core);
  36. sched.UnloadThread();
  37. }
  38. /*
  39. * SelectThread takes care of selecting the new scheduled thread.
  40. * It does it in 3 steps:
  41. * - First a thread is selected from the top of the priority queue. If no thread
  42. * is obtained then we move to step two, else we are done.
  43. * - Second we try to get a suggested thread that's not assigned to any core or
  44. * that is not the top thread in that core.
  45. * - Third is no suggested thread is found, we do a second pass and pick a running
  46. * thread in another core and swap it with its current thread.
  47. */
  48. void GlobalScheduler::SelectThread(u32 core) {
  49. const auto update_thread = [](Thread* thread, Scheduler& sched) {
  50. if (thread != sched.selected_thread) {
  51. if (thread == nullptr) {
  52. ++sched.idle_selection_count;
  53. }
  54. sched.selected_thread = thread;
  55. }
  56. sched.is_context_switch_pending = sched.selected_thread != sched.current_thread;
  57. std::atomic_thread_fence(std::memory_order_seq_cst);
  58. };
  59. Scheduler& sched = system.Scheduler(core);
  60. Thread* current_thread = nullptr;
  61. // Step 1: Get top thread in schedule queue.
  62. current_thread = scheduled_queue[core].empty() ? nullptr : scheduled_queue[core].front();
  63. if (current_thread) {
  64. update_thread(current_thread, sched);
  65. return;
  66. }
  67. // Step 2: Try selecting a suggested thread.
  68. Thread* winner = nullptr;
  69. std::set<s32> sug_cores;
  70. for (auto thread : suggested_queue[core]) {
  71. s32 this_core = thread->GetProcessorID();
  72. Thread* thread_on_core = nullptr;
  73. if (this_core >= 0) {
  74. thread_on_core = scheduled_queue[this_core].front();
  75. }
  76. if (this_core < 0 || thread != thread_on_core) {
  77. winner = thread;
  78. break;
  79. }
  80. sug_cores.insert(this_core);
  81. }
  82. // if we got a suggested thread, select it, else do a second pass.
  83. if (winner && winner->GetPriority() > 2) {
  84. if (winner->IsRunning()) {
  85. UnloadThread(winner->GetProcessorID());
  86. }
  87. TransferToCore(winner->GetPriority(), core, winner);
  88. update_thread(winner, sched);
  89. return;
  90. }
  91. // Step 3: Select a suggested thread from another core
  92. for (auto& src_core : sug_cores) {
  93. auto it = scheduled_queue[src_core].begin();
  94. it++;
  95. if (it != scheduled_queue[src_core].end()) {
  96. Thread* thread_on_core = scheduled_queue[src_core].front();
  97. Thread* to_change = *it;
  98. if (thread_on_core->IsRunning() || to_change->IsRunning()) {
  99. UnloadThread(src_core);
  100. }
  101. TransferToCore(thread_on_core->GetPriority(), core, thread_on_core);
  102. current_thread = thread_on_core;
  103. break;
  104. }
  105. }
  106. update_thread(current_thread, sched);
  107. }
  108. /*
  109. * YieldThread takes a thread and moves it to the back of the it's priority list
  110. * This operation can be redundant and no scheduling is changed if marked as so.
  111. */
  112. bool GlobalScheduler::YieldThread(Thread* yielding_thread) {
  113. // Note: caller should use critical section, etc.
  114. const u32 core_id = static_cast<u32>(yielding_thread->GetProcessorID());
  115. const u32 priority = yielding_thread->GetPriority();
  116. // Yield the thread
  117. ASSERT_MSG(yielding_thread == scheduled_queue[core_id].front(priority),
  118. "Thread yielding without being in front");
  119. scheduled_queue[core_id].yield(priority);
  120. Thread* winner = scheduled_queue[core_id].front(priority);
  121. return AskForReselectionOrMarkRedundant(yielding_thread, winner);
  122. }
  123. /*
  124. * YieldThreadAndBalanceLoad takes a thread and moves it to the back of the it's priority list.
  125. * Afterwards, tries to pick a suggested thread from the suggested queue that has worse time or
  126. * a better priority than the next thread in the core.
  127. * This operation can be redundant and no scheduling is changed if marked as so.
  128. */
  129. bool GlobalScheduler::YieldThreadAndBalanceLoad(Thread* yielding_thread) {
  130. // Note: caller should check if !thread.IsSchedulerOperationRedundant and use critical section,
  131. // etc.
  132. const u32 core_id = static_cast<u32>(yielding_thread->GetProcessorID());
  133. const u32 priority = yielding_thread->GetPriority();
  134. // Yield the thread
  135. ASSERT_MSG(yielding_thread == scheduled_queue[core_id].front(priority),
  136. "Thread yielding without being in front");
  137. scheduled_queue[core_id].yield(priority);
  138. std::array<Thread*, NUM_CPU_CORES> current_threads;
  139. for (u32 i = 0; i < NUM_CPU_CORES; i++) {
  140. current_threads[i] = scheduled_queue[i].empty() ? nullptr : scheduled_queue[i].front();
  141. }
  142. Thread* next_thread = scheduled_queue[core_id].front(priority);
  143. Thread* winner = nullptr;
  144. for (auto& thread : suggested_queue[core_id]) {
  145. const s32 source_core = thread->GetProcessorID();
  146. if (source_core >= 0) {
  147. if (current_threads[source_core] != nullptr) {
  148. if (thread == current_threads[source_core] ||
  149. current_threads[source_core]->GetPriority() < min_regular_priority) {
  150. continue;
  151. }
  152. }
  153. }
  154. if (next_thread->GetLastRunningTicks() >= thread->GetLastRunningTicks() ||
  155. next_thread->GetPriority() < thread->GetPriority()) {
  156. if (thread->GetPriority() <= priority) {
  157. winner = thread;
  158. break;
  159. }
  160. }
  161. }
  162. if (winner != nullptr) {
  163. if (winner != yielding_thread) {
  164. if (winner->IsRunning()) {
  165. UnloadThread(winner->GetProcessorID());
  166. }
  167. TransferToCore(winner->GetPriority(), core_id, winner);
  168. }
  169. } else {
  170. winner = next_thread;
  171. }
  172. return AskForReselectionOrMarkRedundant(yielding_thread, winner);
  173. }
  174. /*
  175. * YieldThreadAndWaitForLoadBalancing takes a thread and moves it out of the scheduling queue
  176. * and into the suggested queue. If no thread can be squeduled afterwards in that core,
  177. * a suggested thread is obtained instead.
  178. * This operation can be redundant and no scheduling is changed if marked as so.
  179. */
  180. bool GlobalScheduler::YieldThreadAndWaitForLoadBalancing(Thread* yielding_thread) {
  181. // Note: caller should check if !thread.IsSchedulerOperationRedundant and use critical section,
  182. // etc.
  183. Thread* winner = nullptr;
  184. const u32 core_id = static_cast<u32>(yielding_thread->GetProcessorID());
  185. // Remove the thread from its scheduled mlq, put it on the corresponding "suggested" one instead
  186. TransferToCore(yielding_thread->GetPriority(), -1, yielding_thread);
  187. // If the core is idle, perform load balancing, excluding the threads that have just used this
  188. // function...
  189. if (scheduled_queue[core_id].empty()) {
  190. // Here, "current_threads" is calculated after the ""yield"", unlike yield -1
  191. std::array<Thread*, NUM_CPU_CORES> current_threads;
  192. for (u32 i = 0; i < NUM_CPU_CORES; i++) {
  193. current_threads[i] = scheduled_queue[i].empty() ? nullptr : scheduled_queue[i].front();
  194. }
  195. for (auto& thread : suggested_queue[core_id]) {
  196. const s32 source_core = thread->GetProcessorID();
  197. if (source_core < 0 || thread == current_threads[source_core]) {
  198. continue;
  199. }
  200. if (current_threads[source_core] == nullptr ||
  201. current_threads[source_core]->GetPriority() >= min_regular_priority) {
  202. winner = thread;
  203. }
  204. break;
  205. }
  206. if (winner != nullptr) {
  207. if (winner != yielding_thread) {
  208. if (winner->IsRunning()) {
  209. UnloadThread(winner->GetProcessorID());
  210. }
  211. TransferToCore(winner->GetPriority(), core_id, winner);
  212. }
  213. } else {
  214. winner = yielding_thread;
  215. }
  216. }
  217. return AskForReselectionOrMarkRedundant(yielding_thread, winner);
  218. }
  219. void GlobalScheduler::PreemptThreads() {
  220. for (std::size_t core_id = 0; core_id < NUM_CPU_CORES; core_id++) {
  221. const u32 priority = preemption_priorities[core_id];
  222. if (scheduled_queue[core_id].size(priority) > 0) {
  223. scheduled_queue[core_id].front(priority)->IncrementYieldCount();
  224. scheduled_queue[core_id].yield(priority);
  225. if (scheduled_queue[core_id].size(priority) > 1) {
  226. scheduled_queue[core_id].front(priority)->IncrementYieldCount();
  227. }
  228. }
  229. Thread* current_thread =
  230. scheduled_queue[core_id].empty() ? nullptr : scheduled_queue[core_id].front();
  231. Thread* winner = nullptr;
  232. for (auto& thread : suggested_queue[core_id]) {
  233. const s32 source_core = thread->GetProcessorID();
  234. if (thread->GetPriority() != priority) {
  235. continue;
  236. }
  237. if (source_core >= 0) {
  238. Thread* next_thread = scheduled_queue[source_core].empty()
  239. ? nullptr
  240. : scheduled_queue[source_core].front();
  241. if (next_thread != nullptr && next_thread->GetPriority() < 2) {
  242. break;
  243. }
  244. if (next_thread == thread) {
  245. continue;
  246. }
  247. }
  248. if (current_thread != nullptr &&
  249. current_thread->GetLastRunningTicks() >= thread->GetLastRunningTicks()) {
  250. winner = thread;
  251. break;
  252. }
  253. }
  254. if (winner != nullptr) {
  255. if (winner->IsRunning()) {
  256. UnloadThread(winner->GetProcessorID());
  257. }
  258. TransferToCore(winner->GetPriority(), core_id, winner);
  259. current_thread =
  260. winner->GetPriority() <= current_thread->GetPriority() ? winner : current_thread;
  261. }
  262. if (current_thread != nullptr && current_thread->GetPriority() > priority) {
  263. for (auto& thread : suggested_queue[core_id]) {
  264. const s32 source_core = thread->GetProcessorID();
  265. if (thread->GetPriority() < priority) {
  266. continue;
  267. }
  268. if (source_core >= 0) {
  269. Thread* next_thread = scheduled_queue[source_core].empty()
  270. ? nullptr
  271. : scheduled_queue[source_core].front();
  272. if (next_thread != nullptr && next_thread->GetPriority() < 2) {
  273. break;
  274. }
  275. if (next_thread == thread) {
  276. continue;
  277. }
  278. }
  279. if (current_thread != nullptr &&
  280. current_thread->GetLastRunningTicks() >= thread->GetLastRunningTicks()) {
  281. winner = thread;
  282. break;
  283. }
  284. }
  285. if (winner != nullptr) {
  286. if (winner->IsRunning()) {
  287. UnloadThread(winner->GetProcessorID());
  288. }
  289. TransferToCore(winner->GetPriority(), core_id, winner);
  290. current_thread = winner;
  291. }
  292. }
  293. is_reselection_pending.store(true, std::memory_order_release);
  294. }
  295. }
  296. void GlobalScheduler::Suggest(u32 priority, u32 core, Thread* thread) {
  297. suggested_queue[core].add(thread, priority);
  298. }
  299. void GlobalScheduler::Unsuggest(u32 priority, u32 core, Thread* thread) {
  300. suggested_queue[core].remove(thread, priority);
  301. }
  302. void GlobalScheduler::Schedule(u32 priority, u32 core, Thread* thread) {
  303. ASSERT_MSG(thread->GetProcessorID() == core, "Thread must be assigned to this core.");
  304. scheduled_queue[core].add(thread, priority);
  305. }
  306. void GlobalScheduler::SchedulePrepend(u32 priority, u32 core, Thread* thread) {
  307. ASSERT_MSG(thread->GetProcessorID() == core, "Thread must be assigned to this core.");
  308. scheduled_queue[core].add(thread, priority, false);
  309. }
  310. void GlobalScheduler::Reschedule(u32 priority, u32 core, Thread* thread) {
  311. scheduled_queue[core].remove(thread, priority);
  312. scheduled_queue[core].add(thread, priority);
  313. }
  314. void GlobalScheduler::Unschedule(u32 priority, u32 core, Thread* thread) {
  315. scheduled_queue[core].remove(thread, priority);
  316. }
  317. void GlobalScheduler::TransferToCore(u32 priority, s32 destination_core, Thread* thread) {
  318. const bool schedulable = thread->GetPriority() < THREADPRIO_COUNT;
  319. const s32 source_core = thread->GetProcessorID();
  320. if (source_core == destination_core || !schedulable) {
  321. return;
  322. }
  323. thread->SetProcessorID(destination_core);
  324. if (source_core >= 0) {
  325. Unschedule(priority, source_core, thread);
  326. }
  327. if (destination_core >= 0) {
  328. Unsuggest(priority, destination_core, thread);
  329. Schedule(priority, destination_core, thread);
  330. }
  331. if (source_core >= 0) {
  332. Suggest(priority, source_core, thread);
  333. }
  334. }
  335. bool GlobalScheduler::AskForReselectionOrMarkRedundant(Thread* current_thread, Thread* winner) {
  336. if (current_thread == winner) {
  337. current_thread->IncrementYieldCount();
  338. return true;
  339. } else {
  340. is_reselection_pending.store(true, std::memory_order_release);
  341. return false;
  342. }
  343. }
  344. void GlobalScheduler::Shutdown() {
  345. for (std::size_t core = 0; core < NUM_CPU_CORES; core++) {
  346. scheduled_queue[core].clear();
  347. suggested_queue[core].clear();
  348. }
  349. thread_list.clear();
  350. }
  351. GlobalScheduler::~GlobalScheduler() = default;
  352. Scheduler::Scheduler(Core::System& system, Core::ARM_Interface& cpu_core, u32 core_id)
  353. : system(system), cpu_core(cpu_core), core_id(core_id) {}
  354. Scheduler::~Scheduler() = default;
  355. bool Scheduler::HaveReadyThreads() const {
  356. return system.GlobalScheduler().HaveReadyThreads(core_id);
  357. }
  358. Thread* Scheduler::GetCurrentThread() const {
  359. return current_thread.get();
  360. }
  361. Thread* Scheduler::GetSelectedThread() const {
  362. return selected_thread.get();
  363. }
  364. void Scheduler::SelectThreads() {
  365. system.GlobalScheduler().SelectThread(core_id);
  366. }
  367. u64 Scheduler::GetLastContextSwitchTicks() const {
  368. return last_context_switch_time;
  369. }
  370. void Scheduler::TryDoContextSwitch() {
  371. if (is_context_switch_pending) {
  372. SwitchContext();
  373. }
  374. }
  375. void Scheduler::UnloadThread() {
  376. Thread* const previous_thread = GetCurrentThread();
  377. Process* const previous_process = system.Kernel().CurrentProcess();
  378. UpdateLastContextSwitchTime(previous_thread, previous_process);
  379. // Save context for previous thread
  380. if (previous_thread) {
  381. cpu_core.SaveContext(previous_thread->GetContext());
  382. // Save the TPIDR_EL0 system register in case it was modified.
  383. previous_thread->SetTPIDR_EL0(cpu_core.GetTPIDR_EL0());
  384. if (previous_thread->GetStatus() == ThreadStatus::Running) {
  385. // This is only the case when a reschedule is triggered without the current thread
  386. // yielding execution (i.e. an event triggered, system core time-sliced, etc)
  387. previous_thread->SetStatus(ThreadStatus::Ready);
  388. }
  389. previous_thread->SetIsRunning(false);
  390. }
  391. current_thread = nullptr;
  392. }
  393. void Scheduler::SwitchContext() {
  394. Thread* const previous_thread = GetCurrentThread();
  395. Thread* const new_thread = GetSelectedThread();
  396. is_context_switch_pending = false;
  397. if (new_thread == previous_thread) {
  398. return;
  399. }
  400. Process* const previous_process = system.Kernel().CurrentProcess();
  401. UpdateLastContextSwitchTime(previous_thread, previous_process);
  402. // Save context for previous thread
  403. if (previous_thread) {
  404. cpu_core.SaveContext(previous_thread->GetContext());
  405. // Save the TPIDR_EL0 system register in case it was modified.
  406. previous_thread->SetTPIDR_EL0(cpu_core.GetTPIDR_EL0());
  407. if (previous_thread->GetStatus() == ThreadStatus::Running) {
  408. // This is only the case when a reschedule is triggered without the current thread
  409. // yielding execution (i.e. an event triggered, system core time-sliced, etc)
  410. previous_thread->SetStatus(ThreadStatus::Ready);
  411. }
  412. previous_thread->SetIsRunning(false);
  413. }
  414. // Load context of new thread
  415. if (new_thread) {
  416. ASSERT_MSG(new_thread->GetProcessorID() == this->core_id,
  417. "Thread must be assigned to this core.");
  418. ASSERT_MSG(new_thread->GetStatus() == ThreadStatus::Ready,
  419. "Thread must be ready to become running.");
  420. // Cancel any outstanding wakeup events for this thread
  421. new_thread->CancelWakeupTimer();
  422. current_thread = new_thread;
  423. new_thread->SetStatus(ThreadStatus::Running);
  424. new_thread->SetIsRunning(true);
  425. auto* const thread_owner_process = current_thread->GetOwnerProcess();
  426. if (previous_process != thread_owner_process) {
  427. system.Kernel().MakeCurrentProcess(thread_owner_process);
  428. }
  429. cpu_core.LoadContext(new_thread->GetContext());
  430. cpu_core.SetTlsAddress(new_thread->GetTLSAddress());
  431. cpu_core.SetTPIDR_EL0(new_thread->GetTPIDR_EL0());
  432. cpu_core.ClearExclusiveState();
  433. } else {
  434. current_thread = nullptr;
  435. // Note: We do not reset the current process and current page table when idling because
  436. // technically we haven't changed processes, our threads are just paused.
  437. }
  438. }
  439. void Scheduler::UpdateLastContextSwitchTime(Thread* thread, Process* process) {
  440. const u64 prev_switch_ticks = last_context_switch_time;
  441. const u64 most_recent_switch_ticks = system.CoreTiming().GetTicks();
  442. const u64 update_ticks = most_recent_switch_ticks - prev_switch_ticks;
  443. if (thread != nullptr) {
  444. thread->UpdateCPUTimeTicks(update_ticks);
  445. }
  446. if (process != nullptr) {
  447. process->UpdateCPUTimeTicks(update_ticks);
  448. }
  449. last_context_switch_time = most_recent_switch_ticks;
  450. }
  451. void Scheduler::Shutdown() {
  452. current_thread = nullptr;
  453. selected_thread = nullptr;
  454. }
  455. } // namespace Kernel