thread.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  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. 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().CurrentScheduler().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. static boost::optional<s32> GetNextProcessorId(u64 mask) {
  129. for (s32 index = 0; index < Core::NUM_CPU_CORES; ++index) {
  130. if (mask & (1ULL << index)) {
  131. if (!Core::System().GetInstance().Scheduler(index)->GetCurrentThread()) {
  132. // Core is enabled and not running any threads, use this one
  133. return index;
  134. }
  135. }
  136. }
  137. return {};
  138. }
  139. void Thread::ResumeFromWait() {
  140. ASSERT_MSG(wait_objects.empty(), "Thread is waking up while waiting for objects");
  141. switch (status) {
  142. case THREADSTATUS_WAIT_SYNCH_ALL:
  143. case THREADSTATUS_WAIT_SYNCH_ANY:
  144. case THREADSTATUS_WAIT_HLE_EVENT:
  145. case THREADSTATUS_WAIT_SLEEP:
  146. case THREADSTATUS_WAIT_IPC:
  147. case THREADSTATUS_WAIT_MUTEX:
  148. break;
  149. case THREADSTATUS_READY:
  150. // The thread's wakeup callback must have already been cleared when the thread was first
  151. // awoken.
  152. ASSERT(wakeup_callback == nullptr);
  153. // If the thread is waiting on multiple wait objects, it might be awoken more than once
  154. // before actually resuming. We can ignore subsequent wakeups if the thread status has
  155. // already been set to THREADSTATUS_READY.
  156. return;
  157. case THREADSTATUS_RUNNING:
  158. DEBUG_ASSERT_MSG(false, "Thread with object id {} has already resumed.", GetObjectId());
  159. return;
  160. case THREADSTATUS_DEAD:
  161. // This should never happen, as threads must complete before being stopped.
  162. DEBUG_ASSERT_MSG(false, "Thread with object id {} cannot be resumed because it's DEAD.",
  163. GetObjectId());
  164. return;
  165. }
  166. wakeup_callback = nullptr;
  167. status = THREADSTATUS_READY;
  168. boost::optional<s32> new_processor_id = GetNextProcessorId(affinity_mask);
  169. if (!new_processor_id) {
  170. new_processor_id = processor_id;
  171. }
  172. if (ideal_core != -1 &&
  173. Core::System().GetInstance().Scheduler(ideal_core)->GetCurrentThread() == nullptr) {
  174. new_processor_id = ideal_core;
  175. }
  176. ASSERT(*new_processor_id < 4);
  177. // Add thread to new core's scheduler
  178. auto& next_scheduler = Core::System().GetInstance().Scheduler(*new_processor_id);
  179. if (*new_processor_id != processor_id) {
  180. // Remove thread from previous core's scheduler
  181. scheduler->RemoveThread(this);
  182. next_scheduler->AddThread(this, current_priority);
  183. }
  184. processor_id = *new_processor_id;
  185. // If the thread was ready, unschedule from the previous core and schedule on the new core
  186. scheduler->UnscheduleThread(this, current_priority);
  187. next_scheduler->ScheduleThread(this, current_priority);
  188. // Change thread's scheduler
  189. scheduler = next_scheduler;
  190. Core::System::GetInstance().CpuCore(processor_id).PrepareReschedule();
  191. }
  192. /**
  193. * Finds a free location for the TLS section of a thread.
  194. * @param tls_slots The TLS page array of the thread's owner process.
  195. * Returns a tuple of (page, slot, alloc_needed) where:
  196. * page: The index of the first allocated TLS page that has free slots.
  197. * slot: The index of the first free slot in the indicated page.
  198. * alloc_needed: Whether there's a need to allocate a new TLS page (All pages are full).
  199. */
  200. std::tuple<u32, u32, bool> GetFreeThreadLocalSlot(std::vector<std::bitset<8>>& tls_slots) {
  201. // Iterate over all the allocated pages, and try to find one where not all slots are used.
  202. for (unsigned page = 0; page < tls_slots.size(); ++page) {
  203. const auto& page_tls_slots = tls_slots[page];
  204. if (!page_tls_slots.all()) {
  205. // We found a page with at least one free slot, find which slot it is
  206. for (unsigned slot = 0; slot < page_tls_slots.size(); ++slot) {
  207. if (!page_tls_slots.test(slot)) {
  208. return std::make_tuple(page, slot, false);
  209. }
  210. }
  211. }
  212. }
  213. return std::make_tuple(0, 0, true);
  214. }
  215. /**
  216. * Resets a thread context, making it ready to be scheduled and run by the CPU
  217. * @param context Thread context to reset
  218. * @param stack_top Address of the top of the stack
  219. * @param entry_point Address of entry point for execution
  220. * @param arg User argument for thread
  221. */
  222. static void ResetThreadContext(ARM_Interface::ThreadContext& context, VAddr stack_top,
  223. VAddr entry_point, u64 arg) {
  224. memset(&context, 0, sizeof(ARM_Interface::ThreadContext));
  225. context.cpu_registers[0] = arg;
  226. context.pc = entry_point;
  227. context.sp = stack_top;
  228. context.cpsr = 0;
  229. context.fpscr = 0;
  230. }
  231. ResultVal<SharedPtr<Thread>> Thread::Create(std::string name, VAddr entry_point, u32 priority,
  232. u64 arg, s32 processor_id, VAddr stack_top,
  233. SharedPtr<Process> owner_process) {
  234. // Check if priority is in ranged. Lowest priority -> highest priority id.
  235. if (priority > THREADPRIO_LOWEST) {
  236. NGLOG_ERROR(Kernel_SVC, "Invalid thread priority: {}", priority);
  237. return ERR_OUT_OF_RANGE;
  238. }
  239. if (processor_id > THREADPROCESSORID_MAX) {
  240. NGLOG_ERROR(Kernel_SVC, "Invalid processor id: {}", processor_id);
  241. return ERR_OUT_OF_RANGE_KERNEL;
  242. }
  243. // TODO(yuriks): Other checks, returning 0xD9001BEA
  244. if (!Memory::IsValidVirtualAddress(*owner_process, entry_point)) {
  245. NGLOG_ERROR(Kernel_SVC, "(name={}): invalid entry {:016X}", name, entry_point);
  246. // TODO (bunnei): Find the correct error code to use here
  247. return ResultCode(-1);
  248. }
  249. SharedPtr<Thread> thread(new Thread);
  250. thread->thread_id = NewThreadId();
  251. thread->status = THREADSTATUS_DORMANT;
  252. thread->entry_point = entry_point;
  253. thread->stack_top = stack_top;
  254. thread->nominal_priority = thread->current_priority = priority;
  255. thread->last_running_ticks = CoreTiming::GetTicks();
  256. thread->processor_id = processor_id;
  257. thread->ideal_core = processor_id;
  258. thread->affinity_mask = 1ULL << processor_id;
  259. thread->wait_objects.clear();
  260. thread->mutex_wait_address = 0;
  261. thread->condvar_wait_address = 0;
  262. thread->wait_handle = 0;
  263. thread->name = std::move(name);
  264. thread->callback_handle = wakeup_callback_handle_table.Create(thread).Unwrap();
  265. thread->owner_process = owner_process;
  266. thread->scheduler = Core::System().GetInstance().Scheduler(processor_id);
  267. thread->scheduler->AddThread(thread, priority);
  268. // Find the next available TLS index, and mark it as used
  269. auto& tls_slots = owner_process->tls_slots;
  270. bool needs_allocation = true;
  271. u32 available_page; // Which allocated page has free space
  272. u32 available_slot; // Which slot within the page is free
  273. std::tie(available_page, available_slot, needs_allocation) = GetFreeThreadLocalSlot(tls_slots);
  274. if (needs_allocation) {
  275. // There are no already-allocated pages with free slots, lets allocate a new one.
  276. // TLS pages are allocated from the BASE region in the linear heap.
  277. MemoryRegionInfo* memory_region = GetMemoryRegion(MemoryRegion::BASE);
  278. auto& linheap_memory = memory_region->linear_heap_memory;
  279. if (linheap_memory->size() + Memory::PAGE_SIZE > memory_region->size) {
  280. NGLOG_ERROR(Kernel_SVC,
  281. "Not enough space in region to allocate a new TLS page for thread");
  282. return ERR_OUT_OF_MEMORY;
  283. }
  284. size_t offset = linheap_memory->size();
  285. // Allocate some memory from the end of the linear heap for this region.
  286. linheap_memory->insert(linheap_memory->end(), Memory::PAGE_SIZE, 0);
  287. memory_region->used += Memory::PAGE_SIZE;
  288. owner_process->linear_heap_used += Memory::PAGE_SIZE;
  289. tls_slots.emplace_back(0); // The page is completely available at the start
  290. available_page = static_cast<u32>(tls_slots.size() - 1);
  291. available_slot = 0; // Use the first slot in the new page
  292. auto& vm_manager = owner_process->vm_manager;
  293. vm_manager.RefreshMemoryBlockMappings(linheap_memory.get());
  294. // Map the page to the current process' address space.
  295. // TODO(Subv): Find the correct MemoryState for this region.
  296. vm_manager.MapMemoryBlock(Memory::TLS_AREA_VADDR + available_page * Memory::PAGE_SIZE,
  297. linheap_memory, offset, Memory::PAGE_SIZE,
  298. MemoryState::ThreadLocal);
  299. }
  300. // Mark the slot as used
  301. tls_slots[available_page].set(available_slot);
  302. thread->tls_address = Memory::TLS_AREA_VADDR + available_page * Memory::PAGE_SIZE +
  303. available_slot * Memory::TLS_ENTRY_SIZE;
  304. // TODO(peachum): move to ScheduleThread() when scheduler is added so selected core is used
  305. // to initialize the context
  306. ResetThreadContext(thread->context, stack_top, entry_point, arg);
  307. return MakeResult<SharedPtr<Thread>>(std::move(thread));
  308. }
  309. void Thread::SetPriority(u32 priority) {
  310. ASSERT_MSG(priority <= THREADPRIO_LOWEST && priority >= THREADPRIO_HIGHEST,
  311. "Invalid priority value.");
  312. nominal_priority = priority;
  313. UpdatePriority();
  314. }
  315. void Thread::BoostPriority(u32 priority) {
  316. scheduler->SetThreadPriority(this, priority);
  317. current_priority = priority;
  318. }
  319. SharedPtr<Thread> SetupMainThread(VAddr entry_point, u32 priority,
  320. SharedPtr<Process> owner_process) {
  321. // Setup page table so we can write to memory
  322. SetCurrentPageTable(&Core::CurrentProcess()->vm_manager.page_table);
  323. // Initialize new "main" thread
  324. auto thread_res = Thread::Create("main", entry_point, priority, 0, THREADPROCESSORID_0,
  325. Memory::STACK_AREA_VADDR_END, owner_process);
  326. SharedPtr<Thread> thread = std::move(thread_res).Unwrap();
  327. // Register 1 must be a handle to the main thread
  328. thread->guest_handle = Kernel::g_handle_table.Create(thread).Unwrap();
  329. thread->context.cpu_registers[1] = thread->guest_handle;
  330. // Threads by default are dormant, wake up the main thread so it runs when the scheduler fires
  331. thread->ResumeFromWait();
  332. return thread;
  333. }
  334. void Thread::SetWaitSynchronizationResult(ResultCode result) {
  335. context.cpu_registers[0] = result.raw;
  336. }
  337. void Thread::SetWaitSynchronizationOutput(s32 output) {
  338. context.cpu_registers[1] = output;
  339. }
  340. s32 Thread::GetWaitObjectIndex(WaitObject* object) const {
  341. ASSERT_MSG(!wait_objects.empty(), "Thread is not waiting for anything");
  342. auto match = std::find(wait_objects.rbegin(), wait_objects.rend(), object);
  343. return static_cast<s32>(std::distance(match, wait_objects.rend()) - 1);
  344. }
  345. VAddr Thread::GetCommandBufferAddress() const {
  346. // Offset from the start of TLS at which the IPC command buffer begins.
  347. static constexpr int CommandHeaderOffset = 0x80;
  348. return GetTLSAddress() + CommandHeaderOffset;
  349. }
  350. void Thread::AddMutexWaiter(SharedPtr<Thread> thread) {
  351. thread->lock_owner = this;
  352. wait_mutex_threads.emplace_back(std::move(thread));
  353. UpdatePriority();
  354. }
  355. void Thread::RemoveMutexWaiter(SharedPtr<Thread> thread) {
  356. boost::remove_erase(wait_mutex_threads, thread);
  357. thread->lock_owner = nullptr;
  358. UpdatePriority();
  359. }
  360. void Thread::UpdatePriority() {
  361. // Find the highest priority among all the threads that are waiting for this thread's lock
  362. u32 new_priority = nominal_priority;
  363. for (const auto& thread : wait_mutex_threads) {
  364. if (thread->nominal_priority < new_priority)
  365. new_priority = thread->nominal_priority;
  366. }
  367. if (new_priority == current_priority)
  368. return;
  369. scheduler->SetThreadPriority(this, new_priority);
  370. current_priority = new_priority;
  371. // Recursively update the priority of the thread that depends on the priority of this one.
  372. if (lock_owner)
  373. lock_owner->UpdatePriority();
  374. }
  375. void Thread::ChangeCore(u32 core, u64 mask) {
  376. ideal_core = core;
  377. mask = mask;
  378. if (status != THREADSTATUS_READY) {
  379. return;
  380. }
  381. boost::optional<s32> new_processor_id{GetNextProcessorId(mask)};
  382. if (!new_processor_id) {
  383. new_processor_id = processor_id;
  384. }
  385. if (ideal_core != -1 &&
  386. Core::System().GetInstance().Scheduler(ideal_core)->GetCurrentThread() == nullptr) {
  387. new_processor_id = ideal_core;
  388. }
  389. ASSERT(new_processor_id < 4);
  390. // Add thread to new core's scheduler
  391. auto& next_scheduler = Core::System().GetInstance().Scheduler(*new_processor_id);
  392. if (*new_processor_id != processor_id) {
  393. // Remove thread from previous core's scheduler
  394. scheduler->RemoveThread(this);
  395. next_scheduler->AddThread(this, current_priority);
  396. }
  397. processor_id = *new_processor_id;
  398. // If the thread was ready, unschedule from the previous core and schedule on the new core
  399. scheduler->UnscheduleThread(this, current_priority);
  400. next_scheduler->ScheduleThread(this, current_priority);
  401. // Change thread's scheduler
  402. scheduler = next_scheduler;
  403. Core::System::GetInstance().CpuCore(processor_id).PrepareReschedule();
  404. }
  405. ////////////////////////////////////////////////////////////////////////////////////////////////////
  406. /**
  407. * Gets the current thread
  408. */
  409. Thread* GetCurrentThread() {
  410. return Core::System::GetInstance().CurrentScheduler().GetCurrentThread();
  411. }
  412. void ThreadingInit() {
  413. ThreadWakeupEventType = CoreTiming::RegisterEvent("ThreadWakeupCallback", ThreadWakeupCallback);
  414. next_thread_id = 1;
  415. }
  416. void ThreadingShutdown() {
  417. Kernel::ClearProcessList();
  418. }
  419. } // namespace Kernel