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