k_thread.cpp 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305
  1. // SPDX-FileCopyrightText: Copyright 2021 yuzu Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #include <algorithm>
  4. #include <atomic>
  5. #include <cinttypes>
  6. #include <optional>
  7. #include <vector>
  8. #include "common/assert.h"
  9. #include "common/bit_util.h"
  10. #include "common/common_funcs.h"
  11. #include "common/common_types.h"
  12. #include "common/fiber.h"
  13. #include "common/logging/log.h"
  14. #include "common/settings.h"
  15. #include "core/core.h"
  16. #include "core/cpu_manager.h"
  17. #include "core/hardware_properties.h"
  18. #include "core/hle/kernel/k_condition_variable.h"
  19. #include "core/hle/kernel/k_handle_table.h"
  20. #include "core/hle/kernel/k_memory_layout.h"
  21. #include "core/hle/kernel/k_process.h"
  22. #include "core/hle/kernel/k_resource_limit.h"
  23. #include "core/hle/kernel/k_scheduler.h"
  24. #include "core/hle/kernel/k_scoped_scheduler_lock_and_sleep.h"
  25. #include "core/hle/kernel/k_system_control.h"
  26. #include "core/hle/kernel/k_thread.h"
  27. #include "core/hle/kernel/k_thread_queue.h"
  28. #include "core/hle/kernel/k_worker_task_manager.h"
  29. #include "core/hle/kernel/kernel.h"
  30. #include "core/hle/kernel/svc_results.h"
  31. #include "core/hle/kernel/svc_types.h"
  32. #include "core/hle/result.h"
  33. #include "core/memory.h"
  34. #ifdef ARCHITECTURE_x86_64
  35. #include "core/arm/dynarmic/arm_dynarmic_32.h"
  36. #endif
  37. namespace {
  38. constexpr inline s32 TerminatingThreadPriority = Kernel::Svc::SystemThreadPriorityHighest - 1;
  39. static void ResetThreadContext32(Core::ARM_Interface::ThreadContext32& context, u32 stack_top,
  40. u32 entry_point, u32 arg) {
  41. context = {};
  42. context.cpu_registers[0] = arg;
  43. context.cpu_registers[15] = entry_point;
  44. context.cpu_registers[13] = stack_top;
  45. }
  46. static void ResetThreadContext64(Core::ARM_Interface::ThreadContext64& context, VAddr stack_top,
  47. VAddr entry_point, u64 arg) {
  48. context = {};
  49. context.cpu_registers[0] = arg;
  50. context.cpu_registers[18] = Kernel::KSystemControl::GenerateRandomU64() | 1;
  51. context.pc = entry_point;
  52. context.sp = stack_top;
  53. // TODO(merry): Perform a hardware test to determine the below value.
  54. context.fpcr = 0;
  55. }
  56. } // namespace
  57. namespace Kernel {
  58. namespace {
  59. struct ThreadLocalRegion {
  60. static constexpr std::size_t MessageBufferSize = 0x100;
  61. std::array<u32, MessageBufferSize / sizeof(u32)> message_buffer;
  62. std::atomic_uint16_t disable_count;
  63. std::atomic_uint16_t interrupt_flag;
  64. };
  65. class ThreadQueueImplForKThreadSleep final : public KThreadQueueWithoutEndWait {
  66. public:
  67. explicit ThreadQueueImplForKThreadSleep(KernelCore& kernel_)
  68. : KThreadQueueWithoutEndWait(kernel_) {}
  69. };
  70. class ThreadQueueImplForKThreadSetProperty final : public KThreadQueue {
  71. public:
  72. explicit ThreadQueueImplForKThreadSetProperty(KernelCore& kernel_, KThread::WaiterList* wl)
  73. : KThreadQueue(kernel_), m_wait_list(wl) {}
  74. void CancelWait(KThread* waiting_thread, Result wait_result, bool cancel_timer_task) override {
  75. // Remove the thread from the wait list.
  76. m_wait_list->erase(m_wait_list->iterator_to(*waiting_thread));
  77. // Invoke the base cancel wait handler.
  78. KThreadQueue::CancelWait(waiting_thread, wait_result, cancel_timer_task);
  79. }
  80. private:
  81. KThread::WaiterList* m_wait_list;
  82. };
  83. } // namespace
  84. KThread::KThread(KernelCore& kernel_)
  85. : KAutoObjectWithSlabHeapAndContainer{kernel_}, activity_pause_lock{kernel_} {}
  86. KThread::~KThread() = default;
  87. Result KThread::Initialize(KThreadFunction func, uintptr_t arg, VAddr user_stack_top, s32 prio,
  88. s32 virt_core, KProcess* owner, ThreadType type) {
  89. // Assert parameters are valid.
  90. ASSERT((type == ThreadType::Main) || (type == ThreadType::Dummy) ||
  91. (Svc::HighestThreadPriority <= prio && prio <= Svc::LowestThreadPriority));
  92. ASSERT((owner != nullptr) || (type != ThreadType::User));
  93. ASSERT(0 <= virt_core && virt_core < static_cast<s32>(Common::BitSize<u64>()));
  94. // Convert the virtual core to a physical core.
  95. const s32 phys_core = Core::Hardware::VirtualToPhysicalCoreMap[virt_core];
  96. ASSERT(0 <= phys_core && phys_core < static_cast<s32>(Core::Hardware::NUM_CPU_CORES));
  97. // First, clear the TLS address.
  98. tls_address = {};
  99. // Next, assert things based on the type.
  100. switch (type) {
  101. case ThreadType::Main:
  102. ASSERT(arg == 0);
  103. [[fallthrough]];
  104. case ThreadType::HighPriority:
  105. [[fallthrough]];
  106. case ThreadType::Dummy:
  107. [[fallthrough]];
  108. case ThreadType::User:
  109. ASSERT(((owner == nullptr) ||
  110. (owner->GetCoreMask() | (1ULL << virt_core)) == owner->GetCoreMask()));
  111. ASSERT(((owner == nullptr) ||
  112. (owner->GetPriorityMask() | (1ULL << prio)) == owner->GetPriorityMask()));
  113. break;
  114. case ThreadType::Kernel:
  115. UNIMPLEMENTED();
  116. break;
  117. default:
  118. ASSERT_MSG(false, "KThread::Initialize: Unknown ThreadType {}", static_cast<u32>(type));
  119. break;
  120. }
  121. thread_type = type;
  122. // Set the ideal core ID and affinity mask.
  123. virtual_ideal_core_id = virt_core;
  124. physical_ideal_core_id = phys_core;
  125. virtual_affinity_mask = 1ULL << virt_core;
  126. physical_affinity_mask.SetAffinity(phys_core, true);
  127. // Set the thread state.
  128. thread_state = (type == ThreadType::Main) ? ThreadState::Runnable : ThreadState::Initialized;
  129. // Set TLS address.
  130. tls_address = 0;
  131. // Set parent and condvar tree.
  132. parent = nullptr;
  133. condvar_tree = nullptr;
  134. // Set sync booleans.
  135. signaled = false;
  136. termination_requested = false;
  137. wait_cancelled = false;
  138. cancellable = false;
  139. // Set core ID and wait result.
  140. core_id = phys_core;
  141. wait_result = ResultNoSynchronizationObject;
  142. // Set priorities.
  143. priority = prio;
  144. base_priority = prio;
  145. // Initialize sleeping queue.
  146. wait_queue = nullptr;
  147. // Set suspend flags.
  148. suspend_request_flags = 0;
  149. suspend_allowed_flags = static_cast<u32>(ThreadState::SuspendFlagMask);
  150. // We're neither debug attached, nor are we nesting our priority inheritance.
  151. debug_attached = false;
  152. priority_inheritance_count = 0;
  153. // We haven't been scheduled, and we have done no light IPC.
  154. schedule_count = -1;
  155. last_scheduled_tick = 0;
  156. light_ipc_data = nullptr;
  157. // We're not waiting for a lock, and we haven't disabled migration.
  158. lock_owner = nullptr;
  159. num_core_migration_disables = 0;
  160. // We have no waiters, but we do have an entrypoint.
  161. num_kernel_waiters = 0;
  162. // Set our current core id.
  163. current_core_id = phys_core;
  164. // We haven't released our resource limit hint, and we've spent no time on the cpu.
  165. resource_limit_release_hint = false;
  166. cpu_time = 0;
  167. // Set debug context.
  168. stack_top = user_stack_top;
  169. argument = arg;
  170. // Clear our stack parameters.
  171. std::memset(static_cast<void*>(std::addressof(GetStackParameters())), 0,
  172. sizeof(StackParameters));
  173. // Set parent, if relevant.
  174. if (owner != nullptr) {
  175. // Setup the TLS, if needed.
  176. if (type == ThreadType::User) {
  177. R_TRY(owner->CreateThreadLocalRegion(std::addressof(tls_address)));
  178. }
  179. parent = owner;
  180. parent->Open();
  181. }
  182. // Initialize thread context.
  183. ResetThreadContext64(thread_context_64, user_stack_top, func, arg);
  184. ResetThreadContext32(thread_context_32, static_cast<u32>(user_stack_top),
  185. static_cast<u32>(func), static_cast<u32>(arg));
  186. // Setup the stack parameters.
  187. StackParameters& sp = GetStackParameters();
  188. sp.cur_thread = this;
  189. sp.disable_count = 1;
  190. SetInExceptionHandler();
  191. // Set thread ID.
  192. thread_id = kernel.CreateNewThreadID();
  193. // We initialized!
  194. initialized = true;
  195. // Register ourselves with our parent process.
  196. if (parent != nullptr) {
  197. parent->RegisterThread(this);
  198. if (parent->IsSuspended()) {
  199. RequestSuspend(SuspendType::Process);
  200. }
  201. }
  202. R_SUCCEED();
  203. }
  204. Result KThread::InitializeThread(KThread* thread, KThreadFunction func, uintptr_t arg,
  205. VAddr user_stack_top, s32 prio, s32 core, KProcess* owner,
  206. ThreadType type, std::function<void()>&& init_func) {
  207. // Initialize the thread.
  208. R_TRY(thread->Initialize(func, arg, user_stack_top, prio, core, owner, type));
  209. // Initialize emulation parameters.
  210. thread->host_context = std::make_shared<Common::Fiber>(std::move(init_func));
  211. thread->is_single_core = !Settings::values.use_multi_core.GetValue();
  212. R_SUCCEED();
  213. }
  214. Result KThread::InitializeDummyThread(KThread* thread) {
  215. // Initialize the thread.
  216. R_TRY(thread->Initialize({}, {}, {}, DummyThreadPriority, 3, {}, ThreadType::Dummy));
  217. // Initialize emulation parameters.
  218. thread->stack_parameters.disable_count = 0;
  219. R_SUCCEED();
  220. }
  221. Result KThread::InitializeMainThread(Core::System& system, KThread* thread, s32 virt_core) {
  222. R_RETURN(InitializeThread(thread, {}, {}, {}, IdleThreadPriority, virt_core, {},
  223. ThreadType::Main, system.GetCpuManager().GetGuestActivateFunc()));
  224. }
  225. Result KThread::InitializeIdleThread(Core::System& system, KThread* thread, s32 virt_core) {
  226. R_RETURN(InitializeThread(thread, {}, {}, {}, IdleThreadPriority, virt_core, {},
  227. ThreadType::Main, system.GetCpuManager().GetIdleThreadStartFunc()));
  228. }
  229. Result KThread::InitializeHighPriorityThread(Core::System& system, KThread* thread,
  230. KThreadFunction func, uintptr_t arg, s32 virt_core) {
  231. R_RETURN(InitializeThread(thread, func, arg, {}, {}, virt_core, nullptr,
  232. ThreadType::HighPriority,
  233. system.GetCpuManager().GetShutdownThreadStartFunc()));
  234. }
  235. Result KThread::InitializeUserThread(Core::System& system, KThread* thread, KThreadFunction func,
  236. uintptr_t arg, VAddr user_stack_top, s32 prio, s32 virt_core,
  237. KProcess* owner) {
  238. system.Kernel().GlobalSchedulerContext().AddThread(thread);
  239. R_RETURN(InitializeThread(thread, func, arg, user_stack_top, prio, virt_core, owner,
  240. ThreadType::User, system.GetCpuManager().GetGuestThreadFunc()));
  241. }
  242. void KThread::PostDestroy(uintptr_t arg) {
  243. KProcess* owner = reinterpret_cast<KProcess*>(arg & ~1ULL);
  244. const bool resource_limit_release_hint = (arg & 1);
  245. const s64 hint_value = (resource_limit_release_hint ? 0 : 1);
  246. if (owner != nullptr) {
  247. owner->GetResourceLimit()->Release(LimitableResource::Threads, 1, hint_value);
  248. owner->Close();
  249. }
  250. }
  251. void KThread::Finalize() {
  252. // If the thread has an owner process, unregister it.
  253. if (parent != nullptr) {
  254. parent->UnregisterThread(this);
  255. }
  256. // If the thread has a local region, delete it.
  257. if (tls_address != 0) {
  258. ASSERT(parent->DeleteThreadLocalRegion(tls_address).IsSuccess());
  259. }
  260. // Release any waiters.
  261. {
  262. ASSERT(lock_owner == nullptr);
  263. KScopedSchedulerLock sl{kernel};
  264. auto it = waiter_list.begin();
  265. while (it != waiter_list.end()) {
  266. // Get the thread.
  267. KThread* const waiter = std::addressof(*it);
  268. // The thread shouldn't be a kernel waiter.
  269. ASSERT(!IsKernelAddressKey(waiter->GetAddressKey()));
  270. // Clear the lock owner.
  271. waiter->SetLockOwner(nullptr);
  272. // Erase the waiter from our list.
  273. it = waiter_list.erase(it);
  274. // Cancel the thread's wait.
  275. waiter->CancelWait(ResultInvalidState, true);
  276. }
  277. }
  278. // Release host emulation members.
  279. host_context.reset();
  280. // Perform inherited finalization.
  281. KSynchronizationObject::Finalize();
  282. }
  283. bool KThread::IsSignaled() const {
  284. return signaled;
  285. }
  286. void KThread::OnTimer() {
  287. ASSERT(kernel.GlobalSchedulerContext().IsLocked());
  288. // If we're waiting, cancel the wait.
  289. if (GetState() == ThreadState::Waiting) {
  290. wait_queue->CancelWait(this, ResultTimedOut, false);
  291. }
  292. }
  293. void KThread::StartTermination() {
  294. ASSERT(kernel.GlobalSchedulerContext().IsLocked());
  295. // Release user exception and unpin, if relevant.
  296. if (parent != nullptr) {
  297. parent->ReleaseUserException(this);
  298. if (parent->GetPinnedThread(GetCurrentCoreId(kernel)) == this) {
  299. parent->UnpinCurrentThread(core_id);
  300. }
  301. }
  302. // Set state to terminated.
  303. SetState(ThreadState::Terminated);
  304. // Clear the thread's status as running in parent.
  305. if (parent != nullptr) {
  306. parent->ClearRunningThread(this);
  307. }
  308. // Signal.
  309. signaled = true;
  310. KSynchronizationObject::NotifyAvailable();
  311. // Clear previous thread in KScheduler.
  312. KScheduler::ClearPreviousThread(kernel, this);
  313. // Register terminated dpc flag.
  314. RegisterDpc(DpcFlag::Terminated);
  315. }
  316. void KThread::FinishTermination() {
  317. // Ensure that the thread is not executing on any core.
  318. if (parent != nullptr) {
  319. for (std::size_t i = 0; i < static_cast<std::size_t>(Core::Hardware::NUM_CPU_CORES); ++i) {
  320. KThread* core_thread{};
  321. do {
  322. core_thread = kernel.Scheduler(i).GetSchedulerCurrentThread();
  323. } while (core_thread == this);
  324. }
  325. }
  326. // Close the thread.
  327. this->Close();
  328. }
  329. void KThread::DoWorkerTaskImpl() {
  330. // Finish the termination that was begun by Exit().
  331. this->FinishTermination();
  332. }
  333. void KThread::Pin(s32 current_core) {
  334. ASSERT(kernel.GlobalSchedulerContext().IsLocked());
  335. // Set ourselves as pinned.
  336. GetStackParameters().is_pinned = true;
  337. // Disable core migration.
  338. ASSERT(num_core_migration_disables == 0);
  339. {
  340. ++num_core_migration_disables;
  341. // Save our ideal state to restore when we're unpinned.
  342. original_physical_ideal_core_id = physical_ideal_core_id;
  343. original_physical_affinity_mask = physical_affinity_mask;
  344. // Bind ourselves to this core.
  345. const s32 active_core = GetActiveCore();
  346. SetActiveCore(current_core);
  347. physical_ideal_core_id = current_core;
  348. physical_affinity_mask.SetAffinityMask(1ULL << current_core);
  349. if (active_core != current_core || physical_affinity_mask.GetAffinityMask() !=
  350. original_physical_affinity_mask.GetAffinityMask()) {
  351. KScheduler::OnThreadAffinityMaskChanged(kernel, this, original_physical_affinity_mask,
  352. active_core);
  353. }
  354. }
  355. // Disallow performing thread suspension.
  356. {
  357. // Update our allow flags.
  358. suspend_allowed_flags &= ~(1 << (static_cast<u32>(SuspendType::Thread) +
  359. static_cast<u32>(ThreadState::SuspendShift)));
  360. // Update our state.
  361. UpdateState();
  362. }
  363. // TODO(bunnei): Update our SVC access permissions.
  364. ASSERT(parent != nullptr);
  365. }
  366. void KThread::Unpin() {
  367. ASSERT(kernel.GlobalSchedulerContext().IsLocked());
  368. // Set ourselves as unpinned.
  369. GetStackParameters().is_pinned = false;
  370. // Enable core migration.
  371. ASSERT(num_core_migration_disables == 1);
  372. {
  373. num_core_migration_disables--;
  374. // Restore our original state.
  375. const KAffinityMask old_mask = physical_affinity_mask;
  376. physical_ideal_core_id = original_physical_ideal_core_id;
  377. physical_affinity_mask = original_physical_affinity_mask;
  378. if (physical_affinity_mask.GetAffinityMask() != old_mask.GetAffinityMask()) {
  379. const s32 active_core = GetActiveCore();
  380. if (!physical_affinity_mask.GetAffinity(active_core)) {
  381. if (physical_ideal_core_id >= 0) {
  382. SetActiveCore(physical_ideal_core_id);
  383. } else {
  384. SetActiveCore(static_cast<s32>(
  385. Common::BitSize<u64>() - 1 -
  386. std::countl_zero(physical_affinity_mask.GetAffinityMask())));
  387. }
  388. }
  389. KScheduler::OnThreadAffinityMaskChanged(kernel, this, old_mask, active_core);
  390. }
  391. }
  392. // Allow performing thread suspension (if termination hasn't been requested).
  393. if (!IsTerminationRequested()) {
  394. // Update our allow flags.
  395. suspend_allowed_flags |= (1 << (static_cast<u32>(SuspendType::Thread) +
  396. static_cast<u32>(ThreadState::SuspendShift)));
  397. // Update our state.
  398. UpdateState();
  399. }
  400. // TODO(bunnei): Update our SVC access permissions.
  401. ASSERT(parent != nullptr);
  402. // Resume any threads that began waiting on us while we were pinned.
  403. for (auto it = pinned_waiter_list.begin(); it != pinned_waiter_list.end(); ++it) {
  404. it->EndWait(ResultSuccess);
  405. }
  406. }
  407. u16 KThread::GetUserDisableCount() const {
  408. if (!IsUserThread()) {
  409. // We only emulate TLS for user threads
  410. return {};
  411. }
  412. auto& memory = kernel.System().Memory();
  413. return memory.Read16(tls_address + offsetof(ThreadLocalRegion, disable_count));
  414. }
  415. void KThread::SetInterruptFlag() {
  416. if (!IsUserThread()) {
  417. // We only emulate TLS for user threads
  418. return;
  419. }
  420. auto& memory = kernel.System().Memory();
  421. memory.Write16(tls_address + offsetof(ThreadLocalRegion, interrupt_flag), 1);
  422. }
  423. void KThread::ClearInterruptFlag() {
  424. if (!IsUserThread()) {
  425. // We only emulate TLS for user threads
  426. return;
  427. }
  428. auto& memory = kernel.System().Memory();
  429. memory.Write16(tls_address + offsetof(ThreadLocalRegion, interrupt_flag), 0);
  430. }
  431. Result KThread::GetCoreMask(s32* out_ideal_core, u64* out_affinity_mask) {
  432. KScopedSchedulerLock sl{kernel};
  433. // Get the virtual mask.
  434. *out_ideal_core = virtual_ideal_core_id;
  435. *out_affinity_mask = virtual_affinity_mask;
  436. R_SUCCEED();
  437. }
  438. Result KThread::GetPhysicalCoreMask(s32* out_ideal_core, u64* out_affinity_mask) {
  439. KScopedSchedulerLock sl{kernel};
  440. ASSERT(num_core_migration_disables >= 0);
  441. // Select between core mask and original core mask.
  442. if (num_core_migration_disables == 0) {
  443. *out_ideal_core = physical_ideal_core_id;
  444. *out_affinity_mask = physical_affinity_mask.GetAffinityMask();
  445. } else {
  446. *out_ideal_core = original_physical_ideal_core_id;
  447. *out_affinity_mask = original_physical_affinity_mask.GetAffinityMask();
  448. }
  449. R_SUCCEED();
  450. }
  451. Result KThread::SetCoreMask(s32 core_id_, u64 v_affinity_mask) {
  452. ASSERT(parent != nullptr);
  453. ASSERT(v_affinity_mask != 0);
  454. KScopedLightLock lk(activity_pause_lock);
  455. // Set the core mask.
  456. u64 p_affinity_mask = 0;
  457. {
  458. KScopedSchedulerLock sl(kernel);
  459. ASSERT(num_core_migration_disables >= 0);
  460. // If we're updating, set our ideal virtual core.
  461. if (core_id_ != Svc::IdealCoreNoUpdate) {
  462. virtual_ideal_core_id = core_id_;
  463. } else {
  464. // Preserve our ideal core id.
  465. core_id_ = virtual_ideal_core_id;
  466. R_UNLESS(((1ULL << core_id_) & v_affinity_mask) != 0, ResultInvalidCombination);
  467. }
  468. // Set our affinity mask.
  469. virtual_affinity_mask = v_affinity_mask;
  470. // Translate the virtual core to a physical core.
  471. if (core_id_ >= 0) {
  472. core_id_ = Core::Hardware::VirtualToPhysicalCoreMap[core_id_];
  473. }
  474. // Translate the virtual affinity mask to a physical one.
  475. while (v_affinity_mask != 0) {
  476. const u64 next = std::countr_zero(v_affinity_mask);
  477. v_affinity_mask &= ~(1ULL << next);
  478. p_affinity_mask |= (1ULL << Core::Hardware::VirtualToPhysicalCoreMap[next]);
  479. }
  480. // If we haven't disabled migration, perform an affinity change.
  481. if (num_core_migration_disables == 0) {
  482. const KAffinityMask old_mask = physical_affinity_mask;
  483. // Set our new ideals.
  484. physical_ideal_core_id = core_id_;
  485. physical_affinity_mask.SetAffinityMask(p_affinity_mask);
  486. if (physical_affinity_mask.GetAffinityMask() != old_mask.GetAffinityMask()) {
  487. const s32 active_core = GetActiveCore();
  488. if (active_core >= 0 && !physical_affinity_mask.GetAffinity(active_core)) {
  489. const s32 new_core = static_cast<s32>(
  490. physical_ideal_core_id >= 0
  491. ? physical_ideal_core_id
  492. : Common::BitSize<u64>() - 1 -
  493. std::countl_zero(physical_affinity_mask.GetAffinityMask()));
  494. SetActiveCore(new_core);
  495. }
  496. KScheduler::OnThreadAffinityMaskChanged(kernel, this, old_mask, active_core);
  497. }
  498. } else {
  499. // Otherwise, we edit the original affinity for restoration later.
  500. original_physical_ideal_core_id = core_id_;
  501. original_physical_affinity_mask.SetAffinityMask(p_affinity_mask);
  502. }
  503. }
  504. // Update the pinned waiter list.
  505. ThreadQueueImplForKThreadSetProperty wait_queue_(kernel, std::addressof(pinned_waiter_list));
  506. {
  507. bool retry_update{};
  508. do {
  509. // Lock the scheduler.
  510. KScopedSchedulerLock sl(kernel);
  511. // Don't do any further management if our termination has been requested.
  512. R_SUCCEED_IF(IsTerminationRequested());
  513. // By default, we won't need to retry.
  514. retry_update = false;
  515. // Check if the thread is currently running.
  516. bool thread_is_current{};
  517. s32 thread_core;
  518. for (thread_core = 0; thread_core < static_cast<s32>(Core::Hardware::NUM_CPU_CORES);
  519. ++thread_core) {
  520. if (kernel.Scheduler(thread_core).GetSchedulerCurrentThread() == this) {
  521. thread_is_current = true;
  522. break;
  523. }
  524. }
  525. // If the thread is currently running, check whether it's no longer allowed under the
  526. // new mask.
  527. if (thread_is_current && ((1ULL << thread_core) & p_affinity_mask) == 0) {
  528. // If the thread is pinned, we want to wait until it's not pinned.
  529. if (GetStackParameters().is_pinned) {
  530. // Verify that the current thread isn't terminating.
  531. R_UNLESS(!GetCurrentThread(kernel).IsTerminationRequested(),
  532. ResultTerminationRequested);
  533. // Wait until the thread isn't pinned any more.
  534. pinned_waiter_list.push_back(GetCurrentThread(kernel));
  535. GetCurrentThread(kernel).BeginWait(std::addressof(wait_queue_));
  536. } else {
  537. // If the thread isn't pinned, release the scheduler lock and retry until it's
  538. // not current.
  539. retry_update = true;
  540. }
  541. }
  542. } while (retry_update);
  543. }
  544. R_SUCCEED();
  545. }
  546. void KThread::SetBasePriority(s32 value) {
  547. ASSERT(Svc::HighestThreadPriority <= value && value <= Svc::LowestThreadPriority);
  548. KScopedSchedulerLock sl{kernel};
  549. // Change our base priority.
  550. base_priority = value;
  551. // Perform a priority restoration.
  552. RestorePriority(kernel, this);
  553. }
  554. void KThread::RequestSuspend(SuspendType type) {
  555. KScopedSchedulerLock sl{kernel};
  556. // Note the request in our flags.
  557. suspend_request_flags |=
  558. (1u << (static_cast<u32>(ThreadState::SuspendShift) + static_cast<u32>(type)));
  559. // Try to perform the suspend.
  560. TrySuspend();
  561. }
  562. void KThread::Resume(SuspendType type) {
  563. KScopedSchedulerLock sl{kernel};
  564. // Clear the request in our flags.
  565. suspend_request_flags &=
  566. ~(1u << (static_cast<u32>(ThreadState::SuspendShift) + static_cast<u32>(type)));
  567. // Update our state.
  568. this->UpdateState();
  569. }
  570. void KThread::WaitCancel() {
  571. KScopedSchedulerLock sl{kernel};
  572. // Check if we're waiting and cancellable.
  573. if (this->GetState() == ThreadState::Waiting && cancellable) {
  574. wait_cancelled = false;
  575. wait_queue->CancelWait(this, ResultCancelled, true);
  576. } else {
  577. // Otherwise, note that we cancelled a wait.
  578. wait_cancelled = true;
  579. }
  580. }
  581. void KThread::TrySuspend() {
  582. ASSERT(kernel.GlobalSchedulerContext().IsLocked());
  583. ASSERT(IsSuspendRequested());
  584. // Ensure that we have no waiters.
  585. if (GetNumKernelWaiters() > 0) {
  586. return;
  587. }
  588. ASSERT(GetNumKernelWaiters() == 0);
  589. // Perform the suspend.
  590. this->UpdateState();
  591. }
  592. void KThread::UpdateState() {
  593. ASSERT(kernel.GlobalSchedulerContext().IsLocked());
  594. // Set our suspend flags in state.
  595. const ThreadState old_state = thread_state.load(std::memory_order_relaxed);
  596. const auto new_state =
  597. static_cast<ThreadState>(this->GetSuspendFlags()) | (old_state & ThreadState::Mask);
  598. thread_state.store(new_state, std::memory_order_relaxed);
  599. // Note the state change in scheduler.
  600. if (new_state != old_state) {
  601. KScheduler::OnThreadStateChanged(kernel, this, old_state);
  602. }
  603. }
  604. void KThread::Continue() {
  605. ASSERT(kernel.GlobalSchedulerContext().IsLocked());
  606. // Clear our suspend flags in state.
  607. const ThreadState old_state = thread_state.load(std::memory_order_relaxed);
  608. thread_state.store(old_state & ThreadState::Mask, std::memory_order_relaxed);
  609. // Note the state change in scheduler.
  610. KScheduler::OnThreadStateChanged(kernel, this, old_state);
  611. }
  612. void KThread::WaitUntilSuspended() {
  613. // Make sure we have a suspend requested.
  614. ASSERT(IsSuspendRequested());
  615. // Loop until the thread is not executing on any core.
  616. for (std::size_t i = 0; i < static_cast<std::size_t>(Core::Hardware::NUM_CPU_CORES); ++i) {
  617. KThread* core_thread{};
  618. do {
  619. core_thread = kernel.Scheduler(i).GetSchedulerCurrentThread();
  620. } while (core_thread == this);
  621. }
  622. }
  623. Result KThread::SetActivity(Svc::ThreadActivity activity) {
  624. // Lock ourselves.
  625. KScopedLightLock lk(activity_pause_lock);
  626. // Set the activity.
  627. {
  628. // Lock the scheduler.
  629. KScopedSchedulerLock sl(kernel);
  630. // Verify our state.
  631. const auto cur_state = this->GetState();
  632. R_UNLESS((cur_state == ThreadState::Waiting || cur_state == ThreadState::Runnable),
  633. ResultInvalidState);
  634. // Either pause or resume.
  635. if (activity == Svc::ThreadActivity::Paused) {
  636. // Verify that we're not suspended.
  637. R_UNLESS(!this->IsSuspendRequested(SuspendType::Thread), ResultInvalidState);
  638. // Suspend.
  639. this->RequestSuspend(SuspendType::Thread);
  640. } else {
  641. ASSERT(activity == Svc::ThreadActivity::Runnable);
  642. // Verify that we're suspended.
  643. R_UNLESS(this->IsSuspendRequested(SuspendType::Thread), ResultInvalidState);
  644. // Resume.
  645. this->Resume(SuspendType::Thread);
  646. }
  647. }
  648. // If the thread is now paused, update the pinned waiter list.
  649. if (activity == Svc::ThreadActivity::Paused) {
  650. ThreadQueueImplForKThreadSetProperty wait_queue_(kernel,
  651. std::addressof(pinned_waiter_list));
  652. bool thread_is_current;
  653. do {
  654. // Lock the scheduler.
  655. KScopedSchedulerLock sl(kernel);
  656. // Don't do any further management if our termination has been requested.
  657. R_SUCCEED_IF(this->IsTerminationRequested());
  658. // By default, treat the thread as not current.
  659. thread_is_current = false;
  660. // Check whether the thread is pinned.
  661. if (this->GetStackParameters().is_pinned) {
  662. // Verify that the current thread isn't terminating.
  663. R_UNLESS(!GetCurrentThread(kernel).IsTerminationRequested(),
  664. ResultTerminationRequested);
  665. // Wait until the thread isn't pinned any more.
  666. pinned_waiter_list.push_back(GetCurrentThread(kernel));
  667. GetCurrentThread(kernel).BeginWait(std::addressof(wait_queue_));
  668. } else {
  669. // Check if the thread is currently running.
  670. // If it is, we'll need to retry.
  671. for (auto i = 0; i < static_cast<s32>(Core::Hardware::NUM_CPU_CORES); ++i) {
  672. if (kernel.Scheduler(i).GetSchedulerCurrentThread() == this) {
  673. thread_is_current = true;
  674. break;
  675. }
  676. }
  677. }
  678. } while (thread_is_current);
  679. }
  680. R_SUCCEED();
  681. }
  682. Result KThread::GetThreadContext3(std::vector<u8>& out) {
  683. // Lock ourselves.
  684. KScopedLightLock lk{activity_pause_lock};
  685. // Get the context.
  686. {
  687. // Lock the scheduler.
  688. KScopedSchedulerLock sl{kernel};
  689. // Verify that we're suspended.
  690. R_UNLESS(IsSuspendRequested(SuspendType::Thread), ResultInvalidState);
  691. // If we're not terminating, get the thread's user context.
  692. if (!IsTerminationRequested()) {
  693. if (parent->Is64BitProcess()) {
  694. // Mask away mode bits, interrupt bits, IL bit, and other reserved bits.
  695. auto context = GetContext64();
  696. context.pstate &= 0xFF0FFE20;
  697. out.resize(sizeof(context));
  698. std::memcpy(out.data(), &context, sizeof(context));
  699. } else {
  700. // Mask away mode bits, interrupt bits, IL bit, and other reserved bits.
  701. auto context = GetContext32();
  702. context.cpsr &= 0xFF0FFE20;
  703. out.resize(sizeof(context));
  704. std::memcpy(out.data(), &context, sizeof(context));
  705. }
  706. }
  707. }
  708. R_SUCCEED();
  709. }
  710. void KThread::AddWaiterImpl(KThread* thread) {
  711. ASSERT(kernel.GlobalSchedulerContext().IsLocked());
  712. // Find the right spot to insert the waiter.
  713. auto it = waiter_list.begin();
  714. while (it != waiter_list.end()) {
  715. if (it->GetPriority() > thread->GetPriority()) {
  716. break;
  717. }
  718. it++;
  719. }
  720. // Keep track of how many kernel waiters we have.
  721. if (IsKernelAddressKey(thread->GetAddressKey())) {
  722. ASSERT((num_kernel_waiters++) >= 0);
  723. KScheduler::SetSchedulerUpdateNeeded(kernel);
  724. }
  725. // Insert the waiter.
  726. waiter_list.insert(it, *thread);
  727. thread->SetLockOwner(this);
  728. }
  729. void KThread::RemoveWaiterImpl(KThread* thread) {
  730. ASSERT(kernel.GlobalSchedulerContext().IsLocked());
  731. // Keep track of how many kernel waiters we have.
  732. if (IsKernelAddressKey(thread->GetAddressKey())) {
  733. ASSERT((num_kernel_waiters--) > 0);
  734. KScheduler::SetSchedulerUpdateNeeded(kernel);
  735. }
  736. // Remove the waiter.
  737. waiter_list.erase(waiter_list.iterator_to(*thread));
  738. thread->SetLockOwner(nullptr);
  739. }
  740. void KThread::RestorePriority(KernelCore& kernel_ctx, KThread* thread) {
  741. ASSERT(kernel_ctx.GlobalSchedulerContext().IsLocked());
  742. while (true) {
  743. // We want to inherit priority where possible.
  744. s32 new_priority = thread->GetBasePriority();
  745. if (thread->HasWaiters()) {
  746. new_priority = std::min(new_priority, thread->waiter_list.front().GetPriority());
  747. }
  748. // If the priority we would inherit is not different from ours, don't do anything.
  749. if (new_priority == thread->GetPriority()) {
  750. return;
  751. }
  752. // Ensure we don't violate condition variable red black tree invariants.
  753. if (auto* cv_tree = thread->GetConditionVariableTree(); cv_tree != nullptr) {
  754. BeforeUpdatePriority(kernel_ctx, cv_tree, thread);
  755. }
  756. // Change the priority.
  757. const s32 old_priority = thread->GetPriority();
  758. thread->SetPriority(new_priority);
  759. // Restore the condition variable, if relevant.
  760. if (auto* cv_tree = thread->GetConditionVariableTree(); cv_tree != nullptr) {
  761. AfterUpdatePriority(kernel_ctx, cv_tree, thread);
  762. }
  763. // Update the scheduler.
  764. KScheduler::OnThreadPriorityChanged(kernel_ctx, thread, old_priority);
  765. // Keep the lock owner up to date.
  766. KThread* lock_owner = thread->GetLockOwner();
  767. if (lock_owner == nullptr) {
  768. return;
  769. }
  770. // Update the thread in the lock owner's sorted list, and continue inheriting.
  771. lock_owner->RemoveWaiterImpl(thread);
  772. lock_owner->AddWaiterImpl(thread);
  773. thread = lock_owner;
  774. }
  775. }
  776. void KThread::AddWaiter(KThread* thread) {
  777. AddWaiterImpl(thread);
  778. RestorePriority(kernel, this);
  779. }
  780. void KThread::RemoveWaiter(KThread* thread) {
  781. RemoveWaiterImpl(thread);
  782. RestorePriority(kernel, this);
  783. }
  784. KThread* KThread::RemoveWaiterByKey(s32* out_num_waiters, VAddr key) {
  785. ASSERT(kernel.GlobalSchedulerContext().IsLocked());
  786. s32 num_waiters{};
  787. KThread* next_lock_owner{};
  788. auto it = waiter_list.begin();
  789. while (it != waiter_list.end()) {
  790. if (it->GetAddressKey() == key) {
  791. KThread* thread = std::addressof(*it);
  792. // Keep track of how many kernel waiters we have.
  793. if (IsKernelAddressKey(thread->GetAddressKey())) {
  794. ASSERT((num_kernel_waiters--) > 0);
  795. KScheduler::SetSchedulerUpdateNeeded(kernel);
  796. }
  797. it = waiter_list.erase(it);
  798. // Update the next lock owner.
  799. if (next_lock_owner == nullptr) {
  800. next_lock_owner = thread;
  801. next_lock_owner->SetLockOwner(nullptr);
  802. } else {
  803. next_lock_owner->AddWaiterImpl(thread);
  804. }
  805. num_waiters++;
  806. } else {
  807. it++;
  808. }
  809. }
  810. // Do priority updates, if we have a next owner.
  811. if (next_lock_owner) {
  812. RestorePriority(kernel, this);
  813. RestorePriority(kernel, next_lock_owner);
  814. }
  815. // Return output.
  816. *out_num_waiters = num_waiters;
  817. return next_lock_owner;
  818. }
  819. Result KThread::Run() {
  820. while (true) {
  821. KScopedSchedulerLock lk{kernel};
  822. // If either this thread or the current thread are requesting termination, note it.
  823. R_UNLESS(!IsTerminationRequested(), ResultTerminationRequested);
  824. R_UNLESS(!GetCurrentThread(kernel).IsTerminationRequested(), ResultTerminationRequested);
  825. // Ensure our thread state is correct.
  826. R_UNLESS(GetState() == ThreadState::Initialized, ResultInvalidState);
  827. // If the current thread has been asked to suspend, suspend it and retry.
  828. if (GetCurrentThread(kernel).IsSuspended()) {
  829. GetCurrentThread(kernel).UpdateState();
  830. continue;
  831. }
  832. // If we're not a kernel thread and we've been asked to suspend, suspend ourselves.
  833. if (KProcess* owner = this->GetOwnerProcess(); owner != nullptr) {
  834. if (IsUserThread() && IsSuspended()) {
  835. this->UpdateState();
  836. }
  837. owner->IncrementRunningThreadCount();
  838. }
  839. // Set our state and finish.
  840. SetState(ThreadState::Runnable);
  841. R_SUCCEED();
  842. }
  843. }
  844. void KThread::Exit() {
  845. ASSERT(this == GetCurrentThreadPointer(kernel));
  846. // Release the thread resource hint, running thread count from parent.
  847. if (parent != nullptr) {
  848. parent->GetResourceLimit()->Release(Kernel::LimitableResource::Threads, 0, 1);
  849. resource_limit_release_hint = true;
  850. parent->DecrementRunningThreadCount();
  851. }
  852. // Perform termination.
  853. {
  854. KScopedSchedulerLock sl{kernel};
  855. // Disallow all suspension.
  856. suspend_allowed_flags = 0;
  857. this->UpdateState();
  858. // Disallow all suspension.
  859. suspend_allowed_flags = 0;
  860. // Start termination.
  861. StartTermination();
  862. // Register the thread as a work task.
  863. KWorkerTaskManager::AddTask(kernel, KWorkerTaskManager::WorkerType::Exit, this);
  864. }
  865. UNREACHABLE_MSG("KThread::Exit() would return");
  866. }
  867. Result KThread::Terminate() {
  868. ASSERT(this != GetCurrentThreadPointer(kernel));
  869. // Request the thread terminate if it hasn't already.
  870. if (const auto new_state = this->RequestTerminate(); new_state != ThreadState::Terminated) {
  871. // If the thread isn't terminated, wait for it to terminate.
  872. s32 index;
  873. KSynchronizationObject* objects[] = {this};
  874. R_TRY(KSynchronizationObject::Wait(kernel, std::addressof(index), objects, 1,
  875. Svc::WaitInfinite));
  876. }
  877. R_SUCCEED();
  878. }
  879. ThreadState KThread::RequestTerminate() {
  880. ASSERT(this != GetCurrentThreadPointer(kernel));
  881. KScopedSchedulerLock sl{kernel};
  882. // Determine if this is the first termination request.
  883. const bool first_request = [&]() -> bool {
  884. // Perform an atomic compare-and-swap from false to true.
  885. bool expected = false;
  886. return termination_requested.compare_exchange_strong(expected, true);
  887. }();
  888. // If this is the first request, start termination procedure.
  889. if (first_request) {
  890. // If the thread is in initialized state, just change state to terminated.
  891. if (this->GetState() == ThreadState::Initialized) {
  892. thread_state = ThreadState::Terminated;
  893. return ThreadState::Terminated;
  894. }
  895. // Register the terminating dpc.
  896. this->RegisterDpc(DpcFlag::Terminating);
  897. // If the thread is pinned, unpin it.
  898. if (this->GetStackParameters().is_pinned) {
  899. this->GetOwnerProcess()->UnpinThread(this);
  900. }
  901. // If the thread is suspended, continue it.
  902. if (this->IsSuspended()) {
  903. suspend_allowed_flags = 0;
  904. this->UpdateState();
  905. }
  906. // Change the thread's priority to be higher than any system thread's.
  907. if (this->GetBasePriority() >= Svc::SystemThreadPriorityHighest) {
  908. this->SetBasePriority(TerminatingThreadPriority);
  909. }
  910. // If the thread is runnable, send a termination interrupt to other cores.
  911. if (this->GetState() == ThreadState::Runnable) {
  912. if (const u64 core_mask =
  913. physical_affinity_mask.GetAffinityMask() & ~(1ULL << GetCurrentCoreId(kernel));
  914. core_mask != 0) {
  915. Kernel::KInterruptManager::SendInterProcessorInterrupt(kernel, core_mask);
  916. }
  917. }
  918. // Wake up the thread.
  919. if (this->GetState() == ThreadState::Waiting) {
  920. wait_queue->CancelWait(this, ResultTerminationRequested, true);
  921. }
  922. }
  923. return this->GetState();
  924. }
  925. Result KThread::Sleep(s64 timeout) {
  926. ASSERT(!kernel.GlobalSchedulerContext().IsLocked());
  927. ASSERT(this == GetCurrentThreadPointer(kernel));
  928. ASSERT(timeout > 0);
  929. ThreadQueueImplForKThreadSleep wait_queue_(kernel);
  930. {
  931. // Setup the scheduling lock and sleep.
  932. KScopedSchedulerLockAndSleep slp(kernel, this, timeout);
  933. // Check if the thread should terminate.
  934. if (this->IsTerminationRequested()) {
  935. slp.CancelSleep();
  936. R_THROW(ResultTerminationRequested);
  937. }
  938. // Wait for the sleep to end.
  939. this->BeginWait(std::addressof(wait_queue_));
  940. SetWaitReasonForDebugging(ThreadWaitReasonForDebugging::Sleep);
  941. }
  942. R_SUCCEED();
  943. }
  944. void KThread::IfDummyThreadTryWait() {
  945. if (!IsDummyThread()) {
  946. return;
  947. }
  948. if (GetState() != ThreadState::Waiting) {
  949. return;
  950. }
  951. ASSERT(!kernel.IsPhantomModeForSingleCore());
  952. // Block until we are no longer waiting.
  953. std::unique_lock lk(dummy_wait_lock);
  954. dummy_wait_cv.wait(
  955. lk, [&] { return GetState() != ThreadState::Waiting || kernel.IsShuttingDown(); });
  956. }
  957. void KThread::IfDummyThreadEndWait() {
  958. if (!IsDummyThread()) {
  959. return;
  960. }
  961. // Wake up the waiting thread.
  962. dummy_wait_cv.notify_one();
  963. }
  964. void KThread::BeginWait(KThreadQueue* queue) {
  965. // Set our state as waiting.
  966. SetState(ThreadState::Waiting);
  967. // Set our wait queue.
  968. wait_queue = queue;
  969. }
  970. void KThread::NotifyAvailable(KSynchronizationObject* signaled_object, Result wait_result_) {
  971. // Lock the scheduler.
  972. KScopedSchedulerLock sl(kernel);
  973. // If we're waiting, notify our queue that we're available.
  974. if (GetState() == ThreadState::Waiting) {
  975. wait_queue->NotifyAvailable(this, signaled_object, wait_result_);
  976. }
  977. }
  978. void KThread::EndWait(Result wait_result_) {
  979. // Lock the scheduler.
  980. KScopedSchedulerLock sl(kernel);
  981. // If we're waiting, notify our queue that we're available.
  982. if (GetState() == ThreadState::Waiting) {
  983. if (wait_queue == nullptr) {
  984. // This should never happen, but avoid a hard crash below to get this logged.
  985. ASSERT_MSG(false, "wait_queue is nullptr!");
  986. return;
  987. }
  988. wait_queue->EndWait(this, wait_result_);
  989. // Special case for dummy threads to wakeup if necessary.
  990. IfDummyThreadEndWait();
  991. }
  992. }
  993. void KThread::CancelWait(Result wait_result_, bool cancel_timer_task) {
  994. // Lock the scheduler.
  995. KScopedSchedulerLock sl(kernel);
  996. // If we're waiting, notify our queue that we're available.
  997. if (GetState() == ThreadState::Waiting) {
  998. wait_queue->CancelWait(this, wait_result_, cancel_timer_task);
  999. }
  1000. }
  1001. void KThread::SetState(ThreadState state) {
  1002. KScopedSchedulerLock sl{kernel};
  1003. // Clear debugging state
  1004. SetMutexWaitAddressForDebugging({});
  1005. SetWaitReasonForDebugging({});
  1006. const ThreadState old_state = thread_state.load(std::memory_order_relaxed);
  1007. thread_state.store(
  1008. static_cast<ThreadState>((old_state & ~ThreadState::Mask) | (state & ThreadState::Mask)),
  1009. std::memory_order_relaxed);
  1010. if (thread_state.load(std::memory_order_relaxed) != old_state) {
  1011. KScheduler::OnThreadStateChanged(kernel, this, old_state);
  1012. }
  1013. }
  1014. std::shared_ptr<Common::Fiber>& KThread::GetHostContext() {
  1015. return host_context;
  1016. }
  1017. void SetCurrentThread(KernelCore& kernel, KThread* thread) {
  1018. kernel.SetCurrentEmuThread(thread);
  1019. }
  1020. KThread* GetCurrentThreadPointer(KernelCore& kernel) {
  1021. return kernel.GetCurrentEmuThread();
  1022. }
  1023. KThread& GetCurrentThread(KernelCore& kernel) {
  1024. return *GetCurrentThreadPointer(kernel);
  1025. }
  1026. s32 GetCurrentCoreId(KernelCore& kernel) {
  1027. return GetCurrentThread(kernel).GetCurrentCore();
  1028. }
  1029. KScopedDisableDispatch::~KScopedDisableDispatch() {
  1030. // If we are shutting down the kernel, none of this is relevant anymore.
  1031. if (kernel.IsShuttingDown()) {
  1032. return;
  1033. }
  1034. if (GetCurrentThread(kernel).GetDisableDispatchCount() <= 1) {
  1035. auto* scheduler = kernel.CurrentScheduler();
  1036. if (scheduler && !kernel.IsPhantomModeForSingleCore()) {
  1037. scheduler->RescheduleCurrentCore();
  1038. } else {
  1039. KScheduler::RescheduleCurrentHLEThread(kernel);
  1040. }
  1041. } else {
  1042. GetCurrentThread(kernel).EnableDispatch();
  1043. }
  1044. }
  1045. } // namespace Kernel