thread.h 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684
  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 <string>
  7. #include <vector>
  8. #include "common/common_types.h"
  9. #include "common/spin_lock.h"
  10. #include "core/arm/arm_interface.h"
  11. #include "core/hle/kernel/object.h"
  12. #include "core/hle/kernel/synchronization_object.h"
  13. #include "core/hle/result.h"
  14. namespace Common {
  15. class Fiber;
  16. }
  17. namespace Core {
  18. class System;
  19. } // namespace Core
  20. namespace Kernel {
  21. class GlobalScheduler;
  22. class KernelCore;
  23. class Process;
  24. class Scheduler;
  25. enum ThreadPriority : u32 {
  26. THREADPRIO_HIGHEST = 0, ///< Highest thread priority
  27. THREADPRIO_MAX_CORE_MIGRATION = 2, ///< Highest priority for a core migration
  28. THREADPRIO_USERLAND_MAX = 24, ///< Highest thread priority for userland apps
  29. THREADPRIO_DEFAULT = 44, ///< Default thread priority for userland apps
  30. THREADPRIO_LOWEST = 63, ///< Lowest thread priority
  31. THREADPRIO_COUNT = 64, ///< Total number of possible thread priorities.
  32. };
  33. enum ThreadType : u32 {
  34. THREADTYPE_USER = 0x1,
  35. THREADTYPE_KERNEL = 0x2,
  36. THREADTYPE_HLE = 0x4,
  37. THREADTYPE_IDLE = 0x8,
  38. THREADTYPE_SUSPEND = 0x10,
  39. };
  40. enum ThreadProcessorId : s32 {
  41. /// Indicates that no particular processor core is preferred.
  42. THREADPROCESSORID_DONT_CARE = -1,
  43. /// Run thread on the ideal core specified by the process.
  44. THREADPROCESSORID_IDEAL = -2,
  45. /// Indicates that the preferred processor ID shouldn't be updated in
  46. /// a core mask setting operation.
  47. THREADPROCESSORID_DONT_UPDATE = -3,
  48. THREADPROCESSORID_0 = 0, ///< Run thread on core 0
  49. THREADPROCESSORID_1 = 1, ///< Run thread on core 1
  50. THREADPROCESSORID_2 = 2, ///< Run thread on core 2
  51. THREADPROCESSORID_3 = 3, ///< Run thread on core 3
  52. THREADPROCESSORID_MAX = 4, ///< Processor ID must be less than this
  53. /// Allowed CPU mask
  54. THREADPROCESSORID_DEFAULT_MASK = (1 << THREADPROCESSORID_0) | (1 << THREADPROCESSORID_1) |
  55. (1 << THREADPROCESSORID_2) | (1 << THREADPROCESSORID_3)
  56. };
  57. enum class ThreadStatus {
  58. Running, ///< Currently running
  59. Ready, ///< Ready to run
  60. Paused, ///< Paused by SetThreadActivity or debug
  61. WaitHLEEvent, ///< Waiting for hle event to finish
  62. WaitSleep, ///< Waiting due to a SleepThread SVC
  63. WaitIPC, ///< Waiting for the reply from an IPC request
  64. WaitSynch, ///< Waiting due to WaitSynchronization
  65. WaitMutex, ///< Waiting due to an ArbitrateLock svc
  66. WaitCondVar, ///< Waiting due to an WaitProcessWideKey svc
  67. WaitArb, ///< Waiting due to a SignalToAddress/WaitForAddress svc
  68. Dormant, ///< Created but not yet made ready
  69. Dead ///< Run to completion, or forcefully terminated
  70. };
  71. enum class ThreadWakeupReason {
  72. Signal, // The thread was woken up by WakeupAllWaitingThreads due to an object signal.
  73. Timeout // The thread was woken up due to a wait timeout.
  74. };
  75. enum class ThreadActivity : u32 {
  76. Normal = 0,
  77. Paused = 1,
  78. };
  79. enum class ThreadSchedStatus : u32 {
  80. None = 0,
  81. Paused = 1,
  82. Runnable = 2,
  83. Exited = 3,
  84. };
  85. enum class ThreadSchedFlags : u32 {
  86. ProcessPauseFlag = 1 << 4,
  87. ThreadPauseFlag = 1 << 5,
  88. ProcessDebugPauseFlag = 1 << 6,
  89. KernelInitPauseFlag = 1 << 8,
  90. };
  91. enum class ThreadSchedMasks : u32 {
  92. LowMask = 0x000f,
  93. HighMask = 0xfff0,
  94. ForcePauseMask = 0x0070,
  95. };
  96. class Thread final : public SynchronizationObject {
  97. public:
  98. explicit Thread(KernelCore& kernel);
  99. ~Thread() override;
  100. using MutexWaitingThreads = std::vector<std::shared_ptr<Thread>>;
  101. using ThreadContext32 = Core::ARM_Interface::ThreadContext32;
  102. using ThreadContext64 = Core::ARM_Interface::ThreadContext64;
  103. using ThreadSynchronizationObjects = std::vector<std::shared_ptr<SynchronizationObject>>;
  104. using WakeupCallback =
  105. std::function<bool(ThreadWakeupReason reason, std::shared_ptr<Thread> thread,
  106. std::shared_ptr<SynchronizationObject> object, std::size_t index)>;
  107. using HLECallback = std::function<bool(std::shared_ptr<Thread> thread)>;
  108. /**
  109. * Creates and returns a new thread. The new thread is immediately scheduled
  110. * @param system The instance of the whole system
  111. * @param name The friendly name desired for the thread
  112. * @param entry_point The address at which the thread should start execution
  113. * @param priority The thread's priority
  114. * @param arg User data to pass to the thread
  115. * @param processor_id The ID(s) of the processors on which the thread is desired to be run
  116. * @param stack_top The address of the thread's stack top
  117. * @param owner_process The parent process for the thread, if null, it's a kernel thread
  118. * @return A shared pointer to the newly created thread
  119. */
  120. static ResultVal<std::shared_ptr<Thread>> Create(Core::System& system, ThreadType type_flags,
  121. std::string name, VAddr entry_point,
  122. u32 priority, u64 arg, s32 processor_id,
  123. VAddr stack_top, Process* owner_process);
  124. /**
  125. * Creates and returns a new thread. The new thread is immediately scheduled
  126. * @param system The instance of the whole system
  127. * @param name The friendly name desired for the thread
  128. * @param entry_point The address at which the thread should start execution
  129. * @param priority The thread's priority
  130. * @param arg User data to pass to the thread
  131. * @param processor_id The ID(s) of the processors on which the thread is desired to be run
  132. * @param stack_top The address of the thread's stack top
  133. * @param owner_process The parent process for the thread, if null, it's a kernel thread
  134. * @param thread_start_func The function where the host context will start.
  135. * @param thread_start_parameter The parameter which will passed to host context on init
  136. * @return A shared pointer to the newly created thread
  137. */
  138. static ResultVal<std::shared_ptr<Thread>> Create(Core::System& system, ThreadType type_flags,
  139. std::string name, VAddr entry_point,
  140. u32 priority, u64 arg, s32 processor_id,
  141. VAddr stack_top, Process* owner_process,
  142. std::function<void(void*)>&& thread_start_func,
  143. void* thread_start_parameter);
  144. std::string GetName() const override {
  145. return name;
  146. }
  147. void SetName(std::string new_name) {
  148. name = std::move(new_name);
  149. }
  150. std::string GetTypeName() const override {
  151. return "Thread";
  152. }
  153. static constexpr HandleType HANDLE_TYPE = HandleType::Thread;
  154. HandleType GetHandleType() const override {
  155. return HANDLE_TYPE;
  156. }
  157. bool ShouldWait(const Thread* thread) const override;
  158. void Acquire(Thread* thread) override;
  159. bool IsSignaled() const override;
  160. /**
  161. * Gets the thread's current priority
  162. * @return The current thread's priority
  163. */
  164. u32 GetPriority() const {
  165. return current_priority;
  166. }
  167. /**
  168. * Gets the thread's nominal priority.
  169. * @return The current thread's nominal priority.
  170. */
  171. u32 GetNominalPriority() const {
  172. return nominal_priority;
  173. }
  174. /**
  175. * Sets the thread's current priority
  176. * @param priority The new priority
  177. */
  178. void SetPriority(u32 priority);
  179. /// Adds a thread to the list of threads that are waiting for a lock held by this thread.
  180. void AddMutexWaiter(std::shared_ptr<Thread> thread);
  181. /// Removes a thread from the list of threads that are waiting for a lock held by this thread.
  182. void RemoveMutexWaiter(std::shared_ptr<Thread> thread);
  183. /// Recalculates the current priority taking into account priority inheritance.
  184. void UpdatePriority();
  185. /// Changes the core that the thread is running or scheduled to run on.
  186. ResultCode SetCoreAndAffinityMask(s32 new_core, u64 new_affinity_mask);
  187. /**
  188. * Gets the thread's thread ID
  189. * @return The thread's ID
  190. */
  191. u64 GetThreadID() const {
  192. return thread_id;
  193. }
  194. /// Resumes a thread from waiting
  195. void /* deprecated */ ResumeFromWait();
  196. void OnWakeUp();
  197. ResultCode Start();
  198. /// Cancels a waiting operation that this thread may or may not be within.
  199. ///
  200. /// When the thread is within a waiting state, this will set the thread's
  201. /// waiting result to signal a canceled wait. The function will then resume
  202. /// this thread.
  203. ///
  204. void CancelWait();
  205. /**
  206. * Schedules an event to wake up the specified thread after the specified delay
  207. * @param nanoseconds The time this thread will be allowed to sleep for
  208. */
  209. void /* deprecated */ WakeAfterDelay(s64 nanoseconds);
  210. /// Cancel any outstanding wakeup events for this thread
  211. void /* deprecated */ CancelWakeupTimer();
  212. /**
  213. * Sets the result after the thread awakens (from svcWaitSynchronization)
  214. * @param result Value to set to the returned result
  215. */
  216. void /*deprecated*/ SetWaitSynchronizationResult(ResultCode result);
  217. /**
  218. * Sets the output parameter value after the thread awakens (from svcWaitSynchronization)
  219. * @param output Value to set to the output parameter
  220. */
  221. void /*deprecated*/ SetWaitSynchronizationOutput(s32 output);
  222. void SetSynchronizationResults(SynchronizationObject* object, ResultCode result);
  223. SynchronizationObject* GetSignalingObject() const {
  224. return signaling_object;
  225. }
  226. ResultCode GetSignalingResult() const {
  227. return signaling_result;
  228. }
  229. /**
  230. * Retrieves the index that this particular object occupies in the list of objects
  231. * that the thread passed to WaitSynchronization, starting the search from the last element.
  232. *
  233. * It is used to set the output index of WaitSynchronization when the thread is awakened.
  234. *
  235. * When a thread wakes up due to an object signal, the kernel will use the index of the last
  236. * matching object in the wait objects list in case of having multiple instances of the same
  237. * object in the list.
  238. *
  239. * @param object Object to query the index of.
  240. */
  241. s32 GetSynchronizationObjectIndex(std::shared_ptr<SynchronizationObject> object) const;
  242. /**
  243. * Stops a thread, invalidating it from further use
  244. */
  245. void Stop();
  246. /*
  247. * Returns the Thread Local Storage address of the current thread
  248. * @returns VAddr of the thread's TLS
  249. */
  250. VAddr GetTLSAddress() const {
  251. return tls_address;
  252. }
  253. /*
  254. * Returns the value of the TPIDR_EL0 Read/Write system register for this thread.
  255. * @returns The value of the TPIDR_EL0 register.
  256. */
  257. u64 GetTPIDR_EL0() const {
  258. return tpidr_el0;
  259. }
  260. /// Sets the value of the TPIDR_EL0 Read/Write system register for this thread.
  261. void SetTPIDR_EL0(u64 value) {
  262. tpidr_el0 = value;
  263. }
  264. /*
  265. * Returns the address of the current thread's command buffer, located in the TLS.
  266. * @returns VAddr of the thread's command buffer.
  267. */
  268. VAddr GetCommandBufferAddress() const;
  269. /// Returns whether this thread is waiting on objects from a WaitSynchronization call.
  270. bool IsSleepingOnWait() const {
  271. return status == ThreadStatus::WaitSynch;
  272. }
  273. ThreadContext32& GetContext32() {
  274. return context_32;
  275. }
  276. const ThreadContext32& GetContext32() const {
  277. return context_32;
  278. }
  279. ThreadContext64& GetContext64() {
  280. return context_64;
  281. }
  282. const ThreadContext64& GetContext64() const {
  283. return context_64;
  284. }
  285. bool IsHLEThread() const {
  286. return (type & THREADTYPE_HLE) != 0;
  287. }
  288. std::shared_ptr<Common::Fiber> GetHostContext() const;
  289. ThreadStatus GetStatus() const {
  290. return status;
  291. }
  292. void SetStatus(ThreadStatus new_status);
  293. u64 GetLastRunningTicks() const {
  294. return last_running_ticks;
  295. }
  296. u64 GetTotalCPUTimeTicks() const {
  297. return total_cpu_time_ticks;
  298. }
  299. void UpdateCPUTimeTicks(u64 ticks) {
  300. total_cpu_time_ticks += ticks;
  301. }
  302. s32 GetProcessorID() const {
  303. return processor_id;
  304. }
  305. void SetProcessorID(s32 new_core) {
  306. processor_id = new_core;
  307. }
  308. Process* GetOwnerProcess() {
  309. return owner_process;
  310. }
  311. const Process* GetOwnerProcess() const {
  312. return owner_process;
  313. }
  314. const ThreadSynchronizationObjects& GetSynchronizationObjects() const {
  315. return *wait_objects;
  316. }
  317. void SetSynchronizationObjects(ThreadSynchronizationObjects* objects) {
  318. wait_objects = objects;
  319. }
  320. void ClearSynchronizationObjects() {
  321. for (const auto& waiting_object : *wait_objects) {
  322. waiting_object->RemoveWaitingThread(SharedFrom(this));
  323. }
  324. wait_objects->clear();
  325. }
  326. /// Determines whether all the objects this thread is waiting on are ready.
  327. bool AllSynchronizationObjectsReady() const;
  328. const MutexWaitingThreads& GetMutexWaitingThreads() const {
  329. return wait_mutex_threads;
  330. }
  331. Thread* GetLockOwner() const {
  332. return lock_owner.get();
  333. }
  334. void SetLockOwner(std::shared_ptr<Thread> owner) {
  335. lock_owner = std::move(owner);
  336. }
  337. VAddr GetCondVarWaitAddress() const {
  338. return condvar_wait_address;
  339. }
  340. void SetCondVarWaitAddress(VAddr address) {
  341. condvar_wait_address = address;
  342. }
  343. VAddr GetMutexWaitAddress() const {
  344. return mutex_wait_address;
  345. }
  346. void SetMutexWaitAddress(VAddr address) {
  347. mutex_wait_address = address;
  348. }
  349. Handle GetWaitHandle() const {
  350. return wait_handle;
  351. }
  352. void SetWaitHandle(Handle handle) {
  353. wait_handle = handle;
  354. }
  355. VAddr GetArbiterWaitAddress() const {
  356. return arb_wait_address;
  357. }
  358. void SetArbiterWaitAddress(VAddr address) {
  359. arb_wait_address = address;
  360. }
  361. bool HasWakeupCallback() const {
  362. return wakeup_callback != nullptr;
  363. }
  364. bool HasHLECallback() const {
  365. return hle_callback != nullptr;
  366. }
  367. void SetWakeupCallback(WakeupCallback callback) {
  368. wakeup_callback = std::move(callback);
  369. }
  370. void SetHLECallback(HLECallback callback) {
  371. hle_callback = std::move(callback);
  372. }
  373. void SetHLETimeEvent(Handle time_event) {
  374. hle_time_event = time_event;
  375. }
  376. Handle GetHLETimeEvent() const {
  377. return hle_time_event;
  378. }
  379. void InvalidateWakeupCallback() {
  380. SetWakeupCallback(nullptr);
  381. }
  382. void InvalidateHLECallback() {
  383. SetHLECallback(nullptr);
  384. }
  385. /**
  386. * Invokes the thread's wakeup callback.
  387. *
  388. * @pre A valid wakeup callback has been set. Violating this precondition
  389. * will cause an assertion to trigger.
  390. */
  391. bool InvokeWakeupCallback(ThreadWakeupReason reason, std::shared_ptr<Thread> thread,
  392. std::shared_ptr<SynchronizationObject> object, std::size_t index);
  393. bool InvokeHLECallback(std::shared_ptr<Thread> thread);
  394. u32 GetIdealCore() const {
  395. return ideal_core;
  396. }
  397. u64 GetAffinityMask() const {
  398. return affinity_mask;
  399. }
  400. ResultCode SetActivity(ThreadActivity value);
  401. /// Sleeps this thread for the given amount of nanoseconds.
  402. ResultCode Sleep(s64 nanoseconds);
  403. /// Yields this thread without rebalancing loads.
  404. ResultCode YieldSimple();
  405. /// Yields this thread and does a load rebalancing.
  406. ResultCode YieldAndBalanceLoad();
  407. /// Yields this thread and if the core is left idle, loads are rebalanced
  408. ResultCode YieldAndWaitForLoadBalancing();
  409. void IncrementYieldCount() {
  410. yield_count++;
  411. }
  412. u64 GetYieldCount() const {
  413. return yield_count;
  414. }
  415. ThreadSchedStatus GetSchedulingStatus() const {
  416. return static_cast<ThreadSchedStatus>(scheduling_state &
  417. static_cast<u32>(ThreadSchedMasks::LowMask));
  418. }
  419. bool IsRunnable() const {
  420. return scheduling_state == static_cast<u32>(ThreadSchedStatus::Runnable);
  421. }
  422. bool IsRunning() const {
  423. return is_running;
  424. }
  425. void SetIsRunning(bool value) {
  426. is_running = value;
  427. }
  428. bool IsSyncCancelled() const {
  429. return is_sync_cancelled;
  430. }
  431. void SetSyncCancelled(bool value) {
  432. is_sync_cancelled = value;
  433. }
  434. Handle GetGlobalHandle() const {
  435. return global_handle;
  436. }
  437. bool IsWaitingForArbitration() const {
  438. return waiting_for_arbitration;
  439. }
  440. void WaitForArbitration(bool set) {
  441. waiting_for_arbitration = set;
  442. }
  443. bool IsWaitingSync() const {
  444. return is_waiting_on_sync;
  445. }
  446. void SetWaitingSync(bool is_waiting) {
  447. is_waiting_on_sync = is_waiting;
  448. }
  449. bool IsPendingTermination() const {
  450. return will_be_terminated || GetSchedulingStatus() == ThreadSchedStatus::Exited;
  451. }
  452. bool IsPaused() const {
  453. return pausing_state != 0;
  454. }
  455. private:
  456. friend class GlobalScheduler;
  457. friend class Scheduler;
  458. void SetSchedulingStatus(ThreadSchedStatus new_status);
  459. void AddSchedulingFlag(ThreadSchedFlags flag);
  460. void RemoveSchedulingFlag(ThreadSchedFlags flag);
  461. void SetCurrentPriority(u32 new_priority);
  462. void AdjustSchedulingOnAffinity(u64 old_affinity_mask, s32 old_core);
  463. ThreadContext32 context_32{};
  464. ThreadContext64 context_64{};
  465. Common::SpinLock context_guard{};
  466. std::shared_ptr<Common::Fiber> host_context{};
  467. u64 thread_id = 0;
  468. ThreadStatus status = ThreadStatus::Dormant;
  469. VAddr entry_point = 0;
  470. VAddr stack_top = 0;
  471. ThreadType type;
  472. /// Nominal thread priority, as set by the emulated application.
  473. /// The nominal priority is the thread priority without priority
  474. /// inheritance taken into account.
  475. u32 nominal_priority = 0;
  476. /// Current thread priority. This may change over the course of the
  477. /// thread's lifetime in order to facilitate priority inheritance.
  478. u32 current_priority = 0;
  479. u64 total_cpu_time_ticks = 0; ///< Total CPU running ticks.
  480. u64 last_running_ticks = 0; ///< CPU tick when thread was last running
  481. u64 yield_count = 0; ///< Number of redundant yields carried by this thread.
  482. ///< a redundant yield is one where no scheduling is changed
  483. s32 processor_id = 0;
  484. VAddr tls_address = 0; ///< Virtual address of the Thread Local Storage of the thread
  485. u64 tpidr_el0 = 0; ///< TPIDR_EL0 read/write system register.
  486. /// Process that owns this thread
  487. Process* owner_process;
  488. /// Objects that the thread is waiting on, in the same order as they were
  489. /// passed to WaitSynchronization.
  490. ThreadSynchronizationObjects* wait_objects;
  491. SynchronizationObject* signaling_object;
  492. ResultCode signaling_result{RESULT_SUCCESS};
  493. /// List of threads that are waiting for a mutex that is held by this thread.
  494. MutexWaitingThreads wait_mutex_threads;
  495. /// Thread that owns the lock that this thread is waiting for.
  496. std::shared_ptr<Thread> lock_owner;
  497. /// If waiting on a ConditionVariable, this is the ConditionVariable address
  498. VAddr condvar_wait_address = 0;
  499. /// If waiting on a Mutex, this is the mutex address
  500. VAddr mutex_wait_address = 0;
  501. /// The handle used to wait for the mutex.
  502. Handle wait_handle = 0;
  503. /// If waiting for an AddressArbiter, this is the address being waited on.
  504. VAddr arb_wait_address{0};
  505. bool waiting_for_arbitration{};
  506. /// Handle used as userdata to reference this object when inserting into the CoreTiming queue.
  507. Handle global_handle = 0;
  508. /// Callback that will be invoked when the thread is resumed from a waiting state. If the thread
  509. /// was waiting via WaitSynchronization then the object will be the last object that became
  510. /// available. In case of a timeout, the object will be nullptr. DEPRECATED
  511. WakeupCallback wakeup_callback;
  512. /// Callback for HLE Events
  513. HLECallback hle_callback;
  514. Handle hle_time_event;
  515. Scheduler* scheduler = nullptr;
  516. u32 ideal_core{0xFFFFFFFF};
  517. u64 affinity_mask{0x1};
  518. s32 ideal_core_override = -1;
  519. u64 affinity_mask_override = 0x1;
  520. u32 affinity_override_count = 0;
  521. u32 scheduling_state = 0;
  522. u32 pausing_state = 0;
  523. bool is_running = false;
  524. bool is_waiting_on_sync = false;
  525. bool is_sync_cancelled = false;
  526. bool will_be_terminated = false;
  527. std::string name;
  528. };
  529. /**
  530. * Gets the current thread
  531. */
  532. Thread* GetCurrentThread();
  533. } // namespace Kernel