k_thread.h 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843
  1. // SPDX-FileCopyrightText: Copyright 2021 yuzu Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #pragma once
  4. #include <array>
  5. #include <atomic>
  6. #include <condition_variable>
  7. #include <mutex>
  8. #include <span>
  9. #include <string>
  10. #include <utility>
  11. #include <vector>
  12. #include <boost/intrusive/list.hpp>
  13. #include "common/common_types.h"
  14. #include "common/intrusive_red_black_tree.h"
  15. #include "common/spin_lock.h"
  16. #include "core/arm/arm_interface.h"
  17. #include "core/hle/kernel/k_affinity_mask.h"
  18. #include "core/hle/kernel/k_light_lock.h"
  19. #include "core/hle/kernel/k_spin_lock.h"
  20. #include "core/hle/kernel/k_synchronization_object.h"
  21. #include "core/hle/kernel/k_worker_task.h"
  22. #include "core/hle/kernel/slab_helpers.h"
  23. #include "core/hle/kernel/svc_common.h"
  24. #include "core/hle/kernel/svc_types.h"
  25. #include "core/hle/result.h"
  26. namespace Common {
  27. class Fiber;
  28. }
  29. namespace Core {
  30. class ARM_Interface;
  31. class System;
  32. } // namespace Core
  33. namespace Kernel {
  34. class GlobalSchedulerContext;
  35. class KernelCore;
  36. class KProcess;
  37. class KScheduler;
  38. class KThreadQueue;
  39. using KThreadFunction = VAddr;
  40. enum class ThreadType : u32 {
  41. Main = 0,
  42. Kernel = 1,
  43. HighPriority = 2,
  44. User = 3,
  45. Dummy = 100, // Special thread type for emulation purposes only
  46. };
  47. DECLARE_ENUM_FLAG_OPERATORS(ThreadType);
  48. enum class SuspendType : u32 {
  49. Process = 0,
  50. Thread = 1,
  51. Debug = 2,
  52. Backtrace = 3,
  53. Init = 4,
  54. Count,
  55. };
  56. enum class ThreadState : u16 {
  57. Initialized = 0,
  58. Waiting = 1,
  59. Runnable = 2,
  60. Terminated = 3,
  61. SuspendShift = 4,
  62. Mask = (1 << SuspendShift) - 1,
  63. ProcessSuspended = (1 << (0 + SuspendShift)),
  64. ThreadSuspended = (1 << (1 + SuspendShift)),
  65. DebugSuspended = (1 << (2 + SuspendShift)),
  66. BacktraceSuspended = (1 << (3 + SuspendShift)),
  67. InitSuspended = (1 << (4 + SuspendShift)),
  68. SuspendFlagMask = ((1 << 5) - 1) << SuspendShift,
  69. };
  70. DECLARE_ENUM_FLAG_OPERATORS(ThreadState);
  71. enum class DpcFlag : u32 {
  72. Terminating = (1 << 0),
  73. Terminated = (1 << 1),
  74. };
  75. enum class ThreadWaitReasonForDebugging : u32 {
  76. None, ///< Thread is not waiting
  77. Sleep, ///< Thread is waiting due to a SleepThread SVC
  78. IPC, ///< Thread is waiting for the reply from an IPC request
  79. Synchronization, ///< Thread is waiting due to a WaitSynchronization SVC
  80. ConditionVar, ///< Thread is waiting due to a WaitProcessWideKey SVC
  81. Arbitration, ///< Thread is waiting due to a SignalToAddress/WaitForAddress SVC
  82. Suspended, ///< Thread is waiting due to process suspension
  83. };
  84. enum class StepState : u32 {
  85. NotStepping, ///< Thread is not currently stepping
  86. StepPending, ///< Thread will step when next scheduled
  87. StepPerformed, ///< Thread has stepped, waiting to be scheduled again
  88. };
  89. void SetCurrentThread(KernelCore& kernel, KThread* thread);
  90. [[nodiscard]] KThread* GetCurrentThreadPointer(KernelCore& kernel);
  91. [[nodiscard]] KThread& GetCurrentThread(KernelCore& kernel);
  92. [[nodiscard]] s32 GetCurrentCoreId(KernelCore& kernel);
  93. class KThread final : public KAutoObjectWithSlabHeapAndContainer<KThread, KWorkerTask>,
  94. public boost::intrusive::list_base_hook<> {
  95. KERNEL_AUTOOBJECT_TRAITS(KThread, KSynchronizationObject);
  96. private:
  97. friend class KScheduler;
  98. friend class KProcess;
  99. public:
  100. static constexpr s32 DefaultThreadPriority = 44;
  101. static constexpr s32 IdleThreadPriority = Svc::LowestThreadPriority + 1;
  102. static constexpr s32 DummyThreadPriority = Svc::LowestThreadPriority + 2;
  103. explicit KThread(KernelCore& kernel_);
  104. ~KThread() override;
  105. public:
  106. using ThreadContext32 = Core::ARM_Interface::ThreadContext32;
  107. using ThreadContext64 = Core::ARM_Interface::ThreadContext64;
  108. using WaiterList = boost::intrusive::list<KThread>;
  109. void SetName(std::string new_name) {
  110. name = std::move(new_name);
  111. }
  112. /**
  113. * Gets the thread's current priority
  114. * @return The current thread's priority
  115. */
  116. [[nodiscard]] s32 GetPriority() const {
  117. return priority;
  118. }
  119. /**
  120. * Sets the thread's current priority.
  121. * @param priority The new priority.
  122. */
  123. void SetPriority(s32 value) {
  124. priority = value;
  125. }
  126. /**
  127. * Gets the thread's nominal priority.
  128. * @return The current thread's nominal priority.
  129. */
  130. [[nodiscard]] s32 GetBasePriority() const {
  131. return base_priority;
  132. }
  133. /**
  134. * Gets the thread's thread ID
  135. * @return The thread's ID
  136. */
  137. [[nodiscard]] u64 GetThreadID() const {
  138. return thread_id;
  139. }
  140. void ContinueIfHasKernelWaiters() {
  141. if (GetNumKernelWaiters() > 0) {
  142. Continue();
  143. }
  144. }
  145. void SetBasePriority(s32 value);
  146. [[nodiscard]] Result Run();
  147. void Exit();
  148. Result Terminate();
  149. ThreadState RequestTerminate();
  150. [[nodiscard]] u32 GetSuspendFlags() const {
  151. return suspend_allowed_flags & suspend_request_flags;
  152. }
  153. [[nodiscard]] bool IsSuspended() const {
  154. return GetSuspendFlags() != 0;
  155. }
  156. [[nodiscard]] bool IsSuspendRequested(SuspendType type) const {
  157. return (suspend_request_flags &
  158. (1u << (static_cast<u32>(ThreadState::SuspendShift) + static_cast<u32>(type)))) !=
  159. 0;
  160. }
  161. [[nodiscard]] bool IsSuspendRequested() const {
  162. return suspend_request_flags != 0;
  163. }
  164. void RequestSuspend(SuspendType type);
  165. void Resume(SuspendType type);
  166. void TrySuspend();
  167. void UpdateState();
  168. void Continue();
  169. void WaitUntilSuspended();
  170. constexpr void SetSyncedIndex(s32 index) {
  171. synced_index = index;
  172. }
  173. [[nodiscard]] constexpr s32 GetSyncedIndex() const {
  174. return synced_index;
  175. }
  176. constexpr void SetWaitResult(Result wait_res) {
  177. wait_result = wait_res;
  178. }
  179. [[nodiscard]] constexpr Result GetWaitResult() const {
  180. return wait_result;
  181. }
  182. /*
  183. * Returns the Thread Local Storage address of the current thread
  184. * @returns VAddr of the thread's TLS
  185. */
  186. [[nodiscard]] VAddr GetTLSAddress() const {
  187. return tls_address;
  188. }
  189. /*
  190. * Returns the value of the TPIDR_EL0 Read/Write system register for this thread.
  191. * @returns The value of the TPIDR_EL0 register.
  192. */
  193. [[nodiscard]] u64 GetTPIDR_EL0() const {
  194. return thread_context_64.tpidr;
  195. }
  196. /// Sets the value of the TPIDR_EL0 Read/Write system register for this thread.
  197. void SetTPIDR_EL0(u64 value) {
  198. thread_context_64.tpidr = value;
  199. thread_context_32.tpidr = static_cast<u32>(value);
  200. }
  201. [[nodiscard]] ThreadContext32& GetContext32() {
  202. return thread_context_32;
  203. }
  204. [[nodiscard]] const ThreadContext32& GetContext32() const {
  205. return thread_context_32;
  206. }
  207. [[nodiscard]] ThreadContext64& GetContext64() {
  208. return thread_context_64;
  209. }
  210. [[nodiscard]] const ThreadContext64& GetContext64() const {
  211. return thread_context_64;
  212. }
  213. [[nodiscard]] std::shared_ptr<Common::Fiber>& GetHostContext();
  214. [[nodiscard]] ThreadState GetState() const {
  215. return thread_state.load(std::memory_order_relaxed) & ThreadState::Mask;
  216. }
  217. [[nodiscard]] ThreadState GetRawState() const {
  218. return thread_state.load(std::memory_order_relaxed);
  219. }
  220. void SetState(ThreadState state);
  221. [[nodiscard]] StepState GetStepState() const {
  222. return step_state;
  223. }
  224. void SetStepState(StepState state) {
  225. step_state = state;
  226. }
  227. [[nodiscard]] s64 GetLastScheduledTick() const {
  228. return last_scheduled_tick;
  229. }
  230. void SetLastScheduledTick(s64 tick) {
  231. last_scheduled_tick = tick;
  232. }
  233. void AddCpuTime([[maybe_unused]] s32 core_id_, s64 amount) {
  234. cpu_time += amount;
  235. // TODO(bunnei): Debug kernels track per-core tick counts. Should we?
  236. }
  237. [[nodiscard]] s64 GetCpuTime() const {
  238. return cpu_time;
  239. }
  240. [[nodiscard]] s32 GetActiveCore() const {
  241. return core_id;
  242. }
  243. void SetActiveCore(s32 core) {
  244. core_id = core;
  245. }
  246. [[nodiscard]] s32 GetCurrentCore() const {
  247. return current_core_id;
  248. }
  249. void SetCurrentCore(s32 core) {
  250. current_core_id = core;
  251. }
  252. [[nodiscard]] KProcess* GetOwnerProcess() {
  253. return parent;
  254. }
  255. [[nodiscard]] const KProcess* GetOwnerProcess() const {
  256. return parent;
  257. }
  258. [[nodiscard]] bool IsUserThread() const {
  259. return parent != nullptr;
  260. }
  261. u16 GetUserDisableCount() const;
  262. void SetInterruptFlag();
  263. void ClearInterruptFlag();
  264. [[nodiscard]] KThread* GetLockOwner() const {
  265. return lock_owner;
  266. }
  267. void SetLockOwner(KThread* owner) {
  268. lock_owner = owner;
  269. }
  270. [[nodiscard]] const KAffinityMask& GetAffinityMask() const {
  271. return physical_affinity_mask;
  272. }
  273. [[nodiscard]] Result GetCoreMask(s32* out_ideal_core, u64* out_affinity_mask);
  274. [[nodiscard]] Result GetPhysicalCoreMask(s32* out_ideal_core, u64* out_affinity_mask);
  275. [[nodiscard]] Result SetCoreMask(s32 cpu_core_id, u64 v_affinity_mask);
  276. [[nodiscard]] Result SetActivity(Svc::ThreadActivity activity);
  277. [[nodiscard]] Result Sleep(s64 timeout);
  278. [[nodiscard]] s64 GetYieldScheduleCount() const {
  279. return schedule_count;
  280. }
  281. void SetYieldScheduleCount(s64 count) {
  282. schedule_count = count;
  283. }
  284. void WaitCancel();
  285. [[nodiscard]] bool IsWaitCancelled() const {
  286. return wait_cancelled;
  287. }
  288. void ClearWaitCancelled() {
  289. wait_cancelled = false;
  290. }
  291. [[nodiscard]] bool IsCancellable() const {
  292. return cancellable;
  293. }
  294. void SetCancellable() {
  295. cancellable = true;
  296. }
  297. void ClearCancellable() {
  298. cancellable = false;
  299. }
  300. [[nodiscard]] bool IsTerminationRequested() const {
  301. return termination_requested || GetRawState() == ThreadState::Terminated;
  302. }
  303. [[nodiscard]] u64 GetId() const override {
  304. return this->GetThreadID();
  305. }
  306. [[nodiscard]] bool IsInitialized() const override {
  307. return initialized;
  308. }
  309. [[nodiscard]] uintptr_t GetPostDestroyArgument() const override {
  310. return reinterpret_cast<uintptr_t>(parent) | (resource_limit_release_hint ? 1 : 0);
  311. }
  312. void Finalize() override;
  313. [[nodiscard]] bool IsSignaled() const override;
  314. void OnTimer();
  315. void DoWorkerTaskImpl();
  316. static void PostDestroy(uintptr_t arg);
  317. [[nodiscard]] static Result InitializeDummyThread(KThread* thread);
  318. [[nodiscard]] static Result InitializeMainThread(Core::System& system, KThread* thread,
  319. s32 virt_core);
  320. [[nodiscard]] static Result InitializeIdleThread(Core::System& system, KThread* thread,
  321. s32 virt_core);
  322. [[nodiscard]] static Result InitializeHighPriorityThread(Core::System& system, KThread* thread,
  323. KThreadFunction func, uintptr_t arg,
  324. s32 virt_core);
  325. [[nodiscard]] static Result InitializeUserThread(Core::System& system, KThread* thread,
  326. KThreadFunction func, uintptr_t arg,
  327. VAddr user_stack_top, s32 prio, s32 virt_core,
  328. KProcess* owner);
  329. public:
  330. struct StackParameters {
  331. u8 svc_permission[0x10];
  332. std::atomic<u8> dpc_flags;
  333. u8 current_svc_id;
  334. bool is_calling_svc;
  335. bool is_in_exception_handler;
  336. bool is_pinned;
  337. s32 disable_count;
  338. KThread* cur_thread;
  339. };
  340. [[nodiscard]] StackParameters& GetStackParameters() {
  341. return stack_parameters;
  342. }
  343. [[nodiscard]] const StackParameters& GetStackParameters() const {
  344. return stack_parameters;
  345. }
  346. class QueueEntry {
  347. public:
  348. constexpr QueueEntry() = default;
  349. constexpr void Initialize() {
  350. prev = nullptr;
  351. next = nullptr;
  352. }
  353. constexpr KThread* GetPrev() const {
  354. return prev;
  355. }
  356. constexpr KThread* GetNext() const {
  357. return next;
  358. }
  359. constexpr void SetPrev(KThread* thread) {
  360. prev = thread;
  361. }
  362. constexpr void SetNext(KThread* thread) {
  363. next = thread;
  364. }
  365. private:
  366. KThread* prev{};
  367. KThread* next{};
  368. };
  369. [[nodiscard]] QueueEntry& GetPriorityQueueEntry(s32 core) {
  370. return per_core_priority_queue_entry[core];
  371. }
  372. [[nodiscard]] const QueueEntry& GetPriorityQueueEntry(s32 core) const {
  373. return per_core_priority_queue_entry[core];
  374. }
  375. [[nodiscard]] s32 GetDisableDispatchCount() const {
  376. return this->GetStackParameters().disable_count;
  377. }
  378. void DisableDispatch() {
  379. ASSERT(GetCurrentThread(kernel).GetDisableDispatchCount() >= 0);
  380. this->GetStackParameters().disable_count++;
  381. }
  382. void EnableDispatch() {
  383. ASSERT(GetCurrentThread(kernel).GetDisableDispatchCount() > 0);
  384. this->GetStackParameters().disable_count--;
  385. }
  386. void Pin(s32 current_core);
  387. void Unpin();
  388. void SetInExceptionHandler() {
  389. this->GetStackParameters().is_in_exception_handler = true;
  390. }
  391. void ClearInExceptionHandler() {
  392. this->GetStackParameters().is_in_exception_handler = false;
  393. }
  394. [[nodiscard]] bool IsInExceptionHandler() const {
  395. return this->GetStackParameters().is_in_exception_handler;
  396. }
  397. void SetIsCallingSvc() {
  398. this->GetStackParameters().is_calling_svc = true;
  399. }
  400. void ClearIsCallingSvc() {
  401. this->GetStackParameters().is_calling_svc = false;
  402. }
  403. [[nodiscard]] bool IsCallingSvc() const {
  404. return this->GetStackParameters().is_calling_svc;
  405. }
  406. [[nodiscard]] u8 GetSvcId() const {
  407. return this->GetStackParameters().current_svc_id;
  408. }
  409. void RegisterDpc(DpcFlag flag) {
  410. this->GetStackParameters().dpc_flags |= static_cast<u8>(flag);
  411. }
  412. void ClearDpc(DpcFlag flag) {
  413. this->GetStackParameters().dpc_flags &= ~static_cast<u8>(flag);
  414. }
  415. [[nodiscard]] u8 GetDpc() const {
  416. return this->GetStackParameters().dpc_flags;
  417. }
  418. [[nodiscard]] bool HasDpc() const {
  419. return this->GetDpc() != 0;
  420. }
  421. void SetWaitReasonForDebugging(ThreadWaitReasonForDebugging reason) {
  422. wait_reason_for_debugging = reason;
  423. }
  424. [[nodiscard]] ThreadWaitReasonForDebugging GetWaitReasonForDebugging() const {
  425. return wait_reason_for_debugging;
  426. }
  427. [[nodiscard]] ThreadType GetThreadType() const {
  428. return thread_type;
  429. }
  430. [[nodiscard]] bool IsDummyThread() const {
  431. return GetThreadType() == ThreadType::Dummy;
  432. }
  433. void SetWaitObjectsForDebugging(const std::span<KSynchronizationObject*>& objects) {
  434. wait_objects_for_debugging.clear();
  435. wait_objects_for_debugging.reserve(objects.size());
  436. for (const auto& object : objects) {
  437. wait_objects_for_debugging.emplace_back(object);
  438. }
  439. }
  440. [[nodiscard]] const std::vector<KSynchronizationObject*>& GetWaitObjectsForDebugging() const {
  441. return wait_objects_for_debugging;
  442. }
  443. void SetMutexWaitAddressForDebugging(VAddr address) {
  444. mutex_wait_address_for_debugging = address;
  445. }
  446. [[nodiscard]] VAddr GetMutexWaitAddressForDebugging() const {
  447. return mutex_wait_address_for_debugging;
  448. }
  449. [[nodiscard]] s32 GetIdealCoreForDebugging() const {
  450. return virtual_ideal_core_id;
  451. }
  452. void AddWaiter(KThread* thread);
  453. void RemoveWaiter(KThread* thread);
  454. [[nodiscard]] Result GetThreadContext3(std::vector<u8>& out);
  455. [[nodiscard]] KThread* RemoveWaiterByKey(s32* out_num_waiters, VAddr key);
  456. [[nodiscard]] VAddr GetAddressKey() const {
  457. return address_key;
  458. }
  459. [[nodiscard]] u32 GetAddressKeyValue() const {
  460. return address_key_value;
  461. }
  462. void SetAddressKey(VAddr key) {
  463. address_key = key;
  464. }
  465. void SetAddressKey(VAddr key, u32 val) {
  466. address_key = key;
  467. address_key_value = val;
  468. }
  469. void ClearWaitQueue() {
  470. wait_queue = nullptr;
  471. }
  472. void BeginWait(KThreadQueue* queue);
  473. void NotifyAvailable(KSynchronizationObject* signaled_object, Result wait_result_);
  474. void EndWait(Result wait_result_);
  475. void CancelWait(Result wait_result_, bool cancel_timer_task);
  476. [[nodiscard]] bool HasWaiters() const {
  477. return !waiter_list.empty();
  478. }
  479. [[nodiscard]] s32 GetNumKernelWaiters() const {
  480. return num_kernel_waiters;
  481. }
  482. [[nodiscard]] u64 GetConditionVariableKey() const {
  483. return condvar_key;
  484. }
  485. [[nodiscard]] u64 GetAddressArbiterKey() const {
  486. return condvar_key;
  487. }
  488. // Dummy threads (used for HLE host threads) cannot wait based on the guest scheduler, and
  489. // therefore will not block on guest kernel synchronization primitives. These methods handle
  490. // blocking as needed.
  491. void IfDummyThreadTryWait();
  492. void IfDummyThreadEndWait();
  493. [[nodiscard]] uintptr_t GetArgument() const {
  494. return argument;
  495. }
  496. [[nodiscard]] VAddr GetUserStackTop() const {
  497. return stack_top;
  498. }
  499. private:
  500. static constexpr size_t PriorityInheritanceCountMax = 10;
  501. union SyncObjectBuffer {
  502. std::array<KSynchronizationObject*, Svc::ArgumentHandleCountMax> sync_objects{};
  503. std::array<Handle,
  504. Svc::ArgumentHandleCountMax*(sizeof(KSynchronizationObject*) / sizeof(Handle))>
  505. handles;
  506. constexpr SyncObjectBuffer() {}
  507. };
  508. static_assert(sizeof(SyncObjectBuffer::sync_objects) == sizeof(SyncObjectBuffer::handles));
  509. struct ConditionVariableComparator {
  510. struct RedBlackKeyType {
  511. u64 cv_key{};
  512. s32 priority{};
  513. [[nodiscard]] constexpr u64 GetConditionVariableKey() const {
  514. return cv_key;
  515. }
  516. [[nodiscard]] constexpr s32 GetPriority() const {
  517. return priority;
  518. }
  519. };
  520. template <typename T>
  521. requires(
  522. std::same_as<T, KThread> ||
  523. std::same_as<T, RedBlackKeyType>) static constexpr int Compare(const T& lhs,
  524. const KThread& rhs) {
  525. const u64 l_key = lhs.GetConditionVariableKey();
  526. const u64 r_key = rhs.GetConditionVariableKey();
  527. if (l_key < r_key) {
  528. // Sort first by key
  529. return -1;
  530. } else if (l_key == r_key && lhs.GetPriority() < rhs.GetPriority()) {
  531. // And then by priority.
  532. return -1;
  533. } else {
  534. return 1;
  535. }
  536. }
  537. };
  538. void AddWaiterImpl(KThread* thread);
  539. void RemoveWaiterImpl(KThread* thread);
  540. void StartTermination();
  541. void FinishTermination();
  542. [[nodiscard]] Result Initialize(KThreadFunction func, uintptr_t arg, VAddr user_stack_top,
  543. s32 prio, s32 virt_core, KProcess* owner, ThreadType type);
  544. [[nodiscard]] static Result InitializeThread(KThread* thread, KThreadFunction func,
  545. uintptr_t arg, VAddr user_stack_top, s32 prio,
  546. s32 core, KProcess* owner, ThreadType type,
  547. std::function<void()>&& init_func);
  548. static void RestorePriority(KernelCore& kernel_ctx, KThread* thread);
  549. // For core KThread implementation
  550. ThreadContext32 thread_context_32{};
  551. ThreadContext64 thread_context_64{};
  552. Common::IntrusiveRedBlackTreeNode condvar_arbiter_tree_node{};
  553. s32 priority{};
  554. using ConditionVariableThreadTreeTraits =
  555. Common::IntrusiveRedBlackTreeMemberTraitsDeferredAssert<
  556. &KThread::condvar_arbiter_tree_node>;
  557. using ConditionVariableThreadTree =
  558. ConditionVariableThreadTreeTraits::TreeType<ConditionVariableComparator>;
  559. ConditionVariableThreadTree* condvar_tree{};
  560. u64 condvar_key{};
  561. u64 virtual_affinity_mask{};
  562. KAffinityMask physical_affinity_mask{};
  563. u64 thread_id{};
  564. std::atomic<s64> cpu_time{};
  565. VAddr address_key{};
  566. KProcess* parent{};
  567. VAddr kernel_stack_top{};
  568. u32* light_ipc_data{};
  569. VAddr tls_address{};
  570. KLightLock activity_pause_lock;
  571. s64 schedule_count{};
  572. s64 last_scheduled_tick{};
  573. std::array<QueueEntry, Core::Hardware::NUM_CPU_CORES> per_core_priority_queue_entry{};
  574. KThreadQueue* wait_queue{};
  575. WaiterList waiter_list{};
  576. WaiterList pinned_waiter_list{};
  577. KThread* lock_owner{};
  578. u32 address_key_value{};
  579. u32 suspend_request_flags{};
  580. u32 suspend_allowed_flags{};
  581. s32 synced_index{};
  582. Result wait_result{ResultSuccess};
  583. s32 base_priority{};
  584. s32 physical_ideal_core_id{};
  585. s32 virtual_ideal_core_id{};
  586. s32 num_kernel_waiters{};
  587. s32 current_core_id{};
  588. s32 core_id{};
  589. KAffinityMask original_physical_affinity_mask{};
  590. s32 original_physical_ideal_core_id{};
  591. s32 num_core_migration_disables{};
  592. std::atomic<ThreadState> thread_state{};
  593. std::atomic<bool> termination_requested{};
  594. bool wait_cancelled{};
  595. bool cancellable{};
  596. bool signaled{};
  597. bool initialized{};
  598. bool debug_attached{};
  599. s8 priority_inheritance_count{};
  600. bool resource_limit_release_hint{};
  601. StackParameters stack_parameters{};
  602. Common::SpinLock context_guard{};
  603. // For emulation
  604. std::shared_ptr<Common::Fiber> host_context{};
  605. bool is_single_core{};
  606. ThreadType thread_type{};
  607. StepState step_state{};
  608. std::mutex dummy_wait_lock;
  609. std::condition_variable dummy_wait_cv;
  610. // For debugging
  611. std::vector<KSynchronizationObject*> wait_objects_for_debugging;
  612. VAddr mutex_wait_address_for_debugging{};
  613. ThreadWaitReasonForDebugging wait_reason_for_debugging{};
  614. uintptr_t argument;
  615. VAddr stack_top;
  616. public:
  617. using ConditionVariableThreadTreeType = ConditionVariableThreadTree;
  618. void SetConditionVariable(ConditionVariableThreadTree* tree, VAddr address, u64 cv_key,
  619. u32 value) {
  620. condvar_tree = tree;
  621. condvar_key = cv_key;
  622. address_key = address;
  623. address_key_value = value;
  624. }
  625. void ClearConditionVariable() {
  626. condvar_tree = nullptr;
  627. }
  628. [[nodiscard]] bool IsWaitingForConditionVariable() const {
  629. return condvar_tree != nullptr;
  630. }
  631. void SetAddressArbiter(ConditionVariableThreadTree* tree, u64 address) {
  632. condvar_tree = tree;
  633. condvar_key = address;
  634. }
  635. void ClearAddressArbiter() {
  636. condvar_tree = nullptr;
  637. }
  638. [[nodiscard]] bool IsWaitingForAddressArbiter() const {
  639. return condvar_tree != nullptr;
  640. }
  641. [[nodiscard]] ConditionVariableThreadTree* GetConditionVariableTree() const {
  642. return condvar_tree;
  643. }
  644. };
  645. class KScopedDisableDispatch {
  646. public:
  647. [[nodiscard]] explicit KScopedDisableDispatch(KernelCore& kernel_) : kernel{kernel_} {
  648. // If we are shutting down the kernel, none of this is relevant anymore.
  649. if (kernel.IsShuttingDown()) {
  650. return;
  651. }
  652. GetCurrentThread(kernel).DisableDispatch();
  653. }
  654. ~KScopedDisableDispatch();
  655. private:
  656. KernelCore& kernel;
  657. };
  658. } // namespace Kernel