RegionHandle.cs 8.4 KB

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