RegionHandle.cs 17 KB

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