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"
32 static int64_t alloc_clusters_noref(BlockDriverState
*bs
, uint64_t size
);
33 static int QEMU_WARN_UNUSED_RESULT
update_refcount(BlockDriverState
*bs
,
34 int64_t offset
, int64_t length
, uint64_t addend
,
35 bool decrease
, enum qcow2_discard_type type
);
37 static uint64_t get_refcount_ro0(const void *refcount_array
, uint64_t index
);
38 static uint64_t get_refcount_ro1(const void *refcount_array
, uint64_t index
);
39 static uint64_t get_refcount_ro2(const void *refcount_array
, uint64_t index
);
40 static uint64_t get_refcount_ro3(const void *refcount_array
, uint64_t index
);
41 static uint64_t get_refcount_ro4(const void *refcount_array
, uint64_t index
);
42 static uint64_t get_refcount_ro5(const void *refcount_array
, uint64_t index
);
43 static uint64_t get_refcount_ro6(const void *refcount_array
, uint64_t index
);
45 static void set_refcount_ro0(void *refcount_array
, uint64_t index
,
47 static void set_refcount_ro1(void *refcount_array
, uint64_t index
,
49 static void set_refcount_ro2(void *refcount_array
, uint64_t index
,
51 static void set_refcount_ro3(void *refcount_array
, uint64_t index
,
53 static void set_refcount_ro4(void *refcount_array
, uint64_t index
,
55 static void set_refcount_ro5(void *refcount_array
, uint64_t index
,
57 static void set_refcount_ro6(void *refcount_array
, uint64_t index
,
61 static Qcow2GetRefcountFunc
*const get_refcount_funcs
[] = {
71 static Qcow2SetRefcountFunc
*const set_refcount_funcs
[] = {
82 /*********************************************************/
83 /* refcount handling */
85 int qcow2_refcount_init(BlockDriverState
*bs
)
87 BDRVQcow2State
*s
= bs
->opaque
;
88 unsigned int refcount_table_size2
, i
;
91 assert(s
->refcount_order
>= 0 && s
->refcount_order
<= 6);
93 s
->get_refcount
= get_refcount_funcs
[s
->refcount_order
];
94 s
->set_refcount
= set_refcount_funcs
[s
->refcount_order
];
96 assert(s
->refcount_table_size
<= INT_MAX
/ sizeof(uint64_t));
97 refcount_table_size2
= s
->refcount_table_size
* sizeof(uint64_t);
98 s
->refcount_table
= g_try_malloc(refcount_table_size2
);
100 if (s
->refcount_table_size
> 0) {
101 if (s
->refcount_table
== NULL
) {
105 BLKDBG_EVENT(bs
->file
, BLKDBG_REFTABLE_LOAD
);
106 ret
= bdrv_pread(bs
->file
->bs
, s
->refcount_table_offset
,
107 s
->refcount_table
, refcount_table_size2
);
111 for(i
= 0; i
< s
->refcount_table_size
; i
++)
112 be64_to_cpus(&s
->refcount_table
[i
]);
119 void qcow2_refcount_close(BlockDriverState
*bs
)
121 BDRVQcow2State
*s
= bs
->opaque
;
122 g_free(s
->refcount_table
);
126 static uint64_t get_refcount_ro0(const void *refcount_array
, uint64_t index
)
128 return (((const uint8_t *)refcount_array
)[index
/ 8] >> (index
% 8)) & 0x1;
131 static void set_refcount_ro0(void *refcount_array
, uint64_t index
,
134 assert(!(value
>> 1));
135 ((uint8_t *)refcount_array
)[index
/ 8] &= ~(0x1 << (index
% 8));
136 ((uint8_t *)refcount_array
)[index
/ 8] |= value
<< (index
% 8);
139 static uint64_t get_refcount_ro1(const void *refcount_array
, uint64_t index
)
141 return (((const uint8_t *)refcount_array
)[index
/ 4] >> (2 * (index
% 4)))
145 static void set_refcount_ro1(void *refcount_array
, uint64_t index
,
148 assert(!(value
>> 2));
149 ((uint8_t *)refcount_array
)[index
/ 4] &= ~(0x3 << (2 * (index
% 4)));
150 ((uint8_t *)refcount_array
)[index
/ 4] |= value
<< (2 * (index
% 4));
153 static uint64_t get_refcount_ro2(const void *refcount_array
, uint64_t index
)
155 return (((const uint8_t *)refcount_array
)[index
/ 2] >> (4 * (index
% 2)))
159 static void set_refcount_ro2(void *refcount_array
, uint64_t index
,
162 assert(!(value
>> 4));
163 ((uint8_t *)refcount_array
)[index
/ 2] &= ~(0xf << (4 * (index
% 2)));
164 ((uint8_t *)refcount_array
)[index
/ 2] |= value
<< (4 * (index
% 2));
167 static uint64_t get_refcount_ro3(const void *refcount_array
, uint64_t index
)
169 return ((const uint8_t *)refcount_array
)[index
];
172 static void set_refcount_ro3(void *refcount_array
, uint64_t index
,
175 assert(!(value
>> 8));
176 ((uint8_t *)refcount_array
)[index
] = value
;
179 static uint64_t get_refcount_ro4(const void *refcount_array
, uint64_t index
)
181 return be16_to_cpu(((const uint16_t *)refcount_array
)[index
]);
184 static void set_refcount_ro4(void *refcount_array
, uint64_t index
,
187 assert(!(value
>> 16));
188 ((uint16_t *)refcount_array
)[index
] = cpu_to_be16(value
);
191 static uint64_t get_refcount_ro5(const void *refcount_array
, uint64_t index
)
193 return be32_to_cpu(((const uint32_t *)refcount_array
)[index
]);
196 static void set_refcount_ro5(void *refcount_array
, uint64_t index
,
199 assert(!(value
>> 32));
200 ((uint32_t *)refcount_array
)[index
] = cpu_to_be32(value
);
203 static uint64_t get_refcount_ro6(const void *refcount_array
, uint64_t index
)
205 return be64_to_cpu(((const uint64_t *)refcount_array
)[index
]);
208 static void set_refcount_ro6(void *refcount_array
, uint64_t index
,
211 ((uint64_t *)refcount_array
)[index
] = cpu_to_be64(value
);
215 static int load_refcount_block(BlockDriverState
*bs
,
216 int64_t refcount_block_offset
,
217 void **refcount_block
)
219 BDRVQcow2State
*s
= bs
->opaque
;
222 BLKDBG_EVENT(bs
->file
, BLKDBG_REFBLOCK_LOAD
);
223 ret
= qcow2_cache_get(bs
, s
->refcount_block_cache
, refcount_block_offset
,
230 * Retrieves the refcount of the cluster given by its index and stores it in
231 * *refcount. Returns 0 on success and -errno on failure.
233 int qcow2_get_refcount(BlockDriverState
*bs
, int64_t cluster_index
,
236 BDRVQcow2State
*s
= bs
->opaque
;
237 uint64_t refcount_table_index
, block_index
;
238 int64_t refcount_block_offset
;
240 void *refcount_block
;
242 refcount_table_index
= cluster_index
>> s
->refcount_block_bits
;
243 if (refcount_table_index
>= s
->refcount_table_size
) {
247 refcount_block_offset
=
248 s
->refcount_table
[refcount_table_index
] & REFT_OFFSET_MASK
;
249 if (!refcount_block_offset
) {
254 if (offset_into_cluster(s
, refcount_block_offset
)) {
255 qcow2_signal_corruption(bs
, true, -1, -1, "Refblock offset %#" PRIx64
256 " unaligned (reftable index: %#" PRIx64
")",
257 refcount_block_offset
, refcount_table_index
);
261 ret
= qcow2_cache_get(bs
, s
->refcount_block_cache
, refcount_block_offset
,
267 block_index
= cluster_index
& (s
->refcount_block_size
- 1);
268 *refcount
= s
->get_refcount(refcount_block
, block_index
);
270 qcow2_cache_put(bs
, s
->refcount_block_cache
, &refcount_block
);
276 * Rounds the refcount table size up to avoid growing the table for each single
277 * refcount block that is allocated.
279 static unsigned int next_refcount_table_size(BDRVQcow2State
*s
,
280 unsigned int min_size
)
282 unsigned int min_clusters
= (min_size
>> (s
->cluster_bits
- 3)) + 1;
283 unsigned int refcount_table_clusters
=
284 MAX(1, s
->refcount_table_size
>> (s
->cluster_bits
- 3));
286 while (min_clusters
> refcount_table_clusters
) {
287 refcount_table_clusters
= (refcount_table_clusters
* 3 + 1) / 2;
290 return refcount_table_clusters
<< (s
->cluster_bits
- 3);
294 /* Checks if two offsets are described by the same refcount block */
295 static int in_same_refcount_block(BDRVQcow2State
*s
, uint64_t offset_a
,
298 uint64_t block_a
= offset_a
>> (s
->cluster_bits
+ s
->refcount_block_bits
);
299 uint64_t block_b
= offset_b
>> (s
->cluster_bits
+ s
->refcount_block_bits
);
301 return (block_a
== block_b
);
305 * Loads a refcount block. If it doesn't exist yet, it is allocated first
306 * (including growing the refcount table if needed).
308 * Returns 0 on success or -errno in error case
310 static int alloc_refcount_block(BlockDriverState
*bs
,
311 int64_t cluster_index
, void **refcount_block
)
313 BDRVQcow2State
*s
= bs
->opaque
;
314 unsigned int refcount_table_index
;
317 BLKDBG_EVENT(bs
->file
, BLKDBG_REFBLOCK_ALLOC
);
319 /* Find the refcount block for the given cluster */
320 refcount_table_index
= cluster_index
>> s
->refcount_block_bits
;
322 if (refcount_table_index
< s
->refcount_table_size
) {
324 uint64_t refcount_block_offset
=
325 s
->refcount_table
[refcount_table_index
] & REFT_OFFSET_MASK
;
327 /* If it's already there, we're done */
328 if (refcount_block_offset
) {
329 if (offset_into_cluster(s
, refcount_block_offset
)) {
330 qcow2_signal_corruption(bs
, true, -1, -1, "Refblock offset %#"
331 PRIx64
" unaligned (reftable index: "
332 "%#x)", refcount_block_offset
,
333 refcount_table_index
);
337 return load_refcount_block(bs
, refcount_block_offset
,
343 * If we came here, we need to allocate something. Something is at least
344 * a cluster for the new refcount block. It may also include a new refcount
345 * table if the old refcount table is too small.
347 * Note that allocating clusters here needs some special care:
349 * - We can't use the normal qcow2_alloc_clusters(), it would try to
350 * increase the refcount and very likely we would end up with an endless
351 * recursion. Instead we must place the refcount blocks in a way that
352 * they can describe them themselves.
354 * - We need to consider that at this point we are inside update_refcounts
355 * and potentially doing an initial refcount increase. This means that
356 * some clusters have already been allocated by the caller, but their
357 * refcount isn't accurate yet. If we allocate clusters for metadata, we
358 * need to return -EAGAIN to signal the caller that it needs to restart
359 * the search for free clusters.
361 * - alloc_clusters_noref and qcow2_free_clusters may load a different
362 * refcount block into the cache
365 *refcount_block
= NULL
;
367 /* We write to the refcount table, so we might depend on L2 tables */
368 ret
= qcow2_cache_flush(bs
, s
->l2_table_cache
);
373 /* Allocate the refcount block itself and mark it as used */
374 int64_t new_block
= alloc_clusters_noref(bs
, s
->cluster_size
);
380 fprintf(stderr
, "qcow2: Allocate refcount block %d for %" PRIx64
382 refcount_table_index
, cluster_index
<< s
->cluster_bits
, new_block
);
385 if (in_same_refcount_block(s
, new_block
, cluster_index
<< s
->cluster_bits
)) {
386 /* Zero the new refcount block before updating it */
387 ret
= qcow2_cache_get_empty(bs
, s
->refcount_block_cache
, new_block
,
393 memset(*refcount_block
, 0, s
->cluster_size
);
395 /* The block describes itself, need to update the cache */
396 int block_index
= (new_block
>> s
->cluster_bits
) &
397 (s
->refcount_block_size
- 1);
398 s
->set_refcount(*refcount_block
, block_index
, 1);
400 /* Described somewhere else. This can recurse at most twice before we
401 * arrive at a block that describes itself. */
402 ret
= update_refcount(bs
, new_block
, s
->cluster_size
, 1, false,
403 QCOW2_DISCARD_NEVER
);
408 ret
= qcow2_cache_flush(bs
, s
->refcount_block_cache
);
413 /* Initialize the new refcount block only after updating its refcount,
414 * update_refcount uses the refcount cache itself */
415 ret
= qcow2_cache_get_empty(bs
, s
->refcount_block_cache
, new_block
,
421 memset(*refcount_block
, 0, s
->cluster_size
);
424 /* Now the new refcount block needs to be written to disk */
425 BLKDBG_EVENT(bs
->file
, BLKDBG_REFBLOCK_ALLOC_WRITE
);
426 qcow2_cache_entry_mark_dirty(bs
, s
->refcount_block_cache
, *refcount_block
);
427 ret
= qcow2_cache_flush(bs
, s
->refcount_block_cache
);
432 /* If the refcount table is big enough, just hook the block up there */
433 if (refcount_table_index
< s
->refcount_table_size
) {
434 uint64_t data64
= cpu_to_be64(new_block
);
435 BLKDBG_EVENT(bs
->file
, BLKDBG_REFBLOCK_ALLOC_HOOKUP
);
436 ret
= bdrv_pwrite_sync(bs
->file
->bs
,
437 s
->refcount_table_offset
+ refcount_table_index
* sizeof(uint64_t),
438 &data64
, sizeof(data64
));
443 s
->refcount_table
[refcount_table_index
] = new_block
;
445 /* The new refcount block may be where the caller intended to put its
446 * data, so let it restart the search. */
450 qcow2_cache_put(bs
, s
->refcount_block_cache
, refcount_block
);
453 * If we come here, we need to grow the refcount table. Again, a new
454 * refcount table needs some space and we can't simply allocate to avoid
457 * Therefore let's grab new refcount blocks at the end of the image, which
458 * will describe themselves and the new refcount table. This way we can
459 * reference them only in the new table and do the switch to the new
460 * refcount table at once without producing an inconsistent state in
463 BLKDBG_EVENT(bs
->file
, BLKDBG_REFTABLE_GROW
);
465 /* Calculate the number of refcount blocks needed so far; this will be the
466 * basis for calculating the index of the first cluster used for the
467 * self-describing refcount structures which we are about to create.
469 * Because we reached this point, there cannot be any refcount entries for
470 * cluster_index or higher indices yet. However, because new_block has been
471 * allocated to describe that cluster (and it will assume this role later
472 * on), we cannot use that index; also, new_block may actually have a higher
473 * cluster index than cluster_index, so it needs to be taken into account
474 * here (and 1 needs to be added to its value because that cluster is used).
476 uint64_t blocks_used
= DIV_ROUND_UP(MAX(cluster_index
+ 1,
477 (new_block
>> s
->cluster_bits
) + 1),
478 s
->refcount_block_size
);
480 if (blocks_used
> QCOW_MAX_REFTABLE_SIZE
/ sizeof(uint64_t)) {
484 /* And now we need at least one block more for the new metadata */
485 uint64_t table_size
= next_refcount_table_size(s
, blocks_used
+ 1);
486 uint64_t last_table_size
;
487 uint64_t blocks_clusters
;
489 uint64_t table_clusters
=
490 size_to_clusters(s
, table_size
* sizeof(uint64_t));
491 blocks_clusters
= 1 +
492 ((table_clusters
+ s
->refcount_block_size
- 1)
493 / 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 ((meta_clusters
+ s
->refcount_block_size
- 1)
499 / s
->refcount_block_size
));
501 } while (last_table_size
!= table_size
);
504 fprintf(stderr
, "qcow2: Grow refcount table %" PRId32
" => %" PRId64
"\n",
505 s
->refcount_table_size
, table_size
);
508 /* Create the new refcount table and blocks */
509 uint64_t meta_offset
= (blocks_used
* s
->refcount_block_size
) *
511 uint64_t table_offset
= meta_offset
+ blocks_clusters
* s
->cluster_size
;
512 uint64_t *new_table
= g_try_new0(uint64_t, table_size
);
513 void *new_blocks
= g_try_malloc0(blocks_clusters
* s
->cluster_size
);
515 assert(table_size
> 0 && blocks_clusters
> 0);
516 if (new_table
== NULL
|| new_blocks
== NULL
) {
521 /* Fill the new refcount table */
522 memcpy(new_table
, s
->refcount_table
,
523 s
->refcount_table_size
* sizeof(uint64_t));
524 new_table
[refcount_table_index
] = new_block
;
527 for (i
= 0; i
< blocks_clusters
; i
++) {
528 new_table
[blocks_used
+ i
] = meta_offset
+ (i
* s
->cluster_size
);
531 /* Fill the refcount blocks */
532 uint64_t table_clusters
= size_to_clusters(s
, table_size
* sizeof(uint64_t));
534 for (i
= 0; i
< table_clusters
+ blocks_clusters
; i
++) {
535 s
->set_refcount(new_blocks
, block
++, 1);
538 /* Write refcount blocks to disk */
539 BLKDBG_EVENT(bs
->file
, BLKDBG_REFBLOCK_ALLOC_WRITE_BLOCKS
);
540 ret
= bdrv_pwrite_sync(bs
->file
->bs
, meta_offset
, new_blocks
,
541 blocks_clusters
* s
->cluster_size
);
548 /* Write refcount table to disk */
549 for(i
= 0; i
< table_size
; i
++) {
550 cpu_to_be64s(&new_table
[i
]);
553 BLKDBG_EVENT(bs
->file
, BLKDBG_REFBLOCK_ALLOC_WRITE_TABLE
);
554 ret
= bdrv_pwrite_sync(bs
->file
->bs
, table_offset
, new_table
,
555 table_size
* sizeof(uint64_t));
560 for(i
= 0; i
< table_size
; i
++) {
561 be64_to_cpus(&new_table
[i
]);
564 /* Hook up the new refcount table in the qcow2 header */
569 cpu_to_be64w(&data
.d64
, table_offset
);
570 cpu_to_be32w(&data
.d32
, table_clusters
);
571 BLKDBG_EVENT(bs
->file
, BLKDBG_REFBLOCK_ALLOC_SWITCH_TABLE
);
572 ret
= bdrv_pwrite_sync(bs
->file
->bs
,
573 offsetof(QCowHeader
, refcount_table_offset
),
574 &data
, sizeof(data
));
579 /* And switch it in memory */
580 uint64_t old_table_offset
= s
->refcount_table_offset
;
581 uint64_t old_table_size
= s
->refcount_table_size
;
583 g_free(s
->refcount_table
);
584 s
->refcount_table
= new_table
;
585 s
->refcount_table_size
= table_size
;
586 s
->refcount_table_offset
= table_offset
;
588 /* Free old table. */
589 qcow2_free_clusters(bs
, old_table_offset
, old_table_size
* sizeof(uint64_t),
590 QCOW2_DISCARD_OTHER
);
592 ret
= load_refcount_block(bs
, new_block
, refcount_block
);
597 /* If we were trying to do the initial refcount update for some cluster
598 * allocation, we might have used the same clusters to store newly
599 * allocated metadata. Make the caller search some new space. */
606 if (*refcount_block
!= NULL
) {
607 qcow2_cache_put(bs
, s
->refcount_block_cache
, refcount_block
);
612 void qcow2_process_discards(BlockDriverState
*bs
, int ret
)
614 BDRVQcow2State
*s
= bs
->opaque
;
615 Qcow2DiscardRegion
*d
, *next
;
617 QTAILQ_FOREACH_SAFE(d
, &s
->discards
, next
, next
) {
618 QTAILQ_REMOVE(&s
->discards
, d
, next
);
620 /* Discard is optional, ignore the return value */
622 bdrv_discard(bs
->file
->bs
,
623 d
->offset
>> BDRV_SECTOR_BITS
,
624 d
->bytes
>> BDRV_SECTOR_BITS
);
631 static void update_refcount_discard(BlockDriverState
*bs
,
632 uint64_t offset
, uint64_t length
)
634 BDRVQcow2State
*s
= bs
->opaque
;
635 Qcow2DiscardRegion
*d
, *p
, *next
;
637 QTAILQ_FOREACH(d
, &s
->discards
, next
) {
638 uint64_t new_start
= MIN(offset
, d
->offset
);
639 uint64_t new_end
= MAX(offset
+ length
, d
->offset
+ d
->bytes
);
641 if (new_end
- new_start
<= length
+ d
->bytes
) {
642 /* There can't be any overlap, areas ending up here have no
643 * references any more and therefore shouldn't get freed another
645 assert(d
->bytes
+ length
== new_end
- new_start
);
646 d
->offset
= new_start
;
647 d
->bytes
= new_end
- new_start
;
652 d
= g_malloc(sizeof(*d
));
653 *d
= (Qcow2DiscardRegion
) {
658 QTAILQ_INSERT_TAIL(&s
->discards
, d
, next
);
661 /* Merge discard requests if they are adjacent now */
662 QTAILQ_FOREACH_SAFE(p
, &s
->discards
, next
, next
) {
664 || p
->offset
> d
->offset
+ d
->bytes
665 || d
->offset
> p
->offset
+ p
->bytes
)
670 /* Still no overlap possible */
671 assert(p
->offset
== d
->offset
+ d
->bytes
672 || d
->offset
== p
->offset
+ p
->bytes
);
674 QTAILQ_REMOVE(&s
->discards
, p
, next
);
675 d
->offset
= MIN(d
->offset
, p
->offset
);
676 d
->bytes
+= p
->bytes
;
681 /* XXX: cache several refcount block clusters ? */
682 /* @addend is the absolute value of the addend; if @decrease is set, @addend
683 * will be subtracted from the current refcount, otherwise it will be added */
684 static int QEMU_WARN_UNUSED_RESULT
update_refcount(BlockDriverState
*bs
,
689 enum qcow2_discard_type type
)
691 BDRVQcow2State
*s
= bs
->opaque
;
692 int64_t start
, last
, cluster_offset
;
693 void *refcount_block
= NULL
;
694 int64_t old_table_index
= -1;
698 fprintf(stderr
, "update_refcount: offset=%" PRId64
" size=%" PRId64
699 " addend=%s%" PRIu64
"\n", offset
, length
, decrease
? "-" : "",
704 } else if (length
== 0) {
709 qcow2_cache_set_dependency(bs
, s
->refcount_block_cache
,
713 start
= start_of_cluster(s
, offset
);
714 last
= start_of_cluster(s
, offset
+ length
- 1);
715 for(cluster_offset
= start
; cluster_offset
<= last
;
716 cluster_offset
+= s
->cluster_size
)
720 int64_t cluster_index
= cluster_offset
>> s
->cluster_bits
;
721 int64_t table_index
= cluster_index
>> s
->refcount_block_bits
;
723 /* Load the refcount block and allocate it if needed */
724 if (table_index
!= old_table_index
) {
725 if (refcount_block
) {
726 qcow2_cache_put(bs
, s
->refcount_block_cache
, &refcount_block
);
728 ret
= alloc_refcount_block(bs
, cluster_index
, &refcount_block
);
733 old_table_index
= table_index
;
735 qcow2_cache_entry_mark_dirty(bs
, s
->refcount_block_cache
,
738 /* we can update the count and save it */
739 block_index
= cluster_index
& (s
->refcount_block_size
- 1);
741 refcount
= s
->get_refcount(refcount_block
, block_index
);
742 if (decrease
? (refcount
- addend
> refcount
)
743 : (refcount
+ addend
< refcount
||
744 refcount
+ addend
> s
->refcount_max
))
754 if (refcount
== 0 && cluster_index
< s
->free_cluster_index
) {
755 s
->free_cluster_index
= cluster_index
;
757 s
->set_refcount(refcount_block
, block_index
, refcount
);
759 if (refcount
== 0 && s
->discard_passthrough
[type
]) {
760 update_refcount_discard(bs
, cluster_offset
, s
->cluster_size
);
766 if (!s
->cache_discards
) {
767 qcow2_process_discards(bs
, ret
);
770 /* Write last changed block to disk */
771 if (refcount_block
) {
772 qcow2_cache_put(bs
, s
->refcount_block_cache
, &refcount_block
);
776 * Try do undo any updates if an error is returned (This may succeed in
777 * some cases like ENOSPC for allocating a new refcount block)
781 dummy
= update_refcount(bs
, offset
, cluster_offset
- offset
, addend
,
782 !decrease
, QCOW2_DISCARD_NEVER
);
790 * Increases or decreases the refcount of a given cluster.
792 * @addend is the absolute value of the addend; if @decrease is set, @addend
793 * will be subtracted from the current refcount, otherwise it will be added.
795 * On success 0 is returned; on failure -errno is returned.
797 int qcow2_update_cluster_refcount(BlockDriverState
*bs
,
798 int64_t cluster_index
,
799 uint64_t addend
, bool decrease
,
800 enum qcow2_discard_type type
)
802 BDRVQcow2State
*s
= bs
->opaque
;
805 ret
= update_refcount(bs
, cluster_index
<< s
->cluster_bits
, 1, addend
,
816 /*********************************************************/
817 /* cluster allocation functions */
821 /* return < 0 if error */
822 static int64_t alloc_clusters_noref(BlockDriverState
*bs
, uint64_t size
)
824 BDRVQcow2State
*s
= bs
->opaque
;
825 uint64_t i
, nb_clusters
, refcount
;
828 /* We can't allocate clusters if they may still be queued for discard. */
829 if (s
->cache_discards
) {
830 qcow2_process_discards(bs
, 0);
833 nb_clusters
= size_to_clusters(s
, size
);
835 for(i
= 0; i
< nb_clusters
; i
++) {
836 uint64_t next_cluster_index
= s
->free_cluster_index
++;
837 ret
= qcow2_get_refcount(bs
, next_cluster_index
, &refcount
);
841 } else if (refcount
!= 0) {
846 /* Make sure that all offsets in the "allocated" range are representable
848 if (s
->free_cluster_index
> 0 &&
849 s
->free_cluster_index
- 1 > (INT64_MAX
>> s
->cluster_bits
))
855 fprintf(stderr
, "alloc_clusters: size=%" PRId64
" -> %" PRId64
"\n",
857 (s
->free_cluster_index
- nb_clusters
) << s
->cluster_bits
);
859 return (s
->free_cluster_index
- nb_clusters
) << s
->cluster_bits
;
862 int64_t qcow2_alloc_clusters(BlockDriverState
*bs
, uint64_t size
)
867 BLKDBG_EVENT(bs
->file
, BLKDBG_CLUSTER_ALLOC
);
869 offset
= alloc_clusters_noref(bs
, size
);
874 ret
= update_refcount(bs
, offset
, size
, 1, false, QCOW2_DISCARD_NEVER
);
875 } while (ret
== -EAGAIN
);
884 int64_t qcow2_alloc_clusters_at(BlockDriverState
*bs
, uint64_t offset
,
887 BDRVQcow2State
*s
= bs
->opaque
;
888 uint64_t cluster_index
, refcount
;
892 assert(nb_clusters
>= 0);
893 if (nb_clusters
== 0) {
898 /* Check how many clusters there are free */
899 cluster_index
= offset
>> s
->cluster_bits
;
900 for(i
= 0; i
< nb_clusters
; i
++) {
901 ret
= qcow2_get_refcount(bs
, cluster_index
++, &refcount
);
904 } else if (refcount
!= 0) {
909 /* And then allocate them */
910 ret
= update_refcount(bs
, offset
, i
<< s
->cluster_bits
, 1, false,
911 QCOW2_DISCARD_NEVER
);
912 } while (ret
== -EAGAIN
);
921 /* only used to allocate compressed sectors. We try to allocate
922 contiguous sectors. size must be <= cluster_size */
923 int64_t qcow2_alloc_bytes(BlockDriverState
*bs
, int size
)
925 BDRVQcow2State
*s
= bs
->opaque
;
927 size_t free_in_cluster
;
930 BLKDBG_EVENT(bs
->file
, BLKDBG_CLUSTER_ALLOC_BYTES
);
931 assert(size
> 0 && size
<= s
->cluster_size
);
932 assert(!s
->free_byte_offset
|| offset_into_cluster(s
, s
->free_byte_offset
));
934 offset
= s
->free_byte_offset
;
938 ret
= qcow2_get_refcount(bs
, offset
>> s
->cluster_bits
, &refcount
);
943 if (refcount
== s
->refcount_max
) {
948 free_in_cluster
= s
->cluster_size
- offset_into_cluster(s
, offset
);
950 if (!offset
|| free_in_cluster
< size
) {
951 int64_t new_cluster
= alloc_clusters_noref(bs
, s
->cluster_size
);
952 if (new_cluster
< 0) {
956 if (!offset
|| ROUND_UP(offset
, s
->cluster_size
) != new_cluster
) {
957 offset
= new_cluster
;
958 free_in_cluster
= s
->cluster_size
;
960 free_in_cluster
+= s
->cluster_size
;
965 ret
= update_refcount(bs
, offset
, size
, 1, false, QCOW2_DISCARD_NEVER
);
969 } while (ret
== -EAGAIN
);
974 /* The cluster refcount was incremented; refcount blocks must be flushed
975 * before the caller's L2 table updates. */
976 qcow2_cache_set_dependency(bs
, s
->l2_table_cache
, s
->refcount_block_cache
);
978 s
->free_byte_offset
= offset
+ size
;
979 if (!offset_into_cluster(s
, s
->free_byte_offset
)) {
980 s
->free_byte_offset
= 0;
986 void qcow2_free_clusters(BlockDriverState
*bs
,
987 int64_t offset
, int64_t size
,
988 enum qcow2_discard_type type
)
992 BLKDBG_EVENT(bs
->file
, BLKDBG_CLUSTER_FREE
);
993 ret
= update_refcount(bs
, offset
, size
, 1, true, type
);
995 fprintf(stderr
, "qcow2_free_clusters failed: %s\n", strerror(-ret
));
996 /* TODO Remember the clusters to free them later and avoid leaking */
1001 * Free a cluster using its L2 entry (handles clusters of all types, e.g.
1002 * normal cluster, compressed cluster, etc.)
1004 void qcow2_free_any_clusters(BlockDriverState
*bs
, uint64_t l2_entry
,
1005 int nb_clusters
, enum qcow2_discard_type type
)
1007 BDRVQcow2State
*s
= bs
->opaque
;
1009 switch (qcow2_get_cluster_type(l2_entry
)) {
1010 case QCOW2_CLUSTER_COMPRESSED
:
1013 nb_csectors
= ((l2_entry
>> s
->csize_shift
) &
1015 qcow2_free_clusters(bs
,
1016 (l2_entry
& s
->cluster_offset_mask
) & ~511,
1017 nb_csectors
* 512, type
);
1020 case QCOW2_CLUSTER_NORMAL
:
1021 case QCOW2_CLUSTER_ZERO
:
1022 if (l2_entry
& L2E_OFFSET_MASK
) {
1023 if (offset_into_cluster(s
, l2_entry
& L2E_OFFSET_MASK
)) {
1024 qcow2_signal_corruption(bs
, false, -1, -1,
1025 "Cannot free unaligned cluster %#llx",
1026 l2_entry
& L2E_OFFSET_MASK
);
1028 qcow2_free_clusters(bs
, l2_entry
& L2E_OFFSET_MASK
,
1029 nb_clusters
<< s
->cluster_bits
, type
);
1033 case QCOW2_CLUSTER_UNALLOCATED
:
1042 /*********************************************************/
1043 /* snapshots and image creation */
1047 /* update the refcounts of snapshots and the copied flag */
1048 int qcow2_update_snapshot_refcount(BlockDriverState
*bs
,
1049 int64_t l1_table_offset
, int l1_size
, int addend
)
1051 BDRVQcow2State
*s
= bs
->opaque
;
1052 uint64_t *l1_table
, *l2_table
, l2_offset
, offset
, l1_size2
, refcount
;
1053 bool l1_allocated
= false;
1054 int64_t old_offset
, old_l2_offset
;
1055 int i
, j
, l1_modified
= 0, nb_csectors
;
1058 assert(addend
>= -1 && addend
<= 1);
1062 l1_size2
= l1_size
* sizeof(uint64_t);
1064 s
->cache_discards
= true;
1066 /* WARNING: qcow2_snapshot_goto relies on this function not using the
1067 * l1_table_offset when it is the current s->l1_table_offset! Be careful
1068 * when changing this! */
1069 if (l1_table_offset
!= s
->l1_table_offset
) {
1070 l1_table
= g_try_malloc0(align_offset(l1_size2
, 512));
1071 if (l1_size2
&& l1_table
== NULL
) {
1075 l1_allocated
= true;
1077 ret
= bdrv_pread(bs
->file
->bs
, l1_table_offset
, l1_table
, l1_size2
);
1082 for(i
= 0;i
< l1_size
; i
++)
1083 be64_to_cpus(&l1_table
[i
]);
1085 assert(l1_size
== s
->l1_size
);
1086 l1_table
= s
->l1_table
;
1087 l1_allocated
= false;
1090 for(i
= 0; i
< l1_size
; i
++) {
1091 l2_offset
= l1_table
[i
];
1093 old_l2_offset
= l2_offset
;
1094 l2_offset
&= L1E_OFFSET_MASK
;
1096 if (offset_into_cluster(s
, l2_offset
)) {
1097 qcow2_signal_corruption(bs
, true, -1, -1, "L2 table offset %#"
1098 PRIx64
" unaligned (L1 index: %#x)",
1104 ret
= qcow2_cache_get(bs
, s
->l2_table_cache
, l2_offset
,
1105 (void**) &l2_table
);
1110 for(j
= 0; j
< s
->l2_size
; j
++) {
1111 uint64_t cluster_index
;
1113 offset
= be64_to_cpu(l2_table
[j
]);
1114 old_offset
= offset
;
1115 offset
&= ~QCOW_OFLAG_COPIED
;
1117 switch (qcow2_get_cluster_type(offset
)) {
1118 case QCOW2_CLUSTER_COMPRESSED
:
1119 nb_csectors
= ((offset
>> s
->csize_shift
) &
1122 ret
= update_refcount(bs
,
1123 (offset
& s
->cluster_offset_mask
) & ~511,
1124 nb_csectors
* 512, abs(addend
), addend
< 0,
1125 QCOW2_DISCARD_SNAPSHOT
);
1130 /* compressed clusters are never modified */
1134 case QCOW2_CLUSTER_NORMAL
:
1135 case QCOW2_CLUSTER_ZERO
:
1136 if (offset_into_cluster(s
, offset
& L2E_OFFSET_MASK
)) {
1137 qcow2_signal_corruption(bs
, true, -1, -1, "Data "
1138 "cluster offset %#llx "
1139 "unaligned (L2 offset: %#"
1140 PRIx64
", L2 index: %#x)",
1141 offset
& L2E_OFFSET_MASK
,
1147 cluster_index
= (offset
& L2E_OFFSET_MASK
) >> s
->cluster_bits
;
1148 if (!cluster_index
) {
1154 ret
= qcow2_update_cluster_refcount(bs
,
1155 cluster_index
, abs(addend
), addend
< 0,
1156 QCOW2_DISCARD_SNAPSHOT
);
1162 ret
= qcow2_get_refcount(bs
, cluster_index
, &refcount
);
1168 case QCOW2_CLUSTER_UNALLOCATED
:
1176 if (refcount
== 1) {
1177 offset
|= QCOW_OFLAG_COPIED
;
1179 if (offset
!= old_offset
) {
1181 qcow2_cache_set_dependency(bs
, s
->l2_table_cache
,
1182 s
->refcount_block_cache
);
1184 l2_table
[j
] = cpu_to_be64(offset
);
1185 qcow2_cache_entry_mark_dirty(bs
, s
->l2_table_cache
,
1190 qcow2_cache_put(bs
, s
->l2_table_cache
, (void **) &l2_table
);
1193 ret
= qcow2_update_cluster_refcount(bs
, l2_offset
>>
1195 abs(addend
), addend
< 0,
1196 QCOW2_DISCARD_SNAPSHOT
);
1201 ret
= qcow2_get_refcount(bs
, l2_offset
>> s
->cluster_bits
,
1205 } else if (refcount
== 1) {
1206 l2_offset
|= QCOW_OFLAG_COPIED
;
1208 if (l2_offset
!= old_l2_offset
) {
1209 l1_table
[i
] = l2_offset
;
1215 ret
= bdrv_flush(bs
);
1218 qcow2_cache_put(bs
, s
->l2_table_cache
, (void**) &l2_table
);
1221 s
->cache_discards
= false;
1222 qcow2_process_discards(bs
, ret
);
1224 /* Update L1 only if it isn't deleted anyway (addend = -1) */
1225 if (ret
== 0 && addend
>= 0 && l1_modified
) {
1226 for (i
= 0; i
< l1_size
; i
++) {
1227 cpu_to_be64s(&l1_table
[i
]);
1230 ret
= bdrv_pwrite_sync(bs
->file
->bs
, l1_table_offset
,
1231 l1_table
, l1_size2
);
1233 for (i
= 0; i
< l1_size
; i
++) {
1234 be64_to_cpus(&l1_table
[i
]);
1245 /*********************************************************/
1246 /* refcount checking functions */
1249 static uint64_t refcount_array_byte_size(BDRVQcow2State
*s
, uint64_t entries
)
1251 /* This assertion holds because there is no way we can address more than
1252 * 2^(64 - 9) clusters at once (with cluster size 512 = 2^9, and because
1253 * offsets have to be representable in bytes); due to every cluster
1254 * corresponding to one refcount entry, we are well below that limit */
1255 assert(entries
< (UINT64_C(1) << (64 - 9)));
1257 /* Thanks to the assertion this will not overflow, because
1258 * s->refcount_order < 7.
1259 * (note: x << s->refcount_order == x * s->refcount_bits) */
1260 return DIV_ROUND_UP(entries
<< s
->refcount_order
, 8);
1264 * Reallocates *array so that it can hold new_size entries. *size must contain
1265 * the current number of entries in *array. If the reallocation fails, *array
1266 * and *size will not be modified and -errno will be returned. If the
1267 * reallocation is successful, *array will be set to the new buffer, *size
1268 * will be set to new_size and 0 will be returned. The size of the reallocated
1269 * refcount array buffer will be aligned to a cluster boundary, and the newly
1270 * allocated area will be zeroed.
1272 static int realloc_refcount_array(BDRVQcow2State
*s
, void **array
,
1273 int64_t *size
, int64_t new_size
)
1275 int64_t old_byte_size
, new_byte_size
;
1278 /* Round to clusters so the array can be directly written to disk */
1279 old_byte_size
= size_to_clusters(s
, refcount_array_byte_size(s
, *size
))
1281 new_byte_size
= size_to_clusters(s
, refcount_array_byte_size(s
, new_size
))
1284 if (new_byte_size
== old_byte_size
) {
1289 assert(new_byte_size
> 0);
1291 if (new_byte_size
> SIZE_MAX
) {
1295 new_ptr
= g_try_realloc(*array
, new_byte_size
);
1300 if (new_byte_size
> old_byte_size
) {
1301 memset((char *)new_ptr
+ old_byte_size
, 0,
1302 new_byte_size
- old_byte_size
);
1312 * Increases the refcount for a range of clusters in a given refcount table.
1313 * This is used to construct a temporary refcount table out of L1 and L2 tables
1314 * which can be compared to the refcount table saved in the image.
1316 * Modifies the number of errors in res.
1318 static int inc_refcounts(BlockDriverState
*bs
,
1319 BdrvCheckResult
*res
,
1320 void **refcount_table
,
1321 int64_t *refcount_table_size
,
1322 int64_t offset
, int64_t size
)
1324 BDRVQcow2State
*s
= bs
->opaque
;
1325 uint64_t start
, last
, cluster_offset
, k
, refcount
;
1332 start
= start_of_cluster(s
, offset
);
1333 last
= start_of_cluster(s
, offset
+ size
- 1);
1334 for(cluster_offset
= start
; cluster_offset
<= last
;
1335 cluster_offset
+= s
->cluster_size
) {
1336 k
= cluster_offset
>> s
->cluster_bits
;
1337 if (k
>= *refcount_table_size
) {
1338 ret
= realloc_refcount_array(s
, refcount_table
,
1339 refcount_table_size
, k
+ 1);
1341 res
->check_errors
++;
1346 refcount
= s
->get_refcount(*refcount_table
, k
);
1347 if (refcount
== s
->refcount_max
) {
1348 fprintf(stderr
, "ERROR: overflow cluster offset=0x%" PRIx64
1349 "\n", cluster_offset
);
1350 fprintf(stderr
, "Use qemu-img amend to increase the refcount entry "
1351 "width or qemu-img convert to create a clean copy if the "
1352 "image cannot be opened for writing\n");
1356 s
->set_refcount(*refcount_table
, k
, refcount
+ 1);
1362 /* Flags for check_refcounts_l1() and check_refcounts_l2() */
1364 CHECK_FRAG_INFO
= 0x2, /* update BlockFragInfo counters */
1368 * Increases the refcount in the given refcount table for the all clusters
1369 * referenced in the L2 table. While doing so, performs some checks on L2
1372 * Returns the number of errors found by the checks or -errno if an internal
1375 static int check_refcounts_l2(BlockDriverState
*bs
, BdrvCheckResult
*res
,
1376 void **refcount_table
,
1377 int64_t *refcount_table_size
, int64_t l2_offset
,
1380 BDRVQcow2State
*s
= bs
->opaque
;
1381 uint64_t *l2_table
, l2_entry
;
1382 uint64_t next_contiguous_offset
= 0;
1383 int i
, l2_size
, nb_csectors
, ret
;
1385 /* Read L2 table from disk */
1386 l2_size
= s
->l2_size
* sizeof(uint64_t);
1387 l2_table
= g_malloc(l2_size
);
1389 ret
= bdrv_pread(bs
->file
->bs
, l2_offset
, l2_table
, l2_size
);
1391 fprintf(stderr
, "ERROR: I/O error in check_refcounts_l2\n");
1392 res
->check_errors
++;
1396 /* Do the actual checks */
1397 for(i
= 0; i
< s
->l2_size
; i
++) {
1398 l2_entry
= be64_to_cpu(l2_table
[i
]);
1400 switch (qcow2_get_cluster_type(l2_entry
)) {
1401 case QCOW2_CLUSTER_COMPRESSED
:
1402 /* Compressed clusters don't have QCOW_OFLAG_COPIED */
1403 if (l2_entry
& QCOW_OFLAG_COPIED
) {
1404 fprintf(stderr
, "ERROR: cluster %" PRId64
": "
1405 "copied flag must never be set for compressed "
1406 "clusters\n", l2_entry
>> s
->cluster_bits
);
1407 l2_entry
&= ~QCOW_OFLAG_COPIED
;
1411 /* Mark cluster as used */
1412 nb_csectors
= ((l2_entry
>> s
->csize_shift
) &
1414 l2_entry
&= s
->cluster_offset_mask
;
1415 ret
= inc_refcounts(bs
, res
, refcount_table
, refcount_table_size
,
1416 l2_entry
& ~511, nb_csectors
* 512);
1421 if (flags
& CHECK_FRAG_INFO
) {
1422 res
->bfi
.allocated_clusters
++;
1423 res
->bfi
.compressed_clusters
++;
1425 /* Compressed clusters are fragmented by nature. Since they
1426 * take up sub-sector space but we only have sector granularity
1427 * I/O we need to re-read the same sectors even for adjacent
1428 * compressed clusters.
1430 res
->bfi
.fragmented_clusters
++;
1434 case QCOW2_CLUSTER_ZERO
:
1435 if ((l2_entry
& L2E_OFFSET_MASK
) == 0) {
1440 case QCOW2_CLUSTER_NORMAL
:
1442 uint64_t offset
= l2_entry
& L2E_OFFSET_MASK
;
1444 if (flags
& CHECK_FRAG_INFO
) {
1445 res
->bfi
.allocated_clusters
++;
1446 if (next_contiguous_offset
&&
1447 offset
!= next_contiguous_offset
) {
1448 res
->bfi
.fragmented_clusters
++;
1450 next_contiguous_offset
= offset
+ s
->cluster_size
;
1453 /* Mark cluster as used */
1454 ret
= inc_refcounts(bs
, res
, refcount_table
, refcount_table_size
,
1455 offset
, s
->cluster_size
);
1460 /* Correct offsets are cluster aligned */
1461 if (offset_into_cluster(s
, offset
)) {
1462 fprintf(stderr
, "ERROR offset=%" PRIx64
": Cluster is not "
1463 "properly aligned; L2 entry corrupted.\n", offset
);
1469 case QCOW2_CLUSTER_UNALLOCATED
:
1486 * Increases the refcount for the L1 table, its L2 tables and all referenced
1487 * clusters in the given refcount table. While doing so, performs some checks
1488 * on L1 and L2 entries.
1490 * Returns the number of errors found by the checks or -errno if an internal
1493 static int check_refcounts_l1(BlockDriverState
*bs
,
1494 BdrvCheckResult
*res
,
1495 void **refcount_table
,
1496 int64_t *refcount_table_size
,
1497 int64_t l1_table_offset
, int l1_size
,
1500 BDRVQcow2State
*s
= bs
->opaque
;
1501 uint64_t *l1_table
= NULL
, l2_offset
, l1_size2
;
1504 l1_size2
= l1_size
* sizeof(uint64_t);
1506 /* Mark L1 table as used */
1507 ret
= inc_refcounts(bs
, res
, refcount_table
, refcount_table_size
,
1508 l1_table_offset
, l1_size2
);
1513 /* Read L1 table entries from disk */
1515 l1_table
= g_try_malloc(l1_size2
);
1516 if (l1_table
== NULL
) {
1518 res
->check_errors
++;
1521 ret
= bdrv_pread(bs
->file
->bs
, l1_table_offset
, l1_table
, l1_size2
);
1523 fprintf(stderr
, "ERROR: I/O error in check_refcounts_l1\n");
1524 res
->check_errors
++;
1527 for(i
= 0;i
< l1_size
; i
++)
1528 be64_to_cpus(&l1_table
[i
]);
1531 /* Do the actual checks */
1532 for(i
= 0; i
< l1_size
; i
++) {
1533 l2_offset
= l1_table
[i
];
1535 /* Mark L2 table as used */
1536 l2_offset
&= L1E_OFFSET_MASK
;
1537 ret
= inc_refcounts(bs
, res
, refcount_table
, refcount_table_size
,
1538 l2_offset
, s
->cluster_size
);
1543 /* L2 tables are cluster aligned */
1544 if (offset_into_cluster(s
, l2_offset
)) {
1545 fprintf(stderr
, "ERROR l2_offset=%" PRIx64
": Table is not "
1546 "cluster aligned; L1 entry corrupted\n", l2_offset
);
1550 /* Process and check L2 entries */
1551 ret
= check_refcounts_l2(bs
, res
, refcount_table
,
1552 refcount_table_size
, l2_offset
, flags
);
1567 * Checks the OFLAG_COPIED flag for all L1 and L2 entries.
1569 * This function does not print an error message nor does it increment
1570 * check_errors if qcow2_get_refcount fails (this is because such an error will
1571 * have been already detected and sufficiently signaled by the calling function
1572 * (qcow2_check_refcounts) by the time this function is called).
1574 static int check_oflag_copied(BlockDriverState
*bs
, BdrvCheckResult
*res
,
1577 BDRVQcow2State
*s
= bs
->opaque
;
1578 uint64_t *l2_table
= qemu_blockalign(bs
, s
->cluster_size
);
1583 for (i
= 0; i
< s
->l1_size
; i
++) {
1584 uint64_t l1_entry
= s
->l1_table
[i
];
1585 uint64_t l2_offset
= l1_entry
& L1E_OFFSET_MASK
;
1586 bool l2_dirty
= false;
1592 ret
= qcow2_get_refcount(bs
, l2_offset
>> s
->cluster_bits
,
1595 /* don't print message nor increment check_errors */
1598 if ((refcount
== 1) != ((l1_entry
& QCOW_OFLAG_COPIED
) != 0)) {
1599 fprintf(stderr
, "%s OFLAG_COPIED L2 cluster: l1_index=%d "
1600 "l1_entry=%" PRIx64
" refcount=%" PRIu64
"\n",
1601 fix
& BDRV_FIX_ERRORS
? "Repairing" :
1603 i
, l1_entry
, refcount
);
1604 if (fix
& BDRV_FIX_ERRORS
) {
1605 s
->l1_table
[i
] = refcount
== 1
1606 ? l1_entry
| QCOW_OFLAG_COPIED
1607 : l1_entry
& ~QCOW_OFLAG_COPIED
;
1608 ret
= qcow2_write_l1_entry(bs
, i
);
1610 res
->check_errors
++;
1613 res
->corruptions_fixed
++;
1619 ret
= bdrv_pread(bs
->file
->bs
, l2_offset
, l2_table
,
1620 s
->l2_size
* sizeof(uint64_t));
1622 fprintf(stderr
, "ERROR: Could not read L2 table: %s\n",
1624 res
->check_errors
++;
1628 for (j
= 0; j
< s
->l2_size
; j
++) {
1629 uint64_t l2_entry
= be64_to_cpu(l2_table
[j
]);
1630 uint64_t data_offset
= l2_entry
& L2E_OFFSET_MASK
;
1631 int cluster_type
= qcow2_get_cluster_type(l2_entry
);
1633 if ((cluster_type
== QCOW2_CLUSTER_NORMAL
) ||
1634 ((cluster_type
== QCOW2_CLUSTER_ZERO
) && (data_offset
!= 0))) {
1635 ret
= qcow2_get_refcount(bs
,
1636 data_offset
>> s
->cluster_bits
,
1639 /* don't print message nor increment check_errors */
1642 if ((refcount
== 1) != ((l2_entry
& QCOW_OFLAG_COPIED
) != 0)) {
1643 fprintf(stderr
, "%s OFLAG_COPIED data cluster: "
1644 "l2_entry=%" PRIx64
" refcount=%" PRIu64
"\n",
1645 fix
& BDRV_FIX_ERRORS
? "Repairing" :
1647 l2_entry
, refcount
);
1648 if (fix
& BDRV_FIX_ERRORS
) {
1649 l2_table
[j
] = cpu_to_be64(refcount
== 1
1650 ? l2_entry
| QCOW_OFLAG_COPIED
1651 : l2_entry
& ~QCOW_OFLAG_COPIED
);
1653 res
->corruptions_fixed
++;
1662 ret
= qcow2_pre_write_overlap_check(bs
, QCOW2_OL_ACTIVE_L2
,
1663 l2_offset
, s
->cluster_size
);
1665 fprintf(stderr
, "ERROR: Could not write L2 table; metadata "
1666 "overlap check failed: %s\n", strerror(-ret
));
1667 res
->check_errors
++;
1671 ret
= bdrv_pwrite(bs
->file
->bs
, l2_offset
, l2_table
,
1674 fprintf(stderr
, "ERROR: Could not write L2 table: %s\n",
1676 res
->check_errors
++;
1685 qemu_vfree(l2_table
);
1690 * Checks consistency of refblocks and accounts for each refblock in
1693 static int check_refblocks(BlockDriverState
*bs
, BdrvCheckResult
*res
,
1694 BdrvCheckMode fix
, bool *rebuild
,
1695 void **refcount_table
, int64_t *nb_clusters
)
1697 BDRVQcow2State
*s
= bs
->opaque
;
1701 for(i
= 0; i
< s
->refcount_table_size
; i
++) {
1702 uint64_t offset
, cluster
;
1703 offset
= s
->refcount_table
[i
];
1704 cluster
= offset
>> s
->cluster_bits
;
1706 /* Refcount blocks are cluster aligned */
1707 if (offset_into_cluster(s
, offset
)) {
1708 fprintf(stderr
, "ERROR refcount block %" PRId64
" is not "
1709 "cluster aligned; refcount table entry corrupted\n", i
);
1715 if (cluster
>= *nb_clusters
) {
1716 fprintf(stderr
, "%s refcount block %" PRId64
" is outside image\n",
1717 fix
& BDRV_FIX_ERRORS
? "Repairing" : "ERROR", i
);
1719 if (fix
& BDRV_FIX_ERRORS
) {
1720 int64_t new_nb_clusters
;
1722 if (offset
> INT64_MAX
- s
->cluster_size
) {
1727 ret
= bdrv_truncate(bs
->file
->bs
, offset
+ s
->cluster_size
);
1731 size
= bdrv_getlength(bs
->file
->bs
);
1737 new_nb_clusters
= size_to_clusters(s
, size
);
1738 assert(new_nb_clusters
>= *nb_clusters
);
1740 ret
= realloc_refcount_array(s
, refcount_table
,
1741 nb_clusters
, new_nb_clusters
);
1743 res
->check_errors
++;
1747 if (cluster
>= *nb_clusters
) {
1752 res
->corruptions_fixed
++;
1753 ret
= inc_refcounts(bs
, res
, refcount_table
, nb_clusters
,
1754 offset
, s
->cluster_size
);
1758 /* No need to check whether the refcount is now greater than 1:
1759 * This area was just allocated and zeroed, so it can only be
1760 * exactly 1 after inc_refcounts() */
1766 fprintf(stderr
, "ERROR could not resize image: %s\n",
1775 ret
= inc_refcounts(bs
, res
, refcount_table
, nb_clusters
,
1776 offset
, s
->cluster_size
);
1780 if (s
->get_refcount(*refcount_table
, cluster
) != 1) {
1781 fprintf(stderr
, "ERROR refcount block %" PRId64
1782 " refcount=%" PRIu64
"\n", i
,
1783 s
->get_refcount(*refcount_table
, cluster
));
1794 * Calculates an in-memory refcount table.
1796 static int calculate_refcounts(BlockDriverState
*bs
, BdrvCheckResult
*res
,
1797 BdrvCheckMode fix
, bool *rebuild
,
1798 void **refcount_table
, int64_t *nb_clusters
)
1800 BDRVQcow2State
*s
= bs
->opaque
;
1805 if (!*refcount_table
) {
1806 int64_t old_size
= 0;
1807 ret
= realloc_refcount_array(s
, refcount_table
,
1808 &old_size
, *nb_clusters
);
1810 res
->check_errors
++;
1816 ret
= inc_refcounts(bs
, res
, refcount_table
, nb_clusters
,
1817 0, s
->cluster_size
);
1822 /* current L1 table */
1823 ret
= check_refcounts_l1(bs
, res
, refcount_table
, nb_clusters
,
1824 s
->l1_table_offset
, s
->l1_size
, CHECK_FRAG_INFO
);
1830 for (i
= 0; i
< s
->nb_snapshots
; i
++) {
1831 sn
= s
->snapshots
+ i
;
1832 ret
= check_refcounts_l1(bs
, res
, refcount_table
, nb_clusters
,
1833 sn
->l1_table_offset
, sn
->l1_size
, 0);
1838 ret
= inc_refcounts(bs
, res
, refcount_table
, nb_clusters
,
1839 s
->snapshots_offset
, s
->snapshots_size
);
1845 ret
= inc_refcounts(bs
, res
, refcount_table
, nb_clusters
,
1846 s
->refcount_table_offset
,
1847 s
->refcount_table_size
* sizeof(uint64_t));
1852 return check_refblocks(bs
, res
, fix
, rebuild
, refcount_table
, nb_clusters
);
1856 * Compares the actual reference count for each cluster in the image against the
1857 * refcount as reported by the refcount structures on-disk.
1859 static void compare_refcounts(BlockDriverState
*bs
, BdrvCheckResult
*res
,
1860 BdrvCheckMode fix
, bool *rebuild
,
1861 int64_t *highest_cluster
,
1862 void *refcount_table
, int64_t nb_clusters
)
1864 BDRVQcow2State
*s
= bs
->opaque
;
1866 uint64_t refcount1
, refcount2
;
1869 for (i
= 0, *highest_cluster
= 0; i
< nb_clusters
; i
++) {
1870 ret
= qcow2_get_refcount(bs
, i
, &refcount1
);
1872 fprintf(stderr
, "Can't get refcount for cluster %" PRId64
": %s\n",
1874 res
->check_errors
++;
1878 refcount2
= s
->get_refcount(refcount_table
, i
);
1880 if (refcount1
> 0 || refcount2
> 0) {
1881 *highest_cluster
= i
;
1884 if (refcount1
!= refcount2
) {
1885 /* Check if we're allowed to fix the mismatch */
1886 int *num_fixed
= NULL
;
1887 if (refcount1
== 0) {
1889 } else if (refcount1
> refcount2
&& (fix
& BDRV_FIX_LEAKS
)) {
1890 num_fixed
= &res
->leaks_fixed
;
1891 } else if (refcount1
< refcount2
&& (fix
& BDRV_FIX_ERRORS
)) {
1892 num_fixed
= &res
->corruptions_fixed
;
1895 fprintf(stderr
, "%s cluster %" PRId64
" refcount=%" PRIu64
1896 " reference=%" PRIu64
"\n",
1897 num_fixed
!= NULL
? "Repairing" :
1898 refcount1
< refcount2
? "ERROR" :
1900 i
, refcount1
, refcount2
);
1903 ret
= update_refcount(bs
, i
<< s
->cluster_bits
, 1,
1904 refcount_diff(refcount1
, refcount2
),
1905 refcount1
> refcount2
,
1906 QCOW2_DISCARD_ALWAYS
);
1913 /* And if we couldn't, print an error */
1914 if (refcount1
< refcount2
) {
1924 * Allocates clusters using an in-memory refcount table (IMRT) in contrast to
1925 * the on-disk refcount structures.
1927 * On input, *first_free_cluster tells where to start looking, and need not
1928 * actually be a free cluster; the returned offset will not be before that
1929 * cluster. On output, *first_free_cluster points to the first gap found, even
1930 * if that gap was too small to be used as the returned offset.
1932 * Note that *first_free_cluster is a cluster index whereas the return value is
1935 static int64_t alloc_clusters_imrt(BlockDriverState
*bs
,
1937 void **refcount_table
,
1938 int64_t *imrt_nb_clusters
,
1939 int64_t *first_free_cluster
)
1941 BDRVQcow2State
*s
= bs
->opaque
;
1942 int64_t cluster
= *first_free_cluster
, i
;
1943 bool first_gap
= true;
1944 int contiguous_free_clusters
;
1947 /* Starting at *first_free_cluster, find a range of at least cluster_count
1948 * continuously free clusters */
1949 for (contiguous_free_clusters
= 0;
1950 cluster
< *imrt_nb_clusters
&&
1951 contiguous_free_clusters
< cluster_count
;
1954 if (!s
->get_refcount(*refcount_table
, cluster
)) {
1955 contiguous_free_clusters
++;
1957 /* If this is the first free cluster found, update
1958 * *first_free_cluster accordingly */
1959 *first_free_cluster
= cluster
;
1962 } else if (contiguous_free_clusters
) {
1963 contiguous_free_clusters
= 0;
1967 /* If contiguous_free_clusters is greater than zero, it contains the number
1968 * of continuously free clusters until the current cluster; the first free
1969 * cluster in the current "gap" is therefore
1970 * cluster - contiguous_free_clusters */
1972 /* If no such range could be found, grow the in-memory refcount table
1973 * accordingly to append free clusters at the end of the image */
1974 if (contiguous_free_clusters
< cluster_count
) {
1975 /* contiguous_free_clusters clusters are already empty at the image end;
1976 * we need cluster_count clusters; therefore, we have to allocate
1977 * cluster_count - contiguous_free_clusters new clusters at the end of
1978 * the image (which is the current value of cluster; note that cluster
1979 * may exceed old_imrt_nb_clusters if *first_free_cluster pointed beyond
1981 ret
= realloc_refcount_array(s
, refcount_table
, imrt_nb_clusters
,
1982 cluster
+ cluster_count
1983 - contiguous_free_clusters
);
1989 /* Go back to the first free cluster */
1990 cluster
-= contiguous_free_clusters
;
1991 for (i
= 0; i
< cluster_count
; i
++) {
1992 s
->set_refcount(*refcount_table
, cluster
+ i
, 1);
1995 return cluster
<< s
->cluster_bits
;
1999 * Creates a new refcount structure based solely on the in-memory information
2000 * given through *refcount_table. All necessary allocations will be reflected
2003 * On success, the old refcount structure is leaked (it will be covered by the
2004 * new refcount structure).
2006 static int rebuild_refcount_structure(BlockDriverState
*bs
,
2007 BdrvCheckResult
*res
,
2008 void **refcount_table
,
2009 int64_t *nb_clusters
)
2011 BDRVQcow2State
*s
= bs
->opaque
;
2012 int64_t first_free_cluster
= 0, reftable_offset
= -1, cluster
= 0;
2013 int64_t refblock_offset
, refblock_start
, refblock_index
;
2014 uint32_t reftable_size
= 0;
2015 uint64_t *on_disk_reftable
= NULL
;
2016 void *on_disk_refblock
;
2019 uint64_t reftable_offset
;
2020 uint32_t reftable_clusters
;
2021 } QEMU_PACKED reftable_offset_and_clusters
;
2023 qcow2_cache_empty(bs
, s
->refcount_block_cache
);
2026 for (; cluster
< *nb_clusters
; cluster
++) {
2027 if (!s
->get_refcount(*refcount_table
, cluster
)) {
2031 refblock_index
= cluster
>> s
->refcount_block_bits
;
2032 refblock_start
= refblock_index
<< s
->refcount_block_bits
;
2034 /* Don't allocate a cluster in a refblock already written to disk */
2035 if (first_free_cluster
< refblock_start
) {
2036 first_free_cluster
= refblock_start
;
2038 refblock_offset
= alloc_clusters_imrt(bs
, 1, refcount_table
,
2039 nb_clusters
, &first_free_cluster
);
2040 if (refblock_offset
< 0) {
2041 fprintf(stderr
, "ERROR allocating refblock: %s\n",
2042 strerror(-refblock_offset
));
2043 res
->check_errors
++;
2044 ret
= refblock_offset
;
2048 if (reftable_size
<= refblock_index
) {
2049 uint32_t old_reftable_size
= reftable_size
;
2050 uint64_t *new_on_disk_reftable
;
2052 reftable_size
= ROUND_UP((refblock_index
+ 1) * sizeof(uint64_t),
2053 s
->cluster_size
) / sizeof(uint64_t);
2054 new_on_disk_reftable
= g_try_realloc(on_disk_reftable
,
2057 if (!new_on_disk_reftable
) {
2058 res
->check_errors
++;
2062 on_disk_reftable
= new_on_disk_reftable
;
2064 memset(on_disk_reftable
+ old_reftable_size
, 0,
2065 (reftable_size
- old_reftable_size
) * sizeof(uint64_t));
2067 /* The offset we have for the reftable is now no longer valid;
2068 * this will leak that range, but we can easily fix that by running
2069 * a leak-fixing check after this rebuild operation */
2070 reftable_offset
= -1;
2072 on_disk_reftable
[refblock_index
] = refblock_offset
;
2074 /* If this is apparently the last refblock (for now), try to squeeze the
2076 if (refblock_index
== (*nb_clusters
- 1) >> s
->refcount_block_bits
&&
2077 reftable_offset
< 0)
2079 uint64_t reftable_clusters
= size_to_clusters(s
, reftable_size
*
2081 reftable_offset
= alloc_clusters_imrt(bs
, reftable_clusters
,
2082 refcount_table
, nb_clusters
,
2083 &first_free_cluster
);
2084 if (reftable_offset
< 0) {
2085 fprintf(stderr
, "ERROR allocating reftable: %s\n",
2086 strerror(-reftable_offset
));
2087 res
->check_errors
++;
2088 ret
= reftable_offset
;
2093 ret
= qcow2_pre_write_overlap_check(bs
, 0, refblock_offset
,
2096 fprintf(stderr
, "ERROR writing refblock: %s\n", strerror(-ret
));
2100 /* The size of *refcount_table is always cluster-aligned, therefore the
2101 * write operation will not overflow */
2102 on_disk_refblock
= (void *)((char *) *refcount_table
+
2103 refblock_index
* s
->cluster_size
);
2105 ret
= bdrv_write(bs
->file
->bs
, refblock_offset
/ BDRV_SECTOR_SIZE
,
2106 on_disk_refblock
, s
->cluster_sectors
);
2108 fprintf(stderr
, "ERROR writing refblock: %s\n", strerror(-ret
));
2112 /* Go to the end of this refblock */
2113 cluster
= refblock_start
+ s
->refcount_block_size
- 1;
2116 if (reftable_offset
< 0) {
2117 uint64_t post_refblock_start
, reftable_clusters
;
2119 post_refblock_start
= ROUND_UP(*nb_clusters
, s
->refcount_block_size
);
2120 reftable_clusters
= size_to_clusters(s
,
2121 reftable_size
* sizeof(uint64_t));
2122 /* Not pretty but simple */
2123 if (first_free_cluster
< post_refblock_start
) {
2124 first_free_cluster
= post_refblock_start
;
2126 reftable_offset
= alloc_clusters_imrt(bs
, reftable_clusters
,
2127 refcount_table
, nb_clusters
,
2128 &first_free_cluster
);
2129 if (reftable_offset
< 0) {
2130 fprintf(stderr
, "ERROR allocating reftable: %s\n",
2131 strerror(-reftable_offset
));
2132 res
->check_errors
++;
2133 ret
= reftable_offset
;
2137 goto write_refblocks
;
2140 assert(on_disk_reftable
);
2142 for (refblock_index
= 0; refblock_index
< reftable_size
; refblock_index
++) {
2143 cpu_to_be64s(&on_disk_reftable
[refblock_index
]);
2146 ret
= qcow2_pre_write_overlap_check(bs
, 0, reftable_offset
,
2147 reftable_size
* sizeof(uint64_t));
2149 fprintf(stderr
, "ERROR writing reftable: %s\n", strerror(-ret
));
2153 assert(reftable_size
< INT_MAX
/ sizeof(uint64_t));
2154 ret
= bdrv_pwrite(bs
->file
->bs
, reftable_offset
, on_disk_reftable
,
2155 reftable_size
* sizeof(uint64_t));
2157 fprintf(stderr
, "ERROR writing reftable: %s\n", strerror(-ret
));
2161 /* Enter new reftable into the image header */
2162 cpu_to_be64w(&reftable_offset_and_clusters
.reftable_offset
,
2164 cpu_to_be32w(&reftable_offset_and_clusters
.reftable_clusters
,
2165 size_to_clusters(s
, reftable_size
* sizeof(uint64_t)));
2166 ret
= bdrv_pwrite_sync(bs
->file
->bs
, offsetof(QCowHeader
,
2167 refcount_table_offset
),
2168 &reftable_offset_and_clusters
,
2169 sizeof(reftable_offset_and_clusters
));
2171 fprintf(stderr
, "ERROR setting reftable: %s\n", strerror(-ret
));
2175 for (refblock_index
= 0; refblock_index
< reftable_size
; refblock_index
++) {
2176 be64_to_cpus(&on_disk_reftable
[refblock_index
]);
2178 s
->refcount_table
= on_disk_reftable
;
2179 s
->refcount_table_offset
= reftable_offset
;
2180 s
->refcount_table_size
= reftable_size
;
2185 g_free(on_disk_reftable
);
2190 * Checks an image for refcount consistency.
2192 * Returns 0 if no errors are found, the number of errors in case the image is
2193 * detected as corrupted, and -errno when an internal error occurred.
2195 int qcow2_check_refcounts(BlockDriverState
*bs
, BdrvCheckResult
*res
,
2198 BDRVQcow2State
*s
= bs
->opaque
;
2199 BdrvCheckResult pre_compare_res
;
2200 int64_t size
, highest_cluster
, nb_clusters
;
2201 void *refcount_table
= NULL
;
2202 bool rebuild
= false;
2205 size
= bdrv_getlength(bs
->file
->bs
);
2207 res
->check_errors
++;
2211 nb_clusters
= size_to_clusters(s
, size
);
2212 if (nb_clusters
> INT_MAX
) {
2213 res
->check_errors
++;
2217 res
->bfi
.total_clusters
=
2218 size_to_clusters(s
, bs
->total_sectors
* BDRV_SECTOR_SIZE
);
2220 ret
= calculate_refcounts(bs
, res
, fix
, &rebuild
, &refcount_table
,
2226 /* In case we don't need to rebuild the refcount structure (but want to fix
2227 * something), this function is immediately called again, in which case the
2228 * result should be ignored */
2229 pre_compare_res
= *res
;
2230 compare_refcounts(bs
, res
, 0, &rebuild
, &highest_cluster
, refcount_table
,
2233 if (rebuild
&& (fix
& BDRV_FIX_ERRORS
)) {
2234 BdrvCheckResult old_res
= *res
;
2235 int fresh_leaks
= 0;
2237 fprintf(stderr
, "Rebuilding refcount structure\n");
2238 ret
= rebuild_refcount_structure(bs
, res
, &refcount_table
,
2244 res
->corruptions
= 0;
2247 /* Because the old reftable has been exchanged for a new one the
2248 * references have to be recalculated */
2250 memset(refcount_table
, 0, refcount_array_byte_size(s
, nb_clusters
));
2251 ret
= calculate_refcounts(bs
, res
, 0, &rebuild
, &refcount_table
,
2257 if (fix
& BDRV_FIX_LEAKS
) {
2258 /* The old refcount structures are now leaked, fix it; the result
2259 * can be ignored, aside from leaks which were introduced by
2260 * rebuild_refcount_structure() that could not be fixed */
2261 BdrvCheckResult saved_res
= *res
;
2262 *res
= (BdrvCheckResult
){ 0 };
2264 compare_refcounts(bs
, res
, BDRV_FIX_LEAKS
, &rebuild
,
2265 &highest_cluster
, refcount_table
, nb_clusters
);
2267 fprintf(stderr
, "ERROR rebuilt refcount structure is still "
2271 /* Any leaks accounted for here were introduced by
2272 * rebuild_refcount_structure() because that function has created a
2273 * new refcount structure from scratch */
2274 fresh_leaks
= res
->leaks
;
2278 if (res
->corruptions
< old_res
.corruptions
) {
2279 res
->corruptions_fixed
+= old_res
.corruptions
- res
->corruptions
;
2281 if (res
->leaks
< old_res
.leaks
) {
2282 res
->leaks_fixed
+= old_res
.leaks
- res
->leaks
;
2284 res
->leaks
+= fresh_leaks
;
2287 fprintf(stderr
, "ERROR need to rebuild refcount structures\n");
2288 res
->check_errors
++;
2293 if (res
->leaks
|| res
->corruptions
) {
2294 *res
= pre_compare_res
;
2295 compare_refcounts(bs
, res
, fix
, &rebuild
, &highest_cluster
,
2296 refcount_table
, nb_clusters
);
2300 /* check OFLAG_COPIED */
2301 ret
= check_oflag_copied(bs
, res
, fix
);
2306 res
->image_end_offset
= (highest_cluster
+ 1) * s
->cluster_size
;
2310 g_free(refcount_table
);
2315 #define overlaps_with(ofs, sz) \
2316 ranges_overlap(offset, size, ofs, sz)
2319 * Checks if the given offset into the image file is actually free to use by
2320 * looking for overlaps with important metadata sections (L1/L2 tables etc.),
2321 * i.e. a sanity check without relying on the refcount tables.
2323 * The ign parameter specifies what checks not to perform (being a bitmask of
2324 * QCow2MetadataOverlap values), i.e., what sections to ignore.
2327 * - 0 if writing to this offset will not affect the mentioned metadata
2328 * - a positive QCow2MetadataOverlap value indicating one overlapping section
2329 * - a negative value (-errno) indicating an error while performing a check,
2330 * e.g. when bdrv_read failed on QCOW2_OL_INACTIVE_L2
2332 int qcow2_check_metadata_overlap(BlockDriverState
*bs
, int ign
, int64_t offset
,
2335 BDRVQcow2State
*s
= bs
->opaque
;
2336 int chk
= s
->overlap_check
& ~ign
;
2343 if (chk
& QCOW2_OL_MAIN_HEADER
) {
2344 if (offset
< s
->cluster_size
) {
2345 return QCOW2_OL_MAIN_HEADER
;
2349 /* align range to test to cluster boundaries */
2350 size
= align_offset(offset_into_cluster(s
, offset
) + size
, s
->cluster_size
);
2351 offset
= start_of_cluster(s
, offset
);
2353 if ((chk
& QCOW2_OL_ACTIVE_L1
) && s
->l1_size
) {
2354 if (overlaps_with(s
->l1_table_offset
, s
->l1_size
* sizeof(uint64_t))) {
2355 return QCOW2_OL_ACTIVE_L1
;
2359 if ((chk
& QCOW2_OL_REFCOUNT_TABLE
) && s
->refcount_table_size
) {
2360 if (overlaps_with(s
->refcount_table_offset
,
2361 s
->refcount_table_size
* sizeof(uint64_t))) {
2362 return QCOW2_OL_REFCOUNT_TABLE
;
2366 if ((chk
& QCOW2_OL_SNAPSHOT_TABLE
) && s
->snapshots_size
) {
2367 if (overlaps_with(s
->snapshots_offset
, s
->snapshots_size
)) {
2368 return QCOW2_OL_SNAPSHOT_TABLE
;
2372 if ((chk
& QCOW2_OL_INACTIVE_L1
) && s
->snapshots
) {
2373 for (i
= 0; i
< s
->nb_snapshots
; i
++) {
2374 if (s
->snapshots
[i
].l1_size
&&
2375 overlaps_with(s
->snapshots
[i
].l1_table_offset
,
2376 s
->snapshots
[i
].l1_size
* sizeof(uint64_t))) {
2377 return QCOW2_OL_INACTIVE_L1
;
2382 if ((chk
& QCOW2_OL_ACTIVE_L2
) && s
->l1_table
) {
2383 for (i
= 0; i
< s
->l1_size
; i
++) {
2384 if ((s
->l1_table
[i
] & L1E_OFFSET_MASK
) &&
2385 overlaps_with(s
->l1_table
[i
] & L1E_OFFSET_MASK
,
2387 return QCOW2_OL_ACTIVE_L2
;
2392 if ((chk
& QCOW2_OL_REFCOUNT_BLOCK
) && s
->refcount_table
) {
2393 for (i
= 0; i
< s
->refcount_table_size
; i
++) {
2394 if ((s
->refcount_table
[i
] & REFT_OFFSET_MASK
) &&
2395 overlaps_with(s
->refcount_table
[i
] & REFT_OFFSET_MASK
,
2397 return QCOW2_OL_REFCOUNT_BLOCK
;
2402 if ((chk
& QCOW2_OL_INACTIVE_L2
) && s
->snapshots
) {
2403 for (i
= 0; i
< s
->nb_snapshots
; i
++) {
2404 uint64_t l1_ofs
= s
->snapshots
[i
].l1_table_offset
;
2405 uint32_t l1_sz
= s
->snapshots
[i
].l1_size
;
2406 uint64_t l1_sz2
= l1_sz
* sizeof(uint64_t);
2407 uint64_t *l1
= g_try_malloc(l1_sz2
);
2410 if (l1_sz2
&& l1
== NULL
) {
2414 ret
= bdrv_pread(bs
->file
->bs
, l1_ofs
, l1
, l1_sz2
);
2420 for (j
= 0; j
< l1_sz
; j
++) {
2421 uint64_t l2_ofs
= be64_to_cpu(l1
[j
]) & L1E_OFFSET_MASK
;
2422 if (l2_ofs
&& overlaps_with(l2_ofs
, s
->cluster_size
)) {
2424 return QCOW2_OL_INACTIVE_L2
;
2435 static const char *metadata_ol_names
[] = {
2436 [QCOW2_OL_MAIN_HEADER_BITNR
] = "qcow2_header",
2437 [QCOW2_OL_ACTIVE_L1_BITNR
] = "active L1 table",
2438 [QCOW2_OL_ACTIVE_L2_BITNR
] = "active L2 table",
2439 [QCOW2_OL_REFCOUNT_TABLE_BITNR
] = "refcount table",
2440 [QCOW2_OL_REFCOUNT_BLOCK_BITNR
] = "refcount block",
2441 [QCOW2_OL_SNAPSHOT_TABLE_BITNR
] = "snapshot table",
2442 [QCOW2_OL_INACTIVE_L1_BITNR
] = "inactive L1 table",
2443 [QCOW2_OL_INACTIVE_L2_BITNR
] = "inactive L2 table",
2447 * First performs a check for metadata overlaps (through
2448 * qcow2_check_metadata_overlap); if that fails with a negative value (error
2449 * while performing a check), that value is returned. If an impending overlap
2450 * is detected, the BDS will be made unusable, the qcow2 file marked corrupt
2451 * and -EIO returned.
2453 * Returns 0 if there were neither overlaps nor errors while checking for
2454 * overlaps; or a negative value (-errno) on error.
2456 int qcow2_pre_write_overlap_check(BlockDriverState
*bs
, int ign
, int64_t offset
,
2459 int ret
= qcow2_check_metadata_overlap(bs
, ign
, offset
, size
);
2463 } else if (ret
> 0) {
2464 int metadata_ol_bitnr
= ctz32(ret
);
2465 assert(metadata_ol_bitnr
< QCOW2_OL_MAX_BITNR
);
2467 qcow2_signal_corruption(bs
, true, offset
, size
, "Preventing invalid "
2468 "write on metadata (overlaps with %s)",
2469 metadata_ol_names
[metadata_ol_bitnr
]);
2476 /* A pointer to a function of this type is given to walk_over_reftable(). That
2477 * function will create refblocks and pass them to a RefblockFinishOp once they
2478 * are completed (@refblock). @refblock_empty is set if the refblock is
2481 * Along with the refblock, a corresponding reftable entry is passed, in the
2482 * reftable @reftable (which may be reallocated) at @reftable_index.
2484 * @allocated should be set to true if a new cluster has been allocated.
2486 typedef int (RefblockFinishOp
)(BlockDriverState
*bs
, uint64_t **reftable
,
2487 uint64_t reftable_index
, uint64_t *reftable_size
,
2488 void *refblock
, bool refblock_empty
,
2489 bool *allocated
, Error
**errp
);
2492 * This "operation" for walk_over_reftable() allocates the refblock on disk (if
2493 * it is not empty) and inserts its offset into the new reftable. The size of
2494 * this new reftable is increased as required.
2496 static int alloc_refblock(BlockDriverState
*bs
, uint64_t **reftable
,
2497 uint64_t reftable_index
, uint64_t *reftable_size
,
2498 void *refblock
, bool refblock_empty
, bool *allocated
,
2501 BDRVQcow2State
*s
= bs
->opaque
;
2504 if (!refblock_empty
&& reftable_index
>= *reftable_size
) {
2505 uint64_t *new_reftable
;
2506 uint64_t new_reftable_size
;
2508 new_reftable_size
= ROUND_UP(reftable_index
+ 1,
2509 s
->cluster_size
/ sizeof(uint64_t));
2510 if (new_reftable_size
> QCOW_MAX_REFTABLE_SIZE
/ sizeof(uint64_t)) {
2512 "This operation would make the refcount table grow "
2513 "beyond the maximum size supported by QEMU, aborting");
2517 new_reftable
= g_try_realloc(*reftable
, new_reftable_size
*
2519 if (!new_reftable
) {
2520 error_setg(errp
, "Failed to increase reftable buffer size");
2524 memset(new_reftable
+ *reftable_size
, 0,
2525 (new_reftable_size
- *reftable_size
) * sizeof(uint64_t));
2527 *reftable
= new_reftable
;
2528 *reftable_size
= new_reftable_size
;
2531 if (!refblock_empty
&& !(*reftable
)[reftable_index
]) {
2532 offset
= qcow2_alloc_clusters(bs
, s
->cluster_size
);
2534 error_setg_errno(errp
, -offset
, "Failed to allocate refblock");
2537 (*reftable
)[reftable_index
] = offset
;
2545 * This "operation" for walk_over_reftable() writes the refblock to disk at the
2546 * offset specified by the new reftable's entry. It does not modify the new
2547 * reftable or change any refcounts.
2549 static int flush_refblock(BlockDriverState
*bs
, uint64_t **reftable
,
2550 uint64_t reftable_index
, uint64_t *reftable_size
,
2551 void *refblock
, bool refblock_empty
, bool *allocated
,
2554 BDRVQcow2State
*s
= bs
->opaque
;
2558 if (reftable_index
< *reftable_size
&& (*reftable
)[reftable_index
]) {
2559 offset
= (*reftable
)[reftable_index
];
2561 ret
= qcow2_pre_write_overlap_check(bs
, 0, offset
, s
->cluster_size
);
2563 error_setg_errno(errp
, -ret
, "Overlap check failed");
2567 ret
= bdrv_pwrite(bs
->file
->bs
, offset
, refblock
, s
->cluster_size
);
2569 error_setg_errno(errp
, -ret
, "Failed to write refblock");
2573 assert(refblock_empty
);
2580 * This function walks over the existing reftable and every referenced refblock;
2581 * if @new_set_refcount is non-NULL, it is called for every refcount entry to
2582 * create an equal new entry in the passed @new_refblock. Once that
2583 * @new_refblock is completely filled, @operation will be called.
2585 * @status_cb and @cb_opaque are used for the amend operation's status callback.
2586 * @index is the index of the walk_over_reftable() calls and @total is the total
2587 * number of walk_over_reftable() calls per amend operation. Both are used for
2588 * calculating the parameters for the status callback.
2590 * @allocated is set to true if a new cluster has been allocated.
2592 static int walk_over_reftable(BlockDriverState
*bs
, uint64_t **new_reftable
,
2593 uint64_t *new_reftable_index
,
2594 uint64_t *new_reftable_size
,
2595 void *new_refblock
, int new_refblock_size
,
2596 int new_refcount_bits
,
2597 RefblockFinishOp
*operation
, bool *allocated
,
2598 Qcow2SetRefcountFunc
*new_set_refcount
,
2599 BlockDriverAmendStatusCB
*status_cb
,
2600 void *cb_opaque
, int index
, int total
,
2603 BDRVQcow2State
*s
= bs
->opaque
;
2604 uint64_t reftable_index
;
2605 bool new_refblock_empty
= true;
2607 int new_refblock_index
= 0;
2610 for (reftable_index
= 0; reftable_index
< s
->refcount_table_size
;
2613 uint64_t refblock_offset
= s
->refcount_table
[reftable_index
]
2616 status_cb(bs
, (uint64_t)index
* s
->refcount_table_size
+ reftable_index
,
2617 (uint64_t)total
* s
->refcount_table_size
, cb_opaque
);
2619 if (refblock_offset
) {
2622 if (offset_into_cluster(s
, refblock_offset
)) {
2623 qcow2_signal_corruption(bs
, true, -1, -1, "Refblock offset %#"
2624 PRIx64
" unaligned (reftable index: %#"
2625 PRIx64
")", refblock_offset
,
2628 "Image is corrupt (unaligned refblock offset)");
2632 ret
= qcow2_cache_get(bs
, s
->refcount_block_cache
, refblock_offset
,
2635 error_setg_errno(errp
, -ret
, "Failed to retrieve refblock");
2639 for (refblock_index
= 0; refblock_index
< s
->refcount_block_size
;
2644 if (new_refblock_index
>= new_refblock_size
) {
2645 /* new_refblock is now complete */
2646 ret
= operation(bs
, new_reftable
, *new_reftable_index
,
2647 new_reftable_size
, new_refblock
,
2648 new_refblock_empty
, allocated
, errp
);
2650 qcow2_cache_put(bs
, s
->refcount_block_cache
, &refblock
);
2654 (*new_reftable_index
)++;
2655 new_refblock_index
= 0;
2656 new_refblock_empty
= true;
2659 refcount
= s
->get_refcount(refblock
, refblock_index
);
2660 if (new_refcount_bits
< 64 && refcount
>> new_refcount_bits
) {
2663 qcow2_cache_put(bs
, s
->refcount_block_cache
, &refblock
);
2665 offset
= ((reftable_index
<< s
->refcount_block_bits
)
2666 + refblock_index
) << s
->cluster_bits
;
2668 error_setg(errp
, "Cannot decrease refcount entry width to "
2669 "%i bits: Cluster at offset %#" PRIx64
" has a "
2670 "refcount of %" PRIu64
, new_refcount_bits
,
2675 if (new_set_refcount
) {
2676 new_set_refcount(new_refblock
, new_refblock_index
++,
2679 new_refblock_index
++;
2681 new_refblock_empty
= new_refblock_empty
&& refcount
== 0;
2684 qcow2_cache_put(bs
, s
->refcount_block_cache
, &refblock
);
2686 /* No refblock means every refcount is 0 */
2687 for (refblock_index
= 0; refblock_index
< s
->refcount_block_size
;
2690 if (new_refblock_index
>= new_refblock_size
) {
2691 /* new_refblock is now complete */
2692 ret
= operation(bs
, new_reftable
, *new_reftable_index
,
2693 new_reftable_size
, new_refblock
,
2694 new_refblock_empty
, allocated
, errp
);
2699 (*new_reftable_index
)++;
2700 new_refblock_index
= 0;
2701 new_refblock_empty
= true;
2704 if (new_set_refcount
) {
2705 new_set_refcount(new_refblock
, new_refblock_index
++, 0);
2707 new_refblock_index
++;
2713 if (new_refblock_index
> 0) {
2714 /* Complete the potentially existing partially filled final refblock */
2715 if (new_set_refcount
) {
2716 for (; new_refblock_index
< new_refblock_size
;
2717 new_refblock_index
++)
2719 new_set_refcount(new_refblock
, new_refblock_index
, 0);
2723 ret
= operation(bs
, new_reftable
, *new_reftable_index
,
2724 new_reftable_size
, new_refblock
, new_refblock_empty
,
2730 (*new_reftable_index
)++;
2733 status_cb(bs
, (uint64_t)(index
+ 1) * s
->refcount_table_size
,
2734 (uint64_t)total
* s
->refcount_table_size
, cb_opaque
);
2739 int qcow2_change_refcount_order(BlockDriverState
*bs
, int refcount_order
,
2740 BlockDriverAmendStatusCB
*status_cb
,
2741 void *cb_opaque
, Error
**errp
)
2743 BDRVQcow2State
*s
= bs
->opaque
;
2744 Qcow2GetRefcountFunc
*new_get_refcount
;
2745 Qcow2SetRefcountFunc
*new_set_refcount
;
2746 void *new_refblock
= qemu_blockalign(bs
->file
->bs
, s
->cluster_size
);
2747 uint64_t *new_reftable
= NULL
, new_reftable_size
= 0;
2748 uint64_t *old_reftable
, old_reftable_size
, old_reftable_offset
;
2749 uint64_t new_reftable_index
= 0;
2751 int64_t new_reftable_offset
= 0, allocated_reftable_size
= 0;
2752 int new_refblock_size
, new_refcount_bits
= 1 << refcount_order
;
2753 int old_refcount_order
;
2756 bool new_allocation
;
2758 assert(s
->qcow_version
>= 3);
2759 assert(refcount_order
>= 0 && refcount_order
<= 6);
2761 /* see qcow2_open() */
2762 new_refblock_size
= 1 << (s
->cluster_bits
- (refcount_order
- 3));
2764 new_get_refcount
= get_refcount_funcs
[refcount_order
];
2765 new_set_refcount
= set_refcount_funcs
[refcount_order
];
2771 new_allocation
= false;
2773 /* At least we have to do this walk and the one which writes the
2774 * refblocks; also, at least we have to do this loop here at least
2775 * twice (normally), first to do the allocations, and second to
2776 * determine that everything is correctly allocated, this then makes
2777 * three walks in total */
2778 total_walks
= MAX(walk_index
+ 2, 3);
2780 /* First, allocate the structures so they are present in the refcount
2782 ret
= walk_over_reftable(bs
, &new_reftable
, &new_reftable_index
,
2783 &new_reftable_size
, NULL
, new_refblock_size
,
2784 new_refcount_bits
, &alloc_refblock
,
2785 &new_allocation
, NULL
, status_cb
, cb_opaque
,
2786 walk_index
++, total_walks
, errp
);
2791 new_reftable_index
= 0;
2793 if (new_allocation
) {
2794 if (new_reftable_offset
) {
2795 qcow2_free_clusters(bs
, new_reftable_offset
,
2796 allocated_reftable_size
* sizeof(uint64_t),
2797 QCOW2_DISCARD_NEVER
);
2800 new_reftable_offset
= qcow2_alloc_clusters(bs
, new_reftable_size
*
2802 if (new_reftable_offset
< 0) {
2803 error_setg_errno(errp
, -new_reftable_offset
,
2804 "Failed to allocate the new reftable");
2805 ret
= new_reftable_offset
;
2808 allocated_reftable_size
= new_reftable_size
;
2810 } while (new_allocation
);
2812 /* Second, write the new refblocks */
2813 ret
= walk_over_reftable(bs
, &new_reftable
, &new_reftable_index
,
2814 &new_reftable_size
, new_refblock
,
2815 new_refblock_size
, new_refcount_bits
,
2816 &flush_refblock
, &new_allocation
, new_set_refcount
,
2817 status_cb
, cb_opaque
, walk_index
, walk_index
+ 1,
2822 assert(!new_allocation
);
2825 /* Write the new reftable */
2826 ret
= qcow2_pre_write_overlap_check(bs
, 0, new_reftable_offset
,
2827 new_reftable_size
* sizeof(uint64_t));
2829 error_setg_errno(errp
, -ret
, "Overlap check failed");
2833 for (i
= 0; i
< new_reftable_size
; i
++) {
2834 cpu_to_be64s(&new_reftable
[i
]);
2837 ret
= bdrv_pwrite(bs
->file
->bs
, new_reftable_offset
, new_reftable
,
2838 new_reftable_size
* sizeof(uint64_t));
2840 for (i
= 0; i
< new_reftable_size
; i
++) {
2841 be64_to_cpus(&new_reftable
[i
]);
2845 error_setg_errno(errp
, -ret
, "Failed to write the new reftable");
2850 /* Empty the refcount cache */
2851 ret
= qcow2_cache_flush(bs
, s
->refcount_block_cache
);
2853 error_setg_errno(errp
, -ret
, "Failed to flush the refblock cache");
2857 /* Update the image header to point to the new reftable; this only updates
2858 * the fields which are relevant to qcow2_update_header(); other fields
2859 * such as s->refcount_table or s->refcount_bits stay stale for now
2860 * (because we have to restore everything if qcow2_update_header() fails) */
2861 old_refcount_order
= s
->refcount_order
;
2862 old_reftable_size
= s
->refcount_table_size
;
2863 old_reftable_offset
= s
->refcount_table_offset
;
2865 s
->refcount_order
= refcount_order
;
2866 s
->refcount_table_size
= new_reftable_size
;
2867 s
->refcount_table_offset
= new_reftable_offset
;
2869 ret
= qcow2_update_header(bs
);
2871 s
->refcount_order
= old_refcount_order
;
2872 s
->refcount_table_size
= old_reftable_size
;
2873 s
->refcount_table_offset
= old_reftable_offset
;
2874 error_setg_errno(errp
, -ret
, "Failed to update the qcow2 header");
2878 /* Now update the rest of the in-memory information */
2879 old_reftable
= s
->refcount_table
;
2880 s
->refcount_table
= new_reftable
;
2882 s
->refcount_bits
= 1 << refcount_order
;
2883 s
->refcount_max
= UINT64_C(1) << (s
->refcount_bits
- 1);
2884 s
->refcount_max
+= s
->refcount_max
- 1;
2886 s
->refcount_block_bits
= s
->cluster_bits
- (refcount_order
- 3);
2887 s
->refcount_block_size
= 1 << s
->refcount_block_bits
;
2889 s
->get_refcount
= new_get_refcount
;
2890 s
->set_refcount
= new_set_refcount
;
2892 /* For cleaning up all old refblocks and the old reftable below the "done"
2894 new_reftable
= old_reftable
;
2895 new_reftable_size
= old_reftable_size
;
2896 new_reftable_offset
= old_reftable_offset
;
2900 /* On success, new_reftable actually points to the old reftable (and
2901 * new_reftable_size is the old reftable's size); but that is just
2903 for (i
= 0; i
< new_reftable_size
; i
++) {
2904 uint64_t offset
= new_reftable
[i
] & REFT_OFFSET_MASK
;
2906 qcow2_free_clusters(bs
, offset
, s
->cluster_size
,
2907 QCOW2_DISCARD_OTHER
);
2910 g_free(new_reftable
);
2912 if (new_reftable_offset
> 0) {
2913 qcow2_free_clusters(bs
, new_reftable_offset
,
2914 new_reftable_size
* sizeof(uint64_t),
2915 QCOW2_DISCARD_OTHER
);
2919 qemu_vfree(new_refblock
);