]> git.proxmox.com Git - mirror_qemu.git/blob - util/hbitmap.c
block/dirty-bitmap: switch _next_dirty_area and _next_zero to int64_t
[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 /*
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 static 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, int64_t start, int64_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 assert(start >= 0 && count >= 0);
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_next_dirty_area(const HBitmap *hb, int64_t *start, int64_t *count)
250 {
251 HBitmapIter hbi;
252 int64_t firt_dirty_off, area_end;
253 uint32_t granularity = 1UL << hb->granularity;
254 uint64_t end;
255
256 assert(*start >= 0 && *count >= 0);
257
258 if (*start >= hb->orig_size || *count == 0) {
259 return false;
260 }
261
262 end = *count > hb->orig_size - *start ? hb->orig_size : *start + *count;
263
264 hbitmap_iter_init(&hbi, hb, *start);
265 firt_dirty_off = hbitmap_iter_next(&hbi);
266
267 if (firt_dirty_off < 0 || firt_dirty_off >= end) {
268 return false;
269 }
270
271 if (firt_dirty_off + granularity >= end) {
272 area_end = end;
273 } else {
274 area_end = hbitmap_next_zero(hb, firt_dirty_off + granularity,
275 end - firt_dirty_off - granularity);
276 if (area_end < 0) {
277 area_end = end;
278 }
279 }
280
281 if (firt_dirty_off > *start) {
282 *start = firt_dirty_off;
283 }
284 *count = area_end - *start;
285
286 return true;
287 }
288
289 bool hbitmap_empty(const HBitmap *hb)
290 {
291 return hb->count == 0;
292 }
293
294 int hbitmap_granularity(const HBitmap *hb)
295 {
296 return hb->granularity;
297 }
298
299 uint64_t hbitmap_count(const HBitmap *hb)
300 {
301 return hb->count << hb->granularity;
302 }
303
304 /**
305 * hbitmap_iter_next_word:
306 * @hbi: HBitmapIter to operate on.
307 * @p_cur: Location where to store the next non-zero word.
308 *
309 * Return the index of the next nonzero word that is set in @hbi's
310 * associated HBitmap, and set *p_cur to the content of that word
311 * (bits before the index that was passed to hbitmap_iter_init are
312 * trimmed on the first call). Return -1, and set *p_cur to zero,
313 * if all remaining words are zero.
314 */
315 static size_t hbitmap_iter_next_word(HBitmapIter *hbi, unsigned long *p_cur)
316 {
317 unsigned long cur = hbi->cur[HBITMAP_LEVELS - 1];
318
319 if (cur == 0) {
320 cur = hbitmap_iter_skip_words(hbi);
321 if (cur == 0) {
322 *p_cur = 0;
323 return -1;
324 }
325 }
326
327 /* The next call will resume work from the next word. */
328 hbi->cur[HBITMAP_LEVELS - 1] = 0;
329 *p_cur = cur;
330 return hbi->pos;
331 }
332
333 /* Count the number of set bits between start and end, not accounting for
334 * the granularity. Also an example of how to use hbitmap_iter_next_word.
335 */
336 static uint64_t hb_count_between(HBitmap *hb, uint64_t start, uint64_t last)
337 {
338 HBitmapIter hbi;
339 uint64_t count = 0;
340 uint64_t end = last + 1;
341 unsigned long cur;
342 size_t pos;
343
344 hbitmap_iter_init(&hbi, hb, start << hb->granularity);
345 for (;;) {
346 pos = hbitmap_iter_next_word(&hbi, &cur);
347 if (pos >= (end >> BITS_PER_LEVEL)) {
348 break;
349 }
350 count += ctpopl(cur);
351 }
352
353 if (pos == (end >> BITS_PER_LEVEL)) {
354 /* Drop bits representing the END-th and subsequent items. */
355 int bit = end & (BITS_PER_LONG - 1);
356 cur &= (1UL << bit) - 1;
357 count += ctpopl(cur);
358 }
359
360 return count;
361 }
362
363 /* Setting starts at the last layer and propagates up if an element
364 * changes.
365 */
366 static inline bool hb_set_elem(unsigned long *elem, uint64_t start, uint64_t last)
367 {
368 unsigned long mask;
369 unsigned long old;
370
371 assert((last >> BITS_PER_LEVEL) == (start >> BITS_PER_LEVEL));
372 assert(start <= last);
373
374 mask = 2UL << (last & (BITS_PER_LONG - 1));
375 mask -= 1UL << (start & (BITS_PER_LONG - 1));
376 old = *elem;
377 *elem |= mask;
378 return old != *elem;
379 }
380
381 /* The recursive workhorse (the depth is limited to HBITMAP_LEVELS)...
382 * Returns true if at least one bit is changed. */
383 static bool hb_set_between(HBitmap *hb, int level, uint64_t start,
384 uint64_t last)
385 {
386 size_t pos = start >> BITS_PER_LEVEL;
387 size_t lastpos = last >> BITS_PER_LEVEL;
388 bool changed = false;
389 size_t i;
390
391 i = pos;
392 if (i < lastpos) {
393 uint64_t next = (start | (BITS_PER_LONG - 1)) + 1;
394 changed |= hb_set_elem(&hb->levels[level][i], start, next - 1);
395 for (;;) {
396 start = next;
397 next += BITS_PER_LONG;
398 if (++i == lastpos) {
399 break;
400 }
401 changed |= (hb->levels[level][i] == 0);
402 hb->levels[level][i] = ~0UL;
403 }
404 }
405 changed |= hb_set_elem(&hb->levels[level][i], start, last);
406
407 /* If there was any change in this layer, we may have to update
408 * the one above.
409 */
410 if (level > 0 && changed) {
411 hb_set_between(hb, level - 1, pos, lastpos);
412 }
413 return changed;
414 }
415
416 void hbitmap_set(HBitmap *hb, uint64_t start, uint64_t count)
417 {
418 /* Compute range in the last layer. */
419 uint64_t first, n;
420 uint64_t last = start + count - 1;
421
422 if (count == 0) {
423 return;
424 }
425
426 trace_hbitmap_set(hb, start, count,
427 start >> hb->granularity, last >> hb->granularity);
428
429 first = start >> hb->granularity;
430 last >>= hb->granularity;
431 assert(last < hb->size);
432 n = last - first + 1;
433
434 hb->count += n - hb_count_between(hb, first, last);
435 if (hb_set_between(hb, HBITMAP_LEVELS - 1, first, last) &&
436 hb->meta) {
437 hbitmap_set(hb->meta, start, count);
438 }
439 }
440
441 /* Resetting works the other way round: propagate up if the new
442 * value is zero.
443 */
444 static inline bool hb_reset_elem(unsigned long *elem, uint64_t start, uint64_t last)
445 {
446 unsigned long mask;
447 bool blanked;
448
449 assert((last >> BITS_PER_LEVEL) == (start >> BITS_PER_LEVEL));
450 assert(start <= last);
451
452 mask = 2UL << (last & (BITS_PER_LONG - 1));
453 mask -= 1UL << (start & (BITS_PER_LONG - 1));
454 blanked = *elem != 0 && ((*elem & ~mask) == 0);
455 *elem &= ~mask;
456 return blanked;
457 }
458
459 /* The recursive workhorse (the depth is limited to HBITMAP_LEVELS)...
460 * Returns true if at least one bit is changed. */
461 static bool hb_reset_between(HBitmap *hb, int level, uint64_t start,
462 uint64_t last)
463 {
464 size_t pos = start >> BITS_PER_LEVEL;
465 size_t lastpos = last >> BITS_PER_LEVEL;
466 bool changed = false;
467 size_t i;
468
469 i = pos;
470 if (i < lastpos) {
471 uint64_t next = (start | (BITS_PER_LONG - 1)) + 1;
472
473 /* Here we need a more complex test than when setting bits. Even if
474 * something was changed, we must not blank bits in the upper level
475 * unless the lower-level word became entirely zero. So, remove pos
476 * from the upper-level range if bits remain set.
477 */
478 if (hb_reset_elem(&hb->levels[level][i], start, next - 1)) {
479 changed = true;
480 } else {
481 pos++;
482 }
483
484 for (;;) {
485 start = next;
486 next += BITS_PER_LONG;
487 if (++i == lastpos) {
488 break;
489 }
490 changed |= (hb->levels[level][i] != 0);
491 hb->levels[level][i] = 0UL;
492 }
493 }
494
495 /* Same as above, this time for lastpos. */
496 if (hb_reset_elem(&hb->levels[level][i], start, last)) {
497 changed = true;
498 } else {
499 lastpos--;
500 }
501
502 if (level > 0 && changed) {
503 hb_reset_between(hb, level - 1, pos, lastpos);
504 }
505
506 return changed;
507
508 }
509
510 void hbitmap_reset(HBitmap *hb, uint64_t start, uint64_t count)
511 {
512 /* Compute range in the last layer. */
513 uint64_t first;
514 uint64_t last = start + count - 1;
515 uint64_t gran = 1ULL << hb->granularity;
516
517 if (count == 0) {
518 return;
519 }
520
521 assert(QEMU_IS_ALIGNED(start, gran));
522 assert(QEMU_IS_ALIGNED(count, gran) || (start + count == hb->orig_size));
523
524 trace_hbitmap_reset(hb, start, count,
525 start >> hb->granularity, last >> hb->granularity);
526
527 first = start >> hb->granularity;
528 last >>= hb->granularity;
529 assert(last < hb->size);
530
531 hb->count -= hb_count_between(hb, first, last);
532 if (hb_reset_between(hb, HBITMAP_LEVELS - 1, first, last) &&
533 hb->meta) {
534 hbitmap_set(hb->meta, start, count);
535 }
536 }
537
538 void hbitmap_reset_all(HBitmap *hb)
539 {
540 unsigned int i;
541
542 /* Same as hbitmap_alloc() except for memset() instead of malloc() */
543 for (i = HBITMAP_LEVELS; --i >= 1; ) {
544 memset(hb->levels[i], 0, hb->sizes[i] * sizeof(unsigned long));
545 }
546
547 hb->levels[0][0] = 1UL << (BITS_PER_LONG - 1);
548 hb->count = 0;
549 }
550
551 bool hbitmap_is_serializable(const HBitmap *hb)
552 {
553 /* Every serialized chunk must be aligned to 64 bits so that endianness
554 * requirements can be fulfilled on both 64 bit and 32 bit hosts.
555 * We have hbitmap_serialization_align() which converts this
556 * alignment requirement from bitmap bits to items covered (e.g. sectors).
557 * That value is:
558 * 64 << hb->granularity
559 * Since this value must not exceed UINT64_MAX, hb->granularity must be
560 * less than 58 (== 64 - 6, where 6 is ld(64), i.e. 1 << 6 == 64).
561 *
562 * In order for hbitmap_serialization_align() to always return a
563 * meaningful value, bitmaps that are to be serialized must have a
564 * granularity of less than 58. */
565
566 return hb->granularity < 58;
567 }
568
569 bool hbitmap_get(const HBitmap *hb, uint64_t item)
570 {
571 /* Compute position and bit in the last layer. */
572 uint64_t pos = item >> hb->granularity;
573 unsigned long bit = 1UL << (pos & (BITS_PER_LONG - 1));
574 assert(pos < hb->size);
575
576 return (hb->levels[HBITMAP_LEVELS - 1][pos >> BITS_PER_LEVEL] & bit) != 0;
577 }
578
579 uint64_t hbitmap_serialization_align(const HBitmap *hb)
580 {
581 assert(hbitmap_is_serializable(hb));
582
583 /* Require at least 64 bit granularity to be safe on both 64 bit and 32 bit
584 * hosts. */
585 return UINT64_C(64) << hb->granularity;
586 }
587
588 /* Start should be aligned to serialization granularity, chunk size should be
589 * aligned to serialization granularity too, except for last chunk.
590 */
591 static void serialization_chunk(const HBitmap *hb,
592 uint64_t start, uint64_t count,
593 unsigned long **first_el, uint64_t *el_count)
594 {
595 uint64_t last = start + count - 1;
596 uint64_t gran = hbitmap_serialization_align(hb);
597
598 assert((start & (gran - 1)) == 0);
599 assert((last >> hb->granularity) < hb->size);
600 if ((last >> hb->granularity) != hb->size - 1) {
601 assert((count & (gran - 1)) == 0);
602 }
603
604 start = (start >> hb->granularity) >> BITS_PER_LEVEL;
605 last = (last >> hb->granularity) >> BITS_PER_LEVEL;
606
607 *first_el = &hb->levels[HBITMAP_LEVELS - 1][start];
608 *el_count = last - start + 1;
609 }
610
611 uint64_t hbitmap_serialization_size(const HBitmap *hb,
612 uint64_t start, uint64_t count)
613 {
614 uint64_t el_count;
615 unsigned long *cur;
616
617 if (!count) {
618 return 0;
619 }
620 serialization_chunk(hb, start, count, &cur, &el_count);
621
622 return el_count * sizeof(unsigned long);
623 }
624
625 void hbitmap_serialize_part(const HBitmap *hb, uint8_t *buf,
626 uint64_t start, uint64_t count)
627 {
628 uint64_t el_count;
629 unsigned long *cur, *end;
630
631 if (!count) {
632 return;
633 }
634 serialization_chunk(hb, start, count, &cur, &el_count);
635 end = cur + el_count;
636
637 while (cur != end) {
638 unsigned long el =
639 (BITS_PER_LONG == 32 ? cpu_to_le32(*cur) : cpu_to_le64(*cur));
640
641 memcpy(buf, &el, sizeof(el));
642 buf += sizeof(el);
643 cur++;
644 }
645 }
646
647 void hbitmap_deserialize_part(HBitmap *hb, uint8_t *buf,
648 uint64_t start, uint64_t count,
649 bool finish)
650 {
651 uint64_t el_count;
652 unsigned long *cur, *end;
653
654 if (!count) {
655 return;
656 }
657 serialization_chunk(hb, start, count, &cur, &el_count);
658 end = cur + el_count;
659
660 while (cur != end) {
661 memcpy(cur, buf, sizeof(*cur));
662
663 if (BITS_PER_LONG == 32) {
664 le32_to_cpus((uint32_t *)cur);
665 } else {
666 le64_to_cpus((uint64_t *)cur);
667 }
668
669 buf += sizeof(unsigned long);
670 cur++;
671 }
672 if (finish) {
673 hbitmap_deserialize_finish(hb);
674 }
675 }
676
677 void hbitmap_deserialize_zeroes(HBitmap *hb, uint64_t start, uint64_t count,
678 bool finish)
679 {
680 uint64_t el_count;
681 unsigned long *first;
682
683 if (!count) {
684 return;
685 }
686 serialization_chunk(hb, start, count, &first, &el_count);
687
688 memset(first, 0, el_count * sizeof(unsigned long));
689 if (finish) {
690 hbitmap_deserialize_finish(hb);
691 }
692 }
693
694 void hbitmap_deserialize_ones(HBitmap *hb, uint64_t start, uint64_t count,
695 bool finish)
696 {
697 uint64_t el_count;
698 unsigned long *first;
699
700 if (!count) {
701 return;
702 }
703 serialization_chunk(hb, start, count, &first, &el_count);
704
705 memset(first, 0xff, el_count * sizeof(unsigned long));
706 if (finish) {
707 hbitmap_deserialize_finish(hb);
708 }
709 }
710
711 void hbitmap_deserialize_finish(HBitmap *bitmap)
712 {
713 int64_t i, size, prev_size;
714 int lev;
715
716 /* restore levels starting from penultimate to zero level, assuming
717 * that the last level is ok */
718 size = MAX((bitmap->size + BITS_PER_LONG - 1) >> BITS_PER_LEVEL, 1);
719 for (lev = HBITMAP_LEVELS - 1; lev-- > 0; ) {
720 prev_size = size;
721 size = MAX((size + BITS_PER_LONG - 1) >> BITS_PER_LEVEL, 1);
722 memset(bitmap->levels[lev], 0, size * sizeof(unsigned long));
723
724 for (i = 0; i < prev_size; ++i) {
725 if (bitmap->levels[lev + 1][i]) {
726 bitmap->levels[lev][i >> BITS_PER_LEVEL] |=
727 1UL << (i & (BITS_PER_LONG - 1));
728 }
729 }
730 }
731
732 bitmap->levels[0][0] |= 1UL << (BITS_PER_LONG - 1);
733 bitmap->count = hb_count_between(bitmap, 0, bitmap->size - 1);
734 }
735
736 void hbitmap_free(HBitmap *hb)
737 {
738 unsigned i;
739 assert(!hb->meta);
740 for (i = HBITMAP_LEVELS; i-- > 0; ) {
741 g_free(hb->levels[i]);
742 }
743 g_free(hb);
744 }
745
746 HBitmap *hbitmap_alloc(uint64_t size, int granularity)
747 {
748 HBitmap *hb = g_new0(struct HBitmap, 1);
749 unsigned i;
750
751 assert(size <= INT64_MAX);
752 hb->orig_size = size;
753
754 assert(granularity >= 0 && granularity < 64);
755 size = (size + (1ULL << granularity) - 1) >> granularity;
756 assert(size <= ((uint64_t)1 << HBITMAP_LOG_MAX_SIZE));
757
758 hb->size = size;
759 hb->granularity = granularity;
760 for (i = HBITMAP_LEVELS; i-- > 0; ) {
761 size = MAX((size + BITS_PER_LONG - 1) >> BITS_PER_LEVEL, 1);
762 hb->sizes[i] = size;
763 hb->levels[i] = g_new0(unsigned long, size);
764 }
765
766 /* We necessarily have free bits in level 0 due to the definition
767 * of HBITMAP_LEVELS, so use one for a sentinel. This speeds up
768 * hbitmap_iter_skip_words.
769 */
770 assert(size == 1);
771 hb->levels[0][0] |= 1UL << (BITS_PER_LONG - 1);
772 return hb;
773 }
774
775 void hbitmap_truncate(HBitmap *hb, uint64_t size)
776 {
777 bool shrink;
778 unsigned i;
779 uint64_t num_elements = size;
780 uint64_t old;
781
782 assert(size <= INT64_MAX);
783 hb->orig_size = size;
784
785 /* Size comes in as logical elements, adjust for granularity. */
786 size = (size + (1ULL << hb->granularity) - 1) >> hb->granularity;
787 assert(size <= ((uint64_t)1 << HBITMAP_LOG_MAX_SIZE));
788 shrink = size < hb->size;
789
790 /* bit sizes are identical; nothing to do. */
791 if (size == hb->size) {
792 return;
793 }
794
795 /* If we're losing bits, let's clear those bits before we invalidate all of
796 * our invariants. This helps keep the bitcount consistent, and will prevent
797 * us from carrying around garbage bits beyond the end of the map.
798 */
799 if (shrink) {
800 /* Don't clear partial granularity groups;
801 * start at the first full one. */
802 uint64_t start = ROUND_UP(num_elements, UINT64_C(1) << hb->granularity);
803 uint64_t fix_count = (hb->size << hb->granularity) - start;
804
805 assert(fix_count);
806 hbitmap_reset(hb, start, fix_count);
807 }
808
809 hb->size = size;
810 for (i = HBITMAP_LEVELS; i-- > 0; ) {
811 size = MAX(BITS_TO_LONGS(size), 1);
812 if (hb->sizes[i] == size) {
813 break;
814 }
815 old = hb->sizes[i];
816 hb->sizes[i] = size;
817 hb->levels[i] = g_realloc(hb->levels[i], size * sizeof(unsigned long));
818 if (!shrink) {
819 memset(&hb->levels[i][old], 0x00,
820 (size - old) * sizeof(*hb->levels[i]));
821 }
822 }
823 if (hb->meta) {
824 hbitmap_truncate(hb->meta, hb->size << hb->granularity);
825 }
826 }
827
828 bool hbitmap_can_merge(const HBitmap *a, const HBitmap *b)
829 {
830 return (a->orig_size == b->orig_size);
831 }
832
833 /**
834 * hbitmap_sparse_merge: performs dst = dst | src
835 * works with differing granularities.
836 * best used when src is sparsely populated.
837 */
838 static void hbitmap_sparse_merge(HBitmap *dst, const HBitmap *src)
839 {
840 int64_t offset = 0;
841 int64_t count = src->orig_size;
842
843 while (hbitmap_next_dirty_area(src, &offset, &count)) {
844 hbitmap_set(dst, offset, count);
845 offset += count;
846 if (offset >= src->orig_size) {
847 break;
848 }
849 count = src->orig_size - offset;
850 }
851 }
852
853 /**
854 * Given HBitmaps A and B, let R := A (BITOR) B.
855 * Bitmaps A and B will not be modified,
856 * except when bitmap R is an alias of A or B.
857 *
858 * @return true if the merge was successful,
859 * false if it was not attempted.
860 */
861 bool hbitmap_merge(const HBitmap *a, const HBitmap *b, HBitmap *result)
862 {
863 int i;
864 uint64_t j;
865
866 if (!hbitmap_can_merge(a, b) || !hbitmap_can_merge(a, result)) {
867 return false;
868 }
869 assert(hbitmap_can_merge(b, result));
870
871 if ((!hbitmap_count(a) && result == b) ||
872 (!hbitmap_count(b) && result == a)) {
873 return true;
874 }
875
876 if (!hbitmap_count(a) && !hbitmap_count(b)) {
877 hbitmap_reset_all(result);
878 return true;
879 }
880
881 if (a->granularity != b->granularity) {
882 if ((a != result) && (b != result)) {
883 hbitmap_reset_all(result);
884 }
885 if (a != result) {
886 hbitmap_sparse_merge(result, a);
887 }
888 if (b != result) {
889 hbitmap_sparse_merge(result, b);
890 }
891 return true;
892 }
893
894 /* This merge is O(size), as BITS_PER_LONG and HBITMAP_LEVELS are constant.
895 * It may be possible to improve running times for sparsely populated maps
896 * by using hbitmap_iter_next, but this is suboptimal for dense maps.
897 */
898 assert(a->size == b->size);
899 for (i = HBITMAP_LEVELS - 1; i >= 0; i--) {
900 for (j = 0; j < a->sizes[i]; j++) {
901 result->levels[i][j] = a->levels[i][j] | b->levels[i][j];
902 }
903 }
904
905 /* Recompute the dirty count */
906 result->count = hb_count_between(result, 0, result->size - 1);
907
908 return true;
909 }
910
911 char *hbitmap_sha256(const HBitmap *bitmap, Error **errp)
912 {
913 size_t size = bitmap->sizes[HBITMAP_LEVELS - 1] * sizeof(unsigned long);
914 char *data = (char *)bitmap->levels[HBITMAP_LEVELS - 1];
915 char *hash = NULL;
916 qcrypto_hash_digest(QCRYPTO_HASH_ALG_SHA256, data, size, &hash, errp);
917
918 return hash;
919 }