k_thread.cpp 35 KB

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