thread.cpp 19 KB

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