k_thread.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  1. // Copyright 2014 Citra Emulator Project / PPSSPP 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/common_funcs.h"
  10. #include "common/common_types.h"
  11. #include "common/fiber.h"
  12. #include "common/logging/log.h"
  13. #include "common/thread_queue_list.h"
  14. #include "core/core.h"
  15. #include "core/cpu_manager.h"
  16. #include "core/hardware_properties.h"
  17. #include "core/hle/kernel/errors.h"
  18. #include "core/hle/kernel/handle_table.h"
  19. #include "core/hle/kernel/k_condition_variable.h"
  20. #include "core/hle/kernel/k_scheduler.h"
  21. #include "core/hle/kernel/k_scoped_scheduler_lock_and_sleep.h"
  22. #include "core/hle/kernel/k_thread.h"
  23. #include "core/hle/kernel/kernel.h"
  24. #include "core/hle/kernel/memory/memory_layout.h"
  25. #include "core/hle/kernel/object.h"
  26. #include "core/hle/kernel/process.h"
  27. #include "core/hle/kernel/svc_results.h"
  28. #include "core/hle/kernel/time_manager.h"
  29. #include "core/hle/result.h"
  30. #include "core/memory.h"
  31. #ifdef ARCHITECTURE_x86_64
  32. #include "core/arm/dynarmic/arm_dynarmic_32.h"
  33. #include "core/arm/dynarmic/arm_dynarmic_64.h"
  34. #endif
  35. namespace Kernel {
  36. bool KThread::IsSignaled() const {
  37. return signaled;
  38. }
  39. KThread::KThread(KernelCore& kernel) : KSynchronizationObject{kernel} {}
  40. KThread::~KThread() = default;
  41. void KThread::Stop() {
  42. {
  43. KScopedSchedulerLock lock(kernel);
  44. SetState(ThreadState::Terminated);
  45. signaled = true;
  46. NotifyAvailable();
  47. kernel.GlobalHandleTable().Close(global_handle);
  48. if (owner_process) {
  49. owner_process->UnregisterThread(this);
  50. // Mark the TLS slot in the thread's page as free.
  51. owner_process->FreeTLSRegion(tls_address);
  52. }
  53. has_exited = true;
  54. }
  55. global_handle = 0;
  56. }
  57. void KThread::Wakeup() {
  58. KScopedSchedulerLock lock(kernel);
  59. SetState(ThreadState::Runnable);
  60. }
  61. ResultCode KThread::Start() {
  62. KScopedSchedulerLock lock(kernel);
  63. SetState(ThreadState::Runnable);
  64. return RESULT_SUCCESS;
  65. }
  66. void KThread::CancelWait() {
  67. KScopedSchedulerLock lock(kernel);
  68. if (GetState() != ThreadState::Waiting || !is_cancellable) {
  69. is_sync_cancelled = true;
  70. return;
  71. }
  72. // TODO(Blinkhawk): Implement cancel of server session
  73. is_sync_cancelled = false;
  74. SetSynchronizationResults(nullptr, ERR_SYNCHRONIZATION_CANCELED);
  75. SetState(ThreadState::Runnable);
  76. }
  77. static void ResetThreadContext32(Core::ARM_Interface::ThreadContext32& context, u32 stack_top,
  78. u32 entry_point, u32 arg) {
  79. context = {};
  80. context.cpu_registers[0] = arg;
  81. context.cpu_registers[15] = entry_point;
  82. context.cpu_registers[13] = stack_top;
  83. }
  84. static void ResetThreadContext64(Core::ARM_Interface::ThreadContext64& context, VAddr stack_top,
  85. VAddr entry_point, u64 arg) {
  86. context = {};
  87. context.cpu_registers[0] = arg;
  88. context.pc = entry_point;
  89. context.sp = stack_top;
  90. // TODO(merry): Perform a hardware test to determine the below value.
  91. context.fpcr = 0;
  92. }
  93. std::shared_ptr<Common::Fiber>& KThread::GetHostContext() {
  94. return host_context;
  95. }
  96. ResultVal<std::shared_ptr<KThread>> KThread::Create(Core::System& system, ThreadType type_flags,
  97. std::string name, VAddr entry_point,
  98. u32 priority, u64 arg, s32 processor_id,
  99. VAddr stack_top, Process* owner_process) {
  100. std::function<void(void*)> init_func = Core::CpuManager::GetGuestThreadStartFunc();
  101. void* init_func_parameter = system.GetCpuManager().GetStartFuncParamater();
  102. return Create(system, type_flags, name, entry_point, priority, arg, processor_id, stack_top,
  103. owner_process, std::move(init_func), init_func_parameter);
  104. }
  105. ResultVal<std::shared_ptr<KThread>> KThread::Create(Core::System& system, ThreadType type_flags,
  106. std::string name, VAddr entry_point,
  107. u32 priority, u64 arg, s32 processor_id,
  108. VAddr stack_top, Process* owner_process,
  109. std::function<void(void*)>&& thread_start_func,
  110. void* thread_start_parameter) {
  111. auto& kernel = system.Kernel();
  112. R_UNLESS(Svc::HighestThreadPriority <= priority && priority <= Svc::LowestThreadPriority,
  113. Svc::ResultInvalidPriority);
  114. if (processor_id > THREADPROCESSORID_MAX) {
  115. LOG_ERROR(Kernel_SVC, "Invalid processor id: {}", processor_id);
  116. return ERR_INVALID_PROCESSOR_ID;
  117. }
  118. if (owner_process) {
  119. if (!system.Memory().IsValidVirtualAddress(*owner_process, entry_point)) {
  120. LOG_ERROR(Kernel_SVC, "(name={}): invalid entry {:016X}", name, entry_point);
  121. // TODO (bunnei): Find the correct error code to use here
  122. return RESULT_UNKNOWN;
  123. }
  124. }
  125. std::shared_ptr<KThread> thread = std::make_shared<KThread>(kernel);
  126. thread->thread_id = kernel.CreateNewThreadID();
  127. thread->thread_state = ThreadState::Initialized;
  128. thread->entry_point = entry_point;
  129. thread->stack_top = stack_top;
  130. thread->disable_count = 1;
  131. thread->tpidr_el0 = 0;
  132. thread->current_priority = priority;
  133. thread->base_priority = priority;
  134. thread->lock_owner = nullptr;
  135. thread->schedule_count = -1;
  136. thread->last_scheduled_tick = 0;
  137. thread->processor_id = processor_id;
  138. thread->ideal_core = processor_id;
  139. thread->affinity_mask.SetAffinity(processor_id, true);
  140. thread->name = std::move(name);
  141. thread->global_handle = kernel.GlobalHandleTable().Create(thread).Unwrap();
  142. thread->owner_process = owner_process;
  143. thread->type = type_flags;
  144. thread->signaled = false;
  145. auto& scheduler = kernel.GlobalSchedulerContext();
  146. scheduler.AddThread(thread);
  147. if (owner_process) {
  148. thread->tls_address = thread->owner_process->CreateTLSRegion();
  149. thread->owner_process->RegisterThread(thread.get());
  150. } else {
  151. thread->tls_address = 0;
  152. }
  153. ResetThreadContext32(thread->context_32, static_cast<u32>(stack_top),
  154. static_cast<u32>(entry_point), static_cast<u32>(arg));
  155. ResetThreadContext64(thread->context_64, stack_top, entry_point, arg);
  156. thread->host_context =
  157. std::make_shared<Common::Fiber>(std::move(thread_start_func), thread_start_parameter);
  158. return MakeResult<std::shared_ptr<KThread>>(std::move(thread));
  159. }
  160. void KThread::SetBasePriority(u32 priority) {
  161. ASSERT(Svc::HighestThreadPriority <= priority && priority <= Svc::LowestThreadPriority);
  162. KScopedSchedulerLock lock(kernel);
  163. // Change our base priority.
  164. base_priority = priority;
  165. // Perform a priority restoration.
  166. RestorePriority(kernel, this);
  167. }
  168. void KThread::SetSynchronizationResults(KSynchronizationObject* object, ResultCode result) {
  169. signaling_object = object;
  170. signaling_result = result;
  171. }
  172. VAddr KThread::GetCommandBufferAddress() const {
  173. // Offset from the start of TLS at which the IPC command buffer begins.
  174. constexpr u64 command_header_offset = 0x80;
  175. return GetTLSAddress() + command_header_offset;
  176. }
  177. void KThread::SetState(ThreadState state) {
  178. KScopedSchedulerLock sl(kernel);
  179. // Clear debugging state
  180. SetMutexWaitAddressForDebugging({});
  181. SetWaitReasonForDebugging({});
  182. const ThreadState old_state = thread_state;
  183. thread_state =
  184. static_cast<ThreadState>((old_state & ~ThreadState::Mask) | (state & ThreadState::Mask));
  185. if (thread_state != old_state) {
  186. KScheduler::OnThreadStateChanged(kernel, this, old_state);
  187. }
  188. }
  189. void KThread::AddWaiterImpl(KThread* thread) {
  190. ASSERT(kernel.GlobalSchedulerContext().IsLocked());
  191. // Find the right spot to insert the waiter.
  192. auto it = waiter_list.begin();
  193. while (it != waiter_list.end()) {
  194. if (it->GetPriority() > thread->GetPriority()) {
  195. break;
  196. }
  197. it++;
  198. }
  199. // Keep track of how many kernel waiters we have.
  200. if (Memory::IsKernelAddressKey(thread->GetAddressKey())) {
  201. ASSERT((num_kernel_waiters++) >= 0);
  202. }
  203. // Insert the waiter.
  204. waiter_list.insert(it, *thread);
  205. thread->SetLockOwner(this);
  206. }
  207. void KThread::RemoveWaiterImpl(KThread* thread) {
  208. ASSERT(kernel.GlobalSchedulerContext().IsLocked());
  209. // Keep track of how many kernel waiters we have.
  210. if (Memory::IsKernelAddressKey(thread->GetAddressKey())) {
  211. ASSERT((num_kernel_waiters--) > 0);
  212. }
  213. // Remove the waiter.
  214. waiter_list.erase(waiter_list.iterator_to(*thread));
  215. thread->SetLockOwner(nullptr);
  216. }
  217. void KThread::RestorePriority(KernelCore& kernel, KThread* thread) {
  218. ASSERT(kernel.GlobalSchedulerContext().IsLocked());
  219. while (true) {
  220. // We want to inherit priority where possible.
  221. s32 new_priority = thread->GetBasePriority();
  222. if (thread->HasWaiters()) {
  223. new_priority = std::min(new_priority, thread->waiter_list.front().GetPriority());
  224. }
  225. // If the priority we would inherit is not different from ours, don't do anything.
  226. if (new_priority == thread->GetPriority()) {
  227. return;
  228. }
  229. // Ensure we don't violate condition variable red black tree invariants.
  230. if (auto* cv_tree = thread->GetConditionVariableTree(); cv_tree != nullptr) {
  231. BeforeUpdatePriority(kernel, cv_tree, thread);
  232. }
  233. // Change the priority.
  234. const s32 old_priority = thread->GetPriority();
  235. thread->SetPriority(new_priority);
  236. // Restore the condition variable, if relevant.
  237. if (auto* cv_tree = thread->GetConditionVariableTree(); cv_tree != nullptr) {
  238. AfterUpdatePriority(kernel, cv_tree, thread);
  239. }
  240. // Update the scheduler.
  241. KScheduler::OnThreadPriorityChanged(kernel, thread, old_priority);
  242. // Keep the lock owner up to date.
  243. KThread* lock_owner = thread->GetLockOwner();
  244. if (lock_owner == nullptr) {
  245. return;
  246. }
  247. // Update the thread in the lock owner's sorted list, and continue inheriting.
  248. lock_owner->RemoveWaiterImpl(thread);
  249. lock_owner->AddWaiterImpl(thread);
  250. thread = lock_owner;
  251. }
  252. }
  253. void KThread::AddWaiter(KThread* thread) {
  254. AddWaiterImpl(thread);
  255. RestorePriority(kernel, this);
  256. }
  257. void KThread::RemoveWaiter(KThread* thread) {
  258. RemoveWaiterImpl(thread);
  259. RestorePriority(kernel, this);
  260. }
  261. KThread* KThread::RemoveWaiterByKey(s32* out_num_waiters, VAddr key) {
  262. ASSERT(kernel.GlobalSchedulerContext().IsLocked());
  263. s32 num_waiters{};
  264. KThread* next_lock_owner{};
  265. auto it = waiter_list.begin();
  266. while (it != waiter_list.end()) {
  267. if (it->GetAddressKey() == key) {
  268. KThread* thread = std::addressof(*it);
  269. // Keep track of how many kernel waiters we have.
  270. if (Memory::IsKernelAddressKey(thread->GetAddressKey())) {
  271. ASSERT((num_kernel_waiters--) > 0);
  272. }
  273. it = waiter_list.erase(it);
  274. // Update the next lock owner.
  275. if (next_lock_owner == nullptr) {
  276. next_lock_owner = thread;
  277. next_lock_owner->SetLockOwner(nullptr);
  278. } else {
  279. next_lock_owner->AddWaiterImpl(thread);
  280. }
  281. num_waiters++;
  282. } else {
  283. it++;
  284. }
  285. }
  286. // Do priority updates, if we have a next owner.
  287. if (next_lock_owner) {
  288. RestorePriority(kernel, this);
  289. RestorePriority(kernel, next_lock_owner);
  290. }
  291. // Return output.
  292. *out_num_waiters = num_waiters;
  293. return next_lock_owner;
  294. }
  295. ResultCode KThread::SetActivity(ThreadActivity value) {
  296. KScopedSchedulerLock lock(kernel);
  297. auto sched_status = GetState();
  298. if (sched_status != ThreadState::Runnable && sched_status != ThreadState::Waiting) {
  299. return ERR_INVALID_STATE;
  300. }
  301. if (IsTerminationRequested()) {
  302. return RESULT_SUCCESS;
  303. }
  304. if (value == ThreadActivity::Paused) {
  305. if ((pausing_state & static_cast<u32>(ThreadSchedFlags::ThreadPauseFlag)) != 0) {
  306. return ERR_INVALID_STATE;
  307. }
  308. AddSchedulingFlag(ThreadSchedFlags::ThreadPauseFlag);
  309. } else {
  310. if ((pausing_state & static_cast<u32>(ThreadSchedFlags::ThreadPauseFlag)) == 0) {
  311. return ERR_INVALID_STATE;
  312. }
  313. RemoveSchedulingFlag(ThreadSchedFlags::ThreadPauseFlag);
  314. }
  315. return RESULT_SUCCESS;
  316. }
  317. ResultCode KThread::Sleep(s64 nanoseconds) {
  318. Handle event_handle{};
  319. {
  320. KScopedSchedulerLockAndSleep lock(kernel, event_handle, this, nanoseconds);
  321. SetState(ThreadState::Waiting);
  322. SetWaitReasonForDebugging(ThreadWaitReasonForDebugging::Sleep);
  323. }
  324. if (event_handle != InvalidHandle) {
  325. auto& time_manager = kernel.TimeManager();
  326. time_manager.UnscheduleTimeEvent(event_handle);
  327. }
  328. return RESULT_SUCCESS;
  329. }
  330. void KThread::AddSchedulingFlag(ThreadSchedFlags flag) {
  331. const auto old_state = GetRawState();
  332. pausing_state |= static_cast<u32>(flag);
  333. const auto base_scheduling = GetState();
  334. thread_state = base_scheduling | static_cast<ThreadState>(pausing_state);
  335. KScheduler::OnThreadStateChanged(kernel, this, old_state);
  336. }
  337. void KThread::RemoveSchedulingFlag(ThreadSchedFlags flag) {
  338. const auto old_state = GetRawState();
  339. pausing_state &= ~static_cast<u32>(flag);
  340. const auto base_scheduling = GetState();
  341. thread_state = base_scheduling | static_cast<ThreadState>(pausing_state);
  342. KScheduler::OnThreadStateChanged(kernel, this, old_state);
  343. }
  344. ResultCode KThread::SetCoreAndAffinityMask(s32 new_core, u64 new_affinity_mask) {
  345. KScopedSchedulerLock lock(kernel);
  346. const auto HighestSetCore = [](u64 mask, u32 max_cores) {
  347. for (s32 core = static_cast<s32>(max_cores - 1); core >= 0; core--) {
  348. if (((mask >> core) & 1) != 0) {
  349. return core;
  350. }
  351. }
  352. return -1;
  353. };
  354. const bool use_override = affinity_override_count != 0;
  355. if (new_core == THREADPROCESSORID_DONT_UPDATE) {
  356. new_core = use_override ? ideal_core_override : ideal_core;
  357. if ((new_affinity_mask & (1ULL << new_core)) == 0) {
  358. LOG_ERROR(Kernel, "New affinity mask is incorrect! new_core={}, new_affinity_mask={}",
  359. new_core, new_affinity_mask);
  360. return ERR_INVALID_COMBINATION;
  361. }
  362. }
  363. if (use_override) {
  364. ideal_core_override = new_core;
  365. } else {
  366. const auto old_affinity_mask = affinity_mask;
  367. affinity_mask.SetAffinityMask(new_affinity_mask);
  368. ideal_core = new_core;
  369. if (old_affinity_mask.GetAffinityMask() != new_affinity_mask) {
  370. const s32 old_core = processor_id;
  371. if (processor_id >= 0 && !affinity_mask.GetAffinity(processor_id)) {
  372. if (static_cast<s32>(ideal_core) < 0) {
  373. processor_id = HighestSetCore(affinity_mask.GetAffinityMask(),
  374. Core::Hardware::NUM_CPU_CORES);
  375. } else {
  376. processor_id = ideal_core;
  377. }
  378. }
  379. KScheduler::OnThreadAffinityMaskChanged(kernel, this, old_affinity_mask, old_core);
  380. }
  381. }
  382. return RESULT_SUCCESS;
  383. }
  384. } // namespace Kernel