scheduler.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  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. 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.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. if (next_thread->GetLastRunningTicks() >= thread->GetLastRunningTicks() ||
  154. next_thread->GetPriority() < thread->GetPriority()) {
  155. if (thread->GetPriority() <= priority) {
  156. winner = thread;
  157. break;
  158. }
  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 u64 priority = preemption_priorities[core_id];
  222. if (scheduled_queue[core_id].size(priority) > 1) {
  223. scheduled_queue[core_id].yield(priority);
  224. reselection_pending.store(true, std::memory_order_release);
  225. }
  226. }
  227. }
  228. void GlobalScheduler::Schedule(u32 priority, u32 core, Thread* thread) {
  229. ASSERT_MSG(thread->GetProcessorID() == core, "Thread must be assigned to this core.");
  230. scheduled_queue[core].add(thread, priority);
  231. }
  232. void GlobalScheduler::SchedulePrepend(u32 priority, u32 core, Thread* thread) {
  233. ASSERT_MSG(thread->GetProcessorID() == core, "Thread must be assigned to this core.");
  234. scheduled_queue[core].add(thread, priority, false);
  235. }
  236. bool GlobalScheduler::AskForReselectionOrMarkRedundant(Thread* current_thread, Thread* winner) {
  237. if (current_thread == winner) {
  238. // TODO(blinkhawk): manage redundant operations, this is not implemented.
  239. // as its mostly an optimization.
  240. // current_thread->SetRedundantSchedulerOperation();
  241. return true;
  242. } else {
  243. reselection_pending.store(true, std::memory_order_release);
  244. return false;
  245. }
  246. }
  247. GlobalScheduler::~GlobalScheduler() = default;
  248. Scheduler::Scheduler(Core::System& system, Core::ARM_Interface& cpu_core, u32 core_id)
  249. : system(system), cpu_core(cpu_core), core_id(core_id) {}
  250. Scheduler::~Scheduler() = default;
  251. bool Scheduler::HaveReadyThreads() const {
  252. return system.GlobalScheduler().HaveReadyThreads(core_id);
  253. }
  254. Thread* Scheduler::GetCurrentThread() const {
  255. return current_thread.get();
  256. }
  257. Thread* Scheduler::GetSelectedThread() const {
  258. return selected_thread.get();
  259. }
  260. void Scheduler::SelectThreads() {
  261. system.GlobalScheduler().SelectThread(core_id);
  262. }
  263. u64 Scheduler::GetLastContextSwitchTicks() const {
  264. return last_context_switch_time;
  265. }
  266. void Scheduler::TryDoContextSwitch() {
  267. if (context_switch_pending) {
  268. SwitchContext();
  269. }
  270. }
  271. void Scheduler::UnloadThread() {
  272. Thread* const previous_thread = GetCurrentThread();
  273. Process* const previous_process = system.Kernel().CurrentProcess();
  274. UpdateLastContextSwitchTime(previous_thread, previous_process);
  275. // Save context for previous thread
  276. if (previous_thread) {
  277. cpu_core.SaveContext(previous_thread->GetContext());
  278. // Save the TPIDR_EL0 system register in case it was modified.
  279. previous_thread->SetTPIDR_EL0(cpu_core.GetTPIDR_EL0());
  280. if (previous_thread->GetStatus() == ThreadStatus::Running) {
  281. // This is only the case when a reschedule is triggered without the current thread
  282. // yielding execution (i.e. an event triggered, system core time-sliced, etc)
  283. previous_thread->SetStatus(ThreadStatus::Ready);
  284. }
  285. previous_thread->SetIsRunning(false);
  286. }
  287. current_thread = nullptr;
  288. }
  289. void Scheduler::SwitchContext() {
  290. Thread* const previous_thread = GetCurrentThread();
  291. Thread* const new_thread = GetSelectedThread();
  292. context_switch_pending = false;
  293. if (new_thread == previous_thread) {
  294. return;
  295. }
  296. Process* const previous_process = system.Kernel().CurrentProcess();
  297. UpdateLastContextSwitchTime(previous_thread, previous_process);
  298. // Save context for previous thread
  299. if (previous_thread) {
  300. cpu_core.SaveContext(previous_thread->GetContext());
  301. // Save the TPIDR_EL0 system register in case it was modified.
  302. previous_thread->SetTPIDR_EL0(cpu_core.GetTPIDR_EL0());
  303. if (previous_thread->GetStatus() == ThreadStatus::Running) {
  304. // This is only the case when a reschedule is triggered without the current thread
  305. // yielding execution (i.e. an event triggered, system core time-sliced, etc)
  306. previous_thread->SetStatus(ThreadStatus::Ready);
  307. }
  308. previous_thread->SetIsRunning(false);
  309. }
  310. // Load context of new thread
  311. if (new_thread) {
  312. ASSERT_MSG(new_thread->GetProcessorID() == this->core_id,
  313. "Thread must be assigned to this core.");
  314. ASSERT_MSG(new_thread->GetStatus() == ThreadStatus::Ready,
  315. "Thread must be ready to become running.");
  316. // Cancel any outstanding wakeup events for this thread
  317. new_thread->CancelWakeupTimer();
  318. current_thread = new_thread;
  319. new_thread->SetStatus(ThreadStatus::Running);
  320. new_thread->SetIsRunning(true);
  321. auto* const thread_owner_process = current_thread->GetOwnerProcess();
  322. if (previous_process != thread_owner_process) {
  323. system.Kernel().MakeCurrentProcess(thread_owner_process);
  324. }
  325. cpu_core.LoadContext(new_thread->GetContext());
  326. cpu_core.SetTlsAddress(new_thread->GetTLSAddress());
  327. cpu_core.SetTPIDR_EL0(new_thread->GetTPIDR_EL0());
  328. cpu_core.ClearExclusiveState();
  329. } else {
  330. current_thread = nullptr;
  331. // Note: We do not reset the current process and current page table when idling because
  332. // technically we haven't changed processes, our threads are just paused.
  333. }
  334. }
  335. void Scheduler::UpdateLastContextSwitchTime(Thread* thread, Process* process) {
  336. const u64 prev_switch_ticks = last_context_switch_time;
  337. const u64 most_recent_switch_ticks = system.CoreTiming().GetTicks();
  338. const u64 update_ticks = most_recent_switch_ticks - prev_switch_ticks;
  339. if (thread != nullptr) {
  340. thread->UpdateCPUTimeTicks(update_ticks);
  341. }
  342. if (process != nullptr) {
  343. process->UpdateCPUTimeTicks(update_ticks);
  344. }
  345. last_context_switch_time = most_recent_switch_ticks;
  346. }
  347. } // namespace Kernel