MemoryTracking.cs 14 KB

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