KAddressArbiter.cs 18 KB

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