2 * Block driver for the QCOW version 2 format
4 * Copyright (c) 2004-2006 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 #include "qemu/osdep.h"
27 #include "block/qdict.h"
28 #include "sysemu/block-backend.h"
29 #include "qemu/main-loop.h"
30 #include "qemu/module.h"
32 #include "qemu/error-report.h"
33 #include "qapi/error.h"
34 #include "qapi/qapi-events-block-core.h"
35 #include "qapi/qmp/qdict.h"
36 #include "qapi/qmp/qstring.h"
38 #include "qemu/option_int.h"
39 #include "qemu/cutils.h"
40 #include "qemu/bswap.h"
41 #include "qapi/qobject-input-visitor.h"
42 #include "qapi/qapi-visit-block-core.h"
44 #include "block/aio_task.h"
47 Differences with QCOW:
49 - Support for multiple incremental snapshots.
50 - Memory management by reference counts.
51 - Clusters which have a reference count of one have the bit
52 QCOW_OFLAG_COPIED to optimize write performance.
53 - Size of compressed clusters is stored in sectors to reduce bit usage
54 in the cluster offsets.
55 - Support for storing additional data (such as the VM state) in the
57 - If a backing store is used, the cluster size is not constrained
58 (could be backported to QCOW).
59 - L2 tables have always a size of one cluster.
66 } QEMU_PACKED QCowExtension;
68 #define QCOW2_EXT_MAGIC_END 0
69 #define QCOW2_EXT_MAGIC_BACKING_FORMAT 0xE2792ACA
70 #define QCOW2_EXT_MAGIC_FEATURE_TABLE 0x6803f857
71 #define QCOW2_EXT_MAGIC_CRYPTO_HEADER 0x0537be77
72 #define QCOW2_EXT_MAGIC_BITMAPS 0x23852875
73 #define QCOW2_EXT_MAGIC_DATA_FILE 0x44415441
75 static int coroutine_fn
76 qcow2_co_preadv_compressed(BlockDriverState *bs,
77 uint64_t file_cluster_offset,
83 static int qcow2_probe(const uint8_t *buf, int buf_size, const char *filename)
85 const QCowHeader *cow_header = (const void *)buf;
87 if (buf_size >= sizeof(QCowHeader) &&
88 be32_to_cpu(cow_header->magic) == QCOW_MAGIC &&
89 be32_to_cpu(cow_header->version) >= 2)
96 static ssize_t qcow2_crypto_hdr_read_func(QCryptoBlock *block, size_t offset,
97 uint8_t *buf, size_t buflen,
98 void *opaque, Error **errp)
100 BlockDriverState *bs = opaque;
101 BDRVQcow2State *s = bs->opaque;
104 if ((offset + buflen) > s->crypto_header.length) {
105 error_setg(errp, "Request for data outside of extension header");
109 ret = bdrv_pread(bs->file,
110 s->crypto_header.offset + offset, buf, buflen);
112 error_setg_errno(errp, -ret, "Could not read encryption header");
119 static ssize_t qcow2_crypto_hdr_init_func(QCryptoBlock *block, size_t headerlen,
120 void *opaque, Error **errp)
122 BlockDriverState *bs = opaque;
123 BDRVQcow2State *s = bs->opaque;
127 ret = qcow2_alloc_clusters(bs, headerlen);
129 error_setg_errno(errp, -ret,
130 "Cannot allocate cluster for LUKS header size %zu",
135 s->crypto_header.length = headerlen;
136 s->crypto_header.offset = ret;
138 /* Zero fill remaining space in cluster so it has predictable
139 * content in case of future spec changes */
140 clusterlen = size_to_clusters(s, headerlen) * s->cluster_size;
141 assert(qcow2_pre_write_overlap_check(bs, 0, ret, clusterlen, false) == 0);
142 ret = bdrv_pwrite_zeroes(bs->file,
144 clusterlen - headerlen, 0);
146 error_setg_errno(errp, -ret, "Could not zero fill encryption header");
154 static ssize_t qcow2_crypto_hdr_write_func(QCryptoBlock *block, size_t offset,
155 const uint8_t *buf, size_t buflen,
156 void *opaque, Error **errp)
158 BlockDriverState *bs = opaque;
159 BDRVQcow2State *s = bs->opaque;
162 if ((offset + buflen) > s->crypto_header.length) {
163 error_setg(errp, "Request for data outside of extension header");
167 ret = bdrv_pwrite(bs->file,
168 s->crypto_header.offset + offset, buf, buflen);
170 error_setg_errno(errp, -ret, "Could not read encryption header");
178 * read qcow2 extension and fill bs
179 * start reading from start_offset
180 * finish reading upon magic of value 0 or when end_offset reached
181 * unknown magic is skipped (future extension this version knows nothing about)
182 * return 0 upon success, non-0 otherwise
184 static int qcow2_read_extensions(BlockDriverState *bs, uint64_t start_offset,
185 uint64_t end_offset, void **p_feature_table,
186 int flags, bool *need_update_header,
189 BDRVQcow2State *s = bs->opaque;
193 Qcow2BitmapHeaderExt bitmaps_ext;
195 if (need_update_header != NULL) {
196 *need_update_header = false;
200 printf("qcow2_read_extensions: start=%ld end=%ld\n", start_offset, end_offset);
202 offset = start_offset;
203 while (offset < end_offset) {
207 if (offset > s->cluster_size)
208 printf("qcow2_read_extension: suspicious offset %lu\n", offset);
210 printf("attempting to read extended header in offset %lu\n", offset);
213 ret = bdrv_pread(bs->file, offset, &ext, sizeof(ext));
215 error_setg_errno(errp, -ret, "qcow2_read_extension: ERROR: "
216 "pread fail from offset %" PRIu64, offset);
219 ext.magic = be32_to_cpu(ext.magic);
220 ext.len = be32_to_cpu(ext.len);
221 offset += sizeof(ext);
223 printf("ext.magic = 0x%x\n", ext.magic);
225 if (offset > end_offset || ext.len > end_offset - offset) {
226 error_setg(errp, "Header extension too large");
231 case QCOW2_EXT_MAGIC_END:
234 case QCOW2_EXT_MAGIC_BACKING_FORMAT:
235 if (ext.len >= sizeof(bs->backing_format)) {
236 error_setg(errp, "ERROR: ext_backing_format: len=%" PRIu32
237 " too large (>=%zu)", ext.len,
238 sizeof(bs->backing_format));
241 ret = bdrv_pread(bs->file, offset, bs->backing_format, ext.len);
243 error_setg_errno(errp, -ret, "ERROR: ext_backing_format: "
244 "Could not read format name");
247 bs->backing_format[ext.len] = '\0';
248 s->image_backing_format = g_strdup(bs->backing_format);
250 printf("Qcow2: Got format extension %s\n", bs->backing_format);
254 case QCOW2_EXT_MAGIC_FEATURE_TABLE:
255 if (p_feature_table != NULL) {
256 void* feature_table = g_malloc0(ext.len + 2 * sizeof(Qcow2Feature));
257 ret = bdrv_pread(bs->file, offset , feature_table, ext.len);
259 error_setg_errno(errp, -ret, "ERROR: ext_feature_table: "
260 "Could not read table");
264 *p_feature_table = feature_table;
268 case QCOW2_EXT_MAGIC_CRYPTO_HEADER: {
269 unsigned int cflags = 0;
270 if (s->crypt_method_header != QCOW_CRYPT_LUKS) {
271 error_setg(errp, "CRYPTO header extension only "
272 "expected with LUKS encryption method");
275 if (ext.len != sizeof(Qcow2CryptoHeaderExtension)) {
276 error_setg(errp, "CRYPTO header extension size %u, "
277 "but expected size %zu", ext.len,
278 sizeof(Qcow2CryptoHeaderExtension));
282 ret = bdrv_pread(bs->file, offset, &s->crypto_header, ext.len);
284 error_setg_errno(errp, -ret,
285 "Unable to read CRYPTO header extension");
288 s->crypto_header.offset = be64_to_cpu(s->crypto_header.offset);
289 s->crypto_header.length = be64_to_cpu(s->crypto_header.length);
291 if ((s->crypto_header.offset % s->cluster_size) != 0) {
292 error_setg(errp, "Encryption header offset '%" PRIu64 "' is "
293 "not a multiple of cluster size '%u'",
294 s->crypto_header.offset, s->cluster_size);
298 if (flags & BDRV_O_NO_IO) {
299 cflags |= QCRYPTO_BLOCK_OPEN_NO_IO;
301 s->crypto = qcrypto_block_open(s->crypto_opts, "encrypt.",
302 qcow2_crypto_hdr_read_func,
303 bs, cflags, QCOW2_MAX_THREADS, errp);
309 case QCOW2_EXT_MAGIC_BITMAPS:
310 if (ext.len != sizeof(bitmaps_ext)) {
311 error_setg_errno(errp, -ret, "bitmaps_ext: "
312 "Invalid extension length");
316 if (!(s->autoclear_features & QCOW2_AUTOCLEAR_BITMAPS)) {
317 if (s->qcow_version < 3) {
318 /* Let's be a bit more specific */
319 warn_report("This qcow2 v2 image contains bitmaps, but "
320 "they may have been modified by a program "
321 "without persistent bitmap support; so now "
322 "they must all be considered inconsistent");
324 warn_report("a program lacking bitmap support "
325 "modified this file, so all bitmaps are now "
326 "considered inconsistent");
328 error_printf("Some clusters may be leaked, "
329 "run 'qemu-img check -r' on the image "
331 if (need_update_header != NULL) {
332 /* Updating is needed to drop invalid bitmap extension. */
333 *need_update_header = true;
338 ret = bdrv_pread(bs->file, offset, &bitmaps_ext, ext.len);
340 error_setg_errno(errp, -ret, "bitmaps_ext: "
341 "Could not read ext header");
345 if (bitmaps_ext.reserved32 != 0) {
346 error_setg_errno(errp, -ret, "bitmaps_ext: "
347 "Reserved field is not zero");
351 bitmaps_ext.nb_bitmaps = be32_to_cpu(bitmaps_ext.nb_bitmaps);
352 bitmaps_ext.bitmap_directory_size =
353 be64_to_cpu(bitmaps_ext.bitmap_directory_size);
354 bitmaps_ext.bitmap_directory_offset =
355 be64_to_cpu(bitmaps_ext.bitmap_directory_offset);
357 if (bitmaps_ext.nb_bitmaps > QCOW2_MAX_BITMAPS) {
359 "bitmaps_ext: Image has %" PRIu32 " bitmaps, "
360 "exceeding the QEMU supported maximum of %d",
361 bitmaps_ext.nb_bitmaps, QCOW2_MAX_BITMAPS);
365 if (bitmaps_ext.nb_bitmaps == 0) {
366 error_setg(errp, "found bitmaps extension with zero bitmaps");
370 if (bitmaps_ext.bitmap_directory_offset & (s->cluster_size - 1)) {
371 error_setg(errp, "bitmaps_ext: "
372 "invalid bitmap directory offset");
376 if (bitmaps_ext.bitmap_directory_size >
377 QCOW2_MAX_BITMAP_DIRECTORY_SIZE) {
378 error_setg(errp, "bitmaps_ext: "
379 "bitmap directory size (%" PRIu64 ") exceeds "
380 "the maximum supported size (%d)",
381 bitmaps_ext.bitmap_directory_size,
382 QCOW2_MAX_BITMAP_DIRECTORY_SIZE);
386 s->nb_bitmaps = bitmaps_ext.nb_bitmaps;
387 s->bitmap_directory_offset =
388 bitmaps_ext.bitmap_directory_offset;
389 s->bitmap_directory_size =
390 bitmaps_ext.bitmap_directory_size;
393 printf("Qcow2: Got bitmaps extension: "
394 "offset=%" PRIu64 " nb_bitmaps=%" PRIu32 "\n",
395 s->bitmap_directory_offset, s->nb_bitmaps);
399 case QCOW2_EXT_MAGIC_DATA_FILE:
401 s->image_data_file = g_malloc0(ext.len + 1);
402 ret = bdrv_pread(bs->file, offset, s->image_data_file, ext.len);
404 error_setg_errno(errp, -ret,
405 "ERROR: Could not read data file name");
409 printf("Qcow2: Got external data file %s\n", s->image_data_file);
415 /* unknown magic - save it in case we need to rewrite the header */
416 /* If you add a new feature, make sure to also update the fast
417 * path of qcow2_make_empty() to deal with it. */
419 Qcow2UnknownHeaderExtension *uext;
421 uext = g_malloc0(sizeof(*uext) + ext.len);
422 uext->magic = ext.magic;
424 QLIST_INSERT_HEAD(&s->unknown_header_ext, uext, next);
426 ret = bdrv_pread(bs->file, offset , uext->data, uext->len);
428 error_setg_errno(errp, -ret, "ERROR: unknown extension: "
429 "Could not read data");
436 offset += ((ext.len + 7) & ~7);
442 static void cleanup_unknown_header_ext(BlockDriverState *bs)
444 BDRVQcow2State *s = bs->opaque;
445 Qcow2UnknownHeaderExtension *uext, *next;
447 QLIST_FOREACH_SAFE(uext, &s->unknown_header_ext, next, next) {
448 QLIST_REMOVE(uext, next);
453 static void report_unsupported_feature(Error **errp, Qcow2Feature *table,
456 char *features = g_strdup("");
459 while (table && table->name[0] != '\0') {
460 if (table->type == QCOW2_FEAT_TYPE_INCOMPATIBLE) {
461 if (mask & (1ULL << table->bit)) {
463 features = g_strdup_printf("%s%s%.46s", old, *old ? ", " : "",
466 mask &= ~(1ULL << table->bit);
474 features = g_strdup_printf("%s%sUnknown incompatible feature: %" PRIx64,
475 old, *old ? ", " : "", mask);
479 error_setg(errp, "Unsupported qcow2 feature(s): %s", features);
484 * Sets the dirty bit and flushes afterwards if necessary.
486 * The incompatible_features bit is only set if the image file header was
487 * updated successfully. Therefore it is not required to check the return
488 * value of this function.
490 int qcow2_mark_dirty(BlockDriverState *bs)
492 BDRVQcow2State *s = bs->opaque;
496 assert(s->qcow_version >= 3);
498 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
499 return 0; /* already dirty */
502 val = cpu_to_be64(s->incompatible_features | QCOW2_INCOMPAT_DIRTY);
503 ret = bdrv_pwrite(bs->file, offsetof(QCowHeader, incompatible_features),
508 ret = bdrv_flush(bs->file->bs);
513 /* Only treat image as dirty if the header was updated successfully */
514 s->incompatible_features |= QCOW2_INCOMPAT_DIRTY;
519 * Clears the dirty bit and flushes before if necessary. Only call this
520 * function when there are no pending requests, it does not guard against
521 * concurrent requests dirtying the image.
523 static int qcow2_mark_clean(BlockDriverState *bs)
525 BDRVQcow2State *s = bs->opaque;
527 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
530 s->incompatible_features &= ~QCOW2_INCOMPAT_DIRTY;
532 ret = qcow2_flush_caches(bs);
537 return qcow2_update_header(bs);
543 * Marks the image as corrupt.
545 int qcow2_mark_corrupt(BlockDriverState *bs)
547 BDRVQcow2State *s = bs->opaque;
549 s->incompatible_features |= QCOW2_INCOMPAT_CORRUPT;
550 return qcow2_update_header(bs);
554 * Marks the image as consistent, i.e., unsets the corrupt bit, and flushes
555 * before if necessary.
557 int qcow2_mark_consistent(BlockDriverState *bs)
559 BDRVQcow2State *s = bs->opaque;
561 if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
562 int ret = qcow2_flush_caches(bs);
567 s->incompatible_features &= ~QCOW2_INCOMPAT_CORRUPT;
568 return qcow2_update_header(bs);
573 static void qcow2_add_check_result(BdrvCheckResult *out,
574 const BdrvCheckResult *src,
575 bool set_allocation_info)
577 out->corruptions += src->corruptions;
578 out->leaks += src->leaks;
579 out->check_errors += src->check_errors;
580 out->corruptions_fixed += src->corruptions_fixed;
581 out->leaks_fixed += src->leaks_fixed;
583 if (set_allocation_info) {
584 out->image_end_offset = src->image_end_offset;
589 static int coroutine_fn qcow2_co_check_locked(BlockDriverState *bs,
590 BdrvCheckResult *result,
593 BdrvCheckResult snapshot_res = {};
594 BdrvCheckResult refcount_res = {};
597 memset(result, 0, sizeof(*result));
599 ret = qcow2_check_read_snapshot_table(bs, &snapshot_res, fix);
600 qcow2_add_check_result(result, &snapshot_res, false);
605 ret = qcow2_check_refcounts(bs, &refcount_res, fix);
606 qcow2_add_check_result(result, &refcount_res, true);
611 if (fix && result->check_errors == 0 && result->corruptions == 0) {
612 ret = qcow2_mark_clean(bs);
616 return qcow2_mark_consistent(bs);
621 static int coroutine_fn qcow2_co_check(BlockDriverState *bs,
622 BdrvCheckResult *result,
625 BDRVQcow2State *s = bs->opaque;
628 qemu_co_mutex_lock(&s->lock);
629 ret = qcow2_co_check_locked(bs, result, fix);
630 qemu_co_mutex_unlock(&s->lock);
634 int qcow2_validate_table(BlockDriverState *bs, uint64_t offset,
635 uint64_t entries, size_t entry_len,
636 int64_t max_size_bytes, const char *table_name,
639 BDRVQcow2State *s = bs->opaque;
641 if (entries > max_size_bytes / entry_len) {
642 error_setg(errp, "%s too large", table_name);
646 /* Use signed INT64_MAX as the maximum even for uint64_t header fields,
647 * because values will be passed to qemu functions taking int64_t. */
648 if ((INT64_MAX - entries * entry_len < offset) ||
649 (offset_into_cluster(s, offset) != 0)) {
650 error_setg(errp, "%s offset invalid", table_name);
657 static const char *const mutable_opts[] = {
658 QCOW2_OPT_LAZY_REFCOUNTS,
659 QCOW2_OPT_DISCARD_REQUEST,
660 QCOW2_OPT_DISCARD_SNAPSHOT,
661 QCOW2_OPT_DISCARD_OTHER,
663 QCOW2_OPT_OVERLAP_TEMPLATE,
664 QCOW2_OPT_OVERLAP_MAIN_HEADER,
665 QCOW2_OPT_OVERLAP_ACTIVE_L1,
666 QCOW2_OPT_OVERLAP_ACTIVE_L2,
667 QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
668 QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
669 QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
670 QCOW2_OPT_OVERLAP_INACTIVE_L1,
671 QCOW2_OPT_OVERLAP_INACTIVE_L2,
672 QCOW2_OPT_OVERLAP_BITMAP_DIRECTORY,
673 QCOW2_OPT_CACHE_SIZE,
674 QCOW2_OPT_L2_CACHE_SIZE,
675 QCOW2_OPT_L2_CACHE_ENTRY_SIZE,
676 QCOW2_OPT_REFCOUNT_CACHE_SIZE,
677 QCOW2_OPT_CACHE_CLEAN_INTERVAL,
681 static QemuOptsList qcow2_runtime_opts = {
683 .head = QTAILQ_HEAD_INITIALIZER(qcow2_runtime_opts.head),
686 .name = QCOW2_OPT_LAZY_REFCOUNTS,
687 .type = QEMU_OPT_BOOL,
688 .help = "Postpone refcount updates",
691 .name = QCOW2_OPT_DISCARD_REQUEST,
692 .type = QEMU_OPT_BOOL,
693 .help = "Pass guest discard requests to the layer below",
696 .name = QCOW2_OPT_DISCARD_SNAPSHOT,
697 .type = QEMU_OPT_BOOL,
698 .help = "Generate discard requests when snapshot related space "
702 .name = QCOW2_OPT_DISCARD_OTHER,
703 .type = QEMU_OPT_BOOL,
704 .help = "Generate discard requests when other clusters are freed",
707 .name = QCOW2_OPT_OVERLAP,
708 .type = QEMU_OPT_STRING,
709 .help = "Selects which overlap checks to perform from a range of "
710 "templates (none, constant, cached, all)",
713 .name = QCOW2_OPT_OVERLAP_TEMPLATE,
714 .type = QEMU_OPT_STRING,
715 .help = "Selects which overlap checks to perform from a range of "
716 "templates (none, constant, cached, all)",
719 .name = QCOW2_OPT_OVERLAP_MAIN_HEADER,
720 .type = QEMU_OPT_BOOL,
721 .help = "Check for unintended writes into the main qcow2 header",
724 .name = QCOW2_OPT_OVERLAP_ACTIVE_L1,
725 .type = QEMU_OPT_BOOL,
726 .help = "Check for unintended writes into the active L1 table",
729 .name = QCOW2_OPT_OVERLAP_ACTIVE_L2,
730 .type = QEMU_OPT_BOOL,
731 .help = "Check for unintended writes into an active L2 table",
734 .name = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
735 .type = QEMU_OPT_BOOL,
736 .help = "Check for unintended writes into the refcount table",
739 .name = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
740 .type = QEMU_OPT_BOOL,
741 .help = "Check for unintended writes into a refcount block",
744 .name = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
745 .type = QEMU_OPT_BOOL,
746 .help = "Check for unintended writes into the snapshot table",
749 .name = QCOW2_OPT_OVERLAP_INACTIVE_L1,
750 .type = QEMU_OPT_BOOL,
751 .help = "Check for unintended writes into an inactive L1 table",
754 .name = QCOW2_OPT_OVERLAP_INACTIVE_L2,
755 .type = QEMU_OPT_BOOL,
756 .help = "Check for unintended writes into an inactive L2 table",
759 .name = QCOW2_OPT_OVERLAP_BITMAP_DIRECTORY,
760 .type = QEMU_OPT_BOOL,
761 .help = "Check for unintended writes into the bitmap directory",
764 .name = QCOW2_OPT_CACHE_SIZE,
765 .type = QEMU_OPT_SIZE,
766 .help = "Maximum combined metadata (L2 tables and refcount blocks) "
770 .name = QCOW2_OPT_L2_CACHE_SIZE,
771 .type = QEMU_OPT_SIZE,
772 .help = "Maximum L2 table cache size",
775 .name = QCOW2_OPT_L2_CACHE_ENTRY_SIZE,
776 .type = QEMU_OPT_SIZE,
777 .help = "Size of each entry in the L2 cache",
780 .name = QCOW2_OPT_REFCOUNT_CACHE_SIZE,
781 .type = QEMU_OPT_SIZE,
782 .help = "Maximum refcount block cache size",
785 .name = QCOW2_OPT_CACHE_CLEAN_INTERVAL,
786 .type = QEMU_OPT_NUMBER,
787 .help = "Clean unused cache entries after this time (in seconds)",
789 BLOCK_CRYPTO_OPT_DEF_KEY_SECRET("encrypt.",
790 "ID of secret providing qcow2 AES key or LUKS passphrase"),
791 { /* end of list */ }
795 static const char *overlap_bool_option_names[QCOW2_OL_MAX_BITNR] = {
796 [QCOW2_OL_MAIN_HEADER_BITNR] = QCOW2_OPT_OVERLAP_MAIN_HEADER,
797 [QCOW2_OL_ACTIVE_L1_BITNR] = QCOW2_OPT_OVERLAP_ACTIVE_L1,
798 [QCOW2_OL_ACTIVE_L2_BITNR] = QCOW2_OPT_OVERLAP_ACTIVE_L2,
799 [QCOW2_OL_REFCOUNT_TABLE_BITNR] = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
800 [QCOW2_OL_REFCOUNT_BLOCK_BITNR] = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
801 [QCOW2_OL_SNAPSHOT_TABLE_BITNR] = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
802 [QCOW2_OL_INACTIVE_L1_BITNR] = QCOW2_OPT_OVERLAP_INACTIVE_L1,
803 [QCOW2_OL_INACTIVE_L2_BITNR] = QCOW2_OPT_OVERLAP_INACTIVE_L2,
804 [QCOW2_OL_BITMAP_DIRECTORY_BITNR] = QCOW2_OPT_OVERLAP_BITMAP_DIRECTORY,
807 static void cache_clean_timer_cb(void *opaque)
809 BlockDriverState *bs = opaque;
810 BDRVQcow2State *s = bs->opaque;
811 qcow2_cache_clean_unused(s->l2_table_cache);
812 qcow2_cache_clean_unused(s->refcount_block_cache);
813 timer_mod(s->cache_clean_timer, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) +
814 (int64_t) s->cache_clean_interval * 1000);
817 static void cache_clean_timer_init(BlockDriverState *bs, AioContext *context)
819 BDRVQcow2State *s = bs->opaque;
820 if (s->cache_clean_interval > 0) {
821 s->cache_clean_timer = aio_timer_new(context, QEMU_CLOCK_VIRTUAL,
822 SCALE_MS, cache_clean_timer_cb,
824 timer_mod(s->cache_clean_timer, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) +
825 (int64_t) s->cache_clean_interval * 1000);
829 static void cache_clean_timer_del(BlockDriverState *bs)
831 BDRVQcow2State *s = bs->opaque;
832 if (s->cache_clean_timer) {
833 timer_del(s->cache_clean_timer);
834 timer_free(s->cache_clean_timer);
835 s->cache_clean_timer = NULL;
839 static void qcow2_detach_aio_context(BlockDriverState *bs)
841 cache_clean_timer_del(bs);
844 static void qcow2_attach_aio_context(BlockDriverState *bs,
845 AioContext *new_context)
847 cache_clean_timer_init(bs, new_context);
850 static void read_cache_sizes(BlockDriverState *bs, QemuOpts *opts,
851 uint64_t *l2_cache_size,
852 uint64_t *l2_cache_entry_size,
853 uint64_t *refcount_cache_size, Error **errp)
855 BDRVQcow2State *s = bs->opaque;
856 uint64_t combined_cache_size, l2_cache_max_setting;
857 bool l2_cache_size_set, refcount_cache_size_set, combined_cache_size_set;
858 bool l2_cache_entry_size_set;
859 int min_refcount_cache = MIN_REFCOUNT_CACHE_SIZE * s->cluster_size;
860 uint64_t virtual_disk_size = bs->total_sectors * BDRV_SECTOR_SIZE;
861 uint64_t max_l2_entries = DIV_ROUND_UP(virtual_disk_size, s->cluster_size);
862 /* An L2 table is always one cluster in size so the max cache size
863 * should be a multiple of the cluster size. */
864 uint64_t max_l2_cache = ROUND_UP(max_l2_entries * sizeof(uint64_t),
867 combined_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_CACHE_SIZE);
868 l2_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_L2_CACHE_SIZE);
869 refcount_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
870 l2_cache_entry_size_set = qemu_opt_get(opts, QCOW2_OPT_L2_CACHE_ENTRY_SIZE);
872 combined_cache_size = qemu_opt_get_size(opts, QCOW2_OPT_CACHE_SIZE, 0);
873 l2_cache_max_setting = qemu_opt_get_size(opts, QCOW2_OPT_L2_CACHE_SIZE,
874 DEFAULT_L2_CACHE_MAX_SIZE);
875 *refcount_cache_size = qemu_opt_get_size(opts,
876 QCOW2_OPT_REFCOUNT_CACHE_SIZE, 0);
878 *l2_cache_entry_size = qemu_opt_get_size(
879 opts, QCOW2_OPT_L2_CACHE_ENTRY_SIZE, s->cluster_size);
881 *l2_cache_size = MIN(max_l2_cache, l2_cache_max_setting);
883 if (combined_cache_size_set) {
884 if (l2_cache_size_set && refcount_cache_size_set) {
885 error_setg(errp, QCOW2_OPT_CACHE_SIZE ", " QCOW2_OPT_L2_CACHE_SIZE
886 " and " QCOW2_OPT_REFCOUNT_CACHE_SIZE " may not be set "
889 } else if (l2_cache_size_set &&
890 (l2_cache_max_setting > combined_cache_size)) {
891 error_setg(errp, QCOW2_OPT_L2_CACHE_SIZE " may not exceed "
892 QCOW2_OPT_CACHE_SIZE);
894 } else if (*refcount_cache_size > combined_cache_size) {
895 error_setg(errp, QCOW2_OPT_REFCOUNT_CACHE_SIZE " may not exceed "
896 QCOW2_OPT_CACHE_SIZE);
900 if (l2_cache_size_set) {
901 *refcount_cache_size = combined_cache_size - *l2_cache_size;
902 } else if (refcount_cache_size_set) {
903 *l2_cache_size = combined_cache_size - *refcount_cache_size;
905 /* Assign as much memory as possible to the L2 cache, and
906 * use the remainder for the refcount cache */
907 if (combined_cache_size >= max_l2_cache + min_refcount_cache) {
908 *l2_cache_size = max_l2_cache;
909 *refcount_cache_size = combined_cache_size - *l2_cache_size;
911 *refcount_cache_size =
912 MIN(combined_cache_size, min_refcount_cache);
913 *l2_cache_size = combined_cache_size - *refcount_cache_size;
919 * If the L2 cache is not enough to cover the whole disk then
920 * default to 4KB entries. Smaller entries reduce the cost of
921 * loads and evictions and increase I/O performance.
923 if (*l2_cache_size < max_l2_cache && !l2_cache_entry_size_set) {
924 *l2_cache_entry_size = MIN(s->cluster_size, 4096);
927 /* l2_cache_size and refcount_cache_size are ensured to have at least
928 * their minimum values in qcow2_update_options_prepare() */
930 if (*l2_cache_entry_size < (1 << MIN_CLUSTER_BITS) ||
931 *l2_cache_entry_size > s->cluster_size ||
932 !is_power_of_2(*l2_cache_entry_size)) {
933 error_setg(errp, "L2 cache entry size must be a power of two "
934 "between %d and the cluster size (%d)",
935 1 << MIN_CLUSTER_BITS, s->cluster_size);
940 typedef struct Qcow2ReopenState {
941 Qcow2Cache *l2_table_cache;
942 Qcow2Cache *refcount_block_cache;
943 int l2_slice_size; /* Number of entries in a slice of the L2 table */
944 bool use_lazy_refcounts;
946 bool discard_passthrough[QCOW2_DISCARD_MAX];
947 uint64_t cache_clean_interval;
948 QCryptoBlockOpenOptions *crypto_opts; /* Disk encryption runtime options */
951 static int qcow2_update_options_prepare(BlockDriverState *bs,
953 QDict *options, int flags,
956 BDRVQcow2State *s = bs->opaque;
957 QemuOpts *opts = NULL;
958 const char *opt_overlap_check, *opt_overlap_check_template;
959 int overlap_check_template = 0;
960 uint64_t l2_cache_size, l2_cache_entry_size, refcount_cache_size;
962 const char *encryptfmt;
963 QDict *encryptopts = NULL;
964 Error *local_err = NULL;
967 qdict_extract_subqdict(options, &encryptopts, "encrypt.");
968 encryptfmt = qdict_get_try_str(encryptopts, "format");
970 opts = qemu_opts_create(&qcow2_runtime_opts, NULL, 0, &error_abort);
971 qemu_opts_absorb_qdict(opts, options, &local_err);
973 error_propagate(errp, local_err);
978 /* get L2 table/refcount block cache size from command line options */
979 read_cache_sizes(bs, opts, &l2_cache_size, &l2_cache_entry_size,
980 &refcount_cache_size, &local_err);
982 error_propagate(errp, local_err);
987 l2_cache_size /= l2_cache_entry_size;
988 if (l2_cache_size < MIN_L2_CACHE_SIZE) {
989 l2_cache_size = MIN_L2_CACHE_SIZE;
991 if (l2_cache_size > INT_MAX) {
992 error_setg(errp, "L2 cache size too big");
997 refcount_cache_size /= s->cluster_size;
998 if (refcount_cache_size < MIN_REFCOUNT_CACHE_SIZE) {
999 refcount_cache_size = MIN_REFCOUNT_CACHE_SIZE;
1001 if (refcount_cache_size > INT_MAX) {
1002 error_setg(errp, "Refcount cache size too big");
1007 /* alloc new L2 table/refcount block cache, flush old one */
1008 if (s->l2_table_cache) {
1009 ret = qcow2_cache_flush(bs, s->l2_table_cache);
1011 error_setg_errno(errp, -ret, "Failed to flush the L2 table cache");
1016 if (s->refcount_block_cache) {
1017 ret = qcow2_cache_flush(bs, s->refcount_block_cache);
1019 error_setg_errno(errp, -ret,
1020 "Failed to flush the refcount block cache");
1025 r->l2_slice_size = l2_cache_entry_size / sizeof(uint64_t);
1026 r->l2_table_cache = qcow2_cache_create(bs, l2_cache_size,
1027 l2_cache_entry_size);
1028 r->refcount_block_cache = qcow2_cache_create(bs, refcount_cache_size,
1030 if (r->l2_table_cache == NULL || r->refcount_block_cache == NULL) {
1031 error_setg(errp, "Could not allocate metadata caches");
1036 /* New interval for cache cleanup timer */
1037 r->cache_clean_interval =
1038 qemu_opt_get_number(opts, QCOW2_OPT_CACHE_CLEAN_INTERVAL,
1039 DEFAULT_CACHE_CLEAN_INTERVAL);
1040 #ifndef CONFIG_LINUX
1041 if (r->cache_clean_interval != 0) {
1042 error_setg(errp, QCOW2_OPT_CACHE_CLEAN_INTERVAL
1043 " not supported on this host");
1048 if (r->cache_clean_interval > UINT_MAX) {
1049 error_setg(errp, "Cache clean interval too big");
1054 /* lazy-refcounts; flush if going from enabled to disabled */
1055 r->use_lazy_refcounts = qemu_opt_get_bool(opts, QCOW2_OPT_LAZY_REFCOUNTS,
1056 (s->compatible_features & QCOW2_COMPAT_LAZY_REFCOUNTS));
1057 if (r->use_lazy_refcounts && s->qcow_version < 3) {
1058 error_setg(errp, "Lazy refcounts require a qcow2 image with at least "
1059 "qemu 1.1 compatibility level");
1064 if (s->use_lazy_refcounts && !r->use_lazy_refcounts) {
1065 ret = qcow2_mark_clean(bs);
1067 error_setg_errno(errp, -ret, "Failed to disable lazy refcounts");
1072 /* Overlap check options */
1073 opt_overlap_check = qemu_opt_get(opts, QCOW2_OPT_OVERLAP);
1074 opt_overlap_check_template = qemu_opt_get(opts, QCOW2_OPT_OVERLAP_TEMPLATE);
1075 if (opt_overlap_check_template && opt_overlap_check &&
1076 strcmp(opt_overlap_check_template, opt_overlap_check))
1078 error_setg(errp, "Conflicting values for qcow2 options '"
1079 QCOW2_OPT_OVERLAP "' ('%s') and '" QCOW2_OPT_OVERLAP_TEMPLATE
1080 "' ('%s')", opt_overlap_check, opt_overlap_check_template);
1084 if (!opt_overlap_check) {
1085 opt_overlap_check = opt_overlap_check_template ?: "cached";
1088 if (!strcmp(opt_overlap_check, "none")) {
1089 overlap_check_template = 0;
1090 } else if (!strcmp(opt_overlap_check, "constant")) {
1091 overlap_check_template = QCOW2_OL_CONSTANT;
1092 } else if (!strcmp(opt_overlap_check, "cached")) {
1093 overlap_check_template = QCOW2_OL_CACHED;
1094 } else if (!strcmp(opt_overlap_check, "all")) {
1095 overlap_check_template = QCOW2_OL_ALL;
1097 error_setg(errp, "Unsupported value '%s' for qcow2 option "
1098 "'overlap-check'. Allowed are any of the following: "
1099 "none, constant, cached, all", opt_overlap_check);
1104 r->overlap_check = 0;
1105 for (i = 0; i < QCOW2_OL_MAX_BITNR; i++) {
1106 /* overlap-check defines a template bitmask, but every flag may be
1107 * overwritten through the associated boolean option */
1109 qemu_opt_get_bool(opts, overlap_bool_option_names[i],
1110 overlap_check_template & (1 << i)) << i;
1113 r->discard_passthrough[QCOW2_DISCARD_NEVER] = false;
1114 r->discard_passthrough[QCOW2_DISCARD_ALWAYS] = true;
1115 r->discard_passthrough[QCOW2_DISCARD_REQUEST] =
1116 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_REQUEST,
1117 flags & BDRV_O_UNMAP);
1118 r->discard_passthrough[QCOW2_DISCARD_SNAPSHOT] =
1119 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_SNAPSHOT, true);
1120 r->discard_passthrough[QCOW2_DISCARD_OTHER] =
1121 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_OTHER, false);
1123 switch (s->crypt_method_header) {
1124 case QCOW_CRYPT_NONE:
1126 error_setg(errp, "No encryption in image header, but options "
1127 "specified format '%s'", encryptfmt);
1133 case QCOW_CRYPT_AES:
1134 if (encryptfmt && !g_str_equal(encryptfmt, "aes")) {
1136 "Header reported 'aes' encryption format but "
1137 "options specify '%s'", encryptfmt);
1141 qdict_put_str(encryptopts, "format", "qcow");
1142 r->crypto_opts = block_crypto_open_opts_init(encryptopts, errp);
1145 case QCOW_CRYPT_LUKS:
1146 if (encryptfmt && !g_str_equal(encryptfmt, "luks")) {
1148 "Header reported 'luks' encryption format but "
1149 "options specify '%s'", encryptfmt);
1153 qdict_put_str(encryptopts, "format", "luks");
1154 r->crypto_opts = block_crypto_open_opts_init(encryptopts, errp);
1158 error_setg(errp, "Unsupported encryption method %d",
1159 s->crypt_method_header);
1162 if (s->crypt_method_header != QCOW_CRYPT_NONE && !r->crypto_opts) {
1169 qobject_unref(encryptopts);
1170 qemu_opts_del(opts);
1175 static void qcow2_update_options_commit(BlockDriverState *bs,
1176 Qcow2ReopenState *r)
1178 BDRVQcow2State *s = bs->opaque;
1181 if (s->l2_table_cache) {
1182 qcow2_cache_destroy(s->l2_table_cache);
1184 if (s->refcount_block_cache) {
1185 qcow2_cache_destroy(s->refcount_block_cache);
1187 s->l2_table_cache = r->l2_table_cache;
1188 s->refcount_block_cache = r->refcount_block_cache;
1189 s->l2_slice_size = r->l2_slice_size;
1191 s->overlap_check = r->overlap_check;
1192 s->use_lazy_refcounts = r->use_lazy_refcounts;
1194 for (i = 0; i < QCOW2_DISCARD_MAX; i++) {
1195 s->discard_passthrough[i] = r->discard_passthrough[i];
1198 if (s->cache_clean_interval != r->cache_clean_interval) {
1199 cache_clean_timer_del(bs);
1200 s->cache_clean_interval = r->cache_clean_interval;
1201 cache_clean_timer_init(bs, bdrv_get_aio_context(bs));
1204 qapi_free_QCryptoBlockOpenOptions(s->crypto_opts);
1205 s->crypto_opts = r->crypto_opts;
1208 static void qcow2_update_options_abort(BlockDriverState *bs,
1209 Qcow2ReopenState *r)
1211 if (r->l2_table_cache) {
1212 qcow2_cache_destroy(r->l2_table_cache);
1214 if (r->refcount_block_cache) {
1215 qcow2_cache_destroy(r->refcount_block_cache);
1217 qapi_free_QCryptoBlockOpenOptions(r->crypto_opts);
1220 static int qcow2_update_options(BlockDriverState *bs, QDict *options,
1221 int flags, Error **errp)
1223 Qcow2ReopenState r = {};
1226 ret = qcow2_update_options_prepare(bs, &r, options, flags, errp);
1228 qcow2_update_options_commit(bs, &r);
1230 qcow2_update_options_abort(bs, &r);
1236 /* Called with s->lock held. */
1237 static int coroutine_fn qcow2_do_open(BlockDriverState *bs, QDict *options,
1238 int flags, Error **errp)
1240 BDRVQcow2State *s = bs->opaque;
1241 unsigned int len, i;
1244 Error *local_err = NULL;
1246 uint64_t l1_vm_state_index;
1247 bool update_header = false;
1249 ret = bdrv_pread(bs->file, 0, &header, sizeof(header));
1251 error_setg_errno(errp, -ret, "Could not read qcow2 header");
1254 header.magic = be32_to_cpu(header.magic);
1255 header.version = be32_to_cpu(header.version);
1256 header.backing_file_offset = be64_to_cpu(header.backing_file_offset);
1257 header.backing_file_size = be32_to_cpu(header.backing_file_size);
1258 header.size = be64_to_cpu(header.size);
1259 header.cluster_bits = be32_to_cpu(header.cluster_bits);
1260 header.crypt_method = be32_to_cpu(header.crypt_method);
1261 header.l1_table_offset = be64_to_cpu(header.l1_table_offset);
1262 header.l1_size = be32_to_cpu(header.l1_size);
1263 header.refcount_table_offset = be64_to_cpu(header.refcount_table_offset);
1264 header.refcount_table_clusters =
1265 be32_to_cpu(header.refcount_table_clusters);
1266 header.snapshots_offset = be64_to_cpu(header.snapshots_offset);
1267 header.nb_snapshots = be32_to_cpu(header.nb_snapshots);
1269 if (header.magic != QCOW_MAGIC) {
1270 error_setg(errp, "Image is not in qcow2 format");
1274 if (header.version < 2 || header.version > 3) {
1275 error_setg(errp, "Unsupported qcow2 version %" PRIu32, header.version);
1280 s->qcow_version = header.version;
1282 /* Initialise cluster size */
1283 if (header.cluster_bits < MIN_CLUSTER_BITS ||
1284 header.cluster_bits > MAX_CLUSTER_BITS) {
1285 error_setg(errp, "Unsupported cluster size: 2^%" PRIu32,
1286 header.cluster_bits);
1291 s->cluster_bits = header.cluster_bits;
1292 s->cluster_size = 1 << s->cluster_bits;
1294 /* Initialise version 3 header fields */
1295 if (header.version == 2) {
1296 header.incompatible_features = 0;
1297 header.compatible_features = 0;
1298 header.autoclear_features = 0;
1299 header.refcount_order = 4;
1300 header.header_length = 72;
1302 header.incompatible_features =
1303 be64_to_cpu(header.incompatible_features);
1304 header.compatible_features = be64_to_cpu(header.compatible_features);
1305 header.autoclear_features = be64_to_cpu(header.autoclear_features);
1306 header.refcount_order = be32_to_cpu(header.refcount_order);
1307 header.header_length = be32_to_cpu(header.header_length);
1309 if (header.header_length < 104) {
1310 error_setg(errp, "qcow2 header too short");
1316 if (header.header_length > s->cluster_size) {
1317 error_setg(errp, "qcow2 header exceeds cluster size");
1322 if (header.header_length > sizeof(header)) {
1323 s->unknown_header_fields_size = header.header_length - sizeof(header);
1324 s->unknown_header_fields = g_malloc(s->unknown_header_fields_size);
1325 ret = bdrv_pread(bs->file, sizeof(header), s->unknown_header_fields,
1326 s->unknown_header_fields_size);
1328 error_setg_errno(errp, -ret, "Could not read unknown qcow2 header "
1334 if (header.backing_file_offset > s->cluster_size) {
1335 error_setg(errp, "Invalid backing file offset");
1340 if (header.backing_file_offset) {
1341 ext_end = header.backing_file_offset;
1343 ext_end = 1 << header.cluster_bits;
1346 /* Handle feature bits */
1347 s->incompatible_features = header.incompatible_features;
1348 s->compatible_features = header.compatible_features;
1349 s->autoclear_features = header.autoclear_features;
1351 if (s->incompatible_features & ~QCOW2_INCOMPAT_MASK) {
1352 void *feature_table = NULL;
1353 qcow2_read_extensions(bs, header.header_length, ext_end,
1354 &feature_table, flags, NULL, NULL);
1355 report_unsupported_feature(errp, feature_table,
1356 s->incompatible_features &
1357 ~QCOW2_INCOMPAT_MASK);
1359 g_free(feature_table);
1363 if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
1364 /* Corrupt images may not be written to unless they are being repaired
1366 if ((flags & BDRV_O_RDWR) && !(flags & BDRV_O_CHECK)) {
1367 error_setg(errp, "qcow2: Image is corrupt; cannot be opened "
1374 /* Check support for various header values */
1375 if (header.refcount_order > 6) {
1376 error_setg(errp, "Reference count entry width too large; may not "
1381 s->refcount_order = header.refcount_order;
1382 s->refcount_bits = 1 << s->refcount_order;
1383 s->refcount_max = UINT64_C(1) << (s->refcount_bits - 1);
1384 s->refcount_max += s->refcount_max - 1;
1386 s->crypt_method_header = header.crypt_method;
1387 if (s->crypt_method_header) {
1388 if (bdrv_uses_whitelist() &&
1389 s->crypt_method_header == QCOW_CRYPT_AES) {
1391 "Use of AES-CBC encrypted qcow2 images is no longer "
1392 "supported in system emulators");
1393 error_append_hint(errp,
1394 "You can use 'qemu-img convert' to convert your "
1395 "image to an alternative supported format, such "
1396 "as unencrypted qcow2, or raw with the LUKS "
1397 "format instead.\n");
1402 if (s->crypt_method_header == QCOW_CRYPT_AES) {
1403 s->crypt_physical_offset = false;
1405 /* Assuming LUKS and any future crypt methods we
1406 * add will all use physical offsets, due to the
1407 * fact that the alternative is insecure... */
1408 s->crypt_physical_offset = true;
1411 bs->encrypted = true;
1414 s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */
1415 s->l2_size = 1 << s->l2_bits;
1416 /* 2^(s->refcount_order - 3) is the refcount width in bytes */
1417 s->refcount_block_bits = s->cluster_bits - (s->refcount_order - 3);
1418 s->refcount_block_size = 1 << s->refcount_block_bits;
1419 bs->total_sectors = header.size / BDRV_SECTOR_SIZE;
1420 s->csize_shift = (62 - (s->cluster_bits - 8));
1421 s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;
1422 s->cluster_offset_mask = (1LL << s->csize_shift) - 1;
1424 s->refcount_table_offset = header.refcount_table_offset;
1425 s->refcount_table_size =
1426 header.refcount_table_clusters << (s->cluster_bits - 3);
1428 if (header.refcount_table_clusters == 0 && !(flags & BDRV_O_CHECK)) {
1429 error_setg(errp, "Image does not contain a reference count table");
1434 ret = qcow2_validate_table(bs, s->refcount_table_offset,
1435 header.refcount_table_clusters,
1436 s->cluster_size, QCOW_MAX_REFTABLE_SIZE,
1437 "Reference count table", errp);
1442 if (!(flags & BDRV_O_CHECK)) {
1444 * The total size in bytes of the snapshot table is checked in
1445 * qcow2_read_snapshots() because the size of each snapshot is
1446 * variable and we don't know it yet.
1447 * Here we only check the offset and number of snapshots.
1449 ret = qcow2_validate_table(bs, header.snapshots_offset,
1450 header.nb_snapshots,
1451 sizeof(QCowSnapshotHeader),
1452 sizeof(QCowSnapshotHeader) *
1454 "Snapshot table", errp);
1460 /* read the level 1 table */
1461 ret = qcow2_validate_table(bs, header.l1_table_offset,
1462 header.l1_size, sizeof(uint64_t),
1463 QCOW_MAX_L1_SIZE, "Active L1 table", errp);
1467 s->l1_size = header.l1_size;
1468 s->l1_table_offset = header.l1_table_offset;
1470 l1_vm_state_index = size_to_l1(s, header.size);
1471 if (l1_vm_state_index > INT_MAX) {
1472 error_setg(errp, "Image is too big");
1476 s->l1_vm_state_index = l1_vm_state_index;
1478 /* the L1 table must contain at least enough entries to put
1479 header.size bytes */
1480 if (s->l1_size < s->l1_vm_state_index) {
1481 error_setg(errp, "L1 table is too small");
1486 if (s->l1_size > 0) {
1487 s->l1_table = qemu_try_blockalign(bs->file->bs,
1488 ROUND_UP(s->l1_size * sizeof(uint64_t), 512));
1489 if (s->l1_table == NULL) {
1490 error_setg(errp, "Could not allocate L1 table");
1494 ret = bdrv_pread(bs->file, s->l1_table_offset, s->l1_table,
1495 s->l1_size * sizeof(uint64_t));
1497 error_setg_errno(errp, -ret, "Could not read L1 table");
1500 for(i = 0;i < s->l1_size; i++) {
1501 s->l1_table[i] = be64_to_cpu(s->l1_table[i]);
1505 /* Parse driver-specific options */
1506 ret = qcow2_update_options(bs, options, flags, errp);
1513 ret = qcow2_refcount_init(bs);
1515 error_setg_errno(errp, -ret, "Could not initialize refcount handling");
1519 QLIST_INIT(&s->cluster_allocs);
1520 QTAILQ_INIT(&s->discards);
1522 /* read qcow2 extensions */
1523 if (qcow2_read_extensions(bs, header.header_length, ext_end, NULL,
1524 flags, &update_header, &local_err)) {
1525 error_propagate(errp, local_err);
1530 /* Open external data file */
1531 s->data_file = bdrv_open_child(NULL, options, "data-file", bs, &child_file,
1534 error_propagate(errp, local_err);
1539 if (s->incompatible_features & QCOW2_INCOMPAT_DATA_FILE) {
1540 if (!s->data_file && s->image_data_file) {
1541 s->data_file = bdrv_open_child(s->image_data_file, options,
1542 "data-file", bs, &child_file,
1544 if (!s->data_file) {
1549 if (!s->data_file) {
1550 error_setg(errp, "'data-file' is required for this image");
1556 error_setg(errp, "'data-file' can only be set for images with an "
1557 "external data file");
1562 s->data_file = bs->file;
1564 if (data_file_is_raw(bs)) {
1565 error_setg(errp, "data-file-raw requires a data file");
1571 /* qcow2_read_extension may have set up the crypto context
1572 * if the crypt method needs a header region, some methods
1573 * don't need header extensions, so must check here
1575 if (s->crypt_method_header && !s->crypto) {
1576 if (s->crypt_method_header == QCOW_CRYPT_AES) {
1577 unsigned int cflags = 0;
1578 if (flags & BDRV_O_NO_IO) {
1579 cflags |= QCRYPTO_BLOCK_OPEN_NO_IO;
1581 s->crypto = qcrypto_block_open(s->crypto_opts, "encrypt.",
1583 QCOW2_MAX_THREADS, errp);
1588 } else if (!(flags & BDRV_O_NO_IO)) {
1589 error_setg(errp, "Missing CRYPTO header for crypt method %d",
1590 s->crypt_method_header);
1596 /* read the backing file name */
1597 if (header.backing_file_offset != 0) {
1598 len = header.backing_file_size;
1599 if (len > MIN(1023, s->cluster_size - header.backing_file_offset) ||
1600 len >= sizeof(bs->backing_file)) {
1601 error_setg(errp, "Backing file name too long");
1605 ret = bdrv_pread(bs->file, header.backing_file_offset,
1606 bs->auto_backing_file, len);
1608 error_setg_errno(errp, -ret, "Could not read backing file name");
1611 bs->auto_backing_file[len] = '\0';
1612 pstrcpy(bs->backing_file, sizeof(bs->backing_file),
1613 bs->auto_backing_file);
1614 s->image_backing_file = g_strdup(bs->auto_backing_file);
1618 * Internal snapshots; skip reading them in check mode, because
1619 * we do not need them then, and we do not want to abort because
1620 * of a broken table.
1622 if (!(flags & BDRV_O_CHECK)) {
1623 s->snapshots_offset = header.snapshots_offset;
1624 s->nb_snapshots = header.nb_snapshots;
1626 ret = qcow2_read_snapshots(bs, errp);
1632 /* Clear unknown autoclear feature bits */
1633 update_header |= s->autoclear_features & ~QCOW2_AUTOCLEAR_MASK;
1635 update_header && !bs->read_only && !(flags & BDRV_O_INACTIVE);
1636 if (update_header) {
1637 s->autoclear_features &= QCOW2_AUTOCLEAR_MASK;
1640 /* == Handle persistent dirty bitmaps ==
1642 * We want load dirty bitmaps in three cases:
1644 * 1. Normal open of the disk in active mode, not related to invalidation
1647 * 2. Invalidation of the target vm after pre-copy phase of migration, if
1648 * bitmaps are _not_ migrating through migration channel, i.e.
1649 * 'dirty-bitmaps' capability is disabled.
1651 * 3. Invalidation of source vm after failed or canceled migration.
1652 * This is a very interesting case. There are two possible types of
1655 * A. Stored on inactivation and removed. They should be loaded from the
1658 * B. Not stored: not-persistent bitmaps and bitmaps, migrated through
1659 * the migration channel (with dirty-bitmaps capability).
1661 * On the other hand, there are two possible sub-cases:
1663 * 3.1 disk was changed by somebody else while were inactive. In this
1664 * case all in-RAM dirty bitmaps (both persistent and not) are
1665 * definitely invalid. And we don't have any method to determine
1668 * Simple and safe thing is to just drop all the bitmaps of type B on
1669 * inactivation. But in this case we lose bitmaps in valid 4.2 case.
1671 * On the other hand, resuming source vm, if disk was already changed
1672 * is a bad thing anyway: not only bitmaps, the whole vm state is
1673 * out of sync with disk.
1675 * This means, that user or management tool, who for some reason
1676 * decided to resume source vm, after disk was already changed by
1677 * target vm, should at least drop all dirty bitmaps by hand.
1679 * So, we can ignore this case for now, but TODO: "generation"
1680 * extension for qcow2, to determine, that image was changed after
1681 * last inactivation. And if it is changed, we will drop (or at least
1682 * mark as 'invalid' all the bitmaps of type B, both persistent
1685 * 3.2 disk was _not_ changed while were inactive. Bitmaps may be saved
1686 * to disk ('dirty-bitmaps' capability disabled), or not saved
1687 * ('dirty-bitmaps' capability enabled), but we don't need to care
1688 * of: let's load bitmaps as always: stored bitmaps will be loaded,
1689 * and not stored has flag IN_USE=1 in the image and will be skipped
1692 * One remaining possible case when we don't want load bitmaps:
1694 * 4. Open disk in inactive mode in target vm (bitmaps are migrating or
1695 * will be loaded on invalidation, no needs try loading them before)
1698 if (!(bdrv_get_flags(bs) & BDRV_O_INACTIVE)) {
1699 /* It's case 1, 2 or 3.2. Or 3.1 which is BUG in management layer. */
1700 bool header_updated = qcow2_load_dirty_bitmaps(bs, &local_err);
1702 update_header = update_header && !header_updated;
1704 if (local_err != NULL) {
1705 error_propagate(errp, local_err);
1710 if (update_header) {
1711 ret = qcow2_update_header(bs);
1713 error_setg_errno(errp, -ret, "Could not update qcow2 header");
1718 bs->supported_zero_flags = header.version >= 3 ? BDRV_REQ_MAY_UNMAP : 0;
1720 /* Repair image if dirty */
1721 if (!(flags & (BDRV_O_CHECK | BDRV_O_INACTIVE)) && !bs->read_only &&
1722 (s->incompatible_features & QCOW2_INCOMPAT_DIRTY)) {
1723 BdrvCheckResult result = {0};
1725 ret = qcow2_co_check_locked(bs, &result,
1726 BDRV_FIX_ERRORS | BDRV_FIX_LEAKS);
1727 if (ret < 0 || result.check_errors) {
1731 error_setg_errno(errp, -ret, "Could not repair dirty image");
1738 BdrvCheckResult result = {0};
1739 qcow2_check_refcounts(bs, &result, 0);
1743 qemu_co_queue_init(&s->thread_task_queue);
1748 g_free(s->image_data_file);
1749 if (has_data_file(bs)) {
1750 bdrv_unref_child(bs, s->data_file);
1752 g_free(s->unknown_header_fields);
1753 cleanup_unknown_header_ext(bs);
1754 qcow2_free_snapshots(bs);
1755 qcow2_refcount_close(bs);
1756 qemu_vfree(s->l1_table);
1757 /* else pre-write overlap checks in cache_destroy may crash */
1759 cache_clean_timer_del(bs);
1760 if (s->l2_table_cache) {
1761 qcow2_cache_destroy(s->l2_table_cache);
1763 if (s->refcount_block_cache) {
1764 qcow2_cache_destroy(s->refcount_block_cache);
1766 qcrypto_block_free(s->crypto);
1767 qapi_free_QCryptoBlockOpenOptions(s->crypto_opts);
1771 typedef struct QCow2OpenCo {
1772 BlockDriverState *bs;
1779 static void coroutine_fn qcow2_open_entry(void *opaque)
1781 QCow2OpenCo *qoc = opaque;
1782 BDRVQcow2State *s = qoc->bs->opaque;
1784 qemu_co_mutex_lock(&s->lock);
1785 qoc->ret = qcow2_do_open(qoc->bs, qoc->options, qoc->flags, qoc->errp);
1786 qemu_co_mutex_unlock(&s->lock);
1789 static int qcow2_open(BlockDriverState *bs, QDict *options, int flags,
1792 BDRVQcow2State *s = bs->opaque;
1801 bs->file = bdrv_open_child(NULL, options, "file", bs, &child_file,
1807 /* Initialise locks */
1808 qemu_co_mutex_init(&s->lock);
1810 if (qemu_in_coroutine()) {
1811 /* From bdrv_co_create. */
1812 qcow2_open_entry(&qoc);
1814 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
1815 qemu_coroutine_enter(qemu_coroutine_create(qcow2_open_entry, &qoc));
1816 BDRV_POLL_WHILE(bs, qoc.ret == -EINPROGRESS);
1821 static void qcow2_refresh_limits(BlockDriverState *bs, Error **errp)
1823 BDRVQcow2State *s = bs->opaque;
1825 if (bs->encrypted) {
1826 /* Encryption works on a sector granularity */
1827 bs->bl.request_alignment = qcrypto_block_get_sector_size(s->crypto);
1829 bs->bl.pwrite_zeroes_alignment = s->cluster_size;
1830 bs->bl.pdiscard_alignment = s->cluster_size;
1833 static int qcow2_reopen_prepare(BDRVReopenState *state,
1834 BlockReopenQueue *queue, Error **errp)
1836 Qcow2ReopenState *r;
1839 r = g_new0(Qcow2ReopenState, 1);
1842 ret = qcow2_update_options_prepare(state->bs, r, state->options,
1843 state->flags, errp);
1848 /* We need to write out any unwritten data if we reopen read-only. */
1849 if ((state->flags & BDRV_O_RDWR) == 0) {
1850 ret = qcow2_reopen_bitmaps_ro(state->bs, errp);
1855 ret = bdrv_flush(state->bs);
1860 ret = qcow2_mark_clean(state->bs);
1869 qcow2_update_options_abort(state->bs, r);
1874 static void qcow2_reopen_commit(BDRVReopenState *state)
1876 qcow2_update_options_commit(state->bs, state->opaque);
1877 if (state->flags & BDRV_O_RDWR) {
1878 Error *local_err = NULL;
1880 if (qcow2_reopen_bitmaps_rw(state->bs, &local_err) < 0) {
1882 * This is not fatal, bitmaps just left read-only, so all following
1883 * writes will fail. User can remove read-only bitmaps to unblock
1884 * writes or retry reopen.
1886 error_reportf_err(local_err,
1887 "%s: Failed to make dirty bitmaps writable: ",
1888 bdrv_get_node_name(state->bs));
1891 g_free(state->opaque);
1894 static void qcow2_reopen_abort(BDRVReopenState *state)
1896 qcow2_update_options_abort(state->bs, state->opaque);
1897 g_free(state->opaque);
1900 static void qcow2_join_options(QDict *options, QDict *old_options)
1902 bool has_new_overlap_template =
1903 qdict_haskey(options, QCOW2_OPT_OVERLAP) ||
1904 qdict_haskey(options, QCOW2_OPT_OVERLAP_TEMPLATE);
1905 bool has_new_total_cache_size =
1906 qdict_haskey(options, QCOW2_OPT_CACHE_SIZE);
1907 bool has_all_cache_options;
1909 /* New overlap template overrides all old overlap options */
1910 if (has_new_overlap_template) {
1911 qdict_del(old_options, QCOW2_OPT_OVERLAP);
1912 qdict_del(old_options, QCOW2_OPT_OVERLAP_TEMPLATE);
1913 qdict_del(old_options, QCOW2_OPT_OVERLAP_MAIN_HEADER);
1914 qdict_del(old_options, QCOW2_OPT_OVERLAP_ACTIVE_L1);
1915 qdict_del(old_options, QCOW2_OPT_OVERLAP_ACTIVE_L2);
1916 qdict_del(old_options, QCOW2_OPT_OVERLAP_REFCOUNT_TABLE);
1917 qdict_del(old_options, QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK);
1918 qdict_del(old_options, QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE);
1919 qdict_del(old_options, QCOW2_OPT_OVERLAP_INACTIVE_L1);
1920 qdict_del(old_options, QCOW2_OPT_OVERLAP_INACTIVE_L2);
1923 /* New total cache size overrides all old options */
1924 if (qdict_haskey(options, QCOW2_OPT_CACHE_SIZE)) {
1925 qdict_del(old_options, QCOW2_OPT_L2_CACHE_SIZE);
1926 qdict_del(old_options, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
1929 qdict_join(options, old_options, false);
1932 * If after merging all cache size options are set, an old total size is
1933 * overwritten. Do keep all options, however, if all three are new. The
1934 * resulting error message is what we want to happen.
1936 has_all_cache_options =
1937 qdict_haskey(options, QCOW2_OPT_CACHE_SIZE) ||
1938 qdict_haskey(options, QCOW2_OPT_L2_CACHE_SIZE) ||
1939 qdict_haskey(options, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
1941 if (has_all_cache_options && !has_new_total_cache_size) {
1942 qdict_del(options, QCOW2_OPT_CACHE_SIZE);
1946 static int coroutine_fn qcow2_co_block_status(BlockDriverState *bs,
1948 int64_t offset, int64_t count,
1949 int64_t *pnum, int64_t *map,
1950 BlockDriverState **file)
1952 BDRVQcow2State *s = bs->opaque;
1953 uint64_t cluster_offset;
1954 int index_in_cluster, ret;
1958 qemu_co_mutex_lock(&s->lock);
1960 if (!s->metadata_preallocation_checked) {
1961 ret = qcow2_detect_metadata_preallocation(bs);
1962 s->metadata_preallocation = (ret == 1);
1963 s->metadata_preallocation_checked = true;
1966 bytes = MIN(INT_MAX, count);
1967 ret = qcow2_get_cluster_offset(bs, offset, &bytes, &cluster_offset);
1968 qemu_co_mutex_unlock(&s->lock);
1975 if ((ret == QCOW2_CLUSTER_NORMAL || ret == QCOW2_CLUSTER_ZERO_ALLOC) &&
1977 index_in_cluster = offset & (s->cluster_size - 1);
1978 *map = cluster_offset | index_in_cluster;
1979 *file = s->data_file->bs;
1980 status |= BDRV_BLOCK_OFFSET_VALID;
1982 if (ret == QCOW2_CLUSTER_ZERO_PLAIN || ret == QCOW2_CLUSTER_ZERO_ALLOC) {
1983 status |= BDRV_BLOCK_ZERO;
1984 } else if (ret != QCOW2_CLUSTER_UNALLOCATED) {
1985 status |= BDRV_BLOCK_DATA;
1987 if (s->metadata_preallocation && (status & BDRV_BLOCK_DATA) &&
1988 (status & BDRV_BLOCK_OFFSET_VALID))
1990 status |= BDRV_BLOCK_RECURSE;
1995 static coroutine_fn int qcow2_handle_l2meta(BlockDriverState *bs,
1996 QCowL2Meta **pl2meta,
2000 QCowL2Meta *l2meta = *pl2meta;
2002 while (l2meta != NULL) {
2006 ret = qcow2_alloc_cluster_link_l2(bs, l2meta);
2011 qcow2_alloc_cluster_abort(bs, l2meta);
2014 /* Take the request off the list of running requests */
2015 if (l2meta->nb_clusters != 0) {
2016 QLIST_REMOVE(l2meta, next_in_flight);
2019 qemu_co_queue_restart_all(&l2meta->dependent_requests);
2021 next = l2meta->next;
2030 static coroutine_fn int
2031 qcow2_co_preadv_encrypted(BlockDriverState *bs,
2032 uint64_t file_cluster_offset,
2036 uint64_t qiov_offset)
2039 BDRVQcow2State *s = bs->opaque;
2042 assert(bs->encrypted && s->crypto);
2043 assert(bytes <= QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
2046 * For encrypted images, read everything into a temporary
2047 * contiguous buffer on which the AES functions can work.
2048 * Also, decryption in a separate buffer is better as it
2049 * prevents the guest from learning information about the
2050 * encrypted nature of the virtual disk.
2053 buf = qemu_try_blockalign(s->data_file->bs, bytes);
2058 BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);
2059 ret = bdrv_co_pread(s->data_file,
2060 file_cluster_offset + offset_into_cluster(s, offset),
2066 assert(QEMU_IS_ALIGNED(offset, BDRV_SECTOR_SIZE));
2067 assert(QEMU_IS_ALIGNED(bytes, BDRV_SECTOR_SIZE));
2068 if (qcow2_co_decrypt(bs,
2069 file_cluster_offset + offset_into_cluster(s, offset),
2070 offset, buf, bytes) < 0)
2075 qemu_iovec_from_buf(qiov, qiov_offset, buf, bytes);
2083 typedef struct Qcow2AioTask {
2086 BlockDriverState *bs;
2087 QCow2ClusterType cluster_type; /* only for read */
2088 uint64_t file_cluster_offset;
2092 uint64_t qiov_offset;
2093 QCowL2Meta *l2meta; /* only for write */
2096 static coroutine_fn int qcow2_co_preadv_task_entry(AioTask *task);
2097 static coroutine_fn int qcow2_add_task(BlockDriverState *bs,
2100 QCow2ClusterType cluster_type,
2101 uint64_t file_cluster_offset,
2108 Qcow2AioTask local_task;
2109 Qcow2AioTask *task = pool ? g_new(Qcow2AioTask, 1) : &local_task;
2111 *task = (Qcow2AioTask) {
2114 .cluster_type = cluster_type,
2116 .file_cluster_offset = file_cluster_offset,
2119 .qiov_offset = qiov_offset,
2123 trace_qcow2_add_task(qemu_coroutine_self(), bs, pool,
2124 func == qcow2_co_preadv_task_entry ? "read" : "write",
2125 cluster_type, file_cluster_offset, offset, bytes,
2129 return func(&task->task);
2132 aio_task_pool_start_task(pool, &task->task);
2137 static coroutine_fn int qcow2_co_preadv_task(BlockDriverState *bs,
2138 QCow2ClusterType cluster_type,
2139 uint64_t file_cluster_offset,
2140 uint64_t offset, uint64_t bytes,
2144 BDRVQcow2State *s = bs->opaque;
2145 int offset_in_cluster = offset_into_cluster(s, offset);
2147 switch (cluster_type) {
2148 case QCOW2_CLUSTER_ZERO_PLAIN:
2149 case QCOW2_CLUSTER_ZERO_ALLOC:
2150 /* Both zero types are handled in qcow2_co_preadv_part */
2151 g_assert_not_reached();
2153 case QCOW2_CLUSTER_UNALLOCATED:
2154 assert(bs->backing); /* otherwise handled in qcow2_co_preadv_part */
2156 BLKDBG_EVENT(bs->file, BLKDBG_READ_BACKING_AIO);
2157 return bdrv_co_preadv_part(bs->backing, offset, bytes,
2158 qiov, qiov_offset, 0);
2160 case QCOW2_CLUSTER_COMPRESSED:
2161 return qcow2_co_preadv_compressed(bs, file_cluster_offset,
2162 offset, bytes, qiov, qiov_offset);
2164 case QCOW2_CLUSTER_NORMAL:
2165 if ((file_cluster_offset & 511) != 0) {
2169 if (bs->encrypted) {
2170 return qcow2_co_preadv_encrypted(bs, file_cluster_offset,
2171 offset, bytes, qiov, qiov_offset);
2174 BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);
2175 return bdrv_co_preadv_part(s->data_file,
2176 file_cluster_offset + offset_in_cluster,
2177 bytes, qiov, qiov_offset, 0);
2180 g_assert_not_reached();
2183 g_assert_not_reached();
2186 static coroutine_fn int qcow2_co_preadv_task_entry(AioTask *task)
2188 Qcow2AioTask *t = container_of(task, Qcow2AioTask, task);
2192 return qcow2_co_preadv_task(t->bs, t->cluster_type, t->file_cluster_offset,
2193 t->offset, t->bytes, t->qiov, t->qiov_offset);
2196 static coroutine_fn int qcow2_co_preadv_part(BlockDriverState *bs,
2197 uint64_t offset, uint64_t bytes,
2199 size_t qiov_offset, int flags)
2201 BDRVQcow2State *s = bs->opaque;
2203 unsigned int cur_bytes; /* number of bytes in current iteration */
2204 uint64_t cluster_offset = 0;
2205 AioTaskPool *aio = NULL;
2207 while (bytes != 0 && aio_task_pool_status(aio) == 0) {
2208 /* prepare next request */
2209 cur_bytes = MIN(bytes, INT_MAX);
2211 cur_bytes = MIN(cur_bytes,
2212 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
2215 qemu_co_mutex_lock(&s->lock);
2216 ret = qcow2_get_cluster_offset(bs, offset, &cur_bytes, &cluster_offset);
2217 qemu_co_mutex_unlock(&s->lock);
2222 if (ret == QCOW2_CLUSTER_ZERO_PLAIN ||
2223 ret == QCOW2_CLUSTER_ZERO_ALLOC ||
2224 (ret == QCOW2_CLUSTER_UNALLOCATED && !bs->backing))
2226 qemu_iovec_memset(qiov, qiov_offset, 0, cur_bytes);
2228 if (!aio && cur_bytes != bytes) {
2229 aio = aio_task_pool_new(QCOW2_MAX_WORKERS);
2231 ret = qcow2_add_task(bs, aio, qcow2_co_preadv_task_entry, ret,
2232 cluster_offset, offset, cur_bytes,
2233 qiov, qiov_offset, NULL);
2240 offset += cur_bytes;
2241 qiov_offset += cur_bytes;
2246 aio_task_pool_wait_all(aio);
2248 ret = aio_task_pool_status(aio);
2256 /* Check if it's possible to merge a write request with the writing of
2257 * the data from the COW regions */
2258 static bool merge_cow(uint64_t offset, unsigned bytes,
2259 QEMUIOVector *qiov, size_t qiov_offset,
2264 for (m = l2meta; m != NULL; m = m->next) {
2265 /* If both COW regions are empty then there's nothing to merge */
2266 if (m->cow_start.nb_bytes == 0 && m->cow_end.nb_bytes == 0) {
2270 /* If COW regions are handled already, skip this too */
2275 /* The data (middle) region must be immediately after the
2277 if (l2meta_cow_start(m) + m->cow_start.nb_bytes != offset) {
2281 /* The end region must be immediately after the data (middle)
2283 if (m->offset + m->cow_end.offset != offset + bytes) {
2287 /* Make sure that adding both COW regions to the QEMUIOVector
2288 * does not exceed IOV_MAX */
2289 if (qemu_iovec_subvec_niov(qiov, qiov_offset, bytes) > IOV_MAX - 2) {
2293 m->data_qiov = qiov;
2294 m->data_qiov_offset = qiov_offset;
2301 static bool is_unallocated(BlockDriverState *bs, int64_t offset, int64_t bytes)
2305 (!bdrv_is_allocated_above(bs, NULL, false, offset, bytes, &nr) &&
2309 static bool is_zero_cow(BlockDriverState *bs, QCowL2Meta *m)
2312 * This check is designed for optimization shortcut so it must be
2314 * Instead of is_zero(), use is_unallocated() as it is faster (but not
2315 * as accurate and can result in false negatives).
2317 return is_unallocated(bs, m->offset + m->cow_start.offset,
2318 m->cow_start.nb_bytes) &&
2319 is_unallocated(bs, m->offset + m->cow_end.offset,
2320 m->cow_end.nb_bytes);
2323 static int handle_alloc_space(BlockDriverState *bs, QCowL2Meta *l2meta)
2325 BDRVQcow2State *s = bs->opaque;
2328 if (!(s->data_file->bs->supported_zero_flags & BDRV_REQ_NO_FALLBACK)) {
2332 if (bs->encrypted) {
2336 for (m = l2meta; m != NULL; m = m->next) {
2339 if (!m->cow_start.nb_bytes && !m->cow_end.nb_bytes) {
2343 if (!is_zero_cow(bs, m)) {
2348 * instead of writing zero COW buffers,
2349 * efficiently zero out the whole clusters
2352 ret = qcow2_pre_write_overlap_check(bs, 0, m->alloc_offset,
2353 m->nb_clusters * s->cluster_size,
2359 BLKDBG_EVENT(bs->file, BLKDBG_CLUSTER_ALLOC_SPACE);
2360 ret = bdrv_co_pwrite_zeroes(s->data_file, m->alloc_offset,
2361 m->nb_clusters * s->cluster_size,
2362 BDRV_REQ_NO_FALLBACK);
2364 if (ret != -ENOTSUP && ret != -EAGAIN) {
2370 trace_qcow2_skip_cow(qemu_coroutine_self(), m->offset, m->nb_clusters);
2377 * qcow2_co_pwritev_task
2378 * Called with s->lock unlocked
2379 * l2meta - if not NULL, qcow2_co_pwritev_task() will consume it. Caller must
2380 * not use it somehow after qcow2_co_pwritev_task() call
2382 static coroutine_fn int qcow2_co_pwritev_task(BlockDriverState *bs,
2383 uint64_t file_cluster_offset,
2384 uint64_t offset, uint64_t bytes,
2386 uint64_t qiov_offset,
2390 BDRVQcow2State *s = bs->opaque;
2391 void *crypt_buf = NULL;
2392 int offset_in_cluster = offset_into_cluster(s, offset);
2393 QEMUIOVector encrypted_qiov;
2395 if (bs->encrypted) {
2397 assert(bytes <= QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
2398 crypt_buf = qemu_try_blockalign(bs->file->bs, bytes);
2399 if (crypt_buf == NULL) {
2403 qemu_iovec_to_buf(qiov, qiov_offset, crypt_buf, bytes);
2405 if (qcow2_co_encrypt(bs, file_cluster_offset + offset_in_cluster,
2406 offset, crypt_buf, bytes) < 0)
2412 qemu_iovec_init_buf(&encrypted_qiov, crypt_buf, bytes);
2413 qiov = &encrypted_qiov;
2417 /* Try to efficiently initialize the physical space with zeroes */
2418 ret = handle_alloc_space(bs, l2meta);
2424 * If we need to do COW, check if it's possible to merge the
2425 * writing of the guest data together with that of the COW regions.
2426 * If it's not possible (or not necessary) then write the
2429 if (!merge_cow(offset, bytes, qiov, qiov_offset, l2meta)) {
2430 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO);
2431 trace_qcow2_writev_data(qemu_coroutine_self(),
2432 file_cluster_offset + offset_in_cluster);
2433 ret = bdrv_co_pwritev_part(s->data_file,
2434 file_cluster_offset + offset_in_cluster,
2435 bytes, qiov, qiov_offset, 0);
2441 qemu_co_mutex_lock(&s->lock);
2443 ret = qcow2_handle_l2meta(bs, &l2meta, true);
2447 qemu_co_mutex_lock(&s->lock);
2450 qcow2_handle_l2meta(bs, &l2meta, false);
2451 qemu_co_mutex_unlock(&s->lock);
2453 qemu_vfree(crypt_buf);
2458 static coroutine_fn int qcow2_co_pwritev_task_entry(AioTask *task)
2460 Qcow2AioTask *t = container_of(task, Qcow2AioTask, task);
2462 assert(!t->cluster_type);
2464 return qcow2_co_pwritev_task(t->bs, t->file_cluster_offset,
2465 t->offset, t->bytes, t->qiov, t->qiov_offset,
2469 static coroutine_fn int qcow2_co_pwritev_part(
2470 BlockDriverState *bs, uint64_t offset, uint64_t bytes,
2471 QEMUIOVector *qiov, size_t qiov_offset, int flags)
2473 BDRVQcow2State *s = bs->opaque;
2474 int offset_in_cluster;
2476 unsigned int cur_bytes; /* number of sectors in current iteration */
2477 uint64_t cluster_offset;
2478 QCowL2Meta *l2meta = NULL;
2479 AioTaskPool *aio = NULL;
2481 trace_qcow2_writev_start_req(qemu_coroutine_self(), offset, bytes);
2483 while (bytes != 0 && aio_task_pool_status(aio) == 0) {
2487 trace_qcow2_writev_start_part(qemu_coroutine_self());
2488 offset_in_cluster = offset_into_cluster(s, offset);
2489 cur_bytes = MIN(bytes, INT_MAX);
2490 if (bs->encrypted) {
2491 cur_bytes = MIN(cur_bytes,
2492 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size
2493 - offset_in_cluster);
2496 qemu_co_mutex_lock(&s->lock);
2498 ret = qcow2_alloc_cluster_offset(bs, offset, &cur_bytes,
2499 &cluster_offset, &l2meta);
2504 assert((cluster_offset & 511) == 0);
2506 ret = qcow2_pre_write_overlap_check(bs, 0,
2507 cluster_offset + offset_in_cluster,
2513 qemu_co_mutex_unlock(&s->lock);
2515 if (!aio && cur_bytes != bytes) {
2516 aio = aio_task_pool_new(QCOW2_MAX_WORKERS);
2518 ret = qcow2_add_task(bs, aio, qcow2_co_pwritev_task_entry, 0,
2519 cluster_offset, offset, cur_bytes,
2520 qiov, qiov_offset, l2meta);
2521 l2meta = NULL; /* l2meta is consumed by qcow2_co_pwritev_task() */
2527 offset += cur_bytes;
2528 qiov_offset += cur_bytes;
2529 trace_qcow2_writev_done_part(qemu_coroutine_self(), cur_bytes);
2533 qemu_co_mutex_lock(&s->lock);
2536 qcow2_handle_l2meta(bs, &l2meta, false);
2538 qemu_co_mutex_unlock(&s->lock);
2542 aio_task_pool_wait_all(aio);
2544 ret = aio_task_pool_status(aio);
2549 trace_qcow2_writev_done_req(qemu_coroutine_self(), ret);
2554 static int qcow2_inactivate(BlockDriverState *bs)
2556 BDRVQcow2State *s = bs->opaque;
2557 int ret, result = 0;
2558 Error *local_err = NULL;
2560 qcow2_store_persistent_dirty_bitmaps(bs, true, &local_err);
2561 if (local_err != NULL) {
2563 error_reportf_err(local_err, "Lost persistent bitmaps during "
2564 "inactivation of node '%s': ",
2565 bdrv_get_device_or_node_name(bs));
2568 ret = qcow2_cache_flush(bs, s->l2_table_cache);
2571 error_report("Failed to flush the L2 table cache: %s",
2575 ret = qcow2_cache_flush(bs, s->refcount_block_cache);
2578 error_report("Failed to flush the refcount block cache: %s",
2583 qcow2_mark_clean(bs);
2589 static void qcow2_close(BlockDriverState *bs)
2591 BDRVQcow2State *s = bs->opaque;
2592 qemu_vfree(s->l1_table);
2593 /* else pre-write overlap checks in cache_destroy may crash */
2596 if (!(s->flags & BDRV_O_INACTIVE)) {
2597 qcow2_inactivate(bs);
2600 cache_clean_timer_del(bs);
2601 qcow2_cache_destroy(s->l2_table_cache);
2602 qcow2_cache_destroy(s->refcount_block_cache);
2604 qcrypto_block_free(s->crypto);
2607 g_free(s->unknown_header_fields);
2608 cleanup_unknown_header_ext(bs);
2610 g_free(s->image_data_file);
2611 g_free(s->image_backing_file);
2612 g_free(s->image_backing_format);
2614 if (has_data_file(bs)) {
2615 bdrv_unref_child(bs, s->data_file);
2618 qcow2_refcount_close(bs);
2619 qcow2_free_snapshots(bs);
2622 static void coroutine_fn qcow2_co_invalidate_cache(BlockDriverState *bs,
2625 BDRVQcow2State *s = bs->opaque;
2626 int flags = s->flags;
2627 QCryptoBlock *crypto = NULL;
2629 Error *local_err = NULL;
2633 * Backing files are read-only which makes all of their metadata immutable,
2634 * that means we don't have to worry about reopening them here.
2642 memset(s, 0, sizeof(BDRVQcow2State));
2643 options = qdict_clone_shallow(bs->options);
2645 flags &= ~BDRV_O_INACTIVE;
2646 qemu_co_mutex_lock(&s->lock);
2647 ret = qcow2_do_open(bs, options, flags, &local_err);
2648 qemu_co_mutex_unlock(&s->lock);
2649 qobject_unref(options);
2651 error_propagate_prepend(errp, local_err,
2652 "Could not reopen qcow2 layer: ");
2655 } else if (ret < 0) {
2656 error_setg_errno(errp, -ret, "Could not reopen qcow2 layer");
2664 static size_t header_ext_add(char *buf, uint32_t magic, const void *s,
2665 size_t len, size_t buflen)
2667 QCowExtension *ext_backing_fmt = (QCowExtension*) buf;
2668 size_t ext_len = sizeof(QCowExtension) + ((len + 7) & ~7);
2670 if (buflen < ext_len) {
2674 *ext_backing_fmt = (QCowExtension) {
2675 .magic = cpu_to_be32(magic),
2676 .len = cpu_to_be32(len),
2680 memcpy(buf + sizeof(QCowExtension), s, len);
2687 * Updates the qcow2 header, including the variable length parts of it, i.e.
2688 * the backing file name and all extensions. qcow2 was not designed to allow
2689 * such changes, so if we run out of space (we can only use the first cluster)
2690 * this function may fail.
2692 * Returns 0 on success, -errno in error cases.
2694 int qcow2_update_header(BlockDriverState *bs)
2696 BDRVQcow2State *s = bs->opaque;
2699 size_t buflen = s->cluster_size;
2701 uint64_t total_size;
2702 uint32_t refcount_table_clusters;
2703 size_t header_length;
2704 Qcow2UnknownHeaderExtension *uext;
2706 buf = qemu_blockalign(bs, buflen);
2708 /* Header structure */
2709 header = (QCowHeader*) buf;
2711 if (buflen < sizeof(*header)) {
2716 header_length = sizeof(*header) + s->unknown_header_fields_size;
2717 total_size = bs->total_sectors * BDRV_SECTOR_SIZE;
2718 refcount_table_clusters = s->refcount_table_size >> (s->cluster_bits - 3);
2720 *header = (QCowHeader) {
2721 /* Version 2 fields */
2722 .magic = cpu_to_be32(QCOW_MAGIC),
2723 .version = cpu_to_be32(s->qcow_version),
2724 .backing_file_offset = 0,
2725 .backing_file_size = 0,
2726 .cluster_bits = cpu_to_be32(s->cluster_bits),
2727 .size = cpu_to_be64(total_size),
2728 .crypt_method = cpu_to_be32(s->crypt_method_header),
2729 .l1_size = cpu_to_be32(s->l1_size),
2730 .l1_table_offset = cpu_to_be64(s->l1_table_offset),
2731 .refcount_table_offset = cpu_to_be64(s->refcount_table_offset),
2732 .refcount_table_clusters = cpu_to_be32(refcount_table_clusters),
2733 .nb_snapshots = cpu_to_be32(s->nb_snapshots),
2734 .snapshots_offset = cpu_to_be64(s->snapshots_offset),
2736 /* Version 3 fields */
2737 .incompatible_features = cpu_to_be64(s->incompatible_features),
2738 .compatible_features = cpu_to_be64(s->compatible_features),
2739 .autoclear_features = cpu_to_be64(s->autoclear_features),
2740 .refcount_order = cpu_to_be32(s->refcount_order),
2741 .header_length = cpu_to_be32(header_length),
2744 /* For older versions, write a shorter header */
2745 switch (s->qcow_version) {
2747 ret = offsetof(QCowHeader, incompatible_features);
2750 ret = sizeof(*header);
2759 memset(buf, 0, buflen);
2761 /* Preserve any unknown field in the header */
2762 if (s->unknown_header_fields_size) {
2763 if (buflen < s->unknown_header_fields_size) {
2768 memcpy(buf, s->unknown_header_fields, s->unknown_header_fields_size);
2769 buf += s->unknown_header_fields_size;
2770 buflen -= s->unknown_header_fields_size;
2773 /* Backing file format header extension */
2774 if (s->image_backing_format) {
2775 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BACKING_FORMAT,
2776 s->image_backing_format,
2777 strlen(s->image_backing_format),
2787 /* External data file header extension */
2788 if (has_data_file(bs) && s->image_data_file) {
2789 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_DATA_FILE,
2790 s->image_data_file, strlen(s->image_data_file),
2800 /* Full disk encryption header pointer extension */
2801 if (s->crypto_header.offset != 0) {
2802 s->crypto_header.offset = cpu_to_be64(s->crypto_header.offset);
2803 s->crypto_header.length = cpu_to_be64(s->crypto_header.length);
2804 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_CRYPTO_HEADER,
2805 &s->crypto_header, sizeof(s->crypto_header),
2807 s->crypto_header.offset = be64_to_cpu(s->crypto_header.offset);
2808 s->crypto_header.length = be64_to_cpu(s->crypto_header.length);
2817 if (s->qcow_version >= 3) {
2818 Qcow2Feature features[] = {
2820 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
2821 .bit = QCOW2_INCOMPAT_DIRTY_BITNR,
2822 .name = "dirty bit",
2825 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
2826 .bit = QCOW2_INCOMPAT_CORRUPT_BITNR,
2827 .name = "corrupt bit",
2830 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
2831 .bit = QCOW2_INCOMPAT_DATA_FILE_BITNR,
2832 .name = "external data file",
2835 .type = QCOW2_FEAT_TYPE_COMPATIBLE,
2836 .bit = QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR,
2837 .name = "lazy refcounts",
2841 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_FEATURE_TABLE,
2842 features, sizeof(features), buflen);
2850 /* Bitmap extension */
2851 if (s->nb_bitmaps > 0) {
2852 Qcow2BitmapHeaderExt bitmaps_header = {
2853 .nb_bitmaps = cpu_to_be32(s->nb_bitmaps),
2854 .bitmap_directory_size =
2855 cpu_to_be64(s->bitmap_directory_size),
2856 .bitmap_directory_offset =
2857 cpu_to_be64(s->bitmap_directory_offset)
2859 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BITMAPS,
2860 &bitmaps_header, sizeof(bitmaps_header),
2869 /* Keep unknown header extensions */
2870 QLIST_FOREACH(uext, &s->unknown_header_ext, next) {
2871 ret = header_ext_add(buf, uext->magic, uext->data, uext->len, buflen);
2880 /* End of header extensions */
2881 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_END, NULL, 0, buflen);
2889 /* Backing file name */
2890 if (s->image_backing_file) {
2891 size_t backing_file_len = strlen(s->image_backing_file);
2893 if (buflen < backing_file_len) {
2898 /* Using strncpy is ok here, since buf is not NUL-terminated. */
2899 strncpy(buf, s->image_backing_file, buflen);
2901 header->backing_file_offset = cpu_to_be64(buf - ((char*) header));
2902 header->backing_file_size = cpu_to_be32(backing_file_len);
2905 /* Write the new header */
2906 ret = bdrv_pwrite(bs->file, 0, header, s->cluster_size);
2917 static int qcow2_change_backing_file(BlockDriverState *bs,
2918 const char *backing_file, const char *backing_fmt)
2920 BDRVQcow2State *s = bs->opaque;
2922 /* Adding a backing file means that the external data file alone won't be
2923 * enough to make sense of the content */
2924 if (backing_file && data_file_is_raw(bs)) {
2928 if (backing_file && strlen(backing_file) > 1023) {
2932 pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
2933 backing_file ?: "");
2934 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
2935 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
2937 g_free(s->image_backing_file);
2938 g_free(s->image_backing_format);
2940 s->image_backing_file = backing_file ? g_strdup(bs->backing_file) : NULL;
2941 s->image_backing_format = backing_fmt ? g_strdup(bs->backing_format) : NULL;
2943 return qcow2_update_header(bs);
2946 static int qcow2_crypt_method_from_format(const char *encryptfmt)
2948 if (g_str_equal(encryptfmt, "luks")) {
2949 return QCOW_CRYPT_LUKS;
2950 } else if (g_str_equal(encryptfmt, "aes")) {
2951 return QCOW_CRYPT_AES;
2957 static int qcow2_set_up_encryption(BlockDriverState *bs,
2958 QCryptoBlockCreateOptions *cryptoopts,
2961 BDRVQcow2State *s = bs->opaque;
2962 QCryptoBlock *crypto = NULL;
2965 switch (cryptoopts->format) {
2966 case Q_CRYPTO_BLOCK_FORMAT_LUKS:
2967 fmt = QCOW_CRYPT_LUKS;
2969 case Q_CRYPTO_BLOCK_FORMAT_QCOW:
2970 fmt = QCOW_CRYPT_AES;
2973 error_setg(errp, "Crypto format not supported in qcow2");
2977 s->crypt_method_header = fmt;
2979 crypto = qcrypto_block_create(cryptoopts, "encrypt.",
2980 qcow2_crypto_hdr_init_func,
2981 qcow2_crypto_hdr_write_func,
2987 ret = qcow2_update_header(bs);
2989 error_setg_errno(errp, -ret, "Could not write encryption header");
2995 qcrypto_block_free(crypto);
3000 * Preallocates metadata structures for data clusters between @offset (in the
3001 * guest disk) and @new_length (which is thus generally the new guest disk
3004 * Returns: 0 on success, -errno on failure.
3006 static int coroutine_fn preallocate_co(BlockDriverState *bs, uint64_t offset,
3007 uint64_t new_length, PreallocMode mode,
3010 BDRVQcow2State *s = bs->opaque;
3012 uint64_t host_offset = 0;
3013 int64_t file_length;
3014 unsigned int cur_bytes;
3018 assert(offset <= new_length);
3019 bytes = new_length - offset;
3022 cur_bytes = MIN(bytes, QEMU_ALIGN_DOWN(INT_MAX, s->cluster_size));
3023 ret = qcow2_alloc_cluster_offset(bs, offset, &cur_bytes,
3024 &host_offset, &meta);
3026 error_setg_errno(errp, -ret, "Allocating clusters failed");
3031 QCowL2Meta *next = meta->next;
3033 ret = qcow2_alloc_cluster_link_l2(bs, meta);
3035 error_setg_errno(errp, -ret, "Mapping clusters failed");
3036 qcow2_free_any_clusters(bs, meta->alloc_offset,
3037 meta->nb_clusters, QCOW2_DISCARD_NEVER);
3041 /* There are no dependent requests, but we need to remove our
3042 * request from the list of in-flight requests */
3043 QLIST_REMOVE(meta, next_in_flight);
3049 /* TODO Preallocate data if requested */
3052 offset += cur_bytes;
3056 * It is expected that the image file is large enough to actually contain
3057 * all of the allocated clusters (otherwise we get failing reads after
3058 * EOF). Extend the image to the last allocated sector.
3060 file_length = bdrv_getlength(s->data_file->bs);
3061 if (file_length < 0) {
3062 error_setg_errno(errp, -file_length, "Could not get file size");
3066 if (host_offset + cur_bytes > file_length) {
3067 if (mode == PREALLOC_MODE_METADATA) {
3068 mode = PREALLOC_MODE_OFF;
3070 ret = bdrv_co_truncate(s->data_file, host_offset + cur_bytes, mode,
3080 /* qcow2_refcount_metadata_size:
3081 * @clusters: number of clusters to refcount (including data and L1/L2 tables)
3082 * @cluster_size: size of a cluster, in bytes
3083 * @refcount_order: refcount bits power-of-2 exponent
3084 * @generous_increase: allow for the refcount table to be 1.5x as large as it
3087 * Returns: Number of bytes required for refcount blocks and table metadata.
3089 int64_t qcow2_refcount_metadata_size(int64_t clusters, size_t cluster_size,
3090 int refcount_order, bool generous_increase,
3091 uint64_t *refblock_count)
3094 * Every host cluster is reference-counted, including metadata (even
3095 * refcount metadata is recursively included).
3097 * An accurate formula for the size of refcount metadata size is difficult
3098 * to derive. An easier method of calculation is finding the fixed point
3099 * where no further refcount blocks or table clusters are required to
3100 * reference count every cluster.
3102 int64_t blocks_per_table_cluster = cluster_size / sizeof(uint64_t);
3103 int64_t refcounts_per_block = cluster_size * 8 / (1 << refcount_order);
3104 int64_t table = 0; /* number of refcount table clusters */
3105 int64_t blocks = 0; /* number of refcount block clusters */
3111 blocks = DIV_ROUND_UP(clusters + table + blocks, refcounts_per_block);
3112 table = DIV_ROUND_UP(blocks, blocks_per_table_cluster);
3113 n = clusters + blocks + table;
3115 if (n == last && generous_increase) {
3116 clusters += DIV_ROUND_UP(table, 2);
3117 n = 0; /* force another loop */
3118 generous_increase = false;
3120 } while (n != last);
3122 if (refblock_count) {
3123 *refblock_count = blocks;
3126 return (blocks + table) * cluster_size;
3130 * qcow2_calc_prealloc_size:
3131 * @total_size: virtual disk size in bytes
3132 * @cluster_size: cluster size in bytes
3133 * @refcount_order: refcount bits power-of-2 exponent
3135 * Returns: Total number of bytes required for the fully allocated image
3136 * (including metadata).
3138 static int64_t qcow2_calc_prealloc_size(int64_t total_size,
3139 size_t cluster_size,
3142 int64_t meta_size = 0;
3143 uint64_t nl1e, nl2e;
3144 int64_t aligned_total_size = ROUND_UP(total_size, cluster_size);
3146 /* header: 1 cluster */
3147 meta_size += cluster_size;
3149 /* total size of L2 tables */
3150 nl2e = aligned_total_size / cluster_size;
3151 nl2e = ROUND_UP(nl2e, cluster_size / sizeof(uint64_t));
3152 meta_size += nl2e * sizeof(uint64_t);
3154 /* total size of L1 tables */
3155 nl1e = nl2e * sizeof(uint64_t) / cluster_size;
3156 nl1e = ROUND_UP(nl1e, cluster_size / sizeof(uint64_t));
3157 meta_size += nl1e * sizeof(uint64_t);
3159 /* total size of refcount table and blocks */
3160 meta_size += qcow2_refcount_metadata_size(
3161 (meta_size + aligned_total_size) / cluster_size,
3162 cluster_size, refcount_order, false, NULL);
3164 return meta_size + aligned_total_size;
3167 static bool validate_cluster_size(size_t cluster_size, Error **errp)
3169 int cluster_bits = ctz32(cluster_size);
3170 if (cluster_bits < MIN_CLUSTER_BITS || cluster_bits > MAX_CLUSTER_BITS ||
3171 (1 << cluster_bits) != cluster_size)
3173 error_setg(errp, "Cluster size must be a power of two between %d and "
3174 "%dk", 1 << MIN_CLUSTER_BITS, 1 << (MAX_CLUSTER_BITS - 10));
3180 static size_t qcow2_opt_get_cluster_size_del(QemuOpts *opts, Error **errp)
3182 size_t cluster_size;
3184 cluster_size = qemu_opt_get_size_del(opts, BLOCK_OPT_CLUSTER_SIZE,
3185 DEFAULT_CLUSTER_SIZE);
3186 if (!validate_cluster_size(cluster_size, errp)) {
3189 return cluster_size;
3192 static int qcow2_opt_get_version_del(QemuOpts *opts, Error **errp)
3197 buf = qemu_opt_get_del(opts, BLOCK_OPT_COMPAT_LEVEL);
3199 ret = 3; /* default */
3200 } else if (!strcmp(buf, "0.10")) {
3202 } else if (!strcmp(buf, "1.1")) {
3205 error_setg(errp, "Invalid compatibility level: '%s'", buf);
3212 static uint64_t qcow2_opt_get_refcount_bits_del(QemuOpts *opts, int version,
3215 uint64_t refcount_bits;
3217 refcount_bits = qemu_opt_get_number_del(opts, BLOCK_OPT_REFCOUNT_BITS, 16);
3218 if (refcount_bits > 64 || !is_power_of_2(refcount_bits)) {
3219 error_setg(errp, "Refcount width must be a power of two and may not "
3224 if (version < 3 && refcount_bits != 16) {
3225 error_setg(errp, "Different refcount widths than 16 bits require "
3226 "compatibility level 1.1 or above (use compat=1.1 or "
3231 return refcount_bits;
3234 static int coroutine_fn
3235 qcow2_co_create(BlockdevCreateOptions *create_options, Error **errp)
3237 BlockdevCreateOptionsQcow2 *qcow2_opts;
3241 * Open the image file and write a minimal qcow2 header.
3243 * We keep things simple and start with a zero-sized image. We also
3244 * do without refcount blocks or a L1 table for now. We'll fix the
3245 * inconsistency later.
3247 * We do need a refcount table because growing the refcount table means
3248 * allocating two new refcount blocks - the seconds of which would be at
3249 * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
3250 * size for any qcow2 image.
3252 BlockBackend *blk = NULL;
3253 BlockDriverState *bs = NULL;
3254 BlockDriverState *data_bs = NULL;
3256 size_t cluster_size;
3259 uint64_t* refcount_table;
3260 Error *local_err = NULL;
3263 assert(create_options->driver == BLOCKDEV_DRIVER_QCOW2);
3264 qcow2_opts = &create_options->u.qcow2;
3266 bs = bdrv_open_blockdev_ref(qcow2_opts->file, errp);
3271 /* Validate options and set default values */
3272 if (!QEMU_IS_ALIGNED(qcow2_opts->size, BDRV_SECTOR_SIZE)) {
3273 error_setg(errp, "Image size must be a multiple of 512 bytes");
3278 if (qcow2_opts->has_version) {
3279 switch (qcow2_opts->version) {
3280 case BLOCKDEV_QCOW2_VERSION_V2:
3283 case BLOCKDEV_QCOW2_VERSION_V3:
3287 g_assert_not_reached();
3293 if (qcow2_opts->has_cluster_size) {
3294 cluster_size = qcow2_opts->cluster_size;
3296 cluster_size = DEFAULT_CLUSTER_SIZE;
3299 if (!validate_cluster_size(cluster_size, errp)) {
3304 if (!qcow2_opts->has_preallocation) {
3305 qcow2_opts->preallocation = PREALLOC_MODE_OFF;
3307 if (qcow2_opts->has_backing_file &&
3308 qcow2_opts->preallocation != PREALLOC_MODE_OFF)
3310 error_setg(errp, "Backing file and preallocation cannot be used at "
3315 if (qcow2_opts->has_backing_fmt && !qcow2_opts->has_backing_file) {
3316 error_setg(errp, "Backing format cannot be used without backing file");
3321 if (!qcow2_opts->has_lazy_refcounts) {
3322 qcow2_opts->lazy_refcounts = false;
3324 if (version < 3 && qcow2_opts->lazy_refcounts) {
3325 error_setg(errp, "Lazy refcounts only supported with compatibility "
3326 "level 1.1 and above (use version=v3 or greater)");
3331 if (!qcow2_opts->has_refcount_bits) {
3332 qcow2_opts->refcount_bits = 16;
3334 if (qcow2_opts->refcount_bits > 64 ||
3335 !is_power_of_2(qcow2_opts->refcount_bits))
3337 error_setg(errp, "Refcount width must be a power of two and may not "
3342 if (version < 3 && qcow2_opts->refcount_bits != 16) {
3343 error_setg(errp, "Different refcount widths than 16 bits require "
3344 "compatibility level 1.1 or above (use version=v3 or "
3349 refcount_order = ctz32(qcow2_opts->refcount_bits);
3351 if (qcow2_opts->data_file_raw && !qcow2_opts->data_file) {
3352 error_setg(errp, "data-file-raw requires data-file");
3356 if (qcow2_opts->data_file_raw && qcow2_opts->has_backing_file) {
3357 error_setg(errp, "Backing file and data-file-raw cannot be used at "
3363 if (qcow2_opts->data_file) {
3365 error_setg(errp, "External data files are only supported with "
3366 "compatibility level 1.1 and above (use version=v3 or "
3371 data_bs = bdrv_open_blockdev_ref(qcow2_opts->data_file, errp);
3372 if (data_bs == NULL) {
3378 /* Create BlockBackend to write to the image */
3379 blk = blk_new(bdrv_get_aio_context(bs),
3380 BLK_PERM_WRITE | BLK_PERM_RESIZE, BLK_PERM_ALL);
3381 ret = blk_insert_bs(blk, bs, errp);
3385 blk_set_allow_write_beyond_eof(blk, true);
3387 /* Clear the protocol layer and preallocate it if necessary */
3388 ret = blk_truncate(blk, 0, PREALLOC_MODE_OFF, errp);
3393 /* Write the header */
3394 QEMU_BUILD_BUG_ON((1 << MIN_CLUSTER_BITS) < sizeof(*header));
3395 header = g_malloc0(cluster_size);
3396 *header = (QCowHeader) {
3397 .magic = cpu_to_be32(QCOW_MAGIC),
3398 .version = cpu_to_be32(version),
3399 .cluster_bits = cpu_to_be32(ctz32(cluster_size)),
3400 .size = cpu_to_be64(0),
3401 .l1_table_offset = cpu_to_be64(0),
3402 .l1_size = cpu_to_be32(0),
3403 .refcount_table_offset = cpu_to_be64(cluster_size),
3404 .refcount_table_clusters = cpu_to_be32(1),
3405 .refcount_order = cpu_to_be32(refcount_order),
3406 .header_length = cpu_to_be32(sizeof(*header)),
3409 /* We'll update this to correct value later */
3410 header->crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
3412 if (qcow2_opts->lazy_refcounts) {
3413 header->compatible_features |=
3414 cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS);
3417 header->incompatible_features |=
3418 cpu_to_be64(QCOW2_INCOMPAT_DATA_FILE);
3420 if (qcow2_opts->data_file_raw) {
3421 header->autoclear_features |=
3422 cpu_to_be64(QCOW2_AUTOCLEAR_DATA_FILE_RAW);
3425 ret = blk_pwrite(blk, 0, header, cluster_size, 0);
3428 error_setg_errno(errp, -ret, "Could not write qcow2 header");
3432 /* Write a refcount table with one refcount block */
3433 refcount_table = g_malloc0(2 * cluster_size);
3434 refcount_table[0] = cpu_to_be64(2 * cluster_size);
3435 ret = blk_pwrite(blk, cluster_size, refcount_table, 2 * cluster_size, 0);
3436 g_free(refcount_table);
3439 error_setg_errno(errp, -ret, "Could not write refcount table");
3447 * And now open the image and make it consistent first (i.e. increase the
3448 * refcount of the cluster that is occupied by the header and the refcount
3451 options = qdict_new();
3452 qdict_put_str(options, "driver", "qcow2");
3453 qdict_put_str(options, "file", bs->node_name);
3455 qdict_put_str(options, "data-file", data_bs->node_name);
3457 blk = blk_new_open(NULL, NULL, options,
3458 BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_NO_FLUSH,
3461 error_propagate(errp, local_err);
3466 ret = qcow2_alloc_clusters(blk_bs(blk), 3 * cluster_size);
3468 error_setg_errno(errp, -ret, "Could not allocate clusters for qcow2 "
3469 "header and refcount table");
3472 } else if (ret != 0) {
3473 error_report("Huh, first cluster in empty image is already in use?");
3477 /* Set the external data file if necessary */
3479 BDRVQcow2State *s = blk_bs(blk)->opaque;
3480 s->image_data_file = g_strdup(data_bs->filename);
3483 /* Create a full header (including things like feature table) */
3484 ret = qcow2_update_header(blk_bs(blk));
3486 error_setg_errno(errp, -ret, "Could not update qcow2 header");
3490 /* Okay, now that we have a valid image, let's give it the right size */
3491 ret = blk_truncate(blk, qcow2_opts->size, qcow2_opts->preallocation, errp);
3493 error_prepend(errp, "Could not resize image: ");
3497 /* Want a backing file? There you go.*/
3498 if (qcow2_opts->has_backing_file) {
3499 const char *backing_format = NULL;
3501 if (qcow2_opts->has_backing_fmt) {
3502 backing_format = BlockdevDriver_str(qcow2_opts->backing_fmt);
3505 ret = bdrv_change_backing_file(blk_bs(blk), qcow2_opts->backing_file,
3508 error_setg_errno(errp, -ret, "Could not assign backing file '%s' "
3509 "with format '%s'", qcow2_opts->backing_file,
3515 /* Want encryption? There you go. */
3516 if (qcow2_opts->has_encrypt) {
3517 ret = qcow2_set_up_encryption(blk_bs(blk), qcow2_opts->encrypt, errp);
3526 /* Reopen the image without BDRV_O_NO_FLUSH to flush it before returning.
3527 * Using BDRV_O_NO_IO, since encryption is now setup we don't want to
3528 * have to setup decryption context. We're not doing any I/O on the top
3529 * level BlockDriverState, only lower layers, where BDRV_O_NO_IO does
3532 options = qdict_new();
3533 qdict_put_str(options, "driver", "qcow2");
3534 qdict_put_str(options, "file", bs->node_name);
3536 qdict_put_str(options, "data-file", data_bs->node_name);
3538 blk = blk_new_open(NULL, NULL, options,
3539 BDRV_O_RDWR | BDRV_O_NO_BACKING | BDRV_O_NO_IO,
3542 error_propagate(errp, local_err);
3551 bdrv_unref(data_bs);
3555 static int coroutine_fn qcow2_co_create_opts(const char *filename, QemuOpts *opts,
3558 BlockdevCreateOptions *create_options = NULL;
3561 BlockDriverState *bs = NULL;
3562 BlockDriverState *data_bs = NULL;
3563 Error *local_err = NULL;
3567 /* Only the keyval visitor supports the dotted syntax needed for
3568 * encryption, so go through a QDict before getting a QAPI type. Ignore
3569 * options meant for the protocol layer so that the visitor doesn't
3571 qdict = qemu_opts_to_qdict_filtered(opts, NULL, bdrv_qcow2.create_opts,
3574 /* Handle encryption options */
3575 val = qdict_get_try_str(qdict, BLOCK_OPT_ENCRYPT);
3576 if (val && !strcmp(val, "on")) {
3577 qdict_put_str(qdict, BLOCK_OPT_ENCRYPT, "qcow");
3578 } else if (val && !strcmp(val, "off")) {
3579 qdict_del(qdict, BLOCK_OPT_ENCRYPT);
3582 val = qdict_get_try_str(qdict, BLOCK_OPT_ENCRYPT_FORMAT);
3583 if (val && !strcmp(val, "aes")) {
3584 qdict_put_str(qdict, BLOCK_OPT_ENCRYPT_FORMAT, "qcow");
3587 /* Convert compat=0.10/1.1 into compat=v2/v3, to be renamed into
3588 * version=v2/v3 below. */
3589 val = qdict_get_try_str(qdict, BLOCK_OPT_COMPAT_LEVEL);
3590 if (val && !strcmp(val, "0.10")) {
3591 qdict_put_str(qdict, BLOCK_OPT_COMPAT_LEVEL, "v2");
3592 } else if (val && !strcmp(val, "1.1")) {
3593 qdict_put_str(qdict, BLOCK_OPT_COMPAT_LEVEL, "v3");
3596 /* Change legacy command line options into QMP ones */
3597 static const QDictRenames opt_renames[] = {
3598 { BLOCK_OPT_BACKING_FILE, "backing-file" },
3599 { BLOCK_OPT_BACKING_FMT, "backing-fmt" },
3600 { BLOCK_OPT_CLUSTER_SIZE, "cluster-size" },
3601 { BLOCK_OPT_LAZY_REFCOUNTS, "lazy-refcounts" },
3602 { BLOCK_OPT_REFCOUNT_BITS, "refcount-bits" },
3603 { BLOCK_OPT_ENCRYPT, BLOCK_OPT_ENCRYPT_FORMAT },
3604 { BLOCK_OPT_COMPAT_LEVEL, "version" },
3605 { BLOCK_OPT_DATA_FILE_RAW, "data-file-raw" },
3609 if (!qdict_rename_keys(qdict, opt_renames, errp)) {
3614 /* Create and open the file (protocol layer) */
3615 ret = bdrv_create_file(filename, opts, errp);
3620 bs = bdrv_open(filename, NULL, NULL,
3621 BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_PROTOCOL, errp);
3627 /* Create and open an external data file (protocol layer) */
3628 val = qdict_get_try_str(qdict, BLOCK_OPT_DATA_FILE);
3630 ret = bdrv_create_file(val, opts, errp);
3635 data_bs = bdrv_open(val, NULL, NULL,
3636 BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_PROTOCOL,
3638 if (data_bs == NULL) {
3643 qdict_del(qdict, BLOCK_OPT_DATA_FILE);
3644 qdict_put_str(qdict, "data-file", data_bs->node_name);
3647 /* Set 'driver' and 'node' options */
3648 qdict_put_str(qdict, "driver", "qcow2");
3649 qdict_put_str(qdict, "file", bs->node_name);
3651 /* Now get the QAPI type BlockdevCreateOptions */
3652 v = qobject_input_visitor_new_flat_confused(qdict, errp);
3658 visit_type_BlockdevCreateOptions(v, NULL, &create_options, &local_err);
3662 error_propagate(errp, local_err);
3667 /* Silently round up size */
3668 create_options->u.qcow2.size = ROUND_UP(create_options->u.qcow2.size,
3671 /* Create the qcow2 image (format layer) */
3672 ret = qcow2_co_create(create_options, errp);
3679 qobject_unref(qdict);
3681 bdrv_unref(data_bs);
3682 qapi_free_BlockdevCreateOptions(create_options);
3687 static bool is_zero(BlockDriverState *bs, int64_t offset, int64_t bytes)
3692 /* Clamp to image length, before checking status of underlying sectors */
3693 if (offset + bytes > bs->total_sectors * BDRV_SECTOR_SIZE) {
3694 bytes = bs->total_sectors * BDRV_SECTOR_SIZE - offset;
3700 res = bdrv_block_status_above(bs, NULL, offset, bytes, &nr, NULL, NULL);
3701 return res >= 0 && (res & BDRV_BLOCK_ZERO) && nr == bytes;
3704 static coroutine_fn int qcow2_co_pwrite_zeroes(BlockDriverState *bs,
3705 int64_t offset, int bytes, BdrvRequestFlags flags)
3708 BDRVQcow2State *s = bs->opaque;
3710 uint32_t head = offset % s->cluster_size;
3711 uint32_t tail = (offset + bytes) % s->cluster_size;
3713 trace_qcow2_pwrite_zeroes_start_req(qemu_coroutine_self(), offset, bytes);
3714 if (offset + bytes == bs->total_sectors * BDRV_SECTOR_SIZE) {
3722 assert(head + bytes <= s->cluster_size);
3724 /* check whether remainder of cluster already reads as zero */
3725 if (!(is_zero(bs, offset - head, head) &&
3726 is_zero(bs, offset + bytes,
3727 tail ? s->cluster_size - tail : 0))) {
3731 qemu_co_mutex_lock(&s->lock);
3732 /* We can have new write after previous check */
3733 offset = QEMU_ALIGN_DOWN(offset, s->cluster_size);
3734 bytes = s->cluster_size;
3735 nr = s->cluster_size;
3736 ret = qcow2_get_cluster_offset(bs, offset, &nr, &off);
3737 if (ret != QCOW2_CLUSTER_UNALLOCATED &&
3738 ret != QCOW2_CLUSTER_ZERO_PLAIN &&
3739 ret != QCOW2_CLUSTER_ZERO_ALLOC) {
3740 qemu_co_mutex_unlock(&s->lock);
3744 qemu_co_mutex_lock(&s->lock);
3747 trace_qcow2_pwrite_zeroes(qemu_coroutine_self(), offset, bytes);
3749 /* Whatever is left can use real zero clusters */
3750 ret = qcow2_cluster_zeroize(bs, offset, bytes, flags);
3751 qemu_co_mutex_unlock(&s->lock);
3756 static coroutine_fn int qcow2_co_pdiscard(BlockDriverState *bs,
3757 int64_t offset, int bytes)
3760 BDRVQcow2State *s = bs->opaque;
3762 if (!QEMU_IS_ALIGNED(offset | bytes, s->cluster_size)) {
3763 assert(bytes < s->cluster_size);
3764 /* Ignore partial clusters, except for the special case of the
3765 * complete partial cluster at the end of an unaligned file */
3766 if (!QEMU_IS_ALIGNED(offset, s->cluster_size) ||
3767 offset + bytes != bs->total_sectors * BDRV_SECTOR_SIZE) {
3772 qemu_co_mutex_lock(&s->lock);
3773 ret = qcow2_cluster_discard(bs, offset, bytes, QCOW2_DISCARD_REQUEST,
3775 qemu_co_mutex_unlock(&s->lock);
3779 static int coroutine_fn
3780 qcow2_co_copy_range_from(BlockDriverState *bs,
3781 BdrvChild *src, uint64_t src_offset,
3782 BdrvChild *dst, uint64_t dst_offset,
3783 uint64_t bytes, BdrvRequestFlags read_flags,
3784 BdrvRequestFlags write_flags)
3786 BDRVQcow2State *s = bs->opaque;
3788 unsigned int cur_bytes; /* number of bytes in current iteration */
3789 BdrvChild *child = NULL;
3790 BdrvRequestFlags cur_write_flags;
3792 assert(!bs->encrypted);
3793 qemu_co_mutex_lock(&s->lock);
3795 while (bytes != 0) {
3796 uint64_t copy_offset = 0;
3797 /* prepare next request */
3798 cur_bytes = MIN(bytes, INT_MAX);
3799 cur_write_flags = write_flags;
3801 ret = qcow2_get_cluster_offset(bs, src_offset, &cur_bytes, ©_offset);
3807 case QCOW2_CLUSTER_UNALLOCATED:
3808 if (bs->backing && bs->backing->bs) {
3809 int64_t backing_length = bdrv_getlength(bs->backing->bs);
3810 if (src_offset >= backing_length) {
3811 cur_write_flags |= BDRV_REQ_ZERO_WRITE;
3813 child = bs->backing;
3814 cur_bytes = MIN(cur_bytes, backing_length - src_offset);
3815 copy_offset = src_offset;
3818 cur_write_flags |= BDRV_REQ_ZERO_WRITE;
3822 case QCOW2_CLUSTER_ZERO_PLAIN:
3823 case QCOW2_CLUSTER_ZERO_ALLOC:
3824 cur_write_flags |= BDRV_REQ_ZERO_WRITE;
3827 case QCOW2_CLUSTER_COMPRESSED:
3831 case QCOW2_CLUSTER_NORMAL:
3832 child = s->data_file;
3833 copy_offset += offset_into_cluster(s, src_offset);
3834 if ((copy_offset & 511) != 0) {
3843 qemu_co_mutex_unlock(&s->lock);
3844 ret = bdrv_co_copy_range_from(child,
3847 cur_bytes, read_flags, cur_write_flags);
3848 qemu_co_mutex_lock(&s->lock);
3854 src_offset += cur_bytes;
3855 dst_offset += cur_bytes;
3860 qemu_co_mutex_unlock(&s->lock);
3864 static int coroutine_fn
3865 qcow2_co_copy_range_to(BlockDriverState *bs,
3866 BdrvChild *src, uint64_t src_offset,
3867 BdrvChild *dst, uint64_t dst_offset,
3868 uint64_t bytes, BdrvRequestFlags read_flags,
3869 BdrvRequestFlags write_flags)
3871 BDRVQcow2State *s = bs->opaque;
3872 int offset_in_cluster;
3874 unsigned int cur_bytes; /* number of sectors in current iteration */
3875 uint64_t cluster_offset;
3876 QCowL2Meta *l2meta = NULL;
3878 assert(!bs->encrypted);
3880 qemu_co_mutex_lock(&s->lock);
3882 while (bytes != 0) {
3886 offset_in_cluster = offset_into_cluster(s, dst_offset);
3887 cur_bytes = MIN(bytes, INT_MAX);
3890 * If src->bs == dst->bs, we could simply copy by incrementing
3891 * the refcnt, without copying user data.
3892 * Or if src->bs == dst->bs->backing->bs, we could copy by discarding. */
3893 ret = qcow2_alloc_cluster_offset(bs, dst_offset, &cur_bytes,
3894 &cluster_offset, &l2meta);
3899 assert((cluster_offset & 511) == 0);
3901 ret = qcow2_pre_write_overlap_check(bs, 0,
3902 cluster_offset + offset_in_cluster, cur_bytes, true);
3907 qemu_co_mutex_unlock(&s->lock);
3908 ret = bdrv_co_copy_range_to(src, src_offset,
3910 cluster_offset + offset_in_cluster,
3911 cur_bytes, read_flags, write_flags);
3912 qemu_co_mutex_lock(&s->lock);
3917 ret = qcow2_handle_l2meta(bs, &l2meta, true);
3923 src_offset += cur_bytes;
3924 dst_offset += cur_bytes;
3929 qcow2_handle_l2meta(bs, &l2meta, false);
3931 qemu_co_mutex_unlock(&s->lock);
3933 trace_qcow2_writev_done_req(qemu_coroutine_self(), ret);
3938 static int coroutine_fn qcow2_co_truncate(BlockDriverState *bs, int64_t offset,
3939 PreallocMode prealloc, Error **errp)
3941 BDRVQcow2State *s = bs->opaque;
3942 uint64_t old_length;
3943 int64_t new_l1_size;
3947 if (prealloc != PREALLOC_MODE_OFF && prealloc != PREALLOC_MODE_METADATA &&
3948 prealloc != PREALLOC_MODE_FALLOC && prealloc != PREALLOC_MODE_FULL)
3950 error_setg(errp, "Unsupported preallocation mode '%s'",
3951 PreallocMode_str(prealloc));
3956 error_setg(errp, "The new size must be a multiple of 512");
3960 qemu_co_mutex_lock(&s->lock);
3962 /* cannot proceed if image has snapshots */
3963 if (s->nb_snapshots) {
3964 error_setg(errp, "Can't resize an image which has snapshots");
3969 /* cannot proceed if image has bitmaps */
3970 if (qcow2_truncate_bitmaps_check(bs, errp)) {
3975 old_length = bs->total_sectors * BDRV_SECTOR_SIZE;
3976 new_l1_size = size_to_l1(s, offset);
3978 if (offset < old_length) {
3979 int64_t last_cluster, old_file_size;
3980 if (prealloc != PREALLOC_MODE_OFF) {
3982 "Preallocation can't be used for shrinking an image");
3987 ret = qcow2_cluster_discard(bs, ROUND_UP(offset, s->cluster_size),
3988 old_length - ROUND_UP(offset,
3990 QCOW2_DISCARD_ALWAYS, true);
3992 error_setg_errno(errp, -ret, "Failed to discard cropped clusters");
3996 ret = qcow2_shrink_l1_table(bs, new_l1_size);
3998 error_setg_errno(errp, -ret,
3999 "Failed to reduce the number of L2 tables");
4003 ret = qcow2_shrink_reftable(bs);
4005 error_setg_errno(errp, -ret,
4006 "Failed to discard unused refblocks");
4010 old_file_size = bdrv_getlength(bs->file->bs);
4011 if (old_file_size < 0) {
4012 error_setg_errno(errp, -old_file_size,
4013 "Failed to inquire current file length");
4014 ret = old_file_size;
4017 last_cluster = qcow2_get_last_cluster(bs, old_file_size);
4018 if (last_cluster < 0) {
4019 error_setg_errno(errp, -last_cluster,
4020 "Failed to find the last cluster");
4024 if ((last_cluster + 1) * s->cluster_size < old_file_size) {
4025 Error *local_err = NULL;
4027 bdrv_co_truncate(bs->file, (last_cluster + 1) * s->cluster_size,
4028 PREALLOC_MODE_OFF, &local_err);
4030 warn_reportf_err(local_err,
4031 "Failed to truncate the tail of the image: ");
4035 ret = qcow2_grow_l1_table(bs, new_l1_size, true);
4037 error_setg_errno(errp, -ret, "Failed to grow the L1 table");
4043 case PREALLOC_MODE_OFF:
4044 if (has_data_file(bs)) {
4045 ret = bdrv_co_truncate(s->data_file, offset, prealloc, errp);
4052 case PREALLOC_MODE_METADATA:
4053 ret = preallocate_co(bs, old_length, offset, prealloc, errp);
4059 case PREALLOC_MODE_FALLOC:
4060 case PREALLOC_MODE_FULL:
4062 int64_t allocation_start, host_offset, guest_offset;
4063 int64_t clusters_allocated;
4064 int64_t old_file_size, new_file_size;
4065 uint64_t nb_new_data_clusters, nb_new_l2_tables;
4067 /* With a data file, preallocation means just allocating the metadata
4068 * and forwarding the truncate request to the data file */
4069 if (has_data_file(bs)) {
4070 ret = preallocate_co(bs, old_length, offset, prealloc, errp);
4077 old_file_size = bdrv_getlength(bs->file->bs);
4078 if (old_file_size < 0) {
4079 error_setg_errno(errp, -old_file_size,
4080 "Failed to inquire current file length");
4081 ret = old_file_size;
4084 old_file_size = ROUND_UP(old_file_size, s->cluster_size);
4086 nb_new_data_clusters = DIV_ROUND_UP(offset - old_length,
4089 /* This is an overestimation; we will not actually allocate space for
4090 * these in the file but just make sure the new refcount structures are
4091 * able to cover them so we will not have to allocate new refblocks
4092 * while entering the data blocks in the potentially new L2 tables.
4093 * (We do not actually care where the L2 tables are placed. Maybe they
4094 * are already allocated or they can be placed somewhere before
4095 * @old_file_size. It does not matter because they will be fully
4096 * allocated automatically, so they do not need to be covered by the
4097 * preallocation. All that matters is that we will not have to allocate
4098 * new refcount structures for them.) */
4099 nb_new_l2_tables = DIV_ROUND_UP(nb_new_data_clusters,
4100 s->cluster_size / sizeof(uint64_t));
4101 /* The cluster range may not be aligned to L2 boundaries, so add one L2
4102 * table for a potential head/tail */
4105 allocation_start = qcow2_refcount_area(bs, old_file_size,
4106 nb_new_data_clusters +
4109 if (allocation_start < 0) {
4110 error_setg_errno(errp, -allocation_start,
4111 "Failed to resize refcount structures");
4112 ret = allocation_start;
4116 clusters_allocated = qcow2_alloc_clusters_at(bs, allocation_start,
4117 nb_new_data_clusters);
4118 if (clusters_allocated < 0) {
4119 error_setg_errno(errp, -clusters_allocated,
4120 "Failed to allocate data clusters");
4121 ret = clusters_allocated;
4125 assert(clusters_allocated == nb_new_data_clusters);
4127 /* Allocate the data area */
4128 new_file_size = allocation_start +
4129 nb_new_data_clusters * s->cluster_size;
4130 ret = bdrv_co_truncate(bs->file, new_file_size, prealloc, errp);
4132 error_prepend(errp, "Failed to resize underlying file: ");
4133 qcow2_free_clusters(bs, allocation_start,
4134 nb_new_data_clusters * s->cluster_size,
4135 QCOW2_DISCARD_OTHER);
4139 /* Create the necessary L2 entries */
4140 host_offset = allocation_start;
4141 guest_offset = old_length;
4142 while (nb_new_data_clusters) {
4143 int64_t nb_clusters = MIN(
4144 nb_new_data_clusters,
4145 s->l2_slice_size - offset_to_l2_slice_index(s, guest_offset));
4146 QCowL2Meta allocation = {
4147 .offset = guest_offset,
4148 .alloc_offset = host_offset,
4149 .nb_clusters = nb_clusters,
4151 qemu_co_queue_init(&allocation.dependent_requests);
4153 ret = qcow2_alloc_cluster_link_l2(bs, &allocation);
4155 error_setg_errno(errp, -ret, "Failed to update L2 tables");
4156 qcow2_free_clusters(bs, host_offset,
4157 nb_new_data_clusters * s->cluster_size,
4158 QCOW2_DISCARD_OTHER);
4162 guest_offset += nb_clusters * s->cluster_size;
4163 host_offset += nb_clusters * s->cluster_size;
4164 nb_new_data_clusters -= nb_clusters;
4170 g_assert_not_reached();
4173 if (prealloc != PREALLOC_MODE_OFF) {
4174 /* Flush metadata before actually changing the image size */
4175 ret = qcow2_write_caches(bs);
4177 error_setg_errno(errp, -ret,
4178 "Failed to flush the preallocated area to disk");
4183 bs->total_sectors = offset / BDRV_SECTOR_SIZE;
4185 /* write updated header.size */
4186 offset = cpu_to_be64(offset);
4187 ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, size),
4188 &offset, sizeof(uint64_t));
4190 error_setg_errno(errp, -ret, "Failed to update the image size");
4194 s->l1_vm_state_index = new_l1_size;
4196 /* Update cache sizes */
4197 options = qdict_clone_shallow(bs->options);
4198 ret = qcow2_update_options(bs, options, s->flags, errp);
4199 qobject_unref(options);
4205 qemu_co_mutex_unlock(&s->lock);
4209 /* XXX: put compressed sectors first, then all the cluster aligned
4210 tables to avoid losing bytes in alignment */
4211 static coroutine_fn int
4212 qcow2_co_pwritev_compressed_part(BlockDriverState *bs,
4213 uint64_t offset, uint64_t bytes,
4214 QEMUIOVector *qiov, size_t qiov_offset)
4216 BDRVQcow2State *s = bs->opaque;
4219 uint8_t *buf, *out_buf;
4220 uint64_t cluster_offset;
4222 if (has_data_file(bs)) {
4227 /* align end of file to a sector boundary to ease reading with
4228 sector based I/Os */
4229 int64_t len = bdrv_getlength(bs->file->bs);
4233 return bdrv_co_truncate(bs->file, len, PREALLOC_MODE_OFF, NULL);
4236 if (offset_into_cluster(s, offset)) {
4240 buf = qemu_blockalign(bs, s->cluster_size);
4241 if (bytes != s->cluster_size) {
4242 if (bytes > s->cluster_size ||
4243 offset + bytes != bs->total_sectors << BDRV_SECTOR_BITS)
4248 /* Zero-pad last write if image size is not cluster aligned */
4249 memset(buf + bytes, 0, s->cluster_size - bytes);
4251 qemu_iovec_to_buf(qiov, qiov_offset, buf, bytes);
4253 out_buf = g_malloc(s->cluster_size);
4255 out_len = qcow2_co_compress(bs, out_buf, s->cluster_size - 1,
4256 buf, s->cluster_size);
4257 if (out_len == -ENOMEM) {
4258 /* could not compress: write normal cluster */
4259 ret = qcow2_co_pwritev_part(bs, offset, bytes, qiov, qiov_offset, 0);
4264 } else if (out_len < 0) {
4269 qemu_co_mutex_lock(&s->lock);
4270 ret = qcow2_alloc_compressed_cluster_offset(bs, offset, out_len,
4273 qemu_co_mutex_unlock(&s->lock);
4277 ret = qcow2_pre_write_overlap_check(bs, 0, cluster_offset, out_len, true);
4278 qemu_co_mutex_unlock(&s->lock);
4283 BLKDBG_EVENT(s->data_file, BLKDBG_WRITE_COMPRESSED);
4284 ret = bdrv_co_pwrite(s->data_file, cluster_offset, out_len, out_buf, 0);
4296 static int coroutine_fn
4297 qcow2_co_preadv_compressed(BlockDriverState *bs,
4298 uint64_t file_cluster_offset,
4304 BDRVQcow2State *s = bs->opaque;
4305 int ret = 0, csize, nb_csectors;
4307 uint8_t *buf, *out_buf;
4308 int offset_in_cluster = offset_into_cluster(s, offset);
4310 coffset = file_cluster_offset & s->cluster_offset_mask;
4311 nb_csectors = ((file_cluster_offset >> s->csize_shift) & s->csize_mask) + 1;
4312 csize = nb_csectors * QCOW2_COMPRESSED_SECTOR_SIZE -
4313 (coffset & ~QCOW2_COMPRESSED_SECTOR_MASK);
4315 buf = g_try_malloc(csize);
4320 out_buf = qemu_blockalign(bs, s->cluster_size);
4322 BLKDBG_EVENT(bs->file, BLKDBG_READ_COMPRESSED);
4323 ret = bdrv_co_pread(bs->file, coffset, csize, buf, 0);
4328 if (qcow2_co_decompress(bs, out_buf, s->cluster_size, buf, csize) < 0) {
4333 qemu_iovec_from_buf(qiov, qiov_offset, out_buf + offset_in_cluster, bytes);
4336 qemu_vfree(out_buf);
4342 static int make_completely_empty(BlockDriverState *bs)
4344 BDRVQcow2State *s = bs->opaque;
4345 Error *local_err = NULL;
4346 int ret, l1_clusters;
4348 uint64_t *new_reftable = NULL;
4349 uint64_t rt_entry, l1_size2;
4352 uint64_t reftable_offset;
4353 uint32_t reftable_clusters;
4354 } QEMU_PACKED l1_ofs_rt_ofs_cls;
4356 ret = qcow2_cache_empty(bs, s->l2_table_cache);
4361 ret = qcow2_cache_empty(bs, s->refcount_block_cache);
4366 /* Refcounts will be broken utterly */
4367 ret = qcow2_mark_dirty(bs);
4372 BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
4374 l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / sizeof(uint64_t));
4375 l1_size2 = (uint64_t)s->l1_size * sizeof(uint64_t);
4377 /* After this call, neither the in-memory nor the on-disk refcount
4378 * information accurately describe the actual references */
4380 ret = bdrv_pwrite_zeroes(bs->file, s->l1_table_offset,
4381 l1_clusters * s->cluster_size, 0);
4383 goto fail_broken_refcounts;
4385 memset(s->l1_table, 0, l1_size2);
4387 BLKDBG_EVENT(bs->file, BLKDBG_EMPTY_IMAGE_PREPARE);
4389 /* Overwrite enough clusters at the beginning of the sectors to place
4390 * the refcount table, a refcount block and the L1 table in; this may
4391 * overwrite parts of the existing refcount and L1 table, which is not
4392 * an issue because the dirty flag is set, complete data loss is in fact
4393 * desired and partial data loss is consequently fine as well */
4394 ret = bdrv_pwrite_zeroes(bs->file, s->cluster_size,
4395 (2 + l1_clusters) * s->cluster_size, 0);
4396 /* This call (even if it failed overall) may have overwritten on-disk
4397 * refcount structures; in that case, the in-memory refcount information
4398 * will probably differ from the on-disk information which makes the BDS
4401 goto fail_broken_refcounts;
4404 BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
4405 BLKDBG_EVENT(bs->file, BLKDBG_REFTABLE_UPDATE);
4407 /* "Create" an empty reftable (one cluster) directly after the image
4408 * header and an empty L1 table three clusters after the image header;
4409 * the cluster between those two will be used as the first refblock */
4410 l1_ofs_rt_ofs_cls.l1_offset = cpu_to_be64(3 * s->cluster_size);
4411 l1_ofs_rt_ofs_cls.reftable_offset = cpu_to_be64(s->cluster_size);
4412 l1_ofs_rt_ofs_cls.reftable_clusters = cpu_to_be32(1);
4413 ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, l1_table_offset),
4414 &l1_ofs_rt_ofs_cls, sizeof(l1_ofs_rt_ofs_cls));
4416 goto fail_broken_refcounts;
4419 s->l1_table_offset = 3 * s->cluster_size;
4421 new_reftable = g_try_new0(uint64_t, s->cluster_size / sizeof(uint64_t));
4422 if (!new_reftable) {
4424 goto fail_broken_refcounts;
4427 s->refcount_table_offset = s->cluster_size;
4428 s->refcount_table_size = s->cluster_size / sizeof(uint64_t);
4429 s->max_refcount_table_index = 0;
4431 g_free(s->refcount_table);
4432 s->refcount_table = new_reftable;
4433 new_reftable = NULL;
4435 /* Now the in-memory refcount information again corresponds to the on-disk
4436 * information (reftable is empty and no refblocks (the refblock cache is
4437 * empty)); however, this means some clusters (e.g. the image header) are
4438 * referenced, but not refcounted, but the normal qcow2 code assumes that
4439 * the in-memory information is always correct */
4441 BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_ALLOC);
4443 /* Enter the first refblock into the reftable */
4444 rt_entry = cpu_to_be64(2 * s->cluster_size);
4445 ret = bdrv_pwrite_sync(bs->file, s->cluster_size,
4446 &rt_entry, sizeof(rt_entry));
4448 goto fail_broken_refcounts;
4450 s->refcount_table[0] = 2 * s->cluster_size;
4452 s->free_cluster_index = 0;
4453 assert(3 + l1_clusters <= s->refcount_block_size);
4454 offset = qcow2_alloc_clusters(bs, 3 * s->cluster_size + l1_size2);
4457 goto fail_broken_refcounts;
4458 } else if (offset > 0) {
4459 error_report("First cluster in emptied image is in use");
4463 /* Now finally the in-memory information corresponds to the on-disk
4464 * structures and is correct */
4465 ret = qcow2_mark_clean(bs);
4470 ret = bdrv_truncate(bs->file, (3 + l1_clusters) * s->cluster_size,
4471 PREALLOC_MODE_OFF, &local_err);
4473 error_report_err(local_err);
4479 fail_broken_refcounts:
4480 /* The BDS is unusable at this point. If we wanted to make it usable, we
4481 * would have to call qcow2_refcount_close(), qcow2_refcount_init(),
4482 * qcow2_check_refcounts(), qcow2_refcount_close() and qcow2_refcount_init()
4483 * again. However, because the functions which could have caused this error
4484 * path to be taken are used by those functions as well, it's very likely
4485 * that that sequence will fail as well. Therefore, just eject the BDS. */
4489 g_free(new_reftable);
4493 static int qcow2_make_empty(BlockDriverState *bs)
4495 BDRVQcow2State *s = bs->opaque;
4496 uint64_t offset, end_offset;
4497 int step = QEMU_ALIGN_DOWN(INT_MAX, s->cluster_size);
4498 int l1_clusters, ret = 0;
4500 l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / sizeof(uint64_t));
4502 if (s->qcow_version >= 3 && !s->snapshots && !s->nb_bitmaps &&
4503 3 + l1_clusters <= s->refcount_block_size &&
4504 s->crypt_method_header != QCOW_CRYPT_LUKS &&
4505 !has_data_file(bs)) {
4506 /* The following function only works for qcow2 v3 images (it
4507 * requires the dirty flag) and only as long as there are no
4508 * features that reserve extra clusters (such as snapshots,
4509 * LUKS header, or persistent bitmaps), because it completely
4510 * empties the image. Furthermore, the L1 table and three
4511 * additional clusters (image header, refcount table, one
4512 * refcount block) have to fit inside one refcount block. It
4513 * only resets the image file, i.e. does not work with an
4514 * external data file. */
4515 return make_completely_empty(bs);
4518 /* This fallback code simply discards every active cluster; this is slow,
4519 * but works in all cases */
4520 end_offset = bs->total_sectors * BDRV_SECTOR_SIZE;
4521 for (offset = 0; offset < end_offset; offset += step) {
4522 /* As this function is generally used after committing an external
4523 * snapshot, QCOW2_DISCARD_SNAPSHOT seems appropriate. Also, the
4524 * default action for this kind of discard is to pass the discard,
4525 * which will ideally result in an actually smaller image file, as
4526 * is probably desired. */
4527 ret = qcow2_cluster_discard(bs, offset, MIN(step, end_offset - offset),
4528 QCOW2_DISCARD_SNAPSHOT, true);
4537 static coroutine_fn int qcow2_co_flush_to_os(BlockDriverState *bs)
4539 BDRVQcow2State *s = bs->opaque;
4542 qemu_co_mutex_lock(&s->lock);
4543 ret = qcow2_write_caches(bs);
4544 qemu_co_mutex_unlock(&s->lock);
4549 static ssize_t qcow2_measure_crypto_hdr_init_func(QCryptoBlock *block,
4550 size_t headerlen, void *opaque, Error **errp)
4552 size_t *headerlenp = opaque;
4554 /* Stash away the payload size */
4555 *headerlenp = headerlen;
4559 static ssize_t qcow2_measure_crypto_hdr_write_func(QCryptoBlock *block,
4560 size_t offset, const uint8_t *buf, size_t buflen,
4561 void *opaque, Error **errp)
4563 /* Discard the bytes, we're not actually writing to an image */
4567 /* Determine the number of bytes for the LUKS payload */
4568 static bool qcow2_measure_luks_headerlen(QemuOpts *opts, size_t *len,
4572 QDict *cryptoopts_qdict;
4573 QCryptoBlockCreateOptions *cryptoopts;
4574 QCryptoBlock *crypto;
4576 /* Extract "encrypt." options into a qdict */
4577 opts_qdict = qemu_opts_to_qdict(opts, NULL);
4578 qdict_extract_subqdict(opts_qdict, &cryptoopts_qdict, "encrypt.");
4579 qobject_unref(opts_qdict);
4581 /* Build QCryptoBlockCreateOptions object from qdict */
4582 qdict_put_str(cryptoopts_qdict, "format", "luks");
4583 cryptoopts = block_crypto_create_opts_init(cryptoopts_qdict, errp);
4584 qobject_unref(cryptoopts_qdict);
4589 /* Fake LUKS creation in order to determine the payload size */
4590 crypto = qcrypto_block_create(cryptoopts, "encrypt.",
4591 qcow2_measure_crypto_hdr_init_func,
4592 qcow2_measure_crypto_hdr_write_func,
4594 qapi_free_QCryptoBlockCreateOptions(cryptoopts);
4599 qcrypto_block_free(crypto);
4603 static BlockMeasureInfo *qcow2_measure(QemuOpts *opts, BlockDriverState *in_bs,
4606 Error *local_err = NULL;
4607 BlockMeasureInfo *info;
4608 uint64_t required = 0; /* bytes that contribute to required size */
4609 uint64_t virtual_size; /* disk size as seen by guest */
4610 uint64_t refcount_bits;
4612 uint64_t luks_payload_size = 0;
4613 size_t cluster_size;
4616 PreallocMode prealloc;
4617 bool has_backing_file;
4620 /* Parse image creation options */
4621 cluster_size = qcow2_opt_get_cluster_size_del(opts, &local_err);
4626 version = qcow2_opt_get_version_del(opts, &local_err);
4631 refcount_bits = qcow2_opt_get_refcount_bits_del(opts, version, &local_err);
4636 optstr = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
4637 prealloc = qapi_enum_parse(&PreallocMode_lookup, optstr,
4638 PREALLOC_MODE_OFF, &local_err);
4644 optstr = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
4645 has_backing_file = !!optstr;
4648 optstr = qemu_opt_get_del(opts, BLOCK_OPT_ENCRYPT_FORMAT);
4649 has_luks = optstr && strcmp(optstr, "luks") == 0;
4655 if (!qcow2_measure_luks_headerlen(opts, &headerlen, &local_err)) {
4659 luks_payload_size = ROUND_UP(headerlen, cluster_size);
4662 virtual_size = qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0);
4663 virtual_size = ROUND_UP(virtual_size, cluster_size);
4665 /* Check that virtual disk size is valid */
4666 l2_tables = DIV_ROUND_UP(virtual_size / cluster_size,
4667 cluster_size / sizeof(uint64_t));
4668 if (l2_tables * sizeof(uint64_t) > QCOW_MAX_L1_SIZE) {
4669 error_setg(&local_err, "The image size is too large "
4670 "(try using a larger cluster size)");
4674 /* Account for input image */
4676 int64_t ssize = bdrv_getlength(in_bs);
4678 error_setg_errno(&local_err, -ssize,
4679 "Unable to get image virtual_size");
4683 virtual_size = ROUND_UP(ssize, cluster_size);
4685 if (has_backing_file) {
4686 /* We don't how much of the backing chain is shared by the input
4687 * image and the new image file. In the worst case the new image's
4688 * backing file has nothing in common with the input image. Be
4689 * conservative and assume all clusters need to be written.
4691 required = virtual_size;
4696 for (offset = 0; offset < ssize; offset += pnum) {
4699 ret = bdrv_block_status_above(in_bs, NULL, offset,
4700 ssize - offset, &pnum, NULL,
4703 error_setg_errno(&local_err, -ret,
4704 "Unable to get block status");
4708 if (ret & BDRV_BLOCK_ZERO) {
4709 /* Skip zero regions (safe with no backing file) */
4710 } else if ((ret & (BDRV_BLOCK_DATA | BDRV_BLOCK_ALLOCATED)) ==
4711 (BDRV_BLOCK_DATA | BDRV_BLOCK_ALLOCATED)) {
4712 /* Extend pnum to end of cluster for next iteration */
4713 pnum = ROUND_UP(offset + pnum, cluster_size) - offset;
4715 /* Count clusters we've seen */
4716 required += offset % cluster_size + pnum;
4722 /* Take into account preallocation. Nothing special is needed for
4723 * PREALLOC_MODE_METADATA since metadata is always counted.
4725 if (prealloc == PREALLOC_MODE_FULL || prealloc == PREALLOC_MODE_FALLOC) {
4726 required = virtual_size;
4729 info = g_new(BlockMeasureInfo, 1);
4730 info->fully_allocated =
4731 qcow2_calc_prealloc_size(virtual_size, cluster_size,
4732 ctz32(refcount_bits)) + luks_payload_size;
4734 /* Remove data clusters that are not required. This overestimates the
4735 * required size because metadata needed for the fully allocated file is
4738 info->required = info->fully_allocated - virtual_size + required;
4742 error_propagate(errp, local_err);
4746 static int qcow2_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
4748 BDRVQcow2State *s = bs->opaque;
4749 bdi->unallocated_blocks_are_zero = true;
4750 bdi->cluster_size = s->cluster_size;
4751 bdi->vm_state_offset = qcow2_vm_state_offset(s);
4755 static ImageInfoSpecific *qcow2_get_specific_info(BlockDriverState *bs,
4758 BDRVQcow2State *s = bs->opaque;
4759 ImageInfoSpecific *spec_info;
4760 QCryptoBlockInfo *encrypt_info = NULL;
4761 Error *local_err = NULL;
4763 if (s->crypto != NULL) {
4764 encrypt_info = qcrypto_block_get_info(s->crypto, &local_err);
4766 error_propagate(errp, local_err);
4771 spec_info = g_new(ImageInfoSpecific, 1);
4772 *spec_info = (ImageInfoSpecific){
4773 .type = IMAGE_INFO_SPECIFIC_KIND_QCOW2,
4774 .u.qcow2.data = g_new0(ImageInfoSpecificQCow2, 1),
4776 if (s->qcow_version == 2) {
4777 *spec_info->u.qcow2.data = (ImageInfoSpecificQCow2){
4778 .compat = g_strdup("0.10"),
4779 .refcount_bits = s->refcount_bits,
4781 } else if (s->qcow_version == 3) {
4782 Qcow2BitmapInfoList *bitmaps;
4783 bitmaps = qcow2_get_bitmap_info_list(bs, &local_err);
4785 error_propagate(errp, local_err);
4786 qapi_free_ImageInfoSpecific(spec_info);
4789 *spec_info->u.qcow2.data = (ImageInfoSpecificQCow2){
4790 .compat = g_strdup("1.1"),
4791 .lazy_refcounts = s->compatible_features &
4792 QCOW2_COMPAT_LAZY_REFCOUNTS,
4793 .has_lazy_refcounts = true,
4794 .corrupt = s->incompatible_features &
4795 QCOW2_INCOMPAT_CORRUPT,
4796 .has_corrupt = true,
4797 .refcount_bits = s->refcount_bits,
4798 .has_bitmaps = !!bitmaps,
4800 .has_data_file = !!s->image_data_file,
4801 .data_file = g_strdup(s->image_data_file),
4802 .has_data_file_raw = has_data_file(bs),
4803 .data_file_raw = data_file_is_raw(bs),
4806 /* if this assertion fails, this probably means a new version was
4807 * added without having it covered here */
4812 ImageInfoSpecificQCow2Encryption *qencrypt =
4813 g_new(ImageInfoSpecificQCow2Encryption, 1);
4814 switch (encrypt_info->format) {
4815 case Q_CRYPTO_BLOCK_FORMAT_QCOW:
4816 qencrypt->format = BLOCKDEV_QCOW2_ENCRYPTION_FORMAT_AES;
4818 case Q_CRYPTO_BLOCK_FORMAT_LUKS:
4819 qencrypt->format = BLOCKDEV_QCOW2_ENCRYPTION_FORMAT_LUKS;
4820 qencrypt->u.luks = encrypt_info->u.luks;
4825 /* Since we did shallow copy above, erase any pointers
4826 * in the original info */
4827 memset(&encrypt_info->u, 0, sizeof(encrypt_info->u));
4828 qapi_free_QCryptoBlockInfo(encrypt_info);
4830 spec_info->u.qcow2.data->has_encrypt = true;
4831 spec_info->u.qcow2.data->encrypt = qencrypt;
4837 static int qcow2_has_zero_init(BlockDriverState *bs)
4839 BDRVQcow2State *s = bs->opaque;
4842 if (qemu_in_coroutine()) {
4843 qemu_co_mutex_lock(&s->lock);
4846 * Check preallocation status: Preallocated images have all L2
4847 * tables allocated, nonpreallocated images have none. It is
4848 * therefore enough to check the first one.
4850 preallocated = s->l1_size > 0 && s->l1_table[0] != 0;
4851 if (qemu_in_coroutine()) {
4852 qemu_co_mutex_unlock(&s->lock);
4855 if (!preallocated) {
4857 } else if (bs->encrypted) {
4860 return bdrv_has_zero_init(s->data_file->bs);
4864 static int qcow2_save_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
4867 BDRVQcow2State *s = bs->opaque;
4869 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_SAVE);
4870 return bs->drv->bdrv_co_pwritev_part(bs, qcow2_vm_state_offset(s) + pos,
4871 qiov->size, qiov, 0, 0);
4874 static int qcow2_load_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
4877 BDRVQcow2State *s = bs->opaque;
4879 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_LOAD);
4880 return bs->drv->bdrv_co_preadv_part(bs, qcow2_vm_state_offset(s) + pos,
4881 qiov->size, qiov, 0, 0);
4885 * Downgrades an image's version. To achieve this, any incompatible features
4886 * have to be removed.
4888 static int qcow2_downgrade(BlockDriverState *bs, int target_version,
4889 BlockDriverAmendStatusCB *status_cb, void *cb_opaque,
4892 BDRVQcow2State *s = bs->opaque;
4893 int current_version = s->qcow_version;
4896 /* This is qcow2_downgrade(), not qcow2_upgrade() */
4897 assert(target_version < current_version);
4899 /* There are no other versions (now) that you can downgrade to */
4900 assert(target_version == 2);
4902 if (s->refcount_order != 4) {
4903 error_setg(errp, "compat=0.10 requires refcount_bits=16");
4907 if (has_data_file(bs)) {
4908 error_setg(errp, "Cannot downgrade an image with a data file");
4912 /* clear incompatible features */
4913 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
4914 ret = qcow2_mark_clean(bs);
4916 error_setg_errno(errp, -ret, "Failed to make the image clean");
4921 /* with QCOW2_INCOMPAT_CORRUPT, it is pretty much impossible to get here in
4922 * the first place; if that happens nonetheless, returning -ENOTSUP is the
4923 * best thing to do anyway */
4925 if (s->incompatible_features) {
4926 error_setg(errp, "Cannot downgrade an image with incompatible features "
4927 "%#" PRIx64 " set", s->incompatible_features);
4931 /* since we can ignore compatible features, we can set them to 0 as well */
4932 s->compatible_features = 0;
4933 /* if lazy refcounts have been used, they have already been fixed through
4934 * clearing the dirty flag */
4936 /* clearing autoclear features is trivial */
4937 s->autoclear_features = 0;
4939 ret = qcow2_expand_zero_clusters(bs, status_cb, cb_opaque);
4941 error_setg_errno(errp, -ret, "Failed to turn zero into data clusters");
4945 s->qcow_version = target_version;
4946 ret = qcow2_update_header(bs);
4948 s->qcow_version = current_version;
4949 error_setg_errno(errp, -ret, "Failed to update the image header");
4956 * Upgrades an image's version. While newer versions encompass all
4957 * features of older versions, some things may have to be presented
4960 static int qcow2_upgrade(BlockDriverState *bs, int target_version,
4961 BlockDriverAmendStatusCB *status_cb, void *cb_opaque,
4964 BDRVQcow2State *s = bs->opaque;
4965 bool need_snapshot_update;
4966 int current_version = s->qcow_version;
4970 /* This is qcow2_upgrade(), not qcow2_downgrade() */
4971 assert(target_version > current_version);
4973 /* There are no other versions (yet) that you can upgrade to */
4974 assert(target_version == 3);
4976 status_cb(bs, 0, 2, cb_opaque);
4979 * In v2, snapshots do not need to have extra data. v3 requires
4980 * the 64-bit VM state size and the virtual disk size to be
4982 * qcow2_write_snapshots() will always write the list in the
4983 * v3-compliant format.
4985 need_snapshot_update = false;
4986 for (i = 0; i < s->nb_snapshots; i++) {
4987 if (s->snapshots[i].extra_data_size <
4988 sizeof_field(QCowSnapshotExtraData, vm_state_size_large) +
4989 sizeof_field(QCowSnapshotExtraData, disk_size))
4991 need_snapshot_update = true;
4995 if (need_snapshot_update) {
4996 ret = qcow2_write_snapshots(bs);
4998 error_setg_errno(errp, -ret, "Failed to update the snapshot table");
5002 status_cb(bs, 1, 2, cb_opaque);
5004 s->qcow_version = target_version;
5005 ret = qcow2_update_header(bs);
5007 s->qcow_version = current_version;
5008 error_setg_errno(errp, -ret, "Failed to update the image header");
5011 status_cb(bs, 2, 2, cb_opaque);
5016 typedef enum Qcow2AmendOperation {
5017 /* This is the value Qcow2AmendHelperCBInfo::last_operation will be
5018 * statically initialized to so that the helper CB can discern the first
5019 * invocation from an operation change */
5020 QCOW2_NO_OPERATION = 0,
5023 QCOW2_CHANGING_REFCOUNT_ORDER,
5025 } Qcow2AmendOperation;
5027 typedef struct Qcow2AmendHelperCBInfo {
5028 /* The code coordinating the amend operations should only modify
5029 * these four fields; the rest will be managed by the CB */
5030 BlockDriverAmendStatusCB *original_status_cb;
5031 void *original_cb_opaque;
5033 Qcow2AmendOperation current_operation;
5035 /* Total number of operations to perform (only set once) */
5036 int total_operations;
5038 /* The following fields are managed by the CB */
5040 /* Number of operations completed */
5041 int operations_completed;
5043 /* Cumulative offset of all completed operations */
5044 int64_t offset_completed;
5046 Qcow2AmendOperation last_operation;
5047 int64_t last_work_size;
5048 } Qcow2AmendHelperCBInfo;
5050 static void qcow2_amend_helper_cb(BlockDriverState *bs,
5051 int64_t operation_offset,
5052 int64_t operation_work_size, void *opaque)
5054 Qcow2AmendHelperCBInfo *info = opaque;
5055 int64_t current_work_size;
5056 int64_t projected_work_size;
5058 if (info->current_operation != info->last_operation) {
5059 if (info->last_operation != QCOW2_NO_OPERATION) {
5060 info->offset_completed += info->last_work_size;
5061 info->operations_completed++;
5064 info->last_operation = info->current_operation;
5067 assert(info->total_operations > 0);
5068 assert(info->operations_completed < info->total_operations);
5070 info->last_work_size = operation_work_size;
5072 current_work_size = info->offset_completed + operation_work_size;
5074 /* current_work_size is the total work size for (operations_completed + 1)
5075 * operations (which includes this one), so multiply it by the number of
5076 * operations not covered and divide it by the number of operations
5077 * covered to get a projection for the operations not covered */
5078 projected_work_size = current_work_size * (info->total_operations -
5079 info->operations_completed - 1)
5080 / (info->operations_completed + 1);
5082 info->original_status_cb(bs, info->offset_completed + operation_offset,
5083 current_work_size + projected_work_size,
5084 info->original_cb_opaque);
5087 static int qcow2_amend_options(BlockDriverState *bs, QemuOpts *opts,
5088 BlockDriverAmendStatusCB *status_cb,
5092 BDRVQcow2State *s = bs->opaque;
5093 int old_version = s->qcow_version, new_version = old_version;
5094 uint64_t new_size = 0;
5095 const char *backing_file = NULL, *backing_format = NULL, *data_file = NULL;
5096 bool lazy_refcounts = s->use_lazy_refcounts;
5097 bool data_file_raw = data_file_is_raw(bs);
5098 const char *compat = NULL;
5099 uint64_t cluster_size = s->cluster_size;
5102 int refcount_bits = s->refcount_bits;
5104 QemuOptDesc *desc = opts->list->desc;
5105 Qcow2AmendHelperCBInfo helper_cb_info;
5107 while (desc && desc->name) {
5108 if (!qemu_opt_find(opts, desc->name)) {
5109 /* only change explicitly defined options */
5114 if (!strcmp(desc->name, BLOCK_OPT_COMPAT_LEVEL)) {
5115 compat = qemu_opt_get(opts, BLOCK_OPT_COMPAT_LEVEL);
5117 /* preserve default */
5118 } else if (!strcmp(compat, "0.10") || !strcmp(compat, "v2")) {
5120 } else if (!strcmp(compat, "1.1") || !strcmp(compat, "v3")) {
5123 error_setg(errp, "Unknown compatibility level %s", compat);
5126 } else if (!strcmp(desc->name, BLOCK_OPT_PREALLOC)) {
5127 error_setg(errp, "Cannot change preallocation mode");
5129 } else if (!strcmp(desc->name, BLOCK_OPT_SIZE)) {
5130 new_size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, 0);
5131 } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FILE)) {
5132 backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
5133 } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FMT)) {
5134 backing_format = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
5135 } else if (!strcmp(desc->name, BLOCK_OPT_ENCRYPT)) {
5136 encrypt = qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT,
5139 if (encrypt != !!s->crypto) {
5141 "Changing the encryption flag is not supported");
5144 } else if (!strcmp(desc->name, BLOCK_OPT_ENCRYPT_FORMAT)) {
5145 encformat = qcow2_crypt_method_from_format(
5146 qemu_opt_get(opts, BLOCK_OPT_ENCRYPT_FORMAT));
5148 if (encformat != s->crypt_method_header) {
5150 "Changing the encryption format is not supported");
5153 } else if (g_str_has_prefix(desc->name, "encrypt.")) {
5155 "Changing the encryption parameters is not supported");
5157 } else if (!strcmp(desc->name, BLOCK_OPT_CLUSTER_SIZE)) {
5158 cluster_size = qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE,
5160 if (cluster_size != s->cluster_size) {
5161 error_setg(errp, "Changing the cluster size is not supported");
5164 } else if (!strcmp(desc->name, BLOCK_OPT_LAZY_REFCOUNTS)) {
5165 lazy_refcounts = qemu_opt_get_bool(opts, BLOCK_OPT_LAZY_REFCOUNTS,
5167 } else if (!strcmp(desc->name, BLOCK_OPT_REFCOUNT_BITS)) {
5168 refcount_bits = qemu_opt_get_number(opts, BLOCK_OPT_REFCOUNT_BITS,
5171 if (refcount_bits <= 0 || refcount_bits > 64 ||
5172 !is_power_of_2(refcount_bits))
5174 error_setg(errp, "Refcount width must be a power of two and "
5175 "may not exceed 64 bits");
5178 } else if (!strcmp(desc->name, BLOCK_OPT_DATA_FILE)) {
5179 data_file = qemu_opt_get(opts, BLOCK_OPT_DATA_FILE);
5180 if (data_file && !has_data_file(bs)) {
5181 error_setg(errp, "data-file can only be set for images that "
5182 "use an external data file");
5185 } else if (!strcmp(desc->name, BLOCK_OPT_DATA_FILE_RAW)) {
5186 data_file_raw = qemu_opt_get_bool(opts, BLOCK_OPT_DATA_FILE_RAW,
5188 if (data_file_raw && !data_file_is_raw(bs)) {
5189 error_setg(errp, "data-file-raw cannot be set on existing "
5194 /* if this point is reached, this probably means a new option was
5195 * added without having it covered here */
5202 helper_cb_info = (Qcow2AmendHelperCBInfo){
5203 .original_status_cb = status_cb,
5204 .original_cb_opaque = cb_opaque,
5205 .total_operations = (new_version != old_version)
5206 + (s->refcount_bits != refcount_bits)
5209 /* Upgrade first (some features may require compat=1.1) */
5210 if (new_version > old_version) {
5211 helper_cb_info.current_operation = QCOW2_UPGRADING;
5212 ret = qcow2_upgrade(bs, new_version, &qcow2_amend_helper_cb,
5213 &helper_cb_info, errp);
5219 if (s->refcount_bits != refcount_bits) {
5220 int refcount_order = ctz32(refcount_bits);
5222 if (new_version < 3 && refcount_bits != 16) {
5223 error_setg(errp, "Refcount widths other than 16 bits require "
5224 "compatibility level 1.1 or above (use compat=1.1 or "
5229 helper_cb_info.current_operation = QCOW2_CHANGING_REFCOUNT_ORDER;
5230 ret = qcow2_change_refcount_order(bs, refcount_order,
5231 &qcow2_amend_helper_cb,
5232 &helper_cb_info, errp);
5238 /* data-file-raw blocks backing files, so clear it first if requested */
5239 if (data_file_raw) {
5240 s->autoclear_features |= QCOW2_AUTOCLEAR_DATA_FILE_RAW;
5242 s->autoclear_features &= ~QCOW2_AUTOCLEAR_DATA_FILE_RAW;
5246 g_free(s->image_data_file);
5247 s->image_data_file = *data_file ? g_strdup(data_file) : NULL;
5250 ret = qcow2_update_header(bs);
5252 error_setg_errno(errp, -ret, "Failed to update the image header");
5256 if (backing_file || backing_format) {
5257 ret = qcow2_change_backing_file(bs,
5258 backing_file ?: s->image_backing_file,
5259 backing_format ?: s->image_backing_format);
5261 error_setg_errno(errp, -ret, "Failed to change the backing file");
5266 if (s->use_lazy_refcounts != lazy_refcounts) {
5267 if (lazy_refcounts) {
5268 if (new_version < 3) {
5269 error_setg(errp, "Lazy refcounts only supported with "
5270 "compatibility level 1.1 and above (use compat=1.1 "
5274 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
5275 ret = qcow2_update_header(bs);
5277 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
5278 error_setg_errno(errp, -ret, "Failed to update the image header");
5281 s->use_lazy_refcounts = true;
5283 /* make image clean first */
5284 ret = qcow2_mark_clean(bs);
5286 error_setg_errno(errp, -ret, "Failed to make the image clean");
5289 /* now disallow lazy refcounts */
5290 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
5291 ret = qcow2_update_header(bs);
5293 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
5294 error_setg_errno(errp, -ret, "Failed to update the image header");
5297 s->use_lazy_refcounts = false;
5302 BlockBackend *blk = blk_new(bdrv_get_aio_context(bs),
5303 BLK_PERM_RESIZE, BLK_PERM_ALL);
5304 ret = blk_insert_bs(blk, bs, errp);
5310 ret = blk_truncate(blk, new_size, PREALLOC_MODE_OFF, errp);
5317 /* Downgrade last (so unsupported features can be removed before) */
5318 if (new_version < old_version) {
5319 helper_cb_info.current_operation = QCOW2_DOWNGRADING;
5320 ret = qcow2_downgrade(bs, new_version, &qcow2_amend_helper_cb,
5321 &helper_cb_info, errp);
5331 * If offset or size are negative, respectively, they will not be included in
5332 * the BLOCK_IMAGE_CORRUPTED event emitted.
5333 * fatal will be ignored for read-only BDS; corruptions found there will always
5334 * be considered non-fatal.
5336 void qcow2_signal_corruption(BlockDriverState *bs, bool fatal, int64_t offset,
5337 int64_t size, const char *message_format, ...)
5339 BDRVQcow2State *s = bs->opaque;
5340 const char *node_name;
5344 fatal = fatal && bdrv_is_writable(bs);
5346 if (s->signaled_corruption &&
5347 (!fatal || (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT)))
5352 va_start(ap, message_format);
5353 message = g_strdup_vprintf(message_format, ap);
5357 fprintf(stderr, "qcow2: Marking image as corrupt: %s; further "
5358 "corruption events will be suppressed\n", message);
5360 fprintf(stderr, "qcow2: Image is corrupt: %s; further non-fatal "
5361 "corruption events will be suppressed\n", message);
5364 node_name = bdrv_get_node_name(bs);
5365 qapi_event_send_block_image_corrupted(bdrv_get_device_name(bs),
5366 *node_name != '\0', node_name,
5367 message, offset >= 0, offset,
5373 qcow2_mark_corrupt(bs);
5374 bs->drv = NULL; /* make BDS unusable */
5377 s->signaled_corruption = true;
5380 static QemuOptsList qcow2_create_opts = {
5381 .name = "qcow2-create-opts",
5382 .head = QTAILQ_HEAD_INITIALIZER(qcow2_create_opts.head),
5385 .name = BLOCK_OPT_SIZE,
5386 .type = QEMU_OPT_SIZE,
5387 .help = "Virtual disk size"
5390 .name = BLOCK_OPT_COMPAT_LEVEL,
5391 .type = QEMU_OPT_STRING,
5392 .help = "Compatibility level (v2 [0.10] or v3 [1.1])"
5395 .name = BLOCK_OPT_BACKING_FILE,
5396 .type = QEMU_OPT_STRING,
5397 .help = "File name of a base image"
5400 .name = BLOCK_OPT_BACKING_FMT,
5401 .type = QEMU_OPT_STRING,
5402 .help = "Image format of the base image"
5405 .name = BLOCK_OPT_DATA_FILE,
5406 .type = QEMU_OPT_STRING,
5407 .help = "File name of an external data file"
5410 .name = BLOCK_OPT_DATA_FILE_RAW,
5411 .type = QEMU_OPT_BOOL,
5412 .help = "The external data file must stay valid as a raw image"
5415 .name = BLOCK_OPT_ENCRYPT,
5416 .type = QEMU_OPT_BOOL,
5417 .help = "Encrypt the image with format 'aes'. (Deprecated "
5418 "in favor of " BLOCK_OPT_ENCRYPT_FORMAT "=aes)",
5421 .name = BLOCK_OPT_ENCRYPT_FORMAT,
5422 .type = QEMU_OPT_STRING,
5423 .help = "Encrypt the image, format choices: 'aes', 'luks'",
5425 BLOCK_CRYPTO_OPT_DEF_KEY_SECRET("encrypt.",
5426 "ID of secret providing qcow AES key or LUKS passphrase"),
5427 BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_ALG("encrypt."),
5428 BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_MODE("encrypt."),
5429 BLOCK_CRYPTO_OPT_DEF_LUKS_IVGEN_ALG("encrypt."),
5430 BLOCK_CRYPTO_OPT_DEF_LUKS_IVGEN_HASH_ALG("encrypt."),
5431 BLOCK_CRYPTO_OPT_DEF_LUKS_HASH_ALG("encrypt."),
5432 BLOCK_CRYPTO_OPT_DEF_LUKS_ITER_TIME("encrypt."),
5434 .name = BLOCK_OPT_CLUSTER_SIZE,
5435 .type = QEMU_OPT_SIZE,
5436 .help = "qcow2 cluster size",
5437 .def_value_str = stringify(DEFAULT_CLUSTER_SIZE)
5440 .name = BLOCK_OPT_PREALLOC,
5441 .type = QEMU_OPT_STRING,
5442 .help = "Preallocation mode (allowed values: off, metadata, "
5446 .name = BLOCK_OPT_LAZY_REFCOUNTS,
5447 .type = QEMU_OPT_BOOL,
5448 .help = "Postpone refcount updates",
5449 .def_value_str = "off"
5452 .name = BLOCK_OPT_REFCOUNT_BITS,
5453 .type = QEMU_OPT_NUMBER,
5454 .help = "Width of a reference count entry in bits",
5455 .def_value_str = "16"
5457 { /* end of list */ }
5461 static const char *const qcow2_strong_runtime_opts[] = {
5462 "encrypt." BLOCK_CRYPTO_OPT_QCOW_KEY_SECRET,
5467 BlockDriver bdrv_qcow2 = {
5468 .format_name = "qcow2",
5469 .instance_size = sizeof(BDRVQcow2State),
5470 .bdrv_probe = qcow2_probe,
5471 .bdrv_open = qcow2_open,
5472 .bdrv_close = qcow2_close,
5473 .bdrv_reopen_prepare = qcow2_reopen_prepare,
5474 .bdrv_reopen_commit = qcow2_reopen_commit,
5475 .bdrv_reopen_abort = qcow2_reopen_abort,
5476 .bdrv_join_options = qcow2_join_options,
5477 .bdrv_child_perm = bdrv_format_default_perms,
5478 .bdrv_co_create_opts = qcow2_co_create_opts,
5479 .bdrv_co_create = qcow2_co_create,
5480 .bdrv_has_zero_init = qcow2_has_zero_init,
5481 .bdrv_has_zero_init_truncate = bdrv_has_zero_init_1,
5482 .bdrv_co_block_status = qcow2_co_block_status,
5484 .bdrv_co_preadv_part = qcow2_co_preadv_part,
5485 .bdrv_co_pwritev_part = qcow2_co_pwritev_part,
5486 .bdrv_co_flush_to_os = qcow2_co_flush_to_os,
5488 .bdrv_co_pwrite_zeroes = qcow2_co_pwrite_zeroes,
5489 .bdrv_co_pdiscard = qcow2_co_pdiscard,
5490 .bdrv_co_copy_range_from = qcow2_co_copy_range_from,
5491 .bdrv_co_copy_range_to = qcow2_co_copy_range_to,
5492 .bdrv_co_truncate = qcow2_co_truncate,
5493 .bdrv_co_pwritev_compressed_part = qcow2_co_pwritev_compressed_part,
5494 .bdrv_make_empty = qcow2_make_empty,
5496 .bdrv_snapshot_create = qcow2_snapshot_create,
5497 .bdrv_snapshot_goto = qcow2_snapshot_goto,
5498 .bdrv_snapshot_delete = qcow2_snapshot_delete,
5499 .bdrv_snapshot_list = qcow2_snapshot_list,
5500 .bdrv_snapshot_load_tmp = qcow2_snapshot_load_tmp,
5501 .bdrv_measure = qcow2_measure,
5502 .bdrv_get_info = qcow2_get_info,
5503 .bdrv_get_specific_info = qcow2_get_specific_info,
5505 .bdrv_save_vmstate = qcow2_save_vmstate,
5506 .bdrv_load_vmstate = qcow2_load_vmstate,
5508 .supports_backing = true,
5509 .bdrv_change_backing_file = qcow2_change_backing_file,
5511 .bdrv_refresh_limits = qcow2_refresh_limits,
5512 .bdrv_co_invalidate_cache = qcow2_co_invalidate_cache,
5513 .bdrv_inactivate = qcow2_inactivate,
5515 .create_opts = &qcow2_create_opts,
5516 .strong_runtime_opts = qcow2_strong_runtime_opts,
5517 .mutable_opts = mutable_opts,
5518 .bdrv_co_check = qcow2_co_check,
5519 .bdrv_amend_options = qcow2_amend_options,
5521 .bdrv_detach_aio_context = qcow2_detach_aio_context,
5522 .bdrv_attach_aio_context = qcow2_attach_aio_context,
5524 .bdrv_co_can_store_new_dirty_bitmap = qcow2_co_can_store_new_dirty_bitmap,
5525 .bdrv_co_remove_persistent_dirty_bitmap =
5526 qcow2_co_remove_persistent_dirty_bitmap,
5529 static void bdrv_qcow2_init(void)
5531 bdrv_register(&bdrv_qcow2);
5534 block_init(bdrv_qcow2_init);