thread.cpp 18 KB

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