k_condition_variable.cpp 11 KB

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