thread.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  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/logging/log.h"
  11. #include "common/thread_queue_list.h"
  12. #include "core/arm/arm_interface.h"
  13. #include "core/core.h"
  14. #include "core/core_cpu.h"
  15. #include "core/core_timing.h"
  16. #include "core/core_timing_util.h"
  17. #include "core/hle/kernel/errors.h"
  18. #include "core/hle/kernel/handle_table.h"
  19. #include "core/hle/kernel/kernel.h"
  20. #include "core/hle/kernel/object.h"
  21. #include "core/hle/kernel/process.h"
  22. #include "core/hle/kernel/scheduler.h"
  23. #include "core/hle/kernel/thread.h"
  24. #include "core/hle/result.h"
  25. #include "core/memory.h"
  26. namespace Kernel {
  27. bool Thread::ShouldWait(const Thread* thread) const {
  28. return status != ThreadStatus::Dead;
  29. }
  30. void Thread::Acquire(Thread* thread) {
  31. ASSERT_MSG(!ShouldWait(thread), "object unavailable!");
  32. }
  33. Thread::Thread(KernelCore& kernel) : WaitObject{kernel} {}
  34. Thread::~Thread() = default;
  35. void Thread::Stop() {
  36. // Cancel any outstanding wakeup events for this thread
  37. Core::System::GetInstance().CoreTiming().UnscheduleEvent(kernel.ThreadWakeupCallbackEventType(),
  38. callback_handle);
  39. kernel.ThreadWakeupCallbackHandleTable().Close(callback_handle);
  40. callback_handle = 0;
  41. SetStatus(ThreadStatus::Dead);
  42. WakeupAllWaitingThreads();
  43. // Clean up any dangling references in objects that this thread was waiting for
  44. for (auto& wait_object : wait_objects) {
  45. wait_object->RemoveWaitingThread(this);
  46. }
  47. wait_objects.clear();
  48. owner_process->UnregisterThread(this);
  49. // Mark the TLS slot in the thread's page as free.
  50. owner_process->FreeTLSRegion(tls_address);
  51. }
  52. void Thread::WakeAfterDelay(s64 nanoseconds) {
  53. // Don't schedule a wakeup if the thread wants to wait forever
  54. if (nanoseconds == -1)
  55. return;
  56. // This function might be called from any thread so we have to be cautious and use the
  57. // thread-safe version of ScheduleEvent.
  58. const s64 cycles = Core::Timing::nsToCycles(std::chrono::nanoseconds{nanoseconds});
  59. Core::System::GetInstance().CoreTiming().ScheduleEvent(
  60. cycles, kernel.ThreadWakeupCallbackEventType(), callback_handle);
  61. }
  62. void Thread::CancelWakeupTimer() {
  63. Core::System::GetInstance().CoreTiming().UnscheduleEvent(kernel.ThreadWakeupCallbackEventType(),
  64. callback_handle);
  65. }
  66. void Thread::ResumeFromWait() {
  67. ASSERT_MSG(wait_objects.empty(), "Thread is waking up while waiting for objects");
  68. switch (status) {
  69. case ThreadStatus::WaitSynch:
  70. case ThreadStatus::WaitHLEEvent:
  71. case ThreadStatus::WaitSleep:
  72. case ThreadStatus::WaitIPC:
  73. case ThreadStatus::WaitMutex:
  74. case ThreadStatus::WaitCondVar:
  75. case ThreadStatus::WaitArb:
  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(wakeup_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. wakeup_callback = nullptr;
  95. if (activity == ThreadActivity::Paused) {
  96. SetStatus(ThreadStatus::Paused);
  97. return;
  98. }
  99. SetStatus(ThreadStatus::Ready);
  100. }
  101. void Thread::CancelWait() {
  102. ASSERT(GetStatus() == ThreadStatus::WaitSynch);
  103. ClearWaitObjects();
  104. SetWaitSynchronizationResult(ERR_SYNCHRONIZATION_CANCELED);
  105. ResumeFromWait();
  106. }
  107. /**
  108. * Resets a thread context, making it ready to be scheduled and run by the CPU
  109. * @param context Thread context to reset
  110. * @param stack_top Address of the top of the stack
  111. * @param entry_point Address of entry point for execution
  112. * @param arg User argument for thread
  113. */
  114. static void ResetThreadContext(Core::ARM_Interface::ThreadContext& context, VAddr stack_top,
  115. VAddr entry_point, u64 arg) {
  116. context = {};
  117. context.cpu_registers[0] = arg;
  118. context.pc = entry_point;
  119. context.sp = stack_top;
  120. // TODO(merry): Perform a hardware test to determine the below value.
  121. // AHP = 0, DN = 1, FTZ = 1, RMode = Round towards zero
  122. context.fpcr = 0x03C00000;
  123. }
  124. ResultVal<SharedPtr<Thread>> Thread::Create(KernelCore& kernel, std::string name, VAddr entry_point,
  125. u32 priority, u64 arg, s32 processor_id,
  126. VAddr stack_top, Process& owner_process) {
  127. // Check if priority is in ranged. Lowest priority -> highest priority id.
  128. if (priority > THREADPRIO_LOWEST) {
  129. LOG_ERROR(Kernel_SVC, "Invalid thread priority: {}", priority);
  130. return ERR_INVALID_THREAD_PRIORITY;
  131. }
  132. if (processor_id > THREADPROCESSORID_MAX) {
  133. LOG_ERROR(Kernel_SVC, "Invalid processor id: {}", processor_id);
  134. return ERR_INVALID_PROCESSOR_ID;
  135. }
  136. if (!Memory::IsValidVirtualAddress(owner_process, entry_point)) {
  137. LOG_ERROR(Kernel_SVC, "(name={}): invalid entry {:016X}", name, entry_point);
  138. // TODO (bunnei): Find the correct error code to use here
  139. return RESULT_UNKNOWN;
  140. }
  141. auto& system = Core::System::GetInstance();
  142. SharedPtr<Thread> thread(new Thread(kernel));
  143. thread->thread_id = kernel.CreateNewThreadID();
  144. thread->status = ThreadStatus::Dormant;
  145. thread->entry_point = entry_point;
  146. thread->stack_top = stack_top;
  147. thread->tpidr_el0 = 0;
  148. thread->nominal_priority = thread->current_priority = priority;
  149. thread->last_running_ticks = system.CoreTiming().GetTicks();
  150. thread->processor_id = processor_id;
  151. thread->ideal_core = processor_id;
  152. thread->affinity_mask = 1ULL << processor_id;
  153. thread->wait_objects.clear();
  154. thread->mutex_wait_address = 0;
  155. thread->condvar_wait_address = 0;
  156. thread->wait_handle = 0;
  157. thread->name = std::move(name);
  158. thread->callback_handle = kernel.ThreadWakeupCallbackHandleTable().Create(thread).Unwrap();
  159. thread->owner_process = &owner_process;
  160. auto& scheduler = kernel.GlobalScheduler();
  161. scheduler.AddThread(thread);
  162. thread->tls_address = thread->owner_process->CreateTLSRegion();
  163. thread->owner_process->RegisterThread(thread.get());
  164. // TODO(peachum): move to ScheduleThread() when scheduler is added so selected core is used
  165. // to initialize the context
  166. ResetThreadContext(thread->context, stack_top, entry_point, arg);
  167. return MakeResult<SharedPtr<Thread>>(std::move(thread));
  168. }
  169. void Thread::SetPriority(u32 priority) {
  170. ASSERT_MSG(priority <= THREADPRIO_LOWEST && priority >= THREADPRIO_HIGHEST,
  171. "Invalid priority value.");
  172. nominal_priority = priority;
  173. UpdatePriority();
  174. }
  175. void Thread::SetWaitSynchronizationResult(ResultCode result) {
  176. context.cpu_registers[0] = result.raw;
  177. }
  178. void Thread::SetWaitSynchronizationOutput(s32 output) {
  179. context.cpu_registers[1] = output;
  180. }
  181. s32 Thread::GetWaitObjectIndex(const WaitObject* object) const {
  182. ASSERT_MSG(!wait_objects.empty(), "Thread is not waiting for anything");
  183. const auto match = std::find(wait_objects.rbegin(), wait_objects.rend(), object);
  184. return static_cast<s32>(std::distance(match, wait_objects.rend()) - 1);
  185. }
  186. VAddr Thread::GetCommandBufferAddress() const {
  187. // Offset from the start of TLS at which the IPC command buffer begins.
  188. constexpr u64 command_header_offset = 0x80;
  189. return GetTLSAddress() + command_header_offset;
  190. }
  191. void Thread::SetStatus(ThreadStatus new_status) {
  192. if (new_status == status) {
  193. return;
  194. }
  195. switch (new_status) {
  196. case ThreadStatus::Ready:
  197. case ThreadStatus::Running:
  198. SetSchedulingStatus(ThreadSchedStatus::Runnable);
  199. break;
  200. case ThreadStatus::Dormant:
  201. SetSchedulingStatus(ThreadSchedStatus::None);
  202. break;
  203. case ThreadStatus::Dead:
  204. SetSchedulingStatus(ThreadSchedStatus::Exited);
  205. break;
  206. default:
  207. SetSchedulingStatus(ThreadSchedStatus::Paused);
  208. break;
  209. }
  210. if (status == ThreadStatus::Running) {
  211. last_running_ticks = Core::System::GetInstance().CoreTiming().GetTicks();
  212. }
  213. status = new_status;
  214. }
  215. void Thread::AddMutexWaiter(SharedPtr<Thread> thread) {
  216. if (thread->lock_owner == this) {
  217. // If the thread is already waiting for this thread to release the mutex, ensure that the
  218. // waiters list is consistent and return without doing anything.
  219. const auto iter = std::find(wait_mutex_threads.begin(), wait_mutex_threads.end(), thread);
  220. ASSERT(iter != wait_mutex_threads.end());
  221. return;
  222. }
  223. // A thread can't wait on two different mutexes at the same time.
  224. ASSERT(thread->lock_owner == nullptr);
  225. // Ensure that the thread is not already in the list of mutex waiters
  226. const auto iter = std::find(wait_mutex_threads.begin(), wait_mutex_threads.end(), thread);
  227. ASSERT(iter == wait_mutex_threads.end());
  228. // Keep the list in an ordered fashion
  229. const auto insertion_point = std::find_if(
  230. wait_mutex_threads.begin(), wait_mutex_threads.end(),
  231. [&thread](const auto& entry) { return entry->GetPriority() > thread->GetPriority(); });
  232. wait_mutex_threads.insert(insertion_point, thread);
  233. thread->lock_owner = this;
  234. UpdatePriority();
  235. }
  236. void Thread::RemoveMutexWaiter(SharedPtr<Thread> thread) {
  237. ASSERT(thread->lock_owner == this);
  238. // Ensure that the thread is in the list of mutex waiters
  239. const auto iter = std::find(wait_mutex_threads.begin(), wait_mutex_threads.end(), thread);
  240. ASSERT(iter != wait_mutex_threads.end());
  241. wait_mutex_threads.erase(iter);
  242. thread->lock_owner = nullptr;
  243. UpdatePriority();
  244. }
  245. void Thread::UpdatePriority() {
  246. // If any of the threads waiting on the mutex have a higher priority
  247. // (taking into account priority inheritance), then this thread inherits
  248. // that thread's priority.
  249. u32 new_priority = nominal_priority;
  250. if (!wait_mutex_threads.empty()) {
  251. if (wait_mutex_threads.front()->current_priority < new_priority) {
  252. new_priority = wait_mutex_threads.front()->current_priority;
  253. }
  254. }
  255. if (new_priority == current_priority) {
  256. return;
  257. }
  258. SetCurrentPriority(new_priority);
  259. if (!lock_owner) {
  260. return;
  261. }
  262. // Ensure that the thread is within the correct location in the waiting list.
  263. auto old_owner = lock_owner;
  264. lock_owner->RemoveMutexWaiter(this);
  265. old_owner->AddMutexWaiter(this);
  266. // Recursively update the priority of the thread that depends on the priority of this one.
  267. lock_owner->UpdatePriority();
  268. }
  269. void Thread::ChangeCore(u32 core, u64 mask) {
  270. SetCoreAndAffinityMask(core, mask);
  271. }
  272. bool Thread::AllWaitObjectsReady() const {
  273. return std::none_of(
  274. wait_objects.begin(), wait_objects.end(),
  275. [this](const SharedPtr<WaitObject>& object) { return object->ShouldWait(this); });
  276. }
  277. bool Thread::InvokeWakeupCallback(ThreadWakeupReason reason, SharedPtr<Thread> thread,
  278. SharedPtr<WaitObject> object, std::size_t index) {
  279. ASSERT(wakeup_callback);
  280. return wakeup_callback(reason, std::move(thread), std::move(object), index);
  281. }
  282. void Thread::SetActivity(ThreadActivity value) {
  283. activity = value;
  284. if (value == ThreadActivity::Paused) {
  285. // Set status if not waiting
  286. if (status == ThreadStatus::Ready || status == ThreadStatus::Running) {
  287. SetStatus(ThreadStatus::Paused);
  288. Core::System::GetInstance().CpuCore(processor_id).PrepareReschedule();
  289. }
  290. } else if (status == ThreadStatus::Paused) {
  291. // Ready to reschedule
  292. ResumeFromWait();
  293. }
  294. }
  295. void Thread::Sleep(s64 nanoseconds) {
  296. // Sleep current thread and check for next thread to schedule
  297. SetStatus(ThreadStatus::WaitSleep);
  298. // Create an event to wake the thread up after the specified nanosecond delay has passed
  299. WakeAfterDelay(nanoseconds);
  300. }
  301. bool Thread::YieldSimple() {
  302. auto& scheduler = kernel.GlobalScheduler();
  303. return scheduler.YieldThread(this);
  304. }
  305. bool Thread::YieldAndBalanceLoad() {
  306. auto& scheduler = kernel.GlobalScheduler();
  307. return scheduler.YieldThreadAndBalanceLoad(this);
  308. }
  309. bool Thread::YieldAndWaitForLoadBalancing() {
  310. auto& scheduler = kernel.GlobalScheduler();
  311. return scheduler.YieldThreadAndWaitForLoadBalancing(this);
  312. }
  313. void Thread::SetSchedulingStatus(ThreadSchedStatus new_status) {
  314. const u32 old_flags = scheduling_state;
  315. scheduling_state = (scheduling_state & static_cast<u32>(ThreadSchedMasks::HighMask)) |
  316. static_cast<u32>(new_status);
  317. AdjustSchedulingOnStatus(old_flags);
  318. }
  319. void Thread::SetCurrentPriority(u32 new_priority) {
  320. const u32 old_priority = std::exchange(current_priority, new_priority);
  321. AdjustSchedulingOnPriority(old_priority);
  322. }
  323. ResultCode Thread::SetCoreAndAffinityMask(s32 new_core, u64 new_affinity_mask) {
  324. const auto HighestSetCore = [](u64 mask, u32 max_cores) {
  325. for (s32 core = static_cast<s32>(max_cores - 1); core >= 0; core--) {
  326. if (((mask >> core) & 1) != 0) {
  327. return core;
  328. }
  329. }
  330. return -1;
  331. };
  332. const bool use_override = affinity_override_count != 0;
  333. if (new_core == THREADPROCESSORID_DONT_UPDATE) {
  334. new_core = use_override ? ideal_core_override : ideal_core;
  335. if ((new_affinity_mask & (1ULL << new_core)) == 0) {
  336. return ERR_INVALID_COMBINATION;
  337. }
  338. }
  339. if (use_override) {
  340. ideal_core_override = new_core;
  341. affinity_mask_override = new_affinity_mask;
  342. } else {
  343. const u64 old_affinity_mask = std::exchange(affinity_mask, new_affinity_mask);
  344. ideal_core = new_core;
  345. if (old_affinity_mask != new_affinity_mask) {
  346. const s32 old_core = processor_id;
  347. if (processor_id >= 0 && ((affinity_mask >> processor_id) & 1) == 0) {
  348. if (static_cast<s32>(ideal_core) < 0) {
  349. processor_id = HighestSetCore(affinity_mask, GlobalScheduler::NUM_CPU_CORES);
  350. } else {
  351. processor_id = ideal_core;
  352. }
  353. }
  354. AdjustSchedulingOnAffinity(old_affinity_mask, old_core);
  355. }
  356. }
  357. return RESULT_SUCCESS;
  358. }
  359. void Thread::AdjustSchedulingOnStatus(u32 old_flags) {
  360. if (old_flags == scheduling_state) {
  361. return;
  362. }
  363. auto& scheduler = kernel.GlobalScheduler();
  364. if (static_cast<ThreadSchedStatus>(old_flags & static_cast<u32>(ThreadSchedMasks::LowMask)) ==
  365. ThreadSchedStatus::Runnable) {
  366. // In this case the thread was running, now it's pausing/exitting
  367. if (processor_id >= 0) {
  368. scheduler.Unschedule(current_priority, static_cast<u32>(processor_id), this);
  369. }
  370. for (u32 core = 0; core < GlobalScheduler::NUM_CPU_CORES; core++) {
  371. if (core != static_cast<u32>(processor_id) && ((affinity_mask >> core) & 1) != 0) {
  372. scheduler.Unsuggest(current_priority, core, this);
  373. }
  374. }
  375. } else if (GetSchedulingStatus() == ThreadSchedStatus::Runnable) {
  376. // The thread is now set to running from being stopped
  377. if (processor_id >= 0) {
  378. scheduler.Schedule(current_priority, static_cast<u32>(processor_id), this);
  379. }
  380. for (u32 core = 0; core < GlobalScheduler::NUM_CPU_CORES; core++) {
  381. if (core != static_cast<u32>(processor_id) && ((affinity_mask >> core) & 1) != 0) {
  382. scheduler.Suggest(current_priority, core, this);
  383. }
  384. }
  385. }
  386. scheduler.SetReselectionPending();
  387. }
  388. void Thread::AdjustSchedulingOnPriority(u32 old_priority) {
  389. if (GetSchedulingStatus() != ThreadSchedStatus::Runnable) {
  390. return;
  391. }
  392. auto& scheduler = Core::System::GetInstance().GlobalScheduler();
  393. if (processor_id >= 0) {
  394. scheduler.Unschedule(old_priority, static_cast<u32>(processor_id), this);
  395. }
  396. for (u32 core = 0; core < GlobalScheduler::NUM_CPU_CORES; core++) {
  397. if (core != static_cast<u32>(processor_id) && ((affinity_mask >> core) & 1) != 0) {
  398. scheduler.Unsuggest(old_priority, core, this);
  399. }
  400. }
  401. // Add thread to the new priority queues.
  402. Thread* current_thread = GetCurrentThread();
  403. if (processor_id >= 0) {
  404. if (current_thread == this) {
  405. scheduler.SchedulePrepend(current_priority, static_cast<u32>(processor_id), this);
  406. } else {
  407. scheduler.Schedule(current_priority, static_cast<u32>(processor_id), this);
  408. }
  409. }
  410. for (u32 core = 0; core < GlobalScheduler::NUM_CPU_CORES; core++) {
  411. if (core != static_cast<u32>(processor_id) && ((affinity_mask >> core) & 1) != 0) {
  412. scheduler.Suggest(current_priority, core, this);
  413. }
  414. }
  415. scheduler.SetReselectionPending();
  416. }
  417. void Thread::AdjustSchedulingOnAffinity(u64 old_affinity_mask, s32 old_core) {
  418. auto& scheduler = Core::System::GetInstance().GlobalScheduler();
  419. if (GetSchedulingStatus() != ThreadSchedStatus::Runnable ||
  420. current_priority >= THREADPRIO_COUNT) {
  421. return;
  422. }
  423. for (u32 core = 0; core < GlobalScheduler::NUM_CPU_CORES; core++) {
  424. if (((old_affinity_mask >> core) & 1) != 0) {
  425. if (core == static_cast<u32>(old_core)) {
  426. scheduler.Unschedule(current_priority, core, this);
  427. } else {
  428. scheduler.Unsuggest(current_priority, core, this);
  429. }
  430. }
  431. }
  432. for (u32 core = 0; core < GlobalScheduler::NUM_CPU_CORES; core++) {
  433. if (((affinity_mask >> core) & 1) != 0) {
  434. if (core == static_cast<u32>(processor_id)) {
  435. scheduler.Schedule(current_priority, core, this);
  436. } else {
  437. scheduler.Suggest(current_priority, core, this);
  438. }
  439. }
  440. }
  441. scheduler.SetReselectionPending();
  442. }
  443. ////////////////////////////////////////////////////////////////////////////////////////////////////
  444. /**
  445. * Gets the current thread
  446. */
  447. Thread* GetCurrentThread() {
  448. return Core::System::GetInstance().CurrentScheduler().GetCurrentThread();
  449. }
  450. } // namespace Kernel