MemoryTracking.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  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. private readonly NonOverlappingRangeList<PhysicalRegion> _physicalRegions;
  15. // Only use these from within the lock.
  16. private readonly VirtualRegion[] _virtualResults = new VirtualRegion[10];
  17. private readonly PhysicalRegion[] _physicalResults = new PhysicalRegion[10];
  18. private readonly int _pageSize;
  19. /// <summary>
  20. /// This lock must be obtained when traversing or updating the region-handle hierarchy.
  21. /// It is not required when reading dirty flags.
  22. /// </summary>
  23. internal object TrackingLock = new object();
  24. public bool EnablePhysicalProtection { get; set; }
  25. /// <summary>
  26. /// Create a new tracking structure for the given "physical" memory block,
  27. /// with a given "virtual" memory manager that will provide mappings and virtual memory protection.
  28. /// </summary>
  29. /// <param name="memoryManager">Virtual memory manager</param>
  30. /// <param name="block">Physical memory block</param>
  31. /// <param name="pageSize">Page size of the virtual memory space</param>
  32. public MemoryTracking(IVirtualMemoryManager memoryManager, MemoryBlock block, int pageSize)
  33. {
  34. _memoryManager = memoryManager;
  35. _block = block;
  36. _pageSize = pageSize;
  37. _virtualRegions = new NonOverlappingRangeList<VirtualRegion>();
  38. _physicalRegions = new NonOverlappingRangeList<PhysicalRegion>();
  39. }
  40. private (ulong address, ulong size) PageAlign(ulong address, ulong size)
  41. {
  42. ulong pageMask = (ulong)_pageSize - 1;
  43. ulong rA = address & ~pageMask;
  44. ulong rS = ((address + size + pageMask) & ~pageMask) - rA;
  45. return (rA, rS);
  46. }
  47. /// <summary>
  48. /// Indicate that a virtual region has been mapped, and which physical region it has been mapped to.
  49. /// Should be called after the mapping is complete.
  50. /// </summary>
  51. /// <param name="va">Virtual memory address</param>
  52. /// <param name="pa">Physical memory address</param>
  53. /// <param name="size">Size to be mapped</param>
  54. public void Map(ulong va, ulong pa, ulong size)
  55. {
  56. // A mapping may mean we need to re-evaluate each VirtualRegion's affected area.
  57. // Find all handles that overlap with the range, we need to recalculate their physical regions
  58. lock (TrackingLock)
  59. {
  60. var results = _virtualResults;
  61. int count = _virtualRegions.FindOverlapsNonOverlapping(va, size, ref results);
  62. for (int i = 0; i < count; i++)
  63. {
  64. VirtualRegion region = results[i];
  65. region.RecalculatePhysicalChildren();
  66. }
  67. }
  68. }
  69. /// <summary>
  70. /// Indicate that a virtual region has been unmapped.
  71. /// Should be called after 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 recalculate their physical regions
  79. lock (TrackingLock)
  80. {
  81. var results = _virtualResults;
  82. int count = _virtualRegions.FindOverlapsNonOverlapping(va, size, ref results);
  83. for (int i = 0; i < count; i++)
  84. {
  85. VirtualRegion region = results[i];
  86. region.RecalculatePhysicalChildren();
  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. /// Get a list of physical regions that a virtual region covers.
  104. /// Note that this becomes outdated if the virtual or physical regions are unmapped or remapped.
  105. /// </summary>
  106. /// <param name="va">Virtual memory address</param>
  107. /// <param name="size">Size of the virtual region</param>
  108. /// <returns>A list of physical regions the virtual region covers</returns>
  109. internal List<PhysicalRegion> GetPhysicalRegionsForVirtual(ulong va, ulong size)
  110. {
  111. List<PhysicalRegion> result = new List<PhysicalRegion>();
  112. // Get a list of physical regions for this virtual region, from our injected virtual mapping function.
  113. (ulong Address, ulong Size)[] physicalRegions = _memoryManager.GetPhysicalRegions(va, size);
  114. if (physicalRegions != null)
  115. {
  116. foreach (var region in physicalRegions)
  117. {
  118. _physicalRegions.GetOrAddRegions(result, region.Address, region.Size, (pa, size) => new PhysicalRegion(this, pa, size));
  119. }
  120. }
  121. return result;
  122. }
  123. /// <summary>
  124. /// Remove a virtual region from the range list. This assumes that the lock has been acquired.
  125. /// </summary>
  126. /// <param name="region">Region to remove</param>
  127. internal void RemoveVirtual(VirtualRegion region)
  128. {
  129. _virtualRegions.Remove(region);
  130. }
  131. /// <summary>
  132. /// Remove a physical region from the range list. This assumes that the lock has been acquired.
  133. /// </summary>
  134. /// <param name="region">Region to remove</param>
  135. internal void RemovePhysical(PhysicalRegion region)
  136. {
  137. _physicalRegions.Remove(region);
  138. }
  139. /// <summary>
  140. /// Obtains a memory tracking handle for the given virtual region, with a specified granularity. This should be disposed when finished with.
  141. /// </summary>
  142. /// <param name="address">CPU virtual address of the region</param>
  143. /// <param name="size">Size of the region</param>
  144. /// <param name="granularity">Desired granularity of write tracking</param>
  145. /// <returns>The memory tracking handle</returns>
  146. public MultiRegionHandle BeginGranularTracking(ulong address, ulong size, ulong granularity)
  147. {
  148. (address, size) = PageAlign(address, size);
  149. return new MultiRegionHandle(this, address, size, granularity);
  150. }
  151. /// <summary>
  152. /// Obtains a smart memory tracking handle for the given virtual region, with a specified granularity. This should be disposed when finished with.
  153. /// </summary>
  154. /// <param name="address">CPU virtual address of the region</param>
  155. /// <param name="size">Size of the region</param>
  156. /// <param name="granularity">Desired granularity of write tracking</param>
  157. /// <returns>The memory tracking handle</returns>
  158. public SmartMultiRegionHandle BeginSmartGranularTracking(ulong address, ulong size, ulong granularity)
  159. {
  160. (address, size) = PageAlign(address, size);
  161. return new SmartMultiRegionHandle(this, address, size, granularity);
  162. }
  163. /// <summary>
  164. /// Obtains a memory tracking handle for the given virtual region. This should be disposed when finished with.
  165. /// </summary>
  166. /// <param name="address">CPU virtual address of the region</param>
  167. /// <param name="size">Size of the region</param>
  168. /// <returns>The memory tracking handle</returns>
  169. public RegionHandle BeginTracking(ulong address, ulong size)
  170. {
  171. (address, size) = PageAlign(address, size);
  172. lock (TrackingLock)
  173. {
  174. RegionHandle handle = new RegionHandle(this, address, size);
  175. return handle;
  176. }
  177. }
  178. /// <summary>
  179. /// Signal that a physical memory event happened at the given location.
  180. /// </summary>
  181. /// <param name="address">Physical address accessed</param>
  182. /// <param name="write">Whether the region was written to or read</param>
  183. /// <returns>True if the event triggered any tracking regions, false otherwise</returns>
  184. public bool PhysicalMemoryEvent(ulong address, bool write)
  185. {
  186. // Look up the physical region using the region list.
  187. // Signal up the chain to relevant handles.
  188. lock (TrackingLock)
  189. {
  190. var results = _physicalResults;
  191. int count = _physicalRegions.FindOverlapsNonOverlapping(address, 1, ref results); // TODO: get/use the actual access size?
  192. if (count == 0)
  193. {
  194. _block.Reprotect(address & ~(ulong)(_pageSize - 1), (ulong)_pageSize, MemoryPermission.ReadAndWrite);
  195. return false; // We can't handle this - unprotect and return.
  196. }
  197. for (int i = 0; i < count; i++)
  198. {
  199. PhysicalRegion region = results[i];
  200. region.Signal(address, 1, write);
  201. }
  202. }
  203. return true;
  204. }
  205. /// <summary>
  206. /// Signal that a virtual memory event happened at the given location (one byte).
  207. /// </summary>
  208. /// <param name="address">Virtual address accessed</param>
  209. /// <param name="write">Whether the address was written to or read</param>
  210. /// <returns>True if the event triggered any tracking regions, false otherwise</returns>
  211. public bool VirtualMemoryEventTracking(ulong address, bool write)
  212. {
  213. return VirtualMemoryEvent(address, 1, write);
  214. }
  215. /// <summary>
  216. /// Signal that a virtual memory event happened at the given location.
  217. /// </summary>
  218. /// <param name="address">Virtual address accessed</param>
  219. /// <param name="size">Size of the region affected in bytes</param>
  220. /// <param name="write">Whether the region was written to or read</param>
  221. /// <returns>True if the event triggered any tracking regions, false otherwise</returns>
  222. public bool VirtualMemoryEvent(ulong address, ulong size, bool write)
  223. {
  224. // Look up the virtual region using the region list.
  225. // Signal up the chain to relevant handles.
  226. lock (TrackingLock)
  227. {
  228. var results = _virtualResults;
  229. int count = _virtualRegions.FindOverlapsNonOverlapping(address, size, ref results);
  230. if (count == 0)
  231. {
  232. _memoryManager.TrackingReprotect(address & ~(ulong)(_pageSize - 1), (ulong)_pageSize, MemoryPermission.ReadAndWrite);
  233. return false; // We can't handle this - it's probably a real invalid access.
  234. }
  235. for (int i = 0; i < count; i++)
  236. {
  237. VirtualRegion region = results[i];
  238. region.Signal(address, size, write);
  239. }
  240. }
  241. return true;
  242. }
  243. /// <summary>
  244. /// Reprotect a given physical region, if enabled. This is protected on the memory block provided during initialization.
  245. /// </summary>
  246. /// <param name="region">Region to reprotect</param>
  247. /// <param name="permission">Memory permission to protect with</param>
  248. internal void ProtectPhysicalRegion(PhysicalRegion region, MemoryPermission permission)
  249. {
  250. if (EnablePhysicalProtection)
  251. {
  252. _block.Reprotect(region.Address, region.Size, permission);
  253. }
  254. }
  255. /// <summary>
  256. /// Reprotect a given virtual region. The virtual memory manager will handle this.
  257. /// </summary>
  258. /// <param name="region">Region to reprotect</param>
  259. /// <param name="permission">Memory permission to protect with</param>
  260. internal void ProtectVirtualRegion(VirtualRegion region, MemoryPermission permission)
  261. {
  262. _memoryManager.TrackingReprotect(region.Address, region.Size, permission);
  263. }
  264. /// <summary>
  265. /// Returns the number of virtual and physical regions currently being tracked.
  266. /// Useful for tests and metrics.
  267. /// </summary>
  268. /// <returns>The number of virtual regions, and the number of physical regions</returns>
  269. public (int VirtualCount, int PhysicalCount) GetRegionCounts()
  270. {
  271. lock (TrackingLock)
  272. {
  273. return (_virtualRegions.Count, _physicalRegions.Count);
  274. }
  275. }
  276. }
  277. }