thread.h 10 KB

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