KScheduler.cs 23 KB

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