thread.cpp 19 KB

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