thread.cpp 19 KB

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