KAddressArbiter.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  1. using Ryujinx.HLE.HOS.Kernel.Common;
  2. using Ryujinx.HLE.HOS.Kernel.Process;
  3. using Ryujinx.Horizon.Common;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Threading;
  8. namespace Ryujinx.HLE.HOS.Kernel.Threading
  9. {
  10. class KAddressArbiter
  11. {
  12. private const int HasListenersMask = 0x40000000;
  13. private readonly KernelContext _context;
  14. private readonly List<KThread> _condVarThreads;
  15. private readonly List<KThread> _arbiterThreads;
  16. public KAddressArbiter(KernelContext context)
  17. {
  18. _context = context;
  19. _condVarThreads = new List<KThread>();
  20. _arbiterThreads = new List<KThread>();
  21. }
  22. public Result ArbitrateLock(int ownerHandle, ulong mutexAddress, int requesterHandle)
  23. {
  24. KThread currentThread = KernelStatic.GetCurrentThread();
  25. _context.CriticalSection.Enter();
  26. if (currentThread.TerminationRequested)
  27. {
  28. _context.CriticalSection.Leave();
  29. return KernelResult.ThreadTerminating;
  30. }
  31. currentThread.SignaledObj = null;
  32. currentThread.ObjSyncResult = Result.Success;
  33. KProcess currentProcess = KernelStatic.GetCurrentProcess();
  34. if (!KernelTransfer.UserToKernel(out int mutexValue, mutexAddress))
  35. {
  36. _context.CriticalSection.Leave();
  37. return KernelResult.InvalidMemState;
  38. }
  39. if (mutexValue != (ownerHandle | HasListenersMask))
  40. {
  41. _context.CriticalSection.Leave();
  42. return Result.Success;
  43. }
  44. KThread mutexOwner = currentProcess.HandleTable.GetObject<KThread>(ownerHandle);
  45. if (mutexOwner == null)
  46. {
  47. _context.CriticalSection.Leave();
  48. return KernelResult.InvalidHandle;
  49. }
  50. currentThread.MutexAddress = mutexAddress;
  51. currentThread.ThreadHandleForUserMutex = requesterHandle;
  52. mutexOwner.AddMutexWaiter(currentThread);
  53. currentThread.Reschedule(ThreadSchedState.Paused);
  54. _context.CriticalSection.Leave();
  55. _context.CriticalSection.Enter();
  56. if (currentThread.MutexOwner != null)
  57. {
  58. currentThread.MutexOwner.RemoveMutexWaiter(currentThread);
  59. }
  60. _context.CriticalSection.Leave();
  61. return currentThread.ObjSyncResult;
  62. }
  63. public Result ArbitrateUnlock(ulong mutexAddress)
  64. {
  65. _context.CriticalSection.Enter();
  66. KThread currentThread = KernelStatic.GetCurrentThread();
  67. (int mutexValue, KThread newOwnerThread) = MutexUnlock(currentThread, mutexAddress);
  68. Result result = Result.Success;
  69. if (!KernelTransfer.KernelToUser(mutexAddress, mutexValue))
  70. {
  71. result = KernelResult.InvalidMemState;
  72. }
  73. if (result != Result.Success && newOwnerThread != null)
  74. {
  75. newOwnerThread.SignaledObj = null;
  76. newOwnerThread.ObjSyncResult = result;
  77. }
  78. _context.CriticalSection.Leave();
  79. return result;
  80. }
  81. public Result WaitProcessWideKeyAtomic(ulong mutexAddress, ulong condVarAddress, int threadHandle, long timeout)
  82. {
  83. _context.CriticalSection.Enter();
  84. KThread currentThread = KernelStatic.GetCurrentThread();
  85. currentThread.SignaledObj = null;
  86. currentThread.ObjSyncResult = KernelResult.TimedOut;
  87. if (currentThread.TerminationRequested)
  88. {
  89. _context.CriticalSection.Leave();
  90. return KernelResult.ThreadTerminating;
  91. }
  92. (int mutexValue, _) = MutexUnlock(currentThread, mutexAddress);
  93. KernelTransfer.KernelToUser(condVarAddress, 1);
  94. if (!KernelTransfer.KernelToUser(mutexAddress, mutexValue))
  95. {
  96. _context.CriticalSection.Leave();
  97. return KernelResult.InvalidMemState;
  98. }
  99. currentThread.MutexAddress = mutexAddress;
  100. currentThread.ThreadHandleForUserMutex = threadHandle;
  101. currentThread.CondVarAddress = condVarAddress;
  102. _condVarThreads.Add(currentThread);
  103. if (timeout != 0)
  104. {
  105. currentThread.Reschedule(ThreadSchedState.Paused);
  106. if (timeout > 0)
  107. {
  108. _context.TimeManager.ScheduleFutureInvocation(currentThread, timeout);
  109. }
  110. }
  111. _context.CriticalSection.Leave();
  112. if (timeout > 0)
  113. {
  114. _context.TimeManager.UnscheduleFutureInvocation(currentThread);
  115. }
  116. _context.CriticalSection.Enter();
  117. if (currentThread.MutexOwner != null)
  118. {
  119. currentThread.MutexOwner.RemoveMutexWaiter(currentThread);
  120. }
  121. _condVarThreads.Remove(currentThread);
  122. _context.CriticalSection.Leave();
  123. return currentThread.ObjSyncResult;
  124. }
  125. private (int, KThread) MutexUnlock(KThread currentThread, ulong mutexAddress)
  126. {
  127. KThread newOwnerThread = currentThread.RelinquishMutex(mutexAddress, out int count);
  128. int mutexValue = 0;
  129. if (newOwnerThread != null)
  130. {
  131. mutexValue = newOwnerThread.ThreadHandleForUserMutex;
  132. if (count >= 2)
  133. {
  134. mutexValue |= HasListenersMask;
  135. }
  136. newOwnerThread.SignaledObj = null;
  137. newOwnerThread.ObjSyncResult = Result.Success;
  138. newOwnerThread.ReleaseAndResume();
  139. }
  140. return (mutexValue, newOwnerThread);
  141. }
  142. public void SignalProcessWideKey(ulong address, int count)
  143. {
  144. _context.CriticalSection.Enter();
  145. WakeThreads(_condVarThreads, count, TryAcquireMutex, x => x.CondVarAddress == address);
  146. if (!_condVarThreads.Any(x => x.CondVarAddress == address))
  147. {
  148. KernelTransfer.KernelToUser(address, 0);
  149. }
  150. _context.CriticalSection.Leave();
  151. }
  152. private static void TryAcquireMutex(KThread requester)
  153. {
  154. ulong address = requester.MutexAddress;
  155. KProcess currentProcess = KernelStatic.GetCurrentProcess();
  156. if (!currentProcess.CpuMemory.IsMapped(address))
  157. {
  158. // Invalid address.
  159. requester.SignaledObj = null;
  160. requester.ObjSyncResult = KernelResult.InvalidMemState;
  161. return;
  162. }
  163. ref int mutexRef = ref currentProcess.CpuMemory.GetRef<int>(address);
  164. int mutexValue, newMutexValue;
  165. do
  166. {
  167. mutexValue = mutexRef;
  168. if (mutexValue != 0)
  169. {
  170. // Update value to indicate there is a mutex waiter now.
  171. newMutexValue = mutexValue | HasListenersMask;
  172. }
  173. else
  174. {
  175. // No thread owning the mutex, assign to requesting thread.
  176. newMutexValue = requester.ThreadHandleForUserMutex;
  177. }
  178. }
  179. while (Interlocked.CompareExchange(ref mutexRef, newMutexValue, mutexValue) != mutexValue);
  180. if (mutexValue == 0)
  181. {
  182. // We now own the mutex.
  183. requester.SignaledObj = null;
  184. requester.ObjSyncResult = Result.Success;
  185. requester.ReleaseAndResume();
  186. return;
  187. }
  188. mutexValue &= ~HasListenersMask;
  189. KThread mutexOwner = currentProcess.HandleTable.GetObject<KThread>(mutexValue);
  190. if (mutexOwner != null)
  191. {
  192. // Mutex already belongs to another thread, wait for it.
  193. mutexOwner.AddMutexWaiter(requester);
  194. }
  195. else
  196. {
  197. // Invalid mutex owner.
  198. requester.SignaledObj = null;
  199. requester.ObjSyncResult = KernelResult.InvalidHandle;
  200. requester.ReleaseAndResume();
  201. }
  202. }
  203. public Result WaitForAddressIfEqual(ulong address, int value, long timeout)
  204. {
  205. KThread currentThread = KernelStatic.GetCurrentThread();
  206. _context.CriticalSection.Enter();
  207. if (currentThread.TerminationRequested)
  208. {
  209. _context.CriticalSection.Leave();
  210. return KernelResult.ThreadTerminating;
  211. }
  212. currentThread.SignaledObj = null;
  213. currentThread.ObjSyncResult = KernelResult.TimedOut;
  214. if (!KernelTransfer.UserToKernel(out int currentValue, address))
  215. {
  216. _context.CriticalSection.Leave();
  217. return KernelResult.InvalidMemState;
  218. }
  219. if (currentValue == value)
  220. {
  221. if (timeout == 0)
  222. {
  223. _context.CriticalSection.Leave();
  224. return KernelResult.TimedOut;
  225. }
  226. currentThread.MutexAddress = address;
  227. currentThread.WaitingInArbitration = true;
  228. _arbiterThreads.Add(currentThread);
  229. currentThread.Reschedule(ThreadSchedState.Paused);
  230. if (timeout > 0)
  231. {
  232. _context.TimeManager.ScheduleFutureInvocation(currentThread, timeout);
  233. }
  234. _context.CriticalSection.Leave();
  235. if (timeout > 0)
  236. {
  237. _context.TimeManager.UnscheduleFutureInvocation(currentThread);
  238. }
  239. _context.CriticalSection.Enter();
  240. if (currentThread.WaitingInArbitration)
  241. {
  242. _arbiterThreads.Remove(currentThread);
  243. currentThread.WaitingInArbitration = false;
  244. }
  245. _context.CriticalSection.Leave();
  246. return currentThread.ObjSyncResult;
  247. }
  248. _context.CriticalSection.Leave();
  249. return KernelResult.InvalidState;
  250. }
  251. public Result WaitForAddressIfLessThan(ulong address, int value, bool shouldDecrement, long timeout)
  252. {
  253. KThread currentThread = KernelStatic.GetCurrentThread();
  254. _context.CriticalSection.Enter();
  255. if (currentThread.TerminationRequested)
  256. {
  257. _context.CriticalSection.Leave();
  258. return KernelResult.ThreadTerminating;
  259. }
  260. currentThread.SignaledObj = null;
  261. currentThread.ObjSyncResult = KernelResult.TimedOut;
  262. KProcess currentProcess = KernelStatic.GetCurrentProcess();
  263. if (!KernelTransfer.UserToKernel(out int currentValue, address))
  264. {
  265. _context.CriticalSection.Leave();
  266. return KernelResult.InvalidMemState;
  267. }
  268. if (shouldDecrement)
  269. {
  270. currentValue = Interlocked.Decrement(ref currentProcess.CpuMemory.GetRef<int>(address)) + 1;
  271. }
  272. if (currentValue < value)
  273. {
  274. if (timeout == 0)
  275. {
  276. _context.CriticalSection.Leave();
  277. return KernelResult.TimedOut;
  278. }
  279. currentThread.MutexAddress = address;
  280. currentThread.WaitingInArbitration = true;
  281. _arbiterThreads.Add(currentThread);
  282. currentThread.Reschedule(ThreadSchedState.Paused);
  283. if (timeout > 0)
  284. {
  285. _context.TimeManager.ScheduleFutureInvocation(currentThread, timeout);
  286. }
  287. _context.CriticalSection.Leave();
  288. if (timeout > 0)
  289. {
  290. _context.TimeManager.UnscheduleFutureInvocation(currentThread);
  291. }
  292. _context.CriticalSection.Enter();
  293. if (currentThread.WaitingInArbitration)
  294. {
  295. _arbiterThreads.Remove(currentThread);
  296. currentThread.WaitingInArbitration = false;
  297. }
  298. _context.CriticalSection.Leave();
  299. return currentThread.ObjSyncResult;
  300. }
  301. _context.CriticalSection.Leave();
  302. return KernelResult.InvalidState;
  303. }
  304. public Result Signal(ulong address, int count)
  305. {
  306. _context.CriticalSection.Enter();
  307. WakeArbiterThreads(address, count);
  308. _context.CriticalSection.Leave();
  309. return Result.Success;
  310. }
  311. public Result SignalAndIncrementIfEqual(ulong address, int value, int count)
  312. {
  313. _context.CriticalSection.Enter();
  314. KProcess currentProcess = KernelStatic.GetCurrentProcess();
  315. if (!currentProcess.CpuMemory.IsMapped(address))
  316. {
  317. _context.CriticalSection.Leave();
  318. return KernelResult.InvalidMemState;
  319. }
  320. ref int valueRef = ref currentProcess.CpuMemory.GetRef<int>(address);
  321. int currentValue;
  322. do
  323. {
  324. currentValue = valueRef;
  325. if (currentValue != value)
  326. {
  327. _context.CriticalSection.Leave();
  328. return KernelResult.InvalidState;
  329. }
  330. }
  331. while (Interlocked.CompareExchange(ref valueRef, currentValue + 1, currentValue) != currentValue);
  332. WakeArbiterThreads(address, count);
  333. _context.CriticalSection.Leave();
  334. return Result.Success;
  335. }
  336. public Result SignalAndModifyIfEqual(ulong address, int value, int count)
  337. {
  338. _context.CriticalSection.Enter();
  339. int addend;
  340. // The value is decremented if the number of threads waiting is less
  341. // or equal to the Count of threads to be signaled, or Count is zero
  342. // or negative. It is incremented if there are no threads waiting.
  343. int waitingCount = 0;
  344. foreach (KThread thread in _arbiterThreads.Where(x => x.MutexAddress == address))
  345. {
  346. if (++waitingCount >= count)
  347. {
  348. break;
  349. }
  350. }
  351. if (waitingCount > 0)
  352. {
  353. if (count <= 0)
  354. {
  355. addend = -2;
  356. }
  357. else if (waitingCount < count)
  358. {
  359. addend = -1;
  360. }
  361. else
  362. {
  363. addend = 0;
  364. }
  365. }
  366. else
  367. {
  368. addend = 1;
  369. }
  370. KProcess currentProcess = KernelStatic.GetCurrentProcess();
  371. if (!currentProcess.CpuMemory.IsMapped(address))
  372. {
  373. _context.CriticalSection.Leave();
  374. return KernelResult.InvalidMemState;
  375. }
  376. ref int valueRef = ref currentProcess.CpuMemory.GetRef<int>(address);
  377. int currentValue;
  378. do
  379. {
  380. currentValue = valueRef;
  381. if (currentValue != value)
  382. {
  383. _context.CriticalSection.Leave();
  384. return KernelResult.InvalidState;
  385. }
  386. }
  387. while (Interlocked.CompareExchange(ref valueRef, currentValue + addend, currentValue) != currentValue);
  388. WakeArbiterThreads(address, count);
  389. _context.CriticalSection.Leave();
  390. return Result.Success;
  391. }
  392. private void WakeArbiterThreads(ulong address, int count)
  393. {
  394. static void RemoveArbiterThread(KThread thread)
  395. {
  396. thread.SignaledObj = null;
  397. thread.ObjSyncResult = Result.Success;
  398. thread.ReleaseAndResume();
  399. thread.WaitingInArbitration = false;
  400. }
  401. WakeThreads(_arbiterThreads, count, RemoveArbiterThread, x => x.MutexAddress == address);
  402. }
  403. private static void WakeThreads(
  404. List<KThread> threads,
  405. int count,
  406. Action<KThread> removeCallback,
  407. Func<KThread, bool> predicate)
  408. {
  409. var candidates = threads.Where(predicate).OrderBy(x => x.DynamicPriority);
  410. var toSignal = (count > 0 ? candidates.Take(count) : candidates).ToArray();
  411. foreach (KThread thread in toSignal)
  412. {
  413. removeCallback(thread);
  414. threads.Remove(thread);
  415. }
  416. }
  417. }
  418. }