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/module.h"
31 #include "qemu/error-report.h"
32 #include "qapi/error.h"
33 #include "qapi/qapi-events-block-core.h"
34 #include "qapi/qmp/qdict.h"
35 #include "qapi/qmp/qstring.h"
37 #include "qemu/option_int.h"
38 #include "qemu/cutils.h"
39 #include "qemu/bswap.h"
40 #include "qapi/qobject-input-visitor.h"
41 #include "qapi/qapi-visit-block-core.h"
45 Differences with QCOW:
47 - Support for multiple incremental snapshots.
48 - Memory management by reference counts.
49 - Clusters which have a reference count of one have the bit
50 QCOW_OFLAG_COPIED to optimize write performance.
51 - Size of compressed clusters is stored in sectors to reduce bit usage
52 in the cluster offsets.
53 - Support for storing additional data (such as the VM state) in the
55 - If a backing store is used, the cluster size is not constrained
56 (could be backported to QCOW).
57 - L2 tables have always a size of one cluster.
64 } QEMU_PACKED QCowExtension
;
66 #define QCOW2_EXT_MAGIC_END 0
67 #define QCOW2_EXT_MAGIC_BACKING_FORMAT 0xE2792ACA
68 #define QCOW2_EXT_MAGIC_FEATURE_TABLE 0x6803f857
69 #define QCOW2_EXT_MAGIC_CRYPTO_HEADER 0x0537be77
70 #define QCOW2_EXT_MAGIC_BITMAPS 0x23852875
71 #define QCOW2_EXT_MAGIC_DATA_FILE 0x44415441
73 static int coroutine_fn
74 qcow2_co_preadv_compressed(BlockDriverState
*bs
,
75 uint64_t file_cluster_offset
,
80 static int qcow2_probe(const uint8_t *buf
, int buf_size
, const char *filename
)
82 const QCowHeader
*cow_header
= (const void *)buf
;
84 if (buf_size
>= sizeof(QCowHeader
) &&
85 be32_to_cpu(cow_header
->magic
) == QCOW_MAGIC
&&
86 be32_to_cpu(cow_header
->version
) >= 2)
93 static ssize_t
qcow2_crypto_hdr_read_func(QCryptoBlock
*block
, size_t offset
,
94 uint8_t *buf
, size_t buflen
,
95 void *opaque
, Error
**errp
)
97 BlockDriverState
*bs
= opaque
;
98 BDRVQcow2State
*s
= bs
->opaque
;
101 if ((offset
+ buflen
) > s
->crypto_header
.length
) {
102 error_setg(errp
, "Request for data outside of extension header");
106 ret
= bdrv_pread(bs
->file
,
107 s
->crypto_header
.offset
+ offset
, buf
, buflen
);
109 error_setg_errno(errp
, -ret
, "Could not read encryption header");
116 static ssize_t
qcow2_crypto_hdr_init_func(QCryptoBlock
*block
, size_t headerlen
,
117 void *opaque
, Error
**errp
)
119 BlockDriverState
*bs
= opaque
;
120 BDRVQcow2State
*s
= bs
->opaque
;
124 ret
= qcow2_alloc_clusters(bs
, headerlen
);
126 error_setg_errno(errp
, -ret
,
127 "Cannot allocate cluster for LUKS header size %zu",
132 s
->crypto_header
.length
= headerlen
;
133 s
->crypto_header
.offset
= ret
;
135 /* Zero fill remaining space in cluster so it has predictable
136 * content in case of future spec changes */
137 clusterlen
= size_to_clusters(s
, headerlen
) * s
->cluster_size
;
138 assert(qcow2_pre_write_overlap_check(bs
, 0, ret
, clusterlen
, false) == 0);
139 ret
= bdrv_pwrite_zeroes(bs
->file
,
141 clusterlen
- headerlen
, 0);
143 error_setg_errno(errp
, -ret
, "Could not zero fill encryption header");
151 static ssize_t
qcow2_crypto_hdr_write_func(QCryptoBlock
*block
, size_t offset
,
152 const uint8_t *buf
, size_t buflen
,
153 void *opaque
, Error
**errp
)
155 BlockDriverState
*bs
= opaque
;
156 BDRVQcow2State
*s
= bs
->opaque
;
159 if ((offset
+ buflen
) > s
->crypto_header
.length
) {
160 error_setg(errp
, "Request for data outside of extension header");
164 ret
= bdrv_pwrite(bs
->file
,
165 s
->crypto_header
.offset
+ offset
, buf
, buflen
);
167 error_setg_errno(errp
, -ret
, "Could not read encryption header");
175 * read qcow2 extension and fill bs
176 * start reading from start_offset
177 * finish reading upon magic of value 0 or when end_offset reached
178 * unknown magic is skipped (future extension this version knows nothing about)
179 * return 0 upon success, non-0 otherwise
181 static int qcow2_read_extensions(BlockDriverState
*bs
, uint64_t start_offset
,
182 uint64_t end_offset
, void **p_feature_table
,
183 int flags
, bool *need_update_header
,
186 BDRVQcow2State
*s
= bs
->opaque
;
190 Qcow2BitmapHeaderExt bitmaps_ext
;
192 if (need_update_header
!= NULL
) {
193 *need_update_header
= false;
197 printf("qcow2_read_extensions: start=%ld end=%ld\n", start_offset
, end_offset
);
199 offset
= start_offset
;
200 while (offset
< end_offset
) {
204 if (offset
> s
->cluster_size
)
205 printf("qcow2_read_extension: suspicious offset %lu\n", offset
);
207 printf("attempting to read extended header in offset %lu\n", offset
);
210 ret
= bdrv_pread(bs
->file
, offset
, &ext
, sizeof(ext
));
212 error_setg_errno(errp
, -ret
, "qcow2_read_extension: ERROR: "
213 "pread fail from offset %" PRIu64
, offset
);
216 ext
.magic
= be32_to_cpu(ext
.magic
);
217 ext
.len
= be32_to_cpu(ext
.len
);
218 offset
+= sizeof(ext
);
220 printf("ext.magic = 0x%x\n", ext
.magic
);
222 if (offset
> end_offset
|| ext
.len
> end_offset
- offset
) {
223 error_setg(errp
, "Header extension too large");
228 case QCOW2_EXT_MAGIC_END
:
231 case QCOW2_EXT_MAGIC_BACKING_FORMAT
:
232 if (ext
.len
>= sizeof(bs
->backing_format
)) {
233 error_setg(errp
, "ERROR: ext_backing_format: len=%" PRIu32
234 " too large (>=%zu)", ext
.len
,
235 sizeof(bs
->backing_format
));
238 ret
= bdrv_pread(bs
->file
, offset
, bs
->backing_format
, ext
.len
);
240 error_setg_errno(errp
, -ret
, "ERROR: ext_backing_format: "
241 "Could not read format name");
244 bs
->backing_format
[ext
.len
] = '\0';
245 s
->image_backing_format
= g_strdup(bs
->backing_format
);
247 printf("Qcow2: Got format extension %s\n", bs
->backing_format
);
251 case QCOW2_EXT_MAGIC_FEATURE_TABLE
:
252 if (p_feature_table
!= NULL
) {
253 void* feature_table
= g_malloc0(ext
.len
+ 2 * sizeof(Qcow2Feature
));
254 ret
= bdrv_pread(bs
->file
, offset
, feature_table
, ext
.len
);
256 error_setg_errno(errp
, -ret
, "ERROR: ext_feature_table: "
257 "Could not read table");
261 *p_feature_table
= feature_table
;
265 case QCOW2_EXT_MAGIC_CRYPTO_HEADER
: {
266 unsigned int cflags
= 0;
267 if (s
->crypt_method_header
!= QCOW_CRYPT_LUKS
) {
268 error_setg(errp
, "CRYPTO header extension only "
269 "expected with LUKS encryption method");
272 if (ext
.len
!= sizeof(Qcow2CryptoHeaderExtension
)) {
273 error_setg(errp
, "CRYPTO header extension size %u, "
274 "but expected size %zu", ext
.len
,
275 sizeof(Qcow2CryptoHeaderExtension
));
279 ret
= bdrv_pread(bs
->file
, offset
, &s
->crypto_header
, ext
.len
);
281 error_setg_errno(errp
, -ret
,
282 "Unable to read CRYPTO header extension");
285 s
->crypto_header
.offset
= be64_to_cpu(s
->crypto_header
.offset
);
286 s
->crypto_header
.length
= be64_to_cpu(s
->crypto_header
.length
);
288 if ((s
->crypto_header
.offset
% s
->cluster_size
) != 0) {
289 error_setg(errp
, "Encryption header offset '%" PRIu64
"' is "
290 "not a multiple of cluster size '%u'",
291 s
->crypto_header
.offset
, s
->cluster_size
);
295 if (flags
& BDRV_O_NO_IO
) {
296 cflags
|= QCRYPTO_BLOCK_OPEN_NO_IO
;
298 s
->crypto
= qcrypto_block_open(s
->crypto_opts
, "encrypt.",
299 qcow2_crypto_hdr_read_func
,
300 bs
, cflags
, 1, errp
);
306 case QCOW2_EXT_MAGIC_BITMAPS
:
307 if (ext
.len
!= sizeof(bitmaps_ext
)) {
308 error_setg_errno(errp
, -ret
, "bitmaps_ext: "
309 "Invalid extension length");
313 if (!(s
->autoclear_features
& QCOW2_AUTOCLEAR_BITMAPS
)) {
314 if (s
->qcow_version
< 3) {
315 /* Let's be a bit more specific */
316 warn_report("This qcow2 v2 image contains bitmaps, but "
317 "they may have been modified by a program "
318 "without persistent bitmap support; so now "
319 "they must all be considered inconsistent");
321 warn_report("a program lacking bitmap support "
322 "modified this file, so all bitmaps are now "
323 "considered inconsistent");
325 error_printf("Some clusters may be leaked, "
326 "run 'qemu-img check -r' on the image "
328 if (need_update_header
!= NULL
) {
329 /* Updating is needed to drop invalid bitmap extension. */
330 *need_update_header
= true;
335 ret
= bdrv_pread(bs
->file
, offset
, &bitmaps_ext
, ext
.len
);
337 error_setg_errno(errp
, -ret
, "bitmaps_ext: "
338 "Could not read ext header");
342 if (bitmaps_ext
.reserved32
!= 0) {
343 error_setg_errno(errp
, -ret
, "bitmaps_ext: "
344 "Reserved field is not zero");
348 bitmaps_ext
.nb_bitmaps
= be32_to_cpu(bitmaps_ext
.nb_bitmaps
);
349 bitmaps_ext
.bitmap_directory_size
=
350 be64_to_cpu(bitmaps_ext
.bitmap_directory_size
);
351 bitmaps_ext
.bitmap_directory_offset
=
352 be64_to_cpu(bitmaps_ext
.bitmap_directory_offset
);
354 if (bitmaps_ext
.nb_bitmaps
> QCOW2_MAX_BITMAPS
) {
356 "bitmaps_ext: Image has %" PRIu32
" bitmaps, "
357 "exceeding the QEMU supported maximum of %d",
358 bitmaps_ext
.nb_bitmaps
, QCOW2_MAX_BITMAPS
);
362 if (bitmaps_ext
.nb_bitmaps
== 0) {
363 error_setg(errp
, "found bitmaps extension with zero bitmaps");
367 if (bitmaps_ext
.bitmap_directory_offset
& (s
->cluster_size
- 1)) {
368 error_setg(errp
, "bitmaps_ext: "
369 "invalid bitmap directory offset");
373 if (bitmaps_ext
.bitmap_directory_size
>
374 QCOW2_MAX_BITMAP_DIRECTORY_SIZE
) {
375 error_setg(errp
, "bitmaps_ext: "
376 "bitmap directory size (%" PRIu64
") exceeds "
377 "the maximum supported size (%d)",
378 bitmaps_ext
.bitmap_directory_size
,
379 QCOW2_MAX_BITMAP_DIRECTORY_SIZE
);
383 s
->nb_bitmaps
= bitmaps_ext
.nb_bitmaps
;
384 s
->bitmap_directory_offset
=
385 bitmaps_ext
.bitmap_directory_offset
;
386 s
->bitmap_directory_size
=
387 bitmaps_ext
.bitmap_directory_size
;
390 printf("Qcow2: Got bitmaps extension: "
391 "offset=%" PRIu64
" nb_bitmaps=%" PRIu32
"\n",
392 s
->bitmap_directory_offset
, s
->nb_bitmaps
);
396 case QCOW2_EXT_MAGIC_DATA_FILE
:
398 s
->image_data_file
= g_malloc0(ext
.len
+ 1);
399 ret
= bdrv_pread(bs
->file
, offset
, s
->image_data_file
, ext
.len
);
401 error_setg_errno(errp
, -ret
,
402 "ERROR: Could not read data file name");
406 printf("Qcow2: Got external data file %s\n", s
->image_data_file
);
412 /* unknown magic - save it in case we need to rewrite the header */
413 /* If you add a new feature, make sure to also update the fast
414 * path of qcow2_make_empty() to deal with it. */
416 Qcow2UnknownHeaderExtension
*uext
;
418 uext
= g_malloc0(sizeof(*uext
) + ext
.len
);
419 uext
->magic
= ext
.magic
;
421 QLIST_INSERT_HEAD(&s
->unknown_header_ext
, uext
, next
);
423 ret
= bdrv_pread(bs
->file
, offset
, uext
->data
, uext
->len
);
425 error_setg_errno(errp
, -ret
, "ERROR: unknown extension: "
426 "Could not read data");
433 offset
+= ((ext
.len
+ 7) & ~7);
439 static void cleanup_unknown_header_ext(BlockDriverState
*bs
)
441 BDRVQcow2State
*s
= bs
->opaque
;
442 Qcow2UnknownHeaderExtension
*uext
, *next
;
444 QLIST_FOREACH_SAFE(uext
, &s
->unknown_header_ext
, next
, next
) {
445 QLIST_REMOVE(uext
, next
);
450 static void report_unsupported_feature(Error
**errp
, Qcow2Feature
*table
,
453 char *features
= g_strdup("");
456 while (table
&& table
->name
[0] != '\0') {
457 if (table
->type
== QCOW2_FEAT_TYPE_INCOMPATIBLE
) {
458 if (mask
& (1ULL << table
->bit
)) {
460 features
= g_strdup_printf("%s%s%.46s", old
, *old
? ", " : "",
463 mask
&= ~(1ULL << table
->bit
);
471 features
= g_strdup_printf("%s%sUnknown incompatible feature: %" PRIx64
,
472 old
, *old
? ", " : "", mask
);
476 error_setg(errp
, "Unsupported qcow2 feature(s): %s", features
);
481 * Sets the dirty bit and flushes afterwards if necessary.
483 * The incompatible_features bit is only set if the image file header was
484 * updated successfully. Therefore it is not required to check the return
485 * value of this function.
487 int qcow2_mark_dirty(BlockDriverState
*bs
)
489 BDRVQcow2State
*s
= bs
->opaque
;
493 assert(s
->qcow_version
>= 3);
495 if (s
->incompatible_features
& QCOW2_INCOMPAT_DIRTY
) {
496 return 0; /* already dirty */
499 val
= cpu_to_be64(s
->incompatible_features
| QCOW2_INCOMPAT_DIRTY
);
500 ret
= bdrv_pwrite(bs
->file
, offsetof(QCowHeader
, incompatible_features
),
505 ret
= bdrv_flush(bs
->file
->bs
);
510 /* Only treat image as dirty if the header was updated successfully */
511 s
->incompatible_features
|= QCOW2_INCOMPAT_DIRTY
;
516 * Clears the dirty bit and flushes before if necessary. Only call this
517 * function when there are no pending requests, it does not guard against
518 * concurrent requests dirtying the image.
520 static int qcow2_mark_clean(BlockDriverState
*bs
)
522 BDRVQcow2State
*s
= bs
->opaque
;
524 if (s
->incompatible_features
& QCOW2_INCOMPAT_DIRTY
) {
527 s
->incompatible_features
&= ~QCOW2_INCOMPAT_DIRTY
;
529 ret
= qcow2_flush_caches(bs
);
534 return qcow2_update_header(bs
);
540 * Marks the image as corrupt.
542 int qcow2_mark_corrupt(BlockDriverState
*bs
)
544 BDRVQcow2State
*s
= bs
->opaque
;
546 s
->incompatible_features
|= QCOW2_INCOMPAT_CORRUPT
;
547 return qcow2_update_header(bs
);
551 * Marks the image as consistent, i.e., unsets the corrupt bit, and flushes
552 * before if necessary.
554 int qcow2_mark_consistent(BlockDriverState
*bs
)
556 BDRVQcow2State
*s
= bs
->opaque
;
558 if (s
->incompatible_features
& QCOW2_INCOMPAT_CORRUPT
) {
559 int ret
= qcow2_flush_caches(bs
);
564 s
->incompatible_features
&= ~QCOW2_INCOMPAT_CORRUPT
;
565 return qcow2_update_header(bs
);
570 static int coroutine_fn
qcow2_co_check_locked(BlockDriverState
*bs
,
571 BdrvCheckResult
*result
,
574 int ret
= qcow2_check_refcounts(bs
, result
, fix
);
579 if (fix
&& result
->check_errors
== 0 && result
->corruptions
== 0) {
580 ret
= qcow2_mark_clean(bs
);
584 return qcow2_mark_consistent(bs
);
589 static int coroutine_fn
qcow2_co_check(BlockDriverState
*bs
,
590 BdrvCheckResult
*result
,
593 BDRVQcow2State
*s
= bs
->opaque
;
596 qemu_co_mutex_lock(&s
->lock
);
597 ret
= qcow2_co_check_locked(bs
, result
, fix
);
598 qemu_co_mutex_unlock(&s
->lock
);
602 int qcow2_validate_table(BlockDriverState
*bs
, uint64_t offset
,
603 uint64_t entries
, size_t entry_len
,
604 int64_t max_size_bytes
, const char *table_name
,
607 BDRVQcow2State
*s
= bs
->opaque
;
609 if (entries
> max_size_bytes
/ entry_len
) {
610 error_setg(errp
, "%s too large", table_name
);
614 /* Use signed INT64_MAX as the maximum even for uint64_t header fields,
615 * because values will be passed to qemu functions taking int64_t. */
616 if ((INT64_MAX
- entries
* entry_len
< offset
) ||
617 (offset_into_cluster(s
, offset
) != 0)) {
618 error_setg(errp
, "%s offset invalid", table_name
);
625 static const char *const mutable_opts
[] = {
626 QCOW2_OPT_LAZY_REFCOUNTS
,
627 QCOW2_OPT_DISCARD_REQUEST
,
628 QCOW2_OPT_DISCARD_SNAPSHOT
,
629 QCOW2_OPT_DISCARD_OTHER
,
631 QCOW2_OPT_OVERLAP_TEMPLATE
,
632 QCOW2_OPT_OVERLAP_MAIN_HEADER
,
633 QCOW2_OPT_OVERLAP_ACTIVE_L1
,
634 QCOW2_OPT_OVERLAP_ACTIVE_L2
,
635 QCOW2_OPT_OVERLAP_REFCOUNT_TABLE
,
636 QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK
,
637 QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE
,
638 QCOW2_OPT_OVERLAP_INACTIVE_L1
,
639 QCOW2_OPT_OVERLAP_INACTIVE_L2
,
640 QCOW2_OPT_OVERLAP_BITMAP_DIRECTORY
,
641 QCOW2_OPT_CACHE_SIZE
,
642 QCOW2_OPT_L2_CACHE_SIZE
,
643 QCOW2_OPT_L2_CACHE_ENTRY_SIZE
,
644 QCOW2_OPT_REFCOUNT_CACHE_SIZE
,
645 QCOW2_OPT_CACHE_CLEAN_INTERVAL
,
649 static QemuOptsList qcow2_runtime_opts
= {
651 .head
= QTAILQ_HEAD_INITIALIZER(qcow2_runtime_opts
.head
),
654 .name
= QCOW2_OPT_LAZY_REFCOUNTS
,
655 .type
= QEMU_OPT_BOOL
,
656 .help
= "Postpone refcount updates",
659 .name
= QCOW2_OPT_DISCARD_REQUEST
,
660 .type
= QEMU_OPT_BOOL
,
661 .help
= "Pass guest discard requests to the layer below",
664 .name
= QCOW2_OPT_DISCARD_SNAPSHOT
,
665 .type
= QEMU_OPT_BOOL
,
666 .help
= "Generate discard requests when snapshot related space "
670 .name
= QCOW2_OPT_DISCARD_OTHER
,
671 .type
= QEMU_OPT_BOOL
,
672 .help
= "Generate discard requests when other clusters are freed",
675 .name
= QCOW2_OPT_OVERLAP
,
676 .type
= QEMU_OPT_STRING
,
677 .help
= "Selects which overlap checks to perform from a range of "
678 "templates (none, constant, cached, all)",
681 .name
= QCOW2_OPT_OVERLAP_TEMPLATE
,
682 .type
= QEMU_OPT_STRING
,
683 .help
= "Selects which overlap checks to perform from a range of "
684 "templates (none, constant, cached, all)",
687 .name
= QCOW2_OPT_OVERLAP_MAIN_HEADER
,
688 .type
= QEMU_OPT_BOOL
,
689 .help
= "Check for unintended writes into the main qcow2 header",
692 .name
= QCOW2_OPT_OVERLAP_ACTIVE_L1
,
693 .type
= QEMU_OPT_BOOL
,
694 .help
= "Check for unintended writes into the active L1 table",
697 .name
= QCOW2_OPT_OVERLAP_ACTIVE_L2
,
698 .type
= QEMU_OPT_BOOL
,
699 .help
= "Check for unintended writes into an active L2 table",
702 .name
= QCOW2_OPT_OVERLAP_REFCOUNT_TABLE
,
703 .type
= QEMU_OPT_BOOL
,
704 .help
= "Check for unintended writes into the refcount table",
707 .name
= QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK
,
708 .type
= QEMU_OPT_BOOL
,
709 .help
= "Check for unintended writes into a refcount block",
712 .name
= QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE
,
713 .type
= QEMU_OPT_BOOL
,
714 .help
= "Check for unintended writes into the snapshot table",
717 .name
= QCOW2_OPT_OVERLAP_INACTIVE_L1
,
718 .type
= QEMU_OPT_BOOL
,
719 .help
= "Check for unintended writes into an inactive L1 table",
722 .name
= QCOW2_OPT_OVERLAP_INACTIVE_L2
,
723 .type
= QEMU_OPT_BOOL
,
724 .help
= "Check for unintended writes into an inactive L2 table",
727 .name
= QCOW2_OPT_OVERLAP_BITMAP_DIRECTORY
,
728 .type
= QEMU_OPT_BOOL
,
729 .help
= "Check for unintended writes into the bitmap directory",
732 .name
= QCOW2_OPT_CACHE_SIZE
,
733 .type
= QEMU_OPT_SIZE
,
734 .help
= "Maximum combined metadata (L2 tables and refcount blocks) "
738 .name
= QCOW2_OPT_L2_CACHE_SIZE
,
739 .type
= QEMU_OPT_SIZE
,
740 .help
= "Maximum L2 table cache size",
743 .name
= QCOW2_OPT_L2_CACHE_ENTRY_SIZE
,
744 .type
= QEMU_OPT_SIZE
,
745 .help
= "Size of each entry in the L2 cache",
748 .name
= QCOW2_OPT_REFCOUNT_CACHE_SIZE
,
749 .type
= QEMU_OPT_SIZE
,
750 .help
= "Maximum refcount block cache size",
753 .name
= QCOW2_OPT_CACHE_CLEAN_INTERVAL
,
754 .type
= QEMU_OPT_NUMBER
,
755 .help
= "Clean unused cache entries after this time (in seconds)",
757 BLOCK_CRYPTO_OPT_DEF_KEY_SECRET("encrypt.",
758 "ID of secret providing qcow2 AES key or LUKS passphrase"),
759 { /* end of list */ }
763 static const char *overlap_bool_option_names
[QCOW2_OL_MAX_BITNR
] = {
764 [QCOW2_OL_MAIN_HEADER_BITNR
] = QCOW2_OPT_OVERLAP_MAIN_HEADER
,
765 [QCOW2_OL_ACTIVE_L1_BITNR
] = QCOW2_OPT_OVERLAP_ACTIVE_L1
,
766 [QCOW2_OL_ACTIVE_L2_BITNR
] = QCOW2_OPT_OVERLAP_ACTIVE_L2
,
767 [QCOW2_OL_REFCOUNT_TABLE_BITNR
] = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE
,
768 [QCOW2_OL_REFCOUNT_BLOCK_BITNR
] = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK
,
769 [QCOW2_OL_SNAPSHOT_TABLE_BITNR
] = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE
,
770 [QCOW2_OL_INACTIVE_L1_BITNR
] = QCOW2_OPT_OVERLAP_INACTIVE_L1
,
771 [QCOW2_OL_INACTIVE_L2_BITNR
] = QCOW2_OPT_OVERLAP_INACTIVE_L2
,
772 [QCOW2_OL_BITMAP_DIRECTORY_BITNR
] = QCOW2_OPT_OVERLAP_BITMAP_DIRECTORY
,
775 static void cache_clean_timer_cb(void *opaque
)
777 BlockDriverState
*bs
= opaque
;
778 BDRVQcow2State
*s
= bs
->opaque
;
779 qcow2_cache_clean_unused(s
->l2_table_cache
);
780 qcow2_cache_clean_unused(s
->refcount_block_cache
);
781 timer_mod(s
->cache_clean_timer
, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL
) +
782 (int64_t) s
->cache_clean_interval
* 1000);
785 static void cache_clean_timer_init(BlockDriverState
*bs
, AioContext
*context
)
787 BDRVQcow2State
*s
= bs
->opaque
;
788 if (s
->cache_clean_interval
> 0) {
789 s
->cache_clean_timer
= aio_timer_new(context
, QEMU_CLOCK_VIRTUAL
,
790 SCALE_MS
, cache_clean_timer_cb
,
792 timer_mod(s
->cache_clean_timer
, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL
) +
793 (int64_t) s
->cache_clean_interval
* 1000);
797 static void cache_clean_timer_del(BlockDriverState
*bs
)
799 BDRVQcow2State
*s
= bs
->opaque
;
800 if (s
->cache_clean_timer
) {
801 timer_del(s
->cache_clean_timer
);
802 timer_free(s
->cache_clean_timer
);
803 s
->cache_clean_timer
= NULL
;
807 static void qcow2_detach_aio_context(BlockDriverState
*bs
)
809 cache_clean_timer_del(bs
);
812 static void qcow2_attach_aio_context(BlockDriverState
*bs
,
813 AioContext
*new_context
)
815 cache_clean_timer_init(bs
, new_context
);
818 static void read_cache_sizes(BlockDriverState
*bs
, QemuOpts
*opts
,
819 uint64_t *l2_cache_size
,
820 uint64_t *l2_cache_entry_size
,
821 uint64_t *refcount_cache_size
, Error
**errp
)
823 BDRVQcow2State
*s
= bs
->opaque
;
824 uint64_t combined_cache_size
, l2_cache_max_setting
;
825 bool l2_cache_size_set
, refcount_cache_size_set
, combined_cache_size_set
;
826 bool l2_cache_entry_size_set
;
827 int min_refcount_cache
= MIN_REFCOUNT_CACHE_SIZE
* s
->cluster_size
;
828 uint64_t virtual_disk_size
= bs
->total_sectors
* BDRV_SECTOR_SIZE
;
829 uint64_t max_l2_cache
= virtual_disk_size
/ (s
->cluster_size
/ 8);
831 combined_cache_size_set
= qemu_opt_get(opts
, QCOW2_OPT_CACHE_SIZE
);
832 l2_cache_size_set
= qemu_opt_get(opts
, QCOW2_OPT_L2_CACHE_SIZE
);
833 refcount_cache_size_set
= qemu_opt_get(opts
, QCOW2_OPT_REFCOUNT_CACHE_SIZE
);
834 l2_cache_entry_size_set
= qemu_opt_get(opts
, QCOW2_OPT_L2_CACHE_ENTRY_SIZE
);
836 combined_cache_size
= qemu_opt_get_size(opts
, QCOW2_OPT_CACHE_SIZE
, 0);
837 l2_cache_max_setting
= qemu_opt_get_size(opts
, QCOW2_OPT_L2_CACHE_SIZE
,
838 DEFAULT_L2_CACHE_MAX_SIZE
);
839 *refcount_cache_size
= qemu_opt_get_size(opts
,
840 QCOW2_OPT_REFCOUNT_CACHE_SIZE
, 0);
842 *l2_cache_entry_size
= qemu_opt_get_size(
843 opts
, QCOW2_OPT_L2_CACHE_ENTRY_SIZE
, s
->cluster_size
);
845 *l2_cache_size
= MIN(max_l2_cache
, l2_cache_max_setting
);
847 if (combined_cache_size_set
) {
848 if (l2_cache_size_set
&& refcount_cache_size_set
) {
849 error_setg(errp
, QCOW2_OPT_CACHE_SIZE
", " QCOW2_OPT_L2_CACHE_SIZE
850 " and " QCOW2_OPT_REFCOUNT_CACHE_SIZE
" may not be set "
853 } else if (l2_cache_size_set
&&
854 (l2_cache_max_setting
> combined_cache_size
)) {
855 error_setg(errp
, QCOW2_OPT_L2_CACHE_SIZE
" may not exceed "
856 QCOW2_OPT_CACHE_SIZE
);
858 } else if (*refcount_cache_size
> combined_cache_size
) {
859 error_setg(errp
, QCOW2_OPT_REFCOUNT_CACHE_SIZE
" may not exceed "
860 QCOW2_OPT_CACHE_SIZE
);
864 if (l2_cache_size_set
) {
865 *refcount_cache_size
= combined_cache_size
- *l2_cache_size
;
866 } else if (refcount_cache_size_set
) {
867 *l2_cache_size
= combined_cache_size
- *refcount_cache_size
;
869 /* Assign as much memory as possible to the L2 cache, and
870 * use the remainder for the refcount cache */
871 if (combined_cache_size
>= max_l2_cache
+ min_refcount_cache
) {
872 *l2_cache_size
= max_l2_cache
;
873 *refcount_cache_size
= combined_cache_size
- *l2_cache_size
;
875 *refcount_cache_size
=
876 MIN(combined_cache_size
, min_refcount_cache
);
877 *l2_cache_size
= combined_cache_size
- *refcount_cache_size
;
883 * If the L2 cache is not enough to cover the whole disk then
884 * default to 4KB entries. Smaller entries reduce the cost of
885 * loads and evictions and increase I/O performance.
887 if (*l2_cache_size
< max_l2_cache
&& !l2_cache_entry_size_set
) {
888 *l2_cache_entry_size
= MIN(s
->cluster_size
, 4096);
891 /* l2_cache_size and refcount_cache_size are ensured to have at least
892 * their minimum values in qcow2_update_options_prepare() */
894 if (*l2_cache_entry_size
< (1 << MIN_CLUSTER_BITS
) ||
895 *l2_cache_entry_size
> s
->cluster_size
||
896 !is_power_of_2(*l2_cache_entry_size
)) {
897 error_setg(errp
, "L2 cache entry size must be a power of two "
898 "between %d and the cluster size (%d)",
899 1 << MIN_CLUSTER_BITS
, s
->cluster_size
);
904 typedef struct Qcow2ReopenState
{
905 Qcow2Cache
*l2_table_cache
;
906 Qcow2Cache
*refcount_block_cache
;
907 int l2_slice_size
; /* Number of entries in a slice of the L2 table */
908 bool use_lazy_refcounts
;
910 bool discard_passthrough
[QCOW2_DISCARD_MAX
];
911 uint64_t cache_clean_interval
;
912 QCryptoBlockOpenOptions
*crypto_opts
; /* Disk encryption runtime options */
915 static int qcow2_update_options_prepare(BlockDriverState
*bs
,
917 QDict
*options
, int flags
,
920 BDRVQcow2State
*s
= bs
->opaque
;
921 QemuOpts
*opts
= NULL
;
922 const char *opt_overlap_check
, *opt_overlap_check_template
;
923 int overlap_check_template
= 0;
924 uint64_t l2_cache_size
, l2_cache_entry_size
, refcount_cache_size
;
926 const char *encryptfmt
;
927 QDict
*encryptopts
= NULL
;
928 Error
*local_err
= NULL
;
931 qdict_extract_subqdict(options
, &encryptopts
, "encrypt.");
932 encryptfmt
= qdict_get_try_str(encryptopts
, "format");
934 opts
= qemu_opts_create(&qcow2_runtime_opts
, NULL
, 0, &error_abort
);
935 qemu_opts_absorb_qdict(opts
, options
, &local_err
);
937 error_propagate(errp
, local_err
);
942 /* get L2 table/refcount block cache size from command line options */
943 read_cache_sizes(bs
, opts
, &l2_cache_size
, &l2_cache_entry_size
,
944 &refcount_cache_size
, &local_err
);
946 error_propagate(errp
, local_err
);
951 l2_cache_size
/= l2_cache_entry_size
;
952 if (l2_cache_size
< MIN_L2_CACHE_SIZE
) {
953 l2_cache_size
= MIN_L2_CACHE_SIZE
;
955 if (l2_cache_size
> INT_MAX
) {
956 error_setg(errp
, "L2 cache size too big");
961 refcount_cache_size
/= s
->cluster_size
;
962 if (refcount_cache_size
< MIN_REFCOUNT_CACHE_SIZE
) {
963 refcount_cache_size
= MIN_REFCOUNT_CACHE_SIZE
;
965 if (refcount_cache_size
> INT_MAX
) {
966 error_setg(errp
, "Refcount cache size too big");
971 /* alloc new L2 table/refcount block cache, flush old one */
972 if (s
->l2_table_cache
) {
973 ret
= qcow2_cache_flush(bs
, s
->l2_table_cache
);
975 error_setg_errno(errp
, -ret
, "Failed to flush the L2 table cache");
980 if (s
->refcount_block_cache
) {
981 ret
= qcow2_cache_flush(bs
, s
->refcount_block_cache
);
983 error_setg_errno(errp
, -ret
,
984 "Failed to flush the refcount block cache");
989 r
->l2_slice_size
= l2_cache_entry_size
/ sizeof(uint64_t);
990 r
->l2_table_cache
= qcow2_cache_create(bs
, l2_cache_size
,
991 l2_cache_entry_size
);
992 r
->refcount_block_cache
= qcow2_cache_create(bs
, refcount_cache_size
,
994 if (r
->l2_table_cache
== NULL
|| r
->refcount_block_cache
== NULL
) {
995 error_setg(errp
, "Could not allocate metadata caches");
1000 /* New interval for cache cleanup timer */
1001 r
->cache_clean_interval
=
1002 qemu_opt_get_number(opts
, QCOW2_OPT_CACHE_CLEAN_INTERVAL
,
1003 DEFAULT_CACHE_CLEAN_INTERVAL
);
1004 #ifndef CONFIG_LINUX
1005 if (r
->cache_clean_interval
!= 0) {
1006 error_setg(errp
, QCOW2_OPT_CACHE_CLEAN_INTERVAL
1007 " not supported on this host");
1012 if (r
->cache_clean_interval
> UINT_MAX
) {
1013 error_setg(errp
, "Cache clean interval too big");
1018 /* lazy-refcounts; flush if going from enabled to disabled */
1019 r
->use_lazy_refcounts
= qemu_opt_get_bool(opts
, QCOW2_OPT_LAZY_REFCOUNTS
,
1020 (s
->compatible_features
& QCOW2_COMPAT_LAZY_REFCOUNTS
));
1021 if (r
->use_lazy_refcounts
&& s
->qcow_version
< 3) {
1022 error_setg(errp
, "Lazy refcounts require a qcow2 image with at least "
1023 "qemu 1.1 compatibility level");
1028 if (s
->use_lazy_refcounts
&& !r
->use_lazy_refcounts
) {
1029 ret
= qcow2_mark_clean(bs
);
1031 error_setg_errno(errp
, -ret
, "Failed to disable lazy refcounts");
1036 /* Overlap check options */
1037 opt_overlap_check
= qemu_opt_get(opts
, QCOW2_OPT_OVERLAP
);
1038 opt_overlap_check_template
= qemu_opt_get(opts
, QCOW2_OPT_OVERLAP_TEMPLATE
);
1039 if (opt_overlap_check_template
&& opt_overlap_check
&&
1040 strcmp(opt_overlap_check_template
, opt_overlap_check
))
1042 error_setg(errp
, "Conflicting values for qcow2 options '"
1043 QCOW2_OPT_OVERLAP
"' ('%s') and '" QCOW2_OPT_OVERLAP_TEMPLATE
1044 "' ('%s')", opt_overlap_check
, opt_overlap_check_template
);
1048 if (!opt_overlap_check
) {
1049 opt_overlap_check
= opt_overlap_check_template
?: "cached";
1052 if (!strcmp(opt_overlap_check
, "none")) {
1053 overlap_check_template
= 0;
1054 } else if (!strcmp(opt_overlap_check
, "constant")) {
1055 overlap_check_template
= QCOW2_OL_CONSTANT
;
1056 } else if (!strcmp(opt_overlap_check
, "cached")) {
1057 overlap_check_template
= QCOW2_OL_CACHED
;
1058 } else if (!strcmp(opt_overlap_check
, "all")) {
1059 overlap_check_template
= QCOW2_OL_ALL
;
1061 error_setg(errp
, "Unsupported value '%s' for qcow2 option "
1062 "'overlap-check'. Allowed are any of the following: "
1063 "none, constant, cached, all", opt_overlap_check
);
1068 r
->overlap_check
= 0;
1069 for (i
= 0; i
< QCOW2_OL_MAX_BITNR
; i
++) {
1070 /* overlap-check defines a template bitmask, but every flag may be
1071 * overwritten through the associated boolean option */
1073 qemu_opt_get_bool(opts
, overlap_bool_option_names
[i
],
1074 overlap_check_template
& (1 << i
)) << i
;
1077 r
->discard_passthrough
[QCOW2_DISCARD_NEVER
] = false;
1078 r
->discard_passthrough
[QCOW2_DISCARD_ALWAYS
] = true;
1079 r
->discard_passthrough
[QCOW2_DISCARD_REQUEST
] =
1080 qemu_opt_get_bool(opts
, QCOW2_OPT_DISCARD_REQUEST
,
1081 flags
& BDRV_O_UNMAP
);
1082 r
->discard_passthrough
[QCOW2_DISCARD_SNAPSHOT
] =
1083 qemu_opt_get_bool(opts
, QCOW2_OPT_DISCARD_SNAPSHOT
, true);
1084 r
->discard_passthrough
[QCOW2_DISCARD_OTHER
] =
1085 qemu_opt_get_bool(opts
, QCOW2_OPT_DISCARD_OTHER
, false);
1087 switch (s
->crypt_method_header
) {
1088 case QCOW_CRYPT_NONE
:
1090 error_setg(errp
, "No encryption in image header, but options "
1091 "specified format '%s'", encryptfmt
);
1097 case QCOW_CRYPT_AES
:
1098 if (encryptfmt
&& !g_str_equal(encryptfmt
, "aes")) {
1100 "Header reported 'aes' encryption format but "
1101 "options specify '%s'", encryptfmt
);
1105 qdict_put_str(encryptopts
, "format", "qcow");
1106 r
->crypto_opts
= block_crypto_open_opts_init(encryptopts
, errp
);
1109 case QCOW_CRYPT_LUKS
:
1110 if (encryptfmt
&& !g_str_equal(encryptfmt
, "luks")) {
1112 "Header reported 'luks' encryption format but "
1113 "options specify '%s'", encryptfmt
);
1117 qdict_put_str(encryptopts
, "format", "luks");
1118 r
->crypto_opts
= block_crypto_open_opts_init(encryptopts
, errp
);
1122 error_setg(errp
, "Unsupported encryption method %d",
1123 s
->crypt_method_header
);
1126 if (s
->crypt_method_header
!= QCOW_CRYPT_NONE
&& !r
->crypto_opts
) {
1133 qobject_unref(encryptopts
);
1134 qemu_opts_del(opts
);
1139 static void qcow2_update_options_commit(BlockDriverState
*bs
,
1140 Qcow2ReopenState
*r
)
1142 BDRVQcow2State
*s
= bs
->opaque
;
1145 if (s
->l2_table_cache
) {
1146 qcow2_cache_destroy(s
->l2_table_cache
);
1148 if (s
->refcount_block_cache
) {
1149 qcow2_cache_destroy(s
->refcount_block_cache
);
1151 s
->l2_table_cache
= r
->l2_table_cache
;
1152 s
->refcount_block_cache
= r
->refcount_block_cache
;
1153 s
->l2_slice_size
= r
->l2_slice_size
;
1155 s
->overlap_check
= r
->overlap_check
;
1156 s
->use_lazy_refcounts
= r
->use_lazy_refcounts
;
1158 for (i
= 0; i
< QCOW2_DISCARD_MAX
; i
++) {
1159 s
->discard_passthrough
[i
] = r
->discard_passthrough
[i
];
1162 if (s
->cache_clean_interval
!= r
->cache_clean_interval
) {
1163 cache_clean_timer_del(bs
);
1164 s
->cache_clean_interval
= r
->cache_clean_interval
;
1165 cache_clean_timer_init(bs
, bdrv_get_aio_context(bs
));
1168 qapi_free_QCryptoBlockOpenOptions(s
->crypto_opts
);
1169 s
->crypto_opts
= r
->crypto_opts
;
1172 static void qcow2_update_options_abort(BlockDriverState
*bs
,
1173 Qcow2ReopenState
*r
)
1175 if (r
->l2_table_cache
) {
1176 qcow2_cache_destroy(r
->l2_table_cache
);
1178 if (r
->refcount_block_cache
) {
1179 qcow2_cache_destroy(r
->refcount_block_cache
);
1181 qapi_free_QCryptoBlockOpenOptions(r
->crypto_opts
);
1184 static int qcow2_update_options(BlockDriverState
*bs
, QDict
*options
,
1185 int flags
, Error
**errp
)
1187 Qcow2ReopenState r
= {};
1190 ret
= qcow2_update_options_prepare(bs
, &r
, options
, flags
, errp
);
1192 qcow2_update_options_commit(bs
, &r
);
1194 qcow2_update_options_abort(bs
, &r
);
1200 /* Called with s->lock held. */
1201 static int coroutine_fn
qcow2_do_open(BlockDriverState
*bs
, QDict
*options
,
1202 int flags
, Error
**errp
)
1204 BDRVQcow2State
*s
= bs
->opaque
;
1205 unsigned int len
, i
;
1208 Error
*local_err
= NULL
;
1210 uint64_t l1_vm_state_index
;
1211 bool update_header
= false;
1213 ret
= bdrv_pread(bs
->file
, 0, &header
, sizeof(header
));
1215 error_setg_errno(errp
, -ret
, "Could not read qcow2 header");
1218 header
.magic
= be32_to_cpu(header
.magic
);
1219 header
.version
= be32_to_cpu(header
.version
);
1220 header
.backing_file_offset
= be64_to_cpu(header
.backing_file_offset
);
1221 header
.backing_file_size
= be32_to_cpu(header
.backing_file_size
);
1222 header
.size
= be64_to_cpu(header
.size
);
1223 header
.cluster_bits
= be32_to_cpu(header
.cluster_bits
);
1224 header
.crypt_method
= be32_to_cpu(header
.crypt_method
);
1225 header
.l1_table_offset
= be64_to_cpu(header
.l1_table_offset
);
1226 header
.l1_size
= be32_to_cpu(header
.l1_size
);
1227 header
.refcount_table_offset
= be64_to_cpu(header
.refcount_table_offset
);
1228 header
.refcount_table_clusters
=
1229 be32_to_cpu(header
.refcount_table_clusters
);
1230 header
.snapshots_offset
= be64_to_cpu(header
.snapshots_offset
);
1231 header
.nb_snapshots
= be32_to_cpu(header
.nb_snapshots
);
1233 if (header
.magic
!= QCOW_MAGIC
) {
1234 error_setg(errp
, "Image is not in qcow2 format");
1238 if (header
.version
< 2 || header
.version
> 3) {
1239 error_setg(errp
, "Unsupported qcow2 version %" PRIu32
, header
.version
);
1244 s
->qcow_version
= header
.version
;
1246 /* Initialise cluster size */
1247 if (header
.cluster_bits
< MIN_CLUSTER_BITS
||
1248 header
.cluster_bits
> MAX_CLUSTER_BITS
) {
1249 error_setg(errp
, "Unsupported cluster size: 2^%" PRIu32
,
1250 header
.cluster_bits
);
1255 s
->cluster_bits
= header
.cluster_bits
;
1256 s
->cluster_size
= 1 << s
->cluster_bits
;
1258 /* Initialise version 3 header fields */
1259 if (header
.version
== 2) {
1260 header
.incompatible_features
= 0;
1261 header
.compatible_features
= 0;
1262 header
.autoclear_features
= 0;
1263 header
.refcount_order
= 4;
1264 header
.header_length
= 72;
1266 header
.incompatible_features
=
1267 be64_to_cpu(header
.incompatible_features
);
1268 header
.compatible_features
= be64_to_cpu(header
.compatible_features
);
1269 header
.autoclear_features
= be64_to_cpu(header
.autoclear_features
);
1270 header
.refcount_order
= be32_to_cpu(header
.refcount_order
);
1271 header
.header_length
= be32_to_cpu(header
.header_length
);
1273 if (header
.header_length
< 104) {
1274 error_setg(errp
, "qcow2 header too short");
1280 if (header
.header_length
> s
->cluster_size
) {
1281 error_setg(errp
, "qcow2 header exceeds cluster size");
1286 if (header
.header_length
> sizeof(header
)) {
1287 s
->unknown_header_fields_size
= header
.header_length
- sizeof(header
);
1288 s
->unknown_header_fields
= g_malloc(s
->unknown_header_fields_size
);
1289 ret
= bdrv_pread(bs
->file
, sizeof(header
), s
->unknown_header_fields
,
1290 s
->unknown_header_fields_size
);
1292 error_setg_errno(errp
, -ret
, "Could not read unknown qcow2 header "
1298 if (header
.backing_file_offset
> s
->cluster_size
) {
1299 error_setg(errp
, "Invalid backing file offset");
1304 if (header
.backing_file_offset
) {
1305 ext_end
= header
.backing_file_offset
;
1307 ext_end
= 1 << header
.cluster_bits
;
1310 /* Handle feature bits */
1311 s
->incompatible_features
= header
.incompatible_features
;
1312 s
->compatible_features
= header
.compatible_features
;
1313 s
->autoclear_features
= header
.autoclear_features
;
1315 if (s
->incompatible_features
& ~QCOW2_INCOMPAT_MASK
) {
1316 void *feature_table
= NULL
;
1317 qcow2_read_extensions(bs
, header
.header_length
, ext_end
,
1318 &feature_table
, flags
, NULL
, NULL
);
1319 report_unsupported_feature(errp
, feature_table
,
1320 s
->incompatible_features
&
1321 ~QCOW2_INCOMPAT_MASK
);
1323 g_free(feature_table
);
1327 if (s
->incompatible_features
& QCOW2_INCOMPAT_CORRUPT
) {
1328 /* Corrupt images may not be written to unless they are being repaired
1330 if ((flags
& BDRV_O_RDWR
) && !(flags
& BDRV_O_CHECK
)) {
1331 error_setg(errp
, "qcow2: Image is corrupt; cannot be opened "
1338 /* Check support for various header values */
1339 if (header
.refcount_order
> 6) {
1340 error_setg(errp
, "Reference count entry width too large; may not "
1345 s
->refcount_order
= header
.refcount_order
;
1346 s
->refcount_bits
= 1 << s
->refcount_order
;
1347 s
->refcount_max
= UINT64_C(1) << (s
->refcount_bits
- 1);
1348 s
->refcount_max
+= s
->refcount_max
- 1;
1350 s
->crypt_method_header
= header
.crypt_method
;
1351 if (s
->crypt_method_header
) {
1352 if (bdrv_uses_whitelist() &&
1353 s
->crypt_method_header
== QCOW_CRYPT_AES
) {
1355 "Use of AES-CBC encrypted qcow2 images is no longer "
1356 "supported in system emulators");
1357 error_append_hint(errp
,
1358 "You can use 'qemu-img convert' to convert your "
1359 "image to an alternative supported format, such "
1360 "as unencrypted qcow2, or raw with the LUKS "
1361 "format instead.\n");
1366 if (s
->crypt_method_header
== QCOW_CRYPT_AES
) {
1367 s
->crypt_physical_offset
= false;
1369 /* Assuming LUKS and any future crypt methods we
1370 * add will all use physical offsets, due to the
1371 * fact that the alternative is insecure... */
1372 s
->crypt_physical_offset
= true;
1375 bs
->encrypted
= true;
1378 s
->l2_bits
= s
->cluster_bits
- 3; /* L2 is always one cluster */
1379 s
->l2_size
= 1 << s
->l2_bits
;
1380 /* 2^(s->refcount_order - 3) is the refcount width in bytes */
1381 s
->refcount_block_bits
= s
->cluster_bits
- (s
->refcount_order
- 3);
1382 s
->refcount_block_size
= 1 << s
->refcount_block_bits
;
1383 bs
->total_sectors
= header
.size
/ BDRV_SECTOR_SIZE
;
1384 s
->csize_shift
= (62 - (s
->cluster_bits
- 8));
1385 s
->csize_mask
= (1 << (s
->cluster_bits
- 8)) - 1;
1386 s
->cluster_offset_mask
= (1LL << s
->csize_shift
) - 1;
1388 s
->refcount_table_offset
= header
.refcount_table_offset
;
1389 s
->refcount_table_size
=
1390 header
.refcount_table_clusters
<< (s
->cluster_bits
- 3);
1392 if (header
.refcount_table_clusters
== 0 && !(flags
& BDRV_O_CHECK
)) {
1393 error_setg(errp
, "Image does not contain a reference count table");
1398 ret
= qcow2_validate_table(bs
, s
->refcount_table_offset
,
1399 header
.refcount_table_clusters
,
1400 s
->cluster_size
, QCOW_MAX_REFTABLE_SIZE
,
1401 "Reference count table", errp
);
1406 /* The total size in bytes of the snapshot table is checked in
1407 * qcow2_read_snapshots() because the size of each snapshot is
1408 * variable and we don't know it yet.
1409 * Here we only check the offset and number of snapshots. */
1410 ret
= qcow2_validate_table(bs
, header
.snapshots_offset
,
1411 header
.nb_snapshots
,
1412 sizeof(QCowSnapshotHeader
),
1413 sizeof(QCowSnapshotHeader
) * QCOW_MAX_SNAPSHOTS
,
1414 "Snapshot table", errp
);
1419 /* read the level 1 table */
1420 ret
= qcow2_validate_table(bs
, header
.l1_table_offset
,
1421 header
.l1_size
, sizeof(uint64_t),
1422 QCOW_MAX_L1_SIZE
, "Active L1 table", errp
);
1426 s
->l1_size
= header
.l1_size
;
1427 s
->l1_table_offset
= header
.l1_table_offset
;
1429 l1_vm_state_index
= size_to_l1(s
, header
.size
);
1430 if (l1_vm_state_index
> INT_MAX
) {
1431 error_setg(errp
, "Image is too big");
1435 s
->l1_vm_state_index
= l1_vm_state_index
;
1437 /* the L1 table must contain at least enough entries to put
1438 header.size bytes */
1439 if (s
->l1_size
< s
->l1_vm_state_index
) {
1440 error_setg(errp
, "L1 table is too small");
1445 if (s
->l1_size
> 0) {
1446 s
->l1_table
= qemu_try_blockalign(bs
->file
->bs
,
1447 ROUND_UP(s
->l1_size
* sizeof(uint64_t), 512));
1448 if (s
->l1_table
== NULL
) {
1449 error_setg(errp
, "Could not allocate L1 table");
1453 ret
= bdrv_pread(bs
->file
, s
->l1_table_offset
, s
->l1_table
,
1454 s
->l1_size
* sizeof(uint64_t));
1456 error_setg_errno(errp
, -ret
, "Could not read L1 table");
1459 for(i
= 0;i
< s
->l1_size
; i
++) {
1460 s
->l1_table
[i
] = be64_to_cpu(s
->l1_table
[i
]);
1464 /* Parse driver-specific options */
1465 ret
= qcow2_update_options(bs
, options
, flags
, errp
);
1472 ret
= qcow2_refcount_init(bs
);
1474 error_setg_errno(errp
, -ret
, "Could not initialize refcount handling");
1478 QLIST_INIT(&s
->cluster_allocs
);
1479 QTAILQ_INIT(&s
->discards
);
1481 /* read qcow2 extensions */
1482 if (qcow2_read_extensions(bs
, header
.header_length
, ext_end
, NULL
,
1483 flags
, &update_header
, &local_err
)) {
1484 error_propagate(errp
, local_err
);
1489 /* Open external data file */
1490 s
->data_file
= bdrv_open_child(NULL
, options
, "data-file", bs
, &child_file
,
1493 error_propagate(errp
, local_err
);
1498 if (s
->incompatible_features
& QCOW2_INCOMPAT_DATA_FILE
) {
1499 if (!s
->data_file
&& s
->image_data_file
) {
1500 s
->data_file
= bdrv_open_child(s
->image_data_file
, options
,
1501 "data-file", bs
, &child_file
,
1503 if (!s
->data_file
) {
1508 if (!s
->data_file
) {
1509 error_setg(errp
, "'data-file' is required for this image");
1515 error_setg(errp
, "'data-file' can only be set for images with an "
1516 "external data file");
1521 s
->data_file
= bs
->file
;
1523 if (data_file_is_raw(bs
)) {
1524 error_setg(errp
, "data-file-raw requires a data file");
1530 /* qcow2_read_extension may have set up the crypto context
1531 * if the crypt method needs a header region, some methods
1532 * don't need header extensions, so must check here
1534 if (s
->crypt_method_header
&& !s
->crypto
) {
1535 if (s
->crypt_method_header
== QCOW_CRYPT_AES
) {
1536 unsigned int cflags
= 0;
1537 if (flags
& BDRV_O_NO_IO
) {
1538 cflags
|= QCRYPTO_BLOCK_OPEN_NO_IO
;
1540 s
->crypto
= qcrypto_block_open(s
->crypto_opts
, "encrypt.",
1541 NULL
, NULL
, cflags
, 1, errp
);
1546 } else if (!(flags
& BDRV_O_NO_IO
)) {
1547 error_setg(errp
, "Missing CRYPTO header for crypt method %d",
1548 s
->crypt_method_header
);
1554 /* read the backing file name */
1555 if (header
.backing_file_offset
!= 0) {
1556 len
= header
.backing_file_size
;
1557 if (len
> MIN(1023, s
->cluster_size
- header
.backing_file_offset
) ||
1558 len
>= sizeof(bs
->backing_file
)) {
1559 error_setg(errp
, "Backing file name too long");
1563 ret
= bdrv_pread(bs
->file
, header
.backing_file_offset
,
1564 bs
->auto_backing_file
, len
);
1566 error_setg_errno(errp
, -ret
, "Could not read backing file name");
1569 bs
->auto_backing_file
[len
] = '\0';
1570 pstrcpy(bs
->backing_file
, sizeof(bs
->backing_file
),
1571 bs
->auto_backing_file
);
1572 s
->image_backing_file
= g_strdup(bs
->auto_backing_file
);
1575 /* Internal snapshots */
1576 s
->snapshots_offset
= header
.snapshots_offset
;
1577 s
->nb_snapshots
= header
.nb_snapshots
;
1579 ret
= qcow2_read_snapshots(bs
);
1581 error_setg_errno(errp
, -ret
, "Could not read snapshots");
1585 /* Clear unknown autoclear feature bits */
1586 update_header
|= s
->autoclear_features
& ~QCOW2_AUTOCLEAR_MASK
;
1588 update_header
&& !bs
->read_only
&& !(flags
& BDRV_O_INACTIVE
);
1589 if (update_header
) {
1590 s
->autoclear_features
&= QCOW2_AUTOCLEAR_MASK
;
1593 /* == Handle persistent dirty bitmaps ==
1595 * We want load dirty bitmaps in three cases:
1597 * 1. Normal open of the disk in active mode, not related to invalidation
1600 * 2. Invalidation of the target vm after pre-copy phase of migration, if
1601 * bitmaps are _not_ migrating through migration channel, i.e.
1602 * 'dirty-bitmaps' capability is disabled.
1604 * 3. Invalidation of source vm after failed or canceled migration.
1605 * This is a very interesting case. There are two possible types of
1608 * A. Stored on inactivation and removed. They should be loaded from the
1611 * B. Not stored: not-persistent bitmaps and bitmaps, migrated through
1612 * the migration channel (with dirty-bitmaps capability).
1614 * On the other hand, there are two possible sub-cases:
1616 * 3.1 disk was changed by somebody else while were inactive. In this
1617 * case all in-RAM dirty bitmaps (both persistent and not) are
1618 * definitely invalid. And we don't have any method to determine
1621 * Simple and safe thing is to just drop all the bitmaps of type B on
1622 * inactivation. But in this case we lose bitmaps in valid 4.2 case.
1624 * On the other hand, resuming source vm, if disk was already changed
1625 * is a bad thing anyway: not only bitmaps, the whole vm state is
1626 * out of sync with disk.
1628 * This means, that user or management tool, who for some reason
1629 * decided to resume source vm, after disk was already changed by
1630 * target vm, should at least drop all dirty bitmaps by hand.
1632 * So, we can ignore this case for now, but TODO: "generation"
1633 * extension for qcow2, to determine, that image was changed after
1634 * last inactivation. And if it is changed, we will drop (or at least
1635 * mark as 'invalid' all the bitmaps of type B, both persistent
1638 * 3.2 disk was _not_ changed while were inactive. Bitmaps may be saved
1639 * to disk ('dirty-bitmaps' capability disabled), or not saved
1640 * ('dirty-bitmaps' capability enabled), but we don't need to care
1641 * of: let's load bitmaps as always: stored bitmaps will be loaded,
1642 * and not stored has flag IN_USE=1 in the image and will be skipped
1645 * One remaining possible case when we don't want load bitmaps:
1647 * 4. Open disk in inactive mode in target vm (bitmaps are migrating or
1648 * will be loaded on invalidation, no needs try loading them before)
1651 if (!(bdrv_get_flags(bs
) & BDRV_O_INACTIVE
)) {
1652 /* It's case 1, 2 or 3.2. Or 3.1 which is BUG in management layer. */
1653 bool header_updated
= qcow2_load_dirty_bitmaps(bs
, &local_err
);
1655 update_header
= update_header
&& !header_updated
;
1657 if (local_err
!= NULL
) {
1658 error_propagate(errp
, local_err
);
1663 if (update_header
) {
1664 ret
= qcow2_update_header(bs
);
1666 error_setg_errno(errp
, -ret
, "Could not update qcow2 header");
1671 bs
->supported_zero_flags
= header
.version
>= 3 ? BDRV_REQ_MAY_UNMAP
: 0;
1673 /* Repair image if dirty */
1674 if (!(flags
& (BDRV_O_CHECK
| BDRV_O_INACTIVE
)) && !bs
->read_only
&&
1675 (s
->incompatible_features
& QCOW2_INCOMPAT_DIRTY
)) {
1676 BdrvCheckResult result
= {0};
1678 ret
= qcow2_co_check_locked(bs
, &result
,
1679 BDRV_FIX_ERRORS
| BDRV_FIX_LEAKS
);
1680 if (ret
< 0 || result
.check_errors
) {
1684 error_setg_errno(errp
, -ret
, "Could not repair dirty image");
1691 BdrvCheckResult result
= {0};
1692 qcow2_check_refcounts(bs
, &result
, 0);
1696 qemu_co_queue_init(&s
->compress_wait_queue
);
1701 g_free(s
->image_data_file
);
1702 if (has_data_file(bs
)) {
1703 bdrv_unref_child(bs
, s
->data_file
);
1705 g_free(s
->unknown_header_fields
);
1706 cleanup_unknown_header_ext(bs
);
1707 qcow2_free_snapshots(bs
);
1708 qcow2_refcount_close(bs
);
1709 qemu_vfree(s
->l1_table
);
1710 /* else pre-write overlap checks in cache_destroy may crash */
1712 cache_clean_timer_del(bs
);
1713 if (s
->l2_table_cache
) {
1714 qcow2_cache_destroy(s
->l2_table_cache
);
1716 if (s
->refcount_block_cache
) {
1717 qcow2_cache_destroy(s
->refcount_block_cache
);
1719 qcrypto_block_free(s
->crypto
);
1720 qapi_free_QCryptoBlockOpenOptions(s
->crypto_opts
);
1724 typedef struct QCow2OpenCo
{
1725 BlockDriverState
*bs
;
1732 static void coroutine_fn
qcow2_open_entry(void *opaque
)
1734 QCow2OpenCo
*qoc
= opaque
;
1735 BDRVQcow2State
*s
= qoc
->bs
->opaque
;
1737 qemu_co_mutex_lock(&s
->lock
);
1738 qoc
->ret
= qcow2_do_open(qoc
->bs
, qoc
->options
, qoc
->flags
, qoc
->errp
);
1739 qemu_co_mutex_unlock(&s
->lock
);
1742 static int qcow2_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
1745 BDRVQcow2State
*s
= bs
->opaque
;
1754 bs
->file
= bdrv_open_child(NULL
, options
, "file", bs
, &child_file
,
1760 /* Initialise locks */
1761 qemu_co_mutex_init(&s
->lock
);
1763 if (qemu_in_coroutine()) {
1764 /* From bdrv_co_create. */
1765 qcow2_open_entry(&qoc
);
1767 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
1768 qemu_coroutine_enter(qemu_coroutine_create(qcow2_open_entry
, &qoc
));
1769 BDRV_POLL_WHILE(bs
, qoc
.ret
== -EINPROGRESS
);
1774 static void qcow2_refresh_limits(BlockDriverState
*bs
, Error
**errp
)
1776 BDRVQcow2State
*s
= bs
->opaque
;
1778 if (bs
->encrypted
) {
1779 /* Encryption works on a sector granularity */
1780 bs
->bl
.request_alignment
= qcrypto_block_get_sector_size(s
->crypto
);
1782 bs
->bl
.pwrite_zeroes_alignment
= s
->cluster_size
;
1783 bs
->bl
.pdiscard_alignment
= s
->cluster_size
;
1786 static int qcow2_reopen_prepare(BDRVReopenState
*state
,
1787 BlockReopenQueue
*queue
, Error
**errp
)
1789 Qcow2ReopenState
*r
;
1792 r
= g_new0(Qcow2ReopenState
, 1);
1795 ret
= qcow2_update_options_prepare(state
->bs
, r
, state
->options
,
1796 state
->flags
, errp
);
1801 /* We need to write out any unwritten data if we reopen read-only. */
1802 if ((state
->flags
& BDRV_O_RDWR
) == 0) {
1803 ret
= qcow2_reopen_bitmaps_ro(state
->bs
, errp
);
1808 ret
= bdrv_flush(state
->bs
);
1813 ret
= qcow2_mark_clean(state
->bs
);
1822 qcow2_update_options_abort(state
->bs
, r
);
1827 static void qcow2_reopen_commit(BDRVReopenState
*state
)
1829 qcow2_update_options_commit(state
->bs
, state
->opaque
);
1830 g_free(state
->opaque
);
1833 static void qcow2_reopen_abort(BDRVReopenState
*state
)
1835 qcow2_update_options_abort(state
->bs
, state
->opaque
);
1836 g_free(state
->opaque
);
1839 static void qcow2_join_options(QDict
*options
, QDict
*old_options
)
1841 bool has_new_overlap_template
=
1842 qdict_haskey(options
, QCOW2_OPT_OVERLAP
) ||
1843 qdict_haskey(options
, QCOW2_OPT_OVERLAP_TEMPLATE
);
1844 bool has_new_total_cache_size
=
1845 qdict_haskey(options
, QCOW2_OPT_CACHE_SIZE
);
1846 bool has_all_cache_options
;
1848 /* New overlap template overrides all old overlap options */
1849 if (has_new_overlap_template
) {
1850 qdict_del(old_options
, QCOW2_OPT_OVERLAP
);
1851 qdict_del(old_options
, QCOW2_OPT_OVERLAP_TEMPLATE
);
1852 qdict_del(old_options
, QCOW2_OPT_OVERLAP_MAIN_HEADER
);
1853 qdict_del(old_options
, QCOW2_OPT_OVERLAP_ACTIVE_L1
);
1854 qdict_del(old_options
, QCOW2_OPT_OVERLAP_ACTIVE_L2
);
1855 qdict_del(old_options
, QCOW2_OPT_OVERLAP_REFCOUNT_TABLE
);
1856 qdict_del(old_options
, QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK
);
1857 qdict_del(old_options
, QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE
);
1858 qdict_del(old_options
, QCOW2_OPT_OVERLAP_INACTIVE_L1
);
1859 qdict_del(old_options
, QCOW2_OPT_OVERLAP_INACTIVE_L2
);
1862 /* New total cache size overrides all old options */
1863 if (qdict_haskey(options
, QCOW2_OPT_CACHE_SIZE
)) {
1864 qdict_del(old_options
, QCOW2_OPT_L2_CACHE_SIZE
);
1865 qdict_del(old_options
, QCOW2_OPT_REFCOUNT_CACHE_SIZE
);
1868 qdict_join(options
, old_options
, false);
1871 * If after merging all cache size options are set, an old total size is
1872 * overwritten. Do keep all options, however, if all three are new. The
1873 * resulting error message is what we want to happen.
1875 has_all_cache_options
=
1876 qdict_haskey(options
, QCOW2_OPT_CACHE_SIZE
) ||
1877 qdict_haskey(options
, QCOW2_OPT_L2_CACHE_SIZE
) ||
1878 qdict_haskey(options
, QCOW2_OPT_REFCOUNT_CACHE_SIZE
);
1880 if (has_all_cache_options
&& !has_new_total_cache_size
) {
1881 qdict_del(options
, QCOW2_OPT_CACHE_SIZE
);
1885 static int coroutine_fn
qcow2_co_block_status(BlockDriverState
*bs
,
1887 int64_t offset
, int64_t count
,
1888 int64_t *pnum
, int64_t *map
,
1889 BlockDriverState
**file
)
1891 BDRVQcow2State
*s
= bs
->opaque
;
1892 uint64_t cluster_offset
;
1893 int index_in_cluster
, ret
;
1897 bytes
= MIN(INT_MAX
, count
);
1898 qemu_co_mutex_lock(&s
->lock
);
1899 ret
= qcow2_get_cluster_offset(bs
, offset
, &bytes
, &cluster_offset
);
1900 qemu_co_mutex_unlock(&s
->lock
);
1907 if ((ret
== QCOW2_CLUSTER_NORMAL
|| ret
== QCOW2_CLUSTER_ZERO_ALLOC
) &&
1909 index_in_cluster
= offset
& (s
->cluster_size
- 1);
1910 *map
= cluster_offset
| index_in_cluster
;
1911 *file
= s
->data_file
->bs
;
1912 status
|= BDRV_BLOCK_OFFSET_VALID
;
1914 if (ret
== QCOW2_CLUSTER_ZERO_PLAIN
|| ret
== QCOW2_CLUSTER_ZERO_ALLOC
) {
1915 status
|= BDRV_BLOCK_ZERO
;
1916 } else if (ret
!= QCOW2_CLUSTER_UNALLOCATED
) {
1917 status
|= BDRV_BLOCK_DATA
;
1922 static coroutine_fn
int qcow2_handle_l2meta(BlockDriverState
*bs
,
1923 QCowL2Meta
**pl2meta
,
1927 QCowL2Meta
*l2meta
= *pl2meta
;
1929 while (l2meta
!= NULL
) {
1933 ret
= qcow2_alloc_cluster_link_l2(bs
, l2meta
);
1938 qcow2_alloc_cluster_abort(bs
, l2meta
);
1941 /* Take the request off the list of running requests */
1942 if (l2meta
->nb_clusters
!= 0) {
1943 QLIST_REMOVE(l2meta
, next_in_flight
);
1946 qemu_co_queue_restart_all(&l2meta
->dependent_requests
);
1948 next
= l2meta
->next
;
1957 static coroutine_fn
int qcow2_co_preadv(BlockDriverState
*bs
, uint64_t offset
,
1958 uint64_t bytes
, QEMUIOVector
*qiov
,
1961 BDRVQcow2State
*s
= bs
->opaque
;
1962 int offset_in_cluster
;
1964 unsigned int cur_bytes
; /* number of bytes in current iteration */
1965 uint64_t cluster_offset
= 0;
1966 uint64_t bytes_done
= 0;
1967 QEMUIOVector hd_qiov
;
1968 uint8_t *cluster_data
= NULL
;
1970 qemu_iovec_init(&hd_qiov
, qiov
->niov
);
1972 qemu_co_mutex_lock(&s
->lock
);
1974 while (bytes
!= 0) {
1976 /* prepare next request */
1977 cur_bytes
= MIN(bytes
, INT_MAX
);
1979 cur_bytes
= MIN(cur_bytes
,
1980 QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_size
);
1983 ret
= qcow2_get_cluster_offset(bs
, offset
, &cur_bytes
, &cluster_offset
);
1988 offset_in_cluster
= offset_into_cluster(s
, offset
);
1990 qemu_iovec_reset(&hd_qiov
);
1991 qemu_iovec_concat(&hd_qiov
, qiov
, bytes_done
, cur_bytes
);
1994 case QCOW2_CLUSTER_UNALLOCATED
:
1997 BLKDBG_EVENT(bs
->file
, BLKDBG_READ_BACKING_AIO
);
1998 qemu_co_mutex_unlock(&s
->lock
);
1999 ret
= bdrv_co_preadv(bs
->backing
, offset
, cur_bytes
,
2001 qemu_co_mutex_lock(&s
->lock
);
2006 /* Note: in this case, no need to wait */
2007 qemu_iovec_memset(&hd_qiov
, 0, 0, cur_bytes
);
2011 case QCOW2_CLUSTER_ZERO_PLAIN
:
2012 case QCOW2_CLUSTER_ZERO_ALLOC
:
2013 qemu_iovec_memset(&hd_qiov
, 0, 0, cur_bytes
);
2016 case QCOW2_CLUSTER_COMPRESSED
:
2017 qemu_co_mutex_unlock(&s
->lock
);
2018 ret
= qcow2_co_preadv_compressed(bs
, cluster_offset
,
2021 qemu_co_mutex_lock(&s
->lock
);
2028 case QCOW2_CLUSTER_NORMAL
:
2029 if ((cluster_offset
& 511) != 0) {
2034 if (bs
->encrypted
) {
2038 * For encrypted images, read everything into a temporary
2039 * contiguous buffer on which the AES functions can work.
2041 if (!cluster_data
) {
2043 qemu_try_blockalign(s
->data_file
->bs
,
2044 QCOW_MAX_CRYPT_CLUSTERS
2046 if (cluster_data
== NULL
) {
2052 assert(cur_bytes
<= QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_size
);
2053 qemu_iovec_reset(&hd_qiov
);
2054 qemu_iovec_add(&hd_qiov
, cluster_data
, cur_bytes
);
2057 BLKDBG_EVENT(bs
->file
, BLKDBG_READ_AIO
);
2058 qemu_co_mutex_unlock(&s
->lock
);
2059 ret
= bdrv_co_preadv(s
->data_file
,
2060 cluster_offset
+ offset_in_cluster
,
2061 cur_bytes
, &hd_qiov
, 0);
2062 qemu_co_mutex_lock(&s
->lock
);
2066 if (bs
->encrypted
) {
2068 assert((offset
& (BDRV_SECTOR_SIZE
- 1)) == 0);
2069 assert((cur_bytes
& (BDRV_SECTOR_SIZE
- 1)) == 0);
2070 if (qcrypto_block_decrypt(s
->crypto
,
2071 (s
->crypt_physical_offset
?
2072 cluster_offset
+ offset_in_cluster
:
2080 qemu_iovec_from_buf(qiov
, bytes_done
, cluster_data
, cur_bytes
);
2085 g_assert_not_reached();
2091 offset
+= cur_bytes
;
2092 bytes_done
+= cur_bytes
;
2097 qemu_co_mutex_unlock(&s
->lock
);
2099 qemu_iovec_destroy(&hd_qiov
);
2100 qemu_vfree(cluster_data
);
2105 /* Check if it's possible to merge a write request with the writing of
2106 * the data from the COW regions */
2107 static bool merge_cow(uint64_t offset
, unsigned bytes
,
2108 QEMUIOVector
*hd_qiov
, QCowL2Meta
*l2meta
)
2112 for (m
= l2meta
; m
!= NULL
; m
= m
->next
) {
2113 /* If both COW regions are empty then there's nothing to merge */
2114 if (m
->cow_start
.nb_bytes
== 0 && m
->cow_end
.nb_bytes
== 0) {
2118 /* The data (middle) region must be immediately after the
2120 if (l2meta_cow_start(m
) + m
->cow_start
.nb_bytes
!= offset
) {
2124 /* The end region must be immediately after the data (middle)
2126 if (m
->offset
+ m
->cow_end
.offset
!= offset
+ bytes
) {
2130 /* Make sure that adding both COW regions to the QEMUIOVector
2131 * does not exceed IOV_MAX */
2132 if (hd_qiov
->niov
> IOV_MAX
- 2) {
2136 m
->data_qiov
= hd_qiov
;
2143 static coroutine_fn
int qcow2_co_pwritev(BlockDriverState
*bs
, uint64_t offset
,
2144 uint64_t bytes
, QEMUIOVector
*qiov
,
2147 BDRVQcow2State
*s
= bs
->opaque
;
2148 int offset_in_cluster
;
2150 unsigned int cur_bytes
; /* number of sectors in current iteration */
2151 uint64_t cluster_offset
;
2152 QEMUIOVector hd_qiov
;
2153 uint64_t bytes_done
= 0;
2154 uint8_t *cluster_data
= NULL
;
2155 QCowL2Meta
*l2meta
= NULL
;
2157 trace_qcow2_writev_start_req(qemu_coroutine_self(), offset
, bytes
);
2159 qemu_iovec_init(&hd_qiov
, qiov
->niov
);
2161 qemu_co_mutex_lock(&s
->lock
);
2163 while (bytes
!= 0) {
2167 trace_qcow2_writev_start_part(qemu_coroutine_self());
2168 offset_in_cluster
= offset_into_cluster(s
, offset
);
2169 cur_bytes
= MIN(bytes
, INT_MAX
);
2170 if (bs
->encrypted
) {
2171 cur_bytes
= MIN(cur_bytes
,
2172 QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_size
2173 - offset_in_cluster
);
2176 ret
= qcow2_alloc_cluster_offset(bs
, offset
, &cur_bytes
,
2177 &cluster_offset
, &l2meta
);
2182 assert((cluster_offset
& 511) == 0);
2184 qemu_iovec_reset(&hd_qiov
);
2185 qemu_iovec_concat(&hd_qiov
, qiov
, bytes_done
, cur_bytes
);
2187 if (bs
->encrypted
) {
2189 if (!cluster_data
) {
2190 cluster_data
= qemu_try_blockalign(bs
->file
->bs
,
2191 QCOW_MAX_CRYPT_CLUSTERS
2193 if (cluster_data
== NULL
) {
2199 assert(hd_qiov
.size
<=
2200 QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_size
);
2201 qemu_iovec_to_buf(&hd_qiov
, 0, cluster_data
, hd_qiov
.size
);
2203 if (qcrypto_block_encrypt(s
->crypto
,
2204 (s
->crypt_physical_offset
?
2205 cluster_offset
+ offset_in_cluster
:
2208 cur_bytes
, NULL
) < 0) {
2213 qemu_iovec_reset(&hd_qiov
);
2214 qemu_iovec_add(&hd_qiov
, cluster_data
, cur_bytes
);
2217 ret
= qcow2_pre_write_overlap_check(bs
, 0,
2218 cluster_offset
+ offset_in_cluster
, cur_bytes
, true);
2223 /* If we need to do COW, check if it's possible to merge the
2224 * writing of the guest data together with that of the COW regions.
2225 * If it's not possible (or not necessary) then write the
2226 * guest data now. */
2227 if (!merge_cow(offset
, cur_bytes
, &hd_qiov
, l2meta
)) {
2228 qemu_co_mutex_unlock(&s
->lock
);
2229 BLKDBG_EVENT(bs
->file
, BLKDBG_WRITE_AIO
);
2230 trace_qcow2_writev_data(qemu_coroutine_self(),
2231 cluster_offset
+ offset_in_cluster
);
2232 ret
= bdrv_co_pwritev(s
->data_file
,
2233 cluster_offset
+ offset_in_cluster
,
2234 cur_bytes
, &hd_qiov
, 0);
2235 qemu_co_mutex_lock(&s
->lock
);
2241 ret
= qcow2_handle_l2meta(bs
, &l2meta
, true);
2247 offset
+= cur_bytes
;
2248 bytes_done
+= cur_bytes
;
2249 trace_qcow2_writev_done_part(qemu_coroutine_self(), cur_bytes
);
2254 qcow2_handle_l2meta(bs
, &l2meta
, false);
2256 qemu_co_mutex_unlock(&s
->lock
);
2258 qemu_iovec_destroy(&hd_qiov
);
2259 qemu_vfree(cluster_data
);
2260 trace_qcow2_writev_done_req(qemu_coroutine_self(), ret
);
2265 static int qcow2_inactivate(BlockDriverState
*bs
)
2267 BDRVQcow2State
*s
= bs
->opaque
;
2268 int ret
, result
= 0;
2269 Error
*local_err
= NULL
;
2271 qcow2_store_persistent_dirty_bitmaps(bs
, &local_err
);
2272 if (local_err
!= NULL
) {
2274 error_reportf_err(local_err
, "Lost persistent bitmaps during "
2275 "inactivation of node '%s': ",
2276 bdrv_get_device_or_node_name(bs
));
2279 ret
= qcow2_cache_flush(bs
, s
->l2_table_cache
);
2282 error_report("Failed to flush the L2 table cache: %s",
2286 ret
= qcow2_cache_flush(bs
, s
->refcount_block_cache
);
2289 error_report("Failed to flush the refcount block cache: %s",
2294 qcow2_mark_clean(bs
);
2300 static void qcow2_close(BlockDriverState
*bs
)
2302 BDRVQcow2State
*s
= bs
->opaque
;
2303 qemu_vfree(s
->l1_table
);
2304 /* else pre-write overlap checks in cache_destroy may crash */
2307 if (!(s
->flags
& BDRV_O_INACTIVE
)) {
2308 qcow2_inactivate(bs
);
2311 cache_clean_timer_del(bs
);
2312 qcow2_cache_destroy(s
->l2_table_cache
);
2313 qcow2_cache_destroy(s
->refcount_block_cache
);
2315 qcrypto_block_free(s
->crypto
);
2318 g_free(s
->unknown_header_fields
);
2319 cleanup_unknown_header_ext(bs
);
2321 g_free(s
->image_data_file
);
2322 g_free(s
->image_backing_file
);
2323 g_free(s
->image_backing_format
);
2325 if (has_data_file(bs
)) {
2326 bdrv_unref_child(bs
, s
->data_file
);
2329 qcow2_refcount_close(bs
);
2330 qcow2_free_snapshots(bs
);
2333 static void coroutine_fn
qcow2_co_invalidate_cache(BlockDriverState
*bs
,
2336 BDRVQcow2State
*s
= bs
->opaque
;
2337 int flags
= s
->flags
;
2338 QCryptoBlock
*crypto
= NULL
;
2340 Error
*local_err
= NULL
;
2344 * Backing files are read-only which makes all of their metadata immutable,
2345 * that means we don't have to worry about reopening them here.
2353 memset(s
, 0, sizeof(BDRVQcow2State
));
2354 options
= qdict_clone_shallow(bs
->options
);
2356 flags
&= ~BDRV_O_INACTIVE
;
2357 qemu_co_mutex_lock(&s
->lock
);
2358 ret
= qcow2_do_open(bs
, options
, flags
, &local_err
);
2359 qemu_co_mutex_unlock(&s
->lock
);
2360 qobject_unref(options
);
2362 error_propagate_prepend(errp
, local_err
,
2363 "Could not reopen qcow2 layer: ");
2366 } else if (ret
< 0) {
2367 error_setg_errno(errp
, -ret
, "Could not reopen qcow2 layer");
2375 static size_t header_ext_add(char *buf
, uint32_t magic
, const void *s
,
2376 size_t len
, size_t buflen
)
2378 QCowExtension
*ext_backing_fmt
= (QCowExtension
*) buf
;
2379 size_t ext_len
= sizeof(QCowExtension
) + ((len
+ 7) & ~7);
2381 if (buflen
< ext_len
) {
2385 *ext_backing_fmt
= (QCowExtension
) {
2386 .magic
= cpu_to_be32(magic
),
2387 .len
= cpu_to_be32(len
),
2391 memcpy(buf
+ sizeof(QCowExtension
), s
, len
);
2398 * Updates the qcow2 header, including the variable length parts of it, i.e.
2399 * the backing file name and all extensions. qcow2 was not designed to allow
2400 * such changes, so if we run out of space (we can only use the first cluster)
2401 * this function may fail.
2403 * Returns 0 on success, -errno in error cases.
2405 int qcow2_update_header(BlockDriverState
*bs
)
2407 BDRVQcow2State
*s
= bs
->opaque
;
2410 size_t buflen
= s
->cluster_size
;
2412 uint64_t total_size
;
2413 uint32_t refcount_table_clusters
;
2414 size_t header_length
;
2415 Qcow2UnknownHeaderExtension
*uext
;
2417 buf
= qemu_blockalign(bs
, buflen
);
2419 /* Header structure */
2420 header
= (QCowHeader
*) buf
;
2422 if (buflen
< sizeof(*header
)) {
2427 header_length
= sizeof(*header
) + s
->unknown_header_fields_size
;
2428 total_size
= bs
->total_sectors
* BDRV_SECTOR_SIZE
;
2429 refcount_table_clusters
= s
->refcount_table_size
>> (s
->cluster_bits
- 3);
2431 *header
= (QCowHeader
) {
2432 /* Version 2 fields */
2433 .magic
= cpu_to_be32(QCOW_MAGIC
),
2434 .version
= cpu_to_be32(s
->qcow_version
),
2435 .backing_file_offset
= 0,
2436 .backing_file_size
= 0,
2437 .cluster_bits
= cpu_to_be32(s
->cluster_bits
),
2438 .size
= cpu_to_be64(total_size
),
2439 .crypt_method
= cpu_to_be32(s
->crypt_method_header
),
2440 .l1_size
= cpu_to_be32(s
->l1_size
),
2441 .l1_table_offset
= cpu_to_be64(s
->l1_table_offset
),
2442 .refcount_table_offset
= cpu_to_be64(s
->refcount_table_offset
),
2443 .refcount_table_clusters
= cpu_to_be32(refcount_table_clusters
),
2444 .nb_snapshots
= cpu_to_be32(s
->nb_snapshots
),
2445 .snapshots_offset
= cpu_to_be64(s
->snapshots_offset
),
2447 /* Version 3 fields */
2448 .incompatible_features
= cpu_to_be64(s
->incompatible_features
),
2449 .compatible_features
= cpu_to_be64(s
->compatible_features
),
2450 .autoclear_features
= cpu_to_be64(s
->autoclear_features
),
2451 .refcount_order
= cpu_to_be32(s
->refcount_order
),
2452 .header_length
= cpu_to_be32(header_length
),
2455 /* For older versions, write a shorter header */
2456 switch (s
->qcow_version
) {
2458 ret
= offsetof(QCowHeader
, incompatible_features
);
2461 ret
= sizeof(*header
);
2470 memset(buf
, 0, buflen
);
2472 /* Preserve any unknown field in the header */
2473 if (s
->unknown_header_fields_size
) {
2474 if (buflen
< s
->unknown_header_fields_size
) {
2479 memcpy(buf
, s
->unknown_header_fields
, s
->unknown_header_fields_size
);
2480 buf
+= s
->unknown_header_fields_size
;
2481 buflen
-= s
->unknown_header_fields_size
;
2484 /* Backing file format header extension */
2485 if (s
->image_backing_format
) {
2486 ret
= header_ext_add(buf
, QCOW2_EXT_MAGIC_BACKING_FORMAT
,
2487 s
->image_backing_format
,
2488 strlen(s
->image_backing_format
),
2498 /* External data file header extension */
2499 if (has_data_file(bs
) && s
->image_data_file
) {
2500 ret
= header_ext_add(buf
, QCOW2_EXT_MAGIC_DATA_FILE
,
2501 s
->image_data_file
, strlen(s
->image_data_file
),
2511 /* Full disk encryption header pointer extension */
2512 if (s
->crypto_header
.offset
!= 0) {
2513 s
->crypto_header
.offset
= cpu_to_be64(s
->crypto_header
.offset
);
2514 s
->crypto_header
.length
= cpu_to_be64(s
->crypto_header
.length
);
2515 ret
= header_ext_add(buf
, QCOW2_EXT_MAGIC_CRYPTO_HEADER
,
2516 &s
->crypto_header
, sizeof(s
->crypto_header
),
2518 s
->crypto_header
.offset
= be64_to_cpu(s
->crypto_header
.offset
);
2519 s
->crypto_header
.length
= be64_to_cpu(s
->crypto_header
.length
);
2528 if (s
->qcow_version
>= 3) {
2529 Qcow2Feature features
[] = {
2531 .type
= QCOW2_FEAT_TYPE_INCOMPATIBLE
,
2532 .bit
= QCOW2_INCOMPAT_DIRTY_BITNR
,
2533 .name
= "dirty bit",
2536 .type
= QCOW2_FEAT_TYPE_INCOMPATIBLE
,
2537 .bit
= QCOW2_INCOMPAT_CORRUPT_BITNR
,
2538 .name
= "corrupt bit",
2541 .type
= QCOW2_FEAT_TYPE_INCOMPATIBLE
,
2542 .bit
= QCOW2_INCOMPAT_DATA_FILE_BITNR
,
2543 .name
= "external data file",
2546 .type
= QCOW2_FEAT_TYPE_COMPATIBLE
,
2547 .bit
= QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR
,
2548 .name
= "lazy refcounts",
2552 ret
= header_ext_add(buf
, QCOW2_EXT_MAGIC_FEATURE_TABLE
,
2553 features
, sizeof(features
), buflen
);
2561 /* Bitmap extension */
2562 if (s
->nb_bitmaps
> 0) {
2563 Qcow2BitmapHeaderExt bitmaps_header
= {
2564 .nb_bitmaps
= cpu_to_be32(s
->nb_bitmaps
),
2565 .bitmap_directory_size
=
2566 cpu_to_be64(s
->bitmap_directory_size
),
2567 .bitmap_directory_offset
=
2568 cpu_to_be64(s
->bitmap_directory_offset
)
2570 ret
= header_ext_add(buf
, QCOW2_EXT_MAGIC_BITMAPS
,
2571 &bitmaps_header
, sizeof(bitmaps_header
),
2580 /* Keep unknown header extensions */
2581 QLIST_FOREACH(uext
, &s
->unknown_header_ext
, next
) {
2582 ret
= header_ext_add(buf
, uext
->magic
, uext
->data
, uext
->len
, buflen
);
2591 /* End of header extensions */
2592 ret
= header_ext_add(buf
, QCOW2_EXT_MAGIC_END
, NULL
, 0, buflen
);
2600 /* Backing file name */
2601 if (s
->image_backing_file
) {
2602 size_t backing_file_len
= strlen(s
->image_backing_file
);
2604 if (buflen
< backing_file_len
) {
2609 /* Using strncpy is ok here, since buf is not NUL-terminated. */
2610 strncpy(buf
, s
->image_backing_file
, buflen
);
2612 header
->backing_file_offset
= cpu_to_be64(buf
- ((char*) header
));
2613 header
->backing_file_size
= cpu_to_be32(backing_file_len
);
2616 /* Write the new header */
2617 ret
= bdrv_pwrite(bs
->file
, 0, header
, s
->cluster_size
);
2628 static int qcow2_change_backing_file(BlockDriverState
*bs
,
2629 const char *backing_file
, const char *backing_fmt
)
2631 BDRVQcow2State
*s
= bs
->opaque
;
2633 /* Adding a backing file means that the external data file alone won't be
2634 * enough to make sense of the content */
2635 if (backing_file
&& data_file_is_raw(bs
)) {
2639 if (backing_file
&& strlen(backing_file
) > 1023) {
2643 pstrcpy(bs
->auto_backing_file
, sizeof(bs
->auto_backing_file
),
2644 backing_file
?: "");
2645 pstrcpy(bs
->backing_file
, sizeof(bs
->backing_file
), backing_file
?: "");
2646 pstrcpy(bs
->backing_format
, sizeof(bs
->backing_format
), backing_fmt
?: "");
2648 g_free(s
->image_backing_file
);
2649 g_free(s
->image_backing_format
);
2651 s
->image_backing_file
= backing_file
? g_strdup(bs
->backing_file
) : NULL
;
2652 s
->image_backing_format
= backing_fmt
? g_strdup(bs
->backing_format
) : NULL
;
2654 return qcow2_update_header(bs
);
2657 static int qcow2_crypt_method_from_format(const char *encryptfmt
)
2659 if (g_str_equal(encryptfmt
, "luks")) {
2660 return QCOW_CRYPT_LUKS
;
2661 } else if (g_str_equal(encryptfmt
, "aes")) {
2662 return QCOW_CRYPT_AES
;
2668 static int qcow2_set_up_encryption(BlockDriverState
*bs
,
2669 QCryptoBlockCreateOptions
*cryptoopts
,
2672 BDRVQcow2State
*s
= bs
->opaque
;
2673 QCryptoBlock
*crypto
= NULL
;
2676 switch (cryptoopts
->format
) {
2677 case Q_CRYPTO_BLOCK_FORMAT_LUKS
:
2678 fmt
= QCOW_CRYPT_LUKS
;
2680 case Q_CRYPTO_BLOCK_FORMAT_QCOW
:
2681 fmt
= QCOW_CRYPT_AES
;
2684 error_setg(errp
, "Crypto format not supported in qcow2");
2688 s
->crypt_method_header
= fmt
;
2690 crypto
= qcrypto_block_create(cryptoopts
, "encrypt.",
2691 qcow2_crypto_hdr_init_func
,
2692 qcow2_crypto_hdr_write_func
,
2698 ret
= qcow2_update_header(bs
);
2700 error_setg_errno(errp
, -ret
, "Could not write encryption header");
2706 qcrypto_block_free(crypto
);
2711 * Preallocates metadata structures for data clusters between @offset (in the
2712 * guest disk) and @new_length (which is thus generally the new guest disk
2715 * Returns: 0 on success, -errno on failure.
2717 static int coroutine_fn
preallocate_co(BlockDriverState
*bs
, uint64_t offset
,
2718 uint64_t new_length
, PreallocMode mode
,
2721 BDRVQcow2State
*s
= bs
->opaque
;
2723 uint64_t host_offset
= 0;
2724 int64_t file_length
;
2725 unsigned int cur_bytes
;
2729 assert(offset
<= new_length
);
2730 bytes
= new_length
- offset
;
2733 cur_bytes
= MIN(bytes
, QEMU_ALIGN_DOWN(INT_MAX
, s
->cluster_size
));
2734 ret
= qcow2_alloc_cluster_offset(bs
, offset
, &cur_bytes
,
2735 &host_offset
, &meta
);
2737 error_setg_errno(errp
, -ret
, "Allocating clusters failed");
2742 QCowL2Meta
*next
= meta
->next
;
2744 ret
= qcow2_alloc_cluster_link_l2(bs
, meta
);
2746 error_setg_errno(errp
, -ret
, "Mapping clusters failed");
2747 qcow2_free_any_clusters(bs
, meta
->alloc_offset
,
2748 meta
->nb_clusters
, QCOW2_DISCARD_NEVER
);
2752 /* There are no dependent requests, but we need to remove our
2753 * request from the list of in-flight requests */
2754 QLIST_REMOVE(meta
, next_in_flight
);
2760 /* TODO Preallocate data if requested */
2763 offset
+= cur_bytes
;
2767 * It is expected that the image file is large enough to actually contain
2768 * all of the allocated clusters (otherwise we get failing reads after
2769 * EOF). Extend the image to the last allocated sector.
2771 file_length
= bdrv_getlength(s
->data_file
->bs
);
2772 if (file_length
< 0) {
2773 error_setg_errno(errp
, -file_length
, "Could not get file size");
2777 if (host_offset
+ cur_bytes
> file_length
) {
2778 if (mode
== PREALLOC_MODE_METADATA
) {
2779 mode
= PREALLOC_MODE_OFF
;
2781 ret
= bdrv_co_truncate(s
->data_file
, host_offset
+ cur_bytes
, mode
,
2791 /* qcow2_refcount_metadata_size:
2792 * @clusters: number of clusters to refcount (including data and L1/L2 tables)
2793 * @cluster_size: size of a cluster, in bytes
2794 * @refcount_order: refcount bits power-of-2 exponent
2795 * @generous_increase: allow for the refcount table to be 1.5x as large as it
2798 * Returns: Number of bytes required for refcount blocks and table metadata.
2800 int64_t qcow2_refcount_metadata_size(int64_t clusters
, size_t cluster_size
,
2801 int refcount_order
, bool generous_increase
,
2802 uint64_t *refblock_count
)
2805 * Every host cluster is reference-counted, including metadata (even
2806 * refcount metadata is recursively included).
2808 * An accurate formula for the size of refcount metadata size is difficult
2809 * to derive. An easier method of calculation is finding the fixed point
2810 * where no further refcount blocks or table clusters are required to
2811 * reference count every cluster.
2813 int64_t blocks_per_table_cluster
= cluster_size
/ sizeof(uint64_t);
2814 int64_t refcounts_per_block
= cluster_size
* 8 / (1 << refcount_order
);
2815 int64_t table
= 0; /* number of refcount table clusters */
2816 int64_t blocks
= 0; /* number of refcount block clusters */
2822 blocks
= DIV_ROUND_UP(clusters
+ table
+ blocks
, refcounts_per_block
);
2823 table
= DIV_ROUND_UP(blocks
, blocks_per_table_cluster
);
2824 n
= clusters
+ blocks
+ table
;
2826 if (n
== last
&& generous_increase
) {
2827 clusters
+= DIV_ROUND_UP(table
, 2);
2828 n
= 0; /* force another loop */
2829 generous_increase
= false;
2831 } while (n
!= last
);
2833 if (refblock_count
) {
2834 *refblock_count
= blocks
;
2837 return (blocks
+ table
) * cluster_size
;
2841 * qcow2_calc_prealloc_size:
2842 * @total_size: virtual disk size in bytes
2843 * @cluster_size: cluster size in bytes
2844 * @refcount_order: refcount bits power-of-2 exponent
2846 * Returns: Total number of bytes required for the fully allocated image
2847 * (including metadata).
2849 static int64_t qcow2_calc_prealloc_size(int64_t total_size
,
2850 size_t cluster_size
,
2853 int64_t meta_size
= 0;
2854 uint64_t nl1e
, nl2e
;
2855 int64_t aligned_total_size
= ROUND_UP(total_size
, cluster_size
);
2857 /* header: 1 cluster */
2858 meta_size
+= cluster_size
;
2860 /* total size of L2 tables */
2861 nl2e
= aligned_total_size
/ cluster_size
;
2862 nl2e
= ROUND_UP(nl2e
, cluster_size
/ sizeof(uint64_t));
2863 meta_size
+= nl2e
* sizeof(uint64_t);
2865 /* total size of L1 tables */
2866 nl1e
= nl2e
* sizeof(uint64_t) / cluster_size
;
2867 nl1e
= ROUND_UP(nl1e
, cluster_size
/ sizeof(uint64_t));
2868 meta_size
+= nl1e
* sizeof(uint64_t);
2870 /* total size of refcount table and blocks */
2871 meta_size
+= qcow2_refcount_metadata_size(
2872 (meta_size
+ aligned_total_size
) / cluster_size
,
2873 cluster_size
, refcount_order
, false, NULL
);
2875 return meta_size
+ aligned_total_size
;
2878 static bool validate_cluster_size(size_t cluster_size
, Error
**errp
)
2880 int cluster_bits
= ctz32(cluster_size
);
2881 if (cluster_bits
< MIN_CLUSTER_BITS
|| cluster_bits
> MAX_CLUSTER_BITS
||
2882 (1 << cluster_bits
) != cluster_size
)
2884 error_setg(errp
, "Cluster size must be a power of two between %d and "
2885 "%dk", 1 << MIN_CLUSTER_BITS
, 1 << (MAX_CLUSTER_BITS
- 10));
2891 static size_t qcow2_opt_get_cluster_size_del(QemuOpts
*opts
, Error
**errp
)
2893 size_t cluster_size
;
2895 cluster_size
= qemu_opt_get_size_del(opts
, BLOCK_OPT_CLUSTER_SIZE
,
2896 DEFAULT_CLUSTER_SIZE
);
2897 if (!validate_cluster_size(cluster_size
, errp
)) {
2900 return cluster_size
;
2903 static int qcow2_opt_get_version_del(QemuOpts
*opts
, Error
**errp
)
2908 buf
= qemu_opt_get_del(opts
, BLOCK_OPT_COMPAT_LEVEL
);
2910 ret
= 3; /* default */
2911 } else if (!strcmp(buf
, "0.10")) {
2913 } else if (!strcmp(buf
, "1.1")) {
2916 error_setg(errp
, "Invalid compatibility level: '%s'", buf
);
2923 static uint64_t qcow2_opt_get_refcount_bits_del(QemuOpts
*opts
, int version
,
2926 uint64_t refcount_bits
;
2928 refcount_bits
= qemu_opt_get_number_del(opts
, BLOCK_OPT_REFCOUNT_BITS
, 16);
2929 if (refcount_bits
> 64 || !is_power_of_2(refcount_bits
)) {
2930 error_setg(errp
, "Refcount width must be a power of two and may not "
2935 if (version
< 3 && refcount_bits
!= 16) {
2936 error_setg(errp
, "Different refcount widths than 16 bits require "
2937 "compatibility level 1.1 or above (use compat=1.1 or "
2942 return refcount_bits
;
2945 static int coroutine_fn
2946 qcow2_co_create(BlockdevCreateOptions
*create_options
, Error
**errp
)
2948 BlockdevCreateOptionsQcow2
*qcow2_opts
;
2952 * Open the image file and write a minimal qcow2 header.
2954 * We keep things simple and start with a zero-sized image. We also
2955 * do without refcount blocks or a L1 table for now. We'll fix the
2956 * inconsistency later.
2958 * We do need a refcount table because growing the refcount table means
2959 * allocating two new refcount blocks - the seconds of which would be at
2960 * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
2961 * size for any qcow2 image.
2963 BlockBackend
*blk
= NULL
;
2964 BlockDriverState
*bs
= NULL
;
2965 BlockDriverState
*data_bs
= NULL
;
2967 size_t cluster_size
;
2970 uint64_t* refcount_table
;
2971 Error
*local_err
= NULL
;
2974 assert(create_options
->driver
== BLOCKDEV_DRIVER_QCOW2
);
2975 qcow2_opts
= &create_options
->u
.qcow2
;
2977 bs
= bdrv_open_blockdev_ref(qcow2_opts
->file
, errp
);
2982 /* Validate options and set default values */
2983 if (!QEMU_IS_ALIGNED(qcow2_opts
->size
, BDRV_SECTOR_SIZE
)) {
2984 error_setg(errp
, "Image size must be a multiple of 512 bytes");
2989 if (qcow2_opts
->has_version
) {
2990 switch (qcow2_opts
->version
) {
2991 case BLOCKDEV_QCOW2_VERSION_V2
:
2994 case BLOCKDEV_QCOW2_VERSION_V3
:
2998 g_assert_not_reached();
3004 if (qcow2_opts
->has_cluster_size
) {
3005 cluster_size
= qcow2_opts
->cluster_size
;
3007 cluster_size
= DEFAULT_CLUSTER_SIZE
;
3010 if (!validate_cluster_size(cluster_size
, errp
)) {
3015 if (!qcow2_opts
->has_preallocation
) {
3016 qcow2_opts
->preallocation
= PREALLOC_MODE_OFF
;
3018 if (qcow2_opts
->has_backing_file
&&
3019 qcow2_opts
->preallocation
!= PREALLOC_MODE_OFF
)
3021 error_setg(errp
, "Backing file and preallocation cannot be used at "
3026 if (qcow2_opts
->has_backing_fmt
&& !qcow2_opts
->has_backing_file
) {
3027 error_setg(errp
, "Backing format cannot be used without backing file");
3032 if (!qcow2_opts
->has_lazy_refcounts
) {
3033 qcow2_opts
->lazy_refcounts
= false;
3035 if (version
< 3 && qcow2_opts
->lazy_refcounts
) {
3036 error_setg(errp
, "Lazy refcounts only supported with compatibility "
3037 "level 1.1 and above (use version=v3 or greater)");
3042 if (!qcow2_opts
->has_refcount_bits
) {
3043 qcow2_opts
->refcount_bits
= 16;
3045 if (qcow2_opts
->refcount_bits
> 64 ||
3046 !is_power_of_2(qcow2_opts
->refcount_bits
))
3048 error_setg(errp
, "Refcount width must be a power of two and may not "
3053 if (version
< 3 && qcow2_opts
->refcount_bits
!= 16) {
3054 error_setg(errp
, "Different refcount widths than 16 bits require "
3055 "compatibility level 1.1 or above (use version=v3 or "
3060 refcount_order
= ctz32(qcow2_opts
->refcount_bits
);
3062 if (qcow2_opts
->data_file_raw
&& !qcow2_opts
->data_file
) {
3063 error_setg(errp
, "data-file-raw requires data-file");
3067 if (qcow2_opts
->data_file_raw
&& qcow2_opts
->has_backing_file
) {
3068 error_setg(errp
, "Backing file and data-file-raw cannot be used at "
3074 if (qcow2_opts
->data_file
) {
3076 error_setg(errp
, "External data files are only supported with "
3077 "compatibility level 1.1 and above (use version=v3 or "
3082 data_bs
= bdrv_open_blockdev_ref(qcow2_opts
->data_file
, errp
);
3083 if (data_bs
== NULL
) {
3089 /* Create BlockBackend to write to the image */
3090 blk
= blk_new(BLK_PERM_WRITE
| BLK_PERM_RESIZE
, BLK_PERM_ALL
);
3091 ret
= blk_insert_bs(blk
, bs
, errp
);
3095 blk_set_allow_write_beyond_eof(blk
, true);
3097 /* Clear the protocol layer and preallocate it if necessary */
3098 ret
= blk_truncate(blk
, 0, PREALLOC_MODE_OFF
, errp
);
3103 /* Write the header */
3104 QEMU_BUILD_BUG_ON((1 << MIN_CLUSTER_BITS
) < sizeof(*header
));
3105 header
= g_malloc0(cluster_size
);
3106 *header
= (QCowHeader
) {
3107 .magic
= cpu_to_be32(QCOW_MAGIC
),
3108 .version
= cpu_to_be32(version
),
3109 .cluster_bits
= cpu_to_be32(ctz32(cluster_size
)),
3110 .size
= cpu_to_be64(0),
3111 .l1_table_offset
= cpu_to_be64(0),
3112 .l1_size
= cpu_to_be32(0),
3113 .refcount_table_offset
= cpu_to_be64(cluster_size
),
3114 .refcount_table_clusters
= cpu_to_be32(1),
3115 .refcount_order
= cpu_to_be32(refcount_order
),
3116 .header_length
= cpu_to_be32(sizeof(*header
)),
3119 /* We'll update this to correct value later */
3120 header
->crypt_method
= cpu_to_be32(QCOW_CRYPT_NONE
);
3122 if (qcow2_opts
->lazy_refcounts
) {
3123 header
->compatible_features
|=
3124 cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS
);
3127 header
->incompatible_features
|=
3128 cpu_to_be64(QCOW2_INCOMPAT_DATA_FILE
);
3130 if (qcow2_opts
->data_file_raw
) {
3131 header
->autoclear_features
|=
3132 cpu_to_be64(QCOW2_AUTOCLEAR_DATA_FILE_RAW
);
3135 ret
= blk_pwrite(blk
, 0, header
, cluster_size
, 0);
3138 error_setg_errno(errp
, -ret
, "Could not write qcow2 header");
3142 /* Write a refcount table with one refcount block */
3143 refcount_table
= g_malloc0(2 * cluster_size
);
3144 refcount_table
[0] = cpu_to_be64(2 * cluster_size
);
3145 ret
= blk_pwrite(blk
, cluster_size
, refcount_table
, 2 * cluster_size
, 0);
3146 g_free(refcount_table
);
3149 error_setg_errno(errp
, -ret
, "Could not write refcount table");
3157 * And now open the image and make it consistent first (i.e. increase the
3158 * refcount of the cluster that is occupied by the header and the refcount
3161 options
= qdict_new();
3162 qdict_put_str(options
, "driver", "qcow2");
3163 qdict_put_str(options
, "file", bs
->node_name
);
3165 qdict_put_str(options
, "data-file", data_bs
->node_name
);
3167 blk
= blk_new_open(NULL
, NULL
, options
,
3168 BDRV_O_RDWR
| BDRV_O_RESIZE
| BDRV_O_NO_FLUSH
,
3171 error_propagate(errp
, local_err
);
3176 ret
= qcow2_alloc_clusters(blk_bs(blk
), 3 * cluster_size
);
3178 error_setg_errno(errp
, -ret
, "Could not allocate clusters for qcow2 "
3179 "header and refcount table");
3182 } else if (ret
!= 0) {
3183 error_report("Huh, first cluster in empty image is already in use?");
3187 /* Set the external data file if necessary */
3189 BDRVQcow2State
*s
= blk_bs(blk
)->opaque
;
3190 s
->image_data_file
= g_strdup(data_bs
->filename
);
3193 /* Create a full header (including things like feature table) */
3194 ret
= qcow2_update_header(blk_bs(blk
));
3196 error_setg_errno(errp
, -ret
, "Could not update qcow2 header");
3200 /* Okay, now that we have a valid image, let's give it the right size */
3201 ret
= blk_truncate(blk
, qcow2_opts
->size
, qcow2_opts
->preallocation
, errp
);
3203 error_prepend(errp
, "Could not resize image: ");
3207 /* Want a backing file? There you go.*/
3208 if (qcow2_opts
->has_backing_file
) {
3209 const char *backing_format
= NULL
;
3211 if (qcow2_opts
->has_backing_fmt
) {
3212 backing_format
= BlockdevDriver_str(qcow2_opts
->backing_fmt
);
3215 ret
= bdrv_change_backing_file(blk_bs(blk
), qcow2_opts
->backing_file
,
3218 error_setg_errno(errp
, -ret
, "Could not assign backing file '%s' "
3219 "with format '%s'", qcow2_opts
->backing_file
,
3225 /* Want encryption? There you go. */
3226 if (qcow2_opts
->has_encrypt
) {
3227 ret
= qcow2_set_up_encryption(blk_bs(blk
), qcow2_opts
->encrypt
, errp
);
3236 /* Reopen the image without BDRV_O_NO_FLUSH to flush it before returning.
3237 * Using BDRV_O_NO_IO, since encryption is now setup we don't want to
3238 * have to setup decryption context. We're not doing any I/O on the top
3239 * level BlockDriverState, only lower layers, where BDRV_O_NO_IO does
3242 options
= qdict_new();
3243 qdict_put_str(options
, "driver", "qcow2");
3244 qdict_put_str(options
, "file", bs
->node_name
);
3246 qdict_put_str(options
, "data-file", data_bs
->node_name
);
3248 blk
= blk_new_open(NULL
, NULL
, options
,
3249 BDRV_O_RDWR
| BDRV_O_NO_BACKING
| BDRV_O_NO_IO
,
3252 error_propagate(errp
, local_err
);
3261 bdrv_unref(data_bs
);
3265 static int coroutine_fn
qcow2_co_create_opts(const char *filename
, QemuOpts
*opts
,
3268 BlockdevCreateOptions
*create_options
= NULL
;
3271 BlockDriverState
*bs
= NULL
;
3272 BlockDriverState
*data_bs
= NULL
;
3273 Error
*local_err
= NULL
;
3277 /* Only the keyval visitor supports the dotted syntax needed for
3278 * encryption, so go through a QDict before getting a QAPI type. Ignore
3279 * options meant for the protocol layer so that the visitor doesn't
3281 qdict
= qemu_opts_to_qdict_filtered(opts
, NULL
, bdrv_qcow2
.create_opts
,
3284 /* Handle encryption options */
3285 val
= qdict_get_try_str(qdict
, BLOCK_OPT_ENCRYPT
);
3286 if (val
&& !strcmp(val
, "on")) {
3287 qdict_put_str(qdict
, BLOCK_OPT_ENCRYPT
, "qcow");
3288 } else if (val
&& !strcmp(val
, "off")) {
3289 qdict_del(qdict
, BLOCK_OPT_ENCRYPT
);
3292 val
= qdict_get_try_str(qdict
, BLOCK_OPT_ENCRYPT_FORMAT
);
3293 if (val
&& !strcmp(val
, "aes")) {
3294 qdict_put_str(qdict
, BLOCK_OPT_ENCRYPT_FORMAT
, "qcow");
3297 /* Convert compat=0.10/1.1 into compat=v2/v3, to be renamed into
3298 * version=v2/v3 below. */
3299 val
= qdict_get_try_str(qdict
, BLOCK_OPT_COMPAT_LEVEL
);
3300 if (val
&& !strcmp(val
, "0.10")) {
3301 qdict_put_str(qdict
, BLOCK_OPT_COMPAT_LEVEL
, "v2");
3302 } else if (val
&& !strcmp(val
, "1.1")) {
3303 qdict_put_str(qdict
, BLOCK_OPT_COMPAT_LEVEL
, "v3");
3306 /* Change legacy command line options into QMP ones */
3307 static const QDictRenames opt_renames
[] = {
3308 { BLOCK_OPT_BACKING_FILE
, "backing-file" },
3309 { BLOCK_OPT_BACKING_FMT
, "backing-fmt" },
3310 { BLOCK_OPT_CLUSTER_SIZE
, "cluster-size" },
3311 { BLOCK_OPT_LAZY_REFCOUNTS
, "lazy-refcounts" },
3312 { BLOCK_OPT_REFCOUNT_BITS
, "refcount-bits" },
3313 { BLOCK_OPT_ENCRYPT
, BLOCK_OPT_ENCRYPT_FORMAT
},
3314 { BLOCK_OPT_COMPAT_LEVEL
, "version" },
3315 { BLOCK_OPT_DATA_FILE_RAW
, "data-file-raw" },
3319 if (!qdict_rename_keys(qdict
, opt_renames
, errp
)) {
3324 /* Create and open the file (protocol layer) */
3325 ret
= bdrv_create_file(filename
, opts
, errp
);
3330 bs
= bdrv_open(filename
, NULL
, NULL
,
3331 BDRV_O_RDWR
| BDRV_O_RESIZE
| BDRV_O_PROTOCOL
, errp
);
3337 /* Create and open an external data file (protocol layer) */
3338 val
= qdict_get_try_str(qdict
, BLOCK_OPT_DATA_FILE
);
3340 ret
= bdrv_create_file(val
, opts
, errp
);
3345 data_bs
= bdrv_open(val
, NULL
, NULL
,
3346 BDRV_O_RDWR
| BDRV_O_RESIZE
| BDRV_O_PROTOCOL
,
3348 if (data_bs
== NULL
) {
3353 qdict_del(qdict
, BLOCK_OPT_DATA_FILE
);
3354 qdict_put_str(qdict
, "data-file", data_bs
->node_name
);
3357 /* Set 'driver' and 'node' options */
3358 qdict_put_str(qdict
, "driver", "qcow2");
3359 qdict_put_str(qdict
, "file", bs
->node_name
);
3361 /* Now get the QAPI type BlockdevCreateOptions */
3362 v
= qobject_input_visitor_new_flat_confused(qdict
, errp
);
3368 visit_type_BlockdevCreateOptions(v
, NULL
, &create_options
, &local_err
);
3372 error_propagate(errp
, local_err
);
3377 /* Silently round up size */
3378 create_options
->u
.qcow2
.size
= ROUND_UP(create_options
->u
.qcow2
.size
,
3381 /* Create the qcow2 image (format layer) */
3382 ret
= qcow2_co_create(create_options
, errp
);
3389 qobject_unref(qdict
);
3391 bdrv_unref(data_bs
);
3392 qapi_free_BlockdevCreateOptions(create_options
);
3397 static bool is_zero(BlockDriverState
*bs
, int64_t offset
, int64_t bytes
)
3402 /* Clamp to image length, before checking status of underlying sectors */
3403 if (offset
+ bytes
> bs
->total_sectors
* BDRV_SECTOR_SIZE
) {
3404 bytes
= bs
->total_sectors
* BDRV_SECTOR_SIZE
- offset
;
3410 res
= bdrv_block_status_above(bs
, NULL
, offset
, bytes
, &nr
, NULL
, NULL
);
3411 return res
>= 0 && (res
& BDRV_BLOCK_ZERO
) && nr
== bytes
;
3414 static coroutine_fn
int qcow2_co_pwrite_zeroes(BlockDriverState
*bs
,
3415 int64_t offset
, int bytes
, BdrvRequestFlags flags
)
3418 BDRVQcow2State
*s
= bs
->opaque
;
3420 uint32_t head
= offset
% s
->cluster_size
;
3421 uint32_t tail
= (offset
+ bytes
) % s
->cluster_size
;
3423 trace_qcow2_pwrite_zeroes_start_req(qemu_coroutine_self(), offset
, bytes
);
3424 if (offset
+ bytes
== bs
->total_sectors
* BDRV_SECTOR_SIZE
) {
3432 assert(head
+ bytes
<= s
->cluster_size
);
3434 /* check whether remainder of cluster already reads as zero */
3435 if (!(is_zero(bs
, offset
- head
, head
) &&
3436 is_zero(bs
, offset
+ bytes
,
3437 tail
? s
->cluster_size
- tail
: 0))) {
3441 qemu_co_mutex_lock(&s
->lock
);
3442 /* We can have new write after previous check */
3443 offset
= QEMU_ALIGN_DOWN(offset
, s
->cluster_size
);
3444 bytes
= s
->cluster_size
;
3445 nr
= s
->cluster_size
;
3446 ret
= qcow2_get_cluster_offset(bs
, offset
, &nr
, &off
);
3447 if (ret
!= QCOW2_CLUSTER_UNALLOCATED
&&
3448 ret
!= QCOW2_CLUSTER_ZERO_PLAIN
&&
3449 ret
!= QCOW2_CLUSTER_ZERO_ALLOC
) {
3450 qemu_co_mutex_unlock(&s
->lock
);
3454 qemu_co_mutex_lock(&s
->lock
);
3457 trace_qcow2_pwrite_zeroes(qemu_coroutine_self(), offset
, bytes
);
3459 /* Whatever is left can use real zero clusters */
3460 ret
= qcow2_cluster_zeroize(bs
, offset
, bytes
, flags
);
3461 qemu_co_mutex_unlock(&s
->lock
);
3466 static coroutine_fn
int qcow2_co_pdiscard(BlockDriverState
*bs
,
3467 int64_t offset
, int bytes
)
3470 BDRVQcow2State
*s
= bs
->opaque
;
3472 if (!QEMU_IS_ALIGNED(offset
| bytes
, s
->cluster_size
)) {
3473 assert(bytes
< s
->cluster_size
);
3474 /* Ignore partial clusters, except for the special case of the
3475 * complete partial cluster at the end of an unaligned file */
3476 if (!QEMU_IS_ALIGNED(offset
, s
->cluster_size
) ||
3477 offset
+ bytes
!= bs
->total_sectors
* BDRV_SECTOR_SIZE
) {
3482 qemu_co_mutex_lock(&s
->lock
);
3483 ret
= qcow2_cluster_discard(bs
, offset
, bytes
, QCOW2_DISCARD_REQUEST
,
3485 qemu_co_mutex_unlock(&s
->lock
);
3489 static int coroutine_fn
3490 qcow2_co_copy_range_from(BlockDriverState
*bs
,
3491 BdrvChild
*src
, uint64_t src_offset
,
3492 BdrvChild
*dst
, uint64_t dst_offset
,
3493 uint64_t bytes
, BdrvRequestFlags read_flags
,
3494 BdrvRequestFlags write_flags
)
3496 BDRVQcow2State
*s
= bs
->opaque
;
3498 unsigned int cur_bytes
; /* number of bytes in current iteration */
3499 BdrvChild
*child
= NULL
;
3500 BdrvRequestFlags cur_write_flags
;
3502 assert(!bs
->encrypted
);
3503 qemu_co_mutex_lock(&s
->lock
);
3505 while (bytes
!= 0) {
3506 uint64_t copy_offset
= 0;
3507 /* prepare next request */
3508 cur_bytes
= MIN(bytes
, INT_MAX
);
3509 cur_write_flags
= write_flags
;
3511 ret
= qcow2_get_cluster_offset(bs
, src_offset
, &cur_bytes
, ©_offset
);
3517 case QCOW2_CLUSTER_UNALLOCATED
:
3518 if (bs
->backing
&& bs
->backing
->bs
) {
3519 int64_t backing_length
= bdrv_getlength(bs
->backing
->bs
);
3520 if (src_offset
>= backing_length
) {
3521 cur_write_flags
|= BDRV_REQ_ZERO_WRITE
;
3523 child
= bs
->backing
;
3524 cur_bytes
= MIN(cur_bytes
, backing_length
- src_offset
);
3525 copy_offset
= src_offset
;
3528 cur_write_flags
|= BDRV_REQ_ZERO_WRITE
;
3532 case QCOW2_CLUSTER_ZERO_PLAIN
:
3533 case QCOW2_CLUSTER_ZERO_ALLOC
:
3534 cur_write_flags
|= BDRV_REQ_ZERO_WRITE
;
3537 case QCOW2_CLUSTER_COMPRESSED
:
3541 case QCOW2_CLUSTER_NORMAL
:
3542 child
= s
->data_file
;
3543 copy_offset
+= offset_into_cluster(s
, src_offset
);
3544 if ((copy_offset
& 511) != 0) {
3553 qemu_co_mutex_unlock(&s
->lock
);
3554 ret
= bdrv_co_copy_range_from(child
,
3557 cur_bytes
, read_flags
, cur_write_flags
);
3558 qemu_co_mutex_lock(&s
->lock
);
3564 src_offset
+= cur_bytes
;
3565 dst_offset
+= cur_bytes
;
3570 qemu_co_mutex_unlock(&s
->lock
);
3574 static int coroutine_fn
3575 qcow2_co_copy_range_to(BlockDriverState
*bs
,
3576 BdrvChild
*src
, uint64_t src_offset
,
3577 BdrvChild
*dst
, uint64_t dst_offset
,
3578 uint64_t bytes
, BdrvRequestFlags read_flags
,
3579 BdrvRequestFlags write_flags
)
3581 BDRVQcow2State
*s
= bs
->opaque
;
3582 int offset_in_cluster
;
3584 unsigned int cur_bytes
; /* number of sectors in current iteration */
3585 uint64_t cluster_offset
;
3586 QCowL2Meta
*l2meta
= NULL
;
3588 assert(!bs
->encrypted
);
3590 qemu_co_mutex_lock(&s
->lock
);
3592 while (bytes
!= 0) {
3596 offset_in_cluster
= offset_into_cluster(s
, dst_offset
);
3597 cur_bytes
= MIN(bytes
, INT_MAX
);
3600 * If src->bs == dst->bs, we could simply copy by incrementing
3601 * the refcnt, without copying user data.
3602 * Or if src->bs == dst->bs->backing->bs, we could copy by discarding. */
3603 ret
= qcow2_alloc_cluster_offset(bs
, dst_offset
, &cur_bytes
,
3604 &cluster_offset
, &l2meta
);
3609 assert((cluster_offset
& 511) == 0);
3611 ret
= qcow2_pre_write_overlap_check(bs
, 0,
3612 cluster_offset
+ offset_in_cluster
, cur_bytes
, true);
3617 qemu_co_mutex_unlock(&s
->lock
);
3618 ret
= bdrv_co_copy_range_to(src
, src_offset
,
3620 cluster_offset
+ offset_in_cluster
,
3621 cur_bytes
, read_flags
, write_flags
);
3622 qemu_co_mutex_lock(&s
->lock
);
3627 ret
= qcow2_handle_l2meta(bs
, &l2meta
, true);
3633 src_offset
+= cur_bytes
;
3634 dst_offset
+= cur_bytes
;
3639 qcow2_handle_l2meta(bs
, &l2meta
, false);
3641 qemu_co_mutex_unlock(&s
->lock
);
3643 trace_qcow2_writev_done_req(qemu_coroutine_self(), ret
);
3648 static int coroutine_fn
qcow2_co_truncate(BlockDriverState
*bs
, int64_t offset
,
3649 PreallocMode prealloc
, Error
**errp
)
3651 BDRVQcow2State
*s
= bs
->opaque
;
3652 uint64_t old_length
;
3653 int64_t new_l1_size
;
3657 if (prealloc
!= PREALLOC_MODE_OFF
&& prealloc
!= PREALLOC_MODE_METADATA
&&
3658 prealloc
!= PREALLOC_MODE_FALLOC
&& prealloc
!= PREALLOC_MODE_FULL
)
3660 error_setg(errp
, "Unsupported preallocation mode '%s'",
3661 PreallocMode_str(prealloc
));
3666 error_setg(errp
, "The new size must be a multiple of 512");
3670 qemu_co_mutex_lock(&s
->lock
);
3672 /* cannot proceed if image has snapshots */
3673 if (s
->nb_snapshots
) {
3674 error_setg(errp
, "Can't resize an image which has snapshots");
3679 /* cannot proceed if image has bitmaps */
3680 if (qcow2_truncate_bitmaps_check(bs
, errp
)) {
3685 old_length
= bs
->total_sectors
* BDRV_SECTOR_SIZE
;
3686 new_l1_size
= size_to_l1(s
, offset
);
3688 if (offset
< old_length
) {
3689 int64_t last_cluster
, old_file_size
;
3690 if (prealloc
!= PREALLOC_MODE_OFF
) {
3692 "Preallocation can't be used for shrinking an image");
3697 ret
= qcow2_cluster_discard(bs
, ROUND_UP(offset
, s
->cluster_size
),
3698 old_length
- ROUND_UP(offset
,
3700 QCOW2_DISCARD_ALWAYS
, true);
3702 error_setg_errno(errp
, -ret
, "Failed to discard cropped clusters");
3706 ret
= qcow2_shrink_l1_table(bs
, new_l1_size
);
3708 error_setg_errno(errp
, -ret
,
3709 "Failed to reduce the number of L2 tables");
3713 ret
= qcow2_shrink_reftable(bs
);
3715 error_setg_errno(errp
, -ret
,
3716 "Failed to discard unused refblocks");
3720 old_file_size
= bdrv_getlength(bs
->file
->bs
);
3721 if (old_file_size
< 0) {
3722 error_setg_errno(errp
, -old_file_size
,
3723 "Failed to inquire current file length");
3724 ret
= old_file_size
;
3727 last_cluster
= qcow2_get_last_cluster(bs
, old_file_size
);
3728 if (last_cluster
< 0) {
3729 error_setg_errno(errp
, -last_cluster
,
3730 "Failed to find the last cluster");
3734 if ((last_cluster
+ 1) * s
->cluster_size
< old_file_size
) {
3735 Error
*local_err
= NULL
;
3737 bdrv_co_truncate(bs
->file
, (last_cluster
+ 1) * s
->cluster_size
,
3738 PREALLOC_MODE_OFF
, &local_err
);
3740 warn_reportf_err(local_err
,
3741 "Failed to truncate the tail of the image: ");
3745 ret
= qcow2_grow_l1_table(bs
, new_l1_size
, true);
3747 error_setg_errno(errp
, -ret
, "Failed to grow the L1 table");
3753 case PREALLOC_MODE_OFF
:
3754 if (has_data_file(bs
)) {
3755 ret
= bdrv_co_truncate(s
->data_file
, offset
, prealloc
, errp
);
3762 case PREALLOC_MODE_METADATA
:
3763 ret
= preallocate_co(bs
, old_length
, offset
, prealloc
, errp
);
3769 case PREALLOC_MODE_FALLOC
:
3770 case PREALLOC_MODE_FULL
:
3772 int64_t allocation_start
, host_offset
, guest_offset
;
3773 int64_t clusters_allocated
;
3774 int64_t old_file_size
, new_file_size
;
3775 uint64_t nb_new_data_clusters
, nb_new_l2_tables
;
3777 /* With a data file, preallocation means just allocating the metadata
3778 * and forwarding the truncate request to the data file */
3779 if (has_data_file(bs
)) {
3780 ret
= preallocate_co(bs
, old_length
, offset
, prealloc
, errp
);
3787 old_file_size
= bdrv_getlength(bs
->file
->bs
);
3788 if (old_file_size
< 0) {
3789 error_setg_errno(errp
, -old_file_size
,
3790 "Failed to inquire current file length");
3791 ret
= old_file_size
;
3794 old_file_size
= ROUND_UP(old_file_size
, s
->cluster_size
);
3796 nb_new_data_clusters
= DIV_ROUND_UP(offset
- old_length
,
3799 /* This is an overestimation; we will not actually allocate space for
3800 * these in the file but just make sure the new refcount structures are
3801 * able to cover them so we will not have to allocate new refblocks
3802 * while entering the data blocks in the potentially new L2 tables.
3803 * (We do not actually care where the L2 tables are placed. Maybe they
3804 * are already allocated or they can be placed somewhere before
3805 * @old_file_size. It does not matter because they will be fully
3806 * allocated automatically, so they do not need to be covered by the
3807 * preallocation. All that matters is that we will not have to allocate
3808 * new refcount structures for them.) */
3809 nb_new_l2_tables
= DIV_ROUND_UP(nb_new_data_clusters
,
3810 s
->cluster_size
/ sizeof(uint64_t));
3811 /* The cluster range may not be aligned to L2 boundaries, so add one L2
3812 * table for a potential head/tail */
3815 allocation_start
= qcow2_refcount_area(bs
, old_file_size
,
3816 nb_new_data_clusters
+
3819 if (allocation_start
< 0) {
3820 error_setg_errno(errp
, -allocation_start
,
3821 "Failed to resize refcount structures");
3822 ret
= allocation_start
;
3826 clusters_allocated
= qcow2_alloc_clusters_at(bs
, allocation_start
,
3827 nb_new_data_clusters
);
3828 if (clusters_allocated
< 0) {
3829 error_setg_errno(errp
, -clusters_allocated
,
3830 "Failed to allocate data clusters");
3831 ret
= clusters_allocated
;
3835 assert(clusters_allocated
== nb_new_data_clusters
);
3837 /* Allocate the data area */
3838 new_file_size
= allocation_start
+
3839 nb_new_data_clusters
* s
->cluster_size
;
3840 ret
= bdrv_co_truncate(bs
->file
, new_file_size
, prealloc
, errp
);
3842 error_prepend(errp
, "Failed to resize underlying file: ");
3843 qcow2_free_clusters(bs
, allocation_start
,
3844 nb_new_data_clusters
* s
->cluster_size
,
3845 QCOW2_DISCARD_OTHER
);
3849 /* Create the necessary L2 entries */
3850 host_offset
= allocation_start
;
3851 guest_offset
= old_length
;
3852 while (nb_new_data_clusters
) {
3853 int64_t nb_clusters
= MIN(
3854 nb_new_data_clusters
,
3855 s
->l2_slice_size
- offset_to_l2_slice_index(s
, guest_offset
));
3856 QCowL2Meta allocation
= {
3857 .offset
= guest_offset
,
3858 .alloc_offset
= host_offset
,
3859 .nb_clusters
= nb_clusters
,
3861 qemu_co_queue_init(&allocation
.dependent_requests
);
3863 ret
= qcow2_alloc_cluster_link_l2(bs
, &allocation
);
3865 error_setg_errno(errp
, -ret
, "Failed to update L2 tables");
3866 qcow2_free_clusters(bs
, host_offset
,
3867 nb_new_data_clusters
* s
->cluster_size
,
3868 QCOW2_DISCARD_OTHER
);
3872 guest_offset
+= nb_clusters
* s
->cluster_size
;
3873 host_offset
+= nb_clusters
* s
->cluster_size
;
3874 nb_new_data_clusters
-= nb_clusters
;
3880 g_assert_not_reached();
3883 if (prealloc
!= PREALLOC_MODE_OFF
) {
3884 /* Flush metadata before actually changing the image size */
3885 ret
= qcow2_write_caches(bs
);
3887 error_setg_errno(errp
, -ret
,
3888 "Failed to flush the preallocated area to disk");
3893 bs
->total_sectors
= offset
/ BDRV_SECTOR_SIZE
;
3895 /* write updated header.size */
3896 offset
= cpu_to_be64(offset
);
3897 ret
= bdrv_pwrite_sync(bs
->file
, offsetof(QCowHeader
, size
),
3898 &offset
, sizeof(uint64_t));
3900 error_setg_errno(errp
, -ret
, "Failed to update the image size");
3904 s
->l1_vm_state_index
= new_l1_size
;
3906 /* Update cache sizes */
3907 options
= qdict_clone_shallow(bs
->options
);
3908 ret
= qcow2_update_options(bs
, options
, s
->flags
, errp
);
3909 qobject_unref(options
);
3915 qemu_co_mutex_unlock(&s
->lock
);
3919 /* XXX: put compressed sectors first, then all the cluster aligned
3920 tables to avoid losing bytes in alignment */
3921 static coroutine_fn
int
3922 qcow2_co_pwritev_compressed(BlockDriverState
*bs
, uint64_t offset
,
3923 uint64_t bytes
, QEMUIOVector
*qiov
)
3925 BDRVQcow2State
*s
= bs
->opaque
;
3928 uint8_t *buf
, *out_buf
;
3929 uint64_t cluster_offset
;
3931 if (has_data_file(bs
)) {
3936 /* align end of file to a sector boundary to ease reading with
3937 sector based I/Os */
3938 int64_t len
= bdrv_getlength(bs
->file
->bs
);
3942 return bdrv_co_truncate(bs
->file
, len
, PREALLOC_MODE_OFF
, NULL
);
3945 if (offset_into_cluster(s
, offset
)) {
3949 buf
= qemu_blockalign(bs
, s
->cluster_size
);
3950 if (bytes
!= s
->cluster_size
) {
3951 if (bytes
> s
->cluster_size
||
3952 offset
+ bytes
!= bs
->total_sectors
<< BDRV_SECTOR_BITS
)
3957 /* Zero-pad last write if image size is not cluster aligned */
3958 memset(buf
+ bytes
, 0, s
->cluster_size
- bytes
);
3960 qemu_iovec_to_buf(qiov
, 0, buf
, bytes
);
3962 out_buf
= g_malloc(s
->cluster_size
);
3964 out_len
= qcow2_co_compress(bs
, out_buf
, s
->cluster_size
- 1,
3965 buf
, s
->cluster_size
);
3966 if (out_len
== -ENOMEM
) {
3967 /* could not compress: write normal cluster */
3968 ret
= qcow2_co_pwritev(bs
, offset
, bytes
, qiov
, 0);
3973 } else if (out_len
< 0) {
3978 qemu_co_mutex_lock(&s
->lock
);
3979 ret
= qcow2_alloc_compressed_cluster_offset(bs
, offset
, out_len
,
3982 qemu_co_mutex_unlock(&s
->lock
);
3986 ret
= qcow2_pre_write_overlap_check(bs
, 0, cluster_offset
, out_len
, true);
3987 qemu_co_mutex_unlock(&s
->lock
);
3992 BLKDBG_EVENT(s
->data_file
, BLKDBG_WRITE_COMPRESSED
);
3993 ret
= bdrv_co_pwrite(s
->data_file
, cluster_offset
, out_len
, out_buf
, 0);
4005 static int coroutine_fn
4006 qcow2_co_preadv_compressed(BlockDriverState
*bs
,
4007 uint64_t file_cluster_offset
,
4012 BDRVQcow2State
*s
= bs
->opaque
;
4013 int ret
= 0, csize
, nb_csectors
;
4015 uint8_t *buf
, *out_buf
;
4016 int offset_in_cluster
= offset_into_cluster(s
, offset
);
4018 coffset
= file_cluster_offset
& s
->cluster_offset_mask
;
4019 nb_csectors
= ((file_cluster_offset
>> s
->csize_shift
) & s
->csize_mask
) + 1;
4020 csize
= nb_csectors
* QCOW2_COMPRESSED_SECTOR_SIZE
-
4021 (coffset
& ~QCOW2_COMPRESSED_SECTOR_MASK
);
4023 buf
= g_try_malloc(csize
);
4028 out_buf
= qemu_blockalign(bs
, s
->cluster_size
);
4030 BLKDBG_EVENT(bs
->file
, BLKDBG_READ_COMPRESSED
);
4031 ret
= bdrv_co_pread(bs
->file
, coffset
, csize
, buf
, 0);
4036 if (qcow2_co_decompress(bs
, out_buf
, s
->cluster_size
, buf
, csize
) < 0) {
4041 qemu_iovec_from_buf(qiov
, 0, out_buf
+ offset_in_cluster
, bytes
);
4044 qemu_vfree(out_buf
);
4050 static int make_completely_empty(BlockDriverState
*bs
)
4052 BDRVQcow2State
*s
= bs
->opaque
;
4053 Error
*local_err
= NULL
;
4054 int ret
, l1_clusters
;
4056 uint64_t *new_reftable
= NULL
;
4057 uint64_t rt_entry
, l1_size2
;
4060 uint64_t reftable_offset
;
4061 uint32_t reftable_clusters
;
4062 } QEMU_PACKED l1_ofs_rt_ofs_cls
;
4064 ret
= qcow2_cache_empty(bs
, s
->l2_table_cache
);
4069 ret
= qcow2_cache_empty(bs
, s
->refcount_block_cache
);
4074 /* Refcounts will be broken utterly */
4075 ret
= qcow2_mark_dirty(bs
);
4080 BLKDBG_EVENT(bs
->file
, BLKDBG_L1_UPDATE
);
4082 l1_clusters
= DIV_ROUND_UP(s
->l1_size
, s
->cluster_size
/ sizeof(uint64_t));
4083 l1_size2
= (uint64_t)s
->l1_size
* sizeof(uint64_t);
4085 /* After this call, neither the in-memory nor the on-disk refcount
4086 * information accurately describe the actual references */
4088 ret
= bdrv_pwrite_zeroes(bs
->file
, s
->l1_table_offset
,
4089 l1_clusters
* s
->cluster_size
, 0);
4091 goto fail_broken_refcounts
;
4093 memset(s
->l1_table
, 0, l1_size2
);
4095 BLKDBG_EVENT(bs
->file
, BLKDBG_EMPTY_IMAGE_PREPARE
);
4097 /* Overwrite enough clusters at the beginning of the sectors to place
4098 * the refcount table, a refcount block and the L1 table in; this may
4099 * overwrite parts of the existing refcount and L1 table, which is not
4100 * an issue because the dirty flag is set, complete data loss is in fact
4101 * desired and partial data loss is consequently fine as well */
4102 ret
= bdrv_pwrite_zeroes(bs
->file
, s
->cluster_size
,
4103 (2 + l1_clusters
) * s
->cluster_size
, 0);
4104 /* This call (even if it failed overall) may have overwritten on-disk
4105 * refcount structures; in that case, the in-memory refcount information
4106 * will probably differ from the on-disk information which makes the BDS
4109 goto fail_broken_refcounts
;
4112 BLKDBG_EVENT(bs
->file
, BLKDBG_L1_UPDATE
);
4113 BLKDBG_EVENT(bs
->file
, BLKDBG_REFTABLE_UPDATE
);
4115 /* "Create" an empty reftable (one cluster) directly after the image
4116 * header and an empty L1 table three clusters after the image header;
4117 * the cluster between those two will be used as the first refblock */
4118 l1_ofs_rt_ofs_cls
.l1_offset
= cpu_to_be64(3 * s
->cluster_size
);
4119 l1_ofs_rt_ofs_cls
.reftable_offset
= cpu_to_be64(s
->cluster_size
);
4120 l1_ofs_rt_ofs_cls
.reftable_clusters
= cpu_to_be32(1);
4121 ret
= bdrv_pwrite_sync(bs
->file
, offsetof(QCowHeader
, l1_table_offset
),
4122 &l1_ofs_rt_ofs_cls
, sizeof(l1_ofs_rt_ofs_cls
));
4124 goto fail_broken_refcounts
;
4127 s
->l1_table_offset
= 3 * s
->cluster_size
;
4129 new_reftable
= g_try_new0(uint64_t, s
->cluster_size
/ sizeof(uint64_t));
4130 if (!new_reftable
) {
4132 goto fail_broken_refcounts
;
4135 s
->refcount_table_offset
= s
->cluster_size
;
4136 s
->refcount_table_size
= s
->cluster_size
/ sizeof(uint64_t);
4137 s
->max_refcount_table_index
= 0;
4139 g_free(s
->refcount_table
);
4140 s
->refcount_table
= new_reftable
;
4141 new_reftable
= NULL
;
4143 /* Now the in-memory refcount information again corresponds to the on-disk
4144 * information (reftable is empty and no refblocks (the refblock cache is
4145 * empty)); however, this means some clusters (e.g. the image header) are
4146 * referenced, but not refcounted, but the normal qcow2 code assumes that
4147 * the in-memory information is always correct */
4149 BLKDBG_EVENT(bs
->file
, BLKDBG_REFBLOCK_ALLOC
);
4151 /* Enter the first refblock into the reftable */
4152 rt_entry
= cpu_to_be64(2 * s
->cluster_size
);
4153 ret
= bdrv_pwrite_sync(bs
->file
, s
->cluster_size
,
4154 &rt_entry
, sizeof(rt_entry
));
4156 goto fail_broken_refcounts
;
4158 s
->refcount_table
[0] = 2 * s
->cluster_size
;
4160 s
->free_cluster_index
= 0;
4161 assert(3 + l1_clusters
<= s
->refcount_block_size
);
4162 offset
= qcow2_alloc_clusters(bs
, 3 * s
->cluster_size
+ l1_size2
);
4165 goto fail_broken_refcounts
;
4166 } else if (offset
> 0) {
4167 error_report("First cluster in emptied image is in use");
4171 /* Now finally the in-memory information corresponds to the on-disk
4172 * structures and is correct */
4173 ret
= qcow2_mark_clean(bs
);
4178 ret
= bdrv_truncate(bs
->file
, (3 + l1_clusters
) * s
->cluster_size
,
4179 PREALLOC_MODE_OFF
, &local_err
);
4181 error_report_err(local_err
);
4187 fail_broken_refcounts
:
4188 /* The BDS is unusable at this point. If we wanted to make it usable, we
4189 * would have to call qcow2_refcount_close(), qcow2_refcount_init(),
4190 * qcow2_check_refcounts(), qcow2_refcount_close() and qcow2_refcount_init()
4191 * again. However, because the functions which could have caused this error
4192 * path to be taken are used by those functions as well, it's very likely
4193 * that that sequence will fail as well. Therefore, just eject the BDS. */
4197 g_free(new_reftable
);
4201 static int qcow2_make_empty(BlockDriverState
*bs
)
4203 BDRVQcow2State
*s
= bs
->opaque
;
4204 uint64_t offset
, end_offset
;
4205 int step
= QEMU_ALIGN_DOWN(INT_MAX
, s
->cluster_size
);
4206 int l1_clusters
, ret
= 0;
4208 l1_clusters
= DIV_ROUND_UP(s
->l1_size
, s
->cluster_size
/ sizeof(uint64_t));
4210 if (s
->qcow_version
>= 3 && !s
->snapshots
&& !s
->nb_bitmaps
&&
4211 3 + l1_clusters
<= s
->refcount_block_size
&&
4212 s
->crypt_method_header
!= QCOW_CRYPT_LUKS
&&
4213 !has_data_file(bs
)) {
4214 /* The following function only works for qcow2 v3 images (it
4215 * requires the dirty flag) and only as long as there are no
4216 * features that reserve extra clusters (such as snapshots,
4217 * LUKS header, or persistent bitmaps), because it completely
4218 * empties the image. Furthermore, the L1 table and three
4219 * additional clusters (image header, refcount table, one
4220 * refcount block) have to fit inside one refcount block. It
4221 * only resets the image file, i.e. does not work with an
4222 * external data file. */
4223 return make_completely_empty(bs
);
4226 /* This fallback code simply discards every active cluster; this is slow,
4227 * but works in all cases */
4228 end_offset
= bs
->total_sectors
* BDRV_SECTOR_SIZE
;
4229 for (offset
= 0; offset
< end_offset
; offset
+= step
) {
4230 /* As this function is generally used after committing an external
4231 * snapshot, QCOW2_DISCARD_SNAPSHOT seems appropriate. Also, the
4232 * default action for this kind of discard is to pass the discard,
4233 * which will ideally result in an actually smaller image file, as
4234 * is probably desired. */
4235 ret
= qcow2_cluster_discard(bs
, offset
, MIN(step
, end_offset
- offset
),
4236 QCOW2_DISCARD_SNAPSHOT
, true);
4245 static coroutine_fn
int qcow2_co_flush_to_os(BlockDriverState
*bs
)
4247 BDRVQcow2State
*s
= bs
->opaque
;
4250 qemu_co_mutex_lock(&s
->lock
);
4251 ret
= qcow2_write_caches(bs
);
4252 qemu_co_mutex_unlock(&s
->lock
);
4257 static ssize_t
qcow2_measure_crypto_hdr_init_func(QCryptoBlock
*block
,
4258 size_t headerlen
, void *opaque
, Error
**errp
)
4260 size_t *headerlenp
= opaque
;
4262 /* Stash away the payload size */
4263 *headerlenp
= headerlen
;
4267 static ssize_t
qcow2_measure_crypto_hdr_write_func(QCryptoBlock
*block
,
4268 size_t offset
, const uint8_t *buf
, size_t buflen
,
4269 void *opaque
, Error
**errp
)
4271 /* Discard the bytes, we're not actually writing to an image */
4275 /* Determine the number of bytes for the LUKS payload */
4276 static bool qcow2_measure_luks_headerlen(QemuOpts
*opts
, size_t *len
,
4280 QDict
*cryptoopts_qdict
;
4281 QCryptoBlockCreateOptions
*cryptoopts
;
4282 QCryptoBlock
*crypto
;
4284 /* Extract "encrypt." options into a qdict */
4285 opts_qdict
= qemu_opts_to_qdict(opts
, NULL
);
4286 qdict_extract_subqdict(opts_qdict
, &cryptoopts_qdict
, "encrypt.");
4287 qobject_unref(opts_qdict
);
4289 /* Build QCryptoBlockCreateOptions object from qdict */
4290 qdict_put_str(cryptoopts_qdict
, "format", "luks");
4291 cryptoopts
= block_crypto_create_opts_init(cryptoopts_qdict
, errp
);
4292 qobject_unref(cryptoopts_qdict
);
4297 /* Fake LUKS creation in order to determine the payload size */
4298 crypto
= qcrypto_block_create(cryptoopts
, "encrypt.",
4299 qcow2_measure_crypto_hdr_init_func
,
4300 qcow2_measure_crypto_hdr_write_func
,
4302 qapi_free_QCryptoBlockCreateOptions(cryptoopts
);
4307 qcrypto_block_free(crypto
);
4311 static BlockMeasureInfo
*qcow2_measure(QemuOpts
*opts
, BlockDriverState
*in_bs
,
4314 Error
*local_err
= NULL
;
4315 BlockMeasureInfo
*info
;
4316 uint64_t required
= 0; /* bytes that contribute to required size */
4317 uint64_t virtual_size
; /* disk size as seen by guest */
4318 uint64_t refcount_bits
;
4320 uint64_t luks_payload_size
= 0;
4321 size_t cluster_size
;
4324 PreallocMode prealloc
;
4325 bool has_backing_file
;
4328 /* Parse image creation options */
4329 cluster_size
= qcow2_opt_get_cluster_size_del(opts
, &local_err
);
4334 version
= qcow2_opt_get_version_del(opts
, &local_err
);
4339 refcount_bits
= qcow2_opt_get_refcount_bits_del(opts
, version
, &local_err
);
4344 optstr
= qemu_opt_get_del(opts
, BLOCK_OPT_PREALLOC
);
4345 prealloc
= qapi_enum_parse(&PreallocMode_lookup
, optstr
,
4346 PREALLOC_MODE_OFF
, &local_err
);
4352 optstr
= qemu_opt_get_del(opts
, BLOCK_OPT_BACKING_FILE
);
4353 has_backing_file
= !!optstr
;
4356 optstr
= qemu_opt_get_del(opts
, BLOCK_OPT_ENCRYPT_FORMAT
);
4357 has_luks
= optstr
&& strcmp(optstr
, "luks") == 0;
4363 if (!qcow2_measure_luks_headerlen(opts
, &headerlen
, &local_err
)) {
4367 luks_payload_size
= ROUND_UP(headerlen
, cluster_size
);
4370 virtual_size
= qemu_opt_get_size_del(opts
, BLOCK_OPT_SIZE
, 0);
4371 virtual_size
= ROUND_UP(virtual_size
, cluster_size
);
4373 /* Check that virtual disk size is valid */
4374 l2_tables
= DIV_ROUND_UP(virtual_size
/ cluster_size
,
4375 cluster_size
/ sizeof(uint64_t));
4376 if (l2_tables
* sizeof(uint64_t) > QCOW_MAX_L1_SIZE
) {
4377 error_setg(&local_err
, "The image size is too large "
4378 "(try using a larger cluster size)");
4382 /* Account for input image */
4384 int64_t ssize
= bdrv_getlength(in_bs
);
4386 error_setg_errno(&local_err
, -ssize
,
4387 "Unable to get image virtual_size");
4391 virtual_size
= ROUND_UP(ssize
, cluster_size
);
4393 if (has_backing_file
) {
4394 /* We don't how much of the backing chain is shared by the input
4395 * image and the new image file. In the worst case the new image's
4396 * backing file has nothing in common with the input image. Be
4397 * conservative and assume all clusters need to be written.
4399 required
= virtual_size
;
4404 for (offset
= 0; offset
< ssize
; offset
+= pnum
) {
4407 ret
= bdrv_block_status_above(in_bs
, NULL
, offset
,
4408 ssize
- offset
, &pnum
, NULL
,
4411 error_setg_errno(&local_err
, -ret
,
4412 "Unable to get block status");
4416 if (ret
& BDRV_BLOCK_ZERO
) {
4417 /* Skip zero regions (safe with no backing file) */
4418 } else if ((ret
& (BDRV_BLOCK_DATA
| BDRV_BLOCK_ALLOCATED
)) ==
4419 (BDRV_BLOCK_DATA
| BDRV_BLOCK_ALLOCATED
)) {
4420 /* Extend pnum to end of cluster for next iteration */
4421 pnum
= ROUND_UP(offset
+ pnum
, cluster_size
) - offset
;
4423 /* Count clusters we've seen */
4424 required
+= offset
% cluster_size
+ pnum
;
4430 /* Take into account preallocation. Nothing special is needed for
4431 * PREALLOC_MODE_METADATA since metadata is always counted.
4433 if (prealloc
== PREALLOC_MODE_FULL
|| prealloc
== PREALLOC_MODE_FALLOC
) {
4434 required
= virtual_size
;
4437 info
= g_new(BlockMeasureInfo
, 1);
4438 info
->fully_allocated
=
4439 qcow2_calc_prealloc_size(virtual_size
, cluster_size
,
4440 ctz32(refcount_bits
)) + luks_payload_size
;
4442 /* Remove data clusters that are not required. This overestimates the
4443 * required size because metadata needed for the fully allocated file is
4446 info
->required
= info
->fully_allocated
- virtual_size
+ required
;
4450 error_propagate(errp
, local_err
);
4454 static int qcow2_get_info(BlockDriverState
*bs
, BlockDriverInfo
*bdi
)
4456 BDRVQcow2State
*s
= bs
->opaque
;
4457 bdi
->unallocated_blocks_are_zero
= true;
4458 bdi
->cluster_size
= s
->cluster_size
;
4459 bdi
->vm_state_offset
= qcow2_vm_state_offset(s
);
4463 static ImageInfoSpecific
*qcow2_get_specific_info(BlockDriverState
*bs
,
4466 BDRVQcow2State
*s
= bs
->opaque
;
4467 ImageInfoSpecific
*spec_info
;
4468 QCryptoBlockInfo
*encrypt_info
= NULL
;
4469 Error
*local_err
= NULL
;
4471 if (s
->crypto
!= NULL
) {
4472 encrypt_info
= qcrypto_block_get_info(s
->crypto
, &local_err
);
4474 error_propagate(errp
, local_err
);
4479 spec_info
= g_new(ImageInfoSpecific
, 1);
4480 *spec_info
= (ImageInfoSpecific
){
4481 .type
= IMAGE_INFO_SPECIFIC_KIND_QCOW2
,
4482 .u
.qcow2
.data
= g_new0(ImageInfoSpecificQCow2
, 1),
4484 if (s
->qcow_version
== 2) {
4485 *spec_info
->u
.qcow2
.data
= (ImageInfoSpecificQCow2
){
4486 .compat
= g_strdup("0.10"),
4487 .refcount_bits
= s
->refcount_bits
,
4489 } else if (s
->qcow_version
== 3) {
4490 Qcow2BitmapInfoList
*bitmaps
;
4491 bitmaps
= qcow2_get_bitmap_info_list(bs
, &local_err
);
4493 error_propagate(errp
, local_err
);
4494 qapi_free_ImageInfoSpecific(spec_info
);
4497 *spec_info
->u
.qcow2
.data
= (ImageInfoSpecificQCow2
){
4498 .compat
= g_strdup("1.1"),
4499 .lazy_refcounts
= s
->compatible_features
&
4500 QCOW2_COMPAT_LAZY_REFCOUNTS
,
4501 .has_lazy_refcounts
= true,
4502 .corrupt
= s
->incompatible_features
&
4503 QCOW2_INCOMPAT_CORRUPT
,
4504 .has_corrupt
= true,
4505 .refcount_bits
= s
->refcount_bits
,
4506 .has_bitmaps
= !!bitmaps
,
4508 .has_data_file
= !!s
->image_data_file
,
4509 .data_file
= g_strdup(s
->image_data_file
),
4510 .has_data_file_raw
= has_data_file(bs
),
4511 .data_file_raw
= data_file_is_raw(bs
),
4514 /* if this assertion fails, this probably means a new version was
4515 * added without having it covered here */
4520 ImageInfoSpecificQCow2Encryption
*qencrypt
=
4521 g_new(ImageInfoSpecificQCow2Encryption
, 1);
4522 switch (encrypt_info
->format
) {
4523 case Q_CRYPTO_BLOCK_FORMAT_QCOW
:
4524 qencrypt
->format
= BLOCKDEV_QCOW2_ENCRYPTION_FORMAT_AES
;
4526 case Q_CRYPTO_BLOCK_FORMAT_LUKS
:
4527 qencrypt
->format
= BLOCKDEV_QCOW2_ENCRYPTION_FORMAT_LUKS
;
4528 qencrypt
->u
.luks
= encrypt_info
->u
.luks
;
4533 /* Since we did shallow copy above, erase any pointers
4534 * in the original info */
4535 memset(&encrypt_info
->u
, 0, sizeof(encrypt_info
->u
));
4536 qapi_free_QCryptoBlockInfo(encrypt_info
);
4538 spec_info
->u
.qcow2
.data
->has_encrypt
= true;
4539 spec_info
->u
.qcow2
.data
->encrypt
= qencrypt
;
4545 static int qcow2_save_vmstate(BlockDriverState
*bs
, QEMUIOVector
*qiov
,
4548 BDRVQcow2State
*s
= bs
->opaque
;
4550 BLKDBG_EVENT(bs
->file
, BLKDBG_VMSTATE_SAVE
);
4551 return bs
->drv
->bdrv_co_pwritev(bs
, qcow2_vm_state_offset(s
) + pos
,
4552 qiov
->size
, qiov
, 0);
4555 static int qcow2_load_vmstate(BlockDriverState
*bs
, QEMUIOVector
*qiov
,
4558 BDRVQcow2State
*s
= bs
->opaque
;
4560 BLKDBG_EVENT(bs
->file
, BLKDBG_VMSTATE_LOAD
);
4561 return bs
->drv
->bdrv_co_preadv(bs
, qcow2_vm_state_offset(s
) + pos
,
4562 qiov
->size
, qiov
, 0);
4566 * Downgrades an image's version. To achieve this, any incompatible features
4567 * have to be removed.
4569 static int qcow2_downgrade(BlockDriverState
*bs
, int target_version
,
4570 BlockDriverAmendStatusCB
*status_cb
, void *cb_opaque
,
4573 BDRVQcow2State
*s
= bs
->opaque
;
4574 int current_version
= s
->qcow_version
;
4577 /* This is qcow2_downgrade(), not qcow2_upgrade() */
4578 assert(target_version
< current_version
);
4580 /* There are no other versions (now) that you can downgrade to */
4581 assert(target_version
== 2);
4583 if (s
->refcount_order
!= 4) {
4584 error_setg(errp
, "compat=0.10 requires refcount_bits=16");
4588 if (has_data_file(bs
)) {
4589 error_setg(errp
, "Cannot downgrade an image with a data file");
4593 /* clear incompatible features */
4594 if (s
->incompatible_features
& QCOW2_INCOMPAT_DIRTY
) {
4595 ret
= qcow2_mark_clean(bs
);
4597 error_setg_errno(errp
, -ret
, "Failed to make the image clean");
4602 /* with QCOW2_INCOMPAT_CORRUPT, it is pretty much impossible to get here in
4603 * the first place; if that happens nonetheless, returning -ENOTSUP is the
4604 * best thing to do anyway */
4606 if (s
->incompatible_features
) {
4607 error_setg(errp
, "Cannot downgrade an image with incompatible features "
4608 "%#" PRIx64
" set", s
->incompatible_features
);
4612 /* since we can ignore compatible features, we can set them to 0 as well */
4613 s
->compatible_features
= 0;
4614 /* if lazy refcounts have been used, they have already been fixed through
4615 * clearing the dirty flag */
4617 /* clearing autoclear features is trivial */
4618 s
->autoclear_features
= 0;
4620 ret
= qcow2_expand_zero_clusters(bs
, status_cb
, cb_opaque
);
4622 error_setg_errno(errp
, -ret
, "Failed to turn zero into data clusters");
4626 s
->qcow_version
= target_version
;
4627 ret
= qcow2_update_header(bs
);
4629 s
->qcow_version
= current_version
;
4630 error_setg_errno(errp
, -ret
, "Failed to update the image header");
4636 typedef enum Qcow2AmendOperation
{
4637 /* This is the value Qcow2AmendHelperCBInfo::last_operation will be
4638 * statically initialized to so that the helper CB can discern the first
4639 * invocation from an operation change */
4640 QCOW2_NO_OPERATION
= 0,
4642 QCOW2_CHANGING_REFCOUNT_ORDER
,
4644 } Qcow2AmendOperation
;
4646 typedef struct Qcow2AmendHelperCBInfo
{
4647 /* The code coordinating the amend operations should only modify
4648 * these four fields; the rest will be managed by the CB */
4649 BlockDriverAmendStatusCB
*original_status_cb
;
4650 void *original_cb_opaque
;
4652 Qcow2AmendOperation current_operation
;
4654 /* Total number of operations to perform (only set once) */
4655 int total_operations
;
4657 /* The following fields are managed by the CB */
4659 /* Number of operations completed */
4660 int operations_completed
;
4662 /* Cumulative offset of all completed operations */
4663 int64_t offset_completed
;
4665 Qcow2AmendOperation last_operation
;
4666 int64_t last_work_size
;
4667 } Qcow2AmendHelperCBInfo
;
4669 static void qcow2_amend_helper_cb(BlockDriverState
*bs
,
4670 int64_t operation_offset
,
4671 int64_t operation_work_size
, void *opaque
)
4673 Qcow2AmendHelperCBInfo
*info
= opaque
;
4674 int64_t current_work_size
;
4675 int64_t projected_work_size
;
4677 if (info
->current_operation
!= info
->last_operation
) {
4678 if (info
->last_operation
!= QCOW2_NO_OPERATION
) {
4679 info
->offset_completed
+= info
->last_work_size
;
4680 info
->operations_completed
++;
4683 info
->last_operation
= info
->current_operation
;
4686 assert(info
->total_operations
> 0);
4687 assert(info
->operations_completed
< info
->total_operations
);
4689 info
->last_work_size
= operation_work_size
;
4691 current_work_size
= info
->offset_completed
+ operation_work_size
;
4693 /* current_work_size is the total work size for (operations_completed + 1)
4694 * operations (which includes this one), so multiply it by the number of
4695 * operations not covered and divide it by the number of operations
4696 * covered to get a projection for the operations not covered */
4697 projected_work_size
= current_work_size
* (info
->total_operations
-
4698 info
->operations_completed
- 1)
4699 / (info
->operations_completed
+ 1);
4701 info
->original_status_cb(bs
, info
->offset_completed
+ operation_offset
,
4702 current_work_size
+ projected_work_size
,
4703 info
->original_cb_opaque
);
4706 static int qcow2_amend_options(BlockDriverState
*bs
, QemuOpts
*opts
,
4707 BlockDriverAmendStatusCB
*status_cb
,
4711 BDRVQcow2State
*s
= bs
->opaque
;
4712 int old_version
= s
->qcow_version
, new_version
= old_version
;
4713 uint64_t new_size
= 0;
4714 const char *backing_file
= NULL
, *backing_format
= NULL
, *data_file
= NULL
;
4715 bool lazy_refcounts
= s
->use_lazy_refcounts
;
4716 bool data_file_raw
= data_file_is_raw(bs
);
4717 const char *compat
= NULL
;
4718 uint64_t cluster_size
= s
->cluster_size
;
4721 int refcount_bits
= s
->refcount_bits
;
4723 QemuOptDesc
*desc
= opts
->list
->desc
;
4724 Qcow2AmendHelperCBInfo helper_cb_info
;
4726 while (desc
&& desc
->name
) {
4727 if (!qemu_opt_find(opts
, desc
->name
)) {
4728 /* only change explicitly defined options */
4733 if (!strcmp(desc
->name
, BLOCK_OPT_COMPAT_LEVEL
)) {
4734 compat
= qemu_opt_get(opts
, BLOCK_OPT_COMPAT_LEVEL
);
4736 /* preserve default */
4737 } else if (!strcmp(compat
, "0.10")) {
4739 } else if (!strcmp(compat
, "1.1")) {
4742 error_setg(errp
, "Unknown compatibility level %s", compat
);
4745 } else if (!strcmp(desc
->name
, BLOCK_OPT_PREALLOC
)) {
4746 error_setg(errp
, "Cannot change preallocation mode");
4748 } else if (!strcmp(desc
->name
, BLOCK_OPT_SIZE
)) {
4749 new_size
= qemu_opt_get_size(opts
, BLOCK_OPT_SIZE
, 0);
4750 } else if (!strcmp(desc
->name
, BLOCK_OPT_BACKING_FILE
)) {
4751 backing_file
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FILE
);
4752 } else if (!strcmp(desc
->name
, BLOCK_OPT_BACKING_FMT
)) {
4753 backing_format
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FMT
);
4754 } else if (!strcmp(desc
->name
, BLOCK_OPT_ENCRYPT
)) {
4755 encrypt
= qemu_opt_get_bool(opts
, BLOCK_OPT_ENCRYPT
,
4758 if (encrypt
!= !!s
->crypto
) {
4760 "Changing the encryption flag is not supported");
4763 } else if (!strcmp(desc
->name
, BLOCK_OPT_ENCRYPT_FORMAT
)) {
4764 encformat
= qcow2_crypt_method_from_format(
4765 qemu_opt_get(opts
, BLOCK_OPT_ENCRYPT_FORMAT
));
4767 if (encformat
!= s
->crypt_method_header
) {
4769 "Changing the encryption format is not supported");
4772 } else if (g_str_has_prefix(desc
->name
, "encrypt.")) {
4774 "Changing the encryption parameters is not supported");
4776 } else if (!strcmp(desc
->name
, BLOCK_OPT_CLUSTER_SIZE
)) {
4777 cluster_size
= qemu_opt_get_size(opts
, BLOCK_OPT_CLUSTER_SIZE
,
4779 if (cluster_size
!= s
->cluster_size
) {
4780 error_setg(errp
, "Changing the cluster size is not supported");
4783 } else if (!strcmp(desc
->name
, BLOCK_OPT_LAZY_REFCOUNTS
)) {
4784 lazy_refcounts
= qemu_opt_get_bool(opts
, BLOCK_OPT_LAZY_REFCOUNTS
,
4786 } else if (!strcmp(desc
->name
, BLOCK_OPT_REFCOUNT_BITS
)) {
4787 refcount_bits
= qemu_opt_get_number(opts
, BLOCK_OPT_REFCOUNT_BITS
,
4790 if (refcount_bits
<= 0 || refcount_bits
> 64 ||
4791 !is_power_of_2(refcount_bits
))
4793 error_setg(errp
, "Refcount width must be a power of two and "
4794 "may not exceed 64 bits");
4797 } else if (!strcmp(desc
->name
, BLOCK_OPT_DATA_FILE
)) {
4798 data_file
= qemu_opt_get(opts
, BLOCK_OPT_DATA_FILE
);
4799 if (data_file
&& !has_data_file(bs
)) {
4800 error_setg(errp
, "data-file can only be set for images that "
4801 "use an external data file");
4804 } else if (!strcmp(desc
->name
, BLOCK_OPT_DATA_FILE_RAW
)) {
4805 data_file_raw
= qemu_opt_get_bool(opts
, BLOCK_OPT_DATA_FILE_RAW
,
4807 if (data_file_raw
&& !data_file_is_raw(bs
)) {
4808 error_setg(errp
, "data-file-raw cannot be set on existing "
4813 /* if this point is reached, this probably means a new option was
4814 * added without having it covered here */
4821 helper_cb_info
= (Qcow2AmendHelperCBInfo
){
4822 .original_status_cb
= status_cb
,
4823 .original_cb_opaque
= cb_opaque
,
4824 .total_operations
= (new_version
< old_version
)
4825 + (s
->refcount_bits
!= refcount_bits
)
4828 /* Upgrade first (some features may require compat=1.1) */
4829 if (new_version
> old_version
) {
4830 s
->qcow_version
= new_version
;
4831 ret
= qcow2_update_header(bs
);
4833 s
->qcow_version
= old_version
;
4834 error_setg_errno(errp
, -ret
, "Failed to update the image header");
4839 if (s
->refcount_bits
!= refcount_bits
) {
4840 int refcount_order
= ctz32(refcount_bits
);
4842 if (new_version
< 3 && refcount_bits
!= 16) {
4843 error_setg(errp
, "Refcount widths other than 16 bits require "
4844 "compatibility level 1.1 or above (use compat=1.1 or "
4849 helper_cb_info
.current_operation
= QCOW2_CHANGING_REFCOUNT_ORDER
;
4850 ret
= qcow2_change_refcount_order(bs
, refcount_order
,
4851 &qcow2_amend_helper_cb
,
4852 &helper_cb_info
, errp
);
4858 /* data-file-raw blocks backing files, so clear it first if requested */
4859 if (data_file_raw
) {
4860 s
->autoclear_features
|= QCOW2_AUTOCLEAR_DATA_FILE_RAW
;
4862 s
->autoclear_features
&= ~QCOW2_AUTOCLEAR_DATA_FILE_RAW
;
4866 g_free(s
->image_data_file
);
4867 s
->image_data_file
= *data_file
? g_strdup(data_file
) : NULL
;
4870 ret
= qcow2_update_header(bs
);
4872 error_setg_errno(errp
, -ret
, "Failed to update the image header");
4876 if (backing_file
|| backing_format
) {
4877 ret
= qcow2_change_backing_file(bs
,
4878 backing_file
?: s
->image_backing_file
,
4879 backing_format
?: s
->image_backing_format
);
4881 error_setg_errno(errp
, -ret
, "Failed to change the backing file");
4886 if (s
->use_lazy_refcounts
!= lazy_refcounts
) {
4887 if (lazy_refcounts
) {
4888 if (new_version
< 3) {
4889 error_setg(errp
, "Lazy refcounts only supported with "
4890 "compatibility level 1.1 and above (use compat=1.1 "
4894 s
->compatible_features
|= QCOW2_COMPAT_LAZY_REFCOUNTS
;
4895 ret
= qcow2_update_header(bs
);
4897 s
->compatible_features
&= ~QCOW2_COMPAT_LAZY_REFCOUNTS
;
4898 error_setg_errno(errp
, -ret
, "Failed to update the image header");
4901 s
->use_lazy_refcounts
= true;
4903 /* make image clean first */
4904 ret
= qcow2_mark_clean(bs
);
4906 error_setg_errno(errp
, -ret
, "Failed to make the image clean");
4909 /* now disallow lazy refcounts */
4910 s
->compatible_features
&= ~QCOW2_COMPAT_LAZY_REFCOUNTS
;
4911 ret
= qcow2_update_header(bs
);
4913 s
->compatible_features
|= QCOW2_COMPAT_LAZY_REFCOUNTS
;
4914 error_setg_errno(errp
, -ret
, "Failed to update the image header");
4917 s
->use_lazy_refcounts
= false;
4922 BlockBackend
*blk
= blk_new(BLK_PERM_RESIZE
, BLK_PERM_ALL
);
4923 ret
= blk_insert_bs(blk
, bs
, errp
);
4929 ret
= blk_truncate(blk
, new_size
, PREALLOC_MODE_OFF
, errp
);
4936 /* Downgrade last (so unsupported features can be removed before) */
4937 if (new_version
< old_version
) {
4938 helper_cb_info
.current_operation
= QCOW2_DOWNGRADING
;
4939 ret
= qcow2_downgrade(bs
, new_version
, &qcow2_amend_helper_cb
,
4940 &helper_cb_info
, errp
);
4950 * If offset or size are negative, respectively, they will not be included in
4951 * the BLOCK_IMAGE_CORRUPTED event emitted.
4952 * fatal will be ignored for read-only BDS; corruptions found there will always
4953 * be considered non-fatal.
4955 void qcow2_signal_corruption(BlockDriverState
*bs
, bool fatal
, int64_t offset
,
4956 int64_t size
, const char *message_format
, ...)
4958 BDRVQcow2State
*s
= bs
->opaque
;
4959 const char *node_name
;
4963 fatal
= fatal
&& bdrv_is_writable(bs
);
4965 if (s
->signaled_corruption
&&
4966 (!fatal
|| (s
->incompatible_features
& QCOW2_INCOMPAT_CORRUPT
)))
4971 va_start(ap
, message_format
);
4972 message
= g_strdup_vprintf(message_format
, ap
);
4976 fprintf(stderr
, "qcow2: Marking image as corrupt: %s; further "
4977 "corruption events will be suppressed\n", message
);
4979 fprintf(stderr
, "qcow2: Image is corrupt: %s; further non-fatal "
4980 "corruption events will be suppressed\n", message
);
4983 node_name
= bdrv_get_node_name(bs
);
4984 qapi_event_send_block_image_corrupted(bdrv_get_device_name(bs
),
4985 *node_name
!= '\0', node_name
,
4986 message
, offset
>= 0, offset
,
4992 qcow2_mark_corrupt(bs
);
4993 bs
->drv
= NULL
; /* make BDS unusable */
4996 s
->signaled_corruption
= true;
4999 static QemuOptsList qcow2_create_opts
= {
5000 .name
= "qcow2-create-opts",
5001 .head
= QTAILQ_HEAD_INITIALIZER(qcow2_create_opts
.head
),
5004 .name
= BLOCK_OPT_SIZE
,
5005 .type
= QEMU_OPT_SIZE
,
5006 .help
= "Virtual disk size"
5009 .name
= BLOCK_OPT_COMPAT_LEVEL
,
5010 .type
= QEMU_OPT_STRING
,
5011 .help
= "Compatibility level (0.10 or 1.1)"
5014 .name
= BLOCK_OPT_BACKING_FILE
,
5015 .type
= QEMU_OPT_STRING
,
5016 .help
= "File name of a base image"
5019 .name
= BLOCK_OPT_BACKING_FMT
,
5020 .type
= QEMU_OPT_STRING
,
5021 .help
= "Image format of the base image"
5024 .name
= BLOCK_OPT_DATA_FILE
,
5025 .type
= QEMU_OPT_STRING
,
5026 .help
= "File name of an external data file"
5029 .name
= BLOCK_OPT_DATA_FILE_RAW
,
5030 .type
= QEMU_OPT_BOOL
,
5031 .help
= "The external data file must stay valid as a raw image"
5034 .name
= BLOCK_OPT_ENCRYPT
,
5035 .type
= QEMU_OPT_BOOL
,
5036 .help
= "Encrypt the image with format 'aes'. (Deprecated "
5037 "in favor of " BLOCK_OPT_ENCRYPT_FORMAT
"=aes)",
5040 .name
= BLOCK_OPT_ENCRYPT_FORMAT
,
5041 .type
= QEMU_OPT_STRING
,
5042 .help
= "Encrypt the image, format choices: 'aes', 'luks'",
5044 BLOCK_CRYPTO_OPT_DEF_KEY_SECRET("encrypt.",
5045 "ID of secret providing qcow AES key or LUKS passphrase"),
5046 BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_ALG("encrypt."),
5047 BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_MODE("encrypt."),
5048 BLOCK_CRYPTO_OPT_DEF_LUKS_IVGEN_ALG("encrypt."),
5049 BLOCK_CRYPTO_OPT_DEF_LUKS_IVGEN_HASH_ALG("encrypt."),
5050 BLOCK_CRYPTO_OPT_DEF_LUKS_HASH_ALG("encrypt."),
5051 BLOCK_CRYPTO_OPT_DEF_LUKS_ITER_TIME("encrypt."),
5053 .name
= BLOCK_OPT_CLUSTER_SIZE
,
5054 .type
= QEMU_OPT_SIZE
,
5055 .help
= "qcow2 cluster size",
5056 .def_value_str
= stringify(DEFAULT_CLUSTER_SIZE
)
5059 .name
= BLOCK_OPT_PREALLOC
,
5060 .type
= QEMU_OPT_STRING
,
5061 .help
= "Preallocation mode (allowed values: off, metadata, "
5065 .name
= BLOCK_OPT_LAZY_REFCOUNTS
,
5066 .type
= QEMU_OPT_BOOL
,
5067 .help
= "Postpone refcount updates",
5068 .def_value_str
= "off"
5071 .name
= BLOCK_OPT_REFCOUNT_BITS
,
5072 .type
= QEMU_OPT_NUMBER
,
5073 .help
= "Width of a reference count entry in bits",
5074 .def_value_str
= "16"
5076 { /* end of list */ }
5080 static const char *const qcow2_strong_runtime_opts
[] = {
5081 "encrypt." BLOCK_CRYPTO_OPT_QCOW_KEY_SECRET
,
5086 BlockDriver bdrv_qcow2
= {
5087 .format_name
= "qcow2",
5088 .instance_size
= sizeof(BDRVQcow2State
),
5089 .bdrv_probe
= qcow2_probe
,
5090 .bdrv_open
= qcow2_open
,
5091 .bdrv_close
= qcow2_close
,
5092 .bdrv_reopen_prepare
= qcow2_reopen_prepare
,
5093 .bdrv_reopen_commit
= qcow2_reopen_commit
,
5094 .bdrv_reopen_abort
= qcow2_reopen_abort
,
5095 .bdrv_join_options
= qcow2_join_options
,
5096 .bdrv_child_perm
= bdrv_format_default_perms
,
5097 .bdrv_co_create_opts
= qcow2_co_create_opts
,
5098 .bdrv_co_create
= qcow2_co_create
,
5099 .bdrv_has_zero_init
= bdrv_has_zero_init_1
,
5100 .bdrv_co_block_status
= qcow2_co_block_status
,
5102 .bdrv_co_preadv
= qcow2_co_preadv
,
5103 .bdrv_co_pwritev
= qcow2_co_pwritev
,
5104 .bdrv_co_flush_to_os
= qcow2_co_flush_to_os
,
5106 .bdrv_co_pwrite_zeroes
= qcow2_co_pwrite_zeroes
,
5107 .bdrv_co_pdiscard
= qcow2_co_pdiscard
,
5108 .bdrv_co_copy_range_from
= qcow2_co_copy_range_from
,
5109 .bdrv_co_copy_range_to
= qcow2_co_copy_range_to
,
5110 .bdrv_co_truncate
= qcow2_co_truncate
,
5111 .bdrv_co_pwritev_compressed
= qcow2_co_pwritev_compressed
,
5112 .bdrv_make_empty
= qcow2_make_empty
,
5114 .bdrv_snapshot_create
= qcow2_snapshot_create
,
5115 .bdrv_snapshot_goto
= qcow2_snapshot_goto
,
5116 .bdrv_snapshot_delete
= qcow2_snapshot_delete
,
5117 .bdrv_snapshot_list
= qcow2_snapshot_list
,
5118 .bdrv_snapshot_load_tmp
= qcow2_snapshot_load_tmp
,
5119 .bdrv_measure
= qcow2_measure
,
5120 .bdrv_get_info
= qcow2_get_info
,
5121 .bdrv_get_specific_info
= qcow2_get_specific_info
,
5123 .bdrv_save_vmstate
= qcow2_save_vmstate
,
5124 .bdrv_load_vmstate
= qcow2_load_vmstate
,
5126 .supports_backing
= true,
5127 .bdrv_change_backing_file
= qcow2_change_backing_file
,
5129 .bdrv_refresh_limits
= qcow2_refresh_limits
,
5130 .bdrv_co_invalidate_cache
= qcow2_co_invalidate_cache
,
5131 .bdrv_inactivate
= qcow2_inactivate
,
5133 .create_opts
= &qcow2_create_opts
,
5134 .strong_runtime_opts
= qcow2_strong_runtime_opts
,
5135 .mutable_opts
= mutable_opts
,
5136 .bdrv_co_check
= qcow2_co_check
,
5137 .bdrv_amend_options
= qcow2_amend_options
,
5139 .bdrv_detach_aio_context
= qcow2_detach_aio_context
,
5140 .bdrv_attach_aio_context
= qcow2_attach_aio_context
,
5142 .bdrv_reopen_bitmaps_rw
= qcow2_reopen_bitmaps_rw
,
5143 .bdrv_can_store_new_dirty_bitmap
= qcow2_can_store_new_dirty_bitmap
,
5144 .bdrv_remove_persistent_dirty_bitmap
= qcow2_remove_persistent_dirty_bitmap
,
5147 static void bdrv_qcow2_init(void)
5149 bdrv_register(&bdrv_qcow2
);
5152 block_init(bdrv_qcow2_init
);