hbitmap.c 26 KB

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