k_thread.cpp 37 KB

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