thread.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  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 <cinttypes>
  6. #include <optional>
  7. #include <vector>
  8. #include "common/assert.h"
  9. #include "common/common_types.h"
  10. #include "common/logging/log.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/core_timing_util.h"
  16. #include "core/hardware_properties.h"
  17. #include "core/hle/kernel/errors.h"
  18. #include "core/hle/kernel/handle_table.h"
  19. #include "core/hle/kernel/kernel.h"
  20. #include "core/hle/kernel/object.h"
  21. #include "core/hle/kernel/process.h"
  22. #include "core/hle/kernel/scheduler.h"
  23. #include "core/hle/kernel/thread.h"
  24. #include "core/hle/result.h"
  25. #include "core/memory.h"
  26. namespace Kernel {
  27. bool Thread::ShouldWait(const Thread* thread) const {
  28. return status != ThreadStatus::Dead;
  29. }
  30. bool Thread::IsSignaled() const {
  31. return status == ThreadStatus::Dead;
  32. }
  33. void Thread::Acquire(Thread* thread) {
  34. ASSERT_MSG(!ShouldWait(thread), "object unavailable!");
  35. }
  36. Thread::Thread(KernelCore& kernel) : SynchronizationObject{kernel} {}
  37. Thread::~Thread() = default;
  38. void Thread::Stop() {
  39. // Cancel any outstanding wakeup events for this thread
  40. Core::System::GetInstance().CoreTiming().UnscheduleEvent(kernel.ThreadWakeupCallbackEventType(),
  41. global_handle);
  42. kernel.GlobalHandleTable().Close(global_handle);
  43. global_handle = 0;
  44. SetStatus(ThreadStatus::Dead);
  45. Signal();
  46. // Clean up any dangling references in objects that this thread was waiting for
  47. for (auto& wait_object : wait_objects) {
  48. wait_object->RemoveWaitingThread(SharedFrom(this));
  49. }
  50. wait_objects.clear();
  51. owner_process->UnregisterThread(this);
  52. // Mark the TLS slot in the thread's page as free.
  53. owner_process->FreeTLSRegion(tls_address);
  54. }
  55. void Thread::WakeAfterDelay(s64 nanoseconds) {
  56. // Don't schedule a wakeup if the thread wants to wait forever
  57. if (nanoseconds == -1)
  58. return;
  59. // This function might be called from any thread so we have to be cautious and use the
  60. // thread-safe version of ScheduleEvent.
  61. const s64 cycles = Core::Timing::nsToCycles(std::chrono::nanoseconds{nanoseconds});
  62. Core::System::GetInstance().CoreTiming().ScheduleEvent(
  63. cycles, kernel.ThreadWakeupCallbackEventType(), global_handle);
  64. }
  65. void Thread::CancelWakeupTimer() {
  66. Core::System::GetInstance().CoreTiming().UnscheduleEvent(kernel.ThreadWakeupCallbackEventType(),
  67. global_handle);
  68. }
  69. void Thread::ResumeFromWait() {
  70. ASSERT_MSG(wait_objects.empty(), "Thread is waking up while waiting for objects");
  71. switch (status) {
  72. case ThreadStatus::Paused:
  73. case ThreadStatus::WaitSynch:
  74. case ThreadStatus::WaitHLEEvent:
  75. case ThreadStatus::WaitSleep:
  76. case ThreadStatus::WaitIPC:
  77. case ThreadStatus::WaitMutex:
  78. case ThreadStatus::WaitCondVar:
  79. case ThreadStatus::WaitArb:
  80. case ThreadStatus::Dormant:
  81. break;
  82. case ThreadStatus::Ready:
  83. // The thread's wakeup callback must have already been cleared when the thread was first
  84. // awoken.
  85. ASSERT(wakeup_callback == nullptr);
  86. // If the thread is waiting on multiple wait objects, it might be awoken more than once
  87. // before actually resuming. We can ignore subsequent wakeups if the thread status has
  88. // already been set to ThreadStatus::Ready.
  89. return;
  90. case ThreadStatus::Running:
  91. DEBUG_ASSERT_MSG(false, "Thread with object id {} has already resumed.", GetObjectId());
  92. return;
  93. case ThreadStatus::Dead:
  94. // This should never happen, as threads must complete before being stopped.
  95. DEBUG_ASSERT_MSG(false, "Thread with object id {} cannot be resumed because it's DEAD.",
  96. GetObjectId());
  97. return;
  98. }
  99. wakeup_callback = nullptr;
  100. if (activity == ThreadActivity::Paused) {
  101. SetStatus(ThreadStatus::Paused);
  102. return;
  103. }
  104. SetStatus(ThreadStatus::Ready);
  105. }
  106. void Thread::CancelWait() {
  107. if (GetSchedulingStatus() != ThreadSchedStatus::Paused) {
  108. is_sync_cancelled = true;
  109. return;
  110. }
  111. is_sync_cancelled = false;
  112. SetWaitSynchronizationResult(ERR_SYNCHRONIZATION_CANCELED);
  113. ResumeFromWait();
  114. }
  115. static void ResetThreadContext32(Core::ARM_Interface::ThreadContext32& context, u32 stack_top,
  116. u32 entry_point, u32 arg) {
  117. context = {};
  118. context.cpu_registers[0] = arg;
  119. context.cpu_registers[15] = entry_point;
  120. context.cpu_registers[13] = stack_top;
  121. }
  122. static void ResetThreadContext64(Core::ARM_Interface::ThreadContext64& context, VAddr stack_top,
  123. VAddr entry_point, u64 arg) {
  124. context = {};
  125. context.cpu_registers[0] = arg;
  126. context.pc = entry_point;
  127. context.sp = stack_top;
  128. // TODO(merry): Perform a hardware test to determine the below value.
  129. context.fpcr = 0;
  130. }
  131. ResultVal<std::shared_ptr<Thread>> Thread::Create(KernelCore& kernel, std::string name,
  132. VAddr entry_point, u32 priority, u64 arg,
  133. s32 processor_id, VAddr stack_top,
  134. Process& owner_process) {
  135. // Check if priority is in ranged. Lowest priority -> highest priority id.
  136. if (priority > THREADPRIO_LOWEST) {
  137. LOG_ERROR(Kernel_SVC, "Invalid thread priority: {}", priority);
  138. return ERR_INVALID_THREAD_PRIORITY;
  139. }
  140. if (processor_id > THREADPROCESSORID_MAX) {
  141. LOG_ERROR(Kernel_SVC, "Invalid processor id: {}", processor_id);
  142. return ERR_INVALID_PROCESSOR_ID;
  143. }
  144. auto& system = Core::System::GetInstance();
  145. if (!system.Memory().IsValidVirtualAddress(owner_process, entry_point)) {
  146. LOG_ERROR(Kernel_SVC, "(name={}): invalid entry {:016X}", name, entry_point);
  147. // TODO (bunnei): Find the correct error code to use here
  148. return RESULT_UNKNOWN;
  149. }
  150. std::shared_ptr<Thread> thread = std::make_shared<Thread>(kernel);
  151. thread->thread_id = kernel.CreateNewThreadID();
  152. thread->status = ThreadStatus::Dormant;
  153. thread->entry_point = entry_point;
  154. thread->stack_top = stack_top;
  155. thread->tpidr_el0 = 0;
  156. thread->nominal_priority = thread->current_priority = priority;
  157. thread->last_running_ticks = system.CoreTiming().GetTicks();
  158. thread->processor_id = processor_id;
  159. thread->ideal_core = processor_id;
  160. thread->affinity_mask = 1ULL << processor_id;
  161. thread->wait_objects.clear();
  162. thread->mutex_wait_address = 0;
  163. thread->condvar_wait_address = 0;
  164. thread->wait_handle = 0;
  165. thread->name = std::move(name);
  166. thread->global_handle = kernel.GlobalHandleTable().Create(thread).Unwrap();
  167. thread->owner_process = &owner_process;
  168. auto& scheduler = kernel.GlobalScheduler();
  169. scheduler.AddThread(thread);
  170. thread->tls_address = thread->owner_process->CreateTLSRegion();
  171. thread->owner_process->RegisterThread(thread.get());
  172. ResetThreadContext32(thread->context_32, static_cast<u32>(stack_top),
  173. static_cast<u32>(entry_point), static_cast<u32>(arg));
  174. ResetThreadContext64(thread->context_64, stack_top, entry_point, arg);
  175. return MakeResult<std::shared_ptr<Thread>>(std::move(thread));
  176. }
  177. void Thread::SetPriority(u32 priority) {
  178. ASSERT_MSG(priority <= THREADPRIO_LOWEST && priority >= THREADPRIO_HIGHEST,
  179. "Invalid priority value.");
  180. nominal_priority = priority;
  181. UpdatePriority();
  182. }
  183. void Thread::SetWaitSynchronizationResult(ResultCode result) {
  184. context_32.cpu_registers[0] = result.raw;
  185. context_64.cpu_registers[0] = result.raw;
  186. }
  187. void Thread::SetWaitSynchronizationOutput(s32 output) {
  188. context_32.cpu_registers[1] = output;
  189. context_64.cpu_registers[1] = output;
  190. }
  191. s32 Thread::GetSynchronizationObjectIndex(std::shared_ptr<SynchronizationObject> object) const {
  192. ASSERT_MSG(!wait_objects.empty(), "Thread is not waiting for anything");
  193. const auto match = std::find(wait_objects.rbegin(), wait_objects.rend(), object);
  194. return static_cast<s32>(std::distance(match, wait_objects.rend()) - 1);
  195. }
  196. VAddr Thread::GetCommandBufferAddress() const {
  197. // Offset from the start of TLS at which the IPC command buffer begins.
  198. constexpr u64 command_header_offset = 0x80;
  199. return GetTLSAddress() + command_header_offset;
  200. }
  201. void Thread::SetStatus(ThreadStatus new_status) {
  202. if (new_status == status) {
  203. return;
  204. }
  205. switch (new_status) {
  206. case ThreadStatus::Ready:
  207. case ThreadStatus::Running:
  208. SetSchedulingStatus(ThreadSchedStatus::Runnable);
  209. break;
  210. case ThreadStatus::Dormant:
  211. SetSchedulingStatus(ThreadSchedStatus::None);
  212. break;
  213. case ThreadStatus::Dead:
  214. SetSchedulingStatus(ThreadSchedStatus::Exited);
  215. break;
  216. default:
  217. SetSchedulingStatus(ThreadSchedStatus::Paused);
  218. break;
  219. }
  220. if (status == ThreadStatus::Running) {
  221. last_running_ticks = Core::System::GetInstance().CoreTiming().GetTicks();
  222. }
  223. status = new_status;
  224. }
  225. void Thread::AddMutexWaiter(std::shared_ptr<Thread> thread) {
  226. if (thread->lock_owner.get() == this) {
  227. // If the thread is already waiting for this thread to release the mutex, ensure that the
  228. // waiters list is consistent and return without doing anything.
  229. const auto iter = std::find(wait_mutex_threads.begin(), wait_mutex_threads.end(), thread);
  230. ASSERT(iter != wait_mutex_threads.end());
  231. return;
  232. }
  233. // A thread can't wait on two different mutexes at the same time.
  234. ASSERT(thread->lock_owner == nullptr);
  235. // Ensure that the thread is not already in the list of mutex waiters
  236. const auto iter = std::find(wait_mutex_threads.begin(), wait_mutex_threads.end(), thread);
  237. ASSERT(iter == wait_mutex_threads.end());
  238. // Keep the list in an ordered fashion
  239. const auto insertion_point = std::find_if(
  240. wait_mutex_threads.begin(), wait_mutex_threads.end(),
  241. [&thread](const auto& entry) { return entry->GetPriority() > thread->GetPriority(); });
  242. wait_mutex_threads.insert(insertion_point, thread);
  243. thread->lock_owner = SharedFrom(this);
  244. UpdatePriority();
  245. }
  246. void Thread::RemoveMutexWaiter(std::shared_ptr<Thread> thread) {
  247. ASSERT(thread->lock_owner.get() == this);
  248. // Ensure that the thread is in the list of mutex waiters
  249. const auto iter = std::find(wait_mutex_threads.begin(), wait_mutex_threads.end(), thread);
  250. ASSERT(iter != wait_mutex_threads.end());
  251. wait_mutex_threads.erase(iter);
  252. thread->lock_owner = nullptr;
  253. UpdatePriority();
  254. }
  255. void Thread::UpdatePriority() {
  256. // If any of the threads waiting on the mutex have a higher priority
  257. // (taking into account priority inheritance), then this thread inherits
  258. // that thread's priority.
  259. u32 new_priority = nominal_priority;
  260. if (!wait_mutex_threads.empty()) {
  261. if (wait_mutex_threads.front()->current_priority < new_priority) {
  262. new_priority = wait_mutex_threads.front()->current_priority;
  263. }
  264. }
  265. if (new_priority == current_priority) {
  266. return;
  267. }
  268. if (GetStatus() == ThreadStatus::WaitCondVar) {
  269. owner_process->RemoveConditionVariableThread(SharedFrom(this));
  270. }
  271. SetCurrentPriority(new_priority);
  272. if (GetStatus() == ThreadStatus::WaitCondVar) {
  273. owner_process->InsertConditionVariableThread(SharedFrom(this));
  274. }
  275. if (!lock_owner) {
  276. return;
  277. }
  278. // Ensure that the thread is within the correct location in the waiting list.
  279. auto old_owner = lock_owner;
  280. lock_owner->RemoveMutexWaiter(SharedFrom(this));
  281. old_owner->AddMutexWaiter(SharedFrom(this));
  282. // Recursively update the priority of the thread that depends on the priority of this one.
  283. lock_owner->UpdatePriority();
  284. }
  285. void Thread::ChangeCore(u32 core, u64 mask) {
  286. SetCoreAndAffinityMask(core, mask);
  287. }
  288. bool Thread::AllSynchronizationObjectsReady() const {
  289. return std::none_of(wait_objects.begin(), wait_objects.end(),
  290. [this](const std::shared_ptr<SynchronizationObject>& object) {
  291. return object->ShouldWait(this);
  292. });
  293. }
  294. bool Thread::InvokeWakeupCallback(ThreadWakeupReason reason, std::shared_ptr<Thread> thread,
  295. std::shared_ptr<SynchronizationObject> object,
  296. std::size_t index) {
  297. ASSERT(wakeup_callback);
  298. return wakeup_callback(reason, std::move(thread), std::move(object), index);
  299. }
  300. void Thread::SetActivity(ThreadActivity value) {
  301. activity = value;
  302. if (value == ThreadActivity::Paused) {
  303. // Set status if not waiting
  304. if (status == ThreadStatus::Ready || status == ThreadStatus::Running) {
  305. SetStatus(ThreadStatus::Paused);
  306. kernel.PrepareReschedule(processor_id);
  307. }
  308. } else if (status == ThreadStatus::Paused) {
  309. // Ready to reschedule
  310. ResumeFromWait();
  311. }
  312. }
  313. void Thread::Sleep(s64 nanoseconds) {
  314. // Sleep current thread and check for next thread to schedule
  315. SetStatus(ThreadStatus::WaitSleep);
  316. // Create an event to wake the thread up after the specified nanosecond delay has passed
  317. WakeAfterDelay(nanoseconds);
  318. }
  319. bool Thread::YieldSimple() {
  320. auto& scheduler = kernel.GlobalScheduler();
  321. return scheduler.YieldThread(this);
  322. }
  323. bool Thread::YieldAndBalanceLoad() {
  324. auto& scheduler = kernel.GlobalScheduler();
  325. return scheduler.YieldThreadAndBalanceLoad(this);
  326. }
  327. bool Thread::YieldAndWaitForLoadBalancing() {
  328. auto& scheduler = kernel.GlobalScheduler();
  329. return scheduler.YieldThreadAndWaitForLoadBalancing(this);
  330. }
  331. void Thread::SetSchedulingStatus(ThreadSchedStatus new_status) {
  332. const u32 old_flags = scheduling_state;
  333. scheduling_state = (scheduling_state & static_cast<u32>(ThreadSchedMasks::HighMask)) |
  334. static_cast<u32>(new_status);
  335. AdjustSchedulingOnStatus(old_flags);
  336. }
  337. void Thread::SetCurrentPriority(u32 new_priority) {
  338. const u32 old_priority = std::exchange(current_priority, new_priority);
  339. AdjustSchedulingOnPriority(old_priority);
  340. }
  341. ResultCode Thread::SetCoreAndAffinityMask(s32 new_core, u64 new_affinity_mask) {
  342. const auto HighestSetCore = [](u64 mask, u32 max_cores) {
  343. for (s32 core = static_cast<s32>(max_cores - 1); core >= 0; core--) {
  344. if (((mask >> core) & 1) != 0) {
  345. return core;
  346. }
  347. }
  348. return -1;
  349. };
  350. const bool use_override = affinity_override_count != 0;
  351. if (new_core == THREADPROCESSORID_DONT_UPDATE) {
  352. new_core = use_override ? ideal_core_override : ideal_core;
  353. if ((new_affinity_mask & (1ULL << new_core)) == 0) {
  354. LOG_ERROR(Kernel, "New affinity mask is incorrect! new_core={}, new_affinity_mask={}",
  355. new_core, new_affinity_mask);
  356. return ERR_INVALID_COMBINATION;
  357. }
  358. }
  359. if (use_override) {
  360. ideal_core_override = new_core;
  361. affinity_mask_override = new_affinity_mask;
  362. } else {
  363. const u64 old_affinity_mask = std::exchange(affinity_mask, new_affinity_mask);
  364. ideal_core = new_core;
  365. if (old_affinity_mask != new_affinity_mask) {
  366. const s32 old_core = processor_id;
  367. if (processor_id >= 0 && ((affinity_mask >> processor_id) & 1) == 0) {
  368. if (static_cast<s32>(ideal_core) < 0) {
  369. processor_id = HighestSetCore(affinity_mask, Core::Hardware::NUM_CPU_CORES);
  370. } else {
  371. processor_id = ideal_core;
  372. }
  373. }
  374. AdjustSchedulingOnAffinity(old_affinity_mask, old_core);
  375. }
  376. }
  377. return RESULT_SUCCESS;
  378. }
  379. void Thread::AdjustSchedulingOnStatus(u32 old_flags) {
  380. if (old_flags == scheduling_state) {
  381. return;
  382. }
  383. auto& scheduler = kernel.GlobalScheduler();
  384. if (static_cast<ThreadSchedStatus>(old_flags & static_cast<u32>(ThreadSchedMasks::LowMask)) ==
  385. ThreadSchedStatus::Runnable) {
  386. // In this case the thread was running, now it's pausing/exitting
  387. if (processor_id >= 0) {
  388. scheduler.Unschedule(current_priority, static_cast<u32>(processor_id), this);
  389. }
  390. for (u32 core = 0; core < Core::Hardware::NUM_CPU_CORES; core++) {
  391. if (core != static_cast<u32>(processor_id) && ((affinity_mask >> core) & 1) != 0) {
  392. scheduler.Unsuggest(current_priority, core, this);
  393. }
  394. }
  395. } else if (GetSchedulingStatus() == ThreadSchedStatus::Runnable) {
  396. // The thread is now set to running from being stopped
  397. if (processor_id >= 0) {
  398. scheduler.Schedule(current_priority, static_cast<u32>(processor_id), this);
  399. }
  400. for (u32 core = 0; core < Core::Hardware::NUM_CPU_CORES; core++) {
  401. if (core != static_cast<u32>(processor_id) && ((affinity_mask >> core) & 1) != 0) {
  402. scheduler.Suggest(current_priority, core, this);
  403. }
  404. }
  405. }
  406. scheduler.SetReselectionPending();
  407. }
  408. void Thread::AdjustSchedulingOnPriority(u32 old_priority) {
  409. if (GetSchedulingStatus() != ThreadSchedStatus::Runnable) {
  410. return;
  411. }
  412. auto& scheduler = kernel.GlobalScheduler();
  413. if (processor_id >= 0) {
  414. scheduler.Unschedule(old_priority, static_cast<u32>(processor_id), this);
  415. }
  416. for (u32 core = 0; core < Core::Hardware::NUM_CPU_CORES; core++) {
  417. if (core != static_cast<u32>(processor_id) && ((affinity_mask >> core) & 1) != 0) {
  418. scheduler.Unsuggest(old_priority, core, this);
  419. }
  420. }
  421. // Add thread to the new priority queues.
  422. Thread* current_thread = GetCurrentThread();
  423. if (processor_id >= 0) {
  424. if (current_thread == this) {
  425. scheduler.SchedulePrepend(current_priority, static_cast<u32>(processor_id), this);
  426. } else {
  427. scheduler.Schedule(current_priority, static_cast<u32>(processor_id), this);
  428. }
  429. }
  430. for (u32 core = 0; core < Core::Hardware::NUM_CPU_CORES; core++) {
  431. if (core != static_cast<u32>(processor_id) && ((affinity_mask >> core) & 1) != 0) {
  432. scheduler.Suggest(current_priority, core, this);
  433. }
  434. }
  435. scheduler.SetReselectionPending();
  436. }
  437. void Thread::AdjustSchedulingOnAffinity(u64 old_affinity_mask, s32 old_core) {
  438. auto& scheduler = kernel.GlobalScheduler();
  439. if (GetSchedulingStatus() != ThreadSchedStatus::Runnable ||
  440. current_priority >= THREADPRIO_COUNT) {
  441. return;
  442. }
  443. for (u32 core = 0; core < Core::Hardware::NUM_CPU_CORES; core++) {
  444. if (((old_affinity_mask >> core) & 1) != 0) {
  445. if (core == static_cast<u32>(old_core)) {
  446. scheduler.Unschedule(current_priority, core, this);
  447. } else {
  448. scheduler.Unsuggest(current_priority, core, this);
  449. }
  450. }
  451. }
  452. for (u32 core = 0; core < Core::Hardware::NUM_CPU_CORES; core++) {
  453. if (((affinity_mask >> core) & 1) != 0) {
  454. if (core == static_cast<u32>(processor_id)) {
  455. scheduler.Schedule(current_priority, core, this);
  456. } else {
  457. scheduler.Suggest(current_priority, core, this);
  458. }
  459. }
  460. }
  461. scheduler.SetReselectionPending();
  462. }
  463. ////////////////////////////////////////////////////////////////////////////////////////////////////
  464. /**
  465. * Gets the current thread
  466. */
  467. Thread* GetCurrentThread() {
  468. return Core::System::GetInstance().CurrentScheduler().GetCurrentThread();
  469. }
  470. } // namespace Kernel