k_process.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  1. // SPDX-FileCopyrightText: 2015 Citra Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #pragma once
  4. #include <array>
  5. #include <cstddef>
  6. #include <list>
  7. #include <map>
  8. #include <string>
  9. #include "core/hle/kernel/k_address_arbiter.h"
  10. #include "core/hle/kernel/k_auto_object.h"
  11. #include "core/hle/kernel/k_condition_variable.h"
  12. #include "core/hle/kernel/k_handle_table.h"
  13. #include "core/hle/kernel/k_page_table.h"
  14. #include "core/hle/kernel/k_synchronization_object.h"
  15. #include "core/hle/kernel/k_thread_local_page.h"
  16. #include "core/hle/kernel/k_typed_address.h"
  17. #include "core/hle/kernel/k_worker_task.h"
  18. #include "core/hle/kernel/process_capability.h"
  19. #include "core/hle/kernel/slab_helpers.h"
  20. #include "core/hle/result.h"
  21. namespace Core {
  22. class System;
  23. }
  24. namespace FileSys {
  25. class ProgramMetadata;
  26. }
  27. namespace Kernel {
  28. class KernelCore;
  29. class KResourceLimit;
  30. class KThread;
  31. class KSharedMemoryInfo;
  32. class TLSPage;
  33. struct CodeSet;
  34. enum class MemoryRegion : u16 {
  35. APPLICATION = 1,
  36. SYSTEM = 2,
  37. BASE = 3,
  38. };
  39. enum class ProcessActivity : u32 {
  40. Runnable,
  41. Paused,
  42. };
  43. enum class DebugWatchpointType : u8 {
  44. None = 0,
  45. Read = 1 << 0,
  46. Write = 1 << 1,
  47. ReadOrWrite = Read | Write,
  48. };
  49. DECLARE_ENUM_FLAG_OPERATORS(DebugWatchpointType);
  50. struct DebugWatchpoint {
  51. KProcessAddress start_address;
  52. KProcessAddress end_address;
  53. DebugWatchpointType type;
  54. };
  55. class KProcess final : public KAutoObjectWithSlabHeapAndContainer<KProcess, KWorkerTask> {
  56. KERNEL_AUTOOBJECT_TRAITS(KProcess, KSynchronizationObject);
  57. public:
  58. explicit KProcess(KernelCore& kernel);
  59. ~KProcess() override;
  60. enum class State {
  61. Created = static_cast<u32>(Svc::ProcessState::Created),
  62. CreatedAttached = static_cast<u32>(Svc::ProcessState::CreatedAttached),
  63. Running = static_cast<u32>(Svc::ProcessState::Running),
  64. Crashed = static_cast<u32>(Svc::ProcessState::Crashed),
  65. RunningAttached = static_cast<u32>(Svc::ProcessState::RunningAttached),
  66. Terminating = static_cast<u32>(Svc::ProcessState::Terminating),
  67. Terminated = static_cast<u32>(Svc::ProcessState::Terminated),
  68. DebugBreak = static_cast<u32>(Svc::ProcessState::DebugBreak),
  69. };
  70. enum : u64 {
  71. /// Lowest allowed process ID for a kernel initial process.
  72. InitialKIPIDMin = 1,
  73. /// Highest allowed process ID for a kernel initial process.
  74. InitialKIPIDMax = 80,
  75. /// Lowest allowed process ID for a userland process.
  76. ProcessIDMin = 81,
  77. /// Highest allowed process ID for a userland process.
  78. ProcessIDMax = 0xFFFFFFFFFFFFFFFF,
  79. };
  80. // Used to determine how process IDs are assigned.
  81. enum class ProcessType {
  82. KernelInternal,
  83. Userland,
  84. };
  85. static constexpr std::size_t RANDOM_ENTROPY_SIZE = 4;
  86. static Result Initialize(KProcess* process, Core::System& system, std::string process_name,
  87. ProcessType type, KResourceLimit* res_limit);
  88. /// Gets a reference to the process' page table.
  89. KPageTable& PageTable() {
  90. return m_page_table;
  91. }
  92. /// Gets const a reference to the process' page table.
  93. const KPageTable& PageTable() const {
  94. return m_page_table;
  95. }
  96. /// Gets a reference to the process' page table.
  97. KPageTable& GetPageTable() {
  98. return m_page_table;
  99. }
  100. /// Gets const a reference to the process' page table.
  101. const KPageTable& GetPageTable() const {
  102. return m_page_table;
  103. }
  104. /// Gets a reference to the process' handle table.
  105. KHandleTable& GetHandleTable() {
  106. return m_handle_table;
  107. }
  108. /// Gets a const reference to the process' handle table.
  109. const KHandleTable& GetHandleTable() const {
  110. return m_handle_table;
  111. }
  112. Result SignalToAddress(KProcessAddress address) {
  113. return m_condition_var.SignalToAddress(address);
  114. }
  115. Result WaitForAddress(Handle handle, KProcessAddress address, u32 tag) {
  116. return m_condition_var.WaitForAddress(handle, address, tag);
  117. }
  118. void SignalConditionVariable(u64 cv_key, int32_t count) {
  119. return m_condition_var.Signal(cv_key, count);
  120. }
  121. Result WaitConditionVariable(KProcessAddress address, u64 cv_key, u32 tag, s64 ns) {
  122. R_RETURN(m_condition_var.Wait(address, cv_key, tag, ns));
  123. }
  124. Result SignalAddressArbiter(uint64_t address, Svc::SignalType signal_type, s32 value,
  125. s32 count) {
  126. R_RETURN(m_address_arbiter.SignalToAddress(address, signal_type, value, count));
  127. }
  128. Result WaitAddressArbiter(uint64_t address, Svc::ArbitrationType arb_type, s32 value,
  129. s64 timeout) {
  130. R_RETURN(m_address_arbiter.WaitForAddress(address, arb_type, value, timeout));
  131. }
  132. KProcessAddress GetProcessLocalRegionAddress() const {
  133. return m_plr_address;
  134. }
  135. /// Gets the current status of the process
  136. State GetState() const {
  137. return m_state;
  138. }
  139. /// Gets the unique ID that identifies this particular process.
  140. u64 GetProcessId() const {
  141. return m_process_id;
  142. }
  143. /// Gets the program ID corresponding to this process.
  144. u64 GetProgramId() const {
  145. return m_program_id;
  146. }
  147. /// Gets the resource limit descriptor for this process
  148. KResourceLimit* GetResourceLimit() const;
  149. /// Gets the ideal CPU core ID for this process
  150. u8 GetIdealCoreId() const {
  151. return m_ideal_core;
  152. }
  153. /// Checks if the specified thread priority is valid.
  154. bool CheckThreadPriority(s32 prio) const {
  155. return ((1ULL << prio) & GetPriorityMask()) != 0;
  156. }
  157. /// Gets the bitmask of allowed cores that this process' threads can run on.
  158. u64 GetCoreMask() const {
  159. return m_capabilities.GetCoreMask();
  160. }
  161. /// Gets the bitmask of allowed thread priorities.
  162. u64 GetPriorityMask() const {
  163. return m_capabilities.GetPriorityMask();
  164. }
  165. /// Gets the amount of secure memory to allocate for memory management.
  166. u32 GetSystemResourceSize() const {
  167. return m_system_resource_size;
  168. }
  169. /// Gets the amount of secure memory currently in use for memory management.
  170. u32 GetSystemResourceUsage() const {
  171. // On hardware, this returns the amount of system resource memory that has
  172. // been used by the kernel. This is problematic for Yuzu to emulate, because
  173. // system resource memory is used for page tables -- and yuzu doesn't really
  174. // have a way to calculate how much memory is required for page tables for
  175. // the current process at any given time.
  176. // TODO: Is this even worth implementing? Games may retrieve this value via
  177. // an SDK function that gets used + available system resource size for debug
  178. // or diagnostic purposes. However, it seems unlikely that a game would make
  179. // decisions based on how much system memory is dedicated to its page tables.
  180. // Is returning a value other than zero wise?
  181. return 0;
  182. }
  183. /// Whether this process is an AArch64 or AArch32 process.
  184. bool Is64BitProcess() const {
  185. return m_is_64bit_process;
  186. }
  187. bool IsSuspended() const {
  188. return m_is_suspended;
  189. }
  190. void SetSuspended(bool suspended) {
  191. m_is_suspended = suspended;
  192. }
  193. /// Gets the total running time of the process instance in ticks.
  194. u64 GetCPUTimeTicks() const {
  195. return m_total_process_running_time_ticks;
  196. }
  197. /// Updates the total running time, adding the given ticks to it.
  198. void UpdateCPUTimeTicks(u64 ticks) {
  199. m_total_process_running_time_ticks += ticks;
  200. }
  201. /// Gets the process schedule count, used for thread yielding
  202. s64 GetScheduledCount() const {
  203. return m_schedule_count;
  204. }
  205. /// Increments the process schedule count, used for thread yielding.
  206. void IncrementScheduledCount() {
  207. ++m_schedule_count;
  208. }
  209. void IncrementRunningThreadCount();
  210. void DecrementRunningThreadCount();
  211. void SetRunningThread(s32 core, KThread* thread, u64 idle_count) {
  212. m_running_threads[core] = thread;
  213. m_running_thread_idle_counts[core] = idle_count;
  214. }
  215. void ClearRunningThread(KThread* thread) {
  216. for (size_t i = 0; i < m_running_threads.size(); ++i) {
  217. if (m_running_threads[i] == thread) {
  218. m_running_threads[i] = nullptr;
  219. }
  220. }
  221. }
  222. [[nodiscard]] KThread* GetRunningThread(s32 core) const {
  223. return m_running_threads[core];
  224. }
  225. bool ReleaseUserException(KThread* thread);
  226. [[nodiscard]] KThread* GetPinnedThread(s32 core_id) const {
  227. ASSERT(0 <= core_id && core_id < static_cast<s32>(Core::Hardware::NUM_CPU_CORES));
  228. return m_pinned_threads[core_id];
  229. }
  230. /// Gets 8 bytes of random data for svcGetInfo RandomEntropy
  231. u64 GetRandomEntropy(std::size_t index) const {
  232. return m_random_entropy.at(index);
  233. }
  234. /// Retrieves the total physical memory available to this process in bytes.
  235. u64 GetTotalPhysicalMemoryAvailable();
  236. /// Retrieves the total physical memory available to this process in bytes,
  237. /// without the size of the personal system resource heap added to it.
  238. u64 GetTotalPhysicalMemoryAvailableWithoutSystemResource();
  239. /// Retrieves the total physical memory used by this process in bytes.
  240. u64 GetTotalPhysicalMemoryUsed();
  241. /// Retrieves the total physical memory used by this process in bytes,
  242. /// without the size of the personal system resource heap added to it.
  243. u64 GetTotalPhysicalMemoryUsedWithoutSystemResource();
  244. /// Gets the list of all threads created with this process as their owner.
  245. std::list<KThread*>& GetThreadList() {
  246. return m_thread_list;
  247. }
  248. /// Registers a thread as being created under this process,
  249. /// adding it to this process' thread list.
  250. void RegisterThread(KThread* thread);
  251. /// Unregisters a thread from this process, removing it
  252. /// from this process' thread list.
  253. void UnregisterThread(KThread* thread);
  254. /// Retrieves the number of available threads for this process.
  255. u64 GetFreeThreadCount() const;
  256. /// Clears the signaled state of the process if and only if it's signaled.
  257. ///
  258. /// @pre The process must not be already terminated. If this is called on a
  259. /// terminated process, then ResultInvalidState will be returned.
  260. ///
  261. /// @pre The process must be in a signaled state. If this is called on a
  262. /// process instance that is not signaled, ResultInvalidState will be
  263. /// returned.
  264. Result Reset();
  265. /**
  266. * Loads process-specifics configuration info with metadata provided
  267. * by an executable.
  268. *
  269. * @param metadata The provided metadata to load process specific info from.
  270. *
  271. * @returns ResultSuccess if all relevant metadata was able to be
  272. * loaded and parsed. Otherwise, an error code is returned.
  273. */
  274. Result LoadFromMetadata(const FileSys::ProgramMetadata& metadata, std::size_t code_size);
  275. /**
  276. * Starts the main application thread for this process.
  277. *
  278. * @param main_thread_priority The priority for the main thread.
  279. * @param stack_size The stack size for the main thread in bytes.
  280. */
  281. void Run(s32 main_thread_priority, u64 stack_size);
  282. /**
  283. * Prepares a process for termination by stopping all of its threads
  284. * and clearing any other resources.
  285. */
  286. void PrepareForTermination();
  287. void LoadModule(CodeSet code_set, KProcessAddress base_addr);
  288. bool IsInitialized() const override {
  289. return m_is_initialized;
  290. }
  291. static void PostDestroy(uintptr_t arg) {}
  292. void Finalize() override;
  293. u64 GetId() const override {
  294. return GetProcessId();
  295. }
  296. bool IsSignaled() const override;
  297. void DoWorkerTaskImpl();
  298. Result SetActivity(ProcessActivity activity);
  299. void PinCurrentThread(s32 core_id);
  300. void UnpinCurrentThread(s32 core_id);
  301. void UnpinThread(KThread* thread);
  302. KLightLock& GetStateLock() {
  303. return m_state_lock;
  304. }
  305. Result AddSharedMemory(KSharedMemory* shmem, KProcessAddress address, size_t size);
  306. void RemoveSharedMemory(KSharedMemory* shmem, KProcessAddress address, size_t size);
  307. ///////////////////////////////////////////////////////////////////////////////////////////////
  308. // Thread-local storage management
  309. // Marks the next available region as used and returns the address of the slot.
  310. [[nodiscard]] Result CreateThreadLocalRegion(KProcessAddress* out);
  311. // Frees a used TLS slot identified by the given address
  312. Result DeleteThreadLocalRegion(KProcessAddress addr);
  313. ///////////////////////////////////////////////////////////////////////////////////////////////
  314. // Debug watchpoint management
  315. // Attempts to insert a watchpoint into a free slot. Returns false if none are available.
  316. bool InsertWatchpoint(Core::System& system, KProcessAddress addr, u64 size,
  317. DebugWatchpointType type);
  318. // Attempts to remove the watchpoint specified by the given parameters.
  319. bool RemoveWatchpoint(Core::System& system, KProcessAddress addr, u64 size,
  320. DebugWatchpointType type);
  321. const std::array<DebugWatchpoint, Core::Hardware::NUM_WATCHPOINTS>& GetWatchpoints() const {
  322. return m_watchpoints;
  323. }
  324. const std::string& GetName() {
  325. return name;
  326. }
  327. private:
  328. void PinThread(s32 core_id, KThread* thread) {
  329. ASSERT(0 <= core_id && core_id < static_cast<s32>(Core::Hardware::NUM_CPU_CORES));
  330. ASSERT(thread != nullptr);
  331. ASSERT(m_pinned_threads[core_id] == nullptr);
  332. m_pinned_threads[core_id] = thread;
  333. }
  334. void UnpinThread(s32 core_id, KThread* thread) {
  335. ASSERT(0 <= core_id && core_id < static_cast<s32>(Core::Hardware::NUM_CPU_CORES));
  336. ASSERT(thread != nullptr);
  337. ASSERT(m_pinned_threads[core_id] == thread);
  338. m_pinned_threads[core_id] = nullptr;
  339. }
  340. void FinalizeHandleTable() {
  341. // Finalize the table.
  342. m_handle_table.Finalize();
  343. // Note that the table is finalized.
  344. m_is_handle_table_initialized = false;
  345. }
  346. void ChangeState(State new_state);
  347. /// Allocates the main thread stack for the process, given the stack size in bytes.
  348. Result AllocateMainThreadStack(std::size_t stack_size);
  349. /// Memory manager for this process
  350. KPageTable m_page_table;
  351. /// Current status of the process
  352. State m_state{};
  353. /// The ID of this process
  354. u64 m_process_id = 0;
  355. /// Title ID corresponding to the process
  356. u64 m_program_id = 0;
  357. /// Specifies additional memory to be reserved for the process's memory management by the
  358. /// system. When this is non-zero, secure memory is allocated and used for page table allocation
  359. /// instead of using the normal global page tables/memory block management.
  360. u32 m_system_resource_size = 0;
  361. /// Resource limit descriptor for this process
  362. KResourceLimit* m_resource_limit{};
  363. KVirtualAddress m_system_resource_address{};
  364. /// The ideal CPU core for this process, threads are scheduled on this core by default.
  365. u8 m_ideal_core = 0;
  366. /// Contains the parsed process capability descriptors.
  367. ProcessCapabilities m_capabilities;
  368. /// Whether or not this process is AArch64, or AArch32.
  369. /// By default, we currently assume this is true, unless otherwise
  370. /// specified by metadata provided to the process during loading.
  371. bool m_is_64bit_process = true;
  372. /// Total running time for the process in ticks.
  373. std::atomic<u64> m_total_process_running_time_ticks = 0;
  374. /// Per-process handle table for storing created object handles in.
  375. KHandleTable m_handle_table;
  376. /// Per-process address arbiter.
  377. KAddressArbiter m_address_arbiter;
  378. /// The per-process mutex lock instance used for handling various
  379. /// forms of services, such as lock arbitration, and condition
  380. /// variable related facilities.
  381. KConditionVariable m_condition_var;
  382. /// Address indicating the location of the process' dedicated TLS region.
  383. KProcessAddress m_plr_address = 0;
  384. /// Random values for svcGetInfo RandomEntropy
  385. std::array<u64, RANDOM_ENTROPY_SIZE> m_random_entropy{};
  386. /// List of threads that are running with this process as their owner.
  387. std::list<KThread*> m_thread_list;
  388. /// List of shared memory that are running with this process as their owner.
  389. std::list<KSharedMemoryInfo*> m_shared_memory_list;
  390. /// Address of the top of the main thread's stack
  391. KProcessAddress m_main_thread_stack_top{};
  392. /// Size of the main thread's stack
  393. std::size_t m_main_thread_stack_size{};
  394. /// Memory usage capacity for the process
  395. std::size_t m_memory_usage_capacity{};
  396. /// Process total image size
  397. std::size_t m_image_size{};
  398. /// Schedule count of this process
  399. s64 m_schedule_count{};
  400. size_t m_memory_release_hint{};
  401. std::string name{};
  402. bool m_is_signaled{};
  403. bool m_is_suspended{};
  404. bool m_is_immortal{};
  405. bool m_is_handle_table_initialized{};
  406. bool m_is_initialized{};
  407. std::atomic<u16> m_num_running_threads{};
  408. std::array<KThread*, Core::Hardware::NUM_CPU_CORES> m_running_threads{};
  409. std::array<u64, Core::Hardware::NUM_CPU_CORES> m_running_thread_idle_counts{};
  410. std::array<KThread*, Core::Hardware::NUM_CPU_CORES> m_pinned_threads{};
  411. std::array<DebugWatchpoint, Core::Hardware::NUM_WATCHPOINTS> m_watchpoints{};
  412. std::map<KProcessAddress, u64> m_debug_page_refcounts;
  413. KThread* m_exception_thread{};
  414. KLightLock m_state_lock;
  415. KLightLock m_list_lock;
  416. using TLPTree =
  417. Common::IntrusiveRedBlackTreeBaseTraits<KThreadLocalPage>::TreeType<KThreadLocalPage>;
  418. using TLPIterator = TLPTree::iterator;
  419. TLPTree m_fully_used_tlp_tree;
  420. TLPTree m_partially_used_tlp_tree;
  421. };
  422. } // namespace Kernel