k_condition_variable.cpp 11 KB

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