KAddressArbiter.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650
  1. using System.Collections.Generic;
  2. using System.Linq;
  3. using static Ryujinx.HLE.HOS.ErrorCode;
  4. namespace Ryujinx.HLE.HOS.Kernel
  5. {
  6. class KAddressArbiter
  7. {
  8. private const int HasListenersMask = 0x40000000;
  9. private Horizon System;
  10. public List<KThread> CondVarThreads;
  11. public List<KThread> ArbiterThreads;
  12. public KAddressArbiter(Horizon System)
  13. {
  14. this.System = System;
  15. CondVarThreads = new List<KThread>();
  16. ArbiterThreads = new List<KThread>();
  17. }
  18. public long ArbitrateLock(int OwnerHandle, long MutexAddress, int RequesterHandle)
  19. {
  20. KThread CurrentThread = System.Scheduler.GetCurrentThread();
  21. System.CriticalSection.Enter();
  22. CurrentThread.SignaledObj = null;
  23. CurrentThread.ObjSyncResult = 0;
  24. KProcess CurrentProcess = System.Scheduler.GetCurrentProcess();
  25. if (!KernelTransfer.UserToKernelInt32(System, MutexAddress, out int MutexValue))
  26. {
  27. System.CriticalSection.Leave();
  28. return MakeError(ErrorModule.Kernel, KernelErr.NoAccessPerm);;
  29. }
  30. if (MutexValue != (OwnerHandle | HasListenersMask))
  31. {
  32. System.CriticalSection.Leave();
  33. return 0;
  34. }
  35. KThread MutexOwner = CurrentProcess.HandleTable.GetObject<KThread>(OwnerHandle);
  36. if (MutexOwner == null)
  37. {
  38. System.CriticalSection.Leave();
  39. return MakeError(ErrorModule.Kernel, KernelErr.InvalidHandle);
  40. }
  41. CurrentThread.MutexAddress = MutexAddress;
  42. CurrentThread.ThreadHandleForUserMutex = RequesterHandle;
  43. MutexOwner.AddMutexWaiter(CurrentThread);
  44. CurrentThread.Reschedule(ThreadSchedState.Paused);
  45. System.CriticalSection.Leave();
  46. System.CriticalSection.Enter();
  47. if (CurrentThread.MutexOwner != null)
  48. {
  49. CurrentThread.MutexOwner.RemoveMutexWaiter(CurrentThread);
  50. }
  51. System.CriticalSection.Leave();
  52. return (uint)CurrentThread.ObjSyncResult;
  53. }
  54. public long ArbitrateUnlock(long MutexAddress)
  55. {
  56. System.CriticalSection.Enter();
  57. KThread CurrentThread = System.Scheduler.GetCurrentThread();
  58. (long Result, KThread NewOwnerThread) = MutexUnlock(CurrentThread, MutexAddress);
  59. if (Result != 0 && NewOwnerThread != null)
  60. {
  61. NewOwnerThread.SignaledObj = null;
  62. NewOwnerThread.ObjSyncResult = (int)Result;
  63. }
  64. System.CriticalSection.Leave();
  65. return Result;
  66. }
  67. public long WaitProcessWideKeyAtomic(
  68. long MutexAddress,
  69. long CondVarAddress,
  70. int ThreadHandle,
  71. long Timeout)
  72. {
  73. System.CriticalSection.Enter();
  74. KThread CurrentThread = System.Scheduler.GetCurrentThread();
  75. CurrentThread.SignaledObj = null;
  76. CurrentThread.ObjSyncResult = (int)MakeError(ErrorModule.Kernel, KernelErr.Timeout);
  77. if (CurrentThread.ShallBeTerminated ||
  78. CurrentThread.SchedFlags == ThreadSchedState.TerminationPending)
  79. {
  80. System.CriticalSection.Leave();
  81. return MakeError(ErrorModule.Kernel, KernelErr.ThreadTerminating);
  82. }
  83. (long Result, _) = MutexUnlock(CurrentThread, MutexAddress);
  84. if (Result != 0)
  85. {
  86. System.CriticalSection.Leave();
  87. return Result;
  88. }
  89. CurrentThread.MutexAddress = MutexAddress;
  90. CurrentThread.ThreadHandleForUserMutex = ThreadHandle;
  91. CurrentThread.CondVarAddress = CondVarAddress;
  92. CondVarThreads.Add(CurrentThread);
  93. if (Timeout != 0)
  94. {
  95. CurrentThread.Reschedule(ThreadSchedState.Paused);
  96. if (Timeout > 0)
  97. {
  98. System.TimeManager.ScheduleFutureInvocation(CurrentThread, Timeout);
  99. }
  100. }
  101. System.CriticalSection.Leave();
  102. if (Timeout > 0)
  103. {
  104. System.TimeManager.UnscheduleFutureInvocation(CurrentThread);
  105. }
  106. System.CriticalSection.Enter();
  107. if (CurrentThread.MutexOwner != null)
  108. {
  109. CurrentThread.MutexOwner.RemoveMutexWaiter(CurrentThread);
  110. }
  111. CondVarThreads.Remove(CurrentThread);
  112. System.CriticalSection.Leave();
  113. return (uint)CurrentThread.ObjSyncResult;
  114. }
  115. private (long, KThread) MutexUnlock(KThread CurrentThread, long MutexAddress)
  116. {
  117. KThread NewOwnerThread = CurrentThread.RelinquishMutex(MutexAddress, out int Count);
  118. int MutexValue = 0;
  119. if (NewOwnerThread != null)
  120. {
  121. MutexValue = NewOwnerThread.ThreadHandleForUserMutex;
  122. if (Count >= 2)
  123. {
  124. MutexValue |= HasListenersMask;
  125. }
  126. NewOwnerThread.SignaledObj = null;
  127. NewOwnerThread.ObjSyncResult = 0;
  128. NewOwnerThread.ReleaseAndResume();
  129. }
  130. long Result = 0;
  131. if (!KernelTransfer.KernelToUserInt32(System, MutexAddress, MutexValue))
  132. {
  133. Result = MakeError(ErrorModule.Kernel, KernelErr.NoAccessPerm);
  134. }
  135. return (Result, NewOwnerThread);
  136. }
  137. public void SignalProcessWideKey(long Address, int Count)
  138. {
  139. Queue<KThread> SignaledThreads = new Queue<KThread>();
  140. System.CriticalSection.Enter();
  141. IOrderedEnumerable<KThread> SortedThreads = CondVarThreads.OrderBy(x => x.DynamicPriority);
  142. foreach (KThread Thread in SortedThreads.Where(x => x.CondVarAddress == Address))
  143. {
  144. TryAcquireMutex(Thread);
  145. SignaledThreads.Enqueue(Thread);
  146. //If the count is <= 0, we should signal all threads waiting.
  147. if (Count >= 1 && --Count == 0)
  148. {
  149. break;
  150. }
  151. }
  152. while (SignaledThreads.TryDequeue(out KThread Thread))
  153. {
  154. CondVarThreads.Remove(Thread);
  155. }
  156. System.CriticalSection.Leave();
  157. }
  158. private KThread TryAcquireMutex(KThread Requester)
  159. {
  160. long Address = Requester.MutexAddress;
  161. KProcess CurrentProcess = System.Scheduler.GetCurrentProcess();
  162. CurrentProcess.CpuMemory.SetExclusive(0, Address);
  163. if (!KernelTransfer.UserToKernelInt32(System, Address, out int MutexValue))
  164. {
  165. //Invalid address.
  166. CurrentProcess.CpuMemory.ClearExclusive(0);
  167. Requester.SignaledObj = null;
  168. Requester.ObjSyncResult = (int)MakeError(ErrorModule.Kernel, KernelErr.NoAccessPerm);
  169. return null;
  170. }
  171. while (true)
  172. {
  173. if (CurrentProcess.CpuMemory.TestExclusive(0, Address))
  174. {
  175. if (MutexValue != 0)
  176. {
  177. //Update value to indicate there is a mutex waiter now.
  178. CurrentProcess.CpuMemory.WriteInt32(Address, MutexValue | HasListenersMask);
  179. }
  180. else
  181. {
  182. //No thread owning the mutex, assign to requesting thread.
  183. CurrentProcess.CpuMemory.WriteInt32(Address, Requester.ThreadHandleForUserMutex);
  184. }
  185. CurrentProcess.CpuMemory.ClearExclusiveForStore(0);
  186. break;
  187. }
  188. CurrentProcess.CpuMemory.SetExclusive(0, Address);
  189. MutexValue = CurrentProcess.CpuMemory.ReadInt32(Address);
  190. }
  191. if (MutexValue == 0)
  192. {
  193. //We now own the mutex.
  194. Requester.SignaledObj = null;
  195. Requester.ObjSyncResult = 0;
  196. Requester.ReleaseAndResume();
  197. return null;
  198. }
  199. MutexValue &= ~HasListenersMask;
  200. KThread MutexOwner = CurrentProcess.HandleTable.GetObject<KThread>(MutexValue);
  201. if (MutexOwner != null)
  202. {
  203. //Mutex already belongs to another thread, wait for it.
  204. MutexOwner.AddMutexWaiter(Requester);
  205. }
  206. else
  207. {
  208. //Invalid mutex owner.
  209. Requester.SignaledObj = null;
  210. Requester.ObjSyncResult = (int)MakeError(ErrorModule.Kernel, KernelErr.InvalidHandle);
  211. Requester.ReleaseAndResume();
  212. }
  213. return MutexOwner;
  214. }
  215. public long WaitForAddressIfEqual(long Address, int Value, long Timeout)
  216. {
  217. KThread CurrentThread = System.Scheduler.GetCurrentThread();
  218. System.CriticalSection.Enter();
  219. if (CurrentThread.ShallBeTerminated ||
  220. CurrentThread.SchedFlags == ThreadSchedState.TerminationPending)
  221. {
  222. System.CriticalSection.Leave();
  223. return MakeError(ErrorModule.Kernel, KernelErr.ThreadTerminating);
  224. }
  225. CurrentThread.SignaledObj = null;
  226. CurrentThread.ObjSyncResult = (int)MakeError(ErrorModule.Kernel, KernelErr.Timeout);
  227. if (!KernelTransfer.UserToKernelInt32(System, Address, out int CurrentValue))
  228. {
  229. System.CriticalSection.Leave();
  230. return MakeError(ErrorModule.Kernel, KernelErr.NoAccessPerm);
  231. }
  232. if (CurrentValue == Value)
  233. {
  234. if (Timeout == 0)
  235. {
  236. System.CriticalSection.Leave();
  237. return MakeError(ErrorModule.Kernel, KernelErr.Timeout);
  238. }
  239. CurrentThread.MutexAddress = Address;
  240. CurrentThread.WaitingInArbitration = true;
  241. InsertSortedByPriority(ArbiterThreads, CurrentThread);
  242. CurrentThread.Reschedule(ThreadSchedState.Paused);
  243. if (Timeout > 0)
  244. {
  245. System.TimeManager.ScheduleFutureInvocation(CurrentThread, Timeout);
  246. }
  247. System.CriticalSection.Leave();
  248. if (Timeout > 0)
  249. {
  250. System.TimeManager.UnscheduleFutureInvocation(CurrentThread);
  251. }
  252. System.CriticalSection.Enter();
  253. if (CurrentThread.WaitingInArbitration)
  254. {
  255. ArbiterThreads.Remove(CurrentThread);
  256. CurrentThread.WaitingInArbitration = false;
  257. }
  258. System.CriticalSection.Leave();
  259. return CurrentThread.ObjSyncResult;
  260. }
  261. System.CriticalSection.Leave();
  262. return MakeError(ErrorModule.Kernel, KernelErr.InvalidState);
  263. }
  264. public long WaitForAddressIfLessThan(long Address, int Value, bool ShouldDecrement, long Timeout)
  265. {
  266. KThread CurrentThread = System.Scheduler.GetCurrentThread();
  267. System.CriticalSection.Enter();
  268. if (CurrentThread.ShallBeTerminated ||
  269. CurrentThread.SchedFlags == ThreadSchedState.TerminationPending)
  270. {
  271. System.CriticalSection.Leave();
  272. return MakeError(ErrorModule.Kernel, KernelErr.ThreadTerminating);
  273. }
  274. CurrentThread.SignaledObj = null;
  275. CurrentThread.ObjSyncResult = (int)MakeError(ErrorModule.Kernel, KernelErr.Timeout);
  276. KProcess CurrentProcess = System.Scheduler.GetCurrentProcess();
  277. //If ShouldDecrement is true, do atomic decrement of the value at Address.
  278. CurrentProcess.CpuMemory.SetExclusive(0, Address);
  279. if (!KernelTransfer.UserToKernelInt32(System, Address, out int CurrentValue))
  280. {
  281. System.CriticalSection.Leave();
  282. return MakeError(ErrorModule.Kernel, KernelErr.NoAccessPerm);
  283. }
  284. if (ShouldDecrement)
  285. {
  286. while (CurrentValue < Value)
  287. {
  288. if (CurrentProcess.CpuMemory.TestExclusive(0, Address))
  289. {
  290. CurrentProcess.CpuMemory.WriteInt32(Address, CurrentValue - 1);
  291. CurrentProcess.CpuMemory.ClearExclusiveForStore(0);
  292. break;
  293. }
  294. CurrentProcess.CpuMemory.SetExclusive(0, Address);
  295. CurrentValue = CurrentProcess.CpuMemory.ReadInt32(Address);
  296. }
  297. }
  298. CurrentProcess.CpuMemory.ClearExclusive(0);
  299. if (CurrentValue < Value)
  300. {
  301. if (Timeout == 0)
  302. {
  303. System.CriticalSection.Leave();
  304. return MakeError(ErrorModule.Kernel, KernelErr.Timeout);
  305. }
  306. CurrentThread.MutexAddress = Address;
  307. CurrentThread.WaitingInArbitration = true;
  308. InsertSortedByPriority(ArbiterThreads, CurrentThread);
  309. CurrentThread.Reschedule(ThreadSchedState.Paused);
  310. if (Timeout > 0)
  311. {
  312. System.TimeManager.ScheduleFutureInvocation(CurrentThread, Timeout);
  313. }
  314. System.CriticalSection.Leave();
  315. if (Timeout > 0)
  316. {
  317. System.TimeManager.UnscheduleFutureInvocation(CurrentThread);
  318. }
  319. System.CriticalSection.Enter();
  320. if (CurrentThread.WaitingInArbitration)
  321. {
  322. ArbiterThreads.Remove(CurrentThread);
  323. CurrentThread.WaitingInArbitration = false;
  324. }
  325. System.CriticalSection.Leave();
  326. return CurrentThread.ObjSyncResult;
  327. }
  328. System.CriticalSection.Leave();
  329. return MakeError(ErrorModule.Kernel, KernelErr.InvalidState);
  330. }
  331. private void InsertSortedByPriority(List<KThread> Threads, KThread Thread)
  332. {
  333. int NextIndex = -1;
  334. for (int Index = 0; Index < Threads.Count; Index++)
  335. {
  336. if (Threads[Index].DynamicPriority > Thread.DynamicPriority)
  337. {
  338. NextIndex = Index;
  339. break;
  340. }
  341. }
  342. if (NextIndex != -1)
  343. {
  344. Threads.Insert(NextIndex, Thread);
  345. }
  346. else
  347. {
  348. Threads.Add(Thread);
  349. }
  350. }
  351. public long Signal(long Address, int Count)
  352. {
  353. System.CriticalSection.Enter();
  354. WakeArbiterThreads(Address, Count);
  355. System.CriticalSection.Leave();
  356. return 0;
  357. }
  358. public long SignalAndIncrementIfEqual(long Address, int Value, int Count)
  359. {
  360. System.CriticalSection.Enter();
  361. KProcess CurrentProcess = System.Scheduler.GetCurrentProcess();
  362. CurrentProcess.CpuMemory.SetExclusive(0, Address);
  363. if (!KernelTransfer.UserToKernelInt32(System, Address, out int CurrentValue))
  364. {
  365. System.CriticalSection.Leave();
  366. return MakeError(ErrorModule.Kernel, KernelErr.NoAccessPerm);
  367. }
  368. while (CurrentValue == Value)
  369. {
  370. if (CurrentProcess.CpuMemory.TestExclusive(0, Address))
  371. {
  372. CurrentProcess.CpuMemory.WriteInt32(Address, CurrentValue + 1);
  373. CurrentProcess.CpuMemory.ClearExclusiveForStore(0);
  374. break;
  375. }
  376. CurrentProcess.CpuMemory.SetExclusive(0, Address);
  377. CurrentValue = CurrentProcess.CpuMemory.ReadInt32(Address);
  378. }
  379. CurrentProcess.CpuMemory.ClearExclusive(0);
  380. if (CurrentValue != Value)
  381. {
  382. System.CriticalSection.Leave();
  383. return MakeError(ErrorModule.Kernel, KernelErr.InvalidState);
  384. }
  385. WakeArbiterThreads(Address, Count);
  386. System.CriticalSection.Leave();
  387. return 0;
  388. }
  389. public long SignalAndModifyIfEqual(long Address, int Value, int Count)
  390. {
  391. System.CriticalSection.Enter();
  392. int Offset;
  393. //The value is decremented if the number of threads waiting is less
  394. //or equal to the Count of threads to be signaled, or Count is zero
  395. //or negative. It is incremented if there are no threads waiting.
  396. int WaitingCount = 0;
  397. foreach (KThread Thread in ArbiterThreads.Where(x => x.MutexAddress == Address))
  398. {
  399. if (++WaitingCount > Count)
  400. {
  401. break;
  402. }
  403. }
  404. if (WaitingCount > 0)
  405. {
  406. Offset = WaitingCount <= Count || Count <= 0 ? -1 : 0;
  407. }
  408. else
  409. {
  410. Offset = 1;
  411. }
  412. KProcess CurrentProcess = System.Scheduler.GetCurrentProcess();
  413. CurrentProcess.CpuMemory.SetExclusive(0, Address);
  414. if (!KernelTransfer.UserToKernelInt32(System, Address, out int CurrentValue))
  415. {
  416. System.CriticalSection.Leave();
  417. return MakeError(ErrorModule.Kernel, KernelErr.NoAccessPerm);
  418. }
  419. while (CurrentValue == Value)
  420. {
  421. if (CurrentProcess.CpuMemory.TestExclusive(0, Address))
  422. {
  423. CurrentProcess.CpuMemory.WriteInt32(Address, CurrentValue + Offset);
  424. CurrentProcess.CpuMemory.ClearExclusiveForStore(0);
  425. break;
  426. }
  427. CurrentProcess.CpuMemory.SetExclusive(0, Address);
  428. CurrentValue = CurrentProcess.CpuMemory.ReadInt32(Address);
  429. }
  430. CurrentProcess.CpuMemory.ClearExclusive(0);
  431. if (CurrentValue != Value)
  432. {
  433. System.CriticalSection.Leave();
  434. return MakeError(ErrorModule.Kernel, KernelErr.InvalidState);
  435. }
  436. WakeArbiterThreads(Address, Count);
  437. System.CriticalSection.Leave();
  438. return 0;
  439. }
  440. private void WakeArbiterThreads(long Address, int Count)
  441. {
  442. Queue<KThread> SignaledThreads = new Queue<KThread>();
  443. foreach (KThread Thread in ArbiterThreads.Where(x => x.MutexAddress == Address))
  444. {
  445. SignaledThreads.Enqueue(Thread);
  446. //If the count is <= 0, we should signal all threads waiting.
  447. if (Count >= 1 && --Count == 0)
  448. {
  449. break;
  450. }
  451. }
  452. while (SignaledThreads.TryDequeue(out KThread Thread))
  453. {
  454. Thread.SignaledObj = null;
  455. Thread.ObjSyncResult = 0;
  456. Thread.ReleaseAndResume();
  457. Thread.WaitingInArbitration = false;
  458. ArbiterThreads.Remove(Thread);
  459. }
  460. }
  461. }
  462. }