thread.cpp 16 KB

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