thread.cpp 19 KB

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