thread.h 19 KB

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