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(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 cluster index in the l2 table is given to the caller.
652 * Returns 0 on success, -errno in failure case
654 static int get_cluster_table(BlockDriverState
*bs
, uint64_t offset
,
655 uint64_t **new_l2_table
,
658 BDRVQcow2State
*s
= bs
->opaque
;
659 unsigned int l2_index
;
660 uint64_t l1_index
, l2_offset
;
661 uint64_t *l2_table
= NULL
;
664 /* seek to the l2 offset in the l1 table */
666 l1_index
= offset
>> (s
->l2_bits
+ s
->cluster_bits
);
667 if (l1_index
>= s
->l1_size
) {
668 ret
= qcow2_grow_l1_table(bs
, l1_index
+ 1, false);
674 assert(l1_index
< s
->l1_size
);
675 l2_offset
= s
->l1_table
[l1_index
] & L1E_OFFSET_MASK
;
676 if (offset_into_cluster(s
, l2_offset
)) {
677 qcow2_signal_corruption(bs
, true, -1, -1, "L2 table offset %#" PRIx64
678 " unaligned (L1 index: %#" PRIx64
")",
679 l2_offset
, l1_index
);
683 /* seek the l2 table of the given l2 offset */
685 if (s
->l1_table
[l1_index
] & QCOW_OFLAG_COPIED
) {
686 /* load the l2 table in memory */
687 ret
= l2_load(bs
, l2_offset
, &l2_table
);
692 /* First allocate a new L2 table (and do COW if needed) */
693 ret
= l2_allocate(bs
, l1_index
, &l2_table
);
698 /* Then decrease the refcount of the old table */
700 qcow2_free_clusters(bs
, l2_offset
, s
->l2_size
* sizeof(uint64_t),
701 QCOW2_DISCARD_OTHER
);
705 /* find the cluster offset for the given disk offset */
707 l2_index
= offset_to_l2_index(s
, offset
);
709 *new_l2_table
= l2_table
;
710 *new_l2_index
= l2_index
;
716 * alloc_compressed_cluster_offset
718 * For a given offset of the disk image, return cluster offset in
721 * If the offset is not found, allocate a new compressed cluster.
723 * Return the cluster offset if successful,
724 * Return 0, otherwise.
728 uint64_t qcow2_alloc_compressed_cluster_offset(BlockDriverState
*bs
,
732 BDRVQcow2State
*s
= bs
->opaque
;
735 int64_t cluster_offset
;
738 ret
= get_cluster_table(bs
, offset
, &l2_table
, &l2_index
);
743 /* Compression can't overwrite anything. Fail if the cluster was already
745 cluster_offset
= be64_to_cpu(l2_table
[l2_index
]);
746 if (cluster_offset
& L2E_OFFSET_MASK
) {
747 qcow2_cache_put(bs
, s
->l2_table_cache
, (void**) &l2_table
);
751 cluster_offset
= qcow2_alloc_bytes(bs
, compressed_size
);
752 if (cluster_offset
< 0) {
753 qcow2_cache_put(bs
, s
->l2_table_cache
, (void**) &l2_table
);
757 nb_csectors
= ((cluster_offset
+ compressed_size
- 1) >> 9) -
758 (cluster_offset
>> 9);
760 cluster_offset
|= QCOW_OFLAG_COMPRESSED
|
761 ((uint64_t)nb_csectors
<< s
->csize_shift
);
763 /* update L2 table */
765 /* compressed clusters never have the copied flag */
767 BLKDBG_EVENT(bs
->file
, BLKDBG_L2_UPDATE_COMPRESSED
);
768 qcow2_cache_entry_mark_dirty(s
->l2_table_cache
, l2_table
);
769 l2_table
[l2_index
] = cpu_to_be64(cluster_offset
);
770 qcow2_cache_put(bs
, s
->l2_table_cache
, (void **) &l2_table
);
772 return cluster_offset
;
775 static int perform_cow(BlockDriverState
*bs
, QCowL2Meta
*m
)
777 BDRVQcow2State
*s
= bs
->opaque
;
778 Qcow2COWRegion
*start
= &m
->cow_start
;
779 Qcow2COWRegion
*end
= &m
->cow_end
;
780 unsigned buffer_size
;
781 unsigned data_bytes
= end
->offset
- (start
->offset
+ start
->nb_bytes
);
783 uint8_t *start_buffer
, *end_buffer
;
787 assert(start
->nb_bytes
<= UINT_MAX
- end
->nb_bytes
);
788 assert(start
->nb_bytes
+ end
->nb_bytes
<= UINT_MAX
- data_bytes
);
789 assert(start
->offset
+ start
->nb_bytes
<= end
->offset
);
790 assert(!m
->data_qiov
|| m
->data_qiov
->size
== data_bytes
);
792 if (start
->nb_bytes
== 0 && end
->nb_bytes
== 0) {
796 /* If we have to read both the start and end COW regions and the
797 * middle region is not too large then perform just one read
799 merge_reads
= start
->nb_bytes
&& end
->nb_bytes
&& data_bytes
<= 16384;
801 buffer_size
= start
->nb_bytes
+ data_bytes
+ end
->nb_bytes
;
803 /* If we have to do two reads, add some padding in the middle
804 * if necessary to make sure that the end region is optimally
806 size_t align
= bdrv_opt_mem_align(bs
);
807 assert(align
> 0 && align
<= UINT_MAX
);
808 assert(QEMU_ALIGN_UP(start
->nb_bytes
, align
) <=
809 UINT_MAX
- end
->nb_bytes
);
810 buffer_size
= QEMU_ALIGN_UP(start
->nb_bytes
, align
) + end
->nb_bytes
;
813 /* Reserve a buffer large enough to store all the data that we're
815 start_buffer
= qemu_try_blockalign(bs
, buffer_size
);
816 if (start_buffer
== NULL
) {
819 /* The part of the buffer where the end region is located */
820 end_buffer
= start_buffer
+ buffer_size
- end
->nb_bytes
;
822 qemu_iovec_init(&qiov
, 2 + (m
->data_qiov
? m
->data_qiov
->niov
: 0));
824 qemu_co_mutex_unlock(&s
->lock
);
825 /* First we read the existing data from both COW regions. We
826 * either read the whole region in one go, or the start and end
827 * regions separately. */
829 qemu_iovec_add(&qiov
, start_buffer
, buffer_size
);
830 ret
= do_perform_cow_read(bs
, m
->offset
, start
->offset
, &qiov
);
832 qemu_iovec_add(&qiov
, start_buffer
, start
->nb_bytes
);
833 ret
= do_perform_cow_read(bs
, m
->offset
, start
->offset
, &qiov
);
838 qemu_iovec_reset(&qiov
);
839 qemu_iovec_add(&qiov
, end_buffer
, end
->nb_bytes
);
840 ret
= do_perform_cow_read(bs
, m
->offset
, end
->offset
, &qiov
);
846 /* Encrypt the data if necessary before writing it */
848 if (!do_perform_cow_encrypt(bs
, m
->offset
, m
->alloc_offset
,
849 start
->offset
, start_buffer
,
851 !do_perform_cow_encrypt(bs
, m
->offset
, m
->alloc_offset
,
852 end
->offset
, end_buffer
, end
->nb_bytes
)) {
858 /* And now we can write everything. If we have the guest data we
859 * can write everything in one single operation */
861 qemu_iovec_reset(&qiov
);
862 if (start
->nb_bytes
) {
863 qemu_iovec_add(&qiov
, start_buffer
, start
->nb_bytes
);
865 qemu_iovec_concat(&qiov
, m
->data_qiov
, 0, data_bytes
);
867 qemu_iovec_add(&qiov
, end_buffer
, end
->nb_bytes
);
869 /* NOTE: we have a write_aio blkdebug event here followed by
870 * a cow_write one in do_perform_cow_write(), but there's only
871 * one single I/O operation */
872 BLKDBG_EVENT(bs
->file
, BLKDBG_WRITE_AIO
);
873 ret
= do_perform_cow_write(bs
, m
->alloc_offset
, start
->offset
, &qiov
);
875 /* If there's no guest data then write both COW regions separately */
876 qemu_iovec_reset(&qiov
);
877 qemu_iovec_add(&qiov
, start_buffer
, start
->nb_bytes
);
878 ret
= do_perform_cow_write(bs
, m
->alloc_offset
, start
->offset
, &qiov
);
883 qemu_iovec_reset(&qiov
);
884 qemu_iovec_add(&qiov
, end_buffer
, end
->nb_bytes
);
885 ret
= do_perform_cow_write(bs
, m
->alloc_offset
, end
->offset
, &qiov
);
889 qemu_co_mutex_lock(&s
->lock
);
892 * Before we update the L2 table to actually point to the new cluster, we
893 * need to be sure that the refcounts have been increased and COW was
897 qcow2_cache_depends_on_flush(s
->l2_table_cache
);
900 qemu_vfree(start_buffer
);
901 qemu_iovec_destroy(&qiov
);
905 int qcow2_alloc_cluster_link_l2(BlockDriverState
*bs
, QCowL2Meta
*m
)
907 BDRVQcow2State
*s
= bs
->opaque
;
908 int i
, j
= 0, l2_index
, ret
;
909 uint64_t *old_cluster
, *l2_table
;
910 uint64_t cluster_offset
= m
->alloc_offset
;
912 trace_qcow2_cluster_link_l2(qemu_coroutine_self(), m
->nb_clusters
);
913 assert(m
->nb_clusters
> 0);
915 old_cluster
= g_try_new(uint64_t, m
->nb_clusters
);
916 if (old_cluster
== NULL
) {
921 /* copy content of unmodified sectors */
922 ret
= perform_cow(bs
, m
);
927 /* Update L2 table. */
928 if (s
->use_lazy_refcounts
) {
929 qcow2_mark_dirty(bs
);
931 if (qcow2_need_accurate_refcounts(s
)) {
932 qcow2_cache_set_dependency(bs
, s
->l2_table_cache
,
933 s
->refcount_block_cache
);
936 ret
= get_cluster_table(bs
, m
->offset
, &l2_table
, &l2_index
);
940 qcow2_cache_entry_mark_dirty(s
->l2_table_cache
, l2_table
);
942 assert(l2_index
+ m
->nb_clusters
<= s
->l2_size
);
943 for (i
= 0; i
< m
->nb_clusters
; i
++) {
944 /* if two concurrent writes happen to the same unallocated cluster
945 * each write allocates separate cluster and writes data concurrently.
946 * The first one to complete updates l2 table with pointer to its
947 * cluster the second one has to do RMW (which is done above by
948 * perform_cow()), update l2 table with its cluster pointer and free
949 * old cluster. This is what this loop does */
950 if (l2_table
[l2_index
+ i
] != 0) {
951 old_cluster
[j
++] = l2_table
[l2_index
+ i
];
954 l2_table
[l2_index
+ i
] = cpu_to_be64((cluster_offset
+
955 (i
<< s
->cluster_bits
)) | QCOW_OFLAG_COPIED
);
959 qcow2_cache_put(bs
, s
->l2_table_cache
, (void **) &l2_table
);
962 * If this was a COW, we need to decrease the refcount of the old cluster.
964 * Don't discard clusters that reach a refcount of 0 (e.g. compressed
965 * clusters), the next write will reuse them anyway.
967 if (!m
->keep_old_clusters
&& j
!= 0) {
968 for (i
= 0; i
< j
; i
++) {
969 qcow2_free_any_clusters(bs
, be64_to_cpu(old_cluster
[i
]), 1,
970 QCOW2_DISCARD_NEVER
);
981 * Returns the number of contiguous clusters that can be used for an allocating
982 * write, but require COW to be performed (this includes yet unallocated space,
983 * which must copy from the backing file)
985 static int count_cow_clusters(BDRVQcow2State
*s
, int nb_clusters
,
986 uint64_t *l2_table
, int l2_index
)
990 for (i
= 0; i
< nb_clusters
; i
++) {
991 uint64_t l2_entry
= be64_to_cpu(l2_table
[l2_index
+ i
]);
992 QCow2ClusterType cluster_type
= qcow2_get_cluster_type(l2_entry
);
994 switch(cluster_type
) {
995 case QCOW2_CLUSTER_NORMAL
:
996 if (l2_entry
& QCOW_OFLAG_COPIED
) {
1000 case QCOW2_CLUSTER_UNALLOCATED
:
1001 case QCOW2_CLUSTER_COMPRESSED
:
1002 case QCOW2_CLUSTER_ZERO_PLAIN
:
1003 case QCOW2_CLUSTER_ZERO_ALLOC
:
1011 assert(i
<= nb_clusters
);
1016 * Check if there already is an AIO write request in flight which allocates
1017 * the same cluster. In this case we need to wait until the previous
1018 * request has completed and updated the L2 table accordingly.
1021 * 0 if there was no dependency. *cur_bytes indicates the number of
1022 * bytes from guest_offset that can be read before the next
1023 * dependency must be processed (or the request is complete)
1025 * -EAGAIN if we had to wait for another request, previously gathered
1026 * information on cluster allocation may be invalid now. The caller
1027 * must start over anyway, so consider *cur_bytes undefined.
1029 static int handle_dependencies(BlockDriverState
*bs
, uint64_t guest_offset
,
1030 uint64_t *cur_bytes
, QCowL2Meta
**m
)
1032 BDRVQcow2State
*s
= bs
->opaque
;
1033 QCowL2Meta
*old_alloc
;
1034 uint64_t bytes
= *cur_bytes
;
1036 QLIST_FOREACH(old_alloc
, &s
->cluster_allocs
, next_in_flight
) {
1038 uint64_t start
= guest_offset
;
1039 uint64_t end
= start
+ bytes
;
1040 uint64_t old_start
= l2meta_cow_start(old_alloc
);
1041 uint64_t old_end
= l2meta_cow_end(old_alloc
);
1043 if (end
<= old_start
|| start
>= old_end
) {
1044 /* No intersection */
1046 if (start
< old_start
) {
1047 /* Stop at the start of a running allocation */
1048 bytes
= old_start
- start
;
1053 /* Stop if already an l2meta exists. After yielding, it wouldn't
1054 * be valid any more, so we'd have to clean up the old L2Metas
1055 * and deal with requests depending on them before starting to
1056 * gather new ones. Not worth the trouble. */
1057 if (bytes
== 0 && *m
) {
1063 /* Wait for the dependency to complete. We need to recheck
1064 * the free/allocated clusters when we continue. */
1065 qemu_co_queue_wait(&old_alloc
->dependent_requests
, &s
->lock
);
1071 /* Make sure that existing clusters and new allocations are only used up to
1072 * the next dependency if we shortened the request above */
1079 * Checks how many already allocated clusters that don't require a copy on
1080 * write there are at the given guest_offset (up to *bytes). If
1081 * *host_offset is not zero, only physically contiguous clusters beginning at
1082 * this host offset are counted.
1084 * Note that guest_offset may not be cluster aligned. In this case, the
1085 * returned *host_offset points to exact byte referenced by guest_offset and
1086 * therefore isn't cluster aligned as well.
1089 * 0: if no allocated clusters are available at the given offset.
1090 * *bytes is normally unchanged. It is set to 0 if the cluster
1091 * is allocated and doesn't need COW, but doesn't have the right
1094 * 1: if allocated clusters that don't require a COW are available at
1095 * the requested offset. *bytes may have decreased and describes
1096 * the length of the area that can be written to.
1098 * -errno: in error cases
1100 static int handle_copied(BlockDriverState
*bs
, uint64_t guest_offset
,
1101 uint64_t *host_offset
, uint64_t *bytes
, QCowL2Meta
**m
)
1103 BDRVQcow2State
*s
= bs
->opaque
;
1105 uint64_t cluster_offset
;
1107 uint64_t nb_clusters
;
1108 unsigned int keep_clusters
;
1111 trace_qcow2_handle_copied(qemu_coroutine_self(), guest_offset
, *host_offset
,
1114 assert(*host_offset
== 0 || offset_into_cluster(s
, guest_offset
)
1115 == offset_into_cluster(s
, *host_offset
));
1118 * Calculate the number of clusters to look for. We stop at L2 table
1119 * boundaries to keep things simple.
1122 size_to_clusters(s
, offset_into_cluster(s
, guest_offset
) + *bytes
);
1124 l2_index
= offset_to_l2_index(s
, guest_offset
);
1125 nb_clusters
= MIN(nb_clusters
, s
->l2_size
- l2_index
);
1126 assert(nb_clusters
<= INT_MAX
);
1128 /* Find L2 entry for the first involved cluster */
1129 ret
= get_cluster_table(bs
, guest_offset
, &l2_table
, &l2_index
);
1134 cluster_offset
= be64_to_cpu(l2_table
[l2_index
]);
1136 /* Check how many clusters are already allocated and don't need COW */
1137 if (qcow2_get_cluster_type(cluster_offset
) == QCOW2_CLUSTER_NORMAL
1138 && (cluster_offset
& QCOW_OFLAG_COPIED
))
1140 /* If a specific host_offset is required, check it */
1141 bool offset_matches
=
1142 (cluster_offset
& L2E_OFFSET_MASK
) == *host_offset
;
1144 if (offset_into_cluster(s
, cluster_offset
& L2E_OFFSET_MASK
)) {
1145 qcow2_signal_corruption(bs
, true, -1, -1, "Data cluster offset "
1146 "%#llx unaligned (guest offset: %#" PRIx64
1147 ")", cluster_offset
& L2E_OFFSET_MASK
,
1153 if (*host_offset
!= 0 && !offset_matches
) {
1159 /* We keep all QCOW_OFLAG_COPIED clusters */
1161 count_contiguous_clusters(nb_clusters
, s
->cluster_size
,
1162 &l2_table
[l2_index
],
1163 QCOW_OFLAG_COPIED
| QCOW_OFLAG_ZERO
);
1164 assert(keep_clusters
<= nb_clusters
);
1166 *bytes
= MIN(*bytes
,
1167 keep_clusters
* s
->cluster_size
1168 - offset_into_cluster(s
, guest_offset
));
1177 qcow2_cache_put(bs
, s
->l2_table_cache
, (void **) &l2_table
);
1179 /* Only return a host offset if we actually made progress. Otherwise we
1180 * would make requirements for handle_alloc() that it can't fulfill */
1182 *host_offset
= (cluster_offset
& L2E_OFFSET_MASK
)
1183 + offset_into_cluster(s
, guest_offset
);
1190 * Allocates new clusters for the given guest_offset.
1192 * At most *nb_clusters are allocated, and on return *nb_clusters is updated to
1193 * contain the number of clusters that have been allocated and are contiguous
1194 * in the image file.
1196 * If *host_offset is non-zero, it specifies the offset in the image file at
1197 * which the new clusters must start. *nb_clusters can be 0 on return in this
1198 * case if the cluster at host_offset is already in use. If *host_offset is
1199 * zero, the clusters can be allocated anywhere in the image file.
1201 * *host_offset is updated to contain the offset into the image file at which
1202 * the first allocated cluster starts.
1204 * Return 0 on success and -errno in error cases. -EAGAIN means that the
1205 * function has been waiting for another request and the allocation must be
1206 * restarted, but the whole request should not be failed.
1208 static int do_alloc_cluster_offset(BlockDriverState
*bs
, uint64_t guest_offset
,
1209 uint64_t *host_offset
, uint64_t *nb_clusters
)
1211 BDRVQcow2State
*s
= bs
->opaque
;
1213 trace_qcow2_do_alloc_clusters_offset(qemu_coroutine_self(), guest_offset
,
1214 *host_offset
, *nb_clusters
);
1216 /* Allocate new clusters */
1217 trace_qcow2_cluster_alloc_phys(qemu_coroutine_self());
1218 if (*host_offset
== 0) {
1219 int64_t cluster_offset
=
1220 qcow2_alloc_clusters(bs
, *nb_clusters
* s
->cluster_size
);
1221 if (cluster_offset
< 0) {
1222 return cluster_offset
;
1224 *host_offset
= cluster_offset
;
1227 int64_t ret
= qcow2_alloc_clusters_at(bs
, *host_offset
, *nb_clusters
);
1237 * Allocates new clusters for an area that either is yet unallocated or needs a
1238 * copy on write. If *host_offset is non-zero, clusters are only allocated if
1239 * the new allocation can match the specified host offset.
1241 * Note that guest_offset may not be cluster aligned. In this case, the
1242 * returned *host_offset points to exact byte referenced by guest_offset and
1243 * therefore isn't cluster aligned as well.
1246 * 0: if no clusters could be allocated. *bytes is set to 0,
1247 * *host_offset is left unchanged.
1249 * 1: if new clusters were allocated. *bytes may be decreased if the
1250 * new allocation doesn't cover all of the requested area.
1251 * *host_offset is updated to contain the host offset of the first
1252 * newly allocated cluster.
1254 * -errno: in error cases
1256 static int handle_alloc(BlockDriverState
*bs
, uint64_t guest_offset
,
1257 uint64_t *host_offset
, uint64_t *bytes
, QCowL2Meta
**m
)
1259 BDRVQcow2State
*s
= bs
->opaque
;
1263 uint64_t nb_clusters
;
1265 bool keep_old_clusters
= false;
1267 uint64_t alloc_cluster_offset
= 0;
1269 trace_qcow2_handle_alloc(qemu_coroutine_self(), guest_offset
, *host_offset
,
1274 * Calculate the number of clusters to look for. We stop at L2 table
1275 * boundaries to keep things simple.
1278 size_to_clusters(s
, offset_into_cluster(s
, guest_offset
) + *bytes
);
1280 l2_index
= offset_to_l2_index(s
, guest_offset
);
1281 nb_clusters
= MIN(nb_clusters
, s
->l2_size
- l2_index
);
1282 assert(nb_clusters
<= INT_MAX
);
1284 /* Find L2 entry for the first involved cluster */
1285 ret
= get_cluster_table(bs
, guest_offset
, &l2_table
, &l2_index
);
1290 entry
= be64_to_cpu(l2_table
[l2_index
]);
1292 /* For the moment, overwrite compressed clusters one by one */
1293 if (entry
& QCOW_OFLAG_COMPRESSED
) {
1296 nb_clusters
= count_cow_clusters(s
, nb_clusters
, l2_table
, l2_index
);
1299 /* This function is only called when there were no non-COW clusters, so if
1300 * we can't find any unallocated or COW clusters either, something is
1301 * wrong with our code. */
1302 assert(nb_clusters
> 0);
1304 if (qcow2_get_cluster_type(entry
) == QCOW2_CLUSTER_ZERO_ALLOC
&&
1305 (entry
& QCOW_OFLAG_COPIED
) &&
1307 start_of_cluster(s
, *host_offset
) == (entry
& L2E_OFFSET_MASK
)))
1309 int preallocated_nb_clusters
;
1311 if (offset_into_cluster(s
, entry
& L2E_OFFSET_MASK
)) {
1312 qcow2_signal_corruption(bs
, true, -1, -1, "Preallocated zero "
1313 "cluster offset %#llx unaligned (guest "
1314 "offset: %#" PRIx64
")",
1315 entry
& L2E_OFFSET_MASK
, guest_offset
);
1320 /* Try to reuse preallocated zero clusters; contiguous normal clusters
1321 * would be fine, too, but count_cow_clusters() above has limited
1322 * nb_clusters already to a range of COW clusters */
1323 preallocated_nb_clusters
=
1324 count_contiguous_clusters(nb_clusters
, s
->cluster_size
,
1325 &l2_table
[l2_index
], QCOW_OFLAG_COPIED
);
1326 assert(preallocated_nb_clusters
> 0);
1328 nb_clusters
= preallocated_nb_clusters
;
1329 alloc_cluster_offset
= entry
& L2E_OFFSET_MASK
;
1331 /* We want to reuse these clusters, so qcow2_alloc_cluster_link_l2()
1332 * should not free them. */
1333 keep_old_clusters
= true;
1336 qcow2_cache_put(bs
, s
->l2_table_cache
, (void **) &l2_table
);
1338 if (!alloc_cluster_offset
) {
1339 /* Allocate, if necessary at a given offset in the image file */
1340 alloc_cluster_offset
= start_of_cluster(s
, *host_offset
);
1341 ret
= do_alloc_cluster_offset(bs
, guest_offset
, &alloc_cluster_offset
,
1347 /* Can't extend contiguous allocation */
1348 if (nb_clusters
== 0) {
1353 /* !*host_offset would overwrite the image header and is reserved for
1354 * "no host offset preferred". If 0 was a valid host offset, it'd
1355 * trigger the following overlap check; do that now to avoid having an
1356 * invalid value in *host_offset. */
1357 if (!alloc_cluster_offset
) {
1358 ret
= qcow2_pre_write_overlap_check(bs
, 0, alloc_cluster_offset
,
1359 nb_clusters
* s
->cluster_size
);
1366 * Save info needed for meta data update.
1368 * requested_bytes: Number of bytes from the start of the first
1369 * newly allocated cluster to the end of the (possibly shortened
1370 * before) write request.
1372 * avail_bytes: Number of bytes from the start of the first
1373 * newly allocated to the end of the last newly allocated cluster.
1375 * nb_bytes: The number of bytes from the start of the first
1376 * newly allocated cluster to the end of the area that the write
1377 * request actually writes to (excluding COW at the end)
1379 uint64_t requested_bytes
= *bytes
+ offset_into_cluster(s
, guest_offset
);
1380 int avail_bytes
= MIN(INT_MAX
, nb_clusters
<< s
->cluster_bits
);
1381 int nb_bytes
= MIN(requested_bytes
, avail_bytes
);
1382 QCowL2Meta
*old_m
= *m
;
1384 *m
= g_malloc0(sizeof(**m
));
1386 **m
= (QCowL2Meta
) {
1389 .alloc_offset
= alloc_cluster_offset
,
1390 .offset
= start_of_cluster(s
, guest_offset
),
1391 .nb_clusters
= nb_clusters
,
1393 .keep_old_clusters
= keep_old_clusters
,
1397 .nb_bytes
= offset_into_cluster(s
, guest_offset
),
1401 .nb_bytes
= avail_bytes
- nb_bytes
,
1404 qemu_co_queue_init(&(*m
)->dependent_requests
);
1405 QLIST_INSERT_HEAD(&s
->cluster_allocs
, *m
, next_in_flight
);
1407 *host_offset
= alloc_cluster_offset
+ offset_into_cluster(s
, guest_offset
);
1408 *bytes
= MIN(*bytes
, nb_bytes
- offset_into_cluster(s
, guest_offset
));
1409 assert(*bytes
!= 0);
1414 if (*m
&& (*m
)->nb_clusters
> 0) {
1415 QLIST_REMOVE(*m
, next_in_flight
);
1421 * alloc_cluster_offset
1423 * For a given offset on the virtual disk, find the cluster offset in qcow2
1424 * file. If the offset is not found, allocate a new cluster.
1426 * If the cluster was already allocated, m->nb_clusters is set to 0 and
1427 * other fields in m are meaningless.
1429 * If the cluster is newly allocated, m->nb_clusters is set to the number of
1430 * contiguous clusters that have been allocated. In this case, the other
1431 * fields of m are valid and contain information about the first allocated
1434 * If the request conflicts with another write request in flight, the coroutine
1435 * is queued and will be reentered when the dependency has completed.
1437 * Return 0 on success and -errno in error cases
1439 int qcow2_alloc_cluster_offset(BlockDriverState
*bs
, uint64_t offset
,
1440 unsigned int *bytes
, uint64_t *host_offset
,
1443 BDRVQcow2State
*s
= bs
->opaque
;
1444 uint64_t start
, remaining
;
1445 uint64_t cluster_offset
;
1449 trace_qcow2_alloc_clusters_offset(qemu_coroutine_self(), offset
, *bytes
);
1461 if (!*host_offset
) {
1462 *host_offset
= start_of_cluster(s
, cluster_offset
);
1465 assert(remaining
>= cur_bytes
);
1468 remaining
-= cur_bytes
;
1469 cluster_offset
+= cur_bytes
;
1471 if (remaining
== 0) {
1475 cur_bytes
= remaining
;
1478 * Now start gathering as many contiguous clusters as possible:
1480 * 1. Check for overlaps with in-flight allocations
1482 * a) Overlap not in the first cluster -> shorten this request and
1483 * let the caller handle the rest in its next loop iteration.
1485 * b) Real overlaps of two requests. Yield and restart the search
1486 * for contiguous clusters (the situation could have changed
1487 * while we were sleeping)
1489 * c) TODO: Request starts in the same cluster as the in-flight
1490 * allocation ends. Shorten the COW of the in-fight allocation,
1491 * set cluster_offset to write to the same cluster and set up
1492 * the right synchronisation between the in-flight request and
1495 ret
= handle_dependencies(bs
, start
, &cur_bytes
, m
);
1496 if (ret
== -EAGAIN
) {
1497 /* Currently handle_dependencies() doesn't yield if we already had
1498 * an allocation. If it did, we would have to clean up the L2Meta
1499 * structs before starting over. */
1502 } else if (ret
< 0) {
1504 } else if (cur_bytes
== 0) {
1507 /* handle_dependencies() may have decreased cur_bytes (shortened
1508 * the allocations below) so that the next dependency is processed
1509 * correctly during the next loop iteration. */
1513 * 2. Count contiguous COPIED clusters.
1515 ret
= handle_copied(bs
, start
, &cluster_offset
, &cur_bytes
, m
);
1520 } else if (cur_bytes
== 0) {
1525 * 3. If the request still hasn't completed, allocate new clusters,
1526 * considering any cluster_offset of steps 1c or 2.
1528 ret
= handle_alloc(bs
, start
, &cluster_offset
, &cur_bytes
, m
);
1534 assert(cur_bytes
== 0);
1539 *bytes
-= remaining
;
1541 assert(*host_offset
!= 0);
1546 static int decompress_buffer(uint8_t *out_buf
, int out_buf_size
,
1547 const uint8_t *buf
, int buf_size
)
1549 z_stream strm1
, *strm
= &strm1
;
1552 memset(strm
, 0, sizeof(*strm
));
1554 strm
->next_in
= (uint8_t *)buf
;
1555 strm
->avail_in
= buf_size
;
1556 strm
->next_out
= out_buf
;
1557 strm
->avail_out
= out_buf_size
;
1559 ret
= inflateInit2(strm
, -12);
1562 ret
= inflate(strm
, Z_FINISH
);
1563 out_len
= strm
->next_out
- out_buf
;
1564 if ((ret
!= Z_STREAM_END
&& ret
!= Z_BUF_ERROR
) ||
1565 out_len
!= out_buf_size
) {
1573 int qcow2_decompress_cluster(BlockDriverState
*bs
, uint64_t cluster_offset
)
1575 BDRVQcow2State
*s
= bs
->opaque
;
1576 int ret
, csize
, nb_csectors
, sector_offset
;
1579 coffset
= cluster_offset
& s
->cluster_offset_mask
;
1580 if (s
->cluster_cache_offset
!= coffset
) {
1581 nb_csectors
= ((cluster_offset
>> s
->csize_shift
) & s
->csize_mask
) + 1;
1582 sector_offset
= coffset
& 511;
1583 csize
= nb_csectors
* 512 - sector_offset
;
1585 /* Allocate buffers on first decompress operation, most images are
1586 * uncompressed and the memory overhead can be avoided. The buffers
1587 * are freed in .bdrv_close().
1589 if (!s
->cluster_data
) {
1590 /* one more sector for decompressed data alignment */
1591 s
->cluster_data
= qemu_try_blockalign(bs
->file
->bs
,
1592 QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_size
+ 512);
1593 if (!s
->cluster_data
) {
1597 if (!s
->cluster_cache
) {
1598 s
->cluster_cache
= g_malloc(s
->cluster_size
);
1601 BLKDBG_EVENT(bs
->file
, BLKDBG_READ_COMPRESSED
);
1602 ret
= bdrv_read(bs
->file
, coffset
>> 9, s
->cluster_data
,
1607 if (decompress_buffer(s
->cluster_cache
, s
->cluster_size
,
1608 s
->cluster_data
+ sector_offset
, csize
) < 0) {
1611 s
->cluster_cache_offset
= coffset
;
1617 * This discards as many clusters of nb_clusters as possible at once (i.e.
1618 * all clusters in the same L2 table) and returns the number of discarded
1621 static int discard_single_l2(BlockDriverState
*bs
, uint64_t offset
,
1622 uint64_t nb_clusters
, enum qcow2_discard_type type
,
1625 BDRVQcow2State
*s
= bs
->opaque
;
1631 ret
= get_cluster_table(bs
, offset
, &l2_table
, &l2_index
);
1636 /* Limit nb_clusters to one L2 table */
1637 nb_clusters
= MIN(nb_clusters
, s
->l2_size
- l2_index
);
1638 assert(nb_clusters
<= INT_MAX
);
1640 for (i
= 0; i
< nb_clusters
; i
++) {
1641 uint64_t old_l2_entry
;
1643 old_l2_entry
= be64_to_cpu(l2_table
[l2_index
+ i
]);
1646 * If full_discard is false, make sure that a discarded area reads back
1647 * as zeroes for v3 images (we cannot do it for v2 without actually
1648 * writing a zero-filled buffer). We can skip the operation if the
1649 * cluster is already marked as zero, or if it's unallocated and we
1650 * don't have a backing file.
1652 * TODO We might want to use bdrv_block_status(bs) here, but we're
1653 * holding s->lock, so that doesn't work today.
1655 * If full_discard is true, the sector should not read back as zeroes,
1656 * but rather fall through to the backing file.
1658 switch (qcow2_get_cluster_type(old_l2_entry
)) {
1659 case QCOW2_CLUSTER_UNALLOCATED
:
1660 if (full_discard
|| !bs
->backing
) {
1665 case QCOW2_CLUSTER_ZERO_PLAIN
:
1666 if (!full_discard
) {
1671 case QCOW2_CLUSTER_ZERO_ALLOC
:
1672 case QCOW2_CLUSTER_NORMAL
:
1673 case QCOW2_CLUSTER_COMPRESSED
:
1680 /* First remove L2 entries */
1681 qcow2_cache_entry_mark_dirty(s
->l2_table_cache
, l2_table
);
1682 if (!full_discard
&& s
->qcow_version
>= 3) {
1683 l2_table
[l2_index
+ i
] = cpu_to_be64(QCOW_OFLAG_ZERO
);
1685 l2_table
[l2_index
+ i
] = cpu_to_be64(0);
1688 /* Then decrease the refcount */
1689 qcow2_free_any_clusters(bs
, old_l2_entry
, 1, type
);
1692 qcow2_cache_put(bs
, s
->l2_table_cache
, (void **) &l2_table
);
1697 int qcow2_cluster_discard(BlockDriverState
*bs
, uint64_t offset
,
1698 uint64_t bytes
, enum qcow2_discard_type type
,
1701 BDRVQcow2State
*s
= bs
->opaque
;
1702 uint64_t end_offset
= offset
+ bytes
;
1703 uint64_t nb_clusters
;
1707 /* Caller must pass aligned values, except at image end */
1708 assert(QEMU_IS_ALIGNED(offset
, s
->cluster_size
));
1709 assert(QEMU_IS_ALIGNED(end_offset
, s
->cluster_size
) ||
1710 end_offset
== bs
->total_sectors
<< BDRV_SECTOR_BITS
);
1712 nb_clusters
= size_to_clusters(s
, bytes
);
1714 s
->cache_discards
= true;
1716 /* Each L2 table is handled by its own loop iteration */
1717 while (nb_clusters
> 0) {
1718 cleared
= discard_single_l2(bs
, offset
, nb_clusters
, type
,
1725 nb_clusters
-= cleared
;
1726 offset
+= (cleared
* s
->cluster_size
);
1731 s
->cache_discards
= false;
1732 qcow2_process_discards(bs
, ret
);
1738 * This zeroes as many clusters of nb_clusters as possible at once (i.e.
1739 * all clusters in the same L2 table) and returns the number of zeroed
1742 static int zero_single_l2(BlockDriverState
*bs
, uint64_t offset
,
1743 uint64_t nb_clusters
, int flags
)
1745 BDRVQcow2State
*s
= bs
->opaque
;
1750 bool unmap
= !!(flags
& BDRV_REQ_MAY_UNMAP
);
1752 ret
= get_cluster_table(bs
, offset
, &l2_table
, &l2_index
);
1757 /* Limit nb_clusters to one L2 table */
1758 nb_clusters
= MIN(nb_clusters
, s
->l2_size
- l2_index
);
1759 assert(nb_clusters
<= INT_MAX
);
1761 for (i
= 0; i
< nb_clusters
; i
++) {
1762 uint64_t old_offset
;
1763 QCow2ClusterType cluster_type
;
1765 old_offset
= be64_to_cpu(l2_table
[l2_index
+ i
]);
1768 * Minimize L2 changes if the cluster already reads back as
1769 * zeroes with correct allocation.
1771 cluster_type
= qcow2_get_cluster_type(old_offset
);
1772 if (cluster_type
== QCOW2_CLUSTER_ZERO_PLAIN
||
1773 (cluster_type
== QCOW2_CLUSTER_ZERO_ALLOC
&& !unmap
)) {
1777 qcow2_cache_entry_mark_dirty(s
->l2_table_cache
, l2_table
);
1778 if (cluster_type
== QCOW2_CLUSTER_COMPRESSED
|| unmap
) {
1779 l2_table
[l2_index
+ i
] = cpu_to_be64(QCOW_OFLAG_ZERO
);
1780 qcow2_free_any_clusters(bs
, old_offset
, 1, QCOW2_DISCARD_REQUEST
);
1782 l2_table
[l2_index
+ i
] |= cpu_to_be64(QCOW_OFLAG_ZERO
);
1786 qcow2_cache_put(bs
, s
->l2_table_cache
, (void **) &l2_table
);
1791 int qcow2_cluster_zeroize(BlockDriverState
*bs
, uint64_t offset
,
1792 uint64_t bytes
, int flags
)
1794 BDRVQcow2State
*s
= bs
->opaque
;
1795 uint64_t end_offset
= offset
+ bytes
;
1796 uint64_t nb_clusters
;
1800 /* Caller must pass aligned values, except at image end */
1801 assert(QEMU_IS_ALIGNED(offset
, s
->cluster_size
));
1802 assert(QEMU_IS_ALIGNED(end_offset
, s
->cluster_size
) ||
1803 end_offset
== bs
->total_sectors
<< BDRV_SECTOR_BITS
);
1805 /* The zero flag is only supported by version 3 and newer */
1806 if (s
->qcow_version
< 3) {
1810 /* Each L2 table is handled by its own loop iteration */
1811 nb_clusters
= size_to_clusters(s
, bytes
);
1813 s
->cache_discards
= true;
1815 while (nb_clusters
> 0) {
1816 cleared
= zero_single_l2(bs
, offset
, nb_clusters
, flags
);
1822 nb_clusters
-= cleared
;
1823 offset
+= (cleared
* s
->cluster_size
);
1828 s
->cache_discards
= false;
1829 qcow2_process_discards(bs
, ret
);
1835 * Expands all zero clusters in a specific L1 table (or deallocates them, for
1836 * non-backed non-pre-allocated zero clusters).
1838 * l1_entries and *visited_l1_entries are used to keep track of progress for
1839 * status_cb(). l1_entries contains the total number of L1 entries and
1840 * *visited_l1_entries counts all visited L1 entries.
1842 static int expand_zero_clusters_in_l1(BlockDriverState
*bs
, uint64_t *l1_table
,
1843 int l1_size
, int64_t *visited_l1_entries
,
1845 BlockDriverAmendStatusCB
*status_cb
,
1848 BDRVQcow2State
*s
= bs
->opaque
;
1849 bool is_active_l1
= (l1_table
== s
->l1_table
);
1850 uint64_t *l2_table
= NULL
;
1854 if (!is_active_l1
) {
1855 /* inactive L2 tables require a buffer to be stored in when loading
1857 l2_table
= qemu_try_blockalign(bs
->file
->bs
, s
->cluster_size
);
1858 if (l2_table
== NULL
) {
1863 for (i
= 0; i
< l1_size
; i
++) {
1864 uint64_t l2_offset
= l1_table
[i
] & L1E_OFFSET_MASK
;
1865 bool l2_dirty
= false;
1866 uint64_t l2_refcount
;
1870 (*visited_l1_entries
)++;
1872 status_cb(bs
, *visited_l1_entries
, l1_entries
, cb_opaque
);
1877 if (offset_into_cluster(s
, l2_offset
)) {
1878 qcow2_signal_corruption(bs
, true, -1, -1, "L2 table offset %#"
1879 PRIx64
" unaligned (L1 index: %#x)",
1886 /* get active L2 tables from cache */
1887 ret
= qcow2_cache_get(bs
, s
->l2_table_cache
, l2_offset
,
1888 (void **)&l2_table
);
1890 /* load inactive L2 tables from disk */
1891 ret
= bdrv_read(bs
->file
, l2_offset
/ BDRV_SECTOR_SIZE
,
1892 (void *)l2_table
, s
->cluster_sectors
);
1898 ret
= qcow2_get_refcount(bs
, l2_offset
>> s
->cluster_bits
,
1904 for (j
= 0; j
< s
->l2_size
; j
++) {
1905 uint64_t l2_entry
= be64_to_cpu(l2_table
[j
]);
1906 int64_t offset
= l2_entry
& L2E_OFFSET_MASK
;
1907 QCow2ClusterType cluster_type
= qcow2_get_cluster_type(l2_entry
);
1909 if (cluster_type
!= QCOW2_CLUSTER_ZERO_PLAIN
&&
1910 cluster_type
!= QCOW2_CLUSTER_ZERO_ALLOC
) {
1914 if (cluster_type
== QCOW2_CLUSTER_ZERO_PLAIN
) {
1916 /* not backed; therefore we can simply deallocate the
1923 offset
= qcow2_alloc_clusters(bs
, s
->cluster_size
);
1929 if (l2_refcount
> 1) {
1930 /* For shared L2 tables, set the refcount accordingly (it is
1931 * already 1 and needs to be l2_refcount) */
1932 ret
= qcow2_update_cluster_refcount(bs
,
1933 offset
>> s
->cluster_bits
,
1934 refcount_diff(1, l2_refcount
), false,
1935 QCOW2_DISCARD_OTHER
);
1937 qcow2_free_clusters(bs
, offset
, s
->cluster_size
,
1938 QCOW2_DISCARD_OTHER
);
1944 if (offset_into_cluster(s
, offset
)) {
1945 qcow2_signal_corruption(bs
, true, -1, -1,
1946 "Cluster allocation offset "
1947 "%#" PRIx64
" unaligned (L2 offset: %#"
1948 PRIx64
", L2 index: %#x)", offset
,
1950 if (cluster_type
== QCOW2_CLUSTER_ZERO_PLAIN
) {
1951 qcow2_free_clusters(bs
, offset
, s
->cluster_size
,
1952 QCOW2_DISCARD_ALWAYS
);
1958 ret
= qcow2_pre_write_overlap_check(bs
, 0, offset
, s
->cluster_size
);
1960 if (cluster_type
== QCOW2_CLUSTER_ZERO_PLAIN
) {
1961 qcow2_free_clusters(bs
, offset
, s
->cluster_size
,
1962 QCOW2_DISCARD_ALWAYS
);
1967 ret
= bdrv_pwrite_zeroes(bs
->file
, offset
, s
->cluster_size
, 0);
1969 if (cluster_type
== QCOW2_CLUSTER_ZERO_PLAIN
) {
1970 qcow2_free_clusters(bs
, offset
, s
->cluster_size
,
1971 QCOW2_DISCARD_ALWAYS
);
1976 if (l2_refcount
== 1) {
1977 l2_table
[j
] = cpu_to_be64(offset
| QCOW_OFLAG_COPIED
);
1979 l2_table
[j
] = cpu_to_be64(offset
);
1986 qcow2_cache_entry_mark_dirty(s
->l2_table_cache
, l2_table
);
1987 qcow2_cache_depends_on_flush(s
->l2_table_cache
);
1989 qcow2_cache_put(bs
, s
->l2_table_cache
, (void **) &l2_table
);
1992 ret
= qcow2_pre_write_overlap_check(bs
,
1993 QCOW2_OL_INACTIVE_L2
| QCOW2_OL_ACTIVE_L2
, l2_offset
,
1999 ret
= bdrv_write(bs
->file
, l2_offset
/ BDRV_SECTOR_SIZE
,
2000 (void *)l2_table
, s
->cluster_sectors
);
2007 (*visited_l1_entries
)++;
2009 status_cb(bs
, *visited_l1_entries
, l1_entries
, cb_opaque
);
2017 if (!is_active_l1
) {
2018 qemu_vfree(l2_table
);
2020 qcow2_cache_put(bs
, s
->l2_table_cache
, (void **) &l2_table
);
2027 * For backed images, expands all zero clusters on the image. For non-backed
2028 * images, deallocates all non-pre-allocated zero clusters (and claims the
2029 * allocation for pre-allocated ones). This is important for downgrading to a
2030 * qcow2 version which doesn't yet support metadata zero clusters.
2032 int qcow2_expand_zero_clusters(BlockDriverState
*bs
,
2033 BlockDriverAmendStatusCB
*status_cb
,
2036 BDRVQcow2State
*s
= bs
->opaque
;
2037 uint64_t *l1_table
= NULL
;
2038 int64_t l1_entries
= 0, visited_l1_entries
= 0;
2043 l1_entries
= s
->l1_size
;
2044 for (i
= 0; i
< s
->nb_snapshots
; i
++) {
2045 l1_entries
+= s
->snapshots
[i
].l1_size
;
2049 ret
= expand_zero_clusters_in_l1(bs
, s
->l1_table
, s
->l1_size
,
2050 &visited_l1_entries
, l1_entries
,
2051 status_cb
, cb_opaque
);
2056 /* Inactive L1 tables may point to active L2 tables - therefore it is
2057 * necessary to flush the L2 table cache before trying to access the L2
2058 * tables pointed to by inactive L1 entries (else we might try to expand
2059 * zero clusters that have already been expanded); furthermore, it is also
2060 * necessary to empty the L2 table cache, since it may contain tables which
2061 * are now going to be modified directly on disk, bypassing the cache.
2062 * qcow2_cache_empty() does both for us. */
2063 ret
= qcow2_cache_empty(bs
, s
->l2_table_cache
);
2068 for (i
= 0; i
< s
->nb_snapshots
; i
++) {
2069 int l1_sectors
= DIV_ROUND_UP(s
->snapshots
[i
].l1_size
*
2070 sizeof(uint64_t), BDRV_SECTOR_SIZE
);
2072 uint64_t *new_l1_table
=
2073 g_try_realloc(l1_table
, l1_sectors
* BDRV_SECTOR_SIZE
);
2075 if (!new_l1_table
) {
2080 l1_table
= new_l1_table
;
2082 ret
= bdrv_read(bs
->file
,
2083 s
->snapshots
[i
].l1_table_offset
/ BDRV_SECTOR_SIZE
,
2084 (void *)l1_table
, l1_sectors
);
2089 for (j
= 0; j
< s
->snapshots
[i
].l1_size
; j
++) {
2090 be64_to_cpus(&l1_table
[j
]);
2093 ret
= expand_zero_clusters_in_l1(bs
, l1_table
, s
->snapshots
[i
].l1_size
,
2094 &visited_l1_entries
, l1_entries
,
2095 status_cb
, cb_opaque
);