GpuContext.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. using Ryujinx.Graphics.GAL;
  2. using Ryujinx.Graphics.Gpu.Engine.GPFifo;
  3. using Ryujinx.Graphics.Gpu.Memory;
  4. using Ryujinx.Graphics.Gpu.Shader;
  5. using Ryujinx.Graphics.Gpu.Synchronization;
  6. using System;
  7. using System.Collections.Concurrent;
  8. using System.Collections.Generic;
  9. using System.Threading;
  10. namespace Ryujinx.Graphics.Gpu
  11. {
  12. /// <summary>
  13. /// GPU emulation context.
  14. /// </summary>
  15. public sealed class GpuContext : IDisposable
  16. {
  17. /// <summary>
  18. /// Event signaled when the host emulation context is ready to be used by the gpu context.
  19. /// </summary>
  20. public ManualResetEvent HostInitalized { get; }
  21. /// <summary>
  22. /// Host renderer.
  23. /// </summary>
  24. public IRenderer Renderer { get; }
  25. /// <summary>
  26. /// GPU General Purpose FIFO queue.
  27. /// </summary>
  28. public GPFifoDevice GPFifo { get; }
  29. /// <summary>
  30. /// GPU synchronization manager.
  31. /// </summary>
  32. public SynchronizationManager Synchronization { get; }
  33. /// <summary>
  34. /// Presentation window.
  35. /// </summary>
  36. public Window Window { get; }
  37. /// <summary>
  38. /// Internal sequence number, used to avoid needless resource data updates
  39. /// in the middle of a command buffer before synchronizations.
  40. /// </summary>
  41. internal int SequenceNumber { get; private set; }
  42. /// <summary>
  43. /// Internal sync number, used to denote points at which host synchronization can be requested.
  44. /// </summary>
  45. internal ulong SyncNumber { get; private set; }
  46. /// <summary>
  47. /// Actions to be performed when a CPU waiting syncpoint or barrier is triggered.
  48. /// If there are more than 0 items when this happens, a host sync object will be generated for the given <see cref="SyncNumber"/>,
  49. /// and the SyncNumber will be incremented.
  50. /// </summary>
  51. internal List<Action> SyncActions { get; }
  52. /// <summary>
  53. /// Actions to be performed when a CPU waiting syncpoint is triggered.
  54. /// If there are more than 0 items when this happens, a host sync object will be generated for the given <see cref="SyncNumber"/>,
  55. /// and the SyncNumber will be incremented.
  56. /// </summary>
  57. internal List<Action> SyncpointActions { get; }
  58. /// <summary>
  59. /// Queue with deferred actions that must run on the render thread.
  60. /// </summary>
  61. internal Queue<Action> DeferredActions { get; }
  62. /// <summary>
  63. /// Registry with physical memories that can be used with this GPU context, keyed by owner process ID.
  64. /// </summary>
  65. internal ConcurrentDictionary<long, PhysicalMemory> PhysicalMemoryRegistry { get; }
  66. /// <summary>
  67. /// Host hardware capabilities.
  68. /// </summary>
  69. internal ref Capabilities Capabilities
  70. {
  71. get
  72. {
  73. if (!_capsLoaded)
  74. {
  75. _caps = Renderer.GetCapabilities();
  76. _capsLoaded = true;
  77. }
  78. return ref _caps;
  79. }
  80. }
  81. /// <summary>
  82. /// Event for signalling shader cache loading progress.
  83. /// </summary>
  84. public event Action<ShaderCacheState, int, int> ShaderCacheStateChanged;
  85. private bool _capsLoaded;
  86. private Capabilities _caps;
  87. private Thread _gpuThread;
  88. /// <summary>
  89. /// Creates a new instance of the GPU emulation context.
  90. /// </summary>
  91. /// <param name="renderer">Host renderer</param>
  92. public GpuContext(IRenderer renderer)
  93. {
  94. Renderer = renderer;
  95. GPFifo = new GPFifoDevice(this);
  96. Synchronization = new SynchronizationManager();
  97. Window = new Window(this);
  98. HostInitalized = new ManualResetEvent(false);
  99. SyncActions = new List<Action>();
  100. SyncpointActions = new List<Action>();
  101. DeferredActions = new Queue<Action>();
  102. PhysicalMemoryRegistry = new ConcurrentDictionary<long, PhysicalMemory>();
  103. }
  104. /// <summary>
  105. /// Creates a new GPU channel.
  106. /// </summary>
  107. /// <returns>The GPU channel</returns>
  108. public GpuChannel CreateChannel()
  109. {
  110. return new GpuChannel(this);
  111. }
  112. /// <summary>
  113. /// Creates a new GPU memory manager.
  114. /// </summary>
  115. /// <param name="pid">ID of the process that owns the memory manager</param>
  116. /// <returns>The memory manager</returns>
  117. /// <exception cref="ArgumentException">Thrown when <paramref name="pid"/> is invalid</exception>
  118. public MemoryManager CreateMemoryManager(long pid)
  119. {
  120. if (!PhysicalMemoryRegistry.TryGetValue(pid, out var physicalMemory))
  121. {
  122. throw new ArgumentException("The PID is invalid or the process was not registered", nameof(pid));
  123. }
  124. return new MemoryManager(physicalMemory);
  125. }
  126. /// <summary>
  127. /// Registers virtual memory used by a process for GPU memory access, caching and read/write tracking.
  128. /// </summary>
  129. /// <param name="pid">ID of the process that owns <paramref name="cpuMemory"/></param>
  130. /// <param name="cpuMemory">Virtual memory owned by the process</param>
  131. /// <exception cref="ArgumentException">Thrown if <paramref name="pid"/> was already registered</exception>
  132. public void RegisterProcess(long pid, Cpu.IVirtualMemoryManagerTracked cpuMemory)
  133. {
  134. var physicalMemory = new PhysicalMemory(this, cpuMemory);
  135. if (!PhysicalMemoryRegistry.TryAdd(pid, physicalMemory))
  136. {
  137. throw new ArgumentException("The PID was already registered", nameof(pid));
  138. }
  139. physicalMemory.ShaderCache.ShaderCacheStateChanged += ShaderCacheStateUpdate;
  140. }
  141. /// <summary>
  142. /// Unregisters a process, indicating that its memory will no longer be used, and that caches can be freed.
  143. /// </summary>
  144. /// <param name="pid">ID of the process</param>
  145. public void UnregisterProcess(long pid)
  146. {
  147. if (PhysicalMemoryRegistry.TryRemove(pid, out var physicalMemory))
  148. {
  149. physicalMemory.ShaderCache.ShaderCacheStateChanged -= ShaderCacheStateUpdate;
  150. physicalMemory.Dispose();
  151. }
  152. }
  153. /// <summary>
  154. /// Shader cache state update handler.
  155. /// </summary>
  156. /// <param name="state">Current state of the shader cache load process</param>
  157. /// <param name="current">Number of the current shader being processed</param>
  158. /// <param name="total">Total number of shaders to process</param>
  159. private void ShaderCacheStateUpdate(ShaderCacheState state, int current, int total)
  160. {
  161. ShaderCacheStateChanged?.Invoke(state, current, total);
  162. }
  163. /// <summary>
  164. /// Initialize the GPU shader cache.
  165. /// </summary>
  166. public void InitializeShaderCache()
  167. {
  168. HostInitalized.WaitOne();
  169. foreach (var physicalMemory in PhysicalMemoryRegistry.Values)
  170. {
  171. physicalMemory.ShaderCache.Initialize();
  172. }
  173. }
  174. /// <summary>
  175. /// Sets the current thread as the main GPU thread.
  176. /// </summary>
  177. public void SetGpuThread()
  178. {
  179. _gpuThread = Thread.CurrentThread;
  180. }
  181. /// <summary>
  182. /// Checks if the current thread is the GPU thread.
  183. /// </summary>
  184. /// <returns>True if the thread is the GPU thread, false otherwise</returns>
  185. public bool IsGpuThread()
  186. {
  187. return _gpuThread == Thread.CurrentThread;
  188. }
  189. /// <summary>
  190. /// Processes the queue of shaders that must save their binaries to the disk cache.
  191. /// </summary>
  192. public void ProcessShaderCacheQueue()
  193. {
  194. foreach (var physicalMemory in PhysicalMemoryRegistry.Values)
  195. {
  196. physicalMemory.ShaderCache.ProcessShaderCacheQueue();
  197. }
  198. }
  199. /// <summary>
  200. /// Advances internal sequence number.
  201. /// This forces the update of any modified GPU resource.
  202. /// </summary>
  203. internal void AdvanceSequence()
  204. {
  205. SequenceNumber++;
  206. }
  207. /// <summary>
  208. /// Registers an action to be performed the next time a syncpoint is incremented.
  209. /// This will also ensure a host sync object is created, and <see cref="SyncNumber"/> is incremented.
  210. /// </summary>
  211. /// <param name="action">The action to be performed on sync object creation</param>
  212. /// <param name="syncpointOnly">True if the sync action should only run when syncpoints are incremented</param>
  213. public void RegisterSyncAction(Action action, bool syncpointOnly = false)
  214. {
  215. if (syncpointOnly)
  216. {
  217. SyncpointActions.Add(action);
  218. }
  219. else
  220. {
  221. SyncActions.Add(action);
  222. }
  223. }
  224. /// <summary>
  225. /// Creates a host sync object if there are any pending sync actions. The actions will then be called.
  226. /// If no actions are present, a host sync object is not created.
  227. /// </summary>
  228. /// <param name="syncpoint">True if host sync is being created by a syncpoint</param>
  229. public void CreateHostSyncIfNeeded(bool syncpoint)
  230. {
  231. if (SyncActions.Count > 0 || (syncpoint && SyncpointActions.Count > 0))
  232. {
  233. Renderer.CreateSync(SyncNumber);
  234. SyncNumber++;
  235. foreach (Action action in SyncActions)
  236. {
  237. action();
  238. }
  239. foreach (Action action in SyncpointActions)
  240. {
  241. action();
  242. }
  243. SyncActions.Clear();
  244. SyncpointActions.Clear();
  245. }
  246. }
  247. /// <summary>
  248. /// Performs deferred actions.
  249. /// This is useful for actions that must run on the render thread, such as resource disposal.
  250. /// </summary>
  251. internal void RunDeferredActions()
  252. {
  253. while (DeferredActions.TryDequeue(out Action action))
  254. {
  255. action();
  256. }
  257. }
  258. /// <summary>
  259. /// Disposes all GPU resources currently cached.
  260. /// It's an error to push any GPU commands after disposal.
  261. /// Additionally, the GPU commands FIFO must be empty for disposal,
  262. /// and processing of all commands must have finished.
  263. /// </summary>
  264. public void Dispose()
  265. {
  266. Renderer.Dispose();
  267. GPFifo.Dispose();
  268. HostInitalized.Dispose();
  269. // Has to be disposed before processing deferred actions, as it will produce some.
  270. foreach (var physicalMemory in PhysicalMemoryRegistry.Values)
  271. {
  272. physicalMemory.Dispose();
  273. }
  274. PhysicalMemoryRegistry.Clear();
  275. RunDeferredActions();
  276. }
  277. }
  278. }