KMemoryRegionManager.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  1. using Ryujinx.Common;
  2. using Ryujinx.HLE.HOS.Kernel.Common;
  3. using System.Diagnostics;
  4. using System.Numerics;
  5. namespace Ryujinx.HLE.HOS.Kernel.Memory
  6. {
  7. class KMemoryRegionManager
  8. {
  9. private static readonly int[] BlockOrders = new int[] { 12, 16, 21, 22, 25, 29, 30 };
  10. public ulong Address { get; private set; }
  11. public ulong EndAddr { get; private set; }
  12. public ulong Size { get; private set; }
  13. private int _blockOrdersCount;
  14. private readonly KMemoryRegionBlock[] _blocks;
  15. private readonly ushort[] _pageReferenceCounts;
  16. public KMemoryRegionManager(ulong address, ulong size, ulong endAddr)
  17. {
  18. _blocks = new KMemoryRegionBlock[BlockOrders.Length];
  19. Address = address;
  20. Size = size;
  21. EndAddr = endAddr;
  22. _blockOrdersCount = BlockOrders.Length;
  23. for (int blockIndex = 0; blockIndex < _blockOrdersCount; blockIndex++)
  24. {
  25. _blocks[blockIndex] = new KMemoryRegionBlock();
  26. _blocks[blockIndex].Order = BlockOrders[blockIndex];
  27. int nextOrder = blockIndex == _blockOrdersCount - 1 ? 0 : BlockOrders[blockIndex + 1];
  28. _blocks[blockIndex].NextOrder = nextOrder;
  29. int currBlockSize = 1 << BlockOrders[blockIndex];
  30. int nextBlockSize = currBlockSize;
  31. if (nextOrder != 0)
  32. {
  33. nextBlockSize = 1 << nextOrder;
  34. }
  35. ulong startAligned = BitUtils.AlignDown(address, nextBlockSize);
  36. ulong endAddrAligned = BitUtils.AlignDown(endAddr, currBlockSize);
  37. ulong sizeInBlocksTruncated = (endAddrAligned - startAligned) >> BlockOrders[blockIndex];
  38. ulong endAddrRounded = BitUtils.AlignUp(address + size, nextBlockSize);
  39. ulong sizeInBlocksRounded = (endAddrRounded - startAligned) >> BlockOrders[blockIndex];
  40. _blocks[blockIndex].StartAligned = startAligned;
  41. _blocks[blockIndex].SizeInBlocksTruncated = sizeInBlocksTruncated;
  42. _blocks[blockIndex].SizeInBlocksRounded = sizeInBlocksRounded;
  43. ulong currSizeInBlocks = sizeInBlocksRounded;
  44. int maxLevel = 0;
  45. do
  46. {
  47. maxLevel++;
  48. }
  49. while ((currSizeInBlocks /= 64) != 0);
  50. _blocks[blockIndex].MaxLevel = maxLevel;
  51. _blocks[blockIndex].Masks = new long[maxLevel][];
  52. currSizeInBlocks = sizeInBlocksRounded;
  53. for (int level = maxLevel - 1; level >= 0; level--)
  54. {
  55. currSizeInBlocks = (currSizeInBlocks + 63) / 64;
  56. _blocks[blockIndex].Masks[level] = new long[currSizeInBlocks];
  57. }
  58. }
  59. _pageReferenceCounts = new ushort[size / KPageTableBase.PageSize];
  60. if (size != 0)
  61. {
  62. FreePages(address, size / KPageTableBase.PageSize);
  63. }
  64. }
  65. public KernelResult AllocatePages(ulong pagesCount, bool backwards, out KPageList pageList)
  66. {
  67. lock (_blocks)
  68. {
  69. KernelResult result = AllocatePagesImpl(pagesCount, backwards, out pageList);
  70. if (result == KernelResult.Success)
  71. {
  72. foreach (var node in pageList)
  73. {
  74. IncrementPagesReferenceCount(node.Address, node.PagesCount);
  75. }
  76. }
  77. return result;
  78. }
  79. }
  80. public ulong AllocatePagesContiguous(KernelContext context, ulong pagesCount, bool backwards)
  81. {
  82. lock (_blocks)
  83. {
  84. ulong address = AllocatePagesContiguousImpl(pagesCount, backwards);
  85. if (address != 0)
  86. {
  87. IncrementPagesReferenceCount(address, pagesCount);
  88. context.Memory.Commit(address - DramMemoryMap.DramBase, pagesCount * KPageTableBase.PageSize);
  89. }
  90. return address;
  91. }
  92. }
  93. private KernelResult AllocatePagesImpl(ulong pagesCount, bool backwards, out KPageList pageList)
  94. {
  95. pageList = new KPageList();
  96. if (_blockOrdersCount > 0)
  97. {
  98. if (GetFreePagesImpl() < pagesCount)
  99. {
  100. return KernelResult.OutOfMemory;
  101. }
  102. }
  103. else if (pagesCount != 0)
  104. {
  105. return KernelResult.OutOfMemory;
  106. }
  107. for (int blockIndex = _blockOrdersCount - 1; blockIndex >= 0; blockIndex--)
  108. {
  109. KMemoryRegionBlock block = _blocks[blockIndex];
  110. ulong bestFitBlockSize = 1UL << block.Order;
  111. ulong blockPagesCount = bestFitBlockSize / KPageTableBase.PageSize;
  112. // Check if this is the best fit for this page size.
  113. // If so, try allocating as much requested pages as possible.
  114. while (blockPagesCount <= pagesCount)
  115. {
  116. ulong address = AllocatePagesForOrder(blockIndex, backwards, bestFitBlockSize);
  117. // The address being zero means that no free space was found on that order,
  118. // just give up and try with the next one.
  119. if (address == 0)
  120. {
  121. break;
  122. }
  123. // Add new allocated page(s) to the pages list.
  124. // If an error occurs, then free all allocated pages and fail.
  125. KernelResult result = pageList.AddRange(address, blockPagesCount);
  126. if (result != KernelResult.Success)
  127. {
  128. FreePages(address, blockPagesCount);
  129. foreach (KPageNode pageNode in pageList)
  130. {
  131. FreePages(pageNode.Address, pageNode.PagesCount);
  132. }
  133. return result;
  134. }
  135. pagesCount -= blockPagesCount;
  136. }
  137. }
  138. // Success case, all requested pages were allocated successfully.
  139. if (pagesCount == 0)
  140. {
  141. return KernelResult.Success;
  142. }
  143. // Error case, free allocated pages and return out of memory.
  144. foreach (KPageNode pageNode in pageList)
  145. {
  146. FreePages(pageNode.Address, pageNode.PagesCount);
  147. }
  148. pageList = null;
  149. return KernelResult.OutOfMemory;
  150. }
  151. private ulong AllocatePagesContiguousImpl(ulong pagesCount, bool backwards)
  152. {
  153. if (pagesCount == 0 || _blocks.Length < 1)
  154. {
  155. return 0;
  156. }
  157. int blockIndex = 0;
  158. while ((1UL << _blocks[blockIndex].Order) / KPageTableBase.PageSize < pagesCount)
  159. {
  160. if (++blockIndex >= _blocks.Length)
  161. {
  162. return 0;
  163. }
  164. }
  165. ulong tightestFitBlockSize = 1UL << _blocks[blockIndex].Order;
  166. ulong address = AllocatePagesForOrder(blockIndex, backwards, tightestFitBlockSize);
  167. ulong requiredSize = pagesCount * KPageTableBase.PageSize;
  168. if (address != 0 && tightestFitBlockSize > requiredSize)
  169. {
  170. FreePages(address + requiredSize, (tightestFitBlockSize - requiredSize) / KPageTableBase.PageSize);
  171. }
  172. return address;
  173. }
  174. private ulong AllocatePagesForOrder(int blockIndex, bool backwards, ulong bestFitBlockSize)
  175. {
  176. ulong address = 0;
  177. KMemoryRegionBlock block = null;
  178. for (int currBlockIndex = blockIndex;
  179. currBlockIndex < _blockOrdersCount && address == 0;
  180. currBlockIndex++)
  181. {
  182. block = _blocks[currBlockIndex];
  183. int index = 0;
  184. bool zeroMask = false;
  185. for (int level = 0; level < block.MaxLevel; level++)
  186. {
  187. long mask = block.Masks[level][index];
  188. if (mask == 0)
  189. {
  190. zeroMask = true;
  191. break;
  192. }
  193. if (backwards)
  194. {
  195. index = (index * 64 + 63) - BitOperations.LeadingZeroCount((ulong)mask);
  196. }
  197. else
  198. {
  199. index = index * 64 + BitOperations.LeadingZeroCount((ulong)BitUtils.ReverseBits64(mask));
  200. }
  201. }
  202. if (block.SizeInBlocksTruncated <= (ulong)index || zeroMask)
  203. {
  204. continue;
  205. }
  206. block.FreeCount--;
  207. int tempIdx = index;
  208. for (int level = block.MaxLevel - 1; level >= 0; level--, tempIdx /= 64)
  209. {
  210. block.Masks[level][tempIdx / 64] &= ~(1L << (tempIdx & 63));
  211. if (block.Masks[level][tempIdx / 64] != 0)
  212. {
  213. break;
  214. }
  215. }
  216. address = block.StartAligned + ((ulong)index << block.Order);
  217. }
  218. for (int currBlockIndex = blockIndex;
  219. currBlockIndex < _blockOrdersCount && address == 0;
  220. currBlockIndex++)
  221. {
  222. block = _blocks[currBlockIndex];
  223. int index = 0;
  224. bool zeroMask = false;
  225. for (int level = 0; level < block.MaxLevel; level++)
  226. {
  227. long mask = block.Masks[level][index];
  228. if (mask == 0)
  229. {
  230. zeroMask = true;
  231. break;
  232. }
  233. if (backwards)
  234. {
  235. index = index * 64 + BitOperations.LeadingZeroCount((ulong)BitUtils.ReverseBits64(mask));
  236. }
  237. else
  238. {
  239. index = (index * 64 + 63) - BitOperations.LeadingZeroCount((ulong)mask);
  240. }
  241. }
  242. if (block.SizeInBlocksTruncated <= (ulong)index || zeroMask)
  243. {
  244. continue;
  245. }
  246. block.FreeCount--;
  247. int tempIdx = index;
  248. for (int level = block.MaxLevel - 1; level >= 0; level--, tempIdx /= 64)
  249. {
  250. block.Masks[level][tempIdx / 64] &= ~(1L << (tempIdx & 63));
  251. if (block.Masks[level][tempIdx / 64] != 0)
  252. {
  253. break;
  254. }
  255. }
  256. address = block.StartAligned + ((ulong)index << block.Order);
  257. }
  258. if (address != 0)
  259. {
  260. // If we are using a larger order than best fit, then we should
  261. // split it into smaller blocks.
  262. ulong firstFreeBlockSize = 1UL << block.Order;
  263. if (firstFreeBlockSize > bestFitBlockSize)
  264. {
  265. FreePages(address + bestFitBlockSize, (firstFreeBlockSize - bestFitBlockSize) / KPageTableBase.PageSize);
  266. }
  267. }
  268. return address;
  269. }
  270. private void FreePages(ulong address, ulong pagesCount)
  271. {
  272. lock (_blocks)
  273. {
  274. ulong endAddr = address + pagesCount * KPageTableBase.PageSize;
  275. int blockIndex = _blockOrdersCount - 1;
  276. ulong addressRounded = 0;
  277. ulong endAddrTruncated = 0;
  278. for (; blockIndex >= 0; blockIndex--)
  279. {
  280. KMemoryRegionBlock allocInfo = _blocks[blockIndex];
  281. int blockSize = 1 << allocInfo.Order;
  282. addressRounded = BitUtils.AlignUp (address, blockSize);
  283. endAddrTruncated = BitUtils.AlignDown(endAddr, blockSize);
  284. if (addressRounded < endAddrTruncated)
  285. {
  286. break;
  287. }
  288. }
  289. void FreeRegion(ulong currAddress)
  290. {
  291. for (int currBlockIndex = blockIndex;
  292. currBlockIndex < _blockOrdersCount && currAddress != 0;
  293. currBlockIndex++)
  294. {
  295. KMemoryRegionBlock block = _blocks[currBlockIndex];
  296. block.FreeCount++;
  297. ulong freedBlocks = (currAddress - block.StartAligned) >> block.Order;
  298. int index = (int)freedBlocks;
  299. for (int level = block.MaxLevel - 1; level >= 0; level--, index /= 64)
  300. {
  301. long mask = block.Masks[level][index / 64];
  302. block.Masks[level][index / 64] = mask | (1L << (index & 63));
  303. if (mask != 0)
  304. {
  305. break;
  306. }
  307. }
  308. int blockSizeDelta = 1 << (block.NextOrder - block.Order);
  309. int freedBlocksTruncated = BitUtils.AlignDown((int)freedBlocks, blockSizeDelta);
  310. if (!block.TryCoalesce(freedBlocksTruncated, blockSizeDelta))
  311. {
  312. break;
  313. }
  314. currAddress = block.StartAligned + ((ulong)freedBlocksTruncated << block.Order);
  315. }
  316. }
  317. // Free inside aligned region.
  318. ulong baseAddress = addressRounded;
  319. while (baseAddress < endAddrTruncated)
  320. {
  321. ulong blockSize = 1UL << _blocks[blockIndex].Order;
  322. FreeRegion(baseAddress);
  323. baseAddress += blockSize;
  324. }
  325. int nextBlockIndex = blockIndex - 1;
  326. // Free region between Address and aligned region start.
  327. baseAddress = addressRounded;
  328. for (blockIndex = nextBlockIndex; blockIndex >= 0; blockIndex--)
  329. {
  330. ulong blockSize = 1UL << _blocks[blockIndex].Order;
  331. while (baseAddress - blockSize >= address)
  332. {
  333. baseAddress -= blockSize;
  334. FreeRegion(baseAddress);
  335. }
  336. }
  337. // Free region between aligned region end and End Address.
  338. baseAddress = endAddrTruncated;
  339. for (blockIndex = nextBlockIndex; blockIndex >= 0; blockIndex--)
  340. {
  341. ulong blockSize = 1UL << _blocks[blockIndex].Order;
  342. while (baseAddress + blockSize <= endAddr)
  343. {
  344. FreeRegion(baseAddress);
  345. baseAddress += blockSize;
  346. }
  347. }
  348. }
  349. }
  350. public ulong GetFreePages()
  351. {
  352. lock (_blocks)
  353. {
  354. return GetFreePagesImpl();
  355. }
  356. }
  357. private ulong GetFreePagesImpl()
  358. {
  359. ulong availablePages = 0;
  360. for (int blockIndex = 0; blockIndex < _blockOrdersCount; blockIndex++)
  361. {
  362. KMemoryRegionBlock block = _blocks[blockIndex];
  363. ulong blockPagesCount = (1UL << block.Order) / KPageTableBase.PageSize;
  364. availablePages += blockPagesCount * block.FreeCount;
  365. }
  366. return availablePages;
  367. }
  368. public void IncrementPagesReferenceCount(ulong address, ulong pagesCount)
  369. {
  370. ulong index = GetPageOffset(address);
  371. ulong endIndex = index + pagesCount;
  372. while (index < endIndex)
  373. {
  374. ushort referenceCount = ++_pageReferenceCounts[index];
  375. Debug.Assert(referenceCount >= 1);
  376. index++;
  377. }
  378. }
  379. public void DecrementPagesReferenceCount(ulong address, ulong pagesCount)
  380. {
  381. ulong index = GetPageOffset(address);
  382. ulong endIndex = index + pagesCount;
  383. ulong freeBaseIndex = 0;
  384. ulong freePagesCount = 0;
  385. while (index < endIndex)
  386. {
  387. Debug.Assert(_pageReferenceCounts[index] > 0);
  388. ushort referenceCount = --_pageReferenceCounts[index];
  389. if (referenceCount == 0)
  390. {
  391. if (freePagesCount != 0)
  392. {
  393. freePagesCount++;
  394. }
  395. else
  396. {
  397. freeBaseIndex = index;
  398. freePagesCount = 1;
  399. }
  400. }
  401. else if (freePagesCount != 0)
  402. {
  403. FreePages(Address + freeBaseIndex * KPageTableBase.PageSize, freePagesCount);
  404. freePagesCount = 0;
  405. }
  406. index++;
  407. }
  408. if (freePagesCount != 0)
  409. {
  410. FreePages(Address + freeBaseIndex * KPageTableBase.PageSize, freePagesCount);
  411. }
  412. }
  413. public ulong GetPageOffset(ulong address)
  414. {
  415. return (address - Address) / KPageTableBase.PageSize;
  416. }
  417. public ulong GetPageOffsetFromEnd(ulong address)
  418. {
  419. return (EndAddr - address) / KPageTableBase.PageSize;
  420. }
  421. }
  422. }