AddressSpace.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  1. using Ryujinx.Common;
  2. using Ryujinx.Common.Collections;
  3. using Ryujinx.Memory;
  4. using System;
  5. namespace Ryujinx.Cpu
  6. {
  7. public class AddressSpace : IDisposable
  8. {
  9. private const int DefaultBlockAlignment = 1 << 20;
  10. private enum MappingType : byte
  11. {
  12. None,
  13. Private,
  14. Shared,
  15. }
  16. private class Mapping : IntrusiveRedBlackTreeNode<Mapping>, IComparable<Mapping>
  17. {
  18. public ulong Address { get; private set; }
  19. public ulong Size { get; private set; }
  20. public ulong EndAddress => Address + Size;
  21. public MappingType Type { get; private set; }
  22. public Mapping(ulong address, ulong size, MappingType type)
  23. {
  24. Address = address;
  25. Size = size;
  26. Type = type;
  27. }
  28. public Mapping Split(ulong splitAddress)
  29. {
  30. ulong leftSize = splitAddress - Address;
  31. ulong rightSize = EndAddress - splitAddress;
  32. Mapping left = new(Address, leftSize, Type);
  33. Address = splitAddress;
  34. Size = rightSize;
  35. return left;
  36. }
  37. public void UpdateState(MappingType newType)
  38. {
  39. Type = newType;
  40. }
  41. public void Extend(ulong sizeDelta)
  42. {
  43. Size += sizeDelta;
  44. }
  45. public int CompareTo(Mapping other)
  46. {
  47. if (Address < other.Address)
  48. {
  49. return -1;
  50. }
  51. else if (Address <= other.EndAddress - 1UL)
  52. {
  53. return 0;
  54. }
  55. else
  56. {
  57. return 1;
  58. }
  59. }
  60. }
  61. private class PrivateMapping : IntrusiveRedBlackTreeNode<PrivateMapping>, IComparable<PrivateMapping>
  62. {
  63. public ulong Address { get; private set; }
  64. public ulong Size { get; private set; }
  65. public ulong EndAddress => Address + Size;
  66. public PrivateMemoryAllocation PrivateAllocation { get; private set; }
  67. public PrivateMapping(ulong address, ulong size, PrivateMemoryAllocation privateAllocation)
  68. {
  69. Address = address;
  70. Size = size;
  71. PrivateAllocation = privateAllocation;
  72. }
  73. public PrivateMapping Split(ulong splitAddress)
  74. {
  75. ulong leftSize = splitAddress - Address;
  76. ulong rightSize = EndAddress - splitAddress;
  77. (var leftAllocation, PrivateAllocation) = PrivateAllocation.Split(leftSize);
  78. PrivateMapping left = new(Address, leftSize, leftAllocation);
  79. Address = splitAddress;
  80. Size = rightSize;
  81. return left;
  82. }
  83. public void Map(MemoryBlock baseBlock, MemoryBlock mirrorBlock, PrivateMemoryAllocation newAllocation)
  84. {
  85. baseBlock.MapView(newAllocation.Memory, newAllocation.Offset, Address, Size);
  86. mirrorBlock.MapView(newAllocation.Memory, newAllocation.Offset, Address, Size);
  87. PrivateAllocation = newAllocation;
  88. }
  89. public void Unmap(MemoryBlock baseBlock, MemoryBlock mirrorBlock)
  90. {
  91. if (PrivateAllocation.IsValid)
  92. {
  93. baseBlock.UnmapView(PrivateAllocation.Memory, Address, Size);
  94. mirrorBlock.UnmapView(PrivateAllocation.Memory, Address, Size);
  95. PrivateAllocation.Dispose();
  96. }
  97. PrivateAllocation = default;
  98. }
  99. public void Extend(ulong sizeDelta)
  100. {
  101. Size += sizeDelta;
  102. }
  103. public int CompareTo(PrivateMapping other)
  104. {
  105. if (Address < other.Address)
  106. {
  107. return -1;
  108. }
  109. else if (Address <= other.EndAddress - 1UL)
  110. {
  111. return 0;
  112. }
  113. else
  114. {
  115. return 1;
  116. }
  117. }
  118. }
  119. private readonly MemoryBlock _backingMemory;
  120. private readonly PrivateMemoryAllocator _privateMemoryAllocator;
  121. private readonly IntrusiveRedBlackTree<Mapping> _mappingTree;
  122. private readonly IntrusiveRedBlackTree<PrivateMapping> _privateTree;
  123. private readonly object _treeLock;
  124. private readonly bool _supports4KBPages;
  125. public MemoryBlock Base { get; }
  126. public MemoryBlock Mirror { get; }
  127. public ulong AddressSpaceSize { get; }
  128. public AddressSpace(MemoryBlock backingMemory, MemoryBlock baseMemory, MemoryBlock mirrorMemory, ulong addressSpaceSize, bool supports4KBPages)
  129. {
  130. if (!supports4KBPages)
  131. {
  132. _privateMemoryAllocator = new PrivateMemoryAllocator(DefaultBlockAlignment, MemoryAllocationFlags.Mirrorable | MemoryAllocationFlags.NoMap);
  133. _mappingTree = new IntrusiveRedBlackTree<Mapping>();
  134. _privateTree = new IntrusiveRedBlackTree<PrivateMapping>();
  135. _treeLock = new object();
  136. _mappingTree.Add(new Mapping(0UL, addressSpaceSize, MappingType.None));
  137. _privateTree.Add(new PrivateMapping(0UL, addressSpaceSize, default));
  138. }
  139. _backingMemory = backingMemory;
  140. _supports4KBPages = supports4KBPages;
  141. Base = baseMemory;
  142. Mirror = mirrorMemory;
  143. AddressSpaceSize = addressSpaceSize;
  144. }
  145. public static bool TryCreate(MemoryBlock backingMemory, ulong asSize, bool supports4KBPages, out AddressSpace addressSpace)
  146. {
  147. addressSpace = null;
  148. const MemoryAllocationFlags AsFlags = MemoryAllocationFlags.Reserve | MemoryAllocationFlags.ViewCompatible;
  149. ulong minAddressSpaceSize = Math.Min(asSize, 1UL << 36);
  150. // Attempt to create the address space with expected size or try to reduce it until it succeed.
  151. for (ulong addressSpaceSize = asSize; addressSpaceSize >= minAddressSpaceSize; addressSpaceSize >>= 1)
  152. {
  153. MemoryBlock baseMemory = null;
  154. MemoryBlock mirrorMemory = null;
  155. try
  156. {
  157. baseMemory = new MemoryBlock(addressSpaceSize, AsFlags);
  158. mirrorMemory = new MemoryBlock(addressSpaceSize, AsFlags);
  159. addressSpace = new AddressSpace(backingMemory, baseMemory, mirrorMemory, addressSpaceSize, supports4KBPages);
  160. break;
  161. }
  162. catch (SystemException)
  163. {
  164. baseMemory?.Dispose();
  165. mirrorMemory?.Dispose();
  166. }
  167. }
  168. return addressSpace != null;
  169. }
  170. public void Map(ulong va, ulong pa, ulong size, MemoryMapFlags flags)
  171. {
  172. if (_supports4KBPages)
  173. {
  174. Base.MapView(_backingMemory, pa, va, size);
  175. Mirror.MapView(_backingMemory, pa, va, size);
  176. return;
  177. }
  178. lock (_treeLock)
  179. {
  180. ulong alignment = MemoryBlock.GetPageSize();
  181. bool isAligned = ((va | pa | size) & (alignment - 1)) == 0;
  182. if (flags.HasFlag(MemoryMapFlags.Private) && !isAligned)
  183. {
  184. Update(va, pa, size, MappingType.Private);
  185. }
  186. else
  187. {
  188. // The update method assumes that shared mappings are already aligned.
  189. if (!flags.HasFlag(MemoryMapFlags.Private))
  190. {
  191. if ((va & (alignment - 1)) != (pa & (alignment - 1)))
  192. {
  193. throw new InvalidMemoryRegionException($"Virtual address 0x{va:X} and physical address 0x{pa:X} are misaligned and can't be aligned.");
  194. }
  195. ulong endAddress = va + size;
  196. va = BitUtils.AlignDown(va, alignment);
  197. pa = BitUtils.AlignDown(pa, alignment);
  198. size = BitUtils.AlignUp(endAddress, alignment) - va;
  199. }
  200. Update(va, pa, size, MappingType.Shared);
  201. }
  202. }
  203. }
  204. public void Unmap(ulong va, ulong size)
  205. {
  206. if (_supports4KBPages)
  207. {
  208. Base.UnmapView(_backingMemory, va, size);
  209. Mirror.UnmapView(_backingMemory, va, size);
  210. return;
  211. }
  212. lock (_treeLock)
  213. {
  214. Update(va, 0UL, size, MappingType.None);
  215. }
  216. }
  217. private void Update(ulong va, ulong pa, ulong size, MappingType type)
  218. {
  219. Mapping map = _mappingTree.GetNode(new Mapping(va, 1UL, MappingType.None));
  220. Update(map, va, pa, size, type);
  221. }
  222. private Mapping Update(Mapping map, ulong va, ulong pa, ulong size, MappingType type)
  223. {
  224. ulong endAddress = va + size;
  225. for (; map != null; map = map.Successor)
  226. {
  227. if (map.Address < va)
  228. {
  229. _mappingTree.Add(map.Split(va));
  230. }
  231. if (map.EndAddress > endAddress)
  232. {
  233. Mapping newMap = map.Split(endAddress);
  234. _mappingTree.Add(newMap);
  235. map = newMap;
  236. }
  237. switch (type)
  238. {
  239. case MappingType.None:
  240. if (map.Type == MappingType.Shared)
  241. {
  242. ulong startOffset = map.Address - va;
  243. ulong mapVa = va + startOffset;
  244. ulong mapSize = Math.Min(size - startOffset, map.Size);
  245. ulong mapEndAddress = mapVa + mapSize;
  246. ulong alignment = MemoryBlock.GetPageSize();
  247. mapVa = BitUtils.AlignDown(mapVa, alignment);
  248. mapEndAddress = BitUtils.AlignUp(mapEndAddress, alignment);
  249. mapSize = mapEndAddress - mapVa;
  250. Base.UnmapView(_backingMemory, mapVa, mapSize);
  251. Mirror.UnmapView(_backingMemory, mapVa, mapSize);
  252. }
  253. else
  254. {
  255. UnmapPrivate(va, size);
  256. }
  257. break;
  258. case MappingType.Private:
  259. if (map.Type == MappingType.Shared)
  260. {
  261. throw new InvalidMemoryRegionException($"Private mapping request at 0x{va:X} with size 0x{size:X} overlaps shared mapping at 0x{map.Address:X} with size 0x{map.Size:X}.");
  262. }
  263. else
  264. {
  265. MapPrivate(va, size);
  266. }
  267. break;
  268. case MappingType.Shared:
  269. if (map.Type != MappingType.None)
  270. {
  271. throw new InvalidMemoryRegionException($"Shared mapping request at 0x{va:X} with size 0x{size:X} overlaps mapping at 0x{map.Address:X} with size 0x{map.Size:X}.");
  272. }
  273. else
  274. {
  275. ulong startOffset = map.Address - va;
  276. ulong mapPa = pa + startOffset;
  277. ulong mapVa = va + startOffset;
  278. ulong mapSize = Math.Min(size - startOffset, map.Size);
  279. Base.MapView(_backingMemory, mapPa, mapVa, mapSize);
  280. Mirror.MapView(_backingMemory, mapPa, mapVa, mapSize);
  281. }
  282. break;
  283. }
  284. map.UpdateState(type);
  285. map = TryCoalesce(map);
  286. if (map.EndAddress >= endAddress)
  287. {
  288. break;
  289. }
  290. }
  291. return map;
  292. }
  293. private Mapping TryCoalesce(Mapping map)
  294. {
  295. Mapping previousMap = map.Predecessor;
  296. Mapping nextMap = map.Successor;
  297. if (previousMap != null && CanCoalesce(previousMap, map))
  298. {
  299. previousMap.Extend(map.Size);
  300. _mappingTree.Remove(map);
  301. map = previousMap;
  302. }
  303. if (nextMap != null && CanCoalesce(map, nextMap))
  304. {
  305. map.Extend(nextMap.Size);
  306. _mappingTree.Remove(nextMap);
  307. }
  308. return map;
  309. }
  310. private static bool CanCoalesce(Mapping left, Mapping right)
  311. {
  312. return left.Type == right.Type;
  313. }
  314. private void MapPrivate(ulong va, ulong size)
  315. {
  316. ulong endAddress = va + size;
  317. ulong alignment = MemoryBlock.GetPageSize();
  318. // Expand the range outwards based on page size to ensure that at least the requested region is mapped.
  319. ulong vaAligned = BitUtils.AlignDown(va, alignment);
  320. ulong endAddressAligned = BitUtils.AlignUp(endAddress, alignment);
  321. PrivateMapping map = _privateTree.GetNode(new PrivateMapping(va, 1UL, default));
  322. for (; map != null; map = map.Successor)
  323. {
  324. if (!map.PrivateAllocation.IsValid)
  325. {
  326. if (map.Address < vaAligned)
  327. {
  328. _privateTree.Add(map.Split(vaAligned));
  329. }
  330. if (map.EndAddress > endAddressAligned)
  331. {
  332. PrivateMapping newMap = map.Split(endAddressAligned);
  333. _privateTree.Add(newMap);
  334. map = newMap;
  335. }
  336. map.Map(Base, Mirror, _privateMemoryAllocator.Allocate(map.Size, MemoryBlock.GetPageSize()));
  337. }
  338. if (map.EndAddress >= endAddressAligned)
  339. {
  340. break;
  341. }
  342. }
  343. }
  344. private void UnmapPrivate(ulong va, ulong size)
  345. {
  346. ulong endAddress = va + size;
  347. ulong alignment = MemoryBlock.GetPageSize();
  348. // Shrink the range inwards based on page size to ensure we won't unmap memory that might be still in use.
  349. ulong vaAligned = BitUtils.AlignUp(va, alignment);
  350. ulong endAddressAligned = BitUtils.AlignDown(endAddress, alignment);
  351. if (endAddressAligned <= vaAligned)
  352. {
  353. return;
  354. }
  355. PrivateMapping map = _privateTree.GetNode(new PrivateMapping(va, 1UL, default));
  356. for (; map != null; map = map.Successor)
  357. {
  358. if (map.PrivateAllocation.IsValid)
  359. {
  360. if (map.Address < vaAligned)
  361. {
  362. _privateTree.Add(map.Split(vaAligned));
  363. }
  364. if (map.EndAddress > endAddressAligned)
  365. {
  366. PrivateMapping newMap = map.Split(endAddressAligned);
  367. _privateTree.Add(newMap);
  368. map = newMap;
  369. }
  370. map.Unmap(Base, Mirror);
  371. map = TryCoalesce(map);
  372. }
  373. if (map.EndAddress >= endAddressAligned)
  374. {
  375. break;
  376. }
  377. }
  378. }
  379. private PrivateMapping TryCoalesce(PrivateMapping map)
  380. {
  381. PrivateMapping previousMap = map.Predecessor;
  382. PrivateMapping nextMap = map.Successor;
  383. if (previousMap != null && CanCoalesce(previousMap, map))
  384. {
  385. previousMap.Extend(map.Size);
  386. _privateTree.Remove(map);
  387. map = previousMap;
  388. }
  389. if (nextMap != null && CanCoalesce(map, nextMap))
  390. {
  391. map.Extend(nextMap.Size);
  392. _privateTree.Remove(nextMap);
  393. }
  394. return map;
  395. }
  396. private static bool CanCoalesce(PrivateMapping left, PrivateMapping right)
  397. {
  398. return !left.PrivateAllocation.IsValid && !right.PrivateAllocation.IsValid;
  399. }
  400. public void Dispose()
  401. {
  402. GC.SuppressFinalize(this);
  403. _privateMemoryAllocator?.Dispose();
  404. Base.Dispose();
  405. Mirror.Dispose();
  406. }
  407. }
  408. }