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"
28 #include "qemu-common.h"
29 #include "block/block_int.h"
30 #include "block/qcow2.h"
31 #include "qemu/bswap.h"
34 int qcow2_shrink_l1_table(BlockDriverState
*bs
, uint64_t exact_size
)
36 BDRVQcow2State
*s
= bs
->opaque
;
37 int new_l1_size
, i
, ret
;
39 if (exact_size
>= s
->l1_size
) {
43 new_l1_size
= exact_size
;
46 fprintf(stderr
, "shrink l1_table from %d to %d\n", s
->l1_size
, new_l1_size
);
49 BLKDBG_EVENT(bs
->file
, BLKDBG_L1_SHRINK_WRITE_TABLE
);
50 ret
= bdrv_pwrite_zeroes(bs
->file
, s
->l1_table_offset
+
51 new_l1_size
* sizeof(uint64_t),
52 (s
->l1_size
- new_l1_size
) * sizeof(uint64_t), 0);
57 ret
= bdrv_flush(bs
->file
->bs
);
62 BLKDBG_EVENT(bs
->file
, BLKDBG_L1_SHRINK_FREE_L2_CLUSTERS
);
63 for (i
= s
->l1_size
- 1; i
> new_l1_size
- 1; i
--) {
64 if ((s
->l1_table
[i
] & L1E_OFFSET_MASK
) == 0) {
67 qcow2_free_clusters(bs
, s
->l1_table
[i
] & L1E_OFFSET_MASK
,
68 s
->cluster_size
, QCOW2_DISCARD_ALWAYS
);
75 * If the write in the l1_table failed the image may contain a partially
76 * overwritten l1_table. In this case it would be better to clear the
77 * l1_table in memory to avoid possible image corruption.
79 memset(s
->l1_table
+ new_l1_size
, 0,
80 (s
->l1_size
- new_l1_size
) * sizeof(uint64_t));
84 int qcow2_grow_l1_table(BlockDriverState
*bs
, uint64_t min_size
,
87 BDRVQcow2State
*s
= bs
->opaque
;
88 int new_l1_size2
, ret
, i
;
89 uint64_t *new_l1_table
;
90 int64_t old_l1_table_offset
, old_l1_size
;
91 int64_t new_l1_table_offset
, new_l1_size
;
94 if (min_size
<= s
->l1_size
)
97 /* Do a sanity check on min_size before trying to calculate new_l1_size
98 * (this prevents overflows during the while loop for the calculation of
100 if (min_size
> INT_MAX
/ sizeof(uint64_t)) {
105 new_l1_size
= min_size
;
107 /* Bump size up to reduce the number of times we have to grow */
108 new_l1_size
= s
->l1_size
;
109 if (new_l1_size
== 0) {
112 while (min_size
> new_l1_size
) {
113 new_l1_size
= DIV_ROUND_UP(new_l1_size
* 3, 2);
117 QEMU_BUILD_BUG_ON(QCOW_MAX_L1_SIZE
> INT_MAX
);
118 if (new_l1_size
> QCOW_MAX_L1_SIZE
/ sizeof(uint64_t)) {
123 fprintf(stderr
, "grow l1_table from %d to %" PRId64
"\n",
124 s
->l1_size
, new_l1_size
);
127 new_l1_size2
= sizeof(uint64_t) * new_l1_size
;
128 new_l1_table
= qemu_try_blockalign(bs
->file
->bs
,
129 align_offset(new_l1_size2
, 512));
130 if (new_l1_table
== NULL
) {
133 memset(new_l1_table
, 0, align_offset(new_l1_size2
, 512));
136 memcpy(new_l1_table
, s
->l1_table
, s
->l1_size
* sizeof(uint64_t));
139 /* write new table (align to cluster) */
140 BLKDBG_EVENT(bs
->file
, BLKDBG_L1_GROW_ALLOC_TABLE
);
141 new_l1_table_offset
= qcow2_alloc_clusters(bs
, new_l1_size2
);
142 if (new_l1_table_offset
< 0) {
143 qemu_vfree(new_l1_table
);
144 return new_l1_table_offset
;
147 ret
= qcow2_cache_flush(bs
, s
->refcount_block_cache
);
152 /* the L1 position has not yet been updated, so these clusters must
153 * indeed be completely free */
154 ret
= qcow2_pre_write_overlap_check(bs
, 0, new_l1_table_offset
,
160 BLKDBG_EVENT(bs
->file
, BLKDBG_L1_GROW_WRITE_TABLE
);
161 for(i
= 0; i
< s
->l1_size
; i
++)
162 new_l1_table
[i
] = cpu_to_be64(new_l1_table
[i
]);
163 ret
= bdrv_pwrite_sync(bs
->file
, new_l1_table_offset
,
164 new_l1_table
, new_l1_size2
);
167 for(i
= 0; i
< s
->l1_size
; i
++)
168 new_l1_table
[i
] = be64_to_cpu(new_l1_table
[i
]);
171 BLKDBG_EVENT(bs
->file
, BLKDBG_L1_GROW_ACTIVATE_TABLE
);
172 stl_be_p(data
, new_l1_size
);
173 stq_be_p(data
+ 4, new_l1_table_offset
);
174 ret
= bdrv_pwrite_sync(bs
->file
, offsetof(QCowHeader
, l1_size
),
179 qemu_vfree(s
->l1_table
);
180 old_l1_table_offset
= s
->l1_table_offset
;
181 s
->l1_table_offset
= new_l1_table_offset
;
182 s
->l1_table
= new_l1_table
;
183 old_l1_size
= s
->l1_size
;
184 s
->l1_size
= new_l1_size
;
185 qcow2_free_clusters(bs
, old_l1_table_offset
, old_l1_size
* sizeof(uint64_t),
186 QCOW2_DISCARD_OTHER
);
189 qemu_vfree(new_l1_table
);
190 qcow2_free_clusters(bs
, new_l1_table_offset
, new_l1_size2
,
191 QCOW2_DISCARD_OTHER
);
198 * Loads a L2 table into memory. If the table is in the cache, the cache
199 * is used; otherwise the L2 table is loaded from the image file.
201 * Returns a pointer to the L2 table on success, or NULL if the read from
202 * the image file failed.
205 static int l2_load(BlockDriverState
*bs
, uint64_t l2_offset
,
208 BDRVQcow2State
*s
= bs
->opaque
;
210 return qcow2_cache_get(bs
, s
->l2_table_cache
, l2_offset
,
215 * Writes one sector of the L1 table to the disk (can't update single entries
216 * and we really don't want bdrv_pread to perform a read-modify-write)
218 #define L1_ENTRIES_PER_SECTOR (512 / 8)
219 int qcow2_write_l1_entry(BlockDriverState
*bs
, int l1_index
)
221 BDRVQcow2State
*s
= bs
->opaque
;
222 uint64_t buf
[L1_ENTRIES_PER_SECTOR
] = { 0 };
226 l1_start_index
= l1_index
& ~(L1_ENTRIES_PER_SECTOR
- 1);
227 for (i
= 0; i
< L1_ENTRIES_PER_SECTOR
&& l1_start_index
+ i
< s
->l1_size
;
230 buf
[i
] = cpu_to_be64(s
->l1_table
[l1_start_index
+ i
]);
233 ret
= qcow2_pre_write_overlap_check(bs
, QCOW2_OL_ACTIVE_L1
,
234 s
->l1_table_offset
+ 8 * l1_start_index
, sizeof(buf
));
239 BLKDBG_EVENT(bs
->file
, BLKDBG_L1_UPDATE
);
240 ret
= bdrv_pwrite_sync(bs
->file
,
241 s
->l1_table_offset
+ 8 * l1_start_index
,
253 * Allocate a new l2 entry in the file. If l1_index points to an already
254 * used entry in the L2 table (i.e. we are doing a copy on write for the L2
255 * table) copy the contents of the old L2 table into the newly allocated one.
256 * Otherwise the new table is initialized with zeros.
260 static int l2_allocate(BlockDriverState
*bs
, int l1_index
, uint64_t **table
)
262 BDRVQcow2State
*s
= bs
->opaque
;
263 uint64_t old_l2_offset
;
264 uint64_t *l2_table
= NULL
;
268 old_l2_offset
= s
->l1_table
[l1_index
];
270 trace_qcow2_l2_allocate(bs
, l1_index
);
272 /* allocate a new l2 entry */
274 l2_offset
= qcow2_alloc_clusters(bs
, s
->l2_size
* sizeof(uint64_t));
280 /* If we're allocating the table at offset 0 then something is wrong */
281 if (l2_offset
== 0) {
282 qcow2_signal_corruption(bs
, true, -1, -1, "Preventing invalid "
283 "allocation of L2 table at offset 0");
288 ret
= qcow2_cache_flush(bs
, s
->refcount_block_cache
);
293 /* allocate a new entry in the l2 cache */
295 trace_qcow2_l2_allocate_get_empty(bs
, l1_index
);
296 ret
= qcow2_cache_get_empty(bs
, s
->l2_table_cache
, l2_offset
, (void**) table
);
303 if ((old_l2_offset
& L1E_OFFSET_MASK
) == 0) {
304 /* if there was no old l2 table, clear the new table */
305 memset(l2_table
, 0, s
->l2_size
* sizeof(uint64_t));
309 /* if there was an old l2 table, read it from the disk */
310 BLKDBG_EVENT(bs
->file
, BLKDBG_L2_ALLOC_COW_READ
);
311 ret
= qcow2_cache_get(bs
, s
->l2_table_cache
,
312 old_l2_offset
& L1E_OFFSET_MASK
,
313 (void**) &old_table
);
318 memcpy(l2_table
, old_table
, s
->cluster_size
);
320 qcow2_cache_put(bs
, s
->l2_table_cache
, (void **) &old_table
);
323 /* write the l2 table to the file */
324 BLKDBG_EVENT(bs
->file
, BLKDBG_L2_ALLOC_WRITE
);
326 trace_qcow2_l2_allocate_write_l2(bs
, l1_index
);
327 qcow2_cache_entry_mark_dirty(bs
, s
->l2_table_cache
, l2_table
);
328 ret
= qcow2_cache_flush(bs
, s
->l2_table_cache
);
333 /* update the L1 entry */
334 trace_qcow2_l2_allocate_write_l1(bs
, l1_index
);
335 s
->l1_table
[l1_index
] = l2_offset
| QCOW_OFLAG_COPIED
;
336 ret
= qcow2_write_l1_entry(bs
, l1_index
);
342 trace_qcow2_l2_allocate_done(bs
, l1_index
, 0);
346 trace_qcow2_l2_allocate_done(bs
, l1_index
, ret
);
347 if (l2_table
!= NULL
) {
348 qcow2_cache_put(bs
, s
->l2_table_cache
, (void**) table
);
350 s
->l1_table
[l1_index
] = old_l2_offset
;
352 qcow2_free_clusters(bs
, l2_offset
, s
->l2_size
* sizeof(uint64_t),
353 QCOW2_DISCARD_ALWAYS
);
359 * Checks how many clusters in a given L2 table are contiguous in the image
360 * file. As soon as one of the flags in the bitmask stop_flags changes compared
361 * to the first cluster, the search is stopped and the cluster is not counted
362 * as contiguous. (This allows it, for example, to stop at the first compressed
363 * cluster which may require a different handling)
365 static int count_contiguous_clusters(int nb_clusters
, int cluster_size
,
366 uint64_t *l2_table
, uint64_t stop_flags
)
369 QCow2ClusterType first_cluster_type
;
370 uint64_t mask
= stop_flags
| L2E_OFFSET_MASK
| QCOW_OFLAG_COMPRESSED
;
371 uint64_t first_entry
= be64_to_cpu(l2_table
[0]);
372 uint64_t offset
= first_entry
& mask
;
378 /* must be allocated */
379 first_cluster_type
= qcow2_get_cluster_type(first_entry
);
380 assert(first_cluster_type
== QCOW2_CLUSTER_NORMAL
||
381 first_cluster_type
== QCOW2_CLUSTER_ZERO_ALLOC
);
383 for (i
= 0; i
< nb_clusters
; i
++) {
384 uint64_t l2_entry
= be64_to_cpu(l2_table
[i
]) & mask
;
385 if (offset
+ (uint64_t) i
* cluster_size
!= l2_entry
) {
394 * Checks how many consecutive unallocated clusters in a given L2
395 * table have the same cluster type.
397 static int count_contiguous_clusters_unallocated(int nb_clusters
,
399 QCow2ClusterType wanted_type
)
403 assert(wanted_type
== QCOW2_CLUSTER_ZERO_PLAIN
||
404 wanted_type
== QCOW2_CLUSTER_UNALLOCATED
);
405 for (i
= 0; i
< nb_clusters
; i
++) {
406 uint64_t entry
= be64_to_cpu(l2_table
[i
]);
407 QCow2ClusterType type
= qcow2_get_cluster_type(entry
);
409 if (type
!= wanted_type
) {
417 static int coroutine_fn
do_perform_cow_read(BlockDriverState
*bs
,
418 uint64_t src_cluster_offset
,
419 unsigned offset_in_cluster
,
424 if (qiov
->size
== 0) {
428 BLKDBG_EVENT(bs
->file
, BLKDBG_COW_READ
);
434 /* Call .bdrv_co_readv() directly instead of using the public block-layer
435 * interface. This avoids double I/O throttling and request tracking,
436 * which can lead to deadlock when block layer copy-on-read is enabled.
438 ret
= bs
->drv
->bdrv_co_preadv(bs
, src_cluster_offset
+ offset_in_cluster
,
439 qiov
->size
, qiov
, 0);
447 static bool coroutine_fn
do_perform_cow_encrypt(BlockDriverState
*bs
,
448 uint64_t src_cluster_offset
,
449 uint64_t cluster_offset
,
450 unsigned offset_in_cluster
,
454 if (bytes
&& bs
->encrypted
) {
455 BDRVQcow2State
*s
= bs
->opaque
;
456 int64_t offset
= (s
->crypt_physical_offset
?
457 (cluster_offset
+ offset_in_cluster
) :
458 (src_cluster_offset
+ offset_in_cluster
));
459 assert((offset_in_cluster
& ~BDRV_SECTOR_MASK
) == 0);
460 assert((bytes
& ~BDRV_SECTOR_MASK
) == 0);
462 if (qcrypto_block_encrypt(s
->crypto
, offset
, buffer
, bytes
, NULL
) < 0) {
469 static int coroutine_fn
do_perform_cow_write(BlockDriverState
*bs
,
470 uint64_t cluster_offset
,
471 unsigned offset_in_cluster
,
476 if (qiov
->size
== 0) {
480 ret
= qcow2_pre_write_overlap_check(bs
, 0,
481 cluster_offset
+ offset_in_cluster
, qiov
->size
);
486 BLKDBG_EVENT(bs
->file
, BLKDBG_COW_WRITE
);
487 ret
= bdrv_co_pwritev(bs
->file
, cluster_offset
+ offset_in_cluster
,
488 qiov
->size
, qiov
, 0);
500 * For a given offset of the virtual disk, find the cluster type and offset in
501 * the qcow2 file. The offset is stored in *cluster_offset.
503 * On entry, *bytes is the maximum number of contiguous bytes starting at
504 * offset that we are interested in.
506 * On exit, *bytes is the number of bytes starting at offset that have the same
507 * cluster type and (if applicable) are stored contiguously in the image file.
508 * Compressed clusters are always returned one by one.
510 * Returns the cluster type (QCOW2_CLUSTER_*) on success, -errno in error
513 int qcow2_get_cluster_offset(BlockDriverState
*bs
, uint64_t offset
,
514 unsigned int *bytes
, uint64_t *cluster_offset
)
516 BDRVQcow2State
*s
= bs
->opaque
;
517 unsigned int l2_index
;
518 uint64_t l1_index
, l2_offset
, *l2_table
;
520 unsigned int offset_in_cluster
;
521 uint64_t bytes_available
, bytes_needed
, nb_clusters
;
522 QCow2ClusterType type
;
525 offset_in_cluster
= offset_into_cluster(s
, offset
);
526 bytes_needed
= (uint64_t) *bytes
+ offset_in_cluster
;
528 l1_bits
= s
->l2_bits
+ s
->cluster_bits
;
530 /* compute how many bytes there are between the start of the cluster
531 * containing offset and the end of the l1 entry */
532 bytes_available
= (1ULL << l1_bits
) - (offset
& ((1ULL << l1_bits
) - 1))
535 if (bytes_needed
> bytes_available
) {
536 bytes_needed
= bytes_available
;
541 /* seek to the l2 offset in the l1 table */
543 l1_index
= offset
>> l1_bits
;
544 if (l1_index
>= s
->l1_size
) {
545 type
= QCOW2_CLUSTER_UNALLOCATED
;
549 l2_offset
= s
->l1_table
[l1_index
] & L1E_OFFSET_MASK
;
551 type
= QCOW2_CLUSTER_UNALLOCATED
;
555 if (offset_into_cluster(s
, l2_offset
)) {
556 qcow2_signal_corruption(bs
, true, -1, -1, "L2 table offset %#" PRIx64
557 " unaligned (L1 index: %#" PRIx64
")",
558 l2_offset
, l1_index
);
562 /* load the l2 table in memory */
564 ret
= l2_load(bs
, l2_offset
, &l2_table
);
569 /* find the cluster offset for the given disk offset */
571 l2_index
= offset_to_l2_index(s
, offset
);
572 *cluster_offset
= be64_to_cpu(l2_table
[l2_index
]);
574 nb_clusters
= size_to_clusters(s
, bytes_needed
);
575 /* bytes_needed <= *bytes + offset_in_cluster, both of which are unsigned
576 * integers; the minimum cluster size is 512, so this assertion is always
578 assert(nb_clusters
<= INT_MAX
);
580 type
= qcow2_get_cluster_type(*cluster_offset
);
581 if (s
->qcow_version
< 3 && (type
== QCOW2_CLUSTER_ZERO_PLAIN
||
582 type
== QCOW2_CLUSTER_ZERO_ALLOC
)) {
583 qcow2_signal_corruption(bs
, true, -1, -1, "Zero cluster entry found"
584 " in pre-v3 image (L2 offset: %#" PRIx64
585 ", L2 index: %#x)", l2_offset
, l2_index
);
590 case QCOW2_CLUSTER_COMPRESSED
:
591 /* Compressed clusters can only be processed one by one */
593 *cluster_offset
&= L2E_COMPRESSED_OFFSET_SIZE_MASK
;
595 case QCOW2_CLUSTER_ZERO_PLAIN
:
596 case QCOW2_CLUSTER_UNALLOCATED
:
597 /* how many empty clusters ? */
598 c
= count_contiguous_clusters_unallocated(nb_clusters
,
599 &l2_table
[l2_index
], type
);
602 case QCOW2_CLUSTER_ZERO_ALLOC
:
603 case QCOW2_CLUSTER_NORMAL
:
604 /* how many allocated clusters ? */
605 c
= count_contiguous_clusters(nb_clusters
, s
->cluster_size
,
606 &l2_table
[l2_index
], QCOW_OFLAG_ZERO
);
607 *cluster_offset
&= L2E_OFFSET_MASK
;
608 if (offset_into_cluster(s
, *cluster_offset
)) {
609 qcow2_signal_corruption(bs
, true, -1, -1,
610 "Cluster allocation offset %#"
611 PRIx64
" unaligned (L2 offset: %#" PRIx64
612 ", L2 index: %#x)", *cluster_offset
,
613 l2_offset
, l2_index
);
622 qcow2_cache_put(bs
, s
->l2_table_cache
, (void**) &l2_table
);
624 bytes_available
= (int64_t)c
* s
->cluster_size
;
627 if (bytes_available
> bytes_needed
) {
628 bytes_available
= bytes_needed
;
631 /* bytes_available <= bytes_needed <= *bytes + offset_in_cluster;
632 * subtracting offset_in_cluster will therefore definitely yield something
633 * not exceeding UINT_MAX */
634 assert(bytes_available
- offset_in_cluster
<= UINT_MAX
);
635 *bytes
= bytes_available
- offset_in_cluster
;
640 qcow2_cache_put(bs
, s
->l2_table_cache
, (void **)&l2_table
);
647 * for a given disk offset, load (and allocate if needed)
650 * the l2 table offset in the qcow2 file and the cluster index
651 * in the l2 table are given to the caller.
653 * Returns 0 on success, -errno in failure case
655 static int get_cluster_table(BlockDriverState
*bs
, uint64_t offset
,
656 uint64_t **new_l2_table
,
659 BDRVQcow2State
*s
= bs
->opaque
;
660 unsigned int l2_index
;
661 uint64_t l1_index
, l2_offset
;
662 uint64_t *l2_table
= NULL
;
665 /* seek to the l2 offset in the l1 table */
667 l1_index
= offset
>> (s
->l2_bits
+ s
->cluster_bits
);
668 if (l1_index
>= s
->l1_size
) {
669 ret
= qcow2_grow_l1_table(bs
, l1_index
+ 1, false);
675 assert(l1_index
< s
->l1_size
);
676 l2_offset
= s
->l1_table
[l1_index
] & L1E_OFFSET_MASK
;
677 if (offset_into_cluster(s
, l2_offset
)) {
678 qcow2_signal_corruption(bs
, true, -1, -1, "L2 table offset %#" PRIx64
679 " unaligned (L1 index: %#" PRIx64
")",
680 l2_offset
, l1_index
);
684 /* seek the l2 table of the given l2 offset */
686 if (s
->l1_table
[l1_index
] & QCOW_OFLAG_COPIED
) {
687 /* load the l2 table in memory */
688 ret
= l2_load(bs
, l2_offset
, &l2_table
);
693 /* First allocate a new L2 table (and do COW if needed) */
694 ret
= l2_allocate(bs
, l1_index
, &l2_table
);
699 /* Then decrease the refcount of the old table */
701 qcow2_free_clusters(bs
, l2_offset
, s
->l2_size
* sizeof(uint64_t),
702 QCOW2_DISCARD_OTHER
);
706 /* find the cluster offset for the given disk offset */
708 l2_index
= offset_to_l2_index(s
, offset
);
710 *new_l2_table
= l2_table
;
711 *new_l2_index
= l2_index
;
717 * alloc_compressed_cluster_offset
719 * For a given offset of the disk image, return cluster offset in
722 * If the offset is not found, allocate a new compressed cluster.
724 * Return the cluster offset if successful,
725 * Return 0, otherwise.
729 uint64_t qcow2_alloc_compressed_cluster_offset(BlockDriverState
*bs
,
733 BDRVQcow2State
*s
= bs
->opaque
;
736 int64_t cluster_offset
;
739 ret
= get_cluster_table(bs
, offset
, &l2_table
, &l2_index
);
744 /* Compression can't overwrite anything. Fail if the cluster was already
746 cluster_offset
= be64_to_cpu(l2_table
[l2_index
]);
747 if (cluster_offset
& L2E_OFFSET_MASK
) {
748 qcow2_cache_put(bs
, s
->l2_table_cache
, (void**) &l2_table
);
752 cluster_offset
= qcow2_alloc_bytes(bs
, compressed_size
);
753 if (cluster_offset
< 0) {
754 qcow2_cache_put(bs
, s
->l2_table_cache
, (void**) &l2_table
);
758 nb_csectors
= ((cluster_offset
+ compressed_size
- 1) >> 9) -
759 (cluster_offset
>> 9);
761 cluster_offset
|= QCOW_OFLAG_COMPRESSED
|
762 ((uint64_t)nb_csectors
<< s
->csize_shift
);
764 /* update L2 table */
766 /* compressed clusters never have the copied flag */
768 BLKDBG_EVENT(bs
->file
, BLKDBG_L2_UPDATE_COMPRESSED
);
769 qcow2_cache_entry_mark_dirty(bs
, s
->l2_table_cache
, l2_table
);
770 l2_table
[l2_index
] = cpu_to_be64(cluster_offset
);
771 qcow2_cache_put(bs
, s
->l2_table_cache
, (void **) &l2_table
);
773 return cluster_offset
;
776 static int perform_cow(BlockDriverState
*bs
, QCowL2Meta
*m
)
778 BDRVQcow2State
*s
= bs
->opaque
;
779 Qcow2COWRegion
*start
= &m
->cow_start
;
780 Qcow2COWRegion
*end
= &m
->cow_end
;
781 unsigned buffer_size
;
782 unsigned data_bytes
= end
->offset
- (start
->offset
+ start
->nb_bytes
);
784 uint8_t *start_buffer
, *end_buffer
;
788 assert(start
->nb_bytes
<= UINT_MAX
- end
->nb_bytes
);
789 assert(start
->nb_bytes
+ end
->nb_bytes
<= UINT_MAX
- data_bytes
);
790 assert(start
->offset
+ start
->nb_bytes
<= end
->offset
);
791 assert(!m
->data_qiov
|| m
->data_qiov
->size
== data_bytes
);
793 if (start
->nb_bytes
== 0 && end
->nb_bytes
== 0) {
797 /* If we have to read both the start and end COW regions and the
798 * middle region is not too large then perform just one read
800 merge_reads
= start
->nb_bytes
&& end
->nb_bytes
&& data_bytes
<= 16384;
802 buffer_size
= start
->nb_bytes
+ data_bytes
+ end
->nb_bytes
;
804 /* If we have to do two reads, add some padding in the middle
805 * if necessary to make sure that the end region is optimally
807 size_t align
= bdrv_opt_mem_align(bs
);
808 assert(align
> 0 && align
<= UINT_MAX
);
809 assert(QEMU_ALIGN_UP(start
->nb_bytes
, align
) <=
810 UINT_MAX
- end
->nb_bytes
);
811 buffer_size
= QEMU_ALIGN_UP(start
->nb_bytes
, align
) + end
->nb_bytes
;
814 /* Reserve a buffer large enough to store all the data that we're
816 start_buffer
= qemu_try_blockalign(bs
, buffer_size
);
817 if (start_buffer
== NULL
) {
820 /* The part of the buffer where the end region is located */
821 end_buffer
= start_buffer
+ buffer_size
- end
->nb_bytes
;
823 qemu_iovec_init(&qiov
, 2 + (m
->data_qiov
? m
->data_qiov
->niov
: 0));
825 qemu_co_mutex_unlock(&s
->lock
);
826 /* First we read the existing data from both COW regions. We
827 * either read the whole region in one go, or the start and end
828 * regions separately. */
830 qemu_iovec_add(&qiov
, start_buffer
, buffer_size
);
831 ret
= do_perform_cow_read(bs
, m
->offset
, start
->offset
, &qiov
);
833 qemu_iovec_add(&qiov
, start_buffer
, start
->nb_bytes
);
834 ret
= do_perform_cow_read(bs
, m
->offset
, start
->offset
, &qiov
);
839 qemu_iovec_reset(&qiov
);
840 qemu_iovec_add(&qiov
, end_buffer
, end
->nb_bytes
);
841 ret
= do_perform_cow_read(bs
, m
->offset
, end
->offset
, &qiov
);
847 /* Encrypt the data if necessary before writing it */
849 if (!do_perform_cow_encrypt(bs
, m
->offset
, m
->alloc_offset
,
850 start
->offset
, start_buffer
,
852 !do_perform_cow_encrypt(bs
, m
->offset
, m
->alloc_offset
,
853 end
->offset
, end_buffer
, end
->nb_bytes
)) {
859 /* And now we can write everything. If we have the guest data we
860 * can write everything in one single operation */
862 qemu_iovec_reset(&qiov
);
863 if (start
->nb_bytes
) {
864 qemu_iovec_add(&qiov
, start_buffer
, start
->nb_bytes
);
866 qemu_iovec_concat(&qiov
, m
->data_qiov
, 0, data_bytes
);
868 qemu_iovec_add(&qiov
, end_buffer
, end
->nb_bytes
);
870 /* NOTE: we have a write_aio blkdebug event here followed by
871 * a cow_write one in do_perform_cow_write(), but there's only
872 * one single I/O operation */
873 BLKDBG_EVENT(bs
->file
, BLKDBG_WRITE_AIO
);
874 ret
= do_perform_cow_write(bs
, m
->alloc_offset
, start
->offset
, &qiov
);
876 /* If there's no guest data then write both COW regions separately */
877 qemu_iovec_reset(&qiov
);
878 qemu_iovec_add(&qiov
, start_buffer
, start
->nb_bytes
);
879 ret
= do_perform_cow_write(bs
, m
->alloc_offset
, start
->offset
, &qiov
);
884 qemu_iovec_reset(&qiov
);
885 qemu_iovec_add(&qiov
, end_buffer
, end
->nb_bytes
);
886 ret
= do_perform_cow_write(bs
, m
->alloc_offset
, end
->offset
, &qiov
);
890 qemu_co_mutex_lock(&s
->lock
);
893 * Before we update the L2 table to actually point to the new cluster, we
894 * need to be sure that the refcounts have been increased and COW was
898 qcow2_cache_depends_on_flush(s
->l2_table_cache
);
901 qemu_vfree(start_buffer
);
902 qemu_iovec_destroy(&qiov
);
906 int qcow2_alloc_cluster_link_l2(BlockDriverState
*bs
, QCowL2Meta
*m
)
908 BDRVQcow2State
*s
= bs
->opaque
;
909 int i
, j
= 0, l2_index
, ret
;
910 uint64_t *old_cluster
, *l2_table
;
911 uint64_t cluster_offset
= m
->alloc_offset
;
913 trace_qcow2_cluster_link_l2(qemu_coroutine_self(), m
->nb_clusters
);
914 assert(m
->nb_clusters
> 0);
916 old_cluster
= g_try_new(uint64_t, m
->nb_clusters
);
917 if (old_cluster
== NULL
) {
922 /* copy content of unmodified sectors */
923 ret
= perform_cow(bs
, m
);
928 /* Update L2 table. */
929 if (s
->use_lazy_refcounts
) {
930 qcow2_mark_dirty(bs
);
932 if (qcow2_need_accurate_refcounts(s
)) {
933 qcow2_cache_set_dependency(bs
, s
->l2_table_cache
,
934 s
->refcount_block_cache
);
937 ret
= get_cluster_table(bs
, m
->offset
, &l2_table
, &l2_index
);
941 qcow2_cache_entry_mark_dirty(bs
, s
->l2_table_cache
, l2_table
);
943 assert(l2_index
+ m
->nb_clusters
<= s
->l2_size
);
944 for (i
= 0; i
< m
->nb_clusters
; i
++) {
945 /* if two concurrent writes happen to the same unallocated cluster
946 * each write allocates separate cluster and writes data concurrently.
947 * The first one to complete updates l2 table with pointer to its
948 * cluster the second one has to do RMW (which is done above by
949 * perform_cow()), update l2 table with its cluster pointer and free
950 * old cluster. This is what this loop does */
951 if (l2_table
[l2_index
+ i
] != 0) {
952 old_cluster
[j
++] = l2_table
[l2_index
+ i
];
955 l2_table
[l2_index
+ i
] = cpu_to_be64((cluster_offset
+
956 (i
<< s
->cluster_bits
)) | QCOW_OFLAG_COPIED
);
960 qcow2_cache_put(bs
, s
->l2_table_cache
, (void **) &l2_table
);
963 * If this was a COW, we need to decrease the refcount of the old cluster.
965 * Don't discard clusters that reach a refcount of 0 (e.g. compressed
966 * clusters), the next write will reuse them anyway.
968 if (!m
->keep_old_clusters
&& j
!= 0) {
969 for (i
= 0; i
< j
; i
++) {
970 qcow2_free_any_clusters(bs
, be64_to_cpu(old_cluster
[i
]), 1,
971 QCOW2_DISCARD_NEVER
);
982 * Returns the number of contiguous clusters that can be used for an allocating
983 * write, but require COW to be performed (this includes yet unallocated space,
984 * which must copy from the backing file)
986 static int count_cow_clusters(BDRVQcow2State
*s
, int nb_clusters
,
987 uint64_t *l2_table
, int l2_index
)
991 for (i
= 0; i
< nb_clusters
; i
++) {
992 uint64_t l2_entry
= be64_to_cpu(l2_table
[l2_index
+ i
]);
993 QCow2ClusterType cluster_type
= qcow2_get_cluster_type(l2_entry
);
995 switch(cluster_type
) {
996 case QCOW2_CLUSTER_NORMAL
:
997 if (l2_entry
& QCOW_OFLAG_COPIED
) {
1001 case QCOW2_CLUSTER_UNALLOCATED
:
1002 case QCOW2_CLUSTER_COMPRESSED
:
1003 case QCOW2_CLUSTER_ZERO_PLAIN
:
1004 case QCOW2_CLUSTER_ZERO_ALLOC
:
1012 assert(i
<= nb_clusters
);
1017 * Check if there already is an AIO write request in flight which allocates
1018 * the same cluster. In this case we need to wait until the previous
1019 * request has completed and updated the L2 table accordingly.
1022 * 0 if there was no dependency. *cur_bytes indicates the number of
1023 * bytes from guest_offset that can be read before the next
1024 * dependency must be processed (or the request is complete)
1026 * -EAGAIN if we had to wait for another request, previously gathered
1027 * information on cluster allocation may be invalid now. The caller
1028 * must start over anyway, so consider *cur_bytes undefined.
1030 static int handle_dependencies(BlockDriverState
*bs
, uint64_t guest_offset
,
1031 uint64_t *cur_bytes
, QCowL2Meta
**m
)
1033 BDRVQcow2State
*s
= bs
->opaque
;
1034 QCowL2Meta
*old_alloc
;
1035 uint64_t bytes
= *cur_bytes
;
1037 QLIST_FOREACH(old_alloc
, &s
->cluster_allocs
, next_in_flight
) {
1039 uint64_t start
= guest_offset
;
1040 uint64_t end
= start
+ bytes
;
1041 uint64_t old_start
= l2meta_cow_start(old_alloc
);
1042 uint64_t old_end
= l2meta_cow_end(old_alloc
);
1044 if (end
<= old_start
|| start
>= old_end
) {
1045 /* No intersection */
1047 if (start
< old_start
) {
1048 /* Stop at the start of a running allocation */
1049 bytes
= old_start
- start
;
1054 /* Stop if already an l2meta exists. After yielding, it wouldn't
1055 * be valid any more, so we'd have to clean up the old L2Metas
1056 * and deal with requests depending on them before starting to
1057 * gather new ones. Not worth the trouble. */
1058 if (bytes
== 0 && *m
) {
1064 /* Wait for the dependency to complete. We need to recheck
1065 * the free/allocated clusters when we continue. */
1066 qemu_co_queue_wait(&old_alloc
->dependent_requests
, &s
->lock
);
1072 /* Make sure that existing clusters and new allocations are only used up to
1073 * the next dependency if we shortened the request above */
1080 * Checks how many already allocated clusters that don't require a copy on
1081 * write there are at the given guest_offset (up to *bytes). If
1082 * *host_offset is not zero, only physically contiguous clusters beginning at
1083 * this host offset are counted.
1085 * Note that guest_offset may not be cluster aligned. In this case, the
1086 * returned *host_offset points to exact byte referenced by guest_offset and
1087 * therefore isn't cluster aligned as well.
1090 * 0: if no allocated clusters are available at the given offset.
1091 * *bytes is normally unchanged. It is set to 0 if the cluster
1092 * is allocated and doesn't need COW, but doesn't have the right
1095 * 1: if allocated clusters that don't require a COW are available at
1096 * the requested offset. *bytes may have decreased and describes
1097 * the length of the area that can be written to.
1099 * -errno: in error cases
1101 static int handle_copied(BlockDriverState
*bs
, uint64_t guest_offset
,
1102 uint64_t *host_offset
, uint64_t *bytes
, QCowL2Meta
**m
)
1104 BDRVQcow2State
*s
= bs
->opaque
;
1106 uint64_t cluster_offset
;
1108 uint64_t nb_clusters
;
1109 unsigned int keep_clusters
;
1112 trace_qcow2_handle_copied(qemu_coroutine_self(), guest_offset
, *host_offset
,
1115 assert(*host_offset
== 0 || offset_into_cluster(s
, guest_offset
)
1116 == offset_into_cluster(s
, *host_offset
));
1119 * Calculate the number of clusters to look for. We stop at L2 table
1120 * boundaries to keep things simple.
1123 size_to_clusters(s
, offset_into_cluster(s
, guest_offset
) + *bytes
);
1125 l2_index
= offset_to_l2_index(s
, guest_offset
);
1126 nb_clusters
= MIN(nb_clusters
, s
->l2_size
- l2_index
);
1127 assert(nb_clusters
<= INT_MAX
);
1129 /* Find L2 entry for the first involved cluster */
1130 ret
= get_cluster_table(bs
, guest_offset
, &l2_table
, &l2_index
);
1135 cluster_offset
= be64_to_cpu(l2_table
[l2_index
]);
1137 /* Check how many clusters are already allocated and don't need COW */
1138 if (qcow2_get_cluster_type(cluster_offset
) == QCOW2_CLUSTER_NORMAL
1139 && (cluster_offset
& QCOW_OFLAG_COPIED
))
1141 /* If a specific host_offset is required, check it */
1142 bool offset_matches
=
1143 (cluster_offset
& L2E_OFFSET_MASK
) == *host_offset
;
1145 if (offset_into_cluster(s
, cluster_offset
& L2E_OFFSET_MASK
)) {
1146 qcow2_signal_corruption(bs
, true, -1, -1, "Data cluster offset "
1147 "%#llx unaligned (guest offset: %#" PRIx64
1148 ")", cluster_offset
& L2E_OFFSET_MASK
,
1154 if (*host_offset
!= 0 && !offset_matches
) {
1160 /* We keep all QCOW_OFLAG_COPIED clusters */
1162 count_contiguous_clusters(nb_clusters
, s
->cluster_size
,
1163 &l2_table
[l2_index
],
1164 QCOW_OFLAG_COPIED
| QCOW_OFLAG_ZERO
);
1165 assert(keep_clusters
<= nb_clusters
);
1167 *bytes
= MIN(*bytes
,
1168 keep_clusters
* s
->cluster_size
1169 - offset_into_cluster(s
, guest_offset
));
1178 qcow2_cache_put(bs
, s
->l2_table_cache
, (void **) &l2_table
);
1180 /* Only return a host offset if we actually made progress. Otherwise we
1181 * would make requirements for handle_alloc() that it can't fulfill */
1183 *host_offset
= (cluster_offset
& L2E_OFFSET_MASK
)
1184 + offset_into_cluster(s
, guest_offset
);
1191 * Allocates new clusters for the given guest_offset.
1193 * At most *nb_clusters are allocated, and on return *nb_clusters is updated to
1194 * contain the number of clusters that have been allocated and are contiguous
1195 * in the image file.
1197 * If *host_offset is non-zero, it specifies the offset in the image file at
1198 * which the new clusters must start. *nb_clusters can be 0 on return in this
1199 * case if the cluster at host_offset is already in use. If *host_offset is
1200 * zero, the clusters can be allocated anywhere in the image file.
1202 * *host_offset is updated to contain the offset into the image file at which
1203 * the first allocated cluster starts.
1205 * Return 0 on success and -errno in error cases. -EAGAIN means that the
1206 * function has been waiting for another request and the allocation must be
1207 * restarted, but the whole request should not be failed.
1209 static int do_alloc_cluster_offset(BlockDriverState
*bs
, uint64_t guest_offset
,
1210 uint64_t *host_offset
, uint64_t *nb_clusters
)
1212 BDRVQcow2State
*s
= bs
->opaque
;
1214 trace_qcow2_do_alloc_clusters_offset(qemu_coroutine_self(), guest_offset
,
1215 *host_offset
, *nb_clusters
);
1217 /* Allocate new clusters */
1218 trace_qcow2_cluster_alloc_phys(qemu_coroutine_self());
1219 if (*host_offset
== 0) {
1220 int64_t cluster_offset
=
1221 qcow2_alloc_clusters(bs
, *nb_clusters
* s
->cluster_size
);
1222 if (cluster_offset
< 0) {
1223 return cluster_offset
;
1225 *host_offset
= cluster_offset
;
1228 int64_t ret
= qcow2_alloc_clusters_at(bs
, *host_offset
, *nb_clusters
);
1238 * Allocates new clusters for an area that either is yet unallocated or needs a
1239 * copy on write. If *host_offset is non-zero, clusters are only allocated if
1240 * the new allocation can match the specified host offset.
1242 * Note that guest_offset may not be cluster aligned. In this case, the
1243 * returned *host_offset points to exact byte referenced by guest_offset and
1244 * therefore isn't cluster aligned as well.
1247 * 0: if no clusters could be allocated. *bytes is set to 0,
1248 * *host_offset is left unchanged.
1250 * 1: if new clusters were allocated. *bytes may be decreased if the
1251 * new allocation doesn't cover all of the requested area.
1252 * *host_offset is updated to contain the host offset of the first
1253 * newly allocated cluster.
1255 * -errno: in error cases
1257 static int handle_alloc(BlockDriverState
*bs
, uint64_t guest_offset
,
1258 uint64_t *host_offset
, uint64_t *bytes
, QCowL2Meta
**m
)
1260 BDRVQcow2State
*s
= bs
->opaque
;
1264 uint64_t nb_clusters
;
1266 bool keep_old_clusters
= false;
1268 uint64_t alloc_cluster_offset
= 0;
1270 trace_qcow2_handle_alloc(qemu_coroutine_self(), guest_offset
, *host_offset
,
1275 * Calculate the number of clusters to look for. We stop at L2 table
1276 * boundaries to keep things simple.
1279 size_to_clusters(s
, offset_into_cluster(s
, guest_offset
) + *bytes
);
1281 l2_index
= offset_to_l2_index(s
, guest_offset
);
1282 nb_clusters
= MIN(nb_clusters
, s
->l2_size
- l2_index
);
1283 assert(nb_clusters
<= INT_MAX
);
1285 /* Find L2 entry for the first involved cluster */
1286 ret
= get_cluster_table(bs
, guest_offset
, &l2_table
, &l2_index
);
1291 entry
= be64_to_cpu(l2_table
[l2_index
]);
1293 /* For the moment, overwrite compressed clusters one by one */
1294 if (entry
& QCOW_OFLAG_COMPRESSED
) {
1297 nb_clusters
= count_cow_clusters(s
, nb_clusters
, l2_table
, l2_index
);
1300 /* This function is only called when there were no non-COW clusters, so if
1301 * we can't find any unallocated or COW clusters either, something is
1302 * wrong with our code. */
1303 assert(nb_clusters
> 0);
1305 if (qcow2_get_cluster_type(entry
) == QCOW2_CLUSTER_ZERO_ALLOC
&&
1306 (entry
& QCOW_OFLAG_COPIED
) &&
1308 start_of_cluster(s
, *host_offset
) == (entry
& L2E_OFFSET_MASK
)))
1310 int preallocated_nb_clusters
;
1312 if (offset_into_cluster(s
, entry
& L2E_OFFSET_MASK
)) {
1313 qcow2_signal_corruption(bs
, true, -1, -1, "Preallocated zero "
1314 "cluster offset %#llx unaligned (guest "
1315 "offset: %#" PRIx64
")",
1316 entry
& L2E_OFFSET_MASK
, guest_offset
);
1321 /* Try to reuse preallocated zero clusters; contiguous normal clusters
1322 * would be fine, too, but count_cow_clusters() above has limited
1323 * nb_clusters already to a range of COW clusters */
1324 preallocated_nb_clusters
=
1325 count_contiguous_clusters(nb_clusters
, s
->cluster_size
,
1326 &l2_table
[l2_index
], QCOW_OFLAG_COPIED
);
1327 assert(preallocated_nb_clusters
> 0);
1329 nb_clusters
= preallocated_nb_clusters
;
1330 alloc_cluster_offset
= entry
& L2E_OFFSET_MASK
;
1332 /* We want to reuse these clusters, so qcow2_alloc_cluster_link_l2()
1333 * should not free them. */
1334 keep_old_clusters
= true;
1337 qcow2_cache_put(bs
, s
->l2_table_cache
, (void **) &l2_table
);
1339 if (!alloc_cluster_offset
) {
1340 /* Allocate, if necessary at a given offset in the image file */
1341 alloc_cluster_offset
= start_of_cluster(s
, *host_offset
);
1342 ret
= do_alloc_cluster_offset(bs
, guest_offset
, &alloc_cluster_offset
,
1348 /* Can't extend contiguous allocation */
1349 if (nb_clusters
== 0) {
1354 /* !*host_offset would overwrite the image header and is reserved for
1355 * "no host offset preferred". If 0 was a valid host offset, it'd
1356 * trigger the following overlap check; do that now to avoid having an
1357 * invalid value in *host_offset. */
1358 if (!alloc_cluster_offset
) {
1359 ret
= qcow2_pre_write_overlap_check(bs
, 0, alloc_cluster_offset
,
1360 nb_clusters
* s
->cluster_size
);
1367 * Save info needed for meta data update.
1369 * requested_bytes: Number of bytes from the start of the first
1370 * newly allocated cluster to the end of the (possibly shortened
1371 * before) write request.
1373 * avail_bytes: Number of bytes from the start of the first
1374 * newly allocated to the end of the last newly allocated cluster.
1376 * nb_bytes: The number of bytes from the start of the first
1377 * newly allocated cluster to the end of the area that the write
1378 * request actually writes to (excluding COW at the end)
1380 uint64_t requested_bytes
= *bytes
+ offset_into_cluster(s
, guest_offset
);
1381 int avail_bytes
= MIN(INT_MAX
, nb_clusters
<< s
->cluster_bits
);
1382 int nb_bytes
= MIN(requested_bytes
, avail_bytes
);
1383 QCowL2Meta
*old_m
= *m
;
1385 *m
= g_malloc0(sizeof(**m
));
1387 **m
= (QCowL2Meta
) {
1390 .alloc_offset
= alloc_cluster_offset
,
1391 .offset
= start_of_cluster(s
, guest_offset
),
1392 .nb_clusters
= nb_clusters
,
1394 .keep_old_clusters
= keep_old_clusters
,
1398 .nb_bytes
= offset_into_cluster(s
, guest_offset
),
1402 .nb_bytes
= avail_bytes
- nb_bytes
,
1405 qemu_co_queue_init(&(*m
)->dependent_requests
);
1406 QLIST_INSERT_HEAD(&s
->cluster_allocs
, *m
, next_in_flight
);
1408 *host_offset
= alloc_cluster_offset
+ offset_into_cluster(s
, guest_offset
);
1409 *bytes
= MIN(*bytes
, nb_bytes
- offset_into_cluster(s
, guest_offset
));
1410 assert(*bytes
!= 0);
1415 if (*m
&& (*m
)->nb_clusters
> 0) {
1416 QLIST_REMOVE(*m
, next_in_flight
);
1422 * alloc_cluster_offset
1424 * For a given offset on the virtual disk, find the cluster offset in qcow2
1425 * file. If the offset is not found, allocate a new cluster.
1427 * If the cluster was already allocated, m->nb_clusters is set to 0 and
1428 * other fields in m are meaningless.
1430 * If the cluster is newly allocated, m->nb_clusters is set to the number of
1431 * contiguous clusters that have been allocated. In this case, the other
1432 * fields of m are valid and contain information about the first allocated
1435 * If the request conflicts with another write request in flight, the coroutine
1436 * is queued and will be reentered when the dependency has completed.
1438 * Return 0 on success and -errno in error cases
1440 int qcow2_alloc_cluster_offset(BlockDriverState
*bs
, uint64_t offset
,
1441 unsigned int *bytes
, uint64_t *host_offset
,
1444 BDRVQcow2State
*s
= bs
->opaque
;
1445 uint64_t start
, remaining
;
1446 uint64_t cluster_offset
;
1450 trace_qcow2_alloc_clusters_offset(qemu_coroutine_self(), offset
, *bytes
);
1462 if (!*host_offset
) {
1463 *host_offset
= start_of_cluster(s
, cluster_offset
);
1466 assert(remaining
>= cur_bytes
);
1469 remaining
-= cur_bytes
;
1470 cluster_offset
+= cur_bytes
;
1472 if (remaining
== 0) {
1476 cur_bytes
= remaining
;
1479 * Now start gathering as many contiguous clusters as possible:
1481 * 1. Check for overlaps with in-flight allocations
1483 * a) Overlap not in the first cluster -> shorten this request and
1484 * let the caller handle the rest in its next loop iteration.
1486 * b) Real overlaps of two requests. Yield and restart the search
1487 * for contiguous clusters (the situation could have changed
1488 * while we were sleeping)
1490 * c) TODO: Request starts in the same cluster as the in-flight
1491 * allocation ends. Shorten the COW of the in-fight allocation,
1492 * set cluster_offset to write to the same cluster and set up
1493 * the right synchronisation between the in-flight request and
1496 ret
= handle_dependencies(bs
, start
, &cur_bytes
, m
);
1497 if (ret
== -EAGAIN
) {
1498 /* Currently handle_dependencies() doesn't yield if we already had
1499 * an allocation. If it did, we would have to clean up the L2Meta
1500 * structs before starting over. */
1503 } else if (ret
< 0) {
1505 } else if (cur_bytes
== 0) {
1508 /* handle_dependencies() may have decreased cur_bytes (shortened
1509 * the allocations below) so that the next dependency is processed
1510 * correctly during the next loop iteration. */
1514 * 2. Count contiguous COPIED clusters.
1516 ret
= handle_copied(bs
, start
, &cluster_offset
, &cur_bytes
, m
);
1521 } else if (cur_bytes
== 0) {
1526 * 3. If the request still hasn't completed, allocate new clusters,
1527 * considering any cluster_offset of steps 1c or 2.
1529 ret
= handle_alloc(bs
, start
, &cluster_offset
, &cur_bytes
, m
);
1535 assert(cur_bytes
== 0);
1540 *bytes
-= remaining
;
1542 assert(*host_offset
!= 0);
1547 static int decompress_buffer(uint8_t *out_buf
, int out_buf_size
,
1548 const uint8_t *buf
, int buf_size
)
1550 z_stream strm1
, *strm
= &strm1
;
1553 memset(strm
, 0, sizeof(*strm
));
1555 strm
->next_in
= (uint8_t *)buf
;
1556 strm
->avail_in
= buf_size
;
1557 strm
->next_out
= out_buf
;
1558 strm
->avail_out
= out_buf_size
;
1560 ret
= inflateInit2(strm
, -12);
1563 ret
= inflate(strm
, Z_FINISH
);
1564 out_len
= strm
->next_out
- out_buf
;
1565 if ((ret
!= Z_STREAM_END
&& ret
!= Z_BUF_ERROR
) ||
1566 out_len
!= out_buf_size
) {
1574 int qcow2_decompress_cluster(BlockDriverState
*bs
, uint64_t cluster_offset
)
1576 BDRVQcow2State
*s
= bs
->opaque
;
1577 int ret
, csize
, nb_csectors
, sector_offset
;
1580 coffset
= cluster_offset
& s
->cluster_offset_mask
;
1581 if (s
->cluster_cache_offset
!= coffset
) {
1582 nb_csectors
= ((cluster_offset
>> s
->csize_shift
) & s
->csize_mask
) + 1;
1583 sector_offset
= coffset
& 511;
1584 csize
= nb_csectors
* 512 - sector_offset
;
1586 /* Allocate buffers on first decompress operation, most images are
1587 * uncompressed and the memory overhead can be avoided. The buffers
1588 * are freed in .bdrv_close().
1590 if (!s
->cluster_data
) {
1591 /* one more sector for decompressed data alignment */
1592 s
->cluster_data
= qemu_try_blockalign(bs
->file
->bs
,
1593 QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_size
+ 512);
1594 if (!s
->cluster_data
) {
1598 if (!s
->cluster_cache
) {
1599 s
->cluster_cache
= g_malloc(s
->cluster_size
);
1602 BLKDBG_EVENT(bs
->file
, BLKDBG_READ_COMPRESSED
);
1603 ret
= bdrv_read(bs
->file
, coffset
>> 9, s
->cluster_data
,
1608 if (decompress_buffer(s
->cluster_cache
, s
->cluster_size
,
1609 s
->cluster_data
+ sector_offset
, csize
) < 0) {
1612 s
->cluster_cache_offset
= coffset
;
1618 * This discards as many clusters of nb_clusters as possible at once (i.e.
1619 * all clusters in the same L2 table) and returns the number of discarded
1622 static int discard_single_l2(BlockDriverState
*bs
, uint64_t offset
,
1623 uint64_t nb_clusters
, enum qcow2_discard_type type
,
1626 BDRVQcow2State
*s
= bs
->opaque
;
1632 ret
= get_cluster_table(bs
, offset
, &l2_table
, &l2_index
);
1637 /* Limit nb_clusters to one L2 table */
1638 nb_clusters
= MIN(nb_clusters
, s
->l2_size
- l2_index
);
1639 assert(nb_clusters
<= INT_MAX
);
1641 for (i
= 0; i
< nb_clusters
; i
++) {
1642 uint64_t old_l2_entry
;
1644 old_l2_entry
= be64_to_cpu(l2_table
[l2_index
+ i
]);
1647 * If full_discard is false, make sure that a discarded area reads back
1648 * as zeroes for v3 images (we cannot do it for v2 without actually
1649 * writing a zero-filled buffer). We can skip the operation if the
1650 * cluster is already marked as zero, or if it's unallocated and we
1651 * don't have a backing file.
1653 * TODO We might want to use bdrv_block_status(bs) here, but we're
1654 * holding s->lock, so that doesn't work today.
1656 * If full_discard is true, the sector should not read back as zeroes,
1657 * but rather fall through to the backing file.
1659 switch (qcow2_get_cluster_type(old_l2_entry
)) {
1660 case QCOW2_CLUSTER_UNALLOCATED
:
1661 if (full_discard
|| !bs
->backing
) {
1666 case QCOW2_CLUSTER_ZERO_PLAIN
:
1667 if (!full_discard
) {
1672 case QCOW2_CLUSTER_ZERO_ALLOC
:
1673 case QCOW2_CLUSTER_NORMAL
:
1674 case QCOW2_CLUSTER_COMPRESSED
:
1681 /* First remove L2 entries */
1682 qcow2_cache_entry_mark_dirty(bs
, s
->l2_table_cache
, l2_table
);
1683 if (!full_discard
&& s
->qcow_version
>= 3) {
1684 l2_table
[l2_index
+ i
] = cpu_to_be64(QCOW_OFLAG_ZERO
);
1686 l2_table
[l2_index
+ i
] = cpu_to_be64(0);
1689 /* Then decrease the refcount */
1690 qcow2_free_any_clusters(bs
, old_l2_entry
, 1, type
);
1693 qcow2_cache_put(bs
, s
->l2_table_cache
, (void **) &l2_table
);
1698 int qcow2_cluster_discard(BlockDriverState
*bs
, uint64_t offset
,
1699 uint64_t bytes
, enum qcow2_discard_type type
,
1702 BDRVQcow2State
*s
= bs
->opaque
;
1703 uint64_t end_offset
= offset
+ bytes
;
1704 uint64_t nb_clusters
;
1708 /* Caller must pass aligned values, except at image end */
1709 assert(QEMU_IS_ALIGNED(offset
, s
->cluster_size
));
1710 assert(QEMU_IS_ALIGNED(end_offset
, s
->cluster_size
) ||
1711 end_offset
== bs
->total_sectors
<< BDRV_SECTOR_BITS
);
1713 nb_clusters
= size_to_clusters(s
, bytes
);
1715 s
->cache_discards
= true;
1717 /* Each L2 table is handled by its own loop iteration */
1718 while (nb_clusters
> 0) {
1719 cleared
= discard_single_l2(bs
, offset
, nb_clusters
, type
,
1726 nb_clusters
-= cleared
;
1727 offset
+= (cleared
* s
->cluster_size
);
1732 s
->cache_discards
= false;
1733 qcow2_process_discards(bs
, ret
);
1739 * This zeroes as many clusters of nb_clusters as possible at once (i.e.
1740 * all clusters in the same L2 table) and returns the number of zeroed
1743 static int zero_single_l2(BlockDriverState
*bs
, uint64_t offset
,
1744 uint64_t nb_clusters
, int flags
)
1746 BDRVQcow2State
*s
= bs
->opaque
;
1751 bool unmap
= !!(flags
& BDRV_REQ_MAY_UNMAP
);
1753 ret
= get_cluster_table(bs
, offset
, &l2_table
, &l2_index
);
1758 /* Limit nb_clusters to one L2 table */
1759 nb_clusters
= MIN(nb_clusters
, s
->l2_size
- l2_index
);
1760 assert(nb_clusters
<= INT_MAX
);
1762 for (i
= 0; i
< nb_clusters
; i
++) {
1763 uint64_t old_offset
;
1764 QCow2ClusterType cluster_type
;
1766 old_offset
= be64_to_cpu(l2_table
[l2_index
+ i
]);
1769 * Minimize L2 changes if the cluster already reads back as
1770 * zeroes with correct allocation.
1772 cluster_type
= qcow2_get_cluster_type(old_offset
);
1773 if (cluster_type
== QCOW2_CLUSTER_ZERO_PLAIN
||
1774 (cluster_type
== QCOW2_CLUSTER_ZERO_ALLOC
&& !unmap
)) {
1778 qcow2_cache_entry_mark_dirty(bs
, s
->l2_table_cache
, l2_table
);
1779 if (cluster_type
== QCOW2_CLUSTER_COMPRESSED
|| unmap
) {
1780 l2_table
[l2_index
+ i
] = cpu_to_be64(QCOW_OFLAG_ZERO
);
1781 qcow2_free_any_clusters(bs
, old_offset
, 1, QCOW2_DISCARD_REQUEST
);
1783 l2_table
[l2_index
+ i
] |= cpu_to_be64(QCOW_OFLAG_ZERO
);
1787 qcow2_cache_put(bs
, s
->l2_table_cache
, (void **) &l2_table
);
1792 int qcow2_cluster_zeroize(BlockDriverState
*bs
, uint64_t offset
,
1793 uint64_t bytes
, int flags
)
1795 BDRVQcow2State
*s
= bs
->opaque
;
1796 uint64_t end_offset
= offset
+ bytes
;
1797 uint64_t nb_clusters
;
1801 /* Caller must pass aligned values, except at image end */
1802 assert(QEMU_IS_ALIGNED(offset
, s
->cluster_size
));
1803 assert(QEMU_IS_ALIGNED(end_offset
, s
->cluster_size
) ||
1804 end_offset
== bs
->total_sectors
<< BDRV_SECTOR_BITS
);
1806 /* The zero flag is only supported by version 3 and newer */
1807 if (s
->qcow_version
< 3) {
1811 /* Each L2 table is handled by its own loop iteration */
1812 nb_clusters
= size_to_clusters(s
, bytes
);
1814 s
->cache_discards
= true;
1816 while (nb_clusters
> 0) {
1817 cleared
= zero_single_l2(bs
, offset
, nb_clusters
, flags
);
1823 nb_clusters
-= cleared
;
1824 offset
+= (cleared
* s
->cluster_size
);
1829 s
->cache_discards
= false;
1830 qcow2_process_discards(bs
, ret
);
1836 * Expands all zero clusters in a specific L1 table (or deallocates them, for
1837 * non-backed non-pre-allocated zero clusters).
1839 * l1_entries and *visited_l1_entries are used to keep track of progress for
1840 * status_cb(). l1_entries contains the total number of L1 entries and
1841 * *visited_l1_entries counts all visited L1 entries.
1843 static int expand_zero_clusters_in_l1(BlockDriverState
*bs
, uint64_t *l1_table
,
1844 int l1_size
, int64_t *visited_l1_entries
,
1846 BlockDriverAmendStatusCB
*status_cb
,
1849 BDRVQcow2State
*s
= bs
->opaque
;
1850 bool is_active_l1
= (l1_table
== s
->l1_table
);
1851 uint64_t *l2_table
= NULL
;
1855 if (!is_active_l1
) {
1856 /* inactive L2 tables require a buffer to be stored in when loading
1858 l2_table
= qemu_try_blockalign(bs
->file
->bs
, s
->cluster_size
);
1859 if (l2_table
== NULL
) {
1864 for (i
= 0; i
< l1_size
; i
++) {
1865 uint64_t l2_offset
= l1_table
[i
] & L1E_OFFSET_MASK
;
1866 bool l2_dirty
= false;
1867 uint64_t l2_refcount
;
1871 (*visited_l1_entries
)++;
1873 status_cb(bs
, *visited_l1_entries
, l1_entries
, cb_opaque
);
1878 if (offset_into_cluster(s
, l2_offset
)) {
1879 qcow2_signal_corruption(bs
, true, -1, -1, "L2 table offset %#"
1880 PRIx64
" unaligned (L1 index: %#x)",
1887 /* get active L2 tables from cache */
1888 ret
= qcow2_cache_get(bs
, s
->l2_table_cache
, l2_offset
,
1889 (void **)&l2_table
);
1891 /* load inactive L2 tables from disk */
1892 ret
= bdrv_read(bs
->file
, l2_offset
/ BDRV_SECTOR_SIZE
,
1893 (void *)l2_table
, s
->cluster_sectors
);
1899 ret
= qcow2_get_refcount(bs
, l2_offset
>> s
->cluster_bits
,
1905 for (j
= 0; j
< s
->l2_size
; j
++) {
1906 uint64_t l2_entry
= be64_to_cpu(l2_table
[j
]);
1907 int64_t offset
= l2_entry
& L2E_OFFSET_MASK
;
1908 QCow2ClusterType cluster_type
= qcow2_get_cluster_type(l2_entry
);
1910 if (cluster_type
!= QCOW2_CLUSTER_ZERO_PLAIN
&&
1911 cluster_type
!= QCOW2_CLUSTER_ZERO_ALLOC
) {
1915 if (cluster_type
== QCOW2_CLUSTER_ZERO_PLAIN
) {
1917 /* not backed; therefore we can simply deallocate the
1924 offset
= qcow2_alloc_clusters(bs
, s
->cluster_size
);
1930 if (l2_refcount
> 1) {
1931 /* For shared L2 tables, set the refcount accordingly (it is
1932 * already 1 and needs to be l2_refcount) */
1933 ret
= qcow2_update_cluster_refcount(bs
,
1934 offset
>> s
->cluster_bits
,
1935 refcount_diff(1, l2_refcount
), false,
1936 QCOW2_DISCARD_OTHER
);
1938 qcow2_free_clusters(bs
, offset
, s
->cluster_size
,
1939 QCOW2_DISCARD_OTHER
);
1945 if (offset_into_cluster(s
, offset
)) {
1946 qcow2_signal_corruption(bs
, true, -1, -1,
1947 "Cluster allocation offset "
1948 "%#" PRIx64
" unaligned (L2 offset: %#"
1949 PRIx64
", L2 index: %#x)", offset
,
1951 if (cluster_type
== QCOW2_CLUSTER_ZERO_PLAIN
) {
1952 qcow2_free_clusters(bs
, offset
, s
->cluster_size
,
1953 QCOW2_DISCARD_ALWAYS
);
1959 ret
= qcow2_pre_write_overlap_check(bs
, 0, offset
, s
->cluster_size
);
1961 if (cluster_type
== QCOW2_CLUSTER_ZERO_PLAIN
) {
1962 qcow2_free_clusters(bs
, offset
, s
->cluster_size
,
1963 QCOW2_DISCARD_ALWAYS
);
1968 ret
= bdrv_pwrite_zeroes(bs
->file
, offset
, s
->cluster_size
, 0);
1970 if (cluster_type
== QCOW2_CLUSTER_ZERO_PLAIN
) {
1971 qcow2_free_clusters(bs
, offset
, s
->cluster_size
,
1972 QCOW2_DISCARD_ALWAYS
);
1977 if (l2_refcount
== 1) {
1978 l2_table
[j
] = cpu_to_be64(offset
| QCOW_OFLAG_COPIED
);
1980 l2_table
[j
] = cpu_to_be64(offset
);
1987 qcow2_cache_entry_mark_dirty(bs
, s
->l2_table_cache
, l2_table
);
1988 qcow2_cache_depends_on_flush(s
->l2_table_cache
);
1990 qcow2_cache_put(bs
, s
->l2_table_cache
, (void **) &l2_table
);
1993 ret
= qcow2_pre_write_overlap_check(bs
,
1994 QCOW2_OL_INACTIVE_L2
| QCOW2_OL_ACTIVE_L2
, l2_offset
,
2000 ret
= bdrv_write(bs
->file
, l2_offset
/ BDRV_SECTOR_SIZE
,
2001 (void *)l2_table
, s
->cluster_sectors
);
2008 (*visited_l1_entries
)++;
2010 status_cb(bs
, *visited_l1_entries
, l1_entries
, cb_opaque
);
2018 if (!is_active_l1
) {
2019 qemu_vfree(l2_table
);
2021 qcow2_cache_put(bs
, s
->l2_table_cache
, (void **) &l2_table
);
2028 * For backed images, expands all zero clusters on the image. For non-backed
2029 * images, deallocates all non-pre-allocated zero clusters (and claims the
2030 * allocation for pre-allocated ones). This is important for downgrading to a
2031 * qcow2 version which doesn't yet support metadata zero clusters.
2033 int qcow2_expand_zero_clusters(BlockDriverState
*bs
,
2034 BlockDriverAmendStatusCB
*status_cb
,
2037 BDRVQcow2State
*s
= bs
->opaque
;
2038 uint64_t *l1_table
= NULL
;
2039 int64_t l1_entries
= 0, visited_l1_entries
= 0;
2044 l1_entries
= s
->l1_size
;
2045 for (i
= 0; i
< s
->nb_snapshots
; i
++) {
2046 l1_entries
+= s
->snapshots
[i
].l1_size
;
2050 ret
= expand_zero_clusters_in_l1(bs
, s
->l1_table
, s
->l1_size
,
2051 &visited_l1_entries
, l1_entries
,
2052 status_cb
, cb_opaque
);
2057 /* Inactive L1 tables may point to active L2 tables - therefore it is
2058 * necessary to flush the L2 table cache before trying to access the L2
2059 * tables pointed to by inactive L1 entries (else we might try to expand
2060 * zero clusters that have already been expanded); furthermore, it is also
2061 * necessary to empty the L2 table cache, since it may contain tables which
2062 * are now going to be modified directly on disk, bypassing the cache.
2063 * qcow2_cache_empty() does both for us. */
2064 ret
= qcow2_cache_empty(bs
, s
->l2_table_cache
);
2069 for (i
= 0; i
< s
->nb_snapshots
; i
++) {
2070 int l1_sectors
= DIV_ROUND_UP(s
->snapshots
[i
].l1_size
*
2071 sizeof(uint64_t), BDRV_SECTOR_SIZE
);
2073 l1_table
= g_realloc(l1_table
, l1_sectors
* BDRV_SECTOR_SIZE
);
2075 ret
= bdrv_read(bs
->file
,
2076 s
->snapshots
[i
].l1_table_offset
/ BDRV_SECTOR_SIZE
,
2077 (void *)l1_table
, l1_sectors
);
2082 for (j
= 0; j
< s
->snapshots
[i
].l1_size
; j
++) {
2083 be64_to_cpus(&l1_table
[j
]);
2086 ret
= expand_zero_clusters_in_l1(bs
, l1_table
, s
->snapshots
[i
].l1_size
,
2087 &visited_l1_entries
, l1_entries
,
2088 status_cb
, cb_opaque
);