thread.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  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/hle.h"
  17. #include "core/hle/kernel/kernel.h"
  18. #include "core/hle/kernel/process.h"
  19. #include "core/hle/kernel/thread.h"
  20. #include "core/hle/kernel/mutex.h"
  21. #include "core/hle/result.h"
  22. #include "core/memory.h"
  23. namespace Kernel {
  24. /// Event type for the thread wake up event
  25. static int ThreadWakeupEventType;
  26. bool Thread::ShouldWait() {
  27. return status != THREADSTATUS_DEAD;
  28. }
  29. void Thread::Acquire() {
  30. ASSERT_MSG(!ShouldWait(), "object unavailable!");
  31. }
  32. // TODO(yuriks): This can be removed if Thread objects are explicitly pooled in the future, allowing
  33. // us to simply use a pool index or similar.
  34. static Kernel::HandleTable wakeup_callback_handle_table;
  35. // Lists all thread ids that aren't deleted/etc.
  36. static std::vector<SharedPtr<Thread>> thread_list;
  37. // Lists only ready thread ids.
  38. static Common::ThreadQueueList<Thread*, THREADPRIO_LOWEST+1> ready_queue;
  39. static Thread* current_thread;
  40. // The first available thread id at startup
  41. static u32 next_thread_id;
  42. /**
  43. * Creates a new thread ID
  44. * @return The new thread ID
  45. */
  46. inline static u32 const NewThreadId() {
  47. return next_thread_id++;
  48. }
  49. Thread::Thread() {}
  50. Thread::~Thread() {}
  51. Thread* GetCurrentThread() {
  52. return current_thread;
  53. }
  54. /**
  55. * Check if a thread is waiting on the specified wait object
  56. * @param thread The thread to test
  57. * @param wait_object The object to test against
  58. * @return True if the thread is waiting, false otherwise
  59. */
  60. static bool CheckWait_WaitObject(const Thread* thread, WaitObject* wait_object) {
  61. if (thread->status != THREADSTATUS_WAIT_SYNCH)
  62. return false;
  63. auto itr = std::find(thread->wait_objects.begin(), thread->wait_objects.end(), wait_object);
  64. return itr != thread->wait_objects.end();
  65. }
  66. /**
  67. * Check if the specified thread is waiting on the specified address to be arbitrated
  68. * @param thread The thread to test
  69. * @param wait_address The address to test against
  70. * @return True if the thread is waiting, false otherwise
  71. */
  72. static bool CheckWait_AddressArbiter(const Thread* thread, VAddr wait_address) {
  73. return thread->status == THREADSTATUS_WAIT_ARB && wait_address == thread->wait_address;
  74. }
  75. void Thread::Stop() {
  76. // Release all the mutexes that this thread holds
  77. ReleaseThreadMutexes(this);
  78. // Cancel any outstanding wakeup events for this thread
  79. CoreTiming::UnscheduleEvent(ThreadWakeupEventType, callback_handle);
  80. wakeup_callback_handle_table.Close(callback_handle);
  81. callback_handle = 0;
  82. // Clean up thread from ready queue
  83. // This is only needed when the thread is termintated forcefully (SVC TerminateProcess)
  84. if (status == THREADSTATUS_READY){
  85. ready_queue.remove(current_priority, this);
  86. }
  87. status = THREADSTATUS_DEAD;
  88. WakeupAllWaitingThreads();
  89. // Clean up any dangling references in objects that this thread was waiting for
  90. for (auto& wait_object : wait_objects) {
  91. wait_object->RemoveWaitingThread(this);
  92. }
  93. wait_objects.clear();
  94. Kernel::g_current_process->used_tls_slots[tls_index] = false;
  95. g_current_process->misc_memory_used -= Memory::TLS_ENTRY_SIZE;
  96. HLE::Reschedule(__func__);
  97. }
  98. Thread* ArbitrateHighestPriorityThread(u32 address) {
  99. Thread* highest_priority_thread = nullptr;
  100. s32 priority = THREADPRIO_LOWEST;
  101. // Iterate through threads, find highest priority thread that is waiting to be arbitrated...
  102. for (auto& thread : thread_list) {
  103. if (!CheckWait_AddressArbiter(thread.get(), address))
  104. continue;
  105. if (thread == nullptr)
  106. continue;
  107. if(thread->current_priority <= priority) {
  108. highest_priority_thread = thread.get();
  109. priority = thread->current_priority;
  110. }
  111. }
  112. // If a thread was arbitrated, resume it
  113. if (nullptr != highest_priority_thread) {
  114. highest_priority_thread->ResumeFromWait();
  115. }
  116. return highest_priority_thread;
  117. }
  118. void ArbitrateAllThreads(u32 address) {
  119. // Resume all threads found to be waiting on the address
  120. for (auto& thread : thread_list) {
  121. if (CheckWait_AddressArbiter(thread.get(), address))
  122. thread->ResumeFromWait();
  123. }
  124. }
  125. /// Boost low priority threads (temporarily) that have been starved
  126. static void PriorityBoostStarvedThreads() {
  127. u64 current_ticks = CoreTiming::GetTicks();
  128. for (auto& thread : thread_list) {
  129. // TODO(bunnei): Threads that have been waiting to be scheduled for `boost_ticks` (or
  130. // longer) will have their priority temporarily adjusted to 1 higher than the highest
  131. // priority thread to prevent thread starvation. This general behavior has been verified
  132. // on hardware. However, this is almost certainly not perfect, and the real CTR OS scheduler
  133. // should probably be reversed to verify this.
  134. const u64 boost_timeout = 2000000; // Boost threads that have been ready for > this long
  135. u64 delta = current_ticks - thread->last_running_ticks;
  136. if (thread->status == THREADSTATUS_READY && delta > boost_timeout) {
  137. const s32 priority = std::max(ready_queue.get_first()->current_priority - 1, 0);
  138. thread->BoostPriority(priority);
  139. }
  140. }
  141. }
  142. /**
  143. * Switches the CPU's active thread context to that of the specified thread
  144. * @param new_thread The thread to switch to
  145. */
  146. static void SwitchContext(Thread* new_thread) {
  147. Thread* previous_thread = GetCurrentThread();
  148. // Save context for previous thread
  149. if (previous_thread) {
  150. previous_thread->last_running_ticks = CoreTiming::GetTicks();
  151. Core::g_app_core->SaveContext(previous_thread->context);
  152. if (previous_thread->status == THREADSTATUS_RUNNING) {
  153. // This is only the case when a reschedule is triggered without the current thread
  154. // yielding execution (i.e. an event triggered, system core time-sliced, etc)
  155. ready_queue.push_front(previous_thread->current_priority, previous_thread);
  156. previous_thread->status = THREADSTATUS_READY;
  157. }
  158. }
  159. // Load context of new thread
  160. if (new_thread) {
  161. DEBUG_ASSERT_MSG(new_thread->status == THREADSTATUS_READY, "Thread must be ready to become running.");
  162. // Cancel any outstanding wakeup events for this thread
  163. CoreTiming::UnscheduleEvent(ThreadWakeupEventType, new_thread->callback_handle);
  164. current_thread = new_thread;
  165. // If the thread was waited by a svcWaitSynch call, step back PC by one instruction to rerun
  166. // the SVC when the thread wakes up. This is necessary to ensure that the thread can acquire
  167. // the requested wait object(s) before continuing.
  168. if (new_thread->waitsynch_waited) {
  169. // CPSR flag indicates CPU mode
  170. bool thumb_mode = (new_thread->context.cpsr & TBIT) != 0;
  171. // SVC instruction is 2 bytes for THUMB, 4 bytes for ARM
  172. new_thread->context.pc -= thumb_mode ? 2 : 4;
  173. }
  174. // Clean up the thread's wait_objects, they'll be restored if needed during
  175. // the svcWaitSynchronization call
  176. for (int i = 0; i < new_thread->wait_objects.size(); ++i) {
  177. SharedPtr<WaitObject> object = new_thread->wait_objects[i];
  178. object->RemoveWaitingThread(new_thread);
  179. }
  180. new_thread->wait_objects.clear();
  181. ready_queue.remove(new_thread->current_priority, new_thread);
  182. new_thread->status = THREADSTATUS_RUNNING;
  183. // Restores thread to its nominal priority if it has been temporarily changed
  184. new_thread->current_priority = new_thread->nominal_priority;
  185. Core::g_app_core->LoadContext(new_thread->context);
  186. Core::g_app_core->SetCP15Register(CP15_THREAD_URO, new_thread->GetTLSAddress());
  187. } else {
  188. current_thread = nullptr;
  189. }
  190. }
  191. /**
  192. * Pops and returns the next thread from the thread queue
  193. * @return A pointer to the next ready thread
  194. */
  195. static Thread* PopNextReadyThread() {
  196. Thread* next;
  197. Thread* thread = GetCurrentThread();
  198. if (thread && thread->status == THREADSTATUS_RUNNING) {
  199. // We have to do better than the current thread.
  200. // This call returns null when that's not possible.
  201. next = ready_queue.pop_first_better(thread->current_priority);
  202. if (!next) {
  203. // Otherwise just keep going with the current thread
  204. next = thread;
  205. }
  206. } else {
  207. next = ready_queue.pop_first();
  208. }
  209. return next;
  210. }
  211. void WaitCurrentThread_Sleep() {
  212. Thread* thread = GetCurrentThread();
  213. thread->status = THREADSTATUS_WAIT_SLEEP;
  214. HLE::Reschedule(__func__);
  215. }
  216. void WaitCurrentThread_WaitSynchronization(std::vector<SharedPtr<WaitObject>> wait_objects, bool wait_set_output, bool wait_all) {
  217. Thread* thread = GetCurrentThread();
  218. thread->wait_set_output = wait_set_output;
  219. thread->wait_all = wait_all;
  220. thread->wait_objects = std::move(wait_objects);
  221. thread->waitsynch_waited = true;
  222. thread->status = THREADSTATUS_WAIT_SYNCH;
  223. }
  224. void WaitCurrentThread_ArbitrateAddress(VAddr wait_address) {
  225. Thread* thread = GetCurrentThread();
  226. thread->wait_address = wait_address;
  227. thread->status = THREADSTATUS_WAIT_ARB;
  228. }
  229. /**
  230. * Callback that will wake up the thread it was scheduled for
  231. * @param thread_handle The handle of the thread that's been awoken
  232. * @param cycles_late The number of CPU cycles that have passed since the desired wakeup time
  233. */
  234. static void ThreadWakeupCallback(u64 thread_handle, int cycles_late) {
  235. SharedPtr<Thread> thread = wakeup_callback_handle_table.Get<Thread>((Handle)thread_handle);
  236. if (thread == nullptr) {
  237. LOG_CRITICAL(Kernel, "Callback fired for invalid thread %08X", (Handle)thread_handle);
  238. return;
  239. }
  240. thread->waitsynch_waited = false;
  241. if (thread->status == THREADSTATUS_WAIT_SYNCH) {
  242. thread->SetWaitSynchronizationResult(ResultCode(ErrorDescription::Timeout, ErrorModule::OS,
  243. ErrorSummary::StatusChanged, ErrorLevel::Info));
  244. if (thread->wait_set_output)
  245. thread->SetWaitSynchronizationOutput(-1);
  246. }
  247. thread->ResumeFromWait();
  248. }
  249. void Thread::WakeAfterDelay(s64 nanoseconds) {
  250. // Don't schedule a wakeup if the thread wants to wait forever
  251. if (nanoseconds == -1)
  252. return;
  253. u64 microseconds = nanoseconds / 1000;
  254. CoreTiming::ScheduleEvent(usToCycles(microseconds), ThreadWakeupEventType, callback_handle);
  255. }
  256. void Thread::ResumeFromWait() {
  257. switch (status) {
  258. case THREADSTATUS_WAIT_SYNCH:
  259. case THREADSTATUS_WAIT_ARB:
  260. case THREADSTATUS_WAIT_SLEEP:
  261. break;
  262. case THREADSTATUS_READY:
  263. // If the thread is waiting on multiple wait objects, it might be awoken more than once
  264. // before actually resuming. We can ignore subsequent wakeups if the thread status has
  265. // already been set to THREADSTATUS_READY.
  266. return;
  267. case THREADSTATUS_RUNNING:
  268. DEBUG_ASSERT_MSG(false, "Thread with object id %u has already resumed.", GetObjectId());
  269. return;
  270. case THREADSTATUS_DEAD:
  271. // This should never happen, as threads must complete before being stopped.
  272. DEBUG_ASSERT_MSG(false, "Thread with object id %u cannot be resumed because it's DEAD.",
  273. GetObjectId());
  274. return;
  275. }
  276. ready_queue.push_back(current_priority, this);
  277. status = THREADSTATUS_READY;
  278. }
  279. /**
  280. * Prints the thread queue for debugging purposes
  281. */
  282. static void DebugThreadQueue() {
  283. Thread* thread = GetCurrentThread();
  284. if (!thread) {
  285. LOG_DEBUG(Kernel, "Current: NO CURRENT THREAD");
  286. } else {
  287. LOG_DEBUG(Kernel, "0x%02X %u (current)", thread->current_priority, GetCurrentThread()->GetObjectId());
  288. }
  289. for (auto& t : thread_list) {
  290. s32 priority = ready_queue.contains(t.get());
  291. if (priority != -1) {
  292. LOG_DEBUG(Kernel, "0x%02X %u", priority, t->GetObjectId());
  293. }
  294. }
  295. }
  296. ResultVal<SharedPtr<Thread>> Thread::Create(std::string name, VAddr entry_point, s32 priority,
  297. u32 arg, s32 processor_id, VAddr stack_top) {
  298. if (priority < THREADPRIO_HIGHEST || priority > THREADPRIO_LOWEST) {
  299. s32 new_priority = MathUtil::Clamp<s32>(priority, THREADPRIO_HIGHEST, THREADPRIO_LOWEST);
  300. LOG_WARNING(Kernel_SVC, "(name=%s): invalid priority=%d, clamping to %d",
  301. name.c_str(), priority, new_priority);
  302. // TODO(bunnei): Clamping to a valid priority is not necessarily correct behavior... Confirm
  303. // validity of this
  304. priority = new_priority;
  305. }
  306. if (!Memory::GetPointer(entry_point)) {
  307. LOG_ERROR(Kernel_SVC, "(name=%s): invalid entry %08x", name.c_str(), entry_point);
  308. // TODO: Verify error
  309. return ResultCode(ErrorDescription::InvalidAddress, ErrorModule::Kernel,
  310. ErrorSummary::InvalidArgument, ErrorLevel::Permanent);
  311. }
  312. SharedPtr<Thread> thread(new Thread);
  313. thread_list.push_back(thread);
  314. ready_queue.prepare(priority);
  315. thread->thread_id = NewThreadId();
  316. thread->status = THREADSTATUS_DORMANT;
  317. thread->entry_point = entry_point;
  318. thread->stack_top = stack_top;
  319. thread->nominal_priority = thread->current_priority = priority;
  320. thread->last_running_ticks = CoreTiming::GetTicks();
  321. thread->processor_id = processor_id;
  322. thread->wait_set_output = false;
  323. thread->wait_all = 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).MoveFrom();
  328. thread->owner_process = g_current_process;
  329. thread->tls_index = -1;
  330. thread->waitsynch_waited = false;
  331. // Find the next available TLS index, and mark it as used
  332. auto& used_tls_slots = Kernel::g_current_process->used_tls_slots;
  333. for (unsigned int i = 0; i < used_tls_slots.size(); ++i) {
  334. if (used_tls_slots[i] == false) {
  335. thread->tls_index = i;
  336. used_tls_slots[i] = true;
  337. break;
  338. }
  339. }
  340. ASSERT_MSG(thread->tls_index != -1, "Out of TLS space");
  341. g_current_process->misc_memory_used += Memory::TLS_ENTRY_SIZE;
  342. // TODO(peachum): move to ScheduleThread() when scheduler is added so selected core is used
  343. // to initialize the context
  344. Core::g_app_core->ResetContext(thread->context, stack_top, entry_point, arg);
  345. ready_queue.push_back(thread->current_priority, thread.get());
  346. thread->status = THREADSTATUS_READY;
  347. HLE::Reschedule(__func__);
  348. return MakeResult<SharedPtr<Thread>>(std::move(thread));
  349. }
  350. // TODO(peachum): Remove this. Range checking should be done, and an appropriate error should be returned.
  351. static void ClampPriority(const Thread* thread, s32* priority) {
  352. if (*priority < THREADPRIO_HIGHEST || *priority > THREADPRIO_LOWEST) {
  353. DEBUG_ASSERT_MSG(false, "Application passed an out of range priority. An error should be returned.");
  354. s32 new_priority = MathUtil::Clamp<s32>(*priority, THREADPRIO_HIGHEST, THREADPRIO_LOWEST);
  355. LOG_WARNING(Kernel_SVC, "(name=%s): invalid priority=%d, clamping to %d",
  356. thread->name.c_str(), *priority, new_priority);
  357. // TODO(bunnei): Clamping to a valid priority is not necessarily correct behavior... Confirm
  358. // validity of this
  359. *priority = new_priority;
  360. }
  361. }
  362. void Thread::SetPriority(s32 priority) {
  363. ClampPriority(this, &priority);
  364. // If thread was ready, adjust queues
  365. if (status == THREADSTATUS_READY)
  366. ready_queue.move(this, current_priority, priority);
  367. else
  368. ready_queue.prepare(priority);
  369. nominal_priority = current_priority = priority;
  370. }
  371. void Thread::BoostPriority(s32 priority) {
  372. ready_queue.move(this, current_priority, priority);
  373. current_priority = priority;
  374. }
  375. SharedPtr<Thread> SetupMainThread(u32 entry_point, s32 priority) {
  376. DEBUG_ASSERT(!GetCurrentThread());
  377. // Initialize new "main" thread
  378. auto thread_res = Thread::Create("main", entry_point, priority, 0,
  379. THREADPROCESSORID_0, Memory::HEAP_VADDR_END);
  380. SharedPtr<Thread> thread = thread_res.MoveFrom();
  381. // Run new "main" thread
  382. SwitchContext(thread.get());
  383. return thread;
  384. }
  385. void Reschedule() {
  386. PriorityBoostStarvedThreads();
  387. Thread* cur = GetCurrentThread();
  388. Thread* next = PopNextReadyThread();
  389. HLE::g_reschedule = false;
  390. // Don't bother switching to the same thread
  391. if (next == cur)
  392. return;
  393. if (cur && next) {
  394. LOG_TRACE(Kernel, "context switch %u -> %u", cur->GetObjectId(), next->GetObjectId());
  395. } else if (cur) {
  396. LOG_TRACE(Kernel, "context switch %u -> idle", cur->GetObjectId());
  397. } else if (next) {
  398. LOG_TRACE(Kernel, "context switch idle -> %u", next->GetObjectId());
  399. }
  400. SwitchContext(next);
  401. }
  402. void Thread::SetWaitSynchronizationResult(ResultCode result) {
  403. context.cpu_registers[0] = result.raw;
  404. }
  405. void Thread::SetWaitSynchronizationOutput(s32 output) {
  406. context.cpu_registers[1] = output;
  407. }
  408. VAddr Thread::GetTLSAddress() const {
  409. return Memory::TLS_AREA_VADDR + tls_index * Memory::TLS_ENTRY_SIZE;
  410. }
  411. ////////////////////////////////////////////////////////////////////////////////////////////////////
  412. void ThreadingInit() {
  413. ThreadWakeupEventType = CoreTiming::RegisterEvent("ThreadWakeupCallback", ThreadWakeupCallback);
  414. current_thread = nullptr;
  415. next_thread_id = 1;
  416. }
  417. void ThreadingShutdown() {
  418. current_thread = nullptr;
  419. for (auto& t : thread_list) {
  420. t->Stop();
  421. }
  422. thread_list.clear();
  423. ready_queue.clear();
  424. }
  425. } // namespace