thread.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  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 <list>
  6. #include <vector>
  7. #include "common/assert.h"
  8. #include "common/common_types.h"
  9. #include "common/logging/log.h"
  10. #include "common/math_util.h"
  11. #include "common/thread_queue_list.h"
  12. #include "core/arm/arm_interface.h"
  13. #include "core/arm/skyeye_common/armstate.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 int ThreadWakeupEventType;
  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. u32 tls_page = (tls_address - Memory::TLS_AREA_VADDR) / Memory::PAGE_SIZE;
  86. u32 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. s32 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. Core::CPU().LoadContext(new_thread->context);
  145. Core::CPU().SetCP15Register(CP15_THREAD_URO, new_thread->GetTLSAddress());
  146. if (previous_process != current_thread->owner_process) {
  147. Kernel::g_current_process = current_thread->owner_process;
  148. Memory::current_page_table = &Kernel::g_current_process->vm_manager.page_table;
  149. // We have switched processes and thus, page tables, clear the instruction cache so we
  150. // don't keep stale data from the previous process.
  151. Core::CPU().ClearInstructionCache();
  152. }
  153. } else {
  154. current_thread = nullptr;
  155. // Note: We do not reset the current process and current page table when idling because
  156. // technically we haven't changed processes, our threads are just paused.
  157. }
  158. }
  159. /**
  160. * Pops and returns the next thread from the thread queue
  161. * @return A pointer to the next ready thread
  162. */
  163. static Thread* PopNextReadyThread() {
  164. Thread* next;
  165. Thread* thread = GetCurrentThread();
  166. if (thread && thread->status == THREADSTATUS_RUNNING) {
  167. // We have to do better than the current thread.
  168. // This call returns null when that's not possible.
  169. next = ready_queue.pop_first_better(thread->current_priority);
  170. if (!next) {
  171. // Otherwise just keep going with the current thread
  172. next = thread;
  173. }
  174. } else {
  175. next = ready_queue.pop_first();
  176. }
  177. return next;
  178. }
  179. void WaitCurrentThread_Sleep() {
  180. Thread* thread = GetCurrentThread();
  181. thread->status = THREADSTATUS_WAIT_SLEEP;
  182. }
  183. void WaitCurrentThread_ArbitrateAddress(VAddr wait_address) {
  184. Thread* thread = GetCurrentThread();
  185. thread->wait_address = wait_address;
  186. thread->status = THREADSTATUS_WAIT_ARB;
  187. }
  188. void ExitCurrentThread() {
  189. Thread* thread = GetCurrentThread();
  190. thread->Stop();
  191. thread_list.erase(std::remove(thread_list.begin(), thread_list.end(), thread),
  192. thread_list.end());
  193. }
  194. /**
  195. * Callback that will wake up the thread it was scheduled for
  196. * @param thread_handle The handle of the thread that's been awoken
  197. * @param cycles_late The number of CPU cycles that have passed since the desired wakeup time
  198. */
  199. static void ThreadWakeupCallback(u64 thread_handle, int cycles_late) {
  200. SharedPtr<Thread> thread = wakeup_callback_handle_table.Get<Thread>((Handle)thread_handle);
  201. if (thread == nullptr) {
  202. LOG_CRITICAL(Kernel, "Callback fired for invalid thread %08X", (Handle)thread_handle);
  203. return;
  204. }
  205. if (thread->status == THREADSTATUS_WAIT_SYNCH_ANY ||
  206. thread->status == THREADSTATUS_WAIT_SYNCH_ALL || thread->status == THREADSTATUS_WAIT_ARB) {
  207. thread->wait_set_output = false;
  208. // Remove the thread from each of its waiting objects' waitlists
  209. for (auto& object : thread->wait_objects)
  210. object->RemoveWaitingThread(thread.get());
  211. thread->wait_objects.clear();
  212. thread->SetWaitSynchronizationResult(RESULT_TIMEOUT);
  213. }
  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. u64 microseconds = nanoseconds / 1000;
  221. CoreTiming::ScheduleEvent(usToCycles(microseconds), ThreadWakeupEventType, callback_handle);
  222. }
  223. void Thread::ResumeFromWait() {
  224. ASSERT_MSG(wait_objects.empty(), "Thread is waking up while waiting for objects");
  225. switch (status) {
  226. case THREADSTATUS_WAIT_SYNCH_ALL:
  227. case THREADSTATUS_WAIT_SYNCH_ANY:
  228. case THREADSTATUS_WAIT_ARB:
  229. case THREADSTATUS_WAIT_SLEEP:
  230. break;
  231. case THREADSTATUS_READY:
  232. // If the thread is waiting on multiple wait objects, it might be awoken more than once
  233. // before actually resuming. We can ignore subsequent wakeups if the thread status has
  234. // already been set to THREADSTATUS_READY.
  235. return;
  236. case THREADSTATUS_RUNNING:
  237. DEBUG_ASSERT_MSG(false, "Thread with object id %u has already resumed.", GetObjectId());
  238. return;
  239. case THREADSTATUS_DEAD:
  240. // This should never happen, as threads must complete before being stopped.
  241. DEBUG_ASSERT_MSG(false, "Thread with object id %u cannot be resumed because it's DEAD.",
  242. GetObjectId());
  243. return;
  244. }
  245. ready_queue.push_back(current_priority, this);
  246. status = THREADSTATUS_READY;
  247. Core::System::GetInstance().PrepareReschedule();
  248. }
  249. /**
  250. * Prints the thread queue for debugging purposes
  251. */
  252. static void DebugThreadQueue() {
  253. Thread* thread = GetCurrentThread();
  254. if (!thread) {
  255. LOG_DEBUG(Kernel, "Current: NO CURRENT THREAD");
  256. } else {
  257. LOG_DEBUG(Kernel, "0x%02X %u (current)", thread->current_priority,
  258. GetCurrentThread()->GetObjectId());
  259. }
  260. for (auto& t : thread_list) {
  261. s32 priority = ready_queue.contains(t.get());
  262. if (priority != -1) {
  263. LOG_DEBUG(Kernel, "0x%02X %u", priority, t->GetObjectId());
  264. }
  265. }
  266. }
  267. /**
  268. * Finds a free location for the TLS section of a thread.
  269. * @param tls_slots The TLS page array of the thread's owner process.
  270. * Returns a tuple of (page, slot, alloc_needed) where:
  271. * page: The index of the first allocated TLS page that has free slots.
  272. * slot: The index of the first free slot in the indicated page.
  273. * alloc_needed: Whether there's a need to allocate a new TLS page (All pages are full).
  274. */
  275. std::tuple<u32, u32, bool> GetFreeThreadLocalSlot(std::vector<std::bitset<8>>& tls_slots) {
  276. // Iterate over all the allocated pages, and try to find one where not all slots are used.
  277. for (unsigned page = 0; page < tls_slots.size(); ++page) {
  278. const auto& page_tls_slots = tls_slots[page];
  279. if (!page_tls_slots.all()) {
  280. // We found a page with at least one free slot, find which slot it is
  281. for (unsigned slot = 0; slot < page_tls_slots.size(); ++slot) {
  282. if (!page_tls_slots.test(slot)) {
  283. return std::make_tuple(page, slot, false);
  284. }
  285. }
  286. }
  287. }
  288. return std::make_tuple(0, 0, true);
  289. }
  290. /**
  291. * Resets a thread context, making it ready to be scheduled and run by the CPU
  292. * @param context Thread context to reset
  293. * @param stack_top Address of the top of the stack
  294. * @param entry_point Address of entry point for execution
  295. * @param arg User argument for thread
  296. */
  297. static void ResetThreadContext(ARM_Interface::ThreadContext& context, u32 stack_top,
  298. u32 entry_point, u32 arg) {
  299. memset(&context, 0, sizeof(ARM_Interface::ThreadContext));
  300. context.cpu_registers[0] = arg;
  301. context.pc = entry_point;
  302. context.sp = stack_top;
  303. context.cpsr = USER32MODE | ((entry_point & 1) << 5); // Usermode and THUMB mode
  304. }
  305. ResultVal<SharedPtr<Thread>> Thread::Create(std::string name, VAddr entry_point, u32 priority,
  306. u32 arg, s32 processor_id, VAddr stack_top) {
  307. // Check if priority is in ranged. Lowest priority -> highest priority id.
  308. if (priority > THREADPRIO_LOWEST) {
  309. LOG_ERROR(Kernel_SVC, "Invalid thread priority: %d", priority);
  310. return ERR_OUT_OF_RANGE;
  311. }
  312. if (processor_id > THREADPROCESSORID_MAX) {
  313. LOG_ERROR(Kernel_SVC, "Invalid processor id: %d", processor_id);
  314. return ERR_OUT_OF_RANGE_KERNEL;
  315. }
  316. // TODO(yuriks): Other checks, returning 0xD9001BEA
  317. if (!Memory::IsValidVirtualAddress(entry_point)) {
  318. LOG_ERROR(Kernel_SVC, "(name=%s): invalid entry %08x", name.c_str(), entry_point);
  319. // TODO: Verify error
  320. return ResultCode(ErrorDescription::InvalidAddress, ErrorModule::Kernel,
  321. ErrorSummary::InvalidArgument, ErrorLevel::Permanent);
  322. }
  323. SharedPtr<Thread> thread(new Thread);
  324. thread_list.push_back(thread);
  325. ready_queue.prepare(priority);
  326. thread->thread_id = NewThreadId();
  327. thread->status = THREADSTATUS_DORMANT;
  328. thread->entry_point = entry_point;
  329. thread->stack_top = stack_top;
  330. thread->nominal_priority = thread->current_priority = priority;
  331. thread->last_running_ticks = CoreTiming::GetTicks();
  332. thread->processor_id = processor_id;
  333. thread->wait_set_output = false;
  334. thread->wait_objects.clear();
  335. thread->wait_address = 0;
  336. thread->name = std::move(name);
  337. thread->callback_handle = wakeup_callback_handle_table.Create(thread).Unwrap();
  338. thread->owner_process = g_current_process;
  339. // Find the next available TLS index, and mark it as used
  340. auto& tls_slots = Kernel::g_current_process->tls_slots;
  341. bool needs_allocation = true;
  342. u32 available_page; // Which allocated page has free space
  343. u32 available_slot; // Which slot within the page is free
  344. std::tie(available_page, available_slot, needs_allocation) = GetFreeThreadLocalSlot(tls_slots);
  345. if (needs_allocation) {
  346. // There are no already-allocated pages with free slots, lets allocate a new one.
  347. // TLS pages are allocated from the BASE region in the linear heap.
  348. MemoryRegionInfo* memory_region = GetMemoryRegion(MemoryRegion::BASE);
  349. auto& linheap_memory = memory_region->linear_heap_memory;
  350. if (linheap_memory->size() + Memory::PAGE_SIZE > memory_region->size) {
  351. LOG_ERROR(Kernel_SVC,
  352. "Not enough space in region to allocate a new TLS page for thread");
  353. return ERR_OUT_OF_MEMORY;
  354. }
  355. u32 offset = linheap_memory->size();
  356. // Allocate some memory from the end of the linear heap for this region.
  357. linheap_memory->insert(linheap_memory->end(), Memory::PAGE_SIZE, 0);
  358. memory_region->used += Memory::PAGE_SIZE;
  359. Kernel::g_current_process->linear_heap_used += Memory::PAGE_SIZE;
  360. tls_slots.emplace_back(0); // The page is completely available at the start
  361. available_page = tls_slots.size() - 1;
  362. available_slot = 0; // Use the first slot in the new page
  363. auto& vm_manager = Kernel::g_current_process->vm_manager;
  364. vm_manager.RefreshMemoryBlockMappings(linheap_memory.get());
  365. // Map the page to the current process' address space.
  366. // TODO(Subv): Find the correct MemoryState for this region.
  367. vm_manager.MapMemoryBlock(Memory::TLS_AREA_VADDR + available_page * Memory::PAGE_SIZE,
  368. linheap_memory, offset, Memory::PAGE_SIZE, MemoryState::Private);
  369. }
  370. // Mark the slot as used
  371. tls_slots[available_page].set(available_slot);
  372. thread->tls_address = Memory::TLS_AREA_VADDR + available_page * Memory::PAGE_SIZE +
  373. available_slot * Memory::TLS_ENTRY_SIZE;
  374. // TODO(peachum): move to ScheduleThread() when scheduler is added so selected core is used
  375. // to initialize the context
  376. ResetThreadContext(thread->context, stack_top, entry_point, arg);
  377. ready_queue.push_back(thread->current_priority, thread.get());
  378. thread->status = THREADSTATUS_READY;
  379. return MakeResult<SharedPtr<Thread>>(std::move(thread));
  380. }
  381. void Thread::SetPriority(s32 priority) {
  382. ASSERT_MSG(priority <= THREADPRIO_LOWEST && priority >= THREADPRIO_HIGHEST,
  383. "Invalid priority value.");
  384. // If thread was ready, adjust queues
  385. if (status == THREADSTATUS_READY)
  386. ready_queue.move(this, current_priority, priority);
  387. else
  388. ready_queue.prepare(priority);
  389. nominal_priority = current_priority = priority;
  390. }
  391. void Thread::UpdatePriority() {
  392. s32 best_priority = nominal_priority;
  393. for (auto& mutex : held_mutexes) {
  394. if (mutex->priority < best_priority)
  395. best_priority = mutex->priority;
  396. }
  397. BoostPriority(best_priority);
  398. }
  399. void Thread::BoostPriority(s32 priority) {
  400. // If thread was ready, adjust queues
  401. if (status == THREADSTATUS_READY)
  402. ready_queue.move(this, current_priority, priority);
  403. else
  404. ready_queue.prepare(priority);
  405. current_priority = priority;
  406. }
  407. SharedPtr<Thread> SetupMainThread(u32 entry_point, s32 priority) {
  408. DEBUG_ASSERT(!GetCurrentThread());
  409. // Initialize new "main" thread
  410. auto thread_res = Thread::Create("main", entry_point, priority, 0, THREADPROCESSORID_0,
  411. Memory::HEAP_VADDR_END);
  412. SharedPtr<Thread> thread = std::move(thread_res).Unwrap();
  413. thread->context.fpscr =
  414. FPSCR_DEFAULT_NAN | FPSCR_FLUSH_TO_ZERO | FPSCR_ROUND_TOZERO | FPSCR_IXC; // 0x03C00010
  415. // Run new "main" thread
  416. SwitchContext(thread.get());
  417. return thread;
  418. }
  419. bool HaveReadyThreads() {
  420. return ready_queue.get_first() != nullptr;
  421. }
  422. void Reschedule() {
  423. Thread* cur = GetCurrentThread();
  424. Thread* next = PopNextReadyThread();
  425. if (cur && next) {
  426. LOG_TRACE(Kernel, "context switch %u -> %u", cur->GetObjectId(), next->GetObjectId());
  427. } else if (cur) {
  428. LOG_TRACE(Kernel, "context switch %u -> idle", cur->GetObjectId());
  429. } else if (next) {
  430. LOG_TRACE(Kernel, "context switch idle -> %u", next->GetObjectId());
  431. }
  432. SwitchContext(next);
  433. }
  434. void Thread::SetWaitSynchronizationResult(ResultCode result) {
  435. context.cpu_registers[0] = result.raw;
  436. }
  437. void Thread::SetWaitSynchronizationOutput(s32 output) {
  438. context.cpu_registers[1] = output;
  439. }
  440. s32 Thread::GetWaitObjectIndex(WaitObject* object) const {
  441. ASSERT_MSG(!wait_objects.empty(), "Thread is not waiting for anything");
  442. auto match = std::find(wait_objects.rbegin(), wait_objects.rend(), object);
  443. return std::distance(match, wait_objects.rend()) - 1;
  444. }
  445. ////////////////////////////////////////////////////////////////////////////////////////////////////
  446. void ThreadingInit() {
  447. ThreadWakeupEventType = CoreTiming::RegisterEvent("ThreadWakeupCallback", ThreadWakeupCallback);
  448. current_thread = nullptr;
  449. next_thread_id = 1;
  450. }
  451. void ThreadingShutdown() {
  452. current_thread = nullptr;
  453. for (auto& t : thread_list) {
  454. t->Stop();
  455. }
  456. thread_list.clear();
  457. ready_queue.clear();
  458. }
  459. const std::vector<SharedPtr<Thread>>& GetThreadList() {
  460. return thread_list;
  461. }
  462. } // namespace