dirty-bitmap: add bdrv_dirty_bitmap_next_dirty_area
[qemu/ar7.git] / util / hbitmap.c
blobfa356522c4fafa475f9cef8210a6b80bba7f9f26
1 /*
2 * Hierarchical Bitmap Data Type
4 * Copyright Red Hat, Inc., 2012
6 * Author: Paolo Bonzini <pbonzini@redhat.com>
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.
12 #include "qemu/osdep.h"
13 #include "qemu/hbitmap.h"
14 #include "qemu/host-utils.h"
15 #include "trace.h"
16 #include "crypto/hash.h"
18 /* HBitmaps provides an array of bits. The bits are stored as usual in an
19 * array of unsigned longs, but HBitmap is also optimized to provide fast
20 * iteration over set bits; going from one bit to the next is O(logB n)
21 * worst case, with B = sizeof(long) * CHAR_BIT: the result is low enough
22 * that the number of levels is in fact fixed.
24 * In order to do this, it stacks multiple bitmaps with progressively coarser
25 * granularity; in all levels except the last, bit N is set iff the N-th
26 * unsigned long is nonzero in the immediately next level. When iteration
27 * completes on the last level it can examine the 2nd-last level to quickly
28 * skip entire words, and even do so recursively to skip blocks of 64 words or
29 * powers thereof (32 on 32-bit machines).
31 * Given an index in the bitmap, it can be split in group of bits like
32 * this (for the 64-bit case):
34 * bits 0-57 => word in the last bitmap | bits 58-63 => bit in the word
35 * bits 0-51 => word in the 2nd-last bitmap | bits 52-57 => bit in the word
36 * bits 0-45 => word in the 3rd-last bitmap | bits 46-51 => bit in the word
38 * So it is easy to move up simply by shifting the index right by
39 * log2(BITS_PER_LONG) bits. To move down, you shift the index left
40 * similarly, and add the word index within the group. Iteration uses
41 * ffs (find first set bit) to find the next word to examine; this
42 * operation can be done in constant time in most current architectures.
44 * Setting or clearing a range of m bits on all levels, the work to perform
45 * is O(m + m/W + m/W^2 + ...), which is O(m) like on a regular bitmap.
47 * When iterating on a bitmap, each bit (on any level) is only visited
48 * once. Hence, The total cost of visiting a bitmap with m bits in it is
49 * the number of bits that are set in all bitmaps. Unless the bitmap is
50 * extremely sparse, this is also O(m + m/W + m/W^2 + ...), so the amortized
51 * cost of advancing from one bit to the next is usually constant (worst case
52 * O(logB n) as in the non-amortized complexity).
55 struct HBitmap {
56 /* Size of the bitmap, as requested in hbitmap_alloc. */
57 uint64_t orig_size;
59 /* Number of total bits in the bottom level. */
60 uint64_t size;
62 /* Number of set bits in the bottom level. */
63 uint64_t count;
65 /* A scaling factor. Given a granularity of G, each bit in the bitmap will
66 * will actually represent a group of 2^G elements. Each operation on a
67 * range of bits first rounds the bits to determine which group they land
68 * in, and then affect the entire page; iteration will only visit the first
69 * bit of each group. Here is an example of operations in a size-16,
70 * granularity-1 HBitmap:
72 * initial state 00000000
73 * set(start=0, count=9) 11111000 (iter: 0, 2, 4, 6, 8)
74 * reset(start=1, count=3) 00111000 (iter: 4, 6, 8)
75 * set(start=9, count=2) 00111100 (iter: 4, 6, 8, 10)
76 * reset(start=5, count=5) 00000000
78 * From an implementation point of view, when setting or resetting bits,
79 * the bitmap will scale bit numbers right by this amount of bits. When
80 * iterating, the bitmap will scale bit numbers left by this amount of
81 * bits.
83 int granularity;
85 /* A meta dirty bitmap to track the dirtiness of bits in this HBitmap. */
86 HBitmap *meta;
88 /* A number of progressively less coarse bitmaps (i.e. level 0 is the
89 * coarsest). Each bit in level N represents a word in level N+1 that
90 * has a set bit, except the last level where each bit represents the
91 * actual bitmap.
93 * Note that all bitmaps have the same number of levels. Even a 1-bit
94 * bitmap will still allocate HBITMAP_LEVELS arrays.
96 unsigned long *levels[HBITMAP_LEVELS];
98 /* The length of each levels[] array. */
99 uint64_t sizes[HBITMAP_LEVELS];
102 /* Advance hbi to the next nonzero word and return it. hbi->pos
103 * is updated. Returns zero if we reach the end of the bitmap.
105 unsigned long hbitmap_iter_skip_words(HBitmapIter *hbi)
107 size_t pos = hbi->pos;
108 const HBitmap *hb = hbi->hb;
109 unsigned i = HBITMAP_LEVELS - 1;
111 unsigned long cur;
112 do {
113 i--;
114 pos >>= BITS_PER_LEVEL;
115 cur = hbi->cur[i] & hb->levels[i][pos];
116 } while (cur == 0);
118 /* Check for end of iteration. We always use fewer than BITS_PER_LONG
119 * bits in the level 0 bitmap; thus we can repurpose the most significant
120 * bit as a sentinel. The sentinel is set in hbitmap_alloc and ensures
121 * that the above loop ends even without an explicit check on i.
124 if (i == 0 && cur == (1UL << (BITS_PER_LONG - 1))) {
125 return 0;
127 for (; i < HBITMAP_LEVELS - 1; i++) {
128 /* Shift back pos to the left, matching the right shifts above.
129 * The index of this word's least significant set bit provides
130 * the low-order bits.
132 assert(cur);
133 pos = (pos << BITS_PER_LEVEL) + ctzl(cur);
134 hbi->cur[i] = cur & (cur - 1);
136 /* Set up next level for iteration. */
137 cur = hb->levels[i + 1][pos];
140 hbi->pos = pos;
141 trace_hbitmap_iter_skip_words(hbi->hb, hbi, pos, cur);
143 assert(cur);
144 return cur;
147 int64_t hbitmap_iter_next(HBitmapIter *hbi, bool advance)
149 unsigned long cur = hbi->cur[HBITMAP_LEVELS - 1] &
150 hbi->hb->levels[HBITMAP_LEVELS - 1][hbi->pos];
151 int64_t item;
153 if (cur == 0) {
154 cur = hbitmap_iter_skip_words(hbi);
155 if (cur == 0) {
156 return -1;
160 if (advance) {
161 /* The next call will resume work from the next bit. */
162 hbi->cur[HBITMAP_LEVELS - 1] = cur & (cur - 1);
163 } else {
164 hbi->cur[HBITMAP_LEVELS - 1] = cur;
166 item = ((uint64_t)hbi->pos << BITS_PER_LEVEL) + ctzl(cur);
168 return item << hbi->granularity;
171 void hbitmap_iter_init(HBitmapIter *hbi, const HBitmap *hb, uint64_t first)
173 unsigned i, bit;
174 uint64_t pos;
176 hbi->hb = hb;
177 pos = first >> hb->granularity;
178 assert(pos < hb->size);
179 hbi->pos = pos >> BITS_PER_LEVEL;
180 hbi->granularity = hb->granularity;
182 for (i = HBITMAP_LEVELS; i-- > 0; ) {
183 bit = pos & (BITS_PER_LONG - 1);
184 pos >>= BITS_PER_LEVEL;
186 /* Drop bits representing items before first. */
187 hbi->cur[i] = hb->levels[i][pos] & ~((1UL << bit) - 1);
189 /* We have already added level i+1, so the lowest set bit has
190 * been processed. Clear it.
192 if (i != HBITMAP_LEVELS - 1) {
193 hbi->cur[i] &= ~(1UL << bit);
198 int64_t hbitmap_next_zero(const HBitmap *hb, uint64_t start, uint64_t count)
200 size_t pos = (start >> hb->granularity) >> BITS_PER_LEVEL;
201 unsigned long *last_lev = hb->levels[HBITMAP_LEVELS - 1];
202 unsigned long cur = last_lev[pos];
203 unsigned start_bit_offset;
204 uint64_t end_bit, sz;
205 int64_t res;
207 if (start >= hb->orig_size || count == 0) {
208 return -1;
211 end_bit = count > hb->orig_size - start ?
212 hb->size :
213 ((start + count - 1) >> hb->granularity) + 1;
214 sz = (end_bit + BITS_PER_LONG - 1) >> BITS_PER_LEVEL;
216 /* There may be some zero bits in @cur before @start. We are not interested
217 * in them, let's set them.
219 start_bit_offset = (start >> hb->granularity) & (BITS_PER_LONG - 1);
220 cur |= (1UL << start_bit_offset) - 1;
221 assert((start >> hb->granularity) < hb->size);
223 if (cur == (unsigned long)-1) {
224 do {
225 pos++;
226 } while (pos < sz && last_lev[pos] == (unsigned long)-1);
228 if (pos >= sz) {
229 return -1;
232 cur = last_lev[pos];
235 res = (pos << BITS_PER_LEVEL) + ctol(cur);
236 if (res >= end_bit) {
237 return -1;
240 res = res << hb->granularity;
241 if (res < start) {
242 assert(((start - res) >> hb->granularity) == 0);
243 return start;
246 return res;
249 bool hbitmap_next_dirty_area(const HBitmap *hb, uint64_t *start,
250 uint64_t *count)
252 HBitmapIter hbi;
253 int64_t firt_dirty_off, area_end;
254 uint32_t granularity = 1UL << hb->granularity;
255 uint64_t end;
257 if (*start >= hb->orig_size || *count == 0) {
258 return false;
261 end = *count > hb->orig_size - *start ? hb->orig_size : *start + *count;
263 hbitmap_iter_init(&hbi, hb, *start);
264 firt_dirty_off = hbitmap_iter_next(&hbi, false);
266 if (firt_dirty_off < 0 || firt_dirty_off >= end) {
267 return false;
270 if (firt_dirty_off + granularity >= end) {
271 area_end = end;
272 } else {
273 area_end = hbitmap_next_zero(hb, firt_dirty_off + granularity,
274 end - firt_dirty_off - granularity);
275 if (area_end < 0) {
276 area_end = end;
280 if (firt_dirty_off > *start) {
281 *start = firt_dirty_off;
283 *count = area_end - *start;
285 return true;
288 bool hbitmap_empty(const HBitmap *hb)
290 return hb->count == 0;
293 int hbitmap_granularity(const HBitmap *hb)
295 return hb->granularity;
298 uint64_t hbitmap_count(const HBitmap *hb)
300 return hb->count << hb->granularity;
303 /* Count the number of set bits between start and end, not accounting for
304 * the granularity. Also an example of how to use hbitmap_iter_next_word.
306 static uint64_t hb_count_between(HBitmap *hb, uint64_t start, uint64_t last)
308 HBitmapIter hbi;
309 uint64_t count = 0;
310 uint64_t end = last + 1;
311 unsigned long cur;
312 size_t pos;
314 hbitmap_iter_init(&hbi, hb, start << hb->granularity);
315 for (;;) {
316 pos = hbitmap_iter_next_word(&hbi, &cur);
317 if (pos >= (end >> BITS_PER_LEVEL)) {
318 break;
320 count += ctpopl(cur);
323 if (pos == (end >> BITS_PER_LEVEL)) {
324 /* Drop bits representing the END-th and subsequent items. */
325 int bit = end & (BITS_PER_LONG - 1);
326 cur &= (1UL << bit) - 1;
327 count += ctpopl(cur);
330 return count;
333 /* Setting starts at the last layer and propagates up if an element
334 * changes.
336 static inline bool hb_set_elem(unsigned long *elem, uint64_t start, uint64_t last)
338 unsigned long mask;
339 unsigned long old;
341 assert((last >> BITS_PER_LEVEL) == (start >> BITS_PER_LEVEL));
342 assert(start <= last);
344 mask = 2UL << (last & (BITS_PER_LONG - 1));
345 mask -= 1UL << (start & (BITS_PER_LONG - 1));
346 old = *elem;
347 *elem |= mask;
348 return old != *elem;
351 /* The recursive workhorse (the depth is limited to HBITMAP_LEVELS)...
352 * Returns true if at least one bit is changed. */
353 static bool hb_set_between(HBitmap *hb, int level, uint64_t start,
354 uint64_t last)
356 size_t pos = start >> BITS_PER_LEVEL;
357 size_t lastpos = last >> BITS_PER_LEVEL;
358 bool changed = false;
359 size_t i;
361 i = pos;
362 if (i < lastpos) {
363 uint64_t next = (start | (BITS_PER_LONG - 1)) + 1;
364 changed |= hb_set_elem(&hb->levels[level][i], start, next - 1);
365 for (;;) {
366 start = next;
367 next += BITS_PER_LONG;
368 if (++i == lastpos) {
369 break;
371 changed |= (hb->levels[level][i] == 0);
372 hb->levels[level][i] = ~0UL;
375 changed |= hb_set_elem(&hb->levels[level][i], start, last);
377 /* If there was any change in this layer, we may have to update
378 * the one above.
380 if (level > 0 && changed) {
381 hb_set_between(hb, level - 1, pos, lastpos);
383 return changed;
386 void hbitmap_set(HBitmap *hb, uint64_t start, uint64_t count)
388 /* Compute range in the last layer. */
389 uint64_t first, n;
390 uint64_t last = start + count - 1;
392 trace_hbitmap_set(hb, start, count,
393 start >> hb->granularity, last >> hb->granularity);
395 first = start >> hb->granularity;
396 last >>= hb->granularity;
397 assert(last < hb->size);
398 n = last - first + 1;
400 hb->count += n - hb_count_between(hb, first, last);
401 if (hb_set_between(hb, HBITMAP_LEVELS - 1, first, last) &&
402 hb->meta) {
403 hbitmap_set(hb->meta, start, count);
407 /* Resetting works the other way round: propagate up if the new
408 * value is zero.
410 static inline bool hb_reset_elem(unsigned long *elem, uint64_t start, uint64_t last)
412 unsigned long mask;
413 bool blanked;
415 assert((last >> BITS_PER_LEVEL) == (start >> BITS_PER_LEVEL));
416 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;
425 /* The recursive workhorse (the depth is limited to HBITMAP_LEVELS)...
426 * Returns true if at least one bit is changed. */
427 static bool hb_reset_between(HBitmap *hb, int level, uint64_t start,
428 uint64_t last)
430 size_t pos = start >> BITS_PER_LEVEL;
431 size_t lastpos = last >> BITS_PER_LEVEL;
432 bool changed = false;
433 size_t i;
435 i = pos;
436 if (i < lastpos) {
437 uint64_t next = (start | (BITS_PER_LONG - 1)) + 1;
439 /* Here we need a more complex test than when setting bits. Even if
440 * something was changed, we must not blank bits in the upper level
441 * unless the lower-level word became entirely zero. So, remove pos
442 * from the upper-level range if bits remain set.
444 if (hb_reset_elem(&hb->levels[level][i], start, next - 1)) {
445 changed = true;
446 } else {
447 pos++;
450 for (;;) {
451 start = next;
452 next += BITS_PER_LONG;
453 if (++i == lastpos) {
454 break;
456 changed |= (hb->levels[level][i] != 0);
457 hb->levels[level][i] = 0UL;
461 /* Same as above, this time for lastpos. */
462 if (hb_reset_elem(&hb->levels[level][i], start, last)) {
463 changed = true;
464 } else {
465 lastpos--;
468 if (level > 0 && changed) {
469 hb_reset_between(hb, level - 1, pos, lastpos);
472 return changed;
476 void hbitmap_reset(HBitmap *hb, uint64_t start, uint64_t count)
478 /* Compute range in the last layer. */
479 uint64_t first;
480 uint64_t last = start + count - 1;
482 trace_hbitmap_reset(hb, start, count,
483 start >> hb->granularity, last >> hb->granularity);
485 first = start >> hb->granularity;
486 last >>= hb->granularity;
487 assert(last < hb->size);
489 hb->count -= hb_count_between(hb, first, last);
490 if (hb_reset_between(hb, HBITMAP_LEVELS - 1, first, last) &&
491 hb->meta) {
492 hbitmap_set(hb->meta, start, count);
496 void hbitmap_reset_all(HBitmap *hb)
498 unsigned int i;
500 /* Same as hbitmap_alloc() except for memset() instead of malloc() */
501 for (i = HBITMAP_LEVELS; --i >= 1; ) {
502 memset(hb->levels[i], 0, hb->sizes[i] * sizeof(unsigned long));
505 hb->levels[0][0] = 1UL << (BITS_PER_LONG - 1);
506 hb->count = 0;
509 bool hbitmap_is_serializable(const HBitmap *hb)
511 /* Every serialized chunk must be aligned to 64 bits so that endianness
512 * requirements can be fulfilled on both 64 bit and 32 bit hosts.
513 * We have hbitmap_serialization_align() which converts this
514 * alignment requirement from bitmap bits to items covered (e.g. sectors).
515 * That value is:
516 * 64 << hb->granularity
517 * Since this value must not exceed UINT64_MAX, hb->granularity must be
518 * less than 58 (== 64 - 6, where 6 is ld(64), i.e. 1 << 6 == 64).
520 * In order for hbitmap_serialization_align() to always return a
521 * meaningful value, bitmaps that are to be serialized must have a
522 * granularity of less than 58. */
524 return hb->granularity < 58;
527 bool hbitmap_get(const HBitmap *hb, uint64_t item)
529 /* Compute position and bit in the last layer. */
530 uint64_t pos = item >> hb->granularity;
531 unsigned long bit = 1UL << (pos & (BITS_PER_LONG - 1));
532 assert(pos < hb->size);
534 return (hb->levels[HBITMAP_LEVELS - 1][pos >> BITS_PER_LEVEL] & bit) != 0;
537 uint64_t hbitmap_serialization_align(const HBitmap *hb)
539 assert(hbitmap_is_serializable(hb));
541 /* Require at least 64 bit granularity to be safe on both 64 bit and 32 bit
542 * hosts. */
543 return UINT64_C(64) << hb->granularity;
546 /* Start should be aligned to serialization granularity, chunk size should be
547 * aligned to serialization granularity too, except for last chunk.
549 static void serialization_chunk(const HBitmap *hb,
550 uint64_t start, uint64_t count,
551 unsigned long **first_el, uint64_t *el_count)
553 uint64_t last = start + count - 1;
554 uint64_t gran = hbitmap_serialization_align(hb);
556 assert((start & (gran - 1)) == 0);
557 assert((last >> hb->granularity) < hb->size);
558 if ((last >> hb->granularity) != hb->size - 1) {
559 assert((count & (gran - 1)) == 0);
562 start = (start >> hb->granularity) >> BITS_PER_LEVEL;
563 last = (last >> hb->granularity) >> BITS_PER_LEVEL;
565 *first_el = &hb->levels[HBITMAP_LEVELS - 1][start];
566 *el_count = last - start + 1;
569 uint64_t hbitmap_serialization_size(const HBitmap *hb,
570 uint64_t start, uint64_t count)
572 uint64_t el_count;
573 unsigned long *cur;
575 if (!count) {
576 return 0;
578 serialization_chunk(hb, start, count, &cur, &el_count);
580 return el_count * sizeof(unsigned long);
583 void hbitmap_serialize_part(const HBitmap *hb, uint8_t *buf,
584 uint64_t start, uint64_t count)
586 uint64_t el_count;
587 unsigned long *cur, *end;
589 if (!count) {
590 return;
592 serialization_chunk(hb, start, count, &cur, &el_count);
593 end = cur + el_count;
595 while (cur != end) {
596 unsigned long el =
597 (BITS_PER_LONG == 32 ? cpu_to_le32(*cur) : cpu_to_le64(*cur));
599 memcpy(buf, &el, sizeof(el));
600 buf += sizeof(el);
601 cur++;
605 void hbitmap_deserialize_part(HBitmap *hb, uint8_t *buf,
606 uint64_t start, uint64_t count,
607 bool finish)
609 uint64_t el_count;
610 unsigned long *cur, *end;
612 if (!count) {
613 return;
615 serialization_chunk(hb, start, count, &cur, &el_count);
616 end = cur + el_count;
618 while (cur != end) {
619 memcpy(cur, buf, sizeof(*cur));
621 if (BITS_PER_LONG == 32) {
622 le32_to_cpus((uint32_t *)cur);
623 } else {
624 le64_to_cpus((uint64_t *)cur);
627 buf += sizeof(unsigned long);
628 cur++;
630 if (finish) {
631 hbitmap_deserialize_finish(hb);
635 void hbitmap_deserialize_zeroes(HBitmap *hb, uint64_t start, uint64_t count,
636 bool finish)
638 uint64_t el_count;
639 unsigned long *first;
641 if (!count) {
642 return;
644 serialization_chunk(hb, start, count, &first, &el_count);
646 memset(first, 0, el_count * sizeof(unsigned long));
647 if (finish) {
648 hbitmap_deserialize_finish(hb);
652 void hbitmap_deserialize_ones(HBitmap *hb, uint64_t start, uint64_t count,
653 bool finish)
655 uint64_t el_count;
656 unsigned long *first;
658 if (!count) {
659 return;
661 serialization_chunk(hb, start, count, &first, &el_count);
663 memset(first, 0xff, el_count * sizeof(unsigned long));
664 if (finish) {
665 hbitmap_deserialize_finish(hb);
669 void hbitmap_deserialize_finish(HBitmap *bitmap)
671 int64_t i, size, prev_size;
672 int lev;
674 /* restore levels starting from penultimate to zero level, assuming
675 * that the last level is ok */
676 size = MAX((bitmap->size + BITS_PER_LONG - 1) >> BITS_PER_LEVEL, 1);
677 for (lev = HBITMAP_LEVELS - 1; lev-- > 0; ) {
678 prev_size = size;
679 size = MAX((size + BITS_PER_LONG - 1) >> BITS_PER_LEVEL, 1);
680 memset(bitmap->levels[lev], 0, size * sizeof(unsigned long));
682 for (i = 0; i < prev_size; ++i) {
683 if (bitmap->levels[lev + 1][i]) {
684 bitmap->levels[lev][i >> BITS_PER_LEVEL] |=
685 1UL << (i & (BITS_PER_LONG - 1));
690 bitmap->levels[0][0] |= 1UL << (BITS_PER_LONG - 1);
691 bitmap->count = hb_count_between(bitmap, 0, bitmap->size - 1);
694 void hbitmap_free(HBitmap *hb)
696 unsigned i;
697 assert(!hb->meta);
698 for (i = HBITMAP_LEVELS; i-- > 0; ) {
699 g_free(hb->levels[i]);
701 g_free(hb);
704 HBitmap *hbitmap_alloc(uint64_t size, int granularity)
706 HBitmap *hb = g_new0(struct HBitmap, 1);
707 unsigned i;
709 hb->orig_size = size;
711 assert(granularity >= 0 && granularity < 64);
712 size = (size + (1ULL << granularity) - 1) >> granularity;
713 assert(size <= ((uint64_t)1 << HBITMAP_LOG_MAX_SIZE));
715 hb->size = size;
716 hb->granularity = granularity;
717 for (i = HBITMAP_LEVELS; i-- > 0; ) {
718 size = MAX((size + BITS_PER_LONG - 1) >> BITS_PER_LEVEL, 1);
719 hb->sizes[i] = size;
720 hb->levels[i] = g_new0(unsigned long, size);
723 /* We necessarily have free bits in level 0 due to the definition
724 * of HBITMAP_LEVELS, so use one for a sentinel. This speeds up
725 * hbitmap_iter_skip_words.
727 assert(size == 1);
728 hb->levels[0][0] |= 1UL << (BITS_PER_LONG - 1);
729 return hb;
732 void hbitmap_truncate(HBitmap *hb, uint64_t size)
734 bool shrink;
735 unsigned i;
736 uint64_t num_elements = size;
737 uint64_t old;
739 /* Size comes in as logical elements, adjust for granularity. */
740 size = (size + (1ULL << hb->granularity) - 1) >> hb->granularity;
741 assert(size <= ((uint64_t)1 << HBITMAP_LOG_MAX_SIZE));
742 shrink = size < hb->size;
744 /* bit sizes are identical; nothing to do. */
745 if (size == hb->size) {
746 return;
749 /* If we're losing bits, let's clear those bits before we invalidate all of
750 * our invariants. This helps keep the bitcount consistent, and will prevent
751 * us from carrying around garbage bits beyond the end of the map.
753 if (shrink) {
754 /* Don't clear partial granularity groups;
755 * start at the first full one. */
756 uint64_t start = ROUND_UP(num_elements, UINT64_C(1) << hb->granularity);
757 uint64_t fix_count = (hb->size << hb->granularity) - start;
759 assert(fix_count);
760 hbitmap_reset(hb, start, fix_count);
763 hb->size = size;
764 for (i = HBITMAP_LEVELS; i-- > 0; ) {
765 size = MAX(BITS_TO_LONGS(size), 1);
766 if (hb->sizes[i] == size) {
767 break;
769 old = hb->sizes[i];
770 hb->sizes[i] = size;
771 hb->levels[i] = g_realloc(hb->levels[i], size * sizeof(unsigned long));
772 if (!shrink) {
773 memset(&hb->levels[i][old], 0x00,
774 (size - old) * sizeof(*hb->levels[i]));
777 if (hb->meta) {
778 hbitmap_truncate(hb->meta, hb->size << hb->granularity);
782 bool hbitmap_can_merge(const HBitmap *a, const HBitmap *b)
784 return (a->size == b->size) && (a->granularity == b->granularity);
788 * Given HBitmaps A and B, let A := A (BITOR) B.
789 * Bitmap B will not be modified.
791 * @return true if the merge was successful,
792 * false if it was not attempted.
794 bool hbitmap_merge(const HBitmap *a, const HBitmap *b, HBitmap *result)
796 int i;
797 uint64_t j;
799 if (!hbitmap_can_merge(a, b) || !hbitmap_can_merge(a, result)) {
800 return false;
802 assert(hbitmap_can_merge(b, result));
804 if (hbitmap_count(b) == 0) {
805 return true;
808 /* This merge is O(size), as BITS_PER_LONG and HBITMAP_LEVELS are constant.
809 * It may be possible to improve running times for sparsely populated maps
810 * by using hbitmap_iter_next, but this is suboptimal for dense maps.
812 for (i = HBITMAP_LEVELS - 1; i >= 0; i--) {
813 for (j = 0; j < a->sizes[i]; j++) {
814 result->levels[i][j] = a->levels[i][j] | b->levels[i][j];
818 /* Recompute the dirty count */
819 result->count = hb_count_between(result, 0, result->size - 1);
821 return true;
824 HBitmap *hbitmap_create_meta(HBitmap *hb, int chunk_size)
826 assert(!(chunk_size & (chunk_size - 1)));
827 assert(!hb->meta);
828 hb->meta = hbitmap_alloc(hb->size << hb->granularity,
829 hb->granularity + ctz32(chunk_size));
830 return hb->meta;
833 void hbitmap_free_meta(HBitmap *hb)
835 assert(hb->meta);
836 hbitmap_free(hb->meta);
837 hb->meta = NULL;
840 char *hbitmap_sha256(const HBitmap *bitmap, Error **errp)
842 size_t size = bitmap->sizes[HBITMAP_LEVELS - 1] * sizeof(unsigned long);
843 char *data = (char *)bitmap->levels[HBITMAP_LEVELS - 1];
844 char *hash = NULL;
845 qcrypto_hash_digest(QCRYPTO_HASH_ALG_SHA256, data, size, &hash, errp);
847 return hash;