thread.h 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  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. /**
  55. * Creates and returns a new thread. The new thread is immediately scheduled
  56. * @param kernel The kernel instance this thread will be created under.
  57. * @param name The friendly name desired for the thread
  58. * @param entry_point The address at which the thread should start execution
  59. * @param priority The thread's priority
  60. * @param arg User data to pass to the thread
  61. * @param processor_id The ID(s) of the processors on which the thread is desired to be run
  62. * @param stack_top The address of the thread's stack top
  63. * @param owner_process The parent process for the thread
  64. * @return A shared pointer to the newly created thread
  65. */
  66. static ResultVal<SharedPtr<Thread>> Create(KernelCore& kernel, std::string name,
  67. VAddr entry_point, u32 priority, u64 arg,
  68. s32 processor_id, VAddr stack_top,
  69. SharedPtr<Process> owner_process);
  70. std::string GetName() const override {
  71. return name;
  72. }
  73. std::string GetTypeName() const override {
  74. return "Thread";
  75. }
  76. static const HandleType HANDLE_TYPE = HandleType::Thread;
  77. HandleType GetHandleType() const override {
  78. return HANDLE_TYPE;
  79. }
  80. bool ShouldWait(Thread* thread) const override;
  81. void Acquire(Thread* thread) override;
  82. /**
  83. * Gets the thread's current priority
  84. * @return The current thread's priority
  85. */
  86. u32 GetPriority() const {
  87. return current_priority;
  88. }
  89. /**
  90. * Sets the thread's current priority
  91. * @param priority The new priority
  92. */
  93. void SetPriority(u32 priority);
  94. /**
  95. * Temporarily boosts the thread's priority until the next time it is scheduled
  96. * @param priority The new priority
  97. */
  98. void BoostPriority(u32 priority);
  99. /// Adds a thread to the list of threads that are waiting for a lock held by this thread.
  100. void AddMutexWaiter(SharedPtr<Thread> thread);
  101. /// Removes a thread from the list of threads that are waiting for a lock held by this thread.
  102. void RemoveMutexWaiter(SharedPtr<Thread> thread);
  103. /// Recalculates the current priority taking into account priority inheritance.
  104. void UpdatePriority();
  105. /// Changes the core that the thread is running or scheduled to run on.
  106. void ChangeCore(u32 core, u64 mask);
  107. /**
  108. * Gets the thread's thread ID
  109. * @return The thread's ID
  110. */
  111. u32 GetThreadId() const {
  112. return thread_id;
  113. }
  114. /**
  115. * Resumes a thread from waiting
  116. */
  117. void ResumeFromWait();
  118. /**
  119. * Schedules an event to wake up the specified thread after the specified delay
  120. * @param nanoseconds The time this thread will be allowed to sleep for
  121. */
  122. void WakeAfterDelay(s64 nanoseconds);
  123. /// Cancel any outstanding wakeup events for this thread
  124. void CancelWakeupTimer();
  125. /**
  126. * Sets the result after the thread awakens (from either WaitSynchronization SVC)
  127. * @param result Value to set to the returned result
  128. */
  129. void SetWaitSynchronizationResult(ResultCode result);
  130. /**
  131. * Sets the output parameter value after the thread awakens (from WaitSynchronizationN SVC only)
  132. * @param output Value to set to the output parameter
  133. */
  134. void SetWaitSynchronizationOutput(s32 output);
  135. /**
  136. * Retrieves the index that this particular object occupies in the list of objects
  137. * that the thread passed to WaitSynchronizationN, starting the search from the last element.
  138. * It is used to set the output value of WaitSynchronizationN when the thread is awakened.
  139. * When a thread wakes up due to an object signal, the kernel will use the index of the last
  140. * matching object in the wait objects list in case of having multiple instances of the same
  141. * object in the list.
  142. * @param object Object to query the index of.
  143. */
  144. s32 GetWaitObjectIndex(WaitObject* object) const;
  145. /**
  146. * Stops a thread, invalidating it from further use
  147. */
  148. void Stop();
  149. /*
  150. * Returns the Thread Local Storage address of the current thread
  151. * @returns VAddr of the thread's TLS
  152. */
  153. VAddr GetTLSAddress() const {
  154. return tls_address;
  155. }
  156. /*
  157. * Returns the value of the TPIDR_EL0 Read/Write system register for this thread.
  158. * @returns The value of the TPIDR_EL0 register.
  159. */
  160. u64 GetTPIDR_EL0() const {
  161. return tpidr_el0;
  162. }
  163. /*
  164. * Returns the address of the current thread's command buffer, located in the TLS.
  165. * @returns VAddr of the thread's command buffer.
  166. */
  167. VAddr GetCommandBufferAddress() const;
  168. /**
  169. * Returns whether this thread is waiting for all the objects in
  170. * its wait list to become ready, as a result of a WaitSynchronizationN call
  171. * with wait_all = true.
  172. */
  173. bool IsSleepingOnWaitAll() const {
  174. return status == ThreadStatus::WaitSynchAll;
  175. }
  176. Core::ARM_Interface::ThreadContext context;
  177. u32 thread_id;
  178. ThreadStatus status;
  179. VAddr entry_point;
  180. VAddr stack_top;
  181. u32 nominal_priority; ///< Nominal thread priority, as set by the emulated application
  182. u32 current_priority; ///< Current thread priority, can be temporarily changed
  183. u64 last_running_ticks; ///< CPU tick when thread was last running
  184. s32 processor_id;
  185. VAddr tls_address; ///< Virtual address of the Thread Local Storage of the thread
  186. u64 tpidr_el0; ///< TPIDR_EL0 read/write system register.
  187. SharedPtr<Process> owner_process; ///< Process that owns this thread
  188. /// Objects that the thread is waiting on, in the same order as they were
  189. // passed to WaitSynchronization1/N.
  190. std::vector<SharedPtr<WaitObject>> wait_objects;
  191. /// List of threads that are waiting for a mutex that is held by this thread.
  192. std::vector<SharedPtr<Thread>> wait_mutex_threads;
  193. /// Thread that owns the lock that this thread is waiting for.
  194. SharedPtr<Thread> lock_owner;
  195. // If waiting on a ConditionVariable, this is the ConditionVariable address
  196. VAddr condvar_wait_address;
  197. VAddr mutex_wait_address; ///< If waiting on a Mutex, this is the mutex address
  198. Handle wait_handle; ///< The handle used to wait for the mutex.
  199. // If waiting for an AddressArbiter, this is the address being waited on.
  200. VAddr arb_wait_address{0};
  201. std::string name;
  202. /// Handle used by guest emulated application to access this thread
  203. Handle guest_handle;
  204. /// Handle used as userdata to reference this object when inserting into the CoreTiming queue.
  205. Handle callback_handle;
  206. using WakeupCallback = bool(ThreadWakeupReason reason, SharedPtr<Thread> thread,
  207. SharedPtr<WaitObject> object, std::size_t index);
  208. // Callback that will be invoked when the thread is resumed from a waiting state. If the thread
  209. // was waiting via WaitSynchronizationN then the object will be the last object that became
  210. // available. In case of a timeout, the object will be nullptr.
  211. std::function<WakeupCallback> wakeup_callback;
  212. std::shared_ptr<Scheduler> scheduler;
  213. u32 ideal_core{0xFFFFFFFF};
  214. u64 affinity_mask{0x1};
  215. private:
  216. explicit Thread(KernelCore& kernel);
  217. ~Thread() override;
  218. std::shared_ptr<std::vector<u8>> tls_memory = std::make_shared<std::vector<u8>>();
  219. };
  220. /**
  221. * Sets up the primary application thread
  222. * @param kernel The kernel instance to create the main thread under.
  223. * @param entry_point The address at which the thread should start execution
  224. * @param priority The priority to give the main thread
  225. * @param owner_process The parent process for the main thread
  226. * @return A shared pointer to the main thread
  227. */
  228. SharedPtr<Thread> SetupMainThread(KernelCore& kernel, VAddr entry_point, u32 priority,
  229. Process& owner_process);
  230. /**
  231. * Gets the current thread
  232. */
  233. Thread* GetCurrentThread();
  234. /**
  235. * Waits the current thread on a sleep
  236. */
  237. void WaitCurrentThread_Sleep();
  238. /**
  239. * Stops the current thread and removes it from the thread_list
  240. */
  241. void ExitCurrentThread();
  242. } // namespace Kernel