thread.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  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 <list>
  7. #include <vector>
  8. #include "common/assert.h"
  9. #include "common/common_types.h"
  10. #include "common/logging/log.h"
  11. #include "common/math_util.h"
  12. #include "common/thread_queue_list.h"
  13. #include "core/arm/arm_interface.h"
  14. #include "core/core.h"
  15. #include "core/core_timing.h"
  16. #include "core/hle/kernel/errors.h"
  17. #include "core/hle/kernel/handle_table.h"
  18. #include "core/hle/kernel/kernel.h"
  19. #include "core/hle/kernel/memory.h"
  20. #include "core/hle/kernel/mutex.h"
  21. #include "core/hle/kernel/process.h"
  22. #include "core/hle/kernel/thread.h"
  23. #include "core/hle/result.h"
  24. #include "core/memory.h"
  25. namespace Kernel {
  26. /// Event type for the thread wake up event
  27. static CoreTiming::EventType* ThreadWakeupEventType = nullptr;
  28. bool Thread::ShouldWait(Thread* thread) const {
  29. return status != THREADSTATUS_DEAD;
  30. }
  31. void Thread::Acquire(Thread* thread) {
  32. ASSERT_MSG(!ShouldWait(thread), "object unavailable!");
  33. }
  34. // TODO(yuriks): This can be removed if Thread objects are explicitly pooled in the future, allowing
  35. // us to simply use a pool index or similar.
  36. static Kernel::HandleTable wakeup_callback_handle_table;
  37. // The first available thread id at startup
  38. static u32 next_thread_id;
  39. /**
  40. * Creates a new thread ID
  41. * @return The new thread ID
  42. */
  43. inline static u32 const NewThreadId() {
  44. return next_thread_id++;
  45. }
  46. Thread::Thread() {}
  47. Thread::~Thread() {}
  48. /**
  49. * Check if the specified thread is waiting on the specified address to be arbitrated
  50. * @param thread The thread to test
  51. * @param wait_address The address to test against
  52. * @return True if the thread is waiting, false otherwise
  53. */
  54. static bool CheckWait_AddressArbiter(const Thread* thread, VAddr wait_address) {
  55. return thread->status == THREADSTATUS_WAIT_ARB && wait_address == thread->wait_address;
  56. }
  57. void Thread::Stop() {
  58. // Cancel any outstanding wakeup events for this thread
  59. CoreTiming::UnscheduleEvent(ThreadWakeupEventType, callback_handle);
  60. wakeup_callback_handle_table.Close(callback_handle);
  61. callback_handle = 0;
  62. // Clean up thread from ready queue
  63. // This is only needed when the thread is termintated forcefully (SVC TerminateProcess)
  64. if (status == THREADSTATUS_READY) {
  65. Core::System::GetInstance().Scheduler().UnscheduleThread(this, current_priority);
  66. }
  67. status = THREADSTATUS_DEAD;
  68. WakeupAllWaitingThreads();
  69. // Clean up any dangling references in objects that this thread was waiting for
  70. for (auto& wait_object : wait_objects) {
  71. wait_object->RemoveWaitingThread(this);
  72. }
  73. wait_objects.clear();
  74. // Release all the mutexes that this thread holds
  75. ReleaseThreadMutexes(this);
  76. // Mark the TLS slot in the thread's page as free.
  77. u64 tls_page = (tls_address - Memory::TLS_AREA_VADDR) / Memory::PAGE_SIZE;
  78. u64 tls_slot =
  79. ((tls_address - Memory::TLS_AREA_VADDR) % Memory::PAGE_SIZE) / Memory::TLS_ENTRY_SIZE;
  80. Kernel::g_current_process->tls_slots[tls_page].reset(tls_slot);
  81. }
  82. void WaitCurrentThread_Sleep() {
  83. Thread* thread = GetCurrentThread();
  84. thread->status = THREADSTATUS_WAIT_SLEEP;
  85. }
  86. void WaitCurrentThread_ArbitrateAddress(VAddr wait_address) {
  87. Thread* thread = GetCurrentThread();
  88. thread->wait_address = wait_address;
  89. thread->status = THREADSTATUS_WAIT_ARB;
  90. }
  91. void ExitCurrentThread() {
  92. Thread* thread = GetCurrentThread();
  93. thread->Stop();
  94. Core::System::GetInstance().Scheduler().RemoveThread(thread);
  95. }
  96. /**
  97. * Callback that will wake up the thread it was scheduled for
  98. * @param thread_handle The handle of the thread that's been awoken
  99. * @param cycles_late The number of CPU cycles that have passed since the desired wakeup time
  100. */
  101. static void ThreadWakeupCallback(u64 thread_handle, int cycles_late) {
  102. SharedPtr<Thread> thread = wakeup_callback_handle_table.Get<Thread>((Handle)thread_handle);
  103. if (thread == nullptr) {
  104. LOG_CRITICAL(Kernel, "Callback fired for invalid thread %08X", (Handle)thread_handle);
  105. return;
  106. }
  107. bool resume = true;
  108. if (thread->status == THREADSTATUS_WAIT_SYNCH_ANY ||
  109. thread->status == THREADSTATUS_WAIT_SYNCH_ALL || thread->status == THREADSTATUS_WAIT_ARB) {
  110. // Remove the thread from each of its waiting objects' waitlists
  111. for (auto& object : thread->wait_objects)
  112. object->RemoveWaitingThread(thread.get());
  113. thread->wait_objects.clear();
  114. // Invoke the wakeup callback before clearing the wait objects
  115. if (thread->wakeup_callback)
  116. resume = thread->wakeup_callback(ThreadWakeupReason::Timeout, thread, nullptr, 0);
  117. }
  118. if (resume)
  119. thread->ResumeFromWait();
  120. }
  121. void Thread::WakeAfterDelay(s64 nanoseconds) {
  122. // Don't schedule a wakeup if the thread wants to wait forever
  123. if (nanoseconds == -1)
  124. return;
  125. CoreTiming::ScheduleEvent(nsToCycles(nanoseconds), ThreadWakeupEventType, callback_handle);
  126. }
  127. void Thread::CancelWakeupTimer() {
  128. CoreTiming::UnscheduleEvent(ThreadWakeupEventType, callback_handle);
  129. }
  130. void Thread::ResumeFromWait() {
  131. ASSERT_MSG(wait_objects.empty(), "Thread is waking up while waiting for objects");
  132. switch (status) {
  133. case THREADSTATUS_WAIT_SYNCH_ALL:
  134. case THREADSTATUS_WAIT_SYNCH_ANY:
  135. case THREADSTATUS_WAIT_ARB:
  136. case THREADSTATUS_WAIT_SLEEP:
  137. case THREADSTATUS_WAIT_IPC:
  138. break;
  139. case THREADSTATUS_READY:
  140. // The thread's wakeup callback must have already been cleared when the thread was first
  141. // awoken.
  142. ASSERT(wakeup_callback == nullptr);
  143. // If the thread is waiting on multiple wait objects, it might be awoken more than once
  144. // before actually resuming. We can ignore subsequent wakeups if the thread status has
  145. // already been set to THREADSTATUS_READY.
  146. return;
  147. case THREADSTATUS_RUNNING:
  148. DEBUG_ASSERT_MSG(false, "Thread with object id %u has already resumed.", GetObjectId());
  149. return;
  150. case THREADSTATUS_DEAD:
  151. // This should never happen, as threads must complete before being stopped.
  152. DEBUG_ASSERT_MSG(false, "Thread with object id %u cannot be resumed because it's DEAD.",
  153. GetObjectId());
  154. return;
  155. }
  156. wakeup_callback = nullptr;
  157. status = THREADSTATUS_READY;
  158. Core::System::GetInstance().Scheduler().ScheduleThread(this, current_priority);
  159. Core::System::GetInstance().PrepareReschedule();
  160. }
  161. /**
  162. * Finds a free location for the TLS section of a thread.
  163. * @param tls_slots The TLS page array of the thread's owner process.
  164. * Returns a tuple of (page, slot, alloc_needed) where:
  165. * page: The index of the first allocated TLS page that has free slots.
  166. * slot: The index of the first free slot in the indicated page.
  167. * alloc_needed: Whether there's a need to allocate a new TLS page (All pages are full).
  168. */
  169. std::tuple<u32, u32, bool> GetFreeThreadLocalSlot(std::vector<std::bitset<8>>& tls_slots) {
  170. // Iterate over all the allocated pages, and try to find one where not all slots are used.
  171. for (unsigned page = 0; page < tls_slots.size(); ++page) {
  172. const auto& page_tls_slots = tls_slots[page];
  173. if (!page_tls_slots.all()) {
  174. // We found a page with at least one free slot, find which slot it is
  175. for (unsigned slot = 0; slot < page_tls_slots.size(); ++slot) {
  176. if (!page_tls_slots.test(slot)) {
  177. return std::make_tuple(page, slot, false);
  178. }
  179. }
  180. }
  181. }
  182. return std::make_tuple(0, 0, true);
  183. }
  184. /**
  185. * Resets a thread context, making it ready to be scheduled and run by the CPU
  186. * @param context Thread context to reset
  187. * @param stack_top Address of the top of the stack
  188. * @param entry_point Address of entry point for execution
  189. * @param arg User argument for thread
  190. */
  191. static void ResetThreadContext(ARM_Interface::ThreadContext& context, VAddr stack_top,
  192. VAddr entry_point, u64 arg) {
  193. memset(&context, 0, sizeof(ARM_Interface::ThreadContext));
  194. context.cpu_registers[0] = arg;
  195. context.pc = entry_point;
  196. context.sp = stack_top;
  197. context.cpsr = 0;
  198. context.fpscr = 0;
  199. }
  200. ResultVal<SharedPtr<Thread>> Thread::Create(std::string name, VAddr entry_point, u32 priority,
  201. u64 arg, s32 processor_id, VAddr stack_top,
  202. SharedPtr<Process> owner_process) {
  203. // Check if priority is in ranged. Lowest priority -> highest priority id.
  204. if (priority > THREADPRIO_LOWEST) {
  205. LOG_ERROR(Kernel_SVC, "Invalid thread priority: %u", priority);
  206. return ERR_OUT_OF_RANGE;
  207. }
  208. if (processor_id > THREADPROCESSORID_MAX) {
  209. LOG_ERROR(Kernel_SVC, "Invalid processor id: %d", processor_id);
  210. return ERR_OUT_OF_RANGE_KERNEL;
  211. }
  212. // TODO(yuriks): Other checks, returning 0xD9001BEA
  213. if (!Memory::IsValidVirtualAddress(*owner_process, entry_point)) {
  214. LOG_ERROR(Kernel_SVC, "(name=%s): invalid entry %016" PRIx64, name.c_str(), entry_point);
  215. // TODO (bunnei): Find the correct error code to use here
  216. return ResultCode(-1);
  217. }
  218. SharedPtr<Thread> thread(new Thread);
  219. Core::System::GetInstance().Scheduler().AddThread(thread, priority);
  220. thread->thread_id = NewThreadId();
  221. thread->status = THREADSTATUS_DORMANT;
  222. thread->entry_point = entry_point;
  223. thread->stack_top = stack_top;
  224. thread->nominal_priority = thread->current_priority = priority;
  225. thread->last_running_ticks = CoreTiming::GetTicks();
  226. thread->processor_id = processor_id;
  227. thread->wait_objects.clear();
  228. thread->wait_address = 0;
  229. thread->name = std::move(name);
  230. thread->callback_handle = wakeup_callback_handle_table.Create(thread).Unwrap();
  231. thread->owner_process = owner_process;
  232. // Find the next available TLS index, and mark it as used
  233. auto& tls_slots = owner_process->tls_slots;
  234. bool needs_allocation = true;
  235. u32 available_page; // Which allocated page has free space
  236. u32 available_slot; // Which slot within the page is free
  237. std::tie(available_page, available_slot, needs_allocation) = GetFreeThreadLocalSlot(tls_slots);
  238. if (needs_allocation) {
  239. // There are no already-allocated pages with free slots, lets allocate a new one.
  240. // TLS pages are allocated from the BASE region in the linear heap.
  241. MemoryRegionInfo* memory_region = GetMemoryRegion(MemoryRegion::BASE);
  242. auto& linheap_memory = memory_region->linear_heap_memory;
  243. if (linheap_memory->size() + Memory::PAGE_SIZE > memory_region->size) {
  244. LOG_ERROR(Kernel_SVC,
  245. "Not enough space in region to allocate a new TLS page for thread");
  246. return ERR_OUT_OF_MEMORY;
  247. }
  248. size_t offset = linheap_memory->size();
  249. // Allocate some memory from the end of the linear heap for this region.
  250. linheap_memory->insert(linheap_memory->end(), Memory::PAGE_SIZE, 0);
  251. memory_region->used += Memory::PAGE_SIZE;
  252. owner_process->linear_heap_used += Memory::PAGE_SIZE;
  253. tls_slots.emplace_back(0); // The page is completely available at the start
  254. available_page = static_cast<u32>(tls_slots.size() - 1);
  255. available_slot = 0; // Use the first slot in the new page
  256. auto& vm_manager = owner_process->vm_manager;
  257. vm_manager.RefreshMemoryBlockMappings(linheap_memory.get());
  258. // Map the page to the current process' address space.
  259. // TODO(Subv): Find the correct MemoryState for this region.
  260. vm_manager.MapMemoryBlock(Memory::TLS_AREA_VADDR + available_page * Memory::PAGE_SIZE,
  261. linheap_memory, offset, Memory::PAGE_SIZE,
  262. MemoryState::ThreadLocalStorage);
  263. }
  264. // Mark the slot as used
  265. tls_slots[available_page].set(available_slot);
  266. thread->tls_address = Memory::TLS_AREA_VADDR + available_page * Memory::PAGE_SIZE +
  267. available_slot * Memory::TLS_ENTRY_SIZE;
  268. // TODO(peachum): move to ScheduleThread() when scheduler is added so selected core is used
  269. // to initialize the context
  270. ResetThreadContext(thread->context, stack_top, entry_point, arg);
  271. return MakeResult<SharedPtr<Thread>>(std::move(thread));
  272. }
  273. void Thread::SetPriority(u32 priority) {
  274. ASSERT_MSG(priority <= THREADPRIO_LOWEST && priority >= THREADPRIO_HIGHEST,
  275. "Invalid priority value.");
  276. Core::System::GetInstance().Scheduler().SetThreadPriority(this, priority);
  277. nominal_priority = current_priority = priority;
  278. }
  279. void Thread::UpdatePriority() {
  280. u32 best_priority = nominal_priority;
  281. for (auto& mutex : held_mutexes) {
  282. if (mutex->priority < best_priority)
  283. best_priority = mutex->priority;
  284. }
  285. BoostPriority(best_priority);
  286. }
  287. void Thread::BoostPriority(u32 priority) {
  288. Core::System::GetInstance().Scheduler().SetThreadPriority(this, priority);
  289. current_priority = priority;
  290. }
  291. SharedPtr<Thread> SetupMainThread(VAddr entry_point, u32 priority,
  292. SharedPtr<Process> owner_process) {
  293. // Setup page table so we can write to memory
  294. SetCurrentPageTable(&Kernel::g_current_process->vm_manager.page_table);
  295. // Initialize new "main" thread
  296. auto thread_res = Thread::Create("main", entry_point, priority, 0, THREADPROCESSORID_0,
  297. Memory::HEAP_VADDR_END, owner_process);
  298. SharedPtr<Thread> thread = std::move(thread_res).Unwrap();
  299. // Register 1 must be a handle to the main thread
  300. thread->guest_handle = Kernel::g_handle_table.Create(thread).Unwrap();
  301. thread->context.cpu_registers[1] = thread->guest_handle;
  302. // Threads by default are dormant, wake up the main thread so it runs when the scheduler fires
  303. thread->ResumeFromWait();
  304. return thread;
  305. }
  306. void Thread::SetWaitSynchronizationResult(ResultCode result) {
  307. context.cpu_registers[0] = result.raw;
  308. }
  309. void Thread::SetWaitSynchronizationOutput(s32 output) {
  310. context.cpu_registers[1] = output;
  311. }
  312. s32 Thread::GetWaitObjectIndex(WaitObject* object) const {
  313. ASSERT_MSG(!wait_objects.empty(), "Thread is not waiting for anything");
  314. auto match = std::find(wait_objects.rbegin(), wait_objects.rend(), object);
  315. return static_cast<s32>(std::distance(match, wait_objects.rend()) - 1);
  316. }
  317. VAddr Thread::GetCommandBufferAddress() const {
  318. // Offset from the start of TLS at which the IPC command buffer begins.
  319. static constexpr int CommandHeaderOffset = 0x80;
  320. return GetTLSAddress() + CommandHeaderOffset;
  321. }
  322. ////////////////////////////////////////////////////////////////////////////////////////////////////
  323. /**
  324. * Gets the current thread
  325. */
  326. Thread* GetCurrentThread() {
  327. return Core::System::GetInstance().Scheduler().GetCurrentThread();
  328. }
  329. void ThreadingInit() {
  330. ThreadWakeupEventType = CoreTiming::RegisterEvent("ThreadWakeupCallback", ThreadWakeupCallback);
  331. next_thread_id = 1;
  332. }
  333. void ThreadingShutdown() {}
  334. } // namespace Kernel