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