MemoryTracking.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  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. /// 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. /// This can be flagged as a precise event, which will avoid reprotection and call special handlers if possible.
  163. /// A precise event has an exact address and size, rather than triggering on page granularity.
  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. /// <param name="precise">True if the access is precise, false otherwise</param>
  169. /// <returns>True if the event triggered any tracking regions, false otherwise</returns>
  170. public bool VirtualMemoryEvent(ulong address, ulong size, bool write, bool precise = false)
  171. {
  172. // Look up the virtual region using the region list.
  173. // Signal up the chain to relevant handles.
  174. bool shouldThrow = false;
  175. lock (TrackingLock)
  176. {
  177. ref var overlaps = ref ThreadStaticArray<VirtualRegion>.Get();
  178. int count = _virtualRegions.FindOverlapsNonOverlapping(address, size, ref overlaps);
  179. if (count == 0 && !precise)
  180. {
  181. if (_memoryManager.IsRangeMapped(address, size))
  182. {
  183. // TODO: There is currently the possibility that a page can be protected after its virtual region is removed.
  184. // This code handles that case when it happens, but it would be better to find out how this happens.
  185. _memoryManager.TrackingReprotect(address & ~(ulong)(_pageSize - 1), (ulong)_pageSize, MemoryPermission.ReadAndWrite);
  186. return true; // This memory _should_ be mapped, so we need to try again.
  187. }
  188. else
  189. {
  190. shouldThrow = true;
  191. }
  192. }
  193. else
  194. {
  195. for (int i = 0; i < count; i++)
  196. {
  197. VirtualRegion region = overlaps[i];
  198. if (precise)
  199. {
  200. region.SignalPrecise(address, size, write);
  201. }
  202. else
  203. {
  204. region.Signal(address, size, write);
  205. }
  206. }
  207. }
  208. }
  209. if (shouldThrow)
  210. {
  211. _invalidAccessHandler?.Invoke(address);
  212. // We can't continue - it's impossible to remove protection from the page.
  213. // Even if the access handler wants us to continue, we wouldn't be able to.
  214. throw new InvalidMemoryRegionException();
  215. }
  216. return true;
  217. }
  218. /// <summary>
  219. /// Reprotect a given virtual region. The virtual memory manager will handle this.
  220. /// </summary>
  221. /// <param name="region">Region to reprotect</param>
  222. /// <param name="permission">Memory permission to protect with</param>
  223. internal void ProtectVirtualRegion(VirtualRegion region, MemoryPermission permission)
  224. {
  225. _memoryManager.TrackingReprotect(region.Address, region.Size, permission);
  226. }
  227. /// <summary>
  228. /// Returns the number of virtual regions currently being tracked.
  229. /// Useful for tests and metrics.
  230. /// </summary>
  231. /// <returns>The number of virtual regions</returns>
  232. public int GetRegionCount()
  233. {
  234. lock (TrackingLock)
  235. {
  236. return _virtualRegions.Count;
  237. }
  238. }
  239. }
  240. }