MemoryTracking.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. using Ryujinx.Memory.Range;
  2. using System.Collections.Generic;
  3. namespace Ryujinx.Memory.Tracking
  4. {
  5. /// <summary>
  6. /// Manages memory tracking for a given virutal/physical memory block.
  7. /// </summary>
  8. public class MemoryTracking
  9. {
  10. private readonly IVirtualMemoryManager _memoryManager;
  11. private readonly MemoryBlock _block;
  12. // Only use these from within the lock.
  13. private readonly NonOverlappingRangeList<VirtualRegion> _virtualRegions;
  14. // Only use these from within the lock.
  15. private readonly VirtualRegion[] _virtualResults = new VirtualRegion[10];
  16. private readonly int _pageSize;
  17. /// <summary>
  18. /// This lock must be obtained when traversing or updating the region-handle hierarchy.
  19. /// It is not required when reading dirty flags.
  20. /// </summary>
  21. internal object TrackingLock = new object();
  22. public bool EnablePhysicalProtection { get; set; }
  23. /// <summary>
  24. /// Create a new tracking structure for the given "physical" memory block,
  25. /// with a given "virtual" memory manager that will provide mappings and virtual memory protection.
  26. /// </summary>
  27. /// <param name="memoryManager">Virtual memory manager</param>
  28. /// <param name="block">Physical memory block</param>
  29. /// <param name="pageSize">Page size of the virtual memory space</param>
  30. public MemoryTracking(IVirtualMemoryManager memoryManager, MemoryBlock block, int pageSize)
  31. {
  32. _memoryManager = memoryManager;
  33. _block = block;
  34. _pageSize = pageSize;
  35. _virtualRegions = new NonOverlappingRangeList<VirtualRegion>();
  36. }
  37. private (ulong address, ulong size) PageAlign(ulong address, ulong size)
  38. {
  39. ulong pageMask = (ulong)_pageSize - 1;
  40. ulong rA = address & ~pageMask;
  41. ulong rS = ((address + size + pageMask) & ~pageMask) - rA;
  42. return (rA, rS);
  43. }
  44. /// <summary>
  45. /// Indicate that a virtual region has been mapped, and which physical region it has been mapped to.
  46. /// Should be called after the mapping is complete.
  47. /// </summary>
  48. /// <param name="va">Virtual memory address</param>
  49. /// <param name="pa">Physical memory address</param>
  50. /// <param name="size">Size to be mapped</param>
  51. public void Map(ulong va, ulong pa, ulong size)
  52. {
  53. // A mapping may mean we need to re-evaluate each VirtualRegion's affected area.
  54. // Find all handles that overlap with the range, we need to recalculate their physical regions
  55. lock (TrackingLock)
  56. {
  57. var results = _virtualResults;
  58. int count = _virtualRegions.FindOverlapsNonOverlapping(va, size, ref results);
  59. for (int i = 0; i < count; i++)
  60. {
  61. VirtualRegion region = results[i];
  62. // If the region has been fully remapped, signal that it has been mapped again.
  63. bool remapped = _memoryManager.IsRangeMapped(region.Address, region.Size);
  64. if (remapped)
  65. {
  66. region.SignalMappingChanged(true);
  67. }
  68. region.UpdateProtection();
  69. }
  70. }
  71. }
  72. /// <summary>
  73. /// Indicate that a virtual region has been unmapped.
  74. /// Should be called before the unmapping is complete.
  75. /// </summary>
  76. /// <param name="va">Virtual memory address</param>
  77. /// <param name="size">Size to be unmapped</param>
  78. public void Unmap(ulong va, ulong size)
  79. {
  80. // An unmapping may mean we need to re-evaluate each VirtualRegion's affected area.
  81. // Find all handles that overlap with the range, we need to notify them that the region was unmapped.
  82. lock (TrackingLock)
  83. {
  84. var results = _virtualResults;
  85. int count = _virtualRegions.FindOverlapsNonOverlapping(va, size, ref results);
  86. for (int i = 0; i < count; i++)
  87. {
  88. VirtualRegion region = results[i];
  89. region.SignalMappingChanged(false);
  90. }
  91. }
  92. }
  93. /// <summary>
  94. /// Get a list of virtual regions that a handle covers.
  95. /// </summary>
  96. /// <param name="va">Starting virtual memory address of the handle</param>
  97. /// <param name="size">Size of the handle's memory region</param>
  98. /// <returns>A list of virtual regions within the given range</returns>
  99. internal List<VirtualRegion> GetVirtualRegionsForHandle(ulong va, ulong size)
  100. {
  101. List<VirtualRegion> result = new List<VirtualRegion>();
  102. _virtualRegions.GetOrAddRegions(result, va, size, (va, size) => new VirtualRegion(this, va, size));
  103. return result;
  104. }
  105. /// <summary>
  106. /// Remove a virtual region from the range list. This assumes that the lock has been acquired.
  107. /// </summary>
  108. /// <param name="region">Region to remove</param>
  109. internal void RemoveVirtual(VirtualRegion region)
  110. {
  111. _virtualRegions.Remove(region);
  112. }
  113. /// <summary>
  114. /// Obtains a memory tracking handle for the given virtual region, with a specified granularity. This should be disposed when finished with.
  115. /// </summary>
  116. /// <param name="address">CPU virtual address of the region</param>
  117. /// <param name="size">Size of the region</param>
  118. /// <param name="granularity">Desired granularity of write tracking</param>
  119. /// <returns>The memory tracking handle</returns>
  120. public MultiRegionHandle BeginGranularTracking(ulong address, ulong size, ulong granularity)
  121. {
  122. (address, size) = PageAlign(address, size);
  123. return new MultiRegionHandle(this, address, size, granularity);
  124. }
  125. /// <summary>
  126. /// Obtains a smart memory tracking handle for the given virtual region, with a specified granularity. This should be disposed when finished with.
  127. /// </summary>
  128. /// <param name="address">CPU virtual address of the region</param>
  129. /// <param name="size">Size of the region</param>
  130. /// <param name="granularity">Desired granularity of write tracking</param>
  131. /// <returns>The memory tracking handle</returns>
  132. public SmartMultiRegionHandle BeginSmartGranularTracking(ulong address, ulong size, ulong granularity)
  133. {
  134. (address, size) = PageAlign(address, size);
  135. return new SmartMultiRegionHandle(this, address, size, granularity);
  136. }
  137. /// <summary>
  138. /// Obtains a memory tracking handle for the given virtual region. This should be disposed when finished with.
  139. /// </summary>
  140. /// <param name="address">CPU virtual address of the region</param>
  141. /// <param name="size">Size of the region</param>
  142. /// <returns>The memory tracking handle</returns>
  143. public RegionHandle BeginTracking(ulong address, ulong size)
  144. {
  145. (address, size) = PageAlign(address, size);
  146. lock (TrackingLock)
  147. {
  148. RegionHandle handle = new RegionHandle(this, address, size, _memoryManager.IsRangeMapped(address, size));
  149. return handle;
  150. }
  151. }
  152. /// <summary>
  153. /// Signal that a virtual memory event happened at the given location (one byte).
  154. /// </summary>
  155. /// <param name="address">Virtual address accessed</param>
  156. /// <param name="write">Whether the address was written to or read</param>
  157. /// <returns>True if the event triggered any tracking regions, false otherwise</returns>
  158. public bool VirtualMemoryEventTracking(ulong address, bool write)
  159. {
  160. return VirtualMemoryEvent(address, 1, write);
  161. }
  162. /// <summary>
  163. /// Signal that a virtual memory event happened at the given location.
  164. /// </summary>
  165. /// <param name="address">Virtual address accessed</param>
  166. /// <param name="size">Size of the region affected in bytes</param>
  167. /// <param name="write">Whether the region was written to or read</param>
  168. /// <returns>True if the event triggered any tracking regions, false otherwise</returns>
  169. public bool VirtualMemoryEvent(ulong address, ulong size, bool write)
  170. {
  171. // Look up the virtual region using the region list.
  172. // Signal up the chain to relevant handles.
  173. lock (TrackingLock)
  174. {
  175. var results = _virtualResults;
  176. int count = _virtualRegions.FindOverlapsNonOverlapping(address, size, ref results);
  177. if (count == 0)
  178. {
  179. _memoryManager.TrackingReprotect(address & ~(ulong)(_pageSize - 1), (ulong)_pageSize, MemoryPermission.ReadAndWrite);
  180. return false; // We can't handle this - it's probably a real invalid access.
  181. }
  182. for (int i = 0; i < count; i++)
  183. {
  184. VirtualRegion region = results[i];
  185. region.Signal(address, size, write);
  186. }
  187. }
  188. return true;
  189. }
  190. /// <summary>
  191. /// Reprotect a given virtual region. The virtual memory manager will handle this.
  192. /// </summary>
  193. /// <param name="region">Region to reprotect</param>
  194. /// <param name="permission">Memory permission to protect with</param>
  195. internal void ProtectVirtualRegion(VirtualRegion region, MemoryPermission permission)
  196. {
  197. _memoryManager.TrackingReprotect(region.Address, region.Size, permission);
  198. }
  199. /// <summary>
  200. /// Returns the number of virtual regions currently being tracked.
  201. /// Useful for tests and metrics.
  202. /// </summary>
  203. /// <returns>The number of virtual regions</returns>
  204. public int GetRegionCount()
  205. {
  206. lock (TrackingLock)
  207. {
  208. return _virtualRegions.Count;
  209. }
  210. }
  211. }
  212. }