k_thread.cpp 49 KB

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