]> git.proxmox.com Git - mirror_qemu.git/blob - util/hbitmap.c
dirty-bitmap: improve bdrv_dirty_bitmap_next_zero
[mirror_qemu.git] / util / hbitmap.c
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
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"
17
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.
23 *
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).
30 *
31 * Given an index in the bitmap, it can be split in group of bits like
32 * this (for the 64-bit case):
33 *
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
37 *
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.
43 *
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.
46 *
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).
53 */
54
55 struct HBitmap {
56 /* Size of the bitmap, as requested in hbitmap_alloc. */
57 uint64_t orig_size;
58
59 /* Number of total bits in the bottom level. */
60 uint64_t size;
61
62 /* Number of set bits in the bottom level. */
63 uint64_t count;
64
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:
71 *
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
77 *
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.
82 */
83 int granularity;
84
85 /* A meta dirty bitmap to track the dirtiness of bits in this HBitmap. */
86 HBitmap *meta;
87
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.
92 *
93 * Note that all bitmaps have the same number of levels. Even a 1-bit
94 * bitmap will still allocate HBITMAP_LEVELS arrays.
95 */
96 unsigned long *levels[HBITMAP_LEVELS];
97
98 /* The length of each levels[] array. */
99 uint64_t sizes[HBITMAP_LEVELS];
100 };
101
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.
104 */
105 unsigned long hbitmap_iter_skip_words(HBitmapIter *hbi)
106 {
107 size_t pos = hbi->pos;
108 const HBitmap *hb = hbi->hb;
109 unsigned i = HBITMAP_LEVELS - 1;
110
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);
117
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.
122 */
123
124 if (i == 0 && cur == (1UL << (BITS_PER_LONG - 1))) {
125 return 0;
126 }
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.
131 */
132 assert(cur);
133 pos = (pos << BITS_PER_LEVEL) + ctzl(cur);
134 hbi->cur[i] = cur & (cur - 1);
135
136 /* Set up next level for iteration. */
137 cur = hb->levels[i + 1][pos];
138 }
139
140 hbi->pos = pos;
141 trace_hbitmap_iter_skip_words(hbi->hb, hbi, pos, cur);
142
143 assert(cur);
144 return cur;
145 }
146
147 int64_t hbitmap_iter_next(HBitmapIter *hbi, bool advance)
148 {
149 unsigned long cur = hbi->cur[HBITMAP_LEVELS - 1] &
150 hbi->hb->levels[HBITMAP_LEVELS - 1][hbi->pos];
151 int64_t item;
152
153 if (cur == 0) {
154 cur = hbitmap_iter_skip_words(hbi);
155 if (cur == 0) {
156 return -1;
157 }
158 }
159
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;
165 }
166 item = ((uint64_t)hbi->pos << BITS_PER_LEVEL) + ctzl(cur);
167
168 return item << hbi->granularity;
169 }
170
171 void hbitmap_iter_init(HBitmapIter *hbi, const HBitmap *hb, uint64_t first)
172 {
173 unsigned i, bit;
174 uint64_t pos;
175
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;
181
182 for (i = HBITMAP_LEVELS; i-- > 0; ) {
183 bit = pos & (BITS_PER_LONG - 1);
184 pos >>= BITS_PER_LEVEL;
185
186 /* Drop bits representing items before first. */
187 hbi->cur[i] = hb->levels[i][pos] & ~((1UL << bit) - 1);
188
189 /* We have already added level i+1, so the lowest set bit has
190 * been processed. Clear it.
191 */
192 if (i != HBITMAP_LEVELS - 1) {
193 hbi->cur[i] &= ~(1UL << bit);
194 }
195 }
196 }
197
198 int64_t hbitmap_next_zero(const HBitmap *hb, uint64_t start, uint64_t count)
199 {
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;
206
207 if (start >= hb->orig_size || count == 0) {
208 return -1;
209 }
210
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;
215
216 /* There may be some zero bits in @cur before @start. We are not interested
217 * in them, let's set them.
218 */
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);
222
223 if (cur == (unsigned long)-1) {
224 do {
225 pos++;
226 } while (pos < sz && last_lev[pos] == (unsigned long)-1);
227
228 if (pos >= sz) {
229 return -1;
230 }
231
232 cur = last_lev[pos];
233 }
234
235 res = (pos << BITS_PER_LEVEL) + ctol(cur);
236 if (res >= end_bit) {
237 return -1;
238 }
239
240 res = res << hb->granularity;
241 if (res < start) {
242 assert(((start - res) >> hb->granularity) == 0);
243 return start;
244 }
245
246 return res;
247 }
248
249 bool hbitmap_empty(const HBitmap *hb)
250 {
251 return hb->count == 0;
252 }
253
254 int hbitmap_granularity(const HBitmap *hb)
255 {
256 return hb->granularity;
257 }
258
259 uint64_t hbitmap_count(const HBitmap *hb)
260 {
261 return hb->count << hb->granularity;
262 }
263
264 /* Count the number of set bits between start and end, not accounting for
265 * the granularity. Also an example of how to use hbitmap_iter_next_word.
266 */
267 static uint64_t hb_count_between(HBitmap *hb, uint64_t start, uint64_t last)
268 {
269 HBitmapIter hbi;
270 uint64_t count = 0;
271 uint64_t end = last + 1;
272 unsigned long cur;
273 size_t pos;
274
275 hbitmap_iter_init(&hbi, hb, start << hb->granularity);
276 for (;;) {
277 pos = hbitmap_iter_next_word(&hbi, &cur);
278 if (pos >= (end >> BITS_PER_LEVEL)) {
279 break;
280 }
281 count += ctpopl(cur);
282 }
283
284 if (pos == (end >> BITS_PER_LEVEL)) {
285 /* Drop bits representing the END-th and subsequent items. */
286 int bit = end & (BITS_PER_LONG - 1);
287 cur &= (1UL << bit) - 1;
288 count += ctpopl(cur);
289 }
290
291 return count;
292 }
293
294 /* Setting starts at the last layer and propagates up if an element
295 * changes.
296 */
297 static inline bool hb_set_elem(unsigned long *elem, uint64_t start, uint64_t last)
298 {
299 unsigned long mask;
300 unsigned long old;
301
302 assert((last >> BITS_PER_LEVEL) == (start >> BITS_PER_LEVEL));
303 assert(start <= last);
304
305 mask = 2UL << (last & (BITS_PER_LONG - 1));
306 mask -= 1UL << (start & (BITS_PER_LONG - 1));
307 old = *elem;
308 *elem |= mask;
309 return old != *elem;
310 }
311
312 /* The recursive workhorse (the depth is limited to HBITMAP_LEVELS)...
313 * Returns true if at least one bit is changed. */
314 static bool hb_set_between(HBitmap *hb, int level, uint64_t start,
315 uint64_t last)
316 {
317 size_t pos = start >> BITS_PER_LEVEL;
318 size_t lastpos = last >> BITS_PER_LEVEL;
319 bool changed = false;
320 size_t i;
321
322 i = pos;
323 if (i < lastpos) {
324 uint64_t next = (start | (BITS_PER_LONG - 1)) + 1;
325 changed |= hb_set_elem(&hb->levels[level][i], start, next - 1);
326 for (;;) {
327 start = next;
328 next += BITS_PER_LONG;
329 if (++i == lastpos) {
330 break;
331 }
332 changed |= (hb->levels[level][i] == 0);
333 hb->levels[level][i] = ~0UL;
334 }
335 }
336 changed |= hb_set_elem(&hb->levels[level][i], start, last);
337
338 /* If there was any change in this layer, we may have to update
339 * the one above.
340 */
341 if (level > 0 && changed) {
342 hb_set_between(hb, level - 1, pos, lastpos);
343 }
344 return changed;
345 }
346
347 void hbitmap_set(HBitmap *hb, uint64_t start, uint64_t count)
348 {
349 /* Compute range in the last layer. */
350 uint64_t first, n;
351 uint64_t last = start + count - 1;
352
353 trace_hbitmap_set(hb, start, count,
354 start >> hb->granularity, last >> hb->granularity);
355
356 first = start >> hb->granularity;
357 last >>= hb->granularity;
358 assert(last < hb->size);
359 n = last - first + 1;
360
361 hb->count += n - hb_count_between(hb, first, last);
362 if (hb_set_between(hb, HBITMAP_LEVELS - 1, first, last) &&
363 hb->meta) {
364 hbitmap_set(hb->meta, start, count);
365 }
366 }
367
368 /* Resetting works the other way round: propagate up if the new
369 * value is zero.
370 */
371 static inline bool hb_reset_elem(unsigned long *elem, uint64_t start, uint64_t last)
372 {
373 unsigned long mask;
374 bool blanked;
375
376 assert((last >> BITS_PER_LEVEL) == (start >> BITS_PER_LEVEL));
377 assert(start <= last);
378
379 mask = 2UL << (last & (BITS_PER_LONG - 1));
380 mask -= 1UL << (start & (BITS_PER_LONG - 1));
381 blanked = *elem != 0 && ((*elem & ~mask) == 0);
382 *elem &= ~mask;
383 return blanked;
384 }
385
386 /* The recursive workhorse (the depth is limited to HBITMAP_LEVELS)...
387 * Returns true if at least one bit is changed. */
388 static bool hb_reset_between(HBitmap *hb, int level, uint64_t start,
389 uint64_t last)
390 {
391 size_t pos = start >> BITS_PER_LEVEL;
392 size_t lastpos = last >> BITS_PER_LEVEL;
393 bool changed = false;
394 size_t i;
395
396 i = pos;
397 if (i < lastpos) {
398 uint64_t next = (start | (BITS_PER_LONG - 1)) + 1;
399
400 /* Here we need a more complex test than when setting bits. Even if
401 * something was changed, we must not blank bits in the upper level
402 * unless the lower-level word became entirely zero. So, remove pos
403 * from the upper-level range if bits remain set.
404 */
405 if (hb_reset_elem(&hb->levels[level][i], start, next - 1)) {
406 changed = true;
407 } else {
408 pos++;
409 }
410
411 for (;;) {
412 start = next;
413 next += BITS_PER_LONG;
414 if (++i == lastpos) {
415 break;
416 }
417 changed |= (hb->levels[level][i] != 0);
418 hb->levels[level][i] = 0UL;
419 }
420 }
421
422 /* Same as above, this time for lastpos. */
423 if (hb_reset_elem(&hb->levels[level][i], start, last)) {
424 changed = true;
425 } else {
426 lastpos--;
427 }
428
429 if (level > 0 && changed) {
430 hb_reset_between(hb, level - 1, pos, lastpos);
431 }
432
433 return changed;
434
435 }
436
437 void hbitmap_reset(HBitmap *hb, uint64_t start, uint64_t count)
438 {
439 /* Compute range in the last layer. */
440 uint64_t first;
441 uint64_t last = start + count - 1;
442
443 trace_hbitmap_reset(hb, start, count,
444 start >> hb->granularity, last >> hb->granularity);
445
446 first = start >> hb->granularity;
447 last >>= hb->granularity;
448 assert(last < hb->size);
449
450 hb->count -= hb_count_between(hb, first, last);
451 if (hb_reset_between(hb, HBITMAP_LEVELS - 1, first, last) &&
452 hb->meta) {
453 hbitmap_set(hb->meta, start, count);
454 }
455 }
456
457 void hbitmap_reset_all(HBitmap *hb)
458 {
459 unsigned int i;
460
461 /* Same as hbitmap_alloc() except for memset() instead of malloc() */
462 for (i = HBITMAP_LEVELS; --i >= 1; ) {
463 memset(hb->levels[i], 0, hb->sizes[i] * sizeof(unsigned long));
464 }
465
466 hb->levels[0][0] = 1UL << (BITS_PER_LONG - 1);
467 hb->count = 0;
468 }
469
470 bool hbitmap_is_serializable(const HBitmap *hb)
471 {
472 /* Every serialized chunk must be aligned to 64 bits so that endianness
473 * requirements can be fulfilled on both 64 bit and 32 bit hosts.
474 * We have hbitmap_serialization_align() which converts this
475 * alignment requirement from bitmap bits to items covered (e.g. sectors).
476 * That value is:
477 * 64 << hb->granularity
478 * Since this value must not exceed UINT64_MAX, hb->granularity must be
479 * less than 58 (== 64 - 6, where 6 is ld(64), i.e. 1 << 6 == 64).
480 *
481 * In order for hbitmap_serialization_align() to always return a
482 * meaningful value, bitmaps that are to be serialized must have a
483 * granularity of less than 58. */
484
485 return hb->granularity < 58;
486 }
487
488 bool hbitmap_get(const HBitmap *hb, uint64_t item)
489 {
490 /* Compute position and bit in the last layer. */
491 uint64_t pos = item >> hb->granularity;
492 unsigned long bit = 1UL << (pos & (BITS_PER_LONG - 1));
493 assert(pos < hb->size);
494
495 return (hb->levels[HBITMAP_LEVELS - 1][pos >> BITS_PER_LEVEL] & bit) != 0;
496 }
497
498 uint64_t hbitmap_serialization_align(const HBitmap *hb)
499 {
500 assert(hbitmap_is_serializable(hb));
501
502 /* Require at least 64 bit granularity to be safe on both 64 bit and 32 bit
503 * hosts. */
504 return UINT64_C(64) << hb->granularity;
505 }
506
507 /* Start should be aligned to serialization granularity, chunk size should be
508 * aligned to serialization granularity too, except for last chunk.
509 */
510 static void serialization_chunk(const HBitmap *hb,
511 uint64_t start, uint64_t count,
512 unsigned long **first_el, uint64_t *el_count)
513 {
514 uint64_t last = start + count - 1;
515 uint64_t gran = hbitmap_serialization_align(hb);
516
517 assert((start & (gran - 1)) == 0);
518 assert((last >> hb->granularity) < hb->size);
519 if ((last >> hb->granularity) != hb->size - 1) {
520 assert((count & (gran - 1)) == 0);
521 }
522
523 start = (start >> hb->granularity) >> BITS_PER_LEVEL;
524 last = (last >> hb->granularity) >> BITS_PER_LEVEL;
525
526 *first_el = &hb->levels[HBITMAP_LEVELS - 1][start];
527 *el_count = last - start + 1;
528 }
529
530 uint64_t hbitmap_serialization_size(const HBitmap *hb,
531 uint64_t start, uint64_t count)
532 {
533 uint64_t el_count;
534 unsigned long *cur;
535
536 if (!count) {
537 return 0;
538 }
539 serialization_chunk(hb, start, count, &cur, &el_count);
540
541 return el_count * sizeof(unsigned long);
542 }
543
544 void hbitmap_serialize_part(const HBitmap *hb, uint8_t *buf,
545 uint64_t start, uint64_t count)
546 {
547 uint64_t el_count;
548 unsigned long *cur, *end;
549
550 if (!count) {
551 return;
552 }
553 serialization_chunk(hb, start, count, &cur, &el_count);
554 end = cur + el_count;
555
556 while (cur != end) {
557 unsigned long el =
558 (BITS_PER_LONG == 32 ? cpu_to_le32(*cur) : cpu_to_le64(*cur));
559
560 memcpy(buf, &el, sizeof(el));
561 buf += sizeof(el);
562 cur++;
563 }
564 }
565
566 void hbitmap_deserialize_part(HBitmap *hb, uint8_t *buf,
567 uint64_t start, uint64_t count,
568 bool finish)
569 {
570 uint64_t el_count;
571 unsigned long *cur, *end;
572
573 if (!count) {
574 return;
575 }
576 serialization_chunk(hb, start, count, &cur, &el_count);
577 end = cur + el_count;
578
579 while (cur != end) {
580 memcpy(cur, buf, sizeof(*cur));
581
582 if (BITS_PER_LONG == 32) {
583 le32_to_cpus((uint32_t *)cur);
584 } else {
585 le64_to_cpus((uint64_t *)cur);
586 }
587
588 buf += sizeof(unsigned long);
589 cur++;
590 }
591 if (finish) {
592 hbitmap_deserialize_finish(hb);
593 }
594 }
595
596 void hbitmap_deserialize_zeroes(HBitmap *hb, uint64_t start, uint64_t count,
597 bool finish)
598 {
599 uint64_t el_count;
600 unsigned long *first;
601
602 if (!count) {
603 return;
604 }
605 serialization_chunk(hb, start, count, &first, &el_count);
606
607 memset(first, 0, el_count * sizeof(unsigned long));
608 if (finish) {
609 hbitmap_deserialize_finish(hb);
610 }
611 }
612
613 void hbitmap_deserialize_ones(HBitmap *hb, uint64_t start, uint64_t count,
614 bool finish)
615 {
616 uint64_t el_count;
617 unsigned long *first;
618
619 if (!count) {
620 return;
621 }
622 serialization_chunk(hb, start, count, &first, &el_count);
623
624 memset(first, 0xff, el_count * sizeof(unsigned long));
625 if (finish) {
626 hbitmap_deserialize_finish(hb);
627 }
628 }
629
630 void hbitmap_deserialize_finish(HBitmap *bitmap)
631 {
632 int64_t i, size, prev_size;
633 int lev;
634
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
643 for (i = 0; i < prev_size; ++i) {
644 if (bitmap->levels[lev + 1][i]) {
645 bitmap->levels[lev][i >> BITS_PER_LEVEL] |=
646 1UL << (i & (BITS_PER_LONG - 1));
647 }
648 }
649 }
650
651 bitmap->levels[0][0] |= 1UL << (BITS_PER_LONG - 1);
652 bitmap->count = hb_count_between(bitmap, 0, bitmap->size - 1);
653 }
654
655 void hbitmap_free(HBitmap *hb)
656 {
657 unsigned i;
658 assert(!hb->meta);
659 for (i = HBITMAP_LEVELS; i-- > 0; ) {
660 g_free(hb->levels[i]);
661 }
662 g_free(hb);
663 }
664
665 HBitmap *hbitmap_alloc(uint64_t size, int granularity)
666 {
667 HBitmap *hb = g_new0(struct HBitmap, 1);
668 unsigned i;
669
670 hb->orig_size = size;
671
672 assert(granularity >= 0 && granularity < 64);
673 size = (size + (1ULL << granularity) - 1) >> granularity;
674 assert(size <= ((uint64_t)1 << HBITMAP_LOG_MAX_SIZE));
675
676 hb->size = size;
677 hb->granularity = granularity;
678 for (i = HBITMAP_LEVELS; i-- > 0; ) {
679 size = MAX((size + BITS_PER_LONG - 1) >> BITS_PER_LEVEL, 1);
680 hb->sizes[i] = size;
681 hb->levels[i] = g_new0(unsigned long, size);
682 }
683
684 /* We necessarily have free bits in level 0 due to the definition
685 * of HBITMAP_LEVELS, so use one for a sentinel. This speeds up
686 * hbitmap_iter_skip_words.
687 */
688 assert(size == 1);
689 hb->levels[0][0] |= 1UL << (BITS_PER_LONG - 1);
690 return hb;
691 }
692
693 void hbitmap_truncate(HBitmap *hb, uint64_t size)
694 {
695 bool shrink;
696 unsigned i;
697 uint64_t num_elements = size;
698 uint64_t old;
699
700 /* Size comes in as logical elements, adjust for granularity. */
701 size = (size + (1ULL << hb->granularity) - 1) >> hb->granularity;
702 assert(size <= ((uint64_t)1 << HBITMAP_LOG_MAX_SIZE));
703 shrink = size < hb->size;
704
705 /* bit sizes are identical; nothing to do. */
706 if (size == hb->size) {
707 return;
708 }
709
710 /* If we're losing bits, let's clear those bits before we invalidate all of
711 * our invariants. This helps keep the bitcount consistent, and will prevent
712 * us from carrying around garbage bits beyond the end of the map.
713 */
714 if (shrink) {
715 /* Don't clear partial granularity groups;
716 * start at the first full one. */
717 uint64_t start = ROUND_UP(num_elements, UINT64_C(1) << hb->granularity);
718 uint64_t fix_count = (hb->size << hb->granularity) - start;
719
720 assert(fix_count);
721 hbitmap_reset(hb, start, fix_count);
722 }
723
724 hb->size = size;
725 for (i = HBITMAP_LEVELS; i-- > 0; ) {
726 size = MAX(BITS_TO_LONGS(size), 1);
727 if (hb->sizes[i] == size) {
728 break;
729 }
730 old = hb->sizes[i];
731 hb->sizes[i] = size;
732 hb->levels[i] = g_realloc(hb->levels[i], size * sizeof(unsigned long));
733 if (!shrink) {
734 memset(&hb->levels[i][old], 0x00,
735 (size - old) * sizeof(*hb->levels[i]));
736 }
737 }
738 if (hb->meta) {
739 hbitmap_truncate(hb->meta, hb->size << hb->granularity);
740 }
741 }
742
743 bool hbitmap_can_merge(const HBitmap *a, const HBitmap *b)
744 {
745 return (a->size == b->size) && (a->granularity == b->granularity);
746 }
747
748 /**
749 * Given HBitmaps A and B, let A := A (BITOR) B.
750 * Bitmap B will not be modified.
751 *
752 * @return true if the merge was successful,
753 * false if it was not attempted.
754 */
755 bool hbitmap_merge(const HBitmap *a, const HBitmap *b, HBitmap *result)
756 {
757 int i;
758 uint64_t j;
759
760 if (!hbitmap_can_merge(a, b) || !hbitmap_can_merge(a, result)) {
761 return false;
762 }
763 assert(hbitmap_can_merge(b, result));
764
765 if (hbitmap_count(b) == 0) {
766 return true;
767 }
768
769 /* This merge is O(size), as BITS_PER_LONG and HBITMAP_LEVELS are constant.
770 * It may be possible to improve running times for sparsely populated maps
771 * by using hbitmap_iter_next, but this is suboptimal for dense maps.
772 */
773 for (i = HBITMAP_LEVELS - 1; i >= 0; i--) {
774 for (j = 0; j < a->sizes[i]; j++) {
775 result->levels[i][j] = a->levels[i][j] | b->levels[i][j];
776 }
777 }
778
779 /* Recompute the dirty count */
780 result->count = hb_count_between(result, 0, result->size - 1);
781
782 return true;
783 }
784
785 HBitmap *hbitmap_create_meta(HBitmap *hb, int chunk_size)
786 {
787 assert(!(chunk_size & (chunk_size - 1)));
788 assert(!hb->meta);
789 hb->meta = hbitmap_alloc(hb->size << hb->granularity,
790 hb->granularity + ctz32(chunk_size));
791 return hb->meta;
792 }
793
794 void hbitmap_free_meta(HBitmap *hb)
795 {
796 assert(hb->meta);
797 hbitmap_free(hb->meta);
798 hb->meta = NULL;
799 }
800
801 char *hbitmap_sha256(const HBitmap *bitmap, Error **errp)
802 {
803 size_t size = bitmap->sizes[HBITMAP_LEVELS - 1] * sizeof(unsigned long);
804 char *data = (char *)bitmap->levels[HBITMAP_LEVELS - 1];
805 char *hash = NULL;
806 qcrypto_hash_digest(QCRYPTO_HASH_ALG_SHA256, data, size, &hash, errp);
807
808 return hash;
809 }