thread.cpp 18 KB

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