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"
30 #include "block/block_int.h"
31 #include "block/qdict.h"
32 #include "sysemu/block-backend.h"
33 #include "qemu/module.h"
35 #include "qemu/error-report.h"
36 #include "qapi/error.h"
37 #include "qapi/qapi-events-block-core.h"
38 #include "qapi/qmp/qdict.h"
39 #include "qapi/qmp/qstring.h"
41 #include "qemu/option_int.h"
42 #include "qemu/cutils.h"
43 #include "qemu/bswap.h"
44 #include "qapi/qobject-input-visitor.h"
45 #include "qapi/qapi-visit-block-core.h"
47 #include "block/thread-pool.h"
50 Differences with QCOW:
52 - Support for multiple incremental snapshots.
53 - Memory management by reference counts.
54 - Clusters which have a reference count of one have the bit
55 QCOW_OFLAG_COPIED to optimize write performance.
56 - Size of compressed clusters is stored in sectors to reduce bit usage
57 in the cluster offsets.
58 - Support for storing additional data (such as the VM state) in the
60 - If a backing store is used, the cluster size is not constrained
61 (could be backported to QCOW).
62 - L2 tables have always a size of one cluster.
69 } QEMU_PACKED QCowExtension;
71 #define QCOW2_EXT_MAGIC_END 0
72 #define QCOW2_EXT_MAGIC_BACKING_FORMAT 0xE2792ACA
73 #define QCOW2_EXT_MAGIC_FEATURE_TABLE 0x6803f857
74 #define QCOW2_EXT_MAGIC_CRYPTO_HEADER 0x0537be77
75 #define QCOW2_EXT_MAGIC_BITMAPS 0x23852875
77 static int qcow2_probe(const uint8_t *buf, int buf_size, const char *filename)
79 const QCowHeader *cow_header = (const void *)buf;
81 if (buf_size >= sizeof(QCowHeader) &&
82 be32_to_cpu(cow_header->magic) == QCOW_MAGIC &&
83 be32_to_cpu(cow_header->version) >= 2)
90 static ssize_t qcow2_crypto_hdr_read_func(QCryptoBlock *block, size_t offset,
91 uint8_t *buf, size_t buflen,
92 void *opaque, Error **errp)
94 BlockDriverState *bs = opaque;
95 BDRVQcow2State *s = bs->opaque;
98 if ((offset + buflen) > s->crypto_header.length) {
99 error_setg(errp, "Request for data outside of extension header");
103 ret = bdrv_pread(bs->file,
104 s->crypto_header.offset + offset, buf, buflen);
106 error_setg_errno(errp, -ret, "Could not read encryption header");
113 static ssize_t qcow2_crypto_hdr_init_func(QCryptoBlock *block, size_t headerlen,
114 void *opaque, Error **errp)
116 BlockDriverState *bs = opaque;
117 BDRVQcow2State *s = bs->opaque;
121 ret = qcow2_alloc_clusters(bs, headerlen);
123 error_setg_errno(errp, -ret,
124 "Cannot allocate cluster for LUKS header size %zu",
129 s->crypto_header.length = headerlen;
130 s->crypto_header.offset = ret;
132 /* Zero fill remaining space in cluster so it has predictable
133 * content in case of future spec changes */
134 clusterlen = size_to_clusters(s, headerlen) * s->cluster_size;
135 assert(qcow2_pre_write_overlap_check(bs, 0, ret, clusterlen) == 0);
136 ret = bdrv_pwrite_zeroes(bs->file,
138 clusterlen - headerlen, 0);
140 error_setg_errno(errp, -ret, "Could not zero fill encryption header");
148 static ssize_t qcow2_crypto_hdr_write_func(QCryptoBlock *block, size_t offset,
149 const uint8_t *buf, size_t buflen,
150 void *opaque, Error **errp)
152 BlockDriverState *bs = opaque;
153 BDRVQcow2State *s = bs->opaque;
156 if ((offset + buflen) > s->crypto_header.length) {
157 error_setg(errp, "Request for data outside of extension header");
161 ret = bdrv_pwrite(bs->file,
162 s->crypto_header.offset + offset, buf, buflen);
164 error_setg_errno(errp, -ret, "Could not read encryption header");
172 * read qcow2 extension and fill bs
173 * start reading from start_offset
174 * finish reading upon magic of value 0 or when end_offset reached
175 * unknown magic is skipped (future extension this version knows nothing about)
176 * return 0 upon success, non-0 otherwise
178 static int qcow2_read_extensions(BlockDriverState *bs, uint64_t start_offset,
179 uint64_t end_offset, void **p_feature_table,
180 int flags, bool *need_update_header,
183 BDRVQcow2State *s = bs->opaque;
187 Qcow2BitmapHeaderExt bitmaps_ext;
189 if (need_update_header != NULL) {
190 *need_update_header = false;
194 printf("qcow2_read_extensions: start=%ld end=%ld\n", start_offset, end_offset);
196 offset = start_offset;
197 while (offset < end_offset) {
201 if (offset > s->cluster_size)
202 printf("qcow2_read_extension: suspicious offset %lu\n", offset);
204 printf("attempting to read extended header in offset %lu\n", offset);
207 ret = bdrv_pread(bs->file, offset, &ext, sizeof(ext));
209 error_setg_errno(errp, -ret, "qcow2_read_extension: ERROR: "
210 "pread fail from offset %" PRIu64, offset);
213 be32_to_cpus(&ext.magic);
214 be32_to_cpus(&ext.len);
215 offset += sizeof(ext);
217 printf("ext.magic = 0x%x\n", ext.magic);
219 if (offset > end_offset || ext.len > end_offset - offset) {
220 error_setg(errp, "Header extension too large");
225 case QCOW2_EXT_MAGIC_END:
228 case QCOW2_EXT_MAGIC_BACKING_FORMAT:
229 if (ext.len >= sizeof(bs->backing_format)) {
230 error_setg(errp, "ERROR: ext_backing_format: len=%" PRIu32
231 " too large (>=%zu)", ext.len,
232 sizeof(bs->backing_format));
235 ret = bdrv_pread(bs->file, offset, bs->backing_format, ext.len);
237 error_setg_errno(errp, -ret, "ERROR: ext_backing_format: "
238 "Could not read format name");
241 bs->backing_format[ext.len] = '\0';
242 s->image_backing_format = g_strdup(bs->backing_format);
244 printf("Qcow2: Got format extension %s\n", bs->backing_format);
248 case QCOW2_EXT_MAGIC_FEATURE_TABLE:
249 if (p_feature_table != NULL) {
250 void* feature_table = g_malloc0(ext.len + 2 * sizeof(Qcow2Feature));
251 ret = bdrv_pread(bs->file, offset , feature_table, ext.len);
253 error_setg_errno(errp, -ret, "ERROR: ext_feature_table: "
254 "Could not read table");
258 *p_feature_table = feature_table;
262 case QCOW2_EXT_MAGIC_CRYPTO_HEADER: {
263 unsigned int cflags = 0;
264 if (s->crypt_method_header != QCOW_CRYPT_LUKS) {
265 error_setg(errp, "CRYPTO header extension only "
266 "expected with LUKS encryption method");
269 if (ext.len != sizeof(Qcow2CryptoHeaderExtension)) {
270 error_setg(errp, "CRYPTO header extension size %u, "
271 "but expected size %zu", ext.len,
272 sizeof(Qcow2CryptoHeaderExtension));
276 ret = bdrv_pread(bs->file, offset, &s->crypto_header, ext.len);
278 error_setg_errno(errp, -ret,
279 "Unable to read CRYPTO header extension");
282 be64_to_cpus(&s->crypto_header.offset);
283 be64_to_cpus(&s->crypto_header.length);
285 if ((s->crypto_header.offset % s->cluster_size) != 0) {
286 error_setg(errp, "Encryption header offset '%" PRIu64 "' is "
287 "not a multiple of cluster size '%u'",
288 s->crypto_header.offset, s->cluster_size);
292 if (flags & BDRV_O_NO_IO) {
293 cflags |= QCRYPTO_BLOCK_OPEN_NO_IO;
295 s->crypto = qcrypto_block_open(s->crypto_opts, "encrypt.",
296 qcow2_crypto_hdr_read_func,
303 case QCOW2_EXT_MAGIC_BITMAPS:
304 if (ext.len != sizeof(bitmaps_ext)) {
305 error_setg_errno(errp, -ret, "bitmaps_ext: "
306 "Invalid extension length");
310 if (!(s->autoclear_features & QCOW2_AUTOCLEAR_BITMAPS)) {
311 if (s->qcow_version < 3) {
312 /* Let's be a bit more specific */
313 warn_report("This qcow2 v2 image contains bitmaps, but "
314 "they may have been modified by a program "
315 "without persistent bitmap support; so now "
316 "they must all be considered inconsistent");
318 warn_report("a program lacking bitmap support "
319 "modified this file, so all bitmaps are now "
320 "considered inconsistent");
322 error_printf("Some clusters may be leaked, "
323 "run 'qemu-img check -r' on the image "
325 if (need_update_header != NULL) {
326 /* Updating is needed to drop invalid bitmap extension. */
327 *need_update_header = true;
332 ret = bdrv_pread(bs->file, offset, &bitmaps_ext, ext.len);
334 error_setg_errno(errp, -ret, "bitmaps_ext: "
335 "Could not read ext header");
339 if (bitmaps_ext.reserved32 != 0) {
340 error_setg_errno(errp, -ret, "bitmaps_ext: "
341 "Reserved field is not zero");
345 be32_to_cpus(&bitmaps_ext.nb_bitmaps);
346 be64_to_cpus(&bitmaps_ext.bitmap_directory_size);
347 be64_to_cpus(&bitmaps_ext.bitmap_directory_offset);
349 if (bitmaps_ext.nb_bitmaps > QCOW2_MAX_BITMAPS) {
351 "bitmaps_ext: Image has %" PRIu32 " bitmaps, "
352 "exceeding the QEMU supported maximum of %d",
353 bitmaps_ext.nb_bitmaps, QCOW2_MAX_BITMAPS);
357 if (bitmaps_ext.nb_bitmaps == 0) {
358 error_setg(errp, "found bitmaps extension with zero bitmaps");
362 if (bitmaps_ext.bitmap_directory_offset & (s->cluster_size - 1)) {
363 error_setg(errp, "bitmaps_ext: "
364 "invalid bitmap directory offset");
368 if (bitmaps_ext.bitmap_directory_size >
369 QCOW2_MAX_BITMAP_DIRECTORY_SIZE) {
370 error_setg(errp, "bitmaps_ext: "
371 "bitmap directory size (%" PRIu64 ") exceeds "
372 "the maximum supported size (%d)",
373 bitmaps_ext.bitmap_directory_size,
374 QCOW2_MAX_BITMAP_DIRECTORY_SIZE);
378 s->nb_bitmaps = bitmaps_ext.nb_bitmaps;
379 s->bitmap_directory_offset =
380 bitmaps_ext.bitmap_directory_offset;
381 s->bitmap_directory_size =
382 bitmaps_ext.bitmap_directory_size;
385 printf("Qcow2: Got bitmaps extension: "
386 "offset=%" PRIu64 " nb_bitmaps=%" PRIu32 "\n",
387 s->bitmap_directory_offset, s->nb_bitmaps);
392 /* unknown magic - save it in case we need to rewrite the header */
393 /* If you add a new feature, make sure to also update the fast
394 * path of qcow2_make_empty() to deal with it. */
396 Qcow2UnknownHeaderExtension *uext;
398 uext = g_malloc0(sizeof(*uext) + ext.len);
399 uext->magic = ext.magic;
401 QLIST_INSERT_HEAD(&s->unknown_header_ext, uext, next);
403 ret = bdrv_pread(bs->file, offset , uext->data, uext->len);
405 error_setg_errno(errp, -ret, "ERROR: unknown extension: "
406 "Could not read data");
413 offset += ((ext.len + 7) & ~7);
419 static void cleanup_unknown_header_ext(BlockDriverState *bs)
421 BDRVQcow2State *s = bs->opaque;
422 Qcow2UnknownHeaderExtension *uext, *next;
424 QLIST_FOREACH_SAFE(uext, &s->unknown_header_ext, next, next) {
425 QLIST_REMOVE(uext, next);
430 static void report_unsupported_feature(Error **errp, Qcow2Feature *table,
433 char *features = g_strdup("");
436 while (table && table->name[0] != '\0') {
437 if (table->type == QCOW2_FEAT_TYPE_INCOMPATIBLE) {
438 if (mask & (1ULL << table->bit)) {
440 features = g_strdup_printf("%s%s%.46s", old, *old ? ", " : "",
443 mask &= ~(1ULL << table->bit);
451 features = g_strdup_printf("%s%sUnknown incompatible feature: %" PRIx64,
452 old, *old ? ", " : "", mask);
456 error_setg(errp, "Unsupported qcow2 feature(s): %s", features);
461 * Sets the dirty bit and flushes afterwards if necessary.
463 * The incompatible_features bit is only set if the image file header was
464 * updated successfully. Therefore it is not required to check the return
465 * value of this function.
467 int qcow2_mark_dirty(BlockDriverState *bs)
469 BDRVQcow2State *s = bs->opaque;
473 assert(s->qcow_version >= 3);
475 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
476 return 0; /* already dirty */
479 val = cpu_to_be64(s->incompatible_features | QCOW2_INCOMPAT_DIRTY);
480 ret = bdrv_pwrite(bs->file, offsetof(QCowHeader, incompatible_features),
485 ret = bdrv_flush(bs->file->bs);
490 /* Only treat image as dirty if the header was updated successfully */
491 s->incompatible_features |= QCOW2_INCOMPAT_DIRTY;
496 * Clears the dirty bit and flushes before if necessary. Only call this
497 * function when there are no pending requests, it does not guard against
498 * concurrent requests dirtying the image.
500 static int qcow2_mark_clean(BlockDriverState *bs)
502 BDRVQcow2State *s = bs->opaque;
504 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
507 s->incompatible_features &= ~QCOW2_INCOMPAT_DIRTY;
509 ret = qcow2_flush_caches(bs);
514 return qcow2_update_header(bs);
520 * Marks the image as corrupt.
522 int qcow2_mark_corrupt(BlockDriverState *bs)
524 BDRVQcow2State *s = bs->opaque;
526 s->incompatible_features |= QCOW2_INCOMPAT_CORRUPT;
527 return qcow2_update_header(bs);
531 * Marks the image as consistent, i.e., unsets the corrupt bit, and flushes
532 * before if necessary.
534 int qcow2_mark_consistent(BlockDriverState *bs)
536 BDRVQcow2State *s = bs->opaque;
538 if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
539 int ret = qcow2_flush_caches(bs);
544 s->incompatible_features &= ~QCOW2_INCOMPAT_CORRUPT;
545 return qcow2_update_header(bs);
550 static int coroutine_fn qcow2_co_check_locked(BlockDriverState *bs,
551 BdrvCheckResult *result,
554 int ret = qcow2_check_refcounts(bs, result, fix);
559 if (fix && result->check_errors == 0 && result->corruptions == 0) {
560 ret = qcow2_mark_clean(bs);
564 return qcow2_mark_consistent(bs);
569 static int coroutine_fn qcow2_co_check(BlockDriverState *bs,
570 BdrvCheckResult *result,
573 BDRVQcow2State *s = bs->opaque;
576 qemu_co_mutex_lock(&s->lock);
577 ret = qcow2_co_check_locked(bs, result, fix);
578 qemu_co_mutex_unlock(&s->lock);
582 int qcow2_validate_table(BlockDriverState *bs, uint64_t offset,
583 uint64_t entries, size_t entry_len,
584 int64_t max_size_bytes, const char *table_name,
587 BDRVQcow2State *s = bs->opaque;
589 if (entries > max_size_bytes / entry_len) {
590 error_setg(errp, "%s too large", table_name);
594 /* Use signed INT64_MAX as the maximum even for uint64_t header fields,
595 * because values will be passed to qemu functions taking int64_t. */
596 if ((INT64_MAX - entries * entry_len < offset) ||
597 (offset_into_cluster(s, offset) != 0)) {
598 error_setg(errp, "%s offset invalid", table_name);
605 static QemuOptsList qcow2_runtime_opts = {
607 .head = QTAILQ_HEAD_INITIALIZER(qcow2_runtime_opts.head),
610 .name = QCOW2_OPT_LAZY_REFCOUNTS,
611 .type = QEMU_OPT_BOOL,
612 .help = "Postpone refcount updates",
615 .name = QCOW2_OPT_DISCARD_REQUEST,
616 .type = QEMU_OPT_BOOL,
617 .help = "Pass guest discard requests to the layer below",
620 .name = QCOW2_OPT_DISCARD_SNAPSHOT,
621 .type = QEMU_OPT_BOOL,
622 .help = "Generate discard requests when snapshot related space "
626 .name = QCOW2_OPT_DISCARD_OTHER,
627 .type = QEMU_OPT_BOOL,
628 .help = "Generate discard requests when other clusters are freed",
631 .name = QCOW2_OPT_OVERLAP,
632 .type = QEMU_OPT_STRING,
633 .help = "Selects which overlap checks to perform from a range of "
634 "templates (none, constant, cached, all)",
637 .name = QCOW2_OPT_OVERLAP_TEMPLATE,
638 .type = QEMU_OPT_STRING,
639 .help = "Selects which overlap checks to perform from a range of "
640 "templates (none, constant, cached, all)",
643 .name = QCOW2_OPT_OVERLAP_MAIN_HEADER,
644 .type = QEMU_OPT_BOOL,
645 .help = "Check for unintended writes into the main qcow2 header",
648 .name = QCOW2_OPT_OVERLAP_ACTIVE_L1,
649 .type = QEMU_OPT_BOOL,
650 .help = "Check for unintended writes into the active L1 table",
653 .name = QCOW2_OPT_OVERLAP_ACTIVE_L2,
654 .type = QEMU_OPT_BOOL,
655 .help = "Check for unintended writes into an active L2 table",
658 .name = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
659 .type = QEMU_OPT_BOOL,
660 .help = "Check for unintended writes into the refcount table",
663 .name = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
664 .type = QEMU_OPT_BOOL,
665 .help = "Check for unintended writes into a refcount block",
668 .name = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
669 .type = QEMU_OPT_BOOL,
670 .help = "Check for unintended writes into the snapshot table",
673 .name = QCOW2_OPT_OVERLAP_INACTIVE_L1,
674 .type = QEMU_OPT_BOOL,
675 .help = "Check for unintended writes into an inactive L1 table",
678 .name = QCOW2_OPT_OVERLAP_INACTIVE_L2,
679 .type = QEMU_OPT_BOOL,
680 .help = "Check for unintended writes into an inactive L2 table",
683 .name = QCOW2_OPT_OVERLAP_BITMAP_DIRECTORY,
684 .type = QEMU_OPT_BOOL,
685 .help = "Check for unintended writes into the bitmap directory",
688 .name = QCOW2_OPT_CACHE_SIZE,
689 .type = QEMU_OPT_SIZE,
690 .help = "Maximum combined metadata (L2 tables and refcount blocks) "
694 .name = QCOW2_OPT_L2_CACHE_SIZE,
695 .type = QEMU_OPT_SIZE,
696 .help = "Maximum L2 table cache size",
699 .name = QCOW2_OPT_L2_CACHE_ENTRY_SIZE,
700 .type = QEMU_OPT_SIZE,
701 .help = "Size of each entry in the L2 cache",
704 .name = QCOW2_OPT_REFCOUNT_CACHE_SIZE,
705 .type = QEMU_OPT_SIZE,
706 .help = "Maximum refcount block cache size",
709 .name = QCOW2_OPT_CACHE_CLEAN_INTERVAL,
710 .type = QEMU_OPT_NUMBER,
711 .help = "Clean unused cache entries after this time (in seconds)",
713 BLOCK_CRYPTO_OPT_DEF_KEY_SECRET("encrypt.",
714 "ID of secret providing qcow2 AES key or LUKS passphrase"),
715 { /* end of list */ }
719 static const char *overlap_bool_option_names[QCOW2_OL_MAX_BITNR] = {
720 [QCOW2_OL_MAIN_HEADER_BITNR] = QCOW2_OPT_OVERLAP_MAIN_HEADER,
721 [QCOW2_OL_ACTIVE_L1_BITNR] = QCOW2_OPT_OVERLAP_ACTIVE_L1,
722 [QCOW2_OL_ACTIVE_L2_BITNR] = QCOW2_OPT_OVERLAP_ACTIVE_L2,
723 [QCOW2_OL_REFCOUNT_TABLE_BITNR] = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
724 [QCOW2_OL_REFCOUNT_BLOCK_BITNR] = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
725 [QCOW2_OL_SNAPSHOT_TABLE_BITNR] = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
726 [QCOW2_OL_INACTIVE_L1_BITNR] = QCOW2_OPT_OVERLAP_INACTIVE_L1,
727 [QCOW2_OL_INACTIVE_L2_BITNR] = QCOW2_OPT_OVERLAP_INACTIVE_L2,
728 [QCOW2_OL_BITMAP_DIRECTORY_BITNR] = QCOW2_OPT_OVERLAP_BITMAP_DIRECTORY,
731 static void cache_clean_timer_cb(void *opaque)
733 BlockDriverState *bs = opaque;
734 BDRVQcow2State *s = bs->opaque;
735 qcow2_cache_clean_unused(s->l2_table_cache);
736 qcow2_cache_clean_unused(s->refcount_block_cache);
737 timer_mod(s->cache_clean_timer, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) +
738 (int64_t) s->cache_clean_interval * 1000);
741 static void cache_clean_timer_init(BlockDriverState *bs, AioContext *context)
743 BDRVQcow2State *s = bs->opaque;
744 if (s->cache_clean_interval > 0) {
745 s->cache_clean_timer = aio_timer_new(context, QEMU_CLOCK_VIRTUAL,
746 SCALE_MS, cache_clean_timer_cb,
748 timer_mod(s->cache_clean_timer, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) +
749 (int64_t) s->cache_clean_interval * 1000);
753 static void cache_clean_timer_del(BlockDriverState *bs)
755 BDRVQcow2State *s = bs->opaque;
756 if (s->cache_clean_timer) {
757 timer_del(s->cache_clean_timer);
758 timer_free(s->cache_clean_timer);
759 s->cache_clean_timer = NULL;
763 static void qcow2_detach_aio_context(BlockDriverState *bs)
765 cache_clean_timer_del(bs);
768 static void qcow2_attach_aio_context(BlockDriverState *bs,
769 AioContext *new_context)
771 cache_clean_timer_init(bs, new_context);
774 static void read_cache_sizes(BlockDriverState *bs, QemuOpts *opts,
775 uint64_t *l2_cache_size,
776 uint64_t *l2_cache_entry_size,
777 uint64_t *refcount_cache_size, Error **errp)
779 BDRVQcow2State *s = bs->opaque;
780 uint64_t combined_cache_size;
781 bool l2_cache_size_set, refcount_cache_size_set, combined_cache_size_set;
782 int min_refcount_cache = MIN_REFCOUNT_CACHE_SIZE * s->cluster_size;
784 combined_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_CACHE_SIZE);
785 l2_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_L2_CACHE_SIZE);
786 refcount_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
788 combined_cache_size = qemu_opt_get_size(opts, QCOW2_OPT_CACHE_SIZE, 0);
789 *l2_cache_size = qemu_opt_get_size(opts, QCOW2_OPT_L2_CACHE_SIZE, 0);
790 *refcount_cache_size = qemu_opt_get_size(opts,
791 QCOW2_OPT_REFCOUNT_CACHE_SIZE, 0);
793 *l2_cache_entry_size = qemu_opt_get_size(
794 opts, QCOW2_OPT_L2_CACHE_ENTRY_SIZE, s->cluster_size);
796 if (combined_cache_size_set) {
797 if (l2_cache_size_set && refcount_cache_size_set) {
798 error_setg(errp, QCOW2_OPT_CACHE_SIZE ", " QCOW2_OPT_L2_CACHE_SIZE
799 " and " QCOW2_OPT_REFCOUNT_CACHE_SIZE " may not be set "
802 } else if (*l2_cache_size > combined_cache_size) {
803 error_setg(errp, QCOW2_OPT_L2_CACHE_SIZE " may not exceed "
804 QCOW2_OPT_CACHE_SIZE);
806 } else if (*refcount_cache_size > combined_cache_size) {
807 error_setg(errp, QCOW2_OPT_REFCOUNT_CACHE_SIZE " may not exceed "
808 QCOW2_OPT_CACHE_SIZE);
812 if (l2_cache_size_set) {
813 *refcount_cache_size = combined_cache_size - *l2_cache_size;
814 } else if (refcount_cache_size_set) {
815 *l2_cache_size = combined_cache_size - *refcount_cache_size;
817 uint64_t virtual_disk_size = bs->total_sectors * BDRV_SECTOR_SIZE;
818 uint64_t max_l2_cache = virtual_disk_size / (s->cluster_size / 8);
820 /* Assign as much memory as possible to the L2 cache, and
821 * use the remainder for the refcount cache */
822 if (combined_cache_size >= max_l2_cache + min_refcount_cache) {
823 *l2_cache_size = max_l2_cache;
824 *refcount_cache_size = combined_cache_size - *l2_cache_size;
826 *refcount_cache_size =
827 MIN(combined_cache_size, min_refcount_cache);
828 *l2_cache_size = combined_cache_size - *refcount_cache_size;
832 if (!l2_cache_size_set) {
833 *l2_cache_size = MAX(DEFAULT_L2_CACHE_SIZE,
834 (uint64_t)DEFAULT_L2_CACHE_CLUSTERS
838 /* l2_cache_size and refcount_cache_size are ensured to have at least
839 * their minimum values in qcow2_update_options_prepare() */
841 if (*l2_cache_entry_size < (1 << MIN_CLUSTER_BITS) ||
842 *l2_cache_entry_size > s->cluster_size ||
843 !is_power_of_2(*l2_cache_entry_size)) {
844 error_setg(errp, "L2 cache entry size must be a power of two "
845 "between %d and the cluster size (%d)",
846 1 << MIN_CLUSTER_BITS, s->cluster_size);
851 typedef struct Qcow2ReopenState {
852 Qcow2Cache *l2_table_cache;
853 Qcow2Cache *refcount_block_cache;
854 int l2_slice_size; /* Number of entries in a slice of the L2 table */
855 bool use_lazy_refcounts;
857 bool discard_passthrough[QCOW2_DISCARD_MAX];
858 uint64_t cache_clean_interval;
859 QCryptoBlockOpenOptions *crypto_opts; /* Disk encryption runtime options */
862 static int qcow2_update_options_prepare(BlockDriverState *bs,
864 QDict *options, int flags,
867 BDRVQcow2State *s = bs->opaque;
868 QemuOpts *opts = NULL;
869 const char *opt_overlap_check, *opt_overlap_check_template;
870 int overlap_check_template = 0;
871 uint64_t l2_cache_size, l2_cache_entry_size, refcount_cache_size;
873 const char *encryptfmt;
874 QDict *encryptopts = NULL;
875 Error *local_err = NULL;
878 qdict_extract_subqdict(options, &encryptopts, "encrypt.");
879 encryptfmt = qdict_get_try_str(encryptopts, "format");
881 opts = qemu_opts_create(&qcow2_runtime_opts, NULL, 0, &error_abort);
882 qemu_opts_absorb_qdict(opts, options, &local_err);
884 error_propagate(errp, local_err);
889 /* get L2 table/refcount block cache size from command line options */
890 read_cache_sizes(bs, opts, &l2_cache_size, &l2_cache_entry_size,
891 &refcount_cache_size, &local_err);
893 error_propagate(errp, local_err);
898 l2_cache_size /= l2_cache_entry_size;
899 if (l2_cache_size < MIN_L2_CACHE_SIZE) {
900 l2_cache_size = MIN_L2_CACHE_SIZE;
902 if (l2_cache_size > INT_MAX) {
903 error_setg(errp, "L2 cache size too big");
908 refcount_cache_size /= s->cluster_size;
909 if (refcount_cache_size < MIN_REFCOUNT_CACHE_SIZE) {
910 refcount_cache_size = MIN_REFCOUNT_CACHE_SIZE;
912 if (refcount_cache_size > INT_MAX) {
913 error_setg(errp, "Refcount cache size too big");
918 /* alloc new L2 table/refcount block cache, flush old one */
919 if (s->l2_table_cache) {
920 ret = qcow2_cache_flush(bs, s->l2_table_cache);
922 error_setg_errno(errp, -ret, "Failed to flush the L2 table cache");
927 if (s->refcount_block_cache) {
928 ret = qcow2_cache_flush(bs, s->refcount_block_cache);
930 error_setg_errno(errp, -ret,
931 "Failed to flush the refcount block cache");
936 r->l2_slice_size = l2_cache_entry_size / sizeof(uint64_t);
937 r->l2_table_cache = qcow2_cache_create(bs, l2_cache_size,
938 l2_cache_entry_size);
939 r->refcount_block_cache = qcow2_cache_create(bs, refcount_cache_size,
941 if (r->l2_table_cache == NULL || r->refcount_block_cache == NULL) {
942 error_setg(errp, "Could not allocate metadata caches");
947 /* New interval for cache cleanup timer */
948 r->cache_clean_interval =
949 qemu_opt_get_number(opts, QCOW2_OPT_CACHE_CLEAN_INTERVAL,
950 s->cache_clean_interval);
952 if (r->cache_clean_interval != 0) {
953 error_setg(errp, QCOW2_OPT_CACHE_CLEAN_INTERVAL
954 " not supported on this host");
959 if (r->cache_clean_interval > UINT_MAX) {
960 error_setg(errp, "Cache clean interval too big");
965 /* lazy-refcounts; flush if going from enabled to disabled */
966 r->use_lazy_refcounts = qemu_opt_get_bool(opts, QCOW2_OPT_LAZY_REFCOUNTS,
967 (s->compatible_features & QCOW2_COMPAT_LAZY_REFCOUNTS));
968 if (r->use_lazy_refcounts && s->qcow_version < 3) {
969 error_setg(errp, "Lazy refcounts require a qcow2 image with at least "
970 "qemu 1.1 compatibility level");
975 if (s->use_lazy_refcounts && !r->use_lazy_refcounts) {
976 ret = qcow2_mark_clean(bs);
978 error_setg_errno(errp, -ret, "Failed to disable lazy refcounts");
983 /* Overlap check options */
984 opt_overlap_check = qemu_opt_get(opts, QCOW2_OPT_OVERLAP);
985 opt_overlap_check_template = qemu_opt_get(opts, QCOW2_OPT_OVERLAP_TEMPLATE);
986 if (opt_overlap_check_template && opt_overlap_check &&
987 strcmp(opt_overlap_check_template, opt_overlap_check))
989 error_setg(errp, "Conflicting values for qcow2 options '"
990 QCOW2_OPT_OVERLAP "' ('%s') and '" QCOW2_OPT_OVERLAP_TEMPLATE
991 "' ('%s')", opt_overlap_check, opt_overlap_check_template);
995 if (!opt_overlap_check) {
996 opt_overlap_check = opt_overlap_check_template ?: "cached";
999 if (!strcmp(opt_overlap_check, "none")) {
1000 overlap_check_template = 0;
1001 } else if (!strcmp(opt_overlap_check, "constant")) {
1002 overlap_check_template = QCOW2_OL_CONSTANT;
1003 } else if (!strcmp(opt_overlap_check, "cached")) {
1004 overlap_check_template = QCOW2_OL_CACHED;
1005 } else if (!strcmp(opt_overlap_check, "all")) {
1006 overlap_check_template = QCOW2_OL_ALL;
1008 error_setg(errp, "Unsupported value '%s' for qcow2 option "
1009 "'overlap-check'. Allowed are any of the following: "
1010 "none, constant, cached, all", opt_overlap_check);
1015 r->overlap_check = 0;
1016 for (i = 0; i < QCOW2_OL_MAX_BITNR; i++) {
1017 /* overlap-check defines a template bitmask, but every flag may be
1018 * overwritten through the associated boolean option */
1020 qemu_opt_get_bool(opts, overlap_bool_option_names[i],
1021 overlap_check_template & (1 << i)) << i;
1024 r->discard_passthrough[QCOW2_DISCARD_NEVER] = false;
1025 r->discard_passthrough[QCOW2_DISCARD_ALWAYS] = true;
1026 r->discard_passthrough[QCOW2_DISCARD_REQUEST] =
1027 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_REQUEST,
1028 flags & BDRV_O_UNMAP);
1029 r->discard_passthrough[QCOW2_DISCARD_SNAPSHOT] =
1030 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_SNAPSHOT, true);
1031 r->discard_passthrough[QCOW2_DISCARD_OTHER] =
1032 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_OTHER, false);
1034 switch (s->crypt_method_header) {
1035 case QCOW_CRYPT_NONE:
1037 error_setg(errp, "No encryption in image header, but options "
1038 "specified format '%s'", encryptfmt);
1044 case QCOW_CRYPT_AES:
1045 if (encryptfmt && !g_str_equal(encryptfmt, "aes")) {
1047 "Header reported 'aes' encryption format but "
1048 "options specify '%s'", encryptfmt);
1052 qdict_put_str(encryptopts, "format", "qcow");
1053 r->crypto_opts = block_crypto_open_opts_init(encryptopts, errp);
1056 case QCOW_CRYPT_LUKS:
1057 if (encryptfmt && !g_str_equal(encryptfmt, "luks")) {
1059 "Header reported 'luks' encryption format but "
1060 "options specify '%s'", encryptfmt);
1064 qdict_put_str(encryptopts, "format", "luks");
1065 r->crypto_opts = block_crypto_open_opts_init(encryptopts, errp);
1069 error_setg(errp, "Unsupported encryption method %d",
1070 s->crypt_method_header);
1073 if (s->crypt_method_header != QCOW_CRYPT_NONE && !r->crypto_opts) {
1080 qobject_unref(encryptopts);
1081 qemu_opts_del(opts);
1086 static void qcow2_update_options_commit(BlockDriverState *bs,
1087 Qcow2ReopenState *r)
1089 BDRVQcow2State *s = bs->opaque;
1092 if (s->l2_table_cache) {
1093 qcow2_cache_destroy(s->l2_table_cache);
1095 if (s->refcount_block_cache) {
1096 qcow2_cache_destroy(s->refcount_block_cache);
1098 s->l2_table_cache = r->l2_table_cache;
1099 s->refcount_block_cache = r->refcount_block_cache;
1100 s->l2_slice_size = r->l2_slice_size;
1102 s->overlap_check = r->overlap_check;
1103 s->use_lazy_refcounts = r->use_lazy_refcounts;
1105 for (i = 0; i < QCOW2_DISCARD_MAX; i++) {
1106 s->discard_passthrough[i] = r->discard_passthrough[i];
1109 if (s->cache_clean_interval != r->cache_clean_interval) {
1110 cache_clean_timer_del(bs);
1111 s->cache_clean_interval = r->cache_clean_interval;
1112 cache_clean_timer_init(bs, bdrv_get_aio_context(bs));
1115 qapi_free_QCryptoBlockOpenOptions(s->crypto_opts);
1116 s->crypto_opts = r->crypto_opts;
1119 static void qcow2_update_options_abort(BlockDriverState *bs,
1120 Qcow2ReopenState *r)
1122 if (r->l2_table_cache) {
1123 qcow2_cache_destroy(r->l2_table_cache);
1125 if (r->refcount_block_cache) {
1126 qcow2_cache_destroy(r->refcount_block_cache);
1128 qapi_free_QCryptoBlockOpenOptions(r->crypto_opts);
1131 static int qcow2_update_options(BlockDriverState *bs, QDict *options,
1132 int flags, Error **errp)
1134 Qcow2ReopenState r = {};
1137 ret = qcow2_update_options_prepare(bs, &r, options, flags, errp);
1139 qcow2_update_options_commit(bs, &r);
1141 qcow2_update_options_abort(bs, &r);
1147 /* Called with s->lock held. */
1148 static int coroutine_fn qcow2_do_open(BlockDriverState *bs, QDict *options,
1149 int flags, Error **errp)
1151 BDRVQcow2State *s = bs->opaque;
1152 unsigned int len, i;
1155 Error *local_err = NULL;
1157 uint64_t l1_vm_state_index;
1158 bool update_header = false;
1159 bool header_updated = false;
1161 ret = bdrv_pread(bs->file, 0, &header, sizeof(header));
1163 error_setg_errno(errp, -ret, "Could not read qcow2 header");
1166 be32_to_cpus(&header.magic);
1167 be32_to_cpus(&header.version);
1168 be64_to_cpus(&header.backing_file_offset);
1169 be32_to_cpus(&header.backing_file_size);
1170 be64_to_cpus(&header.size);
1171 be32_to_cpus(&header.cluster_bits);
1172 be32_to_cpus(&header.crypt_method);
1173 be64_to_cpus(&header.l1_table_offset);
1174 be32_to_cpus(&header.l1_size);
1175 be64_to_cpus(&header.refcount_table_offset);
1176 be32_to_cpus(&header.refcount_table_clusters);
1177 be64_to_cpus(&header.snapshots_offset);
1178 be32_to_cpus(&header.nb_snapshots);
1180 if (header.magic != QCOW_MAGIC) {
1181 error_setg(errp, "Image is not in qcow2 format");
1185 if (header.version < 2 || header.version > 3) {
1186 error_setg(errp, "Unsupported qcow2 version %" PRIu32, header.version);
1191 s->qcow_version = header.version;
1193 /* Initialise cluster size */
1194 if (header.cluster_bits < MIN_CLUSTER_BITS ||
1195 header.cluster_bits > MAX_CLUSTER_BITS) {
1196 error_setg(errp, "Unsupported cluster size: 2^%" PRIu32,
1197 header.cluster_bits);
1202 s->cluster_bits = header.cluster_bits;
1203 s->cluster_size = 1 << s->cluster_bits;
1204 s->cluster_sectors = 1 << (s->cluster_bits - BDRV_SECTOR_BITS);
1206 /* Initialise version 3 header fields */
1207 if (header.version == 2) {
1208 header.incompatible_features = 0;
1209 header.compatible_features = 0;
1210 header.autoclear_features = 0;
1211 header.refcount_order = 4;
1212 header.header_length = 72;
1214 be64_to_cpus(&header.incompatible_features);
1215 be64_to_cpus(&header.compatible_features);
1216 be64_to_cpus(&header.autoclear_features);
1217 be32_to_cpus(&header.refcount_order);
1218 be32_to_cpus(&header.header_length);
1220 if (header.header_length < 104) {
1221 error_setg(errp, "qcow2 header too short");
1227 if (header.header_length > s->cluster_size) {
1228 error_setg(errp, "qcow2 header exceeds cluster size");
1233 if (header.header_length > sizeof(header)) {
1234 s->unknown_header_fields_size = header.header_length - sizeof(header);
1235 s->unknown_header_fields = g_malloc(s->unknown_header_fields_size);
1236 ret = bdrv_pread(bs->file, sizeof(header), s->unknown_header_fields,
1237 s->unknown_header_fields_size);
1239 error_setg_errno(errp, -ret, "Could not read unknown qcow2 header "
1245 if (header.backing_file_offset > s->cluster_size) {
1246 error_setg(errp, "Invalid backing file offset");
1251 if (header.backing_file_offset) {
1252 ext_end = header.backing_file_offset;
1254 ext_end = 1 << header.cluster_bits;
1257 /* Handle feature bits */
1258 s->incompatible_features = header.incompatible_features;
1259 s->compatible_features = header.compatible_features;
1260 s->autoclear_features = header.autoclear_features;
1262 if (s->incompatible_features & ~QCOW2_INCOMPAT_MASK) {
1263 void *feature_table = NULL;
1264 qcow2_read_extensions(bs, header.header_length, ext_end,
1265 &feature_table, flags, NULL, NULL);
1266 report_unsupported_feature(errp, feature_table,
1267 s->incompatible_features &
1268 ~QCOW2_INCOMPAT_MASK);
1270 g_free(feature_table);
1274 if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
1275 /* Corrupt images may not be written to unless they are being repaired
1277 if ((flags & BDRV_O_RDWR) && !(flags & BDRV_O_CHECK)) {
1278 error_setg(errp, "qcow2: Image is corrupt; cannot be opened "
1285 /* Check support for various header values */
1286 if (header.refcount_order > 6) {
1287 error_setg(errp, "Reference count entry width too large; may not "
1292 s->refcount_order = header.refcount_order;
1293 s->refcount_bits = 1 << s->refcount_order;
1294 s->refcount_max = UINT64_C(1) << (s->refcount_bits - 1);
1295 s->refcount_max += s->refcount_max - 1;
1297 s->crypt_method_header = header.crypt_method;
1298 if (s->crypt_method_header) {
1299 if (bdrv_uses_whitelist() &&
1300 s->crypt_method_header == QCOW_CRYPT_AES) {
1302 "Use of AES-CBC encrypted qcow2 images is no longer "
1303 "supported in system emulators");
1304 error_append_hint(errp,
1305 "You can use 'qemu-img convert' to convert your "
1306 "image to an alternative supported format, such "
1307 "as unencrypted qcow2, or raw with the LUKS "
1308 "format instead.\n");
1313 if (s->crypt_method_header == QCOW_CRYPT_AES) {
1314 s->crypt_physical_offset = false;
1316 /* Assuming LUKS and any future crypt methods we
1317 * add will all use physical offsets, due to the
1318 * fact that the alternative is insecure... */
1319 s->crypt_physical_offset = true;
1322 bs->encrypted = true;
1325 s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */
1326 s->l2_size = 1 << s->l2_bits;
1327 /* 2^(s->refcount_order - 3) is the refcount width in bytes */
1328 s->refcount_block_bits = s->cluster_bits - (s->refcount_order - 3);
1329 s->refcount_block_size = 1 << s->refcount_block_bits;
1330 bs->total_sectors = header.size / 512;
1331 s->csize_shift = (62 - (s->cluster_bits - 8));
1332 s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;
1333 s->cluster_offset_mask = (1LL << s->csize_shift) - 1;
1335 s->refcount_table_offset = header.refcount_table_offset;
1336 s->refcount_table_size =
1337 header.refcount_table_clusters << (s->cluster_bits - 3);
1339 if (header.refcount_table_clusters == 0 && !(flags & BDRV_O_CHECK)) {
1340 error_setg(errp, "Image does not contain a reference count table");
1345 ret = qcow2_validate_table(bs, s->refcount_table_offset,
1346 header.refcount_table_clusters,
1347 s->cluster_size, QCOW_MAX_REFTABLE_SIZE,
1348 "Reference count table", errp);
1353 /* The total size in bytes of the snapshot table is checked in
1354 * qcow2_read_snapshots() because the size of each snapshot is
1355 * variable and we don't know it yet.
1356 * Here we only check the offset and number of snapshots. */
1357 ret = qcow2_validate_table(bs, header.snapshots_offset,
1358 header.nb_snapshots,
1359 sizeof(QCowSnapshotHeader),
1360 sizeof(QCowSnapshotHeader) * QCOW_MAX_SNAPSHOTS,
1361 "Snapshot table", errp);
1366 /* read the level 1 table */
1367 ret = qcow2_validate_table(bs, header.l1_table_offset,
1368 header.l1_size, sizeof(uint64_t),
1369 QCOW_MAX_L1_SIZE, "Active L1 table", errp);
1373 s->l1_size = header.l1_size;
1374 s->l1_table_offset = header.l1_table_offset;
1376 l1_vm_state_index = size_to_l1(s, header.size);
1377 if (l1_vm_state_index > INT_MAX) {
1378 error_setg(errp, "Image is too big");
1382 s->l1_vm_state_index = l1_vm_state_index;
1384 /* the L1 table must contain at least enough entries to put
1385 header.size bytes */
1386 if (s->l1_size < s->l1_vm_state_index) {
1387 error_setg(errp, "L1 table is too small");
1392 if (s->l1_size > 0) {
1393 s->l1_table = qemu_try_blockalign(bs->file->bs,
1394 ROUND_UP(s->l1_size * sizeof(uint64_t), 512));
1395 if (s->l1_table == NULL) {
1396 error_setg(errp, "Could not allocate L1 table");
1400 ret = bdrv_pread(bs->file, s->l1_table_offset, s->l1_table,
1401 s->l1_size * sizeof(uint64_t));
1403 error_setg_errno(errp, -ret, "Could not read L1 table");
1406 for(i = 0;i < s->l1_size; i++) {
1407 be64_to_cpus(&s->l1_table[i]);
1411 /* Parse driver-specific options */
1412 ret = qcow2_update_options(bs, options, flags, errp);
1417 s->cluster_cache_offset = -1;
1420 ret = qcow2_refcount_init(bs);
1422 error_setg_errno(errp, -ret, "Could not initialize refcount handling");
1426 QLIST_INIT(&s->cluster_allocs);
1427 QTAILQ_INIT(&s->discards);
1429 /* read qcow2 extensions */
1430 if (qcow2_read_extensions(bs, header.header_length, ext_end, NULL,
1431 flags, &update_header, &local_err)) {
1432 error_propagate(errp, local_err);
1437 /* qcow2_read_extension may have set up the crypto context
1438 * if the crypt method needs a header region, some methods
1439 * don't need header extensions, so must check here
1441 if (s->crypt_method_header && !s->crypto) {
1442 if (s->crypt_method_header == QCOW_CRYPT_AES) {
1443 unsigned int cflags = 0;
1444 if (flags & BDRV_O_NO_IO) {
1445 cflags |= QCRYPTO_BLOCK_OPEN_NO_IO;
1447 s->crypto = qcrypto_block_open(s->crypto_opts, "encrypt.",
1448 NULL, NULL, cflags, errp);
1453 } else if (!(flags & BDRV_O_NO_IO)) {
1454 error_setg(errp, "Missing CRYPTO header for crypt method %d",
1455 s->crypt_method_header);
1461 /* read the backing file name */
1462 if (header.backing_file_offset != 0) {
1463 len = header.backing_file_size;
1464 if (len > MIN(1023, s->cluster_size - header.backing_file_offset) ||
1465 len >= sizeof(bs->backing_file)) {
1466 error_setg(errp, "Backing file name too long");
1470 ret = bdrv_pread(bs->file, header.backing_file_offset,
1471 bs->backing_file, len);
1473 error_setg_errno(errp, -ret, "Could not read backing file name");
1476 bs->backing_file[len] = '\0';
1477 s->image_backing_file = g_strdup(bs->backing_file);
1480 /* Internal snapshots */
1481 s->snapshots_offset = header.snapshots_offset;
1482 s->nb_snapshots = header.nb_snapshots;
1484 ret = qcow2_read_snapshots(bs);
1486 error_setg_errno(errp, -ret, "Could not read snapshots");
1490 /* Clear unknown autoclear feature bits */
1491 update_header |= s->autoclear_features & ~QCOW2_AUTOCLEAR_MASK;
1493 update_header && !bs->read_only && !(flags & BDRV_O_INACTIVE);
1494 if (update_header) {
1495 s->autoclear_features &= QCOW2_AUTOCLEAR_MASK;
1498 if (s->dirty_bitmaps_loaded) {
1499 /* It's some kind of reopen. There are no known cases where we need to
1500 * reload bitmaps in such a situation, so it's safer to skip them.
1502 * Moreover, if we have some readonly bitmaps and we are reopening for
1503 * rw we should reopen bitmaps correspondingly.
1505 if (bdrv_has_readonly_bitmaps(bs) &&
1506 !bdrv_is_read_only(bs) && !(bdrv_get_flags(bs) & BDRV_O_INACTIVE))
1508 qcow2_reopen_bitmaps_rw_hint(bs, &header_updated, &local_err);
1511 header_updated = qcow2_load_dirty_bitmaps(bs, &local_err);
1512 s->dirty_bitmaps_loaded = true;
1514 update_header = update_header && !header_updated;
1515 if (local_err != NULL) {
1516 error_propagate(errp, local_err);
1521 if (update_header) {
1522 ret = qcow2_update_header(bs);
1524 error_setg_errno(errp, -ret, "Could not update qcow2 header");
1529 bs->supported_zero_flags = header.version >= 3 ? BDRV_REQ_MAY_UNMAP : 0;
1531 /* Repair image if dirty */
1532 if (!(flags & (BDRV_O_CHECK | BDRV_O_INACTIVE)) && !bs->read_only &&
1533 (s->incompatible_features & QCOW2_INCOMPAT_DIRTY)) {
1534 BdrvCheckResult result = {0};
1536 ret = qcow2_co_check_locked(bs, &result,
1537 BDRV_FIX_ERRORS | BDRV_FIX_LEAKS);
1538 if (ret < 0 || result.check_errors) {
1542 error_setg_errno(errp, -ret, "Could not repair dirty image");
1549 BdrvCheckResult result = {0};
1550 qcow2_check_refcounts(bs, &result, 0);
1554 qemu_co_queue_init(&s->compress_wait_queue);
1559 g_free(s->unknown_header_fields);
1560 cleanup_unknown_header_ext(bs);
1561 qcow2_free_snapshots(bs);
1562 qcow2_refcount_close(bs);
1563 qemu_vfree(s->l1_table);
1564 /* else pre-write overlap checks in cache_destroy may crash */
1566 cache_clean_timer_del(bs);
1567 if (s->l2_table_cache) {
1568 qcow2_cache_destroy(s->l2_table_cache);
1570 if (s->refcount_block_cache) {
1571 qcow2_cache_destroy(s->refcount_block_cache);
1573 qcrypto_block_free(s->crypto);
1574 qapi_free_QCryptoBlockOpenOptions(s->crypto_opts);
1578 typedef struct QCow2OpenCo {
1579 BlockDriverState *bs;
1586 static void coroutine_fn qcow2_open_entry(void *opaque)
1588 QCow2OpenCo *qoc = opaque;
1589 BDRVQcow2State *s = qoc->bs->opaque;
1591 qemu_co_mutex_lock(&s->lock);
1592 qoc->ret = qcow2_do_open(qoc->bs, qoc->options, qoc->flags, qoc->errp);
1593 qemu_co_mutex_unlock(&s->lock);
1596 static int qcow2_open(BlockDriverState *bs, QDict *options, int flags,
1599 BDRVQcow2State *s = bs->opaque;
1608 bs->file = bdrv_open_child(NULL, options, "file", bs, &child_file,
1614 /* Initialise locks */
1615 qemu_co_mutex_init(&s->lock);
1617 if (qemu_in_coroutine()) {
1618 /* From bdrv_co_create. */
1619 qcow2_open_entry(&qoc);
1621 qemu_coroutine_enter(qemu_coroutine_create(qcow2_open_entry, &qoc));
1622 BDRV_POLL_WHILE(bs, qoc.ret == -EINPROGRESS);
1627 static void qcow2_refresh_limits(BlockDriverState *bs, Error **errp)
1629 BDRVQcow2State *s = bs->opaque;
1631 if (bs->encrypted) {
1632 /* Encryption works on a sector granularity */
1633 bs->bl.request_alignment = BDRV_SECTOR_SIZE;
1635 bs->bl.pwrite_zeroes_alignment = s->cluster_size;
1636 bs->bl.pdiscard_alignment = s->cluster_size;
1639 static int qcow2_reopen_prepare(BDRVReopenState *state,
1640 BlockReopenQueue *queue, Error **errp)
1642 Qcow2ReopenState *r;
1645 r = g_new0(Qcow2ReopenState, 1);
1648 ret = qcow2_update_options_prepare(state->bs, r, state->options,
1649 state->flags, errp);
1654 /* We need to write out any unwritten data if we reopen read-only. */
1655 if ((state->flags & BDRV_O_RDWR) == 0) {
1656 ret = qcow2_reopen_bitmaps_ro(state->bs, errp);
1661 ret = bdrv_flush(state->bs);
1666 ret = qcow2_mark_clean(state->bs);
1675 qcow2_update_options_abort(state->bs, r);
1680 static void qcow2_reopen_commit(BDRVReopenState *state)
1682 qcow2_update_options_commit(state->bs, state->opaque);
1683 g_free(state->opaque);
1686 static void qcow2_reopen_abort(BDRVReopenState *state)
1688 qcow2_update_options_abort(state->bs, state->opaque);
1689 g_free(state->opaque);
1692 static void qcow2_join_options(QDict *options, QDict *old_options)
1694 bool has_new_overlap_template =
1695 qdict_haskey(options, QCOW2_OPT_OVERLAP) ||
1696 qdict_haskey(options, QCOW2_OPT_OVERLAP_TEMPLATE);
1697 bool has_new_total_cache_size =
1698 qdict_haskey(options, QCOW2_OPT_CACHE_SIZE);
1699 bool has_all_cache_options;
1701 /* New overlap template overrides all old overlap options */
1702 if (has_new_overlap_template) {
1703 qdict_del(old_options, QCOW2_OPT_OVERLAP);
1704 qdict_del(old_options, QCOW2_OPT_OVERLAP_TEMPLATE);
1705 qdict_del(old_options, QCOW2_OPT_OVERLAP_MAIN_HEADER);
1706 qdict_del(old_options, QCOW2_OPT_OVERLAP_ACTIVE_L1);
1707 qdict_del(old_options, QCOW2_OPT_OVERLAP_ACTIVE_L2);
1708 qdict_del(old_options, QCOW2_OPT_OVERLAP_REFCOUNT_TABLE);
1709 qdict_del(old_options, QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK);
1710 qdict_del(old_options, QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE);
1711 qdict_del(old_options, QCOW2_OPT_OVERLAP_INACTIVE_L1);
1712 qdict_del(old_options, QCOW2_OPT_OVERLAP_INACTIVE_L2);
1715 /* New total cache size overrides all old options */
1716 if (qdict_haskey(options, QCOW2_OPT_CACHE_SIZE)) {
1717 qdict_del(old_options, QCOW2_OPT_L2_CACHE_SIZE);
1718 qdict_del(old_options, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
1721 qdict_join(options, old_options, false);
1724 * If after merging all cache size options are set, an old total size is
1725 * overwritten. Do keep all options, however, if all three are new. The
1726 * resulting error message is what we want to happen.
1728 has_all_cache_options =
1729 qdict_haskey(options, QCOW2_OPT_CACHE_SIZE) ||
1730 qdict_haskey(options, QCOW2_OPT_L2_CACHE_SIZE) ||
1731 qdict_haskey(options, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
1733 if (has_all_cache_options && !has_new_total_cache_size) {
1734 qdict_del(options, QCOW2_OPT_CACHE_SIZE);
1738 static int coroutine_fn qcow2_co_block_status(BlockDriverState *bs,
1740 int64_t offset, int64_t count,
1741 int64_t *pnum, int64_t *map,
1742 BlockDriverState **file)
1744 BDRVQcow2State *s = bs->opaque;
1745 uint64_t cluster_offset;
1746 int index_in_cluster, ret;
1750 bytes = MIN(INT_MAX, count);
1751 qemu_co_mutex_lock(&s->lock);
1752 ret = qcow2_get_cluster_offset(bs, offset, &bytes, &cluster_offset);
1753 qemu_co_mutex_unlock(&s->lock);
1760 if (cluster_offset != 0 && ret != QCOW2_CLUSTER_COMPRESSED &&
1762 index_in_cluster = offset & (s->cluster_size - 1);
1763 *map = cluster_offset | index_in_cluster;
1764 *file = bs->file->bs;
1765 status |= BDRV_BLOCK_OFFSET_VALID;
1767 if (ret == QCOW2_CLUSTER_ZERO_PLAIN || ret == QCOW2_CLUSTER_ZERO_ALLOC) {
1768 status |= BDRV_BLOCK_ZERO;
1769 } else if (ret != QCOW2_CLUSTER_UNALLOCATED) {
1770 status |= BDRV_BLOCK_DATA;
1775 static coroutine_fn int qcow2_handle_l2meta(BlockDriverState *bs,
1776 QCowL2Meta **pl2meta,
1780 QCowL2Meta *l2meta = *pl2meta;
1782 while (l2meta != NULL) {
1786 ret = qcow2_alloc_cluster_link_l2(bs, l2meta);
1791 qcow2_alloc_cluster_abort(bs, l2meta);
1794 /* Take the request off the list of running requests */
1795 if (l2meta->nb_clusters != 0) {
1796 QLIST_REMOVE(l2meta, next_in_flight);
1799 qemu_co_queue_restart_all(&l2meta->dependent_requests);
1801 next = l2meta->next;
1810 static coroutine_fn int qcow2_co_preadv(BlockDriverState *bs, uint64_t offset,
1811 uint64_t bytes, QEMUIOVector *qiov,
1814 BDRVQcow2State *s = bs->opaque;
1815 int offset_in_cluster;
1817 unsigned int cur_bytes; /* number of bytes in current iteration */
1818 uint64_t cluster_offset = 0;
1819 uint64_t bytes_done = 0;
1820 QEMUIOVector hd_qiov;
1821 uint8_t *cluster_data = NULL;
1823 qemu_iovec_init(&hd_qiov, qiov->niov);
1825 qemu_co_mutex_lock(&s->lock);
1827 while (bytes != 0) {
1829 /* prepare next request */
1830 cur_bytes = MIN(bytes, INT_MAX);
1832 cur_bytes = MIN(cur_bytes,
1833 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
1836 ret = qcow2_get_cluster_offset(bs, offset, &cur_bytes, &cluster_offset);
1841 offset_in_cluster = offset_into_cluster(s, offset);
1843 qemu_iovec_reset(&hd_qiov);
1844 qemu_iovec_concat(&hd_qiov, qiov, bytes_done, cur_bytes);
1847 case QCOW2_CLUSTER_UNALLOCATED:
1850 BLKDBG_EVENT(bs->file, BLKDBG_READ_BACKING_AIO);
1851 qemu_co_mutex_unlock(&s->lock);
1852 ret = bdrv_co_preadv(bs->backing, offset, cur_bytes,
1854 qemu_co_mutex_lock(&s->lock);
1859 /* Note: in this case, no need to wait */
1860 qemu_iovec_memset(&hd_qiov, 0, 0, cur_bytes);
1864 case QCOW2_CLUSTER_ZERO_PLAIN:
1865 case QCOW2_CLUSTER_ZERO_ALLOC:
1866 qemu_iovec_memset(&hd_qiov, 0, 0, cur_bytes);
1869 case QCOW2_CLUSTER_COMPRESSED:
1870 /* add AIO support for compressed blocks ? */
1871 ret = qcow2_decompress_cluster(bs, cluster_offset);
1876 qemu_iovec_from_buf(&hd_qiov, 0,
1877 s->cluster_cache + offset_in_cluster,
1881 case QCOW2_CLUSTER_NORMAL:
1882 if ((cluster_offset & 511) != 0) {
1887 if (bs->encrypted) {
1891 * For encrypted images, read everything into a temporary
1892 * contiguous buffer on which the AES functions can work.
1894 if (!cluster_data) {
1896 qemu_try_blockalign(bs->file->bs,
1897 QCOW_MAX_CRYPT_CLUSTERS
1899 if (cluster_data == NULL) {
1905 assert(cur_bytes <= QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
1906 qemu_iovec_reset(&hd_qiov);
1907 qemu_iovec_add(&hd_qiov, cluster_data, cur_bytes);
1910 BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);
1911 qemu_co_mutex_unlock(&s->lock);
1912 ret = bdrv_co_preadv(bs->file,
1913 cluster_offset + offset_in_cluster,
1914 cur_bytes, &hd_qiov, 0);
1915 qemu_co_mutex_lock(&s->lock);
1919 if (bs->encrypted) {
1921 assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);
1922 assert((cur_bytes & (BDRV_SECTOR_SIZE - 1)) == 0);
1923 if (qcrypto_block_decrypt(s->crypto,
1924 (s->crypt_physical_offset ?
1925 cluster_offset + offset_in_cluster :
1933 qemu_iovec_from_buf(qiov, bytes_done, cluster_data, cur_bytes);
1938 g_assert_not_reached();
1944 offset += cur_bytes;
1945 bytes_done += cur_bytes;
1950 qemu_co_mutex_unlock(&s->lock);
1952 qemu_iovec_destroy(&hd_qiov);
1953 qemu_vfree(cluster_data);
1958 /* Check if it's possible to merge a write request with the writing of
1959 * the data from the COW regions */
1960 static bool merge_cow(uint64_t offset, unsigned bytes,
1961 QEMUIOVector *hd_qiov, QCowL2Meta *l2meta)
1965 for (m = l2meta; m != NULL; m = m->next) {
1966 /* If both COW regions are empty then there's nothing to merge */
1967 if (m->cow_start.nb_bytes == 0 && m->cow_end.nb_bytes == 0) {
1971 /* The data (middle) region must be immediately after the
1973 if (l2meta_cow_start(m) + m->cow_start.nb_bytes != offset) {
1977 /* The end region must be immediately after the data (middle)
1979 if (m->offset + m->cow_end.offset != offset + bytes) {
1983 /* Make sure that adding both COW regions to the QEMUIOVector
1984 * does not exceed IOV_MAX */
1985 if (hd_qiov->niov > IOV_MAX - 2) {
1989 m->data_qiov = hd_qiov;
1996 static coroutine_fn int qcow2_co_pwritev(BlockDriverState *bs, uint64_t offset,
1997 uint64_t bytes, QEMUIOVector *qiov,
2000 BDRVQcow2State *s = bs->opaque;
2001 int offset_in_cluster;
2003 unsigned int cur_bytes; /* number of sectors in current iteration */
2004 uint64_t cluster_offset;
2005 QEMUIOVector hd_qiov;
2006 uint64_t bytes_done = 0;
2007 uint8_t *cluster_data = NULL;
2008 QCowL2Meta *l2meta = NULL;
2010 trace_qcow2_writev_start_req(qemu_coroutine_self(), offset, bytes);
2012 qemu_iovec_init(&hd_qiov, qiov->niov);
2014 s->cluster_cache_offset = -1; /* disable compressed cache */
2016 qemu_co_mutex_lock(&s->lock);
2018 while (bytes != 0) {
2022 trace_qcow2_writev_start_part(qemu_coroutine_self());
2023 offset_in_cluster = offset_into_cluster(s, offset);
2024 cur_bytes = MIN(bytes, INT_MAX);
2025 if (bs->encrypted) {
2026 cur_bytes = MIN(cur_bytes,
2027 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size
2028 - offset_in_cluster);
2031 ret = qcow2_alloc_cluster_offset(bs, offset, &cur_bytes,
2032 &cluster_offset, &l2meta);
2037 assert((cluster_offset & 511) == 0);
2039 qemu_iovec_reset(&hd_qiov);
2040 qemu_iovec_concat(&hd_qiov, qiov, bytes_done, cur_bytes);
2042 if (bs->encrypted) {
2044 if (!cluster_data) {
2045 cluster_data = qemu_try_blockalign(bs->file->bs,
2046 QCOW_MAX_CRYPT_CLUSTERS
2048 if (cluster_data == NULL) {
2054 assert(hd_qiov.size <=
2055 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
2056 qemu_iovec_to_buf(&hd_qiov, 0, cluster_data, hd_qiov.size);
2058 if (qcrypto_block_encrypt(s->crypto,
2059 (s->crypt_physical_offset ?
2060 cluster_offset + offset_in_cluster :
2063 cur_bytes, NULL) < 0) {
2068 qemu_iovec_reset(&hd_qiov);
2069 qemu_iovec_add(&hd_qiov, cluster_data, cur_bytes);
2072 ret = qcow2_pre_write_overlap_check(bs, 0,
2073 cluster_offset + offset_in_cluster, cur_bytes);
2078 /* If we need to do COW, check if it's possible to merge the
2079 * writing of the guest data together with that of the COW regions.
2080 * If it's not possible (or not necessary) then write the
2081 * guest data now. */
2082 if (!merge_cow(offset, cur_bytes, &hd_qiov, l2meta)) {
2083 qemu_co_mutex_unlock(&s->lock);
2084 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO);
2085 trace_qcow2_writev_data(qemu_coroutine_self(),
2086 cluster_offset + offset_in_cluster);
2087 ret = bdrv_co_pwritev(bs->file,
2088 cluster_offset + offset_in_cluster,
2089 cur_bytes, &hd_qiov, 0);
2090 qemu_co_mutex_lock(&s->lock);
2096 ret = qcow2_handle_l2meta(bs, &l2meta, true);
2102 offset += cur_bytes;
2103 bytes_done += cur_bytes;
2104 trace_qcow2_writev_done_part(qemu_coroutine_self(), cur_bytes);
2109 qcow2_handle_l2meta(bs, &l2meta, false);
2111 qemu_co_mutex_unlock(&s->lock);
2113 qemu_iovec_destroy(&hd_qiov);
2114 qemu_vfree(cluster_data);
2115 trace_qcow2_writev_done_req(qemu_coroutine_self(), ret);
2120 static int qcow2_inactivate(BlockDriverState *bs)
2122 BDRVQcow2State *s = bs->opaque;
2123 int ret, result = 0;
2124 Error *local_err = NULL;
2126 qcow2_store_persistent_dirty_bitmaps(bs, &local_err);
2127 if (local_err != NULL) {
2129 error_report_err(local_err);
2130 error_report("Persistent bitmaps are lost for node '%s'",
2131 bdrv_get_device_or_node_name(bs));
2134 ret = qcow2_cache_flush(bs, s->l2_table_cache);
2137 error_report("Failed to flush the L2 table cache: %s",
2141 ret = qcow2_cache_flush(bs, s->refcount_block_cache);
2144 error_report("Failed to flush the refcount block cache: %s",
2149 qcow2_mark_clean(bs);
2155 static void qcow2_close(BlockDriverState *bs)
2157 BDRVQcow2State *s = bs->opaque;
2158 qemu_vfree(s->l1_table);
2159 /* else pre-write overlap checks in cache_destroy may crash */
2162 if (!(s->flags & BDRV_O_INACTIVE)) {
2163 qcow2_inactivate(bs);
2166 cache_clean_timer_del(bs);
2167 qcow2_cache_destroy(s->l2_table_cache);
2168 qcow2_cache_destroy(s->refcount_block_cache);
2170 qcrypto_block_free(s->crypto);
2173 g_free(s->unknown_header_fields);
2174 cleanup_unknown_header_ext(bs);
2176 g_free(s->image_backing_file);
2177 g_free(s->image_backing_format);
2179 g_free(s->cluster_cache);
2180 qemu_vfree(s->cluster_data);
2181 qcow2_refcount_close(bs);
2182 qcow2_free_snapshots(bs);
2185 static void coroutine_fn qcow2_co_invalidate_cache(BlockDriverState *bs,
2188 BDRVQcow2State *s = bs->opaque;
2189 int flags = s->flags;
2190 QCryptoBlock *crypto = NULL;
2192 Error *local_err = NULL;
2196 * Backing files are read-only which makes all of their metadata immutable,
2197 * that means we don't have to worry about reopening them here.
2205 memset(s, 0, sizeof(BDRVQcow2State));
2206 options = qdict_clone_shallow(bs->options);
2208 flags &= ~BDRV_O_INACTIVE;
2209 qemu_co_mutex_lock(&s->lock);
2210 ret = qcow2_do_open(bs, options, flags, &local_err);
2211 qemu_co_mutex_unlock(&s->lock);
2212 qobject_unref(options);
2214 error_propagate(errp, local_err);
2215 error_prepend(errp, "Could not reopen qcow2 layer: ");
2218 } else if (ret < 0) {
2219 error_setg_errno(errp, -ret, "Could not reopen qcow2 layer");
2227 static size_t header_ext_add(char *buf, uint32_t magic, const void *s,
2228 size_t len, size_t buflen)
2230 QCowExtension *ext_backing_fmt = (QCowExtension*) buf;
2231 size_t ext_len = sizeof(QCowExtension) + ((len + 7) & ~7);
2233 if (buflen < ext_len) {
2237 *ext_backing_fmt = (QCowExtension) {
2238 .magic = cpu_to_be32(magic),
2239 .len = cpu_to_be32(len),
2243 memcpy(buf + sizeof(QCowExtension), s, len);
2250 * Updates the qcow2 header, including the variable length parts of it, i.e.
2251 * the backing file name and all extensions. qcow2 was not designed to allow
2252 * such changes, so if we run out of space (we can only use the first cluster)
2253 * this function may fail.
2255 * Returns 0 on success, -errno in error cases.
2257 int qcow2_update_header(BlockDriverState *bs)
2259 BDRVQcow2State *s = bs->opaque;
2262 size_t buflen = s->cluster_size;
2264 uint64_t total_size;
2265 uint32_t refcount_table_clusters;
2266 size_t header_length;
2267 Qcow2UnknownHeaderExtension *uext;
2269 buf = qemu_blockalign(bs, buflen);
2271 /* Header structure */
2272 header = (QCowHeader*) buf;
2274 if (buflen < sizeof(*header)) {
2279 header_length = sizeof(*header) + s->unknown_header_fields_size;
2280 total_size = bs->total_sectors * BDRV_SECTOR_SIZE;
2281 refcount_table_clusters = s->refcount_table_size >> (s->cluster_bits - 3);
2283 *header = (QCowHeader) {
2284 /* Version 2 fields */
2285 .magic = cpu_to_be32(QCOW_MAGIC),
2286 .version = cpu_to_be32(s->qcow_version),
2287 .backing_file_offset = 0,
2288 .backing_file_size = 0,
2289 .cluster_bits = cpu_to_be32(s->cluster_bits),
2290 .size = cpu_to_be64(total_size),
2291 .crypt_method = cpu_to_be32(s->crypt_method_header),
2292 .l1_size = cpu_to_be32(s->l1_size),
2293 .l1_table_offset = cpu_to_be64(s->l1_table_offset),
2294 .refcount_table_offset = cpu_to_be64(s->refcount_table_offset),
2295 .refcount_table_clusters = cpu_to_be32(refcount_table_clusters),
2296 .nb_snapshots = cpu_to_be32(s->nb_snapshots),
2297 .snapshots_offset = cpu_to_be64(s->snapshots_offset),
2299 /* Version 3 fields */
2300 .incompatible_features = cpu_to_be64(s->incompatible_features),
2301 .compatible_features = cpu_to_be64(s->compatible_features),
2302 .autoclear_features = cpu_to_be64(s->autoclear_features),
2303 .refcount_order = cpu_to_be32(s->refcount_order),
2304 .header_length = cpu_to_be32(header_length),
2307 /* For older versions, write a shorter header */
2308 switch (s->qcow_version) {
2310 ret = offsetof(QCowHeader, incompatible_features);
2313 ret = sizeof(*header);
2322 memset(buf, 0, buflen);
2324 /* Preserve any unknown field in the header */
2325 if (s->unknown_header_fields_size) {
2326 if (buflen < s->unknown_header_fields_size) {
2331 memcpy(buf, s->unknown_header_fields, s->unknown_header_fields_size);
2332 buf += s->unknown_header_fields_size;
2333 buflen -= s->unknown_header_fields_size;
2336 /* Backing file format header extension */
2337 if (s->image_backing_format) {
2338 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BACKING_FORMAT,
2339 s->image_backing_format,
2340 strlen(s->image_backing_format),
2350 /* Full disk encryption header pointer extension */
2351 if (s->crypto_header.offset != 0) {
2352 cpu_to_be64s(&s->crypto_header.offset);
2353 cpu_to_be64s(&s->crypto_header.length);
2354 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_CRYPTO_HEADER,
2355 &s->crypto_header, sizeof(s->crypto_header),
2357 be64_to_cpus(&s->crypto_header.offset);
2358 be64_to_cpus(&s->crypto_header.length);
2367 if (s->qcow_version >= 3) {
2368 Qcow2Feature features[] = {
2370 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
2371 .bit = QCOW2_INCOMPAT_DIRTY_BITNR,
2372 .name = "dirty bit",
2375 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
2376 .bit = QCOW2_INCOMPAT_CORRUPT_BITNR,
2377 .name = "corrupt bit",
2380 .type = QCOW2_FEAT_TYPE_COMPATIBLE,
2381 .bit = QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR,
2382 .name = "lazy refcounts",
2386 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_FEATURE_TABLE,
2387 features, sizeof(features), buflen);
2395 /* Bitmap extension */
2396 if (s->nb_bitmaps > 0) {
2397 Qcow2BitmapHeaderExt bitmaps_header = {
2398 .nb_bitmaps = cpu_to_be32(s->nb_bitmaps),
2399 .bitmap_directory_size =
2400 cpu_to_be64(s->bitmap_directory_size),
2401 .bitmap_directory_offset =
2402 cpu_to_be64(s->bitmap_directory_offset)
2404 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BITMAPS,
2405 &bitmaps_header, sizeof(bitmaps_header),
2414 /* Keep unknown header extensions */
2415 QLIST_FOREACH(uext, &s->unknown_header_ext, next) {
2416 ret = header_ext_add(buf, uext->magic, uext->data, uext->len, buflen);
2425 /* End of header extensions */
2426 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_END, NULL, 0, buflen);
2434 /* Backing file name */
2435 if (s->image_backing_file) {
2436 size_t backing_file_len = strlen(s->image_backing_file);
2438 if (buflen < backing_file_len) {
2443 /* Using strncpy is ok here, since buf is not NUL-terminated. */
2444 strncpy(buf, s->image_backing_file, buflen);
2446 header->backing_file_offset = cpu_to_be64(buf - ((char*) header));
2447 header->backing_file_size = cpu_to_be32(backing_file_len);
2450 /* Write the new header */
2451 ret = bdrv_pwrite(bs->file, 0, header, s->cluster_size);
2462 static int qcow2_change_backing_file(BlockDriverState *bs,
2463 const char *backing_file, const char *backing_fmt)
2465 BDRVQcow2State *s = bs->opaque;
2467 if (backing_file && strlen(backing_file) > 1023) {
2471 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
2472 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
2474 g_free(s->image_backing_file);
2475 g_free(s->image_backing_format);
2477 s->image_backing_file = backing_file ? g_strdup(bs->backing_file) : NULL;
2478 s->image_backing_format = backing_fmt ? g_strdup(bs->backing_format) : NULL;
2480 return qcow2_update_header(bs);
2483 static int qcow2_crypt_method_from_format(const char *encryptfmt)
2485 if (g_str_equal(encryptfmt, "luks")) {
2486 return QCOW_CRYPT_LUKS;
2487 } else if (g_str_equal(encryptfmt, "aes")) {
2488 return QCOW_CRYPT_AES;
2494 static int qcow2_set_up_encryption(BlockDriverState *bs,
2495 QCryptoBlockCreateOptions *cryptoopts,
2498 BDRVQcow2State *s = bs->opaque;
2499 QCryptoBlock *crypto = NULL;
2502 switch (cryptoopts->format) {
2503 case Q_CRYPTO_BLOCK_FORMAT_LUKS:
2504 fmt = QCOW_CRYPT_LUKS;
2506 case Q_CRYPTO_BLOCK_FORMAT_QCOW:
2507 fmt = QCOW_CRYPT_AES;
2510 error_setg(errp, "Crypto format not supported in qcow2");
2514 s->crypt_method_header = fmt;
2516 crypto = qcrypto_block_create(cryptoopts, "encrypt.",
2517 qcow2_crypto_hdr_init_func,
2518 qcow2_crypto_hdr_write_func,
2524 ret = qcow2_update_header(bs);
2526 error_setg_errno(errp, -ret, "Could not write encryption header");
2532 qcrypto_block_free(crypto);
2537 * Preallocates metadata structures for data clusters between @offset (in the
2538 * guest disk) and @new_length (which is thus generally the new guest disk
2541 * Returns: 0 on success, -errno on failure.
2543 static int coroutine_fn preallocate_co(BlockDriverState *bs, uint64_t offset,
2544 uint64_t new_length)
2547 uint64_t host_offset = 0;
2548 unsigned int cur_bytes;
2552 assert(offset <= new_length);
2553 bytes = new_length - offset;
2556 cur_bytes = MIN(bytes, INT_MAX);
2557 ret = qcow2_alloc_cluster_offset(bs, offset, &cur_bytes,
2558 &host_offset, &meta);
2564 QCowL2Meta *next = meta->next;
2566 ret = qcow2_alloc_cluster_link_l2(bs, meta);
2568 qcow2_free_any_clusters(bs, meta->alloc_offset,
2569 meta->nb_clusters, QCOW2_DISCARD_NEVER);
2573 /* There are no dependent requests, but we need to remove our
2574 * request from the list of in-flight requests */
2575 QLIST_REMOVE(meta, next_in_flight);
2581 /* TODO Preallocate data if requested */
2584 offset += cur_bytes;
2588 * It is expected that the image file is large enough to actually contain
2589 * all of the allocated clusters (otherwise we get failing reads after
2590 * EOF). Extend the image to the last allocated sector.
2592 if (host_offset != 0) {
2594 ret = bdrv_pwrite(bs->file, (host_offset + cur_bytes) - 1,
2604 /* qcow2_refcount_metadata_size:
2605 * @clusters: number of clusters to refcount (including data and L1/L2 tables)
2606 * @cluster_size: size of a cluster, in bytes
2607 * @refcount_order: refcount bits power-of-2 exponent
2608 * @generous_increase: allow for the refcount table to be 1.5x as large as it
2611 * Returns: Number of bytes required for refcount blocks and table metadata.
2613 int64_t qcow2_refcount_metadata_size(int64_t clusters, size_t cluster_size,
2614 int refcount_order, bool generous_increase,
2615 uint64_t *refblock_count)
2618 * Every host cluster is reference-counted, including metadata (even
2619 * refcount metadata is recursively included).
2621 * An accurate formula for the size of refcount metadata size is difficult
2622 * to derive. An easier method of calculation is finding the fixed point
2623 * where no further refcount blocks or table clusters are required to
2624 * reference count every cluster.
2626 int64_t blocks_per_table_cluster = cluster_size / sizeof(uint64_t);
2627 int64_t refcounts_per_block = cluster_size * 8 / (1 << refcount_order);
2628 int64_t table = 0; /* number of refcount table clusters */
2629 int64_t blocks = 0; /* number of refcount block clusters */
2635 blocks = DIV_ROUND_UP(clusters + table + blocks, refcounts_per_block);
2636 table = DIV_ROUND_UP(blocks, blocks_per_table_cluster);
2637 n = clusters + blocks + table;
2639 if (n == last && generous_increase) {
2640 clusters += DIV_ROUND_UP(table, 2);
2641 n = 0; /* force another loop */
2642 generous_increase = false;
2644 } while (n != last);
2646 if (refblock_count) {
2647 *refblock_count = blocks;
2650 return (blocks + table) * cluster_size;
2654 * qcow2_calc_prealloc_size:
2655 * @total_size: virtual disk size in bytes
2656 * @cluster_size: cluster size in bytes
2657 * @refcount_order: refcount bits power-of-2 exponent
2659 * Returns: Total number of bytes required for the fully allocated image
2660 * (including metadata).
2662 static int64_t qcow2_calc_prealloc_size(int64_t total_size,
2663 size_t cluster_size,
2666 int64_t meta_size = 0;
2667 uint64_t nl1e, nl2e;
2668 int64_t aligned_total_size = ROUND_UP(total_size, cluster_size);
2670 /* header: 1 cluster */
2671 meta_size += cluster_size;
2673 /* total size of L2 tables */
2674 nl2e = aligned_total_size / cluster_size;
2675 nl2e = ROUND_UP(nl2e, cluster_size / sizeof(uint64_t));
2676 meta_size += nl2e * sizeof(uint64_t);
2678 /* total size of L1 tables */
2679 nl1e = nl2e * sizeof(uint64_t) / cluster_size;
2680 nl1e = ROUND_UP(nl1e, cluster_size / sizeof(uint64_t));
2681 meta_size += nl1e * sizeof(uint64_t);
2683 /* total size of refcount table and blocks */
2684 meta_size += qcow2_refcount_metadata_size(
2685 (meta_size + aligned_total_size) / cluster_size,
2686 cluster_size, refcount_order, false, NULL);
2688 return meta_size + aligned_total_size;
2691 static bool validate_cluster_size(size_t cluster_size, Error **errp)
2693 int cluster_bits = ctz32(cluster_size);
2694 if (cluster_bits < MIN_CLUSTER_BITS || cluster_bits > MAX_CLUSTER_BITS ||
2695 (1 << cluster_bits) != cluster_size)
2697 error_setg(errp, "Cluster size must be a power of two between %d and "
2698 "%dk", 1 << MIN_CLUSTER_BITS, 1 << (MAX_CLUSTER_BITS - 10));
2704 static size_t qcow2_opt_get_cluster_size_del(QemuOpts *opts, Error **errp)
2706 size_t cluster_size;
2708 cluster_size = qemu_opt_get_size_del(opts, BLOCK_OPT_CLUSTER_SIZE,
2709 DEFAULT_CLUSTER_SIZE);
2710 if (!validate_cluster_size(cluster_size, errp)) {
2713 return cluster_size;
2716 static int qcow2_opt_get_version_del(QemuOpts *opts, Error **errp)
2721 buf = qemu_opt_get_del(opts, BLOCK_OPT_COMPAT_LEVEL);
2723 ret = 3; /* default */
2724 } else if (!strcmp(buf, "0.10")) {
2726 } else if (!strcmp(buf, "1.1")) {
2729 error_setg(errp, "Invalid compatibility level: '%s'", buf);
2736 static uint64_t qcow2_opt_get_refcount_bits_del(QemuOpts *opts, int version,
2739 uint64_t refcount_bits;
2741 refcount_bits = qemu_opt_get_number_del(opts, BLOCK_OPT_REFCOUNT_BITS, 16);
2742 if (refcount_bits > 64 || !is_power_of_2(refcount_bits)) {
2743 error_setg(errp, "Refcount width must be a power of two and may not "
2748 if (version < 3 && refcount_bits != 16) {
2749 error_setg(errp, "Different refcount widths than 16 bits require "
2750 "compatibility level 1.1 or above (use compat=1.1 or "
2755 return refcount_bits;
2758 static int coroutine_fn
2759 qcow2_co_create(BlockdevCreateOptions *create_options, Error **errp)
2761 BlockdevCreateOptionsQcow2 *qcow2_opts;
2765 * Open the image file and write a minimal qcow2 header.
2767 * We keep things simple and start with a zero-sized image. We also
2768 * do without refcount blocks or a L1 table for now. We'll fix the
2769 * inconsistency later.
2771 * We do need a refcount table because growing the refcount table means
2772 * allocating two new refcount blocks - the seconds of which would be at
2773 * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
2774 * size for any qcow2 image.
2776 BlockBackend *blk = NULL;
2777 BlockDriverState *bs = NULL;
2779 size_t cluster_size;
2782 uint64_t* refcount_table;
2783 Error *local_err = NULL;
2786 assert(create_options->driver == BLOCKDEV_DRIVER_QCOW2);
2787 qcow2_opts = &create_options->u.qcow2;
2789 bs = bdrv_open_blockdev_ref(qcow2_opts->file, errp);
2794 /* Validate options and set default values */
2795 if (!QEMU_IS_ALIGNED(qcow2_opts->size, BDRV_SECTOR_SIZE)) {
2796 error_setg(errp, "Image size must be a multiple of 512 bytes");
2801 if (qcow2_opts->has_version) {
2802 switch (qcow2_opts->version) {
2803 case BLOCKDEV_QCOW2_VERSION_V2:
2806 case BLOCKDEV_QCOW2_VERSION_V3:
2810 g_assert_not_reached();
2816 if (qcow2_opts->has_cluster_size) {
2817 cluster_size = qcow2_opts->cluster_size;
2819 cluster_size = DEFAULT_CLUSTER_SIZE;
2822 if (!validate_cluster_size(cluster_size, errp)) {
2827 if (!qcow2_opts->has_preallocation) {
2828 qcow2_opts->preallocation = PREALLOC_MODE_OFF;
2830 if (qcow2_opts->has_backing_file &&
2831 qcow2_opts->preallocation != PREALLOC_MODE_OFF)
2833 error_setg(errp, "Backing file and preallocation cannot be used at "
2838 if (qcow2_opts->has_backing_fmt && !qcow2_opts->has_backing_file) {
2839 error_setg(errp, "Backing format cannot be used without backing file");
2844 if (!qcow2_opts->has_lazy_refcounts) {
2845 qcow2_opts->lazy_refcounts = false;
2847 if (version < 3 && qcow2_opts->lazy_refcounts) {
2848 error_setg(errp, "Lazy refcounts only supported with compatibility "
2849 "level 1.1 and above (use version=v3 or greater)");
2854 if (!qcow2_opts->has_refcount_bits) {
2855 qcow2_opts->refcount_bits = 16;
2857 if (qcow2_opts->refcount_bits > 64 ||
2858 !is_power_of_2(qcow2_opts->refcount_bits))
2860 error_setg(errp, "Refcount width must be a power of two and may not "
2865 if (version < 3 && qcow2_opts->refcount_bits != 16) {
2866 error_setg(errp, "Different refcount widths than 16 bits require "
2867 "compatibility level 1.1 or above (use version=v3 or "
2872 refcount_order = ctz32(qcow2_opts->refcount_bits);
2875 /* Create BlockBackend to write to the image */
2876 blk = blk_new(BLK_PERM_WRITE | BLK_PERM_RESIZE, BLK_PERM_ALL);
2877 ret = blk_insert_bs(blk, bs, errp);
2881 blk_set_allow_write_beyond_eof(blk, true);
2883 /* Clear the protocol layer and preallocate it if necessary */
2884 ret = blk_truncate(blk, 0, PREALLOC_MODE_OFF, errp);
2889 if (qcow2_opts->preallocation == PREALLOC_MODE_FULL ||
2890 qcow2_opts->preallocation == PREALLOC_MODE_FALLOC)
2892 int64_t prealloc_size =
2893 qcow2_calc_prealloc_size(qcow2_opts->size, cluster_size,
2896 ret = blk_truncate(blk, prealloc_size, qcow2_opts->preallocation, errp);
2902 /* Write the header */
2903 QEMU_BUILD_BUG_ON((1 << MIN_CLUSTER_BITS) < sizeof(*header));
2904 header = g_malloc0(cluster_size);
2905 *header = (QCowHeader) {
2906 .magic = cpu_to_be32(QCOW_MAGIC),
2907 .version = cpu_to_be32(version),
2908 .cluster_bits = cpu_to_be32(ctz32(cluster_size)),
2909 .size = cpu_to_be64(0),
2910 .l1_table_offset = cpu_to_be64(0),
2911 .l1_size = cpu_to_be32(0),
2912 .refcount_table_offset = cpu_to_be64(cluster_size),
2913 .refcount_table_clusters = cpu_to_be32(1),
2914 .refcount_order = cpu_to_be32(refcount_order),
2915 .header_length = cpu_to_be32(sizeof(*header)),
2918 /* We'll update this to correct value later */
2919 header->crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
2921 if (qcow2_opts->lazy_refcounts) {
2922 header->compatible_features |=
2923 cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS);
2926 ret = blk_pwrite(blk, 0, header, cluster_size, 0);
2929 error_setg_errno(errp, -ret, "Could not write qcow2 header");
2933 /* Write a refcount table with one refcount block */
2934 refcount_table = g_malloc0(2 * cluster_size);
2935 refcount_table[0] = cpu_to_be64(2 * cluster_size);
2936 ret = blk_pwrite(blk, cluster_size, refcount_table, 2 * cluster_size, 0);
2937 g_free(refcount_table);
2940 error_setg_errno(errp, -ret, "Could not write refcount table");
2948 * And now open the image and make it consistent first (i.e. increase the
2949 * refcount of the cluster that is occupied by the header and the refcount
2952 options = qdict_new();
2953 qdict_put_str(options, "driver", "qcow2");
2954 qdict_put_str(options, "file", bs->node_name);
2955 blk = blk_new_open(NULL, NULL, options,
2956 BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_NO_FLUSH,
2959 error_propagate(errp, local_err);
2964 ret = qcow2_alloc_clusters(blk_bs(blk), 3 * cluster_size);
2966 error_setg_errno(errp, -ret, "Could not allocate clusters for qcow2 "
2967 "header and refcount table");
2970 } else if (ret != 0) {
2971 error_report("Huh, first cluster in empty image is already in use?");
2975 /* Create a full header (including things like feature table) */
2976 ret = qcow2_update_header(blk_bs(blk));
2978 error_setg_errno(errp, -ret, "Could not update qcow2 header");
2982 /* Okay, now that we have a valid image, let's give it the right size */
2983 ret = blk_truncate(blk, qcow2_opts->size, PREALLOC_MODE_OFF, errp);
2985 error_prepend(errp, "Could not resize image: ");
2989 /* Want a backing file? There you go.*/
2990 if (qcow2_opts->has_backing_file) {
2991 const char *backing_format = NULL;
2993 if (qcow2_opts->has_backing_fmt) {
2994 backing_format = BlockdevDriver_str(qcow2_opts->backing_fmt);
2997 ret = bdrv_change_backing_file(blk_bs(blk), qcow2_opts->backing_file,
3000 error_setg_errno(errp, -ret, "Could not assign backing file '%s' "
3001 "with format '%s'", qcow2_opts->backing_file,
3007 /* Want encryption? There you go. */
3008 if (qcow2_opts->has_encrypt) {
3009 ret = qcow2_set_up_encryption(blk_bs(blk), qcow2_opts->encrypt, errp);
3015 /* And if we're supposed to preallocate metadata, do that now */
3016 if (qcow2_opts->preallocation != PREALLOC_MODE_OFF) {
3017 BDRVQcow2State *s = blk_bs(blk)->opaque;
3018 qemu_co_mutex_lock(&s->lock);
3019 ret = preallocate_co(blk_bs(blk), 0, qcow2_opts->size);
3020 qemu_co_mutex_unlock(&s->lock);
3023 error_setg_errno(errp, -ret, "Could not preallocate metadata");
3031 /* Reopen the image without BDRV_O_NO_FLUSH to flush it before returning.
3032 * Using BDRV_O_NO_IO, since encryption is now setup we don't want to
3033 * have to setup decryption context. We're not doing any I/O on the top
3034 * level BlockDriverState, only lower layers, where BDRV_O_NO_IO does
3037 options = qdict_new();
3038 qdict_put_str(options, "driver", "qcow2");
3039 qdict_put_str(options, "file", bs->node_name);
3040 blk = blk_new_open(NULL, NULL, options,
3041 BDRV_O_RDWR | BDRV_O_NO_BACKING | BDRV_O_NO_IO,
3044 error_propagate(errp, local_err);
3056 static int coroutine_fn qcow2_co_create_opts(const char *filename, QemuOpts *opts,
3059 BlockdevCreateOptions *create_options = NULL;
3062 BlockDriverState *bs = NULL;
3063 Error *local_err = NULL;
3067 /* Only the keyval visitor supports the dotted syntax needed for
3068 * encryption, so go through a QDict before getting a QAPI type. Ignore
3069 * options meant for the protocol layer so that the visitor doesn't
3071 qdict = qemu_opts_to_qdict_filtered(opts, NULL, bdrv_qcow2.create_opts,
3074 /* Handle encryption options */
3075 val = qdict_get_try_str(qdict, BLOCK_OPT_ENCRYPT);
3076 if (val && !strcmp(val, "on")) {
3077 qdict_put_str(qdict, BLOCK_OPT_ENCRYPT, "qcow");
3078 } else if (val && !strcmp(val, "off")) {
3079 qdict_del(qdict, BLOCK_OPT_ENCRYPT);
3082 val = qdict_get_try_str(qdict, BLOCK_OPT_ENCRYPT_FORMAT);
3083 if (val && !strcmp(val, "aes")) {
3084 qdict_put_str(qdict, BLOCK_OPT_ENCRYPT_FORMAT, "qcow");
3087 /* Convert compat=0.10/1.1 into compat=v2/v3, to be renamed into
3088 * version=v2/v3 below. */
3089 val = qdict_get_try_str(qdict, BLOCK_OPT_COMPAT_LEVEL);
3090 if (val && !strcmp(val, "0.10")) {
3091 qdict_put_str(qdict, BLOCK_OPT_COMPAT_LEVEL, "v2");
3092 } else if (val && !strcmp(val, "1.1")) {
3093 qdict_put_str(qdict, BLOCK_OPT_COMPAT_LEVEL, "v3");
3096 /* Change legacy command line options into QMP ones */
3097 static const QDictRenames opt_renames[] = {
3098 { BLOCK_OPT_BACKING_FILE, "backing-file" },
3099 { BLOCK_OPT_BACKING_FMT, "backing-fmt" },
3100 { BLOCK_OPT_CLUSTER_SIZE, "cluster-size" },
3101 { BLOCK_OPT_LAZY_REFCOUNTS, "lazy-refcounts" },
3102 { BLOCK_OPT_REFCOUNT_BITS, "refcount-bits" },
3103 { BLOCK_OPT_ENCRYPT, BLOCK_OPT_ENCRYPT_FORMAT },
3104 { BLOCK_OPT_COMPAT_LEVEL, "version" },
3108 if (!qdict_rename_keys(qdict, opt_renames, errp)) {
3113 /* Create and open the file (protocol layer) */
3114 ret = bdrv_create_file(filename, opts, errp);
3119 bs = bdrv_open(filename, NULL, NULL,
3120 BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_PROTOCOL, errp);
3126 /* Set 'driver' and 'node' options */
3127 qdict_put_str(qdict, "driver", "qcow2");
3128 qdict_put_str(qdict, "file", bs->node_name);
3130 /* Now get the QAPI type BlockdevCreateOptions */
3131 v = qobject_input_visitor_new_flat_confused(qdict, errp);
3137 visit_type_BlockdevCreateOptions(v, NULL, &create_options, &local_err);
3141 error_propagate(errp, local_err);
3146 /* Silently round up size */
3147 create_options->u.qcow2.size = ROUND_UP(create_options->u.qcow2.size,
3150 /* Create the qcow2 image (format layer) */
3151 ret = qcow2_co_create(create_options, errp);
3158 qobject_unref(qdict);
3160 qapi_free_BlockdevCreateOptions(create_options);
3165 static bool is_zero(BlockDriverState *bs, int64_t offset, int64_t bytes)
3170 /* Clamp to image length, before checking status of underlying sectors */
3171 if (offset + bytes > bs->total_sectors * BDRV_SECTOR_SIZE) {
3172 bytes = bs->total_sectors * BDRV_SECTOR_SIZE - offset;
3178 res = bdrv_block_status_above(bs, NULL, offset, bytes, &nr, NULL, NULL);
3179 return res >= 0 && (res & BDRV_BLOCK_ZERO) && nr == bytes;
3182 static coroutine_fn int qcow2_co_pwrite_zeroes(BlockDriverState *bs,
3183 int64_t offset, int bytes, BdrvRequestFlags flags)
3186 BDRVQcow2State *s = bs->opaque;
3188 uint32_t head = offset % s->cluster_size;
3189 uint32_t tail = (offset + bytes) % s->cluster_size;
3191 trace_qcow2_pwrite_zeroes_start_req(qemu_coroutine_self(), offset, bytes);
3192 if (offset + bytes == bs->total_sectors * BDRV_SECTOR_SIZE) {
3200 assert(head + bytes <= s->cluster_size);
3202 /* check whether remainder of cluster already reads as zero */
3203 if (!(is_zero(bs, offset - head, head) &&
3204 is_zero(bs, offset + bytes,
3205 tail ? s->cluster_size - tail : 0))) {
3209 qemu_co_mutex_lock(&s->lock);
3210 /* We can have new write after previous check */
3211 offset = QEMU_ALIGN_DOWN(offset, s->cluster_size);
3212 bytes = s->cluster_size;
3213 nr = s->cluster_size;
3214 ret = qcow2_get_cluster_offset(bs, offset, &nr, &off);
3215 if (ret != QCOW2_CLUSTER_UNALLOCATED &&
3216 ret != QCOW2_CLUSTER_ZERO_PLAIN &&
3217 ret != QCOW2_CLUSTER_ZERO_ALLOC) {
3218 qemu_co_mutex_unlock(&s->lock);
3222 qemu_co_mutex_lock(&s->lock);
3225 trace_qcow2_pwrite_zeroes(qemu_coroutine_self(), offset, bytes);
3227 /* Whatever is left can use real zero clusters */
3228 ret = qcow2_cluster_zeroize(bs, offset, bytes, flags);
3229 qemu_co_mutex_unlock(&s->lock);
3234 static coroutine_fn int qcow2_co_pdiscard(BlockDriverState *bs,
3235 int64_t offset, int bytes)
3238 BDRVQcow2State *s = bs->opaque;
3240 if (!QEMU_IS_ALIGNED(offset | bytes, s->cluster_size)) {
3241 assert(bytes < s->cluster_size);
3242 /* Ignore partial clusters, except for the special case of the
3243 * complete partial cluster at the end of an unaligned file */
3244 if (!QEMU_IS_ALIGNED(offset, s->cluster_size) ||
3245 offset + bytes != bs->total_sectors * BDRV_SECTOR_SIZE) {
3250 qemu_co_mutex_lock(&s->lock);
3251 ret = qcow2_cluster_discard(bs, offset, bytes, QCOW2_DISCARD_REQUEST,
3253 qemu_co_mutex_unlock(&s->lock);
3257 static int coroutine_fn
3258 qcow2_co_copy_range_from(BlockDriverState *bs,
3259 BdrvChild *src, uint64_t src_offset,
3260 BdrvChild *dst, uint64_t dst_offset,
3261 uint64_t bytes, BdrvRequestFlags read_flags,
3262 BdrvRequestFlags write_flags)
3264 BDRVQcow2State *s = bs->opaque;
3266 unsigned int cur_bytes; /* number of bytes in current iteration */
3267 BdrvChild *child = NULL;
3268 BdrvRequestFlags cur_write_flags;
3270 assert(!bs->encrypted);
3271 qemu_co_mutex_lock(&s->lock);
3273 while (bytes != 0) {
3274 uint64_t copy_offset = 0;
3275 /* prepare next request */
3276 cur_bytes = MIN(bytes, INT_MAX);
3277 cur_write_flags = write_flags;
3279 ret = qcow2_get_cluster_offset(bs, src_offset, &cur_bytes, ©_offset);
3285 case QCOW2_CLUSTER_UNALLOCATED:
3286 if (bs->backing && bs->backing->bs) {
3287 int64_t backing_length = bdrv_getlength(bs->backing->bs);
3288 if (src_offset >= backing_length) {
3289 cur_write_flags |= BDRV_REQ_ZERO_WRITE;
3291 child = bs->backing;
3292 cur_bytes = MIN(cur_bytes, backing_length - src_offset);
3293 copy_offset = src_offset;
3296 cur_write_flags |= BDRV_REQ_ZERO_WRITE;
3300 case QCOW2_CLUSTER_ZERO_PLAIN:
3301 case QCOW2_CLUSTER_ZERO_ALLOC:
3302 cur_write_flags |= BDRV_REQ_ZERO_WRITE;
3305 case QCOW2_CLUSTER_COMPRESSED:
3309 case QCOW2_CLUSTER_NORMAL:
3311 copy_offset += offset_into_cluster(s, src_offset);
3312 if ((copy_offset & 511) != 0) {
3321 qemu_co_mutex_unlock(&s->lock);
3322 ret = bdrv_co_copy_range_from(child,
3325 cur_bytes, read_flags, cur_write_flags);
3326 qemu_co_mutex_lock(&s->lock);
3332 src_offset += cur_bytes;
3333 dst_offset += cur_bytes;
3338 qemu_co_mutex_unlock(&s->lock);
3342 static int coroutine_fn
3343 qcow2_co_copy_range_to(BlockDriverState *bs,
3344 BdrvChild *src, uint64_t src_offset,
3345 BdrvChild *dst, uint64_t dst_offset,
3346 uint64_t bytes, BdrvRequestFlags read_flags,
3347 BdrvRequestFlags write_flags)
3349 BDRVQcow2State *s = bs->opaque;
3350 int offset_in_cluster;
3352 unsigned int cur_bytes; /* number of sectors in current iteration */
3353 uint64_t cluster_offset;
3354 QCowL2Meta *l2meta = NULL;
3356 assert(!bs->encrypted);
3357 s->cluster_cache_offset = -1; /* disable compressed cache */
3359 qemu_co_mutex_lock(&s->lock);
3361 while (bytes != 0) {
3365 offset_in_cluster = offset_into_cluster(s, dst_offset);
3366 cur_bytes = MIN(bytes, INT_MAX);
3369 * If src->bs == dst->bs, we could simply copy by incrementing
3370 * the refcnt, without copying user data.
3371 * Or if src->bs == dst->bs->backing->bs, we could copy by discarding. */
3372 ret = qcow2_alloc_cluster_offset(bs, dst_offset, &cur_bytes,
3373 &cluster_offset, &l2meta);
3378 assert((cluster_offset & 511) == 0);
3380 ret = qcow2_pre_write_overlap_check(bs, 0,
3381 cluster_offset + offset_in_cluster, cur_bytes);
3386 qemu_co_mutex_unlock(&s->lock);
3387 ret = bdrv_co_copy_range_to(src, src_offset,
3389 cluster_offset + offset_in_cluster,
3390 cur_bytes, read_flags, write_flags);
3391 qemu_co_mutex_lock(&s->lock);
3396 ret = qcow2_handle_l2meta(bs, &l2meta, true);
3402 src_offset += cur_bytes;
3403 dst_offset += cur_bytes;
3408 qcow2_handle_l2meta(bs, &l2meta, false);
3410 qemu_co_mutex_unlock(&s->lock);
3412 trace_qcow2_writev_done_req(qemu_coroutine_self(), ret);
3417 static int coroutine_fn qcow2_co_truncate(BlockDriverState *bs, int64_t offset,
3418 PreallocMode prealloc, Error **errp)
3420 BDRVQcow2State *s = bs->opaque;
3421 uint64_t old_length;
3422 int64_t new_l1_size;
3425 if (prealloc != PREALLOC_MODE_OFF && prealloc != PREALLOC_MODE_METADATA &&
3426 prealloc != PREALLOC_MODE_FALLOC && prealloc != PREALLOC_MODE_FULL)
3428 error_setg(errp, "Unsupported preallocation mode '%s'",
3429 PreallocMode_str(prealloc));
3434 error_setg(errp, "The new size must be a multiple of 512");
3438 qemu_co_mutex_lock(&s->lock);
3440 /* cannot proceed if image has snapshots */
3441 if (s->nb_snapshots) {
3442 error_setg(errp, "Can't resize an image which has snapshots");
3447 /* cannot proceed if image has bitmaps */
3448 if (s->nb_bitmaps) {
3449 /* TODO: resize bitmaps in the image */
3450 error_setg(errp, "Can't resize an image which has bitmaps");
3455 old_length = bs->total_sectors * 512;
3456 new_l1_size = size_to_l1(s, offset);
3458 if (offset < old_length) {
3459 int64_t last_cluster, old_file_size;
3460 if (prealloc != PREALLOC_MODE_OFF) {
3462 "Preallocation can't be used for shrinking an image");
3467 ret = qcow2_cluster_discard(bs, ROUND_UP(offset, s->cluster_size),
3468 old_length - ROUND_UP(offset,
3470 QCOW2_DISCARD_ALWAYS, true);
3472 error_setg_errno(errp, -ret, "Failed to discard cropped clusters");
3476 ret = qcow2_shrink_l1_table(bs, new_l1_size);
3478 error_setg_errno(errp, -ret,
3479 "Failed to reduce the number of L2 tables");
3483 ret = qcow2_shrink_reftable(bs);
3485 error_setg_errno(errp, -ret,
3486 "Failed to discard unused refblocks");
3490 old_file_size = bdrv_getlength(bs->file->bs);
3491 if (old_file_size < 0) {
3492 error_setg_errno(errp, -old_file_size,
3493 "Failed to inquire current file length");
3494 ret = old_file_size;
3497 last_cluster = qcow2_get_last_cluster(bs, old_file_size);
3498 if (last_cluster < 0) {
3499 error_setg_errno(errp, -last_cluster,
3500 "Failed to find the last cluster");
3504 if ((last_cluster + 1) * s->cluster_size < old_file_size) {
3505 Error *local_err = NULL;
3507 bdrv_co_truncate(bs->file, (last_cluster + 1) * s->cluster_size,
3508 PREALLOC_MODE_OFF, &local_err);
3510 warn_reportf_err(local_err,
3511 "Failed to truncate the tail of the image: ");
3515 ret = qcow2_grow_l1_table(bs, new_l1_size, true);
3517 error_setg_errno(errp, -ret, "Failed to grow the L1 table");
3523 case PREALLOC_MODE_OFF:
3526 case PREALLOC_MODE_METADATA:
3527 ret = preallocate_co(bs, old_length, offset);
3529 error_setg_errno(errp, -ret, "Preallocation failed");
3534 case PREALLOC_MODE_FALLOC:
3535 case PREALLOC_MODE_FULL:
3537 int64_t allocation_start, host_offset, guest_offset;
3538 int64_t clusters_allocated;
3539 int64_t old_file_size, new_file_size;
3540 uint64_t nb_new_data_clusters, nb_new_l2_tables;
3542 old_file_size = bdrv_getlength(bs->file->bs);
3543 if (old_file_size < 0) {
3544 error_setg_errno(errp, -old_file_size,
3545 "Failed to inquire current file length");
3546 ret = old_file_size;
3549 old_file_size = ROUND_UP(old_file_size, s->cluster_size);
3551 nb_new_data_clusters = DIV_ROUND_UP(offset - old_length,
3554 /* This is an overestimation; we will not actually allocate space for
3555 * these in the file but just make sure the new refcount structures are
3556 * able to cover them so we will not have to allocate new refblocks
3557 * while entering the data blocks in the potentially new L2 tables.
3558 * (We do not actually care where the L2 tables are placed. Maybe they
3559 * are already allocated or they can be placed somewhere before
3560 * @old_file_size. It does not matter because they will be fully
3561 * allocated automatically, so they do not need to be covered by the
3562 * preallocation. All that matters is that we will not have to allocate
3563 * new refcount structures for them.) */
3564 nb_new_l2_tables = DIV_ROUND_UP(nb_new_data_clusters,
3565 s->cluster_size / sizeof(uint64_t));
3566 /* The cluster range may not be aligned to L2 boundaries, so add one L2
3567 * table for a potential head/tail */
3570 allocation_start = qcow2_refcount_area(bs, old_file_size,
3571 nb_new_data_clusters +
3574 if (allocation_start < 0) {
3575 error_setg_errno(errp, -allocation_start,
3576 "Failed to resize refcount structures");
3577 ret = allocation_start;
3581 clusters_allocated = qcow2_alloc_clusters_at(bs, allocation_start,
3582 nb_new_data_clusters);
3583 if (clusters_allocated < 0) {
3584 error_setg_errno(errp, -clusters_allocated,
3585 "Failed to allocate data clusters");
3586 ret = clusters_allocated;
3590 assert(clusters_allocated == nb_new_data_clusters);
3592 /* Allocate the data area */
3593 new_file_size = allocation_start +
3594 nb_new_data_clusters * s->cluster_size;
3595 ret = bdrv_co_truncate(bs->file, new_file_size, prealloc, errp);
3597 error_prepend(errp, "Failed to resize underlying file: ");
3598 qcow2_free_clusters(bs, allocation_start,
3599 nb_new_data_clusters * s->cluster_size,
3600 QCOW2_DISCARD_OTHER);
3604 /* Create the necessary L2 entries */
3605 host_offset = allocation_start;
3606 guest_offset = old_length;
3607 while (nb_new_data_clusters) {
3608 int64_t nb_clusters = MIN(
3609 nb_new_data_clusters,
3610 s->l2_slice_size - offset_to_l2_slice_index(s, guest_offset));
3611 QCowL2Meta allocation = {
3612 .offset = guest_offset,
3613 .alloc_offset = host_offset,
3614 .nb_clusters = nb_clusters,
3616 qemu_co_queue_init(&allocation.dependent_requests);
3618 ret = qcow2_alloc_cluster_link_l2(bs, &allocation);
3620 error_setg_errno(errp, -ret, "Failed to update L2 tables");
3621 qcow2_free_clusters(bs, host_offset,
3622 nb_new_data_clusters * s->cluster_size,
3623 QCOW2_DISCARD_OTHER);
3627 guest_offset += nb_clusters * s->cluster_size;
3628 host_offset += nb_clusters * s->cluster_size;
3629 nb_new_data_clusters -= nb_clusters;
3635 g_assert_not_reached();
3638 if (prealloc != PREALLOC_MODE_OFF) {
3639 /* Flush metadata before actually changing the image size */
3640 ret = qcow2_write_caches(bs);
3642 error_setg_errno(errp, -ret,
3643 "Failed to flush the preallocated area to disk");
3648 /* write updated header.size */
3649 offset = cpu_to_be64(offset);
3650 ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, size),
3651 &offset, sizeof(uint64_t));
3653 error_setg_errno(errp, -ret, "Failed to update the image size");
3657 s->l1_vm_state_index = new_l1_size;
3660 qemu_co_mutex_unlock(&s->lock);
3667 * @dest - destination buffer, at least of @size-1 bytes
3668 * @src - source buffer, @size bytes
3670 * Returns: compressed size on success
3671 * -1 if compression is inefficient
3672 * -2 on any other error
3674 static ssize_t qcow2_compress(void *dest, const void *src, size_t size)
3679 /* best compression, small window, no zlib header */
3680 memset(&strm, 0, sizeof(strm));
3681 ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION, Z_DEFLATED,
3682 -12, 9, Z_DEFAULT_STRATEGY);
3687 /* strm.next_in is not const in old zlib versions, such as those used on
3688 * OpenBSD/NetBSD, so cast the const away */
3689 strm.avail_in = size;
3690 strm.next_in = (void *) src;
3691 strm.avail_out = size - 1;
3692 strm.next_out = dest;
3694 ret = deflate(&strm, Z_FINISH);
3695 if (ret == Z_STREAM_END) {
3696 ret = size - 1 - strm.avail_out;
3698 ret = (ret == Z_OK ? -1 : -2);
3706 #define MAX_COMPRESS_THREADS 4
3708 typedef struct Qcow2CompressData {
3713 } Qcow2CompressData;
3715 static int qcow2_compress_pool_func(void *opaque)
3717 Qcow2CompressData *data = opaque;
3719 data->ret = qcow2_compress(data->dest, data->src, data->size);
3724 static void qcow2_compress_complete(void *opaque, int ret)
3726 qemu_coroutine_enter(opaque);
3729 /* See qcow2_compress definition for parameters description */
3730 static ssize_t qcow2_co_compress(BlockDriverState *bs,
3731 void *dest, const void *src, size_t size)
3733 BDRVQcow2State *s = bs->opaque;
3735 ThreadPool *pool = aio_get_thread_pool(bdrv_get_aio_context(bs));
3736 Qcow2CompressData arg = {
3742 while (s->nb_compress_threads >= MAX_COMPRESS_THREADS) {
3743 qemu_co_queue_wait(&s->compress_wait_queue, NULL);
3746 s->nb_compress_threads++;
3747 acb = thread_pool_submit_aio(pool, qcow2_compress_pool_func, &arg,
3748 qcow2_compress_complete,
3749 qemu_coroutine_self());
3752 s->nb_compress_threads--;
3755 qemu_coroutine_yield();
3756 s->nb_compress_threads--;
3757 qemu_co_queue_next(&s->compress_wait_queue);
3762 /* XXX: put compressed sectors first, then all the cluster aligned
3763 tables to avoid losing bytes in alignment */
3764 static coroutine_fn int
3765 qcow2_co_pwritev_compressed(BlockDriverState *bs, uint64_t offset,
3766 uint64_t bytes, QEMUIOVector *qiov)
3768 BDRVQcow2State *s = bs->opaque;
3769 QEMUIOVector hd_qiov;
3773 uint8_t *buf, *out_buf;
3774 int64_t cluster_offset;
3777 /* align end of file to a sector boundary to ease reading with
3778 sector based I/Os */
3779 cluster_offset = bdrv_getlength(bs->file->bs);
3780 if (cluster_offset < 0) {
3781 return cluster_offset;
3783 return bdrv_co_truncate(bs->file, cluster_offset, PREALLOC_MODE_OFF,
3787 if (offset_into_cluster(s, offset)) {
3791 buf = qemu_blockalign(bs, s->cluster_size);
3792 if (bytes != s->cluster_size) {
3793 if (bytes > s->cluster_size ||
3794 offset + bytes != bs->total_sectors << BDRV_SECTOR_BITS)
3799 /* Zero-pad last write if image size is not cluster aligned */
3800 memset(buf + bytes, 0, s->cluster_size - bytes);
3802 qemu_iovec_to_buf(qiov, 0, buf, bytes);
3804 out_buf = g_malloc(s->cluster_size);
3806 out_len = qcow2_co_compress(bs, out_buf, buf, s->cluster_size);
3807 if (out_len == -2) {
3810 } else if (out_len == -1) {
3811 /* could not compress: write normal cluster */
3812 ret = qcow2_co_pwritev(bs, offset, bytes, qiov, 0);
3819 qemu_co_mutex_lock(&s->lock);
3821 qcow2_alloc_compressed_cluster_offset(bs, offset, out_len);
3822 if (!cluster_offset) {
3823 qemu_co_mutex_unlock(&s->lock);
3827 cluster_offset &= s->cluster_offset_mask;
3829 ret = qcow2_pre_write_overlap_check(bs, 0, cluster_offset, out_len);
3830 qemu_co_mutex_unlock(&s->lock);
3835 iov = (struct iovec) {
3836 .iov_base = out_buf,
3839 qemu_iovec_init_external(&hd_qiov, &iov, 1);
3841 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_COMPRESSED);
3842 ret = bdrv_co_pwritev(bs->file, cluster_offset, out_len, &hd_qiov, 0);
3854 static int make_completely_empty(BlockDriverState *bs)
3856 BDRVQcow2State *s = bs->opaque;
3857 Error *local_err = NULL;
3858 int ret, l1_clusters;
3860 uint64_t *new_reftable = NULL;
3861 uint64_t rt_entry, l1_size2;
3864 uint64_t reftable_offset;
3865 uint32_t reftable_clusters;
3866 } QEMU_PACKED l1_ofs_rt_ofs_cls;
3868 ret = qcow2_cache_empty(bs, s->l2_table_cache);
3873 ret = qcow2_cache_empty(bs, s->refcount_block_cache);
3878 /* Refcounts will be broken utterly */
3879 ret = qcow2_mark_dirty(bs);
3884 BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
3886 l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / sizeof(uint64_t));
3887 l1_size2 = (uint64_t)s->l1_size * sizeof(uint64_t);
3889 /* After this call, neither the in-memory nor the on-disk refcount
3890 * information accurately describe the actual references */
3892 ret = bdrv_pwrite_zeroes(bs->file, s->l1_table_offset,
3893 l1_clusters * s->cluster_size, 0);
3895 goto fail_broken_refcounts;
3897 memset(s->l1_table, 0, l1_size2);
3899 BLKDBG_EVENT(bs->file, BLKDBG_EMPTY_IMAGE_PREPARE);
3901 /* Overwrite enough clusters at the beginning of the sectors to place
3902 * the refcount table, a refcount block and the L1 table in; this may
3903 * overwrite parts of the existing refcount and L1 table, which is not
3904 * an issue because the dirty flag is set, complete data loss is in fact
3905 * desired and partial data loss is consequently fine as well */
3906 ret = bdrv_pwrite_zeroes(bs->file, s->cluster_size,
3907 (2 + l1_clusters) * s->cluster_size, 0);
3908 /* This call (even if it failed overall) may have overwritten on-disk
3909 * refcount structures; in that case, the in-memory refcount information
3910 * will probably differ from the on-disk information which makes the BDS
3913 goto fail_broken_refcounts;
3916 BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
3917 BLKDBG_EVENT(bs->file, BLKDBG_REFTABLE_UPDATE);
3919 /* "Create" an empty reftable (one cluster) directly after the image
3920 * header and an empty L1 table three clusters after the image header;
3921 * the cluster between those two will be used as the first refblock */
3922 l1_ofs_rt_ofs_cls.l1_offset = cpu_to_be64(3 * s->cluster_size);
3923 l1_ofs_rt_ofs_cls.reftable_offset = cpu_to_be64(s->cluster_size);
3924 l1_ofs_rt_ofs_cls.reftable_clusters = cpu_to_be32(1);
3925 ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, l1_table_offset),
3926 &l1_ofs_rt_ofs_cls, sizeof(l1_ofs_rt_ofs_cls));
3928 goto fail_broken_refcounts;
3931 s->l1_table_offset = 3 * s->cluster_size;
3933 new_reftable = g_try_new0(uint64_t, s->cluster_size / sizeof(uint64_t));
3934 if (!new_reftable) {
3936 goto fail_broken_refcounts;
3939 s->refcount_table_offset = s->cluster_size;
3940 s->refcount_table_size = s->cluster_size / sizeof(uint64_t);
3941 s->max_refcount_table_index = 0;
3943 g_free(s->refcount_table);
3944 s->refcount_table = new_reftable;
3945 new_reftable = NULL;
3947 /* Now the in-memory refcount information again corresponds to the on-disk
3948 * information (reftable is empty and no refblocks (the refblock cache is
3949 * empty)); however, this means some clusters (e.g. the image header) are
3950 * referenced, but not refcounted, but the normal qcow2 code assumes that
3951 * the in-memory information is always correct */
3953 BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_ALLOC);
3955 /* Enter the first refblock into the reftable */
3956 rt_entry = cpu_to_be64(2 * s->cluster_size);
3957 ret = bdrv_pwrite_sync(bs->file, s->cluster_size,
3958 &rt_entry, sizeof(rt_entry));
3960 goto fail_broken_refcounts;
3962 s->refcount_table[0] = 2 * s->cluster_size;
3964 s->free_cluster_index = 0;
3965 assert(3 + l1_clusters <= s->refcount_block_size);
3966 offset = qcow2_alloc_clusters(bs, 3 * s->cluster_size + l1_size2);
3969 goto fail_broken_refcounts;
3970 } else if (offset > 0) {
3971 error_report("First cluster in emptied image is in use");
3975 /* Now finally the in-memory information corresponds to the on-disk
3976 * structures and is correct */
3977 ret = qcow2_mark_clean(bs);
3982 ret = bdrv_truncate(bs->file, (3 + l1_clusters) * s->cluster_size,
3983 PREALLOC_MODE_OFF, &local_err);
3985 error_report_err(local_err);
3991 fail_broken_refcounts:
3992 /* The BDS is unusable at this point. If we wanted to make it usable, we
3993 * would have to call qcow2_refcount_close(), qcow2_refcount_init(),
3994 * qcow2_check_refcounts(), qcow2_refcount_close() and qcow2_refcount_init()
3995 * again. However, because the functions which could have caused this error
3996 * path to be taken are used by those functions as well, it's very likely
3997 * that that sequence will fail as well. Therefore, just eject the BDS. */
4001 g_free(new_reftable);
4005 static int qcow2_make_empty(BlockDriverState *bs)
4007 BDRVQcow2State *s = bs->opaque;
4008 uint64_t offset, end_offset;
4009 int step = QEMU_ALIGN_DOWN(INT_MAX, s->cluster_size);
4010 int l1_clusters, ret = 0;
4012 l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / sizeof(uint64_t));
4014 if (s->qcow_version >= 3 && !s->snapshots && !s->nb_bitmaps &&
4015 3 + l1_clusters <= s->refcount_block_size &&
4016 s->crypt_method_header != QCOW_CRYPT_LUKS) {
4017 /* The following function only works for qcow2 v3 images (it
4018 * requires the dirty flag) and only as long as there are no
4019 * features that reserve extra clusters (such as snapshots,
4020 * LUKS header, or persistent bitmaps), because it completely
4021 * empties the image. Furthermore, the L1 table and three
4022 * additional clusters (image header, refcount table, one
4023 * refcount block) have to fit inside one refcount block. */
4024 return make_completely_empty(bs);
4027 /* This fallback code simply discards every active cluster; this is slow,
4028 * but works in all cases */
4029 end_offset = bs->total_sectors * BDRV_SECTOR_SIZE;
4030 for (offset = 0; offset < end_offset; offset += step) {
4031 /* As this function is generally used after committing an external
4032 * snapshot, QCOW2_DISCARD_SNAPSHOT seems appropriate. Also, the
4033 * default action for this kind of discard is to pass the discard,
4034 * which will ideally result in an actually smaller image file, as
4035 * is probably desired. */
4036 ret = qcow2_cluster_discard(bs, offset, MIN(step, end_offset - offset),
4037 QCOW2_DISCARD_SNAPSHOT, true);
4046 static coroutine_fn int qcow2_co_flush_to_os(BlockDriverState *bs)
4048 BDRVQcow2State *s = bs->opaque;
4051 qemu_co_mutex_lock(&s->lock);
4052 ret = qcow2_write_caches(bs);
4053 qemu_co_mutex_unlock(&s->lock);
4058 static BlockMeasureInfo *qcow2_measure(QemuOpts *opts, BlockDriverState *in_bs,
4061 Error *local_err = NULL;
4062 BlockMeasureInfo *info;
4063 uint64_t required = 0; /* bytes that contribute to required size */
4064 uint64_t virtual_size; /* disk size as seen by guest */
4065 uint64_t refcount_bits;
4067 size_t cluster_size;
4070 PreallocMode prealloc;
4071 bool has_backing_file;
4073 /* Parse image creation options */
4074 cluster_size = qcow2_opt_get_cluster_size_del(opts, &local_err);
4079 version = qcow2_opt_get_version_del(opts, &local_err);
4084 refcount_bits = qcow2_opt_get_refcount_bits_del(opts, version, &local_err);
4089 optstr = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
4090 prealloc = qapi_enum_parse(&PreallocMode_lookup, optstr,
4091 PREALLOC_MODE_OFF, &local_err);
4097 optstr = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
4098 has_backing_file = !!optstr;
4101 virtual_size = qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0);
4102 virtual_size = ROUND_UP(virtual_size, cluster_size);
4104 /* Check that virtual disk size is valid */
4105 l2_tables = DIV_ROUND_UP(virtual_size / cluster_size,
4106 cluster_size / sizeof(uint64_t));
4107 if (l2_tables * sizeof(uint64_t) > QCOW_MAX_L1_SIZE) {
4108 error_setg(&local_err, "The image size is too large "
4109 "(try using a larger cluster size)");
4113 /* Account for input image */
4115 int64_t ssize = bdrv_getlength(in_bs);
4117 error_setg_errno(&local_err, -ssize,
4118 "Unable to get image virtual_size");
4122 virtual_size = ROUND_UP(ssize, cluster_size);
4124 if (has_backing_file) {
4125 /* We don't how much of the backing chain is shared by the input
4126 * image and the new image file. In the worst case the new image's
4127 * backing file has nothing in common with the input image. Be
4128 * conservative and assume all clusters need to be written.
4130 required = virtual_size;
4135 for (offset = 0; offset < ssize; offset += pnum) {
4138 ret = bdrv_block_status_above(in_bs, NULL, offset,
4139 ssize - offset, &pnum, NULL,
4142 error_setg_errno(&local_err, -ret,
4143 "Unable to get block status");
4147 if (ret & BDRV_BLOCK_ZERO) {
4148 /* Skip zero regions (safe with no backing file) */
4149 } else if ((ret & (BDRV_BLOCK_DATA | BDRV_BLOCK_ALLOCATED)) ==
4150 (BDRV_BLOCK_DATA | BDRV_BLOCK_ALLOCATED)) {
4151 /* Extend pnum to end of cluster for next iteration */
4152 pnum = ROUND_UP(offset + pnum, cluster_size) - offset;
4154 /* Count clusters we've seen */
4155 required += offset % cluster_size + pnum;
4161 /* Take into account preallocation. Nothing special is needed for
4162 * PREALLOC_MODE_METADATA since metadata is always counted.
4164 if (prealloc == PREALLOC_MODE_FULL || prealloc == PREALLOC_MODE_FALLOC) {
4165 required = virtual_size;
4168 info = g_new(BlockMeasureInfo, 1);
4169 info->fully_allocated =
4170 qcow2_calc_prealloc_size(virtual_size, cluster_size,
4171 ctz32(refcount_bits));
4173 /* Remove data clusters that are not required. This overestimates the
4174 * required size because metadata needed for the fully allocated file is
4177 info->required = info->fully_allocated - virtual_size + required;
4181 error_propagate(errp, local_err);
4185 static int qcow2_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
4187 BDRVQcow2State *s = bs->opaque;
4188 bdi->unallocated_blocks_are_zero = true;
4189 bdi->cluster_size = s->cluster_size;
4190 bdi->vm_state_offset = qcow2_vm_state_offset(s);
4194 static ImageInfoSpecific *qcow2_get_specific_info(BlockDriverState *bs)
4196 BDRVQcow2State *s = bs->opaque;
4197 ImageInfoSpecific *spec_info;
4198 QCryptoBlockInfo *encrypt_info = NULL;
4200 if (s->crypto != NULL) {
4201 encrypt_info = qcrypto_block_get_info(s->crypto, &error_abort);
4204 spec_info = g_new(ImageInfoSpecific, 1);
4205 *spec_info = (ImageInfoSpecific){
4206 .type = IMAGE_INFO_SPECIFIC_KIND_QCOW2,
4207 .u.qcow2.data = g_new(ImageInfoSpecificQCow2, 1),
4209 if (s->qcow_version == 2) {
4210 *spec_info->u.qcow2.data = (ImageInfoSpecificQCow2){
4211 .compat = g_strdup("0.10"),
4212 .refcount_bits = s->refcount_bits,
4214 } else if (s->qcow_version == 3) {
4215 *spec_info->u.qcow2.data = (ImageInfoSpecificQCow2){
4216 .compat = g_strdup("1.1"),
4217 .lazy_refcounts = s->compatible_features &
4218 QCOW2_COMPAT_LAZY_REFCOUNTS,
4219 .has_lazy_refcounts = true,
4220 .corrupt = s->incompatible_features &
4221 QCOW2_INCOMPAT_CORRUPT,
4222 .has_corrupt = true,
4223 .refcount_bits = s->refcount_bits,
4226 /* if this assertion fails, this probably means a new version was
4227 * added without having it covered here */
4232 ImageInfoSpecificQCow2Encryption *qencrypt =
4233 g_new(ImageInfoSpecificQCow2Encryption, 1);
4234 switch (encrypt_info->format) {
4235 case Q_CRYPTO_BLOCK_FORMAT_QCOW:
4236 qencrypt->format = BLOCKDEV_QCOW2_ENCRYPTION_FORMAT_AES;
4238 case Q_CRYPTO_BLOCK_FORMAT_LUKS:
4239 qencrypt->format = BLOCKDEV_QCOW2_ENCRYPTION_FORMAT_LUKS;
4240 qencrypt->u.luks = encrypt_info->u.luks;
4245 /* Since we did shallow copy above, erase any pointers
4246 * in the original info */
4247 memset(&encrypt_info->u, 0, sizeof(encrypt_info->u));
4248 qapi_free_QCryptoBlockInfo(encrypt_info);
4250 spec_info->u.qcow2.data->has_encrypt = true;
4251 spec_info->u.qcow2.data->encrypt = qencrypt;
4257 static int qcow2_save_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
4260 BDRVQcow2State *s = bs->opaque;
4262 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_SAVE);
4263 return bs->drv->bdrv_co_pwritev(bs, qcow2_vm_state_offset(s) + pos,
4264 qiov->size, qiov, 0);
4267 static int qcow2_load_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
4270 BDRVQcow2State *s = bs->opaque;
4272 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_LOAD);
4273 return bs->drv->bdrv_co_preadv(bs, qcow2_vm_state_offset(s) + pos,
4274 qiov->size, qiov, 0);
4278 * Downgrades an image's version. To achieve this, any incompatible features
4279 * have to be removed.
4281 static int qcow2_downgrade(BlockDriverState *bs, int target_version,
4282 BlockDriverAmendStatusCB *status_cb, void *cb_opaque,
4285 BDRVQcow2State *s = bs->opaque;
4286 int current_version = s->qcow_version;
4289 /* This is qcow2_downgrade(), not qcow2_upgrade() */
4290 assert(target_version < current_version);
4292 /* There are no other versions (now) that you can downgrade to */
4293 assert(target_version == 2);
4295 if (s->refcount_order != 4) {
4296 error_setg(errp, "compat=0.10 requires refcount_bits=16");
4300 /* clear incompatible features */
4301 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
4302 ret = qcow2_mark_clean(bs);
4304 error_setg_errno(errp, -ret, "Failed to make the image clean");
4309 /* with QCOW2_INCOMPAT_CORRUPT, it is pretty much impossible to get here in
4310 * the first place; if that happens nonetheless, returning -ENOTSUP is the
4311 * best thing to do anyway */
4313 if (s->incompatible_features) {
4314 error_setg(errp, "Cannot downgrade an image with incompatible features "
4315 "%#" PRIx64 " set", s->incompatible_features);
4319 /* since we can ignore compatible features, we can set them to 0 as well */
4320 s->compatible_features = 0;
4321 /* if lazy refcounts have been used, they have already been fixed through
4322 * clearing the dirty flag */
4324 /* clearing autoclear features is trivial */
4325 s->autoclear_features = 0;
4327 ret = qcow2_expand_zero_clusters(bs, status_cb, cb_opaque);
4329 error_setg_errno(errp, -ret, "Failed to turn zero into data clusters");
4333 s->qcow_version = target_version;
4334 ret = qcow2_update_header(bs);
4336 s->qcow_version = current_version;
4337 error_setg_errno(errp, -ret, "Failed to update the image header");
4343 typedef enum Qcow2AmendOperation {
4344 /* This is the value Qcow2AmendHelperCBInfo::last_operation will be
4345 * statically initialized to so that the helper CB can discern the first
4346 * invocation from an operation change */
4347 QCOW2_NO_OPERATION = 0,
4349 QCOW2_CHANGING_REFCOUNT_ORDER,
4351 } Qcow2AmendOperation;
4353 typedef struct Qcow2AmendHelperCBInfo {
4354 /* The code coordinating the amend operations should only modify
4355 * these four fields; the rest will be managed by the CB */
4356 BlockDriverAmendStatusCB *original_status_cb;
4357 void *original_cb_opaque;
4359 Qcow2AmendOperation current_operation;
4361 /* Total number of operations to perform (only set once) */
4362 int total_operations;
4364 /* The following fields are managed by the CB */
4366 /* Number of operations completed */
4367 int operations_completed;
4369 /* Cumulative offset of all completed operations */
4370 int64_t offset_completed;
4372 Qcow2AmendOperation last_operation;
4373 int64_t last_work_size;
4374 } Qcow2AmendHelperCBInfo;
4376 static void qcow2_amend_helper_cb(BlockDriverState *bs,
4377 int64_t operation_offset,
4378 int64_t operation_work_size, void *opaque)
4380 Qcow2AmendHelperCBInfo *info = opaque;
4381 int64_t current_work_size;
4382 int64_t projected_work_size;
4384 if (info->current_operation != info->last_operation) {
4385 if (info->last_operation != QCOW2_NO_OPERATION) {
4386 info->offset_completed += info->last_work_size;
4387 info->operations_completed++;
4390 info->last_operation = info->current_operation;
4393 assert(info->total_operations > 0);
4394 assert(info->operations_completed < info->total_operations);
4396 info->last_work_size = operation_work_size;
4398 current_work_size = info->offset_completed + operation_work_size;
4400 /* current_work_size is the total work size for (operations_completed + 1)
4401 * operations (which includes this one), so multiply it by the number of
4402 * operations not covered and divide it by the number of operations
4403 * covered to get a projection for the operations not covered */
4404 projected_work_size = current_work_size * (info->total_operations -
4405 info->operations_completed - 1)
4406 / (info->operations_completed + 1);
4408 info->original_status_cb(bs, info->offset_completed + operation_offset,
4409 current_work_size + projected_work_size,
4410 info->original_cb_opaque);
4413 static int qcow2_amend_options(BlockDriverState *bs, QemuOpts *opts,
4414 BlockDriverAmendStatusCB *status_cb,
4418 BDRVQcow2State *s = bs->opaque;
4419 int old_version = s->qcow_version, new_version = old_version;
4420 uint64_t new_size = 0;
4421 const char *backing_file = NULL, *backing_format = NULL;
4422 bool lazy_refcounts = s->use_lazy_refcounts;
4423 const char *compat = NULL;
4424 uint64_t cluster_size = s->cluster_size;
4427 int refcount_bits = s->refcount_bits;
4429 QemuOptDesc *desc = opts->list->desc;
4430 Qcow2AmendHelperCBInfo helper_cb_info;
4432 while (desc && desc->name) {
4433 if (!qemu_opt_find(opts, desc->name)) {
4434 /* only change explicitly defined options */
4439 if (!strcmp(desc->name, BLOCK_OPT_COMPAT_LEVEL)) {
4440 compat = qemu_opt_get(opts, BLOCK_OPT_COMPAT_LEVEL);
4442 /* preserve default */
4443 } else if (!strcmp(compat, "0.10")) {
4445 } else if (!strcmp(compat, "1.1")) {
4448 error_setg(errp, "Unknown compatibility level %s", compat);
4451 } else if (!strcmp(desc->name, BLOCK_OPT_PREALLOC)) {
4452 error_setg(errp, "Cannot change preallocation mode");
4454 } else if (!strcmp(desc->name, BLOCK_OPT_SIZE)) {
4455 new_size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, 0);
4456 } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FILE)) {
4457 backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
4458 } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FMT)) {
4459 backing_format = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
4460 } else if (!strcmp(desc->name, BLOCK_OPT_ENCRYPT)) {
4461 encrypt = qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT,
4464 if (encrypt != !!s->crypto) {
4466 "Changing the encryption flag is not supported");
4469 } else if (!strcmp(desc->name, BLOCK_OPT_ENCRYPT_FORMAT)) {
4470 encformat = qcow2_crypt_method_from_format(
4471 qemu_opt_get(opts, BLOCK_OPT_ENCRYPT_FORMAT));
4473 if (encformat != s->crypt_method_header) {
4475 "Changing the encryption format is not supported");
4478 } else if (g_str_has_prefix(desc->name, "encrypt.")) {
4480 "Changing the encryption parameters is not supported");
4482 } else if (!strcmp(desc->name, BLOCK_OPT_CLUSTER_SIZE)) {
4483 cluster_size = qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE,
4485 if (cluster_size != s->cluster_size) {
4486 error_setg(errp, "Changing the cluster size is not supported");
4489 } else if (!strcmp(desc->name, BLOCK_OPT_LAZY_REFCOUNTS)) {
4490 lazy_refcounts = qemu_opt_get_bool(opts, BLOCK_OPT_LAZY_REFCOUNTS,
4492 } else if (!strcmp(desc->name, BLOCK_OPT_REFCOUNT_BITS)) {
4493 refcount_bits = qemu_opt_get_number(opts, BLOCK_OPT_REFCOUNT_BITS,
4496 if (refcount_bits <= 0 || refcount_bits > 64 ||
4497 !is_power_of_2(refcount_bits))
4499 error_setg(errp, "Refcount width must be a power of two and "
4500 "may not exceed 64 bits");
4504 /* if this point is reached, this probably means a new option was
4505 * added without having it covered here */
4512 helper_cb_info = (Qcow2AmendHelperCBInfo){
4513 .original_status_cb = status_cb,
4514 .original_cb_opaque = cb_opaque,
4515 .total_operations = (new_version < old_version)
4516 + (s->refcount_bits != refcount_bits)
4519 /* Upgrade first (some features may require compat=1.1) */
4520 if (new_version > old_version) {
4521 s->qcow_version = new_version;
4522 ret = qcow2_update_header(bs);
4524 s->qcow_version = old_version;
4525 error_setg_errno(errp, -ret, "Failed to update the image header");
4530 if (s->refcount_bits != refcount_bits) {
4531 int refcount_order = ctz32(refcount_bits);
4533 if (new_version < 3 && refcount_bits != 16) {
4534 error_setg(errp, "Refcount widths other than 16 bits require "
4535 "compatibility level 1.1 or above (use compat=1.1 or "
4540 helper_cb_info.current_operation = QCOW2_CHANGING_REFCOUNT_ORDER;
4541 ret = qcow2_change_refcount_order(bs, refcount_order,
4542 &qcow2_amend_helper_cb,
4543 &helper_cb_info, errp);
4549 if (backing_file || backing_format) {
4550 ret = qcow2_change_backing_file(bs,
4551 backing_file ?: s->image_backing_file,
4552 backing_format ?: s->image_backing_format);
4554 error_setg_errno(errp, -ret, "Failed to change the backing file");
4559 if (s->use_lazy_refcounts != lazy_refcounts) {
4560 if (lazy_refcounts) {
4561 if (new_version < 3) {
4562 error_setg(errp, "Lazy refcounts only supported with "
4563 "compatibility level 1.1 and above (use compat=1.1 "
4567 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
4568 ret = qcow2_update_header(bs);
4570 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
4571 error_setg_errno(errp, -ret, "Failed to update the image header");
4574 s->use_lazy_refcounts = true;
4576 /* make image clean first */
4577 ret = qcow2_mark_clean(bs);
4579 error_setg_errno(errp, -ret, "Failed to make the image clean");
4582 /* now disallow lazy refcounts */
4583 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
4584 ret = qcow2_update_header(bs);
4586 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
4587 error_setg_errno(errp, -ret, "Failed to update the image header");
4590 s->use_lazy_refcounts = false;
4595 BlockBackend *blk = blk_new(BLK_PERM_RESIZE, BLK_PERM_ALL);
4596 ret = blk_insert_bs(blk, bs, errp);
4602 ret = blk_truncate(blk, new_size, PREALLOC_MODE_OFF, errp);
4609 /* Downgrade last (so unsupported features can be removed before) */
4610 if (new_version < old_version) {
4611 helper_cb_info.current_operation = QCOW2_DOWNGRADING;
4612 ret = qcow2_downgrade(bs, new_version, &qcow2_amend_helper_cb,
4613 &helper_cb_info, errp);
4623 * If offset or size are negative, respectively, they will not be included in
4624 * the BLOCK_IMAGE_CORRUPTED event emitted.
4625 * fatal will be ignored for read-only BDS; corruptions found there will always
4626 * be considered non-fatal.
4628 void qcow2_signal_corruption(BlockDriverState *bs, bool fatal, int64_t offset,
4629 int64_t size, const char *message_format, ...)
4631 BDRVQcow2State *s = bs->opaque;
4632 const char *node_name;
4636 fatal = fatal && bdrv_is_writable(bs);
4638 if (s->signaled_corruption &&
4639 (!fatal || (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT)))
4644 va_start(ap, message_format);
4645 message = g_strdup_vprintf(message_format, ap);
4649 fprintf(stderr, "qcow2: Marking image as corrupt: %s; further "
4650 "corruption events will be suppressed\n", message);
4652 fprintf(stderr, "qcow2: Image is corrupt: %s; further non-fatal "
4653 "corruption events will be suppressed\n", message);
4656 node_name = bdrv_get_node_name(bs);
4657 qapi_event_send_block_image_corrupted(bdrv_get_device_name(bs),
4658 *node_name != '\0', node_name,
4659 message, offset >= 0, offset,
4665 qcow2_mark_corrupt(bs);
4666 bs->drv = NULL; /* make BDS unusable */
4669 s->signaled_corruption = true;
4672 static QemuOptsList qcow2_create_opts = {
4673 .name = "qcow2-create-opts",
4674 .head = QTAILQ_HEAD_INITIALIZER(qcow2_create_opts.head),
4677 .name = BLOCK_OPT_SIZE,
4678 .type = QEMU_OPT_SIZE,
4679 .help = "Virtual disk size"
4682 .name = BLOCK_OPT_COMPAT_LEVEL,
4683 .type = QEMU_OPT_STRING,
4684 .help = "Compatibility level (0.10 or 1.1)"
4687 .name = BLOCK_OPT_BACKING_FILE,
4688 .type = QEMU_OPT_STRING,
4689 .help = "File name of a base image"
4692 .name = BLOCK_OPT_BACKING_FMT,
4693 .type = QEMU_OPT_STRING,
4694 .help = "Image format of the base image"
4697 .name = BLOCK_OPT_ENCRYPT,
4698 .type = QEMU_OPT_BOOL,
4699 .help = "Encrypt the image with format 'aes'. (Deprecated "
4700 "in favor of " BLOCK_OPT_ENCRYPT_FORMAT "=aes)",
4703 .name = BLOCK_OPT_ENCRYPT_FORMAT,
4704 .type = QEMU_OPT_STRING,
4705 .help = "Encrypt the image, format choices: 'aes', 'luks'",
4707 BLOCK_CRYPTO_OPT_DEF_KEY_SECRET("encrypt.",
4708 "ID of secret providing qcow AES key or LUKS passphrase"),
4709 BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_ALG("encrypt."),
4710 BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_MODE("encrypt."),
4711 BLOCK_CRYPTO_OPT_DEF_LUKS_IVGEN_ALG("encrypt."),
4712 BLOCK_CRYPTO_OPT_DEF_LUKS_IVGEN_HASH_ALG("encrypt."),
4713 BLOCK_CRYPTO_OPT_DEF_LUKS_HASH_ALG("encrypt."),
4714 BLOCK_CRYPTO_OPT_DEF_LUKS_ITER_TIME("encrypt."),
4716 .name = BLOCK_OPT_CLUSTER_SIZE,
4717 .type = QEMU_OPT_SIZE,
4718 .help = "qcow2 cluster size",
4719 .def_value_str = stringify(DEFAULT_CLUSTER_SIZE)
4722 .name = BLOCK_OPT_PREALLOC,
4723 .type = QEMU_OPT_STRING,
4724 .help = "Preallocation mode (allowed values: off, metadata, "
4728 .name = BLOCK_OPT_LAZY_REFCOUNTS,
4729 .type = QEMU_OPT_BOOL,
4730 .help = "Postpone refcount updates",
4731 .def_value_str = "off"
4734 .name = BLOCK_OPT_REFCOUNT_BITS,
4735 .type = QEMU_OPT_NUMBER,
4736 .help = "Width of a reference count entry in bits",
4737 .def_value_str = "16"
4739 { /* end of list */ }
4743 BlockDriver bdrv_qcow2 = {
4744 .format_name = "qcow2",
4745 .instance_size = sizeof(BDRVQcow2State),
4746 .bdrv_probe = qcow2_probe,
4747 .bdrv_open = qcow2_open,
4748 .bdrv_close = qcow2_close,
4749 .bdrv_reopen_prepare = qcow2_reopen_prepare,
4750 .bdrv_reopen_commit = qcow2_reopen_commit,
4751 .bdrv_reopen_abort = qcow2_reopen_abort,
4752 .bdrv_join_options = qcow2_join_options,
4753 .bdrv_child_perm = bdrv_format_default_perms,
4754 .bdrv_co_create_opts = qcow2_co_create_opts,
4755 .bdrv_co_create = qcow2_co_create,
4756 .bdrv_has_zero_init = bdrv_has_zero_init_1,
4757 .bdrv_co_block_status = qcow2_co_block_status,
4759 .bdrv_co_preadv = qcow2_co_preadv,
4760 .bdrv_co_pwritev = qcow2_co_pwritev,
4761 .bdrv_co_flush_to_os = qcow2_co_flush_to_os,
4763 .bdrv_co_pwrite_zeroes = qcow2_co_pwrite_zeroes,
4764 .bdrv_co_pdiscard = qcow2_co_pdiscard,
4765 .bdrv_co_copy_range_from = qcow2_co_copy_range_from,
4766 .bdrv_co_copy_range_to = qcow2_co_copy_range_to,
4767 .bdrv_co_truncate = qcow2_co_truncate,
4768 .bdrv_co_pwritev_compressed = qcow2_co_pwritev_compressed,
4769 .bdrv_make_empty = qcow2_make_empty,
4771 .bdrv_snapshot_create = qcow2_snapshot_create,
4772 .bdrv_snapshot_goto = qcow2_snapshot_goto,
4773 .bdrv_snapshot_delete = qcow2_snapshot_delete,
4774 .bdrv_snapshot_list = qcow2_snapshot_list,
4775 .bdrv_snapshot_load_tmp = qcow2_snapshot_load_tmp,
4776 .bdrv_measure = qcow2_measure,
4777 .bdrv_get_info = qcow2_get_info,
4778 .bdrv_get_specific_info = qcow2_get_specific_info,
4780 .bdrv_save_vmstate = qcow2_save_vmstate,
4781 .bdrv_load_vmstate = qcow2_load_vmstate,
4783 .supports_backing = true,
4784 .bdrv_change_backing_file = qcow2_change_backing_file,
4786 .bdrv_refresh_limits = qcow2_refresh_limits,
4787 .bdrv_co_invalidate_cache = qcow2_co_invalidate_cache,
4788 .bdrv_inactivate = qcow2_inactivate,
4790 .create_opts = &qcow2_create_opts,
4791 .bdrv_co_check = qcow2_co_check,
4792 .bdrv_amend_options = qcow2_amend_options,
4794 .bdrv_detach_aio_context = qcow2_detach_aio_context,
4795 .bdrv_attach_aio_context = qcow2_attach_aio_context,
4797 .bdrv_reopen_bitmaps_rw = qcow2_reopen_bitmaps_rw,
4798 .bdrv_can_store_new_dirty_bitmap = qcow2_can_store_new_dirty_bitmap,
4799 .bdrv_remove_persistent_dirty_bitmap = qcow2_remove_persistent_dirty_bitmap,
4802 static void bdrv_qcow2_init(void)
4804 bdrv_register(&bdrv_qcow2);
4807 block_init(bdrv_qcow2_init);