qcow2: Validate active L1 table offset and size (CVE-2014-0144)
[qemu/kevin.git] / block / qcow2.c
blob36395289a93afa75f8baca48f55c3a7fd976ed46
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 int len, i, ret = 0;
449 QCowHeader header;
450 QemuOpts *opts;
451 Error *local_err = NULL;
452 uint64_t ext_end;
453 uint64_t l1_vm_state_index;
454 const char *opt_overlap_check;
455 int overlap_check_template = 0;
457 ret = bdrv_pread(bs->file, 0, &header, sizeof(header));
458 if (ret < 0) {
459 error_setg_errno(errp, -ret, "Could not read qcow2 header");
460 goto fail;
462 be32_to_cpus(&header.magic);
463 be32_to_cpus(&header.version);
464 be64_to_cpus(&header.backing_file_offset);
465 be32_to_cpus(&header.backing_file_size);
466 be64_to_cpus(&header.size);
467 be32_to_cpus(&header.cluster_bits);
468 be32_to_cpus(&header.crypt_method);
469 be64_to_cpus(&header.l1_table_offset);
470 be32_to_cpus(&header.l1_size);
471 be64_to_cpus(&header.refcount_table_offset);
472 be32_to_cpus(&header.refcount_table_clusters);
473 be64_to_cpus(&header.snapshots_offset);
474 be32_to_cpus(&header.nb_snapshots);
476 if (header.magic != QCOW_MAGIC) {
477 error_setg(errp, "Image is not in qcow2 format");
478 ret = -EINVAL;
479 goto fail;
481 if (header.version < 2 || header.version > 3) {
482 report_unsupported(bs, errp, "QCOW version %d", header.version);
483 ret = -ENOTSUP;
484 goto fail;
487 s->qcow_version = header.version;
489 /* Initialise cluster size */
490 if (header.cluster_bits < MIN_CLUSTER_BITS ||
491 header.cluster_bits > MAX_CLUSTER_BITS) {
492 error_setg(errp, "Unsupported cluster size: 2^%i", header.cluster_bits);
493 ret = -EINVAL;
494 goto fail;
497 s->cluster_bits = header.cluster_bits;
498 s->cluster_size = 1 << s->cluster_bits;
499 s->cluster_sectors = 1 << (s->cluster_bits - 9);
501 /* Initialise version 3 header fields */
502 if (header.version == 2) {
503 header.incompatible_features = 0;
504 header.compatible_features = 0;
505 header.autoclear_features = 0;
506 header.refcount_order = 4;
507 header.header_length = 72;
508 } else {
509 be64_to_cpus(&header.incompatible_features);
510 be64_to_cpus(&header.compatible_features);
511 be64_to_cpus(&header.autoclear_features);
512 be32_to_cpus(&header.refcount_order);
513 be32_to_cpus(&header.header_length);
515 if (header.header_length < 104) {
516 error_setg(errp, "qcow2 header too short");
517 ret = -EINVAL;
518 goto fail;
522 if (header.header_length > s->cluster_size) {
523 error_setg(errp, "qcow2 header exceeds cluster size");
524 ret = -EINVAL;
525 goto fail;
528 if (header.header_length > sizeof(header)) {
529 s->unknown_header_fields_size = header.header_length - sizeof(header);
530 s->unknown_header_fields = g_malloc(s->unknown_header_fields_size);
531 ret = bdrv_pread(bs->file, sizeof(header), s->unknown_header_fields,
532 s->unknown_header_fields_size);
533 if (ret < 0) {
534 error_setg_errno(errp, -ret, "Could not read unknown qcow2 header "
535 "fields");
536 goto fail;
540 if (header.backing_file_offset > s->cluster_size) {
541 error_setg(errp, "Invalid backing file offset");
542 ret = -EINVAL;
543 goto fail;
546 if (header.backing_file_offset) {
547 ext_end = header.backing_file_offset;
548 } else {
549 ext_end = 1 << header.cluster_bits;
552 /* Handle feature bits */
553 s->incompatible_features = header.incompatible_features;
554 s->compatible_features = header.compatible_features;
555 s->autoclear_features = header.autoclear_features;
557 if (s->incompatible_features & ~QCOW2_INCOMPAT_MASK) {
558 void *feature_table = NULL;
559 qcow2_read_extensions(bs, header.header_length, ext_end,
560 &feature_table, NULL);
561 report_unsupported_feature(bs, errp, feature_table,
562 s->incompatible_features &
563 ~QCOW2_INCOMPAT_MASK);
564 ret = -ENOTSUP;
565 g_free(feature_table);
566 goto fail;
569 if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
570 /* Corrupt images may not be written to unless they are being repaired
572 if ((flags & BDRV_O_RDWR) && !(flags & BDRV_O_CHECK)) {
573 error_setg(errp, "qcow2: Image is corrupt; cannot be opened "
574 "read/write");
575 ret = -EACCES;
576 goto fail;
580 /* Check support for various header values */
581 if (header.refcount_order != 4) {
582 report_unsupported(bs, errp, "%d bit reference counts",
583 1 << header.refcount_order);
584 ret = -ENOTSUP;
585 goto fail;
587 s->refcount_order = header.refcount_order;
589 if (header.crypt_method > QCOW_CRYPT_AES) {
590 error_setg(errp, "Unsupported encryption method: %i",
591 header.crypt_method);
592 ret = -EINVAL;
593 goto fail;
595 s->crypt_method_header = header.crypt_method;
596 if (s->crypt_method_header) {
597 bs->encrypted = 1;
600 s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */
601 s->l2_size = 1 << s->l2_bits;
602 bs->total_sectors = header.size / 512;
603 s->csize_shift = (62 - (s->cluster_bits - 8));
604 s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;
605 s->cluster_offset_mask = (1LL << s->csize_shift) - 1;
607 s->refcount_table_offset = header.refcount_table_offset;
608 s->refcount_table_size =
609 header.refcount_table_clusters << (s->cluster_bits - 3);
611 if (header.refcount_table_clusters > (0x800000 >> s->cluster_bits)) {
612 /* 8 MB refcount table is enough for 2 PB images at 64k cluster size
613 * (128 GB for 512 byte clusters, 2 EB for 2 MB clusters) */
614 error_setg(errp, "Reference count table too large");
615 ret = -EINVAL;
616 goto fail;
619 ret = validate_table_offset(bs, s->refcount_table_offset,
620 s->refcount_table_size, sizeof(uint64_t));
621 if (ret < 0) {
622 error_setg(errp, "Invalid reference count table offset");
623 goto fail;
626 /* Snapshot table offset/length */
627 if (header.nb_snapshots > QCOW_MAX_SNAPSHOTS) {
628 error_setg(errp, "Too many snapshots");
629 ret = -EINVAL;
630 goto fail;
633 ret = validate_table_offset(bs, header.snapshots_offset,
634 header.nb_snapshots,
635 sizeof(QCowSnapshotHeader));
636 if (ret < 0) {
637 error_setg(errp, "Invalid snapshot table offset");
638 goto fail;
641 s->snapshots_offset = header.snapshots_offset;
642 s->nb_snapshots = header.nb_snapshots;
644 /* read the level 1 table */
645 if (header.l1_size > 0x2000000) {
646 /* 32 MB L1 table is enough for 2 PB images at 64k cluster size
647 * (128 GB for 512 byte clusters, 2 EB for 2 MB clusters) */
648 error_setg(errp, "Active L1 table too large");
649 ret = -EFBIG;
650 goto fail;
652 s->l1_size = header.l1_size;
654 l1_vm_state_index = size_to_l1(s, header.size);
655 if (l1_vm_state_index > INT_MAX) {
656 error_setg(errp, "Image is too big");
657 ret = -EFBIG;
658 goto fail;
660 s->l1_vm_state_index = l1_vm_state_index;
662 /* the L1 table must contain at least enough entries to put
663 header.size bytes */
664 if (s->l1_size < s->l1_vm_state_index) {
665 error_setg(errp, "L1 table is too small");
666 ret = -EINVAL;
667 goto fail;
670 ret = validate_table_offset(bs, header.l1_table_offset,
671 header.l1_size, sizeof(uint64_t));
672 if (ret < 0) {
673 error_setg(errp, "Invalid L1 table offset");
674 goto fail;
676 s->l1_table_offset = header.l1_table_offset;
679 if (s->l1_size > 0) {
680 s->l1_table = g_malloc0(
681 align_offset(s->l1_size * sizeof(uint64_t), 512));
682 ret = bdrv_pread(bs->file, s->l1_table_offset, s->l1_table,
683 s->l1_size * sizeof(uint64_t));
684 if (ret < 0) {
685 error_setg_errno(errp, -ret, "Could not read L1 table");
686 goto fail;
688 for(i = 0;i < s->l1_size; i++) {
689 be64_to_cpus(&s->l1_table[i]);
693 /* alloc L2 table/refcount block cache */
694 s->l2_table_cache = qcow2_cache_create(bs, L2_CACHE_SIZE);
695 s->refcount_block_cache = qcow2_cache_create(bs, REFCOUNT_CACHE_SIZE);
697 s->cluster_cache = g_malloc(s->cluster_size);
698 /* one more sector for decompressed data alignment */
699 s->cluster_data = qemu_blockalign(bs, QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size
700 + 512);
701 s->cluster_cache_offset = -1;
702 s->flags = flags;
704 ret = qcow2_refcount_init(bs);
705 if (ret != 0) {
706 error_setg_errno(errp, -ret, "Could not initialize refcount handling");
707 goto fail;
710 QLIST_INIT(&s->cluster_allocs);
711 QTAILQ_INIT(&s->discards);
713 /* read qcow2 extensions */
714 if (qcow2_read_extensions(bs, header.header_length, ext_end, NULL,
715 &local_err)) {
716 error_propagate(errp, local_err);
717 ret = -EINVAL;
718 goto fail;
721 /* read the backing file name */
722 if (header.backing_file_offset != 0) {
723 len = header.backing_file_size;
724 if (len > 1023) {
725 len = 1023;
727 ret = bdrv_pread(bs->file, header.backing_file_offset,
728 bs->backing_file, len);
729 if (ret < 0) {
730 error_setg_errno(errp, -ret, "Could not read backing file name");
731 goto fail;
733 bs->backing_file[len] = '\0';
736 ret = qcow2_read_snapshots(bs);
737 if (ret < 0) {
738 error_setg_errno(errp, -ret, "Could not read snapshots");
739 goto fail;
742 /* Clear unknown autoclear feature bits */
743 if (!bs->read_only && !(flags & BDRV_O_INCOMING) && s->autoclear_features) {
744 s->autoclear_features = 0;
745 ret = qcow2_update_header(bs);
746 if (ret < 0) {
747 error_setg_errno(errp, -ret, "Could not update qcow2 header");
748 goto fail;
752 /* Initialise locks */
753 qemu_co_mutex_init(&s->lock);
755 /* Repair image if dirty */
756 if (!(flags & (BDRV_O_CHECK | BDRV_O_INCOMING)) && !bs->read_only &&
757 (s->incompatible_features & QCOW2_INCOMPAT_DIRTY)) {
758 BdrvCheckResult result = {0};
760 ret = qcow2_check(bs, &result, BDRV_FIX_ERRORS);
761 if (ret < 0) {
762 error_setg_errno(errp, -ret, "Could not repair dirty image");
763 goto fail;
767 /* Enable lazy_refcounts according to image and command line options */
768 opts = qemu_opts_create(&qcow2_runtime_opts, NULL, 0, &error_abort);
769 qemu_opts_absorb_qdict(opts, options, &local_err);
770 if (local_err) {
771 error_propagate(errp, local_err);
772 ret = -EINVAL;
773 goto fail;
776 s->use_lazy_refcounts = qemu_opt_get_bool(opts, QCOW2_OPT_LAZY_REFCOUNTS,
777 (s->compatible_features & QCOW2_COMPAT_LAZY_REFCOUNTS));
779 s->discard_passthrough[QCOW2_DISCARD_NEVER] = false;
780 s->discard_passthrough[QCOW2_DISCARD_ALWAYS] = true;
781 s->discard_passthrough[QCOW2_DISCARD_REQUEST] =
782 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_REQUEST,
783 flags & BDRV_O_UNMAP);
784 s->discard_passthrough[QCOW2_DISCARD_SNAPSHOT] =
785 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_SNAPSHOT, true);
786 s->discard_passthrough[QCOW2_DISCARD_OTHER] =
787 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_OTHER, false);
789 opt_overlap_check = qemu_opt_get(opts, "overlap-check") ?: "cached";
790 if (!strcmp(opt_overlap_check, "none")) {
791 overlap_check_template = 0;
792 } else if (!strcmp(opt_overlap_check, "constant")) {
793 overlap_check_template = QCOW2_OL_CONSTANT;
794 } else if (!strcmp(opt_overlap_check, "cached")) {
795 overlap_check_template = QCOW2_OL_CACHED;
796 } else if (!strcmp(opt_overlap_check, "all")) {
797 overlap_check_template = QCOW2_OL_ALL;
798 } else {
799 error_setg(errp, "Unsupported value '%s' for qcow2 option "
800 "'overlap-check'. Allowed are either of the following: "
801 "none, constant, cached, all", opt_overlap_check);
802 qemu_opts_del(opts);
803 ret = -EINVAL;
804 goto fail;
807 s->overlap_check = 0;
808 for (i = 0; i < QCOW2_OL_MAX_BITNR; i++) {
809 /* overlap-check defines a template bitmask, but every flag may be
810 * overwritten through the associated boolean option */
811 s->overlap_check |=
812 qemu_opt_get_bool(opts, overlap_bool_option_names[i],
813 overlap_check_template & (1 << i)) << i;
816 qemu_opts_del(opts);
818 if (s->use_lazy_refcounts && s->qcow_version < 3) {
819 error_setg(errp, "Lazy refcounts require a qcow2 image with at least "
820 "qemu 1.1 compatibility level");
821 ret = -EINVAL;
822 goto fail;
825 #ifdef DEBUG_ALLOC
827 BdrvCheckResult result = {0};
828 qcow2_check_refcounts(bs, &result, 0);
830 #endif
831 return ret;
833 fail:
834 g_free(s->unknown_header_fields);
835 cleanup_unknown_header_ext(bs);
836 qcow2_free_snapshots(bs);
837 qcow2_refcount_close(bs);
838 g_free(s->l1_table);
839 /* else pre-write overlap checks in cache_destroy may crash */
840 s->l1_table = NULL;
841 if (s->l2_table_cache) {
842 qcow2_cache_destroy(bs, s->l2_table_cache);
844 if (s->refcount_block_cache) {
845 qcow2_cache_destroy(bs, s->refcount_block_cache);
847 g_free(s->cluster_cache);
848 qemu_vfree(s->cluster_data);
849 return ret;
852 static int qcow2_refresh_limits(BlockDriverState *bs)
854 BDRVQcowState *s = bs->opaque;
856 bs->bl.write_zeroes_alignment = s->cluster_sectors;
858 return 0;
861 static int qcow2_set_key(BlockDriverState *bs, const char *key)
863 BDRVQcowState *s = bs->opaque;
864 uint8_t keybuf[16];
865 int len, i;
867 memset(keybuf, 0, 16);
868 len = strlen(key);
869 if (len > 16)
870 len = 16;
871 /* XXX: we could compress the chars to 7 bits to increase
872 entropy */
873 for(i = 0;i < len;i++) {
874 keybuf[i] = key[i];
876 s->crypt_method = s->crypt_method_header;
878 if (AES_set_encrypt_key(keybuf, 128, &s->aes_encrypt_key) != 0)
879 return -1;
880 if (AES_set_decrypt_key(keybuf, 128, &s->aes_decrypt_key) != 0)
881 return -1;
882 #if 0
883 /* test */
885 uint8_t in[16];
886 uint8_t out[16];
887 uint8_t tmp[16];
888 for(i=0;i<16;i++)
889 in[i] = i;
890 AES_encrypt(in, tmp, &s->aes_encrypt_key);
891 AES_decrypt(tmp, out, &s->aes_decrypt_key);
892 for(i = 0; i < 16; i++)
893 printf(" %02x", tmp[i]);
894 printf("\n");
895 for(i = 0; i < 16; i++)
896 printf(" %02x", out[i]);
897 printf("\n");
899 #endif
900 return 0;
903 /* We have nothing to do for QCOW2 reopen, stubs just return
904 * success */
905 static int qcow2_reopen_prepare(BDRVReopenState *state,
906 BlockReopenQueue *queue, Error **errp)
908 return 0;
911 static int64_t coroutine_fn qcow2_co_get_block_status(BlockDriverState *bs,
912 int64_t sector_num, int nb_sectors, int *pnum)
914 BDRVQcowState *s = bs->opaque;
915 uint64_t cluster_offset;
916 int index_in_cluster, ret;
917 int64_t status = 0;
919 *pnum = nb_sectors;
920 qemu_co_mutex_lock(&s->lock);
921 ret = qcow2_get_cluster_offset(bs, sector_num << 9, pnum, &cluster_offset);
922 qemu_co_mutex_unlock(&s->lock);
923 if (ret < 0) {
924 return ret;
927 if (cluster_offset != 0 && ret != QCOW2_CLUSTER_COMPRESSED &&
928 !s->crypt_method) {
929 index_in_cluster = sector_num & (s->cluster_sectors - 1);
930 cluster_offset |= (index_in_cluster << BDRV_SECTOR_BITS);
931 status |= BDRV_BLOCK_OFFSET_VALID | cluster_offset;
933 if (ret == QCOW2_CLUSTER_ZERO) {
934 status |= BDRV_BLOCK_ZERO;
935 } else if (ret != QCOW2_CLUSTER_UNALLOCATED) {
936 status |= BDRV_BLOCK_DATA;
938 return status;
941 /* handle reading after the end of the backing file */
942 int qcow2_backing_read1(BlockDriverState *bs, QEMUIOVector *qiov,
943 int64_t sector_num, int nb_sectors)
945 int n1;
946 if ((sector_num + nb_sectors) <= bs->total_sectors)
947 return nb_sectors;
948 if (sector_num >= bs->total_sectors)
949 n1 = 0;
950 else
951 n1 = bs->total_sectors - sector_num;
953 qemu_iovec_memset(qiov, 512 * n1, 0, 512 * (nb_sectors - n1));
955 return n1;
958 static coroutine_fn int qcow2_co_readv(BlockDriverState *bs, int64_t sector_num,
959 int remaining_sectors, QEMUIOVector *qiov)
961 BDRVQcowState *s = bs->opaque;
962 int index_in_cluster, n1;
963 int ret;
964 int cur_nr_sectors; /* number of sectors in current iteration */
965 uint64_t cluster_offset = 0;
966 uint64_t bytes_done = 0;
967 QEMUIOVector hd_qiov;
968 uint8_t *cluster_data = NULL;
970 qemu_iovec_init(&hd_qiov, qiov->niov);
972 qemu_co_mutex_lock(&s->lock);
974 while (remaining_sectors != 0) {
976 /* prepare next request */
977 cur_nr_sectors = remaining_sectors;
978 if (s->crypt_method) {
979 cur_nr_sectors = MIN(cur_nr_sectors,
980 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors);
983 ret = qcow2_get_cluster_offset(bs, sector_num << 9,
984 &cur_nr_sectors, &cluster_offset);
985 if (ret < 0) {
986 goto fail;
989 index_in_cluster = sector_num & (s->cluster_sectors - 1);
991 qemu_iovec_reset(&hd_qiov);
992 qemu_iovec_concat(&hd_qiov, qiov, bytes_done,
993 cur_nr_sectors * 512);
995 switch (ret) {
996 case QCOW2_CLUSTER_UNALLOCATED:
998 if (bs->backing_hd) {
999 /* read from the base image */
1000 n1 = qcow2_backing_read1(bs->backing_hd, &hd_qiov,
1001 sector_num, cur_nr_sectors);
1002 if (n1 > 0) {
1003 BLKDBG_EVENT(bs->file, BLKDBG_READ_BACKING_AIO);
1004 qemu_co_mutex_unlock(&s->lock);
1005 ret = bdrv_co_readv(bs->backing_hd, sector_num,
1006 n1, &hd_qiov);
1007 qemu_co_mutex_lock(&s->lock);
1008 if (ret < 0) {
1009 goto fail;
1012 } else {
1013 /* Note: in this case, no need to wait */
1014 qemu_iovec_memset(&hd_qiov, 0, 0, 512 * cur_nr_sectors);
1016 break;
1018 case QCOW2_CLUSTER_ZERO:
1019 qemu_iovec_memset(&hd_qiov, 0, 0, 512 * cur_nr_sectors);
1020 break;
1022 case QCOW2_CLUSTER_COMPRESSED:
1023 /* add AIO support for compressed blocks ? */
1024 ret = qcow2_decompress_cluster(bs, cluster_offset);
1025 if (ret < 0) {
1026 goto fail;
1029 qemu_iovec_from_buf(&hd_qiov, 0,
1030 s->cluster_cache + index_in_cluster * 512,
1031 512 * cur_nr_sectors);
1032 break;
1034 case QCOW2_CLUSTER_NORMAL:
1035 if ((cluster_offset & 511) != 0) {
1036 ret = -EIO;
1037 goto fail;
1040 if (s->crypt_method) {
1042 * For encrypted images, read everything into a temporary
1043 * contiguous buffer on which the AES functions can work.
1045 if (!cluster_data) {
1046 cluster_data =
1047 qemu_blockalign(bs, QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
1050 assert(cur_nr_sectors <=
1051 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors);
1052 qemu_iovec_reset(&hd_qiov);
1053 qemu_iovec_add(&hd_qiov, cluster_data,
1054 512 * cur_nr_sectors);
1057 BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);
1058 qemu_co_mutex_unlock(&s->lock);
1059 ret = bdrv_co_readv(bs->file,
1060 (cluster_offset >> 9) + index_in_cluster,
1061 cur_nr_sectors, &hd_qiov);
1062 qemu_co_mutex_lock(&s->lock);
1063 if (ret < 0) {
1064 goto fail;
1066 if (s->crypt_method) {
1067 qcow2_encrypt_sectors(s, sector_num, cluster_data,
1068 cluster_data, cur_nr_sectors, 0, &s->aes_decrypt_key);
1069 qemu_iovec_from_buf(qiov, bytes_done,
1070 cluster_data, 512 * cur_nr_sectors);
1072 break;
1074 default:
1075 g_assert_not_reached();
1076 ret = -EIO;
1077 goto fail;
1080 remaining_sectors -= cur_nr_sectors;
1081 sector_num += cur_nr_sectors;
1082 bytes_done += cur_nr_sectors * 512;
1084 ret = 0;
1086 fail:
1087 qemu_co_mutex_unlock(&s->lock);
1089 qemu_iovec_destroy(&hd_qiov);
1090 qemu_vfree(cluster_data);
1092 return ret;
1095 static coroutine_fn int qcow2_co_writev(BlockDriverState *bs,
1096 int64_t sector_num,
1097 int remaining_sectors,
1098 QEMUIOVector *qiov)
1100 BDRVQcowState *s = bs->opaque;
1101 int index_in_cluster;
1102 int ret;
1103 int cur_nr_sectors; /* number of sectors in current iteration */
1104 uint64_t cluster_offset;
1105 QEMUIOVector hd_qiov;
1106 uint64_t bytes_done = 0;
1107 uint8_t *cluster_data = NULL;
1108 QCowL2Meta *l2meta = NULL;
1110 trace_qcow2_writev_start_req(qemu_coroutine_self(), sector_num,
1111 remaining_sectors);
1113 qemu_iovec_init(&hd_qiov, qiov->niov);
1115 s->cluster_cache_offset = -1; /* disable compressed cache */
1117 qemu_co_mutex_lock(&s->lock);
1119 while (remaining_sectors != 0) {
1121 l2meta = NULL;
1123 trace_qcow2_writev_start_part(qemu_coroutine_self());
1124 index_in_cluster = sector_num & (s->cluster_sectors - 1);
1125 cur_nr_sectors = remaining_sectors;
1126 if (s->crypt_method &&
1127 cur_nr_sectors >
1128 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors - index_in_cluster) {
1129 cur_nr_sectors =
1130 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors - index_in_cluster;
1133 ret = qcow2_alloc_cluster_offset(bs, sector_num << 9,
1134 &cur_nr_sectors, &cluster_offset, &l2meta);
1135 if (ret < 0) {
1136 goto fail;
1139 assert((cluster_offset & 511) == 0);
1141 qemu_iovec_reset(&hd_qiov);
1142 qemu_iovec_concat(&hd_qiov, qiov, bytes_done,
1143 cur_nr_sectors * 512);
1145 if (s->crypt_method) {
1146 if (!cluster_data) {
1147 cluster_data = qemu_blockalign(bs, QCOW_MAX_CRYPT_CLUSTERS *
1148 s->cluster_size);
1151 assert(hd_qiov.size <=
1152 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
1153 qemu_iovec_to_buf(&hd_qiov, 0, cluster_data, hd_qiov.size);
1155 qcow2_encrypt_sectors(s, sector_num, cluster_data,
1156 cluster_data, cur_nr_sectors, 1, &s->aes_encrypt_key);
1158 qemu_iovec_reset(&hd_qiov);
1159 qemu_iovec_add(&hd_qiov, cluster_data,
1160 cur_nr_sectors * 512);
1163 ret = qcow2_pre_write_overlap_check(bs, 0,
1164 cluster_offset + index_in_cluster * BDRV_SECTOR_SIZE,
1165 cur_nr_sectors * BDRV_SECTOR_SIZE);
1166 if (ret < 0) {
1167 goto fail;
1170 qemu_co_mutex_unlock(&s->lock);
1171 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO);
1172 trace_qcow2_writev_data(qemu_coroutine_self(),
1173 (cluster_offset >> 9) + index_in_cluster);
1174 ret = bdrv_co_writev(bs->file,
1175 (cluster_offset >> 9) + index_in_cluster,
1176 cur_nr_sectors, &hd_qiov);
1177 qemu_co_mutex_lock(&s->lock);
1178 if (ret < 0) {
1179 goto fail;
1182 while (l2meta != NULL) {
1183 QCowL2Meta *next;
1185 ret = qcow2_alloc_cluster_link_l2(bs, l2meta);
1186 if (ret < 0) {
1187 goto fail;
1190 /* Take the request off the list of running requests */
1191 if (l2meta->nb_clusters != 0) {
1192 QLIST_REMOVE(l2meta, next_in_flight);
1195 qemu_co_queue_restart_all(&l2meta->dependent_requests);
1197 next = l2meta->next;
1198 g_free(l2meta);
1199 l2meta = next;
1202 remaining_sectors -= cur_nr_sectors;
1203 sector_num += cur_nr_sectors;
1204 bytes_done += cur_nr_sectors * 512;
1205 trace_qcow2_writev_done_part(qemu_coroutine_self(), cur_nr_sectors);
1207 ret = 0;
1209 fail:
1210 qemu_co_mutex_unlock(&s->lock);
1212 while (l2meta != NULL) {
1213 QCowL2Meta *next;
1215 if (l2meta->nb_clusters != 0) {
1216 QLIST_REMOVE(l2meta, next_in_flight);
1218 qemu_co_queue_restart_all(&l2meta->dependent_requests);
1220 next = l2meta->next;
1221 g_free(l2meta);
1222 l2meta = next;
1225 qemu_iovec_destroy(&hd_qiov);
1226 qemu_vfree(cluster_data);
1227 trace_qcow2_writev_done_req(qemu_coroutine_self(), ret);
1229 return ret;
1232 static void qcow2_close(BlockDriverState *bs)
1234 BDRVQcowState *s = bs->opaque;
1235 g_free(s->l1_table);
1236 /* else pre-write overlap checks in cache_destroy may crash */
1237 s->l1_table = NULL;
1239 if (!(bs->open_flags & BDRV_O_INCOMING)) {
1240 qcow2_cache_flush(bs, s->l2_table_cache);
1241 qcow2_cache_flush(bs, s->refcount_block_cache);
1243 qcow2_mark_clean(bs);
1246 qcow2_cache_destroy(bs, s->l2_table_cache);
1247 qcow2_cache_destroy(bs, s->refcount_block_cache);
1249 g_free(s->unknown_header_fields);
1250 cleanup_unknown_header_ext(bs);
1252 g_free(s->cluster_cache);
1253 qemu_vfree(s->cluster_data);
1254 qcow2_refcount_close(bs);
1255 qcow2_free_snapshots(bs);
1258 static void qcow2_invalidate_cache(BlockDriverState *bs, Error **errp)
1260 BDRVQcowState *s = bs->opaque;
1261 int flags = s->flags;
1262 AES_KEY aes_encrypt_key;
1263 AES_KEY aes_decrypt_key;
1264 uint32_t crypt_method = 0;
1265 QDict *options;
1266 Error *local_err = NULL;
1267 int ret;
1270 * Backing files are read-only which makes all of their metadata immutable,
1271 * that means we don't have to worry about reopening them here.
1274 if (s->crypt_method) {
1275 crypt_method = s->crypt_method;
1276 memcpy(&aes_encrypt_key, &s->aes_encrypt_key, sizeof(aes_encrypt_key));
1277 memcpy(&aes_decrypt_key, &s->aes_decrypt_key, sizeof(aes_decrypt_key));
1280 qcow2_close(bs);
1282 bdrv_invalidate_cache(bs->file, &local_err);
1283 if (local_err) {
1284 error_propagate(errp, local_err);
1285 return;
1288 memset(s, 0, sizeof(BDRVQcowState));
1289 options = qdict_clone_shallow(bs->options);
1291 ret = qcow2_open(bs, options, flags, &local_err);
1292 if (local_err) {
1293 error_setg(errp, "Could not reopen qcow2 layer: %s",
1294 error_get_pretty(local_err));
1295 error_free(local_err);
1296 return;
1297 } else if (ret < 0) {
1298 error_setg_errno(errp, -ret, "Could not reopen qcow2 layer");
1299 return;
1302 QDECREF(options);
1304 if (crypt_method) {
1305 s->crypt_method = crypt_method;
1306 memcpy(&s->aes_encrypt_key, &aes_encrypt_key, sizeof(aes_encrypt_key));
1307 memcpy(&s->aes_decrypt_key, &aes_decrypt_key, sizeof(aes_decrypt_key));
1311 static size_t header_ext_add(char *buf, uint32_t magic, const void *s,
1312 size_t len, size_t buflen)
1314 QCowExtension *ext_backing_fmt = (QCowExtension*) buf;
1315 size_t ext_len = sizeof(QCowExtension) + ((len + 7) & ~7);
1317 if (buflen < ext_len) {
1318 return -ENOSPC;
1321 *ext_backing_fmt = (QCowExtension) {
1322 .magic = cpu_to_be32(magic),
1323 .len = cpu_to_be32(len),
1325 memcpy(buf + sizeof(QCowExtension), s, len);
1327 return ext_len;
1331 * Updates the qcow2 header, including the variable length parts of it, i.e.
1332 * the backing file name and all extensions. qcow2 was not designed to allow
1333 * such changes, so if we run out of space (we can only use the first cluster)
1334 * this function may fail.
1336 * Returns 0 on success, -errno in error cases.
1338 int qcow2_update_header(BlockDriverState *bs)
1340 BDRVQcowState *s = bs->opaque;
1341 QCowHeader *header;
1342 char *buf;
1343 size_t buflen = s->cluster_size;
1344 int ret;
1345 uint64_t total_size;
1346 uint32_t refcount_table_clusters;
1347 size_t header_length;
1348 Qcow2UnknownHeaderExtension *uext;
1350 buf = qemu_blockalign(bs, buflen);
1352 /* Header structure */
1353 header = (QCowHeader*) buf;
1355 if (buflen < sizeof(*header)) {
1356 ret = -ENOSPC;
1357 goto fail;
1360 header_length = sizeof(*header) + s->unknown_header_fields_size;
1361 total_size = bs->total_sectors * BDRV_SECTOR_SIZE;
1362 refcount_table_clusters = s->refcount_table_size >> (s->cluster_bits - 3);
1364 *header = (QCowHeader) {
1365 /* Version 2 fields */
1366 .magic = cpu_to_be32(QCOW_MAGIC),
1367 .version = cpu_to_be32(s->qcow_version),
1368 .backing_file_offset = 0,
1369 .backing_file_size = 0,
1370 .cluster_bits = cpu_to_be32(s->cluster_bits),
1371 .size = cpu_to_be64(total_size),
1372 .crypt_method = cpu_to_be32(s->crypt_method_header),
1373 .l1_size = cpu_to_be32(s->l1_size),
1374 .l1_table_offset = cpu_to_be64(s->l1_table_offset),
1375 .refcount_table_offset = cpu_to_be64(s->refcount_table_offset),
1376 .refcount_table_clusters = cpu_to_be32(refcount_table_clusters),
1377 .nb_snapshots = cpu_to_be32(s->nb_snapshots),
1378 .snapshots_offset = cpu_to_be64(s->snapshots_offset),
1380 /* Version 3 fields */
1381 .incompatible_features = cpu_to_be64(s->incompatible_features),
1382 .compatible_features = cpu_to_be64(s->compatible_features),
1383 .autoclear_features = cpu_to_be64(s->autoclear_features),
1384 .refcount_order = cpu_to_be32(s->refcount_order),
1385 .header_length = cpu_to_be32(header_length),
1388 /* For older versions, write a shorter header */
1389 switch (s->qcow_version) {
1390 case 2:
1391 ret = offsetof(QCowHeader, incompatible_features);
1392 break;
1393 case 3:
1394 ret = sizeof(*header);
1395 break;
1396 default:
1397 ret = -EINVAL;
1398 goto fail;
1401 buf += ret;
1402 buflen -= ret;
1403 memset(buf, 0, buflen);
1405 /* Preserve any unknown field in the header */
1406 if (s->unknown_header_fields_size) {
1407 if (buflen < s->unknown_header_fields_size) {
1408 ret = -ENOSPC;
1409 goto fail;
1412 memcpy(buf, s->unknown_header_fields, s->unknown_header_fields_size);
1413 buf += s->unknown_header_fields_size;
1414 buflen -= s->unknown_header_fields_size;
1417 /* Backing file format header extension */
1418 if (*bs->backing_format) {
1419 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BACKING_FORMAT,
1420 bs->backing_format, strlen(bs->backing_format),
1421 buflen);
1422 if (ret < 0) {
1423 goto fail;
1426 buf += ret;
1427 buflen -= ret;
1430 /* Feature table */
1431 Qcow2Feature features[] = {
1433 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
1434 .bit = QCOW2_INCOMPAT_DIRTY_BITNR,
1435 .name = "dirty bit",
1438 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
1439 .bit = QCOW2_INCOMPAT_CORRUPT_BITNR,
1440 .name = "corrupt bit",
1443 .type = QCOW2_FEAT_TYPE_COMPATIBLE,
1444 .bit = QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR,
1445 .name = "lazy refcounts",
1449 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_FEATURE_TABLE,
1450 features, sizeof(features), buflen);
1451 if (ret < 0) {
1452 goto fail;
1454 buf += ret;
1455 buflen -= ret;
1457 /* Keep unknown header extensions */
1458 QLIST_FOREACH(uext, &s->unknown_header_ext, next) {
1459 ret = header_ext_add(buf, uext->magic, uext->data, uext->len, buflen);
1460 if (ret < 0) {
1461 goto fail;
1464 buf += ret;
1465 buflen -= ret;
1468 /* End of header extensions */
1469 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_END, NULL, 0, buflen);
1470 if (ret < 0) {
1471 goto fail;
1474 buf += ret;
1475 buflen -= ret;
1477 /* Backing file name */
1478 if (*bs->backing_file) {
1479 size_t backing_file_len = strlen(bs->backing_file);
1481 if (buflen < backing_file_len) {
1482 ret = -ENOSPC;
1483 goto fail;
1486 /* Using strncpy is ok here, since buf is not NUL-terminated. */
1487 strncpy(buf, bs->backing_file, buflen);
1489 header->backing_file_offset = cpu_to_be64(buf - ((char*) header));
1490 header->backing_file_size = cpu_to_be32(backing_file_len);
1493 /* Write the new header */
1494 ret = bdrv_pwrite(bs->file, 0, header, s->cluster_size);
1495 if (ret < 0) {
1496 goto fail;
1499 ret = 0;
1500 fail:
1501 qemu_vfree(header);
1502 return ret;
1505 static int qcow2_change_backing_file(BlockDriverState *bs,
1506 const char *backing_file, const char *backing_fmt)
1508 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
1509 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
1511 return qcow2_update_header(bs);
1514 static int preallocate(BlockDriverState *bs)
1516 uint64_t nb_sectors;
1517 uint64_t offset;
1518 uint64_t host_offset = 0;
1519 int num;
1520 int ret;
1521 QCowL2Meta *meta;
1523 nb_sectors = bdrv_getlength(bs) >> BDRV_SECTOR_BITS;
1524 offset = 0;
1526 while (nb_sectors) {
1527 num = MIN(nb_sectors, INT_MAX >> BDRV_SECTOR_BITS);
1528 ret = qcow2_alloc_cluster_offset(bs, offset, &num,
1529 &host_offset, &meta);
1530 if (ret < 0) {
1531 return ret;
1534 if (meta != NULL) {
1535 ret = qcow2_alloc_cluster_link_l2(bs, meta);
1536 if (ret < 0) {
1537 qcow2_free_any_clusters(bs, meta->alloc_offset,
1538 meta->nb_clusters, QCOW2_DISCARD_NEVER);
1539 return ret;
1542 /* There are no dependent requests, but we need to remove our
1543 * request from the list of in-flight requests */
1544 QLIST_REMOVE(meta, next_in_flight);
1547 /* TODO Preallocate data if requested */
1549 nb_sectors -= num;
1550 offset += num << BDRV_SECTOR_BITS;
1554 * It is expected that the image file is large enough to actually contain
1555 * all of the allocated clusters (otherwise we get failing reads after
1556 * EOF). Extend the image to the last allocated sector.
1558 if (host_offset != 0) {
1559 uint8_t buf[BDRV_SECTOR_SIZE];
1560 memset(buf, 0, BDRV_SECTOR_SIZE);
1561 ret = bdrv_write(bs->file, (host_offset >> BDRV_SECTOR_BITS) + num - 1,
1562 buf, 1);
1563 if (ret < 0) {
1564 return ret;
1568 return 0;
1571 static int qcow2_create2(const char *filename, int64_t total_size,
1572 const char *backing_file, const char *backing_format,
1573 int flags, size_t cluster_size, int prealloc,
1574 QEMUOptionParameter *options, int version,
1575 Error **errp)
1577 /* Calculate cluster_bits */
1578 int cluster_bits;
1579 cluster_bits = ffs(cluster_size) - 1;
1580 if (cluster_bits < MIN_CLUSTER_BITS || cluster_bits > MAX_CLUSTER_BITS ||
1581 (1 << cluster_bits) != cluster_size)
1583 error_setg(errp, "Cluster size must be a power of two between %d and "
1584 "%dk", 1 << MIN_CLUSTER_BITS, 1 << (MAX_CLUSTER_BITS - 10));
1585 return -EINVAL;
1589 * Open the image file and write a minimal qcow2 header.
1591 * We keep things simple and start with a zero-sized image. We also
1592 * do without refcount blocks or a L1 table for now. We'll fix the
1593 * inconsistency later.
1595 * We do need a refcount table because growing the refcount table means
1596 * allocating two new refcount blocks - the seconds of which would be at
1597 * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
1598 * size for any qcow2 image.
1600 BlockDriverState* bs;
1601 QCowHeader *header;
1602 uint8_t* refcount_table;
1603 Error *local_err = NULL;
1604 int ret;
1606 ret = bdrv_create_file(filename, options, &local_err);
1607 if (ret < 0) {
1608 error_propagate(errp, local_err);
1609 return ret;
1612 bs = NULL;
1613 ret = bdrv_open(&bs, filename, NULL, NULL, BDRV_O_RDWR | BDRV_O_PROTOCOL,
1614 NULL, &local_err);
1615 if (ret < 0) {
1616 error_propagate(errp, local_err);
1617 return ret;
1620 /* Write the header */
1621 QEMU_BUILD_BUG_ON((1 << MIN_CLUSTER_BITS) < sizeof(*header));
1622 header = g_malloc0(cluster_size);
1623 *header = (QCowHeader) {
1624 .magic = cpu_to_be32(QCOW_MAGIC),
1625 .version = cpu_to_be32(version),
1626 .cluster_bits = cpu_to_be32(cluster_bits),
1627 .size = cpu_to_be64(0),
1628 .l1_table_offset = cpu_to_be64(0),
1629 .l1_size = cpu_to_be32(0),
1630 .refcount_table_offset = cpu_to_be64(cluster_size),
1631 .refcount_table_clusters = cpu_to_be32(1),
1632 .refcount_order = cpu_to_be32(3 + REFCOUNT_SHIFT),
1633 .header_length = cpu_to_be32(sizeof(*header)),
1636 if (flags & BLOCK_FLAG_ENCRYPT) {
1637 header->crypt_method = cpu_to_be32(QCOW_CRYPT_AES);
1638 } else {
1639 header->crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
1642 if (flags & BLOCK_FLAG_LAZY_REFCOUNTS) {
1643 header->compatible_features |=
1644 cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS);
1647 ret = bdrv_pwrite(bs, 0, header, cluster_size);
1648 g_free(header);
1649 if (ret < 0) {
1650 error_setg_errno(errp, -ret, "Could not write qcow2 header");
1651 goto out;
1654 /* Write an empty refcount table */
1655 refcount_table = g_malloc0(cluster_size);
1656 ret = bdrv_pwrite(bs, cluster_size, refcount_table, cluster_size);
1657 g_free(refcount_table);
1659 if (ret < 0) {
1660 error_setg_errno(errp, -ret, "Could not write refcount table");
1661 goto out;
1664 bdrv_unref(bs);
1665 bs = NULL;
1668 * And now open the image and make it consistent first (i.e. increase the
1669 * refcount of the cluster that is occupied by the header and the refcount
1670 * table)
1672 BlockDriver* drv = bdrv_find_format("qcow2");
1673 assert(drv != NULL);
1674 ret = bdrv_open(&bs, filename, NULL, NULL,
1675 BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_NO_FLUSH, drv, &local_err);
1676 if (ret < 0) {
1677 error_propagate(errp, local_err);
1678 goto out;
1681 ret = qcow2_alloc_clusters(bs, 2 * cluster_size);
1682 if (ret < 0) {
1683 error_setg_errno(errp, -ret, "Could not allocate clusters for qcow2 "
1684 "header and refcount table");
1685 goto out;
1687 } else if (ret != 0) {
1688 error_report("Huh, first cluster in empty image is already in use?");
1689 abort();
1692 /* Okay, now that we have a valid image, let's give it the right size */
1693 ret = bdrv_truncate(bs, total_size * BDRV_SECTOR_SIZE);
1694 if (ret < 0) {
1695 error_setg_errno(errp, -ret, "Could not resize image");
1696 goto out;
1699 /* Want a backing file? There you go.*/
1700 if (backing_file) {
1701 ret = bdrv_change_backing_file(bs, backing_file, backing_format);
1702 if (ret < 0) {
1703 error_setg_errno(errp, -ret, "Could not assign backing file '%s' "
1704 "with format '%s'", backing_file, backing_format);
1705 goto out;
1709 /* And if we're supposed to preallocate metadata, do that now */
1710 if (prealloc) {
1711 BDRVQcowState *s = bs->opaque;
1712 qemu_co_mutex_lock(&s->lock);
1713 ret = preallocate(bs);
1714 qemu_co_mutex_unlock(&s->lock);
1715 if (ret < 0) {
1716 error_setg_errno(errp, -ret, "Could not preallocate metadata");
1717 goto out;
1721 bdrv_unref(bs);
1722 bs = NULL;
1724 /* Reopen the image without BDRV_O_NO_FLUSH to flush it before returning */
1725 ret = bdrv_open(&bs, filename, NULL, NULL,
1726 BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_NO_BACKING,
1727 drv, &local_err);
1728 if (local_err) {
1729 error_propagate(errp, local_err);
1730 goto out;
1733 ret = 0;
1734 out:
1735 if (bs) {
1736 bdrv_unref(bs);
1738 return ret;
1741 static int qcow2_create(const char *filename, QEMUOptionParameter *options,
1742 Error **errp)
1744 const char *backing_file = NULL;
1745 const char *backing_fmt = NULL;
1746 uint64_t sectors = 0;
1747 int flags = 0;
1748 size_t cluster_size = DEFAULT_CLUSTER_SIZE;
1749 int prealloc = 0;
1750 int version = 3;
1751 Error *local_err = NULL;
1752 int ret;
1754 /* Read out options */
1755 while (options && options->name) {
1756 if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
1757 sectors = options->value.n / 512;
1758 } else if (!strcmp(options->name, BLOCK_OPT_BACKING_FILE)) {
1759 backing_file = options->value.s;
1760 } else if (!strcmp(options->name, BLOCK_OPT_BACKING_FMT)) {
1761 backing_fmt = options->value.s;
1762 } else if (!strcmp(options->name, BLOCK_OPT_ENCRYPT)) {
1763 flags |= options->value.n ? BLOCK_FLAG_ENCRYPT : 0;
1764 } else if (!strcmp(options->name, BLOCK_OPT_CLUSTER_SIZE)) {
1765 if (options->value.n) {
1766 cluster_size = options->value.n;
1768 } else if (!strcmp(options->name, BLOCK_OPT_PREALLOC)) {
1769 if (!options->value.s || !strcmp(options->value.s, "off")) {
1770 prealloc = 0;
1771 } else if (!strcmp(options->value.s, "metadata")) {
1772 prealloc = 1;
1773 } else {
1774 error_setg(errp, "Invalid preallocation mode: '%s'",
1775 options->value.s);
1776 return -EINVAL;
1778 } else if (!strcmp(options->name, BLOCK_OPT_COMPAT_LEVEL)) {
1779 if (!options->value.s) {
1780 /* keep the default */
1781 } else if (!strcmp(options->value.s, "0.10")) {
1782 version = 2;
1783 } else if (!strcmp(options->value.s, "1.1")) {
1784 version = 3;
1785 } else {
1786 error_setg(errp, "Invalid compatibility level: '%s'",
1787 options->value.s);
1788 return -EINVAL;
1790 } else if (!strcmp(options->name, BLOCK_OPT_LAZY_REFCOUNTS)) {
1791 flags |= options->value.n ? BLOCK_FLAG_LAZY_REFCOUNTS : 0;
1793 options++;
1796 if (backing_file && prealloc) {
1797 error_setg(errp, "Backing file and preallocation cannot be used at "
1798 "the same time");
1799 return -EINVAL;
1802 if (version < 3 && (flags & BLOCK_FLAG_LAZY_REFCOUNTS)) {
1803 error_setg(errp, "Lazy refcounts only supported with compatibility "
1804 "level 1.1 and above (use compat=1.1 or greater)");
1805 return -EINVAL;
1808 ret = qcow2_create2(filename, sectors, backing_file, backing_fmt, flags,
1809 cluster_size, prealloc, options, version, &local_err);
1810 if (local_err) {
1811 error_propagate(errp, local_err);
1813 return ret;
1816 static coroutine_fn int qcow2_co_write_zeroes(BlockDriverState *bs,
1817 int64_t sector_num, int nb_sectors, BdrvRequestFlags flags)
1819 int ret;
1820 BDRVQcowState *s = bs->opaque;
1822 /* Emulate misaligned zero writes */
1823 if (sector_num % s->cluster_sectors || nb_sectors % s->cluster_sectors) {
1824 return -ENOTSUP;
1827 /* Whatever is left can use real zero clusters */
1828 qemu_co_mutex_lock(&s->lock);
1829 ret = qcow2_zero_clusters(bs, sector_num << BDRV_SECTOR_BITS,
1830 nb_sectors);
1831 qemu_co_mutex_unlock(&s->lock);
1833 return ret;
1836 static coroutine_fn int qcow2_co_discard(BlockDriverState *bs,
1837 int64_t sector_num, int nb_sectors)
1839 int ret;
1840 BDRVQcowState *s = bs->opaque;
1842 qemu_co_mutex_lock(&s->lock);
1843 ret = qcow2_discard_clusters(bs, sector_num << BDRV_SECTOR_BITS,
1844 nb_sectors, QCOW2_DISCARD_REQUEST);
1845 qemu_co_mutex_unlock(&s->lock);
1846 return ret;
1849 static int qcow2_truncate(BlockDriverState *bs, int64_t offset)
1851 BDRVQcowState *s = bs->opaque;
1852 int64_t new_l1_size;
1853 int ret;
1855 if (offset & 511) {
1856 error_report("The new size must be a multiple of 512");
1857 return -EINVAL;
1860 /* cannot proceed if image has snapshots */
1861 if (s->nb_snapshots) {
1862 error_report("Can't resize an image which has snapshots");
1863 return -ENOTSUP;
1866 /* shrinking is currently not supported */
1867 if (offset < bs->total_sectors * 512) {
1868 error_report("qcow2 doesn't support shrinking images yet");
1869 return -ENOTSUP;
1872 new_l1_size = size_to_l1(s, offset);
1873 ret = qcow2_grow_l1_table(bs, new_l1_size, true);
1874 if (ret < 0) {
1875 return ret;
1878 /* write updated header.size */
1879 offset = cpu_to_be64(offset);
1880 ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, size),
1881 &offset, sizeof(uint64_t));
1882 if (ret < 0) {
1883 return ret;
1886 s->l1_vm_state_index = new_l1_size;
1887 return 0;
1890 /* XXX: put compressed sectors first, then all the cluster aligned
1891 tables to avoid losing bytes in alignment */
1892 static int qcow2_write_compressed(BlockDriverState *bs, int64_t sector_num,
1893 const uint8_t *buf, int nb_sectors)
1895 BDRVQcowState *s = bs->opaque;
1896 z_stream strm;
1897 int ret, out_len;
1898 uint8_t *out_buf;
1899 uint64_t cluster_offset;
1901 if (nb_sectors == 0) {
1902 /* align end of file to a sector boundary to ease reading with
1903 sector based I/Os */
1904 cluster_offset = bdrv_getlength(bs->file);
1905 cluster_offset = (cluster_offset + 511) & ~511;
1906 bdrv_truncate(bs->file, cluster_offset);
1907 return 0;
1910 if (nb_sectors != s->cluster_sectors) {
1911 ret = -EINVAL;
1913 /* Zero-pad last write if image size is not cluster aligned */
1914 if (sector_num + nb_sectors == bs->total_sectors &&
1915 nb_sectors < s->cluster_sectors) {
1916 uint8_t *pad_buf = qemu_blockalign(bs, s->cluster_size);
1917 memset(pad_buf, 0, s->cluster_size);
1918 memcpy(pad_buf, buf, nb_sectors * BDRV_SECTOR_SIZE);
1919 ret = qcow2_write_compressed(bs, sector_num,
1920 pad_buf, s->cluster_sectors);
1921 qemu_vfree(pad_buf);
1923 return ret;
1926 out_buf = g_malloc(s->cluster_size + (s->cluster_size / 1000) + 128);
1928 /* best compression, small window, no zlib header */
1929 memset(&strm, 0, sizeof(strm));
1930 ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
1931 Z_DEFLATED, -12,
1932 9, Z_DEFAULT_STRATEGY);
1933 if (ret != 0) {
1934 ret = -EINVAL;
1935 goto fail;
1938 strm.avail_in = s->cluster_size;
1939 strm.next_in = (uint8_t *)buf;
1940 strm.avail_out = s->cluster_size;
1941 strm.next_out = out_buf;
1943 ret = deflate(&strm, Z_FINISH);
1944 if (ret != Z_STREAM_END && ret != Z_OK) {
1945 deflateEnd(&strm);
1946 ret = -EINVAL;
1947 goto fail;
1949 out_len = strm.next_out - out_buf;
1951 deflateEnd(&strm);
1953 if (ret != Z_STREAM_END || out_len >= s->cluster_size) {
1954 /* could not compress: write normal cluster */
1955 ret = bdrv_write(bs, sector_num, buf, s->cluster_sectors);
1956 if (ret < 0) {
1957 goto fail;
1959 } else {
1960 cluster_offset = qcow2_alloc_compressed_cluster_offset(bs,
1961 sector_num << 9, out_len);
1962 if (!cluster_offset) {
1963 ret = -EIO;
1964 goto fail;
1966 cluster_offset &= s->cluster_offset_mask;
1968 ret = qcow2_pre_write_overlap_check(bs, 0, cluster_offset, out_len);
1969 if (ret < 0) {
1970 goto fail;
1973 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_COMPRESSED);
1974 ret = bdrv_pwrite(bs->file, cluster_offset, out_buf, out_len);
1975 if (ret < 0) {
1976 goto fail;
1980 ret = 0;
1981 fail:
1982 g_free(out_buf);
1983 return ret;
1986 static coroutine_fn int qcow2_co_flush_to_os(BlockDriverState *bs)
1988 BDRVQcowState *s = bs->opaque;
1989 int ret;
1991 qemu_co_mutex_lock(&s->lock);
1992 ret = qcow2_cache_flush(bs, s->l2_table_cache);
1993 if (ret < 0) {
1994 qemu_co_mutex_unlock(&s->lock);
1995 return ret;
1998 if (qcow2_need_accurate_refcounts(s)) {
1999 ret = qcow2_cache_flush(bs, s->refcount_block_cache);
2000 if (ret < 0) {
2001 qemu_co_mutex_unlock(&s->lock);
2002 return ret;
2005 qemu_co_mutex_unlock(&s->lock);
2007 return 0;
2010 static int qcow2_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
2012 BDRVQcowState *s = bs->opaque;
2013 bdi->unallocated_blocks_are_zero = true;
2014 bdi->can_write_zeroes_with_unmap = (s->qcow_version >= 3);
2015 bdi->cluster_size = s->cluster_size;
2016 bdi->vm_state_offset = qcow2_vm_state_offset(s);
2017 return 0;
2020 static ImageInfoSpecific *qcow2_get_specific_info(BlockDriverState *bs)
2022 BDRVQcowState *s = bs->opaque;
2023 ImageInfoSpecific *spec_info = g_new(ImageInfoSpecific, 1);
2025 *spec_info = (ImageInfoSpecific){
2026 .kind = IMAGE_INFO_SPECIFIC_KIND_QCOW2,
2028 .qcow2 = g_new(ImageInfoSpecificQCow2, 1),
2031 if (s->qcow_version == 2) {
2032 *spec_info->qcow2 = (ImageInfoSpecificQCow2){
2033 .compat = g_strdup("0.10"),
2035 } else if (s->qcow_version == 3) {
2036 *spec_info->qcow2 = (ImageInfoSpecificQCow2){
2037 .compat = g_strdup("1.1"),
2038 .lazy_refcounts = s->compatible_features &
2039 QCOW2_COMPAT_LAZY_REFCOUNTS,
2040 .has_lazy_refcounts = true,
2044 return spec_info;
2047 #if 0
2048 static void dump_refcounts(BlockDriverState *bs)
2050 BDRVQcowState *s = bs->opaque;
2051 int64_t nb_clusters, k, k1, size;
2052 int refcount;
2054 size = bdrv_getlength(bs->file);
2055 nb_clusters = size_to_clusters(s, size);
2056 for(k = 0; k < nb_clusters;) {
2057 k1 = k;
2058 refcount = get_refcount(bs, k);
2059 k++;
2060 while (k < nb_clusters && get_refcount(bs, k) == refcount)
2061 k++;
2062 printf("%" PRId64 ": refcount=%d nb=%" PRId64 "\n", k, refcount,
2063 k - k1);
2066 #endif
2068 static int qcow2_save_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
2069 int64_t pos)
2071 BDRVQcowState *s = bs->opaque;
2072 int64_t total_sectors = bs->total_sectors;
2073 int growable = bs->growable;
2074 bool zero_beyond_eof = bs->zero_beyond_eof;
2075 int ret;
2077 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_SAVE);
2078 bs->growable = 1;
2079 bs->zero_beyond_eof = false;
2080 ret = bdrv_pwritev(bs, qcow2_vm_state_offset(s) + pos, qiov);
2081 bs->growable = growable;
2082 bs->zero_beyond_eof = zero_beyond_eof;
2084 /* bdrv_co_do_writev will have increased the total_sectors value to include
2085 * the VM state - the VM state is however not an actual part of the block
2086 * device, therefore, we need to restore the old value. */
2087 bs->total_sectors = total_sectors;
2089 return ret;
2092 static int qcow2_load_vmstate(BlockDriverState *bs, uint8_t *buf,
2093 int64_t pos, int size)
2095 BDRVQcowState *s = bs->opaque;
2096 int growable = bs->growable;
2097 bool zero_beyond_eof = bs->zero_beyond_eof;
2098 int ret;
2100 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_LOAD);
2101 bs->growable = 1;
2102 bs->zero_beyond_eof = false;
2103 ret = bdrv_pread(bs, qcow2_vm_state_offset(s) + pos, buf, size);
2104 bs->growable = growable;
2105 bs->zero_beyond_eof = zero_beyond_eof;
2107 return ret;
2111 * Downgrades an image's version. To achieve this, any incompatible features
2112 * have to be removed.
2114 static int qcow2_downgrade(BlockDriverState *bs, int target_version)
2116 BDRVQcowState *s = bs->opaque;
2117 int current_version = s->qcow_version;
2118 int ret;
2120 if (target_version == current_version) {
2121 return 0;
2122 } else if (target_version > current_version) {
2123 return -EINVAL;
2124 } else if (target_version != 2) {
2125 return -EINVAL;
2128 if (s->refcount_order != 4) {
2129 /* we would have to convert the image to a refcount_order == 4 image
2130 * here; however, since qemu (at the time of writing this) does not
2131 * support anything different than 4 anyway, there is no point in doing
2132 * so right now; however, we should error out (if qemu supports this in
2133 * the future and this code has not been adapted) */
2134 error_report("qcow2_downgrade: Image refcount orders other than 4 are "
2135 "currently not supported.");
2136 return -ENOTSUP;
2139 /* clear incompatible features */
2140 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
2141 ret = qcow2_mark_clean(bs);
2142 if (ret < 0) {
2143 return ret;
2147 /* with QCOW2_INCOMPAT_CORRUPT, it is pretty much impossible to get here in
2148 * the first place; if that happens nonetheless, returning -ENOTSUP is the
2149 * best thing to do anyway */
2151 if (s->incompatible_features) {
2152 return -ENOTSUP;
2155 /* since we can ignore compatible features, we can set them to 0 as well */
2156 s->compatible_features = 0;
2157 /* if lazy refcounts have been used, they have already been fixed through
2158 * clearing the dirty flag */
2160 /* clearing autoclear features is trivial */
2161 s->autoclear_features = 0;
2163 ret = qcow2_expand_zero_clusters(bs);
2164 if (ret < 0) {
2165 return ret;
2168 s->qcow_version = target_version;
2169 ret = qcow2_update_header(bs);
2170 if (ret < 0) {
2171 s->qcow_version = current_version;
2172 return ret;
2174 return 0;
2177 static int qcow2_amend_options(BlockDriverState *bs,
2178 QEMUOptionParameter *options)
2180 BDRVQcowState *s = bs->opaque;
2181 int old_version = s->qcow_version, new_version = old_version;
2182 uint64_t new_size = 0;
2183 const char *backing_file = NULL, *backing_format = NULL;
2184 bool lazy_refcounts = s->use_lazy_refcounts;
2185 int ret;
2186 int i;
2188 for (i = 0; options[i].name; i++)
2190 if (!options[i].assigned) {
2191 /* only change explicitly defined options */
2192 continue;
2195 if (!strcmp(options[i].name, "compat")) {
2196 if (!options[i].value.s) {
2197 /* preserve default */
2198 } else if (!strcmp(options[i].value.s, "0.10")) {
2199 new_version = 2;
2200 } else if (!strcmp(options[i].value.s, "1.1")) {
2201 new_version = 3;
2202 } else {
2203 fprintf(stderr, "Unknown compatibility level %s.\n",
2204 options[i].value.s);
2205 return -EINVAL;
2207 } else if (!strcmp(options[i].name, "preallocation")) {
2208 fprintf(stderr, "Cannot change preallocation mode.\n");
2209 return -ENOTSUP;
2210 } else if (!strcmp(options[i].name, "size")) {
2211 new_size = options[i].value.n;
2212 } else if (!strcmp(options[i].name, "backing_file")) {
2213 backing_file = options[i].value.s;
2214 } else if (!strcmp(options[i].name, "backing_fmt")) {
2215 backing_format = options[i].value.s;
2216 } else if (!strcmp(options[i].name, "encryption")) {
2217 if ((options[i].value.n != !!s->crypt_method)) {
2218 fprintf(stderr, "Changing the encryption flag is not "
2219 "supported.\n");
2220 return -ENOTSUP;
2222 } else if (!strcmp(options[i].name, "cluster_size")) {
2223 if (options[i].value.n != s->cluster_size) {
2224 fprintf(stderr, "Changing the cluster size is not "
2225 "supported.\n");
2226 return -ENOTSUP;
2228 } else if (!strcmp(options[i].name, "lazy_refcounts")) {
2229 lazy_refcounts = options[i].value.n;
2230 } else {
2231 /* if this assertion fails, this probably means a new option was
2232 * added without having it covered here */
2233 assert(false);
2237 if (new_version != old_version) {
2238 if (new_version > old_version) {
2239 /* Upgrade */
2240 s->qcow_version = new_version;
2241 ret = qcow2_update_header(bs);
2242 if (ret < 0) {
2243 s->qcow_version = old_version;
2244 return ret;
2246 } else {
2247 ret = qcow2_downgrade(bs, new_version);
2248 if (ret < 0) {
2249 return ret;
2254 if (backing_file || backing_format) {
2255 ret = qcow2_change_backing_file(bs, backing_file ?: bs->backing_file,
2256 backing_format ?: bs->backing_format);
2257 if (ret < 0) {
2258 return ret;
2262 if (s->use_lazy_refcounts != lazy_refcounts) {
2263 if (lazy_refcounts) {
2264 if (s->qcow_version < 3) {
2265 fprintf(stderr, "Lazy refcounts only supported with compatibility "
2266 "level 1.1 and above (use compat=1.1 or greater)\n");
2267 return -EINVAL;
2269 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
2270 ret = qcow2_update_header(bs);
2271 if (ret < 0) {
2272 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
2273 return ret;
2275 s->use_lazy_refcounts = true;
2276 } else {
2277 /* make image clean first */
2278 ret = qcow2_mark_clean(bs);
2279 if (ret < 0) {
2280 return ret;
2282 /* now disallow lazy refcounts */
2283 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
2284 ret = qcow2_update_header(bs);
2285 if (ret < 0) {
2286 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
2287 return ret;
2289 s->use_lazy_refcounts = false;
2293 if (new_size) {
2294 ret = bdrv_truncate(bs, new_size);
2295 if (ret < 0) {
2296 return ret;
2300 return 0;
2303 static QEMUOptionParameter qcow2_create_options[] = {
2305 .name = BLOCK_OPT_SIZE,
2306 .type = OPT_SIZE,
2307 .help = "Virtual disk size"
2310 .name = BLOCK_OPT_COMPAT_LEVEL,
2311 .type = OPT_STRING,
2312 .help = "Compatibility level (0.10 or 1.1)"
2315 .name = BLOCK_OPT_BACKING_FILE,
2316 .type = OPT_STRING,
2317 .help = "File name of a base image"
2320 .name = BLOCK_OPT_BACKING_FMT,
2321 .type = OPT_STRING,
2322 .help = "Image format of the base image"
2325 .name = BLOCK_OPT_ENCRYPT,
2326 .type = OPT_FLAG,
2327 .help = "Encrypt the image"
2330 .name = BLOCK_OPT_CLUSTER_SIZE,
2331 .type = OPT_SIZE,
2332 .help = "qcow2 cluster size",
2333 .value = { .n = DEFAULT_CLUSTER_SIZE },
2336 .name = BLOCK_OPT_PREALLOC,
2337 .type = OPT_STRING,
2338 .help = "Preallocation mode (allowed values: off, metadata)"
2341 .name = BLOCK_OPT_LAZY_REFCOUNTS,
2342 .type = OPT_FLAG,
2343 .help = "Postpone refcount updates",
2345 { NULL }
2348 static BlockDriver bdrv_qcow2 = {
2349 .format_name = "qcow2",
2350 .instance_size = sizeof(BDRVQcowState),
2351 .bdrv_probe = qcow2_probe,
2352 .bdrv_open = qcow2_open,
2353 .bdrv_close = qcow2_close,
2354 .bdrv_reopen_prepare = qcow2_reopen_prepare,
2355 .bdrv_create = qcow2_create,
2356 .bdrv_has_zero_init = bdrv_has_zero_init_1,
2357 .bdrv_co_get_block_status = qcow2_co_get_block_status,
2358 .bdrv_set_key = qcow2_set_key,
2360 .bdrv_co_readv = qcow2_co_readv,
2361 .bdrv_co_writev = qcow2_co_writev,
2362 .bdrv_co_flush_to_os = qcow2_co_flush_to_os,
2364 .bdrv_co_write_zeroes = qcow2_co_write_zeroes,
2365 .bdrv_co_discard = qcow2_co_discard,
2366 .bdrv_truncate = qcow2_truncate,
2367 .bdrv_write_compressed = qcow2_write_compressed,
2369 .bdrv_snapshot_create = qcow2_snapshot_create,
2370 .bdrv_snapshot_goto = qcow2_snapshot_goto,
2371 .bdrv_snapshot_delete = qcow2_snapshot_delete,
2372 .bdrv_snapshot_list = qcow2_snapshot_list,
2373 .bdrv_snapshot_load_tmp = qcow2_snapshot_load_tmp,
2374 .bdrv_get_info = qcow2_get_info,
2375 .bdrv_get_specific_info = qcow2_get_specific_info,
2377 .bdrv_save_vmstate = qcow2_save_vmstate,
2378 .bdrv_load_vmstate = qcow2_load_vmstate,
2380 .bdrv_change_backing_file = qcow2_change_backing_file,
2382 .bdrv_refresh_limits = qcow2_refresh_limits,
2383 .bdrv_invalidate_cache = qcow2_invalidate_cache,
2385 .create_options = qcow2_create_options,
2386 .bdrv_check = qcow2_check,
2387 .bdrv_amend_options = qcow2_amend_options,
2390 static void bdrv_qcow2_init(void)
2392 bdrv_register(&bdrv_qcow2);
2395 block_init(bdrv_qcow2_init);