qcow2: use one single memory block for the L2/refcount cache tables
[qemu/ericb.git] / block / qcow2-refcount.c
blob0707f94206efdf40359cf832ac1b534d24ff728c
1 /*
2 * Block driver for the QCOW version 2 format
4 * Copyright (c) 2004-2006 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
25 #include "qemu-common.h"
26 #include "block/block_int.h"
27 #include "block/qcow2.h"
28 #include "qemu/range.h"
30 static int64_t alloc_clusters_noref(BlockDriverState *bs, uint64_t size);
31 static int QEMU_WARN_UNUSED_RESULT update_refcount(BlockDriverState *bs,
32 int64_t offset, int64_t length, uint64_t addend,
33 bool decrease, enum qcow2_discard_type type);
35 static uint64_t get_refcount_ro0(const void *refcount_array, uint64_t index);
36 static uint64_t get_refcount_ro1(const void *refcount_array, uint64_t index);
37 static uint64_t get_refcount_ro2(const void *refcount_array, uint64_t index);
38 static uint64_t get_refcount_ro3(const void *refcount_array, uint64_t index);
39 static uint64_t get_refcount_ro4(const void *refcount_array, uint64_t index);
40 static uint64_t get_refcount_ro5(const void *refcount_array, uint64_t index);
41 static uint64_t get_refcount_ro6(const void *refcount_array, uint64_t index);
43 static void set_refcount_ro0(void *refcount_array, uint64_t index,
44 uint64_t value);
45 static void set_refcount_ro1(void *refcount_array, uint64_t index,
46 uint64_t value);
47 static void set_refcount_ro2(void *refcount_array, uint64_t index,
48 uint64_t value);
49 static void set_refcount_ro3(void *refcount_array, uint64_t index,
50 uint64_t value);
51 static void set_refcount_ro4(void *refcount_array, uint64_t index,
52 uint64_t value);
53 static void set_refcount_ro5(void *refcount_array, uint64_t index,
54 uint64_t value);
55 static void set_refcount_ro6(void *refcount_array, uint64_t index,
56 uint64_t value);
59 static Qcow2GetRefcountFunc *const get_refcount_funcs[] = {
60 &get_refcount_ro0,
61 &get_refcount_ro1,
62 &get_refcount_ro2,
63 &get_refcount_ro3,
64 &get_refcount_ro4,
65 &get_refcount_ro5,
66 &get_refcount_ro6
69 static Qcow2SetRefcountFunc *const set_refcount_funcs[] = {
70 &set_refcount_ro0,
71 &set_refcount_ro1,
72 &set_refcount_ro2,
73 &set_refcount_ro3,
74 &set_refcount_ro4,
75 &set_refcount_ro5,
76 &set_refcount_ro6
80 /*********************************************************/
81 /* refcount handling */
83 int qcow2_refcount_init(BlockDriverState *bs)
85 BDRVQcowState *s = bs->opaque;
86 unsigned int refcount_table_size2, i;
87 int ret;
89 assert(s->refcount_order >= 0 && s->refcount_order <= 6);
91 s->get_refcount = get_refcount_funcs[s->refcount_order];
92 s->set_refcount = set_refcount_funcs[s->refcount_order];
94 assert(s->refcount_table_size <= INT_MAX / sizeof(uint64_t));
95 refcount_table_size2 = s->refcount_table_size * sizeof(uint64_t);
96 s->refcount_table = g_try_malloc(refcount_table_size2);
98 if (s->refcount_table_size > 0) {
99 if (s->refcount_table == NULL) {
100 ret = -ENOMEM;
101 goto fail;
103 BLKDBG_EVENT(bs->file, BLKDBG_REFTABLE_LOAD);
104 ret = bdrv_pread(bs->file, s->refcount_table_offset,
105 s->refcount_table, refcount_table_size2);
106 if (ret < 0) {
107 goto fail;
109 for(i = 0; i < s->refcount_table_size; i++)
110 be64_to_cpus(&s->refcount_table[i]);
112 return 0;
113 fail:
114 return ret;
117 void qcow2_refcount_close(BlockDriverState *bs)
119 BDRVQcowState *s = bs->opaque;
120 g_free(s->refcount_table);
124 static uint64_t get_refcount_ro0(const void *refcount_array, uint64_t index)
126 return (((const uint8_t *)refcount_array)[index / 8] >> (index % 8)) & 0x1;
129 static void set_refcount_ro0(void *refcount_array, uint64_t index,
130 uint64_t value)
132 assert(!(value >> 1));
133 ((uint8_t *)refcount_array)[index / 8] &= ~(0x1 << (index % 8));
134 ((uint8_t *)refcount_array)[index / 8] |= value << (index % 8);
137 static uint64_t get_refcount_ro1(const void *refcount_array, uint64_t index)
139 return (((const uint8_t *)refcount_array)[index / 4] >> (2 * (index % 4)))
140 & 0x3;
143 static void set_refcount_ro1(void *refcount_array, uint64_t index,
144 uint64_t value)
146 assert(!(value >> 2));
147 ((uint8_t *)refcount_array)[index / 4] &= ~(0x3 << (2 * (index % 4)));
148 ((uint8_t *)refcount_array)[index / 4] |= value << (2 * (index % 4));
151 static uint64_t get_refcount_ro2(const void *refcount_array, uint64_t index)
153 return (((const uint8_t *)refcount_array)[index / 2] >> (4 * (index % 2)))
154 & 0xf;
157 static void set_refcount_ro2(void *refcount_array, uint64_t index,
158 uint64_t value)
160 assert(!(value >> 4));
161 ((uint8_t *)refcount_array)[index / 2] &= ~(0xf << (4 * (index % 2)));
162 ((uint8_t *)refcount_array)[index / 2] |= value << (4 * (index % 2));
165 static uint64_t get_refcount_ro3(const void *refcount_array, uint64_t index)
167 return ((const uint8_t *)refcount_array)[index];
170 static void set_refcount_ro3(void *refcount_array, uint64_t index,
171 uint64_t value)
173 assert(!(value >> 8));
174 ((uint8_t *)refcount_array)[index] = value;
177 static uint64_t get_refcount_ro4(const void *refcount_array, uint64_t index)
179 return be16_to_cpu(((const uint16_t *)refcount_array)[index]);
182 static void set_refcount_ro4(void *refcount_array, uint64_t index,
183 uint64_t value)
185 assert(!(value >> 16));
186 ((uint16_t *)refcount_array)[index] = cpu_to_be16(value);
189 static uint64_t get_refcount_ro5(const void *refcount_array, uint64_t index)
191 return be32_to_cpu(((const uint32_t *)refcount_array)[index]);
194 static void set_refcount_ro5(void *refcount_array, uint64_t index,
195 uint64_t value)
197 assert(!(value >> 32));
198 ((uint32_t *)refcount_array)[index] = cpu_to_be32(value);
201 static uint64_t get_refcount_ro6(const void *refcount_array, uint64_t index)
203 return be64_to_cpu(((const uint64_t *)refcount_array)[index]);
206 static void set_refcount_ro6(void *refcount_array, uint64_t index,
207 uint64_t value)
209 ((uint64_t *)refcount_array)[index] = cpu_to_be64(value);
213 static int load_refcount_block(BlockDriverState *bs,
214 int64_t refcount_block_offset,
215 void **refcount_block)
217 BDRVQcowState *s = bs->opaque;
218 int ret;
220 BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_LOAD);
221 ret = qcow2_cache_get(bs, s->refcount_block_cache, refcount_block_offset,
222 refcount_block);
224 return ret;
228 * Retrieves the refcount of the cluster given by its index and stores it in
229 * *refcount. Returns 0 on success and -errno on failure.
231 int qcow2_get_refcount(BlockDriverState *bs, int64_t cluster_index,
232 uint64_t *refcount)
234 BDRVQcowState *s = bs->opaque;
235 uint64_t refcount_table_index, block_index;
236 int64_t refcount_block_offset;
237 int ret;
238 void *refcount_block;
240 refcount_table_index = cluster_index >> s->refcount_block_bits;
241 if (refcount_table_index >= s->refcount_table_size) {
242 *refcount = 0;
243 return 0;
245 refcount_block_offset =
246 s->refcount_table[refcount_table_index] & REFT_OFFSET_MASK;
247 if (!refcount_block_offset) {
248 *refcount = 0;
249 return 0;
252 if (offset_into_cluster(s, refcount_block_offset)) {
253 qcow2_signal_corruption(bs, true, -1, -1, "Refblock offset %#" PRIx64
254 " unaligned (reftable index: %#" PRIx64 ")",
255 refcount_block_offset, refcount_table_index);
256 return -EIO;
259 ret = qcow2_cache_get(bs, s->refcount_block_cache, refcount_block_offset,
260 &refcount_block);
261 if (ret < 0) {
262 return ret;
265 block_index = cluster_index & (s->refcount_block_size - 1);
266 *refcount = s->get_refcount(refcount_block, block_index);
268 ret = qcow2_cache_put(bs, s->refcount_block_cache, &refcount_block);
269 if (ret < 0) {
270 return ret;
273 return 0;
277 * Rounds the refcount table size up to avoid growing the table for each single
278 * refcount block that is allocated.
280 static unsigned int next_refcount_table_size(BDRVQcowState *s,
281 unsigned int min_size)
283 unsigned int min_clusters = (min_size >> (s->cluster_bits - 3)) + 1;
284 unsigned int refcount_table_clusters =
285 MAX(1, s->refcount_table_size >> (s->cluster_bits - 3));
287 while (min_clusters > refcount_table_clusters) {
288 refcount_table_clusters = (refcount_table_clusters * 3 + 1) / 2;
291 return refcount_table_clusters << (s->cluster_bits - 3);
295 /* Checks if two offsets are described by the same refcount block */
296 static int in_same_refcount_block(BDRVQcowState *s, uint64_t offset_a,
297 uint64_t offset_b)
299 uint64_t block_a = offset_a >> (s->cluster_bits + s->refcount_block_bits);
300 uint64_t block_b = offset_b >> (s->cluster_bits + s->refcount_block_bits);
302 return (block_a == block_b);
306 * Loads a refcount block. If it doesn't exist yet, it is allocated first
307 * (including growing the refcount table if needed).
309 * Returns 0 on success or -errno in error case
311 static int alloc_refcount_block(BlockDriverState *bs,
312 int64_t cluster_index, void **refcount_block)
314 BDRVQcowState *s = bs->opaque;
315 unsigned int refcount_table_index;
316 int ret;
318 BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_ALLOC);
320 /* Find the refcount block for the given cluster */
321 refcount_table_index = cluster_index >> s->refcount_block_bits;
323 if (refcount_table_index < s->refcount_table_size) {
325 uint64_t refcount_block_offset =
326 s->refcount_table[refcount_table_index] & REFT_OFFSET_MASK;
328 /* If it's already there, we're done */
329 if (refcount_block_offset) {
330 if (offset_into_cluster(s, refcount_block_offset)) {
331 qcow2_signal_corruption(bs, true, -1, -1, "Refblock offset %#"
332 PRIx64 " unaligned (reftable index: "
333 "%#x)", refcount_block_offset,
334 refcount_table_index);
335 return -EIO;
338 return load_refcount_block(bs, refcount_block_offset,
339 refcount_block);
344 * If we came here, we need to allocate something. Something is at least
345 * a cluster for the new refcount block. It may also include a new refcount
346 * table if the old refcount table is too small.
348 * Note that allocating clusters here needs some special care:
350 * - We can't use the normal qcow2_alloc_clusters(), it would try to
351 * increase the refcount and very likely we would end up with an endless
352 * recursion. Instead we must place the refcount blocks in a way that
353 * they can describe them themselves.
355 * - We need to consider that at this point we are inside update_refcounts
356 * and potentially doing an initial refcount increase. This means that
357 * some clusters have already been allocated by the caller, but their
358 * refcount isn't accurate yet. If we allocate clusters for metadata, we
359 * need to return -EAGAIN to signal the caller that it needs to restart
360 * the search for free clusters.
362 * - alloc_clusters_noref and qcow2_free_clusters may load a different
363 * refcount block into the cache
366 *refcount_block = NULL;
368 /* We write to the refcount table, so we might depend on L2 tables */
369 ret = qcow2_cache_flush(bs, s->l2_table_cache);
370 if (ret < 0) {
371 return ret;
374 /* Allocate the refcount block itself and mark it as used */
375 int64_t new_block = alloc_clusters_noref(bs, s->cluster_size);
376 if (new_block < 0) {
377 return new_block;
380 #ifdef DEBUG_ALLOC2
381 fprintf(stderr, "qcow2: Allocate refcount block %d for %" PRIx64
382 " at %" PRIx64 "\n",
383 refcount_table_index, cluster_index << s->cluster_bits, new_block);
384 #endif
386 if (in_same_refcount_block(s, new_block, cluster_index << s->cluster_bits)) {
387 /* Zero the new refcount block before updating it */
388 ret = qcow2_cache_get_empty(bs, s->refcount_block_cache, new_block,
389 refcount_block);
390 if (ret < 0) {
391 goto fail_block;
394 memset(*refcount_block, 0, s->cluster_size);
396 /* The block describes itself, need to update the cache */
397 int block_index = (new_block >> s->cluster_bits) &
398 (s->refcount_block_size - 1);
399 s->set_refcount(*refcount_block, block_index, 1);
400 } else {
401 /* Described somewhere else. This can recurse at most twice before we
402 * arrive at a block that describes itself. */
403 ret = update_refcount(bs, new_block, s->cluster_size, 1, false,
404 QCOW2_DISCARD_NEVER);
405 if (ret < 0) {
406 goto fail_block;
409 ret = qcow2_cache_flush(bs, s->refcount_block_cache);
410 if (ret < 0) {
411 goto fail_block;
414 /* Initialize the new refcount block only after updating its refcount,
415 * update_refcount uses the refcount cache itself */
416 ret = qcow2_cache_get_empty(bs, s->refcount_block_cache, new_block,
417 refcount_block);
418 if (ret < 0) {
419 goto fail_block;
422 memset(*refcount_block, 0, s->cluster_size);
425 /* Now the new refcount block needs to be written to disk */
426 BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_ALLOC_WRITE);
427 qcow2_cache_entry_mark_dirty(bs, s->refcount_block_cache, *refcount_block);
428 ret = qcow2_cache_flush(bs, s->refcount_block_cache);
429 if (ret < 0) {
430 goto fail_block;
433 /* If the refcount table is big enough, just hook the block up there */
434 if (refcount_table_index < s->refcount_table_size) {
435 uint64_t data64 = cpu_to_be64(new_block);
436 BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_ALLOC_HOOKUP);
437 ret = bdrv_pwrite_sync(bs->file,
438 s->refcount_table_offset + refcount_table_index * sizeof(uint64_t),
439 &data64, sizeof(data64));
440 if (ret < 0) {
441 goto fail_block;
444 s->refcount_table[refcount_table_index] = new_block;
446 /* The new refcount block may be where the caller intended to put its
447 * data, so let it restart the search. */
448 return -EAGAIN;
451 ret = qcow2_cache_put(bs, s->refcount_block_cache, refcount_block);
452 if (ret < 0) {
453 goto fail_block;
457 * If we come here, we need to grow the refcount table. Again, a new
458 * refcount table needs some space and we can't simply allocate to avoid
459 * endless recursion.
461 * Therefore let's grab new refcount blocks at the end of the image, which
462 * will describe themselves and the new refcount table. This way we can
463 * reference them only in the new table and do the switch to the new
464 * refcount table at once without producing an inconsistent state in
465 * between.
467 BLKDBG_EVENT(bs->file, BLKDBG_REFTABLE_GROW);
469 /* Calculate the number of refcount blocks needed so far; this will be the
470 * basis for calculating the index of the first cluster used for the
471 * self-describing refcount structures which we are about to create.
473 * Because we reached this point, there cannot be any refcount entries for
474 * cluster_index or higher indices yet. However, because new_block has been
475 * allocated to describe that cluster (and it will assume this role later
476 * on), we cannot use that index; also, new_block may actually have a higher
477 * cluster index than cluster_index, so it needs to be taken into account
478 * here (and 1 needs to be added to its value because that cluster is used).
480 uint64_t blocks_used = DIV_ROUND_UP(MAX(cluster_index + 1,
481 (new_block >> s->cluster_bits) + 1),
482 s->refcount_block_size);
484 if (blocks_used > QCOW_MAX_REFTABLE_SIZE / sizeof(uint64_t)) {
485 return -EFBIG;
488 /* And now we need at least one block more for the new metadata */
489 uint64_t table_size = next_refcount_table_size(s, blocks_used + 1);
490 uint64_t last_table_size;
491 uint64_t blocks_clusters;
492 do {
493 uint64_t table_clusters =
494 size_to_clusters(s, table_size * sizeof(uint64_t));
495 blocks_clusters = 1 +
496 ((table_clusters + s->refcount_block_size - 1)
497 / s->refcount_block_size);
498 uint64_t meta_clusters = table_clusters + blocks_clusters;
500 last_table_size = table_size;
501 table_size = next_refcount_table_size(s, blocks_used +
502 ((meta_clusters + s->refcount_block_size - 1)
503 / s->refcount_block_size));
505 } while (last_table_size != table_size);
507 #ifdef DEBUG_ALLOC2
508 fprintf(stderr, "qcow2: Grow refcount table %" PRId32 " => %" PRId64 "\n",
509 s->refcount_table_size, table_size);
510 #endif
512 /* Create the new refcount table and blocks */
513 uint64_t meta_offset = (blocks_used * s->refcount_block_size) *
514 s->cluster_size;
515 uint64_t table_offset = meta_offset + blocks_clusters * s->cluster_size;
516 uint64_t *new_table = g_try_new0(uint64_t, table_size);
517 void *new_blocks = g_try_malloc0(blocks_clusters * s->cluster_size);
519 assert(table_size > 0 && blocks_clusters > 0);
520 if (new_table == NULL || new_blocks == NULL) {
521 ret = -ENOMEM;
522 goto fail_table;
525 /* Fill the new refcount table */
526 memcpy(new_table, s->refcount_table,
527 s->refcount_table_size * sizeof(uint64_t));
528 new_table[refcount_table_index] = new_block;
530 int i;
531 for (i = 0; i < blocks_clusters; i++) {
532 new_table[blocks_used + i] = meta_offset + (i * s->cluster_size);
535 /* Fill the refcount blocks */
536 uint64_t table_clusters = size_to_clusters(s, table_size * sizeof(uint64_t));
537 int block = 0;
538 for (i = 0; i < table_clusters + blocks_clusters; i++) {
539 s->set_refcount(new_blocks, block++, 1);
542 /* Write refcount blocks to disk */
543 BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_ALLOC_WRITE_BLOCKS);
544 ret = bdrv_pwrite_sync(bs->file, meta_offset, new_blocks,
545 blocks_clusters * s->cluster_size);
546 g_free(new_blocks);
547 new_blocks = NULL;
548 if (ret < 0) {
549 goto fail_table;
552 /* Write refcount table to disk */
553 for(i = 0; i < table_size; i++) {
554 cpu_to_be64s(&new_table[i]);
557 BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_ALLOC_WRITE_TABLE);
558 ret = bdrv_pwrite_sync(bs->file, table_offset, new_table,
559 table_size * sizeof(uint64_t));
560 if (ret < 0) {
561 goto fail_table;
564 for(i = 0; i < table_size; i++) {
565 be64_to_cpus(&new_table[i]);
568 /* Hook up the new refcount table in the qcow2 header */
569 uint8_t data[12];
570 cpu_to_be64w((uint64_t*)data, table_offset);
571 cpu_to_be32w((uint32_t*)(data + 8), table_clusters);
572 BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_ALLOC_SWITCH_TABLE);
573 ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, refcount_table_offset),
574 data, sizeof(data));
575 if (ret < 0) {
576 goto fail_table;
579 /* And switch it in memory */
580 uint64_t old_table_offset = s->refcount_table_offset;
581 uint64_t old_table_size = s->refcount_table_size;
583 g_free(s->refcount_table);
584 s->refcount_table = new_table;
585 s->refcount_table_size = table_size;
586 s->refcount_table_offset = table_offset;
588 /* Free old table. */
589 qcow2_free_clusters(bs, old_table_offset, old_table_size * sizeof(uint64_t),
590 QCOW2_DISCARD_OTHER);
592 ret = load_refcount_block(bs, new_block, refcount_block);
593 if (ret < 0) {
594 return ret;
597 /* If we were trying to do the initial refcount update for some cluster
598 * allocation, we might have used the same clusters to store newly
599 * allocated metadata. Make the caller search some new space. */
600 return -EAGAIN;
602 fail_table:
603 g_free(new_blocks);
604 g_free(new_table);
605 fail_block:
606 if (*refcount_block != NULL) {
607 qcow2_cache_put(bs, s->refcount_block_cache, refcount_block);
609 return ret;
612 void qcow2_process_discards(BlockDriverState *bs, int ret)
614 BDRVQcowState *s = bs->opaque;
615 Qcow2DiscardRegion *d, *next;
617 QTAILQ_FOREACH_SAFE(d, &s->discards, next, next) {
618 QTAILQ_REMOVE(&s->discards, d, next);
620 /* Discard is optional, ignore the return value */
621 if (ret >= 0) {
622 bdrv_discard(bs->file,
623 d->offset >> BDRV_SECTOR_BITS,
624 d->bytes >> BDRV_SECTOR_BITS);
627 g_free(d);
631 static void update_refcount_discard(BlockDriverState *bs,
632 uint64_t offset, uint64_t length)
634 BDRVQcowState *s = bs->opaque;
635 Qcow2DiscardRegion *d, *p, *next;
637 QTAILQ_FOREACH(d, &s->discards, next) {
638 uint64_t new_start = MIN(offset, d->offset);
639 uint64_t new_end = MAX(offset + length, d->offset + d->bytes);
641 if (new_end - new_start <= length + d->bytes) {
642 /* There can't be any overlap, areas ending up here have no
643 * references any more and therefore shouldn't get freed another
644 * time. */
645 assert(d->bytes + length == new_end - new_start);
646 d->offset = new_start;
647 d->bytes = new_end - new_start;
648 goto found;
652 d = g_malloc(sizeof(*d));
653 *d = (Qcow2DiscardRegion) {
654 .bs = bs,
655 .offset = offset,
656 .bytes = length,
658 QTAILQ_INSERT_TAIL(&s->discards, d, next);
660 found:
661 /* Merge discard requests if they are adjacent now */
662 QTAILQ_FOREACH_SAFE(p, &s->discards, next, next) {
663 if (p == d
664 || p->offset > d->offset + d->bytes
665 || d->offset > p->offset + p->bytes)
667 continue;
670 /* Still no overlap possible */
671 assert(p->offset == d->offset + d->bytes
672 || d->offset == p->offset + p->bytes);
674 QTAILQ_REMOVE(&s->discards, p, next);
675 d->offset = MIN(d->offset, p->offset);
676 d->bytes += p->bytes;
677 g_free(p);
681 /* XXX: cache several refcount block clusters ? */
682 /* @addend is the absolute value of the addend; if @decrease is set, @addend
683 * will be subtracted from the current refcount, otherwise it will be added */
684 static int QEMU_WARN_UNUSED_RESULT update_refcount(BlockDriverState *bs,
685 int64_t offset,
686 int64_t length,
687 uint64_t addend,
688 bool decrease,
689 enum qcow2_discard_type type)
691 BDRVQcowState *s = bs->opaque;
692 int64_t start, last, cluster_offset;
693 void *refcount_block = NULL;
694 int64_t old_table_index = -1;
695 int ret;
697 #ifdef DEBUG_ALLOC2
698 fprintf(stderr, "update_refcount: offset=%" PRId64 " size=%" PRId64
699 " addend=%s%" PRIu64 "\n", offset, length, decrease ? "-" : "",
700 addend);
701 #endif
702 if (length < 0) {
703 return -EINVAL;
704 } else if (length == 0) {
705 return 0;
708 if (decrease) {
709 qcow2_cache_set_dependency(bs, s->refcount_block_cache,
710 s->l2_table_cache);
713 start = start_of_cluster(s, offset);
714 last = start_of_cluster(s, offset + length - 1);
715 for(cluster_offset = start; cluster_offset <= last;
716 cluster_offset += s->cluster_size)
718 int block_index;
719 uint64_t refcount;
720 int64_t cluster_index = cluster_offset >> s->cluster_bits;
721 int64_t table_index = cluster_index >> s->refcount_block_bits;
723 /* Load the refcount block and allocate it if needed */
724 if (table_index != old_table_index) {
725 if (refcount_block) {
726 ret = qcow2_cache_put(bs, s->refcount_block_cache,
727 &refcount_block);
728 if (ret < 0) {
729 goto fail;
733 ret = alloc_refcount_block(bs, cluster_index, &refcount_block);
734 if (ret < 0) {
735 goto fail;
738 old_table_index = table_index;
740 qcow2_cache_entry_mark_dirty(bs, s->refcount_block_cache,
741 refcount_block);
743 /* we can update the count and save it */
744 block_index = cluster_index & (s->refcount_block_size - 1);
746 refcount = s->get_refcount(refcount_block, block_index);
747 if (decrease ? (refcount - addend > refcount)
748 : (refcount + addend < refcount ||
749 refcount + addend > s->refcount_max))
751 ret = -EINVAL;
752 goto fail;
754 if (decrease) {
755 refcount -= addend;
756 } else {
757 refcount += addend;
759 if (refcount == 0 && cluster_index < s->free_cluster_index) {
760 s->free_cluster_index = cluster_index;
762 s->set_refcount(refcount_block, block_index, refcount);
764 if (refcount == 0 && s->discard_passthrough[type]) {
765 update_refcount_discard(bs, cluster_offset, s->cluster_size);
769 ret = 0;
770 fail:
771 if (!s->cache_discards) {
772 qcow2_process_discards(bs, ret);
775 /* Write last changed block to disk */
776 if (refcount_block) {
777 int wret;
778 wret = qcow2_cache_put(bs, s->refcount_block_cache, &refcount_block);
779 if (wret < 0) {
780 return ret < 0 ? ret : wret;
785 * Try do undo any updates if an error is returned (This may succeed in
786 * some cases like ENOSPC for allocating a new refcount block)
788 if (ret < 0) {
789 int dummy;
790 dummy = update_refcount(bs, offset, cluster_offset - offset, addend,
791 !decrease, QCOW2_DISCARD_NEVER);
792 (void)dummy;
795 return ret;
799 * Increases or decreases the refcount of a given cluster.
801 * @addend is the absolute value of the addend; if @decrease is set, @addend
802 * will be subtracted from the current refcount, otherwise it will be added.
804 * On success 0 is returned; on failure -errno is returned.
806 int qcow2_update_cluster_refcount(BlockDriverState *bs,
807 int64_t cluster_index,
808 uint64_t addend, bool decrease,
809 enum qcow2_discard_type type)
811 BDRVQcowState *s = bs->opaque;
812 int ret;
814 ret = update_refcount(bs, cluster_index << s->cluster_bits, 1, addend,
815 decrease, type);
816 if (ret < 0) {
817 return ret;
820 return 0;
825 /*********************************************************/
826 /* cluster allocation functions */
830 /* return < 0 if error */
831 static int64_t alloc_clusters_noref(BlockDriverState *bs, uint64_t size)
833 BDRVQcowState *s = bs->opaque;
834 uint64_t i, nb_clusters, refcount;
835 int ret;
837 /* We can't allocate clusters if they may still be queued for discard. */
838 if (s->cache_discards) {
839 qcow2_process_discards(bs, 0);
842 nb_clusters = size_to_clusters(s, size);
843 retry:
844 for(i = 0; i < nb_clusters; i++) {
845 uint64_t next_cluster_index = s->free_cluster_index++;
846 ret = qcow2_get_refcount(bs, next_cluster_index, &refcount);
848 if (ret < 0) {
849 return ret;
850 } else if (refcount != 0) {
851 goto retry;
855 /* Make sure that all offsets in the "allocated" range are representable
856 * in an int64_t */
857 if (s->free_cluster_index > 0 &&
858 s->free_cluster_index - 1 > (INT64_MAX >> s->cluster_bits))
860 return -EFBIG;
863 #ifdef DEBUG_ALLOC2
864 fprintf(stderr, "alloc_clusters: size=%" PRId64 " -> %" PRId64 "\n",
865 size,
866 (s->free_cluster_index - nb_clusters) << s->cluster_bits);
867 #endif
868 return (s->free_cluster_index - nb_clusters) << s->cluster_bits;
871 int64_t qcow2_alloc_clusters(BlockDriverState *bs, uint64_t size)
873 int64_t offset;
874 int ret;
876 BLKDBG_EVENT(bs->file, BLKDBG_CLUSTER_ALLOC);
877 do {
878 offset = alloc_clusters_noref(bs, size);
879 if (offset < 0) {
880 return offset;
883 ret = update_refcount(bs, offset, size, 1, false, QCOW2_DISCARD_NEVER);
884 } while (ret == -EAGAIN);
886 if (ret < 0) {
887 return ret;
890 return offset;
893 int qcow2_alloc_clusters_at(BlockDriverState *bs, uint64_t offset,
894 int nb_clusters)
896 BDRVQcowState *s = bs->opaque;
897 uint64_t cluster_index, refcount;
898 uint64_t i;
899 int ret;
901 assert(nb_clusters >= 0);
902 if (nb_clusters == 0) {
903 return 0;
906 do {
907 /* Check how many clusters there are free */
908 cluster_index = offset >> s->cluster_bits;
909 for(i = 0; i < nb_clusters; i++) {
910 ret = qcow2_get_refcount(bs, cluster_index++, &refcount);
911 if (ret < 0) {
912 return ret;
913 } else if (refcount != 0) {
914 break;
918 /* And then allocate them */
919 ret = update_refcount(bs, offset, i << s->cluster_bits, 1, false,
920 QCOW2_DISCARD_NEVER);
921 } while (ret == -EAGAIN);
923 if (ret < 0) {
924 return ret;
927 return i;
930 /* only used to allocate compressed sectors. We try to allocate
931 contiguous sectors. size must be <= cluster_size */
932 int64_t qcow2_alloc_bytes(BlockDriverState *bs, int size)
934 BDRVQcowState *s = bs->opaque;
935 int64_t offset;
936 size_t free_in_cluster;
937 int ret;
939 BLKDBG_EVENT(bs->file, BLKDBG_CLUSTER_ALLOC_BYTES);
940 assert(size > 0 && size <= s->cluster_size);
941 assert(!s->free_byte_offset || offset_into_cluster(s, s->free_byte_offset));
943 offset = s->free_byte_offset;
945 if (offset) {
946 uint64_t refcount;
947 ret = qcow2_get_refcount(bs, offset >> s->cluster_bits, &refcount);
948 if (ret < 0) {
949 return ret;
952 if (refcount == s->refcount_max) {
953 offset = 0;
957 free_in_cluster = s->cluster_size - offset_into_cluster(s, offset);
958 if (!offset || free_in_cluster < size) {
959 int64_t new_cluster = alloc_clusters_noref(bs, s->cluster_size);
960 if (new_cluster < 0) {
961 return new_cluster;
964 if (!offset || ROUND_UP(offset, s->cluster_size) != new_cluster) {
965 offset = new_cluster;
969 assert(offset);
970 ret = update_refcount(bs, offset, size, 1, false, QCOW2_DISCARD_NEVER);
971 if (ret < 0) {
972 return ret;
975 /* The cluster refcount was incremented; refcount blocks must be flushed
976 * before the caller's L2 table updates. */
977 qcow2_cache_set_dependency(bs, s->l2_table_cache, s->refcount_block_cache);
979 s->free_byte_offset = offset + size;
980 if (!offset_into_cluster(s, s->free_byte_offset)) {
981 s->free_byte_offset = 0;
984 return offset;
987 void qcow2_free_clusters(BlockDriverState *bs,
988 int64_t offset, int64_t size,
989 enum qcow2_discard_type type)
991 int ret;
993 BLKDBG_EVENT(bs->file, BLKDBG_CLUSTER_FREE);
994 ret = update_refcount(bs, offset, size, 1, true, type);
995 if (ret < 0) {
996 fprintf(stderr, "qcow2_free_clusters failed: %s\n", strerror(-ret));
997 /* TODO Remember the clusters to free them later and avoid leaking */
1002 * Free a cluster using its L2 entry (handles clusters of all types, e.g.
1003 * normal cluster, compressed cluster, etc.)
1005 void qcow2_free_any_clusters(BlockDriverState *bs, uint64_t l2_entry,
1006 int nb_clusters, enum qcow2_discard_type type)
1008 BDRVQcowState *s = bs->opaque;
1010 switch (qcow2_get_cluster_type(l2_entry)) {
1011 case QCOW2_CLUSTER_COMPRESSED:
1013 int nb_csectors;
1014 nb_csectors = ((l2_entry >> s->csize_shift) &
1015 s->csize_mask) + 1;
1016 qcow2_free_clusters(bs,
1017 (l2_entry & s->cluster_offset_mask) & ~511,
1018 nb_csectors * 512, type);
1020 break;
1021 case QCOW2_CLUSTER_NORMAL:
1022 case QCOW2_CLUSTER_ZERO:
1023 if (l2_entry & L2E_OFFSET_MASK) {
1024 if (offset_into_cluster(s, l2_entry & L2E_OFFSET_MASK)) {
1025 qcow2_signal_corruption(bs, false, -1, -1,
1026 "Cannot free unaligned cluster %#llx",
1027 l2_entry & L2E_OFFSET_MASK);
1028 } else {
1029 qcow2_free_clusters(bs, l2_entry & L2E_OFFSET_MASK,
1030 nb_clusters << s->cluster_bits, type);
1033 break;
1034 case QCOW2_CLUSTER_UNALLOCATED:
1035 break;
1036 default:
1037 abort();
1043 /*********************************************************/
1044 /* snapshots and image creation */
1048 /* update the refcounts of snapshots and the copied flag */
1049 int qcow2_update_snapshot_refcount(BlockDriverState *bs,
1050 int64_t l1_table_offset, int l1_size, int addend)
1052 BDRVQcowState *s = bs->opaque;
1053 uint64_t *l1_table, *l2_table, l2_offset, offset, l1_size2, refcount;
1054 bool l1_allocated = false;
1055 int64_t old_offset, old_l2_offset;
1056 int i, j, l1_modified = 0, nb_csectors;
1057 int ret;
1059 assert(addend >= -1 && addend <= 1);
1061 l2_table = NULL;
1062 l1_table = NULL;
1063 l1_size2 = l1_size * sizeof(uint64_t);
1065 s->cache_discards = true;
1067 /* WARNING: qcow2_snapshot_goto relies on this function not using the
1068 * l1_table_offset when it is the current s->l1_table_offset! Be careful
1069 * when changing this! */
1070 if (l1_table_offset != s->l1_table_offset) {
1071 l1_table = g_try_malloc0(align_offset(l1_size2, 512));
1072 if (l1_size2 && l1_table == NULL) {
1073 ret = -ENOMEM;
1074 goto fail;
1076 l1_allocated = true;
1078 ret = bdrv_pread(bs->file, l1_table_offset, l1_table, l1_size2);
1079 if (ret < 0) {
1080 goto fail;
1083 for(i = 0;i < l1_size; i++)
1084 be64_to_cpus(&l1_table[i]);
1085 } else {
1086 assert(l1_size == s->l1_size);
1087 l1_table = s->l1_table;
1088 l1_allocated = false;
1091 for(i = 0; i < l1_size; i++) {
1092 l2_offset = l1_table[i];
1093 if (l2_offset) {
1094 old_l2_offset = l2_offset;
1095 l2_offset &= L1E_OFFSET_MASK;
1097 if (offset_into_cluster(s, l2_offset)) {
1098 qcow2_signal_corruption(bs, true, -1, -1, "L2 table offset %#"
1099 PRIx64 " unaligned (L1 index: %#x)",
1100 l2_offset, i);
1101 ret = -EIO;
1102 goto fail;
1105 ret = qcow2_cache_get(bs, s->l2_table_cache, l2_offset,
1106 (void**) &l2_table);
1107 if (ret < 0) {
1108 goto fail;
1111 for(j = 0; j < s->l2_size; j++) {
1112 uint64_t cluster_index;
1114 offset = be64_to_cpu(l2_table[j]);
1115 old_offset = offset;
1116 offset &= ~QCOW_OFLAG_COPIED;
1118 switch (qcow2_get_cluster_type(offset)) {
1119 case QCOW2_CLUSTER_COMPRESSED:
1120 nb_csectors = ((offset >> s->csize_shift) &
1121 s->csize_mask) + 1;
1122 if (addend != 0) {
1123 ret = update_refcount(bs,
1124 (offset & s->cluster_offset_mask) & ~511,
1125 nb_csectors * 512, abs(addend), addend < 0,
1126 QCOW2_DISCARD_SNAPSHOT);
1127 if (ret < 0) {
1128 goto fail;
1131 /* compressed clusters are never modified */
1132 refcount = 2;
1133 break;
1135 case QCOW2_CLUSTER_NORMAL:
1136 case QCOW2_CLUSTER_ZERO:
1137 if (offset_into_cluster(s, offset & L2E_OFFSET_MASK)) {
1138 qcow2_signal_corruption(bs, true, -1, -1, "Data "
1139 "cluster offset %#llx "
1140 "unaligned (L2 offset: %#"
1141 PRIx64 ", L2 index: %#x)",
1142 offset & L2E_OFFSET_MASK,
1143 l2_offset, j);
1144 ret = -EIO;
1145 goto fail;
1148 cluster_index = (offset & L2E_OFFSET_MASK) >> s->cluster_bits;
1149 if (!cluster_index) {
1150 /* unallocated */
1151 refcount = 0;
1152 break;
1154 if (addend != 0) {
1155 ret = qcow2_update_cluster_refcount(bs,
1156 cluster_index, abs(addend), addend < 0,
1157 QCOW2_DISCARD_SNAPSHOT);
1158 if (ret < 0) {
1159 goto fail;
1163 ret = qcow2_get_refcount(bs, cluster_index, &refcount);
1164 if (ret < 0) {
1165 goto fail;
1167 break;
1169 case QCOW2_CLUSTER_UNALLOCATED:
1170 refcount = 0;
1171 break;
1173 default:
1174 abort();
1177 if (refcount == 1) {
1178 offset |= QCOW_OFLAG_COPIED;
1180 if (offset != old_offset) {
1181 if (addend > 0) {
1182 qcow2_cache_set_dependency(bs, s->l2_table_cache,
1183 s->refcount_block_cache);
1185 l2_table[j] = cpu_to_be64(offset);
1186 qcow2_cache_entry_mark_dirty(bs, s->l2_table_cache,
1187 l2_table);
1191 ret = qcow2_cache_put(bs, s->l2_table_cache, (void**) &l2_table);
1192 if (ret < 0) {
1193 goto fail;
1197 if (addend != 0) {
1198 ret = qcow2_update_cluster_refcount(bs, l2_offset >>
1199 s->cluster_bits,
1200 abs(addend), addend < 0,
1201 QCOW2_DISCARD_SNAPSHOT);
1202 if (ret < 0) {
1203 goto fail;
1206 ret = qcow2_get_refcount(bs, l2_offset >> s->cluster_bits,
1207 &refcount);
1208 if (ret < 0) {
1209 goto fail;
1210 } else if (refcount == 1) {
1211 l2_offset |= QCOW_OFLAG_COPIED;
1213 if (l2_offset != old_l2_offset) {
1214 l1_table[i] = l2_offset;
1215 l1_modified = 1;
1220 ret = bdrv_flush(bs);
1221 fail:
1222 if (l2_table) {
1223 qcow2_cache_put(bs, s->l2_table_cache, (void**) &l2_table);
1226 s->cache_discards = false;
1227 qcow2_process_discards(bs, ret);
1229 /* Update L1 only if it isn't deleted anyway (addend = -1) */
1230 if (ret == 0 && addend >= 0 && l1_modified) {
1231 for (i = 0; i < l1_size; i++) {
1232 cpu_to_be64s(&l1_table[i]);
1235 ret = bdrv_pwrite_sync(bs->file, l1_table_offset, l1_table, l1_size2);
1237 for (i = 0; i < l1_size; i++) {
1238 be64_to_cpus(&l1_table[i]);
1241 if (l1_allocated)
1242 g_free(l1_table);
1243 return ret;
1249 /*********************************************************/
1250 /* refcount checking functions */
1253 static size_t refcount_array_byte_size(BDRVQcowState *s, uint64_t entries)
1255 /* This assertion holds because there is no way we can address more than
1256 * 2^(64 - 9) clusters at once (with cluster size 512 = 2^9, and because
1257 * offsets have to be representable in bytes); due to every cluster
1258 * corresponding to one refcount entry, we are well below that limit */
1259 assert(entries < (UINT64_C(1) << (64 - 9)));
1261 /* Thanks to the assertion this will not overflow, because
1262 * s->refcount_order < 7.
1263 * (note: x << s->refcount_order == x * s->refcount_bits) */
1264 return DIV_ROUND_UP(entries << s->refcount_order, 8);
1268 * Reallocates *array so that it can hold new_size entries. *size must contain
1269 * the current number of entries in *array. If the reallocation fails, *array
1270 * and *size will not be modified and -errno will be returned. If the
1271 * reallocation is successful, *array will be set to the new buffer, *size
1272 * will be set to new_size and 0 will be returned. The size of the reallocated
1273 * refcount array buffer will be aligned to a cluster boundary, and the newly
1274 * allocated area will be zeroed.
1276 static int realloc_refcount_array(BDRVQcowState *s, void **array,
1277 int64_t *size, int64_t new_size)
1279 size_t old_byte_size, new_byte_size;
1280 void *new_ptr;
1282 /* Round to clusters so the array can be directly written to disk */
1283 old_byte_size = size_to_clusters(s, refcount_array_byte_size(s, *size))
1284 * s->cluster_size;
1285 new_byte_size = size_to_clusters(s, refcount_array_byte_size(s, new_size))
1286 * s->cluster_size;
1288 if (new_byte_size == old_byte_size) {
1289 *size = new_size;
1290 return 0;
1293 assert(new_byte_size > 0);
1295 new_ptr = g_try_realloc(*array, new_byte_size);
1296 if (!new_ptr) {
1297 return -ENOMEM;
1300 if (new_byte_size > old_byte_size) {
1301 memset((void *)((uintptr_t)new_ptr + old_byte_size), 0,
1302 new_byte_size - old_byte_size);
1305 *array = new_ptr;
1306 *size = new_size;
1308 return 0;
1312 * Increases the refcount for a range of clusters in a given refcount table.
1313 * This is used to construct a temporary refcount table out of L1 and L2 tables
1314 * which can be compared the the refcount table saved in the image.
1316 * Modifies the number of errors in res.
1318 static int inc_refcounts(BlockDriverState *bs,
1319 BdrvCheckResult *res,
1320 void **refcount_table,
1321 int64_t *refcount_table_size,
1322 int64_t offset, int64_t size)
1324 BDRVQcowState *s = bs->opaque;
1325 uint64_t start, last, cluster_offset, k, refcount;
1326 int ret;
1328 if (size <= 0) {
1329 return 0;
1332 start = start_of_cluster(s, offset);
1333 last = start_of_cluster(s, offset + size - 1);
1334 for(cluster_offset = start; cluster_offset <= last;
1335 cluster_offset += s->cluster_size) {
1336 k = cluster_offset >> s->cluster_bits;
1337 if (k >= *refcount_table_size) {
1338 ret = realloc_refcount_array(s, refcount_table,
1339 refcount_table_size, k + 1);
1340 if (ret < 0) {
1341 res->check_errors++;
1342 return ret;
1346 refcount = s->get_refcount(*refcount_table, k);
1347 if (refcount == s->refcount_max) {
1348 fprintf(stderr, "ERROR: overflow cluster offset=0x%" PRIx64
1349 "\n", cluster_offset);
1350 res->corruptions++;
1351 continue;
1353 s->set_refcount(*refcount_table, k, refcount + 1);
1356 return 0;
1359 /* Flags for check_refcounts_l1() and check_refcounts_l2() */
1360 enum {
1361 CHECK_FRAG_INFO = 0x2, /* update BlockFragInfo counters */
1365 * Increases the refcount in the given refcount table for the all clusters
1366 * referenced in the L2 table. While doing so, performs some checks on L2
1367 * entries.
1369 * Returns the number of errors found by the checks or -errno if an internal
1370 * error occurred.
1372 static int check_refcounts_l2(BlockDriverState *bs, BdrvCheckResult *res,
1373 void **refcount_table,
1374 int64_t *refcount_table_size, int64_t l2_offset,
1375 int flags)
1377 BDRVQcowState *s = bs->opaque;
1378 uint64_t *l2_table, l2_entry;
1379 uint64_t next_contiguous_offset = 0;
1380 int i, l2_size, nb_csectors, ret;
1382 /* Read L2 table from disk */
1383 l2_size = s->l2_size * sizeof(uint64_t);
1384 l2_table = g_malloc(l2_size);
1386 ret = bdrv_pread(bs->file, l2_offset, l2_table, l2_size);
1387 if (ret < 0) {
1388 fprintf(stderr, "ERROR: I/O error in check_refcounts_l2\n");
1389 res->check_errors++;
1390 goto fail;
1393 /* Do the actual checks */
1394 for(i = 0; i < s->l2_size; i++) {
1395 l2_entry = be64_to_cpu(l2_table[i]);
1397 switch (qcow2_get_cluster_type(l2_entry)) {
1398 case QCOW2_CLUSTER_COMPRESSED:
1399 /* Compressed clusters don't have QCOW_OFLAG_COPIED */
1400 if (l2_entry & QCOW_OFLAG_COPIED) {
1401 fprintf(stderr, "ERROR: cluster %" PRId64 ": "
1402 "copied flag must never be set for compressed "
1403 "clusters\n", l2_entry >> s->cluster_bits);
1404 l2_entry &= ~QCOW_OFLAG_COPIED;
1405 res->corruptions++;
1408 /* Mark cluster as used */
1409 nb_csectors = ((l2_entry >> s->csize_shift) &
1410 s->csize_mask) + 1;
1411 l2_entry &= s->cluster_offset_mask;
1412 ret = inc_refcounts(bs, res, refcount_table, refcount_table_size,
1413 l2_entry & ~511, nb_csectors * 512);
1414 if (ret < 0) {
1415 goto fail;
1418 if (flags & CHECK_FRAG_INFO) {
1419 res->bfi.allocated_clusters++;
1420 res->bfi.compressed_clusters++;
1422 /* Compressed clusters are fragmented by nature. Since they
1423 * take up sub-sector space but we only have sector granularity
1424 * I/O we need to re-read the same sectors even for adjacent
1425 * compressed clusters.
1427 res->bfi.fragmented_clusters++;
1429 break;
1431 case QCOW2_CLUSTER_ZERO:
1432 if ((l2_entry & L2E_OFFSET_MASK) == 0) {
1433 break;
1435 /* fall through */
1437 case QCOW2_CLUSTER_NORMAL:
1439 uint64_t offset = l2_entry & L2E_OFFSET_MASK;
1441 if (flags & CHECK_FRAG_INFO) {
1442 res->bfi.allocated_clusters++;
1443 if (next_contiguous_offset &&
1444 offset != next_contiguous_offset) {
1445 res->bfi.fragmented_clusters++;
1447 next_contiguous_offset = offset + s->cluster_size;
1450 /* Mark cluster as used */
1451 ret = inc_refcounts(bs, res, refcount_table, refcount_table_size,
1452 offset, s->cluster_size);
1453 if (ret < 0) {
1454 goto fail;
1457 /* Correct offsets are cluster aligned */
1458 if (offset_into_cluster(s, offset)) {
1459 fprintf(stderr, "ERROR offset=%" PRIx64 ": Cluster is not "
1460 "properly aligned; L2 entry corrupted.\n", offset);
1461 res->corruptions++;
1463 break;
1466 case QCOW2_CLUSTER_UNALLOCATED:
1467 break;
1469 default:
1470 abort();
1474 g_free(l2_table);
1475 return 0;
1477 fail:
1478 g_free(l2_table);
1479 return ret;
1483 * Increases the refcount for the L1 table, its L2 tables and all referenced
1484 * clusters in the given refcount table. While doing so, performs some checks
1485 * on L1 and L2 entries.
1487 * Returns the number of errors found by the checks or -errno if an internal
1488 * error occurred.
1490 static int check_refcounts_l1(BlockDriverState *bs,
1491 BdrvCheckResult *res,
1492 void **refcount_table,
1493 int64_t *refcount_table_size,
1494 int64_t l1_table_offset, int l1_size,
1495 int flags)
1497 BDRVQcowState *s = bs->opaque;
1498 uint64_t *l1_table = NULL, l2_offset, l1_size2;
1499 int i, ret;
1501 l1_size2 = l1_size * sizeof(uint64_t);
1503 /* Mark L1 table as used */
1504 ret = inc_refcounts(bs, res, refcount_table, refcount_table_size,
1505 l1_table_offset, l1_size2);
1506 if (ret < 0) {
1507 goto fail;
1510 /* Read L1 table entries from disk */
1511 if (l1_size2 > 0) {
1512 l1_table = g_try_malloc(l1_size2);
1513 if (l1_table == NULL) {
1514 ret = -ENOMEM;
1515 res->check_errors++;
1516 goto fail;
1518 ret = bdrv_pread(bs->file, l1_table_offset, l1_table, l1_size2);
1519 if (ret < 0) {
1520 fprintf(stderr, "ERROR: I/O error in check_refcounts_l1\n");
1521 res->check_errors++;
1522 goto fail;
1524 for(i = 0;i < l1_size; i++)
1525 be64_to_cpus(&l1_table[i]);
1528 /* Do the actual checks */
1529 for(i = 0; i < l1_size; i++) {
1530 l2_offset = l1_table[i];
1531 if (l2_offset) {
1532 /* Mark L2 table as used */
1533 l2_offset &= L1E_OFFSET_MASK;
1534 ret = inc_refcounts(bs, res, refcount_table, refcount_table_size,
1535 l2_offset, s->cluster_size);
1536 if (ret < 0) {
1537 goto fail;
1540 /* L2 tables are cluster aligned */
1541 if (offset_into_cluster(s, l2_offset)) {
1542 fprintf(stderr, "ERROR l2_offset=%" PRIx64 ": Table is not "
1543 "cluster aligned; L1 entry corrupted\n", l2_offset);
1544 res->corruptions++;
1547 /* Process and check L2 entries */
1548 ret = check_refcounts_l2(bs, res, refcount_table,
1549 refcount_table_size, l2_offset, flags);
1550 if (ret < 0) {
1551 goto fail;
1555 g_free(l1_table);
1556 return 0;
1558 fail:
1559 g_free(l1_table);
1560 return ret;
1564 * Checks the OFLAG_COPIED flag for all L1 and L2 entries.
1566 * This function does not print an error message nor does it increment
1567 * check_errors if qcow2_get_refcount fails (this is because such an error will
1568 * have been already detected and sufficiently signaled by the calling function
1569 * (qcow2_check_refcounts) by the time this function is called).
1571 static int check_oflag_copied(BlockDriverState *bs, BdrvCheckResult *res,
1572 BdrvCheckMode fix)
1574 BDRVQcowState *s = bs->opaque;
1575 uint64_t *l2_table = qemu_blockalign(bs, s->cluster_size);
1576 int ret;
1577 uint64_t refcount;
1578 int i, j;
1580 for (i = 0; i < s->l1_size; i++) {
1581 uint64_t l1_entry = s->l1_table[i];
1582 uint64_t l2_offset = l1_entry & L1E_OFFSET_MASK;
1583 bool l2_dirty = false;
1585 if (!l2_offset) {
1586 continue;
1589 ret = qcow2_get_refcount(bs, l2_offset >> s->cluster_bits,
1590 &refcount);
1591 if (ret < 0) {
1592 /* don't print message nor increment check_errors */
1593 continue;
1595 if ((refcount == 1) != ((l1_entry & QCOW_OFLAG_COPIED) != 0)) {
1596 fprintf(stderr, "%s OFLAG_COPIED L2 cluster: l1_index=%d "
1597 "l1_entry=%" PRIx64 " refcount=%" PRIu64 "\n",
1598 fix & BDRV_FIX_ERRORS ? "Repairing" :
1599 "ERROR",
1600 i, l1_entry, refcount);
1601 if (fix & BDRV_FIX_ERRORS) {
1602 s->l1_table[i] = refcount == 1
1603 ? l1_entry | QCOW_OFLAG_COPIED
1604 : l1_entry & ~QCOW_OFLAG_COPIED;
1605 ret = qcow2_write_l1_entry(bs, i);
1606 if (ret < 0) {
1607 res->check_errors++;
1608 goto fail;
1610 res->corruptions_fixed++;
1611 } else {
1612 res->corruptions++;
1616 ret = bdrv_pread(bs->file, l2_offset, l2_table,
1617 s->l2_size * sizeof(uint64_t));
1618 if (ret < 0) {
1619 fprintf(stderr, "ERROR: Could not read L2 table: %s\n",
1620 strerror(-ret));
1621 res->check_errors++;
1622 goto fail;
1625 for (j = 0; j < s->l2_size; j++) {
1626 uint64_t l2_entry = be64_to_cpu(l2_table[j]);
1627 uint64_t data_offset = l2_entry & L2E_OFFSET_MASK;
1628 int cluster_type = qcow2_get_cluster_type(l2_entry);
1630 if ((cluster_type == QCOW2_CLUSTER_NORMAL) ||
1631 ((cluster_type == QCOW2_CLUSTER_ZERO) && (data_offset != 0))) {
1632 ret = qcow2_get_refcount(bs,
1633 data_offset >> s->cluster_bits,
1634 &refcount);
1635 if (ret < 0) {
1636 /* don't print message nor increment check_errors */
1637 continue;
1639 if ((refcount == 1) != ((l2_entry & QCOW_OFLAG_COPIED) != 0)) {
1640 fprintf(stderr, "%s OFLAG_COPIED data cluster: "
1641 "l2_entry=%" PRIx64 " refcount=%" PRIu64 "\n",
1642 fix & BDRV_FIX_ERRORS ? "Repairing" :
1643 "ERROR",
1644 l2_entry, refcount);
1645 if (fix & BDRV_FIX_ERRORS) {
1646 l2_table[j] = cpu_to_be64(refcount == 1
1647 ? l2_entry | QCOW_OFLAG_COPIED
1648 : l2_entry & ~QCOW_OFLAG_COPIED);
1649 l2_dirty = true;
1650 res->corruptions_fixed++;
1651 } else {
1652 res->corruptions++;
1658 if (l2_dirty) {
1659 ret = qcow2_pre_write_overlap_check(bs, QCOW2_OL_ACTIVE_L2,
1660 l2_offset, s->cluster_size);
1661 if (ret < 0) {
1662 fprintf(stderr, "ERROR: Could not write L2 table; metadata "
1663 "overlap check failed: %s\n", strerror(-ret));
1664 res->check_errors++;
1665 goto fail;
1668 ret = bdrv_pwrite(bs->file, l2_offset, l2_table, s->cluster_size);
1669 if (ret < 0) {
1670 fprintf(stderr, "ERROR: Could not write L2 table: %s\n",
1671 strerror(-ret));
1672 res->check_errors++;
1673 goto fail;
1678 ret = 0;
1680 fail:
1681 qemu_vfree(l2_table);
1682 return ret;
1686 * Checks consistency of refblocks and accounts for each refblock in
1687 * *refcount_table.
1689 static int check_refblocks(BlockDriverState *bs, BdrvCheckResult *res,
1690 BdrvCheckMode fix, bool *rebuild,
1691 void **refcount_table, int64_t *nb_clusters)
1693 BDRVQcowState *s = bs->opaque;
1694 int64_t i, size;
1695 int ret;
1697 for(i = 0; i < s->refcount_table_size; i++) {
1698 uint64_t offset, cluster;
1699 offset = s->refcount_table[i];
1700 cluster = offset >> s->cluster_bits;
1702 /* Refcount blocks are cluster aligned */
1703 if (offset_into_cluster(s, offset)) {
1704 fprintf(stderr, "ERROR refcount block %" PRId64 " is not "
1705 "cluster aligned; refcount table entry corrupted\n", i);
1706 res->corruptions++;
1707 *rebuild = true;
1708 continue;
1711 if (cluster >= *nb_clusters) {
1712 fprintf(stderr, "%s refcount block %" PRId64 " is outside image\n",
1713 fix & BDRV_FIX_ERRORS ? "Repairing" : "ERROR", i);
1715 if (fix & BDRV_FIX_ERRORS) {
1716 int64_t new_nb_clusters;
1718 if (offset > INT64_MAX - s->cluster_size) {
1719 ret = -EINVAL;
1720 goto resize_fail;
1723 ret = bdrv_truncate(bs->file, offset + s->cluster_size);
1724 if (ret < 0) {
1725 goto resize_fail;
1727 size = bdrv_getlength(bs->file);
1728 if (size < 0) {
1729 ret = size;
1730 goto resize_fail;
1733 new_nb_clusters = size_to_clusters(s, size);
1734 assert(new_nb_clusters >= *nb_clusters);
1736 ret = realloc_refcount_array(s, refcount_table,
1737 nb_clusters, new_nb_clusters);
1738 if (ret < 0) {
1739 res->check_errors++;
1740 return ret;
1743 if (cluster >= *nb_clusters) {
1744 ret = -EINVAL;
1745 goto resize_fail;
1748 res->corruptions_fixed++;
1749 ret = inc_refcounts(bs, res, refcount_table, nb_clusters,
1750 offset, s->cluster_size);
1751 if (ret < 0) {
1752 return ret;
1754 /* No need to check whether the refcount is now greater than 1:
1755 * This area was just allocated and zeroed, so it can only be
1756 * exactly 1 after inc_refcounts() */
1757 continue;
1759 resize_fail:
1760 res->corruptions++;
1761 *rebuild = true;
1762 fprintf(stderr, "ERROR could not resize image: %s\n",
1763 strerror(-ret));
1764 } else {
1765 res->corruptions++;
1767 continue;
1770 if (offset != 0) {
1771 ret = inc_refcounts(bs, res, refcount_table, nb_clusters,
1772 offset, s->cluster_size);
1773 if (ret < 0) {
1774 return ret;
1776 if (s->get_refcount(*refcount_table, cluster) != 1) {
1777 fprintf(stderr, "ERROR refcount block %" PRId64
1778 " refcount=%" PRIu64 "\n", i,
1779 s->get_refcount(*refcount_table, cluster));
1780 res->corruptions++;
1781 *rebuild = true;
1786 return 0;
1790 * Calculates an in-memory refcount table.
1792 static int calculate_refcounts(BlockDriverState *bs, BdrvCheckResult *res,
1793 BdrvCheckMode fix, bool *rebuild,
1794 void **refcount_table, int64_t *nb_clusters)
1796 BDRVQcowState *s = bs->opaque;
1797 int64_t i;
1798 QCowSnapshot *sn;
1799 int ret;
1801 if (!*refcount_table) {
1802 int64_t old_size = 0;
1803 ret = realloc_refcount_array(s, refcount_table,
1804 &old_size, *nb_clusters);
1805 if (ret < 0) {
1806 res->check_errors++;
1807 return ret;
1811 /* header */
1812 ret = inc_refcounts(bs, res, refcount_table, nb_clusters,
1813 0, s->cluster_size);
1814 if (ret < 0) {
1815 return ret;
1818 /* current L1 table */
1819 ret = check_refcounts_l1(bs, res, refcount_table, nb_clusters,
1820 s->l1_table_offset, s->l1_size, CHECK_FRAG_INFO);
1821 if (ret < 0) {
1822 return ret;
1825 /* snapshots */
1826 for (i = 0; i < s->nb_snapshots; i++) {
1827 sn = s->snapshots + i;
1828 ret = check_refcounts_l1(bs, res, refcount_table, nb_clusters,
1829 sn->l1_table_offset, sn->l1_size, 0);
1830 if (ret < 0) {
1831 return ret;
1834 ret = inc_refcounts(bs, res, refcount_table, nb_clusters,
1835 s->snapshots_offset, s->snapshots_size);
1836 if (ret < 0) {
1837 return ret;
1840 /* refcount data */
1841 ret = inc_refcounts(bs, res, refcount_table, nb_clusters,
1842 s->refcount_table_offset,
1843 s->refcount_table_size * sizeof(uint64_t));
1844 if (ret < 0) {
1845 return ret;
1848 return check_refblocks(bs, res, fix, rebuild, refcount_table, nb_clusters);
1852 * Compares the actual reference count for each cluster in the image against the
1853 * refcount as reported by the refcount structures on-disk.
1855 static void compare_refcounts(BlockDriverState *bs, BdrvCheckResult *res,
1856 BdrvCheckMode fix, bool *rebuild,
1857 int64_t *highest_cluster,
1858 void *refcount_table, int64_t nb_clusters)
1860 BDRVQcowState *s = bs->opaque;
1861 int64_t i;
1862 uint64_t refcount1, refcount2;
1863 int ret;
1865 for (i = 0, *highest_cluster = 0; i < nb_clusters; i++) {
1866 ret = qcow2_get_refcount(bs, i, &refcount1);
1867 if (ret < 0) {
1868 fprintf(stderr, "Can't get refcount for cluster %" PRId64 ": %s\n",
1869 i, strerror(-ret));
1870 res->check_errors++;
1871 continue;
1874 refcount2 = s->get_refcount(refcount_table, i);
1876 if (refcount1 > 0 || refcount2 > 0) {
1877 *highest_cluster = i;
1880 if (refcount1 != refcount2) {
1881 /* Check if we're allowed to fix the mismatch */
1882 int *num_fixed = NULL;
1883 if (refcount1 == 0) {
1884 *rebuild = true;
1885 } else if (refcount1 > refcount2 && (fix & BDRV_FIX_LEAKS)) {
1886 num_fixed = &res->leaks_fixed;
1887 } else if (refcount1 < refcount2 && (fix & BDRV_FIX_ERRORS)) {
1888 num_fixed = &res->corruptions_fixed;
1891 fprintf(stderr, "%s cluster %" PRId64 " refcount=%" PRIu64
1892 " reference=%" PRIu64 "\n",
1893 num_fixed != NULL ? "Repairing" :
1894 refcount1 < refcount2 ? "ERROR" :
1895 "Leaked",
1896 i, refcount1, refcount2);
1898 if (num_fixed) {
1899 ret = update_refcount(bs, i << s->cluster_bits, 1,
1900 refcount_diff(refcount1, refcount2),
1901 refcount1 > refcount2,
1902 QCOW2_DISCARD_ALWAYS);
1903 if (ret >= 0) {
1904 (*num_fixed)++;
1905 continue;
1909 /* And if we couldn't, print an error */
1910 if (refcount1 < refcount2) {
1911 res->corruptions++;
1912 } else {
1913 res->leaks++;
1920 * Allocates clusters using an in-memory refcount table (IMRT) in contrast to
1921 * the on-disk refcount structures.
1923 * On input, *first_free_cluster tells where to start looking, and need not
1924 * actually be a free cluster; the returned offset will not be before that
1925 * cluster. On output, *first_free_cluster points to the first gap found, even
1926 * if that gap was too small to be used as the returned offset.
1928 * Note that *first_free_cluster is a cluster index whereas the return value is
1929 * an offset.
1931 static int64_t alloc_clusters_imrt(BlockDriverState *bs,
1932 int cluster_count,
1933 void **refcount_table,
1934 int64_t *imrt_nb_clusters,
1935 int64_t *first_free_cluster)
1937 BDRVQcowState *s = bs->opaque;
1938 int64_t cluster = *first_free_cluster, i;
1939 bool first_gap = true;
1940 int contiguous_free_clusters;
1941 int ret;
1943 /* Starting at *first_free_cluster, find a range of at least cluster_count
1944 * continuously free clusters */
1945 for (contiguous_free_clusters = 0;
1946 cluster < *imrt_nb_clusters &&
1947 contiguous_free_clusters < cluster_count;
1948 cluster++)
1950 if (!s->get_refcount(*refcount_table, cluster)) {
1951 contiguous_free_clusters++;
1952 if (first_gap) {
1953 /* If this is the first free cluster found, update
1954 * *first_free_cluster accordingly */
1955 *first_free_cluster = cluster;
1956 first_gap = false;
1958 } else if (contiguous_free_clusters) {
1959 contiguous_free_clusters = 0;
1963 /* If contiguous_free_clusters is greater than zero, it contains the number
1964 * of continuously free clusters until the current cluster; the first free
1965 * cluster in the current "gap" is therefore
1966 * cluster - contiguous_free_clusters */
1968 /* If no such range could be found, grow the in-memory refcount table
1969 * accordingly to append free clusters at the end of the image */
1970 if (contiguous_free_clusters < cluster_count) {
1971 /* contiguous_free_clusters clusters are already empty at the image end;
1972 * we need cluster_count clusters; therefore, we have to allocate
1973 * cluster_count - contiguous_free_clusters new clusters at the end of
1974 * the image (which is the current value of cluster; note that cluster
1975 * may exceed old_imrt_nb_clusters if *first_free_cluster pointed beyond
1976 * the image end) */
1977 ret = realloc_refcount_array(s, refcount_table, imrt_nb_clusters,
1978 cluster + cluster_count
1979 - contiguous_free_clusters);
1980 if (ret < 0) {
1981 return ret;
1985 /* Go back to the first free cluster */
1986 cluster -= contiguous_free_clusters;
1987 for (i = 0; i < cluster_count; i++) {
1988 s->set_refcount(*refcount_table, cluster + i, 1);
1991 return cluster << s->cluster_bits;
1995 * Creates a new refcount structure based solely on the in-memory information
1996 * given through *refcount_table. All necessary allocations will be reflected
1997 * in that array.
1999 * On success, the old refcount structure is leaked (it will be covered by the
2000 * new refcount structure).
2002 static int rebuild_refcount_structure(BlockDriverState *bs,
2003 BdrvCheckResult *res,
2004 void **refcount_table,
2005 int64_t *nb_clusters)
2007 BDRVQcowState *s = bs->opaque;
2008 int64_t first_free_cluster = 0, reftable_offset = -1, cluster = 0;
2009 int64_t refblock_offset, refblock_start, refblock_index;
2010 uint32_t reftable_size = 0;
2011 uint64_t *on_disk_reftable = NULL;
2012 void *on_disk_refblock;
2013 int ret = 0;
2014 struct {
2015 uint64_t reftable_offset;
2016 uint32_t reftable_clusters;
2017 } QEMU_PACKED reftable_offset_and_clusters;
2019 qcow2_cache_empty(bs, s->refcount_block_cache);
2021 write_refblocks:
2022 for (; cluster < *nb_clusters; cluster++) {
2023 if (!s->get_refcount(*refcount_table, cluster)) {
2024 continue;
2027 refblock_index = cluster >> s->refcount_block_bits;
2028 refblock_start = refblock_index << s->refcount_block_bits;
2030 /* Don't allocate a cluster in a refblock already written to disk */
2031 if (first_free_cluster < refblock_start) {
2032 first_free_cluster = refblock_start;
2034 refblock_offset = alloc_clusters_imrt(bs, 1, refcount_table,
2035 nb_clusters, &first_free_cluster);
2036 if (refblock_offset < 0) {
2037 fprintf(stderr, "ERROR allocating refblock: %s\n",
2038 strerror(-refblock_offset));
2039 res->check_errors++;
2040 ret = refblock_offset;
2041 goto fail;
2044 if (reftable_size <= refblock_index) {
2045 uint32_t old_reftable_size = reftable_size;
2046 uint64_t *new_on_disk_reftable;
2048 reftable_size = ROUND_UP((refblock_index + 1) * sizeof(uint64_t),
2049 s->cluster_size) / sizeof(uint64_t);
2050 new_on_disk_reftable = g_try_realloc(on_disk_reftable,
2051 reftable_size *
2052 sizeof(uint64_t));
2053 if (!new_on_disk_reftable) {
2054 res->check_errors++;
2055 ret = -ENOMEM;
2056 goto fail;
2058 on_disk_reftable = new_on_disk_reftable;
2060 memset(on_disk_reftable + old_reftable_size, 0,
2061 (reftable_size - old_reftable_size) * sizeof(uint64_t));
2063 /* The offset we have for the reftable is now no longer valid;
2064 * this will leak that range, but we can easily fix that by running
2065 * a leak-fixing check after this rebuild operation */
2066 reftable_offset = -1;
2068 on_disk_reftable[refblock_index] = refblock_offset;
2070 /* If this is apparently the last refblock (for now), try to squeeze the
2071 * reftable in */
2072 if (refblock_index == (*nb_clusters - 1) >> s->refcount_block_bits &&
2073 reftable_offset < 0)
2075 uint64_t reftable_clusters = size_to_clusters(s, reftable_size *
2076 sizeof(uint64_t));
2077 reftable_offset = alloc_clusters_imrt(bs, reftable_clusters,
2078 refcount_table, nb_clusters,
2079 &first_free_cluster);
2080 if (reftable_offset < 0) {
2081 fprintf(stderr, "ERROR allocating reftable: %s\n",
2082 strerror(-reftable_offset));
2083 res->check_errors++;
2084 ret = reftable_offset;
2085 goto fail;
2089 ret = qcow2_pre_write_overlap_check(bs, 0, refblock_offset,
2090 s->cluster_size);
2091 if (ret < 0) {
2092 fprintf(stderr, "ERROR writing refblock: %s\n", strerror(-ret));
2093 goto fail;
2096 /* The size of *refcount_table is always cluster-aligned, therefore the
2097 * write operation will not overflow */
2098 on_disk_refblock = (void *)((char *) *refcount_table +
2099 refblock_index * s->cluster_size);
2101 ret = bdrv_write(bs->file, refblock_offset / BDRV_SECTOR_SIZE,
2102 on_disk_refblock, s->cluster_sectors);
2103 if (ret < 0) {
2104 fprintf(stderr, "ERROR writing refblock: %s\n", strerror(-ret));
2105 goto fail;
2108 /* Go to the end of this refblock */
2109 cluster = refblock_start + s->refcount_block_size - 1;
2112 if (reftable_offset < 0) {
2113 uint64_t post_refblock_start, reftable_clusters;
2115 post_refblock_start = ROUND_UP(*nb_clusters, s->refcount_block_size);
2116 reftable_clusters = size_to_clusters(s,
2117 reftable_size * sizeof(uint64_t));
2118 /* Not pretty but simple */
2119 if (first_free_cluster < post_refblock_start) {
2120 first_free_cluster = post_refblock_start;
2122 reftable_offset = alloc_clusters_imrt(bs, reftable_clusters,
2123 refcount_table, nb_clusters,
2124 &first_free_cluster);
2125 if (reftable_offset < 0) {
2126 fprintf(stderr, "ERROR allocating reftable: %s\n",
2127 strerror(-reftable_offset));
2128 res->check_errors++;
2129 ret = reftable_offset;
2130 goto fail;
2133 goto write_refblocks;
2136 assert(on_disk_reftable);
2138 for (refblock_index = 0; refblock_index < reftable_size; refblock_index++) {
2139 cpu_to_be64s(&on_disk_reftable[refblock_index]);
2142 ret = qcow2_pre_write_overlap_check(bs, 0, reftable_offset,
2143 reftable_size * sizeof(uint64_t));
2144 if (ret < 0) {
2145 fprintf(stderr, "ERROR writing reftable: %s\n", strerror(-ret));
2146 goto fail;
2149 assert(reftable_size < INT_MAX / sizeof(uint64_t));
2150 ret = bdrv_pwrite(bs->file, reftable_offset, on_disk_reftable,
2151 reftable_size * sizeof(uint64_t));
2152 if (ret < 0) {
2153 fprintf(stderr, "ERROR writing reftable: %s\n", strerror(-ret));
2154 goto fail;
2157 /* Enter new reftable into the image header */
2158 cpu_to_be64w(&reftable_offset_and_clusters.reftable_offset,
2159 reftable_offset);
2160 cpu_to_be32w(&reftable_offset_and_clusters.reftable_clusters,
2161 size_to_clusters(s, reftable_size * sizeof(uint64_t)));
2162 ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader,
2163 refcount_table_offset),
2164 &reftable_offset_and_clusters,
2165 sizeof(reftable_offset_and_clusters));
2166 if (ret < 0) {
2167 fprintf(stderr, "ERROR setting reftable: %s\n", strerror(-ret));
2168 goto fail;
2171 for (refblock_index = 0; refblock_index < reftable_size; refblock_index++) {
2172 be64_to_cpus(&on_disk_reftable[refblock_index]);
2174 s->refcount_table = on_disk_reftable;
2175 s->refcount_table_offset = reftable_offset;
2176 s->refcount_table_size = reftable_size;
2178 return 0;
2180 fail:
2181 g_free(on_disk_reftable);
2182 return ret;
2186 * Checks an image for refcount consistency.
2188 * Returns 0 if no errors are found, the number of errors in case the image is
2189 * detected as corrupted, and -errno when an internal error occurred.
2191 int qcow2_check_refcounts(BlockDriverState *bs, BdrvCheckResult *res,
2192 BdrvCheckMode fix)
2194 BDRVQcowState *s = bs->opaque;
2195 BdrvCheckResult pre_compare_res;
2196 int64_t size, highest_cluster, nb_clusters;
2197 void *refcount_table = NULL;
2198 bool rebuild = false;
2199 int ret;
2201 size = bdrv_getlength(bs->file);
2202 if (size < 0) {
2203 res->check_errors++;
2204 return size;
2207 nb_clusters = size_to_clusters(s, size);
2208 if (nb_clusters > INT_MAX) {
2209 res->check_errors++;
2210 return -EFBIG;
2213 res->bfi.total_clusters =
2214 size_to_clusters(s, bs->total_sectors * BDRV_SECTOR_SIZE);
2216 ret = calculate_refcounts(bs, res, fix, &rebuild, &refcount_table,
2217 &nb_clusters);
2218 if (ret < 0) {
2219 goto fail;
2222 /* In case we don't need to rebuild the refcount structure (but want to fix
2223 * something), this function is immediately called again, in which case the
2224 * result should be ignored */
2225 pre_compare_res = *res;
2226 compare_refcounts(bs, res, 0, &rebuild, &highest_cluster, refcount_table,
2227 nb_clusters);
2229 if (rebuild && (fix & BDRV_FIX_ERRORS)) {
2230 BdrvCheckResult old_res = *res;
2231 int fresh_leaks = 0;
2233 fprintf(stderr, "Rebuilding refcount structure\n");
2234 ret = rebuild_refcount_structure(bs, res, &refcount_table,
2235 &nb_clusters);
2236 if (ret < 0) {
2237 goto fail;
2240 res->corruptions = 0;
2241 res->leaks = 0;
2243 /* Because the old reftable has been exchanged for a new one the
2244 * references have to be recalculated */
2245 rebuild = false;
2246 memset(refcount_table, 0, refcount_array_byte_size(s, nb_clusters));
2247 ret = calculate_refcounts(bs, res, 0, &rebuild, &refcount_table,
2248 &nb_clusters);
2249 if (ret < 0) {
2250 goto fail;
2253 if (fix & BDRV_FIX_LEAKS) {
2254 /* The old refcount structures are now leaked, fix it; the result
2255 * can be ignored, aside from leaks which were introduced by
2256 * rebuild_refcount_structure() that could not be fixed */
2257 BdrvCheckResult saved_res = *res;
2258 *res = (BdrvCheckResult){ 0 };
2260 compare_refcounts(bs, res, BDRV_FIX_LEAKS, &rebuild,
2261 &highest_cluster, refcount_table, nb_clusters);
2262 if (rebuild) {
2263 fprintf(stderr, "ERROR rebuilt refcount structure is still "
2264 "broken\n");
2267 /* Any leaks accounted for here were introduced by
2268 * rebuild_refcount_structure() because that function has created a
2269 * new refcount structure from scratch */
2270 fresh_leaks = res->leaks;
2271 *res = saved_res;
2274 if (res->corruptions < old_res.corruptions) {
2275 res->corruptions_fixed += old_res.corruptions - res->corruptions;
2277 if (res->leaks < old_res.leaks) {
2278 res->leaks_fixed += old_res.leaks - res->leaks;
2280 res->leaks += fresh_leaks;
2281 } else if (fix) {
2282 if (rebuild) {
2283 fprintf(stderr, "ERROR need to rebuild refcount structures\n");
2284 res->check_errors++;
2285 ret = -EIO;
2286 goto fail;
2289 if (res->leaks || res->corruptions) {
2290 *res = pre_compare_res;
2291 compare_refcounts(bs, res, fix, &rebuild, &highest_cluster,
2292 refcount_table, nb_clusters);
2296 /* check OFLAG_COPIED */
2297 ret = check_oflag_copied(bs, res, fix);
2298 if (ret < 0) {
2299 goto fail;
2302 res->image_end_offset = (highest_cluster + 1) * s->cluster_size;
2303 ret = 0;
2305 fail:
2306 g_free(refcount_table);
2308 return ret;
2311 #define overlaps_with(ofs, sz) \
2312 ranges_overlap(offset, size, ofs, sz)
2315 * Checks if the given offset into the image file is actually free to use by
2316 * looking for overlaps with important metadata sections (L1/L2 tables etc.),
2317 * i.e. a sanity check without relying on the refcount tables.
2319 * The ign parameter specifies what checks not to perform (being a bitmask of
2320 * QCow2MetadataOverlap values), i.e., what sections to ignore.
2322 * Returns:
2323 * - 0 if writing to this offset will not affect the mentioned metadata
2324 * - a positive QCow2MetadataOverlap value indicating one overlapping section
2325 * - a negative value (-errno) indicating an error while performing a check,
2326 * e.g. when bdrv_read failed on QCOW2_OL_INACTIVE_L2
2328 int qcow2_check_metadata_overlap(BlockDriverState *bs, int ign, int64_t offset,
2329 int64_t size)
2331 BDRVQcowState *s = bs->opaque;
2332 int chk = s->overlap_check & ~ign;
2333 int i, j;
2335 if (!size) {
2336 return 0;
2339 if (chk & QCOW2_OL_MAIN_HEADER) {
2340 if (offset < s->cluster_size) {
2341 return QCOW2_OL_MAIN_HEADER;
2345 /* align range to test to cluster boundaries */
2346 size = align_offset(offset_into_cluster(s, offset) + size, s->cluster_size);
2347 offset = start_of_cluster(s, offset);
2349 if ((chk & QCOW2_OL_ACTIVE_L1) && s->l1_size) {
2350 if (overlaps_with(s->l1_table_offset, s->l1_size * sizeof(uint64_t))) {
2351 return QCOW2_OL_ACTIVE_L1;
2355 if ((chk & QCOW2_OL_REFCOUNT_TABLE) && s->refcount_table_size) {
2356 if (overlaps_with(s->refcount_table_offset,
2357 s->refcount_table_size * sizeof(uint64_t))) {
2358 return QCOW2_OL_REFCOUNT_TABLE;
2362 if ((chk & QCOW2_OL_SNAPSHOT_TABLE) && s->snapshots_size) {
2363 if (overlaps_with(s->snapshots_offset, s->snapshots_size)) {
2364 return QCOW2_OL_SNAPSHOT_TABLE;
2368 if ((chk & QCOW2_OL_INACTIVE_L1) && s->snapshots) {
2369 for (i = 0; i < s->nb_snapshots; i++) {
2370 if (s->snapshots[i].l1_size &&
2371 overlaps_with(s->snapshots[i].l1_table_offset,
2372 s->snapshots[i].l1_size * sizeof(uint64_t))) {
2373 return QCOW2_OL_INACTIVE_L1;
2378 if ((chk & QCOW2_OL_ACTIVE_L2) && s->l1_table) {
2379 for (i = 0; i < s->l1_size; i++) {
2380 if ((s->l1_table[i] & L1E_OFFSET_MASK) &&
2381 overlaps_with(s->l1_table[i] & L1E_OFFSET_MASK,
2382 s->cluster_size)) {
2383 return QCOW2_OL_ACTIVE_L2;
2388 if ((chk & QCOW2_OL_REFCOUNT_BLOCK) && s->refcount_table) {
2389 for (i = 0; i < s->refcount_table_size; i++) {
2390 if ((s->refcount_table[i] & REFT_OFFSET_MASK) &&
2391 overlaps_with(s->refcount_table[i] & REFT_OFFSET_MASK,
2392 s->cluster_size)) {
2393 return QCOW2_OL_REFCOUNT_BLOCK;
2398 if ((chk & QCOW2_OL_INACTIVE_L2) && s->snapshots) {
2399 for (i = 0; i < s->nb_snapshots; i++) {
2400 uint64_t l1_ofs = s->snapshots[i].l1_table_offset;
2401 uint32_t l1_sz = s->snapshots[i].l1_size;
2402 uint64_t l1_sz2 = l1_sz * sizeof(uint64_t);
2403 uint64_t *l1 = g_try_malloc(l1_sz2);
2404 int ret;
2406 if (l1_sz2 && l1 == NULL) {
2407 return -ENOMEM;
2410 ret = bdrv_pread(bs->file, l1_ofs, l1, l1_sz2);
2411 if (ret < 0) {
2412 g_free(l1);
2413 return ret;
2416 for (j = 0; j < l1_sz; j++) {
2417 uint64_t l2_ofs = be64_to_cpu(l1[j]) & L1E_OFFSET_MASK;
2418 if (l2_ofs && overlaps_with(l2_ofs, s->cluster_size)) {
2419 g_free(l1);
2420 return QCOW2_OL_INACTIVE_L2;
2424 g_free(l1);
2428 return 0;
2431 static const char *metadata_ol_names[] = {
2432 [QCOW2_OL_MAIN_HEADER_BITNR] = "qcow2_header",
2433 [QCOW2_OL_ACTIVE_L1_BITNR] = "active L1 table",
2434 [QCOW2_OL_ACTIVE_L2_BITNR] = "active L2 table",
2435 [QCOW2_OL_REFCOUNT_TABLE_BITNR] = "refcount table",
2436 [QCOW2_OL_REFCOUNT_BLOCK_BITNR] = "refcount block",
2437 [QCOW2_OL_SNAPSHOT_TABLE_BITNR] = "snapshot table",
2438 [QCOW2_OL_INACTIVE_L1_BITNR] = "inactive L1 table",
2439 [QCOW2_OL_INACTIVE_L2_BITNR] = "inactive L2 table",
2443 * First performs a check for metadata overlaps (through
2444 * qcow2_check_metadata_overlap); if that fails with a negative value (error
2445 * while performing a check), that value is returned. If an impending overlap
2446 * is detected, the BDS will be made unusable, the qcow2 file marked corrupt
2447 * and -EIO returned.
2449 * Returns 0 if there were neither overlaps nor errors while checking for
2450 * overlaps; or a negative value (-errno) on error.
2452 int qcow2_pre_write_overlap_check(BlockDriverState *bs, int ign, int64_t offset,
2453 int64_t size)
2455 int ret = qcow2_check_metadata_overlap(bs, ign, offset, size);
2457 if (ret < 0) {
2458 return ret;
2459 } else if (ret > 0) {
2460 int metadata_ol_bitnr = ctz32(ret);
2461 assert(metadata_ol_bitnr < QCOW2_OL_MAX_BITNR);
2463 qcow2_signal_corruption(bs, true, offset, size, "Preventing invalid "
2464 "write on metadata (overlaps with %s)",
2465 metadata_ol_names[metadata_ol_bitnr]);
2466 return -EIO;
2469 return 0;