thread.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  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/common.h"
  8. #include "common/thread_queue_list.h"
  9. #include "core/arm/arm_interface.h"
  10. #include "core/core.h"
  11. #include "core/core_timing.h"
  12. #include "core/hle/hle.h"
  13. #include "core/hle/kernel/kernel.h"
  14. #include "core/hle/kernel/thread.h"
  15. #include "core/hle/kernel/mutex.h"
  16. #include "core/hle/result.h"
  17. #include "core/mem_map.h"
  18. namespace Kernel {
  19. bool Thread::ShouldWait() {
  20. return status != THREADSTATUS_DORMANT;
  21. }
  22. void Thread::Acquire() {
  23. _assert_msg_(Kernel, !ShouldWait(), "object unavailable!");
  24. }
  25. // Lists all thread ids that aren't deleted/etc.
  26. static std::vector<SharedPtr<Thread>> thread_list;
  27. // Lists only ready thread ids.
  28. static Common::ThreadQueueList<Thread*, THREADPRIO_LOWEST+1> thread_ready_queue;
  29. static Thread* current_thread;
  30. static const u32 INITIAL_THREAD_ID = 1; ///< The first available thread id at startup
  31. static u32 next_thread_id; ///< The next available thread id
  32. Thread::Thread() {
  33. }
  34. Thread* GetCurrentThread() {
  35. return current_thread;
  36. }
  37. /// Resets a thread
  38. static void ResetThread(Thread* t, u32 arg, s32 lowest_priority) {
  39. memset(&t->context, 0, sizeof(Core::ThreadContext));
  40. t->context.cpu_registers[0] = arg;
  41. t->context.pc = t->entry_point;
  42. t->context.sp = t->stack_top;
  43. t->context.cpsr = 0x1F; // Usermode
  44. // TODO(bunnei): This instructs the CPU core to start the execution as if it is "resuming" a
  45. // thread. This is somewhat Sky-Eye specific, and should be re-architected in the future to be
  46. // agnostic of the CPU core.
  47. t->context.mode = 8;
  48. if (t->current_priority < lowest_priority) {
  49. t->current_priority = t->initial_priority;
  50. }
  51. t->wait_objects.clear();
  52. t->wait_address = 0;
  53. }
  54. /// Change a thread to "ready" state
  55. static void ChangeReadyState(Thread* t, bool ready) {
  56. if (t->IsReady()) {
  57. if (!ready) {
  58. thread_ready_queue.remove(t->current_priority, t);
  59. }
  60. } else if (ready) {
  61. if (t->IsRunning()) {
  62. thread_ready_queue.push_front(t->current_priority, t);
  63. } else {
  64. thread_ready_queue.push_back(t->current_priority, t);
  65. }
  66. t->status = THREADSTATUS_READY;
  67. }
  68. }
  69. /// Check if a thread is waiting on a the specified wait object
  70. static bool CheckWait_WaitObject(const Thread* thread, WaitObject* wait_object) {
  71. auto itr = std::find(thread->wait_objects.begin(), thread->wait_objects.end(), wait_object);
  72. if (itr != thread->wait_objects.end())
  73. return thread->IsWaiting();
  74. return false;
  75. }
  76. /// Check if the specified thread is waiting on the specified address to be arbitrated
  77. static bool CheckWait_AddressArbiter(const Thread* thread, VAddr wait_address) {
  78. return thread->IsWaiting() && thread->wait_objects.empty() && wait_address == thread->wait_address;
  79. }
  80. /// Stops the current thread
  81. void Thread::Stop(const char* reason) {
  82. // Release all the mutexes that this thread holds
  83. ReleaseThreadMutexes(this);
  84. ChangeReadyState(this, false);
  85. status = THREADSTATUS_DORMANT;
  86. WakeupAllWaitingThreads();
  87. // Stopped threads are never waiting.
  88. wait_objects.clear();
  89. wait_address = 0;
  90. }
  91. /// Changes a threads state
  92. static void ChangeThreadState(Thread* t, ThreadStatus new_status) {
  93. if (!t || t->status == new_status) {
  94. return;
  95. }
  96. ChangeReadyState(t, (new_status & THREADSTATUS_READY) != 0);
  97. t->status = new_status;
  98. }
  99. /// Arbitrate the highest priority thread that is waiting
  100. Thread* ArbitrateHighestPriorityThread(u32 address) {
  101. Thread* highest_priority_thread = nullptr;
  102. s32 priority = THREADPRIO_LOWEST;
  103. // Iterate through threads, find highest priority thread that is waiting to be arbitrated...
  104. for (auto& thread : thread_list) {
  105. if (!CheckWait_AddressArbiter(thread.get(), address))
  106. continue;
  107. if (thread == nullptr)
  108. continue;
  109. if(thread->current_priority <= priority) {
  110. highest_priority_thread = thread.get();
  111. priority = thread->current_priority;
  112. }
  113. }
  114. // If a thread was arbitrated, resume it
  115. if (nullptr != highest_priority_thread) {
  116. highest_priority_thread->ResumeFromWait();
  117. }
  118. return highest_priority_thread;
  119. }
  120. /// Arbitrate all threads currently waiting
  121. void ArbitrateAllThreads(u32 address) {
  122. // Iterate through threads, find highest priority thread that is waiting to be arbitrated...
  123. for (auto& thread : thread_list) {
  124. if (CheckWait_AddressArbiter(thread.get(), address))
  125. thread->ResumeFromWait();
  126. }
  127. }
  128. /// Calls a thread by marking it as "ready" (note: will not actually execute until current thread yields)
  129. static void CallThread(Thread* t) {
  130. // Stop waiting
  131. ChangeThreadState(t, THREADSTATUS_READY);
  132. }
  133. /// Switches CPU context to that of the specified thread
  134. static void SwitchContext(Thread* t) {
  135. Thread* cur = GetCurrentThread();
  136. // Save context for current thread
  137. if (cur) {
  138. Core::g_app_core->SaveContext(cur->context);
  139. if (cur->IsRunning()) {
  140. ChangeReadyState(cur, true);
  141. }
  142. }
  143. // Load context of new thread
  144. if (t) {
  145. current_thread = t;
  146. ChangeReadyState(t, false);
  147. t->status = (t->status | THREADSTATUS_RUNNING) & ~THREADSTATUS_READY;
  148. Core::g_app_core->LoadContext(t->context);
  149. } else {
  150. current_thread = nullptr;
  151. }
  152. }
  153. /// Gets the next thread that is ready to be run by priority
  154. static Thread* NextThread() {
  155. Thread* next;
  156. Thread* cur = GetCurrentThread();
  157. if (cur && cur->IsRunning()) {
  158. next = thread_ready_queue.pop_first_better(cur->current_priority);
  159. } else {
  160. next = thread_ready_queue.pop_first();
  161. }
  162. if (next == 0) {
  163. return nullptr;
  164. }
  165. return next;
  166. }
  167. void WaitCurrentThread_Sleep() {
  168. Thread* thread = GetCurrentThread();
  169. ChangeThreadState(thread, ThreadStatus(THREADSTATUS_WAIT | (thread->status & THREADSTATUS_SUSPEND)));
  170. }
  171. void WaitCurrentThread_WaitSynchronization(SharedPtr<WaitObject> wait_object, bool wait_set_output, bool wait_all) {
  172. Thread* thread = GetCurrentThread();
  173. thread->wait_set_output = wait_set_output;
  174. thread->wait_all = wait_all;
  175. // It's possible to call WaitSynchronizationN without any objects passed in...
  176. if (wait_object != nullptr)
  177. thread->wait_objects.push_back(wait_object);
  178. ChangeThreadState(thread, ThreadStatus(THREADSTATUS_WAIT | (thread->status & THREADSTATUS_SUSPEND)));
  179. }
  180. void WaitCurrentThread_ArbitrateAddress(VAddr wait_address) {
  181. Thread* thread = GetCurrentThread();
  182. thread->wait_address = wait_address;
  183. ChangeThreadState(thread, ThreadStatus(THREADSTATUS_WAIT | (thread->status & THREADSTATUS_SUSPEND)));
  184. }
  185. /// Event type for the thread wake up event
  186. static int ThreadWakeupEventType = -1;
  187. // TODO(yuriks): This can be removed if Thread objects are explicitly pooled in the future, allowing
  188. // us to simply use a pool index or similar.
  189. static Kernel::HandleTable wakeup_callback_handle_table;
  190. /// Callback that will wake up the thread it was scheduled for
  191. static void ThreadWakeupCallback(u64 thread_handle, int cycles_late) {
  192. SharedPtr<Thread> thread = wakeup_callback_handle_table.Get<Thread>((Handle)thread_handle);
  193. if (thread == nullptr) {
  194. LOG_CRITICAL(Kernel, "Callback fired for invalid thread %08X", thread_handle);
  195. return;
  196. }
  197. thread->SetWaitSynchronizationResult(ResultCode(ErrorDescription::Timeout, ErrorModule::OS,
  198. ErrorSummary::StatusChanged, ErrorLevel::Info));
  199. if (thread->wait_set_output)
  200. thread->SetWaitSynchronizationOutput(-1);
  201. thread->ResumeFromWait();
  202. }
  203. void Thread::WakeAfterDelay(s64 nanoseconds) {
  204. // Don't schedule a wakeup if the thread wants to wait forever
  205. if (nanoseconds == -1)
  206. return;
  207. u64 microseconds = nanoseconds / 1000;
  208. CoreTiming::ScheduleEvent(usToCycles(microseconds), ThreadWakeupEventType, callback_handle);
  209. }
  210. void Thread::ReleaseWaitObject(WaitObject* wait_object) {
  211. if (wait_objects.empty()) {
  212. LOG_CRITICAL(Kernel, "thread is not waiting on any objects!");
  213. return;
  214. }
  215. // Remove this thread from the waiting object's thread list
  216. wait_object->RemoveWaitingThread(this);
  217. unsigned index = 0;
  218. bool wait_all_failed = false; // Will be set to true if any object is unavailable
  219. // Iterate through all waiting objects to check availability...
  220. for (auto itr = wait_objects.begin(); itr != wait_objects.end(); ++itr) {
  221. if ((*itr)->ShouldWait())
  222. wait_all_failed = true;
  223. // The output should be the last index of wait_object
  224. if (*itr == wait_object)
  225. index = itr - wait_objects.begin();
  226. }
  227. // If we are waiting on all objects...
  228. if (wait_all) {
  229. // Resume the thread only if all are available...
  230. if (!wait_all_failed) {
  231. SetWaitSynchronizationResult(RESULT_SUCCESS);
  232. SetWaitSynchronizationOutput(-1);
  233. ResumeFromWait();
  234. }
  235. } else {
  236. // Otherwise, resume
  237. SetWaitSynchronizationResult(RESULT_SUCCESS);
  238. if (wait_set_output)
  239. SetWaitSynchronizationOutput(index);
  240. ResumeFromWait();
  241. }
  242. }
  243. void Thread::ResumeFromWait() {
  244. // Cancel any outstanding wakeup events
  245. CoreTiming::UnscheduleEvent(ThreadWakeupEventType, callback_handle);
  246. status &= ~THREADSTATUS_WAIT;
  247. // Remove this thread from all other WaitObjects
  248. for (auto wait_object : wait_objects)
  249. wait_object->RemoveWaitingThread(this);
  250. wait_objects.clear();
  251. wait_set_output = false;
  252. wait_all = false;
  253. wait_address = 0;
  254. if (!(status & (THREADSTATUS_WAITSUSPEND | THREADSTATUS_DORMANT | THREADSTATUS_DEAD))) {
  255. ChangeReadyState(this, true);
  256. }
  257. }
  258. /// Prints the thread queue for debugging purposes
  259. static void DebugThreadQueue() {
  260. Thread* thread = GetCurrentThread();
  261. if (!thread) {
  262. return;
  263. }
  264. LOG_DEBUG(Kernel, "0x%02X %u (current)", thread->current_priority, GetCurrentThread()->GetObjectId());
  265. for (auto& t : thread_list) {
  266. s32 priority = thread_ready_queue.contains(t.get());
  267. if (priority != -1) {
  268. LOG_DEBUG(Kernel, "0x%02X %u", priority, t->GetObjectId());
  269. }
  270. }
  271. }
  272. ResultVal<SharedPtr<Thread>> Thread::Create(std::string name, VAddr entry_point, s32 priority,
  273. u32 arg, s32 processor_id, VAddr stack_top, u32 stack_size) {
  274. if (stack_size < 0x200) {
  275. LOG_ERROR(Kernel, "(name=%s): invalid stack_size=0x%08X", name.c_str(), stack_size);
  276. // TODO: Verify error
  277. return ResultCode(ErrorDescription::InvalidSize, ErrorModule::Kernel,
  278. ErrorSummary::InvalidArgument, ErrorLevel::Permanent);
  279. }
  280. if (priority < THREADPRIO_HIGHEST || priority > THREADPRIO_LOWEST) {
  281. s32 new_priority = CLAMP(priority, THREADPRIO_HIGHEST, THREADPRIO_LOWEST);
  282. LOG_WARNING(Kernel_SVC, "(name=%s): invalid priority=%d, clamping to %d",
  283. name.c_str(), priority, new_priority);
  284. // TODO(bunnei): Clamping to a valid priority is not necessarily correct behavior... Confirm
  285. // validity of this
  286. priority = new_priority;
  287. }
  288. if (!Memory::GetPointer(entry_point)) {
  289. LOG_ERROR(Kernel_SVC, "(name=%s): invalid entry %08x", name.c_str(), entry_point);
  290. // TODO: Verify error
  291. return ResultCode(ErrorDescription::InvalidAddress, ErrorModule::Kernel,
  292. ErrorSummary::InvalidArgument, ErrorLevel::Permanent);
  293. }
  294. SharedPtr<Thread> thread(new Thread);
  295. // TODO(yuriks): Thread requires a handle to be inserted into the various scheduling queues for
  296. // the time being. Create a handle here, it will be copied to the handle field in
  297. // the object and use by the rest of the code. This should be removed when other
  298. // code doesn't rely on the handle anymore.
  299. ResultVal<Handle> handle = Kernel::g_handle_table.Create(thread);
  300. if (handle.Failed())
  301. return handle.Code();
  302. thread_list.push_back(thread);
  303. thread_ready_queue.prepare(priority);
  304. thread->thread_id = next_thread_id++;
  305. thread->status = THREADSTATUS_DORMANT;
  306. thread->entry_point = entry_point;
  307. thread->stack_top = stack_top;
  308. thread->stack_size = stack_size;
  309. thread->initial_priority = thread->current_priority = priority;
  310. thread->processor_id = processor_id;
  311. thread->wait_set_output = false;
  312. thread->wait_all = false;
  313. thread->wait_objects.clear();
  314. thread->wait_address = 0;
  315. thread->name = std::move(name);
  316. thread->callback_handle = wakeup_callback_handle_table.Create(thread).MoveFrom();
  317. ResetThread(thread.get(), arg, 0);
  318. CallThread(thread.get());
  319. return MakeResult<SharedPtr<Thread>>(std::move(thread));
  320. }
  321. /// Set the priority of the thread specified by handle
  322. void Thread::SetPriority(s32 priority) {
  323. // If priority is invalid, clamp to valid range
  324. if (priority < THREADPRIO_HIGHEST || priority > THREADPRIO_LOWEST) {
  325. s32 new_priority = CLAMP(priority, THREADPRIO_HIGHEST, THREADPRIO_LOWEST);
  326. LOG_WARNING(Kernel_SVC, "invalid priority=%d, clamping to %d", priority, new_priority);
  327. // TODO(bunnei): Clamping to a valid priority is not necessarily correct behavior... Confirm
  328. // validity of this
  329. priority = new_priority;
  330. }
  331. // Change thread priority
  332. s32 old = current_priority;
  333. thread_ready_queue.remove(old, this);
  334. current_priority = priority;
  335. thread_ready_queue.prepare(current_priority);
  336. // Change thread status to "ready" and push to ready queue
  337. if (IsRunning()) {
  338. status = (status & ~THREADSTATUS_RUNNING) | THREADSTATUS_READY;
  339. }
  340. if (IsReady()) {
  341. thread_ready_queue.push_back(current_priority, this);
  342. }
  343. }
  344. SharedPtr<Thread> SetupIdleThread() {
  345. // We need to pass a few valid values to get around parameter checking in Thread::Create.
  346. auto thread = Thread::Create("idle", Memory::KERNEL_MEMORY_VADDR, THREADPRIO_LOWEST, 0,
  347. THREADPROCESSORID_0, 0, Kernel::DEFAULT_STACK_SIZE).MoveFrom();
  348. thread->idle = true;
  349. CallThread(thread.get());
  350. return thread;
  351. }
  352. SharedPtr<Thread> SetupMainThread(s32 priority, u32 stack_size) {
  353. // Initialize new "main" thread
  354. auto thread_res = Thread::Create("main", Core::g_app_core->GetPC(), priority, 0,
  355. THREADPROCESSORID_0, Memory::SCRATCHPAD_VADDR_END, stack_size);
  356. // TODO(yuriks): Propagate error
  357. _dbg_assert_(Kernel, thread_res.Succeeded());
  358. SharedPtr<Thread> thread = std::move(*thread_res);
  359. // If running another thread already, set it to "ready" state
  360. Thread* cur = GetCurrentThread();
  361. if (cur && cur->IsRunning()) {
  362. ChangeReadyState(cur, true);
  363. }
  364. // Run new "main" thread
  365. current_thread = thread.get();
  366. thread->status = THREADSTATUS_RUNNING;
  367. Core::g_app_core->LoadContext(thread->context);
  368. return thread;
  369. }
  370. /// Reschedules to the next available thread (call after current thread is suspended)
  371. void Reschedule() {
  372. Thread* prev = GetCurrentThread();
  373. Thread* next = NextThread();
  374. HLE::g_reschedule = false;
  375. if (next != nullptr) {
  376. LOG_TRACE(Kernel, "context switch %u -> %u", prev->GetObjectId(), next->GetObjectId());
  377. SwitchContext(next);
  378. } else {
  379. LOG_TRACE(Kernel, "cannot context switch from %u, no higher priority thread!", prev->GetObjectId());
  380. for (auto& thread : thread_list) {
  381. LOG_TRACE(Kernel, "\tid=%u prio=0x%02X, status=0x%08X", thread->GetObjectId(),
  382. thread->current_priority, thread->status);
  383. }
  384. }
  385. }
  386. void Thread::SetWaitSynchronizationResult(ResultCode result) {
  387. context.cpu_registers[0] = result.raw;
  388. }
  389. void Thread::SetWaitSynchronizationOutput(s32 output) {
  390. context.cpu_registers[1] = output;
  391. }
  392. ////////////////////////////////////////////////////////////////////////////////////////////////////
  393. void ThreadingInit() {
  394. next_thread_id = INITIAL_THREAD_ID;
  395. ThreadWakeupEventType = CoreTiming::RegisterEvent("ThreadWakeupCallback", ThreadWakeupCallback);
  396. }
  397. void ThreadingShutdown() {
  398. }
  399. } // namespace