k_thread.h 28 KB

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