KThread.cs 30 KB

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