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"
29 #include "qemu/range.h"
30 #include "qemu/bswap.h"
31 #include "qemu/cutils.h"
33 static int64_t alloc_clusters_noref(BlockDriverState
*bs
, uint64_t size
,
35 static int QEMU_WARN_UNUSED_RESULT
update_refcount(BlockDriverState
*bs
,
36 int64_t offset
, int64_t length
, uint64_t addend
,
37 bool decrease
, enum qcow2_discard_type type
);
39 static uint64_t get_refcount_ro0(const void *refcount_array
, uint64_t index
);
40 static uint64_t get_refcount_ro1(const void *refcount_array
, uint64_t index
);
41 static uint64_t get_refcount_ro2(const void *refcount_array
, uint64_t index
);
42 static uint64_t get_refcount_ro3(const void *refcount_array
, uint64_t index
);
43 static uint64_t get_refcount_ro4(const void *refcount_array
, uint64_t index
);
44 static uint64_t get_refcount_ro5(const void *refcount_array
, uint64_t index
);
45 static uint64_t get_refcount_ro6(const void *refcount_array
, uint64_t index
);
47 static void set_refcount_ro0(void *refcount_array
, uint64_t index
,
49 static void set_refcount_ro1(void *refcount_array
, uint64_t index
,
51 static void set_refcount_ro2(void *refcount_array
, uint64_t index
,
53 static void set_refcount_ro3(void *refcount_array
, uint64_t index
,
55 static void set_refcount_ro4(void *refcount_array
, uint64_t index
,
57 static void set_refcount_ro5(void *refcount_array
, uint64_t index
,
59 static void set_refcount_ro6(void *refcount_array
, uint64_t index
,
63 static Qcow2GetRefcountFunc
*const get_refcount_funcs
[] = {
73 static Qcow2SetRefcountFunc
*const set_refcount_funcs
[] = {
84 /*********************************************************/
85 /* refcount handling */
87 static void update_max_refcount_table_index(BDRVQcow2State
*s
)
89 unsigned i
= s
->refcount_table_size
- 1;
90 while (i
> 0 && (s
->refcount_table
[i
] & REFT_OFFSET_MASK
) == 0) {
93 /* Set s->max_refcount_table_index to the index of the last used entry */
94 s
->max_refcount_table_index
= i
;
97 int qcow2_refcount_init(BlockDriverState
*bs
)
99 BDRVQcow2State
*s
= bs
->opaque
;
100 unsigned int refcount_table_size2
, i
;
103 assert(s
->refcount_order
>= 0 && s
->refcount_order
<= 6);
105 s
->get_refcount
= get_refcount_funcs
[s
->refcount_order
];
106 s
->set_refcount
= set_refcount_funcs
[s
->refcount_order
];
108 assert(s
->refcount_table_size
<= INT_MAX
/ sizeof(uint64_t));
109 refcount_table_size2
= s
->refcount_table_size
* sizeof(uint64_t);
110 s
->refcount_table
= g_try_malloc(refcount_table_size2
);
112 if (s
->refcount_table_size
> 0) {
113 if (s
->refcount_table
== NULL
) {
117 BLKDBG_EVENT(bs
->file
, BLKDBG_REFTABLE_LOAD
);
118 ret
= bdrv_pread(bs
->file
, s
->refcount_table_offset
,
119 s
->refcount_table
, refcount_table_size2
);
123 for(i
= 0; i
< s
->refcount_table_size
; i
++)
124 be64_to_cpus(&s
->refcount_table
[i
]);
125 update_max_refcount_table_index(s
);
132 void qcow2_refcount_close(BlockDriverState
*bs
)
134 BDRVQcow2State
*s
= bs
->opaque
;
135 g_free(s
->refcount_table
);
139 static uint64_t get_refcount_ro0(const void *refcount_array
, uint64_t index
)
141 return (((const uint8_t *)refcount_array
)[index
/ 8] >> (index
% 8)) & 0x1;
144 static void set_refcount_ro0(void *refcount_array
, uint64_t index
,
147 assert(!(value
>> 1));
148 ((uint8_t *)refcount_array
)[index
/ 8] &= ~(0x1 << (index
% 8));
149 ((uint8_t *)refcount_array
)[index
/ 8] |= value
<< (index
% 8);
152 static uint64_t get_refcount_ro1(const void *refcount_array
, uint64_t index
)
154 return (((const uint8_t *)refcount_array
)[index
/ 4] >> (2 * (index
% 4)))
158 static void set_refcount_ro1(void *refcount_array
, uint64_t index
,
161 assert(!(value
>> 2));
162 ((uint8_t *)refcount_array
)[index
/ 4] &= ~(0x3 << (2 * (index
% 4)));
163 ((uint8_t *)refcount_array
)[index
/ 4] |= value
<< (2 * (index
% 4));
166 static uint64_t get_refcount_ro2(const void *refcount_array
, uint64_t index
)
168 return (((const uint8_t *)refcount_array
)[index
/ 2] >> (4 * (index
% 2)))
172 static void set_refcount_ro2(void *refcount_array
, uint64_t index
,
175 assert(!(value
>> 4));
176 ((uint8_t *)refcount_array
)[index
/ 2] &= ~(0xf << (4 * (index
% 2)));
177 ((uint8_t *)refcount_array
)[index
/ 2] |= value
<< (4 * (index
% 2));
180 static uint64_t get_refcount_ro3(const void *refcount_array
, uint64_t index
)
182 return ((const uint8_t *)refcount_array
)[index
];
185 static void set_refcount_ro3(void *refcount_array
, uint64_t index
,
188 assert(!(value
>> 8));
189 ((uint8_t *)refcount_array
)[index
] = value
;
192 static uint64_t get_refcount_ro4(const void *refcount_array
, uint64_t index
)
194 return be16_to_cpu(((const uint16_t *)refcount_array
)[index
]);
197 static void set_refcount_ro4(void *refcount_array
, uint64_t index
,
200 assert(!(value
>> 16));
201 ((uint16_t *)refcount_array
)[index
] = cpu_to_be16(value
);
204 static uint64_t get_refcount_ro5(const void *refcount_array
, uint64_t index
)
206 return be32_to_cpu(((const uint32_t *)refcount_array
)[index
]);
209 static void set_refcount_ro5(void *refcount_array
, uint64_t index
,
212 assert(!(value
>> 32));
213 ((uint32_t *)refcount_array
)[index
] = cpu_to_be32(value
);
216 static uint64_t get_refcount_ro6(const void *refcount_array
, uint64_t index
)
218 return be64_to_cpu(((const uint64_t *)refcount_array
)[index
]);
221 static void set_refcount_ro6(void *refcount_array
, uint64_t index
,
224 ((uint64_t *)refcount_array
)[index
] = cpu_to_be64(value
);
228 static int load_refcount_block(BlockDriverState
*bs
,
229 int64_t refcount_block_offset
,
230 void **refcount_block
)
232 BDRVQcow2State
*s
= bs
->opaque
;
234 BLKDBG_EVENT(bs
->file
, BLKDBG_REFBLOCK_LOAD
);
235 return qcow2_cache_get(bs
, s
->refcount_block_cache
, refcount_block_offset
,
240 * Retrieves the refcount of the cluster given by its index and stores it in
241 * *refcount. Returns 0 on success and -errno on failure.
243 int qcow2_get_refcount(BlockDriverState
*bs
, int64_t cluster_index
,
246 BDRVQcow2State
*s
= bs
->opaque
;
247 uint64_t refcount_table_index
, block_index
;
248 int64_t refcount_block_offset
;
250 void *refcount_block
;
252 refcount_table_index
= cluster_index
>> s
->refcount_block_bits
;
253 if (refcount_table_index
>= s
->refcount_table_size
) {
257 refcount_block_offset
=
258 s
->refcount_table
[refcount_table_index
] & REFT_OFFSET_MASK
;
259 if (!refcount_block_offset
) {
264 if (offset_into_cluster(s
, refcount_block_offset
)) {
265 qcow2_signal_corruption(bs
, true, -1, -1, "Refblock offset %#" PRIx64
266 " unaligned (reftable index: %#" PRIx64
")",
267 refcount_block_offset
, refcount_table_index
);
271 ret
= qcow2_cache_get(bs
, s
->refcount_block_cache
, refcount_block_offset
,
277 block_index
= cluster_index
& (s
->refcount_block_size
- 1);
278 *refcount
= s
->get_refcount(refcount_block
, block_index
);
280 qcow2_cache_put(s
->refcount_block_cache
, &refcount_block
);
285 /* Checks if two offsets are described by the same refcount block */
286 static int in_same_refcount_block(BDRVQcow2State
*s
, uint64_t offset_a
,
289 uint64_t block_a
= offset_a
>> (s
->cluster_bits
+ s
->refcount_block_bits
);
290 uint64_t block_b
= offset_b
>> (s
->cluster_bits
+ s
->refcount_block_bits
);
292 return (block_a
== block_b
);
296 * Loads a refcount block. If it doesn't exist yet, it is allocated first
297 * (including growing the refcount table if needed).
299 * Returns 0 on success or -errno in error case
301 static int alloc_refcount_block(BlockDriverState
*bs
,
302 int64_t cluster_index
, void **refcount_block
)
304 BDRVQcow2State
*s
= bs
->opaque
;
305 unsigned int refcount_table_index
;
308 BLKDBG_EVENT(bs
->file
, BLKDBG_REFBLOCK_ALLOC
);
310 /* Find the refcount block for the given cluster */
311 refcount_table_index
= cluster_index
>> s
->refcount_block_bits
;
313 if (refcount_table_index
< s
->refcount_table_size
) {
315 uint64_t refcount_block_offset
=
316 s
->refcount_table
[refcount_table_index
] & REFT_OFFSET_MASK
;
318 /* If it's already there, we're done */
319 if (refcount_block_offset
) {
320 if (offset_into_cluster(s
, refcount_block_offset
)) {
321 qcow2_signal_corruption(bs
, true, -1, -1, "Refblock offset %#"
322 PRIx64
" unaligned (reftable index: "
323 "%#x)", refcount_block_offset
,
324 refcount_table_index
);
328 return load_refcount_block(bs
, refcount_block_offset
,
334 * If we came here, we need to allocate something. Something is at least
335 * a cluster for the new refcount block. It may also include a new refcount
336 * table if the old refcount table is too small.
338 * Note that allocating clusters here needs some special care:
340 * - We can't use the normal qcow2_alloc_clusters(), it would try to
341 * increase the refcount and very likely we would end up with an endless
342 * recursion. Instead we must place the refcount blocks in a way that
343 * they can describe them themselves.
345 * - We need to consider that at this point we are inside update_refcounts
346 * and potentially doing an initial refcount increase. This means that
347 * some clusters have already been allocated by the caller, but their
348 * refcount isn't accurate yet. If we allocate clusters for metadata, we
349 * need to return -EAGAIN to signal the caller that it needs to restart
350 * the search for free clusters.
352 * - alloc_clusters_noref and qcow2_free_clusters may load a different
353 * refcount block into the cache
356 *refcount_block
= NULL
;
358 /* We write to the refcount table, so we might depend on L2 tables */
359 ret
= qcow2_cache_flush(bs
, s
->l2_table_cache
);
364 /* Allocate the refcount block itself and mark it as used */
365 int64_t new_block
= alloc_clusters_noref(bs
, s
->cluster_size
, INT64_MAX
);
370 /* The offset must fit in the offset field of the refcount table entry */
371 assert((new_block
& REFT_OFFSET_MASK
) == new_block
);
373 /* If we're allocating the block at offset 0 then something is wrong */
374 if (new_block
== 0) {
375 qcow2_signal_corruption(bs
, true, -1, -1, "Preventing invalid "
376 "allocation of refcount block at offset 0");
381 fprintf(stderr
, "qcow2: Allocate refcount block %d for %" PRIx64
383 refcount_table_index
, cluster_index
<< s
->cluster_bits
, new_block
);
386 if (in_same_refcount_block(s
, new_block
, cluster_index
<< s
->cluster_bits
)) {
387 /* Zero the new refcount block before updating it */
388 ret
= qcow2_cache_get_empty(bs
, s
->refcount_block_cache
, new_block
,
394 memset(*refcount_block
, 0, s
->cluster_size
);
396 /* The block describes itself, need to update the cache */
397 int block_index
= (new_block
>> s
->cluster_bits
) &
398 (s
->refcount_block_size
- 1);
399 s
->set_refcount(*refcount_block
, block_index
, 1);
401 /* Described somewhere else. This can recurse at most twice before we
402 * arrive at a block that describes itself. */
403 ret
= update_refcount(bs
, new_block
, s
->cluster_size
, 1, false,
404 QCOW2_DISCARD_NEVER
);
409 ret
= qcow2_cache_flush(bs
, s
->refcount_block_cache
);
414 /* Initialize the new refcount block only after updating its refcount,
415 * update_refcount uses the refcount cache itself */
416 ret
= qcow2_cache_get_empty(bs
, s
->refcount_block_cache
, new_block
,
422 memset(*refcount_block
, 0, s
->cluster_size
);
425 /* Now the new refcount block needs to be written to disk */
426 BLKDBG_EVENT(bs
->file
, BLKDBG_REFBLOCK_ALLOC_WRITE
);
427 qcow2_cache_entry_mark_dirty(s
->refcount_block_cache
, *refcount_block
);
428 ret
= qcow2_cache_flush(bs
, s
->refcount_block_cache
);
433 /* If the refcount table is big enough, just hook the block up there */
434 if (refcount_table_index
< s
->refcount_table_size
) {
435 uint64_t data64
= cpu_to_be64(new_block
);
436 BLKDBG_EVENT(bs
->file
, BLKDBG_REFBLOCK_ALLOC_HOOKUP
);
437 ret
= bdrv_pwrite_sync(bs
->file
,
438 s
->refcount_table_offset
+ refcount_table_index
* sizeof(uint64_t),
439 &data64
, sizeof(data64
));
444 s
->refcount_table
[refcount_table_index
] = new_block
;
445 /* If there's a hole in s->refcount_table then it can happen
446 * that refcount_table_index < s->max_refcount_table_index */
447 s
->max_refcount_table_index
=
448 MAX(s
->max_refcount_table_index
, refcount_table_index
);
450 /* The new refcount block may be where the caller intended to put its
451 * data, so let it restart the search. */
455 qcow2_cache_put(s
->refcount_block_cache
, refcount_block
);
458 * If we come here, we need to grow the refcount table. Again, a new
459 * refcount table needs some space and we can't simply allocate to avoid
462 * Therefore let's grab new refcount blocks at the end of the image, which
463 * will describe themselves and the new refcount table. This way we can
464 * reference them only in the new table and do the switch to the new
465 * refcount table at once without producing an inconsistent state in
468 BLKDBG_EVENT(bs
->file
, BLKDBG_REFTABLE_GROW
);
470 /* Calculate the number of refcount blocks needed so far; this will be the
471 * basis for calculating the index of the first cluster used for the
472 * self-describing refcount structures which we are about to create.
474 * Because we reached this point, there cannot be any refcount entries for
475 * cluster_index or higher indices yet. However, because new_block has been
476 * allocated to describe that cluster (and it will assume this role later
477 * on), we cannot use that index; also, new_block may actually have a higher
478 * cluster index than cluster_index, so it needs to be taken into account
479 * here (and 1 needs to be added to its value because that cluster is used).
481 uint64_t blocks_used
= DIV_ROUND_UP(MAX(cluster_index
+ 1,
482 (new_block
>> s
->cluster_bits
) + 1),
483 s
->refcount_block_size
);
485 /* Create the new refcount table and blocks */
486 uint64_t meta_offset
= (blocks_used
* s
->refcount_block_size
) *
489 ret
= qcow2_refcount_area(bs
, meta_offset
, 0, false,
490 refcount_table_index
, new_block
);
495 ret
= load_refcount_block(bs
, new_block
, refcount_block
);
500 /* If we were trying to do the initial refcount update for some cluster
501 * allocation, we might have used the same clusters to store newly
502 * allocated metadata. Make the caller search some new space. */
506 if (*refcount_block
!= NULL
) {
507 qcow2_cache_put(s
->refcount_block_cache
, refcount_block
);
513 * Starting at @start_offset, this function creates new self-covering refcount
514 * structures: A new refcount table and refcount blocks which cover all of
515 * themselves, and a number of @additional_clusters beyond their end.
516 * @start_offset must be at the end of the image file, that is, there must be
517 * only empty space beyond it.
518 * If @exact_size is false, the refcount table will have 50 % more entries than
519 * necessary so it will not need to grow again soon.
520 * If @new_refblock_offset is not zero, it contains the offset of a refcount
521 * block that should be entered into the new refcount table at index
522 * @new_refblock_index.
524 * Returns: The offset after the new refcount structures (i.e. where the
525 * @additional_clusters may be placed) on success, -errno on error.
527 int64_t qcow2_refcount_area(BlockDriverState
*bs
, uint64_t start_offset
,
528 uint64_t additional_clusters
, bool exact_size
,
529 int new_refblock_index
,
530 uint64_t new_refblock_offset
)
532 BDRVQcow2State
*s
= bs
->opaque
;
533 uint64_t total_refblock_count_u64
, additional_refblock_count
;
534 int total_refblock_count
, table_size
, area_reftable_index
, table_clusters
;
536 uint64_t table_offset
, block_offset
, end_offset
;
540 assert(!(start_offset
% s
->cluster_size
));
542 qcow2_refcount_metadata_size(start_offset
/ s
->cluster_size
+
544 s
->cluster_size
, s
->refcount_order
,
545 !exact_size
, &total_refblock_count_u64
);
546 if (total_refblock_count_u64
> QCOW_MAX_REFTABLE_SIZE
) {
549 total_refblock_count
= total_refblock_count_u64
;
551 /* Index in the refcount table of the first refcount block to cover the area
552 * of refcount structures we are about to create; we know that
553 * @total_refblock_count can cover @start_offset, so this will definitely
554 * fit into an int. */
555 area_reftable_index
= (start_offset
/ s
->cluster_size
) /
556 s
->refcount_block_size
;
559 table_size
= total_refblock_count
;
561 table_size
= total_refblock_count
+
562 DIV_ROUND_UP(total_refblock_count
, 2);
564 /* The qcow2 file can only store the reftable size in number of clusters */
565 table_size
= ROUND_UP(table_size
, s
->cluster_size
/ sizeof(uint64_t));
566 table_clusters
= (table_size
* sizeof(uint64_t)) / s
->cluster_size
;
568 if (table_size
> QCOW_MAX_REFTABLE_SIZE
) {
572 new_table
= g_try_new0(uint64_t, table_size
);
574 assert(table_size
> 0);
575 if (new_table
== NULL
) {
580 /* Fill the new refcount table */
581 if (table_size
> s
->max_refcount_table_index
) {
582 /* We're actually growing the reftable */
583 memcpy(new_table
, s
->refcount_table
,
584 (s
->max_refcount_table_index
+ 1) * sizeof(uint64_t));
586 /* Improbable case: We're shrinking the reftable. However, the caller
587 * has assured us that there is only empty space beyond @start_offset,
588 * so we can simply drop all of the refblocks that won't fit into the
590 memcpy(new_table
, s
->refcount_table
, table_size
* sizeof(uint64_t));
593 if (new_refblock_offset
) {
594 assert(new_refblock_index
< total_refblock_count
);
595 new_table
[new_refblock_index
] = new_refblock_offset
;
598 /* Count how many new refblocks we have to create */
599 additional_refblock_count
= 0;
600 for (i
= area_reftable_index
; i
< total_refblock_count
; i
++) {
602 additional_refblock_count
++;
606 table_offset
= start_offset
+ additional_refblock_count
* s
->cluster_size
;
607 end_offset
= table_offset
+ table_clusters
* s
->cluster_size
;
609 /* Fill the refcount blocks, and create new ones, if necessary */
610 block_offset
= start_offset
;
611 for (i
= area_reftable_index
; i
< total_refblock_count
; i
++) {
613 uint64_t first_offset_covered
;
615 /* Reuse an existing refblock if possible, create a new one otherwise */
617 ret
= qcow2_cache_get(bs
, s
->refcount_block_cache
, new_table
[i
],
623 ret
= qcow2_cache_get_empty(bs
, s
->refcount_block_cache
,
624 block_offset
, &refblock_data
);
628 memset(refblock_data
, 0, s
->cluster_size
);
629 qcow2_cache_entry_mark_dirty(s
->refcount_block_cache
,
632 new_table
[i
] = block_offset
;
633 block_offset
+= s
->cluster_size
;
636 /* First host offset covered by this refblock */
637 first_offset_covered
= (uint64_t)i
* s
->refcount_block_size
*
639 if (first_offset_covered
< end_offset
) {
642 /* Set the refcount of all of the new refcount structures to 1 */
644 if (first_offset_covered
< start_offset
) {
645 assert(i
== area_reftable_index
);
646 j
= (start_offset
- first_offset_covered
) / s
->cluster_size
;
647 assert(j
< s
->refcount_block_size
);
652 end_index
= MIN((end_offset
- first_offset_covered
) /
654 s
->refcount_block_size
);
656 for (; j
< end_index
; j
++) {
657 /* The caller guaranteed us this space would be empty */
658 assert(s
->get_refcount(refblock_data
, j
) == 0);
659 s
->set_refcount(refblock_data
, j
, 1);
662 qcow2_cache_entry_mark_dirty(s
->refcount_block_cache
,
666 qcow2_cache_put(s
->refcount_block_cache
, &refblock_data
);
669 assert(block_offset
== table_offset
);
671 /* Write refcount blocks to disk */
672 BLKDBG_EVENT(bs
->file
, BLKDBG_REFBLOCK_ALLOC_WRITE_BLOCKS
);
673 ret
= qcow2_cache_flush(bs
, s
->refcount_block_cache
);
678 /* Write refcount table to disk */
679 for (i
= 0; i
< total_refblock_count
; i
++) {
680 cpu_to_be64s(&new_table
[i
]);
683 BLKDBG_EVENT(bs
->file
, BLKDBG_REFBLOCK_ALLOC_WRITE_TABLE
);
684 ret
= bdrv_pwrite_sync(bs
->file
, table_offset
, new_table
,
685 table_size
* sizeof(uint64_t));
690 for (i
= 0; i
< total_refblock_count
; i
++) {
691 be64_to_cpus(&new_table
[i
]);
694 /* Hook up the new refcount table in the qcow2 header */
699 data
.d64
= cpu_to_be64(table_offset
);
700 data
.d32
= cpu_to_be32(table_clusters
);
701 BLKDBG_EVENT(bs
->file
, BLKDBG_REFBLOCK_ALLOC_SWITCH_TABLE
);
702 ret
= bdrv_pwrite_sync(bs
->file
,
703 offsetof(QCowHeader
, refcount_table_offset
),
704 &data
, sizeof(data
));
709 /* And switch it in memory */
710 uint64_t old_table_offset
= s
->refcount_table_offset
;
711 uint64_t old_table_size
= s
->refcount_table_size
;
713 g_free(s
->refcount_table
);
714 s
->refcount_table
= new_table
;
715 s
->refcount_table_size
= table_size
;
716 s
->refcount_table_offset
= table_offset
;
717 update_max_refcount_table_index(s
);
719 /* Free old table. */
720 qcow2_free_clusters(bs
, old_table_offset
, old_table_size
* sizeof(uint64_t),
721 QCOW2_DISCARD_OTHER
);
730 void qcow2_process_discards(BlockDriverState
*bs
, int ret
)
732 BDRVQcow2State
*s
= bs
->opaque
;
733 Qcow2DiscardRegion
*d
, *next
;
735 QTAILQ_FOREACH_SAFE(d
, &s
->discards
, next
, next
) {
736 QTAILQ_REMOVE(&s
->discards
, d
, next
);
738 /* Discard is optional, ignore the return value */
740 bdrv_pdiscard(bs
->file
, d
->offset
, d
->bytes
);
747 static void update_refcount_discard(BlockDriverState
*bs
,
748 uint64_t offset
, uint64_t length
)
750 BDRVQcow2State
*s
= bs
->opaque
;
751 Qcow2DiscardRegion
*d
, *p
, *next
;
753 QTAILQ_FOREACH(d
, &s
->discards
, next
) {
754 uint64_t new_start
= MIN(offset
, d
->offset
);
755 uint64_t new_end
= MAX(offset
+ length
, d
->offset
+ d
->bytes
);
757 if (new_end
- new_start
<= length
+ d
->bytes
) {
758 /* There can't be any overlap, areas ending up here have no
759 * references any more and therefore shouldn't get freed another
761 assert(d
->bytes
+ length
== new_end
- new_start
);
762 d
->offset
= new_start
;
763 d
->bytes
= new_end
- new_start
;
768 d
= g_malloc(sizeof(*d
));
769 *d
= (Qcow2DiscardRegion
) {
774 QTAILQ_INSERT_TAIL(&s
->discards
, d
, next
);
777 /* Merge discard requests if they are adjacent now */
778 QTAILQ_FOREACH_SAFE(p
, &s
->discards
, next
, next
) {
780 || p
->offset
> d
->offset
+ d
->bytes
781 || d
->offset
> p
->offset
+ p
->bytes
)
786 /* Still no overlap possible */
787 assert(p
->offset
== d
->offset
+ d
->bytes
788 || d
->offset
== p
->offset
+ p
->bytes
);
790 QTAILQ_REMOVE(&s
->discards
, p
, next
);
791 d
->offset
= MIN(d
->offset
, p
->offset
);
792 d
->bytes
+= p
->bytes
;
797 /* XXX: cache several refcount block clusters ? */
798 /* @addend is the absolute value of the addend; if @decrease is set, @addend
799 * will be subtracted from the current refcount, otherwise it will be added */
800 static int QEMU_WARN_UNUSED_RESULT
update_refcount(BlockDriverState
*bs
,
805 enum qcow2_discard_type type
)
807 BDRVQcow2State
*s
= bs
->opaque
;
808 int64_t start
, last
, cluster_offset
;
809 void *refcount_block
= NULL
;
810 int64_t old_table_index
= -1;
814 fprintf(stderr
, "update_refcount: offset=%" PRId64
" size=%" PRId64
815 " addend=%s%" PRIu64
"\n", offset
, length
, decrease
? "-" : "",
820 } else if (length
== 0) {
825 qcow2_cache_set_dependency(bs
, s
->refcount_block_cache
,
829 start
= start_of_cluster(s
, offset
);
830 last
= start_of_cluster(s
, offset
+ length
- 1);
831 for(cluster_offset
= start
; cluster_offset
<= last
;
832 cluster_offset
+= s
->cluster_size
)
836 int64_t cluster_index
= cluster_offset
>> s
->cluster_bits
;
837 int64_t table_index
= cluster_index
>> s
->refcount_block_bits
;
839 /* Load the refcount block and allocate it if needed */
840 if (table_index
!= old_table_index
) {
841 if (refcount_block
) {
842 qcow2_cache_put(s
->refcount_block_cache
, &refcount_block
);
844 ret
= alloc_refcount_block(bs
, cluster_index
, &refcount_block
);
845 /* If the caller needs to restart the search for free clusters,
846 * try the same ones first to see if they're still free. */
847 if (ret
== -EAGAIN
) {
848 if (s
->free_cluster_index
> (start
>> s
->cluster_bits
)) {
849 s
->free_cluster_index
= (start
>> s
->cluster_bits
);
856 old_table_index
= table_index
;
858 qcow2_cache_entry_mark_dirty(s
->refcount_block_cache
, refcount_block
);
860 /* we can update the count and save it */
861 block_index
= cluster_index
& (s
->refcount_block_size
- 1);
863 refcount
= s
->get_refcount(refcount_block
, block_index
);
864 if (decrease
? (refcount
- addend
> refcount
)
865 : (refcount
+ addend
< refcount
||
866 refcount
+ addend
> s
->refcount_max
))
876 if (refcount
== 0 && cluster_index
< s
->free_cluster_index
) {
877 s
->free_cluster_index
= cluster_index
;
879 s
->set_refcount(refcount_block
, block_index
, refcount
);
884 table
= qcow2_cache_is_table_offset(s
->refcount_block_cache
,
887 qcow2_cache_put(s
->refcount_block_cache
, &refcount_block
);
888 qcow2_cache_discard(s
->refcount_block_cache
, table
);
891 table
= qcow2_cache_is_table_offset(s
->l2_table_cache
, offset
);
893 qcow2_cache_discard(s
->l2_table_cache
, table
);
896 if (s
->discard_passthrough
[type
]) {
897 update_refcount_discard(bs
, cluster_offset
, s
->cluster_size
);
904 if (!s
->cache_discards
) {
905 qcow2_process_discards(bs
, ret
);
908 /* Write last changed block to disk */
909 if (refcount_block
) {
910 qcow2_cache_put(s
->refcount_block_cache
, &refcount_block
);
914 * Try do undo any updates if an error is returned (This may succeed in
915 * some cases like ENOSPC for allocating a new refcount block)
919 dummy
= update_refcount(bs
, offset
, cluster_offset
- offset
, addend
,
920 !decrease
, QCOW2_DISCARD_NEVER
);
928 * Increases or decreases the refcount of a given cluster.
930 * @addend is the absolute value of the addend; if @decrease is set, @addend
931 * will be subtracted from the current refcount, otherwise it will be added.
933 * On success 0 is returned; on failure -errno is returned.
935 int qcow2_update_cluster_refcount(BlockDriverState
*bs
,
936 int64_t cluster_index
,
937 uint64_t addend
, bool decrease
,
938 enum qcow2_discard_type type
)
940 BDRVQcow2State
*s
= bs
->opaque
;
943 ret
= update_refcount(bs
, cluster_index
<< s
->cluster_bits
, 1, addend
,
954 /*********************************************************/
955 /* cluster allocation functions */
959 /* return < 0 if error */
960 static int64_t alloc_clusters_noref(BlockDriverState
*bs
, uint64_t size
,
963 BDRVQcow2State
*s
= bs
->opaque
;
964 uint64_t i
, nb_clusters
, refcount
;
967 /* We can't allocate clusters if they may still be queued for discard. */
968 if (s
->cache_discards
) {
969 qcow2_process_discards(bs
, 0);
972 nb_clusters
= size_to_clusters(s
, size
);
974 for(i
= 0; i
< nb_clusters
; i
++) {
975 uint64_t next_cluster_index
= s
->free_cluster_index
++;
976 ret
= qcow2_get_refcount(bs
, next_cluster_index
, &refcount
);
980 } else if (refcount
!= 0) {
985 /* Make sure that all offsets in the "allocated" range are representable
986 * in the requested max */
987 if (s
->free_cluster_index
> 0 &&
988 s
->free_cluster_index
- 1 > (max
>> s
->cluster_bits
))
994 fprintf(stderr
, "alloc_clusters: size=%" PRId64
" -> %" PRId64
"\n",
996 (s
->free_cluster_index
- nb_clusters
) << s
->cluster_bits
);
998 return (s
->free_cluster_index
- nb_clusters
) << s
->cluster_bits
;
1001 int64_t qcow2_alloc_clusters(BlockDriverState
*bs
, uint64_t size
)
1006 BLKDBG_EVENT(bs
->file
, BLKDBG_CLUSTER_ALLOC
);
1008 offset
= alloc_clusters_noref(bs
, size
, QCOW_MAX_CLUSTER_OFFSET
);
1013 ret
= update_refcount(bs
, offset
, size
, 1, false, QCOW2_DISCARD_NEVER
);
1014 } while (ret
== -EAGAIN
);
1023 int64_t qcow2_alloc_clusters_at(BlockDriverState
*bs
, uint64_t offset
,
1024 int64_t nb_clusters
)
1026 BDRVQcow2State
*s
= bs
->opaque
;
1027 uint64_t cluster_index
, refcount
;
1031 assert(nb_clusters
>= 0);
1032 if (nb_clusters
== 0) {
1037 /* Check how many clusters there are free */
1038 cluster_index
= offset
>> s
->cluster_bits
;
1039 for(i
= 0; i
< nb_clusters
; i
++) {
1040 ret
= qcow2_get_refcount(bs
, cluster_index
++, &refcount
);
1043 } else if (refcount
!= 0) {
1048 /* And then allocate them */
1049 ret
= update_refcount(bs
, offset
, i
<< s
->cluster_bits
, 1, false,
1050 QCOW2_DISCARD_NEVER
);
1051 } while (ret
== -EAGAIN
);
1060 /* only used to allocate compressed sectors. We try to allocate
1061 contiguous sectors. size must be <= cluster_size */
1062 int64_t qcow2_alloc_bytes(BlockDriverState
*bs
, int size
)
1064 BDRVQcow2State
*s
= bs
->opaque
;
1066 size_t free_in_cluster
;
1069 BLKDBG_EVENT(bs
->file
, BLKDBG_CLUSTER_ALLOC_BYTES
);
1070 assert(size
> 0 && size
<= s
->cluster_size
);
1071 assert(!s
->free_byte_offset
|| offset_into_cluster(s
, s
->free_byte_offset
));
1073 offset
= s
->free_byte_offset
;
1077 ret
= qcow2_get_refcount(bs
, offset
>> s
->cluster_bits
, &refcount
);
1082 if (refcount
== s
->refcount_max
) {
1087 free_in_cluster
= s
->cluster_size
- offset_into_cluster(s
, offset
);
1089 if (!offset
|| free_in_cluster
< size
) {
1090 int64_t new_cluster
;
1092 new_cluster
= alloc_clusters_noref(bs
, s
->cluster_size
,
1093 MIN(s
->cluster_offset_mask
,
1094 QCOW_MAX_CLUSTER_OFFSET
));
1095 if (new_cluster
< 0) {
1099 if (new_cluster
== 0) {
1100 qcow2_signal_corruption(bs
, true, -1, -1, "Preventing invalid "
1101 "allocation of compressed cluster "
1106 if (!offset
|| ROUND_UP(offset
, s
->cluster_size
) != new_cluster
) {
1107 offset
= new_cluster
;
1108 free_in_cluster
= s
->cluster_size
;
1110 free_in_cluster
+= s
->cluster_size
;
1115 ret
= update_refcount(bs
, offset
, size
, 1, false, QCOW2_DISCARD_NEVER
);
1119 } while (ret
== -EAGAIN
);
1124 /* The cluster refcount was incremented; refcount blocks must be flushed
1125 * before the caller's L2 table updates. */
1126 qcow2_cache_set_dependency(bs
, s
->l2_table_cache
, s
->refcount_block_cache
);
1128 s
->free_byte_offset
= offset
+ size
;
1129 if (!offset_into_cluster(s
, s
->free_byte_offset
)) {
1130 s
->free_byte_offset
= 0;
1136 void qcow2_free_clusters(BlockDriverState
*bs
,
1137 int64_t offset
, int64_t size
,
1138 enum qcow2_discard_type type
)
1142 BLKDBG_EVENT(bs
->file
, BLKDBG_CLUSTER_FREE
);
1143 ret
= update_refcount(bs
, offset
, size
, 1, true, type
);
1145 fprintf(stderr
, "qcow2_free_clusters failed: %s\n", strerror(-ret
));
1146 /* TODO Remember the clusters to free them later and avoid leaking */
1151 * Free a cluster using its L2 entry (handles clusters of all types, e.g.
1152 * normal cluster, compressed cluster, etc.)
1154 void qcow2_free_any_clusters(BlockDriverState
*bs
, uint64_t l2_entry
,
1155 int nb_clusters
, enum qcow2_discard_type type
)
1157 BDRVQcow2State
*s
= bs
->opaque
;
1158 QCow2ClusterType ctype
= qcow2_get_cluster_type(bs
, l2_entry
);
1160 if (has_data_file(bs
)) {
1161 if (s
->discard_passthrough
[type
] &&
1162 (ctype
== QCOW2_CLUSTER_NORMAL
||
1163 ctype
== QCOW2_CLUSTER_ZERO_ALLOC
))
1165 bdrv_pdiscard(s
->data_file
, l2_entry
& L2E_OFFSET_MASK
,
1166 nb_clusters
<< s
->cluster_bits
);
1172 case QCOW2_CLUSTER_COMPRESSED
:
1174 int64_t offset
= (l2_entry
& s
->cluster_offset_mask
)
1175 & QCOW2_COMPRESSED_SECTOR_MASK
;
1176 int size
= QCOW2_COMPRESSED_SECTOR_SIZE
*
1177 (((l2_entry
>> s
->csize_shift
) & s
->csize_mask
) + 1);
1178 qcow2_free_clusters(bs
, offset
, size
, type
);
1181 case QCOW2_CLUSTER_NORMAL
:
1182 case QCOW2_CLUSTER_ZERO_ALLOC
:
1183 if (offset_into_cluster(s
, l2_entry
& L2E_OFFSET_MASK
)) {
1184 qcow2_signal_corruption(bs
, false, -1, -1,
1185 "Cannot free unaligned cluster %#llx",
1186 l2_entry
& L2E_OFFSET_MASK
);
1188 qcow2_free_clusters(bs
, l2_entry
& L2E_OFFSET_MASK
,
1189 nb_clusters
<< s
->cluster_bits
, type
);
1192 case QCOW2_CLUSTER_ZERO_PLAIN
:
1193 case QCOW2_CLUSTER_UNALLOCATED
:
1200 int coroutine_fn
qcow2_write_caches(BlockDriverState
*bs
)
1202 BDRVQcow2State
*s
= bs
->opaque
;
1205 ret
= qcow2_cache_write(bs
, s
->l2_table_cache
);
1210 if (qcow2_need_accurate_refcounts(s
)) {
1211 ret
= qcow2_cache_write(bs
, s
->refcount_block_cache
);
1220 int coroutine_fn
qcow2_flush_caches(BlockDriverState
*bs
)
1222 int ret
= qcow2_write_caches(bs
);
1227 return bdrv_flush(bs
->file
->bs
);
1230 /*********************************************************/
1231 /* snapshots and image creation */
1235 /* update the refcounts of snapshots and the copied flag */
1236 int qcow2_update_snapshot_refcount(BlockDriverState
*bs
,
1237 int64_t l1_table_offset
, int l1_size
, int addend
)
1239 BDRVQcow2State
*s
= bs
->opaque
;
1240 uint64_t *l1_table
, *l2_slice
, l2_offset
, entry
, l1_size2
, refcount
;
1241 bool l1_allocated
= false;
1242 int64_t old_entry
, old_l2_offset
;
1243 unsigned slice
, slice_size2
, n_slices
;
1244 int i
, j
, l1_modified
= 0, nb_csectors
;
1247 assert(addend
>= -1 && addend
<= 1);
1251 l1_size2
= l1_size
* sizeof(uint64_t);
1252 slice_size2
= s
->l2_slice_size
* sizeof(uint64_t);
1253 n_slices
= s
->cluster_size
/ slice_size2
;
1255 s
->cache_discards
= true;
1257 /* WARNING: qcow2_snapshot_goto relies on this function not using the
1258 * l1_table_offset when it is the current s->l1_table_offset! Be careful
1259 * when changing this! */
1260 if (l1_table_offset
!= s
->l1_table_offset
) {
1261 l1_table
= g_try_malloc0(ROUND_UP(l1_size2
, 512));
1262 if (l1_size2
&& l1_table
== NULL
) {
1266 l1_allocated
= true;
1268 ret
= bdrv_pread(bs
->file
, l1_table_offset
, l1_table
, l1_size2
);
1273 for (i
= 0; i
< l1_size
; i
++) {
1274 be64_to_cpus(&l1_table
[i
]);
1277 assert(l1_size
== s
->l1_size
);
1278 l1_table
= s
->l1_table
;
1279 l1_allocated
= false;
1282 for (i
= 0; i
< l1_size
; i
++) {
1283 l2_offset
= l1_table
[i
];
1285 old_l2_offset
= l2_offset
;
1286 l2_offset
&= L1E_OFFSET_MASK
;
1288 if (offset_into_cluster(s
, l2_offset
)) {
1289 qcow2_signal_corruption(bs
, true, -1, -1, "L2 table offset %#"
1290 PRIx64
" unaligned (L1 index: %#x)",
1296 for (slice
= 0; slice
< n_slices
; slice
++) {
1297 ret
= qcow2_cache_get(bs
, s
->l2_table_cache
,
1298 l2_offset
+ slice
* slice_size2
,
1299 (void **) &l2_slice
);
1304 for (j
= 0; j
< s
->l2_slice_size
; j
++) {
1305 uint64_t cluster_index
;
1308 entry
= be64_to_cpu(l2_slice
[j
]);
1310 entry
&= ~QCOW_OFLAG_COPIED
;
1311 offset
= entry
& L2E_OFFSET_MASK
;
1313 switch (qcow2_get_cluster_type(bs
, entry
)) {
1314 case QCOW2_CLUSTER_COMPRESSED
:
1315 nb_csectors
= ((entry
>> s
->csize_shift
) &
1318 uint64_t coffset
= (entry
& s
->cluster_offset_mask
)
1319 & QCOW2_COMPRESSED_SECTOR_MASK
;
1320 ret
= update_refcount(
1322 nb_csectors
* QCOW2_COMPRESSED_SECTOR_SIZE
,
1323 abs(addend
), addend
< 0,
1324 QCOW2_DISCARD_SNAPSHOT
);
1329 /* compressed clusters are never modified */
1333 case QCOW2_CLUSTER_NORMAL
:
1334 case QCOW2_CLUSTER_ZERO_ALLOC
:
1335 if (offset_into_cluster(s
, offset
)) {
1336 /* Here l2_index means table (not slice) index */
1337 int l2_index
= slice
* s
->l2_slice_size
+ j
;
1338 qcow2_signal_corruption(
1339 bs
, true, -1, -1, "Cluster "
1340 "allocation offset %#" PRIx64
1341 " unaligned (L2 offset: %#"
1342 PRIx64
", L2 index: %#x)",
1343 offset
, l2_offset
, l2_index
);
1348 cluster_index
= offset
>> s
->cluster_bits
;
1349 assert(cluster_index
);
1351 ret
= qcow2_update_cluster_refcount(
1352 bs
, cluster_index
, abs(addend
), addend
< 0,
1353 QCOW2_DISCARD_SNAPSHOT
);
1359 ret
= qcow2_get_refcount(bs
, cluster_index
, &refcount
);
1365 case QCOW2_CLUSTER_ZERO_PLAIN
:
1366 case QCOW2_CLUSTER_UNALLOCATED
:
1374 if (refcount
== 1) {
1375 entry
|= QCOW_OFLAG_COPIED
;
1377 if (entry
!= old_entry
) {
1379 qcow2_cache_set_dependency(bs
, s
->l2_table_cache
,
1380 s
->refcount_block_cache
);
1382 l2_slice
[j
] = cpu_to_be64(entry
);
1383 qcow2_cache_entry_mark_dirty(s
->l2_table_cache
,
1388 qcow2_cache_put(s
->l2_table_cache
, (void **) &l2_slice
);
1392 ret
= qcow2_update_cluster_refcount(bs
, l2_offset
>>
1394 abs(addend
), addend
< 0,
1395 QCOW2_DISCARD_SNAPSHOT
);
1400 ret
= qcow2_get_refcount(bs
, l2_offset
>> s
->cluster_bits
,
1404 } else if (refcount
== 1) {
1405 l2_offset
|= QCOW_OFLAG_COPIED
;
1407 if (l2_offset
!= old_l2_offset
) {
1408 l1_table
[i
] = l2_offset
;
1414 ret
= bdrv_flush(bs
);
1417 qcow2_cache_put(s
->l2_table_cache
, (void **) &l2_slice
);
1420 s
->cache_discards
= false;
1421 qcow2_process_discards(bs
, ret
);
1423 /* Update L1 only if it isn't deleted anyway (addend = -1) */
1424 if (ret
== 0 && addend
>= 0 && l1_modified
) {
1425 for (i
= 0; i
< l1_size
; i
++) {
1426 cpu_to_be64s(&l1_table
[i
]);
1429 ret
= bdrv_pwrite_sync(bs
->file
, l1_table_offset
,
1430 l1_table
, l1_size2
);
1432 for (i
= 0; i
< l1_size
; i
++) {
1433 be64_to_cpus(&l1_table
[i
]);
1444 /*********************************************************/
1445 /* refcount checking functions */
1448 static uint64_t refcount_array_byte_size(BDRVQcow2State
*s
, uint64_t entries
)
1450 /* This assertion holds because there is no way we can address more than
1451 * 2^(64 - 9) clusters at once (with cluster size 512 = 2^9, and because
1452 * offsets have to be representable in bytes); due to every cluster
1453 * corresponding to one refcount entry, we are well below that limit */
1454 assert(entries
< (UINT64_C(1) << (64 - 9)));
1456 /* Thanks to the assertion this will not overflow, because
1457 * s->refcount_order < 7.
1458 * (note: x << s->refcount_order == x * s->refcount_bits) */
1459 return DIV_ROUND_UP(entries
<< s
->refcount_order
, 8);
1463 * Reallocates *array so that it can hold new_size entries. *size must contain
1464 * the current number of entries in *array. If the reallocation fails, *array
1465 * and *size will not be modified and -errno will be returned. If the
1466 * reallocation is successful, *array will be set to the new buffer, *size
1467 * will be set to new_size and 0 will be returned. The size of the reallocated
1468 * refcount array buffer will be aligned to a cluster boundary, and the newly
1469 * allocated area will be zeroed.
1471 static int realloc_refcount_array(BDRVQcow2State
*s
, void **array
,
1472 int64_t *size
, int64_t new_size
)
1474 int64_t old_byte_size
, new_byte_size
;
1477 /* Round to clusters so the array can be directly written to disk */
1478 old_byte_size
= size_to_clusters(s
, refcount_array_byte_size(s
, *size
))
1480 new_byte_size
= size_to_clusters(s
, refcount_array_byte_size(s
, new_size
))
1483 if (new_byte_size
== old_byte_size
) {
1488 assert(new_byte_size
> 0);
1490 if (new_byte_size
> SIZE_MAX
) {
1494 new_ptr
= g_try_realloc(*array
, new_byte_size
);
1499 if (new_byte_size
> old_byte_size
) {
1500 memset((char *)new_ptr
+ old_byte_size
, 0,
1501 new_byte_size
- old_byte_size
);
1511 * Increases the refcount for a range of clusters in a given refcount table.
1512 * This is used to construct a temporary refcount table out of L1 and L2 tables
1513 * which can be compared to the refcount table saved in the image.
1515 * Modifies the number of errors in res.
1517 int qcow2_inc_refcounts_imrt(BlockDriverState
*bs
, BdrvCheckResult
*res
,
1518 void **refcount_table
,
1519 int64_t *refcount_table_size
,
1520 int64_t offset
, int64_t size
)
1522 BDRVQcow2State
*s
= bs
->opaque
;
1523 uint64_t start
, last
, cluster_offset
, k
, refcount
;
1531 file_len
= bdrv_getlength(bs
->file
->bs
);
1537 * Last cluster of qcow2 image may be semi-allocated, so it may be OK to
1538 * reference some space after file end but it should be less than one
1541 if (offset
+ size
- file_len
>= s
->cluster_size
) {
1542 fprintf(stderr
, "ERROR: counting reference for region exceeding the "
1543 "end of the file by one cluster or more: offset 0x%" PRIx64
1544 " size 0x%" PRIx64
"\n", offset
, size
);
1549 start
= start_of_cluster(s
, offset
);
1550 last
= start_of_cluster(s
, offset
+ size
- 1);
1551 for(cluster_offset
= start
; cluster_offset
<= last
;
1552 cluster_offset
+= s
->cluster_size
) {
1553 k
= cluster_offset
>> s
->cluster_bits
;
1554 if (k
>= *refcount_table_size
) {
1555 ret
= realloc_refcount_array(s
, refcount_table
,
1556 refcount_table_size
, k
+ 1);
1558 res
->check_errors
++;
1563 refcount
= s
->get_refcount(*refcount_table
, k
);
1564 if (refcount
== s
->refcount_max
) {
1565 fprintf(stderr
, "ERROR: overflow cluster offset=0x%" PRIx64
1566 "\n", cluster_offset
);
1567 fprintf(stderr
, "Use qemu-img amend to increase the refcount entry "
1568 "width or qemu-img convert to create a clean copy if the "
1569 "image cannot be opened for writing\n");
1573 s
->set_refcount(*refcount_table
, k
, refcount
+ 1);
1579 /* Flags for check_refcounts_l1() and check_refcounts_l2() */
1581 CHECK_FRAG_INFO
= 0x2, /* update BlockFragInfo counters */
1585 * Increases the refcount in the given refcount table for the all clusters
1586 * referenced in the L2 table. While doing so, performs some checks on L2
1589 * Returns the number of errors found by the checks or -errno if an internal
1592 static int check_refcounts_l2(BlockDriverState
*bs
, BdrvCheckResult
*res
,
1593 void **refcount_table
,
1594 int64_t *refcount_table_size
, int64_t l2_offset
,
1595 int flags
, BdrvCheckMode fix
, bool active
)
1597 BDRVQcow2State
*s
= bs
->opaque
;
1598 uint64_t *l2_table
, l2_entry
;
1599 uint64_t next_contiguous_offset
= 0;
1600 int i
, l2_size
, nb_csectors
, ret
;
1602 /* Read L2 table from disk */
1603 l2_size
= s
->l2_size
* sizeof(uint64_t);
1604 l2_table
= g_malloc(l2_size
);
1606 ret
= bdrv_pread(bs
->file
, l2_offset
, l2_table
, l2_size
);
1608 fprintf(stderr
, "ERROR: I/O error in check_refcounts_l2\n");
1609 res
->check_errors
++;
1613 /* Do the actual checks */
1614 for(i
= 0; i
< s
->l2_size
; i
++) {
1615 l2_entry
= be64_to_cpu(l2_table
[i
]);
1617 switch (qcow2_get_cluster_type(bs
, l2_entry
)) {
1618 case QCOW2_CLUSTER_COMPRESSED
:
1619 /* Compressed clusters don't have QCOW_OFLAG_COPIED */
1620 if (l2_entry
& QCOW_OFLAG_COPIED
) {
1621 fprintf(stderr
, "ERROR: coffset=0x%" PRIx64
": "
1622 "copied flag must never be set for compressed "
1623 "clusters\n", l2_entry
& s
->cluster_offset_mask
);
1624 l2_entry
&= ~QCOW_OFLAG_COPIED
;
1628 if (has_data_file(bs
)) {
1629 fprintf(stderr
, "ERROR compressed cluster %d with data file, "
1630 "entry=0x%" PRIx64
"\n", i
, l2_entry
);
1635 /* Mark cluster as used */
1636 nb_csectors
= ((l2_entry
>> s
->csize_shift
) &
1638 l2_entry
&= s
->cluster_offset_mask
;
1639 ret
= qcow2_inc_refcounts_imrt(
1640 bs
, res
, refcount_table
, refcount_table_size
,
1641 l2_entry
& QCOW2_COMPRESSED_SECTOR_MASK
,
1642 nb_csectors
* QCOW2_COMPRESSED_SECTOR_SIZE
);
1647 if (flags
& CHECK_FRAG_INFO
) {
1648 res
->bfi
.allocated_clusters
++;
1649 res
->bfi
.compressed_clusters
++;
1651 /* Compressed clusters are fragmented by nature. Since they
1652 * take up sub-sector space but we only have sector granularity
1653 * I/O we need to re-read the same sectors even for adjacent
1654 * compressed clusters.
1656 res
->bfi
.fragmented_clusters
++;
1660 case QCOW2_CLUSTER_ZERO_ALLOC
:
1661 case QCOW2_CLUSTER_NORMAL
:
1663 uint64_t offset
= l2_entry
& L2E_OFFSET_MASK
;
1665 /* Correct offsets are cluster aligned */
1666 if (offset_into_cluster(s
, offset
)) {
1669 if (qcow2_get_cluster_type(bs
, l2_entry
) ==
1670 QCOW2_CLUSTER_ZERO_ALLOC
)
1672 fprintf(stderr
, "%s offset=%" PRIx64
": Preallocated zero "
1673 "cluster is not properly aligned; L2 entry "
1675 fix
& BDRV_FIX_ERRORS
? "Repairing" : "ERROR",
1677 if (fix
& BDRV_FIX_ERRORS
) {
1678 uint64_t l2e_offset
=
1679 l2_offset
+ (uint64_t)i
* sizeof(uint64_t);
1680 int ign
= active
? QCOW2_OL_ACTIVE_L2
:
1681 QCOW2_OL_INACTIVE_L2
;
1683 l2_entry
= QCOW_OFLAG_ZERO
;
1684 l2_table
[i
] = cpu_to_be64(l2_entry
);
1685 ret
= qcow2_pre_write_overlap_check(bs
, ign
,
1686 l2e_offset
, sizeof(uint64_t), false);
1688 fprintf(stderr
, "ERROR: Overlap check failed\n");
1689 res
->check_errors
++;
1690 /* Something is seriously wrong, so abort checking
1695 ret
= bdrv_pwrite_sync(bs
->file
, l2e_offset
,
1696 &l2_table
[i
], sizeof(uint64_t));
1698 fprintf(stderr
, "ERROR: Failed to overwrite L2 "
1699 "table entry: %s\n", strerror(-ret
));
1700 res
->check_errors
++;
1701 /* Do not abort, continue checking the rest of this
1702 * L2 table's entries */
1705 res
->corruptions_fixed
++;
1706 /* Skip marking the cluster as used
1707 * (it is unused now) */
1712 fprintf(stderr
, "ERROR offset=%" PRIx64
": Data cluster is "
1713 "not properly aligned; L2 entry corrupted.\n", offset
);
1717 if (flags
& CHECK_FRAG_INFO
) {
1718 res
->bfi
.allocated_clusters
++;
1719 if (next_contiguous_offset
&&
1720 offset
!= next_contiguous_offset
) {
1721 res
->bfi
.fragmented_clusters
++;
1723 next_contiguous_offset
= offset
+ s
->cluster_size
;
1726 /* Mark cluster as used */
1727 if (!has_data_file(bs
)) {
1728 ret
= qcow2_inc_refcounts_imrt(bs
, res
, refcount_table
,
1729 refcount_table_size
,
1730 offset
, s
->cluster_size
);
1738 case QCOW2_CLUSTER_ZERO_PLAIN
:
1739 case QCOW2_CLUSTER_UNALLOCATED
:
1756 * Increases the refcount for the L1 table, its L2 tables and all referenced
1757 * clusters in the given refcount table. While doing so, performs some checks
1758 * on L1 and L2 entries.
1760 * Returns the number of errors found by the checks or -errno if an internal
1763 static int check_refcounts_l1(BlockDriverState
*bs
,
1764 BdrvCheckResult
*res
,
1765 void **refcount_table
,
1766 int64_t *refcount_table_size
,
1767 int64_t l1_table_offset
, int l1_size
,
1768 int flags
, BdrvCheckMode fix
, bool active
)
1770 BDRVQcow2State
*s
= bs
->opaque
;
1771 uint64_t *l1_table
= NULL
, l2_offset
, l1_size2
;
1774 l1_size2
= l1_size
* sizeof(uint64_t);
1776 /* Mark L1 table as used */
1777 ret
= qcow2_inc_refcounts_imrt(bs
, res
, refcount_table
, refcount_table_size
,
1778 l1_table_offset
, l1_size2
);
1783 /* Read L1 table entries from disk */
1785 l1_table
= g_try_malloc(l1_size2
);
1786 if (l1_table
== NULL
) {
1788 res
->check_errors
++;
1791 ret
= bdrv_pread(bs
->file
, l1_table_offset
, l1_table
, l1_size2
);
1793 fprintf(stderr
, "ERROR: I/O error in check_refcounts_l1\n");
1794 res
->check_errors
++;
1797 for(i
= 0;i
< l1_size
; i
++)
1798 be64_to_cpus(&l1_table
[i
]);
1801 /* Do the actual checks */
1802 for(i
= 0; i
< l1_size
; i
++) {
1803 l2_offset
= l1_table
[i
];
1805 /* Mark L2 table as used */
1806 l2_offset
&= L1E_OFFSET_MASK
;
1807 ret
= qcow2_inc_refcounts_imrt(bs
, res
,
1808 refcount_table
, refcount_table_size
,
1809 l2_offset
, s
->cluster_size
);
1814 /* L2 tables are cluster aligned */
1815 if (offset_into_cluster(s
, l2_offset
)) {
1816 fprintf(stderr
, "ERROR l2_offset=%" PRIx64
": Table is not "
1817 "cluster aligned; L1 entry corrupted\n", l2_offset
);
1821 /* Process and check L2 entries */
1822 ret
= check_refcounts_l2(bs
, res
, refcount_table
,
1823 refcount_table_size
, l2_offset
, flags
,
1839 * Checks the OFLAG_COPIED flag for all L1 and L2 entries.
1841 * This function does not print an error message nor does it increment
1842 * check_errors if qcow2_get_refcount fails (this is because such an error will
1843 * have been already detected and sufficiently signaled by the calling function
1844 * (qcow2_check_refcounts) by the time this function is called).
1846 static int check_oflag_copied(BlockDriverState
*bs
, BdrvCheckResult
*res
,
1849 BDRVQcow2State
*s
= bs
->opaque
;
1850 uint64_t *l2_table
= qemu_blockalign(bs
, s
->cluster_size
);
1856 if (fix
& BDRV_FIX_ERRORS
) {
1859 } else if (fix
& BDRV_FIX_LEAKS
) {
1860 /* Repair only if that seems safe: This function is always
1861 * called after the refcounts have been fixed, so the refcount
1862 * is accurate if that repair was successful */
1863 repair
= !res
->check_errors
&& !res
->corruptions
&& !res
->leaks
;
1868 for (i
= 0; i
< s
->l1_size
; i
++) {
1869 uint64_t l1_entry
= s
->l1_table
[i
];
1870 uint64_t l2_offset
= l1_entry
& L1E_OFFSET_MASK
;
1877 ret
= qcow2_get_refcount(bs
, l2_offset
>> s
->cluster_bits
,
1880 /* don't print message nor increment check_errors */
1883 if ((refcount
== 1) != ((l1_entry
& QCOW_OFLAG_COPIED
) != 0)) {
1885 fprintf(stderr
, "%s OFLAG_COPIED L2 cluster: l1_index=%d "
1886 "l1_entry=%" PRIx64
" refcount=%" PRIu64
"\n",
1887 repair
? "Repairing" : "ERROR", i
, l1_entry
, refcount
);
1889 s
->l1_table
[i
] = refcount
== 1
1890 ? l1_entry
| QCOW_OFLAG_COPIED
1891 : l1_entry
& ~QCOW_OFLAG_COPIED
;
1892 ret
= qcow2_write_l1_entry(bs
, i
);
1894 res
->check_errors
++;
1898 res
->corruptions_fixed
++;
1902 ret
= bdrv_pread(bs
->file
, l2_offset
, l2_table
,
1903 s
->l2_size
* sizeof(uint64_t));
1905 fprintf(stderr
, "ERROR: Could not read L2 table: %s\n",
1907 res
->check_errors
++;
1911 for (j
= 0; j
< s
->l2_size
; j
++) {
1912 uint64_t l2_entry
= be64_to_cpu(l2_table
[j
]);
1913 uint64_t data_offset
= l2_entry
& L2E_OFFSET_MASK
;
1914 QCow2ClusterType cluster_type
= qcow2_get_cluster_type(bs
, l2_entry
);
1916 if (cluster_type
== QCOW2_CLUSTER_NORMAL
||
1917 cluster_type
== QCOW2_CLUSTER_ZERO_ALLOC
) {
1918 if (has_data_file(bs
)) {
1921 ret
= qcow2_get_refcount(bs
,
1922 data_offset
>> s
->cluster_bits
,
1925 /* don't print message nor increment check_errors */
1929 if ((refcount
== 1) != ((l2_entry
& QCOW_OFLAG_COPIED
) != 0)) {
1931 fprintf(stderr
, "%s OFLAG_COPIED data cluster: "
1932 "l2_entry=%" PRIx64
" refcount=%" PRIu64
"\n",
1933 repair
? "Repairing" : "ERROR", l2_entry
, refcount
);
1935 l2_table
[j
] = cpu_to_be64(refcount
== 1
1936 ? l2_entry
| QCOW_OFLAG_COPIED
1937 : l2_entry
& ~QCOW_OFLAG_COPIED
);
1945 ret
= qcow2_pre_write_overlap_check(bs
, QCOW2_OL_ACTIVE_L2
,
1946 l2_offset
, s
->cluster_size
,
1949 fprintf(stderr
, "ERROR: Could not write L2 table; metadata "
1950 "overlap check failed: %s\n", strerror(-ret
));
1951 res
->check_errors
++;
1955 ret
= bdrv_pwrite(bs
->file
, l2_offset
, l2_table
,
1958 fprintf(stderr
, "ERROR: Could not write L2 table: %s\n",
1960 res
->check_errors
++;
1963 res
->corruptions
-= l2_dirty
;
1964 res
->corruptions_fixed
+= l2_dirty
;
1971 qemu_vfree(l2_table
);
1976 * Checks consistency of refblocks and accounts for each refblock in
1979 static int check_refblocks(BlockDriverState
*bs
, BdrvCheckResult
*res
,
1980 BdrvCheckMode fix
, bool *rebuild
,
1981 void **refcount_table
, int64_t *nb_clusters
)
1983 BDRVQcow2State
*s
= bs
->opaque
;
1987 for(i
= 0; i
< s
->refcount_table_size
; i
++) {
1988 uint64_t offset
, cluster
;
1989 offset
= s
->refcount_table
[i
];
1990 cluster
= offset
>> s
->cluster_bits
;
1992 /* Refcount blocks are cluster aligned */
1993 if (offset_into_cluster(s
, offset
)) {
1994 fprintf(stderr
, "ERROR refcount block %" PRId64
" is not "
1995 "cluster aligned; refcount table entry corrupted\n", i
);
2001 if (cluster
>= *nb_clusters
) {
2003 fprintf(stderr
, "%s refcount block %" PRId64
" is outside image\n",
2004 fix
& BDRV_FIX_ERRORS
? "Repairing" : "ERROR", i
);
2006 if (fix
& BDRV_FIX_ERRORS
) {
2007 int64_t new_nb_clusters
;
2008 Error
*local_err
= NULL
;
2010 if (offset
> INT64_MAX
- s
->cluster_size
) {
2015 ret
= bdrv_truncate(bs
->file
, offset
+ s
->cluster_size
,
2016 PREALLOC_MODE_OFF
, &local_err
);
2018 error_report_err(local_err
);
2021 size
= bdrv_getlength(bs
->file
->bs
);
2027 new_nb_clusters
= size_to_clusters(s
, size
);
2028 assert(new_nb_clusters
>= *nb_clusters
);
2030 ret
= realloc_refcount_array(s
, refcount_table
,
2031 nb_clusters
, new_nb_clusters
);
2033 res
->check_errors
++;
2037 if (cluster
>= *nb_clusters
) {
2043 res
->corruptions_fixed
++;
2044 ret
= qcow2_inc_refcounts_imrt(bs
, res
,
2045 refcount_table
, nb_clusters
,
2046 offset
, s
->cluster_size
);
2050 /* No need to check whether the refcount is now greater than 1:
2051 * This area was just allocated and zeroed, so it can only be
2052 * exactly 1 after qcow2_inc_refcounts_imrt() */
2057 fprintf(stderr
, "ERROR could not resize image: %s\n",
2064 ret
= qcow2_inc_refcounts_imrt(bs
, res
, refcount_table
, nb_clusters
,
2065 offset
, s
->cluster_size
);
2069 if (s
->get_refcount(*refcount_table
, cluster
) != 1) {
2070 fprintf(stderr
, "ERROR refcount block %" PRId64
2071 " refcount=%" PRIu64
"\n", i
,
2072 s
->get_refcount(*refcount_table
, cluster
));
2083 * Calculates an in-memory refcount table.
2085 static int calculate_refcounts(BlockDriverState
*bs
, BdrvCheckResult
*res
,
2086 BdrvCheckMode fix
, bool *rebuild
,
2087 void **refcount_table
, int64_t *nb_clusters
)
2089 BDRVQcow2State
*s
= bs
->opaque
;
2094 if (!*refcount_table
) {
2095 int64_t old_size
= 0;
2096 ret
= realloc_refcount_array(s
, refcount_table
,
2097 &old_size
, *nb_clusters
);
2099 res
->check_errors
++;
2105 ret
= qcow2_inc_refcounts_imrt(bs
, res
, refcount_table
, nb_clusters
,
2106 0, s
->cluster_size
);
2111 /* current L1 table */
2112 ret
= check_refcounts_l1(bs
, res
, refcount_table
, nb_clusters
,
2113 s
->l1_table_offset
, s
->l1_size
, CHECK_FRAG_INFO
,
2120 if (has_data_file(bs
) && s
->nb_snapshots
) {
2121 fprintf(stderr
, "ERROR %d snapshots in image with data file\n",
2126 for (i
= 0; i
< s
->nb_snapshots
; i
++) {
2127 sn
= s
->snapshots
+ i
;
2128 if (offset_into_cluster(s
, sn
->l1_table_offset
)) {
2129 fprintf(stderr
, "ERROR snapshot %s (%s) l1_offset=%#" PRIx64
": "
2130 "L1 table is not cluster aligned; snapshot table entry "
2131 "corrupted\n", sn
->id_str
, sn
->name
, sn
->l1_table_offset
);
2135 if (sn
->l1_size
> QCOW_MAX_L1_SIZE
/ sizeof(uint64_t)) {
2136 fprintf(stderr
, "ERROR snapshot %s (%s) l1_size=%#" PRIx32
": "
2137 "L1 table is too large; snapshot table entry corrupted\n",
2138 sn
->id_str
, sn
->name
, sn
->l1_size
);
2142 ret
= check_refcounts_l1(bs
, res
, refcount_table
, nb_clusters
,
2143 sn
->l1_table_offset
, sn
->l1_size
, 0, fix
,
2149 ret
= qcow2_inc_refcounts_imrt(bs
, res
, refcount_table
, nb_clusters
,
2150 s
->snapshots_offset
, s
->snapshots_size
);
2156 ret
= qcow2_inc_refcounts_imrt(bs
, res
, refcount_table
, nb_clusters
,
2157 s
->refcount_table_offset
,
2158 s
->refcount_table_size
* sizeof(uint64_t));
2164 if (s
->crypto_header
.length
) {
2165 ret
= qcow2_inc_refcounts_imrt(bs
, res
, refcount_table
, nb_clusters
,
2166 s
->crypto_header
.offset
,
2167 s
->crypto_header
.length
);
2174 ret
= qcow2_check_bitmaps_refcounts(bs
, res
, refcount_table
, nb_clusters
);
2179 return check_refblocks(bs
, res
, fix
, rebuild
, refcount_table
, nb_clusters
);
2183 * Compares the actual reference count for each cluster in the image against the
2184 * refcount as reported by the refcount structures on-disk.
2186 static void compare_refcounts(BlockDriverState
*bs
, BdrvCheckResult
*res
,
2187 BdrvCheckMode fix
, bool *rebuild
,
2188 int64_t *highest_cluster
,
2189 void *refcount_table
, int64_t nb_clusters
)
2191 BDRVQcow2State
*s
= bs
->opaque
;
2193 uint64_t refcount1
, refcount2
;
2196 for (i
= 0, *highest_cluster
= 0; i
< nb_clusters
; i
++) {
2197 ret
= qcow2_get_refcount(bs
, i
, &refcount1
);
2199 fprintf(stderr
, "Can't get refcount for cluster %" PRId64
": %s\n",
2201 res
->check_errors
++;
2205 refcount2
= s
->get_refcount(refcount_table
, i
);
2207 if (refcount1
> 0 || refcount2
> 0) {
2208 *highest_cluster
= i
;
2211 if (refcount1
!= refcount2
) {
2212 /* Check if we're allowed to fix the mismatch */
2213 int *num_fixed
= NULL
;
2214 if (refcount1
== 0) {
2216 } else if (refcount1
> refcount2
&& (fix
& BDRV_FIX_LEAKS
)) {
2217 num_fixed
= &res
->leaks_fixed
;
2218 } else if (refcount1
< refcount2
&& (fix
& BDRV_FIX_ERRORS
)) {
2219 num_fixed
= &res
->corruptions_fixed
;
2222 fprintf(stderr
, "%s cluster %" PRId64
" refcount=%" PRIu64
2223 " reference=%" PRIu64
"\n",
2224 num_fixed
!= NULL
? "Repairing" :
2225 refcount1
< refcount2
? "ERROR" :
2227 i
, refcount1
, refcount2
);
2230 ret
= update_refcount(bs
, i
<< s
->cluster_bits
, 1,
2231 refcount_diff(refcount1
, refcount2
),
2232 refcount1
> refcount2
,
2233 QCOW2_DISCARD_ALWAYS
);
2240 /* And if we couldn't, print an error */
2241 if (refcount1
< refcount2
) {
2251 * Allocates clusters using an in-memory refcount table (IMRT) in contrast to
2252 * the on-disk refcount structures.
2254 * On input, *first_free_cluster tells where to start looking, and need not
2255 * actually be a free cluster; the returned offset will not be before that
2256 * cluster. On output, *first_free_cluster points to the first gap found, even
2257 * if that gap was too small to be used as the returned offset.
2259 * Note that *first_free_cluster is a cluster index whereas the return value is
2262 static int64_t alloc_clusters_imrt(BlockDriverState
*bs
,
2264 void **refcount_table
,
2265 int64_t *imrt_nb_clusters
,
2266 int64_t *first_free_cluster
)
2268 BDRVQcow2State
*s
= bs
->opaque
;
2269 int64_t cluster
= *first_free_cluster
, i
;
2270 bool first_gap
= true;
2271 int contiguous_free_clusters
;
2274 /* Starting at *first_free_cluster, find a range of at least cluster_count
2275 * continuously free clusters */
2276 for (contiguous_free_clusters
= 0;
2277 cluster
< *imrt_nb_clusters
&&
2278 contiguous_free_clusters
< cluster_count
;
2281 if (!s
->get_refcount(*refcount_table
, cluster
)) {
2282 contiguous_free_clusters
++;
2284 /* If this is the first free cluster found, update
2285 * *first_free_cluster accordingly */
2286 *first_free_cluster
= cluster
;
2289 } else if (contiguous_free_clusters
) {
2290 contiguous_free_clusters
= 0;
2294 /* If contiguous_free_clusters is greater than zero, it contains the number
2295 * of continuously free clusters until the current cluster; the first free
2296 * cluster in the current "gap" is therefore
2297 * cluster - contiguous_free_clusters */
2299 /* If no such range could be found, grow the in-memory refcount table
2300 * accordingly to append free clusters at the end of the image */
2301 if (contiguous_free_clusters
< cluster_count
) {
2302 /* contiguous_free_clusters clusters are already empty at the image end;
2303 * we need cluster_count clusters; therefore, we have to allocate
2304 * cluster_count - contiguous_free_clusters new clusters at the end of
2305 * the image (which is the current value of cluster; note that cluster
2306 * may exceed old_imrt_nb_clusters if *first_free_cluster pointed beyond
2308 ret
= realloc_refcount_array(s
, refcount_table
, imrt_nb_clusters
,
2309 cluster
+ cluster_count
2310 - contiguous_free_clusters
);
2316 /* Go back to the first free cluster */
2317 cluster
-= contiguous_free_clusters
;
2318 for (i
= 0; i
< cluster_count
; i
++) {
2319 s
->set_refcount(*refcount_table
, cluster
+ i
, 1);
2322 return cluster
<< s
->cluster_bits
;
2326 * Creates a new refcount structure based solely on the in-memory information
2327 * given through *refcount_table. All necessary allocations will be reflected
2330 * On success, the old refcount structure is leaked (it will be covered by the
2331 * new refcount structure).
2333 static int rebuild_refcount_structure(BlockDriverState
*bs
,
2334 BdrvCheckResult
*res
,
2335 void **refcount_table
,
2336 int64_t *nb_clusters
)
2338 BDRVQcow2State
*s
= bs
->opaque
;
2339 int64_t first_free_cluster
= 0, reftable_offset
= -1, cluster
= 0;
2340 int64_t refblock_offset
, refblock_start
, refblock_index
;
2341 uint32_t reftable_size
= 0;
2342 uint64_t *on_disk_reftable
= NULL
;
2343 void *on_disk_refblock
;
2346 uint64_t reftable_offset
;
2347 uint32_t reftable_clusters
;
2348 } QEMU_PACKED reftable_offset_and_clusters
;
2350 qcow2_cache_empty(bs
, s
->refcount_block_cache
);
2353 for (; cluster
< *nb_clusters
; cluster
++) {
2354 if (!s
->get_refcount(*refcount_table
, cluster
)) {
2358 refblock_index
= cluster
>> s
->refcount_block_bits
;
2359 refblock_start
= refblock_index
<< s
->refcount_block_bits
;
2361 /* Don't allocate a cluster in a refblock already written to disk */
2362 if (first_free_cluster
< refblock_start
) {
2363 first_free_cluster
= refblock_start
;
2365 refblock_offset
= alloc_clusters_imrt(bs
, 1, refcount_table
,
2366 nb_clusters
, &first_free_cluster
);
2367 if (refblock_offset
< 0) {
2368 fprintf(stderr
, "ERROR allocating refblock: %s\n",
2369 strerror(-refblock_offset
));
2370 res
->check_errors
++;
2371 ret
= refblock_offset
;
2375 if (reftable_size
<= refblock_index
) {
2376 uint32_t old_reftable_size
= reftable_size
;
2377 uint64_t *new_on_disk_reftable
;
2379 reftable_size
= ROUND_UP((refblock_index
+ 1) * sizeof(uint64_t),
2380 s
->cluster_size
) / sizeof(uint64_t);
2381 new_on_disk_reftable
= g_try_realloc(on_disk_reftable
,
2384 if (!new_on_disk_reftable
) {
2385 res
->check_errors
++;
2389 on_disk_reftable
= new_on_disk_reftable
;
2391 memset(on_disk_reftable
+ old_reftable_size
, 0,
2392 (reftable_size
- old_reftable_size
) * sizeof(uint64_t));
2394 /* The offset we have for the reftable is now no longer valid;
2395 * this will leak that range, but we can easily fix that by running
2396 * a leak-fixing check after this rebuild operation */
2397 reftable_offset
= -1;
2399 assert(on_disk_reftable
);
2401 on_disk_reftable
[refblock_index
] = refblock_offset
;
2403 /* If this is apparently the last refblock (for now), try to squeeze the
2405 if (refblock_index
== (*nb_clusters
- 1) >> s
->refcount_block_bits
&&
2406 reftable_offset
< 0)
2408 uint64_t reftable_clusters
= size_to_clusters(s
, reftable_size
*
2410 reftable_offset
= alloc_clusters_imrt(bs
, reftable_clusters
,
2411 refcount_table
, nb_clusters
,
2412 &first_free_cluster
);
2413 if (reftable_offset
< 0) {
2414 fprintf(stderr
, "ERROR allocating reftable: %s\n",
2415 strerror(-reftable_offset
));
2416 res
->check_errors
++;
2417 ret
= reftable_offset
;
2422 ret
= qcow2_pre_write_overlap_check(bs
, 0, refblock_offset
,
2423 s
->cluster_size
, false);
2425 fprintf(stderr
, "ERROR writing refblock: %s\n", strerror(-ret
));
2429 /* The size of *refcount_table is always cluster-aligned, therefore the
2430 * write operation will not overflow */
2431 on_disk_refblock
= (void *)((char *) *refcount_table
+
2432 refblock_index
* s
->cluster_size
);
2434 ret
= bdrv_pwrite(bs
->file
, refblock_offset
, on_disk_refblock
,
2437 fprintf(stderr
, "ERROR writing refblock: %s\n", strerror(-ret
));
2441 /* Go to the end of this refblock */
2442 cluster
= refblock_start
+ s
->refcount_block_size
- 1;
2445 if (reftable_offset
< 0) {
2446 uint64_t post_refblock_start
, reftable_clusters
;
2448 post_refblock_start
= ROUND_UP(*nb_clusters
, s
->refcount_block_size
);
2449 reftable_clusters
= size_to_clusters(s
,
2450 reftable_size
* sizeof(uint64_t));
2451 /* Not pretty but simple */
2452 if (first_free_cluster
< post_refblock_start
) {
2453 first_free_cluster
= post_refblock_start
;
2455 reftable_offset
= alloc_clusters_imrt(bs
, reftable_clusters
,
2456 refcount_table
, nb_clusters
,
2457 &first_free_cluster
);
2458 if (reftable_offset
< 0) {
2459 fprintf(stderr
, "ERROR allocating reftable: %s\n",
2460 strerror(-reftable_offset
));
2461 res
->check_errors
++;
2462 ret
= reftable_offset
;
2466 goto write_refblocks
;
2469 for (refblock_index
= 0; refblock_index
< reftable_size
; refblock_index
++) {
2470 cpu_to_be64s(&on_disk_reftable
[refblock_index
]);
2473 ret
= qcow2_pre_write_overlap_check(bs
, 0, reftable_offset
,
2474 reftable_size
* sizeof(uint64_t),
2477 fprintf(stderr
, "ERROR writing reftable: %s\n", strerror(-ret
));
2481 assert(reftable_size
< INT_MAX
/ sizeof(uint64_t));
2482 ret
= bdrv_pwrite(bs
->file
, reftable_offset
, on_disk_reftable
,
2483 reftable_size
* sizeof(uint64_t));
2485 fprintf(stderr
, "ERROR writing reftable: %s\n", strerror(-ret
));
2489 /* Enter new reftable into the image header */
2490 reftable_offset_and_clusters
.reftable_offset
= cpu_to_be64(reftable_offset
);
2491 reftable_offset_and_clusters
.reftable_clusters
=
2492 cpu_to_be32(size_to_clusters(s
, reftable_size
* sizeof(uint64_t)));
2493 ret
= bdrv_pwrite_sync(bs
->file
,
2494 offsetof(QCowHeader
, refcount_table_offset
),
2495 &reftable_offset_and_clusters
,
2496 sizeof(reftable_offset_and_clusters
));
2498 fprintf(stderr
, "ERROR setting reftable: %s\n", strerror(-ret
));
2502 for (refblock_index
= 0; refblock_index
< reftable_size
; refblock_index
++) {
2503 be64_to_cpus(&on_disk_reftable
[refblock_index
]);
2505 s
->refcount_table
= on_disk_reftable
;
2506 s
->refcount_table_offset
= reftable_offset
;
2507 s
->refcount_table_size
= reftable_size
;
2508 update_max_refcount_table_index(s
);
2513 g_free(on_disk_reftable
);
2518 * Checks an image for refcount consistency.
2520 * Returns 0 if no errors are found, the number of errors in case the image is
2521 * detected as corrupted, and -errno when an internal error occurred.
2523 int qcow2_check_refcounts(BlockDriverState
*bs
, BdrvCheckResult
*res
,
2526 BDRVQcow2State
*s
= bs
->opaque
;
2527 BdrvCheckResult pre_compare_res
;
2528 int64_t size
, highest_cluster
, nb_clusters
;
2529 void *refcount_table
= NULL
;
2530 bool rebuild
= false;
2533 size
= bdrv_getlength(bs
->file
->bs
);
2535 res
->check_errors
++;
2539 nb_clusters
= size_to_clusters(s
, size
);
2540 if (nb_clusters
> INT_MAX
) {
2541 res
->check_errors
++;
2545 res
->bfi
.total_clusters
=
2546 size_to_clusters(s
, bs
->total_sectors
* BDRV_SECTOR_SIZE
);
2548 ret
= calculate_refcounts(bs
, res
, fix
, &rebuild
, &refcount_table
,
2554 /* In case we don't need to rebuild the refcount structure (but want to fix
2555 * something), this function is immediately called again, in which case the
2556 * result should be ignored */
2557 pre_compare_res
= *res
;
2558 compare_refcounts(bs
, res
, 0, &rebuild
, &highest_cluster
, refcount_table
,
2561 if (rebuild
&& (fix
& BDRV_FIX_ERRORS
)) {
2562 BdrvCheckResult old_res
= *res
;
2563 int fresh_leaks
= 0;
2565 fprintf(stderr
, "Rebuilding refcount structure\n");
2566 ret
= rebuild_refcount_structure(bs
, res
, &refcount_table
,
2572 res
->corruptions
= 0;
2575 /* Because the old reftable has been exchanged for a new one the
2576 * references have to be recalculated */
2578 memset(refcount_table
, 0, refcount_array_byte_size(s
, nb_clusters
));
2579 ret
= calculate_refcounts(bs
, res
, 0, &rebuild
, &refcount_table
,
2585 if (fix
& BDRV_FIX_LEAKS
) {
2586 /* The old refcount structures are now leaked, fix it; the result
2587 * can be ignored, aside from leaks which were introduced by
2588 * rebuild_refcount_structure() that could not be fixed */
2589 BdrvCheckResult saved_res
= *res
;
2590 *res
= (BdrvCheckResult
){ 0 };
2592 compare_refcounts(bs
, res
, BDRV_FIX_LEAKS
, &rebuild
,
2593 &highest_cluster
, refcount_table
, nb_clusters
);
2595 fprintf(stderr
, "ERROR rebuilt refcount structure is still "
2599 /* Any leaks accounted for here were introduced by
2600 * rebuild_refcount_structure() because that function has created a
2601 * new refcount structure from scratch */
2602 fresh_leaks
= res
->leaks
;
2606 if (res
->corruptions
< old_res
.corruptions
) {
2607 res
->corruptions_fixed
+= old_res
.corruptions
- res
->corruptions
;
2609 if (res
->leaks
< old_res
.leaks
) {
2610 res
->leaks_fixed
+= old_res
.leaks
- res
->leaks
;
2612 res
->leaks
+= fresh_leaks
;
2615 fprintf(stderr
, "ERROR need to rebuild refcount structures\n");
2616 res
->check_errors
++;
2621 if (res
->leaks
|| res
->corruptions
) {
2622 *res
= pre_compare_res
;
2623 compare_refcounts(bs
, res
, fix
, &rebuild
, &highest_cluster
,
2624 refcount_table
, nb_clusters
);
2628 /* check OFLAG_COPIED */
2629 ret
= check_oflag_copied(bs
, res
, fix
);
2634 res
->image_end_offset
= (highest_cluster
+ 1) * s
->cluster_size
;
2638 g_free(refcount_table
);
2643 #define overlaps_with(ofs, sz) \
2644 ranges_overlap(offset, size, ofs, sz)
2647 * Checks if the given offset into the image file is actually free to use by
2648 * looking for overlaps with important metadata sections (L1/L2 tables etc.),
2649 * i.e. a sanity check without relying on the refcount tables.
2651 * The ign parameter specifies what checks not to perform (being a bitmask of
2652 * QCow2MetadataOverlap values), i.e., what sections to ignore.
2655 * - 0 if writing to this offset will not affect the mentioned metadata
2656 * - a positive QCow2MetadataOverlap value indicating one overlapping section
2657 * - a negative value (-errno) indicating an error while performing a check,
2658 * e.g. when bdrv_read failed on QCOW2_OL_INACTIVE_L2
2660 int qcow2_check_metadata_overlap(BlockDriverState
*bs
, int ign
, int64_t offset
,
2663 BDRVQcow2State
*s
= bs
->opaque
;
2664 int chk
= s
->overlap_check
& ~ign
;
2671 if (chk
& QCOW2_OL_MAIN_HEADER
) {
2672 if (offset
< s
->cluster_size
) {
2673 return QCOW2_OL_MAIN_HEADER
;
2677 /* align range to test to cluster boundaries */
2678 size
= ROUND_UP(offset_into_cluster(s
, offset
) + size
, s
->cluster_size
);
2679 offset
= start_of_cluster(s
, offset
);
2681 if ((chk
& QCOW2_OL_ACTIVE_L1
) && s
->l1_size
) {
2682 if (overlaps_with(s
->l1_table_offset
, s
->l1_size
* sizeof(uint64_t))) {
2683 return QCOW2_OL_ACTIVE_L1
;
2687 if ((chk
& QCOW2_OL_REFCOUNT_TABLE
) && s
->refcount_table_size
) {
2688 if (overlaps_with(s
->refcount_table_offset
,
2689 s
->refcount_table_size
* sizeof(uint64_t))) {
2690 return QCOW2_OL_REFCOUNT_TABLE
;
2694 if ((chk
& QCOW2_OL_SNAPSHOT_TABLE
) && s
->snapshots_size
) {
2695 if (overlaps_with(s
->snapshots_offset
, s
->snapshots_size
)) {
2696 return QCOW2_OL_SNAPSHOT_TABLE
;
2700 if ((chk
& QCOW2_OL_INACTIVE_L1
) && s
->snapshots
) {
2701 for (i
= 0; i
< s
->nb_snapshots
; i
++) {
2702 if (s
->snapshots
[i
].l1_size
&&
2703 overlaps_with(s
->snapshots
[i
].l1_table_offset
,
2704 s
->snapshots
[i
].l1_size
* sizeof(uint64_t))) {
2705 return QCOW2_OL_INACTIVE_L1
;
2710 if ((chk
& QCOW2_OL_ACTIVE_L2
) && s
->l1_table
) {
2711 for (i
= 0; i
< s
->l1_size
; i
++) {
2712 if ((s
->l1_table
[i
] & L1E_OFFSET_MASK
) &&
2713 overlaps_with(s
->l1_table
[i
] & L1E_OFFSET_MASK
,
2715 return QCOW2_OL_ACTIVE_L2
;
2720 if ((chk
& QCOW2_OL_REFCOUNT_BLOCK
) && s
->refcount_table
) {
2721 unsigned last_entry
= s
->max_refcount_table_index
;
2722 assert(last_entry
< s
->refcount_table_size
);
2723 assert(last_entry
+ 1 == s
->refcount_table_size
||
2724 (s
->refcount_table
[last_entry
+ 1] & REFT_OFFSET_MASK
) == 0);
2725 for (i
= 0; i
<= last_entry
; i
++) {
2726 if ((s
->refcount_table
[i
] & REFT_OFFSET_MASK
) &&
2727 overlaps_with(s
->refcount_table
[i
] & REFT_OFFSET_MASK
,
2729 return QCOW2_OL_REFCOUNT_BLOCK
;
2734 if ((chk
& QCOW2_OL_INACTIVE_L2
) && s
->snapshots
) {
2735 for (i
= 0; i
< s
->nb_snapshots
; i
++) {
2736 uint64_t l1_ofs
= s
->snapshots
[i
].l1_table_offset
;
2737 uint32_t l1_sz
= s
->snapshots
[i
].l1_size
;
2738 uint64_t l1_sz2
= l1_sz
* sizeof(uint64_t);
2742 ret
= qcow2_validate_table(bs
, l1_ofs
, l1_sz
, sizeof(uint64_t),
2743 QCOW_MAX_L1_SIZE
, "", NULL
);
2748 l1
= g_try_malloc(l1_sz2
);
2750 if (l1_sz2
&& l1
== NULL
) {
2754 ret
= bdrv_pread(bs
->file
, l1_ofs
, l1
, l1_sz2
);
2760 for (j
= 0; j
< l1_sz
; j
++) {
2761 uint64_t l2_ofs
= be64_to_cpu(l1
[j
]) & L1E_OFFSET_MASK
;
2762 if (l2_ofs
&& overlaps_with(l2_ofs
, s
->cluster_size
)) {
2764 return QCOW2_OL_INACTIVE_L2
;
2772 if ((chk
& QCOW2_OL_BITMAP_DIRECTORY
) &&
2773 (s
->autoclear_features
& QCOW2_AUTOCLEAR_BITMAPS
))
2775 if (overlaps_with(s
->bitmap_directory_offset
,
2776 s
->bitmap_directory_size
))
2778 return QCOW2_OL_BITMAP_DIRECTORY
;
2785 static const char *metadata_ol_names
[] = {
2786 [QCOW2_OL_MAIN_HEADER_BITNR
] = "qcow2_header",
2787 [QCOW2_OL_ACTIVE_L1_BITNR
] = "active L1 table",
2788 [QCOW2_OL_ACTIVE_L2_BITNR
] = "active L2 table",
2789 [QCOW2_OL_REFCOUNT_TABLE_BITNR
] = "refcount table",
2790 [QCOW2_OL_REFCOUNT_BLOCK_BITNR
] = "refcount block",
2791 [QCOW2_OL_SNAPSHOT_TABLE_BITNR
] = "snapshot table",
2792 [QCOW2_OL_INACTIVE_L1_BITNR
] = "inactive L1 table",
2793 [QCOW2_OL_INACTIVE_L2_BITNR
] = "inactive L2 table",
2794 [QCOW2_OL_BITMAP_DIRECTORY_BITNR
] = "bitmap directory",
2796 QEMU_BUILD_BUG_ON(QCOW2_OL_MAX_BITNR
!= ARRAY_SIZE(metadata_ol_names
));
2799 * First performs a check for metadata overlaps (through
2800 * qcow2_check_metadata_overlap); if that fails with a negative value (error
2801 * while performing a check), that value is returned. If an impending overlap
2802 * is detected, the BDS will be made unusable, the qcow2 file marked corrupt
2803 * and -EIO returned.
2805 * Returns 0 if there were neither overlaps nor errors while checking for
2806 * overlaps; or a negative value (-errno) on error.
2808 int qcow2_pre_write_overlap_check(BlockDriverState
*bs
, int ign
, int64_t offset
,
2809 int64_t size
, bool data_file
)
2813 if (data_file
&& has_data_file(bs
)) {
2817 ret
= qcow2_check_metadata_overlap(bs
, ign
, offset
, size
);
2820 } else if (ret
> 0) {
2821 int metadata_ol_bitnr
= ctz32(ret
);
2822 assert(metadata_ol_bitnr
< QCOW2_OL_MAX_BITNR
);
2824 qcow2_signal_corruption(bs
, true, offset
, size
, "Preventing invalid "
2825 "write on metadata (overlaps with %s)",
2826 metadata_ol_names
[metadata_ol_bitnr
]);
2833 /* A pointer to a function of this type is given to walk_over_reftable(). That
2834 * function will create refblocks and pass them to a RefblockFinishOp once they
2835 * are completed (@refblock). @refblock_empty is set if the refblock is
2838 * Along with the refblock, a corresponding reftable entry is passed, in the
2839 * reftable @reftable (which may be reallocated) at @reftable_index.
2841 * @allocated should be set to true if a new cluster has been allocated.
2843 typedef int (RefblockFinishOp
)(BlockDriverState
*bs
, uint64_t **reftable
,
2844 uint64_t reftable_index
, uint64_t *reftable_size
,
2845 void *refblock
, bool refblock_empty
,
2846 bool *allocated
, Error
**errp
);
2849 * This "operation" for walk_over_reftable() allocates the refblock on disk (if
2850 * it is not empty) and inserts its offset into the new reftable. The size of
2851 * this new reftable is increased as required.
2853 static int alloc_refblock(BlockDriverState
*bs
, uint64_t **reftable
,
2854 uint64_t reftable_index
, uint64_t *reftable_size
,
2855 void *refblock
, bool refblock_empty
, bool *allocated
,
2858 BDRVQcow2State
*s
= bs
->opaque
;
2861 if (!refblock_empty
&& reftable_index
>= *reftable_size
) {
2862 uint64_t *new_reftable
;
2863 uint64_t new_reftable_size
;
2865 new_reftable_size
= ROUND_UP(reftable_index
+ 1,
2866 s
->cluster_size
/ sizeof(uint64_t));
2867 if (new_reftable_size
> QCOW_MAX_REFTABLE_SIZE
/ sizeof(uint64_t)) {
2869 "This operation would make the refcount table grow "
2870 "beyond the maximum size supported by QEMU, aborting");
2874 new_reftable
= g_try_realloc(*reftable
, new_reftable_size
*
2876 if (!new_reftable
) {
2877 error_setg(errp
, "Failed to increase reftable buffer size");
2881 memset(new_reftable
+ *reftable_size
, 0,
2882 (new_reftable_size
- *reftable_size
) * sizeof(uint64_t));
2884 *reftable
= new_reftable
;
2885 *reftable_size
= new_reftable_size
;
2888 if (!refblock_empty
&& !(*reftable
)[reftable_index
]) {
2889 offset
= qcow2_alloc_clusters(bs
, s
->cluster_size
);
2891 error_setg_errno(errp
, -offset
, "Failed to allocate refblock");
2894 (*reftable
)[reftable_index
] = offset
;
2902 * This "operation" for walk_over_reftable() writes the refblock to disk at the
2903 * offset specified by the new reftable's entry. It does not modify the new
2904 * reftable or change any refcounts.
2906 static int flush_refblock(BlockDriverState
*bs
, uint64_t **reftable
,
2907 uint64_t reftable_index
, uint64_t *reftable_size
,
2908 void *refblock
, bool refblock_empty
, bool *allocated
,
2911 BDRVQcow2State
*s
= bs
->opaque
;
2915 if (reftable_index
< *reftable_size
&& (*reftable
)[reftable_index
]) {
2916 offset
= (*reftable
)[reftable_index
];
2918 ret
= qcow2_pre_write_overlap_check(bs
, 0, offset
, s
->cluster_size
,
2921 error_setg_errno(errp
, -ret
, "Overlap check failed");
2925 ret
= bdrv_pwrite(bs
->file
, offset
, refblock
, s
->cluster_size
);
2927 error_setg_errno(errp
, -ret
, "Failed to write refblock");
2931 assert(refblock_empty
);
2938 * This function walks over the existing reftable and every referenced refblock;
2939 * if @new_set_refcount is non-NULL, it is called for every refcount entry to
2940 * create an equal new entry in the passed @new_refblock. Once that
2941 * @new_refblock is completely filled, @operation will be called.
2943 * @status_cb and @cb_opaque are used for the amend operation's status callback.
2944 * @index is the index of the walk_over_reftable() calls and @total is the total
2945 * number of walk_over_reftable() calls per amend operation. Both are used for
2946 * calculating the parameters for the status callback.
2948 * @allocated is set to true if a new cluster has been allocated.
2950 static int walk_over_reftable(BlockDriverState
*bs
, uint64_t **new_reftable
,
2951 uint64_t *new_reftable_index
,
2952 uint64_t *new_reftable_size
,
2953 void *new_refblock
, int new_refblock_size
,
2954 int new_refcount_bits
,
2955 RefblockFinishOp
*operation
, bool *allocated
,
2956 Qcow2SetRefcountFunc
*new_set_refcount
,
2957 BlockDriverAmendStatusCB
*status_cb
,
2958 void *cb_opaque
, int index
, int total
,
2961 BDRVQcow2State
*s
= bs
->opaque
;
2962 uint64_t reftable_index
;
2963 bool new_refblock_empty
= true;
2965 int new_refblock_index
= 0;
2968 for (reftable_index
= 0; reftable_index
< s
->refcount_table_size
;
2971 uint64_t refblock_offset
= s
->refcount_table
[reftable_index
]
2974 status_cb(bs
, (uint64_t)index
* s
->refcount_table_size
+ reftable_index
,
2975 (uint64_t)total
* s
->refcount_table_size
, cb_opaque
);
2977 if (refblock_offset
) {
2980 if (offset_into_cluster(s
, refblock_offset
)) {
2981 qcow2_signal_corruption(bs
, true, -1, -1, "Refblock offset %#"
2982 PRIx64
" unaligned (reftable index: %#"
2983 PRIx64
")", refblock_offset
,
2986 "Image is corrupt (unaligned refblock offset)");
2990 ret
= qcow2_cache_get(bs
, s
->refcount_block_cache
, refblock_offset
,
2993 error_setg_errno(errp
, -ret
, "Failed to retrieve refblock");
2997 for (refblock_index
= 0; refblock_index
< s
->refcount_block_size
;
3002 if (new_refblock_index
>= new_refblock_size
) {
3003 /* new_refblock is now complete */
3004 ret
= operation(bs
, new_reftable
, *new_reftable_index
,
3005 new_reftable_size
, new_refblock
,
3006 new_refblock_empty
, allocated
, errp
);
3008 qcow2_cache_put(s
->refcount_block_cache
, &refblock
);
3012 (*new_reftable_index
)++;
3013 new_refblock_index
= 0;
3014 new_refblock_empty
= true;
3017 refcount
= s
->get_refcount(refblock
, refblock_index
);
3018 if (new_refcount_bits
< 64 && refcount
>> new_refcount_bits
) {
3021 qcow2_cache_put(s
->refcount_block_cache
, &refblock
);
3023 offset
= ((reftable_index
<< s
->refcount_block_bits
)
3024 + refblock_index
) << s
->cluster_bits
;
3026 error_setg(errp
, "Cannot decrease refcount entry width to "
3027 "%i bits: Cluster at offset %#" PRIx64
" has a "
3028 "refcount of %" PRIu64
, new_refcount_bits
,
3033 if (new_set_refcount
) {
3034 new_set_refcount(new_refblock
, new_refblock_index
++,
3037 new_refblock_index
++;
3039 new_refblock_empty
= new_refblock_empty
&& refcount
== 0;
3042 qcow2_cache_put(s
->refcount_block_cache
, &refblock
);
3044 /* No refblock means every refcount is 0 */
3045 for (refblock_index
= 0; refblock_index
< s
->refcount_block_size
;
3048 if (new_refblock_index
>= new_refblock_size
) {
3049 /* new_refblock is now complete */
3050 ret
= operation(bs
, new_reftable
, *new_reftable_index
,
3051 new_reftable_size
, new_refblock
,
3052 new_refblock_empty
, allocated
, errp
);
3057 (*new_reftable_index
)++;
3058 new_refblock_index
= 0;
3059 new_refblock_empty
= true;
3062 if (new_set_refcount
) {
3063 new_set_refcount(new_refblock
, new_refblock_index
++, 0);
3065 new_refblock_index
++;
3071 if (new_refblock_index
> 0) {
3072 /* Complete the potentially existing partially filled final refblock */
3073 if (new_set_refcount
) {
3074 for (; new_refblock_index
< new_refblock_size
;
3075 new_refblock_index
++)
3077 new_set_refcount(new_refblock
, new_refblock_index
, 0);
3081 ret
= operation(bs
, new_reftable
, *new_reftable_index
,
3082 new_reftable_size
, new_refblock
, new_refblock_empty
,
3088 (*new_reftable_index
)++;
3091 status_cb(bs
, (uint64_t)(index
+ 1) * s
->refcount_table_size
,
3092 (uint64_t)total
* s
->refcount_table_size
, cb_opaque
);
3097 int qcow2_change_refcount_order(BlockDriverState
*bs
, int refcount_order
,
3098 BlockDriverAmendStatusCB
*status_cb
,
3099 void *cb_opaque
, Error
**errp
)
3101 BDRVQcow2State
*s
= bs
->opaque
;
3102 Qcow2GetRefcountFunc
*new_get_refcount
;
3103 Qcow2SetRefcountFunc
*new_set_refcount
;
3104 void *new_refblock
= qemu_blockalign(bs
->file
->bs
, s
->cluster_size
);
3105 uint64_t *new_reftable
= NULL
, new_reftable_size
= 0;
3106 uint64_t *old_reftable
, old_reftable_size
, old_reftable_offset
;
3107 uint64_t new_reftable_index
= 0;
3109 int64_t new_reftable_offset
= 0, allocated_reftable_size
= 0;
3110 int new_refblock_size
, new_refcount_bits
= 1 << refcount_order
;
3111 int old_refcount_order
;
3114 bool new_allocation
;
3116 assert(s
->qcow_version
>= 3);
3117 assert(refcount_order
>= 0 && refcount_order
<= 6);
3119 /* see qcow2_open() */
3120 new_refblock_size
= 1 << (s
->cluster_bits
- (refcount_order
- 3));
3122 new_get_refcount
= get_refcount_funcs
[refcount_order
];
3123 new_set_refcount
= set_refcount_funcs
[refcount_order
];
3129 new_allocation
= false;
3131 /* At least we have to do this walk and the one which writes the
3132 * refblocks; also, at least we have to do this loop here at least
3133 * twice (normally), first to do the allocations, and second to
3134 * determine that everything is correctly allocated, this then makes
3135 * three walks in total */
3136 total_walks
= MAX(walk_index
+ 2, 3);
3138 /* First, allocate the structures so they are present in the refcount
3140 ret
= walk_over_reftable(bs
, &new_reftable
, &new_reftable_index
,
3141 &new_reftable_size
, NULL
, new_refblock_size
,
3142 new_refcount_bits
, &alloc_refblock
,
3143 &new_allocation
, NULL
, status_cb
, cb_opaque
,
3144 walk_index
++, total_walks
, errp
);
3149 new_reftable_index
= 0;
3151 if (new_allocation
) {
3152 if (new_reftable_offset
) {
3153 qcow2_free_clusters(bs
, new_reftable_offset
,
3154 allocated_reftable_size
* sizeof(uint64_t),
3155 QCOW2_DISCARD_NEVER
);
3158 new_reftable_offset
= qcow2_alloc_clusters(bs
, new_reftable_size
*
3160 if (new_reftable_offset
< 0) {
3161 error_setg_errno(errp
, -new_reftable_offset
,
3162 "Failed to allocate the new reftable");
3163 ret
= new_reftable_offset
;
3166 allocated_reftable_size
= new_reftable_size
;
3168 } while (new_allocation
);
3170 /* Second, write the new refblocks */
3171 ret
= walk_over_reftable(bs
, &new_reftable
, &new_reftable_index
,
3172 &new_reftable_size
, new_refblock
,
3173 new_refblock_size
, new_refcount_bits
,
3174 &flush_refblock
, &new_allocation
, new_set_refcount
,
3175 status_cb
, cb_opaque
, walk_index
, walk_index
+ 1,
3180 assert(!new_allocation
);
3183 /* Write the new reftable */
3184 ret
= qcow2_pre_write_overlap_check(bs
, 0, new_reftable_offset
,
3185 new_reftable_size
* sizeof(uint64_t),
3188 error_setg_errno(errp
, -ret
, "Overlap check failed");
3192 for (i
= 0; i
< new_reftable_size
; i
++) {
3193 cpu_to_be64s(&new_reftable
[i
]);
3196 ret
= bdrv_pwrite(bs
->file
, new_reftable_offset
, new_reftable
,
3197 new_reftable_size
* sizeof(uint64_t));
3199 for (i
= 0; i
< new_reftable_size
; i
++) {
3200 be64_to_cpus(&new_reftable
[i
]);
3204 error_setg_errno(errp
, -ret
, "Failed to write the new reftable");
3209 /* Empty the refcount cache */
3210 ret
= qcow2_cache_flush(bs
, s
->refcount_block_cache
);
3212 error_setg_errno(errp
, -ret
, "Failed to flush the refblock cache");
3216 /* Update the image header to point to the new reftable; this only updates
3217 * the fields which are relevant to qcow2_update_header(); other fields
3218 * such as s->refcount_table or s->refcount_bits stay stale for now
3219 * (because we have to restore everything if qcow2_update_header() fails) */
3220 old_refcount_order
= s
->refcount_order
;
3221 old_reftable_size
= s
->refcount_table_size
;
3222 old_reftable_offset
= s
->refcount_table_offset
;
3224 s
->refcount_order
= refcount_order
;
3225 s
->refcount_table_size
= new_reftable_size
;
3226 s
->refcount_table_offset
= new_reftable_offset
;
3228 ret
= qcow2_update_header(bs
);
3230 s
->refcount_order
= old_refcount_order
;
3231 s
->refcount_table_size
= old_reftable_size
;
3232 s
->refcount_table_offset
= old_reftable_offset
;
3233 error_setg_errno(errp
, -ret
, "Failed to update the qcow2 header");
3237 /* Now update the rest of the in-memory information */
3238 old_reftable
= s
->refcount_table
;
3239 s
->refcount_table
= new_reftable
;
3240 update_max_refcount_table_index(s
);
3242 s
->refcount_bits
= 1 << refcount_order
;
3243 s
->refcount_max
= UINT64_C(1) << (s
->refcount_bits
- 1);
3244 s
->refcount_max
+= s
->refcount_max
- 1;
3246 s
->refcount_block_bits
= s
->cluster_bits
- (refcount_order
- 3);
3247 s
->refcount_block_size
= 1 << s
->refcount_block_bits
;
3249 s
->get_refcount
= new_get_refcount
;
3250 s
->set_refcount
= new_set_refcount
;
3252 /* For cleaning up all old refblocks and the old reftable below the "done"
3254 new_reftable
= old_reftable
;
3255 new_reftable_size
= old_reftable_size
;
3256 new_reftable_offset
= old_reftable_offset
;
3260 /* On success, new_reftable actually points to the old reftable (and
3261 * new_reftable_size is the old reftable's size); but that is just
3263 for (i
= 0; i
< new_reftable_size
; i
++) {
3264 uint64_t offset
= new_reftable
[i
] & REFT_OFFSET_MASK
;
3266 qcow2_free_clusters(bs
, offset
, s
->cluster_size
,
3267 QCOW2_DISCARD_OTHER
);
3270 g_free(new_reftable
);
3272 if (new_reftable_offset
> 0) {
3273 qcow2_free_clusters(bs
, new_reftable_offset
,
3274 new_reftable_size
* sizeof(uint64_t),
3275 QCOW2_DISCARD_OTHER
);
3279 qemu_vfree(new_refblock
);
3283 static int64_t get_refblock_offset(BlockDriverState
*bs
, uint64_t offset
)
3285 BDRVQcow2State
*s
= bs
->opaque
;
3286 uint32_t index
= offset_to_reftable_index(s
, offset
);
3287 int64_t covering_refblock_offset
= 0;
3289 if (index
< s
->refcount_table_size
) {
3290 covering_refblock_offset
= s
->refcount_table
[index
] & REFT_OFFSET_MASK
;
3292 if (!covering_refblock_offset
) {
3293 qcow2_signal_corruption(bs
, true, -1, -1, "Refblock at %#" PRIx64
" is "
3294 "not covered by the refcount structures",
3299 return covering_refblock_offset
;
3302 static int qcow2_discard_refcount_block(BlockDriverState
*bs
,
3303 uint64_t discard_block_offs
)
3305 BDRVQcow2State
*s
= bs
->opaque
;
3306 int64_t refblock_offs
;
3307 uint64_t cluster_index
= discard_block_offs
>> s
->cluster_bits
;
3308 uint32_t block_index
= cluster_index
& (s
->refcount_block_size
- 1);
3312 refblock_offs
= get_refblock_offset(bs
, discard_block_offs
);
3313 if (refblock_offs
< 0) {
3314 return refblock_offs
;
3317 assert(discard_block_offs
!= 0);
3319 ret
= qcow2_cache_get(bs
, s
->refcount_block_cache
, refblock_offs
,
3325 if (s
->get_refcount(refblock
, block_index
) != 1) {
3326 qcow2_signal_corruption(bs
, true, -1, -1, "Invalid refcount:"
3327 " refblock offset %#" PRIx64
3328 ", reftable index %u"
3329 ", block offset %#" PRIx64
3330 ", refcount %#" PRIx64
,
3332 offset_to_reftable_index(s
, discard_block_offs
),
3334 s
->get_refcount(refblock
, block_index
));
3335 qcow2_cache_put(s
->refcount_block_cache
, &refblock
);
3338 s
->set_refcount(refblock
, block_index
, 0);
3340 qcow2_cache_entry_mark_dirty(s
->refcount_block_cache
, refblock
);
3342 qcow2_cache_put(s
->refcount_block_cache
, &refblock
);
3344 if (cluster_index
< s
->free_cluster_index
) {
3345 s
->free_cluster_index
= cluster_index
;
3348 refblock
= qcow2_cache_is_table_offset(s
->refcount_block_cache
,
3349 discard_block_offs
);
3351 /* discard refblock from the cache if refblock is cached */
3352 qcow2_cache_discard(s
->refcount_block_cache
, refblock
);
3354 update_refcount_discard(bs
, discard_block_offs
, s
->cluster_size
);
3359 int qcow2_shrink_reftable(BlockDriverState
*bs
)
3361 BDRVQcow2State
*s
= bs
->opaque
;
3362 uint64_t *reftable_tmp
=
3363 g_malloc(s
->refcount_table_size
* sizeof(uint64_t));
3366 for (i
= 0; i
< s
->refcount_table_size
; i
++) {
3367 int64_t refblock_offs
= s
->refcount_table
[i
] & REFT_OFFSET_MASK
;
3371 if (refblock_offs
== 0) {
3372 reftable_tmp
[i
] = 0;
3375 ret
= qcow2_cache_get(bs
, s
->refcount_block_cache
, refblock_offs
,
3381 /* the refblock has own reference */
3382 if (i
== offset_to_reftable_index(s
, refblock_offs
)) {
3383 uint64_t block_index
= (refblock_offs
>> s
->cluster_bits
) &
3384 (s
->refcount_block_size
- 1);
3385 uint64_t refcount
= s
->get_refcount(refblock
, block_index
);
3387 s
->set_refcount(refblock
, block_index
, 0);
3389 unused_block
= buffer_is_zero(refblock
, s
->cluster_size
);
3391 s
->set_refcount(refblock
, block_index
, refcount
);
3393 unused_block
= buffer_is_zero(refblock
, s
->cluster_size
);
3395 qcow2_cache_put(s
->refcount_block_cache
, &refblock
);
3397 reftable_tmp
[i
] = unused_block
? 0 : cpu_to_be64(s
->refcount_table
[i
]);
3400 ret
= bdrv_pwrite_sync(bs
->file
, s
->refcount_table_offset
, reftable_tmp
,
3401 s
->refcount_table_size
* sizeof(uint64_t));
3403 * If the write in the reftable failed the image may contain a partially
3404 * overwritten reftable. In this case it would be better to clear the
3405 * reftable in memory to avoid possible image corruption.
3407 for (i
= 0; i
< s
->refcount_table_size
; i
++) {
3408 if (s
->refcount_table
[i
] && !reftable_tmp
[i
]) {
3410 ret
= qcow2_discard_refcount_block(bs
, s
->refcount_table
[i
] &
3413 s
->refcount_table
[i
] = 0;
3417 if (!s
->cache_discards
) {
3418 qcow2_process_discards(bs
, ret
);
3422 g_free(reftable_tmp
);
3426 int64_t qcow2_get_last_cluster(BlockDriverState
*bs
, int64_t size
)
3428 BDRVQcow2State
*s
= bs
->opaque
;
3431 for (i
= size_to_clusters(s
, size
) - 1; i
>= 0; i
--) {
3433 int ret
= qcow2_get_refcount(bs
, i
, &refcount
);
3435 fprintf(stderr
, "Can't get refcount for cluster %" PRId64
": %s\n",
3443 qcow2_signal_corruption(bs
, true, -1, -1,
3444 "There are no references in the refcount table.");