k_page_bitmap.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. // SPDX-FileCopyrightText: Copyright 2021 yuzu Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #pragma once
  4. #include <array>
  5. #include <bit>
  6. #include "common/alignment.h"
  7. #include "common/assert.h"
  8. #include "common/bit_util.h"
  9. #include "common/common_types.h"
  10. #include "common/tiny_mt.h"
  11. #include "core/hle/kernel/k_system_control.h"
  12. namespace Kernel {
  13. class KPageBitmap {
  14. public:
  15. class RandomBitGenerator {
  16. public:
  17. RandomBitGenerator() {
  18. m_rng.Initialize(static_cast<u32>(KSystemControl::GenerateRandomU64()));
  19. }
  20. u64 SelectRandomBit(u64 bitmap) {
  21. u64 selected = 0;
  22. for (size_t cur_num_bits = Common::BitSize<decltype(bitmap)>() / 2; cur_num_bits != 0;
  23. cur_num_bits /= 2) {
  24. const u64 high = (bitmap >> cur_num_bits);
  25. const u64 low = (bitmap & (~(UINT64_C(0xFFFFFFFFFFFFFFFF) << cur_num_bits)));
  26. // Choose high if we have high and (don't have low or select high randomly).
  27. if (high && (low == 0 || this->GenerateRandomBit())) {
  28. bitmap = high;
  29. selected += cur_num_bits;
  30. } else {
  31. bitmap = low;
  32. selected += 0;
  33. }
  34. }
  35. return selected;
  36. }
  37. u64 GenerateRandom(u64 max) {
  38. // Determine the number of bits we need.
  39. const u64 bits_needed = 1 + (Common::BitSize<decltype(max)>() - std::countl_zero(max));
  40. // Generate a random value of the desired bitwidth.
  41. const u64 rnd = this->GenerateRandomBits(static_cast<u32>(bits_needed));
  42. // Adjust the value to be in range.
  43. return rnd - ((rnd / max) * max);
  44. }
  45. private:
  46. void RefreshEntropy() {
  47. m_entropy = m_rng.GenerateRandomU32();
  48. m_bits_available = static_cast<u32>(Common::BitSize<decltype(m_entropy)>());
  49. }
  50. bool GenerateRandomBit() {
  51. if (m_bits_available == 0) {
  52. this->RefreshEntropy();
  53. }
  54. const bool rnd_bit = (m_entropy & 1) != 0;
  55. m_entropy >>= 1;
  56. --m_bits_available;
  57. return rnd_bit;
  58. }
  59. u64 GenerateRandomBits(u32 num_bits) {
  60. u64 result = 0;
  61. // Iteratively add random bits to our result.
  62. while (num_bits > 0) {
  63. // Ensure we have random bits to take from.
  64. if (m_bits_available == 0) {
  65. this->RefreshEntropy();
  66. }
  67. // Determine how many bits to take this round.
  68. const auto cur_bits = std::min(num_bits, m_bits_available);
  69. // Generate mask for our current bits.
  70. const u64 mask = (static_cast<u64>(1) << cur_bits) - 1;
  71. // Add bits to output from our entropy.
  72. result <<= cur_bits;
  73. result |= (m_entropy & mask);
  74. // Remove bits from our entropy.
  75. m_entropy >>= cur_bits;
  76. m_bits_available -= cur_bits;
  77. // Advance.
  78. num_bits -= cur_bits;
  79. }
  80. return result;
  81. }
  82. private:
  83. Common::TinyMT m_rng;
  84. u32 m_entropy{};
  85. u32 m_bits_available{};
  86. };
  87. public:
  88. static constexpr size_t MaxDepth = 4;
  89. public:
  90. KPageBitmap() = default;
  91. constexpr size_t GetNumBits() const {
  92. return m_num_bits;
  93. }
  94. constexpr s32 GetHighestDepthIndex() const {
  95. return static_cast<s32>(m_used_depths) - 1;
  96. }
  97. u64* Initialize(u64* storage, size_t size) {
  98. // Initially, everything is un-set.
  99. m_num_bits = 0;
  100. // Calculate the needed bitmap depth.
  101. m_used_depths = static_cast<size_t>(GetRequiredDepth(size));
  102. ASSERT(m_used_depths <= MaxDepth);
  103. // Set the bitmap pointers.
  104. for (s32 depth = this->GetHighestDepthIndex(); depth >= 0; depth--) {
  105. m_bit_storages[depth] = storage;
  106. size = Common::AlignUp(size, Common::BitSize<u64>()) / Common::BitSize<u64>();
  107. storage += size;
  108. m_end_storages[depth] = storage;
  109. }
  110. return storage;
  111. }
  112. s64 FindFreeBlock(bool random) {
  113. uintptr_t offset = 0;
  114. s32 depth = 0;
  115. if (random) {
  116. do {
  117. const u64 v = m_bit_storages[depth][offset];
  118. if (v == 0) {
  119. // If depth is bigger than zero, then a previous level indicated a block was
  120. // free.
  121. ASSERT(depth == 0);
  122. return -1;
  123. }
  124. offset = offset * Common::BitSize<u64>() + m_rng.SelectRandomBit(v);
  125. ++depth;
  126. } while (depth < static_cast<s32>(m_used_depths));
  127. } else {
  128. do {
  129. const u64 v = m_bit_storages[depth][offset];
  130. if (v == 0) {
  131. // If depth is bigger than zero, then a previous level indicated a block was
  132. // free.
  133. ASSERT(depth == 0);
  134. return -1;
  135. }
  136. offset = offset * Common::BitSize<u64>() + std::countr_zero(v);
  137. ++depth;
  138. } while (depth < static_cast<s32>(m_used_depths));
  139. }
  140. return static_cast<s64>(offset);
  141. }
  142. s64 FindFreeRange(size_t count) {
  143. // Check that it is possible to find a range.
  144. const u64* const storage_start = m_bit_storages[m_used_depths - 1];
  145. const u64* const storage_end = m_end_storages[m_used_depths - 1];
  146. // If we don't have a storage to iterate (or want more blocks than fit in a single storage),
  147. // we can't find a free range.
  148. if (!(storage_start < storage_end && count <= Common::BitSize<u64>())) {
  149. return -1;
  150. }
  151. // Walk the storages to select a random free range.
  152. const size_t options_per_storage = std::max<size_t>(Common::BitSize<u64>() / count, 1);
  153. const size_t num_entries = std::max<size_t>(storage_end - storage_start, 1);
  154. const u64 free_mask = (static_cast<u64>(1) << count) - 1;
  155. size_t num_valid_options = 0;
  156. s64 chosen_offset = -1;
  157. for (size_t storage_index = 0; storage_index < num_entries; ++storage_index) {
  158. u64 storage = storage_start[storage_index];
  159. for (size_t option = 0; option < options_per_storage; ++option) {
  160. if ((storage & free_mask) == free_mask) {
  161. // We've found a new valid option.
  162. ++num_valid_options;
  163. // Select the Kth valid option with probability 1/K. This leads to an overall
  164. // uniform distribution.
  165. if (num_valid_options == 1 || m_rng.GenerateRandom(num_valid_options) == 0) {
  166. // This is our first option, so select it.
  167. chosen_offset = storage_index * Common::BitSize<u64>() + option * count;
  168. }
  169. }
  170. storage >>= count;
  171. }
  172. }
  173. // Return the random offset we chose.*/
  174. return chosen_offset;
  175. }
  176. void SetBit(size_t offset) {
  177. this->SetBit(this->GetHighestDepthIndex(), offset);
  178. m_num_bits++;
  179. }
  180. void ClearBit(size_t offset) {
  181. this->ClearBit(this->GetHighestDepthIndex(), offset);
  182. m_num_bits--;
  183. }
  184. bool ClearRange(size_t offset, size_t count) {
  185. s32 depth = this->GetHighestDepthIndex();
  186. u64* bits = m_bit_storages[depth];
  187. size_t bit_ind = offset / Common::BitSize<u64>();
  188. if (count < Common::BitSize<u64>()) [[likely]] {
  189. const size_t shift = offset % Common::BitSize<u64>();
  190. ASSERT(shift + count <= Common::BitSize<u64>());
  191. // Check that all the bits are set.
  192. const u64 mask = ((u64(1) << count) - 1) << shift;
  193. u64 v = bits[bit_ind];
  194. if ((v & mask) != mask) {
  195. return false;
  196. }
  197. // Clear the bits.
  198. v &= ~mask;
  199. bits[bit_ind] = v;
  200. if (v == 0) {
  201. this->ClearBit(depth - 1, bit_ind);
  202. }
  203. } else {
  204. ASSERT(offset % Common::BitSize<u64>() == 0);
  205. ASSERT(count % Common::BitSize<u64>() == 0);
  206. // Check that all the bits are set.
  207. size_t remaining = count;
  208. size_t i = 0;
  209. do {
  210. if (bits[bit_ind + i++] != ~u64(0)) {
  211. return false;
  212. }
  213. remaining -= Common::BitSize<u64>();
  214. } while (remaining > 0);
  215. // Clear the bits.
  216. remaining = count;
  217. i = 0;
  218. do {
  219. bits[bit_ind + i] = 0;
  220. this->ClearBit(depth - 1, bit_ind + i);
  221. i++;
  222. remaining -= Common::BitSize<u64>();
  223. } while (remaining > 0);
  224. }
  225. m_num_bits -= count;
  226. return true;
  227. }
  228. private:
  229. void SetBit(s32 depth, size_t offset) {
  230. while (depth >= 0) {
  231. size_t ind = offset / Common::BitSize<u64>();
  232. size_t which = offset % Common::BitSize<u64>();
  233. const u64 mask = u64(1) << which;
  234. u64* bit = std::addressof(m_bit_storages[depth][ind]);
  235. u64 v = *bit;
  236. ASSERT((v & mask) == 0);
  237. *bit = v | mask;
  238. if (v) {
  239. break;
  240. }
  241. offset = ind;
  242. depth--;
  243. }
  244. }
  245. void ClearBit(s32 depth, size_t offset) {
  246. while (depth >= 0) {
  247. size_t ind = offset / Common::BitSize<u64>();
  248. size_t which = offset % Common::BitSize<u64>();
  249. const u64 mask = u64(1) << which;
  250. u64* bit = std::addressof(m_bit_storages[depth][ind]);
  251. u64 v = *bit;
  252. ASSERT((v & mask) != 0);
  253. v &= ~mask;
  254. *bit = v;
  255. if (v) {
  256. break;
  257. }
  258. offset = ind;
  259. depth--;
  260. }
  261. }
  262. private:
  263. static constexpr s32 GetRequiredDepth(size_t region_size) {
  264. s32 depth = 0;
  265. while (true) {
  266. region_size /= Common::BitSize<u64>();
  267. depth++;
  268. if (region_size == 0) {
  269. return depth;
  270. }
  271. }
  272. }
  273. public:
  274. static constexpr size_t CalculateManagementOverheadSize(size_t region_size) {
  275. size_t overhead_bits = 0;
  276. for (s32 depth = GetRequiredDepth(region_size) - 1; depth >= 0; depth--) {
  277. region_size =
  278. Common::AlignUp(region_size, Common::BitSize<u64>()) / Common::BitSize<u64>();
  279. overhead_bits += region_size;
  280. }
  281. return overhead_bits * sizeof(u64);
  282. }
  283. private:
  284. std::array<u64*, MaxDepth> m_bit_storages{};
  285. std::array<u64*, MaxDepth> m_end_storages{};
  286. RandomBitGenerator m_rng;
  287. size_t m_num_bits{};
  288. size_t m_used_depths{};
  289. };
  290. } // namespace Kernel