RegionHandle.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  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. _preAction = null;
  129. }
  130. }
  131. finally
  132. {
  133. Monitor.Enter(_tracking.TrackingLock);
  134. }
  135. }
  136. if (write)
  137. {
  138. bool oldDirty = Dirty;
  139. Dirty = true;
  140. if (!oldDirty)
  141. {
  142. _onDirty?.Invoke();
  143. }
  144. Parent?.SignalWrite();
  145. }
  146. }
  147. /// <summary>
  148. /// Signal that a precise memory action occurred within this handle's virtual regions.
  149. /// If there is no precise action, or the action returns false, the normal signal handler will be called.
  150. /// </summary>
  151. /// <param name="address">Address accessed</param>
  152. /// <param name="size">Size of the region affected in bytes</param>
  153. /// <param name="write">Whether the region was written to or read</param>
  154. /// <param name="handleIterable">Reference to the handles being iterated, in case the list needs to be copied</param>
  155. /// <returns>True if a precise action was performed and returned true, false otherwise</returns>
  156. internal bool SignalPrecise(ulong address, ulong size, bool write, ref IList<RegionHandle> handleIterable)
  157. {
  158. if (!Unmapped && _preciseAction != null && _preciseAction(address, size, write))
  159. {
  160. return true;
  161. }
  162. Signal(address, size, write, ref handleIterable);
  163. return false;
  164. }
  165. /// <summary>
  166. /// Force this handle to be dirty, without reprotecting.
  167. /// </summary>
  168. public void ForceDirty()
  169. {
  170. Dirty = true;
  171. }
  172. /// <summary>
  173. /// Consume the dirty flag for this handle, and reprotect so it can be set on the next write.
  174. /// </summary>
  175. public void Reprotect(bool asDirty = false)
  176. {
  177. if (_volatile) return;
  178. Dirty = asDirty;
  179. bool protectionChanged = false;
  180. lock (_tracking.TrackingLock)
  181. {
  182. foreach (VirtualRegion region in _regions)
  183. {
  184. protectionChanged |= region.UpdateProtection();
  185. }
  186. }
  187. if (!protectionChanged)
  188. {
  189. // Counteract the check count being incremented when this handle was forced dirty.
  190. // It doesn't count for protected write tracking.
  191. _checkCount--;
  192. }
  193. else if (!asDirty)
  194. {
  195. if (_checkCount > 0 && _checkCount < CheckCountForInfrequent)
  196. {
  197. if (++_volatileCount >= VolatileThreshold && _preAction == null)
  198. {
  199. _volatile = true;
  200. return;
  201. }
  202. }
  203. else
  204. {
  205. _volatileCount = 0;
  206. }
  207. _checkCount = 0;
  208. }
  209. }
  210. /// <summary>
  211. /// Register an action to perform when the tracked region is read or written.
  212. /// The action is automatically removed after it runs.
  213. /// </summary>
  214. /// <param name="action">Action to call on read or write</param>
  215. public void RegisterAction(RegionSignal action)
  216. {
  217. ClearVolatile();
  218. lock (_preActionLock)
  219. {
  220. RegionSignal lastAction = _preAction;
  221. _preAction = action;
  222. if (lastAction == null && action != lastAction)
  223. {
  224. lock (_tracking.TrackingLock)
  225. {
  226. foreach (VirtualRegion region in _regions)
  227. {
  228. region.UpdateProtection();
  229. }
  230. }
  231. }
  232. }
  233. }
  234. /// <summary>
  235. /// Register an action to perform when a precise access occurs (one with exact address and size).
  236. /// If the action returns true, read/write tracking are skipped.
  237. /// </summary>
  238. /// <param name="action">Action to call on read or write</param>
  239. public void RegisterPreciseAction(PreciseRegionSignal action)
  240. {
  241. _preciseAction = action;
  242. }
  243. /// <summary>
  244. /// Register an action to perform when the region is written to.
  245. /// This action will not be removed when it is called - it is called each time the dirty flag is set.
  246. /// </summary>
  247. /// <param name="action">Action to call on dirty</param>
  248. public void RegisterDirtyEvent(Action action)
  249. {
  250. _onDirty += action;
  251. }
  252. /// <summary>
  253. /// Add a child virtual region to this handle.
  254. /// </summary>
  255. /// <param name="region">Virtual region to add as a child</param>
  256. internal void AddChild(VirtualRegion region)
  257. {
  258. _regions.Add(region);
  259. }
  260. /// <summary>
  261. /// Signal that this handle has been mapped or unmapped.
  262. /// </summary>
  263. /// <param name="mapped">True if the handle has been mapped, false if unmapped</param>
  264. internal void SignalMappingChanged(bool mapped)
  265. {
  266. if (Unmapped == mapped)
  267. {
  268. Unmapped = !mapped;
  269. if (Unmapped)
  270. {
  271. ClearVolatile();
  272. Dirty = false;
  273. }
  274. }
  275. }
  276. /// <summary>
  277. /// Check if this region overlaps with another.
  278. /// </summary>
  279. /// <param name="address">Base address</param>
  280. /// <param name="size">Size of the region</param>
  281. /// <returns>True if overlapping, false otherwise</returns>
  282. public bool OverlapsWith(ulong address, ulong size)
  283. {
  284. return Address < address + size && address < EndAddress;
  285. }
  286. /// <summary>
  287. /// Dispose the handle. Within the tracking lock, this removes references from virtual regions.
  288. /// </summary>
  289. public void Dispose()
  290. {
  291. if (_disposed)
  292. {
  293. throw new ObjectDisposedException(GetType().FullName);
  294. }
  295. _disposed = true;
  296. lock (_tracking.TrackingLock)
  297. {
  298. foreach (VirtualRegion region in _regions)
  299. {
  300. region.RemoveHandle(this);
  301. }
  302. }
  303. }
  304. }
  305. }