thread.cpp 16 KB

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