block: Rename BDRV_O_INCOMING to BDRV_O_INACTIVE
[qemu/ar7.git] / block / qcow2.c
blob340ae8f8a3e9c23b89362cdfad51ae73a259ab7d
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/osdep.h"
25 #include "qemu-common.h"
26 #include "block/block_int.h"
27 #include "qemu/module.h"
28 #include <zlib.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 BDRVQcow2State *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->bs, 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->bs, 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 s->image_backing_format = g_strdup(bs->backing_format);
144 #ifdef DEBUG_EXT
145 printf("Qcow2: Got format extension %s\n", bs->backing_format);
146 #endif
147 break;
149 case QCOW2_EXT_MAGIC_FEATURE_TABLE:
150 if (p_feature_table != NULL) {
151 void* feature_table = g_malloc0(ext.len + 2 * sizeof(Qcow2Feature));
152 ret = bdrv_pread(bs->file->bs, offset , feature_table, ext.len);
153 if (ret < 0) {
154 error_setg_errno(errp, -ret, "ERROR: ext_feature_table: "
155 "Could not read table");
156 return ret;
159 *p_feature_table = feature_table;
161 break;
163 default:
164 /* unknown magic - save it in case we need to rewrite the header */
166 Qcow2UnknownHeaderExtension *uext;
168 uext = g_malloc0(sizeof(*uext) + ext.len);
169 uext->magic = ext.magic;
170 uext->len = ext.len;
171 QLIST_INSERT_HEAD(&s->unknown_header_ext, uext, next);
173 ret = bdrv_pread(bs->file->bs, offset , uext->data, uext->len);
174 if (ret < 0) {
175 error_setg_errno(errp, -ret, "ERROR: unknown extension: "
176 "Could not read data");
177 return ret;
180 break;
183 offset += ((ext.len + 7) & ~7);
186 return 0;
189 static void cleanup_unknown_header_ext(BlockDriverState *bs)
191 BDRVQcow2State *s = bs->opaque;
192 Qcow2UnknownHeaderExtension *uext, *next;
194 QLIST_FOREACH_SAFE(uext, &s->unknown_header_ext, next, next) {
195 QLIST_REMOVE(uext, next);
196 g_free(uext);
200 static void GCC_FMT_ATTR(3, 4) report_unsupported(BlockDriverState *bs,
201 Error **errp, const char *fmt, ...)
203 char msg[64];
204 va_list ap;
206 va_start(ap, fmt);
207 vsnprintf(msg, sizeof(msg), fmt, ap);
208 va_end(ap);
210 error_setg(errp, QERR_UNKNOWN_BLOCK_FORMAT_FEATURE,
211 bdrv_get_device_or_node_name(bs), "qcow2", msg);
214 static void report_unsupported_feature(BlockDriverState *bs,
215 Error **errp, Qcow2Feature *table, uint64_t mask)
217 char *features = g_strdup("");
218 char *old;
220 while (table && table->name[0] != '\0') {
221 if (table->type == QCOW2_FEAT_TYPE_INCOMPATIBLE) {
222 if (mask & (1ULL << table->bit)) {
223 old = features;
224 features = g_strdup_printf("%s%s%.46s", old, *old ? ", " : "",
225 table->name);
226 g_free(old);
227 mask &= ~(1ULL << table->bit);
230 table++;
233 if (mask) {
234 old = features;
235 features = g_strdup_printf("%s%sUnknown incompatible feature: %" PRIx64,
236 old, *old ? ", " : "", mask);
237 g_free(old);
240 report_unsupported(bs, errp, "%s", features);
241 g_free(features);
245 * Sets the dirty bit and flushes afterwards if necessary.
247 * The incompatible_features bit is only set if the image file header was
248 * updated successfully. Therefore it is not required to check the return
249 * value of this function.
251 int qcow2_mark_dirty(BlockDriverState *bs)
253 BDRVQcow2State *s = bs->opaque;
254 uint64_t val;
255 int ret;
257 assert(s->qcow_version >= 3);
259 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
260 return 0; /* already dirty */
263 val = cpu_to_be64(s->incompatible_features | QCOW2_INCOMPAT_DIRTY);
264 ret = bdrv_pwrite(bs->file->bs, offsetof(QCowHeader, incompatible_features),
265 &val, sizeof(val));
266 if (ret < 0) {
267 return ret;
269 ret = bdrv_flush(bs->file->bs);
270 if (ret < 0) {
271 return ret;
274 /* Only treat image as dirty if the header was updated successfully */
275 s->incompatible_features |= QCOW2_INCOMPAT_DIRTY;
276 return 0;
280 * Clears the dirty bit and flushes before if necessary. Only call this
281 * function when there are no pending requests, it does not guard against
282 * concurrent requests dirtying the image.
284 static int qcow2_mark_clean(BlockDriverState *bs)
286 BDRVQcow2State *s = bs->opaque;
288 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
289 int ret;
291 s->incompatible_features &= ~QCOW2_INCOMPAT_DIRTY;
293 ret = bdrv_flush(bs);
294 if (ret < 0) {
295 return ret;
298 return qcow2_update_header(bs);
300 return 0;
304 * Marks the image as corrupt.
306 int qcow2_mark_corrupt(BlockDriverState *bs)
308 BDRVQcow2State *s = bs->opaque;
310 s->incompatible_features |= QCOW2_INCOMPAT_CORRUPT;
311 return qcow2_update_header(bs);
315 * Marks the image as consistent, i.e., unsets the corrupt bit, and flushes
316 * before if necessary.
318 int qcow2_mark_consistent(BlockDriverState *bs)
320 BDRVQcow2State *s = bs->opaque;
322 if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
323 int ret = bdrv_flush(bs);
324 if (ret < 0) {
325 return ret;
328 s->incompatible_features &= ~QCOW2_INCOMPAT_CORRUPT;
329 return qcow2_update_header(bs);
331 return 0;
334 static int qcow2_check(BlockDriverState *bs, BdrvCheckResult *result,
335 BdrvCheckMode fix)
337 int ret = qcow2_check_refcounts(bs, result, fix);
338 if (ret < 0) {
339 return ret;
342 if (fix && result->check_errors == 0 && result->corruptions == 0) {
343 ret = qcow2_mark_clean(bs);
344 if (ret < 0) {
345 return ret;
347 return qcow2_mark_consistent(bs);
349 return ret;
352 static int validate_table_offset(BlockDriverState *bs, uint64_t offset,
353 uint64_t entries, size_t entry_len)
355 BDRVQcow2State *s = bs->opaque;
356 uint64_t size;
358 /* Use signed INT64_MAX as the maximum even for uint64_t header fields,
359 * because values will be passed to qemu functions taking int64_t. */
360 if (entries > INT64_MAX / entry_len) {
361 return -EINVAL;
364 size = entries * entry_len;
366 if (INT64_MAX - size < offset) {
367 return -EINVAL;
370 /* Tables must be cluster aligned */
371 if (offset & (s->cluster_size - 1)) {
372 return -EINVAL;
375 return 0;
378 static QemuOptsList qcow2_runtime_opts = {
379 .name = "qcow2",
380 .head = QTAILQ_HEAD_INITIALIZER(qcow2_runtime_opts.head),
381 .desc = {
383 .name = QCOW2_OPT_LAZY_REFCOUNTS,
384 .type = QEMU_OPT_BOOL,
385 .help = "Postpone refcount updates",
388 .name = QCOW2_OPT_DISCARD_REQUEST,
389 .type = QEMU_OPT_BOOL,
390 .help = "Pass guest discard requests to the layer below",
393 .name = QCOW2_OPT_DISCARD_SNAPSHOT,
394 .type = QEMU_OPT_BOOL,
395 .help = "Generate discard requests when snapshot related space "
396 "is freed",
399 .name = QCOW2_OPT_DISCARD_OTHER,
400 .type = QEMU_OPT_BOOL,
401 .help = "Generate discard requests when other clusters are freed",
404 .name = QCOW2_OPT_OVERLAP,
405 .type = QEMU_OPT_STRING,
406 .help = "Selects which overlap checks to perform from a range of "
407 "templates (none, constant, cached, all)",
410 .name = QCOW2_OPT_OVERLAP_TEMPLATE,
411 .type = QEMU_OPT_STRING,
412 .help = "Selects which overlap checks to perform from a range of "
413 "templates (none, constant, cached, all)",
416 .name = QCOW2_OPT_OVERLAP_MAIN_HEADER,
417 .type = QEMU_OPT_BOOL,
418 .help = "Check for unintended writes into the main qcow2 header",
421 .name = QCOW2_OPT_OVERLAP_ACTIVE_L1,
422 .type = QEMU_OPT_BOOL,
423 .help = "Check for unintended writes into the active L1 table",
426 .name = QCOW2_OPT_OVERLAP_ACTIVE_L2,
427 .type = QEMU_OPT_BOOL,
428 .help = "Check for unintended writes into an active L2 table",
431 .name = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
432 .type = QEMU_OPT_BOOL,
433 .help = "Check for unintended writes into the refcount table",
436 .name = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
437 .type = QEMU_OPT_BOOL,
438 .help = "Check for unintended writes into a refcount block",
441 .name = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
442 .type = QEMU_OPT_BOOL,
443 .help = "Check for unintended writes into the snapshot table",
446 .name = QCOW2_OPT_OVERLAP_INACTIVE_L1,
447 .type = QEMU_OPT_BOOL,
448 .help = "Check for unintended writes into an inactive L1 table",
451 .name = QCOW2_OPT_OVERLAP_INACTIVE_L2,
452 .type = QEMU_OPT_BOOL,
453 .help = "Check for unintended writes into an inactive L2 table",
456 .name = QCOW2_OPT_CACHE_SIZE,
457 .type = QEMU_OPT_SIZE,
458 .help = "Maximum combined metadata (L2 tables and refcount blocks) "
459 "cache size",
462 .name = QCOW2_OPT_L2_CACHE_SIZE,
463 .type = QEMU_OPT_SIZE,
464 .help = "Maximum L2 table cache size",
467 .name = QCOW2_OPT_REFCOUNT_CACHE_SIZE,
468 .type = QEMU_OPT_SIZE,
469 .help = "Maximum refcount block cache size",
472 .name = QCOW2_OPT_CACHE_CLEAN_INTERVAL,
473 .type = QEMU_OPT_NUMBER,
474 .help = "Clean unused cache entries after this time (in seconds)",
476 { /* end of list */ }
480 static const char *overlap_bool_option_names[QCOW2_OL_MAX_BITNR] = {
481 [QCOW2_OL_MAIN_HEADER_BITNR] = QCOW2_OPT_OVERLAP_MAIN_HEADER,
482 [QCOW2_OL_ACTIVE_L1_BITNR] = QCOW2_OPT_OVERLAP_ACTIVE_L1,
483 [QCOW2_OL_ACTIVE_L2_BITNR] = QCOW2_OPT_OVERLAP_ACTIVE_L2,
484 [QCOW2_OL_REFCOUNT_TABLE_BITNR] = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
485 [QCOW2_OL_REFCOUNT_BLOCK_BITNR] = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
486 [QCOW2_OL_SNAPSHOT_TABLE_BITNR] = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
487 [QCOW2_OL_INACTIVE_L1_BITNR] = QCOW2_OPT_OVERLAP_INACTIVE_L1,
488 [QCOW2_OL_INACTIVE_L2_BITNR] = QCOW2_OPT_OVERLAP_INACTIVE_L2,
491 static void cache_clean_timer_cb(void *opaque)
493 BlockDriverState *bs = opaque;
494 BDRVQcow2State *s = bs->opaque;
495 qcow2_cache_clean_unused(bs, s->l2_table_cache);
496 qcow2_cache_clean_unused(bs, s->refcount_block_cache);
497 timer_mod(s->cache_clean_timer, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) +
498 (int64_t) s->cache_clean_interval * 1000);
501 static void cache_clean_timer_init(BlockDriverState *bs, AioContext *context)
503 BDRVQcow2State *s = bs->opaque;
504 if (s->cache_clean_interval > 0) {
505 s->cache_clean_timer = aio_timer_new(context, QEMU_CLOCK_VIRTUAL,
506 SCALE_MS, cache_clean_timer_cb,
507 bs);
508 timer_mod(s->cache_clean_timer, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) +
509 (int64_t) s->cache_clean_interval * 1000);
513 static void cache_clean_timer_del(BlockDriverState *bs)
515 BDRVQcow2State *s = bs->opaque;
516 if (s->cache_clean_timer) {
517 timer_del(s->cache_clean_timer);
518 timer_free(s->cache_clean_timer);
519 s->cache_clean_timer = NULL;
523 static void qcow2_detach_aio_context(BlockDriverState *bs)
525 cache_clean_timer_del(bs);
528 static void qcow2_attach_aio_context(BlockDriverState *bs,
529 AioContext *new_context)
531 cache_clean_timer_init(bs, new_context);
534 static void read_cache_sizes(BlockDriverState *bs, QemuOpts *opts,
535 uint64_t *l2_cache_size,
536 uint64_t *refcount_cache_size, Error **errp)
538 BDRVQcow2State *s = bs->opaque;
539 uint64_t combined_cache_size;
540 bool l2_cache_size_set, refcount_cache_size_set, combined_cache_size_set;
542 combined_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_CACHE_SIZE);
543 l2_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_L2_CACHE_SIZE);
544 refcount_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
546 combined_cache_size = qemu_opt_get_size(opts, QCOW2_OPT_CACHE_SIZE, 0);
547 *l2_cache_size = qemu_opt_get_size(opts, QCOW2_OPT_L2_CACHE_SIZE, 0);
548 *refcount_cache_size = qemu_opt_get_size(opts,
549 QCOW2_OPT_REFCOUNT_CACHE_SIZE, 0);
551 if (combined_cache_size_set) {
552 if (l2_cache_size_set && refcount_cache_size_set) {
553 error_setg(errp, QCOW2_OPT_CACHE_SIZE ", " QCOW2_OPT_L2_CACHE_SIZE
554 " and " QCOW2_OPT_REFCOUNT_CACHE_SIZE " may not be set "
555 "the same time");
556 return;
557 } else if (*l2_cache_size > combined_cache_size) {
558 error_setg(errp, QCOW2_OPT_L2_CACHE_SIZE " may not exceed "
559 QCOW2_OPT_CACHE_SIZE);
560 return;
561 } else if (*refcount_cache_size > combined_cache_size) {
562 error_setg(errp, QCOW2_OPT_REFCOUNT_CACHE_SIZE " may not exceed "
563 QCOW2_OPT_CACHE_SIZE);
564 return;
567 if (l2_cache_size_set) {
568 *refcount_cache_size = combined_cache_size - *l2_cache_size;
569 } else if (refcount_cache_size_set) {
570 *l2_cache_size = combined_cache_size - *refcount_cache_size;
571 } else {
572 *refcount_cache_size = combined_cache_size
573 / (DEFAULT_L2_REFCOUNT_SIZE_RATIO + 1);
574 *l2_cache_size = combined_cache_size - *refcount_cache_size;
576 } else {
577 if (!l2_cache_size_set && !refcount_cache_size_set) {
578 *l2_cache_size = MAX(DEFAULT_L2_CACHE_BYTE_SIZE,
579 (uint64_t)DEFAULT_L2_CACHE_CLUSTERS
580 * s->cluster_size);
581 *refcount_cache_size = *l2_cache_size
582 / DEFAULT_L2_REFCOUNT_SIZE_RATIO;
583 } else if (!l2_cache_size_set) {
584 *l2_cache_size = *refcount_cache_size
585 * DEFAULT_L2_REFCOUNT_SIZE_RATIO;
586 } else if (!refcount_cache_size_set) {
587 *refcount_cache_size = *l2_cache_size
588 / DEFAULT_L2_REFCOUNT_SIZE_RATIO;
593 typedef struct Qcow2ReopenState {
594 Qcow2Cache *l2_table_cache;
595 Qcow2Cache *refcount_block_cache;
596 bool use_lazy_refcounts;
597 int overlap_check;
598 bool discard_passthrough[QCOW2_DISCARD_MAX];
599 uint64_t cache_clean_interval;
600 } Qcow2ReopenState;
602 static int qcow2_update_options_prepare(BlockDriverState *bs,
603 Qcow2ReopenState *r,
604 QDict *options, int flags,
605 Error **errp)
607 BDRVQcow2State *s = bs->opaque;
608 QemuOpts *opts = NULL;
609 const char *opt_overlap_check, *opt_overlap_check_template;
610 int overlap_check_template = 0;
611 uint64_t l2_cache_size, refcount_cache_size;
612 int i;
613 Error *local_err = NULL;
614 int ret;
616 opts = qemu_opts_create(&qcow2_runtime_opts, NULL, 0, &error_abort);
617 qemu_opts_absorb_qdict(opts, options, &local_err);
618 if (local_err) {
619 error_propagate(errp, local_err);
620 ret = -EINVAL;
621 goto fail;
624 /* get L2 table/refcount block cache size from command line options */
625 read_cache_sizes(bs, opts, &l2_cache_size, &refcount_cache_size,
626 &local_err);
627 if (local_err) {
628 error_propagate(errp, local_err);
629 ret = -EINVAL;
630 goto fail;
633 l2_cache_size /= s->cluster_size;
634 if (l2_cache_size < MIN_L2_CACHE_SIZE) {
635 l2_cache_size = MIN_L2_CACHE_SIZE;
637 if (l2_cache_size > INT_MAX) {
638 error_setg(errp, "L2 cache size too big");
639 ret = -EINVAL;
640 goto fail;
643 refcount_cache_size /= s->cluster_size;
644 if (refcount_cache_size < MIN_REFCOUNT_CACHE_SIZE) {
645 refcount_cache_size = MIN_REFCOUNT_CACHE_SIZE;
647 if (refcount_cache_size > INT_MAX) {
648 error_setg(errp, "Refcount cache size too big");
649 ret = -EINVAL;
650 goto fail;
653 /* alloc new L2 table/refcount block cache, flush old one */
654 if (s->l2_table_cache) {
655 ret = qcow2_cache_flush(bs, s->l2_table_cache);
656 if (ret) {
657 error_setg_errno(errp, -ret, "Failed to flush the L2 table cache");
658 goto fail;
662 if (s->refcount_block_cache) {
663 ret = qcow2_cache_flush(bs, s->refcount_block_cache);
664 if (ret) {
665 error_setg_errno(errp, -ret,
666 "Failed to flush the refcount block cache");
667 goto fail;
671 r->l2_table_cache = qcow2_cache_create(bs, l2_cache_size);
672 r->refcount_block_cache = qcow2_cache_create(bs, refcount_cache_size);
673 if (r->l2_table_cache == NULL || r->refcount_block_cache == NULL) {
674 error_setg(errp, "Could not allocate metadata caches");
675 ret = -ENOMEM;
676 goto fail;
679 /* New interval for cache cleanup timer */
680 r->cache_clean_interval =
681 qemu_opt_get_number(opts, QCOW2_OPT_CACHE_CLEAN_INTERVAL,
682 s->cache_clean_interval);
683 if (r->cache_clean_interval > UINT_MAX) {
684 error_setg(errp, "Cache clean interval too big");
685 ret = -EINVAL;
686 goto fail;
689 /* lazy-refcounts; flush if going from enabled to disabled */
690 r->use_lazy_refcounts = qemu_opt_get_bool(opts, QCOW2_OPT_LAZY_REFCOUNTS,
691 (s->compatible_features & QCOW2_COMPAT_LAZY_REFCOUNTS));
692 if (r->use_lazy_refcounts && s->qcow_version < 3) {
693 error_setg(errp, "Lazy refcounts require a qcow2 image with at least "
694 "qemu 1.1 compatibility level");
695 ret = -EINVAL;
696 goto fail;
699 if (s->use_lazy_refcounts && !r->use_lazy_refcounts) {
700 ret = qcow2_mark_clean(bs);
701 if (ret < 0) {
702 error_setg_errno(errp, -ret, "Failed to disable lazy refcounts");
703 goto fail;
707 /* Overlap check options */
708 opt_overlap_check = qemu_opt_get(opts, QCOW2_OPT_OVERLAP);
709 opt_overlap_check_template = qemu_opt_get(opts, QCOW2_OPT_OVERLAP_TEMPLATE);
710 if (opt_overlap_check_template && opt_overlap_check &&
711 strcmp(opt_overlap_check_template, opt_overlap_check))
713 error_setg(errp, "Conflicting values for qcow2 options '"
714 QCOW2_OPT_OVERLAP "' ('%s') and '" QCOW2_OPT_OVERLAP_TEMPLATE
715 "' ('%s')", opt_overlap_check, opt_overlap_check_template);
716 ret = -EINVAL;
717 goto fail;
719 if (!opt_overlap_check) {
720 opt_overlap_check = opt_overlap_check_template ?: "cached";
723 if (!strcmp(opt_overlap_check, "none")) {
724 overlap_check_template = 0;
725 } else if (!strcmp(opt_overlap_check, "constant")) {
726 overlap_check_template = QCOW2_OL_CONSTANT;
727 } else if (!strcmp(opt_overlap_check, "cached")) {
728 overlap_check_template = QCOW2_OL_CACHED;
729 } else if (!strcmp(opt_overlap_check, "all")) {
730 overlap_check_template = QCOW2_OL_ALL;
731 } else {
732 error_setg(errp, "Unsupported value '%s' for qcow2 option "
733 "'overlap-check'. Allowed are any of the following: "
734 "none, constant, cached, all", opt_overlap_check);
735 ret = -EINVAL;
736 goto fail;
739 r->overlap_check = 0;
740 for (i = 0; i < QCOW2_OL_MAX_BITNR; i++) {
741 /* overlap-check defines a template bitmask, but every flag may be
742 * overwritten through the associated boolean option */
743 r->overlap_check |=
744 qemu_opt_get_bool(opts, overlap_bool_option_names[i],
745 overlap_check_template & (1 << i)) << i;
748 r->discard_passthrough[QCOW2_DISCARD_NEVER] = false;
749 r->discard_passthrough[QCOW2_DISCARD_ALWAYS] = true;
750 r->discard_passthrough[QCOW2_DISCARD_REQUEST] =
751 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_REQUEST,
752 flags & BDRV_O_UNMAP);
753 r->discard_passthrough[QCOW2_DISCARD_SNAPSHOT] =
754 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_SNAPSHOT, true);
755 r->discard_passthrough[QCOW2_DISCARD_OTHER] =
756 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_OTHER, false);
758 ret = 0;
759 fail:
760 qemu_opts_del(opts);
761 opts = NULL;
762 return ret;
765 static void qcow2_update_options_commit(BlockDriverState *bs,
766 Qcow2ReopenState *r)
768 BDRVQcow2State *s = bs->opaque;
769 int i;
771 if (s->l2_table_cache) {
772 qcow2_cache_destroy(bs, s->l2_table_cache);
774 if (s->refcount_block_cache) {
775 qcow2_cache_destroy(bs, s->refcount_block_cache);
777 s->l2_table_cache = r->l2_table_cache;
778 s->refcount_block_cache = r->refcount_block_cache;
780 s->overlap_check = r->overlap_check;
781 s->use_lazy_refcounts = r->use_lazy_refcounts;
783 for (i = 0; i < QCOW2_DISCARD_MAX; i++) {
784 s->discard_passthrough[i] = r->discard_passthrough[i];
787 if (s->cache_clean_interval != r->cache_clean_interval) {
788 cache_clean_timer_del(bs);
789 s->cache_clean_interval = r->cache_clean_interval;
790 cache_clean_timer_init(bs, bdrv_get_aio_context(bs));
794 static void qcow2_update_options_abort(BlockDriverState *bs,
795 Qcow2ReopenState *r)
797 if (r->l2_table_cache) {
798 qcow2_cache_destroy(bs, r->l2_table_cache);
800 if (r->refcount_block_cache) {
801 qcow2_cache_destroy(bs, r->refcount_block_cache);
805 static int qcow2_update_options(BlockDriverState *bs, QDict *options,
806 int flags, Error **errp)
808 Qcow2ReopenState r = {};
809 int ret;
811 ret = qcow2_update_options_prepare(bs, &r, options, flags, errp);
812 if (ret >= 0) {
813 qcow2_update_options_commit(bs, &r);
814 } else {
815 qcow2_update_options_abort(bs, &r);
818 return ret;
821 static int qcow2_open(BlockDriverState *bs, QDict *options, int flags,
822 Error **errp)
824 BDRVQcow2State *s = bs->opaque;
825 unsigned int len, i;
826 int ret = 0;
827 QCowHeader header;
828 Error *local_err = NULL;
829 uint64_t ext_end;
830 uint64_t l1_vm_state_index;
832 ret = bdrv_pread(bs->file->bs, 0, &header, sizeof(header));
833 if (ret < 0) {
834 error_setg_errno(errp, -ret, "Could not read qcow2 header");
835 goto fail;
837 be32_to_cpus(&header.magic);
838 be32_to_cpus(&header.version);
839 be64_to_cpus(&header.backing_file_offset);
840 be32_to_cpus(&header.backing_file_size);
841 be64_to_cpus(&header.size);
842 be32_to_cpus(&header.cluster_bits);
843 be32_to_cpus(&header.crypt_method);
844 be64_to_cpus(&header.l1_table_offset);
845 be32_to_cpus(&header.l1_size);
846 be64_to_cpus(&header.refcount_table_offset);
847 be32_to_cpus(&header.refcount_table_clusters);
848 be64_to_cpus(&header.snapshots_offset);
849 be32_to_cpus(&header.nb_snapshots);
851 if (header.magic != QCOW_MAGIC) {
852 error_setg(errp, "Image is not in qcow2 format");
853 ret = -EINVAL;
854 goto fail;
856 if (header.version < 2 || header.version > 3) {
857 report_unsupported(bs, errp, "QCOW version %" PRIu32, header.version);
858 ret = -ENOTSUP;
859 goto fail;
862 s->qcow_version = header.version;
864 /* Initialise cluster size */
865 if (header.cluster_bits < MIN_CLUSTER_BITS ||
866 header.cluster_bits > MAX_CLUSTER_BITS) {
867 error_setg(errp, "Unsupported cluster size: 2^%" PRIu32,
868 header.cluster_bits);
869 ret = -EINVAL;
870 goto fail;
873 s->cluster_bits = header.cluster_bits;
874 s->cluster_size = 1 << s->cluster_bits;
875 s->cluster_sectors = 1 << (s->cluster_bits - 9);
877 /* Initialise version 3 header fields */
878 if (header.version == 2) {
879 header.incompatible_features = 0;
880 header.compatible_features = 0;
881 header.autoclear_features = 0;
882 header.refcount_order = 4;
883 header.header_length = 72;
884 } else {
885 be64_to_cpus(&header.incompatible_features);
886 be64_to_cpus(&header.compatible_features);
887 be64_to_cpus(&header.autoclear_features);
888 be32_to_cpus(&header.refcount_order);
889 be32_to_cpus(&header.header_length);
891 if (header.header_length < 104) {
892 error_setg(errp, "qcow2 header too short");
893 ret = -EINVAL;
894 goto fail;
898 if (header.header_length > s->cluster_size) {
899 error_setg(errp, "qcow2 header exceeds cluster size");
900 ret = -EINVAL;
901 goto fail;
904 if (header.header_length > sizeof(header)) {
905 s->unknown_header_fields_size = header.header_length - sizeof(header);
906 s->unknown_header_fields = g_malloc(s->unknown_header_fields_size);
907 ret = bdrv_pread(bs->file->bs, sizeof(header), s->unknown_header_fields,
908 s->unknown_header_fields_size);
909 if (ret < 0) {
910 error_setg_errno(errp, -ret, "Could not read unknown qcow2 header "
911 "fields");
912 goto fail;
916 if (header.backing_file_offset > s->cluster_size) {
917 error_setg(errp, "Invalid backing file offset");
918 ret = -EINVAL;
919 goto fail;
922 if (header.backing_file_offset) {
923 ext_end = header.backing_file_offset;
924 } else {
925 ext_end = 1 << header.cluster_bits;
928 /* Handle feature bits */
929 s->incompatible_features = header.incompatible_features;
930 s->compatible_features = header.compatible_features;
931 s->autoclear_features = header.autoclear_features;
933 if (s->incompatible_features & ~QCOW2_INCOMPAT_MASK) {
934 void *feature_table = NULL;
935 qcow2_read_extensions(bs, header.header_length, ext_end,
936 &feature_table, NULL);
937 report_unsupported_feature(bs, errp, feature_table,
938 s->incompatible_features &
939 ~QCOW2_INCOMPAT_MASK);
940 ret = -ENOTSUP;
941 g_free(feature_table);
942 goto fail;
945 if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
946 /* Corrupt images may not be written to unless they are being repaired
948 if ((flags & BDRV_O_RDWR) && !(flags & BDRV_O_CHECK)) {
949 error_setg(errp, "qcow2: Image is corrupt; cannot be opened "
950 "read/write");
951 ret = -EACCES;
952 goto fail;
956 /* Check support for various header values */
957 if (header.refcount_order > 6) {
958 error_setg(errp, "Reference count entry width too large; may not "
959 "exceed 64 bits");
960 ret = -EINVAL;
961 goto fail;
963 s->refcount_order = header.refcount_order;
964 s->refcount_bits = 1 << s->refcount_order;
965 s->refcount_max = UINT64_C(1) << (s->refcount_bits - 1);
966 s->refcount_max += s->refcount_max - 1;
968 if (header.crypt_method > QCOW_CRYPT_AES) {
969 error_setg(errp, "Unsupported encryption method: %" PRIu32,
970 header.crypt_method);
971 ret = -EINVAL;
972 goto fail;
974 if (!qcrypto_cipher_supports(QCRYPTO_CIPHER_ALG_AES_128)) {
975 error_setg(errp, "AES cipher not available");
976 ret = -EINVAL;
977 goto fail;
979 s->crypt_method_header = header.crypt_method;
980 if (s->crypt_method_header) {
981 bs->encrypted = 1;
984 s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */
985 s->l2_size = 1 << s->l2_bits;
986 /* 2^(s->refcount_order - 3) is the refcount width in bytes */
987 s->refcount_block_bits = s->cluster_bits - (s->refcount_order - 3);
988 s->refcount_block_size = 1 << s->refcount_block_bits;
989 bs->total_sectors = header.size / 512;
990 s->csize_shift = (62 - (s->cluster_bits - 8));
991 s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;
992 s->cluster_offset_mask = (1LL << s->csize_shift) - 1;
994 s->refcount_table_offset = header.refcount_table_offset;
995 s->refcount_table_size =
996 header.refcount_table_clusters << (s->cluster_bits - 3);
998 if (header.refcount_table_clusters > qcow2_max_refcount_clusters(s)) {
999 error_setg(errp, "Reference count table too large");
1000 ret = -EINVAL;
1001 goto fail;
1004 ret = validate_table_offset(bs, s->refcount_table_offset,
1005 s->refcount_table_size, sizeof(uint64_t));
1006 if (ret < 0) {
1007 error_setg(errp, "Invalid reference count table offset");
1008 goto fail;
1011 /* Snapshot table offset/length */
1012 if (header.nb_snapshots > QCOW_MAX_SNAPSHOTS) {
1013 error_setg(errp, "Too many snapshots");
1014 ret = -EINVAL;
1015 goto fail;
1018 ret = validate_table_offset(bs, header.snapshots_offset,
1019 header.nb_snapshots,
1020 sizeof(QCowSnapshotHeader));
1021 if (ret < 0) {
1022 error_setg(errp, "Invalid snapshot table offset");
1023 goto fail;
1026 /* read the level 1 table */
1027 if (header.l1_size > QCOW_MAX_L1_SIZE / sizeof(uint64_t)) {
1028 error_setg(errp, "Active L1 table too large");
1029 ret = -EFBIG;
1030 goto fail;
1032 s->l1_size = header.l1_size;
1034 l1_vm_state_index = size_to_l1(s, header.size);
1035 if (l1_vm_state_index > INT_MAX) {
1036 error_setg(errp, "Image is too big");
1037 ret = -EFBIG;
1038 goto fail;
1040 s->l1_vm_state_index = l1_vm_state_index;
1042 /* the L1 table must contain at least enough entries to put
1043 header.size bytes */
1044 if (s->l1_size < s->l1_vm_state_index) {
1045 error_setg(errp, "L1 table is too small");
1046 ret = -EINVAL;
1047 goto fail;
1050 ret = validate_table_offset(bs, header.l1_table_offset,
1051 header.l1_size, sizeof(uint64_t));
1052 if (ret < 0) {
1053 error_setg(errp, "Invalid L1 table offset");
1054 goto fail;
1056 s->l1_table_offset = header.l1_table_offset;
1059 if (s->l1_size > 0) {
1060 s->l1_table = qemu_try_blockalign(bs->file->bs,
1061 align_offset(s->l1_size * sizeof(uint64_t), 512));
1062 if (s->l1_table == NULL) {
1063 error_setg(errp, "Could not allocate L1 table");
1064 ret = -ENOMEM;
1065 goto fail;
1067 ret = bdrv_pread(bs->file->bs, s->l1_table_offset, s->l1_table,
1068 s->l1_size * sizeof(uint64_t));
1069 if (ret < 0) {
1070 error_setg_errno(errp, -ret, "Could not read L1 table");
1071 goto fail;
1073 for(i = 0;i < s->l1_size; i++) {
1074 be64_to_cpus(&s->l1_table[i]);
1078 /* Parse driver-specific options */
1079 ret = qcow2_update_options(bs, options, flags, errp);
1080 if (ret < 0) {
1081 goto fail;
1084 s->cluster_cache = g_malloc(s->cluster_size);
1085 /* one more sector for decompressed data alignment */
1086 s->cluster_data = qemu_try_blockalign(bs->file->bs, QCOW_MAX_CRYPT_CLUSTERS
1087 * s->cluster_size + 512);
1088 if (s->cluster_data == NULL) {
1089 error_setg(errp, "Could not allocate temporary cluster buffer");
1090 ret = -ENOMEM;
1091 goto fail;
1094 s->cluster_cache_offset = -1;
1095 s->flags = flags;
1097 ret = qcow2_refcount_init(bs);
1098 if (ret != 0) {
1099 error_setg_errno(errp, -ret, "Could not initialize refcount handling");
1100 goto fail;
1103 QLIST_INIT(&s->cluster_allocs);
1104 QTAILQ_INIT(&s->discards);
1106 /* read qcow2 extensions */
1107 if (qcow2_read_extensions(bs, header.header_length, ext_end, NULL,
1108 &local_err)) {
1109 error_propagate(errp, local_err);
1110 ret = -EINVAL;
1111 goto fail;
1114 /* read the backing file name */
1115 if (header.backing_file_offset != 0) {
1116 len = header.backing_file_size;
1117 if (len > MIN(1023, s->cluster_size - header.backing_file_offset) ||
1118 len >= sizeof(bs->backing_file)) {
1119 error_setg(errp, "Backing file name too long");
1120 ret = -EINVAL;
1121 goto fail;
1123 ret = bdrv_pread(bs->file->bs, header.backing_file_offset,
1124 bs->backing_file, len);
1125 if (ret < 0) {
1126 error_setg_errno(errp, -ret, "Could not read backing file name");
1127 goto fail;
1129 bs->backing_file[len] = '\0';
1130 s->image_backing_file = g_strdup(bs->backing_file);
1133 /* Internal snapshots */
1134 s->snapshots_offset = header.snapshots_offset;
1135 s->nb_snapshots = header.nb_snapshots;
1137 ret = qcow2_read_snapshots(bs);
1138 if (ret < 0) {
1139 error_setg_errno(errp, -ret, "Could not read snapshots");
1140 goto fail;
1143 /* Clear unknown autoclear feature bits */
1144 if (!bs->read_only && !(flags & BDRV_O_INACTIVE) && s->autoclear_features) {
1145 s->autoclear_features = 0;
1146 ret = qcow2_update_header(bs);
1147 if (ret < 0) {
1148 error_setg_errno(errp, -ret, "Could not update qcow2 header");
1149 goto fail;
1153 /* Initialise locks */
1154 qemu_co_mutex_init(&s->lock);
1156 /* Repair image if dirty */
1157 if (!(flags & (BDRV_O_CHECK | BDRV_O_INACTIVE)) && !bs->read_only &&
1158 (s->incompatible_features & QCOW2_INCOMPAT_DIRTY)) {
1159 BdrvCheckResult result = {0};
1161 ret = qcow2_check(bs, &result, BDRV_FIX_ERRORS | BDRV_FIX_LEAKS);
1162 if (ret < 0) {
1163 error_setg_errno(errp, -ret, "Could not repair dirty image");
1164 goto fail;
1168 #ifdef DEBUG_ALLOC
1170 BdrvCheckResult result = {0};
1171 qcow2_check_refcounts(bs, &result, 0);
1173 #endif
1174 return ret;
1176 fail:
1177 g_free(s->unknown_header_fields);
1178 cleanup_unknown_header_ext(bs);
1179 qcow2_free_snapshots(bs);
1180 qcow2_refcount_close(bs);
1181 qemu_vfree(s->l1_table);
1182 /* else pre-write overlap checks in cache_destroy may crash */
1183 s->l1_table = NULL;
1184 cache_clean_timer_del(bs);
1185 if (s->l2_table_cache) {
1186 qcow2_cache_destroy(bs, s->l2_table_cache);
1188 if (s->refcount_block_cache) {
1189 qcow2_cache_destroy(bs, s->refcount_block_cache);
1191 g_free(s->cluster_cache);
1192 qemu_vfree(s->cluster_data);
1193 return ret;
1196 static void qcow2_refresh_limits(BlockDriverState *bs, Error **errp)
1198 BDRVQcow2State *s = bs->opaque;
1200 bs->bl.write_zeroes_alignment = s->cluster_sectors;
1203 static int qcow2_set_key(BlockDriverState *bs, const char *key)
1205 BDRVQcow2State *s = bs->opaque;
1206 uint8_t keybuf[16];
1207 int len, i;
1208 Error *err = NULL;
1210 memset(keybuf, 0, 16);
1211 len = strlen(key);
1212 if (len > 16)
1213 len = 16;
1214 /* XXX: we could compress the chars to 7 bits to increase
1215 entropy */
1216 for(i = 0;i < len;i++) {
1217 keybuf[i] = key[i];
1219 assert(bs->encrypted);
1221 qcrypto_cipher_free(s->cipher);
1222 s->cipher = qcrypto_cipher_new(
1223 QCRYPTO_CIPHER_ALG_AES_128,
1224 QCRYPTO_CIPHER_MODE_CBC,
1225 keybuf, G_N_ELEMENTS(keybuf),
1226 &err);
1228 if (!s->cipher) {
1229 /* XXX would be nice if errors in this method could
1230 * be properly propagate to the caller. Would need
1231 * the bdrv_set_key() API signature to be fixed. */
1232 error_free(err);
1233 return -1;
1235 return 0;
1238 static int qcow2_reopen_prepare(BDRVReopenState *state,
1239 BlockReopenQueue *queue, Error **errp)
1241 Qcow2ReopenState *r;
1242 int ret;
1244 r = g_new0(Qcow2ReopenState, 1);
1245 state->opaque = r;
1247 ret = qcow2_update_options_prepare(state->bs, r, state->options,
1248 state->flags, errp);
1249 if (ret < 0) {
1250 goto fail;
1253 /* We need to write out any unwritten data if we reopen read-only. */
1254 if ((state->flags & BDRV_O_RDWR) == 0) {
1255 ret = bdrv_flush(state->bs);
1256 if (ret < 0) {
1257 goto fail;
1260 ret = qcow2_mark_clean(state->bs);
1261 if (ret < 0) {
1262 goto fail;
1266 return 0;
1268 fail:
1269 qcow2_update_options_abort(state->bs, r);
1270 g_free(r);
1271 return ret;
1274 static void qcow2_reopen_commit(BDRVReopenState *state)
1276 qcow2_update_options_commit(state->bs, state->opaque);
1277 g_free(state->opaque);
1280 static void qcow2_reopen_abort(BDRVReopenState *state)
1282 qcow2_update_options_abort(state->bs, state->opaque);
1283 g_free(state->opaque);
1286 static void qcow2_join_options(QDict *options, QDict *old_options)
1288 bool has_new_overlap_template =
1289 qdict_haskey(options, QCOW2_OPT_OVERLAP) ||
1290 qdict_haskey(options, QCOW2_OPT_OVERLAP_TEMPLATE);
1291 bool has_new_total_cache_size =
1292 qdict_haskey(options, QCOW2_OPT_CACHE_SIZE);
1293 bool has_all_cache_options;
1295 /* New overlap template overrides all old overlap options */
1296 if (has_new_overlap_template) {
1297 qdict_del(old_options, QCOW2_OPT_OVERLAP);
1298 qdict_del(old_options, QCOW2_OPT_OVERLAP_TEMPLATE);
1299 qdict_del(old_options, QCOW2_OPT_OVERLAP_MAIN_HEADER);
1300 qdict_del(old_options, QCOW2_OPT_OVERLAP_ACTIVE_L1);
1301 qdict_del(old_options, QCOW2_OPT_OVERLAP_ACTIVE_L2);
1302 qdict_del(old_options, QCOW2_OPT_OVERLAP_REFCOUNT_TABLE);
1303 qdict_del(old_options, QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK);
1304 qdict_del(old_options, QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE);
1305 qdict_del(old_options, QCOW2_OPT_OVERLAP_INACTIVE_L1);
1306 qdict_del(old_options, QCOW2_OPT_OVERLAP_INACTIVE_L2);
1309 /* New total cache size overrides all old options */
1310 if (qdict_haskey(options, QCOW2_OPT_CACHE_SIZE)) {
1311 qdict_del(old_options, QCOW2_OPT_L2_CACHE_SIZE);
1312 qdict_del(old_options, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
1315 qdict_join(options, old_options, false);
1318 * If after merging all cache size options are set, an old total size is
1319 * overwritten. Do keep all options, however, if all three are new. The
1320 * resulting error message is what we want to happen.
1322 has_all_cache_options =
1323 qdict_haskey(options, QCOW2_OPT_CACHE_SIZE) ||
1324 qdict_haskey(options, QCOW2_OPT_L2_CACHE_SIZE) ||
1325 qdict_haskey(options, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
1327 if (has_all_cache_options && !has_new_total_cache_size) {
1328 qdict_del(options, QCOW2_OPT_CACHE_SIZE);
1332 static int64_t coroutine_fn qcow2_co_get_block_status(BlockDriverState *bs,
1333 int64_t sector_num, int nb_sectors, int *pnum)
1335 BDRVQcow2State *s = bs->opaque;
1336 uint64_t cluster_offset;
1337 int index_in_cluster, ret;
1338 int64_t status = 0;
1340 *pnum = nb_sectors;
1341 qemu_co_mutex_lock(&s->lock);
1342 ret = qcow2_get_cluster_offset(bs, sector_num << 9, pnum, &cluster_offset);
1343 qemu_co_mutex_unlock(&s->lock);
1344 if (ret < 0) {
1345 return ret;
1348 if (cluster_offset != 0 && ret != QCOW2_CLUSTER_COMPRESSED &&
1349 !s->cipher) {
1350 index_in_cluster = sector_num & (s->cluster_sectors - 1);
1351 cluster_offset |= (index_in_cluster << BDRV_SECTOR_BITS);
1352 status |= BDRV_BLOCK_OFFSET_VALID | cluster_offset;
1354 if (ret == QCOW2_CLUSTER_ZERO) {
1355 status |= BDRV_BLOCK_ZERO;
1356 } else if (ret != QCOW2_CLUSTER_UNALLOCATED) {
1357 status |= BDRV_BLOCK_DATA;
1359 return status;
1362 /* handle reading after the end of the backing file */
1363 int qcow2_backing_read1(BlockDriverState *bs, QEMUIOVector *qiov,
1364 int64_t sector_num, int nb_sectors)
1366 int n1;
1367 if ((sector_num + nb_sectors) <= bs->total_sectors)
1368 return nb_sectors;
1369 if (sector_num >= bs->total_sectors)
1370 n1 = 0;
1371 else
1372 n1 = bs->total_sectors - sector_num;
1374 qemu_iovec_memset(qiov, 512 * n1, 0, 512 * (nb_sectors - n1));
1376 return n1;
1379 static coroutine_fn int qcow2_co_readv(BlockDriverState *bs, int64_t sector_num,
1380 int remaining_sectors, QEMUIOVector *qiov)
1382 BDRVQcow2State *s = bs->opaque;
1383 int index_in_cluster, n1;
1384 int ret;
1385 int cur_nr_sectors; /* number of sectors in current iteration */
1386 uint64_t cluster_offset = 0;
1387 uint64_t bytes_done = 0;
1388 QEMUIOVector hd_qiov;
1389 uint8_t *cluster_data = NULL;
1391 qemu_iovec_init(&hd_qiov, qiov->niov);
1393 qemu_co_mutex_lock(&s->lock);
1395 while (remaining_sectors != 0) {
1397 /* prepare next request */
1398 cur_nr_sectors = remaining_sectors;
1399 if (s->cipher) {
1400 cur_nr_sectors = MIN(cur_nr_sectors,
1401 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors);
1404 ret = qcow2_get_cluster_offset(bs, sector_num << 9,
1405 &cur_nr_sectors, &cluster_offset);
1406 if (ret < 0) {
1407 goto fail;
1410 index_in_cluster = sector_num & (s->cluster_sectors - 1);
1412 qemu_iovec_reset(&hd_qiov);
1413 qemu_iovec_concat(&hd_qiov, qiov, bytes_done,
1414 cur_nr_sectors * 512);
1416 switch (ret) {
1417 case QCOW2_CLUSTER_UNALLOCATED:
1419 if (bs->backing) {
1420 /* read from the base image */
1421 n1 = qcow2_backing_read1(bs->backing->bs, &hd_qiov,
1422 sector_num, cur_nr_sectors);
1423 if (n1 > 0) {
1424 QEMUIOVector local_qiov;
1426 qemu_iovec_init(&local_qiov, hd_qiov.niov);
1427 qemu_iovec_concat(&local_qiov, &hd_qiov, 0,
1428 n1 * BDRV_SECTOR_SIZE);
1430 BLKDBG_EVENT(bs->file, BLKDBG_READ_BACKING_AIO);
1431 qemu_co_mutex_unlock(&s->lock);
1432 ret = bdrv_co_readv(bs->backing->bs, sector_num,
1433 n1, &local_qiov);
1434 qemu_co_mutex_lock(&s->lock);
1436 qemu_iovec_destroy(&local_qiov);
1438 if (ret < 0) {
1439 goto fail;
1442 } else {
1443 /* Note: in this case, no need to wait */
1444 qemu_iovec_memset(&hd_qiov, 0, 0, 512 * cur_nr_sectors);
1446 break;
1448 case QCOW2_CLUSTER_ZERO:
1449 qemu_iovec_memset(&hd_qiov, 0, 0, 512 * cur_nr_sectors);
1450 break;
1452 case QCOW2_CLUSTER_COMPRESSED:
1453 /* add AIO support for compressed blocks ? */
1454 ret = qcow2_decompress_cluster(bs, cluster_offset);
1455 if (ret < 0) {
1456 goto fail;
1459 qemu_iovec_from_buf(&hd_qiov, 0,
1460 s->cluster_cache + index_in_cluster * 512,
1461 512 * cur_nr_sectors);
1462 break;
1464 case QCOW2_CLUSTER_NORMAL:
1465 if ((cluster_offset & 511) != 0) {
1466 ret = -EIO;
1467 goto fail;
1470 if (bs->encrypted) {
1471 assert(s->cipher);
1474 * For encrypted images, read everything into a temporary
1475 * contiguous buffer on which the AES functions can work.
1477 if (!cluster_data) {
1478 cluster_data =
1479 qemu_try_blockalign(bs->file->bs,
1480 QCOW_MAX_CRYPT_CLUSTERS
1481 * s->cluster_size);
1482 if (cluster_data == NULL) {
1483 ret = -ENOMEM;
1484 goto fail;
1488 assert(cur_nr_sectors <=
1489 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors);
1490 qemu_iovec_reset(&hd_qiov);
1491 qemu_iovec_add(&hd_qiov, cluster_data,
1492 512 * cur_nr_sectors);
1495 BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);
1496 qemu_co_mutex_unlock(&s->lock);
1497 ret = bdrv_co_readv(bs->file->bs,
1498 (cluster_offset >> 9) + index_in_cluster,
1499 cur_nr_sectors, &hd_qiov);
1500 qemu_co_mutex_lock(&s->lock);
1501 if (ret < 0) {
1502 goto fail;
1504 if (bs->encrypted) {
1505 assert(s->cipher);
1506 Error *err = NULL;
1507 if (qcow2_encrypt_sectors(s, sector_num, cluster_data,
1508 cluster_data, cur_nr_sectors, false,
1509 &err) < 0) {
1510 error_free(err);
1511 ret = -EIO;
1512 goto fail;
1514 qemu_iovec_from_buf(qiov, bytes_done,
1515 cluster_data, 512 * cur_nr_sectors);
1517 break;
1519 default:
1520 g_assert_not_reached();
1521 ret = -EIO;
1522 goto fail;
1525 remaining_sectors -= cur_nr_sectors;
1526 sector_num += cur_nr_sectors;
1527 bytes_done += cur_nr_sectors * 512;
1529 ret = 0;
1531 fail:
1532 qemu_co_mutex_unlock(&s->lock);
1534 qemu_iovec_destroy(&hd_qiov);
1535 qemu_vfree(cluster_data);
1537 return ret;
1540 static coroutine_fn int qcow2_co_writev(BlockDriverState *bs,
1541 int64_t sector_num,
1542 int remaining_sectors,
1543 QEMUIOVector *qiov)
1545 BDRVQcow2State *s = bs->opaque;
1546 int index_in_cluster;
1547 int ret;
1548 int cur_nr_sectors; /* number of sectors in current iteration */
1549 uint64_t cluster_offset;
1550 QEMUIOVector hd_qiov;
1551 uint64_t bytes_done = 0;
1552 uint8_t *cluster_data = NULL;
1553 QCowL2Meta *l2meta = NULL;
1555 trace_qcow2_writev_start_req(qemu_coroutine_self(), sector_num,
1556 remaining_sectors);
1558 qemu_iovec_init(&hd_qiov, qiov->niov);
1560 s->cluster_cache_offset = -1; /* disable compressed cache */
1562 qemu_co_mutex_lock(&s->lock);
1564 while (remaining_sectors != 0) {
1566 l2meta = NULL;
1568 trace_qcow2_writev_start_part(qemu_coroutine_self());
1569 index_in_cluster = sector_num & (s->cluster_sectors - 1);
1570 cur_nr_sectors = remaining_sectors;
1571 if (bs->encrypted &&
1572 cur_nr_sectors >
1573 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors - index_in_cluster) {
1574 cur_nr_sectors =
1575 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors - index_in_cluster;
1578 ret = qcow2_alloc_cluster_offset(bs, sector_num << 9,
1579 &cur_nr_sectors, &cluster_offset, &l2meta);
1580 if (ret < 0) {
1581 goto fail;
1584 assert((cluster_offset & 511) == 0);
1586 qemu_iovec_reset(&hd_qiov);
1587 qemu_iovec_concat(&hd_qiov, qiov, bytes_done,
1588 cur_nr_sectors * 512);
1590 if (bs->encrypted) {
1591 Error *err = NULL;
1592 assert(s->cipher);
1593 if (!cluster_data) {
1594 cluster_data = qemu_try_blockalign(bs->file->bs,
1595 QCOW_MAX_CRYPT_CLUSTERS
1596 * s->cluster_size);
1597 if (cluster_data == NULL) {
1598 ret = -ENOMEM;
1599 goto fail;
1603 assert(hd_qiov.size <=
1604 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
1605 qemu_iovec_to_buf(&hd_qiov, 0, cluster_data, hd_qiov.size);
1607 if (qcow2_encrypt_sectors(s, sector_num, cluster_data,
1608 cluster_data, cur_nr_sectors,
1609 true, &err) < 0) {
1610 error_free(err);
1611 ret = -EIO;
1612 goto fail;
1615 qemu_iovec_reset(&hd_qiov);
1616 qemu_iovec_add(&hd_qiov, cluster_data,
1617 cur_nr_sectors * 512);
1620 ret = qcow2_pre_write_overlap_check(bs, 0,
1621 cluster_offset + index_in_cluster * BDRV_SECTOR_SIZE,
1622 cur_nr_sectors * BDRV_SECTOR_SIZE);
1623 if (ret < 0) {
1624 goto fail;
1627 qemu_co_mutex_unlock(&s->lock);
1628 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO);
1629 trace_qcow2_writev_data(qemu_coroutine_self(),
1630 (cluster_offset >> 9) + index_in_cluster);
1631 ret = bdrv_co_writev(bs->file->bs,
1632 (cluster_offset >> 9) + index_in_cluster,
1633 cur_nr_sectors, &hd_qiov);
1634 qemu_co_mutex_lock(&s->lock);
1635 if (ret < 0) {
1636 goto fail;
1639 while (l2meta != NULL) {
1640 QCowL2Meta *next;
1642 ret = qcow2_alloc_cluster_link_l2(bs, l2meta);
1643 if (ret < 0) {
1644 goto fail;
1647 /* Take the request off the list of running requests */
1648 if (l2meta->nb_clusters != 0) {
1649 QLIST_REMOVE(l2meta, next_in_flight);
1652 qemu_co_queue_restart_all(&l2meta->dependent_requests);
1654 next = l2meta->next;
1655 g_free(l2meta);
1656 l2meta = next;
1659 remaining_sectors -= cur_nr_sectors;
1660 sector_num += cur_nr_sectors;
1661 bytes_done += cur_nr_sectors * 512;
1662 trace_qcow2_writev_done_part(qemu_coroutine_self(), cur_nr_sectors);
1664 ret = 0;
1666 fail:
1667 qemu_co_mutex_unlock(&s->lock);
1669 while (l2meta != NULL) {
1670 QCowL2Meta *next;
1672 if (l2meta->nb_clusters != 0) {
1673 QLIST_REMOVE(l2meta, next_in_flight);
1675 qemu_co_queue_restart_all(&l2meta->dependent_requests);
1677 next = l2meta->next;
1678 g_free(l2meta);
1679 l2meta = next;
1682 qemu_iovec_destroy(&hd_qiov);
1683 qemu_vfree(cluster_data);
1684 trace_qcow2_writev_done_req(qemu_coroutine_self(), ret);
1686 return ret;
1689 static void qcow2_close(BlockDriverState *bs)
1691 BDRVQcow2State *s = bs->opaque;
1692 qemu_vfree(s->l1_table);
1693 /* else pre-write overlap checks in cache_destroy may crash */
1694 s->l1_table = NULL;
1696 if (!(bs->open_flags & BDRV_O_INACTIVE)) {
1697 int ret1, ret2;
1699 ret1 = qcow2_cache_flush(bs, s->l2_table_cache);
1700 ret2 = qcow2_cache_flush(bs, s->refcount_block_cache);
1702 if (ret1) {
1703 error_report("Failed to flush the L2 table cache: %s",
1704 strerror(-ret1));
1706 if (ret2) {
1707 error_report("Failed to flush the refcount block cache: %s",
1708 strerror(-ret2));
1711 if (!ret1 && !ret2) {
1712 qcow2_mark_clean(bs);
1716 cache_clean_timer_del(bs);
1717 qcow2_cache_destroy(bs, s->l2_table_cache);
1718 qcow2_cache_destroy(bs, s->refcount_block_cache);
1720 qcrypto_cipher_free(s->cipher);
1721 s->cipher = NULL;
1723 g_free(s->unknown_header_fields);
1724 cleanup_unknown_header_ext(bs);
1726 g_free(s->image_backing_file);
1727 g_free(s->image_backing_format);
1729 g_free(s->cluster_cache);
1730 qemu_vfree(s->cluster_data);
1731 qcow2_refcount_close(bs);
1732 qcow2_free_snapshots(bs);
1735 static void qcow2_invalidate_cache(BlockDriverState *bs, Error **errp)
1737 BDRVQcow2State *s = bs->opaque;
1738 int flags = s->flags;
1739 QCryptoCipher *cipher = NULL;
1740 QDict *options;
1741 Error *local_err = NULL;
1742 int ret;
1745 * Backing files are read-only which makes all of their metadata immutable,
1746 * that means we don't have to worry about reopening them here.
1749 cipher = s->cipher;
1750 s->cipher = NULL;
1752 qcow2_close(bs);
1754 bdrv_invalidate_cache(bs->file->bs, &local_err);
1755 if (local_err) {
1756 error_propagate(errp, local_err);
1757 return;
1760 memset(s, 0, sizeof(BDRVQcow2State));
1761 options = qdict_clone_shallow(bs->options);
1763 ret = qcow2_open(bs, options, flags, &local_err);
1764 QDECREF(options);
1765 if (local_err) {
1766 error_propagate(errp, local_err);
1767 error_prepend(errp, "Could not reopen qcow2 layer: ");
1768 return;
1769 } else if (ret < 0) {
1770 error_setg_errno(errp, -ret, "Could not reopen qcow2 layer");
1771 return;
1774 s->cipher = cipher;
1777 static size_t header_ext_add(char *buf, uint32_t magic, const void *s,
1778 size_t len, size_t buflen)
1780 QCowExtension *ext_backing_fmt = (QCowExtension*) buf;
1781 size_t ext_len = sizeof(QCowExtension) + ((len + 7) & ~7);
1783 if (buflen < ext_len) {
1784 return -ENOSPC;
1787 *ext_backing_fmt = (QCowExtension) {
1788 .magic = cpu_to_be32(magic),
1789 .len = cpu_to_be32(len),
1791 memcpy(buf + sizeof(QCowExtension), s, len);
1793 return ext_len;
1797 * Updates the qcow2 header, including the variable length parts of it, i.e.
1798 * the backing file name and all extensions. qcow2 was not designed to allow
1799 * such changes, so if we run out of space (we can only use the first cluster)
1800 * this function may fail.
1802 * Returns 0 on success, -errno in error cases.
1804 int qcow2_update_header(BlockDriverState *bs)
1806 BDRVQcow2State *s = bs->opaque;
1807 QCowHeader *header;
1808 char *buf;
1809 size_t buflen = s->cluster_size;
1810 int ret;
1811 uint64_t total_size;
1812 uint32_t refcount_table_clusters;
1813 size_t header_length;
1814 Qcow2UnknownHeaderExtension *uext;
1816 buf = qemu_blockalign(bs, buflen);
1818 /* Header structure */
1819 header = (QCowHeader*) buf;
1821 if (buflen < sizeof(*header)) {
1822 ret = -ENOSPC;
1823 goto fail;
1826 header_length = sizeof(*header) + s->unknown_header_fields_size;
1827 total_size = bs->total_sectors * BDRV_SECTOR_SIZE;
1828 refcount_table_clusters = s->refcount_table_size >> (s->cluster_bits - 3);
1830 *header = (QCowHeader) {
1831 /* Version 2 fields */
1832 .magic = cpu_to_be32(QCOW_MAGIC),
1833 .version = cpu_to_be32(s->qcow_version),
1834 .backing_file_offset = 0,
1835 .backing_file_size = 0,
1836 .cluster_bits = cpu_to_be32(s->cluster_bits),
1837 .size = cpu_to_be64(total_size),
1838 .crypt_method = cpu_to_be32(s->crypt_method_header),
1839 .l1_size = cpu_to_be32(s->l1_size),
1840 .l1_table_offset = cpu_to_be64(s->l1_table_offset),
1841 .refcount_table_offset = cpu_to_be64(s->refcount_table_offset),
1842 .refcount_table_clusters = cpu_to_be32(refcount_table_clusters),
1843 .nb_snapshots = cpu_to_be32(s->nb_snapshots),
1844 .snapshots_offset = cpu_to_be64(s->snapshots_offset),
1846 /* Version 3 fields */
1847 .incompatible_features = cpu_to_be64(s->incompatible_features),
1848 .compatible_features = cpu_to_be64(s->compatible_features),
1849 .autoclear_features = cpu_to_be64(s->autoclear_features),
1850 .refcount_order = cpu_to_be32(s->refcount_order),
1851 .header_length = cpu_to_be32(header_length),
1854 /* For older versions, write a shorter header */
1855 switch (s->qcow_version) {
1856 case 2:
1857 ret = offsetof(QCowHeader, incompatible_features);
1858 break;
1859 case 3:
1860 ret = sizeof(*header);
1861 break;
1862 default:
1863 ret = -EINVAL;
1864 goto fail;
1867 buf += ret;
1868 buflen -= ret;
1869 memset(buf, 0, buflen);
1871 /* Preserve any unknown field in the header */
1872 if (s->unknown_header_fields_size) {
1873 if (buflen < s->unknown_header_fields_size) {
1874 ret = -ENOSPC;
1875 goto fail;
1878 memcpy(buf, s->unknown_header_fields, s->unknown_header_fields_size);
1879 buf += s->unknown_header_fields_size;
1880 buflen -= s->unknown_header_fields_size;
1883 /* Backing file format header extension */
1884 if (s->image_backing_format) {
1885 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BACKING_FORMAT,
1886 s->image_backing_format,
1887 strlen(s->image_backing_format),
1888 buflen);
1889 if (ret < 0) {
1890 goto fail;
1893 buf += ret;
1894 buflen -= ret;
1897 /* Feature table */
1898 if (s->qcow_version >= 3) {
1899 Qcow2Feature features[] = {
1901 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
1902 .bit = QCOW2_INCOMPAT_DIRTY_BITNR,
1903 .name = "dirty bit",
1906 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
1907 .bit = QCOW2_INCOMPAT_CORRUPT_BITNR,
1908 .name = "corrupt bit",
1911 .type = QCOW2_FEAT_TYPE_COMPATIBLE,
1912 .bit = QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR,
1913 .name = "lazy refcounts",
1917 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_FEATURE_TABLE,
1918 features, sizeof(features), buflen);
1919 if (ret < 0) {
1920 goto fail;
1922 buf += ret;
1923 buflen -= ret;
1926 /* Keep unknown header extensions */
1927 QLIST_FOREACH(uext, &s->unknown_header_ext, next) {
1928 ret = header_ext_add(buf, uext->magic, uext->data, uext->len, buflen);
1929 if (ret < 0) {
1930 goto fail;
1933 buf += ret;
1934 buflen -= ret;
1937 /* End of header extensions */
1938 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_END, NULL, 0, buflen);
1939 if (ret < 0) {
1940 goto fail;
1943 buf += ret;
1944 buflen -= ret;
1946 /* Backing file name */
1947 if (s->image_backing_file) {
1948 size_t backing_file_len = strlen(s->image_backing_file);
1950 if (buflen < backing_file_len) {
1951 ret = -ENOSPC;
1952 goto fail;
1955 /* Using strncpy is ok here, since buf is not NUL-terminated. */
1956 strncpy(buf, s->image_backing_file, buflen);
1958 header->backing_file_offset = cpu_to_be64(buf - ((char*) header));
1959 header->backing_file_size = cpu_to_be32(backing_file_len);
1962 /* Write the new header */
1963 ret = bdrv_pwrite(bs->file->bs, 0, header, s->cluster_size);
1964 if (ret < 0) {
1965 goto fail;
1968 ret = 0;
1969 fail:
1970 qemu_vfree(header);
1971 return ret;
1974 static int qcow2_change_backing_file(BlockDriverState *bs,
1975 const char *backing_file, const char *backing_fmt)
1977 BDRVQcow2State *s = bs->opaque;
1979 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
1980 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
1982 g_free(s->image_backing_file);
1983 g_free(s->image_backing_format);
1985 s->image_backing_file = backing_file ? g_strdup(bs->backing_file) : NULL;
1986 s->image_backing_format = backing_fmt ? g_strdup(bs->backing_format) : NULL;
1988 return qcow2_update_header(bs);
1991 static int preallocate(BlockDriverState *bs)
1993 uint64_t nb_sectors;
1994 uint64_t offset;
1995 uint64_t host_offset = 0;
1996 int num;
1997 int ret;
1998 QCowL2Meta *meta;
2000 nb_sectors = bdrv_nb_sectors(bs);
2001 offset = 0;
2003 while (nb_sectors) {
2004 num = MIN(nb_sectors, INT_MAX >> BDRV_SECTOR_BITS);
2005 ret = qcow2_alloc_cluster_offset(bs, offset, &num,
2006 &host_offset, &meta);
2007 if (ret < 0) {
2008 return ret;
2011 while (meta) {
2012 QCowL2Meta *next = meta->next;
2014 ret = qcow2_alloc_cluster_link_l2(bs, meta);
2015 if (ret < 0) {
2016 qcow2_free_any_clusters(bs, meta->alloc_offset,
2017 meta->nb_clusters, QCOW2_DISCARD_NEVER);
2018 return ret;
2021 /* There are no dependent requests, but we need to remove our
2022 * request from the list of in-flight requests */
2023 QLIST_REMOVE(meta, next_in_flight);
2025 g_free(meta);
2026 meta = next;
2029 /* TODO Preallocate data if requested */
2031 nb_sectors -= num;
2032 offset += num << BDRV_SECTOR_BITS;
2036 * It is expected that the image file is large enough to actually contain
2037 * all of the allocated clusters (otherwise we get failing reads after
2038 * EOF). Extend the image to the last allocated sector.
2040 if (host_offset != 0) {
2041 uint8_t buf[BDRV_SECTOR_SIZE];
2042 memset(buf, 0, BDRV_SECTOR_SIZE);
2043 ret = bdrv_write(bs->file->bs,
2044 (host_offset >> BDRV_SECTOR_BITS) + num - 1,
2045 buf, 1);
2046 if (ret < 0) {
2047 return ret;
2051 return 0;
2054 static int qcow2_create2(const char *filename, int64_t total_size,
2055 const char *backing_file, const char *backing_format,
2056 int flags, size_t cluster_size, PreallocMode prealloc,
2057 QemuOpts *opts, int version, int refcount_order,
2058 Error **errp)
2060 int cluster_bits;
2061 QDict *options;
2063 /* Calculate cluster_bits */
2064 cluster_bits = ctz32(cluster_size);
2065 if (cluster_bits < MIN_CLUSTER_BITS || cluster_bits > MAX_CLUSTER_BITS ||
2066 (1 << cluster_bits) != cluster_size)
2068 error_setg(errp, "Cluster size must be a power of two between %d and "
2069 "%dk", 1 << MIN_CLUSTER_BITS, 1 << (MAX_CLUSTER_BITS - 10));
2070 return -EINVAL;
2074 * Open the image file and write a minimal qcow2 header.
2076 * We keep things simple and start with a zero-sized image. We also
2077 * do without refcount blocks or a L1 table for now. We'll fix the
2078 * inconsistency later.
2080 * We do need a refcount table because growing the refcount table means
2081 * allocating two new refcount blocks - the seconds of which would be at
2082 * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
2083 * size for any qcow2 image.
2085 BlockDriverState* bs;
2086 QCowHeader *header;
2087 uint64_t* refcount_table;
2088 Error *local_err = NULL;
2089 int ret;
2091 if (prealloc == PREALLOC_MODE_FULL || prealloc == PREALLOC_MODE_FALLOC) {
2092 /* Note: The following calculation does not need to be exact; if it is a
2093 * bit off, either some bytes will be "leaked" (which is fine) or we
2094 * will need to increase the file size by some bytes (which is fine,
2095 * too, as long as the bulk is allocated here). Therefore, using
2096 * floating point arithmetic is fine. */
2097 int64_t meta_size = 0;
2098 uint64_t nreftablee, nrefblocke, nl1e, nl2e;
2099 int64_t aligned_total_size = align_offset(total_size, cluster_size);
2100 int refblock_bits, refblock_size;
2101 /* refcount entry size in bytes */
2102 double rces = (1 << refcount_order) / 8.;
2104 /* see qcow2_open() */
2105 refblock_bits = cluster_bits - (refcount_order - 3);
2106 refblock_size = 1 << refblock_bits;
2108 /* header: 1 cluster */
2109 meta_size += cluster_size;
2111 /* total size of L2 tables */
2112 nl2e = aligned_total_size / cluster_size;
2113 nl2e = align_offset(nl2e, cluster_size / sizeof(uint64_t));
2114 meta_size += nl2e * sizeof(uint64_t);
2116 /* total size of L1 tables */
2117 nl1e = nl2e * sizeof(uint64_t) / cluster_size;
2118 nl1e = align_offset(nl1e, cluster_size / sizeof(uint64_t));
2119 meta_size += nl1e * sizeof(uint64_t);
2121 /* total size of refcount blocks
2123 * note: every host cluster is reference-counted, including metadata
2124 * (even refcount blocks are recursively included).
2125 * Let:
2126 * a = total_size (this is the guest disk size)
2127 * m = meta size not including refcount blocks and refcount tables
2128 * c = cluster size
2129 * y1 = number of refcount blocks entries
2130 * y2 = meta size including everything
2131 * rces = refcount entry size in bytes
2132 * then,
2133 * y1 = (y2 + a)/c
2134 * y2 = y1 * rces + y1 * rces * sizeof(u64) / c + m
2135 * we can get y1:
2136 * y1 = (a + m) / (c - rces - rces * sizeof(u64) / c)
2138 nrefblocke = (aligned_total_size + meta_size + cluster_size)
2139 / (cluster_size - rces - rces * sizeof(uint64_t)
2140 / cluster_size);
2141 meta_size += DIV_ROUND_UP(nrefblocke, refblock_size) * cluster_size;
2143 /* total size of refcount tables */
2144 nreftablee = nrefblocke / refblock_size;
2145 nreftablee = align_offset(nreftablee, cluster_size / sizeof(uint64_t));
2146 meta_size += nreftablee * sizeof(uint64_t);
2148 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
2149 aligned_total_size + meta_size, &error_abort);
2150 qemu_opt_set(opts, BLOCK_OPT_PREALLOC, PreallocMode_lookup[prealloc],
2151 &error_abort);
2154 ret = bdrv_create_file(filename, opts, &local_err);
2155 if (ret < 0) {
2156 error_propagate(errp, local_err);
2157 return ret;
2160 bs = NULL;
2161 ret = bdrv_open(&bs, filename, NULL, NULL, BDRV_O_RDWR | BDRV_O_PROTOCOL,
2162 &local_err);
2163 if (ret < 0) {
2164 error_propagate(errp, local_err);
2165 return ret;
2168 /* Write the header */
2169 QEMU_BUILD_BUG_ON((1 << MIN_CLUSTER_BITS) < sizeof(*header));
2170 header = g_malloc0(cluster_size);
2171 *header = (QCowHeader) {
2172 .magic = cpu_to_be32(QCOW_MAGIC),
2173 .version = cpu_to_be32(version),
2174 .cluster_bits = cpu_to_be32(cluster_bits),
2175 .size = cpu_to_be64(0),
2176 .l1_table_offset = cpu_to_be64(0),
2177 .l1_size = cpu_to_be32(0),
2178 .refcount_table_offset = cpu_to_be64(cluster_size),
2179 .refcount_table_clusters = cpu_to_be32(1),
2180 .refcount_order = cpu_to_be32(refcount_order),
2181 .header_length = cpu_to_be32(sizeof(*header)),
2184 if (flags & BLOCK_FLAG_ENCRYPT) {
2185 header->crypt_method = cpu_to_be32(QCOW_CRYPT_AES);
2186 } else {
2187 header->crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
2190 if (flags & BLOCK_FLAG_LAZY_REFCOUNTS) {
2191 header->compatible_features |=
2192 cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS);
2195 ret = bdrv_pwrite(bs, 0, header, cluster_size);
2196 g_free(header);
2197 if (ret < 0) {
2198 error_setg_errno(errp, -ret, "Could not write qcow2 header");
2199 goto out;
2202 /* Write a refcount table with one refcount block */
2203 refcount_table = g_malloc0(2 * cluster_size);
2204 refcount_table[0] = cpu_to_be64(2 * cluster_size);
2205 ret = bdrv_pwrite(bs, cluster_size, refcount_table, 2 * cluster_size);
2206 g_free(refcount_table);
2208 if (ret < 0) {
2209 error_setg_errno(errp, -ret, "Could not write refcount table");
2210 goto out;
2213 bdrv_unref(bs);
2214 bs = NULL;
2217 * And now open the image and make it consistent first (i.e. increase the
2218 * refcount of the cluster that is occupied by the header and the refcount
2219 * table)
2221 options = qdict_new();
2222 qdict_put(options, "driver", qstring_from_str("qcow2"));
2223 ret = bdrv_open(&bs, filename, NULL, options,
2224 BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_NO_FLUSH,
2225 &local_err);
2226 if (ret < 0) {
2227 error_propagate(errp, local_err);
2228 goto out;
2231 ret = qcow2_alloc_clusters(bs, 3 * cluster_size);
2232 if (ret < 0) {
2233 error_setg_errno(errp, -ret, "Could not allocate clusters for qcow2 "
2234 "header and refcount table");
2235 goto out;
2237 } else if (ret != 0) {
2238 error_report("Huh, first cluster in empty image is already in use?");
2239 abort();
2242 /* Create a full header (including things like feature table) */
2243 ret = qcow2_update_header(bs);
2244 if (ret < 0) {
2245 error_setg_errno(errp, -ret, "Could not update qcow2 header");
2246 goto out;
2249 /* Okay, now that we have a valid image, let's give it the right size */
2250 ret = bdrv_truncate(bs, total_size);
2251 if (ret < 0) {
2252 error_setg_errno(errp, -ret, "Could not resize image");
2253 goto out;
2256 /* Want a backing file? There you go.*/
2257 if (backing_file) {
2258 ret = bdrv_change_backing_file(bs, backing_file, backing_format);
2259 if (ret < 0) {
2260 error_setg_errno(errp, -ret, "Could not assign backing file '%s' "
2261 "with format '%s'", backing_file, backing_format);
2262 goto out;
2266 /* And if we're supposed to preallocate metadata, do that now */
2267 if (prealloc != PREALLOC_MODE_OFF) {
2268 BDRVQcow2State *s = bs->opaque;
2269 qemu_co_mutex_lock(&s->lock);
2270 ret = preallocate(bs);
2271 qemu_co_mutex_unlock(&s->lock);
2272 if (ret < 0) {
2273 error_setg_errno(errp, -ret, "Could not preallocate metadata");
2274 goto out;
2278 bdrv_unref(bs);
2279 bs = NULL;
2281 /* Reopen the image without BDRV_O_NO_FLUSH to flush it before returning */
2282 options = qdict_new();
2283 qdict_put(options, "driver", qstring_from_str("qcow2"));
2284 ret = bdrv_open(&bs, filename, NULL, options,
2285 BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_NO_BACKING,
2286 &local_err);
2287 if (local_err) {
2288 error_propagate(errp, local_err);
2289 goto out;
2292 ret = 0;
2293 out:
2294 if (bs) {
2295 bdrv_unref(bs);
2297 return ret;
2300 static int qcow2_create(const char *filename, QemuOpts *opts, Error **errp)
2302 char *backing_file = NULL;
2303 char *backing_fmt = NULL;
2304 char *buf = NULL;
2305 uint64_t size = 0;
2306 int flags = 0;
2307 size_t cluster_size = DEFAULT_CLUSTER_SIZE;
2308 PreallocMode prealloc;
2309 int version = 3;
2310 uint64_t refcount_bits = 16;
2311 int refcount_order;
2312 Error *local_err = NULL;
2313 int ret;
2315 /* Read out options */
2316 size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
2317 BDRV_SECTOR_SIZE);
2318 backing_file = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
2319 backing_fmt = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FMT);
2320 if (qemu_opt_get_bool_del(opts, BLOCK_OPT_ENCRYPT, false)) {
2321 flags |= BLOCK_FLAG_ENCRYPT;
2323 cluster_size = qemu_opt_get_size_del(opts, BLOCK_OPT_CLUSTER_SIZE,
2324 DEFAULT_CLUSTER_SIZE);
2325 buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
2326 prealloc = qapi_enum_parse(PreallocMode_lookup, buf,
2327 PREALLOC_MODE__MAX, PREALLOC_MODE_OFF,
2328 &local_err);
2329 if (local_err) {
2330 error_propagate(errp, local_err);
2331 ret = -EINVAL;
2332 goto finish;
2334 g_free(buf);
2335 buf = qemu_opt_get_del(opts, BLOCK_OPT_COMPAT_LEVEL);
2336 if (!buf) {
2337 /* keep the default */
2338 } else if (!strcmp(buf, "0.10")) {
2339 version = 2;
2340 } else if (!strcmp(buf, "1.1")) {
2341 version = 3;
2342 } else {
2343 error_setg(errp, "Invalid compatibility level: '%s'", buf);
2344 ret = -EINVAL;
2345 goto finish;
2348 if (qemu_opt_get_bool_del(opts, BLOCK_OPT_LAZY_REFCOUNTS, false)) {
2349 flags |= BLOCK_FLAG_LAZY_REFCOUNTS;
2352 if (backing_file && prealloc != PREALLOC_MODE_OFF) {
2353 error_setg(errp, "Backing file and preallocation cannot be used at "
2354 "the same time");
2355 ret = -EINVAL;
2356 goto finish;
2359 if (version < 3 && (flags & BLOCK_FLAG_LAZY_REFCOUNTS)) {
2360 error_setg(errp, "Lazy refcounts only supported with compatibility "
2361 "level 1.1 and above (use compat=1.1 or greater)");
2362 ret = -EINVAL;
2363 goto finish;
2366 refcount_bits = qemu_opt_get_number_del(opts, BLOCK_OPT_REFCOUNT_BITS,
2367 refcount_bits);
2368 if (refcount_bits > 64 || !is_power_of_2(refcount_bits)) {
2369 error_setg(errp, "Refcount width must be a power of two and may not "
2370 "exceed 64 bits");
2371 ret = -EINVAL;
2372 goto finish;
2375 if (version < 3 && refcount_bits != 16) {
2376 error_setg(errp, "Different refcount widths than 16 bits require "
2377 "compatibility level 1.1 or above (use compat=1.1 or "
2378 "greater)");
2379 ret = -EINVAL;
2380 goto finish;
2383 refcount_order = ctz32(refcount_bits);
2385 ret = qcow2_create2(filename, size, backing_file, backing_fmt, flags,
2386 cluster_size, prealloc, opts, version, refcount_order,
2387 &local_err);
2388 if (local_err) {
2389 error_propagate(errp, local_err);
2392 finish:
2393 g_free(backing_file);
2394 g_free(backing_fmt);
2395 g_free(buf);
2396 return ret;
2399 static coroutine_fn int qcow2_co_write_zeroes(BlockDriverState *bs,
2400 int64_t sector_num, int nb_sectors, BdrvRequestFlags flags)
2402 int ret;
2403 BDRVQcow2State *s = bs->opaque;
2405 /* Emulate misaligned zero writes */
2406 if (sector_num % s->cluster_sectors || nb_sectors % s->cluster_sectors) {
2407 return -ENOTSUP;
2410 /* Whatever is left can use real zero clusters */
2411 qemu_co_mutex_lock(&s->lock);
2412 ret = qcow2_zero_clusters(bs, sector_num << BDRV_SECTOR_BITS,
2413 nb_sectors);
2414 qemu_co_mutex_unlock(&s->lock);
2416 return ret;
2419 static coroutine_fn int qcow2_co_discard(BlockDriverState *bs,
2420 int64_t sector_num, int nb_sectors)
2422 int ret;
2423 BDRVQcow2State *s = bs->opaque;
2425 qemu_co_mutex_lock(&s->lock);
2426 ret = qcow2_discard_clusters(bs, sector_num << BDRV_SECTOR_BITS,
2427 nb_sectors, QCOW2_DISCARD_REQUEST, false);
2428 qemu_co_mutex_unlock(&s->lock);
2429 return ret;
2432 static int qcow2_truncate(BlockDriverState *bs, int64_t offset)
2434 BDRVQcow2State *s = bs->opaque;
2435 int64_t new_l1_size;
2436 int ret;
2438 if (offset & 511) {
2439 error_report("The new size must be a multiple of 512");
2440 return -EINVAL;
2443 /* cannot proceed if image has snapshots */
2444 if (s->nb_snapshots) {
2445 error_report("Can't resize an image which has snapshots");
2446 return -ENOTSUP;
2449 /* shrinking is currently not supported */
2450 if (offset < bs->total_sectors * 512) {
2451 error_report("qcow2 doesn't support shrinking images yet");
2452 return -ENOTSUP;
2455 new_l1_size = size_to_l1(s, offset);
2456 ret = qcow2_grow_l1_table(bs, new_l1_size, true);
2457 if (ret < 0) {
2458 return ret;
2461 /* write updated header.size */
2462 offset = cpu_to_be64(offset);
2463 ret = bdrv_pwrite_sync(bs->file->bs, offsetof(QCowHeader, size),
2464 &offset, sizeof(uint64_t));
2465 if (ret < 0) {
2466 return ret;
2469 s->l1_vm_state_index = new_l1_size;
2470 return 0;
2473 /* XXX: put compressed sectors first, then all the cluster aligned
2474 tables to avoid losing bytes in alignment */
2475 static int qcow2_write_compressed(BlockDriverState *bs, int64_t sector_num,
2476 const uint8_t *buf, int nb_sectors)
2478 BDRVQcow2State *s = bs->opaque;
2479 z_stream strm;
2480 int ret, out_len;
2481 uint8_t *out_buf;
2482 uint64_t cluster_offset;
2484 if (nb_sectors == 0) {
2485 /* align end of file to a sector boundary to ease reading with
2486 sector based I/Os */
2487 cluster_offset = bdrv_getlength(bs->file->bs);
2488 return bdrv_truncate(bs->file->bs, cluster_offset);
2491 if (nb_sectors != s->cluster_sectors) {
2492 ret = -EINVAL;
2494 /* Zero-pad last write if image size is not cluster aligned */
2495 if (sector_num + nb_sectors == bs->total_sectors &&
2496 nb_sectors < s->cluster_sectors) {
2497 uint8_t *pad_buf = qemu_blockalign(bs, s->cluster_size);
2498 memset(pad_buf, 0, s->cluster_size);
2499 memcpy(pad_buf, buf, nb_sectors * BDRV_SECTOR_SIZE);
2500 ret = qcow2_write_compressed(bs, sector_num,
2501 pad_buf, s->cluster_sectors);
2502 qemu_vfree(pad_buf);
2504 return ret;
2507 out_buf = g_malloc(s->cluster_size + (s->cluster_size / 1000) + 128);
2509 /* best compression, small window, no zlib header */
2510 memset(&strm, 0, sizeof(strm));
2511 ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
2512 Z_DEFLATED, -12,
2513 9, Z_DEFAULT_STRATEGY);
2514 if (ret != 0) {
2515 ret = -EINVAL;
2516 goto fail;
2519 strm.avail_in = s->cluster_size;
2520 strm.next_in = (uint8_t *)buf;
2521 strm.avail_out = s->cluster_size;
2522 strm.next_out = out_buf;
2524 ret = deflate(&strm, Z_FINISH);
2525 if (ret != Z_STREAM_END && ret != Z_OK) {
2526 deflateEnd(&strm);
2527 ret = -EINVAL;
2528 goto fail;
2530 out_len = strm.next_out - out_buf;
2532 deflateEnd(&strm);
2534 if (ret != Z_STREAM_END || out_len >= s->cluster_size) {
2535 /* could not compress: write normal cluster */
2536 ret = bdrv_write(bs, sector_num, buf, s->cluster_sectors);
2537 if (ret < 0) {
2538 goto fail;
2540 } else {
2541 cluster_offset = qcow2_alloc_compressed_cluster_offset(bs,
2542 sector_num << 9, out_len);
2543 if (!cluster_offset) {
2544 ret = -EIO;
2545 goto fail;
2547 cluster_offset &= s->cluster_offset_mask;
2549 ret = qcow2_pre_write_overlap_check(bs, 0, cluster_offset, out_len);
2550 if (ret < 0) {
2551 goto fail;
2554 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_COMPRESSED);
2555 ret = bdrv_pwrite(bs->file->bs, cluster_offset, out_buf, out_len);
2556 if (ret < 0) {
2557 goto fail;
2561 ret = 0;
2562 fail:
2563 g_free(out_buf);
2564 return ret;
2567 static int make_completely_empty(BlockDriverState *bs)
2569 BDRVQcow2State *s = bs->opaque;
2570 int ret, l1_clusters;
2571 int64_t offset;
2572 uint64_t *new_reftable = NULL;
2573 uint64_t rt_entry, l1_size2;
2574 struct {
2575 uint64_t l1_offset;
2576 uint64_t reftable_offset;
2577 uint32_t reftable_clusters;
2578 } QEMU_PACKED l1_ofs_rt_ofs_cls;
2580 ret = qcow2_cache_empty(bs, s->l2_table_cache);
2581 if (ret < 0) {
2582 goto fail;
2585 ret = qcow2_cache_empty(bs, s->refcount_block_cache);
2586 if (ret < 0) {
2587 goto fail;
2590 /* Refcounts will be broken utterly */
2591 ret = qcow2_mark_dirty(bs);
2592 if (ret < 0) {
2593 goto fail;
2596 BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
2598 l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / sizeof(uint64_t));
2599 l1_size2 = (uint64_t)s->l1_size * sizeof(uint64_t);
2601 /* After this call, neither the in-memory nor the on-disk refcount
2602 * information accurately describe the actual references */
2604 ret = bdrv_write_zeroes(bs->file->bs, s->l1_table_offset / BDRV_SECTOR_SIZE,
2605 l1_clusters * s->cluster_sectors, 0);
2606 if (ret < 0) {
2607 goto fail_broken_refcounts;
2609 memset(s->l1_table, 0, l1_size2);
2611 BLKDBG_EVENT(bs->file, BLKDBG_EMPTY_IMAGE_PREPARE);
2613 /* Overwrite enough clusters at the beginning of the sectors to place
2614 * the refcount table, a refcount block and the L1 table in; this may
2615 * overwrite parts of the existing refcount and L1 table, which is not
2616 * an issue because the dirty flag is set, complete data loss is in fact
2617 * desired and partial data loss is consequently fine as well */
2618 ret = bdrv_write_zeroes(bs->file->bs, s->cluster_size / BDRV_SECTOR_SIZE,
2619 (2 + l1_clusters) * s->cluster_size /
2620 BDRV_SECTOR_SIZE, 0);
2621 /* This call (even if it failed overall) may have overwritten on-disk
2622 * refcount structures; in that case, the in-memory refcount information
2623 * will probably differ from the on-disk information which makes the BDS
2624 * unusable */
2625 if (ret < 0) {
2626 goto fail_broken_refcounts;
2629 BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
2630 BLKDBG_EVENT(bs->file, BLKDBG_REFTABLE_UPDATE);
2632 /* "Create" an empty reftable (one cluster) directly after the image
2633 * header and an empty L1 table three clusters after the image header;
2634 * the cluster between those two will be used as the first refblock */
2635 cpu_to_be64w(&l1_ofs_rt_ofs_cls.l1_offset, 3 * s->cluster_size);
2636 cpu_to_be64w(&l1_ofs_rt_ofs_cls.reftable_offset, s->cluster_size);
2637 cpu_to_be32w(&l1_ofs_rt_ofs_cls.reftable_clusters, 1);
2638 ret = bdrv_pwrite_sync(bs->file->bs, offsetof(QCowHeader, l1_table_offset),
2639 &l1_ofs_rt_ofs_cls, sizeof(l1_ofs_rt_ofs_cls));
2640 if (ret < 0) {
2641 goto fail_broken_refcounts;
2644 s->l1_table_offset = 3 * s->cluster_size;
2646 new_reftable = g_try_new0(uint64_t, s->cluster_size / sizeof(uint64_t));
2647 if (!new_reftable) {
2648 ret = -ENOMEM;
2649 goto fail_broken_refcounts;
2652 s->refcount_table_offset = s->cluster_size;
2653 s->refcount_table_size = s->cluster_size / sizeof(uint64_t);
2655 g_free(s->refcount_table);
2656 s->refcount_table = new_reftable;
2657 new_reftable = NULL;
2659 /* Now the in-memory refcount information again corresponds to the on-disk
2660 * information (reftable is empty and no refblocks (the refblock cache is
2661 * empty)); however, this means some clusters (e.g. the image header) are
2662 * referenced, but not refcounted, but the normal qcow2 code assumes that
2663 * the in-memory information is always correct */
2665 BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_ALLOC);
2667 /* Enter the first refblock into the reftable */
2668 rt_entry = cpu_to_be64(2 * s->cluster_size);
2669 ret = bdrv_pwrite_sync(bs->file->bs, s->cluster_size,
2670 &rt_entry, sizeof(rt_entry));
2671 if (ret < 0) {
2672 goto fail_broken_refcounts;
2674 s->refcount_table[0] = 2 * s->cluster_size;
2676 s->free_cluster_index = 0;
2677 assert(3 + l1_clusters <= s->refcount_block_size);
2678 offset = qcow2_alloc_clusters(bs, 3 * s->cluster_size + l1_size2);
2679 if (offset < 0) {
2680 ret = offset;
2681 goto fail_broken_refcounts;
2682 } else if (offset > 0) {
2683 error_report("First cluster in emptied image is in use");
2684 abort();
2687 /* Now finally the in-memory information corresponds to the on-disk
2688 * structures and is correct */
2689 ret = qcow2_mark_clean(bs);
2690 if (ret < 0) {
2691 goto fail;
2694 ret = bdrv_truncate(bs->file->bs, (3 + l1_clusters) * s->cluster_size);
2695 if (ret < 0) {
2696 goto fail;
2699 return 0;
2701 fail_broken_refcounts:
2702 /* The BDS is unusable at this point. If we wanted to make it usable, we
2703 * would have to call qcow2_refcount_close(), qcow2_refcount_init(),
2704 * qcow2_check_refcounts(), qcow2_refcount_close() and qcow2_refcount_init()
2705 * again. However, because the functions which could have caused this error
2706 * path to be taken are used by those functions as well, it's very likely
2707 * that that sequence will fail as well. Therefore, just eject the BDS. */
2708 bs->drv = NULL;
2710 fail:
2711 g_free(new_reftable);
2712 return ret;
2715 static int qcow2_make_empty(BlockDriverState *bs)
2717 BDRVQcow2State *s = bs->opaque;
2718 uint64_t start_sector;
2719 int sector_step = INT_MAX / BDRV_SECTOR_SIZE;
2720 int l1_clusters, ret = 0;
2722 l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / sizeof(uint64_t));
2724 if (s->qcow_version >= 3 && !s->snapshots &&
2725 3 + l1_clusters <= s->refcount_block_size) {
2726 /* The following function only works for qcow2 v3 images (it requires
2727 * the dirty flag) and only as long as there are no snapshots (because
2728 * it completely empties the image). Furthermore, the L1 table and three
2729 * additional clusters (image header, refcount table, one refcount
2730 * block) have to fit inside one refcount block. */
2731 return make_completely_empty(bs);
2734 /* This fallback code simply discards every active cluster; this is slow,
2735 * but works in all cases */
2736 for (start_sector = 0; start_sector < bs->total_sectors;
2737 start_sector += sector_step)
2739 /* As this function is generally used after committing an external
2740 * snapshot, QCOW2_DISCARD_SNAPSHOT seems appropriate. Also, the
2741 * default action for this kind of discard is to pass the discard,
2742 * which will ideally result in an actually smaller image file, as
2743 * is probably desired. */
2744 ret = qcow2_discard_clusters(bs, start_sector * BDRV_SECTOR_SIZE,
2745 MIN(sector_step,
2746 bs->total_sectors - start_sector),
2747 QCOW2_DISCARD_SNAPSHOT, true);
2748 if (ret < 0) {
2749 break;
2753 return ret;
2756 static coroutine_fn int qcow2_co_flush_to_os(BlockDriverState *bs)
2758 BDRVQcow2State *s = bs->opaque;
2759 int ret;
2761 qemu_co_mutex_lock(&s->lock);
2762 ret = qcow2_cache_flush(bs, s->l2_table_cache);
2763 if (ret < 0) {
2764 qemu_co_mutex_unlock(&s->lock);
2765 return ret;
2768 if (qcow2_need_accurate_refcounts(s)) {
2769 ret = qcow2_cache_flush(bs, s->refcount_block_cache);
2770 if (ret < 0) {
2771 qemu_co_mutex_unlock(&s->lock);
2772 return ret;
2775 qemu_co_mutex_unlock(&s->lock);
2777 return 0;
2780 static int qcow2_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
2782 BDRVQcow2State *s = bs->opaque;
2783 bdi->unallocated_blocks_are_zero = true;
2784 bdi->can_write_zeroes_with_unmap = (s->qcow_version >= 3);
2785 bdi->cluster_size = s->cluster_size;
2786 bdi->vm_state_offset = qcow2_vm_state_offset(s);
2787 return 0;
2790 static ImageInfoSpecific *qcow2_get_specific_info(BlockDriverState *bs)
2792 BDRVQcow2State *s = bs->opaque;
2793 ImageInfoSpecific *spec_info = g_new(ImageInfoSpecific, 1);
2795 *spec_info = (ImageInfoSpecific){
2796 .type = IMAGE_INFO_SPECIFIC_KIND_QCOW2,
2797 .u.qcow2 = g_new(ImageInfoSpecificQCow2, 1),
2799 if (s->qcow_version == 2) {
2800 *spec_info->u.qcow2 = (ImageInfoSpecificQCow2){
2801 .compat = g_strdup("0.10"),
2802 .refcount_bits = s->refcount_bits,
2804 } else if (s->qcow_version == 3) {
2805 *spec_info->u.qcow2 = (ImageInfoSpecificQCow2){
2806 .compat = g_strdup("1.1"),
2807 .lazy_refcounts = s->compatible_features &
2808 QCOW2_COMPAT_LAZY_REFCOUNTS,
2809 .has_lazy_refcounts = true,
2810 .corrupt = s->incompatible_features &
2811 QCOW2_INCOMPAT_CORRUPT,
2812 .has_corrupt = true,
2813 .refcount_bits = s->refcount_bits,
2815 } else {
2816 /* if this assertion fails, this probably means a new version was
2817 * added without having it covered here */
2818 assert(false);
2821 return spec_info;
2824 #if 0
2825 static void dump_refcounts(BlockDriverState *bs)
2827 BDRVQcow2State *s = bs->opaque;
2828 int64_t nb_clusters, k, k1, size;
2829 int refcount;
2831 size = bdrv_getlength(bs->file->bs);
2832 nb_clusters = size_to_clusters(s, size);
2833 for(k = 0; k < nb_clusters;) {
2834 k1 = k;
2835 refcount = get_refcount(bs, k);
2836 k++;
2837 while (k < nb_clusters && get_refcount(bs, k) == refcount)
2838 k++;
2839 printf("%" PRId64 ": refcount=%d nb=%" PRId64 "\n", k, refcount,
2840 k - k1);
2843 #endif
2845 static int qcow2_save_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
2846 int64_t pos)
2848 BDRVQcow2State *s = bs->opaque;
2849 int64_t total_sectors = bs->total_sectors;
2850 bool zero_beyond_eof = bs->zero_beyond_eof;
2851 int ret;
2853 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_SAVE);
2854 bs->zero_beyond_eof = false;
2855 ret = bdrv_pwritev(bs, qcow2_vm_state_offset(s) + pos, qiov);
2856 bs->zero_beyond_eof = zero_beyond_eof;
2858 /* bdrv_co_do_writev will have increased the total_sectors value to include
2859 * the VM state - the VM state is however not an actual part of the block
2860 * device, therefore, we need to restore the old value. */
2861 bs->total_sectors = total_sectors;
2863 return ret;
2866 static int qcow2_load_vmstate(BlockDriverState *bs, uint8_t *buf,
2867 int64_t pos, int size)
2869 BDRVQcow2State *s = bs->opaque;
2870 bool zero_beyond_eof = bs->zero_beyond_eof;
2871 int ret;
2873 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_LOAD);
2874 bs->zero_beyond_eof = false;
2875 ret = bdrv_pread(bs, qcow2_vm_state_offset(s) + pos, buf, size);
2876 bs->zero_beyond_eof = zero_beyond_eof;
2878 return ret;
2882 * Downgrades an image's version. To achieve this, any incompatible features
2883 * have to be removed.
2885 static int qcow2_downgrade(BlockDriverState *bs, int target_version,
2886 BlockDriverAmendStatusCB *status_cb, void *cb_opaque)
2888 BDRVQcow2State *s = bs->opaque;
2889 int current_version = s->qcow_version;
2890 int ret;
2892 if (target_version == current_version) {
2893 return 0;
2894 } else if (target_version > current_version) {
2895 return -EINVAL;
2896 } else if (target_version != 2) {
2897 return -EINVAL;
2900 if (s->refcount_order != 4) {
2901 error_report("compat=0.10 requires refcount_bits=16");
2902 return -ENOTSUP;
2905 /* clear incompatible features */
2906 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
2907 ret = qcow2_mark_clean(bs);
2908 if (ret < 0) {
2909 return ret;
2913 /* with QCOW2_INCOMPAT_CORRUPT, it is pretty much impossible to get here in
2914 * the first place; if that happens nonetheless, returning -ENOTSUP is the
2915 * best thing to do anyway */
2917 if (s->incompatible_features) {
2918 return -ENOTSUP;
2921 /* since we can ignore compatible features, we can set them to 0 as well */
2922 s->compatible_features = 0;
2923 /* if lazy refcounts have been used, they have already been fixed through
2924 * clearing the dirty flag */
2926 /* clearing autoclear features is trivial */
2927 s->autoclear_features = 0;
2929 ret = qcow2_expand_zero_clusters(bs, status_cb, cb_opaque);
2930 if (ret < 0) {
2931 return ret;
2934 s->qcow_version = target_version;
2935 ret = qcow2_update_header(bs);
2936 if (ret < 0) {
2937 s->qcow_version = current_version;
2938 return ret;
2940 return 0;
2943 typedef enum Qcow2AmendOperation {
2944 /* This is the value Qcow2AmendHelperCBInfo::last_operation will be
2945 * statically initialized to so that the helper CB can discern the first
2946 * invocation from an operation change */
2947 QCOW2_NO_OPERATION = 0,
2949 QCOW2_CHANGING_REFCOUNT_ORDER,
2950 QCOW2_DOWNGRADING,
2951 } Qcow2AmendOperation;
2953 typedef struct Qcow2AmendHelperCBInfo {
2954 /* The code coordinating the amend operations should only modify
2955 * these four fields; the rest will be managed by the CB */
2956 BlockDriverAmendStatusCB *original_status_cb;
2957 void *original_cb_opaque;
2959 Qcow2AmendOperation current_operation;
2961 /* Total number of operations to perform (only set once) */
2962 int total_operations;
2964 /* The following fields are managed by the CB */
2966 /* Number of operations completed */
2967 int operations_completed;
2969 /* Cumulative offset of all completed operations */
2970 int64_t offset_completed;
2972 Qcow2AmendOperation last_operation;
2973 int64_t last_work_size;
2974 } Qcow2AmendHelperCBInfo;
2976 static void qcow2_amend_helper_cb(BlockDriverState *bs,
2977 int64_t operation_offset,
2978 int64_t operation_work_size, void *opaque)
2980 Qcow2AmendHelperCBInfo *info = opaque;
2981 int64_t current_work_size;
2982 int64_t projected_work_size;
2984 if (info->current_operation != info->last_operation) {
2985 if (info->last_operation != QCOW2_NO_OPERATION) {
2986 info->offset_completed += info->last_work_size;
2987 info->operations_completed++;
2990 info->last_operation = info->current_operation;
2993 assert(info->total_operations > 0);
2994 assert(info->operations_completed < info->total_operations);
2996 info->last_work_size = operation_work_size;
2998 current_work_size = info->offset_completed + operation_work_size;
3000 /* current_work_size is the total work size for (operations_completed + 1)
3001 * operations (which includes this one), so multiply it by the number of
3002 * operations not covered and divide it by the number of operations
3003 * covered to get a projection for the operations not covered */
3004 projected_work_size = current_work_size * (info->total_operations -
3005 info->operations_completed - 1)
3006 / (info->operations_completed + 1);
3008 info->original_status_cb(bs, info->offset_completed + operation_offset,
3009 current_work_size + projected_work_size,
3010 info->original_cb_opaque);
3013 static int qcow2_amend_options(BlockDriverState *bs, QemuOpts *opts,
3014 BlockDriverAmendStatusCB *status_cb,
3015 void *cb_opaque)
3017 BDRVQcow2State *s = bs->opaque;
3018 int old_version = s->qcow_version, new_version = old_version;
3019 uint64_t new_size = 0;
3020 const char *backing_file = NULL, *backing_format = NULL;
3021 bool lazy_refcounts = s->use_lazy_refcounts;
3022 const char *compat = NULL;
3023 uint64_t cluster_size = s->cluster_size;
3024 bool encrypt;
3025 int refcount_bits = s->refcount_bits;
3026 int ret;
3027 QemuOptDesc *desc = opts->list->desc;
3028 Qcow2AmendHelperCBInfo helper_cb_info;
3030 while (desc && desc->name) {
3031 if (!qemu_opt_find(opts, desc->name)) {
3032 /* only change explicitly defined options */
3033 desc++;
3034 continue;
3037 if (!strcmp(desc->name, BLOCK_OPT_COMPAT_LEVEL)) {
3038 compat = qemu_opt_get(opts, BLOCK_OPT_COMPAT_LEVEL);
3039 if (!compat) {
3040 /* preserve default */
3041 } else if (!strcmp(compat, "0.10")) {
3042 new_version = 2;
3043 } else if (!strcmp(compat, "1.1")) {
3044 new_version = 3;
3045 } else {
3046 error_report("Unknown compatibility level %s", compat);
3047 return -EINVAL;
3049 } else if (!strcmp(desc->name, BLOCK_OPT_PREALLOC)) {
3050 error_report("Cannot change preallocation mode");
3051 return -ENOTSUP;
3052 } else if (!strcmp(desc->name, BLOCK_OPT_SIZE)) {
3053 new_size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, 0);
3054 } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FILE)) {
3055 backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
3056 } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FMT)) {
3057 backing_format = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
3058 } else if (!strcmp(desc->name, BLOCK_OPT_ENCRYPT)) {
3059 encrypt = qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT,
3060 !!s->cipher);
3062 if (encrypt != !!s->cipher) {
3063 error_report("Changing the encryption flag is not supported");
3064 return -ENOTSUP;
3066 } else if (!strcmp(desc->name, BLOCK_OPT_CLUSTER_SIZE)) {
3067 cluster_size = qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE,
3068 cluster_size);
3069 if (cluster_size != s->cluster_size) {
3070 error_report("Changing the cluster size is not supported");
3071 return -ENOTSUP;
3073 } else if (!strcmp(desc->name, BLOCK_OPT_LAZY_REFCOUNTS)) {
3074 lazy_refcounts = qemu_opt_get_bool(opts, BLOCK_OPT_LAZY_REFCOUNTS,
3075 lazy_refcounts);
3076 } else if (!strcmp(desc->name, BLOCK_OPT_REFCOUNT_BITS)) {
3077 refcount_bits = qemu_opt_get_number(opts, BLOCK_OPT_REFCOUNT_BITS,
3078 refcount_bits);
3080 if (refcount_bits <= 0 || refcount_bits > 64 ||
3081 !is_power_of_2(refcount_bits))
3083 error_report("Refcount width must be a power of two and may "
3084 "not exceed 64 bits");
3085 return -EINVAL;
3087 } else {
3088 /* if this point is reached, this probably means a new option was
3089 * added without having it covered here */
3090 abort();
3093 desc++;
3096 helper_cb_info = (Qcow2AmendHelperCBInfo){
3097 .original_status_cb = status_cb,
3098 .original_cb_opaque = cb_opaque,
3099 .total_operations = (new_version < old_version)
3100 + (s->refcount_bits != refcount_bits)
3103 /* Upgrade first (some features may require compat=1.1) */
3104 if (new_version > old_version) {
3105 s->qcow_version = new_version;
3106 ret = qcow2_update_header(bs);
3107 if (ret < 0) {
3108 s->qcow_version = old_version;
3109 return ret;
3113 if (s->refcount_bits != refcount_bits) {
3114 int refcount_order = ctz32(refcount_bits);
3115 Error *local_error = NULL;
3117 if (new_version < 3 && refcount_bits != 16) {
3118 error_report("Different refcount widths than 16 bits require "
3119 "compatibility level 1.1 or above (use compat=1.1 or "
3120 "greater)");
3121 return -EINVAL;
3124 helper_cb_info.current_operation = QCOW2_CHANGING_REFCOUNT_ORDER;
3125 ret = qcow2_change_refcount_order(bs, refcount_order,
3126 &qcow2_amend_helper_cb,
3127 &helper_cb_info, &local_error);
3128 if (ret < 0) {
3129 error_report_err(local_error);
3130 return ret;
3134 if (backing_file || backing_format) {
3135 ret = qcow2_change_backing_file(bs,
3136 backing_file ?: s->image_backing_file,
3137 backing_format ?: s->image_backing_format);
3138 if (ret < 0) {
3139 return ret;
3143 if (s->use_lazy_refcounts != lazy_refcounts) {
3144 if (lazy_refcounts) {
3145 if (new_version < 3) {
3146 error_report("Lazy refcounts only supported with compatibility "
3147 "level 1.1 and above (use compat=1.1 or greater)");
3148 return -EINVAL;
3150 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
3151 ret = qcow2_update_header(bs);
3152 if (ret < 0) {
3153 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
3154 return ret;
3156 s->use_lazy_refcounts = true;
3157 } else {
3158 /* make image clean first */
3159 ret = qcow2_mark_clean(bs);
3160 if (ret < 0) {
3161 return ret;
3163 /* now disallow lazy refcounts */
3164 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
3165 ret = qcow2_update_header(bs);
3166 if (ret < 0) {
3167 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
3168 return ret;
3170 s->use_lazy_refcounts = false;
3174 if (new_size) {
3175 ret = bdrv_truncate(bs, new_size);
3176 if (ret < 0) {
3177 return ret;
3181 /* Downgrade last (so unsupported features can be removed before) */
3182 if (new_version < old_version) {
3183 helper_cb_info.current_operation = QCOW2_DOWNGRADING;
3184 ret = qcow2_downgrade(bs, new_version, &qcow2_amend_helper_cb,
3185 &helper_cb_info);
3186 if (ret < 0) {
3187 return ret;
3191 return 0;
3195 * If offset or size are negative, respectively, they will not be included in
3196 * the BLOCK_IMAGE_CORRUPTED event emitted.
3197 * fatal will be ignored for read-only BDS; corruptions found there will always
3198 * be considered non-fatal.
3200 void qcow2_signal_corruption(BlockDriverState *bs, bool fatal, int64_t offset,
3201 int64_t size, const char *message_format, ...)
3203 BDRVQcow2State *s = bs->opaque;
3204 const char *node_name;
3205 char *message;
3206 va_list ap;
3208 fatal = fatal && !bs->read_only;
3210 if (s->signaled_corruption &&
3211 (!fatal || (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT)))
3213 return;
3216 va_start(ap, message_format);
3217 message = g_strdup_vprintf(message_format, ap);
3218 va_end(ap);
3220 if (fatal) {
3221 fprintf(stderr, "qcow2: Marking image as corrupt: %s; further "
3222 "corruption events will be suppressed\n", message);
3223 } else {
3224 fprintf(stderr, "qcow2: Image is corrupt: %s; further non-fatal "
3225 "corruption events will be suppressed\n", message);
3228 node_name = bdrv_get_node_name(bs);
3229 qapi_event_send_block_image_corrupted(bdrv_get_device_name(bs),
3230 *node_name != '\0', node_name,
3231 message, offset >= 0, offset,
3232 size >= 0, size,
3233 fatal, &error_abort);
3234 g_free(message);
3236 if (fatal) {
3237 qcow2_mark_corrupt(bs);
3238 bs->drv = NULL; /* make BDS unusable */
3241 s->signaled_corruption = true;
3244 static QemuOptsList qcow2_create_opts = {
3245 .name = "qcow2-create-opts",
3246 .head = QTAILQ_HEAD_INITIALIZER(qcow2_create_opts.head),
3247 .desc = {
3249 .name = BLOCK_OPT_SIZE,
3250 .type = QEMU_OPT_SIZE,
3251 .help = "Virtual disk size"
3254 .name = BLOCK_OPT_COMPAT_LEVEL,
3255 .type = QEMU_OPT_STRING,
3256 .help = "Compatibility level (0.10 or 1.1)"
3259 .name = BLOCK_OPT_BACKING_FILE,
3260 .type = QEMU_OPT_STRING,
3261 .help = "File name of a base image"
3264 .name = BLOCK_OPT_BACKING_FMT,
3265 .type = QEMU_OPT_STRING,
3266 .help = "Image format of the base image"
3269 .name = BLOCK_OPT_ENCRYPT,
3270 .type = QEMU_OPT_BOOL,
3271 .help = "Encrypt the image",
3272 .def_value_str = "off"
3275 .name = BLOCK_OPT_CLUSTER_SIZE,
3276 .type = QEMU_OPT_SIZE,
3277 .help = "qcow2 cluster size",
3278 .def_value_str = stringify(DEFAULT_CLUSTER_SIZE)
3281 .name = BLOCK_OPT_PREALLOC,
3282 .type = QEMU_OPT_STRING,
3283 .help = "Preallocation mode (allowed values: off, metadata, "
3284 "falloc, full)"
3287 .name = BLOCK_OPT_LAZY_REFCOUNTS,
3288 .type = QEMU_OPT_BOOL,
3289 .help = "Postpone refcount updates",
3290 .def_value_str = "off"
3293 .name = BLOCK_OPT_REFCOUNT_BITS,
3294 .type = QEMU_OPT_NUMBER,
3295 .help = "Width of a reference count entry in bits",
3296 .def_value_str = "16"
3298 { /* end of list */ }
3302 BlockDriver bdrv_qcow2 = {
3303 .format_name = "qcow2",
3304 .instance_size = sizeof(BDRVQcow2State),
3305 .bdrv_probe = qcow2_probe,
3306 .bdrv_open = qcow2_open,
3307 .bdrv_close = qcow2_close,
3308 .bdrv_reopen_prepare = qcow2_reopen_prepare,
3309 .bdrv_reopen_commit = qcow2_reopen_commit,
3310 .bdrv_reopen_abort = qcow2_reopen_abort,
3311 .bdrv_join_options = qcow2_join_options,
3312 .bdrv_create = qcow2_create,
3313 .bdrv_has_zero_init = bdrv_has_zero_init_1,
3314 .bdrv_co_get_block_status = qcow2_co_get_block_status,
3315 .bdrv_set_key = qcow2_set_key,
3317 .bdrv_co_readv = qcow2_co_readv,
3318 .bdrv_co_writev = qcow2_co_writev,
3319 .bdrv_co_flush_to_os = qcow2_co_flush_to_os,
3321 .bdrv_co_write_zeroes = qcow2_co_write_zeroes,
3322 .bdrv_co_discard = qcow2_co_discard,
3323 .bdrv_truncate = qcow2_truncate,
3324 .bdrv_write_compressed = qcow2_write_compressed,
3325 .bdrv_make_empty = qcow2_make_empty,
3327 .bdrv_snapshot_create = qcow2_snapshot_create,
3328 .bdrv_snapshot_goto = qcow2_snapshot_goto,
3329 .bdrv_snapshot_delete = qcow2_snapshot_delete,
3330 .bdrv_snapshot_list = qcow2_snapshot_list,
3331 .bdrv_snapshot_load_tmp = qcow2_snapshot_load_tmp,
3332 .bdrv_get_info = qcow2_get_info,
3333 .bdrv_get_specific_info = qcow2_get_specific_info,
3335 .bdrv_save_vmstate = qcow2_save_vmstate,
3336 .bdrv_load_vmstate = qcow2_load_vmstate,
3338 .supports_backing = true,
3339 .bdrv_change_backing_file = qcow2_change_backing_file,
3341 .bdrv_refresh_limits = qcow2_refresh_limits,
3342 .bdrv_invalidate_cache = qcow2_invalidate_cache,
3344 .create_opts = &qcow2_create_opts,
3345 .bdrv_check = qcow2_check,
3346 .bdrv_amend_options = qcow2_amend_options,
3348 .bdrv_detach_aio_context = qcow2_detach_aio_context,
3349 .bdrv_attach_aio_context = qcow2_attach_aio_context,
3352 static void bdrv_qcow2_init(void)
3354 bdrv_register(&bdrv_qcow2);
3357 block_init(bdrv_qcow2_init);