KThread.cs 35 KB

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