thread.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  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 <vector>
  7. #include <boost/optional.hpp>
  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. const u64 tls_page = (tls_address - Memory::TLS_AREA_VADDR) / Memory::PAGE_SIZE;
  56. const u64 tls_slot =
  57. ((tls_address - Memory::TLS_AREA_VADDR) % Memory::PAGE_SIZE) / Memory::TLS_ENTRY_SIZE;
  58. Core::CurrentProcess()->tls_slots[tls_page].reset(tls_slot);
  59. }
  60. void WaitCurrentThread_Sleep() {
  61. Thread* thread = GetCurrentThread();
  62. thread->status = ThreadStatus::WaitSleep;
  63. }
  64. void ExitCurrentThread() {
  65. Thread* thread = GetCurrentThread();
  66. thread->Stop();
  67. Core::System::GetInstance().CurrentScheduler().RemoveThread(thread);
  68. }
  69. void Thread::WakeAfterDelay(s64 nanoseconds) {
  70. // Don't schedule a wakeup if the thread wants to wait forever
  71. if (nanoseconds == -1)
  72. return;
  73. // This function might be called from any thread so we have to be cautious and use the
  74. // thread-safe version of ScheduleEvent.
  75. CoreTiming::ScheduleEventThreadsafe(CoreTiming::nsToCycles(nanoseconds),
  76. kernel.ThreadWakeupCallbackEventType(), callback_handle);
  77. }
  78. void Thread::CancelWakeupTimer() {
  79. CoreTiming::UnscheduleEventThreadsafe(kernel.ThreadWakeupCallbackEventType(), callback_handle);
  80. }
  81. static boost::optional<s32> GetNextProcessorId(u64 mask) {
  82. for (s32 index = 0; index < Core::NUM_CPU_CORES; ++index) {
  83. if (mask & (1ULL << index)) {
  84. if (!Core::System::GetInstance().Scheduler(index)->GetCurrentThread()) {
  85. // Core is enabled and not running any threads, use this one
  86. return index;
  87. }
  88. }
  89. }
  90. return {};
  91. }
  92. void Thread::ResumeFromWait() {
  93. ASSERT_MSG(wait_objects.empty(), "Thread is waking up while waiting for objects");
  94. switch (status) {
  95. case ThreadStatus::WaitSynchAll:
  96. case ThreadStatus::WaitSynchAny:
  97. case ThreadStatus::WaitHLEEvent:
  98. case ThreadStatus::WaitSleep:
  99. case ThreadStatus::WaitIPC:
  100. case ThreadStatus::WaitMutex:
  101. case ThreadStatus::WaitArb:
  102. break;
  103. case ThreadStatus::Ready:
  104. // The thread's wakeup callback must have already been cleared when the thread was first
  105. // awoken.
  106. ASSERT(wakeup_callback == nullptr);
  107. // If the thread is waiting on multiple wait objects, it might be awoken more than once
  108. // before actually resuming. We can ignore subsequent wakeups if the thread status has
  109. // already been set to ThreadStatus::Ready.
  110. return;
  111. case ThreadStatus::Running:
  112. DEBUG_ASSERT_MSG(false, "Thread with object id {} has already resumed.", GetObjectId());
  113. return;
  114. case ThreadStatus::Dead:
  115. // This should never happen, as threads must complete before being stopped.
  116. DEBUG_ASSERT_MSG(false, "Thread with object id {} cannot be resumed because it's DEAD.",
  117. GetObjectId());
  118. return;
  119. }
  120. wakeup_callback = nullptr;
  121. status = ThreadStatus::Ready;
  122. boost::optional<s32> new_processor_id = GetNextProcessorId(affinity_mask);
  123. if (!new_processor_id) {
  124. new_processor_id = processor_id;
  125. }
  126. if (ideal_core != -1 &&
  127. Core::System::GetInstance().Scheduler(ideal_core)->GetCurrentThread() == nullptr) {
  128. new_processor_id = ideal_core;
  129. }
  130. ASSERT(*new_processor_id < 4);
  131. // Add thread to new core's scheduler
  132. auto& next_scheduler = Core::System::GetInstance().Scheduler(*new_processor_id);
  133. if (*new_processor_id != processor_id) {
  134. // Remove thread from previous core's scheduler
  135. scheduler->RemoveThread(this);
  136. next_scheduler->AddThread(this, current_priority);
  137. }
  138. processor_id = *new_processor_id;
  139. // If the thread was ready, unschedule from the previous core and schedule on the new core
  140. scheduler->UnscheduleThread(this, current_priority);
  141. next_scheduler->ScheduleThread(this, current_priority);
  142. // Change thread's scheduler
  143. scheduler = next_scheduler;
  144. Core::System::GetInstance().CpuCore(processor_id).PrepareReschedule();
  145. }
  146. /**
  147. * Finds a free location for the TLS section of a thread.
  148. * @param tls_slots The TLS page array of the thread's owner process.
  149. * Returns a tuple of (page, slot, alloc_needed) where:
  150. * page: The index of the first allocated TLS page that has free slots.
  151. * slot: The index of the first free slot in the indicated page.
  152. * alloc_needed: Whether there's a need to allocate a new TLS page (All pages are full).
  153. */
  154. static std::tuple<std::size_t, std::size_t, bool> GetFreeThreadLocalSlot(
  155. const std::vector<std::bitset<8>>& tls_slots) {
  156. // Iterate over all the allocated pages, and try to find one where not all slots are used.
  157. for (std::size_t page = 0; page < tls_slots.size(); ++page) {
  158. const auto& page_tls_slots = tls_slots[page];
  159. if (!page_tls_slots.all()) {
  160. // We found a page with at least one free slot, find which slot it is
  161. for (std::size_t slot = 0; slot < page_tls_slots.size(); ++slot) {
  162. if (!page_tls_slots.test(slot)) {
  163. return std::make_tuple(page, slot, false);
  164. }
  165. }
  166. }
  167. }
  168. return std::make_tuple(0, 0, true);
  169. }
  170. /**
  171. * Resets a thread context, making it ready to be scheduled and run by the CPU
  172. * @param context Thread context to reset
  173. * @param stack_top Address of the top of the stack
  174. * @param entry_point Address of entry point for execution
  175. * @param arg User argument for thread
  176. */
  177. static void ResetThreadContext(Core::ARM_Interface::ThreadContext& context, VAddr stack_top,
  178. VAddr entry_point, u64 arg) {
  179. memset(&context, 0, sizeof(Core::ARM_Interface::ThreadContext));
  180. context.cpu_registers[0] = arg;
  181. context.pc = entry_point;
  182. context.sp = stack_top;
  183. context.cpsr = 0;
  184. context.fpscr = 0;
  185. }
  186. ResultVal<SharedPtr<Thread>> Thread::Create(KernelCore& kernel, std::string name, VAddr entry_point,
  187. u32 priority, u64 arg, s32 processor_id,
  188. VAddr stack_top, SharedPtr<Process> owner_process) {
  189. // Check if priority is in ranged. Lowest priority -> highest priority id.
  190. if (priority > THREADPRIO_LOWEST) {
  191. LOG_ERROR(Kernel_SVC, "Invalid thread priority: {}", priority);
  192. return ERR_INVALID_THREAD_PRIORITY;
  193. }
  194. if (processor_id > THREADPROCESSORID_MAX) {
  195. LOG_ERROR(Kernel_SVC, "Invalid processor id: {}", processor_id);
  196. return ERR_INVALID_PROCESSOR_ID;
  197. }
  198. // TODO(yuriks): Other checks, returning 0xD9001BEA
  199. if (!Memory::IsValidVirtualAddress(*owner_process, entry_point)) {
  200. LOG_ERROR(Kernel_SVC, "(name={}): invalid entry {:016X}", name, entry_point);
  201. // TODO (bunnei): Find the correct error code to use here
  202. return ResultCode(-1);
  203. }
  204. SharedPtr<Thread> thread(new Thread(kernel));
  205. thread->thread_id = kernel.CreateNewThreadID();
  206. thread->status = ThreadStatus::Dormant;
  207. thread->entry_point = entry_point;
  208. thread->stack_top = stack_top;
  209. thread->tpidr_el0 = 0;
  210. thread->nominal_priority = thread->current_priority = priority;
  211. thread->last_running_ticks = CoreTiming::GetTicks();
  212. thread->processor_id = processor_id;
  213. thread->ideal_core = processor_id;
  214. thread->affinity_mask = 1ULL << processor_id;
  215. thread->wait_objects.clear();
  216. thread->mutex_wait_address = 0;
  217. thread->condvar_wait_address = 0;
  218. thread->wait_handle = 0;
  219. thread->name = std::move(name);
  220. thread->callback_handle = kernel.ThreadWakeupCallbackHandleTable().Create(thread).Unwrap();
  221. thread->owner_process = owner_process;
  222. thread->scheduler = Core::System::GetInstance().Scheduler(processor_id);
  223. thread->scheduler->AddThread(thread, priority);
  224. // Find the next available TLS index, and mark it as used
  225. auto& tls_slots = owner_process->tls_slots;
  226. auto [available_page, available_slot, needs_allocation] = GetFreeThreadLocalSlot(tls_slots);
  227. if (needs_allocation) {
  228. tls_slots.emplace_back(0); // The page is completely available at the start
  229. available_page = tls_slots.size() - 1;
  230. available_slot = 0; // Use the first slot in the new page
  231. // Allocate some memory from the end of the linear heap for this region.
  232. const size_t offset = thread->tls_memory->size();
  233. thread->tls_memory->insert(thread->tls_memory->end(), Memory::PAGE_SIZE, 0);
  234. auto& vm_manager = owner_process->vm_manager;
  235. vm_manager.RefreshMemoryBlockMappings(thread->tls_memory.get());
  236. vm_manager.MapMemoryBlock(Memory::TLS_AREA_VADDR + available_page * Memory::PAGE_SIZE,
  237. thread->tls_memory, 0, Memory::PAGE_SIZE,
  238. MemoryState::ThreadLocal);
  239. }
  240. // Mark the slot as used
  241. tls_slots[available_page].set(available_slot);
  242. thread->tls_address = Memory::TLS_AREA_VADDR + available_page * Memory::PAGE_SIZE +
  243. available_slot * Memory::TLS_ENTRY_SIZE;
  244. // TODO(peachum): move to ScheduleThread() when scheduler is added so selected core is used
  245. // to initialize the context
  246. ResetThreadContext(thread->context, stack_top, entry_point, arg);
  247. return MakeResult<SharedPtr<Thread>>(std::move(thread));
  248. }
  249. void Thread::SetPriority(u32 priority) {
  250. ASSERT_MSG(priority <= THREADPRIO_LOWEST && priority >= THREADPRIO_HIGHEST,
  251. "Invalid priority value.");
  252. nominal_priority = priority;
  253. UpdatePriority();
  254. }
  255. void Thread::BoostPriority(u32 priority) {
  256. scheduler->SetThreadPriority(this, priority);
  257. current_priority = priority;
  258. }
  259. SharedPtr<Thread> SetupMainThread(KernelCore& kernel, VAddr entry_point, u32 priority,
  260. SharedPtr<Process> owner_process) {
  261. // Setup page table so we can write to memory
  262. SetCurrentPageTable(&Core::CurrentProcess()->vm_manager.page_table);
  263. // Initialize new "main" thread
  264. auto thread_res = Thread::Create(kernel, "main", entry_point, priority, 0, THREADPROCESSORID_0,
  265. Memory::STACK_AREA_VADDR_END, std::move(owner_process));
  266. SharedPtr<Thread> thread = std::move(thread_res).Unwrap();
  267. // Register 1 must be a handle to the main thread
  268. thread->guest_handle = kernel.HandleTable().Create(thread).Unwrap();
  269. thread->context.cpu_registers[1] = thread->guest_handle;
  270. // Threads by default are dormant, wake up the main thread so it runs when the scheduler fires
  271. thread->ResumeFromWait();
  272. return thread;
  273. }
  274. void Thread::SetWaitSynchronizationResult(ResultCode result) {
  275. context.cpu_registers[0] = result.raw;
  276. }
  277. void Thread::SetWaitSynchronizationOutput(s32 output) {
  278. context.cpu_registers[1] = output;
  279. }
  280. s32 Thread::GetWaitObjectIndex(WaitObject* object) const {
  281. ASSERT_MSG(!wait_objects.empty(), "Thread is not waiting for anything");
  282. auto match = std::find(wait_objects.rbegin(), wait_objects.rend(), object);
  283. return static_cast<s32>(std::distance(match, wait_objects.rend()) - 1);
  284. }
  285. VAddr Thread::GetCommandBufferAddress() const {
  286. // Offset from the start of TLS at which the IPC command buffer begins.
  287. static constexpr int CommandHeaderOffset = 0x80;
  288. return GetTLSAddress() + CommandHeaderOffset;
  289. }
  290. void Thread::AddMutexWaiter(SharedPtr<Thread> thread) {
  291. if (thread->lock_owner == this) {
  292. // If the thread is already waiting for this thread to release the mutex, ensure that the
  293. // waiters list is consistent and return without doing anything.
  294. auto itr = std::find(wait_mutex_threads.begin(), wait_mutex_threads.end(), thread);
  295. ASSERT(itr != wait_mutex_threads.end());
  296. return;
  297. }
  298. // A thread can't wait on two different mutexes at the same time.
  299. ASSERT(thread->lock_owner == nullptr);
  300. // Ensure that the thread is not already in the list of mutex waiters
  301. auto itr = std::find(wait_mutex_threads.begin(), wait_mutex_threads.end(), thread);
  302. ASSERT(itr == wait_mutex_threads.end());
  303. thread->lock_owner = this;
  304. wait_mutex_threads.emplace_back(std::move(thread));
  305. UpdatePriority();
  306. }
  307. void Thread::RemoveMutexWaiter(SharedPtr<Thread> thread) {
  308. ASSERT(thread->lock_owner == this);
  309. // Ensure that the thread is in the list of mutex waiters
  310. auto itr = std::find(wait_mutex_threads.begin(), wait_mutex_threads.end(), thread);
  311. ASSERT(itr != wait_mutex_threads.end());
  312. boost::remove_erase(wait_mutex_threads, thread);
  313. thread->lock_owner = nullptr;
  314. UpdatePriority();
  315. }
  316. void Thread::UpdatePriority() {
  317. // Find the highest priority among all the threads that are waiting for this thread's lock
  318. u32 new_priority = nominal_priority;
  319. for (const auto& thread : wait_mutex_threads) {
  320. if (thread->nominal_priority < new_priority)
  321. new_priority = thread->nominal_priority;
  322. }
  323. if (new_priority == current_priority)
  324. return;
  325. scheduler->SetThreadPriority(this, new_priority);
  326. current_priority = new_priority;
  327. // Recursively update the priority of the thread that depends on the priority of this one.
  328. if (lock_owner)
  329. lock_owner->UpdatePriority();
  330. }
  331. void Thread::ChangeCore(u32 core, u64 mask) {
  332. ideal_core = core;
  333. affinity_mask = mask;
  334. if (status != ThreadStatus::Ready) {
  335. return;
  336. }
  337. boost::optional<s32> new_processor_id{GetNextProcessorId(affinity_mask)};
  338. if (!new_processor_id) {
  339. new_processor_id = processor_id;
  340. }
  341. if (ideal_core != -1 &&
  342. Core::System::GetInstance().Scheduler(ideal_core)->GetCurrentThread() == nullptr) {
  343. new_processor_id = ideal_core;
  344. }
  345. ASSERT(*new_processor_id < 4);
  346. // Add thread to new core's scheduler
  347. auto& next_scheduler = Core::System::GetInstance().Scheduler(*new_processor_id);
  348. if (*new_processor_id != processor_id) {
  349. // Remove thread from previous core's scheduler
  350. scheduler->RemoveThread(this);
  351. next_scheduler->AddThread(this, current_priority);
  352. }
  353. processor_id = *new_processor_id;
  354. // If the thread was ready, unschedule from the previous core and schedule on the new core
  355. scheduler->UnscheduleThread(this, current_priority);
  356. next_scheduler->ScheduleThread(this, current_priority);
  357. // Change thread's scheduler
  358. scheduler = next_scheduler;
  359. Core::System::GetInstance().CpuCore(processor_id).PrepareReschedule();
  360. }
  361. ////////////////////////////////////////////////////////////////////////////////////////////////////
  362. /**
  363. * Gets the current thread
  364. */
  365. Thread* GetCurrentThread() {
  366. return Core::System::GetInstance().CurrentScheduler().GetCurrentThread();
  367. }
  368. } // namespace Kernel