KThread.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068
  1. using ChocolArm64;
  2. using ChocolArm64.Memory;
  3. using Ryujinx.HLE.HOS.Kernel.Common;
  4. using Ryujinx.HLE.HOS.Kernel.Process;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Linq;
  8. namespace Ryujinx.HLE.HOS.Kernel.Threading
  9. {
  10. class KThread : KSynchronizationObject, IKFutureSchedulerObject
  11. {
  12. public CpuThread Context { get; private set; }
  13. public long AffinityMask { get; set; }
  14. public long ThreadUid { get; private set; }
  15. public long TotalTimeRunning { get; set; }
  16. public KSynchronizationObject SignaledObj { get; set; }
  17. public ulong CondVarAddress { get; set; }
  18. private ulong _entrypoint;
  19. public ulong MutexAddress { get; set; }
  20. public KProcess Owner { get; private set; }
  21. private ulong _tlsAddress;
  22. public ulong TlsAddress => _tlsAddress;
  23. public ulong TlsDramAddress { get; private set; }
  24. public long LastScheduledTime { get; set; }
  25. public LinkedListNode<KThread>[] SiblingsPerCore { get; private set; }
  26. public LinkedList<KThread> Withholder { get; set; }
  27. public LinkedListNode<KThread> WithholderNode { get; set; }
  28. public LinkedListNode<KThread> ProcessListNode { get; set; }
  29. private LinkedList<KThread> _mutexWaiters;
  30. private LinkedListNode<KThread> _mutexWaiterNode;
  31. public KThread MutexOwner { get; private set; }
  32. public int ThreadHandleForUserMutex { get; set; }
  33. private ThreadSchedState _forcePauseFlags;
  34. public KernelResult ObjSyncResult { get; set; }
  35. public int DynamicPriority { get; set; }
  36. public int CurrentCore { get; set; }
  37. public int BasePriority { get; set; }
  38. public int PreferredCore { get; set; }
  39. private long _affinityMaskOverride;
  40. private int _preferredCoreOverride;
  41. private int _affinityOverrideCount;
  42. public ThreadSchedState SchedFlags { get; private set; }
  43. public bool ShallBeTerminated { get; private set; }
  44. public bool SyncCancelled { get; set; }
  45. public bool WaitingSync { get; set; }
  46. private bool _hasExited;
  47. private bool _hasBeenInitialized;
  48. private bool _hasBeenReleased;
  49. public bool WaitingInArbitration { get; set; }
  50. private KScheduler _scheduler;
  51. private KSchedulingData _schedulingData;
  52. public long LastPc { get; set; }
  53. public KThread(Horizon system) : base(system)
  54. {
  55. _scheduler = system.Scheduler;
  56. _schedulingData = system.Scheduler.SchedulingData;
  57. SiblingsPerCore = new LinkedListNode<KThread>[KScheduler.CpuCoresCount];
  58. _mutexWaiters = new LinkedList<KThread>();
  59. }
  60. public KernelResult Initialize(
  61. ulong entrypoint,
  62. ulong argsPtr,
  63. ulong stackTop,
  64. int priority,
  65. int defaultCpuCore,
  66. KProcess owner,
  67. ThreadType type = ThreadType.User)
  68. {
  69. if ((uint)type > 3)
  70. {
  71. throw new ArgumentException($"Invalid thread type \"{type}\".");
  72. }
  73. PreferredCore = defaultCpuCore;
  74. AffinityMask |= 1L << defaultCpuCore;
  75. SchedFlags = type == ThreadType.Dummy
  76. ? ThreadSchedState.Running
  77. : ThreadSchedState.None;
  78. CurrentCore = PreferredCore;
  79. DynamicPriority = priority;
  80. BasePriority = priority;
  81. ObjSyncResult = KernelResult.ThreadNotStarted;
  82. _entrypoint = entrypoint;
  83. if (type == ThreadType.User)
  84. {
  85. if (owner.AllocateThreadLocalStorage(out _tlsAddress) != KernelResult.Success)
  86. {
  87. return KernelResult.OutOfMemory;
  88. }
  89. TlsDramAddress = owner.MemoryManager.GetDramAddressFromVa(_tlsAddress);
  90. MemoryHelper.FillWithZeros(owner.CpuMemory, (long)_tlsAddress, KTlsPageInfo.TlsEntrySize);
  91. }
  92. bool is64Bits;
  93. if (owner != null)
  94. {
  95. Owner = owner;
  96. owner.IncrementReferenceCount();
  97. owner.IncrementThreadCount();
  98. is64Bits = (owner.MmuFlags & 1) != 0;
  99. }
  100. else
  101. {
  102. is64Bits = true;
  103. }
  104. Context = new CpuThread(owner.Translator, owner.CpuMemory, (long)entrypoint);
  105. Context.ThreadState.X0 = argsPtr;
  106. Context.ThreadState.X31 = stackTop;
  107. Context.ThreadState.CntfrqEl0 = 19200000;
  108. Context.ThreadState.Tpidr = (long)_tlsAddress;
  109. owner.SubscribeThreadEventHandlers(Context);
  110. Context.WorkFinished += ThreadFinishedHandler;
  111. ThreadUid = System.GetThreadUid();
  112. _hasBeenInitialized = true;
  113. if (owner != null)
  114. {
  115. owner.AddThread(this);
  116. if (owner.IsPaused)
  117. {
  118. System.CriticalSection.Enter();
  119. if (ShallBeTerminated || SchedFlags == ThreadSchedState.TerminationPending)
  120. {
  121. System.CriticalSection.Leave();
  122. return KernelResult.Success;
  123. }
  124. _forcePauseFlags |= ThreadSchedState.ProcessPauseFlag;
  125. CombineForcePauseFlags();
  126. System.CriticalSection.Leave();
  127. }
  128. }
  129. return KernelResult.Success;
  130. }
  131. public KernelResult Start()
  132. {
  133. if (!System.KernelInitialized)
  134. {
  135. System.CriticalSection.Enter();
  136. if (!ShallBeTerminated && SchedFlags != ThreadSchedState.TerminationPending)
  137. {
  138. _forcePauseFlags |= ThreadSchedState.KernelInitPauseFlag;
  139. CombineForcePauseFlags();
  140. }
  141. System.CriticalSection.Leave();
  142. }
  143. KernelResult result = KernelResult.ThreadTerminating;
  144. System.CriticalSection.Enter();
  145. if (!ShallBeTerminated)
  146. {
  147. KThread currentThread = System.Scheduler.GetCurrentThread();
  148. while (SchedFlags != ThreadSchedState.TerminationPending &&
  149. currentThread.SchedFlags != ThreadSchedState.TerminationPending &&
  150. !currentThread.ShallBeTerminated)
  151. {
  152. if ((SchedFlags & ThreadSchedState.LowMask) != ThreadSchedState.None)
  153. {
  154. result = KernelResult.InvalidState;
  155. break;
  156. }
  157. if (currentThread._forcePauseFlags == ThreadSchedState.None)
  158. {
  159. if (Owner != null && _forcePauseFlags != ThreadSchedState.None)
  160. {
  161. CombineForcePauseFlags();
  162. }
  163. SetNewSchedFlags(ThreadSchedState.Running);
  164. result = KernelResult.Success;
  165. break;
  166. }
  167. else
  168. {
  169. currentThread.CombineForcePauseFlags();
  170. System.CriticalSection.Leave();
  171. System.CriticalSection.Enter();
  172. if (currentThread.ShallBeTerminated)
  173. {
  174. break;
  175. }
  176. }
  177. }
  178. }
  179. System.CriticalSection.Leave();
  180. return result;
  181. }
  182. public void Exit()
  183. {
  184. //TODO: Debug event.
  185. if (Owner != null)
  186. {
  187. Owner.ResourceLimit?.Release(LimitableResource.Thread, 0, 1);
  188. _hasBeenReleased = true;
  189. }
  190. System.CriticalSection.Enter();
  191. _forcePauseFlags &= ~ThreadSchedState.ForcePauseMask;
  192. ExitImpl();
  193. System.CriticalSection.Leave();
  194. DecrementReferenceCount();
  195. }
  196. private void ExitImpl()
  197. {
  198. System.CriticalSection.Enter();
  199. SetNewSchedFlags(ThreadSchedState.TerminationPending);
  200. _hasExited = true;
  201. Signal();
  202. System.CriticalSection.Leave();
  203. }
  204. public KernelResult Sleep(long timeout)
  205. {
  206. System.CriticalSection.Enter();
  207. if (ShallBeTerminated || SchedFlags == ThreadSchedState.TerminationPending)
  208. {
  209. System.CriticalSection.Leave();
  210. return KernelResult.ThreadTerminating;
  211. }
  212. SetNewSchedFlags(ThreadSchedState.Paused);
  213. if (timeout > 0)
  214. {
  215. System.TimeManager.ScheduleFutureInvocation(this, timeout);
  216. }
  217. System.CriticalSection.Leave();
  218. if (timeout > 0)
  219. {
  220. System.TimeManager.UnscheduleFutureInvocation(this);
  221. }
  222. return 0;
  223. }
  224. public void Yield()
  225. {
  226. System.CriticalSection.Enter();
  227. if (SchedFlags != ThreadSchedState.Running)
  228. {
  229. System.CriticalSection.Leave();
  230. System.Scheduler.ContextSwitch();
  231. return;
  232. }
  233. if (DynamicPriority < KScheduler.PrioritiesCount)
  234. {
  235. //Move current thread to the end of the queue.
  236. _schedulingData.Reschedule(DynamicPriority, CurrentCore, this);
  237. }
  238. _scheduler.ThreadReselectionRequested = true;
  239. System.CriticalSection.Leave();
  240. System.Scheduler.ContextSwitch();
  241. }
  242. public void YieldWithLoadBalancing()
  243. {
  244. System.CriticalSection.Enter();
  245. if (SchedFlags != ThreadSchedState.Running)
  246. {
  247. System.CriticalSection.Leave();
  248. System.Scheduler.ContextSwitch();
  249. return;
  250. }
  251. int prio = DynamicPriority;
  252. int core = CurrentCore;
  253. KThread nextThreadOnCurrentQueue = null;
  254. if (DynamicPriority < KScheduler.PrioritiesCount)
  255. {
  256. //Move current thread to the end of the queue.
  257. _schedulingData.Reschedule(prio, core, this);
  258. Func<KThread, bool> predicate = x => x.DynamicPriority == prio;
  259. nextThreadOnCurrentQueue = _schedulingData.ScheduledThreads(core).FirstOrDefault(predicate);
  260. }
  261. IEnumerable<KThread> SuitableCandidates()
  262. {
  263. foreach (KThread thread in _schedulingData.SuggestedThreads(core))
  264. {
  265. int srcCore = thread.CurrentCore;
  266. if (srcCore >= 0)
  267. {
  268. KThread selectedSrcCore = _scheduler.CoreContexts[srcCore].SelectedThread;
  269. if (selectedSrcCore == thread || ((selectedSrcCore?.DynamicPriority ?? 2) < 2))
  270. {
  271. continue;
  272. }
  273. }
  274. //If the candidate was scheduled after the current thread, then it's not worth it,
  275. //unless the priority is higher than the current one.
  276. if (nextThreadOnCurrentQueue.LastScheduledTime >= thread.LastScheduledTime ||
  277. nextThreadOnCurrentQueue.DynamicPriority < thread.DynamicPriority)
  278. {
  279. yield return thread;
  280. }
  281. }
  282. }
  283. KThread dst = SuitableCandidates().FirstOrDefault(x => x.DynamicPriority <= prio);
  284. if (dst != null)
  285. {
  286. _schedulingData.TransferToCore(dst.DynamicPriority, core, dst);
  287. _scheduler.ThreadReselectionRequested = true;
  288. }
  289. if (this != nextThreadOnCurrentQueue)
  290. {
  291. _scheduler.ThreadReselectionRequested = true;
  292. }
  293. System.CriticalSection.Leave();
  294. System.Scheduler.ContextSwitch();
  295. }
  296. public void YieldAndWaitForLoadBalancing()
  297. {
  298. System.CriticalSection.Enter();
  299. if (SchedFlags != ThreadSchedState.Running)
  300. {
  301. System.CriticalSection.Leave();
  302. System.Scheduler.ContextSwitch();
  303. return;
  304. }
  305. int core = CurrentCore;
  306. _schedulingData.TransferToCore(DynamicPriority, -1, this);
  307. KThread selectedThread = null;
  308. if (!_schedulingData.ScheduledThreads(core).Any())
  309. {
  310. foreach (KThread thread in _schedulingData.SuggestedThreads(core))
  311. {
  312. if (thread.CurrentCore < 0)
  313. {
  314. continue;
  315. }
  316. KThread firstCandidate = _schedulingData.ScheduledThreads(thread.CurrentCore).FirstOrDefault();
  317. if (firstCandidate == thread)
  318. {
  319. continue;
  320. }
  321. if (firstCandidate == null || firstCandidate.DynamicPriority >= 2)
  322. {
  323. _schedulingData.TransferToCore(thread.DynamicPriority, core, thread);
  324. selectedThread = thread;
  325. }
  326. break;
  327. }
  328. }
  329. if (selectedThread != this)
  330. {
  331. _scheduler.ThreadReselectionRequested = true;
  332. }
  333. System.CriticalSection.Leave();
  334. System.Scheduler.ContextSwitch();
  335. }
  336. public void SetPriority(int priority)
  337. {
  338. System.CriticalSection.Enter();
  339. BasePriority = priority;
  340. UpdatePriorityInheritance();
  341. System.CriticalSection.Leave();
  342. }
  343. public KernelResult SetActivity(bool pause)
  344. {
  345. KernelResult result = KernelResult.Success;
  346. System.CriticalSection.Enter();
  347. ThreadSchedState lowNibble = SchedFlags & ThreadSchedState.LowMask;
  348. if (lowNibble != ThreadSchedState.Paused && lowNibble != ThreadSchedState.Running)
  349. {
  350. System.CriticalSection.Leave();
  351. return KernelResult.InvalidState;
  352. }
  353. System.CriticalSection.Enter();
  354. if (!ShallBeTerminated && SchedFlags != ThreadSchedState.TerminationPending)
  355. {
  356. if (pause)
  357. {
  358. //Pause, the force pause flag should be clear (thread is NOT paused).
  359. if ((_forcePauseFlags & ThreadSchedState.ThreadPauseFlag) == 0)
  360. {
  361. _forcePauseFlags |= ThreadSchedState.ThreadPauseFlag;
  362. CombineForcePauseFlags();
  363. }
  364. else
  365. {
  366. result = KernelResult.InvalidState;
  367. }
  368. }
  369. else
  370. {
  371. //Unpause, the force pause flag should be set (thread is paused).
  372. if ((_forcePauseFlags & ThreadSchedState.ThreadPauseFlag) != 0)
  373. {
  374. ThreadSchedState oldForcePauseFlags = _forcePauseFlags;
  375. _forcePauseFlags &= ~ThreadSchedState.ThreadPauseFlag;
  376. if ((oldForcePauseFlags & ~ThreadSchedState.ThreadPauseFlag) == ThreadSchedState.None)
  377. {
  378. ThreadSchedState oldSchedFlags = SchedFlags;
  379. SchedFlags &= ThreadSchedState.LowMask;
  380. AdjustScheduling(oldSchedFlags);
  381. }
  382. }
  383. else
  384. {
  385. result = KernelResult.InvalidState;
  386. }
  387. }
  388. }
  389. System.CriticalSection.Leave();
  390. System.CriticalSection.Leave();
  391. return result;
  392. }
  393. public void CancelSynchronization()
  394. {
  395. System.CriticalSection.Enter();
  396. if ((SchedFlags & ThreadSchedState.LowMask) != ThreadSchedState.Paused || !WaitingSync)
  397. {
  398. SyncCancelled = true;
  399. }
  400. else if (Withholder != null)
  401. {
  402. Withholder.Remove(WithholderNode);
  403. SetNewSchedFlags(ThreadSchedState.Running);
  404. Withholder = null;
  405. SyncCancelled = true;
  406. }
  407. else
  408. {
  409. SignaledObj = null;
  410. ObjSyncResult = KernelResult.Cancelled;
  411. SetNewSchedFlags(ThreadSchedState.Running);
  412. SyncCancelled = false;
  413. }
  414. System.CriticalSection.Leave();
  415. }
  416. public KernelResult SetCoreAndAffinityMask(int newCore, long newAffinityMask)
  417. {
  418. System.CriticalSection.Enter();
  419. bool useOverride = _affinityOverrideCount != 0;
  420. //The value -3 is "do not change the preferred core".
  421. if (newCore == -3)
  422. {
  423. newCore = useOverride ? _preferredCoreOverride : PreferredCore;
  424. if ((newAffinityMask & (1 << newCore)) == 0)
  425. {
  426. System.CriticalSection.Leave();
  427. return KernelResult.InvalidCombination;
  428. }
  429. }
  430. if (useOverride)
  431. {
  432. _preferredCoreOverride = newCore;
  433. _affinityMaskOverride = newAffinityMask;
  434. }
  435. else
  436. {
  437. long oldAffinityMask = AffinityMask;
  438. PreferredCore = newCore;
  439. AffinityMask = newAffinityMask;
  440. if (oldAffinityMask != newAffinityMask)
  441. {
  442. int oldCore = CurrentCore;
  443. if (CurrentCore >= 0 && ((AffinityMask >> CurrentCore) & 1) == 0)
  444. {
  445. if (PreferredCore < 0)
  446. {
  447. CurrentCore = HighestSetCore(AffinityMask);
  448. }
  449. else
  450. {
  451. CurrentCore = PreferredCore;
  452. }
  453. }
  454. AdjustSchedulingForNewAffinity(oldAffinityMask, oldCore);
  455. }
  456. }
  457. System.CriticalSection.Leave();
  458. return KernelResult.Success;
  459. }
  460. private static int HighestSetCore(long mask)
  461. {
  462. for (int core = KScheduler.CpuCoresCount - 1; core >= 0; core--)
  463. {
  464. if (((mask >> core) & 1) != 0)
  465. {
  466. return core;
  467. }
  468. }
  469. return -1;
  470. }
  471. private void CombineForcePauseFlags()
  472. {
  473. ThreadSchedState oldFlags = SchedFlags;
  474. ThreadSchedState lowNibble = SchedFlags & ThreadSchedState.LowMask;
  475. SchedFlags = lowNibble | _forcePauseFlags;
  476. AdjustScheduling(oldFlags);
  477. }
  478. private void SetNewSchedFlags(ThreadSchedState newFlags)
  479. {
  480. System.CriticalSection.Enter();
  481. ThreadSchedState oldFlags = SchedFlags;
  482. SchedFlags = (oldFlags & ThreadSchedState.HighMask) | newFlags;
  483. if ((oldFlags & ThreadSchedState.LowMask) != newFlags)
  484. {
  485. AdjustScheduling(oldFlags);
  486. }
  487. System.CriticalSection.Leave();
  488. }
  489. public void ReleaseAndResume()
  490. {
  491. System.CriticalSection.Enter();
  492. if ((SchedFlags & ThreadSchedState.LowMask) == ThreadSchedState.Paused)
  493. {
  494. if (Withholder != null)
  495. {
  496. Withholder.Remove(WithholderNode);
  497. SetNewSchedFlags(ThreadSchedState.Running);
  498. Withholder = null;
  499. }
  500. else
  501. {
  502. SetNewSchedFlags(ThreadSchedState.Running);
  503. }
  504. }
  505. System.CriticalSection.Leave();
  506. }
  507. public void Reschedule(ThreadSchedState newFlags)
  508. {
  509. System.CriticalSection.Enter();
  510. ThreadSchedState oldFlags = SchedFlags;
  511. SchedFlags = (oldFlags & ThreadSchedState.HighMask) |
  512. (newFlags & ThreadSchedState.LowMask);
  513. AdjustScheduling(oldFlags);
  514. System.CriticalSection.Leave();
  515. }
  516. public void AddMutexWaiter(KThread requester)
  517. {
  518. AddToMutexWaitersList(requester);
  519. requester.MutexOwner = this;
  520. UpdatePriorityInheritance();
  521. }
  522. public void RemoveMutexWaiter(KThread thread)
  523. {
  524. if (thread._mutexWaiterNode?.List != null)
  525. {
  526. _mutexWaiters.Remove(thread._mutexWaiterNode);
  527. }
  528. thread.MutexOwner = null;
  529. UpdatePriorityInheritance();
  530. }
  531. public KThread RelinquishMutex(ulong mutexAddress, out int count)
  532. {
  533. count = 0;
  534. if (_mutexWaiters.First == null)
  535. {
  536. return null;
  537. }
  538. KThread newMutexOwner = null;
  539. LinkedListNode<KThread> currentNode = _mutexWaiters.First;
  540. do
  541. {
  542. //Skip all threads that are not waiting for this mutex.
  543. while (currentNode != null && currentNode.Value.MutexAddress != mutexAddress)
  544. {
  545. currentNode = currentNode.Next;
  546. }
  547. if (currentNode == null)
  548. {
  549. break;
  550. }
  551. LinkedListNode<KThread> nextNode = currentNode.Next;
  552. _mutexWaiters.Remove(currentNode);
  553. currentNode.Value.MutexOwner = newMutexOwner;
  554. if (newMutexOwner != null)
  555. {
  556. //New owner was already selected, re-insert on new owner list.
  557. newMutexOwner.AddToMutexWaitersList(currentNode.Value);
  558. }
  559. else
  560. {
  561. //New owner not selected yet, use current thread.
  562. newMutexOwner = currentNode.Value;
  563. }
  564. count++;
  565. currentNode = nextNode;
  566. }
  567. while (currentNode != null);
  568. if (newMutexOwner != null)
  569. {
  570. UpdatePriorityInheritance();
  571. newMutexOwner.UpdatePriorityInheritance();
  572. }
  573. return newMutexOwner;
  574. }
  575. private void UpdatePriorityInheritance()
  576. {
  577. //If any of the threads waiting for the mutex has
  578. //higher priority than the current thread, then
  579. //the current thread inherits that priority.
  580. int highestPriority = BasePriority;
  581. if (_mutexWaiters.First != null)
  582. {
  583. int waitingDynamicPriority = _mutexWaiters.First.Value.DynamicPriority;
  584. if (waitingDynamicPriority < highestPriority)
  585. {
  586. highestPriority = waitingDynamicPriority;
  587. }
  588. }
  589. if (highestPriority != DynamicPriority)
  590. {
  591. int oldPriority = DynamicPriority;
  592. DynamicPriority = highestPriority;
  593. AdjustSchedulingForNewPriority(oldPriority);
  594. if (MutexOwner != null)
  595. {
  596. //Remove and re-insert to ensure proper sorting based on new priority.
  597. MutexOwner._mutexWaiters.Remove(_mutexWaiterNode);
  598. MutexOwner.AddToMutexWaitersList(this);
  599. MutexOwner.UpdatePriorityInheritance();
  600. }
  601. }
  602. }
  603. private void AddToMutexWaitersList(KThread thread)
  604. {
  605. LinkedListNode<KThread> nextPrio = _mutexWaiters.First;
  606. int currentPriority = thread.DynamicPriority;
  607. while (nextPrio != null && nextPrio.Value.DynamicPriority <= currentPriority)
  608. {
  609. nextPrio = nextPrio.Next;
  610. }
  611. if (nextPrio != null)
  612. {
  613. thread._mutexWaiterNode = _mutexWaiters.AddBefore(nextPrio, thread);
  614. }
  615. else
  616. {
  617. thread._mutexWaiterNode = _mutexWaiters.AddLast(thread);
  618. }
  619. }
  620. private void AdjustScheduling(ThreadSchedState oldFlags)
  621. {
  622. if (oldFlags == SchedFlags)
  623. {
  624. return;
  625. }
  626. if (oldFlags == ThreadSchedState.Running)
  627. {
  628. //Was running, now it's stopped.
  629. if (CurrentCore >= 0)
  630. {
  631. _schedulingData.Unschedule(DynamicPriority, CurrentCore, this);
  632. }
  633. for (int core = 0; core < KScheduler.CpuCoresCount; core++)
  634. {
  635. if (core != CurrentCore && ((AffinityMask >> core) & 1) != 0)
  636. {
  637. _schedulingData.Unsuggest(DynamicPriority, core, this);
  638. }
  639. }
  640. }
  641. else if (SchedFlags == ThreadSchedState.Running)
  642. {
  643. //Was stopped, now it's running.
  644. if (CurrentCore >= 0)
  645. {
  646. _schedulingData.Schedule(DynamicPriority, CurrentCore, this);
  647. }
  648. for (int core = 0; core < KScheduler.CpuCoresCount; core++)
  649. {
  650. if (core != CurrentCore && ((AffinityMask >> core) & 1) != 0)
  651. {
  652. _schedulingData.Suggest(DynamicPriority, core, this);
  653. }
  654. }
  655. }
  656. _scheduler.ThreadReselectionRequested = true;
  657. }
  658. private void AdjustSchedulingForNewPriority(int oldPriority)
  659. {
  660. if (SchedFlags != ThreadSchedState.Running)
  661. {
  662. return;
  663. }
  664. //Remove thread from the old priority queues.
  665. if (CurrentCore >= 0)
  666. {
  667. _schedulingData.Unschedule(oldPriority, CurrentCore, this);
  668. }
  669. for (int core = 0; core < KScheduler.CpuCoresCount; core++)
  670. {
  671. if (core != CurrentCore && ((AffinityMask >> core) & 1) != 0)
  672. {
  673. _schedulingData.Unsuggest(oldPriority, core, this);
  674. }
  675. }
  676. //Add thread to the new priority queues.
  677. KThread currentThread = _scheduler.GetCurrentThread();
  678. if (CurrentCore >= 0)
  679. {
  680. if (currentThread == this)
  681. {
  682. _schedulingData.SchedulePrepend(DynamicPriority, CurrentCore, this);
  683. }
  684. else
  685. {
  686. _schedulingData.Schedule(DynamicPriority, CurrentCore, this);
  687. }
  688. }
  689. for (int core = 0; core < KScheduler.CpuCoresCount; core++)
  690. {
  691. if (core != CurrentCore && ((AffinityMask >> core) & 1) != 0)
  692. {
  693. _schedulingData.Suggest(DynamicPriority, core, this);
  694. }
  695. }
  696. _scheduler.ThreadReselectionRequested = true;
  697. }
  698. private void AdjustSchedulingForNewAffinity(long oldAffinityMask, int oldCore)
  699. {
  700. if (SchedFlags != ThreadSchedState.Running || DynamicPriority >= KScheduler.PrioritiesCount)
  701. {
  702. return;
  703. }
  704. //Remove thread from the old priority queues.
  705. for (int core = 0; core < KScheduler.CpuCoresCount; core++)
  706. {
  707. if (((oldAffinityMask >> core) & 1) != 0)
  708. {
  709. if (core == oldCore)
  710. {
  711. _schedulingData.Unschedule(DynamicPriority, core, this);
  712. }
  713. else
  714. {
  715. _schedulingData.Unsuggest(DynamicPriority, core, this);
  716. }
  717. }
  718. }
  719. //Add thread to the new priority queues.
  720. for (int core = 0; core < KScheduler.CpuCoresCount; core++)
  721. {
  722. if (((AffinityMask >> core) & 1) != 0)
  723. {
  724. if (core == CurrentCore)
  725. {
  726. _schedulingData.Schedule(DynamicPriority, core, this);
  727. }
  728. else
  729. {
  730. _schedulingData.Suggest(DynamicPriority, core, this);
  731. }
  732. }
  733. }
  734. _scheduler.ThreadReselectionRequested = true;
  735. }
  736. public void SetEntryArguments(long argsPtr, int threadHandle)
  737. {
  738. Context.ThreadState.X0 = (ulong)argsPtr;
  739. Context.ThreadState.X1 = (ulong)threadHandle;
  740. }
  741. public void ClearExclusive()
  742. {
  743. Owner.CpuMemory.ClearExclusive(CurrentCore);
  744. }
  745. public void TimeUp()
  746. {
  747. ReleaseAndResume();
  748. }
  749. public void PrintGuestStackTrace()
  750. {
  751. Owner.Debugger.PrintGuestStackTrace(Context.ThreadState);
  752. }
  753. private void ThreadFinishedHandler(object sender, EventArgs e)
  754. {
  755. System.Scheduler.ExitThread(this);
  756. System.Scheduler.RemoveThread(this);
  757. }
  758. public override bool IsSignaled()
  759. {
  760. return _hasExited;
  761. }
  762. protected override void Destroy()
  763. {
  764. if (_hasBeenInitialized)
  765. {
  766. FreeResources();
  767. bool released = Owner != null || _hasBeenReleased;
  768. if (Owner != null)
  769. {
  770. Owner.ResourceLimit?.Release(LimitableResource.Thread, 1, released ? 0 : 1);
  771. Owner.DecrementReferenceCount();
  772. }
  773. else
  774. {
  775. System.ResourceLimit.Release(LimitableResource.Thread, 1, released ? 0 : 1);
  776. }
  777. }
  778. }
  779. private void FreeResources()
  780. {
  781. Owner?.RemoveThread(this);
  782. if (_tlsAddress != 0 && Owner.FreeThreadLocalStorage(_tlsAddress) != KernelResult.Success)
  783. {
  784. throw new InvalidOperationException("Unexpected failure freeing thread local storage.");
  785. }
  786. System.CriticalSection.Enter();
  787. //Wake up all threads that may be waiting for a mutex being held by this thread.
  788. foreach (KThread thread in _mutexWaiters)
  789. {
  790. thread.MutexOwner = null;
  791. thread._preferredCoreOverride = 0;
  792. thread.ObjSyncResult = KernelResult.InvalidState;
  793. thread.ReleaseAndResume();
  794. }
  795. System.CriticalSection.Leave();
  796. Owner?.DecrementThreadCountAndTerminateIfZero();
  797. }
  798. }
  799. }