KAddressArbiter.cs 17 KB

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