scheduler.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  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(std::shared_ptr<Thread> thread) {
  24. thread_list.push_back(std::move(thread));
  25. }
  26. void GlobalScheduler::RemoveThread(std::shared_ptr<Thread> thread) {
  27. thread_list.erase(std::remove(thread_list.begin(), thread_list.end(), thread),
  28. thread_list.end());
  29. }
  30. void GlobalScheduler::UnloadThread(std::size_t core) {
  31. Scheduler& sched = system.Scheduler(core);
  32. sched.UnloadThread();
  33. }
  34. void GlobalScheduler::SelectThread(std::size_t core) {
  35. const auto update_thread = [](Thread* thread, Scheduler& sched) {
  36. if (thread != sched.selected_thread.get()) {
  37. if (thread == nullptr) {
  38. ++sched.idle_selection_count;
  39. }
  40. sched.selected_thread = SharedFrom(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(static_cast<u32>(winner->GetProcessorID()));
  72. }
  73. TransferToCore(winner->GetPriority(), static_cast<s32>(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(static_cast<u32>(src_core));
  86. }
  87. TransferToCore(thread_on_core->GetPriority(), static_cast<s32>(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. const Thread* const winner = scheduled_queue[core_id].front(priority);
  100. ASSERT_MSG(yielding_thread == winner, "Thread yielding without being in front");
  101. scheduled_queue[core_id].yield(priority);
  102. return AskForReselectionOrMarkRedundant(yielding_thread, winner);
  103. }
  104. bool GlobalScheduler::YieldThreadAndBalanceLoad(Thread* yielding_thread) {
  105. // Note: caller should check if !thread.IsSchedulerOperationRedundant and use critical section,
  106. // etc.
  107. const u32 core_id = static_cast<u32>(yielding_thread->GetProcessorID());
  108. const u32 priority = yielding_thread->GetPriority();
  109. // Yield the thread
  110. ASSERT_MSG(yielding_thread == scheduled_queue[core_id].front(priority),
  111. "Thread yielding without being in front");
  112. scheduled_queue[core_id].yield(priority);
  113. std::array<Thread*, NUM_CPU_CORES> current_threads;
  114. for (u32 i = 0; i < NUM_CPU_CORES; i++) {
  115. current_threads[i] = scheduled_queue[i].empty() ? nullptr : scheduled_queue[i].front();
  116. }
  117. Thread* next_thread = scheduled_queue[core_id].front(priority);
  118. Thread* winner = nullptr;
  119. for (auto& thread : suggested_queue[core_id]) {
  120. const s32 source_core = thread->GetProcessorID();
  121. if (source_core >= 0) {
  122. if (current_threads[source_core] != nullptr) {
  123. if (thread == current_threads[source_core] ||
  124. current_threads[source_core]->GetPriority() < min_regular_priority) {
  125. continue;
  126. }
  127. }
  128. }
  129. if (next_thread->GetLastRunningTicks() >= thread->GetLastRunningTicks() ||
  130. next_thread->GetPriority() < thread->GetPriority()) {
  131. if (thread->GetPriority() <= priority) {
  132. winner = thread;
  133. break;
  134. }
  135. }
  136. }
  137. if (winner != nullptr) {
  138. if (winner != yielding_thread) {
  139. if (winner->IsRunning()) {
  140. UnloadThread(static_cast<u32>(winner->GetProcessorID()));
  141. }
  142. TransferToCore(winner->GetPriority(), s32(core_id), winner);
  143. }
  144. } else {
  145. winner = next_thread;
  146. }
  147. return AskForReselectionOrMarkRedundant(yielding_thread, winner);
  148. }
  149. bool GlobalScheduler::YieldThreadAndWaitForLoadBalancing(Thread* yielding_thread) {
  150. // Note: caller should check if !thread.IsSchedulerOperationRedundant and use critical section,
  151. // etc.
  152. Thread* winner = nullptr;
  153. const u32 core_id = static_cast<u32>(yielding_thread->GetProcessorID());
  154. // Remove the thread from its scheduled mlq, put it on the corresponding "suggested" one instead
  155. TransferToCore(yielding_thread->GetPriority(), -1, yielding_thread);
  156. // If the core is idle, perform load balancing, excluding the threads that have just used this
  157. // function...
  158. if (scheduled_queue[core_id].empty()) {
  159. // Here, "current_threads" is calculated after the ""yield"", unlike yield -1
  160. std::array<Thread*, NUM_CPU_CORES> current_threads;
  161. for (u32 i = 0; i < NUM_CPU_CORES; i++) {
  162. current_threads[i] = scheduled_queue[i].empty() ? nullptr : scheduled_queue[i].front();
  163. }
  164. for (auto& thread : suggested_queue[core_id]) {
  165. const s32 source_core = thread->GetProcessorID();
  166. if (source_core < 0 || thread == current_threads[source_core]) {
  167. continue;
  168. }
  169. if (current_threads[source_core] == nullptr ||
  170. current_threads[source_core]->GetPriority() >= min_regular_priority) {
  171. winner = thread;
  172. }
  173. break;
  174. }
  175. if (winner != nullptr) {
  176. if (winner != yielding_thread) {
  177. if (winner->IsRunning()) {
  178. UnloadThread(static_cast<u32>(winner->GetProcessorID()));
  179. }
  180. TransferToCore(winner->GetPriority(), static_cast<s32>(core_id), winner);
  181. }
  182. } else {
  183. winner = yielding_thread;
  184. }
  185. }
  186. return AskForReselectionOrMarkRedundant(yielding_thread, winner);
  187. }
  188. void GlobalScheduler::PreemptThreads() {
  189. for (std::size_t core_id = 0; core_id < NUM_CPU_CORES; core_id++) {
  190. const u32 priority = preemption_priorities[core_id];
  191. if (scheduled_queue[core_id].size(priority) > 0) {
  192. scheduled_queue[core_id].front(priority)->IncrementYieldCount();
  193. scheduled_queue[core_id].yield(priority);
  194. if (scheduled_queue[core_id].size(priority) > 1) {
  195. scheduled_queue[core_id].front(priority)->IncrementYieldCount();
  196. }
  197. }
  198. Thread* current_thread =
  199. scheduled_queue[core_id].empty() ? nullptr : scheduled_queue[core_id].front();
  200. Thread* winner = nullptr;
  201. for (auto& thread : suggested_queue[core_id]) {
  202. const s32 source_core = thread->GetProcessorID();
  203. if (thread->GetPriority() != priority) {
  204. continue;
  205. }
  206. if (source_core >= 0) {
  207. Thread* next_thread = scheduled_queue[source_core].empty()
  208. ? nullptr
  209. : scheduled_queue[source_core].front();
  210. if (next_thread != nullptr && next_thread->GetPriority() < 2) {
  211. break;
  212. }
  213. if (next_thread == thread) {
  214. continue;
  215. }
  216. }
  217. if (current_thread != nullptr &&
  218. current_thread->GetLastRunningTicks() >= thread->GetLastRunningTicks()) {
  219. winner = thread;
  220. break;
  221. }
  222. }
  223. if (winner != nullptr) {
  224. if (winner->IsRunning()) {
  225. UnloadThread(static_cast<u32>(winner->GetProcessorID()));
  226. }
  227. TransferToCore(winner->GetPriority(), s32(core_id), winner);
  228. current_thread =
  229. winner->GetPriority() <= current_thread->GetPriority() ? winner : current_thread;
  230. }
  231. if (current_thread != nullptr && current_thread->GetPriority() > priority) {
  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(static_cast<u32>(winner->GetProcessorID()));
  257. }
  258. TransferToCore(winner->GetPriority(), s32(core_id), winner);
  259. current_thread = winner;
  260. }
  261. }
  262. is_reselection_pending.store(true, std::memory_order_release);
  263. }
  264. }
  265. void GlobalScheduler::Suggest(u32 priority, std::size_t core, Thread* thread) {
  266. suggested_queue[core].add(thread, priority);
  267. }
  268. void GlobalScheduler::Unsuggest(u32 priority, std::size_t core, Thread* thread) {
  269. suggested_queue[core].remove(thread, priority);
  270. }
  271. void GlobalScheduler::Schedule(u32 priority, std::size_t core, Thread* thread) {
  272. ASSERT_MSG(thread->GetProcessorID() == s32(core), "Thread must be assigned to this core.");
  273. scheduled_queue[core].add(thread, priority);
  274. }
  275. void GlobalScheduler::SchedulePrepend(u32 priority, std::size_t core, Thread* thread) {
  276. ASSERT_MSG(thread->GetProcessorID() == s32(core), "Thread must be assigned to this core.");
  277. scheduled_queue[core].add(thread, priority, false);
  278. }
  279. void GlobalScheduler::Reschedule(u32 priority, std::size_t core, Thread* thread) {
  280. scheduled_queue[core].remove(thread, priority);
  281. scheduled_queue[core].add(thread, priority);
  282. }
  283. void GlobalScheduler::Unschedule(u32 priority, std::size_t core, Thread* thread) {
  284. scheduled_queue[core].remove(thread, priority);
  285. }
  286. void GlobalScheduler::TransferToCore(u32 priority, s32 destination_core, Thread* thread) {
  287. const bool schedulable = thread->GetPriority() < THREADPRIO_COUNT;
  288. const s32 source_core = thread->GetProcessorID();
  289. if (source_core == destination_core || !schedulable) {
  290. return;
  291. }
  292. thread->SetProcessorID(destination_core);
  293. if (source_core >= 0) {
  294. Unschedule(priority, static_cast<u32>(source_core), thread);
  295. }
  296. if (destination_core >= 0) {
  297. Unsuggest(priority, static_cast<u32>(destination_core), thread);
  298. Schedule(priority, static_cast<u32>(destination_core), thread);
  299. }
  300. if (source_core >= 0) {
  301. Suggest(priority, static_cast<u32>(source_core), thread);
  302. }
  303. }
  304. bool GlobalScheduler::AskForReselectionOrMarkRedundant(Thread* current_thread,
  305. const 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, std::size_t 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() == s32(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 = SharedFrom(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. } else {
  402. current_thread = nullptr;
  403. // Note: We do not reset the current process and current page table when idling because
  404. // technically we haven't changed processes, our threads are just paused.
  405. }
  406. }
  407. void Scheduler::UpdateLastContextSwitchTime(Thread* thread, Process* process) {
  408. const u64 prev_switch_ticks = last_context_switch_time;
  409. const u64 most_recent_switch_ticks = system.CoreTiming().GetTicks();
  410. const u64 update_ticks = most_recent_switch_ticks - prev_switch_ticks;
  411. if (thread != nullptr) {
  412. thread->UpdateCPUTimeTicks(update_ticks);
  413. }
  414. if (process != nullptr) {
  415. process->UpdateCPUTimeTicks(update_ticks);
  416. }
  417. last_context_switch_time = most_recent_switch_ticks;
  418. }
  419. void Scheduler::Shutdown() {
  420. current_thread = nullptr;
  421. selected_thread = nullptr;
  422. }
  423. } // namespace Kernel