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
25 #include "qemu/osdep.h"
26 #include "qapi/error.h"
27 #include "qemu-common.h"
28 #include "block/block_int.h"
29 #include "block/qcow2.h"
30 #include "qemu/range.h"
31 #include "qemu/bswap.h"
33 static int64_t alloc_clusters_noref(BlockDriverState
*bs
, uint64_t size
);
34 static int QEMU_WARN_UNUSED_RESULT
update_refcount(BlockDriverState
*bs
,
35 int64_t offset
, int64_t length
, uint64_t addend
,
36 bool decrease
, enum qcow2_discard_type type
);
38 static uint64_t get_refcount_ro0(const void *refcount_array
, uint64_t index
);
39 static uint64_t get_refcount_ro1(const void *refcount_array
, uint64_t index
);
40 static uint64_t get_refcount_ro2(const void *refcount_array
, uint64_t index
);
41 static uint64_t get_refcount_ro3(const void *refcount_array
, uint64_t index
);
42 static uint64_t get_refcount_ro4(const void *refcount_array
, uint64_t index
);
43 static uint64_t get_refcount_ro5(const void *refcount_array
, uint64_t index
);
44 static uint64_t get_refcount_ro6(const void *refcount_array
, uint64_t index
);
46 static void set_refcount_ro0(void *refcount_array
, uint64_t index
,
48 static void set_refcount_ro1(void *refcount_array
, uint64_t index
,
50 static void set_refcount_ro2(void *refcount_array
, uint64_t index
,
52 static void set_refcount_ro3(void *refcount_array
, uint64_t index
,
54 static void set_refcount_ro4(void *refcount_array
, uint64_t index
,
56 static void set_refcount_ro5(void *refcount_array
, uint64_t index
,
58 static void set_refcount_ro6(void *refcount_array
, uint64_t index
,
62 static Qcow2GetRefcountFunc
*const get_refcount_funcs
[] = {
72 static Qcow2SetRefcountFunc
*const set_refcount_funcs
[] = {
83 /*********************************************************/
84 /* refcount handling */
86 int qcow2_refcount_init(BlockDriverState
*bs
)
88 BDRVQcow2State
*s
= bs
->opaque
;
89 unsigned int refcount_table_size2
, i
;
92 assert(s
->refcount_order
>= 0 && s
->refcount_order
<= 6);
94 s
->get_refcount
= get_refcount_funcs
[s
->refcount_order
];
95 s
->set_refcount
= set_refcount_funcs
[s
->refcount_order
];
97 assert(s
->refcount_table_size
<= INT_MAX
/ sizeof(uint64_t));
98 refcount_table_size2
= s
->refcount_table_size
* sizeof(uint64_t);
99 s
->refcount_table
= g_try_malloc(refcount_table_size2
);
101 if (s
->refcount_table_size
> 0) {
102 if (s
->refcount_table
== NULL
) {
106 BLKDBG_EVENT(bs
->file
, BLKDBG_REFTABLE_LOAD
);
107 ret
= bdrv_pread(bs
->file
->bs
, s
->refcount_table_offset
,
108 s
->refcount_table
, refcount_table_size2
);
112 for(i
= 0; i
< s
->refcount_table_size
; i
++)
113 be64_to_cpus(&s
->refcount_table
[i
]);
120 void qcow2_refcount_close(BlockDriverState
*bs
)
122 BDRVQcow2State
*s
= bs
->opaque
;
123 g_free(s
->refcount_table
);
127 static uint64_t get_refcount_ro0(const void *refcount_array
, uint64_t index
)
129 return (((const uint8_t *)refcount_array
)[index
/ 8] >> (index
% 8)) & 0x1;
132 static void set_refcount_ro0(void *refcount_array
, uint64_t index
,
135 assert(!(value
>> 1));
136 ((uint8_t *)refcount_array
)[index
/ 8] &= ~(0x1 << (index
% 8));
137 ((uint8_t *)refcount_array
)[index
/ 8] |= value
<< (index
% 8);
140 static uint64_t get_refcount_ro1(const void *refcount_array
, uint64_t index
)
142 return (((const uint8_t *)refcount_array
)[index
/ 4] >> (2 * (index
% 4)))
146 static void set_refcount_ro1(void *refcount_array
, uint64_t index
,
149 assert(!(value
>> 2));
150 ((uint8_t *)refcount_array
)[index
/ 4] &= ~(0x3 << (2 * (index
% 4)));
151 ((uint8_t *)refcount_array
)[index
/ 4] |= value
<< (2 * (index
% 4));
154 static uint64_t get_refcount_ro2(const void *refcount_array
, uint64_t index
)
156 return (((const uint8_t *)refcount_array
)[index
/ 2] >> (4 * (index
% 2)))
160 static void set_refcount_ro2(void *refcount_array
, uint64_t index
,
163 assert(!(value
>> 4));
164 ((uint8_t *)refcount_array
)[index
/ 2] &= ~(0xf << (4 * (index
% 2)));
165 ((uint8_t *)refcount_array
)[index
/ 2] |= value
<< (4 * (index
% 2));
168 static uint64_t get_refcount_ro3(const void *refcount_array
, uint64_t index
)
170 return ((const uint8_t *)refcount_array
)[index
];
173 static void set_refcount_ro3(void *refcount_array
, uint64_t index
,
176 assert(!(value
>> 8));
177 ((uint8_t *)refcount_array
)[index
] = value
;
180 static uint64_t get_refcount_ro4(const void *refcount_array
, uint64_t index
)
182 return be16_to_cpu(((const uint16_t *)refcount_array
)[index
]);
185 static void set_refcount_ro4(void *refcount_array
, uint64_t index
,
188 assert(!(value
>> 16));
189 ((uint16_t *)refcount_array
)[index
] = cpu_to_be16(value
);
192 static uint64_t get_refcount_ro5(const void *refcount_array
, uint64_t index
)
194 return be32_to_cpu(((const uint32_t *)refcount_array
)[index
]);
197 static void set_refcount_ro5(void *refcount_array
, uint64_t index
,
200 assert(!(value
>> 32));
201 ((uint32_t *)refcount_array
)[index
] = cpu_to_be32(value
);
204 static uint64_t get_refcount_ro6(const void *refcount_array
, uint64_t index
)
206 return be64_to_cpu(((const uint64_t *)refcount_array
)[index
]);
209 static void set_refcount_ro6(void *refcount_array
, uint64_t index
,
212 ((uint64_t *)refcount_array
)[index
] = cpu_to_be64(value
);
216 static int load_refcount_block(BlockDriverState
*bs
,
217 int64_t refcount_block_offset
,
218 void **refcount_block
)
220 BDRVQcow2State
*s
= bs
->opaque
;
223 BLKDBG_EVENT(bs
->file
, BLKDBG_REFBLOCK_LOAD
);
224 ret
= qcow2_cache_get(bs
, s
->refcount_block_cache
, refcount_block_offset
,
231 * Retrieves the refcount of the cluster given by its index and stores it in
232 * *refcount. Returns 0 on success and -errno on failure.
234 int qcow2_get_refcount(BlockDriverState
*bs
, int64_t cluster_index
,
237 BDRVQcow2State
*s
= bs
->opaque
;
238 uint64_t refcount_table_index
, block_index
;
239 int64_t refcount_block_offset
;
241 void *refcount_block
;
243 refcount_table_index
= cluster_index
>> s
->refcount_block_bits
;
244 if (refcount_table_index
>= s
->refcount_table_size
) {
248 refcount_block_offset
=
249 s
->refcount_table
[refcount_table_index
] & REFT_OFFSET_MASK
;
250 if (!refcount_block_offset
) {
255 if (offset_into_cluster(s
, refcount_block_offset
)) {
256 qcow2_signal_corruption(bs
, true, -1, -1, "Refblock offset %#" PRIx64
257 " unaligned (reftable index: %#" PRIx64
")",
258 refcount_block_offset
, refcount_table_index
);
262 ret
= qcow2_cache_get(bs
, s
->refcount_block_cache
, refcount_block_offset
,
268 block_index
= cluster_index
& (s
->refcount_block_size
- 1);
269 *refcount
= s
->get_refcount(refcount_block
, block_index
);
271 qcow2_cache_put(bs
, s
->refcount_block_cache
, &refcount_block
);
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(BDRVQcow2State
*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(BDRVQcow2State
*s
, uint64_t offset_a
,
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 BDRVQcow2State
*s
= bs
->opaque
;
315 unsigned int refcount_table_index
;
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
);
338 return load_refcount_block(bs
, refcount_block_offset
,
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
);
374 /* Allocate the refcount block itself and mark it as used */
375 int64_t new_block
= alloc_clusters_noref(bs
, s
->cluster_size
);
381 fprintf(stderr
, "qcow2: Allocate refcount block %d for %" PRIx64
383 refcount_table_index
, cluster_index
<< s
->cluster_bits
, new_block
);
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
,
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);
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
);
409 ret
= qcow2_cache_flush(bs
, s
->refcount_block_cache
);
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
,
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
);
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
->bs
,
438 s
->refcount_table_offset
+ refcount_table_index
* sizeof(uint64_t),
439 &data64
, sizeof(data64
));
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. */
451 qcow2_cache_put(bs
, s
->refcount_block_cache
, refcount_block
);
454 * If we come here, we need to grow the refcount table. Again, a new
455 * refcount table needs some space and we can't simply allocate to avoid
458 * Therefore let's grab new refcount blocks at the end of the image, which
459 * will describe themselves and the new refcount table. This way we can
460 * reference them only in the new table and do the switch to the new
461 * refcount table at once without producing an inconsistent state in
464 BLKDBG_EVENT(bs
->file
, BLKDBG_REFTABLE_GROW
);
466 /* Calculate the number of refcount blocks needed so far; this will be the
467 * basis for calculating the index of the first cluster used for the
468 * self-describing refcount structures which we are about to create.
470 * Because we reached this point, there cannot be any refcount entries for
471 * cluster_index or higher indices yet. However, because new_block has been
472 * allocated to describe that cluster (and it will assume this role later
473 * on), we cannot use that index; also, new_block may actually have a higher
474 * cluster index than cluster_index, so it needs to be taken into account
475 * here (and 1 needs to be added to its value because that cluster is used).
477 uint64_t blocks_used
= DIV_ROUND_UP(MAX(cluster_index
+ 1,
478 (new_block
>> s
->cluster_bits
) + 1),
479 s
->refcount_block_size
);
481 if (blocks_used
> QCOW_MAX_REFTABLE_SIZE
/ sizeof(uint64_t)) {
485 /* And now we need at least one block more for the new metadata */
486 uint64_t table_size
= next_refcount_table_size(s
, blocks_used
+ 1);
487 uint64_t last_table_size
;
488 uint64_t blocks_clusters
;
490 uint64_t table_clusters
=
491 size_to_clusters(s
, table_size
* sizeof(uint64_t));
492 blocks_clusters
= 1 +
493 DIV_ROUND_UP(table_clusters
, s
->refcount_block_size
);
494 uint64_t meta_clusters
= table_clusters
+ blocks_clusters
;
496 last_table_size
= table_size
;
497 table_size
= next_refcount_table_size(s
, blocks_used
+
498 DIV_ROUND_UP(meta_clusters
, s
->refcount_block_size
));
500 } while (last_table_size
!= table_size
);
503 fprintf(stderr
, "qcow2: Grow refcount table %" PRId32
" => %" PRId64
"\n",
504 s
->refcount_table_size
, table_size
);
507 /* Create the new refcount table and blocks */
508 uint64_t meta_offset
= (blocks_used
* s
->refcount_block_size
) *
510 uint64_t table_offset
= meta_offset
+ blocks_clusters
* s
->cluster_size
;
511 uint64_t *new_table
= g_try_new0(uint64_t, table_size
);
512 void *new_blocks
= g_try_malloc0(blocks_clusters
* s
->cluster_size
);
514 assert(table_size
> 0 && blocks_clusters
> 0);
515 if (new_table
== NULL
|| new_blocks
== NULL
) {
520 /* Fill the new refcount table */
521 memcpy(new_table
, s
->refcount_table
,
522 s
->refcount_table_size
* sizeof(uint64_t));
523 new_table
[refcount_table_index
] = new_block
;
526 for (i
= 0; i
< blocks_clusters
; i
++) {
527 new_table
[blocks_used
+ i
] = meta_offset
+ (i
* s
->cluster_size
);
530 /* Fill the refcount blocks */
531 uint64_t table_clusters
= size_to_clusters(s
, table_size
* sizeof(uint64_t));
533 for (i
= 0; i
< table_clusters
+ blocks_clusters
; i
++) {
534 s
->set_refcount(new_blocks
, block
++, 1);
537 /* Write refcount blocks to disk */
538 BLKDBG_EVENT(bs
->file
, BLKDBG_REFBLOCK_ALLOC_WRITE_BLOCKS
);
539 ret
= bdrv_pwrite_sync(bs
->file
->bs
, meta_offset
, new_blocks
,
540 blocks_clusters
* s
->cluster_size
);
547 /* Write refcount table to disk */
548 for(i
= 0; i
< table_size
; i
++) {
549 cpu_to_be64s(&new_table
[i
]);
552 BLKDBG_EVENT(bs
->file
, BLKDBG_REFBLOCK_ALLOC_WRITE_TABLE
);
553 ret
= bdrv_pwrite_sync(bs
->file
->bs
, table_offset
, new_table
,
554 table_size
* sizeof(uint64_t));
559 for(i
= 0; i
< table_size
; i
++) {
560 be64_to_cpus(&new_table
[i
]);
563 /* Hook up the new refcount table in the qcow2 header */
568 cpu_to_be64w(&data
.d64
, table_offset
);
569 cpu_to_be32w(&data
.d32
, table_clusters
);
570 BLKDBG_EVENT(bs
->file
, BLKDBG_REFBLOCK_ALLOC_SWITCH_TABLE
);
571 ret
= bdrv_pwrite_sync(bs
->file
->bs
,
572 offsetof(QCowHeader
, refcount_table_offset
),
573 &data
, sizeof(data
));
578 /* And switch it in memory */
579 uint64_t old_table_offset
= s
->refcount_table_offset
;
580 uint64_t old_table_size
= s
->refcount_table_size
;
582 g_free(s
->refcount_table
);
583 s
->refcount_table
= new_table
;
584 s
->refcount_table_size
= table_size
;
585 s
->refcount_table_offset
= table_offset
;
587 /* Free old table. */
588 qcow2_free_clusters(bs
, old_table_offset
, old_table_size
* sizeof(uint64_t),
589 QCOW2_DISCARD_OTHER
);
591 ret
= load_refcount_block(bs
, new_block
, refcount_block
);
596 /* If we were trying to do the initial refcount update for some cluster
597 * allocation, we might have used the same clusters to store newly
598 * allocated metadata. Make the caller search some new space. */
605 if (*refcount_block
!= NULL
) {
606 qcow2_cache_put(bs
, s
->refcount_block_cache
, refcount_block
);
611 void qcow2_process_discards(BlockDriverState
*bs
, int ret
)
613 BDRVQcow2State
*s
= bs
->opaque
;
614 Qcow2DiscardRegion
*d
, *next
;
616 QTAILQ_FOREACH_SAFE(d
, &s
->discards
, next
, next
) {
617 QTAILQ_REMOVE(&s
->discards
, d
, next
);
619 /* Discard is optional, ignore the return value */
621 bdrv_discard(bs
->file
->bs
,
622 d
->offset
>> BDRV_SECTOR_BITS
,
623 d
->bytes
>> BDRV_SECTOR_BITS
);
630 static void update_refcount_discard(BlockDriverState
*bs
,
631 uint64_t offset
, uint64_t length
)
633 BDRVQcow2State
*s
= bs
->opaque
;
634 Qcow2DiscardRegion
*d
, *p
, *next
;
636 QTAILQ_FOREACH(d
, &s
->discards
, next
) {
637 uint64_t new_start
= MIN(offset
, d
->offset
);
638 uint64_t new_end
= MAX(offset
+ length
, d
->offset
+ d
->bytes
);
640 if (new_end
- new_start
<= length
+ d
->bytes
) {
641 /* There can't be any overlap, areas ending up here have no
642 * references any more and therefore shouldn't get freed another
644 assert(d
->bytes
+ length
== new_end
- new_start
);
645 d
->offset
= new_start
;
646 d
->bytes
= new_end
- new_start
;
651 d
= g_malloc(sizeof(*d
));
652 *d
= (Qcow2DiscardRegion
) {
657 QTAILQ_INSERT_TAIL(&s
->discards
, d
, next
);
660 /* Merge discard requests if they are adjacent now */
661 QTAILQ_FOREACH_SAFE(p
, &s
->discards
, next
, next
) {
663 || p
->offset
> d
->offset
+ d
->bytes
664 || d
->offset
> p
->offset
+ p
->bytes
)
669 /* Still no overlap possible */
670 assert(p
->offset
== d
->offset
+ d
->bytes
671 || d
->offset
== p
->offset
+ p
->bytes
);
673 QTAILQ_REMOVE(&s
->discards
, p
, next
);
674 d
->offset
= MIN(d
->offset
, p
->offset
);
675 d
->bytes
+= p
->bytes
;
680 /* XXX: cache several refcount block clusters ? */
681 /* @addend is the absolute value of the addend; if @decrease is set, @addend
682 * will be subtracted from the current refcount, otherwise it will be added */
683 static int QEMU_WARN_UNUSED_RESULT
update_refcount(BlockDriverState
*bs
,
688 enum qcow2_discard_type type
)
690 BDRVQcow2State
*s
= bs
->opaque
;
691 int64_t start
, last
, cluster_offset
;
692 void *refcount_block
= NULL
;
693 int64_t old_table_index
= -1;
697 fprintf(stderr
, "update_refcount: offset=%" PRId64
" size=%" PRId64
698 " addend=%s%" PRIu64
"\n", offset
, length
, decrease
? "-" : "",
703 } else if (length
== 0) {
708 qcow2_cache_set_dependency(bs
, s
->refcount_block_cache
,
712 start
= start_of_cluster(s
, offset
);
713 last
= start_of_cluster(s
, offset
+ length
- 1);
714 for(cluster_offset
= start
; cluster_offset
<= last
;
715 cluster_offset
+= s
->cluster_size
)
719 int64_t cluster_index
= cluster_offset
>> s
->cluster_bits
;
720 int64_t table_index
= cluster_index
>> s
->refcount_block_bits
;
722 /* Load the refcount block and allocate it if needed */
723 if (table_index
!= old_table_index
) {
724 if (refcount_block
) {
725 qcow2_cache_put(bs
, s
->refcount_block_cache
, &refcount_block
);
727 ret
= alloc_refcount_block(bs
, cluster_index
, &refcount_block
);
732 old_table_index
= table_index
;
734 qcow2_cache_entry_mark_dirty(bs
, s
->refcount_block_cache
,
737 /* we can update the count and save it */
738 block_index
= cluster_index
& (s
->refcount_block_size
- 1);
740 refcount
= s
->get_refcount(refcount_block
, block_index
);
741 if (decrease
? (refcount
- addend
> refcount
)
742 : (refcount
+ addend
< refcount
||
743 refcount
+ addend
> s
->refcount_max
))
753 if (refcount
== 0 && cluster_index
< s
->free_cluster_index
) {
754 s
->free_cluster_index
= cluster_index
;
756 s
->set_refcount(refcount_block
, block_index
, refcount
);
758 if (refcount
== 0 && s
->discard_passthrough
[type
]) {
759 update_refcount_discard(bs
, cluster_offset
, s
->cluster_size
);
765 if (!s
->cache_discards
) {
766 qcow2_process_discards(bs
, ret
);
769 /* Write last changed block to disk */
770 if (refcount_block
) {
771 qcow2_cache_put(bs
, s
->refcount_block_cache
, &refcount_block
);
775 * Try do undo any updates if an error is returned (This may succeed in
776 * some cases like ENOSPC for allocating a new refcount block)
780 dummy
= update_refcount(bs
, offset
, cluster_offset
- offset
, addend
,
781 !decrease
, QCOW2_DISCARD_NEVER
);
789 * Increases or decreases the refcount of a given cluster.
791 * @addend is the absolute value of the addend; if @decrease is set, @addend
792 * will be subtracted from the current refcount, otherwise it will be added.
794 * On success 0 is returned; on failure -errno is returned.
796 int qcow2_update_cluster_refcount(BlockDriverState
*bs
,
797 int64_t cluster_index
,
798 uint64_t addend
, bool decrease
,
799 enum qcow2_discard_type type
)
801 BDRVQcow2State
*s
= bs
->opaque
;
804 ret
= update_refcount(bs
, cluster_index
<< s
->cluster_bits
, 1, addend
,
815 /*********************************************************/
816 /* cluster allocation functions */
820 /* return < 0 if error */
821 static int64_t alloc_clusters_noref(BlockDriverState
*bs
, uint64_t size
)
823 BDRVQcow2State
*s
= bs
->opaque
;
824 uint64_t i
, nb_clusters
, refcount
;
827 /* We can't allocate clusters if they may still be queued for discard. */
828 if (s
->cache_discards
) {
829 qcow2_process_discards(bs
, 0);
832 nb_clusters
= size_to_clusters(s
, size
);
834 for(i
= 0; i
< nb_clusters
; i
++) {
835 uint64_t next_cluster_index
= s
->free_cluster_index
++;
836 ret
= qcow2_get_refcount(bs
, next_cluster_index
, &refcount
);
840 } else if (refcount
!= 0) {
845 /* Make sure that all offsets in the "allocated" range are representable
847 if (s
->free_cluster_index
> 0 &&
848 s
->free_cluster_index
- 1 > (INT64_MAX
>> s
->cluster_bits
))
854 fprintf(stderr
, "alloc_clusters: size=%" PRId64
" -> %" PRId64
"\n",
856 (s
->free_cluster_index
- nb_clusters
) << s
->cluster_bits
);
858 return (s
->free_cluster_index
- nb_clusters
) << s
->cluster_bits
;
861 int64_t qcow2_alloc_clusters(BlockDriverState
*bs
, uint64_t size
)
866 BLKDBG_EVENT(bs
->file
, BLKDBG_CLUSTER_ALLOC
);
868 offset
= alloc_clusters_noref(bs
, size
);
873 ret
= update_refcount(bs
, offset
, size
, 1, false, QCOW2_DISCARD_NEVER
);
874 } while (ret
== -EAGAIN
);
883 int64_t qcow2_alloc_clusters_at(BlockDriverState
*bs
, uint64_t offset
,
886 BDRVQcow2State
*s
= bs
->opaque
;
887 uint64_t cluster_index
, refcount
;
891 assert(nb_clusters
>= 0);
892 if (nb_clusters
== 0) {
897 /* Check how many clusters there are free */
898 cluster_index
= offset
>> s
->cluster_bits
;
899 for(i
= 0; i
< nb_clusters
; i
++) {
900 ret
= qcow2_get_refcount(bs
, cluster_index
++, &refcount
);
903 } else if (refcount
!= 0) {
908 /* And then allocate them */
909 ret
= update_refcount(bs
, offset
, i
<< s
->cluster_bits
, 1, false,
910 QCOW2_DISCARD_NEVER
);
911 } while (ret
== -EAGAIN
);
920 /* only used to allocate compressed sectors. We try to allocate
921 contiguous sectors. size must be <= cluster_size */
922 int64_t qcow2_alloc_bytes(BlockDriverState
*bs
, int size
)
924 BDRVQcow2State
*s
= bs
->opaque
;
926 size_t free_in_cluster
;
929 BLKDBG_EVENT(bs
->file
, BLKDBG_CLUSTER_ALLOC_BYTES
);
930 assert(size
> 0 && size
<= s
->cluster_size
);
931 assert(!s
->free_byte_offset
|| offset_into_cluster(s
, s
->free_byte_offset
));
933 offset
= s
->free_byte_offset
;
937 ret
= qcow2_get_refcount(bs
, offset
>> s
->cluster_bits
, &refcount
);
942 if (refcount
== s
->refcount_max
) {
947 free_in_cluster
= s
->cluster_size
- offset_into_cluster(s
, offset
);
949 if (!offset
|| free_in_cluster
< size
) {
950 int64_t new_cluster
= alloc_clusters_noref(bs
, s
->cluster_size
);
951 if (new_cluster
< 0) {
955 if (!offset
|| ROUND_UP(offset
, s
->cluster_size
) != new_cluster
) {
956 offset
= new_cluster
;
957 free_in_cluster
= s
->cluster_size
;
959 free_in_cluster
+= s
->cluster_size
;
964 ret
= update_refcount(bs
, offset
, size
, 1, false, QCOW2_DISCARD_NEVER
);
968 } while (ret
== -EAGAIN
);
973 /* The cluster refcount was incremented; refcount blocks must be flushed
974 * before the caller's L2 table updates. */
975 qcow2_cache_set_dependency(bs
, s
->l2_table_cache
, s
->refcount_block_cache
);
977 s
->free_byte_offset
= offset
+ size
;
978 if (!offset_into_cluster(s
, s
->free_byte_offset
)) {
979 s
->free_byte_offset
= 0;
985 void qcow2_free_clusters(BlockDriverState
*bs
,
986 int64_t offset
, int64_t size
,
987 enum qcow2_discard_type type
)
991 BLKDBG_EVENT(bs
->file
, BLKDBG_CLUSTER_FREE
);
992 ret
= update_refcount(bs
, offset
, size
, 1, true, type
);
994 fprintf(stderr
, "qcow2_free_clusters failed: %s\n", strerror(-ret
));
995 /* TODO Remember the clusters to free them later and avoid leaking */
1000 * Free a cluster using its L2 entry (handles clusters of all types, e.g.
1001 * normal cluster, compressed cluster, etc.)
1003 void qcow2_free_any_clusters(BlockDriverState
*bs
, uint64_t l2_entry
,
1004 int nb_clusters
, enum qcow2_discard_type type
)
1006 BDRVQcow2State
*s
= bs
->opaque
;
1008 switch (qcow2_get_cluster_type(l2_entry
)) {
1009 case QCOW2_CLUSTER_COMPRESSED
:
1012 nb_csectors
= ((l2_entry
>> s
->csize_shift
) &
1014 qcow2_free_clusters(bs
,
1015 (l2_entry
& s
->cluster_offset_mask
) & ~511,
1016 nb_csectors
* 512, type
);
1019 case QCOW2_CLUSTER_NORMAL
:
1020 case QCOW2_CLUSTER_ZERO
:
1021 if (l2_entry
& L2E_OFFSET_MASK
) {
1022 if (offset_into_cluster(s
, l2_entry
& L2E_OFFSET_MASK
)) {
1023 qcow2_signal_corruption(bs
, false, -1, -1,
1024 "Cannot free unaligned cluster %#llx",
1025 l2_entry
& L2E_OFFSET_MASK
);
1027 qcow2_free_clusters(bs
, l2_entry
& L2E_OFFSET_MASK
,
1028 nb_clusters
<< s
->cluster_bits
, type
);
1032 case QCOW2_CLUSTER_UNALLOCATED
:
1041 /*********************************************************/
1042 /* snapshots and image creation */
1046 /* update the refcounts of snapshots and the copied flag */
1047 int qcow2_update_snapshot_refcount(BlockDriverState
*bs
,
1048 int64_t l1_table_offset
, int l1_size
, int addend
)
1050 BDRVQcow2State
*s
= bs
->opaque
;
1051 uint64_t *l1_table
, *l2_table
, l2_offset
, offset
, l1_size2
, refcount
;
1052 bool l1_allocated
= false;
1053 int64_t old_offset
, old_l2_offset
;
1054 int i
, j
, l1_modified
= 0, nb_csectors
;
1057 assert(addend
>= -1 && addend
<= 1);
1061 l1_size2
= l1_size
* sizeof(uint64_t);
1063 s
->cache_discards
= true;
1065 /* WARNING: qcow2_snapshot_goto relies on this function not using the
1066 * l1_table_offset when it is the current s->l1_table_offset! Be careful
1067 * when changing this! */
1068 if (l1_table_offset
!= s
->l1_table_offset
) {
1069 l1_table
= g_try_malloc0(align_offset(l1_size2
, 512));
1070 if (l1_size2
&& l1_table
== NULL
) {
1074 l1_allocated
= true;
1076 ret
= bdrv_pread(bs
->file
->bs
, l1_table_offset
, l1_table
, l1_size2
);
1081 for(i
= 0;i
< l1_size
; i
++)
1082 be64_to_cpus(&l1_table
[i
]);
1084 assert(l1_size
== s
->l1_size
);
1085 l1_table
= s
->l1_table
;
1086 l1_allocated
= false;
1089 for(i
= 0; i
< l1_size
; i
++) {
1090 l2_offset
= l1_table
[i
];
1092 old_l2_offset
= l2_offset
;
1093 l2_offset
&= L1E_OFFSET_MASK
;
1095 if (offset_into_cluster(s
, l2_offset
)) {
1096 qcow2_signal_corruption(bs
, true, -1, -1, "L2 table offset %#"
1097 PRIx64
" unaligned (L1 index: %#x)",
1103 ret
= qcow2_cache_get(bs
, s
->l2_table_cache
, l2_offset
,
1104 (void**) &l2_table
);
1109 for(j
= 0; j
< s
->l2_size
; j
++) {
1110 uint64_t cluster_index
;
1112 offset
= be64_to_cpu(l2_table
[j
]);
1113 old_offset
= offset
;
1114 offset
&= ~QCOW_OFLAG_COPIED
;
1116 switch (qcow2_get_cluster_type(offset
)) {
1117 case QCOW2_CLUSTER_COMPRESSED
:
1118 nb_csectors
= ((offset
>> s
->csize_shift
) &
1121 ret
= update_refcount(bs
,
1122 (offset
& s
->cluster_offset_mask
) & ~511,
1123 nb_csectors
* 512, abs(addend
), addend
< 0,
1124 QCOW2_DISCARD_SNAPSHOT
);
1129 /* compressed clusters are never modified */
1133 case QCOW2_CLUSTER_NORMAL
:
1134 case QCOW2_CLUSTER_ZERO
:
1135 if (offset_into_cluster(s
, offset
& L2E_OFFSET_MASK
)) {
1136 qcow2_signal_corruption(bs
, true, -1, -1, "Data "
1137 "cluster offset %#llx "
1138 "unaligned (L2 offset: %#"
1139 PRIx64
", L2 index: %#x)",
1140 offset
& L2E_OFFSET_MASK
,
1146 cluster_index
= (offset
& L2E_OFFSET_MASK
) >> s
->cluster_bits
;
1147 if (!cluster_index
) {
1153 ret
= qcow2_update_cluster_refcount(bs
,
1154 cluster_index
, abs(addend
), addend
< 0,
1155 QCOW2_DISCARD_SNAPSHOT
);
1161 ret
= qcow2_get_refcount(bs
, cluster_index
, &refcount
);
1167 case QCOW2_CLUSTER_UNALLOCATED
:
1175 if (refcount
== 1) {
1176 offset
|= QCOW_OFLAG_COPIED
;
1178 if (offset
!= old_offset
) {
1180 qcow2_cache_set_dependency(bs
, s
->l2_table_cache
,
1181 s
->refcount_block_cache
);
1183 l2_table
[j
] = cpu_to_be64(offset
);
1184 qcow2_cache_entry_mark_dirty(bs
, s
->l2_table_cache
,
1189 qcow2_cache_put(bs
, s
->l2_table_cache
, (void **) &l2_table
);
1192 ret
= qcow2_update_cluster_refcount(bs
, l2_offset
>>
1194 abs(addend
), addend
< 0,
1195 QCOW2_DISCARD_SNAPSHOT
);
1200 ret
= qcow2_get_refcount(bs
, l2_offset
>> s
->cluster_bits
,
1204 } else if (refcount
== 1) {
1205 l2_offset
|= QCOW_OFLAG_COPIED
;
1207 if (l2_offset
!= old_l2_offset
) {
1208 l1_table
[i
] = l2_offset
;
1214 ret
= bdrv_flush(bs
);
1217 qcow2_cache_put(bs
, s
->l2_table_cache
, (void**) &l2_table
);
1220 s
->cache_discards
= false;
1221 qcow2_process_discards(bs
, ret
);
1223 /* Update L1 only if it isn't deleted anyway (addend = -1) */
1224 if (ret
== 0 && addend
>= 0 && l1_modified
) {
1225 for (i
= 0; i
< l1_size
; i
++) {
1226 cpu_to_be64s(&l1_table
[i
]);
1229 ret
= bdrv_pwrite_sync(bs
->file
->bs
, l1_table_offset
,
1230 l1_table
, l1_size2
);
1232 for (i
= 0; i
< l1_size
; i
++) {
1233 be64_to_cpus(&l1_table
[i
]);
1244 /*********************************************************/
1245 /* refcount checking functions */
1248 static uint64_t refcount_array_byte_size(BDRVQcow2State
*s
, uint64_t entries
)
1250 /* This assertion holds because there is no way we can address more than
1251 * 2^(64 - 9) clusters at once (with cluster size 512 = 2^9, and because
1252 * offsets have to be representable in bytes); due to every cluster
1253 * corresponding to one refcount entry, we are well below that limit */
1254 assert(entries
< (UINT64_C(1) << (64 - 9)));
1256 /* Thanks to the assertion this will not overflow, because
1257 * s->refcount_order < 7.
1258 * (note: x << s->refcount_order == x * s->refcount_bits) */
1259 return DIV_ROUND_UP(entries
<< s
->refcount_order
, 8);
1263 * Reallocates *array so that it can hold new_size entries. *size must contain
1264 * the current number of entries in *array. If the reallocation fails, *array
1265 * and *size will not be modified and -errno will be returned. If the
1266 * reallocation is successful, *array will be set to the new buffer, *size
1267 * will be set to new_size and 0 will be returned. The size of the reallocated
1268 * refcount array buffer will be aligned to a cluster boundary, and the newly
1269 * allocated area will be zeroed.
1271 static int realloc_refcount_array(BDRVQcow2State
*s
, void **array
,
1272 int64_t *size
, int64_t new_size
)
1274 int64_t old_byte_size
, new_byte_size
;
1277 /* Round to clusters so the array can be directly written to disk */
1278 old_byte_size
= size_to_clusters(s
, refcount_array_byte_size(s
, *size
))
1280 new_byte_size
= size_to_clusters(s
, refcount_array_byte_size(s
, new_size
))
1283 if (new_byte_size
== old_byte_size
) {
1288 assert(new_byte_size
> 0);
1290 if (new_byte_size
> SIZE_MAX
) {
1294 new_ptr
= g_try_realloc(*array
, new_byte_size
);
1299 if (new_byte_size
> old_byte_size
) {
1300 memset((char *)new_ptr
+ old_byte_size
, 0,
1301 new_byte_size
- old_byte_size
);
1311 * Increases the refcount for a range of clusters in a given refcount table.
1312 * This is used to construct a temporary refcount table out of L1 and L2 tables
1313 * which can be compared to the refcount table saved in the image.
1315 * Modifies the number of errors in res.
1317 static int inc_refcounts(BlockDriverState
*bs
,
1318 BdrvCheckResult
*res
,
1319 void **refcount_table
,
1320 int64_t *refcount_table_size
,
1321 int64_t offset
, int64_t size
)
1323 BDRVQcow2State
*s
= bs
->opaque
;
1324 uint64_t start
, last
, cluster_offset
, k
, refcount
;
1331 start
= start_of_cluster(s
, offset
);
1332 last
= start_of_cluster(s
, offset
+ size
- 1);
1333 for(cluster_offset
= start
; cluster_offset
<= last
;
1334 cluster_offset
+= s
->cluster_size
) {
1335 k
= cluster_offset
>> s
->cluster_bits
;
1336 if (k
>= *refcount_table_size
) {
1337 ret
= realloc_refcount_array(s
, refcount_table
,
1338 refcount_table_size
, k
+ 1);
1340 res
->check_errors
++;
1345 refcount
= s
->get_refcount(*refcount_table
, k
);
1346 if (refcount
== s
->refcount_max
) {
1347 fprintf(stderr
, "ERROR: overflow cluster offset=0x%" PRIx64
1348 "\n", cluster_offset
);
1349 fprintf(stderr
, "Use qemu-img amend to increase the refcount entry "
1350 "width or qemu-img convert to create a clean copy if the "
1351 "image cannot be opened for writing\n");
1355 s
->set_refcount(*refcount_table
, k
, refcount
+ 1);
1361 /* Flags for check_refcounts_l1() and check_refcounts_l2() */
1363 CHECK_FRAG_INFO
= 0x2, /* update BlockFragInfo counters */
1367 * Increases the refcount in the given refcount table for the all clusters
1368 * referenced in the L2 table. While doing so, performs some checks on L2
1371 * Returns the number of errors found by the checks or -errno if an internal
1374 static int check_refcounts_l2(BlockDriverState
*bs
, BdrvCheckResult
*res
,
1375 void **refcount_table
,
1376 int64_t *refcount_table_size
, int64_t l2_offset
,
1379 BDRVQcow2State
*s
= bs
->opaque
;
1380 uint64_t *l2_table
, l2_entry
;
1381 uint64_t next_contiguous_offset
= 0;
1382 int i
, l2_size
, nb_csectors
, ret
;
1384 /* Read L2 table from disk */
1385 l2_size
= s
->l2_size
* sizeof(uint64_t);
1386 l2_table
= g_malloc(l2_size
);
1388 ret
= bdrv_pread(bs
->file
->bs
, l2_offset
, l2_table
, l2_size
);
1390 fprintf(stderr
, "ERROR: I/O error in check_refcounts_l2\n");
1391 res
->check_errors
++;
1395 /* Do the actual checks */
1396 for(i
= 0; i
< s
->l2_size
; i
++) {
1397 l2_entry
= be64_to_cpu(l2_table
[i
]);
1399 switch (qcow2_get_cluster_type(l2_entry
)) {
1400 case QCOW2_CLUSTER_COMPRESSED
:
1401 /* Compressed clusters don't have QCOW_OFLAG_COPIED */
1402 if (l2_entry
& QCOW_OFLAG_COPIED
) {
1403 fprintf(stderr
, "ERROR: cluster %" PRId64
": "
1404 "copied flag must never be set for compressed "
1405 "clusters\n", l2_entry
>> s
->cluster_bits
);
1406 l2_entry
&= ~QCOW_OFLAG_COPIED
;
1410 /* Mark cluster as used */
1411 nb_csectors
= ((l2_entry
>> s
->csize_shift
) &
1413 l2_entry
&= s
->cluster_offset_mask
;
1414 ret
= inc_refcounts(bs
, res
, refcount_table
, refcount_table_size
,
1415 l2_entry
& ~511, nb_csectors
* 512);
1420 if (flags
& CHECK_FRAG_INFO
) {
1421 res
->bfi
.allocated_clusters
++;
1422 res
->bfi
.compressed_clusters
++;
1424 /* Compressed clusters are fragmented by nature. Since they
1425 * take up sub-sector space but we only have sector granularity
1426 * I/O we need to re-read the same sectors even for adjacent
1427 * compressed clusters.
1429 res
->bfi
.fragmented_clusters
++;
1433 case QCOW2_CLUSTER_ZERO
:
1434 if ((l2_entry
& L2E_OFFSET_MASK
) == 0) {
1439 case QCOW2_CLUSTER_NORMAL
:
1441 uint64_t offset
= l2_entry
& L2E_OFFSET_MASK
;
1443 if (flags
& CHECK_FRAG_INFO
) {
1444 res
->bfi
.allocated_clusters
++;
1445 if (next_contiguous_offset
&&
1446 offset
!= next_contiguous_offset
) {
1447 res
->bfi
.fragmented_clusters
++;
1449 next_contiguous_offset
= offset
+ s
->cluster_size
;
1452 /* Mark cluster as used */
1453 ret
= inc_refcounts(bs
, res
, refcount_table
, refcount_table_size
,
1454 offset
, s
->cluster_size
);
1459 /* Correct offsets are cluster aligned */
1460 if (offset_into_cluster(s
, offset
)) {
1461 fprintf(stderr
, "ERROR offset=%" PRIx64
": Cluster is not "
1462 "properly aligned; L2 entry corrupted.\n", offset
);
1468 case QCOW2_CLUSTER_UNALLOCATED
:
1485 * Increases the refcount for the L1 table, its L2 tables and all referenced
1486 * clusters in the given refcount table. While doing so, performs some checks
1487 * on L1 and L2 entries.
1489 * Returns the number of errors found by the checks or -errno if an internal
1492 static int check_refcounts_l1(BlockDriverState
*bs
,
1493 BdrvCheckResult
*res
,
1494 void **refcount_table
,
1495 int64_t *refcount_table_size
,
1496 int64_t l1_table_offset
, int l1_size
,
1499 BDRVQcow2State
*s
= bs
->opaque
;
1500 uint64_t *l1_table
= NULL
, l2_offset
, l1_size2
;
1503 l1_size2
= l1_size
* sizeof(uint64_t);
1505 /* Mark L1 table as used */
1506 ret
= inc_refcounts(bs
, res
, refcount_table
, refcount_table_size
,
1507 l1_table_offset
, l1_size2
);
1512 /* Read L1 table entries from disk */
1514 l1_table
= g_try_malloc(l1_size2
);
1515 if (l1_table
== NULL
) {
1517 res
->check_errors
++;
1520 ret
= bdrv_pread(bs
->file
->bs
, l1_table_offset
, l1_table
, l1_size2
);
1522 fprintf(stderr
, "ERROR: I/O error in check_refcounts_l1\n");
1523 res
->check_errors
++;
1526 for(i
= 0;i
< l1_size
; i
++)
1527 be64_to_cpus(&l1_table
[i
]);
1530 /* Do the actual checks */
1531 for(i
= 0; i
< l1_size
; i
++) {
1532 l2_offset
= l1_table
[i
];
1534 /* Mark L2 table as used */
1535 l2_offset
&= L1E_OFFSET_MASK
;
1536 ret
= inc_refcounts(bs
, res
, refcount_table
, refcount_table_size
,
1537 l2_offset
, s
->cluster_size
);
1542 /* L2 tables are cluster aligned */
1543 if (offset_into_cluster(s
, l2_offset
)) {
1544 fprintf(stderr
, "ERROR l2_offset=%" PRIx64
": Table is not "
1545 "cluster aligned; L1 entry corrupted\n", l2_offset
);
1549 /* Process and check L2 entries */
1550 ret
= check_refcounts_l2(bs
, res
, refcount_table
,
1551 refcount_table_size
, l2_offset
, flags
);
1566 * Checks the OFLAG_COPIED flag for all L1 and L2 entries.
1568 * This function does not print an error message nor does it increment
1569 * check_errors if qcow2_get_refcount fails (this is because such an error will
1570 * have been already detected and sufficiently signaled by the calling function
1571 * (qcow2_check_refcounts) by the time this function is called).
1573 static int check_oflag_copied(BlockDriverState
*bs
, BdrvCheckResult
*res
,
1576 BDRVQcow2State
*s
= bs
->opaque
;
1577 uint64_t *l2_table
= qemu_blockalign(bs
, s
->cluster_size
);
1582 for (i
= 0; i
< s
->l1_size
; i
++) {
1583 uint64_t l1_entry
= s
->l1_table
[i
];
1584 uint64_t l2_offset
= l1_entry
& L1E_OFFSET_MASK
;
1585 bool l2_dirty
= false;
1591 ret
= qcow2_get_refcount(bs
, l2_offset
>> s
->cluster_bits
,
1594 /* don't print message nor increment check_errors */
1597 if ((refcount
== 1) != ((l1_entry
& QCOW_OFLAG_COPIED
) != 0)) {
1598 fprintf(stderr
, "%s OFLAG_COPIED L2 cluster: l1_index=%d "
1599 "l1_entry=%" PRIx64
" refcount=%" PRIu64
"\n",
1600 fix
& BDRV_FIX_ERRORS
? "Repairing" :
1602 i
, l1_entry
, refcount
);
1603 if (fix
& BDRV_FIX_ERRORS
) {
1604 s
->l1_table
[i
] = refcount
== 1
1605 ? l1_entry
| QCOW_OFLAG_COPIED
1606 : l1_entry
& ~QCOW_OFLAG_COPIED
;
1607 ret
= qcow2_write_l1_entry(bs
, i
);
1609 res
->check_errors
++;
1612 res
->corruptions_fixed
++;
1618 ret
= bdrv_pread(bs
->file
->bs
, l2_offset
, l2_table
,
1619 s
->l2_size
* sizeof(uint64_t));
1621 fprintf(stderr
, "ERROR: Could not read L2 table: %s\n",
1623 res
->check_errors
++;
1627 for (j
= 0; j
< s
->l2_size
; j
++) {
1628 uint64_t l2_entry
= be64_to_cpu(l2_table
[j
]);
1629 uint64_t data_offset
= l2_entry
& L2E_OFFSET_MASK
;
1630 int cluster_type
= qcow2_get_cluster_type(l2_entry
);
1632 if ((cluster_type
== QCOW2_CLUSTER_NORMAL
) ||
1633 ((cluster_type
== QCOW2_CLUSTER_ZERO
) && (data_offset
!= 0))) {
1634 ret
= qcow2_get_refcount(bs
,
1635 data_offset
>> s
->cluster_bits
,
1638 /* don't print message nor increment check_errors */
1641 if ((refcount
== 1) != ((l2_entry
& QCOW_OFLAG_COPIED
) != 0)) {
1642 fprintf(stderr
, "%s OFLAG_COPIED data cluster: "
1643 "l2_entry=%" PRIx64
" refcount=%" PRIu64
"\n",
1644 fix
& BDRV_FIX_ERRORS
? "Repairing" :
1646 l2_entry
, refcount
);
1647 if (fix
& BDRV_FIX_ERRORS
) {
1648 l2_table
[j
] = cpu_to_be64(refcount
== 1
1649 ? l2_entry
| QCOW_OFLAG_COPIED
1650 : l2_entry
& ~QCOW_OFLAG_COPIED
);
1652 res
->corruptions_fixed
++;
1661 ret
= qcow2_pre_write_overlap_check(bs
, QCOW2_OL_ACTIVE_L2
,
1662 l2_offset
, s
->cluster_size
);
1664 fprintf(stderr
, "ERROR: Could not write L2 table; metadata "
1665 "overlap check failed: %s\n", strerror(-ret
));
1666 res
->check_errors
++;
1670 ret
= bdrv_pwrite(bs
->file
->bs
, l2_offset
, l2_table
,
1673 fprintf(stderr
, "ERROR: Could not write L2 table: %s\n",
1675 res
->check_errors
++;
1684 qemu_vfree(l2_table
);
1689 * Checks consistency of refblocks and accounts for each refblock in
1692 static int check_refblocks(BlockDriverState
*bs
, BdrvCheckResult
*res
,
1693 BdrvCheckMode fix
, bool *rebuild
,
1694 void **refcount_table
, int64_t *nb_clusters
)
1696 BDRVQcow2State
*s
= bs
->opaque
;
1700 for(i
= 0; i
< s
->refcount_table_size
; i
++) {
1701 uint64_t offset
, cluster
;
1702 offset
= s
->refcount_table
[i
];
1703 cluster
= offset
>> s
->cluster_bits
;
1705 /* Refcount blocks are cluster aligned */
1706 if (offset_into_cluster(s
, offset
)) {
1707 fprintf(stderr
, "ERROR refcount block %" PRId64
" is not "
1708 "cluster aligned; refcount table entry corrupted\n", i
);
1714 if (cluster
>= *nb_clusters
) {
1715 fprintf(stderr
, "%s refcount block %" PRId64
" is outside image\n",
1716 fix
& BDRV_FIX_ERRORS
? "Repairing" : "ERROR", i
);
1718 if (fix
& BDRV_FIX_ERRORS
) {
1719 int64_t new_nb_clusters
;
1721 if (offset
> INT64_MAX
- s
->cluster_size
) {
1726 ret
= bdrv_truncate(bs
->file
->bs
, offset
+ s
->cluster_size
);
1730 size
= bdrv_getlength(bs
->file
->bs
);
1736 new_nb_clusters
= size_to_clusters(s
, size
);
1737 assert(new_nb_clusters
>= *nb_clusters
);
1739 ret
= realloc_refcount_array(s
, refcount_table
,
1740 nb_clusters
, new_nb_clusters
);
1742 res
->check_errors
++;
1746 if (cluster
>= *nb_clusters
) {
1751 res
->corruptions_fixed
++;
1752 ret
= inc_refcounts(bs
, res
, refcount_table
, nb_clusters
,
1753 offset
, s
->cluster_size
);
1757 /* No need to check whether the refcount is now greater than 1:
1758 * This area was just allocated and zeroed, so it can only be
1759 * exactly 1 after inc_refcounts() */
1765 fprintf(stderr
, "ERROR could not resize image: %s\n",
1774 ret
= inc_refcounts(bs
, res
, refcount_table
, nb_clusters
,
1775 offset
, s
->cluster_size
);
1779 if (s
->get_refcount(*refcount_table
, cluster
) != 1) {
1780 fprintf(stderr
, "ERROR refcount block %" PRId64
1781 " refcount=%" PRIu64
"\n", i
,
1782 s
->get_refcount(*refcount_table
, cluster
));
1793 * Calculates an in-memory refcount table.
1795 static int calculate_refcounts(BlockDriverState
*bs
, BdrvCheckResult
*res
,
1796 BdrvCheckMode fix
, bool *rebuild
,
1797 void **refcount_table
, int64_t *nb_clusters
)
1799 BDRVQcow2State
*s
= bs
->opaque
;
1804 if (!*refcount_table
) {
1805 int64_t old_size
= 0;
1806 ret
= realloc_refcount_array(s
, refcount_table
,
1807 &old_size
, *nb_clusters
);
1809 res
->check_errors
++;
1815 ret
= inc_refcounts(bs
, res
, refcount_table
, nb_clusters
,
1816 0, s
->cluster_size
);
1821 /* current L1 table */
1822 ret
= check_refcounts_l1(bs
, res
, refcount_table
, nb_clusters
,
1823 s
->l1_table_offset
, s
->l1_size
, CHECK_FRAG_INFO
);
1829 for (i
= 0; i
< s
->nb_snapshots
; i
++) {
1830 sn
= s
->snapshots
+ i
;
1831 ret
= check_refcounts_l1(bs
, res
, refcount_table
, nb_clusters
,
1832 sn
->l1_table_offset
, sn
->l1_size
, 0);
1837 ret
= inc_refcounts(bs
, res
, refcount_table
, nb_clusters
,
1838 s
->snapshots_offset
, s
->snapshots_size
);
1844 ret
= inc_refcounts(bs
, res
, refcount_table
, nb_clusters
,
1845 s
->refcount_table_offset
,
1846 s
->refcount_table_size
* sizeof(uint64_t));
1851 return check_refblocks(bs
, res
, fix
, rebuild
, refcount_table
, nb_clusters
);
1855 * Compares the actual reference count for each cluster in the image against the
1856 * refcount as reported by the refcount structures on-disk.
1858 static void compare_refcounts(BlockDriverState
*bs
, BdrvCheckResult
*res
,
1859 BdrvCheckMode fix
, bool *rebuild
,
1860 int64_t *highest_cluster
,
1861 void *refcount_table
, int64_t nb_clusters
)
1863 BDRVQcow2State
*s
= bs
->opaque
;
1865 uint64_t refcount1
, refcount2
;
1868 for (i
= 0, *highest_cluster
= 0; i
< nb_clusters
; i
++) {
1869 ret
= qcow2_get_refcount(bs
, i
, &refcount1
);
1871 fprintf(stderr
, "Can't get refcount for cluster %" PRId64
": %s\n",
1873 res
->check_errors
++;
1877 refcount2
= s
->get_refcount(refcount_table
, i
);
1879 if (refcount1
> 0 || refcount2
> 0) {
1880 *highest_cluster
= i
;
1883 if (refcount1
!= refcount2
) {
1884 /* Check if we're allowed to fix the mismatch */
1885 int *num_fixed
= NULL
;
1886 if (refcount1
== 0) {
1888 } else if (refcount1
> refcount2
&& (fix
& BDRV_FIX_LEAKS
)) {
1889 num_fixed
= &res
->leaks_fixed
;
1890 } else if (refcount1
< refcount2
&& (fix
& BDRV_FIX_ERRORS
)) {
1891 num_fixed
= &res
->corruptions_fixed
;
1894 fprintf(stderr
, "%s cluster %" PRId64
" refcount=%" PRIu64
1895 " reference=%" PRIu64
"\n",
1896 num_fixed
!= NULL
? "Repairing" :
1897 refcount1
< refcount2
? "ERROR" :
1899 i
, refcount1
, refcount2
);
1902 ret
= update_refcount(bs
, i
<< s
->cluster_bits
, 1,
1903 refcount_diff(refcount1
, refcount2
),
1904 refcount1
> refcount2
,
1905 QCOW2_DISCARD_ALWAYS
);
1912 /* And if we couldn't, print an error */
1913 if (refcount1
< refcount2
) {
1923 * Allocates clusters using an in-memory refcount table (IMRT) in contrast to
1924 * the on-disk refcount structures.
1926 * On input, *first_free_cluster tells where to start looking, and need not
1927 * actually be a free cluster; the returned offset will not be before that
1928 * cluster. On output, *first_free_cluster points to the first gap found, even
1929 * if that gap was too small to be used as the returned offset.
1931 * Note that *first_free_cluster is a cluster index whereas the return value is
1934 static int64_t alloc_clusters_imrt(BlockDriverState
*bs
,
1936 void **refcount_table
,
1937 int64_t *imrt_nb_clusters
,
1938 int64_t *first_free_cluster
)
1940 BDRVQcow2State
*s
= bs
->opaque
;
1941 int64_t cluster
= *first_free_cluster
, i
;
1942 bool first_gap
= true;
1943 int contiguous_free_clusters
;
1946 /* Starting at *first_free_cluster, find a range of at least cluster_count
1947 * continuously free clusters */
1948 for (contiguous_free_clusters
= 0;
1949 cluster
< *imrt_nb_clusters
&&
1950 contiguous_free_clusters
< cluster_count
;
1953 if (!s
->get_refcount(*refcount_table
, cluster
)) {
1954 contiguous_free_clusters
++;
1956 /* If this is the first free cluster found, update
1957 * *first_free_cluster accordingly */
1958 *first_free_cluster
= cluster
;
1961 } else if (contiguous_free_clusters
) {
1962 contiguous_free_clusters
= 0;
1966 /* If contiguous_free_clusters is greater than zero, it contains the number
1967 * of continuously free clusters until the current cluster; the first free
1968 * cluster in the current "gap" is therefore
1969 * cluster - contiguous_free_clusters */
1971 /* If no such range could be found, grow the in-memory refcount table
1972 * accordingly to append free clusters at the end of the image */
1973 if (contiguous_free_clusters
< cluster_count
) {
1974 /* contiguous_free_clusters clusters are already empty at the image end;
1975 * we need cluster_count clusters; therefore, we have to allocate
1976 * cluster_count - contiguous_free_clusters new clusters at the end of
1977 * the image (which is the current value of cluster; note that cluster
1978 * may exceed old_imrt_nb_clusters if *first_free_cluster pointed beyond
1980 ret
= realloc_refcount_array(s
, refcount_table
, imrt_nb_clusters
,
1981 cluster
+ cluster_count
1982 - contiguous_free_clusters
);
1988 /* Go back to the first free cluster */
1989 cluster
-= contiguous_free_clusters
;
1990 for (i
= 0; i
< cluster_count
; i
++) {
1991 s
->set_refcount(*refcount_table
, cluster
+ i
, 1);
1994 return cluster
<< s
->cluster_bits
;
1998 * Creates a new refcount structure based solely on the in-memory information
1999 * given through *refcount_table. All necessary allocations will be reflected
2002 * On success, the old refcount structure is leaked (it will be covered by the
2003 * new refcount structure).
2005 static int rebuild_refcount_structure(BlockDriverState
*bs
,
2006 BdrvCheckResult
*res
,
2007 void **refcount_table
,
2008 int64_t *nb_clusters
)
2010 BDRVQcow2State
*s
= bs
->opaque
;
2011 int64_t first_free_cluster
= 0, reftable_offset
= -1, cluster
= 0;
2012 int64_t refblock_offset
, refblock_start
, refblock_index
;
2013 uint32_t reftable_size
= 0;
2014 uint64_t *on_disk_reftable
= NULL
;
2015 void *on_disk_refblock
;
2018 uint64_t reftable_offset
;
2019 uint32_t reftable_clusters
;
2020 } QEMU_PACKED reftable_offset_and_clusters
;
2022 qcow2_cache_empty(bs
, s
->refcount_block_cache
);
2025 for (; cluster
< *nb_clusters
; cluster
++) {
2026 if (!s
->get_refcount(*refcount_table
, cluster
)) {
2030 refblock_index
= cluster
>> s
->refcount_block_bits
;
2031 refblock_start
= refblock_index
<< s
->refcount_block_bits
;
2033 /* Don't allocate a cluster in a refblock already written to disk */
2034 if (first_free_cluster
< refblock_start
) {
2035 first_free_cluster
= refblock_start
;
2037 refblock_offset
= alloc_clusters_imrt(bs
, 1, refcount_table
,
2038 nb_clusters
, &first_free_cluster
);
2039 if (refblock_offset
< 0) {
2040 fprintf(stderr
, "ERROR allocating refblock: %s\n",
2041 strerror(-refblock_offset
));
2042 res
->check_errors
++;
2043 ret
= refblock_offset
;
2047 if (reftable_size
<= refblock_index
) {
2048 uint32_t old_reftable_size
= reftable_size
;
2049 uint64_t *new_on_disk_reftable
;
2051 reftable_size
= ROUND_UP((refblock_index
+ 1) * sizeof(uint64_t),
2052 s
->cluster_size
) / sizeof(uint64_t);
2053 new_on_disk_reftable
= g_try_realloc(on_disk_reftable
,
2056 if (!new_on_disk_reftable
) {
2057 res
->check_errors
++;
2061 on_disk_reftable
= new_on_disk_reftable
;
2063 memset(on_disk_reftable
+ old_reftable_size
, 0,
2064 (reftable_size
- old_reftable_size
) * sizeof(uint64_t));
2066 /* The offset we have for the reftable is now no longer valid;
2067 * this will leak that range, but we can easily fix that by running
2068 * a leak-fixing check after this rebuild operation */
2069 reftable_offset
= -1;
2071 on_disk_reftable
[refblock_index
] = refblock_offset
;
2073 /* If this is apparently the last refblock (for now), try to squeeze the
2075 if (refblock_index
== (*nb_clusters
- 1) >> s
->refcount_block_bits
&&
2076 reftable_offset
< 0)
2078 uint64_t reftable_clusters
= size_to_clusters(s
, reftable_size
*
2080 reftable_offset
= alloc_clusters_imrt(bs
, reftable_clusters
,
2081 refcount_table
, nb_clusters
,
2082 &first_free_cluster
);
2083 if (reftable_offset
< 0) {
2084 fprintf(stderr
, "ERROR allocating reftable: %s\n",
2085 strerror(-reftable_offset
));
2086 res
->check_errors
++;
2087 ret
= reftable_offset
;
2092 ret
= qcow2_pre_write_overlap_check(bs
, 0, refblock_offset
,
2095 fprintf(stderr
, "ERROR writing refblock: %s\n", strerror(-ret
));
2099 /* The size of *refcount_table is always cluster-aligned, therefore the
2100 * write operation will not overflow */
2101 on_disk_refblock
= (void *)((char *) *refcount_table
+
2102 refblock_index
* s
->cluster_size
);
2104 ret
= bdrv_write(bs
->file
->bs
, refblock_offset
/ BDRV_SECTOR_SIZE
,
2105 on_disk_refblock
, s
->cluster_sectors
);
2107 fprintf(stderr
, "ERROR writing refblock: %s\n", strerror(-ret
));
2111 /* Go to the end of this refblock */
2112 cluster
= refblock_start
+ s
->refcount_block_size
- 1;
2115 if (reftable_offset
< 0) {
2116 uint64_t post_refblock_start
, reftable_clusters
;
2118 post_refblock_start
= ROUND_UP(*nb_clusters
, s
->refcount_block_size
);
2119 reftable_clusters
= size_to_clusters(s
,
2120 reftable_size
* sizeof(uint64_t));
2121 /* Not pretty but simple */
2122 if (first_free_cluster
< post_refblock_start
) {
2123 first_free_cluster
= post_refblock_start
;
2125 reftable_offset
= alloc_clusters_imrt(bs
, reftable_clusters
,
2126 refcount_table
, nb_clusters
,
2127 &first_free_cluster
);
2128 if (reftable_offset
< 0) {
2129 fprintf(stderr
, "ERROR allocating reftable: %s\n",
2130 strerror(-reftable_offset
));
2131 res
->check_errors
++;
2132 ret
= reftable_offset
;
2136 goto write_refblocks
;
2139 assert(on_disk_reftable
);
2141 for (refblock_index
= 0; refblock_index
< reftable_size
; refblock_index
++) {
2142 cpu_to_be64s(&on_disk_reftable
[refblock_index
]);
2145 ret
= qcow2_pre_write_overlap_check(bs
, 0, reftable_offset
,
2146 reftable_size
* sizeof(uint64_t));
2148 fprintf(stderr
, "ERROR writing reftable: %s\n", strerror(-ret
));
2152 assert(reftable_size
< INT_MAX
/ sizeof(uint64_t));
2153 ret
= bdrv_pwrite(bs
->file
->bs
, reftable_offset
, on_disk_reftable
,
2154 reftable_size
* sizeof(uint64_t));
2156 fprintf(stderr
, "ERROR writing reftable: %s\n", strerror(-ret
));
2160 /* Enter new reftable into the image header */
2161 cpu_to_be64w(&reftable_offset_and_clusters
.reftable_offset
,
2163 cpu_to_be32w(&reftable_offset_and_clusters
.reftable_clusters
,
2164 size_to_clusters(s
, reftable_size
* sizeof(uint64_t)));
2165 ret
= bdrv_pwrite_sync(bs
->file
->bs
, offsetof(QCowHeader
,
2166 refcount_table_offset
),
2167 &reftable_offset_and_clusters
,
2168 sizeof(reftable_offset_and_clusters
));
2170 fprintf(stderr
, "ERROR setting reftable: %s\n", strerror(-ret
));
2174 for (refblock_index
= 0; refblock_index
< reftable_size
; refblock_index
++) {
2175 be64_to_cpus(&on_disk_reftable
[refblock_index
]);
2177 s
->refcount_table
= on_disk_reftable
;
2178 s
->refcount_table_offset
= reftable_offset
;
2179 s
->refcount_table_size
= reftable_size
;
2184 g_free(on_disk_reftable
);
2189 * Checks an image for refcount consistency.
2191 * Returns 0 if no errors are found, the number of errors in case the image is
2192 * detected as corrupted, and -errno when an internal error occurred.
2194 int qcow2_check_refcounts(BlockDriverState
*bs
, BdrvCheckResult
*res
,
2197 BDRVQcow2State
*s
= bs
->opaque
;
2198 BdrvCheckResult pre_compare_res
;
2199 int64_t size
, highest_cluster
, nb_clusters
;
2200 void *refcount_table
= NULL
;
2201 bool rebuild
= false;
2204 size
= bdrv_getlength(bs
->file
->bs
);
2206 res
->check_errors
++;
2210 nb_clusters
= size_to_clusters(s
, size
);
2211 if (nb_clusters
> INT_MAX
) {
2212 res
->check_errors
++;
2216 res
->bfi
.total_clusters
=
2217 size_to_clusters(s
, bs
->total_sectors
* BDRV_SECTOR_SIZE
);
2219 ret
= calculate_refcounts(bs
, res
, fix
, &rebuild
, &refcount_table
,
2225 /* In case we don't need to rebuild the refcount structure (but want to fix
2226 * something), this function is immediately called again, in which case the
2227 * result should be ignored */
2228 pre_compare_res
= *res
;
2229 compare_refcounts(bs
, res
, 0, &rebuild
, &highest_cluster
, refcount_table
,
2232 if (rebuild
&& (fix
& BDRV_FIX_ERRORS
)) {
2233 BdrvCheckResult old_res
= *res
;
2234 int fresh_leaks
= 0;
2236 fprintf(stderr
, "Rebuilding refcount structure\n");
2237 ret
= rebuild_refcount_structure(bs
, res
, &refcount_table
,
2243 res
->corruptions
= 0;
2246 /* Because the old reftable has been exchanged for a new one the
2247 * references have to be recalculated */
2249 memset(refcount_table
, 0, refcount_array_byte_size(s
, nb_clusters
));
2250 ret
= calculate_refcounts(bs
, res
, 0, &rebuild
, &refcount_table
,
2256 if (fix
& BDRV_FIX_LEAKS
) {
2257 /* The old refcount structures are now leaked, fix it; the result
2258 * can be ignored, aside from leaks which were introduced by
2259 * rebuild_refcount_structure() that could not be fixed */
2260 BdrvCheckResult saved_res
= *res
;
2261 *res
= (BdrvCheckResult
){ 0 };
2263 compare_refcounts(bs
, res
, BDRV_FIX_LEAKS
, &rebuild
,
2264 &highest_cluster
, refcount_table
, nb_clusters
);
2266 fprintf(stderr
, "ERROR rebuilt refcount structure is still "
2270 /* Any leaks accounted for here were introduced by
2271 * rebuild_refcount_structure() because that function has created a
2272 * new refcount structure from scratch */
2273 fresh_leaks
= res
->leaks
;
2277 if (res
->corruptions
< old_res
.corruptions
) {
2278 res
->corruptions_fixed
+= old_res
.corruptions
- res
->corruptions
;
2280 if (res
->leaks
< old_res
.leaks
) {
2281 res
->leaks_fixed
+= old_res
.leaks
- res
->leaks
;
2283 res
->leaks
+= fresh_leaks
;
2286 fprintf(stderr
, "ERROR need to rebuild refcount structures\n");
2287 res
->check_errors
++;
2292 if (res
->leaks
|| res
->corruptions
) {
2293 *res
= pre_compare_res
;
2294 compare_refcounts(bs
, res
, fix
, &rebuild
, &highest_cluster
,
2295 refcount_table
, nb_clusters
);
2299 /* check OFLAG_COPIED */
2300 ret
= check_oflag_copied(bs
, res
, fix
);
2305 res
->image_end_offset
= (highest_cluster
+ 1) * s
->cluster_size
;
2309 g_free(refcount_table
);
2314 #define overlaps_with(ofs, sz) \
2315 ranges_overlap(offset, size, ofs, sz)
2318 * Checks if the given offset into the image file is actually free to use by
2319 * looking for overlaps with important metadata sections (L1/L2 tables etc.),
2320 * i.e. a sanity check without relying on the refcount tables.
2322 * The ign parameter specifies what checks not to perform (being a bitmask of
2323 * QCow2MetadataOverlap values), i.e., what sections to ignore.
2326 * - 0 if writing to this offset will not affect the mentioned metadata
2327 * - a positive QCow2MetadataOverlap value indicating one overlapping section
2328 * - a negative value (-errno) indicating an error while performing a check,
2329 * e.g. when bdrv_read failed on QCOW2_OL_INACTIVE_L2
2331 int qcow2_check_metadata_overlap(BlockDriverState
*bs
, int ign
, int64_t offset
,
2334 BDRVQcow2State
*s
= bs
->opaque
;
2335 int chk
= s
->overlap_check
& ~ign
;
2342 if (chk
& QCOW2_OL_MAIN_HEADER
) {
2343 if (offset
< s
->cluster_size
) {
2344 return QCOW2_OL_MAIN_HEADER
;
2348 /* align range to test to cluster boundaries */
2349 size
= align_offset(offset_into_cluster(s
, offset
) + size
, s
->cluster_size
);
2350 offset
= start_of_cluster(s
, offset
);
2352 if ((chk
& QCOW2_OL_ACTIVE_L1
) && s
->l1_size
) {
2353 if (overlaps_with(s
->l1_table_offset
, s
->l1_size
* sizeof(uint64_t))) {
2354 return QCOW2_OL_ACTIVE_L1
;
2358 if ((chk
& QCOW2_OL_REFCOUNT_TABLE
) && s
->refcount_table_size
) {
2359 if (overlaps_with(s
->refcount_table_offset
,
2360 s
->refcount_table_size
* sizeof(uint64_t))) {
2361 return QCOW2_OL_REFCOUNT_TABLE
;
2365 if ((chk
& QCOW2_OL_SNAPSHOT_TABLE
) && s
->snapshots_size
) {
2366 if (overlaps_with(s
->snapshots_offset
, s
->snapshots_size
)) {
2367 return QCOW2_OL_SNAPSHOT_TABLE
;
2371 if ((chk
& QCOW2_OL_INACTIVE_L1
) && s
->snapshots
) {
2372 for (i
= 0; i
< s
->nb_snapshots
; i
++) {
2373 if (s
->snapshots
[i
].l1_size
&&
2374 overlaps_with(s
->snapshots
[i
].l1_table_offset
,
2375 s
->snapshots
[i
].l1_size
* sizeof(uint64_t))) {
2376 return QCOW2_OL_INACTIVE_L1
;
2381 if ((chk
& QCOW2_OL_ACTIVE_L2
) && s
->l1_table
) {
2382 for (i
= 0; i
< s
->l1_size
; i
++) {
2383 if ((s
->l1_table
[i
] & L1E_OFFSET_MASK
) &&
2384 overlaps_with(s
->l1_table
[i
] & L1E_OFFSET_MASK
,
2386 return QCOW2_OL_ACTIVE_L2
;
2391 if ((chk
& QCOW2_OL_REFCOUNT_BLOCK
) && s
->refcount_table
) {
2392 for (i
= 0; i
< s
->refcount_table_size
; i
++) {
2393 if ((s
->refcount_table
[i
] & REFT_OFFSET_MASK
) &&
2394 overlaps_with(s
->refcount_table
[i
] & REFT_OFFSET_MASK
,
2396 return QCOW2_OL_REFCOUNT_BLOCK
;
2401 if ((chk
& QCOW2_OL_INACTIVE_L2
) && s
->snapshots
) {
2402 for (i
= 0; i
< s
->nb_snapshots
; i
++) {
2403 uint64_t l1_ofs
= s
->snapshots
[i
].l1_table_offset
;
2404 uint32_t l1_sz
= s
->snapshots
[i
].l1_size
;
2405 uint64_t l1_sz2
= l1_sz
* sizeof(uint64_t);
2406 uint64_t *l1
= g_try_malloc(l1_sz2
);
2409 if (l1_sz2
&& l1
== NULL
) {
2413 ret
= bdrv_pread(bs
->file
->bs
, l1_ofs
, l1
, l1_sz2
);
2419 for (j
= 0; j
< l1_sz
; j
++) {
2420 uint64_t l2_ofs
= be64_to_cpu(l1
[j
]) & L1E_OFFSET_MASK
;
2421 if (l2_ofs
&& overlaps_with(l2_ofs
, s
->cluster_size
)) {
2423 return QCOW2_OL_INACTIVE_L2
;
2434 static const char *metadata_ol_names
[] = {
2435 [QCOW2_OL_MAIN_HEADER_BITNR
] = "qcow2_header",
2436 [QCOW2_OL_ACTIVE_L1_BITNR
] = "active L1 table",
2437 [QCOW2_OL_ACTIVE_L2_BITNR
] = "active L2 table",
2438 [QCOW2_OL_REFCOUNT_TABLE_BITNR
] = "refcount table",
2439 [QCOW2_OL_REFCOUNT_BLOCK_BITNR
] = "refcount block",
2440 [QCOW2_OL_SNAPSHOT_TABLE_BITNR
] = "snapshot table",
2441 [QCOW2_OL_INACTIVE_L1_BITNR
] = "inactive L1 table",
2442 [QCOW2_OL_INACTIVE_L2_BITNR
] = "inactive L2 table",
2446 * First performs a check for metadata overlaps (through
2447 * qcow2_check_metadata_overlap); if that fails with a negative value (error
2448 * while performing a check), that value is returned. If an impending overlap
2449 * is detected, the BDS will be made unusable, the qcow2 file marked corrupt
2450 * and -EIO returned.
2452 * Returns 0 if there were neither overlaps nor errors while checking for
2453 * overlaps; or a negative value (-errno) on error.
2455 int qcow2_pre_write_overlap_check(BlockDriverState
*bs
, int ign
, int64_t offset
,
2458 int ret
= qcow2_check_metadata_overlap(bs
, ign
, offset
, size
);
2462 } else if (ret
> 0) {
2463 int metadata_ol_bitnr
= ctz32(ret
);
2464 assert(metadata_ol_bitnr
< QCOW2_OL_MAX_BITNR
);
2466 qcow2_signal_corruption(bs
, true, offset
, size
, "Preventing invalid "
2467 "write on metadata (overlaps with %s)",
2468 metadata_ol_names
[metadata_ol_bitnr
]);
2475 /* A pointer to a function of this type is given to walk_over_reftable(). That
2476 * function will create refblocks and pass them to a RefblockFinishOp once they
2477 * are completed (@refblock). @refblock_empty is set if the refblock is
2480 * Along with the refblock, a corresponding reftable entry is passed, in the
2481 * reftable @reftable (which may be reallocated) at @reftable_index.
2483 * @allocated should be set to true if a new cluster has been allocated.
2485 typedef int (RefblockFinishOp
)(BlockDriverState
*bs
, uint64_t **reftable
,
2486 uint64_t reftable_index
, uint64_t *reftable_size
,
2487 void *refblock
, bool refblock_empty
,
2488 bool *allocated
, Error
**errp
);
2491 * This "operation" for walk_over_reftable() allocates the refblock on disk (if
2492 * it is not empty) and inserts its offset into the new reftable. The size of
2493 * this new reftable is increased as required.
2495 static int alloc_refblock(BlockDriverState
*bs
, uint64_t **reftable
,
2496 uint64_t reftable_index
, uint64_t *reftable_size
,
2497 void *refblock
, bool refblock_empty
, bool *allocated
,
2500 BDRVQcow2State
*s
= bs
->opaque
;
2503 if (!refblock_empty
&& reftable_index
>= *reftable_size
) {
2504 uint64_t *new_reftable
;
2505 uint64_t new_reftable_size
;
2507 new_reftable_size
= ROUND_UP(reftable_index
+ 1,
2508 s
->cluster_size
/ sizeof(uint64_t));
2509 if (new_reftable_size
> QCOW_MAX_REFTABLE_SIZE
/ sizeof(uint64_t)) {
2511 "This operation would make the refcount table grow "
2512 "beyond the maximum size supported by QEMU, aborting");
2516 new_reftable
= g_try_realloc(*reftable
, new_reftable_size
*
2518 if (!new_reftable
) {
2519 error_setg(errp
, "Failed to increase reftable buffer size");
2523 memset(new_reftable
+ *reftable_size
, 0,
2524 (new_reftable_size
- *reftable_size
) * sizeof(uint64_t));
2526 *reftable
= new_reftable
;
2527 *reftable_size
= new_reftable_size
;
2530 if (!refblock_empty
&& !(*reftable
)[reftable_index
]) {
2531 offset
= qcow2_alloc_clusters(bs
, s
->cluster_size
);
2533 error_setg_errno(errp
, -offset
, "Failed to allocate refblock");
2536 (*reftable
)[reftable_index
] = offset
;
2544 * This "operation" for walk_over_reftable() writes the refblock to disk at the
2545 * offset specified by the new reftable's entry. It does not modify the new
2546 * reftable or change any refcounts.
2548 static int flush_refblock(BlockDriverState
*bs
, uint64_t **reftable
,
2549 uint64_t reftable_index
, uint64_t *reftable_size
,
2550 void *refblock
, bool refblock_empty
, bool *allocated
,
2553 BDRVQcow2State
*s
= bs
->opaque
;
2557 if (reftable_index
< *reftable_size
&& (*reftable
)[reftable_index
]) {
2558 offset
= (*reftable
)[reftable_index
];
2560 ret
= qcow2_pre_write_overlap_check(bs
, 0, offset
, s
->cluster_size
);
2562 error_setg_errno(errp
, -ret
, "Overlap check failed");
2566 ret
= bdrv_pwrite(bs
->file
->bs
, offset
, refblock
, s
->cluster_size
);
2568 error_setg_errno(errp
, -ret
, "Failed to write refblock");
2572 assert(refblock_empty
);
2579 * This function walks over the existing reftable and every referenced refblock;
2580 * if @new_set_refcount is non-NULL, it is called for every refcount entry to
2581 * create an equal new entry in the passed @new_refblock. Once that
2582 * @new_refblock is completely filled, @operation will be called.
2584 * @status_cb and @cb_opaque are used for the amend operation's status callback.
2585 * @index is the index of the walk_over_reftable() calls and @total is the total
2586 * number of walk_over_reftable() calls per amend operation. Both are used for
2587 * calculating the parameters for the status callback.
2589 * @allocated is set to true if a new cluster has been allocated.
2591 static int walk_over_reftable(BlockDriverState
*bs
, uint64_t **new_reftable
,
2592 uint64_t *new_reftable_index
,
2593 uint64_t *new_reftable_size
,
2594 void *new_refblock
, int new_refblock_size
,
2595 int new_refcount_bits
,
2596 RefblockFinishOp
*operation
, bool *allocated
,
2597 Qcow2SetRefcountFunc
*new_set_refcount
,
2598 BlockDriverAmendStatusCB
*status_cb
,
2599 void *cb_opaque
, int index
, int total
,
2602 BDRVQcow2State
*s
= bs
->opaque
;
2603 uint64_t reftable_index
;
2604 bool new_refblock_empty
= true;
2606 int new_refblock_index
= 0;
2609 for (reftable_index
= 0; reftable_index
< s
->refcount_table_size
;
2612 uint64_t refblock_offset
= s
->refcount_table
[reftable_index
]
2615 status_cb(bs
, (uint64_t)index
* s
->refcount_table_size
+ reftable_index
,
2616 (uint64_t)total
* s
->refcount_table_size
, cb_opaque
);
2618 if (refblock_offset
) {
2621 if (offset_into_cluster(s
, refblock_offset
)) {
2622 qcow2_signal_corruption(bs
, true, -1, -1, "Refblock offset %#"
2623 PRIx64
" unaligned (reftable index: %#"
2624 PRIx64
")", refblock_offset
,
2627 "Image is corrupt (unaligned refblock offset)");
2631 ret
= qcow2_cache_get(bs
, s
->refcount_block_cache
, refblock_offset
,
2634 error_setg_errno(errp
, -ret
, "Failed to retrieve refblock");
2638 for (refblock_index
= 0; refblock_index
< s
->refcount_block_size
;
2643 if (new_refblock_index
>= new_refblock_size
) {
2644 /* new_refblock is now complete */
2645 ret
= operation(bs
, new_reftable
, *new_reftable_index
,
2646 new_reftable_size
, new_refblock
,
2647 new_refblock_empty
, allocated
, errp
);
2649 qcow2_cache_put(bs
, s
->refcount_block_cache
, &refblock
);
2653 (*new_reftable_index
)++;
2654 new_refblock_index
= 0;
2655 new_refblock_empty
= true;
2658 refcount
= s
->get_refcount(refblock
, refblock_index
);
2659 if (new_refcount_bits
< 64 && refcount
>> new_refcount_bits
) {
2662 qcow2_cache_put(bs
, s
->refcount_block_cache
, &refblock
);
2664 offset
= ((reftable_index
<< s
->refcount_block_bits
)
2665 + refblock_index
) << s
->cluster_bits
;
2667 error_setg(errp
, "Cannot decrease refcount entry width to "
2668 "%i bits: Cluster at offset %#" PRIx64
" has a "
2669 "refcount of %" PRIu64
, new_refcount_bits
,
2674 if (new_set_refcount
) {
2675 new_set_refcount(new_refblock
, new_refblock_index
++,
2678 new_refblock_index
++;
2680 new_refblock_empty
= new_refblock_empty
&& refcount
== 0;
2683 qcow2_cache_put(bs
, s
->refcount_block_cache
, &refblock
);
2685 /* No refblock means every refcount is 0 */
2686 for (refblock_index
= 0; refblock_index
< s
->refcount_block_size
;
2689 if (new_refblock_index
>= new_refblock_size
) {
2690 /* new_refblock is now complete */
2691 ret
= operation(bs
, new_reftable
, *new_reftable_index
,
2692 new_reftable_size
, new_refblock
,
2693 new_refblock_empty
, allocated
, errp
);
2698 (*new_reftable_index
)++;
2699 new_refblock_index
= 0;
2700 new_refblock_empty
= true;
2703 if (new_set_refcount
) {
2704 new_set_refcount(new_refblock
, new_refblock_index
++, 0);
2706 new_refblock_index
++;
2712 if (new_refblock_index
> 0) {
2713 /* Complete the potentially existing partially filled final refblock */
2714 if (new_set_refcount
) {
2715 for (; new_refblock_index
< new_refblock_size
;
2716 new_refblock_index
++)
2718 new_set_refcount(new_refblock
, new_refblock_index
, 0);
2722 ret
= operation(bs
, new_reftable
, *new_reftable_index
,
2723 new_reftable_size
, new_refblock
, new_refblock_empty
,
2729 (*new_reftable_index
)++;
2732 status_cb(bs
, (uint64_t)(index
+ 1) * s
->refcount_table_size
,
2733 (uint64_t)total
* s
->refcount_table_size
, cb_opaque
);
2738 int qcow2_change_refcount_order(BlockDriverState
*bs
, int refcount_order
,
2739 BlockDriverAmendStatusCB
*status_cb
,
2740 void *cb_opaque
, Error
**errp
)
2742 BDRVQcow2State
*s
= bs
->opaque
;
2743 Qcow2GetRefcountFunc
*new_get_refcount
;
2744 Qcow2SetRefcountFunc
*new_set_refcount
;
2745 void *new_refblock
= qemu_blockalign(bs
->file
->bs
, s
->cluster_size
);
2746 uint64_t *new_reftable
= NULL
, new_reftable_size
= 0;
2747 uint64_t *old_reftable
, old_reftable_size
, old_reftable_offset
;
2748 uint64_t new_reftable_index
= 0;
2750 int64_t new_reftable_offset
= 0, allocated_reftable_size
= 0;
2751 int new_refblock_size
, new_refcount_bits
= 1 << refcount_order
;
2752 int old_refcount_order
;
2755 bool new_allocation
;
2757 assert(s
->qcow_version
>= 3);
2758 assert(refcount_order
>= 0 && refcount_order
<= 6);
2760 /* see qcow2_open() */
2761 new_refblock_size
= 1 << (s
->cluster_bits
- (refcount_order
- 3));
2763 new_get_refcount
= get_refcount_funcs
[refcount_order
];
2764 new_set_refcount
= set_refcount_funcs
[refcount_order
];
2770 new_allocation
= false;
2772 /* At least we have to do this walk and the one which writes the
2773 * refblocks; also, at least we have to do this loop here at least
2774 * twice (normally), first to do the allocations, and second to
2775 * determine that everything is correctly allocated, this then makes
2776 * three walks in total */
2777 total_walks
= MAX(walk_index
+ 2, 3);
2779 /* First, allocate the structures so they are present in the refcount
2781 ret
= walk_over_reftable(bs
, &new_reftable
, &new_reftable_index
,
2782 &new_reftable_size
, NULL
, new_refblock_size
,
2783 new_refcount_bits
, &alloc_refblock
,
2784 &new_allocation
, NULL
, status_cb
, cb_opaque
,
2785 walk_index
++, total_walks
, errp
);
2790 new_reftable_index
= 0;
2792 if (new_allocation
) {
2793 if (new_reftable_offset
) {
2794 qcow2_free_clusters(bs
, new_reftable_offset
,
2795 allocated_reftable_size
* sizeof(uint64_t),
2796 QCOW2_DISCARD_NEVER
);
2799 new_reftable_offset
= qcow2_alloc_clusters(bs
, new_reftable_size
*
2801 if (new_reftable_offset
< 0) {
2802 error_setg_errno(errp
, -new_reftable_offset
,
2803 "Failed to allocate the new reftable");
2804 ret
= new_reftable_offset
;
2807 allocated_reftable_size
= new_reftable_size
;
2809 } while (new_allocation
);
2811 /* Second, write the new refblocks */
2812 ret
= walk_over_reftable(bs
, &new_reftable
, &new_reftable_index
,
2813 &new_reftable_size
, new_refblock
,
2814 new_refblock_size
, new_refcount_bits
,
2815 &flush_refblock
, &new_allocation
, new_set_refcount
,
2816 status_cb
, cb_opaque
, walk_index
, walk_index
+ 1,
2821 assert(!new_allocation
);
2824 /* Write the new reftable */
2825 ret
= qcow2_pre_write_overlap_check(bs
, 0, new_reftable_offset
,
2826 new_reftable_size
* sizeof(uint64_t));
2828 error_setg_errno(errp
, -ret
, "Overlap check failed");
2832 for (i
= 0; i
< new_reftable_size
; i
++) {
2833 cpu_to_be64s(&new_reftable
[i
]);
2836 ret
= bdrv_pwrite(bs
->file
->bs
, new_reftable_offset
, new_reftable
,
2837 new_reftable_size
* sizeof(uint64_t));
2839 for (i
= 0; i
< new_reftable_size
; i
++) {
2840 be64_to_cpus(&new_reftable
[i
]);
2844 error_setg_errno(errp
, -ret
, "Failed to write the new reftable");
2849 /* Empty the refcount cache */
2850 ret
= qcow2_cache_flush(bs
, s
->refcount_block_cache
);
2852 error_setg_errno(errp
, -ret
, "Failed to flush the refblock cache");
2856 /* Update the image header to point to the new reftable; this only updates
2857 * the fields which are relevant to qcow2_update_header(); other fields
2858 * such as s->refcount_table or s->refcount_bits stay stale for now
2859 * (because we have to restore everything if qcow2_update_header() fails) */
2860 old_refcount_order
= s
->refcount_order
;
2861 old_reftable_size
= s
->refcount_table_size
;
2862 old_reftable_offset
= s
->refcount_table_offset
;
2864 s
->refcount_order
= refcount_order
;
2865 s
->refcount_table_size
= new_reftable_size
;
2866 s
->refcount_table_offset
= new_reftable_offset
;
2868 ret
= qcow2_update_header(bs
);
2870 s
->refcount_order
= old_refcount_order
;
2871 s
->refcount_table_size
= old_reftable_size
;
2872 s
->refcount_table_offset
= old_reftable_offset
;
2873 error_setg_errno(errp
, -ret
, "Failed to update the qcow2 header");
2877 /* Now update the rest of the in-memory information */
2878 old_reftable
= s
->refcount_table
;
2879 s
->refcount_table
= new_reftable
;
2881 s
->refcount_bits
= 1 << refcount_order
;
2882 s
->refcount_max
= UINT64_C(1) << (s
->refcount_bits
- 1);
2883 s
->refcount_max
+= s
->refcount_max
- 1;
2885 s
->refcount_block_bits
= s
->cluster_bits
- (refcount_order
- 3);
2886 s
->refcount_block_size
= 1 << s
->refcount_block_bits
;
2888 s
->get_refcount
= new_get_refcount
;
2889 s
->set_refcount
= new_set_refcount
;
2891 /* For cleaning up all old refblocks and the old reftable below the "done"
2893 new_reftable
= old_reftable
;
2894 new_reftable_size
= old_reftable_size
;
2895 new_reftable_offset
= old_reftable_offset
;
2899 /* On success, new_reftable actually points to the old reftable (and
2900 * new_reftable_size is the old reftable's size); but that is just
2902 for (i
= 0; i
< new_reftable_size
; i
++) {
2903 uint64_t offset
= new_reftable
[i
] & REFT_OFFSET_MASK
;
2905 qcow2_free_clusters(bs
, offset
, s
->cluster_size
,
2906 QCOW2_DISCARD_OTHER
);
2909 g_free(new_reftable
);
2911 if (new_reftable_offset
> 0) {
2912 qcow2_free_clusters(bs
, new_reftable_offset
,
2913 new_reftable_size
* sizeof(uint64_t),
2914 QCOW2_DISCARD_OTHER
);
2918 qemu_vfree(new_refblock
);