k_thread.cpp 35 KB

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