thread.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  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. // Lists all thread ids that aren't deleted/etc.
  38. static std::vector<SharedPtr<Thread>> thread_list;
  39. // Lists only ready thread ids.
  40. static Common::ThreadQueueList<Thread*, THREADPRIO_LOWEST + 1> ready_queue;
  41. static SharedPtr<Thread> current_thread;
  42. // The first available thread id at startup
  43. static u32 next_thread_id;
  44. /**
  45. * Creates a new thread ID
  46. * @return The new thread ID
  47. */
  48. inline static u32 const NewThreadId() {
  49. return next_thread_id++;
  50. }
  51. Thread::Thread() {}
  52. Thread::~Thread() {}
  53. Thread* GetCurrentThread() {
  54. return current_thread.get();
  55. }
  56. /**
  57. * Check if the specified thread is waiting on the specified address to be arbitrated
  58. * @param thread The thread to test
  59. * @param wait_address The address to test against
  60. * @return True if the thread is waiting, false otherwise
  61. */
  62. static bool CheckWait_AddressArbiter(const Thread* thread, VAddr wait_address) {
  63. return thread->status == THREADSTATUS_WAIT_ARB && wait_address == thread->wait_address;
  64. }
  65. void Thread::Stop() {
  66. // Cancel any outstanding wakeup events for this thread
  67. CoreTiming::UnscheduleEvent(ThreadWakeupEventType, callback_handle);
  68. wakeup_callback_handle_table.Close(callback_handle);
  69. callback_handle = 0;
  70. // Clean up thread from ready queue
  71. // This is only needed when the thread is termintated forcefully (SVC TerminateProcess)
  72. if (status == THREADSTATUS_READY) {
  73. ready_queue.remove(current_priority, this);
  74. }
  75. status = THREADSTATUS_DEAD;
  76. WakeupAllWaitingThreads();
  77. // Clean up any dangling references in objects that this thread was waiting for
  78. for (auto& wait_object : wait_objects) {
  79. wait_object->RemoveWaitingThread(this);
  80. }
  81. wait_objects.clear();
  82. // Release all the mutexes that this thread holds
  83. ReleaseThreadMutexes(this);
  84. // Mark the TLS slot in the thread's page as free.
  85. u64 tls_page = (tls_address - Memory::TLS_AREA_VADDR) / Memory::PAGE_SIZE;
  86. u64 tls_slot =
  87. ((tls_address - Memory::TLS_AREA_VADDR) % Memory::PAGE_SIZE) / Memory::TLS_ENTRY_SIZE;
  88. Kernel::g_current_process->tls_slots[tls_page].reset(tls_slot);
  89. }
  90. Thread* ArbitrateHighestPriorityThread(u32 address) {
  91. Thread* highest_priority_thread = nullptr;
  92. u32 priority = THREADPRIO_LOWEST;
  93. // Iterate through threads, find highest priority thread that is waiting to be arbitrated...
  94. for (auto& thread : thread_list) {
  95. if (!CheckWait_AddressArbiter(thread.get(), address))
  96. continue;
  97. if (thread == nullptr)
  98. continue;
  99. if (thread->current_priority <= priority) {
  100. highest_priority_thread = thread.get();
  101. priority = thread->current_priority;
  102. }
  103. }
  104. // If a thread was arbitrated, resume it
  105. if (nullptr != highest_priority_thread) {
  106. highest_priority_thread->ResumeFromWait();
  107. }
  108. return highest_priority_thread;
  109. }
  110. void ArbitrateAllThreads(u32 address) {
  111. // Resume all threads found to be waiting on the address
  112. for (auto& thread : thread_list) {
  113. if (CheckWait_AddressArbiter(thread.get(), address))
  114. thread->ResumeFromWait();
  115. }
  116. }
  117. /**
  118. * Switches the CPU's active thread context to that of the specified thread
  119. * @param new_thread The thread to switch to
  120. */
  121. static void SwitchContext(Thread* new_thread) {
  122. Thread* previous_thread = GetCurrentThread();
  123. // Save context for previous thread
  124. if (previous_thread) {
  125. previous_thread->last_running_ticks = CoreTiming::GetTicks();
  126. Core::CPU().SaveContext(previous_thread->context);
  127. if (previous_thread->status == THREADSTATUS_RUNNING) {
  128. // This is only the case when a reschedule is triggered without the current thread
  129. // yielding execution (i.e. an event triggered, system core time-sliced, etc)
  130. ready_queue.push_front(previous_thread->current_priority, previous_thread);
  131. previous_thread->status = THREADSTATUS_READY;
  132. }
  133. }
  134. // Load context of new thread
  135. if (new_thread) {
  136. ASSERT_MSG(new_thread->status == THREADSTATUS_READY,
  137. "Thread must be ready to become running.");
  138. // Cancel any outstanding wakeup events for this thread
  139. CoreTiming::UnscheduleEvent(ThreadWakeupEventType, new_thread->callback_handle);
  140. auto previous_process = Kernel::g_current_process;
  141. current_thread = new_thread;
  142. ready_queue.remove(new_thread->current_priority, new_thread);
  143. new_thread->status = THREADSTATUS_RUNNING;
  144. if (previous_process != current_thread->owner_process) {
  145. Kernel::g_current_process = current_thread->owner_process;
  146. SetCurrentPageTable(&Kernel::g_current_process->vm_manager.page_table);
  147. }
  148. Core::CPU().LoadContext(new_thread->context);
  149. Core::CPU().SetTlsAddress(new_thread->GetTLSAddress());
  150. } else {
  151. current_thread = nullptr;
  152. // Note: We do not reset the current process and current page table when idling because
  153. // technically we haven't changed processes, our threads are just paused.
  154. }
  155. }
  156. /**
  157. * Pops and returns the next thread from the thread queue
  158. * @return A pointer to the next ready thread
  159. */
  160. static Thread* PopNextReadyThread() {
  161. Thread* next;
  162. Thread* thread = GetCurrentThread();
  163. if (thread && thread->status == THREADSTATUS_RUNNING) {
  164. // We have to do better than the current thread.
  165. // This call returns null when that's not possible.
  166. next = ready_queue.pop_first_better(thread->current_priority);
  167. if (!next) {
  168. // Otherwise just keep going with the current thread
  169. next = thread;
  170. }
  171. } else {
  172. next = ready_queue.pop_first();
  173. }
  174. return next;
  175. }
  176. void WaitCurrentThread_Sleep() {
  177. Thread* thread = GetCurrentThread();
  178. thread->status = THREADSTATUS_WAIT_SLEEP;
  179. }
  180. void WaitCurrentThread_ArbitrateAddress(VAddr wait_address) {
  181. Thread* thread = GetCurrentThread();
  182. thread->wait_address = wait_address;
  183. thread->status = THREADSTATUS_WAIT_ARB;
  184. }
  185. void ExitCurrentThread() {
  186. Thread* thread = GetCurrentThread();
  187. thread->Stop();
  188. thread_list.erase(std::remove(thread_list.begin(), thread_list.end(), thread),
  189. thread_list.end());
  190. }
  191. /**
  192. * Callback that will wake up the thread it was scheduled for
  193. * @param thread_handle The handle of the thread that's been awoken
  194. * @param cycles_late The number of CPU cycles that have passed since the desired wakeup time
  195. */
  196. static void ThreadWakeupCallback(u64 thread_handle, int cycles_late) {
  197. SharedPtr<Thread> thread = wakeup_callback_handle_table.Get<Thread>((Handle)thread_handle);
  198. if (thread == nullptr) {
  199. LOG_CRITICAL(Kernel, "Callback fired for invalid thread %08X", (Handle)thread_handle);
  200. return;
  201. }
  202. bool resume = true;
  203. if (thread->status == THREADSTATUS_WAIT_SYNCH_ANY ||
  204. thread->status == THREADSTATUS_WAIT_SYNCH_ALL || thread->status == THREADSTATUS_WAIT_ARB) {
  205. // Remove the thread from each of its waiting objects' waitlists
  206. for (auto& object : thread->wait_objects)
  207. object->RemoveWaitingThread(thread.get());
  208. thread->wait_objects.clear();
  209. // Invoke the wakeup callback before clearing the wait objects
  210. if (thread->wakeup_callback)
  211. resume = thread->wakeup_callback(ThreadWakeupReason::Timeout, thread, nullptr, 0);
  212. }
  213. if (resume)
  214. thread->ResumeFromWait();
  215. }
  216. void Thread::WakeAfterDelay(s64 nanoseconds) {
  217. // Don't schedule a wakeup if the thread wants to wait forever
  218. if (nanoseconds == -1)
  219. return;
  220. CoreTiming::ScheduleEvent(nsToCycles(nanoseconds), ThreadWakeupEventType, callback_handle);
  221. }
  222. void Thread::CancelWakeupTimer() {
  223. CoreTiming::UnscheduleEvent(ThreadWakeupEventType, callback_handle);
  224. }
  225. void Thread::ResumeFromWait() {
  226. ASSERT_MSG(wait_objects.empty(), "Thread is waking up while waiting for objects");
  227. switch (status) {
  228. case THREADSTATUS_WAIT_SYNCH_ALL:
  229. case THREADSTATUS_WAIT_SYNCH_ANY:
  230. case THREADSTATUS_WAIT_ARB:
  231. case THREADSTATUS_WAIT_SLEEP:
  232. case THREADSTATUS_WAIT_IPC:
  233. break;
  234. case THREADSTATUS_READY:
  235. // The thread's wakeup callback must have already been cleared when the thread was first
  236. // awoken.
  237. ASSERT(wakeup_callback == nullptr);
  238. // If the thread is waiting on multiple wait objects, it might be awoken more than once
  239. // before actually resuming. We can ignore subsequent wakeups if the thread status has
  240. // already been set to THREADSTATUS_READY.
  241. return;
  242. case THREADSTATUS_RUNNING:
  243. DEBUG_ASSERT_MSG(false, "Thread with object id %u has already resumed.", GetObjectId());
  244. return;
  245. case THREADSTATUS_DEAD:
  246. // This should never happen, as threads must complete before being stopped.
  247. DEBUG_ASSERT_MSG(false, "Thread with object id %u cannot be resumed because it's DEAD.",
  248. GetObjectId());
  249. return;
  250. }
  251. wakeup_callback = nullptr;
  252. ready_queue.push_back(current_priority, this);
  253. status = THREADSTATUS_READY;
  254. Core::System::GetInstance().PrepareReschedule();
  255. }
  256. /**
  257. * Prints the thread queue for debugging purposes
  258. */
  259. static void DebugThreadQueue() {
  260. Thread* thread = GetCurrentThread();
  261. if (!thread) {
  262. LOG_DEBUG(Kernel, "Current: NO CURRENT THREAD");
  263. } else {
  264. LOG_DEBUG(Kernel, "0x%02X %u (current)", thread->current_priority,
  265. GetCurrentThread()->GetObjectId());
  266. }
  267. for (auto& t : thread_list) {
  268. u32 priority = ready_queue.contains(t.get());
  269. if (priority != -1) {
  270. LOG_DEBUG(Kernel, "0x%02X %u", priority, t->GetObjectId());
  271. }
  272. }
  273. }
  274. /**
  275. * Finds a free location for the TLS section of a thread.
  276. * @param tls_slots The TLS page array of the thread's owner process.
  277. * Returns a tuple of (page, slot, alloc_needed) where:
  278. * page: The index of the first allocated TLS page that has free slots.
  279. * slot: The index of the first free slot in the indicated page.
  280. * alloc_needed: Whether there's a need to allocate a new TLS page (All pages are full).
  281. */
  282. std::tuple<u32, u32, bool> GetFreeThreadLocalSlot(std::vector<std::bitset<8>>& tls_slots) {
  283. // Iterate over all the allocated pages, and try to find one where not all slots are used.
  284. for (unsigned page = 0; page < tls_slots.size(); ++page) {
  285. const auto& page_tls_slots = tls_slots[page];
  286. if (!page_tls_slots.all()) {
  287. // We found a page with at least one free slot, find which slot it is
  288. for (unsigned slot = 0; slot < page_tls_slots.size(); ++slot) {
  289. if (!page_tls_slots.test(slot)) {
  290. return std::make_tuple(page, slot, false);
  291. }
  292. }
  293. }
  294. }
  295. return std::make_tuple(0, 0, true);
  296. }
  297. /**
  298. * Resets a thread context, making it ready to be scheduled and run by the CPU
  299. * @param context Thread context to reset
  300. * @param stack_top Address of the top of the stack
  301. * @param entry_point Address of entry point for execution
  302. * @param arg User argument for thread
  303. */
  304. static void ResetThreadContext(ARM_Interface::ThreadContext& context, VAddr stack_top,
  305. VAddr entry_point, u64 arg) {
  306. memset(&context, 0, sizeof(ARM_Interface::ThreadContext));
  307. context.cpu_registers[0] = arg;
  308. context.pc = entry_point;
  309. context.sp = stack_top;
  310. context.cpsr = 0;
  311. context.fpscr = 0;
  312. }
  313. ResultVal<SharedPtr<Thread>> Thread::Create(std::string name, VAddr entry_point, u32 priority,
  314. u64 arg, s32 processor_id, VAddr stack_top,
  315. SharedPtr<Process> owner_process) {
  316. // Check if priority is in ranged. Lowest priority -> highest priority id.
  317. if (priority > THREADPRIO_LOWEST) {
  318. LOG_ERROR(Kernel_SVC, "Invalid thread priority: %u", priority);
  319. return ERR_OUT_OF_RANGE;
  320. }
  321. if (processor_id > THREADPROCESSORID_MAX) {
  322. LOG_ERROR(Kernel_SVC, "Invalid processor id: %d", processor_id);
  323. return ERR_OUT_OF_RANGE_KERNEL;
  324. }
  325. // TODO(yuriks): Other checks, returning 0xD9001BEA
  326. if (!Memory::IsValidVirtualAddress(*owner_process, entry_point)) {
  327. LOG_ERROR(Kernel_SVC, "(name=%s): invalid entry %016" PRIx64, name.c_str(), entry_point);
  328. // TODO (bunnei): Find the correct error code to use here
  329. return ResultCode(-1);
  330. }
  331. SharedPtr<Thread> thread(new Thread);
  332. thread_list.push_back(thread);
  333. ready_queue.prepare(priority);
  334. thread->thread_id = NewThreadId();
  335. thread->status = THREADSTATUS_DORMANT;
  336. thread->entry_point = entry_point;
  337. thread->stack_top = stack_top;
  338. thread->nominal_priority = thread->current_priority = priority;
  339. thread->last_running_ticks = CoreTiming::GetTicks();
  340. thread->processor_id = processor_id;
  341. thread->wait_objects.clear();
  342. thread->wait_address = 0;
  343. thread->name = std::move(name);
  344. thread->callback_handle = wakeup_callback_handle_table.Create(thread).Unwrap();
  345. thread->owner_process = owner_process;
  346. // Find the next available TLS index, and mark it as used
  347. auto& tls_slots = owner_process->tls_slots;
  348. bool needs_allocation = true;
  349. u32 available_page; // Which allocated page has free space
  350. u32 available_slot; // Which slot within the page is free
  351. std::tie(available_page, available_slot, needs_allocation) = GetFreeThreadLocalSlot(tls_slots);
  352. if (needs_allocation) {
  353. // There are no already-allocated pages with free slots, lets allocate a new one.
  354. // TLS pages are allocated from the BASE region in the linear heap.
  355. MemoryRegionInfo* memory_region = GetMemoryRegion(MemoryRegion::BASE);
  356. auto& linheap_memory = memory_region->linear_heap_memory;
  357. if (linheap_memory->size() + Memory::PAGE_SIZE > memory_region->size) {
  358. LOG_ERROR(Kernel_SVC,
  359. "Not enough space in region to allocate a new TLS page for thread");
  360. return ERR_OUT_OF_MEMORY;
  361. }
  362. size_t offset = linheap_memory->size();
  363. // Allocate some memory from the end of the linear heap for this region.
  364. linheap_memory->insert(linheap_memory->end(), Memory::PAGE_SIZE, 0);
  365. memory_region->used += Memory::PAGE_SIZE;
  366. owner_process->linear_heap_used += Memory::PAGE_SIZE;
  367. tls_slots.emplace_back(0); // The page is completely available at the start
  368. available_page = static_cast<u32>(tls_slots.size() - 1);
  369. available_slot = 0; // Use the first slot in the new page
  370. auto& vm_manager = owner_process->vm_manager;
  371. vm_manager.RefreshMemoryBlockMappings(linheap_memory.get());
  372. // Map the page to the current process' address space.
  373. // TODO(Subv): Find the correct MemoryState for this region.
  374. vm_manager.MapMemoryBlock(Memory::TLS_AREA_VADDR + available_page * Memory::PAGE_SIZE,
  375. linheap_memory, offset, Memory::PAGE_SIZE,
  376. MemoryState::ThreadLocalStorage);
  377. }
  378. // Mark the slot as used
  379. tls_slots[available_page].set(available_slot);
  380. thread->tls_address = Memory::TLS_AREA_VADDR + available_page * Memory::PAGE_SIZE +
  381. available_slot * Memory::TLS_ENTRY_SIZE;
  382. // TODO(peachum): move to ScheduleThread() when scheduler is added so selected core is used
  383. // to initialize the context
  384. ResetThreadContext(thread->context, stack_top, entry_point, arg);
  385. return MakeResult<SharedPtr<Thread>>(std::move(thread));
  386. }
  387. void Thread::SetPriority(u32 priority) {
  388. ASSERT_MSG(priority <= THREADPRIO_LOWEST && priority >= THREADPRIO_HIGHEST,
  389. "Invalid priority value.");
  390. // If thread was ready, adjust queues
  391. if (status == THREADSTATUS_READY)
  392. ready_queue.move(this, current_priority, priority);
  393. else
  394. ready_queue.prepare(priority);
  395. nominal_priority = current_priority = priority;
  396. }
  397. void Thread::UpdatePriority() {
  398. u32 best_priority = nominal_priority;
  399. for (auto& mutex : held_mutexes) {
  400. if (mutex->priority < best_priority)
  401. best_priority = mutex->priority;
  402. }
  403. BoostPriority(best_priority);
  404. }
  405. void Thread::BoostPriority(u32 priority) {
  406. // If thread was ready, adjust queues
  407. if (status == THREADSTATUS_READY)
  408. ready_queue.move(this, current_priority, priority);
  409. else
  410. ready_queue.prepare(priority);
  411. current_priority = priority;
  412. }
  413. SharedPtr<Thread> SetupMainThread(VAddr entry_point, u32 priority,
  414. SharedPtr<Process> owner_process) {
  415. // Setup page table so we can write to memory
  416. SetCurrentPageTable(&Kernel::g_current_process->vm_manager.page_table);
  417. // Initialize new "main" thread
  418. auto thread_res = Thread::Create("main", entry_point, priority, 0, THREADPROCESSORID_0,
  419. Memory::HEAP_VADDR_END, owner_process);
  420. SharedPtr<Thread> thread = std::move(thread_res).Unwrap();
  421. // Register 1 must be a handle to the main thread
  422. thread->guest_handle = Kernel::g_handle_table.Create(thread).Unwrap();
  423. thread->context.cpu_registers[1] = thread->guest_handle;
  424. // Threads by default are dormant, wake up the main thread so it runs when the scheduler fires
  425. thread->ResumeFromWait();
  426. return thread;
  427. }
  428. bool HaveReadyThreads() {
  429. return ready_queue.get_first() != nullptr;
  430. }
  431. void Reschedule() {
  432. Thread* cur = GetCurrentThread();
  433. Thread* next = PopNextReadyThread();
  434. if (cur && next) {
  435. LOG_TRACE(Kernel, "context switch %u -> %u", cur->GetObjectId(), next->GetObjectId());
  436. } else if (cur) {
  437. LOG_TRACE(Kernel, "context switch %u -> idle", cur->GetObjectId());
  438. } else if (next) {
  439. LOG_TRACE(Kernel, "context switch idle -> %u", next->GetObjectId());
  440. }
  441. SwitchContext(next);
  442. }
  443. void Thread::SetWaitSynchronizationResult(ResultCode result) {
  444. context.cpu_registers[0] = result.raw;
  445. }
  446. void Thread::SetWaitSynchronizationOutput(s32 output) {
  447. context.cpu_registers[1] = output;
  448. }
  449. s32 Thread::GetWaitObjectIndex(WaitObject* object) const {
  450. ASSERT_MSG(!wait_objects.empty(), "Thread is not waiting for anything");
  451. auto match = std::find(wait_objects.rbegin(), wait_objects.rend(), object);
  452. return static_cast<s32>(std::distance(match, wait_objects.rend()) - 1);
  453. }
  454. VAddr Thread::GetCommandBufferAddress() const {
  455. // Offset from the start of TLS at which the IPC command buffer begins.
  456. static constexpr int CommandHeaderOffset = 0x80;
  457. return GetTLSAddress() + CommandHeaderOffset;
  458. }
  459. ////////////////////////////////////////////////////////////////////////////////////////////////////
  460. void ThreadingInit() {
  461. ThreadWakeupEventType = CoreTiming::RegisterEvent("ThreadWakeupCallback", ThreadWakeupCallback);
  462. current_thread = nullptr;
  463. next_thread_id = 1;
  464. }
  465. void ThreadingShutdown() {
  466. current_thread = nullptr;
  467. for (auto& t : thread_list) {
  468. t->Stop();
  469. }
  470. thread_list.clear();
  471. ready_queue.clear();
  472. }
  473. const std::vector<SharedPtr<Thread>>& GetThreadList() {
  474. return thread_list;
  475. }
  476. } // namespace Kernel