k_thread.h 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967
  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 "common/intrusive_list.h"
  13. #include "common/intrusive_red_black_tree.h"
  14. #include "common/scratch_buffer.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_timer_task.h"
  22. #include "core/hle/kernel/k_typed_address.h"
  23. #include "core/hle/kernel/k_worker_task.h"
  24. #include "core/hle/kernel/slab_helpers.h"
  25. #include "core/hle/kernel/svc_common.h"
  26. #include "core/hle/kernel/svc_types.h"
  27. #include "core/hle/result.h"
  28. namespace Common {
  29. class Fiber;
  30. }
  31. namespace Core {
  32. namespace Memory {
  33. class Memory;
  34. }
  35. class ARM_Interface;
  36. class System;
  37. } // namespace Core
  38. namespace Kernel {
  39. class GlobalSchedulerContext;
  40. class KernelCore;
  41. class KProcess;
  42. class KScheduler;
  43. class KThreadQueue;
  44. using KThreadFunction = KProcessAddress;
  45. enum class ThreadType : u32 {
  46. Main = 0,
  47. Kernel = 1,
  48. HighPriority = 2,
  49. User = 3,
  50. Dummy = 100, // Special thread type for emulation purposes only
  51. };
  52. DECLARE_ENUM_FLAG_OPERATORS(ThreadType);
  53. enum class SuspendType : u32 {
  54. Process = 0,
  55. Thread = 1,
  56. Debug = 2,
  57. Backtrace = 3,
  58. Init = 4,
  59. Count,
  60. };
  61. enum class ThreadState : u16 {
  62. Initialized = 0,
  63. Waiting = 1,
  64. Runnable = 2,
  65. Terminated = 3,
  66. SuspendShift = 4,
  67. Mask = (1 << SuspendShift) - 1,
  68. ProcessSuspended = (1 << (0 + SuspendShift)),
  69. ThreadSuspended = (1 << (1 + SuspendShift)),
  70. DebugSuspended = (1 << (2 + SuspendShift)),
  71. BacktraceSuspended = (1 << (3 + SuspendShift)),
  72. InitSuspended = (1 << (4 + SuspendShift)),
  73. SuspendFlagMask = ((1 << 5) - 1) << SuspendShift,
  74. };
  75. DECLARE_ENUM_FLAG_OPERATORS(ThreadState);
  76. enum class DpcFlag : u32 {
  77. Terminating = (1 << 0),
  78. Terminated = (1 << 1),
  79. };
  80. enum class ThreadWaitReasonForDebugging : u32 {
  81. None, ///< Thread is not waiting
  82. Sleep, ///< Thread is waiting due to a SleepThread SVC
  83. IPC, ///< Thread is waiting for the reply from an IPC request
  84. Synchronization, ///< Thread is waiting due to a WaitSynchronization SVC
  85. ConditionVar, ///< Thread is waiting due to a WaitProcessWideKey SVC
  86. Arbitration, ///< Thread is waiting due to a SignalToAddress/WaitForAddress SVC
  87. Suspended, ///< Thread is waiting due to process suspension
  88. };
  89. enum class StepState : u32 {
  90. NotStepping, ///< Thread is not currently stepping
  91. StepPending, ///< Thread will step when next scheduled
  92. StepPerformed, ///< Thread has stepped, waiting to be scheduled again
  93. };
  94. void SetCurrentThread(KernelCore& kernel, KThread* thread);
  95. KThread* GetCurrentThreadPointer(KernelCore& kernel);
  96. KThread& GetCurrentThread(KernelCore& kernel);
  97. KProcess* GetCurrentProcessPointer(KernelCore& kernel);
  98. KProcess& GetCurrentProcess(KernelCore& kernel);
  99. s32 GetCurrentCoreId(KernelCore& kernel);
  100. Core::Memory::Memory& GetCurrentMemory(KernelCore& kernel);
  101. class KThread final : public KAutoObjectWithSlabHeapAndContainer<KThread, KWorkerTask>,
  102. public Common::IntrusiveListBaseNode<KThread>,
  103. public KTimerTask {
  104. KERNEL_AUTOOBJECT_TRAITS(KThread, KSynchronizationObject);
  105. private:
  106. friend class KScheduler;
  107. friend class KProcess;
  108. public:
  109. static constexpr s32 DefaultThreadPriority = 44;
  110. static constexpr s32 IdleThreadPriority = Svc::LowestThreadPriority + 1;
  111. static constexpr s32 DummyThreadPriority = Svc::LowestThreadPriority + 2;
  112. explicit KThread(KernelCore& kernel);
  113. ~KThread() override;
  114. public:
  115. using ThreadContext32 = Core::ARM_Interface::ThreadContext32;
  116. using ThreadContext64 = Core::ARM_Interface::ThreadContext64;
  117. using WaiterList = Common::IntrusiveListBaseTraits<KThread>::ListType;
  118. /**
  119. * Gets the thread's current priority
  120. * @return The current thread's priority
  121. */
  122. s32 GetPriority() const {
  123. return m_priority;
  124. }
  125. /**
  126. * Sets the thread's current priority.
  127. * @param priority The new priority.
  128. */
  129. void SetPriority(s32 value) {
  130. m_priority = value;
  131. }
  132. /**
  133. * Gets the thread's nominal priority.
  134. * @return The current thread's nominal priority.
  135. */
  136. s32 GetBasePriority() const {
  137. return m_base_priority;
  138. }
  139. /**
  140. * Gets the thread's thread ID
  141. * @return The thread's ID
  142. */
  143. u64 GetThreadId() const {
  144. return m_thread_id;
  145. }
  146. void ContinueIfHasKernelWaiters() {
  147. if (GetNumKernelWaiters() > 0) {
  148. Continue();
  149. }
  150. }
  151. void SetBasePriority(s32 value);
  152. Result Run();
  153. void Exit();
  154. Result Terminate();
  155. ThreadState RequestTerminate();
  156. u32 GetSuspendFlags() const {
  157. return m_suspend_allowed_flags & m_suspend_request_flags;
  158. }
  159. bool IsSuspended() const {
  160. return GetSuspendFlags() != 0;
  161. }
  162. bool IsSuspendRequested(SuspendType type) const {
  163. return (m_suspend_request_flags &
  164. (1U << (static_cast<u32>(ThreadState::SuspendShift) + static_cast<u32>(type)))) !=
  165. 0;
  166. }
  167. bool IsSuspendRequested() const {
  168. return m_suspend_request_flags != 0;
  169. }
  170. void RequestSuspend(SuspendType type);
  171. void Resume(SuspendType type);
  172. void TrySuspend();
  173. void UpdateState();
  174. void Continue();
  175. constexpr void SetSyncedIndex(s32 index) {
  176. m_synced_index = index;
  177. }
  178. constexpr s32 GetSyncedIndex() const {
  179. return m_synced_index;
  180. }
  181. constexpr void SetWaitResult(Result wait_res) {
  182. m_wait_result = wait_res;
  183. }
  184. constexpr Result GetWaitResult() const {
  185. return m_wait_result;
  186. }
  187. /*
  188. * Returns the Thread Local Storage address of the current thread
  189. * @returns Address of the thread's TLS
  190. */
  191. KProcessAddress GetTlsAddress() const {
  192. return m_tls_address;
  193. }
  194. /*
  195. * Returns the value of the TPIDR_EL0 Read/Write system register for this thread.
  196. * @returns The value of the TPIDR_EL0 register.
  197. */
  198. u64 GetTpidrEl0() const {
  199. return m_thread_context_64.tpidr;
  200. }
  201. /// Sets the value of the TPIDR_EL0 Read/Write system register for this thread.
  202. void SetTpidrEl0(u64 value) {
  203. m_thread_context_64.tpidr = value;
  204. m_thread_context_32.tpidr = static_cast<u32>(value);
  205. }
  206. void CloneFpuStatus();
  207. ThreadContext32& GetContext32() {
  208. return m_thread_context_32;
  209. }
  210. const ThreadContext32& GetContext32() const {
  211. return m_thread_context_32;
  212. }
  213. ThreadContext64& GetContext64() {
  214. return m_thread_context_64;
  215. }
  216. const ThreadContext64& GetContext64() const {
  217. return m_thread_context_64;
  218. }
  219. std::shared_ptr<Common::Fiber>& GetHostContext();
  220. ThreadState GetState() const {
  221. return m_thread_state.load(std::memory_order_relaxed) & ThreadState::Mask;
  222. }
  223. ThreadState GetRawState() const {
  224. return m_thread_state.load(std::memory_order_relaxed);
  225. }
  226. void SetState(ThreadState state);
  227. StepState GetStepState() const {
  228. return m_step_state;
  229. }
  230. void SetStepState(StepState state) {
  231. m_step_state = state;
  232. }
  233. s64 GetLastScheduledTick() const {
  234. return m_last_scheduled_tick;
  235. }
  236. void SetLastScheduledTick(s64 tick) {
  237. m_last_scheduled_tick = tick;
  238. }
  239. void AddCpuTime(s32 core_id, s64 amount) {
  240. m_cpu_time += amount;
  241. // TODO(bunnei): Debug kernels track per-core tick counts. Should we?
  242. }
  243. s64 GetCpuTime() const {
  244. return m_cpu_time;
  245. }
  246. s32 GetActiveCore() const {
  247. return m_core_id;
  248. }
  249. void SetActiveCore(s32 core) {
  250. m_core_id = core;
  251. }
  252. s32 GetCurrentCore() const {
  253. return m_current_core_id;
  254. }
  255. void SetCurrentCore(s32 core) {
  256. m_current_core_id = core;
  257. }
  258. KProcess* GetOwnerProcess() {
  259. return m_parent;
  260. }
  261. const KProcess* GetOwnerProcess() const {
  262. return m_parent;
  263. }
  264. bool IsUserThread() const {
  265. return m_parent != nullptr;
  266. }
  267. u16 GetUserDisableCount() const;
  268. void SetInterruptFlag();
  269. void ClearInterruptFlag();
  270. KThread* GetLockOwner() const;
  271. const KAffinityMask& GetAffinityMask() const {
  272. return m_physical_affinity_mask;
  273. }
  274. Result GetCoreMask(s32* out_ideal_core, u64* out_affinity_mask);
  275. Result GetPhysicalCoreMask(s32* out_ideal_core, u64* out_affinity_mask);
  276. Result SetCoreMask(s32 cpu_core_id, u64 v_affinity_mask);
  277. Result SetActivity(Svc::ThreadActivity activity);
  278. Result Sleep(s64 timeout);
  279. s64 GetYieldScheduleCount() const {
  280. return m_schedule_count;
  281. }
  282. void SetYieldScheduleCount(s64 count) {
  283. m_schedule_count = count;
  284. }
  285. void WaitCancel();
  286. bool IsWaitCancelled() const {
  287. return m_wait_cancelled;
  288. }
  289. void ClearWaitCancelled() {
  290. m_wait_cancelled = false;
  291. }
  292. bool IsCancellable() const {
  293. return m_cancellable;
  294. }
  295. void SetCancellable() {
  296. m_cancellable = true;
  297. }
  298. void ClearCancellable() {
  299. m_cancellable = false;
  300. }
  301. bool IsTerminationRequested() const {
  302. return m_termination_requested || GetRawState() == ThreadState::Terminated;
  303. }
  304. u64 GetId() const override {
  305. return this->GetThreadId();
  306. }
  307. bool IsInitialized() const override {
  308. return m_initialized;
  309. }
  310. uintptr_t GetPostDestroyArgument() const override {
  311. return reinterpret_cast<uintptr_t>(m_parent) | (m_resource_limit_release_hint ? 1 : 0);
  312. }
  313. void Finalize() override;
  314. bool IsSignaled() const override;
  315. void OnTimer();
  316. void DoWorkerTaskImpl();
  317. static void PostDestroy(uintptr_t arg);
  318. static Result InitializeDummyThread(KThread* thread, KProcess* owner);
  319. static Result InitializeMainThread(Core::System& system, KThread* thread, s32 virt_core);
  320. static Result InitializeIdleThread(Core::System& system, KThread* thread, s32 virt_core);
  321. static Result InitializeHighPriorityThread(Core::System& system, KThread* thread,
  322. KThreadFunction func, uintptr_t arg, s32 virt_core);
  323. static Result InitializeUserThread(Core::System& system, KThread* thread, KThreadFunction func,
  324. uintptr_t arg, KProcessAddress user_stack_top, s32 prio,
  325. s32 virt_core, KProcess* owner);
  326. static Result InitializeServiceThread(Core::System& system, KThread* thread,
  327. std::function<void()>&& thread_func, s32 prio,
  328. s32 virt_core, 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. StackParameters& GetStackParameters() {
  341. return m_stack_parameters;
  342. }
  343. const StackParameters& GetStackParameters() const {
  344. return m_stack_parameters;
  345. }
  346. class QueueEntry {
  347. public:
  348. constexpr QueueEntry() = default;
  349. constexpr void Initialize() {
  350. m_prev = nullptr;
  351. m_next = nullptr;
  352. }
  353. constexpr KThread* GetPrev() const {
  354. return m_prev;
  355. }
  356. constexpr KThread* GetNext() const {
  357. return m_next;
  358. }
  359. constexpr void SetPrev(KThread* thread) {
  360. m_prev = thread;
  361. }
  362. constexpr void SetNext(KThread* thread) {
  363. m_next = thread;
  364. }
  365. private:
  366. KThread* m_prev{};
  367. KThread* m_next{};
  368. };
  369. QueueEntry& GetPriorityQueueEntry(s32 core) {
  370. return m_per_core_priority_queue_entry[core];
  371. }
  372. const QueueEntry& GetPriorityQueueEntry(s32 core) const {
  373. return m_per_core_priority_queue_entry[core];
  374. }
  375. s32 GetDisableDispatchCount() const {
  376. return this->GetStackParameters().disable_count;
  377. }
  378. void DisableDispatch() {
  379. ASSERT(GetCurrentThread(m_kernel).GetDisableDispatchCount() >= 0);
  380. this->GetStackParameters().disable_count++;
  381. }
  382. void EnableDispatch() {
  383. ASSERT(GetCurrentThread(m_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. 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. bool IsCallingSvc() const {
  404. return this->GetStackParameters().is_calling_svc;
  405. }
  406. 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. u8 GetDpc() const {
  416. return this->GetStackParameters().dpc_flags;
  417. }
  418. bool HasDpc() const {
  419. return this->GetDpc() != 0;
  420. }
  421. void SetWaitReasonForDebugging(ThreadWaitReasonForDebugging reason) {
  422. m_wait_reason_for_debugging = reason;
  423. }
  424. ThreadWaitReasonForDebugging GetWaitReasonForDebugging() const {
  425. return m_wait_reason_for_debugging;
  426. }
  427. ThreadType GetThreadType() const {
  428. return m_thread_type;
  429. }
  430. bool IsDummyThread() const {
  431. return this->GetThreadType() == ThreadType::Dummy;
  432. }
  433. void AddWaiter(KThread* thread);
  434. void RemoveWaiter(KThread* thread);
  435. Result GetThreadContext3(Common::ScratchBuffer<u8>& out);
  436. KThread* RemoveUserWaiterByKey(bool* out_has_waiters, KProcessAddress key) {
  437. return this->RemoveWaiterByKey(out_has_waiters, key, false);
  438. }
  439. KThread* RemoveKernelWaiterByKey(bool* out_has_waiters, KProcessAddress key) {
  440. return this->RemoveWaiterByKey(out_has_waiters, key, true);
  441. }
  442. KProcessAddress GetAddressKey() const {
  443. return m_address_key;
  444. }
  445. u32 GetAddressKeyValue() const {
  446. return m_address_key_value;
  447. }
  448. bool GetIsKernelAddressKey() const {
  449. return m_is_kernel_address_key;
  450. }
  451. //! NB: intentional deviation from official kernel.
  452. //
  453. // Separate SetAddressKey into user and kernel versions
  454. // to cope with arbitrary host pointers making their way
  455. // into things.
  456. void SetUserAddressKey(KProcessAddress key, u32 val) {
  457. ASSERT(m_waiting_lock_info == nullptr);
  458. m_address_key = key;
  459. m_address_key_value = val;
  460. m_is_kernel_address_key = false;
  461. }
  462. void SetKernelAddressKey(KProcessAddress key) {
  463. ASSERT(m_waiting_lock_info == nullptr);
  464. m_address_key = key;
  465. m_is_kernel_address_key = true;
  466. }
  467. void ClearWaitQueue() {
  468. m_wait_queue = nullptr;
  469. }
  470. void BeginWait(KThreadQueue* queue);
  471. void NotifyAvailable(KSynchronizationObject* signaled_object, Result wait_result);
  472. void EndWait(Result wait_result);
  473. void CancelWait(Result wait_result, bool cancel_timer_task);
  474. s32 GetNumKernelWaiters() const {
  475. return m_num_kernel_waiters;
  476. }
  477. u64 GetConditionVariableKey() const {
  478. return m_condvar_key;
  479. }
  480. u64 GetAddressArbiterKey() const {
  481. return m_condvar_key;
  482. }
  483. // Dummy threads (used for HLE host threads) cannot wait based on the guest scheduler, and
  484. // therefore will not block on guest kernel synchronization primitives. These methods handle
  485. // blocking as needed.
  486. void RequestDummyThreadWait();
  487. void DummyThreadBeginWait();
  488. void DummyThreadEndWait();
  489. uintptr_t GetArgument() const {
  490. return m_argument;
  491. }
  492. KProcessAddress GetUserStackTop() const {
  493. return m_stack_top;
  494. }
  495. private:
  496. KThread* RemoveWaiterByKey(bool* out_has_waiters, KProcessAddress key,
  497. bool is_kernel_address_key);
  498. static constexpr size_t PriorityInheritanceCountMax = 10;
  499. union SyncObjectBuffer {
  500. std::array<KSynchronizationObject*, Svc::ArgumentHandleCountMax> sync_objects{};
  501. std::array<Handle,
  502. Svc::ArgumentHandleCountMax * (sizeof(KSynchronizationObject*) / sizeof(Handle))>
  503. handles;
  504. constexpr SyncObjectBuffer() {}
  505. };
  506. static_assert(sizeof(SyncObjectBuffer::sync_objects) == sizeof(SyncObjectBuffer::handles));
  507. struct ConditionVariableComparator {
  508. struct RedBlackKeyType {
  509. u64 cv_key{};
  510. s32 priority{};
  511. constexpr u64 GetConditionVariableKey() const {
  512. return cv_key;
  513. }
  514. constexpr s32 GetPriority() const {
  515. return priority;
  516. }
  517. };
  518. template <typename T>
  519. requires(std::same_as<T, KThread> || std::same_as<T, RedBlackKeyType>)
  520. static constexpr int Compare(const T& lhs, const KThread& rhs) {
  521. const u64 l_key = lhs.GetConditionVariableKey();
  522. const u64 r_key = rhs.GetConditionVariableKey();
  523. if (l_key < r_key) {
  524. // Sort first by key
  525. return -1;
  526. } else if (l_key == r_key && lhs.GetPriority() < rhs.GetPriority()) {
  527. // And then by priority.
  528. return -1;
  529. } else {
  530. return 1;
  531. }
  532. }
  533. };
  534. void AddWaiterImpl(KThread* thread);
  535. void RemoveWaiterImpl(KThread* thread);
  536. static void RestorePriority(KernelCore& kernel, KThread* thread);
  537. void StartTermination();
  538. void FinishTermination();
  539. void IncreaseBasePriority(s32 priority);
  540. Result Initialize(KThreadFunction func, uintptr_t arg, KProcessAddress user_stack_top, s32 prio,
  541. s32 virt_core, KProcess* owner, ThreadType type);
  542. static Result InitializeThread(KThread* thread, KThreadFunction func, uintptr_t arg,
  543. KProcessAddress user_stack_top, s32 prio, s32 core,
  544. KProcess* owner, ThreadType type,
  545. std::function<void()>&& init_func);
  546. // For core KThread implementation
  547. ThreadContext32 m_thread_context_32{};
  548. ThreadContext64 m_thread_context_64{};
  549. Common::IntrusiveRedBlackTreeNode m_condvar_arbiter_tree_node{};
  550. s32 m_priority{};
  551. using ConditionVariableThreadTreeTraits =
  552. Common::IntrusiveRedBlackTreeMemberTraitsDeferredAssert<
  553. &KThread::m_condvar_arbiter_tree_node>;
  554. using ConditionVariableThreadTree =
  555. ConditionVariableThreadTreeTraits::TreeType<ConditionVariableComparator>;
  556. private:
  557. struct LockWithPriorityInheritanceComparator {
  558. struct RedBlackKeyType {
  559. s32 m_priority;
  560. constexpr s32 GetPriority() const {
  561. return m_priority;
  562. }
  563. };
  564. template <typename T>
  565. requires(std::same_as<T, KThread> || std::same_as<T, RedBlackKeyType>)
  566. static constexpr int Compare(const T& lhs, const KThread& rhs) {
  567. if (lhs.GetPriority() < rhs.GetPriority()) {
  568. // Sort by priority.
  569. return -1;
  570. } else {
  571. return 1;
  572. }
  573. }
  574. };
  575. static_assert(std::same_as<Common::RedBlackKeyType<LockWithPriorityInheritanceComparator, void>,
  576. LockWithPriorityInheritanceComparator::RedBlackKeyType>);
  577. using LockWithPriorityInheritanceThreadTreeTraits =
  578. Common::IntrusiveRedBlackTreeMemberTraitsDeferredAssert<
  579. &KThread::m_condvar_arbiter_tree_node>;
  580. using LockWithPriorityInheritanceThreadTree =
  581. ConditionVariableThreadTreeTraits::TreeType<LockWithPriorityInheritanceComparator>;
  582. public:
  583. class LockWithPriorityInheritanceInfo
  584. : public KSlabAllocated<LockWithPriorityInheritanceInfo>,
  585. public Common::IntrusiveListBaseNode<LockWithPriorityInheritanceInfo> {
  586. public:
  587. explicit LockWithPriorityInheritanceInfo(KernelCore&) {}
  588. static LockWithPriorityInheritanceInfo* Create(KernelCore& kernel,
  589. KProcessAddress address_key,
  590. bool is_kernel_address_key) {
  591. // Create a new lock info.
  592. auto* new_lock = LockWithPriorityInheritanceInfo::Allocate(kernel);
  593. ASSERT(new_lock != nullptr);
  594. // Set the new lock's address key.
  595. new_lock->m_address_key = address_key;
  596. new_lock->m_is_kernel_address_key = is_kernel_address_key;
  597. return new_lock;
  598. }
  599. void SetOwner(KThread* new_owner) {
  600. // Set new owner.
  601. m_owner = new_owner;
  602. }
  603. void AddWaiter(KThread* waiter) {
  604. // Insert the waiter.
  605. m_tree.insert(*waiter);
  606. m_waiter_count++;
  607. waiter->SetWaitingLockInfo(this);
  608. }
  609. bool RemoveWaiter(KThread* waiter) {
  610. m_tree.erase(m_tree.iterator_to(*waiter));
  611. waiter->SetWaitingLockInfo(nullptr);
  612. return (--m_waiter_count) == 0;
  613. }
  614. KThread* GetHighestPriorityWaiter() {
  615. return std::addressof(m_tree.front());
  616. }
  617. const KThread* GetHighestPriorityWaiter() const {
  618. return std::addressof(m_tree.front());
  619. }
  620. LockWithPriorityInheritanceThreadTree& GetThreadTree() {
  621. return m_tree;
  622. }
  623. const LockWithPriorityInheritanceThreadTree& GetThreadTree() const {
  624. return m_tree;
  625. }
  626. KProcessAddress GetAddressKey() const {
  627. return m_address_key;
  628. }
  629. bool GetIsKernelAddressKey() const {
  630. return m_is_kernel_address_key;
  631. }
  632. KThread* GetOwner() const {
  633. return m_owner;
  634. }
  635. u32 GetWaiterCount() const {
  636. return m_waiter_count;
  637. }
  638. private:
  639. LockWithPriorityInheritanceThreadTree m_tree{};
  640. KProcessAddress m_address_key{};
  641. KThread* m_owner{};
  642. u32 m_waiter_count{};
  643. bool m_is_kernel_address_key{};
  644. };
  645. void SetWaitingLockInfo(LockWithPriorityInheritanceInfo* lock) {
  646. m_waiting_lock_info = lock;
  647. }
  648. LockWithPriorityInheritanceInfo* GetWaitingLockInfo() {
  649. return m_waiting_lock_info;
  650. }
  651. void AddHeldLock(LockWithPriorityInheritanceInfo* lock_info);
  652. LockWithPriorityInheritanceInfo* FindHeldLock(KProcessAddress address_key,
  653. bool is_kernel_address_key);
  654. private:
  655. using LockWithPriorityInheritanceInfoList =
  656. Common::IntrusiveListBaseTraits<LockWithPriorityInheritanceInfo>::ListType;
  657. ConditionVariableThreadTree* m_condvar_tree{};
  658. u64 m_condvar_key{};
  659. u64 m_virtual_affinity_mask{};
  660. KAffinityMask m_physical_affinity_mask{};
  661. u64 m_thread_id{};
  662. std::atomic<s64> m_cpu_time{};
  663. KProcessAddress m_address_key{};
  664. KProcess* m_parent{};
  665. KVirtualAddress m_kernel_stack_top{};
  666. u32* m_light_ipc_data{};
  667. KProcessAddress m_tls_address{};
  668. KLightLock m_activity_pause_lock;
  669. s64 m_schedule_count{};
  670. s64 m_last_scheduled_tick{};
  671. std::array<QueueEntry, Core::Hardware::NUM_CPU_CORES> m_per_core_priority_queue_entry{};
  672. KThreadQueue* m_wait_queue{};
  673. LockWithPriorityInheritanceInfoList m_held_lock_info_list{};
  674. LockWithPriorityInheritanceInfo* m_waiting_lock_info{};
  675. WaiterList m_pinned_waiter_list{};
  676. u32 m_address_key_value{};
  677. u32 m_suspend_request_flags{};
  678. u32 m_suspend_allowed_flags{};
  679. s32 m_synced_index{};
  680. Result m_wait_result{ResultSuccess};
  681. s32 m_base_priority{};
  682. s32 m_physical_ideal_core_id{};
  683. s32 m_virtual_ideal_core_id{};
  684. s32 m_num_kernel_waiters{};
  685. s32 m_current_core_id{};
  686. s32 m_core_id{};
  687. KAffinityMask m_original_physical_affinity_mask{};
  688. s32 m_original_physical_ideal_core_id{};
  689. s32 m_num_core_migration_disables{};
  690. std::atomic<ThreadState> m_thread_state{};
  691. std::atomic<bool> m_termination_requested{};
  692. bool m_wait_cancelled{};
  693. bool m_cancellable{};
  694. bool m_signaled{};
  695. bool m_initialized{};
  696. bool m_debug_attached{};
  697. s8 m_priority_inheritance_count{};
  698. bool m_resource_limit_release_hint{};
  699. bool m_is_kernel_address_key{};
  700. StackParameters m_stack_parameters{};
  701. Common::SpinLock m_context_guard{};
  702. // For emulation
  703. std::shared_ptr<Common::Fiber> m_host_context{};
  704. ThreadType m_thread_type{};
  705. StepState m_step_state{};
  706. bool m_dummy_thread_runnable{true};
  707. std::mutex m_dummy_thread_mutex{};
  708. std::condition_variable m_dummy_thread_cv{};
  709. // For debugging
  710. std::vector<KSynchronizationObject*> m_wait_objects_for_debugging{};
  711. KProcessAddress m_mutex_wait_address_for_debugging{};
  712. ThreadWaitReasonForDebugging m_wait_reason_for_debugging{};
  713. uintptr_t m_argument{};
  714. KProcessAddress m_stack_top{};
  715. public:
  716. using ConditionVariableThreadTreeType = ConditionVariableThreadTree;
  717. void SetConditionVariable(ConditionVariableThreadTree* tree, KProcessAddress address,
  718. u64 cv_key, u32 value) {
  719. ASSERT(m_waiting_lock_info == nullptr);
  720. m_condvar_tree = tree;
  721. m_condvar_key = cv_key;
  722. m_address_key = address;
  723. m_address_key_value = value;
  724. m_is_kernel_address_key = false;
  725. }
  726. void ClearConditionVariable() {
  727. m_condvar_tree = nullptr;
  728. }
  729. bool IsWaitingForConditionVariable() const {
  730. return m_condvar_tree != nullptr;
  731. }
  732. void SetAddressArbiter(ConditionVariableThreadTree* tree, u64 address) {
  733. ASSERT(m_waiting_lock_info == nullptr);
  734. m_condvar_tree = tree;
  735. m_condvar_key = address;
  736. }
  737. void ClearAddressArbiter() {
  738. m_condvar_tree = nullptr;
  739. }
  740. bool IsWaitingForAddressArbiter() const {
  741. return m_condvar_tree != nullptr;
  742. }
  743. ConditionVariableThreadTree* GetConditionVariableTree() const {
  744. return m_condvar_tree;
  745. }
  746. };
  747. class KScopedDisableDispatch {
  748. public:
  749. explicit KScopedDisableDispatch(KernelCore& kernel) : m_kernel{kernel} {
  750. // If we are shutting down the kernel, none of this is relevant anymore.
  751. if (m_kernel.IsShuttingDown()) {
  752. return;
  753. }
  754. GetCurrentThread(kernel).DisableDispatch();
  755. }
  756. ~KScopedDisableDispatch();
  757. private:
  758. KernelCore& m_kernel;
  759. };
  760. inline void KTimerTask::OnTimer() {
  761. static_cast<KThread*>(this)->OnTimer();
  762. }
  763. } // namespace Kernel