GpuContext.cs 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  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. /// Advances internal sequence number.
  157. /// This forces the update of any modified GPU resource.
  158. /// </summary>
  159. internal void AdvanceSequence()
  160. {
  161. SequenceNumber++;
  162. }
  163. /// <summary>
  164. /// Registers an action to be performed the next time a syncpoint is incremented.
  165. /// This will also ensure a host sync object is created, and <see cref="SyncNumber"/> is incremented.
  166. /// </summary>
  167. /// <param name="action">The action to be performed on sync object creation</param>
  168. public void RegisterSyncAction(Action action)
  169. {
  170. SyncActions.Add(action);
  171. }
  172. /// <summary>
  173. /// Creates a host sync object if there are any pending sync actions. The actions will then be called.
  174. /// If no actions are present, a host sync object is not created.
  175. /// </summary>
  176. public void CreateHostSyncIfNeeded()
  177. {
  178. if (SyncActions.Count > 0)
  179. {
  180. Renderer.CreateSync(SyncNumber);
  181. SyncNumber++;
  182. foreach (Action action in SyncActions)
  183. {
  184. action();
  185. }
  186. SyncActions.Clear();
  187. }
  188. }
  189. /// <summary>
  190. /// Performs deferred actions.
  191. /// This is useful for actions that must run on the render thread, such as resource disposal.
  192. /// </summary>
  193. internal void RunDeferredActions()
  194. {
  195. while (DeferredActions.TryDequeue(out Action action))
  196. {
  197. action();
  198. }
  199. }
  200. /// <summary>
  201. /// Disposes all GPU resources currently cached.
  202. /// It's an error to push any GPU commands after disposal.
  203. /// Additionally, the GPU commands FIFO must be empty for disposal,
  204. /// and processing of all commands must have finished.
  205. /// </summary>
  206. public void Dispose()
  207. {
  208. Renderer.Dispose();
  209. GPFifo.Dispose();
  210. HostInitalized.Dispose();
  211. // Has to be disposed before processing deferred actions, as it will produce some.
  212. foreach (var physicalMemory in PhysicalMemoryRegistry.Values)
  213. {
  214. physicalMemory.Dispose();
  215. }
  216. PhysicalMemoryRegistry.Clear();
  217. RunDeferredActions();
  218. }
  219. }
  220. }