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
24 #include "qemu-common.h"
25 #include "block/block_int.h"
26 #include "qemu/module.h"
28 #include "block/qcow2.h"
29 #include "qemu/error-report.h"
30 #include "qapi/qmp/qerror.h"
31 #include "qapi/qmp/qbool.h"
32 #include "qapi/util.h"
33 #include "qapi/qmp/types.h"
34 #include "qapi-event.h"
36 #include "qemu/option_int.h"
39 Differences with QCOW:
41 - Support for multiple incremental snapshots.
42 - Memory management by reference counts.
43 - Clusters which have a reference count of one have the bit
44 QCOW_OFLAG_COPIED to optimize write performance.
45 - Size of compressed clusters is stored in sectors to reduce bit usage
46 in the cluster offsets.
47 - Support for storing additional data (such as the VM state) in the
49 - If a backing store is used, the cluster size is not constrained
50 (could be backported to QCOW).
51 - L2 tables have always a size of one cluster.
58 } QEMU_PACKED QCowExtension;
60 #define QCOW2_EXT_MAGIC_END 0
61 #define QCOW2_EXT_MAGIC_BACKING_FORMAT 0xE2792ACA
62 #define QCOW2_EXT_MAGIC_FEATURE_TABLE 0x6803f857
64 static int qcow2_probe(const uint8_t *buf, int buf_size, const char *filename)
66 const QCowHeader *cow_header = (const void *)buf;
68 if (buf_size >= sizeof(QCowHeader) &&
69 be32_to_cpu(cow_header->magic) == QCOW_MAGIC &&
70 be32_to_cpu(cow_header->version) >= 2)
78 * read qcow2 extension and fill bs
79 * start reading from start_offset
80 * finish reading upon magic of value 0 or when end_offset reached
81 * unknown magic is skipped (future extension this version knows nothing about)
82 * return 0 upon success, non-0 otherwise
84 static int qcow2_read_extensions(BlockDriverState *bs, uint64_t start_offset,
85 uint64_t end_offset, void **p_feature_table,
88 BDRVQcow2State *s = bs->opaque;
94 printf("qcow2_read_extensions: start=%ld end=%ld\n", start_offset, end_offset);
96 offset = start_offset;
97 while (offset < end_offset) {
101 if (offset > s->cluster_size)
102 printf("qcow2_read_extension: suspicious offset %lu\n", offset);
104 printf("attempting to read extended header in offset %lu\n", offset);
107 ret = bdrv_pread(bs->file->bs, offset, &ext, sizeof(ext));
109 error_setg_errno(errp, -ret, "qcow2_read_extension: ERROR: "
110 "pread fail from offset %" PRIu64, offset);
113 be32_to_cpus(&ext.magic);
114 be32_to_cpus(&ext.len);
115 offset += sizeof(ext);
117 printf("ext.magic = 0x%x\n", ext.magic);
119 if (offset > end_offset || ext.len > end_offset - offset) {
120 error_setg(errp, "Header extension too large");
125 case QCOW2_EXT_MAGIC_END:
128 case QCOW2_EXT_MAGIC_BACKING_FORMAT:
129 if (ext.len >= sizeof(bs->backing_format)) {
130 error_setg(errp, "ERROR: ext_backing_format: len=%" PRIu32
131 " too large (>=%zu)", ext.len,
132 sizeof(bs->backing_format));
135 ret = bdrv_pread(bs->file->bs, offset, bs->backing_format, ext.len);
137 error_setg_errno(errp, -ret, "ERROR: ext_backing_format: "
138 "Could not read format name");
141 bs->backing_format[ext.len] = '\0';
142 s->image_backing_format = g_strdup(bs->backing_format);
144 printf("Qcow2: Got format extension %s\n", bs->backing_format);
148 case QCOW2_EXT_MAGIC_FEATURE_TABLE:
149 if (p_feature_table != NULL) {
150 void* feature_table = g_malloc0(ext.len + 2 * sizeof(Qcow2Feature));
151 ret = bdrv_pread(bs->file->bs, offset , feature_table, ext.len);
153 error_setg_errno(errp, -ret, "ERROR: ext_feature_table: "
154 "Could not read table");
158 *p_feature_table = feature_table;
163 /* unknown magic - save it in case we need to rewrite the header */
165 Qcow2UnknownHeaderExtension *uext;
167 uext = g_malloc0(sizeof(*uext) + ext.len);
168 uext->magic = ext.magic;
170 QLIST_INSERT_HEAD(&s->unknown_header_ext, uext, next);
172 ret = bdrv_pread(bs->file->bs, offset , uext->data, uext->len);
174 error_setg_errno(errp, -ret, "ERROR: unknown extension: "
175 "Could not read data");
182 offset += ((ext.len + 7) & ~7);
188 static void cleanup_unknown_header_ext(BlockDriverState *bs)
190 BDRVQcow2State *s = bs->opaque;
191 Qcow2UnknownHeaderExtension *uext, *next;
193 QLIST_FOREACH_SAFE(uext, &s->unknown_header_ext, next, next) {
194 QLIST_REMOVE(uext, next);
199 static void GCC_FMT_ATTR(3, 4) report_unsupported(BlockDriverState *bs,
200 Error **errp, const char *fmt, ...)
206 vsnprintf(msg, sizeof(msg), fmt, ap);
209 error_setg(errp, QERR_UNKNOWN_BLOCK_FORMAT_FEATURE,
210 bdrv_get_device_or_node_name(bs), "qcow2", msg);
213 static void report_unsupported_feature(BlockDriverState *bs,
214 Error **errp, Qcow2Feature *table, uint64_t mask)
216 char *features = g_strdup("");
219 while (table && table->name[0] != '\0') {
220 if (table->type == QCOW2_FEAT_TYPE_INCOMPATIBLE) {
221 if (mask & (1ULL << table->bit)) {
223 features = g_strdup_printf("%s%s%.46s", old, *old ? ", " : "",
226 mask &= ~(1ULL << table->bit);
234 features = g_strdup_printf("%s%sUnknown incompatible feature: %" PRIx64,
235 old, *old ? ", " : "", mask);
239 report_unsupported(bs, errp, "%s", features);
244 * Sets the dirty bit and flushes afterwards if necessary.
246 * The incompatible_features bit is only set if the image file header was
247 * updated successfully. Therefore it is not required to check the return
248 * value of this function.
250 int qcow2_mark_dirty(BlockDriverState *bs)
252 BDRVQcow2State *s = bs->opaque;
256 assert(s->qcow_version >= 3);
258 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
259 return 0; /* already dirty */
262 val = cpu_to_be64(s->incompatible_features | QCOW2_INCOMPAT_DIRTY);
263 ret = bdrv_pwrite(bs->file->bs, offsetof(QCowHeader, incompatible_features),
268 ret = bdrv_flush(bs->file->bs);
273 /* Only treat image as dirty if the header was updated successfully */
274 s->incompatible_features |= QCOW2_INCOMPAT_DIRTY;
279 * Clears the dirty bit and flushes before if necessary. Only call this
280 * function when there are no pending requests, it does not guard against
281 * concurrent requests dirtying the image.
283 static int qcow2_mark_clean(BlockDriverState *bs)
285 BDRVQcow2State *s = bs->opaque;
287 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
290 s->incompatible_features &= ~QCOW2_INCOMPAT_DIRTY;
292 ret = bdrv_flush(bs);
297 return qcow2_update_header(bs);
303 * Marks the image as corrupt.
305 int qcow2_mark_corrupt(BlockDriverState *bs)
307 BDRVQcow2State *s = bs->opaque;
309 s->incompatible_features |= QCOW2_INCOMPAT_CORRUPT;
310 return qcow2_update_header(bs);
314 * Marks the image as consistent, i.e., unsets the corrupt bit, and flushes
315 * before if necessary.
317 int qcow2_mark_consistent(BlockDriverState *bs)
319 BDRVQcow2State *s = bs->opaque;
321 if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
322 int ret = bdrv_flush(bs);
327 s->incompatible_features &= ~QCOW2_INCOMPAT_CORRUPT;
328 return qcow2_update_header(bs);
333 static int qcow2_check(BlockDriverState *bs, BdrvCheckResult *result,
336 int ret = qcow2_check_refcounts(bs, result, fix);
341 if (fix && result->check_errors == 0 && result->corruptions == 0) {
342 ret = qcow2_mark_clean(bs);
346 return qcow2_mark_consistent(bs);
351 static int validate_table_offset(BlockDriverState *bs, uint64_t offset,
352 uint64_t entries, size_t entry_len)
354 BDRVQcow2State *s = bs->opaque;
357 /* Use signed INT64_MAX as the maximum even for uint64_t header fields,
358 * because values will be passed to qemu functions taking int64_t. */
359 if (entries > INT64_MAX / entry_len) {
363 size = entries * entry_len;
365 if (INT64_MAX - size < offset) {
369 /* Tables must be cluster aligned */
370 if (offset & (s->cluster_size - 1)) {
377 static QemuOptsList qcow2_runtime_opts = {
379 .head = QTAILQ_HEAD_INITIALIZER(qcow2_runtime_opts.head),
382 .name = QCOW2_OPT_LAZY_REFCOUNTS,
383 .type = QEMU_OPT_BOOL,
384 .help = "Postpone refcount updates",
387 .name = QCOW2_OPT_DISCARD_REQUEST,
388 .type = QEMU_OPT_BOOL,
389 .help = "Pass guest discard requests to the layer below",
392 .name = QCOW2_OPT_DISCARD_SNAPSHOT,
393 .type = QEMU_OPT_BOOL,
394 .help = "Generate discard requests when snapshot related space "
398 .name = QCOW2_OPT_DISCARD_OTHER,
399 .type = QEMU_OPT_BOOL,
400 .help = "Generate discard requests when other clusters are freed",
403 .name = QCOW2_OPT_OVERLAP,
404 .type = QEMU_OPT_STRING,
405 .help = "Selects which overlap checks to perform from a range of "
406 "templates (none, constant, cached, all)",
409 .name = QCOW2_OPT_OVERLAP_TEMPLATE,
410 .type = QEMU_OPT_STRING,
411 .help = "Selects which overlap checks to perform from a range of "
412 "templates (none, constant, cached, all)",
415 .name = QCOW2_OPT_OVERLAP_MAIN_HEADER,
416 .type = QEMU_OPT_BOOL,
417 .help = "Check for unintended writes into the main qcow2 header",
420 .name = QCOW2_OPT_OVERLAP_ACTIVE_L1,
421 .type = QEMU_OPT_BOOL,
422 .help = "Check for unintended writes into the active L1 table",
425 .name = QCOW2_OPT_OVERLAP_ACTIVE_L2,
426 .type = QEMU_OPT_BOOL,
427 .help = "Check for unintended writes into an active L2 table",
430 .name = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
431 .type = QEMU_OPT_BOOL,
432 .help = "Check for unintended writes into the refcount table",
435 .name = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
436 .type = QEMU_OPT_BOOL,
437 .help = "Check for unintended writes into a refcount block",
440 .name = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
441 .type = QEMU_OPT_BOOL,
442 .help = "Check for unintended writes into the snapshot table",
445 .name = QCOW2_OPT_OVERLAP_INACTIVE_L1,
446 .type = QEMU_OPT_BOOL,
447 .help = "Check for unintended writes into an inactive L1 table",
450 .name = QCOW2_OPT_OVERLAP_INACTIVE_L2,
451 .type = QEMU_OPT_BOOL,
452 .help = "Check for unintended writes into an inactive L2 table",
455 .name = QCOW2_OPT_CACHE_SIZE,
456 .type = QEMU_OPT_SIZE,
457 .help = "Maximum combined metadata (L2 tables and refcount blocks) "
461 .name = QCOW2_OPT_L2_CACHE_SIZE,
462 .type = QEMU_OPT_SIZE,
463 .help = "Maximum L2 table cache size",
466 .name = QCOW2_OPT_REFCOUNT_CACHE_SIZE,
467 .type = QEMU_OPT_SIZE,
468 .help = "Maximum refcount block cache size",
471 .name = QCOW2_OPT_CACHE_CLEAN_INTERVAL,
472 .type = QEMU_OPT_NUMBER,
473 .help = "Clean unused cache entries after this time (in seconds)",
475 { /* end of list */ }
479 static const char *overlap_bool_option_names[QCOW2_OL_MAX_BITNR] = {
480 [QCOW2_OL_MAIN_HEADER_BITNR] = QCOW2_OPT_OVERLAP_MAIN_HEADER,
481 [QCOW2_OL_ACTIVE_L1_BITNR] = QCOW2_OPT_OVERLAP_ACTIVE_L1,
482 [QCOW2_OL_ACTIVE_L2_BITNR] = QCOW2_OPT_OVERLAP_ACTIVE_L2,
483 [QCOW2_OL_REFCOUNT_TABLE_BITNR] = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
484 [QCOW2_OL_REFCOUNT_BLOCK_BITNR] = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
485 [QCOW2_OL_SNAPSHOT_TABLE_BITNR] = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
486 [QCOW2_OL_INACTIVE_L1_BITNR] = QCOW2_OPT_OVERLAP_INACTIVE_L1,
487 [QCOW2_OL_INACTIVE_L2_BITNR] = QCOW2_OPT_OVERLAP_INACTIVE_L2,
490 static void cache_clean_timer_cb(void *opaque)
492 BlockDriverState *bs = opaque;
493 BDRVQcow2State *s = bs->opaque;
494 qcow2_cache_clean_unused(bs, s->l2_table_cache);
495 qcow2_cache_clean_unused(bs, s->refcount_block_cache);
496 timer_mod(s->cache_clean_timer, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) +
497 (int64_t) s->cache_clean_interval * 1000);
500 static void cache_clean_timer_init(BlockDriverState *bs, AioContext *context)
502 BDRVQcow2State *s = bs->opaque;
503 if (s->cache_clean_interval > 0) {
504 s->cache_clean_timer = aio_timer_new(context, QEMU_CLOCK_VIRTUAL,
505 SCALE_MS, cache_clean_timer_cb,
507 timer_mod(s->cache_clean_timer, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) +
508 (int64_t) s->cache_clean_interval * 1000);
512 static void cache_clean_timer_del(BlockDriverState *bs)
514 BDRVQcow2State *s = bs->opaque;
515 if (s->cache_clean_timer) {
516 timer_del(s->cache_clean_timer);
517 timer_free(s->cache_clean_timer);
518 s->cache_clean_timer = NULL;
522 static void qcow2_detach_aio_context(BlockDriverState *bs)
524 cache_clean_timer_del(bs);
527 static void qcow2_attach_aio_context(BlockDriverState *bs,
528 AioContext *new_context)
530 cache_clean_timer_init(bs, new_context);
533 static void read_cache_sizes(BlockDriverState *bs, QemuOpts *opts,
534 uint64_t *l2_cache_size,
535 uint64_t *refcount_cache_size, Error **errp)
537 BDRVQcow2State *s = bs->opaque;
538 uint64_t combined_cache_size;
539 bool l2_cache_size_set, refcount_cache_size_set, combined_cache_size_set;
541 combined_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_CACHE_SIZE);
542 l2_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_L2_CACHE_SIZE);
543 refcount_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
545 combined_cache_size = qemu_opt_get_size(opts, QCOW2_OPT_CACHE_SIZE, 0);
546 *l2_cache_size = qemu_opt_get_size(opts, QCOW2_OPT_L2_CACHE_SIZE, 0);
547 *refcount_cache_size = qemu_opt_get_size(opts,
548 QCOW2_OPT_REFCOUNT_CACHE_SIZE, 0);
550 if (combined_cache_size_set) {
551 if (l2_cache_size_set && refcount_cache_size_set) {
552 error_setg(errp, QCOW2_OPT_CACHE_SIZE ", " QCOW2_OPT_L2_CACHE_SIZE
553 " and " QCOW2_OPT_REFCOUNT_CACHE_SIZE " may not be set "
556 } else if (*l2_cache_size > combined_cache_size) {
557 error_setg(errp, QCOW2_OPT_L2_CACHE_SIZE " may not exceed "
558 QCOW2_OPT_CACHE_SIZE);
560 } else if (*refcount_cache_size > combined_cache_size) {
561 error_setg(errp, QCOW2_OPT_REFCOUNT_CACHE_SIZE " may not exceed "
562 QCOW2_OPT_CACHE_SIZE);
566 if (l2_cache_size_set) {
567 *refcount_cache_size = combined_cache_size - *l2_cache_size;
568 } else if (refcount_cache_size_set) {
569 *l2_cache_size = combined_cache_size - *refcount_cache_size;
571 *refcount_cache_size = combined_cache_size
572 / (DEFAULT_L2_REFCOUNT_SIZE_RATIO + 1);
573 *l2_cache_size = combined_cache_size - *refcount_cache_size;
576 if (!l2_cache_size_set && !refcount_cache_size_set) {
577 *l2_cache_size = MAX(DEFAULT_L2_CACHE_BYTE_SIZE,
578 (uint64_t)DEFAULT_L2_CACHE_CLUSTERS
580 *refcount_cache_size = *l2_cache_size
581 / DEFAULT_L2_REFCOUNT_SIZE_RATIO;
582 } else if (!l2_cache_size_set) {
583 *l2_cache_size = *refcount_cache_size
584 * DEFAULT_L2_REFCOUNT_SIZE_RATIO;
585 } else if (!refcount_cache_size_set) {
586 *refcount_cache_size = *l2_cache_size
587 / DEFAULT_L2_REFCOUNT_SIZE_RATIO;
592 typedef struct Qcow2ReopenState {
593 Qcow2Cache *l2_table_cache;
594 Qcow2Cache *refcount_block_cache;
595 bool use_lazy_refcounts;
597 bool discard_passthrough[QCOW2_DISCARD_MAX];
598 uint64_t cache_clean_interval;
601 static int qcow2_update_options_prepare(BlockDriverState *bs,
603 QDict *options, int flags,
606 BDRVQcow2State *s = bs->opaque;
607 QemuOpts *opts = NULL;
608 const char *opt_overlap_check, *opt_overlap_check_template;
609 int overlap_check_template = 0;
610 uint64_t l2_cache_size, refcount_cache_size;
612 Error *local_err = NULL;
615 opts = qemu_opts_create(&qcow2_runtime_opts, NULL, 0, &error_abort);
616 qemu_opts_absorb_qdict(opts, options, &local_err);
618 error_propagate(errp, local_err);
623 /* get L2 table/refcount block cache size from command line options */
624 read_cache_sizes(bs, opts, &l2_cache_size, &refcount_cache_size,
627 error_propagate(errp, local_err);
632 l2_cache_size /= s->cluster_size;
633 if (l2_cache_size < MIN_L2_CACHE_SIZE) {
634 l2_cache_size = MIN_L2_CACHE_SIZE;
636 if (l2_cache_size > INT_MAX) {
637 error_setg(errp, "L2 cache size too big");
642 refcount_cache_size /= s->cluster_size;
643 if (refcount_cache_size < MIN_REFCOUNT_CACHE_SIZE) {
644 refcount_cache_size = MIN_REFCOUNT_CACHE_SIZE;
646 if (refcount_cache_size > INT_MAX) {
647 error_setg(errp, "Refcount cache size too big");
652 /* alloc new L2 table/refcount block cache, flush old one */
653 if (s->l2_table_cache) {
654 ret = qcow2_cache_flush(bs, s->l2_table_cache);
656 error_setg_errno(errp, -ret, "Failed to flush the L2 table cache");
661 if (s->refcount_block_cache) {
662 ret = qcow2_cache_flush(bs, s->refcount_block_cache);
664 error_setg_errno(errp, -ret,
665 "Failed to flush the refcount block cache");
670 r->l2_table_cache = qcow2_cache_create(bs, l2_cache_size);
671 r->refcount_block_cache = qcow2_cache_create(bs, refcount_cache_size);
672 if (r->l2_table_cache == NULL || r->refcount_block_cache == NULL) {
673 error_setg(errp, "Could not allocate metadata caches");
678 /* New interval for cache cleanup timer */
679 r->cache_clean_interval =
680 qemu_opt_get_number(opts, QCOW2_OPT_CACHE_CLEAN_INTERVAL,
681 s->cache_clean_interval);
682 if (r->cache_clean_interval > UINT_MAX) {
683 error_setg(errp, "Cache clean interval too big");
688 /* lazy-refcounts; flush if going from enabled to disabled */
689 r->use_lazy_refcounts = qemu_opt_get_bool(opts, QCOW2_OPT_LAZY_REFCOUNTS,
690 (s->compatible_features & QCOW2_COMPAT_LAZY_REFCOUNTS));
691 if (r->use_lazy_refcounts && s->qcow_version < 3) {
692 error_setg(errp, "Lazy refcounts require a qcow2 image with at least "
693 "qemu 1.1 compatibility level");
698 if (s->use_lazy_refcounts && !r->use_lazy_refcounts) {
699 ret = qcow2_mark_clean(bs);
701 error_setg_errno(errp, -ret, "Failed to disable lazy refcounts");
706 /* Overlap check options */
707 opt_overlap_check = qemu_opt_get(opts, QCOW2_OPT_OVERLAP);
708 opt_overlap_check_template = qemu_opt_get(opts, QCOW2_OPT_OVERLAP_TEMPLATE);
709 if (opt_overlap_check_template && opt_overlap_check &&
710 strcmp(opt_overlap_check_template, opt_overlap_check))
712 error_setg(errp, "Conflicting values for qcow2 options '"
713 QCOW2_OPT_OVERLAP "' ('%s') and '" QCOW2_OPT_OVERLAP_TEMPLATE
714 "' ('%s')", opt_overlap_check, opt_overlap_check_template);
718 if (!opt_overlap_check) {
719 opt_overlap_check = opt_overlap_check_template ?: "cached";
722 if (!strcmp(opt_overlap_check, "none")) {
723 overlap_check_template = 0;
724 } else if (!strcmp(opt_overlap_check, "constant")) {
725 overlap_check_template = QCOW2_OL_CONSTANT;
726 } else if (!strcmp(opt_overlap_check, "cached")) {
727 overlap_check_template = QCOW2_OL_CACHED;
728 } else if (!strcmp(opt_overlap_check, "all")) {
729 overlap_check_template = QCOW2_OL_ALL;
731 error_setg(errp, "Unsupported value '%s' for qcow2 option "
732 "'overlap-check'. Allowed are any of the following: "
733 "none, constant, cached, all", opt_overlap_check);
738 r->overlap_check = 0;
739 for (i = 0; i < QCOW2_OL_MAX_BITNR; i++) {
740 /* overlap-check defines a template bitmask, but every flag may be
741 * overwritten through the associated boolean option */
743 qemu_opt_get_bool(opts, overlap_bool_option_names[i],
744 overlap_check_template & (1 << i)) << i;
747 r->discard_passthrough[QCOW2_DISCARD_NEVER] = false;
748 r->discard_passthrough[QCOW2_DISCARD_ALWAYS] = true;
749 r->discard_passthrough[QCOW2_DISCARD_REQUEST] =
750 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_REQUEST,
751 flags & BDRV_O_UNMAP);
752 r->discard_passthrough[QCOW2_DISCARD_SNAPSHOT] =
753 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_SNAPSHOT, true);
754 r->discard_passthrough[QCOW2_DISCARD_OTHER] =
755 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_OTHER, false);
764 static void qcow2_update_options_commit(BlockDriverState *bs,
767 BDRVQcow2State *s = bs->opaque;
770 if (s->l2_table_cache) {
771 qcow2_cache_destroy(bs, s->l2_table_cache);
773 if (s->refcount_block_cache) {
774 qcow2_cache_destroy(bs, s->refcount_block_cache);
776 s->l2_table_cache = r->l2_table_cache;
777 s->refcount_block_cache = r->refcount_block_cache;
779 s->overlap_check = r->overlap_check;
780 s->use_lazy_refcounts = r->use_lazy_refcounts;
782 for (i = 0; i < QCOW2_DISCARD_MAX; i++) {
783 s->discard_passthrough[i] = r->discard_passthrough[i];
786 if (s->cache_clean_interval != r->cache_clean_interval) {
787 cache_clean_timer_del(bs);
788 s->cache_clean_interval = r->cache_clean_interval;
789 cache_clean_timer_init(bs, bdrv_get_aio_context(bs));
793 static void qcow2_update_options_abort(BlockDriverState *bs,
796 if (r->l2_table_cache) {
797 qcow2_cache_destroy(bs, r->l2_table_cache);
799 if (r->refcount_block_cache) {
800 qcow2_cache_destroy(bs, r->refcount_block_cache);
804 static int qcow2_update_options(BlockDriverState *bs, QDict *options,
805 int flags, Error **errp)
807 Qcow2ReopenState r = {};
810 ret = qcow2_update_options_prepare(bs, &r, options, flags, errp);
812 qcow2_update_options_commit(bs, &r);
814 qcow2_update_options_abort(bs, &r);
820 static int qcow2_open(BlockDriverState *bs, QDict *options, int flags,
823 BDRVQcow2State *s = bs->opaque;
827 Error *local_err = NULL;
829 uint64_t l1_vm_state_index;
831 ret = bdrv_pread(bs->file->bs, 0, &header, sizeof(header));
833 error_setg_errno(errp, -ret, "Could not read qcow2 header");
836 be32_to_cpus(&header.magic);
837 be32_to_cpus(&header.version);
838 be64_to_cpus(&header.backing_file_offset);
839 be32_to_cpus(&header.backing_file_size);
840 be64_to_cpus(&header.size);
841 be32_to_cpus(&header.cluster_bits);
842 be32_to_cpus(&header.crypt_method);
843 be64_to_cpus(&header.l1_table_offset);
844 be32_to_cpus(&header.l1_size);
845 be64_to_cpus(&header.refcount_table_offset);
846 be32_to_cpus(&header.refcount_table_clusters);
847 be64_to_cpus(&header.snapshots_offset);
848 be32_to_cpus(&header.nb_snapshots);
850 if (header.magic != QCOW_MAGIC) {
851 error_setg(errp, "Image is not in qcow2 format");
855 if (header.version < 2 || header.version > 3) {
856 report_unsupported(bs, errp, "QCOW version %" PRIu32, header.version);
861 s->qcow_version = header.version;
863 /* Initialise cluster size */
864 if (header.cluster_bits < MIN_CLUSTER_BITS ||
865 header.cluster_bits > MAX_CLUSTER_BITS) {
866 error_setg(errp, "Unsupported cluster size: 2^%" PRIu32,
867 header.cluster_bits);
872 s->cluster_bits = header.cluster_bits;
873 s->cluster_size = 1 << s->cluster_bits;
874 s->cluster_sectors = 1 << (s->cluster_bits - 9);
876 /* Initialise version 3 header fields */
877 if (header.version == 2) {
878 header.incompatible_features = 0;
879 header.compatible_features = 0;
880 header.autoclear_features = 0;
881 header.refcount_order = 4;
882 header.header_length = 72;
884 be64_to_cpus(&header.incompatible_features);
885 be64_to_cpus(&header.compatible_features);
886 be64_to_cpus(&header.autoclear_features);
887 be32_to_cpus(&header.refcount_order);
888 be32_to_cpus(&header.header_length);
890 if (header.header_length < 104) {
891 error_setg(errp, "qcow2 header too short");
897 if (header.header_length > s->cluster_size) {
898 error_setg(errp, "qcow2 header exceeds cluster size");
903 if (header.header_length > sizeof(header)) {
904 s->unknown_header_fields_size = header.header_length - sizeof(header);
905 s->unknown_header_fields = g_malloc(s->unknown_header_fields_size);
906 ret = bdrv_pread(bs->file->bs, sizeof(header), s->unknown_header_fields,
907 s->unknown_header_fields_size);
909 error_setg_errno(errp, -ret, "Could not read unknown qcow2 header "
915 if (header.backing_file_offset > s->cluster_size) {
916 error_setg(errp, "Invalid backing file offset");
921 if (header.backing_file_offset) {
922 ext_end = header.backing_file_offset;
924 ext_end = 1 << header.cluster_bits;
927 /* Handle feature bits */
928 s->incompatible_features = header.incompatible_features;
929 s->compatible_features = header.compatible_features;
930 s->autoclear_features = header.autoclear_features;
932 if (s->incompatible_features & ~QCOW2_INCOMPAT_MASK) {
933 void *feature_table = NULL;
934 qcow2_read_extensions(bs, header.header_length, ext_end,
935 &feature_table, NULL);
936 report_unsupported_feature(bs, errp, feature_table,
937 s->incompatible_features &
938 ~QCOW2_INCOMPAT_MASK);
940 g_free(feature_table);
944 if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
945 /* Corrupt images may not be written to unless they are being repaired
947 if ((flags & BDRV_O_RDWR) && !(flags & BDRV_O_CHECK)) {
948 error_setg(errp, "qcow2: Image is corrupt; cannot be opened "
955 /* Check support for various header values */
956 if (header.refcount_order > 6) {
957 error_setg(errp, "Reference count entry width too large; may not "
962 s->refcount_order = header.refcount_order;
963 s->refcount_bits = 1 << s->refcount_order;
964 s->refcount_max = UINT64_C(1) << (s->refcount_bits - 1);
965 s->refcount_max += s->refcount_max - 1;
967 if (header.crypt_method > QCOW_CRYPT_AES) {
968 error_setg(errp, "Unsupported encryption method: %" PRIu32,
969 header.crypt_method);
973 if (!qcrypto_cipher_supports(QCRYPTO_CIPHER_ALG_AES_128)) {
974 error_setg(errp, "AES cipher not available");
978 s->crypt_method_header = header.crypt_method;
979 if (s->crypt_method_header) {
983 s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */
984 s->l2_size = 1 << s->l2_bits;
985 /* 2^(s->refcount_order - 3) is the refcount width in bytes */
986 s->refcount_block_bits = s->cluster_bits - (s->refcount_order - 3);
987 s->refcount_block_size = 1 << s->refcount_block_bits;
988 bs->total_sectors = header.size / 512;
989 s->csize_shift = (62 - (s->cluster_bits - 8));
990 s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;
991 s->cluster_offset_mask = (1LL << s->csize_shift) - 1;
993 s->refcount_table_offset = header.refcount_table_offset;
994 s->refcount_table_size =
995 header.refcount_table_clusters << (s->cluster_bits - 3);
997 if (header.refcount_table_clusters > qcow2_max_refcount_clusters(s)) {
998 error_setg(errp, "Reference count table too large");
1003 ret = validate_table_offset(bs, s->refcount_table_offset,
1004 s->refcount_table_size, sizeof(uint64_t));
1006 error_setg(errp, "Invalid reference count table offset");
1010 /* Snapshot table offset/length */
1011 if (header.nb_snapshots > QCOW_MAX_SNAPSHOTS) {
1012 error_setg(errp, "Too many snapshots");
1017 ret = validate_table_offset(bs, header.snapshots_offset,
1018 header.nb_snapshots,
1019 sizeof(QCowSnapshotHeader));
1021 error_setg(errp, "Invalid snapshot table offset");
1025 /* read the level 1 table */
1026 if (header.l1_size > QCOW_MAX_L1_SIZE / sizeof(uint64_t)) {
1027 error_setg(errp, "Active L1 table too large");
1031 s->l1_size = header.l1_size;
1033 l1_vm_state_index = size_to_l1(s, header.size);
1034 if (l1_vm_state_index > INT_MAX) {
1035 error_setg(errp, "Image is too big");
1039 s->l1_vm_state_index = l1_vm_state_index;
1041 /* the L1 table must contain at least enough entries to put
1042 header.size bytes */
1043 if (s->l1_size < s->l1_vm_state_index) {
1044 error_setg(errp, "L1 table is too small");
1049 ret = validate_table_offset(bs, header.l1_table_offset,
1050 header.l1_size, sizeof(uint64_t));
1052 error_setg(errp, "Invalid L1 table offset");
1055 s->l1_table_offset = header.l1_table_offset;
1058 if (s->l1_size > 0) {
1059 s->l1_table = qemu_try_blockalign(bs->file->bs,
1060 align_offset(s->l1_size * sizeof(uint64_t), 512));
1061 if (s->l1_table == NULL) {
1062 error_setg(errp, "Could not allocate L1 table");
1066 ret = bdrv_pread(bs->file->bs, s->l1_table_offset, s->l1_table,
1067 s->l1_size * sizeof(uint64_t));
1069 error_setg_errno(errp, -ret, "Could not read L1 table");
1072 for(i = 0;i < s->l1_size; i++) {
1073 be64_to_cpus(&s->l1_table[i]);
1077 /* Parse driver-specific options */
1078 ret = qcow2_update_options(bs, options, flags, errp);
1083 s->cluster_cache = g_malloc(s->cluster_size);
1084 /* one more sector for decompressed data alignment */
1085 s->cluster_data = qemu_try_blockalign(bs->file->bs, QCOW_MAX_CRYPT_CLUSTERS
1086 * s->cluster_size + 512);
1087 if (s->cluster_data == NULL) {
1088 error_setg(errp, "Could not allocate temporary cluster buffer");
1093 s->cluster_cache_offset = -1;
1096 ret = qcow2_refcount_init(bs);
1098 error_setg_errno(errp, -ret, "Could not initialize refcount handling");
1102 QLIST_INIT(&s->cluster_allocs);
1103 QTAILQ_INIT(&s->discards);
1105 /* read qcow2 extensions */
1106 if (qcow2_read_extensions(bs, header.header_length, ext_end, NULL,
1108 error_propagate(errp, local_err);
1113 /* read the backing file name */
1114 if (header.backing_file_offset != 0) {
1115 len = header.backing_file_size;
1116 if (len > MIN(1023, s->cluster_size - header.backing_file_offset) ||
1117 len >= sizeof(bs->backing_file)) {
1118 error_setg(errp, "Backing file name too long");
1122 ret = bdrv_pread(bs->file->bs, header.backing_file_offset,
1123 bs->backing_file, len);
1125 error_setg_errno(errp, -ret, "Could not read backing file name");
1128 bs->backing_file[len] = '\0';
1129 s->image_backing_file = g_strdup(bs->backing_file);
1132 /* Internal snapshots */
1133 s->snapshots_offset = header.snapshots_offset;
1134 s->nb_snapshots = header.nb_snapshots;
1136 ret = qcow2_read_snapshots(bs);
1138 error_setg_errno(errp, -ret, "Could not read snapshots");
1142 /* Clear unknown autoclear feature bits */
1143 if (!bs->read_only && !(flags & BDRV_O_INCOMING) && s->autoclear_features) {
1144 s->autoclear_features = 0;
1145 ret = qcow2_update_header(bs);
1147 error_setg_errno(errp, -ret, "Could not update qcow2 header");
1152 /* Initialise locks */
1153 qemu_co_mutex_init(&s->lock);
1155 /* Repair image if dirty */
1156 if (!(flags & (BDRV_O_CHECK | BDRV_O_INCOMING)) && !bs->read_only &&
1157 (s->incompatible_features & QCOW2_INCOMPAT_DIRTY)) {
1158 BdrvCheckResult result = {0};
1160 ret = qcow2_check(bs, &result, BDRV_FIX_ERRORS | BDRV_FIX_LEAKS);
1162 error_setg_errno(errp, -ret, "Could not repair dirty image");
1169 BdrvCheckResult result = {0};
1170 qcow2_check_refcounts(bs, &result, 0);
1176 g_free(s->unknown_header_fields);
1177 cleanup_unknown_header_ext(bs);
1178 qcow2_free_snapshots(bs);
1179 qcow2_refcount_close(bs);
1180 qemu_vfree(s->l1_table);
1181 /* else pre-write overlap checks in cache_destroy may crash */
1183 cache_clean_timer_del(bs);
1184 if (s->l2_table_cache) {
1185 qcow2_cache_destroy(bs, s->l2_table_cache);
1187 if (s->refcount_block_cache) {
1188 qcow2_cache_destroy(bs, s->refcount_block_cache);
1190 g_free(s->cluster_cache);
1191 qemu_vfree(s->cluster_data);
1195 static void qcow2_refresh_limits(BlockDriverState *bs, Error **errp)
1197 BDRVQcow2State *s = bs->opaque;
1199 bs->bl.write_zeroes_alignment = s->cluster_sectors;
1202 static int qcow2_set_key(BlockDriverState *bs, const char *key)
1204 BDRVQcow2State *s = bs->opaque;
1209 memset(keybuf, 0, 16);
1213 /* XXX: we could compress the chars to 7 bits to increase
1215 for(i = 0;i < len;i++) {
1218 assert(bs->encrypted);
1220 qcrypto_cipher_free(s->cipher);
1221 s->cipher = qcrypto_cipher_new(
1222 QCRYPTO_CIPHER_ALG_AES_128,
1223 QCRYPTO_CIPHER_MODE_CBC,
1224 keybuf, G_N_ELEMENTS(keybuf),
1228 /* XXX would be nice if errors in this method could
1229 * be properly propagate to the caller. Would need
1230 * the bdrv_set_key() API signature to be fixed. */
1237 static int qcow2_reopen_prepare(BDRVReopenState *state,
1238 BlockReopenQueue *queue, Error **errp)
1240 Qcow2ReopenState *r;
1243 r = g_new0(Qcow2ReopenState, 1);
1246 ret = qcow2_update_options_prepare(state->bs, r, state->options,
1247 state->flags, errp);
1252 /* We need to write out any unwritten data if we reopen read-only. */
1253 if ((state->flags & BDRV_O_RDWR) == 0) {
1254 ret = bdrv_flush(state->bs);
1259 ret = qcow2_mark_clean(state->bs);
1268 qcow2_update_options_abort(state->bs, r);
1273 static void qcow2_reopen_commit(BDRVReopenState *state)
1275 qcow2_update_options_commit(state->bs, state->opaque);
1276 g_free(state->opaque);
1279 static void qcow2_reopen_abort(BDRVReopenState *state)
1281 qcow2_update_options_abort(state->bs, state->opaque);
1282 g_free(state->opaque);
1285 static int64_t coroutine_fn qcow2_co_get_block_status(BlockDriverState *bs,
1286 int64_t sector_num, int nb_sectors, int *pnum)
1288 BDRVQcow2State *s = bs->opaque;
1289 uint64_t cluster_offset;
1290 int index_in_cluster, ret;
1294 qemu_co_mutex_lock(&s->lock);
1295 ret = qcow2_get_cluster_offset(bs, sector_num << 9, pnum, &cluster_offset);
1296 qemu_co_mutex_unlock(&s->lock);
1301 if (cluster_offset != 0 && ret != QCOW2_CLUSTER_COMPRESSED &&
1303 index_in_cluster = sector_num & (s->cluster_sectors - 1);
1304 cluster_offset |= (index_in_cluster << BDRV_SECTOR_BITS);
1305 status |= BDRV_BLOCK_OFFSET_VALID | cluster_offset;
1307 if (ret == QCOW2_CLUSTER_ZERO) {
1308 status |= BDRV_BLOCK_ZERO;
1309 } else if (ret != QCOW2_CLUSTER_UNALLOCATED) {
1310 status |= BDRV_BLOCK_DATA;
1315 /* handle reading after the end of the backing file */
1316 int qcow2_backing_read1(BlockDriverState *bs, QEMUIOVector *qiov,
1317 int64_t sector_num, int nb_sectors)
1320 if ((sector_num + nb_sectors) <= bs->total_sectors)
1322 if (sector_num >= bs->total_sectors)
1325 n1 = bs->total_sectors - sector_num;
1327 qemu_iovec_memset(qiov, 512 * n1, 0, 512 * (nb_sectors - n1));
1332 static coroutine_fn int qcow2_co_readv(BlockDriverState *bs, int64_t sector_num,
1333 int remaining_sectors, QEMUIOVector *qiov)
1335 BDRVQcow2State *s = bs->opaque;
1336 int index_in_cluster, n1;
1338 int cur_nr_sectors; /* number of sectors in current iteration */
1339 uint64_t cluster_offset = 0;
1340 uint64_t bytes_done = 0;
1341 QEMUIOVector hd_qiov;
1342 uint8_t *cluster_data = NULL;
1344 qemu_iovec_init(&hd_qiov, qiov->niov);
1346 qemu_co_mutex_lock(&s->lock);
1348 while (remaining_sectors != 0) {
1350 /* prepare next request */
1351 cur_nr_sectors = remaining_sectors;
1353 cur_nr_sectors = MIN(cur_nr_sectors,
1354 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors);
1357 ret = qcow2_get_cluster_offset(bs, sector_num << 9,
1358 &cur_nr_sectors, &cluster_offset);
1363 index_in_cluster = sector_num & (s->cluster_sectors - 1);
1365 qemu_iovec_reset(&hd_qiov);
1366 qemu_iovec_concat(&hd_qiov, qiov, bytes_done,
1367 cur_nr_sectors * 512);
1370 case QCOW2_CLUSTER_UNALLOCATED:
1373 /* read from the base image */
1374 n1 = qcow2_backing_read1(bs->backing->bs, &hd_qiov,
1375 sector_num, cur_nr_sectors);
1377 QEMUIOVector local_qiov;
1379 qemu_iovec_init(&local_qiov, hd_qiov.niov);
1380 qemu_iovec_concat(&local_qiov, &hd_qiov, 0,
1381 n1 * BDRV_SECTOR_SIZE);
1383 BLKDBG_EVENT(bs->file, BLKDBG_READ_BACKING_AIO);
1384 qemu_co_mutex_unlock(&s->lock);
1385 ret = bdrv_co_readv(bs->backing->bs, sector_num,
1387 qemu_co_mutex_lock(&s->lock);
1389 qemu_iovec_destroy(&local_qiov);
1396 /* Note: in this case, no need to wait */
1397 qemu_iovec_memset(&hd_qiov, 0, 0, 512 * cur_nr_sectors);
1401 case QCOW2_CLUSTER_ZERO:
1402 qemu_iovec_memset(&hd_qiov, 0, 0, 512 * cur_nr_sectors);
1405 case QCOW2_CLUSTER_COMPRESSED:
1406 /* add AIO support for compressed blocks ? */
1407 ret = qcow2_decompress_cluster(bs, cluster_offset);
1412 qemu_iovec_from_buf(&hd_qiov, 0,
1413 s->cluster_cache + index_in_cluster * 512,
1414 512 * cur_nr_sectors);
1417 case QCOW2_CLUSTER_NORMAL:
1418 if ((cluster_offset & 511) != 0) {
1423 if (bs->encrypted) {
1427 * For encrypted images, read everything into a temporary
1428 * contiguous buffer on which the AES functions can work.
1430 if (!cluster_data) {
1432 qemu_try_blockalign(bs->file->bs,
1433 QCOW_MAX_CRYPT_CLUSTERS
1435 if (cluster_data == NULL) {
1441 assert(cur_nr_sectors <=
1442 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors);
1443 qemu_iovec_reset(&hd_qiov);
1444 qemu_iovec_add(&hd_qiov, cluster_data,
1445 512 * cur_nr_sectors);
1448 BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);
1449 qemu_co_mutex_unlock(&s->lock);
1450 ret = bdrv_co_readv(bs->file->bs,
1451 (cluster_offset >> 9) + index_in_cluster,
1452 cur_nr_sectors, &hd_qiov);
1453 qemu_co_mutex_lock(&s->lock);
1457 if (bs->encrypted) {
1460 if (qcow2_encrypt_sectors(s, sector_num, cluster_data,
1461 cluster_data, cur_nr_sectors, false,
1467 qemu_iovec_from_buf(qiov, bytes_done,
1468 cluster_data, 512 * cur_nr_sectors);
1473 g_assert_not_reached();
1478 remaining_sectors -= cur_nr_sectors;
1479 sector_num += cur_nr_sectors;
1480 bytes_done += cur_nr_sectors * 512;
1485 qemu_co_mutex_unlock(&s->lock);
1487 qemu_iovec_destroy(&hd_qiov);
1488 qemu_vfree(cluster_data);
1493 static coroutine_fn int qcow2_co_writev(BlockDriverState *bs,
1495 int remaining_sectors,
1498 BDRVQcow2State *s = bs->opaque;
1499 int index_in_cluster;
1501 int cur_nr_sectors; /* number of sectors in current iteration */
1502 uint64_t cluster_offset;
1503 QEMUIOVector hd_qiov;
1504 uint64_t bytes_done = 0;
1505 uint8_t *cluster_data = NULL;
1506 QCowL2Meta *l2meta = NULL;
1508 trace_qcow2_writev_start_req(qemu_coroutine_self(), sector_num,
1511 qemu_iovec_init(&hd_qiov, qiov->niov);
1513 s->cluster_cache_offset = -1; /* disable compressed cache */
1515 qemu_co_mutex_lock(&s->lock);
1517 while (remaining_sectors != 0) {
1521 trace_qcow2_writev_start_part(qemu_coroutine_self());
1522 index_in_cluster = sector_num & (s->cluster_sectors - 1);
1523 cur_nr_sectors = remaining_sectors;
1524 if (bs->encrypted &&
1526 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors - index_in_cluster) {
1528 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors - index_in_cluster;
1531 ret = qcow2_alloc_cluster_offset(bs, sector_num << 9,
1532 &cur_nr_sectors, &cluster_offset, &l2meta);
1537 assert((cluster_offset & 511) == 0);
1539 qemu_iovec_reset(&hd_qiov);
1540 qemu_iovec_concat(&hd_qiov, qiov, bytes_done,
1541 cur_nr_sectors * 512);
1543 if (bs->encrypted) {
1546 if (!cluster_data) {
1547 cluster_data = qemu_try_blockalign(bs->file->bs,
1548 QCOW_MAX_CRYPT_CLUSTERS
1550 if (cluster_data == NULL) {
1556 assert(hd_qiov.size <=
1557 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
1558 qemu_iovec_to_buf(&hd_qiov, 0, cluster_data, hd_qiov.size);
1560 if (qcow2_encrypt_sectors(s, sector_num, cluster_data,
1561 cluster_data, cur_nr_sectors,
1568 qemu_iovec_reset(&hd_qiov);
1569 qemu_iovec_add(&hd_qiov, cluster_data,
1570 cur_nr_sectors * 512);
1573 ret = qcow2_pre_write_overlap_check(bs, 0,
1574 cluster_offset + index_in_cluster * BDRV_SECTOR_SIZE,
1575 cur_nr_sectors * BDRV_SECTOR_SIZE);
1580 qemu_co_mutex_unlock(&s->lock);
1581 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO);
1582 trace_qcow2_writev_data(qemu_coroutine_self(),
1583 (cluster_offset >> 9) + index_in_cluster);
1584 ret = bdrv_co_writev(bs->file->bs,
1585 (cluster_offset >> 9) + index_in_cluster,
1586 cur_nr_sectors, &hd_qiov);
1587 qemu_co_mutex_lock(&s->lock);
1592 while (l2meta != NULL) {
1595 ret = qcow2_alloc_cluster_link_l2(bs, l2meta);
1600 /* Take the request off the list of running requests */
1601 if (l2meta->nb_clusters != 0) {
1602 QLIST_REMOVE(l2meta, next_in_flight);
1605 qemu_co_queue_restart_all(&l2meta->dependent_requests);
1607 next = l2meta->next;
1612 remaining_sectors -= cur_nr_sectors;
1613 sector_num += cur_nr_sectors;
1614 bytes_done += cur_nr_sectors * 512;
1615 trace_qcow2_writev_done_part(qemu_coroutine_self(), cur_nr_sectors);
1620 qemu_co_mutex_unlock(&s->lock);
1622 while (l2meta != NULL) {
1625 if (l2meta->nb_clusters != 0) {
1626 QLIST_REMOVE(l2meta, next_in_flight);
1628 qemu_co_queue_restart_all(&l2meta->dependent_requests);
1630 next = l2meta->next;
1635 qemu_iovec_destroy(&hd_qiov);
1636 qemu_vfree(cluster_data);
1637 trace_qcow2_writev_done_req(qemu_coroutine_self(), ret);
1642 static void qcow2_close(BlockDriverState *bs)
1644 BDRVQcow2State *s = bs->opaque;
1645 qemu_vfree(s->l1_table);
1646 /* else pre-write overlap checks in cache_destroy may crash */
1649 if (!(bs->open_flags & BDRV_O_INCOMING)) {
1652 ret1 = qcow2_cache_flush(bs, s->l2_table_cache);
1653 ret2 = qcow2_cache_flush(bs, s->refcount_block_cache);
1656 error_report("Failed to flush the L2 table cache: %s",
1660 error_report("Failed to flush the refcount block cache: %s",
1664 if (!ret1 && !ret2) {
1665 qcow2_mark_clean(bs);
1669 cache_clean_timer_del(bs);
1670 qcow2_cache_destroy(bs, s->l2_table_cache);
1671 qcow2_cache_destroy(bs, s->refcount_block_cache);
1673 qcrypto_cipher_free(s->cipher);
1676 g_free(s->unknown_header_fields);
1677 cleanup_unknown_header_ext(bs);
1679 g_free(s->image_backing_file);
1680 g_free(s->image_backing_format);
1682 g_free(s->cluster_cache);
1683 qemu_vfree(s->cluster_data);
1684 qcow2_refcount_close(bs);
1685 qcow2_free_snapshots(bs);
1688 static void qcow2_invalidate_cache(BlockDriverState *bs, Error **errp)
1690 BDRVQcow2State *s = bs->opaque;
1691 int flags = s->flags;
1692 QCryptoCipher *cipher = NULL;
1694 Error *local_err = NULL;
1698 * Backing files are read-only which makes all of their metadata immutable,
1699 * that means we don't have to worry about reopening them here.
1707 bdrv_invalidate_cache(bs->file->bs, &local_err);
1709 error_propagate(errp, local_err);
1713 memset(s, 0, sizeof(BDRVQcow2State));
1714 options = qdict_clone_shallow(bs->options);
1716 ret = qcow2_open(bs, options, flags, &local_err);
1719 error_setg(errp, "Could not reopen qcow2 layer: %s",
1720 error_get_pretty(local_err));
1721 error_free(local_err);
1723 } else if (ret < 0) {
1724 error_setg_errno(errp, -ret, "Could not reopen qcow2 layer");
1731 static size_t header_ext_add(char *buf, uint32_t magic, const void *s,
1732 size_t len, size_t buflen)
1734 QCowExtension *ext_backing_fmt = (QCowExtension*) buf;
1735 size_t ext_len = sizeof(QCowExtension) + ((len + 7) & ~7);
1737 if (buflen < ext_len) {
1741 *ext_backing_fmt = (QCowExtension) {
1742 .magic = cpu_to_be32(magic),
1743 .len = cpu_to_be32(len),
1745 memcpy(buf + sizeof(QCowExtension), s, len);
1751 * Updates the qcow2 header, including the variable length parts of it, i.e.
1752 * the backing file name and all extensions. qcow2 was not designed to allow
1753 * such changes, so if we run out of space (we can only use the first cluster)
1754 * this function may fail.
1756 * Returns 0 on success, -errno in error cases.
1758 int qcow2_update_header(BlockDriverState *bs)
1760 BDRVQcow2State *s = bs->opaque;
1763 size_t buflen = s->cluster_size;
1765 uint64_t total_size;
1766 uint32_t refcount_table_clusters;
1767 size_t header_length;
1768 Qcow2UnknownHeaderExtension *uext;
1770 buf = qemu_blockalign(bs, buflen);
1772 /* Header structure */
1773 header = (QCowHeader*) buf;
1775 if (buflen < sizeof(*header)) {
1780 header_length = sizeof(*header) + s->unknown_header_fields_size;
1781 total_size = bs->total_sectors * BDRV_SECTOR_SIZE;
1782 refcount_table_clusters = s->refcount_table_size >> (s->cluster_bits - 3);
1784 *header = (QCowHeader) {
1785 /* Version 2 fields */
1786 .magic = cpu_to_be32(QCOW_MAGIC),
1787 .version = cpu_to_be32(s->qcow_version),
1788 .backing_file_offset = 0,
1789 .backing_file_size = 0,
1790 .cluster_bits = cpu_to_be32(s->cluster_bits),
1791 .size = cpu_to_be64(total_size),
1792 .crypt_method = cpu_to_be32(s->crypt_method_header),
1793 .l1_size = cpu_to_be32(s->l1_size),
1794 .l1_table_offset = cpu_to_be64(s->l1_table_offset),
1795 .refcount_table_offset = cpu_to_be64(s->refcount_table_offset),
1796 .refcount_table_clusters = cpu_to_be32(refcount_table_clusters),
1797 .nb_snapshots = cpu_to_be32(s->nb_snapshots),
1798 .snapshots_offset = cpu_to_be64(s->snapshots_offset),
1800 /* Version 3 fields */
1801 .incompatible_features = cpu_to_be64(s->incompatible_features),
1802 .compatible_features = cpu_to_be64(s->compatible_features),
1803 .autoclear_features = cpu_to_be64(s->autoclear_features),
1804 .refcount_order = cpu_to_be32(s->refcount_order),
1805 .header_length = cpu_to_be32(header_length),
1808 /* For older versions, write a shorter header */
1809 switch (s->qcow_version) {
1811 ret = offsetof(QCowHeader, incompatible_features);
1814 ret = sizeof(*header);
1823 memset(buf, 0, buflen);
1825 /* Preserve any unknown field in the header */
1826 if (s->unknown_header_fields_size) {
1827 if (buflen < s->unknown_header_fields_size) {
1832 memcpy(buf, s->unknown_header_fields, s->unknown_header_fields_size);
1833 buf += s->unknown_header_fields_size;
1834 buflen -= s->unknown_header_fields_size;
1837 /* Backing file format header extension */
1838 if (s->image_backing_format) {
1839 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BACKING_FORMAT,
1840 s->image_backing_format,
1841 strlen(s->image_backing_format),
1852 Qcow2Feature features[] = {
1854 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
1855 .bit = QCOW2_INCOMPAT_DIRTY_BITNR,
1856 .name = "dirty bit",
1859 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
1860 .bit = QCOW2_INCOMPAT_CORRUPT_BITNR,
1861 .name = "corrupt bit",
1864 .type = QCOW2_FEAT_TYPE_COMPATIBLE,
1865 .bit = QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR,
1866 .name = "lazy refcounts",
1870 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_FEATURE_TABLE,
1871 features, sizeof(features), buflen);
1878 /* Keep unknown header extensions */
1879 QLIST_FOREACH(uext, &s->unknown_header_ext, next) {
1880 ret = header_ext_add(buf, uext->magic, uext->data, uext->len, buflen);
1889 /* End of header extensions */
1890 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_END, NULL, 0, buflen);
1898 /* Backing file name */
1899 if (s->image_backing_file) {
1900 size_t backing_file_len = strlen(s->image_backing_file);
1902 if (buflen < backing_file_len) {
1907 /* Using strncpy is ok here, since buf is not NUL-terminated. */
1908 strncpy(buf, s->image_backing_file, buflen);
1910 header->backing_file_offset = cpu_to_be64(buf - ((char*) header));
1911 header->backing_file_size = cpu_to_be32(backing_file_len);
1914 /* Write the new header */
1915 ret = bdrv_pwrite(bs->file->bs, 0, header, s->cluster_size);
1926 static int qcow2_change_backing_file(BlockDriverState *bs,
1927 const char *backing_file, const char *backing_fmt)
1929 BDRVQcow2State *s = bs->opaque;
1931 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
1932 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
1934 g_free(s->image_backing_file);
1935 g_free(s->image_backing_format);
1937 s->image_backing_file = backing_file ? g_strdup(bs->backing_file) : NULL;
1938 s->image_backing_format = backing_fmt ? g_strdup(bs->backing_format) : NULL;
1940 return qcow2_update_header(bs);
1943 static int preallocate(BlockDriverState *bs)
1945 uint64_t nb_sectors;
1947 uint64_t host_offset = 0;
1952 nb_sectors = bdrv_nb_sectors(bs);
1955 while (nb_sectors) {
1956 num = MIN(nb_sectors, INT_MAX >> BDRV_SECTOR_BITS);
1957 ret = qcow2_alloc_cluster_offset(bs, offset, &num,
1958 &host_offset, &meta);
1964 QCowL2Meta *next = meta->next;
1966 ret = qcow2_alloc_cluster_link_l2(bs, meta);
1968 qcow2_free_any_clusters(bs, meta->alloc_offset,
1969 meta->nb_clusters, QCOW2_DISCARD_NEVER);
1973 /* There are no dependent requests, but we need to remove our
1974 * request from the list of in-flight requests */
1975 QLIST_REMOVE(meta, next_in_flight);
1981 /* TODO Preallocate data if requested */
1984 offset += num << BDRV_SECTOR_BITS;
1988 * It is expected that the image file is large enough to actually contain
1989 * all of the allocated clusters (otherwise we get failing reads after
1990 * EOF). Extend the image to the last allocated sector.
1992 if (host_offset != 0) {
1993 uint8_t buf[BDRV_SECTOR_SIZE];
1994 memset(buf, 0, BDRV_SECTOR_SIZE);
1995 ret = bdrv_write(bs->file->bs,
1996 (host_offset >> BDRV_SECTOR_BITS) + num - 1,
2006 static int qcow2_create2(const char *filename, int64_t total_size,
2007 const char *backing_file, const char *backing_format,
2008 int flags, size_t cluster_size, PreallocMode prealloc,
2009 QemuOpts *opts, int version, int refcount_order,
2015 /* Calculate cluster_bits */
2016 cluster_bits = ctz32(cluster_size);
2017 if (cluster_bits < MIN_CLUSTER_BITS || cluster_bits > MAX_CLUSTER_BITS ||
2018 (1 << cluster_bits) != cluster_size)
2020 error_setg(errp, "Cluster size must be a power of two between %d and "
2021 "%dk", 1 << MIN_CLUSTER_BITS, 1 << (MAX_CLUSTER_BITS - 10));
2026 * Open the image file and write a minimal qcow2 header.
2028 * We keep things simple and start with a zero-sized image. We also
2029 * do without refcount blocks or a L1 table for now. We'll fix the
2030 * inconsistency later.
2032 * We do need a refcount table because growing the refcount table means
2033 * allocating two new refcount blocks - the seconds of which would be at
2034 * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
2035 * size for any qcow2 image.
2037 BlockDriverState* bs;
2039 uint64_t* refcount_table;
2040 Error *local_err = NULL;
2043 if (prealloc == PREALLOC_MODE_FULL || prealloc == PREALLOC_MODE_FALLOC) {
2044 /* Note: The following calculation does not need to be exact; if it is a
2045 * bit off, either some bytes will be "leaked" (which is fine) or we
2046 * will need to increase the file size by some bytes (which is fine,
2047 * too, as long as the bulk is allocated here). Therefore, using
2048 * floating point arithmetic is fine. */
2049 int64_t meta_size = 0;
2050 uint64_t nreftablee, nrefblocke, nl1e, nl2e;
2051 int64_t aligned_total_size = align_offset(total_size, cluster_size);
2052 int refblock_bits, refblock_size;
2053 /* refcount entry size in bytes */
2054 double rces = (1 << refcount_order) / 8.;
2056 /* see qcow2_open() */
2057 refblock_bits = cluster_bits - (refcount_order - 3);
2058 refblock_size = 1 << refblock_bits;
2060 /* header: 1 cluster */
2061 meta_size += cluster_size;
2063 /* total size of L2 tables */
2064 nl2e = aligned_total_size / cluster_size;
2065 nl2e = align_offset(nl2e, cluster_size / sizeof(uint64_t));
2066 meta_size += nl2e * sizeof(uint64_t);
2068 /* total size of L1 tables */
2069 nl1e = nl2e * sizeof(uint64_t) / cluster_size;
2070 nl1e = align_offset(nl1e, cluster_size / sizeof(uint64_t));
2071 meta_size += nl1e * sizeof(uint64_t);
2073 /* total size of refcount blocks
2075 * note: every host cluster is reference-counted, including metadata
2076 * (even refcount blocks are recursively included).
2078 * a = total_size (this is the guest disk size)
2079 * m = meta size not including refcount blocks and refcount tables
2081 * y1 = number of refcount blocks entries
2082 * y2 = meta size including everything
2083 * rces = refcount entry size in bytes
2086 * y2 = y1 * rces + y1 * rces * sizeof(u64) / c + m
2088 * y1 = (a + m) / (c - rces - rces * sizeof(u64) / c)
2090 nrefblocke = (aligned_total_size + meta_size + cluster_size)
2091 / (cluster_size - rces - rces * sizeof(uint64_t)
2093 meta_size += DIV_ROUND_UP(nrefblocke, refblock_size) * cluster_size;
2095 /* total size of refcount tables */
2096 nreftablee = nrefblocke / refblock_size;
2097 nreftablee = align_offset(nreftablee, cluster_size / sizeof(uint64_t));
2098 meta_size += nreftablee * sizeof(uint64_t);
2100 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
2101 aligned_total_size + meta_size, &error_abort);
2102 qemu_opt_set(opts, BLOCK_OPT_PREALLOC, PreallocMode_lookup[prealloc],
2106 ret = bdrv_create_file(filename, opts, &local_err);
2108 error_propagate(errp, local_err);
2113 ret = bdrv_open(&bs, filename, NULL, NULL, BDRV_O_RDWR | BDRV_O_PROTOCOL,
2116 error_propagate(errp, local_err);
2120 /* Write the header */
2121 QEMU_BUILD_BUG_ON((1 << MIN_CLUSTER_BITS) < sizeof(*header));
2122 header = g_malloc0(cluster_size);
2123 *header = (QCowHeader) {
2124 .magic = cpu_to_be32(QCOW_MAGIC),
2125 .version = cpu_to_be32(version),
2126 .cluster_bits = cpu_to_be32(cluster_bits),
2127 .size = cpu_to_be64(0),
2128 .l1_table_offset = cpu_to_be64(0),
2129 .l1_size = cpu_to_be32(0),
2130 .refcount_table_offset = cpu_to_be64(cluster_size),
2131 .refcount_table_clusters = cpu_to_be32(1),
2132 .refcount_order = cpu_to_be32(refcount_order),
2133 .header_length = cpu_to_be32(sizeof(*header)),
2136 if (flags & BLOCK_FLAG_ENCRYPT) {
2137 header->crypt_method = cpu_to_be32(QCOW_CRYPT_AES);
2139 header->crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
2142 if (flags & BLOCK_FLAG_LAZY_REFCOUNTS) {
2143 header->compatible_features |=
2144 cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS);
2147 ret = bdrv_pwrite(bs, 0, header, cluster_size);
2150 error_setg_errno(errp, -ret, "Could not write qcow2 header");
2154 /* Write a refcount table with one refcount block */
2155 refcount_table = g_malloc0(2 * cluster_size);
2156 refcount_table[0] = cpu_to_be64(2 * cluster_size);
2157 ret = bdrv_pwrite(bs, cluster_size, refcount_table, 2 * cluster_size);
2158 g_free(refcount_table);
2161 error_setg_errno(errp, -ret, "Could not write refcount table");
2169 * And now open the image and make it consistent first (i.e. increase the
2170 * refcount of the cluster that is occupied by the header and the refcount
2173 options = qdict_new();
2174 qdict_put(options, "driver", qstring_from_str("qcow2"));
2175 ret = bdrv_open(&bs, filename, NULL, options,
2176 BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_NO_FLUSH,
2179 error_propagate(errp, local_err);
2183 ret = qcow2_alloc_clusters(bs, 3 * cluster_size);
2185 error_setg_errno(errp, -ret, "Could not allocate clusters for qcow2 "
2186 "header and refcount table");
2189 } else if (ret != 0) {
2190 error_report("Huh, first cluster in empty image is already in use?");
2194 /* Okay, now that we have a valid image, let's give it the right size */
2195 ret = bdrv_truncate(bs, total_size);
2197 error_setg_errno(errp, -ret, "Could not resize image");
2201 /* Want a backing file? There you go.*/
2203 ret = bdrv_change_backing_file(bs, backing_file, backing_format);
2205 error_setg_errno(errp, -ret, "Could not assign backing file '%s' "
2206 "with format '%s'", backing_file, backing_format);
2211 /* And if we're supposed to preallocate metadata, do that now */
2212 if (prealloc != PREALLOC_MODE_OFF) {
2213 BDRVQcow2State *s = bs->opaque;
2214 qemu_co_mutex_lock(&s->lock);
2215 ret = preallocate(bs);
2216 qemu_co_mutex_unlock(&s->lock);
2218 error_setg_errno(errp, -ret, "Could not preallocate metadata");
2226 /* Reopen the image without BDRV_O_NO_FLUSH to flush it before returning */
2227 options = qdict_new();
2228 qdict_put(options, "driver", qstring_from_str("qcow2"));
2229 ret = bdrv_open(&bs, filename, NULL, options,
2230 BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_NO_BACKING,
2233 error_propagate(errp, local_err);
2245 static int qcow2_create(const char *filename, QemuOpts *opts, Error **errp)
2247 char *backing_file = NULL;
2248 char *backing_fmt = NULL;
2252 size_t cluster_size = DEFAULT_CLUSTER_SIZE;
2253 PreallocMode prealloc;
2255 uint64_t refcount_bits = 16;
2257 Error *local_err = NULL;
2260 /* Read out options */
2261 size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
2263 backing_file = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
2264 backing_fmt = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FMT);
2265 if (qemu_opt_get_bool_del(opts, BLOCK_OPT_ENCRYPT, false)) {
2266 flags |= BLOCK_FLAG_ENCRYPT;
2268 cluster_size = qemu_opt_get_size_del(opts, BLOCK_OPT_CLUSTER_SIZE,
2269 DEFAULT_CLUSTER_SIZE);
2270 buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
2271 prealloc = qapi_enum_parse(PreallocMode_lookup, buf,
2272 PREALLOC_MODE_MAX, PREALLOC_MODE_OFF,
2275 error_propagate(errp, local_err);
2280 buf = qemu_opt_get_del(opts, BLOCK_OPT_COMPAT_LEVEL);
2282 /* keep the default */
2283 } else if (!strcmp(buf, "0.10")) {
2285 } else if (!strcmp(buf, "1.1")) {
2288 error_setg(errp, "Invalid compatibility level: '%s'", buf);
2293 if (qemu_opt_get_bool_del(opts, BLOCK_OPT_LAZY_REFCOUNTS, false)) {
2294 flags |= BLOCK_FLAG_LAZY_REFCOUNTS;
2297 if (backing_file && prealloc != PREALLOC_MODE_OFF) {
2298 error_setg(errp, "Backing file and preallocation cannot be used at "
2304 if (version < 3 && (flags & BLOCK_FLAG_LAZY_REFCOUNTS)) {
2305 error_setg(errp, "Lazy refcounts only supported with compatibility "
2306 "level 1.1 and above (use compat=1.1 or greater)");
2311 refcount_bits = qemu_opt_get_number_del(opts, BLOCK_OPT_REFCOUNT_BITS,
2313 if (refcount_bits > 64 || !is_power_of_2(refcount_bits)) {
2314 error_setg(errp, "Refcount width must be a power of two and may not "
2320 if (version < 3 && refcount_bits != 16) {
2321 error_setg(errp, "Different refcount widths than 16 bits require "
2322 "compatibility level 1.1 or above (use compat=1.1 or "
2328 refcount_order = ctz32(refcount_bits);
2330 ret = qcow2_create2(filename, size, backing_file, backing_fmt, flags,
2331 cluster_size, prealloc, opts, version, refcount_order,
2334 error_propagate(errp, local_err);
2338 g_free(backing_file);
2339 g_free(backing_fmt);
2344 static coroutine_fn int qcow2_co_write_zeroes(BlockDriverState *bs,
2345 int64_t sector_num, int nb_sectors, BdrvRequestFlags flags)
2348 BDRVQcow2State *s = bs->opaque;
2350 /* Emulate misaligned zero writes */
2351 if (sector_num % s->cluster_sectors || nb_sectors % s->cluster_sectors) {
2355 /* Whatever is left can use real zero clusters */
2356 qemu_co_mutex_lock(&s->lock);
2357 ret = qcow2_zero_clusters(bs, sector_num << BDRV_SECTOR_BITS,
2359 qemu_co_mutex_unlock(&s->lock);
2364 static coroutine_fn int qcow2_co_discard(BlockDriverState *bs,
2365 int64_t sector_num, int nb_sectors)
2368 BDRVQcow2State *s = bs->opaque;
2370 qemu_co_mutex_lock(&s->lock);
2371 ret = qcow2_discard_clusters(bs, sector_num << BDRV_SECTOR_BITS,
2372 nb_sectors, QCOW2_DISCARD_REQUEST, false);
2373 qemu_co_mutex_unlock(&s->lock);
2377 static int qcow2_truncate(BlockDriverState *bs, int64_t offset)
2379 BDRVQcow2State *s = bs->opaque;
2380 int64_t new_l1_size;
2384 error_report("The new size must be a multiple of 512");
2388 /* cannot proceed if image has snapshots */
2389 if (s->nb_snapshots) {
2390 error_report("Can't resize an image which has snapshots");
2394 /* shrinking is currently not supported */
2395 if (offset < bs->total_sectors * 512) {
2396 error_report("qcow2 doesn't support shrinking images yet");
2400 new_l1_size = size_to_l1(s, offset);
2401 ret = qcow2_grow_l1_table(bs, new_l1_size, true);
2406 /* write updated header.size */
2407 offset = cpu_to_be64(offset);
2408 ret = bdrv_pwrite_sync(bs->file->bs, offsetof(QCowHeader, size),
2409 &offset, sizeof(uint64_t));
2414 s->l1_vm_state_index = new_l1_size;
2418 /* XXX: put compressed sectors first, then all the cluster aligned
2419 tables to avoid losing bytes in alignment */
2420 static int qcow2_write_compressed(BlockDriverState *bs, int64_t sector_num,
2421 const uint8_t *buf, int nb_sectors)
2423 BDRVQcow2State *s = bs->opaque;
2427 uint64_t cluster_offset;
2429 if (nb_sectors == 0) {
2430 /* align end of file to a sector boundary to ease reading with
2431 sector based I/Os */
2432 cluster_offset = bdrv_getlength(bs->file->bs);
2433 return bdrv_truncate(bs->file->bs, cluster_offset);
2436 if (nb_sectors != s->cluster_sectors) {
2439 /* Zero-pad last write if image size is not cluster aligned */
2440 if (sector_num + nb_sectors == bs->total_sectors &&
2441 nb_sectors < s->cluster_sectors) {
2442 uint8_t *pad_buf = qemu_blockalign(bs, s->cluster_size);
2443 memset(pad_buf, 0, s->cluster_size);
2444 memcpy(pad_buf, buf, nb_sectors * BDRV_SECTOR_SIZE);
2445 ret = qcow2_write_compressed(bs, sector_num,
2446 pad_buf, s->cluster_sectors);
2447 qemu_vfree(pad_buf);
2452 out_buf = g_malloc(s->cluster_size + (s->cluster_size / 1000) + 128);
2454 /* best compression, small window, no zlib header */
2455 memset(&strm, 0, sizeof(strm));
2456 ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
2458 9, Z_DEFAULT_STRATEGY);
2464 strm.avail_in = s->cluster_size;
2465 strm.next_in = (uint8_t *)buf;
2466 strm.avail_out = s->cluster_size;
2467 strm.next_out = out_buf;
2469 ret = deflate(&strm, Z_FINISH);
2470 if (ret != Z_STREAM_END && ret != Z_OK) {
2475 out_len = strm.next_out - out_buf;
2479 if (ret != Z_STREAM_END || out_len >= s->cluster_size) {
2480 /* could not compress: write normal cluster */
2481 ret = bdrv_write(bs, sector_num, buf, s->cluster_sectors);
2486 cluster_offset = qcow2_alloc_compressed_cluster_offset(bs,
2487 sector_num << 9, out_len);
2488 if (!cluster_offset) {
2492 cluster_offset &= s->cluster_offset_mask;
2494 ret = qcow2_pre_write_overlap_check(bs, 0, cluster_offset, out_len);
2499 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_COMPRESSED);
2500 ret = bdrv_pwrite(bs->file->bs, cluster_offset, out_buf, out_len);
2512 static int make_completely_empty(BlockDriverState *bs)
2514 BDRVQcow2State *s = bs->opaque;
2515 int ret, l1_clusters;
2517 uint64_t *new_reftable = NULL;
2518 uint64_t rt_entry, l1_size2;
2521 uint64_t reftable_offset;
2522 uint32_t reftable_clusters;
2523 } QEMU_PACKED l1_ofs_rt_ofs_cls;
2525 ret = qcow2_cache_empty(bs, s->l2_table_cache);
2530 ret = qcow2_cache_empty(bs, s->refcount_block_cache);
2535 /* Refcounts will be broken utterly */
2536 ret = qcow2_mark_dirty(bs);
2541 BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
2543 l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / sizeof(uint64_t));
2544 l1_size2 = (uint64_t)s->l1_size * sizeof(uint64_t);
2546 /* After this call, neither the in-memory nor the on-disk refcount
2547 * information accurately describe the actual references */
2549 ret = bdrv_write_zeroes(bs->file->bs, s->l1_table_offset / BDRV_SECTOR_SIZE,
2550 l1_clusters * s->cluster_sectors, 0);
2552 goto fail_broken_refcounts;
2554 memset(s->l1_table, 0, l1_size2);
2556 BLKDBG_EVENT(bs->file, BLKDBG_EMPTY_IMAGE_PREPARE);
2558 /* Overwrite enough clusters at the beginning of the sectors to place
2559 * the refcount table, a refcount block and the L1 table in; this may
2560 * overwrite parts of the existing refcount and L1 table, which is not
2561 * an issue because the dirty flag is set, complete data loss is in fact
2562 * desired and partial data loss is consequently fine as well */
2563 ret = bdrv_write_zeroes(bs->file->bs, s->cluster_size / BDRV_SECTOR_SIZE,
2564 (2 + l1_clusters) * s->cluster_size /
2565 BDRV_SECTOR_SIZE, 0);
2566 /* This call (even if it failed overall) may have overwritten on-disk
2567 * refcount structures; in that case, the in-memory refcount information
2568 * will probably differ from the on-disk information which makes the BDS
2571 goto fail_broken_refcounts;
2574 BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
2575 BLKDBG_EVENT(bs->file, BLKDBG_REFTABLE_UPDATE);
2577 /* "Create" an empty reftable (one cluster) directly after the image
2578 * header and an empty L1 table three clusters after the image header;
2579 * the cluster between those two will be used as the first refblock */
2580 cpu_to_be64w(&l1_ofs_rt_ofs_cls.l1_offset, 3 * s->cluster_size);
2581 cpu_to_be64w(&l1_ofs_rt_ofs_cls.reftable_offset, s->cluster_size);
2582 cpu_to_be32w(&l1_ofs_rt_ofs_cls.reftable_clusters, 1);
2583 ret = bdrv_pwrite_sync(bs->file->bs, offsetof(QCowHeader, l1_table_offset),
2584 &l1_ofs_rt_ofs_cls, sizeof(l1_ofs_rt_ofs_cls));
2586 goto fail_broken_refcounts;
2589 s->l1_table_offset = 3 * s->cluster_size;
2591 new_reftable = g_try_new0(uint64_t, s->cluster_size / sizeof(uint64_t));
2592 if (!new_reftable) {
2594 goto fail_broken_refcounts;
2597 s->refcount_table_offset = s->cluster_size;
2598 s->refcount_table_size = s->cluster_size / sizeof(uint64_t);
2600 g_free(s->refcount_table);
2601 s->refcount_table = new_reftable;
2602 new_reftable = NULL;
2604 /* Now the in-memory refcount information again corresponds to the on-disk
2605 * information (reftable is empty and no refblocks (the refblock cache is
2606 * empty)); however, this means some clusters (e.g. the image header) are
2607 * referenced, but not refcounted, but the normal qcow2 code assumes that
2608 * the in-memory information is always correct */
2610 BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_ALLOC);
2612 /* Enter the first refblock into the reftable */
2613 rt_entry = cpu_to_be64(2 * s->cluster_size);
2614 ret = bdrv_pwrite_sync(bs->file->bs, s->cluster_size,
2615 &rt_entry, sizeof(rt_entry));
2617 goto fail_broken_refcounts;
2619 s->refcount_table[0] = 2 * s->cluster_size;
2621 s->free_cluster_index = 0;
2622 assert(3 + l1_clusters <= s->refcount_block_size);
2623 offset = qcow2_alloc_clusters(bs, 3 * s->cluster_size + l1_size2);
2626 goto fail_broken_refcounts;
2627 } else if (offset > 0) {
2628 error_report("First cluster in emptied image is in use");
2632 /* Now finally the in-memory information corresponds to the on-disk
2633 * structures and is correct */
2634 ret = qcow2_mark_clean(bs);
2639 ret = bdrv_truncate(bs->file->bs, (3 + l1_clusters) * s->cluster_size);
2646 fail_broken_refcounts:
2647 /* The BDS is unusable at this point. If we wanted to make it usable, we
2648 * would have to call qcow2_refcount_close(), qcow2_refcount_init(),
2649 * qcow2_check_refcounts(), qcow2_refcount_close() and qcow2_refcount_init()
2650 * again. However, because the functions which could have caused this error
2651 * path to be taken are used by those functions as well, it's very likely
2652 * that that sequence will fail as well. Therefore, just eject the BDS. */
2656 g_free(new_reftable);
2660 static int qcow2_make_empty(BlockDriverState *bs)
2662 BDRVQcow2State *s = bs->opaque;
2663 uint64_t start_sector;
2664 int sector_step = INT_MAX / BDRV_SECTOR_SIZE;
2665 int l1_clusters, ret = 0;
2667 l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / sizeof(uint64_t));
2669 if (s->qcow_version >= 3 && !s->snapshots &&
2670 3 + l1_clusters <= s->refcount_block_size) {
2671 /* The following function only works for qcow2 v3 images (it requires
2672 * the dirty flag) and only as long as there are no snapshots (because
2673 * it completely empties the image). Furthermore, the L1 table and three
2674 * additional clusters (image header, refcount table, one refcount
2675 * block) have to fit inside one refcount block. */
2676 return make_completely_empty(bs);
2679 /* This fallback code simply discards every active cluster; this is slow,
2680 * but works in all cases */
2681 for (start_sector = 0; start_sector < bs->total_sectors;
2682 start_sector += sector_step)
2684 /* As this function is generally used after committing an external
2685 * snapshot, QCOW2_DISCARD_SNAPSHOT seems appropriate. Also, the
2686 * default action for this kind of discard is to pass the discard,
2687 * which will ideally result in an actually smaller image file, as
2688 * is probably desired. */
2689 ret = qcow2_discard_clusters(bs, start_sector * BDRV_SECTOR_SIZE,
2691 bs->total_sectors - start_sector),
2692 QCOW2_DISCARD_SNAPSHOT, true);
2701 static coroutine_fn int qcow2_co_flush_to_os(BlockDriverState *bs)
2703 BDRVQcow2State *s = bs->opaque;
2706 qemu_co_mutex_lock(&s->lock);
2707 ret = qcow2_cache_flush(bs, s->l2_table_cache);
2709 qemu_co_mutex_unlock(&s->lock);
2713 if (qcow2_need_accurate_refcounts(s)) {
2714 ret = qcow2_cache_flush(bs, s->refcount_block_cache);
2716 qemu_co_mutex_unlock(&s->lock);
2720 qemu_co_mutex_unlock(&s->lock);
2725 static int qcow2_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
2727 BDRVQcow2State *s = bs->opaque;
2728 bdi->unallocated_blocks_are_zero = true;
2729 bdi->can_write_zeroes_with_unmap = (s->qcow_version >= 3);
2730 bdi->cluster_size = s->cluster_size;
2731 bdi->vm_state_offset = qcow2_vm_state_offset(s);
2735 static ImageInfoSpecific *qcow2_get_specific_info(BlockDriverState *bs)
2737 BDRVQcow2State *s = bs->opaque;
2738 ImageInfoSpecific *spec_info = g_new(ImageInfoSpecific, 1);
2740 *spec_info = (ImageInfoSpecific){
2741 .type = IMAGE_INFO_SPECIFIC_KIND_QCOW2,
2742 .u.qcow2 = g_new(ImageInfoSpecificQCow2, 1),
2744 if (s->qcow_version == 2) {
2745 *spec_info->u.qcow2 = (ImageInfoSpecificQCow2){
2746 .compat = g_strdup("0.10"),
2747 .refcount_bits = s->refcount_bits,
2749 } else if (s->qcow_version == 3) {
2750 *spec_info->u.qcow2 = (ImageInfoSpecificQCow2){
2751 .compat = g_strdup("1.1"),
2752 .lazy_refcounts = s->compatible_features &
2753 QCOW2_COMPAT_LAZY_REFCOUNTS,
2754 .has_lazy_refcounts = true,
2755 .corrupt = s->incompatible_features &
2756 QCOW2_INCOMPAT_CORRUPT,
2757 .has_corrupt = true,
2758 .refcount_bits = s->refcount_bits,
2766 static void dump_refcounts(BlockDriverState *bs)
2768 BDRVQcow2State *s = bs->opaque;
2769 int64_t nb_clusters, k, k1, size;
2772 size = bdrv_getlength(bs->file->bs);
2773 nb_clusters = size_to_clusters(s, size);
2774 for(k = 0; k < nb_clusters;) {
2776 refcount = get_refcount(bs, k);
2778 while (k < nb_clusters && get_refcount(bs, k) == refcount)
2780 printf("%" PRId64 ": refcount=%d nb=%" PRId64 "\n", k, refcount,
2786 static int qcow2_save_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
2789 BDRVQcow2State *s = bs->opaque;
2790 int64_t total_sectors = bs->total_sectors;
2791 bool zero_beyond_eof = bs->zero_beyond_eof;
2794 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_SAVE);
2795 bs->zero_beyond_eof = false;
2796 ret = bdrv_pwritev(bs, qcow2_vm_state_offset(s) + pos, qiov);
2797 bs->zero_beyond_eof = zero_beyond_eof;
2799 /* bdrv_co_do_writev will have increased the total_sectors value to include
2800 * the VM state - the VM state is however not an actual part of the block
2801 * device, therefore, we need to restore the old value. */
2802 bs->total_sectors = total_sectors;
2807 static int qcow2_load_vmstate(BlockDriverState *bs, uint8_t *buf,
2808 int64_t pos, int size)
2810 BDRVQcow2State *s = bs->opaque;
2811 bool zero_beyond_eof = bs->zero_beyond_eof;
2814 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_LOAD);
2815 bs->zero_beyond_eof = false;
2816 ret = bdrv_pread(bs, qcow2_vm_state_offset(s) + pos, buf, size);
2817 bs->zero_beyond_eof = zero_beyond_eof;
2823 * Downgrades an image's version. To achieve this, any incompatible features
2824 * have to be removed.
2826 static int qcow2_downgrade(BlockDriverState *bs, int target_version,
2827 BlockDriverAmendStatusCB *status_cb)
2829 BDRVQcow2State *s = bs->opaque;
2830 int current_version = s->qcow_version;
2833 if (target_version == current_version) {
2835 } else if (target_version > current_version) {
2837 } else if (target_version != 2) {
2841 if (s->refcount_order != 4) {
2842 /* we would have to convert the image to a refcount_order == 4 image
2843 * here; however, since qemu (at the time of writing this) does not
2844 * support anything different than 4 anyway, there is no point in doing
2845 * so right now; however, we should error out (if qemu supports this in
2846 * the future and this code has not been adapted) */
2847 error_report("qcow2_downgrade: Image refcount orders other than 4 are "
2848 "currently not supported.");
2852 /* clear incompatible features */
2853 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
2854 ret = qcow2_mark_clean(bs);
2860 /* with QCOW2_INCOMPAT_CORRUPT, it is pretty much impossible to get here in
2861 * the first place; if that happens nonetheless, returning -ENOTSUP is the
2862 * best thing to do anyway */
2864 if (s->incompatible_features) {
2868 /* since we can ignore compatible features, we can set them to 0 as well */
2869 s->compatible_features = 0;
2870 /* if lazy refcounts have been used, they have already been fixed through
2871 * clearing the dirty flag */
2873 /* clearing autoclear features is trivial */
2874 s->autoclear_features = 0;
2876 ret = qcow2_expand_zero_clusters(bs, status_cb);
2881 s->qcow_version = target_version;
2882 ret = qcow2_update_header(bs);
2884 s->qcow_version = current_version;
2890 static int qcow2_amend_options(BlockDriverState *bs, QemuOpts *opts,
2891 BlockDriverAmendStatusCB *status_cb)
2893 BDRVQcow2State *s = bs->opaque;
2894 int old_version = s->qcow_version, new_version = old_version;
2895 uint64_t new_size = 0;
2896 const char *backing_file = NULL, *backing_format = NULL;
2897 bool lazy_refcounts = s->use_lazy_refcounts;
2898 const char *compat = NULL;
2899 uint64_t cluster_size = s->cluster_size;
2902 QemuOptDesc *desc = opts->list->desc;
2904 while (desc && desc->name) {
2905 if (!qemu_opt_find(opts, desc->name)) {
2906 /* only change explicitly defined options */
2911 if (!strcmp(desc->name, BLOCK_OPT_COMPAT_LEVEL)) {
2912 compat = qemu_opt_get(opts, BLOCK_OPT_COMPAT_LEVEL);
2914 /* preserve default */
2915 } else if (!strcmp(compat, "0.10")) {
2917 } else if (!strcmp(compat, "1.1")) {
2920 fprintf(stderr, "Unknown compatibility level %s.\n", compat);
2923 } else if (!strcmp(desc->name, BLOCK_OPT_PREALLOC)) {
2924 fprintf(stderr, "Cannot change preallocation mode.\n");
2926 } else if (!strcmp(desc->name, BLOCK_OPT_SIZE)) {
2927 new_size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, 0);
2928 } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FILE)) {
2929 backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
2930 } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FMT)) {
2931 backing_format = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
2932 } else if (!strcmp(desc->name, BLOCK_OPT_ENCRYPT)) {
2933 encrypt = qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT,
2936 if (encrypt != !!s->cipher) {
2937 fprintf(stderr, "Changing the encryption flag is not "
2941 } else if (!strcmp(desc->name, BLOCK_OPT_CLUSTER_SIZE)) {
2942 cluster_size = qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE,
2944 if (cluster_size != s->cluster_size) {
2945 fprintf(stderr, "Changing the cluster size is not "
2949 } else if (!strcmp(desc->name, BLOCK_OPT_LAZY_REFCOUNTS)) {
2950 lazy_refcounts = qemu_opt_get_bool(opts, BLOCK_OPT_LAZY_REFCOUNTS,
2952 } else if (!strcmp(desc->name, BLOCK_OPT_REFCOUNT_BITS)) {
2953 error_report("Cannot change refcount entry width");
2956 /* if this assertion fails, this probably means a new option was
2957 * added without having it covered here */
2964 if (new_version != old_version) {
2965 if (new_version > old_version) {
2967 s->qcow_version = new_version;
2968 ret = qcow2_update_header(bs);
2970 s->qcow_version = old_version;
2974 ret = qcow2_downgrade(bs, new_version, status_cb);
2981 if (backing_file || backing_format) {
2982 ret = qcow2_change_backing_file(bs,
2983 backing_file ?: s->image_backing_file,
2984 backing_format ?: s->image_backing_format);
2990 if (s->use_lazy_refcounts != lazy_refcounts) {
2991 if (lazy_refcounts) {
2992 if (s->qcow_version < 3) {
2993 fprintf(stderr, "Lazy refcounts only supported with compatibility "
2994 "level 1.1 and above (use compat=1.1 or greater)\n");
2997 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
2998 ret = qcow2_update_header(bs);
3000 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
3003 s->use_lazy_refcounts = true;
3005 /* make image clean first */
3006 ret = qcow2_mark_clean(bs);
3010 /* now disallow lazy refcounts */
3011 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
3012 ret = qcow2_update_header(bs);
3014 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
3017 s->use_lazy_refcounts = false;
3022 ret = bdrv_truncate(bs, new_size);
3032 * If offset or size are negative, respectively, they will not be included in
3033 * the BLOCK_IMAGE_CORRUPTED event emitted.
3034 * fatal will be ignored for read-only BDS; corruptions found there will always
3035 * be considered non-fatal.
3037 void qcow2_signal_corruption(BlockDriverState *bs, bool fatal, int64_t offset,
3038 int64_t size, const char *message_format, ...)
3040 BDRVQcow2State *s = bs->opaque;
3041 const char *node_name;
3045 fatal = fatal && !bs->read_only;
3047 if (s->signaled_corruption &&
3048 (!fatal || (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT)))
3053 va_start(ap, message_format);
3054 message = g_strdup_vprintf(message_format, ap);
3058 fprintf(stderr, "qcow2: Marking image as corrupt: %s; further "
3059 "corruption events will be suppressed\n", message);
3061 fprintf(stderr, "qcow2: Image is corrupt: %s; further non-fatal "
3062 "corruption events will be suppressed\n", message);
3065 node_name = bdrv_get_node_name(bs);
3066 qapi_event_send_block_image_corrupted(bdrv_get_device_name(bs),
3067 *node_name != '\0', node_name,
3068 message, offset >= 0, offset,
3070 fatal, &error_abort);
3074 qcow2_mark_corrupt(bs);
3075 bs->drv = NULL; /* make BDS unusable */
3078 s->signaled_corruption = true;
3081 static QemuOptsList qcow2_create_opts = {
3082 .name = "qcow2-create-opts",
3083 .head = QTAILQ_HEAD_INITIALIZER(qcow2_create_opts.head),
3086 .name = BLOCK_OPT_SIZE,
3087 .type = QEMU_OPT_SIZE,
3088 .help = "Virtual disk size"
3091 .name = BLOCK_OPT_COMPAT_LEVEL,
3092 .type = QEMU_OPT_STRING,
3093 .help = "Compatibility level (0.10 or 1.1)"
3096 .name = BLOCK_OPT_BACKING_FILE,
3097 .type = QEMU_OPT_STRING,
3098 .help = "File name of a base image"
3101 .name = BLOCK_OPT_BACKING_FMT,
3102 .type = QEMU_OPT_STRING,
3103 .help = "Image format of the base image"
3106 .name = BLOCK_OPT_ENCRYPT,
3107 .type = QEMU_OPT_BOOL,
3108 .help = "Encrypt the image",
3109 .def_value_str = "off"
3112 .name = BLOCK_OPT_CLUSTER_SIZE,
3113 .type = QEMU_OPT_SIZE,
3114 .help = "qcow2 cluster size",
3115 .def_value_str = stringify(DEFAULT_CLUSTER_SIZE)
3118 .name = BLOCK_OPT_PREALLOC,
3119 .type = QEMU_OPT_STRING,
3120 .help = "Preallocation mode (allowed values: off, metadata, "
3124 .name = BLOCK_OPT_LAZY_REFCOUNTS,
3125 .type = QEMU_OPT_BOOL,
3126 .help = "Postpone refcount updates",
3127 .def_value_str = "off"
3130 .name = BLOCK_OPT_REFCOUNT_BITS,
3131 .type = QEMU_OPT_NUMBER,
3132 .help = "Width of a reference count entry in bits",
3133 .def_value_str = "16"
3135 { /* end of list */ }
3139 BlockDriver bdrv_qcow2 = {
3140 .format_name = "qcow2",
3141 .instance_size = sizeof(BDRVQcow2State),
3142 .bdrv_probe = qcow2_probe,
3143 .bdrv_open = qcow2_open,
3144 .bdrv_close = qcow2_close,
3145 .bdrv_reopen_prepare = qcow2_reopen_prepare,
3146 .bdrv_reopen_commit = qcow2_reopen_commit,
3147 .bdrv_reopen_abort = qcow2_reopen_abort,
3148 .bdrv_create = qcow2_create,
3149 .bdrv_has_zero_init = bdrv_has_zero_init_1,
3150 .bdrv_co_get_block_status = qcow2_co_get_block_status,
3151 .bdrv_set_key = qcow2_set_key,
3153 .bdrv_co_readv = qcow2_co_readv,
3154 .bdrv_co_writev = qcow2_co_writev,
3155 .bdrv_co_flush_to_os = qcow2_co_flush_to_os,
3157 .bdrv_co_write_zeroes = qcow2_co_write_zeroes,
3158 .bdrv_co_discard = qcow2_co_discard,
3159 .bdrv_truncate = qcow2_truncate,
3160 .bdrv_write_compressed = qcow2_write_compressed,
3161 .bdrv_make_empty = qcow2_make_empty,
3163 .bdrv_snapshot_create = qcow2_snapshot_create,
3164 .bdrv_snapshot_goto = qcow2_snapshot_goto,
3165 .bdrv_snapshot_delete = qcow2_snapshot_delete,
3166 .bdrv_snapshot_list = qcow2_snapshot_list,
3167 .bdrv_snapshot_load_tmp = qcow2_snapshot_load_tmp,
3168 .bdrv_get_info = qcow2_get_info,
3169 .bdrv_get_specific_info = qcow2_get_specific_info,
3171 .bdrv_save_vmstate = qcow2_save_vmstate,
3172 .bdrv_load_vmstate = qcow2_load_vmstate,
3174 .supports_backing = true,
3175 .bdrv_change_backing_file = qcow2_change_backing_file,
3177 .bdrv_refresh_limits = qcow2_refresh_limits,
3178 .bdrv_invalidate_cache = qcow2_invalidate_cache,
3180 .create_opts = &qcow2_create_opts,
3181 .bdrv_check = qcow2_check,
3182 .bdrv_amend_options = qcow2_amend_options,
3184 .bdrv_detach_aio_context = qcow2_detach_aio_context,
3185 .bdrv_attach_aio_context = qcow2_attach_aio_context,
3188 static void bdrv_qcow2_init(void)
3190 bdrv_register(&bdrv_qcow2);
3193 block_init(bdrv_qcow2_init);