MemoryTracking.cs 11 KB

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