MemoryTracking.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. using Ryujinx.Common.Pools;
  2. using Ryujinx.Memory.Range;
  3. using System;
  4. using System.Collections.Generic;
  5. namespace Ryujinx.Memory.Tracking
  6. {
  7. /// <summary>
  8. /// Manages memory tracking for a given virutal/physical memory block.
  9. /// </summary>
  10. public class MemoryTracking
  11. {
  12. private readonly IVirtualMemoryManager _memoryManager;
  13. private readonly InvalidAccessHandler _invalidAccessHandler;
  14. // Only use these from within the lock.
  15. private readonly NonOverlappingRangeList<VirtualRegion> _virtualRegions;
  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. ref var overlaps = ref ThreadStaticArray<VirtualRegion>.Get();
  56. int count = _virtualRegions.FindOverlapsNonOverlapping(va, size, ref overlaps);
  57. for (int i = 0; i < count; i++)
  58. {
  59. VirtualRegion region = overlaps[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. ref var overlaps = ref ThreadStaticArray<VirtualRegion>.Get();
  83. int count = _virtualRegions.FindOverlapsNonOverlapping(va, size, ref overlaps);
  84. for (int i = 0; i < count; i++)
  85. {
  86. VirtualRegion region = overlaps[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="handles">Handles to inherit state from or reuse. When none are present, provide null</param>
  117. /// <param name="granularity">Desired granularity of write tracking</param>
  118. /// <returns>The memory tracking handle</returns>
  119. public MultiRegionHandle BeginGranularTracking(ulong address, ulong size, IEnumerable<IRegionHandle> handles, ulong granularity)
  120. {
  121. (address, size) = PageAlign(address, size);
  122. return new MultiRegionHandle(this, address, size, handles, granularity);
  123. }
  124. /// <summary>
  125. /// Obtains a smart memory tracking handle for the given virtual region, with a specified granularity. This should be disposed when finished with.
  126. /// </summary>
  127. /// <param name="address">CPU virtual address of the region</param>
  128. /// <param name="size">Size of the region</param>
  129. /// <param name="granularity">Desired granularity of write tracking</param>
  130. /// <returns>The memory tracking handle</returns>
  131. public SmartMultiRegionHandle BeginSmartGranularTracking(ulong address, ulong size, ulong granularity)
  132. {
  133. (address, size) = PageAlign(address, size);
  134. return new SmartMultiRegionHandle(this, address, size, granularity);
  135. }
  136. /// <summary>
  137. /// Obtains a memory tracking handle for the given virtual region. This should be disposed when finished with.
  138. /// </summary>
  139. /// <param name="address">CPU virtual address of the region</param>
  140. /// <param name="size">Size of the region</param>
  141. /// <returns>The memory tracking handle</returns>
  142. public RegionHandle BeginTracking(ulong address, ulong size)
  143. {
  144. (address, size) = PageAlign(address, size);
  145. lock (TrackingLock)
  146. {
  147. RegionHandle handle = new RegionHandle(this, address, size, _memoryManager.IsRangeMapped(address, size));
  148. return handle;
  149. }
  150. }
  151. /// <summary>
  152. /// Signal that a virtual memory event happened at the given location (one byte).
  153. /// </summary>
  154. /// <param name="address">Virtual address accessed</param>
  155. /// <param name="write">Whether the address was written to or read</param>
  156. /// <returns>True if the event triggered any tracking regions, false otherwise</returns>
  157. public bool VirtualMemoryEventTracking(ulong address, bool write)
  158. {
  159. return VirtualMemoryEvent(address, 1, write);
  160. }
  161. /// <summary>
  162. /// Signal that a virtual memory event happened at the given location.
  163. /// This can be flagged as a precise event, which will avoid reprotection and call special handlers if possible.
  164. /// A precise event has an exact address and size, rather than triggering on page granularity.
  165. /// </summary>
  166. /// <param name="address">Virtual address accessed</param>
  167. /// <param name="size">Size of the region affected in bytes</param>
  168. /// <param name="write">Whether the region was written to or read</param>
  169. /// <param name="precise">True if the access is precise, false otherwise</param>
  170. /// <returns>True if the event triggered any tracking regions, false otherwise</returns>
  171. public bool VirtualMemoryEvent(ulong address, ulong size, bool write, bool precise = false)
  172. {
  173. // Look up the virtual region using the region list.
  174. // Signal up the chain to relevant handles.
  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.IsMapped(address))
  182. {
  183. _invalidAccessHandler?.Invoke(address);
  184. // We can't continue - it's impossible to remove protection from the page.
  185. // Even if the access handler wants us to continue, we wouldn't be able to.
  186. throw new InvalidMemoryRegionException();
  187. }
  188. _memoryManager.TrackingReprotect(address & ~(ulong)(_pageSize - 1), (ulong)_pageSize, MemoryPermission.ReadAndWrite);
  189. return false; // We can't handle this - it's probably a real invalid access.
  190. }
  191. for (int i = 0; i < count; i++)
  192. {
  193. VirtualRegion region = overlaps[i];
  194. if (precise)
  195. {
  196. region.SignalPrecise(address, size, write);
  197. }
  198. else
  199. {
  200. region.Signal(address, size, write);
  201. }
  202. }
  203. }
  204. return true;
  205. }
  206. /// <summary>
  207. /// Reprotect a given virtual region. The virtual memory manager will handle this.
  208. /// </summary>
  209. /// <param name="region">Region to reprotect</param>
  210. /// <param name="permission">Memory permission to protect with</param>
  211. internal void ProtectVirtualRegion(VirtualRegion region, MemoryPermission permission)
  212. {
  213. _memoryManager.TrackingReprotect(region.Address, region.Size, permission);
  214. }
  215. /// <summary>
  216. /// Returns the number of virtual regions currently being tracked.
  217. /// Useful for tests and metrics.
  218. /// </summary>
  219. /// <returns>The number of virtual regions</returns>
  220. public int GetRegionCount()
  221. {
  222. lock (TrackingLock)
  223. {
  224. return _virtualRegions.Count;
  225. }
  226. }
  227. }
  228. }