thread.h 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731
  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. #pragma once
  5. #include <array>
  6. #include <functional>
  7. #include <string>
  8. #include <utility>
  9. #include <vector>
  10. #include "common/common_types.h"
  11. #include "common/spin_lock.h"
  12. #include "core/arm/arm_interface.h"
  13. #include "core/hle/kernel/k_affinity_mask.h"
  14. #include "core/hle/kernel/object.h"
  15. #include "core/hle/kernel/synchronization_object.h"
  16. #include "core/hle/result.h"
  17. namespace Common {
  18. class Fiber;
  19. }
  20. namespace Core {
  21. class ARM_Interface;
  22. class System;
  23. } // namespace Core
  24. namespace Kernel {
  25. class GlobalSchedulerContext;
  26. class KernelCore;
  27. class Process;
  28. class KScheduler;
  29. enum ThreadPriority : u32 {
  30. THREADPRIO_HIGHEST = 0, ///< Highest thread priority
  31. THREADPRIO_MAX_CORE_MIGRATION = 2, ///< Highest priority for a core migration
  32. THREADPRIO_USERLAND_MAX = 24, ///< Highest thread priority for userland apps
  33. THREADPRIO_DEFAULT = 44, ///< Default thread priority for userland apps
  34. THREADPRIO_LOWEST = 63, ///< Lowest thread priority
  35. THREADPRIO_COUNT = 64, ///< Total number of possible thread priorities.
  36. };
  37. enum ThreadType : u32 {
  38. THREADTYPE_USER = 0x1,
  39. THREADTYPE_KERNEL = 0x2,
  40. THREADTYPE_HLE = 0x4,
  41. THREADTYPE_IDLE = 0x8,
  42. THREADTYPE_SUSPEND = 0x10,
  43. };
  44. enum ThreadProcessorId : s32 {
  45. /// Indicates that no particular processor core is preferred.
  46. THREADPROCESSORID_DONT_CARE = -1,
  47. /// Run thread on the ideal core specified by the process.
  48. THREADPROCESSORID_IDEAL = -2,
  49. /// Indicates that the preferred processor ID shouldn't be updated in
  50. /// a core mask setting operation.
  51. THREADPROCESSORID_DONT_UPDATE = -3,
  52. THREADPROCESSORID_0 = 0, ///< Run thread on core 0
  53. THREADPROCESSORID_1 = 1, ///< Run thread on core 1
  54. THREADPROCESSORID_2 = 2, ///< Run thread on core 2
  55. THREADPROCESSORID_3 = 3, ///< Run thread on core 3
  56. THREADPROCESSORID_MAX = 4, ///< Processor ID must be less than this
  57. /// Allowed CPU mask
  58. THREADPROCESSORID_DEFAULT_MASK = (1 << THREADPROCESSORID_0) | (1 << THREADPROCESSORID_1) |
  59. (1 << THREADPROCESSORID_2) | (1 << THREADPROCESSORID_3)
  60. };
  61. enum class ThreadStatus {
  62. Ready, ///< Ready to run
  63. Paused, ///< Paused by SetThreadActivity or debug
  64. WaitHLEEvent, ///< Waiting for hle event to finish
  65. WaitSleep, ///< Waiting due to a SleepThread SVC
  66. WaitIPC, ///< Waiting for the reply from an IPC request
  67. WaitSynch, ///< Waiting due to WaitSynchronization
  68. WaitMutex, ///< Waiting due to an ArbitrateLock svc
  69. WaitCondVar, ///< Waiting due to an WaitProcessWideKey svc
  70. WaitArb, ///< Waiting due to a SignalToAddress/WaitForAddress svc
  71. Dormant, ///< Created but not yet made ready
  72. Dead ///< Run to completion, or forcefully terminated
  73. };
  74. enum class ThreadWakeupReason {
  75. Signal, // The thread was woken up by WakeupAllWaitingThreads due to an object signal.
  76. Timeout // The thread was woken up due to a wait timeout.
  77. };
  78. enum class ThreadActivity : u32 {
  79. Normal = 0,
  80. Paused = 1,
  81. };
  82. enum class ThreadSchedStatus : u32 {
  83. None = 0,
  84. Paused = 1,
  85. Runnable = 2,
  86. Exited = 3,
  87. };
  88. enum class ThreadSchedFlags : u32 {
  89. ProcessPauseFlag = 1 << 4,
  90. ThreadPauseFlag = 1 << 5,
  91. ProcessDebugPauseFlag = 1 << 6,
  92. KernelInitPauseFlag = 1 << 8,
  93. };
  94. enum class ThreadSchedMasks : u32 {
  95. LowMask = 0x000f,
  96. HighMask = 0xfff0,
  97. ForcePauseMask = 0x0070,
  98. };
  99. class Thread final : public SynchronizationObject {
  100. public:
  101. explicit Thread(KernelCore& kernel);
  102. ~Thread() override;
  103. using MutexWaitingThreads = std::vector<std::shared_ptr<Thread>>;
  104. using ThreadContext32 = Core::ARM_Interface::ThreadContext32;
  105. using ThreadContext64 = Core::ARM_Interface::ThreadContext64;
  106. using ThreadSynchronizationObjects = std::vector<std::shared_ptr<SynchronizationObject>>;
  107. using HLECallback = std::function<bool(std::shared_ptr<Thread> thread)>;
  108. /**
  109. * Creates and returns a new thread. The new thread is immediately scheduled
  110. * @param system The instance of the whole system
  111. * @param name The friendly name desired for the thread
  112. * @param entry_point The address at which the thread should start execution
  113. * @param priority The thread's priority
  114. * @param arg User data to pass to the thread
  115. * @param processor_id The ID(s) of the processors on which the thread is desired to be run
  116. * @param stack_top The address of the thread's stack top
  117. * @param owner_process The parent process for the thread, if null, it's a kernel thread
  118. * @return A shared pointer to the newly created thread
  119. */
  120. static ResultVal<std::shared_ptr<Thread>> Create(Core::System& system, ThreadType type_flags,
  121. std::string name, VAddr entry_point,
  122. u32 priority, u64 arg, s32 processor_id,
  123. VAddr stack_top, Process* owner_process);
  124. /**
  125. * Creates and returns a new thread. The new thread is immediately scheduled
  126. * @param system The instance of the whole system
  127. * @param name The friendly name desired for the thread
  128. * @param entry_point The address at which the thread should start execution
  129. * @param priority The thread's priority
  130. * @param arg User data to pass to the thread
  131. * @param processor_id The ID(s) of the processors on which the thread is desired to be run
  132. * @param stack_top The address of the thread's stack top
  133. * @param owner_process The parent process for the thread, if null, it's a kernel thread
  134. * @param thread_start_func The function where the host context will start.
  135. * @param thread_start_parameter The parameter which will passed to host context on init
  136. * @return A shared pointer to the newly created thread
  137. */
  138. static ResultVal<std::shared_ptr<Thread>> Create(Core::System& system, ThreadType type_flags,
  139. std::string name, VAddr entry_point,
  140. u32 priority, u64 arg, s32 processor_id,
  141. VAddr stack_top, Process* owner_process,
  142. std::function<void(void*)>&& thread_start_func,
  143. void* thread_start_parameter);
  144. std::string GetName() const override {
  145. return name;
  146. }
  147. void SetName(std::string new_name) {
  148. name = std::move(new_name);
  149. }
  150. std::string GetTypeName() const override {
  151. return "Thread";
  152. }
  153. static constexpr HandleType HANDLE_TYPE = HandleType::Thread;
  154. HandleType GetHandleType() const override {
  155. return HANDLE_TYPE;
  156. }
  157. bool ShouldWait(const Thread* thread) const override;
  158. void Acquire(Thread* thread) override;
  159. bool IsSignaled() const override;
  160. /**
  161. * Gets the thread's current priority
  162. * @return The current thread's priority
  163. */
  164. u32 GetPriority() const {
  165. return current_priority;
  166. }
  167. /**
  168. * Gets the thread's nominal priority.
  169. * @return The current thread's nominal priority.
  170. */
  171. u32 GetNominalPriority() const {
  172. return nominal_priority;
  173. }
  174. /**
  175. * Sets the thread's current priority
  176. * @param priority The new priority
  177. */
  178. void SetPriority(u32 priority);
  179. /// Adds a thread to the list of threads that are waiting for a lock held by this thread.
  180. void AddMutexWaiter(std::shared_ptr<Thread> thread);
  181. /// Removes a thread from the list of threads that are waiting for a lock held by this thread.
  182. void RemoveMutexWaiter(std::shared_ptr<Thread> thread);
  183. /// Recalculates the current priority taking into account priority inheritance.
  184. void UpdatePriority();
  185. /// Changes the core that the thread is running or scheduled to run on.
  186. ResultCode SetCoreAndAffinityMask(s32 new_core, u64 new_affinity_mask);
  187. /**
  188. * Gets the thread's thread ID
  189. * @return The thread's ID
  190. */
  191. u64 GetThreadID() const {
  192. return thread_id;
  193. }
  194. /// Resumes a thread from waiting
  195. void ResumeFromWait();
  196. void OnWakeUp();
  197. ResultCode Start();
  198. /// Cancels a waiting operation that this thread may or may not be within.
  199. ///
  200. /// When the thread is within a waiting state, this will set the thread's
  201. /// waiting result to signal a canceled wait. The function will then resume
  202. /// this thread.
  203. ///
  204. void CancelWait();
  205. void SetSynchronizationResults(SynchronizationObject* object, ResultCode result);
  206. SynchronizationObject* GetSignalingObject() const {
  207. return signaling_object;
  208. }
  209. ResultCode GetSignalingResult() const {
  210. return signaling_result;
  211. }
  212. /**
  213. * Retrieves the index that this particular object occupies in the list of objects
  214. * that the thread passed to WaitSynchronization, starting the search from the last element.
  215. *
  216. * It is used to set the output index of WaitSynchronization when the thread is awakened.
  217. *
  218. * When a thread wakes up due to an object signal, the kernel will use the index of the last
  219. * matching object in the wait objects list in case of having multiple instances of the same
  220. * object in the list.
  221. *
  222. * @param object Object to query the index of.
  223. */
  224. s32 GetSynchronizationObjectIndex(std::shared_ptr<SynchronizationObject> object) const;
  225. /**
  226. * Stops a thread, invalidating it from further use
  227. */
  228. void Stop();
  229. /*
  230. * Returns the Thread Local Storage address of the current thread
  231. * @returns VAddr of the thread's TLS
  232. */
  233. VAddr GetTLSAddress() const {
  234. return tls_address;
  235. }
  236. /*
  237. * Returns the value of the TPIDR_EL0 Read/Write system register for this thread.
  238. * @returns The value of the TPIDR_EL0 register.
  239. */
  240. u64 GetTPIDR_EL0() const {
  241. return tpidr_el0;
  242. }
  243. /// Sets the value of the TPIDR_EL0 Read/Write system register for this thread.
  244. void SetTPIDR_EL0(u64 value) {
  245. tpidr_el0 = value;
  246. }
  247. /*
  248. * Returns the address of the current thread's command buffer, located in the TLS.
  249. * @returns VAddr of the thread's command buffer.
  250. */
  251. VAddr GetCommandBufferAddress() const;
  252. ThreadContext32& GetContext32() {
  253. return context_32;
  254. }
  255. const ThreadContext32& GetContext32() const {
  256. return context_32;
  257. }
  258. ThreadContext64& GetContext64() {
  259. return context_64;
  260. }
  261. const ThreadContext64& GetContext64() const {
  262. return context_64;
  263. }
  264. bool IsHLEThread() const {
  265. return (type & THREADTYPE_HLE) != 0;
  266. }
  267. bool IsSuspendThread() const {
  268. return (type & THREADTYPE_SUSPEND) != 0;
  269. }
  270. bool IsIdleThread() const {
  271. return (type & THREADTYPE_IDLE) != 0;
  272. }
  273. bool WasRunning() const {
  274. return was_running;
  275. }
  276. void SetWasRunning(bool value) {
  277. was_running = value;
  278. }
  279. std::shared_ptr<Common::Fiber>& GetHostContext();
  280. ThreadStatus GetStatus() const {
  281. return status;
  282. }
  283. void SetStatus(ThreadStatus new_status);
  284. s64 GetLastScheduledTick() const {
  285. return this->last_scheduled_tick;
  286. }
  287. void SetLastScheduledTick(s64 tick) {
  288. this->last_scheduled_tick = tick;
  289. }
  290. u64 GetTotalCPUTimeTicks() const {
  291. return total_cpu_time_ticks;
  292. }
  293. void UpdateCPUTimeTicks(u64 ticks) {
  294. total_cpu_time_ticks += ticks;
  295. }
  296. s32 GetProcessorID() const {
  297. return processor_id;
  298. }
  299. s32 GetActiveCore() const {
  300. return GetProcessorID();
  301. }
  302. void SetProcessorID(s32 new_core) {
  303. processor_id = new_core;
  304. }
  305. void SetActiveCore(s32 new_core) {
  306. processor_id = new_core;
  307. }
  308. Process* GetOwnerProcess() {
  309. return owner_process;
  310. }
  311. const Process* GetOwnerProcess() const {
  312. return owner_process;
  313. }
  314. const ThreadSynchronizationObjects& GetSynchronizationObjects() const {
  315. return *wait_objects;
  316. }
  317. void SetSynchronizationObjects(ThreadSynchronizationObjects* objects) {
  318. wait_objects = objects;
  319. }
  320. void ClearSynchronizationObjects() {
  321. for (const auto& waiting_object : *wait_objects) {
  322. waiting_object->RemoveWaitingThread(SharedFrom(this));
  323. }
  324. wait_objects->clear();
  325. }
  326. /// Determines whether all the objects this thread is waiting on are ready.
  327. bool AllSynchronizationObjectsReady() const;
  328. const MutexWaitingThreads& GetMutexWaitingThreads() const {
  329. return wait_mutex_threads;
  330. }
  331. Thread* GetLockOwner() const {
  332. return lock_owner.get();
  333. }
  334. void SetLockOwner(std::shared_ptr<Thread> owner) {
  335. lock_owner = std::move(owner);
  336. }
  337. VAddr GetCondVarWaitAddress() const {
  338. return condvar_wait_address;
  339. }
  340. void SetCondVarWaitAddress(VAddr address) {
  341. condvar_wait_address = address;
  342. }
  343. VAddr GetMutexWaitAddress() const {
  344. return mutex_wait_address;
  345. }
  346. void SetMutexWaitAddress(VAddr address) {
  347. mutex_wait_address = address;
  348. }
  349. Handle GetWaitHandle() const {
  350. return wait_handle;
  351. }
  352. void SetWaitHandle(Handle handle) {
  353. wait_handle = handle;
  354. }
  355. VAddr GetArbiterWaitAddress() const {
  356. return arb_wait_address;
  357. }
  358. void SetArbiterWaitAddress(VAddr address) {
  359. arb_wait_address = address;
  360. }
  361. bool HasHLECallback() const {
  362. return hle_callback != nullptr;
  363. }
  364. void SetHLECallback(HLECallback callback) {
  365. hle_callback = std::move(callback);
  366. }
  367. void SetHLETimeEvent(Handle time_event) {
  368. hle_time_event = time_event;
  369. }
  370. void SetHLESyncObject(SynchronizationObject* object) {
  371. hle_object = object;
  372. }
  373. Handle GetHLETimeEvent() const {
  374. return hle_time_event;
  375. }
  376. SynchronizationObject* GetHLESyncObject() const {
  377. return hle_object;
  378. }
  379. void InvalidateHLECallback() {
  380. SetHLECallback(nullptr);
  381. }
  382. bool InvokeHLECallback(std::shared_ptr<Thread> thread);
  383. u32 GetIdealCore() const {
  384. return ideal_core;
  385. }
  386. const KAffinityMask& GetAffinityMask() const {
  387. return affinity_mask;
  388. }
  389. ResultCode SetActivity(ThreadActivity value);
  390. /// Sleeps this thread for the given amount of nanoseconds.
  391. ResultCode Sleep(s64 nanoseconds);
  392. s64 GetYieldScheduleCount() const {
  393. return this->schedule_count;
  394. }
  395. void SetYieldScheduleCount(s64 count) {
  396. this->schedule_count = count;
  397. }
  398. ThreadSchedStatus GetSchedulingStatus() const {
  399. return static_cast<ThreadSchedStatus>(scheduling_state &
  400. static_cast<u32>(ThreadSchedMasks::LowMask));
  401. }
  402. bool IsRunnable() const {
  403. return scheduling_state == static_cast<u32>(ThreadSchedStatus::Runnable);
  404. }
  405. bool IsRunning() const {
  406. return is_running;
  407. }
  408. void SetIsRunning(bool value) {
  409. is_running = value;
  410. }
  411. bool IsSyncCancelled() const {
  412. return is_sync_cancelled;
  413. }
  414. void SetSyncCancelled(bool value) {
  415. is_sync_cancelled = value;
  416. }
  417. Handle GetGlobalHandle() const {
  418. return global_handle;
  419. }
  420. bool IsWaitingForArbitration() const {
  421. return waiting_for_arbitration;
  422. }
  423. void WaitForArbitration(bool set) {
  424. waiting_for_arbitration = set;
  425. }
  426. bool IsWaitingSync() const {
  427. return is_waiting_on_sync;
  428. }
  429. void SetWaitingSync(bool is_waiting) {
  430. is_waiting_on_sync = is_waiting;
  431. }
  432. bool IsPendingTermination() const {
  433. return will_be_terminated || GetSchedulingStatus() == ThreadSchedStatus::Exited;
  434. }
  435. bool IsPaused() const {
  436. return pausing_state != 0;
  437. }
  438. bool IsContinuousOnSVC() const {
  439. return is_continuous_on_svc;
  440. }
  441. void SetContinuousOnSVC(bool is_continuous) {
  442. is_continuous_on_svc = is_continuous;
  443. }
  444. bool IsPhantomMode() const {
  445. return is_phantom_mode;
  446. }
  447. void SetPhantomMode(bool phantom) {
  448. is_phantom_mode = phantom;
  449. }
  450. bool HasExited() const {
  451. return has_exited;
  452. }
  453. class QueueEntry {
  454. public:
  455. constexpr QueueEntry() = default;
  456. constexpr void Initialize() {
  457. this->prev = nullptr;
  458. this->next = nullptr;
  459. }
  460. constexpr Thread* GetPrev() const {
  461. return this->prev;
  462. }
  463. constexpr Thread* GetNext() const {
  464. return this->next;
  465. }
  466. constexpr void SetPrev(Thread* thread) {
  467. this->prev = thread;
  468. }
  469. constexpr void SetNext(Thread* thread) {
  470. this->next = thread;
  471. }
  472. private:
  473. Thread* prev{};
  474. Thread* next{};
  475. };
  476. QueueEntry& GetPriorityQueueEntry(s32 core) {
  477. return this->per_core_priority_queue_entry[core];
  478. }
  479. const QueueEntry& GetPriorityQueueEntry(s32 core) const {
  480. return this->per_core_priority_queue_entry[core];
  481. }
  482. s32 GetDisableDispatchCount() const {
  483. return disable_count;
  484. }
  485. void DisableDispatch() {
  486. ASSERT(GetDisableDispatchCount() >= 0);
  487. disable_count++;
  488. }
  489. void EnableDispatch() {
  490. ASSERT(GetDisableDispatchCount() > 0);
  491. disable_count--;
  492. }
  493. private:
  494. friend class GlobalSchedulerContext;
  495. friend class KScheduler;
  496. friend class Process;
  497. void SetSchedulingStatus(ThreadSchedStatus new_status);
  498. void AddSchedulingFlag(ThreadSchedFlags flag);
  499. void RemoveSchedulingFlag(ThreadSchedFlags flag);
  500. void SetCurrentPriority(u32 new_priority);
  501. Common::SpinLock context_guard{};
  502. ThreadContext32 context_32{};
  503. ThreadContext64 context_64{};
  504. std::shared_ptr<Common::Fiber> host_context{};
  505. ThreadStatus status = ThreadStatus::Dormant;
  506. u32 scheduling_state = 0;
  507. u64 thread_id = 0;
  508. VAddr entry_point = 0;
  509. VAddr stack_top = 0;
  510. std::atomic_int disable_count = 0;
  511. ThreadType type;
  512. /// Nominal thread priority, as set by the emulated application.
  513. /// The nominal priority is the thread priority without priority
  514. /// inheritance taken into account.
  515. u32 nominal_priority = 0;
  516. /// Current thread priority. This may change over the course of the
  517. /// thread's lifetime in order to facilitate priority inheritance.
  518. u32 current_priority = 0;
  519. u64 total_cpu_time_ticks = 0; ///< Total CPU running ticks.
  520. s64 schedule_count{};
  521. s64 last_scheduled_tick{};
  522. s32 processor_id = 0;
  523. VAddr tls_address = 0; ///< Virtual address of the Thread Local Storage of the thread
  524. u64 tpidr_el0 = 0; ///< TPIDR_EL0 read/write system register.
  525. /// Process that owns this thread
  526. Process* owner_process;
  527. /// Objects that the thread is waiting on, in the same order as they were
  528. /// passed to WaitSynchronization.
  529. ThreadSynchronizationObjects* wait_objects;
  530. SynchronizationObject* signaling_object;
  531. ResultCode signaling_result{RESULT_SUCCESS};
  532. /// List of threads that are waiting for a mutex that is held by this thread.
  533. MutexWaitingThreads wait_mutex_threads;
  534. /// Thread that owns the lock that this thread is waiting for.
  535. std::shared_ptr<Thread> lock_owner;
  536. /// If waiting on a ConditionVariable, this is the ConditionVariable address
  537. VAddr condvar_wait_address = 0;
  538. /// If waiting on a Mutex, this is the mutex address
  539. VAddr mutex_wait_address = 0;
  540. /// The handle used to wait for the mutex.
  541. Handle wait_handle = 0;
  542. /// If waiting for an AddressArbiter, this is the address being waited on.
  543. VAddr arb_wait_address{0};
  544. bool waiting_for_arbitration{};
  545. /// Handle used as userdata to reference this object when inserting into the CoreTiming queue.
  546. Handle global_handle = 0;
  547. /// Callback for HLE Events
  548. HLECallback hle_callback;
  549. Handle hle_time_event;
  550. SynchronizationObject* hle_object;
  551. KScheduler* scheduler = nullptr;
  552. std::array<QueueEntry, Core::Hardware::NUM_CPU_CORES> per_core_priority_queue_entry{};
  553. u32 ideal_core{0xFFFFFFFF};
  554. KAffinityMask affinity_mask{};
  555. s32 ideal_core_override = -1;
  556. u32 affinity_override_count = 0;
  557. u32 pausing_state = 0;
  558. bool is_running = false;
  559. bool is_waiting_on_sync = false;
  560. bool is_sync_cancelled = false;
  561. bool is_continuous_on_svc = false;
  562. bool will_be_terminated = false;
  563. bool is_phantom_mode = false;
  564. bool has_exited = false;
  565. bool was_running = false;
  566. std::string name;
  567. };
  568. } // namespace Kernel