thread.cpp 19 KB

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