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 "qapi/error.h"
29 #include "qemu-common.h"
30 #include "block/block_int.h"
32 #include "qemu/bswap.h"
35 int qcow2_shrink_l1_table(BlockDriverState
*bs
, uint64_t exact_size
)
37 BDRVQcow2State
*s
= bs
->opaque
;
38 int new_l1_size
, i
, ret
;
40 if (exact_size
>= s
->l1_size
) {
44 new_l1_size
= exact_size
;
47 fprintf(stderr
, "shrink l1_table from %d to %d\n", s
->l1_size
, new_l1_size
);
50 BLKDBG_EVENT(bs
->file
, BLKDBG_L1_SHRINK_WRITE_TABLE
);
51 ret
= bdrv_pwrite_zeroes(bs
->file
, s
->l1_table_offset
+
52 new_l1_size
* sizeof(uint64_t),
53 (s
->l1_size
- new_l1_size
) * sizeof(uint64_t), 0);
58 ret
= bdrv_flush(bs
->file
->bs
);
63 BLKDBG_EVENT(bs
->file
, BLKDBG_L1_SHRINK_FREE_L2_CLUSTERS
);
64 for (i
= s
->l1_size
- 1; i
> new_l1_size
- 1; i
--) {
65 if ((s
->l1_table
[i
] & L1E_OFFSET_MASK
) == 0) {
68 qcow2_free_clusters(bs
, s
->l1_table
[i
] & L1E_OFFSET_MASK
,
69 s
->cluster_size
, QCOW2_DISCARD_ALWAYS
);
76 * If the write in the l1_table failed the image may contain a partially
77 * overwritten l1_table. In this case it would be better to clear the
78 * l1_table in memory to avoid possible image corruption.
80 memset(s
->l1_table
+ new_l1_size
, 0,
81 (s
->l1_size
- new_l1_size
) * sizeof(uint64_t));
85 int qcow2_grow_l1_table(BlockDriverState
*bs
, uint64_t min_size
,
88 BDRVQcow2State
*s
= bs
->opaque
;
89 int new_l1_size2
, ret
, i
;
90 uint64_t *new_l1_table
;
91 int64_t old_l1_table_offset
, old_l1_size
;
92 int64_t new_l1_table_offset
, new_l1_size
;
95 if (min_size
<= s
->l1_size
)
98 /* Do a sanity check on min_size before trying to calculate new_l1_size
99 * (this prevents overflows during the while loop for the calculation of
101 if (min_size
> INT_MAX
/ sizeof(uint64_t)) {
106 new_l1_size
= min_size
;
108 /* Bump size up to reduce the number of times we have to grow */
109 new_l1_size
= s
->l1_size
;
110 if (new_l1_size
== 0) {
113 while (min_size
> new_l1_size
) {
114 new_l1_size
= DIV_ROUND_UP(new_l1_size
* 3, 2);
118 QEMU_BUILD_BUG_ON(QCOW_MAX_L1_SIZE
> INT_MAX
);
119 if (new_l1_size
> QCOW_MAX_L1_SIZE
/ sizeof(uint64_t)) {
124 fprintf(stderr
, "grow l1_table from %d to %" PRId64
"\n",
125 s
->l1_size
, new_l1_size
);
128 new_l1_size2
= sizeof(uint64_t) * new_l1_size
;
129 new_l1_table
= qemu_try_blockalign(bs
->file
->bs
,
130 ROUND_UP(new_l1_size2
, 512));
131 if (new_l1_table
== NULL
) {
134 memset(new_l1_table
, 0, ROUND_UP(new_l1_size2
, 512));
137 memcpy(new_l1_table
, s
->l1_table
, s
->l1_size
* sizeof(uint64_t));
140 /* write new table (align to cluster) */
141 BLKDBG_EVENT(bs
->file
, BLKDBG_L1_GROW_ALLOC_TABLE
);
142 new_l1_table_offset
= qcow2_alloc_clusters(bs
, new_l1_size2
);
143 if (new_l1_table_offset
< 0) {
144 qemu_vfree(new_l1_table
);
145 return new_l1_table_offset
;
148 ret
= qcow2_cache_flush(bs
, s
->refcount_block_cache
);
153 /* the L1 position has not yet been updated, so these clusters must
154 * indeed be completely free */
155 ret
= qcow2_pre_write_overlap_check(bs
, 0, new_l1_table_offset
,
161 BLKDBG_EVENT(bs
->file
, BLKDBG_L1_GROW_WRITE_TABLE
);
162 for(i
= 0; i
< s
->l1_size
; i
++)
163 new_l1_table
[i
] = cpu_to_be64(new_l1_table
[i
]);
164 ret
= bdrv_pwrite_sync(bs
->file
, new_l1_table_offset
,
165 new_l1_table
, new_l1_size2
);
168 for(i
= 0; i
< s
->l1_size
; i
++)
169 new_l1_table
[i
] = be64_to_cpu(new_l1_table
[i
]);
172 BLKDBG_EVENT(bs
->file
, BLKDBG_L1_GROW_ACTIVATE_TABLE
);
173 stl_be_p(data
, new_l1_size
);
174 stq_be_p(data
+ 4, new_l1_table_offset
);
175 ret
= bdrv_pwrite_sync(bs
->file
, offsetof(QCowHeader
, l1_size
),
180 qemu_vfree(s
->l1_table
);
181 old_l1_table_offset
= s
->l1_table_offset
;
182 s
->l1_table_offset
= new_l1_table_offset
;
183 s
->l1_table
= new_l1_table
;
184 old_l1_size
= s
->l1_size
;
185 s
->l1_size
= new_l1_size
;
186 qcow2_free_clusters(bs
, old_l1_table_offset
, old_l1_size
* sizeof(uint64_t),
187 QCOW2_DISCARD_OTHER
);
190 qemu_vfree(new_l1_table
);
191 qcow2_free_clusters(bs
, new_l1_table_offset
, new_l1_size2
,
192 QCOW2_DISCARD_OTHER
);
199 * @bs: The BlockDriverState
200 * @offset: A guest offset, used to calculate what slice of the L2
202 * @l2_offset: Offset to the L2 table in the image file.
203 * @l2_slice: Location to store the pointer to the L2 slice.
205 * Loads a L2 slice into memory (L2 slices are the parts of L2 tables
206 * that are loaded by the qcow2 cache). If the slice is in the cache,
207 * the cache is used; otherwise the L2 slice is loaded from the image
210 static int l2_load(BlockDriverState
*bs
, uint64_t offset
,
211 uint64_t l2_offset
, uint64_t **l2_slice
)
213 BDRVQcow2State
*s
= bs
->opaque
;
214 int start_of_slice
= sizeof(uint64_t) *
215 (offset_to_l2_index(s
, offset
) - offset_to_l2_slice_index(s
, offset
));
217 return qcow2_cache_get(bs
, s
->l2_table_cache
, l2_offset
+ start_of_slice
,
222 * Writes one sector of the L1 table to the disk (can't update single entries
223 * and we really don't want bdrv_pread to perform a read-modify-write)
225 #define L1_ENTRIES_PER_SECTOR (512 / 8)
226 int qcow2_write_l1_entry(BlockDriverState
*bs
, int l1_index
)
228 BDRVQcow2State
*s
= bs
->opaque
;
229 uint64_t buf
[L1_ENTRIES_PER_SECTOR
] = { 0 };
233 l1_start_index
= l1_index
& ~(L1_ENTRIES_PER_SECTOR
- 1);
234 for (i
= 0; i
< L1_ENTRIES_PER_SECTOR
&& l1_start_index
+ i
< s
->l1_size
;
237 buf
[i
] = cpu_to_be64(s
->l1_table
[l1_start_index
+ i
]);
240 ret
= qcow2_pre_write_overlap_check(bs
, QCOW2_OL_ACTIVE_L1
,
241 s
->l1_table_offset
+ 8 * l1_start_index
, sizeof(buf
));
246 BLKDBG_EVENT(bs
->file
, BLKDBG_L1_UPDATE
);
247 ret
= bdrv_pwrite_sync(bs
->file
,
248 s
->l1_table_offset
+ 8 * l1_start_index
,
260 * Allocate a new l2 entry in the file. If l1_index points to an already
261 * used entry in the L2 table (i.e. we are doing a copy on write for the L2
262 * table) copy the contents of the old L2 table into the newly allocated one.
263 * Otherwise the new table is initialized with zeros.
267 static int l2_allocate(BlockDriverState
*bs
, int l1_index
)
269 BDRVQcow2State
*s
= bs
->opaque
;
270 uint64_t old_l2_offset
;
271 uint64_t *l2_slice
= NULL
;
272 unsigned slice
, slice_size2
, n_slices
;
276 old_l2_offset
= s
->l1_table
[l1_index
];
278 trace_qcow2_l2_allocate(bs
, l1_index
);
280 /* allocate a new l2 entry */
282 l2_offset
= qcow2_alloc_clusters(bs
, s
->l2_size
* sizeof(uint64_t));
288 /* The offset must fit in the offset field of the L1 table entry */
289 assert((l2_offset
& L1E_OFFSET_MASK
) == l2_offset
);
291 /* If we're allocating the table at offset 0 then something is wrong */
292 if (l2_offset
== 0) {
293 qcow2_signal_corruption(bs
, true, -1, -1, "Preventing invalid "
294 "allocation of L2 table at offset 0");
299 ret
= qcow2_cache_flush(bs
, s
->refcount_block_cache
);
304 /* allocate a new entry in the l2 cache */
306 slice_size2
= s
->l2_slice_size
* sizeof(uint64_t);
307 n_slices
= s
->cluster_size
/ slice_size2
;
309 trace_qcow2_l2_allocate_get_empty(bs
, l1_index
);
310 for (slice
= 0; slice
< n_slices
; slice
++) {
311 ret
= qcow2_cache_get_empty(bs
, s
->l2_table_cache
,
312 l2_offset
+ slice
* slice_size2
,
313 (void **) &l2_slice
);
318 if ((old_l2_offset
& L1E_OFFSET_MASK
) == 0) {
319 /* if there was no old l2 table, clear the new slice */
320 memset(l2_slice
, 0, slice_size2
);
323 uint64_t old_l2_slice_offset
=
324 (old_l2_offset
& L1E_OFFSET_MASK
) + slice
* slice_size2
;
326 /* if there was an old l2 table, read a slice from the disk */
327 BLKDBG_EVENT(bs
->file
, BLKDBG_L2_ALLOC_COW_READ
);
328 ret
= qcow2_cache_get(bs
, s
->l2_table_cache
, old_l2_slice_offset
,
329 (void **) &old_slice
);
334 memcpy(l2_slice
, old_slice
, slice_size2
);
336 qcow2_cache_put(s
->l2_table_cache
, (void **) &old_slice
);
339 /* write the l2 slice to the file */
340 BLKDBG_EVENT(bs
->file
, BLKDBG_L2_ALLOC_WRITE
);
342 trace_qcow2_l2_allocate_write_l2(bs
, l1_index
);
343 qcow2_cache_entry_mark_dirty(s
->l2_table_cache
, l2_slice
);
344 qcow2_cache_put(s
->l2_table_cache
, (void **) &l2_slice
);
347 ret
= qcow2_cache_flush(bs
, s
->l2_table_cache
);
352 /* update the L1 entry */
353 trace_qcow2_l2_allocate_write_l1(bs
, l1_index
);
354 s
->l1_table
[l1_index
] = l2_offset
| QCOW_OFLAG_COPIED
;
355 ret
= qcow2_write_l1_entry(bs
, l1_index
);
360 trace_qcow2_l2_allocate_done(bs
, l1_index
, 0);
364 trace_qcow2_l2_allocate_done(bs
, l1_index
, ret
);
365 if (l2_slice
!= NULL
) {
366 qcow2_cache_put(s
->l2_table_cache
, (void **) &l2_slice
);
368 s
->l1_table
[l1_index
] = old_l2_offset
;
370 qcow2_free_clusters(bs
, l2_offset
, s
->l2_size
* sizeof(uint64_t),
371 QCOW2_DISCARD_ALWAYS
);
377 * Checks how many clusters in a given L2 slice are contiguous in the image
378 * file. As soon as one of the flags in the bitmask stop_flags changes compared
379 * to the first cluster, the search is stopped and the cluster is not counted
380 * as contiguous. (This allows it, for example, to stop at the first compressed
381 * cluster which may require a different handling)
383 static int count_contiguous_clusters(BlockDriverState
*bs
, int nb_clusters
,
384 int cluster_size
, uint64_t *l2_slice
, uint64_t stop_flags
)
387 QCow2ClusterType first_cluster_type
;
388 uint64_t mask
= stop_flags
| L2E_OFFSET_MASK
| QCOW_OFLAG_COMPRESSED
;
389 uint64_t first_entry
= be64_to_cpu(l2_slice
[0]);
390 uint64_t offset
= first_entry
& mask
;
392 first_cluster_type
= qcow2_get_cluster_type(bs
, first_entry
);
393 if (first_cluster_type
== QCOW2_CLUSTER_UNALLOCATED
) {
397 /* must be allocated */
398 assert(first_cluster_type
== QCOW2_CLUSTER_NORMAL
||
399 first_cluster_type
== QCOW2_CLUSTER_ZERO_ALLOC
);
401 for (i
= 0; i
< nb_clusters
; i
++) {
402 uint64_t l2_entry
= be64_to_cpu(l2_slice
[i
]) & mask
;
403 if (offset
+ (uint64_t) i
* cluster_size
!= l2_entry
) {
412 * Checks how many consecutive unallocated clusters in a given L2
413 * slice have the same cluster type.
415 static int count_contiguous_clusters_unallocated(BlockDriverState
*bs
,
418 QCow2ClusterType wanted_type
)
422 assert(wanted_type
== QCOW2_CLUSTER_ZERO_PLAIN
||
423 wanted_type
== QCOW2_CLUSTER_UNALLOCATED
);
424 for (i
= 0; i
< nb_clusters
; i
++) {
425 uint64_t entry
= be64_to_cpu(l2_slice
[i
]);
426 QCow2ClusterType type
= qcow2_get_cluster_type(bs
, entry
);
428 if (type
!= wanted_type
) {
436 static int coroutine_fn
do_perform_cow_read(BlockDriverState
*bs
,
437 uint64_t src_cluster_offset
,
438 unsigned offset_in_cluster
,
443 if (qiov
->size
== 0) {
447 BLKDBG_EVENT(bs
->file
, BLKDBG_COW_READ
);
453 /* Call .bdrv_co_readv() directly instead of using the public block-layer
454 * interface. This avoids double I/O throttling and request tracking,
455 * which can lead to deadlock when block layer copy-on-read is enabled.
457 ret
= bs
->drv
->bdrv_co_preadv(bs
, src_cluster_offset
+ offset_in_cluster
,
458 qiov
->size
, qiov
, 0);
466 static bool coroutine_fn
do_perform_cow_encrypt(BlockDriverState
*bs
,
467 uint64_t src_cluster_offset
,
468 uint64_t cluster_offset
,
469 unsigned offset_in_cluster
,
473 if (bytes
&& bs
->encrypted
) {
474 BDRVQcow2State
*s
= bs
->opaque
;
475 int64_t offset
= (s
->crypt_physical_offset
?
476 (cluster_offset
+ offset_in_cluster
) :
477 (src_cluster_offset
+ offset_in_cluster
));
478 assert((offset_in_cluster
& ~BDRV_SECTOR_MASK
) == 0);
479 assert((bytes
& ~BDRV_SECTOR_MASK
) == 0);
481 if (qcrypto_block_encrypt(s
->crypto
, offset
, buffer
, bytes
, NULL
) < 0) {
488 static int coroutine_fn
do_perform_cow_write(BlockDriverState
*bs
,
489 uint64_t cluster_offset
,
490 unsigned offset_in_cluster
,
495 if (qiov
->size
== 0) {
499 ret
= qcow2_pre_write_overlap_check(bs
, 0,
500 cluster_offset
+ offset_in_cluster
, qiov
->size
);
505 BLKDBG_EVENT(bs
->file
, BLKDBG_COW_WRITE
);
506 ret
= bdrv_co_pwritev(bs
->file
, cluster_offset
+ offset_in_cluster
,
507 qiov
->size
, qiov
, 0);
519 * For a given offset of the virtual disk, find the cluster type and offset in
520 * the qcow2 file. The offset is stored in *cluster_offset.
522 * On entry, *bytes is the maximum number of contiguous bytes starting at
523 * offset that we are interested in.
525 * On exit, *bytes is the number of bytes starting at offset that have the same
526 * cluster type and (if applicable) are stored contiguously in the image file.
527 * Compressed clusters are always returned one by one.
529 * Returns the cluster type (QCOW2_CLUSTER_*) on success, -errno in error
532 int qcow2_get_cluster_offset(BlockDriverState
*bs
, uint64_t offset
,
533 unsigned int *bytes
, uint64_t *cluster_offset
)
535 BDRVQcow2State
*s
= bs
->opaque
;
536 unsigned int l2_index
;
537 uint64_t l1_index
, l2_offset
, *l2_slice
;
539 unsigned int offset_in_cluster
;
540 uint64_t bytes_available
, bytes_needed
, nb_clusters
;
541 QCow2ClusterType type
;
544 offset_in_cluster
= offset_into_cluster(s
, offset
);
545 bytes_needed
= (uint64_t) *bytes
+ offset_in_cluster
;
547 /* compute how many bytes there are between the start of the cluster
548 * containing offset and the end of the l2 slice that contains
549 * the entry pointing to it */
551 ((uint64_t) (s
->l2_slice_size
- offset_to_l2_slice_index(s
, offset
)))
554 if (bytes_needed
> bytes_available
) {
555 bytes_needed
= bytes_available
;
560 /* seek to the l2 offset in the l1 table */
562 l1_index
= offset_to_l1_index(s
, offset
);
563 if (l1_index
>= s
->l1_size
) {
564 type
= QCOW2_CLUSTER_UNALLOCATED
;
568 l2_offset
= s
->l1_table
[l1_index
] & L1E_OFFSET_MASK
;
570 type
= QCOW2_CLUSTER_UNALLOCATED
;
574 if (offset_into_cluster(s
, l2_offset
)) {
575 qcow2_signal_corruption(bs
, true, -1, -1, "L2 table offset %#" PRIx64
576 " unaligned (L1 index: %#" PRIx64
")",
577 l2_offset
, l1_index
);
581 /* load the l2 slice in memory */
583 ret
= l2_load(bs
, offset
, l2_offset
, &l2_slice
);
588 /* find the cluster offset for the given disk offset */
590 l2_index
= offset_to_l2_slice_index(s
, offset
);
591 *cluster_offset
= be64_to_cpu(l2_slice
[l2_index
]);
593 nb_clusters
= size_to_clusters(s
, bytes_needed
);
594 /* bytes_needed <= *bytes + offset_in_cluster, both of which are unsigned
595 * integers; the minimum cluster size is 512, so this assertion is always
597 assert(nb_clusters
<= INT_MAX
);
599 type
= qcow2_get_cluster_type(bs
, *cluster_offset
);
600 if (s
->qcow_version
< 3 && (type
== QCOW2_CLUSTER_ZERO_PLAIN
||
601 type
== QCOW2_CLUSTER_ZERO_ALLOC
)) {
602 qcow2_signal_corruption(bs
, true, -1, -1, "Zero cluster entry found"
603 " in pre-v3 image (L2 offset: %#" PRIx64
604 ", L2 index: %#x)", l2_offset
, l2_index
);
609 case QCOW2_CLUSTER_COMPRESSED
:
610 /* Compressed clusters can only be processed one by one */
612 *cluster_offset
&= L2E_COMPRESSED_OFFSET_SIZE_MASK
;
614 case QCOW2_CLUSTER_ZERO_PLAIN
:
615 case QCOW2_CLUSTER_UNALLOCATED
:
616 /* how many empty clusters ? */
617 c
= count_contiguous_clusters_unallocated(bs
, nb_clusters
,
618 &l2_slice
[l2_index
], type
);
621 case QCOW2_CLUSTER_ZERO_ALLOC
:
622 case QCOW2_CLUSTER_NORMAL
:
623 /* how many allocated clusters ? */
624 c
= count_contiguous_clusters(bs
, nb_clusters
, s
->cluster_size
,
625 &l2_slice
[l2_index
], QCOW_OFLAG_ZERO
);
626 *cluster_offset
&= L2E_OFFSET_MASK
;
627 if (offset_into_cluster(s
, *cluster_offset
)) {
628 qcow2_signal_corruption(bs
, true, -1, -1,
629 "Cluster allocation offset %#"
630 PRIx64
" unaligned (L2 offset: %#" PRIx64
631 ", L2 index: %#x)", *cluster_offset
,
632 l2_offset
, l2_index
);
641 qcow2_cache_put(s
->l2_table_cache
, (void **) &l2_slice
);
643 bytes_available
= (int64_t)c
* s
->cluster_size
;
646 if (bytes_available
> bytes_needed
) {
647 bytes_available
= bytes_needed
;
650 /* bytes_available <= bytes_needed <= *bytes + offset_in_cluster;
651 * subtracting offset_in_cluster will therefore definitely yield something
652 * not exceeding UINT_MAX */
653 assert(bytes_available
- offset_in_cluster
<= UINT_MAX
);
654 *bytes
= bytes_available
- offset_in_cluster
;
659 qcow2_cache_put(s
->l2_table_cache
, (void **)&l2_slice
);
666 * for a given disk offset, load (and allocate if needed)
667 * the appropriate slice of its l2 table.
669 * the cluster index in the l2 slice is given to the caller.
671 * Returns 0 on success, -errno in failure case
673 static int get_cluster_table(BlockDriverState
*bs
, uint64_t offset
,
674 uint64_t **new_l2_slice
,
677 BDRVQcow2State
*s
= bs
->opaque
;
678 unsigned int l2_index
;
679 uint64_t l1_index
, l2_offset
;
680 uint64_t *l2_slice
= NULL
;
683 /* seek to the l2 offset in the l1 table */
685 l1_index
= offset_to_l1_index(s
, offset
);
686 if (l1_index
>= s
->l1_size
) {
687 ret
= qcow2_grow_l1_table(bs
, l1_index
+ 1, false);
693 assert(l1_index
< s
->l1_size
);
694 l2_offset
= s
->l1_table
[l1_index
] & L1E_OFFSET_MASK
;
695 if (offset_into_cluster(s
, l2_offset
)) {
696 qcow2_signal_corruption(bs
, true, -1, -1, "L2 table offset %#" PRIx64
697 " unaligned (L1 index: %#" PRIx64
")",
698 l2_offset
, l1_index
);
702 if (!(s
->l1_table
[l1_index
] & QCOW_OFLAG_COPIED
)) {
703 /* First allocate a new L2 table (and do COW if needed) */
704 ret
= l2_allocate(bs
, l1_index
);
709 /* Then decrease the refcount of the old table */
711 qcow2_free_clusters(bs
, l2_offset
, s
->l2_size
* sizeof(uint64_t),
712 QCOW2_DISCARD_OTHER
);
715 /* Get the offset of the newly-allocated l2 table */
716 l2_offset
= s
->l1_table
[l1_index
] & L1E_OFFSET_MASK
;
717 assert(offset_into_cluster(s
, l2_offset
) == 0);
720 /* load the l2 slice in memory */
721 ret
= l2_load(bs
, offset
, l2_offset
, &l2_slice
);
726 /* find the cluster offset for the given disk offset */
728 l2_index
= offset_to_l2_slice_index(s
, offset
);
730 *new_l2_slice
= l2_slice
;
731 *new_l2_index
= l2_index
;
737 * alloc_compressed_cluster_offset
739 * For a given offset on the virtual disk, allocate a new compressed cluster
740 * and put the host offset of the cluster into *host_offset. If a cluster is
741 * already allocated at the offset, return an error.
743 * Return 0 on success and -errno in error cases
745 int qcow2_alloc_compressed_cluster_offset(BlockDriverState
*bs
,
748 uint64_t *host_offset
)
750 BDRVQcow2State
*s
= bs
->opaque
;
753 int64_t cluster_offset
;
756 ret
= get_cluster_table(bs
, offset
, &l2_slice
, &l2_index
);
761 /* Compression can't overwrite anything. Fail if the cluster was already
763 cluster_offset
= be64_to_cpu(l2_slice
[l2_index
]);
764 if (cluster_offset
& L2E_OFFSET_MASK
) {
765 qcow2_cache_put(s
->l2_table_cache
, (void **) &l2_slice
);
769 cluster_offset
= qcow2_alloc_bytes(bs
, compressed_size
);
770 if (cluster_offset
< 0) {
771 qcow2_cache_put(s
->l2_table_cache
, (void **) &l2_slice
);
772 return cluster_offset
;
775 nb_csectors
= ((cluster_offset
+ compressed_size
- 1) >> 9) -
776 (cluster_offset
>> 9);
778 cluster_offset
|= QCOW_OFLAG_COMPRESSED
|
779 ((uint64_t)nb_csectors
<< s
->csize_shift
);
781 /* update L2 table */
783 /* compressed clusters never have the copied flag */
785 BLKDBG_EVENT(bs
->file
, BLKDBG_L2_UPDATE_COMPRESSED
);
786 qcow2_cache_entry_mark_dirty(s
->l2_table_cache
, l2_slice
);
787 l2_slice
[l2_index
] = cpu_to_be64(cluster_offset
);
788 qcow2_cache_put(s
->l2_table_cache
, (void **) &l2_slice
);
790 *host_offset
= cluster_offset
& s
->cluster_offset_mask
;
794 static int perform_cow(BlockDriverState
*bs
, QCowL2Meta
*m
)
796 BDRVQcow2State
*s
= bs
->opaque
;
797 Qcow2COWRegion
*start
= &m
->cow_start
;
798 Qcow2COWRegion
*end
= &m
->cow_end
;
799 unsigned buffer_size
;
800 unsigned data_bytes
= end
->offset
- (start
->offset
+ start
->nb_bytes
);
802 uint8_t *start_buffer
, *end_buffer
;
806 assert(start
->nb_bytes
<= UINT_MAX
- end
->nb_bytes
);
807 assert(start
->nb_bytes
+ end
->nb_bytes
<= UINT_MAX
- data_bytes
);
808 assert(start
->offset
+ start
->nb_bytes
<= end
->offset
);
809 assert(!m
->data_qiov
|| m
->data_qiov
->size
== data_bytes
);
811 if (start
->nb_bytes
== 0 && end
->nb_bytes
== 0) {
815 /* If we have to read both the start and end COW regions and the
816 * middle region is not too large then perform just one read
818 merge_reads
= start
->nb_bytes
&& end
->nb_bytes
&& data_bytes
<= 16384;
820 buffer_size
= start
->nb_bytes
+ data_bytes
+ end
->nb_bytes
;
822 /* If we have to do two reads, add some padding in the middle
823 * if necessary to make sure that the end region is optimally
825 size_t align
= bdrv_opt_mem_align(bs
);
826 assert(align
> 0 && align
<= UINT_MAX
);
827 assert(QEMU_ALIGN_UP(start
->nb_bytes
, align
) <=
828 UINT_MAX
- end
->nb_bytes
);
829 buffer_size
= QEMU_ALIGN_UP(start
->nb_bytes
, align
) + end
->nb_bytes
;
832 /* Reserve a buffer large enough to store all the data that we're
834 start_buffer
= qemu_try_blockalign(bs
, buffer_size
);
835 if (start_buffer
== NULL
) {
838 /* The part of the buffer where the end region is located */
839 end_buffer
= start_buffer
+ buffer_size
- end
->nb_bytes
;
841 qemu_iovec_init(&qiov
, 2 + (m
->data_qiov
? m
->data_qiov
->niov
: 0));
843 qemu_co_mutex_unlock(&s
->lock
);
844 /* First we read the existing data from both COW regions. We
845 * either read the whole region in one go, or the start and end
846 * regions separately. */
848 qemu_iovec_add(&qiov
, start_buffer
, buffer_size
);
849 ret
= do_perform_cow_read(bs
, m
->offset
, start
->offset
, &qiov
);
851 qemu_iovec_add(&qiov
, start_buffer
, start
->nb_bytes
);
852 ret
= do_perform_cow_read(bs
, m
->offset
, start
->offset
, &qiov
);
857 qemu_iovec_reset(&qiov
);
858 qemu_iovec_add(&qiov
, end_buffer
, end
->nb_bytes
);
859 ret
= do_perform_cow_read(bs
, m
->offset
, end
->offset
, &qiov
);
865 /* Encrypt the data if necessary before writing it */
867 if (!do_perform_cow_encrypt(bs
, m
->offset
, m
->alloc_offset
,
868 start
->offset
, start_buffer
,
870 !do_perform_cow_encrypt(bs
, m
->offset
, m
->alloc_offset
,
871 end
->offset
, end_buffer
, end
->nb_bytes
)) {
877 /* And now we can write everything. If we have the guest data we
878 * can write everything in one single operation */
880 qemu_iovec_reset(&qiov
);
881 if (start
->nb_bytes
) {
882 qemu_iovec_add(&qiov
, start_buffer
, start
->nb_bytes
);
884 qemu_iovec_concat(&qiov
, m
->data_qiov
, 0, data_bytes
);
886 qemu_iovec_add(&qiov
, end_buffer
, end
->nb_bytes
);
888 /* NOTE: we have a write_aio blkdebug event here followed by
889 * a cow_write one in do_perform_cow_write(), but there's only
890 * one single I/O operation */
891 BLKDBG_EVENT(bs
->file
, BLKDBG_WRITE_AIO
);
892 ret
= do_perform_cow_write(bs
, m
->alloc_offset
, start
->offset
, &qiov
);
894 /* If there's no guest data then write both COW regions separately */
895 qemu_iovec_reset(&qiov
);
896 qemu_iovec_add(&qiov
, start_buffer
, start
->nb_bytes
);
897 ret
= do_perform_cow_write(bs
, m
->alloc_offset
, start
->offset
, &qiov
);
902 qemu_iovec_reset(&qiov
);
903 qemu_iovec_add(&qiov
, end_buffer
, end
->nb_bytes
);
904 ret
= do_perform_cow_write(bs
, m
->alloc_offset
, end
->offset
, &qiov
);
908 qemu_co_mutex_lock(&s
->lock
);
911 * Before we update the L2 table to actually point to the new cluster, we
912 * need to be sure that the refcounts have been increased and COW was
916 qcow2_cache_depends_on_flush(s
->l2_table_cache
);
919 qemu_vfree(start_buffer
);
920 qemu_iovec_destroy(&qiov
);
924 int qcow2_alloc_cluster_link_l2(BlockDriverState
*bs
, QCowL2Meta
*m
)
926 BDRVQcow2State
*s
= bs
->opaque
;
927 int i
, j
= 0, l2_index
, ret
;
928 uint64_t *old_cluster
, *l2_slice
;
929 uint64_t cluster_offset
= m
->alloc_offset
;
931 trace_qcow2_cluster_link_l2(qemu_coroutine_self(), m
->nb_clusters
);
932 assert(m
->nb_clusters
> 0);
934 old_cluster
= g_try_new(uint64_t, m
->nb_clusters
);
935 if (old_cluster
== NULL
) {
940 /* copy content of unmodified sectors */
941 ret
= perform_cow(bs
, m
);
946 /* Update L2 table. */
947 if (s
->use_lazy_refcounts
) {
948 qcow2_mark_dirty(bs
);
950 if (qcow2_need_accurate_refcounts(s
)) {
951 qcow2_cache_set_dependency(bs
, s
->l2_table_cache
,
952 s
->refcount_block_cache
);
955 ret
= get_cluster_table(bs
, m
->offset
, &l2_slice
, &l2_index
);
959 qcow2_cache_entry_mark_dirty(s
->l2_table_cache
, l2_slice
);
961 assert(l2_index
+ m
->nb_clusters
<= s
->l2_slice_size
);
962 for (i
= 0; i
< m
->nb_clusters
; i
++) {
963 /* if two concurrent writes happen to the same unallocated cluster
964 * each write allocates separate cluster and writes data concurrently.
965 * The first one to complete updates l2 table with pointer to its
966 * cluster the second one has to do RMW (which is done above by
967 * perform_cow()), update l2 table with its cluster pointer and free
968 * old cluster. This is what this loop does */
969 if (l2_slice
[l2_index
+ i
] != 0) {
970 old_cluster
[j
++] = l2_slice
[l2_index
+ i
];
973 l2_slice
[l2_index
+ i
] = cpu_to_be64((cluster_offset
+
974 (i
<< s
->cluster_bits
)) | QCOW_OFLAG_COPIED
);
978 qcow2_cache_put(s
->l2_table_cache
, (void **) &l2_slice
);
981 * If this was a COW, we need to decrease the refcount of the old cluster.
983 * Don't discard clusters that reach a refcount of 0 (e.g. compressed
984 * clusters), the next write will reuse them anyway.
986 if (!m
->keep_old_clusters
&& j
!= 0) {
987 for (i
= 0; i
< j
; i
++) {
988 qcow2_free_any_clusters(bs
, be64_to_cpu(old_cluster
[i
]), 1,
989 QCOW2_DISCARD_NEVER
);
1000 * Frees the allocated clusters because the request failed and they won't
1001 * actually be linked.
1003 void qcow2_alloc_cluster_abort(BlockDriverState
*bs
, QCowL2Meta
*m
)
1005 BDRVQcow2State
*s
= bs
->opaque
;
1006 qcow2_free_clusters(bs
, m
->alloc_offset
, m
->nb_clusters
<< s
->cluster_bits
,
1007 QCOW2_DISCARD_NEVER
);
1011 * Returns the number of contiguous clusters that can be used for an allocating
1012 * write, but require COW to be performed (this includes yet unallocated space,
1013 * which must copy from the backing file)
1015 static int count_cow_clusters(BlockDriverState
*bs
, int nb_clusters
,
1016 uint64_t *l2_slice
, int l2_index
)
1020 for (i
= 0; i
< nb_clusters
; i
++) {
1021 uint64_t l2_entry
= be64_to_cpu(l2_slice
[l2_index
+ i
]);
1022 QCow2ClusterType cluster_type
= qcow2_get_cluster_type(bs
, l2_entry
);
1024 switch(cluster_type
) {
1025 case QCOW2_CLUSTER_NORMAL
:
1026 if (l2_entry
& QCOW_OFLAG_COPIED
) {
1030 case QCOW2_CLUSTER_UNALLOCATED
:
1031 case QCOW2_CLUSTER_COMPRESSED
:
1032 case QCOW2_CLUSTER_ZERO_PLAIN
:
1033 case QCOW2_CLUSTER_ZERO_ALLOC
:
1041 assert(i
<= nb_clusters
);
1046 * Check if there already is an AIO write request in flight which allocates
1047 * the same cluster. In this case we need to wait until the previous
1048 * request has completed and updated the L2 table accordingly.
1051 * 0 if there was no dependency. *cur_bytes indicates the number of
1052 * bytes from guest_offset that can be read before the next
1053 * dependency must be processed (or the request is complete)
1055 * -EAGAIN if we had to wait for another request, previously gathered
1056 * information on cluster allocation may be invalid now. The caller
1057 * must start over anyway, so consider *cur_bytes undefined.
1059 static int handle_dependencies(BlockDriverState
*bs
, uint64_t guest_offset
,
1060 uint64_t *cur_bytes
, QCowL2Meta
**m
)
1062 BDRVQcow2State
*s
= bs
->opaque
;
1063 QCowL2Meta
*old_alloc
;
1064 uint64_t bytes
= *cur_bytes
;
1066 QLIST_FOREACH(old_alloc
, &s
->cluster_allocs
, next_in_flight
) {
1068 uint64_t start
= guest_offset
;
1069 uint64_t end
= start
+ bytes
;
1070 uint64_t old_start
= l2meta_cow_start(old_alloc
);
1071 uint64_t old_end
= l2meta_cow_end(old_alloc
);
1073 if (end
<= old_start
|| start
>= old_end
) {
1074 /* No intersection */
1076 if (start
< old_start
) {
1077 /* Stop at the start of a running allocation */
1078 bytes
= old_start
- start
;
1083 /* Stop if already an l2meta exists. After yielding, it wouldn't
1084 * be valid any more, so we'd have to clean up the old L2Metas
1085 * and deal with requests depending on them before starting to
1086 * gather new ones. Not worth the trouble. */
1087 if (bytes
== 0 && *m
) {
1093 /* Wait for the dependency to complete. We need to recheck
1094 * the free/allocated clusters when we continue. */
1095 qemu_co_queue_wait(&old_alloc
->dependent_requests
, &s
->lock
);
1101 /* Make sure that existing clusters and new allocations are only used up to
1102 * the next dependency if we shortened the request above */
1109 * Checks how many already allocated clusters that don't require a copy on
1110 * write there are at the given guest_offset (up to *bytes). If *host_offset is
1111 * not INV_OFFSET, only physically contiguous clusters beginning at this host
1112 * offset are counted.
1114 * Note that guest_offset may not be cluster aligned. In this case, the
1115 * returned *host_offset points to exact byte referenced by guest_offset and
1116 * therefore isn't cluster aligned as well.
1119 * 0: if no allocated clusters are available at the given offset.
1120 * *bytes is normally unchanged. It is set to 0 if the cluster
1121 * is allocated and doesn't need COW, but doesn't have the right
1124 * 1: if allocated clusters that don't require a COW are available at
1125 * the requested offset. *bytes may have decreased and describes
1126 * the length of the area that can be written to.
1128 * -errno: in error cases
1130 static int handle_copied(BlockDriverState
*bs
, uint64_t guest_offset
,
1131 uint64_t *host_offset
, uint64_t *bytes
, QCowL2Meta
**m
)
1133 BDRVQcow2State
*s
= bs
->opaque
;
1135 uint64_t cluster_offset
;
1137 uint64_t nb_clusters
;
1138 unsigned int keep_clusters
;
1141 trace_qcow2_handle_copied(qemu_coroutine_self(), guest_offset
, *host_offset
,
1144 assert(*host_offset
== INV_OFFSET
|| offset_into_cluster(s
, guest_offset
)
1145 == offset_into_cluster(s
, *host_offset
));
1148 * Calculate the number of clusters to look for. We stop at L2 slice
1149 * boundaries to keep things simple.
1152 size_to_clusters(s
, offset_into_cluster(s
, guest_offset
) + *bytes
);
1154 l2_index
= offset_to_l2_slice_index(s
, guest_offset
);
1155 nb_clusters
= MIN(nb_clusters
, s
->l2_slice_size
- l2_index
);
1156 assert(nb_clusters
<= INT_MAX
);
1158 /* Find L2 entry for the first involved cluster */
1159 ret
= get_cluster_table(bs
, guest_offset
, &l2_slice
, &l2_index
);
1164 cluster_offset
= be64_to_cpu(l2_slice
[l2_index
]);
1166 /* Check how many clusters are already allocated and don't need COW */
1167 if (qcow2_get_cluster_type(bs
, cluster_offset
) == QCOW2_CLUSTER_NORMAL
1168 && (cluster_offset
& QCOW_OFLAG_COPIED
))
1170 /* If a specific host_offset is required, check it */
1171 bool offset_matches
=
1172 (cluster_offset
& L2E_OFFSET_MASK
) == *host_offset
;
1174 if (offset_into_cluster(s
, cluster_offset
& L2E_OFFSET_MASK
)) {
1175 qcow2_signal_corruption(bs
, true, -1, -1, "Data cluster offset "
1176 "%#llx unaligned (guest offset: %#" PRIx64
1177 ")", cluster_offset
& L2E_OFFSET_MASK
,
1183 if (*host_offset
!= INV_OFFSET
&& !offset_matches
) {
1189 /* We keep all QCOW_OFLAG_COPIED clusters */
1191 count_contiguous_clusters(bs
, nb_clusters
, s
->cluster_size
,
1192 &l2_slice
[l2_index
],
1193 QCOW_OFLAG_COPIED
| QCOW_OFLAG_ZERO
);
1194 assert(keep_clusters
<= nb_clusters
);
1196 *bytes
= MIN(*bytes
,
1197 keep_clusters
* s
->cluster_size
1198 - offset_into_cluster(s
, guest_offset
));
1207 qcow2_cache_put(s
->l2_table_cache
, (void **) &l2_slice
);
1209 /* Only return a host offset if we actually made progress. Otherwise we
1210 * would make requirements for handle_alloc() that it can't fulfill */
1212 *host_offset
= (cluster_offset
& L2E_OFFSET_MASK
)
1213 + offset_into_cluster(s
, guest_offset
);
1220 * Allocates new clusters for the given guest_offset.
1222 * At most *nb_clusters are allocated, and on return *nb_clusters is updated to
1223 * contain the number of clusters that have been allocated and are contiguous
1224 * in the image file.
1226 * If *host_offset is not INV_OFFSET, it specifies the offset in the image file
1227 * at which the new clusters must start. *nb_clusters can be 0 on return in
1228 * this case if the cluster at host_offset is already in use. If *host_offset
1229 * is INV_OFFSET, the clusters can be allocated anywhere in the image file.
1231 * *host_offset is updated to contain the offset into the image file at which
1232 * the first allocated cluster starts.
1234 * Return 0 on success and -errno in error cases. -EAGAIN means that the
1235 * function has been waiting for another request and the allocation must be
1236 * restarted, but the whole request should not be failed.
1238 static int do_alloc_cluster_offset(BlockDriverState
*bs
, uint64_t guest_offset
,
1239 uint64_t *host_offset
, uint64_t *nb_clusters
)
1241 BDRVQcow2State
*s
= bs
->opaque
;
1243 trace_qcow2_do_alloc_clusters_offset(qemu_coroutine_self(), guest_offset
,
1244 *host_offset
, *nb_clusters
);
1246 /* Allocate new clusters */
1247 trace_qcow2_cluster_alloc_phys(qemu_coroutine_self());
1248 if (*host_offset
== INV_OFFSET
) {
1249 int64_t cluster_offset
=
1250 qcow2_alloc_clusters(bs
, *nb_clusters
* s
->cluster_size
);
1251 if (cluster_offset
< 0) {
1252 return cluster_offset
;
1254 *host_offset
= cluster_offset
;
1257 int64_t ret
= qcow2_alloc_clusters_at(bs
, *host_offset
, *nb_clusters
);
1267 * Allocates new clusters for an area that either is yet unallocated or needs a
1268 * copy on write. If *host_offset is not INV_OFFSET, clusters are only
1269 * allocated if the new allocation can match the specified host offset.
1271 * Note that guest_offset may not be cluster aligned. In this case, the
1272 * returned *host_offset points to exact byte referenced by guest_offset and
1273 * therefore isn't cluster aligned as well.
1276 * 0: if no clusters could be allocated. *bytes is set to 0,
1277 * *host_offset is left unchanged.
1279 * 1: if new clusters were allocated. *bytes may be decreased if the
1280 * new allocation doesn't cover all of the requested area.
1281 * *host_offset is updated to contain the host offset of the first
1282 * newly allocated cluster.
1284 * -errno: in error cases
1286 static int handle_alloc(BlockDriverState
*bs
, uint64_t guest_offset
,
1287 uint64_t *host_offset
, uint64_t *bytes
, QCowL2Meta
**m
)
1289 BDRVQcow2State
*s
= bs
->opaque
;
1293 uint64_t nb_clusters
;
1295 bool keep_old_clusters
= false;
1297 uint64_t alloc_cluster_offset
= INV_OFFSET
;
1299 trace_qcow2_handle_alloc(qemu_coroutine_self(), guest_offset
, *host_offset
,
1304 * Calculate the number of clusters to look for. We stop at L2 slice
1305 * boundaries to keep things simple.
1308 size_to_clusters(s
, offset_into_cluster(s
, guest_offset
) + *bytes
);
1310 l2_index
= offset_to_l2_slice_index(s
, guest_offset
);
1311 nb_clusters
= MIN(nb_clusters
, s
->l2_slice_size
- l2_index
);
1312 assert(nb_clusters
<= INT_MAX
);
1314 /* Find L2 entry for the first involved cluster */
1315 ret
= get_cluster_table(bs
, guest_offset
, &l2_slice
, &l2_index
);
1320 entry
= be64_to_cpu(l2_slice
[l2_index
]);
1322 /* For the moment, overwrite compressed clusters one by one */
1323 if (entry
& QCOW_OFLAG_COMPRESSED
) {
1326 nb_clusters
= count_cow_clusters(bs
, nb_clusters
, l2_slice
, l2_index
);
1329 /* This function is only called when there were no non-COW clusters, so if
1330 * we can't find any unallocated or COW clusters either, something is
1331 * wrong with our code. */
1332 assert(nb_clusters
> 0);
1334 if (qcow2_get_cluster_type(bs
, entry
) == QCOW2_CLUSTER_ZERO_ALLOC
&&
1335 (entry
& QCOW_OFLAG_COPIED
) &&
1336 (*host_offset
== INV_OFFSET
||
1337 start_of_cluster(s
, *host_offset
) == (entry
& L2E_OFFSET_MASK
)))
1339 int preallocated_nb_clusters
;
1341 if (offset_into_cluster(s
, entry
& L2E_OFFSET_MASK
)) {
1342 qcow2_signal_corruption(bs
, true, -1, -1, "Preallocated zero "
1343 "cluster offset %#llx unaligned (guest "
1344 "offset: %#" PRIx64
")",
1345 entry
& L2E_OFFSET_MASK
, guest_offset
);
1350 /* Try to reuse preallocated zero clusters; contiguous normal clusters
1351 * would be fine, too, but count_cow_clusters() above has limited
1352 * nb_clusters already to a range of COW clusters */
1353 preallocated_nb_clusters
=
1354 count_contiguous_clusters(bs
, nb_clusters
, s
->cluster_size
,
1355 &l2_slice
[l2_index
], QCOW_OFLAG_COPIED
);
1356 assert(preallocated_nb_clusters
> 0);
1358 nb_clusters
= preallocated_nb_clusters
;
1359 alloc_cluster_offset
= entry
& L2E_OFFSET_MASK
;
1361 /* We want to reuse these clusters, so qcow2_alloc_cluster_link_l2()
1362 * should not free them. */
1363 keep_old_clusters
= true;
1366 qcow2_cache_put(s
->l2_table_cache
, (void **) &l2_slice
);
1368 if (alloc_cluster_offset
== INV_OFFSET
) {
1369 /* Allocate, if necessary at a given offset in the image file */
1370 alloc_cluster_offset
= *host_offset
== INV_OFFSET
? INV_OFFSET
:
1371 start_of_cluster(s
, *host_offset
);
1372 ret
= do_alloc_cluster_offset(bs
, guest_offset
, &alloc_cluster_offset
,
1378 /* Can't extend contiguous allocation */
1379 if (nb_clusters
== 0) {
1384 assert(alloc_cluster_offset
!= INV_OFFSET
);
1388 * Save info needed for meta data update.
1390 * requested_bytes: Number of bytes from the start of the first
1391 * newly allocated cluster to the end of the (possibly shortened
1392 * before) write request.
1394 * avail_bytes: Number of bytes from the start of the first
1395 * newly allocated to the end of the last newly allocated cluster.
1397 * nb_bytes: The number of bytes from the start of the first
1398 * newly allocated cluster to the end of the area that the write
1399 * request actually writes to (excluding COW at the end)
1401 uint64_t requested_bytes
= *bytes
+ offset_into_cluster(s
, guest_offset
);
1402 int avail_bytes
= MIN(INT_MAX
, nb_clusters
<< s
->cluster_bits
);
1403 int nb_bytes
= MIN(requested_bytes
, avail_bytes
);
1404 QCowL2Meta
*old_m
= *m
;
1406 *m
= g_malloc0(sizeof(**m
));
1408 **m
= (QCowL2Meta
) {
1411 .alloc_offset
= alloc_cluster_offset
,
1412 .offset
= start_of_cluster(s
, guest_offset
),
1413 .nb_clusters
= nb_clusters
,
1415 .keep_old_clusters
= keep_old_clusters
,
1419 .nb_bytes
= offset_into_cluster(s
, guest_offset
),
1423 .nb_bytes
= avail_bytes
- nb_bytes
,
1426 qemu_co_queue_init(&(*m
)->dependent_requests
);
1427 QLIST_INSERT_HEAD(&s
->cluster_allocs
, *m
, next_in_flight
);
1429 *host_offset
= alloc_cluster_offset
+ offset_into_cluster(s
, guest_offset
);
1430 *bytes
= MIN(*bytes
, nb_bytes
- offset_into_cluster(s
, guest_offset
));
1431 assert(*bytes
!= 0);
1436 if (*m
&& (*m
)->nb_clusters
> 0) {
1437 QLIST_REMOVE(*m
, next_in_flight
);
1443 * alloc_cluster_offset
1445 * For a given offset on the virtual disk, find the cluster offset in qcow2
1446 * file. If the offset is not found, allocate a new cluster.
1448 * If the cluster was already allocated, m->nb_clusters is set to 0 and
1449 * other fields in m are meaningless.
1451 * If the cluster is newly allocated, m->nb_clusters is set to the number of
1452 * contiguous clusters that have been allocated. In this case, the other
1453 * fields of m are valid and contain information about the first allocated
1456 * If the request conflicts with another write request in flight, the coroutine
1457 * is queued and will be reentered when the dependency has completed.
1459 * Return 0 on success and -errno in error cases
1461 int qcow2_alloc_cluster_offset(BlockDriverState
*bs
, uint64_t offset
,
1462 unsigned int *bytes
, uint64_t *host_offset
,
1465 BDRVQcow2State
*s
= bs
->opaque
;
1466 uint64_t start
, remaining
;
1467 uint64_t cluster_offset
;
1471 trace_qcow2_alloc_clusters_offset(qemu_coroutine_self(), offset
, *bytes
);
1476 cluster_offset
= INV_OFFSET
;
1477 *host_offset
= INV_OFFSET
;
1483 if (*host_offset
== INV_OFFSET
&& cluster_offset
!= INV_OFFSET
) {
1484 *host_offset
= start_of_cluster(s
, cluster_offset
);
1487 assert(remaining
>= cur_bytes
);
1490 remaining
-= cur_bytes
;
1492 if (cluster_offset
!= INV_OFFSET
) {
1493 cluster_offset
+= cur_bytes
;
1496 if (remaining
== 0) {
1500 cur_bytes
= remaining
;
1503 * Now start gathering as many contiguous clusters as possible:
1505 * 1. Check for overlaps with in-flight allocations
1507 * a) Overlap not in the first cluster -> shorten this request and
1508 * let the caller handle the rest in its next loop iteration.
1510 * b) Real overlaps of two requests. Yield and restart the search
1511 * for contiguous clusters (the situation could have changed
1512 * while we were sleeping)
1514 * c) TODO: Request starts in the same cluster as the in-flight
1515 * allocation ends. Shorten the COW of the in-fight allocation,
1516 * set cluster_offset to write to the same cluster and set up
1517 * the right synchronisation between the in-flight request and
1520 ret
= handle_dependencies(bs
, start
, &cur_bytes
, m
);
1521 if (ret
== -EAGAIN
) {
1522 /* Currently handle_dependencies() doesn't yield if we already had
1523 * an allocation. If it did, we would have to clean up the L2Meta
1524 * structs before starting over. */
1527 } else if (ret
< 0) {
1529 } else if (cur_bytes
== 0) {
1532 /* handle_dependencies() may have decreased cur_bytes (shortened
1533 * the allocations below) so that the next dependency is processed
1534 * correctly during the next loop iteration. */
1538 * 2. Count contiguous COPIED clusters.
1540 ret
= handle_copied(bs
, start
, &cluster_offset
, &cur_bytes
, m
);
1545 } else if (cur_bytes
== 0) {
1550 * 3. If the request still hasn't completed, allocate new clusters,
1551 * considering any cluster_offset of steps 1c or 2.
1553 ret
= handle_alloc(bs
, start
, &cluster_offset
, &cur_bytes
, m
);
1559 assert(cur_bytes
== 0);
1564 *bytes
-= remaining
;
1566 assert(*host_offset
!= INV_OFFSET
);
1572 * This discards as many clusters of nb_clusters as possible at once (i.e.
1573 * all clusters in the same L2 slice) and returns the number of discarded
1576 static int discard_in_l2_slice(BlockDriverState
*bs
, uint64_t offset
,
1577 uint64_t nb_clusters
,
1578 enum qcow2_discard_type type
, bool full_discard
)
1580 BDRVQcow2State
*s
= bs
->opaque
;
1586 ret
= get_cluster_table(bs
, offset
, &l2_slice
, &l2_index
);
1591 /* Limit nb_clusters to one L2 slice */
1592 nb_clusters
= MIN(nb_clusters
, s
->l2_slice_size
- l2_index
);
1593 assert(nb_clusters
<= INT_MAX
);
1595 for (i
= 0; i
< nb_clusters
; i
++) {
1596 uint64_t old_l2_entry
;
1598 old_l2_entry
= be64_to_cpu(l2_slice
[l2_index
+ i
]);
1601 * If full_discard is false, make sure that a discarded area reads back
1602 * as zeroes for v3 images (we cannot do it for v2 without actually
1603 * writing a zero-filled buffer). We can skip the operation if the
1604 * cluster is already marked as zero, or if it's unallocated and we
1605 * don't have a backing file.
1607 * TODO We might want to use bdrv_block_status(bs) here, but we're
1608 * holding s->lock, so that doesn't work today.
1610 * If full_discard is true, the sector should not read back as zeroes,
1611 * but rather fall through to the backing file.
1613 switch (qcow2_get_cluster_type(bs
, old_l2_entry
)) {
1614 case QCOW2_CLUSTER_UNALLOCATED
:
1615 if (full_discard
|| !bs
->backing
) {
1620 case QCOW2_CLUSTER_ZERO_PLAIN
:
1621 if (!full_discard
) {
1626 case QCOW2_CLUSTER_ZERO_ALLOC
:
1627 case QCOW2_CLUSTER_NORMAL
:
1628 case QCOW2_CLUSTER_COMPRESSED
:
1635 /* First remove L2 entries */
1636 qcow2_cache_entry_mark_dirty(s
->l2_table_cache
, l2_slice
);
1637 if (!full_discard
&& s
->qcow_version
>= 3) {
1638 l2_slice
[l2_index
+ i
] = cpu_to_be64(QCOW_OFLAG_ZERO
);
1640 l2_slice
[l2_index
+ i
] = cpu_to_be64(0);
1643 /* Then decrease the refcount */
1644 qcow2_free_any_clusters(bs
, old_l2_entry
, 1, type
);
1647 qcow2_cache_put(s
->l2_table_cache
, (void **) &l2_slice
);
1652 int qcow2_cluster_discard(BlockDriverState
*bs
, uint64_t offset
,
1653 uint64_t bytes
, enum qcow2_discard_type type
,
1656 BDRVQcow2State
*s
= bs
->opaque
;
1657 uint64_t end_offset
= offset
+ bytes
;
1658 uint64_t nb_clusters
;
1662 /* Caller must pass aligned values, except at image end */
1663 assert(QEMU_IS_ALIGNED(offset
, s
->cluster_size
));
1664 assert(QEMU_IS_ALIGNED(end_offset
, s
->cluster_size
) ||
1665 end_offset
== bs
->total_sectors
<< BDRV_SECTOR_BITS
);
1667 nb_clusters
= size_to_clusters(s
, bytes
);
1669 s
->cache_discards
= true;
1671 /* Each L2 slice is handled by its own loop iteration */
1672 while (nb_clusters
> 0) {
1673 cleared
= discard_in_l2_slice(bs
, offset
, nb_clusters
, type
,
1680 nb_clusters
-= cleared
;
1681 offset
+= (cleared
* s
->cluster_size
);
1686 s
->cache_discards
= false;
1687 qcow2_process_discards(bs
, ret
);
1693 * This zeroes as many clusters of nb_clusters as possible at once (i.e.
1694 * all clusters in the same L2 slice) and returns the number of zeroed
1697 static int zero_in_l2_slice(BlockDriverState
*bs
, uint64_t offset
,
1698 uint64_t nb_clusters
, int flags
)
1700 BDRVQcow2State
*s
= bs
->opaque
;
1705 bool unmap
= !!(flags
& BDRV_REQ_MAY_UNMAP
);
1707 ret
= get_cluster_table(bs
, offset
, &l2_slice
, &l2_index
);
1712 /* Limit nb_clusters to one L2 slice */
1713 nb_clusters
= MIN(nb_clusters
, s
->l2_slice_size
- l2_index
);
1714 assert(nb_clusters
<= INT_MAX
);
1716 for (i
= 0; i
< nb_clusters
; i
++) {
1717 uint64_t old_offset
;
1718 QCow2ClusterType cluster_type
;
1720 old_offset
= be64_to_cpu(l2_slice
[l2_index
+ i
]);
1723 * Minimize L2 changes if the cluster already reads back as
1724 * zeroes with correct allocation.
1726 cluster_type
= qcow2_get_cluster_type(bs
, old_offset
);
1727 if (cluster_type
== QCOW2_CLUSTER_ZERO_PLAIN
||
1728 (cluster_type
== QCOW2_CLUSTER_ZERO_ALLOC
&& !unmap
)) {
1732 qcow2_cache_entry_mark_dirty(s
->l2_table_cache
, l2_slice
);
1733 if (cluster_type
== QCOW2_CLUSTER_COMPRESSED
|| unmap
) {
1734 l2_slice
[l2_index
+ i
] = cpu_to_be64(QCOW_OFLAG_ZERO
);
1735 qcow2_free_any_clusters(bs
, old_offset
, 1, QCOW2_DISCARD_REQUEST
);
1737 l2_slice
[l2_index
+ i
] |= cpu_to_be64(QCOW_OFLAG_ZERO
);
1741 qcow2_cache_put(s
->l2_table_cache
, (void **) &l2_slice
);
1746 int qcow2_cluster_zeroize(BlockDriverState
*bs
, uint64_t offset
,
1747 uint64_t bytes
, int flags
)
1749 BDRVQcow2State
*s
= bs
->opaque
;
1750 uint64_t end_offset
= offset
+ bytes
;
1751 uint64_t nb_clusters
;
1755 /* Caller must pass aligned values, except at image end */
1756 assert(QEMU_IS_ALIGNED(offset
, s
->cluster_size
));
1757 assert(QEMU_IS_ALIGNED(end_offset
, s
->cluster_size
) ||
1758 end_offset
== bs
->total_sectors
<< BDRV_SECTOR_BITS
);
1760 /* The zero flag is only supported by version 3 and newer */
1761 if (s
->qcow_version
< 3) {
1765 /* Each L2 slice is handled by its own loop iteration */
1766 nb_clusters
= size_to_clusters(s
, bytes
);
1768 s
->cache_discards
= true;
1770 while (nb_clusters
> 0) {
1771 cleared
= zero_in_l2_slice(bs
, offset
, nb_clusters
, flags
);
1777 nb_clusters
-= cleared
;
1778 offset
+= (cleared
* s
->cluster_size
);
1783 s
->cache_discards
= false;
1784 qcow2_process_discards(bs
, ret
);
1790 * Expands all zero clusters in a specific L1 table (or deallocates them, for
1791 * non-backed non-pre-allocated zero clusters).
1793 * l1_entries and *visited_l1_entries are used to keep track of progress for
1794 * status_cb(). l1_entries contains the total number of L1 entries and
1795 * *visited_l1_entries counts all visited L1 entries.
1797 static int expand_zero_clusters_in_l1(BlockDriverState
*bs
, uint64_t *l1_table
,
1798 int l1_size
, int64_t *visited_l1_entries
,
1800 BlockDriverAmendStatusCB
*status_cb
,
1803 BDRVQcow2State
*s
= bs
->opaque
;
1804 bool is_active_l1
= (l1_table
== s
->l1_table
);
1805 uint64_t *l2_slice
= NULL
;
1806 unsigned slice
, slice_size2
, n_slices
;
1810 slice_size2
= s
->l2_slice_size
* sizeof(uint64_t);
1811 n_slices
= s
->cluster_size
/ slice_size2
;
1813 if (!is_active_l1
) {
1814 /* inactive L2 tables require a buffer to be stored in when loading
1816 l2_slice
= qemu_try_blockalign(bs
->file
->bs
, slice_size2
);
1817 if (l2_slice
== NULL
) {
1822 for (i
= 0; i
< l1_size
; i
++) {
1823 uint64_t l2_offset
= l1_table
[i
] & L1E_OFFSET_MASK
;
1824 uint64_t l2_refcount
;
1828 (*visited_l1_entries
)++;
1830 status_cb(bs
, *visited_l1_entries
, l1_entries
, cb_opaque
);
1835 if (offset_into_cluster(s
, l2_offset
)) {
1836 qcow2_signal_corruption(bs
, true, -1, -1, "L2 table offset %#"
1837 PRIx64
" unaligned (L1 index: %#x)",
1843 ret
= qcow2_get_refcount(bs
, l2_offset
>> s
->cluster_bits
,
1849 for (slice
= 0; slice
< n_slices
; slice
++) {
1850 uint64_t slice_offset
= l2_offset
+ slice
* slice_size2
;
1851 bool l2_dirty
= false;
1853 /* get active L2 tables from cache */
1854 ret
= qcow2_cache_get(bs
, s
->l2_table_cache
, slice_offset
,
1855 (void **)&l2_slice
);
1857 /* load inactive L2 tables from disk */
1858 ret
= bdrv_pread(bs
->file
, slice_offset
, l2_slice
, slice_size2
);
1864 for (j
= 0; j
< s
->l2_slice_size
; j
++) {
1865 uint64_t l2_entry
= be64_to_cpu(l2_slice
[j
]);
1866 int64_t offset
= l2_entry
& L2E_OFFSET_MASK
;
1867 QCow2ClusterType cluster_type
=
1868 qcow2_get_cluster_type(bs
, l2_entry
);
1870 if (cluster_type
!= QCOW2_CLUSTER_ZERO_PLAIN
&&
1871 cluster_type
!= QCOW2_CLUSTER_ZERO_ALLOC
) {
1875 if (cluster_type
== QCOW2_CLUSTER_ZERO_PLAIN
) {
1877 /* not backed; therefore we can simply deallocate the
1884 offset
= qcow2_alloc_clusters(bs
, s
->cluster_size
);
1890 if (l2_refcount
> 1) {
1891 /* For shared L2 tables, set the refcount accordingly
1892 * (it is already 1 and needs to be l2_refcount) */
1893 ret
= qcow2_update_cluster_refcount(
1894 bs
, offset
>> s
->cluster_bits
,
1895 refcount_diff(1, l2_refcount
), false,
1896 QCOW2_DISCARD_OTHER
);
1898 qcow2_free_clusters(bs
, offset
, s
->cluster_size
,
1899 QCOW2_DISCARD_OTHER
);
1905 if (offset_into_cluster(s
, offset
)) {
1906 int l2_index
= slice
* s
->l2_slice_size
+ j
;
1907 qcow2_signal_corruption(
1909 "Cluster allocation offset "
1910 "%#" PRIx64
" unaligned (L2 offset: %#"
1911 PRIx64
", L2 index: %#x)", offset
,
1912 l2_offset
, l2_index
);
1913 if (cluster_type
== QCOW2_CLUSTER_ZERO_PLAIN
) {
1914 qcow2_free_clusters(bs
, offset
, s
->cluster_size
,
1915 QCOW2_DISCARD_ALWAYS
);
1921 ret
= qcow2_pre_write_overlap_check(bs
, 0, offset
,
1924 if (cluster_type
== QCOW2_CLUSTER_ZERO_PLAIN
) {
1925 qcow2_free_clusters(bs
, offset
, s
->cluster_size
,
1926 QCOW2_DISCARD_ALWAYS
);
1931 ret
= bdrv_pwrite_zeroes(bs
->file
, offset
, s
->cluster_size
, 0);
1933 if (cluster_type
== QCOW2_CLUSTER_ZERO_PLAIN
) {
1934 qcow2_free_clusters(bs
, offset
, s
->cluster_size
,
1935 QCOW2_DISCARD_ALWAYS
);
1940 if (l2_refcount
== 1) {
1941 l2_slice
[j
] = cpu_to_be64(offset
| QCOW_OFLAG_COPIED
);
1943 l2_slice
[j
] = cpu_to_be64(offset
);
1950 qcow2_cache_entry_mark_dirty(s
->l2_table_cache
, l2_slice
);
1951 qcow2_cache_depends_on_flush(s
->l2_table_cache
);
1953 qcow2_cache_put(s
->l2_table_cache
, (void **) &l2_slice
);
1956 ret
= qcow2_pre_write_overlap_check(
1957 bs
, QCOW2_OL_INACTIVE_L2
| QCOW2_OL_ACTIVE_L2
,
1958 slice_offset
, slice_size2
);
1963 ret
= bdrv_pwrite(bs
->file
, slice_offset
,
1964 l2_slice
, slice_size2
);
1972 (*visited_l1_entries
)++;
1974 status_cb(bs
, *visited_l1_entries
, l1_entries
, cb_opaque
);
1982 if (!is_active_l1
) {
1983 qemu_vfree(l2_slice
);
1985 qcow2_cache_put(s
->l2_table_cache
, (void **) &l2_slice
);
1992 * For backed images, expands all zero clusters on the image. For non-backed
1993 * images, deallocates all non-pre-allocated zero clusters (and claims the
1994 * allocation for pre-allocated ones). This is important for downgrading to a
1995 * qcow2 version which doesn't yet support metadata zero clusters.
1997 int qcow2_expand_zero_clusters(BlockDriverState
*bs
,
1998 BlockDriverAmendStatusCB
*status_cb
,
2001 BDRVQcow2State
*s
= bs
->opaque
;
2002 uint64_t *l1_table
= NULL
;
2003 int64_t l1_entries
= 0, visited_l1_entries
= 0;
2008 l1_entries
= s
->l1_size
;
2009 for (i
= 0; i
< s
->nb_snapshots
; i
++) {
2010 l1_entries
+= s
->snapshots
[i
].l1_size
;
2014 ret
= expand_zero_clusters_in_l1(bs
, s
->l1_table
, s
->l1_size
,
2015 &visited_l1_entries
, l1_entries
,
2016 status_cb
, cb_opaque
);
2021 /* Inactive L1 tables may point to active L2 tables - therefore it is
2022 * necessary to flush the L2 table cache before trying to access the L2
2023 * tables pointed to by inactive L1 entries (else we might try to expand
2024 * zero clusters that have already been expanded); furthermore, it is also
2025 * necessary to empty the L2 table cache, since it may contain tables which
2026 * are now going to be modified directly on disk, bypassing the cache.
2027 * qcow2_cache_empty() does both for us. */
2028 ret
= qcow2_cache_empty(bs
, s
->l2_table_cache
);
2033 for (i
= 0; i
< s
->nb_snapshots
; i
++) {
2035 uint64_t *new_l1_table
;
2036 Error
*local_err
= NULL
;
2038 ret
= qcow2_validate_table(bs
, s
->snapshots
[i
].l1_table_offset
,
2039 s
->snapshots
[i
].l1_size
, sizeof(uint64_t),
2040 QCOW_MAX_L1_SIZE
, "Snapshot L1 table",
2043 error_report_err(local_err
);
2047 l1_size2
= s
->snapshots
[i
].l1_size
* sizeof(uint64_t);
2048 new_l1_table
= g_try_realloc(l1_table
, l1_size2
);
2050 if (!new_l1_table
) {
2055 l1_table
= new_l1_table
;
2057 ret
= bdrv_pread(bs
->file
, s
->snapshots
[i
].l1_table_offset
,
2058 l1_table
, l1_size2
);
2063 for (j
= 0; j
< s
->snapshots
[i
].l1_size
; j
++) {
2064 be64_to_cpus(&l1_table
[j
]);
2067 ret
= expand_zero_clusters_in_l1(bs
, l1_table
, s
->snapshots
[i
].l1_size
,
2068 &visited_l1_entries
, l1_entries
,
2069 status_cb
, cb_opaque
);