thread.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  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 <functional>
  6. #include <memory>
  7. #include <string>
  8. #include <vector>
  9. #include "common/common_types.h"
  10. #include "core/arm/arm_interface.h"
  11. #include "core/hle/kernel/object.h"
  12. #include "core/hle/kernel/wait_object.h"
  13. #include "core/hle/result.h"
  14. namespace Kernel {
  15. class KernelCore;
  16. class Process;
  17. class Scheduler;
  18. enum ThreadPriority : u32 {
  19. THREADPRIO_HIGHEST = 0, ///< Highest thread priority
  20. THREADPRIO_USERLAND_MAX = 24, ///< Highest thread priority for userland apps
  21. THREADPRIO_DEFAULT = 44, ///< Default thread priority for userland apps
  22. THREADPRIO_LOWEST = 63, ///< Lowest thread priority
  23. THREADPRIO_COUNT = 64, ///< Total number of possible thread priorities.
  24. };
  25. enum ThreadProcessorId : s32 {
  26. /// Indicates that no particular processor core is preferred.
  27. THREADPROCESSORID_DONT_CARE = -1,
  28. /// Run thread on the ideal core specified by the process.
  29. THREADPROCESSORID_IDEAL = -2,
  30. /// Indicates that the preferred processor ID shouldn't be updated in
  31. /// a core mask setting operation.
  32. THREADPROCESSORID_DONT_UPDATE = -3,
  33. THREADPROCESSORID_0 = 0, ///< Run thread on core 0
  34. THREADPROCESSORID_1 = 1, ///< Run thread on core 1
  35. THREADPROCESSORID_2 = 2, ///< Run thread on core 2
  36. THREADPROCESSORID_3 = 3, ///< Run thread on core 3
  37. THREADPROCESSORID_MAX = 4, ///< Processor ID must be less than this
  38. /// Allowed CPU mask
  39. THREADPROCESSORID_DEFAULT_MASK = (1 << THREADPROCESSORID_0) | (1 << THREADPROCESSORID_1) |
  40. (1 << THREADPROCESSORID_2) | (1 << THREADPROCESSORID_3)
  41. };
  42. enum class ThreadStatus {
  43. Running, ///< Currently running
  44. Ready, ///< Ready to run
  45. Paused, ///< Paused by SetThreadActivity or debug
  46. WaitHLEEvent, ///< Waiting for hle event to finish
  47. WaitSleep, ///< Waiting due to a SleepThread SVC
  48. WaitIPC, ///< Waiting for the reply from an IPC request
  49. WaitSynch, ///< Waiting due to WaitSynchronization
  50. WaitMutex, ///< Waiting due to an ArbitrateLock svc
  51. WaitCondVar, ///< Waiting due to an WaitProcessWideKey svc
  52. WaitArb, ///< Waiting due to a SignalToAddress/WaitForAddress svc
  53. Dormant, ///< Created but not yet made ready
  54. Dead ///< Run to completion, or forcefully terminated
  55. };
  56. enum class ThreadWakeupReason {
  57. Signal, // The thread was woken up by WakeupAllWaitingThreads due to an object signal.
  58. Timeout // The thread was woken up due to a wait timeout.
  59. };
  60. enum class ThreadActivity : u32 {
  61. Normal = 0,
  62. Paused = 1,
  63. };
  64. class Thread final : public WaitObject {
  65. public:
  66. using TLSMemory = std::vector<u8>;
  67. using TLSMemoryPtr = std::shared_ptr<TLSMemory>;
  68. using MutexWaitingThreads = std::vector<SharedPtr<Thread>>;
  69. using ThreadContext = Core::ARM_Interface::ThreadContext;
  70. using ThreadWaitObjects = std::vector<SharedPtr<WaitObject>>;
  71. using WakeupCallback = std::function<bool(ThreadWakeupReason reason, SharedPtr<Thread> thread,
  72. SharedPtr<WaitObject> object, std::size_t index)>;
  73. /**
  74. * Creates and returns a new thread. The new thread is immediately scheduled
  75. * @param kernel The kernel instance this thread will be created under.
  76. * @param name The friendly name desired for the thread
  77. * @param entry_point The address at which the thread should start execution
  78. * @param priority The thread's priority
  79. * @param arg User data to pass to the thread
  80. * @param processor_id The ID(s) of the processors on which the thread is desired to be run
  81. * @param stack_top The address of the thread's stack top
  82. * @param owner_process The parent process for the thread
  83. * @return A shared pointer to the newly created thread
  84. */
  85. static ResultVal<SharedPtr<Thread>> Create(KernelCore& kernel, std::string name,
  86. VAddr entry_point, u32 priority, u64 arg,
  87. s32 processor_id, VAddr stack_top,
  88. Process& owner_process);
  89. std::string GetName() const override {
  90. return name;
  91. }
  92. void SetName(std::string new_name) {
  93. name = std::move(new_name);
  94. }
  95. std::string GetTypeName() const override {
  96. return "Thread";
  97. }
  98. static constexpr HandleType HANDLE_TYPE = HandleType::Thread;
  99. HandleType GetHandleType() const override {
  100. return HANDLE_TYPE;
  101. }
  102. bool ShouldWait(const Thread* thread) const override;
  103. void Acquire(Thread* thread) override;
  104. /**
  105. * Gets the thread's current priority
  106. * @return The current thread's priority
  107. */
  108. u32 GetPriority() const {
  109. return current_priority;
  110. }
  111. /**
  112. * Gets the thread's nominal priority.
  113. * @return The current thread's nominal priority.
  114. */
  115. u32 GetNominalPriority() const {
  116. return nominal_priority;
  117. }
  118. /**
  119. * Sets the thread's current priority
  120. * @param priority The new priority
  121. */
  122. void SetPriority(u32 priority);
  123. /// Adds a thread to the list of threads that are waiting for a lock held by this thread.
  124. void AddMutexWaiter(SharedPtr<Thread> thread);
  125. /// Removes a thread from the list of threads that are waiting for a lock held by this thread.
  126. void RemoveMutexWaiter(SharedPtr<Thread> thread);
  127. /// Recalculates the current priority taking into account priority inheritance.
  128. void UpdatePriority();
  129. /// Changes the core that the thread is running or scheduled to run on.
  130. void ChangeCore(u32 core, u64 mask);
  131. /**
  132. * Gets the thread's thread ID
  133. * @return The thread's ID
  134. */
  135. u64 GetThreadID() const {
  136. return thread_id;
  137. }
  138. TLSMemoryPtr& GetTLSMemory() {
  139. return tls_memory;
  140. }
  141. const TLSMemoryPtr& GetTLSMemory() const {
  142. return tls_memory;
  143. }
  144. /// Resumes a thread from waiting
  145. void ResumeFromWait();
  146. /// Cancels a waiting operation that this thread may or may not be within.
  147. ///
  148. /// When the thread is within a waiting state, this will set the thread's
  149. /// waiting result to signal a canceled wait. The function will then resume
  150. /// this thread.
  151. ///
  152. void CancelWait();
  153. /**
  154. * Schedules an event to wake up the specified thread after the specified delay
  155. * @param nanoseconds The time this thread will be allowed to sleep for
  156. */
  157. void WakeAfterDelay(s64 nanoseconds);
  158. /// Cancel any outstanding wakeup events for this thread
  159. void CancelWakeupTimer();
  160. /**
  161. * Sets the result after the thread awakens (from svcWaitSynchronization)
  162. * @param result Value to set to the returned result
  163. */
  164. void SetWaitSynchronizationResult(ResultCode result);
  165. /**
  166. * Sets the output parameter value after the thread awakens (from svcWaitSynchronization)
  167. * @param output Value to set to the output parameter
  168. */
  169. void SetWaitSynchronizationOutput(s32 output);
  170. /**
  171. * Retrieves the index that this particular object occupies in the list of objects
  172. * that the thread passed to WaitSynchronization, starting the search from the last element.
  173. *
  174. * It is used to set the output index of WaitSynchronization when the thread is awakened.
  175. *
  176. * When a thread wakes up due to an object signal, the kernel will use the index of the last
  177. * matching object in the wait objects list in case of having multiple instances of the same
  178. * object in the list.
  179. *
  180. * @param object Object to query the index of.
  181. */
  182. s32 GetWaitObjectIndex(const WaitObject* object) const;
  183. /**
  184. * Stops a thread, invalidating it from further use
  185. */
  186. void Stop();
  187. /*
  188. * Returns the Thread Local Storage address of the current thread
  189. * @returns VAddr of the thread's TLS
  190. */
  191. VAddr GetTLSAddress() const {
  192. return tls_address;
  193. }
  194. /*
  195. * Returns the value of the TPIDR_EL0 Read/Write system register for this thread.
  196. * @returns The value of the TPIDR_EL0 register.
  197. */
  198. u64 GetTPIDR_EL0() const {
  199. return tpidr_el0;
  200. }
  201. /// Sets the value of the TPIDR_EL0 Read/Write system register for this thread.
  202. void SetTPIDR_EL0(u64 value) {
  203. tpidr_el0 = value;
  204. }
  205. /*
  206. * Returns the address of the current thread's command buffer, located in the TLS.
  207. * @returns VAddr of the thread's command buffer.
  208. */
  209. VAddr GetCommandBufferAddress() const;
  210. /// Returns whether this thread is waiting on objects from a WaitSynchronization call.
  211. bool IsSleepingOnWait() const {
  212. return status == ThreadStatus::WaitSynch;
  213. }
  214. ThreadContext& GetContext() {
  215. return context;
  216. }
  217. const ThreadContext& GetContext() const {
  218. return context;
  219. }
  220. ThreadStatus GetStatus() const {
  221. return status;
  222. }
  223. void SetStatus(ThreadStatus new_status);
  224. u64 GetLastRunningTicks() const {
  225. return last_running_ticks;
  226. }
  227. u64 GetTotalCPUTimeTicks() const {
  228. return total_cpu_time_ticks;
  229. }
  230. void UpdateCPUTimeTicks(u64 ticks) {
  231. total_cpu_time_ticks += ticks;
  232. }
  233. s32 GetProcessorID() const {
  234. return processor_id;
  235. }
  236. Process* GetOwnerProcess() {
  237. return owner_process;
  238. }
  239. const Process* GetOwnerProcess() const {
  240. return owner_process;
  241. }
  242. const ThreadWaitObjects& GetWaitObjects() const {
  243. return wait_objects;
  244. }
  245. void SetWaitObjects(ThreadWaitObjects objects) {
  246. wait_objects = std::move(objects);
  247. }
  248. void ClearWaitObjects() {
  249. wait_objects.clear();
  250. }
  251. /// Determines whether all the objects this thread is waiting on are ready.
  252. bool AllWaitObjectsReady() const;
  253. const MutexWaitingThreads& GetMutexWaitingThreads() const {
  254. return wait_mutex_threads;
  255. }
  256. Thread* GetLockOwner() const {
  257. return lock_owner.get();
  258. }
  259. void SetLockOwner(SharedPtr<Thread> owner) {
  260. lock_owner = std::move(owner);
  261. }
  262. VAddr GetCondVarWaitAddress() const {
  263. return condvar_wait_address;
  264. }
  265. void SetCondVarWaitAddress(VAddr address) {
  266. condvar_wait_address = address;
  267. }
  268. VAddr GetMutexWaitAddress() const {
  269. return mutex_wait_address;
  270. }
  271. void SetMutexWaitAddress(VAddr address) {
  272. mutex_wait_address = address;
  273. }
  274. Handle GetWaitHandle() const {
  275. return wait_handle;
  276. }
  277. void SetWaitHandle(Handle handle) {
  278. wait_handle = handle;
  279. }
  280. VAddr GetArbiterWaitAddress() const {
  281. return arb_wait_address;
  282. }
  283. void SetArbiterWaitAddress(VAddr address) {
  284. arb_wait_address = address;
  285. }
  286. bool HasWakeupCallback() const {
  287. return wakeup_callback != nullptr;
  288. }
  289. void SetWakeupCallback(WakeupCallback callback) {
  290. wakeup_callback = std::move(callback);
  291. }
  292. void InvalidateWakeupCallback() {
  293. SetWakeupCallback(nullptr);
  294. }
  295. /**
  296. * Invokes the thread's wakeup callback.
  297. *
  298. * @pre A valid wakeup callback has been set. Violating this precondition
  299. * will cause an assertion to trigger.
  300. */
  301. bool InvokeWakeupCallback(ThreadWakeupReason reason, SharedPtr<Thread> thread,
  302. SharedPtr<WaitObject> object, std::size_t index);
  303. u32 GetIdealCore() const {
  304. return ideal_core;
  305. }
  306. u64 GetAffinityMask() const {
  307. return affinity_mask;
  308. }
  309. ThreadActivity GetActivity() const {
  310. return activity;
  311. }
  312. void SetActivity(ThreadActivity value);
  313. /// Sleeps this thread for the given amount of nanoseconds.
  314. void Sleep(s64 nanoseconds);
  315. private:
  316. explicit Thread(KernelCore& kernel);
  317. ~Thread() override;
  318. void ChangeScheduler();
  319. Core::ARM_Interface::ThreadContext context{};
  320. u64 thread_id = 0;
  321. ThreadStatus status = ThreadStatus::Dormant;
  322. VAddr entry_point = 0;
  323. VAddr stack_top = 0;
  324. /// Nominal thread priority, as set by the emulated application.
  325. /// The nominal priority is the thread priority without priority
  326. /// inheritance taken into account.
  327. u32 nominal_priority = 0;
  328. /// Current thread priority. This may change over the course of the
  329. /// thread's lifetime in order to facilitate priority inheritance.
  330. u32 current_priority = 0;
  331. u64 total_cpu_time_ticks = 0; ///< Total CPU running ticks.
  332. u64 last_running_ticks = 0; ///< CPU tick when thread was last running
  333. s32 processor_id = 0;
  334. VAddr tls_address = 0; ///< Virtual address of the Thread Local Storage of the thread
  335. u64 tpidr_el0 = 0; ///< TPIDR_EL0 read/write system register.
  336. /// Process that owns this thread
  337. Process* owner_process;
  338. /// Objects that the thread is waiting on, in the same order as they were
  339. /// passed to WaitSynchronization.
  340. ThreadWaitObjects wait_objects;
  341. /// List of threads that are waiting for a mutex that is held by this thread.
  342. MutexWaitingThreads wait_mutex_threads;
  343. /// Thread that owns the lock that this thread is waiting for.
  344. SharedPtr<Thread> lock_owner;
  345. /// If waiting on a ConditionVariable, this is the ConditionVariable address
  346. VAddr condvar_wait_address = 0;
  347. /// If waiting on a Mutex, this is the mutex address
  348. VAddr mutex_wait_address = 0;
  349. /// The handle used to wait for the mutex.
  350. Handle wait_handle = 0;
  351. /// If waiting for an AddressArbiter, this is the address being waited on.
  352. VAddr arb_wait_address{0};
  353. /// Handle used as userdata to reference this object when inserting into the CoreTiming queue.
  354. Handle callback_handle = 0;
  355. /// Callback that will be invoked when the thread is resumed from a waiting state. If the thread
  356. /// was waiting via WaitSynchronization then the object will be the last object that became
  357. /// available. In case of a timeout, the object will be nullptr.
  358. WakeupCallback wakeup_callback;
  359. Scheduler* scheduler = nullptr;
  360. u32 ideal_core{0xFFFFFFFF};
  361. u64 affinity_mask{0x1};
  362. TLSMemoryPtr tls_memory = std::make_shared<TLSMemory>();
  363. std::string name;
  364. ThreadActivity activity = ThreadActivity::Normal;
  365. };
  366. /**
  367. * Gets the current thread
  368. */
  369. Thread* GetCurrentThread();
  370. } // namespace Kernel