thread.h 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  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/kernel.h"
  12. #include "core/hle/kernel/wait_object.h"
  13. #include "core/hle/result.h"
  14. enum ThreadPriority : u32 {
  15. THREADPRIO_HIGHEST = 0, ///< Highest thread priority
  16. THREADPRIO_USERLAND_MAX = 24, ///< Highest thread priority for userland apps
  17. THREADPRIO_DEFAULT = 44, ///< Default thread priority for userland apps
  18. THREADPRIO_LOWEST = 63, ///< Lowest thread priority
  19. };
  20. enum ThreadProcessorId : s32 {
  21. THREADPROCESSORID_DEFAULT = -2, ///< Run thread on default core specified by exheader
  22. THREADPROCESSORID_0 = 0, ///< Run thread on core 0
  23. THREADPROCESSORID_1 = 1, ///< Run thread on core 1
  24. THREADPROCESSORID_2 = 2, ///< Run thread on core 2
  25. THREADPROCESSORID_3 = 3, ///< Run thread on core 3
  26. THREADPROCESSORID_MAX = 4, ///< Processor ID must be less than this
  27. /// Allowed CPU mask
  28. THREADPROCESSORID_DEFAULT_MASK = (1 << THREADPROCESSORID_0) | (1 << THREADPROCESSORID_1) |
  29. (1 << THREADPROCESSORID_2) | (1 << THREADPROCESSORID_3)
  30. };
  31. enum class ThreadStatus {
  32. Running, ///< Currently running
  33. Ready, ///< Ready to run
  34. WaitHLEEvent, ///< Waiting for hle event to finish
  35. WaitSleep, ///< Waiting due to a SleepThread SVC
  36. WaitIPC, ///< Waiting for the reply from an IPC request
  37. WaitSynchAny, ///< Waiting due to WaitSynch1 or WaitSynchN with wait_all = false
  38. WaitSynchAll, ///< Waiting due to WaitSynchronizationN with wait_all = true
  39. WaitMutex, ///< Waiting due to an ArbitrateLock/WaitProcessWideKey svc
  40. WaitArb, ///< Waiting due to a SignalToAddress/WaitForAddress svc
  41. Dormant, ///< Created but not yet made ready
  42. Dead ///< Run to completion, or forcefully terminated
  43. };
  44. enum class ThreadWakeupReason {
  45. Signal, // The thread was woken up by WakeupAllWaitingThreads due to an object signal.
  46. Timeout // The thread was woken up due to a wait timeout.
  47. };
  48. namespace Kernel {
  49. class Process;
  50. class Scheduler;
  51. class Thread final : public WaitObject {
  52. public:
  53. /**
  54. * Creates and returns a new thread. The new thread is immediately scheduled
  55. * @param name The friendly name desired for the thread
  56. * @param entry_point The address at which the thread should start execution
  57. * @param priority The thread's priority
  58. * @param arg User data to pass to the thread
  59. * @param processor_id The ID(s) of the processors on which the thread is desired to be run
  60. * @param stack_top The address of the thread's stack top
  61. * @param owner_process The parent process for the thread
  62. * @return A shared pointer to the newly created thread
  63. */
  64. static ResultVal<SharedPtr<Thread>> Create(std::string name, VAddr entry_point, u32 priority,
  65. u64 arg, s32 processor_id, VAddr stack_top,
  66. SharedPtr<Process> owner_process);
  67. std::string GetName() const override {
  68. return name;
  69. }
  70. std::string GetTypeName() const override {
  71. return "Thread";
  72. }
  73. static const HandleType HANDLE_TYPE = HandleType::Thread;
  74. HandleType GetHandleType() const override {
  75. return HANDLE_TYPE;
  76. }
  77. bool ShouldWait(Thread* thread) const override;
  78. void Acquire(Thread* thread) override;
  79. /**
  80. * Gets the thread's current priority
  81. * @return The current thread's priority
  82. */
  83. u32 GetPriority() const {
  84. return current_priority;
  85. }
  86. /**
  87. * Sets the thread's current priority
  88. * @param priority The new priority
  89. */
  90. void SetPriority(u32 priority);
  91. /**
  92. * Temporarily boosts the thread's priority until the next time it is scheduled
  93. * @param priority The new priority
  94. */
  95. void BoostPriority(u32 priority);
  96. /// Adds a thread to the list of threads that are waiting for a lock held by this thread.
  97. void AddMutexWaiter(SharedPtr<Thread> thread);
  98. /// Removes a thread from the list of threads that are waiting for a lock held by this thread.
  99. void RemoveMutexWaiter(SharedPtr<Thread> thread);
  100. /// Recalculates the current priority taking into account priority inheritance.
  101. void UpdatePriority();
  102. /// Changes the core that the thread is running or scheduled to run on.
  103. void ChangeCore(u32 core, u64 mask);
  104. /**
  105. * Gets the thread's thread ID
  106. * @return The thread's ID
  107. */
  108. u32 GetThreadId() const {
  109. return thread_id;
  110. }
  111. /**
  112. * Resumes a thread from waiting
  113. */
  114. void ResumeFromWait();
  115. /**
  116. * Schedules an event to wake up the specified thread after the specified delay
  117. * @param nanoseconds The time this thread will be allowed to sleep for
  118. */
  119. void WakeAfterDelay(s64 nanoseconds);
  120. /// Cancel any outstanding wakeup events for this thread
  121. void CancelWakeupTimer();
  122. /**
  123. * Sets the result after the thread awakens (from either WaitSynchronization SVC)
  124. * @param result Value to set to the returned result
  125. */
  126. void SetWaitSynchronizationResult(ResultCode result);
  127. /**
  128. * Sets the output parameter value after the thread awakens (from WaitSynchronizationN SVC only)
  129. * @param output Value to set to the output parameter
  130. */
  131. void SetWaitSynchronizationOutput(s32 output);
  132. /**
  133. * Retrieves the index that this particular object occupies in the list of objects
  134. * that the thread passed to WaitSynchronizationN, starting the search from the last element.
  135. * It is used to set the output value of WaitSynchronizationN when the thread is awakened.
  136. * When a thread wakes up due to an object signal, the kernel will use the index of the last
  137. * matching object in the wait objects list in case of having multiple instances of the same
  138. * object in the list.
  139. * @param object Object to query the index of.
  140. */
  141. s32 GetWaitObjectIndex(WaitObject* object) const;
  142. /**
  143. * Stops a thread, invalidating it from further use
  144. */
  145. void Stop();
  146. /*
  147. * Returns the Thread Local Storage address of the current thread
  148. * @returns VAddr of the thread's TLS
  149. */
  150. VAddr GetTLSAddress() const {
  151. return tls_address;
  152. }
  153. /*
  154. * Returns the value of the TPIDR_EL0 Read/Write system register for this thread.
  155. * @returns The value of the TPIDR_EL0 register.
  156. */
  157. u64 GetTPIDR_EL0() const {
  158. return tpidr_el0;
  159. }
  160. /*
  161. * Returns the address of the current thread's command buffer, located in the TLS.
  162. * @returns VAddr of the thread's command buffer.
  163. */
  164. VAddr GetCommandBufferAddress() const;
  165. /**
  166. * Returns whether this thread is waiting for all the objects in
  167. * its wait list to become ready, as a result of a WaitSynchronizationN call
  168. * with wait_all = true.
  169. */
  170. bool IsSleepingOnWaitAll() const {
  171. return status == ThreadStatus::WaitSynchAll;
  172. }
  173. ARM_Interface::ThreadContext context;
  174. u32 thread_id;
  175. ThreadStatus status;
  176. VAddr entry_point;
  177. VAddr stack_top;
  178. u32 nominal_priority; ///< Nominal thread priority, as set by the emulated application
  179. u32 current_priority; ///< Current thread priority, can be temporarily changed
  180. u64 last_running_ticks; ///< CPU tick when thread was last running
  181. s32 processor_id;
  182. VAddr tls_address; ///< Virtual address of the Thread Local Storage of the thread
  183. u64 tpidr_el0; ///< TPIDR_EL0 read/write system register.
  184. SharedPtr<Process> owner_process; ///< Process that owns this thread
  185. /// Objects that the thread is waiting on, in the same order as they were
  186. // passed to WaitSynchronization1/N.
  187. std::vector<SharedPtr<WaitObject>> wait_objects;
  188. /// List of threads that are waiting for a mutex that is held by this thread.
  189. std::vector<SharedPtr<Thread>> wait_mutex_threads;
  190. /// Thread that owns the lock that this thread is waiting for.
  191. SharedPtr<Thread> lock_owner;
  192. // If waiting on a ConditionVariable, this is the ConditionVariable address
  193. VAddr condvar_wait_address;
  194. VAddr mutex_wait_address; ///< If waiting on a Mutex, this is the mutex address
  195. Handle wait_handle; ///< The handle used to wait for the mutex.
  196. // If waiting for an AddressArbiter, this is the address being waited on.
  197. VAddr arb_wait_address{0};
  198. std::string name;
  199. /// Handle used by guest emulated application to access this thread
  200. Handle guest_handle;
  201. /// Handle used as userdata to reference this object when inserting into the CoreTiming queue.
  202. Handle callback_handle;
  203. using WakeupCallback = bool(ThreadWakeupReason reason, SharedPtr<Thread> thread,
  204. SharedPtr<WaitObject> object, size_t index);
  205. // Callback that will be invoked when the thread is resumed from a waiting state. If the thread
  206. // was waiting via WaitSynchronizationN then the object will be the last object that became
  207. // available. In case of a timeout, the object will be nullptr.
  208. std::function<WakeupCallback> wakeup_callback;
  209. std::shared_ptr<Scheduler> scheduler;
  210. u32 ideal_core{0xFFFFFFFF};
  211. u64 affinity_mask{0x1};
  212. private:
  213. Thread();
  214. ~Thread() override;
  215. };
  216. /**
  217. * Sets up the primary application thread
  218. * @param entry_point The address at which the thread should start execution
  219. * @param priority The priority to give the main thread
  220. * @param owner_process The parent process for the main thread
  221. * @return A shared pointer to the main thread
  222. */
  223. SharedPtr<Thread> SetupMainThread(VAddr entry_point, u32 priority,
  224. SharedPtr<Process> owner_process);
  225. /**
  226. * Gets the current thread
  227. */
  228. Thread* GetCurrentThread();
  229. /**
  230. * Waits the current thread on a sleep
  231. */
  232. void WaitCurrentThread_Sleep();
  233. /**
  234. * Waits the current thread from an ArbitrateAddress call
  235. * @param wait_address Arbitration address used to resume from wait
  236. */
  237. void WaitCurrentThread_ArbitrateAddress(VAddr wait_address);
  238. /**
  239. * Stops the current thread and removes it from the thread_list
  240. */
  241. void ExitCurrentThread();
  242. /**
  243. * Initialize threading
  244. */
  245. void ThreadingInit();
  246. /**
  247. * Shutdown threading
  248. */
  249. void ThreadingShutdown();
  250. } // namespace Kernel