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"
26 #include "block/block_int.h"
27 #include "sysemu/block-backend.h"
28 #include "qemu/module.h"
30 #include "block/qcow2.h"
31 #include "qemu/error-report.h"
32 #include "qapi/error.h"
33 #include "qapi/qmp/qdict.h"
34 #include "qapi/qmp/qstring.h"
35 #include "qapi-event.h"
37 #include "qemu/option_int.h"
38 #include "qemu/cutils.h"
39 #include "qemu/bswap.h"
40 #include "qapi/opts-visitor.h"
41 #include "qapi-visit.h"
42 #include "block/crypto.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
72 static int qcow2_probe(const uint8_t *buf
, int buf_size
, const char *filename
)
74 const QCowHeader
*cow_header
= (const void *)buf
;
76 if (buf_size
>= sizeof(QCowHeader
) &&
77 be32_to_cpu(cow_header
->magic
) == QCOW_MAGIC
&&
78 be32_to_cpu(cow_header
->version
) >= 2)
85 static ssize_t
qcow2_crypto_hdr_read_func(QCryptoBlock
*block
, size_t offset
,
86 uint8_t *buf
, size_t buflen
,
87 void *opaque
, Error
**errp
)
89 BlockDriverState
*bs
= opaque
;
90 BDRVQcow2State
*s
= bs
->opaque
;
93 if ((offset
+ buflen
) > s
->crypto_header
.length
) {
94 error_setg(errp
, "Request for data outside of extension header");
98 ret
= bdrv_pread(bs
->file
,
99 s
->crypto_header
.offset
+ offset
, buf
, buflen
);
101 error_setg_errno(errp
, -ret
, "Could not read encryption header");
108 static ssize_t
qcow2_crypto_hdr_init_func(QCryptoBlock
*block
, size_t headerlen
,
109 void *opaque
, Error
**errp
)
111 BlockDriverState
*bs
= opaque
;
112 BDRVQcow2State
*s
= bs
->opaque
;
116 ret
= qcow2_alloc_clusters(bs
, headerlen
);
118 error_setg_errno(errp
, -ret
,
119 "Cannot allocate cluster for LUKS header size %zu",
124 s
->crypto_header
.length
= headerlen
;
125 s
->crypto_header
.offset
= ret
;
127 /* Zero fill remaining space in cluster so it has predictable
128 * content in case of future spec changes */
129 clusterlen
= size_to_clusters(s
, headerlen
) * s
->cluster_size
;
130 assert(qcow2_pre_write_overlap_check(bs
, 0, ret
, clusterlen
) == 0);
131 ret
= bdrv_pwrite_zeroes(bs
->file
,
133 clusterlen
- headerlen
, 0);
135 error_setg_errno(errp
, -ret
, "Could not zero fill encryption header");
143 static ssize_t
qcow2_crypto_hdr_write_func(QCryptoBlock
*block
, size_t offset
,
144 const uint8_t *buf
, size_t buflen
,
145 void *opaque
, Error
**errp
)
147 BlockDriverState
*bs
= opaque
;
148 BDRVQcow2State
*s
= bs
->opaque
;
151 if ((offset
+ buflen
) > s
->crypto_header
.length
) {
152 error_setg(errp
, "Request for data outside of extension header");
156 ret
= bdrv_pwrite(bs
->file
,
157 s
->crypto_header
.offset
+ offset
, buf
, buflen
);
159 error_setg_errno(errp
, -ret
, "Could not read encryption header");
167 * read qcow2 extension and fill bs
168 * start reading from start_offset
169 * finish reading upon magic of value 0 or when end_offset reached
170 * unknown magic is skipped (future extension this version knows nothing about)
171 * return 0 upon success, non-0 otherwise
173 static int qcow2_read_extensions(BlockDriverState
*bs
, uint64_t start_offset
,
174 uint64_t end_offset
, void **p_feature_table
,
175 int flags
, bool *need_update_header
,
178 BDRVQcow2State
*s
= bs
->opaque
;
182 Qcow2BitmapHeaderExt bitmaps_ext
;
184 if (need_update_header
!= NULL
) {
185 *need_update_header
= false;
189 printf("qcow2_read_extensions: start=%ld end=%ld\n", start_offset
, end_offset
);
191 offset
= start_offset
;
192 while (offset
< end_offset
) {
196 if (offset
> s
->cluster_size
)
197 printf("qcow2_read_extension: suspicious offset %lu\n", offset
);
199 printf("attempting to read extended header in offset %lu\n", offset
);
202 ret
= bdrv_pread(bs
->file
, offset
, &ext
, sizeof(ext
));
204 error_setg_errno(errp
, -ret
, "qcow2_read_extension: ERROR: "
205 "pread fail from offset %" PRIu64
, offset
);
208 be32_to_cpus(&ext
.magic
);
209 be32_to_cpus(&ext
.len
);
210 offset
+= sizeof(ext
);
212 printf("ext.magic = 0x%x\n", ext
.magic
);
214 if (offset
> end_offset
|| ext
.len
> end_offset
- offset
) {
215 error_setg(errp
, "Header extension too large");
220 case QCOW2_EXT_MAGIC_END
:
223 case QCOW2_EXT_MAGIC_BACKING_FORMAT
:
224 if (ext
.len
>= sizeof(bs
->backing_format
)) {
225 error_setg(errp
, "ERROR: ext_backing_format: len=%" PRIu32
226 " too large (>=%zu)", ext
.len
,
227 sizeof(bs
->backing_format
));
230 ret
= bdrv_pread(bs
->file
, offset
, bs
->backing_format
, ext
.len
);
232 error_setg_errno(errp
, -ret
, "ERROR: ext_backing_format: "
233 "Could not read format name");
236 bs
->backing_format
[ext
.len
] = '\0';
237 s
->image_backing_format
= g_strdup(bs
->backing_format
);
239 printf("Qcow2: Got format extension %s\n", bs
->backing_format
);
243 case QCOW2_EXT_MAGIC_FEATURE_TABLE
:
244 if (p_feature_table
!= NULL
) {
245 void* feature_table
= g_malloc0(ext
.len
+ 2 * sizeof(Qcow2Feature
));
246 ret
= bdrv_pread(bs
->file
, offset
, feature_table
, ext
.len
);
248 error_setg_errno(errp
, -ret
, "ERROR: ext_feature_table: "
249 "Could not read table");
253 *p_feature_table
= feature_table
;
257 case QCOW2_EXT_MAGIC_CRYPTO_HEADER
: {
258 unsigned int cflags
= 0;
259 if (s
->crypt_method_header
!= QCOW_CRYPT_LUKS
) {
260 error_setg(errp
, "CRYPTO header extension only "
261 "expected with LUKS encryption method");
264 if (ext
.len
!= sizeof(Qcow2CryptoHeaderExtension
)) {
265 error_setg(errp
, "CRYPTO header extension size %u, "
266 "but expected size %zu", ext
.len
,
267 sizeof(Qcow2CryptoHeaderExtension
));
271 ret
= bdrv_pread(bs
->file
, offset
, &s
->crypto_header
, ext
.len
);
273 error_setg_errno(errp
, -ret
,
274 "Unable to read CRYPTO header extension");
277 be64_to_cpus(&s
->crypto_header
.offset
);
278 be64_to_cpus(&s
->crypto_header
.length
);
280 if ((s
->crypto_header
.offset
% s
->cluster_size
) != 0) {
281 error_setg(errp
, "Encryption header offset '%" PRIu64
"' is "
282 "not a multiple of cluster size '%u'",
283 s
->crypto_header
.offset
, s
->cluster_size
);
287 if (flags
& BDRV_O_NO_IO
) {
288 cflags
|= QCRYPTO_BLOCK_OPEN_NO_IO
;
290 s
->crypto
= qcrypto_block_open(s
->crypto_opts
, "encrypt.",
291 qcow2_crypto_hdr_read_func
,
298 case QCOW2_EXT_MAGIC_BITMAPS
:
299 if (ext
.len
!= sizeof(bitmaps_ext
)) {
300 error_setg_errno(errp
, -ret
, "bitmaps_ext: "
301 "Invalid extension length");
305 if (!(s
->autoclear_features
& QCOW2_AUTOCLEAR_BITMAPS
)) {
306 if (s
->qcow_version
< 3) {
307 /* Let's be a bit more specific */
308 warn_report("This qcow2 v2 image contains bitmaps, but "
309 "they may have been modified by a program "
310 "without persistent bitmap support; so now "
311 "they must all be considered inconsistent");
313 warn_report("a program lacking bitmap support "
314 "modified this file, so all bitmaps are now "
315 "considered inconsistent");
317 error_printf("Some clusters may be leaked, "
318 "run 'qemu-img check -r' on the image "
320 if (need_update_header
!= NULL
) {
321 /* Updating is needed to drop invalid bitmap extension. */
322 *need_update_header
= true;
327 ret
= bdrv_pread(bs
->file
, offset
, &bitmaps_ext
, ext
.len
);
329 error_setg_errno(errp
, -ret
, "bitmaps_ext: "
330 "Could not read ext header");
334 if (bitmaps_ext
.reserved32
!= 0) {
335 error_setg_errno(errp
, -ret
, "bitmaps_ext: "
336 "Reserved field is not zero");
340 be32_to_cpus(&bitmaps_ext
.nb_bitmaps
);
341 be64_to_cpus(&bitmaps_ext
.bitmap_directory_size
);
342 be64_to_cpus(&bitmaps_ext
.bitmap_directory_offset
);
344 if (bitmaps_ext
.nb_bitmaps
> QCOW2_MAX_BITMAPS
) {
346 "bitmaps_ext: Image has %" PRIu32
" bitmaps, "
347 "exceeding the QEMU supported maximum of %d",
348 bitmaps_ext
.nb_bitmaps
, QCOW2_MAX_BITMAPS
);
352 if (bitmaps_ext
.nb_bitmaps
== 0) {
353 error_setg(errp
, "found bitmaps extension with zero bitmaps");
357 if (bitmaps_ext
.bitmap_directory_offset
& (s
->cluster_size
- 1)) {
358 error_setg(errp
, "bitmaps_ext: "
359 "invalid bitmap directory offset");
363 if (bitmaps_ext
.bitmap_directory_size
>
364 QCOW2_MAX_BITMAP_DIRECTORY_SIZE
) {
365 error_setg(errp
, "bitmaps_ext: "
366 "bitmap directory size (%" PRIu64
") exceeds "
367 "the maximum supported size (%d)",
368 bitmaps_ext
.bitmap_directory_size
,
369 QCOW2_MAX_BITMAP_DIRECTORY_SIZE
);
373 s
->nb_bitmaps
= bitmaps_ext
.nb_bitmaps
;
374 s
->bitmap_directory_offset
=
375 bitmaps_ext
.bitmap_directory_offset
;
376 s
->bitmap_directory_size
=
377 bitmaps_ext
.bitmap_directory_size
;
380 printf("Qcow2: Got bitmaps extension: "
381 "offset=%" PRIu64
" nb_bitmaps=%" PRIu32
"\n",
382 s
->bitmap_directory_offset
, s
->nb_bitmaps
);
387 /* unknown magic - save it in case we need to rewrite the header */
388 /* If you add a new feature, make sure to also update the fast
389 * path of qcow2_make_empty() to deal with it. */
391 Qcow2UnknownHeaderExtension
*uext
;
393 uext
= g_malloc0(sizeof(*uext
) + ext
.len
);
394 uext
->magic
= ext
.magic
;
396 QLIST_INSERT_HEAD(&s
->unknown_header_ext
, uext
, next
);
398 ret
= bdrv_pread(bs
->file
, offset
, uext
->data
, uext
->len
);
400 error_setg_errno(errp
, -ret
, "ERROR: unknown extension: "
401 "Could not read data");
408 offset
+= ((ext
.len
+ 7) & ~7);
414 static void cleanup_unknown_header_ext(BlockDriverState
*bs
)
416 BDRVQcow2State
*s
= bs
->opaque
;
417 Qcow2UnknownHeaderExtension
*uext
, *next
;
419 QLIST_FOREACH_SAFE(uext
, &s
->unknown_header_ext
, next
, next
) {
420 QLIST_REMOVE(uext
, next
);
425 static void report_unsupported_feature(Error
**errp
, Qcow2Feature
*table
,
428 char *features
= g_strdup("");
431 while (table
&& table
->name
[0] != '\0') {
432 if (table
->type
== QCOW2_FEAT_TYPE_INCOMPATIBLE
) {
433 if (mask
& (1ULL << table
->bit
)) {
435 features
= g_strdup_printf("%s%s%.46s", old
, *old
? ", " : "",
438 mask
&= ~(1ULL << table
->bit
);
446 features
= g_strdup_printf("%s%sUnknown incompatible feature: %" PRIx64
,
447 old
, *old
? ", " : "", mask
);
451 error_setg(errp
, "Unsupported qcow2 feature(s): %s", features
);
456 * Sets the dirty bit and flushes afterwards if necessary.
458 * The incompatible_features bit is only set if the image file header was
459 * updated successfully. Therefore it is not required to check the return
460 * value of this function.
462 int qcow2_mark_dirty(BlockDriverState
*bs
)
464 BDRVQcow2State
*s
= bs
->opaque
;
468 assert(s
->qcow_version
>= 3);
470 if (s
->incompatible_features
& QCOW2_INCOMPAT_DIRTY
) {
471 return 0; /* already dirty */
474 val
= cpu_to_be64(s
->incompatible_features
| QCOW2_INCOMPAT_DIRTY
);
475 ret
= bdrv_pwrite(bs
->file
, offsetof(QCowHeader
, incompatible_features
),
480 ret
= bdrv_flush(bs
->file
->bs
);
485 /* Only treat image as dirty if the header was updated successfully */
486 s
->incompatible_features
|= QCOW2_INCOMPAT_DIRTY
;
491 * Clears the dirty bit and flushes before if necessary. Only call this
492 * function when there are no pending requests, it does not guard against
493 * concurrent requests dirtying the image.
495 static int qcow2_mark_clean(BlockDriverState
*bs
)
497 BDRVQcow2State
*s
= bs
->opaque
;
499 if (s
->incompatible_features
& QCOW2_INCOMPAT_DIRTY
) {
502 s
->incompatible_features
&= ~QCOW2_INCOMPAT_DIRTY
;
504 ret
= bdrv_flush(bs
);
509 return qcow2_update_header(bs
);
515 * Marks the image as corrupt.
517 int qcow2_mark_corrupt(BlockDriverState
*bs
)
519 BDRVQcow2State
*s
= bs
->opaque
;
521 s
->incompatible_features
|= QCOW2_INCOMPAT_CORRUPT
;
522 return qcow2_update_header(bs
);
526 * Marks the image as consistent, i.e., unsets the corrupt bit, and flushes
527 * before if necessary.
529 int qcow2_mark_consistent(BlockDriverState
*bs
)
531 BDRVQcow2State
*s
= bs
->opaque
;
533 if (s
->incompatible_features
& QCOW2_INCOMPAT_CORRUPT
) {
534 int ret
= bdrv_flush(bs
);
539 s
->incompatible_features
&= ~QCOW2_INCOMPAT_CORRUPT
;
540 return qcow2_update_header(bs
);
545 static int qcow2_check(BlockDriverState
*bs
, BdrvCheckResult
*result
,
548 int ret
= qcow2_check_refcounts(bs
, result
, fix
);
553 if (fix
&& result
->check_errors
== 0 && result
->corruptions
== 0) {
554 ret
= qcow2_mark_clean(bs
);
558 return qcow2_mark_consistent(bs
);
563 static int validate_table_offset(BlockDriverState
*bs
, uint64_t offset
,
564 uint64_t entries
, size_t entry_len
)
566 BDRVQcow2State
*s
= bs
->opaque
;
569 /* Use signed INT64_MAX as the maximum even for uint64_t header fields,
570 * because values will be passed to qemu functions taking int64_t. */
571 if (entries
> INT64_MAX
/ entry_len
) {
575 size
= entries
* entry_len
;
577 if (INT64_MAX
- size
< offset
) {
581 /* Tables must be cluster aligned */
582 if (offset_into_cluster(s
, offset
) != 0) {
589 static QemuOptsList qcow2_runtime_opts
= {
591 .head
= QTAILQ_HEAD_INITIALIZER(qcow2_runtime_opts
.head
),
594 .name
= QCOW2_OPT_LAZY_REFCOUNTS
,
595 .type
= QEMU_OPT_BOOL
,
596 .help
= "Postpone refcount updates",
599 .name
= QCOW2_OPT_DISCARD_REQUEST
,
600 .type
= QEMU_OPT_BOOL
,
601 .help
= "Pass guest discard requests to the layer below",
604 .name
= QCOW2_OPT_DISCARD_SNAPSHOT
,
605 .type
= QEMU_OPT_BOOL
,
606 .help
= "Generate discard requests when snapshot related space "
610 .name
= QCOW2_OPT_DISCARD_OTHER
,
611 .type
= QEMU_OPT_BOOL
,
612 .help
= "Generate discard requests when other clusters are freed",
615 .name
= QCOW2_OPT_OVERLAP
,
616 .type
= QEMU_OPT_STRING
,
617 .help
= "Selects which overlap checks to perform from a range of "
618 "templates (none, constant, cached, all)",
621 .name
= QCOW2_OPT_OVERLAP_TEMPLATE
,
622 .type
= QEMU_OPT_STRING
,
623 .help
= "Selects which overlap checks to perform from a range of "
624 "templates (none, constant, cached, all)",
627 .name
= QCOW2_OPT_OVERLAP_MAIN_HEADER
,
628 .type
= QEMU_OPT_BOOL
,
629 .help
= "Check for unintended writes into the main qcow2 header",
632 .name
= QCOW2_OPT_OVERLAP_ACTIVE_L1
,
633 .type
= QEMU_OPT_BOOL
,
634 .help
= "Check for unintended writes into the active L1 table",
637 .name
= QCOW2_OPT_OVERLAP_ACTIVE_L2
,
638 .type
= QEMU_OPT_BOOL
,
639 .help
= "Check for unintended writes into an active L2 table",
642 .name
= QCOW2_OPT_OVERLAP_REFCOUNT_TABLE
,
643 .type
= QEMU_OPT_BOOL
,
644 .help
= "Check for unintended writes into the refcount table",
647 .name
= QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK
,
648 .type
= QEMU_OPT_BOOL
,
649 .help
= "Check for unintended writes into a refcount block",
652 .name
= QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE
,
653 .type
= QEMU_OPT_BOOL
,
654 .help
= "Check for unintended writes into the snapshot table",
657 .name
= QCOW2_OPT_OVERLAP_INACTIVE_L1
,
658 .type
= QEMU_OPT_BOOL
,
659 .help
= "Check for unintended writes into an inactive L1 table",
662 .name
= QCOW2_OPT_OVERLAP_INACTIVE_L2
,
663 .type
= QEMU_OPT_BOOL
,
664 .help
= "Check for unintended writes into an inactive L2 table",
667 .name
= QCOW2_OPT_CACHE_SIZE
,
668 .type
= QEMU_OPT_SIZE
,
669 .help
= "Maximum combined metadata (L2 tables and refcount blocks) "
673 .name
= QCOW2_OPT_L2_CACHE_SIZE
,
674 .type
= QEMU_OPT_SIZE
,
675 .help
= "Maximum L2 table cache size",
678 .name
= QCOW2_OPT_L2_CACHE_ENTRY_SIZE
,
679 .type
= QEMU_OPT_SIZE
,
680 .help
= "Size of each entry in the L2 cache",
683 .name
= QCOW2_OPT_REFCOUNT_CACHE_SIZE
,
684 .type
= QEMU_OPT_SIZE
,
685 .help
= "Maximum refcount block cache size",
688 .name
= QCOW2_OPT_CACHE_CLEAN_INTERVAL
,
689 .type
= QEMU_OPT_NUMBER
,
690 .help
= "Clean unused cache entries after this time (in seconds)",
692 BLOCK_CRYPTO_OPT_DEF_KEY_SECRET("encrypt.",
693 "ID of secret providing qcow2 AES key or LUKS passphrase"),
694 { /* end of list */ }
698 static const char *overlap_bool_option_names
[QCOW2_OL_MAX_BITNR
] = {
699 [QCOW2_OL_MAIN_HEADER_BITNR
] = QCOW2_OPT_OVERLAP_MAIN_HEADER
,
700 [QCOW2_OL_ACTIVE_L1_BITNR
] = QCOW2_OPT_OVERLAP_ACTIVE_L1
,
701 [QCOW2_OL_ACTIVE_L2_BITNR
] = QCOW2_OPT_OVERLAP_ACTIVE_L2
,
702 [QCOW2_OL_REFCOUNT_TABLE_BITNR
] = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE
,
703 [QCOW2_OL_REFCOUNT_BLOCK_BITNR
] = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK
,
704 [QCOW2_OL_SNAPSHOT_TABLE_BITNR
] = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE
,
705 [QCOW2_OL_INACTIVE_L1_BITNR
] = QCOW2_OPT_OVERLAP_INACTIVE_L1
,
706 [QCOW2_OL_INACTIVE_L2_BITNR
] = QCOW2_OPT_OVERLAP_INACTIVE_L2
,
709 static void cache_clean_timer_cb(void *opaque
)
711 BlockDriverState
*bs
= opaque
;
712 BDRVQcow2State
*s
= bs
->opaque
;
713 qcow2_cache_clean_unused(s
->l2_table_cache
);
714 qcow2_cache_clean_unused(s
->refcount_block_cache
);
715 timer_mod(s
->cache_clean_timer
, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL
) +
716 (int64_t) s
->cache_clean_interval
* 1000);
719 static void cache_clean_timer_init(BlockDriverState
*bs
, AioContext
*context
)
721 BDRVQcow2State
*s
= bs
->opaque
;
722 if (s
->cache_clean_interval
> 0) {
723 s
->cache_clean_timer
= aio_timer_new(context
, QEMU_CLOCK_VIRTUAL
,
724 SCALE_MS
, cache_clean_timer_cb
,
726 timer_mod(s
->cache_clean_timer
, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL
) +
727 (int64_t) s
->cache_clean_interval
* 1000);
731 static void cache_clean_timer_del(BlockDriverState
*bs
)
733 BDRVQcow2State
*s
= bs
->opaque
;
734 if (s
->cache_clean_timer
) {
735 timer_del(s
->cache_clean_timer
);
736 timer_free(s
->cache_clean_timer
);
737 s
->cache_clean_timer
= NULL
;
741 static void qcow2_detach_aio_context(BlockDriverState
*bs
)
743 cache_clean_timer_del(bs
);
746 static void qcow2_attach_aio_context(BlockDriverState
*bs
,
747 AioContext
*new_context
)
749 cache_clean_timer_init(bs
, new_context
);
752 static void read_cache_sizes(BlockDriverState
*bs
, QemuOpts
*opts
,
753 uint64_t *l2_cache_size
,
754 uint64_t *l2_cache_entry_size
,
755 uint64_t *refcount_cache_size
, Error
**errp
)
757 BDRVQcow2State
*s
= bs
->opaque
;
758 uint64_t combined_cache_size
;
759 bool l2_cache_size_set
, refcount_cache_size_set
, combined_cache_size_set
;
761 combined_cache_size_set
= qemu_opt_get(opts
, QCOW2_OPT_CACHE_SIZE
);
762 l2_cache_size_set
= qemu_opt_get(opts
, QCOW2_OPT_L2_CACHE_SIZE
);
763 refcount_cache_size_set
= qemu_opt_get(opts
, QCOW2_OPT_REFCOUNT_CACHE_SIZE
);
765 combined_cache_size
= qemu_opt_get_size(opts
, QCOW2_OPT_CACHE_SIZE
, 0);
766 *l2_cache_size
= qemu_opt_get_size(opts
, QCOW2_OPT_L2_CACHE_SIZE
, 0);
767 *refcount_cache_size
= qemu_opt_get_size(opts
,
768 QCOW2_OPT_REFCOUNT_CACHE_SIZE
, 0);
770 *l2_cache_entry_size
= qemu_opt_get_size(
771 opts
, QCOW2_OPT_L2_CACHE_ENTRY_SIZE
, s
->cluster_size
);
773 if (combined_cache_size_set
) {
774 if (l2_cache_size_set
&& refcount_cache_size_set
) {
775 error_setg(errp
, QCOW2_OPT_CACHE_SIZE
", " QCOW2_OPT_L2_CACHE_SIZE
776 " and " QCOW2_OPT_REFCOUNT_CACHE_SIZE
" may not be set "
779 } else if (*l2_cache_size
> combined_cache_size
) {
780 error_setg(errp
, QCOW2_OPT_L2_CACHE_SIZE
" may not exceed "
781 QCOW2_OPT_CACHE_SIZE
);
783 } else if (*refcount_cache_size
> combined_cache_size
) {
784 error_setg(errp
, QCOW2_OPT_REFCOUNT_CACHE_SIZE
" may not exceed "
785 QCOW2_OPT_CACHE_SIZE
);
789 if (l2_cache_size_set
) {
790 *refcount_cache_size
= combined_cache_size
- *l2_cache_size
;
791 } else if (refcount_cache_size_set
) {
792 *l2_cache_size
= combined_cache_size
- *refcount_cache_size
;
794 *refcount_cache_size
= combined_cache_size
795 / (DEFAULT_L2_REFCOUNT_SIZE_RATIO
+ 1);
796 *l2_cache_size
= combined_cache_size
- *refcount_cache_size
;
799 if (!l2_cache_size_set
&& !refcount_cache_size_set
) {
800 *l2_cache_size
= MAX(DEFAULT_L2_CACHE_BYTE_SIZE
,
801 (uint64_t)DEFAULT_L2_CACHE_CLUSTERS
803 *refcount_cache_size
= *l2_cache_size
804 / DEFAULT_L2_REFCOUNT_SIZE_RATIO
;
805 } else if (!l2_cache_size_set
) {
806 *l2_cache_size
= *refcount_cache_size
807 * DEFAULT_L2_REFCOUNT_SIZE_RATIO
;
808 } else if (!refcount_cache_size_set
) {
809 *refcount_cache_size
= *l2_cache_size
810 / DEFAULT_L2_REFCOUNT_SIZE_RATIO
;
814 if (*l2_cache_entry_size
< (1 << MIN_CLUSTER_BITS
) ||
815 *l2_cache_entry_size
> s
->cluster_size
||
816 !is_power_of_2(*l2_cache_entry_size
)) {
817 error_setg(errp
, "L2 cache entry size must be a power of two "
818 "between %d and the cluster size (%d)",
819 1 << MIN_CLUSTER_BITS
, s
->cluster_size
);
824 typedef struct Qcow2ReopenState
{
825 Qcow2Cache
*l2_table_cache
;
826 Qcow2Cache
*refcount_block_cache
;
827 int l2_slice_size
; /* Number of entries in a slice of the L2 table */
828 bool use_lazy_refcounts
;
830 bool discard_passthrough
[QCOW2_DISCARD_MAX
];
831 uint64_t cache_clean_interval
;
832 QCryptoBlockOpenOptions
*crypto_opts
; /* Disk encryption runtime options */
835 static int qcow2_update_options_prepare(BlockDriverState
*bs
,
837 QDict
*options
, int flags
,
840 BDRVQcow2State
*s
= bs
->opaque
;
841 QemuOpts
*opts
= NULL
;
842 const char *opt_overlap_check
, *opt_overlap_check_template
;
843 int overlap_check_template
= 0;
844 uint64_t l2_cache_size
, l2_cache_entry_size
, refcount_cache_size
;
846 const char *encryptfmt
;
847 QDict
*encryptopts
= NULL
;
848 Error
*local_err
= NULL
;
851 qdict_extract_subqdict(options
, &encryptopts
, "encrypt.");
852 encryptfmt
= qdict_get_try_str(encryptopts
, "format");
854 opts
= qemu_opts_create(&qcow2_runtime_opts
, NULL
, 0, &error_abort
);
855 qemu_opts_absorb_qdict(opts
, options
, &local_err
);
857 error_propagate(errp
, local_err
);
862 /* get L2 table/refcount block cache size from command line options */
863 read_cache_sizes(bs
, opts
, &l2_cache_size
, &l2_cache_entry_size
,
864 &refcount_cache_size
, &local_err
);
866 error_propagate(errp
, local_err
);
871 l2_cache_size
/= l2_cache_entry_size
;
872 if (l2_cache_size
< MIN_L2_CACHE_SIZE
) {
873 l2_cache_size
= MIN_L2_CACHE_SIZE
;
875 if (l2_cache_size
> INT_MAX
) {
876 error_setg(errp
, "L2 cache size too big");
881 refcount_cache_size
/= s
->cluster_size
;
882 if (refcount_cache_size
< MIN_REFCOUNT_CACHE_SIZE
) {
883 refcount_cache_size
= MIN_REFCOUNT_CACHE_SIZE
;
885 if (refcount_cache_size
> INT_MAX
) {
886 error_setg(errp
, "Refcount cache size too big");
891 /* alloc new L2 table/refcount block cache, flush old one */
892 if (s
->l2_table_cache
) {
893 ret
= qcow2_cache_flush(bs
, s
->l2_table_cache
);
895 error_setg_errno(errp
, -ret
, "Failed to flush the L2 table cache");
900 if (s
->refcount_block_cache
) {
901 ret
= qcow2_cache_flush(bs
, s
->refcount_block_cache
);
903 error_setg_errno(errp
, -ret
,
904 "Failed to flush the refcount block cache");
909 r
->l2_slice_size
= l2_cache_entry_size
/ sizeof(uint64_t);
910 r
->l2_table_cache
= qcow2_cache_create(bs
, l2_cache_size
,
911 l2_cache_entry_size
);
912 r
->refcount_block_cache
= qcow2_cache_create(bs
, refcount_cache_size
,
914 if (r
->l2_table_cache
== NULL
|| r
->refcount_block_cache
== NULL
) {
915 error_setg(errp
, "Could not allocate metadata caches");
920 /* New interval for cache cleanup timer */
921 r
->cache_clean_interval
=
922 qemu_opt_get_number(opts
, QCOW2_OPT_CACHE_CLEAN_INTERVAL
,
923 s
->cache_clean_interval
);
925 if (r
->cache_clean_interval
!= 0) {
926 error_setg(errp
, QCOW2_OPT_CACHE_CLEAN_INTERVAL
927 " not supported on this host");
932 if (r
->cache_clean_interval
> UINT_MAX
) {
933 error_setg(errp
, "Cache clean interval too big");
938 /* lazy-refcounts; flush if going from enabled to disabled */
939 r
->use_lazy_refcounts
= qemu_opt_get_bool(opts
, QCOW2_OPT_LAZY_REFCOUNTS
,
940 (s
->compatible_features
& QCOW2_COMPAT_LAZY_REFCOUNTS
));
941 if (r
->use_lazy_refcounts
&& s
->qcow_version
< 3) {
942 error_setg(errp
, "Lazy refcounts require a qcow2 image with at least "
943 "qemu 1.1 compatibility level");
948 if (s
->use_lazy_refcounts
&& !r
->use_lazy_refcounts
) {
949 ret
= qcow2_mark_clean(bs
);
951 error_setg_errno(errp
, -ret
, "Failed to disable lazy refcounts");
956 /* Overlap check options */
957 opt_overlap_check
= qemu_opt_get(opts
, QCOW2_OPT_OVERLAP
);
958 opt_overlap_check_template
= qemu_opt_get(opts
, QCOW2_OPT_OVERLAP_TEMPLATE
);
959 if (opt_overlap_check_template
&& opt_overlap_check
&&
960 strcmp(opt_overlap_check_template
, opt_overlap_check
))
962 error_setg(errp
, "Conflicting values for qcow2 options '"
963 QCOW2_OPT_OVERLAP
"' ('%s') and '" QCOW2_OPT_OVERLAP_TEMPLATE
964 "' ('%s')", opt_overlap_check
, opt_overlap_check_template
);
968 if (!opt_overlap_check
) {
969 opt_overlap_check
= opt_overlap_check_template
?: "cached";
972 if (!strcmp(opt_overlap_check
, "none")) {
973 overlap_check_template
= 0;
974 } else if (!strcmp(opt_overlap_check
, "constant")) {
975 overlap_check_template
= QCOW2_OL_CONSTANT
;
976 } else if (!strcmp(opt_overlap_check
, "cached")) {
977 overlap_check_template
= QCOW2_OL_CACHED
;
978 } else if (!strcmp(opt_overlap_check
, "all")) {
979 overlap_check_template
= QCOW2_OL_ALL
;
981 error_setg(errp
, "Unsupported value '%s' for qcow2 option "
982 "'overlap-check'. Allowed are any of the following: "
983 "none, constant, cached, all", opt_overlap_check
);
988 r
->overlap_check
= 0;
989 for (i
= 0; i
< QCOW2_OL_MAX_BITNR
; i
++) {
990 /* overlap-check defines a template bitmask, but every flag may be
991 * overwritten through the associated boolean option */
993 qemu_opt_get_bool(opts
, overlap_bool_option_names
[i
],
994 overlap_check_template
& (1 << i
)) << i
;
997 r
->discard_passthrough
[QCOW2_DISCARD_NEVER
] = false;
998 r
->discard_passthrough
[QCOW2_DISCARD_ALWAYS
] = true;
999 r
->discard_passthrough
[QCOW2_DISCARD_REQUEST
] =
1000 qemu_opt_get_bool(opts
, QCOW2_OPT_DISCARD_REQUEST
,
1001 flags
& BDRV_O_UNMAP
);
1002 r
->discard_passthrough
[QCOW2_DISCARD_SNAPSHOT
] =
1003 qemu_opt_get_bool(opts
, QCOW2_OPT_DISCARD_SNAPSHOT
, true);
1004 r
->discard_passthrough
[QCOW2_DISCARD_OTHER
] =
1005 qemu_opt_get_bool(opts
, QCOW2_OPT_DISCARD_OTHER
, false);
1007 switch (s
->crypt_method_header
) {
1008 case QCOW_CRYPT_NONE
:
1010 error_setg(errp
, "No encryption in image header, but options "
1011 "specified format '%s'", encryptfmt
);
1017 case QCOW_CRYPT_AES
:
1018 if (encryptfmt
&& !g_str_equal(encryptfmt
, "aes")) {
1020 "Header reported 'aes' encryption format but "
1021 "options specify '%s'", encryptfmt
);
1025 qdict_del(encryptopts
, "format");
1026 r
->crypto_opts
= block_crypto_open_opts_init(
1027 Q_CRYPTO_BLOCK_FORMAT_QCOW
, encryptopts
, errp
);
1030 case QCOW_CRYPT_LUKS
:
1031 if (encryptfmt
&& !g_str_equal(encryptfmt
, "luks")) {
1033 "Header reported 'luks' encryption format but "
1034 "options specify '%s'", encryptfmt
);
1038 qdict_del(encryptopts
, "format");
1039 r
->crypto_opts
= block_crypto_open_opts_init(
1040 Q_CRYPTO_BLOCK_FORMAT_LUKS
, encryptopts
, errp
);
1044 error_setg(errp
, "Unsupported encryption method %d",
1045 s
->crypt_method_header
);
1048 if (s
->crypt_method_header
!= QCOW_CRYPT_NONE
&& !r
->crypto_opts
) {
1055 QDECREF(encryptopts
);
1056 qemu_opts_del(opts
);
1061 static void qcow2_update_options_commit(BlockDriverState
*bs
,
1062 Qcow2ReopenState
*r
)
1064 BDRVQcow2State
*s
= bs
->opaque
;
1067 if (s
->l2_table_cache
) {
1068 qcow2_cache_destroy(s
->l2_table_cache
);
1070 if (s
->refcount_block_cache
) {
1071 qcow2_cache_destroy(s
->refcount_block_cache
);
1073 s
->l2_table_cache
= r
->l2_table_cache
;
1074 s
->refcount_block_cache
= r
->refcount_block_cache
;
1075 s
->l2_slice_size
= r
->l2_slice_size
;
1077 s
->overlap_check
= r
->overlap_check
;
1078 s
->use_lazy_refcounts
= r
->use_lazy_refcounts
;
1080 for (i
= 0; i
< QCOW2_DISCARD_MAX
; i
++) {
1081 s
->discard_passthrough
[i
] = r
->discard_passthrough
[i
];
1084 if (s
->cache_clean_interval
!= r
->cache_clean_interval
) {
1085 cache_clean_timer_del(bs
);
1086 s
->cache_clean_interval
= r
->cache_clean_interval
;
1087 cache_clean_timer_init(bs
, bdrv_get_aio_context(bs
));
1090 qapi_free_QCryptoBlockOpenOptions(s
->crypto_opts
);
1091 s
->crypto_opts
= r
->crypto_opts
;
1094 static void qcow2_update_options_abort(BlockDriverState
*bs
,
1095 Qcow2ReopenState
*r
)
1097 if (r
->l2_table_cache
) {
1098 qcow2_cache_destroy(r
->l2_table_cache
);
1100 if (r
->refcount_block_cache
) {
1101 qcow2_cache_destroy(r
->refcount_block_cache
);
1103 qapi_free_QCryptoBlockOpenOptions(r
->crypto_opts
);
1106 static int qcow2_update_options(BlockDriverState
*bs
, QDict
*options
,
1107 int flags
, Error
**errp
)
1109 Qcow2ReopenState r
= {};
1112 ret
= qcow2_update_options_prepare(bs
, &r
, options
, flags
, errp
);
1114 qcow2_update_options_commit(bs
, &r
);
1116 qcow2_update_options_abort(bs
, &r
);
1122 static int qcow2_do_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
1125 BDRVQcow2State
*s
= bs
->opaque
;
1126 unsigned int len
, i
;
1129 Error
*local_err
= NULL
;
1131 uint64_t l1_vm_state_index
;
1132 bool update_header
= false;
1134 ret
= bdrv_pread(bs
->file
, 0, &header
, sizeof(header
));
1136 error_setg_errno(errp
, -ret
, "Could not read qcow2 header");
1139 be32_to_cpus(&header
.magic
);
1140 be32_to_cpus(&header
.version
);
1141 be64_to_cpus(&header
.backing_file_offset
);
1142 be32_to_cpus(&header
.backing_file_size
);
1143 be64_to_cpus(&header
.size
);
1144 be32_to_cpus(&header
.cluster_bits
);
1145 be32_to_cpus(&header
.crypt_method
);
1146 be64_to_cpus(&header
.l1_table_offset
);
1147 be32_to_cpus(&header
.l1_size
);
1148 be64_to_cpus(&header
.refcount_table_offset
);
1149 be32_to_cpus(&header
.refcount_table_clusters
);
1150 be64_to_cpus(&header
.snapshots_offset
);
1151 be32_to_cpus(&header
.nb_snapshots
);
1153 if (header
.magic
!= QCOW_MAGIC
) {
1154 error_setg(errp
, "Image is not in qcow2 format");
1158 if (header
.version
< 2 || header
.version
> 3) {
1159 error_setg(errp
, "Unsupported qcow2 version %" PRIu32
, header
.version
);
1164 s
->qcow_version
= header
.version
;
1166 /* Initialise cluster size */
1167 if (header
.cluster_bits
< MIN_CLUSTER_BITS
||
1168 header
.cluster_bits
> MAX_CLUSTER_BITS
) {
1169 error_setg(errp
, "Unsupported cluster size: 2^%" PRIu32
,
1170 header
.cluster_bits
);
1175 s
->cluster_bits
= header
.cluster_bits
;
1176 s
->cluster_size
= 1 << s
->cluster_bits
;
1177 s
->cluster_sectors
= 1 << (s
->cluster_bits
- BDRV_SECTOR_BITS
);
1179 /* Initialise version 3 header fields */
1180 if (header
.version
== 2) {
1181 header
.incompatible_features
= 0;
1182 header
.compatible_features
= 0;
1183 header
.autoclear_features
= 0;
1184 header
.refcount_order
= 4;
1185 header
.header_length
= 72;
1187 be64_to_cpus(&header
.incompatible_features
);
1188 be64_to_cpus(&header
.compatible_features
);
1189 be64_to_cpus(&header
.autoclear_features
);
1190 be32_to_cpus(&header
.refcount_order
);
1191 be32_to_cpus(&header
.header_length
);
1193 if (header
.header_length
< 104) {
1194 error_setg(errp
, "qcow2 header too short");
1200 if (header
.header_length
> s
->cluster_size
) {
1201 error_setg(errp
, "qcow2 header exceeds cluster size");
1206 if (header
.header_length
> sizeof(header
)) {
1207 s
->unknown_header_fields_size
= header
.header_length
- sizeof(header
);
1208 s
->unknown_header_fields
= g_malloc(s
->unknown_header_fields_size
);
1209 ret
= bdrv_pread(bs
->file
, sizeof(header
), s
->unknown_header_fields
,
1210 s
->unknown_header_fields_size
);
1212 error_setg_errno(errp
, -ret
, "Could not read unknown qcow2 header "
1218 if (header
.backing_file_offset
> s
->cluster_size
) {
1219 error_setg(errp
, "Invalid backing file offset");
1224 if (header
.backing_file_offset
) {
1225 ext_end
= header
.backing_file_offset
;
1227 ext_end
= 1 << header
.cluster_bits
;
1230 /* Handle feature bits */
1231 s
->incompatible_features
= header
.incompatible_features
;
1232 s
->compatible_features
= header
.compatible_features
;
1233 s
->autoclear_features
= header
.autoclear_features
;
1235 if (s
->incompatible_features
& ~QCOW2_INCOMPAT_MASK
) {
1236 void *feature_table
= NULL
;
1237 qcow2_read_extensions(bs
, header
.header_length
, ext_end
,
1238 &feature_table
, flags
, NULL
, NULL
);
1239 report_unsupported_feature(errp
, feature_table
,
1240 s
->incompatible_features
&
1241 ~QCOW2_INCOMPAT_MASK
);
1243 g_free(feature_table
);
1247 if (s
->incompatible_features
& QCOW2_INCOMPAT_CORRUPT
) {
1248 /* Corrupt images may not be written to unless they are being repaired
1250 if ((flags
& BDRV_O_RDWR
) && !(flags
& BDRV_O_CHECK
)) {
1251 error_setg(errp
, "qcow2: Image is corrupt; cannot be opened "
1258 /* Check support for various header values */
1259 if (header
.refcount_order
> 6) {
1260 error_setg(errp
, "Reference count entry width too large; may not "
1265 s
->refcount_order
= header
.refcount_order
;
1266 s
->refcount_bits
= 1 << s
->refcount_order
;
1267 s
->refcount_max
= UINT64_C(1) << (s
->refcount_bits
- 1);
1268 s
->refcount_max
+= s
->refcount_max
- 1;
1270 s
->crypt_method_header
= header
.crypt_method
;
1271 if (s
->crypt_method_header
) {
1272 if (bdrv_uses_whitelist() &&
1273 s
->crypt_method_header
== QCOW_CRYPT_AES
) {
1275 "Use of AES-CBC encrypted qcow2 images is no longer "
1276 "supported in system emulators");
1277 error_append_hint(errp
,
1278 "You can use 'qemu-img convert' to convert your "
1279 "image to an alternative supported format, such "
1280 "as unencrypted qcow2, or raw with the LUKS "
1281 "format instead.\n");
1286 if (s
->crypt_method_header
== QCOW_CRYPT_AES
) {
1287 s
->crypt_physical_offset
= false;
1289 /* Assuming LUKS and any future crypt methods we
1290 * add will all use physical offsets, due to the
1291 * fact that the alternative is insecure... */
1292 s
->crypt_physical_offset
= true;
1295 bs
->encrypted
= true;
1298 s
->l2_bits
= s
->cluster_bits
- 3; /* L2 is always one cluster */
1299 s
->l2_size
= 1 << s
->l2_bits
;
1300 /* 2^(s->refcount_order - 3) is the refcount width in bytes */
1301 s
->refcount_block_bits
= s
->cluster_bits
- (s
->refcount_order
- 3);
1302 s
->refcount_block_size
= 1 << s
->refcount_block_bits
;
1303 bs
->total_sectors
= header
.size
/ 512;
1304 s
->csize_shift
= (62 - (s
->cluster_bits
- 8));
1305 s
->csize_mask
= (1 << (s
->cluster_bits
- 8)) - 1;
1306 s
->cluster_offset_mask
= (1LL << s
->csize_shift
) - 1;
1308 s
->refcount_table_offset
= header
.refcount_table_offset
;
1309 s
->refcount_table_size
=
1310 header
.refcount_table_clusters
<< (s
->cluster_bits
- 3);
1312 if (header
.refcount_table_clusters
> qcow2_max_refcount_clusters(s
)) {
1313 error_setg(errp
, "Reference count table too large");
1318 if (header
.refcount_table_clusters
== 0 && !(flags
& BDRV_O_CHECK
)) {
1319 error_setg(errp
, "Image does not contain a reference count table");
1324 ret
= validate_table_offset(bs
, s
->refcount_table_offset
,
1325 s
->refcount_table_size
, sizeof(uint64_t));
1327 error_setg(errp
, "Invalid reference count table offset");
1331 /* Snapshot table offset/length */
1332 if (header
.nb_snapshots
> QCOW_MAX_SNAPSHOTS
) {
1333 error_setg(errp
, "Too many snapshots");
1338 ret
= validate_table_offset(bs
, header
.snapshots_offset
,
1339 header
.nb_snapshots
,
1340 sizeof(QCowSnapshotHeader
));
1342 error_setg(errp
, "Invalid snapshot table offset");
1346 /* read the level 1 table */
1347 if (header
.l1_size
> QCOW_MAX_L1_SIZE
/ sizeof(uint64_t)) {
1348 error_setg(errp
, "Active L1 table too large");
1352 s
->l1_size
= header
.l1_size
;
1354 l1_vm_state_index
= size_to_l1(s
, header
.size
);
1355 if (l1_vm_state_index
> INT_MAX
) {
1356 error_setg(errp
, "Image is too big");
1360 s
->l1_vm_state_index
= l1_vm_state_index
;
1362 /* the L1 table must contain at least enough entries to put
1363 header.size bytes */
1364 if (s
->l1_size
< s
->l1_vm_state_index
) {
1365 error_setg(errp
, "L1 table is too small");
1370 ret
= validate_table_offset(bs
, header
.l1_table_offset
,
1371 header
.l1_size
, sizeof(uint64_t));
1373 error_setg(errp
, "Invalid L1 table offset");
1376 s
->l1_table_offset
= header
.l1_table_offset
;
1379 if (s
->l1_size
> 0) {
1380 s
->l1_table
= qemu_try_blockalign(bs
->file
->bs
,
1381 align_offset(s
->l1_size
* sizeof(uint64_t), 512));
1382 if (s
->l1_table
== NULL
) {
1383 error_setg(errp
, "Could not allocate L1 table");
1387 ret
= bdrv_pread(bs
->file
, s
->l1_table_offset
, s
->l1_table
,
1388 s
->l1_size
* sizeof(uint64_t));
1390 error_setg_errno(errp
, -ret
, "Could not read L1 table");
1393 for(i
= 0;i
< s
->l1_size
; i
++) {
1394 be64_to_cpus(&s
->l1_table
[i
]);
1398 /* Parse driver-specific options */
1399 ret
= qcow2_update_options(bs
, options
, flags
, errp
);
1404 s
->cluster_cache_offset
= -1;
1407 ret
= qcow2_refcount_init(bs
);
1409 error_setg_errno(errp
, -ret
, "Could not initialize refcount handling");
1413 QLIST_INIT(&s
->cluster_allocs
);
1414 QTAILQ_INIT(&s
->discards
);
1416 /* read qcow2 extensions */
1417 if (qcow2_read_extensions(bs
, header
.header_length
, ext_end
, NULL
,
1418 flags
, &update_header
, &local_err
)) {
1419 error_propagate(errp
, local_err
);
1424 /* qcow2_read_extension may have set up the crypto context
1425 * if the crypt method needs a header region, some methods
1426 * don't need header extensions, so must check here
1428 if (s
->crypt_method_header
&& !s
->crypto
) {
1429 if (s
->crypt_method_header
== QCOW_CRYPT_AES
) {
1430 unsigned int cflags
= 0;
1431 if (flags
& BDRV_O_NO_IO
) {
1432 cflags
|= QCRYPTO_BLOCK_OPEN_NO_IO
;
1434 s
->crypto
= qcrypto_block_open(s
->crypto_opts
, "encrypt.",
1435 NULL
, NULL
, cflags
, errp
);
1440 } else if (!(flags
& BDRV_O_NO_IO
)) {
1441 error_setg(errp
, "Missing CRYPTO header for crypt method %d",
1442 s
->crypt_method_header
);
1448 /* read the backing file name */
1449 if (header
.backing_file_offset
!= 0) {
1450 len
= header
.backing_file_size
;
1451 if (len
> MIN(1023, s
->cluster_size
- header
.backing_file_offset
) ||
1452 len
>= sizeof(bs
->backing_file
)) {
1453 error_setg(errp
, "Backing file name too long");
1457 ret
= bdrv_pread(bs
->file
, header
.backing_file_offset
,
1458 bs
->backing_file
, len
);
1460 error_setg_errno(errp
, -ret
, "Could not read backing file name");
1463 bs
->backing_file
[len
] = '\0';
1464 s
->image_backing_file
= g_strdup(bs
->backing_file
);
1467 /* Internal snapshots */
1468 s
->snapshots_offset
= header
.snapshots_offset
;
1469 s
->nb_snapshots
= header
.nb_snapshots
;
1471 ret
= qcow2_read_snapshots(bs
);
1473 error_setg_errno(errp
, -ret
, "Could not read snapshots");
1477 /* Clear unknown autoclear feature bits */
1478 update_header
|= s
->autoclear_features
& ~QCOW2_AUTOCLEAR_MASK
;
1480 update_header
&& !bs
->read_only
&& !(flags
& BDRV_O_INACTIVE
);
1481 if (update_header
) {
1482 s
->autoclear_features
&= QCOW2_AUTOCLEAR_MASK
;
1485 if (qcow2_load_dirty_bitmaps(bs
, &local_err
)) {
1486 update_header
= false;
1488 if (local_err
!= NULL
) {
1489 error_propagate(errp
, local_err
);
1494 if (update_header
) {
1495 ret
= qcow2_update_header(bs
);
1497 error_setg_errno(errp
, -ret
, "Could not update qcow2 header");
1502 /* Initialise locks */
1503 qemu_co_mutex_init(&s
->lock
);
1504 bs
->supported_zero_flags
= header
.version
>= 3 ? BDRV_REQ_MAY_UNMAP
: 0;
1506 /* Repair image if dirty */
1507 if (!(flags
& (BDRV_O_CHECK
| BDRV_O_INACTIVE
)) && !bs
->read_only
&&
1508 (s
->incompatible_features
& QCOW2_INCOMPAT_DIRTY
)) {
1509 BdrvCheckResult result
= {0};
1511 ret
= qcow2_check(bs
, &result
, BDRV_FIX_ERRORS
| BDRV_FIX_LEAKS
);
1512 if (ret
< 0 || result
.check_errors
) {
1516 error_setg_errno(errp
, -ret
, "Could not repair dirty image");
1523 BdrvCheckResult result
= {0};
1524 qcow2_check_refcounts(bs
, &result
, 0);
1530 g_free(s
->unknown_header_fields
);
1531 cleanup_unknown_header_ext(bs
);
1532 qcow2_free_snapshots(bs
);
1533 qcow2_refcount_close(bs
);
1534 qemu_vfree(s
->l1_table
);
1535 /* else pre-write overlap checks in cache_destroy may crash */
1537 cache_clean_timer_del(bs
);
1538 if (s
->l2_table_cache
) {
1539 qcow2_cache_destroy(s
->l2_table_cache
);
1541 if (s
->refcount_block_cache
) {
1542 qcow2_cache_destroy(s
->refcount_block_cache
);
1544 qcrypto_block_free(s
->crypto
);
1545 qapi_free_QCryptoBlockOpenOptions(s
->crypto_opts
);
1549 static int qcow2_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
1552 bs
->file
= bdrv_open_child(NULL
, options
, "file", bs
, &child_file
,
1558 return qcow2_do_open(bs
, options
, flags
, errp
);
1561 static void qcow2_refresh_limits(BlockDriverState
*bs
, Error
**errp
)
1563 BDRVQcow2State
*s
= bs
->opaque
;
1565 if (bs
->encrypted
) {
1566 /* Encryption works on a sector granularity */
1567 bs
->bl
.request_alignment
= BDRV_SECTOR_SIZE
;
1569 bs
->bl
.pwrite_zeroes_alignment
= s
->cluster_size
;
1570 bs
->bl
.pdiscard_alignment
= s
->cluster_size
;
1573 static int qcow2_reopen_prepare(BDRVReopenState
*state
,
1574 BlockReopenQueue
*queue
, Error
**errp
)
1576 Qcow2ReopenState
*r
;
1579 r
= g_new0(Qcow2ReopenState
, 1);
1582 ret
= qcow2_update_options_prepare(state
->bs
, r
, state
->options
,
1583 state
->flags
, errp
);
1588 /* We need to write out any unwritten data if we reopen read-only. */
1589 if ((state
->flags
& BDRV_O_RDWR
) == 0) {
1590 ret
= qcow2_reopen_bitmaps_ro(state
->bs
, errp
);
1595 ret
= bdrv_flush(state
->bs
);
1600 ret
= qcow2_mark_clean(state
->bs
);
1609 qcow2_update_options_abort(state
->bs
, r
);
1614 static void qcow2_reopen_commit(BDRVReopenState
*state
)
1616 qcow2_update_options_commit(state
->bs
, state
->opaque
);
1617 g_free(state
->opaque
);
1620 static void qcow2_reopen_abort(BDRVReopenState
*state
)
1622 qcow2_update_options_abort(state
->bs
, state
->opaque
);
1623 g_free(state
->opaque
);
1626 static void qcow2_join_options(QDict
*options
, QDict
*old_options
)
1628 bool has_new_overlap_template
=
1629 qdict_haskey(options
, QCOW2_OPT_OVERLAP
) ||
1630 qdict_haskey(options
, QCOW2_OPT_OVERLAP_TEMPLATE
);
1631 bool has_new_total_cache_size
=
1632 qdict_haskey(options
, QCOW2_OPT_CACHE_SIZE
);
1633 bool has_all_cache_options
;
1635 /* New overlap template overrides all old overlap options */
1636 if (has_new_overlap_template
) {
1637 qdict_del(old_options
, QCOW2_OPT_OVERLAP
);
1638 qdict_del(old_options
, QCOW2_OPT_OVERLAP_TEMPLATE
);
1639 qdict_del(old_options
, QCOW2_OPT_OVERLAP_MAIN_HEADER
);
1640 qdict_del(old_options
, QCOW2_OPT_OVERLAP_ACTIVE_L1
);
1641 qdict_del(old_options
, QCOW2_OPT_OVERLAP_ACTIVE_L2
);
1642 qdict_del(old_options
, QCOW2_OPT_OVERLAP_REFCOUNT_TABLE
);
1643 qdict_del(old_options
, QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK
);
1644 qdict_del(old_options
, QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE
);
1645 qdict_del(old_options
, QCOW2_OPT_OVERLAP_INACTIVE_L1
);
1646 qdict_del(old_options
, QCOW2_OPT_OVERLAP_INACTIVE_L2
);
1649 /* New total cache size overrides all old options */
1650 if (qdict_haskey(options
, QCOW2_OPT_CACHE_SIZE
)) {
1651 qdict_del(old_options
, QCOW2_OPT_L2_CACHE_SIZE
);
1652 qdict_del(old_options
, QCOW2_OPT_REFCOUNT_CACHE_SIZE
);
1655 qdict_join(options
, old_options
, false);
1658 * If after merging all cache size options are set, an old total size is
1659 * overwritten. Do keep all options, however, if all three are new. The
1660 * resulting error message is what we want to happen.
1662 has_all_cache_options
=
1663 qdict_haskey(options
, QCOW2_OPT_CACHE_SIZE
) ||
1664 qdict_haskey(options
, QCOW2_OPT_L2_CACHE_SIZE
) ||
1665 qdict_haskey(options
, QCOW2_OPT_REFCOUNT_CACHE_SIZE
);
1667 if (has_all_cache_options
&& !has_new_total_cache_size
) {
1668 qdict_del(options
, QCOW2_OPT_CACHE_SIZE
);
1672 static int64_t coroutine_fn
qcow2_co_get_block_status(BlockDriverState
*bs
,
1673 int64_t sector_num
, int nb_sectors
, int *pnum
, BlockDriverState
**file
)
1675 BDRVQcow2State
*s
= bs
->opaque
;
1676 uint64_t cluster_offset
;
1677 int index_in_cluster
, ret
;
1681 bytes
= MIN(INT_MAX
, nb_sectors
* BDRV_SECTOR_SIZE
);
1682 qemu_co_mutex_lock(&s
->lock
);
1683 ret
= qcow2_get_cluster_offset(bs
, sector_num
<< BDRV_SECTOR_BITS
, &bytes
,
1685 qemu_co_mutex_unlock(&s
->lock
);
1690 *pnum
= bytes
>> BDRV_SECTOR_BITS
;
1692 if (cluster_offset
!= 0 && ret
!= QCOW2_CLUSTER_COMPRESSED
&&
1694 index_in_cluster
= sector_num
& (s
->cluster_sectors
- 1);
1695 cluster_offset
|= (index_in_cluster
<< BDRV_SECTOR_BITS
);
1696 *file
= bs
->file
->bs
;
1697 status
|= BDRV_BLOCK_OFFSET_VALID
| cluster_offset
;
1699 if (ret
== QCOW2_CLUSTER_ZERO_PLAIN
|| ret
== QCOW2_CLUSTER_ZERO_ALLOC
) {
1700 status
|= BDRV_BLOCK_ZERO
;
1701 } else if (ret
!= QCOW2_CLUSTER_UNALLOCATED
) {
1702 status
|= BDRV_BLOCK_DATA
;
1707 static coroutine_fn
int qcow2_co_preadv(BlockDriverState
*bs
, uint64_t offset
,
1708 uint64_t bytes
, QEMUIOVector
*qiov
,
1711 BDRVQcow2State
*s
= bs
->opaque
;
1712 int offset_in_cluster
;
1714 unsigned int cur_bytes
; /* number of bytes in current iteration */
1715 uint64_t cluster_offset
= 0;
1716 uint64_t bytes_done
= 0;
1717 QEMUIOVector hd_qiov
;
1718 uint8_t *cluster_data
= NULL
;
1720 qemu_iovec_init(&hd_qiov
, qiov
->niov
);
1722 qemu_co_mutex_lock(&s
->lock
);
1724 while (bytes
!= 0) {
1726 /* prepare next request */
1727 cur_bytes
= MIN(bytes
, INT_MAX
);
1729 cur_bytes
= MIN(cur_bytes
,
1730 QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_size
);
1733 ret
= qcow2_get_cluster_offset(bs
, offset
, &cur_bytes
, &cluster_offset
);
1738 offset_in_cluster
= offset_into_cluster(s
, offset
);
1740 qemu_iovec_reset(&hd_qiov
);
1741 qemu_iovec_concat(&hd_qiov
, qiov
, bytes_done
, cur_bytes
);
1744 case QCOW2_CLUSTER_UNALLOCATED
:
1747 BLKDBG_EVENT(bs
->file
, BLKDBG_READ_BACKING_AIO
);
1748 qemu_co_mutex_unlock(&s
->lock
);
1749 ret
= bdrv_co_preadv(bs
->backing
, offset
, cur_bytes
,
1751 qemu_co_mutex_lock(&s
->lock
);
1756 /* Note: in this case, no need to wait */
1757 qemu_iovec_memset(&hd_qiov
, 0, 0, cur_bytes
);
1761 case QCOW2_CLUSTER_ZERO_PLAIN
:
1762 case QCOW2_CLUSTER_ZERO_ALLOC
:
1763 qemu_iovec_memset(&hd_qiov
, 0, 0, cur_bytes
);
1766 case QCOW2_CLUSTER_COMPRESSED
:
1767 /* add AIO support for compressed blocks ? */
1768 ret
= qcow2_decompress_cluster(bs
, cluster_offset
);
1773 qemu_iovec_from_buf(&hd_qiov
, 0,
1774 s
->cluster_cache
+ offset_in_cluster
,
1778 case QCOW2_CLUSTER_NORMAL
:
1779 if ((cluster_offset
& 511) != 0) {
1784 if (bs
->encrypted
) {
1788 * For encrypted images, read everything into a temporary
1789 * contiguous buffer on which the AES functions can work.
1791 if (!cluster_data
) {
1793 qemu_try_blockalign(bs
->file
->bs
,
1794 QCOW_MAX_CRYPT_CLUSTERS
1796 if (cluster_data
== NULL
) {
1802 assert(cur_bytes
<= QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_size
);
1803 qemu_iovec_reset(&hd_qiov
);
1804 qemu_iovec_add(&hd_qiov
, cluster_data
, cur_bytes
);
1807 BLKDBG_EVENT(bs
->file
, BLKDBG_READ_AIO
);
1808 qemu_co_mutex_unlock(&s
->lock
);
1809 ret
= bdrv_co_preadv(bs
->file
,
1810 cluster_offset
+ offset_in_cluster
,
1811 cur_bytes
, &hd_qiov
, 0);
1812 qemu_co_mutex_lock(&s
->lock
);
1816 if (bs
->encrypted
) {
1818 assert((offset
& (BDRV_SECTOR_SIZE
- 1)) == 0);
1819 assert((cur_bytes
& (BDRV_SECTOR_SIZE
- 1)) == 0);
1820 if (qcrypto_block_decrypt(s
->crypto
,
1821 (s
->crypt_physical_offset
?
1822 cluster_offset
+ offset_in_cluster
:
1830 qemu_iovec_from_buf(qiov
, bytes_done
, cluster_data
, cur_bytes
);
1835 g_assert_not_reached();
1841 offset
+= cur_bytes
;
1842 bytes_done
+= cur_bytes
;
1847 qemu_co_mutex_unlock(&s
->lock
);
1849 qemu_iovec_destroy(&hd_qiov
);
1850 qemu_vfree(cluster_data
);
1855 /* Check if it's possible to merge a write request with the writing of
1856 * the data from the COW regions */
1857 static bool merge_cow(uint64_t offset
, unsigned bytes
,
1858 QEMUIOVector
*hd_qiov
, QCowL2Meta
*l2meta
)
1862 for (m
= l2meta
; m
!= NULL
; m
= m
->next
) {
1863 /* If both COW regions are empty then there's nothing to merge */
1864 if (m
->cow_start
.nb_bytes
== 0 && m
->cow_end
.nb_bytes
== 0) {
1868 /* The data (middle) region must be immediately after the
1870 if (l2meta_cow_start(m
) + m
->cow_start
.nb_bytes
!= offset
) {
1874 /* The end region must be immediately after the data (middle)
1876 if (m
->offset
+ m
->cow_end
.offset
!= offset
+ bytes
) {
1880 /* Make sure that adding both COW regions to the QEMUIOVector
1881 * does not exceed IOV_MAX */
1882 if (hd_qiov
->niov
> IOV_MAX
- 2) {
1886 m
->data_qiov
= hd_qiov
;
1893 static coroutine_fn
int qcow2_co_pwritev(BlockDriverState
*bs
, uint64_t offset
,
1894 uint64_t bytes
, QEMUIOVector
*qiov
,
1897 BDRVQcow2State
*s
= bs
->opaque
;
1898 int offset_in_cluster
;
1900 unsigned int cur_bytes
; /* number of sectors in current iteration */
1901 uint64_t cluster_offset
;
1902 QEMUIOVector hd_qiov
;
1903 uint64_t bytes_done
= 0;
1904 uint8_t *cluster_data
= NULL
;
1905 QCowL2Meta
*l2meta
= NULL
;
1907 trace_qcow2_writev_start_req(qemu_coroutine_self(), offset
, bytes
);
1909 qemu_iovec_init(&hd_qiov
, qiov
->niov
);
1911 s
->cluster_cache_offset
= -1; /* disable compressed cache */
1913 qemu_co_mutex_lock(&s
->lock
);
1915 while (bytes
!= 0) {
1919 trace_qcow2_writev_start_part(qemu_coroutine_self());
1920 offset_in_cluster
= offset_into_cluster(s
, offset
);
1921 cur_bytes
= MIN(bytes
, INT_MAX
);
1922 if (bs
->encrypted
) {
1923 cur_bytes
= MIN(cur_bytes
,
1924 QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_size
1925 - offset_in_cluster
);
1928 ret
= qcow2_alloc_cluster_offset(bs
, offset
, &cur_bytes
,
1929 &cluster_offset
, &l2meta
);
1934 assert((cluster_offset
& 511) == 0);
1936 qemu_iovec_reset(&hd_qiov
);
1937 qemu_iovec_concat(&hd_qiov
, qiov
, bytes_done
, cur_bytes
);
1939 if (bs
->encrypted
) {
1941 if (!cluster_data
) {
1942 cluster_data
= qemu_try_blockalign(bs
->file
->bs
,
1943 QCOW_MAX_CRYPT_CLUSTERS
1945 if (cluster_data
== NULL
) {
1951 assert(hd_qiov
.size
<=
1952 QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_size
);
1953 qemu_iovec_to_buf(&hd_qiov
, 0, cluster_data
, hd_qiov
.size
);
1955 if (qcrypto_block_encrypt(s
->crypto
,
1956 (s
->crypt_physical_offset
?
1957 cluster_offset
+ offset_in_cluster
:
1960 cur_bytes
, NULL
) < 0) {
1965 qemu_iovec_reset(&hd_qiov
);
1966 qemu_iovec_add(&hd_qiov
, cluster_data
, cur_bytes
);
1969 ret
= qcow2_pre_write_overlap_check(bs
, 0,
1970 cluster_offset
+ offset_in_cluster
, cur_bytes
);
1975 /* If we need to do COW, check if it's possible to merge the
1976 * writing of the guest data together with that of the COW regions.
1977 * If it's not possible (or not necessary) then write the
1978 * guest data now. */
1979 if (!merge_cow(offset
, cur_bytes
, &hd_qiov
, l2meta
)) {
1980 qemu_co_mutex_unlock(&s
->lock
);
1981 BLKDBG_EVENT(bs
->file
, BLKDBG_WRITE_AIO
);
1982 trace_qcow2_writev_data(qemu_coroutine_self(),
1983 cluster_offset
+ offset_in_cluster
);
1984 ret
= bdrv_co_pwritev(bs
->file
,
1985 cluster_offset
+ offset_in_cluster
,
1986 cur_bytes
, &hd_qiov
, 0);
1987 qemu_co_mutex_lock(&s
->lock
);
1993 while (l2meta
!= NULL
) {
1996 ret
= qcow2_alloc_cluster_link_l2(bs
, l2meta
);
2001 /* Take the request off the list of running requests */
2002 if (l2meta
->nb_clusters
!= 0) {
2003 QLIST_REMOVE(l2meta
, next_in_flight
);
2006 qemu_co_queue_restart_all(&l2meta
->dependent_requests
);
2008 next
= l2meta
->next
;
2014 offset
+= cur_bytes
;
2015 bytes_done
+= cur_bytes
;
2016 trace_qcow2_writev_done_part(qemu_coroutine_self(), cur_bytes
);
2021 while (l2meta
!= NULL
) {
2024 if (l2meta
->nb_clusters
!= 0) {
2025 QLIST_REMOVE(l2meta
, next_in_flight
);
2027 qemu_co_queue_restart_all(&l2meta
->dependent_requests
);
2029 next
= l2meta
->next
;
2034 qemu_co_mutex_unlock(&s
->lock
);
2036 qemu_iovec_destroy(&hd_qiov
);
2037 qemu_vfree(cluster_data
);
2038 trace_qcow2_writev_done_req(qemu_coroutine_self(), ret
);
2043 static int qcow2_inactivate(BlockDriverState
*bs
)
2045 BDRVQcow2State
*s
= bs
->opaque
;
2046 int ret
, result
= 0;
2047 Error
*local_err
= NULL
;
2049 qcow2_store_persistent_dirty_bitmaps(bs
, &local_err
);
2050 if (local_err
!= NULL
) {
2052 error_report_err(local_err
);
2053 error_report("Persistent bitmaps are lost for node '%s'",
2054 bdrv_get_device_or_node_name(bs
));
2057 ret
= qcow2_cache_flush(bs
, s
->l2_table_cache
);
2060 error_report("Failed to flush the L2 table cache: %s",
2064 ret
= qcow2_cache_flush(bs
, s
->refcount_block_cache
);
2067 error_report("Failed to flush the refcount block cache: %s",
2072 qcow2_mark_clean(bs
);
2078 static void qcow2_close(BlockDriverState
*bs
)
2080 BDRVQcow2State
*s
= bs
->opaque
;
2081 qemu_vfree(s
->l1_table
);
2082 /* else pre-write overlap checks in cache_destroy may crash */
2085 if (!(s
->flags
& BDRV_O_INACTIVE
)) {
2086 qcow2_inactivate(bs
);
2089 cache_clean_timer_del(bs
);
2090 qcow2_cache_destroy(s
->l2_table_cache
);
2091 qcow2_cache_destroy(s
->refcount_block_cache
);
2093 qcrypto_block_free(s
->crypto
);
2096 g_free(s
->unknown_header_fields
);
2097 cleanup_unknown_header_ext(bs
);
2099 g_free(s
->image_backing_file
);
2100 g_free(s
->image_backing_format
);
2102 g_free(s
->cluster_cache
);
2103 qemu_vfree(s
->cluster_data
);
2104 qcow2_refcount_close(bs
);
2105 qcow2_free_snapshots(bs
);
2108 static void qcow2_invalidate_cache(BlockDriverState
*bs
, Error
**errp
)
2110 BDRVQcow2State
*s
= bs
->opaque
;
2111 int flags
= s
->flags
;
2112 QCryptoBlock
*crypto
= NULL
;
2114 Error
*local_err
= NULL
;
2118 * Backing files are read-only which makes all of their metadata immutable,
2119 * that means we don't have to worry about reopening them here.
2127 memset(s
, 0, sizeof(BDRVQcow2State
));
2128 options
= qdict_clone_shallow(bs
->options
);
2130 flags
&= ~BDRV_O_INACTIVE
;
2131 ret
= qcow2_do_open(bs
, options
, flags
, &local_err
);
2134 error_propagate(errp
, local_err
);
2135 error_prepend(errp
, "Could not reopen qcow2 layer: ");
2138 } else if (ret
< 0) {
2139 error_setg_errno(errp
, -ret
, "Could not reopen qcow2 layer");
2147 static size_t header_ext_add(char *buf
, uint32_t magic
, const void *s
,
2148 size_t len
, size_t buflen
)
2150 QCowExtension
*ext_backing_fmt
= (QCowExtension
*) buf
;
2151 size_t ext_len
= sizeof(QCowExtension
) + ((len
+ 7) & ~7);
2153 if (buflen
< ext_len
) {
2157 *ext_backing_fmt
= (QCowExtension
) {
2158 .magic
= cpu_to_be32(magic
),
2159 .len
= cpu_to_be32(len
),
2163 memcpy(buf
+ sizeof(QCowExtension
), s
, len
);
2170 * Updates the qcow2 header, including the variable length parts of it, i.e.
2171 * the backing file name and all extensions. qcow2 was not designed to allow
2172 * such changes, so if we run out of space (we can only use the first cluster)
2173 * this function may fail.
2175 * Returns 0 on success, -errno in error cases.
2177 int qcow2_update_header(BlockDriverState
*bs
)
2179 BDRVQcow2State
*s
= bs
->opaque
;
2182 size_t buflen
= s
->cluster_size
;
2184 uint64_t total_size
;
2185 uint32_t refcount_table_clusters
;
2186 size_t header_length
;
2187 Qcow2UnknownHeaderExtension
*uext
;
2189 buf
= qemu_blockalign(bs
, buflen
);
2191 /* Header structure */
2192 header
= (QCowHeader
*) buf
;
2194 if (buflen
< sizeof(*header
)) {
2199 header_length
= sizeof(*header
) + s
->unknown_header_fields_size
;
2200 total_size
= bs
->total_sectors
* BDRV_SECTOR_SIZE
;
2201 refcount_table_clusters
= s
->refcount_table_size
>> (s
->cluster_bits
- 3);
2203 *header
= (QCowHeader
) {
2204 /* Version 2 fields */
2205 .magic
= cpu_to_be32(QCOW_MAGIC
),
2206 .version
= cpu_to_be32(s
->qcow_version
),
2207 .backing_file_offset
= 0,
2208 .backing_file_size
= 0,
2209 .cluster_bits
= cpu_to_be32(s
->cluster_bits
),
2210 .size
= cpu_to_be64(total_size
),
2211 .crypt_method
= cpu_to_be32(s
->crypt_method_header
),
2212 .l1_size
= cpu_to_be32(s
->l1_size
),
2213 .l1_table_offset
= cpu_to_be64(s
->l1_table_offset
),
2214 .refcount_table_offset
= cpu_to_be64(s
->refcount_table_offset
),
2215 .refcount_table_clusters
= cpu_to_be32(refcount_table_clusters
),
2216 .nb_snapshots
= cpu_to_be32(s
->nb_snapshots
),
2217 .snapshots_offset
= cpu_to_be64(s
->snapshots_offset
),
2219 /* Version 3 fields */
2220 .incompatible_features
= cpu_to_be64(s
->incompatible_features
),
2221 .compatible_features
= cpu_to_be64(s
->compatible_features
),
2222 .autoclear_features
= cpu_to_be64(s
->autoclear_features
),
2223 .refcount_order
= cpu_to_be32(s
->refcount_order
),
2224 .header_length
= cpu_to_be32(header_length
),
2227 /* For older versions, write a shorter header */
2228 switch (s
->qcow_version
) {
2230 ret
= offsetof(QCowHeader
, incompatible_features
);
2233 ret
= sizeof(*header
);
2242 memset(buf
, 0, buflen
);
2244 /* Preserve any unknown field in the header */
2245 if (s
->unknown_header_fields_size
) {
2246 if (buflen
< s
->unknown_header_fields_size
) {
2251 memcpy(buf
, s
->unknown_header_fields
, s
->unknown_header_fields_size
);
2252 buf
+= s
->unknown_header_fields_size
;
2253 buflen
-= s
->unknown_header_fields_size
;
2256 /* Backing file format header extension */
2257 if (s
->image_backing_format
) {
2258 ret
= header_ext_add(buf
, QCOW2_EXT_MAGIC_BACKING_FORMAT
,
2259 s
->image_backing_format
,
2260 strlen(s
->image_backing_format
),
2270 /* Full disk encryption header pointer extension */
2271 if (s
->crypto_header
.offset
!= 0) {
2272 cpu_to_be64s(&s
->crypto_header
.offset
);
2273 cpu_to_be64s(&s
->crypto_header
.length
);
2274 ret
= header_ext_add(buf
, QCOW2_EXT_MAGIC_CRYPTO_HEADER
,
2275 &s
->crypto_header
, sizeof(s
->crypto_header
),
2277 be64_to_cpus(&s
->crypto_header
.offset
);
2278 be64_to_cpus(&s
->crypto_header
.length
);
2287 if (s
->qcow_version
>= 3) {
2288 Qcow2Feature features
[] = {
2290 .type
= QCOW2_FEAT_TYPE_INCOMPATIBLE
,
2291 .bit
= QCOW2_INCOMPAT_DIRTY_BITNR
,
2292 .name
= "dirty bit",
2295 .type
= QCOW2_FEAT_TYPE_INCOMPATIBLE
,
2296 .bit
= QCOW2_INCOMPAT_CORRUPT_BITNR
,
2297 .name
= "corrupt bit",
2300 .type
= QCOW2_FEAT_TYPE_COMPATIBLE
,
2301 .bit
= QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR
,
2302 .name
= "lazy refcounts",
2306 ret
= header_ext_add(buf
, QCOW2_EXT_MAGIC_FEATURE_TABLE
,
2307 features
, sizeof(features
), buflen
);
2315 /* Bitmap extension */
2316 if (s
->nb_bitmaps
> 0) {
2317 Qcow2BitmapHeaderExt bitmaps_header
= {
2318 .nb_bitmaps
= cpu_to_be32(s
->nb_bitmaps
),
2319 .bitmap_directory_size
=
2320 cpu_to_be64(s
->bitmap_directory_size
),
2321 .bitmap_directory_offset
=
2322 cpu_to_be64(s
->bitmap_directory_offset
)
2324 ret
= header_ext_add(buf
, QCOW2_EXT_MAGIC_BITMAPS
,
2325 &bitmaps_header
, sizeof(bitmaps_header
),
2334 /* Keep unknown header extensions */
2335 QLIST_FOREACH(uext
, &s
->unknown_header_ext
, next
) {
2336 ret
= header_ext_add(buf
, uext
->magic
, uext
->data
, uext
->len
, buflen
);
2345 /* End of header extensions */
2346 ret
= header_ext_add(buf
, QCOW2_EXT_MAGIC_END
, NULL
, 0, buflen
);
2354 /* Backing file name */
2355 if (s
->image_backing_file
) {
2356 size_t backing_file_len
= strlen(s
->image_backing_file
);
2358 if (buflen
< backing_file_len
) {
2363 /* Using strncpy is ok here, since buf is not NUL-terminated. */
2364 strncpy(buf
, s
->image_backing_file
, buflen
);
2366 header
->backing_file_offset
= cpu_to_be64(buf
- ((char*) header
));
2367 header
->backing_file_size
= cpu_to_be32(backing_file_len
);
2370 /* Write the new header */
2371 ret
= bdrv_pwrite(bs
->file
, 0, header
, s
->cluster_size
);
2382 static int qcow2_change_backing_file(BlockDriverState
*bs
,
2383 const char *backing_file
, const char *backing_fmt
)
2385 BDRVQcow2State
*s
= bs
->opaque
;
2387 if (backing_file
&& strlen(backing_file
) > 1023) {
2391 pstrcpy(bs
->backing_file
, sizeof(bs
->backing_file
), backing_file
?: "");
2392 pstrcpy(bs
->backing_format
, sizeof(bs
->backing_format
), backing_fmt
?: "");
2394 g_free(s
->image_backing_file
);
2395 g_free(s
->image_backing_format
);
2397 s
->image_backing_file
= backing_file
? g_strdup(bs
->backing_file
) : NULL
;
2398 s
->image_backing_format
= backing_fmt
? g_strdup(bs
->backing_format
) : NULL
;
2400 return qcow2_update_header(bs
);
2403 static int qcow2_crypt_method_from_format(const char *encryptfmt
)
2405 if (g_str_equal(encryptfmt
, "luks")) {
2406 return QCOW_CRYPT_LUKS
;
2407 } else if (g_str_equal(encryptfmt
, "aes")) {
2408 return QCOW_CRYPT_AES
;
2414 static int qcow2_set_up_encryption(BlockDriverState
*bs
, const char *encryptfmt
,
2415 QemuOpts
*opts
, Error
**errp
)
2417 BDRVQcow2State
*s
= bs
->opaque
;
2418 QCryptoBlockCreateOptions
*cryptoopts
= NULL
;
2419 QCryptoBlock
*crypto
= NULL
;
2421 QDict
*options
, *encryptopts
;
2424 options
= qemu_opts_to_qdict(opts
, NULL
);
2425 qdict_extract_subqdict(options
, &encryptopts
, "encrypt.");
2428 fmt
= qcow2_crypt_method_from_format(encryptfmt
);
2431 case QCOW_CRYPT_LUKS
:
2432 cryptoopts
= block_crypto_create_opts_init(
2433 Q_CRYPTO_BLOCK_FORMAT_LUKS
, encryptopts
, errp
);
2435 case QCOW_CRYPT_AES
:
2436 cryptoopts
= block_crypto_create_opts_init(
2437 Q_CRYPTO_BLOCK_FORMAT_QCOW
, encryptopts
, errp
);
2440 error_setg(errp
, "Unknown encryption format '%s'", encryptfmt
);
2447 s
->crypt_method_header
= fmt
;
2449 crypto
= qcrypto_block_create(cryptoopts
, "encrypt.",
2450 qcow2_crypto_hdr_init_func
,
2451 qcow2_crypto_hdr_write_func
,
2458 ret
= qcow2_update_header(bs
);
2460 error_setg_errno(errp
, -ret
, "Could not write encryption header");
2465 QDECREF(encryptopts
);
2466 qcrypto_block_free(crypto
);
2467 qapi_free_QCryptoBlockCreateOptions(cryptoopts
);
2472 typedef struct PreallocCo
{
2473 BlockDriverState
*bs
;
2475 uint64_t new_length
;
2481 * Preallocates metadata structures for data clusters between @offset (in the
2482 * guest disk) and @new_length (which is thus generally the new guest disk
2485 * Returns: 0 on success, -errno on failure.
2487 static void coroutine_fn
preallocate_co(void *opaque
)
2489 PreallocCo
*params
= opaque
;
2490 BlockDriverState
*bs
= params
->bs
;
2491 uint64_t offset
= params
->offset
;
2492 uint64_t new_length
= params
->new_length
;
2493 BDRVQcow2State
*s
= bs
->opaque
;
2495 uint64_t host_offset
= 0;
2496 unsigned int cur_bytes
;
2500 qemu_co_mutex_lock(&s
->lock
);
2502 assert(offset
<= new_length
);
2503 bytes
= new_length
- offset
;
2506 cur_bytes
= MIN(bytes
, INT_MAX
);
2507 ret
= qcow2_alloc_cluster_offset(bs
, offset
, &cur_bytes
,
2508 &host_offset
, &meta
);
2514 QCowL2Meta
*next
= meta
->next
;
2516 ret
= qcow2_alloc_cluster_link_l2(bs
, meta
);
2518 qcow2_free_any_clusters(bs
, meta
->alloc_offset
,
2519 meta
->nb_clusters
, QCOW2_DISCARD_NEVER
);
2523 /* There are no dependent requests, but we need to remove our
2524 * request from the list of in-flight requests */
2525 QLIST_REMOVE(meta
, next_in_flight
);
2531 /* TODO Preallocate data if requested */
2534 offset
+= cur_bytes
;
2538 * It is expected that the image file is large enough to actually contain
2539 * all of the allocated clusters (otherwise we get failing reads after
2540 * EOF). Extend the image to the last allocated sector.
2542 if (host_offset
!= 0) {
2544 ret
= bdrv_pwrite(bs
->file
, (host_offset
+ cur_bytes
) - 1,
2554 qemu_co_mutex_unlock(&s
->lock
);
2558 static int preallocate(BlockDriverState
*bs
,
2559 uint64_t offset
, uint64_t new_length
)
2561 PreallocCo params
= {
2564 .new_length
= new_length
,
2565 .ret
= -EINPROGRESS
,
2568 if (qemu_in_coroutine()) {
2569 preallocate_co(¶ms
);
2571 Coroutine
*co
= qemu_coroutine_create(preallocate_co
, ¶ms
);
2572 bdrv_coroutine_enter(bs
, co
);
2573 BDRV_POLL_WHILE(bs
, params
.ret
== -EINPROGRESS
);
2578 /* qcow2_refcount_metadata_size:
2579 * @clusters: number of clusters to refcount (including data and L1/L2 tables)
2580 * @cluster_size: size of a cluster, in bytes
2581 * @refcount_order: refcount bits power-of-2 exponent
2582 * @generous_increase: allow for the refcount table to be 1.5x as large as it
2585 * Returns: Number of bytes required for refcount blocks and table metadata.
2587 int64_t qcow2_refcount_metadata_size(int64_t clusters
, size_t cluster_size
,
2588 int refcount_order
, bool generous_increase
,
2589 uint64_t *refblock_count
)
2592 * Every host cluster is reference-counted, including metadata (even
2593 * refcount metadata is recursively included).
2595 * An accurate formula for the size of refcount metadata size is difficult
2596 * to derive. An easier method of calculation is finding the fixed point
2597 * where no further refcount blocks or table clusters are required to
2598 * reference count every cluster.
2600 int64_t blocks_per_table_cluster
= cluster_size
/ sizeof(uint64_t);
2601 int64_t refcounts_per_block
= cluster_size
* 8 / (1 << refcount_order
);
2602 int64_t table
= 0; /* number of refcount table clusters */
2603 int64_t blocks
= 0; /* number of refcount block clusters */
2609 blocks
= DIV_ROUND_UP(clusters
+ table
+ blocks
, refcounts_per_block
);
2610 table
= DIV_ROUND_UP(blocks
, blocks_per_table_cluster
);
2611 n
= clusters
+ blocks
+ table
;
2613 if (n
== last
&& generous_increase
) {
2614 clusters
+= DIV_ROUND_UP(table
, 2);
2615 n
= 0; /* force another loop */
2616 generous_increase
= false;
2618 } while (n
!= last
);
2620 if (refblock_count
) {
2621 *refblock_count
= blocks
;
2624 return (blocks
+ table
) * cluster_size
;
2628 * qcow2_calc_prealloc_size:
2629 * @total_size: virtual disk size in bytes
2630 * @cluster_size: cluster size in bytes
2631 * @refcount_order: refcount bits power-of-2 exponent
2633 * Returns: Total number of bytes required for the fully allocated image
2634 * (including metadata).
2636 static int64_t qcow2_calc_prealloc_size(int64_t total_size
,
2637 size_t cluster_size
,
2640 int64_t meta_size
= 0;
2641 uint64_t nl1e
, nl2e
;
2642 int64_t aligned_total_size
= align_offset(total_size
, cluster_size
);
2644 /* header: 1 cluster */
2645 meta_size
+= cluster_size
;
2647 /* total size of L2 tables */
2648 nl2e
= aligned_total_size
/ cluster_size
;
2649 nl2e
= align_offset(nl2e
, cluster_size
/ sizeof(uint64_t));
2650 meta_size
+= nl2e
* sizeof(uint64_t);
2652 /* total size of L1 tables */
2653 nl1e
= nl2e
* sizeof(uint64_t) / cluster_size
;
2654 nl1e
= align_offset(nl1e
, cluster_size
/ sizeof(uint64_t));
2655 meta_size
+= nl1e
* sizeof(uint64_t);
2657 /* total size of refcount table and blocks */
2658 meta_size
+= qcow2_refcount_metadata_size(
2659 (meta_size
+ aligned_total_size
) / cluster_size
,
2660 cluster_size
, refcount_order
, false, NULL
);
2662 return meta_size
+ aligned_total_size
;
2665 static size_t qcow2_opt_get_cluster_size_del(QemuOpts
*opts
, Error
**errp
)
2667 size_t cluster_size
;
2670 cluster_size
= qemu_opt_get_size_del(opts
, BLOCK_OPT_CLUSTER_SIZE
,
2671 DEFAULT_CLUSTER_SIZE
);
2672 cluster_bits
= ctz32(cluster_size
);
2673 if (cluster_bits
< MIN_CLUSTER_BITS
|| cluster_bits
> MAX_CLUSTER_BITS
||
2674 (1 << cluster_bits
) != cluster_size
)
2676 error_setg(errp
, "Cluster size must be a power of two between %d and "
2677 "%dk", 1 << MIN_CLUSTER_BITS
, 1 << (MAX_CLUSTER_BITS
- 10));
2680 return cluster_size
;
2683 static int qcow2_opt_get_version_del(QemuOpts
*opts
, Error
**errp
)
2688 buf
= qemu_opt_get_del(opts
, BLOCK_OPT_COMPAT_LEVEL
);
2690 ret
= 3; /* default */
2691 } else if (!strcmp(buf
, "0.10")) {
2693 } else if (!strcmp(buf
, "1.1")) {
2696 error_setg(errp
, "Invalid compatibility level: '%s'", buf
);
2703 static uint64_t qcow2_opt_get_refcount_bits_del(QemuOpts
*opts
, int version
,
2706 uint64_t refcount_bits
;
2708 refcount_bits
= qemu_opt_get_number_del(opts
, BLOCK_OPT_REFCOUNT_BITS
, 16);
2709 if (refcount_bits
> 64 || !is_power_of_2(refcount_bits
)) {
2710 error_setg(errp
, "Refcount width must be a power of two and may not "
2715 if (version
< 3 && refcount_bits
!= 16) {
2716 error_setg(errp
, "Different refcount widths than 16 bits require "
2717 "compatibility level 1.1 or above (use compat=1.1 or "
2722 return refcount_bits
;
2725 static int qcow2_create2(const char *filename
, int64_t total_size
,
2726 const char *backing_file
, const char *backing_format
,
2727 int flags
, size_t cluster_size
, PreallocMode prealloc
,
2728 QemuOpts
*opts
, int version
, int refcount_order
,
2729 const char *encryptfmt
, Error
**errp
)
2734 * Open the image file and write a minimal qcow2 header.
2736 * We keep things simple and start with a zero-sized image. We also
2737 * do without refcount blocks or a L1 table for now. We'll fix the
2738 * inconsistency later.
2740 * We do need a refcount table because growing the refcount table means
2741 * allocating two new refcount blocks - the seconds of which would be at
2742 * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
2743 * size for any qcow2 image.
2747 uint64_t* refcount_table
;
2748 Error
*local_err
= NULL
;
2751 if (prealloc
== PREALLOC_MODE_FULL
|| prealloc
== PREALLOC_MODE_FALLOC
) {
2752 int64_t prealloc_size
=
2753 qcow2_calc_prealloc_size(total_size
, cluster_size
, refcount_order
);
2754 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, prealloc_size
, &error_abort
);
2755 qemu_opt_set(opts
, BLOCK_OPT_PREALLOC
, PreallocMode_str(prealloc
),
2759 ret
= bdrv_create_file(filename
, opts
, &local_err
);
2761 error_propagate(errp
, local_err
);
2765 blk
= blk_new_open(filename
, NULL
, NULL
,
2766 BDRV_O_RDWR
| BDRV_O_RESIZE
| BDRV_O_PROTOCOL
,
2769 error_propagate(errp
, local_err
);
2773 blk_set_allow_write_beyond_eof(blk
, true);
2775 /* Write the header */
2776 QEMU_BUILD_BUG_ON((1 << MIN_CLUSTER_BITS
) < sizeof(*header
));
2777 header
= g_malloc0(cluster_size
);
2778 *header
= (QCowHeader
) {
2779 .magic
= cpu_to_be32(QCOW_MAGIC
),
2780 .version
= cpu_to_be32(version
),
2781 .cluster_bits
= cpu_to_be32(ctz32(cluster_size
)),
2782 .size
= cpu_to_be64(0),
2783 .l1_table_offset
= cpu_to_be64(0),
2784 .l1_size
= cpu_to_be32(0),
2785 .refcount_table_offset
= cpu_to_be64(cluster_size
),
2786 .refcount_table_clusters
= cpu_to_be32(1),
2787 .refcount_order
= cpu_to_be32(refcount_order
),
2788 .header_length
= cpu_to_be32(sizeof(*header
)),
2791 /* We'll update this to correct value later */
2792 header
->crypt_method
= cpu_to_be32(QCOW_CRYPT_NONE
);
2794 if (flags
& BLOCK_FLAG_LAZY_REFCOUNTS
) {
2795 header
->compatible_features
|=
2796 cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS
);
2799 ret
= blk_pwrite(blk
, 0, header
, cluster_size
, 0);
2802 error_setg_errno(errp
, -ret
, "Could not write qcow2 header");
2806 /* Write a refcount table with one refcount block */
2807 refcount_table
= g_malloc0(2 * cluster_size
);
2808 refcount_table
[0] = cpu_to_be64(2 * cluster_size
);
2809 ret
= blk_pwrite(blk
, cluster_size
, refcount_table
, 2 * cluster_size
, 0);
2810 g_free(refcount_table
);
2813 error_setg_errno(errp
, -ret
, "Could not write refcount table");
2821 * And now open the image and make it consistent first (i.e. increase the
2822 * refcount of the cluster that is occupied by the header and the refcount
2825 options
= qdict_new();
2826 qdict_put_str(options
, "driver", "qcow2");
2827 blk
= blk_new_open(filename
, NULL
, options
,
2828 BDRV_O_RDWR
| BDRV_O_RESIZE
| BDRV_O_NO_FLUSH
,
2831 error_propagate(errp
, local_err
);
2836 ret
= qcow2_alloc_clusters(blk_bs(blk
), 3 * cluster_size
);
2838 error_setg_errno(errp
, -ret
, "Could not allocate clusters for qcow2 "
2839 "header and refcount table");
2842 } else if (ret
!= 0) {
2843 error_report("Huh, first cluster in empty image is already in use?");
2847 /* Create a full header (including things like feature table) */
2848 ret
= qcow2_update_header(blk_bs(blk
));
2850 error_setg_errno(errp
, -ret
, "Could not update qcow2 header");
2854 /* Okay, now that we have a valid image, let's give it the right size */
2855 ret
= blk_truncate(blk
, total_size
, PREALLOC_MODE_OFF
, errp
);
2857 error_prepend(errp
, "Could not resize image: ");
2861 /* Want a backing file? There you go.*/
2863 ret
= bdrv_change_backing_file(blk_bs(blk
), backing_file
, backing_format
);
2865 error_setg_errno(errp
, -ret
, "Could not assign backing file '%s' "
2866 "with format '%s'", backing_file
, backing_format
);
2871 /* Want encryption? There you go. */
2873 ret
= qcow2_set_up_encryption(blk_bs(blk
), encryptfmt
, opts
, errp
);
2879 /* And if we're supposed to preallocate metadata, do that now */
2880 if (prealloc
!= PREALLOC_MODE_OFF
) {
2881 ret
= preallocate(blk_bs(blk
), 0, total_size
);
2883 error_setg_errno(errp
, -ret
, "Could not preallocate metadata");
2891 /* Reopen the image without BDRV_O_NO_FLUSH to flush it before returning.
2892 * Using BDRV_O_NO_IO, since encryption is now setup we don't want to
2893 * have to setup decryption context. We're not doing any I/O on the top
2894 * level BlockDriverState, only lower layers, where BDRV_O_NO_IO does
2897 options
= qdict_new();
2898 qdict_put_str(options
, "driver", "qcow2");
2899 blk
= blk_new_open(filename
, NULL
, options
,
2900 BDRV_O_RDWR
| BDRV_O_NO_BACKING
| BDRV_O_NO_IO
,
2903 error_propagate(errp
, local_err
);
2916 static int qcow2_create(const char *filename
, QemuOpts
*opts
, Error
**errp
)
2918 char *backing_file
= NULL
;
2919 char *backing_fmt
= NULL
;
2923 size_t cluster_size
= DEFAULT_CLUSTER_SIZE
;
2924 PreallocMode prealloc
;
2926 uint64_t refcount_bits
;
2928 char *encryptfmt
= NULL
;
2929 Error
*local_err
= NULL
;
2932 /* Read out options */
2933 size
= ROUND_UP(qemu_opt_get_size_del(opts
, BLOCK_OPT_SIZE
, 0),
2935 backing_file
= qemu_opt_get_del(opts
, BLOCK_OPT_BACKING_FILE
);
2936 backing_fmt
= qemu_opt_get_del(opts
, BLOCK_OPT_BACKING_FMT
);
2937 encryptfmt
= qemu_opt_get_del(opts
, BLOCK_OPT_ENCRYPT_FORMAT
);
2939 if (qemu_opt_get(opts
, BLOCK_OPT_ENCRYPT
)) {
2940 error_setg(errp
, "Options " BLOCK_OPT_ENCRYPT
" and "
2941 BLOCK_OPT_ENCRYPT_FORMAT
" are mutually exclusive");
2945 } else if (qemu_opt_get_bool_del(opts
, BLOCK_OPT_ENCRYPT
, false)) {
2946 encryptfmt
= g_strdup("aes");
2948 cluster_size
= qcow2_opt_get_cluster_size_del(opts
, &local_err
);
2950 error_propagate(errp
, local_err
);
2954 buf
= qemu_opt_get_del(opts
, BLOCK_OPT_PREALLOC
);
2955 prealloc
= qapi_enum_parse(&PreallocMode_lookup
, buf
,
2956 PREALLOC_MODE_OFF
, &local_err
);
2958 error_propagate(errp
, local_err
);
2963 version
= qcow2_opt_get_version_del(opts
, &local_err
);
2965 error_propagate(errp
, local_err
);
2970 if (qemu_opt_get_bool_del(opts
, BLOCK_OPT_LAZY_REFCOUNTS
, false)) {
2971 flags
|= BLOCK_FLAG_LAZY_REFCOUNTS
;
2974 if (backing_file
&& prealloc
!= PREALLOC_MODE_OFF
) {
2975 error_setg(errp
, "Backing file and preallocation cannot be used at "
2981 if (version
< 3 && (flags
& BLOCK_FLAG_LAZY_REFCOUNTS
)) {
2982 error_setg(errp
, "Lazy refcounts only supported with compatibility "
2983 "level 1.1 and above (use compat=1.1 or greater)");
2988 refcount_bits
= qcow2_opt_get_refcount_bits_del(opts
, version
, &local_err
);
2990 error_propagate(errp
, local_err
);
2995 refcount_order
= ctz32(refcount_bits
);
2997 ret
= qcow2_create2(filename
, size
, backing_file
, backing_fmt
, flags
,
2998 cluster_size
, prealloc
, opts
, version
, refcount_order
,
2999 encryptfmt
, &local_err
);
3000 error_propagate(errp
, local_err
);
3003 g_free(backing_file
);
3004 g_free(backing_fmt
);
3011 static bool is_zero(BlockDriverState
*bs
, int64_t offset
, int64_t bytes
)
3016 /* Clamp to image length, before checking status of underlying sectors */
3017 if (offset
+ bytes
> bs
->total_sectors
* BDRV_SECTOR_SIZE
) {
3018 bytes
= bs
->total_sectors
* BDRV_SECTOR_SIZE
- offset
;
3024 res
= bdrv_block_status_above(bs
, NULL
, offset
, bytes
, &nr
, NULL
, NULL
);
3025 return res
>= 0 && (res
& BDRV_BLOCK_ZERO
) && nr
== bytes
;
3028 static coroutine_fn
int qcow2_co_pwrite_zeroes(BlockDriverState
*bs
,
3029 int64_t offset
, int bytes
, BdrvRequestFlags flags
)
3032 BDRVQcow2State
*s
= bs
->opaque
;
3034 uint32_t head
= offset
% s
->cluster_size
;
3035 uint32_t tail
= (offset
+ bytes
) % s
->cluster_size
;
3037 trace_qcow2_pwrite_zeroes_start_req(qemu_coroutine_self(), offset
, bytes
);
3038 if (offset
+ bytes
== bs
->total_sectors
* BDRV_SECTOR_SIZE
) {
3046 assert(head
+ bytes
<= s
->cluster_size
);
3048 /* check whether remainder of cluster already reads as zero */
3049 if (!(is_zero(bs
, offset
- head
, head
) &&
3050 is_zero(bs
, offset
+ bytes
,
3051 tail
? s
->cluster_size
- tail
: 0))) {
3055 qemu_co_mutex_lock(&s
->lock
);
3056 /* We can have new write after previous check */
3057 offset
= QEMU_ALIGN_DOWN(offset
, s
->cluster_size
);
3058 bytes
= s
->cluster_size
;
3059 nr
= s
->cluster_size
;
3060 ret
= qcow2_get_cluster_offset(bs
, offset
, &nr
, &off
);
3061 if (ret
!= QCOW2_CLUSTER_UNALLOCATED
&&
3062 ret
!= QCOW2_CLUSTER_ZERO_PLAIN
&&
3063 ret
!= QCOW2_CLUSTER_ZERO_ALLOC
) {
3064 qemu_co_mutex_unlock(&s
->lock
);
3068 qemu_co_mutex_lock(&s
->lock
);
3071 trace_qcow2_pwrite_zeroes(qemu_coroutine_self(), offset
, bytes
);
3073 /* Whatever is left can use real zero clusters */
3074 ret
= qcow2_cluster_zeroize(bs
, offset
, bytes
, flags
);
3075 qemu_co_mutex_unlock(&s
->lock
);
3080 static coroutine_fn
int qcow2_co_pdiscard(BlockDriverState
*bs
,
3081 int64_t offset
, int bytes
)
3084 BDRVQcow2State
*s
= bs
->opaque
;
3086 if (!QEMU_IS_ALIGNED(offset
| bytes
, s
->cluster_size
)) {
3087 assert(bytes
< s
->cluster_size
);
3088 /* Ignore partial clusters, except for the special case of the
3089 * complete partial cluster at the end of an unaligned file */
3090 if (!QEMU_IS_ALIGNED(offset
, s
->cluster_size
) ||
3091 offset
+ bytes
!= bs
->total_sectors
* BDRV_SECTOR_SIZE
) {
3096 qemu_co_mutex_lock(&s
->lock
);
3097 ret
= qcow2_cluster_discard(bs
, offset
, bytes
, QCOW2_DISCARD_REQUEST
,
3099 qemu_co_mutex_unlock(&s
->lock
);
3103 static int qcow2_truncate(BlockDriverState
*bs
, int64_t offset
,
3104 PreallocMode prealloc
, Error
**errp
)
3106 BDRVQcow2State
*s
= bs
->opaque
;
3107 uint64_t old_length
;
3108 int64_t new_l1_size
;
3111 if (prealloc
!= PREALLOC_MODE_OFF
&& prealloc
!= PREALLOC_MODE_METADATA
&&
3112 prealloc
!= PREALLOC_MODE_FALLOC
&& prealloc
!= PREALLOC_MODE_FULL
)
3114 error_setg(errp
, "Unsupported preallocation mode '%s'",
3115 PreallocMode_str(prealloc
));
3120 error_setg(errp
, "The new size must be a multiple of 512");
3124 /* cannot proceed if image has snapshots */
3125 if (s
->nb_snapshots
) {
3126 error_setg(errp
, "Can't resize an image which has snapshots");
3130 /* cannot proceed if image has bitmaps */
3131 if (s
->nb_bitmaps
) {
3132 /* TODO: resize bitmaps in the image */
3133 error_setg(errp
, "Can't resize an image which has bitmaps");
3137 old_length
= bs
->total_sectors
* 512;
3138 new_l1_size
= size_to_l1(s
, offset
);
3140 if (offset
< old_length
) {
3141 int64_t last_cluster
, old_file_size
;
3142 if (prealloc
!= PREALLOC_MODE_OFF
) {
3144 "Preallocation can't be used for shrinking an image");
3148 ret
= qcow2_cluster_discard(bs
, ROUND_UP(offset
, s
->cluster_size
),
3149 old_length
- ROUND_UP(offset
,
3151 QCOW2_DISCARD_ALWAYS
, true);
3153 error_setg_errno(errp
, -ret
, "Failed to discard cropped clusters");
3157 ret
= qcow2_shrink_l1_table(bs
, new_l1_size
);
3159 error_setg_errno(errp
, -ret
,
3160 "Failed to reduce the number of L2 tables");
3164 ret
= qcow2_shrink_reftable(bs
);
3166 error_setg_errno(errp
, -ret
,
3167 "Failed to discard unused refblocks");
3171 old_file_size
= bdrv_getlength(bs
->file
->bs
);
3172 if (old_file_size
< 0) {
3173 error_setg_errno(errp
, -old_file_size
,
3174 "Failed to inquire current file length");
3175 return old_file_size
;
3177 last_cluster
= qcow2_get_last_cluster(bs
, old_file_size
);
3178 if (last_cluster
< 0) {
3179 error_setg_errno(errp
, -last_cluster
,
3180 "Failed to find the last cluster");
3181 return last_cluster
;
3183 if ((last_cluster
+ 1) * s
->cluster_size
< old_file_size
) {
3184 Error
*local_err
= NULL
;
3186 bdrv_truncate(bs
->file
, (last_cluster
+ 1) * s
->cluster_size
,
3187 PREALLOC_MODE_OFF
, &local_err
);
3189 warn_reportf_err(local_err
,
3190 "Failed to truncate the tail of the image: ");
3194 ret
= qcow2_grow_l1_table(bs
, new_l1_size
, true);
3196 error_setg_errno(errp
, -ret
, "Failed to grow the L1 table");
3202 case PREALLOC_MODE_OFF
:
3205 case PREALLOC_MODE_METADATA
:
3206 ret
= preallocate(bs
, old_length
, offset
);
3208 error_setg_errno(errp
, -ret
, "Preallocation failed");
3213 case PREALLOC_MODE_FALLOC
:
3214 case PREALLOC_MODE_FULL
:
3216 int64_t allocation_start
, host_offset
, guest_offset
;
3217 int64_t clusters_allocated
;
3218 int64_t old_file_size
, new_file_size
;
3219 uint64_t nb_new_data_clusters
, nb_new_l2_tables
;
3221 old_file_size
= bdrv_getlength(bs
->file
->bs
);
3222 if (old_file_size
< 0) {
3223 error_setg_errno(errp
, -old_file_size
,
3224 "Failed to inquire current file length");
3225 return old_file_size
;
3227 old_file_size
= ROUND_UP(old_file_size
, s
->cluster_size
);
3229 nb_new_data_clusters
= DIV_ROUND_UP(offset
- old_length
,
3232 /* This is an overestimation; we will not actually allocate space for
3233 * these in the file but just make sure the new refcount structures are
3234 * able to cover them so we will not have to allocate new refblocks
3235 * while entering the data blocks in the potentially new L2 tables.
3236 * (We do not actually care where the L2 tables are placed. Maybe they
3237 * are already allocated or they can be placed somewhere before
3238 * @old_file_size. It does not matter because they will be fully
3239 * allocated automatically, so they do not need to be covered by the
3240 * preallocation. All that matters is that we will not have to allocate
3241 * new refcount structures for them.) */
3242 nb_new_l2_tables
= DIV_ROUND_UP(nb_new_data_clusters
,
3243 s
->cluster_size
/ sizeof(uint64_t));
3244 /* The cluster range may not be aligned to L2 boundaries, so add one L2
3245 * table for a potential head/tail */
3248 allocation_start
= qcow2_refcount_area(bs
, old_file_size
,
3249 nb_new_data_clusters
+
3252 if (allocation_start
< 0) {
3253 error_setg_errno(errp
, -allocation_start
,
3254 "Failed to resize refcount structures");
3255 return allocation_start
;
3258 clusters_allocated
= qcow2_alloc_clusters_at(bs
, allocation_start
,
3259 nb_new_data_clusters
);
3260 if (clusters_allocated
< 0) {
3261 error_setg_errno(errp
, -clusters_allocated
,
3262 "Failed to allocate data clusters");
3263 return -clusters_allocated
;
3266 assert(clusters_allocated
== nb_new_data_clusters
);
3268 /* Allocate the data area */
3269 new_file_size
= allocation_start
+
3270 nb_new_data_clusters
* s
->cluster_size
;
3271 ret
= bdrv_truncate(bs
->file
, new_file_size
, prealloc
, errp
);
3273 error_prepend(errp
, "Failed to resize underlying file: ");
3274 qcow2_free_clusters(bs
, allocation_start
,
3275 nb_new_data_clusters
* s
->cluster_size
,
3276 QCOW2_DISCARD_OTHER
);
3280 /* Create the necessary L2 entries */
3281 host_offset
= allocation_start
;
3282 guest_offset
= old_length
;
3283 while (nb_new_data_clusters
) {
3284 int64_t nb_clusters
= MIN(
3285 nb_new_data_clusters
,
3286 s
->l2_slice_size
- offset_to_l2_slice_index(s
, guest_offset
));
3287 QCowL2Meta allocation
= {
3288 .offset
= guest_offset
,
3289 .alloc_offset
= host_offset
,
3290 .nb_clusters
= nb_clusters
,
3292 qemu_co_queue_init(&allocation
.dependent_requests
);
3294 ret
= qcow2_alloc_cluster_link_l2(bs
, &allocation
);
3296 error_setg_errno(errp
, -ret
, "Failed to update L2 tables");
3297 qcow2_free_clusters(bs
, host_offset
,
3298 nb_new_data_clusters
* s
->cluster_size
,
3299 QCOW2_DISCARD_OTHER
);
3303 guest_offset
+= nb_clusters
* s
->cluster_size
;
3304 host_offset
+= nb_clusters
* s
->cluster_size
;
3305 nb_new_data_clusters
-= nb_clusters
;
3311 g_assert_not_reached();
3314 if (prealloc
!= PREALLOC_MODE_OFF
) {
3315 /* Flush metadata before actually changing the image size */
3316 ret
= bdrv_flush(bs
);
3318 error_setg_errno(errp
, -ret
,
3319 "Failed to flush the preallocated area to disk");
3324 /* write updated header.size */
3325 offset
= cpu_to_be64(offset
);
3326 ret
= bdrv_pwrite_sync(bs
->file
, offsetof(QCowHeader
, size
),
3327 &offset
, sizeof(uint64_t));
3329 error_setg_errno(errp
, -ret
, "Failed to update the image size");
3333 s
->l1_vm_state_index
= new_l1_size
;
3337 /* XXX: put compressed sectors first, then all the cluster aligned
3338 tables to avoid losing bytes in alignment */
3339 static coroutine_fn
int
3340 qcow2_co_pwritev_compressed(BlockDriverState
*bs
, uint64_t offset
,
3341 uint64_t bytes
, QEMUIOVector
*qiov
)
3343 BDRVQcow2State
*s
= bs
->opaque
;
3344 QEMUIOVector hd_qiov
;
3348 uint8_t *buf
, *out_buf
;
3349 int64_t cluster_offset
;
3352 /* align end of file to a sector boundary to ease reading with
3353 sector based I/Os */
3354 cluster_offset
= bdrv_getlength(bs
->file
->bs
);
3355 if (cluster_offset
< 0) {
3356 return cluster_offset
;
3358 return bdrv_truncate(bs
->file
, cluster_offset
, PREALLOC_MODE_OFF
, NULL
);
3361 if (offset_into_cluster(s
, offset
)) {
3365 buf
= qemu_blockalign(bs
, s
->cluster_size
);
3366 if (bytes
!= s
->cluster_size
) {
3367 if (bytes
> s
->cluster_size
||
3368 offset
+ bytes
!= bs
->total_sectors
<< BDRV_SECTOR_BITS
)
3373 /* Zero-pad last write if image size is not cluster aligned */
3374 memset(buf
+ bytes
, 0, s
->cluster_size
- bytes
);
3376 qemu_iovec_to_buf(qiov
, 0, buf
, bytes
);
3378 out_buf
= g_malloc(s
->cluster_size
);
3380 /* best compression, small window, no zlib header */
3381 memset(&strm
, 0, sizeof(strm
));
3382 ret
= deflateInit2(&strm
, Z_DEFAULT_COMPRESSION
,
3384 9, Z_DEFAULT_STRATEGY
);
3390 strm
.avail_in
= s
->cluster_size
;
3391 strm
.next_in
= (uint8_t *)buf
;
3392 strm
.avail_out
= s
->cluster_size
;
3393 strm
.next_out
= out_buf
;
3395 ret
= deflate(&strm
, Z_FINISH
);
3396 if (ret
!= Z_STREAM_END
&& ret
!= Z_OK
) {
3401 out_len
= strm
.next_out
- out_buf
;
3405 if (ret
!= Z_STREAM_END
|| out_len
>= s
->cluster_size
) {
3406 /* could not compress: write normal cluster */
3407 ret
= qcow2_co_pwritev(bs
, offset
, bytes
, qiov
, 0);
3414 qemu_co_mutex_lock(&s
->lock
);
3416 qcow2_alloc_compressed_cluster_offset(bs
, offset
, out_len
);
3417 if (!cluster_offset
) {
3418 qemu_co_mutex_unlock(&s
->lock
);
3422 cluster_offset
&= s
->cluster_offset_mask
;
3424 ret
= qcow2_pre_write_overlap_check(bs
, 0, cluster_offset
, out_len
);
3425 qemu_co_mutex_unlock(&s
->lock
);
3430 iov
= (struct iovec
) {
3431 .iov_base
= out_buf
,
3434 qemu_iovec_init_external(&hd_qiov
, &iov
, 1);
3436 BLKDBG_EVENT(bs
->file
, BLKDBG_WRITE_COMPRESSED
);
3437 ret
= bdrv_co_pwritev(bs
->file
, cluster_offset
, out_len
, &hd_qiov
, 0);
3449 static int make_completely_empty(BlockDriverState
*bs
)
3451 BDRVQcow2State
*s
= bs
->opaque
;
3452 Error
*local_err
= NULL
;
3453 int ret
, l1_clusters
;
3455 uint64_t *new_reftable
= NULL
;
3456 uint64_t rt_entry
, l1_size2
;
3459 uint64_t reftable_offset
;
3460 uint32_t reftable_clusters
;
3461 } QEMU_PACKED l1_ofs_rt_ofs_cls
;
3463 ret
= qcow2_cache_empty(bs
, s
->l2_table_cache
);
3468 ret
= qcow2_cache_empty(bs
, s
->refcount_block_cache
);
3473 /* Refcounts will be broken utterly */
3474 ret
= qcow2_mark_dirty(bs
);
3479 BLKDBG_EVENT(bs
->file
, BLKDBG_L1_UPDATE
);
3481 l1_clusters
= DIV_ROUND_UP(s
->l1_size
, s
->cluster_size
/ sizeof(uint64_t));
3482 l1_size2
= (uint64_t)s
->l1_size
* sizeof(uint64_t);
3484 /* After this call, neither the in-memory nor the on-disk refcount
3485 * information accurately describe the actual references */
3487 ret
= bdrv_pwrite_zeroes(bs
->file
, s
->l1_table_offset
,
3488 l1_clusters
* s
->cluster_size
, 0);
3490 goto fail_broken_refcounts
;
3492 memset(s
->l1_table
, 0, l1_size2
);
3494 BLKDBG_EVENT(bs
->file
, BLKDBG_EMPTY_IMAGE_PREPARE
);
3496 /* Overwrite enough clusters at the beginning of the sectors to place
3497 * the refcount table, a refcount block and the L1 table in; this may
3498 * overwrite parts of the existing refcount and L1 table, which is not
3499 * an issue because the dirty flag is set, complete data loss is in fact
3500 * desired and partial data loss is consequently fine as well */
3501 ret
= bdrv_pwrite_zeroes(bs
->file
, s
->cluster_size
,
3502 (2 + l1_clusters
) * s
->cluster_size
, 0);
3503 /* This call (even if it failed overall) may have overwritten on-disk
3504 * refcount structures; in that case, the in-memory refcount information
3505 * will probably differ from the on-disk information which makes the BDS
3508 goto fail_broken_refcounts
;
3511 BLKDBG_EVENT(bs
->file
, BLKDBG_L1_UPDATE
);
3512 BLKDBG_EVENT(bs
->file
, BLKDBG_REFTABLE_UPDATE
);
3514 /* "Create" an empty reftable (one cluster) directly after the image
3515 * header and an empty L1 table three clusters after the image header;
3516 * the cluster between those two will be used as the first refblock */
3517 l1_ofs_rt_ofs_cls
.l1_offset
= cpu_to_be64(3 * s
->cluster_size
);
3518 l1_ofs_rt_ofs_cls
.reftable_offset
= cpu_to_be64(s
->cluster_size
);
3519 l1_ofs_rt_ofs_cls
.reftable_clusters
= cpu_to_be32(1);
3520 ret
= bdrv_pwrite_sync(bs
->file
, offsetof(QCowHeader
, l1_table_offset
),
3521 &l1_ofs_rt_ofs_cls
, sizeof(l1_ofs_rt_ofs_cls
));
3523 goto fail_broken_refcounts
;
3526 s
->l1_table_offset
= 3 * s
->cluster_size
;
3528 new_reftable
= g_try_new0(uint64_t, s
->cluster_size
/ sizeof(uint64_t));
3529 if (!new_reftable
) {
3531 goto fail_broken_refcounts
;
3534 s
->refcount_table_offset
= s
->cluster_size
;
3535 s
->refcount_table_size
= s
->cluster_size
/ sizeof(uint64_t);
3536 s
->max_refcount_table_index
= 0;
3538 g_free(s
->refcount_table
);
3539 s
->refcount_table
= new_reftable
;
3540 new_reftable
= NULL
;
3542 /* Now the in-memory refcount information again corresponds to the on-disk
3543 * information (reftable is empty and no refblocks (the refblock cache is
3544 * empty)); however, this means some clusters (e.g. the image header) are
3545 * referenced, but not refcounted, but the normal qcow2 code assumes that
3546 * the in-memory information is always correct */
3548 BLKDBG_EVENT(bs
->file
, BLKDBG_REFBLOCK_ALLOC
);
3550 /* Enter the first refblock into the reftable */
3551 rt_entry
= cpu_to_be64(2 * s
->cluster_size
);
3552 ret
= bdrv_pwrite_sync(bs
->file
, s
->cluster_size
,
3553 &rt_entry
, sizeof(rt_entry
));
3555 goto fail_broken_refcounts
;
3557 s
->refcount_table
[0] = 2 * s
->cluster_size
;
3559 s
->free_cluster_index
= 0;
3560 assert(3 + l1_clusters
<= s
->refcount_block_size
);
3561 offset
= qcow2_alloc_clusters(bs
, 3 * s
->cluster_size
+ l1_size2
);
3564 goto fail_broken_refcounts
;
3565 } else if (offset
> 0) {
3566 error_report("First cluster in emptied image is in use");
3570 /* Now finally the in-memory information corresponds to the on-disk
3571 * structures and is correct */
3572 ret
= qcow2_mark_clean(bs
);
3577 ret
= bdrv_truncate(bs
->file
, (3 + l1_clusters
) * s
->cluster_size
,
3578 PREALLOC_MODE_OFF
, &local_err
);
3580 error_report_err(local_err
);
3586 fail_broken_refcounts
:
3587 /* The BDS is unusable at this point. If we wanted to make it usable, we
3588 * would have to call qcow2_refcount_close(), qcow2_refcount_init(),
3589 * qcow2_check_refcounts(), qcow2_refcount_close() and qcow2_refcount_init()
3590 * again. However, because the functions which could have caused this error
3591 * path to be taken are used by those functions as well, it's very likely
3592 * that that sequence will fail as well. Therefore, just eject the BDS. */
3596 g_free(new_reftable
);
3600 static int qcow2_make_empty(BlockDriverState
*bs
)
3602 BDRVQcow2State
*s
= bs
->opaque
;
3603 uint64_t offset
, end_offset
;
3604 int step
= QEMU_ALIGN_DOWN(INT_MAX
, s
->cluster_size
);
3605 int l1_clusters
, ret
= 0;
3607 l1_clusters
= DIV_ROUND_UP(s
->l1_size
, s
->cluster_size
/ sizeof(uint64_t));
3609 if (s
->qcow_version
>= 3 && !s
->snapshots
&& !s
->nb_bitmaps
&&
3610 3 + l1_clusters
<= s
->refcount_block_size
&&
3611 s
->crypt_method_header
!= QCOW_CRYPT_LUKS
) {
3612 /* The following function only works for qcow2 v3 images (it
3613 * requires the dirty flag) and only as long as there are no
3614 * features that reserve extra clusters (such as snapshots,
3615 * LUKS header, or persistent bitmaps), because it completely
3616 * empties the image. Furthermore, the L1 table and three
3617 * additional clusters (image header, refcount table, one
3618 * refcount block) have to fit inside one refcount block. */
3619 return make_completely_empty(bs
);
3622 /* This fallback code simply discards every active cluster; this is slow,
3623 * but works in all cases */
3624 end_offset
= bs
->total_sectors
* BDRV_SECTOR_SIZE
;
3625 for (offset
= 0; offset
< end_offset
; offset
+= step
) {
3626 /* As this function is generally used after committing an external
3627 * snapshot, QCOW2_DISCARD_SNAPSHOT seems appropriate. Also, the
3628 * default action for this kind of discard is to pass the discard,
3629 * which will ideally result in an actually smaller image file, as
3630 * is probably desired. */
3631 ret
= qcow2_cluster_discard(bs
, offset
, MIN(step
, end_offset
- offset
),
3632 QCOW2_DISCARD_SNAPSHOT
, true);
3641 static coroutine_fn
int qcow2_co_flush_to_os(BlockDriverState
*bs
)
3643 BDRVQcow2State
*s
= bs
->opaque
;
3646 qemu_co_mutex_lock(&s
->lock
);
3647 ret
= qcow2_cache_write(bs
, s
->l2_table_cache
);
3649 qemu_co_mutex_unlock(&s
->lock
);
3653 if (qcow2_need_accurate_refcounts(s
)) {
3654 ret
= qcow2_cache_write(bs
, s
->refcount_block_cache
);
3656 qemu_co_mutex_unlock(&s
->lock
);
3660 qemu_co_mutex_unlock(&s
->lock
);
3665 static BlockMeasureInfo
*qcow2_measure(QemuOpts
*opts
, BlockDriverState
*in_bs
,
3668 Error
*local_err
= NULL
;
3669 BlockMeasureInfo
*info
;
3670 uint64_t required
= 0; /* bytes that contribute to required size */
3671 uint64_t virtual_size
; /* disk size as seen by guest */
3672 uint64_t refcount_bits
;
3674 size_t cluster_size
;
3677 PreallocMode prealloc
;
3678 bool has_backing_file
;
3680 /* Parse image creation options */
3681 cluster_size
= qcow2_opt_get_cluster_size_del(opts
, &local_err
);
3686 version
= qcow2_opt_get_version_del(opts
, &local_err
);
3691 refcount_bits
= qcow2_opt_get_refcount_bits_del(opts
, version
, &local_err
);
3696 optstr
= qemu_opt_get_del(opts
, BLOCK_OPT_PREALLOC
);
3697 prealloc
= qapi_enum_parse(&PreallocMode_lookup
, optstr
,
3698 PREALLOC_MODE_OFF
, &local_err
);
3704 optstr
= qemu_opt_get_del(opts
, BLOCK_OPT_BACKING_FILE
);
3705 has_backing_file
= !!optstr
;
3708 virtual_size
= align_offset(qemu_opt_get_size_del(opts
, BLOCK_OPT_SIZE
, 0),
3711 /* Check that virtual disk size is valid */
3712 l2_tables
= DIV_ROUND_UP(virtual_size
/ cluster_size
,
3713 cluster_size
/ sizeof(uint64_t));
3714 if (l2_tables
* sizeof(uint64_t) > QCOW_MAX_L1_SIZE
) {
3715 error_setg(&local_err
, "The image size is too large "
3716 "(try using a larger cluster size)");
3720 /* Account for input image */
3722 int64_t ssize
= bdrv_getlength(in_bs
);
3724 error_setg_errno(&local_err
, -ssize
,
3725 "Unable to get image virtual_size");
3729 virtual_size
= align_offset(ssize
, cluster_size
);
3731 if (has_backing_file
) {
3732 /* We don't how much of the backing chain is shared by the input
3733 * image and the new image file. In the worst case the new image's
3734 * backing file has nothing in common with the input image. Be
3735 * conservative and assume all clusters need to be written.
3737 required
= virtual_size
;
3742 for (offset
= 0; offset
< ssize
; offset
+= pnum
) {
3745 ret
= bdrv_block_status_above(in_bs
, NULL
, offset
,
3746 ssize
- offset
, &pnum
, NULL
,
3749 error_setg_errno(&local_err
, -ret
,
3750 "Unable to get block status");
3754 if (ret
& BDRV_BLOCK_ZERO
) {
3755 /* Skip zero regions (safe with no backing file) */
3756 } else if ((ret
& (BDRV_BLOCK_DATA
| BDRV_BLOCK_ALLOCATED
)) ==
3757 (BDRV_BLOCK_DATA
| BDRV_BLOCK_ALLOCATED
)) {
3758 /* Extend pnum to end of cluster for next iteration */
3759 pnum
= ROUND_UP(offset
+ pnum
, cluster_size
) - offset
;
3761 /* Count clusters we've seen */
3762 required
+= offset
% cluster_size
+ pnum
;
3768 /* Take into account preallocation. Nothing special is needed for
3769 * PREALLOC_MODE_METADATA since metadata is always counted.
3771 if (prealloc
== PREALLOC_MODE_FULL
|| prealloc
== PREALLOC_MODE_FALLOC
) {
3772 required
= virtual_size
;
3775 info
= g_new(BlockMeasureInfo
, 1);
3776 info
->fully_allocated
=
3777 qcow2_calc_prealloc_size(virtual_size
, cluster_size
,
3778 ctz32(refcount_bits
));
3780 /* Remove data clusters that are not required. This overestimates the
3781 * required size because metadata needed for the fully allocated file is
3784 info
->required
= info
->fully_allocated
- virtual_size
+ required
;
3788 error_propagate(errp
, local_err
);
3792 static int qcow2_get_info(BlockDriverState
*bs
, BlockDriverInfo
*bdi
)
3794 BDRVQcow2State
*s
= bs
->opaque
;
3795 bdi
->unallocated_blocks_are_zero
= true;
3796 bdi
->cluster_size
= s
->cluster_size
;
3797 bdi
->vm_state_offset
= qcow2_vm_state_offset(s
);
3801 static ImageInfoSpecific
*qcow2_get_specific_info(BlockDriverState
*bs
)
3803 BDRVQcow2State
*s
= bs
->opaque
;
3804 ImageInfoSpecific
*spec_info
;
3805 QCryptoBlockInfo
*encrypt_info
= NULL
;
3807 if (s
->crypto
!= NULL
) {
3808 encrypt_info
= qcrypto_block_get_info(s
->crypto
, &error_abort
);
3811 spec_info
= g_new(ImageInfoSpecific
, 1);
3812 *spec_info
= (ImageInfoSpecific
){
3813 .type
= IMAGE_INFO_SPECIFIC_KIND_QCOW2
,
3814 .u
.qcow2
.data
= g_new(ImageInfoSpecificQCow2
, 1),
3816 if (s
->qcow_version
== 2) {
3817 *spec_info
->u
.qcow2
.data
= (ImageInfoSpecificQCow2
){
3818 .compat
= g_strdup("0.10"),
3819 .refcount_bits
= s
->refcount_bits
,
3821 } else if (s
->qcow_version
== 3) {
3822 *spec_info
->u
.qcow2
.data
= (ImageInfoSpecificQCow2
){
3823 .compat
= g_strdup("1.1"),
3824 .lazy_refcounts
= s
->compatible_features
&
3825 QCOW2_COMPAT_LAZY_REFCOUNTS
,
3826 .has_lazy_refcounts
= true,
3827 .corrupt
= s
->incompatible_features
&
3828 QCOW2_INCOMPAT_CORRUPT
,
3829 .has_corrupt
= true,
3830 .refcount_bits
= s
->refcount_bits
,
3833 /* if this assertion fails, this probably means a new version was
3834 * added without having it covered here */
3839 ImageInfoSpecificQCow2Encryption
*qencrypt
=
3840 g_new(ImageInfoSpecificQCow2Encryption
, 1);
3841 switch (encrypt_info
->format
) {
3842 case Q_CRYPTO_BLOCK_FORMAT_QCOW
:
3843 qencrypt
->format
= BLOCKDEV_QCOW2_ENCRYPTION_FORMAT_AES
;
3844 qencrypt
->u
.aes
= encrypt_info
->u
.qcow
;
3846 case Q_CRYPTO_BLOCK_FORMAT_LUKS
:
3847 qencrypt
->format
= BLOCKDEV_QCOW2_ENCRYPTION_FORMAT_LUKS
;
3848 qencrypt
->u
.luks
= encrypt_info
->u
.luks
;
3853 /* Since we did shallow copy above, erase any pointers
3854 * in the original info */
3855 memset(&encrypt_info
->u
, 0, sizeof(encrypt_info
->u
));
3856 qapi_free_QCryptoBlockInfo(encrypt_info
);
3858 spec_info
->u
.qcow2
.data
->has_encrypt
= true;
3859 spec_info
->u
.qcow2
.data
->encrypt
= qencrypt
;
3865 static int qcow2_save_vmstate(BlockDriverState
*bs
, QEMUIOVector
*qiov
,
3868 BDRVQcow2State
*s
= bs
->opaque
;
3870 BLKDBG_EVENT(bs
->file
, BLKDBG_VMSTATE_SAVE
);
3871 return bs
->drv
->bdrv_co_pwritev(bs
, qcow2_vm_state_offset(s
) + pos
,
3872 qiov
->size
, qiov
, 0);
3875 static int qcow2_load_vmstate(BlockDriverState
*bs
, QEMUIOVector
*qiov
,
3878 BDRVQcow2State
*s
= bs
->opaque
;
3880 BLKDBG_EVENT(bs
->file
, BLKDBG_VMSTATE_LOAD
);
3881 return bs
->drv
->bdrv_co_preadv(bs
, qcow2_vm_state_offset(s
) + pos
,
3882 qiov
->size
, qiov
, 0);
3886 * Downgrades an image's version. To achieve this, any incompatible features
3887 * have to be removed.
3889 static int qcow2_downgrade(BlockDriverState
*bs
, int target_version
,
3890 BlockDriverAmendStatusCB
*status_cb
, void *cb_opaque
)
3892 BDRVQcow2State
*s
= bs
->opaque
;
3893 int current_version
= s
->qcow_version
;
3896 if (target_version
== current_version
) {
3898 } else if (target_version
> current_version
) {
3900 } else if (target_version
!= 2) {
3904 if (s
->refcount_order
!= 4) {
3905 error_report("compat=0.10 requires refcount_bits=16");
3909 /* clear incompatible features */
3910 if (s
->incompatible_features
& QCOW2_INCOMPAT_DIRTY
) {
3911 ret
= qcow2_mark_clean(bs
);
3917 /* with QCOW2_INCOMPAT_CORRUPT, it is pretty much impossible to get here in
3918 * the first place; if that happens nonetheless, returning -ENOTSUP is the
3919 * best thing to do anyway */
3921 if (s
->incompatible_features
) {
3925 /* since we can ignore compatible features, we can set them to 0 as well */
3926 s
->compatible_features
= 0;
3927 /* if lazy refcounts have been used, they have already been fixed through
3928 * clearing the dirty flag */
3930 /* clearing autoclear features is trivial */
3931 s
->autoclear_features
= 0;
3933 ret
= qcow2_expand_zero_clusters(bs
, status_cb
, cb_opaque
);
3938 s
->qcow_version
= target_version
;
3939 ret
= qcow2_update_header(bs
);
3941 s
->qcow_version
= current_version
;
3947 typedef enum Qcow2AmendOperation
{
3948 /* This is the value Qcow2AmendHelperCBInfo::last_operation will be
3949 * statically initialized to so that the helper CB can discern the first
3950 * invocation from an operation change */
3951 QCOW2_NO_OPERATION
= 0,
3953 QCOW2_CHANGING_REFCOUNT_ORDER
,
3955 } Qcow2AmendOperation
;
3957 typedef struct Qcow2AmendHelperCBInfo
{
3958 /* The code coordinating the amend operations should only modify
3959 * these four fields; the rest will be managed by the CB */
3960 BlockDriverAmendStatusCB
*original_status_cb
;
3961 void *original_cb_opaque
;
3963 Qcow2AmendOperation current_operation
;
3965 /* Total number of operations to perform (only set once) */
3966 int total_operations
;
3968 /* The following fields are managed by the CB */
3970 /* Number of operations completed */
3971 int operations_completed
;
3973 /* Cumulative offset of all completed operations */
3974 int64_t offset_completed
;
3976 Qcow2AmendOperation last_operation
;
3977 int64_t last_work_size
;
3978 } Qcow2AmendHelperCBInfo
;
3980 static void qcow2_amend_helper_cb(BlockDriverState
*bs
,
3981 int64_t operation_offset
,
3982 int64_t operation_work_size
, void *opaque
)
3984 Qcow2AmendHelperCBInfo
*info
= opaque
;
3985 int64_t current_work_size
;
3986 int64_t projected_work_size
;
3988 if (info
->current_operation
!= info
->last_operation
) {
3989 if (info
->last_operation
!= QCOW2_NO_OPERATION
) {
3990 info
->offset_completed
+= info
->last_work_size
;
3991 info
->operations_completed
++;
3994 info
->last_operation
= info
->current_operation
;
3997 assert(info
->total_operations
> 0);
3998 assert(info
->operations_completed
< info
->total_operations
);
4000 info
->last_work_size
= operation_work_size
;
4002 current_work_size
= info
->offset_completed
+ operation_work_size
;
4004 /* current_work_size is the total work size for (operations_completed + 1)
4005 * operations (which includes this one), so multiply it by the number of
4006 * operations not covered and divide it by the number of operations
4007 * covered to get a projection for the operations not covered */
4008 projected_work_size
= current_work_size
* (info
->total_operations
-
4009 info
->operations_completed
- 1)
4010 / (info
->operations_completed
+ 1);
4012 info
->original_status_cb(bs
, info
->offset_completed
+ operation_offset
,
4013 current_work_size
+ projected_work_size
,
4014 info
->original_cb_opaque
);
4017 static int qcow2_amend_options(BlockDriverState
*bs
, QemuOpts
*opts
,
4018 BlockDriverAmendStatusCB
*status_cb
,
4021 BDRVQcow2State
*s
= bs
->opaque
;
4022 int old_version
= s
->qcow_version
, new_version
= old_version
;
4023 uint64_t new_size
= 0;
4024 const char *backing_file
= NULL
, *backing_format
= NULL
;
4025 bool lazy_refcounts
= s
->use_lazy_refcounts
;
4026 const char *compat
= NULL
;
4027 uint64_t cluster_size
= s
->cluster_size
;
4030 int refcount_bits
= s
->refcount_bits
;
4031 Error
*local_err
= NULL
;
4033 QemuOptDesc
*desc
= opts
->list
->desc
;
4034 Qcow2AmendHelperCBInfo helper_cb_info
;
4036 while (desc
&& desc
->name
) {
4037 if (!qemu_opt_find(opts
, desc
->name
)) {
4038 /* only change explicitly defined options */
4043 if (!strcmp(desc
->name
, BLOCK_OPT_COMPAT_LEVEL
)) {
4044 compat
= qemu_opt_get(opts
, BLOCK_OPT_COMPAT_LEVEL
);
4046 /* preserve default */
4047 } else if (!strcmp(compat
, "0.10")) {
4049 } else if (!strcmp(compat
, "1.1")) {
4052 error_report("Unknown compatibility level %s", compat
);
4055 } else if (!strcmp(desc
->name
, BLOCK_OPT_PREALLOC
)) {
4056 error_report("Cannot change preallocation mode");
4058 } else if (!strcmp(desc
->name
, BLOCK_OPT_SIZE
)) {
4059 new_size
= qemu_opt_get_size(opts
, BLOCK_OPT_SIZE
, 0);
4060 } else if (!strcmp(desc
->name
, BLOCK_OPT_BACKING_FILE
)) {
4061 backing_file
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FILE
);
4062 } else if (!strcmp(desc
->name
, BLOCK_OPT_BACKING_FMT
)) {
4063 backing_format
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FMT
);
4064 } else if (!strcmp(desc
->name
, BLOCK_OPT_ENCRYPT
)) {
4065 encrypt
= qemu_opt_get_bool(opts
, BLOCK_OPT_ENCRYPT
,
4068 if (encrypt
!= !!s
->crypto
) {
4069 error_report("Changing the encryption flag is not supported");
4072 } else if (!strcmp(desc
->name
, BLOCK_OPT_ENCRYPT_FORMAT
)) {
4073 encformat
= qcow2_crypt_method_from_format(
4074 qemu_opt_get(opts
, BLOCK_OPT_ENCRYPT_FORMAT
));
4076 if (encformat
!= s
->crypt_method_header
) {
4077 error_report("Changing the encryption format is not supported");
4080 } else if (g_str_has_prefix(desc
->name
, "encrypt.")) {
4081 error_report("Changing the encryption parameters is not supported");
4083 } else if (!strcmp(desc
->name
, BLOCK_OPT_CLUSTER_SIZE
)) {
4084 cluster_size
= qemu_opt_get_size(opts
, BLOCK_OPT_CLUSTER_SIZE
,
4086 if (cluster_size
!= s
->cluster_size
) {
4087 error_report("Changing the cluster size is not supported");
4090 } else if (!strcmp(desc
->name
, BLOCK_OPT_LAZY_REFCOUNTS
)) {
4091 lazy_refcounts
= qemu_opt_get_bool(opts
, BLOCK_OPT_LAZY_REFCOUNTS
,
4093 } else if (!strcmp(desc
->name
, BLOCK_OPT_REFCOUNT_BITS
)) {
4094 refcount_bits
= qemu_opt_get_number(opts
, BLOCK_OPT_REFCOUNT_BITS
,
4097 if (refcount_bits
<= 0 || refcount_bits
> 64 ||
4098 !is_power_of_2(refcount_bits
))
4100 error_report("Refcount width must be a power of two and may "
4101 "not exceed 64 bits");
4105 /* if this point is reached, this probably means a new option was
4106 * added without having it covered here */
4113 helper_cb_info
= (Qcow2AmendHelperCBInfo
){
4114 .original_status_cb
= status_cb
,
4115 .original_cb_opaque
= cb_opaque
,
4116 .total_operations
= (new_version
< old_version
)
4117 + (s
->refcount_bits
!= refcount_bits
)
4120 /* Upgrade first (some features may require compat=1.1) */
4121 if (new_version
> old_version
) {
4122 s
->qcow_version
= new_version
;
4123 ret
= qcow2_update_header(bs
);
4125 s
->qcow_version
= old_version
;
4130 if (s
->refcount_bits
!= refcount_bits
) {
4131 int refcount_order
= ctz32(refcount_bits
);
4133 if (new_version
< 3 && refcount_bits
!= 16) {
4134 error_report("Different refcount widths than 16 bits require "
4135 "compatibility level 1.1 or above (use compat=1.1 or "
4140 helper_cb_info
.current_operation
= QCOW2_CHANGING_REFCOUNT_ORDER
;
4141 ret
= qcow2_change_refcount_order(bs
, refcount_order
,
4142 &qcow2_amend_helper_cb
,
4143 &helper_cb_info
, &local_err
);
4145 error_report_err(local_err
);
4150 if (backing_file
|| backing_format
) {
4151 ret
= qcow2_change_backing_file(bs
,
4152 backing_file
?: s
->image_backing_file
,
4153 backing_format
?: s
->image_backing_format
);
4159 if (s
->use_lazy_refcounts
!= lazy_refcounts
) {
4160 if (lazy_refcounts
) {
4161 if (new_version
< 3) {
4162 error_report("Lazy refcounts only supported with compatibility "
4163 "level 1.1 and above (use compat=1.1 or greater)");
4166 s
->compatible_features
|= QCOW2_COMPAT_LAZY_REFCOUNTS
;
4167 ret
= qcow2_update_header(bs
);
4169 s
->compatible_features
&= ~QCOW2_COMPAT_LAZY_REFCOUNTS
;
4172 s
->use_lazy_refcounts
= true;
4174 /* make image clean first */
4175 ret
= qcow2_mark_clean(bs
);
4179 /* now disallow lazy refcounts */
4180 s
->compatible_features
&= ~QCOW2_COMPAT_LAZY_REFCOUNTS
;
4181 ret
= qcow2_update_header(bs
);
4183 s
->compatible_features
|= QCOW2_COMPAT_LAZY_REFCOUNTS
;
4186 s
->use_lazy_refcounts
= false;
4191 BlockBackend
*blk
= blk_new(BLK_PERM_RESIZE
, BLK_PERM_ALL
);
4192 ret
= blk_insert_bs(blk
, bs
, &local_err
);
4194 error_report_err(local_err
);
4199 ret
= blk_truncate(blk
, new_size
, PREALLOC_MODE_OFF
, &local_err
);
4202 error_report_err(local_err
);
4207 /* Downgrade last (so unsupported features can be removed before) */
4208 if (new_version
< old_version
) {
4209 helper_cb_info
.current_operation
= QCOW2_DOWNGRADING
;
4210 ret
= qcow2_downgrade(bs
, new_version
, &qcow2_amend_helper_cb
,
4221 * If offset or size are negative, respectively, they will not be included in
4222 * the BLOCK_IMAGE_CORRUPTED event emitted.
4223 * fatal will be ignored for read-only BDS; corruptions found there will always
4224 * be considered non-fatal.
4226 void qcow2_signal_corruption(BlockDriverState
*bs
, bool fatal
, int64_t offset
,
4227 int64_t size
, const char *message_format
, ...)
4229 BDRVQcow2State
*s
= bs
->opaque
;
4230 const char *node_name
;
4234 fatal
= fatal
&& !bs
->read_only
;
4236 if (s
->signaled_corruption
&&
4237 (!fatal
|| (s
->incompatible_features
& QCOW2_INCOMPAT_CORRUPT
)))
4242 va_start(ap
, message_format
);
4243 message
= g_strdup_vprintf(message_format
, ap
);
4247 fprintf(stderr
, "qcow2: Marking image as corrupt: %s; further "
4248 "corruption events will be suppressed\n", message
);
4250 fprintf(stderr
, "qcow2: Image is corrupt: %s; further non-fatal "
4251 "corruption events will be suppressed\n", message
);
4254 node_name
= bdrv_get_node_name(bs
);
4255 qapi_event_send_block_image_corrupted(bdrv_get_device_name(bs
),
4256 *node_name
!= '\0', node_name
,
4257 message
, offset
>= 0, offset
,
4259 fatal
, &error_abort
);
4263 qcow2_mark_corrupt(bs
);
4264 bs
->drv
= NULL
; /* make BDS unusable */
4267 s
->signaled_corruption
= true;
4270 static QemuOptsList qcow2_create_opts
= {
4271 .name
= "qcow2-create-opts",
4272 .head
= QTAILQ_HEAD_INITIALIZER(qcow2_create_opts
.head
),
4275 .name
= BLOCK_OPT_SIZE
,
4276 .type
= QEMU_OPT_SIZE
,
4277 .help
= "Virtual disk size"
4280 .name
= BLOCK_OPT_COMPAT_LEVEL
,
4281 .type
= QEMU_OPT_STRING
,
4282 .help
= "Compatibility level (0.10 or 1.1)"
4285 .name
= BLOCK_OPT_BACKING_FILE
,
4286 .type
= QEMU_OPT_STRING
,
4287 .help
= "File name of a base image"
4290 .name
= BLOCK_OPT_BACKING_FMT
,
4291 .type
= QEMU_OPT_STRING
,
4292 .help
= "Image format of the base image"
4295 .name
= BLOCK_OPT_ENCRYPT
,
4296 .type
= QEMU_OPT_BOOL
,
4297 .help
= "Encrypt the image with format 'aes'. (Deprecated "
4298 "in favor of " BLOCK_OPT_ENCRYPT_FORMAT
"=aes)",
4301 .name
= BLOCK_OPT_ENCRYPT_FORMAT
,
4302 .type
= QEMU_OPT_STRING
,
4303 .help
= "Encrypt the image, format choices: 'aes', 'luks'",
4305 BLOCK_CRYPTO_OPT_DEF_KEY_SECRET("encrypt.",
4306 "ID of secret providing qcow AES key or LUKS passphrase"),
4307 BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_ALG("encrypt."),
4308 BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_MODE("encrypt."),
4309 BLOCK_CRYPTO_OPT_DEF_LUKS_IVGEN_ALG("encrypt."),
4310 BLOCK_CRYPTO_OPT_DEF_LUKS_IVGEN_HASH_ALG("encrypt."),
4311 BLOCK_CRYPTO_OPT_DEF_LUKS_HASH_ALG("encrypt."),
4312 BLOCK_CRYPTO_OPT_DEF_LUKS_ITER_TIME("encrypt."),
4314 .name
= BLOCK_OPT_CLUSTER_SIZE
,
4315 .type
= QEMU_OPT_SIZE
,
4316 .help
= "qcow2 cluster size",
4317 .def_value_str
= stringify(DEFAULT_CLUSTER_SIZE
)
4320 .name
= BLOCK_OPT_PREALLOC
,
4321 .type
= QEMU_OPT_STRING
,
4322 .help
= "Preallocation mode (allowed values: off, metadata, "
4326 .name
= BLOCK_OPT_LAZY_REFCOUNTS
,
4327 .type
= QEMU_OPT_BOOL
,
4328 .help
= "Postpone refcount updates",
4329 .def_value_str
= "off"
4332 .name
= BLOCK_OPT_REFCOUNT_BITS
,
4333 .type
= QEMU_OPT_NUMBER
,
4334 .help
= "Width of a reference count entry in bits",
4335 .def_value_str
= "16"
4337 { /* end of list */ }
4341 BlockDriver bdrv_qcow2
= {
4342 .format_name
= "qcow2",
4343 .instance_size
= sizeof(BDRVQcow2State
),
4344 .bdrv_probe
= qcow2_probe
,
4345 .bdrv_open
= qcow2_open
,
4346 .bdrv_close
= qcow2_close
,
4347 .bdrv_reopen_prepare
= qcow2_reopen_prepare
,
4348 .bdrv_reopen_commit
= qcow2_reopen_commit
,
4349 .bdrv_reopen_abort
= qcow2_reopen_abort
,
4350 .bdrv_join_options
= qcow2_join_options
,
4351 .bdrv_child_perm
= bdrv_format_default_perms
,
4352 .bdrv_create
= qcow2_create
,
4353 .bdrv_has_zero_init
= bdrv_has_zero_init_1
,
4354 .bdrv_co_get_block_status
= qcow2_co_get_block_status
,
4356 .bdrv_co_preadv
= qcow2_co_preadv
,
4357 .bdrv_co_pwritev
= qcow2_co_pwritev
,
4358 .bdrv_co_flush_to_os
= qcow2_co_flush_to_os
,
4360 .bdrv_co_pwrite_zeroes
= qcow2_co_pwrite_zeroes
,
4361 .bdrv_co_pdiscard
= qcow2_co_pdiscard
,
4362 .bdrv_truncate
= qcow2_truncate
,
4363 .bdrv_co_pwritev_compressed
= qcow2_co_pwritev_compressed
,
4364 .bdrv_make_empty
= qcow2_make_empty
,
4366 .bdrv_snapshot_create
= qcow2_snapshot_create
,
4367 .bdrv_snapshot_goto
= qcow2_snapshot_goto
,
4368 .bdrv_snapshot_delete
= qcow2_snapshot_delete
,
4369 .bdrv_snapshot_list
= qcow2_snapshot_list
,
4370 .bdrv_snapshot_load_tmp
= qcow2_snapshot_load_tmp
,
4371 .bdrv_measure
= qcow2_measure
,
4372 .bdrv_get_info
= qcow2_get_info
,
4373 .bdrv_get_specific_info
= qcow2_get_specific_info
,
4375 .bdrv_save_vmstate
= qcow2_save_vmstate
,
4376 .bdrv_load_vmstate
= qcow2_load_vmstate
,
4378 .supports_backing
= true,
4379 .bdrv_change_backing_file
= qcow2_change_backing_file
,
4381 .bdrv_refresh_limits
= qcow2_refresh_limits
,
4382 .bdrv_invalidate_cache
= qcow2_invalidate_cache
,
4383 .bdrv_inactivate
= qcow2_inactivate
,
4385 .create_opts
= &qcow2_create_opts
,
4386 .bdrv_check
= qcow2_check
,
4387 .bdrv_amend_options
= qcow2_amend_options
,
4389 .bdrv_detach_aio_context
= qcow2_detach_aio_context
,
4390 .bdrv_attach_aio_context
= qcow2_attach_aio_context
,
4392 .bdrv_reopen_bitmaps_rw
= qcow2_reopen_bitmaps_rw
,
4393 .bdrv_can_store_new_dirty_bitmap
= qcow2_can_store_new_dirty_bitmap
,
4394 .bdrv_remove_persistent_dirty_bitmap
= qcow2_remove_persistent_dirty_bitmap
,
4397 static void bdrv_qcow2_init(void)
4399 bdrv_register(&bdrv_qcow2
);
4402 block_init(bdrv_qcow2_init
);