RegionHandle.cs 9.2 KB

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