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/qapi-events-block-core.h"
34 #include "qapi/qmp/qdict.h"
35 #include "qapi/qmp/qstring.h"
37 #include "qemu/option_int.h"
38 #include "qemu/cutils.h"
39 #include "qemu/bswap.h"
40 #include "qapi/opts-visitor.h"
41 #include "block/crypto.h"
44 Differences with QCOW:
46 - Support for multiple incremental snapshots.
47 - Memory management by reference counts.
48 - Clusters which have a reference count of one have the bit
49 QCOW_OFLAG_COPIED to optimize write performance.
50 - Size of compressed clusters is stored in sectors to reduce bit usage
51 in the cluster offsets.
52 - Support for storing additional data (such as the VM state) in the
54 - If a backing store is used, the cluster size is not constrained
55 (could be backported to QCOW).
56 - L2 tables have always a size of one cluster.
63 } QEMU_PACKED QCowExtension
;
65 #define QCOW2_EXT_MAGIC_END 0
66 #define QCOW2_EXT_MAGIC_BACKING_FORMAT 0xE2792ACA
67 #define QCOW2_EXT_MAGIC_FEATURE_TABLE 0x6803f857
68 #define QCOW2_EXT_MAGIC_CRYPTO_HEADER 0x0537be77
69 #define QCOW2_EXT_MAGIC_BITMAPS 0x23852875
71 static int qcow2_probe(const uint8_t *buf
, int buf_size
, const char *filename
)
73 const QCowHeader
*cow_header
= (const void *)buf
;
75 if (buf_size
>= sizeof(QCowHeader
) &&
76 be32_to_cpu(cow_header
->magic
) == QCOW_MAGIC
&&
77 be32_to_cpu(cow_header
->version
) >= 2)
84 static ssize_t
qcow2_crypto_hdr_read_func(QCryptoBlock
*block
, size_t offset
,
85 uint8_t *buf
, size_t buflen
,
86 void *opaque
, Error
**errp
)
88 BlockDriverState
*bs
= opaque
;
89 BDRVQcow2State
*s
= bs
->opaque
;
92 if ((offset
+ buflen
) > s
->crypto_header
.length
) {
93 error_setg(errp
, "Request for data outside of extension header");
97 ret
= bdrv_pread(bs
->file
,
98 s
->crypto_header
.offset
+ offset
, buf
, buflen
);
100 error_setg_errno(errp
, -ret
, "Could not read encryption header");
107 static ssize_t
qcow2_crypto_hdr_init_func(QCryptoBlock
*block
, size_t headerlen
,
108 void *opaque
, Error
**errp
)
110 BlockDriverState
*bs
= opaque
;
111 BDRVQcow2State
*s
= bs
->opaque
;
115 ret
= qcow2_alloc_clusters(bs
, headerlen
);
117 error_setg_errno(errp
, -ret
,
118 "Cannot allocate cluster for LUKS header size %zu",
123 s
->crypto_header
.length
= headerlen
;
124 s
->crypto_header
.offset
= ret
;
126 /* Zero fill remaining space in cluster so it has predictable
127 * content in case of future spec changes */
128 clusterlen
= size_to_clusters(s
, headerlen
) * s
->cluster_size
;
129 assert(qcow2_pre_write_overlap_check(bs
, 0, ret
, clusterlen
) == 0);
130 ret
= bdrv_pwrite_zeroes(bs
->file
,
132 clusterlen
- headerlen
, 0);
134 error_setg_errno(errp
, -ret
, "Could not zero fill encryption header");
142 static ssize_t
qcow2_crypto_hdr_write_func(QCryptoBlock
*block
, size_t offset
,
143 const uint8_t *buf
, size_t buflen
,
144 void *opaque
, Error
**errp
)
146 BlockDriverState
*bs
= opaque
;
147 BDRVQcow2State
*s
= bs
->opaque
;
150 if ((offset
+ buflen
) > s
->crypto_header
.length
) {
151 error_setg(errp
, "Request for data outside of extension header");
155 ret
= bdrv_pwrite(bs
->file
,
156 s
->crypto_header
.offset
+ offset
, buf
, buflen
);
158 error_setg_errno(errp
, -ret
, "Could not read encryption header");
166 * read qcow2 extension and fill bs
167 * start reading from start_offset
168 * finish reading upon magic of value 0 or when end_offset reached
169 * unknown magic is skipped (future extension this version knows nothing about)
170 * return 0 upon success, non-0 otherwise
172 static int qcow2_read_extensions(BlockDriverState
*bs
, uint64_t start_offset
,
173 uint64_t end_offset
, void **p_feature_table
,
174 int flags
, bool *need_update_header
,
177 BDRVQcow2State
*s
= bs
->opaque
;
181 Qcow2BitmapHeaderExt bitmaps_ext
;
183 if (need_update_header
!= NULL
) {
184 *need_update_header
= false;
188 printf("qcow2_read_extensions: start=%ld end=%ld\n", start_offset
, end_offset
);
190 offset
= start_offset
;
191 while (offset
< end_offset
) {
195 if (offset
> s
->cluster_size
)
196 printf("qcow2_read_extension: suspicious offset %lu\n", offset
);
198 printf("attempting to read extended header in offset %lu\n", offset
);
201 ret
= bdrv_pread(bs
->file
, offset
, &ext
, sizeof(ext
));
203 error_setg_errno(errp
, -ret
, "qcow2_read_extension: ERROR: "
204 "pread fail from offset %" PRIu64
, offset
);
207 be32_to_cpus(&ext
.magic
);
208 be32_to_cpus(&ext
.len
);
209 offset
+= sizeof(ext
);
211 printf("ext.magic = 0x%x\n", ext
.magic
);
213 if (offset
> end_offset
|| ext
.len
> end_offset
- offset
) {
214 error_setg(errp
, "Header extension too large");
219 case QCOW2_EXT_MAGIC_END
:
222 case QCOW2_EXT_MAGIC_BACKING_FORMAT
:
223 if (ext
.len
>= sizeof(bs
->backing_format
)) {
224 error_setg(errp
, "ERROR: ext_backing_format: len=%" PRIu32
225 " too large (>=%zu)", ext
.len
,
226 sizeof(bs
->backing_format
));
229 ret
= bdrv_pread(bs
->file
, offset
, bs
->backing_format
, ext
.len
);
231 error_setg_errno(errp
, -ret
, "ERROR: ext_backing_format: "
232 "Could not read format name");
235 bs
->backing_format
[ext
.len
] = '\0';
236 s
->image_backing_format
= g_strdup(bs
->backing_format
);
238 printf("Qcow2: Got format extension %s\n", bs
->backing_format
);
242 case QCOW2_EXT_MAGIC_FEATURE_TABLE
:
243 if (p_feature_table
!= NULL
) {
244 void* feature_table
= g_malloc0(ext
.len
+ 2 * sizeof(Qcow2Feature
));
245 ret
= bdrv_pread(bs
->file
, offset
, feature_table
, ext
.len
);
247 error_setg_errno(errp
, -ret
, "ERROR: ext_feature_table: "
248 "Could not read table");
252 *p_feature_table
= feature_table
;
256 case QCOW2_EXT_MAGIC_CRYPTO_HEADER
: {
257 unsigned int cflags
= 0;
258 if (s
->crypt_method_header
!= QCOW_CRYPT_LUKS
) {
259 error_setg(errp
, "CRYPTO header extension only "
260 "expected with LUKS encryption method");
263 if (ext
.len
!= sizeof(Qcow2CryptoHeaderExtension
)) {
264 error_setg(errp
, "CRYPTO header extension size %u, "
265 "but expected size %zu", ext
.len
,
266 sizeof(Qcow2CryptoHeaderExtension
));
270 ret
= bdrv_pread(bs
->file
, offset
, &s
->crypto_header
, ext
.len
);
272 error_setg_errno(errp
, -ret
,
273 "Unable to read CRYPTO header extension");
276 be64_to_cpus(&s
->crypto_header
.offset
);
277 be64_to_cpus(&s
->crypto_header
.length
);
279 if ((s
->crypto_header
.offset
% s
->cluster_size
) != 0) {
280 error_setg(errp
, "Encryption header offset '%" PRIu64
"' is "
281 "not a multiple of cluster size '%u'",
282 s
->crypto_header
.offset
, s
->cluster_size
);
286 if (flags
& BDRV_O_NO_IO
) {
287 cflags
|= QCRYPTO_BLOCK_OPEN_NO_IO
;
289 s
->crypto
= qcrypto_block_open(s
->crypto_opts
, "encrypt.",
290 qcow2_crypto_hdr_read_func
,
297 case QCOW2_EXT_MAGIC_BITMAPS
:
298 if (ext
.len
!= sizeof(bitmaps_ext
)) {
299 error_setg_errno(errp
, -ret
, "bitmaps_ext: "
300 "Invalid extension length");
304 if (!(s
->autoclear_features
& QCOW2_AUTOCLEAR_BITMAPS
)) {
305 if (s
->qcow_version
< 3) {
306 /* Let's be a bit more specific */
307 warn_report("This qcow2 v2 image contains bitmaps, but "
308 "they may have been modified by a program "
309 "without persistent bitmap support; so now "
310 "they must all be considered inconsistent");
312 warn_report("a program lacking bitmap support "
313 "modified this file, so all bitmaps are now "
314 "considered inconsistent");
316 error_printf("Some clusters may be leaked, "
317 "run 'qemu-img check -r' on the image "
319 if (need_update_header
!= NULL
) {
320 /* Updating is needed to drop invalid bitmap extension. */
321 *need_update_header
= true;
326 ret
= bdrv_pread(bs
->file
, offset
, &bitmaps_ext
, ext
.len
);
328 error_setg_errno(errp
, -ret
, "bitmaps_ext: "
329 "Could not read ext header");
333 if (bitmaps_ext
.reserved32
!= 0) {
334 error_setg_errno(errp
, -ret
, "bitmaps_ext: "
335 "Reserved field is not zero");
339 be32_to_cpus(&bitmaps_ext
.nb_bitmaps
);
340 be64_to_cpus(&bitmaps_ext
.bitmap_directory_size
);
341 be64_to_cpus(&bitmaps_ext
.bitmap_directory_offset
);
343 if (bitmaps_ext
.nb_bitmaps
> QCOW2_MAX_BITMAPS
) {
345 "bitmaps_ext: Image has %" PRIu32
" bitmaps, "
346 "exceeding the QEMU supported maximum of %d",
347 bitmaps_ext
.nb_bitmaps
, QCOW2_MAX_BITMAPS
);
351 if (bitmaps_ext
.nb_bitmaps
== 0) {
352 error_setg(errp
, "found bitmaps extension with zero bitmaps");
356 if (bitmaps_ext
.bitmap_directory_offset
& (s
->cluster_size
- 1)) {
357 error_setg(errp
, "bitmaps_ext: "
358 "invalid bitmap directory offset");
362 if (bitmaps_ext
.bitmap_directory_size
>
363 QCOW2_MAX_BITMAP_DIRECTORY_SIZE
) {
364 error_setg(errp
, "bitmaps_ext: "
365 "bitmap directory size (%" PRIu64
") exceeds "
366 "the maximum supported size (%d)",
367 bitmaps_ext
.bitmap_directory_size
,
368 QCOW2_MAX_BITMAP_DIRECTORY_SIZE
);
372 s
->nb_bitmaps
= bitmaps_ext
.nb_bitmaps
;
373 s
->bitmap_directory_offset
=
374 bitmaps_ext
.bitmap_directory_offset
;
375 s
->bitmap_directory_size
=
376 bitmaps_ext
.bitmap_directory_size
;
379 printf("Qcow2: Got bitmaps extension: "
380 "offset=%" PRIu64
" nb_bitmaps=%" PRIu32
"\n",
381 s
->bitmap_directory_offset
, s
->nb_bitmaps
);
386 /* unknown magic - save it in case we need to rewrite the header */
387 /* If you add a new feature, make sure to also update the fast
388 * path of qcow2_make_empty() to deal with it. */
390 Qcow2UnknownHeaderExtension
*uext
;
392 uext
= g_malloc0(sizeof(*uext
) + ext
.len
);
393 uext
->magic
= ext
.magic
;
395 QLIST_INSERT_HEAD(&s
->unknown_header_ext
, uext
, next
);
397 ret
= bdrv_pread(bs
->file
, offset
, uext
->data
, uext
->len
);
399 error_setg_errno(errp
, -ret
, "ERROR: unknown extension: "
400 "Could not read data");
407 offset
+= ((ext
.len
+ 7) & ~7);
413 static void cleanup_unknown_header_ext(BlockDriverState
*bs
)
415 BDRVQcow2State
*s
= bs
->opaque
;
416 Qcow2UnknownHeaderExtension
*uext
, *next
;
418 QLIST_FOREACH_SAFE(uext
, &s
->unknown_header_ext
, next
, next
) {
419 QLIST_REMOVE(uext
, next
);
424 static void report_unsupported_feature(Error
**errp
, Qcow2Feature
*table
,
427 char *features
= g_strdup("");
430 while (table
&& table
->name
[0] != '\0') {
431 if (table
->type
== QCOW2_FEAT_TYPE_INCOMPATIBLE
) {
432 if (mask
& (1ULL << table
->bit
)) {
434 features
= g_strdup_printf("%s%s%.46s", old
, *old
? ", " : "",
437 mask
&= ~(1ULL << table
->bit
);
445 features
= g_strdup_printf("%s%sUnknown incompatible feature: %" PRIx64
,
446 old
, *old
? ", " : "", mask
);
450 error_setg(errp
, "Unsupported qcow2 feature(s): %s", features
);
455 * Sets the dirty bit and flushes afterwards if necessary.
457 * The incompatible_features bit is only set if the image file header was
458 * updated successfully. Therefore it is not required to check the return
459 * value of this function.
461 int qcow2_mark_dirty(BlockDriverState
*bs
)
463 BDRVQcow2State
*s
= bs
->opaque
;
467 assert(s
->qcow_version
>= 3);
469 if (s
->incompatible_features
& QCOW2_INCOMPAT_DIRTY
) {
470 return 0; /* already dirty */
473 val
= cpu_to_be64(s
->incompatible_features
| QCOW2_INCOMPAT_DIRTY
);
474 ret
= bdrv_pwrite(bs
->file
, offsetof(QCowHeader
, incompatible_features
),
479 ret
= bdrv_flush(bs
->file
->bs
);
484 /* Only treat image as dirty if the header was updated successfully */
485 s
->incompatible_features
|= QCOW2_INCOMPAT_DIRTY
;
490 * Clears the dirty bit and flushes before if necessary. Only call this
491 * function when there are no pending requests, it does not guard against
492 * concurrent requests dirtying the image.
494 static int qcow2_mark_clean(BlockDriverState
*bs
)
496 BDRVQcow2State
*s
= bs
->opaque
;
498 if (s
->incompatible_features
& QCOW2_INCOMPAT_DIRTY
) {
501 s
->incompatible_features
&= ~QCOW2_INCOMPAT_DIRTY
;
503 ret
= qcow2_flush_caches(bs
);
508 return qcow2_update_header(bs
);
514 * Marks the image as corrupt.
516 int qcow2_mark_corrupt(BlockDriverState
*bs
)
518 BDRVQcow2State
*s
= bs
->opaque
;
520 s
->incompatible_features
|= QCOW2_INCOMPAT_CORRUPT
;
521 return qcow2_update_header(bs
);
525 * Marks the image as consistent, i.e., unsets the corrupt bit, and flushes
526 * before if necessary.
528 int qcow2_mark_consistent(BlockDriverState
*bs
)
530 BDRVQcow2State
*s
= bs
->opaque
;
532 if (s
->incompatible_features
& QCOW2_INCOMPAT_CORRUPT
) {
533 int ret
= qcow2_flush_caches(bs
);
538 s
->incompatible_features
&= ~QCOW2_INCOMPAT_CORRUPT
;
539 return qcow2_update_header(bs
);
544 static int qcow2_check(BlockDriverState
*bs
, BdrvCheckResult
*result
,
547 int ret
= qcow2_check_refcounts(bs
, result
, fix
);
552 if (fix
&& result
->check_errors
== 0 && result
->corruptions
== 0) {
553 ret
= qcow2_mark_clean(bs
);
557 return qcow2_mark_consistent(bs
);
562 static int validate_table_offset(BlockDriverState
*bs
, uint64_t offset
,
563 uint64_t entries
, size_t entry_len
)
565 BDRVQcow2State
*s
= bs
->opaque
;
568 /* Use signed INT64_MAX as the maximum even for uint64_t header fields,
569 * because values will be passed to qemu functions taking int64_t. */
570 if (entries
> INT64_MAX
/ entry_len
) {
574 size
= entries
* entry_len
;
576 if (INT64_MAX
- size
< offset
) {
580 /* Tables must be cluster aligned */
581 if (offset_into_cluster(s
, offset
) != 0) {
588 static QemuOptsList qcow2_runtime_opts
= {
590 .head
= QTAILQ_HEAD_INITIALIZER(qcow2_runtime_opts
.head
),
593 .name
= QCOW2_OPT_LAZY_REFCOUNTS
,
594 .type
= QEMU_OPT_BOOL
,
595 .help
= "Postpone refcount updates",
598 .name
= QCOW2_OPT_DISCARD_REQUEST
,
599 .type
= QEMU_OPT_BOOL
,
600 .help
= "Pass guest discard requests to the layer below",
603 .name
= QCOW2_OPT_DISCARD_SNAPSHOT
,
604 .type
= QEMU_OPT_BOOL
,
605 .help
= "Generate discard requests when snapshot related space "
609 .name
= QCOW2_OPT_DISCARD_OTHER
,
610 .type
= QEMU_OPT_BOOL
,
611 .help
= "Generate discard requests when other clusters are freed",
614 .name
= QCOW2_OPT_OVERLAP
,
615 .type
= QEMU_OPT_STRING
,
616 .help
= "Selects which overlap checks to perform from a range of "
617 "templates (none, constant, cached, all)",
620 .name
= QCOW2_OPT_OVERLAP_TEMPLATE
,
621 .type
= QEMU_OPT_STRING
,
622 .help
= "Selects which overlap checks to perform from a range of "
623 "templates (none, constant, cached, all)",
626 .name
= QCOW2_OPT_OVERLAP_MAIN_HEADER
,
627 .type
= QEMU_OPT_BOOL
,
628 .help
= "Check for unintended writes into the main qcow2 header",
631 .name
= QCOW2_OPT_OVERLAP_ACTIVE_L1
,
632 .type
= QEMU_OPT_BOOL
,
633 .help
= "Check for unintended writes into the active L1 table",
636 .name
= QCOW2_OPT_OVERLAP_ACTIVE_L2
,
637 .type
= QEMU_OPT_BOOL
,
638 .help
= "Check for unintended writes into an active L2 table",
641 .name
= QCOW2_OPT_OVERLAP_REFCOUNT_TABLE
,
642 .type
= QEMU_OPT_BOOL
,
643 .help
= "Check for unintended writes into the refcount table",
646 .name
= QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK
,
647 .type
= QEMU_OPT_BOOL
,
648 .help
= "Check for unintended writes into a refcount block",
651 .name
= QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE
,
652 .type
= QEMU_OPT_BOOL
,
653 .help
= "Check for unintended writes into the snapshot table",
656 .name
= QCOW2_OPT_OVERLAP_INACTIVE_L1
,
657 .type
= QEMU_OPT_BOOL
,
658 .help
= "Check for unintended writes into an inactive L1 table",
661 .name
= QCOW2_OPT_OVERLAP_INACTIVE_L2
,
662 .type
= QEMU_OPT_BOOL
,
663 .help
= "Check for unintended writes into an inactive L2 table",
666 .name
= QCOW2_OPT_CACHE_SIZE
,
667 .type
= QEMU_OPT_SIZE
,
668 .help
= "Maximum combined metadata (L2 tables and refcount blocks) "
672 .name
= QCOW2_OPT_L2_CACHE_SIZE
,
673 .type
= QEMU_OPT_SIZE
,
674 .help
= "Maximum L2 table cache size",
677 .name
= QCOW2_OPT_L2_CACHE_ENTRY_SIZE
,
678 .type
= QEMU_OPT_SIZE
,
679 .help
= "Size of each entry in the L2 cache",
682 .name
= QCOW2_OPT_REFCOUNT_CACHE_SIZE
,
683 .type
= QEMU_OPT_SIZE
,
684 .help
= "Maximum refcount block cache size",
687 .name
= QCOW2_OPT_CACHE_CLEAN_INTERVAL
,
688 .type
= QEMU_OPT_NUMBER
,
689 .help
= "Clean unused cache entries after this time (in seconds)",
691 BLOCK_CRYPTO_OPT_DEF_KEY_SECRET("encrypt.",
692 "ID of secret providing qcow2 AES key or LUKS passphrase"),
693 { /* end of list */ }
697 static const char *overlap_bool_option_names
[QCOW2_OL_MAX_BITNR
] = {
698 [QCOW2_OL_MAIN_HEADER_BITNR
] = QCOW2_OPT_OVERLAP_MAIN_HEADER
,
699 [QCOW2_OL_ACTIVE_L1_BITNR
] = QCOW2_OPT_OVERLAP_ACTIVE_L1
,
700 [QCOW2_OL_ACTIVE_L2_BITNR
] = QCOW2_OPT_OVERLAP_ACTIVE_L2
,
701 [QCOW2_OL_REFCOUNT_TABLE_BITNR
] = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE
,
702 [QCOW2_OL_REFCOUNT_BLOCK_BITNR
] = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK
,
703 [QCOW2_OL_SNAPSHOT_TABLE_BITNR
] = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE
,
704 [QCOW2_OL_INACTIVE_L1_BITNR
] = QCOW2_OPT_OVERLAP_INACTIVE_L1
,
705 [QCOW2_OL_INACTIVE_L2_BITNR
] = QCOW2_OPT_OVERLAP_INACTIVE_L2
,
708 static void cache_clean_timer_cb(void *opaque
)
710 BlockDriverState
*bs
= opaque
;
711 BDRVQcow2State
*s
= bs
->opaque
;
712 qcow2_cache_clean_unused(s
->l2_table_cache
);
713 qcow2_cache_clean_unused(s
->refcount_block_cache
);
714 timer_mod(s
->cache_clean_timer
, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL
) +
715 (int64_t) s
->cache_clean_interval
* 1000);
718 static void cache_clean_timer_init(BlockDriverState
*bs
, AioContext
*context
)
720 BDRVQcow2State
*s
= bs
->opaque
;
721 if (s
->cache_clean_interval
> 0) {
722 s
->cache_clean_timer
= aio_timer_new(context
, QEMU_CLOCK_VIRTUAL
,
723 SCALE_MS
, cache_clean_timer_cb
,
725 timer_mod(s
->cache_clean_timer
, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL
) +
726 (int64_t) s
->cache_clean_interval
* 1000);
730 static void cache_clean_timer_del(BlockDriverState
*bs
)
732 BDRVQcow2State
*s
= bs
->opaque
;
733 if (s
->cache_clean_timer
) {
734 timer_del(s
->cache_clean_timer
);
735 timer_free(s
->cache_clean_timer
);
736 s
->cache_clean_timer
= NULL
;
740 static void qcow2_detach_aio_context(BlockDriverState
*bs
)
742 cache_clean_timer_del(bs
);
745 static void qcow2_attach_aio_context(BlockDriverState
*bs
,
746 AioContext
*new_context
)
748 cache_clean_timer_init(bs
, new_context
);
751 static void read_cache_sizes(BlockDriverState
*bs
, QemuOpts
*opts
,
752 uint64_t *l2_cache_size
,
753 uint64_t *l2_cache_entry_size
,
754 uint64_t *refcount_cache_size
, Error
**errp
)
756 BDRVQcow2State
*s
= bs
->opaque
;
757 uint64_t combined_cache_size
;
758 bool l2_cache_size_set
, refcount_cache_size_set
, combined_cache_size_set
;
760 combined_cache_size_set
= qemu_opt_get(opts
, QCOW2_OPT_CACHE_SIZE
);
761 l2_cache_size_set
= qemu_opt_get(opts
, QCOW2_OPT_L2_CACHE_SIZE
);
762 refcount_cache_size_set
= qemu_opt_get(opts
, QCOW2_OPT_REFCOUNT_CACHE_SIZE
);
764 combined_cache_size
= qemu_opt_get_size(opts
, QCOW2_OPT_CACHE_SIZE
, 0);
765 *l2_cache_size
= qemu_opt_get_size(opts
, QCOW2_OPT_L2_CACHE_SIZE
, 0);
766 *refcount_cache_size
= qemu_opt_get_size(opts
,
767 QCOW2_OPT_REFCOUNT_CACHE_SIZE
, 0);
769 *l2_cache_entry_size
= qemu_opt_get_size(
770 opts
, QCOW2_OPT_L2_CACHE_ENTRY_SIZE
, s
->cluster_size
);
772 if (combined_cache_size_set
) {
773 if (l2_cache_size_set
&& refcount_cache_size_set
) {
774 error_setg(errp
, QCOW2_OPT_CACHE_SIZE
", " QCOW2_OPT_L2_CACHE_SIZE
775 " and " QCOW2_OPT_REFCOUNT_CACHE_SIZE
" may not be set "
778 } else if (*l2_cache_size
> combined_cache_size
) {
779 error_setg(errp
, QCOW2_OPT_L2_CACHE_SIZE
" may not exceed "
780 QCOW2_OPT_CACHE_SIZE
);
782 } else if (*refcount_cache_size
> combined_cache_size
) {
783 error_setg(errp
, QCOW2_OPT_REFCOUNT_CACHE_SIZE
" may not exceed "
784 QCOW2_OPT_CACHE_SIZE
);
788 if (l2_cache_size_set
) {
789 *refcount_cache_size
= combined_cache_size
- *l2_cache_size
;
790 } else if (refcount_cache_size_set
) {
791 *l2_cache_size
= combined_cache_size
- *refcount_cache_size
;
793 *refcount_cache_size
= combined_cache_size
794 / (DEFAULT_L2_REFCOUNT_SIZE_RATIO
+ 1);
795 *l2_cache_size
= combined_cache_size
- *refcount_cache_size
;
798 if (!l2_cache_size_set
&& !refcount_cache_size_set
) {
799 *l2_cache_size
= MAX(DEFAULT_L2_CACHE_BYTE_SIZE
,
800 (uint64_t)DEFAULT_L2_CACHE_CLUSTERS
802 *refcount_cache_size
= *l2_cache_size
803 / DEFAULT_L2_REFCOUNT_SIZE_RATIO
;
804 } else if (!l2_cache_size_set
) {
805 *l2_cache_size
= *refcount_cache_size
806 * DEFAULT_L2_REFCOUNT_SIZE_RATIO
;
807 } else if (!refcount_cache_size_set
) {
808 *refcount_cache_size
= *l2_cache_size
809 / DEFAULT_L2_REFCOUNT_SIZE_RATIO
;
813 if (*l2_cache_entry_size
< (1 << MIN_CLUSTER_BITS
) ||
814 *l2_cache_entry_size
> s
->cluster_size
||
815 !is_power_of_2(*l2_cache_entry_size
)) {
816 error_setg(errp
, "L2 cache entry size must be a power of two "
817 "between %d and the cluster size (%d)",
818 1 << MIN_CLUSTER_BITS
, s
->cluster_size
);
823 typedef struct Qcow2ReopenState
{
824 Qcow2Cache
*l2_table_cache
;
825 Qcow2Cache
*refcount_block_cache
;
826 int l2_slice_size
; /* Number of entries in a slice of the L2 table */
827 bool use_lazy_refcounts
;
829 bool discard_passthrough
[QCOW2_DISCARD_MAX
];
830 uint64_t cache_clean_interval
;
831 QCryptoBlockOpenOptions
*crypto_opts
; /* Disk encryption runtime options */
834 static int qcow2_update_options_prepare(BlockDriverState
*bs
,
836 QDict
*options
, int flags
,
839 BDRVQcow2State
*s
= bs
->opaque
;
840 QemuOpts
*opts
= NULL
;
841 const char *opt_overlap_check
, *opt_overlap_check_template
;
842 int overlap_check_template
= 0;
843 uint64_t l2_cache_size
, l2_cache_entry_size
, refcount_cache_size
;
845 const char *encryptfmt
;
846 QDict
*encryptopts
= NULL
;
847 Error
*local_err
= NULL
;
850 qdict_extract_subqdict(options
, &encryptopts
, "encrypt.");
851 encryptfmt
= qdict_get_try_str(encryptopts
, "format");
853 opts
= qemu_opts_create(&qcow2_runtime_opts
, NULL
, 0, &error_abort
);
854 qemu_opts_absorb_qdict(opts
, options
, &local_err
);
856 error_propagate(errp
, local_err
);
861 /* get L2 table/refcount block cache size from command line options */
862 read_cache_sizes(bs
, opts
, &l2_cache_size
, &l2_cache_entry_size
,
863 &refcount_cache_size
, &local_err
);
865 error_propagate(errp
, local_err
);
870 l2_cache_size
/= l2_cache_entry_size
;
871 if (l2_cache_size
< MIN_L2_CACHE_SIZE
) {
872 l2_cache_size
= MIN_L2_CACHE_SIZE
;
874 if (l2_cache_size
> INT_MAX
) {
875 error_setg(errp
, "L2 cache size too big");
880 refcount_cache_size
/= s
->cluster_size
;
881 if (refcount_cache_size
< MIN_REFCOUNT_CACHE_SIZE
) {
882 refcount_cache_size
= MIN_REFCOUNT_CACHE_SIZE
;
884 if (refcount_cache_size
> INT_MAX
) {
885 error_setg(errp
, "Refcount cache size too big");
890 /* alloc new L2 table/refcount block cache, flush old one */
891 if (s
->l2_table_cache
) {
892 ret
= qcow2_cache_flush(bs
, s
->l2_table_cache
);
894 error_setg_errno(errp
, -ret
, "Failed to flush the L2 table cache");
899 if (s
->refcount_block_cache
) {
900 ret
= qcow2_cache_flush(bs
, s
->refcount_block_cache
);
902 error_setg_errno(errp
, -ret
,
903 "Failed to flush the refcount block cache");
908 r
->l2_slice_size
= l2_cache_entry_size
/ sizeof(uint64_t);
909 r
->l2_table_cache
= qcow2_cache_create(bs
, l2_cache_size
,
910 l2_cache_entry_size
);
911 r
->refcount_block_cache
= qcow2_cache_create(bs
, refcount_cache_size
,
913 if (r
->l2_table_cache
== NULL
|| r
->refcount_block_cache
== NULL
) {
914 error_setg(errp
, "Could not allocate metadata caches");
919 /* New interval for cache cleanup timer */
920 r
->cache_clean_interval
=
921 qemu_opt_get_number(opts
, QCOW2_OPT_CACHE_CLEAN_INTERVAL
,
922 s
->cache_clean_interval
);
924 if (r
->cache_clean_interval
!= 0) {
925 error_setg(errp
, QCOW2_OPT_CACHE_CLEAN_INTERVAL
926 " not supported on this host");
931 if (r
->cache_clean_interval
> UINT_MAX
) {
932 error_setg(errp
, "Cache clean interval too big");
937 /* lazy-refcounts; flush if going from enabled to disabled */
938 r
->use_lazy_refcounts
= qemu_opt_get_bool(opts
, QCOW2_OPT_LAZY_REFCOUNTS
,
939 (s
->compatible_features
& QCOW2_COMPAT_LAZY_REFCOUNTS
));
940 if (r
->use_lazy_refcounts
&& s
->qcow_version
< 3) {
941 error_setg(errp
, "Lazy refcounts require a qcow2 image with at least "
942 "qemu 1.1 compatibility level");
947 if (s
->use_lazy_refcounts
&& !r
->use_lazy_refcounts
) {
948 ret
= qcow2_mark_clean(bs
);
950 error_setg_errno(errp
, -ret
, "Failed to disable lazy refcounts");
955 /* Overlap check options */
956 opt_overlap_check
= qemu_opt_get(opts
, QCOW2_OPT_OVERLAP
);
957 opt_overlap_check_template
= qemu_opt_get(opts
, QCOW2_OPT_OVERLAP_TEMPLATE
);
958 if (opt_overlap_check_template
&& opt_overlap_check
&&
959 strcmp(opt_overlap_check_template
, opt_overlap_check
))
961 error_setg(errp
, "Conflicting values for qcow2 options '"
962 QCOW2_OPT_OVERLAP
"' ('%s') and '" QCOW2_OPT_OVERLAP_TEMPLATE
963 "' ('%s')", opt_overlap_check
, opt_overlap_check_template
);
967 if (!opt_overlap_check
) {
968 opt_overlap_check
= opt_overlap_check_template
?: "cached";
971 if (!strcmp(opt_overlap_check
, "none")) {
972 overlap_check_template
= 0;
973 } else if (!strcmp(opt_overlap_check
, "constant")) {
974 overlap_check_template
= QCOW2_OL_CONSTANT
;
975 } else if (!strcmp(opt_overlap_check
, "cached")) {
976 overlap_check_template
= QCOW2_OL_CACHED
;
977 } else if (!strcmp(opt_overlap_check
, "all")) {
978 overlap_check_template
= QCOW2_OL_ALL
;
980 error_setg(errp
, "Unsupported value '%s' for qcow2 option "
981 "'overlap-check'. Allowed are any of the following: "
982 "none, constant, cached, all", opt_overlap_check
);
987 r
->overlap_check
= 0;
988 for (i
= 0; i
< QCOW2_OL_MAX_BITNR
; i
++) {
989 /* overlap-check defines a template bitmask, but every flag may be
990 * overwritten through the associated boolean option */
992 qemu_opt_get_bool(opts
, overlap_bool_option_names
[i
],
993 overlap_check_template
& (1 << i
)) << i
;
996 r
->discard_passthrough
[QCOW2_DISCARD_NEVER
] = false;
997 r
->discard_passthrough
[QCOW2_DISCARD_ALWAYS
] = true;
998 r
->discard_passthrough
[QCOW2_DISCARD_REQUEST
] =
999 qemu_opt_get_bool(opts
, QCOW2_OPT_DISCARD_REQUEST
,
1000 flags
& BDRV_O_UNMAP
);
1001 r
->discard_passthrough
[QCOW2_DISCARD_SNAPSHOT
] =
1002 qemu_opt_get_bool(opts
, QCOW2_OPT_DISCARD_SNAPSHOT
, true);
1003 r
->discard_passthrough
[QCOW2_DISCARD_OTHER
] =
1004 qemu_opt_get_bool(opts
, QCOW2_OPT_DISCARD_OTHER
, false);
1006 switch (s
->crypt_method_header
) {
1007 case QCOW_CRYPT_NONE
:
1009 error_setg(errp
, "No encryption in image header, but options "
1010 "specified format '%s'", encryptfmt
);
1016 case QCOW_CRYPT_AES
:
1017 if (encryptfmt
&& !g_str_equal(encryptfmt
, "aes")) {
1019 "Header reported 'aes' encryption format but "
1020 "options specify '%s'", encryptfmt
);
1024 qdict_del(encryptopts
, "format");
1025 r
->crypto_opts
= block_crypto_open_opts_init(
1026 Q_CRYPTO_BLOCK_FORMAT_QCOW
, encryptopts
, errp
);
1029 case QCOW_CRYPT_LUKS
:
1030 if (encryptfmt
&& !g_str_equal(encryptfmt
, "luks")) {
1032 "Header reported 'luks' encryption format but "
1033 "options specify '%s'", encryptfmt
);
1037 qdict_del(encryptopts
, "format");
1038 r
->crypto_opts
= block_crypto_open_opts_init(
1039 Q_CRYPTO_BLOCK_FORMAT_LUKS
, encryptopts
, errp
);
1043 error_setg(errp
, "Unsupported encryption method %d",
1044 s
->crypt_method_header
);
1047 if (s
->crypt_method_header
!= QCOW_CRYPT_NONE
&& !r
->crypto_opts
) {
1054 QDECREF(encryptopts
);
1055 qemu_opts_del(opts
);
1060 static void qcow2_update_options_commit(BlockDriverState
*bs
,
1061 Qcow2ReopenState
*r
)
1063 BDRVQcow2State
*s
= bs
->opaque
;
1066 if (s
->l2_table_cache
) {
1067 qcow2_cache_destroy(s
->l2_table_cache
);
1069 if (s
->refcount_block_cache
) {
1070 qcow2_cache_destroy(s
->refcount_block_cache
);
1072 s
->l2_table_cache
= r
->l2_table_cache
;
1073 s
->refcount_block_cache
= r
->refcount_block_cache
;
1074 s
->l2_slice_size
= r
->l2_slice_size
;
1076 s
->overlap_check
= r
->overlap_check
;
1077 s
->use_lazy_refcounts
= r
->use_lazy_refcounts
;
1079 for (i
= 0; i
< QCOW2_DISCARD_MAX
; i
++) {
1080 s
->discard_passthrough
[i
] = r
->discard_passthrough
[i
];
1083 if (s
->cache_clean_interval
!= r
->cache_clean_interval
) {
1084 cache_clean_timer_del(bs
);
1085 s
->cache_clean_interval
= r
->cache_clean_interval
;
1086 cache_clean_timer_init(bs
, bdrv_get_aio_context(bs
));
1089 qapi_free_QCryptoBlockOpenOptions(s
->crypto_opts
);
1090 s
->crypto_opts
= r
->crypto_opts
;
1093 static void qcow2_update_options_abort(BlockDriverState
*bs
,
1094 Qcow2ReopenState
*r
)
1096 if (r
->l2_table_cache
) {
1097 qcow2_cache_destroy(r
->l2_table_cache
);
1099 if (r
->refcount_block_cache
) {
1100 qcow2_cache_destroy(r
->refcount_block_cache
);
1102 qapi_free_QCryptoBlockOpenOptions(r
->crypto_opts
);
1105 static int qcow2_update_options(BlockDriverState
*bs
, QDict
*options
,
1106 int flags
, Error
**errp
)
1108 Qcow2ReopenState r
= {};
1111 ret
= qcow2_update_options_prepare(bs
, &r
, options
, flags
, errp
);
1113 qcow2_update_options_commit(bs
, &r
);
1115 qcow2_update_options_abort(bs
, &r
);
1121 /* Called with s->lock held. */
1122 static int coroutine_fn
qcow2_do_open(BlockDriverState
*bs
, QDict
*options
,
1123 int flags
, Error
**errp
)
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 ROUND_UP(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 bs
->supported_zero_flags
= header
.version
>= 3 ? BDRV_REQ_MAY_UNMAP
: 0;
1504 /* Repair image if dirty */
1505 if (!(flags
& (BDRV_O_CHECK
| BDRV_O_INACTIVE
)) && !bs
->read_only
&&
1506 (s
->incompatible_features
& QCOW2_INCOMPAT_DIRTY
)) {
1507 BdrvCheckResult result
= {0};
1509 ret
= qcow2_check(bs
, &result
, BDRV_FIX_ERRORS
| BDRV_FIX_LEAKS
);
1510 if (ret
< 0 || result
.check_errors
) {
1514 error_setg_errno(errp
, -ret
, "Could not repair dirty image");
1521 BdrvCheckResult result
= {0};
1522 qcow2_check_refcounts(bs
, &result
, 0);
1528 g_free(s
->unknown_header_fields
);
1529 cleanup_unknown_header_ext(bs
);
1530 qcow2_free_snapshots(bs
);
1531 qcow2_refcount_close(bs
);
1532 qemu_vfree(s
->l1_table
);
1533 /* else pre-write overlap checks in cache_destroy may crash */
1535 cache_clean_timer_del(bs
);
1536 if (s
->l2_table_cache
) {
1537 qcow2_cache_destroy(s
->l2_table_cache
);
1539 if (s
->refcount_block_cache
) {
1540 qcow2_cache_destroy(s
->refcount_block_cache
);
1542 qcrypto_block_free(s
->crypto
);
1543 qapi_free_QCryptoBlockOpenOptions(s
->crypto_opts
);
1547 typedef struct QCow2OpenCo
{
1548 BlockDriverState
*bs
;
1555 static void coroutine_fn
qcow2_open_entry(void *opaque
)
1557 QCow2OpenCo
*qoc
= opaque
;
1558 BDRVQcow2State
*s
= qoc
->bs
->opaque
;
1560 qemu_co_mutex_lock(&s
->lock
);
1561 qoc
->ret
= qcow2_do_open(qoc
->bs
, qoc
->options
, qoc
->flags
, qoc
->errp
);
1562 qemu_co_mutex_unlock(&s
->lock
);
1565 static int qcow2_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
1568 BDRVQcow2State
*s
= bs
->opaque
;
1577 bs
->file
= bdrv_open_child(NULL
, options
, "file", bs
, &child_file
,
1583 /* Initialise locks */
1584 qemu_co_mutex_init(&s
->lock
);
1586 if (qemu_in_coroutine()) {
1587 /* From bdrv_co_create. */
1588 qcow2_open_entry(&qoc
);
1590 qemu_coroutine_enter(qemu_coroutine_create(qcow2_open_entry
, &qoc
));
1591 BDRV_POLL_WHILE(bs
, qoc
.ret
== -EINPROGRESS
);
1596 static void qcow2_refresh_limits(BlockDriverState
*bs
, Error
**errp
)
1598 BDRVQcow2State
*s
= bs
->opaque
;
1600 if (bs
->encrypted
) {
1601 /* Encryption works on a sector granularity */
1602 bs
->bl
.request_alignment
= BDRV_SECTOR_SIZE
;
1604 bs
->bl
.pwrite_zeroes_alignment
= s
->cluster_size
;
1605 bs
->bl
.pdiscard_alignment
= s
->cluster_size
;
1608 static int qcow2_reopen_prepare(BDRVReopenState
*state
,
1609 BlockReopenQueue
*queue
, Error
**errp
)
1611 Qcow2ReopenState
*r
;
1614 r
= g_new0(Qcow2ReopenState
, 1);
1617 ret
= qcow2_update_options_prepare(state
->bs
, r
, state
->options
,
1618 state
->flags
, errp
);
1623 /* We need to write out any unwritten data if we reopen read-only. */
1624 if ((state
->flags
& BDRV_O_RDWR
) == 0) {
1625 ret
= qcow2_reopen_bitmaps_ro(state
->bs
, errp
);
1630 ret
= bdrv_flush(state
->bs
);
1635 ret
= qcow2_mark_clean(state
->bs
);
1644 qcow2_update_options_abort(state
->bs
, r
);
1649 static void qcow2_reopen_commit(BDRVReopenState
*state
)
1651 qcow2_update_options_commit(state
->bs
, state
->opaque
);
1652 g_free(state
->opaque
);
1655 static void qcow2_reopen_abort(BDRVReopenState
*state
)
1657 qcow2_update_options_abort(state
->bs
, state
->opaque
);
1658 g_free(state
->opaque
);
1661 static void qcow2_join_options(QDict
*options
, QDict
*old_options
)
1663 bool has_new_overlap_template
=
1664 qdict_haskey(options
, QCOW2_OPT_OVERLAP
) ||
1665 qdict_haskey(options
, QCOW2_OPT_OVERLAP_TEMPLATE
);
1666 bool has_new_total_cache_size
=
1667 qdict_haskey(options
, QCOW2_OPT_CACHE_SIZE
);
1668 bool has_all_cache_options
;
1670 /* New overlap template overrides all old overlap options */
1671 if (has_new_overlap_template
) {
1672 qdict_del(old_options
, QCOW2_OPT_OVERLAP
);
1673 qdict_del(old_options
, QCOW2_OPT_OVERLAP_TEMPLATE
);
1674 qdict_del(old_options
, QCOW2_OPT_OVERLAP_MAIN_HEADER
);
1675 qdict_del(old_options
, QCOW2_OPT_OVERLAP_ACTIVE_L1
);
1676 qdict_del(old_options
, QCOW2_OPT_OVERLAP_ACTIVE_L2
);
1677 qdict_del(old_options
, QCOW2_OPT_OVERLAP_REFCOUNT_TABLE
);
1678 qdict_del(old_options
, QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK
);
1679 qdict_del(old_options
, QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE
);
1680 qdict_del(old_options
, QCOW2_OPT_OVERLAP_INACTIVE_L1
);
1681 qdict_del(old_options
, QCOW2_OPT_OVERLAP_INACTIVE_L2
);
1684 /* New total cache size overrides all old options */
1685 if (qdict_haskey(options
, QCOW2_OPT_CACHE_SIZE
)) {
1686 qdict_del(old_options
, QCOW2_OPT_L2_CACHE_SIZE
);
1687 qdict_del(old_options
, QCOW2_OPT_REFCOUNT_CACHE_SIZE
);
1690 qdict_join(options
, old_options
, false);
1693 * If after merging all cache size options are set, an old total size is
1694 * overwritten. Do keep all options, however, if all three are new. The
1695 * resulting error message is what we want to happen.
1697 has_all_cache_options
=
1698 qdict_haskey(options
, QCOW2_OPT_CACHE_SIZE
) ||
1699 qdict_haskey(options
, QCOW2_OPT_L2_CACHE_SIZE
) ||
1700 qdict_haskey(options
, QCOW2_OPT_REFCOUNT_CACHE_SIZE
);
1702 if (has_all_cache_options
&& !has_new_total_cache_size
) {
1703 qdict_del(options
, QCOW2_OPT_CACHE_SIZE
);
1707 static int coroutine_fn
qcow2_co_block_status(BlockDriverState
*bs
,
1709 int64_t offset
, int64_t count
,
1710 int64_t *pnum
, int64_t *map
,
1711 BlockDriverState
**file
)
1713 BDRVQcow2State
*s
= bs
->opaque
;
1714 uint64_t cluster_offset
;
1715 int index_in_cluster
, ret
;
1719 bytes
= MIN(INT_MAX
, count
);
1720 qemu_co_mutex_lock(&s
->lock
);
1721 ret
= qcow2_get_cluster_offset(bs
, offset
, &bytes
, &cluster_offset
);
1722 qemu_co_mutex_unlock(&s
->lock
);
1729 if (cluster_offset
!= 0 && ret
!= QCOW2_CLUSTER_COMPRESSED
&&
1731 index_in_cluster
= offset
& (s
->cluster_size
- 1);
1732 *map
= cluster_offset
| index_in_cluster
;
1733 *file
= bs
->file
->bs
;
1734 status
|= BDRV_BLOCK_OFFSET_VALID
;
1736 if (ret
== QCOW2_CLUSTER_ZERO_PLAIN
|| ret
== QCOW2_CLUSTER_ZERO_ALLOC
) {
1737 status
|= BDRV_BLOCK_ZERO
;
1738 } else if (ret
!= QCOW2_CLUSTER_UNALLOCATED
) {
1739 status
|= BDRV_BLOCK_DATA
;
1744 static coroutine_fn
int qcow2_co_preadv(BlockDriverState
*bs
, uint64_t offset
,
1745 uint64_t bytes
, QEMUIOVector
*qiov
,
1748 BDRVQcow2State
*s
= bs
->opaque
;
1749 int offset_in_cluster
;
1751 unsigned int cur_bytes
; /* number of bytes in current iteration */
1752 uint64_t cluster_offset
= 0;
1753 uint64_t bytes_done
= 0;
1754 QEMUIOVector hd_qiov
;
1755 uint8_t *cluster_data
= NULL
;
1757 qemu_iovec_init(&hd_qiov
, qiov
->niov
);
1759 qemu_co_mutex_lock(&s
->lock
);
1761 while (bytes
!= 0) {
1763 /* prepare next request */
1764 cur_bytes
= MIN(bytes
, INT_MAX
);
1766 cur_bytes
= MIN(cur_bytes
,
1767 QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_size
);
1770 ret
= qcow2_get_cluster_offset(bs
, offset
, &cur_bytes
, &cluster_offset
);
1775 offset_in_cluster
= offset_into_cluster(s
, offset
);
1777 qemu_iovec_reset(&hd_qiov
);
1778 qemu_iovec_concat(&hd_qiov
, qiov
, bytes_done
, cur_bytes
);
1781 case QCOW2_CLUSTER_UNALLOCATED
:
1784 BLKDBG_EVENT(bs
->file
, BLKDBG_READ_BACKING_AIO
);
1785 qemu_co_mutex_unlock(&s
->lock
);
1786 ret
= bdrv_co_preadv(bs
->backing
, offset
, cur_bytes
,
1788 qemu_co_mutex_lock(&s
->lock
);
1793 /* Note: in this case, no need to wait */
1794 qemu_iovec_memset(&hd_qiov
, 0, 0, cur_bytes
);
1798 case QCOW2_CLUSTER_ZERO_PLAIN
:
1799 case QCOW2_CLUSTER_ZERO_ALLOC
:
1800 qemu_iovec_memset(&hd_qiov
, 0, 0, cur_bytes
);
1803 case QCOW2_CLUSTER_COMPRESSED
:
1804 /* add AIO support for compressed blocks ? */
1805 ret
= qcow2_decompress_cluster(bs
, cluster_offset
);
1810 qemu_iovec_from_buf(&hd_qiov
, 0,
1811 s
->cluster_cache
+ offset_in_cluster
,
1815 case QCOW2_CLUSTER_NORMAL
:
1816 if ((cluster_offset
& 511) != 0) {
1821 if (bs
->encrypted
) {
1825 * For encrypted images, read everything into a temporary
1826 * contiguous buffer on which the AES functions can work.
1828 if (!cluster_data
) {
1830 qemu_try_blockalign(bs
->file
->bs
,
1831 QCOW_MAX_CRYPT_CLUSTERS
1833 if (cluster_data
== NULL
) {
1839 assert(cur_bytes
<= QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_size
);
1840 qemu_iovec_reset(&hd_qiov
);
1841 qemu_iovec_add(&hd_qiov
, cluster_data
, cur_bytes
);
1844 BLKDBG_EVENT(bs
->file
, BLKDBG_READ_AIO
);
1845 qemu_co_mutex_unlock(&s
->lock
);
1846 ret
= bdrv_co_preadv(bs
->file
,
1847 cluster_offset
+ offset_in_cluster
,
1848 cur_bytes
, &hd_qiov
, 0);
1849 qemu_co_mutex_lock(&s
->lock
);
1853 if (bs
->encrypted
) {
1855 assert((offset
& (BDRV_SECTOR_SIZE
- 1)) == 0);
1856 assert((cur_bytes
& (BDRV_SECTOR_SIZE
- 1)) == 0);
1857 if (qcrypto_block_decrypt(s
->crypto
,
1858 (s
->crypt_physical_offset
?
1859 cluster_offset
+ offset_in_cluster
:
1867 qemu_iovec_from_buf(qiov
, bytes_done
, cluster_data
, cur_bytes
);
1872 g_assert_not_reached();
1878 offset
+= cur_bytes
;
1879 bytes_done
+= cur_bytes
;
1884 qemu_co_mutex_unlock(&s
->lock
);
1886 qemu_iovec_destroy(&hd_qiov
);
1887 qemu_vfree(cluster_data
);
1892 /* Check if it's possible to merge a write request with the writing of
1893 * the data from the COW regions */
1894 static bool merge_cow(uint64_t offset
, unsigned bytes
,
1895 QEMUIOVector
*hd_qiov
, QCowL2Meta
*l2meta
)
1899 for (m
= l2meta
; m
!= NULL
; m
= m
->next
) {
1900 /* If both COW regions are empty then there's nothing to merge */
1901 if (m
->cow_start
.nb_bytes
== 0 && m
->cow_end
.nb_bytes
== 0) {
1905 /* The data (middle) region must be immediately after the
1907 if (l2meta_cow_start(m
) + m
->cow_start
.nb_bytes
!= offset
) {
1911 /* The end region must be immediately after the data (middle)
1913 if (m
->offset
+ m
->cow_end
.offset
!= offset
+ bytes
) {
1917 /* Make sure that adding both COW regions to the QEMUIOVector
1918 * does not exceed IOV_MAX */
1919 if (hd_qiov
->niov
> IOV_MAX
- 2) {
1923 m
->data_qiov
= hd_qiov
;
1930 static coroutine_fn
int qcow2_co_pwritev(BlockDriverState
*bs
, uint64_t offset
,
1931 uint64_t bytes
, QEMUIOVector
*qiov
,
1934 BDRVQcow2State
*s
= bs
->opaque
;
1935 int offset_in_cluster
;
1937 unsigned int cur_bytes
; /* number of sectors in current iteration */
1938 uint64_t cluster_offset
;
1939 QEMUIOVector hd_qiov
;
1940 uint64_t bytes_done
= 0;
1941 uint8_t *cluster_data
= NULL
;
1942 QCowL2Meta
*l2meta
= NULL
;
1944 trace_qcow2_writev_start_req(qemu_coroutine_self(), offset
, bytes
);
1946 qemu_iovec_init(&hd_qiov
, qiov
->niov
);
1948 s
->cluster_cache_offset
= -1; /* disable compressed cache */
1950 qemu_co_mutex_lock(&s
->lock
);
1952 while (bytes
!= 0) {
1956 trace_qcow2_writev_start_part(qemu_coroutine_self());
1957 offset_in_cluster
= offset_into_cluster(s
, offset
);
1958 cur_bytes
= MIN(bytes
, INT_MAX
);
1959 if (bs
->encrypted
) {
1960 cur_bytes
= MIN(cur_bytes
,
1961 QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_size
1962 - offset_in_cluster
);
1965 ret
= qcow2_alloc_cluster_offset(bs
, offset
, &cur_bytes
,
1966 &cluster_offset
, &l2meta
);
1971 assert((cluster_offset
& 511) == 0);
1973 qemu_iovec_reset(&hd_qiov
);
1974 qemu_iovec_concat(&hd_qiov
, qiov
, bytes_done
, cur_bytes
);
1976 if (bs
->encrypted
) {
1978 if (!cluster_data
) {
1979 cluster_data
= qemu_try_blockalign(bs
->file
->bs
,
1980 QCOW_MAX_CRYPT_CLUSTERS
1982 if (cluster_data
== NULL
) {
1988 assert(hd_qiov
.size
<=
1989 QCOW_MAX_CRYPT_CLUSTERS
* s
->cluster_size
);
1990 qemu_iovec_to_buf(&hd_qiov
, 0, cluster_data
, hd_qiov
.size
);
1992 if (qcrypto_block_encrypt(s
->crypto
,
1993 (s
->crypt_physical_offset
?
1994 cluster_offset
+ offset_in_cluster
:
1997 cur_bytes
, NULL
) < 0) {
2002 qemu_iovec_reset(&hd_qiov
);
2003 qemu_iovec_add(&hd_qiov
, cluster_data
, cur_bytes
);
2006 ret
= qcow2_pre_write_overlap_check(bs
, 0,
2007 cluster_offset
+ offset_in_cluster
, cur_bytes
);
2012 /* If we need to do COW, check if it's possible to merge the
2013 * writing of the guest data together with that of the COW regions.
2014 * If it's not possible (or not necessary) then write the
2015 * guest data now. */
2016 if (!merge_cow(offset
, cur_bytes
, &hd_qiov
, l2meta
)) {
2017 qemu_co_mutex_unlock(&s
->lock
);
2018 BLKDBG_EVENT(bs
->file
, BLKDBG_WRITE_AIO
);
2019 trace_qcow2_writev_data(qemu_coroutine_self(),
2020 cluster_offset
+ offset_in_cluster
);
2021 ret
= bdrv_co_pwritev(bs
->file
,
2022 cluster_offset
+ offset_in_cluster
,
2023 cur_bytes
, &hd_qiov
, 0);
2024 qemu_co_mutex_lock(&s
->lock
);
2030 while (l2meta
!= NULL
) {
2033 ret
= qcow2_alloc_cluster_link_l2(bs
, l2meta
);
2038 /* Take the request off the list of running requests */
2039 if (l2meta
->nb_clusters
!= 0) {
2040 QLIST_REMOVE(l2meta
, next_in_flight
);
2043 qemu_co_queue_restart_all(&l2meta
->dependent_requests
);
2045 next
= l2meta
->next
;
2051 offset
+= cur_bytes
;
2052 bytes_done
+= cur_bytes
;
2053 trace_qcow2_writev_done_part(qemu_coroutine_self(), cur_bytes
);
2058 while (l2meta
!= NULL
) {
2061 if (l2meta
->nb_clusters
!= 0) {
2062 QLIST_REMOVE(l2meta
, next_in_flight
);
2064 qemu_co_queue_restart_all(&l2meta
->dependent_requests
);
2066 next
= l2meta
->next
;
2071 qemu_co_mutex_unlock(&s
->lock
);
2073 qemu_iovec_destroy(&hd_qiov
);
2074 qemu_vfree(cluster_data
);
2075 trace_qcow2_writev_done_req(qemu_coroutine_self(), ret
);
2080 static int qcow2_inactivate(BlockDriverState
*bs
)
2082 BDRVQcow2State
*s
= bs
->opaque
;
2083 int ret
, result
= 0;
2084 Error
*local_err
= NULL
;
2086 qcow2_store_persistent_dirty_bitmaps(bs
, &local_err
);
2087 if (local_err
!= NULL
) {
2089 error_report_err(local_err
);
2090 error_report("Persistent bitmaps are lost for node '%s'",
2091 bdrv_get_device_or_node_name(bs
));
2094 ret
= qcow2_cache_flush(bs
, s
->l2_table_cache
);
2097 error_report("Failed to flush the L2 table cache: %s",
2101 ret
= qcow2_cache_flush(bs
, s
->refcount_block_cache
);
2104 error_report("Failed to flush the refcount block cache: %s",
2109 qcow2_mark_clean(bs
);
2115 static void qcow2_close(BlockDriverState
*bs
)
2117 BDRVQcow2State
*s
= bs
->opaque
;
2118 qemu_vfree(s
->l1_table
);
2119 /* else pre-write overlap checks in cache_destroy may crash */
2122 if (!(s
->flags
& BDRV_O_INACTIVE
)) {
2123 qcow2_inactivate(bs
);
2126 cache_clean_timer_del(bs
);
2127 qcow2_cache_destroy(s
->l2_table_cache
);
2128 qcow2_cache_destroy(s
->refcount_block_cache
);
2130 qcrypto_block_free(s
->crypto
);
2133 g_free(s
->unknown_header_fields
);
2134 cleanup_unknown_header_ext(bs
);
2136 g_free(s
->image_backing_file
);
2137 g_free(s
->image_backing_format
);
2139 g_free(s
->cluster_cache
);
2140 qemu_vfree(s
->cluster_data
);
2141 qcow2_refcount_close(bs
);
2142 qcow2_free_snapshots(bs
);
2145 static void coroutine_fn
qcow2_co_invalidate_cache(BlockDriverState
*bs
,
2148 BDRVQcow2State
*s
= bs
->opaque
;
2149 int flags
= s
->flags
;
2150 QCryptoBlock
*crypto
= NULL
;
2152 Error
*local_err
= NULL
;
2156 * Backing files are read-only which makes all of their metadata immutable,
2157 * that means we don't have to worry about reopening them here.
2165 memset(s
, 0, sizeof(BDRVQcow2State
));
2166 options
= qdict_clone_shallow(bs
->options
);
2168 flags
&= ~BDRV_O_INACTIVE
;
2169 qemu_co_mutex_lock(&s
->lock
);
2170 ret
= qcow2_do_open(bs
, options
, flags
, &local_err
);
2171 qemu_co_mutex_unlock(&s
->lock
);
2174 error_propagate(errp
, local_err
);
2175 error_prepend(errp
, "Could not reopen qcow2 layer: ");
2178 } else if (ret
< 0) {
2179 error_setg_errno(errp
, -ret
, "Could not reopen qcow2 layer");
2187 static size_t header_ext_add(char *buf
, uint32_t magic
, const void *s
,
2188 size_t len
, size_t buflen
)
2190 QCowExtension
*ext_backing_fmt
= (QCowExtension
*) buf
;
2191 size_t ext_len
= sizeof(QCowExtension
) + ((len
+ 7) & ~7);
2193 if (buflen
< ext_len
) {
2197 *ext_backing_fmt
= (QCowExtension
) {
2198 .magic
= cpu_to_be32(magic
),
2199 .len
= cpu_to_be32(len
),
2203 memcpy(buf
+ sizeof(QCowExtension
), s
, len
);
2210 * Updates the qcow2 header, including the variable length parts of it, i.e.
2211 * the backing file name and all extensions. qcow2 was not designed to allow
2212 * such changes, so if we run out of space (we can only use the first cluster)
2213 * this function may fail.
2215 * Returns 0 on success, -errno in error cases.
2217 int qcow2_update_header(BlockDriverState
*bs
)
2219 BDRVQcow2State
*s
= bs
->opaque
;
2222 size_t buflen
= s
->cluster_size
;
2224 uint64_t total_size
;
2225 uint32_t refcount_table_clusters
;
2226 size_t header_length
;
2227 Qcow2UnknownHeaderExtension
*uext
;
2229 buf
= qemu_blockalign(bs
, buflen
);
2231 /* Header structure */
2232 header
= (QCowHeader
*) buf
;
2234 if (buflen
< sizeof(*header
)) {
2239 header_length
= sizeof(*header
) + s
->unknown_header_fields_size
;
2240 total_size
= bs
->total_sectors
* BDRV_SECTOR_SIZE
;
2241 refcount_table_clusters
= s
->refcount_table_size
>> (s
->cluster_bits
- 3);
2243 *header
= (QCowHeader
) {
2244 /* Version 2 fields */
2245 .magic
= cpu_to_be32(QCOW_MAGIC
),
2246 .version
= cpu_to_be32(s
->qcow_version
),
2247 .backing_file_offset
= 0,
2248 .backing_file_size
= 0,
2249 .cluster_bits
= cpu_to_be32(s
->cluster_bits
),
2250 .size
= cpu_to_be64(total_size
),
2251 .crypt_method
= cpu_to_be32(s
->crypt_method_header
),
2252 .l1_size
= cpu_to_be32(s
->l1_size
),
2253 .l1_table_offset
= cpu_to_be64(s
->l1_table_offset
),
2254 .refcount_table_offset
= cpu_to_be64(s
->refcount_table_offset
),
2255 .refcount_table_clusters
= cpu_to_be32(refcount_table_clusters
),
2256 .nb_snapshots
= cpu_to_be32(s
->nb_snapshots
),
2257 .snapshots_offset
= cpu_to_be64(s
->snapshots_offset
),
2259 /* Version 3 fields */
2260 .incompatible_features
= cpu_to_be64(s
->incompatible_features
),
2261 .compatible_features
= cpu_to_be64(s
->compatible_features
),
2262 .autoclear_features
= cpu_to_be64(s
->autoclear_features
),
2263 .refcount_order
= cpu_to_be32(s
->refcount_order
),
2264 .header_length
= cpu_to_be32(header_length
),
2267 /* For older versions, write a shorter header */
2268 switch (s
->qcow_version
) {
2270 ret
= offsetof(QCowHeader
, incompatible_features
);
2273 ret
= sizeof(*header
);
2282 memset(buf
, 0, buflen
);
2284 /* Preserve any unknown field in the header */
2285 if (s
->unknown_header_fields_size
) {
2286 if (buflen
< s
->unknown_header_fields_size
) {
2291 memcpy(buf
, s
->unknown_header_fields
, s
->unknown_header_fields_size
);
2292 buf
+= s
->unknown_header_fields_size
;
2293 buflen
-= s
->unknown_header_fields_size
;
2296 /* Backing file format header extension */
2297 if (s
->image_backing_format
) {
2298 ret
= header_ext_add(buf
, QCOW2_EXT_MAGIC_BACKING_FORMAT
,
2299 s
->image_backing_format
,
2300 strlen(s
->image_backing_format
),
2310 /* Full disk encryption header pointer extension */
2311 if (s
->crypto_header
.offset
!= 0) {
2312 cpu_to_be64s(&s
->crypto_header
.offset
);
2313 cpu_to_be64s(&s
->crypto_header
.length
);
2314 ret
= header_ext_add(buf
, QCOW2_EXT_MAGIC_CRYPTO_HEADER
,
2315 &s
->crypto_header
, sizeof(s
->crypto_header
),
2317 be64_to_cpus(&s
->crypto_header
.offset
);
2318 be64_to_cpus(&s
->crypto_header
.length
);
2327 if (s
->qcow_version
>= 3) {
2328 Qcow2Feature features
[] = {
2330 .type
= QCOW2_FEAT_TYPE_INCOMPATIBLE
,
2331 .bit
= QCOW2_INCOMPAT_DIRTY_BITNR
,
2332 .name
= "dirty bit",
2335 .type
= QCOW2_FEAT_TYPE_INCOMPATIBLE
,
2336 .bit
= QCOW2_INCOMPAT_CORRUPT_BITNR
,
2337 .name
= "corrupt bit",
2340 .type
= QCOW2_FEAT_TYPE_COMPATIBLE
,
2341 .bit
= QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR
,
2342 .name
= "lazy refcounts",
2346 ret
= header_ext_add(buf
, QCOW2_EXT_MAGIC_FEATURE_TABLE
,
2347 features
, sizeof(features
), buflen
);
2355 /* Bitmap extension */
2356 if (s
->nb_bitmaps
> 0) {
2357 Qcow2BitmapHeaderExt bitmaps_header
= {
2358 .nb_bitmaps
= cpu_to_be32(s
->nb_bitmaps
),
2359 .bitmap_directory_size
=
2360 cpu_to_be64(s
->bitmap_directory_size
),
2361 .bitmap_directory_offset
=
2362 cpu_to_be64(s
->bitmap_directory_offset
)
2364 ret
= header_ext_add(buf
, QCOW2_EXT_MAGIC_BITMAPS
,
2365 &bitmaps_header
, sizeof(bitmaps_header
),
2374 /* Keep unknown header extensions */
2375 QLIST_FOREACH(uext
, &s
->unknown_header_ext
, next
) {
2376 ret
= header_ext_add(buf
, uext
->magic
, uext
->data
, uext
->len
, buflen
);
2385 /* End of header extensions */
2386 ret
= header_ext_add(buf
, QCOW2_EXT_MAGIC_END
, NULL
, 0, buflen
);
2394 /* Backing file name */
2395 if (s
->image_backing_file
) {
2396 size_t backing_file_len
= strlen(s
->image_backing_file
);
2398 if (buflen
< backing_file_len
) {
2403 /* Using strncpy is ok here, since buf is not NUL-terminated. */
2404 strncpy(buf
, s
->image_backing_file
, buflen
);
2406 header
->backing_file_offset
= cpu_to_be64(buf
- ((char*) header
));
2407 header
->backing_file_size
= cpu_to_be32(backing_file_len
);
2410 /* Write the new header */
2411 ret
= bdrv_pwrite(bs
->file
, 0, header
, s
->cluster_size
);
2422 static int qcow2_change_backing_file(BlockDriverState
*bs
,
2423 const char *backing_file
, const char *backing_fmt
)
2425 BDRVQcow2State
*s
= bs
->opaque
;
2427 if (backing_file
&& strlen(backing_file
) > 1023) {
2431 pstrcpy(bs
->backing_file
, sizeof(bs
->backing_file
), backing_file
?: "");
2432 pstrcpy(bs
->backing_format
, sizeof(bs
->backing_format
), backing_fmt
?: "");
2434 g_free(s
->image_backing_file
);
2435 g_free(s
->image_backing_format
);
2437 s
->image_backing_file
= backing_file
? g_strdup(bs
->backing_file
) : NULL
;
2438 s
->image_backing_format
= backing_fmt
? g_strdup(bs
->backing_format
) : NULL
;
2440 return qcow2_update_header(bs
);
2443 static int qcow2_crypt_method_from_format(const char *encryptfmt
)
2445 if (g_str_equal(encryptfmt
, "luks")) {
2446 return QCOW_CRYPT_LUKS
;
2447 } else if (g_str_equal(encryptfmt
, "aes")) {
2448 return QCOW_CRYPT_AES
;
2454 static int qcow2_set_up_encryption(BlockDriverState
*bs
, const char *encryptfmt
,
2455 QemuOpts
*opts
, Error
**errp
)
2457 BDRVQcow2State
*s
= bs
->opaque
;
2458 QCryptoBlockCreateOptions
*cryptoopts
= NULL
;
2459 QCryptoBlock
*crypto
= NULL
;
2461 QDict
*options
, *encryptopts
;
2464 options
= qemu_opts_to_qdict(opts
, NULL
);
2465 qdict_extract_subqdict(options
, &encryptopts
, "encrypt.");
2468 fmt
= qcow2_crypt_method_from_format(encryptfmt
);
2471 case QCOW_CRYPT_LUKS
:
2472 cryptoopts
= block_crypto_create_opts_init(
2473 Q_CRYPTO_BLOCK_FORMAT_LUKS
, encryptopts
, errp
);
2475 case QCOW_CRYPT_AES
:
2476 cryptoopts
= block_crypto_create_opts_init(
2477 Q_CRYPTO_BLOCK_FORMAT_QCOW
, encryptopts
, errp
);
2480 error_setg(errp
, "Unknown encryption format '%s'", encryptfmt
);
2487 s
->crypt_method_header
= fmt
;
2489 crypto
= qcrypto_block_create(cryptoopts
, "encrypt.",
2490 qcow2_crypto_hdr_init_func
,
2491 qcow2_crypto_hdr_write_func
,
2498 ret
= qcow2_update_header(bs
);
2500 error_setg_errno(errp
, -ret
, "Could not write encryption header");
2505 QDECREF(encryptopts
);
2506 qcrypto_block_free(crypto
);
2507 qapi_free_QCryptoBlockCreateOptions(cryptoopts
);
2512 typedef struct PreallocCo
{
2513 BlockDriverState
*bs
;
2515 uint64_t new_length
;
2521 * Preallocates metadata structures for data clusters between @offset (in the
2522 * guest disk) and @new_length (which is thus generally the new guest disk
2525 * Returns: 0 on success, -errno on failure.
2527 static void coroutine_fn
preallocate_co(void *opaque
)
2529 PreallocCo
*params
= opaque
;
2530 BlockDriverState
*bs
= params
->bs
;
2531 uint64_t offset
= params
->offset
;
2532 uint64_t new_length
= params
->new_length
;
2533 BDRVQcow2State
*s
= bs
->opaque
;
2535 uint64_t host_offset
= 0;
2536 unsigned int cur_bytes
;
2540 qemu_co_mutex_lock(&s
->lock
);
2542 assert(offset
<= new_length
);
2543 bytes
= new_length
- offset
;
2546 cur_bytes
= MIN(bytes
, INT_MAX
);
2547 ret
= qcow2_alloc_cluster_offset(bs
, offset
, &cur_bytes
,
2548 &host_offset
, &meta
);
2554 QCowL2Meta
*next
= meta
->next
;
2556 ret
= qcow2_alloc_cluster_link_l2(bs
, meta
);
2558 qcow2_free_any_clusters(bs
, meta
->alloc_offset
,
2559 meta
->nb_clusters
, QCOW2_DISCARD_NEVER
);
2563 /* There are no dependent requests, but we need to remove our
2564 * request from the list of in-flight requests */
2565 QLIST_REMOVE(meta
, next_in_flight
);
2571 /* TODO Preallocate data if requested */
2574 offset
+= cur_bytes
;
2578 * It is expected that the image file is large enough to actually contain
2579 * all of the allocated clusters (otherwise we get failing reads after
2580 * EOF). Extend the image to the last allocated sector.
2582 if (host_offset
!= 0) {
2584 ret
= bdrv_pwrite(bs
->file
, (host_offset
+ cur_bytes
) - 1,
2594 qemu_co_mutex_unlock(&s
->lock
);
2598 static int preallocate(BlockDriverState
*bs
,
2599 uint64_t offset
, uint64_t new_length
)
2601 PreallocCo params
= {
2604 .new_length
= new_length
,
2605 .ret
= -EINPROGRESS
,
2608 if (qemu_in_coroutine()) {
2609 preallocate_co(¶ms
);
2611 Coroutine
*co
= qemu_coroutine_create(preallocate_co
, ¶ms
);
2612 bdrv_coroutine_enter(bs
, co
);
2613 BDRV_POLL_WHILE(bs
, params
.ret
== -EINPROGRESS
);
2618 /* qcow2_refcount_metadata_size:
2619 * @clusters: number of clusters to refcount (including data and L1/L2 tables)
2620 * @cluster_size: size of a cluster, in bytes
2621 * @refcount_order: refcount bits power-of-2 exponent
2622 * @generous_increase: allow for the refcount table to be 1.5x as large as it
2625 * Returns: Number of bytes required for refcount blocks and table metadata.
2627 int64_t qcow2_refcount_metadata_size(int64_t clusters
, size_t cluster_size
,
2628 int refcount_order
, bool generous_increase
,
2629 uint64_t *refblock_count
)
2632 * Every host cluster is reference-counted, including metadata (even
2633 * refcount metadata is recursively included).
2635 * An accurate formula for the size of refcount metadata size is difficult
2636 * to derive. An easier method of calculation is finding the fixed point
2637 * where no further refcount blocks or table clusters are required to
2638 * reference count every cluster.
2640 int64_t blocks_per_table_cluster
= cluster_size
/ sizeof(uint64_t);
2641 int64_t refcounts_per_block
= cluster_size
* 8 / (1 << refcount_order
);
2642 int64_t table
= 0; /* number of refcount table clusters */
2643 int64_t blocks
= 0; /* number of refcount block clusters */
2649 blocks
= DIV_ROUND_UP(clusters
+ table
+ blocks
, refcounts_per_block
);
2650 table
= DIV_ROUND_UP(blocks
, blocks_per_table_cluster
);
2651 n
= clusters
+ blocks
+ table
;
2653 if (n
== last
&& generous_increase
) {
2654 clusters
+= DIV_ROUND_UP(table
, 2);
2655 n
= 0; /* force another loop */
2656 generous_increase
= false;
2658 } while (n
!= last
);
2660 if (refblock_count
) {
2661 *refblock_count
= blocks
;
2664 return (blocks
+ table
) * cluster_size
;
2668 * qcow2_calc_prealloc_size:
2669 * @total_size: virtual disk size in bytes
2670 * @cluster_size: cluster size in bytes
2671 * @refcount_order: refcount bits power-of-2 exponent
2673 * Returns: Total number of bytes required for the fully allocated image
2674 * (including metadata).
2676 static int64_t qcow2_calc_prealloc_size(int64_t total_size
,
2677 size_t cluster_size
,
2680 int64_t meta_size
= 0;
2681 uint64_t nl1e
, nl2e
;
2682 int64_t aligned_total_size
= ROUND_UP(total_size
, cluster_size
);
2684 /* header: 1 cluster */
2685 meta_size
+= cluster_size
;
2687 /* total size of L2 tables */
2688 nl2e
= aligned_total_size
/ cluster_size
;
2689 nl2e
= ROUND_UP(nl2e
, cluster_size
/ sizeof(uint64_t));
2690 meta_size
+= nl2e
* sizeof(uint64_t);
2692 /* total size of L1 tables */
2693 nl1e
= nl2e
* sizeof(uint64_t) / cluster_size
;
2694 nl1e
= ROUND_UP(nl1e
, cluster_size
/ sizeof(uint64_t));
2695 meta_size
+= nl1e
* sizeof(uint64_t);
2697 /* total size of refcount table and blocks */
2698 meta_size
+= qcow2_refcount_metadata_size(
2699 (meta_size
+ aligned_total_size
) / cluster_size
,
2700 cluster_size
, refcount_order
, false, NULL
);
2702 return meta_size
+ aligned_total_size
;
2705 static size_t qcow2_opt_get_cluster_size_del(QemuOpts
*opts
, Error
**errp
)
2707 size_t cluster_size
;
2710 cluster_size
= qemu_opt_get_size_del(opts
, BLOCK_OPT_CLUSTER_SIZE
,
2711 DEFAULT_CLUSTER_SIZE
);
2712 cluster_bits
= ctz32(cluster_size
);
2713 if (cluster_bits
< MIN_CLUSTER_BITS
|| cluster_bits
> MAX_CLUSTER_BITS
||
2714 (1 << cluster_bits
) != cluster_size
)
2716 error_setg(errp
, "Cluster size must be a power of two between %d and "
2717 "%dk", 1 << MIN_CLUSTER_BITS
, 1 << (MAX_CLUSTER_BITS
- 10));
2720 return cluster_size
;
2723 static int qcow2_opt_get_version_del(QemuOpts
*opts
, Error
**errp
)
2728 buf
= qemu_opt_get_del(opts
, BLOCK_OPT_COMPAT_LEVEL
);
2730 ret
= 3; /* default */
2731 } else if (!strcmp(buf
, "0.10")) {
2733 } else if (!strcmp(buf
, "1.1")) {
2736 error_setg(errp
, "Invalid compatibility level: '%s'", buf
);
2743 static uint64_t qcow2_opt_get_refcount_bits_del(QemuOpts
*opts
, int version
,
2746 uint64_t refcount_bits
;
2748 refcount_bits
= qemu_opt_get_number_del(opts
, BLOCK_OPT_REFCOUNT_BITS
, 16);
2749 if (refcount_bits
> 64 || !is_power_of_2(refcount_bits
)) {
2750 error_setg(errp
, "Refcount width must be a power of two and may not "
2755 if (version
< 3 && refcount_bits
!= 16) {
2756 error_setg(errp
, "Different refcount widths than 16 bits require "
2757 "compatibility level 1.1 or above (use compat=1.1 or "
2762 return refcount_bits
;
2765 static int coroutine_fn
2766 qcow2_co_create2(const char *filename
, int64_t total_size
,
2767 const char *backing_file
, const char *backing_format
,
2768 int flags
, size_t cluster_size
, PreallocMode prealloc
,
2769 QemuOpts
*opts
, int version
, int refcount_order
,
2770 const char *encryptfmt
, Error
**errp
)
2775 * Open the image file and write a minimal qcow2 header.
2777 * We keep things simple and start with a zero-sized image. We also
2778 * do without refcount blocks or a L1 table for now. We'll fix the
2779 * inconsistency later.
2781 * We do need a refcount table because growing the refcount table means
2782 * allocating two new refcount blocks - the seconds of which would be at
2783 * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
2784 * size for any qcow2 image.
2788 uint64_t* refcount_table
;
2789 Error
*local_err
= NULL
;
2792 if (prealloc
== PREALLOC_MODE_FULL
|| prealloc
== PREALLOC_MODE_FALLOC
) {
2793 int64_t prealloc_size
=
2794 qcow2_calc_prealloc_size(total_size
, cluster_size
, refcount_order
);
2795 qemu_opt_set_number(opts
, BLOCK_OPT_SIZE
, prealloc_size
, &error_abort
);
2796 qemu_opt_set(opts
, BLOCK_OPT_PREALLOC
, PreallocMode_str(prealloc
),
2800 ret
= bdrv_create_file(filename
, opts
, &local_err
);
2802 error_propagate(errp
, local_err
);
2806 blk
= blk_new_open(filename
, NULL
, NULL
,
2807 BDRV_O_RDWR
| BDRV_O_RESIZE
| BDRV_O_PROTOCOL
,
2810 error_propagate(errp
, local_err
);
2814 blk_set_allow_write_beyond_eof(blk
, true);
2816 /* Write the header */
2817 QEMU_BUILD_BUG_ON((1 << MIN_CLUSTER_BITS
) < sizeof(*header
));
2818 header
= g_malloc0(cluster_size
);
2819 *header
= (QCowHeader
) {
2820 .magic
= cpu_to_be32(QCOW_MAGIC
),
2821 .version
= cpu_to_be32(version
),
2822 .cluster_bits
= cpu_to_be32(ctz32(cluster_size
)),
2823 .size
= cpu_to_be64(0),
2824 .l1_table_offset
= cpu_to_be64(0),
2825 .l1_size
= cpu_to_be32(0),
2826 .refcount_table_offset
= cpu_to_be64(cluster_size
),
2827 .refcount_table_clusters
= cpu_to_be32(1),
2828 .refcount_order
= cpu_to_be32(refcount_order
),
2829 .header_length
= cpu_to_be32(sizeof(*header
)),
2832 /* We'll update this to correct value later */
2833 header
->crypt_method
= cpu_to_be32(QCOW_CRYPT_NONE
);
2835 if (flags
& BLOCK_FLAG_LAZY_REFCOUNTS
) {
2836 header
->compatible_features
|=
2837 cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS
);
2840 ret
= blk_pwrite(blk
, 0, header
, cluster_size
, 0);
2843 error_setg_errno(errp
, -ret
, "Could not write qcow2 header");
2847 /* Write a refcount table with one refcount block */
2848 refcount_table
= g_malloc0(2 * cluster_size
);
2849 refcount_table
[0] = cpu_to_be64(2 * cluster_size
);
2850 ret
= blk_pwrite(blk
, cluster_size
, refcount_table
, 2 * cluster_size
, 0);
2851 g_free(refcount_table
);
2854 error_setg_errno(errp
, -ret
, "Could not write refcount table");
2862 * And now open the image and make it consistent first (i.e. increase the
2863 * refcount of the cluster that is occupied by the header and the refcount
2866 options
= qdict_new();
2867 qdict_put_str(options
, "driver", "qcow2");
2868 blk
= blk_new_open(filename
, NULL
, options
,
2869 BDRV_O_RDWR
| BDRV_O_RESIZE
| BDRV_O_NO_FLUSH
,
2872 error_propagate(errp
, local_err
);
2877 ret
= qcow2_alloc_clusters(blk_bs(blk
), 3 * cluster_size
);
2879 error_setg_errno(errp
, -ret
, "Could not allocate clusters for qcow2 "
2880 "header and refcount table");
2883 } else if (ret
!= 0) {
2884 error_report("Huh, first cluster in empty image is already in use?");
2888 /* Create a full header (including things like feature table) */
2889 ret
= qcow2_update_header(blk_bs(blk
));
2891 error_setg_errno(errp
, -ret
, "Could not update qcow2 header");
2895 /* Okay, now that we have a valid image, let's give it the right size */
2896 ret
= blk_truncate(blk
, total_size
, PREALLOC_MODE_OFF
, errp
);
2898 error_prepend(errp
, "Could not resize image: ");
2902 /* Want a backing file? There you go.*/
2904 ret
= bdrv_change_backing_file(blk_bs(blk
), backing_file
, backing_format
);
2906 error_setg_errno(errp
, -ret
, "Could not assign backing file '%s' "
2907 "with format '%s'", backing_file
, backing_format
);
2912 /* Want encryption? There you go. */
2914 ret
= qcow2_set_up_encryption(blk_bs(blk
), encryptfmt
, opts
, errp
);
2920 /* And if we're supposed to preallocate metadata, do that now */
2921 if (prealloc
!= PREALLOC_MODE_OFF
) {
2922 ret
= preallocate(blk_bs(blk
), 0, total_size
);
2924 error_setg_errno(errp
, -ret
, "Could not preallocate metadata");
2932 /* Reopen the image without BDRV_O_NO_FLUSH to flush it before returning.
2933 * Using BDRV_O_NO_IO, since encryption is now setup we don't want to
2934 * have to setup decryption context. We're not doing any I/O on the top
2935 * level BlockDriverState, only lower layers, where BDRV_O_NO_IO does
2938 options
= qdict_new();
2939 qdict_put_str(options
, "driver", "qcow2");
2940 blk
= blk_new_open(filename
, NULL
, options
,
2941 BDRV_O_RDWR
| BDRV_O_NO_BACKING
| BDRV_O_NO_IO
,
2944 error_propagate(errp
, local_err
);
2957 static int coroutine_fn
qcow2_co_create_opts(const char *filename
, QemuOpts
*opts
,
2960 char *backing_file
= NULL
;
2961 char *backing_fmt
= NULL
;
2965 size_t cluster_size
= DEFAULT_CLUSTER_SIZE
;
2966 PreallocMode prealloc
;
2968 uint64_t refcount_bits
;
2970 char *encryptfmt
= NULL
;
2971 Error
*local_err
= NULL
;
2974 /* Read out options */
2975 size
= ROUND_UP(qemu_opt_get_size_del(opts
, BLOCK_OPT_SIZE
, 0),
2977 backing_file
= qemu_opt_get_del(opts
, BLOCK_OPT_BACKING_FILE
);
2978 backing_fmt
= qemu_opt_get_del(opts
, BLOCK_OPT_BACKING_FMT
);
2979 encryptfmt
= qemu_opt_get_del(opts
, BLOCK_OPT_ENCRYPT_FORMAT
);
2981 if (qemu_opt_get(opts
, BLOCK_OPT_ENCRYPT
)) {
2982 error_setg(errp
, "Options " BLOCK_OPT_ENCRYPT
" and "
2983 BLOCK_OPT_ENCRYPT_FORMAT
" are mutually exclusive");
2987 } else if (qemu_opt_get_bool_del(opts
, BLOCK_OPT_ENCRYPT
, false)) {
2988 encryptfmt
= g_strdup("aes");
2990 cluster_size
= qcow2_opt_get_cluster_size_del(opts
, &local_err
);
2992 error_propagate(errp
, local_err
);
2996 buf
= qemu_opt_get_del(opts
, BLOCK_OPT_PREALLOC
);
2997 prealloc
= qapi_enum_parse(&PreallocMode_lookup
, buf
,
2998 PREALLOC_MODE_OFF
, &local_err
);
3000 error_propagate(errp
, local_err
);
3005 version
= qcow2_opt_get_version_del(opts
, &local_err
);
3007 error_propagate(errp
, local_err
);
3012 if (qemu_opt_get_bool_del(opts
, BLOCK_OPT_LAZY_REFCOUNTS
, false)) {
3013 flags
|= BLOCK_FLAG_LAZY_REFCOUNTS
;
3016 if (backing_file
&& prealloc
!= PREALLOC_MODE_OFF
) {
3017 error_setg(errp
, "Backing file and preallocation cannot be used at "
3023 if (version
< 3 && (flags
& BLOCK_FLAG_LAZY_REFCOUNTS
)) {
3024 error_setg(errp
, "Lazy refcounts only supported with compatibility "
3025 "level 1.1 and above (use compat=1.1 or greater)");
3030 refcount_bits
= qcow2_opt_get_refcount_bits_del(opts
, version
, &local_err
);
3032 error_propagate(errp
, local_err
);
3037 refcount_order
= ctz32(refcount_bits
);
3039 ret
= qcow2_co_create2(filename
, size
, backing_file
, backing_fmt
, flags
,
3040 cluster_size
, prealloc
, opts
, version
, refcount_order
,
3041 encryptfmt
, &local_err
);
3042 error_propagate(errp
, local_err
);
3045 g_free(backing_file
);
3046 g_free(backing_fmt
);
3053 static bool is_zero(BlockDriverState
*bs
, int64_t offset
, int64_t bytes
)
3058 /* Clamp to image length, before checking status of underlying sectors */
3059 if (offset
+ bytes
> bs
->total_sectors
* BDRV_SECTOR_SIZE
) {
3060 bytes
= bs
->total_sectors
* BDRV_SECTOR_SIZE
- offset
;
3066 res
= bdrv_block_status_above(bs
, NULL
, offset
, bytes
, &nr
, NULL
, NULL
);
3067 return res
>= 0 && (res
& BDRV_BLOCK_ZERO
) && nr
== bytes
;
3070 static coroutine_fn
int qcow2_co_pwrite_zeroes(BlockDriverState
*bs
,
3071 int64_t offset
, int bytes
, BdrvRequestFlags flags
)
3074 BDRVQcow2State
*s
= bs
->opaque
;
3076 uint32_t head
= offset
% s
->cluster_size
;
3077 uint32_t tail
= (offset
+ bytes
) % s
->cluster_size
;
3079 trace_qcow2_pwrite_zeroes_start_req(qemu_coroutine_self(), offset
, bytes
);
3080 if (offset
+ bytes
== bs
->total_sectors
* BDRV_SECTOR_SIZE
) {
3088 assert(head
+ bytes
<= s
->cluster_size
);
3090 /* check whether remainder of cluster already reads as zero */
3091 if (!(is_zero(bs
, offset
- head
, head
) &&
3092 is_zero(bs
, offset
+ bytes
,
3093 tail
? s
->cluster_size
- tail
: 0))) {
3097 qemu_co_mutex_lock(&s
->lock
);
3098 /* We can have new write after previous check */
3099 offset
= QEMU_ALIGN_DOWN(offset
, s
->cluster_size
);
3100 bytes
= s
->cluster_size
;
3101 nr
= s
->cluster_size
;
3102 ret
= qcow2_get_cluster_offset(bs
, offset
, &nr
, &off
);
3103 if (ret
!= QCOW2_CLUSTER_UNALLOCATED
&&
3104 ret
!= QCOW2_CLUSTER_ZERO_PLAIN
&&
3105 ret
!= QCOW2_CLUSTER_ZERO_ALLOC
) {
3106 qemu_co_mutex_unlock(&s
->lock
);
3110 qemu_co_mutex_lock(&s
->lock
);
3113 trace_qcow2_pwrite_zeroes(qemu_coroutine_self(), offset
, bytes
);
3115 /* Whatever is left can use real zero clusters */
3116 ret
= qcow2_cluster_zeroize(bs
, offset
, bytes
, flags
);
3117 qemu_co_mutex_unlock(&s
->lock
);
3122 static coroutine_fn
int qcow2_co_pdiscard(BlockDriverState
*bs
,
3123 int64_t offset
, int bytes
)
3126 BDRVQcow2State
*s
= bs
->opaque
;
3128 if (!QEMU_IS_ALIGNED(offset
| bytes
, s
->cluster_size
)) {
3129 assert(bytes
< s
->cluster_size
);
3130 /* Ignore partial clusters, except for the special case of the
3131 * complete partial cluster at the end of an unaligned file */
3132 if (!QEMU_IS_ALIGNED(offset
, s
->cluster_size
) ||
3133 offset
+ bytes
!= bs
->total_sectors
* BDRV_SECTOR_SIZE
) {
3138 qemu_co_mutex_lock(&s
->lock
);
3139 ret
= qcow2_cluster_discard(bs
, offset
, bytes
, QCOW2_DISCARD_REQUEST
,
3141 qemu_co_mutex_unlock(&s
->lock
);
3145 static int qcow2_truncate(BlockDriverState
*bs
, int64_t offset
,
3146 PreallocMode prealloc
, Error
**errp
)
3148 BDRVQcow2State
*s
= bs
->opaque
;
3149 uint64_t old_length
;
3150 int64_t new_l1_size
;
3153 if (prealloc
!= PREALLOC_MODE_OFF
&& prealloc
!= PREALLOC_MODE_METADATA
&&
3154 prealloc
!= PREALLOC_MODE_FALLOC
&& prealloc
!= PREALLOC_MODE_FULL
)
3156 error_setg(errp
, "Unsupported preallocation mode '%s'",
3157 PreallocMode_str(prealloc
));
3162 error_setg(errp
, "The new size must be a multiple of 512");
3166 /* cannot proceed if image has snapshots */
3167 if (s
->nb_snapshots
) {
3168 error_setg(errp
, "Can't resize an image which has snapshots");
3172 /* cannot proceed if image has bitmaps */
3173 if (s
->nb_bitmaps
) {
3174 /* TODO: resize bitmaps in the image */
3175 error_setg(errp
, "Can't resize an image which has bitmaps");
3179 old_length
= bs
->total_sectors
* 512;
3180 new_l1_size
= size_to_l1(s
, offset
);
3182 if (offset
< old_length
) {
3183 int64_t last_cluster
, old_file_size
;
3184 if (prealloc
!= PREALLOC_MODE_OFF
) {
3186 "Preallocation can't be used for shrinking an image");
3190 ret
= qcow2_cluster_discard(bs
, ROUND_UP(offset
, s
->cluster_size
),
3191 old_length
- ROUND_UP(offset
,
3193 QCOW2_DISCARD_ALWAYS
, true);
3195 error_setg_errno(errp
, -ret
, "Failed to discard cropped clusters");
3199 ret
= qcow2_shrink_l1_table(bs
, new_l1_size
);
3201 error_setg_errno(errp
, -ret
,
3202 "Failed to reduce the number of L2 tables");
3206 ret
= qcow2_shrink_reftable(bs
);
3208 error_setg_errno(errp
, -ret
,
3209 "Failed to discard unused refblocks");
3213 old_file_size
= bdrv_getlength(bs
->file
->bs
);
3214 if (old_file_size
< 0) {
3215 error_setg_errno(errp
, -old_file_size
,
3216 "Failed to inquire current file length");
3217 return old_file_size
;
3219 last_cluster
= qcow2_get_last_cluster(bs
, old_file_size
);
3220 if (last_cluster
< 0) {
3221 error_setg_errno(errp
, -last_cluster
,
3222 "Failed to find the last cluster");
3223 return last_cluster
;
3225 if ((last_cluster
+ 1) * s
->cluster_size
< old_file_size
) {
3226 Error
*local_err
= NULL
;
3228 bdrv_truncate(bs
->file
, (last_cluster
+ 1) * s
->cluster_size
,
3229 PREALLOC_MODE_OFF
, &local_err
);
3231 warn_reportf_err(local_err
,
3232 "Failed to truncate the tail of the image: ");
3236 ret
= qcow2_grow_l1_table(bs
, new_l1_size
, true);
3238 error_setg_errno(errp
, -ret
, "Failed to grow the L1 table");
3244 case PREALLOC_MODE_OFF
:
3247 case PREALLOC_MODE_METADATA
:
3248 ret
= preallocate(bs
, old_length
, offset
);
3250 error_setg_errno(errp
, -ret
, "Preallocation failed");
3255 case PREALLOC_MODE_FALLOC
:
3256 case PREALLOC_MODE_FULL
:
3258 int64_t allocation_start
, host_offset
, guest_offset
;
3259 int64_t clusters_allocated
;
3260 int64_t old_file_size
, new_file_size
;
3261 uint64_t nb_new_data_clusters
, nb_new_l2_tables
;
3263 old_file_size
= bdrv_getlength(bs
->file
->bs
);
3264 if (old_file_size
< 0) {
3265 error_setg_errno(errp
, -old_file_size
,
3266 "Failed to inquire current file length");
3267 return old_file_size
;
3269 old_file_size
= ROUND_UP(old_file_size
, s
->cluster_size
);
3271 nb_new_data_clusters
= DIV_ROUND_UP(offset
- old_length
,
3274 /* This is an overestimation; we will not actually allocate space for
3275 * these in the file but just make sure the new refcount structures are
3276 * able to cover them so we will not have to allocate new refblocks
3277 * while entering the data blocks in the potentially new L2 tables.
3278 * (We do not actually care where the L2 tables are placed. Maybe they
3279 * are already allocated or they can be placed somewhere before
3280 * @old_file_size. It does not matter because they will be fully
3281 * allocated automatically, so they do not need to be covered by the
3282 * preallocation. All that matters is that we will not have to allocate
3283 * new refcount structures for them.) */
3284 nb_new_l2_tables
= DIV_ROUND_UP(nb_new_data_clusters
,
3285 s
->cluster_size
/ sizeof(uint64_t));
3286 /* The cluster range may not be aligned to L2 boundaries, so add one L2
3287 * table for a potential head/tail */
3290 allocation_start
= qcow2_refcount_area(bs
, old_file_size
,
3291 nb_new_data_clusters
+
3294 if (allocation_start
< 0) {
3295 error_setg_errno(errp
, -allocation_start
,
3296 "Failed to resize refcount structures");
3297 return allocation_start
;
3300 clusters_allocated
= qcow2_alloc_clusters_at(bs
, allocation_start
,
3301 nb_new_data_clusters
);
3302 if (clusters_allocated
< 0) {
3303 error_setg_errno(errp
, -clusters_allocated
,
3304 "Failed to allocate data clusters");
3305 return -clusters_allocated
;
3308 assert(clusters_allocated
== nb_new_data_clusters
);
3310 /* Allocate the data area */
3311 new_file_size
= allocation_start
+
3312 nb_new_data_clusters
* s
->cluster_size
;
3313 ret
= bdrv_truncate(bs
->file
, new_file_size
, prealloc
, errp
);
3315 error_prepend(errp
, "Failed to resize underlying file: ");
3316 qcow2_free_clusters(bs
, allocation_start
,
3317 nb_new_data_clusters
* s
->cluster_size
,
3318 QCOW2_DISCARD_OTHER
);
3322 /* Create the necessary L2 entries */
3323 host_offset
= allocation_start
;
3324 guest_offset
= old_length
;
3325 while (nb_new_data_clusters
) {
3326 int64_t nb_clusters
= MIN(
3327 nb_new_data_clusters
,
3328 s
->l2_slice_size
- offset_to_l2_slice_index(s
, guest_offset
));
3329 QCowL2Meta allocation
= {
3330 .offset
= guest_offset
,
3331 .alloc_offset
= host_offset
,
3332 .nb_clusters
= nb_clusters
,
3334 qemu_co_queue_init(&allocation
.dependent_requests
);
3336 ret
= qcow2_alloc_cluster_link_l2(bs
, &allocation
);
3338 error_setg_errno(errp
, -ret
, "Failed to update L2 tables");
3339 qcow2_free_clusters(bs
, host_offset
,
3340 nb_new_data_clusters
* s
->cluster_size
,
3341 QCOW2_DISCARD_OTHER
);
3345 guest_offset
+= nb_clusters
* s
->cluster_size
;
3346 host_offset
+= nb_clusters
* s
->cluster_size
;
3347 nb_new_data_clusters
-= nb_clusters
;
3353 g_assert_not_reached();
3356 if (prealloc
!= PREALLOC_MODE_OFF
) {
3357 /* Flush metadata before actually changing the image size */
3358 ret
= bdrv_flush(bs
);
3360 error_setg_errno(errp
, -ret
,
3361 "Failed to flush the preallocated area to disk");
3366 /* write updated header.size */
3367 offset
= cpu_to_be64(offset
);
3368 ret
= bdrv_pwrite_sync(bs
->file
, offsetof(QCowHeader
, size
),
3369 &offset
, sizeof(uint64_t));
3371 error_setg_errno(errp
, -ret
, "Failed to update the image size");
3375 s
->l1_vm_state_index
= new_l1_size
;
3379 /* XXX: put compressed sectors first, then all the cluster aligned
3380 tables to avoid losing bytes in alignment */
3381 static coroutine_fn
int
3382 qcow2_co_pwritev_compressed(BlockDriverState
*bs
, uint64_t offset
,
3383 uint64_t bytes
, QEMUIOVector
*qiov
)
3385 BDRVQcow2State
*s
= bs
->opaque
;
3386 QEMUIOVector hd_qiov
;
3390 uint8_t *buf
, *out_buf
;
3391 int64_t cluster_offset
;
3394 /* align end of file to a sector boundary to ease reading with
3395 sector based I/Os */
3396 cluster_offset
= bdrv_getlength(bs
->file
->bs
);
3397 if (cluster_offset
< 0) {
3398 return cluster_offset
;
3400 return bdrv_truncate(bs
->file
, cluster_offset
, PREALLOC_MODE_OFF
, NULL
);
3403 if (offset_into_cluster(s
, offset
)) {
3407 buf
= qemu_blockalign(bs
, s
->cluster_size
);
3408 if (bytes
!= s
->cluster_size
) {
3409 if (bytes
> s
->cluster_size
||
3410 offset
+ bytes
!= bs
->total_sectors
<< BDRV_SECTOR_BITS
)
3415 /* Zero-pad last write if image size is not cluster aligned */
3416 memset(buf
+ bytes
, 0, s
->cluster_size
- bytes
);
3418 qemu_iovec_to_buf(qiov
, 0, buf
, bytes
);
3420 out_buf
= g_malloc(s
->cluster_size
);
3422 /* best compression, small window, no zlib header */
3423 memset(&strm
, 0, sizeof(strm
));
3424 ret
= deflateInit2(&strm
, Z_DEFAULT_COMPRESSION
,
3426 9, Z_DEFAULT_STRATEGY
);
3432 strm
.avail_in
= s
->cluster_size
;
3433 strm
.next_in
= (uint8_t *)buf
;
3434 strm
.avail_out
= s
->cluster_size
;
3435 strm
.next_out
= out_buf
;
3437 ret
= deflate(&strm
, Z_FINISH
);
3438 if (ret
!= Z_STREAM_END
&& ret
!= Z_OK
) {
3443 out_len
= strm
.next_out
- out_buf
;
3447 if (ret
!= Z_STREAM_END
|| out_len
>= s
->cluster_size
) {
3448 /* could not compress: write normal cluster */
3449 ret
= qcow2_co_pwritev(bs
, offset
, bytes
, qiov
, 0);
3456 qemu_co_mutex_lock(&s
->lock
);
3458 qcow2_alloc_compressed_cluster_offset(bs
, offset
, out_len
);
3459 if (!cluster_offset
) {
3460 qemu_co_mutex_unlock(&s
->lock
);
3464 cluster_offset
&= s
->cluster_offset_mask
;
3466 ret
= qcow2_pre_write_overlap_check(bs
, 0, cluster_offset
, out_len
);
3467 qemu_co_mutex_unlock(&s
->lock
);
3472 iov
= (struct iovec
) {
3473 .iov_base
= out_buf
,
3476 qemu_iovec_init_external(&hd_qiov
, &iov
, 1);
3478 BLKDBG_EVENT(bs
->file
, BLKDBG_WRITE_COMPRESSED
);
3479 ret
= bdrv_co_pwritev(bs
->file
, cluster_offset
, out_len
, &hd_qiov
, 0);
3491 static int make_completely_empty(BlockDriverState
*bs
)
3493 BDRVQcow2State
*s
= bs
->opaque
;
3494 Error
*local_err
= NULL
;
3495 int ret
, l1_clusters
;
3497 uint64_t *new_reftable
= NULL
;
3498 uint64_t rt_entry
, l1_size2
;
3501 uint64_t reftable_offset
;
3502 uint32_t reftable_clusters
;
3503 } QEMU_PACKED l1_ofs_rt_ofs_cls
;
3505 ret
= qcow2_cache_empty(bs
, s
->l2_table_cache
);
3510 ret
= qcow2_cache_empty(bs
, s
->refcount_block_cache
);
3515 /* Refcounts will be broken utterly */
3516 ret
= qcow2_mark_dirty(bs
);
3521 BLKDBG_EVENT(bs
->file
, BLKDBG_L1_UPDATE
);
3523 l1_clusters
= DIV_ROUND_UP(s
->l1_size
, s
->cluster_size
/ sizeof(uint64_t));
3524 l1_size2
= (uint64_t)s
->l1_size
* sizeof(uint64_t);
3526 /* After this call, neither the in-memory nor the on-disk refcount
3527 * information accurately describe the actual references */
3529 ret
= bdrv_pwrite_zeroes(bs
->file
, s
->l1_table_offset
,
3530 l1_clusters
* s
->cluster_size
, 0);
3532 goto fail_broken_refcounts
;
3534 memset(s
->l1_table
, 0, l1_size2
);
3536 BLKDBG_EVENT(bs
->file
, BLKDBG_EMPTY_IMAGE_PREPARE
);
3538 /* Overwrite enough clusters at the beginning of the sectors to place
3539 * the refcount table, a refcount block and the L1 table in; this may
3540 * overwrite parts of the existing refcount and L1 table, which is not
3541 * an issue because the dirty flag is set, complete data loss is in fact
3542 * desired and partial data loss is consequently fine as well */
3543 ret
= bdrv_pwrite_zeroes(bs
->file
, s
->cluster_size
,
3544 (2 + l1_clusters
) * s
->cluster_size
, 0);
3545 /* This call (even if it failed overall) may have overwritten on-disk
3546 * refcount structures; in that case, the in-memory refcount information
3547 * will probably differ from the on-disk information which makes the BDS
3550 goto fail_broken_refcounts
;
3553 BLKDBG_EVENT(bs
->file
, BLKDBG_L1_UPDATE
);
3554 BLKDBG_EVENT(bs
->file
, BLKDBG_REFTABLE_UPDATE
);
3556 /* "Create" an empty reftable (one cluster) directly after the image
3557 * header and an empty L1 table three clusters after the image header;
3558 * the cluster between those two will be used as the first refblock */
3559 l1_ofs_rt_ofs_cls
.l1_offset
= cpu_to_be64(3 * s
->cluster_size
);
3560 l1_ofs_rt_ofs_cls
.reftable_offset
= cpu_to_be64(s
->cluster_size
);
3561 l1_ofs_rt_ofs_cls
.reftable_clusters
= cpu_to_be32(1);
3562 ret
= bdrv_pwrite_sync(bs
->file
, offsetof(QCowHeader
, l1_table_offset
),
3563 &l1_ofs_rt_ofs_cls
, sizeof(l1_ofs_rt_ofs_cls
));
3565 goto fail_broken_refcounts
;
3568 s
->l1_table_offset
= 3 * s
->cluster_size
;
3570 new_reftable
= g_try_new0(uint64_t, s
->cluster_size
/ sizeof(uint64_t));
3571 if (!new_reftable
) {
3573 goto fail_broken_refcounts
;
3576 s
->refcount_table_offset
= s
->cluster_size
;
3577 s
->refcount_table_size
= s
->cluster_size
/ sizeof(uint64_t);
3578 s
->max_refcount_table_index
= 0;
3580 g_free(s
->refcount_table
);
3581 s
->refcount_table
= new_reftable
;
3582 new_reftable
= NULL
;
3584 /* Now the in-memory refcount information again corresponds to the on-disk
3585 * information (reftable is empty and no refblocks (the refblock cache is
3586 * empty)); however, this means some clusters (e.g. the image header) are
3587 * referenced, but not refcounted, but the normal qcow2 code assumes that
3588 * the in-memory information is always correct */
3590 BLKDBG_EVENT(bs
->file
, BLKDBG_REFBLOCK_ALLOC
);
3592 /* Enter the first refblock into the reftable */
3593 rt_entry
= cpu_to_be64(2 * s
->cluster_size
);
3594 ret
= bdrv_pwrite_sync(bs
->file
, s
->cluster_size
,
3595 &rt_entry
, sizeof(rt_entry
));
3597 goto fail_broken_refcounts
;
3599 s
->refcount_table
[0] = 2 * s
->cluster_size
;
3601 s
->free_cluster_index
= 0;
3602 assert(3 + l1_clusters
<= s
->refcount_block_size
);
3603 offset
= qcow2_alloc_clusters(bs
, 3 * s
->cluster_size
+ l1_size2
);
3606 goto fail_broken_refcounts
;
3607 } else if (offset
> 0) {
3608 error_report("First cluster in emptied image is in use");
3612 /* Now finally the in-memory information corresponds to the on-disk
3613 * structures and is correct */
3614 ret
= qcow2_mark_clean(bs
);
3619 ret
= bdrv_truncate(bs
->file
, (3 + l1_clusters
) * s
->cluster_size
,
3620 PREALLOC_MODE_OFF
, &local_err
);
3622 error_report_err(local_err
);
3628 fail_broken_refcounts
:
3629 /* The BDS is unusable at this point. If we wanted to make it usable, we
3630 * would have to call qcow2_refcount_close(), qcow2_refcount_init(),
3631 * qcow2_check_refcounts(), qcow2_refcount_close() and qcow2_refcount_init()
3632 * again. However, because the functions which could have caused this error
3633 * path to be taken are used by those functions as well, it's very likely
3634 * that that sequence will fail as well. Therefore, just eject the BDS. */
3638 g_free(new_reftable
);
3642 static int qcow2_make_empty(BlockDriverState
*bs
)
3644 BDRVQcow2State
*s
= bs
->opaque
;
3645 uint64_t offset
, end_offset
;
3646 int step
= QEMU_ALIGN_DOWN(INT_MAX
, s
->cluster_size
);
3647 int l1_clusters
, ret
= 0;
3649 l1_clusters
= DIV_ROUND_UP(s
->l1_size
, s
->cluster_size
/ sizeof(uint64_t));
3651 if (s
->qcow_version
>= 3 && !s
->snapshots
&& !s
->nb_bitmaps
&&
3652 3 + l1_clusters
<= s
->refcount_block_size
&&
3653 s
->crypt_method_header
!= QCOW_CRYPT_LUKS
) {
3654 /* The following function only works for qcow2 v3 images (it
3655 * requires the dirty flag) and only as long as there are no
3656 * features that reserve extra clusters (such as snapshots,
3657 * LUKS header, or persistent bitmaps), because it completely
3658 * empties the image. Furthermore, the L1 table and three
3659 * additional clusters (image header, refcount table, one
3660 * refcount block) have to fit inside one refcount block. */
3661 return make_completely_empty(bs
);
3664 /* This fallback code simply discards every active cluster; this is slow,
3665 * but works in all cases */
3666 end_offset
= bs
->total_sectors
* BDRV_SECTOR_SIZE
;
3667 for (offset
= 0; offset
< end_offset
; offset
+= step
) {
3668 /* As this function is generally used after committing an external
3669 * snapshot, QCOW2_DISCARD_SNAPSHOT seems appropriate. Also, the
3670 * default action for this kind of discard is to pass the discard,
3671 * which will ideally result in an actually smaller image file, as
3672 * is probably desired. */
3673 ret
= qcow2_cluster_discard(bs
, offset
, MIN(step
, end_offset
- offset
),
3674 QCOW2_DISCARD_SNAPSHOT
, true);
3683 static coroutine_fn
int qcow2_co_flush_to_os(BlockDriverState
*bs
)
3685 BDRVQcow2State
*s
= bs
->opaque
;
3688 qemu_co_mutex_lock(&s
->lock
);
3689 ret
= qcow2_write_caches(bs
);
3690 qemu_co_mutex_unlock(&s
->lock
);
3695 static BlockMeasureInfo
*qcow2_measure(QemuOpts
*opts
, BlockDriverState
*in_bs
,
3698 Error
*local_err
= NULL
;
3699 BlockMeasureInfo
*info
;
3700 uint64_t required
= 0; /* bytes that contribute to required size */
3701 uint64_t virtual_size
; /* disk size as seen by guest */
3702 uint64_t refcount_bits
;
3704 size_t cluster_size
;
3707 PreallocMode prealloc
;
3708 bool has_backing_file
;
3710 /* Parse image creation options */
3711 cluster_size
= qcow2_opt_get_cluster_size_del(opts
, &local_err
);
3716 version
= qcow2_opt_get_version_del(opts
, &local_err
);
3721 refcount_bits
= qcow2_opt_get_refcount_bits_del(opts
, version
, &local_err
);
3726 optstr
= qemu_opt_get_del(opts
, BLOCK_OPT_PREALLOC
);
3727 prealloc
= qapi_enum_parse(&PreallocMode_lookup
, optstr
,
3728 PREALLOC_MODE_OFF
, &local_err
);
3734 optstr
= qemu_opt_get_del(opts
, BLOCK_OPT_BACKING_FILE
);
3735 has_backing_file
= !!optstr
;
3738 virtual_size
= qemu_opt_get_size_del(opts
, BLOCK_OPT_SIZE
, 0);
3739 virtual_size
= ROUND_UP(virtual_size
, cluster_size
);
3741 /* Check that virtual disk size is valid */
3742 l2_tables
= DIV_ROUND_UP(virtual_size
/ cluster_size
,
3743 cluster_size
/ sizeof(uint64_t));
3744 if (l2_tables
* sizeof(uint64_t) > QCOW_MAX_L1_SIZE
) {
3745 error_setg(&local_err
, "The image size is too large "
3746 "(try using a larger cluster size)");
3750 /* Account for input image */
3752 int64_t ssize
= bdrv_getlength(in_bs
);
3754 error_setg_errno(&local_err
, -ssize
,
3755 "Unable to get image virtual_size");
3759 virtual_size
= ROUND_UP(ssize
, cluster_size
);
3761 if (has_backing_file
) {
3762 /* We don't how much of the backing chain is shared by the input
3763 * image and the new image file. In the worst case the new image's
3764 * backing file has nothing in common with the input image. Be
3765 * conservative and assume all clusters need to be written.
3767 required
= virtual_size
;
3772 for (offset
= 0; offset
< ssize
; offset
+= pnum
) {
3775 ret
= bdrv_block_status_above(in_bs
, NULL
, offset
,
3776 ssize
- offset
, &pnum
, NULL
,
3779 error_setg_errno(&local_err
, -ret
,
3780 "Unable to get block status");
3784 if (ret
& BDRV_BLOCK_ZERO
) {
3785 /* Skip zero regions (safe with no backing file) */
3786 } else if ((ret
& (BDRV_BLOCK_DATA
| BDRV_BLOCK_ALLOCATED
)) ==
3787 (BDRV_BLOCK_DATA
| BDRV_BLOCK_ALLOCATED
)) {
3788 /* Extend pnum to end of cluster for next iteration */
3789 pnum
= ROUND_UP(offset
+ pnum
, cluster_size
) - offset
;
3791 /* Count clusters we've seen */
3792 required
+= offset
% cluster_size
+ pnum
;
3798 /* Take into account preallocation. Nothing special is needed for
3799 * PREALLOC_MODE_METADATA since metadata is always counted.
3801 if (prealloc
== PREALLOC_MODE_FULL
|| prealloc
== PREALLOC_MODE_FALLOC
) {
3802 required
= virtual_size
;
3805 info
= g_new(BlockMeasureInfo
, 1);
3806 info
->fully_allocated
=
3807 qcow2_calc_prealloc_size(virtual_size
, cluster_size
,
3808 ctz32(refcount_bits
));
3810 /* Remove data clusters that are not required. This overestimates the
3811 * required size because metadata needed for the fully allocated file is
3814 info
->required
= info
->fully_allocated
- virtual_size
+ required
;
3818 error_propagate(errp
, local_err
);
3822 static int qcow2_get_info(BlockDriverState
*bs
, BlockDriverInfo
*bdi
)
3824 BDRVQcow2State
*s
= bs
->opaque
;
3825 bdi
->unallocated_blocks_are_zero
= true;
3826 bdi
->cluster_size
= s
->cluster_size
;
3827 bdi
->vm_state_offset
= qcow2_vm_state_offset(s
);
3831 static ImageInfoSpecific
*qcow2_get_specific_info(BlockDriverState
*bs
)
3833 BDRVQcow2State
*s
= bs
->opaque
;
3834 ImageInfoSpecific
*spec_info
;
3835 QCryptoBlockInfo
*encrypt_info
= NULL
;
3837 if (s
->crypto
!= NULL
) {
3838 encrypt_info
= qcrypto_block_get_info(s
->crypto
, &error_abort
);
3841 spec_info
= g_new(ImageInfoSpecific
, 1);
3842 *spec_info
= (ImageInfoSpecific
){
3843 .type
= IMAGE_INFO_SPECIFIC_KIND_QCOW2
,
3844 .u
.qcow2
.data
= g_new(ImageInfoSpecificQCow2
, 1),
3846 if (s
->qcow_version
== 2) {
3847 *spec_info
->u
.qcow2
.data
= (ImageInfoSpecificQCow2
){
3848 .compat
= g_strdup("0.10"),
3849 .refcount_bits
= s
->refcount_bits
,
3851 } else if (s
->qcow_version
== 3) {
3852 *spec_info
->u
.qcow2
.data
= (ImageInfoSpecificQCow2
){
3853 .compat
= g_strdup("1.1"),
3854 .lazy_refcounts
= s
->compatible_features
&
3855 QCOW2_COMPAT_LAZY_REFCOUNTS
,
3856 .has_lazy_refcounts
= true,
3857 .corrupt
= s
->incompatible_features
&
3858 QCOW2_INCOMPAT_CORRUPT
,
3859 .has_corrupt
= true,
3860 .refcount_bits
= s
->refcount_bits
,
3863 /* if this assertion fails, this probably means a new version was
3864 * added without having it covered here */
3869 ImageInfoSpecificQCow2Encryption
*qencrypt
=
3870 g_new(ImageInfoSpecificQCow2Encryption
, 1);
3871 switch (encrypt_info
->format
) {
3872 case Q_CRYPTO_BLOCK_FORMAT_QCOW
:
3873 qencrypt
->format
= BLOCKDEV_QCOW2_ENCRYPTION_FORMAT_AES
;
3874 qencrypt
->u
.aes
= encrypt_info
->u
.qcow
;
3876 case Q_CRYPTO_BLOCK_FORMAT_LUKS
:
3877 qencrypt
->format
= BLOCKDEV_QCOW2_ENCRYPTION_FORMAT_LUKS
;
3878 qencrypt
->u
.luks
= encrypt_info
->u
.luks
;
3883 /* Since we did shallow copy above, erase any pointers
3884 * in the original info */
3885 memset(&encrypt_info
->u
, 0, sizeof(encrypt_info
->u
));
3886 qapi_free_QCryptoBlockInfo(encrypt_info
);
3888 spec_info
->u
.qcow2
.data
->has_encrypt
= true;
3889 spec_info
->u
.qcow2
.data
->encrypt
= qencrypt
;
3895 static int qcow2_save_vmstate(BlockDriverState
*bs
, QEMUIOVector
*qiov
,
3898 BDRVQcow2State
*s
= bs
->opaque
;
3900 BLKDBG_EVENT(bs
->file
, BLKDBG_VMSTATE_SAVE
);
3901 return bs
->drv
->bdrv_co_pwritev(bs
, qcow2_vm_state_offset(s
) + pos
,
3902 qiov
->size
, qiov
, 0);
3905 static int qcow2_load_vmstate(BlockDriverState
*bs
, QEMUIOVector
*qiov
,
3908 BDRVQcow2State
*s
= bs
->opaque
;
3910 BLKDBG_EVENT(bs
->file
, BLKDBG_VMSTATE_LOAD
);
3911 return bs
->drv
->bdrv_co_preadv(bs
, qcow2_vm_state_offset(s
) + pos
,
3912 qiov
->size
, qiov
, 0);
3916 * Downgrades an image's version. To achieve this, any incompatible features
3917 * have to be removed.
3919 static int qcow2_downgrade(BlockDriverState
*bs
, int target_version
,
3920 BlockDriverAmendStatusCB
*status_cb
, void *cb_opaque
)
3922 BDRVQcow2State
*s
= bs
->opaque
;
3923 int current_version
= s
->qcow_version
;
3926 if (target_version
== current_version
) {
3928 } else if (target_version
> current_version
) {
3930 } else if (target_version
!= 2) {
3934 if (s
->refcount_order
!= 4) {
3935 error_report("compat=0.10 requires refcount_bits=16");
3939 /* clear incompatible features */
3940 if (s
->incompatible_features
& QCOW2_INCOMPAT_DIRTY
) {
3941 ret
= qcow2_mark_clean(bs
);
3947 /* with QCOW2_INCOMPAT_CORRUPT, it is pretty much impossible to get here in
3948 * the first place; if that happens nonetheless, returning -ENOTSUP is the
3949 * best thing to do anyway */
3951 if (s
->incompatible_features
) {
3955 /* since we can ignore compatible features, we can set them to 0 as well */
3956 s
->compatible_features
= 0;
3957 /* if lazy refcounts have been used, they have already been fixed through
3958 * clearing the dirty flag */
3960 /* clearing autoclear features is trivial */
3961 s
->autoclear_features
= 0;
3963 ret
= qcow2_expand_zero_clusters(bs
, status_cb
, cb_opaque
);
3968 s
->qcow_version
= target_version
;
3969 ret
= qcow2_update_header(bs
);
3971 s
->qcow_version
= current_version
;
3977 typedef enum Qcow2AmendOperation
{
3978 /* This is the value Qcow2AmendHelperCBInfo::last_operation will be
3979 * statically initialized to so that the helper CB can discern the first
3980 * invocation from an operation change */
3981 QCOW2_NO_OPERATION
= 0,
3983 QCOW2_CHANGING_REFCOUNT_ORDER
,
3985 } Qcow2AmendOperation
;
3987 typedef struct Qcow2AmendHelperCBInfo
{
3988 /* The code coordinating the amend operations should only modify
3989 * these four fields; the rest will be managed by the CB */
3990 BlockDriverAmendStatusCB
*original_status_cb
;
3991 void *original_cb_opaque
;
3993 Qcow2AmendOperation current_operation
;
3995 /* Total number of operations to perform (only set once) */
3996 int total_operations
;
3998 /* The following fields are managed by the CB */
4000 /* Number of operations completed */
4001 int operations_completed
;
4003 /* Cumulative offset of all completed operations */
4004 int64_t offset_completed
;
4006 Qcow2AmendOperation last_operation
;
4007 int64_t last_work_size
;
4008 } Qcow2AmendHelperCBInfo
;
4010 static void qcow2_amend_helper_cb(BlockDriverState
*bs
,
4011 int64_t operation_offset
,
4012 int64_t operation_work_size
, void *opaque
)
4014 Qcow2AmendHelperCBInfo
*info
= opaque
;
4015 int64_t current_work_size
;
4016 int64_t projected_work_size
;
4018 if (info
->current_operation
!= info
->last_operation
) {
4019 if (info
->last_operation
!= QCOW2_NO_OPERATION
) {
4020 info
->offset_completed
+= info
->last_work_size
;
4021 info
->operations_completed
++;
4024 info
->last_operation
= info
->current_operation
;
4027 assert(info
->total_operations
> 0);
4028 assert(info
->operations_completed
< info
->total_operations
);
4030 info
->last_work_size
= operation_work_size
;
4032 current_work_size
= info
->offset_completed
+ operation_work_size
;
4034 /* current_work_size is the total work size for (operations_completed + 1)
4035 * operations (which includes this one), so multiply it by the number of
4036 * operations not covered and divide it by the number of operations
4037 * covered to get a projection for the operations not covered */
4038 projected_work_size
= current_work_size
* (info
->total_operations
-
4039 info
->operations_completed
- 1)
4040 / (info
->operations_completed
+ 1);
4042 info
->original_status_cb(bs
, info
->offset_completed
+ operation_offset
,
4043 current_work_size
+ projected_work_size
,
4044 info
->original_cb_opaque
);
4047 static int qcow2_amend_options(BlockDriverState
*bs
, QemuOpts
*opts
,
4048 BlockDriverAmendStatusCB
*status_cb
,
4051 BDRVQcow2State
*s
= bs
->opaque
;
4052 int old_version
= s
->qcow_version
, new_version
= old_version
;
4053 uint64_t new_size
= 0;
4054 const char *backing_file
= NULL
, *backing_format
= NULL
;
4055 bool lazy_refcounts
= s
->use_lazy_refcounts
;
4056 const char *compat
= NULL
;
4057 uint64_t cluster_size
= s
->cluster_size
;
4060 int refcount_bits
= s
->refcount_bits
;
4061 Error
*local_err
= NULL
;
4063 QemuOptDesc
*desc
= opts
->list
->desc
;
4064 Qcow2AmendHelperCBInfo helper_cb_info
;
4066 while (desc
&& desc
->name
) {
4067 if (!qemu_opt_find(opts
, desc
->name
)) {
4068 /* only change explicitly defined options */
4073 if (!strcmp(desc
->name
, BLOCK_OPT_COMPAT_LEVEL
)) {
4074 compat
= qemu_opt_get(opts
, BLOCK_OPT_COMPAT_LEVEL
);
4076 /* preserve default */
4077 } else if (!strcmp(compat
, "0.10")) {
4079 } else if (!strcmp(compat
, "1.1")) {
4082 error_report("Unknown compatibility level %s", compat
);
4085 } else if (!strcmp(desc
->name
, BLOCK_OPT_PREALLOC
)) {
4086 error_report("Cannot change preallocation mode");
4088 } else if (!strcmp(desc
->name
, BLOCK_OPT_SIZE
)) {
4089 new_size
= qemu_opt_get_size(opts
, BLOCK_OPT_SIZE
, 0);
4090 } else if (!strcmp(desc
->name
, BLOCK_OPT_BACKING_FILE
)) {
4091 backing_file
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FILE
);
4092 } else if (!strcmp(desc
->name
, BLOCK_OPT_BACKING_FMT
)) {
4093 backing_format
= qemu_opt_get(opts
, BLOCK_OPT_BACKING_FMT
);
4094 } else if (!strcmp(desc
->name
, BLOCK_OPT_ENCRYPT
)) {
4095 encrypt
= qemu_opt_get_bool(opts
, BLOCK_OPT_ENCRYPT
,
4098 if (encrypt
!= !!s
->crypto
) {
4099 error_report("Changing the encryption flag is not supported");
4102 } else if (!strcmp(desc
->name
, BLOCK_OPT_ENCRYPT_FORMAT
)) {
4103 encformat
= qcow2_crypt_method_from_format(
4104 qemu_opt_get(opts
, BLOCK_OPT_ENCRYPT_FORMAT
));
4106 if (encformat
!= s
->crypt_method_header
) {
4107 error_report("Changing the encryption format is not supported");
4110 } else if (g_str_has_prefix(desc
->name
, "encrypt.")) {
4111 error_report("Changing the encryption parameters is not supported");
4113 } else if (!strcmp(desc
->name
, BLOCK_OPT_CLUSTER_SIZE
)) {
4114 cluster_size
= qemu_opt_get_size(opts
, BLOCK_OPT_CLUSTER_SIZE
,
4116 if (cluster_size
!= s
->cluster_size
) {
4117 error_report("Changing the cluster size is not supported");
4120 } else if (!strcmp(desc
->name
, BLOCK_OPT_LAZY_REFCOUNTS
)) {
4121 lazy_refcounts
= qemu_opt_get_bool(opts
, BLOCK_OPT_LAZY_REFCOUNTS
,
4123 } else if (!strcmp(desc
->name
, BLOCK_OPT_REFCOUNT_BITS
)) {
4124 refcount_bits
= qemu_opt_get_number(opts
, BLOCK_OPT_REFCOUNT_BITS
,
4127 if (refcount_bits
<= 0 || refcount_bits
> 64 ||
4128 !is_power_of_2(refcount_bits
))
4130 error_report("Refcount width must be a power of two and may "
4131 "not exceed 64 bits");
4135 /* if this point is reached, this probably means a new option was
4136 * added without having it covered here */
4143 helper_cb_info
= (Qcow2AmendHelperCBInfo
){
4144 .original_status_cb
= status_cb
,
4145 .original_cb_opaque
= cb_opaque
,
4146 .total_operations
= (new_version
< old_version
)
4147 + (s
->refcount_bits
!= refcount_bits
)
4150 /* Upgrade first (some features may require compat=1.1) */
4151 if (new_version
> old_version
) {
4152 s
->qcow_version
= new_version
;
4153 ret
= qcow2_update_header(bs
);
4155 s
->qcow_version
= old_version
;
4160 if (s
->refcount_bits
!= refcount_bits
) {
4161 int refcount_order
= ctz32(refcount_bits
);
4163 if (new_version
< 3 && refcount_bits
!= 16) {
4164 error_report("Different refcount widths than 16 bits require "
4165 "compatibility level 1.1 or above (use compat=1.1 or "
4170 helper_cb_info
.current_operation
= QCOW2_CHANGING_REFCOUNT_ORDER
;
4171 ret
= qcow2_change_refcount_order(bs
, refcount_order
,
4172 &qcow2_amend_helper_cb
,
4173 &helper_cb_info
, &local_err
);
4175 error_report_err(local_err
);
4180 if (backing_file
|| backing_format
) {
4181 ret
= qcow2_change_backing_file(bs
,
4182 backing_file
?: s
->image_backing_file
,
4183 backing_format
?: s
->image_backing_format
);
4189 if (s
->use_lazy_refcounts
!= lazy_refcounts
) {
4190 if (lazy_refcounts
) {
4191 if (new_version
< 3) {
4192 error_report("Lazy refcounts only supported with compatibility "
4193 "level 1.1 and above (use compat=1.1 or greater)");
4196 s
->compatible_features
|= QCOW2_COMPAT_LAZY_REFCOUNTS
;
4197 ret
= qcow2_update_header(bs
);
4199 s
->compatible_features
&= ~QCOW2_COMPAT_LAZY_REFCOUNTS
;
4202 s
->use_lazy_refcounts
= true;
4204 /* make image clean first */
4205 ret
= qcow2_mark_clean(bs
);
4209 /* now disallow lazy refcounts */
4210 s
->compatible_features
&= ~QCOW2_COMPAT_LAZY_REFCOUNTS
;
4211 ret
= qcow2_update_header(bs
);
4213 s
->compatible_features
|= QCOW2_COMPAT_LAZY_REFCOUNTS
;
4216 s
->use_lazy_refcounts
= false;
4221 BlockBackend
*blk
= blk_new(BLK_PERM_RESIZE
, BLK_PERM_ALL
);
4222 ret
= blk_insert_bs(blk
, bs
, &local_err
);
4224 error_report_err(local_err
);
4229 ret
= blk_truncate(blk
, new_size
, PREALLOC_MODE_OFF
, &local_err
);
4232 error_report_err(local_err
);
4237 /* Downgrade last (so unsupported features can be removed before) */
4238 if (new_version
< old_version
) {
4239 helper_cb_info
.current_operation
= QCOW2_DOWNGRADING
;
4240 ret
= qcow2_downgrade(bs
, new_version
, &qcow2_amend_helper_cb
,
4251 * If offset or size are negative, respectively, they will not be included in
4252 * the BLOCK_IMAGE_CORRUPTED event emitted.
4253 * fatal will be ignored for read-only BDS; corruptions found there will always
4254 * be considered non-fatal.
4256 void qcow2_signal_corruption(BlockDriverState
*bs
, bool fatal
, int64_t offset
,
4257 int64_t size
, const char *message_format
, ...)
4259 BDRVQcow2State
*s
= bs
->opaque
;
4260 const char *node_name
;
4264 fatal
= fatal
&& !bs
->read_only
;
4266 if (s
->signaled_corruption
&&
4267 (!fatal
|| (s
->incompatible_features
& QCOW2_INCOMPAT_CORRUPT
)))
4272 va_start(ap
, message_format
);
4273 message
= g_strdup_vprintf(message_format
, ap
);
4277 fprintf(stderr
, "qcow2: Marking image as corrupt: %s; further "
4278 "corruption events will be suppressed\n", message
);
4280 fprintf(stderr
, "qcow2: Image is corrupt: %s; further non-fatal "
4281 "corruption events will be suppressed\n", message
);
4284 node_name
= bdrv_get_node_name(bs
);
4285 qapi_event_send_block_image_corrupted(bdrv_get_device_name(bs
),
4286 *node_name
!= '\0', node_name
,
4287 message
, offset
>= 0, offset
,
4289 fatal
, &error_abort
);
4293 qcow2_mark_corrupt(bs
);
4294 bs
->drv
= NULL
; /* make BDS unusable */
4297 s
->signaled_corruption
= true;
4300 static QemuOptsList qcow2_create_opts
= {
4301 .name
= "qcow2-create-opts",
4302 .head
= QTAILQ_HEAD_INITIALIZER(qcow2_create_opts
.head
),
4305 .name
= BLOCK_OPT_SIZE
,
4306 .type
= QEMU_OPT_SIZE
,
4307 .help
= "Virtual disk size"
4310 .name
= BLOCK_OPT_COMPAT_LEVEL
,
4311 .type
= QEMU_OPT_STRING
,
4312 .help
= "Compatibility level (0.10 or 1.1)"
4315 .name
= BLOCK_OPT_BACKING_FILE
,
4316 .type
= QEMU_OPT_STRING
,
4317 .help
= "File name of a base image"
4320 .name
= BLOCK_OPT_BACKING_FMT
,
4321 .type
= QEMU_OPT_STRING
,
4322 .help
= "Image format of the base image"
4325 .name
= BLOCK_OPT_ENCRYPT
,
4326 .type
= QEMU_OPT_BOOL
,
4327 .help
= "Encrypt the image with format 'aes'. (Deprecated "
4328 "in favor of " BLOCK_OPT_ENCRYPT_FORMAT
"=aes)",
4331 .name
= BLOCK_OPT_ENCRYPT_FORMAT
,
4332 .type
= QEMU_OPT_STRING
,
4333 .help
= "Encrypt the image, format choices: 'aes', 'luks'",
4335 BLOCK_CRYPTO_OPT_DEF_KEY_SECRET("encrypt.",
4336 "ID of secret providing qcow AES key or LUKS passphrase"),
4337 BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_ALG("encrypt."),
4338 BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_MODE("encrypt."),
4339 BLOCK_CRYPTO_OPT_DEF_LUKS_IVGEN_ALG("encrypt."),
4340 BLOCK_CRYPTO_OPT_DEF_LUKS_IVGEN_HASH_ALG("encrypt."),
4341 BLOCK_CRYPTO_OPT_DEF_LUKS_HASH_ALG("encrypt."),
4342 BLOCK_CRYPTO_OPT_DEF_LUKS_ITER_TIME("encrypt."),
4344 .name
= BLOCK_OPT_CLUSTER_SIZE
,
4345 .type
= QEMU_OPT_SIZE
,
4346 .help
= "qcow2 cluster size",
4347 .def_value_str
= stringify(DEFAULT_CLUSTER_SIZE
)
4350 .name
= BLOCK_OPT_PREALLOC
,
4351 .type
= QEMU_OPT_STRING
,
4352 .help
= "Preallocation mode (allowed values: off, metadata, "
4356 .name
= BLOCK_OPT_LAZY_REFCOUNTS
,
4357 .type
= QEMU_OPT_BOOL
,
4358 .help
= "Postpone refcount updates",
4359 .def_value_str
= "off"
4362 .name
= BLOCK_OPT_REFCOUNT_BITS
,
4363 .type
= QEMU_OPT_NUMBER
,
4364 .help
= "Width of a reference count entry in bits",
4365 .def_value_str
= "16"
4367 { /* end of list */ }
4371 BlockDriver bdrv_qcow2
= {
4372 .format_name
= "qcow2",
4373 .instance_size
= sizeof(BDRVQcow2State
),
4374 .bdrv_probe
= qcow2_probe
,
4375 .bdrv_open
= qcow2_open
,
4376 .bdrv_close
= qcow2_close
,
4377 .bdrv_reopen_prepare
= qcow2_reopen_prepare
,
4378 .bdrv_reopen_commit
= qcow2_reopen_commit
,
4379 .bdrv_reopen_abort
= qcow2_reopen_abort
,
4380 .bdrv_join_options
= qcow2_join_options
,
4381 .bdrv_child_perm
= bdrv_format_default_perms
,
4382 .bdrv_co_create_opts
= qcow2_co_create_opts
,
4383 .bdrv_has_zero_init
= bdrv_has_zero_init_1
,
4384 .bdrv_co_block_status
= qcow2_co_block_status
,
4386 .bdrv_co_preadv
= qcow2_co_preadv
,
4387 .bdrv_co_pwritev
= qcow2_co_pwritev
,
4388 .bdrv_co_flush_to_os
= qcow2_co_flush_to_os
,
4390 .bdrv_co_pwrite_zeroes
= qcow2_co_pwrite_zeroes
,
4391 .bdrv_co_pdiscard
= qcow2_co_pdiscard
,
4392 .bdrv_truncate
= qcow2_truncate
,
4393 .bdrv_co_pwritev_compressed
= qcow2_co_pwritev_compressed
,
4394 .bdrv_make_empty
= qcow2_make_empty
,
4396 .bdrv_snapshot_create
= qcow2_snapshot_create
,
4397 .bdrv_snapshot_goto
= qcow2_snapshot_goto
,
4398 .bdrv_snapshot_delete
= qcow2_snapshot_delete
,
4399 .bdrv_snapshot_list
= qcow2_snapshot_list
,
4400 .bdrv_snapshot_load_tmp
= qcow2_snapshot_load_tmp
,
4401 .bdrv_measure
= qcow2_measure
,
4402 .bdrv_get_info
= qcow2_get_info
,
4403 .bdrv_get_specific_info
= qcow2_get_specific_info
,
4405 .bdrv_save_vmstate
= qcow2_save_vmstate
,
4406 .bdrv_load_vmstate
= qcow2_load_vmstate
,
4408 .supports_backing
= true,
4409 .bdrv_change_backing_file
= qcow2_change_backing_file
,
4411 .bdrv_refresh_limits
= qcow2_refresh_limits
,
4412 .bdrv_co_invalidate_cache
= qcow2_co_invalidate_cache
,
4413 .bdrv_inactivate
= qcow2_inactivate
,
4415 .create_opts
= &qcow2_create_opts
,
4416 .bdrv_check
= qcow2_check
,
4417 .bdrv_amend_options
= qcow2_amend_options
,
4419 .bdrv_detach_aio_context
= qcow2_detach_aio_context
,
4420 .bdrv_attach_aio_context
= qcow2_attach_aio_context
,
4422 .bdrv_reopen_bitmaps_rw
= qcow2_reopen_bitmaps_rw
,
4423 .bdrv_can_store_new_dirty_bitmap
= qcow2_can_store_new_dirty_bitmap
,
4424 .bdrv_remove_persistent_dirty_bitmap
= qcow2_remove_persistent_dirty_bitmap
,
4427 static void bdrv_qcow2_init(void)
4429 bdrv_register(&bdrv_qcow2
);
4432 block_init(bdrv_qcow2_init
);