KThread.cs 35 KB

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