KAddressArbiter.cs 18 KB

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