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"
30 #include "qemu/range.h"
31 #include "qemu/bswap.h"
32 #include "qemu/cutils.h"
34 static int64_t alloc_clusters_noref(BlockDriverState
*bs
, uint64_t size
,
36 static int QEMU_WARN_UNUSED_RESULT
update_refcount(BlockDriverState
*bs
,
37 int64_t offset
, int64_t length
, uint64_t addend
,
38 bool decrease
, enum qcow2_discard_type type
);
40 static uint64_t get_refcount_ro0(const void *refcount_array
, uint64_t index
);
41 static uint64_t get_refcount_ro1(const void *refcount_array
, uint64_t index
);
42 static uint64_t get_refcount_ro2(const void *refcount_array
, uint64_t index
);
43 static uint64_t get_refcount_ro3(const void *refcount_array
, uint64_t index
);
44 static uint64_t get_refcount_ro4(const void *refcount_array
, uint64_t index
);
45 static uint64_t get_refcount_ro5(const void *refcount_array
, uint64_t index
);
46 static uint64_t get_refcount_ro6(const void *refcount_array
, uint64_t index
);
48 static void set_refcount_ro0(void *refcount_array
, uint64_t index
,
50 static void set_refcount_ro1(void *refcount_array
, uint64_t index
,
52 static void set_refcount_ro2(void *refcount_array
, uint64_t index
,
54 static void set_refcount_ro3(void *refcount_array
, uint64_t index
,
56 static void set_refcount_ro4(void *refcount_array
, uint64_t index
,
58 static void set_refcount_ro5(void *refcount_array
, uint64_t index
,
60 static void set_refcount_ro6(void *refcount_array
, uint64_t index
,
64 static Qcow2GetRefcountFunc
*const get_refcount_funcs
[] = {
74 static Qcow2SetRefcountFunc
*const set_refcount_funcs
[] = {
85 /*********************************************************/
86 /* refcount handling */
88 static void update_max_refcount_table_index(BDRVQcow2State
*s
)
90 unsigned i
= s
->refcount_table_size
- 1;
91 while (i
> 0 && (s
->refcount_table
[i
] & REFT_OFFSET_MASK
) == 0) {
94 /* Set s->max_refcount_table_index to the index of the last used entry */
95 s
->max_refcount_table_index
= i
;
98 int qcow2_refcount_init(BlockDriverState
*bs
)
100 BDRVQcow2State
*s
= bs
->opaque
;
101 unsigned int refcount_table_size2
, i
;
104 assert(s
->refcount_order
>= 0 && s
->refcount_order
<= 6);
106 s
->get_refcount
= get_refcount_funcs
[s
->refcount_order
];
107 s
->set_refcount
= set_refcount_funcs
[s
->refcount_order
];
109 assert(s
->refcount_table_size
<= INT_MAX
/ sizeof(uint64_t));
110 refcount_table_size2
= s
->refcount_table_size
* sizeof(uint64_t);
111 s
->refcount_table
= g_try_malloc(refcount_table_size2
);
113 if (s
->refcount_table_size
> 0) {
114 if (s
->refcount_table
== NULL
) {
118 BLKDBG_EVENT(bs
->file
, BLKDBG_REFTABLE_LOAD
);
119 ret
= bdrv_pread(bs
->file
, s
->refcount_table_offset
,
120 s
->refcount_table
, refcount_table_size2
);
124 for(i
= 0; i
< s
->refcount_table_size
; i
++)
125 be64_to_cpus(&s
->refcount_table
[i
]);
126 update_max_refcount_table_index(s
);
133 void qcow2_refcount_close(BlockDriverState
*bs
)
135 BDRVQcow2State
*s
= bs
->opaque
;
136 g_free(s
->refcount_table
);
140 static uint64_t get_refcount_ro0(const void *refcount_array
, uint64_t index
)
142 return (((const uint8_t *)refcount_array
)[index
/ 8] >> (index
% 8)) & 0x1;
145 static void set_refcount_ro0(void *refcount_array
, uint64_t index
,
148 assert(!(value
>> 1));
149 ((uint8_t *)refcount_array
)[index
/ 8] &= ~(0x1 << (index
% 8));
150 ((uint8_t *)refcount_array
)[index
/ 8] |= value
<< (index
% 8);
153 static uint64_t get_refcount_ro1(const void *refcount_array
, uint64_t index
)
155 return (((const uint8_t *)refcount_array
)[index
/ 4] >> (2 * (index
% 4)))
159 static void set_refcount_ro1(void *refcount_array
, uint64_t index
,
162 assert(!(value
>> 2));
163 ((uint8_t *)refcount_array
)[index
/ 4] &= ~(0x3 << (2 * (index
% 4)));
164 ((uint8_t *)refcount_array
)[index
/ 4] |= value
<< (2 * (index
% 4));
167 static uint64_t get_refcount_ro2(const void *refcount_array
, uint64_t index
)
169 return (((const uint8_t *)refcount_array
)[index
/ 2] >> (4 * (index
% 2)))
173 static void set_refcount_ro2(void *refcount_array
, uint64_t index
,
176 assert(!(value
>> 4));
177 ((uint8_t *)refcount_array
)[index
/ 2] &= ~(0xf << (4 * (index
% 2)));
178 ((uint8_t *)refcount_array
)[index
/ 2] |= value
<< (4 * (index
% 2));
181 static uint64_t get_refcount_ro3(const void *refcount_array
, uint64_t index
)
183 return ((const uint8_t *)refcount_array
)[index
];
186 static void set_refcount_ro3(void *refcount_array
, uint64_t index
,
189 assert(!(value
>> 8));
190 ((uint8_t *)refcount_array
)[index
] = value
;
193 static uint64_t get_refcount_ro4(const void *refcount_array
, uint64_t index
)
195 return be16_to_cpu(((const uint16_t *)refcount_array
)[index
]);
198 static void set_refcount_ro4(void *refcount_array
, uint64_t index
,
201 assert(!(value
>> 16));
202 ((uint16_t *)refcount_array
)[index
] = cpu_to_be16(value
);
205 static uint64_t get_refcount_ro5(const void *refcount_array
, uint64_t index
)
207 return be32_to_cpu(((const uint32_t *)refcount_array
)[index
]);
210 static void set_refcount_ro5(void *refcount_array
, uint64_t index
,
213 assert(!(value
>> 32));
214 ((uint32_t *)refcount_array
)[index
] = cpu_to_be32(value
);
217 static uint64_t get_refcount_ro6(const void *refcount_array
, uint64_t index
)
219 return be64_to_cpu(((const uint64_t *)refcount_array
)[index
]);
222 static void set_refcount_ro6(void *refcount_array
, uint64_t index
,
225 ((uint64_t *)refcount_array
)[index
] = cpu_to_be64(value
);
229 static int load_refcount_block(BlockDriverState
*bs
,
230 int64_t refcount_block_offset
,
231 void **refcount_block
)
233 BDRVQcow2State
*s
= bs
->opaque
;
235 BLKDBG_EVENT(bs
->file
, BLKDBG_REFBLOCK_LOAD
);
236 return qcow2_cache_get(bs
, s
->refcount_block_cache
, refcount_block_offset
,
241 * Retrieves the refcount of the cluster given by its index and stores it in
242 * *refcount. Returns 0 on success and -errno on failure.
244 int qcow2_get_refcount(BlockDriverState
*bs
, int64_t cluster_index
,
247 BDRVQcow2State
*s
= bs
->opaque
;
248 uint64_t refcount_table_index
, block_index
;
249 int64_t refcount_block_offset
;
251 void *refcount_block
;
253 refcount_table_index
= cluster_index
>> s
->refcount_block_bits
;
254 if (refcount_table_index
>= s
->refcount_table_size
) {
258 refcount_block_offset
=
259 s
->refcount_table
[refcount_table_index
] & REFT_OFFSET_MASK
;
260 if (!refcount_block_offset
) {
265 if (offset_into_cluster(s
, refcount_block_offset
)) {
266 qcow2_signal_corruption(bs
, true, -1, -1, "Refblock offset %#" PRIx64
267 " unaligned (reftable index: %#" PRIx64
")",
268 refcount_block_offset
, refcount_table_index
);
272 ret
= qcow2_cache_get(bs
, s
->refcount_block_cache
, refcount_block_offset
,
278 block_index
= cluster_index
& (s
->refcount_block_size
- 1);
279 *refcount
= s
->get_refcount(refcount_block
, block_index
);
281 qcow2_cache_put(s
->refcount_block_cache
, &refcount_block
);
286 /* Checks if two offsets are described by the same refcount block */
287 static int in_same_refcount_block(BDRVQcow2State
*s
, uint64_t offset_a
,
290 uint64_t block_a
= offset_a
>> (s
->cluster_bits
+ s
->refcount_block_bits
);
291 uint64_t block_b
= offset_b
>> (s
->cluster_bits
+ s
->refcount_block_bits
);
293 return (block_a
== block_b
);
297 * Loads a refcount block. If it doesn't exist yet, it is allocated first
298 * (including growing the refcount table if needed).
300 * Returns 0 on success or -errno in error case
302 static int alloc_refcount_block(BlockDriverState
*bs
,
303 int64_t cluster_index
, void **refcount_block
)
305 BDRVQcow2State
*s
= bs
->opaque
;
306 unsigned int refcount_table_index
;
309 BLKDBG_EVENT(bs
->file
, BLKDBG_REFBLOCK_ALLOC
);
311 /* Find the refcount block for the given cluster */
312 refcount_table_index
= cluster_index
>> s
->refcount_block_bits
;
314 if (refcount_table_index
< s
->refcount_table_size
) {
316 uint64_t refcount_block_offset
=
317 s
->refcount_table
[refcount_table_index
] & REFT_OFFSET_MASK
;
319 /* If it's already there, we're done */
320 if (refcount_block_offset
) {
321 if (offset_into_cluster(s
, refcount_block_offset
)) {
322 qcow2_signal_corruption(bs
, true, -1, -1, "Refblock offset %#"
323 PRIx64
" unaligned (reftable index: "
324 "%#x)", refcount_block_offset
,
325 refcount_table_index
);
329 return load_refcount_block(bs
, refcount_block_offset
,
335 * If we came here, we need to allocate something. Something is at least
336 * a cluster for the new refcount block. It may also include a new refcount
337 * table if the old refcount table is too small.
339 * Note that allocating clusters here needs some special care:
341 * - We can't use the normal qcow2_alloc_clusters(), it would try to
342 * increase the refcount and very likely we would end up with an endless
343 * recursion. Instead we must place the refcount blocks in a way that
344 * they can describe them themselves.
346 * - We need to consider that at this point we are inside update_refcounts
347 * and potentially doing an initial refcount increase. This means that
348 * some clusters have already been allocated by the caller, but their
349 * refcount isn't accurate yet. If we allocate clusters for metadata, we
350 * need to return -EAGAIN to signal the caller that it needs to restart
351 * the search for free clusters.
353 * - alloc_clusters_noref and qcow2_free_clusters may load a different
354 * refcount block into the cache
357 *refcount_block
= NULL
;
359 /* We write to the refcount table, so we might depend on L2 tables */
360 ret
= qcow2_cache_flush(bs
, s
->l2_table_cache
);
365 /* Allocate the refcount block itself and mark it as used */
366 int64_t new_block
= alloc_clusters_noref(bs
, s
->cluster_size
, INT64_MAX
);
371 /* The offset must fit in the offset field of the refcount table entry */
372 assert((new_block
& REFT_OFFSET_MASK
) == new_block
);
374 /* If we're allocating the block at offset 0 then something is wrong */
375 if (new_block
== 0) {
376 qcow2_signal_corruption(bs
, true, -1, -1, "Preventing invalid "
377 "allocation of refcount block at offset 0");
382 fprintf(stderr
, "qcow2: Allocate refcount block %d for %" PRIx64
384 refcount_table_index
, cluster_index
<< s
->cluster_bits
, new_block
);
387 if (in_same_refcount_block(s
, new_block
, cluster_index
<< s
->cluster_bits
)) {
388 /* Zero the new refcount block before updating it */
389 ret
= qcow2_cache_get_empty(bs
, s
->refcount_block_cache
, new_block
,
395 memset(*refcount_block
, 0, s
->cluster_size
);
397 /* The block describes itself, need to update the cache */
398 int block_index
= (new_block
>> s
->cluster_bits
) &
399 (s
->refcount_block_size
- 1);
400 s
->set_refcount(*refcount_block
, block_index
, 1);
402 /* Described somewhere else. This can recurse at most twice before we
403 * arrive at a block that describes itself. */
404 ret
= update_refcount(bs
, new_block
, s
->cluster_size
, 1, false,
405 QCOW2_DISCARD_NEVER
);
410 ret
= qcow2_cache_flush(bs
, s
->refcount_block_cache
);
415 /* Initialize the new refcount block only after updating its refcount,
416 * update_refcount uses the refcount cache itself */
417 ret
= qcow2_cache_get_empty(bs
, s
->refcount_block_cache
, new_block
,
423 memset(*refcount_block
, 0, s
->cluster_size
);
426 /* Now the new refcount block needs to be written to disk */
427 BLKDBG_EVENT(bs
->file
, BLKDBG_REFBLOCK_ALLOC_WRITE
);
428 qcow2_cache_entry_mark_dirty(s
->refcount_block_cache
, *refcount_block
);
429 ret
= qcow2_cache_flush(bs
, s
->refcount_block_cache
);
434 /* If the refcount table is big enough, just hook the block up there */
435 if (refcount_table_index
< s
->refcount_table_size
) {
436 uint64_t data64
= cpu_to_be64(new_block
);
437 BLKDBG_EVENT(bs
->file
, BLKDBG_REFBLOCK_ALLOC_HOOKUP
);
438 ret
= bdrv_pwrite_sync(bs
->file
,
439 s
->refcount_table_offset
+ refcount_table_index
* sizeof(uint64_t),
440 &data64
, sizeof(data64
));
445 s
->refcount_table
[refcount_table_index
] = new_block
;
446 /* If there's a hole in s->refcount_table then it can happen
447 * that refcount_table_index < s->max_refcount_table_index */
448 s
->max_refcount_table_index
=
449 MAX(s
->max_refcount_table_index
, refcount_table_index
);
451 /* The new refcount block may be where the caller intended to put its
452 * data, so let it restart the search. */
456 qcow2_cache_put(s
->refcount_block_cache
, refcount_block
);
459 * If we come here, we need to grow the refcount table. Again, a new
460 * refcount table needs some space and we can't simply allocate to avoid
463 * Therefore let's grab new refcount blocks at the end of the image, which
464 * will describe themselves and the new refcount table. This way we can
465 * reference them only in the new table and do the switch to the new
466 * refcount table at once without producing an inconsistent state in
469 BLKDBG_EVENT(bs
->file
, BLKDBG_REFTABLE_GROW
);
471 /* Calculate the number of refcount blocks needed so far; this will be the
472 * basis for calculating the index of the first cluster used for the
473 * self-describing refcount structures which we are about to create.
475 * Because we reached this point, there cannot be any refcount entries for
476 * cluster_index or higher indices yet. However, because new_block has been
477 * allocated to describe that cluster (and it will assume this role later
478 * on), we cannot use that index; also, new_block may actually have a higher
479 * cluster index than cluster_index, so it needs to be taken into account
480 * here (and 1 needs to be added to its value because that cluster is used).
482 uint64_t blocks_used
= DIV_ROUND_UP(MAX(cluster_index
+ 1,
483 (new_block
>> s
->cluster_bits
) + 1),
484 s
->refcount_block_size
);
486 /* Create the new refcount table and blocks */
487 uint64_t meta_offset
= (blocks_used
* s
->refcount_block_size
) *
490 ret
= qcow2_refcount_area(bs
, meta_offset
, 0, false,
491 refcount_table_index
, new_block
);
496 ret
= load_refcount_block(bs
, new_block
, refcount_block
);
501 /* If we were trying to do the initial refcount update for some cluster
502 * allocation, we might have used the same clusters to store newly
503 * allocated metadata. Make the caller search some new space. */
507 if (*refcount_block
!= NULL
) {
508 qcow2_cache_put(s
->refcount_block_cache
, refcount_block
);
514 * Starting at @start_offset, this function creates new self-covering refcount
515 * structures: A new refcount table and refcount blocks which cover all of
516 * themselves, and a number of @additional_clusters beyond their end.
517 * @start_offset must be at the end of the image file, that is, there must be
518 * only empty space beyond it.
519 * If @exact_size is false, the refcount table will have 50 % more entries than
520 * necessary so it will not need to grow again soon.
521 * If @new_refblock_offset is not zero, it contains the offset of a refcount
522 * block that should be entered into the new refcount table at index
523 * @new_refblock_index.
525 * Returns: The offset after the new refcount structures (i.e. where the
526 * @additional_clusters may be placed) on success, -errno on error.
528 int64_t qcow2_refcount_area(BlockDriverState
*bs
, uint64_t start_offset
,
529 uint64_t additional_clusters
, bool exact_size
,
530 int new_refblock_index
,
531 uint64_t new_refblock_offset
)
533 BDRVQcow2State
*s
= bs
->opaque
;
534 uint64_t total_refblock_count_u64
, additional_refblock_count
;
535 int total_refblock_count
, table_size
, area_reftable_index
, table_clusters
;
537 uint64_t table_offset
, block_offset
, end_offset
;
541 assert(!(start_offset
% s
->cluster_size
));
543 qcow2_refcount_metadata_size(start_offset
/ s
->cluster_size
+
545 s
->cluster_size
, s
->refcount_order
,
546 !exact_size
, &total_refblock_count_u64
);
547 if (total_refblock_count_u64
> QCOW_MAX_REFTABLE_SIZE
) {
550 total_refblock_count
= total_refblock_count_u64
;
552 /* Index in the refcount table of the first refcount block to cover the area
553 * of refcount structures we are about to create; we know that
554 * @total_refblock_count can cover @start_offset, so this will definitely
555 * fit into an int. */
556 area_reftable_index
= (start_offset
/ s
->cluster_size
) /
557 s
->refcount_block_size
;
560 table_size
= total_refblock_count
;
562 table_size
= total_refblock_count
+
563 DIV_ROUND_UP(total_refblock_count
, 2);
565 /* The qcow2 file can only store the reftable size in number of clusters */
566 table_size
= ROUND_UP(table_size
, s
->cluster_size
/ sizeof(uint64_t));
567 table_clusters
= (table_size
* sizeof(uint64_t)) / s
->cluster_size
;
569 if (table_size
> QCOW_MAX_REFTABLE_SIZE
) {
573 new_table
= g_try_new0(uint64_t, table_size
);
575 assert(table_size
> 0);
576 if (new_table
== NULL
) {
581 /* Fill the new refcount table */
582 if (table_size
> s
->max_refcount_table_index
) {
583 /* We're actually growing the reftable */
584 memcpy(new_table
, s
->refcount_table
,
585 (s
->max_refcount_table_index
+ 1) * sizeof(uint64_t));
587 /* Improbable case: We're shrinking the reftable. However, the caller
588 * has assured us that there is only empty space beyond @start_offset,
589 * so we can simply drop all of the refblocks that won't fit into the
591 memcpy(new_table
, s
->refcount_table
, table_size
* sizeof(uint64_t));
594 if (new_refblock_offset
) {
595 assert(new_refblock_index
< total_refblock_count
);
596 new_table
[new_refblock_index
] = new_refblock_offset
;
599 /* Count how many new refblocks we have to create */
600 additional_refblock_count
= 0;
601 for (i
= area_reftable_index
; i
< total_refblock_count
; i
++) {
603 additional_refblock_count
++;
607 table_offset
= start_offset
+ additional_refblock_count
* s
->cluster_size
;
608 end_offset
= table_offset
+ table_clusters
* s
->cluster_size
;
610 /* Fill the refcount blocks, and create new ones, if necessary */
611 block_offset
= start_offset
;
612 for (i
= area_reftable_index
; i
< total_refblock_count
; i
++) {
614 uint64_t first_offset_covered
;
616 /* Reuse an existing refblock if possible, create a new one otherwise */
618 ret
= qcow2_cache_get(bs
, s
->refcount_block_cache
, new_table
[i
],
624 ret
= qcow2_cache_get_empty(bs
, s
->refcount_block_cache
,
625 block_offset
, &refblock_data
);
629 memset(refblock_data
, 0, s
->cluster_size
);
630 qcow2_cache_entry_mark_dirty(s
->refcount_block_cache
,
633 new_table
[i
] = block_offset
;
634 block_offset
+= s
->cluster_size
;
637 /* First host offset covered by this refblock */
638 first_offset_covered
= (uint64_t)i
* s
->refcount_block_size
*
640 if (first_offset_covered
< end_offset
) {
643 /* Set the refcount of all of the new refcount structures to 1 */
645 if (first_offset_covered
< start_offset
) {
646 assert(i
== area_reftable_index
);
647 j
= (start_offset
- first_offset_covered
) / s
->cluster_size
;
648 assert(j
< s
->refcount_block_size
);
653 end_index
= MIN((end_offset
- first_offset_covered
) /
655 s
->refcount_block_size
);
657 for (; j
< end_index
; j
++) {
658 /* The caller guaranteed us this space would be empty */
659 assert(s
->get_refcount(refblock_data
, j
) == 0);
660 s
->set_refcount(refblock_data
, j
, 1);
663 qcow2_cache_entry_mark_dirty(s
->refcount_block_cache
,
667 qcow2_cache_put(s
->refcount_block_cache
, &refblock_data
);
670 assert(block_offset
== table_offset
);
672 /* Write refcount blocks to disk */
673 BLKDBG_EVENT(bs
->file
, BLKDBG_REFBLOCK_ALLOC_WRITE_BLOCKS
);
674 ret
= qcow2_cache_flush(bs
, s
->refcount_block_cache
);
679 /* Write refcount table to disk */
680 for (i
= 0; i
< total_refblock_count
; i
++) {
681 cpu_to_be64s(&new_table
[i
]);
684 BLKDBG_EVENT(bs
->file
, BLKDBG_REFBLOCK_ALLOC_WRITE_TABLE
);
685 ret
= bdrv_pwrite_sync(bs
->file
, table_offset
, new_table
,
686 table_size
* sizeof(uint64_t));
691 for (i
= 0; i
< total_refblock_count
; i
++) {
692 be64_to_cpus(&new_table
[i
]);
695 /* Hook up the new refcount table in the qcow2 header */
700 data
.d64
= cpu_to_be64(table_offset
);
701 data
.d32
= cpu_to_be32(table_clusters
);
702 BLKDBG_EVENT(bs
->file
, BLKDBG_REFBLOCK_ALLOC_SWITCH_TABLE
);
703 ret
= bdrv_pwrite_sync(bs
->file
,
704 offsetof(QCowHeader
, refcount_table_offset
),
705 &data
, sizeof(data
));
710 /* And switch it in memory */
711 uint64_t old_table_offset
= s
->refcount_table_offset
;
712 uint64_t old_table_size
= s
->refcount_table_size
;
714 g_free(s
->refcount_table
);
715 s
->refcount_table
= new_table
;
716 s
->refcount_table_size
= table_size
;
717 s
->refcount_table_offset
= table_offset
;
718 update_max_refcount_table_index(s
);
720 /* Free old table. */
721 qcow2_free_clusters(bs
, old_table_offset
, old_table_size
* sizeof(uint64_t),
722 QCOW2_DISCARD_OTHER
);
731 void qcow2_process_discards(BlockDriverState
*bs
, int ret
)
733 BDRVQcow2State
*s
= bs
->opaque
;
734 Qcow2DiscardRegion
*d
, *next
;
736 QTAILQ_FOREACH_SAFE(d
, &s
->discards
, next
, next
) {
737 QTAILQ_REMOVE(&s
->discards
, d
, next
);
739 /* Discard is optional, ignore the return value */
741 bdrv_pdiscard(bs
->file
, d
->offset
, d
->bytes
);
748 static void update_refcount_discard(BlockDriverState
*bs
,
749 uint64_t offset
, uint64_t length
)
751 BDRVQcow2State
*s
= bs
->opaque
;
752 Qcow2DiscardRegion
*d
, *p
, *next
;
754 QTAILQ_FOREACH(d
, &s
->discards
, next
) {
755 uint64_t new_start
= MIN(offset
, d
->offset
);
756 uint64_t new_end
= MAX(offset
+ length
, d
->offset
+ d
->bytes
);
758 if (new_end
- new_start
<= length
+ d
->bytes
) {
759 /* There can't be any overlap, areas ending up here have no
760 * references any more and therefore shouldn't get freed another
762 assert(d
->bytes
+ length
== new_end
- new_start
);
763 d
->offset
= new_start
;
764 d
->bytes
= new_end
- new_start
;
769 d
= g_malloc(sizeof(*d
));
770 *d
= (Qcow2DiscardRegion
) {
775 QTAILQ_INSERT_TAIL(&s
->discards
, d
, next
);
778 /* Merge discard requests if they are adjacent now */
779 QTAILQ_FOREACH_SAFE(p
, &s
->discards
, next
, next
) {
781 || p
->offset
> d
->offset
+ d
->bytes
782 || d
->offset
> p
->offset
+ p
->bytes
)
787 /* Still no overlap possible */
788 assert(p
->offset
== d
->offset
+ d
->bytes
789 || d
->offset
== p
->offset
+ p
->bytes
);
791 QTAILQ_REMOVE(&s
->discards
, p
, next
);
792 d
->offset
= MIN(d
->offset
, p
->offset
);
793 d
->bytes
+= p
->bytes
;
798 /* XXX: cache several refcount block clusters ? */
799 /* @addend is the absolute value of the addend; if @decrease is set, @addend
800 * will be subtracted from the current refcount, otherwise it will be added */
801 static int QEMU_WARN_UNUSED_RESULT
update_refcount(BlockDriverState
*bs
,
806 enum qcow2_discard_type type
)
808 BDRVQcow2State
*s
= bs
->opaque
;
809 int64_t start
, last
, cluster_offset
;
810 void *refcount_block
= NULL
;
811 int64_t old_table_index
= -1;
815 fprintf(stderr
, "update_refcount: offset=%" PRId64
" size=%" PRId64
816 " addend=%s%" PRIu64
"\n", offset
, length
, decrease
? "-" : "",
821 } else if (length
== 0) {
826 qcow2_cache_set_dependency(bs
, s
->refcount_block_cache
,
830 start
= start_of_cluster(s
, offset
);
831 last
= start_of_cluster(s
, offset
+ length
- 1);
832 for(cluster_offset
= start
; cluster_offset
<= last
;
833 cluster_offset
+= s
->cluster_size
)
837 int64_t cluster_index
= cluster_offset
>> s
->cluster_bits
;
838 int64_t table_index
= cluster_index
>> s
->refcount_block_bits
;
840 /* Load the refcount block and allocate it if needed */
841 if (table_index
!= old_table_index
) {
842 if (refcount_block
) {
843 qcow2_cache_put(s
->refcount_block_cache
, &refcount_block
);
845 ret
= alloc_refcount_block(bs
, cluster_index
, &refcount_block
);
846 /* If the caller needs to restart the search for free clusters,
847 * try the same ones first to see if they're still free. */
848 if (ret
== -EAGAIN
) {
849 if (s
->free_cluster_index
> (start
>> s
->cluster_bits
)) {
850 s
->free_cluster_index
= (start
>> s
->cluster_bits
);
857 old_table_index
= table_index
;
859 qcow2_cache_entry_mark_dirty(s
->refcount_block_cache
, refcount_block
);
861 /* we can update the count and save it */
862 block_index
= cluster_index
& (s
->refcount_block_size
- 1);
864 refcount
= s
->get_refcount(refcount_block
, block_index
);
865 if (decrease
? (refcount
- addend
> refcount
)
866 : (refcount
+ addend
< refcount
||
867 refcount
+ addend
> s
->refcount_max
))
877 if (refcount
== 0 && cluster_index
< s
->free_cluster_index
) {
878 s
->free_cluster_index
= cluster_index
;
880 s
->set_refcount(refcount_block
, block_index
, refcount
);
885 table
= qcow2_cache_is_table_offset(s
->refcount_block_cache
,
888 qcow2_cache_put(s
->refcount_block_cache
, &refcount_block
);
889 qcow2_cache_discard(s
->refcount_block_cache
, table
);
892 table
= qcow2_cache_is_table_offset(s
->l2_table_cache
, offset
);
894 qcow2_cache_discard(s
->l2_table_cache
, table
);
897 if (s
->discard_passthrough
[type
]) {
898 update_refcount_discard(bs
, cluster_offset
, s
->cluster_size
);
905 if (!s
->cache_discards
) {
906 qcow2_process_discards(bs
, ret
);
909 /* Write last changed block to disk */
910 if (refcount_block
) {
911 qcow2_cache_put(s
->refcount_block_cache
, &refcount_block
);
915 * Try do undo any updates if an error is returned (This may succeed in
916 * some cases like ENOSPC for allocating a new refcount block)
920 dummy
= update_refcount(bs
, offset
, cluster_offset
- offset
, addend
,
921 !decrease
, QCOW2_DISCARD_NEVER
);
929 * Increases or decreases the refcount of a given cluster.
931 * @addend is the absolute value of the addend; if @decrease is set, @addend
932 * will be subtracted from the current refcount, otherwise it will be added.
934 * On success 0 is returned; on failure -errno is returned.
936 int qcow2_update_cluster_refcount(BlockDriverState
*bs
,
937 int64_t cluster_index
,
938 uint64_t addend
, bool decrease
,
939 enum qcow2_discard_type type
)
941 BDRVQcow2State
*s
= bs
->opaque
;
944 ret
= update_refcount(bs
, cluster_index
<< s
->cluster_bits
, 1, addend
,
955 /*********************************************************/
956 /* cluster allocation functions */
960 /* return < 0 if error */
961 static int64_t alloc_clusters_noref(BlockDriverState
*bs
, uint64_t size
,
964 BDRVQcow2State
*s
= bs
->opaque
;
965 uint64_t i
, nb_clusters
, refcount
;
968 /* We can't allocate clusters if they may still be queued for discard. */
969 if (s
->cache_discards
) {
970 qcow2_process_discards(bs
, 0);
973 nb_clusters
= size_to_clusters(s
, size
);
975 for(i
= 0; i
< nb_clusters
; i
++) {
976 uint64_t next_cluster_index
= s
->free_cluster_index
++;
977 ret
= qcow2_get_refcount(bs
, next_cluster_index
, &refcount
);
981 } else if (refcount
!= 0) {
986 /* Make sure that all offsets in the "allocated" range are representable
987 * in the requested max */
988 if (s
->free_cluster_index
> 0 &&
989 s
->free_cluster_index
- 1 > (max
>> s
->cluster_bits
))
995 fprintf(stderr
, "alloc_clusters: size=%" PRId64
" -> %" PRId64
"\n",
997 (s
->free_cluster_index
- nb_clusters
) << s
->cluster_bits
);
999 return (s
->free_cluster_index
- nb_clusters
) << s
->cluster_bits
;
1002 int64_t qcow2_alloc_clusters(BlockDriverState
*bs
, uint64_t size
)
1007 BLKDBG_EVENT(bs
->file
, BLKDBG_CLUSTER_ALLOC
);
1009 offset
= alloc_clusters_noref(bs
, size
, QCOW_MAX_CLUSTER_OFFSET
);
1014 ret
= update_refcount(bs
, offset
, size
, 1, false, QCOW2_DISCARD_NEVER
);
1015 } while (ret
== -EAGAIN
);
1024 int64_t qcow2_alloc_clusters_at(BlockDriverState
*bs
, uint64_t offset
,
1025 int64_t nb_clusters
)
1027 BDRVQcow2State
*s
= bs
->opaque
;
1028 uint64_t cluster_index
, refcount
;
1032 assert(nb_clusters
>= 0);
1033 if (nb_clusters
== 0) {
1038 /* Check how many clusters there are free */
1039 cluster_index
= offset
>> s
->cluster_bits
;
1040 for(i
= 0; i
< nb_clusters
; i
++) {
1041 ret
= qcow2_get_refcount(bs
, cluster_index
++, &refcount
);
1044 } else if (refcount
!= 0) {
1049 /* And then allocate them */
1050 ret
= update_refcount(bs
, offset
, i
<< s
->cluster_bits
, 1, false,
1051 QCOW2_DISCARD_NEVER
);
1052 } while (ret
== -EAGAIN
);
1061 /* only used to allocate compressed sectors. We try to allocate
1062 contiguous sectors. size must be <= cluster_size */
1063 int64_t qcow2_alloc_bytes(BlockDriverState
*bs
, int size
)
1065 BDRVQcow2State
*s
= bs
->opaque
;
1067 size_t free_in_cluster
;
1070 BLKDBG_EVENT(bs
->file
, BLKDBG_CLUSTER_ALLOC_BYTES
);
1071 assert(size
> 0 && size
<= s
->cluster_size
);
1072 assert(!s
->free_byte_offset
|| offset_into_cluster(s
, s
->free_byte_offset
));
1074 offset
= s
->free_byte_offset
;
1078 ret
= qcow2_get_refcount(bs
, offset
>> s
->cluster_bits
, &refcount
);
1083 if (refcount
== s
->refcount_max
) {
1088 free_in_cluster
= s
->cluster_size
- offset_into_cluster(s
, offset
);
1090 if (!offset
|| free_in_cluster
< size
) {
1091 int64_t new_cluster
;
1093 new_cluster
= alloc_clusters_noref(bs
, s
->cluster_size
,
1094 MIN(s
->cluster_offset_mask
,
1095 QCOW_MAX_CLUSTER_OFFSET
));
1096 if (new_cluster
< 0) {
1100 if (new_cluster
== 0) {
1101 qcow2_signal_corruption(bs
, true, -1, -1, "Preventing invalid "
1102 "allocation of compressed cluster "
1107 if (!offset
|| ROUND_UP(offset
, s
->cluster_size
) != new_cluster
) {
1108 offset
= new_cluster
;
1109 free_in_cluster
= s
->cluster_size
;
1111 free_in_cluster
+= s
->cluster_size
;
1116 ret
= update_refcount(bs
, offset
, size
, 1, false, QCOW2_DISCARD_NEVER
);
1120 } while (ret
== -EAGAIN
);
1125 /* The cluster refcount was incremented; refcount blocks must be flushed
1126 * before the caller's L2 table updates. */
1127 qcow2_cache_set_dependency(bs
, s
->l2_table_cache
, s
->refcount_block_cache
);
1129 s
->free_byte_offset
= offset
+ size
;
1130 if (!offset_into_cluster(s
, s
->free_byte_offset
)) {
1131 s
->free_byte_offset
= 0;
1137 void qcow2_free_clusters(BlockDriverState
*bs
,
1138 int64_t offset
, int64_t size
,
1139 enum qcow2_discard_type type
)
1143 BLKDBG_EVENT(bs
->file
, BLKDBG_CLUSTER_FREE
);
1144 ret
= update_refcount(bs
, offset
, size
, 1, true, type
);
1146 fprintf(stderr
, "qcow2_free_clusters failed: %s\n", strerror(-ret
));
1147 /* TODO Remember the clusters to free them later and avoid leaking */
1152 * Free a cluster using its L2 entry (handles clusters of all types, e.g.
1153 * normal cluster, compressed cluster, etc.)
1155 void qcow2_free_any_clusters(BlockDriverState
*bs
, uint64_t l2_entry
,
1156 int nb_clusters
, enum qcow2_discard_type type
)
1158 BDRVQcow2State
*s
= bs
->opaque
;
1159 QCow2ClusterType ctype
= qcow2_get_cluster_type(bs
, l2_entry
);
1161 if (has_data_file(bs
)) {
1162 if (s
->discard_passthrough
[type
] &&
1163 (ctype
== QCOW2_CLUSTER_NORMAL
||
1164 ctype
== QCOW2_CLUSTER_ZERO_ALLOC
))
1166 bdrv_pdiscard(s
->data_file
, l2_entry
& L2E_OFFSET_MASK
,
1167 nb_clusters
<< s
->cluster_bits
);
1173 case QCOW2_CLUSTER_COMPRESSED
:
1176 nb_csectors
= ((l2_entry
>> s
->csize_shift
) &
1178 qcow2_free_clusters(bs
,
1179 (l2_entry
& s
->cluster_offset_mask
) & ~511,
1180 nb_csectors
* 512, type
);
1183 case QCOW2_CLUSTER_NORMAL
:
1184 case QCOW2_CLUSTER_ZERO_ALLOC
:
1185 if (offset_into_cluster(s
, l2_entry
& L2E_OFFSET_MASK
)) {
1186 qcow2_signal_corruption(bs
, false, -1, -1,
1187 "Cannot free unaligned cluster %#llx",
1188 l2_entry
& L2E_OFFSET_MASK
);
1190 qcow2_free_clusters(bs
, l2_entry
& L2E_OFFSET_MASK
,
1191 nb_clusters
<< s
->cluster_bits
, type
);
1194 case QCOW2_CLUSTER_ZERO_PLAIN
:
1195 case QCOW2_CLUSTER_UNALLOCATED
:
1202 int coroutine_fn
qcow2_write_caches(BlockDriverState
*bs
)
1204 BDRVQcow2State
*s
= bs
->opaque
;
1207 ret
= qcow2_cache_write(bs
, s
->l2_table_cache
);
1212 if (qcow2_need_accurate_refcounts(s
)) {
1213 ret
= qcow2_cache_write(bs
, s
->refcount_block_cache
);
1222 int coroutine_fn
qcow2_flush_caches(BlockDriverState
*bs
)
1224 int ret
= qcow2_write_caches(bs
);
1229 return bdrv_flush(bs
->file
->bs
);
1232 /*********************************************************/
1233 /* snapshots and image creation */
1237 /* update the refcounts of snapshots and the copied flag */
1238 int qcow2_update_snapshot_refcount(BlockDriverState
*bs
,
1239 int64_t l1_table_offset
, int l1_size
, int addend
)
1241 BDRVQcow2State
*s
= bs
->opaque
;
1242 uint64_t *l1_table
, *l2_slice
, l2_offset
, entry
, l1_size2
, refcount
;
1243 bool l1_allocated
= false;
1244 int64_t old_entry
, old_l2_offset
;
1245 unsigned slice
, slice_size2
, n_slices
;
1246 int i
, j
, l1_modified
= 0, nb_csectors
;
1249 assert(addend
>= -1 && addend
<= 1);
1253 l1_size2
= l1_size
* sizeof(uint64_t);
1254 slice_size2
= s
->l2_slice_size
* sizeof(uint64_t);
1255 n_slices
= s
->cluster_size
/ slice_size2
;
1257 s
->cache_discards
= true;
1259 /* WARNING: qcow2_snapshot_goto relies on this function not using the
1260 * l1_table_offset when it is the current s->l1_table_offset! Be careful
1261 * when changing this! */
1262 if (l1_table_offset
!= s
->l1_table_offset
) {
1263 l1_table
= g_try_malloc0(ROUND_UP(l1_size2
, 512));
1264 if (l1_size2
&& l1_table
== NULL
) {
1268 l1_allocated
= true;
1270 ret
= bdrv_pread(bs
->file
, l1_table_offset
, l1_table
, l1_size2
);
1275 for (i
= 0; i
< l1_size
; i
++) {
1276 be64_to_cpus(&l1_table
[i
]);
1279 assert(l1_size
== s
->l1_size
);
1280 l1_table
= s
->l1_table
;
1281 l1_allocated
= false;
1284 for (i
= 0; i
< l1_size
; i
++) {
1285 l2_offset
= l1_table
[i
];
1287 old_l2_offset
= l2_offset
;
1288 l2_offset
&= L1E_OFFSET_MASK
;
1290 if (offset_into_cluster(s
, l2_offset
)) {
1291 qcow2_signal_corruption(bs
, true, -1, -1, "L2 table offset %#"
1292 PRIx64
" unaligned (L1 index: %#x)",
1298 for (slice
= 0; slice
< n_slices
; slice
++) {
1299 ret
= qcow2_cache_get(bs
, s
->l2_table_cache
,
1300 l2_offset
+ slice
* slice_size2
,
1301 (void **) &l2_slice
);
1306 for (j
= 0; j
< s
->l2_slice_size
; j
++) {
1307 uint64_t cluster_index
;
1310 entry
= be64_to_cpu(l2_slice
[j
]);
1312 entry
&= ~QCOW_OFLAG_COPIED
;
1313 offset
= entry
& L2E_OFFSET_MASK
;
1315 switch (qcow2_get_cluster_type(bs
, entry
)) {
1316 case QCOW2_CLUSTER_COMPRESSED
:
1317 nb_csectors
= ((entry
>> s
->csize_shift
) &
1320 ret
= update_refcount(
1321 bs
, (entry
& s
->cluster_offset_mask
) & ~511,
1322 nb_csectors
* 512, abs(addend
), addend
< 0,
1323 QCOW2_DISCARD_SNAPSHOT
);
1328 /* compressed clusters are never modified */
1332 case QCOW2_CLUSTER_NORMAL
:
1333 case QCOW2_CLUSTER_ZERO_ALLOC
:
1334 if (offset_into_cluster(s
, offset
)) {
1335 /* Here l2_index means table (not slice) index */
1336 int l2_index
= slice
* s
->l2_slice_size
+ j
;
1337 qcow2_signal_corruption(
1338 bs
, true, -1, -1, "Cluster "
1339 "allocation offset %#" PRIx64
1340 " unaligned (L2 offset: %#"
1341 PRIx64
", L2 index: %#x)",
1342 offset
, l2_offset
, l2_index
);
1347 cluster_index
= offset
>> s
->cluster_bits
;
1348 assert(cluster_index
);
1350 ret
= qcow2_update_cluster_refcount(
1351 bs
, cluster_index
, abs(addend
), addend
< 0,
1352 QCOW2_DISCARD_SNAPSHOT
);
1358 ret
= qcow2_get_refcount(bs
, cluster_index
, &refcount
);
1364 case QCOW2_CLUSTER_ZERO_PLAIN
:
1365 case QCOW2_CLUSTER_UNALLOCATED
:
1373 if (refcount
== 1) {
1374 entry
|= QCOW_OFLAG_COPIED
;
1376 if (entry
!= old_entry
) {
1378 qcow2_cache_set_dependency(bs
, s
->l2_table_cache
,
1379 s
->refcount_block_cache
);
1381 l2_slice
[j
] = cpu_to_be64(entry
);
1382 qcow2_cache_entry_mark_dirty(s
->l2_table_cache
,
1387 qcow2_cache_put(s
->l2_table_cache
, (void **) &l2_slice
);
1391 ret
= qcow2_update_cluster_refcount(bs
, l2_offset
>>
1393 abs(addend
), addend
< 0,
1394 QCOW2_DISCARD_SNAPSHOT
);
1399 ret
= qcow2_get_refcount(bs
, l2_offset
>> s
->cluster_bits
,
1403 } else if (refcount
== 1) {
1404 l2_offset
|= QCOW_OFLAG_COPIED
;
1406 if (l2_offset
!= old_l2_offset
) {
1407 l1_table
[i
] = l2_offset
;
1413 ret
= bdrv_flush(bs
);
1416 qcow2_cache_put(s
->l2_table_cache
, (void **) &l2_slice
);
1419 s
->cache_discards
= false;
1420 qcow2_process_discards(bs
, ret
);
1422 /* Update L1 only if it isn't deleted anyway (addend = -1) */
1423 if (ret
== 0 && addend
>= 0 && l1_modified
) {
1424 for (i
= 0; i
< l1_size
; i
++) {
1425 cpu_to_be64s(&l1_table
[i
]);
1428 ret
= bdrv_pwrite_sync(bs
->file
, l1_table_offset
,
1429 l1_table
, l1_size2
);
1431 for (i
= 0; i
< l1_size
; i
++) {
1432 be64_to_cpus(&l1_table
[i
]);
1443 /*********************************************************/
1444 /* refcount checking functions */
1447 static uint64_t refcount_array_byte_size(BDRVQcow2State
*s
, uint64_t entries
)
1449 /* This assertion holds because there is no way we can address more than
1450 * 2^(64 - 9) clusters at once (with cluster size 512 = 2^9, and because
1451 * offsets have to be representable in bytes); due to every cluster
1452 * corresponding to one refcount entry, we are well below that limit */
1453 assert(entries
< (UINT64_C(1) << (64 - 9)));
1455 /* Thanks to the assertion this will not overflow, because
1456 * s->refcount_order < 7.
1457 * (note: x << s->refcount_order == x * s->refcount_bits) */
1458 return DIV_ROUND_UP(entries
<< s
->refcount_order
, 8);
1462 * Reallocates *array so that it can hold new_size entries. *size must contain
1463 * the current number of entries in *array. If the reallocation fails, *array
1464 * and *size will not be modified and -errno will be returned. If the
1465 * reallocation is successful, *array will be set to the new buffer, *size
1466 * will be set to new_size and 0 will be returned. The size of the reallocated
1467 * refcount array buffer will be aligned to a cluster boundary, and the newly
1468 * allocated area will be zeroed.
1470 static int realloc_refcount_array(BDRVQcow2State
*s
, void **array
,
1471 int64_t *size
, int64_t new_size
)
1473 int64_t old_byte_size
, new_byte_size
;
1476 /* Round to clusters so the array can be directly written to disk */
1477 old_byte_size
= size_to_clusters(s
, refcount_array_byte_size(s
, *size
))
1479 new_byte_size
= size_to_clusters(s
, refcount_array_byte_size(s
, new_size
))
1482 if (new_byte_size
== old_byte_size
) {
1487 assert(new_byte_size
> 0);
1489 if (new_byte_size
> SIZE_MAX
) {
1493 new_ptr
= g_try_realloc(*array
, new_byte_size
);
1498 if (new_byte_size
> old_byte_size
) {
1499 memset((char *)new_ptr
+ old_byte_size
, 0,
1500 new_byte_size
- old_byte_size
);
1510 * Increases the refcount for a range of clusters in a given refcount table.
1511 * This is used to construct a temporary refcount table out of L1 and L2 tables
1512 * which can be compared to the refcount table saved in the image.
1514 * Modifies the number of errors in res.
1516 int qcow2_inc_refcounts_imrt(BlockDriverState
*bs
, BdrvCheckResult
*res
,
1517 void **refcount_table
,
1518 int64_t *refcount_table_size
,
1519 int64_t offset
, int64_t size
)
1521 BDRVQcow2State
*s
= bs
->opaque
;
1522 uint64_t start
, last
, cluster_offset
, k
, refcount
;
1530 file_len
= bdrv_getlength(bs
->file
->bs
);
1536 * Last cluster of qcow2 image may be semi-allocated, so it may be OK to
1537 * reference some space after file end but it should be less than one
1540 if (offset
+ size
- file_len
>= s
->cluster_size
) {
1541 fprintf(stderr
, "ERROR: counting reference for region exceeding the "
1542 "end of the file by one cluster or more: offset 0x%" PRIx64
1543 " size 0x%" PRIx64
"\n", offset
, size
);
1548 start
= start_of_cluster(s
, offset
);
1549 last
= start_of_cluster(s
, offset
+ size
- 1);
1550 for(cluster_offset
= start
; cluster_offset
<= last
;
1551 cluster_offset
+= s
->cluster_size
) {
1552 k
= cluster_offset
>> s
->cluster_bits
;
1553 if (k
>= *refcount_table_size
) {
1554 ret
= realloc_refcount_array(s
, refcount_table
,
1555 refcount_table_size
, k
+ 1);
1557 res
->check_errors
++;
1562 refcount
= s
->get_refcount(*refcount_table
, k
);
1563 if (refcount
== s
->refcount_max
) {
1564 fprintf(stderr
, "ERROR: overflow cluster offset=0x%" PRIx64
1565 "\n", cluster_offset
);
1566 fprintf(stderr
, "Use qemu-img amend to increase the refcount entry "
1567 "width or qemu-img convert to create a clean copy if the "
1568 "image cannot be opened for writing\n");
1572 s
->set_refcount(*refcount_table
, k
, refcount
+ 1);
1578 /* Flags for check_refcounts_l1() and check_refcounts_l2() */
1580 CHECK_FRAG_INFO
= 0x2, /* update BlockFragInfo counters */
1584 * Increases the refcount in the given refcount table for the all clusters
1585 * referenced in the L2 table. While doing so, performs some checks on L2
1588 * Returns the number of errors found by the checks or -errno if an internal
1591 static int check_refcounts_l2(BlockDriverState
*bs
, BdrvCheckResult
*res
,
1592 void **refcount_table
,
1593 int64_t *refcount_table_size
, int64_t l2_offset
,
1594 int flags
, BdrvCheckMode fix
, bool active
)
1596 BDRVQcow2State
*s
= bs
->opaque
;
1597 uint64_t *l2_table
, l2_entry
;
1598 uint64_t next_contiguous_offset
= 0;
1599 int i
, l2_size
, nb_csectors
, ret
;
1601 /* Read L2 table from disk */
1602 l2_size
= s
->l2_size
* sizeof(uint64_t);
1603 l2_table
= g_malloc(l2_size
);
1605 ret
= bdrv_pread(bs
->file
, l2_offset
, l2_table
, l2_size
);
1607 fprintf(stderr
, "ERROR: I/O error in check_refcounts_l2\n");
1608 res
->check_errors
++;
1612 /* Do the actual checks */
1613 for(i
= 0; i
< s
->l2_size
; i
++) {
1614 l2_entry
= be64_to_cpu(l2_table
[i
]);
1616 switch (qcow2_get_cluster_type(bs
, l2_entry
)) {
1617 case QCOW2_CLUSTER_COMPRESSED
:
1618 /* Compressed clusters don't have QCOW_OFLAG_COPIED */
1619 if (l2_entry
& QCOW_OFLAG_COPIED
) {
1620 fprintf(stderr
, "ERROR: coffset=0x%" PRIx64
": "
1621 "copied flag must never be set for compressed "
1622 "clusters\n", l2_entry
& s
->cluster_offset_mask
);
1623 l2_entry
&= ~QCOW_OFLAG_COPIED
;
1627 if (has_data_file(bs
)) {
1628 fprintf(stderr
, "ERROR compressed cluster %d with data file, "
1629 "entry=0x%" PRIx64
"\n", i
, l2_entry
);
1634 /* Mark cluster as used */
1635 nb_csectors
= ((l2_entry
>> s
->csize_shift
) &
1637 l2_entry
&= s
->cluster_offset_mask
;
1638 ret
= qcow2_inc_refcounts_imrt(bs
, res
,
1639 refcount_table
, refcount_table_size
,
1640 l2_entry
& ~511, nb_csectors
* 512);
1645 if (flags
& CHECK_FRAG_INFO
) {
1646 res
->bfi
.allocated_clusters
++;
1647 res
->bfi
.compressed_clusters
++;
1649 /* Compressed clusters are fragmented by nature. Since they
1650 * take up sub-sector space but we only have sector granularity
1651 * I/O we need to re-read the same sectors even for adjacent
1652 * compressed clusters.
1654 res
->bfi
.fragmented_clusters
++;
1658 case QCOW2_CLUSTER_ZERO_ALLOC
:
1659 case QCOW2_CLUSTER_NORMAL
:
1661 uint64_t offset
= l2_entry
& L2E_OFFSET_MASK
;
1663 /* Correct offsets are cluster aligned */
1664 if (offset_into_cluster(s
, offset
)) {
1667 if (qcow2_get_cluster_type(bs
, l2_entry
) ==
1668 QCOW2_CLUSTER_ZERO_ALLOC
)
1670 fprintf(stderr
, "%s offset=%" PRIx64
": Preallocated zero "
1671 "cluster is not properly aligned; L2 entry "
1673 fix
& BDRV_FIX_ERRORS
? "Repairing" : "ERROR",
1675 if (fix
& BDRV_FIX_ERRORS
) {
1676 uint64_t l2e_offset
=
1677 l2_offset
+ (uint64_t)i
* sizeof(uint64_t);
1678 int ign
= active
? QCOW2_OL_ACTIVE_L2
:
1679 QCOW2_OL_INACTIVE_L2
;
1681 l2_entry
= QCOW_OFLAG_ZERO
;
1682 l2_table
[i
] = cpu_to_be64(l2_entry
);
1683 ret
= qcow2_pre_write_overlap_check(bs
, ign
,
1684 l2e_offset
, sizeof(uint64_t), false);
1686 fprintf(stderr
, "ERROR: Overlap check failed\n");
1687 res
->check_errors
++;
1688 /* Something is seriously wrong, so abort checking
1693 ret
= bdrv_pwrite_sync(bs
->file
, l2e_offset
,
1694 &l2_table
[i
], sizeof(uint64_t));
1696 fprintf(stderr
, "ERROR: Failed to overwrite L2 "
1697 "table entry: %s\n", strerror(-ret
));
1698 res
->check_errors
++;
1699 /* Do not abort, continue checking the rest of this
1700 * L2 table's entries */
1703 res
->corruptions_fixed
++;
1704 /* Skip marking the cluster as used
1705 * (it is unused now) */
1710 fprintf(stderr
, "ERROR offset=%" PRIx64
": Data cluster is "
1711 "not properly aligned; L2 entry corrupted.\n", offset
);
1715 if (flags
& CHECK_FRAG_INFO
) {
1716 res
->bfi
.allocated_clusters
++;
1717 if (next_contiguous_offset
&&
1718 offset
!= next_contiguous_offset
) {
1719 res
->bfi
.fragmented_clusters
++;
1721 next_contiguous_offset
= offset
+ s
->cluster_size
;
1724 /* Mark cluster as used */
1725 if (!has_data_file(bs
)) {
1726 ret
= qcow2_inc_refcounts_imrt(bs
, res
, refcount_table
,
1727 refcount_table_size
,
1728 offset
, s
->cluster_size
);
1736 case QCOW2_CLUSTER_ZERO_PLAIN
:
1737 case QCOW2_CLUSTER_UNALLOCATED
:
1754 * Increases the refcount for the L1 table, its L2 tables and all referenced
1755 * clusters in the given refcount table. While doing so, performs some checks
1756 * on L1 and L2 entries.
1758 * Returns the number of errors found by the checks or -errno if an internal
1761 static int check_refcounts_l1(BlockDriverState
*bs
,
1762 BdrvCheckResult
*res
,
1763 void **refcount_table
,
1764 int64_t *refcount_table_size
,
1765 int64_t l1_table_offset
, int l1_size
,
1766 int flags
, BdrvCheckMode fix
, bool active
)
1768 BDRVQcow2State
*s
= bs
->opaque
;
1769 uint64_t *l1_table
= NULL
, l2_offset
, l1_size2
;
1772 l1_size2
= l1_size
* sizeof(uint64_t);
1774 /* Mark L1 table as used */
1775 ret
= qcow2_inc_refcounts_imrt(bs
, res
, refcount_table
, refcount_table_size
,
1776 l1_table_offset
, l1_size2
);
1781 /* Read L1 table entries from disk */
1783 l1_table
= g_try_malloc(l1_size2
);
1784 if (l1_table
== NULL
) {
1786 res
->check_errors
++;
1789 ret
= bdrv_pread(bs
->file
, l1_table_offset
, l1_table
, l1_size2
);
1791 fprintf(stderr
, "ERROR: I/O error in check_refcounts_l1\n");
1792 res
->check_errors
++;
1795 for(i
= 0;i
< l1_size
; i
++)
1796 be64_to_cpus(&l1_table
[i
]);
1799 /* Do the actual checks */
1800 for(i
= 0; i
< l1_size
; i
++) {
1801 l2_offset
= l1_table
[i
];
1803 /* Mark L2 table as used */
1804 l2_offset
&= L1E_OFFSET_MASK
;
1805 ret
= qcow2_inc_refcounts_imrt(bs
, res
,
1806 refcount_table
, refcount_table_size
,
1807 l2_offset
, s
->cluster_size
);
1812 /* L2 tables are cluster aligned */
1813 if (offset_into_cluster(s
, l2_offset
)) {
1814 fprintf(stderr
, "ERROR l2_offset=%" PRIx64
": Table is not "
1815 "cluster aligned; L1 entry corrupted\n", l2_offset
);
1819 /* Process and check L2 entries */
1820 ret
= check_refcounts_l2(bs
, res
, refcount_table
,
1821 refcount_table_size
, l2_offset
, flags
,
1837 * Checks the OFLAG_COPIED flag for all L1 and L2 entries.
1839 * This function does not print an error message nor does it increment
1840 * check_errors if qcow2_get_refcount fails (this is because such an error will
1841 * have been already detected and sufficiently signaled by the calling function
1842 * (qcow2_check_refcounts) by the time this function is called).
1844 static int check_oflag_copied(BlockDriverState
*bs
, BdrvCheckResult
*res
,
1847 BDRVQcow2State
*s
= bs
->opaque
;
1848 uint64_t *l2_table
= qemu_blockalign(bs
, s
->cluster_size
);
1854 if (fix
& BDRV_FIX_ERRORS
) {
1857 } else if (fix
& BDRV_FIX_LEAKS
) {
1858 /* Repair only if that seems safe: This function is always
1859 * called after the refcounts have been fixed, so the refcount
1860 * is accurate if that repair was successful */
1861 repair
= !res
->check_errors
&& !res
->corruptions
&& !res
->leaks
;
1866 for (i
= 0; i
< s
->l1_size
; i
++) {
1867 uint64_t l1_entry
= s
->l1_table
[i
];
1868 uint64_t l2_offset
= l1_entry
& L1E_OFFSET_MASK
;
1875 ret
= qcow2_get_refcount(bs
, l2_offset
>> s
->cluster_bits
,
1878 /* don't print message nor increment check_errors */
1881 if ((refcount
== 1) != ((l1_entry
& QCOW_OFLAG_COPIED
) != 0)) {
1883 fprintf(stderr
, "%s OFLAG_COPIED L2 cluster: l1_index=%d "
1884 "l1_entry=%" PRIx64
" refcount=%" PRIu64
"\n",
1885 repair
? "Repairing" : "ERROR", i
, l1_entry
, refcount
);
1887 s
->l1_table
[i
] = refcount
== 1
1888 ? l1_entry
| QCOW_OFLAG_COPIED
1889 : l1_entry
& ~QCOW_OFLAG_COPIED
;
1890 ret
= qcow2_write_l1_entry(bs
, i
);
1892 res
->check_errors
++;
1896 res
->corruptions_fixed
++;
1900 ret
= bdrv_pread(bs
->file
, l2_offset
, l2_table
,
1901 s
->l2_size
* sizeof(uint64_t));
1903 fprintf(stderr
, "ERROR: Could not read L2 table: %s\n",
1905 res
->check_errors
++;
1909 for (j
= 0; j
< s
->l2_size
; j
++) {
1910 uint64_t l2_entry
= be64_to_cpu(l2_table
[j
]);
1911 uint64_t data_offset
= l2_entry
& L2E_OFFSET_MASK
;
1912 QCow2ClusterType cluster_type
= qcow2_get_cluster_type(bs
, l2_entry
);
1914 if (cluster_type
== QCOW2_CLUSTER_NORMAL
||
1915 cluster_type
== QCOW2_CLUSTER_ZERO_ALLOC
) {
1916 if (has_data_file(bs
)) {
1919 ret
= qcow2_get_refcount(bs
,
1920 data_offset
>> s
->cluster_bits
,
1923 /* don't print message nor increment check_errors */
1927 if ((refcount
== 1) != ((l2_entry
& QCOW_OFLAG_COPIED
) != 0)) {
1929 fprintf(stderr
, "%s OFLAG_COPIED data cluster: "
1930 "l2_entry=%" PRIx64
" refcount=%" PRIu64
"\n",
1931 repair
? "Repairing" : "ERROR", l2_entry
, refcount
);
1933 l2_table
[j
] = cpu_to_be64(refcount
== 1
1934 ? l2_entry
| QCOW_OFLAG_COPIED
1935 : l2_entry
& ~QCOW_OFLAG_COPIED
);
1943 ret
= qcow2_pre_write_overlap_check(bs
, QCOW2_OL_ACTIVE_L2
,
1944 l2_offset
, s
->cluster_size
,
1947 fprintf(stderr
, "ERROR: Could not write L2 table; metadata "
1948 "overlap check failed: %s\n", strerror(-ret
));
1949 res
->check_errors
++;
1953 ret
= bdrv_pwrite(bs
->file
, l2_offset
, l2_table
,
1956 fprintf(stderr
, "ERROR: Could not write L2 table: %s\n",
1958 res
->check_errors
++;
1961 res
->corruptions
-= l2_dirty
;
1962 res
->corruptions_fixed
+= l2_dirty
;
1969 qemu_vfree(l2_table
);
1974 * Checks consistency of refblocks and accounts for each refblock in
1977 static int check_refblocks(BlockDriverState
*bs
, BdrvCheckResult
*res
,
1978 BdrvCheckMode fix
, bool *rebuild
,
1979 void **refcount_table
, int64_t *nb_clusters
)
1981 BDRVQcow2State
*s
= bs
->opaque
;
1985 for(i
= 0; i
< s
->refcount_table_size
; i
++) {
1986 uint64_t offset
, cluster
;
1987 offset
= s
->refcount_table
[i
];
1988 cluster
= offset
>> s
->cluster_bits
;
1990 /* Refcount blocks are cluster aligned */
1991 if (offset_into_cluster(s
, offset
)) {
1992 fprintf(stderr
, "ERROR refcount block %" PRId64
" is not "
1993 "cluster aligned; refcount table entry corrupted\n", i
);
1999 if (cluster
>= *nb_clusters
) {
2001 fprintf(stderr
, "%s refcount block %" PRId64
" is outside image\n",
2002 fix
& BDRV_FIX_ERRORS
? "Repairing" : "ERROR", i
);
2004 if (fix
& BDRV_FIX_ERRORS
) {
2005 int64_t new_nb_clusters
;
2006 Error
*local_err
= NULL
;
2008 if (offset
> INT64_MAX
- s
->cluster_size
) {
2013 ret
= bdrv_truncate(bs
->file
, offset
+ s
->cluster_size
,
2014 PREALLOC_MODE_OFF
, &local_err
);
2016 error_report_err(local_err
);
2019 size
= bdrv_getlength(bs
->file
->bs
);
2025 new_nb_clusters
= size_to_clusters(s
, size
);
2026 assert(new_nb_clusters
>= *nb_clusters
);
2028 ret
= realloc_refcount_array(s
, refcount_table
,
2029 nb_clusters
, new_nb_clusters
);
2031 res
->check_errors
++;
2035 if (cluster
>= *nb_clusters
) {
2041 res
->corruptions_fixed
++;
2042 ret
= qcow2_inc_refcounts_imrt(bs
, res
,
2043 refcount_table
, nb_clusters
,
2044 offset
, s
->cluster_size
);
2048 /* No need to check whether the refcount is now greater than 1:
2049 * This area was just allocated and zeroed, so it can only be
2050 * exactly 1 after qcow2_inc_refcounts_imrt() */
2055 fprintf(stderr
, "ERROR could not resize image: %s\n",
2062 ret
= qcow2_inc_refcounts_imrt(bs
, res
, refcount_table
, nb_clusters
,
2063 offset
, s
->cluster_size
);
2067 if (s
->get_refcount(*refcount_table
, cluster
) != 1) {
2068 fprintf(stderr
, "ERROR refcount block %" PRId64
2069 " refcount=%" PRIu64
"\n", i
,
2070 s
->get_refcount(*refcount_table
, cluster
));
2081 * Calculates an in-memory refcount table.
2083 static int calculate_refcounts(BlockDriverState
*bs
, BdrvCheckResult
*res
,
2084 BdrvCheckMode fix
, bool *rebuild
,
2085 void **refcount_table
, int64_t *nb_clusters
)
2087 BDRVQcow2State
*s
= bs
->opaque
;
2092 if (!*refcount_table
) {
2093 int64_t old_size
= 0;
2094 ret
= realloc_refcount_array(s
, refcount_table
,
2095 &old_size
, *nb_clusters
);
2097 res
->check_errors
++;
2103 ret
= qcow2_inc_refcounts_imrt(bs
, res
, refcount_table
, nb_clusters
,
2104 0, s
->cluster_size
);
2109 /* current L1 table */
2110 ret
= check_refcounts_l1(bs
, res
, refcount_table
, nb_clusters
,
2111 s
->l1_table_offset
, s
->l1_size
, CHECK_FRAG_INFO
,
2118 if (has_data_file(bs
) && s
->nb_snapshots
) {
2119 fprintf(stderr
, "ERROR %d snapshots in image with data file\n",
2124 for (i
= 0; i
< s
->nb_snapshots
; i
++) {
2125 sn
= s
->snapshots
+ i
;
2126 if (offset_into_cluster(s
, sn
->l1_table_offset
)) {
2127 fprintf(stderr
, "ERROR snapshot %s (%s) l1_offset=%#" PRIx64
": "
2128 "L1 table is not cluster aligned; snapshot table entry "
2129 "corrupted\n", sn
->id_str
, sn
->name
, sn
->l1_table_offset
);
2133 if (sn
->l1_size
> QCOW_MAX_L1_SIZE
/ sizeof(uint64_t)) {
2134 fprintf(stderr
, "ERROR snapshot %s (%s) l1_size=%#" PRIx32
": "
2135 "L1 table is too large; snapshot table entry corrupted\n",
2136 sn
->id_str
, sn
->name
, sn
->l1_size
);
2140 ret
= check_refcounts_l1(bs
, res
, refcount_table
, nb_clusters
,
2141 sn
->l1_table_offset
, sn
->l1_size
, 0, fix
,
2147 ret
= qcow2_inc_refcounts_imrt(bs
, res
, refcount_table
, nb_clusters
,
2148 s
->snapshots_offset
, s
->snapshots_size
);
2154 ret
= qcow2_inc_refcounts_imrt(bs
, res
, refcount_table
, nb_clusters
,
2155 s
->refcount_table_offset
,
2156 s
->refcount_table_size
* sizeof(uint64_t));
2162 if (s
->crypto_header
.length
) {
2163 ret
= qcow2_inc_refcounts_imrt(bs
, res
, refcount_table
, nb_clusters
,
2164 s
->crypto_header
.offset
,
2165 s
->crypto_header
.length
);
2172 ret
= qcow2_check_bitmaps_refcounts(bs
, res
, refcount_table
, nb_clusters
);
2177 return check_refblocks(bs
, res
, fix
, rebuild
, refcount_table
, nb_clusters
);
2181 * Compares the actual reference count for each cluster in the image against the
2182 * refcount as reported by the refcount structures on-disk.
2184 static void compare_refcounts(BlockDriverState
*bs
, BdrvCheckResult
*res
,
2185 BdrvCheckMode fix
, bool *rebuild
,
2186 int64_t *highest_cluster
,
2187 void *refcount_table
, int64_t nb_clusters
)
2189 BDRVQcow2State
*s
= bs
->opaque
;
2191 uint64_t refcount1
, refcount2
;
2194 for (i
= 0, *highest_cluster
= 0; i
< nb_clusters
; i
++) {
2195 ret
= qcow2_get_refcount(bs
, i
, &refcount1
);
2197 fprintf(stderr
, "Can't get refcount for cluster %" PRId64
": %s\n",
2199 res
->check_errors
++;
2203 refcount2
= s
->get_refcount(refcount_table
, i
);
2205 if (refcount1
> 0 || refcount2
> 0) {
2206 *highest_cluster
= i
;
2209 if (refcount1
!= refcount2
) {
2210 /* Check if we're allowed to fix the mismatch */
2211 int *num_fixed
= NULL
;
2212 if (refcount1
== 0) {
2214 } else if (refcount1
> refcount2
&& (fix
& BDRV_FIX_LEAKS
)) {
2215 num_fixed
= &res
->leaks_fixed
;
2216 } else if (refcount1
< refcount2
&& (fix
& BDRV_FIX_ERRORS
)) {
2217 num_fixed
= &res
->corruptions_fixed
;
2220 fprintf(stderr
, "%s cluster %" PRId64
" refcount=%" PRIu64
2221 " reference=%" PRIu64
"\n",
2222 num_fixed
!= NULL
? "Repairing" :
2223 refcount1
< refcount2
? "ERROR" :
2225 i
, refcount1
, refcount2
);
2228 ret
= update_refcount(bs
, i
<< s
->cluster_bits
, 1,
2229 refcount_diff(refcount1
, refcount2
),
2230 refcount1
> refcount2
,
2231 QCOW2_DISCARD_ALWAYS
);
2238 /* And if we couldn't, print an error */
2239 if (refcount1
< refcount2
) {
2249 * Allocates clusters using an in-memory refcount table (IMRT) in contrast to
2250 * the on-disk refcount structures.
2252 * On input, *first_free_cluster tells where to start looking, and need not
2253 * actually be a free cluster; the returned offset will not be before that
2254 * cluster. On output, *first_free_cluster points to the first gap found, even
2255 * if that gap was too small to be used as the returned offset.
2257 * Note that *first_free_cluster is a cluster index whereas the return value is
2260 static int64_t alloc_clusters_imrt(BlockDriverState
*bs
,
2262 void **refcount_table
,
2263 int64_t *imrt_nb_clusters
,
2264 int64_t *first_free_cluster
)
2266 BDRVQcow2State
*s
= bs
->opaque
;
2267 int64_t cluster
= *first_free_cluster
, i
;
2268 bool first_gap
= true;
2269 int contiguous_free_clusters
;
2272 /* Starting at *first_free_cluster, find a range of at least cluster_count
2273 * continuously free clusters */
2274 for (contiguous_free_clusters
= 0;
2275 cluster
< *imrt_nb_clusters
&&
2276 contiguous_free_clusters
< cluster_count
;
2279 if (!s
->get_refcount(*refcount_table
, cluster
)) {
2280 contiguous_free_clusters
++;
2282 /* If this is the first free cluster found, update
2283 * *first_free_cluster accordingly */
2284 *first_free_cluster
= cluster
;
2287 } else if (contiguous_free_clusters
) {
2288 contiguous_free_clusters
= 0;
2292 /* If contiguous_free_clusters is greater than zero, it contains the number
2293 * of continuously free clusters until the current cluster; the first free
2294 * cluster in the current "gap" is therefore
2295 * cluster - contiguous_free_clusters */
2297 /* If no such range could be found, grow the in-memory refcount table
2298 * accordingly to append free clusters at the end of the image */
2299 if (contiguous_free_clusters
< cluster_count
) {
2300 /* contiguous_free_clusters clusters are already empty at the image end;
2301 * we need cluster_count clusters; therefore, we have to allocate
2302 * cluster_count - contiguous_free_clusters new clusters at the end of
2303 * the image (which is the current value of cluster; note that cluster
2304 * may exceed old_imrt_nb_clusters if *first_free_cluster pointed beyond
2306 ret
= realloc_refcount_array(s
, refcount_table
, imrt_nb_clusters
,
2307 cluster
+ cluster_count
2308 - contiguous_free_clusters
);
2314 /* Go back to the first free cluster */
2315 cluster
-= contiguous_free_clusters
;
2316 for (i
= 0; i
< cluster_count
; i
++) {
2317 s
->set_refcount(*refcount_table
, cluster
+ i
, 1);
2320 return cluster
<< s
->cluster_bits
;
2324 * Creates a new refcount structure based solely on the in-memory information
2325 * given through *refcount_table. All necessary allocations will be reflected
2328 * On success, the old refcount structure is leaked (it will be covered by the
2329 * new refcount structure).
2331 static int rebuild_refcount_structure(BlockDriverState
*bs
,
2332 BdrvCheckResult
*res
,
2333 void **refcount_table
,
2334 int64_t *nb_clusters
)
2336 BDRVQcow2State
*s
= bs
->opaque
;
2337 int64_t first_free_cluster
= 0, reftable_offset
= -1, cluster
= 0;
2338 int64_t refblock_offset
, refblock_start
, refblock_index
;
2339 uint32_t reftable_size
= 0;
2340 uint64_t *on_disk_reftable
= NULL
;
2341 void *on_disk_refblock
;
2344 uint64_t reftable_offset
;
2345 uint32_t reftable_clusters
;
2346 } QEMU_PACKED reftable_offset_and_clusters
;
2348 qcow2_cache_empty(bs
, s
->refcount_block_cache
);
2351 for (; cluster
< *nb_clusters
; cluster
++) {
2352 if (!s
->get_refcount(*refcount_table
, cluster
)) {
2356 refblock_index
= cluster
>> s
->refcount_block_bits
;
2357 refblock_start
= refblock_index
<< s
->refcount_block_bits
;
2359 /* Don't allocate a cluster in a refblock already written to disk */
2360 if (first_free_cluster
< refblock_start
) {
2361 first_free_cluster
= refblock_start
;
2363 refblock_offset
= alloc_clusters_imrt(bs
, 1, refcount_table
,
2364 nb_clusters
, &first_free_cluster
);
2365 if (refblock_offset
< 0) {
2366 fprintf(stderr
, "ERROR allocating refblock: %s\n",
2367 strerror(-refblock_offset
));
2368 res
->check_errors
++;
2369 ret
= refblock_offset
;
2373 if (reftable_size
<= refblock_index
) {
2374 uint32_t old_reftable_size
= reftable_size
;
2375 uint64_t *new_on_disk_reftable
;
2377 reftable_size
= ROUND_UP((refblock_index
+ 1) * sizeof(uint64_t),
2378 s
->cluster_size
) / sizeof(uint64_t);
2379 new_on_disk_reftable
= g_try_realloc(on_disk_reftable
,
2382 if (!new_on_disk_reftable
) {
2383 res
->check_errors
++;
2387 on_disk_reftable
= new_on_disk_reftable
;
2389 memset(on_disk_reftable
+ old_reftable_size
, 0,
2390 (reftable_size
- old_reftable_size
) * sizeof(uint64_t));
2392 /* The offset we have for the reftable is now no longer valid;
2393 * this will leak that range, but we can easily fix that by running
2394 * a leak-fixing check after this rebuild operation */
2395 reftable_offset
= -1;
2397 assert(on_disk_reftable
);
2399 on_disk_reftable
[refblock_index
] = refblock_offset
;
2401 /* If this is apparently the last refblock (for now), try to squeeze the
2403 if (refblock_index
== (*nb_clusters
- 1) >> s
->refcount_block_bits
&&
2404 reftable_offset
< 0)
2406 uint64_t reftable_clusters
= size_to_clusters(s
, reftable_size
*
2408 reftable_offset
= alloc_clusters_imrt(bs
, reftable_clusters
,
2409 refcount_table
, nb_clusters
,
2410 &first_free_cluster
);
2411 if (reftable_offset
< 0) {
2412 fprintf(stderr
, "ERROR allocating reftable: %s\n",
2413 strerror(-reftable_offset
));
2414 res
->check_errors
++;
2415 ret
= reftable_offset
;
2420 ret
= qcow2_pre_write_overlap_check(bs
, 0, refblock_offset
,
2421 s
->cluster_size
, false);
2423 fprintf(stderr
, "ERROR writing refblock: %s\n", strerror(-ret
));
2427 /* The size of *refcount_table is always cluster-aligned, therefore the
2428 * write operation will not overflow */
2429 on_disk_refblock
= (void *)((char *) *refcount_table
+
2430 refblock_index
* s
->cluster_size
);
2432 ret
= bdrv_pwrite(bs
->file
, refblock_offset
, on_disk_refblock
,
2435 fprintf(stderr
, "ERROR writing refblock: %s\n", strerror(-ret
));
2439 /* Go to the end of this refblock */
2440 cluster
= refblock_start
+ s
->refcount_block_size
- 1;
2443 if (reftable_offset
< 0) {
2444 uint64_t post_refblock_start
, reftable_clusters
;
2446 post_refblock_start
= ROUND_UP(*nb_clusters
, s
->refcount_block_size
);
2447 reftable_clusters
= size_to_clusters(s
,
2448 reftable_size
* sizeof(uint64_t));
2449 /* Not pretty but simple */
2450 if (first_free_cluster
< post_refblock_start
) {
2451 first_free_cluster
= post_refblock_start
;
2453 reftable_offset
= alloc_clusters_imrt(bs
, reftable_clusters
,
2454 refcount_table
, nb_clusters
,
2455 &first_free_cluster
);
2456 if (reftable_offset
< 0) {
2457 fprintf(stderr
, "ERROR allocating reftable: %s\n",
2458 strerror(-reftable_offset
));
2459 res
->check_errors
++;
2460 ret
= reftable_offset
;
2464 goto write_refblocks
;
2467 for (refblock_index
= 0; refblock_index
< reftable_size
; refblock_index
++) {
2468 cpu_to_be64s(&on_disk_reftable
[refblock_index
]);
2471 ret
= qcow2_pre_write_overlap_check(bs
, 0, reftable_offset
,
2472 reftable_size
* sizeof(uint64_t),
2475 fprintf(stderr
, "ERROR writing reftable: %s\n", strerror(-ret
));
2479 assert(reftable_size
< INT_MAX
/ sizeof(uint64_t));
2480 ret
= bdrv_pwrite(bs
->file
, reftable_offset
, on_disk_reftable
,
2481 reftable_size
* sizeof(uint64_t));
2483 fprintf(stderr
, "ERROR writing reftable: %s\n", strerror(-ret
));
2487 /* Enter new reftable into the image header */
2488 reftable_offset_and_clusters
.reftable_offset
= cpu_to_be64(reftable_offset
);
2489 reftable_offset_and_clusters
.reftable_clusters
=
2490 cpu_to_be32(size_to_clusters(s
, reftable_size
* sizeof(uint64_t)));
2491 ret
= bdrv_pwrite_sync(bs
->file
,
2492 offsetof(QCowHeader
, refcount_table_offset
),
2493 &reftable_offset_and_clusters
,
2494 sizeof(reftable_offset_and_clusters
));
2496 fprintf(stderr
, "ERROR setting reftable: %s\n", strerror(-ret
));
2500 for (refblock_index
= 0; refblock_index
< reftable_size
; refblock_index
++) {
2501 be64_to_cpus(&on_disk_reftable
[refblock_index
]);
2503 s
->refcount_table
= on_disk_reftable
;
2504 s
->refcount_table_offset
= reftable_offset
;
2505 s
->refcount_table_size
= reftable_size
;
2506 update_max_refcount_table_index(s
);
2511 g_free(on_disk_reftable
);
2516 * Checks an image for refcount consistency.
2518 * Returns 0 if no errors are found, the number of errors in case the image is
2519 * detected as corrupted, and -errno when an internal error occurred.
2521 int qcow2_check_refcounts(BlockDriverState
*bs
, BdrvCheckResult
*res
,
2524 BDRVQcow2State
*s
= bs
->opaque
;
2525 BdrvCheckResult pre_compare_res
;
2526 int64_t size
, highest_cluster
, nb_clusters
;
2527 void *refcount_table
= NULL
;
2528 bool rebuild
= false;
2531 size
= bdrv_getlength(bs
->file
->bs
);
2533 res
->check_errors
++;
2537 nb_clusters
= size_to_clusters(s
, size
);
2538 if (nb_clusters
> INT_MAX
) {
2539 res
->check_errors
++;
2543 res
->bfi
.total_clusters
=
2544 size_to_clusters(s
, bs
->total_sectors
* BDRV_SECTOR_SIZE
);
2546 ret
= calculate_refcounts(bs
, res
, fix
, &rebuild
, &refcount_table
,
2552 /* In case we don't need to rebuild the refcount structure (but want to fix
2553 * something), this function is immediately called again, in which case the
2554 * result should be ignored */
2555 pre_compare_res
= *res
;
2556 compare_refcounts(bs
, res
, 0, &rebuild
, &highest_cluster
, refcount_table
,
2559 if (rebuild
&& (fix
& BDRV_FIX_ERRORS
)) {
2560 BdrvCheckResult old_res
= *res
;
2561 int fresh_leaks
= 0;
2563 fprintf(stderr
, "Rebuilding refcount structure\n");
2564 ret
= rebuild_refcount_structure(bs
, res
, &refcount_table
,
2570 res
->corruptions
= 0;
2573 /* Because the old reftable has been exchanged for a new one the
2574 * references have to be recalculated */
2576 memset(refcount_table
, 0, refcount_array_byte_size(s
, nb_clusters
));
2577 ret
= calculate_refcounts(bs
, res
, 0, &rebuild
, &refcount_table
,
2583 if (fix
& BDRV_FIX_LEAKS
) {
2584 /* The old refcount structures are now leaked, fix it; the result
2585 * can be ignored, aside from leaks which were introduced by
2586 * rebuild_refcount_structure() that could not be fixed */
2587 BdrvCheckResult saved_res
= *res
;
2588 *res
= (BdrvCheckResult
){ 0 };
2590 compare_refcounts(bs
, res
, BDRV_FIX_LEAKS
, &rebuild
,
2591 &highest_cluster
, refcount_table
, nb_clusters
);
2593 fprintf(stderr
, "ERROR rebuilt refcount structure is still "
2597 /* Any leaks accounted for here were introduced by
2598 * rebuild_refcount_structure() because that function has created a
2599 * new refcount structure from scratch */
2600 fresh_leaks
= res
->leaks
;
2604 if (res
->corruptions
< old_res
.corruptions
) {
2605 res
->corruptions_fixed
+= old_res
.corruptions
- res
->corruptions
;
2607 if (res
->leaks
< old_res
.leaks
) {
2608 res
->leaks_fixed
+= old_res
.leaks
- res
->leaks
;
2610 res
->leaks
+= fresh_leaks
;
2613 fprintf(stderr
, "ERROR need to rebuild refcount structures\n");
2614 res
->check_errors
++;
2619 if (res
->leaks
|| res
->corruptions
) {
2620 *res
= pre_compare_res
;
2621 compare_refcounts(bs
, res
, fix
, &rebuild
, &highest_cluster
,
2622 refcount_table
, nb_clusters
);
2626 /* check OFLAG_COPIED */
2627 ret
= check_oflag_copied(bs
, res
, fix
);
2632 res
->image_end_offset
= (highest_cluster
+ 1) * s
->cluster_size
;
2636 g_free(refcount_table
);
2641 #define overlaps_with(ofs, sz) \
2642 ranges_overlap(offset, size, ofs, sz)
2645 * Checks if the given offset into the image file is actually free to use by
2646 * looking for overlaps with important metadata sections (L1/L2 tables etc.),
2647 * i.e. a sanity check without relying on the refcount tables.
2649 * The ign parameter specifies what checks not to perform (being a bitmask of
2650 * QCow2MetadataOverlap values), i.e., what sections to ignore.
2653 * - 0 if writing to this offset will not affect the mentioned metadata
2654 * - a positive QCow2MetadataOverlap value indicating one overlapping section
2655 * - a negative value (-errno) indicating an error while performing a check,
2656 * e.g. when bdrv_read failed on QCOW2_OL_INACTIVE_L2
2658 int qcow2_check_metadata_overlap(BlockDriverState
*bs
, int ign
, int64_t offset
,
2661 BDRVQcow2State
*s
= bs
->opaque
;
2662 int chk
= s
->overlap_check
& ~ign
;
2669 if (chk
& QCOW2_OL_MAIN_HEADER
) {
2670 if (offset
< s
->cluster_size
) {
2671 return QCOW2_OL_MAIN_HEADER
;
2675 /* align range to test to cluster boundaries */
2676 size
= ROUND_UP(offset_into_cluster(s
, offset
) + size
, s
->cluster_size
);
2677 offset
= start_of_cluster(s
, offset
);
2679 if ((chk
& QCOW2_OL_ACTIVE_L1
) && s
->l1_size
) {
2680 if (overlaps_with(s
->l1_table_offset
, s
->l1_size
* sizeof(uint64_t))) {
2681 return QCOW2_OL_ACTIVE_L1
;
2685 if ((chk
& QCOW2_OL_REFCOUNT_TABLE
) && s
->refcount_table_size
) {
2686 if (overlaps_with(s
->refcount_table_offset
,
2687 s
->refcount_table_size
* sizeof(uint64_t))) {
2688 return QCOW2_OL_REFCOUNT_TABLE
;
2692 if ((chk
& QCOW2_OL_SNAPSHOT_TABLE
) && s
->snapshots_size
) {
2693 if (overlaps_with(s
->snapshots_offset
, s
->snapshots_size
)) {
2694 return QCOW2_OL_SNAPSHOT_TABLE
;
2698 if ((chk
& QCOW2_OL_INACTIVE_L1
) && s
->snapshots
) {
2699 for (i
= 0; i
< s
->nb_snapshots
; i
++) {
2700 if (s
->snapshots
[i
].l1_size
&&
2701 overlaps_with(s
->snapshots
[i
].l1_table_offset
,
2702 s
->snapshots
[i
].l1_size
* sizeof(uint64_t))) {
2703 return QCOW2_OL_INACTIVE_L1
;
2708 if ((chk
& QCOW2_OL_ACTIVE_L2
) && s
->l1_table
) {
2709 for (i
= 0; i
< s
->l1_size
; i
++) {
2710 if ((s
->l1_table
[i
] & L1E_OFFSET_MASK
) &&
2711 overlaps_with(s
->l1_table
[i
] & L1E_OFFSET_MASK
,
2713 return QCOW2_OL_ACTIVE_L2
;
2718 if ((chk
& QCOW2_OL_REFCOUNT_BLOCK
) && s
->refcount_table
) {
2719 unsigned last_entry
= s
->max_refcount_table_index
;
2720 assert(last_entry
< s
->refcount_table_size
);
2721 assert(last_entry
+ 1 == s
->refcount_table_size
||
2722 (s
->refcount_table
[last_entry
+ 1] & REFT_OFFSET_MASK
) == 0);
2723 for (i
= 0; i
<= last_entry
; i
++) {
2724 if ((s
->refcount_table
[i
] & REFT_OFFSET_MASK
) &&
2725 overlaps_with(s
->refcount_table
[i
] & REFT_OFFSET_MASK
,
2727 return QCOW2_OL_REFCOUNT_BLOCK
;
2732 if ((chk
& QCOW2_OL_INACTIVE_L2
) && s
->snapshots
) {
2733 for (i
= 0; i
< s
->nb_snapshots
; i
++) {
2734 uint64_t l1_ofs
= s
->snapshots
[i
].l1_table_offset
;
2735 uint32_t l1_sz
= s
->snapshots
[i
].l1_size
;
2736 uint64_t l1_sz2
= l1_sz
* sizeof(uint64_t);
2740 ret
= qcow2_validate_table(bs
, l1_ofs
, l1_sz
, sizeof(uint64_t),
2741 QCOW_MAX_L1_SIZE
, "", NULL
);
2746 l1
= g_try_malloc(l1_sz2
);
2748 if (l1_sz2
&& l1
== NULL
) {
2752 ret
= bdrv_pread(bs
->file
, l1_ofs
, l1
, l1_sz2
);
2758 for (j
= 0; j
< l1_sz
; j
++) {
2759 uint64_t l2_ofs
= be64_to_cpu(l1
[j
]) & L1E_OFFSET_MASK
;
2760 if (l2_ofs
&& overlaps_with(l2_ofs
, s
->cluster_size
)) {
2762 return QCOW2_OL_INACTIVE_L2
;
2770 if ((chk
& QCOW2_OL_BITMAP_DIRECTORY
) &&
2771 (s
->autoclear_features
& QCOW2_AUTOCLEAR_BITMAPS
))
2773 if (overlaps_with(s
->bitmap_directory_offset
,
2774 s
->bitmap_directory_size
))
2776 return QCOW2_OL_BITMAP_DIRECTORY
;
2783 static const char *metadata_ol_names
[] = {
2784 [QCOW2_OL_MAIN_HEADER_BITNR
] = "qcow2_header",
2785 [QCOW2_OL_ACTIVE_L1_BITNR
] = "active L1 table",
2786 [QCOW2_OL_ACTIVE_L2_BITNR
] = "active L2 table",
2787 [QCOW2_OL_REFCOUNT_TABLE_BITNR
] = "refcount table",
2788 [QCOW2_OL_REFCOUNT_BLOCK_BITNR
] = "refcount block",
2789 [QCOW2_OL_SNAPSHOT_TABLE_BITNR
] = "snapshot table",
2790 [QCOW2_OL_INACTIVE_L1_BITNR
] = "inactive L1 table",
2791 [QCOW2_OL_INACTIVE_L2_BITNR
] = "inactive L2 table",
2792 [QCOW2_OL_BITMAP_DIRECTORY_BITNR
] = "bitmap directory",
2794 QEMU_BUILD_BUG_ON(QCOW2_OL_MAX_BITNR
!= ARRAY_SIZE(metadata_ol_names
));
2797 * First performs a check for metadata overlaps (through
2798 * qcow2_check_metadata_overlap); if that fails with a negative value (error
2799 * while performing a check), that value is returned. If an impending overlap
2800 * is detected, the BDS will be made unusable, the qcow2 file marked corrupt
2801 * and -EIO returned.
2803 * Returns 0 if there were neither overlaps nor errors while checking for
2804 * overlaps; or a negative value (-errno) on error.
2806 int qcow2_pre_write_overlap_check(BlockDriverState
*bs
, int ign
, int64_t offset
,
2807 int64_t size
, bool data_file
)
2811 if (data_file
&& has_data_file(bs
)) {
2815 ret
= qcow2_check_metadata_overlap(bs
, ign
, offset
, size
);
2818 } else if (ret
> 0) {
2819 int metadata_ol_bitnr
= ctz32(ret
);
2820 assert(metadata_ol_bitnr
< QCOW2_OL_MAX_BITNR
);
2822 qcow2_signal_corruption(bs
, true, offset
, size
, "Preventing invalid "
2823 "write on metadata (overlaps with %s)",
2824 metadata_ol_names
[metadata_ol_bitnr
]);
2831 /* A pointer to a function of this type is given to walk_over_reftable(). That
2832 * function will create refblocks and pass them to a RefblockFinishOp once they
2833 * are completed (@refblock). @refblock_empty is set if the refblock is
2836 * Along with the refblock, a corresponding reftable entry is passed, in the
2837 * reftable @reftable (which may be reallocated) at @reftable_index.
2839 * @allocated should be set to true if a new cluster has been allocated.
2841 typedef int (RefblockFinishOp
)(BlockDriverState
*bs
, uint64_t **reftable
,
2842 uint64_t reftable_index
, uint64_t *reftable_size
,
2843 void *refblock
, bool refblock_empty
,
2844 bool *allocated
, Error
**errp
);
2847 * This "operation" for walk_over_reftable() allocates the refblock on disk (if
2848 * it is not empty) and inserts its offset into the new reftable. The size of
2849 * this new reftable is increased as required.
2851 static int alloc_refblock(BlockDriverState
*bs
, uint64_t **reftable
,
2852 uint64_t reftable_index
, uint64_t *reftable_size
,
2853 void *refblock
, bool refblock_empty
, bool *allocated
,
2856 BDRVQcow2State
*s
= bs
->opaque
;
2859 if (!refblock_empty
&& reftable_index
>= *reftable_size
) {
2860 uint64_t *new_reftable
;
2861 uint64_t new_reftable_size
;
2863 new_reftable_size
= ROUND_UP(reftable_index
+ 1,
2864 s
->cluster_size
/ sizeof(uint64_t));
2865 if (new_reftable_size
> QCOW_MAX_REFTABLE_SIZE
/ sizeof(uint64_t)) {
2867 "This operation would make the refcount table grow "
2868 "beyond the maximum size supported by QEMU, aborting");
2872 new_reftable
= g_try_realloc(*reftable
, new_reftable_size
*
2874 if (!new_reftable
) {
2875 error_setg(errp
, "Failed to increase reftable buffer size");
2879 memset(new_reftable
+ *reftable_size
, 0,
2880 (new_reftable_size
- *reftable_size
) * sizeof(uint64_t));
2882 *reftable
= new_reftable
;
2883 *reftable_size
= new_reftable_size
;
2886 if (!refblock_empty
&& !(*reftable
)[reftable_index
]) {
2887 offset
= qcow2_alloc_clusters(bs
, s
->cluster_size
);
2889 error_setg_errno(errp
, -offset
, "Failed to allocate refblock");
2892 (*reftable
)[reftable_index
] = offset
;
2900 * This "operation" for walk_over_reftable() writes the refblock to disk at the
2901 * offset specified by the new reftable's entry. It does not modify the new
2902 * reftable or change any refcounts.
2904 static int flush_refblock(BlockDriverState
*bs
, uint64_t **reftable
,
2905 uint64_t reftable_index
, uint64_t *reftable_size
,
2906 void *refblock
, bool refblock_empty
, bool *allocated
,
2909 BDRVQcow2State
*s
= bs
->opaque
;
2913 if (reftable_index
< *reftable_size
&& (*reftable
)[reftable_index
]) {
2914 offset
= (*reftable
)[reftable_index
];
2916 ret
= qcow2_pre_write_overlap_check(bs
, 0, offset
, s
->cluster_size
,
2919 error_setg_errno(errp
, -ret
, "Overlap check failed");
2923 ret
= bdrv_pwrite(bs
->file
, offset
, refblock
, s
->cluster_size
);
2925 error_setg_errno(errp
, -ret
, "Failed to write refblock");
2929 assert(refblock_empty
);
2936 * This function walks over the existing reftable and every referenced refblock;
2937 * if @new_set_refcount is non-NULL, it is called for every refcount entry to
2938 * create an equal new entry in the passed @new_refblock. Once that
2939 * @new_refblock is completely filled, @operation will be called.
2941 * @status_cb and @cb_opaque are used for the amend operation's status callback.
2942 * @index is the index of the walk_over_reftable() calls and @total is the total
2943 * number of walk_over_reftable() calls per amend operation. Both are used for
2944 * calculating the parameters for the status callback.
2946 * @allocated is set to true if a new cluster has been allocated.
2948 static int walk_over_reftable(BlockDriverState
*bs
, uint64_t **new_reftable
,
2949 uint64_t *new_reftable_index
,
2950 uint64_t *new_reftable_size
,
2951 void *new_refblock
, int new_refblock_size
,
2952 int new_refcount_bits
,
2953 RefblockFinishOp
*operation
, bool *allocated
,
2954 Qcow2SetRefcountFunc
*new_set_refcount
,
2955 BlockDriverAmendStatusCB
*status_cb
,
2956 void *cb_opaque
, int index
, int total
,
2959 BDRVQcow2State
*s
= bs
->opaque
;
2960 uint64_t reftable_index
;
2961 bool new_refblock_empty
= true;
2963 int new_refblock_index
= 0;
2966 for (reftable_index
= 0; reftable_index
< s
->refcount_table_size
;
2969 uint64_t refblock_offset
= s
->refcount_table
[reftable_index
]
2972 status_cb(bs
, (uint64_t)index
* s
->refcount_table_size
+ reftable_index
,
2973 (uint64_t)total
* s
->refcount_table_size
, cb_opaque
);
2975 if (refblock_offset
) {
2978 if (offset_into_cluster(s
, refblock_offset
)) {
2979 qcow2_signal_corruption(bs
, true, -1, -1, "Refblock offset %#"
2980 PRIx64
" unaligned (reftable index: %#"
2981 PRIx64
")", refblock_offset
,
2984 "Image is corrupt (unaligned refblock offset)");
2988 ret
= qcow2_cache_get(bs
, s
->refcount_block_cache
, refblock_offset
,
2991 error_setg_errno(errp
, -ret
, "Failed to retrieve refblock");
2995 for (refblock_index
= 0; refblock_index
< s
->refcount_block_size
;
3000 if (new_refblock_index
>= new_refblock_size
) {
3001 /* new_refblock is now complete */
3002 ret
= operation(bs
, new_reftable
, *new_reftable_index
,
3003 new_reftable_size
, new_refblock
,
3004 new_refblock_empty
, allocated
, errp
);
3006 qcow2_cache_put(s
->refcount_block_cache
, &refblock
);
3010 (*new_reftable_index
)++;
3011 new_refblock_index
= 0;
3012 new_refblock_empty
= true;
3015 refcount
= s
->get_refcount(refblock
, refblock_index
);
3016 if (new_refcount_bits
< 64 && refcount
>> new_refcount_bits
) {
3019 qcow2_cache_put(s
->refcount_block_cache
, &refblock
);
3021 offset
= ((reftable_index
<< s
->refcount_block_bits
)
3022 + refblock_index
) << s
->cluster_bits
;
3024 error_setg(errp
, "Cannot decrease refcount entry width to "
3025 "%i bits: Cluster at offset %#" PRIx64
" has a "
3026 "refcount of %" PRIu64
, new_refcount_bits
,
3031 if (new_set_refcount
) {
3032 new_set_refcount(new_refblock
, new_refblock_index
++,
3035 new_refblock_index
++;
3037 new_refblock_empty
= new_refblock_empty
&& refcount
== 0;
3040 qcow2_cache_put(s
->refcount_block_cache
, &refblock
);
3042 /* No refblock means every refcount is 0 */
3043 for (refblock_index
= 0; refblock_index
< s
->refcount_block_size
;
3046 if (new_refblock_index
>= new_refblock_size
) {
3047 /* new_refblock is now complete */
3048 ret
= operation(bs
, new_reftable
, *new_reftable_index
,
3049 new_reftable_size
, new_refblock
,
3050 new_refblock_empty
, allocated
, errp
);
3055 (*new_reftable_index
)++;
3056 new_refblock_index
= 0;
3057 new_refblock_empty
= true;
3060 if (new_set_refcount
) {
3061 new_set_refcount(new_refblock
, new_refblock_index
++, 0);
3063 new_refblock_index
++;
3069 if (new_refblock_index
> 0) {
3070 /* Complete the potentially existing partially filled final refblock */
3071 if (new_set_refcount
) {
3072 for (; new_refblock_index
< new_refblock_size
;
3073 new_refblock_index
++)
3075 new_set_refcount(new_refblock
, new_refblock_index
, 0);
3079 ret
= operation(bs
, new_reftable
, *new_reftable_index
,
3080 new_reftable_size
, new_refblock
, new_refblock_empty
,
3086 (*new_reftable_index
)++;
3089 status_cb(bs
, (uint64_t)(index
+ 1) * s
->refcount_table_size
,
3090 (uint64_t)total
* s
->refcount_table_size
, cb_opaque
);
3095 int qcow2_change_refcount_order(BlockDriverState
*bs
, int refcount_order
,
3096 BlockDriverAmendStatusCB
*status_cb
,
3097 void *cb_opaque
, Error
**errp
)
3099 BDRVQcow2State
*s
= bs
->opaque
;
3100 Qcow2GetRefcountFunc
*new_get_refcount
;
3101 Qcow2SetRefcountFunc
*new_set_refcount
;
3102 void *new_refblock
= qemu_blockalign(bs
->file
->bs
, s
->cluster_size
);
3103 uint64_t *new_reftable
= NULL
, new_reftable_size
= 0;
3104 uint64_t *old_reftable
, old_reftable_size
, old_reftable_offset
;
3105 uint64_t new_reftable_index
= 0;
3107 int64_t new_reftable_offset
= 0, allocated_reftable_size
= 0;
3108 int new_refblock_size
, new_refcount_bits
= 1 << refcount_order
;
3109 int old_refcount_order
;
3112 bool new_allocation
;
3114 assert(s
->qcow_version
>= 3);
3115 assert(refcount_order
>= 0 && refcount_order
<= 6);
3117 /* see qcow2_open() */
3118 new_refblock_size
= 1 << (s
->cluster_bits
- (refcount_order
- 3));
3120 new_get_refcount
= get_refcount_funcs
[refcount_order
];
3121 new_set_refcount
= set_refcount_funcs
[refcount_order
];
3127 new_allocation
= false;
3129 /* At least we have to do this walk and the one which writes the
3130 * refblocks; also, at least we have to do this loop here at least
3131 * twice (normally), first to do the allocations, and second to
3132 * determine that everything is correctly allocated, this then makes
3133 * three walks in total */
3134 total_walks
= MAX(walk_index
+ 2, 3);
3136 /* First, allocate the structures so they are present in the refcount
3138 ret
= walk_over_reftable(bs
, &new_reftable
, &new_reftable_index
,
3139 &new_reftable_size
, NULL
, new_refblock_size
,
3140 new_refcount_bits
, &alloc_refblock
,
3141 &new_allocation
, NULL
, status_cb
, cb_opaque
,
3142 walk_index
++, total_walks
, errp
);
3147 new_reftable_index
= 0;
3149 if (new_allocation
) {
3150 if (new_reftable_offset
) {
3151 qcow2_free_clusters(bs
, new_reftable_offset
,
3152 allocated_reftable_size
* sizeof(uint64_t),
3153 QCOW2_DISCARD_NEVER
);
3156 new_reftable_offset
= qcow2_alloc_clusters(bs
, new_reftable_size
*
3158 if (new_reftable_offset
< 0) {
3159 error_setg_errno(errp
, -new_reftable_offset
,
3160 "Failed to allocate the new reftable");
3161 ret
= new_reftable_offset
;
3164 allocated_reftable_size
= new_reftable_size
;
3166 } while (new_allocation
);
3168 /* Second, write the new refblocks */
3169 ret
= walk_over_reftable(bs
, &new_reftable
, &new_reftable_index
,
3170 &new_reftable_size
, new_refblock
,
3171 new_refblock_size
, new_refcount_bits
,
3172 &flush_refblock
, &new_allocation
, new_set_refcount
,
3173 status_cb
, cb_opaque
, walk_index
, walk_index
+ 1,
3178 assert(!new_allocation
);
3181 /* Write the new reftable */
3182 ret
= qcow2_pre_write_overlap_check(bs
, 0, new_reftable_offset
,
3183 new_reftable_size
* sizeof(uint64_t),
3186 error_setg_errno(errp
, -ret
, "Overlap check failed");
3190 for (i
= 0; i
< new_reftable_size
; i
++) {
3191 cpu_to_be64s(&new_reftable
[i
]);
3194 ret
= bdrv_pwrite(bs
->file
, new_reftable_offset
, new_reftable
,
3195 new_reftable_size
* sizeof(uint64_t));
3197 for (i
= 0; i
< new_reftable_size
; i
++) {
3198 be64_to_cpus(&new_reftable
[i
]);
3202 error_setg_errno(errp
, -ret
, "Failed to write the new reftable");
3207 /* Empty the refcount cache */
3208 ret
= qcow2_cache_flush(bs
, s
->refcount_block_cache
);
3210 error_setg_errno(errp
, -ret
, "Failed to flush the refblock cache");
3214 /* Update the image header to point to the new reftable; this only updates
3215 * the fields which are relevant to qcow2_update_header(); other fields
3216 * such as s->refcount_table or s->refcount_bits stay stale for now
3217 * (because we have to restore everything if qcow2_update_header() fails) */
3218 old_refcount_order
= s
->refcount_order
;
3219 old_reftable_size
= s
->refcount_table_size
;
3220 old_reftable_offset
= s
->refcount_table_offset
;
3222 s
->refcount_order
= refcount_order
;
3223 s
->refcount_table_size
= new_reftable_size
;
3224 s
->refcount_table_offset
= new_reftable_offset
;
3226 ret
= qcow2_update_header(bs
);
3228 s
->refcount_order
= old_refcount_order
;
3229 s
->refcount_table_size
= old_reftable_size
;
3230 s
->refcount_table_offset
= old_reftable_offset
;
3231 error_setg_errno(errp
, -ret
, "Failed to update the qcow2 header");
3235 /* Now update the rest of the in-memory information */
3236 old_reftable
= s
->refcount_table
;
3237 s
->refcount_table
= new_reftable
;
3238 update_max_refcount_table_index(s
);
3240 s
->refcount_bits
= 1 << refcount_order
;
3241 s
->refcount_max
= UINT64_C(1) << (s
->refcount_bits
- 1);
3242 s
->refcount_max
+= s
->refcount_max
- 1;
3244 s
->refcount_block_bits
= s
->cluster_bits
- (refcount_order
- 3);
3245 s
->refcount_block_size
= 1 << s
->refcount_block_bits
;
3247 s
->get_refcount
= new_get_refcount
;
3248 s
->set_refcount
= new_set_refcount
;
3250 /* For cleaning up all old refblocks and the old reftable below the "done"
3252 new_reftable
= old_reftable
;
3253 new_reftable_size
= old_reftable_size
;
3254 new_reftable_offset
= old_reftable_offset
;
3258 /* On success, new_reftable actually points to the old reftable (and
3259 * new_reftable_size is the old reftable's size); but that is just
3261 for (i
= 0; i
< new_reftable_size
; i
++) {
3262 uint64_t offset
= new_reftable
[i
] & REFT_OFFSET_MASK
;
3264 qcow2_free_clusters(bs
, offset
, s
->cluster_size
,
3265 QCOW2_DISCARD_OTHER
);
3268 g_free(new_reftable
);
3270 if (new_reftable_offset
> 0) {
3271 qcow2_free_clusters(bs
, new_reftable_offset
,
3272 new_reftable_size
* sizeof(uint64_t),
3273 QCOW2_DISCARD_OTHER
);
3277 qemu_vfree(new_refblock
);
3281 static int64_t get_refblock_offset(BlockDriverState
*bs
, uint64_t offset
)
3283 BDRVQcow2State
*s
= bs
->opaque
;
3284 uint32_t index
= offset_to_reftable_index(s
, offset
);
3285 int64_t covering_refblock_offset
= 0;
3287 if (index
< s
->refcount_table_size
) {
3288 covering_refblock_offset
= s
->refcount_table
[index
] & REFT_OFFSET_MASK
;
3290 if (!covering_refblock_offset
) {
3291 qcow2_signal_corruption(bs
, true, -1, -1, "Refblock at %#" PRIx64
" is "
3292 "not covered by the refcount structures",
3297 return covering_refblock_offset
;
3300 static int qcow2_discard_refcount_block(BlockDriverState
*bs
,
3301 uint64_t discard_block_offs
)
3303 BDRVQcow2State
*s
= bs
->opaque
;
3304 int64_t refblock_offs
;
3305 uint64_t cluster_index
= discard_block_offs
>> s
->cluster_bits
;
3306 uint32_t block_index
= cluster_index
& (s
->refcount_block_size
- 1);
3310 refblock_offs
= get_refblock_offset(bs
, discard_block_offs
);
3311 if (refblock_offs
< 0) {
3312 return refblock_offs
;
3315 assert(discard_block_offs
!= 0);
3317 ret
= qcow2_cache_get(bs
, s
->refcount_block_cache
, refblock_offs
,
3323 if (s
->get_refcount(refblock
, block_index
) != 1) {
3324 qcow2_signal_corruption(bs
, true, -1, -1, "Invalid refcount:"
3325 " refblock offset %#" PRIx64
3326 ", reftable index %u"
3327 ", block offset %#" PRIx64
3328 ", refcount %#" PRIx64
,
3330 offset_to_reftable_index(s
, discard_block_offs
),
3332 s
->get_refcount(refblock
, block_index
));
3333 qcow2_cache_put(s
->refcount_block_cache
, &refblock
);
3336 s
->set_refcount(refblock
, block_index
, 0);
3338 qcow2_cache_entry_mark_dirty(s
->refcount_block_cache
, refblock
);
3340 qcow2_cache_put(s
->refcount_block_cache
, &refblock
);
3342 if (cluster_index
< s
->free_cluster_index
) {
3343 s
->free_cluster_index
= cluster_index
;
3346 refblock
= qcow2_cache_is_table_offset(s
->refcount_block_cache
,
3347 discard_block_offs
);
3349 /* discard refblock from the cache if refblock is cached */
3350 qcow2_cache_discard(s
->refcount_block_cache
, refblock
);
3352 update_refcount_discard(bs
, discard_block_offs
, s
->cluster_size
);
3357 int qcow2_shrink_reftable(BlockDriverState
*bs
)
3359 BDRVQcow2State
*s
= bs
->opaque
;
3360 uint64_t *reftable_tmp
=
3361 g_malloc(s
->refcount_table_size
* sizeof(uint64_t));
3364 for (i
= 0; i
< s
->refcount_table_size
; i
++) {
3365 int64_t refblock_offs
= s
->refcount_table
[i
] & REFT_OFFSET_MASK
;
3369 if (refblock_offs
== 0) {
3370 reftable_tmp
[i
] = 0;
3373 ret
= qcow2_cache_get(bs
, s
->refcount_block_cache
, refblock_offs
,
3379 /* the refblock has own reference */
3380 if (i
== offset_to_reftable_index(s
, refblock_offs
)) {
3381 uint64_t block_index
= (refblock_offs
>> s
->cluster_bits
) &
3382 (s
->refcount_block_size
- 1);
3383 uint64_t refcount
= s
->get_refcount(refblock
, block_index
);
3385 s
->set_refcount(refblock
, block_index
, 0);
3387 unused_block
= buffer_is_zero(refblock
, s
->cluster_size
);
3389 s
->set_refcount(refblock
, block_index
, refcount
);
3391 unused_block
= buffer_is_zero(refblock
, s
->cluster_size
);
3393 qcow2_cache_put(s
->refcount_block_cache
, &refblock
);
3395 reftable_tmp
[i
] = unused_block
? 0 : cpu_to_be64(s
->refcount_table
[i
]);
3398 ret
= bdrv_pwrite_sync(bs
->file
, s
->refcount_table_offset
, reftable_tmp
,
3399 s
->refcount_table_size
* sizeof(uint64_t));
3401 * If the write in the reftable failed the image may contain a partially
3402 * overwritten reftable. In this case it would be better to clear the
3403 * reftable in memory to avoid possible image corruption.
3405 for (i
= 0; i
< s
->refcount_table_size
; i
++) {
3406 if (s
->refcount_table
[i
] && !reftable_tmp
[i
]) {
3408 ret
= qcow2_discard_refcount_block(bs
, s
->refcount_table
[i
] &
3411 s
->refcount_table
[i
] = 0;
3415 if (!s
->cache_discards
) {
3416 qcow2_process_discards(bs
, ret
);
3420 g_free(reftable_tmp
);
3424 int64_t qcow2_get_last_cluster(BlockDriverState
*bs
, int64_t size
)
3426 BDRVQcow2State
*s
= bs
->opaque
;
3429 for (i
= size_to_clusters(s
, size
) - 1; i
>= 0; i
--) {
3431 int ret
= qcow2_get_refcount(bs
, i
, &refcount
);
3433 fprintf(stderr
, "Can't get refcount for cluster %" PRId64
": %s\n",
3441 qcow2_signal_corruption(bs
, true, -1, -1,
3442 "There are no references in the refcount table.");