thread.cpp 16 KB

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