k_thread.cpp 37 KB

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