Merge remote-tracking branch 'remotes/ehabkost/tags/work/numa-verify-cpus-pull-reques...
[qemu/ar7.git] / block / qcow2.c
blob32bdf756cabc33a55a249a9065cffdbbcf200597
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 "qapi/util.h"
34 #include "qapi/qmp/types.h"
35 #include "qapi-event.h"
36 #include "trace.h"
37 #include "qemu/option_int.h"
40 Differences with QCOW:
42 - Support for multiple incremental snapshots.
43 - Memory management by reference counts.
44 - Clusters which have a reference count of one have the bit
45 QCOW_OFLAG_COPIED to optimize write performance.
46 - Size of compressed clusters is stored in sectors to reduce bit usage
47 in the cluster offsets.
48 - Support for storing additional data (such as the VM state) in the
49 snapshots.
50 - If a backing store is used, the cluster size is not constrained
51 (could be backported to QCOW).
52 - L2 tables have always a size of one cluster.
56 typedef struct {
57 uint32_t magic;
58 uint32_t len;
59 } QEMU_PACKED QCowExtension;
61 #define QCOW2_EXT_MAGIC_END 0
62 #define QCOW2_EXT_MAGIC_BACKING_FORMAT 0xE2792ACA
63 #define QCOW2_EXT_MAGIC_FEATURE_TABLE 0x6803f857
65 static int qcow2_probe(const uint8_t *buf, int buf_size, const char *filename)
67 const QCowHeader *cow_header = (const void *)buf;
69 if (buf_size >= sizeof(QCowHeader) &&
70 be32_to_cpu(cow_header->magic) == QCOW_MAGIC &&
71 be32_to_cpu(cow_header->version) >= 2)
72 return 100;
73 else
74 return 0;
78 /*
79 * read qcow2 extension and fill bs
80 * start reading from start_offset
81 * finish reading upon magic of value 0 or when end_offset reached
82 * unknown magic is skipped (future extension this version knows nothing about)
83 * return 0 upon success, non-0 otherwise
85 static int qcow2_read_extensions(BlockDriverState *bs, uint64_t start_offset,
86 uint64_t end_offset, void **p_feature_table,
87 Error **errp)
89 BDRVQcowState *s = bs->opaque;
90 QCowExtension ext;
91 uint64_t offset;
92 int ret;
94 #ifdef DEBUG_EXT
95 printf("qcow2_read_extensions: start=%ld end=%ld\n", start_offset, end_offset);
96 #endif
97 offset = start_offset;
98 while (offset < end_offset) {
100 #ifdef DEBUG_EXT
101 /* Sanity check */
102 if (offset > s->cluster_size)
103 printf("qcow2_read_extension: suspicious offset %lu\n", offset);
105 printf("attempting to read extended header in offset %lu\n", offset);
106 #endif
108 ret = bdrv_pread(bs->file, offset, &ext, sizeof(ext));
109 if (ret < 0) {
110 error_setg_errno(errp, -ret, "qcow2_read_extension: ERROR: "
111 "pread fail from offset %" PRIu64, offset);
112 return 1;
114 be32_to_cpus(&ext.magic);
115 be32_to_cpus(&ext.len);
116 offset += sizeof(ext);
117 #ifdef DEBUG_EXT
118 printf("ext.magic = 0x%x\n", ext.magic);
119 #endif
120 if (offset > end_offset || ext.len > end_offset - offset) {
121 error_setg(errp, "Header extension too large");
122 return -EINVAL;
125 switch (ext.magic) {
126 case QCOW2_EXT_MAGIC_END:
127 return 0;
129 case QCOW2_EXT_MAGIC_BACKING_FORMAT:
130 if (ext.len >= sizeof(bs->backing_format)) {
131 error_setg(errp, "ERROR: ext_backing_format: len=%" PRIu32
132 " too large (>=%zu)", ext.len,
133 sizeof(bs->backing_format));
134 return 2;
136 ret = bdrv_pread(bs->file, offset, bs->backing_format, ext.len);
137 if (ret < 0) {
138 error_setg_errno(errp, -ret, "ERROR: ext_backing_format: "
139 "Could not read format name");
140 return 3;
142 bs->backing_format[ext.len] = '\0';
143 #ifdef DEBUG_EXT
144 printf("Qcow2: Got format extension %s\n", bs->backing_format);
145 #endif
146 break;
148 case QCOW2_EXT_MAGIC_FEATURE_TABLE:
149 if (p_feature_table != NULL) {
150 void* feature_table = g_malloc0(ext.len + 2 * sizeof(Qcow2Feature));
151 ret = bdrv_pread(bs->file, offset , feature_table, ext.len);
152 if (ret < 0) {
153 error_setg_errno(errp, -ret, "ERROR: ext_feature_table: "
154 "Could not read table");
155 return ret;
158 *p_feature_table = feature_table;
160 break;
162 default:
163 /* unknown magic - save it in case we need to rewrite the header */
165 Qcow2UnknownHeaderExtension *uext;
167 uext = g_malloc0(sizeof(*uext) + ext.len);
168 uext->magic = ext.magic;
169 uext->len = ext.len;
170 QLIST_INSERT_HEAD(&s->unknown_header_ext, uext, next);
172 ret = bdrv_pread(bs->file, offset , uext->data, uext->len);
173 if (ret < 0) {
174 error_setg_errno(errp, -ret, "ERROR: unknown extension: "
175 "Could not read data");
176 return ret;
179 break;
182 offset += ((ext.len + 7) & ~7);
185 return 0;
188 static void cleanup_unknown_header_ext(BlockDriverState *bs)
190 BDRVQcowState *s = bs->opaque;
191 Qcow2UnknownHeaderExtension *uext, *next;
193 QLIST_FOREACH_SAFE(uext, &s->unknown_header_ext, next, next) {
194 QLIST_REMOVE(uext, next);
195 g_free(uext);
199 static void GCC_FMT_ATTR(3, 4) report_unsupported(BlockDriverState *bs,
200 Error **errp, const char *fmt, ...)
202 char msg[64];
203 va_list ap;
205 va_start(ap, fmt);
206 vsnprintf(msg, sizeof(msg), fmt, ap);
207 va_end(ap);
209 error_set(errp, QERR_UNKNOWN_BLOCK_FORMAT_FEATURE,
210 bdrv_get_device_name(bs), "qcow2", msg);
213 static void report_unsupported_feature(BlockDriverState *bs,
214 Error **errp, Qcow2Feature *table, uint64_t mask)
216 char *features = g_strdup("");
217 char *old;
219 while (table && table->name[0] != '\0') {
220 if (table->type == QCOW2_FEAT_TYPE_INCOMPATIBLE) {
221 if (mask & (1ULL << table->bit)) {
222 old = features;
223 features = g_strdup_printf("%s%s%.46s", old, *old ? ", " : "",
224 table->name);
225 g_free(old);
226 mask &= ~(1ULL << table->bit);
229 table++;
232 if (mask) {
233 old = features;
234 features = g_strdup_printf("%s%sUnknown incompatible feature: %" PRIx64,
235 old, *old ? ", " : "", mask);
236 g_free(old);
239 report_unsupported(bs, errp, "%s", features);
240 g_free(features);
244 * Sets the dirty bit and flushes afterwards if necessary.
246 * The incompatible_features bit is only set if the image file header was
247 * updated successfully. Therefore it is not required to check the return
248 * value of this function.
250 int qcow2_mark_dirty(BlockDriverState *bs)
252 BDRVQcowState *s = bs->opaque;
253 uint64_t val;
254 int ret;
256 assert(s->qcow_version >= 3);
258 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
259 return 0; /* already dirty */
262 val = cpu_to_be64(s->incompatible_features | QCOW2_INCOMPAT_DIRTY);
263 ret = bdrv_pwrite(bs->file, offsetof(QCowHeader, incompatible_features),
264 &val, sizeof(val));
265 if (ret < 0) {
266 return ret;
268 ret = bdrv_flush(bs->file);
269 if (ret < 0) {
270 return ret;
273 /* Only treat image as dirty if the header was updated successfully */
274 s->incompatible_features |= QCOW2_INCOMPAT_DIRTY;
275 return 0;
279 * Clears the dirty bit and flushes before if necessary. Only call this
280 * function when there are no pending requests, it does not guard against
281 * concurrent requests dirtying the image.
283 static int qcow2_mark_clean(BlockDriverState *bs)
285 BDRVQcowState *s = bs->opaque;
287 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
288 int ret;
290 s->incompatible_features &= ~QCOW2_INCOMPAT_DIRTY;
292 ret = bdrv_flush(bs);
293 if (ret < 0) {
294 return ret;
297 return qcow2_update_header(bs);
299 return 0;
303 * Marks the image as corrupt.
305 int qcow2_mark_corrupt(BlockDriverState *bs)
307 BDRVQcowState *s = bs->opaque;
309 s->incompatible_features |= QCOW2_INCOMPAT_CORRUPT;
310 return qcow2_update_header(bs);
314 * Marks the image as consistent, i.e., unsets the corrupt bit, and flushes
315 * before if necessary.
317 int qcow2_mark_consistent(BlockDriverState *bs)
319 BDRVQcowState *s = bs->opaque;
321 if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
322 int ret = bdrv_flush(bs);
323 if (ret < 0) {
324 return ret;
327 s->incompatible_features &= ~QCOW2_INCOMPAT_CORRUPT;
328 return qcow2_update_header(bs);
330 return 0;
333 static int qcow2_check(BlockDriverState *bs, BdrvCheckResult *result,
334 BdrvCheckMode fix)
336 int ret = qcow2_check_refcounts(bs, result, fix);
337 if (ret < 0) {
338 return ret;
341 if (fix && result->check_errors == 0 && result->corruptions == 0) {
342 ret = qcow2_mark_clean(bs);
343 if (ret < 0) {
344 return ret;
346 return qcow2_mark_consistent(bs);
348 return ret;
351 static int validate_table_offset(BlockDriverState *bs, uint64_t offset,
352 uint64_t entries, size_t entry_len)
354 BDRVQcowState *s = bs->opaque;
355 uint64_t size;
357 /* Use signed INT64_MAX as the maximum even for uint64_t header fields,
358 * because values will be passed to qemu functions taking int64_t. */
359 if (entries > INT64_MAX / entry_len) {
360 return -EINVAL;
363 size = entries * entry_len;
365 if (INT64_MAX - size < offset) {
366 return -EINVAL;
369 /* Tables must be cluster aligned */
370 if (offset & (s->cluster_size - 1)) {
371 return -EINVAL;
374 return 0;
377 static QemuOptsList qcow2_runtime_opts = {
378 .name = "qcow2",
379 .head = QTAILQ_HEAD_INITIALIZER(qcow2_runtime_opts.head),
380 .desc = {
382 .name = QCOW2_OPT_LAZY_REFCOUNTS,
383 .type = QEMU_OPT_BOOL,
384 .help = "Postpone refcount updates",
387 .name = QCOW2_OPT_DISCARD_REQUEST,
388 .type = QEMU_OPT_BOOL,
389 .help = "Pass guest discard requests to the layer below",
392 .name = QCOW2_OPT_DISCARD_SNAPSHOT,
393 .type = QEMU_OPT_BOOL,
394 .help = "Generate discard requests when snapshot related space "
395 "is freed",
398 .name = QCOW2_OPT_DISCARD_OTHER,
399 .type = QEMU_OPT_BOOL,
400 .help = "Generate discard requests when other clusters are freed",
403 .name = QCOW2_OPT_OVERLAP,
404 .type = QEMU_OPT_STRING,
405 .help = "Selects which overlap checks to perform from a range of "
406 "templates (none, constant, cached, all)",
409 .name = QCOW2_OPT_OVERLAP_TEMPLATE,
410 .type = QEMU_OPT_STRING,
411 .help = "Selects which overlap checks to perform from a range of "
412 "templates (none, constant, cached, all)",
415 .name = QCOW2_OPT_OVERLAP_MAIN_HEADER,
416 .type = QEMU_OPT_BOOL,
417 .help = "Check for unintended writes into the main qcow2 header",
420 .name = QCOW2_OPT_OVERLAP_ACTIVE_L1,
421 .type = QEMU_OPT_BOOL,
422 .help = "Check for unintended writes into the active L1 table",
425 .name = QCOW2_OPT_OVERLAP_ACTIVE_L2,
426 .type = QEMU_OPT_BOOL,
427 .help = "Check for unintended writes into an active L2 table",
430 .name = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
431 .type = QEMU_OPT_BOOL,
432 .help = "Check for unintended writes into the refcount table",
435 .name = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
436 .type = QEMU_OPT_BOOL,
437 .help = "Check for unintended writes into a refcount block",
440 .name = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
441 .type = QEMU_OPT_BOOL,
442 .help = "Check for unintended writes into the snapshot table",
445 .name = QCOW2_OPT_OVERLAP_INACTIVE_L1,
446 .type = QEMU_OPT_BOOL,
447 .help = "Check for unintended writes into an inactive L1 table",
450 .name = QCOW2_OPT_OVERLAP_INACTIVE_L2,
451 .type = QEMU_OPT_BOOL,
452 .help = "Check for unintended writes into an inactive L2 table",
455 .name = QCOW2_OPT_CACHE_SIZE,
456 .type = QEMU_OPT_SIZE,
457 .help = "Maximum combined metadata (L2 tables and refcount blocks) "
458 "cache size",
461 .name = QCOW2_OPT_L2_CACHE_SIZE,
462 .type = QEMU_OPT_SIZE,
463 .help = "Maximum L2 table cache size",
466 .name = QCOW2_OPT_REFCOUNT_CACHE_SIZE,
467 .type = QEMU_OPT_SIZE,
468 .help = "Maximum refcount block cache size",
470 { /* end of list */ }
474 static const char *overlap_bool_option_names[QCOW2_OL_MAX_BITNR] = {
475 [QCOW2_OL_MAIN_HEADER_BITNR] = QCOW2_OPT_OVERLAP_MAIN_HEADER,
476 [QCOW2_OL_ACTIVE_L1_BITNR] = QCOW2_OPT_OVERLAP_ACTIVE_L1,
477 [QCOW2_OL_ACTIVE_L2_BITNR] = QCOW2_OPT_OVERLAP_ACTIVE_L2,
478 [QCOW2_OL_REFCOUNT_TABLE_BITNR] = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
479 [QCOW2_OL_REFCOUNT_BLOCK_BITNR] = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
480 [QCOW2_OL_SNAPSHOT_TABLE_BITNR] = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
481 [QCOW2_OL_INACTIVE_L1_BITNR] = QCOW2_OPT_OVERLAP_INACTIVE_L1,
482 [QCOW2_OL_INACTIVE_L2_BITNR] = QCOW2_OPT_OVERLAP_INACTIVE_L2,
485 static void read_cache_sizes(QemuOpts *opts, uint64_t *l2_cache_size,
486 uint64_t *refcount_cache_size, Error **errp)
488 uint64_t combined_cache_size;
489 bool l2_cache_size_set, refcount_cache_size_set, combined_cache_size_set;
491 combined_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_CACHE_SIZE);
492 l2_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_L2_CACHE_SIZE);
493 refcount_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
495 combined_cache_size = qemu_opt_get_size(opts, QCOW2_OPT_CACHE_SIZE, 0);
496 *l2_cache_size = qemu_opt_get_size(opts, QCOW2_OPT_L2_CACHE_SIZE, 0);
497 *refcount_cache_size = qemu_opt_get_size(opts,
498 QCOW2_OPT_REFCOUNT_CACHE_SIZE, 0);
500 if (combined_cache_size_set) {
501 if (l2_cache_size_set && refcount_cache_size_set) {
502 error_setg(errp, QCOW2_OPT_CACHE_SIZE ", " QCOW2_OPT_L2_CACHE_SIZE
503 " and " QCOW2_OPT_REFCOUNT_CACHE_SIZE " may not be set "
504 "the same time");
505 return;
506 } else if (*l2_cache_size > combined_cache_size) {
507 error_setg(errp, QCOW2_OPT_L2_CACHE_SIZE " may not exceed "
508 QCOW2_OPT_CACHE_SIZE);
509 return;
510 } else if (*refcount_cache_size > combined_cache_size) {
511 error_setg(errp, QCOW2_OPT_REFCOUNT_CACHE_SIZE " may not exceed "
512 QCOW2_OPT_CACHE_SIZE);
513 return;
516 if (l2_cache_size_set) {
517 *refcount_cache_size = combined_cache_size - *l2_cache_size;
518 } else if (refcount_cache_size_set) {
519 *l2_cache_size = combined_cache_size - *refcount_cache_size;
520 } else {
521 *refcount_cache_size = combined_cache_size
522 / (DEFAULT_L2_REFCOUNT_SIZE_RATIO + 1);
523 *l2_cache_size = combined_cache_size - *refcount_cache_size;
525 } else {
526 if (!l2_cache_size_set && !refcount_cache_size_set) {
527 *l2_cache_size = DEFAULT_L2_CACHE_BYTE_SIZE;
528 *refcount_cache_size = *l2_cache_size
529 / DEFAULT_L2_REFCOUNT_SIZE_RATIO;
530 } else if (!l2_cache_size_set) {
531 *l2_cache_size = *refcount_cache_size
532 * DEFAULT_L2_REFCOUNT_SIZE_RATIO;
533 } else if (!refcount_cache_size_set) {
534 *refcount_cache_size = *l2_cache_size
535 / DEFAULT_L2_REFCOUNT_SIZE_RATIO;
540 static int qcow2_open(BlockDriverState *bs, QDict *options, int flags,
541 Error **errp)
543 BDRVQcowState *s = bs->opaque;
544 unsigned int len, i;
545 int ret = 0;
546 QCowHeader header;
547 QemuOpts *opts = NULL;
548 Error *local_err = NULL;
549 uint64_t ext_end;
550 uint64_t l1_vm_state_index;
551 const char *opt_overlap_check, *opt_overlap_check_template;
552 int overlap_check_template = 0;
553 uint64_t l2_cache_size, refcount_cache_size;
555 ret = bdrv_pread(bs->file, 0, &header, sizeof(header));
556 if (ret < 0) {
557 error_setg_errno(errp, -ret, "Could not read qcow2 header");
558 goto fail;
560 be32_to_cpus(&header.magic);
561 be32_to_cpus(&header.version);
562 be64_to_cpus(&header.backing_file_offset);
563 be32_to_cpus(&header.backing_file_size);
564 be64_to_cpus(&header.size);
565 be32_to_cpus(&header.cluster_bits);
566 be32_to_cpus(&header.crypt_method);
567 be64_to_cpus(&header.l1_table_offset);
568 be32_to_cpus(&header.l1_size);
569 be64_to_cpus(&header.refcount_table_offset);
570 be32_to_cpus(&header.refcount_table_clusters);
571 be64_to_cpus(&header.snapshots_offset);
572 be32_to_cpus(&header.nb_snapshots);
574 if (header.magic != QCOW_MAGIC) {
575 error_setg(errp, "Image is not in qcow2 format");
576 ret = -EINVAL;
577 goto fail;
579 if (header.version < 2 || header.version > 3) {
580 report_unsupported(bs, errp, "QCOW version %" PRIu32, header.version);
581 ret = -ENOTSUP;
582 goto fail;
585 s->qcow_version = header.version;
587 /* Initialise cluster size */
588 if (header.cluster_bits < MIN_CLUSTER_BITS ||
589 header.cluster_bits > MAX_CLUSTER_BITS) {
590 error_setg(errp, "Unsupported cluster size: 2^%" PRIu32,
591 header.cluster_bits);
592 ret = -EINVAL;
593 goto fail;
596 s->cluster_bits = header.cluster_bits;
597 s->cluster_size = 1 << s->cluster_bits;
598 s->cluster_sectors = 1 << (s->cluster_bits - 9);
600 /* Initialise version 3 header fields */
601 if (header.version == 2) {
602 header.incompatible_features = 0;
603 header.compatible_features = 0;
604 header.autoclear_features = 0;
605 header.refcount_order = 4;
606 header.header_length = 72;
607 } else {
608 be64_to_cpus(&header.incompatible_features);
609 be64_to_cpus(&header.compatible_features);
610 be64_to_cpus(&header.autoclear_features);
611 be32_to_cpus(&header.refcount_order);
612 be32_to_cpus(&header.header_length);
614 if (header.header_length < 104) {
615 error_setg(errp, "qcow2 header too short");
616 ret = -EINVAL;
617 goto fail;
621 if (header.header_length > s->cluster_size) {
622 error_setg(errp, "qcow2 header exceeds cluster size");
623 ret = -EINVAL;
624 goto fail;
627 if (header.header_length > sizeof(header)) {
628 s->unknown_header_fields_size = header.header_length - sizeof(header);
629 s->unknown_header_fields = g_malloc(s->unknown_header_fields_size);
630 ret = bdrv_pread(bs->file, sizeof(header), s->unknown_header_fields,
631 s->unknown_header_fields_size);
632 if (ret < 0) {
633 error_setg_errno(errp, -ret, "Could not read unknown qcow2 header "
634 "fields");
635 goto fail;
639 if (header.backing_file_offset > s->cluster_size) {
640 error_setg(errp, "Invalid backing file offset");
641 ret = -EINVAL;
642 goto fail;
645 if (header.backing_file_offset) {
646 ext_end = header.backing_file_offset;
647 } else {
648 ext_end = 1 << header.cluster_bits;
651 /* Handle feature bits */
652 s->incompatible_features = header.incompatible_features;
653 s->compatible_features = header.compatible_features;
654 s->autoclear_features = header.autoclear_features;
656 if (s->incompatible_features & ~QCOW2_INCOMPAT_MASK) {
657 void *feature_table = NULL;
658 qcow2_read_extensions(bs, header.header_length, ext_end,
659 &feature_table, NULL);
660 report_unsupported_feature(bs, errp, feature_table,
661 s->incompatible_features &
662 ~QCOW2_INCOMPAT_MASK);
663 ret = -ENOTSUP;
664 g_free(feature_table);
665 goto fail;
668 if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
669 /* Corrupt images may not be written to unless they are being repaired
671 if ((flags & BDRV_O_RDWR) && !(flags & BDRV_O_CHECK)) {
672 error_setg(errp, "qcow2: Image is corrupt; cannot be opened "
673 "read/write");
674 ret = -EACCES;
675 goto fail;
679 /* Check support for various header values */
680 if (header.refcount_order > 6) {
681 error_setg(errp, "Reference count entry width too large; may not "
682 "exceed 64 bits");
683 ret = -EINVAL;
684 goto fail;
686 s->refcount_order = header.refcount_order;
687 s->refcount_bits = 1 << s->refcount_order;
688 s->refcount_max = UINT64_C(1) << (s->refcount_bits - 1);
689 s->refcount_max += s->refcount_max - 1;
691 if (header.crypt_method > QCOW_CRYPT_AES) {
692 error_setg(errp, "Unsupported encryption method: %" PRIu32,
693 header.crypt_method);
694 ret = -EINVAL;
695 goto fail;
697 s->crypt_method_header = header.crypt_method;
698 if (s->crypt_method_header) {
699 bs->encrypted = 1;
702 s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */
703 s->l2_size = 1 << s->l2_bits;
704 /* 2^(s->refcount_order - 3) is the refcount width in bytes */
705 s->refcount_block_bits = s->cluster_bits - (s->refcount_order - 3);
706 s->refcount_block_size = 1 << s->refcount_block_bits;
707 bs->total_sectors = header.size / 512;
708 s->csize_shift = (62 - (s->cluster_bits - 8));
709 s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;
710 s->cluster_offset_mask = (1LL << s->csize_shift) - 1;
712 s->refcount_table_offset = header.refcount_table_offset;
713 s->refcount_table_size =
714 header.refcount_table_clusters << (s->cluster_bits - 3);
716 if (header.refcount_table_clusters > qcow2_max_refcount_clusters(s)) {
717 error_setg(errp, "Reference count table too large");
718 ret = -EINVAL;
719 goto fail;
722 ret = validate_table_offset(bs, s->refcount_table_offset,
723 s->refcount_table_size, sizeof(uint64_t));
724 if (ret < 0) {
725 error_setg(errp, "Invalid reference count table offset");
726 goto fail;
729 /* Snapshot table offset/length */
730 if (header.nb_snapshots > QCOW_MAX_SNAPSHOTS) {
731 error_setg(errp, "Too many snapshots");
732 ret = -EINVAL;
733 goto fail;
736 ret = validate_table_offset(bs, header.snapshots_offset,
737 header.nb_snapshots,
738 sizeof(QCowSnapshotHeader));
739 if (ret < 0) {
740 error_setg(errp, "Invalid snapshot table offset");
741 goto fail;
744 /* read the level 1 table */
745 if (header.l1_size > QCOW_MAX_L1_SIZE / sizeof(uint64_t)) {
746 error_setg(errp, "Active L1 table too large");
747 ret = -EFBIG;
748 goto fail;
750 s->l1_size = header.l1_size;
752 l1_vm_state_index = size_to_l1(s, header.size);
753 if (l1_vm_state_index > INT_MAX) {
754 error_setg(errp, "Image is too big");
755 ret = -EFBIG;
756 goto fail;
758 s->l1_vm_state_index = l1_vm_state_index;
760 /* the L1 table must contain at least enough entries to put
761 header.size bytes */
762 if (s->l1_size < s->l1_vm_state_index) {
763 error_setg(errp, "L1 table is too small");
764 ret = -EINVAL;
765 goto fail;
768 ret = validate_table_offset(bs, header.l1_table_offset,
769 header.l1_size, sizeof(uint64_t));
770 if (ret < 0) {
771 error_setg(errp, "Invalid L1 table offset");
772 goto fail;
774 s->l1_table_offset = header.l1_table_offset;
777 if (s->l1_size > 0) {
778 s->l1_table = qemu_try_blockalign(bs->file,
779 align_offset(s->l1_size * sizeof(uint64_t), 512));
780 if (s->l1_table == NULL) {
781 error_setg(errp, "Could not allocate L1 table");
782 ret = -ENOMEM;
783 goto fail;
785 ret = bdrv_pread(bs->file, s->l1_table_offset, s->l1_table,
786 s->l1_size * sizeof(uint64_t));
787 if (ret < 0) {
788 error_setg_errno(errp, -ret, "Could not read L1 table");
789 goto fail;
791 for(i = 0;i < s->l1_size; i++) {
792 be64_to_cpus(&s->l1_table[i]);
796 /* get L2 table/refcount block cache size from command line options */
797 opts = qemu_opts_create(&qcow2_runtime_opts, NULL, 0, &error_abort);
798 qemu_opts_absorb_qdict(opts, options, &local_err);
799 if (local_err) {
800 error_propagate(errp, local_err);
801 ret = -EINVAL;
802 goto fail;
805 read_cache_sizes(opts, &l2_cache_size, &refcount_cache_size, &local_err);
806 if (local_err) {
807 error_propagate(errp, local_err);
808 ret = -EINVAL;
809 goto fail;
812 l2_cache_size /= s->cluster_size;
813 if (l2_cache_size < MIN_L2_CACHE_SIZE) {
814 l2_cache_size = MIN_L2_CACHE_SIZE;
816 if (l2_cache_size > INT_MAX) {
817 error_setg(errp, "L2 cache size too big");
818 ret = -EINVAL;
819 goto fail;
822 refcount_cache_size /= s->cluster_size;
823 if (refcount_cache_size < MIN_REFCOUNT_CACHE_SIZE) {
824 refcount_cache_size = MIN_REFCOUNT_CACHE_SIZE;
826 if (refcount_cache_size > INT_MAX) {
827 error_setg(errp, "Refcount cache size too big");
828 ret = -EINVAL;
829 goto fail;
832 /* alloc L2 table/refcount block cache */
833 s->l2_table_cache = qcow2_cache_create(bs, l2_cache_size);
834 s->refcount_block_cache = qcow2_cache_create(bs, refcount_cache_size);
835 if (s->l2_table_cache == NULL || s->refcount_block_cache == NULL) {
836 error_setg(errp, "Could not allocate metadata caches");
837 ret = -ENOMEM;
838 goto fail;
841 s->cluster_cache = g_malloc(s->cluster_size);
842 /* one more sector for decompressed data alignment */
843 s->cluster_data = qemu_try_blockalign(bs->file, QCOW_MAX_CRYPT_CLUSTERS
844 * s->cluster_size + 512);
845 if (s->cluster_data == NULL) {
846 error_setg(errp, "Could not allocate temporary cluster buffer");
847 ret = -ENOMEM;
848 goto fail;
851 s->cluster_cache_offset = -1;
852 s->flags = flags;
854 ret = qcow2_refcount_init(bs);
855 if (ret != 0) {
856 error_setg_errno(errp, -ret, "Could not initialize refcount handling");
857 goto fail;
860 QLIST_INIT(&s->cluster_allocs);
861 QTAILQ_INIT(&s->discards);
863 /* read qcow2 extensions */
864 if (qcow2_read_extensions(bs, header.header_length, ext_end, NULL,
865 &local_err)) {
866 error_propagate(errp, local_err);
867 ret = -EINVAL;
868 goto fail;
871 /* read the backing file name */
872 if (header.backing_file_offset != 0) {
873 len = header.backing_file_size;
874 if (len > MIN(1023, s->cluster_size - header.backing_file_offset) ||
875 len >= sizeof(bs->backing_file)) {
876 error_setg(errp, "Backing file name too long");
877 ret = -EINVAL;
878 goto fail;
880 ret = bdrv_pread(bs->file, header.backing_file_offset,
881 bs->backing_file, len);
882 if (ret < 0) {
883 error_setg_errno(errp, -ret, "Could not read backing file name");
884 goto fail;
886 bs->backing_file[len] = '\0';
889 /* Internal snapshots */
890 s->snapshots_offset = header.snapshots_offset;
891 s->nb_snapshots = header.nb_snapshots;
893 ret = qcow2_read_snapshots(bs);
894 if (ret < 0) {
895 error_setg_errno(errp, -ret, "Could not read snapshots");
896 goto fail;
899 /* Clear unknown autoclear feature bits */
900 if (!bs->read_only && !(flags & BDRV_O_INCOMING) && s->autoclear_features) {
901 s->autoclear_features = 0;
902 ret = qcow2_update_header(bs);
903 if (ret < 0) {
904 error_setg_errno(errp, -ret, "Could not update qcow2 header");
905 goto fail;
909 /* Initialise locks */
910 qemu_co_mutex_init(&s->lock);
912 /* Repair image if dirty */
913 if (!(flags & (BDRV_O_CHECK | BDRV_O_INCOMING)) && !bs->read_only &&
914 (s->incompatible_features & QCOW2_INCOMPAT_DIRTY)) {
915 BdrvCheckResult result = {0};
917 ret = qcow2_check(bs, &result, BDRV_FIX_ERRORS | BDRV_FIX_LEAKS);
918 if (ret < 0) {
919 error_setg_errno(errp, -ret, "Could not repair dirty image");
920 goto fail;
924 /* Enable lazy_refcounts according to image and command line options */
925 s->use_lazy_refcounts = qemu_opt_get_bool(opts, QCOW2_OPT_LAZY_REFCOUNTS,
926 (s->compatible_features & QCOW2_COMPAT_LAZY_REFCOUNTS));
928 s->discard_passthrough[QCOW2_DISCARD_NEVER] = false;
929 s->discard_passthrough[QCOW2_DISCARD_ALWAYS] = true;
930 s->discard_passthrough[QCOW2_DISCARD_REQUEST] =
931 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_REQUEST,
932 flags & BDRV_O_UNMAP);
933 s->discard_passthrough[QCOW2_DISCARD_SNAPSHOT] =
934 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_SNAPSHOT, true);
935 s->discard_passthrough[QCOW2_DISCARD_OTHER] =
936 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_OTHER, false);
938 opt_overlap_check = qemu_opt_get(opts, QCOW2_OPT_OVERLAP);
939 opt_overlap_check_template = qemu_opt_get(opts, QCOW2_OPT_OVERLAP_TEMPLATE);
940 if (opt_overlap_check_template && opt_overlap_check &&
941 strcmp(opt_overlap_check_template, opt_overlap_check))
943 error_setg(errp, "Conflicting values for qcow2 options '"
944 QCOW2_OPT_OVERLAP "' ('%s') and '" QCOW2_OPT_OVERLAP_TEMPLATE
945 "' ('%s')", opt_overlap_check, opt_overlap_check_template);
946 ret = -EINVAL;
947 goto fail;
949 if (!opt_overlap_check) {
950 opt_overlap_check = opt_overlap_check_template ?: "cached";
953 if (!strcmp(opt_overlap_check, "none")) {
954 overlap_check_template = 0;
955 } else if (!strcmp(opt_overlap_check, "constant")) {
956 overlap_check_template = QCOW2_OL_CONSTANT;
957 } else if (!strcmp(opt_overlap_check, "cached")) {
958 overlap_check_template = QCOW2_OL_CACHED;
959 } else if (!strcmp(opt_overlap_check, "all")) {
960 overlap_check_template = QCOW2_OL_ALL;
961 } else {
962 error_setg(errp, "Unsupported value '%s' for qcow2 option "
963 "'overlap-check'. Allowed are either of the following: "
964 "none, constant, cached, all", opt_overlap_check);
965 ret = -EINVAL;
966 goto fail;
969 s->overlap_check = 0;
970 for (i = 0; i < QCOW2_OL_MAX_BITNR; i++) {
971 /* overlap-check defines a template bitmask, but every flag may be
972 * overwritten through the associated boolean option */
973 s->overlap_check |=
974 qemu_opt_get_bool(opts, overlap_bool_option_names[i],
975 overlap_check_template & (1 << i)) << i;
978 qemu_opts_del(opts);
979 opts = NULL;
981 if (s->use_lazy_refcounts && s->qcow_version < 3) {
982 error_setg(errp, "Lazy refcounts require a qcow2 image with at least "
983 "qemu 1.1 compatibility level");
984 ret = -EINVAL;
985 goto fail;
988 #ifdef DEBUG_ALLOC
990 BdrvCheckResult result = {0};
991 qcow2_check_refcounts(bs, &result, 0);
993 #endif
994 return ret;
996 fail:
997 qemu_opts_del(opts);
998 g_free(s->unknown_header_fields);
999 cleanup_unknown_header_ext(bs);
1000 qcow2_free_snapshots(bs);
1001 qcow2_refcount_close(bs);
1002 qemu_vfree(s->l1_table);
1003 /* else pre-write overlap checks in cache_destroy may crash */
1004 s->l1_table = NULL;
1005 if (s->l2_table_cache) {
1006 qcow2_cache_destroy(bs, s->l2_table_cache);
1008 if (s->refcount_block_cache) {
1009 qcow2_cache_destroy(bs, s->refcount_block_cache);
1011 g_free(s->cluster_cache);
1012 qemu_vfree(s->cluster_data);
1013 return ret;
1016 static void qcow2_refresh_limits(BlockDriverState *bs, Error **errp)
1018 BDRVQcowState *s = bs->opaque;
1020 bs->bl.write_zeroes_alignment = s->cluster_sectors;
1023 static int qcow2_set_key(BlockDriverState *bs, const char *key)
1025 BDRVQcowState *s = bs->opaque;
1026 uint8_t keybuf[16];
1027 int len, i;
1029 memset(keybuf, 0, 16);
1030 len = strlen(key);
1031 if (len > 16)
1032 len = 16;
1033 /* XXX: we could compress the chars to 7 bits to increase
1034 entropy */
1035 for(i = 0;i < len;i++) {
1036 keybuf[i] = key[i];
1038 s->crypt_method = s->crypt_method_header;
1040 if (AES_set_encrypt_key(keybuf, 128, &s->aes_encrypt_key) != 0)
1041 return -1;
1042 if (AES_set_decrypt_key(keybuf, 128, &s->aes_decrypt_key) != 0)
1043 return -1;
1044 #if 0
1045 /* test */
1047 uint8_t in[16];
1048 uint8_t out[16];
1049 uint8_t tmp[16];
1050 for(i=0;i<16;i++)
1051 in[i] = i;
1052 AES_encrypt(in, tmp, &s->aes_encrypt_key);
1053 AES_decrypt(tmp, out, &s->aes_decrypt_key);
1054 for(i = 0; i < 16; i++)
1055 printf(" %02x", tmp[i]);
1056 printf("\n");
1057 for(i = 0; i < 16; i++)
1058 printf(" %02x", out[i]);
1059 printf("\n");
1061 #endif
1062 return 0;
1065 /* We have no actual commit/abort logic for qcow2, but we need to write out any
1066 * unwritten data if we reopen read-only. */
1067 static int qcow2_reopen_prepare(BDRVReopenState *state,
1068 BlockReopenQueue *queue, Error **errp)
1070 int ret;
1072 if ((state->flags & BDRV_O_RDWR) == 0) {
1073 ret = bdrv_flush(state->bs);
1074 if (ret < 0) {
1075 return ret;
1078 ret = qcow2_mark_clean(state->bs);
1079 if (ret < 0) {
1080 return ret;
1084 return 0;
1087 static int64_t coroutine_fn qcow2_co_get_block_status(BlockDriverState *bs,
1088 int64_t sector_num, int nb_sectors, int *pnum)
1090 BDRVQcowState *s = bs->opaque;
1091 uint64_t cluster_offset;
1092 int index_in_cluster, ret;
1093 int64_t status = 0;
1095 *pnum = nb_sectors;
1096 qemu_co_mutex_lock(&s->lock);
1097 ret = qcow2_get_cluster_offset(bs, sector_num << 9, pnum, &cluster_offset);
1098 qemu_co_mutex_unlock(&s->lock);
1099 if (ret < 0) {
1100 return ret;
1103 if (cluster_offset != 0 && ret != QCOW2_CLUSTER_COMPRESSED &&
1104 !s->crypt_method) {
1105 index_in_cluster = sector_num & (s->cluster_sectors - 1);
1106 cluster_offset |= (index_in_cluster << BDRV_SECTOR_BITS);
1107 status |= BDRV_BLOCK_OFFSET_VALID | cluster_offset;
1109 if (ret == QCOW2_CLUSTER_ZERO) {
1110 status |= BDRV_BLOCK_ZERO;
1111 } else if (ret != QCOW2_CLUSTER_UNALLOCATED) {
1112 status |= BDRV_BLOCK_DATA;
1114 return status;
1117 /* handle reading after the end of the backing file */
1118 int qcow2_backing_read1(BlockDriverState *bs, QEMUIOVector *qiov,
1119 int64_t sector_num, int nb_sectors)
1121 int n1;
1122 if ((sector_num + nb_sectors) <= bs->total_sectors)
1123 return nb_sectors;
1124 if (sector_num >= bs->total_sectors)
1125 n1 = 0;
1126 else
1127 n1 = bs->total_sectors - sector_num;
1129 qemu_iovec_memset(qiov, 512 * n1, 0, 512 * (nb_sectors - n1));
1131 return n1;
1134 static coroutine_fn int qcow2_co_readv(BlockDriverState *bs, int64_t sector_num,
1135 int remaining_sectors, QEMUIOVector *qiov)
1137 BDRVQcowState *s = bs->opaque;
1138 int index_in_cluster, n1;
1139 int ret;
1140 int cur_nr_sectors; /* number of sectors in current iteration */
1141 uint64_t cluster_offset = 0;
1142 uint64_t bytes_done = 0;
1143 QEMUIOVector hd_qiov;
1144 uint8_t *cluster_data = NULL;
1146 qemu_iovec_init(&hd_qiov, qiov->niov);
1148 qemu_co_mutex_lock(&s->lock);
1150 while (remaining_sectors != 0) {
1152 /* prepare next request */
1153 cur_nr_sectors = remaining_sectors;
1154 if (s->crypt_method) {
1155 cur_nr_sectors = MIN(cur_nr_sectors,
1156 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors);
1159 ret = qcow2_get_cluster_offset(bs, sector_num << 9,
1160 &cur_nr_sectors, &cluster_offset);
1161 if (ret < 0) {
1162 goto fail;
1165 index_in_cluster = sector_num & (s->cluster_sectors - 1);
1167 qemu_iovec_reset(&hd_qiov);
1168 qemu_iovec_concat(&hd_qiov, qiov, bytes_done,
1169 cur_nr_sectors * 512);
1171 switch (ret) {
1172 case QCOW2_CLUSTER_UNALLOCATED:
1174 if (bs->backing_hd) {
1175 /* read from the base image */
1176 n1 = qcow2_backing_read1(bs->backing_hd, &hd_qiov,
1177 sector_num, cur_nr_sectors);
1178 if (n1 > 0) {
1179 QEMUIOVector local_qiov;
1181 qemu_iovec_init(&local_qiov, hd_qiov.niov);
1182 qemu_iovec_concat(&local_qiov, &hd_qiov, 0,
1183 n1 * BDRV_SECTOR_SIZE);
1185 BLKDBG_EVENT(bs->file, BLKDBG_READ_BACKING_AIO);
1186 qemu_co_mutex_unlock(&s->lock);
1187 ret = bdrv_co_readv(bs->backing_hd, sector_num,
1188 n1, &local_qiov);
1189 qemu_co_mutex_lock(&s->lock);
1191 qemu_iovec_destroy(&local_qiov);
1193 if (ret < 0) {
1194 goto fail;
1197 } else {
1198 /* Note: in this case, no need to wait */
1199 qemu_iovec_memset(&hd_qiov, 0, 0, 512 * cur_nr_sectors);
1201 break;
1203 case QCOW2_CLUSTER_ZERO:
1204 qemu_iovec_memset(&hd_qiov, 0, 0, 512 * cur_nr_sectors);
1205 break;
1207 case QCOW2_CLUSTER_COMPRESSED:
1208 /* add AIO support for compressed blocks ? */
1209 ret = qcow2_decompress_cluster(bs, cluster_offset);
1210 if (ret < 0) {
1211 goto fail;
1214 qemu_iovec_from_buf(&hd_qiov, 0,
1215 s->cluster_cache + index_in_cluster * 512,
1216 512 * cur_nr_sectors);
1217 break;
1219 case QCOW2_CLUSTER_NORMAL:
1220 if ((cluster_offset & 511) != 0) {
1221 ret = -EIO;
1222 goto fail;
1225 if (s->crypt_method) {
1227 * For encrypted images, read everything into a temporary
1228 * contiguous buffer on which the AES functions can work.
1230 if (!cluster_data) {
1231 cluster_data =
1232 qemu_try_blockalign(bs->file, QCOW_MAX_CRYPT_CLUSTERS
1233 * s->cluster_size);
1234 if (cluster_data == NULL) {
1235 ret = -ENOMEM;
1236 goto fail;
1240 assert(cur_nr_sectors <=
1241 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors);
1242 qemu_iovec_reset(&hd_qiov);
1243 qemu_iovec_add(&hd_qiov, cluster_data,
1244 512 * cur_nr_sectors);
1247 BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);
1248 qemu_co_mutex_unlock(&s->lock);
1249 ret = bdrv_co_readv(bs->file,
1250 (cluster_offset >> 9) + index_in_cluster,
1251 cur_nr_sectors, &hd_qiov);
1252 qemu_co_mutex_lock(&s->lock);
1253 if (ret < 0) {
1254 goto fail;
1256 if (s->crypt_method) {
1257 qcow2_encrypt_sectors(s, sector_num, cluster_data,
1258 cluster_data, cur_nr_sectors, 0, &s->aes_decrypt_key);
1259 qemu_iovec_from_buf(qiov, bytes_done,
1260 cluster_data, 512 * cur_nr_sectors);
1262 break;
1264 default:
1265 g_assert_not_reached();
1266 ret = -EIO;
1267 goto fail;
1270 remaining_sectors -= cur_nr_sectors;
1271 sector_num += cur_nr_sectors;
1272 bytes_done += cur_nr_sectors * 512;
1274 ret = 0;
1276 fail:
1277 qemu_co_mutex_unlock(&s->lock);
1279 qemu_iovec_destroy(&hd_qiov);
1280 qemu_vfree(cluster_data);
1282 return ret;
1285 static coroutine_fn int qcow2_co_writev(BlockDriverState *bs,
1286 int64_t sector_num,
1287 int remaining_sectors,
1288 QEMUIOVector *qiov)
1290 BDRVQcowState *s = bs->opaque;
1291 int index_in_cluster;
1292 int ret;
1293 int cur_nr_sectors; /* number of sectors in current iteration */
1294 uint64_t cluster_offset;
1295 QEMUIOVector hd_qiov;
1296 uint64_t bytes_done = 0;
1297 uint8_t *cluster_data = NULL;
1298 QCowL2Meta *l2meta = NULL;
1300 trace_qcow2_writev_start_req(qemu_coroutine_self(), sector_num,
1301 remaining_sectors);
1303 qemu_iovec_init(&hd_qiov, qiov->niov);
1305 s->cluster_cache_offset = -1; /* disable compressed cache */
1307 qemu_co_mutex_lock(&s->lock);
1309 while (remaining_sectors != 0) {
1311 l2meta = NULL;
1313 trace_qcow2_writev_start_part(qemu_coroutine_self());
1314 index_in_cluster = sector_num & (s->cluster_sectors - 1);
1315 cur_nr_sectors = remaining_sectors;
1316 if (s->crypt_method &&
1317 cur_nr_sectors >
1318 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors - index_in_cluster) {
1319 cur_nr_sectors =
1320 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors - index_in_cluster;
1323 ret = qcow2_alloc_cluster_offset(bs, sector_num << 9,
1324 &cur_nr_sectors, &cluster_offset, &l2meta);
1325 if (ret < 0) {
1326 goto fail;
1329 assert((cluster_offset & 511) == 0);
1331 qemu_iovec_reset(&hd_qiov);
1332 qemu_iovec_concat(&hd_qiov, qiov, bytes_done,
1333 cur_nr_sectors * 512);
1335 if (s->crypt_method) {
1336 if (!cluster_data) {
1337 cluster_data = qemu_try_blockalign(bs->file,
1338 QCOW_MAX_CRYPT_CLUSTERS
1339 * s->cluster_size);
1340 if (cluster_data == NULL) {
1341 ret = -ENOMEM;
1342 goto fail;
1346 assert(hd_qiov.size <=
1347 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
1348 qemu_iovec_to_buf(&hd_qiov, 0, cluster_data, hd_qiov.size);
1350 qcow2_encrypt_sectors(s, sector_num, cluster_data,
1351 cluster_data, cur_nr_sectors, 1, &s->aes_encrypt_key);
1353 qemu_iovec_reset(&hd_qiov);
1354 qemu_iovec_add(&hd_qiov, cluster_data,
1355 cur_nr_sectors * 512);
1358 ret = qcow2_pre_write_overlap_check(bs, 0,
1359 cluster_offset + index_in_cluster * BDRV_SECTOR_SIZE,
1360 cur_nr_sectors * BDRV_SECTOR_SIZE);
1361 if (ret < 0) {
1362 goto fail;
1365 qemu_co_mutex_unlock(&s->lock);
1366 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO);
1367 trace_qcow2_writev_data(qemu_coroutine_self(),
1368 (cluster_offset >> 9) + index_in_cluster);
1369 ret = bdrv_co_writev(bs->file,
1370 (cluster_offset >> 9) + index_in_cluster,
1371 cur_nr_sectors, &hd_qiov);
1372 qemu_co_mutex_lock(&s->lock);
1373 if (ret < 0) {
1374 goto fail;
1377 while (l2meta != NULL) {
1378 QCowL2Meta *next;
1380 ret = qcow2_alloc_cluster_link_l2(bs, l2meta);
1381 if (ret < 0) {
1382 goto fail;
1385 /* Take the request off the list of running requests */
1386 if (l2meta->nb_clusters != 0) {
1387 QLIST_REMOVE(l2meta, next_in_flight);
1390 qemu_co_queue_restart_all(&l2meta->dependent_requests);
1392 next = l2meta->next;
1393 g_free(l2meta);
1394 l2meta = next;
1397 remaining_sectors -= cur_nr_sectors;
1398 sector_num += cur_nr_sectors;
1399 bytes_done += cur_nr_sectors * 512;
1400 trace_qcow2_writev_done_part(qemu_coroutine_self(), cur_nr_sectors);
1402 ret = 0;
1404 fail:
1405 qemu_co_mutex_unlock(&s->lock);
1407 while (l2meta != NULL) {
1408 QCowL2Meta *next;
1410 if (l2meta->nb_clusters != 0) {
1411 QLIST_REMOVE(l2meta, next_in_flight);
1413 qemu_co_queue_restart_all(&l2meta->dependent_requests);
1415 next = l2meta->next;
1416 g_free(l2meta);
1417 l2meta = next;
1420 qemu_iovec_destroy(&hd_qiov);
1421 qemu_vfree(cluster_data);
1422 trace_qcow2_writev_done_req(qemu_coroutine_self(), ret);
1424 return ret;
1427 static void qcow2_close(BlockDriverState *bs)
1429 BDRVQcowState *s = bs->opaque;
1430 qemu_vfree(s->l1_table);
1431 /* else pre-write overlap checks in cache_destroy may crash */
1432 s->l1_table = NULL;
1434 if (!(bs->open_flags & BDRV_O_INCOMING)) {
1435 int ret1, ret2;
1437 ret1 = qcow2_cache_flush(bs, s->l2_table_cache);
1438 ret2 = qcow2_cache_flush(bs, s->refcount_block_cache);
1440 if (ret1) {
1441 error_report("Failed to flush the L2 table cache: %s",
1442 strerror(-ret1));
1444 if (ret2) {
1445 error_report("Failed to flush the refcount block cache: %s",
1446 strerror(-ret2));
1449 if (!ret1 && !ret2) {
1450 qcow2_mark_clean(bs);
1454 qcow2_cache_destroy(bs, s->l2_table_cache);
1455 qcow2_cache_destroy(bs, s->refcount_block_cache);
1457 g_free(s->unknown_header_fields);
1458 cleanup_unknown_header_ext(bs);
1460 g_free(s->cluster_cache);
1461 qemu_vfree(s->cluster_data);
1462 qcow2_refcount_close(bs);
1463 qcow2_free_snapshots(bs);
1466 static void qcow2_invalidate_cache(BlockDriverState *bs, Error **errp)
1468 BDRVQcowState *s = bs->opaque;
1469 int flags = s->flags;
1470 AES_KEY aes_encrypt_key;
1471 AES_KEY aes_decrypt_key;
1472 uint32_t crypt_method = 0;
1473 QDict *options;
1474 Error *local_err = NULL;
1475 int ret;
1478 * Backing files are read-only which makes all of their metadata immutable,
1479 * that means we don't have to worry about reopening them here.
1482 if (s->crypt_method) {
1483 crypt_method = s->crypt_method;
1484 memcpy(&aes_encrypt_key, &s->aes_encrypt_key, sizeof(aes_encrypt_key));
1485 memcpy(&aes_decrypt_key, &s->aes_decrypt_key, sizeof(aes_decrypt_key));
1488 qcow2_close(bs);
1490 bdrv_invalidate_cache(bs->file, &local_err);
1491 if (local_err) {
1492 error_propagate(errp, local_err);
1493 return;
1496 memset(s, 0, sizeof(BDRVQcowState));
1497 options = qdict_clone_shallow(bs->options);
1499 ret = qcow2_open(bs, options, flags, &local_err);
1500 QDECREF(options);
1501 if (local_err) {
1502 error_setg(errp, "Could not reopen qcow2 layer: %s",
1503 error_get_pretty(local_err));
1504 error_free(local_err);
1505 return;
1506 } else if (ret < 0) {
1507 error_setg_errno(errp, -ret, "Could not reopen qcow2 layer");
1508 return;
1511 if (crypt_method) {
1512 s->crypt_method = crypt_method;
1513 memcpy(&s->aes_encrypt_key, &aes_encrypt_key, sizeof(aes_encrypt_key));
1514 memcpy(&s->aes_decrypt_key, &aes_decrypt_key, sizeof(aes_decrypt_key));
1518 static size_t header_ext_add(char *buf, uint32_t magic, const void *s,
1519 size_t len, size_t buflen)
1521 QCowExtension *ext_backing_fmt = (QCowExtension*) buf;
1522 size_t ext_len = sizeof(QCowExtension) + ((len + 7) & ~7);
1524 if (buflen < ext_len) {
1525 return -ENOSPC;
1528 *ext_backing_fmt = (QCowExtension) {
1529 .magic = cpu_to_be32(magic),
1530 .len = cpu_to_be32(len),
1532 memcpy(buf + sizeof(QCowExtension), s, len);
1534 return ext_len;
1538 * Updates the qcow2 header, including the variable length parts of it, i.e.
1539 * the backing file name and all extensions. qcow2 was not designed to allow
1540 * such changes, so if we run out of space (we can only use the first cluster)
1541 * this function may fail.
1543 * Returns 0 on success, -errno in error cases.
1545 int qcow2_update_header(BlockDriverState *bs)
1547 BDRVQcowState *s = bs->opaque;
1548 QCowHeader *header;
1549 char *buf;
1550 size_t buflen = s->cluster_size;
1551 int ret;
1552 uint64_t total_size;
1553 uint32_t refcount_table_clusters;
1554 size_t header_length;
1555 Qcow2UnknownHeaderExtension *uext;
1557 buf = qemu_blockalign(bs, buflen);
1559 /* Header structure */
1560 header = (QCowHeader*) buf;
1562 if (buflen < sizeof(*header)) {
1563 ret = -ENOSPC;
1564 goto fail;
1567 header_length = sizeof(*header) + s->unknown_header_fields_size;
1568 total_size = bs->total_sectors * BDRV_SECTOR_SIZE;
1569 refcount_table_clusters = s->refcount_table_size >> (s->cluster_bits - 3);
1571 *header = (QCowHeader) {
1572 /* Version 2 fields */
1573 .magic = cpu_to_be32(QCOW_MAGIC),
1574 .version = cpu_to_be32(s->qcow_version),
1575 .backing_file_offset = 0,
1576 .backing_file_size = 0,
1577 .cluster_bits = cpu_to_be32(s->cluster_bits),
1578 .size = cpu_to_be64(total_size),
1579 .crypt_method = cpu_to_be32(s->crypt_method_header),
1580 .l1_size = cpu_to_be32(s->l1_size),
1581 .l1_table_offset = cpu_to_be64(s->l1_table_offset),
1582 .refcount_table_offset = cpu_to_be64(s->refcount_table_offset),
1583 .refcount_table_clusters = cpu_to_be32(refcount_table_clusters),
1584 .nb_snapshots = cpu_to_be32(s->nb_snapshots),
1585 .snapshots_offset = cpu_to_be64(s->snapshots_offset),
1587 /* Version 3 fields */
1588 .incompatible_features = cpu_to_be64(s->incompatible_features),
1589 .compatible_features = cpu_to_be64(s->compatible_features),
1590 .autoclear_features = cpu_to_be64(s->autoclear_features),
1591 .refcount_order = cpu_to_be32(s->refcount_order),
1592 .header_length = cpu_to_be32(header_length),
1595 /* For older versions, write a shorter header */
1596 switch (s->qcow_version) {
1597 case 2:
1598 ret = offsetof(QCowHeader, incompatible_features);
1599 break;
1600 case 3:
1601 ret = sizeof(*header);
1602 break;
1603 default:
1604 ret = -EINVAL;
1605 goto fail;
1608 buf += ret;
1609 buflen -= ret;
1610 memset(buf, 0, buflen);
1612 /* Preserve any unknown field in the header */
1613 if (s->unknown_header_fields_size) {
1614 if (buflen < s->unknown_header_fields_size) {
1615 ret = -ENOSPC;
1616 goto fail;
1619 memcpy(buf, s->unknown_header_fields, s->unknown_header_fields_size);
1620 buf += s->unknown_header_fields_size;
1621 buflen -= s->unknown_header_fields_size;
1624 /* Backing file format header extension */
1625 if (*bs->backing_format) {
1626 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BACKING_FORMAT,
1627 bs->backing_format, strlen(bs->backing_format),
1628 buflen);
1629 if (ret < 0) {
1630 goto fail;
1633 buf += ret;
1634 buflen -= ret;
1637 /* Feature table */
1638 Qcow2Feature features[] = {
1640 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
1641 .bit = QCOW2_INCOMPAT_DIRTY_BITNR,
1642 .name = "dirty bit",
1645 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
1646 .bit = QCOW2_INCOMPAT_CORRUPT_BITNR,
1647 .name = "corrupt bit",
1650 .type = QCOW2_FEAT_TYPE_COMPATIBLE,
1651 .bit = QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR,
1652 .name = "lazy refcounts",
1656 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_FEATURE_TABLE,
1657 features, sizeof(features), buflen);
1658 if (ret < 0) {
1659 goto fail;
1661 buf += ret;
1662 buflen -= ret;
1664 /* Keep unknown header extensions */
1665 QLIST_FOREACH(uext, &s->unknown_header_ext, next) {
1666 ret = header_ext_add(buf, uext->magic, uext->data, uext->len, buflen);
1667 if (ret < 0) {
1668 goto fail;
1671 buf += ret;
1672 buflen -= ret;
1675 /* End of header extensions */
1676 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_END, NULL, 0, buflen);
1677 if (ret < 0) {
1678 goto fail;
1681 buf += ret;
1682 buflen -= ret;
1684 /* Backing file name */
1685 if (*bs->backing_file) {
1686 size_t backing_file_len = strlen(bs->backing_file);
1688 if (buflen < backing_file_len) {
1689 ret = -ENOSPC;
1690 goto fail;
1693 /* Using strncpy is ok here, since buf is not NUL-terminated. */
1694 strncpy(buf, bs->backing_file, buflen);
1696 header->backing_file_offset = cpu_to_be64(buf - ((char*) header));
1697 header->backing_file_size = cpu_to_be32(backing_file_len);
1700 /* Write the new header */
1701 ret = bdrv_pwrite(bs->file, 0, header, s->cluster_size);
1702 if (ret < 0) {
1703 goto fail;
1706 ret = 0;
1707 fail:
1708 qemu_vfree(header);
1709 return ret;
1712 static int qcow2_change_backing_file(BlockDriverState *bs,
1713 const char *backing_file, const char *backing_fmt)
1715 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
1716 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
1718 return qcow2_update_header(bs);
1721 static int preallocate(BlockDriverState *bs)
1723 uint64_t nb_sectors;
1724 uint64_t offset;
1725 uint64_t host_offset = 0;
1726 int num;
1727 int ret;
1728 QCowL2Meta *meta;
1730 nb_sectors = bdrv_nb_sectors(bs);
1731 offset = 0;
1733 while (nb_sectors) {
1734 num = MIN(nb_sectors, INT_MAX >> BDRV_SECTOR_BITS);
1735 ret = qcow2_alloc_cluster_offset(bs, offset, &num,
1736 &host_offset, &meta);
1737 if (ret < 0) {
1738 return ret;
1741 while (meta) {
1742 QCowL2Meta *next = meta->next;
1744 ret = qcow2_alloc_cluster_link_l2(bs, meta);
1745 if (ret < 0) {
1746 qcow2_free_any_clusters(bs, meta->alloc_offset,
1747 meta->nb_clusters, QCOW2_DISCARD_NEVER);
1748 return ret;
1751 /* There are no dependent requests, but we need to remove our
1752 * request from the list of in-flight requests */
1753 QLIST_REMOVE(meta, next_in_flight);
1755 g_free(meta);
1756 meta = next;
1759 /* TODO Preallocate data if requested */
1761 nb_sectors -= num;
1762 offset += num << BDRV_SECTOR_BITS;
1766 * It is expected that the image file is large enough to actually contain
1767 * all of the allocated clusters (otherwise we get failing reads after
1768 * EOF). Extend the image to the last allocated sector.
1770 if (host_offset != 0) {
1771 uint8_t buf[BDRV_SECTOR_SIZE];
1772 memset(buf, 0, BDRV_SECTOR_SIZE);
1773 ret = bdrv_write(bs->file, (host_offset >> BDRV_SECTOR_BITS) + num - 1,
1774 buf, 1);
1775 if (ret < 0) {
1776 return ret;
1780 return 0;
1783 static int qcow2_create2(const char *filename, int64_t total_size,
1784 const char *backing_file, const char *backing_format,
1785 int flags, size_t cluster_size, PreallocMode prealloc,
1786 QemuOpts *opts, int version, int refcount_order,
1787 Error **errp)
1789 /* Calculate cluster_bits */
1790 int cluster_bits;
1791 cluster_bits = ffs(cluster_size) - 1;
1792 if (cluster_bits < MIN_CLUSTER_BITS || cluster_bits > MAX_CLUSTER_BITS ||
1793 (1 << cluster_bits) != cluster_size)
1795 error_setg(errp, "Cluster size must be a power of two between %d and "
1796 "%dk", 1 << MIN_CLUSTER_BITS, 1 << (MAX_CLUSTER_BITS - 10));
1797 return -EINVAL;
1801 * Open the image file and write a minimal qcow2 header.
1803 * We keep things simple and start with a zero-sized image. We also
1804 * do without refcount blocks or a L1 table for now. We'll fix the
1805 * inconsistency later.
1807 * We do need a refcount table because growing the refcount table means
1808 * allocating two new refcount blocks - the seconds of which would be at
1809 * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
1810 * size for any qcow2 image.
1812 BlockDriverState* bs;
1813 QCowHeader *header;
1814 uint64_t* refcount_table;
1815 Error *local_err = NULL;
1816 int ret;
1818 if (prealloc == PREALLOC_MODE_FULL || prealloc == PREALLOC_MODE_FALLOC) {
1819 /* Note: The following calculation does not need to be exact; if it is a
1820 * bit off, either some bytes will be "leaked" (which is fine) or we
1821 * will need to increase the file size by some bytes (which is fine,
1822 * too, as long as the bulk is allocated here). Therefore, using
1823 * floating point arithmetic is fine. */
1824 int64_t meta_size = 0;
1825 uint64_t nreftablee, nrefblocke, nl1e, nl2e;
1826 int64_t aligned_total_size = align_offset(total_size, cluster_size);
1827 int refblock_bits, refblock_size;
1828 /* refcount entry size in bytes */
1829 double rces = (1 << refcount_order) / 8.;
1831 /* see qcow2_open() */
1832 refblock_bits = cluster_bits - (refcount_order - 3);
1833 refblock_size = 1 << refblock_bits;
1835 /* header: 1 cluster */
1836 meta_size += cluster_size;
1838 /* total size of L2 tables */
1839 nl2e = aligned_total_size / cluster_size;
1840 nl2e = align_offset(nl2e, cluster_size / sizeof(uint64_t));
1841 meta_size += nl2e * sizeof(uint64_t);
1843 /* total size of L1 tables */
1844 nl1e = nl2e * sizeof(uint64_t) / cluster_size;
1845 nl1e = align_offset(nl1e, cluster_size / sizeof(uint64_t));
1846 meta_size += nl1e * sizeof(uint64_t);
1848 /* total size of refcount blocks
1850 * note: every host cluster is reference-counted, including metadata
1851 * (even refcount blocks are recursively included).
1852 * Let:
1853 * a = total_size (this is the guest disk size)
1854 * m = meta size not including refcount blocks and refcount tables
1855 * c = cluster size
1856 * y1 = number of refcount blocks entries
1857 * y2 = meta size including everything
1858 * rces = refcount entry size in bytes
1859 * then,
1860 * y1 = (y2 + a)/c
1861 * y2 = y1 * rces + y1 * rces * sizeof(u64) / c + m
1862 * we can get y1:
1863 * y1 = (a + m) / (c - rces - rces * sizeof(u64) / c)
1865 nrefblocke = (aligned_total_size + meta_size + cluster_size)
1866 / (cluster_size - rces - rces * sizeof(uint64_t)
1867 / cluster_size);
1868 meta_size += DIV_ROUND_UP(nrefblocke, refblock_size) * cluster_size;
1870 /* total size of refcount tables */
1871 nreftablee = nrefblocke / refblock_size;
1872 nreftablee = align_offset(nreftablee, cluster_size / sizeof(uint64_t));
1873 meta_size += nreftablee * sizeof(uint64_t);
1875 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
1876 aligned_total_size + meta_size, &error_abort);
1877 qemu_opt_set(opts, BLOCK_OPT_PREALLOC, PreallocMode_lookup[prealloc],
1878 &error_abort);
1881 ret = bdrv_create_file(filename, opts, &local_err);
1882 if (ret < 0) {
1883 error_propagate(errp, local_err);
1884 return ret;
1887 bs = NULL;
1888 ret = bdrv_open(&bs, filename, NULL, NULL, BDRV_O_RDWR | BDRV_O_PROTOCOL,
1889 NULL, &local_err);
1890 if (ret < 0) {
1891 error_propagate(errp, local_err);
1892 return ret;
1895 /* Write the header */
1896 QEMU_BUILD_BUG_ON((1 << MIN_CLUSTER_BITS) < sizeof(*header));
1897 header = g_malloc0(cluster_size);
1898 *header = (QCowHeader) {
1899 .magic = cpu_to_be32(QCOW_MAGIC),
1900 .version = cpu_to_be32(version),
1901 .cluster_bits = cpu_to_be32(cluster_bits),
1902 .size = cpu_to_be64(0),
1903 .l1_table_offset = cpu_to_be64(0),
1904 .l1_size = cpu_to_be32(0),
1905 .refcount_table_offset = cpu_to_be64(cluster_size),
1906 .refcount_table_clusters = cpu_to_be32(1),
1907 .refcount_order = cpu_to_be32(refcount_order),
1908 .header_length = cpu_to_be32(sizeof(*header)),
1911 if (flags & BLOCK_FLAG_ENCRYPT) {
1912 header->crypt_method = cpu_to_be32(QCOW_CRYPT_AES);
1913 } else {
1914 header->crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
1917 if (flags & BLOCK_FLAG_LAZY_REFCOUNTS) {
1918 header->compatible_features |=
1919 cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS);
1922 ret = bdrv_pwrite(bs, 0, header, cluster_size);
1923 g_free(header);
1924 if (ret < 0) {
1925 error_setg_errno(errp, -ret, "Could not write qcow2 header");
1926 goto out;
1929 /* Write a refcount table with one refcount block */
1930 refcount_table = g_malloc0(2 * cluster_size);
1931 refcount_table[0] = cpu_to_be64(2 * cluster_size);
1932 ret = bdrv_pwrite(bs, cluster_size, refcount_table, 2 * cluster_size);
1933 g_free(refcount_table);
1935 if (ret < 0) {
1936 error_setg_errno(errp, -ret, "Could not write refcount table");
1937 goto out;
1940 bdrv_unref(bs);
1941 bs = NULL;
1944 * And now open the image and make it consistent first (i.e. increase the
1945 * refcount of the cluster that is occupied by the header and the refcount
1946 * table)
1948 ret = bdrv_open(&bs, filename, NULL, NULL,
1949 BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_NO_FLUSH,
1950 &bdrv_qcow2, &local_err);
1951 if (ret < 0) {
1952 error_propagate(errp, local_err);
1953 goto out;
1956 ret = qcow2_alloc_clusters(bs, 3 * cluster_size);
1957 if (ret < 0) {
1958 error_setg_errno(errp, -ret, "Could not allocate clusters for qcow2 "
1959 "header and refcount table");
1960 goto out;
1962 } else if (ret != 0) {
1963 error_report("Huh, first cluster in empty image is already in use?");
1964 abort();
1967 /* Okay, now that we have a valid image, let's give it the right size */
1968 ret = bdrv_truncate(bs, total_size);
1969 if (ret < 0) {
1970 error_setg_errno(errp, -ret, "Could not resize image");
1971 goto out;
1974 /* Want a backing file? There you go.*/
1975 if (backing_file) {
1976 ret = bdrv_change_backing_file(bs, backing_file, backing_format);
1977 if (ret < 0) {
1978 error_setg_errno(errp, -ret, "Could not assign backing file '%s' "
1979 "with format '%s'", backing_file, backing_format);
1980 goto out;
1984 /* And if we're supposed to preallocate metadata, do that now */
1985 if (prealloc != PREALLOC_MODE_OFF) {
1986 BDRVQcowState *s = bs->opaque;
1987 qemu_co_mutex_lock(&s->lock);
1988 ret = preallocate(bs);
1989 qemu_co_mutex_unlock(&s->lock);
1990 if (ret < 0) {
1991 error_setg_errno(errp, -ret, "Could not preallocate metadata");
1992 goto out;
1996 bdrv_unref(bs);
1997 bs = NULL;
1999 /* Reopen the image without BDRV_O_NO_FLUSH to flush it before returning */
2000 ret = bdrv_open(&bs, filename, NULL, NULL,
2001 BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_NO_BACKING,
2002 &bdrv_qcow2, &local_err);
2003 if (local_err) {
2004 error_propagate(errp, local_err);
2005 goto out;
2008 ret = 0;
2009 out:
2010 if (bs) {
2011 bdrv_unref(bs);
2013 return ret;
2016 static int qcow2_create(const char *filename, QemuOpts *opts, Error **errp)
2018 char *backing_file = NULL;
2019 char *backing_fmt = NULL;
2020 char *buf = NULL;
2021 uint64_t size = 0;
2022 int flags = 0;
2023 size_t cluster_size = DEFAULT_CLUSTER_SIZE;
2024 PreallocMode prealloc;
2025 int version = 3;
2026 uint64_t refcount_bits = 16;
2027 int refcount_order;
2028 Error *local_err = NULL;
2029 int ret;
2031 /* Read out options */
2032 size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
2033 BDRV_SECTOR_SIZE);
2034 backing_file = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
2035 backing_fmt = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FMT);
2036 if (qemu_opt_get_bool_del(opts, BLOCK_OPT_ENCRYPT, false)) {
2037 flags |= BLOCK_FLAG_ENCRYPT;
2039 cluster_size = qemu_opt_get_size_del(opts, BLOCK_OPT_CLUSTER_SIZE,
2040 DEFAULT_CLUSTER_SIZE);
2041 buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
2042 prealloc = qapi_enum_parse(PreallocMode_lookup, buf,
2043 PREALLOC_MODE_MAX, PREALLOC_MODE_OFF,
2044 &local_err);
2045 if (local_err) {
2046 error_propagate(errp, local_err);
2047 ret = -EINVAL;
2048 goto finish;
2050 g_free(buf);
2051 buf = qemu_opt_get_del(opts, BLOCK_OPT_COMPAT_LEVEL);
2052 if (!buf) {
2053 /* keep the default */
2054 } else if (!strcmp(buf, "0.10")) {
2055 version = 2;
2056 } else if (!strcmp(buf, "1.1")) {
2057 version = 3;
2058 } else {
2059 error_setg(errp, "Invalid compatibility level: '%s'", buf);
2060 ret = -EINVAL;
2061 goto finish;
2064 if (qemu_opt_get_bool_del(opts, BLOCK_OPT_LAZY_REFCOUNTS, false)) {
2065 flags |= BLOCK_FLAG_LAZY_REFCOUNTS;
2068 if (backing_file && prealloc != PREALLOC_MODE_OFF) {
2069 error_setg(errp, "Backing file and preallocation cannot be used at "
2070 "the same time");
2071 ret = -EINVAL;
2072 goto finish;
2075 if (version < 3 && (flags & BLOCK_FLAG_LAZY_REFCOUNTS)) {
2076 error_setg(errp, "Lazy refcounts only supported with compatibility "
2077 "level 1.1 and above (use compat=1.1 or greater)");
2078 ret = -EINVAL;
2079 goto finish;
2082 refcount_bits = qemu_opt_get_number_del(opts, BLOCK_OPT_REFCOUNT_BITS,
2083 refcount_bits);
2084 if (refcount_bits > 64 || !is_power_of_2(refcount_bits)) {
2085 error_setg(errp, "Refcount width must be a power of two and may not "
2086 "exceed 64 bits");
2087 ret = -EINVAL;
2088 goto finish;
2091 if (version < 3 && refcount_bits != 16) {
2092 error_setg(errp, "Different refcount widths than 16 bits require "
2093 "compatibility level 1.1 or above (use compat=1.1 or "
2094 "greater)");
2095 ret = -EINVAL;
2096 goto finish;
2099 refcount_order = ffs(refcount_bits) - 1;
2101 ret = qcow2_create2(filename, size, backing_file, backing_fmt, flags,
2102 cluster_size, prealloc, opts, version, refcount_order,
2103 &local_err);
2104 if (local_err) {
2105 error_propagate(errp, local_err);
2108 finish:
2109 g_free(backing_file);
2110 g_free(backing_fmt);
2111 g_free(buf);
2112 return ret;
2115 static coroutine_fn int qcow2_co_write_zeroes(BlockDriverState *bs,
2116 int64_t sector_num, int nb_sectors, BdrvRequestFlags flags)
2118 int ret;
2119 BDRVQcowState *s = bs->opaque;
2121 /* Emulate misaligned zero writes */
2122 if (sector_num % s->cluster_sectors || nb_sectors % s->cluster_sectors) {
2123 return -ENOTSUP;
2126 /* Whatever is left can use real zero clusters */
2127 qemu_co_mutex_lock(&s->lock);
2128 ret = qcow2_zero_clusters(bs, sector_num << BDRV_SECTOR_BITS,
2129 nb_sectors);
2130 qemu_co_mutex_unlock(&s->lock);
2132 return ret;
2135 static coroutine_fn int qcow2_co_discard(BlockDriverState *bs,
2136 int64_t sector_num, int nb_sectors)
2138 int ret;
2139 BDRVQcowState *s = bs->opaque;
2141 qemu_co_mutex_lock(&s->lock);
2142 ret = qcow2_discard_clusters(bs, sector_num << BDRV_SECTOR_BITS,
2143 nb_sectors, QCOW2_DISCARD_REQUEST, false);
2144 qemu_co_mutex_unlock(&s->lock);
2145 return ret;
2148 static int qcow2_truncate(BlockDriverState *bs, int64_t offset)
2150 BDRVQcowState *s = bs->opaque;
2151 int64_t new_l1_size;
2152 int ret;
2154 if (offset & 511) {
2155 error_report("The new size must be a multiple of 512");
2156 return -EINVAL;
2159 /* cannot proceed if image has snapshots */
2160 if (s->nb_snapshots) {
2161 error_report("Can't resize an image which has snapshots");
2162 return -ENOTSUP;
2165 /* shrinking is currently not supported */
2166 if (offset < bs->total_sectors * 512) {
2167 error_report("qcow2 doesn't support shrinking images yet");
2168 return -ENOTSUP;
2171 new_l1_size = size_to_l1(s, offset);
2172 ret = qcow2_grow_l1_table(bs, new_l1_size, true);
2173 if (ret < 0) {
2174 return ret;
2177 /* write updated header.size */
2178 offset = cpu_to_be64(offset);
2179 ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, size),
2180 &offset, sizeof(uint64_t));
2181 if (ret < 0) {
2182 return ret;
2185 s->l1_vm_state_index = new_l1_size;
2186 return 0;
2189 /* XXX: put compressed sectors first, then all the cluster aligned
2190 tables to avoid losing bytes in alignment */
2191 static int qcow2_write_compressed(BlockDriverState *bs, int64_t sector_num,
2192 const uint8_t *buf, int nb_sectors)
2194 BDRVQcowState *s = bs->opaque;
2195 z_stream strm;
2196 int ret, out_len;
2197 uint8_t *out_buf;
2198 uint64_t cluster_offset;
2200 if (nb_sectors == 0) {
2201 /* align end of file to a sector boundary to ease reading with
2202 sector based I/Os */
2203 cluster_offset = bdrv_getlength(bs->file);
2204 return bdrv_truncate(bs->file, cluster_offset);
2207 if (nb_sectors != s->cluster_sectors) {
2208 ret = -EINVAL;
2210 /* Zero-pad last write if image size is not cluster aligned */
2211 if (sector_num + nb_sectors == bs->total_sectors &&
2212 nb_sectors < s->cluster_sectors) {
2213 uint8_t *pad_buf = qemu_blockalign(bs, s->cluster_size);
2214 memset(pad_buf, 0, s->cluster_size);
2215 memcpy(pad_buf, buf, nb_sectors * BDRV_SECTOR_SIZE);
2216 ret = qcow2_write_compressed(bs, sector_num,
2217 pad_buf, s->cluster_sectors);
2218 qemu_vfree(pad_buf);
2220 return ret;
2223 out_buf = g_malloc(s->cluster_size + (s->cluster_size / 1000) + 128);
2225 /* best compression, small window, no zlib header */
2226 memset(&strm, 0, sizeof(strm));
2227 ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
2228 Z_DEFLATED, -12,
2229 9, Z_DEFAULT_STRATEGY);
2230 if (ret != 0) {
2231 ret = -EINVAL;
2232 goto fail;
2235 strm.avail_in = s->cluster_size;
2236 strm.next_in = (uint8_t *)buf;
2237 strm.avail_out = s->cluster_size;
2238 strm.next_out = out_buf;
2240 ret = deflate(&strm, Z_FINISH);
2241 if (ret != Z_STREAM_END && ret != Z_OK) {
2242 deflateEnd(&strm);
2243 ret = -EINVAL;
2244 goto fail;
2246 out_len = strm.next_out - out_buf;
2248 deflateEnd(&strm);
2250 if (ret != Z_STREAM_END || out_len >= s->cluster_size) {
2251 /* could not compress: write normal cluster */
2252 ret = bdrv_write(bs, sector_num, buf, s->cluster_sectors);
2253 if (ret < 0) {
2254 goto fail;
2256 } else {
2257 cluster_offset = qcow2_alloc_compressed_cluster_offset(bs,
2258 sector_num << 9, out_len);
2259 if (!cluster_offset) {
2260 ret = -EIO;
2261 goto fail;
2263 cluster_offset &= s->cluster_offset_mask;
2265 ret = qcow2_pre_write_overlap_check(bs, 0, cluster_offset, out_len);
2266 if (ret < 0) {
2267 goto fail;
2270 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_COMPRESSED);
2271 ret = bdrv_pwrite(bs->file, cluster_offset, out_buf, out_len);
2272 if (ret < 0) {
2273 goto fail;
2277 ret = 0;
2278 fail:
2279 g_free(out_buf);
2280 return ret;
2283 static int make_completely_empty(BlockDriverState *bs)
2285 BDRVQcowState *s = bs->opaque;
2286 int ret, l1_clusters;
2287 int64_t offset;
2288 uint64_t *new_reftable = NULL;
2289 uint64_t rt_entry, l1_size2;
2290 struct {
2291 uint64_t l1_offset;
2292 uint64_t reftable_offset;
2293 uint32_t reftable_clusters;
2294 } QEMU_PACKED l1_ofs_rt_ofs_cls;
2296 ret = qcow2_cache_empty(bs, s->l2_table_cache);
2297 if (ret < 0) {
2298 goto fail;
2301 ret = qcow2_cache_empty(bs, s->refcount_block_cache);
2302 if (ret < 0) {
2303 goto fail;
2306 /* Refcounts will be broken utterly */
2307 ret = qcow2_mark_dirty(bs);
2308 if (ret < 0) {
2309 goto fail;
2312 BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
2314 l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / sizeof(uint64_t));
2315 l1_size2 = (uint64_t)s->l1_size * sizeof(uint64_t);
2317 /* After this call, neither the in-memory nor the on-disk refcount
2318 * information accurately describe the actual references */
2320 ret = bdrv_write_zeroes(bs->file, s->l1_table_offset / BDRV_SECTOR_SIZE,
2321 l1_clusters * s->cluster_sectors, 0);
2322 if (ret < 0) {
2323 goto fail_broken_refcounts;
2325 memset(s->l1_table, 0, l1_size2);
2327 BLKDBG_EVENT(bs->file, BLKDBG_EMPTY_IMAGE_PREPARE);
2329 /* Overwrite enough clusters at the beginning of the sectors to place
2330 * the refcount table, a refcount block and the L1 table in; this may
2331 * overwrite parts of the existing refcount and L1 table, which is not
2332 * an issue because the dirty flag is set, complete data loss is in fact
2333 * desired and partial data loss is consequently fine as well */
2334 ret = bdrv_write_zeroes(bs->file, s->cluster_size / BDRV_SECTOR_SIZE,
2335 (2 + l1_clusters) * s->cluster_size /
2336 BDRV_SECTOR_SIZE, 0);
2337 /* This call (even if it failed overall) may have overwritten on-disk
2338 * refcount structures; in that case, the in-memory refcount information
2339 * will probably differ from the on-disk information which makes the BDS
2340 * unusable */
2341 if (ret < 0) {
2342 goto fail_broken_refcounts;
2345 BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
2346 BLKDBG_EVENT(bs->file, BLKDBG_REFTABLE_UPDATE);
2348 /* "Create" an empty reftable (one cluster) directly after the image
2349 * header and an empty L1 table three clusters after the image header;
2350 * the cluster between those two will be used as the first refblock */
2351 cpu_to_be64w(&l1_ofs_rt_ofs_cls.l1_offset, 3 * s->cluster_size);
2352 cpu_to_be64w(&l1_ofs_rt_ofs_cls.reftable_offset, s->cluster_size);
2353 cpu_to_be32w(&l1_ofs_rt_ofs_cls.reftable_clusters, 1);
2354 ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, l1_table_offset),
2355 &l1_ofs_rt_ofs_cls, sizeof(l1_ofs_rt_ofs_cls));
2356 if (ret < 0) {
2357 goto fail_broken_refcounts;
2360 s->l1_table_offset = 3 * s->cluster_size;
2362 new_reftable = g_try_new0(uint64_t, s->cluster_size / sizeof(uint64_t));
2363 if (!new_reftable) {
2364 ret = -ENOMEM;
2365 goto fail_broken_refcounts;
2368 s->refcount_table_offset = s->cluster_size;
2369 s->refcount_table_size = s->cluster_size / sizeof(uint64_t);
2371 g_free(s->refcount_table);
2372 s->refcount_table = new_reftable;
2373 new_reftable = NULL;
2375 /* Now the in-memory refcount information again corresponds to the on-disk
2376 * information (reftable is empty and no refblocks (the refblock cache is
2377 * empty)); however, this means some clusters (e.g. the image header) are
2378 * referenced, but not refcounted, but the normal qcow2 code assumes that
2379 * the in-memory information is always correct */
2381 BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_ALLOC);
2383 /* Enter the first refblock into the reftable */
2384 rt_entry = cpu_to_be64(2 * s->cluster_size);
2385 ret = bdrv_pwrite_sync(bs->file, s->cluster_size,
2386 &rt_entry, sizeof(rt_entry));
2387 if (ret < 0) {
2388 goto fail_broken_refcounts;
2390 s->refcount_table[0] = 2 * s->cluster_size;
2392 s->free_cluster_index = 0;
2393 assert(3 + l1_clusters <= s->refcount_block_size);
2394 offset = qcow2_alloc_clusters(bs, 3 * s->cluster_size + l1_size2);
2395 if (offset < 0) {
2396 ret = offset;
2397 goto fail_broken_refcounts;
2398 } else if (offset > 0) {
2399 error_report("First cluster in emptied image is in use");
2400 abort();
2403 /* Now finally the in-memory information corresponds to the on-disk
2404 * structures and is correct */
2405 ret = qcow2_mark_clean(bs);
2406 if (ret < 0) {
2407 goto fail;
2410 ret = bdrv_truncate(bs->file, (3 + l1_clusters) * s->cluster_size);
2411 if (ret < 0) {
2412 goto fail;
2415 return 0;
2417 fail_broken_refcounts:
2418 /* The BDS is unusable at this point. If we wanted to make it usable, we
2419 * would have to call qcow2_refcount_close(), qcow2_refcount_init(),
2420 * qcow2_check_refcounts(), qcow2_refcount_close() and qcow2_refcount_init()
2421 * again. However, because the functions which could have caused this error
2422 * path to be taken are used by those functions as well, it's very likely
2423 * that that sequence will fail as well. Therefore, just eject the BDS. */
2424 bs->drv = NULL;
2426 fail:
2427 g_free(new_reftable);
2428 return ret;
2431 static int qcow2_make_empty(BlockDriverState *bs)
2433 BDRVQcowState *s = bs->opaque;
2434 uint64_t start_sector;
2435 int sector_step = INT_MAX / BDRV_SECTOR_SIZE;
2436 int l1_clusters, ret = 0;
2438 l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / sizeof(uint64_t));
2440 if (s->qcow_version >= 3 && !s->snapshots &&
2441 3 + l1_clusters <= s->refcount_block_size) {
2442 /* The following function only works for qcow2 v3 images (it requires
2443 * the dirty flag) and only as long as there are no snapshots (because
2444 * it completely empties the image). Furthermore, the L1 table and three
2445 * additional clusters (image header, refcount table, one refcount
2446 * block) have to fit inside one refcount block. */
2447 return make_completely_empty(bs);
2450 /* This fallback code simply discards every active cluster; this is slow,
2451 * but works in all cases */
2452 for (start_sector = 0; start_sector < bs->total_sectors;
2453 start_sector += sector_step)
2455 /* As this function is generally used after committing an external
2456 * snapshot, QCOW2_DISCARD_SNAPSHOT seems appropriate. Also, the
2457 * default action for this kind of discard is to pass the discard,
2458 * which will ideally result in an actually smaller image file, as
2459 * is probably desired. */
2460 ret = qcow2_discard_clusters(bs, start_sector * BDRV_SECTOR_SIZE,
2461 MIN(sector_step,
2462 bs->total_sectors - start_sector),
2463 QCOW2_DISCARD_SNAPSHOT, true);
2464 if (ret < 0) {
2465 break;
2469 return ret;
2472 static coroutine_fn int qcow2_co_flush_to_os(BlockDriverState *bs)
2474 BDRVQcowState *s = bs->opaque;
2475 int ret;
2477 qemu_co_mutex_lock(&s->lock);
2478 ret = qcow2_cache_flush(bs, s->l2_table_cache);
2479 if (ret < 0) {
2480 qemu_co_mutex_unlock(&s->lock);
2481 return ret;
2484 if (qcow2_need_accurate_refcounts(s)) {
2485 ret = qcow2_cache_flush(bs, s->refcount_block_cache);
2486 if (ret < 0) {
2487 qemu_co_mutex_unlock(&s->lock);
2488 return ret;
2491 qemu_co_mutex_unlock(&s->lock);
2493 return 0;
2496 static int qcow2_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
2498 BDRVQcowState *s = bs->opaque;
2499 bdi->unallocated_blocks_are_zero = true;
2500 bdi->can_write_zeroes_with_unmap = (s->qcow_version >= 3);
2501 bdi->cluster_size = s->cluster_size;
2502 bdi->vm_state_offset = qcow2_vm_state_offset(s);
2503 return 0;
2506 static ImageInfoSpecific *qcow2_get_specific_info(BlockDriverState *bs)
2508 BDRVQcowState *s = bs->opaque;
2509 ImageInfoSpecific *spec_info = g_new(ImageInfoSpecific, 1);
2511 *spec_info = (ImageInfoSpecific){
2512 .kind = IMAGE_INFO_SPECIFIC_KIND_QCOW2,
2514 .qcow2 = g_new(ImageInfoSpecificQCow2, 1),
2517 if (s->qcow_version == 2) {
2518 *spec_info->qcow2 = (ImageInfoSpecificQCow2){
2519 .compat = g_strdup("0.10"),
2520 .refcount_bits = s->refcount_bits,
2522 } else if (s->qcow_version == 3) {
2523 *spec_info->qcow2 = (ImageInfoSpecificQCow2){
2524 .compat = g_strdup("1.1"),
2525 .lazy_refcounts = s->compatible_features &
2526 QCOW2_COMPAT_LAZY_REFCOUNTS,
2527 .has_lazy_refcounts = true,
2528 .corrupt = s->incompatible_features &
2529 QCOW2_INCOMPAT_CORRUPT,
2530 .has_corrupt = true,
2531 .refcount_bits = s->refcount_bits,
2535 return spec_info;
2538 #if 0
2539 static void dump_refcounts(BlockDriverState *bs)
2541 BDRVQcowState *s = bs->opaque;
2542 int64_t nb_clusters, k, k1, size;
2543 int refcount;
2545 size = bdrv_getlength(bs->file);
2546 nb_clusters = size_to_clusters(s, size);
2547 for(k = 0; k < nb_clusters;) {
2548 k1 = k;
2549 refcount = get_refcount(bs, k);
2550 k++;
2551 while (k < nb_clusters && get_refcount(bs, k) == refcount)
2552 k++;
2553 printf("%" PRId64 ": refcount=%d nb=%" PRId64 "\n", k, refcount,
2554 k - k1);
2557 #endif
2559 static int qcow2_save_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
2560 int64_t pos)
2562 BDRVQcowState *s = bs->opaque;
2563 int64_t total_sectors = bs->total_sectors;
2564 bool zero_beyond_eof = bs->zero_beyond_eof;
2565 int ret;
2567 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_SAVE);
2568 bs->zero_beyond_eof = false;
2569 ret = bdrv_pwritev(bs, qcow2_vm_state_offset(s) + pos, qiov);
2570 bs->zero_beyond_eof = zero_beyond_eof;
2572 /* bdrv_co_do_writev will have increased the total_sectors value to include
2573 * the VM state - the VM state is however not an actual part of the block
2574 * device, therefore, we need to restore the old value. */
2575 bs->total_sectors = total_sectors;
2577 return ret;
2580 static int qcow2_load_vmstate(BlockDriverState *bs, uint8_t *buf,
2581 int64_t pos, int size)
2583 BDRVQcowState *s = bs->opaque;
2584 bool zero_beyond_eof = bs->zero_beyond_eof;
2585 int ret;
2587 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_LOAD);
2588 bs->zero_beyond_eof = false;
2589 ret = bdrv_pread(bs, qcow2_vm_state_offset(s) + pos, buf, size);
2590 bs->zero_beyond_eof = zero_beyond_eof;
2592 return ret;
2596 * Downgrades an image's version. To achieve this, any incompatible features
2597 * have to be removed.
2599 static int qcow2_downgrade(BlockDriverState *bs, int target_version,
2600 BlockDriverAmendStatusCB *status_cb)
2602 BDRVQcowState *s = bs->opaque;
2603 int current_version = s->qcow_version;
2604 int ret;
2606 if (target_version == current_version) {
2607 return 0;
2608 } else if (target_version > current_version) {
2609 return -EINVAL;
2610 } else if (target_version != 2) {
2611 return -EINVAL;
2614 if (s->refcount_order != 4) {
2615 /* we would have to convert the image to a refcount_order == 4 image
2616 * here; however, since qemu (at the time of writing this) does not
2617 * support anything different than 4 anyway, there is no point in doing
2618 * so right now; however, we should error out (if qemu supports this in
2619 * the future and this code has not been adapted) */
2620 error_report("qcow2_downgrade: Image refcount orders other than 4 are "
2621 "currently not supported.");
2622 return -ENOTSUP;
2625 /* clear incompatible features */
2626 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
2627 ret = qcow2_mark_clean(bs);
2628 if (ret < 0) {
2629 return ret;
2633 /* with QCOW2_INCOMPAT_CORRUPT, it is pretty much impossible to get here in
2634 * the first place; if that happens nonetheless, returning -ENOTSUP is the
2635 * best thing to do anyway */
2637 if (s->incompatible_features) {
2638 return -ENOTSUP;
2641 /* since we can ignore compatible features, we can set them to 0 as well */
2642 s->compatible_features = 0;
2643 /* if lazy refcounts have been used, they have already been fixed through
2644 * clearing the dirty flag */
2646 /* clearing autoclear features is trivial */
2647 s->autoclear_features = 0;
2649 ret = qcow2_expand_zero_clusters(bs, status_cb);
2650 if (ret < 0) {
2651 return ret;
2654 s->qcow_version = target_version;
2655 ret = qcow2_update_header(bs);
2656 if (ret < 0) {
2657 s->qcow_version = current_version;
2658 return ret;
2660 return 0;
2663 static int qcow2_amend_options(BlockDriverState *bs, QemuOpts *opts,
2664 BlockDriverAmendStatusCB *status_cb)
2666 BDRVQcowState *s = bs->opaque;
2667 int old_version = s->qcow_version, new_version = old_version;
2668 uint64_t new_size = 0;
2669 const char *backing_file = NULL, *backing_format = NULL;
2670 bool lazy_refcounts = s->use_lazy_refcounts;
2671 const char *compat = NULL;
2672 uint64_t cluster_size = s->cluster_size;
2673 bool encrypt;
2674 int ret;
2675 QemuOptDesc *desc = opts->list->desc;
2677 while (desc && desc->name) {
2678 if (!qemu_opt_find(opts, desc->name)) {
2679 /* only change explicitly defined options */
2680 desc++;
2681 continue;
2684 if (!strcmp(desc->name, BLOCK_OPT_COMPAT_LEVEL)) {
2685 compat = qemu_opt_get(opts, BLOCK_OPT_COMPAT_LEVEL);
2686 if (!compat) {
2687 /* preserve default */
2688 } else if (!strcmp(compat, "0.10")) {
2689 new_version = 2;
2690 } else if (!strcmp(compat, "1.1")) {
2691 new_version = 3;
2692 } else {
2693 fprintf(stderr, "Unknown compatibility level %s.\n", compat);
2694 return -EINVAL;
2696 } else if (!strcmp(desc->name, BLOCK_OPT_PREALLOC)) {
2697 fprintf(stderr, "Cannot change preallocation mode.\n");
2698 return -ENOTSUP;
2699 } else if (!strcmp(desc->name, BLOCK_OPT_SIZE)) {
2700 new_size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, 0);
2701 } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FILE)) {
2702 backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
2703 } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FMT)) {
2704 backing_format = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
2705 } else if (!strcmp(desc->name, BLOCK_OPT_ENCRYPT)) {
2706 encrypt = qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT,
2707 s->crypt_method);
2708 if (encrypt != !!s->crypt_method) {
2709 fprintf(stderr, "Changing the encryption flag is not "
2710 "supported.\n");
2711 return -ENOTSUP;
2713 } else if (!strcmp(desc->name, BLOCK_OPT_CLUSTER_SIZE)) {
2714 cluster_size = qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE,
2715 cluster_size);
2716 if (cluster_size != s->cluster_size) {
2717 fprintf(stderr, "Changing the cluster size is not "
2718 "supported.\n");
2719 return -ENOTSUP;
2721 } else if (!strcmp(desc->name, BLOCK_OPT_LAZY_REFCOUNTS)) {
2722 lazy_refcounts = qemu_opt_get_bool(opts, BLOCK_OPT_LAZY_REFCOUNTS,
2723 lazy_refcounts);
2724 } else if (!strcmp(desc->name, BLOCK_OPT_REFCOUNT_BITS)) {
2725 error_report("Cannot change refcount entry width");
2726 return -ENOTSUP;
2727 } else {
2728 /* if this assertion fails, this probably means a new option was
2729 * added without having it covered here */
2730 assert(false);
2733 desc++;
2736 if (new_version != old_version) {
2737 if (new_version > old_version) {
2738 /* Upgrade */
2739 s->qcow_version = new_version;
2740 ret = qcow2_update_header(bs);
2741 if (ret < 0) {
2742 s->qcow_version = old_version;
2743 return ret;
2745 } else {
2746 ret = qcow2_downgrade(bs, new_version, status_cb);
2747 if (ret < 0) {
2748 return ret;
2753 if (backing_file || backing_format) {
2754 ret = qcow2_change_backing_file(bs, backing_file ?: bs->backing_file,
2755 backing_format ?: bs->backing_format);
2756 if (ret < 0) {
2757 return ret;
2761 if (s->use_lazy_refcounts != lazy_refcounts) {
2762 if (lazy_refcounts) {
2763 if (s->qcow_version < 3) {
2764 fprintf(stderr, "Lazy refcounts only supported with compatibility "
2765 "level 1.1 and above (use compat=1.1 or greater)\n");
2766 return -EINVAL;
2768 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
2769 ret = qcow2_update_header(bs);
2770 if (ret < 0) {
2771 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
2772 return ret;
2774 s->use_lazy_refcounts = true;
2775 } else {
2776 /* make image clean first */
2777 ret = qcow2_mark_clean(bs);
2778 if (ret < 0) {
2779 return ret;
2781 /* now disallow lazy refcounts */
2782 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
2783 ret = qcow2_update_header(bs);
2784 if (ret < 0) {
2785 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
2786 return ret;
2788 s->use_lazy_refcounts = false;
2792 if (new_size) {
2793 ret = bdrv_truncate(bs, new_size);
2794 if (ret < 0) {
2795 return ret;
2799 return 0;
2803 * If offset or size are negative, respectively, they will not be included in
2804 * the BLOCK_IMAGE_CORRUPTED event emitted.
2805 * fatal will be ignored for read-only BDS; corruptions found there will always
2806 * be considered non-fatal.
2808 void qcow2_signal_corruption(BlockDriverState *bs, bool fatal, int64_t offset,
2809 int64_t size, const char *message_format, ...)
2811 BDRVQcowState *s = bs->opaque;
2812 char *message;
2813 va_list ap;
2815 fatal = fatal && !bs->read_only;
2817 if (s->signaled_corruption &&
2818 (!fatal || (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT)))
2820 return;
2823 va_start(ap, message_format);
2824 message = g_strdup_vprintf(message_format, ap);
2825 va_end(ap);
2827 if (fatal) {
2828 fprintf(stderr, "qcow2: Marking image as corrupt: %s; further "
2829 "corruption events will be suppressed\n", message);
2830 } else {
2831 fprintf(stderr, "qcow2: Image is corrupt: %s; further non-fatal "
2832 "corruption events will be suppressed\n", message);
2835 qapi_event_send_block_image_corrupted(bdrv_get_device_name(bs), message,
2836 offset >= 0, offset, size >= 0, size,
2837 fatal, &error_abort);
2838 g_free(message);
2840 if (fatal) {
2841 qcow2_mark_corrupt(bs);
2842 bs->drv = NULL; /* make BDS unusable */
2845 s->signaled_corruption = true;
2848 static QemuOptsList qcow2_create_opts = {
2849 .name = "qcow2-create-opts",
2850 .head = QTAILQ_HEAD_INITIALIZER(qcow2_create_opts.head),
2851 .desc = {
2853 .name = BLOCK_OPT_SIZE,
2854 .type = QEMU_OPT_SIZE,
2855 .help = "Virtual disk size"
2858 .name = BLOCK_OPT_COMPAT_LEVEL,
2859 .type = QEMU_OPT_STRING,
2860 .help = "Compatibility level (0.10 or 1.1)"
2863 .name = BLOCK_OPT_BACKING_FILE,
2864 .type = QEMU_OPT_STRING,
2865 .help = "File name of a base image"
2868 .name = BLOCK_OPT_BACKING_FMT,
2869 .type = QEMU_OPT_STRING,
2870 .help = "Image format of the base image"
2873 .name = BLOCK_OPT_ENCRYPT,
2874 .type = QEMU_OPT_BOOL,
2875 .help = "Encrypt the image",
2876 .def_value_str = "off"
2879 .name = BLOCK_OPT_CLUSTER_SIZE,
2880 .type = QEMU_OPT_SIZE,
2881 .help = "qcow2 cluster size",
2882 .def_value_str = stringify(DEFAULT_CLUSTER_SIZE)
2885 .name = BLOCK_OPT_PREALLOC,
2886 .type = QEMU_OPT_STRING,
2887 .help = "Preallocation mode (allowed values: off, metadata, "
2888 "falloc, full)"
2891 .name = BLOCK_OPT_LAZY_REFCOUNTS,
2892 .type = QEMU_OPT_BOOL,
2893 .help = "Postpone refcount updates",
2894 .def_value_str = "off"
2897 .name = BLOCK_OPT_REFCOUNT_BITS,
2898 .type = QEMU_OPT_NUMBER,
2899 .help = "Width of a reference count entry in bits",
2900 .def_value_str = "16"
2902 { /* end of list */ }
2906 BlockDriver bdrv_qcow2 = {
2907 .format_name = "qcow2",
2908 .instance_size = sizeof(BDRVQcowState),
2909 .bdrv_probe = qcow2_probe,
2910 .bdrv_open = qcow2_open,
2911 .bdrv_close = qcow2_close,
2912 .bdrv_reopen_prepare = qcow2_reopen_prepare,
2913 .bdrv_create = qcow2_create,
2914 .bdrv_has_zero_init = bdrv_has_zero_init_1,
2915 .bdrv_co_get_block_status = qcow2_co_get_block_status,
2916 .bdrv_set_key = qcow2_set_key,
2918 .bdrv_co_readv = qcow2_co_readv,
2919 .bdrv_co_writev = qcow2_co_writev,
2920 .bdrv_co_flush_to_os = qcow2_co_flush_to_os,
2922 .bdrv_co_write_zeroes = qcow2_co_write_zeroes,
2923 .bdrv_co_discard = qcow2_co_discard,
2924 .bdrv_truncate = qcow2_truncate,
2925 .bdrv_write_compressed = qcow2_write_compressed,
2926 .bdrv_make_empty = qcow2_make_empty,
2928 .bdrv_snapshot_create = qcow2_snapshot_create,
2929 .bdrv_snapshot_goto = qcow2_snapshot_goto,
2930 .bdrv_snapshot_delete = qcow2_snapshot_delete,
2931 .bdrv_snapshot_list = qcow2_snapshot_list,
2932 .bdrv_snapshot_load_tmp = qcow2_snapshot_load_tmp,
2933 .bdrv_get_info = qcow2_get_info,
2934 .bdrv_get_specific_info = qcow2_get_specific_info,
2936 .bdrv_save_vmstate = qcow2_save_vmstate,
2937 .bdrv_load_vmstate = qcow2_load_vmstate,
2939 .supports_backing = true,
2940 .bdrv_change_backing_file = qcow2_change_backing_file,
2942 .bdrv_refresh_limits = qcow2_refresh_limits,
2943 .bdrv_invalidate_cache = qcow2_invalidate_cache,
2945 .create_opts = &qcow2_create_opts,
2946 .bdrv_check = qcow2_check,
2947 .bdrv_amend_options = qcow2_amend_options,
2950 static void bdrv_qcow2_init(void)
2952 bdrv_register(&bdrv_qcow2);
2955 block_init(bdrv_qcow2_init);