RegionHandle.cs 12 KB

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