PhysicalMemory.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using System;
  2. using System.Runtime.CompilerServices;
  3. using System.Runtime.InteropServices;
  4. namespace Ryujinx.Graphics.Gpu.Memory
  5. {
  6. /// <summary>
  7. /// Represents physical memory, accessible from the GPU.
  8. /// This is actually working CPU virtual addresses, of memory mapped on the application process.
  9. /// </summary>
  10. class PhysicalMemory
  11. {
  12. public const int PageSize = Cpu.MemoryManager.PageSize;
  13. private readonly Cpu.MemoryManager _cpuMemory;
  14. /// <summary>
  15. /// Creates a new instance of the physical memory.
  16. /// </summary>
  17. /// <param name="cpuMemory">CPU memory manager of the application process</param>
  18. public PhysicalMemory(Cpu.MemoryManager cpuMemory)
  19. {
  20. _cpuMemory = cpuMemory;
  21. }
  22. /// <summary>
  23. /// Gets a span of data from the application process.
  24. /// </summary>
  25. /// <param name="address">Start address of the range</param>
  26. /// <param name="size">Size in bytes to be range</param>
  27. /// <returns>A read only span of the data at the specified memory location</returns>
  28. public ReadOnlySpan<byte> GetSpan(ulong address, int size)
  29. {
  30. return _cpuMemory.GetSpan(address, size);
  31. }
  32. /// <summary>
  33. /// Reads data from the application process.
  34. /// </summary>
  35. /// <typeparam name="T">Type of the structure</typeparam>
  36. /// <param name="gpuVa">Address to read from</param>
  37. /// <returns>The data at the specified memory location</returns>
  38. public T Read<T>(ulong address) where T : unmanaged
  39. {
  40. return MemoryMarshal.Cast<byte, T>(GetSpan(address, Unsafe.SizeOf<T>()))[0];
  41. }
  42. /// <summary>
  43. /// Writes data to the application process.
  44. /// </summary>
  45. /// <param name="address">Address to write into</param>
  46. /// <param name="data">Data to be written</param>
  47. public void Write(ulong address, ReadOnlySpan<byte> data)
  48. {
  49. _cpuMemory.Write(address, data);
  50. }
  51. /// <summary>
  52. /// Checks if a specified virtual memory region has been modified by the CPU since the last call.
  53. /// </summary>
  54. /// <param name="address">CPU virtual address of the region</param>
  55. /// <param name="size">Size of the region</param>
  56. /// <param name="name">Resource name</param>
  57. /// <param name="modifiedRanges">Optional array where the modified ranges should be written</param>
  58. /// <returns>The number of modified ranges</returns>
  59. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  60. public int QueryModified(ulong address, ulong size, ResourceName name, (ulong, ulong)[] modifiedRanges = null)
  61. {
  62. return _cpuMemory.QueryModified(address, size, (int)name, modifiedRanges);
  63. }
  64. }
  65. }