thread.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  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/arm/arm_interface.h"
  14. #ifdef ARCHITECTURE_x86_64
  15. #include "core/arm/dynarmic/arm_dynarmic_32.h"
  16. #include "core/arm/dynarmic/arm_dynarmic_64.h"
  17. #endif
  18. #include "core/arm/cpu_interrupt_handler.h"
  19. #include "core/arm/exclusive_monitor.h"
  20. #include "core/arm/unicorn/arm_unicorn.h"
  21. #include "core/core.h"
  22. #include "core/core_timing.h"
  23. #include "core/core_timing_util.h"
  24. #include "core/cpu_manager.h"
  25. #include "core/hardware_properties.h"
  26. #include "core/hle/kernel/errors.h"
  27. #include "core/hle/kernel/handle_table.h"
  28. #include "core/hle/kernel/kernel.h"
  29. #include "core/hle/kernel/object.h"
  30. #include "core/hle/kernel/process.h"
  31. #include "core/hle/kernel/scheduler.h"
  32. #include "core/hle/kernel/thread.h"
  33. #include "core/hle/kernel/time_manager.h"
  34. #include "core/hle/result.h"
  35. #include "core/memory.h"
  36. namespace Kernel {
  37. bool Thread::ShouldWait(const Thread* thread) const {
  38. return status != ThreadStatus::Dead;
  39. }
  40. bool Thread::IsSignaled() const {
  41. return status == ThreadStatus::Dead;
  42. }
  43. void Thread::Acquire(Thread* thread) {
  44. ASSERT_MSG(!ShouldWait(thread), "object unavailable!");
  45. }
  46. Thread::Thread(KernelCore& kernel) : SynchronizationObject{kernel} {}
  47. Thread::~Thread() = default;
  48. void Thread::Stop() {
  49. {
  50. SchedulerLock lock(kernel);
  51. SetStatus(ThreadStatus::Dead);
  52. Signal();
  53. kernel.GlobalHandleTable().Close(global_handle);
  54. if (owner_process) {
  55. owner_process->UnregisterThread(this);
  56. // Mark the TLS slot in the thread's page as free.
  57. owner_process->FreeTLSRegion(tls_address);
  58. }
  59. arm_interface.reset();
  60. has_exited = true;
  61. }
  62. global_handle = 0;
  63. }
  64. void Thread::ResumeFromWait() {
  65. SchedulerLock lock(kernel);
  66. switch (status) {
  67. case ThreadStatus::Paused:
  68. case ThreadStatus::WaitSynch:
  69. case ThreadStatus::WaitHLEEvent:
  70. case ThreadStatus::WaitSleep:
  71. case ThreadStatus::WaitIPC:
  72. case ThreadStatus::WaitMutex:
  73. case ThreadStatus::WaitCondVar:
  74. case ThreadStatus::WaitArb:
  75. case ThreadStatus::Dormant:
  76. break;
  77. case ThreadStatus::Ready:
  78. // The thread's wakeup callback must have already been cleared when the thread was first
  79. // awoken.
  80. ASSERT(hle_callback == nullptr);
  81. // If the thread is waiting on multiple wait objects, it might be awoken more than once
  82. // before actually resuming. We can ignore subsequent wakeups if the thread status has
  83. // already been set to ThreadStatus::Ready.
  84. return;
  85. case ThreadStatus::Running:
  86. DEBUG_ASSERT_MSG(false, "Thread with object id {} has already resumed.", GetObjectId());
  87. return;
  88. case ThreadStatus::Dead:
  89. // This should never happen, as threads must complete before being stopped.
  90. DEBUG_ASSERT_MSG(false, "Thread with object id {} cannot be resumed because it's DEAD.",
  91. GetObjectId());
  92. return;
  93. }
  94. SetStatus(ThreadStatus::Ready);
  95. }
  96. void Thread::OnWakeUp() {
  97. SchedulerLock lock(kernel);
  98. SetStatus(ThreadStatus::Ready);
  99. }
  100. ResultCode Thread::Start() {
  101. SchedulerLock lock(kernel);
  102. SetStatus(ThreadStatus::Ready);
  103. return RESULT_SUCCESS;
  104. }
  105. void Thread::CancelWait() {
  106. SchedulerLock lock(kernel);
  107. if (GetSchedulingStatus() != ThreadSchedStatus::Paused || !is_waiting_on_sync) {
  108. is_sync_cancelled = true;
  109. return;
  110. }
  111. // TODO(Blinkhawk): Implement cancel of server session
  112. is_sync_cancelled = false;
  113. SetSynchronizationResults(nullptr, ERR_SYNCHRONIZATION_CANCELED);
  114. SetStatus(ThreadStatus::Ready);
  115. }
  116. static void ResetThreadContext32(Core::ARM_Interface::ThreadContext32& context, u32 stack_top,
  117. u32 entry_point, u32 arg) {
  118. context = {};
  119. context.cpu_registers[0] = arg;
  120. context.cpu_registers[15] = entry_point;
  121. context.cpu_registers[13] = stack_top;
  122. }
  123. static void ResetThreadContext64(Core::ARM_Interface::ThreadContext64& context, VAddr stack_top,
  124. VAddr entry_point, u64 arg) {
  125. context = {};
  126. context.cpu_registers[0] = arg;
  127. context.pc = entry_point;
  128. context.sp = stack_top;
  129. // TODO(merry): Perform a hardware test to determine the below value.
  130. context.fpcr = 0;
  131. }
  132. std::shared_ptr<Common::Fiber>& Thread::GetHostContext() {
  133. return host_context;
  134. }
  135. ResultVal<std::shared_ptr<Thread>> Thread::Create(Core::System& system, ThreadType type_flags,
  136. std::string name, VAddr entry_point, u32 priority,
  137. u64 arg, s32 processor_id, VAddr stack_top,
  138. Process* owner_process) {
  139. std::function<void(void*)> init_func = system.GetCpuManager().GetGuestThreadStartFunc();
  140. void* init_func_parameter = system.GetCpuManager().GetStartFuncParamater();
  141. return Create(system, type_flags, name, entry_point, priority, arg, processor_id, stack_top,
  142. owner_process, std::move(init_func), init_func_parameter);
  143. }
  144. ResultVal<std::shared_ptr<Thread>> Thread::Create(Core::System& system, ThreadType type_flags,
  145. std::string name, VAddr entry_point, u32 priority,
  146. u64 arg, s32 processor_id, VAddr stack_top,
  147. Process* owner_process,
  148. std::function<void(void*)>&& thread_start_func,
  149. void* thread_start_parameter) {
  150. auto& kernel = system.Kernel();
  151. // Check if priority is in ranged. Lowest priority -> highest priority id.
  152. if (priority > THREADPRIO_LOWEST && ((type_flags & THREADTYPE_IDLE) == 0)) {
  153. LOG_ERROR(Kernel_SVC, "Invalid thread priority: {}", priority);
  154. return ERR_INVALID_THREAD_PRIORITY;
  155. }
  156. if (processor_id > THREADPROCESSORID_MAX) {
  157. LOG_ERROR(Kernel_SVC, "Invalid processor id: {}", processor_id);
  158. return ERR_INVALID_PROCESSOR_ID;
  159. }
  160. if (owner_process) {
  161. if (!system.Memory().IsValidVirtualAddress(*owner_process, entry_point)) {
  162. LOG_ERROR(Kernel_SVC, "(name={}): invalid entry {:016X}", name, entry_point);
  163. // TODO (bunnei): Find the correct error code to use here
  164. return RESULT_UNKNOWN;
  165. }
  166. }
  167. std::shared_ptr<Thread> thread = std::make_shared<Thread>(kernel);
  168. thread->thread_id = kernel.CreateNewThreadID();
  169. thread->status = ThreadStatus::Dormant;
  170. thread->entry_point = entry_point;
  171. thread->stack_top = stack_top;
  172. thread->tpidr_el0 = 0;
  173. thread->nominal_priority = thread->current_priority = priority;
  174. thread->last_running_ticks = 0;
  175. thread->processor_id = processor_id;
  176. thread->ideal_core = processor_id;
  177. thread->affinity_mask = 1ULL << processor_id;
  178. thread->wait_objects = nullptr;
  179. thread->mutex_wait_address = 0;
  180. thread->condvar_wait_address = 0;
  181. thread->wait_handle = 0;
  182. thread->name = std::move(name);
  183. thread->global_handle = kernel.GlobalHandleTable().Create(thread).Unwrap();
  184. thread->owner_process = owner_process;
  185. thread->type = type_flags;
  186. if ((type_flags & THREADTYPE_IDLE) == 0) {
  187. auto& scheduler = kernel.GlobalScheduler();
  188. scheduler.AddThread(thread);
  189. }
  190. if (owner_process) {
  191. thread->tls_address = thread->owner_process->CreateTLSRegion();
  192. thread->owner_process->RegisterThread(thread.get());
  193. } else {
  194. thread->tls_address = 0;
  195. }
  196. // TODO(peachum): move to ScheduleThread() when scheduler is added so selected core is used
  197. // to initialize the context
  198. thread->arm_interface.reset();
  199. if ((type_flags & THREADTYPE_HLE) == 0) {
  200. #ifdef ARCHITECTURE_x86_64
  201. if (owner_process && !owner_process->Is64BitProcess()) {
  202. thread->arm_interface = std::make_unique<Core::ARM_Dynarmic_32>(
  203. system, kernel.Interrupts(), kernel.IsMulticore(), kernel.GetExclusiveMonitor(),
  204. processor_id);
  205. } else {
  206. thread->arm_interface = std::make_unique<Core::ARM_Dynarmic_64>(
  207. system, kernel.Interrupts(), kernel.IsMulticore(), kernel.GetExclusiveMonitor(),
  208. processor_id);
  209. }
  210. #else
  211. if (owner_process && !owner_process->Is64BitProcess()) {
  212. thread->arm_interface = std::make_shared<Core::ARM_Unicorn>(
  213. system, kernel.Interrupts(), kernel.IsMulticore(), ARM_Unicorn::Arch::AArch32,
  214. processor_id);
  215. } else {
  216. thread->arm_interface = std::make_shared<Core::ARM_Unicorn>(
  217. system, kernel.Interrupts(), kernel.IsMulticore(), ARM_Unicorn::Arch::AArch64,
  218. processor_id);
  219. }
  220. LOG_WARNING(Core, "CPU JIT requested, but Dynarmic not available");
  221. #endif
  222. ResetThreadContext32(thread->context_32, static_cast<u32>(stack_top),
  223. static_cast<u32>(entry_point), static_cast<u32>(arg));
  224. ResetThreadContext64(thread->context_64, stack_top, entry_point, arg);
  225. }
  226. thread->host_context =
  227. std::make_shared<Common::Fiber>(std::move(thread_start_func), thread_start_parameter);
  228. return MakeResult<std::shared_ptr<Thread>>(std::move(thread));
  229. }
  230. void Thread::SetPriority(u32 priority) {
  231. SchedulerLock lock(kernel);
  232. ASSERT_MSG(priority <= THREADPRIO_LOWEST && priority >= THREADPRIO_HIGHEST,
  233. "Invalid priority value.");
  234. nominal_priority = priority;
  235. UpdatePriority();
  236. }
  237. void Thread::SetSynchronizationResults(SynchronizationObject* object, ResultCode result) {
  238. signaling_object = object;
  239. signaling_result = result;
  240. }
  241. s32 Thread::GetSynchronizationObjectIndex(std::shared_ptr<SynchronizationObject> object) const {
  242. ASSERT_MSG(!wait_objects->empty(), "Thread is not waiting for anything");
  243. const auto match = std::find(wait_objects->rbegin(), wait_objects->rend(), object);
  244. return static_cast<s32>(std::distance(match, wait_objects->rend()) - 1);
  245. }
  246. VAddr Thread::GetCommandBufferAddress() const {
  247. // Offset from the start of TLS at which the IPC command buffer begins.
  248. constexpr u64 command_header_offset = 0x80;
  249. return GetTLSAddress() + command_header_offset;
  250. }
  251. Core::ARM_Interface& Thread::ArmInterface() {
  252. return *arm_interface;
  253. }
  254. const Core::ARM_Interface& Thread::ArmInterface() const {
  255. return *arm_interface;
  256. }
  257. void Thread::SetStatus(ThreadStatus new_status) {
  258. if (new_status == status) {
  259. return;
  260. }
  261. switch (new_status) {
  262. case ThreadStatus::Ready:
  263. case ThreadStatus::Running:
  264. SetSchedulingStatus(ThreadSchedStatus::Runnable);
  265. break;
  266. case ThreadStatus::Dormant:
  267. SetSchedulingStatus(ThreadSchedStatus::None);
  268. break;
  269. case ThreadStatus::Dead:
  270. SetSchedulingStatus(ThreadSchedStatus::Exited);
  271. break;
  272. default:
  273. SetSchedulingStatus(ThreadSchedStatus::Paused);
  274. break;
  275. }
  276. status = new_status;
  277. }
  278. void Thread::AddMutexWaiter(std::shared_ptr<Thread> thread) {
  279. if (thread->lock_owner.get() == this) {
  280. // If the thread is already waiting for this thread to release the mutex, ensure that the
  281. // waiters list is consistent and return without doing anything.
  282. const auto iter = std::find(wait_mutex_threads.begin(), wait_mutex_threads.end(), thread);
  283. ASSERT(iter != wait_mutex_threads.end());
  284. return;
  285. }
  286. // A thread can't wait on two different mutexes at the same time.
  287. ASSERT(thread->lock_owner == nullptr);
  288. // Ensure that the thread is not already in the list of mutex waiters
  289. const auto iter = std::find(wait_mutex_threads.begin(), wait_mutex_threads.end(), thread);
  290. ASSERT(iter == wait_mutex_threads.end());
  291. // Keep the list in an ordered fashion
  292. const auto insertion_point = std::find_if(
  293. wait_mutex_threads.begin(), wait_mutex_threads.end(),
  294. [&thread](const auto& entry) { return entry->GetPriority() > thread->GetPriority(); });
  295. wait_mutex_threads.insert(insertion_point, thread);
  296. thread->lock_owner = SharedFrom(this);
  297. UpdatePriority();
  298. }
  299. void Thread::RemoveMutexWaiter(std::shared_ptr<Thread> thread) {
  300. ASSERT(thread->lock_owner.get() == this);
  301. // Ensure that the thread is in the list of mutex waiters
  302. const auto iter = std::find(wait_mutex_threads.begin(), wait_mutex_threads.end(), thread);
  303. ASSERT(iter != wait_mutex_threads.end());
  304. wait_mutex_threads.erase(iter);
  305. thread->lock_owner = nullptr;
  306. UpdatePriority();
  307. }
  308. void Thread::UpdatePriority() {
  309. // If any of the threads waiting on the mutex have a higher priority
  310. // (taking into account priority inheritance), then this thread inherits
  311. // that thread's priority.
  312. u32 new_priority = nominal_priority;
  313. if (!wait_mutex_threads.empty()) {
  314. if (wait_mutex_threads.front()->current_priority < new_priority) {
  315. new_priority = wait_mutex_threads.front()->current_priority;
  316. }
  317. }
  318. if (new_priority == current_priority) {
  319. return;
  320. }
  321. if (GetStatus() == ThreadStatus::WaitCondVar) {
  322. owner_process->RemoveConditionVariableThread(SharedFrom(this));
  323. }
  324. SetCurrentPriority(new_priority);
  325. if (GetStatus() == ThreadStatus::WaitCondVar) {
  326. owner_process->InsertConditionVariableThread(SharedFrom(this));
  327. }
  328. if (!lock_owner) {
  329. return;
  330. }
  331. // Ensure that the thread is within the correct location in the waiting list.
  332. auto old_owner = lock_owner;
  333. lock_owner->RemoveMutexWaiter(SharedFrom(this));
  334. old_owner->AddMutexWaiter(SharedFrom(this));
  335. // Recursively update the priority of the thread that depends on the priority of this one.
  336. lock_owner->UpdatePriority();
  337. }
  338. bool Thread::AllSynchronizationObjectsReady() const {
  339. return std::none_of(wait_objects->begin(), wait_objects->end(),
  340. [this](const std::shared_ptr<SynchronizationObject>& object) {
  341. return object->ShouldWait(this);
  342. });
  343. }
  344. bool Thread::InvokeHLECallback(std::shared_ptr<Thread> thread) {
  345. ASSERT(hle_callback);
  346. return hle_callback(std::move(thread));
  347. }
  348. ResultCode Thread::SetActivity(ThreadActivity value) {
  349. SchedulerLock lock(kernel);
  350. auto sched_status = GetSchedulingStatus();
  351. if (sched_status != ThreadSchedStatus::Runnable && sched_status != ThreadSchedStatus::Paused) {
  352. return ERR_INVALID_STATE;
  353. }
  354. if (IsPendingTermination()) {
  355. return RESULT_SUCCESS;
  356. }
  357. if (value == ThreadActivity::Paused) {
  358. if ((pausing_state & static_cast<u32>(ThreadSchedFlags::ThreadPauseFlag)) != 0) {
  359. return ERR_INVALID_STATE;
  360. }
  361. AddSchedulingFlag(ThreadSchedFlags::ThreadPauseFlag);
  362. } else {
  363. if ((pausing_state & static_cast<u32>(ThreadSchedFlags::ThreadPauseFlag)) == 0) {
  364. return ERR_INVALID_STATE;
  365. }
  366. RemoveSchedulingFlag(ThreadSchedFlags::ThreadPauseFlag);
  367. }
  368. return RESULT_SUCCESS;
  369. }
  370. ResultCode Thread::Sleep(s64 nanoseconds) {
  371. Handle event_handle{};
  372. {
  373. SchedulerLockAndSleep lock(kernel, event_handle, this, nanoseconds);
  374. SetStatus(ThreadStatus::WaitSleep);
  375. }
  376. if (event_handle != InvalidHandle) {
  377. auto& time_manager = kernel.TimeManager();
  378. time_manager.UnscheduleTimeEvent(event_handle);
  379. }
  380. return RESULT_SUCCESS;
  381. }
  382. std::pair<ResultCode, bool> Thread::YieldSimple() {
  383. bool is_redundant = false;
  384. {
  385. SchedulerLock lock(kernel);
  386. is_redundant = kernel.GlobalScheduler().YieldThread(this);
  387. }
  388. return {RESULT_SUCCESS, is_redundant};
  389. }
  390. std::pair<ResultCode, bool> Thread::YieldAndBalanceLoad() {
  391. bool is_redundant = false;
  392. {
  393. SchedulerLock lock(kernel);
  394. is_redundant = kernel.GlobalScheduler().YieldThreadAndBalanceLoad(this);
  395. }
  396. return {RESULT_SUCCESS, is_redundant};
  397. }
  398. std::pair<ResultCode, bool> Thread::YieldAndWaitForLoadBalancing() {
  399. bool is_redundant = false;
  400. {
  401. SchedulerLock lock(kernel);
  402. is_redundant = kernel.GlobalScheduler().YieldThreadAndWaitForLoadBalancing(this);
  403. }
  404. return {RESULT_SUCCESS, is_redundant};
  405. }
  406. void Thread::AddSchedulingFlag(ThreadSchedFlags flag) {
  407. const u32 old_state = scheduling_state;
  408. pausing_state |= static_cast<u32>(flag);
  409. const u32 base_scheduling = static_cast<u32>(GetSchedulingStatus());
  410. scheduling_state = base_scheduling | pausing_state;
  411. kernel.GlobalScheduler().AdjustSchedulingOnStatus(this, old_state);
  412. }
  413. void Thread::RemoveSchedulingFlag(ThreadSchedFlags flag) {
  414. const u32 old_state = scheduling_state;
  415. pausing_state &= ~static_cast<u32>(flag);
  416. const u32 base_scheduling = static_cast<u32>(GetSchedulingStatus());
  417. scheduling_state = base_scheduling | pausing_state;
  418. kernel.GlobalScheduler().AdjustSchedulingOnStatus(this, old_state);
  419. }
  420. void Thread::SetSchedulingStatus(ThreadSchedStatus new_status) {
  421. const u32 old_state = scheduling_state;
  422. scheduling_state = (scheduling_state & static_cast<u32>(ThreadSchedMasks::HighMask)) |
  423. static_cast<u32>(new_status);
  424. kernel.GlobalScheduler().AdjustSchedulingOnStatus(this, old_state);
  425. }
  426. void Thread::SetCurrentPriority(u32 new_priority) {
  427. const u32 old_priority = std::exchange(current_priority, new_priority);
  428. kernel.GlobalScheduler().AdjustSchedulingOnPriority(this, old_priority);
  429. }
  430. ResultCode Thread::SetCoreAndAffinityMask(s32 new_core, u64 new_affinity_mask) {
  431. SchedulerLock lock(kernel);
  432. const auto HighestSetCore = [](u64 mask, u32 max_cores) {
  433. for (s32 core = static_cast<s32>(max_cores - 1); core >= 0; core--) {
  434. if (((mask >> core) & 1) != 0) {
  435. return core;
  436. }
  437. }
  438. return -1;
  439. };
  440. const bool use_override = affinity_override_count != 0;
  441. if (new_core == THREADPROCESSORID_DONT_UPDATE) {
  442. new_core = use_override ? ideal_core_override : ideal_core;
  443. if ((new_affinity_mask & (1ULL << new_core)) == 0) {
  444. LOG_ERROR(Kernel, "New affinity mask is incorrect! new_core={}, new_affinity_mask={}",
  445. new_core, new_affinity_mask);
  446. return ERR_INVALID_COMBINATION;
  447. }
  448. }
  449. if (use_override) {
  450. ideal_core_override = new_core;
  451. affinity_mask_override = new_affinity_mask;
  452. } else {
  453. const u64 old_affinity_mask = std::exchange(affinity_mask, new_affinity_mask);
  454. ideal_core = new_core;
  455. if (old_affinity_mask != new_affinity_mask) {
  456. const s32 old_core = processor_id;
  457. if (processor_id >= 0 && ((affinity_mask >> processor_id) & 1) == 0) {
  458. if (static_cast<s32>(ideal_core) < 0) {
  459. processor_id = HighestSetCore(affinity_mask, Core::Hardware::NUM_CPU_CORES);
  460. } else {
  461. processor_id = ideal_core;
  462. }
  463. }
  464. kernel.GlobalScheduler().AdjustSchedulingOnAffinity(this, old_affinity_mask, old_core);
  465. }
  466. }
  467. return RESULT_SUCCESS;
  468. }
  469. ////////////////////////////////////////////////////////////////////////////////////////////////////
  470. /**
  471. * Gets the current thread
  472. */
  473. Thread* GetCurrentThread() {
  474. return Core::System::GetInstance().CurrentScheduler().GetCurrentThread();
  475. }
  476. } // namespace Kernel