MemoryTracking.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  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. region.UpdateProtection();
  67. }
  68. }
  69. }
  70. /// <summary>
  71. /// Indicate that a virtual region has been unmapped.
  72. /// Should be called after 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 recalculate their physical regions
  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.RecalculatePhysicalChildren();
  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. /// Get a list of physical regions that a virtual region covers.
  105. /// Note that this becomes outdated if the virtual or physical regions are unmapped or remapped.
  106. /// </summary>
  107. /// <param name="va">Virtual memory address</param>
  108. /// <param name="size">Size of the virtual region</param>
  109. /// <returns>A list of physical regions the virtual region covers</returns>
  110. internal List<PhysicalRegion> GetPhysicalRegionsForVirtual(ulong va, ulong size)
  111. {
  112. List<PhysicalRegion> result = new List<PhysicalRegion>();
  113. // Get a list of physical regions for this virtual region, from our injected virtual mapping function.
  114. (ulong Address, ulong Size)[] physicalRegions = _memoryManager.GetPhysicalRegions(va, size);
  115. if (physicalRegions != null)
  116. {
  117. foreach (var region in physicalRegions)
  118. {
  119. _physicalRegions.GetOrAddRegions(result, region.Address, region.Size, (pa, size) => new PhysicalRegion(this, pa, size));
  120. }
  121. }
  122. return result;
  123. }
  124. /// <summary>
  125. /// Remove a virtual region from the range list. This assumes that the lock has been acquired.
  126. /// </summary>
  127. /// <param name="region">Region to remove</param>
  128. internal void RemoveVirtual(VirtualRegion region)
  129. {
  130. _virtualRegions.Remove(region);
  131. }
  132. /// <summary>
  133. /// Remove a physical region from the range list. This assumes that the lock has been acquired.
  134. /// </summary>
  135. /// <param name="region">Region to remove</param>
  136. internal void RemovePhysical(PhysicalRegion region)
  137. {
  138. _physicalRegions.Remove(region);
  139. }
  140. /// <summary>
  141. /// Obtains a memory tracking handle for the given virtual region, with a specified granularity. This should be disposed when finished with.
  142. /// </summary>
  143. /// <param name="address">CPU virtual address of the region</param>
  144. /// <param name="size">Size of the region</param>
  145. /// <param name="granularity">Desired granularity of write tracking</param>
  146. /// <returns>The memory tracking handle</returns>
  147. public MultiRegionHandle BeginGranularTracking(ulong address, ulong size, ulong granularity)
  148. {
  149. (address, size) = PageAlign(address, size);
  150. return new MultiRegionHandle(this, address, size, granularity);
  151. }
  152. /// <summary>
  153. /// Obtains a smart memory tracking handle for the given virtual region, with a specified granularity. This should be disposed when finished with.
  154. /// </summary>
  155. /// <param name="address">CPU virtual address of the region</param>
  156. /// <param name="size">Size of the region</param>
  157. /// <param name="granularity">Desired granularity of write tracking</param>
  158. /// <returns>The memory tracking handle</returns>
  159. public SmartMultiRegionHandle BeginSmartGranularTracking(ulong address, ulong size, ulong granularity)
  160. {
  161. (address, size) = PageAlign(address, size);
  162. return new SmartMultiRegionHandle(this, address, size, granularity);
  163. }
  164. /// <summary>
  165. /// Obtains a memory tracking handle for the given virtual region. This should be disposed when finished with.
  166. /// </summary>
  167. /// <param name="address">CPU virtual address of the region</param>
  168. /// <param name="size">Size of the region</param>
  169. /// <returns>The memory tracking handle</returns>
  170. public RegionHandle BeginTracking(ulong address, ulong size)
  171. {
  172. (address, size) = PageAlign(address, size);
  173. lock (TrackingLock)
  174. {
  175. RegionHandle handle = new RegionHandle(this, address, size, _memoryManager.IsRangeMapped(address, size));
  176. return handle;
  177. }
  178. }
  179. /// <summary>
  180. /// Signal that a physical memory event happened at the given location.
  181. /// </summary>
  182. /// <param name="address">Physical address accessed</param>
  183. /// <param name="write">Whether the region was written to or read</param>
  184. /// <returns>True if the event triggered any tracking regions, false otherwise</returns>
  185. public bool PhysicalMemoryEvent(ulong address, bool write)
  186. {
  187. // Look up the physical region using the region list.
  188. // Signal up the chain to relevant handles.
  189. lock (TrackingLock)
  190. {
  191. var results = _physicalResults;
  192. int count = _physicalRegions.FindOverlapsNonOverlapping(address, 1, ref results); // TODO: get/use the actual access size?
  193. if (count == 0)
  194. {
  195. _block.Reprotect(address & ~(ulong)(_pageSize - 1), (ulong)_pageSize, MemoryPermission.ReadAndWrite);
  196. return false; // We can't handle this - unprotect and return.
  197. }
  198. for (int i = 0; i < count; i++)
  199. {
  200. PhysicalRegion region = results[i];
  201. region.Signal(address, 1, write);
  202. }
  203. }
  204. return true;
  205. }
  206. /// <summary>
  207. /// Signal that a virtual memory event happened at the given location (one byte).
  208. /// </summary>
  209. /// <param name="address">Virtual address accessed</param>
  210. /// <param name="write">Whether the address was written to or read</param>
  211. /// <returns>True if the event triggered any tracking regions, false otherwise</returns>
  212. public bool VirtualMemoryEventTracking(ulong address, bool write)
  213. {
  214. return VirtualMemoryEvent(address, 1, write);
  215. }
  216. /// <summary>
  217. /// Signal that a virtual memory event happened at the given location.
  218. /// </summary>
  219. /// <param name="address">Virtual address accessed</param>
  220. /// <param name="size">Size of the region affected in bytes</param>
  221. /// <param name="write">Whether the region was written to or read</param>
  222. /// <returns>True if the event triggered any tracking regions, false otherwise</returns>
  223. public bool VirtualMemoryEvent(ulong address, ulong size, bool write)
  224. {
  225. // Look up the virtual region using the region list.
  226. // Signal up the chain to relevant handles.
  227. lock (TrackingLock)
  228. {
  229. var results = _virtualResults;
  230. int count = _virtualRegions.FindOverlapsNonOverlapping(address, size, ref results);
  231. if (count == 0)
  232. {
  233. _memoryManager.TrackingReprotect(address & ~(ulong)(_pageSize - 1), (ulong)_pageSize, MemoryPermission.ReadAndWrite);
  234. return false; // We can't handle this - it's probably a real invalid access.
  235. }
  236. for (int i = 0; i < count; i++)
  237. {
  238. VirtualRegion region = results[i];
  239. region.Signal(address, size, write);
  240. }
  241. }
  242. return true;
  243. }
  244. /// <summary>
  245. /// Reprotect a given physical region, if enabled. This is protected on the memory block provided during initialization.
  246. /// </summary>
  247. /// <param name="region">Region to reprotect</param>
  248. /// <param name="permission">Memory permission to protect with</param>
  249. internal void ProtectPhysicalRegion(PhysicalRegion region, MemoryPermission permission)
  250. {
  251. if (EnablePhysicalProtection)
  252. {
  253. _block.Reprotect(region.Address, region.Size, permission);
  254. }
  255. }
  256. /// <summary>
  257. /// Reprotect a given virtual region. The virtual memory manager will handle this.
  258. /// </summary>
  259. /// <param name="region">Region to reprotect</param>
  260. /// <param name="permission">Memory permission to protect with</param>
  261. internal void ProtectVirtualRegion(VirtualRegion region, MemoryPermission permission)
  262. {
  263. _memoryManager.TrackingReprotect(region.Address, region.Size, permission);
  264. }
  265. /// <summary>
  266. /// Returns the number of virtual and physical regions currently being tracked.
  267. /// Useful for tests and metrics.
  268. /// </summary>
  269. /// <returns>The number of virtual regions, and the number of physical regions</returns>
  270. public (int VirtualCount, int PhysicalCount) GetRegionCounts()
  271. {
  272. lock (TrackingLock)
  273. {
  274. return (_virtualRegions.Count, _physicalRegions.Count);
  275. }
  276. }
  277. }
  278. }