qcow2: Leave s unchanged on qcow2_update_options() failure
[qemu/ar7.git] / block / qcow2.c
blobc61d996f1457ceb9a2d311c7ed899fc7469b6b31
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 "block/qcow2.h"
29 #include "qemu/error-report.h"
30 #include "qapi/qmp/qerror.h"
31 #include "qapi/qmp/qbool.h"
32 #include "qapi/util.h"
33 #include "qapi/qmp/types.h"
34 #include "qapi-event.h"
35 #include "trace.h"
36 #include "qemu/option_int.h"
39 Differences with QCOW:
41 - Support for multiple incremental snapshots.
42 - Memory management by reference counts.
43 - Clusters which have a reference count of one have the bit
44 QCOW_OFLAG_COPIED to optimize write performance.
45 - Size of compressed clusters is stored in sectors to reduce bit usage
46 in the cluster offsets.
47 - Support for storing additional data (such as the VM state) in the
48 snapshots.
49 - If a backing store is used, the cluster size is not constrained
50 (could be backported to QCOW).
51 - L2 tables have always a size of one cluster.
55 typedef struct {
56 uint32_t magic;
57 uint32_t len;
58 } QEMU_PACKED QCowExtension;
60 #define QCOW2_EXT_MAGIC_END 0
61 #define QCOW2_EXT_MAGIC_BACKING_FORMAT 0xE2792ACA
62 #define QCOW2_EXT_MAGIC_FEATURE_TABLE 0x6803f857
64 static int qcow2_probe(const uint8_t *buf, int buf_size, const char *filename)
66 const QCowHeader *cow_header = (const void *)buf;
68 if (buf_size >= sizeof(QCowHeader) &&
69 be32_to_cpu(cow_header->magic) == QCOW_MAGIC &&
70 be32_to_cpu(cow_header->version) >= 2)
71 return 100;
72 else
73 return 0;
77 /*
78 * read qcow2 extension and fill bs
79 * start reading from start_offset
80 * finish reading upon magic of value 0 or when end_offset reached
81 * unknown magic is skipped (future extension this version knows nothing about)
82 * return 0 upon success, non-0 otherwise
84 static int qcow2_read_extensions(BlockDriverState *bs, uint64_t start_offset,
85 uint64_t end_offset, void **p_feature_table,
86 Error **errp)
88 BDRVQcow2State *s = bs->opaque;
89 QCowExtension ext;
90 uint64_t offset;
91 int ret;
93 #ifdef DEBUG_EXT
94 printf("qcow2_read_extensions: start=%ld end=%ld\n", start_offset, end_offset);
95 #endif
96 offset = start_offset;
97 while (offset < end_offset) {
99 #ifdef DEBUG_EXT
100 /* Sanity check */
101 if (offset > s->cluster_size)
102 printf("qcow2_read_extension: suspicious offset %lu\n", offset);
104 printf("attempting to read extended header in offset %lu\n", offset);
105 #endif
107 ret = bdrv_pread(bs->file, offset, &ext, sizeof(ext));
108 if (ret < 0) {
109 error_setg_errno(errp, -ret, "qcow2_read_extension: ERROR: "
110 "pread fail from offset %" PRIu64, offset);
111 return 1;
113 be32_to_cpus(&ext.magic);
114 be32_to_cpus(&ext.len);
115 offset += sizeof(ext);
116 #ifdef DEBUG_EXT
117 printf("ext.magic = 0x%x\n", ext.magic);
118 #endif
119 if (offset > end_offset || ext.len > end_offset - offset) {
120 error_setg(errp, "Header extension too large");
121 return -EINVAL;
124 switch (ext.magic) {
125 case QCOW2_EXT_MAGIC_END:
126 return 0;
128 case QCOW2_EXT_MAGIC_BACKING_FORMAT:
129 if (ext.len >= sizeof(bs->backing_format)) {
130 error_setg(errp, "ERROR: ext_backing_format: len=%" PRIu32
131 " too large (>=%zu)", ext.len,
132 sizeof(bs->backing_format));
133 return 2;
135 ret = bdrv_pread(bs->file, offset, bs->backing_format, ext.len);
136 if (ret < 0) {
137 error_setg_errno(errp, -ret, "ERROR: ext_backing_format: "
138 "Could not read format name");
139 return 3;
141 bs->backing_format[ext.len] = '\0';
142 s->image_backing_format = g_strdup(bs->backing_format);
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 BDRVQcow2State *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_setg(errp, QERR_UNKNOWN_BLOCK_FORMAT_FEATURE,
210 bdrv_get_device_or_node_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 BDRVQcow2State *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 BDRVQcow2State *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 BDRVQcow2State *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 BDRVQcow2State *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 BDRVQcow2State *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",
471 .name = QCOW2_OPT_CACHE_CLEAN_INTERVAL,
472 .type = QEMU_OPT_NUMBER,
473 .help = "Clean unused cache entries after this time (in seconds)",
475 { /* end of list */ }
479 static const char *overlap_bool_option_names[QCOW2_OL_MAX_BITNR] = {
480 [QCOW2_OL_MAIN_HEADER_BITNR] = QCOW2_OPT_OVERLAP_MAIN_HEADER,
481 [QCOW2_OL_ACTIVE_L1_BITNR] = QCOW2_OPT_OVERLAP_ACTIVE_L1,
482 [QCOW2_OL_ACTIVE_L2_BITNR] = QCOW2_OPT_OVERLAP_ACTIVE_L2,
483 [QCOW2_OL_REFCOUNT_TABLE_BITNR] = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
484 [QCOW2_OL_REFCOUNT_BLOCK_BITNR] = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
485 [QCOW2_OL_SNAPSHOT_TABLE_BITNR] = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
486 [QCOW2_OL_INACTIVE_L1_BITNR] = QCOW2_OPT_OVERLAP_INACTIVE_L1,
487 [QCOW2_OL_INACTIVE_L2_BITNR] = QCOW2_OPT_OVERLAP_INACTIVE_L2,
490 static void cache_clean_timer_cb(void *opaque)
492 BlockDriverState *bs = opaque;
493 BDRVQcow2State *s = bs->opaque;
494 qcow2_cache_clean_unused(bs, s->l2_table_cache);
495 qcow2_cache_clean_unused(bs, s->refcount_block_cache);
496 timer_mod(s->cache_clean_timer, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) +
497 (int64_t) s->cache_clean_interval * 1000);
500 static void cache_clean_timer_init(BlockDriverState *bs, AioContext *context)
502 BDRVQcow2State *s = bs->opaque;
503 if (s->cache_clean_interval > 0) {
504 s->cache_clean_timer = aio_timer_new(context, QEMU_CLOCK_VIRTUAL,
505 SCALE_MS, cache_clean_timer_cb,
506 bs);
507 timer_mod(s->cache_clean_timer, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) +
508 (int64_t) s->cache_clean_interval * 1000);
512 static void cache_clean_timer_del(BlockDriverState *bs)
514 BDRVQcow2State *s = bs->opaque;
515 if (s->cache_clean_timer) {
516 timer_del(s->cache_clean_timer);
517 timer_free(s->cache_clean_timer);
518 s->cache_clean_timer = NULL;
522 static void qcow2_detach_aio_context(BlockDriverState *bs)
524 cache_clean_timer_del(bs);
527 static void qcow2_attach_aio_context(BlockDriverState *bs,
528 AioContext *new_context)
530 cache_clean_timer_init(bs, new_context);
533 static void read_cache_sizes(BlockDriverState *bs, QemuOpts *opts,
534 uint64_t *l2_cache_size,
535 uint64_t *refcount_cache_size, Error **errp)
537 BDRVQcow2State *s = bs->opaque;
538 uint64_t combined_cache_size;
539 bool l2_cache_size_set, refcount_cache_size_set, combined_cache_size_set;
541 combined_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_CACHE_SIZE);
542 l2_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_L2_CACHE_SIZE);
543 refcount_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
545 combined_cache_size = qemu_opt_get_size(opts, QCOW2_OPT_CACHE_SIZE, 0);
546 *l2_cache_size = qemu_opt_get_size(opts, QCOW2_OPT_L2_CACHE_SIZE, 0);
547 *refcount_cache_size = qemu_opt_get_size(opts,
548 QCOW2_OPT_REFCOUNT_CACHE_SIZE, 0);
550 if (combined_cache_size_set) {
551 if (l2_cache_size_set && refcount_cache_size_set) {
552 error_setg(errp, QCOW2_OPT_CACHE_SIZE ", " QCOW2_OPT_L2_CACHE_SIZE
553 " and " QCOW2_OPT_REFCOUNT_CACHE_SIZE " may not be set "
554 "the same time");
555 return;
556 } else if (*l2_cache_size > combined_cache_size) {
557 error_setg(errp, QCOW2_OPT_L2_CACHE_SIZE " may not exceed "
558 QCOW2_OPT_CACHE_SIZE);
559 return;
560 } else if (*refcount_cache_size > combined_cache_size) {
561 error_setg(errp, QCOW2_OPT_REFCOUNT_CACHE_SIZE " may not exceed "
562 QCOW2_OPT_CACHE_SIZE);
563 return;
566 if (l2_cache_size_set) {
567 *refcount_cache_size = combined_cache_size - *l2_cache_size;
568 } else if (refcount_cache_size_set) {
569 *l2_cache_size = combined_cache_size - *refcount_cache_size;
570 } else {
571 *refcount_cache_size = combined_cache_size
572 / (DEFAULT_L2_REFCOUNT_SIZE_RATIO + 1);
573 *l2_cache_size = combined_cache_size - *refcount_cache_size;
575 } else {
576 if (!l2_cache_size_set && !refcount_cache_size_set) {
577 *l2_cache_size = MAX(DEFAULT_L2_CACHE_BYTE_SIZE,
578 (uint64_t)DEFAULT_L2_CACHE_CLUSTERS
579 * s->cluster_size);
580 *refcount_cache_size = *l2_cache_size
581 / DEFAULT_L2_REFCOUNT_SIZE_RATIO;
582 } else if (!l2_cache_size_set) {
583 *l2_cache_size = *refcount_cache_size
584 * DEFAULT_L2_REFCOUNT_SIZE_RATIO;
585 } else if (!refcount_cache_size_set) {
586 *refcount_cache_size = *l2_cache_size
587 / DEFAULT_L2_REFCOUNT_SIZE_RATIO;
592 static int qcow2_update_options(BlockDriverState *bs, QDict *options,
593 int flags, Error **errp)
595 BDRVQcow2State *s = bs->opaque;
596 QemuOpts *opts = NULL;
597 const char *opt_overlap_check, *opt_overlap_check_template;
598 int overlap_check_template = 0;
599 uint64_t l2_cache_size, refcount_cache_size;
600 Qcow2Cache *l2_table_cache;
601 Qcow2Cache *refcount_block_cache;
602 uint64_t cache_clean_interval;
603 bool use_lazy_refcounts;
604 int i;
605 Error *local_err = NULL;
606 int ret;
608 opts = qemu_opts_create(&qcow2_runtime_opts, NULL, 0, &error_abort);
609 qemu_opts_absorb_qdict(opts, options, &local_err);
610 if (local_err) {
611 error_propagate(errp, local_err);
612 ret = -EINVAL;
613 goto fail;
616 /* get L2 table/refcount block cache size from command line options */
617 read_cache_sizes(bs, opts, &l2_cache_size, &refcount_cache_size,
618 &local_err);
619 if (local_err) {
620 error_propagate(errp, local_err);
621 ret = -EINVAL;
622 goto fail;
625 l2_cache_size /= s->cluster_size;
626 if (l2_cache_size < MIN_L2_CACHE_SIZE) {
627 l2_cache_size = MIN_L2_CACHE_SIZE;
629 if (l2_cache_size > INT_MAX) {
630 error_setg(errp, "L2 cache size too big");
631 ret = -EINVAL;
632 goto fail;
635 refcount_cache_size /= s->cluster_size;
636 if (refcount_cache_size < MIN_REFCOUNT_CACHE_SIZE) {
637 refcount_cache_size = MIN_REFCOUNT_CACHE_SIZE;
639 if (refcount_cache_size > INT_MAX) {
640 error_setg(errp, "Refcount cache size too big");
641 ret = -EINVAL;
642 goto fail;
645 /* alloc L2 table/refcount block cache */
646 l2_table_cache = qcow2_cache_create(bs, l2_cache_size);
647 refcount_block_cache = qcow2_cache_create(bs, refcount_cache_size);
648 if (l2_table_cache == NULL || refcount_block_cache == NULL) {
649 error_setg(errp, "Could not allocate metadata caches");
650 ret = -ENOMEM;
651 goto fail;
654 /* New interval for cache cleanup timer */
655 cache_clean_interval =
656 qemu_opt_get_number(opts, QCOW2_OPT_CACHE_CLEAN_INTERVAL, 0);
657 if (cache_clean_interval > UINT_MAX) {
658 error_setg(errp, "Cache clean interval too big");
659 ret = -EINVAL;
660 goto fail;
663 /* Enable lazy_refcounts according to image and command line options */
664 use_lazy_refcounts = qemu_opt_get_bool(opts, QCOW2_OPT_LAZY_REFCOUNTS,
665 (s->compatible_features & QCOW2_COMPAT_LAZY_REFCOUNTS));
666 if (use_lazy_refcounts && s->qcow_version < 3) {
667 error_setg(errp, "Lazy refcounts require a qcow2 image with at least "
668 "qemu 1.1 compatibility level");
669 ret = -EINVAL;
670 goto fail;
673 /* Overlap check options */
674 opt_overlap_check = qemu_opt_get(opts, QCOW2_OPT_OVERLAP);
675 opt_overlap_check_template = qemu_opt_get(opts, QCOW2_OPT_OVERLAP_TEMPLATE);
676 if (opt_overlap_check_template && opt_overlap_check &&
677 strcmp(opt_overlap_check_template, opt_overlap_check))
679 error_setg(errp, "Conflicting values for qcow2 options '"
680 QCOW2_OPT_OVERLAP "' ('%s') and '" QCOW2_OPT_OVERLAP_TEMPLATE
681 "' ('%s')", opt_overlap_check, opt_overlap_check_template);
682 ret = -EINVAL;
683 goto fail;
685 if (!opt_overlap_check) {
686 opt_overlap_check = opt_overlap_check_template ?: "cached";
689 if (!strcmp(opt_overlap_check, "none")) {
690 overlap_check_template = 0;
691 } else if (!strcmp(opt_overlap_check, "constant")) {
692 overlap_check_template = QCOW2_OL_CONSTANT;
693 } else if (!strcmp(opt_overlap_check, "cached")) {
694 overlap_check_template = QCOW2_OL_CACHED;
695 } else if (!strcmp(opt_overlap_check, "all")) {
696 overlap_check_template = QCOW2_OL_ALL;
697 } else {
698 error_setg(errp, "Unsupported value '%s' for qcow2 option "
699 "'overlap-check'. Allowed are any of the following: "
700 "none, constant, cached, all", opt_overlap_check);
701 ret = -EINVAL;
702 goto fail;
706 * Start updating fields in BDRVQcow2State.
707 * After this point no failure is allowed any more.
709 s->overlap_check = 0;
710 for (i = 0; i < QCOW2_OL_MAX_BITNR; i++) {
711 /* overlap-check defines a template bitmask, but every flag may be
712 * overwritten through the associated boolean option */
713 s->overlap_check |=
714 qemu_opt_get_bool(opts, overlap_bool_option_names[i],
715 overlap_check_template & (1 << i)) << i;
718 s->l2_table_cache = l2_table_cache;
719 s->refcount_block_cache = refcount_block_cache;
721 s->use_lazy_refcounts = use_lazy_refcounts;
723 s->discard_passthrough[QCOW2_DISCARD_NEVER] = false;
724 s->discard_passthrough[QCOW2_DISCARD_ALWAYS] = true;
725 s->discard_passthrough[QCOW2_DISCARD_REQUEST] =
726 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_REQUEST,
727 flags & BDRV_O_UNMAP);
728 s->discard_passthrough[QCOW2_DISCARD_SNAPSHOT] =
729 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_SNAPSHOT, true);
730 s->discard_passthrough[QCOW2_DISCARD_OTHER] =
731 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_OTHER, false);
733 s->cache_clean_interval = cache_clean_interval;
734 cache_clean_timer_init(bs, bdrv_get_aio_context(bs));
736 ret = 0;
737 fail:
738 qemu_opts_del(opts);
739 opts = NULL;
741 return ret;
744 static int qcow2_open(BlockDriverState *bs, QDict *options, int flags,
745 Error **errp)
747 BDRVQcow2State *s = bs->opaque;
748 unsigned int len, i;
749 int ret = 0;
750 QCowHeader header;
751 Error *local_err = NULL;
752 uint64_t ext_end;
753 uint64_t l1_vm_state_index;
755 ret = bdrv_pread(bs->file, 0, &header, sizeof(header));
756 if (ret < 0) {
757 error_setg_errno(errp, -ret, "Could not read qcow2 header");
758 goto fail;
760 be32_to_cpus(&header.magic);
761 be32_to_cpus(&header.version);
762 be64_to_cpus(&header.backing_file_offset);
763 be32_to_cpus(&header.backing_file_size);
764 be64_to_cpus(&header.size);
765 be32_to_cpus(&header.cluster_bits);
766 be32_to_cpus(&header.crypt_method);
767 be64_to_cpus(&header.l1_table_offset);
768 be32_to_cpus(&header.l1_size);
769 be64_to_cpus(&header.refcount_table_offset);
770 be32_to_cpus(&header.refcount_table_clusters);
771 be64_to_cpus(&header.snapshots_offset);
772 be32_to_cpus(&header.nb_snapshots);
774 if (header.magic != QCOW_MAGIC) {
775 error_setg(errp, "Image is not in qcow2 format");
776 ret = -EINVAL;
777 goto fail;
779 if (header.version < 2 || header.version > 3) {
780 report_unsupported(bs, errp, "QCOW version %" PRIu32, header.version);
781 ret = -ENOTSUP;
782 goto fail;
785 s->qcow_version = header.version;
787 /* Initialise cluster size */
788 if (header.cluster_bits < MIN_CLUSTER_BITS ||
789 header.cluster_bits > MAX_CLUSTER_BITS) {
790 error_setg(errp, "Unsupported cluster size: 2^%" PRIu32,
791 header.cluster_bits);
792 ret = -EINVAL;
793 goto fail;
796 s->cluster_bits = header.cluster_bits;
797 s->cluster_size = 1 << s->cluster_bits;
798 s->cluster_sectors = 1 << (s->cluster_bits - 9);
800 /* Initialise version 3 header fields */
801 if (header.version == 2) {
802 header.incompatible_features = 0;
803 header.compatible_features = 0;
804 header.autoclear_features = 0;
805 header.refcount_order = 4;
806 header.header_length = 72;
807 } else {
808 be64_to_cpus(&header.incompatible_features);
809 be64_to_cpus(&header.compatible_features);
810 be64_to_cpus(&header.autoclear_features);
811 be32_to_cpus(&header.refcount_order);
812 be32_to_cpus(&header.header_length);
814 if (header.header_length < 104) {
815 error_setg(errp, "qcow2 header too short");
816 ret = -EINVAL;
817 goto fail;
821 if (header.header_length > s->cluster_size) {
822 error_setg(errp, "qcow2 header exceeds cluster size");
823 ret = -EINVAL;
824 goto fail;
827 if (header.header_length > sizeof(header)) {
828 s->unknown_header_fields_size = header.header_length - sizeof(header);
829 s->unknown_header_fields = g_malloc(s->unknown_header_fields_size);
830 ret = bdrv_pread(bs->file, sizeof(header), s->unknown_header_fields,
831 s->unknown_header_fields_size);
832 if (ret < 0) {
833 error_setg_errno(errp, -ret, "Could not read unknown qcow2 header "
834 "fields");
835 goto fail;
839 if (header.backing_file_offset > s->cluster_size) {
840 error_setg(errp, "Invalid backing file offset");
841 ret = -EINVAL;
842 goto fail;
845 if (header.backing_file_offset) {
846 ext_end = header.backing_file_offset;
847 } else {
848 ext_end = 1 << header.cluster_bits;
851 /* Handle feature bits */
852 s->incompatible_features = header.incompatible_features;
853 s->compatible_features = header.compatible_features;
854 s->autoclear_features = header.autoclear_features;
856 if (s->incompatible_features & ~QCOW2_INCOMPAT_MASK) {
857 void *feature_table = NULL;
858 qcow2_read_extensions(bs, header.header_length, ext_end,
859 &feature_table, NULL);
860 report_unsupported_feature(bs, errp, feature_table,
861 s->incompatible_features &
862 ~QCOW2_INCOMPAT_MASK);
863 ret = -ENOTSUP;
864 g_free(feature_table);
865 goto fail;
868 if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
869 /* Corrupt images may not be written to unless they are being repaired
871 if ((flags & BDRV_O_RDWR) && !(flags & BDRV_O_CHECK)) {
872 error_setg(errp, "qcow2: Image is corrupt; cannot be opened "
873 "read/write");
874 ret = -EACCES;
875 goto fail;
879 /* Check support for various header values */
880 if (header.refcount_order > 6) {
881 error_setg(errp, "Reference count entry width too large; may not "
882 "exceed 64 bits");
883 ret = -EINVAL;
884 goto fail;
886 s->refcount_order = header.refcount_order;
887 s->refcount_bits = 1 << s->refcount_order;
888 s->refcount_max = UINT64_C(1) << (s->refcount_bits - 1);
889 s->refcount_max += s->refcount_max - 1;
891 if (header.crypt_method > QCOW_CRYPT_AES) {
892 error_setg(errp, "Unsupported encryption method: %" PRIu32,
893 header.crypt_method);
894 ret = -EINVAL;
895 goto fail;
897 if (!qcrypto_cipher_supports(QCRYPTO_CIPHER_ALG_AES_128)) {
898 error_setg(errp, "AES cipher not available");
899 ret = -EINVAL;
900 goto fail;
902 s->crypt_method_header = header.crypt_method;
903 if (s->crypt_method_header) {
904 bs->encrypted = 1;
907 s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */
908 s->l2_size = 1 << s->l2_bits;
909 /* 2^(s->refcount_order - 3) is the refcount width in bytes */
910 s->refcount_block_bits = s->cluster_bits - (s->refcount_order - 3);
911 s->refcount_block_size = 1 << s->refcount_block_bits;
912 bs->total_sectors = header.size / 512;
913 s->csize_shift = (62 - (s->cluster_bits - 8));
914 s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;
915 s->cluster_offset_mask = (1LL << s->csize_shift) - 1;
917 s->refcount_table_offset = header.refcount_table_offset;
918 s->refcount_table_size =
919 header.refcount_table_clusters << (s->cluster_bits - 3);
921 if (header.refcount_table_clusters > qcow2_max_refcount_clusters(s)) {
922 error_setg(errp, "Reference count table too large");
923 ret = -EINVAL;
924 goto fail;
927 ret = validate_table_offset(bs, s->refcount_table_offset,
928 s->refcount_table_size, sizeof(uint64_t));
929 if (ret < 0) {
930 error_setg(errp, "Invalid reference count table offset");
931 goto fail;
934 /* Snapshot table offset/length */
935 if (header.nb_snapshots > QCOW_MAX_SNAPSHOTS) {
936 error_setg(errp, "Too many snapshots");
937 ret = -EINVAL;
938 goto fail;
941 ret = validate_table_offset(bs, header.snapshots_offset,
942 header.nb_snapshots,
943 sizeof(QCowSnapshotHeader));
944 if (ret < 0) {
945 error_setg(errp, "Invalid snapshot table offset");
946 goto fail;
949 /* read the level 1 table */
950 if (header.l1_size > QCOW_MAX_L1_SIZE / sizeof(uint64_t)) {
951 error_setg(errp, "Active L1 table too large");
952 ret = -EFBIG;
953 goto fail;
955 s->l1_size = header.l1_size;
957 l1_vm_state_index = size_to_l1(s, header.size);
958 if (l1_vm_state_index > INT_MAX) {
959 error_setg(errp, "Image is too big");
960 ret = -EFBIG;
961 goto fail;
963 s->l1_vm_state_index = l1_vm_state_index;
965 /* the L1 table must contain at least enough entries to put
966 header.size bytes */
967 if (s->l1_size < s->l1_vm_state_index) {
968 error_setg(errp, "L1 table is too small");
969 ret = -EINVAL;
970 goto fail;
973 ret = validate_table_offset(bs, header.l1_table_offset,
974 header.l1_size, sizeof(uint64_t));
975 if (ret < 0) {
976 error_setg(errp, "Invalid L1 table offset");
977 goto fail;
979 s->l1_table_offset = header.l1_table_offset;
982 if (s->l1_size > 0) {
983 s->l1_table = qemu_try_blockalign(bs->file,
984 align_offset(s->l1_size * sizeof(uint64_t), 512));
985 if (s->l1_table == NULL) {
986 error_setg(errp, "Could not allocate L1 table");
987 ret = -ENOMEM;
988 goto fail;
990 ret = bdrv_pread(bs->file, s->l1_table_offset, s->l1_table,
991 s->l1_size * sizeof(uint64_t));
992 if (ret < 0) {
993 error_setg_errno(errp, -ret, "Could not read L1 table");
994 goto fail;
996 for(i = 0;i < s->l1_size; i++) {
997 be64_to_cpus(&s->l1_table[i]);
1001 /* Parse driver-specific options */
1002 ret = qcow2_update_options(bs, options, flags, errp);
1003 if (ret < 0) {
1004 goto fail;
1007 s->cluster_cache = g_malloc(s->cluster_size);
1008 /* one more sector for decompressed data alignment */
1009 s->cluster_data = qemu_try_blockalign(bs->file, QCOW_MAX_CRYPT_CLUSTERS
1010 * s->cluster_size + 512);
1011 if (s->cluster_data == NULL) {
1012 error_setg(errp, "Could not allocate temporary cluster buffer");
1013 ret = -ENOMEM;
1014 goto fail;
1017 s->cluster_cache_offset = -1;
1018 s->flags = flags;
1020 ret = qcow2_refcount_init(bs);
1021 if (ret != 0) {
1022 error_setg_errno(errp, -ret, "Could not initialize refcount handling");
1023 goto fail;
1026 QLIST_INIT(&s->cluster_allocs);
1027 QTAILQ_INIT(&s->discards);
1029 /* read qcow2 extensions */
1030 if (qcow2_read_extensions(bs, header.header_length, ext_end, NULL,
1031 &local_err)) {
1032 error_propagate(errp, local_err);
1033 ret = -EINVAL;
1034 goto fail;
1037 /* read the backing file name */
1038 if (header.backing_file_offset != 0) {
1039 len = header.backing_file_size;
1040 if (len > MIN(1023, s->cluster_size - header.backing_file_offset) ||
1041 len >= sizeof(bs->backing_file)) {
1042 error_setg(errp, "Backing file name too long");
1043 ret = -EINVAL;
1044 goto fail;
1046 ret = bdrv_pread(bs->file, header.backing_file_offset,
1047 bs->backing_file, len);
1048 if (ret < 0) {
1049 error_setg_errno(errp, -ret, "Could not read backing file name");
1050 goto fail;
1052 bs->backing_file[len] = '\0';
1053 s->image_backing_file = g_strdup(bs->backing_file);
1056 /* Internal snapshots */
1057 s->snapshots_offset = header.snapshots_offset;
1058 s->nb_snapshots = header.nb_snapshots;
1060 ret = qcow2_read_snapshots(bs);
1061 if (ret < 0) {
1062 error_setg_errno(errp, -ret, "Could not read snapshots");
1063 goto fail;
1066 /* Clear unknown autoclear feature bits */
1067 if (!bs->read_only && !(flags & BDRV_O_INCOMING) && s->autoclear_features) {
1068 s->autoclear_features = 0;
1069 ret = qcow2_update_header(bs);
1070 if (ret < 0) {
1071 error_setg_errno(errp, -ret, "Could not update qcow2 header");
1072 goto fail;
1076 /* Initialise locks */
1077 qemu_co_mutex_init(&s->lock);
1079 /* Repair image if dirty */
1080 if (!(flags & (BDRV_O_CHECK | BDRV_O_INCOMING)) && !bs->read_only &&
1081 (s->incompatible_features & QCOW2_INCOMPAT_DIRTY)) {
1082 BdrvCheckResult result = {0};
1084 ret = qcow2_check(bs, &result, BDRV_FIX_ERRORS | BDRV_FIX_LEAKS);
1085 if (ret < 0) {
1086 error_setg_errno(errp, -ret, "Could not repair dirty image");
1087 goto fail;
1091 #ifdef DEBUG_ALLOC
1093 BdrvCheckResult result = {0};
1094 qcow2_check_refcounts(bs, &result, 0);
1096 #endif
1097 return ret;
1099 fail:
1100 g_free(s->unknown_header_fields);
1101 cleanup_unknown_header_ext(bs);
1102 qcow2_free_snapshots(bs);
1103 qcow2_refcount_close(bs);
1104 qemu_vfree(s->l1_table);
1105 /* else pre-write overlap checks in cache_destroy may crash */
1106 s->l1_table = NULL;
1107 cache_clean_timer_del(bs);
1108 if (s->l2_table_cache) {
1109 qcow2_cache_destroy(bs, s->l2_table_cache);
1111 if (s->refcount_block_cache) {
1112 qcow2_cache_destroy(bs, s->refcount_block_cache);
1114 g_free(s->cluster_cache);
1115 qemu_vfree(s->cluster_data);
1116 return ret;
1119 static void qcow2_refresh_limits(BlockDriverState *bs, Error **errp)
1121 BDRVQcow2State *s = bs->opaque;
1123 bs->bl.write_zeroes_alignment = s->cluster_sectors;
1126 static int qcow2_set_key(BlockDriverState *bs, const char *key)
1128 BDRVQcow2State *s = bs->opaque;
1129 uint8_t keybuf[16];
1130 int len, i;
1131 Error *err = NULL;
1133 memset(keybuf, 0, 16);
1134 len = strlen(key);
1135 if (len > 16)
1136 len = 16;
1137 /* XXX: we could compress the chars to 7 bits to increase
1138 entropy */
1139 for(i = 0;i < len;i++) {
1140 keybuf[i] = key[i];
1142 assert(bs->encrypted);
1144 qcrypto_cipher_free(s->cipher);
1145 s->cipher = qcrypto_cipher_new(
1146 QCRYPTO_CIPHER_ALG_AES_128,
1147 QCRYPTO_CIPHER_MODE_CBC,
1148 keybuf, G_N_ELEMENTS(keybuf),
1149 &err);
1151 if (!s->cipher) {
1152 /* XXX would be nice if errors in this method could
1153 * be properly propagate to the caller. Would need
1154 * the bdrv_set_key() API signature to be fixed. */
1155 error_free(err);
1156 return -1;
1158 return 0;
1161 /* We have no actual commit/abort logic for qcow2, but we need to write out any
1162 * unwritten data if we reopen read-only. */
1163 static int qcow2_reopen_prepare(BDRVReopenState *state,
1164 BlockReopenQueue *queue, Error **errp)
1166 int ret;
1168 if ((state->flags & BDRV_O_RDWR) == 0) {
1169 ret = bdrv_flush(state->bs);
1170 if (ret < 0) {
1171 return ret;
1174 ret = qcow2_mark_clean(state->bs);
1175 if (ret < 0) {
1176 return ret;
1180 return 0;
1183 static int64_t coroutine_fn qcow2_co_get_block_status(BlockDriverState *bs,
1184 int64_t sector_num, int nb_sectors, int *pnum)
1186 BDRVQcow2State *s = bs->opaque;
1187 uint64_t cluster_offset;
1188 int index_in_cluster, ret;
1189 int64_t status = 0;
1191 *pnum = nb_sectors;
1192 qemu_co_mutex_lock(&s->lock);
1193 ret = qcow2_get_cluster_offset(bs, sector_num << 9, pnum, &cluster_offset);
1194 qemu_co_mutex_unlock(&s->lock);
1195 if (ret < 0) {
1196 return ret;
1199 if (cluster_offset != 0 && ret != QCOW2_CLUSTER_COMPRESSED &&
1200 !s->cipher) {
1201 index_in_cluster = sector_num & (s->cluster_sectors - 1);
1202 cluster_offset |= (index_in_cluster << BDRV_SECTOR_BITS);
1203 status |= BDRV_BLOCK_OFFSET_VALID | cluster_offset;
1205 if (ret == QCOW2_CLUSTER_ZERO) {
1206 status |= BDRV_BLOCK_ZERO;
1207 } else if (ret != QCOW2_CLUSTER_UNALLOCATED) {
1208 status |= BDRV_BLOCK_DATA;
1210 return status;
1213 /* handle reading after the end of the backing file */
1214 int qcow2_backing_read1(BlockDriverState *bs, QEMUIOVector *qiov,
1215 int64_t sector_num, int nb_sectors)
1217 int n1;
1218 if ((sector_num + nb_sectors) <= bs->total_sectors)
1219 return nb_sectors;
1220 if (sector_num >= bs->total_sectors)
1221 n1 = 0;
1222 else
1223 n1 = bs->total_sectors - sector_num;
1225 qemu_iovec_memset(qiov, 512 * n1, 0, 512 * (nb_sectors - n1));
1227 return n1;
1230 static coroutine_fn int qcow2_co_readv(BlockDriverState *bs, int64_t sector_num,
1231 int remaining_sectors, QEMUIOVector *qiov)
1233 BDRVQcow2State *s = bs->opaque;
1234 int index_in_cluster, n1;
1235 int ret;
1236 int cur_nr_sectors; /* number of sectors in current iteration */
1237 uint64_t cluster_offset = 0;
1238 uint64_t bytes_done = 0;
1239 QEMUIOVector hd_qiov;
1240 uint8_t *cluster_data = NULL;
1242 qemu_iovec_init(&hd_qiov, qiov->niov);
1244 qemu_co_mutex_lock(&s->lock);
1246 while (remaining_sectors != 0) {
1248 /* prepare next request */
1249 cur_nr_sectors = remaining_sectors;
1250 if (s->cipher) {
1251 cur_nr_sectors = MIN(cur_nr_sectors,
1252 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors);
1255 ret = qcow2_get_cluster_offset(bs, sector_num << 9,
1256 &cur_nr_sectors, &cluster_offset);
1257 if (ret < 0) {
1258 goto fail;
1261 index_in_cluster = sector_num & (s->cluster_sectors - 1);
1263 qemu_iovec_reset(&hd_qiov);
1264 qemu_iovec_concat(&hd_qiov, qiov, bytes_done,
1265 cur_nr_sectors * 512);
1267 switch (ret) {
1268 case QCOW2_CLUSTER_UNALLOCATED:
1270 if (bs->backing_hd) {
1271 /* read from the base image */
1272 n1 = qcow2_backing_read1(bs->backing_hd, &hd_qiov,
1273 sector_num, cur_nr_sectors);
1274 if (n1 > 0) {
1275 QEMUIOVector local_qiov;
1277 qemu_iovec_init(&local_qiov, hd_qiov.niov);
1278 qemu_iovec_concat(&local_qiov, &hd_qiov, 0,
1279 n1 * BDRV_SECTOR_SIZE);
1281 BLKDBG_EVENT(bs->file, BLKDBG_READ_BACKING_AIO);
1282 qemu_co_mutex_unlock(&s->lock);
1283 ret = bdrv_co_readv(bs->backing_hd, sector_num,
1284 n1, &local_qiov);
1285 qemu_co_mutex_lock(&s->lock);
1287 qemu_iovec_destroy(&local_qiov);
1289 if (ret < 0) {
1290 goto fail;
1293 } else {
1294 /* Note: in this case, no need to wait */
1295 qemu_iovec_memset(&hd_qiov, 0, 0, 512 * cur_nr_sectors);
1297 break;
1299 case QCOW2_CLUSTER_ZERO:
1300 qemu_iovec_memset(&hd_qiov, 0, 0, 512 * cur_nr_sectors);
1301 break;
1303 case QCOW2_CLUSTER_COMPRESSED:
1304 /* add AIO support for compressed blocks ? */
1305 ret = qcow2_decompress_cluster(bs, cluster_offset);
1306 if (ret < 0) {
1307 goto fail;
1310 qemu_iovec_from_buf(&hd_qiov, 0,
1311 s->cluster_cache + index_in_cluster * 512,
1312 512 * cur_nr_sectors);
1313 break;
1315 case QCOW2_CLUSTER_NORMAL:
1316 if ((cluster_offset & 511) != 0) {
1317 ret = -EIO;
1318 goto fail;
1321 if (bs->encrypted) {
1322 assert(s->cipher);
1325 * For encrypted images, read everything into a temporary
1326 * contiguous buffer on which the AES functions can work.
1328 if (!cluster_data) {
1329 cluster_data =
1330 qemu_try_blockalign(bs->file, QCOW_MAX_CRYPT_CLUSTERS
1331 * s->cluster_size);
1332 if (cluster_data == NULL) {
1333 ret = -ENOMEM;
1334 goto fail;
1338 assert(cur_nr_sectors <=
1339 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors);
1340 qemu_iovec_reset(&hd_qiov);
1341 qemu_iovec_add(&hd_qiov, cluster_data,
1342 512 * cur_nr_sectors);
1345 BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);
1346 qemu_co_mutex_unlock(&s->lock);
1347 ret = bdrv_co_readv(bs->file,
1348 (cluster_offset >> 9) + index_in_cluster,
1349 cur_nr_sectors, &hd_qiov);
1350 qemu_co_mutex_lock(&s->lock);
1351 if (ret < 0) {
1352 goto fail;
1354 if (bs->encrypted) {
1355 assert(s->cipher);
1356 Error *err = NULL;
1357 if (qcow2_encrypt_sectors(s, sector_num, cluster_data,
1358 cluster_data, cur_nr_sectors, false,
1359 &err) < 0) {
1360 error_free(err);
1361 ret = -EIO;
1362 goto fail;
1364 qemu_iovec_from_buf(qiov, bytes_done,
1365 cluster_data, 512 * cur_nr_sectors);
1367 break;
1369 default:
1370 g_assert_not_reached();
1371 ret = -EIO;
1372 goto fail;
1375 remaining_sectors -= cur_nr_sectors;
1376 sector_num += cur_nr_sectors;
1377 bytes_done += cur_nr_sectors * 512;
1379 ret = 0;
1381 fail:
1382 qemu_co_mutex_unlock(&s->lock);
1384 qemu_iovec_destroy(&hd_qiov);
1385 qemu_vfree(cluster_data);
1387 return ret;
1390 static coroutine_fn int qcow2_co_writev(BlockDriverState *bs,
1391 int64_t sector_num,
1392 int remaining_sectors,
1393 QEMUIOVector *qiov)
1395 BDRVQcow2State *s = bs->opaque;
1396 int index_in_cluster;
1397 int ret;
1398 int cur_nr_sectors; /* number of sectors in current iteration */
1399 uint64_t cluster_offset;
1400 QEMUIOVector hd_qiov;
1401 uint64_t bytes_done = 0;
1402 uint8_t *cluster_data = NULL;
1403 QCowL2Meta *l2meta = NULL;
1405 trace_qcow2_writev_start_req(qemu_coroutine_self(), sector_num,
1406 remaining_sectors);
1408 qemu_iovec_init(&hd_qiov, qiov->niov);
1410 s->cluster_cache_offset = -1; /* disable compressed cache */
1412 qemu_co_mutex_lock(&s->lock);
1414 while (remaining_sectors != 0) {
1416 l2meta = NULL;
1418 trace_qcow2_writev_start_part(qemu_coroutine_self());
1419 index_in_cluster = sector_num & (s->cluster_sectors - 1);
1420 cur_nr_sectors = remaining_sectors;
1421 if (bs->encrypted &&
1422 cur_nr_sectors >
1423 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors - index_in_cluster) {
1424 cur_nr_sectors =
1425 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors - index_in_cluster;
1428 ret = qcow2_alloc_cluster_offset(bs, sector_num << 9,
1429 &cur_nr_sectors, &cluster_offset, &l2meta);
1430 if (ret < 0) {
1431 goto fail;
1434 assert((cluster_offset & 511) == 0);
1436 qemu_iovec_reset(&hd_qiov);
1437 qemu_iovec_concat(&hd_qiov, qiov, bytes_done,
1438 cur_nr_sectors * 512);
1440 if (bs->encrypted) {
1441 Error *err = NULL;
1442 assert(s->cipher);
1443 if (!cluster_data) {
1444 cluster_data = qemu_try_blockalign(bs->file,
1445 QCOW_MAX_CRYPT_CLUSTERS
1446 * s->cluster_size);
1447 if (cluster_data == NULL) {
1448 ret = -ENOMEM;
1449 goto fail;
1453 assert(hd_qiov.size <=
1454 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
1455 qemu_iovec_to_buf(&hd_qiov, 0, cluster_data, hd_qiov.size);
1457 if (qcow2_encrypt_sectors(s, sector_num, cluster_data,
1458 cluster_data, cur_nr_sectors,
1459 true, &err) < 0) {
1460 error_free(err);
1461 ret = -EIO;
1462 goto fail;
1465 qemu_iovec_reset(&hd_qiov);
1466 qemu_iovec_add(&hd_qiov, cluster_data,
1467 cur_nr_sectors * 512);
1470 ret = qcow2_pre_write_overlap_check(bs, 0,
1471 cluster_offset + index_in_cluster * BDRV_SECTOR_SIZE,
1472 cur_nr_sectors * BDRV_SECTOR_SIZE);
1473 if (ret < 0) {
1474 goto fail;
1477 qemu_co_mutex_unlock(&s->lock);
1478 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO);
1479 trace_qcow2_writev_data(qemu_coroutine_self(),
1480 (cluster_offset >> 9) + index_in_cluster);
1481 ret = bdrv_co_writev(bs->file,
1482 (cluster_offset >> 9) + index_in_cluster,
1483 cur_nr_sectors, &hd_qiov);
1484 qemu_co_mutex_lock(&s->lock);
1485 if (ret < 0) {
1486 goto fail;
1489 while (l2meta != NULL) {
1490 QCowL2Meta *next;
1492 ret = qcow2_alloc_cluster_link_l2(bs, l2meta);
1493 if (ret < 0) {
1494 goto fail;
1497 /* Take the request off the list of running requests */
1498 if (l2meta->nb_clusters != 0) {
1499 QLIST_REMOVE(l2meta, next_in_flight);
1502 qemu_co_queue_restart_all(&l2meta->dependent_requests);
1504 next = l2meta->next;
1505 g_free(l2meta);
1506 l2meta = next;
1509 remaining_sectors -= cur_nr_sectors;
1510 sector_num += cur_nr_sectors;
1511 bytes_done += cur_nr_sectors * 512;
1512 trace_qcow2_writev_done_part(qemu_coroutine_self(), cur_nr_sectors);
1514 ret = 0;
1516 fail:
1517 qemu_co_mutex_unlock(&s->lock);
1519 while (l2meta != NULL) {
1520 QCowL2Meta *next;
1522 if (l2meta->nb_clusters != 0) {
1523 QLIST_REMOVE(l2meta, next_in_flight);
1525 qemu_co_queue_restart_all(&l2meta->dependent_requests);
1527 next = l2meta->next;
1528 g_free(l2meta);
1529 l2meta = next;
1532 qemu_iovec_destroy(&hd_qiov);
1533 qemu_vfree(cluster_data);
1534 trace_qcow2_writev_done_req(qemu_coroutine_self(), ret);
1536 return ret;
1539 static void qcow2_close(BlockDriverState *bs)
1541 BDRVQcow2State *s = bs->opaque;
1542 qemu_vfree(s->l1_table);
1543 /* else pre-write overlap checks in cache_destroy may crash */
1544 s->l1_table = NULL;
1546 if (!(bs->open_flags & BDRV_O_INCOMING)) {
1547 int ret1, ret2;
1549 ret1 = qcow2_cache_flush(bs, s->l2_table_cache);
1550 ret2 = qcow2_cache_flush(bs, s->refcount_block_cache);
1552 if (ret1) {
1553 error_report("Failed to flush the L2 table cache: %s",
1554 strerror(-ret1));
1556 if (ret2) {
1557 error_report("Failed to flush the refcount block cache: %s",
1558 strerror(-ret2));
1561 if (!ret1 && !ret2) {
1562 qcow2_mark_clean(bs);
1566 cache_clean_timer_del(bs);
1567 qcow2_cache_destroy(bs, s->l2_table_cache);
1568 qcow2_cache_destroy(bs, s->refcount_block_cache);
1570 qcrypto_cipher_free(s->cipher);
1571 s->cipher = NULL;
1573 g_free(s->unknown_header_fields);
1574 cleanup_unknown_header_ext(bs);
1576 g_free(s->image_backing_file);
1577 g_free(s->image_backing_format);
1579 g_free(s->cluster_cache);
1580 qemu_vfree(s->cluster_data);
1581 qcow2_refcount_close(bs);
1582 qcow2_free_snapshots(bs);
1585 static void qcow2_invalidate_cache(BlockDriverState *bs, Error **errp)
1587 BDRVQcow2State *s = bs->opaque;
1588 int flags = s->flags;
1589 QCryptoCipher *cipher = NULL;
1590 QDict *options;
1591 Error *local_err = NULL;
1592 int ret;
1595 * Backing files are read-only which makes all of their metadata immutable,
1596 * that means we don't have to worry about reopening them here.
1599 cipher = s->cipher;
1600 s->cipher = NULL;
1602 qcow2_close(bs);
1604 bdrv_invalidate_cache(bs->file, &local_err);
1605 if (local_err) {
1606 error_propagate(errp, local_err);
1607 return;
1610 memset(s, 0, sizeof(BDRVQcow2State));
1611 options = qdict_clone_shallow(bs->options);
1613 ret = qcow2_open(bs, options, flags, &local_err);
1614 QDECREF(options);
1615 if (local_err) {
1616 error_setg(errp, "Could not reopen qcow2 layer: %s",
1617 error_get_pretty(local_err));
1618 error_free(local_err);
1619 return;
1620 } else if (ret < 0) {
1621 error_setg_errno(errp, -ret, "Could not reopen qcow2 layer");
1622 return;
1625 s->cipher = cipher;
1628 static size_t header_ext_add(char *buf, uint32_t magic, const void *s,
1629 size_t len, size_t buflen)
1631 QCowExtension *ext_backing_fmt = (QCowExtension*) buf;
1632 size_t ext_len = sizeof(QCowExtension) + ((len + 7) & ~7);
1634 if (buflen < ext_len) {
1635 return -ENOSPC;
1638 *ext_backing_fmt = (QCowExtension) {
1639 .magic = cpu_to_be32(magic),
1640 .len = cpu_to_be32(len),
1642 memcpy(buf + sizeof(QCowExtension), s, len);
1644 return ext_len;
1648 * Updates the qcow2 header, including the variable length parts of it, i.e.
1649 * the backing file name and all extensions. qcow2 was not designed to allow
1650 * such changes, so if we run out of space (we can only use the first cluster)
1651 * this function may fail.
1653 * Returns 0 on success, -errno in error cases.
1655 int qcow2_update_header(BlockDriverState *bs)
1657 BDRVQcow2State *s = bs->opaque;
1658 QCowHeader *header;
1659 char *buf;
1660 size_t buflen = s->cluster_size;
1661 int ret;
1662 uint64_t total_size;
1663 uint32_t refcount_table_clusters;
1664 size_t header_length;
1665 Qcow2UnknownHeaderExtension *uext;
1667 buf = qemu_blockalign(bs, buflen);
1669 /* Header structure */
1670 header = (QCowHeader*) buf;
1672 if (buflen < sizeof(*header)) {
1673 ret = -ENOSPC;
1674 goto fail;
1677 header_length = sizeof(*header) + s->unknown_header_fields_size;
1678 total_size = bs->total_sectors * BDRV_SECTOR_SIZE;
1679 refcount_table_clusters = s->refcount_table_size >> (s->cluster_bits - 3);
1681 *header = (QCowHeader) {
1682 /* Version 2 fields */
1683 .magic = cpu_to_be32(QCOW_MAGIC),
1684 .version = cpu_to_be32(s->qcow_version),
1685 .backing_file_offset = 0,
1686 .backing_file_size = 0,
1687 .cluster_bits = cpu_to_be32(s->cluster_bits),
1688 .size = cpu_to_be64(total_size),
1689 .crypt_method = cpu_to_be32(s->crypt_method_header),
1690 .l1_size = cpu_to_be32(s->l1_size),
1691 .l1_table_offset = cpu_to_be64(s->l1_table_offset),
1692 .refcount_table_offset = cpu_to_be64(s->refcount_table_offset),
1693 .refcount_table_clusters = cpu_to_be32(refcount_table_clusters),
1694 .nb_snapshots = cpu_to_be32(s->nb_snapshots),
1695 .snapshots_offset = cpu_to_be64(s->snapshots_offset),
1697 /* Version 3 fields */
1698 .incompatible_features = cpu_to_be64(s->incompatible_features),
1699 .compatible_features = cpu_to_be64(s->compatible_features),
1700 .autoclear_features = cpu_to_be64(s->autoclear_features),
1701 .refcount_order = cpu_to_be32(s->refcount_order),
1702 .header_length = cpu_to_be32(header_length),
1705 /* For older versions, write a shorter header */
1706 switch (s->qcow_version) {
1707 case 2:
1708 ret = offsetof(QCowHeader, incompatible_features);
1709 break;
1710 case 3:
1711 ret = sizeof(*header);
1712 break;
1713 default:
1714 ret = -EINVAL;
1715 goto fail;
1718 buf += ret;
1719 buflen -= ret;
1720 memset(buf, 0, buflen);
1722 /* Preserve any unknown field in the header */
1723 if (s->unknown_header_fields_size) {
1724 if (buflen < s->unknown_header_fields_size) {
1725 ret = -ENOSPC;
1726 goto fail;
1729 memcpy(buf, s->unknown_header_fields, s->unknown_header_fields_size);
1730 buf += s->unknown_header_fields_size;
1731 buflen -= s->unknown_header_fields_size;
1734 /* Backing file format header extension */
1735 if (s->image_backing_format) {
1736 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BACKING_FORMAT,
1737 s->image_backing_format,
1738 strlen(s->image_backing_format),
1739 buflen);
1740 if (ret < 0) {
1741 goto fail;
1744 buf += ret;
1745 buflen -= ret;
1748 /* Feature table */
1749 Qcow2Feature features[] = {
1751 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
1752 .bit = QCOW2_INCOMPAT_DIRTY_BITNR,
1753 .name = "dirty bit",
1756 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
1757 .bit = QCOW2_INCOMPAT_CORRUPT_BITNR,
1758 .name = "corrupt bit",
1761 .type = QCOW2_FEAT_TYPE_COMPATIBLE,
1762 .bit = QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR,
1763 .name = "lazy refcounts",
1767 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_FEATURE_TABLE,
1768 features, sizeof(features), buflen);
1769 if (ret < 0) {
1770 goto fail;
1772 buf += ret;
1773 buflen -= ret;
1775 /* Keep unknown header extensions */
1776 QLIST_FOREACH(uext, &s->unknown_header_ext, next) {
1777 ret = header_ext_add(buf, uext->magic, uext->data, uext->len, buflen);
1778 if (ret < 0) {
1779 goto fail;
1782 buf += ret;
1783 buflen -= ret;
1786 /* End of header extensions */
1787 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_END, NULL, 0, buflen);
1788 if (ret < 0) {
1789 goto fail;
1792 buf += ret;
1793 buflen -= ret;
1795 /* Backing file name */
1796 if (s->image_backing_file) {
1797 size_t backing_file_len = strlen(s->image_backing_file);
1799 if (buflen < backing_file_len) {
1800 ret = -ENOSPC;
1801 goto fail;
1804 /* Using strncpy is ok here, since buf is not NUL-terminated. */
1805 strncpy(buf, s->image_backing_file, buflen);
1807 header->backing_file_offset = cpu_to_be64(buf - ((char*) header));
1808 header->backing_file_size = cpu_to_be32(backing_file_len);
1811 /* Write the new header */
1812 ret = bdrv_pwrite(bs->file, 0, header, s->cluster_size);
1813 if (ret < 0) {
1814 goto fail;
1817 ret = 0;
1818 fail:
1819 qemu_vfree(header);
1820 return ret;
1823 static int qcow2_change_backing_file(BlockDriverState *bs,
1824 const char *backing_file, const char *backing_fmt)
1826 BDRVQcow2State *s = bs->opaque;
1828 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
1829 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
1831 g_free(s->image_backing_file);
1832 g_free(s->image_backing_format);
1834 s->image_backing_file = backing_file ? g_strdup(bs->backing_file) : NULL;
1835 s->image_backing_format = backing_fmt ? g_strdup(bs->backing_format) : NULL;
1837 return qcow2_update_header(bs);
1840 static int preallocate(BlockDriverState *bs)
1842 uint64_t nb_sectors;
1843 uint64_t offset;
1844 uint64_t host_offset = 0;
1845 int num;
1846 int ret;
1847 QCowL2Meta *meta;
1849 nb_sectors = bdrv_nb_sectors(bs);
1850 offset = 0;
1852 while (nb_sectors) {
1853 num = MIN(nb_sectors, INT_MAX >> BDRV_SECTOR_BITS);
1854 ret = qcow2_alloc_cluster_offset(bs, offset, &num,
1855 &host_offset, &meta);
1856 if (ret < 0) {
1857 return ret;
1860 while (meta) {
1861 QCowL2Meta *next = meta->next;
1863 ret = qcow2_alloc_cluster_link_l2(bs, meta);
1864 if (ret < 0) {
1865 qcow2_free_any_clusters(bs, meta->alloc_offset,
1866 meta->nb_clusters, QCOW2_DISCARD_NEVER);
1867 return ret;
1870 /* There are no dependent requests, but we need to remove our
1871 * request from the list of in-flight requests */
1872 QLIST_REMOVE(meta, next_in_flight);
1874 g_free(meta);
1875 meta = next;
1878 /* TODO Preallocate data if requested */
1880 nb_sectors -= num;
1881 offset += num << BDRV_SECTOR_BITS;
1885 * It is expected that the image file is large enough to actually contain
1886 * all of the allocated clusters (otherwise we get failing reads after
1887 * EOF). Extend the image to the last allocated sector.
1889 if (host_offset != 0) {
1890 uint8_t buf[BDRV_SECTOR_SIZE];
1891 memset(buf, 0, BDRV_SECTOR_SIZE);
1892 ret = bdrv_write(bs->file, (host_offset >> BDRV_SECTOR_BITS) + num - 1,
1893 buf, 1);
1894 if (ret < 0) {
1895 return ret;
1899 return 0;
1902 static int qcow2_create2(const char *filename, int64_t total_size,
1903 const char *backing_file, const char *backing_format,
1904 int flags, size_t cluster_size, PreallocMode prealloc,
1905 QemuOpts *opts, int version, int refcount_order,
1906 Error **errp)
1908 int cluster_bits;
1909 QDict *options;
1911 /* Calculate cluster_bits */
1912 cluster_bits = ctz32(cluster_size);
1913 if (cluster_bits < MIN_CLUSTER_BITS || cluster_bits > MAX_CLUSTER_BITS ||
1914 (1 << cluster_bits) != cluster_size)
1916 error_setg(errp, "Cluster size must be a power of two between %d and "
1917 "%dk", 1 << MIN_CLUSTER_BITS, 1 << (MAX_CLUSTER_BITS - 10));
1918 return -EINVAL;
1922 * Open the image file and write a minimal qcow2 header.
1924 * We keep things simple and start with a zero-sized image. We also
1925 * do without refcount blocks or a L1 table for now. We'll fix the
1926 * inconsistency later.
1928 * We do need a refcount table because growing the refcount table means
1929 * allocating two new refcount blocks - the seconds of which would be at
1930 * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
1931 * size for any qcow2 image.
1933 BlockDriverState* bs;
1934 QCowHeader *header;
1935 uint64_t* refcount_table;
1936 Error *local_err = NULL;
1937 int ret;
1939 if (prealloc == PREALLOC_MODE_FULL || prealloc == PREALLOC_MODE_FALLOC) {
1940 /* Note: The following calculation does not need to be exact; if it is a
1941 * bit off, either some bytes will be "leaked" (which is fine) or we
1942 * will need to increase the file size by some bytes (which is fine,
1943 * too, as long as the bulk is allocated here). Therefore, using
1944 * floating point arithmetic is fine. */
1945 int64_t meta_size = 0;
1946 uint64_t nreftablee, nrefblocke, nl1e, nl2e;
1947 int64_t aligned_total_size = align_offset(total_size, cluster_size);
1948 int refblock_bits, refblock_size;
1949 /* refcount entry size in bytes */
1950 double rces = (1 << refcount_order) / 8.;
1952 /* see qcow2_open() */
1953 refblock_bits = cluster_bits - (refcount_order - 3);
1954 refblock_size = 1 << refblock_bits;
1956 /* header: 1 cluster */
1957 meta_size += cluster_size;
1959 /* total size of L2 tables */
1960 nl2e = aligned_total_size / cluster_size;
1961 nl2e = align_offset(nl2e, cluster_size / sizeof(uint64_t));
1962 meta_size += nl2e * sizeof(uint64_t);
1964 /* total size of L1 tables */
1965 nl1e = nl2e * sizeof(uint64_t) / cluster_size;
1966 nl1e = align_offset(nl1e, cluster_size / sizeof(uint64_t));
1967 meta_size += nl1e * sizeof(uint64_t);
1969 /* total size of refcount blocks
1971 * note: every host cluster is reference-counted, including metadata
1972 * (even refcount blocks are recursively included).
1973 * Let:
1974 * a = total_size (this is the guest disk size)
1975 * m = meta size not including refcount blocks and refcount tables
1976 * c = cluster size
1977 * y1 = number of refcount blocks entries
1978 * y2 = meta size including everything
1979 * rces = refcount entry size in bytes
1980 * then,
1981 * y1 = (y2 + a)/c
1982 * y2 = y1 * rces + y1 * rces * sizeof(u64) / c + m
1983 * we can get y1:
1984 * y1 = (a + m) / (c - rces - rces * sizeof(u64) / c)
1986 nrefblocke = (aligned_total_size + meta_size + cluster_size)
1987 / (cluster_size - rces - rces * sizeof(uint64_t)
1988 / cluster_size);
1989 meta_size += DIV_ROUND_UP(nrefblocke, refblock_size) * cluster_size;
1991 /* total size of refcount tables */
1992 nreftablee = nrefblocke / refblock_size;
1993 nreftablee = align_offset(nreftablee, cluster_size / sizeof(uint64_t));
1994 meta_size += nreftablee * sizeof(uint64_t);
1996 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
1997 aligned_total_size + meta_size, &error_abort);
1998 qemu_opt_set(opts, BLOCK_OPT_PREALLOC, PreallocMode_lookup[prealloc],
1999 &error_abort);
2002 ret = bdrv_create_file(filename, opts, &local_err);
2003 if (ret < 0) {
2004 error_propagate(errp, local_err);
2005 return ret;
2008 bs = NULL;
2009 ret = bdrv_open(&bs, filename, NULL, NULL, BDRV_O_RDWR | BDRV_O_PROTOCOL,
2010 &local_err);
2011 if (ret < 0) {
2012 error_propagate(errp, local_err);
2013 return ret;
2016 /* Write the header */
2017 QEMU_BUILD_BUG_ON((1 << MIN_CLUSTER_BITS) < sizeof(*header));
2018 header = g_malloc0(cluster_size);
2019 *header = (QCowHeader) {
2020 .magic = cpu_to_be32(QCOW_MAGIC),
2021 .version = cpu_to_be32(version),
2022 .cluster_bits = cpu_to_be32(cluster_bits),
2023 .size = cpu_to_be64(0),
2024 .l1_table_offset = cpu_to_be64(0),
2025 .l1_size = cpu_to_be32(0),
2026 .refcount_table_offset = cpu_to_be64(cluster_size),
2027 .refcount_table_clusters = cpu_to_be32(1),
2028 .refcount_order = cpu_to_be32(refcount_order),
2029 .header_length = cpu_to_be32(sizeof(*header)),
2032 if (flags & BLOCK_FLAG_ENCRYPT) {
2033 header->crypt_method = cpu_to_be32(QCOW_CRYPT_AES);
2034 } else {
2035 header->crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
2038 if (flags & BLOCK_FLAG_LAZY_REFCOUNTS) {
2039 header->compatible_features |=
2040 cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS);
2043 ret = bdrv_pwrite(bs, 0, header, cluster_size);
2044 g_free(header);
2045 if (ret < 0) {
2046 error_setg_errno(errp, -ret, "Could not write qcow2 header");
2047 goto out;
2050 /* Write a refcount table with one refcount block */
2051 refcount_table = g_malloc0(2 * cluster_size);
2052 refcount_table[0] = cpu_to_be64(2 * cluster_size);
2053 ret = bdrv_pwrite(bs, cluster_size, refcount_table, 2 * cluster_size);
2054 g_free(refcount_table);
2056 if (ret < 0) {
2057 error_setg_errno(errp, -ret, "Could not write refcount table");
2058 goto out;
2061 bdrv_unref(bs);
2062 bs = NULL;
2065 * And now open the image and make it consistent first (i.e. increase the
2066 * refcount of the cluster that is occupied by the header and the refcount
2067 * table)
2069 options = qdict_new();
2070 qdict_put(options, "driver", qstring_from_str("qcow2"));
2071 ret = bdrv_open(&bs, filename, NULL, options,
2072 BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_NO_FLUSH,
2073 &local_err);
2074 if (ret < 0) {
2075 error_propagate(errp, local_err);
2076 goto out;
2079 ret = qcow2_alloc_clusters(bs, 3 * cluster_size);
2080 if (ret < 0) {
2081 error_setg_errno(errp, -ret, "Could not allocate clusters for qcow2 "
2082 "header and refcount table");
2083 goto out;
2085 } else if (ret != 0) {
2086 error_report("Huh, first cluster in empty image is already in use?");
2087 abort();
2090 /* Okay, now that we have a valid image, let's give it the right size */
2091 ret = bdrv_truncate(bs, total_size);
2092 if (ret < 0) {
2093 error_setg_errno(errp, -ret, "Could not resize image");
2094 goto out;
2097 /* Want a backing file? There you go.*/
2098 if (backing_file) {
2099 ret = bdrv_change_backing_file(bs, backing_file, backing_format);
2100 if (ret < 0) {
2101 error_setg_errno(errp, -ret, "Could not assign backing file '%s' "
2102 "with format '%s'", backing_file, backing_format);
2103 goto out;
2107 /* And if we're supposed to preallocate metadata, do that now */
2108 if (prealloc != PREALLOC_MODE_OFF) {
2109 BDRVQcow2State *s = bs->opaque;
2110 qemu_co_mutex_lock(&s->lock);
2111 ret = preallocate(bs);
2112 qemu_co_mutex_unlock(&s->lock);
2113 if (ret < 0) {
2114 error_setg_errno(errp, -ret, "Could not preallocate metadata");
2115 goto out;
2119 bdrv_unref(bs);
2120 bs = NULL;
2122 /* Reopen the image without BDRV_O_NO_FLUSH to flush it before returning */
2123 options = qdict_new();
2124 qdict_put(options, "driver", qstring_from_str("qcow2"));
2125 ret = bdrv_open(&bs, filename, NULL, options,
2126 BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_NO_BACKING,
2127 &local_err);
2128 if (local_err) {
2129 error_propagate(errp, local_err);
2130 goto out;
2133 ret = 0;
2134 out:
2135 if (bs) {
2136 bdrv_unref(bs);
2138 return ret;
2141 static int qcow2_create(const char *filename, QemuOpts *opts, Error **errp)
2143 char *backing_file = NULL;
2144 char *backing_fmt = NULL;
2145 char *buf = NULL;
2146 uint64_t size = 0;
2147 int flags = 0;
2148 size_t cluster_size = DEFAULT_CLUSTER_SIZE;
2149 PreallocMode prealloc;
2150 int version = 3;
2151 uint64_t refcount_bits = 16;
2152 int refcount_order;
2153 Error *local_err = NULL;
2154 int ret;
2156 /* Read out options */
2157 size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
2158 BDRV_SECTOR_SIZE);
2159 backing_file = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
2160 backing_fmt = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FMT);
2161 if (qemu_opt_get_bool_del(opts, BLOCK_OPT_ENCRYPT, false)) {
2162 flags |= BLOCK_FLAG_ENCRYPT;
2164 cluster_size = qemu_opt_get_size_del(opts, BLOCK_OPT_CLUSTER_SIZE,
2165 DEFAULT_CLUSTER_SIZE);
2166 buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
2167 prealloc = qapi_enum_parse(PreallocMode_lookup, buf,
2168 PREALLOC_MODE_MAX, PREALLOC_MODE_OFF,
2169 &local_err);
2170 if (local_err) {
2171 error_propagate(errp, local_err);
2172 ret = -EINVAL;
2173 goto finish;
2175 g_free(buf);
2176 buf = qemu_opt_get_del(opts, BLOCK_OPT_COMPAT_LEVEL);
2177 if (!buf) {
2178 /* keep the default */
2179 } else if (!strcmp(buf, "0.10")) {
2180 version = 2;
2181 } else if (!strcmp(buf, "1.1")) {
2182 version = 3;
2183 } else {
2184 error_setg(errp, "Invalid compatibility level: '%s'", buf);
2185 ret = -EINVAL;
2186 goto finish;
2189 if (qemu_opt_get_bool_del(opts, BLOCK_OPT_LAZY_REFCOUNTS, false)) {
2190 flags |= BLOCK_FLAG_LAZY_REFCOUNTS;
2193 if (backing_file && prealloc != PREALLOC_MODE_OFF) {
2194 error_setg(errp, "Backing file and preallocation cannot be used at "
2195 "the same time");
2196 ret = -EINVAL;
2197 goto finish;
2200 if (version < 3 && (flags & BLOCK_FLAG_LAZY_REFCOUNTS)) {
2201 error_setg(errp, "Lazy refcounts only supported with compatibility "
2202 "level 1.1 and above (use compat=1.1 or greater)");
2203 ret = -EINVAL;
2204 goto finish;
2207 refcount_bits = qemu_opt_get_number_del(opts, BLOCK_OPT_REFCOUNT_BITS,
2208 refcount_bits);
2209 if (refcount_bits > 64 || !is_power_of_2(refcount_bits)) {
2210 error_setg(errp, "Refcount width must be a power of two and may not "
2211 "exceed 64 bits");
2212 ret = -EINVAL;
2213 goto finish;
2216 if (version < 3 && refcount_bits != 16) {
2217 error_setg(errp, "Different refcount widths than 16 bits require "
2218 "compatibility level 1.1 or above (use compat=1.1 or "
2219 "greater)");
2220 ret = -EINVAL;
2221 goto finish;
2224 refcount_order = ctz32(refcount_bits);
2226 ret = qcow2_create2(filename, size, backing_file, backing_fmt, flags,
2227 cluster_size, prealloc, opts, version, refcount_order,
2228 &local_err);
2229 if (local_err) {
2230 error_propagate(errp, local_err);
2233 finish:
2234 g_free(backing_file);
2235 g_free(backing_fmt);
2236 g_free(buf);
2237 return ret;
2240 static coroutine_fn int qcow2_co_write_zeroes(BlockDriverState *bs,
2241 int64_t sector_num, int nb_sectors, BdrvRequestFlags flags)
2243 int ret;
2244 BDRVQcow2State *s = bs->opaque;
2246 /* Emulate misaligned zero writes */
2247 if (sector_num % s->cluster_sectors || nb_sectors % s->cluster_sectors) {
2248 return -ENOTSUP;
2251 /* Whatever is left can use real zero clusters */
2252 qemu_co_mutex_lock(&s->lock);
2253 ret = qcow2_zero_clusters(bs, sector_num << BDRV_SECTOR_BITS,
2254 nb_sectors);
2255 qemu_co_mutex_unlock(&s->lock);
2257 return ret;
2260 static coroutine_fn int qcow2_co_discard(BlockDriverState *bs,
2261 int64_t sector_num, int nb_sectors)
2263 int ret;
2264 BDRVQcow2State *s = bs->opaque;
2266 qemu_co_mutex_lock(&s->lock);
2267 ret = qcow2_discard_clusters(bs, sector_num << BDRV_SECTOR_BITS,
2268 nb_sectors, QCOW2_DISCARD_REQUEST, false);
2269 qemu_co_mutex_unlock(&s->lock);
2270 return ret;
2273 static int qcow2_truncate(BlockDriverState *bs, int64_t offset)
2275 BDRVQcow2State *s = bs->opaque;
2276 int64_t new_l1_size;
2277 int ret;
2279 if (offset & 511) {
2280 error_report("The new size must be a multiple of 512");
2281 return -EINVAL;
2284 /* cannot proceed if image has snapshots */
2285 if (s->nb_snapshots) {
2286 error_report("Can't resize an image which has snapshots");
2287 return -ENOTSUP;
2290 /* shrinking is currently not supported */
2291 if (offset < bs->total_sectors * 512) {
2292 error_report("qcow2 doesn't support shrinking images yet");
2293 return -ENOTSUP;
2296 new_l1_size = size_to_l1(s, offset);
2297 ret = qcow2_grow_l1_table(bs, new_l1_size, true);
2298 if (ret < 0) {
2299 return ret;
2302 /* write updated header.size */
2303 offset = cpu_to_be64(offset);
2304 ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, size),
2305 &offset, sizeof(uint64_t));
2306 if (ret < 0) {
2307 return ret;
2310 s->l1_vm_state_index = new_l1_size;
2311 return 0;
2314 /* XXX: put compressed sectors first, then all the cluster aligned
2315 tables to avoid losing bytes in alignment */
2316 static int qcow2_write_compressed(BlockDriverState *bs, int64_t sector_num,
2317 const uint8_t *buf, int nb_sectors)
2319 BDRVQcow2State *s = bs->opaque;
2320 z_stream strm;
2321 int ret, out_len;
2322 uint8_t *out_buf;
2323 uint64_t cluster_offset;
2325 if (nb_sectors == 0) {
2326 /* align end of file to a sector boundary to ease reading with
2327 sector based I/Os */
2328 cluster_offset = bdrv_getlength(bs->file);
2329 return bdrv_truncate(bs->file, cluster_offset);
2332 if (nb_sectors != s->cluster_sectors) {
2333 ret = -EINVAL;
2335 /* Zero-pad last write if image size is not cluster aligned */
2336 if (sector_num + nb_sectors == bs->total_sectors &&
2337 nb_sectors < s->cluster_sectors) {
2338 uint8_t *pad_buf = qemu_blockalign(bs, s->cluster_size);
2339 memset(pad_buf, 0, s->cluster_size);
2340 memcpy(pad_buf, buf, nb_sectors * BDRV_SECTOR_SIZE);
2341 ret = qcow2_write_compressed(bs, sector_num,
2342 pad_buf, s->cluster_sectors);
2343 qemu_vfree(pad_buf);
2345 return ret;
2348 out_buf = g_malloc(s->cluster_size + (s->cluster_size / 1000) + 128);
2350 /* best compression, small window, no zlib header */
2351 memset(&strm, 0, sizeof(strm));
2352 ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
2353 Z_DEFLATED, -12,
2354 9, Z_DEFAULT_STRATEGY);
2355 if (ret != 0) {
2356 ret = -EINVAL;
2357 goto fail;
2360 strm.avail_in = s->cluster_size;
2361 strm.next_in = (uint8_t *)buf;
2362 strm.avail_out = s->cluster_size;
2363 strm.next_out = out_buf;
2365 ret = deflate(&strm, Z_FINISH);
2366 if (ret != Z_STREAM_END && ret != Z_OK) {
2367 deflateEnd(&strm);
2368 ret = -EINVAL;
2369 goto fail;
2371 out_len = strm.next_out - out_buf;
2373 deflateEnd(&strm);
2375 if (ret != Z_STREAM_END || out_len >= s->cluster_size) {
2376 /* could not compress: write normal cluster */
2377 ret = bdrv_write(bs, sector_num, buf, s->cluster_sectors);
2378 if (ret < 0) {
2379 goto fail;
2381 } else {
2382 cluster_offset = qcow2_alloc_compressed_cluster_offset(bs,
2383 sector_num << 9, out_len);
2384 if (!cluster_offset) {
2385 ret = -EIO;
2386 goto fail;
2388 cluster_offset &= s->cluster_offset_mask;
2390 ret = qcow2_pre_write_overlap_check(bs, 0, cluster_offset, out_len);
2391 if (ret < 0) {
2392 goto fail;
2395 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_COMPRESSED);
2396 ret = bdrv_pwrite(bs->file, cluster_offset, out_buf, out_len);
2397 if (ret < 0) {
2398 goto fail;
2402 ret = 0;
2403 fail:
2404 g_free(out_buf);
2405 return ret;
2408 static int make_completely_empty(BlockDriverState *bs)
2410 BDRVQcow2State *s = bs->opaque;
2411 int ret, l1_clusters;
2412 int64_t offset;
2413 uint64_t *new_reftable = NULL;
2414 uint64_t rt_entry, l1_size2;
2415 struct {
2416 uint64_t l1_offset;
2417 uint64_t reftable_offset;
2418 uint32_t reftable_clusters;
2419 } QEMU_PACKED l1_ofs_rt_ofs_cls;
2421 ret = qcow2_cache_empty(bs, s->l2_table_cache);
2422 if (ret < 0) {
2423 goto fail;
2426 ret = qcow2_cache_empty(bs, s->refcount_block_cache);
2427 if (ret < 0) {
2428 goto fail;
2431 /* Refcounts will be broken utterly */
2432 ret = qcow2_mark_dirty(bs);
2433 if (ret < 0) {
2434 goto fail;
2437 BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
2439 l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / sizeof(uint64_t));
2440 l1_size2 = (uint64_t)s->l1_size * sizeof(uint64_t);
2442 /* After this call, neither the in-memory nor the on-disk refcount
2443 * information accurately describe the actual references */
2445 ret = bdrv_write_zeroes(bs->file, s->l1_table_offset / BDRV_SECTOR_SIZE,
2446 l1_clusters * s->cluster_sectors, 0);
2447 if (ret < 0) {
2448 goto fail_broken_refcounts;
2450 memset(s->l1_table, 0, l1_size2);
2452 BLKDBG_EVENT(bs->file, BLKDBG_EMPTY_IMAGE_PREPARE);
2454 /* Overwrite enough clusters at the beginning of the sectors to place
2455 * the refcount table, a refcount block and the L1 table in; this may
2456 * overwrite parts of the existing refcount and L1 table, which is not
2457 * an issue because the dirty flag is set, complete data loss is in fact
2458 * desired and partial data loss is consequently fine as well */
2459 ret = bdrv_write_zeroes(bs->file, s->cluster_size / BDRV_SECTOR_SIZE,
2460 (2 + l1_clusters) * s->cluster_size /
2461 BDRV_SECTOR_SIZE, 0);
2462 /* This call (even if it failed overall) may have overwritten on-disk
2463 * refcount structures; in that case, the in-memory refcount information
2464 * will probably differ from the on-disk information which makes the BDS
2465 * unusable */
2466 if (ret < 0) {
2467 goto fail_broken_refcounts;
2470 BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
2471 BLKDBG_EVENT(bs->file, BLKDBG_REFTABLE_UPDATE);
2473 /* "Create" an empty reftable (one cluster) directly after the image
2474 * header and an empty L1 table three clusters after the image header;
2475 * the cluster between those two will be used as the first refblock */
2476 cpu_to_be64w(&l1_ofs_rt_ofs_cls.l1_offset, 3 * s->cluster_size);
2477 cpu_to_be64w(&l1_ofs_rt_ofs_cls.reftable_offset, s->cluster_size);
2478 cpu_to_be32w(&l1_ofs_rt_ofs_cls.reftable_clusters, 1);
2479 ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, l1_table_offset),
2480 &l1_ofs_rt_ofs_cls, sizeof(l1_ofs_rt_ofs_cls));
2481 if (ret < 0) {
2482 goto fail_broken_refcounts;
2485 s->l1_table_offset = 3 * s->cluster_size;
2487 new_reftable = g_try_new0(uint64_t, s->cluster_size / sizeof(uint64_t));
2488 if (!new_reftable) {
2489 ret = -ENOMEM;
2490 goto fail_broken_refcounts;
2493 s->refcount_table_offset = s->cluster_size;
2494 s->refcount_table_size = s->cluster_size / sizeof(uint64_t);
2496 g_free(s->refcount_table);
2497 s->refcount_table = new_reftable;
2498 new_reftable = NULL;
2500 /* Now the in-memory refcount information again corresponds to the on-disk
2501 * information (reftable is empty and no refblocks (the refblock cache is
2502 * empty)); however, this means some clusters (e.g. the image header) are
2503 * referenced, but not refcounted, but the normal qcow2 code assumes that
2504 * the in-memory information is always correct */
2506 BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_ALLOC);
2508 /* Enter the first refblock into the reftable */
2509 rt_entry = cpu_to_be64(2 * s->cluster_size);
2510 ret = bdrv_pwrite_sync(bs->file, s->cluster_size,
2511 &rt_entry, sizeof(rt_entry));
2512 if (ret < 0) {
2513 goto fail_broken_refcounts;
2515 s->refcount_table[0] = 2 * s->cluster_size;
2517 s->free_cluster_index = 0;
2518 assert(3 + l1_clusters <= s->refcount_block_size);
2519 offset = qcow2_alloc_clusters(bs, 3 * s->cluster_size + l1_size2);
2520 if (offset < 0) {
2521 ret = offset;
2522 goto fail_broken_refcounts;
2523 } else if (offset > 0) {
2524 error_report("First cluster in emptied image is in use");
2525 abort();
2528 /* Now finally the in-memory information corresponds to the on-disk
2529 * structures and is correct */
2530 ret = qcow2_mark_clean(bs);
2531 if (ret < 0) {
2532 goto fail;
2535 ret = bdrv_truncate(bs->file, (3 + l1_clusters) * s->cluster_size);
2536 if (ret < 0) {
2537 goto fail;
2540 return 0;
2542 fail_broken_refcounts:
2543 /* The BDS is unusable at this point. If we wanted to make it usable, we
2544 * would have to call qcow2_refcount_close(), qcow2_refcount_init(),
2545 * qcow2_check_refcounts(), qcow2_refcount_close() and qcow2_refcount_init()
2546 * again. However, because the functions which could have caused this error
2547 * path to be taken are used by those functions as well, it's very likely
2548 * that that sequence will fail as well. Therefore, just eject the BDS. */
2549 bs->drv = NULL;
2551 fail:
2552 g_free(new_reftable);
2553 return ret;
2556 static int qcow2_make_empty(BlockDriverState *bs)
2558 BDRVQcow2State *s = bs->opaque;
2559 uint64_t start_sector;
2560 int sector_step = INT_MAX / BDRV_SECTOR_SIZE;
2561 int l1_clusters, ret = 0;
2563 l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / sizeof(uint64_t));
2565 if (s->qcow_version >= 3 && !s->snapshots &&
2566 3 + l1_clusters <= s->refcount_block_size) {
2567 /* The following function only works for qcow2 v3 images (it requires
2568 * the dirty flag) and only as long as there are no snapshots (because
2569 * it completely empties the image). Furthermore, the L1 table and three
2570 * additional clusters (image header, refcount table, one refcount
2571 * block) have to fit inside one refcount block. */
2572 return make_completely_empty(bs);
2575 /* This fallback code simply discards every active cluster; this is slow,
2576 * but works in all cases */
2577 for (start_sector = 0; start_sector < bs->total_sectors;
2578 start_sector += sector_step)
2580 /* As this function is generally used after committing an external
2581 * snapshot, QCOW2_DISCARD_SNAPSHOT seems appropriate. Also, the
2582 * default action for this kind of discard is to pass the discard,
2583 * which will ideally result in an actually smaller image file, as
2584 * is probably desired. */
2585 ret = qcow2_discard_clusters(bs, start_sector * BDRV_SECTOR_SIZE,
2586 MIN(sector_step,
2587 bs->total_sectors - start_sector),
2588 QCOW2_DISCARD_SNAPSHOT, true);
2589 if (ret < 0) {
2590 break;
2594 return ret;
2597 static coroutine_fn int qcow2_co_flush_to_os(BlockDriverState *bs)
2599 BDRVQcow2State *s = bs->opaque;
2600 int ret;
2602 qemu_co_mutex_lock(&s->lock);
2603 ret = qcow2_cache_flush(bs, s->l2_table_cache);
2604 if (ret < 0) {
2605 qemu_co_mutex_unlock(&s->lock);
2606 return ret;
2609 if (qcow2_need_accurate_refcounts(s)) {
2610 ret = qcow2_cache_flush(bs, s->refcount_block_cache);
2611 if (ret < 0) {
2612 qemu_co_mutex_unlock(&s->lock);
2613 return ret;
2616 qemu_co_mutex_unlock(&s->lock);
2618 return 0;
2621 static int qcow2_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
2623 BDRVQcow2State *s = bs->opaque;
2624 bdi->unallocated_blocks_are_zero = true;
2625 bdi->can_write_zeroes_with_unmap = (s->qcow_version >= 3);
2626 bdi->cluster_size = s->cluster_size;
2627 bdi->vm_state_offset = qcow2_vm_state_offset(s);
2628 return 0;
2631 static ImageInfoSpecific *qcow2_get_specific_info(BlockDriverState *bs)
2633 BDRVQcow2State *s = bs->opaque;
2634 ImageInfoSpecific *spec_info = g_new(ImageInfoSpecific, 1);
2636 *spec_info = (ImageInfoSpecific){
2637 .kind = IMAGE_INFO_SPECIFIC_KIND_QCOW2,
2639 .qcow2 = g_new(ImageInfoSpecificQCow2, 1),
2642 if (s->qcow_version == 2) {
2643 *spec_info->qcow2 = (ImageInfoSpecificQCow2){
2644 .compat = g_strdup("0.10"),
2645 .refcount_bits = s->refcount_bits,
2647 } else if (s->qcow_version == 3) {
2648 *spec_info->qcow2 = (ImageInfoSpecificQCow2){
2649 .compat = g_strdup("1.1"),
2650 .lazy_refcounts = s->compatible_features &
2651 QCOW2_COMPAT_LAZY_REFCOUNTS,
2652 .has_lazy_refcounts = true,
2653 .corrupt = s->incompatible_features &
2654 QCOW2_INCOMPAT_CORRUPT,
2655 .has_corrupt = true,
2656 .refcount_bits = s->refcount_bits,
2660 return spec_info;
2663 #if 0
2664 static void dump_refcounts(BlockDriverState *bs)
2666 BDRVQcow2State *s = bs->opaque;
2667 int64_t nb_clusters, k, k1, size;
2668 int refcount;
2670 size = bdrv_getlength(bs->file);
2671 nb_clusters = size_to_clusters(s, size);
2672 for(k = 0; k < nb_clusters;) {
2673 k1 = k;
2674 refcount = get_refcount(bs, k);
2675 k++;
2676 while (k < nb_clusters && get_refcount(bs, k) == refcount)
2677 k++;
2678 printf("%" PRId64 ": refcount=%d nb=%" PRId64 "\n", k, refcount,
2679 k - k1);
2682 #endif
2684 static int qcow2_save_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
2685 int64_t pos)
2687 BDRVQcow2State *s = bs->opaque;
2688 int64_t total_sectors = bs->total_sectors;
2689 bool zero_beyond_eof = bs->zero_beyond_eof;
2690 int ret;
2692 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_SAVE);
2693 bs->zero_beyond_eof = false;
2694 ret = bdrv_pwritev(bs, qcow2_vm_state_offset(s) + pos, qiov);
2695 bs->zero_beyond_eof = zero_beyond_eof;
2697 /* bdrv_co_do_writev will have increased the total_sectors value to include
2698 * the VM state - the VM state is however not an actual part of the block
2699 * device, therefore, we need to restore the old value. */
2700 bs->total_sectors = total_sectors;
2702 return ret;
2705 static int qcow2_load_vmstate(BlockDriverState *bs, uint8_t *buf,
2706 int64_t pos, int size)
2708 BDRVQcow2State *s = bs->opaque;
2709 bool zero_beyond_eof = bs->zero_beyond_eof;
2710 int ret;
2712 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_LOAD);
2713 bs->zero_beyond_eof = false;
2714 ret = bdrv_pread(bs, qcow2_vm_state_offset(s) + pos, buf, size);
2715 bs->zero_beyond_eof = zero_beyond_eof;
2717 return ret;
2721 * Downgrades an image's version. To achieve this, any incompatible features
2722 * have to be removed.
2724 static int qcow2_downgrade(BlockDriverState *bs, int target_version,
2725 BlockDriverAmendStatusCB *status_cb)
2727 BDRVQcow2State *s = bs->opaque;
2728 int current_version = s->qcow_version;
2729 int ret;
2731 if (target_version == current_version) {
2732 return 0;
2733 } else if (target_version > current_version) {
2734 return -EINVAL;
2735 } else if (target_version != 2) {
2736 return -EINVAL;
2739 if (s->refcount_order != 4) {
2740 /* we would have to convert the image to a refcount_order == 4 image
2741 * here; however, since qemu (at the time of writing this) does not
2742 * support anything different than 4 anyway, there is no point in doing
2743 * so right now; however, we should error out (if qemu supports this in
2744 * the future and this code has not been adapted) */
2745 error_report("qcow2_downgrade: Image refcount orders other than 4 are "
2746 "currently not supported.");
2747 return -ENOTSUP;
2750 /* clear incompatible features */
2751 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
2752 ret = qcow2_mark_clean(bs);
2753 if (ret < 0) {
2754 return ret;
2758 /* with QCOW2_INCOMPAT_CORRUPT, it is pretty much impossible to get here in
2759 * the first place; if that happens nonetheless, returning -ENOTSUP is the
2760 * best thing to do anyway */
2762 if (s->incompatible_features) {
2763 return -ENOTSUP;
2766 /* since we can ignore compatible features, we can set them to 0 as well */
2767 s->compatible_features = 0;
2768 /* if lazy refcounts have been used, they have already been fixed through
2769 * clearing the dirty flag */
2771 /* clearing autoclear features is trivial */
2772 s->autoclear_features = 0;
2774 ret = qcow2_expand_zero_clusters(bs, status_cb);
2775 if (ret < 0) {
2776 return ret;
2779 s->qcow_version = target_version;
2780 ret = qcow2_update_header(bs);
2781 if (ret < 0) {
2782 s->qcow_version = current_version;
2783 return ret;
2785 return 0;
2788 static int qcow2_amend_options(BlockDriverState *bs, QemuOpts *opts,
2789 BlockDriverAmendStatusCB *status_cb)
2791 BDRVQcow2State *s = bs->opaque;
2792 int old_version = s->qcow_version, new_version = old_version;
2793 uint64_t new_size = 0;
2794 const char *backing_file = NULL, *backing_format = NULL;
2795 bool lazy_refcounts = s->use_lazy_refcounts;
2796 const char *compat = NULL;
2797 uint64_t cluster_size = s->cluster_size;
2798 bool encrypt;
2799 int ret;
2800 QemuOptDesc *desc = opts->list->desc;
2802 while (desc && desc->name) {
2803 if (!qemu_opt_find(opts, desc->name)) {
2804 /* only change explicitly defined options */
2805 desc++;
2806 continue;
2809 if (!strcmp(desc->name, BLOCK_OPT_COMPAT_LEVEL)) {
2810 compat = qemu_opt_get(opts, BLOCK_OPT_COMPAT_LEVEL);
2811 if (!compat) {
2812 /* preserve default */
2813 } else if (!strcmp(compat, "0.10")) {
2814 new_version = 2;
2815 } else if (!strcmp(compat, "1.1")) {
2816 new_version = 3;
2817 } else {
2818 fprintf(stderr, "Unknown compatibility level %s.\n", compat);
2819 return -EINVAL;
2821 } else if (!strcmp(desc->name, BLOCK_OPT_PREALLOC)) {
2822 fprintf(stderr, "Cannot change preallocation mode.\n");
2823 return -ENOTSUP;
2824 } else if (!strcmp(desc->name, BLOCK_OPT_SIZE)) {
2825 new_size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, 0);
2826 } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FILE)) {
2827 backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
2828 } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FMT)) {
2829 backing_format = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
2830 } else if (!strcmp(desc->name, BLOCK_OPT_ENCRYPT)) {
2831 encrypt = qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT,
2832 !!s->cipher);
2834 if (encrypt != !!s->cipher) {
2835 fprintf(stderr, "Changing the encryption flag is not "
2836 "supported.\n");
2837 return -ENOTSUP;
2839 } else if (!strcmp(desc->name, BLOCK_OPT_CLUSTER_SIZE)) {
2840 cluster_size = qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE,
2841 cluster_size);
2842 if (cluster_size != s->cluster_size) {
2843 fprintf(stderr, "Changing the cluster size is not "
2844 "supported.\n");
2845 return -ENOTSUP;
2847 } else if (!strcmp(desc->name, BLOCK_OPT_LAZY_REFCOUNTS)) {
2848 lazy_refcounts = qemu_opt_get_bool(opts, BLOCK_OPT_LAZY_REFCOUNTS,
2849 lazy_refcounts);
2850 } else if (!strcmp(desc->name, BLOCK_OPT_REFCOUNT_BITS)) {
2851 error_report("Cannot change refcount entry width");
2852 return -ENOTSUP;
2853 } else {
2854 /* if this assertion fails, this probably means a new option was
2855 * added without having it covered here */
2856 assert(false);
2859 desc++;
2862 if (new_version != old_version) {
2863 if (new_version > old_version) {
2864 /* Upgrade */
2865 s->qcow_version = new_version;
2866 ret = qcow2_update_header(bs);
2867 if (ret < 0) {
2868 s->qcow_version = old_version;
2869 return ret;
2871 } else {
2872 ret = qcow2_downgrade(bs, new_version, status_cb);
2873 if (ret < 0) {
2874 return ret;
2879 if (backing_file || backing_format) {
2880 ret = qcow2_change_backing_file(bs,
2881 backing_file ?: s->image_backing_file,
2882 backing_format ?: s->image_backing_format);
2883 if (ret < 0) {
2884 return ret;
2888 if (s->use_lazy_refcounts != lazy_refcounts) {
2889 if (lazy_refcounts) {
2890 if (s->qcow_version < 3) {
2891 fprintf(stderr, "Lazy refcounts only supported with compatibility "
2892 "level 1.1 and above (use compat=1.1 or greater)\n");
2893 return -EINVAL;
2895 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
2896 ret = qcow2_update_header(bs);
2897 if (ret < 0) {
2898 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
2899 return ret;
2901 s->use_lazy_refcounts = true;
2902 } else {
2903 /* make image clean first */
2904 ret = qcow2_mark_clean(bs);
2905 if (ret < 0) {
2906 return ret;
2908 /* now disallow lazy refcounts */
2909 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
2910 ret = qcow2_update_header(bs);
2911 if (ret < 0) {
2912 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
2913 return ret;
2915 s->use_lazy_refcounts = false;
2919 if (new_size) {
2920 ret = bdrv_truncate(bs, new_size);
2921 if (ret < 0) {
2922 return ret;
2926 return 0;
2930 * If offset or size are negative, respectively, they will not be included in
2931 * the BLOCK_IMAGE_CORRUPTED event emitted.
2932 * fatal will be ignored for read-only BDS; corruptions found there will always
2933 * be considered non-fatal.
2935 void qcow2_signal_corruption(BlockDriverState *bs, bool fatal, int64_t offset,
2936 int64_t size, const char *message_format, ...)
2938 BDRVQcow2State *s = bs->opaque;
2939 const char *node_name;
2940 char *message;
2941 va_list ap;
2943 fatal = fatal && !bs->read_only;
2945 if (s->signaled_corruption &&
2946 (!fatal || (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT)))
2948 return;
2951 va_start(ap, message_format);
2952 message = g_strdup_vprintf(message_format, ap);
2953 va_end(ap);
2955 if (fatal) {
2956 fprintf(stderr, "qcow2: Marking image as corrupt: %s; further "
2957 "corruption events will be suppressed\n", message);
2958 } else {
2959 fprintf(stderr, "qcow2: Image is corrupt: %s; further non-fatal "
2960 "corruption events will be suppressed\n", message);
2963 node_name = bdrv_get_node_name(bs);
2964 qapi_event_send_block_image_corrupted(bdrv_get_device_name(bs),
2965 *node_name != '\0', node_name,
2966 message, offset >= 0, offset,
2967 size >= 0, size,
2968 fatal, &error_abort);
2969 g_free(message);
2971 if (fatal) {
2972 qcow2_mark_corrupt(bs);
2973 bs->drv = NULL; /* make BDS unusable */
2976 s->signaled_corruption = true;
2979 static QemuOptsList qcow2_create_opts = {
2980 .name = "qcow2-create-opts",
2981 .head = QTAILQ_HEAD_INITIALIZER(qcow2_create_opts.head),
2982 .desc = {
2984 .name = BLOCK_OPT_SIZE,
2985 .type = QEMU_OPT_SIZE,
2986 .help = "Virtual disk size"
2989 .name = BLOCK_OPT_COMPAT_LEVEL,
2990 .type = QEMU_OPT_STRING,
2991 .help = "Compatibility level (0.10 or 1.1)"
2994 .name = BLOCK_OPT_BACKING_FILE,
2995 .type = QEMU_OPT_STRING,
2996 .help = "File name of a base image"
2999 .name = BLOCK_OPT_BACKING_FMT,
3000 .type = QEMU_OPT_STRING,
3001 .help = "Image format of the base image"
3004 .name = BLOCK_OPT_ENCRYPT,
3005 .type = QEMU_OPT_BOOL,
3006 .help = "Encrypt the image",
3007 .def_value_str = "off"
3010 .name = BLOCK_OPT_CLUSTER_SIZE,
3011 .type = QEMU_OPT_SIZE,
3012 .help = "qcow2 cluster size",
3013 .def_value_str = stringify(DEFAULT_CLUSTER_SIZE)
3016 .name = BLOCK_OPT_PREALLOC,
3017 .type = QEMU_OPT_STRING,
3018 .help = "Preallocation mode (allowed values: off, metadata, "
3019 "falloc, full)"
3022 .name = BLOCK_OPT_LAZY_REFCOUNTS,
3023 .type = QEMU_OPT_BOOL,
3024 .help = "Postpone refcount updates",
3025 .def_value_str = "off"
3028 .name = BLOCK_OPT_REFCOUNT_BITS,
3029 .type = QEMU_OPT_NUMBER,
3030 .help = "Width of a reference count entry in bits",
3031 .def_value_str = "16"
3033 { /* end of list */ }
3037 BlockDriver bdrv_qcow2 = {
3038 .format_name = "qcow2",
3039 .instance_size = sizeof(BDRVQcow2State),
3040 .bdrv_probe = qcow2_probe,
3041 .bdrv_open = qcow2_open,
3042 .bdrv_close = qcow2_close,
3043 .bdrv_reopen_prepare = qcow2_reopen_prepare,
3044 .bdrv_create = qcow2_create,
3045 .bdrv_has_zero_init = bdrv_has_zero_init_1,
3046 .bdrv_co_get_block_status = qcow2_co_get_block_status,
3047 .bdrv_set_key = qcow2_set_key,
3049 .bdrv_co_readv = qcow2_co_readv,
3050 .bdrv_co_writev = qcow2_co_writev,
3051 .bdrv_co_flush_to_os = qcow2_co_flush_to_os,
3053 .bdrv_co_write_zeroes = qcow2_co_write_zeroes,
3054 .bdrv_co_discard = qcow2_co_discard,
3055 .bdrv_truncate = qcow2_truncate,
3056 .bdrv_write_compressed = qcow2_write_compressed,
3057 .bdrv_make_empty = qcow2_make_empty,
3059 .bdrv_snapshot_create = qcow2_snapshot_create,
3060 .bdrv_snapshot_goto = qcow2_snapshot_goto,
3061 .bdrv_snapshot_delete = qcow2_snapshot_delete,
3062 .bdrv_snapshot_list = qcow2_snapshot_list,
3063 .bdrv_snapshot_load_tmp = qcow2_snapshot_load_tmp,
3064 .bdrv_get_info = qcow2_get_info,
3065 .bdrv_get_specific_info = qcow2_get_specific_info,
3067 .bdrv_save_vmstate = qcow2_save_vmstate,
3068 .bdrv_load_vmstate = qcow2_load_vmstate,
3070 .supports_backing = true,
3071 .bdrv_change_backing_file = qcow2_change_backing_file,
3073 .bdrv_refresh_limits = qcow2_refresh_limits,
3074 .bdrv_invalidate_cache = qcow2_invalidate_cache,
3076 .create_opts = &qcow2_create_opts,
3077 .bdrv_check = qcow2_check,
3078 .bdrv_amend_options = qcow2_amend_options,
3080 .bdrv_detach_aio_context = qcow2_detach_aio_context,
3081 .bdrv_attach_aio_context = qcow2_attach_aio_context,
3084 static void bdrv_qcow2_init(void)
3086 bdrv_register(&bdrv_qcow2);
3089 block_init(bdrv_qcow2_init);