RegionHandle.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Threading;
  5. namespace Ryujinx.Memory.Tracking
  6. {
  7. /// <summary>
  8. /// A tracking handle for a given region of virtual memory. The Dirty flag is updated whenever any changes are made,
  9. /// and an action can be performed when the region is read to or written from.
  10. /// </summary>
  11. public class RegionHandle : IRegionHandle
  12. {
  13. /// <summary>
  14. /// If more than this number of checks have been performed on a dirty flag since its last reprotect,
  15. /// then it is dirtied infrequently.
  16. /// </summary>
  17. private static int CheckCountForInfrequent = 3;
  18. /// <summary>
  19. /// Number of frequent dirty/consume in a row to make this handle volatile.
  20. /// </summary>
  21. private static int VolatileThreshold = 5;
  22. public bool Dirty
  23. {
  24. get
  25. {
  26. return Bitmap.IsSet(DirtyBit);
  27. }
  28. protected set
  29. {
  30. Bitmap.Set(DirtyBit, value);
  31. }
  32. }
  33. internal int SequenceNumber { get; set; }
  34. public bool Unmapped { get; private set; }
  35. public ulong Address { get; }
  36. public ulong Size { get; }
  37. public ulong EndAddress { get; }
  38. public ulong RealAddress { get; }
  39. public ulong RealSize { get; }
  40. public ulong RealEndAddress { get; }
  41. internal IMultiRegionHandle Parent { get; set; }
  42. private event Action _onDirty;
  43. private object _preActionLock = new object();
  44. private RegionSignal _preAction; // Action to perform before a read or write. This will block the memory access.
  45. private PreciseRegionSignal _preciseAction; // Action to perform on a precise read or write.
  46. private readonly List<VirtualRegion> _regions;
  47. private readonly MemoryTracking _tracking;
  48. private bool _disposed;
  49. private int _checkCount = 0;
  50. private int _volatileCount = 0;
  51. private bool _volatile;
  52. internal MemoryPermission RequiredPermission
  53. {
  54. get
  55. {
  56. // If this is unmapped, allow reprotecting as RW as it can't be dirtied.
  57. // This is required for the partial unmap cases where part of the data are still being accessed.
  58. if (Unmapped)
  59. {
  60. return MemoryPermission.ReadAndWrite;
  61. }
  62. if (_preAction != null)
  63. {
  64. return MemoryPermission.None;
  65. }
  66. return Dirty ? MemoryPermission.ReadAndWrite : MemoryPermission.Read;
  67. }
  68. }
  69. internal RegionSignal PreAction => _preAction;
  70. internal ConcurrentBitmap Bitmap;
  71. internal int DirtyBit;
  72. /// <summary>
  73. /// Create a new bitmap backed region handle. The handle is registered with the given tracking object,
  74. /// and will be notified of any changes to the specified region.
  75. /// </summary>
  76. /// <param name="tracking">Tracking object for the target memory block</param>
  77. /// <param name="address">Virtual address of the region to track</param>
  78. /// <param name="size">Size of the region to track</param>
  79. /// <param name="realAddress">The real, unaligned address of the handle</param>
  80. /// <param name="realSize">The real, unaligned size of the handle</param>
  81. /// <param name="bitmap">The bitmap the dirty flag for this handle is stored in</param>
  82. /// <param name="bit">The bit index representing the dirty flag for this handle</param>
  83. /// <param name="mapped">True if the region handle starts mapped</param>
  84. internal RegionHandle(MemoryTracking tracking, ulong address, ulong size, ulong realAddress, ulong realSize, ConcurrentBitmap bitmap, int bit, bool mapped = true)
  85. {
  86. Bitmap = bitmap;
  87. DirtyBit = bit;
  88. Dirty = mapped;
  89. Unmapped = !mapped;
  90. Address = address;
  91. Size = size;
  92. EndAddress = address + size;
  93. RealAddress = realAddress;
  94. RealSize = realSize;
  95. RealEndAddress = realAddress + realSize;
  96. _tracking = tracking;
  97. _regions = tracking.GetVirtualRegionsForHandle(address, size);
  98. foreach (var region in _regions)
  99. {
  100. region.Handles.Add(this);
  101. }
  102. }
  103. /// <summary>
  104. /// Create a new region handle. The handle is registered with the given tracking object,
  105. /// and will be notified of any changes to the specified region.
  106. /// </summary>
  107. /// <param name="tracking">Tracking object for the target memory block</param>
  108. /// <param name="address">Virtual address of the region to track</param>
  109. /// <param name="size">Size of the region to track</param>
  110. /// <param name="realAddress">The real, unaligned address of the handle</param>
  111. /// <param name="realSize">The real, unaligned size of the handle</param>
  112. /// <param name="mapped">True if the region handle starts mapped</param>
  113. internal RegionHandle(MemoryTracking tracking, ulong address, ulong size, ulong realAddress, ulong realSize, bool mapped = true)
  114. {
  115. Bitmap = new ConcurrentBitmap(1, mapped);
  116. Unmapped = !mapped;
  117. Address = address;
  118. Size = size;
  119. EndAddress = address + size;
  120. RealAddress = realAddress;
  121. RealSize = realSize;
  122. RealEndAddress = realAddress + realSize;
  123. _tracking = tracking;
  124. _regions = tracking.GetVirtualRegionsForHandle(address, size);
  125. foreach (var region in _regions)
  126. {
  127. region.Handles.Add(this);
  128. }
  129. }
  130. /// <summary>
  131. /// Replace the bitmap and bit index used to track dirty state.
  132. /// </summary>
  133. /// <remarks>
  134. /// The tracking lock should be held when this is called, to ensure neither bitmap is modified.
  135. /// </remarks>
  136. /// <param name="bitmap">The bitmap the dirty flag for this handle is stored in</param>
  137. /// <param name="bit">The bit index representing the dirty flag for this handle</param>
  138. internal void ReplaceBitmap(ConcurrentBitmap bitmap, int bit)
  139. {
  140. // Assumes the tracking lock is held, so nothing else can signal right now.
  141. var oldBitmap = Bitmap;
  142. var oldBit = DirtyBit;
  143. bitmap.Set(bit, Dirty);
  144. Bitmap = bitmap;
  145. DirtyBit = bit;
  146. Dirty |= oldBitmap.IsSet(oldBit);
  147. }
  148. /// <summary>
  149. /// Clear the volatile state of this handle.
  150. /// </summary>
  151. private void ClearVolatile()
  152. {
  153. _volatileCount = 0;
  154. _volatile = false;
  155. }
  156. /// <summary>
  157. /// Check if this handle is dirty, or if it is volatile. (changes very often)
  158. /// </summary>
  159. /// <returns>True if the handle is dirty or volatile, false otherwise</returns>
  160. public bool DirtyOrVolatile()
  161. {
  162. _checkCount++;
  163. return _volatile || Dirty;
  164. }
  165. /// <summary>
  166. /// Signal that a memory action occurred within this handle's virtual regions.
  167. /// </summary>
  168. /// <param name="address">Address accessed</param>
  169. /// <param name="size">Size of the region affected in bytes</param>
  170. /// <param name="write">Whether the region was written to or read</param>
  171. /// <param name="handleIterable">Reference to the handles being iterated, in case the list needs to be copied</param>
  172. internal void Signal(ulong address, ulong size, bool write, ref IList<RegionHandle> handleIterable)
  173. {
  174. // If this handle was already unmapped (even if just partially),
  175. // then we have nothing to do until it is mapped again.
  176. // The pre-action should be still consumed to avoid flushing on remap.
  177. if (Unmapped)
  178. {
  179. Interlocked.Exchange(ref _preAction, null);
  180. return;
  181. }
  182. if (_preAction != null)
  183. {
  184. // Limit the range to within this handle.
  185. ulong maxAddress = Math.Max(address, RealAddress);
  186. ulong minEndAddress = Math.Min(address + size, RealAddress + RealSize);
  187. // Copy the handles list in case it changes when we're out of the lock.
  188. if (handleIterable is List<RegionHandle>)
  189. {
  190. handleIterable = handleIterable.ToArray();
  191. }
  192. // Temporarily release the tracking lock while we're running the action.
  193. Monitor.Exit(_tracking.TrackingLock);
  194. try
  195. {
  196. lock (_preActionLock)
  197. {
  198. _preAction?.Invoke(maxAddress, minEndAddress - maxAddress);
  199. // The action is removed after it returns, to ensure that the null check above succeeds when
  200. // it's still in progress rather than continuing and possibly missing a required data flush.
  201. Interlocked.Exchange(ref _preAction, null);
  202. }
  203. }
  204. finally
  205. {
  206. Monitor.Enter(_tracking.TrackingLock);
  207. }
  208. }
  209. if (write)
  210. {
  211. bool oldDirty = Dirty;
  212. Dirty = true;
  213. if (!oldDirty)
  214. {
  215. _onDirty?.Invoke();
  216. }
  217. Parent?.SignalWrite();
  218. }
  219. }
  220. /// <summary>
  221. /// Signal that a precise memory action occurred within this handle's virtual regions.
  222. /// If there is no precise action, or the action returns false, the normal signal handler will be called.
  223. /// </summary>
  224. /// <param name="address">Address accessed</param>
  225. /// <param name="size">Size of the region affected in bytes</param>
  226. /// <param name="write">Whether the region was written to or read</param>
  227. /// <param name="handleIterable">Reference to the handles being iterated, in case the list needs to be copied</param>
  228. /// <returns>True if a precise action was performed and returned true, false otherwise</returns>
  229. internal bool SignalPrecise(ulong address, ulong size, bool write, ref IList<RegionHandle> handleIterable)
  230. {
  231. if (!Unmapped && _preciseAction != null && _preciseAction(address, size, write))
  232. {
  233. return true;
  234. }
  235. Signal(address, size, write, ref handleIterable);
  236. return false;
  237. }
  238. /// <summary>
  239. /// Force this handle to be dirty, without reprotecting.
  240. /// </summary>
  241. public void ForceDirty()
  242. {
  243. Dirty = true;
  244. }
  245. /// <summary>
  246. /// Consume the dirty flag for this handle, and reprotect so it can be set on the next write.
  247. /// </summary>
  248. /// <param name="asDirty">True if the handle should be reprotected as dirty, rather than have it cleared</param>
  249. /// <param name="consecutiveCheck">True if this reprotect is the result of consecutive dirty checks</param>
  250. public void Reprotect(bool asDirty, bool consecutiveCheck = false)
  251. {
  252. if (_volatile) return;
  253. Dirty = asDirty;
  254. bool protectionChanged = false;
  255. lock (_tracking.TrackingLock)
  256. {
  257. foreach (VirtualRegion region in _regions)
  258. {
  259. protectionChanged |= region.UpdateProtection();
  260. }
  261. }
  262. if (!protectionChanged)
  263. {
  264. // Counteract the check count being incremented when this handle was forced dirty.
  265. // It doesn't count for protected write tracking.
  266. _checkCount--;
  267. }
  268. else if (!asDirty)
  269. {
  270. if (consecutiveCheck || (_checkCount > 0 && _checkCount < CheckCountForInfrequent))
  271. {
  272. if (++_volatileCount >= VolatileThreshold && _preAction == null)
  273. {
  274. _volatile = true;
  275. return;
  276. }
  277. }
  278. else
  279. {
  280. _volatileCount = 0;
  281. }
  282. _checkCount = 0;
  283. }
  284. }
  285. /// <summary>
  286. /// Consume the dirty flag for this handle, and reprotect so it can be set on the next write.
  287. /// </summary>
  288. /// <param name="asDirty">True if the handle should be reprotected as dirty, rather than have it cleared</param>
  289. public void Reprotect(bool asDirty = false)
  290. {
  291. Reprotect(asDirty, false);
  292. }
  293. /// <summary>
  294. /// Register an action to perform when the tracked region is read or written.
  295. /// The action is automatically removed after it runs.
  296. /// </summary>
  297. /// <param name="action">Action to call on read or write</param>
  298. public void RegisterAction(RegionSignal action)
  299. {
  300. ClearVolatile();
  301. lock (_preActionLock)
  302. {
  303. RegionSignal lastAction = Interlocked.Exchange(ref _preAction, action);
  304. if (lastAction == null && action != lastAction)
  305. {
  306. lock (_tracking.TrackingLock)
  307. {
  308. foreach (VirtualRegion region in _regions)
  309. {
  310. region.UpdateProtection();
  311. }
  312. }
  313. }
  314. }
  315. }
  316. /// <summary>
  317. /// Register an action to perform when a precise access occurs (one with exact address and size).
  318. /// If the action returns true, read/write tracking are skipped.
  319. /// </summary>
  320. /// <param name="action">Action to call on read or write</param>
  321. public void RegisterPreciseAction(PreciseRegionSignal action)
  322. {
  323. _preciseAction = action;
  324. }
  325. /// <summary>
  326. /// Register an action to perform when the region is written to.
  327. /// This action will not be removed when it is called - it is called each time the dirty flag is set.
  328. /// </summary>
  329. /// <param name="action">Action to call on dirty</param>
  330. public void RegisterDirtyEvent(Action action)
  331. {
  332. _onDirty += action;
  333. }
  334. /// <summary>
  335. /// Add a child virtual region to this handle.
  336. /// </summary>
  337. /// <param name="region">Virtual region to add as a child</param>
  338. internal void AddChild(VirtualRegion region)
  339. {
  340. _regions.Add(region);
  341. }
  342. /// <summary>
  343. /// Signal that this handle has been mapped or unmapped.
  344. /// </summary>
  345. /// <param name="mapped">True if the handle has been mapped, false if unmapped</param>
  346. internal void SignalMappingChanged(bool mapped)
  347. {
  348. if (Unmapped == mapped)
  349. {
  350. Unmapped = !mapped;
  351. if (Unmapped)
  352. {
  353. ClearVolatile();
  354. Dirty = false;
  355. }
  356. }
  357. }
  358. /// <summary>
  359. /// Check if this region overlaps with another.
  360. /// </summary>
  361. /// <param name="address">Base address</param>
  362. /// <param name="size">Size of the region</param>
  363. /// <returns>True if overlapping, false otherwise</returns>
  364. public bool OverlapsWith(ulong address, ulong size)
  365. {
  366. return Address < address + size && address < EndAddress;
  367. }
  368. /// <summary>
  369. /// Dispose the handle. Within the tracking lock, this removes references from virtual regions.
  370. /// </summary>
  371. public void Dispose()
  372. {
  373. ObjectDisposedException.ThrowIf(_disposed, this);
  374. _disposed = true;
  375. lock (_tracking.TrackingLock)
  376. {
  377. foreach (VirtualRegion region in _regions)
  378. {
  379. region.RemoveHandle(this);
  380. }
  381. }
  382. }
  383. }
  384. }