KScheduler.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619
  1. using Ryujinx.Common;
  2. using Ryujinx.HLE.HOS.Kernel.Process;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Numerics;
  7. using System.Threading;
  8. namespace Ryujinx.HLE.HOS.Kernel.Threading
  9. {
  10. partial class KScheduler : IDisposable
  11. {
  12. public const int PrioritiesCount = 64;
  13. public const int CpuCoresCount = 4;
  14. private const int RoundRobinTimeQuantumMs = 10;
  15. private static readonly int[] PreemptionPriorities = new int[] { 59, 59, 59, 63 };
  16. private readonly KernelContext _context;
  17. private readonly int _coreId;
  18. private struct SchedulingState
  19. {
  20. public bool NeedsScheduling;
  21. public KThread SelectedThread;
  22. }
  23. private SchedulingState _state;
  24. private AutoResetEvent _idleInterruptEvent;
  25. private readonly object _idleInterruptEventLock;
  26. private KThread _previousThread;
  27. private KThread _currentThread;
  28. private readonly KThread _idleThread;
  29. public KThread PreviousThread => _previousThread;
  30. public long LastContextSwitchTime { get; private set; }
  31. public long TotalIdleTimeTicks => _idleThread.TotalTimeRunning;
  32. public KScheduler(KernelContext context, int coreId)
  33. {
  34. _context = context;
  35. _coreId = coreId;
  36. _idleInterruptEvent = new AutoResetEvent(false);
  37. _idleInterruptEventLock = new object();
  38. KThread idleThread = CreateIdleThread(context, coreId);
  39. _currentThread = idleThread;
  40. _idleThread = idleThread;
  41. idleThread.StartHostThread();
  42. idleThread.SchedulerWaitEvent.Set();
  43. }
  44. private KThread CreateIdleThread(KernelContext context, int cpuCore)
  45. {
  46. KThread idleThread = new KThread(context);
  47. idleThread.Initialize(0UL, 0UL, 0UL, PrioritiesCount, cpuCore, null, ThreadType.Dummy, IdleThreadLoop);
  48. return idleThread;
  49. }
  50. public static ulong SelectThreads(KernelContext context)
  51. {
  52. if (context.ThreadReselectionRequested)
  53. {
  54. return SelectThreadsImpl(context);
  55. }
  56. else
  57. {
  58. return 0UL;
  59. }
  60. }
  61. private static ulong SelectThreadsImpl(KernelContext context)
  62. {
  63. context.ThreadReselectionRequested = false;
  64. ulong scheduledCoresMask = 0UL;
  65. for (int core = 0; core < CpuCoresCount; core++)
  66. {
  67. KThread thread = context.PriorityQueue.ScheduledThreads(core).FirstOrDefault();
  68. scheduledCoresMask |= context.Schedulers[core].SelectThread(thread);
  69. }
  70. for (int core = 0; core < CpuCoresCount; core++)
  71. {
  72. // If the core is not idle (there's already a thread running on it),
  73. // then we don't need to attempt load balancing.
  74. if (context.PriorityQueue.ScheduledThreads(core).Any())
  75. {
  76. continue;
  77. }
  78. int[] srcCoresHighestPrioThreads = new int[CpuCoresCount];
  79. int srcCoresHighestPrioThreadsCount = 0;
  80. KThread dst = null;
  81. // Select candidate threads that could run on this core.
  82. // Give preference to threads that are not yet selected.
  83. foreach (KThread suggested in context.PriorityQueue.SuggestedThreads(core))
  84. {
  85. if (suggested.ActiveCore < 0 || suggested != context.Schedulers[suggested.ActiveCore]._state.SelectedThread)
  86. {
  87. dst = suggested;
  88. break;
  89. }
  90. srcCoresHighestPrioThreads[srcCoresHighestPrioThreadsCount++] = suggested.ActiveCore;
  91. }
  92. // Not yet selected candidate found.
  93. if (dst != null)
  94. {
  95. // Priorities < 2 are used for the kernel message dispatching
  96. // threads, we should skip load balancing entirely.
  97. if (dst.DynamicPriority >= 2)
  98. {
  99. context.PriorityQueue.TransferToCore(dst.DynamicPriority, core, dst);
  100. scheduledCoresMask |= context.Schedulers[core].SelectThread(dst);
  101. }
  102. continue;
  103. }
  104. // All candidates are already selected, choose the best one
  105. // (the first one that doesn't make the source core idle if moved).
  106. for (int index = 0; index < srcCoresHighestPrioThreadsCount; index++)
  107. {
  108. int srcCore = srcCoresHighestPrioThreads[index];
  109. KThread src = context.PriorityQueue.ScheduledThreads(srcCore).ElementAtOrDefault(1);
  110. if (src != null)
  111. {
  112. // Run the second thread on the queue on the source core,
  113. // move the first one to the current core.
  114. KThread origSelectedCoreSrc = context.Schedulers[srcCore]._state.SelectedThread;
  115. scheduledCoresMask |= context.Schedulers[srcCore].SelectThread(src);
  116. context.PriorityQueue.TransferToCore(origSelectedCoreSrc.DynamicPriority, core, origSelectedCoreSrc);
  117. scheduledCoresMask |= context.Schedulers[core].SelectThread(origSelectedCoreSrc);
  118. }
  119. }
  120. }
  121. return scheduledCoresMask;
  122. }
  123. private ulong SelectThread(KThread nextThread)
  124. {
  125. KThread previousThread = _state.SelectedThread;
  126. if (previousThread != nextThread)
  127. {
  128. if (previousThread != null)
  129. {
  130. previousThread.LastScheduledTime = PerformanceCounter.ElapsedTicks;
  131. }
  132. _state.SelectedThread = nextThread;
  133. _state.NeedsScheduling = true;
  134. return 1UL << _coreId;
  135. }
  136. else
  137. {
  138. return 0UL;
  139. }
  140. }
  141. public static void EnableScheduling(KernelContext context, ulong scheduledCoresMask)
  142. {
  143. KScheduler currentScheduler = context.Schedulers[KernelStatic.GetCurrentThread().CurrentCore];
  144. // Note that "RescheduleCurrentCore" will block, so "RescheduleOtherCores" must be done first.
  145. currentScheduler.RescheduleOtherCores(scheduledCoresMask);
  146. currentScheduler.RescheduleCurrentCore();
  147. }
  148. public static void EnableSchedulingFromForeignThread(KernelContext context, ulong scheduledCoresMask)
  149. {
  150. RescheduleOtherCores(context, scheduledCoresMask);
  151. }
  152. private void RescheduleCurrentCore()
  153. {
  154. if (_state.NeedsScheduling)
  155. {
  156. Schedule();
  157. }
  158. }
  159. private void RescheduleOtherCores(ulong scheduledCoresMask)
  160. {
  161. RescheduleOtherCores(_context, scheduledCoresMask & ~(1UL << _coreId));
  162. }
  163. private static void RescheduleOtherCores(KernelContext context, ulong scheduledCoresMask)
  164. {
  165. while (scheduledCoresMask != 0)
  166. {
  167. int coreToSignal = BitOperations.TrailingZeroCount(scheduledCoresMask);
  168. KThread threadToSignal = context.Schedulers[coreToSignal]._currentThread;
  169. // Request the thread running on that core to stop and reschedule, if we have one.
  170. if (threadToSignal != context.Schedulers[coreToSignal]._idleThread)
  171. {
  172. threadToSignal.Context.RequestInterrupt();
  173. }
  174. // If the core is idle, ensure that the idle thread is awaken.
  175. context.Schedulers[coreToSignal]._idleInterruptEvent.Set();
  176. scheduledCoresMask &= ~(1UL << coreToSignal);
  177. }
  178. }
  179. private void IdleThreadLoop()
  180. {
  181. while (_context.Running)
  182. {
  183. _state.NeedsScheduling = false;
  184. Thread.MemoryBarrier();
  185. KThread nextThread = PickNextThread(_state.SelectedThread);
  186. if (_idleThread != nextThread)
  187. {
  188. _idleThread.SchedulerWaitEvent.Reset();
  189. WaitHandle.SignalAndWait(nextThread.SchedulerWaitEvent, _idleThread.SchedulerWaitEvent);
  190. }
  191. _idleInterruptEvent.WaitOne();
  192. }
  193. lock (_idleInterruptEventLock)
  194. {
  195. _idleInterruptEvent.Dispose();
  196. _idleInterruptEvent = null;
  197. }
  198. }
  199. public void Schedule()
  200. {
  201. _state.NeedsScheduling = false;
  202. Thread.MemoryBarrier();
  203. KThread currentThread = KernelStatic.GetCurrentThread();
  204. KThread selectedThread = _state.SelectedThread;
  205. // If the thread is already scheduled and running on the core, we have nothing to do.
  206. if (currentThread == selectedThread)
  207. {
  208. return;
  209. }
  210. currentThread.SchedulerWaitEvent.Reset();
  211. currentThread.ThreadContext.Unlock();
  212. // Wake all the threads that might be waiting until this thread context is unlocked.
  213. for (int core = 0; core < CpuCoresCount; core++)
  214. {
  215. _context.Schedulers[core]._idleInterruptEvent.Set();
  216. }
  217. KThread nextThread = PickNextThread(selectedThread);
  218. if (currentThread.Context.Running)
  219. {
  220. // Wait until this thread is scheduled again, and allow the next thread to run.
  221. WaitHandle.SignalAndWait(nextThread.SchedulerWaitEvent, currentThread.SchedulerWaitEvent);
  222. }
  223. else
  224. {
  225. // Allow the next thread to run.
  226. nextThread.SchedulerWaitEvent.Set();
  227. // We don't need to wait since the thread is exiting, however we need to
  228. // make sure this thread will never call the scheduler again, since it is
  229. // no longer assigned to a core.
  230. currentThread.MakeUnschedulable();
  231. // Just to be sure, set the core to a invalid value.
  232. // This will trigger a exception if it attempts to call schedule again,
  233. // rather than leaving the scheduler in a invalid state.
  234. currentThread.CurrentCore = -1;
  235. }
  236. }
  237. private KThread PickNextThread(KThread selectedThread)
  238. {
  239. while (true)
  240. {
  241. if (selectedThread != null)
  242. {
  243. // Try to run the selected thread.
  244. // We need to acquire the context lock to be sure the thread is not
  245. // already running on another core. If it is, then we return here
  246. // and the caller should try again once there is something available for scheduling.
  247. // The thread currently running on the core should have been requested to
  248. // interrupt so this is not expected to take long.
  249. // The idle thread must also be paused if we are scheduling a thread
  250. // on the core, as the scheduled thread will handle the next switch.
  251. if (selectedThread.ThreadContext.Lock())
  252. {
  253. SwitchTo(selectedThread);
  254. if (!_state.NeedsScheduling)
  255. {
  256. return selectedThread;
  257. }
  258. selectedThread.ThreadContext.Unlock();
  259. }
  260. else
  261. {
  262. return _idleThread;
  263. }
  264. }
  265. else
  266. {
  267. // The core is idle now, make sure that the idle thread can run
  268. // and switch the core when a thread is available.
  269. SwitchTo(null);
  270. return _idleThread;
  271. }
  272. _state.NeedsScheduling = false;
  273. Thread.MemoryBarrier();
  274. selectedThread = _state.SelectedThread;
  275. }
  276. }
  277. private void SwitchTo(KThread nextThread)
  278. {
  279. KProcess currentProcess = KernelStatic.GetCurrentProcess();
  280. KThread currentThread = KernelStatic.GetCurrentThread();
  281. nextThread ??= _idleThread;
  282. if (currentThread == nextThread)
  283. {
  284. return;
  285. }
  286. long previousTicks = LastContextSwitchTime;
  287. long currentTicks = PerformanceCounter.ElapsedTicks;
  288. long ticksDelta = currentTicks - previousTicks;
  289. currentThread.AddCpuTime(ticksDelta);
  290. if (currentProcess != null)
  291. {
  292. currentProcess.AddCpuTime(ticksDelta);
  293. }
  294. LastContextSwitchTime = currentTicks;
  295. if (currentProcess != null)
  296. {
  297. _previousThread = !currentThread.TerminationRequested && currentThread.ActiveCore == _coreId ? currentThread : null;
  298. }
  299. else if (currentThread == _idleThread)
  300. {
  301. _previousThread = null;
  302. }
  303. if (nextThread.CurrentCore != _coreId)
  304. {
  305. nextThread.CurrentCore = _coreId;
  306. }
  307. _currentThread = nextThread;
  308. }
  309. public static void PreemptionThreadLoop(KernelContext context)
  310. {
  311. while (context.Running)
  312. {
  313. context.CriticalSection.Enter();
  314. for (int core = 0; core < CpuCoresCount; core++)
  315. {
  316. RotateScheduledQueue(context, core, PreemptionPriorities[core]);
  317. }
  318. context.CriticalSection.Leave();
  319. Thread.Sleep(RoundRobinTimeQuantumMs);
  320. }
  321. }
  322. private static void RotateScheduledQueue(KernelContext context, int core, int prio)
  323. {
  324. IEnumerable<KThread> scheduledThreads = context.PriorityQueue.ScheduledThreads(core);
  325. KThread selectedThread = scheduledThreads.FirstOrDefault(x => x.DynamicPriority == prio);
  326. KThread nextThread = null;
  327. // Yield priority queue.
  328. if (selectedThread != null)
  329. {
  330. nextThread = context.PriorityQueue.Reschedule(prio, core, selectedThread);
  331. }
  332. IEnumerable<KThread> SuitableCandidates()
  333. {
  334. foreach (KThread suggested in context.PriorityQueue.SuggestedThreads(core))
  335. {
  336. int suggestedCore = suggested.ActiveCore;
  337. if (suggestedCore >= 0)
  338. {
  339. KThread selectedSuggestedCore = context.PriorityQueue.ScheduledThreads(suggestedCore).FirstOrDefault();
  340. if (selectedSuggestedCore == suggested || (selectedSuggestedCore != null && selectedSuggestedCore.DynamicPriority < 2))
  341. {
  342. continue;
  343. }
  344. }
  345. // If the candidate was scheduled after the current thread, then it's not worth it.
  346. if (nextThread == selectedThread ||
  347. nextThread == null ||
  348. nextThread.LastScheduledTime >= suggested.LastScheduledTime)
  349. {
  350. yield return suggested;
  351. }
  352. }
  353. }
  354. // Select candidate threads that could run on this core.
  355. // Only take into account threads that are not yet selected.
  356. KThread dst = SuitableCandidates().FirstOrDefault(x => x.DynamicPriority == prio);
  357. if (dst != null)
  358. {
  359. context.PriorityQueue.TransferToCore(prio, core, dst);
  360. }
  361. // If the priority of the currently selected thread is lower or same as the preemption priority,
  362. // then try to migrate a thread with lower priority.
  363. KThread bestCandidate = context.PriorityQueue.ScheduledThreads(core).FirstOrDefault();
  364. if (bestCandidate != null && bestCandidate.DynamicPriority >= prio)
  365. {
  366. dst = SuitableCandidates().FirstOrDefault(x => x.DynamicPriority < bestCandidate.DynamicPriority);
  367. if (dst != null)
  368. {
  369. context.PriorityQueue.TransferToCore(dst.DynamicPriority, core, dst);
  370. }
  371. }
  372. context.ThreadReselectionRequested = true;
  373. }
  374. public static void Yield(KernelContext context)
  375. {
  376. KThread currentThread = KernelStatic.GetCurrentThread();
  377. context.CriticalSection.Enter();
  378. if (currentThread.SchedFlags != ThreadSchedState.Running)
  379. {
  380. context.CriticalSection.Leave();
  381. return;
  382. }
  383. KThread nextThread = context.PriorityQueue.Reschedule(currentThread.DynamicPriority, currentThread.ActiveCore, currentThread);
  384. if (nextThread != currentThread)
  385. {
  386. context.ThreadReselectionRequested = true;
  387. }
  388. context.CriticalSection.Leave();
  389. }
  390. public static void YieldWithLoadBalancing(KernelContext context)
  391. {
  392. KThread currentThread = KernelStatic.GetCurrentThread();
  393. context.CriticalSection.Enter();
  394. if (currentThread.SchedFlags != ThreadSchedState.Running)
  395. {
  396. context.CriticalSection.Leave();
  397. return;
  398. }
  399. int prio = currentThread.DynamicPriority;
  400. int core = currentThread.ActiveCore;
  401. // Move current thread to the end of the queue.
  402. KThread nextThread = context.PriorityQueue.Reschedule(prio, core, currentThread);
  403. IEnumerable<KThread> SuitableCandidates()
  404. {
  405. foreach (KThread suggested in context.PriorityQueue.SuggestedThreads(core))
  406. {
  407. int suggestedCore = suggested.ActiveCore;
  408. if (suggestedCore >= 0)
  409. {
  410. KThread selectedSuggestedCore = context.Schedulers[suggestedCore]._state.SelectedThread;
  411. if (selectedSuggestedCore == suggested || (selectedSuggestedCore != null && selectedSuggestedCore.DynamicPriority < 2))
  412. {
  413. continue;
  414. }
  415. }
  416. // If the candidate was scheduled after the current thread, then it's not worth it,
  417. // unless the priority is higher than the current one.
  418. if (suggested.LastScheduledTime <= nextThread.LastScheduledTime ||
  419. suggested.DynamicPriority < nextThread.DynamicPriority)
  420. {
  421. yield return suggested;
  422. }
  423. }
  424. }
  425. KThread dst = SuitableCandidates().FirstOrDefault(x => x.DynamicPriority <= prio);
  426. if (dst != null)
  427. {
  428. context.PriorityQueue.TransferToCore(dst.DynamicPriority, core, dst);
  429. context.ThreadReselectionRequested = true;
  430. }
  431. else if (currentThread != nextThread)
  432. {
  433. context.ThreadReselectionRequested = true;
  434. }
  435. context.CriticalSection.Leave();
  436. }
  437. public static void YieldToAnyThread(KernelContext context)
  438. {
  439. KThread currentThread = KernelStatic.GetCurrentThread();
  440. context.CriticalSection.Enter();
  441. if (currentThread.SchedFlags != ThreadSchedState.Running)
  442. {
  443. context.CriticalSection.Leave();
  444. return;
  445. }
  446. int core = currentThread.ActiveCore;
  447. context.PriorityQueue.TransferToCore(currentThread.DynamicPriority, -1, currentThread);
  448. if (!context.PriorityQueue.ScheduledThreads(core).Any())
  449. {
  450. KThread selectedThread = null;
  451. foreach (KThread suggested in context.PriorityQueue.SuggestedThreads(core))
  452. {
  453. int suggestedCore = suggested.ActiveCore;
  454. if (suggestedCore < 0)
  455. {
  456. continue;
  457. }
  458. KThread firstCandidate = context.PriorityQueue.ScheduledThreads(suggestedCore).FirstOrDefault();
  459. if (firstCandidate == suggested)
  460. {
  461. continue;
  462. }
  463. if (firstCandidate == null || firstCandidate.DynamicPriority >= 2)
  464. {
  465. context.PriorityQueue.TransferToCore(suggested.DynamicPriority, core, suggested);
  466. }
  467. selectedThread = suggested;
  468. break;
  469. }
  470. if (currentThread != selectedThread)
  471. {
  472. context.ThreadReselectionRequested = true;
  473. }
  474. }
  475. else
  476. {
  477. context.ThreadReselectionRequested = true;
  478. }
  479. context.CriticalSection.Leave();
  480. }
  481. public void Dispose()
  482. {
  483. // Ensure that the idle thread is not blocked and can exit.
  484. lock (_idleInterruptEventLock)
  485. {
  486. if (_idleInterruptEvent != null)
  487. {
  488. _idleInterruptEvent.Set();
  489. }
  490. }
  491. }
  492. }
  493. }