scheduler.cpp 18 KB

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