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