KThread.cs 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438
  1. using Ryujinx.Common.Logging;
  2. using Ryujinx.Cpu;
  3. using Ryujinx.HLE.HOS.Kernel.Common;
  4. using Ryujinx.HLE.HOS.Kernel.Process;
  5. using Ryujinx.HLE.HOS.Kernel.SupervisorCall;
  6. using Ryujinx.Horizon.Common;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Numerics;
  10. using System.Threading;
  11. namespace Ryujinx.HLE.HOS.Kernel.Threading
  12. {
  13. class KThread : KSynchronizationObject, IKFutureSchedulerObject
  14. {
  15. private const int TlsUserDisableCountOffset = 0x100;
  16. private const int TlsUserInterruptFlagOffset = 0x102;
  17. public const int MaxWaitSyncObjects = 64;
  18. private ManualResetEvent _schedulerWaitEvent;
  19. public ManualResetEvent SchedulerWaitEvent => _schedulerWaitEvent;
  20. public Thread HostThread { get; private set; }
  21. public IExecutionContext Context { get; private set; }
  22. public KThreadContext ThreadContext { get; private set; }
  23. public int DynamicPriority { get; set; }
  24. public ulong AffinityMask { get; set; }
  25. public ulong ThreadUid { get; private set; }
  26. private long _totalTimeRunning;
  27. public long TotalTimeRunning => _totalTimeRunning;
  28. public KSynchronizationObject SignaledObj { get; set; }
  29. public ulong CondVarAddress { get; set; }
  30. private ulong _entrypoint;
  31. private ThreadStart _customThreadStart;
  32. private bool _forcedUnschedulable;
  33. public bool IsSchedulable => _customThreadStart == null && !_forcedUnschedulable;
  34. public ulong MutexAddress { get; set; }
  35. public int KernelWaitersCount { get; private set; }
  36. public KProcess Owner { get; private set; }
  37. private ulong _tlsAddress;
  38. public ulong TlsAddress => _tlsAddress;
  39. public KSynchronizationObject[] WaitSyncObjects { get; }
  40. public int[] WaitSyncHandles { get; }
  41. public long LastScheduledTime { get; set; }
  42. public LinkedListNode<KThread>[] SiblingsPerCore { get; private set; }
  43. public LinkedList<KThread> Withholder { get; set; }
  44. public LinkedListNode<KThread> WithholderNode { get; set; }
  45. public LinkedListNode<KThread> ProcessListNode { get; set; }
  46. private LinkedList<KThread> _mutexWaiters;
  47. private LinkedListNode<KThread> _mutexWaiterNode;
  48. private LinkedList<KThread> _pinnedWaiters;
  49. public KThread MutexOwner { get; private set; }
  50. public int ThreadHandleForUserMutex { get; set; }
  51. private ThreadSchedState _forcePauseFlags;
  52. private ThreadSchedState _forcePausePermissionFlags;
  53. public Result ObjSyncResult { get; set; }
  54. public int BasePriority { get; set; }
  55. public int PreferredCore { get; set; }
  56. public int CurrentCore { get; set; }
  57. public int ActiveCore { get; set; }
  58. public bool IsPinned { get; private set; }
  59. private ulong _originalAffinityMask;
  60. private int _originalPreferredCore;
  61. private int _originalBasePriority;
  62. private int _coreMigrationDisableCount;
  63. public ThreadSchedState SchedFlags { get; private set; }
  64. private int _shallBeTerminated;
  65. private bool ShallBeTerminated => _shallBeTerminated != 0;
  66. public bool TerminationRequested => ShallBeTerminated || SchedFlags == ThreadSchedState.TerminationPending;
  67. public bool SyncCancelled { get; set; }
  68. public bool WaitingSync { get; set; }
  69. private int _hasExited;
  70. private bool _hasBeenInitialized;
  71. private bool _hasBeenReleased;
  72. public bool WaitingInArbitration { get; set; }
  73. private object _activityOperationLock;
  74. public KThread(KernelContext context) : base(context)
  75. {
  76. WaitSyncObjects = new KSynchronizationObject[MaxWaitSyncObjects];
  77. WaitSyncHandles = new int[MaxWaitSyncObjects];
  78. SiblingsPerCore = new LinkedListNode<KThread>[KScheduler.CpuCoresCount];
  79. _mutexWaiters = new LinkedList<KThread>();
  80. _pinnedWaiters = new LinkedList<KThread>();
  81. _activityOperationLock = new object();
  82. }
  83. public Result Initialize(
  84. ulong entrypoint,
  85. ulong argsPtr,
  86. ulong stackTop,
  87. int priority,
  88. int cpuCore,
  89. KProcess owner,
  90. ThreadType type,
  91. ThreadStart customThreadStart = null)
  92. {
  93. if ((uint)type > 3)
  94. {
  95. throw new ArgumentException($"Invalid thread type \"{type}\".");
  96. }
  97. PreferredCore = cpuCore;
  98. AffinityMask |= 1UL << cpuCore;
  99. SchedFlags = type == ThreadType.Dummy
  100. ? ThreadSchedState.Running
  101. : ThreadSchedState.None;
  102. ActiveCore = cpuCore;
  103. ObjSyncResult = KernelResult.ThreadNotStarted;
  104. DynamicPriority = priority;
  105. BasePriority = priority;
  106. CurrentCore = cpuCore;
  107. IsPinned = false;
  108. _entrypoint = entrypoint;
  109. _customThreadStart = customThreadStart;
  110. if (type == ThreadType.User)
  111. {
  112. if (owner.AllocateThreadLocalStorage(out _tlsAddress) != Result.Success)
  113. {
  114. return KernelResult.OutOfMemory;
  115. }
  116. MemoryHelper.FillWithZeros(owner.CpuMemory, _tlsAddress, KTlsPageInfo.TlsEntrySize);
  117. }
  118. bool is64Bits;
  119. if (owner != null)
  120. {
  121. Owner = owner;
  122. owner.IncrementReferenceCount();
  123. owner.IncrementThreadCount();
  124. is64Bits = owner.Flags.HasFlag(ProcessCreationFlags.Is64Bit);
  125. }
  126. else
  127. {
  128. is64Bits = true;
  129. }
  130. HostThread = new Thread(ThreadStart);
  131. Context = owner?.CreateExecutionContext() ?? new ProcessExecutionContext();
  132. ThreadContext = new KThreadContext(Context);
  133. Context.IsAarch32 = !is64Bits;
  134. Context.SetX(0, argsPtr);
  135. if (is64Bits)
  136. {
  137. Context.SetX(18, KSystemControl.GenerateRandom() | 1);
  138. Context.SetX(31, stackTop);
  139. }
  140. else
  141. {
  142. Context.SetX(13, (uint)stackTop);
  143. }
  144. Context.TpidrroEl0 = (long)_tlsAddress;
  145. ThreadUid = KernelContext.NewThreadUid();
  146. HostThread.Name = customThreadStart != null ? $"HLE.OsThread.{ThreadUid}" : $"HLE.GuestThread.{ThreadUid}";
  147. _hasBeenInitialized = true;
  148. _forcePausePermissionFlags = ThreadSchedState.ForcePauseMask;
  149. if (owner != null)
  150. {
  151. owner.AddThread(this);
  152. if (owner.IsPaused)
  153. {
  154. KernelContext.CriticalSection.Enter();
  155. if (TerminationRequested)
  156. {
  157. KernelContext.CriticalSection.Leave();
  158. return Result.Success;
  159. }
  160. _forcePauseFlags |= ThreadSchedState.ProcessPauseFlag;
  161. CombineForcePauseFlags();
  162. KernelContext.CriticalSection.Leave();
  163. }
  164. }
  165. return Result.Success;
  166. }
  167. public Result Start()
  168. {
  169. if (!KernelContext.KernelInitialized)
  170. {
  171. KernelContext.CriticalSection.Enter();
  172. if (!TerminationRequested)
  173. {
  174. _forcePauseFlags |= ThreadSchedState.KernelInitPauseFlag;
  175. CombineForcePauseFlags();
  176. }
  177. KernelContext.CriticalSection.Leave();
  178. }
  179. Result result = KernelResult.ThreadTerminating;
  180. KernelContext.CriticalSection.Enter();
  181. if (!ShallBeTerminated)
  182. {
  183. KThread currentThread = KernelStatic.GetCurrentThread();
  184. while (SchedFlags != ThreadSchedState.TerminationPending && (currentThread == null || !currentThread.TerminationRequested))
  185. {
  186. if ((SchedFlags & ThreadSchedState.LowMask) != ThreadSchedState.None)
  187. {
  188. result = KernelResult.InvalidState;
  189. break;
  190. }
  191. if (currentThread == null || currentThread._forcePauseFlags == ThreadSchedState.None)
  192. {
  193. if (Owner != null && _forcePauseFlags != ThreadSchedState.None)
  194. {
  195. CombineForcePauseFlags();
  196. }
  197. SetNewSchedFlags(ThreadSchedState.Running);
  198. StartHostThread();
  199. result = Result.Success;
  200. break;
  201. }
  202. else
  203. {
  204. currentThread.CombineForcePauseFlags();
  205. KernelContext.CriticalSection.Leave();
  206. KernelContext.CriticalSection.Enter();
  207. if (currentThread.ShallBeTerminated)
  208. {
  209. break;
  210. }
  211. }
  212. }
  213. }
  214. KernelContext.CriticalSection.Leave();
  215. return result;
  216. }
  217. public ThreadSchedState PrepareForTermination()
  218. {
  219. KernelContext.CriticalSection.Enter();
  220. if (Owner != null && Owner.PinnedThreads[KernelStatic.GetCurrentThread().CurrentCore] == this)
  221. {
  222. Owner.UnpinThread(this);
  223. }
  224. ThreadSchedState result;
  225. if (Interlocked.Exchange(ref _shallBeTerminated, 1) == 0)
  226. {
  227. if ((SchedFlags & ThreadSchedState.LowMask) == ThreadSchedState.None)
  228. {
  229. SchedFlags = ThreadSchedState.TerminationPending;
  230. }
  231. else
  232. {
  233. if (_forcePauseFlags != ThreadSchedState.None)
  234. {
  235. _forcePauseFlags &= ~ThreadSchedState.ThreadPauseFlag;
  236. ThreadSchedState oldSchedFlags = SchedFlags;
  237. SchedFlags &= ThreadSchedState.LowMask;
  238. AdjustScheduling(oldSchedFlags);
  239. }
  240. if (BasePriority >= 0x10)
  241. {
  242. SetPriority(0xF);
  243. }
  244. if ((SchedFlags & ThreadSchedState.LowMask) == ThreadSchedState.Running)
  245. {
  246. // TODO: GIC distributor stuffs (sgir changes ect)
  247. Context.RequestInterrupt();
  248. }
  249. SignaledObj = null;
  250. ObjSyncResult = KernelResult.ThreadTerminating;
  251. ReleaseAndResume();
  252. }
  253. }
  254. result = SchedFlags;
  255. KernelContext.CriticalSection.Leave();
  256. return result & ThreadSchedState.LowMask;
  257. }
  258. public void Terminate()
  259. {
  260. ThreadSchedState state = PrepareForTermination();
  261. if (state != ThreadSchedState.TerminationPending)
  262. {
  263. KernelContext.Synchronization.WaitFor(new KSynchronizationObject[] { this }, -1, out _);
  264. }
  265. }
  266. public void HandlePostSyscall()
  267. {
  268. ThreadSchedState state;
  269. do
  270. {
  271. if (TerminationRequested)
  272. {
  273. Exit();
  274. // As the death of the thread is handled by the CPU emulator, we differ from the official kernel and return here.
  275. break;
  276. }
  277. KernelContext.CriticalSection.Enter();
  278. if (TerminationRequested)
  279. {
  280. state = ThreadSchedState.TerminationPending;
  281. }
  282. else
  283. {
  284. if (_forcePauseFlags != ThreadSchedState.None)
  285. {
  286. CombineForcePauseFlags();
  287. }
  288. state = ThreadSchedState.Running;
  289. }
  290. KernelContext.CriticalSection.Leave();
  291. } while (state == ThreadSchedState.TerminationPending);
  292. }
  293. public void Exit()
  294. {
  295. // TODO: Debug event.
  296. if (Owner != null)
  297. {
  298. Owner.ResourceLimit?.Release(LimitableResource.Thread, 0, 1);
  299. _hasBeenReleased = true;
  300. }
  301. KernelContext.CriticalSection.Enter();
  302. _forcePauseFlags &= ~ThreadSchedState.ForcePauseMask;
  303. _forcePausePermissionFlags = 0;
  304. bool decRef = ExitImpl();
  305. Context.StopRunning();
  306. KernelContext.CriticalSection.Leave();
  307. if (decRef)
  308. {
  309. DecrementReferenceCount();
  310. }
  311. }
  312. private bool ExitImpl()
  313. {
  314. KernelContext.CriticalSection.Enter();
  315. SetNewSchedFlags(ThreadSchedState.TerminationPending);
  316. bool decRef = Interlocked.Exchange(ref _hasExited, 1) == 0;
  317. Signal();
  318. KernelContext.CriticalSection.Leave();
  319. return decRef;
  320. }
  321. private int GetEffectiveRunningCore()
  322. {
  323. for (int coreNumber = 0; coreNumber < KScheduler.CpuCoresCount; coreNumber++)
  324. {
  325. if (KernelContext.Schedulers[coreNumber].CurrentThread == this)
  326. {
  327. return coreNumber;
  328. }
  329. }
  330. return -1;
  331. }
  332. public Result Sleep(long timeout)
  333. {
  334. KernelContext.CriticalSection.Enter();
  335. if (TerminationRequested)
  336. {
  337. KernelContext.CriticalSection.Leave();
  338. return KernelResult.ThreadTerminating;
  339. }
  340. SetNewSchedFlags(ThreadSchedState.Paused);
  341. if (timeout > 0)
  342. {
  343. KernelContext.TimeManager.ScheduleFutureInvocation(this, timeout);
  344. }
  345. KernelContext.CriticalSection.Leave();
  346. if (timeout > 0)
  347. {
  348. KernelContext.TimeManager.UnscheduleFutureInvocation(this);
  349. }
  350. return Result.Success;
  351. }
  352. public void SetPriority(int priority)
  353. {
  354. KernelContext.CriticalSection.Enter();
  355. if (IsPinned)
  356. {
  357. _originalBasePriority = priority;
  358. }
  359. else
  360. {
  361. BasePriority = priority;
  362. }
  363. UpdatePriorityInheritance();
  364. KernelContext.CriticalSection.Leave();
  365. }
  366. public void Suspend(ThreadSchedState type)
  367. {
  368. _forcePauseFlags |= type;
  369. CombineForcePauseFlags();
  370. }
  371. public void Resume(ThreadSchedState type)
  372. {
  373. ThreadSchedState oldForcePauseFlags = _forcePauseFlags;
  374. _forcePauseFlags &= ~type;
  375. if ((oldForcePauseFlags & ~type) == ThreadSchedState.None)
  376. {
  377. ThreadSchedState oldSchedFlags = SchedFlags;
  378. SchedFlags &= ThreadSchedState.LowMask;
  379. AdjustScheduling(oldSchedFlags);
  380. }
  381. }
  382. public Result SetActivity(bool pause)
  383. {
  384. lock (_activityOperationLock)
  385. {
  386. Result result = Result.Success;
  387. KernelContext.CriticalSection.Enter();
  388. ThreadSchedState lowNibble = SchedFlags & ThreadSchedState.LowMask;
  389. if (lowNibble != ThreadSchedState.Paused && lowNibble != ThreadSchedState.Running)
  390. {
  391. KernelContext.CriticalSection.Leave();
  392. return KernelResult.InvalidState;
  393. }
  394. if (!TerminationRequested)
  395. {
  396. if (pause)
  397. {
  398. // Pause, the force pause flag should be clear (thread is NOT paused).
  399. if ((_forcePauseFlags & ThreadSchedState.ThreadPauseFlag) == 0)
  400. {
  401. Suspend(ThreadSchedState.ThreadPauseFlag);
  402. }
  403. else
  404. {
  405. result = KernelResult.InvalidState;
  406. }
  407. }
  408. else
  409. {
  410. // Unpause, the force pause flag should be set (thread is paused).
  411. if ((_forcePauseFlags & ThreadSchedState.ThreadPauseFlag) != 0)
  412. {
  413. Resume(ThreadSchedState.ThreadPauseFlag);
  414. }
  415. else
  416. {
  417. result = KernelResult.InvalidState;
  418. }
  419. }
  420. }
  421. KernelContext.CriticalSection.Leave();
  422. if (result == Result.Success && pause)
  423. {
  424. bool isThreadRunning = true;
  425. while (isThreadRunning)
  426. {
  427. KernelContext.CriticalSection.Enter();
  428. if (TerminationRequested)
  429. {
  430. KernelContext.CriticalSection.Leave();
  431. break;
  432. }
  433. isThreadRunning = false;
  434. if (IsPinned)
  435. {
  436. KThread currentThread = KernelStatic.GetCurrentThread();
  437. if (currentThread.TerminationRequested)
  438. {
  439. KernelContext.CriticalSection.Leave();
  440. result = KernelResult.ThreadTerminating;
  441. break;
  442. }
  443. _pinnedWaiters.AddLast(currentThread);
  444. currentThread.Reschedule(ThreadSchedState.Paused);
  445. }
  446. else
  447. {
  448. isThreadRunning = GetEffectiveRunningCore() >= 0;
  449. }
  450. KernelContext.CriticalSection.Leave();
  451. }
  452. }
  453. return result;
  454. }
  455. }
  456. public Result GetThreadContext3(out ThreadContext context)
  457. {
  458. context = default;
  459. lock (_activityOperationLock)
  460. {
  461. KernelContext.CriticalSection.Enter();
  462. if ((_forcePauseFlags & ThreadSchedState.ThreadPauseFlag) == 0)
  463. {
  464. KernelContext.CriticalSection.Leave();
  465. return KernelResult.InvalidState;
  466. }
  467. if (!TerminationRequested)
  468. {
  469. context = GetCurrentContext();
  470. }
  471. KernelContext.CriticalSection.Leave();
  472. }
  473. return Result.Success;
  474. }
  475. private static uint GetPsr(IExecutionContext context)
  476. {
  477. return context.Pstate & 0xFF0FFE20;
  478. }
  479. private ThreadContext GetCurrentContext()
  480. {
  481. const int MaxRegistersAArch32 = 15;
  482. const int MaxFpuRegistersAArch32 = 16;
  483. ThreadContext context = new ThreadContext();
  484. if (Owner.Flags.HasFlag(ProcessCreationFlags.Is64Bit))
  485. {
  486. for (int i = 0; i < context.Registers.Length; i++)
  487. {
  488. context.Registers[i] = Context.GetX(i);
  489. }
  490. for (int i = 0; i < context.FpuRegisters.Length; i++)
  491. {
  492. context.FpuRegisters[i] = Context.GetV(i);
  493. }
  494. context.Fp = Context.GetX(29);
  495. context.Lr = Context.GetX(30);
  496. context.Sp = Context.GetX(31);
  497. context.Pc = Context.Pc;
  498. context.Pstate = GetPsr(Context);
  499. context.Tpidr = (ulong)Context.TpidrroEl0;
  500. }
  501. else
  502. {
  503. for (int i = 0; i < MaxRegistersAArch32; i++)
  504. {
  505. context.Registers[i] = (uint)Context.GetX(i);
  506. }
  507. for (int i = 0; i < MaxFpuRegistersAArch32; i++)
  508. {
  509. context.FpuRegisters[i] = Context.GetV(i);
  510. }
  511. context.Pc = (uint)Context.Pc;
  512. context.Pstate = GetPsr(Context);
  513. context.Tpidr = (uint)Context.TpidrroEl0;
  514. }
  515. context.Fpcr = (uint)Context.Fpcr;
  516. context.Fpsr = (uint)Context.Fpsr;
  517. return context;
  518. }
  519. public void CancelSynchronization()
  520. {
  521. KernelContext.CriticalSection.Enter();
  522. if ((SchedFlags & ThreadSchedState.LowMask) != ThreadSchedState.Paused || !WaitingSync)
  523. {
  524. SyncCancelled = true;
  525. }
  526. else if (Withholder != null)
  527. {
  528. Withholder.Remove(WithholderNode);
  529. SetNewSchedFlags(ThreadSchedState.Running);
  530. Withholder = null;
  531. SyncCancelled = true;
  532. }
  533. else
  534. {
  535. SignaledObj = null;
  536. ObjSyncResult = KernelResult.Cancelled;
  537. SetNewSchedFlags(ThreadSchedState.Running);
  538. SyncCancelled = false;
  539. }
  540. KernelContext.CriticalSection.Leave();
  541. }
  542. public Result SetCoreAndAffinityMask(int newCore, ulong newAffinityMask)
  543. {
  544. lock (_activityOperationLock)
  545. {
  546. KernelContext.CriticalSection.Enter();
  547. bool isCoreMigrationDisabled = _coreMigrationDisableCount != 0;
  548. // The value -3 is "do not change the preferred core".
  549. if (newCore == -3)
  550. {
  551. newCore = isCoreMigrationDisabled ? _originalPreferredCore : PreferredCore;
  552. if ((newAffinityMask & (1UL << newCore)) == 0)
  553. {
  554. KernelContext.CriticalSection.Leave();
  555. return KernelResult.InvalidCombination;
  556. }
  557. }
  558. if (isCoreMigrationDisabled)
  559. {
  560. _originalPreferredCore = newCore;
  561. _originalAffinityMask = newAffinityMask;
  562. }
  563. else
  564. {
  565. ulong oldAffinityMask = AffinityMask;
  566. PreferredCore = newCore;
  567. AffinityMask = newAffinityMask;
  568. if (oldAffinityMask != newAffinityMask)
  569. {
  570. int oldCore = ActiveCore;
  571. if (oldCore >= 0 && ((AffinityMask >> oldCore) & 1) == 0)
  572. {
  573. if (PreferredCore < 0)
  574. {
  575. ActiveCore = sizeof(ulong) * 8 - 1 - BitOperations.LeadingZeroCount(AffinityMask);
  576. }
  577. else
  578. {
  579. ActiveCore = PreferredCore;
  580. }
  581. }
  582. AdjustSchedulingForNewAffinity(oldAffinityMask, oldCore);
  583. }
  584. }
  585. KernelContext.CriticalSection.Leave();
  586. bool targetThreadPinned = true;
  587. while (targetThreadPinned)
  588. {
  589. KernelContext.CriticalSection.Enter();
  590. if (TerminationRequested)
  591. {
  592. KernelContext.CriticalSection.Leave();
  593. break;
  594. }
  595. targetThreadPinned = false;
  596. int coreNumber = GetEffectiveRunningCore();
  597. bool isPinnedThreadCurrentlyRunning = coreNumber >= 0;
  598. if (isPinnedThreadCurrentlyRunning && ((1UL << coreNumber) & AffinityMask) == 0)
  599. {
  600. if (IsPinned)
  601. {
  602. KThread currentThread = KernelStatic.GetCurrentThread();
  603. if (currentThread.TerminationRequested)
  604. {
  605. KernelContext.CriticalSection.Leave();
  606. return KernelResult.ThreadTerminating;
  607. }
  608. _pinnedWaiters.AddLast(currentThread);
  609. currentThread.Reschedule(ThreadSchedState.Paused);
  610. }
  611. else
  612. {
  613. targetThreadPinned = true;
  614. }
  615. }
  616. KernelContext.CriticalSection.Leave();
  617. }
  618. return Result.Success;
  619. }
  620. }
  621. private void CombineForcePauseFlags()
  622. {
  623. ThreadSchedState oldFlags = SchedFlags;
  624. ThreadSchedState lowNibble = SchedFlags & ThreadSchedState.LowMask;
  625. SchedFlags = lowNibble | (_forcePauseFlags & _forcePausePermissionFlags);
  626. AdjustScheduling(oldFlags);
  627. }
  628. private void SetNewSchedFlags(ThreadSchedState newFlags)
  629. {
  630. KernelContext.CriticalSection.Enter();
  631. ThreadSchedState oldFlags = SchedFlags;
  632. SchedFlags = (oldFlags & ThreadSchedState.HighMask) | newFlags;
  633. if ((oldFlags & ThreadSchedState.LowMask) != newFlags)
  634. {
  635. AdjustScheduling(oldFlags);
  636. }
  637. KernelContext.CriticalSection.Leave();
  638. }
  639. public void ReleaseAndResume()
  640. {
  641. KernelContext.CriticalSection.Enter();
  642. if ((SchedFlags & ThreadSchedState.LowMask) == ThreadSchedState.Paused)
  643. {
  644. if (Withholder != null)
  645. {
  646. Withholder.Remove(WithholderNode);
  647. SetNewSchedFlags(ThreadSchedState.Running);
  648. Withholder = null;
  649. }
  650. else
  651. {
  652. SetNewSchedFlags(ThreadSchedState.Running);
  653. }
  654. }
  655. KernelContext.CriticalSection.Leave();
  656. }
  657. public void Reschedule(ThreadSchedState newFlags)
  658. {
  659. KernelContext.CriticalSection.Enter();
  660. ThreadSchedState oldFlags = SchedFlags;
  661. SchedFlags = (oldFlags & ThreadSchedState.HighMask) |
  662. (newFlags & ThreadSchedState.LowMask);
  663. AdjustScheduling(oldFlags);
  664. KernelContext.CriticalSection.Leave();
  665. }
  666. public void AddMutexWaiter(KThread requester)
  667. {
  668. AddToMutexWaitersList(requester);
  669. requester.MutexOwner = this;
  670. UpdatePriorityInheritance();
  671. }
  672. public void RemoveMutexWaiter(KThread thread)
  673. {
  674. if (thread._mutexWaiterNode?.List != null)
  675. {
  676. _mutexWaiters.Remove(thread._mutexWaiterNode);
  677. }
  678. thread.MutexOwner = null;
  679. UpdatePriorityInheritance();
  680. }
  681. public KThread RelinquishMutex(ulong mutexAddress, out int count)
  682. {
  683. count = 0;
  684. if (_mutexWaiters.First == null)
  685. {
  686. return null;
  687. }
  688. KThread newMutexOwner = null;
  689. LinkedListNode<KThread> currentNode = _mutexWaiters.First;
  690. do
  691. {
  692. // Skip all threads that are not waiting for this mutex.
  693. while (currentNode != null && currentNode.Value.MutexAddress != mutexAddress)
  694. {
  695. currentNode = currentNode.Next;
  696. }
  697. if (currentNode == null)
  698. {
  699. break;
  700. }
  701. LinkedListNode<KThread> nextNode = currentNode.Next;
  702. _mutexWaiters.Remove(currentNode);
  703. currentNode.Value.MutexOwner = newMutexOwner;
  704. if (newMutexOwner != null)
  705. {
  706. // New owner was already selected, re-insert on new owner list.
  707. newMutexOwner.AddToMutexWaitersList(currentNode.Value);
  708. }
  709. else
  710. {
  711. // New owner not selected yet, use current thread.
  712. newMutexOwner = currentNode.Value;
  713. }
  714. count++;
  715. currentNode = nextNode;
  716. }
  717. while (currentNode != null);
  718. if (newMutexOwner != null)
  719. {
  720. UpdatePriorityInheritance();
  721. newMutexOwner.UpdatePriorityInheritance();
  722. }
  723. return newMutexOwner;
  724. }
  725. private void UpdatePriorityInheritance()
  726. {
  727. // If any of the threads waiting for the mutex has
  728. // higher priority than the current thread, then
  729. // the current thread inherits that priority.
  730. int highestPriority = BasePriority;
  731. if (_mutexWaiters.First != null)
  732. {
  733. int waitingDynamicPriority = _mutexWaiters.First.Value.DynamicPriority;
  734. if (waitingDynamicPriority < highestPriority)
  735. {
  736. highestPriority = waitingDynamicPriority;
  737. }
  738. }
  739. if (highestPriority != DynamicPriority)
  740. {
  741. int oldPriority = DynamicPriority;
  742. DynamicPriority = highestPriority;
  743. AdjustSchedulingForNewPriority(oldPriority);
  744. if (MutexOwner != null)
  745. {
  746. // Remove and re-insert to ensure proper sorting based on new priority.
  747. MutexOwner._mutexWaiters.Remove(_mutexWaiterNode);
  748. MutexOwner.AddToMutexWaitersList(this);
  749. MutexOwner.UpdatePriorityInheritance();
  750. }
  751. }
  752. }
  753. private void AddToMutexWaitersList(KThread thread)
  754. {
  755. LinkedListNode<KThread> nextPrio = _mutexWaiters.First;
  756. int currentPriority = thread.DynamicPriority;
  757. while (nextPrio != null && nextPrio.Value.DynamicPriority <= currentPriority)
  758. {
  759. nextPrio = nextPrio.Next;
  760. }
  761. if (nextPrio != null)
  762. {
  763. thread._mutexWaiterNode = _mutexWaiters.AddBefore(nextPrio, thread);
  764. }
  765. else
  766. {
  767. thread._mutexWaiterNode = _mutexWaiters.AddLast(thread);
  768. }
  769. }
  770. private void AdjustScheduling(ThreadSchedState oldFlags)
  771. {
  772. if (oldFlags == SchedFlags)
  773. {
  774. return;
  775. }
  776. if (!IsSchedulable)
  777. {
  778. if (!_forcedUnschedulable)
  779. {
  780. // Ensure our thread is running and we have an event.
  781. StartHostThread();
  782. // If the thread is not schedulable, we want to just run or pause
  783. // it directly as we don't care about priority or the core it is
  784. // running on in this case.
  785. if (SchedFlags == ThreadSchedState.Running)
  786. {
  787. _schedulerWaitEvent.Set();
  788. }
  789. else
  790. {
  791. _schedulerWaitEvent.Reset();
  792. }
  793. }
  794. return;
  795. }
  796. if (oldFlags == ThreadSchedState.Running)
  797. {
  798. // Was running, now it's stopped.
  799. if (ActiveCore >= 0)
  800. {
  801. KernelContext.PriorityQueue.Unschedule(DynamicPriority, ActiveCore, this);
  802. }
  803. for (int core = 0; core < KScheduler.CpuCoresCount; core++)
  804. {
  805. if (core != ActiveCore && ((AffinityMask >> core) & 1) != 0)
  806. {
  807. KernelContext.PriorityQueue.Unsuggest(DynamicPriority, core, this);
  808. }
  809. }
  810. }
  811. else if (SchedFlags == ThreadSchedState.Running)
  812. {
  813. // Was stopped, now it's running.
  814. if (ActiveCore >= 0)
  815. {
  816. KernelContext.PriorityQueue.Schedule(DynamicPriority, ActiveCore, this);
  817. }
  818. for (int core = 0; core < KScheduler.CpuCoresCount; core++)
  819. {
  820. if (core != ActiveCore && ((AffinityMask >> core) & 1) != 0)
  821. {
  822. KernelContext.PriorityQueue.Suggest(DynamicPriority, core, this);
  823. }
  824. }
  825. }
  826. KernelContext.ThreadReselectionRequested = true;
  827. }
  828. private void AdjustSchedulingForNewPriority(int oldPriority)
  829. {
  830. if (SchedFlags != ThreadSchedState.Running || !IsSchedulable)
  831. {
  832. return;
  833. }
  834. // Remove thread from the old priority queues.
  835. if (ActiveCore >= 0)
  836. {
  837. KernelContext.PriorityQueue.Unschedule(oldPriority, ActiveCore, this);
  838. }
  839. for (int core = 0; core < KScheduler.CpuCoresCount; core++)
  840. {
  841. if (core != ActiveCore && ((AffinityMask >> core) & 1) != 0)
  842. {
  843. KernelContext.PriorityQueue.Unsuggest(oldPriority, core, this);
  844. }
  845. }
  846. // Add thread to the new priority queues.
  847. KThread currentThread = KernelStatic.GetCurrentThread();
  848. if (ActiveCore >= 0)
  849. {
  850. if (currentThread == this)
  851. {
  852. KernelContext.PriorityQueue.SchedulePrepend(DynamicPriority, ActiveCore, this);
  853. }
  854. else
  855. {
  856. KernelContext.PriorityQueue.Schedule(DynamicPriority, ActiveCore, this);
  857. }
  858. }
  859. for (int core = 0; core < KScheduler.CpuCoresCount; core++)
  860. {
  861. if (core != ActiveCore && ((AffinityMask >> core) & 1) != 0)
  862. {
  863. KernelContext.PriorityQueue.Suggest(DynamicPriority, core, this);
  864. }
  865. }
  866. KernelContext.ThreadReselectionRequested = true;
  867. }
  868. private void AdjustSchedulingForNewAffinity(ulong oldAffinityMask, int oldCore)
  869. {
  870. if (SchedFlags != ThreadSchedState.Running || DynamicPriority >= KScheduler.PrioritiesCount || !IsSchedulable)
  871. {
  872. return;
  873. }
  874. // Remove thread from the old priority queues.
  875. for (int core = 0; core < KScheduler.CpuCoresCount; core++)
  876. {
  877. if (((oldAffinityMask >> core) & 1) != 0)
  878. {
  879. if (core == oldCore)
  880. {
  881. KernelContext.PriorityQueue.Unschedule(DynamicPriority, core, this);
  882. }
  883. else
  884. {
  885. KernelContext.PriorityQueue.Unsuggest(DynamicPriority, core, this);
  886. }
  887. }
  888. }
  889. // Add thread to the new priority queues.
  890. for (int core = 0; core < KScheduler.CpuCoresCount; core++)
  891. {
  892. if (((AffinityMask >> core) & 1) != 0)
  893. {
  894. if (core == ActiveCore)
  895. {
  896. KernelContext.PriorityQueue.Schedule(DynamicPriority, core, this);
  897. }
  898. else
  899. {
  900. KernelContext.PriorityQueue.Suggest(DynamicPriority, core, this);
  901. }
  902. }
  903. }
  904. KernelContext.ThreadReselectionRequested = true;
  905. }
  906. public void SetEntryArguments(long argsPtr, int threadHandle)
  907. {
  908. Context.SetX(0, (ulong)argsPtr);
  909. Context.SetX(1, (ulong)threadHandle);
  910. }
  911. public void TimeUp()
  912. {
  913. ReleaseAndResume();
  914. }
  915. public string GetGuestStackTrace()
  916. {
  917. return Owner.Debugger.GetGuestStackTrace(this);
  918. }
  919. public string GetGuestRegisterPrintout()
  920. {
  921. return Owner.Debugger.GetCpuRegisterPrintout(this);
  922. }
  923. public void PrintGuestStackTrace()
  924. {
  925. Logger.Info?.Print(LogClass.Cpu, $"Guest stack trace:\n{GetGuestStackTrace()}\n");
  926. }
  927. public void PrintGuestRegisterPrintout()
  928. {
  929. Logger.Info?.Print(LogClass.Cpu, $"Guest CPU registers:\n{GetGuestRegisterPrintout()}\n");
  930. }
  931. public void AddCpuTime(long ticks)
  932. {
  933. Interlocked.Add(ref _totalTimeRunning, ticks);
  934. }
  935. public void StartHostThread()
  936. {
  937. if (_schedulerWaitEvent == null)
  938. {
  939. var schedulerWaitEvent = new ManualResetEvent(false);
  940. if (Interlocked.Exchange(ref _schedulerWaitEvent, schedulerWaitEvent) == null)
  941. {
  942. HostThread.Start();
  943. }
  944. else
  945. {
  946. schedulerWaitEvent.Dispose();
  947. }
  948. }
  949. }
  950. private void ThreadStart()
  951. {
  952. _schedulerWaitEvent.WaitOne();
  953. KernelStatic.SetKernelContext(KernelContext, this);
  954. if (_customThreadStart != null)
  955. {
  956. _customThreadStart();
  957. // Ensure that anything trying to join the HLE thread is unblocked.
  958. Exit();
  959. HandlePostSyscall();
  960. }
  961. else
  962. {
  963. Owner.Context.Execute(Context, _entrypoint);
  964. }
  965. Context.Dispose();
  966. _schedulerWaitEvent.Dispose();
  967. }
  968. public void MakeUnschedulable()
  969. {
  970. _forcedUnschedulable = true;
  971. }
  972. public override bool IsSignaled()
  973. {
  974. return _hasExited != 0;
  975. }
  976. protected override void Destroy()
  977. {
  978. if (_hasBeenInitialized)
  979. {
  980. FreeResources();
  981. bool released = Owner != null || _hasBeenReleased;
  982. if (Owner != null)
  983. {
  984. Owner.ResourceLimit?.Release(LimitableResource.Thread, 1, released ? 0 : 1);
  985. Owner.DecrementReferenceCount();
  986. }
  987. else
  988. {
  989. KernelContext.ResourceLimit.Release(LimitableResource.Thread, 1, released ? 0 : 1);
  990. }
  991. }
  992. }
  993. private void FreeResources()
  994. {
  995. Owner?.RemoveThread(this);
  996. if (_tlsAddress != 0 && Owner.FreeThreadLocalStorage(_tlsAddress) != Result.Success)
  997. {
  998. throw new InvalidOperationException("Unexpected failure freeing thread local storage.");
  999. }
  1000. KernelContext.CriticalSection.Enter();
  1001. // Wake up all threads that may be waiting for a mutex being held by this thread.
  1002. foreach (KThread thread in _mutexWaiters)
  1003. {
  1004. thread.MutexOwner = null;
  1005. thread._originalPreferredCore = 0;
  1006. thread.ObjSyncResult = KernelResult.InvalidState;
  1007. thread.ReleaseAndResume();
  1008. }
  1009. KernelContext.CriticalSection.Leave();
  1010. Owner?.DecrementThreadCountAndTerminateIfZero();
  1011. }
  1012. public void Pin()
  1013. {
  1014. IsPinned = true;
  1015. _coreMigrationDisableCount++;
  1016. int activeCore = ActiveCore;
  1017. _originalPreferredCore = PreferredCore;
  1018. _originalAffinityMask = AffinityMask;
  1019. ActiveCore = CurrentCore;
  1020. PreferredCore = CurrentCore;
  1021. AffinityMask = 1UL << CurrentCore;
  1022. if (activeCore != CurrentCore || _originalAffinityMask != AffinityMask)
  1023. {
  1024. AdjustSchedulingForNewAffinity(_originalAffinityMask, activeCore);
  1025. }
  1026. _originalBasePriority = BasePriority;
  1027. BasePriority = Math.Min(_originalBasePriority, BitOperations.TrailingZeroCount(Owner.Capabilities.AllowedThreadPriosMask) - 1);
  1028. UpdatePriorityInheritance();
  1029. // Disallows thread pausing
  1030. _forcePausePermissionFlags &= ~ThreadSchedState.ThreadPauseFlag;
  1031. CombineForcePauseFlags();
  1032. // TODO: Assign reduced SVC permissions
  1033. }
  1034. public void Unpin()
  1035. {
  1036. IsPinned = false;
  1037. _coreMigrationDisableCount--;
  1038. ulong affinityMask = AffinityMask;
  1039. int activeCore = ActiveCore;
  1040. PreferredCore = _originalPreferredCore;
  1041. AffinityMask = _originalAffinityMask;
  1042. if (AffinityMask != affinityMask)
  1043. {
  1044. if ((AffinityMask & 1UL << ActiveCore) != 0)
  1045. {
  1046. if (PreferredCore >= 0)
  1047. {
  1048. ActiveCore = PreferredCore;
  1049. }
  1050. else
  1051. {
  1052. ActiveCore = sizeof(ulong) * 8 - 1 - BitOperations.LeadingZeroCount((ulong)AffinityMask);
  1053. }
  1054. AdjustSchedulingForNewAffinity(affinityMask, activeCore);
  1055. }
  1056. }
  1057. BasePriority = _originalBasePriority;
  1058. UpdatePriorityInheritance();
  1059. if (!TerminationRequested)
  1060. {
  1061. // Allows thread pausing
  1062. _forcePausePermissionFlags |= ThreadSchedState.ThreadPauseFlag;
  1063. CombineForcePauseFlags();
  1064. // TODO: Restore SVC permissions
  1065. }
  1066. // Wake up waiters
  1067. foreach (KThread waiter in _pinnedWaiters)
  1068. {
  1069. waiter.ReleaseAndResume();
  1070. }
  1071. _pinnedWaiters.Clear();
  1072. }
  1073. public void SynchronizePreemptionState()
  1074. {
  1075. KernelContext.CriticalSection.Enter();
  1076. if (Owner != null && Owner.PinnedThreads[CurrentCore] == this)
  1077. {
  1078. ClearUserInterruptFlag();
  1079. Owner.UnpinThread(this);
  1080. }
  1081. KernelContext.CriticalSection.Leave();
  1082. }
  1083. public ushort GetUserDisableCount()
  1084. {
  1085. return Owner.CpuMemory.Read<ushort>(_tlsAddress + TlsUserDisableCountOffset);
  1086. }
  1087. public void SetUserInterruptFlag()
  1088. {
  1089. Owner.CpuMemory.Write<ushort>(_tlsAddress + TlsUserInterruptFlagOffset, 1);
  1090. }
  1091. public void ClearUserInterruptFlag()
  1092. {
  1093. Owner.CpuMemory.Write<ushort>(_tlsAddress + TlsUserInterruptFlagOffset, 0);
  1094. }
  1095. }
  1096. }