thread.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  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 <boost/range/algorithm_ext/erase.hpp>
  9. #include "common/assert.h"
  10. #include "common/common_types.h"
  11. #include "common/logging/log.h"
  12. #include "common/math_util.h"
  13. #include "common/thread_queue_list.h"
  14. #include "core/arm/arm_interface.h"
  15. #include "core/core.h"
  16. #include "core/core_cpu.h"
  17. #include "core/core_timing.h"
  18. #include "core/core_timing_util.h"
  19. #include "core/hle/kernel/errors.h"
  20. #include "core/hle/kernel/handle_table.h"
  21. #include "core/hle/kernel/kernel.h"
  22. #include "core/hle/kernel/object.h"
  23. #include "core/hle/kernel/process.h"
  24. #include "core/hle/kernel/scheduler.h"
  25. #include "core/hle/kernel/thread.h"
  26. #include "core/hle/result.h"
  27. #include "core/memory.h"
  28. namespace Kernel {
  29. bool Thread::ShouldWait(Thread* thread) const {
  30. return status != ThreadStatus::Dead;
  31. }
  32. void Thread::Acquire(Thread* thread) {
  33. ASSERT_MSG(!ShouldWait(thread), "object unavailable!");
  34. }
  35. Thread::Thread(KernelCore& kernel) : WaitObject{kernel} {}
  36. Thread::~Thread() = default;
  37. void Thread::Stop() {
  38. // Cancel any outstanding wakeup events for this thread
  39. CoreTiming::UnscheduleEvent(kernel.ThreadWakeupCallbackEventType(), callback_handle);
  40. kernel.ThreadWakeupCallbackHandleTable().Close(callback_handle);
  41. callback_handle = 0;
  42. // Clean up thread from ready queue
  43. // This is only needed when the thread is terminated forcefully (SVC TerminateProcess)
  44. if (status == ThreadStatus::Ready) {
  45. scheduler->UnscheduleThread(this, current_priority);
  46. }
  47. status = ThreadStatus::Dead;
  48. WakeupAllWaitingThreads();
  49. // Clean up any dangling references in objects that this thread was waiting for
  50. for (auto& wait_object : wait_objects) {
  51. wait_object->RemoveWaitingThread(this);
  52. }
  53. wait_objects.clear();
  54. // Mark the TLS slot in the thread's page as free.
  55. owner_process->FreeTLSSlot(tls_address);
  56. }
  57. void WaitCurrentThread_Sleep() {
  58. Thread* thread = GetCurrentThread();
  59. thread->SetStatus(ThreadStatus::WaitSleep);
  60. }
  61. void ExitCurrentThread() {
  62. Thread* thread = GetCurrentThread();
  63. thread->Stop();
  64. Core::System::GetInstance().CurrentScheduler().RemoveThread(thread);
  65. }
  66. void Thread::WakeAfterDelay(s64 nanoseconds) {
  67. // Don't schedule a wakeup if the thread wants to wait forever
  68. if (nanoseconds == -1)
  69. return;
  70. // This function might be called from any thread so we have to be cautious and use the
  71. // thread-safe version of ScheduleEvent.
  72. CoreTiming::ScheduleEventThreadsafe(CoreTiming::nsToCycles(nanoseconds),
  73. kernel.ThreadWakeupCallbackEventType(), callback_handle);
  74. }
  75. void Thread::CancelWakeupTimer() {
  76. CoreTiming::UnscheduleEventThreadsafe(kernel.ThreadWakeupCallbackEventType(), callback_handle);
  77. }
  78. static std::optional<s32> GetNextProcessorId(u64 mask) {
  79. for (s32 index = 0; index < Core::NUM_CPU_CORES; ++index) {
  80. if (mask & (1ULL << index)) {
  81. if (!Core::System::GetInstance().Scheduler(index).GetCurrentThread()) {
  82. // Core is enabled and not running any threads, use this one
  83. return index;
  84. }
  85. }
  86. }
  87. return {};
  88. }
  89. void Thread::ResumeFromWait() {
  90. ASSERT_MSG(wait_objects.empty(), "Thread is waking up while waiting for objects");
  91. switch (status) {
  92. case ThreadStatus::WaitSynchAll:
  93. case ThreadStatus::WaitSynchAny:
  94. case ThreadStatus::WaitHLEEvent:
  95. case ThreadStatus::WaitSleep:
  96. case ThreadStatus::WaitIPC:
  97. case ThreadStatus::WaitMutex:
  98. case ThreadStatus::WaitArb:
  99. break;
  100. case ThreadStatus::Ready:
  101. // The thread's wakeup callback must have already been cleared when the thread was first
  102. // awoken.
  103. ASSERT(wakeup_callback == nullptr);
  104. // If the thread is waiting on multiple wait objects, it might be awoken more than once
  105. // before actually resuming. We can ignore subsequent wakeups if the thread status has
  106. // already been set to ThreadStatus::Ready.
  107. return;
  108. case ThreadStatus::Running:
  109. DEBUG_ASSERT_MSG(false, "Thread with object id {} has already resumed.", GetObjectId());
  110. return;
  111. case ThreadStatus::Dead:
  112. // This should never happen, as threads must complete before being stopped.
  113. DEBUG_ASSERT_MSG(false, "Thread with object id {} cannot be resumed because it's DEAD.",
  114. GetObjectId());
  115. return;
  116. }
  117. wakeup_callback = nullptr;
  118. status = ThreadStatus::Ready;
  119. ChangeScheduler();
  120. }
  121. /**
  122. * Resets a thread context, making it ready to be scheduled and run by the CPU
  123. * @param context Thread context to reset
  124. * @param stack_top Address of the top of the stack
  125. * @param entry_point Address of entry point for execution
  126. * @param arg User argument for thread
  127. */
  128. static void ResetThreadContext(Core::ARM_Interface::ThreadContext& context, VAddr stack_top,
  129. VAddr entry_point, u64 arg) {
  130. context = {};
  131. context.cpu_registers[0] = arg;
  132. context.pc = entry_point;
  133. context.sp = stack_top;
  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. // TODO(yuriks): Other checks, returning 0xD9001BEA
  148. if (!Memory::IsValidVirtualAddress(owner_process, entry_point)) {
  149. LOG_ERROR(Kernel_SVC, "(name={}): invalid entry {:016X}", name, entry_point);
  150. // TODO (bunnei): Find the correct error code to use here
  151. return ResultCode(-1);
  152. }
  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 = 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 = &Core::System::GetInstance().Scheduler(processor_id);
  172. thread->scheduler->AddThread(thread, priority);
  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. SharedPtr<Thread> SetupMainThread(KernelCore& kernel, VAddr entry_point, u32 priority,
  190. Process& owner_process) {
  191. // Setup page table so we can write to memory
  192. SetCurrentPageTable(&owner_process.VMManager().page_table);
  193. // Initialize new "main" thread
  194. const VAddr stack_top = owner_process.VMManager().GetTLSIORegionEndAddress();
  195. auto thread_res = Thread::Create(kernel, "main", entry_point, priority, 0, THREADPROCESSORID_0,
  196. stack_top, owner_process);
  197. SharedPtr<Thread> thread = std::move(thread_res).Unwrap();
  198. // Register 1 must be a handle to the main thread
  199. const Handle guest_handle = owner_process.GetHandleTable().Create(thread).Unwrap();
  200. thread->SetGuestHandle(guest_handle);
  201. thread->GetContext().cpu_registers[1] = guest_handle;
  202. // Threads by default are dormant, wake up the main thread so it runs when the scheduler fires
  203. thread->ResumeFromWait();
  204. return thread;
  205. }
  206. void Thread::SetWaitSynchronizationResult(ResultCode result) {
  207. context.cpu_registers[0] = result.raw;
  208. }
  209. void Thread::SetWaitSynchronizationOutput(s32 output) {
  210. context.cpu_registers[1] = output;
  211. }
  212. s32 Thread::GetWaitObjectIndex(WaitObject* object) const {
  213. ASSERT_MSG(!wait_objects.empty(), "Thread is not waiting for anything");
  214. auto match = std::find(wait_objects.rbegin(), wait_objects.rend(), object);
  215. return static_cast<s32>(std::distance(match, wait_objects.rend()) - 1);
  216. }
  217. VAddr Thread::GetCommandBufferAddress() const {
  218. // Offset from the start of TLS at which the IPC command buffer begins.
  219. static constexpr int CommandHeaderOffset = 0x80;
  220. return GetTLSAddress() + CommandHeaderOffset;
  221. }
  222. void Thread::SetStatus(ThreadStatus new_status) {
  223. if (new_status == status) {
  224. return;
  225. }
  226. if (status == ThreadStatus::Running) {
  227. last_running_ticks = CoreTiming::GetTicks();
  228. }
  229. status = new_status;
  230. }
  231. void Thread::AddMutexWaiter(SharedPtr<Thread> thread) {
  232. if (thread->lock_owner == this) {
  233. // If the thread is already waiting for this thread to release the mutex, ensure that the
  234. // waiters list is consistent and return without doing anything.
  235. auto itr = std::find(wait_mutex_threads.begin(), wait_mutex_threads.end(), thread);
  236. ASSERT(itr != wait_mutex_threads.end());
  237. return;
  238. }
  239. // A thread can't wait on two different mutexes at the same time.
  240. ASSERT(thread->lock_owner == nullptr);
  241. // Ensure that the thread is not already in the list of mutex waiters
  242. auto itr = std::find(wait_mutex_threads.begin(), wait_mutex_threads.end(), thread);
  243. ASSERT(itr == wait_mutex_threads.end());
  244. thread->lock_owner = this;
  245. wait_mutex_threads.emplace_back(std::move(thread));
  246. UpdatePriority();
  247. }
  248. void Thread::RemoveMutexWaiter(SharedPtr<Thread> thread) {
  249. ASSERT(thread->lock_owner == this);
  250. // Ensure that the thread is in the list of mutex waiters
  251. auto itr = std::find(wait_mutex_threads.begin(), wait_mutex_threads.end(), thread);
  252. ASSERT(itr != wait_mutex_threads.end());
  253. boost::remove_erase(wait_mutex_threads, thread);
  254. thread->lock_owner = nullptr;
  255. UpdatePriority();
  256. }
  257. void Thread::UpdatePriority() {
  258. // Find the highest priority among all the threads that are waiting for this thread's lock
  259. u32 new_priority = nominal_priority;
  260. for (const auto& thread : wait_mutex_threads) {
  261. if (thread->nominal_priority < new_priority)
  262. new_priority = thread->nominal_priority;
  263. }
  264. if (new_priority == current_priority)
  265. return;
  266. scheduler->SetThreadPriority(this, new_priority);
  267. current_priority = new_priority;
  268. // Recursively update the priority of the thread that depends on the priority of this one.
  269. if (lock_owner)
  270. lock_owner->UpdatePriority();
  271. }
  272. void Thread::ChangeCore(u32 core, u64 mask) {
  273. ideal_core = core;
  274. affinity_mask = mask;
  275. ChangeScheduler();
  276. }
  277. void Thread::ChangeScheduler() {
  278. if (status != ThreadStatus::Ready) {
  279. return;
  280. }
  281. auto& system = Core::System::GetInstance();
  282. std::optional<s32> new_processor_id{GetNextProcessorId(affinity_mask)};
  283. if (!new_processor_id) {
  284. new_processor_id = processor_id;
  285. }
  286. if (ideal_core != -1 && system.Scheduler(ideal_core).GetCurrentThread() == nullptr) {
  287. new_processor_id = ideal_core;
  288. }
  289. ASSERT(*new_processor_id < 4);
  290. // Add thread to new core's scheduler
  291. auto& next_scheduler = system.Scheduler(*new_processor_id);
  292. if (*new_processor_id != processor_id) {
  293. // Remove thread from previous core's scheduler
  294. scheduler->RemoveThread(this);
  295. next_scheduler.AddThread(this, current_priority);
  296. }
  297. processor_id = *new_processor_id;
  298. // If the thread was ready, unschedule from the previous core and schedule on the new core
  299. scheduler->UnscheduleThread(this, current_priority);
  300. next_scheduler.ScheduleThread(this, current_priority);
  301. // Change thread's scheduler
  302. scheduler = &next_scheduler;
  303. system.CpuCore(processor_id).PrepareReschedule();
  304. }
  305. bool Thread::AllWaitObjectsReady() {
  306. return std::none_of(
  307. wait_objects.begin(), wait_objects.end(),
  308. [this](const SharedPtr<WaitObject>& object) { return object->ShouldWait(this); });
  309. }
  310. bool Thread::InvokeWakeupCallback(ThreadWakeupReason reason, SharedPtr<Thread> thread,
  311. SharedPtr<WaitObject> object, std::size_t index) {
  312. ASSERT(wakeup_callback);
  313. return wakeup_callback(reason, std::move(thread), std::move(object), index);
  314. }
  315. void Thread::YieldNormal() {
  316. // Avoid yielding if the thread isn't even running.
  317. if (status != ThreadStatus::Running) {
  318. return;
  319. }
  320. if (nominal_priority < THREADPRIO_COUNT) {
  321. scheduler->RescheduleThread(this, nominal_priority);
  322. scheduler->Reschedule();
  323. }
  324. }
  325. void Thread::YieldWithLoadBalancing() {
  326. auto priority = nominal_priority;
  327. auto core = processor_id;
  328. // Avoid yielding if the thread isn't even running.
  329. if (status != ThreadStatus::Running) {
  330. Core::System::GetInstance().CpuCore(processor_id).PrepareReschedule();
  331. return;
  332. }
  333. SharedPtr<Thread> next;
  334. const auto& threads = scheduler->GetThreadList();
  335. if (priority < THREADPRIO_COUNT) {
  336. // Reschedule thread to end of queue.
  337. scheduler->RescheduleThread(this, priority);
  338. const auto iter = std::find_if(threads.begin(), threads.end(),
  339. [&priority](const SharedPtr<Thread>& thread) {
  340. return thread->GetNominalPriority() == priority;
  341. });
  342. if (iter != threads.end())
  343. next = iter->get();
  344. }
  345. Thread* suggested_thread = nullptr;
  346. for (int i = 0; i < 4; ++i) {
  347. if (i == core)
  348. continue;
  349. const auto res =
  350. Core::System::GetInstance().CpuCore(i).Scheduler().GetNextSuggestedThread(core);
  351. if (res != nullptr) {
  352. suggested_thread = res;
  353. break;
  354. }
  355. }
  356. if (suggested_thread != nullptr)
  357. suggested_thread->ChangeCore(core, suggested_thread->GetAffinityMask());
  358. }
  359. void Thread::YieldAndWaitForLoadBalancing() {
  360. UNIMPLEMENTED_MSG("Wait for load balancing thread yield type is not implemented!");
  361. }
  362. ////////////////////////////////////////////////////////////////////////////////////////////////////
  363. /**
  364. * Gets the current thread
  365. */
  366. Thread* GetCurrentThread() {
  367. return Core::System::GetInstance().CurrentScheduler().GetCurrentThread();
  368. }
  369. } // namespace Kernel