PhysicalMemory.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. using Ryujinx.Cpu;
  2. using Ryujinx.Graphics.Gpu.Image;
  3. using Ryujinx.Graphics.Gpu.Shader;
  4. using Ryujinx.Memory;
  5. using Ryujinx.Memory.Range;
  6. using Ryujinx.Memory.Tracking;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Linq;
  10. using System.Runtime.InteropServices;
  11. using System.Threading;
  12. namespace Ryujinx.Graphics.Gpu.Memory
  13. {
  14. /// <summary>
  15. /// Represents physical memory, accessible from the GPU.
  16. /// This is actually working CPU virtual addresses, of memory mapped on the application process.
  17. /// </summary>
  18. class PhysicalMemory : IDisposable
  19. {
  20. private readonly GpuContext _context;
  21. private IVirtualMemoryManagerTracked _cpuMemory;
  22. private int _referenceCount;
  23. /// <summary>
  24. /// Indicates whenever the memory manager supports 4KB pages.
  25. /// </summary>
  26. public bool Supports4KBPages => _cpuMemory.Supports4KBPages;
  27. /// <summary>
  28. /// In-memory shader cache.
  29. /// </summary>
  30. public ShaderCache ShaderCache { get; }
  31. /// <summary>
  32. /// GPU buffer manager.
  33. /// </summary>
  34. public BufferCache BufferCache { get; }
  35. /// <summary>
  36. /// GPU texture manager.
  37. /// </summary>
  38. public TextureCache TextureCache { get; }
  39. /// <summary>
  40. /// Creates a new instance of the physical memory.
  41. /// </summary>
  42. /// <param name="context">GPU context that the physical memory belongs to</param>
  43. /// <param name="cpuMemory">CPU memory manager of the application process</param>
  44. public PhysicalMemory(GpuContext context, IVirtualMemoryManagerTracked cpuMemory)
  45. {
  46. _context = context;
  47. _cpuMemory = cpuMemory;
  48. ShaderCache = new ShaderCache(context);
  49. BufferCache = new BufferCache(context, this);
  50. TextureCache = new TextureCache(context, this);
  51. if (cpuMemory is IRefCounted rc)
  52. {
  53. rc.IncrementReferenceCount();
  54. }
  55. _referenceCount = 1;
  56. }
  57. /// <summary>
  58. /// Increments the memory reference count.
  59. /// </summary>
  60. public void IncrementReferenceCount()
  61. {
  62. Interlocked.Increment(ref _referenceCount);
  63. }
  64. /// <summary>
  65. /// Decrements the memory reference count.
  66. /// </summary>
  67. public void DecrementReferenceCount()
  68. {
  69. if (Interlocked.Decrement(ref _referenceCount) == 0 && _cpuMemory is IRefCounted rc)
  70. {
  71. rc.DecrementReferenceCount();
  72. }
  73. }
  74. /// <summary>
  75. /// Gets a host pointer for a given range of application memory.
  76. /// If the memory region is not a single contiguous block, this method returns 0.
  77. /// </summary>
  78. /// <remarks>
  79. /// Getting a host pointer is unsafe. It should be considered invalid immediately if the GPU memory is unmapped.
  80. /// </remarks>
  81. /// <param name="range">Ranges of physical memory where the target data is located</param>
  82. /// <returns>Pointer to the range of memory</returns>
  83. public nint GetHostPointer(MultiRange range)
  84. {
  85. if (range.Count == 1)
  86. {
  87. var singleRange = range.GetSubRange(0);
  88. if (singleRange.Address != MemoryManager.PteUnmapped)
  89. {
  90. var regions = _cpuMemory.GetHostRegions(singleRange.Address, singleRange.Size);
  91. if (regions != null && regions.Count() == 1)
  92. {
  93. return (nint)regions.First().Address;
  94. }
  95. }
  96. }
  97. return 0;
  98. }
  99. /// <summary>
  100. /// Gets a span of data from the application process.
  101. /// </summary>
  102. /// <param name="address">Start address of the range</param>
  103. /// <param name="size">Size in bytes to be range</param>
  104. /// <param name="tracked">True if read tracking is triggered on the span</param>
  105. /// <returns>A read only span of the data at the specified memory location</returns>
  106. public ReadOnlySpan<byte> GetSpan(ulong address, int size, bool tracked = false)
  107. {
  108. return _cpuMemory.GetSpan(address, size, tracked);
  109. }
  110. /// <summary>
  111. /// Gets a span of data from the application process.
  112. /// </summary>
  113. /// <param name="range">Ranges of physical memory where the data is located</param>
  114. /// <param name="tracked">True if read tracking is triggered on the span</param>
  115. /// <returns>A read only span of the data at the specified memory location</returns>
  116. public ReadOnlySpan<byte> GetSpan(MultiRange range, bool tracked = false)
  117. {
  118. if (range.Count == 1)
  119. {
  120. var singleRange = range.GetSubRange(0);
  121. if (singleRange.Address != MemoryManager.PteUnmapped)
  122. {
  123. return _cpuMemory.GetSpan(singleRange.Address, (int)singleRange.Size, tracked);
  124. }
  125. }
  126. Span<byte> data = new byte[range.GetSize()];
  127. int offset = 0;
  128. for (int i = 0; i < range.Count; i++)
  129. {
  130. var currentRange = range.GetSubRange(i);
  131. int size = (int)currentRange.Size;
  132. if (currentRange.Address != MemoryManager.PteUnmapped)
  133. {
  134. _cpuMemory.GetSpan(currentRange.Address, size, tracked).CopyTo(data.Slice(offset, size));
  135. }
  136. offset += size;
  137. }
  138. return data;
  139. }
  140. /// <summary>
  141. /// Gets a writable region from the application process.
  142. /// </summary>
  143. /// <param name="address">Start address of the range</param>
  144. /// <param name="size">Size in bytes to be range</param>
  145. /// <param name="tracked">True if write tracking is triggered on the span</param>
  146. /// <returns>A writable region with the data at the specified memory location</returns>
  147. public WritableRegion GetWritableRegion(ulong address, int size, bool tracked = false)
  148. {
  149. return _cpuMemory.GetWritableRegion(address, size, tracked);
  150. }
  151. /// <summary>
  152. /// Gets a writable region from GPU mapped memory.
  153. /// </summary>
  154. /// <param name="range">Range</param>
  155. /// <param name="tracked">True if write tracking is triggered on the span</param>
  156. /// <returns>A writable region with the data at the specified memory location</returns>
  157. public WritableRegion GetWritableRegion(MultiRange range, bool tracked = false)
  158. {
  159. if (range.Count == 1)
  160. {
  161. MemoryRange subrange = range.GetSubRange(0);
  162. return GetWritableRegion(subrange.Address, (int)subrange.Size, tracked);
  163. }
  164. else
  165. {
  166. Memory<byte> memory = new byte[range.GetSize()];
  167. int offset = 0;
  168. for (int i = 0; i < range.Count; i++)
  169. {
  170. var currentRange = range.GetSubRange(i);
  171. int size = (int)currentRange.Size;
  172. if (currentRange.Address != MemoryManager.PteUnmapped)
  173. {
  174. GetSpan(currentRange.Address, size).CopyTo(memory.Span.Slice(offset, size));
  175. }
  176. offset += size;
  177. }
  178. return new WritableRegion(new MultiRangeWritableBlock(range, this), 0, memory, tracked);
  179. }
  180. }
  181. /// <summary>
  182. /// Reads data from the application process.
  183. /// </summary>
  184. /// <typeparam name="T">Type of the structure</typeparam>
  185. /// <param name="address">Address to read from</param>
  186. /// <returns>The data at the specified memory location</returns>
  187. public T Read<T>(ulong address) where T : unmanaged
  188. {
  189. return _cpuMemory.Read<T>(address);
  190. }
  191. /// <summary>
  192. /// Reads data from the application process, with write tracking.
  193. /// </summary>
  194. /// <typeparam name="T">Type of the structure</typeparam>
  195. /// <param name="address">Address to read from</param>
  196. /// <returns>The data at the specified memory location</returns>
  197. public T ReadTracked<T>(ulong address) where T : unmanaged
  198. {
  199. return _cpuMemory.ReadTracked<T>(address);
  200. }
  201. /// <summary>
  202. /// Writes data to the application process, triggering a precise memory tracking event.
  203. /// </summary>
  204. /// <param name="address">Address to write into</param>
  205. /// <param name="data">Data to be written</param>
  206. public void WriteTrackedResource(ulong address, ReadOnlySpan<byte> data)
  207. {
  208. _cpuMemory.SignalMemoryTracking(address, (ulong)data.Length, true, precise: true);
  209. _cpuMemory.WriteUntracked(address, data);
  210. }
  211. /// <summary>
  212. /// Writes data to the application process.
  213. /// </summary>
  214. /// <param name="address">Address to write into</param>
  215. /// <param name="data">Data to be written</param>
  216. public void Write(ulong address, ReadOnlySpan<byte> data)
  217. {
  218. _cpuMemory.Write(address, data);
  219. }
  220. /// <summary>
  221. /// Writes data to the application process.
  222. /// </summary>
  223. /// <param name="range">Ranges of physical memory where the data is located</param>
  224. /// <param name="data">Data to be written</param>
  225. public void Write(MultiRange range, ReadOnlySpan<byte> data)
  226. {
  227. WriteImpl(range, data, _cpuMemory.Write);
  228. }
  229. /// <summary>
  230. /// Writes data to the application process, without any tracking.
  231. /// </summary>
  232. /// <param name="address">Address to write into</param>
  233. /// <param name="data">Data to be written</param>
  234. public void WriteUntracked(ulong address, ReadOnlySpan<byte> data)
  235. {
  236. _cpuMemory.WriteUntracked(address, data);
  237. }
  238. /// <summary>
  239. /// Writes data to the application process, without any tracking.
  240. /// </summary>
  241. /// <param name="range">Ranges of physical memory where the data is located</param>
  242. /// <param name="data">Data to be written</param>
  243. public void WriteUntracked(MultiRange range, ReadOnlySpan<byte> data)
  244. {
  245. WriteImpl(range, data, _cpuMemory.WriteUntracked);
  246. }
  247. /// <summary>
  248. /// Writes data to the application process, returning false if the data was not changed.
  249. /// This triggers read memory tracking, as a redundancy check would be useless if the data is not up to date.
  250. /// </summary>
  251. /// <remarks>The memory manager can return that memory has changed when it hasn't to avoid expensive data copies.</remarks>
  252. /// <param name="address">Address to write into</param>
  253. /// <param name="data">Data to be written</param>
  254. /// <returns>True if the data was changed, false otherwise</returns>
  255. public bool WriteWithRedundancyCheck(ulong address, ReadOnlySpan<byte> data)
  256. {
  257. return _cpuMemory.WriteWithRedundancyCheck(address, data);
  258. }
  259. private delegate void WriteCallback(ulong address, ReadOnlySpan<byte> data);
  260. /// <summary>
  261. /// Writes data to the application process, using the supplied callback method.
  262. /// </summary>
  263. /// <param name="range">Ranges of physical memory where the data is located</param>
  264. /// <param name="data">Data to be written</param>
  265. /// <param name="writeCallback">Callback method that will perform the write</param>
  266. private static void WriteImpl(MultiRange range, ReadOnlySpan<byte> data, WriteCallback writeCallback)
  267. {
  268. if (range.Count == 1)
  269. {
  270. var singleRange = range.GetSubRange(0);
  271. if (singleRange.Address != MemoryManager.PteUnmapped)
  272. {
  273. writeCallback(singleRange.Address, data);
  274. }
  275. }
  276. else
  277. {
  278. int offset = 0;
  279. for (int i = 0; i < range.Count; i++)
  280. {
  281. var currentRange = range.GetSubRange(i);
  282. int size = (int)currentRange.Size;
  283. if (currentRange.Address != MemoryManager.PteUnmapped)
  284. {
  285. writeCallback(currentRange.Address, data.Slice(offset, size));
  286. }
  287. offset += size;
  288. }
  289. }
  290. }
  291. /// <summary>
  292. /// Fills the specified memory region with a 32-bit integer value.
  293. /// </summary>
  294. /// <param name="address">CPU virtual address of the region</param>
  295. /// <param name="size">Size of the region</param>
  296. /// <param name="value">Value to fill the region with</param>
  297. /// <param name="kind">Kind of the resource being filled, which will not be signalled as CPU modified</param>
  298. public void FillTrackedResource(ulong address, ulong size, uint value, ResourceKind kind)
  299. {
  300. _cpuMemory.SignalMemoryTracking(address, size, write: true, precise: true, (int)kind);
  301. using WritableRegion region = _cpuMemory.GetWritableRegion(address, (int)size);
  302. MemoryMarshal.Cast<byte, uint>(region.Memory.Span).Fill(value);
  303. }
  304. /// <summary>
  305. /// Obtains a memory tracking handle for the given virtual region. This should be disposed when finished with.
  306. /// </summary>
  307. /// <param name="address">CPU virtual address of the region</param>
  308. /// <param name="size">Size of the region</param>
  309. /// <param name="kind">Kind of the resource being tracked</param>
  310. /// <returns>The memory tracking handle</returns>
  311. public RegionHandle BeginTracking(ulong address, ulong size, ResourceKind kind)
  312. {
  313. return _cpuMemory.BeginTracking(address, size, (int)kind);
  314. }
  315. /// <summary>
  316. /// Obtains a memory tracking handle for the given virtual region. This should be disposed when finished with.
  317. /// </summary>
  318. /// <param name="range">Ranges of physical memory where the data is located</param>
  319. /// <param name="kind">Kind of the resource being tracked</param>
  320. /// <returns>The memory tracking handle</returns>
  321. public GpuRegionHandle BeginTracking(MultiRange range, ResourceKind kind)
  322. {
  323. var cpuRegionHandles = new RegionHandle[range.Count];
  324. int count = 0;
  325. for (int i = 0; i < range.Count; i++)
  326. {
  327. var currentRange = range.GetSubRange(i);
  328. if (currentRange.Address != MemoryManager.PteUnmapped)
  329. {
  330. cpuRegionHandles[count++] = _cpuMemory.BeginTracking(currentRange.Address, currentRange.Size, (int)kind);
  331. }
  332. }
  333. if (count != range.Count)
  334. {
  335. Array.Resize(ref cpuRegionHandles, count);
  336. }
  337. return new GpuRegionHandle(cpuRegionHandles);
  338. }
  339. /// <summary>
  340. /// Obtains a memory tracking handle for the given virtual region, with a specified granularity. This should be disposed when finished with.
  341. /// </summary>
  342. /// <param name="address">CPU virtual address of the region</param>
  343. /// <param name="size">Size of the region</param>
  344. /// <param name="kind">Kind of the resource being tracked</param>
  345. /// <param name="handles">Handles to inherit state from or reuse</param>
  346. /// <param name="granularity">Desired granularity of write tracking</param>
  347. /// <returns>The memory tracking handle</returns>
  348. public MultiRegionHandle BeginGranularTracking(ulong address, ulong size, ResourceKind kind, IEnumerable<IRegionHandle> handles = null, ulong granularity = 4096)
  349. {
  350. return _cpuMemory.BeginGranularTracking(address, size, handles, granularity, (int)kind);
  351. }
  352. /// <summary>
  353. /// Obtains a smart memory tracking handle for the given virtual region, with a specified granularity. This should be disposed when finished with.
  354. /// </summary>
  355. /// <param name="address">CPU virtual address of the region</param>
  356. /// <param name="size">Size of the region</param>
  357. /// <param name="kind">Kind of the resource being tracked</param>
  358. /// <param name="granularity">Desired granularity of write tracking</param>
  359. /// <returns>The memory tracking handle</returns>
  360. public SmartMultiRegionHandle BeginSmartGranularTracking(ulong address, ulong size, ResourceKind kind, ulong granularity = 4096)
  361. {
  362. return _cpuMemory.BeginSmartGranularTracking(address, size, granularity, (int)kind);
  363. }
  364. /// <summary>
  365. /// Checks if a given memory page is mapped.
  366. /// </summary>
  367. /// <param name="address">CPU virtual address of the page</param>
  368. /// <returns>True if mapped, false otherwise</returns>
  369. public bool IsMapped(ulong address)
  370. {
  371. return _cpuMemory.IsMapped(address);
  372. }
  373. /// <summary>
  374. /// Release our reference to the CPU memory manager.
  375. /// </summary>
  376. public void Dispose()
  377. {
  378. _context.DeferredActions.Enqueue(Destroy);
  379. }
  380. /// <summary>
  381. /// Performs disposal of the host GPU caches with resources mapped on this physical memory.
  382. /// This must only be called from the render thread.
  383. /// </summary>
  384. private void Destroy()
  385. {
  386. ShaderCache.Dispose();
  387. BufferCache.Dispose();
  388. TextureCache.Dispose();
  389. DecrementReferenceCount();
  390. }
  391. }
  392. }