thread.h 14 KB

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