KScheduler.cs 23 KB

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