k_condition_variable.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  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 = GetCurrentProcess(kernel)
  133. .GetHandleTable()
  134. .GetObjectWithoutPseudoHandle<KThread>(handle)
  135. .ReleasePointerUnsafe();
  136. R_UNLESS(owner_thread != nullptr, ResultInvalidHandle);
  137. // Update the lock.
  138. cur_thread->SetUserAddressKey(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. // NOTE: If scheduler lock is not held here, interrupt disable is required.
  160. // KScopedInterruptDisable di;
  161. // TODO(bunnei): We should call CanAccessAtomic(..) here.
  162. can_access = true;
  163. if (can_access) [[likely]] {
  164. UpdateLockAtomic(system, std::addressof(prev_tag), address, own_tag,
  165. Svc::HandleWaitMask);
  166. }
  167. }
  168. if (can_access) [[likely]] {
  169. if (prev_tag == Svc::InvalidHandle) {
  170. // If nobody held the lock previously, we're all good.
  171. thread->EndWait(ResultSuccess);
  172. } else {
  173. // Get the previous owner.
  174. KThread* owner_thread = GetCurrentProcess(kernel)
  175. .GetHandleTable()
  176. .GetObjectWithoutPseudoHandle<KThread>(
  177. static_cast<Handle>(prev_tag & ~Svc::HandleWaitMask))
  178. .ReleasePointerUnsafe();
  179. if (owner_thread) [[likely]] {
  180. // Add the thread as a waiter on the owner.
  181. owner_thread->AddWaiter(thread);
  182. owner_thread->Close();
  183. } else {
  184. // The lock was tagged with a thread that doesn't exist.
  185. thread->EndWait(ResultInvalidState);
  186. }
  187. }
  188. } else {
  189. // If the address wasn't accessible, note so.
  190. thread->EndWait(ResultInvalidCurrentMemory);
  191. }
  192. }
  193. void KConditionVariable::Signal(u64 cv_key, s32 count) {
  194. // Perform signaling.
  195. s32 num_waiters{};
  196. {
  197. KScopedSchedulerLock sl(kernel);
  198. auto it = thread_tree.nfind_key({cv_key, -1});
  199. while ((it != thread_tree.end()) && (count <= 0 || num_waiters < count) &&
  200. (it->GetConditionVariableKey() == cv_key)) {
  201. KThread* target_thread = std::addressof(*it);
  202. this->SignalImpl(target_thread);
  203. it = thread_tree.erase(it);
  204. target_thread->ClearConditionVariable();
  205. ++num_waiters;
  206. }
  207. // If we have no waiters, clear the has waiter flag.
  208. if (it == thread_tree.end() || it->GetConditionVariableKey() != cv_key) {
  209. const u32 has_waiter_flag{};
  210. WriteToUser(system, cv_key, std::addressof(has_waiter_flag));
  211. }
  212. }
  213. }
  214. Result KConditionVariable::Wait(VAddr addr, u64 key, u32 value, s64 timeout) {
  215. // Prepare to wait.
  216. KThread* cur_thread = GetCurrentThreadPointer(kernel);
  217. ThreadQueueImplForKConditionVariableWaitConditionVariable wait_queue(
  218. kernel, std::addressof(thread_tree));
  219. {
  220. KScopedSchedulerLockAndSleep slp(kernel, cur_thread, timeout);
  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->EndWait(ResultSuccess);
  242. }
  243. // Write to the cv key.
  244. {
  245. const u32 has_waiter_flag = 1;
  246. WriteToUser(system, key, std::addressof(has_waiter_flag));
  247. // TODO(bunnei): We should call DataMemoryBarrier(..) here.
  248. }
  249. // Write the value to userspace.
  250. if (!WriteToUser(system, addr, std::addressof(next_value))) {
  251. slp.CancelSleep();
  252. return ResultInvalidCurrentMemory;
  253. }
  254. }
  255. // If timeout is zero, time out.
  256. R_UNLESS(timeout != 0, ResultTimedOut);
  257. // Update condition variable tracking.
  258. cur_thread->SetConditionVariable(std::addressof(thread_tree), addr, key, value);
  259. thread_tree.insert(*cur_thread);
  260. // Begin waiting.
  261. cur_thread->BeginWait(std::addressof(wait_queue));
  262. cur_thread->SetWaitReasonForDebugging(ThreadWaitReasonForDebugging::ConditionVar);
  263. cur_thread->SetMutexWaitAddressForDebugging(addr);
  264. }
  265. // Get the wait result.
  266. return cur_thread->GetWaitResult();
  267. }
  268. } // namespace Kernel