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"
29 #include "block/qcow2.h"
30 #include "qemu/error-report.h"
31 #include "qapi/qmp/qerror.h"
32 #include "qapi/qmp/qbool.h"
33 #include "qapi/util.h"
34 #include "qapi/qmp/types.h"
35 #include "qapi-event.h"
37 #include "qemu/option_int.h"
40 Differences with QCOW:
42 - Support for multiple incremental snapshots.
43 - Memory management by reference counts.
44 - Clusters which have a reference count of one have the bit
45 QCOW_OFLAG_COPIED to optimize write performance.
46 - Size of compressed clusters is stored in sectors to reduce bit usage
47 in the cluster offsets.
48 - Support for storing additional data (such as the VM state) in the
50 - If a backing store is used, the cluster size is not constrained
51 (could be backported to QCOW).
52 - L2 tables have always a size of one cluster.
59 } QEMU_PACKED QCowExtension;
61 #define QCOW2_EXT_MAGIC_END 0
62 #define QCOW2_EXT_MAGIC_BACKING_FORMAT 0xE2792ACA
63 #define QCOW2_EXT_MAGIC_FEATURE_TABLE 0x6803f857
65 static int qcow2_probe(const uint8_t *buf, int buf_size, const char *filename)
67 const QCowHeader *cow_header = (const void *)buf;
69 if (buf_size >= sizeof(QCowHeader) &&
70 be32_to_cpu(cow_header->magic) == QCOW_MAGIC &&
71 be32_to_cpu(cow_header->version) >= 2)
79 * read qcow2 extension and fill bs
80 * start reading from start_offset
81 * finish reading upon magic of value 0 or when end_offset reached
82 * unknown magic is skipped (future extension this version knows nothing about)
83 * return 0 upon success, non-0 otherwise
85 static int qcow2_read_extensions(BlockDriverState *bs, uint64_t start_offset,
86 uint64_t end_offset, void **p_feature_table,
89 BDRVQcowState *s = bs->opaque;
95 printf("qcow2_read_extensions: start=%ld end=%ld\n", start_offset, end_offset);
97 offset = start_offset;
98 while (offset < end_offset) {
102 if (offset > s->cluster_size)
103 printf("qcow2_read_extension: suspicious offset %lu\n", offset);
105 printf("attempting to read extended header in offset %lu\n", offset);
108 ret = bdrv_pread(bs->file, offset, &ext, sizeof(ext));
110 error_setg_errno(errp, -ret, "qcow2_read_extension: ERROR: "
111 "pread fail from offset %" PRIu64, offset);
114 be32_to_cpus(&ext.magic);
115 be32_to_cpus(&ext.len);
116 offset += sizeof(ext);
118 printf("ext.magic = 0x%x\n", ext.magic);
120 if (ext.len > end_offset - offset) {
121 error_setg(errp, "Header extension too large");
126 case QCOW2_EXT_MAGIC_END:
129 case QCOW2_EXT_MAGIC_BACKING_FORMAT:
130 if (ext.len >= sizeof(bs->backing_format)) {
131 error_setg(errp, "ERROR: ext_backing_format: len=%" PRIu32
132 " too large (>=%zu)", ext.len,
133 sizeof(bs->backing_format));
136 ret = bdrv_pread(bs->file, offset, bs->backing_format, ext.len);
138 error_setg_errno(errp, -ret, "ERROR: ext_backing_format: "
139 "Could not read format name");
142 bs->backing_format[ext.len] = '\0';
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, 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, 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 BDRVQcowState *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_set(errp, QERR_UNKNOWN_BLOCK_FORMAT_FEATURE,
210 bdrv_get_device_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 BDRVQcowState *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, offsetof(QCowHeader, incompatible_features),
268 ret = bdrv_flush(bs->file);
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 BDRVQcowState *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 BDRVQcowState *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 BDRVQcowState *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 BDRVQcowState *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",
470 { /* end of list */ }
474 static const char *overlap_bool_option_names[QCOW2_OL_MAX_BITNR] = {
475 [QCOW2_OL_MAIN_HEADER_BITNR] = QCOW2_OPT_OVERLAP_MAIN_HEADER,
476 [QCOW2_OL_ACTIVE_L1_BITNR] = QCOW2_OPT_OVERLAP_ACTIVE_L1,
477 [QCOW2_OL_ACTIVE_L2_BITNR] = QCOW2_OPT_OVERLAP_ACTIVE_L2,
478 [QCOW2_OL_REFCOUNT_TABLE_BITNR] = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
479 [QCOW2_OL_REFCOUNT_BLOCK_BITNR] = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
480 [QCOW2_OL_SNAPSHOT_TABLE_BITNR] = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
481 [QCOW2_OL_INACTIVE_L1_BITNR] = QCOW2_OPT_OVERLAP_INACTIVE_L1,
482 [QCOW2_OL_INACTIVE_L2_BITNR] = QCOW2_OPT_OVERLAP_INACTIVE_L2,
485 static void read_cache_sizes(QemuOpts *opts, uint64_t *l2_cache_size,
486 uint64_t *refcount_cache_size, Error **errp)
488 uint64_t combined_cache_size;
489 bool l2_cache_size_set, refcount_cache_size_set, combined_cache_size_set;
491 combined_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_CACHE_SIZE);
492 l2_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_L2_CACHE_SIZE);
493 refcount_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
495 combined_cache_size = qemu_opt_get_size(opts, QCOW2_OPT_CACHE_SIZE, 0);
496 *l2_cache_size = qemu_opt_get_size(opts, QCOW2_OPT_L2_CACHE_SIZE, 0);
497 *refcount_cache_size = qemu_opt_get_size(opts,
498 QCOW2_OPT_REFCOUNT_CACHE_SIZE, 0);
500 if (combined_cache_size_set) {
501 if (l2_cache_size_set && refcount_cache_size_set) {
502 error_setg(errp, QCOW2_OPT_CACHE_SIZE ", " QCOW2_OPT_L2_CACHE_SIZE
503 " and " QCOW2_OPT_REFCOUNT_CACHE_SIZE " may not be set "
506 } else if (*l2_cache_size > combined_cache_size) {
507 error_setg(errp, QCOW2_OPT_L2_CACHE_SIZE " may not exceed "
508 QCOW2_OPT_CACHE_SIZE);
510 } else if (*refcount_cache_size > combined_cache_size) {
511 error_setg(errp, QCOW2_OPT_REFCOUNT_CACHE_SIZE " may not exceed "
512 QCOW2_OPT_CACHE_SIZE);
516 if (l2_cache_size_set) {
517 *refcount_cache_size = combined_cache_size - *l2_cache_size;
518 } else if (refcount_cache_size_set) {
519 *l2_cache_size = combined_cache_size - *refcount_cache_size;
521 *refcount_cache_size = combined_cache_size
522 / (DEFAULT_L2_REFCOUNT_SIZE_RATIO + 1);
523 *l2_cache_size = combined_cache_size - *refcount_cache_size;
526 if (!l2_cache_size_set && !refcount_cache_size_set) {
527 *l2_cache_size = DEFAULT_L2_CACHE_BYTE_SIZE;
528 *refcount_cache_size = *l2_cache_size
529 / DEFAULT_L2_REFCOUNT_SIZE_RATIO;
530 } else if (!l2_cache_size_set) {
531 *l2_cache_size = *refcount_cache_size
532 * DEFAULT_L2_REFCOUNT_SIZE_RATIO;
533 } else if (!refcount_cache_size_set) {
534 *refcount_cache_size = *l2_cache_size
535 / DEFAULT_L2_REFCOUNT_SIZE_RATIO;
540 static int qcow2_open(BlockDriverState *bs, QDict *options, int flags,
543 BDRVQcowState *s = bs->opaque;
547 QemuOpts *opts = NULL;
548 Error *local_err = NULL;
550 uint64_t l1_vm_state_index;
551 const char *opt_overlap_check, *opt_overlap_check_template;
552 int overlap_check_template = 0;
553 uint64_t l2_cache_size, refcount_cache_size;
555 ret = bdrv_pread(bs->file, 0, &header, sizeof(header));
557 error_setg_errno(errp, -ret, "Could not read qcow2 header");
560 be32_to_cpus(&header.magic);
561 be32_to_cpus(&header.version);
562 be64_to_cpus(&header.backing_file_offset);
563 be32_to_cpus(&header.backing_file_size);
564 be64_to_cpus(&header.size);
565 be32_to_cpus(&header.cluster_bits);
566 be32_to_cpus(&header.crypt_method);
567 be64_to_cpus(&header.l1_table_offset);
568 be32_to_cpus(&header.l1_size);
569 be64_to_cpus(&header.refcount_table_offset);
570 be32_to_cpus(&header.refcount_table_clusters);
571 be64_to_cpus(&header.snapshots_offset);
572 be32_to_cpus(&header.nb_snapshots);
574 if (header.magic != QCOW_MAGIC) {
575 error_setg(errp, "Image is not in qcow2 format");
579 if (header.version < 2 || header.version > 3) {
580 report_unsupported(bs, errp, "QCOW version %" PRIu32, header.version);
585 s->qcow_version = header.version;
587 /* Initialise cluster size */
588 if (header.cluster_bits < MIN_CLUSTER_BITS ||
589 header.cluster_bits > MAX_CLUSTER_BITS) {
590 error_setg(errp, "Unsupported cluster size: 2^%" PRIu32,
591 header.cluster_bits);
596 s->cluster_bits = header.cluster_bits;
597 s->cluster_size = 1 << s->cluster_bits;
598 s->cluster_sectors = 1 << (s->cluster_bits - 9);
600 /* Initialise version 3 header fields */
601 if (header.version == 2) {
602 header.incompatible_features = 0;
603 header.compatible_features = 0;
604 header.autoclear_features = 0;
605 header.refcount_order = 4;
606 header.header_length = 72;
608 be64_to_cpus(&header.incompatible_features);
609 be64_to_cpus(&header.compatible_features);
610 be64_to_cpus(&header.autoclear_features);
611 be32_to_cpus(&header.refcount_order);
612 be32_to_cpus(&header.header_length);
614 if (header.header_length < 104) {
615 error_setg(errp, "qcow2 header too short");
621 if (header.header_length > s->cluster_size) {
622 error_setg(errp, "qcow2 header exceeds cluster size");
627 if (header.header_length > sizeof(header)) {
628 s->unknown_header_fields_size = header.header_length - sizeof(header);
629 s->unknown_header_fields = g_malloc(s->unknown_header_fields_size);
630 ret = bdrv_pread(bs->file, sizeof(header), s->unknown_header_fields,
631 s->unknown_header_fields_size);
633 error_setg_errno(errp, -ret, "Could not read unknown qcow2 header "
639 if (header.backing_file_offset > s->cluster_size) {
640 error_setg(errp, "Invalid backing file offset");
645 if (header.backing_file_offset) {
646 ext_end = header.backing_file_offset;
648 ext_end = 1 << header.cluster_bits;
651 /* Handle feature bits */
652 s->incompatible_features = header.incompatible_features;
653 s->compatible_features = header.compatible_features;
654 s->autoclear_features = header.autoclear_features;
656 if (s->incompatible_features & ~QCOW2_INCOMPAT_MASK) {
657 void *feature_table = NULL;
658 qcow2_read_extensions(bs, header.header_length, ext_end,
659 &feature_table, NULL);
660 report_unsupported_feature(bs, errp, feature_table,
661 s->incompatible_features &
662 ~QCOW2_INCOMPAT_MASK);
664 g_free(feature_table);
668 if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
669 /* Corrupt images may not be written to unless they are being repaired
671 if ((flags & BDRV_O_RDWR) && !(flags & BDRV_O_CHECK)) {
672 error_setg(errp, "qcow2: Image is corrupt; cannot be opened "
679 /* Check support for various header values */
680 if (header.refcount_order != 4) {
681 report_unsupported(bs, errp, "%d bit reference counts",
682 1 << header.refcount_order);
686 s->refcount_order = header.refcount_order;
688 if (header.crypt_method > QCOW_CRYPT_AES) {
689 error_setg(errp, "Unsupported encryption method: %" PRIu32,
690 header.crypt_method);
694 s->crypt_method_header = header.crypt_method;
695 if (s->crypt_method_header) {
699 s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */
700 s->l2_size = 1 << s->l2_bits;
701 /* 2^(s->refcount_order - 3) is the refcount width in bytes */
702 s->refcount_block_bits = s->cluster_bits - (s->refcount_order - 3);
703 s->refcount_block_size = 1 << s->refcount_block_bits;
704 bs->total_sectors = header.size / 512;
705 s->csize_shift = (62 - (s->cluster_bits - 8));
706 s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;
707 s->cluster_offset_mask = (1LL << s->csize_shift) - 1;
709 s->refcount_table_offset = header.refcount_table_offset;
710 s->refcount_table_size =
711 header.refcount_table_clusters << (s->cluster_bits - 3);
713 if (header.refcount_table_clusters > qcow2_max_refcount_clusters(s)) {
714 error_setg(errp, "Reference count table too large");
719 ret = validate_table_offset(bs, s->refcount_table_offset,
720 s->refcount_table_size, sizeof(uint64_t));
722 error_setg(errp, "Invalid reference count table offset");
726 /* Snapshot table offset/length */
727 if (header.nb_snapshots > QCOW_MAX_SNAPSHOTS) {
728 error_setg(errp, "Too many snapshots");
733 ret = validate_table_offset(bs, header.snapshots_offset,
735 sizeof(QCowSnapshotHeader));
737 error_setg(errp, "Invalid snapshot table offset");
741 /* read the level 1 table */
742 if (header.l1_size > QCOW_MAX_L1_SIZE) {
743 error_setg(errp, "Active L1 table too large");
747 s->l1_size = header.l1_size;
749 l1_vm_state_index = size_to_l1(s, header.size);
750 if (l1_vm_state_index > INT_MAX) {
751 error_setg(errp, "Image is too big");
755 s->l1_vm_state_index = l1_vm_state_index;
757 /* the L1 table must contain at least enough entries to put
759 if (s->l1_size < s->l1_vm_state_index) {
760 error_setg(errp, "L1 table is too small");
765 ret = validate_table_offset(bs, header.l1_table_offset,
766 header.l1_size, sizeof(uint64_t));
768 error_setg(errp, "Invalid L1 table offset");
771 s->l1_table_offset = header.l1_table_offset;
774 if (s->l1_size > 0) {
775 s->l1_table = qemu_try_blockalign(bs->file,
776 align_offset(s->l1_size * sizeof(uint64_t), 512));
777 if (s->l1_table == NULL) {
778 error_setg(errp, "Could not allocate L1 table");
782 ret = bdrv_pread(bs->file, s->l1_table_offset, s->l1_table,
783 s->l1_size * sizeof(uint64_t));
785 error_setg_errno(errp, -ret, "Could not read L1 table");
788 for(i = 0;i < s->l1_size; i++) {
789 be64_to_cpus(&s->l1_table[i]);
793 /* get L2 table/refcount block cache size from command line options */
794 opts = qemu_opts_create(&qcow2_runtime_opts, NULL, 0, &error_abort);
795 qemu_opts_absorb_qdict(opts, options, &local_err);
797 error_propagate(errp, local_err);
802 read_cache_sizes(opts, &l2_cache_size, &refcount_cache_size, &local_err);
804 error_propagate(errp, local_err);
809 l2_cache_size /= s->cluster_size;
810 if (l2_cache_size < MIN_L2_CACHE_SIZE) {
811 l2_cache_size = MIN_L2_CACHE_SIZE;
813 if (l2_cache_size > INT_MAX) {
814 error_setg(errp, "L2 cache size too big");
819 refcount_cache_size /= s->cluster_size;
820 if (refcount_cache_size < MIN_REFCOUNT_CACHE_SIZE) {
821 refcount_cache_size = MIN_REFCOUNT_CACHE_SIZE;
823 if (refcount_cache_size > INT_MAX) {
824 error_setg(errp, "Refcount cache size too big");
829 /* alloc L2 table/refcount block cache */
830 s->l2_table_cache = qcow2_cache_create(bs, l2_cache_size);
831 s->refcount_block_cache = qcow2_cache_create(bs, refcount_cache_size);
832 if (s->l2_table_cache == NULL || s->refcount_block_cache == NULL) {
833 error_setg(errp, "Could not allocate metadata caches");
838 s->cluster_cache = g_malloc(s->cluster_size);
839 /* one more sector for decompressed data alignment */
840 s->cluster_data = qemu_try_blockalign(bs->file, QCOW_MAX_CRYPT_CLUSTERS
841 * s->cluster_size + 512);
842 if (s->cluster_data == NULL) {
843 error_setg(errp, "Could not allocate temporary cluster buffer");
848 s->cluster_cache_offset = -1;
851 ret = qcow2_refcount_init(bs);
853 error_setg_errno(errp, -ret, "Could not initialize refcount handling");
857 QLIST_INIT(&s->cluster_allocs);
858 QTAILQ_INIT(&s->discards);
860 /* read qcow2 extensions */
861 if (qcow2_read_extensions(bs, header.header_length, ext_end, NULL,
863 error_propagate(errp, local_err);
868 /* read the backing file name */
869 if (header.backing_file_offset != 0) {
870 len = header.backing_file_size;
871 if (len > MIN(1023, s->cluster_size - header.backing_file_offset)) {
872 error_setg(errp, "Backing file name too long");
876 ret = bdrv_pread(bs->file, header.backing_file_offset,
877 bs->backing_file, len);
879 error_setg_errno(errp, -ret, "Could not read backing file name");
882 bs->backing_file[len] = '\0';
885 /* Internal snapshots */
886 s->snapshots_offset = header.snapshots_offset;
887 s->nb_snapshots = header.nb_snapshots;
889 ret = qcow2_read_snapshots(bs);
891 error_setg_errno(errp, -ret, "Could not read snapshots");
895 /* Clear unknown autoclear feature bits */
896 if (!bs->read_only && !(flags & BDRV_O_INCOMING) && s->autoclear_features) {
897 s->autoclear_features = 0;
898 ret = qcow2_update_header(bs);
900 error_setg_errno(errp, -ret, "Could not update qcow2 header");
905 /* Initialise locks */
906 qemu_co_mutex_init(&s->lock);
908 /* Repair image if dirty */
909 if (!(flags & (BDRV_O_CHECK | BDRV_O_INCOMING)) && !bs->read_only &&
910 (s->incompatible_features & QCOW2_INCOMPAT_DIRTY)) {
911 BdrvCheckResult result = {0};
913 ret = qcow2_check(bs, &result, BDRV_FIX_ERRORS | BDRV_FIX_LEAKS);
915 error_setg_errno(errp, -ret, "Could not repair dirty image");
920 /* Enable lazy_refcounts according to image and command line options */
921 s->use_lazy_refcounts = qemu_opt_get_bool(opts, QCOW2_OPT_LAZY_REFCOUNTS,
922 (s->compatible_features & QCOW2_COMPAT_LAZY_REFCOUNTS));
924 s->discard_passthrough[QCOW2_DISCARD_NEVER] = false;
925 s->discard_passthrough[QCOW2_DISCARD_ALWAYS] = true;
926 s->discard_passthrough[QCOW2_DISCARD_REQUEST] =
927 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_REQUEST,
928 flags & BDRV_O_UNMAP);
929 s->discard_passthrough[QCOW2_DISCARD_SNAPSHOT] =
930 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_SNAPSHOT, true);
931 s->discard_passthrough[QCOW2_DISCARD_OTHER] =
932 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_OTHER, false);
934 opt_overlap_check = qemu_opt_get(opts, QCOW2_OPT_OVERLAP);
935 opt_overlap_check_template = qemu_opt_get(opts, QCOW2_OPT_OVERLAP_TEMPLATE);
936 if (opt_overlap_check_template && opt_overlap_check &&
937 strcmp(opt_overlap_check_template, opt_overlap_check))
939 error_setg(errp, "Conflicting values for qcow2 options '"
940 QCOW2_OPT_OVERLAP "' ('%s') and '" QCOW2_OPT_OVERLAP_TEMPLATE
941 "' ('%s')", opt_overlap_check, opt_overlap_check_template);
945 if (!opt_overlap_check) {
946 opt_overlap_check = opt_overlap_check_template ?: "cached";
949 if (!strcmp(opt_overlap_check, "none")) {
950 overlap_check_template = 0;
951 } else if (!strcmp(opt_overlap_check, "constant")) {
952 overlap_check_template = QCOW2_OL_CONSTANT;
953 } else if (!strcmp(opt_overlap_check, "cached")) {
954 overlap_check_template = QCOW2_OL_CACHED;
955 } else if (!strcmp(opt_overlap_check, "all")) {
956 overlap_check_template = QCOW2_OL_ALL;
958 error_setg(errp, "Unsupported value '%s' for qcow2 option "
959 "'overlap-check'. Allowed are either of the following: "
960 "none, constant, cached, all", opt_overlap_check);
965 s->overlap_check = 0;
966 for (i = 0; i < QCOW2_OL_MAX_BITNR; i++) {
967 /* overlap-check defines a template bitmask, but every flag may be
968 * overwritten through the associated boolean option */
970 qemu_opt_get_bool(opts, overlap_bool_option_names[i],
971 overlap_check_template & (1 << i)) << i;
977 if (s->use_lazy_refcounts && s->qcow_version < 3) {
978 error_setg(errp, "Lazy refcounts require a qcow2 image with at least "
979 "qemu 1.1 compatibility level");
986 BdrvCheckResult result = {0};
987 qcow2_check_refcounts(bs, &result, 0);
994 g_free(s->unknown_header_fields);
995 cleanup_unknown_header_ext(bs);
996 qcow2_free_snapshots(bs);
997 qcow2_refcount_close(bs);
998 qemu_vfree(s->l1_table);
999 /* else pre-write overlap checks in cache_destroy may crash */
1001 if (s->l2_table_cache) {
1002 qcow2_cache_destroy(bs, s->l2_table_cache);
1004 if (s->refcount_block_cache) {
1005 qcow2_cache_destroy(bs, s->refcount_block_cache);
1007 g_free(s->cluster_cache);
1008 qemu_vfree(s->cluster_data);
1012 static void qcow2_refresh_limits(BlockDriverState *bs, Error **errp)
1014 BDRVQcowState *s = bs->opaque;
1016 bs->bl.write_zeroes_alignment = s->cluster_sectors;
1019 static int qcow2_set_key(BlockDriverState *bs, const char *key)
1021 BDRVQcowState *s = bs->opaque;
1025 memset(keybuf, 0, 16);
1029 /* XXX: we could compress the chars to 7 bits to increase
1031 for(i = 0;i < len;i++) {
1034 s->crypt_method = s->crypt_method_header;
1036 if (AES_set_encrypt_key(keybuf, 128, &s->aes_encrypt_key) != 0)
1038 if (AES_set_decrypt_key(keybuf, 128, &s->aes_decrypt_key) != 0)
1048 AES_encrypt(in, tmp, &s->aes_encrypt_key);
1049 AES_decrypt(tmp, out, &s->aes_decrypt_key);
1050 for(i = 0; i < 16; i++)
1051 printf(" %02x", tmp[i]);
1053 for(i = 0; i < 16; i++)
1054 printf(" %02x", out[i]);
1061 /* We have no actual commit/abort logic for qcow2, but we need to write out any
1062 * unwritten data if we reopen read-only. */
1063 static int qcow2_reopen_prepare(BDRVReopenState *state,
1064 BlockReopenQueue *queue, Error **errp)
1068 if ((state->flags & BDRV_O_RDWR) == 0) {
1069 ret = bdrv_flush(state->bs);
1074 ret = qcow2_mark_clean(state->bs);
1083 static int64_t coroutine_fn qcow2_co_get_block_status(BlockDriverState *bs,
1084 int64_t sector_num, int nb_sectors, int *pnum)
1086 BDRVQcowState *s = bs->opaque;
1087 uint64_t cluster_offset;
1088 int index_in_cluster, ret;
1092 qemu_co_mutex_lock(&s->lock);
1093 ret = qcow2_get_cluster_offset(bs, sector_num << 9, pnum, &cluster_offset);
1094 qemu_co_mutex_unlock(&s->lock);
1099 if (cluster_offset != 0 && ret != QCOW2_CLUSTER_COMPRESSED &&
1101 index_in_cluster = sector_num & (s->cluster_sectors - 1);
1102 cluster_offset |= (index_in_cluster << BDRV_SECTOR_BITS);
1103 status |= BDRV_BLOCK_OFFSET_VALID | cluster_offset;
1105 if (ret == QCOW2_CLUSTER_ZERO) {
1106 status |= BDRV_BLOCK_ZERO;
1107 } else if (ret != QCOW2_CLUSTER_UNALLOCATED) {
1108 status |= BDRV_BLOCK_DATA;
1113 /* handle reading after the end of the backing file */
1114 int qcow2_backing_read1(BlockDriverState *bs, QEMUIOVector *qiov,
1115 int64_t sector_num, int nb_sectors)
1118 if ((sector_num + nb_sectors) <= bs->total_sectors)
1120 if (sector_num >= bs->total_sectors)
1123 n1 = bs->total_sectors - sector_num;
1125 qemu_iovec_memset(qiov, 512 * n1, 0, 512 * (nb_sectors - n1));
1130 static coroutine_fn int qcow2_co_readv(BlockDriverState *bs, int64_t sector_num,
1131 int remaining_sectors, QEMUIOVector *qiov)
1133 BDRVQcowState *s = bs->opaque;
1134 int index_in_cluster, n1;
1136 int cur_nr_sectors; /* number of sectors in current iteration */
1137 uint64_t cluster_offset = 0;
1138 uint64_t bytes_done = 0;
1139 QEMUIOVector hd_qiov;
1140 uint8_t *cluster_data = NULL;
1142 qemu_iovec_init(&hd_qiov, qiov->niov);
1144 qemu_co_mutex_lock(&s->lock);
1146 while (remaining_sectors != 0) {
1148 /* prepare next request */
1149 cur_nr_sectors = remaining_sectors;
1150 if (s->crypt_method) {
1151 cur_nr_sectors = MIN(cur_nr_sectors,
1152 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors);
1155 ret = qcow2_get_cluster_offset(bs, sector_num << 9,
1156 &cur_nr_sectors, &cluster_offset);
1161 index_in_cluster = sector_num & (s->cluster_sectors - 1);
1163 qemu_iovec_reset(&hd_qiov);
1164 qemu_iovec_concat(&hd_qiov, qiov, bytes_done,
1165 cur_nr_sectors * 512);
1168 case QCOW2_CLUSTER_UNALLOCATED:
1170 if (bs->backing_hd) {
1171 /* read from the base image */
1172 n1 = qcow2_backing_read1(bs->backing_hd, &hd_qiov,
1173 sector_num, cur_nr_sectors);
1175 QEMUIOVector local_qiov;
1177 qemu_iovec_init(&local_qiov, hd_qiov.niov);
1178 qemu_iovec_concat(&local_qiov, &hd_qiov, 0,
1179 n1 * BDRV_SECTOR_SIZE);
1181 BLKDBG_EVENT(bs->file, BLKDBG_READ_BACKING_AIO);
1182 qemu_co_mutex_unlock(&s->lock);
1183 ret = bdrv_co_readv(bs->backing_hd, sector_num,
1185 qemu_co_mutex_lock(&s->lock);
1187 qemu_iovec_destroy(&local_qiov);
1194 /* Note: in this case, no need to wait */
1195 qemu_iovec_memset(&hd_qiov, 0, 0, 512 * cur_nr_sectors);
1199 case QCOW2_CLUSTER_ZERO:
1200 qemu_iovec_memset(&hd_qiov, 0, 0, 512 * cur_nr_sectors);
1203 case QCOW2_CLUSTER_COMPRESSED:
1204 /* add AIO support for compressed blocks ? */
1205 ret = qcow2_decompress_cluster(bs, cluster_offset);
1210 qemu_iovec_from_buf(&hd_qiov, 0,
1211 s->cluster_cache + index_in_cluster * 512,
1212 512 * cur_nr_sectors);
1215 case QCOW2_CLUSTER_NORMAL:
1216 if ((cluster_offset & 511) != 0) {
1221 if (s->crypt_method) {
1223 * For encrypted images, read everything into a temporary
1224 * contiguous buffer on which the AES functions can work.
1226 if (!cluster_data) {
1228 qemu_try_blockalign(bs->file, QCOW_MAX_CRYPT_CLUSTERS
1230 if (cluster_data == NULL) {
1236 assert(cur_nr_sectors <=
1237 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors);
1238 qemu_iovec_reset(&hd_qiov);
1239 qemu_iovec_add(&hd_qiov, cluster_data,
1240 512 * cur_nr_sectors);
1243 BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);
1244 qemu_co_mutex_unlock(&s->lock);
1245 ret = bdrv_co_readv(bs->file,
1246 (cluster_offset >> 9) + index_in_cluster,
1247 cur_nr_sectors, &hd_qiov);
1248 qemu_co_mutex_lock(&s->lock);
1252 if (s->crypt_method) {
1253 qcow2_encrypt_sectors(s, sector_num, cluster_data,
1254 cluster_data, cur_nr_sectors, 0, &s->aes_decrypt_key);
1255 qemu_iovec_from_buf(qiov, bytes_done,
1256 cluster_data, 512 * cur_nr_sectors);
1261 g_assert_not_reached();
1266 remaining_sectors -= cur_nr_sectors;
1267 sector_num += cur_nr_sectors;
1268 bytes_done += cur_nr_sectors * 512;
1273 qemu_co_mutex_unlock(&s->lock);
1275 qemu_iovec_destroy(&hd_qiov);
1276 qemu_vfree(cluster_data);
1281 static coroutine_fn int qcow2_co_writev(BlockDriverState *bs,
1283 int remaining_sectors,
1286 BDRVQcowState *s = bs->opaque;
1287 int index_in_cluster;
1289 int cur_nr_sectors; /* number of sectors in current iteration */
1290 uint64_t cluster_offset;
1291 QEMUIOVector hd_qiov;
1292 uint64_t bytes_done = 0;
1293 uint8_t *cluster_data = NULL;
1294 QCowL2Meta *l2meta = NULL;
1296 trace_qcow2_writev_start_req(qemu_coroutine_self(), sector_num,
1299 qemu_iovec_init(&hd_qiov, qiov->niov);
1301 s->cluster_cache_offset = -1; /* disable compressed cache */
1303 qemu_co_mutex_lock(&s->lock);
1305 while (remaining_sectors != 0) {
1309 trace_qcow2_writev_start_part(qemu_coroutine_self());
1310 index_in_cluster = sector_num & (s->cluster_sectors - 1);
1311 cur_nr_sectors = remaining_sectors;
1312 if (s->crypt_method &&
1314 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors - index_in_cluster) {
1316 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors - index_in_cluster;
1319 ret = qcow2_alloc_cluster_offset(bs, sector_num << 9,
1320 &cur_nr_sectors, &cluster_offset, &l2meta);
1325 assert((cluster_offset & 511) == 0);
1327 qemu_iovec_reset(&hd_qiov);
1328 qemu_iovec_concat(&hd_qiov, qiov, bytes_done,
1329 cur_nr_sectors * 512);
1331 if (s->crypt_method) {
1332 if (!cluster_data) {
1333 cluster_data = qemu_try_blockalign(bs->file,
1334 QCOW_MAX_CRYPT_CLUSTERS
1336 if (cluster_data == NULL) {
1342 assert(hd_qiov.size <=
1343 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
1344 qemu_iovec_to_buf(&hd_qiov, 0, cluster_data, hd_qiov.size);
1346 qcow2_encrypt_sectors(s, sector_num, cluster_data,
1347 cluster_data, cur_nr_sectors, 1, &s->aes_encrypt_key);
1349 qemu_iovec_reset(&hd_qiov);
1350 qemu_iovec_add(&hd_qiov, cluster_data,
1351 cur_nr_sectors * 512);
1354 ret = qcow2_pre_write_overlap_check(bs, 0,
1355 cluster_offset + index_in_cluster * BDRV_SECTOR_SIZE,
1356 cur_nr_sectors * BDRV_SECTOR_SIZE);
1361 qemu_co_mutex_unlock(&s->lock);
1362 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO);
1363 trace_qcow2_writev_data(qemu_coroutine_self(),
1364 (cluster_offset >> 9) + index_in_cluster);
1365 ret = bdrv_co_writev(bs->file,
1366 (cluster_offset >> 9) + index_in_cluster,
1367 cur_nr_sectors, &hd_qiov);
1368 qemu_co_mutex_lock(&s->lock);
1373 while (l2meta != NULL) {
1376 ret = qcow2_alloc_cluster_link_l2(bs, l2meta);
1381 /* Take the request off the list of running requests */
1382 if (l2meta->nb_clusters != 0) {
1383 QLIST_REMOVE(l2meta, next_in_flight);
1386 qemu_co_queue_restart_all(&l2meta->dependent_requests);
1388 next = l2meta->next;
1393 remaining_sectors -= cur_nr_sectors;
1394 sector_num += cur_nr_sectors;
1395 bytes_done += cur_nr_sectors * 512;
1396 trace_qcow2_writev_done_part(qemu_coroutine_self(), cur_nr_sectors);
1401 qemu_co_mutex_unlock(&s->lock);
1403 while (l2meta != NULL) {
1406 if (l2meta->nb_clusters != 0) {
1407 QLIST_REMOVE(l2meta, next_in_flight);
1409 qemu_co_queue_restart_all(&l2meta->dependent_requests);
1411 next = l2meta->next;
1416 qemu_iovec_destroy(&hd_qiov);
1417 qemu_vfree(cluster_data);
1418 trace_qcow2_writev_done_req(qemu_coroutine_self(), ret);
1423 static void qcow2_close(BlockDriverState *bs)
1425 BDRVQcowState *s = bs->opaque;
1426 qemu_vfree(s->l1_table);
1427 /* else pre-write overlap checks in cache_destroy may crash */
1430 if (!(bs->open_flags & BDRV_O_INCOMING)) {
1431 qcow2_cache_flush(bs, s->l2_table_cache);
1432 qcow2_cache_flush(bs, s->refcount_block_cache);
1434 qcow2_mark_clean(bs);
1437 qcow2_cache_destroy(bs, s->l2_table_cache);
1438 qcow2_cache_destroy(bs, s->refcount_block_cache);
1440 g_free(s->unknown_header_fields);
1441 cleanup_unknown_header_ext(bs);
1443 g_free(s->cluster_cache);
1444 qemu_vfree(s->cluster_data);
1445 qcow2_refcount_close(bs);
1446 qcow2_free_snapshots(bs);
1449 static void qcow2_invalidate_cache(BlockDriverState *bs, Error **errp)
1451 BDRVQcowState *s = bs->opaque;
1452 int flags = s->flags;
1453 AES_KEY aes_encrypt_key;
1454 AES_KEY aes_decrypt_key;
1455 uint32_t crypt_method = 0;
1457 Error *local_err = NULL;
1461 * Backing files are read-only which makes all of their metadata immutable,
1462 * that means we don't have to worry about reopening them here.
1465 if (s->crypt_method) {
1466 crypt_method = s->crypt_method;
1467 memcpy(&aes_encrypt_key, &s->aes_encrypt_key, sizeof(aes_encrypt_key));
1468 memcpy(&aes_decrypt_key, &s->aes_decrypt_key, sizeof(aes_decrypt_key));
1473 bdrv_invalidate_cache(bs->file, &local_err);
1475 error_propagate(errp, local_err);
1479 memset(s, 0, sizeof(BDRVQcowState));
1480 options = qdict_clone_shallow(bs->options);
1482 ret = qcow2_open(bs, options, flags, &local_err);
1485 error_setg(errp, "Could not reopen qcow2 layer: %s",
1486 error_get_pretty(local_err));
1487 error_free(local_err);
1489 } else if (ret < 0) {
1490 error_setg_errno(errp, -ret, "Could not reopen qcow2 layer");
1495 s->crypt_method = crypt_method;
1496 memcpy(&s->aes_encrypt_key, &aes_encrypt_key, sizeof(aes_encrypt_key));
1497 memcpy(&s->aes_decrypt_key, &aes_decrypt_key, sizeof(aes_decrypt_key));
1501 static size_t header_ext_add(char *buf, uint32_t magic, const void *s,
1502 size_t len, size_t buflen)
1504 QCowExtension *ext_backing_fmt = (QCowExtension*) buf;
1505 size_t ext_len = sizeof(QCowExtension) + ((len + 7) & ~7);
1507 if (buflen < ext_len) {
1511 *ext_backing_fmt = (QCowExtension) {
1512 .magic = cpu_to_be32(magic),
1513 .len = cpu_to_be32(len),
1515 memcpy(buf + sizeof(QCowExtension), s, len);
1521 * Updates the qcow2 header, including the variable length parts of it, i.e.
1522 * the backing file name and all extensions. qcow2 was not designed to allow
1523 * such changes, so if we run out of space (we can only use the first cluster)
1524 * this function may fail.
1526 * Returns 0 on success, -errno in error cases.
1528 int qcow2_update_header(BlockDriverState *bs)
1530 BDRVQcowState *s = bs->opaque;
1533 size_t buflen = s->cluster_size;
1535 uint64_t total_size;
1536 uint32_t refcount_table_clusters;
1537 size_t header_length;
1538 Qcow2UnknownHeaderExtension *uext;
1540 buf = qemu_blockalign(bs, buflen);
1542 /* Header structure */
1543 header = (QCowHeader*) buf;
1545 if (buflen < sizeof(*header)) {
1550 header_length = sizeof(*header) + s->unknown_header_fields_size;
1551 total_size = bs->total_sectors * BDRV_SECTOR_SIZE;
1552 refcount_table_clusters = s->refcount_table_size >> (s->cluster_bits - 3);
1554 *header = (QCowHeader) {
1555 /* Version 2 fields */
1556 .magic = cpu_to_be32(QCOW_MAGIC),
1557 .version = cpu_to_be32(s->qcow_version),
1558 .backing_file_offset = 0,
1559 .backing_file_size = 0,
1560 .cluster_bits = cpu_to_be32(s->cluster_bits),
1561 .size = cpu_to_be64(total_size),
1562 .crypt_method = cpu_to_be32(s->crypt_method_header),
1563 .l1_size = cpu_to_be32(s->l1_size),
1564 .l1_table_offset = cpu_to_be64(s->l1_table_offset),
1565 .refcount_table_offset = cpu_to_be64(s->refcount_table_offset),
1566 .refcount_table_clusters = cpu_to_be32(refcount_table_clusters),
1567 .nb_snapshots = cpu_to_be32(s->nb_snapshots),
1568 .snapshots_offset = cpu_to_be64(s->snapshots_offset),
1570 /* Version 3 fields */
1571 .incompatible_features = cpu_to_be64(s->incompatible_features),
1572 .compatible_features = cpu_to_be64(s->compatible_features),
1573 .autoclear_features = cpu_to_be64(s->autoclear_features),
1574 .refcount_order = cpu_to_be32(s->refcount_order),
1575 .header_length = cpu_to_be32(header_length),
1578 /* For older versions, write a shorter header */
1579 switch (s->qcow_version) {
1581 ret = offsetof(QCowHeader, incompatible_features);
1584 ret = sizeof(*header);
1593 memset(buf, 0, buflen);
1595 /* Preserve any unknown field in the header */
1596 if (s->unknown_header_fields_size) {
1597 if (buflen < s->unknown_header_fields_size) {
1602 memcpy(buf, s->unknown_header_fields, s->unknown_header_fields_size);
1603 buf += s->unknown_header_fields_size;
1604 buflen -= s->unknown_header_fields_size;
1607 /* Backing file format header extension */
1608 if (*bs->backing_format) {
1609 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BACKING_FORMAT,
1610 bs->backing_format, strlen(bs->backing_format),
1621 Qcow2Feature features[] = {
1623 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
1624 .bit = QCOW2_INCOMPAT_DIRTY_BITNR,
1625 .name = "dirty bit",
1628 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
1629 .bit = QCOW2_INCOMPAT_CORRUPT_BITNR,
1630 .name = "corrupt bit",
1633 .type = QCOW2_FEAT_TYPE_COMPATIBLE,
1634 .bit = QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR,
1635 .name = "lazy refcounts",
1639 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_FEATURE_TABLE,
1640 features, sizeof(features), buflen);
1647 /* Keep unknown header extensions */
1648 QLIST_FOREACH(uext, &s->unknown_header_ext, next) {
1649 ret = header_ext_add(buf, uext->magic, uext->data, uext->len, buflen);
1658 /* End of header extensions */
1659 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_END, NULL, 0, buflen);
1667 /* Backing file name */
1668 if (*bs->backing_file) {
1669 size_t backing_file_len = strlen(bs->backing_file);
1671 if (buflen < backing_file_len) {
1676 /* Using strncpy is ok here, since buf is not NUL-terminated. */
1677 strncpy(buf, bs->backing_file, buflen);
1679 header->backing_file_offset = cpu_to_be64(buf - ((char*) header));
1680 header->backing_file_size = cpu_to_be32(backing_file_len);
1683 /* Write the new header */
1684 ret = bdrv_pwrite(bs->file, 0, header, s->cluster_size);
1695 static int qcow2_change_backing_file(BlockDriverState *bs,
1696 const char *backing_file, const char *backing_fmt)
1698 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
1699 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
1701 return qcow2_update_header(bs);
1704 static int preallocate(BlockDriverState *bs)
1706 uint64_t nb_sectors;
1708 uint64_t host_offset = 0;
1713 nb_sectors = bdrv_nb_sectors(bs);
1716 while (nb_sectors) {
1717 num = MIN(nb_sectors, INT_MAX >> BDRV_SECTOR_BITS);
1718 ret = qcow2_alloc_cluster_offset(bs, offset, &num,
1719 &host_offset, &meta);
1725 QCowL2Meta *next = meta->next;
1727 ret = qcow2_alloc_cluster_link_l2(bs, meta);
1729 qcow2_free_any_clusters(bs, meta->alloc_offset,
1730 meta->nb_clusters, QCOW2_DISCARD_NEVER);
1734 /* There are no dependent requests, but we need to remove our
1735 * request from the list of in-flight requests */
1736 QLIST_REMOVE(meta, next_in_flight);
1742 /* TODO Preallocate data if requested */
1745 offset += num << BDRV_SECTOR_BITS;
1749 * It is expected that the image file is large enough to actually contain
1750 * all of the allocated clusters (otherwise we get failing reads after
1751 * EOF). Extend the image to the last allocated sector.
1753 if (host_offset != 0) {
1754 uint8_t buf[BDRV_SECTOR_SIZE];
1755 memset(buf, 0, BDRV_SECTOR_SIZE);
1756 ret = bdrv_write(bs->file, (host_offset >> BDRV_SECTOR_BITS) + num - 1,
1766 static int qcow2_create2(const char *filename, int64_t total_size,
1767 const char *backing_file, const char *backing_format,
1768 int flags, size_t cluster_size, PreallocMode prealloc,
1769 QemuOpts *opts, int version,
1772 /* Calculate cluster_bits */
1774 cluster_bits = ffs(cluster_size) - 1;
1775 if (cluster_bits < MIN_CLUSTER_BITS || cluster_bits > MAX_CLUSTER_BITS ||
1776 (1 << cluster_bits) != cluster_size)
1778 error_setg(errp, "Cluster size must be a power of two between %d and "
1779 "%dk", 1 << MIN_CLUSTER_BITS, 1 << (MAX_CLUSTER_BITS - 10));
1784 * Open the image file and write a minimal qcow2 header.
1786 * We keep things simple and start with a zero-sized image. We also
1787 * do without refcount blocks or a L1 table for now. We'll fix the
1788 * inconsistency later.
1790 * We do need a refcount table because growing the refcount table means
1791 * allocating two new refcount blocks - the seconds of which would be at
1792 * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
1793 * size for any qcow2 image.
1795 BlockDriverState* bs;
1797 uint64_t* refcount_table;
1798 Error *local_err = NULL;
1801 if (prealloc == PREALLOC_MODE_FULL || prealloc == PREALLOC_MODE_FALLOC) {
1802 int64_t meta_size = 0;
1803 uint64_t nreftablee, nrefblocke, nl1e, nl2e;
1804 int64_t aligned_total_size = align_offset(total_size, cluster_size);
1806 /* header: 1 cluster */
1807 meta_size += cluster_size;
1809 /* total size of L2 tables */
1810 nl2e = aligned_total_size / cluster_size;
1811 nl2e = align_offset(nl2e, cluster_size / sizeof(uint64_t));
1812 meta_size += nl2e * sizeof(uint64_t);
1814 /* total size of L1 tables */
1815 nl1e = nl2e * sizeof(uint64_t) / cluster_size;
1816 nl1e = align_offset(nl1e, cluster_size / sizeof(uint64_t));
1817 meta_size += nl1e * sizeof(uint64_t);
1819 /* total size of refcount blocks
1821 * note: every host cluster is reference-counted, including metadata
1822 * (even refcount blocks are recursively included).
1824 * a = total_size (this is the guest disk size)
1825 * m = meta size not including refcount blocks and refcount tables
1827 * y1 = number of refcount blocks entries
1828 * y2 = meta size including everything
1831 * y2 = y1 * sizeof(u16) + y1 * sizeof(u16) * sizeof(u64) / c + m
1833 * y1 = (a + m) / (c - sizeof(u16) - sizeof(u16) * sizeof(u64) / c)
1835 nrefblocke = (aligned_total_size + meta_size + cluster_size) /
1836 (cluster_size - sizeof(uint16_t) -
1837 1.0 * sizeof(uint16_t) * sizeof(uint64_t) / cluster_size);
1838 nrefblocke = align_offset(nrefblocke, cluster_size / sizeof(uint16_t));
1839 meta_size += nrefblocke * sizeof(uint16_t);
1841 /* total size of refcount tables */
1842 nreftablee = nrefblocke * sizeof(uint16_t) / cluster_size;
1843 nreftablee = align_offset(nreftablee, cluster_size / sizeof(uint64_t));
1844 meta_size += nreftablee * sizeof(uint64_t);
1846 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
1847 aligned_total_size + meta_size);
1848 qemu_opt_set(opts, BLOCK_OPT_PREALLOC, PreallocMode_lookup[prealloc]);
1851 ret = bdrv_create_file(filename, opts, &local_err);
1853 error_propagate(errp, local_err);
1858 ret = bdrv_open(&bs, filename, NULL, NULL, BDRV_O_RDWR | BDRV_O_PROTOCOL,
1861 error_propagate(errp, local_err);
1865 /* Write the header */
1866 QEMU_BUILD_BUG_ON((1 << MIN_CLUSTER_BITS) < sizeof(*header));
1867 header = g_malloc0(cluster_size);
1868 *header = (QCowHeader) {
1869 .magic = cpu_to_be32(QCOW_MAGIC),
1870 .version = cpu_to_be32(version),
1871 .cluster_bits = cpu_to_be32(cluster_bits),
1872 .size = cpu_to_be64(0),
1873 .l1_table_offset = cpu_to_be64(0),
1874 .l1_size = cpu_to_be32(0),
1875 .refcount_table_offset = cpu_to_be64(cluster_size),
1876 .refcount_table_clusters = cpu_to_be32(1),
1877 .refcount_order = cpu_to_be32(4),
1878 .header_length = cpu_to_be32(sizeof(*header)),
1881 if (flags & BLOCK_FLAG_ENCRYPT) {
1882 header->crypt_method = cpu_to_be32(QCOW_CRYPT_AES);
1884 header->crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
1887 if (flags & BLOCK_FLAG_LAZY_REFCOUNTS) {
1888 header->compatible_features |=
1889 cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS);
1892 ret = bdrv_pwrite(bs, 0, header, cluster_size);
1895 error_setg_errno(errp, -ret, "Could not write qcow2 header");
1899 /* Write a refcount table with one refcount block */
1900 refcount_table = g_malloc0(2 * cluster_size);
1901 refcount_table[0] = cpu_to_be64(2 * cluster_size);
1902 ret = bdrv_pwrite(bs, cluster_size, refcount_table, 2 * cluster_size);
1903 g_free(refcount_table);
1906 error_setg_errno(errp, -ret, "Could not write refcount table");
1914 * And now open the image and make it consistent first (i.e. increase the
1915 * refcount of the cluster that is occupied by the header and the refcount
1918 BlockDriver* drv = bdrv_find_format("qcow2");
1919 assert(drv != NULL);
1920 ret = bdrv_open(&bs, filename, NULL, NULL,
1921 BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_NO_FLUSH, drv, &local_err);
1923 error_propagate(errp, local_err);
1927 ret = qcow2_alloc_clusters(bs, 3 * cluster_size);
1929 error_setg_errno(errp, -ret, "Could not allocate clusters for qcow2 "
1930 "header and refcount table");
1933 } else if (ret != 0) {
1934 error_report("Huh, first cluster in empty image is already in use?");
1938 /* Okay, now that we have a valid image, let's give it the right size */
1939 ret = bdrv_truncate(bs, total_size);
1941 error_setg_errno(errp, -ret, "Could not resize image");
1945 /* Want a backing file? There you go.*/
1947 ret = bdrv_change_backing_file(bs, backing_file, backing_format);
1949 error_setg_errno(errp, -ret, "Could not assign backing file '%s' "
1950 "with format '%s'", backing_file, backing_format);
1955 /* And if we're supposed to preallocate metadata, do that now */
1956 if (prealloc != PREALLOC_MODE_OFF) {
1957 BDRVQcowState *s = bs->opaque;
1958 qemu_co_mutex_lock(&s->lock);
1959 ret = preallocate(bs);
1960 qemu_co_mutex_unlock(&s->lock);
1962 error_setg_errno(errp, -ret, "Could not preallocate metadata");
1970 /* Reopen the image without BDRV_O_NO_FLUSH to flush it before returning */
1971 ret = bdrv_open(&bs, filename, NULL, NULL,
1972 BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_NO_BACKING,
1975 error_propagate(errp, local_err);
1987 static int qcow2_create(const char *filename, QemuOpts *opts, Error **errp)
1989 char *backing_file = NULL;
1990 char *backing_fmt = NULL;
1994 size_t cluster_size = DEFAULT_CLUSTER_SIZE;
1995 PreallocMode prealloc;
1997 Error *local_err = NULL;
2000 /* Read out options */
2001 size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
2003 backing_file = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
2004 backing_fmt = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FMT);
2005 if (qemu_opt_get_bool_del(opts, BLOCK_OPT_ENCRYPT, false)) {
2006 flags |= BLOCK_FLAG_ENCRYPT;
2008 cluster_size = qemu_opt_get_size_del(opts, BLOCK_OPT_CLUSTER_SIZE,
2009 DEFAULT_CLUSTER_SIZE);
2010 buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
2011 prealloc = qapi_enum_parse(PreallocMode_lookup, buf,
2012 PREALLOC_MODE_MAX, PREALLOC_MODE_OFF,
2015 error_propagate(errp, local_err);
2020 buf = qemu_opt_get_del(opts, BLOCK_OPT_COMPAT_LEVEL);
2022 /* keep the default */
2023 } else if (!strcmp(buf, "0.10")) {
2025 } else if (!strcmp(buf, "1.1")) {
2028 error_setg(errp, "Invalid compatibility level: '%s'", buf);
2033 if (qemu_opt_get_bool_del(opts, BLOCK_OPT_LAZY_REFCOUNTS, false)) {
2034 flags |= BLOCK_FLAG_LAZY_REFCOUNTS;
2037 if (backing_file && prealloc != PREALLOC_MODE_OFF) {
2038 error_setg(errp, "Backing file and preallocation cannot be used at "
2044 if (version < 3 && (flags & BLOCK_FLAG_LAZY_REFCOUNTS)) {
2045 error_setg(errp, "Lazy refcounts only supported with compatibility "
2046 "level 1.1 and above (use compat=1.1 or greater)");
2051 ret = qcow2_create2(filename, size, backing_file, backing_fmt, flags,
2052 cluster_size, prealloc, opts, version, &local_err);
2054 error_propagate(errp, local_err);
2058 g_free(backing_file);
2059 g_free(backing_fmt);
2064 static coroutine_fn int qcow2_co_write_zeroes(BlockDriverState *bs,
2065 int64_t sector_num, int nb_sectors, BdrvRequestFlags flags)
2068 BDRVQcowState *s = bs->opaque;
2070 /* Emulate misaligned zero writes */
2071 if (sector_num % s->cluster_sectors || nb_sectors % s->cluster_sectors) {
2075 /* Whatever is left can use real zero clusters */
2076 qemu_co_mutex_lock(&s->lock);
2077 ret = qcow2_zero_clusters(bs, sector_num << BDRV_SECTOR_BITS,
2079 qemu_co_mutex_unlock(&s->lock);
2084 static coroutine_fn int qcow2_co_discard(BlockDriverState *bs,
2085 int64_t sector_num, int nb_sectors)
2088 BDRVQcowState *s = bs->opaque;
2090 qemu_co_mutex_lock(&s->lock);
2091 ret = qcow2_discard_clusters(bs, sector_num << BDRV_SECTOR_BITS,
2092 nb_sectors, QCOW2_DISCARD_REQUEST, false);
2093 qemu_co_mutex_unlock(&s->lock);
2097 static int qcow2_truncate(BlockDriverState *bs, int64_t offset)
2099 BDRVQcowState *s = bs->opaque;
2100 int64_t new_l1_size;
2104 error_report("The new size must be a multiple of 512");
2108 /* cannot proceed if image has snapshots */
2109 if (s->nb_snapshots) {
2110 error_report("Can't resize an image which has snapshots");
2114 /* shrinking is currently not supported */
2115 if (offset < bs->total_sectors * 512) {
2116 error_report("qcow2 doesn't support shrinking images yet");
2120 new_l1_size = size_to_l1(s, offset);
2121 ret = qcow2_grow_l1_table(bs, new_l1_size, true);
2126 /* write updated header.size */
2127 offset = cpu_to_be64(offset);
2128 ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, size),
2129 &offset, sizeof(uint64_t));
2134 s->l1_vm_state_index = new_l1_size;
2138 /* XXX: put compressed sectors first, then all the cluster aligned
2139 tables to avoid losing bytes in alignment */
2140 static int qcow2_write_compressed(BlockDriverState *bs, int64_t sector_num,
2141 const uint8_t *buf, int nb_sectors)
2143 BDRVQcowState *s = bs->opaque;
2147 uint64_t cluster_offset;
2149 if (nb_sectors == 0) {
2150 /* align end of file to a sector boundary to ease reading with
2151 sector based I/Os */
2152 cluster_offset = bdrv_getlength(bs->file);
2153 bdrv_truncate(bs->file, cluster_offset);
2157 if (nb_sectors != s->cluster_sectors) {
2160 /* Zero-pad last write if image size is not cluster aligned */
2161 if (sector_num + nb_sectors == bs->total_sectors &&
2162 nb_sectors < s->cluster_sectors) {
2163 uint8_t *pad_buf = qemu_blockalign(bs, s->cluster_size);
2164 memset(pad_buf, 0, s->cluster_size);
2165 memcpy(pad_buf, buf, nb_sectors * BDRV_SECTOR_SIZE);
2166 ret = qcow2_write_compressed(bs, sector_num,
2167 pad_buf, s->cluster_sectors);
2168 qemu_vfree(pad_buf);
2173 out_buf = g_malloc(s->cluster_size + (s->cluster_size / 1000) + 128);
2175 /* best compression, small window, no zlib header */
2176 memset(&strm, 0, sizeof(strm));
2177 ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
2179 9, Z_DEFAULT_STRATEGY);
2185 strm.avail_in = s->cluster_size;
2186 strm.next_in = (uint8_t *)buf;
2187 strm.avail_out = s->cluster_size;
2188 strm.next_out = out_buf;
2190 ret = deflate(&strm, Z_FINISH);
2191 if (ret != Z_STREAM_END && ret != Z_OK) {
2196 out_len = strm.next_out - out_buf;
2200 if (ret != Z_STREAM_END || out_len >= s->cluster_size) {
2201 /* could not compress: write normal cluster */
2202 ret = bdrv_write(bs, sector_num, buf, s->cluster_sectors);
2207 cluster_offset = qcow2_alloc_compressed_cluster_offset(bs,
2208 sector_num << 9, out_len);
2209 if (!cluster_offset) {
2213 cluster_offset &= s->cluster_offset_mask;
2215 ret = qcow2_pre_write_overlap_check(bs, 0, cluster_offset, out_len);
2220 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_COMPRESSED);
2221 ret = bdrv_pwrite(bs->file, cluster_offset, out_buf, out_len);
2233 static int make_completely_empty(BlockDriverState *bs)
2235 BDRVQcowState *s = bs->opaque;
2236 int ret, l1_clusters;
2238 uint64_t *new_reftable = NULL;
2239 uint64_t rt_entry, l1_size2;
2242 uint64_t reftable_offset;
2243 uint32_t reftable_clusters;
2244 } QEMU_PACKED l1_ofs_rt_ofs_cls;
2246 ret = qcow2_cache_empty(bs, s->l2_table_cache);
2251 ret = qcow2_cache_empty(bs, s->refcount_block_cache);
2256 /* Refcounts will be broken utterly */
2257 ret = qcow2_mark_dirty(bs);
2262 BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
2264 l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / sizeof(uint64_t));
2265 l1_size2 = (uint64_t)s->l1_size * sizeof(uint64_t);
2267 /* After this call, neither the in-memory nor the on-disk refcount
2268 * information accurately describe the actual references */
2270 ret = bdrv_write_zeroes(bs->file, s->l1_table_offset / BDRV_SECTOR_SIZE,
2271 l1_clusters * s->cluster_sectors, 0);
2273 goto fail_broken_refcounts;
2275 memset(s->l1_table, 0, l1_size2);
2277 BLKDBG_EVENT(bs->file, BLKDBG_EMPTY_IMAGE_PREPARE);
2279 /* Overwrite enough clusters at the beginning of the sectors to place
2280 * the refcount table, a refcount block and the L1 table in; this may
2281 * overwrite parts of the existing refcount and L1 table, which is not
2282 * an issue because the dirty flag is set, complete data loss is in fact
2283 * desired and partial data loss is consequently fine as well */
2284 ret = bdrv_write_zeroes(bs->file, s->cluster_size / BDRV_SECTOR_SIZE,
2285 (2 + l1_clusters) * s->cluster_size /
2286 BDRV_SECTOR_SIZE, 0);
2287 /* This call (even if it failed overall) may have overwritten on-disk
2288 * refcount structures; in that case, the in-memory refcount information
2289 * will probably differ from the on-disk information which makes the BDS
2292 goto fail_broken_refcounts;
2295 BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
2296 BLKDBG_EVENT(bs->file, BLKDBG_REFTABLE_UPDATE);
2298 /* "Create" an empty reftable (one cluster) directly after the image
2299 * header and an empty L1 table three clusters after the image header;
2300 * the cluster between those two will be used as the first refblock */
2301 cpu_to_be64w(&l1_ofs_rt_ofs_cls.l1_offset, 3 * s->cluster_size);
2302 cpu_to_be64w(&l1_ofs_rt_ofs_cls.reftable_offset, s->cluster_size);
2303 cpu_to_be32w(&l1_ofs_rt_ofs_cls.reftable_clusters, 1);
2304 ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, l1_table_offset),
2305 &l1_ofs_rt_ofs_cls, sizeof(l1_ofs_rt_ofs_cls));
2307 goto fail_broken_refcounts;
2310 s->l1_table_offset = 3 * s->cluster_size;
2312 new_reftable = g_try_new0(uint64_t, s->cluster_size / sizeof(uint64_t));
2313 if (!new_reftable) {
2315 goto fail_broken_refcounts;
2318 s->refcount_table_offset = s->cluster_size;
2319 s->refcount_table_size = s->cluster_size / sizeof(uint64_t);
2321 g_free(s->refcount_table);
2322 s->refcount_table = new_reftable;
2323 new_reftable = NULL;
2325 /* Now the in-memory refcount information again corresponds to the on-disk
2326 * information (reftable is empty and no refblocks (the refblock cache is
2327 * empty)); however, this means some clusters (e.g. the image header) are
2328 * referenced, but not refcounted, but the normal qcow2 code assumes that
2329 * the in-memory information is always correct */
2331 BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_ALLOC);
2333 /* Enter the first refblock into the reftable */
2334 rt_entry = cpu_to_be64(2 * s->cluster_size);
2335 ret = bdrv_pwrite_sync(bs->file, s->cluster_size,
2336 &rt_entry, sizeof(rt_entry));
2338 goto fail_broken_refcounts;
2340 s->refcount_table[0] = 2 * s->cluster_size;
2342 s->free_cluster_index = 0;
2343 assert(3 + l1_clusters <= s->refcount_block_size);
2344 offset = qcow2_alloc_clusters(bs, 3 * s->cluster_size + l1_size2);
2347 goto fail_broken_refcounts;
2348 } else if (offset > 0) {
2349 error_report("First cluster in emptied image is in use");
2353 /* Now finally the in-memory information corresponds to the on-disk
2354 * structures and is correct */
2355 ret = qcow2_mark_clean(bs);
2360 ret = bdrv_truncate(bs->file, (3 + l1_clusters) * s->cluster_size);
2367 fail_broken_refcounts:
2368 /* The BDS is unusable at this point. If we wanted to make it usable, we
2369 * would have to call qcow2_refcount_close(), qcow2_refcount_init(),
2370 * qcow2_check_refcounts(), qcow2_refcount_close() and qcow2_refcount_init()
2371 * again. However, because the functions which could have caused this error
2372 * path to be taken are used by those functions as well, it's very likely
2373 * that that sequence will fail as well. Therefore, just eject the BDS. */
2377 g_free(new_reftable);
2381 static int qcow2_make_empty(BlockDriverState *bs)
2383 BDRVQcowState *s = bs->opaque;
2384 uint64_t start_sector;
2385 int sector_step = INT_MAX / BDRV_SECTOR_SIZE;
2386 int l1_clusters, ret = 0;
2388 l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / sizeof(uint64_t));
2390 if (s->qcow_version >= 3 && !s->snapshots &&
2391 3 + l1_clusters <= s->refcount_block_size) {
2392 /* The following function only works for qcow2 v3 images (it requires
2393 * the dirty flag) and only as long as there are no snapshots (because
2394 * it completely empties the image). Furthermore, the L1 table and three
2395 * additional clusters (image header, refcount table, one refcount
2396 * block) have to fit inside one refcount block. */
2397 return make_completely_empty(bs);
2400 /* This fallback code simply discards every active cluster; this is slow,
2401 * but works in all cases */
2402 for (start_sector = 0; start_sector < bs->total_sectors;
2403 start_sector += sector_step)
2405 /* As this function is generally used after committing an external
2406 * snapshot, QCOW2_DISCARD_SNAPSHOT seems appropriate. Also, the
2407 * default action for this kind of discard is to pass the discard,
2408 * which will ideally result in an actually smaller image file, as
2409 * is probably desired. */
2410 ret = qcow2_discard_clusters(bs, start_sector * BDRV_SECTOR_SIZE,
2412 bs->total_sectors - start_sector),
2413 QCOW2_DISCARD_SNAPSHOT, true);
2422 static coroutine_fn int qcow2_co_flush_to_os(BlockDriverState *bs)
2424 BDRVQcowState *s = bs->opaque;
2427 qemu_co_mutex_lock(&s->lock);
2428 ret = qcow2_cache_flush(bs, s->l2_table_cache);
2430 qemu_co_mutex_unlock(&s->lock);
2434 if (qcow2_need_accurate_refcounts(s)) {
2435 ret = qcow2_cache_flush(bs, s->refcount_block_cache);
2437 qemu_co_mutex_unlock(&s->lock);
2441 qemu_co_mutex_unlock(&s->lock);
2446 static int qcow2_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
2448 BDRVQcowState *s = bs->opaque;
2449 bdi->unallocated_blocks_are_zero = true;
2450 bdi->can_write_zeroes_with_unmap = (s->qcow_version >= 3);
2451 bdi->cluster_size = s->cluster_size;
2452 bdi->vm_state_offset = qcow2_vm_state_offset(s);
2456 static ImageInfoSpecific *qcow2_get_specific_info(BlockDriverState *bs)
2458 BDRVQcowState *s = bs->opaque;
2459 ImageInfoSpecific *spec_info = g_new(ImageInfoSpecific, 1);
2461 *spec_info = (ImageInfoSpecific){
2462 .kind = IMAGE_INFO_SPECIFIC_KIND_QCOW2,
2464 .qcow2 = g_new(ImageInfoSpecificQCow2, 1),
2467 if (s->qcow_version == 2) {
2468 *spec_info->qcow2 = (ImageInfoSpecificQCow2){
2469 .compat = g_strdup("0.10"),
2471 } else if (s->qcow_version == 3) {
2472 *spec_info->qcow2 = (ImageInfoSpecificQCow2){
2473 .compat = g_strdup("1.1"),
2474 .lazy_refcounts = s->compatible_features &
2475 QCOW2_COMPAT_LAZY_REFCOUNTS,
2476 .has_lazy_refcounts = true,
2477 .corrupt = s->incompatible_features &
2478 QCOW2_INCOMPAT_CORRUPT,
2479 .has_corrupt = true,
2487 static void dump_refcounts(BlockDriverState *bs)
2489 BDRVQcowState *s = bs->opaque;
2490 int64_t nb_clusters, k, k1, size;
2493 size = bdrv_getlength(bs->file);
2494 nb_clusters = size_to_clusters(s, size);
2495 for(k = 0; k < nb_clusters;) {
2497 refcount = get_refcount(bs, k);
2499 while (k < nb_clusters && get_refcount(bs, k) == refcount)
2501 printf("%" PRId64 ": refcount=%d nb=%" PRId64 "\n", k, refcount,
2507 static int qcow2_save_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
2510 BDRVQcowState *s = bs->opaque;
2511 int64_t total_sectors = bs->total_sectors;
2512 int growable = bs->growable;
2513 bool zero_beyond_eof = bs->zero_beyond_eof;
2516 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_SAVE);
2518 bs->zero_beyond_eof = false;
2519 ret = bdrv_pwritev(bs, qcow2_vm_state_offset(s) + pos, qiov);
2520 bs->growable = growable;
2521 bs->zero_beyond_eof = zero_beyond_eof;
2523 /* bdrv_co_do_writev will have increased the total_sectors value to include
2524 * the VM state - the VM state is however not an actual part of the block
2525 * device, therefore, we need to restore the old value. */
2526 bs->total_sectors = total_sectors;
2531 static int qcow2_load_vmstate(BlockDriverState *bs, uint8_t *buf,
2532 int64_t pos, int size)
2534 BDRVQcowState *s = bs->opaque;
2535 int growable = bs->growable;
2536 bool zero_beyond_eof = bs->zero_beyond_eof;
2539 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_LOAD);
2541 bs->zero_beyond_eof = false;
2542 ret = bdrv_pread(bs, qcow2_vm_state_offset(s) + pos, buf, size);
2543 bs->growable = growable;
2544 bs->zero_beyond_eof = zero_beyond_eof;
2550 * Downgrades an image's version. To achieve this, any incompatible features
2551 * have to be removed.
2553 static int qcow2_downgrade(BlockDriverState *bs, int target_version,
2554 BlockDriverAmendStatusCB *status_cb)
2556 BDRVQcowState *s = bs->opaque;
2557 int current_version = s->qcow_version;
2560 if (target_version == current_version) {
2562 } else if (target_version > current_version) {
2564 } else if (target_version != 2) {
2568 if (s->refcount_order != 4) {
2569 /* we would have to convert the image to a refcount_order == 4 image
2570 * here; however, since qemu (at the time of writing this) does not
2571 * support anything different than 4 anyway, there is no point in doing
2572 * so right now; however, we should error out (if qemu supports this in
2573 * the future and this code has not been adapted) */
2574 error_report("qcow2_downgrade: Image refcount orders other than 4 are "
2575 "currently not supported.");
2579 /* clear incompatible features */
2580 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
2581 ret = qcow2_mark_clean(bs);
2587 /* with QCOW2_INCOMPAT_CORRUPT, it is pretty much impossible to get here in
2588 * the first place; if that happens nonetheless, returning -ENOTSUP is the
2589 * best thing to do anyway */
2591 if (s->incompatible_features) {
2595 /* since we can ignore compatible features, we can set them to 0 as well */
2596 s->compatible_features = 0;
2597 /* if lazy refcounts have been used, they have already been fixed through
2598 * clearing the dirty flag */
2600 /* clearing autoclear features is trivial */
2601 s->autoclear_features = 0;
2603 ret = qcow2_expand_zero_clusters(bs, status_cb);
2608 s->qcow_version = target_version;
2609 ret = qcow2_update_header(bs);
2611 s->qcow_version = current_version;
2617 static int qcow2_amend_options(BlockDriverState *bs, QemuOpts *opts,
2618 BlockDriverAmendStatusCB *status_cb)
2620 BDRVQcowState *s = bs->opaque;
2621 int old_version = s->qcow_version, new_version = old_version;
2622 uint64_t new_size = 0;
2623 const char *backing_file = NULL, *backing_format = NULL;
2624 bool lazy_refcounts = s->use_lazy_refcounts;
2625 const char *compat = NULL;
2626 uint64_t cluster_size = s->cluster_size;
2629 QemuOptDesc *desc = opts->list->desc;
2631 while (desc && desc->name) {
2632 if (!qemu_opt_find(opts, desc->name)) {
2633 /* only change explicitly defined options */
2638 if (!strcmp(desc->name, "compat")) {
2639 compat = qemu_opt_get(opts, "compat");
2641 /* preserve default */
2642 } else if (!strcmp(compat, "0.10")) {
2644 } else if (!strcmp(compat, "1.1")) {
2647 fprintf(stderr, "Unknown compatibility level %s.\n", compat);
2650 } else if (!strcmp(desc->name, "preallocation")) {
2651 fprintf(stderr, "Cannot change preallocation mode.\n");
2653 } else if (!strcmp(desc->name, "size")) {
2654 new_size = qemu_opt_get_size(opts, "size", 0);
2655 } else if (!strcmp(desc->name, "backing_file")) {
2656 backing_file = qemu_opt_get(opts, "backing_file");
2657 } else if (!strcmp(desc->name, "backing_fmt")) {
2658 backing_format = qemu_opt_get(opts, "backing_fmt");
2659 } else if (!strcmp(desc->name, "encryption")) {
2660 encrypt = qemu_opt_get_bool(opts, "encryption", s->crypt_method);
2661 if (encrypt != !!s->crypt_method) {
2662 fprintf(stderr, "Changing the encryption flag is not "
2666 } else if (!strcmp(desc->name, "cluster_size")) {
2667 cluster_size = qemu_opt_get_size(opts, "cluster_size",
2669 if (cluster_size != s->cluster_size) {
2670 fprintf(stderr, "Changing the cluster size is not "
2674 } else if (!strcmp(desc->name, "lazy_refcounts")) {
2675 lazy_refcounts = qemu_opt_get_bool(opts, "lazy_refcounts",
2678 /* if this assertion fails, this probably means a new option was
2679 * added without having it covered here */
2686 if (new_version != old_version) {
2687 if (new_version > old_version) {
2689 s->qcow_version = new_version;
2690 ret = qcow2_update_header(bs);
2692 s->qcow_version = old_version;
2696 ret = qcow2_downgrade(bs, new_version, status_cb);
2703 if (backing_file || backing_format) {
2704 ret = qcow2_change_backing_file(bs, backing_file ?: bs->backing_file,
2705 backing_format ?: bs->backing_format);
2711 if (s->use_lazy_refcounts != lazy_refcounts) {
2712 if (lazy_refcounts) {
2713 if (s->qcow_version < 3) {
2714 fprintf(stderr, "Lazy refcounts only supported with compatibility "
2715 "level 1.1 and above (use compat=1.1 or greater)\n");
2718 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
2719 ret = qcow2_update_header(bs);
2721 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
2724 s->use_lazy_refcounts = true;
2726 /* make image clean first */
2727 ret = qcow2_mark_clean(bs);
2731 /* now disallow lazy refcounts */
2732 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
2733 ret = qcow2_update_header(bs);
2735 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
2738 s->use_lazy_refcounts = false;
2743 ret = bdrv_truncate(bs, new_size);
2753 * If offset or size are negative, respectively, they will not be included in
2754 * the BLOCK_IMAGE_CORRUPTED event emitted.
2755 * fatal will be ignored for read-only BDS; corruptions found there will always
2756 * be considered non-fatal.
2758 void qcow2_signal_corruption(BlockDriverState *bs, bool fatal, int64_t offset,
2759 int64_t size, const char *message_format, ...)
2761 BDRVQcowState *s = bs->opaque;
2765 fatal = fatal && !bs->read_only;
2767 if (s->signaled_corruption &&
2768 (!fatal || (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT)))
2773 va_start(ap, message_format);
2774 message = g_strdup_vprintf(message_format, ap);
2778 fprintf(stderr, "qcow2: Marking image as corrupt: %s; further "
2779 "corruption events will be suppressed\n", message);
2781 fprintf(stderr, "qcow2: Image is corrupt: %s; further non-fatal "
2782 "corruption events will be suppressed\n", message);
2785 qapi_event_send_block_image_corrupted(bdrv_get_device_name(bs), message,
2786 offset >= 0, offset, size >= 0, size,
2787 fatal, &error_abort);
2791 qcow2_mark_corrupt(bs);
2792 bs->drv = NULL; /* make BDS unusable */
2795 s->signaled_corruption = true;
2798 static QemuOptsList qcow2_create_opts = {
2799 .name = "qcow2-create-opts",
2800 .head = QTAILQ_HEAD_INITIALIZER(qcow2_create_opts.head),
2803 .name = BLOCK_OPT_SIZE,
2804 .type = QEMU_OPT_SIZE,
2805 .help = "Virtual disk size"
2808 .name = BLOCK_OPT_COMPAT_LEVEL,
2809 .type = QEMU_OPT_STRING,
2810 .help = "Compatibility level (0.10 or 1.1)"
2813 .name = BLOCK_OPT_BACKING_FILE,
2814 .type = QEMU_OPT_STRING,
2815 .help = "File name of a base image"
2818 .name = BLOCK_OPT_BACKING_FMT,
2819 .type = QEMU_OPT_STRING,
2820 .help = "Image format of the base image"
2823 .name = BLOCK_OPT_ENCRYPT,
2824 .type = QEMU_OPT_BOOL,
2825 .help = "Encrypt the image",
2826 .def_value_str = "off"
2829 .name = BLOCK_OPT_CLUSTER_SIZE,
2830 .type = QEMU_OPT_SIZE,
2831 .help = "qcow2 cluster size",
2832 .def_value_str = stringify(DEFAULT_CLUSTER_SIZE)
2835 .name = BLOCK_OPT_PREALLOC,
2836 .type = QEMU_OPT_STRING,
2837 .help = "Preallocation mode (allowed values: off, metadata, "
2841 .name = BLOCK_OPT_LAZY_REFCOUNTS,
2842 .type = QEMU_OPT_BOOL,
2843 .help = "Postpone refcount updates",
2844 .def_value_str = "off"
2846 { /* end of list */ }
2850 static BlockDriver bdrv_qcow2 = {
2851 .format_name = "qcow2",
2852 .instance_size = sizeof(BDRVQcowState),
2853 .bdrv_probe = qcow2_probe,
2854 .bdrv_open = qcow2_open,
2855 .bdrv_close = qcow2_close,
2856 .bdrv_reopen_prepare = qcow2_reopen_prepare,
2857 .bdrv_create = qcow2_create,
2858 .bdrv_has_zero_init = bdrv_has_zero_init_1,
2859 .bdrv_co_get_block_status = qcow2_co_get_block_status,
2860 .bdrv_set_key = qcow2_set_key,
2862 .bdrv_co_readv = qcow2_co_readv,
2863 .bdrv_co_writev = qcow2_co_writev,
2864 .bdrv_co_flush_to_os = qcow2_co_flush_to_os,
2866 .bdrv_co_write_zeroes = qcow2_co_write_zeroes,
2867 .bdrv_co_discard = qcow2_co_discard,
2868 .bdrv_truncate = qcow2_truncate,
2869 .bdrv_write_compressed = qcow2_write_compressed,
2870 .bdrv_make_empty = qcow2_make_empty,
2872 .bdrv_snapshot_create = qcow2_snapshot_create,
2873 .bdrv_snapshot_goto = qcow2_snapshot_goto,
2874 .bdrv_snapshot_delete = qcow2_snapshot_delete,
2875 .bdrv_snapshot_list = qcow2_snapshot_list,
2876 .bdrv_snapshot_load_tmp = qcow2_snapshot_load_tmp,
2877 .bdrv_get_info = qcow2_get_info,
2878 .bdrv_get_specific_info = qcow2_get_specific_info,
2880 .bdrv_save_vmstate = qcow2_save_vmstate,
2881 .bdrv_load_vmstate = qcow2_load_vmstate,
2883 .supports_backing = true,
2884 .bdrv_change_backing_file = qcow2_change_backing_file,
2886 .bdrv_refresh_limits = qcow2_refresh_limits,
2887 .bdrv_invalidate_cache = qcow2_invalidate_cache,
2889 .create_opts = &qcow2_create_opts,
2890 .bdrv_check = qcow2_check,
2891 .bdrv_amend_options = qcow2_amend_options,
2894 static void bdrv_qcow2_init(void)
2896 bdrv_register(&bdrv_qcow2);
2899 block_init(bdrv_qcow2_init);