qcow2: Make qiov match request size until backing file EOF
[qemu/ar7.git] / block / qcow2.c
blobb0faa6917baf816c6d78a0242e70f83cca6d8f31
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"
34 #include "qemu/option_int.h"
37 Differences with QCOW:
39 - Support for multiple incremental snapshots.
40 - Memory management by reference counts.
41 - Clusters which have a reference count of one have the bit
42 QCOW_OFLAG_COPIED to optimize write performance.
43 - Size of compressed clusters is stored in sectors to reduce bit usage
44 in the cluster offsets.
45 - Support for storing additional data (such as the VM state) in the
46 snapshots.
47 - If a backing store is used, the cluster size is not constrained
48 (could be backported to QCOW).
49 - L2 tables have always a size of one cluster.
53 typedef struct {
54 uint32_t magic;
55 uint32_t len;
56 } QEMU_PACKED QCowExtension;
58 #define QCOW2_EXT_MAGIC_END 0
59 #define QCOW2_EXT_MAGIC_BACKING_FORMAT 0xE2792ACA
60 #define QCOW2_EXT_MAGIC_FEATURE_TABLE 0x6803f857
62 static int qcow2_probe(const uint8_t *buf, int buf_size, const char *filename)
64 const QCowHeader *cow_header = (const void *)buf;
66 if (buf_size >= sizeof(QCowHeader) &&
67 be32_to_cpu(cow_header->magic) == QCOW_MAGIC &&
68 be32_to_cpu(cow_header->version) >= 2)
69 return 100;
70 else
71 return 0;
75 /*
76 * read qcow2 extension and fill bs
77 * start reading from start_offset
78 * finish reading upon magic of value 0 or when end_offset reached
79 * unknown magic is skipped (future extension this version knows nothing about)
80 * return 0 upon success, non-0 otherwise
82 static int qcow2_read_extensions(BlockDriverState *bs, uint64_t start_offset,
83 uint64_t end_offset, void **p_feature_table,
84 Error **errp)
86 BDRVQcowState *s = bs->opaque;
87 QCowExtension ext;
88 uint64_t offset;
89 int ret;
91 #ifdef DEBUG_EXT
92 printf("qcow2_read_extensions: start=%ld end=%ld\n", start_offset, end_offset);
93 #endif
94 offset = start_offset;
95 while (offset < end_offset) {
97 #ifdef DEBUG_EXT
98 /* Sanity check */
99 if (offset > s->cluster_size)
100 printf("qcow2_read_extension: suspicious offset %lu\n", offset);
102 printf("attempting to read extended header in offset %lu\n", offset);
103 #endif
105 ret = bdrv_pread(bs->file, offset, &ext, sizeof(ext));
106 if (ret < 0) {
107 error_setg_errno(errp, -ret, "qcow2_read_extension: ERROR: "
108 "pread fail from offset %" PRIu64, offset);
109 return 1;
111 be32_to_cpus(&ext.magic);
112 be32_to_cpus(&ext.len);
113 offset += sizeof(ext);
114 #ifdef DEBUG_EXT
115 printf("ext.magic = 0x%x\n", ext.magic);
116 #endif
117 if (ext.len > end_offset - offset) {
118 error_setg(errp, "Header extension too large");
119 return -EINVAL;
122 switch (ext.magic) {
123 case QCOW2_EXT_MAGIC_END:
124 return 0;
126 case QCOW2_EXT_MAGIC_BACKING_FORMAT:
127 if (ext.len >= sizeof(bs->backing_format)) {
128 error_setg(errp, "ERROR: ext_backing_format: len=%" PRIu32
129 " too large (>=%zu)", ext.len,
130 sizeof(bs->backing_format));
131 return 2;
133 ret = bdrv_pread(bs->file, offset, bs->backing_format, ext.len);
134 if (ret < 0) {
135 error_setg_errno(errp, -ret, "ERROR: ext_backing_format: "
136 "Could not read format name");
137 return 3;
139 bs->backing_format[ext.len] = '\0';
140 #ifdef DEBUG_EXT
141 printf("Qcow2: Got format extension %s\n", bs->backing_format);
142 #endif
143 break;
145 case QCOW2_EXT_MAGIC_FEATURE_TABLE:
146 if (p_feature_table != NULL) {
147 void* feature_table = g_malloc0(ext.len + 2 * sizeof(Qcow2Feature));
148 ret = bdrv_pread(bs->file, offset , feature_table, ext.len);
149 if (ret < 0) {
150 error_setg_errno(errp, -ret, "ERROR: ext_feature_table: "
151 "Could not read table");
152 return ret;
155 *p_feature_table = feature_table;
157 break;
159 default:
160 /* unknown magic - save it in case we need to rewrite the header */
162 Qcow2UnknownHeaderExtension *uext;
164 uext = g_malloc0(sizeof(*uext) + ext.len);
165 uext->magic = ext.magic;
166 uext->len = ext.len;
167 QLIST_INSERT_HEAD(&s->unknown_header_ext, uext, next);
169 ret = bdrv_pread(bs->file, offset , uext->data, uext->len);
170 if (ret < 0) {
171 error_setg_errno(errp, -ret, "ERROR: unknown extension: "
172 "Could not read data");
173 return ret;
176 break;
179 offset += ((ext.len + 7) & ~7);
182 return 0;
185 static void cleanup_unknown_header_ext(BlockDriverState *bs)
187 BDRVQcowState *s = bs->opaque;
188 Qcow2UnknownHeaderExtension *uext, *next;
190 QLIST_FOREACH_SAFE(uext, &s->unknown_header_ext, next, next) {
191 QLIST_REMOVE(uext, next);
192 g_free(uext);
196 static void GCC_FMT_ATTR(3, 4) report_unsupported(BlockDriverState *bs,
197 Error **errp, const char *fmt, ...)
199 char msg[64];
200 va_list ap;
202 va_start(ap, fmt);
203 vsnprintf(msg, sizeof(msg), fmt, ap);
204 va_end(ap);
206 error_set(errp, QERR_UNKNOWN_BLOCK_FORMAT_FEATURE, bs->device_name, "qcow2",
207 msg);
210 static void report_unsupported_feature(BlockDriverState *bs,
211 Error **errp, Qcow2Feature *table, uint64_t mask)
213 while (table && table->name[0] != '\0') {
214 if (table->type == QCOW2_FEAT_TYPE_INCOMPATIBLE) {
215 if (mask & (1 << table->bit)) {
216 report_unsupported(bs, errp, "%.46s", table->name);
217 mask &= ~(1 << table->bit);
220 table++;
223 if (mask) {
224 report_unsupported(bs, errp, "Unknown incompatible feature: %" PRIx64,
225 mask);
230 * Sets the dirty bit and flushes afterwards if necessary.
232 * The incompatible_features bit is only set if the image file header was
233 * updated successfully. Therefore it is not required to check the return
234 * value of this function.
236 int qcow2_mark_dirty(BlockDriverState *bs)
238 BDRVQcowState *s = bs->opaque;
239 uint64_t val;
240 int ret;
242 assert(s->qcow_version >= 3);
244 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
245 return 0; /* already dirty */
248 val = cpu_to_be64(s->incompatible_features | QCOW2_INCOMPAT_DIRTY);
249 ret = bdrv_pwrite(bs->file, offsetof(QCowHeader, incompatible_features),
250 &val, sizeof(val));
251 if (ret < 0) {
252 return ret;
254 ret = bdrv_flush(bs->file);
255 if (ret < 0) {
256 return ret;
259 /* Only treat image as dirty if the header was updated successfully */
260 s->incompatible_features |= QCOW2_INCOMPAT_DIRTY;
261 return 0;
265 * Clears the dirty bit and flushes before if necessary. Only call this
266 * function when there are no pending requests, it does not guard against
267 * concurrent requests dirtying the image.
269 static int qcow2_mark_clean(BlockDriverState *bs)
271 BDRVQcowState *s = bs->opaque;
273 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
274 int ret;
276 s->incompatible_features &= ~QCOW2_INCOMPAT_DIRTY;
278 ret = bdrv_flush(bs);
279 if (ret < 0) {
280 return ret;
283 return qcow2_update_header(bs);
285 return 0;
289 * Marks the image as corrupt.
291 int qcow2_mark_corrupt(BlockDriverState *bs)
293 BDRVQcowState *s = bs->opaque;
295 s->incompatible_features |= QCOW2_INCOMPAT_CORRUPT;
296 return qcow2_update_header(bs);
300 * Marks the image as consistent, i.e., unsets the corrupt bit, and flushes
301 * before if necessary.
303 int qcow2_mark_consistent(BlockDriverState *bs)
305 BDRVQcowState *s = bs->opaque;
307 if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
308 int ret = bdrv_flush(bs);
309 if (ret < 0) {
310 return ret;
313 s->incompatible_features &= ~QCOW2_INCOMPAT_CORRUPT;
314 return qcow2_update_header(bs);
316 return 0;
319 static int qcow2_check(BlockDriverState *bs, BdrvCheckResult *result,
320 BdrvCheckMode fix)
322 int ret = qcow2_check_refcounts(bs, result, fix);
323 if (ret < 0) {
324 return ret;
327 if (fix && result->check_errors == 0 && result->corruptions == 0) {
328 ret = qcow2_mark_clean(bs);
329 if (ret < 0) {
330 return ret;
332 return qcow2_mark_consistent(bs);
334 return ret;
337 static int validate_table_offset(BlockDriverState *bs, uint64_t offset,
338 uint64_t entries, size_t entry_len)
340 BDRVQcowState *s = bs->opaque;
341 uint64_t size;
343 /* Use signed INT64_MAX as the maximum even for uint64_t header fields,
344 * because values will be passed to qemu functions taking int64_t. */
345 if (entries > INT64_MAX / entry_len) {
346 return -EINVAL;
349 size = entries * entry_len;
351 if (INT64_MAX - size < offset) {
352 return -EINVAL;
355 /* Tables must be cluster aligned */
356 if (offset & (s->cluster_size - 1)) {
357 return -EINVAL;
360 return 0;
363 static QemuOptsList qcow2_runtime_opts = {
364 .name = "qcow2",
365 .head = QTAILQ_HEAD_INITIALIZER(qcow2_runtime_opts.head),
366 .desc = {
368 .name = QCOW2_OPT_LAZY_REFCOUNTS,
369 .type = QEMU_OPT_BOOL,
370 .help = "Postpone refcount updates",
373 .name = QCOW2_OPT_DISCARD_REQUEST,
374 .type = QEMU_OPT_BOOL,
375 .help = "Pass guest discard requests to the layer below",
378 .name = QCOW2_OPT_DISCARD_SNAPSHOT,
379 .type = QEMU_OPT_BOOL,
380 .help = "Generate discard requests when snapshot related space "
381 "is freed",
384 .name = QCOW2_OPT_DISCARD_OTHER,
385 .type = QEMU_OPT_BOOL,
386 .help = "Generate discard requests when other clusters are freed",
389 .name = QCOW2_OPT_OVERLAP,
390 .type = QEMU_OPT_STRING,
391 .help = "Selects which overlap checks to perform from a range of "
392 "templates (none, constant, cached, all)",
395 .name = QCOW2_OPT_OVERLAP_MAIN_HEADER,
396 .type = QEMU_OPT_BOOL,
397 .help = "Check for unintended writes into the main qcow2 header",
400 .name = QCOW2_OPT_OVERLAP_ACTIVE_L1,
401 .type = QEMU_OPT_BOOL,
402 .help = "Check for unintended writes into the active L1 table",
405 .name = QCOW2_OPT_OVERLAP_ACTIVE_L2,
406 .type = QEMU_OPT_BOOL,
407 .help = "Check for unintended writes into an active L2 table",
410 .name = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
411 .type = QEMU_OPT_BOOL,
412 .help = "Check for unintended writes into the refcount table",
415 .name = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
416 .type = QEMU_OPT_BOOL,
417 .help = "Check for unintended writes into a refcount block",
420 .name = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
421 .type = QEMU_OPT_BOOL,
422 .help = "Check for unintended writes into the snapshot table",
425 .name = QCOW2_OPT_OVERLAP_INACTIVE_L1,
426 .type = QEMU_OPT_BOOL,
427 .help = "Check for unintended writes into an inactive L1 table",
430 .name = QCOW2_OPT_OVERLAP_INACTIVE_L2,
431 .type = QEMU_OPT_BOOL,
432 .help = "Check for unintended writes into an inactive L2 table",
434 { /* end of list */ }
438 static const char *overlap_bool_option_names[QCOW2_OL_MAX_BITNR] = {
439 [QCOW2_OL_MAIN_HEADER_BITNR] = QCOW2_OPT_OVERLAP_MAIN_HEADER,
440 [QCOW2_OL_ACTIVE_L1_BITNR] = QCOW2_OPT_OVERLAP_ACTIVE_L1,
441 [QCOW2_OL_ACTIVE_L2_BITNR] = QCOW2_OPT_OVERLAP_ACTIVE_L2,
442 [QCOW2_OL_REFCOUNT_TABLE_BITNR] = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
443 [QCOW2_OL_REFCOUNT_BLOCK_BITNR] = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
444 [QCOW2_OL_SNAPSHOT_TABLE_BITNR] = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
445 [QCOW2_OL_INACTIVE_L1_BITNR] = QCOW2_OPT_OVERLAP_INACTIVE_L1,
446 [QCOW2_OL_INACTIVE_L2_BITNR] = QCOW2_OPT_OVERLAP_INACTIVE_L2,
449 static int qcow2_open(BlockDriverState *bs, QDict *options, int flags,
450 Error **errp)
452 BDRVQcowState *s = bs->opaque;
453 unsigned int len, i;
454 int ret = 0;
455 QCowHeader header;
456 QemuOpts *opts;
457 Error *local_err = NULL;
458 uint64_t ext_end;
459 uint64_t l1_vm_state_index;
460 const char *opt_overlap_check;
461 int overlap_check_template = 0;
463 ret = bdrv_pread(bs->file, 0, &header, sizeof(header));
464 if (ret < 0) {
465 error_setg_errno(errp, -ret, "Could not read qcow2 header");
466 goto fail;
468 be32_to_cpus(&header.magic);
469 be32_to_cpus(&header.version);
470 be64_to_cpus(&header.backing_file_offset);
471 be32_to_cpus(&header.backing_file_size);
472 be64_to_cpus(&header.size);
473 be32_to_cpus(&header.cluster_bits);
474 be32_to_cpus(&header.crypt_method);
475 be64_to_cpus(&header.l1_table_offset);
476 be32_to_cpus(&header.l1_size);
477 be64_to_cpus(&header.refcount_table_offset);
478 be32_to_cpus(&header.refcount_table_clusters);
479 be64_to_cpus(&header.snapshots_offset);
480 be32_to_cpus(&header.nb_snapshots);
482 if (header.magic != QCOW_MAGIC) {
483 error_setg(errp, "Image is not in qcow2 format");
484 ret = -EINVAL;
485 goto fail;
487 if (header.version < 2 || header.version > 3) {
488 report_unsupported(bs, errp, "QCOW version %" PRIu32, header.version);
489 ret = -ENOTSUP;
490 goto fail;
493 s->qcow_version = header.version;
495 /* Initialise cluster size */
496 if (header.cluster_bits < MIN_CLUSTER_BITS ||
497 header.cluster_bits > MAX_CLUSTER_BITS) {
498 error_setg(errp, "Unsupported cluster size: 2^%" PRIu32,
499 header.cluster_bits);
500 ret = -EINVAL;
501 goto fail;
504 s->cluster_bits = header.cluster_bits;
505 s->cluster_size = 1 << s->cluster_bits;
506 s->cluster_sectors = 1 << (s->cluster_bits - 9);
508 /* Initialise version 3 header fields */
509 if (header.version == 2) {
510 header.incompatible_features = 0;
511 header.compatible_features = 0;
512 header.autoclear_features = 0;
513 header.refcount_order = 4;
514 header.header_length = 72;
515 } else {
516 be64_to_cpus(&header.incompatible_features);
517 be64_to_cpus(&header.compatible_features);
518 be64_to_cpus(&header.autoclear_features);
519 be32_to_cpus(&header.refcount_order);
520 be32_to_cpus(&header.header_length);
522 if (header.header_length < 104) {
523 error_setg(errp, "qcow2 header too short");
524 ret = -EINVAL;
525 goto fail;
529 if (header.header_length > s->cluster_size) {
530 error_setg(errp, "qcow2 header exceeds cluster size");
531 ret = -EINVAL;
532 goto fail;
535 if (header.header_length > sizeof(header)) {
536 s->unknown_header_fields_size = header.header_length - sizeof(header);
537 s->unknown_header_fields = g_malloc(s->unknown_header_fields_size);
538 ret = bdrv_pread(bs->file, sizeof(header), s->unknown_header_fields,
539 s->unknown_header_fields_size);
540 if (ret < 0) {
541 error_setg_errno(errp, -ret, "Could not read unknown qcow2 header "
542 "fields");
543 goto fail;
547 if (header.backing_file_offset > s->cluster_size) {
548 error_setg(errp, "Invalid backing file offset");
549 ret = -EINVAL;
550 goto fail;
553 if (header.backing_file_offset) {
554 ext_end = header.backing_file_offset;
555 } else {
556 ext_end = 1 << header.cluster_bits;
559 /* Handle feature bits */
560 s->incompatible_features = header.incompatible_features;
561 s->compatible_features = header.compatible_features;
562 s->autoclear_features = header.autoclear_features;
564 if (s->incompatible_features & ~QCOW2_INCOMPAT_MASK) {
565 void *feature_table = NULL;
566 qcow2_read_extensions(bs, header.header_length, ext_end,
567 &feature_table, NULL);
568 report_unsupported_feature(bs, errp, feature_table,
569 s->incompatible_features &
570 ~QCOW2_INCOMPAT_MASK);
571 ret = -ENOTSUP;
572 g_free(feature_table);
573 goto fail;
576 if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
577 /* Corrupt images may not be written to unless they are being repaired
579 if ((flags & BDRV_O_RDWR) && !(flags & BDRV_O_CHECK)) {
580 error_setg(errp, "qcow2: Image is corrupt; cannot be opened "
581 "read/write");
582 ret = -EACCES;
583 goto fail;
587 /* Check support for various header values */
588 if (header.refcount_order != 4) {
589 report_unsupported(bs, errp, "%d bit reference counts",
590 1 << header.refcount_order);
591 ret = -ENOTSUP;
592 goto fail;
594 s->refcount_order = header.refcount_order;
596 if (header.crypt_method > QCOW_CRYPT_AES) {
597 error_setg(errp, "Unsupported encryption method: %" PRIu32,
598 header.crypt_method);
599 ret = -EINVAL;
600 goto fail;
602 s->crypt_method_header = header.crypt_method;
603 if (s->crypt_method_header) {
604 bs->encrypted = 1;
607 s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */
608 s->l2_size = 1 << s->l2_bits;
609 bs->total_sectors = header.size / 512;
610 s->csize_shift = (62 - (s->cluster_bits - 8));
611 s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;
612 s->cluster_offset_mask = (1LL << s->csize_shift) - 1;
614 s->refcount_table_offset = header.refcount_table_offset;
615 s->refcount_table_size =
616 header.refcount_table_clusters << (s->cluster_bits - 3);
618 if (header.refcount_table_clusters > qcow2_max_refcount_clusters(s)) {
619 error_setg(errp, "Reference count table too large");
620 ret = -EINVAL;
621 goto fail;
624 ret = validate_table_offset(bs, s->refcount_table_offset,
625 s->refcount_table_size, sizeof(uint64_t));
626 if (ret < 0) {
627 error_setg(errp, "Invalid reference count table offset");
628 goto fail;
631 /* Snapshot table offset/length */
632 if (header.nb_snapshots > QCOW_MAX_SNAPSHOTS) {
633 error_setg(errp, "Too many snapshots");
634 ret = -EINVAL;
635 goto fail;
638 ret = validate_table_offset(bs, header.snapshots_offset,
639 header.nb_snapshots,
640 sizeof(QCowSnapshotHeader));
641 if (ret < 0) {
642 error_setg(errp, "Invalid snapshot table offset");
643 goto fail;
646 /* read the level 1 table */
647 if (header.l1_size > QCOW_MAX_L1_SIZE) {
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 > MIN(1023, s->cluster_size - header.backing_file_offset)) {
725 error_setg(errp, "Backing file name too long");
726 ret = -EINVAL;
727 goto fail;
729 ret = bdrv_pread(bs->file, header.backing_file_offset,
730 bs->backing_file, len);
731 if (ret < 0) {
732 error_setg_errno(errp, -ret, "Could not read backing file name");
733 goto fail;
735 bs->backing_file[len] = '\0';
738 /* Internal snapshots */
739 s->snapshots_offset = header.snapshots_offset;
740 s->nb_snapshots = header.nb_snapshots;
742 ret = qcow2_read_snapshots(bs);
743 if (ret < 0) {
744 error_setg_errno(errp, -ret, "Could not read snapshots");
745 goto fail;
748 /* Clear unknown autoclear feature bits */
749 if (!bs->read_only && !(flags & BDRV_O_INCOMING) && s->autoclear_features) {
750 s->autoclear_features = 0;
751 ret = qcow2_update_header(bs);
752 if (ret < 0) {
753 error_setg_errno(errp, -ret, "Could not update qcow2 header");
754 goto fail;
758 /* Initialise locks */
759 qemu_co_mutex_init(&s->lock);
761 /* Repair image if dirty */
762 if (!(flags & (BDRV_O_CHECK | BDRV_O_INCOMING)) && !bs->read_only &&
763 (s->incompatible_features & QCOW2_INCOMPAT_DIRTY)) {
764 BdrvCheckResult result = {0};
766 ret = qcow2_check(bs, &result, BDRV_FIX_ERRORS);
767 if (ret < 0) {
768 error_setg_errno(errp, -ret, "Could not repair dirty image");
769 goto fail;
773 /* Enable lazy_refcounts according to image and command line options */
774 opts = qemu_opts_create(&qcow2_runtime_opts, NULL, 0, &error_abort);
775 qemu_opts_absorb_qdict(opts, options, &local_err);
776 if (local_err) {
777 error_propagate(errp, local_err);
778 ret = -EINVAL;
779 goto fail;
782 s->use_lazy_refcounts = qemu_opt_get_bool(opts, QCOW2_OPT_LAZY_REFCOUNTS,
783 (s->compatible_features & QCOW2_COMPAT_LAZY_REFCOUNTS));
785 s->discard_passthrough[QCOW2_DISCARD_NEVER] = false;
786 s->discard_passthrough[QCOW2_DISCARD_ALWAYS] = true;
787 s->discard_passthrough[QCOW2_DISCARD_REQUEST] =
788 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_REQUEST,
789 flags & BDRV_O_UNMAP);
790 s->discard_passthrough[QCOW2_DISCARD_SNAPSHOT] =
791 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_SNAPSHOT, true);
792 s->discard_passthrough[QCOW2_DISCARD_OTHER] =
793 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_OTHER, false);
795 opt_overlap_check = qemu_opt_get(opts, "overlap-check") ?: "cached";
796 if (!strcmp(opt_overlap_check, "none")) {
797 overlap_check_template = 0;
798 } else if (!strcmp(opt_overlap_check, "constant")) {
799 overlap_check_template = QCOW2_OL_CONSTANT;
800 } else if (!strcmp(opt_overlap_check, "cached")) {
801 overlap_check_template = QCOW2_OL_CACHED;
802 } else if (!strcmp(opt_overlap_check, "all")) {
803 overlap_check_template = QCOW2_OL_ALL;
804 } else {
805 error_setg(errp, "Unsupported value '%s' for qcow2 option "
806 "'overlap-check'. Allowed are either of the following: "
807 "none, constant, cached, all", opt_overlap_check);
808 qemu_opts_del(opts);
809 ret = -EINVAL;
810 goto fail;
813 s->overlap_check = 0;
814 for (i = 0; i < QCOW2_OL_MAX_BITNR; i++) {
815 /* overlap-check defines a template bitmask, but every flag may be
816 * overwritten through the associated boolean option */
817 s->overlap_check |=
818 qemu_opt_get_bool(opts, overlap_bool_option_names[i],
819 overlap_check_template & (1 << i)) << i;
822 qemu_opts_del(opts);
824 if (s->use_lazy_refcounts && s->qcow_version < 3) {
825 error_setg(errp, "Lazy refcounts require a qcow2 image with at least "
826 "qemu 1.1 compatibility level");
827 ret = -EINVAL;
828 goto fail;
831 #ifdef DEBUG_ALLOC
833 BdrvCheckResult result = {0};
834 qcow2_check_refcounts(bs, &result, 0);
836 #endif
837 return ret;
839 fail:
840 g_free(s->unknown_header_fields);
841 cleanup_unknown_header_ext(bs);
842 qcow2_free_snapshots(bs);
843 qcow2_refcount_close(bs);
844 g_free(s->l1_table);
845 /* else pre-write overlap checks in cache_destroy may crash */
846 s->l1_table = NULL;
847 if (s->l2_table_cache) {
848 qcow2_cache_destroy(bs, s->l2_table_cache);
850 if (s->refcount_block_cache) {
851 qcow2_cache_destroy(bs, s->refcount_block_cache);
853 g_free(s->cluster_cache);
854 qemu_vfree(s->cluster_data);
855 return ret;
858 static int qcow2_refresh_limits(BlockDriverState *bs)
860 BDRVQcowState *s = bs->opaque;
862 bs->bl.write_zeroes_alignment = s->cluster_sectors;
864 return 0;
867 static int qcow2_set_key(BlockDriverState *bs, const char *key)
869 BDRVQcowState *s = bs->opaque;
870 uint8_t keybuf[16];
871 int len, i;
873 memset(keybuf, 0, 16);
874 len = strlen(key);
875 if (len > 16)
876 len = 16;
877 /* XXX: we could compress the chars to 7 bits to increase
878 entropy */
879 for(i = 0;i < len;i++) {
880 keybuf[i] = key[i];
882 s->crypt_method = s->crypt_method_header;
884 if (AES_set_encrypt_key(keybuf, 128, &s->aes_encrypt_key) != 0)
885 return -1;
886 if (AES_set_decrypt_key(keybuf, 128, &s->aes_decrypt_key) != 0)
887 return -1;
888 #if 0
889 /* test */
891 uint8_t in[16];
892 uint8_t out[16];
893 uint8_t tmp[16];
894 for(i=0;i<16;i++)
895 in[i] = i;
896 AES_encrypt(in, tmp, &s->aes_encrypt_key);
897 AES_decrypt(tmp, out, &s->aes_decrypt_key);
898 for(i = 0; i < 16; i++)
899 printf(" %02x", tmp[i]);
900 printf("\n");
901 for(i = 0; i < 16; i++)
902 printf(" %02x", out[i]);
903 printf("\n");
905 #endif
906 return 0;
909 /* We have no actual commit/abort logic for qcow2, but we need to write out any
910 * unwritten data if we reopen read-only. */
911 static int qcow2_reopen_prepare(BDRVReopenState *state,
912 BlockReopenQueue *queue, Error **errp)
914 int ret;
916 if ((state->flags & BDRV_O_RDWR) == 0) {
917 ret = bdrv_flush(state->bs);
918 if (ret < 0) {
919 return ret;
922 ret = qcow2_mark_clean(state->bs);
923 if (ret < 0) {
924 return ret;
928 return 0;
931 static int64_t coroutine_fn qcow2_co_get_block_status(BlockDriverState *bs,
932 int64_t sector_num, int nb_sectors, int *pnum)
934 BDRVQcowState *s = bs->opaque;
935 uint64_t cluster_offset;
936 int index_in_cluster, ret;
937 int64_t status = 0;
939 *pnum = nb_sectors;
940 qemu_co_mutex_lock(&s->lock);
941 ret = qcow2_get_cluster_offset(bs, sector_num << 9, pnum, &cluster_offset);
942 qemu_co_mutex_unlock(&s->lock);
943 if (ret < 0) {
944 return ret;
947 if (cluster_offset != 0 && ret != QCOW2_CLUSTER_COMPRESSED &&
948 !s->crypt_method) {
949 index_in_cluster = sector_num & (s->cluster_sectors - 1);
950 cluster_offset |= (index_in_cluster << BDRV_SECTOR_BITS);
951 status |= BDRV_BLOCK_OFFSET_VALID | cluster_offset;
953 if (ret == QCOW2_CLUSTER_ZERO) {
954 status |= BDRV_BLOCK_ZERO;
955 } else if (ret != QCOW2_CLUSTER_UNALLOCATED) {
956 status |= BDRV_BLOCK_DATA;
958 return status;
961 /* handle reading after the end of the backing file */
962 int qcow2_backing_read1(BlockDriverState *bs, QEMUIOVector *qiov,
963 int64_t sector_num, int nb_sectors)
965 int n1;
966 if ((sector_num + nb_sectors) <= bs->total_sectors)
967 return nb_sectors;
968 if (sector_num >= bs->total_sectors)
969 n1 = 0;
970 else
971 n1 = bs->total_sectors - sector_num;
973 qemu_iovec_memset(qiov, 512 * n1, 0, 512 * (nb_sectors - n1));
975 return n1;
978 static coroutine_fn int qcow2_co_readv(BlockDriverState *bs, int64_t sector_num,
979 int remaining_sectors, QEMUIOVector *qiov)
981 BDRVQcowState *s = bs->opaque;
982 int index_in_cluster, n1;
983 int ret;
984 int cur_nr_sectors; /* number of sectors in current iteration */
985 uint64_t cluster_offset = 0;
986 uint64_t bytes_done = 0;
987 QEMUIOVector hd_qiov;
988 uint8_t *cluster_data = NULL;
990 qemu_iovec_init(&hd_qiov, qiov->niov);
992 qemu_co_mutex_lock(&s->lock);
994 while (remaining_sectors != 0) {
996 /* prepare next request */
997 cur_nr_sectors = remaining_sectors;
998 if (s->crypt_method) {
999 cur_nr_sectors = MIN(cur_nr_sectors,
1000 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors);
1003 ret = qcow2_get_cluster_offset(bs, sector_num << 9,
1004 &cur_nr_sectors, &cluster_offset);
1005 if (ret < 0) {
1006 goto fail;
1009 index_in_cluster = sector_num & (s->cluster_sectors - 1);
1011 qemu_iovec_reset(&hd_qiov);
1012 qemu_iovec_concat(&hd_qiov, qiov, bytes_done,
1013 cur_nr_sectors * 512);
1015 switch (ret) {
1016 case QCOW2_CLUSTER_UNALLOCATED:
1018 if (bs->backing_hd) {
1019 /* read from the base image */
1020 n1 = qcow2_backing_read1(bs->backing_hd, &hd_qiov,
1021 sector_num, cur_nr_sectors);
1022 if (n1 > 0) {
1023 QEMUIOVector local_qiov;
1025 qemu_iovec_init(&local_qiov, hd_qiov.niov);
1026 qemu_iovec_concat(&local_qiov, &hd_qiov, 0,
1027 n1 * BDRV_SECTOR_SIZE);
1029 BLKDBG_EVENT(bs->file, BLKDBG_READ_BACKING_AIO);
1030 qemu_co_mutex_unlock(&s->lock);
1031 ret = bdrv_co_readv(bs->backing_hd, sector_num,
1032 n1, &local_qiov);
1033 qemu_co_mutex_lock(&s->lock);
1035 qemu_iovec_destroy(&local_qiov);
1037 if (ret < 0) {
1038 goto fail;
1041 } else {
1042 /* Note: in this case, no need to wait */
1043 qemu_iovec_memset(&hd_qiov, 0, 0, 512 * cur_nr_sectors);
1045 break;
1047 case QCOW2_CLUSTER_ZERO:
1048 qemu_iovec_memset(&hd_qiov, 0, 0, 512 * cur_nr_sectors);
1049 break;
1051 case QCOW2_CLUSTER_COMPRESSED:
1052 /* add AIO support for compressed blocks ? */
1053 ret = qcow2_decompress_cluster(bs, cluster_offset);
1054 if (ret < 0) {
1055 goto fail;
1058 qemu_iovec_from_buf(&hd_qiov, 0,
1059 s->cluster_cache + index_in_cluster * 512,
1060 512 * cur_nr_sectors);
1061 break;
1063 case QCOW2_CLUSTER_NORMAL:
1064 if ((cluster_offset & 511) != 0) {
1065 ret = -EIO;
1066 goto fail;
1069 if (s->crypt_method) {
1071 * For encrypted images, read everything into a temporary
1072 * contiguous buffer on which the AES functions can work.
1074 if (!cluster_data) {
1075 cluster_data =
1076 qemu_blockalign(bs, QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
1079 assert(cur_nr_sectors <=
1080 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors);
1081 qemu_iovec_reset(&hd_qiov);
1082 qemu_iovec_add(&hd_qiov, cluster_data,
1083 512 * cur_nr_sectors);
1086 BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);
1087 qemu_co_mutex_unlock(&s->lock);
1088 ret = bdrv_co_readv(bs->file,
1089 (cluster_offset >> 9) + index_in_cluster,
1090 cur_nr_sectors, &hd_qiov);
1091 qemu_co_mutex_lock(&s->lock);
1092 if (ret < 0) {
1093 goto fail;
1095 if (s->crypt_method) {
1096 qcow2_encrypt_sectors(s, sector_num, cluster_data,
1097 cluster_data, cur_nr_sectors, 0, &s->aes_decrypt_key);
1098 qemu_iovec_from_buf(qiov, bytes_done,
1099 cluster_data, 512 * cur_nr_sectors);
1101 break;
1103 default:
1104 g_assert_not_reached();
1105 ret = -EIO;
1106 goto fail;
1109 remaining_sectors -= cur_nr_sectors;
1110 sector_num += cur_nr_sectors;
1111 bytes_done += cur_nr_sectors * 512;
1113 ret = 0;
1115 fail:
1116 qemu_co_mutex_unlock(&s->lock);
1118 qemu_iovec_destroy(&hd_qiov);
1119 qemu_vfree(cluster_data);
1121 return ret;
1124 static coroutine_fn int qcow2_co_writev(BlockDriverState *bs,
1125 int64_t sector_num,
1126 int remaining_sectors,
1127 QEMUIOVector *qiov)
1129 BDRVQcowState *s = bs->opaque;
1130 int index_in_cluster;
1131 int ret;
1132 int cur_nr_sectors; /* number of sectors in current iteration */
1133 uint64_t cluster_offset;
1134 QEMUIOVector hd_qiov;
1135 uint64_t bytes_done = 0;
1136 uint8_t *cluster_data = NULL;
1137 QCowL2Meta *l2meta = NULL;
1139 trace_qcow2_writev_start_req(qemu_coroutine_self(), sector_num,
1140 remaining_sectors);
1142 qemu_iovec_init(&hd_qiov, qiov->niov);
1144 s->cluster_cache_offset = -1; /* disable compressed cache */
1146 qemu_co_mutex_lock(&s->lock);
1148 while (remaining_sectors != 0) {
1150 l2meta = NULL;
1152 trace_qcow2_writev_start_part(qemu_coroutine_self());
1153 index_in_cluster = sector_num & (s->cluster_sectors - 1);
1154 cur_nr_sectors = remaining_sectors;
1155 if (s->crypt_method &&
1156 cur_nr_sectors >
1157 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors - index_in_cluster) {
1158 cur_nr_sectors =
1159 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors - index_in_cluster;
1162 ret = qcow2_alloc_cluster_offset(bs, sector_num << 9,
1163 &cur_nr_sectors, &cluster_offset, &l2meta);
1164 if (ret < 0) {
1165 goto fail;
1168 assert((cluster_offset & 511) == 0);
1170 qemu_iovec_reset(&hd_qiov);
1171 qemu_iovec_concat(&hd_qiov, qiov, bytes_done,
1172 cur_nr_sectors * 512);
1174 if (s->crypt_method) {
1175 if (!cluster_data) {
1176 cluster_data = qemu_blockalign(bs, QCOW_MAX_CRYPT_CLUSTERS *
1177 s->cluster_size);
1180 assert(hd_qiov.size <=
1181 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
1182 qemu_iovec_to_buf(&hd_qiov, 0, cluster_data, hd_qiov.size);
1184 qcow2_encrypt_sectors(s, sector_num, cluster_data,
1185 cluster_data, cur_nr_sectors, 1, &s->aes_encrypt_key);
1187 qemu_iovec_reset(&hd_qiov);
1188 qemu_iovec_add(&hd_qiov, cluster_data,
1189 cur_nr_sectors * 512);
1192 ret = qcow2_pre_write_overlap_check(bs, 0,
1193 cluster_offset + index_in_cluster * BDRV_SECTOR_SIZE,
1194 cur_nr_sectors * BDRV_SECTOR_SIZE);
1195 if (ret < 0) {
1196 goto fail;
1199 qemu_co_mutex_unlock(&s->lock);
1200 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO);
1201 trace_qcow2_writev_data(qemu_coroutine_self(),
1202 (cluster_offset >> 9) + index_in_cluster);
1203 ret = bdrv_co_writev(bs->file,
1204 (cluster_offset >> 9) + index_in_cluster,
1205 cur_nr_sectors, &hd_qiov);
1206 qemu_co_mutex_lock(&s->lock);
1207 if (ret < 0) {
1208 goto fail;
1211 while (l2meta != NULL) {
1212 QCowL2Meta *next;
1214 ret = qcow2_alloc_cluster_link_l2(bs, l2meta);
1215 if (ret < 0) {
1216 goto fail;
1219 /* Take the request off the list of running requests */
1220 if (l2meta->nb_clusters != 0) {
1221 QLIST_REMOVE(l2meta, next_in_flight);
1224 qemu_co_queue_restart_all(&l2meta->dependent_requests);
1226 next = l2meta->next;
1227 g_free(l2meta);
1228 l2meta = next;
1231 remaining_sectors -= cur_nr_sectors;
1232 sector_num += cur_nr_sectors;
1233 bytes_done += cur_nr_sectors * 512;
1234 trace_qcow2_writev_done_part(qemu_coroutine_self(), cur_nr_sectors);
1236 ret = 0;
1238 fail:
1239 qemu_co_mutex_unlock(&s->lock);
1241 while (l2meta != NULL) {
1242 QCowL2Meta *next;
1244 if (l2meta->nb_clusters != 0) {
1245 QLIST_REMOVE(l2meta, next_in_flight);
1247 qemu_co_queue_restart_all(&l2meta->dependent_requests);
1249 next = l2meta->next;
1250 g_free(l2meta);
1251 l2meta = next;
1254 qemu_iovec_destroy(&hd_qiov);
1255 qemu_vfree(cluster_data);
1256 trace_qcow2_writev_done_req(qemu_coroutine_self(), ret);
1258 return ret;
1261 static void qcow2_close(BlockDriverState *bs)
1263 BDRVQcowState *s = bs->opaque;
1264 g_free(s->l1_table);
1265 /* else pre-write overlap checks in cache_destroy may crash */
1266 s->l1_table = NULL;
1268 if (!(bs->open_flags & BDRV_O_INCOMING)) {
1269 qcow2_cache_flush(bs, s->l2_table_cache);
1270 qcow2_cache_flush(bs, s->refcount_block_cache);
1272 qcow2_mark_clean(bs);
1275 qcow2_cache_destroy(bs, s->l2_table_cache);
1276 qcow2_cache_destroy(bs, s->refcount_block_cache);
1278 g_free(s->unknown_header_fields);
1279 cleanup_unknown_header_ext(bs);
1281 g_free(s->cluster_cache);
1282 qemu_vfree(s->cluster_data);
1283 qcow2_refcount_close(bs);
1284 qcow2_free_snapshots(bs);
1287 static void qcow2_invalidate_cache(BlockDriverState *bs, Error **errp)
1289 BDRVQcowState *s = bs->opaque;
1290 int flags = s->flags;
1291 AES_KEY aes_encrypt_key;
1292 AES_KEY aes_decrypt_key;
1293 uint32_t crypt_method = 0;
1294 QDict *options;
1295 Error *local_err = NULL;
1296 int ret;
1299 * Backing files are read-only which makes all of their metadata immutable,
1300 * that means we don't have to worry about reopening them here.
1303 if (s->crypt_method) {
1304 crypt_method = s->crypt_method;
1305 memcpy(&aes_encrypt_key, &s->aes_encrypt_key, sizeof(aes_encrypt_key));
1306 memcpy(&aes_decrypt_key, &s->aes_decrypt_key, sizeof(aes_decrypt_key));
1309 qcow2_close(bs);
1311 bdrv_invalidate_cache(bs->file, &local_err);
1312 if (local_err) {
1313 error_propagate(errp, local_err);
1314 return;
1317 memset(s, 0, sizeof(BDRVQcowState));
1318 options = qdict_clone_shallow(bs->options);
1320 ret = qcow2_open(bs, options, flags, &local_err);
1321 QDECREF(options);
1322 if (local_err) {
1323 error_setg(errp, "Could not reopen qcow2 layer: %s",
1324 error_get_pretty(local_err));
1325 error_free(local_err);
1326 return;
1327 } else if (ret < 0) {
1328 error_setg_errno(errp, -ret, "Could not reopen qcow2 layer");
1329 return;
1332 if (crypt_method) {
1333 s->crypt_method = crypt_method;
1334 memcpy(&s->aes_encrypt_key, &aes_encrypt_key, sizeof(aes_encrypt_key));
1335 memcpy(&s->aes_decrypt_key, &aes_decrypt_key, sizeof(aes_decrypt_key));
1339 static size_t header_ext_add(char *buf, uint32_t magic, const void *s,
1340 size_t len, size_t buflen)
1342 QCowExtension *ext_backing_fmt = (QCowExtension*) buf;
1343 size_t ext_len = sizeof(QCowExtension) + ((len + 7) & ~7);
1345 if (buflen < ext_len) {
1346 return -ENOSPC;
1349 *ext_backing_fmt = (QCowExtension) {
1350 .magic = cpu_to_be32(magic),
1351 .len = cpu_to_be32(len),
1353 memcpy(buf + sizeof(QCowExtension), s, len);
1355 return ext_len;
1359 * Updates the qcow2 header, including the variable length parts of it, i.e.
1360 * the backing file name and all extensions. qcow2 was not designed to allow
1361 * such changes, so if we run out of space (we can only use the first cluster)
1362 * this function may fail.
1364 * Returns 0 on success, -errno in error cases.
1366 int qcow2_update_header(BlockDriverState *bs)
1368 BDRVQcowState *s = bs->opaque;
1369 QCowHeader *header;
1370 char *buf;
1371 size_t buflen = s->cluster_size;
1372 int ret;
1373 uint64_t total_size;
1374 uint32_t refcount_table_clusters;
1375 size_t header_length;
1376 Qcow2UnknownHeaderExtension *uext;
1378 buf = qemu_blockalign(bs, buflen);
1380 /* Header structure */
1381 header = (QCowHeader*) buf;
1383 if (buflen < sizeof(*header)) {
1384 ret = -ENOSPC;
1385 goto fail;
1388 header_length = sizeof(*header) + s->unknown_header_fields_size;
1389 total_size = bs->total_sectors * BDRV_SECTOR_SIZE;
1390 refcount_table_clusters = s->refcount_table_size >> (s->cluster_bits - 3);
1392 *header = (QCowHeader) {
1393 /* Version 2 fields */
1394 .magic = cpu_to_be32(QCOW_MAGIC),
1395 .version = cpu_to_be32(s->qcow_version),
1396 .backing_file_offset = 0,
1397 .backing_file_size = 0,
1398 .cluster_bits = cpu_to_be32(s->cluster_bits),
1399 .size = cpu_to_be64(total_size),
1400 .crypt_method = cpu_to_be32(s->crypt_method_header),
1401 .l1_size = cpu_to_be32(s->l1_size),
1402 .l1_table_offset = cpu_to_be64(s->l1_table_offset),
1403 .refcount_table_offset = cpu_to_be64(s->refcount_table_offset),
1404 .refcount_table_clusters = cpu_to_be32(refcount_table_clusters),
1405 .nb_snapshots = cpu_to_be32(s->nb_snapshots),
1406 .snapshots_offset = cpu_to_be64(s->snapshots_offset),
1408 /* Version 3 fields */
1409 .incompatible_features = cpu_to_be64(s->incompatible_features),
1410 .compatible_features = cpu_to_be64(s->compatible_features),
1411 .autoclear_features = cpu_to_be64(s->autoclear_features),
1412 .refcount_order = cpu_to_be32(s->refcount_order),
1413 .header_length = cpu_to_be32(header_length),
1416 /* For older versions, write a shorter header */
1417 switch (s->qcow_version) {
1418 case 2:
1419 ret = offsetof(QCowHeader, incompatible_features);
1420 break;
1421 case 3:
1422 ret = sizeof(*header);
1423 break;
1424 default:
1425 ret = -EINVAL;
1426 goto fail;
1429 buf += ret;
1430 buflen -= ret;
1431 memset(buf, 0, buflen);
1433 /* Preserve any unknown field in the header */
1434 if (s->unknown_header_fields_size) {
1435 if (buflen < s->unknown_header_fields_size) {
1436 ret = -ENOSPC;
1437 goto fail;
1440 memcpy(buf, s->unknown_header_fields, s->unknown_header_fields_size);
1441 buf += s->unknown_header_fields_size;
1442 buflen -= s->unknown_header_fields_size;
1445 /* Backing file format header extension */
1446 if (*bs->backing_format) {
1447 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BACKING_FORMAT,
1448 bs->backing_format, strlen(bs->backing_format),
1449 buflen);
1450 if (ret < 0) {
1451 goto fail;
1454 buf += ret;
1455 buflen -= ret;
1458 /* Feature table */
1459 Qcow2Feature features[] = {
1461 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
1462 .bit = QCOW2_INCOMPAT_DIRTY_BITNR,
1463 .name = "dirty bit",
1466 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
1467 .bit = QCOW2_INCOMPAT_CORRUPT_BITNR,
1468 .name = "corrupt bit",
1471 .type = QCOW2_FEAT_TYPE_COMPATIBLE,
1472 .bit = QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR,
1473 .name = "lazy refcounts",
1477 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_FEATURE_TABLE,
1478 features, sizeof(features), buflen);
1479 if (ret < 0) {
1480 goto fail;
1482 buf += ret;
1483 buflen -= ret;
1485 /* Keep unknown header extensions */
1486 QLIST_FOREACH(uext, &s->unknown_header_ext, next) {
1487 ret = header_ext_add(buf, uext->magic, uext->data, uext->len, buflen);
1488 if (ret < 0) {
1489 goto fail;
1492 buf += ret;
1493 buflen -= ret;
1496 /* End of header extensions */
1497 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_END, NULL, 0, buflen);
1498 if (ret < 0) {
1499 goto fail;
1502 buf += ret;
1503 buflen -= ret;
1505 /* Backing file name */
1506 if (*bs->backing_file) {
1507 size_t backing_file_len = strlen(bs->backing_file);
1509 if (buflen < backing_file_len) {
1510 ret = -ENOSPC;
1511 goto fail;
1514 /* Using strncpy is ok here, since buf is not NUL-terminated. */
1515 strncpy(buf, bs->backing_file, buflen);
1517 header->backing_file_offset = cpu_to_be64(buf - ((char*) header));
1518 header->backing_file_size = cpu_to_be32(backing_file_len);
1521 /* Write the new header */
1522 ret = bdrv_pwrite(bs->file, 0, header, s->cluster_size);
1523 if (ret < 0) {
1524 goto fail;
1527 ret = 0;
1528 fail:
1529 qemu_vfree(header);
1530 return ret;
1533 static int qcow2_change_backing_file(BlockDriverState *bs,
1534 const char *backing_file, const char *backing_fmt)
1536 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
1537 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
1539 return qcow2_update_header(bs);
1542 static int preallocate(BlockDriverState *bs)
1544 uint64_t nb_sectors;
1545 uint64_t offset;
1546 uint64_t host_offset = 0;
1547 int num;
1548 int ret;
1549 QCowL2Meta *meta;
1551 nb_sectors = bdrv_getlength(bs) >> BDRV_SECTOR_BITS;
1552 offset = 0;
1554 while (nb_sectors) {
1555 num = MIN(nb_sectors, INT_MAX >> BDRV_SECTOR_BITS);
1556 ret = qcow2_alloc_cluster_offset(bs, offset, &num,
1557 &host_offset, &meta);
1558 if (ret < 0) {
1559 return ret;
1562 while (meta) {
1563 QCowL2Meta *next = meta->next;
1565 ret = qcow2_alloc_cluster_link_l2(bs, meta);
1566 if (ret < 0) {
1567 qcow2_free_any_clusters(bs, meta->alloc_offset,
1568 meta->nb_clusters, QCOW2_DISCARD_NEVER);
1569 return ret;
1572 /* There are no dependent requests, but we need to remove our
1573 * request from the list of in-flight requests */
1574 QLIST_REMOVE(meta, next_in_flight);
1576 g_free(meta);
1577 meta = next;
1580 /* TODO Preallocate data if requested */
1582 nb_sectors -= num;
1583 offset += num << BDRV_SECTOR_BITS;
1587 * It is expected that the image file is large enough to actually contain
1588 * all of the allocated clusters (otherwise we get failing reads after
1589 * EOF). Extend the image to the last allocated sector.
1591 if (host_offset != 0) {
1592 uint8_t buf[BDRV_SECTOR_SIZE];
1593 memset(buf, 0, BDRV_SECTOR_SIZE);
1594 ret = bdrv_write(bs->file, (host_offset >> BDRV_SECTOR_BITS) + num - 1,
1595 buf, 1);
1596 if (ret < 0) {
1597 return ret;
1601 return 0;
1604 static int qcow2_create2(const char *filename, int64_t total_size,
1605 const char *backing_file, const char *backing_format,
1606 int flags, size_t cluster_size, int prealloc,
1607 QemuOpts *opts, int version,
1608 Error **errp)
1610 /* Calculate cluster_bits */
1611 int cluster_bits;
1612 cluster_bits = ffs(cluster_size) - 1;
1613 if (cluster_bits < MIN_CLUSTER_BITS || cluster_bits > MAX_CLUSTER_BITS ||
1614 (1 << cluster_bits) != cluster_size)
1616 error_setg(errp, "Cluster size must be a power of two between %d and "
1617 "%dk", 1 << MIN_CLUSTER_BITS, 1 << (MAX_CLUSTER_BITS - 10));
1618 return -EINVAL;
1622 * Open the image file and write a minimal qcow2 header.
1624 * We keep things simple and start with a zero-sized image. We also
1625 * do without refcount blocks or a L1 table for now. We'll fix the
1626 * inconsistency later.
1628 * We do need a refcount table because growing the refcount table means
1629 * allocating two new refcount blocks - the seconds of which would be at
1630 * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
1631 * size for any qcow2 image.
1633 BlockDriverState* bs;
1634 QCowHeader *header;
1635 uint64_t* refcount_table;
1636 Error *local_err = NULL;
1637 int ret;
1639 ret = bdrv_create_file(filename, opts, &local_err);
1640 if (ret < 0) {
1641 error_propagate(errp, local_err);
1642 return ret;
1645 bs = NULL;
1646 ret = bdrv_open(&bs, filename, NULL, NULL, BDRV_O_RDWR | BDRV_O_PROTOCOL,
1647 NULL, &local_err);
1648 if (ret < 0) {
1649 error_propagate(errp, local_err);
1650 return ret;
1653 /* Write the header */
1654 QEMU_BUILD_BUG_ON((1 << MIN_CLUSTER_BITS) < sizeof(*header));
1655 header = g_malloc0(cluster_size);
1656 *header = (QCowHeader) {
1657 .magic = cpu_to_be32(QCOW_MAGIC),
1658 .version = cpu_to_be32(version),
1659 .cluster_bits = cpu_to_be32(cluster_bits),
1660 .size = cpu_to_be64(0),
1661 .l1_table_offset = cpu_to_be64(0),
1662 .l1_size = cpu_to_be32(0),
1663 .refcount_table_offset = cpu_to_be64(cluster_size),
1664 .refcount_table_clusters = cpu_to_be32(1),
1665 .refcount_order = cpu_to_be32(3 + REFCOUNT_SHIFT),
1666 .header_length = cpu_to_be32(sizeof(*header)),
1669 if (flags & BLOCK_FLAG_ENCRYPT) {
1670 header->crypt_method = cpu_to_be32(QCOW_CRYPT_AES);
1671 } else {
1672 header->crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
1675 if (flags & BLOCK_FLAG_LAZY_REFCOUNTS) {
1676 header->compatible_features |=
1677 cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS);
1680 ret = bdrv_pwrite(bs, 0, header, cluster_size);
1681 g_free(header);
1682 if (ret < 0) {
1683 error_setg_errno(errp, -ret, "Could not write qcow2 header");
1684 goto out;
1687 /* Write a refcount table with one refcount block */
1688 refcount_table = g_malloc0(2 * cluster_size);
1689 refcount_table[0] = cpu_to_be64(2 * cluster_size);
1690 ret = bdrv_pwrite(bs, cluster_size, refcount_table, 2 * cluster_size);
1691 g_free(refcount_table);
1693 if (ret < 0) {
1694 error_setg_errno(errp, -ret, "Could not write refcount table");
1695 goto out;
1698 bdrv_unref(bs);
1699 bs = NULL;
1702 * And now open the image and make it consistent first (i.e. increase the
1703 * refcount of the cluster that is occupied by the header and the refcount
1704 * table)
1706 BlockDriver* drv = bdrv_find_format("qcow2");
1707 assert(drv != NULL);
1708 ret = bdrv_open(&bs, filename, NULL, NULL,
1709 BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_NO_FLUSH, drv, &local_err);
1710 if (ret < 0) {
1711 error_propagate(errp, local_err);
1712 goto out;
1715 ret = qcow2_alloc_clusters(bs, 3 * cluster_size);
1716 if (ret < 0) {
1717 error_setg_errno(errp, -ret, "Could not allocate clusters for qcow2 "
1718 "header and refcount table");
1719 goto out;
1721 } else if (ret != 0) {
1722 error_report("Huh, first cluster in empty image is already in use?");
1723 abort();
1726 /* Okay, now that we have a valid image, let's give it the right size */
1727 ret = bdrv_truncate(bs, total_size * BDRV_SECTOR_SIZE);
1728 if (ret < 0) {
1729 error_setg_errno(errp, -ret, "Could not resize image");
1730 goto out;
1733 /* Want a backing file? There you go.*/
1734 if (backing_file) {
1735 ret = bdrv_change_backing_file(bs, backing_file, backing_format);
1736 if (ret < 0) {
1737 error_setg_errno(errp, -ret, "Could not assign backing file '%s' "
1738 "with format '%s'", backing_file, backing_format);
1739 goto out;
1743 /* And if we're supposed to preallocate metadata, do that now */
1744 if (prealloc) {
1745 BDRVQcowState *s = bs->opaque;
1746 qemu_co_mutex_lock(&s->lock);
1747 ret = preallocate(bs);
1748 qemu_co_mutex_unlock(&s->lock);
1749 if (ret < 0) {
1750 error_setg_errno(errp, -ret, "Could not preallocate metadata");
1751 goto out;
1755 bdrv_unref(bs);
1756 bs = NULL;
1758 /* Reopen the image without BDRV_O_NO_FLUSH to flush it before returning */
1759 ret = bdrv_open(&bs, filename, NULL, NULL,
1760 BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_NO_BACKING,
1761 drv, &local_err);
1762 if (local_err) {
1763 error_propagate(errp, local_err);
1764 goto out;
1767 ret = 0;
1768 out:
1769 if (bs) {
1770 bdrv_unref(bs);
1772 return ret;
1775 static int qcow2_create(const char *filename, QemuOpts *opts, Error **errp)
1777 char *backing_file = NULL;
1778 char *backing_fmt = NULL;
1779 char *buf = NULL;
1780 uint64_t sectors = 0;
1781 int flags = 0;
1782 size_t cluster_size = DEFAULT_CLUSTER_SIZE;
1783 int prealloc = 0;
1784 int version = 3;
1785 Error *local_err = NULL;
1786 int ret;
1788 /* Read out options */
1789 sectors = qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0) / 512;
1790 backing_file = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
1791 backing_fmt = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FMT);
1792 if (qemu_opt_get_bool_del(opts, BLOCK_OPT_ENCRYPT, false)) {
1793 flags |= BLOCK_FLAG_ENCRYPT;
1795 cluster_size = qemu_opt_get_size_del(opts, BLOCK_OPT_CLUSTER_SIZE,
1796 DEFAULT_CLUSTER_SIZE);
1797 buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
1798 if (!buf || !strcmp(buf, "off")) {
1799 prealloc = 0;
1800 } else if (!strcmp(buf, "metadata")) {
1801 prealloc = 1;
1802 } else {
1803 error_setg(errp, "Invalid preallocation mode: '%s'", buf);
1804 ret = -EINVAL;
1805 goto finish;
1807 g_free(buf);
1808 buf = qemu_opt_get_del(opts, BLOCK_OPT_COMPAT_LEVEL);
1809 if (!buf) {
1810 /* keep the default */
1811 } else if (!strcmp(buf, "0.10")) {
1812 version = 2;
1813 } else if (!strcmp(buf, "1.1")) {
1814 version = 3;
1815 } else {
1816 error_setg(errp, "Invalid compatibility level: '%s'", buf);
1817 ret = -EINVAL;
1818 goto finish;
1821 if (qemu_opt_get_bool_del(opts, BLOCK_OPT_LAZY_REFCOUNTS, false)) {
1822 flags |= BLOCK_FLAG_LAZY_REFCOUNTS;
1825 if (backing_file && prealloc) {
1826 error_setg(errp, "Backing file and preallocation cannot be used at "
1827 "the same time");
1828 ret = -EINVAL;
1829 goto finish;
1832 if (version < 3 && (flags & BLOCK_FLAG_LAZY_REFCOUNTS)) {
1833 error_setg(errp, "Lazy refcounts only supported with compatibility "
1834 "level 1.1 and above (use compat=1.1 or greater)");
1835 ret = -EINVAL;
1836 goto finish;
1839 ret = qcow2_create2(filename, sectors, backing_file, backing_fmt, flags,
1840 cluster_size, prealloc, opts, version, &local_err);
1841 if (local_err) {
1842 error_propagate(errp, local_err);
1845 finish:
1846 g_free(backing_file);
1847 g_free(backing_fmt);
1848 g_free(buf);
1849 return ret;
1852 static coroutine_fn int qcow2_co_write_zeroes(BlockDriverState *bs,
1853 int64_t sector_num, int nb_sectors, BdrvRequestFlags flags)
1855 int ret;
1856 BDRVQcowState *s = bs->opaque;
1858 /* Emulate misaligned zero writes */
1859 if (sector_num % s->cluster_sectors || nb_sectors % s->cluster_sectors) {
1860 return -ENOTSUP;
1863 /* Whatever is left can use real zero clusters */
1864 qemu_co_mutex_lock(&s->lock);
1865 ret = qcow2_zero_clusters(bs, sector_num << BDRV_SECTOR_BITS,
1866 nb_sectors);
1867 qemu_co_mutex_unlock(&s->lock);
1869 return ret;
1872 static coroutine_fn int qcow2_co_discard(BlockDriverState *bs,
1873 int64_t sector_num, int nb_sectors)
1875 int ret;
1876 BDRVQcowState *s = bs->opaque;
1878 qemu_co_mutex_lock(&s->lock);
1879 ret = qcow2_discard_clusters(bs, sector_num << BDRV_SECTOR_BITS,
1880 nb_sectors, QCOW2_DISCARD_REQUEST);
1881 qemu_co_mutex_unlock(&s->lock);
1882 return ret;
1885 static int qcow2_truncate(BlockDriverState *bs, int64_t offset)
1887 BDRVQcowState *s = bs->opaque;
1888 int64_t new_l1_size;
1889 int ret;
1891 if (offset & 511) {
1892 error_report("The new size must be a multiple of 512");
1893 return -EINVAL;
1896 /* cannot proceed if image has snapshots */
1897 if (s->nb_snapshots) {
1898 error_report("Can't resize an image which has snapshots");
1899 return -ENOTSUP;
1902 /* shrinking is currently not supported */
1903 if (offset < bs->total_sectors * 512) {
1904 error_report("qcow2 doesn't support shrinking images yet");
1905 return -ENOTSUP;
1908 new_l1_size = size_to_l1(s, offset);
1909 ret = qcow2_grow_l1_table(bs, new_l1_size, true);
1910 if (ret < 0) {
1911 return ret;
1914 /* write updated header.size */
1915 offset = cpu_to_be64(offset);
1916 ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, size),
1917 &offset, sizeof(uint64_t));
1918 if (ret < 0) {
1919 return ret;
1922 s->l1_vm_state_index = new_l1_size;
1923 return 0;
1926 /* XXX: put compressed sectors first, then all the cluster aligned
1927 tables to avoid losing bytes in alignment */
1928 static int qcow2_write_compressed(BlockDriverState *bs, int64_t sector_num,
1929 const uint8_t *buf, int nb_sectors)
1931 BDRVQcowState *s = bs->opaque;
1932 z_stream strm;
1933 int ret, out_len;
1934 uint8_t *out_buf;
1935 uint64_t cluster_offset;
1937 if (nb_sectors == 0) {
1938 /* align end of file to a sector boundary to ease reading with
1939 sector based I/Os */
1940 cluster_offset = bdrv_getlength(bs->file);
1941 cluster_offset = (cluster_offset + 511) & ~511;
1942 bdrv_truncate(bs->file, cluster_offset);
1943 return 0;
1946 if (nb_sectors != s->cluster_sectors) {
1947 ret = -EINVAL;
1949 /* Zero-pad last write if image size is not cluster aligned */
1950 if (sector_num + nb_sectors == bs->total_sectors &&
1951 nb_sectors < s->cluster_sectors) {
1952 uint8_t *pad_buf = qemu_blockalign(bs, s->cluster_size);
1953 memset(pad_buf, 0, s->cluster_size);
1954 memcpy(pad_buf, buf, nb_sectors * BDRV_SECTOR_SIZE);
1955 ret = qcow2_write_compressed(bs, sector_num,
1956 pad_buf, s->cluster_sectors);
1957 qemu_vfree(pad_buf);
1959 return ret;
1962 out_buf = g_malloc(s->cluster_size + (s->cluster_size / 1000) + 128);
1964 /* best compression, small window, no zlib header */
1965 memset(&strm, 0, sizeof(strm));
1966 ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
1967 Z_DEFLATED, -12,
1968 9, Z_DEFAULT_STRATEGY);
1969 if (ret != 0) {
1970 ret = -EINVAL;
1971 goto fail;
1974 strm.avail_in = s->cluster_size;
1975 strm.next_in = (uint8_t *)buf;
1976 strm.avail_out = s->cluster_size;
1977 strm.next_out = out_buf;
1979 ret = deflate(&strm, Z_FINISH);
1980 if (ret != Z_STREAM_END && ret != Z_OK) {
1981 deflateEnd(&strm);
1982 ret = -EINVAL;
1983 goto fail;
1985 out_len = strm.next_out - out_buf;
1987 deflateEnd(&strm);
1989 if (ret != Z_STREAM_END || out_len >= s->cluster_size) {
1990 /* could not compress: write normal cluster */
1991 ret = bdrv_write(bs, sector_num, buf, s->cluster_sectors);
1992 if (ret < 0) {
1993 goto fail;
1995 } else {
1996 cluster_offset = qcow2_alloc_compressed_cluster_offset(bs,
1997 sector_num << 9, out_len);
1998 if (!cluster_offset) {
1999 ret = -EIO;
2000 goto fail;
2002 cluster_offset &= s->cluster_offset_mask;
2004 ret = qcow2_pre_write_overlap_check(bs, 0, cluster_offset, out_len);
2005 if (ret < 0) {
2006 goto fail;
2009 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_COMPRESSED);
2010 ret = bdrv_pwrite(bs->file, cluster_offset, out_buf, out_len);
2011 if (ret < 0) {
2012 goto fail;
2016 ret = 0;
2017 fail:
2018 g_free(out_buf);
2019 return ret;
2022 static coroutine_fn int qcow2_co_flush_to_os(BlockDriverState *bs)
2024 BDRVQcowState *s = bs->opaque;
2025 int ret;
2027 qemu_co_mutex_lock(&s->lock);
2028 ret = qcow2_cache_flush(bs, s->l2_table_cache);
2029 if (ret < 0) {
2030 qemu_co_mutex_unlock(&s->lock);
2031 return ret;
2034 if (qcow2_need_accurate_refcounts(s)) {
2035 ret = qcow2_cache_flush(bs, s->refcount_block_cache);
2036 if (ret < 0) {
2037 qemu_co_mutex_unlock(&s->lock);
2038 return ret;
2041 qemu_co_mutex_unlock(&s->lock);
2043 return 0;
2046 static int qcow2_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
2048 BDRVQcowState *s = bs->opaque;
2049 bdi->unallocated_blocks_are_zero = true;
2050 bdi->can_write_zeroes_with_unmap = (s->qcow_version >= 3);
2051 bdi->cluster_size = s->cluster_size;
2052 bdi->vm_state_offset = qcow2_vm_state_offset(s);
2053 return 0;
2056 static ImageInfoSpecific *qcow2_get_specific_info(BlockDriverState *bs)
2058 BDRVQcowState *s = bs->opaque;
2059 ImageInfoSpecific *spec_info = g_new(ImageInfoSpecific, 1);
2061 *spec_info = (ImageInfoSpecific){
2062 .kind = IMAGE_INFO_SPECIFIC_KIND_QCOW2,
2064 .qcow2 = g_new(ImageInfoSpecificQCow2, 1),
2067 if (s->qcow_version == 2) {
2068 *spec_info->qcow2 = (ImageInfoSpecificQCow2){
2069 .compat = g_strdup("0.10"),
2071 } else if (s->qcow_version == 3) {
2072 *spec_info->qcow2 = (ImageInfoSpecificQCow2){
2073 .compat = g_strdup("1.1"),
2074 .lazy_refcounts = s->compatible_features &
2075 QCOW2_COMPAT_LAZY_REFCOUNTS,
2076 .has_lazy_refcounts = true,
2080 return spec_info;
2083 #if 0
2084 static void dump_refcounts(BlockDriverState *bs)
2086 BDRVQcowState *s = bs->opaque;
2087 int64_t nb_clusters, k, k1, size;
2088 int refcount;
2090 size = bdrv_getlength(bs->file);
2091 nb_clusters = size_to_clusters(s, size);
2092 for(k = 0; k < nb_clusters;) {
2093 k1 = k;
2094 refcount = get_refcount(bs, k);
2095 k++;
2096 while (k < nb_clusters && get_refcount(bs, k) == refcount)
2097 k++;
2098 printf("%" PRId64 ": refcount=%d nb=%" PRId64 "\n", k, refcount,
2099 k - k1);
2102 #endif
2104 static int qcow2_save_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
2105 int64_t pos)
2107 BDRVQcowState *s = bs->opaque;
2108 int64_t total_sectors = bs->total_sectors;
2109 int growable = bs->growable;
2110 bool zero_beyond_eof = bs->zero_beyond_eof;
2111 int ret;
2113 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_SAVE);
2114 bs->growable = 1;
2115 bs->zero_beyond_eof = false;
2116 ret = bdrv_pwritev(bs, qcow2_vm_state_offset(s) + pos, qiov);
2117 bs->growable = growable;
2118 bs->zero_beyond_eof = zero_beyond_eof;
2120 /* bdrv_co_do_writev will have increased the total_sectors value to include
2121 * the VM state - the VM state is however not an actual part of the block
2122 * device, therefore, we need to restore the old value. */
2123 bs->total_sectors = total_sectors;
2125 return ret;
2128 static int qcow2_load_vmstate(BlockDriverState *bs, uint8_t *buf,
2129 int64_t pos, int size)
2131 BDRVQcowState *s = bs->opaque;
2132 int growable = bs->growable;
2133 bool zero_beyond_eof = bs->zero_beyond_eof;
2134 int ret;
2136 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_LOAD);
2137 bs->growable = 1;
2138 bs->zero_beyond_eof = false;
2139 ret = bdrv_pread(bs, qcow2_vm_state_offset(s) + pos, buf, size);
2140 bs->growable = growable;
2141 bs->zero_beyond_eof = zero_beyond_eof;
2143 return ret;
2147 * Downgrades an image's version. To achieve this, any incompatible features
2148 * have to be removed.
2150 static int qcow2_downgrade(BlockDriverState *bs, int target_version)
2152 BDRVQcowState *s = bs->opaque;
2153 int current_version = s->qcow_version;
2154 int ret;
2156 if (target_version == current_version) {
2157 return 0;
2158 } else if (target_version > current_version) {
2159 return -EINVAL;
2160 } else if (target_version != 2) {
2161 return -EINVAL;
2164 if (s->refcount_order != 4) {
2165 /* we would have to convert the image to a refcount_order == 4 image
2166 * here; however, since qemu (at the time of writing this) does not
2167 * support anything different than 4 anyway, there is no point in doing
2168 * so right now; however, we should error out (if qemu supports this in
2169 * the future and this code has not been adapted) */
2170 error_report("qcow2_downgrade: Image refcount orders other than 4 are "
2171 "currently not supported.");
2172 return -ENOTSUP;
2175 /* clear incompatible features */
2176 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
2177 ret = qcow2_mark_clean(bs);
2178 if (ret < 0) {
2179 return ret;
2183 /* with QCOW2_INCOMPAT_CORRUPT, it is pretty much impossible to get here in
2184 * the first place; if that happens nonetheless, returning -ENOTSUP is the
2185 * best thing to do anyway */
2187 if (s->incompatible_features) {
2188 return -ENOTSUP;
2191 /* since we can ignore compatible features, we can set them to 0 as well */
2192 s->compatible_features = 0;
2193 /* if lazy refcounts have been used, they have already been fixed through
2194 * clearing the dirty flag */
2196 /* clearing autoclear features is trivial */
2197 s->autoclear_features = 0;
2199 ret = qcow2_expand_zero_clusters(bs);
2200 if (ret < 0) {
2201 return ret;
2204 s->qcow_version = target_version;
2205 ret = qcow2_update_header(bs);
2206 if (ret < 0) {
2207 s->qcow_version = current_version;
2208 return ret;
2210 return 0;
2213 static int qcow2_amend_options(BlockDriverState *bs, QemuOpts *opts)
2215 BDRVQcowState *s = bs->opaque;
2216 int old_version = s->qcow_version, new_version = old_version;
2217 uint64_t new_size = 0;
2218 const char *backing_file = NULL, *backing_format = NULL;
2219 bool lazy_refcounts = s->use_lazy_refcounts;
2220 const char *compat = NULL;
2221 uint64_t cluster_size = s->cluster_size;
2222 bool encrypt;
2223 int ret;
2224 QemuOptDesc *desc = opts->list->desc;
2226 while (desc && desc->name) {
2227 if (!qemu_opt_find(opts, desc->name)) {
2228 /* only change explicitly defined options */
2229 desc++;
2230 continue;
2233 if (!strcmp(desc->name, "compat")) {
2234 compat = qemu_opt_get(opts, "compat");
2235 if (!compat) {
2236 /* preserve default */
2237 } else if (!strcmp(compat, "0.10")) {
2238 new_version = 2;
2239 } else if (!strcmp(compat, "1.1")) {
2240 new_version = 3;
2241 } else {
2242 fprintf(stderr, "Unknown compatibility level %s.\n", compat);
2243 return -EINVAL;
2245 } else if (!strcmp(desc->name, "preallocation")) {
2246 fprintf(stderr, "Cannot change preallocation mode.\n");
2247 return -ENOTSUP;
2248 } else if (!strcmp(desc->name, "size")) {
2249 new_size = qemu_opt_get_size(opts, "size", 0);
2250 } else if (!strcmp(desc->name, "backing_file")) {
2251 backing_file = qemu_opt_get(opts, "backing_file");
2252 } else if (!strcmp(desc->name, "backing_fmt")) {
2253 backing_format = qemu_opt_get(opts, "backing_fmt");
2254 } else if (!strcmp(desc->name, "encryption")) {
2255 encrypt = qemu_opt_get_bool(opts, "encryption", s->crypt_method);
2256 if (encrypt != !!s->crypt_method) {
2257 fprintf(stderr, "Changing the encryption flag is not "
2258 "supported.\n");
2259 return -ENOTSUP;
2261 } else if (!strcmp(desc->name, "cluster_size")) {
2262 cluster_size = qemu_opt_get_size(opts, "cluster_size",
2263 cluster_size);
2264 if (cluster_size != s->cluster_size) {
2265 fprintf(stderr, "Changing the cluster size is not "
2266 "supported.\n");
2267 return -ENOTSUP;
2269 } else if (!strcmp(desc->name, "lazy_refcounts")) {
2270 lazy_refcounts = qemu_opt_get_bool(opts, "lazy_refcounts",
2271 lazy_refcounts);
2272 } else {
2273 /* if this assertion fails, this probably means a new option was
2274 * added without having it covered here */
2275 assert(false);
2278 desc++;
2281 if (new_version != old_version) {
2282 if (new_version > old_version) {
2283 /* Upgrade */
2284 s->qcow_version = new_version;
2285 ret = qcow2_update_header(bs);
2286 if (ret < 0) {
2287 s->qcow_version = old_version;
2288 return ret;
2290 } else {
2291 ret = qcow2_downgrade(bs, new_version);
2292 if (ret < 0) {
2293 return ret;
2298 if (backing_file || backing_format) {
2299 ret = qcow2_change_backing_file(bs, backing_file ?: bs->backing_file,
2300 backing_format ?: bs->backing_format);
2301 if (ret < 0) {
2302 return ret;
2306 if (s->use_lazy_refcounts != lazy_refcounts) {
2307 if (lazy_refcounts) {
2308 if (s->qcow_version < 3) {
2309 fprintf(stderr, "Lazy refcounts only supported with compatibility "
2310 "level 1.1 and above (use compat=1.1 or greater)\n");
2311 return -EINVAL;
2313 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
2314 ret = qcow2_update_header(bs);
2315 if (ret < 0) {
2316 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
2317 return ret;
2319 s->use_lazy_refcounts = true;
2320 } else {
2321 /* make image clean first */
2322 ret = qcow2_mark_clean(bs);
2323 if (ret < 0) {
2324 return ret;
2326 /* now disallow lazy refcounts */
2327 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
2328 ret = qcow2_update_header(bs);
2329 if (ret < 0) {
2330 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
2331 return ret;
2333 s->use_lazy_refcounts = false;
2337 if (new_size) {
2338 ret = bdrv_truncate(bs, new_size);
2339 if (ret < 0) {
2340 return ret;
2344 return 0;
2347 static QemuOptsList qcow2_create_opts = {
2348 .name = "qcow2-create-opts",
2349 .head = QTAILQ_HEAD_INITIALIZER(qcow2_create_opts.head),
2350 .desc = {
2352 .name = BLOCK_OPT_SIZE,
2353 .type = QEMU_OPT_SIZE,
2354 .help = "Virtual disk size"
2357 .name = BLOCK_OPT_COMPAT_LEVEL,
2358 .type = QEMU_OPT_STRING,
2359 .help = "Compatibility level (0.10 or 1.1)"
2362 .name = BLOCK_OPT_BACKING_FILE,
2363 .type = QEMU_OPT_STRING,
2364 .help = "File name of a base image"
2367 .name = BLOCK_OPT_BACKING_FMT,
2368 .type = QEMU_OPT_STRING,
2369 .help = "Image format of the base image"
2372 .name = BLOCK_OPT_ENCRYPT,
2373 .type = QEMU_OPT_BOOL,
2374 .help = "Encrypt the image",
2375 .def_value_str = "off"
2378 .name = BLOCK_OPT_CLUSTER_SIZE,
2379 .type = QEMU_OPT_SIZE,
2380 .help = "qcow2 cluster size",
2381 .def_value_str = stringify(DEFAULT_CLUSTER_SIZE)
2384 .name = BLOCK_OPT_PREALLOC,
2385 .type = QEMU_OPT_STRING,
2386 .help = "Preallocation mode (allowed values: off, metadata)"
2389 .name = BLOCK_OPT_LAZY_REFCOUNTS,
2390 .type = QEMU_OPT_BOOL,
2391 .help = "Postpone refcount updates",
2392 .def_value_str = "off"
2394 { /* end of list */ }
2398 static BlockDriver bdrv_qcow2 = {
2399 .format_name = "qcow2",
2400 .instance_size = sizeof(BDRVQcowState),
2401 .bdrv_probe = qcow2_probe,
2402 .bdrv_open = qcow2_open,
2403 .bdrv_close = qcow2_close,
2404 .bdrv_reopen_prepare = qcow2_reopen_prepare,
2405 .bdrv_create = qcow2_create,
2406 .bdrv_has_zero_init = bdrv_has_zero_init_1,
2407 .bdrv_co_get_block_status = qcow2_co_get_block_status,
2408 .bdrv_set_key = qcow2_set_key,
2410 .bdrv_co_readv = qcow2_co_readv,
2411 .bdrv_co_writev = qcow2_co_writev,
2412 .bdrv_co_flush_to_os = qcow2_co_flush_to_os,
2414 .bdrv_co_write_zeroes = qcow2_co_write_zeroes,
2415 .bdrv_co_discard = qcow2_co_discard,
2416 .bdrv_truncate = qcow2_truncate,
2417 .bdrv_write_compressed = qcow2_write_compressed,
2419 .bdrv_snapshot_create = qcow2_snapshot_create,
2420 .bdrv_snapshot_goto = qcow2_snapshot_goto,
2421 .bdrv_snapshot_delete = qcow2_snapshot_delete,
2422 .bdrv_snapshot_list = qcow2_snapshot_list,
2423 .bdrv_snapshot_load_tmp = qcow2_snapshot_load_tmp,
2424 .bdrv_get_info = qcow2_get_info,
2425 .bdrv_get_specific_info = qcow2_get_specific_info,
2427 .bdrv_save_vmstate = qcow2_save_vmstate,
2428 .bdrv_load_vmstate = qcow2_load_vmstate,
2430 .supports_backing = true,
2431 .bdrv_change_backing_file = qcow2_change_backing_file,
2433 .bdrv_refresh_limits = qcow2_refresh_limits,
2434 .bdrv_invalidate_cache = qcow2_invalidate_cache,
2436 .create_opts = &qcow2_create_opts,
2437 .bdrv_check = qcow2_check,
2438 .bdrv_amend_options = qcow2_amend_options,
2441 static void bdrv_qcow2_init(void)
2443 bdrv_register(&bdrv_qcow2);
2446 block_init(bdrv_qcow2_init);