qcow2: Fix L1 allocation size in qcow2_snapshot_load_tmp() (CVE-2014-0145)
[qemu/kevin.git] / block / qcow2.c
blobbe48a27afafe029e49ae475e6e362ce2238303e9
1 /*
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
22 * THE SOFTWARE.
24 #include "qemu-common.h"
25 #include "block/block_int.h"
26 #include "qemu/module.h"
27 #include <zlib.h>
28 #include "qemu/aes.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 "trace.h"
36 Differences with QCOW:
38 - Support for multiple incremental snapshots.
39 - Memory management by reference counts.
40 - Clusters which have a reference count of one have the bit
41 QCOW_OFLAG_COPIED to optimize write performance.
42 - Size of compressed clusters is stored in sectors to reduce bit usage
43 in the cluster offsets.
44 - Support for storing additional data (such as the VM state) in the
45 snapshots.
46 - If a backing store is used, the cluster size is not constrained
47 (could be backported to QCOW).
48 - L2 tables have always a size of one cluster.
52 typedef struct {
53 uint32_t magic;
54 uint32_t len;
55 } QEMU_PACKED QCowExtension;
57 #define QCOW2_EXT_MAGIC_END 0
58 #define QCOW2_EXT_MAGIC_BACKING_FORMAT 0xE2792ACA
59 #define QCOW2_EXT_MAGIC_FEATURE_TABLE 0x6803f857
61 static int qcow2_probe(const uint8_t *buf, int buf_size, const char *filename)
63 const QCowHeader *cow_header = (const void *)buf;
65 if (buf_size >= sizeof(QCowHeader) &&
66 be32_to_cpu(cow_header->magic) == QCOW_MAGIC &&
67 be32_to_cpu(cow_header->version) >= 2)
68 return 100;
69 else
70 return 0;
74 /*
75 * read qcow2 extension and fill bs
76 * start reading from start_offset
77 * finish reading upon magic of value 0 or when end_offset reached
78 * unknown magic is skipped (future extension this version knows nothing about)
79 * return 0 upon success, non-0 otherwise
81 static int qcow2_read_extensions(BlockDriverState *bs, uint64_t start_offset,
82 uint64_t end_offset, void **p_feature_table,
83 Error **errp)
85 BDRVQcowState *s = bs->opaque;
86 QCowExtension ext;
87 uint64_t offset;
88 int ret;
90 #ifdef DEBUG_EXT
91 printf("qcow2_read_extensions: start=%ld end=%ld\n", start_offset, end_offset);
92 #endif
93 offset = start_offset;
94 while (offset < end_offset) {
96 #ifdef DEBUG_EXT
97 /* Sanity check */
98 if (offset > s->cluster_size)
99 printf("qcow2_read_extension: suspicious offset %lu\n", offset);
101 printf("attempting to read extended header in offset %lu\n", offset);
102 #endif
104 ret = bdrv_pread(bs->file, offset, &ext, sizeof(ext));
105 if (ret < 0) {
106 error_setg_errno(errp, -ret, "qcow2_read_extension: ERROR: "
107 "pread fail from offset %" PRIu64, offset);
108 return 1;
110 be32_to_cpus(&ext.magic);
111 be32_to_cpus(&ext.len);
112 offset += sizeof(ext);
113 #ifdef DEBUG_EXT
114 printf("ext.magic = 0x%x\n", ext.magic);
115 #endif
116 if (ext.len > end_offset - offset) {
117 error_setg(errp, "Header extension too large");
118 return -EINVAL;
121 switch (ext.magic) {
122 case QCOW2_EXT_MAGIC_END:
123 return 0;
125 case QCOW2_EXT_MAGIC_BACKING_FORMAT:
126 if (ext.len >= sizeof(bs->backing_format)) {
127 error_setg(errp, "ERROR: ext_backing_format: len=%u too large"
128 " (>=%zu)", ext.len, sizeof(bs->backing_format));
129 return 2;
131 ret = bdrv_pread(bs->file, offset, bs->backing_format, ext.len);
132 if (ret < 0) {
133 error_setg_errno(errp, -ret, "ERROR: ext_backing_format: "
134 "Could not read format name");
135 return 3;
137 bs->backing_format[ext.len] = '\0';
138 #ifdef DEBUG_EXT
139 printf("Qcow2: Got format extension %s\n", bs->backing_format);
140 #endif
141 break;
143 case QCOW2_EXT_MAGIC_FEATURE_TABLE:
144 if (p_feature_table != NULL) {
145 void* feature_table = g_malloc0(ext.len + 2 * sizeof(Qcow2Feature));
146 ret = bdrv_pread(bs->file, offset , feature_table, ext.len);
147 if (ret < 0) {
148 error_setg_errno(errp, -ret, "ERROR: ext_feature_table: "
149 "Could not read table");
150 return ret;
153 *p_feature_table = feature_table;
155 break;
157 default:
158 /* unknown magic - save it in case we need to rewrite the header */
160 Qcow2UnknownHeaderExtension *uext;
162 uext = g_malloc0(sizeof(*uext) + ext.len);
163 uext->magic = ext.magic;
164 uext->len = ext.len;
165 QLIST_INSERT_HEAD(&s->unknown_header_ext, uext, next);
167 ret = bdrv_pread(bs->file, offset , uext->data, uext->len);
168 if (ret < 0) {
169 error_setg_errno(errp, -ret, "ERROR: unknown extension: "
170 "Could not read data");
171 return ret;
174 break;
177 offset += ((ext.len + 7) & ~7);
180 return 0;
183 static void cleanup_unknown_header_ext(BlockDriverState *bs)
185 BDRVQcowState *s = bs->opaque;
186 Qcow2UnknownHeaderExtension *uext, *next;
188 QLIST_FOREACH_SAFE(uext, &s->unknown_header_ext, next, next) {
189 QLIST_REMOVE(uext, next);
190 g_free(uext);
194 static void GCC_FMT_ATTR(3, 4) report_unsupported(BlockDriverState *bs,
195 Error **errp, const char *fmt, ...)
197 char msg[64];
198 va_list ap;
200 va_start(ap, fmt);
201 vsnprintf(msg, sizeof(msg), fmt, ap);
202 va_end(ap);
204 error_set(errp, QERR_UNKNOWN_BLOCK_FORMAT_FEATURE, bs->device_name, "qcow2",
205 msg);
208 static void report_unsupported_feature(BlockDriverState *bs,
209 Error **errp, Qcow2Feature *table, uint64_t mask)
211 while (table && table->name[0] != '\0') {
212 if (table->type == QCOW2_FEAT_TYPE_INCOMPATIBLE) {
213 if (mask & (1 << table->bit)) {
214 report_unsupported(bs, errp, "%.46s", table->name);
215 mask &= ~(1 << table->bit);
218 table++;
221 if (mask) {
222 report_unsupported(bs, errp, "Unknown incompatible feature: %" PRIx64,
223 mask);
228 * Sets the dirty bit and flushes afterwards if necessary.
230 * The incompatible_features bit is only set if the image file header was
231 * updated successfully. Therefore it is not required to check the return
232 * value of this function.
234 int qcow2_mark_dirty(BlockDriverState *bs)
236 BDRVQcowState *s = bs->opaque;
237 uint64_t val;
238 int ret;
240 assert(s->qcow_version >= 3);
242 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
243 return 0; /* already dirty */
246 val = cpu_to_be64(s->incompatible_features | QCOW2_INCOMPAT_DIRTY);
247 ret = bdrv_pwrite(bs->file, offsetof(QCowHeader, incompatible_features),
248 &val, sizeof(val));
249 if (ret < 0) {
250 return ret;
252 ret = bdrv_flush(bs->file);
253 if (ret < 0) {
254 return ret;
257 /* Only treat image as dirty if the header was updated successfully */
258 s->incompatible_features |= QCOW2_INCOMPAT_DIRTY;
259 return 0;
263 * Clears the dirty bit and flushes before if necessary. Only call this
264 * function when there are no pending requests, it does not guard against
265 * concurrent requests dirtying the image.
267 static int qcow2_mark_clean(BlockDriverState *bs)
269 BDRVQcowState *s = bs->opaque;
271 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
272 int ret = bdrv_flush(bs);
273 if (ret < 0) {
274 return ret;
277 s->incompatible_features &= ~QCOW2_INCOMPAT_DIRTY;
278 return qcow2_update_header(bs);
280 return 0;
284 * Marks the image as corrupt.
286 int qcow2_mark_corrupt(BlockDriverState *bs)
288 BDRVQcowState *s = bs->opaque;
290 s->incompatible_features |= QCOW2_INCOMPAT_CORRUPT;
291 return qcow2_update_header(bs);
295 * Marks the image as consistent, i.e., unsets the corrupt bit, and flushes
296 * before if necessary.
298 int qcow2_mark_consistent(BlockDriverState *bs)
300 BDRVQcowState *s = bs->opaque;
302 if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
303 int ret = bdrv_flush(bs);
304 if (ret < 0) {
305 return ret;
308 s->incompatible_features &= ~QCOW2_INCOMPAT_CORRUPT;
309 return qcow2_update_header(bs);
311 return 0;
314 static int qcow2_check(BlockDriverState *bs, BdrvCheckResult *result,
315 BdrvCheckMode fix)
317 int ret = qcow2_check_refcounts(bs, result, fix);
318 if (ret < 0) {
319 return ret;
322 if (fix && result->check_errors == 0 && result->corruptions == 0) {
323 ret = qcow2_mark_clean(bs);
324 if (ret < 0) {
325 return ret;
327 return qcow2_mark_consistent(bs);
329 return ret;
332 static int validate_table_offset(BlockDriverState *bs, uint64_t offset,
333 uint64_t entries, size_t entry_len)
335 BDRVQcowState *s = bs->opaque;
336 uint64_t size;
338 /* Use signed INT64_MAX as the maximum even for uint64_t header fields,
339 * because values will be passed to qemu functions taking int64_t. */
340 if (entries > INT64_MAX / entry_len) {
341 return -EINVAL;
344 size = entries * entry_len;
346 if (INT64_MAX - size < offset) {
347 return -EINVAL;
350 /* Tables must be cluster aligned */
351 if (offset & (s->cluster_size - 1)) {
352 return -EINVAL;
355 return 0;
358 static QemuOptsList qcow2_runtime_opts = {
359 .name = "qcow2",
360 .head = QTAILQ_HEAD_INITIALIZER(qcow2_runtime_opts.head),
361 .desc = {
363 .name = QCOW2_OPT_LAZY_REFCOUNTS,
364 .type = QEMU_OPT_BOOL,
365 .help = "Postpone refcount updates",
368 .name = QCOW2_OPT_DISCARD_REQUEST,
369 .type = QEMU_OPT_BOOL,
370 .help = "Pass guest discard requests to the layer below",
373 .name = QCOW2_OPT_DISCARD_SNAPSHOT,
374 .type = QEMU_OPT_BOOL,
375 .help = "Generate discard requests when snapshot related space "
376 "is freed",
379 .name = QCOW2_OPT_DISCARD_OTHER,
380 .type = QEMU_OPT_BOOL,
381 .help = "Generate discard requests when other clusters are freed",
384 .name = QCOW2_OPT_OVERLAP,
385 .type = QEMU_OPT_STRING,
386 .help = "Selects which overlap checks to perform from a range of "
387 "templates (none, constant, cached, all)",
390 .name = QCOW2_OPT_OVERLAP_MAIN_HEADER,
391 .type = QEMU_OPT_BOOL,
392 .help = "Check for unintended writes into the main qcow2 header",
395 .name = QCOW2_OPT_OVERLAP_ACTIVE_L1,
396 .type = QEMU_OPT_BOOL,
397 .help = "Check for unintended writes into the active L1 table",
400 .name = QCOW2_OPT_OVERLAP_ACTIVE_L2,
401 .type = QEMU_OPT_BOOL,
402 .help = "Check for unintended writes into an active L2 table",
405 .name = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
406 .type = QEMU_OPT_BOOL,
407 .help = "Check for unintended writes into the refcount table",
410 .name = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
411 .type = QEMU_OPT_BOOL,
412 .help = "Check for unintended writes into a refcount block",
415 .name = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
416 .type = QEMU_OPT_BOOL,
417 .help = "Check for unintended writes into the snapshot table",
420 .name = QCOW2_OPT_OVERLAP_INACTIVE_L1,
421 .type = QEMU_OPT_BOOL,
422 .help = "Check for unintended writes into an inactive L1 table",
425 .name = QCOW2_OPT_OVERLAP_INACTIVE_L2,
426 .type = QEMU_OPT_BOOL,
427 .help = "Check for unintended writes into an inactive L2 table",
429 { /* end of list */ }
433 static const char *overlap_bool_option_names[QCOW2_OL_MAX_BITNR] = {
434 [QCOW2_OL_MAIN_HEADER_BITNR] = QCOW2_OPT_OVERLAP_MAIN_HEADER,
435 [QCOW2_OL_ACTIVE_L1_BITNR] = QCOW2_OPT_OVERLAP_ACTIVE_L1,
436 [QCOW2_OL_ACTIVE_L2_BITNR] = QCOW2_OPT_OVERLAP_ACTIVE_L2,
437 [QCOW2_OL_REFCOUNT_TABLE_BITNR] = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
438 [QCOW2_OL_REFCOUNT_BLOCK_BITNR] = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
439 [QCOW2_OL_SNAPSHOT_TABLE_BITNR] = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
440 [QCOW2_OL_INACTIVE_L1_BITNR] = QCOW2_OPT_OVERLAP_INACTIVE_L1,
441 [QCOW2_OL_INACTIVE_L2_BITNR] = QCOW2_OPT_OVERLAP_INACTIVE_L2,
444 static int qcow2_open(BlockDriverState *bs, QDict *options, int flags,
445 Error **errp)
447 BDRVQcowState *s = bs->opaque;
448 unsigned int len, i;
449 int ret = 0;
450 QCowHeader header;
451 QemuOpts *opts;
452 Error *local_err = NULL;
453 uint64_t ext_end;
454 uint64_t l1_vm_state_index;
455 const char *opt_overlap_check;
456 int overlap_check_template = 0;
458 ret = bdrv_pread(bs->file, 0, &header, sizeof(header));
459 if (ret < 0) {
460 error_setg_errno(errp, -ret, "Could not read qcow2 header");
461 goto fail;
463 be32_to_cpus(&header.magic);
464 be32_to_cpus(&header.version);
465 be64_to_cpus(&header.backing_file_offset);
466 be32_to_cpus(&header.backing_file_size);
467 be64_to_cpus(&header.size);
468 be32_to_cpus(&header.cluster_bits);
469 be32_to_cpus(&header.crypt_method);
470 be64_to_cpus(&header.l1_table_offset);
471 be32_to_cpus(&header.l1_size);
472 be64_to_cpus(&header.refcount_table_offset);
473 be32_to_cpus(&header.refcount_table_clusters);
474 be64_to_cpus(&header.snapshots_offset);
475 be32_to_cpus(&header.nb_snapshots);
477 if (header.magic != QCOW_MAGIC) {
478 error_setg(errp, "Image is not in qcow2 format");
479 ret = -EINVAL;
480 goto fail;
482 if (header.version < 2 || header.version > 3) {
483 report_unsupported(bs, errp, "QCOW version %d", header.version);
484 ret = -ENOTSUP;
485 goto fail;
488 s->qcow_version = header.version;
490 /* Initialise cluster size */
491 if (header.cluster_bits < MIN_CLUSTER_BITS ||
492 header.cluster_bits > MAX_CLUSTER_BITS) {
493 error_setg(errp, "Unsupported cluster size: 2^%i", header.cluster_bits);
494 ret = -EINVAL;
495 goto fail;
498 s->cluster_bits = header.cluster_bits;
499 s->cluster_size = 1 << s->cluster_bits;
500 s->cluster_sectors = 1 << (s->cluster_bits - 9);
502 /* Initialise version 3 header fields */
503 if (header.version == 2) {
504 header.incompatible_features = 0;
505 header.compatible_features = 0;
506 header.autoclear_features = 0;
507 header.refcount_order = 4;
508 header.header_length = 72;
509 } else {
510 be64_to_cpus(&header.incompatible_features);
511 be64_to_cpus(&header.compatible_features);
512 be64_to_cpus(&header.autoclear_features);
513 be32_to_cpus(&header.refcount_order);
514 be32_to_cpus(&header.header_length);
516 if (header.header_length < 104) {
517 error_setg(errp, "qcow2 header too short");
518 ret = -EINVAL;
519 goto fail;
523 if (header.header_length > s->cluster_size) {
524 error_setg(errp, "qcow2 header exceeds cluster size");
525 ret = -EINVAL;
526 goto fail;
529 if (header.header_length > sizeof(header)) {
530 s->unknown_header_fields_size = header.header_length - sizeof(header);
531 s->unknown_header_fields = g_malloc(s->unknown_header_fields_size);
532 ret = bdrv_pread(bs->file, sizeof(header), s->unknown_header_fields,
533 s->unknown_header_fields_size);
534 if (ret < 0) {
535 error_setg_errno(errp, -ret, "Could not read unknown qcow2 header "
536 "fields");
537 goto fail;
541 if (header.backing_file_offset > s->cluster_size) {
542 error_setg(errp, "Invalid backing file offset");
543 ret = -EINVAL;
544 goto fail;
547 if (header.backing_file_offset) {
548 ext_end = header.backing_file_offset;
549 } else {
550 ext_end = 1 << header.cluster_bits;
553 /* Handle feature bits */
554 s->incompatible_features = header.incompatible_features;
555 s->compatible_features = header.compatible_features;
556 s->autoclear_features = header.autoclear_features;
558 if (s->incompatible_features & ~QCOW2_INCOMPAT_MASK) {
559 void *feature_table = NULL;
560 qcow2_read_extensions(bs, header.header_length, ext_end,
561 &feature_table, NULL);
562 report_unsupported_feature(bs, errp, feature_table,
563 s->incompatible_features &
564 ~QCOW2_INCOMPAT_MASK);
565 ret = -ENOTSUP;
566 g_free(feature_table);
567 goto fail;
570 if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
571 /* Corrupt images may not be written to unless they are being repaired
573 if ((flags & BDRV_O_RDWR) && !(flags & BDRV_O_CHECK)) {
574 error_setg(errp, "qcow2: Image is corrupt; cannot be opened "
575 "read/write");
576 ret = -EACCES;
577 goto fail;
581 /* Check support for various header values */
582 if (header.refcount_order != 4) {
583 report_unsupported(bs, errp, "%d bit reference counts",
584 1 << header.refcount_order);
585 ret = -ENOTSUP;
586 goto fail;
588 s->refcount_order = header.refcount_order;
590 if (header.crypt_method > QCOW_CRYPT_AES) {
591 error_setg(errp, "Unsupported encryption method: %i",
592 header.crypt_method);
593 ret = -EINVAL;
594 goto fail;
596 s->crypt_method_header = header.crypt_method;
597 if (s->crypt_method_header) {
598 bs->encrypted = 1;
601 s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */
602 s->l2_size = 1 << s->l2_bits;
603 bs->total_sectors = header.size / 512;
604 s->csize_shift = (62 - (s->cluster_bits - 8));
605 s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;
606 s->cluster_offset_mask = (1LL << s->csize_shift) - 1;
608 s->refcount_table_offset = header.refcount_table_offset;
609 s->refcount_table_size =
610 header.refcount_table_clusters << (s->cluster_bits - 3);
612 if (header.refcount_table_clusters > qcow2_max_refcount_clusters(s)) {
613 error_setg(errp, "Reference count table too large");
614 ret = -EINVAL;
615 goto fail;
618 ret = validate_table_offset(bs, s->refcount_table_offset,
619 s->refcount_table_size, sizeof(uint64_t));
620 if (ret < 0) {
621 error_setg(errp, "Invalid reference count table offset");
622 goto fail;
625 /* Snapshot table offset/length */
626 if (header.nb_snapshots > QCOW_MAX_SNAPSHOTS) {
627 error_setg(errp, "Too many snapshots");
628 ret = -EINVAL;
629 goto fail;
632 ret = validate_table_offset(bs, header.snapshots_offset,
633 header.nb_snapshots,
634 sizeof(QCowSnapshotHeader));
635 if (ret < 0) {
636 error_setg(errp, "Invalid snapshot table offset");
637 goto fail;
640 /* read the level 1 table */
641 if (header.l1_size > 0x2000000) {
642 /* 32 MB L1 table is enough for 2 PB images at 64k cluster size
643 * (128 GB for 512 byte clusters, 2 EB for 2 MB clusters) */
644 error_setg(errp, "Active L1 table too large");
645 ret = -EFBIG;
646 goto fail;
648 s->l1_size = header.l1_size;
650 l1_vm_state_index = size_to_l1(s, header.size);
651 if (l1_vm_state_index > INT_MAX) {
652 error_setg(errp, "Image is too big");
653 ret = -EFBIG;
654 goto fail;
656 s->l1_vm_state_index = l1_vm_state_index;
658 /* the L1 table must contain at least enough entries to put
659 header.size bytes */
660 if (s->l1_size < s->l1_vm_state_index) {
661 error_setg(errp, "L1 table is too small");
662 ret = -EINVAL;
663 goto fail;
666 ret = validate_table_offset(bs, header.l1_table_offset,
667 header.l1_size, sizeof(uint64_t));
668 if (ret < 0) {
669 error_setg(errp, "Invalid L1 table offset");
670 goto fail;
672 s->l1_table_offset = header.l1_table_offset;
675 if (s->l1_size > 0) {
676 s->l1_table = g_malloc0(
677 align_offset(s->l1_size * sizeof(uint64_t), 512));
678 ret = bdrv_pread(bs->file, s->l1_table_offset, s->l1_table,
679 s->l1_size * sizeof(uint64_t));
680 if (ret < 0) {
681 error_setg_errno(errp, -ret, "Could not read L1 table");
682 goto fail;
684 for(i = 0;i < s->l1_size; i++) {
685 be64_to_cpus(&s->l1_table[i]);
689 /* alloc L2 table/refcount block cache */
690 s->l2_table_cache = qcow2_cache_create(bs, L2_CACHE_SIZE);
691 s->refcount_block_cache = qcow2_cache_create(bs, REFCOUNT_CACHE_SIZE);
693 s->cluster_cache = g_malloc(s->cluster_size);
694 /* one more sector for decompressed data alignment */
695 s->cluster_data = qemu_blockalign(bs, QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size
696 + 512);
697 s->cluster_cache_offset = -1;
698 s->flags = flags;
700 ret = qcow2_refcount_init(bs);
701 if (ret != 0) {
702 error_setg_errno(errp, -ret, "Could not initialize refcount handling");
703 goto fail;
706 QLIST_INIT(&s->cluster_allocs);
707 QTAILQ_INIT(&s->discards);
709 /* read qcow2 extensions */
710 if (qcow2_read_extensions(bs, header.header_length, ext_end, NULL,
711 &local_err)) {
712 error_propagate(errp, local_err);
713 ret = -EINVAL;
714 goto fail;
717 /* read the backing file name */
718 if (header.backing_file_offset != 0) {
719 len = header.backing_file_size;
720 if (len > MIN(1023, s->cluster_size - header.backing_file_offset)) {
721 error_setg(errp, "Backing file name too long");
722 ret = -EINVAL;
723 goto fail;
725 ret = bdrv_pread(bs->file, header.backing_file_offset,
726 bs->backing_file, len);
727 if (ret < 0) {
728 error_setg_errno(errp, -ret, "Could not read backing file name");
729 goto fail;
731 bs->backing_file[len] = '\0';
734 /* Internal snapshots */
735 s->snapshots_offset = header.snapshots_offset;
736 s->nb_snapshots = header.nb_snapshots;
738 ret = qcow2_read_snapshots(bs);
739 if (ret < 0) {
740 error_setg_errno(errp, -ret, "Could not read snapshots");
741 goto fail;
744 /* Clear unknown autoclear feature bits */
745 if (!bs->read_only && !(flags & BDRV_O_INCOMING) && s->autoclear_features) {
746 s->autoclear_features = 0;
747 ret = qcow2_update_header(bs);
748 if (ret < 0) {
749 error_setg_errno(errp, -ret, "Could not update qcow2 header");
750 goto fail;
754 /* Initialise locks */
755 qemu_co_mutex_init(&s->lock);
757 /* Repair image if dirty */
758 if (!(flags & (BDRV_O_CHECK | BDRV_O_INCOMING)) && !bs->read_only &&
759 (s->incompatible_features & QCOW2_INCOMPAT_DIRTY)) {
760 BdrvCheckResult result = {0};
762 ret = qcow2_check(bs, &result, BDRV_FIX_ERRORS);
763 if (ret < 0) {
764 error_setg_errno(errp, -ret, "Could not repair dirty image");
765 goto fail;
769 /* Enable lazy_refcounts according to image and command line options */
770 opts = qemu_opts_create(&qcow2_runtime_opts, NULL, 0, &error_abort);
771 qemu_opts_absorb_qdict(opts, options, &local_err);
772 if (local_err) {
773 error_propagate(errp, local_err);
774 ret = -EINVAL;
775 goto fail;
778 s->use_lazy_refcounts = qemu_opt_get_bool(opts, QCOW2_OPT_LAZY_REFCOUNTS,
779 (s->compatible_features & QCOW2_COMPAT_LAZY_REFCOUNTS));
781 s->discard_passthrough[QCOW2_DISCARD_NEVER] = false;
782 s->discard_passthrough[QCOW2_DISCARD_ALWAYS] = true;
783 s->discard_passthrough[QCOW2_DISCARD_REQUEST] =
784 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_REQUEST,
785 flags & BDRV_O_UNMAP);
786 s->discard_passthrough[QCOW2_DISCARD_SNAPSHOT] =
787 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_SNAPSHOT, true);
788 s->discard_passthrough[QCOW2_DISCARD_OTHER] =
789 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_OTHER, false);
791 opt_overlap_check = qemu_opt_get(opts, "overlap-check") ?: "cached";
792 if (!strcmp(opt_overlap_check, "none")) {
793 overlap_check_template = 0;
794 } else if (!strcmp(opt_overlap_check, "constant")) {
795 overlap_check_template = QCOW2_OL_CONSTANT;
796 } else if (!strcmp(opt_overlap_check, "cached")) {
797 overlap_check_template = QCOW2_OL_CACHED;
798 } else if (!strcmp(opt_overlap_check, "all")) {
799 overlap_check_template = QCOW2_OL_ALL;
800 } else {
801 error_setg(errp, "Unsupported value '%s' for qcow2 option "
802 "'overlap-check'. Allowed are either of the following: "
803 "none, constant, cached, all", opt_overlap_check);
804 qemu_opts_del(opts);
805 ret = -EINVAL;
806 goto fail;
809 s->overlap_check = 0;
810 for (i = 0; i < QCOW2_OL_MAX_BITNR; i++) {
811 /* overlap-check defines a template bitmask, but every flag may be
812 * overwritten through the associated boolean option */
813 s->overlap_check |=
814 qemu_opt_get_bool(opts, overlap_bool_option_names[i],
815 overlap_check_template & (1 << i)) << i;
818 qemu_opts_del(opts);
820 if (s->use_lazy_refcounts && s->qcow_version < 3) {
821 error_setg(errp, "Lazy refcounts require a qcow2 image with at least "
822 "qemu 1.1 compatibility level");
823 ret = -EINVAL;
824 goto fail;
827 #ifdef DEBUG_ALLOC
829 BdrvCheckResult result = {0};
830 qcow2_check_refcounts(bs, &result, 0);
832 #endif
833 return ret;
835 fail:
836 g_free(s->unknown_header_fields);
837 cleanup_unknown_header_ext(bs);
838 qcow2_free_snapshots(bs);
839 qcow2_refcount_close(bs);
840 g_free(s->l1_table);
841 /* else pre-write overlap checks in cache_destroy may crash */
842 s->l1_table = NULL;
843 if (s->l2_table_cache) {
844 qcow2_cache_destroy(bs, s->l2_table_cache);
846 if (s->refcount_block_cache) {
847 qcow2_cache_destroy(bs, s->refcount_block_cache);
849 g_free(s->cluster_cache);
850 qemu_vfree(s->cluster_data);
851 return ret;
854 static int qcow2_refresh_limits(BlockDriverState *bs)
856 BDRVQcowState *s = bs->opaque;
858 bs->bl.write_zeroes_alignment = s->cluster_sectors;
860 return 0;
863 static int qcow2_set_key(BlockDriverState *bs, const char *key)
865 BDRVQcowState *s = bs->opaque;
866 uint8_t keybuf[16];
867 int len, i;
869 memset(keybuf, 0, 16);
870 len = strlen(key);
871 if (len > 16)
872 len = 16;
873 /* XXX: we could compress the chars to 7 bits to increase
874 entropy */
875 for(i = 0;i < len;i++) {
876 keybuf[i] = key[i];
878 s->crypt_method = s->crypt_method_header;
880 if (AES_set_encrypt_key(keybuf, 128, &s->aes_encrypt_key) != 0)
881 return -1;
882 if (AES_set_decrypt_key(keybuf, 128, &s->aes_decrypt_key) != 0)
883 return -1;
884 #if 0
885 /* test */
887 uint8_t in[16];
888 uint8_t out[16];
889 uint8_t tmp[16];
890 for(i=0;i<16;i++)
891 in[i] = i;
892 AES_encrypt(in, tmp, &s->aes_encrypt_key);
893 AES_decrypt(tmp, out, &s->aes_decrypt_key);
894 for(i = 0; i < 16; i++)
895 printf(" %02x", tmp[i]);
896 printf("\n");
897 for(i = 0; i < 16; i++)
898 printf(" %02x", out[i]);
899 printf("\n");
901 #endif
902 return 0;
905 /* We have nothing to do for QCOW2 reopen, stubs just return
906 * success */
907 static int qcow2_reopen_prepare(BDRVReopenState *state,
908 BlockReopenQueue *queue, Error **errp)
910 return 0;
913 static int64_t coroutine_fn qcow2_co_get_block_status(BlockDriverState *bs,
914 int64_t sector_num, int nb_sectors, int *pnum)
916 BDRVQcowState *s = bs->opaque;
917 uint64_t cluster_offset;
918 int index_in_cluster, ret;
919 int64_t status = 0;
921 *pnum = nb_sectors;
922 qemu_co_mutex_lock(&s->lock);
923 ret = qcow2_get_cluster_offset(bs, sector_num << 9, pnum, &cluster_offset);
924 qemu_co_mutex_unlock(&s->lock);
925 if (ret < 0) {
926 return ret;
929 if (cluster_offset != 0 && ret != QCOW2_CLUSTER_COMPRESSED &&
930 !s->crypt_method) {
931 index_in_cluster = sector_num & (s->cluster_sectors - 1);
932 cluster_offset |= (index_in_cluster << BDRV_SECTOR_BITS);
933 status |= BDRV_BLOCK_OFFSET_VALID | cluster_offset;
935 if (ret == QCOW2_CLUSTER_ZERO) {
936 status |= BDRV_BLOCK_ZERO;
937 } else if (ret != QCOW2_CLUSTER_UNALLOCATED) {
938 status |= BDRV_BLOCK_DATA;
940 return status;
943 /* handle reading after the end of the backing file */
944 int qcow2_backing_read1(BlockDriverState *bs, QEMUIOVector *qiov,
945 int64_t sector_num, int nb_sectors)
947 int n1;
948 if ((sector_num + nb_sectors) <= bs->total_sectors)
949 return nb_sectors;
950 if (sector_num >= bs->total_sectors)
951 n1 = 0;
952 else
953 n1 = bs->total_sectors - sector_num;
955 qemu_iovec_memset(qiov, 512 * n1, 0, 512 * (nb_sectors - n1));
957 return n1;
960 static coroutine_fn int qcow2_co_readv(BlockDriverState *bs, int64_t sector_num,
961 int remaining_sectors, QEMUIOVector *qiov)
963 BDRVQcowState *s = bs->opaque;
964 int index_in_cluster, n1;
965 int ret;
966 int cur_nr_sectors; /* number of sectors in current iteration */
967 uint64_t cluster_offset = 0;
968 uint64_t bytes_done = 0;
969 QEMUIOVector hd_qiov;
970 uint8_t *cluster_data = NULL;
972 qemu_iovec_init(&hd_qiov, qiov->niov);
974 qemu_co_mutex_lock(&s->lock);
976 while (remaining_sectors != 0) {
978 /* prepare next request */
979 cur_nr_sectors = remaining_sectors;
980 if (s->crypt_method) {
981 cur_nr_sectors = MIN(cur_nr_sectors,
982 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors);
985 ret = qcow2_get_cluster_offset(bs, sector_num << 9,
986 &cur_nr_sectors, &cluster_offset);
987 if (ret < 0) {
988 goto fail;
991 index_in_cluster = sector_num & (s->cluster_sectors - 1);
993 qemu_iovec_reset(&hd_qiov);
994 qemu_iovec_concat(&hd_qiov, qiov, bytes_done,
995 cur_nr_sectors * 512);
997 switch (ret) {
998 case QCOW2_CLUSTER_UNALLOCATED:
1000 if (bs->backing_hd) {
1001 /* read from the base image */
1002 n1 = qcow2_backing_read1(bs->backing_hd, &hd_qiov,
1003 sector_num, cur_nr_sectors);
1004 if (n1 > 0) {
1005 BLKDBG_EVENT(bs->file, BLKDBG_READ_BACKING_AIO);
1006 qemu_co_mutex_unlock(&s->lock);
1007 ret = bdrv_co_readv(bs->backing_hd, sector_num,
1008 n1, &hd_qiov);
1009 qemu_co_mutex_lock(&s->lock);
1010 if (ret < 0) {
1011 goto fail;
1014 } else {
1015 /* Note: in this case, no need to wait */
1016 qemu_iovec_memset(&hd_qiov, 0, 0, 512 * cur_nr_sectors);
1018 break;
1020 case QCOW2_CLUSTER_ZERO:
1021 qemu_iovec_memset(&hd_qiov, 0, 0, 512 * cur_nr_sectors);
1022 break;
1024 case QCOW2_CLUSTER_COMPRESSED:
1025 /* add AIO support for compressed blocks ? */
1026 ret = qcow2_decompress_cluster(bs, cluster_offset);
1027 if (ret < 0) {
1028 goto fail;
1031 qemu_iovec_from_buf(&hd_qiov, 0,
1032 s->cluster_cache + index_in_cluster * 512,
1033 512 * cur_nr_sectors);
1034 break;
1036 case QCOW2_CLUSTER_NORMAL:
1037 if ((cluster_offset & 511) != 0) {
1038 ret = -EIO;
1039 goto fail;
1042 if (s->crypt_method) {
1044 * For encrypted images, read everything into a temporary
1045 * contiguous buffer on which the AES functions can work.
1047 if (!cluster_data) {
1048 cluster_data =
1049 qemu_blockalign(bs, QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
1052 assert(cur_nr_sectors <=
1053 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors);
1054 qemu_iovec_reset(&hd_qiov);
1055 qemu_iovec_add(&hd_qiov, cluster_data,
1056 512 * cur_nr_sectors);
1059 BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);
1060 qemu_co_mutex_unlock(&s->lock);
1061 ret = bdrv_co_readv(bs->file,
1062 (cluster_offset >> 9) + index_in_cluster,
1063 cur_nr_sectors, &hd_qiov);
1064 qemu_co_mutex_lock(&s->lock);
1065 if (ret < 0) {
1066 goto fail;
1068 if (s->crypt_method) {
1069 qcow2_encrypt_sectors(s, sector_num, cluster_data,
1070 cluster_data, cur_nr_sectors, 0, &s->aes_decrypt_key);
1071 qemu_iovec_from_buf(qiov, bytes_done,
1072 cluster_data, 512 * cur_nr_sectors);
1074 break;
1076 default:
1077 g_assert_not_reached();
1078 ret = -EIO;
1079 goto fail;
1082 remaining_sectors -= cur_nr_sectors;
1083 sector_num += cur_nr_sectors;
1084 bytes_done += cur_nr_sectors * 512;
1086 ret = 0;
1088 fail:
1089 qemu_co_mutex_unlock(&s->lock);
1091 qemu_iovec_destroy(&hd_qiov);
1092 qemu_vfree(cluster_data);
1094 return ret;
1097 static coroutine_fn int qcow2_co_writev(BlockDriverState *bs,
1098 int64_t sector_num,
1099 int remaining_sectors,
1100 QEMUIOVector *qiov)
1102 BDRVQcowState *s = bs->opaque;
1103 int index_in_cluster;
1104 int ret;
1105 int cur_nr_sectors; /* number of sectors in current iteration */
1106 uint64_t cluster_offset;
1107 QEMUIOVector hd_qiov;
1108 uint64_t bytes_done = 0;
1109 uint8_t *cluster_data = NULL;
1110 QCowL2Meta *l2meta = NULL;
1112 trace_qcow2_writev_start_req(qemu_coroutine_self(), sector_num,
1113 remaining_sectors);
1115 qemu_iovec_init(&hd_qiov, qiov->niov);
1117 s->cluster_cache_offset = -1; /* disable compressed cache */
1119 qemu_co_mutex_lock(&s->lock);
1121 while (remaining_sectors != 0) {
1123 l2meta = NULL;
1125 trace_qcow2_writev_start_part(qemu_coroutine_self());
1126 index_in_cluster = sector_num & (s->cluster_sectors - 1);
1127 cur_nr_sectors = remaining_sectors;
1128 if (s->crypt_method &&
1129 cur_nr_sectors >
1130 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors - index_in_cluster) {
1131 cur_nr_sectors =
1132 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors - index_in_cluster;
1135 ret = qcow2_alloc_cluster_offset(bs, sector_num << 9,
1136 &cur_nr_sectors, &cluster_offset, &l2meta);
1137 if (ret < 0) {
1138 goto fail;
1141 assert((cluster_offset & 511) == 0);
1143 qemu_iovec_reset(&hd_qiov);
1144 qemu_iovec_concat(&hd_qiov, qiov, bytes_done,
1145 cur_nr_sectors * 512);
1147 if (s->crypt_method) {
1148 if (!cluster_data) {
1149 cluster_data = qemu_blockalign(bs, QCOW_MAX_CRYPT_CLUSTERS *
1150 s->cluster_size);
1153 assert(hd_qiov.size <=
1154 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
1155 qemu_iovec_to_buf(&hd_qiov, 0, cluster_data, hd_qiov.size);
1157 qcow2_encrypt_sectors(s, sector_num, cluster_data,
1158 cluster_data, cur_nr_sectors, 1, &s->aes_encrypt_key);
1160 qemu_iovec_reset(&hd_qiov);
1161 qemu_iovec_add(&hd_qiov, cluster_data,
1162 cur_nr_sectors * 512);
1165 ret = qcow2_pre_write_overlap_check(bs, 0,
1166 cluster_offset + index_in_cluster * BDRV_SECTOR_SIZE,
1167 cur_nr_sectors * BDRV_SECTOR_SIZE);
1168 if (ret < 0) {
1169 goto fail;
1172 qemu_co_mutex_unlock(&s->lock);
1173 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO);
1174 trace_qcow2_writev_data(qemu_coroutine_self(),
1175 (cluster_offset >> 9) + index_in_cluster);
1176 ret = bdrv_co_writev(bs->file,
1177 (cluster_offset >> 9) + index_in_cluster,
1178 cur_nr_sectors, &hd_qiov);
1179 qemu_co_mutex_lock(&s->lock);
1180 if (ret < 0) {
1181 goto fail;
1184 while (l2meta != NULL) {
1185 QCowL2Meta *next;
1187 ret = qcow2_alloc_cluster_link_l2(bs, l2meta);
1188 if (ret < 0) {
1189 goto fail;
1192 /* Take the request off the list of running requests */
1193 if (l2meta->nb_clusters != 0) {
1194 QLIST_REMOVE(l2meta, next_in_flight);
1197 qemu_co_queue_restart_all(&l2meta->dependent_requests);
1199 next = l2meta->next;
1200 g_free(l2meta);
1201 l2meta = next;
1204 remaining_sectors -= cur_nr_sectors;
1205 sector_num += cur_nr_sectors;
1206 bytes_done += cur_nr_sectors * 512;
1207 trace_qcow2_writev_done_part(qemu_coroutine_self(), cur_nr_sectors);
1209 ret = 0;
1211 fail:
1212 qemu_co_mutex_unlock(&s->lock);
1214 while (l2meta != NULL) {
1215 QCowL2Meta *next;
1217 if (l2meta->nb_clusters != 0) {
1218 QLIST_REMOVE(l2meta, next_in_flight);
1220 qemu_co_queue_restart_all(&l2meta->dependent_requests);
1222 next = l2meta->next;
1223 g_free(l2meta);
1224 l2meta = next;
1227 qemu_iovec_destroy(&hd_qiov);
1228 qemu_vfree(cluster_data);
1229 trace_qcow2_writev_done_req(qemu_coroutine_self(), ret);
1231 return ret;
1234 static void qcow2_close(BlockDriverState *bs)
1236 BDRVQcowState *s = bs->opaque;
1237 g_free(s->l1_table);
1238 /* else pre-write overlap checks in cache_destroy may crash */
1239 s->l1_table = NULL;
1241 if (!(bs->open_flags & BDRV_O_INCOMING)) {
1242 qcow2_cache_flush(bs, s->l2_table_cache);
1243 qcow2_cache_flush(bs, s->refcount_block_cache);
1245 qcow2_mark_clean(bs);
1248 qcow2_cache_destroy(bs, s->l2_table_cache);
1249 qcow2_cache_destroy(bs, s->refcount_block_cache);
1251 g_free(s->unknown_header_fields);
1252 cleanup_unknown_header_ext(bs);
1254 g_free(s->cluster_cache);
1255 qemu_vfree(s->cluster_data);
1256 qcow2_refcount_close(bs);
1257 qcow2_free_snapshots(bs);
1260 static void qcow2_invalidate_cache(BlockDriverState *bs, Error **errp)
1262 BDRVQcowState *s = bs->opaque;
1263 int flags = s->flags;
1264 AES_KEY aes_encrypt_key;
1265 AES_KEY aes_decrypt_key;
1266 uint32_t crypt_method = 0;
1267 QDict *options;
1268 Error *local_err = NULL;
1269 int ret;
1272 * Backing files are read-only which makes all of their metadata immutable,
1273 * that means we don't have to worry about reopening them here.
1276 if (s->crypt_method) {
1277 crypt_method = s->crypt_method;
1278 memcpy(&aes_encrypt_key, &s->aes_encrypt_key, sizeof(aes_encrypt_key));
1279 memcpy(&aes_decrypt_key, &s->aes_decrypt_key, sizeof(aes_decrypt_key));
1282 qcow2_close(bs);
1284 bdrv_invalidate_cache(bs->file, &local_err);
1285 if (local_err) {
1286 error_propagate(errp, local_err);
1287 return;
1290 memset(s, 0, sizeof(BDRVQcowState));
1291 options = qdict_clone_shallow(bs->options);
1293 ret = qcow2_open(bs, options, flags, &local_err);
1294 if (local_err) {
1295 error_setg(errp, "Could not reopen qcow2 layer: %s",
1296 error_get_pretty(local_err));
1297 error_free(local_err);
1298 return;
1299 } else if (ret < 0) {
1300 error_setg_errno(errp, -ret, "Could not reopen qcow2 layer");
1301 return;
1304 QDECREF(options);
1306 if (crypt_method) {
1307 s->crypt_method = crypt_method;
1308 memcpy(&s->aes_encrypt_key, &aes_encrypt_key, sizeof(aes_encrypt_key));
1309 memcpy(&s->aes_decrypt_key, &aes_decrypt_key, sizeof(aes_decrypt_key));
1313 static size_t header_ext_add(char *buf, uint32_t magic, const void *s,
1314 size_t len, size_t buflen)
1316 QCowExtension *ext_backing_fmt = (QCowExtension*) buf;
1317 size_t ext_len = sizeof(QCowExtension) + ((len + 7) & ~7);
1319 if (buflen < ext_len) {
1320 return -ENOSPC;
1323 *ext_backing_fmt = (QCowExtension) {
1324 .magic = cpu_to_be32(magic),
1325 .len = cpu_to_be32(len),
1327 memcpy(buf + sizeof(QCowExtension), s, len);
1329 return ext_len;
1333 * Updates the qcow2 header, including the variable length parts of it, i.e.
1334 * the backing file name and all extensions. qcow2 was not designed to allow
1335 * such changes, so if we run out of space (we can only use the first cluster)
1336 * this function may fail.
1338 * Returns 0 on success, -errno in error cases.
1340 int qcow2_update_header(BlockDriverState *bs)
1342 BDRVQcowState *s = bs->opaque;
1343 QCowHeader *header;
1344 char *buf;
1345 size_t buflen = s->cluster_size;
1346 int ret;
1347 uint64_t total_size;
1348 uint32_t refcount_table_clusters;
1349 size_t header_length;
1350 Qcow2UnknownHeaderExtension *uext;
1352 buf = qemu_blockalign(bs, buflen);
1354 /* Header structure */
1355 header = (QCowHeader*) buf;
1357 if (buflen < sizeof(*header)) {
1358 ret = -ENOSPC;
1359 goto fail;
1362 header_length = sizeof(*header) + s->unknown_header_fields_size;
1363 total_size = bs->total_sectors * BDRV_SECTOR_SIZE;
1364 refcount_table_clusters = s->refcount_table_size >> (s->cluster_bits - 3);
1366 *header = (QCowHeader) {
1367 /* Version 2 fields */
1368 .magic = cpu_to_be32(QCOW_MAGIC),
1369 .version = cpu_to_be32(s->qcow_version),
1370 .backing_file_offset = 0,
1371 .backing_file_size = 0,
1372 .cluster_bits = cpu_to_be32(s->cluster_bits),
1373 .size = cpu_to_be64(total_size),
1374 .crypt_method = cpu_to_be32(s->crypt_method_header),
1375 .l1_size = cpu_to_be32(s->l1_size),
1376 .l1_table_offset = cpu_to_be64(s->l1_table_offset),
1377 .refcount_table_offset = cpu_to_be64(s->refcount_table_offset),
1378 .refcount_table_clusters = cpu_to_be32(refcount_table_clusters),
1379 .nb_snapshots = cpu_to_be32(s->nb_snapshots),
1380 .snapshots_offset = cpu_to_be64(s->snapshots_offset),
1382 /* Version 3 fields */
1383 .incompatible_features = cpu_to_be64(s->incompatible_features),
1384 .compatible_features = cpu_to_be64(s->compatible_features),
1385 .autoclear_features = cpu_to_be64(s->autoclear_features),
1386 .refcount_order = cpu_to_be32(s->refcount_order),
1387 .header_length = cpu_to_be32(header_length),
1390 /* For older versions, write a shorter header */
1391 switch (s->qcow_version) {
1392 case 2:
1393 ret = offsetof(QCowHeader, incompatible_features);
1394 break;
1395 case 3:
1396 ret = sizeof(*header);
1397 break;
1398 default:
1399 ret = -EINVAL;
1400 goto fail;
1403 buf += ret;
1404 buflen -= ret;
1405 memset(buf, 0, buflen);
1407 /* Preserve any unknown field in the header */
1408 if (s->unknown_header_fields_size) {
1409 if (buflen < s->unknown_header_fields_size) {
1410 ret = -ENOSPC;
1411 goto fail;
1414 memcpy(buf, s->unknown_header_fields, s->unknown_header_fields_size);
1415 buf += s->unknown_header_fields_size;
1416 buflen -= s->unknown_header_fields_size;
1419 /* Backing file format header extension */
1420 if (*bs->backing_format) {
1421 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BACKING_FORMAT,
1422 bs->backing_format, strlen(bs->backing_format),
1423 buflen);
1424 if (ret < 0) {
1425 goto fail;
1428 buf += ret;
1429 buflen -= ret;
1432 /* Feature table */
1433 Qcow2Feature features[] = {
1435 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
1436 .bit = QCOW2_INCOMPAT_DIRTY_BITNR,
1437 .name = "dirty bit",
1440 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
1441 .bit = QCOW2_INCOMPAT_CORRUPT_BITNR,
1442 .name = "corrupt bit",
1445 .type = QCOW2_FEAT_TYPE_COMPATIBLE,
1446 .bit = QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR,
1447 .name = "lazy refcounts",
1451 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_FEATURE_TABLE,
1452 features, sizeof(features), buflen);
1453 if (ret < 0) {
1454 goto fail;
1456 buf += ret;
1457 buflen -= ret;
1459 /* Keep unknown header extensions */
1460 QLIST_FOREACH(uext, &s->unknown_header_ext, next) {
1461 ret = header_ext_add(buf, uext->magic, uext->data, uext->len, buflen);
1462 if (ret < 0) {
1463 goto fail;
1466 buf += ret;
1467 buflen -= ret;
1470 /* End of header extensions */
1471 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_END, NULL, 0, buflen);
1472 if (ret < 0) {
1473 goto fail;
1476 buf += ret;
1477 buflen -= ret;
1479 /* Backing file name */
1480 if (*bs->backing_file) {
1481 size_t backing_file_len = strlen(bs->backing_file);
1483 if (buflen < backing_file_len) {
1484 ret = -ENOSPC;
1485 goto fail;
1488 /* Using strncpy is ok here, since buf is not NUL-terminated. */
1489 strncpy(buf, bs->backing_file, buflen);
1491 header->backing_file_offset = cpu_to_be64(buf - ((char*) header));
1492 header->backing_file_size = cpu_to_be32(backing_file_len);
1495 /* Write the new header */
1496 ret = bdrv_pwrite(bs->file, 0, header, s->cluster_size);
1497 if (ret < 0) {
1498 goto fail;
1501 ret = 0;
1502 fail:
1503 qemu_vfree(header);
1504 return ret;
1507 static int qcow2_change_backing_file(BlockDriverState *bs,
1508 const char *backing_file, const char *backing_fmt)
1510 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
1511 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
1513 return qcow2_update_header(bs);
1516 static int preallocate(BlockDriverState *bs)
1518 uint64_t nb_sectors;
1519 uint64_t offset;
1520 uint64_t host_offset = 0;
1521 int num;
1522 int ret;
1523 QCowL2Meta *meta;
1525 nb_sectors = bdrv_getlength(bs) >> BDRV_SECTOR_BITS;
1526 offset = 0;
1528 while (nb_sectors) {
1529 num = MIN(nb_sectors, INT_MAX >> BDRV_SECTOR_BITS);
1530 ret = qcow2_alloc_cluster_offset(bs, offset, &num,
1531 &host_offset, &meta);
1532 if (ret < 0) {
1533 return ret;
1536 if (meta != NULL) {
1537 ret = qcow2_alloc_cluster_link_l2(bs, meta);
1538 if (ret < 0) {
1539 qcow2_free_any_clusters(bs, meta->alloc_offset,
1540 meta->nb_clusters, QCOW2_DISCARD_NEVER);
1541 return ret;
1544 /* There are no dependent requests, but we need to remove our
1545 * request from the list of in-flight requests */
1546 QLIST_REMOVE(meta, next_in_flight);
1549 /* TODO Preallocate data if requested */
1551 nb_sectors -= num;
1552 offset += num << BDRV_SECTOR_BITS;
1556 * It is expected that the image file is large enough to actually contain
1557 * all of the allocated clusters (otherwise we get failing reads after
1558 * EOF). Extend the image to the last allocated sector.
1560 if (host_offset != 0) {
1561 uint8_t buf[BDRV_SECTOR_SIZE];
1562 memset(buf, 0, BDRV_SECTOR_SIZE);
1563 ret = bdrv_write(bs->file, (host_offset >> BDRV_SECTOR_BITS) + num - 1,
1564 buf, 1);
1565 if (ret < 0) {
1566 return ret;
1570 return 0;
1573 static int qcow2_create2(const char *filename, int64_t total_size,
1574 const char *backing_file, const char *backing_format,
1575 int flags, size_t cluster_size, int prealloc,
1576 QEMUOptionParameter *options, int version,
1577 Error **errp)
1579 /* Calculate cluster_bits */
1580 int cluster_bits;
1581 cluster_bits = ffs(cluster_size) - 1;
1582 if (cluster_bits < MIN_CLUSTER_BITS || cluster_bits > MAX_CLUSTER_BITS ||
1583 (1 << cluster_bits) != cluster_size)
1585 error_setg(errp, "Cluster size must be a power of two between %d and "
1586 "%dk", 1 << MIN_CLUSTER_BITS, 1 << (MAX_CLUSTER_BITS - 10));
1587 return -EINVAL;
1591 * Open the image file and write a minimal qcow2 header.
1593 * We keep things simple and start with a zero-sized image. We also
1594 * do without refcount blocks or a L1 table for now. We'll fix the
1595 * inconsistency later.
1597 * We do need a refcount table because growing the refcount table means
1598 * allocating two new refcount blocks - the seconds of which would be at
1599 * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
1600 * size for any qcow2 image.
1602 BlockDriverState* bs;
1603 QCowHeader *header;
1604 uint64_t* refcount_table;
1605 Error *local_err = NULL;
1606 int ret;
1608 ret = bdrv_create_file(filename, options, &local_err);
1609 if (ret < 0) {
1610 error_propagate(errp, local_err);
1611 return ret;
1614 bs = NULL;
1615 ret = bdrv_open(&bs, filename, NULL, NULL, BDRV_O_RDWR | BDRV_O_PROTOCOL,
1616 NULL, &local_err);
1617 if (ret < 0) {
1618 error_propagate(errp, local_err);
1619 return ret;
1622 /* Write the header */
1623 QEMU_BUILD_BUG_ON((1 << MIN_CLUSTER_BITS) < sizeof(*header));
1624 header = g_malloc0(cluster_size);
1625 *header = (QCowHeader) {
1626 .magic = cpu_to_be32(QCOW_MAGIC),
1627 .version = cpu_to_be32(version),
1628 .cluster_bits = cpu_to_be32(cluster_bits),
1629 .size = cpu_to_be64(0),
1630 .l1_table_offset = cpu_to_be64(0),
1631 .l1_size = cpu_to_be32(0),
1632 .refcount_table_offset = cpu_to_be64(cluster_size),
1633 .refcount_table_clusters = cpu_to_be32(1),
1634 .refcount_order = cpu_to_be32(3 + REFCOUNT_SHIFT),
1635 .header_length = cpu_to_be32(sizeof(*header)),
1638 if (flags & BLOCK_FLAG_ENCRYPT) {
1639 header->crypt_method = cpu_to_be32(QCOW_CRYPT_AES);
1640 } else {
1641 header->crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
1644 if (flags & BLOCK_FLAG_LAZY_REFCOUNTS) {
1645 header->compatible_features |=
1646 cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS);
1649 ret = bdrv_pwrite(bs, 0, header, cluster_size);
1650 g_free(header);
1651 if (ret < 0) {
1652 error_setg_errno(errp, -ret, "Could not write qcow2 header");
1653 goto out;
1656 /* Write a refcount table with one refcount block */
1657 refcount_table = g_malloc0(2 * cluster_size);
1658 refcount_table[0] = cpu_to_be64(2 * cluster_size);
1659 ret = bdrv_pwrite(bs, cluster_size, refcount_table, 2 * cluster_size);
1660 g_free(refcount_table);
1662 if (ret < 0) {
1663 error_setg_errno(errp, -ret, "Could not write refcount table");
1664 goto out;
1667 bdrv_unref(bs);
1668 bs = NULL;
1671 * And now open the image and make it consistent first (i.e. increase the
1672 * refcount of the cluster that is occupied by the header and the refcount
1673 * table)
1675 BlockDriver* drv = bdrv_find_format("qcow2");
1676 assert(drv != NULL);
1677 ret = bdrv_open(&bs, filename, NULL, NULL,
1678 BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_NO_FLUSH, drv, &local_err);
1679 if (ret < 0) {
1680 error_propagate(errp, local_err);
1681 goto out;
1684 ret = qcow2_alloc_clusters(bs, 3 * cluster_size);
1685 if (ret < 0) {
1686 error_setg_errno(errp, -ret, "Could not allocate clusters for qcow2 "
1687 "header and refcount table");
1688 goto out;
1690 } else if (ret != 0) {
1691 error_report("Huh, first cluster in empty image is already in use?");
1692 abort();
1695 /* Okay, now that we have a valid image, let's give it the right size */
1696 ret = bdrv_truncate(bs, total_size * BDRV_SECTOR_SIZE);
1697 if (ret < 0) {
1698 error_setg_errno(errp, -ret, "Could not resize image");
1699 goto out;
1702 /* Want a backing file? There you go.*/
1703 if (backing_file) {
1704 ret = bdrv_change_backing_file(bs, backing_file, backing_format);
1705 if (ret < 0) {
1706 error_setg_errno(errp, -ret, "Could not assign backing file '%s' "
1707 "with format '%s'", backing_file, backing_format);
1708 goto out;
1712 /* And if we're supposed to preallocate metadata, do that now */
1713 if (prealloc) {
1714 BDRVQcowState *s = bs->opaque;
1715 qemu_co_mutex_lock(&s->lock);
1716 ret = preallocate(bs);
1717 qemu_co_mutex_unlock(&s->lock);
1718 if (ret < 0) {
1719 error_setg_errno(errp, -ret, "Could not preallocate metadata");
1720 goto out;
1724 bdrv_unref(bs);
1725 bs = NULL;
1727 /* Reopen the image without BDRV_O_NO_FLUSH to flush it before returning */
1728 ret = bdrv_open(&bs, filename, NULL, NULL,
1729 BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_NO_BACKING,
1730 drv, &local_err);
1731 if (local_err) {
1732 error_propagate(errp, local_err);
1733 goto out;
1736 ret = 0;
1737 out:
1738 if (bs) {
1739 bdrv_unref(bs);
1741 return ret;
1744 static int qcow2_create(const char *filename, QEMUOptionParameter *options,
1745 Error **errp)
1747 const char *backing_file = NULL;
1748 const char *backing_fmt = NULL;
1749 uint64_t sectors = 0;
1750 int flags = 0;
1751 size_t cluster_size = DEFAULT_CLUSTER_SIZE;
1752 int prealloc = 0;
1753 int version = 3;
1754 Error *local_err = NULL;
1755 int ret;
1757 /* Read out options */
1758 while (options && options->name) {
1759 if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
1760 sectors = options->value.n / 512;
1761 } else if (!strcmp(options->name, BLOCK_OPT_BACKING_FILE)) {
1762 backing_file = options->value.s;
1763 } else if (!strcmp(options->name, BLOCK_OPT_BACKING_FMT)) {
1764 backing_fmt = options->value.s;
1765 } else if (!strcmp(options->name, BLOCK_OPT_ENCRYPT)) {
1766 flags |= options->value.n ? BLOCK_FLAG_ENCRYPT : 0;
1767 } else if (!strcmp(options->name, BLOCK_OPT_CLUSTER_SIZE)) {
1768 if (options->value.n) {
1769 cluster_size = options->value.n;
1771 } else if (!strcmp(options->name, BLOCK_OPT_PREALLOC)) {
1772 if (!options->value.s || !strcmp(options->value.s, "off")) {
1773 prealloc = 0;
1774 } else if (!strcmp(options->value.s, "metadata")) {
1775 prealloc = 1;
1776 } else {
1777 error_setg(errp, "Invalid preallocation mode: '%s'",
1778 options->value.s);
1779 return -EINVAL;
1781 } else if (!strcmp(options->name, BLOCK_OPT_COMPAT_LEVEL)) {
1782 if (!options->value.s) {
1783 /* keep the default */
1784 } else if (!strcmp(options->value.s, "0.10")) {
1785 version = 2;
1786 } else if (!strcmp(options->value.s, "1.1")) {
1787 version = 3;
1788 } else {
1789 error_setg(errp, "Invalid compatibility level: '%s'",
1790 options->value.s);
1791 return -EINVAL;
1793 } else if (!strcmp(options->name, BLOCK_OPT_LAZY_REFCOUNTS)) {
1794 flags |= options->value.n ? BLOCK_FLAG_LAZY_REFCOUNTS : 0;
1796 options++;
1799 if (backing_file && prealloc) {
1800 error_setg(errp, "Backing file and preallocation cannot be used at "
1801 "the same time");
1802 return -EINVAL;
1805 if (version < 3 && (flags & BLOCK_FLAG_LAZY_REFCOUNTS)) {
1806 error_setg(errp, "Lazy refcounts only supported with compatibility "
1807 "level 1.1 and above (use compat=1.1 or greater)");
1808 return -EINVAL;
1811 ret = qcow2_create2(filename, sectors, backing_file, backing_fmt, flags,
1812 cluster_size, prealloc, options, version, &local_err);
1813 if (local_err) {
1814 error_propagate(errp, local_err);
1816 return ret;
1819 static coroutine_fn int qcow2_co_write_zeroes(BlockDriverState *bs,
1820 int64_t sector_num, int nb_sectors, BdrvRequestFlags flags)
1822 int ret;
1823 BDRVQcowState *s = bs->opaque;
1825 /* Emulate misaligned zero writes */
1826 if (sector_num % s->cluster_sectors || nb_sectors % s->cluster_sectors) {
1827 return -ENOTSUP;
1830 /* Whatever is left can use real zero clusters */
1831 qemu_co_mutex_lock(&s->lock);
1832 ret = qcow2_zero_clusters(bs, sector_num << BDRV_SECTOR_BITS,
1833 nb_sectors);
1834 qemu_co_mutex_unlock(&s->lock);
1836 return ret;
1839 static coroutine_fn int qcow2_co_discard(BlockDriverState *bs,
1840 int64_t sector_num, int nb_sectors)
1842 int ret;
1843 BDRVQcowState *s = bs->opaque;
1845 qemu_co_mutex_lock(&s->lock);
1846 ret = qcow2_discard_clusters(bs, sector_num << BDRV_SECTOR_BITS,
1847 nb_sectors, QCOW2_DISCARD_REQUEST);
1848 qemu_co_mutex_unlock(&s->lock);
1849 return ret;
1852 static int qcow2_truncate(BlockDriverState *bs, int64_t offset)
1854 BDRVQcowState *s = bs->opaque;
1855 int64_t new_l1_size;
1856 int ret;
1858 if (offset & 511) {
1859 error_report("The new size must be a multiple of 512");
1860 return -EINVAL;
1863 /* cannot proceed if image has snapshots */
1864 if (s->nb_snapshots) {
1865 error_report("Can't resize an image which has snapshots");
1866 return -ENOTSUP;
1869 /* shrinking is currently not supported */
1870 if (offset < bs->total_sectors * 512) {
1871 error_report("qcow2 doesn't support shrinking images yet");
1872 return -ENOTSUP;
1875 new_l1_size = size_to_l1(s, offset);
1876 ret = qcow2_grow_l1_table(bs, new_l1_size, true);
1877 if (ret < 0) {
1878 return ret;
1881 /* write updated header.size */
1882 offset = cpu_to_be64(offset);
1883 ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, size),
1884 &offset, sizeof(uint64_t));
1885 if (ret < 0) {
1886 return ret;
1889 s->l1_vm_state_index = new_l1_size;
1890 return 0;
1893 /* XXX: put compressed sectors first, then all the cluster aligned
1894 tables to avoid losing bytes in alignment */
1895 static int qcow2_write_compressed(BlockDriverState *bs, int64_t sector_num,
1896 const uint8_t *buf, int nb_sectors)
1898 BDRVQcowState *s = bs->opaque;
1899 z_stream strm;
1900 int ret, out_len;
1901 uint8_t *out_buf;
1902 uint64_t cluster_offset;
1904 if (nb_sectors == 0) {
1905 /* align end of file to a sector boundary to ease reading with
1906 sector based I/Os */
1907 cluster_offset = bdrv_getlength(bs->file);
1908 cluster_offset = (cluster_offset + 511) & ~511;
1909 bdrv_truncate(bs->file, cluster_offset);
1910 return 0;
1913 if (nb_sectors != s->cluster_sectors) {
1914 ret = -EINVAL;
1916 /* Zero-pad last write if image size is not cluster aligned */
1917 if (sector_num + nb_sectors == bs->total_sectors &&
1918 nb_sectors < s->cluster_sectors) {
1919 uint8_t *pad_buf = qemu_blockalign(bs, s->cluster_size);
1920 memset(pad_buf, 0, s->cluster_size);
1921 memcpy(pad_buf, buf, nb_sectors * BDRV_SECTOR_SIZE);
1922 ret = qcow2_write_compressed(bs, sector_num,
1923 pad_buf, s->cluster_sectors);
1924 qemu_vfree(pad_buf);
1926 return ret;
1929 out_buf = g_malloc(s->cluster_size + (s->cluster_size / 1000) + 128);
1931 /* best compression, small window, no zlib header */
1932 memset(&strm, 0, sizeof(strm));
1933 ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
1934 Z_DEFLATED, -12,
1935 9, Z_DEFAULT_STRATEGY);
1936 if (ret != 0) {
1937 ret = -EINVAL;
1938 goto fail;
1941 strm.avail_in = s->cluster_size;
1942 strm.next_in = (uint8_t *)buf;
1943 strm.avail_out = s->cluster_size;
1944 strm.next_out = out_buf;
1946 ret = deflate(&strm, Z_FINISH);
1947 if (ret != Z_STREAM_END && ret != Z_OK) {
1948 deflateEnd(&strm);
1949 ret = -EINVAL;
1950 goto fail;
1952 out_len = strm.next_out - out_buf;
1954 deflateEnd(&strm);
1956 if (ret != Z_STREAM_END || out_len >= s->cluster_size) {
1957 /* could not compress: write normal cluster */
1958 ret = bdrv_write(bs, sector_num, buf, s->cluster_sectors);
1959 if (ret < 0) {
1960 goto fail;
1962 } else {
1963 cluster_offset = qcow2_alloc_compressed_cluster_offset(bs,
1964 sector_num << 9, out_len);
1965 if (!cluster_offset) {
1966 ret = -EIO;
1967 goto fail;
1969 cluster_offset &= s->cluster_offset_mask;
1971 ret = qcow2_pre_write_overlap_check(bs, 0, cluster_offset, out_len);
1972 if (ret < 0) {
1973 goto fail;
1976 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_COMPRESSED);
1977 ret = bdrv_pwrite(bs->file, cluster_offset, out_buf, out_len);
1978 if (ret < 0) {
1979 goto fail;
1983 ret = 0;
1984 fail:
1985 g_free(out_buf);
1986 return ret;
1989 static coroutine_fn int qcow2_co_flush_to_os(BlockDriverState *bs)
1991 BDRVQcowState *s = bs->opaque;
1992 int ret;
1994 qemu_co_mutex_lock(&s->lock);
1995 ret = qcow2_cache_flush(bs, s->l2_table_cache);
1996 if (ret < 0) {
1997 qemu_co_mutex_unlock(&s->lock);
1998 return ret;
2001 if (qcow2_need_accurate_refcounts(s)) {
2002 ret = qcow2_cache_flush(bs, s->refcount_block_cache);
2003 if (ret < 0) {
2004 qemu_co_mutex_unlock(&s->lock);
2005 return ret;
2008 qemu_co_mutex_unlock(&s->lock);
2010 return 0;
2013 static int qcow2_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
2015 BDRVQcowState *s = bs->opaque;
2016 bdi->unallocated_blocks_are_zero = true;
2017 bdi->can_write_zeroes_with_unmap = (s->qcow_version >= 3);
2018 bdi->cluster_size = s->cluster_size;
2019 bdi->vm_state_offset = qcow2_vm_state_offset(s);
2020 return 0;
2023 static ImageInfoSpecific *qcow2_get_specific_info(BlockDriverState *bs)
2025 BDRVQcowState *s = bs->opaque;
2026 ImageInfoSpecific *spec_info = g_new(ImageInfoSpecific, 1);
2028 *spec_info = (ImageInfoSpecific){
2029 .kind = IMAGE_INFO_SPECIFIC_KIND_QCOW2,
2031 .qcow2 = g_new(ImageInfoSpecificQCow2, 1),
2034 if (s->qcow_version == 2) {
2035 *spec_info->qcow2 = (ImageInfoSpecificQCow2){
2036 .compat = g_strdup("0.10"),
2038 } else if (s->qcow_version == 3) {
2039 *spec_info->qcow2 = (ImageInfoSpecificQCow2){
2040 .compat = g_strdup("1.1"),
2041 .lazy_refcounts = s->compatible_features &
2042 QCOW2_COMPAT_LAZY_REFCOUNTS,
2043 .has_lazy_refcounts = true,
2047 return spec_info;
2050 #if 0
2051 static void dump_refcounts(BlockDriverState *bs)
2053 BDRVQcowState *s = bs->opaque;
2054 int64_t nb_clusters, k, k1, size;
2055 int refcount;
2057 size = bdrv_getlength(bs->file);
2058 nb_clusters = size_to_clusters(s, size);
2059 for(k = 0; k < nb_clusters;) {
2060 k1 = k;
2061 refcount = get_refcount(bs, k);
2062 k++;
2063 while (k < nb_clusters && get_refcount(bs, k) == refcount)
2064 k++;
2065 printf("%" PRId64 ": refcount=%d nb=%" PRId64 "\n", k, refcount,
2066 k - k1);
2069 #endif
2071 static int qcow2_save_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
2072 int64_t pos)
2074 BDRVQcowState *s = bs->opaque;
2075 int64_t total_sectors = bs->total_sectors;
2076 int growable = bs->growable;
2077 bool zero_beyond_eof = bs->zero_beyond_eof;
2078 int ret;
2080 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_SAVE);
2081 bs->growable = 1;
2082 bs->zero_beyond_eof = false;
2083 ret = bdrv_pwritev(bs, qcow2_vm_state_offset(s) + pos, qiov);
2084 bs->growable = growable;
2085 bs->zero_beyond_eof = zero_beyond_eof;
2087 /* bdrv_co_do_writev will have increased the total_sectors value to include
2088 * the VM state - the VM state is however not an actual part of the block
2089 * device, therefore, we need to restore the old value. */
2090 bs->total_sectors = total_sectors;
2092 return ret;
2095 static int qcow2_load_vmstate(BlockDriverState *bs, uint8_t *buf,
2096 int64_t pos, int size)
2098 BDRVQcowState *s = bs->opaque;
2099 int growable = bs->growable;
2100 bool zero_beyond_eof = bs->zero_beyond_eof;
2101 int ret;
2103 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_LOAD);
2104 bs->growable = 1;
2105 bs->zero_beyond_eof = false;
2106 ret = bdrv_pread(bs, qcow2_vm_state_offset(s) + pos, buf, size);
2107 bs->growable = growable;
2108 bs->zero_beyond_eof = zero_beyond_eof;
2110 return ret;
2114 * Downgrades an image's version. To achieve this, any incompatible features
2115 * have to be removed.
2117 static int qcow2_downgrade(BlockDriverState *bs, int target_version)
2119 BDRVQcowState *s = bs->opaque;
2120 int current_version = s->qcow_version;
2121 int ret;
2123 if (target_version == current_version) {
2124 return 0;
2125 } else if (target_version > current_version) {
2126 return -EINVAL;
2127 } else if (target_version != 2) {
2128 return -EINVAL;
2131 if (s->refcount_order != 4) {
2132 /* we would have to convert the image to a refcount_order == 4 image
2133 * here; however, since qemu (at the time of writing this) does not
2134 * support anything different than 4 anyway, there is no point in doing
2135 * so right now; however, we should error out (if qemu supports this in
2136 * the future and this code has not been adapted) */
2137 error_report("qcow2_downgrade: Image refcount orders other than 4 are "
2138 "currently not supported.");
2139 return -ENOTSUP;
2142 /* clear incompatible features */
2143 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
2144 ret = qcow2_mark_clean(bs);
2145 if (ret < 0) {
2146 return ret;
2150 /* with QCOW2_INCOMPAT_CORRUPT, it is pretty much impossible to get here in
2151 * the first place; if that happens nonetheless, returning -ENOTSUP is the
2152 * best thing to do anyway */
2154 if (s->incompatible_features) {
2155 return -ENOTSUP;
2158 /* since we can ignore compatible features, we can set them to 0 as well */
2159 s->compatible_features = 0;
2160 /* if lazy refcounts have been used, they have already been fixed through
2161 * clearing the dirty flag */
2163 /* clearing autoclear features is trivial */
2164 s->autoclear_features = 0;
2166 ret = qcow2_expand_zero_clusters(bs);
2167 if (ret < 0) {
2168 return ret;
2171 s->qcow_version = target_version;
2172 ret = qcow2_update_header(bs);
2173 if (ret < 0) {
2174 s->qcow_version = current_version;
2175 return ret;
2177 return 0;
2180 static int qcow2_amend_options(BlockDriverState *bs,
2181 QEMUOptionParameter *options)
2183 BDRVQcowState *s = bs->opaque;
2184 int old_version = s->qcow_version, new_version = old_version;
2185 uint64_t new_size = 0;
2186 const char *backing_file = NULL, *backing_format = NULL;
2187 bool lazy_refcounts = s->use_lazy_refcounts;
2188 int ret;
2189 int i;
2191 for (i = 0; options[i].name; i++)
2193 if (!options[i].assigned) {
2194 /* only change explicitly defined options */
2195 continue;
2198 if (!strcmp(options[i].name, "compat")) {
2199 if (!options[i].value.s) {
2200 /* preserve default */
2201 } else if (!strcmp(options[i].value.s, "0.10")) {
2202 new_version = 2;
2203 } else if (!strcmp(options[i].value.s, "1.1")) {
2204 new_version = 3;
2205 } else {
2206 fprintf(stderr, "Unknown compatibility level %s.\n",
2207 options[i].value.s);
2208 return -EINVAL;
2210 } else if (!strcmp(options[i].name, "preallocation")) {
2211 fprintf(stderr, "Cannot change preallocation mode.\n");
2212 return -ENOTSUP;
2213 } else if (!strcmp(options[i].name, "size")) {
2214 new_size = options[i].value.n;
2215 } else if (!strcmp(options[i].name, "backing_file")) {
2216 backing_file = options[i].value.s;
2217 } else if (!strcmp(options[i].name, "backing_fmt")) {
2218 backing_format = options[i].value.s;
2219 } else if (!strcmp(options[i].name, "encryption")) {
2220 if ((options[i].value.n != !!s->crypt_method)) {
2221 fprintf(stderr, "Changing the encryption flag is not "
2222 "supported.\n");
2223 return -ENOTSUP;
2225 } else if (!strcmp(options[i].name, "cluster_size")) {
2226 if (options[i].value.n != s->cluster_size) {
2227 fprintf(stderr, "Changing the cluster size is not "
2228 "supported.\n");
2229 return -ENOTSUP;
2231 } else if (!strcmp(options[i].name, "lazy_refcounts")) {
2232 lazy_refcounts = options[i].value.n;
2233 } else {
2234 /* if this assertion fails, this probably means a new option was
2235 * added without having it covered here */
2236 assert(false);
2240 if (new_version != old_version) {
2241 if (new_version > old_version) {
2242 /* Upgrade */
2243 s->qcow_version = new_version;
2244 ret = qcow2_update_header(bs);
2245 if (ret < 0) {
2246 s->qcow_version = old_version;
2247 return ret;
2249 } else {
2250 ret = qcow2_downgrade(bs, new_version);
2251 if (ret < 0) {
2252 return ret;
2257 if (backing_file || backing_format) {
2258 ret = qcow2_change_backing_file(bs, backing_file ?: bs->backing_file,
2259 backing_format ?: bs->backing_format);
2260 if (ret < 0) {
2261 return ret;
2265 if (s->use_lazy_refcounts != lazy_refcounts) {
2266 if (lazy_refcounts) {
2267 if (s->qcow_version < 3) {
2268 fprintf(stderr, "Lazy refcounts only supported with compatibility "
2269 "level 1.1 and above (use compat=1.1 or greater)\n");
2270 return -EINVAL;
2272 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
2273 ret = qcow2_update_header(bs);
2274 if (ret < 0) {
2275 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
2276 return ret;
2278 s->use_lazy_refcounts = true;
2279 } else {
2280 /* make image clean first */
2281 ret = qcow2_mark_clean(bs);
2282 if (ret < 0) {
2283 return ret;
2285 /* now disallow lazy refcounts */
2286 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
2287 ret = qcow2_update_header(bs);
2288 if (ret < 0) {
2289 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
2290 return ret;
2292 s->use_lazy_refcounts = false;
2296 if (new_size) {
2297 ret = bdrv_truncate(bs, new_size);
2298 if (ret < 0) {
2299 return ret;
2303 return 0;
2306 static QEMUOptionParameter qcow2_create_options[] = {
2308 .name = BLOCK_OPT_SIZE,
2309 .type = OPT_SIZE,
2310 .help = "Virtual disk size"
2313 .name = BLOCK_OPT_COMPAT_LEVEL,
2314 .type = OPT_STRING,
2315 .help = "Compatibility level (0.10 or 1.1)"
2318 .name = BLOCK_OPT_BACKING_FILE,
2319 .type = OPT_STRING,
2320 .help = "File name of a base image"
2323 .name = BLOCK_OPT_BACKING_FMT,
2324 .type = OPT_STRING,
2325 .help = "Image format of the base image"
2328 .name = BLOCK_OPT_ENCRYPT,
2329 .type = OPT_FLAG,
2330 .help = "Encrypt the image"
2333 .name = BLOCK_OPT_CLUSTER_SIZE,
2334 .type = OPT_SIZE,
2335 .help = "qcow2 cluster size",
2336 .value = { .n = DEFAULT_CLUSTER_SIZE },
2339 .name = BLOCK_OPT_PREALLOC,
2340 .type = OPT_STRING,
2341 .help = "Preallocation mode (allowed values: off, metadata)"
2344 .name = BLOCK_OPT_LAZY_REFCOUNTS,
2345 .type = OPT_FLAG,
2346 .help = "Postpone refcount updates",
2348 { NULL }
2351 static BlockDriver bdrv_qcow2 = {
2352 .format_name = "qcow2",
2353 .instance_size = sizeof(BDRVQcowState),
2354 .bdrv_probe = qcow2_probe,
2355 .bdrv_open = qcow2_open,
2356 .bdrv_close = qcow2_close,
2357 .bdrv_reopen_prepare = qcow2_reopen_prepare,
2358 .bdrv_create = qcow2_create,
2359 .bdrv_has_zero_init = bdrv_has_zero_init_1,
2360 .bdrv_co_get_block_status = qcow2_co_get_block_status,
2361 .bdrv_set_key = qcow2_set_key,
2363 .bdrv_co_readv = qcow2_co_readv,
2364 .bdrv_co_writev = qcow2_co_writev,
2365 .bdrv_co_flush_to_os = qcow2_co_flush_to_os,
2367 .bdrv_co_write_zeroes = qcow2_co_write_zeroes,
2368 .bdrv_co_discard = qcow2_co_discard,
2369 .bdrv_truncate = qcow2_truncate,
2370 .bdrv_write_compressed = qcow2_write_compressed,
2372 .bdrv_snapshot_create = qcow2_snapshot_create,
2373 .bdrv_snapshot_goto = qcow2_snapshot_goto,
2374 .bdrv_snapshot_delete = qcow2_snapshot_delete,
2375 .bdrv_snapshot_list = qcow2_snapshot_list,
2376 .bdrv_snapshot_load_tmp = qcow2_snapshot_load_tmp,
2377 .bdrv_get_info = qcow2_get_info,
2378 .bdrv_get_specific_info = qcow2_get_specific_info,
2380 .bdrv_save_vmstate = qcow2_save_vmstate,
2381 .bdrv_load_vmstate = qcow2_load_vmstate,
2383 .bdrv_change_backing_file = qcow2_change_backing_file,
2385 .bdrv_refresh_limits = qcow2_refresh_limits,
2386 .bdrv_invalidate_cache = qcow2_invalidate_cache,
2388 .create_options = qcow2_create_options,
2389 .bdrv_check = qcow2_check,
2390 .bdrv_amend_options = qcow2_amend_options,
2393 static void bdrv_qcow2_init(void)
2395 bdrv_register(&bdrv_qcow2);
2398 block_init(bdrv_qcow2_init);