thread.cpp 14 KB

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