KScheduler.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632
  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 volatile bool NeedsScheduling;
  21. public volatile 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. long previousTicks = LastContextSwitchTime;
  285. long currentTicks = PerformanceCounter.ElapsedTicks;
  286. long ticksDelta = currentTicks - previousTicks;
  287. currentThread.AddCpuTime(ticksDelta);
  288. if (currentProcess != null)
  289. {
  290. currentProcess.AddCpuTime(ticksDelta);
  291. }
  292. LastContextSwitchTime = currentTicks;
  293. if (currentProcess != null)
  294. {
  295. _previousThread = !currentThread.TerminationRequested && currentThread.ActiveCore == _coreId ? currentThread : null;
  296. }
  297. else if (currentThread == _idleThread)
  298. {
  299. _previousThread = null;
  300. }
  301. }
  302. if (nextThread.CurrentCore != _coreId)
  303. {
  304. nextThread.CurrentCore = _coreId;
  305. }
  306. _currentThread = nextThread;
  307. }
  308. public static void PreemptionThreadLoop(KernelContext context)
  309. {
  310. while (context.Running)
  311. {
  312. context.CriticalSection.Enter();
  313. for (int core = 0; core < CpuCoresCount; core++)
  314. {
  315. RotateScheduledQueue(context, core, PreemptionPriorities[core]);
  316. }
  317. context.CriticalSection.Leave();
  318. Thread.Sleep(RoundRobinTimeQuantumMs);
  319. }
  320. }
  321. private static void RotateScheduledQueue(KernelContext context, int core, int prio)
  322. {
  323. IEnumerable<KThread> scheduledThreads = context.PriorityQueue.ScheduledThreads(core);
  324. KThread selectedThread = scheduledThreads.FirstOrDefault(x => x.DynamicPriority == prio);
  325. KThread nextThread = null;
  326. // Yield priority queue.
  327. if (selectedThread != null)
  328. {
  329. nextThread = context.PriorityQueue.Reschedule(prio, core, selectedThread);
  330. }
  331. IEnumerable<KThread> SuitableCandidates()
  332. {
  333. foreach (KThread suggested in context.PriorityQueue.SuggestedThreads(core))
  334. {
  335. int suggestedCore = suggested.ActiveCore;
  336. if (suggestedCore >= 0)
  337. {
  338. KThread selectedSuggestedCore = context.PriorityQueue.ScheduledThreads(suggestedCore).FirstOrDefault();
  339. if (selectedSuggestedCore == suggested || (selectedSuggestedCore != null && selectedSuggestedCore.DynamicPriority < 2))
  340. {
  341. continue;
  342. }
  343. }
  344. // If the candidate was scheduled after the current thread, then it's not worth it.
  345. if (nextThread == selectedThread ||
  346. nextThread == null ||
  347. nextThread.LastScheduledTime >= suggested.LastScheduledTime)
  348. {
  349. yield return suggested;
  350. }
  351. }
  352. }
  353. // Select candidate threads that could run on this core.
  354. // Only take into account threads that are not yet selected.
  355. KThread dst = SuitableCandidates().FirstOrDefault(x => x.DynamicPriority == prio);
  356. if (dst != null)
  357. {
  358. context.PriorityQueue.TransferToCore(prio, core, dst);
  359. }
  360. // If the priority of the currently selected thread is lower or same as the preemption priority,
  361. // then try to migrate a thread with lower priority.
  362. KThread bestCandidate = context.PriorityQueue.ScheduledThreads(core).FirstOrDefault();
  363. if (bestCandidate != null && bestCandidate.DynamicPriority >= prio)
  364. {
  365. dst = SuitableCandidates().FirstOrDefault(x => x.DynamicPriority < bestCandidate.DynamicPriority);
  366. if (dst != null)
  367. {
  368. context.PriorityQueue.TransferToCore(dst.DynamicPriority, core, dst);
  369. }
  370. }
  371. context.ThreadReselectionRequested = true;
  372. }
  373. public static void Yield(KernelContext context)
  374. {
  375. KThread currentThread = KernelStatic.GetCurrentThread();
  376. if (!currentThread.IsSchedulable)
  377. {
  378. return;
  379. }
  380. context.CriticalSection.Enter();
  381. if (currentThread.SchedFlags != ThreadSchedState.Running)
  382. {
  383. context.CriticalSection.Leave();
  384. return;
  385. }
  386. KThread nextThread = context.PriorityQueue.Reschedule(currentThread.DynamicPriority, currentThread.ActiveCore, currentThread);
  387. if (nextThread != currentThread)
  388. {
  389. context.ThreadReselectionRequested = true;
  390. }
  391. context.CriticalSection.Leave();
  392. }
  393. public static void YieldWithLoadBalancing(KernelContext context)
  394. {
  395. KThread currentThread = KernelStatic.GetCurrentThread();
  396. if (!currentThread.IsSchedulable)
  397. {
  398. return;
  399. }
  400. context.CriticalSection.Enter();
  401. if (currentThread.SchedFlags != ThreadSchedState.Running)
  402. {
  403. context.CriticalSection.Leave();
  404. return;
  405. }
  406. int prio = currentThread.DynamicPriority;
  407. int core = currentThread.ActiveCore;
  408. // Move current thread to the end of the queue.
  409. KThread nextThread = context.PriorityQueue.Reschedule(prio, core, currentThread);
  410. IEnumerable<KThread> SuitableCandidates()
  411. {
  412. foreach (KThread suggested in context.PriorityQueue.SuggestedThreads(core))
  413. {
  414. int suggestedCore = suggested.ActiveCore;
  415. if (suggestedCore >= 0)
  416. {
  417. KThread selectedSuggestedCore = context.Schedulers[suggestedCore]._state.SelectedThread;
  418. if (selectedSuggestedCore == suggested || (selectedSuggestedCore != null && selectedSuggestedCore.DynamicPriority < 2))
  419. {
  420. continue;
  421. }
  422. }
  423. // If the candidate was scheduled after the current thread, then it's not worth it,
  424. // unless the priority is higher than the current one.
  425. if (suggested.LastScheduledTime <= nextThread.LastScheduledTime ||
  426. suggested.DynamicPriority < nextThread.DynamicPriority)
  427. {
  428. yield return suggested;
  429. }
  430. }
  431. }
  432. KThread dst = SuitableCandidates().FirstOrDefault(x => x.DynamicPriority <= prio);
  433. if (dst != null)
  434. {
  435. context.PriorityQueue.TransferToCore(dst.DynamicPriority, core, dst);
  436. context.ThreadReselectionRequested = true;
  437. }
  438. else if (currentThread != nextThread)
  439. {
  440. context.ThreadReselectionRequested = true;
  441. }
  442. context.CriticalSection.Leave();
  443. }
  444. public static void YieldToAnyThread(KernelContext context)
  445. {
  446. KThread currentThread = KernelStatic.GetCurrentThread();
  447. if (!currentThread.IsSchedulable)
  448. {
  449. return;
  450. }
  451. context.CriticalSection.Enter();
  452. if (currentThread.SchedFlags != ThreadSchedState.Running)
  453. {
  454. context.CriticalSection.Leave();
  455. return;
  456. }
  457. int core = currentThread.ActiveCore;
  458. context.PriorityQueue.TransferToCore(currentThread.DynamicPriority, -1, currentThread);
  459. if (!context.PriorityQueue.ScheduledThreads(core).Any())
  460. {
  461. KThread selectedThread = null;
  462. foreach (KThread suggested in context.PriorityQueue.SuggestedThreads(core))
  463. {
  464. int suggestedCore = suggested.ActiveCore;
  465. if (suggestedCore < 0)
  466. {
  467. continue;
  468. }
  469. KThread firstCandidate = context.PriorityQueue.ScheduledThreads(suggestedCore).FirstOrDefault();
  470. if (firstCandidate == suggested)
  471. {
  472. continue;
  473. }
  474. if (firstCandidate == null || firstCandidate.DynamicPriority >= 2)
  475. {
  476. context.PriorityQueue.TransferToCore(suggested.DynamicPriority, core, suggested);
  477. }
  478. selectedThread = suggested;
  479. break;
  480. }
  481. if (currentThread != selectedThread)
  482. {
  483. context.ThreadReselectionRequested = true;
  484. }
  485. }
  486. else
  487. {
  488. context.ThreadReselectionRequested = true;
  489. }
  490. context.CriticalSection.Leave();
  491. }
  492. public void Dispose()
  493. {
  494. // Ensure that the idle thread is not blocked and can exit.
  495. lock (_idleInterruptEventLock)
  496. {
  497. if (_idleInterruptEvent != null)
  498. {
  499. _idleInterruptEvent.Set();
  500. }
  501. }
  502. }
  503. }
  504. }