KAddressArbiter.cs 20 KB

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