thread.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  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(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. // Clean up thread from ready queue
  42. // This is only needed when the thread is terminated forcefully (SVC TerminateProcess)
  43. if (status == ThreadStatus::Ready || status == ThreadStatus::Paused) {
  44. scheduler->UnscheduleThread(this, current_priority);
  45. }
  46. status = ThreadStatus::Dead;
  47. WakeupAllWaitingThreads();
  48. // Clean up any dangling references in objects that this thread was waiting for
  49. for (auto& wait_object : wait_objects) {
  50. wait_object->RemoveWaitingThread(this);
  51. }
  52. wait_objects.clear();
  53. // Mark the TLS slot in the thread's page as free.
  54. owner_process->FreeTLSSlot(tls_address);
  55. }
  56. void WaitCurrentThread_Sleep() {
  57. Thread* thread = GetCurrentThread();
  58. thread->SetStatus(ThreadStatus::WaitSleep);
  59. }
  60. void ExitCurrentThread() {
  61. Thread* thread = GetCurrentThread();
  62. thread->Stop();
  63. Core::System::GetInstance().CurrentScheduler().RemoveThread(thread);
  64. }
  65. void Thread::WakeAfterDelay(s64 nanoseconds) {
  66. // Don't schedule a wakeup if the thread wants to wait forever
  67. if (nanoseconds == -1)
  68. return;
  69. // This function might be called from any thread so we have to be cautious and use the
  70. // thread-safe version of ScheduleEvent.
  71. Core::System::GetInstance().CoreTiming().ScheduleEventThreadsafe(
  72. Core::Timing::nsToCycles(nanoseconds), kernel.ThreadWakeupCallbackEventType(),
  73. callback_handle);
  74. }
  75. void Thread::CancelWakeupTimer() {
  76. Core::System::GetInstance().CoreTiming().UnscheduleEventThreadsafe(
  77. kernel.ThreadWakeupCallbackEventType(), callback_handle);
  78. }
  79. static std::optional<s32> GetNextProcessorId(u64 mask) {
  80. for (s32 index = 0; index < Core::NUM_CPU_CORES; ++index) {
  81. if (mask & (1ULL << index)) {
  82. if (!Core::System::GetInstance().Scheduler(index).GetCurrentThread()) {
  83. // Core is enabled and not running any threads, use this one
  84. return index;
  85. }
  86. }
  87. }
  88. return {};
  89. }
  90. void Thread::ResumeFromWait() {
  91. ASSERT_MSG(wait_objects.empty(), "Thread is waking up while waiting for objects");
  92. switch (status) {
  93. case ThreadStatus::WaitSynchAll:
  94. case ThreadStatus::WaitSynchAny:
  95. case ThreadStatus::WaitHLEEvent:
  96. case ThreadStatus::WaitSleep:
  97. case ThreadStatus::WaitIPC:
  98. case ThreadStatus::WaitMutex:
  99. case ThreadStatus::WaitArb:
  100. break;
  101. case ThreadStatus::Ready:
  102. // The thread's wakeup callback must have already been cleared when the thread was first
  103. // awoken.
  104. ASSERT(wakeup_callback == nullptr);
  105. // If the thread is waiting on multiple wait objects, it might be awoken more than once
  106. // before actually resuming. We can ignore subsequent wakeups if the thread status has
  107. // already been set to ThreadStatus::Ready.
  108. return;
  109. case ThreadStatus::Running:
  110. DEBUG_ASSERT_MSG(false, "Thread with object id {} has already resumed.", GetObjectId());
  111. return;
  112. case ThreadStatus::Dead:
  113. // This should never happen, as threads must complete before being stopped.
  114. DEBUG_ASSERT_MSG(false, "Thread with object id {} cannot be resumed because it's DEAD.",
  115. GetObjectId());
  116. return;
  117. }
  118. wakeup_callback = nullptr;
  119. if (activity == ThreadActivity::Paused) {
  120. status = ThreadStatus::Paused;
  121. return;
  122. }
  123. status = ThreadStatus::Ready;
  124. ChangeScheduler();
  125. }
  126. /**
  127. * Resets a thread context, making it ready to be scheduled and run by the CPU
  128. * @param context Thread context to reset
  129. * @param stack_top Address of the top of the stack
  130. * @param entry_point Address of entry point for execution
  131. * @param arg User argument for thread
  132. */
  133. static void ResetThreadContext(Core::ARM_Interface::ThreadContext& 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. // AHP = 0, DN = 1, FTZ = 1, RMode = Round towards zero
  141. context.fpcr = 0x03C00000;
  142. }
  143. ResultVal<SharedPtr<Thread>> Thread::Create(KernelCore& kernel, std::string name, VAddr entry_point,
  144. u32 priority, u64 arg, s32 processor_id,
  145. VAddr stack_top, Process& owner_process) {
  146. // Check if priority is in ranged. Lowest priority -> highest priority id.
  147. if (priority > THREADPRIO_LOWEST) {
  148. LOG_ERROR(Kernel_SVC, "Invalid thread priority: {}", priority);
  149. return ERR_INVALID_THREAD_PRIORITY;
  150. }
  151. if (processor_id > THREADPROCESSORID_MAX) {
  152. LOG_ERROR(Kernel_SVC, "Invalid processor id: {}", processor_id);
  153. return ERR_INVALID_PROCESSOR_ID;
  154. }
  155. if (!Memory::IsValidVirtualAddress(owner_process, entry_point)) {
  156. LOG_ERROR(Kernel_SVC, "(name={}): invalid entry {:016X}", name, entry_point);
  157. // TODO (bunnei): Find the correct error code to use here
  158. return ResultCode(-1);
  159. }
  160. auto& system = Core::System::GetInstance();
  161. SharedPtr<Thread> thread(new Thread(kernel));
  162. thread->thread_id = kernel.CreateNewThreadID();
  163. thread->status = ThreadStatus::Dormant;
  164. thread->entry_point = entry_point;
  165. thread->stack_top = stack_top;
  166. thread->tpidr_el0 = 0;
  167. thread->nominal_priority = thread->current_priority = priority;
  168. thread->last_running_ticks = system.CoreTiming().GetTicks();
  169. thread->processor_id = processor_id;
  170. thread->ideal_core = processor_id;
  171. thread->affinity_mask = 1ULL << processor_id;
  172. thread->wait_objects.clear();
  173. thread->mutex_wait_address = 0;
  174. thread->condvar_wait_address = 0;
  175. thread->wait_handle = 0;
  176. thread->name = std::move(name);
  177. thread->callback_handle = kernel.ThreadWakeupCallbackHandleTable().Create(thread).Unwrap();
  178. thread->owner_process = &owner_process;
  179. thread->scheduler = &system.Scheduler(processor_id);
  180. thread->scheduler->AddThread(thread, priority);
  181. thread->tls_address = thread->owner_process->MarkNextAvailableTLSSlotAsUsed(*thread);
  182. // TODO(peachum): move to ScheduleThread() when scheduler is added so selected core is used
  183. // to initialize the context
  184. ResetThreadContext(thread->context, stack_top, entry_point, arg);
  185. return MakeResult<SharedPtr<Thread>>(std::move(thread));
  186. }
  187. void Thread::SetPriority(u32 priority) {
  188. ASSERT_MSG(priority <= THREADPRIO_LOWEST && priority >= THREADPRIO_HIGHEST,
  189. "Invalid priority value.");
  190. nominal_priority = priority;
  191. UpdatePriority();
  192. }
  193. void Thread::BoostPriority(u32 priority) {
  194. scheduler->SetThreadPriority(this, priority);
  195. current_priority = priority;
  196. }
  197. void Thread::SetWaitSynchronizationResult(ResultCode result) {
  198. context.cpu_registers[0] = result.raw;
  199. }
  200. void Thread::SetWaitSynchronizationOutput(s32 output) {
  201. context.cpu_registers[1] = output;
  202. }
  203. s32 Thread::GetWaitObjectIndex(WaitObject* object) const {
  204. ASSERT_MSG(!wait_objects.empty(), "Thread is not waiting for anything");
  205. auto match = std::find(wait_objects.rbegin(), wait_objects.rend(), object);
  206. return static_cast<s32>(std::distance(match, wait_objects.rend()) - 1);
  207. }
  208. VAddr Thread::GetCommandBufferAddress() const {
  209. // Offset from the start of TLS at which the IPC command buffer begins.
  210. static constexpr int CommandHeaderOffset = 0x80;
  211. return GetTLSAddress() + CommandHeaderOffset;
  212. }
  213. void Thread::SetStatus(ThreadStatus new_status) {
  214. if (new_status == status) {
  215. return;
  216. }
  217. if (status == ThreadStatus::Running) {
  218. last_running_ticks = Core::System::GetInstance().CoreTiming().GetTicks();
  219. }
  220. status = new_status;
  221. }
  222. void Thread::AddMutexWaiter(SharedPtr<Thread> thread) {
  223. if (thread->lock_owner == this) {
  224. // If the thread is already waiting for this thread to release the mutex, ensure that the
  225. // waiters list is consistent and return without doing anything.
  226. const auto iter = std::find(wait_mutex_threads.begin(), wait_mutex_threads.end(), thread);
  227. ASSERT(iter != wait_mutex_threads.end());
  228. return;
  229. }
  230. // A thread can't wait on two different mutexes at the same time.
  231. ASSERT(thread->lock_owner == nullptr);
  232. // Ensure that the thread is not already in the list of mutex waiters
  233. const auto iter = std::find(wait_mutex_threads.begin(), wait_mutex_threads.end(), thread);
  234. ASSERT(iter == wait_mutex_threads.end());
  235. // Keep the list in an ordered fashion
  236. const auto insertion_point = std::find_if(
  237. wait_mutex_threads.begin(), wait_mutex_threads.end(),
  238. [&thread](const auto& entry) { return entry->GetPriority() > thread->GetPriority(); });
  239. wait_mutex_threads.insert(insertion_point, thread);
  240. thread->lock_owner = this;
  241. UpdatePriority();
  242. }
  243. void Thread::RemoveMutexWaiter(SharedPtr<Thread> thread) {
  244. ASSERT(thread->lock_owner == this);
  245. // Ensure that the thread is in the list of mutex waiters
  246. const auto iter = std::find(wait_mutex_threads.begin(), wait_mutex_threads.end(), thread);
  247. ASSERT(iter != wait_mutex_threads.end());
  248. wait_mutex_threads.erase(iter);
  249. thread->lock_owner = nullptr;
  250. UpdatePriority();
  251. }
  252. void Thread::UpdatePriority() {
  253. // If any of the threads waiting on the mutex have a higher priority
  254. // (taking into account priority inheritance), then this thread inherits
  255. // that thread's priority.
  256. u32 new_priority = nominal_priority;
  257. if (!wait_mutex_threads.empty()) {
  258. if (wait_mutex_threads.front()->current_priority < new_priority) {
  259. new_priority = wait_mutex_threads.front()->current_priority;
  260. }
  261. }
  262. if (new_priority == current_priority) {
  263. return;
  264. }
  265. scheduler->SetThreadPriority(this, new_priority);
  266. current_priority = new_priority;
  267. if (!lock_owner) {
  268. return;
  269. }
  270. // Ensure that the thread is within the correct location in the waiting list.
  271. lock_owner->RemoveMutexWaiter(this);
  272. lock_owner->AddMutexWaiter(this);
  273. // Recursively update the priority of the thread that depends on the priority of this one.
  274. lock_owner->UpdatePriority();
  275. }
  276. void Thread::ChangeCore(u32 core, u64 mask) {
  277. ideal_core = core;
  278. affinity_mask = mask;
  279. ChangeScheduler();
  280. }
  281. void Thread::ChangeScheduler() {
  282. if (status != ThreadStatus::Ready) {
  283. return;
  284. }
  285. auto& system = Core::System::GetInstance();
  286. std::optional<s32> new_processor_id{GetNextProcessorId(affinity_mask)};
  287. if (!new_processor_id) {
  288. new_processor_id = processor_id;
  289. }
  290. if (ideal_core != -1 && system.Scheduler(ideal_core).GetCurrentThread() == nullptr) {
  291. new_processor_id = ideal_core;
  292. }
  293. ASSERT(*new_processor_id < 4);
  294. // Add thread to new core's scheduler
  295. auto& next_scheduler = system.Scheduler(*new_processor_id);
  296. if (*new_processor_id != processor_id) {
  297. // Remove thread from previous core's scheduler
  298. scheduler->RemoveThread(this);
  299. next_scheduler.AddThread(this, current_priority);
  300. }
  301. processor_id = *new_processor_id;
  302. // If the thread was ready, unschedule from the previous core and schedule on the new core
  303. scheduler->UnscheduleThread(this, current_priority);
  304. next_scheduler.ScheduleThread(this, current_priority);
  305. // Change thread's scheduler
  306. scheduler = &next_scheduler;
  307. system.CpuCore(processor_id).PrepareReschedule();
  308. }
  309. bool Thread::AllWaitObjectsReady() {
  310. return std::none_of(
  311. wait_objects.begin(), wait_objects.end(),
  312. [this](const SharedPtr<WaitObject>& object) { return object->ShouldWait(this); });
  313. }
  314. bool Thread::InvokeWakeupCallback(ThreadWakeupReason reason, SharedPtr<Thread> thread,
  315. SharedPtr<WaitObject> object, std::size_t index) {
  316. ASSERT(wakeup_callback);
  317. return wakeup_callback(reason, std::move(thread), std::move(object), index);
  318. }
  319. void Thread::SetActivity(ThreadActivity value) {
  320. activity = value;
  321. if (value == ThreadActivity::Paused) {
  322. // Set status if not waiting
  323. if (status == ThreadStatus::Ready) {
  324. status = ThreadStatus::Paused;
  325. } else if (status == ThreadStatus::Running) {
  326. status = ThreadStatus::Paused;
  327. Core::System::GetInstance().CpuCore(processor_id).PrepareReschedule();
  328. }
  329. } else if (status == ThreadStatus::Paused) {
  330. // Ready to reschedule
  331. ResumeFromWait();
  332. }
  333. }
  334. ////////////////////////////////////////////////////////////////////////////////////////////////////
  335. /**
  336. * Gets the current thread
  337. */
  338. Thread* GetCurrentThread() {
  339. return Core::System::GetInstance().CurrentScheduler().GetCurrentThread();
  340. }
  341. } // namespace Kernel