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"
27 #include "block/qdict.h"
28 #include "sysemu/block-backend.h"
29 #include "qemu/main-loop.h"
30 #include "qemu/module.h"
32 #include "qemu/error-report.h"
33 #include "qapi/error.h"
34 #include "qapi/qapi-events-block-core.h"
35 #include "qapi/qmp/qdict.h"
36 #include "qapi/qmp/qstring.h"
38 #include "qemu/option_int.h"
39 #include "qemu/cutils.h"
40 #include "qemu/bswap.h"
41 #include "qapi/qobject-input-visitor.h"
42 #include "qapi/qapi-visit-block-core.h"
44 #include "block/aio_task.h"
47 Differences with QCOW:
49 - Support for multiple incremental snapshots.
50 - Memory management by reference counts.
51 - Clusters which have a reference count of one have the bit
52 QCOW_OFLAG_COPIED to optimize write performance.
53 - Size of compressed clusters is stored in sectors to reduce bit usage
54 in the cluster offsets.
55 - Support for storing additional data (such as the VM state) in the
57 - If a backing store is used, the cluster size is not constrained
58 (could be backported to QCOW).
59 - L2 tables have always a size of one cluster.
66 } QEMU_PACKED QCowExtension
;
68 #define QCOW2_EXT_MAGIC_END 0
69 #define QCOW2_EXT_MAGIC_BACKING_FORMAT 0xE2792ACA
70 #define QCOW2_EXT_MAGIC_FEATURE_TABLE 0x6803f857
71 #define QCOW2_EXT_MAGIC_CRYPTO_HEADER 0x0537be77
72 #define QCOW2_EXT_MAGIC_BITMAPS 0x23852875
73 #define QCOW2_EXT_MAGIC_DATA_FILE 0x44415441
75 static int coroutine_fn
76 qcow2_co_preadv_compressed(BlockDriverState
*bs
,
77 uint64_t file_cluster_offset
,
83 static int qcow2_probe(const uint8_t *buf
, int buf_size
, const char *filename
)
85 const QCowHeader
*cow_header
= (const void *)buf
;
87 if (buf_size
>= sizeof(QCowHeader
) &&
88 be32_to_cpu(cow_header
->magic
) == QCOW_MAGIC
&&
89 be32_to_cpu(cow_header
->version
) >= 2)
96 static ssize_t
qcow2_crypto_hdr_read_func(QCryptoBlock
*block
, size_t offset
,
97 uint8_t *buf
, size_t buflen
,
98 void *opaque
, Error
**errp
)
100 BlockDriverState
*bs
= opaque
;
101 BDRVQcow2State
*s
= bs
->opaque
;
104 if ((offset
+ buflen
) > s
->crypto_header
.length
) {
105 error_setg(errp
, "Request for data outside of extension header");
109 ret
= bdrv_pread(bs
->file
,
110 s
->crypto_header
.offset
+ offset
, buf
, buflen
);
112 error_setg_errno(errp
, -ret
, "Could not read encryption header");
119 static ssize_t
qcow2_crypto_hdr_init_func(QCryptoBlock
*block
, size_t headerlen
,
120 void *opaque
, Error
**errp
)
122 BlockDriverState
*bs
= opaque
;
123 BDRVQcow2State
*s
= bs
->opaque
;
127 ret
= qcow2_alloc_clusters(bs
, headerlen
);
129 error_setg_errno(errp
, -ret
,
130 "Cannot allocate cluster for LUKS header size %zu",
135 s
->crypto_header
.length
= headerlen
;
136 s
->crypto_header
.offset
= ret
;
139 * Zero fill all space in cluster so it has predictable
140 * content, as we may not initialize some regions of the
141 * header (eg only 1 out of 8 key slots will be initialized)
143 clusterlen
= size_to_clusters(s
, headerlen
) * s
->cluster_size
;
144 assert(qcow2_pre_write_overlap_check(bs
, 0, ret
, clusterlen
, false) == 0);
145 ret
= bdrv_pwrite_zeroes(bs
->file
,
149 error_setg_errno(errp
, -ret
, "Could not zero fill encryption header");
157 static ssize_t
qcow2_crypto_hdr_write_func(QCryptoBlock
*block
, size_t offset
,
158 const uint8_t *buf
, size_t buflen
,
159 void *opaque
, Error
**errp
)
161 BlockDriverState
*bs
= opaque
;
162 BDRVQcow2State
*s
= bs
->opaque
;
165 if ((offset
+ buflen
) > s
->crypto_header
.length
) {
166 error_setg(errp
, "Request for data outside of extension header");
170 ret
= bdrv_pwrite(bs
->file
,
171 s
->crypto_header
.offset
+ offset
, buf
, buflen
);
173 error_setg_errno(errp
, -ret
, "Could not read encryption header");
181 * read qcow2 extension and fill bs
182 * start reading from start_offset
183 * finish reading upon magic of value 0 or when end_offset reached
184 * unknown magic is skipped (future extension this version knows nothing about)
185 * return 0 upon success, non-0 otherwise
187 static int qcow2_read_extensions(BlockDriverState
*bs
, uint64_t start_offset
,
188 uint64_t end_offset
, void **p_feature_table
,
189 int flags
, bool *need_update_header
,
192 BDRVQcow2State
*s
= bs
->opaque
;
196 Qcow2BitmapHeaderExt bitmaps_ext
;
198 if (need_update_header
!= NULL
) {
199 *need_update_header
= false;
203 printf("qcow2_read_extensions: start=%ld end=%ld\n", start_offset
, end_offset
);
205 offset
= start_offset
;
206 while (offset
< end_offset
) {
210 if (offset
> s
->cluster_size
)
211 printf("qcow2_read_extension: suspicious offset %lu\n", offset
);
213 printf("attempting to read extended header in offset %lu\n", offset
);
216 ret
= bdrv_pread(bs
->file
, offset
, &ext
, sizeof(ext
));
218 error_setg_errno(errp
, -ret
, "qcow2_read_extension: ERROR: "
219 "pread fail from offset %" PRIu64
, offset
);
222 ext
.magic
= be32_to_cpu(ext
.magic
);
223 ext
.len
= be32_to_cpu(ext
.len
);
224 offset
+= sizeof(ext
);
226 printf("ext.magic = 0x%x\n", ext
.magic
);
228 if (offset
> end_offset
|| ext
.len
> end_offset
- offset
) {
229 error_setg(errp
, "Header extension too large");
234 case QCOW2_EXT_MAGIC_END
:
237 case QCOW2_EXT_MAGIC_BACKING_FORMAT
:
238 if (ext
.len
>= sizeof(bs
->backing_format
)) {
239 error_setg(errp
, "ERROR: ext_backing_format: len=%" PRIu32
240 " too large (>=%zu)", ext
.len
,
241 sizeof(bs
->backing_format
));
244 ret
= bdrv_pread(bs
->file
, offset
, bs
->backing_format
, ext
.len
);
246 error_setg_errno(errp
, -ret
, "ERROR: ext_backing_format: "
247 "Could not read format name");
250 bs
->backing_format
[ext
.len
] = '\0';
251 s
->image_backing_format
= g_strdup(bs
->backing_format
);
253 printf("Qcow2: Got format extension %s\n", bs
->backing_format
);
257 case QCOW2_EXT_MAGIC_FEATURE_TABLE
:
258 if (p_feature_table
!= NULL
) {
259 void* feature_table
= g_malloc0(ext
.len
+ 2 * sizeof(Qcow2Feature
));
260 ret
= bdrv_pread(bs
->file
, offset
, feature_table
, ext
.len
);
262 error_setg_errno(errp
, -ret
, "ERROR: ext_feature_table: "
263 "Could not read table");
267 *p_feature_table
= feature_table
;
271 case QCOW2_EXT_MAGIC_CRYPTO_HEADER
: {
272 unsigned int cflags
= 0;
273 if (s
->crypt_method_header
!= QCOW_CRYPT_LUKS
) {
274 error_setg(errp
, "CRYPTO header extension only "
275 "expected with LUKS encryption method");
278 if (ext
.len
!= sizeof(Qcow2CryptoHeaderExtension
)) {
279 error_setg(errp
, "CRYPTO header extension size %u, "
280 "but expected size %zu", ext
.len
,
281 sizeof(Qcow2CryptoHeaderExtension
));
285 ret
= bdrv_pread(bs
->file
, offset
, &s
->crypto_header
, ext
.len
);
287 error_setg_errno(errp
, -ret
,
288 "Unable to read CRYPTO header extension");
291 s
->crypto_header
.offset
= be64_to_cpu(s
->crypto_header
.offset
);
292 s
->crypto_header
.length
= be64_to_cpu(s
->crypto_header
.length
);
294 if ((s
->crypto_header
.offset
% s
->cluster_size
) != 0) {
295 error_setg(errp
, "Encryption header offset '%" PRIu64
"' is "
296 "not a multiple of cluster size '%u'",
297 s
->crypto_header
.offset
, s
->cluster_size
);
301 if (flags
& BDRV_O_NO_IO
) {
302 cflags
|= QCRYPTO_BLOCK_OPEN_NO_IO
;
304 s
->crypto
= qcrypto_block_open(s
->crypto_opts
, "encrypt.",
305 qcow2_crypto_hdr_read_func
,
306 bs
, cflags
, QCOW2_MAX_THREADS
, errp
);
312 case QCOW2_EXT_MAGIC_BITMAPS
:
313 if (ext
.len
!= sizeof(bitmaps_ext
)) {
314 error_setg_errno(errp
, -ret
, "bitmaps_ext: "
315 "Invalid extension length");
319 if (!(s
->autoclear_features
& QCOW2_AUTOCLEAR_BITMAPS
)) {
320 if (s
->qcow_version
< 3) {
321 /* Let's be a bit more specific */
322 warn_report("This qcow2 v2 image contains bitmaps, but "
323 "they may have been modified by a program "
324 "without persistent bitmap support; so now "
325 "they must all be considered inconsistent");
327 warn_report("a program lacking bitmap support "
328 "modified this file, so all bitmaps are now "
329 "considered inconsistent");
331 error_printf("Some clusters may be leaked, "
332 "run 'qemu-img check -r' on the image "
334 if (need_update_header
!= NULL
) {
335 /* Updating is needed to drop invalid bitmap extension. */
336 *need_update_header
= true;
341 ret
= bdrv_pread(bs
->file
, offset
, &bitmaps_ext
, ext
.len
);
343 error_setg_errno(errp
, -ret
, "bitmaps_ext: "
344 "Could not read ext header");
348 if (bitmaps_ext
.reserved32
!= 0) {
349 error_setg_errno(errp
, -ret
, "bitmaps_ext: "
350 "Reserved field is not zero");
354 bitmaps_ext
.nb_bitmaps
= be32_to_cpu(bitmaps_ext
.nb_bitmaps
);
355 bitmaps_ext
.bitmap_directory_size
=
356 be64_to_cpu(bitmaps_ext
.bitmap_directory_size
);
357 bitmaps_ext
.bitmap_directory_offset
=
358 be64_to_cpu(bitmaps_ext
.bitmap_directory_offset
);
360 if (bitmaps_ext
.nb_bitmaps
> QCOW2_MAX_BITMAPS
) {
362 "bitmaps_ext: Image has %" PRIu32
" bitmaps, "
363 "exceeding the QEMU supported maximum of %d",
364 bitmaps_ext
.nb_bitmaps
, QCOW2_MAX_BITMAPS
);
368 if (bitmaps_ext
.nb_bitmaps
== 0) {
369 error_setg(errp
, "found bitmaps extension with zero bitmaps");
373 if (offset_into_cluster(s
, bitmaps_ext
.bitmap_directory_offset
)) {
374 error_setg(errp
, "bitmaps_ext: "
375 "invalid bitmap directory offset");
379 if (bitmaps_ext
.bitmap_directory_size
>
380 QCOW2_MAX_BITMAP_DIRECTORY_SIZE
) {
381 error_setg(errp
, "bitmaps_ext: "
382 "bitmap directory size (%" PRIu64
") exceeds "
383 "the maximum supported size (%d)",
384 bitmaps_ext
.bitmap_directory_size
,
385 QCOW2_MAX_BITMAP_DIRECTORY_SIZE
);
389 s
->nb_bitmaps
= bitmaps_ext
.nb_bitmaps
;
390 s
->bitmap_directory_offset
=
391 bitmaps_ext
.bitmap_directory_offset
;
392 s
->bitmap_directory_size
=
393 bitmaps_ext
.bitmap_directory_size
;
396 printf("Qcow2: Got bitmaps extension: "
397 "offset=%" PRIu64
" nb_bitmaps=%" PRIu32
"\n",
398 s
->bitmap_directory_offset
, s
->nb_bitmaps
);
402 case QCOW2_EXT_MAGIC_DATA_FILE
:
404 s
->image_data_file
= g_malloc0(ext
.len
+ 1);
405 ret
= bdrv_pread(bs
->file
, offset
, s
->image_data_file
, ext
.len
);
407 error_setg_errno(errp
, -ret
,
408 "ERROR: Could not read data file name");
412 printf("Qcow2: Got external data file %s\n", s
->image_data_file
);
418 /* unknown magic - save it in case we need to rewrite the header */
419 /* If you add a new feature, make sure to also update the fast
420 * path of qcow2_make_empty() to deal with it. */
422 Qcow2UnknownHeaderExtension
*uext
;
424 uext
= g_malloc0(sizeof(*uext
) + ext
.len
);
425 uext
->magic
= ext
.magic
;
427 QLIST_INSERT_HEAD(&s
->unknown_header_ext
, uext
, next
);
429 ret
= bdrv_pread(bs
->file
, offset
, uext
->data
, uext
->len
);
431 error_setg_errno(errp
, -ret
, "ERROR: unknown extension: "
432 "Could not read data");
439 offset
+= ((ext
.len
+ 7) & ~7);
445 static void cleanup_unknown_header_ext(BlockDriverState
*bs
)
447 BDRVQcow2State
*s
= bs
->opaque
;
448 Qcow2UnknownHeaderExtension
*uext
, *next
;
450 QLIST_FOREACH_SAFE(uext
, &s
->unknown_header_ext
, next
, next
) {
451 QLIST_REMOVE(uext
, next
);
456 static void report_unsupported_feature(Error
**errp
, Qcow2Feature
*table
,
459 g_autoptr(GString
) features
= g_string_sized_new(60);
461 while (table
&& table
->name
[0] != '\0') {
462 if (table
->type
== QCOW2_FEAT_TYPE_INCOMPATIBLE
) {
463 if (mask
& (1ULL << table
->bit
)) {
464 if (features
->len
> 0) {
465 g_string_append(features
, ", ");
467 g_string_append_printf(features
, "%.46s", table
->name
);
468 mask
&= ~(1ULL << table
->bit
);
475 if (features
->len
> 0) {
476 g_string_append(features
, ", ");
478 g_string_append_printf(features
,
479 "Unknown incompatible feature: %" PRIx64
, mask
);
482 error_setg(errp
, "Unsupported qcow2 feature(s): %s", features
->str
);
486 * Sets the dirty bit and flushes afterwards if necessary.
488 * The incompatible_features bit is only set if the image file header was
489 * updated successfully. Therefore it is not required to check the return
490 * value of this function.
492 int qcow2_mark_dirty(BlockDriverState
*bs
)
494 BDRVQcow2State
*s
= bs
->opaque
;
498 assert(s
->qcow_version
>= 3);
500 if (s
->incompatible_features
& QCOW2_INCOMPAT_DIRTY
) {
501 return 0; /* already dirty */
504 val
= cpu_to_be64(s
->incompatible_features
| QCOW2_INCOMPAT_DIRTY
);
505 ret
= bdrv_pwrite(bs
->file
, offsetof(QCowHeader
, incompatible_features
),
510 ret
= bdrv_flush(bs
->file
->bs
);
515 /* Only treat image as dirty if the header was updated successfully */
516 s
->incompatible_features
|= QCOW2_INCOMPAT_DIRTY
;
521 * Clears the dirty bit and flushes before if necessary. Only call this
522 * function when there are no pending requests, it does not guard against
523 * concurrent requests dirtying the image.
525 static int qcow2_mark_clean(BlockDriverState
*bs
)
527 BDRVQcow2State
*s
= bs
->opaque
;
529 if (s
->incompatible_features
& QCOW2_INCOMPAT_DIRTY
) {
532 s
->incompatible_features
&= ~QCOW2_INCOMPAT_DIRTY
;
534 ret
= qcow2_flush_caches(bs
);
539 return qcow2_update_header(bs
);
545 * Marks the image as corrupt.
547 int qcow2_mark_corrupt(BlockDriverState
*bs
)
549 BDRVQcow2State
*s
= bs
->opaque
;
551 s
->incompatible_features
|= QCOW2_INCOMPAT_CORRUPT
;
552 return qcow2_update_header(bs
);
556 * Marks the image as consistent, i.e., unsets the corrupt bit, and flushes
557 * before if necessary.
559 int qcow2_mark_consistent(BlockDriverState
*bs
)
561 BDRVQcow2State
*s
= bs
->opaque
;
563 if (s
->incompatible_features
& QCOW2_INCOMPAT_CORRUPT
) {
564 int ret
= qcow2_flush_caches(bs
);
569 s
->incompatible_features
&= ~QCOW2_INCOMPAT_CORRUPT
;
570 return qcow2_update_header(bs
);
575 static void qcow2_add_check_result(BdrvCheckResult
*out
,
576 const BdrvCheckResult
*src
,
577 bool set_allocation_info
)
579 out
->corruptions
+= src
->corruptions
;
580 out
->leaks
+= src
->leaks
;
581 out
->check_errors
+= src
->check_errors
;
582 out
->corruptions_fixed
+= src
->corruptions_fixed
;
583 out
->leaks_fixed
+= src
->leaks_fixed
;
585 if (set_allocation_info
) {
586 out
->image_end_offset
= src
->image_end_offset
;
591 static int coroutine_fn
qcow2_co_check_locked(BlockDriverState
*bs
,
592 BdrvCheckResult
*result
,
595 BdrvCheckResult snapshot_res
= {};
596 BdrvCheckResult refcount_res
= {};
599 memset(result
, 0, sizeof(*result
));
601 ret
= qcow2_check_read_snapshot_table(bs
, &snapshot_res
, fix
);
603 qcow2_add_check_result(result
, &snapshot_res
, false);
607 ret
= qcow2_check_refcounts(bs
, &refcount_res
, fix
);
608 qcow2_add_check_result(result
, &refcount_res
, true);
610 qcow2_add_check_result(result
, &snapshot_res
, false);
614 ret
= qcow2_check_fix_snapshot_table(bs
, &snapshot_res
, fix
);
615 qcow2_add_check_result(result
, &snapshot_res
, false);
620 if (fix
&& result
->check_errors
== 0 && result
->corruptions
== 0) {
621 ret
= qcow2_mark_clean(bs
);
625 return qcow2_mark_consistent(bs
);
630 static int coroutine_fn
qcow2_co_check(BlockDriverState
*bs
,
631 BdrvCheckResult
*result
,
634 BDRVQcow2State
*s
= bs
->opaque
;
637 qemu_co_mutex_lock(&s
->lock
);
638 ret
= qcow2_co_check_locked(bs
, result
, fix
);
639 qemu_co_mutex_unlock(&s
->lock
);
643 int qcow2_validate_table(BlockDriverState
*bs
, uint64_t offset
,
644 uint64_t entries
, size_t entry_len
,
645 int64_t max_size_bytes
, const char *table_name
,
648 BDRVQcow2State
*s
= bs
->opaque
;
650 if (entries
> max_size_bytes
/ entry_len
) {
651 error_setg(errp
, "%s too large", table_name
);
655 /* Use signed INT64_MAX as the maximum even for uint64_t header fields,
656 * because values will be passed to qemu functions taking int64_t. */
657 if ((INT64_MAX
- entries
* entry_len
< offset
) ||
658 (offset_into_cluster(s
, offset
) != 0)) {
659 error_setg(errp
, "%s offset invalid", table_name
);
666 static const char *const mutable_opts
[] = {
667 QCOW2_OPT_LAZY_REFCOUNTS
,
668 QCOW2_OPT_DISCARD_REQUEST
,
669 QCOW2_OPT_DISCARD_SNAPSHOT
,
670 QCOW2_OPT_DISCARD_OTHER
,
672 QCOW2_OPT_OVERLAP_TEMPLATE
,
673 QCOW2_OPT_OVERLAP_MAIN_HEADER
,
674 QCOW2_OPT_OVERLAP_ACTIVE_L1
,
675 QCOW2_OPT_OVERLAP_ACTIVE_L2
,
676 QCOW2_OPT_OVERLAP_REFCOUNT_TABLE
,
677 QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK
,
678 QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE
,
679 QCOW2_OPT_OVERLAP_INACTIVE_L1
,
680 QCOW2_OPT_OVERLAP_INACTIVE_L2
,
681 QCOW2_OPT_OVERLAP_BITMAP_DIRECTORY
,
682 QCOW2_OPT_CACHE_SIZE
,
683 QCOW2_OPT_L2_CACHE_SIZE
,
684 QCOW2_OPT_L2_CACHE_ENTRY_SIZE
,
685 QCOW2_OPT_REFCOUNT_CACHE_SIZE
,
686 QCOW2_OPT_CACHE_CLEAN_INTERVAL
,
690 static QemuOptsList qcow2_runtime_opts
= {
692 .head
= QTAILQ_HEAD_INITIALIZER(qcow2_runtime_opts
.head
),
695 .name
= QCOW2_OPT_LAZY_REFCOUNTS
,
696 .type
= QEMU_OPT_BOOL
,
697 .help
= "Postpone refcount updates",
700 .name
= QCOW2_OPT_DISCARD_REQUEST
,
701 .type
= QEMU_OPT_BOOL
,
702 .help
= "Pass guest discard requests to the layer below",
705 .name
= QCOW2_OPT_DISCARD_SNAPSHOT
,
706 .type
= QEMU_OPT_BOOL
,
707 .help
= "Generate discard requests when snapshot related space "
711 .name
= QCOW2_OPT_DISCARD_OTHER
,
712 .type
= QEMU_OPT_BOOL
,
713 .help
= "Generate discard requests when other clusters are freed",
716 .name
= QCOW2_OPT_OVERLAP
,
717 .type
= QEMU_OPT_STRING
,
718 .help
= "Selects which overlap checks to perform from a range of "
719 "templates (none, constant, cached, all)",
722 .name
= QCOW2_OPT_OVERLAP_TEMPLATE
,
723 .type
= QEMU_OPT_STRING
,
724 .help
= "Selects which overlap checks to perform from a range of "
725 "templates (none, constant, cached, all)",
728 .name
= QCOW2_OPT_OVERLAP_MAIN_HEADER
,
729 .type
= QEMU_OPT_BOOL
,
730 .help
= "Check for unintended writes into the main qcow2 header",
733 .name
= QCOW2_OPT_OVERLAP_ACTIVE_L1
,
734 .type
= QEMU_OPT_BOOL
,
735 .help
= "Check for unintended writes into the active L1 table",
738 .name
= QCOW2_OPT_OVERLAP_ACTIVE_L2
,
739 .type
= QEMU_OPT_BOOL
,
740 .help
= "Check for unintended writes into an active L2 table",
743 .name
= QCOW2_OPT_OVERLAP_REFCOUNT_TABLE
,
744 .type
= QEMU_OPT_BOOL
,
745 .help
= "Check for unintended writes into the refcount table",
748 .name
= QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK
,
749 .type
= QEMU_OPT_BOOL
,
750 .help
= "Check for unintended writes into a refcount block",
753 .name
= QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE
,
754 .type
= QEMU_OPT_BOOL
,
755 .help
= "Check for unintended writes into the snapshot table",
758 .name
= QCOW2_OPT_OVERLAP_INACTIVE_L1
,
759 .type
= QEMU_OPT_BOOL
,
760 .help
= "Check for unintended writes into an inactive L1 table",
763 .name
= QCOW2_OPT_OVERLAP_INACTIVE_L2
,
764 .type
= QEMU_OPT_BOOL
,
765 .help
= "Check for unintended writes into an inactive L2 table",
768 .name
= QCOW2_OPT_OVERLAP_BITMAP_DIRECTORY
,
769 .type
= QEMU_OPT_BOOL
,
770 .help
= "Check for unintended writes into the bitmap directory",
773 .name
= QCOW2_OPT_CACHE_SIZE
,
774 .type
= QEMU_OPT_SIZE
,
775 .help
= "Maximum combined metadata (L2 tables and refcount blocks) "
779 .name
= QCOW2_OPT_L2_CACHE_SIZE
,
780 .type
= QEMU_OPT_SIZE
,
781 .help
= "Maximum L2 table cache size",
784 .name
= QCOW2_OPT_L2_CACHE_ENTRY_SIZE
,
785 .type
= QEMU_OPT_SIZE
,
786 .help
= "Size of each entry in the L2 cache",
789 .name
= QCOW2_OPT_REFCOUNT_CACHE_SIZE
,
790 .type
= QEMU_OPT_SIZE
,
791 .help
= "Maximum refcount block cache size",
794 .name
= QCOW2_OPT_CACHE_CLEAN_INTERVAL
,
795 .type
= QEMU_OPT_NUMBER
,
796 .help
= "Clean unused cache entries after this time (in seconds)",
798 BLOCK_CRYPTO_OPT_DEF_KEY_SECRET("encrypt.",
799 "ID of secret providing qcow2 AES key or LUKS passphrase"),
800 { /* end of list */ }
804 static const char *overlap_bool_option_names
[QCOW2_OL_MAX_BITNR
] = {
805 [QCOW2_OL_MAIN_HEADER_BITNR
] = QCOW2_OPT_OVERLAP_MAIN_HEADER
,
806 [QCOW2_OL_ACTIVE_L1_BITNR
] = QCOW2_OPT_OVERLAP_ACTIVE_L1
,
807 [QCOW2_OL_ACTIVE_L2_BITNR
] = QCOW2_OPT_OVERLAP_ACTIVE_L2
,
808 [QCOW2_OL_REFCOUNT_TABLE_BITNR
] = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE
,
809 [QCOW2_OL_REFCOUNT_BLOCK_BITNR
] = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK
,
810 [QCOW2_OL_SNAPSHOT_TABLE_BITNR
] = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE
,
811 [QCOW2_OL_INACTIVE_L1_BITNR
] = QCOW2_OPT_OVERLAP_INACTIVE_L1
,
812 [QCOW2_OL_INACTIVE_L2_BITNR
] = QCOW2_OPT_OVERLAP_INACTIVE_L2
,
813 [QCOW2_OL_BITMAP_DIRECTORY_BITNR
] = QCOW2_OPT_OVERLAP_BITMAP_DIRECTORY
,
816 static void cache_clean_timer_cb(void *opaque
)
818 BlockDriverState
*bs
= opaque
;
819 BDRVQcow2State
*s
= bs
->opaque
;
820 qcow2_cache_clean_unused(s
->l2_table_cache
);
821 qcow2_cache_clean_unused(s
->refcount_block_cache
);
822 timer_mod(s
->cache_clean_timer
, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL
) +
823 (int64_t) s
->cache_clean_interval
* 1000);
826 static void cache_clean_timer_init(BlockDriverState
*bs
, AioContext
*context
)
828 BDRVQcow2State
*s
= bs
->opaque
;
829 if (s
->cache_clean_interval
> 0) {
830 s
->cache_clean_timer
= aio_timer_new(context
, QEMU_CLOCK_VIRTUAL
,
831 SCALE_MS
, cache_clean_timer_cb
,
833 timer_mod(s
->cache_clean_timer
, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL
) +
834 (int64_t) s
->cache_clean_interval
* 1000);
838 static void cache_clean_timer_del(BlockDriverState
*bs
)
840 BDRVQcow2State
*s
= bs
->opaque
;
841 if (s
->cache_clean_timer
) {
842 timer_del(s
->cache_clean_timer
);
843 timer_free(s
->cache_clean_timer
);
844 s
->cache_clean_timer
= NULL
;
848 static void qcow2_detach_aio_context(BlockDriverState
*bs
)
850 cache_clean_timer_del(bs
);
853 static void qcow2_attach_aio_context(BlockDriverState
*bs
,
854 AioContext
*new_context
)
856 cache_clean_timer_init(bs
, new_context
);
859 static void read_cache_sizes(BlockDriverState
*bs
, QemuOpts
*opts
,
860 uint64_t *l2_cache_size
,
861 uint64_t *l2_cache_entry_size
,
862 uint64_t *refcount_cache_size
, Error
**errp
)
864 BDRVQcow2State
*s
= bs
->opaque
;
865 uint64_t combined_cache_size
, l2_cache_max_setting
;
866 bool l2_cache_size_set
, refcount_cache_size_set
, combined_cache_size_set
;
867 bool l2_cache_entry_size_set
;
868 int min_refcount_cache
= MIN_REFCOUNT_CACHE_SIZE
* s
->cluster_size
;
869 uint64_t virtual_disk_size
= bs
->total_sectors
* BDRV_SECTOR_SIZE
;
870 uint64_t max_l2_entries
= DIV_ROUND_UP(virtual_disk_size
, s
->cluster_size
);
871 /* An L2 table is always one cluster in size so the max cache size
872 * should be a multiple of the cluster size. */
873 uint64_t max_l2_cache
= ROUND_UP(max_l2_entries
* sizeof(uint64_t),
876 combined_cache_size_set
= qemu_opt_get(opts
, QCOW2_OPT_CACHE_SIZE
);
877 l2_cache_size_set
= qemu_opt_get(opts
, QCOW2_OPT_L2_CACHE_SIZE
);
878 refcount_cache_size_set
= qemu_opt_get(opts
, QCOW2_OPT_REFCOUNT_CACHE_SIZE
);
879 l2_cache_entry_size_set
= qemu_opt_get(opts
, QCOW2_OPT_L2_CACHE_ENTRY_SIZE
);
881 combined_cache_size
= qemu_opt_get_size(opts
, QCOW2_OPT_CACHE_SIZE
, 0);
882 l2_cache_max_setting
= qemu_opt_get_size(opts
, QCOW2_OPT_L2_CACHE_SIZE
,
883 DEFAULT_L2_CACHE_MAX_SIZE
);
884 *refcount_cache_size
= qemu_opt_get_size(opts
,
885 QCOW2_OPT_REFCOUNT_CACHE_SIZE
, 0);
887 *l2_cache_entry_size
= qemu_opt_get_size(
888 opts
, QCOW2_OPT_L2_CACHE_ENTRY_SIZE
, s
->cluster_size
);
890 *l2_cache_size
= MIN(max_l2_cache
, l2_cache_max_setting
);
892 if (combined_cache_size_set
) {
893 if (l2_cache_size_set
&& refcount_cache_size_set
) {
894 error_setg(errp
, QCOW2_OPT_CACHE_SIZE
", " QCOW2_OPT_L2_CACHE_SIZE
895 " and " QCOW2_OPT_REFCOUNT_CACHE_SIZE
" may not be set "
898 } else if (l2_cache_size_set
&&
899 (l2_cache_max_setting
> combined_cache_size
)) {
900 error_setg(errp
, QCOW2_OPT_L2_CACHE_SIZE
" may not exceed "
901 QCOW2_OPT_CACHE_SIZE
);
903 } else if (*refcount_cache_size
> combined_cache_size
) {
904 error_setg(errp
, QCOW2_OPT_REFCOUNT_CACHE_SIZE
" may not exceed "
905 QCOW2_OPT_CACHE_SIZE
);
909 if (l2_cache_size_set
) {
910 *refcount_cache_size
= combined_cache_size
- *l2_cache_size
;
911 } else if (refcount_cache_size_set
) {
912 *l2_cache_size
= combined_cache_size
- *refcount_cache_size
;
914 /* Assign as much memory as possible to the L2 cache, and
915 * use the remainder for the refcount cache */
916 if (combined_cache_size
>= max_l2_cache
+ min_refcount_cache
) {
917 *l2_cache_size
= max_l2_cache
;
918 *refcount_cache_size
= combined_cache_size
- *l2_cache_size
;
920 *refcount_cache_size
=
921 MIN(combined_cache_size
, min_refcount_cache
);
922 *l2_cache_size
= combined_cache_size
- *refcount_cache_size
;
928 * If the L2 cache is not enough to cover the whole disk then
929 * default to 4KB entries. Smaller entries reduce the cost of
930 * loads and evictions and increase I/O performance.
932 if (*l2_cache_size
< max_l2_cache
&& !l2_cache_entry_size_set
) {
933 *l2_cache_entry_size
= MIN(s
->cluster_size
, 4096);
936 /* l2_cache_size and refcount_cache_size are ensured to have at least
937 * their minimum values in qcow2_update_options_prepare() */
939 if (*l2_cache_entry_size
< (1 << MIN_CLUSTER_BITS
) ||
940 *l2_cache_entry_size
> s
->cluster_size
||
941 !is_power_of_2(*l2_cache_entry_size
)) {
942 error_setg(errp
, "L2 cache entry size must be a power of two "
943 "between %d and the cluster size (%d)",
944 1 << MIN_CLUSTER_BITS
, s
->cluster_size
);
949 typedef struct Qcow2ReopenState
{
950 Qcow2Cache
*l2_table_cache
;
951 Qcow2Cache
*refcount_block_cache
;
952 int l2_slice_size
; /* Number of entries in a slice of the L2 table */
953 bool use_lazy_refcounts
;
955 bool discard_passthrough
[QCOW2_DISCARD_MAX
];
956 uint64_t cache_clean_interval
;
957 QCryptoBlockOpenOptions
*crypto_opts
; /* Disk encryption runtime options */
960 static int qcow2_update_options_prepare(BlockDriverState
*bs
,
962 QDict
*options
, int flags
,
965 BDRVQcow2State
*s
= bs
->opaque
;
966 QemuOpts
*opts
= NULL
;
967 const char *opt_overlap_check
, *opt_overlap_check_template
;
968 int overlap_check_template
= 0;
969 uint64_t l2_cache_size
, l2_cache_entry_size
, refcount_cache_size
;
971 const char *encryptfmt
;
972 QDict
*encryptopts
= NULL
;
973 Error
*local_err
= NULL
;
976 qdict_extract_subqdict(options
, &encryptopts
, "encrypt.");
977 encryptfmt
= qdict_get_try_str(encryptopts
, "format");
979 opts
= qemu_opts_create(&qcow2_runtime_opts
, NULL
, 0, &error_abort
);
980 qemu_opts_absorb_qdict(opts
, options
, &local_err
);
982 error_propagate(errp
, local_err
);
987 /* get L2 table/refcount block cache size from command line options */
988 read_cache_sizes(bs
, opts
, &l2_cache_size
, &l2_cache_entry_size
,
989 &refcount_cache_size
, &local_err
);
991 error_propagate(errp
, local_err
);
996 l2_cache_size
/= l2_cache_entry_size
;
997 if (l2_cache_size
< MIN_L2_CACHE_SIZE
) {
998 l2_cache_size
= MIN_L2_CACHE_SIZE
;
1000 if (l2_cache_size
> INT_MAX
) {
1001 error_setg(errp
, "L2 cache size too big");
1006 refcount_cache_size
/= s
->cluster_size
;
1007 if (refcount_cache_size
< MIN_REFCOUNT_CACHE_SIZE
) {
1008 refcount_cache_size
= MIN_REFCOUNT_CACHE_SIZE
;
1010 if (refcount_cache_size
> INT_MAX
) {
1011 error_setg(errp
, "Refcount cache size too big");
1016 /* alloc new L2 table/refcount block cache, flush old one */
1017 if (s
->l2_table_cache
) {
1018 ret
= qcow2_cache_flush(bs
, s
->l2_table_cache
);
1020 error_setg_errno(errp
, -ret
, "Failed to flush the L2 table cache");
1025 if (s
->refcount_block_cache
) {
1026 ret
= qcow2_cache_flush(bs
, s
->refcount_block_cache
);
1028 error_setg_errno(errp
, -ret
,
1029 "Failed to flush the refcount block cache");
1034 r
->l2_slice_size
= l2_cache_entry_size
/ sizeof(uint64_t);
1035 r
->l2_table_cache
= qcow2_cache_create(bs
, l2_cache_size
,
1036 l2_cache_entry_size
);
1037 r
->refcount_block_cache
= qcow2_cache_create(bs
, refcount_cache_size
,
1039 if (r
->l2_table_cache
== NULL
|| r
->refcount_block_cache
== NULL
) {
1040 error_setg(errp
, "Could not allocate metadata caches");
1045 /* New interval for cache cleanup timer */
1046 r
->cache_clean_interval
=
1047 qemu_opt_get_number(opts
, QCOW2_OPT_CACHE_CLEAN_INTERVAL
,
1048 DEFAULT_CACHE_CLEAN_INTERVAL
);
1049 #ifndef CONFIG_LINUX
1050 if (r
->cache_clean_interval
!= 0) {
1051 error_setg(errp
, QCOW2_OPT_CACHE_CLEAN_INTERVAL
1052 " not supported on this host");
1057 if (r
->cache_clean_interval
> UINT_MAX
) {
1058 error_setg(errp
, "Cache clean interval too big");
1063 /* lazy-refcounts; flush if going from enabled to disabled */
1064 r
->use_lazy_refcounts
= qemu_opt_get_bool(opts
, QCOW2_OPT_LAZY_REFCOUNTS
,
1065 (s
->compatible_features
& QCOW2_COMPAT_LAZY_REFCOUNTS
));
1066 if (r
->use_lazy_refcounts
&& s
->qcow_version
< 3) {
1067 error_setg(errp
, "Lazy refcounts require a qcow2 image with at least "
1068 "qemu 1.1 compatibility level");
1073 if (s
->use_lazy_refcounts
&& !r
->use_lazy_refcounts
) {
1074 ret
= qcow2_mark_clean(bs
);
1076 error_setg_errno(errp
, -ret
, "Failed to disable lazy refcounts");
1081 /* Overlap check options */
1082 opt_overlap_check
= qemu_opt_get(opts
, QCOW2_OPT_OVERLAP
);
1083 opt_overlap_check_template
= qemu_opt_get(opts
, QCOW2_OPT_OVERLAP_TEMPLATE
);
1084 if (opt_overlap_check_template
&& opt_overlap_check
&&
1085 strcmp(opt_overlap_check_template
, opt_overlap_check
))
1087 error_setg(errp
, "Conflicting values for qcow2 options '"
1088 QCOW2_OPT_OVERLAP
"' ('%s') and '" QCOW2_OPT_OVERLAP_TEMPLATE
1089 "' ('%s')", opt_overlap_check
, opt_overlap_check_template
);
1093 if (!opt_overlap_check
) {
1094 opt_overlap_check
= opt_overlap_check_template
?: "cached";
1097 if (!strcmp(opt_overlap_check
, "none")) {
1098 overlap_check_template
= 0;
1099 } else if (!strcmp(opt_overlap_check
, "constant")) {
1100 overlap_check_template
= QCOW2_OL_CONSTANT
;
1101 } else if (!strcmp(opt_overlap_check
, "cached")) {
1102 overlap_check_template
= QCOW2_OL_CACHED
;
1103 } else if (!strcmp(opt_overlap_check
, "all")) {
1104 overlap_check_template
= QCOW2_OL_ALL
;
1106 error_setg(errp
, "Unsupported value '%s' for qcow2 option "
1107 "'overlap-check'. Allowed are any of the following: "
1108 "none, constant, cached, all", opt_overlap_check
);
1113 r
->overlap_check
= 0;
1114 for (i
= 0; i
< QCOW2_OL_MAX_BITNR
; i
++) {
1115 /* overlap-check defines a template bitmask, but every flag may be
1116 * overwritten through the associated boolean option */
1118 qemu_opt_get_bool(opts
, overlap_bool_option_names
[i
],
1119 overlap_check_template
& (1 << i
)) << i
;
1122 r
->discard_passthrough
[QCOW2_DISCARD_NEVER
] = false;
1123 r
->discard_passthrough
[QCOW2_DISCARD_ALWAYS
] = true;
1124 r
->discard_passthrough
[QCOW2_DISCARD_REQUEST
] =
1125 qemu_opt_get_bool(opts
, QCOW2_OPT_DISCARD_REQUEST
,
1126 flags
& BDRV_O_UNMAP
);
1127 r
->discard_passthrough
[QCOW2_DISCARD_SNAPSHOT
] =
1128 qemu_opt_get_bool(opts
, QCOW2_OPT_DISCARD_SNAPSHOT
, true);
1129 r
->discard_passthrough
[QCOW2_DISCARD_OTHER
] =
1130 qemu_opt_get_bool(opts
, QCOW2_OPT_DISCARD_OTHER
, false);
1132 switch (s
->crypt_method_header
) {
1133 case QCOW_CRYPT_NONE
:
1135 error_setg(errp
, "No encryption in image header, but options "
1136 "specified format '%s'", encryptfmt
);
1142 case QCOW_CRYPT_AES
:
1143 if (encryptfmt
&& !g_str_equal(encryptfmt
, "aes")) {
1145 "Header reported 'aes' encryption format but "
1146 "options specify '%s'", encryptfmt
);
1150 qdict_put_str(encryptopts
, "format", "qcow");
1151 r
->crypto_opts
= block_crypto_open_opts_init(encryptopts
, errp
);
1154 case QCOW_CRYPT_LUKS
:
1155 if (encryptfmt
&& !g_str_equal(encryptfmt
, "luks")) {
1157 "Header reported 'luks' encryption format but "
1158 "options specify '%s'", encryptfmt
);
1162 qdict_put_str(encryptopts
, "format", "luks");
1163 r
->crypto_opts
= block_crypto_open_opts_init(encryptopts
, errp
);
1167 error_setg(errp
, "Unsupported encryption method %d",
1168 s
->crypt_method_header
);
1171 if (s
->crypt_method_header
!= QCOW_CRYPT_NONE
&& !r
->crypto_opts
) {
1178 qobject_unref(encryptopts
);
1179 qemu_opts_del(opts
);
1184 static void qcow2_update_options_commit(BlockDriverState
*bs
,
1185 Qcow2ReopenState
*r
)
1187 BDRVQcow2State
*s
= bs
->opaque
;
1190 if (s
->l2_table_cache
) {
1191 qcow2_cache_destroy(s
->l2_table_cache
);
1193 if (s
->refcount_block_cache
) {
1194 qcow2_cache_destroy(s
->refcount_block_cache
);
1196 s
->l2_table_cache
= r
->l2_table_cache
;
1197 s
->refcount_block_cache
= r
->refcount_block_cache
;
1198 s
->l2_slice_size
= r
->l2_slice_size
;
1200 s
->overlap_check
= r
->overlap_check
;
1201 s
->use_lazy_refcounts
= r
->use_lazy_refcounts
;
1203 for (i
= 0; i
< QCOW2_DISCARD_MAX
; i
++) {
1204 s
->discard_passthrough
[i
] = r
->discard_passthrough
[i
];
1207 if (s
->cache_clean_interval
!= r
->cache_clean_interval
) {
1208 cache_clean_timer_del(bs
);
1209 s
->cache_clean_interval
= r
->cache_clean_interval
;
1210 cache_clean_timer_init(bs
, bdrv_get_aio_context(bs
));
1213 qapi_free_QCryptoBlockOpenOptions(s
->crypto_opts
);
1214 s
->crypto_opts
= r
->crypto_opts
;
1217 static void qcow2_update_options_abort(BlockDriverState
*bs
,
1218 Qcow2ReopenState
*r
)
1220 if (r
->l2_table_cache
) {
1221 qcow2_cache_destroy(r
->l2_table_cache
);
1223 if (r
->refcount_block_cache
) {
1224 qcow2_cache_destroy(r
->refcount_block_cache
);
1226 qapi_free_QCryptoBlockOpenOptions(r
->crypto_opts
);
1229 static int qcow2_update_options(BlockDriverState
*bs
, QDict
*options
,
1230 int flags
, Error
**errp
)
1232 Qcow2ReopenState r
= {};
1235 ret
= qcow2_update_options_prepare(bs
, &r
, options
, flags
, errp
);
1237 qcow2_update_options_commit(bs
, &r
);
1239 qcow2_update_options_abort(bs
, &r
);
1245 /* Called with s->lock held. */
1246 static int coroutine_fn
qcow2_do_open(BlockDriverState
*bs
, QDict
*options
,
1247 int flags
, Error
**errp
)
1249 BDRVQcow2State
*s
= bs
->opaque
;
1250 unsigned int len
, i
;
1253 Error
*local_err
= NULL
;
1255 uint64_t l1_vm_state_index
;
1256 bool update_header
= false;
1258 ret
= bdrv_pread(bs
->file
, 0, &header
, sizeof(header
));
1260 error_setg_errno(errp
, -ret
, "Could not read qcow2 header");
1263 header
.magic
= be32_to_cpu(header
.magic
);
1264 header
.version
= be32_to_cpu(header
.version
);
1265 header
.backing_file_offset
= be64_to_cpu(header
.backing_file_offset
);
1266 header
.backing_file_size
= be32_to_cpu(header
.backing_file_size
);
1267 header
.size
= be64_to_cpu(header
.size
);
1268 header
.cluster_bits
= be32_to_cpu(header
.cluster_bits
);
1269 header
.crypt_method
= be32_to_cpu(header
.crypt_method
);
1270 header
.l1_table_offset
= be64_to_cpu(header
.l1_table_offset
);
1271 header
.l1_size
= be32_to_cpu(header
.l1_size
);
1272 header
.refcount_table_offset
= be64_to_cpu(header
.refcount_table_offset
);
1273 header
.refcount_table_clusters
=
1274 be32_to_cpu(header
.refcount_table_clusters
);
1275 header
.snapshots_offset
= be64_to_cpu(header
.snapshots_offset
);
1276 header
.nb_snapshots
= be32_to_cpu(header
.nb_snapshots
);
1278 if (header
.magic
!= QCOW_MAGIC
) {
1279 error_setg(errp
, "Image is not in qcow2 format");
1283 if (header
.version
< 2 || header
.version
> 3) {
1284 error_setg(errp
, "Unsupported qcow2 version %" PRIu32
, header
.version
);
1289 s
->qcow_version
= header
.version
;
1291 /* Initialise cluster size */
1292 if (header
.cluster_bits
< MIN_CLUSTER_BITS
||
1293 header
.cluster_bits
> MAX_CLUSTER_BITS
) {
1294 error_setg(errp
, "Unsupported cluster size: 2^%" PRIu32
,
1295 header
.cluster_bits
);
1300 s
->cluster_bits
= header
.cluster_bits
;
1301 s
->cluster_size
= 1 << s
->cluster_bits
;
1303 /* Initialise version 3 header fields */
1304 if (header
.version
== 2) {
1305 header
.incompatible_features
= 0;
1306 header
.compatible_features
= 0;
1307 header
.autoclear_features
= 0;
1308 header
.refcount_order
= 4;
1309 header
.header_length
= 72;
1311 header
.incompatible_features
=
1312 be64_to_cpu(header
.incompatible_features
);
1313 header
.compatible_features
= be64_to_cpu(header
.compatible_features
);
1314 header
.autoclear_features
= be64_to_cpu(header
.autoclear_features
);
1315 header
.refcount_order
= be32_to_cpu(header
.refcount_order
);
1316 header
.header_length
= be32_to_cpu(header
.header_length
);
1318 if (header
.header_length
< 104) {
1319 error_setg(errp
, "qcow2 header too short");
1325 if (header
.header_length
> s
->cluster_size
) {
1326 error_setg(errp
, "qcow2 header exceeds cluster size");
1331 if (header
.header_length
> sizeof(header
)) {
1332 s
->unknown_header_fields_size
= header
.header_length
- sizeof(header
);
1333 s
->unknown_header_fields
= g_malloc(s
->unknown_header_fields_size
);
1334 ret
= bdrv_pread(bs
->file
, sizeof(header
), s
->unknown_header_fields
,
1335 s
->unknown_header_fields_size
);
1337 error_setg_errno(errp
, -ret
, "Could not read unknown qcow2 header "
1343 if (header
.backing_file_offset
> s
->cluster_size
) {
1344 error_setg(errp
, "Invalid backing file offset");
1349 if (header
.backing_file_offset
) {
1350 ext_end
= header
.backing_file_offset
;
1352 ext_end
= 1 << header
.cluster_bits
;
1355 /* Handle feature bits */
1356 s
->incompatible_features
= header
.incompatible_features
;
1357 s
->compatible_features
= header
.compatible_features
;
1358 s
->autoclear_features
= header
.autoclear_features
;
1360 if (s
->incompatible_features
& ~QCOW2_INCOMPAT_MASK
) {
1361 void *feature_table
= NULL
;
1362 qcow2_read_extensions(bs
, header
.header_length
, ext_end
,
1363 &feature_table
, flags
, NULL
, NULL
);
1364 report_unsupported_feature(errp
, feature_table
,
1365 s
->incompatible_features
&
1366 ~QCOW2_INCOMPAT_MASK
);
1368 g_free(feature_table
);
1372 if (s
->incompatible_features
& QCOW2_INCOMPAT_CORRUPT
) {
1373 /* Corrupt images may not be written to unless they are being repaired
1375 if ((flags
& BDRV_O_RDWR
) && !(flags
& BDRV_O_CHECK
)) {
1376 error_setg(errp
, "qcow2: Image is corrupt; cannot be opened "
1383 /* Check support for various header values */
1384 if (header
.refcount_order
> 6) {
1385 error_setg(errp
, "Reference count entry width too large; may not "
1390 s
->refcount_order
= header
.refcount_order
;
1391 s
->refcount_bits
= 1 << s
->refcount_order
;
1392 s
->refcount_max
= UINT64_C(1) << (s
->refcount_bits
- 1);
1393 s
->refcount_max
+= s
->refcount_max
- 1;
1395 s
->crypt_method_header
= header
.crypt_method
;
1396 if (s
->crypt_method_header
) {
1397 if (bdrv_uses_whitelist() &&
1398 s
->crypt_method_header
== QCOW_CRYPT_AES
) {
1400 "Use of AES-CBC encrypted qcow2 images is no longer "
1401 "supported in system emulators");
1402 error_append_hint(errp
,
1403 "You can use 'qemu-img convert' to convert your "
1404 "image to an alternative supported format, such "
1405 "as unencrypted qcow2, or raw with the LUKS "
1406 "format instead.\n");
1411 if (s
->crypt_method_header
== QCOW_CRYPT_AES
) {
1412 s
->crypt_physical_offset
= false;
1414 /* Assuming LUKS and any future crypt methods we
1415 * add will all use physical offsets, due to the
1416 * fact that the alternative is insecure... */
1417 s
->crypt_physical_offset
= true;
1420 bs
->encrypted
= true;
1423 s
->l2_bits
= s
->cluster_bits
- 3; /* L2 is always one cluster */
1424 s
->l2_size
= 1 << s
->l2_bits
;
1425 /* 2^(s->refcount_order - 3) is the refcount width in bytes */
1426 s
->refcount_block_bits
= s
->cluster_bits
- (s
->refcount_order
- 3);
1427 s
->refcount_block_size
= 1 << s
->refcount_block_bits
;
1428 bs
->total_sectors
= header
.size
/ BDRV_SECTOR_SIZE
;
1429 s
->csize_shift
= (62 - (s
->cluster_bits
- 8));
1430 s
->csize_mask
= (1 << (s
->cluster_bits
- 8)) - 1;
1431 s
->cluster_offset_mask
= (1LL << s
->csize_shift
) - 1;
1433 s
->refcount_table_offset
= header
.refcount_table_offset
;
1434 s
->refcount_table_size
=
1435 header
.refcount_table_clusters
<< (s
->cluster_bits
- 3);
1437 if (header
.refcount_table_clusters
== 0 && !(flags
& BDRV_O_CHECK
)) {
1438 error_setg(errp
, "Image does not contain a reference count table");
1443 ret
= qcow2_validate_table(bs
, s
->refcount_table_offset
,
1444 header
.refcount_table_clusters
,
1445 s
->cluster_size
, QCOW_MAX_REFTABLE_SIZE
,
1446 "Reference count table", errp
);
1451 if (!(flags
& BDRV_O_CHECK
)) {
1453 * The total size in bytes of the snapshot table is checked in
1454 * qcow2_read_snapshots() because the size of each snapshot is
1455 * variable and we don't know it yet.
1456 * Here we only check the offset and number of snapshots.
1458 ret
= qcow2_validate_table(bs
, header
.snapshots_offset
,
1459 header
.nb_snapshots
,
1460 sizeof(QCowSnapshotHeader
),
1461 sizeof(QCowSnapshotHeader
) *
1463 "Snapshot table", errp
);
1469 /* read the level 1 table */
1470 ret
= qcow2_validate_table(bs
, header
.l1_table_offset
,
1471 header
.l1_size
, sizeof(uint64_t),
1472 QCOW_MAX_L1_SIZE
, "Active L1 table", errp
);
1476 s
->l1_size
= header
.l1_size
;
1477 s
->l1_table_offset
= header
.l1_table_offset
;
1479 l1_vm_state_index
= size_to_l1(s
, header
.size
);
1480 if (l1_vm_state_index
> INT_MAX
) {
1481 error_setg(errp
, "Image is too big");
1485 s
->l1_vm_state_index
= l1_vm_state_index
;
1487 /* the L1 table must contain at least enough entries to put
1488 header.size bytes */
1489 if (s
->l1_size
< s
->l1_vm_state_index
) {
1490 error_setg(errp
, "L1 table is too small");
1495 if (s
->l1_size
> 0) {
1496 s
->l1_table
= qemu_try_blockalign(bs
->file
->bs
,
1497 s
->l1_size
* sizeof(uint64_t));
1498 if (s
->l1_table
== NULL
) {
1499 error_setg(errp
, "Could not allocate L1 table");
1503 ret
= bdrv_pread(bs
->file
, s
->l1_table_offset
, s
->l1_table
,
1504 s
->l1_size
* sizeof(uint64_t));
1506 error_setg_errno(errp
, -ret
, "Could not read L1 table");
1509 for(i
= 0;i
< s
->l1_size
; i
++) {
1510 s
->l1_table
[i
] = be64_to_cpu(s
->l1_table
[i
]);
1514 /* Parse driver-specific options */
1515 ret
= qcow2_update_options(bs
, options
, flags
, errp
);
1522 ret
= qcow2_refcount_init(bs
);
1524 error_setg_errno(errp
, -ret
, "Could not initialize refcount handling");
1528 QLIST_INIT(&s
->cluster_allocs
);
1529 QTAILQ_INIT(&s
->discards
);
1531 /* read qcow2 extensions */
1532 if (qcow2_read_extensions(bs
, header
.header_length
, ext_end
, NULL
,
1533 flags
, &update_header
, &local_err
)) {
1534 error_propagate(errp
, local_err
);
1539 /* Open external data file */
1540 s
->data_file
= bdrv_open_child(NULL
, options
, "data-file", bs
, &child_file
,
1543 error_propagate(errp
, local_err
);
1548 if (s
->incompatible_features
& QCOW2_INCOMPAT_DATA_FILE
) {
1549 if (!s
->data_file
&& s
->image_data_file
) {
1550 s
->data_file
= bdrv_open_child(s
->image_data_file
, options
,
1551 "data-file", bs
, &child_file
,
1553 if (!s
->data_file
) {
1558 if (!s
->data_file
) {
1559 error_setg(errp
, "'data-file' is required for this image");
1565 error_setg(errp
, "'data-file' can only be set for images with an "
1566 "external data file");
1571 s
->data_file
= bs
->file
;
1573 if (data_file_is_raw(bs
)) {
1574 error_setg(errp
, "data-file-raw requires a data file");
1580 /* qcow2_read_extension may have set up the crypto context
1581 * if the crypt method needs a header region, some methods
1582 * don't need header extensions, so must check here
1584 if (s
->crypt_method_header
&& !s
->crypto
) {
1585 if (s
->crypt_method_header
== QCOW_CRYPT_AES
) {
1586 unsigned int cflags
= 0;
1587 if (flags
& BDRV_O_NO_IO
) {
1588 cflags
|= QCRYPTO_BLOCK_OPEN_NO_IO
;
1590 s
->crypto
= qcrypto_block_open(s
->crypto_opts
, "encrypt.",
1592 QCOW2_MAX_THREADS
, errp
);
1597 } else if (!(flags
& BDRV_O_NO_IO
)) {
1598 error_setg(errp
, "Missing CRYPTO header for crypt method %d",
1599 s
->crypt_method_header
);
1605 /* read the backing file name */
1606 if (header
.backing_file_offset
!= 0) {
1607 len
= header
.backing_file_size
;
1608 if (len
> MIN(1023, s
->cluster_size
- header
.backing_file_offset
) ||
1609 len
>= sizeof(bs
->backing_file
)) {
1610 error_setg(errp
, "Backing file name too long");
1614 ret
= bdrv_pread(bs
->file
, header
.backing_file_offset
,
1615 bs
->auto_backing_file
, len
);
1617 error_setg_errno(errp
, -ret
, "Could not read backing file name");
1620 bs
->auto_backing_file
[len
] = '\0';
1621 pstrcpy(bs
->backing_file
, sizeof(bs
->backing_file
),
1622 bs
->auto_backing_file
);
1623 s
->image_backing_file
= g_strdup(bs
->auto_backing_file
);
1627 * Internal snapshots; skip reading them in check mode, because
1628 * we do not need them then, and we do not want to abort because
1629 * of a broken table.
1631 if (!(flags
& BDRV_O_CHECK
)) {
1632 s
->snapshots_offset
= header
.snapshots_offset
;
1633 s
->nb_snapshots
= header
.nb_snapshots
;
1635 ret
= qcow2_read_snapshots(bs
, errp
);
1641 /* Clear unknown autoclear feature bits */
1642 update_header
|= s
->autoclear_features
& ~QCOW2_AUTOCLEAR_MASK
;
1644 update_header
&& !bs
->read_only
&& !(flags
& BDRV_O_INACTIVE
);
1645 if (update_header
) {
1646 s
->autoclear_features
&= QCOW2_AUTOCLEAR_MASK
;
1649 /* == Handle persistent dirty bitmaps ==
1651 * We want load dirty bitmaps in three cases:
1653 * 1. Normal open of the disk in active mode, not related to invalidation
1656 * 2. Invalidation of the target vm after pre-copy phase of migration, if
1657 * bitmaps are _not_ migrating through migration channel, i.e.
1658 * 'dirty-bitmaps' capability is disabled.
1660 * 3. Invalidation of source vm after failed or canceled migration.
1661 * This is a very interesting case. There are two possible types of
1664 * A. Stored on inactivation and removed. They should be loaded from the
1667 * B. Not stored: not-persistent bitmaps and bitmaps, migrated through
1668 * the migration channel (with dirty-bitmaps capability).
1670 * On the other hand, there are two possible sub-cases:
1672 * 3.1 disk was changed by somebody else while were inactive. In this
1673 * case all in-RAM dirty bitmaps (both persistent and not) are
1674 * definitely invalid. And we don't have any method to determine
1677 * Simple and safe thing is to just drop all the bitmaps of type B on
1678 * inactivation. But in this case we lose bitmaps in valid 4.2 case.
1680 * On the other hand, resuming source vm, if disk was already changed
1681 * is a bad thing anyway: not only bitmaps, the whole vm state is
1682 * out of sync with disk.
1684 * This means, that user or management tool, who for some reason
1685 * decided to resume source vm, after disk was already changed by
1686 * target vm, should at least drop all dirty bitmaps by hand.
1688 * So, we can ignore this case for now, but TODO: "generation"
1689 * extension for qcow2, to determine, that image was changed after
1690 * last inactivation. And if it is changed, we will drop (or at least
1691 * mark as 'invalid' all the bitmaps of type B, both persistent
1694 * 3.2 disk was _not_ changed while were inactive. Bitmaps may be saved
1695 * to disk ('dirty-bitmaps' capability disabled), or not saved
1696 * ('dirty-bitmaps' capability enabled), but we don't need to care
1697 * of: let's load bitmaps as always: stored bitmaps will be loaded,
1698 * and not stored has flag IN_USE=1 in the image and will be skipped
1701 * One remaining possible case when we don't want load bitmaps:
1703 * 4. Open disk in inactive mode in target vm (bitmaps are migrating or
1704 * will be loaded on invalidation, no needs try loading them before)
1707 if (!(bdrv_get_flags(bs
) & BDRV_O_INACTIVE
)) {
1708 /* It's case 1, 2 or 3.2. Or 3.1 which is BUG in management layer. */
1709 bool header_updated
= qcow2_load_dirty_bitmaps(bs
, &local_err
);
1710 if (local_err
!= NULL
) {
1711 error_propagate(errp
, local_err
);
1716 update_header
= update_header
&& !header_updated
;
1719 if (update_header
) {
1720 ret
= qcow2_update_header(bs
);
1722 error_setg_errno(errp
, -ret
, "Could not update qcow2 header");
1727 bs
->supported_zero_flags
= header
.version
>= 3 ?
1728 BDRV_REQ_MAY_UNMAP
| BDRV_REQ_NO_FALLBACK
: 0;
1730 /* Repair image if dirty */
1731 if (!(flags
& (BDRV_O_CHECK
| BDRV_O_INACTIVE
)) && !bs
->read_only
&&
1732 (s
->incompatible_features
& QCOW2_INCOMPAT_DIRTY
)) {
1733 BdrvCheckResult result
= {0};
1735 ret
= qcow2_co_check_locked(bs
, &result
,
1736 BDRV_FIX_ERRORS
| BDRV_FIX_LEAKS
);
1737 if (ret
< 0 || result
.check_errors
) {
1741 error_setg_errno(errp
, -ret
, "Could not repair dirty image");
1748 BdrvCheckResult result
= {0};
1749 qcow2_check_refcounts(bs
, &result
, 0);
1753 qemu_co_queue_init(&s
->thread_task_queue
);
1758 g_free(s
->image_data_file
);
1759 if (has_data_file(bs
)) {
1760 bdrv_unref_child(bs
, s
->data_file
);
1762 g_free(s
->unknown_header_fields
);
1763 cleanup_unknown_header_ext(bs
);
1764 qcow2_free_snapshots(bs
);
1765 qcow2_refcount_close(bs
);
1766 qemu_vfree(s
->l1_table
);
1767 /* else pre-write overlap checks in cache_destroy may crash */
1769 cache_clean_timer_del(bs
);
1770 if (s
->l2_table_cache
) {
1771 qcow2_cache_destroy(s
->l2_table_cache
);
1773 if (s
->refcount_block_cache
) {
1774 qcow2_cache_destroy(s
->refcount_block_cache
);
1776 qcrypto_block_free(s
->crypto
);
1777 qapi_free_QCryptoBlockOpenOptions(s
->crypto_opts
);
1781 typedef struct QCow2OpenCo
{
1782 BlockDriverState
*bs
;
1789 static void coroutine_fn
qcow2_open_entry(void *opaque
)
1791 QCow2OpenCo
*qoc
= opaque
;
1792 BDRVQcow2State
*s
= qoc
->bs
->opaque
;
1794 qemu_co_mutex_lock(&s
->lock
);
1795 qoc
->ret
= qcow2_do_open(qoc
->bs
, qoc
->options
, qoc
->flags
, qoc
->errp
);
1796 qemu_co_mutex_unlock(&s
->lock
);
1799 static int qcow2_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
1802 BDRVQcow2State
*s
= bs
->opaque
;
1811 bs
->file
= bdrv_open_child(NULL
, options
, "file", bs
, &child_file
,
1817 /* Initialise locks */
1818 qemu_co_mutex_init(&s
->lock
);
1820 if (qemu_in_coroutine()) {
1821 /* From bdrv_co_create. */
1822 qcow2_open_entry(&qoc
);
1824 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
1825 qemu_coroutine_enter(qemu_coroutine_create(qcow2_open_entry
, &qoc
));
1826 BDRV_POLL_WHILE(bs
, qoc
.ret
== -EINPROGRESS
);
1831 static void qcow2_refresh_limits(BlockDriverState
*bs
, Error
**errp
)
1833 BDRVQcow2State
*s
= bs
->opaque
;
1835 if (bs
->encrypted
) {
1836 /* Encryption works on a sector granularity */
1837 bs
->bl
.request_alignment
= qcrypto_block_get_sector_size(s
->crypto
);
1839 bs
->bl
.pwrite_zeroes_alignment
= s
->cluster_size
;
1840 bs
->bl
.pdiscard_alignment
= s
->cluster_size
;
1843 static int qcow2_reopen_prepare(BDRVReopenState
*state
,
1844 BlockReopenQueue
*queue
, Error
**errp
)
1846 Qcow2ReopenState
*r
;
1849 r
= g_new0(Qcow2ReopenState
, 1);
1852 ret
= qcow2_update_options_prepare(state
->bs
, r
, state
->options
,
1853 state
->flags
, errp
);
1858 /* We need to write out any unwritten data if we reopen read-only. */
1859 if ((state
->flags
& BDRV_O_RDWR
) == 0) {
1860 ret
= qcow2_reopen_bitmaps_ro(state
->bs
, errp
);
1865 ret
= bdrv_flush(state
->bs
);
1870 ret
= qcow2_mark_clean(state
->bs
);
1879 qcow2_update_options_abort(state
->bs
, r
);
1884 static void qcow2_reopen_commit(BDRVReopenState
*state
)
1886 qcow2_update_options_commit(state
->bs
, state
->opaque
);
1887 g_free(state
->opaque
);
1890 static void qcow2_reopen_commit_post(BDRVReopenState
*state
)
1892 if (state
->flags
& BDRV_O_RDWR
) {
1893 Error
*local_err
= NULL
;
1895 if (qcow2_reopen_bitmaps_rw(state
->bs
, &local_err
) < 0) {
1897 * This is not fatal, bitmaps just left read-only, so all following
1898 * writes will fail. User can remove read-only bitmaps to unblock
1899 * writes or retry reopen.
1901 error_reportf_err(local_err
,
1902 "%s: Failed to make dirty bitmaps writable: ",
1903 bdrv_get_node_name(state
->bs
));
1908 static void qcow2_reopen_abort(BDRVReopenState
*state
)
1910 qcow2_update_options_abort(state
->bs
, state
->opaque
);
1911 g_free(state
->opaque
);
1914 static void qcow2_join_options(QDict
*options
, QDict
*old_options
)
1916 bool has_new_overlap_template
=
1917 qdict_haskey(options
, QCOW2_OPT_OVERLAP
) ||
1918 qdict_haskey(options
, QCOW2_OPT_OVERLAP_TEMPLATE
);
1919 bool has_new_total_cache_size
=
1920 qdict_haskey(options
, QCOW2_OPT_CACHE_SIZE
);
1921 bool has_all_cache_options
;
1923 /* New overlap template overrides all old overlap options */
1924 if (has_new_overlap_template
) {
1925 qdict_del(old_options
, QCOW2_OPT_OVERLAP
);
1926 qdict_del(old_options
, QCOW2_OPT_OVERLAP_TEMPLATE
);
1927 qdict_del(old_options
, QCOW2_OPT_OVERLAP_MAIN_HEADER
);
1928 qdict_del(old_options
, QCOW2_OPT_OVERLAP_ACTIVE_L1
);
1929 qdict_del(old_options
, QCOW2_OPT_OVERLAP_ACTIVE_L2
);
1930 qdict_del(old_options
, QCOW2_OPT_OVERLAP_REFCOUNT_TABLE
);
1931 qdict_del(old_options
, QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK
);
1932 qdict_del(old_options
, QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE
);
1933 qdict_del(old_options
, QCOW2_OPT_OVERLAP_INACTIVE_L1
);
1934 qdict_del(old_options
, QCOW2_OPT_OVERLAP_INACTIVE_L2
);
1937 /* New total cache size overrides all old options */
1938 if (qdict_haskey(options
, QCOW2_OPT_CACHE_SIZE
)) {
1939 qdict_del(old_options
, QCOW2_OPT_L2_CACHE_SIZE
);
1940 qdict_del(old_options
, QCOW2_OPT_REFCOUNT_CACHE_SIZE
);
1943 qdict_join(options
, old_options
, false);
1946 * If after merging all cache size options are set, an old total size is
1947 * overwritten. Do keep all options, however, if all three are new. The
1948 * resulting error message is what we want to happen.
1950 has_all_cache_options
=
1951 qdict_haskey(options
, QCOW2_OPT_CACHE_SIZE
) ||
1952 qdict_haskey(options
, QCOW2_OPT_L2_CACHE_SIZE
) ||
1953 qdict_haskey(options
, QCOW2_OPT_REFCOUNT_CACHE_SIZE
);
1955 if (has_all_cache_options
&& !has_new_total_cache_size
) {
1956 qdict_del(options
, QCOW2_OPT_CACHE_SIZE
);
1960 static int coroutine_fn
qcow2_co_block_status(BlockDriverState
*bs
,
1962 int64_t offset
, int64_t count
,
1963 int64_t *pnum
, int64_t *map
,
1964 BlockDriverState
**file
)
1966 BDRVQcow2State
*s
= bs
->opaque
;
1967 uint64_t cluster_offset
;
1969 int ret
, status
= 0;
1971 qemu_co_mutex_lock(&s
->lock
);
1973 if (!s
->metadata_preallocation_checked
) {
1974 ret
= qcow2_detect_metadata_preallocation(bs
);
1975 s
->metadata_preallocation
= (ret
== 1);
1976 s
->metadata_preallocation_checked
= true;
1979 bytes
= MIN(INT_MAX
, count
);
1980 ret
= qcow2_get_cluster_offset(bs
, offset
, &bytes
, &cluster_offset
);
1981 qemu_co_mutex_unlock(&s
->lock
);
1988 if ((ret
== QCOW2_CLUSTER_NORMAL
|| ret
== QCOW2_CLUSTER_ZERO_ALLOC
) &&
1990 *map
= cluster_offset
| offset_into_cluster(s
, offset
);
1991 *file
= s
->data_file
->bs
;
1992 status
|= BDRV_BLOCK_OFFSET_VALID
;
1994 if (ret
== QCOW2_CLUSTER_ZERO_PLAIN
|| ret
== QCOW2_CLUSTER_ZERO_ALLOC
) {
1995 status
|= BDRV_BLOCK_ZERO
;
1996 } else if (ret
!= QCOW2_CLUSTER_UNALLOCATED
) {
1997 status
|= BDRV_BLOCK_DATA
;
1999 if (s
->metadata_preallocation
&& (status
& BDRV_BLOCK_DATA
) &&
2000 (status
& BDRV_BLOCK_OFFSET_VALID
))
2002 status
|= BDRV_BLOCK_RECURSE
;
2007 static coroutine_fn
int qcow2_handle_l2meta(BlockDriverState
*bs
,
2008 QCowL2Meta
**pl2meta
,
2012 QCowL2Meta
*l2meta
= *pl2meta
;
2014 while (l2meta
!= NULL
) {
2018 ret
= qcow2_alloc_cluster_link_l2(bs
, l2meta
);
2023 qcow2_alloc_cluster_abort(bs
, l2meta
);
2026 /* Take the request off the list of running requests */
2027 if (l2meta
->nb_clusters
!= 0) {
2028 QLIST_REMOVE(l2meta
, next_in_flight
);
2031 qemu_co_queue_restart_all(&l2meta
->dependent_requests
);
2033 next
= l2meta
->next
;
2042 static coroutine_fn
int
2043 qcow2_co_preadv_encrypted(BlockDriverState
*bs
,
2044 uint64_t file_cluster_offset
,
2048 uint64_t qiov_offset
)
2051 BDRVQcow2State
*s
= bs
->opaque
;
2054 assert(bs
->encrypted
&& s
->crypto
);
2055 assert(bytes
<= QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_size
);
2058 * For encrypted images, read everything into a temporary
2059 * contiguous buffer on which the AES functions can work.
2060 * Also, decryption in a separate buffer is better as it
2061 * prevents the guest from learning information about the
2062 * encrypted nature of the virtual disk.
2065 buf
= qemu_try_blockalign(s
->data_file
->bs
, bytes
);
2070 BLKDBG_EVENT(bs
->file
, BLKDBG_READ_AIO
);
2071 ret
= bdrv_co_pread(s
->data_file
,
2072 file_cluster_offset
+ offset_into_cluster(s
, offset
),
2078 if (qcow2_co_decrypt(bs
,
2079 file_cluster_offset
+ offset_into_cluster(s
, offset
),
2080 offset
, buf
, bytes
) < 0)
2085 qemu_iovec_from_buf(qiov
, qiov_offset
, buf
, bytes
);
2093 typedef struct Qcow2AioTask
{
2096 BlockDriverState
*bs
;
2097 QCow2ClusterType cluster_type
; /* only for read */
2098 uint64_t file_cluster_offset
;
2102 uint64_t qiov_offset
;
2103 QCowL2Meta
*l2meta
; /* only for write */
2106 static coroutine_fn
int qcow2_co_preadv_task_entry(AioTask
*task
);
2107 static coroutine_fn
int qcow2_add_task(BlockDriverState
*bs
,
2110 QCow2ClusterType cluster_type
,
2111 uint64_t file_cluster_offset
,
2118 Qcow2AioTask local_task
;
2119 Qcow2AioTask
*task
= pool
? g_new(Qcow2AioTask
, 1) : &local_task
;
2121 *task
= (Qcow2AioTask
) {
2124 .cluster_type
= cluster_type
,
2126 .file_cluster_offset
= file_cluster_offset
,
2129 .qiov_offset
= qiov_offset
,
2133 trace_qcow2_add_task(qemu_coroutine_self(), bs
, pool
,
2134 func
== qcow2_co_preadv_task_entry
? "read" : "write",
2135 cluster_type
, file_cluster_offset
, offset
, bytes
,
2139 return func(&task
->task
);
2142 aio_task_pool_start_task(pool
, &task
->task
);
2147 static coroutine_fn
int qcow2_co_preadv_task(BlockDriverState
*bs
,
2148 QCow2ClusterType cluster_type
,
2149 uint64_t file_cluster_offset
,
2150 uint64_t offset
, uint64_t bytes
,
2154 BDRVQcow2State
*s
= bs
->opaque
;
2155 int offset_in_cluster
= offset_into_cluster(s
, offset
);
2157 switch (cluster_type
) {
2158 case QCOW2_CLUSTER_ZERO_PLAIN
:
2159 case QCOW2_CLUSTER_ZERO_ALLOC
:
2160 /* Both zero types are handled in qcow2_co_preadv_part */
2161 g_assert_not_reached();
2163 case QCOW2_CLUSTER_UNALLOCATED
:
2164 assert(bs
->backing
); /* otherwise handled in qcow2_co_preadv_part */
2166 BLKDBG_EVENT(bs
->file
, BLKDBG_READ_BACKING_AIO
);
2167 return bdrv_co_preadv_part(bs
->backing
, offset
, bytes
,
2168 qiov
, qiov_offset
, 0);
2170 case QCOW2_CLUSTER_COMPRESSED
:
2171 return qcow2_co_preadv_compressed(bs
, file_cluster_offset
,
2172 offset
, bytes
, qiov
, qiov_offset
);
2174 case QCOW2_CLUSTER_NORMAL
:
2175 assert(offset_into_cluster(s
, file_cluster_offset
) == 0);
2176 if (bs
->encrypted
) {
2177 return qcow2_co_preadv_encrypted(bs
, file_cluster_offset
,
2178 offset
, bytes
, qiov
, qiov_offset
);
2181 BLKDBG_EVENT(bs
->file
, BLKDBG_READ_AIO
);
2182 return bdrv_co_preadv_part(s
->data_file
,
2183 file_cluster_offset
+ offset_in_cluster
,
2184 bytes
, qiov
, qiov_offset
, 0);
2187 g_assert_not_reached();
2190 g_assert_not_reached();
2193 static coroutine_fn
int qcow2_co_preadv_task_entry(AioTask
*task
)
2195 Qcow2AioTask
*t
= container_of(task
, Qcow2AioTask
, task
);
2199 return qcow2_co_preadv_task(t
->bs
, t
->cluster_type
, t
->file_cluster_offset
,
2200 t
->offset
, t
->bytes
, t
->qiov
, t
->qiov_offset
);
2203 static coroutine_fn
int qcow2_co_preadv_part(BlockDriverState
*bs
,
2204 uint64_t offset
, uint64_t bytes
,
2206 size_t qiov_offset
, int flags
)
2208 BDRVQcow2State
*s
= bs
->opaque
;
2210 unsigned int cur_bytes
; /* number of bytes in current iteration */
2211 uint64_t cluster_offset
= 0;
2212 AioTaskPool
*aio
= NULL
;
2214 while (bytes
!= 0 && aio_task_pool_status(aio
) == 0) {
2215 /* prepare next request */
2216 cur_bytes
= MIN(bytes
, INT_MAX
);
2218 cur_bytes
= MIN(cur_bytes
,
2219 QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_size
);
2222 qemu_co_mutex_lock(&s
->lock
);
2223 ret
= qcow2_get_cluster_offset(bs
, offset
, &cur_bytes
, &cluster_offset
);
2224 qemu_co_mutex_unlock(&s
->lock
);
2229 if (ret
== QCOW2_CLUSTER_ZERO_PLAIN
||
2230 ret
== QCOW2_CLUSTER_ZERO_ALLOC
||
2231 (ret
== QCOW2_CLUSTER_UNALLOCATED
&& !bs
->backing
))
2233 qemu_iovec_memset(qiov
, qiov_offset
, 0, cur_bytes
);
2235 if (!aio
&& cur_bytes
!= bytes
) {
2236 aio
= aio_task_pool_new(QCOW2_MAX_WORKERS
);
2238 ret
= qcow2_add_task(bs
, aio
, qcow2_co_preadv_task_entry
, ret
,
2239 cluster_offset
, offset
, cur_bytes
,
2240 qiov
, qiov_offset
, NULL
);
2247 offset
+= cur_bytes
;
2248 qiov_offset
+= cur_bytes
;
2253 aio_task_pool_wait_all(aio
);
2255 ret
= aio_task_pool_status(aio
);
2263 /* Check if it's possible to merge a write request with the writing of
2264 * the data from the COW regions */
2265 static bool merge_cow(uint64_t offset
, unsigned bytes
,
2266 QEMUIOVector
*qiov
, size_t qiov_offset
,
2271 for (m
= l2meta
; m
!= NULL
; m
= m
->next
) {
2272 /* If both COW regions are empty then there's nothing to merge */
2273 if (m
->cow_start
.nb_bytes
== 0 && m
->cow_end
.nb_bytes
== 0) {
2277 /* If COW regions are handled already, skip this too */
2282 /* The data (middle) region must be immediately after the
2284 if (l2meta_cow_start(m
) + m
->cow_start
.nb_bytes
!= offset
) {
2288 /* The end region must be immediately after the data (middle)
2290 if (m
->offset
+ m
->cow_end
.offset
!= offset
+ bytes
) {
2294 /* Make sure that adding both COW regions to the QEMUIOVector
2295 * does not exceed IOV_MAX */
2296 if (qemu_iovec_subvec_niov(qiov
, qiov_offset
, bytes
) > IOV_MAX
- 2) {
2300 m
->data_qiov
= qiov
;
2301 m
->data_qiov_offset
= qiov_offset
;
2308 static bool is_unallocated(BlockDriverState
*bs
, int64_t offset
, int64_t bytes
)
2312 (!bdrv_is_allocated_above(bs
, NULL
, false, offset
, bytes
, &nr
) &&
2316 static bool is_zero_cow(BlockDriverState
*bs
, QCowL2Meta
*m
)
2319 * This check is designed for optimization shortcut so it must be
2321 * Instead of is_zero(), use is_unallocated() as it is faster (but not
2322 * as accurate and can result in false negatives).
2324 return is_unallocated(bs
, m
->offset
+ m
->cow_start
.offset
,
2325 m
->cow_start
.nb_bytes
) &&
2326 is_unallocated(bs
, m
->offset
+ m
->cow_end
.offset
,
2327 m
->cow_end
.nb_bytes
);
2330 static int handle_alloc_space(BlockDriverState
*bs
, QCowL2Meta
*l2meta
)
2332 BDRVQcow2State
*s
= bs
->opaque
;
2335 if (!(s
->data_file
->bs
->supported_zero_flags
& BDRV_REQ_NO_FALLBACK
)) {
2339 if (bs
->encrypted
) {
2343 for (m
= l2meta
; m
!= NULL
; m
= m
->next
) {
2346 if (!m
->cow_start
.nb_bytes
&& !m
->cow_end
.nb_bytes
) {
2350 if (!is_zero_cow(bs
, m
)) {
2355 * instead of writing zero COW buffers,
2356 * efficiently zero out the whole clusters
2359 ret
= qcow2_pre_write_overlap_check(bs
, 0, m
->alloc_offset
,
2360 m
->nb_clusters
* s
->cluster_size
,
2366 BLKDBG_EVENT(bs
->file
, BLKDBG_CLUSTER_ALLOC_SPACE
);
2367 ret
= bdrv_co_pwrite_zeroes(s
->data_file
, m
->alloc_offset
,
2368 m
->nb_clusters
* s
->cluster_size
,
2369 BDRV_REQ_NO_FALLBACK
);
2371 if (ret
!= -ENOTSUP
&& ret
!= -EAGAIN
) {
2377 trace_qcow2_skip_cow(qemu_coroutine_self(), m
->offset
, m
->nb_clusters
);
2384 * qcow2_co_pwritev_task
2385 * Called with s->lock unlocked
2386 * l2meta - if not NULL, qcow2_co_pwritev_task() will consume it. Caller must
2387 * not use it somehow after qcow2_co_pwritev_task() call
2389 static coroutine_fn
int qcow2_co_pwritev_task(BlockDriverState
*bs
,
2390 uint64_t file_cluster_offset
,
2391 uint64_t offset
, uint64_t bytes
,
2393 uint64_t qiov_offset
,
2397 BDRVQcow2State
*s
= bs
->opaque
;
2398 void *crypt_buf
= NULL
;
2399 int offset_in_cluster
= offset_into_cluster(s
, offset
);
2400 QEMUIOVector encrypted_qiov
;
2402 if (bs
->encrypted
) {
2404 assert(bytes
<= QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_size
);
2405 crypt_buf
= qemu_try_blockalign(bs
->file
->bs
, bytes
);
2406 if (crypt_buf
== NULL
) {
2410 qemu_iovec_to_buf(qiov
, qiov_offset
, crypt_buf
, bytes
);
2412 if (qcow2_co_encrypt(bs
, file_cluster_offset
+ offset_in_cluster
,
2413 offset
, crypt_buf
, bytes
) < 0)
2419 qemu_iovec_init_buf(&encrypted_qiov
, crypt_buf
, bytes
);
2420 qiov
= &encrypted_qiov
;
2424 /* Try to efficiently initialize the physical space with zeroes */
2425 ret
= handle_alloc_space(bs
, l2meta
);
2431 * If we need to do COW, check if it's possible to merge the
2432 * writing of the guest data together with that of the COW regions.
2433 * If it's not possible (or not necessary) then write the
2436 if (!merge_cow(offset
, bytes
, qiov
, qiov_offset
, l2meta
)) {
2437 BLKDBG_EVENT(bs
->file
, BLKDBG_WRITE_AIO
);
2438 trace_qcow2_writev_data(qemu_coroutine_self(),
2439 file_cluster_offset
+ offset_in_cluster
);
2440 ret
= bdrv_co_pwritev_part(s
->data_file
,
2441 file_cluster_offset
+ offset_in_cluster
,
2442 bytes
, qiov
, qiov_offset
, 0);
2448 qemu_co_mutex_lock(&s
->lock
);
2450 ret
= qcow2_handle_l2meta(bs
, &l2meta
, true);
2454 qemu_co_mutex_lock(&s
->lock
);
2457 qcow2_handle_l2meta(bs
, &l2meta
, false);
2458 qemu_co_mutex_unlock(&s
->lock
);
2460 qemu_vfree(crypt_buf
);
2465 static coroutine_fn
int qcow2_co_pwritev_task_entry(AioTask
*task
)
2467 Qcow2AioTask
*t
= container_of(task
, Qcow2AioTask
, task
);
2469 assert(!t
->cluster_type
);
2471 return qcow2_co_pwritev_task(t
->bs
, t
->file_cluster_offset
,
2472 t
->offset
, t
->bytes
, t
->qiov
, t
->qiov_offset
,
2476 static coroutine_fn
int qcow2_co_pwritev_part(
2477 BlockDriverState
*bs
, uint64_t offset
, uint64_t bytes
,
2478 QEMUIOVector
*qiov
, size_t qiov_offset
, int flags
)
2480 BDRVQcow2State
*s
= bs
->opaque
;
2481 int offset_in_cluster
;
2483 unsigned int cur_bytes
; /* number of sectors in current iteration */
2484 uint64_t cluster_offset
;
2485 QCowL2Meta
*l2meta
= NULL
;
2486 AioTaskPool
*aio
= NULL
;
2488 trace_qcow2_writev_start_req(qemu_coroutine_self(), offset
, bytes
);
2490 while (bytes
!= 0 && aio_task_pool_status(aio
) == 0) {
2494 trace_qcow2_writev_start_part(qemu_coroutine_self());
2495 offset_in_cluster
= offset_into_cluster(s
, offset
);
2496 cur_bytes
= MIN(bytes
, INT_MAX
);
2497 if (bs
->encrypted
) {
2498 cur_bytes
= MIN(cur_bytes
,
2499 QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_size
2500 - offset_in_cluster
);
2503 qemu_co_mutex_lock(&s
->lock
);
2505 ret
= qcow2_alloc_cluster_offset(bs
, offset
, &cur_bytes
,
2506 &cluster_offset
, &l2meta
);
2511 assert(offset_into_cluster(s
, cluster_offset
) == 0);
2513 ret
= qcow2_pre_write_overlap_check(bs
, 0,
2514 cluster_offset
+ offset_in_cluster
,
2520 qemu_co_mutex_unlock(&s
->lock
);
2522 if (!aio
&& cur_bytes
!= bytes
) {
2523 aio
= aio_task_pool_new(QCOW2_MAX_WORKERS
);
2525 ret
= qcow2_add_task(bs
, aio
, qcow2_co_pwritev_task_entry
, 0,
2526 cluster_offset
, offset
, cur_bytes
,
2527 qiov
, qiov_offset
, l2meta
);
2528 l2meta
= NULL
; /* l2meta is consumed by qcow2_co_pwritev_task() */
2534 offset
+= cur_bytes
;
2535 qiov_offset
+= cur_bytes
;
2536 trace_qcow2_writev_done_part(qemu_coroutine_self(), cur_bytes
);
2540 qemu_co_mutex_lock(&s
->lock
);
2543 qcow2_handle_l2meta(bs
, &l2meta
, false);
2545 qemu_co_mutex_unlock(&s
->lock
);
2549 aio_task_pool_wait_all(aio
);
2551 ret
= aio_task_pool_status(aio
);
2556 trace_qcow2_writev_done_req(qemu_coroutine_self(), ret
);
2561 static int qcow2_inactivate(BlockDriverState
*bs
)
2563 BDRVQcow2State
*s
= bs
->opaque
;
2564 int ret
, result
= 0;
2565 Error
*local_err
= NULL
;
2567 qcow2_store_persistent_dirty_bitmaps(bs
, true, &local_err
);
2568 if (local_err
!= NULL
) {
2570 error_reportf_err(local_err
, "Lost persistent bitmaps during "
2571 "inactivation of node '%s': ",
2572 bdrv_get_device_or_node_name(bs
));
2575 ret
= qcow2_cache_flush(bs
, s
->l2_table_cache
);
2578 error_report("Failed to flush the L2 table cache: %s",
2582 ret
= qcow2_cache_flush(bs
, s
->refcount_block_cache
);
2585 error_report("Failed to flush the refcount block cache: %s",
2590 qcow2_mark_clean(bs
);
2596 static void qcow2_close(BlockDriverState
*bs
)
2598 BDRVQcow2State
*s
= bs
->opaque
;
2599 qemu_vfree(s
->l1_table
);
2600 /* else pre-write overlap checks in cache_destroy may crash */
2603 if (!(s
->flags
& BDRV_O_INACTIVE
)) {
2604 qcow2_inactivate(bs
);
2607 cache_clean_timer_del(bs
);
2608 qcow2_cache_destroy(s
->l2_table_cache
);
2609 qcow2_cache_destroy(s
->refcount_block_cache
);
2611 qcrypto_block_free(s
->crypto
);
2613 qapi_free_QCryptoBlockOpenOptions(s
->crypto_opts
);
2615 g_free(s
->unknown_header_fields
);
2616 cleanup_unknown_header_ext(bs
);
2618 g_free(s
->image_data_file
);
2619 g_free(s
->image_backing_file
);
2620 g_free(s
->image_backing_format
);
2622 if (has_data_file(bs
)) {
2623 bdrv_unref_child(bs
, s
->data_file
);
2626 qcow2_refcount_close(bs
);
2627 qcow2_free_snapshots(bs
);
2630 static void coroutine_fn
qcow2_co_invalidate_cache(BlockDriverState
*bs
,
2633 BDRVQcow2State
*s
= bs
->opaque
;
2634 int flags
= s
->flags
;
2635 QCryptoBlock
*crypto
= NULL
;
2637 Error
*local_err
= NULL
;
2641 * Backing files are read-only which makes all of their metadata immutable,
2642 * that means we don't have to worry about reopening them here.
2650 memset(s
, 0, sizeof(BDRVQcow2State
));
2651 options
= qdict_clone_shallow(bs
->options
);
2653 flags
&= ~BDRV_O_INACTIVE
;
2654 qemu_co_mutex_lock(&s
->lock
);
2655 ret
= qcow2_do_open(bs
, options
, flags
, &local_err
);
2656 qemu_co_mutex_unlock(&s
->lock
);
2657 qobject_unref(options
);
2659 error_propagate_prepend(errp
, local_err
,
2660 "Could not reopen qcow2 layer: ");
2663 } else if (ret
< 0) {
2664 error_setg_errno(errp
, -ret
, "Could not reopen qcow2 layer");
2672 static size_t header_ext_add(char *buf
, uint32_t magic
, const void *s
,
2673 size_t len
, size_t buflen
)
2675 QCowExtension
*ext_backing_fmt
= (QCowExtension
*) buf
;
2676 size_t ext_len
= sizeof(QCowExtension
) + ((len
+ 7) & ~7);
2678 if (buflen
< ext_len
) {
2682 *ext_backing_fmt
= (QCowExtension
) {
2683 .magic
= cpu_to_be32(magic
),
2684 .len
= cpu_to_be32(len
),
2688 memcpy(buf
+ sizeof(QCowExtension
), s
, len
);
2695 * Updates the qcow2 header, including the variable length parts of it, i.e.
2696 * the backing file name and all extensions. qcow2 was not designed to allow
2697 * such changes, so if we run out of space (we can only use the first cluster)
2698 * this function may fail.
2700 * Returns 0 on success, -errno in error cases.
2702 int qcow2_update_header(BlockDriverState
*bs
)
2704 BDRVQcow2State
*s
= bs
->opaque
;
2707 size_t buflen
= s
->cluster_size
;
2709 uint64_t total_size
;
2710 uint32_t refcount_table_clusters
;
2711 size_t header_length
;
2712 Qcow2UnknownHeaderExtension
*uext
;
2714 buf
= qemu_blockalign(bs
, buflen
);
2716 /* Header structure */
2717 header
= (QCowHeader
*) buf
;
2719 if (buflen
< sizeof(*header
)) {
2724 header_length
= sizeof(*header
) + s
->unknown_header_fields_size
;
2725 total_size
= bs
->total_sectors
* BDRV_SECTOR_SIZE
;
2726 refcount_table_clusters
= s
->refcount_table_size
>> (s
->cluster_bits
- 3);
2728 *header
= (QCowHeader
) {
2729 /* Version 2 fields */
2730 .magic
= cpu_to_be32(QCOW_MAGIC
),
2731 .version
= cpu_to_be32(s
->qcow_version
),
2732 .backing_file_offset
= 0,
2733 .backing_file_size
= 0,
2734 .cluster_bits
= cpu_to_be32(s
->cluster_bits
),
2735 .size
= cpu_to_be64(total_size
),
2736 .crypt_method
= cpu_to_be32(s
->crypt_method_header
),
2737 .l1_size
= cpu_to_be32(s
->l1_size
),
2738 .l1_table_offset
= cpu_to_be64(s
->l1_table_offset
),
2739 .refcount_table_offset
= cpu_to_be64(s
->refcount_table_offset
),
2740 .refcount_table_clusters
= cpu_to_be32(refcount_table_clusters
),
2741 .nb_snapshots
= cpu_to_be32(s
->nb_snapshots
),
2742 .snapshots_offset
= cpu_to_be64(s
->snapshots_offset
),
2744 /* Version 3 fields */
2745 .incompatible_features
= cpu_to_be64(s
->incompatible_features
),
2746 .compatible_features
= cpu_to_be64(s
->compatible_features
),
2747 .autoclear_features
= cpu_to_be64(s
->autoclear_features
),
2748 .refcount_order
= cpu_to_be32(s
->refcount_order
),
2749 .header_length
= cpu_to_be32(header_length
),
2752 /* For older versions, write a shorter header */
2753 switch (s
->qcow_version
) {
2755 ret
= offsetof(QCowHeader
, incompatible_features
);
2758 ret
= sizeof(*header
);
2767 memset(buf
, 0, buflen
);
2769 /* Preserve any unknown field in the header */
2770 if (s
->unknown_header_fields_size
) {
2771 if (buflen
< s
->unknown_header_fields_size
) {
2776 memcpy(buf
, s
->unknown_header_fields
, s
->unknown_header_fields_size
);
2777 buf
+= s
->unknown_header_fields_size
;
2778 buflen
-= s
->unknown_header_fields_size
;
2781 /* Backing file format header extension */
2782 if (s
->image_backing_format
) {
2783 ret
= header_ext_add(buf
, QCOW2_EXT_MAGIC_BACKING_FORMAT
,
2784 s
->image_backing_format
,
2785 strlen(s
->image_backing_format
),
2795 /* External data file header extension */
2796 if (has_data_file(bs
) && s
->image_data_file
) {
2797 ret
= header_ext_add(buf
, QCOW2_EXT_MAGIC_DATA_FILE
,
2798 s
->image_data_file
, strlen(s
->image_data_file
),
2808 /* Full disk encryption header pointer extension */
2809 if (s
->crypto_header
.offset
!= 0) {
2810 s
->crypto_header
.offset
= cpu_to_be64(s
->crypto_header
.offset
);
2811 s
->crypto_header
.length
= cpu_to_be64(s
->crypto_header
.length
);
2812 ret
= header_ext_add(buf
, QCOW2_EXT_MAGIC_CRYPTO_HEADER
,
2813 &s
->crypto_header
, sizeof(s
->crypto_header
),
2815 s
->crypto_header
.offset
= be64_to_cpu(s
->crypto_header
.offset
);
2816 s
->crypto_header
.length
= be64_to_cpu(s
->crypto_header
.length
);
2825 if (s
->qcow_version
>= 3) {
2826 Qcow2Feature features
[] = {
2828 .type
= QCOW2_FEAT_TYPE_INCOMPATIBLE
,
2829 .bit
= QCOW2_INCOMPAT_DIRTY_BITNR
,
2830 .name
= "dirty bit",
2833 .type
= QCOW2_FEAT_TYPE_INCOMPATIBLE
,
2834 .bit
= QCOW2_INCOMPAT_CORRUPT_BITNR
,
2835 .name
= "corrupt bit",
2838 .type
= QCOW2_FEAT_TYPE_INCOMPATIBLE
,
2839 .bit
= QCOW2_INCOMPAT_DATA_FILE_BITNR
,
2840 .name
= "external data file",
2843 .type
= QCOW2_FEAT_TYPE_COMPATIBLE
,
2844 .bit
= QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR
,
2845 .name
= "lazy refcounts",
2849 ret
= header_ext_add(buf
, QCOW2_EXT_MAGIC_FEATURE_TABLE
,
2850 features
, sizeof(features
), buflen
);
2858 /* Bitmap extension */
2859 if (s
->nb_bitmaps
> 0) {
2860 Qcow2BitmapHeaderExt bitmaps_header
= {
2861 .nb_bitmaps
= cpu_to_be32(s
->nb_bitmaps
),
2862 .bitmap_directory_size
=
2863 cpu_to_be64(s
->bitmap_directory_size
),
2864 .bitmap_directory_offset
=
2865 cpu_to_be64(s
->bitmap_directory_offset
)
2867 ret
= header_ext_add(buf
, QCOW2_EXT_MAGIC_BITMAPS
,
2868 &bitmaps_header
, sizeof(bitmaps_header
),
2877 /* Keep unknown header extensions */
2878 QLIST_FOREACH(uext
, &s
->unknown_header_ext
, next
) {
2879 ret
= header_ext_add(buf
, uext
->magic
, uext
->data
, uext
->len
, buflen
);
2888 /* End of header extensions */
2889 ret
= header_ext_add(buf
, QCOW2_EXT_MAGIC_END
, NULL
, 0, buflen
);
2897 /* Backing file name */
2898 if (s
->image_backing_file
) {
2899 size_t backing_file_len
= strlen(s
->image_backing_file
);
2901 if (buflen
< backing_file_len
) {
2906 /* Using strncpy is ok here, since buf is not NUL-terminated. */
2907 strncpy(buf
, s
->image_backing_file
, buflen
);
2909 header
->backing_file_offset
= cpu_to_be64(buf
- ((char*) header
));
2910 header
->backing_file_size
= cpu_to_be32(backing_file_len
);
2913 /* Write the new header */
2914 ret
= bdrv_pwrite(bs
->file
, 0, header
, s
->cluster_size
);
2925 static int qcow2_change_backing_file(BlockDriverState
*bs
,
2926 const char *backing_file
, const char *backing_fmt
)
2928 BDRVQcow2State
*s
= bs
->opaque
;
2930 /* Adding a backing file means that the external data file alone won't be
2931 * enough to make sense of the content */
2932 if (backing_file
&& data_file_is_raw(bs
)) {
2936 if (backing_file
&& strlen(backing_file
) > 1023) {
2940 pstrcpy(bs
->auto_backing_file
, sizeof(bs
->auto_backing_file
),
2941 backing_file
?: "");
2942 pstrcpy(bs
->backing_file
, sizeof(bs
->backing_file
), backing_file
?: "");
2943 pstrcpy(bs
->backing_format
, sizeof(bs
->backing_format
), backing_fmt
?: "");
2945 g_free(s
->image_backing_file
);
2946 g_free(s
->image_backing_format
);
2948 s
->image_backing_file
= backing_file
? g_strdup(bs
->backing_file
) : NULL
;
2949 s
->image_backing_format
= backing_fmt
? g_strdup(bs
->backing_format
) : NULL
;
2951 return qcow2_update_header(bs
);
2954 static int qcow2_crypt_method_from_format(const char *encryptfmt
)
2956 if (g_str_equal(encryptfmt
, "luks")) {
2957 return QCOW_CRYPT_LUKS
;
2958 } else if (g_str_equal(encryptfmt
, "aes")) {
2959 return QCOW_CRYPT_AES
;
2965 static int qcow2_set_up_encryption(BlockDriverState
*bs
,
2966 QCryptoBlockCreateOptions
*cryptoopts
,
2969 BDRVQcow2State
*s
= bs
->opaque
;
2970 QCryptoBlock
*crypto
= NULL
;
2973 switch (cryptoopts
->format
) {
2974 case Q_CRYPTO_BLOCK_FORMAT_LUKS
:
2975 fmt
= QCOW_CRYPT_LUKS
;
2977 case Q_CRYPTO_BLOCK_FORMAT_QCOW
:
2978 fmt
= QCOW_CRYPT_AES
;
2981 error_setg(errp
, "Crypto format not supported in qcow2");
2985 s
->crypt_method_header
= fmt
;
2987 crypto
= qcrypto_block_create(cryptoopts
, "encrypt.",
2988 qcow2_crypto_hdr_init_func
,
2989 qcow2_crypto_hdr_write_func
,
2995 ret
= qcow2_update_header(bs
);
2997 error_setg_errno(errp
, -ret
, "Could not write encryption header");
3003 qcrypto_block_free(crypto
);
3008 * Preallocates metadata structures for data clusters between @offset (in the
3009 * guest disk) and @new_length (which is thus generally the new guest disk
3012 * Returns: 0 on success, -errno on failure.
3014 static int coroutine_fn
preallocate_co(BlockDriverState
*bs
, uint64_t offset
,
3015 uint64_t new_length
, PreallocMode mode
,
3018 BDRVQcow2State
*s
= bs
->opaque
;
3020 uint64_t host_offset
= 0;
3021 int64_t file_length
;
3022 unsigned int cur_bytes
;
3026 assert(offset
<= new_length
);
3027 bytes
= new_length
- offset
;
3030 cur_bytes
= MIN(bytes
, QEMU_ALIGN_DOWN(INT_MAX
, s
->cluster_size
));
3031 ret
= qcow2_alloc_cluster_offset(bs
, offset
, &cur_bytes
,
3032 &host_offset
, &meta
);
3034 error_setg_errno(errp
, -ret
, "Allocating clusters failed");
3039 QCowL2Meta
*next
= meta
->next
;
3041 ret
= qcow2_alloc_cluster_link_l2(bs
, meta
);
3043 error_setg_errno(errp
, -ret
, "Mapping clusters failed");
3044 qcow2_free_any_clusters(bs
, meta
->alloc_offset
,
3045 meta
->nb_clusters
, QCOW2_DISCARD_NEVER
);
3049 /* There are no dependent requests, but we need to remove our
3050 * request from the list of in-flight requests */
3051 QLIST_REMOVE(meta
, next_in_flight
);
3057 /* TODO Preallocate data if requested */
3060 offset
+= cur_bytes
;
3064 * It is expected that the image file is large enough to actually contain
3065 * all of the allocated clusters (otherwise we get failing reads after
3066 * EOF). Extend the image to the last allocated sector.
3068 file_length
= bdrv_getlength(s
->data_file
->bs
);
3069 if (file_length
< 0) {
3070 error_setg_errno(errp
, -file_length
, "Could not get file size");
3074 if (host_offset
+ cur_bytes
> file_length
) {
3075 if (mode
== PREALLOC_MODE_METADATA
) {
3076 mode
= PREALLOC_MODE_OFF
;
3078 ret
= bdrv_co_truncate(s
->data_file
, host_offset
+ cur_bytes
, false,
3088 /* qcow2_refcount_metadata_size:
3089 * @clusters: number of clusters to refcount (including data and L1/L2 tables)
3090 * @cluster_size: size of a cluster, in bytes
3091 * @refcount_order: refcount bits power-of-2 exponent
3092 * @generous_increase: allow for the refcount table to be 1.5x as large as it
3095 * Returns: Number of bytes required for refcount blocks and table metadata.
3097 int64_t qcow2_refcount_metadata_size(int64_t clusters
, size_t cluster_size
,
3098 int refcount_order
, bool generous_increase
,
3099 uint64_t *refblock_count
)
3102 * Every host cluster is reference-counted, including metadata (even
3103 * refcount metadata is recursively included).
3105 * An accurate formula for the size of refcount metadata size is difficult
3106 * to derive. An easier method of calculation is finding the fixed point
3107 * where no further refcount blocks or table clusters are required to
3108 * reference count every cluster.
3110 int64_t blocks_per_table_cluster
= cluster_size
/ sizeof(uint64_t);
3111 int64_t refcounts_per_block
= cluster_size
* 8 / (1 << refcount_order
);
3112 int64_t table
= 0; /* number of refcount table clusters */
3113 int64_t blocks
= 0; /* number of refcount block clusters */
3119 blocks
= DIV_ROUND_UP(clusters
+ table
+ blocks
, refcounts_per_block
);
3120 table
= DIV_ROUND_UP(blocks
, blocks_per_table_cluster
);
3121 n
= clusters
+ blocks
+ table
;
3123 if (n
== last
&& generous_increase
) {
3124 clusters
+= DIV_ROUND_UP(table
, 2);
3125 n
= 0; /* force another loop */
3126 generous_increase
= false;
3128 } while (n
!= last
);
3130 if (refblock_count
) {
3131 *refblock_count
= blocks
;
3134 return (blocks
+ table
) * cluster_size
;
3138 * qcow2_calc_prealloc_size:
3139 * @total_size: virtual disk size in bytes
3140 * @cluster_size: cluster size in bytes
3141 * @refcount_order: refcount bits power-of-2 exponent
3143 * Returns: Total number of bytes required for the fully allocated image
3144 * (including metadata).
3146 static int64_t qcow2_calc_prealloc_size(int64_t total_size
,
3147 size_t cluster_size
,
3150 int64_t meta_size
= 0;
3151 uint64_t nl1e
, nl2e
;
3152 int64_t aligned_total_size
= ROUND_UP(total_size
, cluster_size
);
3154 /* header: 1 cluster */
3155 meta_size
+= cluster_size
;
3157 /* total size of L2 tables */
3158 nl2e
= aligned_total_size
/ cluster_size
;
3159 nl2e
= ROUND_UP(nl2e
, cluster_size
/ sizeof(uint64_t));
3160 meta_size
+= nl2e
* sizeof(uint64_t);
3162 /* total size of L1 tables */
3163 nl1e
= nl2e
* sizeof(uint64_t) / cluster_size
;
3164 nl1e
= ROUND_UP(nl1e
, cluster_size
/ sizeof(uint64_t));
3165 meta_size
+= nl1e
* sizeof(uint64_t);
3167 /* total size of refcount table and blocks */
3168 meta_size
+= qcow2_refcount_metadata_size(
3169 (meta_size
+ aligned_total_size
) / cluster_size
,
3170 cluster_size
, refcount_order
, false, NULL
);
3172 return meta_size
+ aligned_total_size
;
3175 static bool validate_cluster_size(size_t cluster_size
, Error
**errp
)
3177 int cluster_bits
= ctz32(cluster_size
);
3178 if (cluster_bits
< MIN_CLUSTER_BITS
|| cluster_bits
> MAX_CLUSTER_BITS
||
3179 (1 << cluster_bits
) != cluster_size
)
3181 error_setg(errp
, "Cluster size must be a power of two between %d and "
3182 "%dk", 1 << MIN_CLUSTER_BITS
, 1 << (MAX_CLUSTER_BITS
- 10));
3188 static size_t qcow2_opt_get_cluster_size_del(QemuOpts
*opts
, Error
**errp
)
3190 size_t cluster_size
;
3192 cluster_size
= qemu_opt_get_size_del(opts
, BLOCK_OPT_CLUSTER_SIZE
,
3193 DEFAULT_CLUSTER_SIZE
);
3194 if (!validate_cluster_size(cluster_size
, errp
)) {
3197 return cluster_size
;
3200 static int qcow2_opt_get_version_del(QemuOpts
*opts
, Error
**errp
)
3205 buf
= qemu_opt_get_del(opts
, BLOCK_OPT_COMPAT_LEVEL
);
3207 ret
= 3; /* default */
3208 } else if (!strcmp(buf
, "0.10")) {
3210 } else if (!strcmp(buf
, "1.1")) {
3213 error_setg(errp
, "Invalid compatibility level: '%s'", buf
);
3220 static uint64_t qcow2_opt_get_refcount_bits_del(QemuOpts
*opts
, int version
,
3223 uint64_t refcount_bits
;
3225 refcount_bits
= qemu_opt_get_number_del(opts
, BLOCK_OPT_REFCOUNT_BITS
, 16);
3226 if (refcount_bits
> 64 || !is_power_of_2(refcount_bits
)) {
3227 error_setg(errp
, "Refcount width must be a power of two and may not "
3232 if (version
< 3 && refcount_bits
!= 16) {
3233 error_setg(errp
, "Different refcount widths than 16 bits require "
3234 "compatibility level 1.1 or above (use compat=1.1 or "
3239 return refcount_bits
;
3242 static int coroutine_fn
3243 qcow2_co_create(BlockdevCreateOptions
*create_options
, Error
**errp
)
3245 BlockdevCreateOptionsQcow2
*qcow2_opts
;
3249 * Open the image file and write a minimal qcow2 header.
3251 * We keep things simple and start with a zero-sized image. We also
3252 * do without refcount blocks or a L1 table for now. We'll fix the
3253 * inconsistency later.
3255 * We do need a refcount table because growing the refcount table means
3256 * allocating two new refcount blocks - the seconds of which would be at
3257 * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
3258 * size for any qcow2 image.
3260 BlockBackend
*blk
= NULL
;
3261 BlockDriverState
*bs
= NULL
;
3262 BlockDriverState
*data_bs
= NULL
;
3264 size_t cluster_size
;
3267 uint64_t* refcount_table
;
3268 Error
*local_err
= NULL
;
3271 assert(create_options
->driver
== BLOCKDEV_DRIVER_QCOW2
);
3272 qcow2_opts
= &create_options
->u
.qcow2
;
3274 bs
= bdrv_open_blockdev_ref(qcow2_opts
->file
, errp
);
3279 /* Validate options and set default values */
3280 if (!QEMU_IS_ALIGNED(qcow2_opts
->size
, BDRV_SECTOR_SIZE
)) {
3281 error_setg(errp
, "Image size must be a multiple of %u bytes",
3282 (unsigned) BDRV_SECTOR_SIZE
);
3287 if (qcow2_opts
->has_version
) {
3288 switch (qcow2_opts
->version
) {
3289 case BLOCKDEV_QCOW2_VERSION_V2
:
3292 case BLOCKDEV_QCOW2_VERSION_V3
:
3296 g_assert_not_reached();
3302 if (qcow2_opts
->has_cluster_size
) {
3303 cluster_size
= qcow2_opts
->cluster_size
;
3305 cluster_size
= DEFAULT_CLUSTER_SIZE
;
3308 if (!validate_cluster_size(cluster_size
, errp
)) {
3313 if (!qcow2_opts
->has_preallocation
) {
3314 qcow2_opts
->preallocation
= PREALLOC_MODE_OFF
;
3316 if (qcow2_opts
->has_backing_file
&&
3317 qcow2_opts
->preallocation
!= PREALLOC_MODE_OFF
)
3319 error_setg(errp
, "Backing file and preallocation cannot be used at "
3324 if (qcow2_opts
->has_backing_fmt
&& !qcow2_opts
->has_backing_file
) {
3325 error_setg(errp
, "Backing format cannot be used without backing file");
3330 if (!qcow2_opts
->has_lazy_refcounts
) {
3331 qcow2_opts
->lazy_refcounts
= false;
3333 if (version
< 3 && qcow2_opts
->lazy_refcounts
) {
3334 error_setg(errp
, "Lazy refcounts only supported with compatibility "
3335 "level 1.1 and above (use version=v3 or greater)");
3340 if (!qcow2_opts
->has_refcount_bits
) {
3341 qcow2_opts
->refcount_bits
= 16;
3343 if (qcow2_opts
->refcount_bits
> 64 ||
3344 !is_power_of_2(qcow2_opts
->refcount_bits
))
3346 error_setg(errp
, "Refcount width must be a power of two and may not "
3351 if (version
< 3 && qcow2_opts
->refcount_bits
!= 16) {
3352 error_setg(errp
, "Different refcount widths than 16 bits require "
3353 "compatibility level 1.1 or above (use version=v3 or "
3358 refcount_order
= ctz32(qcow2_opts
->refcount_bits
);
3360 if (qcow2_opts
->data_file_raw
&& !qcow2_opts
->data_file
) {
3361 error_setg(errp
, "data-file-raw requires data-file");
3365 if (qcow2_opts
->data_file_raw
&& qcow2_opts
->has_backing_file
) {
3366 error_setg(errp
, "Backing file and data-file-raw cannot be used at "
3372 if (qcow2_opts
->data_file
) {
3374 error_setg(errp
, "External data files are only supported with "
3375 "compatibility level 1.1 and above (use version=v3 or "
3380 data_bs
= bdrv_open_blockdev_ref(qcow2_opts
->data_file
, errp
);
3381 if (data_bs
== NULL
) {
3387 /* Create BlockBackend to write to the image */
3388 blk
= blk_new(bdrv_get_aio_context(bs
),
3389 BLK_PERM_WRITE
| BLK_PERM_RESIZE
, BLK_PERM_ALL
);
3390 ret
= blk_insert_bs(blk
, bs
, errp
);
3394 blk_set_allow_write_beyond_eof(blk
, true);
3396 /* Write the header */
3397 QEMU_BUILD_BUG_ON((1 << MIN_CLUSTER_BITS
) < sizeof(*header
));
3398 header
= g_malloc0(cluster_size
);
3399 *header
= (QCowHeader
) {
3400 .magic
= cpu_to_be32(QCOW_MAGIC
),
3401 .version
= cpu_to_be32(version
),
3402 .cluster_bits
= cpu_to_be32(ctz32(cluster_size
)),
3403 .size
= cpu_to_be64(0),
3404 .l1_table_offset
= cpu_to_be64(0),
3405 .l1_size
= cpu_to_be32(0),
3406 .refcount_table_offset
= cpu_to_be64(cluster_size
),
3407 .refcount_table_clusters
= cpu_to_be32(1),
3408 .refcount_order
= cpu_to_be32(refcount_order
),
3409 .header_length
= cpu_to_be32(sizeof(*header
)),
3412 /* We'll update this to correct value later */
3413 header
->crypt_method
= cpu_to_be32(QCOW_CRYPT_NONE
);
3415 if (qcow2_opts
->lazy_refcounts
) {
3416 header
->compatible_features
|=
3417 cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS
);
3420 header
->incompatible_features
|=
3421 cpu_to_be64(QCOW2_INCOMPAT_DATA_FILE
);
3423 if (qcow2_opts
->data_file_raw
) {
3424 header
->autoclear_features
|=
3425 cpu_to_be64(QCOW2_AUTOCLEAR_DATA_FILE_RAW
);
3428 ret
= blk_pwrite(blk
, 0, header
, cluster_size
, 0);
3431 error_setg_errno(errp
, -ret
, "Could not write qcow2 header");
3435 /* Write a refcount table with one refcount block */
3436 refcount_table
= g_malloc0(2 * cluster_size
);
3437 refcount_table
[0] = cpu_to_be64(2 * cluster_size
);
3438 ret
= blk_pwrite(blk
, cluster_size
, refcount_table
, 2 * cluster_size
, 0);
3439 g_free(refcount_table
);
3442 error_setg_errno(errp
, -ret
, "Could not write refcount table");
3450 * And now open the image and make it consistent first (i.e. increase the
3451 * refcount of the cluster that is occupied by the header and the refcount
3454 options
= qdict_new();
3455 qdict_put_str(options
, "driver", "qcow2");
3456 qdict_put_str(options
, "file", bs
->node_name
);
3458 qdict_put_str(options
, "data-file", data_bs
->node_name
);
3460 blk
= blk_new_open(NULL
, NULL
, options
,
3461 BDRV_O_RDWR
| BDRV_O_RESIZE
| BDRV_O_NO_FLUSH
,
3464 error_propagate(errp
, local_err
);
3469 ret
= qcow2_alloc_clusters(blk_bs(blk
), 3 * cluster_size
);
3471 error_setg_errno(errp
, -ret
, "Could not allocate clusters for qcow2 "
3472 "header and refcount table");
3475 } else if (ret
!= 0) {
3476 error_report("Huh, first cluster in empty image is already in use?");
3480 /* Set the external data file if necessary */
3482 BDRVQcow2State
*s
= blk_bs(blk
)->opaque
;
3483 s
->image_data_file
= g_strdup(data_bs
->filename
);
3486 /* Create a full header (including things like feature table) */
3487 ret
= qcow2_update_header(blk_bs(blk
));
3489 error_setg_errno(errp
, -ret
, "Could not update qcow2 header");
3493 /* Okay, now that we have a valid image, let's give it the right size */
3494 ret
= blk_truncate(blk
, qcow2_opts
->size
, false, qcow2_opts
->preallocation
,
3497 error_prepend(errp
, "Could not resize image: ");
3501 /* Want a backing file? There you go.*/
3502 if (qcow2_opts
->has_backing_file
) {
3503 const char *backing_format
= NULL
;
3505 if (qcow2_opts
->has_backing_fmt
) {
3506 backing_format
= BlockdevDriver_str(qcow2_opts
->backing_fmt
);
3509 ret
= bdrv_change_backing_file(blk_bs(blk
), qcow2_opts
->backing_file
,
3512 error_setg_errno(errp
, -ret
, "Could not assign backing file '%s' "
3513 "with format '%s'", qcow2_opts
->backing_file
,
3519 /* Want encryption? There you go. */
3520 if (qcow2_opts
->has_encrypt
) {
3521 ret
= qcow2_set_up_encryption(blk_bs(blk
), qcow2_opts
->encrypt
, errp
);
3530 /* Reopen the image without BDRV_O_NO_FLUSH to flush it before returning.
3531 * Using BDRV_O_NO_IO, since encryption is now setup we don't want to
3532 * have to setup decryption context. We're not doing any I/O on the top
3533 * level BlockDriverState, only lower layers, where BDRV_O_NO_IO does
3536 options
= qdict_new();
3537 qdict_put_str(options
, "driver", "qcow2");
3538 qdict_put_str(options
, "file", bs
->node_name
);
3540 qdict_put_str(options
, "data-file", data_bs
->node_name
);
3542 blk
= blk_new_open(NULL
, NULL
, options
,
3543 BDRV_O_RDWR
| BDRV_O_NO_BACKING
| BDRV_O_NO_IO
,
3546 error_propagate(errp
, local_err
);
3555 bdrv_unref(data_bs
);
3559 static int coroutine_fn
qcow2_co_create_opts(const char *filename
, QemuOpts
*opts
,
3562 BlockdevCreateOptions
*create_options
= NULL
;
3565 BlockDriverState
*bs
= NULL
;
3566 BlockDriverState
*data_bs
= NULL
;
3567 Error
*local_err
= NULL
;
3571 /* Only the keyval visitor supports the dotted syntax needed for
3572 * encryption, so go through a QDict before getting a QAPI type. Ignore
3573 * options meant for the protocol layer so that the visitor doesn't
3575 qdict
= qemu_opts_to_qdict_filtered(opts
, NULL
, bdrv_qcow2
.create_opts
,
3578 /* Handle encryption options */
3579 val
= qdict_get_try_str(qdict
, BLOCK_OPT_ENCRYPT
);
3580 if (val
&& !strcmp(val
, "on")) {
3581 qdict_put_str(qdict
, BLOCK_OPT_ENCRYPT
, "qcow");
3582 } else if (val
&& !strcmp(val
, "off")) {
3583 qdict_del(qdict
, BLOCK_OPT_ENCRYPT
);
3586 val
= qdict_get_try_str(qdict
, BLOCK_OPT_ENCRYPT_FORMAT
);
3587 if (val
&& !strcmp(val
, "aes")) {
3588 qdict_put_str(qdict
, BLOCK_OPT_ENCRYPT_FORMAT
, "qcow");
3591 /* Convert compat=0.10/1.1 into compat=v2/v3, to be renamed into
3592 * version=v2/v3 below. */
3593 val
= qdict_get_try_str(qdict
, BLOCK_OPT_COMPAT_LEVEL
);
3594 if (val
&& !strcmp(val
, "0.10")) {
3595 qdict_put_str(qdict
, BLOCK_OPT_COMPAT_LEVEL
, "v2");
3596 } else if (val
&& !strcmp(val
, "1.1")) {
3597 qdict_put_str(qdict
, BLOCK_OPT_COMPAT_LEVEL
, "v3");
3600 /* Change legacy command line options into QMP ones */
3601 static const QDictRenames opt_renames
[] = {
3602 { BLOCK_OPT_BACKING_FILE
, "backing-file" },
3603 { BLOCK_OPT_BACKING_FMT
, "backing-fmt" },
3604 { BLOCK_OPT_CLUSTER_SIZE
, "cluster-size" },
3605 { BLOCK_OPT_LAZY_REFCOUNTS
, "lazy-refcounts" },
3606 { BLOCK_OPT_REFCOUNT_BITS
, "refcount-bits" },
3607 { BLOCK_OPT_ENCRYPT
, BLOCK_OPT_ENCRYPT_FORMAT
},
3608 { BLOCK_OPT_COMPAT_LEVEL
, "version" },
3609 { BLOCK_OPT_DATA_FILE_RAW
, "data-file-raw" },
3613 if (!qdict_rename_keys(qdict
, opt_renames
, errp
)) {
3618 /* Create and open the file (protocol layer) */
3619 ret
= bdrv_create_file(filename
, opts
, errp
);
3624 bs
= bdrv_open(filename
, NULL
, NULL
,
3625 BDRV_O_RDWR
| BDRV_O_RESIZE
| BDRV_O_PROTOCOL
, errp
);
3631 /* Create and open an external data file (protocol layer) */
3632 val
= qdict_get_try_str(qdict
, BLOCK_OPT_DATA_FILE
);
3634 ret
= bdrv_create_file(val
, opts
, errp
);
3639 data_bs
= bdrv_open(val
, NULL
, NULL
,
3640 BDRV_O_RDWR
| BDRV_O_RESIZE
| BDRV_O_PROTOCOL
,
3642 if (data_bs
== NULL
) {
3647 qdict_del(qdict
, BLOCK_OPT_DATA_FILE
);
3648 qdict_put_str(qdict
, "data-file", data_bs
->node_name
);
3651 /* Set 'driver' and 'node' options */
3652 qdict_put_str(qdict
, "driver", "qcow2");
3653 qdict_put_str(qdict
, "file", bs
->node_name
);
3655 /* Now get the QAPI type BlockdevCreateOptions */
3656 v
= qobject_input_visitor_new_flat_confused(qdict
, errp
);
3662 visit_type_BlockdevCreateOptions(v
, NULL
, &create_options
, &local_err
);
3666 error_propagate(errp
, local_err
);
3671 /* Silently round up size */
3672 create_options
->u
.qcow2
.size
= ROUND_UP(create_options
->u
.qcow2
.size
,
3675 /* Create the qcow2 image (format layer) */
3676 ret
= qcow2_co_create(create_options
, errp
);
3683 qobject_unref(qdict
);
3685 bdrv_unref(data_bs
);
3686 qapi_free_BlockdevCreateOptions(create_options
);
3691 static bool is_zero(BlockDriverState
*bs
, int64_t offset
, int64_t bytes
)
3696 /* Clamp to image length, before checking status of underlying sectors */
3697 if (offset
+ bytes
> bs
->total_sectors
* BDRV_SECTOR_SIZE
) {
3698 bytes
= bs
->total_sectors
* BDRV_SECTOR_SIZE
- offset
;
3704 res
= bdrv_block_status_above(bs
, NULL
, offset
, bytes
, &nr
, NULL
, NULL
);
3705 return res
>= 0 && (res
& BDRV_BLOCK_ZERO
) && nr
== bytes
;
3708 static coroutine_fn
int qcow2_co_pwrite_zeroes(BlockDriverState
*bs
,
3709 int64_t offset
, int bytes
, BdrvRequestFlags flags
)
3712 BDRVQcow2State
*s
= bs
->opaque
;
3714 uint32_t head
= offset
% s
->cluster_size
;
3715 uint32_t tail
= (offset
+ bytes
) % s
->cluster_size
;
3717 trace_qcow2_pwrite_zeroes_start_req(qemu_coroutine_self(), offset
, bytes
);
3718 if (offset
+ bytes
== bs
->total_sectors
* BDRV_SECTOR_SIZE
) {
3726 assert(head
+ bytes
<= s
->cluster_size
);
3728 /* check whether remainder of cluster already reads as zero */
3729 if (!(is_zero(bs
, offset
- head
, head
) &&
3730 is_zero(bs
, offset
+ bytes
,
3731 tail
? s
->cluster_size
- tail
: 0))) {
3735 qemu_co_mutex_lock(&s
->lock
);
3736 /* We can have new write after previous check */
3737 offset
= QEMU_ALIGN_DOWN(offset
, s
->cluster_size
);
3738 bytes
= s
->cluster_size
;
3739 nr
= s
->cluster_size
;
3740 ret
= qcow2_get_cluster_offset(bs
, offset
, &nr
, &off
);
3741 if (ret
!= QCOW2_CLUSTER_UNALLOCATED
&&
3742 ret
!= QCOW2_CLUSTER_ZERO_PLAIN
&&
3743 ret
!= QCOW2_CLUSTER_ZERO_ALLOC
) {
3744 qemu_co_mutex_unlock(&s
->lock
);
3748 qemu_co_mutex_lock(&s
->lock
);
3751 trace_qcow2_pwrite_zeroes(qemu_coroutine_self(), offset
, bytes
);
3753 /* Whatever is left can use real zero clusters */
3754 ret
= qcow2_cluster_zeroize(bs
, offset
, bytes
, flags
);
3755 qemu_co_mutex_unlock(&s
->lock
);
3760 static coroutine_fn
int qcow2_co_pdiscard(BlockDriverState
*bs
,
3761 int64_t offset
, int bytes
)
3764 BDRVQcow2State
*s
= bs
->opaque
;
3766 if (!QEMU_IS_ALIGNED(offset
| bytes
, s
->cluster_size
)) {
3767 assert(bytes
< s
->cluster_size
);
3768 /* Ignore partial clusters, except for the special case of the
3769 * complete partial cluster at the end of an unaligned file */
3770 if (!QEMU_IS_ALIGNED(offset
, s
->cluster_size
) ||
3771 offset
+ bytes
!= bs
->total_sectors
* BDRV_SECTOR_SIZE
) {
3776 qemu_co_mutex_lock(&s
->lock
);
3777 ret
= qcow2_cluster_discard(bs
, offset
, bytes
, QCOW2_DISCARD_REQUEST
,
3779 qemu_co_mutex_unlock(&s
->lock
);
3783 static int coroutine_fn
3784 qcow2_co_copy_range_from(BlockDriverState
*bs
,
3785 BdrvChild
*src
, uint64_t src_offset
,
3786 BdrvChild
*dst
, uint64_t dst_offset
,
3787 uint64_t bytes
, BdrvRequestFlags read_flags
,
3788 BdrvRequestFlags write_flags
)
3790 BDRVQcow2State
*s
= bs
->opaque
;
3792 unsigned int cur_bytes
; /* number of bytes in current iteration */
3793 BdrvChild
*child
= NULL
;
3794 BdrvRequestFlags cur_write_flags
;
3796 assert(!bs
->encrypted
);
3797 qemu_co_mutex_lock(&s
->lock
);
3799 while (bytes
!= 0) {
3800 uint64_t copy_offset
= 0;
3801 /* prepare next request */
3802 cur_bytes
= MIN(bytes
, INT_MAX
);
3803 cur_write_flags
= write_flags
;
3805 ret
= qcow2_get_cluster_offset(bs
, src_offset
, &cur_bytes
, ©_offset
);
3811 case QCOW2_CLUSTER_UNALLOCATED
:
3812 if (bs
->backing
&& bs
->backing
->bs
) {
3813 int64_t backing_length
= bdrv_getlength(bs
->backing
->bs
);
3814 if (src_offset
>= backing_length
) {
3815 cur_write_flags
|= BDRV_REQ_ZERO_WRITE
;
3817 child
= bs
->backing
;
3818 cur_bytes
= MIN(cur_bytes
, backing_length
- src_offset
);
3819 copy_offset
= src_offset
;
3822 cur_write_flags
|= BDRV_REQ_ZERO_WRITE
;
3826 case QCOW2_CLUSTER_ZERO_PLAIN
:
3827 case QCOW2_CLUSTER_ZERO_ALLOC
:
3828 cur_write_flags
|= BDRV_REQ_ZERO_WRITE
;
3831 case QCOW2_CLUSTER_COMPRESSED
:
3835 case QCOW2_CLUSTER_NORMAL
:
3836 child
= s
->data_file
;
3837 copy_offset
+= offset_into_cluster(s
, src_offset
);
3843 qemu_co_mutex_unlock(&s
->lock
);
3844 ret
= bdrv_co_copy_range_from(child
,
3847 cur_bytes
, read_flags
, cur_write_flags
);
3848 qemu_co_mutex_lock(&s
->lock
);
3854 src_offset
+= cur_bytes
;
3855 dst_offset
+= cur_bytes
;
3860 qemu_co_mutex_unlock(&s
->lock
);
3864 static int coroutine_fn
3865 qcow2_co_copy_range_to(BlockDriverState
*bs
,
3866 BdrvChild
*src
, uint64_t src_offset
,
3867 BdrvChild
*dst
, uint64_t dst_offset
,
3868 uint64_t bytes
, BdrvRequestFlags read_flags
,
3869 BdrvRequestFlags write_flags
)
3871 BDRVQcow2State
*s
= bs
->opaque
;
3872 int offset_in_cluster
;
3874 unsigned int cur_bytes
; /* number of sectors in current iteration */
3875 uint64_t cluster_offset
;
3876 QCowL2Meta
*l2meta
= NULL
;
3878 assert(!bs
->encrypted
);
3880 qemu_co_mutex_lock(&s
->lock
);
3882 while (bytes
!= 0) {
3886 offset_in_cluster
= offset_into_cluster(s
, dst_offset
);
3887 cur_bytes
= MIN(bytes
, INT_MAX
);
3890 * If src->bs == dst->bs, we could simply copy by incrementing
3891 * the refcnt, without copying user data.
3892 * Or if src->bs == dst->bs->backing->bs, we could copy by discarding. */
3893 ret
= qcow2_alloc_cluster_offset(bs
, dst_offset
, &cur_bytes
,
3894 &cluster_offset
, &l2meta
);
3899 assert(offset_into_cluster(s
, cluster_offset
) == 0);
3901 ret
= qcow2_pre_write_overlap_check(bs
, 0,
3902 cluster_offset
+ offset_in_cluster
, cur_bytes
, true);
3907 qemu_co_mutex_unlock(&s
->lock
);
3908 ret
= bdrv_co_copy_range_to(src
, src_offset
,
3910 cluster_offset
+ offset_in_cluster
,
3911 cur_bytes
, read_flags
, write_flags
);
3912 qemu_co_mutex_lock(&s
->lock
);
3917 ret
= qcow2_handle_l2meta(bs
, &l2meta
, true);
3923 src_offset
+= cur_bytes
;
3924 dst_offset
+= cur_bytes
;
3929 qcow2_handle_l2meta(bs
, &l2meta
, false);
3931 qemu_co_mutex_unlock(&s
->lock
);
3933 trace_qcow2_writev_done_req(qemu_coroutine_self(), ret
);
3938 static int coroutine_fn
qcow2_co_truncate(BlockDriverState
*bs
, int64_t offset
,
3939 bool exact
, PreallocMode prealloc
,
3942 BDRVQcow2State
*s
= bs
->opaque
;
3943 uint64_t old_length
;
3944 int64_t new_l1_size
;
3948 if (prealloc
!= PREALLOC_MODE_OFF
&& prealloc
!= PREALLOC_MODE_METADATA
&&
3949 prealloc
!= PREALLOC_MODE_FALLOC
&& prealloc
!= PREALLOC_MODE_FULL
)
3951 error_setg(errp
, "Unsupported preallocation mode '%s'",
3952 PreallocMode_str(prealloc
));
3956 if (!QEMU_IS_ALIGNED(offset
, BDRV_SECTOR_SIZE
)) {
3957 error_setg(errp
, "The new size must be a multiple of %u",
3958 (unsigned) BDRV_SECTOR_SIZE
);
3962 qemu_co_mutex_lock(&s
->lock
);
3964 /* cannot proceed if image has snapshots */
3965 if (s
->nb_snapshots
) {
3966 error_setg(errp
, "Can't resize an image which has snapshots");
3971 /* cannot proceed if image has bitmaps */
3972 if (qcow2_truncate_bitmaps_check(bs
, errp
)) {
3977 old_length
= bs
->total_sectors
* BDRV_SECTOR_SIZE
;
3978 new_l1_size
= size_to_l1(s
, offset
);
3980 if (offset
< old_length
) {
3981 int64_t last_cluster
, old_file_size
;
3982 if (prealloc
!= PREALLOC_MODE_OFF
) {
3984 "Preallocation can't be used for shrinking an image");
3989 ret
= qcow2_cluster_discard(bs
, ROUND_UP(offset
, s
->cluster_size
),
3990 old_length
- ROUND_UP(offset
,
3992 QCOW2_DISCARD_ALWAYS
, true);
3994 error_setg_errno(errp
, -ret
, "Failed to discard cropped clusters");
3998 ret
= qcow2_shrink_l1_table(bs
, new_l1_size
);
4000 error_setg_errno(errp
, -ret
,
4001 "Failed to reduce the number of L2 tables");
4005 ret
= qcow2_shrink_reftable(bs
);
4007 error_setg_errno(errp
, -ret
,
4008 "Failed to discard unused refblocks");
4012 old_file_size
= bdrv_getlength(bs
->file
->bs
);
4013 if (old_file_size
< 0) {
4014 error_setg_errno(errp
, -old_file_size
,
4015 "Failed to inquire current file length");
4016 ret
= old_file_size
;
4019 last_cluster
= qcow2_get_last_cluster(bs
, old_file_size
);
4020 if (last_cluster
< 0) {
4021 error_setg_errno(errp
, -last_cluster
,
4022 "Failed to find the last cluster");
4026 if ((last_cluster
+ 1) * s
->cluster_size
< old_file_size
) {
4027 Error
*local_err
= NULL
;
4030 * Do not pass @exact here: It will not help the user if
4031 * we get an error here just because they wanted to shrink
4032 * their qcow2 image (on a block device) with qemu-img.
4033 * (And on the qcow2 layer, the @exact requirement is
4034 * always fulfilled, so there is no need to pass it on.)
4036 bdrv_co_truncate(bs
->file
, (last_cluster
+ 1) * s
->cluster_size
,
4037 false, PREALLOC_MODE_OFF
, &local_err
);
4039 warn_reportf_err(local_err
,
4040 "Failed to truncate the tail of the image: ");
4044 ret
= qcow2_grow_l1_table(bs
, new_l1_size
, true);
4046 error_setg_errno(errp
, -ret
, "Failed to grow the L1 table");
4052 case PREALLOC_MODE_OFF
:
4053 if (has_data_file(bs
)) {
4055 * If the caller wants an exact resize, the external data
4056 * file should be resized to the exact target size, too,
4057 * so we pass @exact here.
4059 ret
= bdrv_co_truncate(s
->data_file
, offset
, exact
, prealloc
, errp
);
4066 case PREALLOC_MODE_METADATA
:
4067 ret
= preallocate_co(bs
, old_length
, offset
, prealloc
, errp
);
4073 case PREALLOC_MODE_FALLOC
:
4074 case PREALLOC_MODE_FULL
:
4076 int64_t allocation_start
, host_offset
, guest_offset
;
4077 int64_t clusters_allocated
;
4078 int64_t old_file_size
, new_file_size
;
4079 uint64_t nb_new_data_clusters
, nb_new_l2_tables
;
4081 /* With a data file, preallocation means just allocating the metadata
4082 * and forwarding the truncate request to the data file */
4083 if (has_data_file(bs
)) {
4084 ret
= preallocate_co(bs
, old_length
, offset
, prealloc
, errp
);
4091 old_file_size
= bdrv_getlength(bs
->file
->bs
);
4092 if (old_file_size
< 0) {
4093 error_setg_errno(errp
, -old_file_size
,
4094 "Failed to inquire current file length");
4095 ret
= old_file_size
;
4098 old_file_size
= ROUND_UP(old_file_size
, s
->cluster_size
);
4100 nb_new_data_clusters
= DIV_ROUND_UP(offset
- old_length
,
4103 /* This is an overestimation; we will not actually allocate space for
4104 * these in the file but just make sure the new refcount structures are
4105 * able to cover them so we will not have to allocate new refblocks
4106 * while entering the data blocks in the potentially new L2 tables.
4107 * (We do not actually care where the L2 tables are placed. Maybe they
4108 * are already allocated or they can be placed somewhere before
4109 * @old_file_size. It does not matter because they will be fully
4110 * allocated automatically, so they do not need to be covered by the
4111 * preallocation. All that matters is that we will not have to allocate
4112 * new refcount structures for them.) */
4113 nb_new_l2_tables
= DIV_ROUND_UP(nb_new_data_clusters
,
4114 s
->cluster_size
/ sizeof(uint64_t));
4115 /* The cluster range may not be aligned to L2 boundaries, so add one L2
4116 * table for a potential head/tail */
4119 allocation_start
= qcow2_refcount_area(bs
, old_file_size
,
4120 nb_new_data_clusters
+
4123 if (allocation_start
< 0) {
4124 error_setg_errno(errp
, -allocation_start
,
4125 "Failed to resize refcount structures");
4126 ret
= allocation_start
;
4130 clusters_allocated
= qcow2_alloc_clusters_at(bs
, allocation_start
,
4131 nb_new_data_clusters
);
4132 if (clusters_allocated
< 0) {
4133 error_setg_errno(errp
, -clusters_allocated
,
4134 "Failed to allocate data clusters");
4135 ret
= clusters_allocated
;
4139 assert(clusters_allocated
== nb_new_data_clusters
);
4141 /* Allocate the data area */
4142 new_file_size
= allocation_start
+
4143 nb_new_data_clusters
* s
->cluster_size
;
4144 /* Image file grows, so @exact does not matter */
4145 ret
= bdrv_co_truncate(bs
->file
, new_file_size
, false, prealloc
, errp
);
4147 error_prepend(errp
, "Failed to resize underlying file: ");
4148 qcow2_free_clusters(bs
, allocation_start
,
4149 nb_new_data_clusters
* s
->cluster_size
,
4150 QCOW2_DISCARD_OTHER
);
4154 /* Create the necessary L2 entries */
4155 host_offset
= allocation_start
;
4156 guest_offset
= old_length
;
4157 while (nb_new_data_clusters
) {
4158 int64_t nb_clusters
= MIN(
4159 nb_new_data_clusters
,
4160 s
->l2_slice_size
- offset_to_l2_slice_index(s
, guest_offset
));
4161 QCowL2Meta allocation
= {
4162 .offset
= guest_offset
,
4163 .alloc_offset
= host_offset
,
4164 .nb_clusters
= nb_clusters
,
4166 qemu_co_queue_init(&allocation
.dependent_requests
);
4168 ret
= qcow2_alloc_cluster_link_l2(bs
, &allocation
);
4170 error_setg_errno(errp
, -ret
, "Failed to update L2 tables");
4171 qcow2_free_clusters(bs
, host_offset
,
4172 nb_new_data_clusters
* s
->cluster_size
,
4173 QCOW2_DISCARD_OTHER
);
4177 guest_offset
+= nb_clusters
* s
->cluster_size
;
4178 host_offset
+= nb_clusters
* s
->cluster_size
;
4179 nb_new_data_clusters
-= nb_clusters
;
4185 g_assert_not_reached();
4188 if (prealloc
!= PREALLOC_MODE_OFF
) {
4189 /* Flush metadata before actually changing the image size */
4190 ret
= qcow2_write_caches(bs
);
4192 error_setg_errno(errp
, -ret
,
4193 "Failed to flush the preallocated area to disk");
4198 bs
->total_sectors
= offset
/ BDRV_SECTOR_SIZE
;
4200 /* write updated header.size */
4201 offset
= cpu_to_be64(offset
);
4202 ret
= bdrv_pwrite_sync(bs
->file
, offsetof(QCowHeader
, size
),
4203 &offset
, sizeof(uint64_t));
4205 error_setg_errno(errp
, -ret
, "Failed to update the image size");
4209 s
->l1_vm_state_index
= new_l1_size
;
4211 /* Update cache sizes */
4212 options
= qdict_clone_shallow(bs
->options
);
4213 ret
= qcow2_update_options(bs
, options
, s
->flags
, errp
);
4214 qobject_unref(options
);
4220 qemu_co_mutex_unlock(&s
->lock
);
4224 static coroutine_fn
int
4225 qcow2_co_pwritev_compressed_task(BlockDriverState
*bs
,
4226 uint64_t offset
, uint64_t bytes
,
4227 QEMUIOVector
*qiov
, size_t qiov_offset
)
4229 BDRVQcow2State
*s
= bs
->opaque
;
4232 uint8_t *buf
, *out_buf
;
4233 uint64_t cluster_offset
;
4235 assert(bytes
== s
->cluster_size
|| (bytes
< s
->cluster_size
&&
4236 (offset
+ bytes
== bs
->total_sectors
<< BDRV_SECTOR_BITS
)));
4238 buf
= qemu_blockalign(bs
, s
->cluster_size
);
4239 if (bytes
< s
->cluster_size
) {
4240 /* Zero-pad last write if image size is not cluster aligned */
4241 memset(buf
+ bytes
, 0, s
->cluster_size
- bytes
);
4243 qemu_iovec_to_buf(qiov
, qiov_offset
, buf
, bytes
);
4245 out_buf
= g_malloc(s
->cluster_size
);
4247 out_len
= qcow2_co_compress(bs
, out_buf
, s
->cluster_size
- 1,
4248 buf
, s
->cluster_size
);
4249 if (out_len
== -ENOMEM
) {
4250 /* could not compress: write normal cluster */
4251 ret
= qcow2_co_pwritev_part(bs
, offset
, bytes
, qiov
, qiov_offset
, 0);
4256 } else if (out_len
< 0) {
4261 qemu_co_mutex_lock(&s
->lock
);
4262 ret
= qcow2_alloc_compressed_cluster_offset(bs
, offset
, out_len
,
4265 qemu_co_mutex_unlock(&s
->lock
);
4269 ret
= qcow2_pre_write_overlap_check(bs
, 0, cluster_offset
, out_len
, true);
4270 qemu_co_mutex_unlock(&s
->lock
);
4275 BLKDBG_EVENT(s
->data_file
, BLKDBG_WRITE_COMPRESSED
);
4276 ret
= bdrv_co_pwrite(s
->data_file
, cluster_offset
, out_len
, out_buf
, 0);
4288 static coroutine_fn
int qcow2_co_pwritev_compressed_task_entry(AioTask
*task
)
4290 Qcow2AioTask
*t
= container_of(task
, Qcow2AioTask
, task
);
4292 assert(!t
->cluster_type
&& !t
->l2meta
);
4294 return qcow2_co_pwritev_compressed_task(t
->bs
, t
->offset
, t
->bytes
, t
->qiov
,
4299 * XXX: put compressed sectors first, then all the cluster aligned
4300 * tables to avoid losing bytes in alignment
4302 static coroutine_fn
int
4303 qcow2_co_pwritev_compressed_part(BlockDriverState
*bs
,
4304 uint64_t offset
, uint64_t bytes
,
4305 QEMUIOVector
*qiov
, size_t qiov_offset
)
4307 BDRVQcow2State
*s
= bs
->opaque
;
4308 AioTaskPool
*aio
= NULL
;
4311 if (has_data_file(bs
)) {
4317 * align end of file to a sector boundary to ease reading with
4320 int64_t len
= bdrv_getlength(bs
->file
->bs
);
4324 return bdrv_co_truncate(bs
->file
, len
, false, PREALLOC_MODE_OFF
, NULL
);
4327 if (offset_into_cluster(s
, offset
)) {
4331 while (bytes
&& aio_task_pool_status(aio
) == 0) {
4332 uint64_t chunk_size
= MIN(bytes
, s
->cluster_size
);
4334 if (!aio
&& chunk_size
!= bytes
) {
4335 aio
= aio_task_pool_new(QCOW2_MAX_WORKERS
);
4338 ret
= qcow2_add_task(bs
, aio
, qcow2_co_pwritev_compressed_task_entry
,
4339 0, 0, offset
, chunk_size
, qiov
, qiov_offset
, NULL
);
4343 qiov_offset
+= chunk_size
;
4344 offset
+= chunk_size
;
4345 bytes
-= chunk_size
;
4349 aio_task_pool_wait_all(aio
);
4351 ret
= aio_task_pool_status(aio
);
4359 static int coroutine_fn
4360 qcow2_co_preadv_compressed(BlockDriverState
*bs
,
4361 uint64_t file_cluster_offset
,
4367 BDRVQcow2State
*s
= bs
->opaque
;
4368 int ret
= 0, csize
, nb_csectors
;
4370 uint8_t *buf
, *out_buf
;
4371 int offset_in_cluster
= offset_into_cluster(s
, offset
);
4373 coffset
= file_cluster_offset
& s
->cluster_offset_mask
;
4374 nb_csectors
= ((file_cluster_offset
>> s
->csize_shift
) & s
->csize_mask
) + 1;
4375 csize
= nb_csectors
* QCOW2_COMPRESSED_SECTOR_SIZE
-
4376 (coffset
& ~QCOW2_COMPRESSED_SECTOR_MASK
);
4378 buf
= g_try_malloc(csize
);
4383 out_buf
= qemu_blockalign(bs
, s
->cluster_size
);
4385 BLKDBG_EVENT(bs
->file
, BLKDBG_READ_COMPRESSED
);
4386 ret
= bdrv_co_pread(bs
->file
, coffset
, csize
, buf
, 0);
4391 if (qcow2_co_decompress(bs
, out_buf
, s
->cluster_size
, buf
, csize
) < 0) {
4396 qemu_iovec_from_buf(qiov
, qiov_offset
, out_buf
+ offset_in_cluster
, bytes
);
4399 qemu_vfree(out_buf
);
4405 static int make_completely_empty(BlockDriverState
*bs
)
4407 BDRVQcow2State
*s
= bs
->opaque
;
4408 Error
*local_err
= NULL
;
4409 int ret
, l1_clusters
;
4411 uint64_t *new_reftable
= NULL
;
4412 uint64_t rt_entry
, l1_size2
;
4415 uint64_t reftable_offset
;
4416 uint32_t reftable_clusters
;
4417 } QEMU_PACKED l1_ofs_rt_ofs_cls
;
4419 ret
= qcow2_cache_empty(bs
, s
->l2_table_cache
);
4424 ret
= qcow2_cache_empty(bs
, s
->refcount_block_cache
);
4429 /* Refcounts will be broken utterly */
4430 ret
= qcow2_mark_dirty(bs
);
4435 BLKDBG_EVENT(bs
->file
, BLKDBG_L1_UPDATE
);
4437 l1_clusters
= DIV_ROUND_UP(s
->l1_size
, s
->cluster_size
/ sizeof(uint64_t));
4438 l1_size2
= (uint64_t)s
->l1_size
* sizeof(uint64_t);
4440 /* After this call, neither the in-memory nor the on-disk refcount
4441 * information accurately describe the actual references */
4443 ret
= bdrv_pwrite_zeroes(bs
->file
, s
->l1_table_offset
,
4444 l1_clusters
* s
->cluster_size
, 0);
4446 goto fail_broken_refcounts
;
4448 memset(s
->l1_table
, 0, l1_size2
);
4450 BLKDBG_EVENT(bs
->file
, BLKDBG_EMPTY_IMAGE_PREPARE
);
4452 /* Overwrite enough clusters at the beginning of the sectors to place
4453 * the refcount table, a refcount block and the L1 table in; this may
4454 * overwrite parts of the existing refcount and L1 table, which is not
4455 * an issue because the dirty flag is set, complete data loss is in fact
4456 * desired and partial data loss is consequently fine as well */
4457 ret
= bdrv_pwrite_zeroes(bs
->file
, s
->cluster_size
,
4458 (2 + l1_clusters
) * s
->cluster_size
, 0);
4459 /* This call (even if it failed overall) may have overwritten on-disk
4460 * refcount structures; in that case, the in-memory refcount information
4461 * will probably differ from the on-disk information which makes the BDS
4464 goto fail_broken_refcounts
;
4467 BLKDBG_EVENT(bs
->file
, BLKDBG_L1_UPDATE
);
4468 BLKDBG_EVENT(bs
->file
, BLKDBG_REFTABLE_UPDATE
);
4470 /* "Create" an empty reftable (one cluster) directly after the image
4471 * header and an empty L1 table three clusters after the image header;
4472 * the cluster between those two will be used as the first refblock */
4473 l1_ofs_rt_ofs_cls
.l1_offset
= cpu_to_be64(3 * s
->cluster_size
);
4474 l1_ofs_rt_ofs_cls
.reftable_offset
= cpu_to_be64(s
->cluster_size
);
4475 l1_ofs_rt_ofs_cls
.reftable_clusters
= cpu_to_be32(1);
4476 ret
= bdrv_pwrite_sync(bs
->file
, offsetof(QCowHeader
, l1_table_offset
),
4477 &l1_ofs_rt_ofs_cls
, sizeof(l1_ofs_rt_ofs_cls
));
4479 goto fail_broken_refcounts
;
4482 s
->l1_table_offset
= 3 * s
->cluster_size
;
4484 new_reftable
= g_try_new0(uint64_t, s
->cluster_size
/ sizeof(uint64_t));
4485 if (!new_reftable
) {
4487 goto fail_broken_refcounts
;
4490 s
->refcount_table_offset
= s
->cluster_size
;
4491 s
->refcount_table_size
= s
->cluster_size
/ sizeof(uint64_t);
4492 s
->max_refcount_table_index
= 0;
4494 g_free(s
->refcount_table
);
4495 s
->refcount_table
= new_reftable
;
4496 new_reftable
= NULL
;
4498 /* Now the in-memory refcount information again corresponds to the on-disk
4499 * information (reftable is empty and no refblocks (the refblock cache is
4500 * empty)); however, this means some clusters (e.g. the image header) are
4501 * referenced, but not refcounted, but the normal qcow2 code assumes that
4502 * the in-memory information is always correct */
4504 BLKDBG_EVENT(bs
->file
, BLKDBG_REFBLOCK_ALLOC
);
4506 /* Enter the first refblock into the reftable */
4507 rt_entry
= cpu_to_be64(2 * s
->cluster_size
);
4508 ret
= bdrv_pwrite_sync(bs
->file
, s
->cluster_size
,
4509 &rt_entry
, sizeof(rt_entry
));
4511 goto fail_broken_refcounts
;
4513 s
->refcount_table
[0] = 2 * s
->cluster_size
;
4515 s
->free_cluster_index
= 0;
4516 assert(3 + l1_clusters
<= s
->refcount_block_size
);
4517 offset
= qcow2_alloc_clusters(bs
, 3 * s
->cluster_size
+ l1_size2
);
4520 goto fail_broken_refcounts
;
4521 } else if (offset
> 0) {
4522 error_report("First cluster in emptied image is in use");
4526 /* Now finally the in-memory information corresponds to the on-disk
4527 * structures and is correct */
4528 ret
= qcow2_mark_clean(bs
);
4533 ret
= bdrv_truncate(bs
->file
, (3 + l1_clusters
) * s
->cluster_size
, false,
4534 PREALLOC_MODE_OFF
, &local_err
);
4536 error_report_err(local_err
);
4542 fail_broken_refcounts
:
4543 /* The BDS is unusable at this point. If we wanted to make it usable, we
4544 * would have to call qcow2_refcount_close(), qcow2_refcount_init(),
4545 * qcow2_check_refcounts(), qcow2_refcount_close() and qcow2_refcount_init()
4546 * again. However, because the functions which could have caused this error
4547 * path to be taken are used by those functions as well, it's very likely
4548 * that that sequence will fail as well. Therefore, just eject the BDS. */
4552 g_free(new_reftable
);
4556 static int qcow2_make_empty(BlockDriverState
*bs
)
4558 BDRVQcow2State
*s
= bs
->opaque
;
4559 uint64_t offset
, end_offset
;
4560 int step
= QEMU_ALIGN_DOWN(INT_MAX
, s
->cluster_size
);
4561 int l1_clusters
, ret
= 0;
4563 l1_clusters
= DIV_ROUND_UP(s
->l1_size
, s
->cluster_size
/ sizeof(uint64_t));
4565 if (s
->qcow_version
>= 3 && !s
->snapshots
&& !s
->nb_bitmaps
&&
4566 3 + l1_clusters
<= s
->refcount_block_size
&&
4567 s
->crypt_method_header
!= QCOW_CRYPT_LUKS
&&
4568 !has_data_file(bs
)) {
4569 /* The following function only works for qcow2 v3 images (it
4570 * requires the dirty flag) and only as long as there are no
4571 * features that reserve extra clusters (such as snapshots,
4572 * LUKS header, or persistent bitmaps), because it completely
4573 * empties the image. Furthermore, the L1 table and three
4574 * additional clusters (image header, refcount table, one
4575 * refcount block) have to fit inside one refcount block. It
4576 * only resets the image file, i.e. does not work with an
4577 * external data file. */
4578 return make_completely_empty(bs
);
4581 /* This fallback code simply discards every active cluster; this is slow,
4582 * but works in all cases */
4583 end_offset
= bs
->total_sectors
* BDRV_SECTOR_SIZE
;
4584 for (offset
= 0; offset
< end_offset
; offset
+= step
) {
4585 /* As this function is generally used after committing an external
4586 * snapshot, QCOW2_DISCARD_SNAPSHOT seems appropriate. Also, the
4587 * default action for this kind of discard is to pass the discard,
4588 * which will ideally result in an actually smaller image file, as
4589 * is probably desired. */
4590 ret
= qcow2_cluster_discard(bs
, offset
, MIN(step
, end_offset
- offset
),
4591 QCOW2_DISCARD_SNAPSHOT
, true);
4600 static coroutine_fn
int qcow2_co_flush_to_os(BlockDriverState
*bs
)
4602 BDRVQcow2State
*s
= bs
->opaque
;
4605 qemu_co_mutex_lock(&s
->lock
);
4606 ret
= qcow2_write_caches(bs
);
4607 qemu_co_mutex_unlock(&s
->lock
);
4612 static BlockMeasureInfo
*qcow2_measure(QemuOpts
*opts
, BlockDriverState
*in_bs
,
4615 Error
*local_err
= NULL
;
4616 BlockMeasureInfo
*info
;
4617 uint64_t required
= 0; /* bytes that contribute to required size */
4618 uint64_t virtual_size
; /* disk size as seen by guest */
4619 uint64_t refcount_bits
;
4621 uint64_t luks_payload_size
= 0;
4622 size_t cluster_size
;
4625 PreallocMode prealloc
;
4626 bool has_backing_file
;
4629 /* Parse image creation options */
4630 cluster_size
= qcow2_opt_get_cluster_size_del(opts
, &local_err
);
4635 version
= qcow2_opt_get_version_del(opts
, &local_err
);
4640 refcount_bits
= qcow2_opt_get_refcount_bits_del(opts
, version
, &local_err
);
4645 optstr
= qemu_opt_get_del(opts
, BLOCK_OPT_PREALLOC
);
4646 prealloc
= qapi_enum_parse(&PreallocMode_lookup
, optstr
,
4647 PREALLOC_MODE_OFF
, &local_err
);
4653 optstr
= qemu_opt_get_del(opts
, BLOCK_OPT_BACKING_FILE
);
4654 has_backing_file
= !!optstr
;
4657 optstr
= qemu_opt_get_del(opts
, BLOCK_OPT_ENCRYPT_FORMAT
);
4658 has_luks
= optstr
&& strcmp(optstr
, "luks") == 0;
4662 g_autoptr(QCryptoBlockCreateOptions
) create_opts
= NULL
;
4667 opts_qdict
= qemu_opts_to_qdict(opts
, NULL
);
4668 qdict_extract_subqdict(opts_qdict
, &cryptoopts
, "encrypt.");
4669 qobject_unref(opts_qdict
);
4671 qdict_put_str(cryptoopts
, "format", "luks");
4673 create_opts
= block_crypto_create_opts_init(cryptoopts
, errp
);
4674 qobject_unref(cryptoopts
);
4679 if (!qcrypto_block_calculate_payload_offset(create_opts
,
4686 luks_payload_size
= ROUND_UP(headerlen
, cluster_size
);
4689 virtual_size
= qemu_opt_get_size_del(opts
, BLOCK_OPT_SIZE
, 0);
4690 virtual_size
= ROUND_UP(virtual_size
, cluster_size
);
4692 /* Check that virtual disk size is valid */
4693 l2_tables
= DIV_ROUND_UP(virtual_size
/ cluster_size
,
4694 cluster_size
/ sizeof(uint64_t));
4695 if (l2_tables
* sizeof(uint64_t) > QCOW_MAX_L1_SIZE
) {
4696 error_setg(&local_err
, "The image size is too large "
4697 "(try using a larger cluster size)");
4701 /* Account for input image */
4703 int64_t ssize
= bdrv_getlength(in_bs
);
4705 error_setg_errno(&local_err
, -ssize
,
4706 "Unable to get image virtual_size");
4710 virtual_size
= ROUND_UP(ssize
, cluster_size
);
4712 if (has_backing_file
) {
4713 /* We don't how much of the backing chain is shared by the input
4714 * image and the new image file. In the worst case the new image's
4715 * backing file has nothing in common with the input image. Be
4716 * conservative and assume all clusters need to be written.
4718 required
= virtual_size
;
4723 for (offset
= 0; offset
< ssize
; offset
+= pnum
) {
4726 ret
= bdrv_block_status_above(in_bs
, NULL
, offset
,
4727 ssize
- offset
, &pnum
, NULL
,
4730 error_setg_errno(&local_err
, -ret
,
4731 "Unable to get block status");
4735 if (ret
& BDRV_BLOCK_ZERO
) {
4736 /* Skip zero regions (safe with no backing file) */
4737 } else if ((ret
& (BDRV_BLOCK_DATA
| BDRV_BLOCK_ALLOCATED
)) ==
4738 (BDRV_BLOCK_DATA
| BDRV_BLOCK_ALLOCATED
)) {
4739 /* Extend pnum to end of cluster for next iteration */
4740 pnum
= ROUND_UP(offset
+ pnum
, cluster_size
) - offset
;
4742 /* Count clusters we've seen */
4743 required
+= offset
% cluster_size
+ pnum
;
4749 /* Take into account preallocation. Nothing special is needed for
4750 * PREALLOC_MODE_METADATA since metadata is always counted.
4752 if (prealloc
== PREALLOC_MODE_FULL
|| prealloc
== PREALLOC_MODE_FALLOC
) {
4753 required
= virtual_size
;
4756 info
= g_new(BlockMeasureInfo
, 1);
4757 info
->fully_allocated
=
4758 qcow2_calc_prealloc_size(virtual_size
, cluster_size
,
4759 ctz32(refcount_bits
)) + luks_payload_size
;
4761 /* Remove data clusters that are not required. This overestimates the
4762 * required size because metadata needed for the fully allocated file is
4765 info
->required
= info
->fully_allocated
- virtual_size
+ required
;
4769 error_propagate(errp
, local_err
);
4773 static int qcow2_get_info(BlockDriverState
*bs
, BlockDriverInfo
*bdi
)
4775 BDRVQcow2State
*s
= bs
->opaque
;
4776 bdi
->unallocated_blocks_are_zero
= true;
4777 bdi
->cluster_size
= s
->cluster_size
;
4778 bdi
->vm_state_offset
= qcow2_vm_state_offset(s
);
4782 static ImageInfoSpecific
*qcow2_get_specific_info(BlockDriverState
*bs
,
4785 BDRVQcow2State
*s
= bs
->opaque
;
4786 ImageInfoSpecific
*spec_info
;
4787 QCryptoBlockInfo
*encrypt_info
= NULL
;
4788 Error
*local_err
= NULL
;
4790 if (s
->crypto
!= NULL
) {
4791 encrypt_info
= qcrypto_block_get_info(s
->crypto
, &local_err
);
4793 error_propagate(errp
, local_err
);
4798 spec_info
= g_new(ImageInfoSpecific
, 1);
4799 *spec_info
= (ImageInfoSpecific
){
4800 .type
= IMAGE_INFO_SPECIFIC_KIND_QCOW2
,
4801 .u
.qcow2
.data
= g_new0(ImageInfoSpecificQCow2
, 1),
4803 if (s
->qcow_version
== 2) {
4804 *spec_info
->u
.qcow2
.data
= (ImageInfoSpecificQCow2
){
4805 .compat
= g_strdup("0.10"),
4806 .refcount_bits
= s
->refcount_bits
,
4808 } else if (s
->qcow_version
== 3) {
4809 Qcow2BitmapInfoList
*bitmaps
;
4810 bitmaps
= qcow2_get_bitmap_info_list(bs
, &local_err
);
4812 error_propagate(errp
, local_err
);
4813 qapi_free_ImageInfoSpecific(spec_info
);
4816 *spec_info
->u
.qcow2
.data
= (ImageInfoSpecificQCow2
){
4817 .compat
= g_strdup("1.1"),
4818 .lazy_refcounts
= s
->compatible_features
&
4819 QCOW2_COMPAT_LAZY_REFCOUNTS
,
4820 .has_lazy_refcounts
= true,
4821 .corrupt
= s
->incompatible_features
&
4822 QCOW2_INCOMPAT_CORRUPT
,
4823 .has_corrupt
= true,
4824 .refcount_bits
= s
->refcount_bits
,
4825 .has_bitmaps
= !!bitmaps
,
4827 .has_data_file
= !!s
->image_data_file
,
4828 .data_file
= g_strdup(s
->image_data_file
),
4829 .has_data_file_raw
= has_data_file(bs
),
4830 .data_file_raw
= data_file_is_raw(bs
),
4833 /* if this assertion fails, this probably means a new version was
4834 * added without having it covered here */
4839 ImageInfoSpecificQCow2Encryption
*qencrypt
=
4840 g_new(ImageInfoSpecificQCow2Encryption
, 1);
4841 switch (encrypt_info
->format
) {
4842 case Q_CRYPTO_BLOCK_FORMAT_QCOW
:
4843 qencrypt
->format
= BLOCKDEV_QCOW2_ENCRYPTION_FORMAT_AES
;
4845 case Q_CRYPTO_BLOCK_FORMAT_LUKS
:
4846 qencrypt
->format
= BLOCKDEV_QCOW2_ENCRYPTION_FORMAT_LUKS
;
4847 qencrypt
->u
.luks
= encrypt_info
->u
.luks
;
4852 /* Since we did shallow copy above, erase any pointers
4853 * in the original info */
4854 memset(&encrypt_info
->u
, 0, sizeof(encrypt_info
->u
));
4855 qapi_free_QCryptoBlockInfo(encrypt_info
);
4857 spec_info
->u
.qcow2
.data
->has_encrypt
= true;
4858 spec_info
->u
.qcow2
.data
->encrypt
= qencrypt
;
4864 static int qcow2_has_zero_init(BlockDriverState
*bs
)
4866 BDRVQcow2State
*s
= bs
->opaque
;
4869 if (qemu_in_coroutine()) {
4870 qemu_co_mutex_lock(&s
->lock
);
4873 * Check preallocation status: Preallocated images have all L2
4874 * tables allocated, nonpreallocated images have none. It is
4875 * therefore enough to check the first one.
4877 preallocated
= s
->l1_size
> 0 && s
->l1_table
[0] != 0;
4878 if (qemu_in_coroutine()) {
4879 qemu_co_mutex_unlock(&s
->lock
);
4882 if (!preallocated
) {
4884 } else if (bs
->encrypted
) {
4887 return bdrv_has_zero_init(s
->data_file
->bs
);
4891 static int qcow2_save_vmstate(BlockDriverState
*bs
, QEMUIOVector
*qiov
,
4894 BDRVQcow2State
*s
= bs
->opaque
;
4896 BLKDBG_EVENT(bs
->file
, BLKDBG_VMSTATE_SAVE
);
4897 return bs
->drv
->bdrv_co_pwritev_part(bs
, qcow2_vm_state_offset(s
) + pos
,
4898 qiov
->size
, qiov
, 0, 0);
4901 static int qcow2_load_vmstate(BlockDriverState
*bs
, QEMUIOVector
*qiov
,
4904 BDRVQcow2State
*s
= bs
->opaque
;
4906 BLKDBG_EVENT(bs
->file
, BLKDBG_VMSTATE_LOAD
);
4907 return bs
->drv
->bdrv_co_preadv_part(bs
, qcow2_vm_state_offset(s
) + pos
,
4908 qiov
->size
, qiov
, 0, 0);
4912 * Downgrades an image's version. To achieve this, any incompatible features
4913 * have to be removed.
4915 static int qcow2_downgrade(BlockDriverState
*bs
, int target_version
,
4916 BlockDriverAmendStatusCB
*status_cb
, void *cb_opaque
,
4919 BDRVQcow2State
*s
= bs
->opaque
;
4920 int current_version
= s
->qcow_version
;
4923 /* This is qcow2_downgrade(), not qcow2_upgrade() */
4924 assert(target_version
< current_version
);
4926 /* There are no other versions (now) that you can downgrade to */
4927 assert(target_version
== 2);
4929 if (s
->refcount_order
!= 4) {
4930 error_setg(errp
, "compat=0.10 requires refcount_bits=16");
4934 if (has_data_file(bs
)) {
4935 error_setg(errp
, "Cannot downgrade an image with a data file");
4939 /* clear incompatible features */
4940 if (s
->incompatible_features
& QCOW2_INCOMPAT_DIRTY
) {
4941 ret
= qcow2_mark_clean(bs
);
4943 error_setg_errno(errp
, -ret
, "Failed to make the image clean");
4948 /* with QCOW2_INCOMPAT_CORRUPT, it is pretty much impossible to get here in
4949 * the first place; if that happens nonetheless, returning -ENOTSUP is the
4950 * best thing to do anyway */
4952 if (s
->incompatible_features
) {
4953 error_setg(errp
, "Cannot downgrade an image with incompatible features "
4954 "%#" PRIx64
" set", s
->incompatible_features
);
4958 /* since we can ignore compatible features, we can set them to 0 as well */
4959 s
->compatible_features
= 0;
4960 /* if lazy refcounts have been used, they have already been fixed through
4961 * clearing the dirty flag */
4963 /* clearing autoclear features is trivial */
4964 s
->autoclear_features
= 0;
4966 ret
= qcow2_expand_zero_clusters(bs
, status_cb
, cb_opaque
);
4968 error_setg_errno(errp
, -ret
, "Failed to turn zero into data clusters");
4972 s
->qcow_version
= target_version
;
4973 ret
= qcow2_update_header(bs
);
4975 s
->qcow_version
= current_version
;
4976 error_setg_errno(errp
, -ret
, "Failed to update the image header");
4983 * Upgrades an image's version. While newer versions encompass all
4984 * features of older versions, some things may have to be presented
4987 static int qcow2_upgrade(BlockDriverState
*bs
, int target_version
,
4988 BlockDriverAmendStatusCB
*status_cb
, void *cb_opaque
,
4991 BDRVQcow2State
*s
= bs
->opaque
;
4992 bool need_snapshot_update
;
4993 int current_version
= s
->qcow_version
;
4997 /* This is qcow2_upgrade(), not qcow2_downgrade() */
4998 assert(target_version
> current_version
);
5000 /* There are no other versions (yet) that you can upgrade to */
5001 assert(target_version
== 3);
5003 status_cb(bs
, 0, 2, cb_opaque
);
5006 * In v2, snapshots do not need to have extra data. v3 requires
5007 * the 64-bit VM state size and the virtual disk size to be
5009 * qcow2_write_snapshots() will always write the list in the
5010 * v3-compliant format.
5012 need_snapshot_update
= false;
5013 for (i
= 0; i
< s
->nb_snapshots
; i
++) {
5014 if (s
->snapshots
[i
].extra_data_size
<
5015 sizeof_field(QCowSnapshotExtraData
, vm_state_size_large
) +
5016 sizeof_field(QCowSnapshotExtraData
, disk_size
))
5018 need_snapshot_update
= true;
5022 if (need_snapshot_update
) {
5023 ret
= qcow2_write_snapshots(bs
);
5025 error_setg_errno(errp
, -ret
, "Failed to update the snapshot table");
5029 status_cb(bs
, 1, 2, cb_opaque
);
5031 s
->qcow_version
= target_version
;
5032 ret
= qcow2_update_header(bs
);
5034 s
->qcow_version
= current_version
;
5035 error_setg_errno(errp
, -ret
, "Failed to update the image header");
5038 status_cb(bs
, 2, 2, cb_opaque
);
5043 typedef enum Qcow2AmendOperation
{
5044 /* This is the value Qcow2AmendHelperCBInfo::last_operation will be
5045 * statically initialized to so that the helper CB can discern the first
5046 * invocation from an operation change */
5047 QCOW2_NO_OPERATION
= 0,
5050 QCOW2_CHANGING_REFCOUNT_ORDER
,
5052 } Qcow2AmendOperation
;
5054 typedef struct Qcow2AmendHelperCBInfo
{
5055 /* The code coordinating the amend operations should only modify
5056 * these four fields; the rest will be managed by the CB */
5057 BlockDriverAmendStatusCB
*original_status_cb
;
5058 void *original_cb_opaque
;
5060 Qcow2AmendOperation current_operation
;
5062 /* Total number of operations to perform (only set once) */
5063 int total_operations
;
5065 /* The following fields are managed by the CB */
5067 /* Number of operations completed */
5068 int operations_completed
;
5070 /* Cumulative offset of all completed operations */
5071 int64_t offset_completed
;
5073 Qcow2AmendOperation last_operation
;
5074 int64_t last_work_size
;
5075 } Qcow2AmendHelperCBInfo
;
5077 static void qcow2_amend_helper_cb(BlockDriverState
*bs
,
5078 int64_t operation_offset
,
5079 int64_t operation_work_size
, void *opaque
)
5081 Qcow2AmendHelperCBInfo
*info
= opaque
;
5082 int64_t current_work_size
;
5083 int64_t projected_work_size
;
5085 if (info
->current_operation
!= info
->last_operation
) {
5086 if (info
->last_operation
!= QCOW2_NO_OPERATION
) {
5087 info
->offset_completed
+= info
->last_work_size
;
5088 info
->operations_completed
++;
5091 info
->last_operation
= info
->current_operation
;
5094 assert(info
->total_operations
> 0);
5095 assert(info
->operations_completed
< info
->total_operations
);
5097 info
->last_work_size
= operation_work_size
;
5099 current_work_size
= info
->offset_completed
+ operation_work_size
;
5101 /* current_work_size is the total work size for (operations_completed + 1)
5102 * operations (which includes this one), so multiply it by the number of
5103 * operations not covered and divide it by the number of operations
5104 * covered to get a projection for the operations not covered */
5105 projected_work_size
= current_work_size
* (info
->total_operations
-
5106 info
->operations_completed
- 1)
5107 / (info
->operations_completed
+ 1);
5109 info
->original_status_cb(bs
, info
->offset_completed
+ operation_offset
,
5110 current_work_size
+ projected_work_size
,
5111 info
->original_cb_opaque
);
5114 static int qcow2_amend_options(BlockDriverState
*bs
, QemuOpts
*opts
,
5115 BlockDriverAmendStatusCB
*status_cb
,
5119 BDRVQcow2State
*s
= bs
->opaque
;
5120 int old_version
= s
->qcow_version
, new_version
= old_version
;
5121 uint64_t new_size
= 0;
5122 const char *backing_file
= NULL
, *backing_format
= NULL
, *data_file
= NULL
;
5123 bool lazy_refcounts
= s
->use_lazy_refcounts
;
5124 bool data_file_raw
= data_file_is_raw(bs
);
5125 const char *compat
= NULL
;
5126 uint64_t cluster_size
= s
->cluster_size
;
5129 int refcount_bits
= s
->refcount_bits
;
5131 QemuOptDesc
*desc
= opts
->list
->desc
;
5132 Qcow2AmendHelperCBInfo helper_cb_info
;
5134 while (desc
&& desc
->name
) {
5135 if (!qemu_opt_find(opts
, desc
->name
)) {
5136 /* only change explicitly defined options */
5141 if (!strcmp(desc
->name
, BLOCK_OPT_COMPAT_LEVEL
)) {
5142 compat
= qemu_opt_get(opts
, BLOCK_OPT_COMPAT_LEVEL
);
5144 /* preserve default */
5145 } else if (!strcmp(compat
, "0.10") || !strcmp(compat
, "v2")) {
5147 } else if (!strcmp(compat
, "1.1") || !strcmp(compat
, "v3")) {
5150 error_setg(errp
, "Unknown compatibility level %s", compat
);
5153 } else if (!strcmp(desc
->name
, BLOCK_OPT_PREALLOC
)) {
5154 error_setg(errp
, "Cannot change preallocation mode");
5156 } else if (!strcmp(desc
->name
, BLOCK_OPT_SIZE
)) {
5157 new_size
= qemu_opt_get_size(opts
, BLOCK_OPT_SIZE
, 0);
5158 } else if (!strcmp(desc
->name
, BLOCK_OPT_BACKING_FILE
)) {
5159 backing_file
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FILE
);
5160 } else if (!strcmp(desc
->name
, BLOCK_OPT_BACKING_FMT
)) {
5161 backing_format
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FMT
);
5162 } else if (!strcmp(desc
->name
, BLOCK_OPT_ENCRYPT
)) {
5163 encrypt
= qemu_opt_get_bool(opts
, BLOCK_OPT_ENCRYPT
,
5166 if (encrypt
!= !!s
->crypto
) {
5168 "Changing the encryption flag is not supported");
5171 } else if (!strcmp(desc
->name
, BLOCK_OPT_ENCRYPT_FORMAT
)) {
5172 encformat
= qcow2_crypt_method_from_format(
5173 qemu_opt_get(opts
, BLOCK_OPT_ENCRYPT_FORMAT
));
5175 if (encformat
!= s
->crypt_method_header
) {
5177 "Changing the encryption format is not supported");
5180 } else if (g_str_has_prefix(desc
->name
, "encrypt.")) {
5182 "Changing the encryption parameters is not supported");
5184 } else if (!strcmp(desc
->name
, BLOCK_OPT_CLUSTER_SIZE
)) {
5185 cluster_size
= qemu_opt_get_size(opts
, BLOCK_OPT_CLUSTER_SIZE
,
5187 if (cluster_size
!= s
->cluster_size
) {
5188 error_setg(errp
, "Changing the cluster size is not supported");
5191 } else if (!strcmp(desc
->name
, BLOCK_OPT_LAZY_REFCOUNTS
)) {
5192 lazy_refcounts
= qemu_opt_get_bool(opts
, BLOCK_OPT_LAZY_REFCOUNTS
,
5194 } else if (!strcmp(desc
->name
, BLOCK_OPT_REFCOUNT_BITS
)) {
5195 refcount_bits
= qemu_opt_get_number(opts
, BLOCK_OPT_REFCOUNT_BITS
,
5198 if (refcount_bits
<= 0 || refcount_bits
> 64 ||
5199 !is_power_of_2(refcount_bits
))
5201 error_setg(errp
, "Refcount width must be a power of two and "
5202 "may not exceed 64 bits");
5205 } else if (!strcmp(desc
->name
, BLOCK_OPT_DATA_FILE
)) {
5206 data_file
= qemu_opt_get(opts
, BLOCK_OPT_DATA_FILE
);
5207 if (data_file
&& !has_data_file(bs
)) {
5208 error_setg(errp
, "data-file can only be set for images that "
5209 "use an external data file");
5212 } else if (!strcmp(desc
->name
, BLOCK_OPT_DATA_FILE_RAW
)) {
5213 data_file_raw
= qemu_opt_get_bool(opts
, BLOCK_OPT_DATA_FILE_RAW
,
5215 if (data_file_raw
&& !data_file_is_raw(bs
)) {
5216 error_setg(errp
, "data-file-raw cannot be set on existing "
5221 /* if this point is reached, this probably means a new option was
5222 * added without having it covered here */
5229 helper_cb_info
= (Qcow2AmendHelperCBInfo
){
5230 .original_status_cb
= status_cb
,
5231 .original_cb_opaque
= cb_opaque
,
5232 .total_operations
= (new_version
!= old_version
)
5233 + (s
->refcount_bits
!= refcount_bits
)
5236 /* Upgrade first (some features may require compat=1.1) */
5237 if (new_version
> old_version
) {
5238 helper_cb_info
.current_operation
= QCOW2_UPGRADING
;
5239 ret
= qcow2_upgrade(bs
, new_version
, &qcow2_amend_helper_cb
,
5240 &helper_cb_info
, errp
);
5246 if (s
->refcount_bits
!= refcount_bits
) {
5247 int refcount_order
= ctz32(refcount_bits
);
5249 if (new_version
< 3 && refcount_bits
!= 16) {
5250 error_setg(errp
, "Refcount widths other than 16 bits require "
5251 "compatibility level 1.1 or above (use compat=1.1 or "
5256 helper_cb_info
.current_operation
= QCOW2_CHANGING_REFCOUNT_ORDER
;
5257 ret
= qcow2_change_refcount_order(bs
, refcount_order
,
5258 &qcow2_amend_helper_cb
,
5259 &helper_cb_info
, errp
);
5265 /* data-file-raw blocks backing files, so clear it first if requested */
5266 if (data_file_raw
) {
5267 s
->autoclear_features
|= QCOW2_AUTOCLEAR_DATA_FILE_RAW
;
5269 s
->autoclear_features
&= ~QCOW2_AUTOCLEAR_DATA_FILE_RAW
;
5273 g_free(s
->image_data_file
);
5274 s
->image_data_file
= *data_file
? g_strdup(data_file
) : NULL
;
5277 ret
= qcow2_update_header(bs
);
5279 error_setg_errno(errp
, -ret
, "Failed to update the image header");
5283 if (backing_file
|| backing_format
) {
5284 ret
= qcow2_change_backing_file(bs
,
5285 backing_file
?: s
->image_backing_file
,
5286 backing_format
?: s
->image_backing_format
);
5288 error_setg_errno(errp
, -ret
, "Failed to change the backing file");
5293 if (s
->use_lazy_refcounts
!= lazy_refcounts
) {
5294 if (lazy_refcounts
) {
5295 if (new_version
< 3) {
5296 error_setg(errp
, "Lazy refcounts only supported with "
5297 "compatibility level 1.1 and above (use compat=1.1 "
5301 s
->compatible_features
|= QCOW2_COMPAT_LAZY_REFCOUNTS
;
5302 ret
= qcow2_update_header(bs
);
5304 s
->compatible_features
&= ~QCOW2_COMPAT_LAZY_REFCOUNTS
;
5305 error_setg_errno(errp
, -ret
, "Failed to update the image header");
5308 s
->use_lazy_refcounts
= true;
5310 /* make image clean first */
5311 ret
= qcow2_mark_clean(bs
);
5313 error_setg_errno(errp
, -ret
, "Failed to make the image clean");
5316 /* now disallow lazy refcounts */
5317 s
->compatible_features
&= ~QCOW2_COMPAT_LAZY_REFCOUNTS
;
5318 ret
= qcow2_update_header(bs
);
5320 s
->compatible_features
|= QCOW2_COMPAT_LAZY_REFCOUNTS
;
5321 error_setg_errno(errp
, -ret
, "Failed to update the image header");
5324 s
->use_lazy_refcounts
= false;
5329 BlockBackend
*blk
= blk_new(bdrv_get_aio_context(bs
),
5330 BLK_PERM_RESIZE
, BLK_PERM_ALL
);
5331 ret
= blk_insert_bs(blk
, bs
, errp
);
5338 * Amending image options should ensure that the image has
5339 * exactly the given new values, so pass exact=true here.
5341 ret
= blk_truncate(blk
, new_size
, true, PREALLOC_MODE_OFF
, errp
);
5348 /* Downgrade last (so unsupported features can be removed before) */
5349 if (new_version
< old_version
) {
5350 helper_cb_info
.current_operation
= QCOW2_DOWNGRADING
;
5351 ret
= qcow2_downgrade(bs
, new_version
, &qcow2_amend_helper_cb
,
5352 &helper_cb_info
, errp
);
5362 * If offset or size are negative, respectively, they will not be included in
5363 * the BLOCK_IMAGE_CORRUPTED event emitted.
5364 * fatal will be ignored for read-only BDS; corruptions found there will always
5365 * be considered non-fatal.
5367 void qcow2_signal_corruption(BlockDriverState
*bs
, bool fatal
, int64_t offset
,
5368 int64_t size
, const char *message_format
, ...)
5370 BDRVQcow2State
*s
= bs
->opaque
;
5371 const char *node_name
;
5375 fatal
= fatal
&& bdrv_is_writable(bs
);
5377 if (s
->signaled_corruption
&&
5378 (!fatal
|| (s
->incompatible_features
& QCOW2_INCOMPAT_CORRUPT
)))
5383 va_start(ap
, message_format
);
5384 message
= g_strdup_vprintf(message_format
, ap
);
5388 fprintf(stderr
, "qcow2: Marking image as corrupt: %s; further "
5389 "corruption events will be suppressed\n", message
);
5391 fprintf(stderr
, "qcow2: Image is corrupt: %s; further non-fatal "
5392 "corruption events will be suppressed\n", message
);
5395 node_name
= bdrv_get_node_name(bs
);
5396 qapi_event_send_block_image_corrupted(bdrv_get_device_name(bs
),
5397 *node_name
!= '\0', node_name
,
5398 message
, offset
>= 0, offset
,
5404 qcow2_mark_corrupt(bs
);
5405 bs
->drv
= NULL
; /* make BDS unusable */
5408 s
->signaled_corruption
= true;
5411 static QemuOptsList qcow2_create_opts
= {
5412 .name
= "qcow2-create-opts",
5413 .head
= QTAILQ_HEAD_INITIALIZER(qcow2_create_opts
.head
),
5416 .name
= BLOCK_OPT_SIZE
,
5417 .type
= QEMU_OPT_SIZE
,
5418 .help
= "Virtual disk size"
5421 .name
= BLOCK_OPT_COMPAT_LEVEL
,
5422 .type
= QEMU_OPT_STRING
,
5423 .help
= "Compatibility level (v2 [0.10] or v3 [1.1])"
5426 .name
= BLOCK_OPT_BACKING_FILE
,
5427 .type
= QEMU_OPT_STRING
,
5428 .help
= "File name of a base image"
5431 .name
= BLOCK_OPT_BACKING_FMT
,
5432 .type
= QEMU_OPT_STRING
,
5433 .help
= "Image format of the base image"
5436 .name
= BLOCK_OPT_DATA_FILE
,
5437 .type
= QEMU_OPT_STRING
,
5438 .help
= "File name of an external data file"
5441 .name
= BLOCK_OPT_DATA_FILE_RAW
,
5442 .type
= QEMU_OPT_BOOL
,
5443 .help
= "The external data file must stay valid as a raw image"
5446 .name
= BLOCK_OPT_ENCRYPT
,
5447 .type
= QEMU_OPT_BOOL
,
5448 .help
= "Encrypt the image with format 'aes'. (Deprecated "
5449 "in favor of " BLOCK_OPT_ENCRYPT_FORMAT
"=aes)",
5452 .name
= BLOCK_OPT_ENCRYPT_FORMAT
,
5453 .type
= QEMU_OPT_STRING
,
5454 .help
= "Encrypt the image, format choices: 'aes', 'luks'",
5456 BLOCK_CRYPTO_OPT_DEF_KEY_SECRET("encrypt.",
5457 "ID of secret providing qcow AES key or LUKS passphrase"),
5458 BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_ALG("encrypt."),
5459 BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_MODE("encrypt."),
5460 BLOCK_CRYPTO_OPT_DEF_LUKS_IVGEN_ALG("encrypt."),
5461 BLOCK_CRYPTO_OPT_DEF_LUKS_IVGEN_HASH_ALG("encrypt."),
5462 BLOCK_CRYPTO_OPT_DEF_LUKS_HASH_ALG("encrypt."),
5463 BLOCK_CRYPTO_OPT_DEF_LUKS_ITER_TIME("encrypt."),
5465 .name
= BLOCK_OPT_CLUSTER_SIZE
,
5466 .type
= QEMU_OPT_SIZE
,
5467 .help
= "qcow2 cluster size",
5468 .def_value_str
= stringify(DEFAULT_CLUSTER_SIZE
)
5471 .name
= BLOCK_OPT_PREALLOC
,
5472 .type
= QEMU_OPT_STRING
,
5473 .help
= "Preallocation mode (allowed values: off, metadata, "
5477 .name
= BLOCK_OPT_LAZY_REFCOUNTS
,
5478 .type
= QEMU_OPT_BOOL
,
5479 .help
= "Postpone refcount updates",
5480 .def_value_str
= "off"
5483 .name
= BLOCK_OPT_REFCOUNT_BITS
,
5484 .type
= QEMU_OPT_NUMBER
,
5485 .help
= "Width of a reference count entry in bits",
5486 .def_value_str
= "16"
5488 { /* end of list */ }
5492 static const char *const qcow2_strong_runtime_opts
[] = {
5493 "encrypt." BLOCK_CRYPTO_OPT_QCOW_KEY_SECRET
,
5498 BlockDriver bdrv_qcow2
= {
5499 .format_name
= "qcow2",
5500 .instance_size
= sizeof(BDRVQcow2State
),
5501 .bdrv_probe
= qcow2_probe
,
5502 .bdrv_open
= qcow2_open
,
5503 .bdrv_close
= qcow2_close
,
5504 .bdrv_reopen_prepare
= qcow2_reopen_prepare
,
5505 .bdrv_reopen_commit
= qcow2_reopen_commit
,
5506 .bdrv_reopen_commit_post
= qcow2_reopen_commit_post
,
5507 .bdrv_reopen_abort
= qcow2_reopen_abort
,
5508 .bdrv_join_options
= qcow2_join_options
,
5509 .bdrv_child_perm
= bdrv_format_default_perms
,
5510 .bdrv_co_create_opts
= qcow2_co_create_opts
,
5511 .bdrv_co_create
= qcow2_co_create
,
5512 .bdrv_has_zero_init
= qcow2_has_zero_init
,
5513 .bdrv_has_zero_init_truncate
= bdrv_has_zero_init_1
,
5514 .bdrv_co_block_status
= qcow2_co_block_status
,
5516 .bdrv_co_preadv_part
= qcow2_co_preadv_part
,
5517 .bdrv_co_pwritev_part
= qcow2_co_pwritev_part
,
5518 .bdrv_co_flush_to_os
= qcow2_co_flush_to_os
,
5520 .bdrv_co_pwrite_zeroes
= qcow2_co_pwrite_zeroes
,
5521 .bdrv_co_pdiscard
= qcow2_co_pdiscard
,
5522 .bdrv_co_copy_range_from
= qcow2_co_copy_range_from
,
5523 .bdrv_co_copy_range_to
= qcow2_co_copy_range_to
,
5524 .bdrv_co_truncate
= qcow2_co_truncate
,
5525 .bdrv_co_pwritev_compressed_part
= qcow2_co_pwritev_compressed_part
,
5526 .bdrv_make_empty
= qcow2_make_empty
,
5528 .bdrv_snapshot_create
= qcow2_snapshot_create
,
5529 .bdrv_snapshot_goto
= qcow2_snapshot_goto
,
5530 .bdrv_snapshot_delete
= qcow2_snapshot_delete
,
5531 .bdrv_snapshot_list
= qcow2_snapshot_list
,
5532 .bdrv_snapshot_load_tmp
= qcow2_snapshot_load_tmp
,
5533 .bdrv_measure
= qcow2_measure
,
5534 .bdrv_get_info
= qcow2_get_info
,
5535 .bdrv_get_specific_info
= qcow2_get_specific_info
,
5537 .bdrv_save_vmstate
= qcow2_save_vmstate
,
5538 .bdrv_load_vmstate
= qcow2_load_vmstate
,
5540 .supports_backing
= true,
5541 .bdrv_change_backing_file
= qcow2_change_backing_file
,
5543 .bdrv_refresh_limits
= qcow2_refresh_limits
,
5544 .bdrv_co_invalidate_cache
= qcow2_co_invalidate_cache
,
5545 .bdrv_inactivate
= qcow2_inactivate
,
5547 .create_opts
= &qcow2_create_opts
,
5548 .strong_runtime_opts
= qcow2_strong_runtime_opts
,
5549 .mutable_opts
= mutable_opts
,
5550 .bdrv_co_check
= qcow2_co_check
,
5551 .bdrv_amend_options
= qcow2_amend_options
,
5553 .bdrv_detach_aio_context
= qcow2_detach_aio_context
,
5554 .bdrv_attach_aio_context
= qcow2_attach_aio_context
,
5556 .bdrv_co_can_store_new_dirty_bitmap
= qcow2_co_can_store_new_dirty_bitmap
,
5557 .bdrv_co_remove_persistent_dirty_bitmap
=
5558 qcow2_co_remove_persistent_dirty_bitmap
,
5561 static void bdrv_qcow2_init(void)
5563 bdrv_register(&bdrv_qcow2
);
5566 block_init(bdrv_qcow2_init
);