k_condition_variable.cpp 11 KB

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