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; private set; }
  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. this.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. this.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. }