GpuContext.cs 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  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 sync point 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. /// Queue with deferred actions that must run on the render thread.
  54. /// </summary>
  55. internal Queue<Action> DeferredActions { get; }
  56. /// <summary>
  57. /// Registry with physical memories that can be used with this GPU context, keyed by owner process ID.
  58. /// </summary>
  59. internal ConcurrentDictionary<long, PhysicalMemory> PhysicalMemoryRegistry { get; }
  60. /// <summary>
  61. /// Host hardware capabilities.
  62. /// </summary>
  63. internal Capabilities Capabilities => _caps.Value;
  64. /// <summary>
  65. /// Event for signalling shader cache loading progress.
  66. /// </summary>
  67. public event Action<ShaderCacheState, int, int> ShaderCacheStateChanged;
  68. private readonly Lazy<Capabilities> _caps;
  69. /// <summary>
  70. /// Creates a new instance of the GPU emulation context.
  71. /// </summary>
  72. /// <param name="renderer">Host renderer</param>
  73. public GpuContext(IRenderer renderer)
  74. {
  75. Renderer = renderer;
  76. GPFifo = new GPFifoDevice(this);
  77. Synchronization = new SynchronizationManager();
  78. Window = new Window(this);
  79. HostInitalized = new ManualResetEvent(false);
  80. SyncActions = new List<Action>();
  81. DeferredActions = new Queue<Action>();
  82. PhysicalMemoryRegistry = new ConcurrentDictionary<long, PhysicalMemory>();
  83. _caps = new Lazy<Capabilities>(Renderer.GetCapabilities);
  84. }
  85. /// <summary>
  86. /// Creates a new GPU channel.
  87. /// </summary>
  88. /// <returns>The GPU channel</returns>
  89. public GpuChannel CreateChannel()
  90. {
  91. return new GpuChannel(this);
  92. }
  93. /// <summary>
  94. /// Creates a new GPU memory manager.
  95. /// </summary>
  96. /// <param name="pid">ID of the process that owns the memory manager</param>
  97. /// <returns>The memory manager</returns>
  98. /// <exception cref="ArgumentException">Thrown when <paramref name="pid"/> is invalid</exception>
  99. public MemoryManager CreateMemoryManager(long pid)
  100. {
  101. if (!PhysicalMemoryRegistry.TryGetValue(pid, out var physicalMemory))
  102. {
  103. throw new ArgumentException("The PID is invalid or the process was not registered", nameof(pid));
  104. }
  105. return new MemoryManager(physicalMemory);
  106. }
  107. /// <summary>
  108. /// Registers virtual memory used by a process for GPU memory access, caching and read/write tracking.
  109. /// </summary>
  110. /// <param name="pid">ID of the process that owns <paramref name="cpuMemory"/></param>
  111. /// <param name="cpuMemory">Virtual memory owned by the process</param>
  112. /// <exception cref="ArgumentException">Thrown if <paramref name="pid"/> was already registered</exception>
  113. public void RegisterProcess(long pid, Cpu.IVirtualMemoryManagerTracked cpuMemory)
  114. {
  115. var physicalMemory = new PhysicalMemory(this, cpuMemory);
  116. if (!PhysicalMemoryRegistry.TryAdd(pid, physicalMemory))
  117. {
  118. throw new ArgumentException("The PID was already registered", nameof(pid));
  119. }
  120. physicalMemory.ShaderCache.ShaderCacheStateChanged += ShaderCacheStateUpdate;
  121. }
  122. /// <summary>
  123. /// Unregisters a process, indicating that its memory will no longer be used, and that caches can be freed.
  124. /// </summary>
  125. /// <param name="pid">ID of the process</param>
  126. public void UnregisterProcess(long pid)
  127. {
  128. if (PhysicalMemoryRegistry.TryRemove(pid, out var physicalMemory))
  129. {
  130. physicalMemory.ShaderCache.ShaderCacheStateChanged -= ShaderCacheStateUpdate;
  131. physicalMemory.Dispose();
  132. }
  133. }
  134. /// <summary>
  135. /// Shader cache state update handler.
  136. /// </summary>
  137. /// <param name="state">Current state of the shader cache load process</param>
  138. /// <param name="current">Number of the current shader being processed</param>
  139. /// <param name="total">Total number of shaders to process</param>
  140. private void ShaderCacheStateUpdate(ShaderCacheState state, int current, int total)
  141. {
  142. ShaderCacheStateChanged?.Invoke(state, current, total);
  143. }
  144. /// <summary>
  145. /// Initialize the GPU shader cache.
  146. /// </summary>
  147. public void InitializeShaderCache()
  148. {
  149. HostInitalized.WaitOne();
  150. foreach (var physicalMemory in PhysicalMemoryRegistry.Values)
  151. {
  152. physicalMemory.ShaderCache.Initialize();
  153. }
  154. }
  155. /// <summary>
  156. /// Processes the queue of shaders that must save their binaries to the disk cache.
  157. /// </summary>
  158. public void ProcessShaderCacheQueue()
  159. {
  160. foreach (var physicalMemory in PhysicalMemoryRegistry.Values)
  161. {
  162. physicalMemory.ShaderCache.ProcessShaderCacheQueue();
  163. }
  164. }
  165. /// <summary>
  166. /// Advances internal sequence number.
  167. /// This forces the update of any modified GPU resource.
  168. /// </summary>
  169. internal void AdvanceSequence()
  170. {
  171. SequenceNumber++;
  172. }
  173. /// <summary>
  174. /// Registers an action to be performed the next time a syncpoint is incremented.
  175. /// This will also ensure a host sync object is created, and <see cref="SyncNumber"/> is incremented.
  176. /// </summary>
  177. /// <param name="action">The action to be performed on sync object creation</param>
  178. public void RegisterSyncAction(Action action)
  179. {
  180. SyncActions.Add(action);
  181. }
  182. /// <summary>
  183. /// Creates a host sync object if there are any pending sync actions. The actions will then be called.
  184. /// If no actions are present, a host sync object is not created.
  185. /// </summary>
  186. public void CreateHostSyncIfNeeded()
  187. {
  188. if (SyncActions.Count > 0)
  189. {
  190. Renderer.CreateSync(SyncNumber);
  191. SyncNumber++;
  192. foreach (Action action in SyncActions)
  193. {
  194. action();
  195. }
  196. SyncActions.Clear();
  197. }
  198. }
  199. /// <summary>
  200. /// Performs deferred actions.
  201. /// This is useful for actions that must run on the render thread, such as resource disposal.
  202. /// </summary>
  203. internal void RunDeferredActions()
  204. {
  205. while (DeferredActions.TryDequeue(out Action action))
  206. {
  207. action();
  208. }
  209. }
  210. /// <summary>
  211. /// Disposes all GPU resources currently cached.
  212. /// It's an error to push any GPU commands after disposal.
  213. /// Additionally, the GPU commands FIFO must be empty for disposal,
  214. /// and processing of all commands must have finished.
  215. /// </summary>
  216. public void Dispose()
  217. {
  218. Renderer.Dispose();
  219. GPFifo.Dispose();
  220. HostInitalized.Dispose();
  221. // Has to be disposed before processing deferred actions, as it will produce some.
  222. foreach (var physicalMemory in PhysicalMemoryRegistry.Values)
  223. {
  224. physicalMemory.Dispose();
  225. }
  226. PhysicalMemoryRegistry.Clear();
  227. RunDeferredActions();
  228. }
  229. }
  230. }