KThread.cs 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212
  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. Context.Dispose();
  855. ThreadExit();
  856. }
  857. private void ThreadExit()
  858. {
  859. System.Scheduler.ExitThread(this);
  860. System.Scheduler.RemoveThread(this);
  861. }
  862. public bool IsCurrentHostThread()
  863. {
  864. return Thread.CurrentThread == HostThread;
  865. }
  866. public override bool IsSignaled()
  867. {
  868. return _hasExited;
  869. }
  870. protected override void Destroy()
  871. {
  872. if (_hasBeenInitialized)
  873. {
  874. FreeResources();
  875. bool released = Owner != null || _hasBeenReleased;
  876. if (Owner != null)
  877. {
  878. Owner.ResourceLimit?.Release(LimitableResource.Thread, 1, released ? 0 : 1);
  879. Owner.DecrementReferenceCount();
  880. }
  881. else
  882. {
  883. System.ResourceLimit.Release(LimitableResource.Thread, 1, released ? 0 : 1);
  884. }
  885. }
  886. }
  887. private void FreeResources()
  888. {
  889. Owner?.RemoveThread(this);
  890. if (_tlsAddress != 0 && Owner.FreeThreadLocalStorage(_tlsAddress) != KernelResult.Success)
  891. {
  892. throw new InvalidOperationException("Unexpected failure freeing thread local storage.");
  893. }
  894. System.CriticalSection.Enter();
  895. // Wake up all threads that may be waiting for a mutex being held by this thread.
  896. foreach (KThread thread in _mutexWaiters)
  897. {
  898. thread.MutexOwner = null;
  899. thread._preferredCoreOverride = 0;
  900. thread.ObjSyncResult = KernelResult.InvalidState;
  901. thread.ReleaseAndResume();
  902. }
  903. System.CriticalSection.Leave();
  904. Owner?.DecrementThreadCountAndTerminateIfZero();
  905. }
  906. }
  907. }