k_thread.cpp 38 KB

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