hbitmap.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955
  1. /*
  2. * Hierarchical Bitmap Data Type
  3. *
  4. * Copyright Red Hat, Inc., 2012
  5. *
  6. * Author: Paolo Bonzini <pbonzini@redhat.com>
  7. *
  8. * This work is licensed under the terms of the GNU GPL, version 2 or
  9. * later. See the COPYING file in the top-level directory.
  10. */
  11. #include "qemu/osdep.h"
  12. #include "qemu/hbitmap.h"
  13. #include "qemu/host-utils.h"
  14. #include "trace.h"
  15. #include "crypto/hash.h"
  16. /* HBitmaps provides an array of bits. The bits are stored as usual in an
  17. * array of unsigned longs, but HBitmap is also optimized to provide fast
  18. * iteration over set bits; going from one bit to the next is O(logB n)
  19. * worst case, with B = sizeof(long) * CHAR_BIT: the result is low enough
  20. * that the number of levels is in fact fixed.
  21. *
  22. * In order to do this, it stacks multiple bitmaps with progressively coarser
  23. * granularity; in all levels except the last, bit N is set iff the N-th
  24. * unsigned long is nonzero in the immediately next level. When iteration
  25. * completes on the last level it can examine the 2nd-last level to quickly
  26. * skip entire words, and even do so recursively to skip blocks of 64 words or
  27. * powers thereof (32 on 32-bit machines).
  28. *
  29. * Given an index in the bitmap, it can be split in group of bits like
  30. * this (for the 64-bit case):
  31. *
  32. * bits 0-57 => word in the last bitmap | bits 58-63 => bit in the word
  33. * bits 0-51 => word in the 2nd-last bitmap | bits 52-57 => bit in the word
  34. * bits 0-45 => word in the 3rd-last bitmap | bits 46-51 => bit in the word
  35. *
  36. * So it is easy to move up simply by shifting the index right by
  37. * log2(BITS_PER_LONG) bits. To move down, you shift the index left
  38. * similarly, and add the word index within the group. Iteration uses
  39. * ffs (find first set bit) to find the next word to examine; this
  40. * operation can be done in constant time in most current architectures.
  41. *
  42. * Setting or clearing a range of m bits on all levels, the work to perform
  43. * is O(m + m/W + m/W^2 + ...), which is O(m) like on a regular bitmap.
  44. *
  45. * When iterating on a bitmap, each bit (on any level) is only visited
  46. * once. Hence, The total cost of visiting a bitmap with m bits in it is
  47. * the number of bits that are set in all bitmaps. Unless the bitmap is
  48. * extremely sparse, this is also O(m + m/W + m/W^2 + ...), so the amortized
  49. * cost of advancing from one bit to the next is usually constant (worst case
  50. * O(logB n) as in the non-amortized complexity).
  51. */
  52. struct HBitmap {
  53. /*
  54. * Size of the bitmap, as requested in hbitmap_alloc or in hbitmap_truncate.
  55. */
  56. uint64_t orig_size;
  57. /* Number of total bits in the bottom level. */
  58. uint64_t size;
  59. /* Number of set bits in the bottom level. */
  60. uint64_t count;
  61. /* A scaling factor. Given a granularity of G, each bit in the bitmap will
  62. * will actually represent a group of 2^G elements. Each operation on a
  63. * range of bits first rounds the bits to determine which group they land
  64. * in, and then affect the entire page; iteration will only visit the first
  65. * bit of each group. Here is an example of operations in a size-16,
  66. * granularity-1 HBitmap:
  67. *
  68. * initial state 00000000
  69. * set(start=0, count=9) 11111000 (iter: 0, 2, 4, 6, 8)
  70. * reset(start=1, count=3) 00111000 (iter: 4, 6, 8)
  71. * set(start=9, count=2) 00111100 (iter: 4, 6, 8, 10)
  72. * reset(start=5, count=5) 00000000
  73. *
  74. * From an implementation point of view, when setting or resetting bits,
  75. * the bitmap will scale bit numbers right by this amount of bits. When
  76. * iterating, the bitmap will scale bit numbers left by this amount of
  77. * bits.
  78. */
  79. int granularity;
  80. /* A meta dirty bitmap to track the dirtiness of bits in this HBitmap. */
  81. HBitmap *meta;
  82. /* A number of progressively less coarse bitmaps (i.e. level 0 is the
  83. * coarsest). Each bit in level N represents a word in level N+1 that
  84. * has a set bit, except the last level where each bit represents the
  85. * actual bitmap.
  86. *
  87. * Note that all bitmaps have the same number of levels. Even a 1-bit
  88. * bitmap will still allocate HBITMAP_LEVELS arrays.
  89. */
  90. unsigned long *levels[HBITMAP_LEVELS];
  91. /* The length of each levels[] array. */
  92. uint64_t sizes[HBITMAP_LEVELS];
  93. };
  94. /* Advance hbi to the next nonzero word and return it. hbi->pos
  95. * is updated. Returns zero if we reach the end of the bitmap.
  96. */
  97. static unsigned long hbitmap_iter_skip_words(HBitmapIter *hbi)
  98. {
  99. size_t pos = hbi->pos;
  100. const HBitmap *hb = hbi->hb;
  101. unsigned i = HBITMAP_LEVELS - 1;
  102. unsigned long cur;
  103. do {
  104. i--;
  105. pos >>= BITS_PER_LEVEL;
  106. cur = hbi->cur[i] & hb->levels[i][pos];
  107. } while (cur == 0);
  108. /* Check for end of iteration. We always use fewer than BITS_PER_LONG
  109. * bits in the level 0 bitmap; thus we can repurpose the most significant
  110. * bit as a sentinel. The sentinel is set in hbitmap_alloc and ensures
  111. * that the above loop ends even without an explicit check on i.
  112. */
  113. if (i == 0 && cur == (1UL << (BITS_PER_LONG - 1))) {
  114. return 0;
  115. }
  116. for (; i < HBITMAP_LEVELS - 1; i++) {
  117. /* Shift back pos to the left, matching the right shifts above.
  118. * The index of this word's least significant set bit provides
  119. * the low-order bits.
  120. */
  121. assert(cur);
  122. pos = (pos << BITS_PER_LEVEL) + ctzl(cur);
  123. hbi->cur[i] = cur & (cur - 1);
  124. /* Set up next level for iteration. */
  125. cur = hb->levels[i + 1][pos];
  126. }
  127. hbi->pos = pos;
  128. trace_hbitmap_iter_skip_words(hbi->hb, hbi, pos, cur);
  129. assert(cur);
  130. return cur;
  131. }
  132. int64_t hbitmap_iter_next(HBitmapIter *hbi)
  133. {
  134. unsigned long cur = hbi->cur[HBITMAP_LEVELS - 1] &
  135. hbi->hb->levels[HBITMAP_LEVELS - 1][hbi->pos];
  136. int64_t item;
  137. if (cur == 0) {
  138. cur = hbitmap_iter_skip_words(hbi);
  139. if (cur == 0) {
  140. return -1;
  141. }
  142. }
  143. /* The next call will resume work from the next bit. */
  144. hbi->cur[HBITMAP_LEVELS - 1] = cur & (cur - 1);
  145. item = ((uint64_t)hbi->pos << BITS_PER_LEVEL) + ctzl(cur);
  146. return item << hbi->granularity;
  147. }
  148. void hbitmap_iter_init(HBitmapIter *hbi, const HBitmap *hb, uint64_t first)
  149. {
  150. unsigned i, bit;
  151. uint64_t pos;
  152. hbi->hb = hb;
  153. pos = first >> hb->granularity;
  154. assert(pos < hb->size);
  155. hbi->pos = pos >> BITS_PER_LEVEL;
  156. hbi->granularity = hb->granularity;
  157. for (i = HBITMAP_LEVELS; i-- > 0; ) {
  158. bit = pos & (BITS_PER_LONG - 1);
  159. pos >>= BITS_PER_LEVEL;
  160. /* Drop bits representing items before first. */
  161. hbi->cur[i] = hb->levels[i][pos] & ~((1UL << bit) - 1);
  162. /* We have already added level i+1, so the lowest set bit has
  163. * been processed. Clear it.
  164. */
  165. if (i != HBITMAP_LEVELS - 1) {
  166. hbi->cur[i] &= ~(1UL << bit);
  167. }
  168. }
  169. }
  170. int64_t hbitmap_next_dirty(const HBitmap *hb, int64_t start, int64_t count)
  171. {
  172. HBitmapIter hbi;
  173. int64_t first_dirty_off;
  174. uint64_t end;
  175. assert(start >= 0 && count >= 0);
  176. if (start >= hb->orig_size || count == 0) {
  177. return -1;
  178. }
  179. end = count > hb->orig_size - start ? hb->orig_size : start + count;
  180. hbitmap_iter_init(&hbi, hb, start);
  181. first_dirty_off = hbitmap_iter_next(&hbi);
  182. if (first_dirty_off < 0 || first_dirty_off >= end) {
  183. return -1;
  184. }
  185. return MAX(start, first_dirty_off);
  186. }
  187. int64_t hbitmap_next_zero(const HBitmap *hb, int64_t start, int64_t count)
  188. {
  189. size_t pos = (start >> hb->granularity) >> BITS_PER_LEVEL;
  190. unsigned long *last_lev = hb->levels[HBITMAP_LEVELS - 1];
  191. unsigned long cur = last_lev[pos];
  192. unsigned start_bit_offset;
  193. uint64_t end_bit, sz;
  194. int64_t res;
  195. assert(start >= 0 && count >= 0);
  196. if (start >= hb->orig_size || count == 0) {
  197. return -1;
  198. }
  199. end_bit = count > hb->orig_size - start ?
  200. hb->size :
  201. ((start + count - 1) >> hb->granularity) + 1;
  202. sz = (end_bit + BITS_PER_LONG - 1) >> BITS_PER_LEVEL;
  203. /* There may be some zero bits in @cur before @start. We are not interested
  204. * in them, let's set them.
  205. */
  206. start_bit_offset = (start >> hb->granularity) & (BITS_PER_LONG - 1);
  207. cur |= (1UL << start_bit_offset) - 1;
  208. assert((start >> hb->granularity) < hb->size);
  209. if (cur == (unsigned long)-1) {
  210. do {
  211. pos++;
  212. } while (pos < sz && last_lev[pos] == (unsigned long)-1);
  213. if (pos >= sz) {
  214. return -1;
  215. }
  216. cur = last_lev[pos];
  217. }
  218. res = (pos << BITS_PER_LEVEL) + ctol(cur);
  219. if (res >= end_bit) {
  220. return -1;
  221. }
  222. res = res << hb->granularity;
  223. if (res < start) {
  224. assert(((start - res) >> hb->granularity) == 0);
  225. return start;
  226. }
  227. return res;
  228. }
  229. bool hbitmap_next_dirty_area(const HBitmap *hb, int64_t start, int64_t end,
  230. int64_t max_dirty_count,
  231. int64_t *dirty_start, int64_t *dirty_count)
  232. {
  233. int64_t next_zero;
  234. assert(start >= 0 && end >= 0 && max_dirty_count > 0);
  235. end = MIN(end, hb->orig_size);
  236. if (start >= end) {
  237. return false;
  238. }
  239. start = hbitmap_next_dirty(hb, start, end - start);
  240. if (start < 0) {
  241. return false;
  242. }
  243. end = start + MIN(end - start, max_dirty_count);
  244. next_zero = hbitmap_next_zero(hb, start, end - start);
  245. if (next_zero >= 0) {
  246. end = next_zero;
  247. }
  248. *dirty_start = start;
  249. *dirty_count = end - start;
  250. return true;
  251. }
  252. bool hbitmap_status(const HBitmap *hb, int64_t start, int64_t count,
  253. int64_t *pnum)
  254. {
  255. int64_t next_dirty, next_zero;
  256. assert(start >= 0);
  257. assert(count > 0);
  258. assert(start + count <= hb->orig_size);
  259. next_dirty = hbitmap_next_dirty(hb, start, count);
  260. if (next_dirty == -1) {
  261. *pnum = count;
  262. return false;
  263. }
  264. if (next_dirty > start) {
  265. *pnum = next_dirty - start;
  266. return false;
  267. }
  268. assert(next_dirty == start);
  269. next_zero = hbitmap_next_zero(hb, start, count);
  270. if (next_zero == -1) {
  271. *pnum = count;
  272. return true;
  273. }
  274. assert(next_zero > start);
  275. *pnum = next_zero - start;
  276. return true;
  277. }
  278. bool hbitmap_empty(const HBitmap *hb)
  279. {
  280. return hb->count == 0;
  281. }
  282. int hbitmap_granularity(const HBitmap *hb)
  283. {
  284. return hb->granularity;
  285. }
  286. uint64_t hbitmap_count(const HBitmap *hb)
  287. {
  288. return hb->count << hb->granularity;
  289. }
  290. /**
  291. * hbitmap_iter_next_word:
  292. * @hbi: HBitmapIter to operate on.
  293. * @p_cur: Location where to store the next non-zero word.
  294. *
  295. * Return the index of the next nonzero word that is set in @hbi's
  296. * associated HBitmap, and set *p_cur to the content of that word
  297. * (bits before the index that was passed to hbitmap_iter_init are
  298. * trimmed on the first call). Return -1, and set *p_cur to zero,
  299. * if all remaining words are zero.
  300. */
  301. static size_t hbitmap_iter_next_word(HBitmapIter *hbi, unsigned long *p_cur)
  302. {
  303. unsigned long cur = hbi->cur[HBITMAP_LEVELS - 1];
  304. if (cur == 0) {
  305. cur = hbitmap_iter_skip_words(hbi);
  306. if (cur == 0) {
  307. *p_cur = 0;
  308. return -1;
  309. }
  310. }
  311. /* The next call will resume work from the next word. */
  312. hbi->cur[HBITMAP_LEVELS - 1] = 0;
  313. *p_cur = cur;
  314. return hbi->pos;
  315. }
  316. /* Count the number of set bits between start and end, not accounting for
  317. * the granularity. Also an example of how to use hbitmap_iter_next_word.
  318. */
  319. static uint64_t hb_count_between(HBitmap *hb, uint64_t start, uint64_t last)
  320. {
  321. HBitmapIter hbi;
  322. uint64_t count = 0;
  323. uint64_t end = last + 1;
  324. unsigned long cur;
  325. size_t pos;
  326. hbitmap_iter_init(&hbi, hb, start << hb->granularity);
  327. for (;;) {
  328. pos = hbitmap_iter_next_word(&hbi, &cur);
  329. if (pos >= (end >> BITS_PER_LEVEL)) {
  330. break;
  331. }
  332. count += ctpopl(cur);
  333. }
  334. if (pos == (end >> BITS_PER_LEVEL)) {
  335. /* Drop bits representing the END-th and subsequent items. */
  336. int bit = end & (BITS_PER_LONG - 1);
  337. cur &= (1UL << bit) - 1;
  338. count += ctpopl(cur);
  339. }
  340. return count;
  341. }
  342. /* Setting starts at the last layer and propagates up if an element
  343. * changes.
  344. */
  345. static inline bool hb_set_elem(unsigned long *elem, uint64_t start, uint64_t last)
  346. {
  347. unsigned long mask;
  348. unsigned long old;
  349. assert((last >> BITS_PER_LEVEL) == (start >> BITS_PER_LEVEL));
  350. assert(start <= last);
  351. mask = 2UL << (last & (BITS_PER_LONG - 1));
  352. mask -= 1UL << (start & (BITS_PER_LONG - 1));
  353. old = *elem;
  354. *elem |= mask;
  355. return old != *elem;
  356. }
  357. /* The recursive workhorse (the depth is limited to HBITMAP_LEVELS)...
  358. * Returns true if at least one bit is changed. */
  359. static bool hb_set_between(HBitmap *hb, int level, uint64_t start,
  360. uint64_t last)
  361. {
  362. size_t pos = start >> BITS_PER_LEVEL;
  363. size_t lastpos = last >> BITS_PER_LEVEL;
  364. bool changed = false;
  365. size_t i;
  366. i = pos;
  367. if (i < lastpos) {
  368. uint64_t next = (start | (BITS_PER_LONG - 1)) + 1;
  369. changed |= hb_set_elem(&hb->levels[level][i], start, next - 1);
  370. for (;;) {
  371. start = next;
  372. next += BITS_PER_LONG;
  373. if (++i == lastpos) {
  374. break;
  375. }
  376. changed |= (hb->levels[level][i] == 0);
  377. hb->levels[level][i] = ~0UL;
  378. }
  379. }
  380. changed |= hb_set_elem(&hb->levels[level][i], start, last);
  381. /* If there was any change in this layer, we may have to update
  382. * the one above.
  383. */
  384. if (level > 0 && changed) {
  385. hb_set_between(hb, level - 1, pos, lastpos);
  386. }
  387. return changed;
  388. }
  389. void hbitmap_set(HBitmap *hb, uint64_t start, uint64_t count)
  390. {
  391. /* Compute range in the last layer. */
  392. uint64_t first, n;
  393. uint64_t last = start + count - 1;
  394. if (count == 0) {
  395. return;
  396. }
  397. trace_hbitmap_set(hb, start, count,
  398. start >> hb->granularity, last >> hb->granularity);
  399. first = start >> hb->granularity;
  400. last >>= hb->granularity;
  401. assert(last < hb->size);
  402. n = last - first + 1;
  403. hb->count += n - hb_count_between(hb, first, last);
  404. if (hb_set_between(hb, HBITMAP_LEVELS - 1, first, last) &&
  405. hb->meta) {
  406. hbitmap_set(hb->meta, start, count);
  407. }
  408. }
  409. /* Resetting works the other way round: propagate up if the new
  410. * value is zero.
  411. */
  412. static inline bool hb_reset_elem(unsigned long *elem, uint64_t start, uint64_t last)
  413. {
  414. unsigned long mask;
  415. bool blanked;
  416. assert((last >> BITS_PER_LEVEL) == (start >> BITS_PER_LEVEL));
  417. assert(start <= last);
  418. mask = 2UL << (last & (BITS_PER_LONG - 1));
  419. mask -= 1UL << (start & (BITS_PER_LONG - 1));
  420. blanked = *elem != 0 && ((*elem & ~mask) == 0);
  421. *elem &= ~mask;
  422. return blanked;
  423. }
  424. /* The recursive workhorse (the depth is limited to HBITMAP_LEVELS)...
  425. * Returns true if at least one bit is changed. */
  426. static bool hb_reset_between(HBitmap *hb, int level, uint64_t start,
  427. uint64_t last)
  428. {
  429. size_t pos = start >> BITS_PER_LEVEL;
  430. size_t lastpos = last >> BITS_PER_LEVEL;
  431. bool changed = false;
  432. size_t i;
  433. i = pos;
  434. if (i < lastpos) {
  435. uint64_t next = (start | (BITS_PER_LONG - 1)) + 1;
  436. /* Here we need a more complex test than when setting bits. Even if
  437. * something was changed, we must not blank bits in the upper level
  438. * unless the lower-level word became entirely zero. So, remove pos
  439. * from the upper-level range if bits remain set.
  440. */
  441. if (hb_reset_elem(&hb->levels[level][i], start, next - 1)) {
  442. changed = true;
  443. } else {
  444. pos++;
  445. }
  446. for (;;) {
  447. start = next;
  448. next += BITS_PER_LONG;
  449. if (++i == lastpos) {
  450. break;
  451. }
  452. changed |= (hb->levels[level][i] != 0);
  453. hb->levels[level][i] = 0UL;
  454. }
  455. }
  456. /* Same as above, this time for lastpos. */
  457. if (hb_reset_elem(&hb->levels[level][i], start, last)) {
  458. changed = true;
  459. } else {
  460. lastpos--;
  461. }
  462. if (level > 0 && changed) {
  463. hb_reset_between(hb, level - 1, pos, lastpos);
  464. }
  465. return changed;
  466. }
  467. void hbitmap_reset(HBitmap *hb, uint64_t start, uint64_t count)
  468. {
  469. /* Compute range in the last layer. */
  470. uint64_t first;
  471. uint64_t last = start + count - 1;
  472. uint64_t gran = 1ULL << hb->granularity;
  473. if (count == 0) {
  474. return;
  475. }
  476. assert(QEMU_IS_ALIGNED(start, gran));
  477. assert(QEMU_IS_ALIGNED(count, gran) || (start + count == hb->orig_size));
  478. trace_hbitmap_reset(hb, start, count,
  479. start >> hb->granularity, last >> hb->granularity);
  480. first = start >> hb->granularity;
  481. last >>= hb->granularity;
  482. assert(last < hb->size);
  483. hb->count -= hb_count_between(hb, first, last);
  484. if (hb_reset_between(hb, HBITMAP_LEVELS - 1, first, last) &&
  485. hb->meta) {
  486. hbitmap_set(hb->meta, start, count);
  487. }
  488. }
  489. void hbitmap_reset_all(HBitmap *hb)
  490. {
  491. unsigned int i;
  492. /* Same as hbitmap_alloc() except for memset() instead of malloc() */
  493. for (i = HBITMAP_LEVELS; --i >= 1; ) {
  494. memset(hb->levels[i], 0, hb->sizes[i] * sizeof(unsigned long));
  495. }
  496. hb->levels[0][0] = 1UL << (BITS_PER_LONG - 1);
  497. hb->count = 0;
  498. }
  499. bool hbitmap_is_serializable(const HBitmap *hb)
  500. {
  501. /* Every serialized chunk must be aligned to 64 bits so that endianness
  502. * requirements can be fulfilled on both 64 bit and 32 bit hosts.
  503. * We have hbitmap_serialization_align() which converts this
  504. * alignment requirement from bitmap bits to items covered (e.g. sectors).
  505. * That value is:
  506. * 64 << hb->granularity
  507. * Since this value must not exceed UINT64_MAX, hb->granularity must be
  508. * less than 58 (== 64 - 6, where 6 is ld(64), i.e. 1 << 6 == 64).
  509. *
  510. * In order for hbitmap_serialization_align() to always return a
  511. * meaningful value, bitmaps that are to be serialized must have a
  512. * granularity of less than 58. */
  513. return hb->granularity < 58;
  514. }
  515. bool hbitmap_get(const HBitmap *hb, uint64_t item)
  516. {
  517. /* Compute position and bit in the last layer. */
  518. uint64_t pos = item >> hb->granularity;
  519. unsigned long bit = 1UL << (pos & (BITS_PER_LONG - 1));
  520. assert(pos < hb->size);
  521. return (hb->levels[HBITMAP_LEVELS - 1][pos >> BITS_PER_LEVEL] & bit) != 0;
  522. }
  523. uint64_t hbitmap_serialization_align(const HBitmap *hb)
  524. {
  525. assert(hbitmap_is_serializable(hb));
  526. /* Require at least 64 bit granularity to be safe on both 64 bit and 32 bit
  527. * hosts. */
  528. return UINT64_C(64) << hb->granularity;
  529. }
  530. /* Start should be aligned to serialization granularity, chunk size should be
  531. * aligned to serialization granularity too, except for last chunk.
  532. */
  533. static void serialization_chunk(const HBitmap *hb,
  534. uint64_t start, uint64_t count,
  535. unsigned long **first_el, uint64_t *el_count)
  536. {
  537. uint64_t last = start + count - 1;
  538. uint64_t gran = hbitmap_serialization_align(hb);
  539. assert((start & (gran - 1)) == 0);
  540. assert((last >> hb->granularity) < hb->size);
  541. if ((last >> hb->granularity) != hb->size - 1) {
  542. assert((count & (gran - 1)) == 0);
  543. }
  544. start = (start >> hb->granularity) >> BITS_PER_LEVEL;
  545. last = (last >> hb->granularity) >> BITS_PER_LEVEL;
  546. *first_el = &hb->levels[HBITMAP_LEVELS - 1][start];
  547. *el_count = last - start + 1;
  548. }
  549. uint64_t hbitmap_serialization_size(const HBitmap *hb,
  550. uint64_t start, uint64_t count)
  551. {
  552. uint64_t el_count;
  553. unsigned long *cur;
  554. if (!count) {
  555. return 0;
  556. }
  557. serialization_chunk(hb, start, count, &cur, &el_count);
  558. return el_count * sizeof(unsigned long);
  559. }
  560. void hbitmap_serialize_part(const HBitmap *hb, uint8_t *buf,
  561. uint64_t start, uint64_t count)
  562. {
  563. uint64_t el_count;
  564. unsigned long *cur, *end;
  565. if (!count) {
  566. return;
  567. }
  568. serialization_chunk(hb, start, count, &cur, &el_count);
  569. end = cur + el_count;
  570. while (cur != end) {
  571. unsigned long el =
  572. (BITS_PER_LONG == 32 ? cpu_to_le32(*cur) : cpu_to_le64(*cur));
  573. memcpy(buf, &el, sizeof(el));
  574. buf += sizeof(el);
  575. cur++;
  576. }
  577. }
  578. void hbitmap_deserialize_part(HBitmap *hb, uint8_t *buf,
  579. uint64_t start, uint64_t count,
  580. bool finish)
  581. {
  582. uint64_t el_count;
  583. unsigned long *cur, *end;
  584. if (!count) {
  585. return;
  586. }
  587. serialization_chunk(hb, start, count, &cur, &el_count);
  588. end = cur + el_count;
  589. while (cur != end) {
  590. memcpy(cur, buf, sizeof(*cur));
  591. if (BITS_PER_LONG == 32) {
  592. le32_to_cpus((uint32_t *)cur);
  593. } else {
  594. le64_to_cpus((uint64_t *)cur);
  595. }
  596. buf += sizeof(unsigned long);
  597. cur++;
  598. }
  599. if (finish) {
  600. hbitmap_deserialize_finish(hb);
  601. }
  602. }
  603. void hbitmap_deserialize_zeroes(HBitmap *hb, uint64_t start, uint64_t count,
  604. bool finish)
  605. {
  606. uint64_t el_count;
  607. unsigned long *first;
  608. if (!count) {
  609. return;
  610. }
  611. serialization_chunk(hb, start, count, &first, &el_count);
  612. memset(first, 0, el_count * sizeof(unsigned long));
  613. if (finish) {
  614. hbitmap_deserialize_finish(hb);
  615. }
  616. }
  617. void hbitmap_deserialize_ones(HBitmap *hb, uint64_t start, uint64_t count,
  618. bool finish)
  619. {
  620. uint64_t el_count;
  621. unsigned long *first;
  622. if (!count) {
  623. return;
  624. }
  625. serialization_chunk(hb, start, count, &first, &el_count);
  626. memset(first, 0xff, el_count * sizeof(unsigned long));
  627. if (finish) {
  628. hbitmap_deserialize_finish(hb);
  629. }
  630. }
  631. void hbitmap_deserialize_finish(HBitmap *bitmap)
  632. {
  633. int64_t i, size, prev_size;
  634. int lev;
  635. /* restore levels starting from penultimate to zero level, assuming
  636. * that the last level is ok */
  637. size = MAX((bitmap->size + BITS_PER_LONG - 1) >> BITS_PER_LEVEL, 1);
  638. for (lev = HBITMAP_LEVELS - 1; lev-- > 0; ) {
  639. prev_size = size;
  640. size = MAX((size + BITS_PER_LONG - 1) >> BITS_PER_LEVEL, 1);
  641. memset(bitmap->levels[lev], 0, size * sizeof(unsigned long));
  642. for (i = 0; i < prev_size; ++i) {
  643. if (bitmap->levels[lev + 1][i]) {
  644. bitmap->levels[lev][i >> BITS_PER_LEVEL] |=
  645. 1UL << (i & (BITS_PER_LONG - 1));
  646. }
  647. }
  648. }
  649. bitmap->levels[0][0] |= 1UL << (BITS_PER_LONG - 1);
  650. bitmap->count = hb_count_between(bitmap, 0, bitmap->size - 1);
  651. }
  652. void hbitmap_free(HBitmap *hb)
  653. {
  654. unsigned i;
  655. assert(!hb->meta);
  656. for (i = HBITMAP_LEVELS; i-- > 0; ) {
  657. g_free(hb->levels[i]);
  658. }
  659. g_free(hb);
  660. }
  661. HBitmap *hbitmap_alloc(uint64_t size, int granularity)
  662. {
  663. HBitmap *hb = g_new0(struct HBitmap, 1);
  664. unsigned i;
  665. assert(size <= INT64_MAX);
  666. hb->orig_size = size;
  667. assert(granularity >= 0 && granularity < 64);
  668. size = (size + (1ULL << granularity) - 1) >> granularity;
  669. assert(size <= ((uint64_t)1 << HBITMAP_LOG_MAX_SIZE));
  670. hb->size = size;
  671. hb->granularity = granularity;
  672. for (i = HBITMAP_LEVELS; i-- > 0; ) {
  673. size = MAX((size + BITS_PER_LONG - 1) >> BITS_PER_LEVEL, 1);
  674. hb->sizes[i] = size;
  675. hb->levels[i] = g_new0(unsigned long, size);
  676. }
  677. /* We necessarily have free bits in level 0 due to the definition
  678. * of HBITMAP_LEVELS, so use one for a sentinel. This speeds up
  679. * hbitmap_iter_skip_words.
  680. */
  681. assert(size == 1);
  682. hb->levels[0][0] |= 1UL << (BITS_PER_LONG - 1);
  683. return hb;
  684. }
  685. void hbitmap_truncate(HBitmap *hb, uint64_t size)
  686. {
  687. bool shrink;
  688. unsigned i;
  689. uint64_t num_elements = size;
  690. uint64_t old;
  691. assert(size <= INT64_MAX);
  692. hb->orig_size = size;
  693. /* Size comes in as logical elements, adjust for granularity. */
  694. size = (size + (1ULL << hb->granularity) - 1) >> hb->granularity;
  695. assert(size <= ((uint64_t)1 << HBITMAP_LOG_MAX_SIZE));
  696. shrink = size < hb->size;
  697. /* bit sizes are identical; nothing to do. */
  698. if (size == hb->size) {
  699. return;
  700. }
  701. /* If we're losing bits, let's clear those bits before we invalidate all of
  702. * our invariants. This helps keep the bitcount consistent, and will prevent
  703. * us from carrying around garbage bits beyond the end of the map.
  704. */
  705. if (shrink) {
  706. /* Don't clear partial granularity groups;
  707. * start at the first full one. */
  708. uint64_t start = ROUND_UP(num_elements, UINT64_C(1) << hb->granularity);
  709. uint64_t fix_count = (hb->size << hb->granularity) - start;
  710. assert(fix_count);
  711. hbitmap_reset(hb, start, fix_count);
  712. }
  713. hb->size = size;
  714. for (i = HBITMAP_LEVELS; i-- > 0; ) {
  715. size = MAX(BITS_TO_LONGS(size), 1);
  716. if (hb->sizes[i] == size) {
  717. break;
  718. }
  719. old = hb->sizes[i];
  720. hb->sizes[i] = size;
  721. hb->levels[i] = g_renew(unsigned long, hb->levels[i], size);
  722. if (!shrink) {
  723. memset(&hb->levels[i][old], 0x00,
  724. (size - old) * sizeof(*hb->levels[i]));
  725. }
  726. }
  727. if (hb->meta) {
  728. hbitmap_truncate(hb->meta, hb->size << hb->granularity);
  729. }
  730. }
  731. /**
  732. * hbitmap_sparse_merge: performs dst = dst | src
  733. * works with differing granularities.
  734. * best used when src is sparsely populated.
  735. */
  736. static void hbitmap_sparse_merge(HBitmap *dst, const HBitmap *src)
  737. {
  738. int64_t offset;
  739. int64_t count;
  740. for (offset = 0;
  741. hbitmap_next_dirty_area(src, offset, src->orig_size, INT64_MAX,
  742. &offset, &count);
  743. offset += count)
  744. {
  745. hbitmap_set(dst, offset, count);
  746. }
  747. }
  748. /**
  749. * Given HBitmaps A and B, let R := A (BITOR) B.
  750. * Bitmaps A and B will not be modified,
  751. * except when bitmap R is an alias of A or B.
  752. * Bitmaps must have same size.
  753. */
  754. void hbitmap_merge(const HBitmap *a, const HBitmap *b, HBitmap *result)
  755. {
  756. int i;
  757. uint64_t j;
  758. assert(a->orig_size == result->orig_size);
  759. assert(b->orig_size == result->orig_size);
  760. if ((!hbitmap_count(a) && result == b) ||
  761. (!hbitmap_count(b) && result == a)) {
  762. return;
  763. }
  764. if (!hbitmap_count(a) && !hbitmap_count(b)) {
  765. hbitmap_reset_all(result);
  766. return;
  767. }
  768. if (a->granularity != b->granularity) {
  769. if ((a != result) && (b != result)) {
  770. hbitmap_reset_all(result);
  771. }
  772. if (a != result) {
  773. hbitmap_sparse_merge(result, a);
  774. }
  775. if (b != result) {
  776. hbitmap_sparse_merge(result, b);
  777. }
  778. return;
  779. }
  780. /* This merge is O(size), as BITS_PER_LONG and HBITMAP_LEVELS are constant.
  781. * It may be possible to improve running times for sparsely populated maps
  782. * by using hbitmap_iter_next, but this is suboptimal for dense maps.
  783. */
  784. assert(a->size == b->size);
  785. for (i = HBITMAP_LEVELS - 1; i >= 0; i--) {
  786. for (j = 0; j < a->sizes[i]; j++) {
  787. result->levels[i][j] = a->levels[i][j] | b->levels[i][j];
  788. }
  789. }
  790. /* Recompute the dirty count */
  791. result->count = hb_count_between(result, 0, result->size - 1);
  792. }
  793. char *hbitmap_sha256(const HBitmap *bitmap, Error **errp)
  794. {
  795. size_t size = bitmap->sizes[HBITMAP_LEVELS - 1] * sizeof(unsigned long);
  796. char *data = (char *)bitmap->levels[HBITMAP_LEVELS - 1];
  797. char *hash = NULL;
  798. qcrypto_hash_digest(QCRYPTO_HASH_ALGO_SHA256, data, size, &hash, errp);
  799. return hash;
  800. }