kernel.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. // Copyright 2021 yuzu Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #pragma once
  5. #include <array>
  6. #include <functional>
  7. #include <memory>
  8. #include <string>
  9. #include <unordered_map>
  10. #include <vector>
  11. #include "core/arm/cpu_interrupt_handler.h"
  12. #include "core/hardware_properties.h"
  13. #include "core/hle/kernel/k_auto_object.h"
  14. #include "core/hle/kernel/k_slab_heap.h"
  15. #include "core/hle/kernel/memory_types.h"
  16. #include "core/hle/kernel/svc_common.h"
  17. namespace Core {
  18. class CPUInterruptHandler;
  19. class ExclusiveMonitor;
  20. class System;
  21. } // namespace Core
  22. namespace Core::Timing {
  23. class CoreTiming;
  24. struct EventType;
  25. } // namespace Core::Timing
  26. namespace Service::SM {
  27. class ServiceManager;
  28. }
  29. namespace Kernel {
  30. class KClientPort;
  31. class GlobalSchedulerContext;
  32. class KAutoObjectWithListContainer;
  33. class KClientSession;
  34. class KEvent;
  35. class KHandleTable;
  36. class KLinkedListNode;
  37. class KMemoryManager;
  38. class KPort;
  39. class KProcess;
  40. class KResourceLimit;
  41. class KScheduler;
  42. class KServerSession;
  43. class KSession;
  44. class KSharedMemory;
  45. class KSharedMemoryInfo;
  46. class KThread;
  47. class KTransferMemory;
  48. class KWorkerTaskManager;
  49. class KWritableEvent;
  50. class KCodeMemory;
  51. class PhysicalCore;
  52. class ServiceThread;
  53. class Synchronization;
  54. class TimeManager;
  55. using ServiceInterfaceFactory =
  56. std::function<KClientPort&(Service::SM::ServiceManager&, Core::System&)>;
  57. namespace Init {
  58. struct KSlabResourceCounts;
  59. }
  60. template <typename T>
  61. class KSlabHeap;
  62. using EmuThreadHandle = uintptr_t;
  63. constexpr EmuThreadHandle EmuThreadHandleInvalid{};
  64. constexpr EmuThreadHandle EmuThreadHandleReserved{1ULL << 63};
  65. /// Represents a single instance of the kernel.
  66. class KernelCore {
  67. private:
  68. using NamedPortTable = std::unordered_map<std::string, KClientPort*>;
  69. public:
  70. /// Constructs an instance of the kernel using the given System
  71. /// instance as a context for any necessary system-related state,
  72. /// such as threads, CPU core state, etc.
  73. ///
  74. /// @post After execution of the constructor, the provided System
  75. /// object *must* outlive the kernel instance itself.
  76. ///
  77. explicit KernelCore(Core::System& system);
  78. ~KernelCore();
  79. KernelCore(const KernelCore&) = delete;
  80. KernelCore& operator=(const KernelCore&) = delete;
  81. KernelCore(KernelCore&&) = delete;
  82. KernelCore& operator=(KernelCore&&) = delete;
  83. /// Sets if emulation is multicore or single core, must be set before Initialize
  84. void SetMulticore(bool is_multicore);
  85. /// Resets the kernel to a clean slate for use.
  86. void Initialize();
  87. /// Initializes the CPU cores.
  88. void InitializeCores();
  89. /// Clears all resources in use by the kernel instance.
  90. void Shutdown();
  91. /// Retrieves a shared pointer to the system resource limit instance.
  92. const KResourceLimit* GetSystemResourceLimit() const;
  93. /// Retrieves a shared pointer to the system resource limit instance.
  94. KResourceLimit* GetSystemResourceLimit();
  95. /// Retrieves a shared pointer to a Thread instance within the thread wakeup handle table.
  96. KScopedAutoObject<KThread> RetrieveThreadFromGlobalHandleTable(Handle handle) const;
  97. /// Adds the given shared pointer to an internal list of active processes.
  98. void AppendNewProcess(KProcess* process);
  99. /// Makes the given process the new current process.
  100. void MakeCurrentProcess(KProcess* process);
  101. /// Retrieves a pointer to the current process.
  102. KProcess* CurrentProcess();
  103. /// Retrieves a const pointer to the current process.
  104. const KProcess* CurrentProcess() const;
  105. /// Retrieves the list of processes.
  106. const std::vector<KProcess*>& GetProcessList() const;
  107. /// Gets the sole instance of the global scheduler
  108. Kernel::GlobalSchedulerContext& GlobalSchedulerContext();
  109. /// Gets the sole instance of the global scheduler
  110. const Kernel::GlobalSchedulerContext& GlobalSchedulerContext() const;
  111. /// Gets the sole instance of the Scheduler assoviated with cpu core 'id'
  112. Kernel::KScheduler& Scheduler(std::size_t id);
  113. /// Gets the sole instance of the Scheduler assoviated with cpu core 'id'
  114. const Kernel::KScheduler& Scheduler(std::size_t id) const;
  115. /// Gets the an instance of the respective physical CPU core.
  116. Kernel::PhysicalCore& PhysicalCore(std::size_t id);
  117. /// Gets the an instance of the respective physical CPU core.
  118. const Kernel::PhysicalCore& PhysicalCore(std::size_t id) const;
  119. /// Gets the current physical core index for the running host thread.
  120. std::size_t CurrentPhysicalCoreIndex() const;
  121. /// Gets the sole instance of the Scheduler at the current running core.
  122. Kernel::KScheduler* CurrentScheduler();
  123. /// Gets the an instance of the current physical CPU core.
  124. Kernel::PhysicalCore& CurrentPhysicalCore();
  125. /// Gets the an instance of the current physical CPU core.
  126. const Kernel::PhysicalCore& CurrentPhysicalCore() const;
  127. /// Gets the an instance of the TimeManager Interface.
  128. Kernel::TimeManager& TimeManager();
  129. /// Gets the an instance of the TimeManager Interface.
  130. const Kernel::TimeManager& TimeManager() const;
  131. /// Stops execution of 'id' core, in order to reschedule a new thread.
  132. void PrepareReschedule(std::size_t id);
  133. Core::ExclusiveMonitor& GetExclusiveMonitor();
  134. const Core::ExclusiveMonitor& GetExclusiveMonitor() const;
  135. KAutoObjectWithListContainer& ObjectListContainer();
  136. const KAutoObjectWithListContainer& ObjectListContainer() const;
  137. std::array<Core::CPUInterruptHandler, Core::Hardware::NUM_CPU_CORES>& Interrupts();
  138. const std::array<Core::CPUInterruptHandler, Core::Hardware::NUM_CPU_CORES>& Interrupts() const;
  139. void InvalidateAllInstructionCaches();
  140. void InvalidateCpuInstructionCacheRange(VAddr addr, std::size_t size);
  141. /// Registers a named HLE service, passing a factory used to open a port to that service.
  142. void RegisterNamedService(std::string name, ServiceInterfaceFactory&& factory);
  143. /// Opens a port to a service previously registered with RegisterNamedService.
  144. KClientPort* CreateNamedServicePort(std::string name);
  145. /// Registers a server session with the gobal emulation state, to be freed on shutdown. This is
  146. /// necessary because we do not emulate processes for HLE sessions.
  147. void RegisterServerSession(KServerSession* server_session);
  148. /// Unregisters a server session previously registered with RegisterServerSession when it was
  149. /// destroyed during the current emulation session.
  150. void UnregisterServerSession(KServerSession* server_session);
  151. /// Registers all kernel objects with the global emulation state, this is purely for tracking
  152. /// leaks after emulation has been shutdown.
  153. void RegisterKernelObject(KAutoObject* object);
  154. /// Unregisters a kernel object previously registered with RegisterKernelObject when it was
  155. /// destroyed during the current emulation session.
  156. void UnregisterKernelObject(KAutoObject* object);
  157. /// Registers kernel objects with guest in use state, this is purely for close
  158. /// after emulation has been shutdown.
  159. void RegisterInUseObject(KAutoObject* object);
  160. /// Unregisters a kernel object previously registered with RegisterInUseObject when it was
  161. /// destroyed during the current emulation session.
  162. void UnregisterInUseObject(KAutoObject* object);
  163. /// Determines whether or not the given port is a valid named port.
  164. bool IsValidNamedPort(NamedPortTable::const_iterator port) const;
  165. /// Gets the current host_thread/guest_thread pointer.
  166. KThread* GetCurrentEmuThread() const;
  167. /// Gets the current host_thread handle.
  168. u32 GetCurrentHostThreadID() const;
  169. /// Register the current thread as a CPU Core Thread.
  170. void RegisterCoreThread(std::size_t core_id);
  171. /// Register the current thread as a non CPU core thread.
  172. void RegisterHostThread();
  173. /// Gets the virtual memory manager for the kernel.
  174. KMemoryManager& MemoryManager();
  175. /// Gets the virtual memory manager for the kernel.
  176. const KMemoryManager& MemoryManager() const;
  177. /// Gets the slab heap allocated for user space pages.
  178. KSlabHeap<Page>& GetUserSlabHeapPages();
  179. /// Gets the slab heap allocated for user space pages.
  180. const KSlabHeap<Page>& GetUserSlabHeapPages() const;
  181. /// Gets the shared memory object for HID services.
  182. Kernel::KSharedMemory& GetHidSharedMem();
  183. /// Gets the shared memory object for HID services.
  184. const Kernel::KSharedMemory& GetHidSharedMem() const;
  185. /// Gets the shared memory object for font services.
  186. Kernel::KSharedMemory& GetFontSharedMem();
  187. /// Gets the shared memory object for font services.
  188. const Kernel::KSharedMemory& GetFontSharedMem() const;
  189. /// Gets the shared memory object for IRS services.
  190. Kernel::KSharedMemory& GetIrsSharedMem();
  191. /// Gets the shared memory object for IRS services.
  192. const Kernel::KSharedMemory& GetIrsSharedMem() const;
  193. /// Gets the shared memory object for Time services.
  194. Kernel::KSharedMemory& GetTimeSharedMem();
  195. /// Gets the shared memory object for Time services.
  196. const Kernel::KSharedMemory& GetTimeSharedMem() const;
  197. /// Suspend/unsuspend the OS.
  198. void Suspend(bool in_suspention);
  199. /// Exceptional exit the OS.
  200. void ExceptionalExit();
  201. bool IsMulticore() const;
  202. bool IsShuttingDown() const;
  203. void EnterSVCProfile();
  204. void ExitSVCProfile();
  205. /**
  206. * Creates an HLE service thread, which are used to execute service routines asynchronously.
  207. * While these are allocated per ServerSession, these need to be owned and managed outside
  208. * of ServerSession to avoid a circular dependency.
  209. * @param name String name for the ServerSession creating this thread, used for debug
  210. * purposes.
  211. * @returns The a weak pointer newly created service thread.
  212. */
  213. std::weak_ptr<Kernel::ServiceThread> CreateServiceThread(const std::string& name);
  214. /**
  215. * Releases a HLE service thread, instructing KernelCore to free it. This should be called when
  216. * the ServerSession associated with the thread is destroyed.
  217. * @param service_thread Service thread to release.
  218. */
  219. void ReleaseServiceThread(std::weak_ptr<Kernel::ServiceThread> service_thread);
  220. /// Workaround for single-core mode when preempting threads while idle.
  221. bool IsPhantomModeForSingleCore() const;
  222. void SetIsPhantomModeForSingleCore(bool value);
  223. Core::System& System();
  224. const Core::System& System() const;
  225. /// Gets the slab heap for the specified kernel object type.
  226. template <typename T>
  227. KSlabHeap<T>& SlabHeap() {
  228. if constexpr (std::is_same_v<T, KClientSession>) {
  229. return slab_heap_container->client_session;
  230. } else if constexpr (std::is_same_v<T, KEvent>) {
  231. return slab_heap_container->event;
  232. } else if constexpr (std::is_same_v<T, KLinkedListNode>) {
  233. return slab_heap_container->linked_list_node;
  234. } else if constexpr (std::is_same_v<T, KPort>) {
  235. return slab_heap_container->port;
  236. } else if constexpr (std::is_same_v<T, KProcess>) {
  237. return slab_heap_container->process;
  238. } else if constexpr (std::is_same_v<T, KResourceLimit>) {
  239. return slab_heap_container->resource_limit;
  240. } else if constexpr (std::is_same_v<T, KSession>) {
  241. return slab_heap_container->session;
  242. } else if constexpr (std::is_same_v<T, KSharedMemory>) {
  243. return slab_heap_container->shared_memory;
  244. } else if constexpr (std::is_same_v<T, KSharedMemoryInfo>) {
  245. return slab_heap_container->shared_memory_info;
  246. } else if constexpr (std::is_same_v<T, KThread>) {
  247. return slab_heap_container->thread;
  248. } else if constexpr (std::is_same_v<T, KTransferMemory>) {
  249. return slab_heap_container->transfer_memory;
  250. } else if constexpr (std::is_same_v<T, KWritableEvent>) {
  251. return slab_heap_container->writeable_event;
  252. } else if constexpr (std::is_same_v<T, KCodeMemory>) {
  253. return slab_heap_container->code_memory;
  254. }
  255. }
  256. /// Gets the current slab resource counts.
  257. Init::KSlabResourceCounts& SlabResourceCounts();
  258. /// Gets the current slab resource counts.
  259. const Init::KSlabResourceCounts& SlabResourceCounts() const;
  260. /// Gets the current worker task manager, used for dispatching KThread/KProcess tasks.
  261. KWorkerTaskManager& WorkerTaskManager();
  262. /// Gets the current worker task manager, used for dispatching KThread/KProcess tasks.
  263. const KWorkerTaskManager& WorkerTaskManager() const;
  264. private:
  265. friend class KProcess;
  266. friend class KThread;
  267. /// Creates a new object ID, incrementing the internal object ID counter.
  268. u32 CreateNewObjectID();
  269. /// Creates a new process ID, incrementing the internal process ID counter;
  270. u64 CreateNewKernelProcessID();
  271. /// Creates a new process ID, incrementing the internal process ID counter;
  272. u64 CreateNewUserProcessID();
  273. /// Creates a new thread ID, incrementing the internal thread ID counter.
  274. u64 CreateNewThreadID();
  275. /// Provides a reference to the global handle table.
  276. KHandleTable& GlobalHandleTable();
  277. /// Provides a const reference to the global handle table.
  278. const KHandleTable& GlobalHandleTable() const;
  279. struct Impl;
  280. std::unique_ptr<Impl> impl;
  281. bool exception_exited{};
  282. private:
  283. /// Helper to encapsulate all slab heaps in a single heap allocated container
  284. struct SlabHeapContainer {
  285. KSlabHeap<KClientSession> client_session;
  286. KSlabHeap<KEvent> event;
  287. KSlabHeap<KLinkedListNode> linked_list_node;
  288. KSlabHeap<KPort> port;
  289. KSlabHeap<KProcess> process;
  290. KSlabHeap<KResourceLimit> resource_limit;
  291. KSlabHeap<KSession> session;
  292. KSlabHeap<KSharedMemory> shared_memory;
  293. KSlabHeap<KSharedMemoryInfo> shared_memory_info;
  294. KSlabHeap<KThread> thread;
  295. KSlabHeap<KTransferMemory> transfer_memory;
  296. KSlabHeap<KWritableEvent> writeable_event;
  297. KSlabHeap<KCodeMemory> code_memory;
  298. };
  299. std::unique_ptr<SlabHeapContainer> slab_heap_container;
  300. };
  301. } // namespace Kernel