RegionHandle.cs 10 KB

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