k_thread.cpp 39 KB

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