thread.h 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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. /**
  112. * Sets the result after the thread awakens (from either WaitSynchronization SVC)
  113. * @param result Value to set to the returned result
  114. */
  115. void SetWaitSynchronizationResult(ResultCode result);
  116. /**
  117. * Sets the output parameter value after the thread awakens (from WaitSynchronizationN SVC only)
  118. * @param output Value to set to the output parameter
  119. */
  120. void SetWaitSynchronizationOutput(s32 output);
  121. /**
  122. * Retrieves the index that this particular object occupies in the list of objects
  123. * that the thread passed to WaitSynchronizationN, starting the search from the last element.
  124. * It is used to set the output value of WaitSynchronizationN when the thread is awakened.
  125. * When a thread wakes up due to an object signal, the kernel will use the index of the last
  126. * matching object in the wait objects list in case of having multiple instances of the same
  127. * object in the list.
  128. * @param object Object to query the index of.
  129. */
  130. s32 GetWaitObjectIndex(WaitObject* object) const;
  131. /**
  132. * Stops a thread, invalidating it from further use
  133. */
  134. void Stop();
  135. /*
  136. * Returns the Thread Local Storage address of the current thread
  137. * @returns VAddr of the thread's TLS
  138. */
  139. VAddr GetTLSAddress() const {
  140. return tls_address;
  141. }
  142. /*
  143. * Returns the address of the current thread's command buffer, located in the TLS.
  144. * @returns VAddr of the thread's command buffer.
  145. */
  146. VAddr GetCommandBufferAddress() const;
  147. /**
  148. * Returns whether this thread is waiting for all the objects in
  149. * its wait list to become ready, as a result of a WaitSynchronizationN call
  150. * with wait_all = true.
  151. */
  152. bool IsSleepingOnWaitAll() const {
  153. return status == THREADSTATUS_WAIT_SYNCH_ALL;
  154. }
  155. ARM_Interface::ThreadContext context;
  156. u32 thread_id;
  157. u32 status;
  158. VAddr entry_point;
  159. VAddr stack_top;
  160. u32 nominal_priority; ///< Nominal thread priority, as set by the emulated application
  161. u32 current_priority; ///< Current thread priority, can be temporarily changed
  162. u64 last_running_ticks; ///< CPU tick when thread was last running
  163. s32 processor_id;
  164. VAddr tls_address; ///< Virtual address of the Thread Local Storage of the thread
  165. /// Mutexes currently held by this thread, which will be released when it exits.
  166. boost::container::flat_set<SharedPtr<Mutex>> held_mutexes;
  167. /// Mutexes that this thread is currently waiting for.
  168. boost::container::flat_set<SharedPtr<Mutex>> pending_mutexes;
  169. SharedPtr<Process> owner_process; ///< Process that owns this thread
  170. /// Objects that the thread is waiting on, in the same order as they were
  171. // passed to WaitSynchronization1/N.
  172. std::vector<SharedPtr<WaitObject>> wait_objects;
  173. VAddr wait_address; ///< If waiting on an AddressArbiter, this is the arbitration address
  174. std::string name;
  175. /// Handle used by guest emulated application to access this thread
  176. Handle guest_handle;
  177. /// Handle used as userdata to reference this object when inserting into the CoreTiming queue.
  178. Handle callback_handle;
  179. using WakeupCallback = void(ThreadWakeupReason reason, SharedPtr<Thread> thread,
  180. SharedPtr<WaitObject> object);
  181. // Callback that will be invoked when the thread is resumed from a waiting state. If the thread
  182. // was waiting via WaitSynchronizationN then the object will be the last object that became
  183. // available. In case of a timeout, the object will be nullptr.
  184. std::function<WakeupCallback> wakeup_callback;
  185. private:
  186. Thread();
  187. ~Thread() override;
  188. };
  189. /**
  190. * Sets up the primary application thread
  191. * @param entry_point The address at which the thread should start execution
  192. * @param priority The priority to give the main thread
  193. * @param owner_process The parent process for the main thread
  194. * @return A shared pointer to the main thread
  195. */
  196. SharedPtr<Thread> SetupMainThread(VAddr entry_point, u32 priority, SharedPtr<Process> owner_process);
  197. /**
  198. * Returns whether there are any threads that are ready to run.
  199. */
  200. bool HaveReadyThreads();
  201. /**
  202. * Reschedules to the next available thread (call after current thread is suspended)
  203. */
  204. void Reschedule();
  205. /**
  206. * Arbitrate the highest priority thread that is waiting
  207. * @param address The address for which waiting threads should be arbitrated
  208. */
  209. Thread* ArbitrateHighestPriorityThread(VAddr address);
  210. /**
  211. * Arbitrate all threads currently waiting.
  212. * @param address The address for which waiting threads should be arbitrated
  213. */
  214. void ArbitrateAllThreads(VAddr address);
  215. /**
  216. * Gets the current thread
  217. */
  218. Thread* GetCurrentThread();
  219. /**
  220. * Waits the current thread on a sleep
  221. */
  222. void WaitCurrentThread_Sleep();
  223. /**
  224. * Waits the current thread from an ArbitrateAddress call
  225. * @param wait_address Arbitration address used to resume from wait
  226. */
  227. void WaitCurrentThread_ArbitrateAddress(VAddr wait_address);
  228. /**
  229. * Stops the current thread and removes it from the thread_list
  230. */
  231. void ExitCurrentThread();
  232. /**
  233. * Initialize threading
  234. */
  235. void ThreadingInit();
  236. /**
  237. * Shutdown threading
  238. */
  239. void ThreadingShutdown();
  240. /**
  241. * Get a const reference to the thread list for debug use
  242. */
  243. const std::vector<SharedPtr<Thread>>& GetThreadList();
  244. } // namespace Kernel