qapi: treat all negative return of strtosz_suffix() as error
[qemu.git] / block / qcow2.c
bloba4b97e8263c307c1043754f319b2781cf83979d7
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=%" PRIu32
128 " too large (>=%zu)", ext.len,
129 sizeof(bs->backing_format));
130 return 2;
132 ret = bdrv_pread(bs->file, offset, bs->backing_format, ext.len);
133 if (ret < 0) {
134 error_setg_errno(errp, -ret, "ERROR: ext_backing_format: "
135 "Could not read format name");
136 return 3;
138 bs->backing_format[ext.len] = '\0';
139 #ifdef DEBUG_EXT
140 printf("Qcow2: Got format extension %s\n", bs->backing_format);
141 #endif
142 break;
144 case QCOW2_EXT_MAGIC_FEATURE_TABLE:
145 if (p_feature_table != NULL) {
146 void* feature_table = g_malloc0(ext.len + 2 * sizeof(Qcow2Feature));
147 ret = bdrv_pread(bs->file, offset , feature_table, ext.len);
148 if (ret < 0) {
149 error_setg_errno(errp, -ret, "ERROR: ext_feature_table: "
150 "Could not read table");
151 return ret;
154 *p_feature_table = feature_table;
156 break;
158 default:
159 /* unknown magic - save it in case we need to rewrite the header */
161 Qcow2UnknownHeaderExtension *uext;
163 uext = g_malloc0(sizeof(*uext) + ext.len);
164 uext->magic = ext.magic;
165 uext->len = ext.len;
166 QLIST_INSERT_HEAD(&s->unknown_header_ext, uext, next);
168 ret = bdrv_pread(bs->file, offset , uext->data, uext->len);
169 if (ret < 0) {
170 error_setg_errno(errp, -ret, "ERROR: unknown extension: "
171 "Could not read data");
172 return ret;
175 break;
178 offset += ((ext.len + 7) & ~7);
181 return 0;
184 static void cleanup_unknown_header_ext(BlockDriverState *bs)
186 BDRVQcowState *s = bs->opaque;
187 Qcow2UnknownHeaderExtension *uext, *next;
189 QLIST_FOREACH_SAFE(uext, &s->unknown_header_ext, next, next) {
190 QLIST_REMOVE(uext, next);
191 g_free(uext);
195 static void GCC_FMT_ATTR(3, 4) report_unsupported(BlockDriverState *bs,
196 Error **errp, const char *fmt, ...)
198 char msg[64];
199 va_list ap;
201 va_start(ap, fmt);
202 vsnprintf(msg, sizeof(msg), fmt, ap);
203 va_end(ap);
205 error_set(errp, QERR_UNKNOWN_BLOCK_FORMAT_FEATURE, bs->device_name, "qcow2",
206 msg);
209 static void report_unsupported_feature(BlockDriverState *bs,
210 Error **errp, Qcow2Feature *table, uint64_t mask)
212 while (table && table->name[0] != '\0') {
213 if (table->type == QCOW2_FEAT_TYPE_INCOMPATIBLE) {
214 if (mask & (1 << table->bit)) {
215 report_unsupported(bs, errp, "%.46s", table->name);
216 mask &= ~(1 << table->bit);
219 table++;
222 if (mask) {
223 report_unsupported(bs, errp, "Unknown incompatible feature: %" PRIx64,
224 mask);
229 * Sets the dirty bit and flushes afterwards if necessary.
231 * The incompatible_features bit is only set if the image file header was
232 * updated successfully. Therefore it is not required to check the return
233 * value of this function.
235 int qcow2_mark_dirty(BlockDriverState *bs)
237 BDRVQcowState *s = bs->opaque;
238 uint64_t val;
239 int ret;
241 assert(s->qcow_version >= 3);
243 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
244 return 0; /* already dirty */
247 val = cpu_to_be64(s->incompatible_features | QCOW2_INCOMPAT_DIRTY);
248 ret = bdrv_pwrite(bs->file, offsetof(QCowHeader, incompatible_features),
249 &val, sizeof(val));
250 if (ret < 0) {
251 return ret;
253 ret = bdrv_flush(bs->file);
254 if (ret < 0) {
255 return ret;
258 /* Only treat image as dirty if the header was updated successfully */
259 s->incompatible_features |= QCOW2_INCOMPAT_DIRTY;
260 return 0;
264 * Clears the dirty bit and flushes before if necessary. Only call this
265 * function when there are no pending requests, it does not guard against
266 * concurrent requests dirtying the image.
268 static int qcow2_mark_clean(BlockDriverState *bs)
270 BDRVQcowState *s = bs->opaque;
272 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
273 int ret;
275 s->incompatible_features &= ~QCOW2_INCOMPAT_DIRTY;
277 ret = bdrv_flush(bs);
278 if (ret < 0) {
279 return ret;
282 return qcow2_update_header(bs);
284 return 0;
288 * Marks the image as corrupt.
290 int qcow2_mark_corrupt(BlockDriverState *bs)
292 BDRVQcowState *s = bs->opaque;
294 s->incompatible_features |= QCOW2_INCOMPAT_CORRUPT;
295 return qcow2_update_header(bs);
299 * Marks the image as consistent, i.e., unsets the corrupt bit, and flushes
300 * before if necessary.
302 int qcow2_mark_consistent(BlockDriverState *bs)
304 BDRVQcowState *s = bs->opaque;
306 if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
307 int ret = bdrv_flush(bs);
308 if (ret < 0) {
309 return ret;
312 s->incompatible_features &= ~QCOW2_INCOMPAT_CORRUPT;
313 return qcow2_update_header(bs);
315 return 0;
318 static int qcow2_check(BlockDriverState *bs, BdrvCheckResult *result,
319 BdrvCheckMode fix)
321 int ret = qcow2_check_refcounts(bs, result, fix);
322 if (ret < 0) {
323 return ret;
326 if (fix && result->check_errors == 0 && result->corruptions == 0) {
327 ret = qcow2_mark_clean(bs);
328 if (ret < 0) {
329 return ret;
331 return qcow2_mark_consistent(bs);
333 return ret;
336 static int validate_table_offset(BlockDriverState *bs, uint64_t offset,
337 uint64_t entries, size_t entry_len)
339 BDRVQcowState *s = bs->opaque;
340 uint64_t size;
342 /* Use signed INT64_MAX as the maximum even for uint64_t header fields,
343 * because values will be passed to qemu functions taking int64_t. */
344 if (entries > INT64_MAX / entry_len) {
345 return -EINVAL;
348 size = entries * entry_len;
350 if (INT64_MAX - size < offset) {
351 return -EINVAL;
354 /* Tables must be cluster aligned */
355 if (offset & (s->cluster_size - 1)) {
356 return -EINVAL;
359 return 0;
362 static QemuOptsList qcow2_runtime_opts = {
363 .name = "qcow2",
364 .head = QTAILQ_HEAD_INITIALIZER(qcow2_runtime_opts.head),
365 .desc = {
367 .name = QCOW2_OPT_LAZY_REFCOUNTS,
368 .type = QEMU_OPT_BOOL,
369 .help = "Postpone refcount updates",
372 .name = QCOW2_OPT_DISCARD_REQUEST,
373 .type = QEMU_OPT_BOOL,
374 .help = "Pass guest discard requests to the layer below",
377 .name = QCOW2_OPT_DISCARD_SNAPSHOT,
378 .type = QEMU_OPT_BOOL,
379 .help = "Generate discard requests when snapshot related space "
380 "is freed",
383 .name = QCOW2_OPT_DISCARD_OTHER,
384 .type = QEMU_OPT_BOOL,
385 .help = "Generate discard requests when other clusters are freed",
388 .name = QCOW2_OPT_OVERLAP,
389 .type = QEMU_OPT_STRING,
390 .help = "Selects which overlap checks to perform from a range of "
391 "templates (none, constant, cached, all)",
394 .name = QCOW2_OPT_OVERLAP_MAIN_HEADER,
395 .type = QEMU_OPT_BOOL,
396 .help = "Check for unintended writes into the main qcow2 header",
399 .name = QCOW2_OPT_OVERLAP_ACTIVE_L1,
400 .type = QEMU_OPT_BOOL,
401 .help = "Check for unintended writes into the active L1 table",
404 .name = QCOW2_OPT_OVERLAP_ACTIVE_L2,
405 .type = QEMU_OPT_BOOL,
406 .help = "Check for unintended writes into an active L2 table",
409 .name = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
410 .type = QEMU_OPT_BOOL,
411 .help = "Check for unintended writes into the refcount table",
414 .name = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
415 .type = QEMU_OPT_BOOL,
416 .help = "Check for unintended writes into a refcount block",
419 .name = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
420 .type = QEMU_OPT_BOOL,
421 .help = "Check for unintended writes into the snapshot table",
424 .name = QCOW2_OPT_OVERLAP_INACTIVE_L1,
425 .type = QEMU_OPT_BOOL,
426 .help = "Check for unintended writes into an inactive L1 table",
429 .name = QCOW2_OPT_OVERLAP_INACTIVE_L2,
430 .type = QEMU_OPT_BOOL,
431 .help = "Check for unintended writes into an inactive L2 table",
433 { /* end of list */ }
437 static const char *overlap_bool_option_names[QCOW2_OL_MAX_BITNR] = {
438 [QCOW2_OL_MAIN_HEADER_BITNR] = QCOW2_OPT_OVERLAP_MAIN_HEADER,
439 [QCOW2_OL_ACTIVE_L1_BITNR] = QCOW2_OPT_OVERLAP_ACTIVE_L1,
440 [QCOW2_OL_ACTIVE_L2_BITNR] = QCOW2_OPT_OVERLAP_ACTIVE_L2,
441 [QCOW2_OL_REFCOUNT_TABLE_BITNR] = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
442 [QCOW2_OL_REFCOUNT_BLOCK_BITNR] = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
443 [QCOW2_OL_SNAPSHOT_TABLE_BITNR] = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
444 [QCOW2_OL_INACTIVE_L1_BITNR] = QCOW2_OPT_OVERLAP_INACTIVE_L1,
445 [QCOW2_OL_INACTIVE_L2_BITNR] = QCOW2_OPT_OVERLAP_INACTIVE_L2,
448 static int qcow2_open(BlockDriverState *bs, QDict *options, int flags,
449 Error **errp)
451 BDRVQcowState *s = bs->opaque;
452 unsigned int len, i;
453 int ret = 0;
454 QCowHeader header;
455 QemuOpts *opts;
456 Error *local_err = NULL;
457 uint64_t ext_end;
458 uint64_t l1_vm_state_index;
459 const char *opt_overlap_check;
460 int overlap_check_template = 0;
462 ret = bdrv_pread(bs->file, 0, &header, sizeof(header));
463 if (ret < 0) {
464 error_setg_errno(errp, -ret, "Could not read qcow2 header");
465 goto fail;
467 be32_to_cpus(&header.magic);
468 be32_to_cpus(&header.version);
469 be64_to_cpus(&header.backing_file_offset);
470 be32_to_cpus(&header.backing_file_size);
471 be64_to_cpus(&header.size);
472 be32_to_cpus(&header.cluster_bits);
473 be32_to_cpus(&header.crypt_method);
474 be64_to_cpus(&header.l1_table_offset);
475 be32_to_cpus(&header.l1_size);
476 be64_to_cpus(&header.refcount_table_offset);
477 be32_to_cpus(&header.refcount_table_clusters);
478 be64_to_cpus(&header.snapshots_offset);
479 be32_to_cpus(&header.nb_snapshots);
481 if (header.magic != QCOW_MAGIC) {
482 error_setg(errp, "Image is not in qcow2 format");
483 ret = -EINVAL;
484 goto fail;
486 if (header.version < 2 || header.version > 3) {
487 report_unsupported(bs, errp, "QCOW version %" PRIu32, header.version);
488 ret = -ENOTSUP;
489 goto fail;
492 s->qcow_version = header.version;
494 /* Initialise cluster size */
495 if (header.cluster_bits < MIN_CLUSTER_BITS ||
496 header.cluster_bits > MAX_CLUSTER_BITS) {
497 error_setg(errp, "Unsupported cluster size: 2^%" PRIu32,
498 header.cluster_bits);
499 ret = -EINVAL;
500 goto fail;
503 s->cluster_bits = header.cluster_bits;
504 s->cluster_size = 1 << s->cluster_bits;
505 s->cluster_sectors = 1 << (s->cluster_bits - 9);
507 /* Initialise version 3 header fields */
508 if (header.version == 2) {
509 header.incompatible_features = 0;
510 header.compatible_features = 0;
511 header.autoclear_features = 0;
512 header.refcount_order = 4;
513 header.header_length = 72;
514 } else {
515 be64_to_cpus(&header.incompatible_features);
516 be64_to_cpus(&header.compatible_features);
517 be64_to_cpus(&header.autoclear_features);
518 be32_to_cpus(&header.refcount_order);
519 be32_to_cpus(&header.header_length);
521 if (header.header_length < 104) {
522 error_setg(errp, "qcow2 header too short");
523 ret = -EINVAL;
524 goto fail;
528 if (header.header_length > s->cluster_size) {
529 error_setg(errp, "qcow2 header exceeds cluster size");
530 ret = -EINVAL;
531 goto fail;
534 if (header.header_length > sizeof(header)) {
535 s->unknown_header_fields_size = header.header_length - sizeof(header);
536 s->unknown_header_fields = g_malloc(s->unknown_header_fields_size);
537 ret = bdrv_pread(bs->file, sizeof(header), s->unknown_header_fields,
538 s->unknown_header_fields_size);
539 if (ret < 0) {
540 error_setg_errno(errp, -ret, "Could not read unknown qcow2 header "
541 "fields");
542 goto fail;
546 if (header.backing_file_offset > s->cluster_size) {
547 error_setg(errp, "Invalid backing file offset");
548 ret = -EINVAL;
549 goto fail;
552 if (header.backing_file_offset) {
553 ext_end = header.backing_file_offset;
554 } else {
555 ext_end = 1 << header.cluster_bits;
558 /* Handle feature bits */
559 s->incompatible_features = header.incompatible_features;
560 s->compatible_features = header.compatible_features;
561 s->autoclear_features = header.autoclear_features;
563 if (s->incompatible_features & ~QCOW2_INCOMPAT_MASK) {
564 void *feature_table = NULL;
565 qcow2_read_extensions(bs, header.header_length, ext_end,
566 &feature_table, NULL);
567 report_unsupported_feature(bs, errp, feature_table,
568 s->incompatible_features &
569 ~QCOW2_INCOMPAT_MASK);
570 ret = -ENOTSUP;
571 g_free(feature_table);
572 goto fail;
575 if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
576 /* Corrupt images may not be written to unless they are being repaired
578 if ((flags & BDRV_O_RDWR) && !(flags & BDRV_O_CHECK)) {
579 error_setg(errp, "qcow2: Image is corrupt; cannot be opened "
580 "read/write");
581 ret = -EACCES;
582 goto fail;
586 /* Check support for various header values */
587 if (header.refcount_order != 4) {
588 report_unsupported(bs, errp, "%d bit reference counts",
589 1 << header.refcount_order);
590 ret = -ENOTSUP;
591 goto fail;
593 s->refcount_order = header.refcount_order;
595 if (header.crypt_method > QCOW_CRYPT_AES) {
596 error_setg(errp, "Unsupported encryption method: %" PRIu32,
597 header.crypt_method);
598 ret = -EINVAL;
599 goto fail;
601 s->crypt_method_header = header.crypt_method;
602 if (s->crypt_method_header) {
603 bs->encrypted = 1;
606 s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */
607 s->l2_size = 1 << s->l2_bits;
608 bs->total_sectors = header.size / 512;
609 s->csize_shift = (62 - (s->cluster_bits - 8));
610 s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;
611 s->cluster_offset_mask = (1LL << s->csize_shift) - 1;
613 s->refcount_table_offset = header.refcount_table_offset;
614 s->refcount_table_size =
615 header.refcount_table_clusters << (s->cluster_bits - 3);
617 if (header.refcount_table_clusters > qcow2_max_refcount_clusters(s)) {
618 error_setg(errp, "Reference count table too large");
619 ret = -EINVAL;
620 goto fail;
623 ret = validate_table_offset(bs, s->refcount_table_offset,
624 s->refcount_table_size, sizeof(uint64_t));
625 if (ret < 0) {
626 error_setg(errp, "Invalid reference count table offset");
627 goto fail;
630 /* Snapshot table offset/length */
631 if (header.nb_snapshots > QCOW_MAX_SNAPSHOTS) {
632 error_setg(errp, "Too many snapshots");
633 ret = -EINVAL;
634 goto fail;
637 ret = validate_table_offset(bs, header.snapshots_offset,
638 header.nb_snapshots,
639 sizeof(QCowSnapshotHeader));
640 if (ret < 0) {
641 error_setg(errp, "Invalid snapshot table offset");
642 goto fail;
645 /* read the level 1 table */
646 if (header.l1_size > QCOW_MAX_L1_SIZE) {
647 error_setg(errp, "Active L1 table too large");
648 ret = -EFBIG;
649 goto fail;
651 s->l1_size = header.l1_size;
653 l1_vm_state_index = size_to_l1(s, header.size);
654 if (l1_vm_state_index > INT_MAX) {
655 error_setg(errp, "Image is too big");
656 ret = -EFBIG;
657 goto fail;
659 s->l1_vm_state_index = l1_vm_state_index;
661 /* the L1 table must contain at least enough entries to put
662 header.size bytes */
663 if (s->l1_size < s->l1_vm_state_index) {
664 error_setg(errp, "L1 table is too small");
665 ret = -EINVAL;
666 goto fail;
669 ret = validate_table_offset(bs, header.l1_table_offset,
670 header.l1_size, sizeof(uint64_t));
671 if (ret < 0) {
672 error_setg(errp, "Invalid L1 table offset");
673 goto fail;
675 s->l1_table_offset = header.l1_table_offset;
678 if (s->l1_size > 0) {
679 s->l1_table = g_malloc0(
680 align_offset(s->l1_size * sizeof(uint64_t), 512));
681 ret = bdrv_pread(bs->file, s->l1_table_offset, s->l1_table,
682 s->l1_size * sizeof(uint64_t));
683 if (ret < 0) {
684 error_setg_errno(errp, -ret, "Could not read L1 table");
685 goto fail;
687 for(i = 0;i < s->l1_size; i++) {
688 be64_to_cpus(&s->l1_table[i]);
692 /* alloc L2 table/refcount block cache */
693 s->l2_table_cache = qcow2_cache_create(bs, L2_CACHE_SIZE);
694 s->refcount_block_cache = qcow2_cache_create(bs, REFCOUNT_CACHE_SIZE);
696 s->cluster_cache = g_malloc(s->cluster_size);
697 /* one more sector for decompressed data alignment */
698 s->cluster_data = qemu_blockalign(bs, QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size
699 + 512);
700 s->cluster_cache_offset = -1;
701 s->flags = flags;
703 ret = qcow2_refcount_init(bs);
704 if (ret != 0) {
705 error_setg_errno(errp, -ret, "Could not initialize refcount handling");
706 goto fail;
709 QLIST_INIT(&s->cluster_allocs);
710 QTAILQ_INIT(&s->discards);
712 /* read qcow2 extensions */
713 if (qcow2_read_extensions(bs, header.header_length, ext_end, NULL,
714 &local_err)) {
715 error_propagate(errp, local_err);
716 ret = -EINVAL;
717 goto fail;
720 /* read the backing file name */
721 if (header.backing_file_offset != 0) {
722 len = header.backing_file_size;
723 if (len > MIN(1023, s->cluster_size - header.backing_file_offset)) {
724 error_setg(errp, "Backing file name too long");
725 ret = -EINVAL;
726 goto fail;
728 ret = bdrv_pread(bs->file, header.backing_file_offset,
729 bs->backing_file, len);
730 if (ret < 0) {
731 error_setg_errno(errp, -ret, "Could not read backing file name");
732 goto fail;
734 bs->backing_file[len] = '\0';
737 /* Internal snapshots */
738 s->snapshots_offset = header.snapshots_offset;
739 s->nb_snapshots = header.nb_snapshots;
741 ret = qcow2_read_snapshots(bs);
742 if (ret < 0) {
743 error_setg_errno(errp, -ret, "Could not read snapshots");
744 goto fail;
747 /* Clear unknown autoclear feature bits */
748 if (!bs->read_only && !(flags & BDRV_O_INCOMING) && s->autoclear_features) {
749 s->autoclear_features = 0;
750 ret = qcow2_update_header(bs);
751 if (ret < 0) {
752 error_setg_errno(errp, -ret, "Could not update qcow2 header");
753 goto fail;
757 /* Initialise locks */
758 qemu_co_mutex_init(&s->lock);
760 /* Repair image if dirty */
761 if (!(flags & (BDRV_O_CHECK | BDRV_O_INCOMING)) && !bs->read_only &&
762 (s->incompatible_features & QCOW2_INCOMPAT_DIRTY)) {
763 BdrvCheckResult result = {0};
765 ret = qcow2_check(bs, &result, BDRV_FIX_ERRORS);
766 if (ret < 0) {
767 error_setg_errno(errp, -ret, "Could not repair dirty image");
768 goto fail;
772 /* Enable lazy_refcounts according to image and command line options */
773 opts = qemu_opts_create(&qcow2_runtime_opts, NULL, 0, &error_abort);
774 qemu_opts_absorb_qdict(opts, options, &local_err);
775 if (local_err) {
776 error_propagate(errp, local_err);
777 ret = -EINVAL;
778 goto fail;
781 s->use_lazy_refcounts = qemu_opt_get_bool(opts, QCOW2_OPT_LAZY_REFCOUNTS,
782 (s->compatible_features & QCOW2_COMPAT_LAZY_REFCOUNTS));
784 s->discard_passthrough[QCOW2_DISCARD_NEVER] = false;
785 s->discard_passthrough[QCOW2_DISCARD_ALWAYS] = true;
786 s->discard_passthrough[QCOW2_DISCARD_REQUEST] =
787 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_REQUEST,
788 flags & BDRV_O_UNMAP);
789 s->discard_passthrough[QCOW2_DISCARD_SNAPSHOT] =
790 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_SNAPSHOT, true);
791 s->discard_passthrough[QCOW2_DISCARD_OTHER] =
792 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_OTHER, false);
794 opt_overlap_check = qemu_opt_get(opts, "overlap-check") ?: "cached";
795 if (!strcmp(opt_overlap_check, "none")) {
796 overlap_check_template = 0;
797 } else if (!strcmp(opt_overlap_check, "constant")) {
798 overlap_check_template = QCOW2_OL_CONSTANT;
799 } else if (!strcmp(opt_overlap_check, "cached")) {
800 overlap_check_template = QCOW2_OL_CACHED;
801 } else if (!strcmp(opt_overlap_check, "all")) {
802 overlap_check_template = QCOW2_OL_ALL;
803 } else {
804 error_setg(errp, "Unsupported value '%s' for qcow2 option "
805 "'overlap-check'. Allowed are either of the following: "
806 "none, constant, cached, all", opt_overlap_check);
807 qemu_opts_del(opts);
808 ret = -EINVAL;
809 goto fail;
812 s->overlap_check = 0;
813 for (i = 0; i < QCOW2_OL_MAX_BITNR; i++) {
814 /* overlap-check defines a template bitmask, but every flag may be
815 * overwritten through the associated boolean option */
816 s->overlap_check |=
817 qemu_opt_get_bool(opts, overlap_bool_option_names[i],
818 overlap_check_template & (1 << i)) << i;
821 qemu_opts_del(opts);
823 if (s->use_lazy_refcounts && s->qcow_version < 3) {
824 error_setg(errp, "Lazy refcounts require a qcow2 image with at least "
825 "qemu 1.1 compatibility level");
826 ret = -EINVAL;
827 goto fail;
830 #ifdef DEBUG_ALLOC
832 BdrvCheckResult result = {0};
833 qcow2_check_refcounts(bs, &result, 0);
835 #endif
836 return ret;
838 fail:
839 g_free(s->unknown_header_fields);
840 cleanup_unknown_header_ext(bs);
841 qcow2_free_snapshots(bs);
842 qcow2_refcount_close(bs);
843 g_free(s->l1_table);
844 /* else pre-write overlap checks in cache_destroy may crash */
845 s->l1_table = NULL;
846 if (s->l2_table_cache) {
847 qcow2_cache_destroy(bs, s->l2_table_cache);
849 if (s->refcount_block_cache) {
850 qcow2_cache_destroy(bs, s->refcount_block_cache);
852 g_free(s->cluster_cache);
853 qemu_vfree(s->cluster_data);
854 return ret;
857 static int qcow2_refresh_limits(BlockDriverState *bs)
859 BDRVQcowState *s = bs->opaque;
861 bs->bl.write_zeroes_alignment = s->cluster_sectors;
863 return 0;
866 static int qcow2_set_key(BlockDriverState *bs, const char *key)
868 BDRVQcowState *s = bs->opaque;
869 uint8_t keybuf[16];
870 int len, i;
872 memset(keybuf, 0, 16);
873 len = strlen(key);
874 if (len > 16)
875 len = 16;
876 /* XXX: we could compress the chars to 7 bits to increase
877 entropy */
878 for(i = 0;i < len;i++) {
879 keybuf[i] = key[i];
881 s->crypt_method = s->crypt_method_header;
883 if (AES_set_encrypt_key(keybuf, 128, &s->aes_encrypt_key) != 0)
884 return -1;
885 if (AES_set_decrypt_key(keybuf, 128, &s->aes_decrypt_key) != 0)
886 return -1;
887 #if 0
888 /* test */
890 uint8_t in[16];
891 uint8_t out[16];
892 uint8_t tmp[16];
893 for(i=0;i<16;i++)
894 in[i] = i;
895 AES_encrypt(in, tmp, &s->aes_encrypt_key);
896 AES_decrypt(tmp, out, &s->aes_decrypt_key);
897 for(i = 0; i < 16; i++)
898 printf(" %02x", tmp[i]);
899 printf("\n");
900 for(i = 0; i < 16; i++)
901 printf(" %02x", out[i]);
902 printf("\n");
904 #endif
905 return 0;
908 /* We have no actual commit/abort logic for qcow2, but we need to write out any
909 * unwritten data if we reopen read-only. */
910 static int qcow2_reopen_prepare(BDRVReopenState *state,
911 BlockReopenQueue *queue, Error **errp)
913 int ret;
915 if ((state->flags & BDRV_O_RDWR) == 0) {
916 ret = bdrv_flush(state->bs);
917 if (ret < 0) {
918 return ret;
921 ret = qcow2_mark_clean(state->bs);
922 if (ret < 0) {
923 return ret;
927 return 0;
930 static int64_t coroutine_fn qcow2_co_get_block_status(BlockDriverState *bs,
931 int64_t sector_num, int nb_sectors, int *pnum)
933 BDRVQcowState *s = bs->opaque;
934 uint64_t cluster_offset;
935 int index_in_cluster, ret;
936 int64_t status = 0;
938 *pnum = nb_sectors;
939 qemu_co_mutex_lock(&s->lock);
940 ret = qcow2_get_cluster_offset(bs, sector_num << 9, pnum, &cluster_offset);
941 qemu_co_mutex_unlock(&s->lock);
942 if (ret < 0) {
943 return ret;
946 if (cluster_offset != 0 && ret != QCOW2_CLUSTER_COMPRESSED &&
947 !s->crypt_method) {
948 index_in_cluster = sector_num & (s->cluster_sectors - 1);
949 cluster_offset |= (index_in_cluster << BDRV_SECTOR_BITS);
950 status |= BDRV_BLOCK_OFFSET_VALID | cluster_offset;
952 if (ret == QCOW2_CLUSTER_ZERO) {
953 status |= BDRV_BLOCK_ZERO;
954 } else if (ret != QCOW2_CLUSTER_UNALLOCATED) {
955 status |= BDRV_BLOCK_DATA;
957 return status;
960 /* handle reading after the end of the backing file */
961 int qcow2_backing_read1(BlockDriverState *bs, QEMUIOVector *qiov,
962 int64_t sector_num, int nb_sectors)
964 int n1;
965 if ((sector_num + nb_sectors) <= bs->total_sectors)
966 return nb_sectors;
967 if (sector_num >= bs->total_sectors)
968 n1 = 0;
969 else
970 n1 = bs->total_sectors - sector_num;
972 qemu_iovec_memset(qiov, 512 * n1, 0, 512 * (nb_sectors - n1));
974 return n1;
977 static coroutine_fn int qcow2_co_readv(BlockDriverState *bs, int64_t sector_num,
978 int remaining_sectors, QEMUIOVector *qiov)
980 BDRVQcowState *s = bs->opaque;
981 int index_in_cluster, n1;
982 int ret;
983 int cur_nr_sectors; /* number of sectors in current iteration */
984 uint64_t cluster_offset = 0;
985 uint64_t bytes_done = 0;
986 QEMUIOVector hd_qiov;
987 uint8_t *cluster_data = NULL;
989 qemu_iovec_init(&hd_qiov, qiov->niov);
991 qemu_co_mutex_lock(&s->lock);
993 while (remaining_sectors != 0) {
995 /* prepare next request */
996 cur_nr_sectors = remaining_sectors;
997 if (s->crypt_method) {
998 cur_nr_sectors = MIN(cur_nr_sectors,
999 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors);
1002 ret = qcow2_get_cluster_offset(bs, sector_num << 9,
1003 &cur_nr_sectors, &cluster_offset);
1004 if (ret < 0) {
1005 goto fail;
1008 index_in_cluster = sector_num & (s->cluster_sectors - 1);
1010 qemu_iovec_reset(&hd_qiov);
1011 qemu_iovec_concat(&hd_qiov, qiov, bytes_done,
1012 cur_nr_sectors * 512);
1014 switch (ret) {
1015 case QCOW2_CLUSTER_UNALLOCATED:
1017 if (bs->backing_hd) {
1018 /* read from the base image */
1019 n1 = qcow2_backing_read1(bs->backing_hd, &hd_qiov,
1020 sector_num, cur_nr_sectors);
1021 if (n1 > 0) {
1022 BLKDBG_EVENT(bs->file, BLKDBG_READ_BACKING_AIO);
1023 qemu_co_mutex_unlock(&s->lock);
1024 ret = bdrv_co_readv(bs->backing_hd, sector_num,
1025 n1, &hd_qiov);
1026 qemu_co_mutex_lock(&s->lock);
1027 if (ret < 0) {
1028 goto fail;
1031 } else {
1032 /* Note: in this case, no need to wait */
1033 qemu_iovec_memset(&hd_qiov, 0, 0, 512 * cur_nr_sectors);
1035 break;
1037 case QCOW2_CLUSTER_ZERO:
1038 qemu_iovec_memset(&hd_qiov, 0, 0, 512 * cur_nr_sectors);
1039 break;
1041 case QCOW2_CLUSTER_COMPRESSED:
1042 /* add AIO support for compressed blocks ? */
1043 ret = qcow2_decompress_cluster(bs, cluster_offset);
1044 if (ret < 0) {
1045 goto fail;
1048 qemu_iovec_from_buf(&hd_qiov, 0,
1049 s->cluster_cache + index_in_cluster * 512,
1050 512 * cur_nr_sectors);
1051 break;
1053 case QCOW2_CLUSTER_NORMAL:
1054 if ((cluster_offset & 511) != 0) {
1055 ret = -EIO;
1056 goto fail;
1059 if (s->crypt_method) {
1061 * For encrypted images, read everything into a temporary
1062 * contiguous buffer on which the AES functions can work.
1064 if (!cluster_data) {
1065 cluster_data =
1066 qemu_blockalign(bs, QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
1069 assert(cur_nr_sectors <=
1070 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors);
1071 qemu_iovec_reset(&hd_qiov);
1072 qemu_iovec_add(&hd_qiov, cluster_data,
1073 512 * cur_nr_sectors);
1076 BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);
1077 qemu_co_mutex_unlock(&s->lock);
1078 ret = bdrv_co_readv(bs->file,
1079 (cluster_offset >> 9) + index_in_cluster,
1080 cur_nr_sectors, &hd_qiov);
1081 qemu_co_mutex_lock(&s->lock);
1082 if (ret < 0) {
1083 goto fail;
1085 if (s->crypt_method) {
1086 qcow2_encrypt_sectors(s, sector_num, cluster_data,
1087 cluster_data, cur_nr_sectors, 0, &s->aes_decrypt_key);
1088 qemu_iovec_from_buf(qiov, bytes_done,
1089 cluster_data, 512 * cur_nr_sectors);
1091 break;
1093 default:
1094 g_assert_not_reached();
1095 ret = -EIO;
1096 goto fail;
1099 remaining_sectors -= cur_nr_sectors;
1100 sector_num += cur_nr_sectors;
1101 bytes_done += cur_nr_sectors * 512;
1103 ret = 0;
1105 fail:
1106 qemu_co_mutex_unlock(&s->lock);
1108 qemu_iovec_destroy(&hd_qiov);
1109 qemu_vfree(cluster_data);
1111 return ret;
1114 static coroutine_fn int qcow2_co_writev(BlockDriverState *bs,
1115 int64_t sector_num,
1116 int remaining_sectors,
1117 QEMUIOVector *qiov)
1119 BDRVQcowState *s = bs->opaque;
1120 int index_in_cluster;
1121 int ret;
1122 int cur_nr_sectors; /* number of sectors in current iteration */
1123 uint64_t cluster_offset;
1124 QEMUIOVector hd_qiov;
1125 uint64_t bytes_done = 0;
1126 uint8_t *cluster_data = NULL;
1127 QCowL2Meta *l2meta = NULL;
1129 trace_qcow2_writev_start_req(qemu_coroutine_self(), sector_num,
1130 remaining_sectors);
1132 qemu_iovec_init(&hd_qiov, qiov->niov);
1134 s->cluster_cache_offset = -1; /* disable compressed cache */
1136 qemu_co_mutex_lock(&s->lock);
1138 while (remaining_sectors != 0) {
1140 l2meta = NULL;
1142 trace_qcow2_writev_start_part(qemu_coroutine_self());
1143 index_in_cluster = sector_num & (s->cluster_sectors - 1);
1144 cur_nr_sectors = remaining_sectors;
1145 if (s->crypt_method &&
1146 cur_nr_sectors >
1147 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors - index_in_cluster) {
1148 cur_nr_sectors =
1149 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors - index_in_cluster;
1152 ret = qcow2_alloc_cluster_offset(bs, sector_num << 9,
1153 &cur_nr_sectors, &cluster_offset, &l2meta);
1154 if (ret < 0) {
1155 goto fail;
1158 assert((cluster_offset & 511) == 0);
1160 qemu_iovec_reset(&hd_qiov);
1161 qemu_iovec_concat(&hd_qiov, qiov, bytes_done,
1162 cur_nr_sectors * 512);
1164 if (s->crypt_method) {
1165 if (!cluster_data) {
1166 cluster_data = qemu_blockalign(bs, QCOW_MAX_CRYPT_CLUSTERS *
1167 s->cluster_size);
1170 assert(hd_qiov.size <=
1171 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
1172 qemu_iovec_to_buf(&hd_qiov, 0, cluster_data, hd_qiov.size);
1174 qcow2_encrypt_sectors(s, sector_num, cluster_data,
1175 cluster_data, cur_nr_sectors, 1, &s->aes_encrypt_key);
1177 qemu_iovec_reset(&hd_qiov);
1178 qemu_iovec_add(&hd_qiov, cluster_data,
1179 cur_nr_sectors * 512);
1182 ret = qcow2_pre_write_overlap_check(bs, 0,
1183 cluster_offset + index_in_cluster * BDRV_SECTOR_SIZE,
1184 cur_nr_sectors * BDRV_SECTOR_SIZE);
1185 if (ret < 0) {
1186 goto fail;
1189 qemu_co_mutex_unlock(&s->lock);
1190 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO);
1191 trace_qcow2_writev_data(qemu_coroutine_self(),
1192 (cluster_offset >> 9) + index_in_cluster);
1193 ret = bdrv_co_writev(bs->file,
1194 (cluster_offset >> 9) + index_in_cluster,
1195 cur_nr_sectors, &hd_qiov);
1196 qemu_co_mutex_lock(&s->lock);
1197 if (ret < 0) {
1198 goto fail;
1201 while (l2meta != NULL) {
1202 QCowL2Meta *next;
1204 ret = qcow2_alloc_cluster_link_l2(bs, l2meta);
1205 if (ret < 0) {
1206 goto fail;
1209 /* Take the request off the list of running requests */
1210 if (l2meta->nb_clusters != 0) {
1211 QLIST_REMOVE(l2meta, next_in_flight);
1214 qemu_co_queue_restart_all(&l2meta->dependent_requests);
1216 next = l2meta->next;
1217 g_free(l2meta);
1218 l2meta = next;
1221 remaining_sectors -= cur_nr_sectors;
1222 sector_num += cur_nr_sectors;
1223 bytes_done += cur_nr_sectors * 512;
1224 trace_qcow2_writev_done_part(qemu_coroutine_self(), cur_nr_sectors);
1226 ret = 0;
1228 fail:
1229 qemu_co_mutex_unlock(&s->lock);
1231 while (l2meta != NULL) {
1232 QCowL2Meta *next;
1234 if (l2meta->nb_clusters != 0) {
1235 QLIST_REMOVE(l2meta, next_in_flight);
1237 qemu_co_queue_restart_all(&l2meta->dependent_requests);
1239 next = l2meta->next;
1240 g_free(l2meta);
1241 l2meta = next;
1244 qemu_iovec_destroy(&hd_qiov);
1245 qemu_vfree(cluster_data);
1246 trace_qcow2_writev_done_req(qemu_coroutine_self(), ret);
1248 return ret;
1251 static void qcow2_close(BlockDriverState *bs)
1253 BDRVQcowState *s = bs->opaque;
1254 g_free(s->l1_table);
1255 /* else pre-write overlap checks in cache_destroy may crash */
1256 s->l1_table = NULL;
1258 if (!(bs->open_flags & BDRV_O_INCOMING)) {
1259 qcow2_cache_flush(bs, s->l2_table_cache);
1260 qcow2_cache_flush(bs, s->refcount_block_cache);
1262 qcow2_mark_clean(bs);
1265 qcow2_cache_destroy(bs, s->l2_table_cache);
1266 qcow2_cache_destroy(bs, s->refcount_block_cache);
1268 g_free(s->unknown_header_fields);
1269 cleanup_unknown_header_ext(bs);
1271 g_free(s->cluster_cache);
1272 qemu_vfree(s->cluster_data);
1273 qcow2_refcount_close(bs);
1274 qcow2_free_snapshots(bs);
1277 static void qcow2_invalidate_cache(BlockDriverState *bs, Error **errp)
1279 BDRVQcowState *s = bs->opaque;
1280 int flags = s->flags;
1281 AES_KEY aes_encrypt_key;
1282 AES_KEY aes_decrypt_key;
1283 uint32_t crypt_method = 0;
1284 QDict *options;
1285 Error *local_err = NULL;
1286 int ret;
1289 * Backing files are read-only which makes all of their metadata immutable,
1290 * that means we don't have to worry about reopening them here.
1293 if (s->crypt_method) {
1294 crypt_method = s->crypt_method;
1295 memcpy(&aes_encrypt_key, &s->aes_encrypt_key, sizeof(aes_encrypt_key));
1296 memcpy(&aes_decrypt_key, &s->aes_decrypt_key, sizeof(aes_decrypt_key));
1299 qcow2_close(bs);
1301 bdrv_invalidate_cache(bs->file, &local_err);
1302 if (local_err) {
1303 error_propagate(errp, local_err);
1304 return;
1307 memset(s, 0, sizeof(BDRVQcowState));
1308 options = qdict_clone_shallow(bs->options);
1310 ret = qcow2_open(bs, options, flags, &local_err);
1311 if (local_err) {
1312 error_setg(errp, "Could not reopen qcow2 layer: %s",
1313 error_get_pretty(local_err));
1314 error_free(local_err);
1315 return;
1316 } else if (ret < 0) {
1317 error_setg_errno(errp, -ret, "Could not reopen qcow2 layer");
1318 return;
1321 QDECREF(options);
1323 if (crypt_method) {
1324 s->crypt_method = crypt_method;
1325 memcpy(&s->aes_encrypt_key, &aes_encrypt_key, sizeof(aes_encrypt_key));
1326 memcpy(&s->aes_decrypt_key, &aes_decrypt_key, sizeof(aes_decrypt_key));
1330 static size_t header_ext_add(char *buf, uint32_t magic, const void *s,
1331 size_t len, size_t buflen)
1333 QCowExtension *ext_backing_fmt = (QCowExtension*) buf;
1334 size_t ext_len = sizeof(QCowExtension) + ((len + 7) & ~7);
1336 if (buflen < ext_len) {
1337 return -ENOSPC;
1340 *ext_backing_fmt = (QCowExtension) {
1341 .magic = cpu_to_be32(magic),
1342 .len = cpu_to_be32(len),
1344 memcpy(buf + sizeof(QCowExtension), s, len);
1346 return ext_len;
1350 * Updates the qcow2 header, including the variable length parts of it, i.e.
1351 * the backing file name and all extensions. qcow2 was not designed to allow
1352 * such changes, so if we run out of space (we can only use the first cluster)
1353 * this function may fail.
1355 * Returns 0 on success, -errno in error cases.
1357 int qcow2_update_header(BlockDriverState *bs)
1359 BDRVQcowState *s = bs->opaque;
1360 QCowHeader *header;
1361 char *buf;
1362 size_t buflen = s->cluster_size;
1363 int ret;
1364 uint64_t total_size;
1365 uint32_t refcount_table_clusters;
1366 size_t header_length;
1367 Qcow2UnknownHeaderExtension *uext;
1369 buf = qemu_blockalign(bs, buflen);
1371 /* Header structure */
1372 header = (QCowHeader*) buf;
1374 if (buflen < sizeof(*header)) {
1375 ret = -ENOSPC;
1376 goto fail;
1379 header_length = sizeof(*header) + s->unknown_header_fields_size;
1380 total_size = bs->total_sectors * BDRV_SECTOR_SIZE;
1381 refcount_table_clusters = s->refcount_table_size >> (s->cluster_bits - 3);
1383 *header = (QCowHeader) {
1384 /* Version 2 fields */
1385 .magic = cpu_to_be32(QCOW_MAGIC),
1386 .version = cpu_to_be32(s->qcow_version),
1387 .backing_file_offset = 0,
1388 .backing_file_size = 0,
1389 .cluster_bits = cpu_to_be32(s->cluster_bits),
1390 .size = cpu_to_be64(total_size),
1391 .crypt_method = cpu_to_be32(s->crypt_method_header),
1392 .l1_size = cpu_to_be32(s->l1_size),
1393 .l1_table_offset = cpu_to_be64(s->l1_table_offset),
1394 .refcount_table_offset = cpu_to_be64(s->refcount_table_offset),
1395 .refcount_table_clusters = cpu_to_be32(refcount_table_clusters),
1396 .nb_snapshots = cpu_to_be32(s->nb_snapshots),
1397 .snapshots_offset = cpu_to_be64(s->snapshots_offset),
1399 /* Version 3 fields */
1400 .incompatible_features = cpu_to_be64(s->incompatible_features),
1401 .compatible_features = cpu_to_be64(s->compatible_features),
1402 .autoclear_features = cpu_to_be64(s->autoclear_features),
1403 .refcount_order = cpu_to_be32(s->refcount_order),
1404 .header_length = cpu_to_be32(header_length),
1407 /* For older versions, write a shorter header */
1408 switch (s->qcow_version) {
1409 case 2:
1410 ret = offsetof(QCowHeader, incompatible_features);
1411 break;
1412 case 3:
1413 ret = sizeof(*header);
1414 break;
1415 default:
1416 ret = -EINVAL;
1417 goto fail;
1420 buf += ret;
1421 buflen -= ret;
1422 memset(buf, 0, buflen);
1424 /* Preserve any unknown field in the header */
1425 if (s->unknown_header_fields_size) {
1426 if (buflen < s->unknown_header_fields_size) {
1427 ret = -ENOSPC;
1428 goto fail;
1431 memcpy(buf, s->unknown_header_fields, s->unknown_header_fields_size);
1432 buf += s->unknown_header_fields_size;
1433 buflen -= s->unknown_header_fields_size;
1436 /* Backing file format header extension */
1437 if (*bs->backing_format) {
1438 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BACKING_FORMAT,
1439 bs->backing_format, strlen(bs->backing_format),
1440 buflen);
1441 if (ret < 0) {
1442 goto fail;
1445 buf += ret;
1446 buflen -= ret;
1449 /* Feature table */
1450 Qcow2Feature features[] = {
1452 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
1453 .bit = QCOW2_INCOMPAT_DIRTY_BITNR,
1454 .name = "dirty bit",
1457 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
1458 .bit = QCOW2_INCOMPAT_CORRUPT_BITNR,
1459 .name = "corrupt bit",
1462 .type = QCOW2_FEAT_TYPE_COMPATIBLE,
1463 .bit = QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR,
1464 .name = "lazy refcounts",
1468 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_FEATURE_TABLE,
1469 features, sizeof(features), buflen);
1470 if (ret < 0) {
1471 goto fail;
1473 buf += ret;
1474 buflen -= ret;
1476 /* Keep unknown header extensions */
1477 QLIST_FOREACH(uext, &s->unknown_header_ext, next) {
1478 ret = header_ext_add(buf, uext->magic, uext->data, uext->len, buflen);
1479 if (ret < 0) {
1480 goto fail;
1483 buf += ret;
1484 buflen -= ret;
1487 /* End of header extensions */
1488 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_END, NULL, 0, buflen);
1489 if (ret < 0) {
1490 goto fail;
1493 buf += ret;
1494 buflen -= ret;
1496 /* Backing file name */
1497 if (*bs->backing_file) {
1498 size_t backing_file_len = strlen(bs->backing_file);
1500 if (buflen < backing_file_len) {
1501 ret = -ENOSPC;
1502 goto fail;
1505 /* Using strncpy is ok here, since buf is not NUL-terminated. */
1506 strncpy(buf, bs->backing_file, buflen);
1508 header->backing_file_offset = cpu_to_be64(buf - ((char*) header));
1509 header->backing_file_size = cpu_to_be32(backing_file_len);
1512 /* Write the new header */
1513 ret = bdrv_pwrite(bs->file, 0, header, s->cluster_size);
1514 if (ret < 0) {
1515 goto fail;
1518 ret = 0;
1519 fail:
1520 qemu_vfree(header);
1521 return ret;
1524 static int qcow2_change_backing_file(BlockDriverState *bs,
1525 const char *backing_file, const char *backing_fmt)
1527 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
1528 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
1530 return qcow2_update_header(bs);
1533 static int preallocate(BlockDriverState *bs)
1535 uint64_t nb_sectors;
1536 uint64_t offset;
1537 uint64_t host_offset = 0;
1538 int num;
1539 int ret;
1540 QCowL2Meta *meta;
1542 nb_sectors = bdrv_getlength(bs) >> BDRV_SECTOR_BITS;
1543 offset = 0;
1545 while (nb_sectors) {
1546 num = MIN(nb_sectors, INT_MAX >> BDRV_SECTOR_BITS);
1547 ret = qcow2_alloc_cluster_offset(bs, offset, &num,
1548 &host_offset, &meta);
1549 if (ret < 0) {
1550 return ret;
1553 while (meta) {
1554 QCowL2Meta *next = meta->next;
1556 ret = qcow2_alloc_cluster_link_l2(bs, meta);
1557 if (ret < 0) {
1558 qcow2_free_any_clusters(bs, meta->alloc_offset,
1559 meta->nb_clusters, QCOW2_DISCARD_NEVER);
1560 return ret;
1563 /* There are no dependent requests, but we need to remove our
1564 * request from the list of in-flight requests */
1565 QLIST_REMOVE(meta, next_in_flight);
1567 g_free(meta);
1568 meta = next;
1571 /* TODO Preallocate data if requested */
1573 nb_sectors -= num;
1574 offset += num << BDRV_SECTOR_BITS;
1578 * It is expected that the image file is large enough to actually contain
1579 * all of the allocated clusters (otherwise we get failing reads after
1580 * EOF). Extend the image to the last allocated sector.
1582 if (host_offset != 0) {
1583 uint8_t buf[BDRV_SECTOR_SIZE];
1584 memset(buf, 0, BDRV_SECTOR_SIZE);
1585 ret = bdrv_write(bs->file, (host_offset >> BDRV_SECTOR_BITS) + num - 1,
1586 buf, 1);
1587 if (ret < 0) {
1588 return ret;
1592 return 0;
1595 static int qcow2_create2(const char *filename, int64_t total_size,
1596 const char *backing_file, const char *backing_format,
1597 int flags, size_t cluster_size, int prealloc,
1598 QEMUOptionParameter *options, int version,
1599 Error **errp)
1601 /* Calculate cluster_bits */
1602 int cluster_bits;
1603 cluster_bits = ffs(cluster_size) - 1;
1604 if (cluster_bits < MIN_CLUSTER_BITS || cluster_bits > MAX_CLUSTER_BITS ||
1605 (1 << cluster_bits) != cluster_size)
1607 error_setg(errp, "Cluster size must be a power of two between %d and "
1608 "%dk", 1 << MIN_CLUSTER_BITS, 1 << (MAX_CLUSTER_BITS - 10));
1609 return -EINVAL;
1613 * Open the image file and write a minimal qcow2 header.
1615 * We keep things simple and start with a zero-sized image. We also
1616 * do without refcount blocks or a L1 table for now. We'll fix the
1617 * inconsistency later.
1619 * We do need a refcount table because growing the refcount table means
1620 * allocating two new refcount blocks - the seconds of which would be at
1621 * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
1622 * size for any qcow2 image.
1624 BlockDriverState* bs;
1625 QCowHeader *header;
1626 uint64_t* refcount_table;
1627 Error *local_err = NULL;
1628 int ret;
1630 ret = bdrv_create_file(filename, options, &local_err);
1631 if (ret < 0) {
1632 error_propagate(errp, local_err);
1633 return ret;
1636 bs = NULL;
1637 ret = bdrv_open(&bs, filename, NULL, NULL, BDRV_O_RDWR | BDRV_O_PROTOCOL,
1638 NULL, &local_err);
1639 if (ret < 0) {
1640 error_propagate(errp, local_err);
1641 return ret;
1644 /* Write the header */
1645 QEMU_BUILD_BUG_ON((1 << MIN_CLUSTER_BITS) < sizeof(*header));
1646 header = g_malloc0(cluster_size);
1647 *header = (QCowHeader) {
1648 .magic = cpu_to_be32(QCOW_MAGIC),
1649 .version = cpu_to_be32(version),
1650 .cluster_bits = cpu_to_be32(cluster_bits),
1651 .size = cpu_to_be64(0),
1652 .l1_table_offset = cpu_to_be64(0),
1653 .l1_size = cpu_to_be32(0),
1654 .refcount_table_offset = cpu_to_be64(cluster_size),
1655 .refcount_table_clusters = cpu_to_be32(1),
1656 .refcount_order = cpu_to_be32(3 + REFCOUNT_SHIFT),
1657 .header_length = cpu_to_be32(sizeof(*header)),
1660 if (flags & BLOCK_FLAG_ENCRYPT) {
1661 header->crypt_method = cpu_to_be32(QCOW_CRYPT_AES);
1662 } else {
1663 header->crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
1666 if (flags & BLOCK_FLAG_LAZY_REFCOUNTS) {
1667 header->compatible_features |=
1668 cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS);
1671 ret = bdrv_pwrite(bs, 0, header, cluster_size);
1672 g_free(header);
1673 if (ret < 0) {
1674 error_setg_errno(errp, -ret, "Could not write qcow2 header");
1675 goto out;
1678 /* Write a refcount table with one refcount block */
1679 refcount_table = g_malloc0(2 * cluster_size);
1680 refcount_table[0] = cpu_to_be64(2 * cluster_size);
1681 ret = bdrv_pwrite(bs, cluster_size, refcount_table, 2 * cluster_size);
1682 g_free(refcount_table);
1684 if (ret < 0) {
1685 error_setg_errno(errp, -ret, "Could not write refcount table");
1686 goto out;
1689 bdrv_unref(bs);
1690 bs = NULL;
1693 * And now open the image and make it consistent first (i.e. increase the
1694 * refcount of the cluster that is occupied by the header and the refcount
1695 * table)
1697 BlockDriver* drv = bdrv_find_format("qcow2");
1698 assert(drv != NULL);
1699 ret = bdrv_open(&bs, filename, NULL, NULL,
1700 BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_NO_FLUSH, drv, &local_err);
1701 if (ret < 0) {
1702 error_propagate(errp, local_err);
1703 goto out;
1706 ret = qcow2_alloc_clusters(bs, 3 * cluster_size);
1707 if (ret < 0) {
1708 error_setg_errno(errp, -ret, "Could not allocate clusters for qcow2 "
1709 "header and refcount table");
1710 goto out;
1712 } else if (ret != 0) {
1713 error_report("Huh, first cluster in empty image is already in use?");
1714 abort();
1717 /* Okay, now that we have a valid image, let's give it the right size */
1718 ret = bdrv_truncate(bs, total_size * BDRV_SECTOR_SIZE);
1719 if (ret < 0) {
1720 error_setg_errno(errp, -ret, "Could not resize image");
1721 goto out;
1724 /* Want a backing file? There you go.*/
1725 if (backing_file) {
1726 ret = bdrv_change_backing_file(bs, backing_file, backing_format);
1727 if (ret < 0) {
1728 error_setg_errno(errp, -ret, "Could not assign backing file '%s' "
1729 "with format '%s'", backing_file, backing_format);
1730 goto out;
1734 /* And if we're supposed to preallocate metadata, do that now */
1735 if (prealloc) {
1736 BDRVQcowState *s = bs->opaque;
1737 qemu_co_mutex_lock(&s->lock);
1738 ret = preallocate(bs);
1739 qemu_co_mutex_unlock(&s->lock);
1740 if (ret < 0) {
1741 error_setg_errno(errp, -ret, "Could not preallocate metadata");
1742 goto out;
1746 bdrv_unref(bs);
1747 bs = NULL;
1749 /* Reopen the image without BDRV_O_NO_FLUSH to flush it before returning */
1750 ret = bdrv_open(&bs, filename, NULL, NULL,
1751 BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_NO_BACKING,
1752 drv, &local_err);
1753 if (local_err) {
1754 error_propagate(errp, local_err);
1755 goto out;
1758 ret = 0;
1759 out:
1760 if (bs) {
1761 bdrv_unref(bs);
1763 return ret;
1766 static int qcow2_create(const char *filename, QEMUOptionParameter *options,
1767 Error **errp)
1769 const char *backing_file = NULL;
1770 const char *backing_fmt = NULL;
1771 uint64_t sectors = 0;
1772 int flags = 0;
1773 size_t cluster_size = DEFAULT_CLUSTER_SIZE;
1774 int prealloc = 0;
1775 int version = 3;
1776 Error *local_err = NULL;
1777 int ret;
1779 /* Read out options */
1780 while (options && options->name) {
1781 if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
1782 sectors = options->value.n / 512;
1783 } else if (!strcmp(options->name, BLOCK_OPT_BACKING_FILE)) {
1784 backing_file = options->value.s;
1785 } else if (!strcmp(options->name, BLOCK_OPT_BACKING_FMT)) {
1786 backing_fmt = options->value.s;
1787 } else if (!strcmp(options->name, BLOCK_OPT_ENCRYPT)) {
1788 flags |= options->value.n ? BLOCK_FLAG_ENCRYPT : 0;
1789 } else if (!strcmp(options->name, BLOCK_OPT_CLUSTER_SIZE)) {
1790 if (options->value.n) {
1791 cluster_size = options->value.n;
1793 } else if (!strcmp(options->name, BLOCK_OPT_PREALLOC)) {
1794 if (!options->value.s || !strcmp(options->value.s, "off")) {
1795 prealloc = 0;
1796 } else if (!strcmp(options->value.s, "metadata")) {
1797 prealloc = 1;
1798 } else {
1799 error_setg(errp, "Invalid preallocation mode: '%s'",
1800 options->value.s);
1801 return -EINVAL;
1803 } else if (!strcmp(options->name, BLOCK_OPT_COMPAT_LEVEL)) {
1804 if (!options->value.s) {
1805 /* keep the default */
1806 } else if (!strcmp(options->value.s, "0.10")) {
1807 version = 2;
1808 } else if (!strcmp(options->value.s, "1.1")) {
1809 version = 3;
1810 } else {
1811 error_setg(errp, "Invalid compatibility level: '%s'",
1812 options->value.s);
1813 return -EINVAL;
1815 } else if (!strcmp(options->name, BLOCK_OPT_LAZY_REFCOUNTS)) {
1816 flags |= options->value.n ? BLOCK_FLAG_LAZY_REFCOUNTS : 0;
1818 options++;
1821 if (backing_file && prealloc) {
1822 error_setg(errp, "Backing file and preallocation cannot be used at "
1823 "the same time");
1824 return -EINVAL;
1827 if (version < 3 && (flags & BLOCK_FLAG_LAZY_REFCOUNTS)) {
1828 error_setg(errp, "Lazy refcounts only supported with compatibility "
1829 "level 1.1 and above (use compat=1.1 or greater)");
1830 return -EINVAL;
1833 ret = qcow2_create2(filename, sectors, backing_file, backing_fmt, flags,
1834 cluster_size, prealloc, options, version, &local_err);
1835 if (local_err) {
1836 error_propagate(errp, local_err);
1838 return ret;
1841 static coroutine_fn int qcow2_co_write_zeroes(BlockDriverState *bs,
1842 int64_t sector_num, int nb_sectors, BdrvRequestFlags flags)
1844 int ret;
1845 BDRVQcowState *s = bs->opaque;
1847 /* Emulate misaligned zero writes */
1848 if (sector_num % s->cluster_sectors || nb_sectors % s->cluster_sectors) {
1849 return -ENOTSUP;
1852 /* Whatever is left can use real zero clusters */
1853 qemu_co_mutex_lock(&s->lock);
1854 ret = qcow2_zero_clusters(bs, sector_num << BDRV_SECTOR_BITS,
1855 nb_sectors);
1856 qemu_co_mutex_unlock(&s->lock);
1858 return ret;
1861 static coroutine_fn int qcow2_co_discard(BlockDriverState *bs,
1862 int64_t sector_num, int nb_sectors)
1864 int ret;
1865 BDRVQcowState *s = bs->opaque;
1867 qemu_co_mutex_lock(&s->lock);
1868 ret = qcow2_discard_clusters(bs, sector_num << BDRV_SECTOR_BITS,
1869 nb_sectors, QCOW2_DISCARD_REQUEST);
1870 qemu_co_mutex_unlock(&s->lock);
1871 return ret;
1874 static int qcow2_truncate(BlockDriverState *bs, int64_t offset)
1876 BDRVQcowState *s = bs->opaque;
1877 int64_t new_l1_size;
1878 int ret;
1880 if (offset & 511) {
1881 error_report("The new size must be a multiple of 512");
1882 return -EINVAL;
1885 /* cannot proceed if image has snapshots */
1886 if (s->nb_snapshots) {
1887 error_report("Can't resize an image which has snapshots");
1888 return -ENOTSUP;
1891 /* shrinking is currently not supported */
1892 if (offset < bs->total_sectors * 512) {
1893 error_report("qcow2 doesn't support shrinking images yet");
1894 return -ENOTSUP;
1897 new_l1_size = size_to_l1(s, offset);
1898 ret = qcow2_grow_l1_table(bs, new_l1_size, true);
1899 if (ret < 0) {
1900 return ret;
1903 /* write updated header.size */
1904 offset = cpu_to_be64(offset);
1905 ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, size),
1906 &offset, sizeof(uint64_t));
1907 if (ret < 0) {
1908 return ret;
1911 s->l1_vm_state_index = new_l1_size;
1912 return 0;
1915 /* XXX: put compressed sectors first, then all the cluster aligned
1916 tables to avoid losing bytes in alignment */
1917 static int qcow2_write_compressed(BlockDriverState *bs, int64_t sector_num,
1918 const uint8_t *buf, int nb_sectors)
1920 BDRVQcowState *s = bs->opaque;
1921 z_stream strm;
1922 int ret, out_len;
1923 uint8_t *out_buf;
1924 uint64_t cluster_offset;
1926 if (nb_sectors == 0) {
1927 /* align end of file to a sector boundary to ease reading with
1928 sector based I/Os */
1929 cluster_offset = bdrv_getlength(bs->file);
1930 cluster_offset = (cluster_offset + 511) & ~511;
1931 bdrv_truncate(bs->file, cluster_offset);
1932 return 0;
1935 if (nb_sectors != s->cluster_sectors) {
1936 ret = -EINVAL;
1938 /* Zero-pad last write if image size is not cluster aligned */
1939 if (sector_num + nb_sectors == bs->total_sectors &&
1940 nb_sectors < s->cluster_sectors) {
1941 uint8_t *pad_buf = qemu_blockalign(bs, s->cluster_size);
1942 memset(pad_buf, 0, s->cluster_size);
1943 memcpy(pad_buf, buf, nb_sectors * BDRV_SECTOR_SIZE);
1944 ret = qcow2_write_compressed(bs, sector_num,
1945 pad_buf, s->cluster_sectors);
1946 qemu_vfree(pad_buf);
1948 return ret;
1951 out_buf = g_malloc(s->cluster_size + (s->cluster_size / 1000) + 128);
1953 /* best compression, small window, no zlib header */
1954 memset(&strm, 0, sizeof(strm));
1955 ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
1956 Z_DEFLATED, -12,
1957 9, Z_DEFAULT_STRATEGY);
1958 if (ret != 0) {
1959 ret = -EINVAL;
1960 goto fail;
1963 strm.avail_in = s->cluster_size;
1964 strm.next_in = (uint8_t *)buf;
1965 strm.avail_out = s->cluster_size;
1966 strm.next_out = out_buf;
1968 ret = deflate(&strm, Z_FINISH);
1969 if (ret != Z_STREAM_END && ret != Z_OK) {
1970 deflateEnd(&strm);
1971 ret = -EINVAL;
1972 goto fail;
1974 out_len = strm.next_out - out_buf;
1976 deflateEnd(&strm);
1978 if (ret != Z_STREAM_END || out_len >= s->cluster_size) {
1979 /* could not compress: write normal cluster */
1980 ret = bdrv_write(bs, sector_num, buf, s->cluster_sectors);
1981 if (ret < 0) {
1982 goto fail;
1984 } else {
1985 cluster_offset = qcow2_alloc_compressed_cluster_offset(bs,
1986 sector_num << 9, out_len);
1987 if (!cluster_offset) {
1988 ret = -EIO;
1989 goto fail;
1991 cluster_offset &= s->cluster_offset_mask;
1993 ret = qcow2_pre_write_overlap_check(bs, 0, cluster_offset, out_len);
1994 if (ret < 0) {
1995 goto fail;
1998 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_COMPRESSED);
1999 ret = bdrv_pwrite(bs->file, cluster_offset, out_buf, out_len);
2000 if (ret < 0) {
2001 goto fail;
2005 ret = 0;
2006 fail:
2007 g_free(out_buf);
2008 return ret;
2011 static coroutine_fn int qcow2_co_flush_to_os(BlockDriverState *bs)
2013 BDRVQcowState *s = bs->opaque;
2014 int ret;
2016 qemu_co_mutex_lock(&s->lock);
2017 ret = qcow2_cache_flush(bs, s->l2_table_cache);
2018 if (ret < 0) {
2019 qemu_co_mutex_unlock(&s->lock);
2020 return ret;
2023 if (qcow2_need_accurate_refcounts(s)) {
2024 ret = qcow2_cache_flush(bs, s->refcount_block_cache);
2025 if (ret < 0) {
2026 qemu_co_mutex_unlock(&s->lock);
2027 return ret;
2030 qemu_co_mutex_unlock(&s->lock);
2032 return 0;
2035 static int qcow2_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
2037 BDRVQcowState *s = bs->opaque;
2038 bdi->unallocated_blocks_are_zero = true;
2039 bdi->can_write_zeroes_with_unmap = (s->qcow_version >= 3);
2040 bdi->cluster_size = s->cluster_size;
2041 bdi->vm_state_offset = qcow2_vm_state_offset(s);
2042 return 0;
2045 static ImageInfoSpecific *qcow2_get_specific_info(BlockDriverState *bs)
2047 BDRVQcowState *s = bs->opaque;
2048 ImageInfoSpecific *spec_info = g_new(ImageInfoSpecific, 1);
2050 *spec_info = (ImageInfoSpecific){
2051 .kind = IMAGE_INFO_SPECIFIC_KIND_QCOW2,
2053 .qcow2 = g_new(ImageInfoSpecificQCow2, 1),
2056 if (s->qcow_version == 2) {
2057 *spec_info->qcow2 = (ImageInfoSpecificQCow2){
2058 .compat = g_strdup("0.10"),
2060 } else if (s->qcow_version == 3) {
2061 *spec_info->qcow2 = (ImageInfoSpecificQCow2){
2062 .compat = g_strdup("1.1"),
2063 .lazy_refcounts = s->compatible_features &
2064 QCOW2_COMPAT_LAZY_REFCOUNTS,
2065 .has_lazy_refcounts = true,
2069 return spec_info;
2072 #if 0
2073 static void dump_refcounts(BlockDriverState *bs)
2075 BDRVQcowState *s = bs->opaque;
2076 int64_t nb_clusters, k, k1, size;
2077 int refcount;
2079 size = bdrv_getlength(bs->file);
2080 nb_clusters = size_to_clusters(s, size);
2081 for(k = 0; k < nb_clusters;) {
2082 k1 = k;
2083 refcount = get_refcount(bs, k);
2084 k++;
2085 while (k < nb_clusters && get_refcount(bs, k) == refcount)
2086 k++;
2087 printf("%" PRId64 ": refcount=%d nb=%" PRId64 "\n", k, refcount,
2088 k - k1);
2091 #endif
2093 static int qcow2_save_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
2094 int64_t pos)
2096 BDRVQcowState *s = bs->opaque;
2097 int64_t total_sectors = bs->total_sectors;
2098 int growable = bs->growable;
2099 bool zero_beyond_eof = bs->zero_beyond_eof;
2100 int ret;
2102 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_SAVE);
2103 bs->growable = 1;
2104 bs->zero_beyond_eof = false;
2105 ret = bdrv_pwritev(bs, qcow2_vm_state_offset(s) + pos, qiov);
2106 bs->growable = growable;
2107 bs->zero_beyond_eof = zero_beyond_eof;
2109 /* bdrv_co_do_writev will have increased the total_sectors value to include
2110 * the VM state - the VM state is however not an actual part of the block
2111 * device, therefore, we need to restore the old value. */
2112 bs->total_sectors = total_sectors;
2114 return ret;
2117 static int qcow2_load_vmstate(BlockDriverState *bs, uint8_t *buf,
2118 int64_t pos, int size)
2120 BDRVQcowState *s = bs->opaque;
2121 int growable = bs->growable;
2122 bool zero_beyond_eof = bs->zero_beyond_eof;
2123 int ret;
2125 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_LOAD);
2126 bs->growable = 1;
2127 bs->zero_beyond_eof = false;
2128 ret = bdrv_pread(bs, qcow2_vm_state_offset(s) + pos, buf, size);
2129 bs->growable = growable;
2130 bs->zero_beyond_eof = zero_beyond_eof;
2132 return ret;
2136 * Downgrades an image's version. To achieve this, any incompatible features
2137 * have to be removed.
2139 static int qcow2_downgrade(BlockDriverState *bs, int target_version)
2141 BDRVQcowState *s = bs->opaque;
2142 int current_version = s->qcow_version;
2143 int ret;
2145 if (target_version == current_version) {
2146 return 0;
2147 } else if (target_version > current_version) {
2148 return -EINVAL;
2149 } else if (target_version != 2) {
2150 return -EINVAL;
2153 if (s->refcount_order != 4) {
2154 /* we would have to convert the image to a refcount_order == 4 image
2155 * here; however, since qemu (at the time of writing this) does not
2156 * support anything different than 4 anyway, there is no point in doing
2157 * so right now; however, we should error out (if qemu supports this in
2158 * the future and this code has not been adapted) */
2159 error_report("qcow2_downgrade: Image refcount orders other than 4 are "
2160 "currently not supported.");
2161 return -ENOTSUP;
2164 /* clear incompatible features */
2165 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
2166 ret = qcow2_mark_clean(bs);
2167 if (ret < 0) {
2168 return ret;
2172 /* with QCOW2_INCOMPAT_CORRUPT, it is pretty much impossible to get here in
2173 * the first place; if that happens nonetheless, returning -ENOTSUP is the
2174 * best thing to do anyway */
2176 if (s->incompatible_features) {
2177 return -ENOTSUP;
2180 /* since we can ignore compatible features, we can set them to 0 as well */
2181 s->compatible_features = 0;
2182 /* if lazy refcounts have been used, they have already been fixed through
2183 * clearing the dirty flag */
2185 /* clearing autoclear features is trivial */
2186 s->autoclear_features = 0;
2188 ret = qcow2_expand_zero_clusters(bs);
2189 if (ret < 0) {
2190 return ret;
2193 s->qcow_version = target_version;
2194 ret = qcow2_update_header(bs);
2195 if (ret < 0) {
2196 s->qcow_version = current_version;
2197 return ret;
2199 return 0;
2202 static int qcow2_amend_options(BlockDriverState *bs,
2203 QEMUOptionParameter *options)
2205 BDRVQcowState *s = bs->opaque;
2206 int old_version = s->qcow_version, new_version = old_version;
2207 uint64_t new_size = 0;
2208 const char *backing_file = NULL, *backing_format = NULL;
2209 bool lazy_refcounts = s->use_lazy_refcounts;
2210 int ret;
2211 int i;
2213 for (i = 0; options[i].name; i++)
2215 if (!options[i].assigned) {
2216 /* only change explicitly defined options */
2217 continue;
2220 if (!strcmp(options[i].name, "compat")) {
2221 if (!options[i].value.s) {
2222 /* preserve default */
2223 } else if (!strcmp(options[i].value.s, "0.10")) {
2224 new_version = 2;
2225 } else if (!strcmp(options[i].value.s, "1.1")) {
2226 new_version = 3;
2227 } else {
2228 fprintf(stderr, "Unknown compatibility level %s.\n",
2229 options[i].value.s);
2230 return -EINVAL;
2232 } else if (!strcmp(options[i].name, "preallocation")) {
2233 fprintf(stderr, "Cannot change preallocation mode.\n");
2234 return -ENOTSUP;
2235 } else if (!strcmp(options[i].name, "size")) {
2236 new_size = options[i].value.n;
2237 } else if (!strcmp(options[i].name, "backing_file")) {
2238 backing_file = options[i].value.s;
2239 } else if (!strcmp(options[i].name, "backing_fmt")) {
2240 backing_format = options[i].value.s;
2241 } else if (!strcmp(options[i].name, "encryption")) {
2242 if ((options[i].value.n != !!s->crypt_method)) {
2243 fprintf(stderr, "Changing the encryption flag is not "
2244 "supported.\n");
2245 return -ENOTSUP;
2247 } else if (!strcmp(options[i].name, "cluster_size")) {
2248 if (options[i].value.n != s->cluster_size) {
2249 fprintf(stderr, "Changing the cluster size is not "
2250 "supported.\n");
2251 return -ENOTSUP;
2253 } else if (!strcmp(options[i].name, "lazy_refcounts")) {
2254 lazy_refcounts = options[i].value.n;
2255 } else {
2256 /* if this assertion fails, this probably means a new option was
2257 * added without having it covered here */
2258 assert(false);
2262 if (new_version != old_version) {
2263 if (new_version > old_version) {
2264 /* Upgrade */
2265 s->qcow_version = new_version;
2266 ret = qcow2_update_header(bs);
2267 if (ret < 0) {
2268 s->qcow_version = old_version;
2269 return ret;
2271 } else {
2272 ret = qcow2_downgrade(bs, new_version);
2273 if (ret < 0) {
2274 return ret;
2279 if (backing_file || backing_format) {
2280 ret = qcow2_change_backing_file(bs, backing_file ?: bs->backing_file,
2281 backing_format ?: bs->backing_format);
2282 if (ret < 0) {
2283 return ret;
2287 if (s->use_lazy_refcounts != lazy_refcounts) {
2288 if (lazy_refcounts) {
2289 if (s->qcow_version < 3) {
2290 fprintf(stderr, "Lazy refcounts only supported with compatibility "
2291 "level 1.1 and above (use compat=1.1 or greater)\n");
2292 return -EINVAL;
2294 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
2295 ret = qcow2_update_header(bs);
2296 if (ret < 0) {
2297 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
2298 return ret;
2300 s->use_lazy_refcounts = true;
2301 } else {
2302 /* make image clean first */
2303 ret = qcow2_mark_clean(bs);
2304 if (ret < 0) {
2305 return ret;
2307 /* now disallow lazy refcounts */
2308 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
2309 ret = qcow2_update_header(bs);
2310 if (ret < 0) {
2311 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
2312 return ret;
2314 s->use_lazy_refcounts = false;
2318 if (new_size) {
2319 ret = bdrv_truncate(bs, new_size);
2320 if (ret < 0) {
2321 return ret;
2325 return 0;
2328 static QEMUOptionParameter qcow2_create_options[] = {
2330 .name = BLOCK_OPT_SIZE,
2331 .type = OPT_SIZE,
2332 .help = "Virtual disk size"
2335 .name = BLOCK_OPT_COMPAT_LEVEL,
2336 .type = OPT_STRING,
2337 .help = "Compatibility level (0.10 or 1.1)"
2340 .name = BLOCK_OPT_BACKING_FILE,
2341 .type = OPT_STRING,
2342 .help = "File name of a base image"
2345 .name = BLOCK_OPT_BACKING_FMT,
2346 .type = OPT_STRING,
2347 .help = "Image format of the base image"
2350 .name = BLOCK_OPT_ENCRYPT,
2351 .type = OPT_FLAG,
2352 .help = "Encrypt the image"
2355 .name = BLOCK_OPT_CLUSTER_SIZE,
2356 .type = OPT_SIZE,
2357 .help = "qcow2 cluster size",
2358 .value = { .n = DEFAULT_CLUSTER_SIZE },
2361 .name = BLOCK_OPT_PREALLOC,
2362 .type = OPT_STRING,
2363 .help = "Preallocation mode (allowed values: off, metadata)"
2366 .name = BLOCK_OPT_LAZY_REFCOUNTS,
2367 .type = OPT_FLAG,
2368 .help = "Postpone refcount updates",
2370 { NULL }
2373 static BlockDriver bdrv_qcow2 = {
2374 .format_name = "qcow2",
2375 .instance_size = sizeof(BDRVQcowState),
2376 .bdrv_probe = qcow2_probe,
2377 .bdrv_open = qcow2_open,
2378 .bdrv_close = qcow2_close,
2379 .bdrv_reopen_prepare = qcow2_reopen_prepare,
2380 .bdrv_create = qcow2_create,
2381 .bdrv_has_zero_init = bdrv_has_zero_init_1,
2382 .bdrv_co_get_block_status = qcow2_co_get_block_status,
2383 .bdrv_set_key = qcow2_set_key,
2385 .bdrv_co_readv = qcow2_co_readv,
2386 .bdrv_co_writev = qcow2_co_writev,
2387 .bdrv_co_flush_to_os = qcow2_co_flush_to_os,
2389 .bdrv_co_write_zeroes = qcow2_co_write_zeroes,
2390 .bdrv_co_discard = qcow2_co_discard,
2391 .bdrv_truncate = qcow2_truncate,
2392 .bdrv_write_compressed = qcow2_write_compressed,
2394 .bdrv_snapshot_create = qcow2_snapshot_create,
2395 .bdrv_snapshot_goto = qcow2_snapshot_goto,
2396 .bdrv_snapshot_delete = qcow2_snapshot_delete,
2397 .bdrv_snapshot_list = qcow2_snapshot_list,
2398 .bdrv_snapshot_load_tmp = qcow2_snapshot_load_tmp,
2399 .bdrv_get_info = qcow2_get_info,
2400 .bdrv_get_specific_info = qcow2_get_specific_info,
2402 .bdrv_save_vmstate = qcow2_save_vmstate,
2403 .bdrv_load_vmstate = qcow2_load_vmstate,
2405 .bdrv_change_backing_file = qcow2_change_backing_file,
2407 .bdrv_refresh_limits = qcow2_refresh_limits,
2408 .bdrv_invalidate_cache = qcow2_invalidate_cache,
2410 .create_options = qcow2_create_options,
2411 .bdrv_check = qcow2_check,
2412 .bdrv_amend_options = qcow2_amend_options,
2415 static void bdrv_qcow2_init(void)
2417 bdrv_register(&bdrv_qcow2);
2420 block_init(bdrv_qcow2_init);