RegionHandle.cs 15 KB

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