thread.h 9.8 KB

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