k_thread.cpp 39 KB

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