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
, 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
;
222 BLKDBG_EVENT(bs
->file
, BLKDBG_REFBLOCK_LOAD
);
223 return qcow2_cache_get(bs
, s
->refcount_block_cache
, refcount_block_offset
,
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
,
234 BDRVQcow2State
*s
= bs
->opaque
;
235 uint64_t refcount_table_index
, block_index
;
236 int64_t refcount_block_offset
;
238 void *refcount_block
;
240 refcount_table_index
= cluster_index
>> s
->refcount_block_bits
;
241 if (refcount_table_index
>= s
->refcount_table_size
) {
245 refcount_block_offset
=
246 s
->refcount_table
[refcount_table_index
] & REFT_OFFSET_MASK
;
247 if (!refcount_block_offset
) {
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
);
259 ret
= qcow2_cache_get(bs
, s
->refcount_block_cache
, refcount_block_offset
,
265 block_index
= cluster_index
& (s
->refcount_block_size
- 1);
266 *refcount
= s
->get_refcount(refcount_block
, block_index
);
268 qcow2_cache_put(bs
, s
->refcount_block_cache
, &refcount_block
);
274 * Rounds the refcount table size up to avoid growing the table for each single
275 * refcount block that is allocated.
277 static unsigned int next_refcount_table_size(BDRVQcow2State
*s
,
278 unsigned int min_size
)
280 unsigned int min_clusters
= (min_size
>> (s
->cluster_bits
- 3)) + 1;
281 unsigned int refcount_table_clusters
=
282 MAX(1, s
->refcount_table_size
>> (s
->cluster_bits
- 3));
284 while (min_clusters
> refcount_table_clusters
) {
285 refcount_table_clusters
= (refcount_table_clusters
* 3 + 1) / 2;
288 return refcount_table_clusters
<< (s
->cluster_bits
- 3);
292 /* Checks if two offsets are described by the same refcount block */
293 static int in_same_refcount_block(BDRVQcow2State
*s
, uint64_t offset_a
,
296 uint64_t block_a
= offset_a
>> (s
->cluster_bits
+ s
->refcount_block_bits
);
297 uint64_t block_b
= offset_b
>> (s
->cluster_bits
+ s
->refcount_block_bits
);
299 return (block_a
== block_b
);
303 * Loads a refcount block. If it doesn't exist yet, it is allocated first
304 * (including growing the refcount table if needed).
306 * Returns 0 on success or -errno in error case
308 static int alloc_refcount_block(BlockDriverState
*bs
,
309 int64_t cluster_index
, void **refcount_block
)
311 BDRVQcow2State
*s
= bs
->opaque
;
312 unsigned int refcount_table_index
;
315 BLKDBG_EVENT(bs
->file
, BLKDBG_REFBLOCK_ALLOC
);
317 /* Find the refcount block for the given cluster */
318 refcount_table_index
= cluster_index
>> s
->refcount_block_bits
;
320 if (refcount_table_index
< s
->refcount_table_size
) {
322 uint64_t refcount_block_offset
=
323 s
->refcount_table
[refcount_table_index
] & REFT_OFFSET_MASK
;
325 /* If it's already there, we're done */
326 if (refcount_block_offset
) {
327 if (offset_into_cluster(s
, refcount_block_offset
)) {
328 qcow2_signal_corruption(bs
, true, -1, -1, "Refblock offset %#"
329 PRIx64
" unaligned (reftable index: "
330 "%#x)", refcount_block_offset
,
331 refcount_table_index
);
335 return load_refcount_block(bs
, refcount_block_offset
,
341 * If we came here, we need to allocate something. Something is at least
342 * a cluster for the new refcount block. It may also include a new refcount
343 * table if the old refcount table is too small.
345 * Note that allocating clusters here needs some special care:
347 * - We can't use the normal qcow2_alloc_clusters(), it would try to
348 * increase the refcount and very likely we would end up with an endless
349 * recursion. Instead we must place the refcount blocks in a way that
350 * they can describe them themselves.
352 * - We need to consider that at this point we are inside update_refcounts
353 * and potentially doing an initial refcount increase. This means that
354 * some clusters have already been allocated by the caller, but their
355 * refcount isn't accurate yet. If we allocate clusters for metadata, we
356 * need to return -EAGAIN to signal the caller that it needs to restart
357 * the search for free clusters.
359 * - alloc_clusters_noref and qcow2_free_clusters may load a different
360 * refcount block into the cache
363 *refcount_block
= NULL
;
365 /* We write to the refcount table, so we might depend on L2 tables */
366 ret
= qcow2_cache_flush(bs
, s
->l2_table_cache
);
371 /* Allocate the refcount block itself and mark it as used */
372 int64_t new_block
= alloc_clusters_noref(bs
, s
->cluster_size
);
378 fprintf(stderr
, "qcow2: Allocate refcount block %d for %" PRIx64
380 refcount_table_index
, cluster_index
<< s
->cluster_bits
, new_block
);
383 if (in_same_refcount_block(s
, new_block
, cluster_index
<< s
->cluster_bits
)) {
384 /* Zero the new refcount block before updating it */
385 ret
= qcow2_cache_get_empty(bs
, s
->refcount_block_cache
, new_block
,
391 memset(*refcount_block
, 0, s
->cluster_size
);
393 /* The block describes itself, need to update the cache */
394 int block_index
= (new_block
>> s
->cluster_bits
) &
395 (s
->refcount_block_size
- 1);
396 s
->set_refcount(*refcount_block
, block_index
, 1);
398 /* Described somewhere else. This can recurse at most twice before we
399 * arrive at a block that describes itself. */
400 ret
= update_refcount(bs
, new_block
, s
->cluster_size
, 1, false,
401 QCOW2_DISCARD_NEVER
);
406 ret
= qcow2_cache_flush(bs
, s
->refcount_block_cache
);
411 /* Initialize the new refcount block only after updating its refcount,
412 * update_refcount uses the refcount cache itself */
413 ret
= qcow2_cache_get_empty(bs
, s
->refcount_block_cache
, new_block
,
419 memset(*refcount_block
, 0, s
->cluster_size
);
422 /* Now the new refcount block needs to be written to disk */
423 BLKDBG_EVENT(bs
->file
, BLKDBG_REFBLOCK_ALLOC_WRITE
);
424 qcow2_cache_entry_mark_dirty(bs
, s
->refcount_block_cache
, *refcount_block
);
425 ret
= qcow2_cache_flush(bs
, s
->refcount_block_cache
);
430 /* If the refcount table is big enough, just hook the block up there */
431 if (refcount_table_index
< s
->refcount_table_size
) {
432 uint64_t data64
= cpu_to_be64(new_block
);
433 BLKDBG_EVENT(bs
->file
, BLKDBG_REFBLOCK_ALLOC_HOOKUP
);
434 ret
= bdrv_pwrite_sync(bs
->file
,
435 s
->refcount_table_offset
+ refcount_table_index
* sizeof(uint64_t),
436 &data64
, sizeof(data64
));
441 s
->refcount_table
[refcount_table_index
] = new_block
;
443 /* The new refcount block may be where the caller intended to put its
444 * data, so let it restart the search. */
448 qcow2_cache_put(bs
, s
->refcount_block_cache
, refcount_block
);
451 * If we come here, we need to grow the refcount table. Again, a new
452 * refcount table needs some space and we can't simply allocate to avoid
455 * Therefore let's grab new refcount blocks at the end of the image, which
456 * will describe themselves and the new refcount table. This way we can
457 * reference them only in the new table and do the switch to the new
458 * refcount table at once without producing an inconsistent state in
461 BLKDBG_EVENT(bs
->file
, BLKDBG_REFTABLE_GROW
);
463 /* Calculate the number of refcount blocks needed so far; this will be the
464 * basis for calculating the index of the first cluster used for the
465 * self-describing refcount structures which we are about to create.
467 * Because we reached this point, there cannot be any refcount entries for
468 * cluster_index or higher indices yet. However, because new_block has been
469 * allocated to describe that cluster (and it will assume this role later
470 * on), we cannot use that index; also, new_block may actually have a higher
471 * cluster index than cluster_index, so it needs to be taken into account
472 * here (and 1 needs to be added to its value because that cluster is used).
474 uint64_t blocks_used
= DIV_ROUND_UP(MAX(cluster_index
+ 1,
475 (new_block
>> s
->cluster_bits
) + 1),
476 s
->refcount_block_size
);
478 if (blocks_used
> QCOW_MAX_REFTABLE_SIZE
/ sizeof(uint64_t)) {
482 /* And now we need at least one block more for the new metadata */
483 uint64_t table_size
= next_refcount_table_size(s
, blocks_used
+ 1);
484 uint64_t last_table_size
;
485 uint64_t blocks_clusters
;
487 uint64_t table_clusters
=
488 size_to_clusters(s
, table_size
* sizeof(uint64_t));
489 blocks_clusters
= 1 +
490 DIV_ROUND_UP(table_clusters
, s
->refcount_block_size
);
491 uint64_t meta_clusters
= table_clusters
+ blocks_clusters
;
493 last_table_size
= table_size
;
494 table_size
= next_refcount_table_size(s
, blocks_used
+
495 DIV_ROUND_UP(meta_clusters
, s
->refcount_block_size
));
497 } while (last_table_size
!= table_size
);
500 fprintf(stderr
, "qcow2: Grow refcount table %" PRId32
" => %" PRId64
"\n",
501 s
->refcount_table_size
, table_size
);
504 /* Create the new refcount table and blocks */
505 uint64_t meta_offset
= (blocks_used
* s
->refcount_block_size
) *
507 uint64_t table_offset
= meta_offset
+ blocks_clusters
* s
->cluster_size
;
508 uint64_t *new_table
= g_try_new0(uint64_t, table_size
);
509 void *new_blocks
= g_try_malloc0(blocks_clusters
* s
->cluster_size
);
511 assert(table_size
> 0 && blocks_clusters
> 0);
512 if (new_table
== NULL
|| new_blocks
== NULL
) {
517 /* Fill the new refcount table */
518 memcpy(new_table
, s
->refcount_table
,
519 s
->refcount_table_size
* sizeof(uint64_t));
520 new_table
[refcount_table_index
] = new_block
;
523 for (i
= 0; i
< blocks_clusters
; i
++) {
524 new_table
[blocks_used
+ i
] = meta_offset
+ (i
* s
->cluster_size
);
527 /* Fill the refcount blocks */
528 uint64_t table_clusters
= size_to_clusters(s
, table_size
* sizeof(uint64_t));
530 for (i
= 0; i
< table_clusters
+ blocks_clusters
; i
++) {
531 s
->set_refcount(new_blocks
, block
++, 1);
534 /* Write refcount blocks to disk */
535 BLKDBG_EVENT(bs
->file
, BLKDBG_REFBLOCK_ALLOC_WRITE_BLOCKS
);
536 ret
= bdrv_pwrite_sync(bs
->file
, meta_offset
, new_blocks
,
537 blocks_clusters
* s
->cluster_size
);
544 /* Write refcount table to disk */
545 for(i
= 0; i
< table_size
; i
++) {
546 cpu_to_be64s(&new_table
[i
]);
549 BLKDBG_EVENT(bs
->file
, BLKDBG_REFBLOCK_ALLOC_WRITE_TABLE
);
550 ret
= bdrv_pwrite_sync(bs
->file
, table_offset
, new_table
,
551 table_size
* sizeof(uint64_t));
556 for(i
= 0; i
< table_size
; i
++) {
557 be64_to_cpus(&new_table
[i
]);
560 /* Hook up the new refcount table in the qcow2 header */
565 data
.d64
= cpu_to_be64(table_offset
);
566 data
.d32
= cpu_to_be32(table_clusters
);
567 BLKDBG_EVENT(bs
->file
, BLKDBG_REFBLOCK_ALLOC_SWITCH_TABLE
);
568 ret
= bdrv_pwrite_sync(bs
->file
,
569 offsetof(QCowHeader
, refcount_table_offset
),
570 &data
, sizeof(data
));
575 /* And switch it in memory */
576 uint64_t old_table_offset
= s
->refcount_table_offset
;
577 uint64_t old_table_size
= s
->refcount_table_size
;
579 g_free(s
->refcount_table
);
580 s
->refcount_table
= new_table
;
581 s
->refcount_table_size
= table_size
;
582 s
->refcount_table_offset
= table_offset
;
584 /* Free old table. */
585 qcow2_free_clusters(bs
, old_table_offset
, old_table_size
* sizeof(uint64_t),
586 QCOW2_DISCARD_OTHER
);
588 ret
= load_refcount_block(bs
, new_block
, refcount_block
);
593 /* If we were trying to do the initial refcount update for some cluster
594 * allocation, we might have used the same clusters to store newly
595 * allocated metadata. Make the caller search some new space. */
602 if (*refcount_block
!= NULL
) {
603 qcow2_cache_put(bs
, s
->refcount_block_cache
, refcount_block
);
608 void qcow2_process_discards(BlockDriverState
*bs
, int ret
)
610 BDRVQcow2State
*s
= bs
->opaque
;
611 Qcow2DiscardRegion
*d
, *next
;
613 QTAILQ_FOREACH_SAFE(d
, &s
->discards
, next
, next
) {
614 QTAILQ_REMOVE(&s
->discards
, d
, next
);
616 /* Discard is optional, ignore the return value */
618 bdrv_discard(bs
->file
->bs
,
619 d
->offset
>> BDRV_SECTOR_BITS
,
620 d
->bytes
>> BDRV_SECTOR_BITS
);
627 static void update_refcount_discard(BlockDriverState
*bs
,
628 uint64_t offset
, uint64_t length
)
630 BDRVQcow2State
*s
= bs
->opaque
;
631 Qcow2DiscardRegion
*d
, *p
, *next
;
633 QTAILQ_FOREACH(d
, &s
->discards
, next
) {
634 uint64_t new_start
= MIN(offset
, d
->offset
);
635 uint64_t new_end
= MAX(offset
+ length
, d
->offset
+ d
->bytes
);
637 if (new_end
- new_start
<= length
+ d
->bytes
) {
638 /* There can't be any overlap, areas ending up here have no
639 * references any more and therefore shouldn't get freed another
641 assert(d
->bytes
+ length
== new_end
- new_start
);
642 d
->offset
= new_start
;
643 d
->bytes
= new_end
- new_start
;
648 d
= g_malloc(sizeof(*d
));
649 *d
= (Qcow2DiscardRegion
) {
654 QTAILQ_INSERT_TAIL(&s
->discards
, d
, next
);
657 /* Merge discard requests if they are adjacent now */
658 QTAILQ_FOREACH_SAFE(p
, &s
->discards
, next
, next
) {
660 || p
->offset
> d
->offset
+ d
->bytes
661 || d
->offset
> p
->offset
+ p
->bytes
)
666 /* Still no overlap possible */
667 assert(p
->offset
== d
->offset
+ d
->bytes
668 || d
->offset
== p
->offset
+ p
->bytes
);
670 QTAILQ_REMOVE(&s
->discards
, p
, next
);
671 d
->offset
= MIN(d
->offset
, p
->offset
);
672 d
->bytes
+= p
->bytes
;
677 /* XXX: cache several refcount block clusters ? */
678 /* @addend is the absolute value of the addend; if @decrease is set, @addend
679 * will be subtracted from the current refcount, otherwise it will be added */
680 static int QEMU_WARN_UNUSED_RESULT
update_refcount(BlockDriverState
*bs
,
685 enum qcow2_discard_type type
)
687 BDRVQcow2State
*s
= bs
->opaque
;
688 int64_t start
, last
, cluster_offset
;
689 void *refcount_block
= NULL
;
690 int64_t old_table_index
= -1;
694 fprintf(stderr
, "update_refcount: offset=%" PRId64
" size=%" PRId64
695 " addend=%s%" PRIu64
"\n", offset
, length
, decrease
? "-" : "",
700 } else if (length
== 0) {
705 qcow2_cache_set_dependency(bs
, s
->refcount_block_cache
,
709 start
= start_of_cluster(s
, offset
);
710 last
= start_of_cluster(s
, offset
+ length
- 1);
711 for(cluster_offset
= start
; cluster_offset
<= last
;
712 cluster_offset
+= s
->cluster_size
)
716 int64_t cluster_index
= cluster_offset
>> s
->cluster_bits
;
717 int64_t table_index
= cluster_index
>> s
->refcount_block_bits
;
719 /* Load the refcount block and allocate it if needed */
720 if (table_index
!= old_table_index
) {
721 if (refcount_block
) {
722 qcow2_cache_put(bs
, s
->refcount_block_cache
, &refcount_block
);
724 ret
= alloc_refcount_block(bs
, cluster_index
, &refcount_block
);
729 old_table_index
= table_index
;
731 qcow2_cache_entry_mark_dirty(bs
, s
->refcount_block_cache
,
734 /* we can update the count and save it */
735 block_index
= cluster_index
& (s
->refcount_block_size
- 1);
737 refcount
= s
->get_refcount(refcount_block
, block_index
);
738 if (decrease
? (refcount
- addend
> refcount
)
739 : (refcount
+ addend
< refcount
||
740 refcount
+ addend
> s
->refcount_max
))
750 if (refcount
== 0 && cluster_index
< s
->free_cluster_index
) {
751 s
->free_cluster_index
= cluster_index
;
753 s
->set_refcount(refcount_block
, block_index
, refcount
);
755 if (refcount
== 0 && s
->discard_passthrough
[type
]) {
756 update_refcount_discard(bs
, cluster_offset
, s
->cluster_size
);
762 if (!s
->cache_discards
) {
763 qcow2_process_discards(bs
, ret
);
766 /* Write last changed block to disk */
767 if (refcount_block
) {
768 qcow2_cache_put(bs
, s
->refcount_block_cache
, &refcount_block
);
772 * Try do undo any updates if an error is returned (This may succeed in
773 * some cases like ENOSPC for allocating a new refcount block)
777 dummy
= update_refcount(bs
, offset
, cluster_offset
- offset
, addend
,
778 !decrease
, QCOW2_DISCARD_NEVER
);
786 * Increases or decreases the refcount of a given cluster.
788 * @addend is the absolute value of the addend; if @decrease is set, @addend
789 * will be subtracted from the current refcount, otherwise it will be added.
791 * On success 0 is returned; on failure -errno is returned.
793 int qcow2_update_cluster_refcount(BlockDriverState
*bs
,
794 int64_t cluster_index
,
795 uint64_t addend
, bool decrease
,
796 enum qcow2_discard_type type
)
798 BDRVQcow2State
*s
= bs
->opaque
;
801 ret
= update_refcount(bs
, cluster_index
<< s
->cluster_bits
, 1, addend
,
812 /*********************************************************/
813 /* cluster allocation functions */
817 /* return < 0 if error */
818 static int64_t alloc_clusters_noref(BlockDriverState
*bs
, uint64_t size
)
820 BDRVQcow2State
*s
= bs
->opaque
;
821 uint64_t i
, nb_clusters
, refcount
;
824 /* We can't allocate clusters if they may still be queued for discard. */
825 if (s
->cache_discards
) {
826 qcow2_process_discards(bs
, 0);
829 nb_clusters
= size_to_clusters(s
, size
);
831 for(i
= 0; i
< nb_clusters
; i
++) {
832 uint64_t next_cluster_index
= s
->free_cluster_index
++;
833 ret
= qcow2_get_refcount(bs
, next_cluster_index
, &refcount
);
837 } else if (refcount
!= 0) {
842 /* Make sure that all offsets in the "allocated" range are representable
844 if (s
->free_cluster_index
> 0 &&
845 s
->free_cluster_index
- 1 > (INT64_MAX
>> s
->cluster_bits
))
851 fprintf(stderr
, "alloc_clusters: size=%" PRId64
" -> %" PRId64
"\n",
853 (s
->free_cluster_index
- nb_clusters
) << s
->cluster_bits
);
855 return (s
->free_cluster_index
- nb_clusters
) << s
->cluster_bits
;
858 int64_t qcow2_alloc_clusters(BlockDriverState
*bs
, uint64_t size
)
863 BLKDBG_EVENT(bs
->file
, BLKDBG_CLUSTER_ALLOC
);
865 offset
= alloc_clusters_noref(bs
, size
);
870 ret
= update_refcount(bs
, offset
, size
, 1, false, QCOW2_DISCARD_NEVER
);
871 } while (ret
== -EAGAIN
);
880 int64_t qcow2_alloc_clusters_at(BlockDriverState
*bs
, uint64_t offset
,
883 BDRVQcow2State
*s
= bs
->opaque
;
884 uint64_t cluster_index
, refcount
;
888 assert(nb_clusters
>= 0);
889 if (nb_clusters
== 0) {
894 /* Check how many clusters there are free */
895 cluster_index
= offset
>> s
->cluster_bits
;
896 for(i
= 0; i
< nb_clusters
; i
++) {
897 ret
= qcow2_get_refcount(bs
, cluster_index
++, &refcount
);
900 } else if (refcount
!= 0) {
905 /* And then allocate them */
906 ret
= update_refcount(bs
, offset
, i
<< s
->cluster_bits
, 1, false,
907 QCOW2_DISCARD_NEVER
);
908 } while (ret
== -EAGAIN
);
917 /* only used to allocate compressed sectors. We try to allocate
918 contiguous sectors. size must be <= cluster_size */
919 int64_t qcow2_alloc_bytes(BlockDriverState
*bs
, int size
)
921 BDRVQcow2State
*s
= bs
->opaque
;
923 size_t free_in_cluster
;
926 BLKDBG_EVENT(bs
->file
, BLKDBG_CLUSTER_ALLOC_BYTES
);
927 assert(size
> 0 && size
<= s
->cluster_size
);
928 assert(!s
->free_byte_offset
|| offset_into_cluster(s
, s
->free_byte_offset
));
930 offset
= s
->free_byte_offset
;
934 ret
= qcow2_get_refcount(bs
, offset
>> s
->cluster_bits
, &refcount
);
939 if (refcount
== s
->refcount_max
) {
944 free_in_cluster
= s
->cluster_size
- offset_into_cluster(s
, offset
);
946 if (!offset
|| free_in_cluster
< size
) {
947 int64_t new_cluster
= alloc_clusters_noref(bs
, s
->cluster_size
);
948 if (new_cluster
< 0) {
952 if (!offset
|| ROUND_UP(offset
, s
->cluster_size
) != new_cluster
) {
953 offset
= new_cluster
;
954 free_in_cluster
= s
->cluster_size
;
956 free_in_cluster
+= s
->cluster_size
;
961 ret
= update_refcount(bs
, offset
, size
, 1, false, QCOW2_DISCARD_NEVER
);
965 } while (ret
== -EAGAIN
);
970 /* The cluster refcount was incremented; refcount blocks must be flushed
971 * before the caller's L2 table updates. */
972 qcow2_cache_set_dependency(bs
, s
->l2_table_cache
, s
->refcount_block_cache
);
974 s
->free_byte_offset
= offset
+ size
;
975 if (!offset_into_cluster(s
, s
->free_byte_offset
)) {
976 s
->free_byte_offset
= 0;
982 void qcow2_free_clusters(BlockDriverState
*bs
,
983 int64_t offset
, int64_t size
,
984 enum qcow2_discard_type type
)
988 BLKDBG_EVENT(bs
->file
, BLKDBG_CLUSTER_FREE
);
989 ret
= update_refcount(bs
, offset
, size
, 1, true, type
);
991 fprintf(stderr
, "qcow2_free_clusters failed: %s\n", strerror(-ret
));
992 /* TODO Remember the clusters to free them later and avoid leaking */
997 * Free a cluster using its L2 entry (handles clusters of all types, e.g.
998 * normal cluster, compressed cluster, etc.)
1000 void qcow2_free_any_clusters(BlockDriverState
*bs
, uint64_t l2_entry
,
1001 int nb_clusters
, enum qcow2_discard_type type
)
1003 BDRVQcow2State
*s
= bs
->opaque
;
1005 switch (qcow2_get_cluster_type(l2_entry
)) {
1006 case QCOW2_CLUSTER_COMPRESSED
:
1009 nb_csectors
= ((l2_entry
>> s
->csize_shift
) &
1011 qcow2_free_clusters(bs
,
1012 (l2_entry
& s
->cluster_offset_mask
) & ~511,
1013 nb_csectors
* 512, type
);
1016 case QCOW2_CLUSTER_NORMAL
:
1017 case QCOW2_CLUSTER_ZERO
:
1018 if (l2_entry
& L2E_OFFSET_MASK
) {
1019 if (offset_into_cluster(s
, l2_entry
& L2E_OFFSET_MASK
)) {
1020 qcow2_signal_corruption(bs
, false, -1, -1,
1021 "Cannot free unaligned cluster %#llx",
1022 l2_entry
& L2E_OFFSET_MASK
);
1024 qcow2_free_clusters(bs
, l2_entry
& L2E_OFFSET_MASK
,
1025 nb_clusters
<< s
->cluster_bits
, type
);
1029 case QCOW2_CLUSTER_UNALLOCATED
:
1038 /*********************************************************/
1039 /* snapshots and image creation */
1043 /* update the refcounts of snapshots and the copied flag */
1044 int qcow2_update_snapshot_refcount(BlockDriverState
*bs
,
1045 int64_t l1_table_offset
, int l1_size
, int addend
)
1047 BDRVQcow2State
*s
= bs
->opaque
;
1048 uint64_t *l1_table
, *l2_table
, l2_offset
, offset
, l1_size2
, refcount
;
1049 bool l1_allocated
= false;
1050 int64_t old_offset
, old_l2_offset
;
1051 int i
, j
, l1_modified
= 0, nb_csectors
;
1054 assert(addend
>= -1 && addend
<= 1);
1058 l1_size2
= l1_size
* sizeof(uint64_t);
1060 s
->cache_discards
= true;
1062 /* WARNING: qcow2_snapshot_goto relies on this function not using the
1063 * l1_table_offset when it is the current s->l1_table_offset! Be careful
1064 * when changing this! */
1065 if (l1_table_offset
!= s
->l1_table_offset
) {
1066 l1_table
= g_try_malloc0(align_offset(l1_size2
, 512));
1067 if (l1_size2
&& l1_table
== NULL
) {
1071 l1_allocated
= true;
1073 ret
= bdrv_pread(bs
->file
, l1_table_offset
, l1_table
, l1_size2
);
1078 for(i
= 0;i
< l1_size
; i
++)
1079 be64_to_cpus(&l1_table
[i
]);
1081 assert(l1_size
== s
->l1_size
);
1082 l1_table
= s
->l1_table
;
1083 l1_allocated
= false;
1086 for(i
= 0; i
< l1_size
; i
++) {
1087 l2_offset
= l1_table
[i
];
1089 old_l2_offset
= l2_offset
;
1090 l2_offset
&= L1E_OFFSET_MASK
;
1092 if (offset_into_cluster(s
, l2_offset
)) {
1093 qcow2_signal_corruption(bs
, true, -1, -1, "L2 table offset %#"
1094 PRIx64
" unaligned (L1 index: %#x)",
1100 ret
= qcow2_cache_get(bs
, s
->l2_table_cache
, l2_offset
,
1101 (void**) &l2_table
);
1106 for(j
= 0; j
< s
->l2_size
; j
++) {
1107 uint64_t cluster_index
;
1109 offset
= be64_to_cpu(l2_table
[j
]);
1110 old_offset
= offset
;
1111 offset
&= ~QCOW_OFLAG_COPIED
;
1113 switch (qcow2_get_cluster_type(offset
)) {
1114 case QCOW2_CLUSTER_COMPRESSED
:
1115 nb_csectors
= ((offset
>> s
->csize_shift
) &
1118 ret
= update_refcount(bs
,
1119 (offset
& s
->cluster_offset_mask
) & ~511,
1120 nb_csectors
* 512, abs(addend
), addend
< 0,
1121 QCOW2_DISCARD_SNAPSHOT
);
1126 /* compressed clusters are never modified */
1130 case QCOW2_CLUSTER_NORMAL
:
1131 case QCOW2_CLUSTER_ZERO
:
1132 if (offset_into_cluster(s
, offset
& L2E_OFFSET_MASK
)) {
1133 qcow2_signal_corruption(bs
, true, -1, -1, "Data "
1134 "cluster offset %#llx "
1135 "unaligned (L2 offset: %#"
1136 PRIx64
", L2 index: %#x)",
1137 offset
& L2E_OFFSET_MASK
,
1143 cluster_index
= (offset
& L2E_OFFSET_MASK
) >> s
->cluster_bits
;
1144 if (!cluster_index
) {
1150 ret
= qcow2_update_cluster_refcount(bs
,
1151 cluster_index
, abs(addend
), addend
< 0,
1152 QCOW2_DISCARD_SNAPSHOT
);
1158 ret
= qcow2_get_refcount(bs
, cluster_index
, &refcount
);
1164 case QCOW2_CLUSTER_UNALLOCATED
:
1172 if (refcount
== 1) {
1173 offset
|= QCOW_OFLAG_COPIED
;
1175 if (offset
!= old_offset
) {
1177 qcow2_cache_set_dependency(bs
, s
->l2_table_cache
,
1178 s
->refcount_block_cache
);
1180 l2_table
[j
] = cpu_to_be64(offset
);
1181 qcow2_cache_entry_mark_dirty(bs
, s
->l2_table_cache
,
1186 qcow2_cache_put(bs
, s
->l2_table_cache
, (void **) &l2_table
);
1189 ret
= qcow2_update_cluster_refcount(bs
, l2_offset
>>
1191 abs(addend
), addend
< 0,
1192 QCOW2_DISCARD_SNAPSHOT
);
1197 ret
= qcow2_get_refcount(bs
, l2_offset
>> s
->cluster_bits
,
1201 } else if (refcount
== 1) {
1202 l2_offset
|= QCOW_OFLAG_COPIED
;
1204 if (l2_offset
!= old_l2_offset
) {
1205 l1_table
[i
] = l2_offset
;
1211 ret
= bdrv_flush(bs
);
1214 qcow2_cache_put(bs
, s
->l2_table_cache
, (void**) &l2_table
);
1217 s
->cache_discards
= false;
1218 qcow2_process_discards(bs
, ret
);
1220 /* Update L1 only if it isn't deleted anyway (addend = -1) */
1221 if (ret
== 0 && addend
>= 0 && l1_modified
) {
1222 for (i
= 0; i
< l1_size
; i
++) {
1223 cpu_to_be64s(&l1_table
[i
]);
1226 ret
= bdrv_pwrite_sync(bs
->file
, l1_table_offset
,
1227 l1_table
, l1_size2
);
1229 for (i
= 0; i
< l1_size
; i
++) {
1230 be64_to_cpus(&l1_table
[i
]);
1241 /*********************************************************/
1242 /* refcount checking functions */
1245 static uint64_t refcount_array_byte_size(BDRVQcow2State
*s
, uint64_t entries
)
1247 /* This assertion holds because there is no way we can address more than
1248 * 2^(64 - 9) clusters at once (with cluster size 512 = 2^9, and because
1249 * offsets have to be representable in bytes); due to every cluster
1250 * corresponding to one refcount entry, we are well below that limit */
1251 assert(entries
< (UINT64_C(1) << (64 - 9)));
1253 /* Thanks to the assertion this will not overflow, because
1254 * s->refcount_order < 7.
1255 * (note: x << s->refcount_order == x * s->refcount_bits) */
1256 return DIV_ROUND_UP(entries
<< s
->refcount_order
, 8);
1260 * Reallocates *array so that it can hold new_size entries. *size must contain
1261 * the current number of entries in *array. If the reallocation fails, *array
1262 * and *size will not be modified and -errno will be returned. If the
1263 * reallocation is successful, *array will be set to the new buffer, *size
1264 * will be set to new_size and 0 will be returned. The size of the reallocated
1265 * refcount array buffer will be aligned to a cluster boundary, and the newly
1266 * allocated area will be zeroed.
1268 static int realloc_refcount_array(BDRVQcow2State
*s
, void **array
,
1269 int64_t *size
, int64_t new_size
)
1271 int64_t old_byte_size
, new_byte_size
;
1274 /* Round to clusters so the array can be directly written to disk */
1275 old_byte_size
= size_to_clusters(s
, refcount_array_byte_size(s
, *size
))
1277 new_byte_size
= size_to_clusters(s
, refcount_array_byte_size(s
, new_size
))
1280 if (new_byte_size
== old_byte_size
) {
1285 assert(new_byte_size
> 0);
1287 if (new_byte_size
> SIZE_MAX
) {
1291 new_ptr
= g_try_realloc(*array
, new_byte_size
);
1296 if (new_byte_size
> old_byte_size
) {
1297 memset((char *)new_ptr
+ old_byte_size
, 0,
1298 new_byte_size
- old_byte_size
);
1308 * Increases the refcount for a range of clusters in a given refcount table.
1309 * This is used to construct a temporary refcount table out of L1 and L2 tables
1310 * which can be compared to the refcount table saved in the image.
1312 * Modifies the number of errors in res.
1314 static int inc_refcounts(BlockDriverState
*bs
,
1315 BdrvCheckResult
*res
,
1316 void **refcount_table
,
1317 int64_t *refcount_table_size
,
1318 int64_t offset
, int64_t size
)
1320 BDRVQcow2State
*s
= bs
->opaque
;
1321 uint64_t start
, last
, cluster_offset
, k
, refcount
;
1328 start
= start_of_cluster(s
, offset
);
1329 last
= start_of_cluster(s
, offset
+ size
- 1);
1330 for(cluster_offset
= start
; cluster_offset
<= last
;
1331 cluster_offset
+= s
->cluster_size
) {
1332 k
= cluster_offset
>> s
->cluster_bits
;
1333 if (k
>= *refcount_table_size
) {
1334 ret
= realloc_refcount_array(s
, refcount_table
,
1335 refcount_table_size
, k
+ 1);
1337 res
->check_errors
++;
1342 refcount
= s
->get_refcount(*refcount_table
, k
);
1343 if (refcount
== s
->refcount_max
) {
1344 fprintf(stderr
, "ERROR: overflow cluster offset=0x%" PRIx64
1345 "\n", cluster_offset
);
1346 fprintf(stderr
, "Use qemu-img amend to increase the refcount entry "
1347 "width or qemu-img convert to create a clean copy if the "
1348 "image cannot be opened for writing\n");
1352 s
->set_refcount(*refcount_table
, k
, refcount
+ 1);
1358 /* Flags for check_refcounts_l1() and check_refcounts_l2() */
1360 CHECK_FRAG_INFO
= 0x2, /* update BlockFragInfo counters */
1364 * Increases the refcount in the given refcount table for the all clusters
1365 * referenced in the L2 table. While doing so, performs some checks on L2
1368 * Returns the number of errors found by the checks or -errno if an internal
1371 static int check_refcounts_l2(BlockDriverState
*bs
, BdrvCheckResult
*res
,
1372 void **refcount_table
,
1373 int64_t *refcount_table_size
, int64_t l2_offset
,
1376 BDRVQcow2State
*s
= bs
->opaque
;
1377 uint64_t *l2_table
, l2_entry
;
1378 uint64_t next_contiguous_offset
= 0;
1379 int i
, l2_size
, nb_csectors
, ret
;
1381 /* Read L2 table from disk */
1382 l2_size
= s
->l2_size
* sizeof(uint64_t);
1383 l2_table
= g_malloc(l2_size
);
1385 ret
= bdrv_pread(bs
->file
, l2_offset
, l2_table
, l2_size
);
1387 fprintf(stderr
, "ERROR: I/O error in check_refcounts_l2\n");
1388 res
->check_errors
++;
1392 /* Do the actual checks */
1393 for(i
= 0; i
< s
->l2_size
; i
++) {
1394 l2_entry
= be64_to_cpu(l2_table
[i
]);
1396 switch (qcow2_get_cluster_type(l2_entry
)) {
1397 case QCOW2_CLUSTER_COMPRESSED
:
1398 /* Compressed clusters don't have QCOW_OFLAG_COPIED */
1399 if (l2_entry
& QCOW_OFLAG_COPIED
) {
1400 fprintf(stderr
, "ERROR: cluster %" PRId64
": "
1401 "copied flag must never be set for compressed "
1402 "clusters\n", l2_entry
>> s
->cluster_bits
);
1403 l2_entry
&= ~QCOW_OFLAG_COPIED
;
1407 /* Mark cluster as used */
1408 nb_csectors
= ((l2_entry
>> s
->csize_shift
) &
1410 l2_entry
&= s
->cluster_offset_mask
;
1411 ret
= inc_refcounts(bs
, res
, refcount_table
, refcount_table_size
,
1412 l2_entry
& ~511, nb_csectors
* 512);
1417 if (flags
& CHECK_FRAG_INFO
) {
1418 res
->bfi
.allocated_clusters
++;
1419 res
->bfi
.compressed_clusters
++;
1421 /* Compressed clusters are fragmented by nature. Since they
1422 * take up sub-sector space but we only have sector granularity
1423 * I/O we need to re-read the same sectors even for adjacent
1424 * compressed clusters.
1426 res
->bfi
.fragmented_clusters
++;
1430 case QCOW2_CLUSTER_ZERO
:
1431 if ((l2_entry
& L2E_OFFSET_MASK
) == 0) {
1436 case QCOW2_CLUSTER_NORMAL
:
1438 uint64_t offset
= l2_entry
& L2E_OFFSET_MASK
;
1440 if (flags
& CHECK_FRAG_INFO
) {
1441 res
->bfi
.allocated_clusters
++;
1442 if (next_contiguous_offset
&&
1443 offset
!= next_contiguous_offset
) {
1444 res
->bfi
.fragmented_clusters
++;
1446 next_contiguous_offset
= offset
+ s
->cluster_size
;
1449 /* Mark cluster as used */
1450 ret
= inc_refcounts(bs
, res
, refcount_table
, refcount_table_size
,
1451 offset
, s
->cluster_size
);
1456 /* Correct offsets are cluster aligned */
1457 if (offset_into_cluster(s
, offset
)) {
1458 fprintf(stderr
, "ERROR offset=%" PRIx64
": Cluster is not "
1459 "properly aligned; L2 entry corrupted.\n", offset
);
1465 case QCOW2_CLUSTER_UNALLOCATED
:
1482 * Increases the refcount for the L1 table, its L2 tables and all referenced
1483 * clusters in the given refcount table. While doing so, performs some checks
1484 * on L1 and L2 entries.
1486 * Returns the number of errors found by the checks or -errno if an internal
1489 static int check_refcounts_l1(BlockDriverState
*bs
,
1490 BdrvCheckResult
*res
,
1491 void **refcount_table
,
1492 int64_t *refcount_table_size
,
1493 int64_t l1_table_offset
, int l1_size
,
1496 BDRVQcow2State
*s
= bs
->opaque
;
1497 uint64_t *l1_table
= NULL
, l2_offset
, l1_size2
;
1500 l1_size2
= l1_size
* sizeof(uint64_t);
1502 /* Mark L1 table as used */
1503 ret
= inc_refcounts(bs
, res
, refcount_table
, refcount_table_size
,
1504 l1_table_offset
, l1_size2
);
1509 /* Read L1 table entries from disk */
1511 l1_table
= g_try_malloc(l1_size2
);
1512 if (l1_table
== NULL
) {
1514 res
->check_errors
++;
1517 ret
= bdrv_pread(bs
->file
, l1_table_offset
, l1_table
, l1_size2
);
1519 fprintf(stderr
, "ERROR: I/O error in check_refcounts_l1\n");
1520 res
->check_errors
++;
1523 for(i
= 0;i
< l1_size
; i
++)
1524 be64_to_cpus(&l1_table
[i
]);
1527 /* Do the actual checks */
1528 for(i
= 0; i
< l1_size
; i
++) {
1529 l2_offset
= l1_table
[i
];
1531 /* Mark L2 table as used */
1532 l2_offset
&= L1E_OFFSET_MASK
;
1533 ret
= inc_refcounts(bs
, res
, refcount_table
, refcount_table_size
,
1534 l2_offset
, s
->cluster_size
);
1539 /* L2 tables are cluster aligned */
1540 if (offset_into_cluster(s
, l2_offset
)) {
1541 fprintf(stderr
, "ERROR l2_offset=%" PRIx64
": Table is not "
1542 "cluster aligned; L1 entry corrupted\n", l2_offset
);
1546 /* Process and check L2 entries */
1547 ret
= check_refcounts_l2(bs
, res
, refcount_table
,
1548 refcount_table_size
, l2_offset
, flags
);
1563 * Checks the OFLAG_COPIED flag for all L1 and L2 entries.
1565 * This function does not print an error message nor does it increment
1566 * check_errors if qcow2_get_refcount fails (this is because such an error will
1567 * have been already detected and sufficiently signaled by the calling function
1568 * (qcow2_check_refcounts) by the time this function is called).
1570 static int check_oflag_copied(BlockDriverState
*bs
, BdrvCheckResult
*res
,
1573 BDRVQcow2State
*s
= bs
->opaque
;
1574 uint64_t *l2_table
= qemu_blockalign(bs
, s
->cluster_size
);
1579 for (i
= 0; i
< s
->l1_size
; i
++) {
1580 uint64_t l1_entry
= s
->l1_table
[i
];
1581 uint64_t l2_offset
= l1_entry
& L1E_OFFSET_MASK
;
1582 bool l2_dirty
= false;
1588 ret
= qcow2_get_refcount(bs
, l2_offset
>> s
->cluster_bits
,
1591 /* don't print message nor increment check_errors */
1594 if ((refcount
== 1) != ((l1_entry
& QCOW_OFLAG_COPIED
) != 0)) {
1595 fprintf(stderr
, "%s OFLAG_COPIED L2 cluster: l1_index=%d "
1596 "l1_entry=%" PRIx64
" refcount=%" PRIu64
"\n",
1597 fix
& BDRV_FIX_ERRORS
? "Repairing" :
1599 i
, l1_entry
, refcount
);
1600 if (fix
& BDRV_FIX_ERRORS
) {
1601 s
->l1_table
[i
] = refcount
== 1
1602 ? l1_entry
| QCOW_OFLAG_COPIED
1603 : l1_entry
& ~QCOW_OFLAG_COPIED
;
1604 ret
= qcow2_write_l1_entry(bs
, i
);
1606 res
->check_errors
++;
1609 res
->corruptions_fixed
++;
1615 ret
= bdrv_pread(bs
->file
, l2_offset
, l2_table
,
1616 s
->l2_size
* sizeof(uint64_t));
1618 fprintf(stderr
, "ERROR: Could not read L2 table: %s\n",
1620 res
->check_errors
++;
1624 for (j
= 0; j
< s
->l2_size
; j
++) {
1625 uint64_t l2_entry
= be64_to_cpu(l2_table
[j
]);
1626 uint64_t data_offset
= l2_entry
& L2E_OFFSET_MASK
;
1627 int cluster_type
= qcow2_get_cluster_type(l2_entry
);
1629 if ((cluster_type
== QCOW2_CLUSTER_NORMAL
) ||
1630 ((cluster_type
== QCOW2_CLUSTER_ZERO
) && (data_offset
!= 0))) {
1631 ret
= qcow2_get_refcount(bs
,
1632 data_offset
>> s
->cluster_bits
,
1635 /* don't print message nor increment check_errors */
1638 if ((refcount
== 1) != ((l2_entry
& QCOW_OFLAG_COPIED
) != 0)) {
1639 fprintf(stderr
, "%s OFLAG_COPIED data cluster: "
1640 "l2_entry=%" PRIx64
" refcount=%" PRIu64
"\n",
1641 fix
& BDRV_FIX_ERRORS
? "Repairing" :
1643 l2_entry
, refcount
);
1644 if (fix
& BDRV_FIX_ERRORS
) {
1645 l2_table
[j
] = cpu_to_be64(refcount
== 1
1646 ? l2_entry
| QCOW_OFLAG_COPIED
1647 : l2_entry
& ~QCOW_OFLAG_COPIED
);
1649 res
->corruptions_fixed
++;
1658 ret
= qcow2_pre_write_overlap_check(bs
, QCOW2_OL_ACTIVE_L2
,
1659 l2_offset
, s
->cluster_size
);
1661 fprintf(stderr
, "ERROR: Could not write L2 table; metadata "
1662 "overlap check failed: %s\n", strerror(-ret
));
1663 res
->check_errors
++;
1667 ret
= bdrv_pwrite(bs
->file
, l2_offset
, l2_table
,
1670 fprintf(stderr
, "ERROR: Could not write L2 table: %s\n",
1672 res
->check_errors
++;
1681 qemu_vfree(l2_table
);
1686 * Checks consistency of refblocks and accounts for each refblock in
1689 static int check_refblocks(BlockDriverState
*bs
, BdrvCheckResult
*res
,
1690 BdrvCheckMode fix
, bool *rebuild
,
1691 void **refcount_table
, int64_t *nb_clusters
)
1693 BDRVQcow2State
*s
= bs
->opaque
;
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
);
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
) {
1723 ret
= bdrv_truncate(bs
->file
->bs
, offset
+ s
->cluster_size
);
1727 size
= bdrv_getlength(bs
->file
->bs
);
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
);
1739 res
->check_errors
++;
1743 if (cluster
>= *nb_clusters
) {
1748 res
->corruptions_fixed
++;
1749 ret
= inc_refcounts(bs
, res
, refcount_table
, nb_clusters
,
1750 offset
, s
->cluster_size
);
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() */
1762 fprintf(stderr
, "ERROR could not resize image: %s\n",
1771 ret
= inc_refcounts(bs
, res
, refcount_table
, nb_clusters
,
1772 offset
, s
->cluster_size
);
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
));
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 BDRVQcow2State
*s
= bs
->opaque
;
1801 if (!*refcount_table
) {
1802 int64_t old_size
= 0;
1803 ret
= realloc_refcount_array(s
, refcount_table
,
1804 &old_size
, *nb_clusters
);
1806 res
->check_errors
++;
1812 ret
= inc_refcounts(bs
, res
, refcount_table
, nb_clusters
,
1813 0, s
->cluster_size
);
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
);
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);
1834 ret
= inc_refcounts(bs
, res
, refcount_table
, nb_clusters
,
1835 s
->snapshots_offset
, s
->snapshots_size
);
1841 ret
= inc_refcounts(bs
, res
, refcount_table
, nb_clusters
,
1842 s
->refcount_table_offset
,
1843 s
->refcount_table_size
* sizeof(uint64_t));
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 BDRVQcow2State
*s
= bs
->opaque
;
1862 uint64_t refcount1
, refcount2
;
1865 for (i
= 0, *highest_cluster
= 0; i
< nb_clusters
; i
++) {
1866 ret
= qcow2_get_refcount(bs
, i
, &refcount1
);
1868 fprintf(stderr
, "Can't get refcount for cluster %" PRId64
": %s\n",
1870 res
->check_errors
++;
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) {
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" :
1896 i
, refcount1
, refcount2
);
1899 ret
= update_refcount(bs
, i
<< s
->cluster_bits
, 1,
1900 refcount_diff(refcount1
, refcount2
),
1901 refcount1
> refcount2
,
1902 QCOW2_DISCARD_ALWAYS
);
1909 /* And if we couldn't, print an error */
1910 if (refcount1
< refcount2
) {
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
1931 static int64_t alloc_clusters_imrt(BlockDriverState
*bs
,
1933 void **refcount_table
,
1934 int64_t *imrt_nb_clusters
,
1935 int64_t *first_free_cluster
)
1937 BDRVQcow2State
*s
= bs
->opaque
;
1938 int64_t cluster
= *first_free_cluster
, i
;
1939 bool first_gap
= true;
1940 int contiguous_free_clusters
;
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
;
1950 if (!s
->get_refcount(*refcount_table
, cluster
)) {
1951 contiguous_free_clusters
++;
1953 /* If this is the first free cluster found, update
1954 * *first_free_cluster accordingly */
1955 *first_free_cluster
= cluster
;
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
1977 ret
= realloc_refcount_array(s
, refcount_table
, imrt_nb_clusters
,
1978 cluster
+ cluster_count
1979 - contiguous_free_clusters
);
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
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 BDRVQcow2State
*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
;
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
);
2022 for (; cluster
< *nb_clusters
; cluster
++) {
2023 if (!s
->get_refcount(*refcount_table
, cluster
)) {
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
;
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
,
2053 if (!new_on_disk_reftable
) {
2054 res
->check_errors
++;
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
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
*
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
;
2089 ret
= qcow2_pre_write_overlap_check(bs
, 0, refblock_offset
,
2092 fprintf(stderr
, "ERROR writing refblock: %s\n", strerror(-ret
));
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
);
2104 fprintf(stderr
, "ERROR writing refblock: %s\n", strerror(-ret
));
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
;
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));
2145 fprintf(stderr
, "ERROR writing reftable: %s\n", strerror(-ret
));
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));
2153 fprintf(stderr
, "ERROR writing reftable: %s\n", strerror(-ret
));
2157 /* Enter new reftable into the image header */
2158 reftable_offset_and_clusters
.reftable_offset
= cpu_to_be64(reftable_offset
);
2159 reftable_offset_and_clusters
.reftable_clusters
=
2160 cpu_to_be32(size_to_clusters(s
, reftable_size
* sizeof(uint64_t)));
2161 ret
= bdrv_pwrite_sync(bs
->file
,
2162 offsetof(QCowHeader
, refcount_table_offset
),
2163 &reftable_offset_and_clusters
,
2164 sizeof(reftable_offset_and_clusters
));
2166 fprintf(stderr
, "ERROR setting reftable: %s\n", strerror(-ret
));
2170 for (refblock_index
= 0; refblock_index
< reftable_size
; refblock_index
++) {
2171 be64_to_cpus(&on_disk_reftable
[refblock_index
]);
2173 s
->refcount_table
= on_disk_reftable
;
2174 s
->refcount_table_offset
= reftable_offset
;
2175 s
->refcount_table_size
= reftable_size
;
2180 g_free(on_disk_reftable
);
2185 * Checks an image for refcount consistency.
2187 * Returns 0 if no errors are found, the number of errors in case the image is
2188 * detected as corrupted, and -errno when an internal error occurred.
2190 int qcow2_check_refcounts(BlockDriverState
*bs
, BdrvCheckResult
*res
,
2193 BDRVQcow2State
*s
= bs
->opaque
;
2194 BdrvCheckResult pre_compare_res
;
2195 int64_t size
, highest_cluster
, nb_clusters
;
2196 void *refcount_table
= NULL
;
2197 bool rebuild
= false;
2200 size
= bdrv_getlength(bs
->file
->bs
);
2202 res
->check_errors
++;
2206 nb_clusters
= size_to_clusters(s
, size
);
2207 if (nb_clusters
> INT_MAX
) {
2208 res
->check_errors
++;
2212 res
->bfi
.total_clusters
=
2213 size_to_clusters(s
, bs
->total_sectors
* BDRV_SECTOR_SIZE
);
2215 ret
= calculate_refcounts(bs
, res
, fix
, &rebuild
, &refcount_table
,
2221 /* In case we don't need to rebuild the refcount structure (but want to fix
2222 * something), this function is immediately called again, in which case the
2223 * result should be ignored */
2224 pre_compare_res
= *res
;
2225 compare_refcounts(bs
, res
, 0, &rebuild
, &highest_cluster
, refcount_table
,
2228 if (rebuild
&& (fix
& BDRV_FIX_ERRORS
)) {
2229 BdrvCheckResult old_res
= *res
;
2230 int fresh_leaks
= 0;
2232 fprintf(stderr
, "Rebuilding refcount structure\n");
2233 ret
= rebuild_refcount_structure(bs
, res
, &refcount_table
,
2239 res
->corruptions
= 0;
2242 /* Because the old reftable has been exchanged for a new one the
2243 * references have to be recalculated */
2245 memset(refcount_table
, 0, refcount_array_byte_size(s
, nb_clusters
));
2246 ret
= calculate_refcounts(bs
, res
, 0, &rebuild
, &refcount_table
,
2252 if (fix
& BDRV_FIX_LEAKS
) {
2253 /* The old refcount structures are now leaked, fix it; the result
2254 * can be ignored, aside from leaks which were introduced by
2255 * rebuild_refcount_structure() that could not be fixed */
2256 BdrvCheckResult saved_res
= *res
;
2257 *res
= (BdrvCheckResult
){ 0 };
2259 compare_refcounts(bs
, res
, BDRV_FIX_LEAKS
, &rebuild
,
2260 &highest_cluster
, refcount_table
, nb_clusters
);
2262 fprintf(stderr
, "ERROR rebuilt refcount structure is still "
2266 /* Any leaks accounted for here were introduced by
2267 * rebuild_refcount_structure() because that function has created a
2268 * new refcount structure from scratch */
2269 fresh_leaks
= res
->leaks
;
2273 if (res
->corruptions
< old_res
.corruptions
) {
2274 res
->corruptions_fixed
+= old_res
.corruptions
- res
->corruptions
;
2276 if (res
->leaks
< old_res
.leaks
) {
2277 res
->leaks_fixed
+= old_res
.leaks
- res
->leaks
;
2279 res
->leaks
+= fresh_leaks
;
2282 fprintf(stderr
, "ERROR need to rebuild refcount structures\n");
2283 res
->check_errors
++;
2288 if (res
->leaks
|| res
->corruptions
) {
2289 *res
= pre_compare_res
;
2290 compare_refcounts(bs
, res
, fix
, &rebuild
, &highest_cluster
,
2291 refcount_table
, nb_clusters
);
2295 /* check OFLAG_COPIED */
2296 ret
= check_oflag_copied(bs
, res
, fix
);
2301 res
->image_end_offset
= (highest_cluster
+ 1) * s
->cluster_size
;
2305 g_free(refcount_table
);
2310 #define overlaps_with(ofs, sz) \
2311 ranges_overlap(offset, size, ofs, sz)
2314 * Checks if the given offset into the image file is actually free to use by
2315 * looking for overlaps with important metadata sections (L1/L2 tables etc.),
2316 * i.e. a sanity check without relying on the refcount tables.
2318 * The ign parameter specifies what checks not to perform (being a bitmask of
2319 * QCow2MetadataOverlap values), i.e., what sections to ignore.
2322 * - 0 if writing to this offset will not affect the mentioned metadata
2323 * - a positive QCow2MetadataOverlap value indicating one overlapping section
2324 * - a negative value (-errno) indicating an error while performing a check,
2325 * e.g. when bdrv_read failed on QCOW2_OL_INACTIVE_L2
2327 int qcow2_check_metadata_overlap(BlockDriverState
*bs
, int ign
, int64_t offset
,
2330 BDRVQcow2State
*s
= bs
->opaque
;
2331 int chk
= s
->overlap_check
& ~ign
;
2338 if (chk
& QCOW2_OL_MAIN_HEADER
) {
2339 if (offset
< s
->cluster_size
) {
2340 return QCOW2_OL_MAIN_HEADER
;
2344 /* align range to test to cluster boundaries */
2345 size
= align_offset(offset_into_cluster(s
, offset
) + size
, s
->cluster_size
);
2346 offset
= start_of_cluster(s
, offset
);
2348 if ((chk
& QCOW2_OL_ACTIVE_L1
) && s
->l1_size
) {
2349 if (overlaps_with(s
->l1_table_offset
, s
->l1_size
* sizeof(uint64_t))) {
2350 return QCOW2_OL_ACTIVE_L1
;
2354 if ((chk
& QCOW2_OL_REFCOUNT_TABLE
) && s
->refcount_table_size
) {
2355 if (overlaps_with(s
->refcount_table_offset
,
2356 s
->refcount_table_size
* sizeof(uint64_t))) {
2357 return QCOW2_OL_REFCOUNT_TABLE
;
2361 if ((chk
& QCOW2_OL_SNAPSHOT_TABLE
) && s
->snapshots_size
) {
2362 if (overlaps_with(s
->snapshots_offset
, s
->snapshots_size
)) {
2363 return QCOW2_OL_SNAPSHOT_TABLE
;
2367 if ((chk
& QCOW2_OL_INACTIVE_L1
) && s
->snapshots
) {
2368 for (i
= 0; i
< s
->nb_snapshots
; i
++) {
2369 if (s
->snapshots
[i
].l1_size
&&
2370 overlaps_with(s
->snapshots
[i
].l1_table_offset
,
2371 s
->snapshots
[i
].l1_size
* sizeof(uint64_t))) {
2372 return QCOW2_OL_INACTIVE_L1
;
2377 if ((chk
& QCOW2_OL_ACTIVE_L2
) && s
->l1_table
) {
2378 for (i
= 0; i
< s
->l1_size
; i
++) {
2379 if ((s
->l1_table
[i
] & L1E_OFFSET_MASK
) &&
2380 overlaps_with(s
->l1_table
[i
] & L1E_OFFSET_MASK
,
2382 return QCOW2_OL_ACTIVE_L2
;
2387 if ((chk
& QCOW2_OL_REFCOUNT_BLOCK
) && s
->refcount_table
) {
2388 for (i
= 0; i
< s
->refcount_table_size
; i
++) {
2389 if ((s
->refcount_table
[i
] & REFT_OFFSET_MASK
) &&
2390 overlaps_with(s
->refcount_table
[i
] & REFT_OFFSET_MASK
,
2392 return QCOW2_OL_REFCOUNT_BLOCK
;
2397 if ((chk
& QCOW2_OL_INACTIVE_L2
) && s
->snapshots
) {
2398 for (i
= 0; i
< s
->nb_snapshots
; i
++) {
2399 uint64_t l1_ofs
= s
->snapshots
[i
].l1_table_offset
;
2400 uint32_t l1_sz
= s
->snapshots
[i
].l1_size
;
2401 uint64_t l1_sz2
= l1_sz
* sizeof(uint64_t);
2402 uint64_t *l1
= g_try_malloc(l1_sz2
);
2405 if (l1_sz2
&& l1
== NULL
) {
2409 ret
= bdrv_pread(bs
->file
, l1_ofs
, l1
, l1_sz2
);
2415 for (j
= 0; j
< l1_sz
; j
++) {
2416 uint64_t l2_ofs
= be64_to_cpu(l1
[j
]) & L1E_OFFSET_MASK
;
2417 if (l2_ofs
&& overlaps_with(l2_ofs
, s
->cluster_size
)) {
2419 return QCOW2_OL_INACTIVE_L2
;
2430 static const char *metadata_ol_names
[] = {
2431 [QCOW2_OL_MAIN_HEADER_BITNR
] = "qcow2_header",
2432 [QCOW2_OL_ACTIVE_L1_BITNR
] = "active L1 table",
2433 [QCOW2_OL_ACTIVE_L2_BITNR
] = "active L2 table",
2434 [QCOW2_OL_REFCOUNT_TABLE_BITNR
] = "refcount table",
2435 [QCOW2_OL_REFCOUNT_BLOCK_BITNR
] = "refcount block",
2436 [QCOW2_OL_SNAPSHOT_TABLE_BITNR
] = "snapshot table",
2437 [QCOW2_OL_INACTIVE_L1_BITNR
] = "inactive L1 table",
2438 [QCOW2_OL_INACTIVE_L2_BITNR
] = "inactive L2 table",
2442 * First performs a check for metadata overlaps (through
2443 * qcow2_check_metadata_overlap); if that fails with a negative value (error
2444 * while performing a check), that value is returned. If an impending overlap
2445 * is detected, the BDS will be made unusable, the qcow2 file marked corrupt
2446 * and -EIO returned.
2448 * Returns 0 if there were neither overlaps nor errors while checking for
2449 * overlaps; or a negative value (-errno) on error.
2451 int qcow2_pre_write_overlap_check(BlockDriverState
*bs
, int ign
, int64_t offset
,
2454 int ret
= qcow2_check_metadata_overlap(bs
, ign
, offset
, size
);
2458 } else if (ret
> 0) {
2459 int metadata_ol_bitnr
= ctz32(ret
);
2460 assert(metadata_ol_bitnr
< QCOW2_OL_MAX_BITNR
);
2462 qcow2_signal_corruption(bs
, true, offset
, size
, "Preventing invalid "
2463 "write on metadata (overlaps with %s)",
2464 metadata_ol_names
[metadata_ol_bitnr
]);
2471 /* A pointer to a function of this type is given to walk_over_reftable(). That
2472 * function will create refblocks and pass them to a RefblockFinishOp once they
2473 * are completed (@refblock). @refblock_empty is set if the refblock is
2476 * Along with the refblock, a corresponding reftable entry is passed, in the
2477 * reftable @reftable (which may be reallocated) at @reftable_index.
2479 * @allocated should be set to true if a new cluster has been allocated.
2481 typedef int (RefblockFinishOp
)(BlockDriverState
*bs
, uint64_t **reftable
,
2482 uint64_t reftable_index
, uint64_t *reftable_size
,
2483 void *refblock
, bool refblock_empty
,
2484 bool *allocated
, Error
**errp
);
2487 * This "operation" for walk_over_reftable() allocates the refblock on disk (if
2488 * it is not empty) and inserts its offset into the new reftable. The size of
2489 * this new reftable is increased as required.
2491 static int alloc_refblock(BlockDriverState
*bs
, uint64_t **reftable
,
2492 uint64_t reftable_index
, uint64_t *reftable_size
,
2493 void *refblock
, bool refblock_empty
, bool *allocated
,
2496 BDRVQcow2State
*s
= bs
->opaque
;
2499 if (!refblock_empty
&& reftable_index
>= *reftable_size
) {
2500 uint64_t *new_reftable
;
2501 uint64_t new_reftable_size
;
2503 new_reftable_size
= ROUND_UP(reftable_index
+ 1,
2504 s
->cluster_size
/ sizeof(uint64_t));
2505 if (new_reftable_size
> QCOW_MAX_REFTABLE_SIZE
/ sizeof(uint64_t)) {
2507 "This operation would make the refcount table grow "
2508 "beyond the maximum size supported by QEMU, aborting");
2512 new_reftable
= g_try_realloc(*reftable
, new_reftable_size
*
2514 if (!new_reftable
) {
2515 error_setg(errp
, "Failed to increase reftable buffer size");
2519 memset(new_reftable
+ *reftable_size
, 0,
2520 (new_reftable_size
- *reftable_size
) * sizeof(uint64_t));
2522 *reftable
= new_reftable
;
2523 *reftable_size
= new_reftable_size
;
2526 if (!refblock_empty
&& !(*reftable
)[reftable_index
]) {
2527 offset
= qcow2_alloc_clusters(bs
, s
->cluster_size
);
2529 error_setg_errno(errp
, -offset
, "Failed to allocate refblock");
2532 (*reftable
)[reftable_index
] = offset
;
2540 * This "operation" for walk_over_reftable() writes the refblock to disk at the
2541 * offset specified by the new reftable's entry. It does not modify the new
2542 * reftable or change any refcounts.
2544 static int flush_refblock(BlockDriverState
*bs
, uint64_t **reftable
,
2545 uint64_t reftable_index
, uint64_t *reftable_size
,
2546 void *refblock
, bool refblock_empty
, bool *allocated
,
2549 BDRVQcow2State
*s
= bs
->opaque
;
2553 if (reftable_index
< *reftable_size
&& (*reftable
)[reftable_index
]) {
2554 offset
= (*reftable
)[reftable_index
];
2556 ret
= qcow2_pre_write_overlap_check(bs
, 0, offset
, s
->cluster_size
);
2558 error_setg_errno(errp
, -ret
, "Overlap check failed");
2562 ret
= bdrv_pwrite(bs
->file
, offset
, refblock
, s
->cluster_size
);
2564 error_setg_errno(errp
, -ret
, "Failed to write refblock");
2568 assert(refblock_empty
);
2575 * This function walks over the existing reftable and every referenced refblock;
2576 * if @new_set_refcount is non-NULL, it is called for every refcount entry to
2577 * create an equal new entry in the passed @new_refblock. Once that
2578 * @new_refblock is completely filled, @operation will be called.
2580 * @status_cb and @cb_opaque are used for the amend operation's status callback.
2581 * @index is the index of the walk_over_reftable() calls and @total is the total
2582 * number of walk_over_reftable() calls per amend operation. Both are used for
2583 * calculating the parameters for the status callback.
2585 * @allocated is set to true if a new cluster has been allocated.
2587 static int walk_over_reftable(BlockDriverState
*bs
, uint64_t **new_reftable
,
2588 uint64_t *new_reftable_index
,
2589 uint64_t *new_reftable_size
,
2590 void *new_refblock
, int new_refblock_size
,
2591 int new_refcount_bits
,
2592 RefblockFinishOp
*operation
, bool *allocated
,
2593 Qcow2SetRefcountFunc
*new_set_refcount
,
2594 BlockDriverAmendStatusCB
*status_cb
,
2595 void *cb_opaque
, int index
, int total
,
2598 BDRVQcow2State
*s
= bs
->opaque
;
2599 uint64_t reftable_index
;
2600 bool new_refblock_empty
= true;
2602 int new_refblock_index
= 0;
2605 for (reftable_index
= 0; reftable_index
< s
->refcount_table_size
;
2608 uint64_t refblock_offset
= s
->refcount_table
[reftable_index
]
2611 status_cb(bs
, (uint64_t)index
* s
->refcount_table_size
+ reftable_index
,
2612 (uint64_t)total
* s
->refcount_table_size
, cb_opaque
);
2614 if (refblock_offset
) {
2617 if (offset_into_cluster(s
, refblock_offset
)) {
2618 qcow2_signal_corruption(bs
, true, -1, -1, "Refblock offset %#"
2619 PRIx64
" unaligned (reftable index: %#"
2620 PRIx64
")", refblock_offset
,
2623 "Image is corrupt (unaligned refblock offset)");
2627 ret
= qcow2_cache_get(bs
, s
->refcount_block_cache
, refblock_offset
,
2630 error_setg_errno(errp
, -ret
, "Failed to retrieve refblock");
2634 for (refblock_index
= 0; refblock_index
< s
->refcount_block_size
;
2639 if (new_refblock_index
>= new_refblock_size
) {
2640 /* new_refblock is now complete */
2641 ret
= operation(bs
, new_reftable
, *new_reftable_index
,
2642 new_reftable_size
, new_refblock
,
2643 new_refblock_empty
, allocated
, errp
);
2645 qcow2_cache_put(bs
, s
->refcount_block_cache
, &refblock
);
2649 (*new_reftable_index
)++;
2650 new_refblock_index
= 0;
2651 new_refblock_empty
= true;
2654 refcount
= s
->get_refcount(refblock
, refblock_index
);
2655 if (new_refcount_bits
< 64 && refcount
>> new_refcount_bits
) {
2658 qcow2_cache_put(bs
, s
->refcount_block_cache
, &refblock
);
2660 offset
= ((reftable_index
<< s
->refcount_block_bits
)
2661 + refblock_index
) << s
->cluster_bits
;
2663 error_setg(errp
, "Cannot decrease refcount entry width to "
2664 "%i bits: Cluster at offset %#" PRIx64
" has a "
2665 "refcount of %" PRIu64
, new_refcount_bits
,
2670 if (new_set_refcount
) {
2671 new_set_refcount(new_refblock
, new_refblock_index
++,
2674 new_refblock_index
++;
2676 new_refblock_empty
= new_refblock_empty
&& refcount
== 0;
2679 qcow2_cache_put(bs
, s
->refcount_block_cache
, &refblock
);
2681 /* No refblock means every refcount is 0 */
2682 for (refblock_index
= 0; refblock_index
< s
->refcount_block_size
;
2685 if (new_refblock_index
>= new_refblock_size
) {
2686 /* new_refblock is now complete */
2687 ret
= operation(bs
, new_reftable
, *new_reftable_index
,
2688 new_reftable_size
, new_refblock
,
2689 new_refblock_empty
, allocated
, errp
);
2694 (*new_reftable_index
)++;
2695 new_refblock_index
= 0;
2696 new_refblock_empty
= true;
2699 if (new_set_refcount
) {
2700 new_set_refcount(new_refblock
, new_refblock_index
++, 0);
2702 new_refblock_index
++;
2708 if (new_refblock_index
> 0) {
2709 /* Complete the potentially existing partially filled final refblock */
2710 if (new_set_refcount
) {
2711 for (; new_refblock_index
< new_refblock_size
;
2712 new_refblock_index
++)
2714 new_set_refcount(new_refblock
, new_refblock_index
, 0);
2718 ret
= operation(bs
, new_reftable
, *new_reftable_index
,
2719 new_reftable_size
, new_refblock
, new_refblock_empty
,
2725 (*new_reftable_index
)++;
2728 status_cb(bs
, (uint64_t)(index
+ 1) * s
->refcount_table_size
,
2729 (uint64_t)total
* s
->refcount_table_size
, cb_opaque
);
2734 int qcow2_change_refcount_order(BlockDriverState
*bs
, int refcount_order
,
2735 BlockDriverAmendStatusCB
*status_cb
,
2736 void *cb_opaque
, Error
**errp
)
2738 BDRVQcow2State
*s
= bs
->opaque
;
2739 Qcow2GetRefcountFunc
*new_get_refcount
;
2740 Qcow2SetRefcountFunc
*new_set_refcount
;
2741 void *new_refblock
= qemu_blockalign(bs
->file
->bs
, s
->cluster_size
);
2742 uint64_t *new_reftable
= NULL
, new_reftable_size
= 0;
2743 uint64_t *old_reftable
, old_reftable_size
, old_reftable_offset
;
2744 uint64_t new_reftable_index
= 0;
2746 int64_t new_reftable_offset
= 0, allocated_reftable_size
= 0;
2747 int new_refblock_size
, new_refcount_bits
= 1 << refcount_order
;
2748 int old_refcount_order
;
2751 bool new_allocation
;
2753 assert(s
->qcow_version
>= 3);
2754 assert(refcount_order
>= 0 && refcount_order
<= 6);
2756 /* see qcow2_open() */
2757 new_refblock_size
= 1 << (s
->cluster_bits
- (refcount_order
- 3));
2759 new_get_refcount
= get_refcount_funcs
[refcount_order
];
2760 new_set_refcount
= set_refcount_funcs
[refcount_order
];
2766 new_allocation
= false;
2768 /* At least we have to do this walk and the one which writes the
2769 * refblocks; also, at least we have to do this loop here at least
2770 * twice (normally), first to do the allocations, and second to
2771 * determine that everything is correctly allocated, this then makes
2772 * three walks in total */
2773 total_walks
= MAX(walk_index
+ 2, 3);
2775 /* First, allocate the structures so they are present in the refcount
2777 ret
= walk_over_reftable(bs
, &new_reftable
, &new_reftable_index
,
2778 &new_reftable_size
, NULL
, new_refblock_size
,
2779 new_refcount_bits
, &alloc_refblock
,
2780 &new_allocation
, NULL
, status_cb
, cb_opaque
,
2781 walk_index
++, total_walks
, errp
);
2786 new_reftable_index
= 0;
2788 if (new_allocation
) {
2789 if (new_reftable_offset
) {
2790 qcow2_free_clusters(bs
, new_reftable_offset
,
2791 allocated_reftable_size
* sizeof(uint64_t),
2792 QCOW2_DISCARD_NEVER
);
2795 new_reftable_offset
= qcow2_alloc_clusters(bs
, new_reftable_size
*
2797 if (new_reftable_offset
< 0) {
2798 error_setg_errno(errp
, -new_reftable_offset
,
2799 "Failed to allocate the new reftable");
2800 ret
= new_reftable_offset
;
2803 allocated_reftable_size
= new_reftable_size
;
2805 } while (new_allocation
);
2807 /* Second, write the new refblocks */
2808 ret
= walk_over_reftable(bs
, &new_reftable
, &new_reftable_index
,
2809 &new_reftable_size
, new_refblock
,
2810 new_refblock_size
, new_refcount_bits
,
2811 &flush_refblock
, &new_allocation
, new_set_refcount
,
2812 status_cb
, cb_opaque
, walk_index
, walk_index
+ 1,
2817 assert(!new_allocation
);
2820 /* Write the new reftable */
2821 ret
= qcow2_pre_write_overlap_check(bs
, 0, new_reftable_offset
,
2822 new_reftable_size
* sizeof(uint64_t));
2824 error_setg_errno(errp
, -ret
, "Overlap check failed");
2828 for (i
= 0; i
< new_reftable_size
; i
++) {
2829 cpu_to_be64s(&new_reftable
[i
]);
2832 ret
= bdrv_pwrite(bs
->file
, new_reftable_offset
, new_reftable
,
2833 new_reftable_size
* sizeof(uint64_t));
2835 for (i
= 0; i
< new_reftable_size
; i
++) {
2836 be64_to_cpus(&new_reftable
[i
]);
2840 error_setg_errno(errp
, -ret
, "Failed to write the new reftable");
2845 /* Empty the refcount cache */
2846 ret
= qcow2_cache_flush(bs
, s
->refcount_block_cache
);
2848 error_setg_errno(errp
, -ret
, "Failed to flush the refblock cache");
2852 /* Update the image header to point to the new reftable; this only updates
2853 * the fields which are relevant to qcow2_update_header(); other fields
2854 * such as s->refcount_table or s->refcount_bits stay stale for now
2855 * (because we have to restore everything if qcow2_update_header() fails) */
2856 old_refcount_order
= s
->refcount_order
;
2857 old_reftable_size
= s
->refcount_table_size
;
2858 old_reftable_offset
= s
->refcount_table_offset
;
2860 s
->refcount_order
= refcount_order
;
2861 s
->refcount_table_size
= new_reftable_size
;
2862 s
->refcount_table_offset
= new_reftable_offset
;
2864 ret
= qcow2_update_header(bs
);
2866 s
->refcount_order
= old_refcount_order
;
2867 s
->refcount_table_size
= old_reftable_size
;
2868 s
->refcount_table_offset
= old_reftable_offset
;
2869 error_setg_errno(errp
, -ret
, "Failed to update the qcow2 header");
2873 /* Now update the rest of the in-memory information */
2874 old_reftable
= s
->refcount_table
;
2875 s
->refcount_table
= new_reftable
;
2877 s
->refcount_bits
= 1 << refcount_order
;
2878 s
->refcount_max
= UINT64_C(1) << (s
->refcount_bits
- 1);
2879 s
->refcount_max
+= s
->refcount_max
- 1;
2881 s
->refcount_block_bits
= s
->cluster_bits
- (refcount_order
- 3);
2882 s
->refcount_block_size
= 1 << s
->refcount_block_bits
;
2884 s
->get_refcount
= new_get_refcount
;
2885 s
->set_refcount
= new_set_refcount
;
2887 /* For cleaning up all old refblocks and the old reftable below the "done"
2889 new_reftable
= old_reftable
;
2890 new_reftable_size
= old_reftable_size
;
2891 new_reftable_offset
= old_reftable_offset
;
2895 /* On success, new_reftable actually points to the old reftable (and
2896 * new_reftable_size is the old reftable's size); but that is just
2898 for (i
= 0; i
< new_reftable_size
; i
++) {
2899 uint64_t offset
= new_reftable
[i
] & REFT_OFFSET_MASK
;
2901 qcow2_free_clusters(bs
, offset
, s
->cluster_size
,
2902 QCOW2_DISCARD_OTHER
);
2905 g_free(new_reftable
);
2907 if (new_reftable_offset
> 0) {
2908 qcow2_free_clusters(bs
, new_reftable_offset
,
2909 new_reftable_size
* sizeof(uint64_t),
2910 QCOW2_DISCARD_OTHER
);
2914 qemu_vfree(new_refblock
);