thread.h 14 KB

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