RegionHandle.cs 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  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 RegionSignal _preAction; // Action to perform before a read or write. This will block the memory access.
  32. private readonly List<VirtualRegion> _regions;
  33. private readonly MemoryTracking _tracking;
  34. private bool _disposed;
  35. private int _checkCount = 0;
  36. private int _volatileCount = 0;
  37. private bool _volatile;
  38. internal MemoryPermission RequiredPermission
  39. {
  40. get
  41. {
  42. // If this is unmapped, allow reprotecting as RW as it can't be dirtied.
  43. // This is required for the partial unmap cases where part of the data are still being accessed.
  44. if (Unmapped)
  45. {
  46. return MemoryPermission.ReadAndWrite;
  47. }
  48. if (_preAction != null)
  49. {
  50. return MemoryPermission.None;
  51. }
  52. return Dirty ? MemoryPermission.ReadAndWrite : MemoryPermission.Read;
  53. }
  54. }
  55. internal RegionSignal PreAction => _preAction;
  56. /// <summary>
  57. /// Create a new region handle. The handle is registered with the given tracking object,
  58. /// and will be notified of any changes to the specified region.
  59. /// </summary>
  60. /// <param name="tracking">Tracking object for the target memory block</param>
  61. /// <param name="address">Virtual address of the region to track</param>
  62. /// <param name="size">Size of the region to track</param>
  63. /// <param name="mapped">True if the region handle starts mapped</param>
  64. internal RegionHandle(MemoryTracking tracking, ulong address, ulong size, bool mapped = true)
  65. {
  66. Dirty = mapped;
  67. Unmapped = !mapped;
  68. Address = address;
  69. Size = size;
  70. EndAddress = address + size;
  71. _tracking = tracking;
  72. _regions = tracking.GetVirtualRegionsForHandle(address, size);
  73. foreach (var region in _regions)
  74. {
  75. region.Handles.Add(this);
  76. }
  77. }
  78. /// <summary>
  79. /// Clear the volatile state of this handle.
  80. /// </summary>
  81. private void ClearVolatile()
  82. {
  83. _volatileCount = 0;
  84. _volatile = false;
  85. }
  86. /// <summary>
  87. /// Check if this handle is dirty, or if it is volatile. (changes very often)
  88. /// </summary>
  89. /// <returns>True if the handle is dirty or volatile, false otherwise</returns>
  90. public bool DirtyOrVolatile()
  91. {
  92. _checkCount++;
  93. return Dirty || _volatile;
  94. }
  95. /// <summary>
  96. /// Signal that a memory action occurred within this handle's virtual regions.
  97. /// </summary>
  98. /// <param name="write">Whether the region was written to or read</param>
  99. internal void Signal(ulong address, ulong size, bool write, ref IList<RegionHandle> handleIterable)
  100. {
  101. RegionSignal action = Interlocked.Exchange(ref _preAction, null);
  102. // If this handle was already unmapped (even if just partially),
  103. // then we have nothing to do until it is mapped again.
  104. // The pre-action should be still consumed to avoid flushing on remap.
  105. if (Unmapped)
  106. {
  107. return;
  108. }
  109. if (action != null)
  110. {
  111. // Copy the handles list in case it changes when we're out of the lock.
  112. if (handleIterable is List<RegionHandle>)
  113. {
  114. handleIterable = handleIterable.ToArray();
  115. }
  116. // Temporarily release the tracking lock while we're running the action.
  117. Monitor.Exit(_tracking.TrackingLock);
  118. try
  119. {
  120. action.Invoke(address, size);
  121. }
  122. finally
  123. {
  124. Monitor.Enter(_tracking.TrackingLock);
  125. }
  126. }
  127. if (write)
  128. {
  129. bool oldDirty = Dirty;
  130. Dirty = true;
  131. if (!oldDirty)
  132. {
  133. _onDirty?.Invoke();
  134. }
  135. Parent?.SignalWrite();
  136. }
  137. }
  138. /// <summary>
  139. /// Force this handle to be dirty, without reprotecting.
  140. /// </summary>
  141. public void ForceDirty()
  142. {
  143. Dirty = true;
  144. }
  145. /// <summary>
  146. /// Consume the dirty flag for this handle, and reprotect so it can be set on the next write.
  147. /// </summary>
  148. public void Reprotect(bool asDirty = false)
  149. {
  150. if (_volatile) return;
  151. Dirty = asDirty;
  152. bool protectionChanged = false;
  153. lock (_tracking.TrackingLock)
  154. {
  155. foreach (VirtualRegion region in _regions)
  156. {
  157. protectionChanged |= region.UpdateProtection();
  158. }
  159. }
  160. if (!protectionChanged)
  161. {
  162. // Counteract the check count being incremented when this handle was forced dirty.
  163. // It doesn't count for protected write tracking.
  164. _checkCount--;
  165. }
  166. else if (!asDirty)
  167. {
  168. if (_checkCount > 0 && _checkCount < CheckCountForInfrequent)
  169. {
  170. if (++_volatileCount >= VolatileThreshold && _preAction == null)
  171. {
  172. _volatile = true;
  173. return;
  174. }
  175. }
  176. else
  177. {
  178. _volatileCount = 0;
  179. }
  180. _checkCount = 0;
  181. }
  182. }
  183. /// <summary>
  184. /// Register an action to perform when the tracked region is read or written.
  185. /// The action is automatically removed after it runs.
  186. /// </summary>
  187. /// <param name="action">Action to call on read or write</param>
  188. public void RegisterAction(RegionSignal action)
  189. {
  190. ClearVolatile();
  191. RegionSignal lastAction = Interlocked.Exchange(ref _preAction, action);
  192. if (lastAction == null && action != lastAction)
  193. {
  194. lock (_tracking.TrackingLock)
  195. {
  196. foreach (VirtualRegion region in _regions)
  197. {
  198. region.UpdateProtection();
  199. }
  200. }
  201. }
  202. }
  203. /// <summary>
  204. /// Register an action to perform when the region is written to.
  205. /// This action will not be removed when it is called - it is called each time the dirty flag is set.
  206. /// </summary>
  207. /// <param name="action">Action to call on dirty</param>
  208. public void RegisterDirtyEvent(Action action)
  209. {
  210. _onDirty += action;
  211. }
  212. /// <summary>
  213. /// Add a child virtual region to this handle.
  214. /// </summary>
  215. /// <param name="region">Virtual region to add as a child</param>
  216. internal void AddChild(VirtualRegion region)
  217. {
  218. _regions.Add(region);
  219. }
  220. /// <summary>
  221. /// Signal that this handle has been mapped or unmapped.
  222. /// </summary>
  223. /// <param name="mapped">True if the handle has been mapped, false if unmapped</param>
  224. internal void SignalMappingChanged(bool mapped)
  225. {
  226. if (Unmapped == mapped)
  227. {
  228. Unmapped = !mapped;
  229. if (Unmapped)
  230. {
  231. ClearVolatile();
  232. Dirty = false;
  233. }
  234. }
  235. }
  236. /// <summary>
  237. /// Check if this region overlaps with another.
  238. /// </summary>
  239. /// <param name="address">Base address</param>
  240. /// <param name="size">Size of the region</param>
  241. /// <returns>True if overlapping, false otherwise</returns>
  242. public bool OverlapsWith(ulong address, ulong size)
  243. {
  244. return Address < address + size && address < EndAddress;
  245. }
  246. /// <summary>
  247. /// Dispose the handle. Within the tracking lock, this removes references from virtual regions.
  248. /// </summary>
  249. public void Dispose()
  250. {
  251. if (_disposed)
  252. {
  253. throw new ObjectDisposedException(GetType().FullName);
  254. }
  255. _disposed = true;
  256. lock (_tracking.TrackingLock)
  257. {
  258. foreach (VirtualRegion region in _regions)
  259. {
  260. region.RemoveHandle(this);
  261. }
  262. }
  263. }
  264. }
  265. }