thread.h 14 KB

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