KAddressArbiter.cs 19 KB

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