KAddressArbiter.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654
  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. currentProcess.CpuMemory.SetExclusive(0, (long)address);
  164. if (!KernelTransfer.UserToKernelInt32(_system, address, out int mutexValue))
  165. {
  166. //Invalid address.
  167. currentProcess.CpuMemory.ClearExclusive(0);
  168. requester.SignaledObj = null;
  169. requester.ObjSyncResult = KernelResult.InvalidMemState;
  170. return null;
  171. }
  172. while (true)
  173. {
  174. if (currentProcess.CpuMemory.TestExclusive(0, (long)address))
  175. {
  176. if (mutexValue != 0)
  177. {
  178. //Update value to indicate there is a mutex waiter now.
  179. currentProcess.CpuMemory.WriteInt32((long)address, mutexValue | HasListenersMask);
  180. }
  181. else
  182. {
  183. //No thread owning the mutex, assign to requesting thread.
  184. currentProcess.CpuMemory.WriteInt32((long)address, requester.ThreadHandleForUserMutex);
  185. }
  186. currentProcess.CpuMemory.ClearExclusiveForStore(0);
  187. break;
  188. }
  189. currentProcess.CpuMemory.SetExclusive(0, (long)address);
  190. mutexValue = currentProcess.CpuMemory.ReadInt32((long)address);
  191. }
  192. if (mutexValue == 0)
  193. {
  194. //We now own the mutex.
  195. requester.SignaledObj = null;
  196. requester.ObjSyncResult = KernelResult.Success;
  197. requester.ReleaseAndResume();
  198. return null;
  199. }
  200. mutexValue &= ~HasListenersMask;
  201. KThread mutexOwner = currentProcess.HandleTable.GetObject<KThread>(mutexValue);
  202. if (mutexOwner != null)
  203. {
  204. //Mutex already belongs to another thread, wait for it.
  205. mutexOwner.AddMutexWaiter(requester);
  206. }
  207. else
  208. {
  209. //Invalid mutex owner.
  210. requester.SignaledObj = null;
  211. requester.ObjSyncResult = KernelResult.InvalidHandle;
  212. requester.ReleaseAndResume();
  213. }
  214. return mutexOwner;
  215. }
  216. public KernelResult WaitForAddressIfEqual(ulong address, int value, long timeout)
  217. {
  218. KThread currentThread = _system.Scheduler.GetCurrentThread();
  219. _system.CriticalSection.Enter();
  220. if (currentThread.ShallBeTerminated ||
  221. currentThread.SchedFlags == ThreadSchedState.TerminationPending)
  222. {
  223. _system.CriticalSection.Leave();
  224. return KernelResult.ThreadTerminating;
  225. }
  226. currentThread.SignaledObj = null;
  227. currentThread.ObjSyncResult = KernelResult.TimedOut;
  228. if (!KernelTransfer.UserToKernelInt32(_system, address, out int currentValue))
  229. {
  230. _system.CriticalSection.Leave();
  231. return KernelResult.InvalidMemState;
  232. }
  233. if (currentValue == value)
  234. {
  235. if (timeout == 0)
  236. {
  237. _system.CriticalSection.Leave();
  238. return KernelResult.TimedOut;
  239. }
  240. currentThread.MutexAddress = address;
  241. currentThread.WaitingInArbitration = true;
  242. InsertSortedByPriority(ArbiterThreads, currentThread);
  243. currentThread.Reschedule(ThreadSchedState.Paused);
  244. if (timeout > 0)
  245. {
  246. _system.TimeManager.ScheduleFutureInvocation(currentThread, timeout);
  247. }
  248. _system.CriticalSection.Leave();
  249. if (timeout > 0)
  250. {
  251. _system.TimeManager.UnscheduleFutureInvocation(currentThread);
  252. }
  253. _system.CriticalSection.Enter();
  254. if (currentThread.WaitingInArbitration)
  255. {
  256. ArbiterThreads.Remove(currentThread);
  257. currentThread.WaitingInArbitration = false;
  258. }
  259. _system.CriticalSection.Leave();
  260. return (KernelResult)currentThread.ObjSyncResult;
  261. }
  262. _system.CriticalSection.Leave();
  263. return KernelResult.InvalidState;
  264. }
  265. public KernelResult WaitForAddressIfLessThan(
  266. ulong address,
  267. int value,
  268. bool shouldDecrement,
  269. long timeout)
  270. {
  271. KThread currentThread = _system.Scheduler.GetCurrentThread();
  272. _system.CriticalSection.Enter();
  273. if (currentThread.ShallBeTerminated ||
  274. currentThread.SchedFlags == ThreadSchedState.TerminationPending)
  275. {
  276. _system.CriticalSection.Leave();
  277. return KernelResult.ThreadTerminating;
  278. }
  279. currentThread.SignaledObj = null;
  280. currentThread.ObjSyncResult = KernelResult.TimedOut;
  281. KProcess currentProcess = _system.Scheduler.GetCurrentProcess();
  282. //If ShouldDecrement is true, do atomic decrement of the value at Address.
  283. currentProcess.CpuMemory.SetExclusive(0, (long)address);
  284. if (!KernelTransfer.UserToKernelInt32(_system, address, out int currentValue))
  285. {
  286. _system.CriticalSection.Leave();
  287. return KernelResult.InvalidMemState;
  288. }
  289. if (shouldDecrement)
  290. {
  291. while (currentValue < value)
  292. {
  293. if (currentProcess.CpuMemory.TestExclusive(0, (long)address))
  294. {
  295. currentProcess.CpuMemory.WriteInt32((long)address, currentValue - 1);
  296. currentProcess.CpuMemory.ClearExclusiveForStore(0);
  297. break;
  298. }
  299. currentProcess.CpuMemory.SetExclusive(0, (long)address);
  300. currentValue = currentProcess.CpuMemory.ReadInt32((long)address);
  301. }
  302. }
  303. currentProcess.CpuMemory.ClearExclusive(0);
  304. if (currentValue < value)
  305. {
  306. if (timeout == 0)
  307. {
  308. _system.CriticalSection.Leave();
  309. return KernelResult.TimedOut;
  310. }
  311. currentThread.MutexAddress = address;
  312. currentThread.WaitingInArbitration = true;
  313. InsertSortedByPriority(ArbiterThreads, currentThread);
  314. currentThread.Reschedule(ThreadSchedState.Paused);
  315. if (timeout > 0)
  316. {
  317. _system.TimeManager.ScheduleFutureInvocation(currentThread, timeout);
  318. }
  319. _system.CriticalSection.Leave();
  320. if (timeout > 0)
  321. {
  322. _system.TimeManager.UnscheduleFutureInvocation(currentThread);
  323. }
  324. _system.CriticalSection.Enter();
  325. if (currentThread.WaitingInArbitration)
  326. {
  327. ArbiterThreads.Remove(currentThread);
  328. currentThread.WaitingInArbitration = false;
  329. }
  330. _system.CriticalSection.Leave();
  331. return (KernelResult)currentThread.ObjSyncResult;
  332. }
  333. _system.CriticalSection.Leave();
  334. return KernelResult.InvalidState;
  335. }
  336. private void InsertSortedByPriority(List<KThread> threads, KThread thread)
  337. {
  338. int nextIndex = -1;
  339. for (int index = 0; index < threads.Count; index++)
  340. {
  341. if (threads[index].DynamicPriority > thread.DynamicPriority)
  342. {
  343. nextIndex = index;
  344. break;
  345. }
  346. }
  347. if (nextIndex != -1)
  348. {
  349. threads.Insert(nextIndex, thread);
  350. }
  351. else
  352. {
  353. threads.Add(thread);
  354. }
  355. }
  356. public KernelResult Signal(ulong address, int count)
  357. {
  358. _system.CriticalSection.Enter();
  359. WakeArbiterThreads(address, count);
  360. _system.CriticalSection.Leave();
  361. return KernelResult.Success;
  362. }
  363. public KernelResult SignalAndIncrementIfEqual(ulong address, int value, int count)
  364. {
  365. _system.CriticalSection.Enter();
  366. KProcess currentProcess = _system.Scheduler.GetCurrentProcess();
  367. currentProcess.CpuMemory.SetExclusive(0, (long)address);
  368. if (!KernelTransfer.UserToKernelInt32(_system, address, out int currentValue))
  369. {
  370. _system.CriticalSection.Leave();
  371. return KernelResult.InvalidMemState;
  372. }
  373. while (currentValue == value)
  374. {
  375. if (currentProcess.CpuMemory.TestExclusive(0, (long)address))
  376. {
  377. currentProcess.CpuMemory.WriteInt32((long)address, currentValue + 1);
  378. currentProcess.CpuMemory.ClearExclusiveForStore(0);
  379. break;
  380. }
  381. currentProcess.CpuMemory.SetExclusive(0, (long)address);
  382. currentValue = currentProcess.CpuMemory.ReadInt32((long)address);
  383. }
  384. currentProcess.CpuMemory.ClearExclusive(0);
  385. if (currentValue != value)
  386. {
  387. _system.CriticalSection.Leave();
  388. return KernelResult.InvalidState;
  389. }
  390. WakeArbiterThreads(address, count);
  391. _system.CriticalSection.Leave();
  392. return KernelResult.Success;
  393. }
  394. public KernelResult SignalAndModifyIfEqual(ulong address, int value, int count)
  395. {
  396. _system.CriticalSection.Enter();
  397. int offset;
  398. //The value is decremented if the number of threads waiting is less
  399. //or equal to the Count of threads to be signaled, or Count is zero
  400. //or negative. It is incremented if there are no threads waiting.
  401. int waitingCount = 0;
  402. foreach (KThread thread in ArbiterThreads.Where(x => x.MutexAddress == address))
  403. {
  404. if (++waitingCount > count)
  405. {
  406. break;
  407. }
  408. }
  409. if (waitingCount > 0)
  410. {
  411. offset = waitingCount <= count || count <= 0 ? -1 : 0;
  412. }
  413. else
  414. {
  415. offset = 1;
  416. }
  417. KProcess currentProcess = _system.Scheduler.GetCurrentProcess();
  418. currentProcess.CpuMemory.SetExclusive(0, (long)address);
  419. if (!KernelTransfer.UserToKernelInt32(_system, address, out int currentValue))
  420. {
  421. _system.CriticalSection.Leave();
  422. return KernelResult.InvalidMemState;
  423. }
  424. while (currentValue == value)
  425. {
  426. if (currentProcess.CpuMemory.TestExclusive(0, (long)address))
  427. {
  428. currentProcess.CpuMemory.WriteInt32((long)address, currentValue + offset);
  429. currentProcess.CpuMemory.ClearExclusiveForStore(0);
  430. break;
  431. }
  432. currentProcess.CpuMemory.SetExclusive(0, (long)address);
  433. currentValue = currentProcess.CpuMemory.ReadInt32((long)address);
  434. }
  435. currentProcess.CpuMemory.ClearExclusive(0);
  436. if (currentValue != value)
  437. {
  438. _system.CriticalSection.Leave();
  439. return KernelResult.InvalidState;
  440. }
  441. WakeArbiterThreads(address, count);
  442. _system.CriticalSection.Leave();
  443. return KernelResult.Success;
  444. }
  445. private void WakeArbiterThreads(ulong address, int count)
  446. {
  447. Queue<KThread> signaledThreads = new Queue<KThread>();
  448. foreach (KThread thread in ArbiterThreads.Where(x => x.MutexAddress == address))
  449. {
  450. signaledThreads.Enqueue(thread);
  451. //If the count is <= 0, we should signal all threads waiting.
  452. if (count >= 1 && --count == 0)
  453. {
  454. break;
  455. }
  456. }
  457. while (signaledThreads.TryDequeue(out KThread thread))
  458. {
  459. thread.SignaledObj = null;
  460. thread.ObjSyncResult = KernelResult.Success;
  461. thread.ReleaseAndResume();
  462. thread.WaitingInArbitration = false;
  463. ArbiterThreads.Remove(thread);
  464. }
  465. }
  466. }
  467. }