GpuContext.cs 9.2 KB

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