thread.cpp 18 KB

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