MemoryTracking.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. using Ryujinx.Common.Pools;
  2. using Ryujinx.Memory.Range;
  3. using System.Collections.Generic;
  4. namespace Ryujinx.Memory.Tracking
  5. {
  6. /// <summary>
  7. /// Manages memory tracking for a given virutal/physical memory block.
  8. /// </summary>
  9. public class MemoryTracking
  10. {
  11. private readonly IVirtualMemoryManager _memoryManager;
  12. private readonly InvalidAccessHandler _invalidAccessHandler;
  13. // Only use these from within the lock.
  14. private readonly NonOverlappingRangeList<VirtualRegion> _virtualRegions;
  15. private readonly int _pageSize;
  16. /// <summary>
  17. /// This lock must be obtained when traversing or updating the region-handle hierarchy.
  18. /// It is not required when reading dirty flags.
  19. /// </summary>
  20. internal object TrackingLock = new object();
  21. /// <summary>
  22. /// Create a new tracking structure for the given "physical" memory block,
  23. /// with a given "virtual" memory manager that will provide mappings and virtual memory protection.
  24. /// </summary>
  25. /// <param name="memoryManager">Virtual memory manager</param>
  26. /// <param name="block">Physical memory block</param>
  27. /// <param name="pageSize">Page size of the virtual memory space</param>
  28. public MemoryTracking(IVirtualMemoryManager memoryManager, int pageSize, InvalidAccessHandler invalidAccessHandler = null)
  29. {
  30. _memoryManager = memoryManager;
  31. _pageSize = pageSize;
  32. _invalidAccessHandler = invalidAccessHandler;
  33. _virtualRegions = new NonOverlappingRangeList<VirtualRegion>();
  34. }
  35. private (ulong address, ulong size) PageAlign(ulong address, ulong size)
  36. {
  37. ulong pageMask = (ulong)_pageSize - 1;
  38. ulong rA = address & ~pageMask;
  39. ulong rS = ((address + size + pageMask) & ~pageMask) - rA;
  40. return (rA, rS);
  41. }
  42. /// <summary>
  43. /// Indicate that a virtual region has been mapped, and which physical region it has been mapped to.
  44. /// Should be called after the mapping is complete.
  45. /// </summary>
  46. /// <param name="va">Virtual memory address</param>
  47. /// <param name="size">Size to be mapped</param>
  48. public void Map(ulong va, ulong size)
  49. {
  50. // A mapping may mean we need to re-evaluate each VirtualRegion's affected area.
  51. // Find all handles that overlap with the range, we need to recalculate their physical regions
  52. lock (TrackingLock)
  53. {
  54. ref var overlaps = ref ThreadStaticArray<VirtualRegion>.Get();
  55. int count = _virtualRegions.FindOverlapsNonOverlapping(va, size, ref overlaps);
  56. for (int i = 0; i < count; i++)
  57. {
  58. VirtualRegion region = overlaps[i];
  59. // If the region has been fully remapped, signal that it has been mapped again.
  60. bool remapped = _memoryManager.IsRangeMapped(region.Address, region.Size);
  61. if (remapped)
  62. {
  63. region.SignalMappingChanged(true);
  64. }
  65. region.UpdateProtection();
  66. }
  67. }
  68. }
  69. /// <summary>
  70. /// Indicate that a virtual region has been unmapped.
  71. /// Should be called before the unmapping is complete.
  72. /// </summary>
  73. /// <param name="va">Virtual memory address</param>
  74. /// <param name="size">Size to be unmapped</param>
  75. public void Unmap(ulong va, ulong size)
  76. {
  77. // An unmapping may mean we need to re-evaluate each VirtualRegion's affected area.
  78. // Find all handles that overlap with the range, we need to notify them that the region was unmapped.
  79. lock (TrackingLock)
  80. {
  81. ref var overlaps = ref ThreadStaticArray<VirtualRegion>.Get();
  82. int count = _virtualRegions.FindOverlapsNonOverlapping(va, size, ref overlaps);
  83. for (int i = 0; i < count; i++)
  84. {
  85. VirtualRegion region = overlaps[i];
  86. region.SignalMappingChanged(false);
  87. }
  88. }
  89. }
  90. /// <summary>
  91. /// Get a list of virtual regions that a handle covers.
  92. /// </summary>
  93. /// <param name="va">Starting virtual memory address of the handle</param>
  94. /// <param name="size">Size of the handle's memory region</param>
  95. /// <returns>A list of virtual regions within the given range</returns>
  96. internal List<VirtualRegion> GetVirtualRegionsForHandle(ulong va, ulong size)
  97. {
  98. List<VirtualRegion> result = new List<VirtualRegion>();
  99. _virtualRegions.GetOrAddRegions(result, va, size, (va, size) => new VirtualRegion(this, va, size));
  100. return result;
  101. }
  102. /// <summary>
  103. /// Remove a virtual region from the range list. This assumes that the lock has been acquired.
  104. /// </summary>
  105. /// <param name="region">Region to remove</param>
  106. internal void RemoveVirtual(VirtualRegion region)
  107. {
  108. _virtualRegions.Remove(region);
  109. }
  110. /// <summary>
  111. /// Obtains a memory tracking handle for the given virtual region, with a specified granularity. This should be disposed when finished with.
  112. /// </summary>
  113. /// <param name="address">CPU virtual address of the region</param>
  114. /// <param name="size">Size of the region</param>
  115. /// <param name="handles">Handles to inherit state from or reuse. When none are present, provide null</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, IEnumerable<IRegionHandle> handles, ulong granularity)
  119. {
  120. (address, size) = PageAlign(address, size);
  121. return new MultiRegionHandle(this, address, size, handles, 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. /// Obtains a memory tracking handle for the given virtual region. This should be disposed when finished with.
  152. /// </summary>
  153. /// <param name="address">CPU virtual address of the region</param>
  154. /// <param name="size">Size of the region</param>
  155. /// <param name="bitmap">The bitmap owning the dirty flag for this handle</param>
  156. /// <param name="bit">The bit of this handle within the dirty flag</param>
  157. /// <returns>The memory tracking handle</returns>
  158. internal RegionHandle BeginTrackingBitmap(ulong address, ulong size, ConcurrentBitmap bitmap, int bit)
  159. {
  160. (address, size) = PageAlign(address, size);
  161. lock (TrackingLock)
  162. {
  163. RegionHandle handle = new RegionHandle(this, address, size, bitmap, bit, _memoryManager.IsRangeMapped(address, size));
  164. return handle;
  165. }
  166. }
  167. /// <summary>
  168. /// Signal that a virtual memory event happened at the given location (one byte).
  169. /// </summary>
  170. /// <param name="address">Virtual address accessed</param>
  171. /// <param name="write">Whether the address was written to or read</param>
  172. /// <returns>True if the event triggered any tracking regions, false otherwise</returns>
  173. public bool VirtualMemoryEventTracking(ulong address, bool write)
  174. {
  175. return VirtualMemoryEvent(address, 1, write);
  176. }
  177. /// <summary>
  178. /// Signal that a virtual memory event happened at the given location.
  179. /// This can be flagged as a precise event, which will avoid reprotection and call special handlers if possible.
  180. /// A precise event has an exact address and size, rather than triggering on page granularity.
  181. /// </summary>
  182. /// <param name="address">Virtual address accessed</param>
  183. /// <param name="size">Size of the region affected in bytes</param>
  184. /// <param name="write">Whether the region was written to or read</param>
  185. /// <param name="precise">True if the access is precise, false otherwise</param>
  186. /// <returns>True if the event triggered any tracking regions, false otherwise</returns>
  187. public bool VirtualMemoryEvent(ulong address, ulong size, bool write, bool precise = false)
  188. {
  189. // Look up the virtual region using the region list.
  190. // Signal up the chain to relevant handles.
  191. bool shouldThrow = false;
  192. lock (TrackingLock)
  193. {
  194. ref var overlaps = ref ThreadStaticArray<VirtualRegion>.Get();
  195. int count = _virtualRegions.FindOverlapsNonOverlapping(address, size, ref overlaps);
  196. if (count == 0 && !precise)
  197. {
  198. if (_memoryManager.IsRangeMapped(address, size))
  199. {
  200. // TODO: There is currently the possibility that a page can be protected after its virtual region is removed.
  201. // This code handles that case when it happens, but it would be better to find out how this happens.
  202. _memoryManager.TrackingReprotect(address & ~(ulong)(_pageSize - 1), (ulong)_pageSize, MemoryPermission.ReadAndWrite);
  203. return true; // This memory _should_ be mapped, so we need to try again.
  204. }
  205. else
  206. {
  207. shouldThrow = true;
  208. }
  209. }
  210. else
  211. {
  212. for (int i = 0; i < count; i++)
  213. {
  214. VirtualRegion region = overlaps[i];
  215. if (precise)
  216. {
  217. region.SignalPrecise(address, size, write);
  218. }
  219. else
  220. {
  221. region.Signal(address, size, write);
  222. }
  223. }
  224. }
  225. }
  226. if (shouldThrow)
  227. {
  228. _invalidAccessHandler?.Invoke(address);
  229. // We can't continue - it's impossible to remove protection from the page.
  230. // Even if the access handler wants us to continue, we wouldn't be able to.
  231. throw new InvalidMemoryRegionException();
  232. }
  233. return true;
  234. }
  235. /// <summary>
  236. /// Reprotect a given virtual region. The virtual memory manager will handle this.
  237. /// </summary>
  238. /// <param name="region">Region to reprotect</param>
  239. /// <param name="permission">Memory permission to protect with</param>
  240. internal void ProtectVirtualRegion(VirtualRegion region, MemoryPermission permission)
  241. {
  242. _memoryManager.TrackingReprotect(region.Address, region.Size, permission);
  243. }
  244. /// <summary>
  245. /// Returns the number of virtual regions currently being tracked.
  246. /// Useful for tests and metrics.
  247. /// </summary>
  248. /// <returns>The number of virtual regions</returns>
  249. public int GetRegionCount()
  250. {
  251. lock (TrackingLock)
  252. {
  253. return _virtualRegions.Count;
  254. }
  255. }
  256. }
  257. }