GpuContext.cs 11 KB

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