k_condition_variable.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. // Copyright 2021 yuzu Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include <vector>
  5. #include "core/arm/exclusive_monitor.h"
  6. #include "core/core.h"
  7. #include "core/hle/kernel/k_condition_variable.h"
  8. #include "core/hle/kernel/k_linked_list.h"
  9. #include "core/hle/kernel/k_process.h"
  10. #include "core/hle/kernel/k_scheduler.h"
  11. #include "core/hle/kernel/k_scoped_scheduler_lock_and_sleep.h"
  12. #include "core/hle/kernel/k_synchronization_object.h"
  13. #include "core/hle/kernel/k_thread.h"
  14. #include "core/hle/kernel/kernel.h"
  15. #include "core/hle/kernel/svc_common.h"
  16. #include "core/hle/kernel/svc_results.h"
  17. #include "core/memory.h"
  18. namespace Kernel {
  19. namespace {
  20. bool ReadFromUser(Core::System& system, u32* out, VAddr address) {
  21. *out = system.Memory().Read32(address);
  22. return true;
  23. }
  24. bool WriteToUser(Core::System& system, VAddr address, const u32* p) {
  25. system.Memory().Write32(address, *p);
  26. return true;
  27. }
  28. bool UpdateLockAtomic(Core::System& system, u32* out, VAddr address, u32 if_zero,
  29. u32 new_orr_mask) {
  30. auto& monitor = system.Monitor();
  31. const auto current_core = system.CurrentCoreIndex();
  32. // Load the value from the address.
  33. const auto expected = monitor.ExclusiveRead32(current_core, address);
  34. // Orr in the new mask.
  35. u32 value = expected | new_orr_mask;
  36. // If the value is zero, use the if_zero value, otherwise use the newly orr'd value.
  37. if (!expected) {
  38. value = if_zero;
  39. }
  40. // Try to store.
  41. if (!monitor.ExclusiveWrite32(current_core, address, value)) {
  42. // If we failed to store, try again.
  43. return UpdateLockAtomic(system, out, address, if_zero, new_orr_mask);
  44. }
  45. // We're done.
  46. *out = expected;
  47. return true;
  48. }
  49. } // namespace
  50. KConditionVariable::KConditionVariable(Core::System& system_)
  51. : system{system_}, kernel{system.Kernel()} {}
  52. KConditionVariable::~KConditionVariable() = default;
  53. ResultCode KConditionVariable::SignalToAddress(VAddr addr) {
  54. KThread* owner_thread = kernel.CurrentScheduler()->GetCurrentThread();
  55. // Signal the address.
  56. {
  57. KScopedSchedulerLock sl(kernel);
  58. // Remove waiter thread.
  59. s32 num_waiters{};
  60. KThread* next_owner_thread =
  61. owner_thread->RemoveWaiterByKey(std::addressof(num_waiters), addr);
  62. // Determine the next tag.
  63. u32 next_value{};
  64. if (next_owner_thread) {
  65. next_value = next_owner_thread->GetAddressKeyValue();
  66. if (num_waiters > 1) {
  67. next_value |= Svc::HandleWaitMask;
  68. }
  69. next_owner_thread->SetSyncedObject(nullptr, RESULT_SUCCESS);
  70. next_owner_thread->Wakeup();
  71. }
  72. // Write the value to userspace.
  73. if (!WriteToUser(system, addr, std::addressof(next_value))) {
  74. if (next_owner_thread) {
  75. next_owner_thread->SetSyncedObject(nullptr, ResultInvalidCurrentMemory);
  76. }
  77. return ResultInvalidCurrentMemory;
  78. }
  79. }
  80. return RESULT_SUCCESS;
  81. }
  82. ResultCode KConditionVariable::WaitForAddress(Handle handle, VAddr addr, u32 value) {
  83. KThread* cur_thread = kernel.CurrentScheduler()->GetCurrentThread();
  84. // Wait for the address.
  85. {
  86. KScopedAutoObject<KThread> owner_thread;
  87. ASSERT(owner_thread.IsNull());
  88. {
  89. KScopedSchedulerLock sl(kernel);
  90. cur_thread->SetSyncedObject(nullptr, RESULT_SUCCESS);
  91. // Check if the thread should terminate.
  92. R_UNLESS(!cur_thread->IsTerminationRequested(), ResultTerminationRequested);
  93. {
  94. // Read the tag from userspace.
  95. u32 test_tag{};
  96. R_UNLESS(ReadFromUser(system, std::addressof(test_tag), addr),
  97. ResultInvalidCurrentMemory);
  98. // If the tag isn't the handle (with wait mask), we're done.
  99. R_UNLESS(test_tag == (handle | Svc::HandleWaitMask), RESULT_SUCCESS);
  100. // Get the lock owner thread.
  101. owner_thread =
  102. kernel.CurrentProcess()->GetHandleTable().GetObjectWithoutPseudoHandle<KThread>(
  103. handle);
  104. R_UNLESS(owner_thread.IsNotNull(), ResultInvalidHandle);
  105. // Update the lock.
  106. cur_thread->SetAddressKey(addr, value);
  107. owner_thread->AddWaiter(cur_thread);
  108. cur_thread->SetState(ThreadState::Waiting);
  109. cur_thread->SetWaitReasonForDebugging(ThreadWaitReasonForDebugging::ConditionVar);
  110. cur_thread->SetMutexWaitAddressForDebugging(addr);
  111. }
  112. }
  113. ASSERT(owner_thread.IsNotNull());
  114. }
  115. // Remove the thread as a waiter from the lock owner.
  116. {
  117. KScopedSchedulerLock sl(kernel);
  118. KThread* owner_thread = cur_thread->GetLockOwner();
  119. if (owner_thread != nullptr) {
  120. owner_thread->RemoveWaiter(cur_thread);
  121. }
  122. }
  123. // Get the wait result.
  124. KSynchronizationObject* dummy{};
  125. return cur_thread->GetWaitResult(std::addressof(dummy));
  126. }
  127. KThread* KConditionVariable::SignalImpl(KThread* thread) {
  128. // Check pre-conditions.
  129. ASSERT(kernel.GlobalSchedulerContext().IsLocked());
  130. // Update the tag.
  131. VAddr address = thread->GetAddressKey();
  132. u32 own_tag = thread->GetAddressKeyValue();
  133. u32 prev_tag{};
  134. bool can_access{};
  135. {
  136. // TODO(bunnei): We should disable interrupts here via KScopedInterruptDisable.
  137. // TODO(bunnei): We should call CanAccessAtomic(..) here.
  138. can_access = true;
  139. if (can_access) {
  140. UpdateLockAtomic(system, std::addressof(prev_tag), address, own_tag,
  141. Svc::HandleWaitMask);
  142. }
  143. }
  144. KThread* thread_to_close = nullptr;
  145. if (can_access) {
  146. if (prev_tag == Svc::InvalidHandle) {
  147. // If nobody held the lock previously, we're all good.
  148. thread->SetSyncedObject(nullptr, RESULT_SUCCESS);
  149. thread->Wakeup();
  150. } else {
  151. // Get the previous owner.
  152. KThread* owner_thread = kernel.CurrentProcess()
  153. ->GetHandleTable()
  154. .GetObjectWithoutPseudoHandle<KThread>(
  155. static_cast<Handle>(prev_tag & ~Svc::HandleWaitMask))
  156. .ReleasePointerUnsafe();
  157. if (owner_thread) {
  158. // Add the thread as a waiter on the owner.
  159. owner_thread->AddWaiter(thread);
  160. thread_to_close = owner_thread;
  161. } else {
  162. // The lock was tagged with a thread that doesn't exist.
  163. thread->SetSyncedObject(nullptr, ResultInvalidState);
  164. thread->Wakeup();
  165. }
  166. }
  167. } else {
  168. // If the address wasn't accessible, note so.
  169. thread->SetSyncedObject(nullptr, ResultInvalidCurrentMemory);
  170. thread->Wakeup();
  171. }
  172. return thread_to_close;
  173. }
  174. void KConditionVariable::Signal(u64 cv_key, s32 count) {
  175. // Prepare for signaling.
  176. constexpr int MaxThreads = 16;
  177. KLinkedList<KThread> thread_list{kernel};
  178. std::array<KThread*, MaxThreads> thread_array;
  179. s32 num_to_close{};
  180. // Perform signaling.
  181. s32 num_waiters{};
  182. {
  183. KScopedSchedulerLock sl(kernel);
  184. auto it = thread_tree.nfind_light({cv_key, -1});
  185. while ((it != thread_tree.end()) && (count <= 0 || num_waiters < count) &&
  186. (it->GetConditionVariableKey() == cv_key)) {
  187. KThread* target_thread = std::addressof(*it);
  188. if (KThread* thread = SignalImpl(target_thread); thread != nullptr) {
  189. if (num_to_close < MaxThreads) {
  190. thread_array[num_to_close++] = thread;
  191. } else {
  192. thread_list.push_back(*thread);
  193. }
  194. }
  195. it = thread_tree.erase(it);
  196. target_thread->ClearConditionVariable();
  197. ++num_waiters;
  198. }
  199. // If we have no waiters, clear the has waiter flag.
  200. if (it == thread_tree.end() || it->GetConditionVariableKey() != cv_key) {
  201. const u32 has_waiter_flag{};
  202. WriteToUser(system, cv_key, std::addressof(has_waiter_flag));
  203. }
  204. }
  205. // Close threads in the array.
  206. for (auto i = 0; i < num_to_close; ++i) {
  207. thread_array[i]->Close();
  208. }
  209. // Close threads in the list.
  210. for (auto it = thread_list.begin(); it != thread_list.end(); it = thread_list.erase(it)) {
  211. (*it).Close();
  212. }
  213. }
  214. ResultCode KConditionVariable::Wait(VAddr addr, u64 key, u32 value, s64 timeout) {
  215. // Prepare to wait.
  216. KThread* cur_thread = kernel.CurrentScheduler()->GetCurrentThread();
  217. {
  218. KScopedSchedulerLockAndSleep slp{kernel, cur_thread, timeout};
  219. // Set the synced object.
  220. cur_thread->SetSyncedObject(nullptr, ResultTimedOut);
  221. // Check that the thread isn't terminating.
  222. if (cur_thread->IsTerminationRequested()) {
  223. slp.CancelSleep();
  224. return ResultTerminationRequested;
  225. }
  226. // Update the value and process for the next owner.
  227. {
  228. // Remove waiter thread.
  229. s32 num_waiters{};
  230. KThread* next_owner_thread =
  231. cur_thread->RemoveWaiterByKey(std::addressof(num_waiters), addr);
  232. // Update for the next owner thread.
  233. u32 next_value{};
  234. if (next_owner_thread != nullptr) {
  235. // Get the next tag value.
  236. next_value = next_owner_thread->GetAddressKeyValue();
  237. if (num_waiters > 1) {
  238. next_value |= Svc::HandleWaitMask;
  239. }
  240. // Wake up the next owner.
  241. next_owner_thread->SetSyncedObject(nullptr, RESULT_SUCCESS);
  242. next_owner_thread->Wakeup();
  243. }
  244. // Write to the cv key.
  245. {
  246. const u32 has_waiter_flag = 1;
  247. WriteToUser(system, key, std::addressof(has_waiter_flag));
  248. // TODO(bunnei): We should call DataMemoryBarrier(..) here.
  249. }
  250. // Write the value to userspace.
  251. if (!WriteToUser(system, addr, std::addressof(next_value))) {
  252. slp.CancelSleep();
  253. return ResultInvalidCurrentMemory;
  254. }
  255. }
  256. // Update condition variable tracking.
  257. {
  258. cur_thread->SetConditionVariable(std::addressof(thread_tree), addr, key, value);
  259. thread_tree.insert(*cur_thread);
  260. }
  261. // If the timeout is non-zero, set the thread as waiting.
  262. if (timeout != 0) {
  263. cur_thread->SetState(ThreadState::Waiting);
  264. cur_thread->SetWaitReasonForDebugging(ThreadWaitReasonForDebugging::ConditionVar);
  265. cur_thread->SetMutexWaitAddressForDebugging(addr);
  266. }
  267. }
  268. // Cancel the timer wait.
  269. kernel.TimeManager().UnscheduleTimeEvent(cur_thread);
  270. // Remove from the condition variable.
  271. {
  272. KScopedSchedulerLock sl(kernel);
  273. if (KThread* owner = cur_thread->GetLockOwner(); owner != nullptr) {
  274. owner->RemoveWaiter(cur_thread);
  275. }
  276. if (cur_thread->IsWaitingForConditionVariable()) {
  277. thread_tree.erase(thread_tree.iterator_to(*cur_thread));
  278. cur_thread->ClearConditionVariable();
  279. }
  280. }
  281. // Get the result.
  282. KSynchronizationObject* dummy{};
  283. return cur_thread->GetWaitResult(std::addressof(dummy));
  284. }
  285. } // namespace Kernel