nvdimm: implement NVDIMM device abstract
[qemu/ar7.git] / block / qcow2.c
blob1789af43d23c680cd3a7825bd45a2b636bdc4a7f
1 /*
2 * Block driver for the QCOW version 2 format
4 * Copyright (c) 2004-2006 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
24 #include "qemu-common.h"
25 #include "block/block_int.h"
26 #include "qemu/module.h"
27 #include <zlib.h>
28 #include "block/qcow2.h"
29 #include "qemu/error-report.h"
30 #include "qapi/qmp/qerror.h"
31 #include "qapi/qmp/qbool.h"
32 #include "qapi/util.h"
33 #include "qapi/qmp/types.h"
34 #include "qapi-event.h"
35 #include "trace.h"
36 #include "qemu/option_int.h"
39 Differences with QCOW:
41 - Support for multiple incremental snapshots.
42 - Memory management by reference counts.
43 - Clusters which have a reference count of one have the bit
44 QCOW_OFLAG_COPIED to optimize write performance.
45 - Size of compressed clusters is stored in sectors to reduce bit usage
46 in the cluster offsets.
47 - Support for storing additional data (such as the VM state) in the
48 snapshots.
49 - If a backing store is used, the cluster size is not constrained
50 (could be backported to QCOW).
51 - L2 tables have always a size of one cluster.
55 typedef struct {
56 uint32_t magic;
57 uint32_t len;
58 } QEMU_PACKED QCowExtension;
60 #define QCOW2_EXT_MAGIC_END 0
61 #define QCOW2_EXT_MAGIC_BACKING_FORMAT 0xE2792ACA
62 #define QCOW2_EXT_MAGIC_FEATURE_TABLE 0x6803f857
64 static int qcow2_probe(const uint8_t *buf, int buf_size, const char *filename)
66 const QCowHeader *cow_header = (const void *)buf;
68 if (buf_size >= sizeof(QCowHeader) &&
69 be32_to_cpu(cow_header->magic) == QCOW_MAGIC &&
70 be32_to_cpu(cow_header->version) >= 2)
71 return 100;
72 else
73 return 0;
77 /*
78 * read qcow2 extension and fill bs
79 * start reading from start_offset
80 * finish reading upon magic of value 0 or when end_offset reached
81 * unknown magic is skipped (future extension this version knows nothing about)
82 * return 0 upon success, non-0 otherwise
84 static int qcow2_read_extensions(BlockDriverState *bs, uint64_t start_offset,
85 uint64_t end_offset, void **p_feature_table,
86 Error **errp)
88 BDRVQcow2State *s = bs->opaque;
89 QCowExtension ext;
90 uint64_t offset;
91 int ret;
93 #ifdef DEBUG_EXT
94 printf("qcow2_read_extensions: start=%ld end=%ld\n", start_offset, end_offset);
95 #endif
96 offset = start_offset;
97 while (offset < end_offset) {
99 #ifdef DEBUG_EXT
100 /* Sanity check */
101 if (offset > s->cluster_size)
102 printf("qcow2_read_extension: suspicious offset %lu\n", offset);
104 printf("attempting to read extended header in offset %lu\n", offset);
105 #endif
107 ret = bdrv_pread(bs->file->bs, offset, &ext, sizeof(ext));
108 if (ret < 0) {
109 error_setg_errno(errp, -ret, "qcow2_read_extension: ERROR: "
110 "pread fail from offset %" PRIu64, offset);
111 return 1;
113 be32_to_cpus(&ext.magic);
114 be32_to_cpus(&ext.len);
115 offset += sizeof(ext);
116 #ifdef DEBUG_EXT
117 printf("ext.magic = 0x%x\n", ext.magic);
118 #endif
119 if (offset > end_offset || ext.len > end_offset - offset) {
120 error_setg(errp, "Header extension too large");
121 return -EINVAL;
124 switch (ext.magic) {
125 case QCOW2_EXT_MAGIC_END:
126 return 0;
128 case QCOW2_EXT_MAGIC_BACKING_FORMAT:
129 if (ext.len >= sizeof(bs->backing_format)) {
130 error_setg(errp, "ERROR: ext_backing_format: len=%" PRIu32
131 " too large (>=%zu)", ext.len,
132 sizeof(bs->backing_format));
133 return 2;
135 ret = bdrv_pread(bs->file->bs, offset, bs->backing_format, ext.len);
136 if (ret < 0) {
137 error_setg_errno(errp, -ret, "ERROR: ext_backing_format: "
138 "Could not read format name");
139 return 3;
141 bs->backing_format[ext.len] = '\0';
142 s->image_backing_format = g_strdup(bs->backing_format);
143 #ifdef DEBUG_EXT
144 printf("Qcow2: Got format extension %s\n", bs->backing_format);
145 #endif
146 break;
148 case QCOW2_EXT_MAGIC_FEATURE_TABLE:
149 if (p_feature_table != NULL) {
150 void* feature_table = g_malloc0(ext.len + 2 * sizeof(Qcow2Feature));
151 ret = bdrv_pread(bs->file->bs, offset , feature_table, ext.len);
152 if (ret < 0) {
153 error_setg_errno(errp, -ret, "ERROR: ext_feature_table: "
154 "Could not read table");
155 return ret;
158 *p_feature_table = feature_table;
160 break;
162 default:
163 /* unknown magic - save it in case we need to rewrite the header */
165 Qcow2UnknownHeaderExtension *uext;
167 uext = g_malloc0(sizeof(*uext) + ext.len);
168 uext->magic = ext.magic;
169 uext->len = ext.len;
170 QLIST_INSERT_HEAD(&s->unknown_header_ext, uext, next);
172 ret = bdrv_pread(bs->file->bs, offset , uext->data, uext->len);
173 if (ret < 0) {
174 error_setg_errno(errp, -ret, "ERROR: unknown extension: "
175 "Could not read data");
176 return ret;
179 break;
182 offset += ((ext.len + 7) & ~7);
185 return 0;
188 static void cleanup_unknown_header_ext(BlockDriverState *bs)
190 BDRVQcow2State *s = bs->opaque;
191 Qcow2UnknownHeaderExtension *uext, *next;
193 QLIST_FOREACH_SAFE(uext, &s->unknown_header_ext, next, next) {
194 QLIST_REMOVE(uext, next);
195 g_free(uext);
199 static void GCC_FMT_ATTR(3, 4) report_unsupported(BlockDriverState *bs,
200 Error **errp, const char *fmt, ...)
202 char msg[64];
203 va_list ap;
205 va_start(ap, fmt);
206 vsnprintf(msg, sizeof(msg), fmt, ap);
207 va_end(ap);
209 error_setg(errp, QERR_UNKNOWN_BLOCK_FORMAT_FEATURE,
210 bdrv_get_device_or_node_name(bs), "qcow2", msg);
213 static void report_unsupported_feature(BlockDriverState *bs,
214 Error **errp, Qcow2Feature *table, uint64_t mask)
216 char *features = g_strdup("");
217 char *old;
219 while (table && table->name[0] != '\0') {
220 if (table->type == QCOW2_FEAT_TYPE_INCOMPATIBLE) {
221 if (mask & (1ULL << table->bit)) {
222 old = features;
223 features = g_strdup_printf("%s%s%.46s", old, *old ? ", " : "",
224 table->name);
225 g_free(old);
226 mask &= ~(1ULL << table->bit);
229 table++;
232 if (mask) {
233 old = features;
234 features = g_strdup_printf("%s%sUnknown incompatible feature: %" PRIx64,
235 old, *old ? ", " : "", mask);
236 g_free(old);
239 report_unsupported(bs, errp, "%s", features);
240 g_free(features);
244 * Sets the dirty bit and flushes afterwards if necessary.
246 * The incompatible_features bit is only set if the image file header was
247 * updated successfully. Therefore it is not required to check the return
248 * value of this function.
250 int qcow2_mark_dirty(BlockDriverState *bs)
252 BDRVQcow2State *s = bs->opaque;
253 uint64_t val;
254 int ret;
256 assert(s->qcow_version >= 3);
258 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
259 return 0; /* already dirty */
262 val = cpu_to_be64(s->incompatible_features | QCOW2_INCOMPAT_DIRTY);
263 ret = bdrv_pwrite(bs->file->bs, offsetof(QCowHeader, incompatible_features),
264 &val, sizeof(val));
265 if (ret < 0) {
266 return ret;
268 ret = bdrv_flush(bs->file->bs);
269 if (ret < 0) {
270 return ret;
273 /* Only treat image as dirty if the header was updated successfully */
274 s->incompatible_features |= QCOW2_INCOMPAT_DIRTY;
275 return 0;
279 * Clears the dirty bit and flushes before if necessary. Only call this
280 * function when there are no pending requests, it does not guard against
281 * concurrent requests dirtying the image.
283 static int qcow2_mark_clean(BlockDriverState *bs)
285 BDRVQcow2State *s = bs->opaque;
287 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
288 int ret;
290 s->incompatible_features &= ~QCOW2_INCOMPAT_DIRTY;
292 ret = bdrv_flush(bs);
293 if (ret < 0) {
294 return ret;
297 return qcow2_update_header(bs);
299 return 0;
303 * Marks the image as corrupt.
305 int qcow2_mark_corrupt(BlockDriverState *bs)
307 BDRVQcow2State *s = bs->opaque;
309 s->incompatible_features |= QCOW2_INCOMPAT_CORRUPT;
310 return qcow2_update_header(bs);
314 * Marks the image as consistent, i.e., unsets the corrupt bit, and flushes
315 * before if necessary.
317 int qcow2_mark_consistent(BlockDriverState *bs)
319 BDRVQcow2State *s = bs->opaque;
321 if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
322 int ret = bdrv_flush(bs);
323 if (ret < 0) {
324 return ret;
327 s->incompatible_features &= ~QCOW2_INCOMPAT_CORRUPT;
328 return qcow2_update_header(bs);
330 return 0;
333 static int qcow2_check(BlockDriverState *bs, BdrvCheckResult *result,
334 BdrvCheckMode fix)
336 int ret = qcow2_check_refcounts(bs, result, fix);
337 if (ret < 0) {
338 return ret;
341 if (fix && result->check_errors == 0 && result->corruptions == 0) {
342 ret = qcow2_mark_clean(bs);
343 if (ret < 0) {
344 return ret;
346 return qcow2_mark_consistent(bs);
348 return ret;
351 static int validate_table_offset(BlockDriverState *bs, uint64_t offset,
352 uint64_t entries, size_t entry_len)
354 BDRVQcow2State *s = bs->opaque;
355 uint64_t size;
357 /* Use signed INT64_MAX as the maximum even for uint64_t header fields,
358 * because values will be passed to qemu functions taking int64_t. */
359 if (entries > INT64_MAX / entry_len) {
360 return -EINVAL;
363 size = entries * entry_len;
365 if (INT64_MAX - size < offset) {
366 return -EINVAL;
369 /* Tables must be cluster aligned */
370 if (offset & (s->cluster_size - 1)) {
371 return -EINVAL;
374 return 0;
377 static QemuOptsList qcow2_runtime_opts = {
378 .name = "qcow2",
379 .head = QTAILQ_HEAD_INITIALIZER(qcow2_runtime_opts.head),
380 .desc = {
382 .name = QCOW2_OPT_LAZY_REFCOUNTS,
383 .type = QEMU_OPT_BOOL,
384 .help = "Postpone refcount updates",
387 .name = QCOW2_OPT_DISCARD_REQUEST,
388 .type = QEMU_OPT_BOOL,
389 .help = "Pass guest discard requests to the layer below",
392 .name = QCOW2_OPT_DISCARD_SNAPSHOT,
393 .type = QEMU_OPT_BOOL,
394 .help = "Generate discard requests when snapshot related space "
395 "is freed",
398 .name = QCOW2_OPT_DISCARD_OTHER,
399 .type = QEMU_OPT_BOOL,
400 .help = "Generate discard requests when other clusters are freed",
403 .name = QCOW2_OPT_OVERLAP,
404 .type = QEMU_OPT_STRING,
405 .help = "Selects which overlap checks to perform from a range of "
406 "templates (none, constant, cached, all)",
409 .name = QCOW2_OPT_OVERLAP_TEMPLATE,
410 .type = QEMU_OPT_STRING,
411 .help = "Selects which overlap checks to perform from a range of "
412 "templates (none, constant, cached, all)",
415 .name = QCOW2_OPT_OVERLAP_MAIN_HEADER,
416 .type = QEMU_OPT_BOOL,
417 .help = "Check for unintended writes into the main qcow2 header",
420 .name = QCOW2_OPT_OVERLAP_ACTIVE_L1,
421 .type = QEMU_OPT_BOOL,
422 .help = "Check for unintended writes into the active L1 table",
425 .name = QCOW2_OPT_OVERLAP_ACTIVE_L2,
426 .type = QEMU_OPT_BOOL,
427 .help = "Check for unintended writes into an active L2 table",
430 .name = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
431 .type = QEMU_OPT_BOOL,
432 .help = "Check for unintended writes into the refcount table",
435 .name = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
436 .type = QEMU_OPT_BOOL,
437 .help = "Check for unintended writes into a refcount block",
440 .name = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
441 .type = QEMU_OPT_BOOL,
442 .help = "Check for unintended writes into the snapshot table",
445 .name = QCOW2_OPT_OVERLAP_INACTIVE_L1,
446 .type = QEMU_OPT_BOOL,
447 .help = "Check for unintended writes into an inactive L1 table",
450 .name = QCOW2_OPT_OVERLAP_INACTIVE_L2,
451 .type = QEMU_OPT_BOOL,
452 .help = "Check for unintended writes into an inactive L2 table",
455 .name = QCOW2_OPT_CACHE_SIZE,
456 .type = QEMU_OPT_SIZE,
457 .help = "Maximum combined metadata (L2 tables and refcount blocks) "
458 "cache size",
461 .name = QCOW2_OPT_L2_CACHE_SIZE,
462 .type = QEMU_OPT_SIZE,
463 .help = "Maximum L2 table cache size",
466 .name = QCOW2_OPT_REFCOUNT_CACHE_SIZE,
467 .type = QEMU_OPT_SIZE,
468 .help = "Maximum refcount block cache size",
471 .name = QCOW2_OPT_CACHE_CLEAN_INTERVAL,
472 .type = QEMU_OPT_NUMBER,
473 .help = "Clean unused cache entries after this time (in seconds)",
475 { /* end of list */ }
479 static const char *overlap_bool_option_names[QCOW2_OL_MAX_BITNR] = {
480 [QCOW2_OL_MAIN_HEADER_BITNR] = QCOW2_OPT_OVERLAP_MAIN_HEADER,
481 [QCOW2_OL_ACTIVE_L1_BITNR] = QCOW2_OPT_OVERLAP_ACTIVE_L1,
482 [QCOW2_OL_ACTIVE_L2_BITNR] = QCOW2_OPT_OVERLAP_ACTIVE_L2,
483 [QCOW2_OL_REFCOUNT_TABLE_BITNR] = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
484 [QCOW2_OL_REFCOUNT_BLOCK_BITNR] = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
485 [QCOW2_OL_SNAPSHOT_TABLE_BITNR] = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
486 [QCOW2_OL_INACTIVE_L1_BITNR] = QCOW2_OPT_OVERLAP_INACTIVE_L1,
487 [QCOW2_OL_INACTIVE_L2_BITNR] = QCOW2_OPT_OVERLAP_INACTIVE_L2,
490 static void cache_clean_timer_cb(void *opaque)
492 BlockDriverState *bs = opaque;
493 BDRVQcow2State *s = bs->opaque;
494 qcow2_cache_clean_unused(bs, s->l2_table_cache);
495 qcow2_cache_clean_unused(bs, s->refcount_block_cache);
496 timer_mod(s->cache_clean_timer, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) +
497 (int64_t) s->cache_clean_interval * 1000);
500 static void cache_clean_timer_init(BlockDriverState *bs, AioContext *context)
502 BDRVQcow2State *s = bs->opaque;
503 if (s->cache_clean_interval > 0) {
504 s->cache_clean_timer = aio_timer_new(context, QEMU_CLOCK_VIRTUAL,
505 SCALE_MS, cache_clean_timer_cb,
506 bs);
507 timer_mod(s->cache_clean_timer, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) +
508 (int64_t) s->cache_clean_interval * 1000);
512 static void cache_clean_timer_del(BlockDriverState *bs)
514 BDRVQcow2State *s = bs->opaque;
515 if (s->cache_clean_timer) {
516 timer_del(s->cache_clean_timer);
517 timer_free(s->cache_clean_timer);
518 s->cache_clean_timer = NULL;
522 static void qcow2_detach_aio_context(BlockDriverState *bs)
524 cache_clean_timer_del(bs);
527 static void qcow2_attach_aio_context(BlockDriverState *bs,
528 AioContext *new_context)
530 cache_clean_timer_init(bs, new_context);
533 static void read_cache_sizes(BlockDriverState *bs, QemuOpts *opts,
534 uint64_t *l2_cache_size,
535 uint64_t *refcount_cache_size, Error **errp)
537 BDRVQcow2State *s = bs->opaque;
538 uint64_t combined_cache_size;
539 bool l2_cache_size_set, refcount_cache_size_set, combined_cache_size_set;
541 combined_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_CACHE_SIZE);
542 l2_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_L2_CACHE_SIZE);
543 refcount_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
545 combined_cache_size = qemu_opt_get_size(opts, QCOW2_OPT_CACHE_SIZE, 0);
546 *l2_cache_size = qemu_opt_get_size(opts, QCOW2_OPT_L2_CACHE_SIZE, 0);
547 *refcount_cache_size = qemu_opt_get_size(opts,
548 QCOW2_OPT_REFCOUNT_CACHE_SIZE, 0);
550 if (combined_cache_size_set) {
551 if (l2_cache_size_set && refcount_cache_size_set) {
552 error_setg(errp, QCOW2_OPT_CACHE_SIZE ", " QCOW2_OPT_L2_CACHE_SIZE
553 " and " QCOW2_OPT_REFCOUNT_CACHE_SIZE " may not be set "
554 "the same time");
555 return;
556 } else if (*l2_cache_size > combined_cache_size) {
557 error_setg(errp, QCOW2_OPT_L2_CACHE_SIZE " may not exceed "
558 QCOW2_OPT_CACHE_SIZE);
559 return;
560 } else if (*refcount_cache_size > combined_cache_size) {
561 error_setg(errp, QCOW2_OPT_REFCOUNT_CACHE_SIZE " may not exceed "
562 QCOW2_OPT_CACHE_SIZE);
563 return;
566 if (l2_cache_size_set) {
567 *refcount_cache_size = combined_cache_size - *l2_cache_size;
568 } else if (refcount_cache_size_set) {
569 *l2_cache_size = combined_cache_size - *refcount_cache_size;
570 } else {
571 *refcount_cache_size = combined_cache_size
572 / (DEFAULT_L2_REFCOUNT_SIZE_RATIO + 1);
573 *l2_cache_size = combined_cache_size - *refcount_cache_size;
575 } else {
576 if (!l2_cache_size_set && !refcount_cache_size_set) {
577 *l2_cache_size = MAX(DEFAULT_L2_CACHE_BYTE_SIZE,
578 (uint64_t)DEFAULT_L2_CACHE_CLUSTERS
579 * s->cluster_size);
580 *refcount_cache_size = *l2_cache_size
581 / DEFAULT_L2_REFCOUNT_SIZE_RATIO;
582 } else if (!l2_cache_size_set) {
583 *l2_cache_size = *refcount_cache_size
584 * DEFAULT_L2_REFCOUNT_SIZE_RATIO;
585 } else if (!refcount_cache_size_set) {
586 *refcount_cache_size = *l2_cache_size
587 / DEFAULT_L2_REFCOUNT_SIZE_RATIO;
592 typedef struct Qcow2ReopenState {
593 Qcow2Cache *l2_table_cache;
594 Qcow2Cache *refcount_block_cache;
595 bool use_lazy_refcounts;
596 int overlap_check;
597 bool discard_passthrough[QCOW2_DISCARD_MAX];
598 uint64_t cache_clean_interval;
599 } Qcow2ReopenState;
601 static int qcow2_update_options_prepare(BlockDriverState *bs,
602 Qcow2ReopenState *r,
603 QDict *options, int flags,
604 Error **errp)
606 BDRVQcow2State *s = bs->opaque;
607 QemuOpts *opts = NULL;
608 const char *opt_overlap_check, *opt_overlap_check_template;
609 int overlap_check_template = 0;
610 uint64_t l2_cache_size, refcount_cache_size;
611 int i;
612 Error *local_err = NULL;
613 int ret;
615 opts = qemu_opts_create(&qcow2_runtime_opts, NULL, 0, &error_abort);
616 qemu_opts_absorb_qdict(opts, options, &local_err);
617 if (local_err) {
618 error_propagate(errp, local_err);
619 ret = -EINVAL;
620 goto fail;
623 /* get L2 table/refcount block cache size from command line options */
624 read_cache_sizes(bs, opts, &l2_cache_size, &refcount_cache_size,
625 &local_err);
626 if (local_err) {
627 error_propagate(errp, local_err);
628 ret = -EINVAL;
629 goto fail;
632 l2_cache_size /= s->cluster_size;
633 if (l2_cache_size < MIN_L2_CACHE_SIZE) {
634 l2_cache_size = MIN_L2_CACHE_SIZE;
636 if (l2_cache_size > INT_MAX) {
637 error_setg(errp, "L2 cache size too big");
638 ret = -EINVAL;
639 goto fail;
642 refcount_cache_size /= s->cluster_size;
643 if (refcount_cache_size < MIN_REFCOUNT_CACHE_SIZE) {
644 refcount_cache_size = MIN_REFCOUNT_CACHE_SIZE;
646 if (refcount_cache_size > INT_MAX) {
647 error_setg(errp, "Refcount cache size too big");
648 ret = -EINVAL;
649 goto fail;
652 /* alloc new L2 table/refcount block cache, flush old one */
653 if (s->l2_table_cache) {
654 ret = qcow2_cache_flush(bs, s->l2_table_cache);
655 if (ret) {
656 error_setg_errno(errp, -ret, "Failed to flush the L2 table cache");
657 goto fail;
661 if (s->refcount_block_cache) {
662 ret = qcow2_cache_flush(bs, s->refcount_block_cache);
663 if (ret) {
664 error_setg_errno(errp, -ret,
665 "Failed to flush the refcount block cache");
666 goto fail;
670 r->l2_table_cache = qcow2_cache_create(bs, l2_cache_size);
671 r->refcount_block_cache = qcow2_cache_create(bs, refcount_cache_size);
672 if (r->l2_table_cache == NULL || r->refcount_block_cache == NULL) {
673 error_setg(errp, "Could not allocate metadata caches");
674 ret = -ENOMEM;
675 goto fail;
678 /* New interval for cache cleanup timer */
679 r->cache_clean_interval =
680 qemu_opt_get_number(opts, QCOW2_OPT_CACHE_CLEAN_INTERVAL,
681 s->cache_clean_interval);
682 if (r->cache_clean_interval > UINT_MAX) {
683 error_setg(errp, "Cache clean interval too big");
684 ret = -EINVAL;
685 goto fail;
688 /* lazy-refcounts; flush if going from enabled to disabled */
689 r->use_lazy_refcounts = qemu_opt_get_bool(opts, QCOW2_OPT_LAZY_REFCOUNTS,
690 (s->compatible_features & QCOW2_COMPAT_LAZY_REFCOUNTS));
691 if (r->use_lazy_refcounts && s->qcow_version < 3) {
692 error_setg(errp, "Lazy refcounts require a qcow2 image with at least "
693 "qemu 1.1 compatibility level");
694 ret = -EINVAL;
695 goto fail;
698 if (s->use_lazy_refcounts && !r->use_lazy_refcounts) {
699 ret = qcow2_mark_clean(bs);
700 if (ret < 0) {
701 error_setg_errno(errp, -ret, "Failed to disable lazy refcounts");
702 goto fail;
706 /* Overlap check options */
707 opt_overlap_check = qemu_opt_get(opts, QCOW2_OPT_OVERLAP);
708 opt_overlap_check_template = qemu_opt_get(opts, QCOW2_OPT_OVERLAP_TEMPLATE);
709 if (opt_overlap_check_template && opt_overlap_check &&
710 strcmp(opt_overlap_check_template, opt_overlap_check))
712 error_setg(errp, "Conflicting values for qcow2 options '"
713 QCOW2_OPT_OVERLAP "' ('%s') and '" QCOW2_OPT_OVERLAP_TEMPLATE
714 "' ('%s')", opt_overlap_check, opt_overlap_check_template);
715 ret = -EINVAL;
716 goto fail;
718 if (!opt_overlap_check) {
719 opt_overlap_check = opt_overlap_check_template ?: "cached";
722 if (!strcmp(opt_overlap_check, "none")) {
723 overlap_check_template = 0;
724 } else if (!strcmp(opt_overlap_check, "constant")) {
725 overlap_check_template = QCOW2_OL_CONSTANT;
726 } else if (!strcmp(opt_overlap_check, "cached")) {
727 overlap_check_template = QCOW2_OL_CACHED;
728 } else if (!strcmp(opt_overlap_check, "all")) {
729 overlap_check_template = QCOW2_OL_ALL;
730 } else {
731 error_setg(errp, "Unsupported value '%s' for qcow2 option "
732 "'overlap-check'. Allowed are any of the following: "
733 "none, constant, cached, all", opt_overlap_check);
734 ret = -EINVAL;
735 goto fail;
738 r->overlap_check = 0;
739 for (i = 0; i < QCOW2_OL_MAX_BITNR; i++) {
740 /* overlap-check defines a template bitmask, but every flag may be
741 * overwritten through the associated boolean option */
742 r->overlap_check |=
743 qemu_opt_get_bool(opts, overlap_bool_option_names[i],
744 overlap_check_template & (1 << i)) << i;
747 r->discard_passthrough[QCOW2_DISCARD_NEVER] = false;
748 r->discard_passthrough[QCOW2_DISCARD_ALWAYS] = true;
749 r->discard_passthrough[QCOW2_DISCARD_REQUEST] =
750 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_REQUEST,
751 flags & BDRV_O_UNMAP);
752 r->discard_passthrough[QCOW2_DISCARD_SNAPSHOT] =
753 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_SNAPSHOT, true);
754 r->discard_passthrough[QCOW2_DISCARD_OTHER] =
755 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_OTHER, false);
757 ret = 0;
758 fail:
759 qemu_opts_del(opts);
760 opts = NULL;
761 return ret;
764 static void qcow2_update_options_commit(BlockDriverState *bs,
765 Qcow2ReopenState *r)
767 BDRVQcow2State *s = bs->opaque;
768 int i;
770 if (s->l2_table_cache) {
771 qcow2_cache_destroy(bs, s->l2_table_cache);
773 if (s->refcount_block_cache) {
774 qcow2_cache_destroy(bs, s->refcount_block_cache);
776 s->l2_table_cache = r->l2_table_cache;
777 s->refcount_block_cache = r->refcount_block_cache;
779 s->overlap_check = r->overlap_check;
780 s->use_lazy_refcounts = r->use_lazy_refcounts;
782 for (i = 0; i < QCOW2_DISCARD_MAX; i++) {
783 s->discard_passthrough[i] = r->discard_passthrough[i];
786 if (s->cache_clean_interval != r->cache_clean_interval) {
787 cache_clean_timer_del(bs);
788 s->cache_clean_interval = r->cache_clean_interval;
789 cache_clean_timer_init(bs, bdrv_get_aio_context(bs));
793 static void qcow2_update_options_abort(BlockDriverState *bs,
794 Qcow2ReopenState *r)
796 if (r->l2_table_cache) {
797 qcow2_cache_destroy(bs, r->l2_table_cache);
799 if (r->refcount_block_cache) {
800 qcow2_cache_destroy(bs, r->refcount_block_cache);
804 static int qcow2_update_options(BlockDriverState *bs, QDict *options,
805 int flags, Error **errp)
807 Qcow2ReopenState r = {};
808 int ret;
810 ret = qcow2_update_options_prepare(bs, &r, options, flags, errp);
811 if (ret >= 0) {
812 qcow2_update_options_commit(bs, &r);
813 } else {
814 qcow2_update_options_abort(bs, &r);
817 return ret;
820 static int qcow2_open(BlockDriverState *bs, QDict *options, int flags,
821 Error **errp)
823 BDRVQcow2State *s = bs->opaque;
824 unsigned int len, i;
825 int ret = 0;
826 QCowHeader header;
827 Error *local_err = NULL;
828 uint64_t ext_end;
829 uint64_t l1_vm_state_index;
831 ret = bdrv_pread(bs->file->bs, 0, &header, sizeof(header));
832 if (ret < 0) {
833 error_setg_errno(errp, -ret, "Could not read qcow2 header");
834 goto fail;
836 be32_to_cpus(&header.magic);
837 be32_to_cpus(&header.version);
838 be64_to_cpus(&header.backing_file_offset);
839 be32_to_cpus(&header.backing_file_size);
840 be64_to_cpus(&header.size);
841 be32_to_cpus(&header.cluster_bits);
842 be32_to_cpus(&header.crypt_method);
843 be64_to_cpus(&header.l1_table_offset);
844 be32_to_cpus(&header.l1_size);
845 be64_to_cpus(&header.refcount_table_offset);
846 be32_to_cpus(&header.refcount_table_clusters);
847 be64_to_cpus(&header.snapshots_offset);
848 be32_to_cpus(&header.nb_snapshots);
850 if (header.magic != QCOW_MAGIC) {
851 error_setg(errp, "Image is not in qcow2 format");
852 ret = -EINVAL;
853 goto fail;
855 if (header.version < 2 || header.version > 3) {
856 report_unsupported(bs, errp, "QCOW version %" PRIu32, header.version);
857 ret = -ENOTSUP;
858 goto fail;
861 s->qcow_version = header.version;
863 /* Initialise cluster size */
864 if (header.cluster_bits < MIN_CLUSTER_BITS ||
865 header.cluster_bits > MAX_CLUSTER_BITS) {
866 error_setg(errp, "Unsupported cluster size: 2^%" PRIu32,
867 header.cluster_bits);
868 ret = -EINVAL;
869 goto fail;
872 s->cluster_bits = header.cluster_bits;
873 s->cluster_size = 1 << s->cluster_bits;
874 s->cluster_sectors = 1 << (s->cluster_bits - 9);
876 /* Initialise version 3 header fields */
877 if (header.version == 2) {
878 header.incompatible_features = 0;
879 header.compatible_features = 0;
880 header.autoclear_features = 0;
881 header.refcount_order = 4;
882 header.header_length = 72;
883 } else {
884 be64_to_cpus(&header.incompatible_features);
885 be64_to_cpus(&header.compatible_features);
886 be64_to_cpus(&header.autoclear_features);
887 be32_to_cpus(&header.refcount_order);
888 be32_to_cpus(&header.header_length);
890 if (header.header_length < 104) {
891 error_setg(errp, "qcow2 header too short");
892 ret = -EINVAL;
893 goto fail;
897 if (header.header_length > s->cluster_size) {
898 error_setg(errp, "qcow2 header exceeds cluster size");
899 ret = -EINVAL;
900 goto fail;
903 if (header.header_length > sizeof(header)) {
904 s->unknown_header_fields_size = header.header_length - sizeof(header);
905 s->unknown_header_fields = g_malloc(s->unknown_header_fields_size);
906 ret = bdrv_pread(bs->file->bs, sizeof(header), s->unknown_header_fields,
907 s->unknown_header_fields_size);
908 if (ret < 0) {
909 error_setg_errno(errp, -ret, "Could not read unknown qcow2 header "
910 "fields");
911 goto fail;
915 if (header.backing_file_offset > s->cluster_size) {
916 error_setg(errp, "Invalid backing file offset");
917 ret = -EINVAL;
918 goto fail;
921 if (header.backing_file_offset) {
922 ext_end = header.backing_file_offset;
923 } else {
924 ext_end = 1 << header.cluster_bits;
927 /* Handle feature bits */
928 s->incompatible_features = header.incompatible_features;
929 s->compatible_features = header.compatible_features;
930 s->autoclear_features = header.autoclear_features;
932 if (s->incompatible_features & ~QCOW2_INCOMPAT_MASK) {
933 void *feature_table = NULL;
934 qcow2_read_extensions(bs, header.header_length, ext_end,
935 &feature_table, NULL);
936 report_unsupported_feature(bs, errp, feature_table,
937 s->incompatible_features &
938 ~QCOW2_INCOMPAT_MASK);
939 ret = -ENOTSUP;
940 g_free(feature_table);
941 goto fail;
944 if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
945 /* Corrupt images may not be written to unless they are being repaired
947 if ((flags & BDRV_O_RDWR) && !(flags & BDRV_O_CHECK)) {
948 error_setg(errp, "qcow2: Image is corrupt; cannot be opened "
949 "read/write");
950 ret = -EACCES;
951 goto fail;
955 /* Check support for various header values */
956 if (header.refcount_order > 6) {
957 error_setg(errp, "Reference count entry width too large; may not "
958 "exceed 64 bits");
959 ret = -EINVAL;
960 goto fail;
962 s->refcount_order = header.refcount_order;
963 s->refcount_bits = 1 << s->refcount_order;
964 s->refcount_max = UINT64_C(1) << (s->refcount_bits - 1);
965 s->refcount_max += s->refcount_max - 1;
967 if (header.crypt_method > QCOW_CRYPT_AES) {
968 error_setg(errp, "Unsupported encryption method: %" PRIu32,
969 header.crypt_method);
970 ret = -EINVAL;
971 goto fail;
973 if (!qcrypto_cipher_supports(QCRYPTO_CIPHER_ALG_AES_128)) {
974 error_setg(errp, "AES cipher not available");
975 ret = -EINVAL;
976 goto fail;
978 s->crypt_method_header = header.crypt_method;
979 if (s->crypt_method_header) {
980 bs->encrypted = 1;
983 s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */
984 s->l2_size = 1 << s->l2_bits;
985 /* 2^(s->refcount_order - 3) is the refcount width in bytes */
986 s->refcount_block_bits = s->cluster_bits - (s->refcount_order - 3);
987 s->refcount_block_size = 1 << s->refcount_block_bits;
988 bs->total_sectors = header.size / 512;
989 s->csize_shift = (62 - (s->cluster_bits - 8));
990 s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;
991 s->cluster_offset_mask = (1LL << s->csize_shift) - 1;
993 s->refcount_table_offset = header.refcount_table_offset;
994 s->refcount_table_size =
995 header.refcount_table_clusters << (s->cluster_bits - 3);
997 if (header.refcount_table_clusters > qcow2_max_refcount_clusters(s)) {
998 error_setg(errp, "Reference count table too large");
999 ret = -EINVAL;
1000 goto fail;
1003 ret = validate_table_offset(bs, s->refcount_table_offset,
1004 s->refcount_table_size, sizeof(uint64_t));
1005 if (ret < 0) {
1006 error_setg(errp, "Invalid reference count table offset");
1007 goto fail;
1010 /* Snapshot table offset/length */
1011 if (header.nb_snapshots > QCOW_MAX_SNAPSHOTS) {
1012 error_setg(errp, "Too many snapshots");
1013 ret = -EINVAL;
1014 goto fail;
1017 ret = validate_table_offset(bs, header.snapshots_offset,
1018 header.nb_snapshots,
1019 sizeof(QCowSnapshotHeader));
1020 if (ret < 0) {
1021 error_setg(errp, "Invalid snapshot table offset");
1022 goto fail;
1025 /* read the level 1 table */
1026 if (header.l1_size > QCOW_MAX_L1_SIZE / sizeof(uint64_t)) {
1027 error_setg(errp, "Active L1 table too large");
1028 ret = -EFBIG;
1029 goto fail;
1031 s->l1_size = header.l1_size;
1033 l1_vm_state_index = size_to_l1(s, header.size);
1034 if (l1_vm_state_index > INT_MAX) {
1035 error_setg(errp, "Image is too big");
1036 ret = -EFBIG;
1037 goto fail;
1039 s->l1_vm_state_index = l1_vm_state_index;
1041 /* the L1 table must contain at least enough entries to put
1042 header.size bytes */
1043 if (s->l1_size < s->l1_vm_state_index) {
1044 error_setg(errp, "L1 table is too small");
1045 ret = -EINVAL;
1046 goto fail;
1049 ret = validate_table_offset(bs, header.l1_table_offset,
1050 header.l1_size, sizeof(uint64_t));
1051 if (ret < 0) {
1052 error_setg(errp, "Invalid L1 table offset");
1053 goto fail;
1055 s->l1_table_offset = header.l1_table_offset;
1058 if (s->l1_size > 0) {
1059 s->l1_table = qemu_try_blockalign(bs->file->bs,
1060 align_offset(s->l1_size * sizeof(uint64_t), 512));
1061 if (s->l1_table == NULL) {
1062 error_setg(errp, "Could not allocate L1 table");
1063 ret = -ENOMEM;
1064 goto fail;
1066 ret = bdrv_pread(bs->file->bs, s->l1_table_offset, s->l1_table,
1067 s->l1_size * sizeof(uint64_t));
1068 if (ret < 0) {
1069 error_setg_errno(errp, -ret, "Could not read L1 table");
1070 goto fail;
1072 for(i = 0;i < s->l1_size; i++) {
1073 be64_to_cpus(&s->l1_table[i]);
1077 /* Parse driver-specific options */
1078 ret = qcow2_update_options(bs, options, flags, errp);
1079 if (ret < 0) {
1080 goto fail;
1083 s->cluster_cache = g_malloc(s->cluster_size);
1084 /* one more sector for decompressed data alignment */
1085 s->cluster_data = qemu_try_blockalign(bs->file->bs, QCOW_MAX_CRYPT_CLUSTERS
1086 * s->cluster_size + 512);
1087 if (s->cluster_data == NULL) {
1088 error_setg(errp, "Could not allocate temporary cluster buffer");
1089 ret = -ENOMEM;
1090 goto fail;
1093 s->cluster_cache_offset = -1;
1094 s->flags = flags;
1096 ret = qcow2_refcount_init(bs);
1097 if (ret != 0) {
1098 error_setg_errno(errp, -ret, "Could not initialize refcount handling");
1099 goto fail;
1102 QLIST_INIT(&s->cluster_allocs);
1103 QTAILQ_INIT(&s->discards);
1105 /* read qcow2 extensions */
1106 if (qcow2_read_extensions(bs, header.header_length, ext_end, NULL,
1107 &local_err)) {
1108 error_propagate(errp, local_err);
1109 ret = -EINVAL;
1110 goto fail;
1113 /* read the backing file name */
1114 if (header.backing_file_offset != 0) {
1115 len = header.backing_file_size;
1116 if (len > MIN(1023, s->cluster_size - header.backing_file_offset) ||
1117 len >= sizeof(bs->backing_file)) {
1118 error_setg(errp, "Backing file name too long");
1119 ret = -EINVAL;
1120 goto fail;
1122 ret = bdrv_pread(bs->file->bs, header.backing_file_offset,
1123 bs->backing_file, len);
1124 if (ret < 0) {
1125 error_setg_errno(errp, -ret, "Could not read backing file name");
1126 goto fail;
1128 bs->backing_file[len] = '\0';
1129 s->image_backing_file = g_strdup(bs->backing_file);
1132 /* Internal snapshots */
1133 s->snapshots_offset = header.snapshots_offset;
1134 s->nb_snapshots = header.nb_snapshots;
1136 ret = qcow2_read_snapshots(bs);
1137 if (ret < 0) {
1138 error_setg_errno(errp, -ret, "Could not read snapshots");
1139 goto fail;
1142 /* Clear unknown autoclear feature bits */
1143 if (!bs->read_only && !(flags & BDRV_O_INCOMING) && s->autoclear_features) {
1144 s->autoclear_features = 0;
1145 ret = qcow2_update_header(bs);
1146 if (ret < 0) {
1147 error_setg_errno(errp, -ret, "Could not update qcow2 header");
1148 goto fail;
1152 /* Initialise locks */
1153 qemu_co_mutex_init(&s->lock);
1155 /* Repair image if dirty */
1156 if (!(flags & (BDRV_O_CHECK | BDRV_O_INCOMING)) && !bs->read_only &&
1157 (s->incompatible_features & QCOW2_INCOMPAT_DIRTY)) {
1158 BdrvCheckResult result = {0};
1160 ret = qcow2_check(bs, &result, BDRV_FIX_ERRORS | BDRV_FIX_LEAKS);
1161 if (ret < 0) {
1162 error_setg_errno(errp, -ret, "Could not repair dirty image");
1163 goto fail;
1167 #ifdef DEBUG_ALLOC
1169 BdrvCheckResult result = {0};
1170 qcow2_check_refcounts(bs, &result, 0);
1172 #endif
1173 return ret;
1175 fail:
1176 g_free(s->unknown_header_fields);
1177 cleanup_unknown_header_ext(bs);
1178 qcow2_free_snapshots(bs);
1179 qcow2_refcount_close(bs);
1180 qemu_vfree(s->l1_table);
1181 /* else pre-write overlap checks in cache_destroy may crash */
1182 s->l1_table = NULL;
1183 cache_clean_timer_del(bs);
1184 if (s->l2_table_cache) {
1185 qcow2_cache_destroy(bs, s->l2_table_cache);
1187 if (s->refcount_block_cache) {
1188 qcow2_cache_destroy(bs, s->refcount_block_cache);
1190 g_free(s->cluster_cache);
1191 qemu_vfree(s->cluster_data);
1192 return ret;
1195 static void qcow2_refresh_limits(BlockDriverState *bs, Error **errp)
1197 BDRVQcow2State *s = bs->opaque;
1199 bs->bl.write_zeroes_alignment = s->cluster_sectors;
1202 static int qcow2_set_key(BlockDriverState *bs, const char *key)
1204 BDRVQcow2State *s = bs->opaque;
1205 uint8_t keybuf[16];
1206 int len, i;
1207 Error *err = NULL;
1209 memset(keybuf, 0, 16);
1210 len = strlen(key);
1211 if (len > 16)
1212 len = 16;
1213 /* XXX: we could compress the chars to 7 bits to increase
1214 entropy */
1215 for(i = 0;i < len;i++) {
1216 keybuf[i] = key[i];
1218 assert(bs->encrypted);
1220 qcrypto_cipher_free(s->cipher);
1221 s->cipher = qcrypto_cipher_new(
1222 QCRYPTO_CIPHER_ALG_AES_128,
1223 QCRYPTO_CIPHER_MODE_CBC,
1224 keybuf, G_N_ELEMENTS(keybuf),
1225 &err);
1227 if (!s->cipher) {
1228 /* XXX would be nice if errors in this method could
1229 * be properly propagate to the caller. Would need
1230 * the bdrv_set_key() API signature to be fixed. */
1231 error_free(err);
1232 return -1;
1234 return 0;
1237 static int qcow2_reopen_prepare(BDRVReopenState *state,
1238 BlockReopenQueue *queue, Error **errp)
1240 Qcow2ReopenState *r;
1241 int ret;
1243 r = g_new0(Qcow2ReopenState, 1);
1244 state->opaque = r;
1246 ret = qcow2_update_options_prepare(state->bs, r, state->options,
1247 state->flags, errp);
1248 if (ret < 0) {
1249 goto fail;
1252 /* We need to write out any unwritten data if we reopen read-only. */
1253 if ((state->flags & BDRV_O_RDWR) == 0) {
1254 ret = bdrv_flush(state->bs);
1255 if (ret < 0) {
1256 goto fail;
1259 ret = qcow2_mark_clean(state->bs);
1260 if (ret < 0) {
1261 goto fail;
1265 return 0;
1267 fail:
1268 qcow2_update_options_abort(state->bs, r);
1269 g_free(r);
1270 return ret;
1273 static void qcow2_reopen_commit(BDRVReopenState *state)
1275 qcow2_update_options_commit(state->bs, state->opaque);
1276 g_free(state->opaque);
1279 static void qcow2_reopen_abort(BDRVReopenState *state)
1281 qcow2_update_options_abort(state->bs, state->opaque);
1282 g_free(state->opaque);
1285 static void qcow2_join_options(QDict *options, QDict *old_options)
1287 bool has_new_overlap_template =
1288 qdict_haskey(options, QCOW2_OPT_OVERLAP) ||
1289 qdict_haskey(options, QCOW2_OPT_OVERLAP_TEMPLATE);
1290 bool has_new_total_cache_size =
1291 qdict_haskey(options, QCOW2_OPT_CACHE_SIZE);
1292 bool has_all_cache_options;
1294 /* New overlap template overrides all old overlap options */
1295 if (has_new_overlap_template) {
1296 qdict_del(old_options, QCOW2_OPT_OVERLAP);
1297 qdict_del(old_options, QCOW2_OPT_OVERLAP_TEMPLATE);
1298 qdict_del(old_options, QCOW2_OPT_OVERLAP_MAIN_HEADER);
1299 qdict_del(old_options, QCOW2_OPT_OVERLAP_ACTIVE_L1);
1300 qdict_del(old_options, QCOW2_OPT_OVERLAP_ACTIVE_L2);
1301 qdict_del(old_options, QCOW2_OPT_OVERLAP_REFCOUNT_TABLE);
1302 qdict_del(old_options, QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK);
1303 qdict_del(old_options, QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE);
1304 qdict_del(old_options, QCOW2_OPT_OVERLAP_INACTIVE_L1);
1305 qdict_del(old_options, QCOW2_OPT_OVERLAP_INACTIVE_L2);
1308 /* New total cache size overrides all old options */
1309 if (qdict_haskey(options, QCOW2_OPT_CACHE_SIZE)) {
1310 qdict_del(old_options, QCOW2_OPT_L2_CACHE_SIZE);
1311 qdict_del(old_options, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
1314 qdict_join(options, old_options, false);
1317 * If after merging all cache size options are set, an old total size is
1318 * overwritten. Do keep all options, however, if all three are new. The
1319 * resulting error message is what we want to happen.
1321 has_all_cache_options =
1322 qdict_haskey(options, QCOW2_OPT_CACHE_SIZE) ||
1323 qdict_haskey(options, QCOW2_OPT_L2_CACHE_SIZE) ||
1324 qdict_haskey(options, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
1326 if (has_all_cache_options && !has_new_total_cache_size) {
1327 qdict_del(options, QCOW2_OPT_CACHE_SIZE);
1331 static int64_t coroutine_fn qcow2_co_get_block_status(BlockDriverState *bs,
1332 int64_t sector_num, int nb_sectors, int *pnum)
1334 BDRVQcow2State *s = bs->opaque;
1335 uint64_t cluster_offset;
1336 int index_in_cluster, ret;
1337 int64_t status = 0;
1339 *pnum = nb_sectors;
1340 qemu_co_mutex_lock(&s->lock);
1341 ret = qcow2_get_cluster_offset(bs, sector_num << 9, pnum, &cluster_offset);
1342 qemu_co_mutex_unlock(&s->lock);
1343 if (ret < 0) {
1344 return ret;
1347 if (cluster_offset != 0 && ret != QCOW2_CLUSTER_COMPRESSED &&
1348 !s->cipher) {
1349 index_in_cluster = sector_num & (s->cluster_sectors - 1);
1350 cluster_offset |= (index_in_cluster << BDRV_SECTOR_BITS);
1351 status |= BDRV_BLOCK_OFFSET_VALID | cluster_offset;
1353 if (ret == QCOW2_CLUSTER_ZERO) {
1354 status |= BDRV_BLOCK_ZERO;
1355 } else if (ret != QCOW2_CLUSTER_UNALLOCATED) {
1356 status |= BDRV_BLOCK_DATA;
1358 return status;
1361 /* handle reading after the end of the backing file */
1362 int qcow2_backing_read1(BlockDriverState *bs, QEMUIOVector *qiov,
1363 int64_t sector_num, int nb_sectors)
1365 int n1;
1366 if ((sector_num + nb_sectors) <= bs->total_sectors)
1367 return nb_sectors;
1368 if (sector_num >= bs->total_sectors)
1369 n1 = 0;
1370 else
1371 n1 = bs->total_sectors - sector_num;
1373 qemu_iovec_memset(qiov, 512 * n1, 0, 512 * (nb_sectors - n1));
1375 return n1;
1378 static coroutine_fn int qcow2_co_readv(BlockDriverState *bs, int64_t sector_num,
1379 int remaining_sectors, QEMUIOVector *qiov)
1381 BDRVQcow2State *s = bs->opaque;
1382 int index_in_cluster, n1;
1383 int ret;
1384 int cur_nr_sectors; /* number of sectors in current iteration */
1385 uint64_t cluster_offset = 0;
1386 uint64_t bytes_done = 0;
1387 QEMUIOVector hd_qiov;
1388 uint8_t *cluster_data = NULL;
1390 qemu_iovec_init(&hd_qiov, qiov->niov);
1392 qemu_co_mutex_lock(&s->lock);
1394 while (remaining_sectors != 0) {
1396 /* prepare next request */
1397 cur_nr_sectors = remaining_sectors;
1398 if (s->cipher) {
1399 cur_nr_sectors = MIN(cur_nr_sectors,
1400 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors);
1403 ret = qcow2_get_cluster_offset(bs, sector_num << 9,
1404 &cur_nr_sectors, &cluster_offset);
1405 if (ret < 0) {
1406 goto fail;
1409 index_in_cluster = sector_num & (s->cluster_sectors - 1);
1411 qemu_iovec_reset(&hd_qiov);
1412 qemu_iovec_concat(&hd_qiov, qiov, bytes_done,
1413 cur_nr_sectors * 512);
1415 switch (ret) {
1416 case QCOW2_CLUSTER_UNALLOCATED:
1418 if (bs->backing) {
1419 /* read from the base image */
1420 n1 = qcow2_backing_read1(bs->backing->bs, &hd_qiov,
1421 sector_num, cur_nr_sectors);
1422 if (n1 > 0) {
1423 QEMUIOVector local_qiov;
1425 qemu_iovec_init(&local_qiov, hd_qiov.niov);
1426 qemu_iovec_concat(&local_qiov, &hd_qiov, 0,
1427 n1 * BDRV_SECTOR_SIZE);
1429 BLKDBG_EVENT(bs->file, BLKDBG_READ_BACKING_AIO);
1430 qemu_co_mutex_unlock(&s->lock);
1431 ret = bdrv_co_readv(bs->backing->bs, sector_num,
1432 n1, &local_qiov);
1433 qemu_co_mutex_lock(&s->lock);
1435 qemu_iovec_destroy(&local_qiov);
1437 if (ret < 0) {
1438 goto fail;
1441 } else {
1442 /* Note: in this case, no need to wait */
1443 qemu_iovec_memset(&hd_qiov, 0, 0, 512 * cur_nr_sectors);
1445 break;
1447 case QCOW2_CLUSTER_ZERO:
1448 qemu_iovec_memset(&hd_qiov, 0, 0, 512 * cur_nr_sectors);
1449 break;
1451 case QCOW2_CLUSTER_COMPRESSED:
1452 /* add AIO support for compressed blocks ? */
1453 ret = qcow2_decompress_cluster(bs, cluster_offset);
1454 if (ret < 0) {
1455 goto fail;
1458 qemu_iovec_from_buf(&hd_qiov, 0,
1459 s->cluster_cache + index_in_cluster * 512,
1460 512 * cur_nr_sectors);
1461 break;
1463 case QCOW2_CLUSTER_NORMAL:
1464 if ((cluster_offset & 511) != 0) {
1465 ret = -EIO;
1466 goto fail;
1469 if (bs->encrypted) {
1470 assert(s->cipher);
1473 * For encrypted images, read everything into a temporary
1474 * contiguous buffer on which the AES functions can work.
1476 if (!cluster_data) {
1477 cluster_data =
1478 qemu_try_blockalign(bs->file->bs,
1479 QCOW_MAX_CRYPT_CLUSTERS
1480 * s->cluster_size);
1481 if (cluster_data == NULL) {
1482 ret = -ENOMEM;
1483 goto fail;
1487 assert(cur_nr_sectors <=
1488 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors);
1489 qemu_iovec_reset(&hd_qiov);
1490 qemu_iovec_add(&hd_qiov, cluster_data,
1491 512 * cur_nr_sectors);
1494 BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);
1495 qemu_co_mutex_unlock(&s->lock);
1496 ret = bdrv_co_readv(bs->file->bs,
1497 (cluster_offset >> 9) + index_in_cluster,
1498 cur_nr_sectors, &hd_qiov);
1499 qemu_co_mutex_lock(&s->lock);
1500 if (ret < 0) {
1501 goto fail;
1503 if (bs->encrypted) {
1504 assert(s->cipher);
1505 Error *err = NULL;
1506 if (qcow2_encrypt_sectors(s, sector_num, cluster_data,
1507 cluster_data, cur_nr_sectors, false,
1508 &err) < 0) {
1509 error_free(err);
1510 ret = -EIO;
1511 goto fail;
1513 qemu_iovec_from_buf(qiov, bytes_done,
1514 cluster_data, 512 * cur_nr_sectors);
1516 break;
1518 default:
1519 g_assert_not_reached();
1520 ret = -EIO;
1521 goto fail;
1524 remaining_sectors -= cur_nr_sectors;
1525 sector_num += cur_nr_sectors;
1526 bytes_done += cur_nr_sectors * 512;
1528 ret = 0;
1530 fail:
1531 qemu_co_mutex_unlock(&s->lock);
1533 qemu_iovec_destroy(&hd_qiov);
1534 qemu_vfree(cluster_data);
1536 return ret;
1539 static coroutine_fn int qcow2_co_writev(BlockDriverState *bs,
1540 int64_t sector_num,
1541 int remaining_sectors,
1542 QEMUIOVector *qiov)
1544 BDRVQcow2State *s = bs->opaque;
1545 int index_in_cluster;
1546 int ret;
1547 int cur_nr_sectors; /* number of sectors in current iteration */
1548 uint64_t cluster_offset;
1549 QEMUIOVector hd_qiov;
1550 uint64_t bytes_done = 0;
1551 uint8_t *cluster_data = NULL;
1552 QCowL2Meta *l2meta = NULL;
1554 trace_qcow2_writev_start_req(qemu_coroutine_self(), sector_num,
1555 remaining_sectors);
1557 qemu_iovec_init(&hd_qiov, qiov->niov);
1559 s->cluster_cache_offset = -1; /* disable compressed cache */
1561 qemu_co_mutex_lock(&s->lock);
1563 while (remaining_sectors != 0) {
1565 l2meta = NULL;
1567 trace_qcow2_writev_start_part(qemu_coroutine_self());
1568 index_in_cluster = sector_num & (s->cluster_sectors - 1);
1569 cur_nr_sectors = remaining_sectors;
1570 if (bs->encrypted &&
1571 cur_nr_sectors >
1572 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors - index_in_cluster) {
1573 cur_nr_sectors =
1574 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors - index_in_cluster;
1577 ret = qcow2_alloc_cluster_offset(bs, sector_num << 9,
1578 &cur_nr_sectors, &cluster_offset, &l2meta);
1579 if (ret < 0) {
1580 goto fail;
1583 assert((cluster_offset & 511) == 0);
1585 qemu_iovec_reset(&hd_qiov);
1586 qemu_iovec_concat(&hd_qiov, qiov, bytes_done,
1587 cur_nr_sectors * 512);
1589 if (bs->encrypted) {
1590 Error *err = NULL;
1591 assert(s->cipher);
1592 if (!cluster_data) {
1593 cluster_data = qemu_try_blockalign(bs->file->bs,
1594 QCOW_MAX_CRYPT_CLUSTERS
1595 * s->cluster_size);
1596 if (cluster_data == NULL) {
1597 ret = -ENOMEM;
1598 goto fail;
1602 assert(hd_qiov.size <=
1603 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
1604 qemu_iovec_to_buf(&hd_qiov, 0, cluster_data, hd_qiov.size);
1606 if (qcow2_encrypt_sectors(s, sector_num, cluster_data,
1607 cluster_data, cur_nr_sectors,
1608 true, &err) < 0) {
1609 error_free(err);
1610 ret = -EIO;
1611 goto fail;
1614 qemu_iovec_reset(&hd_qiov);
1615 qemu_iovec_add(&hd_qiov, cluster_data,
1616 cur_nr_sectors * 512);
1619 ret = qcow2_pre_write_overlap_check(bs, 0,
1620 cluster_offset + index_in_cluster * BDRV_SECTOR_SIZE,
1621 cur_nr_sectors * BDRV_SECTOR_SIZE);
1622 if (ret < 0) {
1623 goto fail;
1626 qemu_co_mutex_unlock(&s->lock);
1627 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO);
1628 trace_qcow2_writev_data(qemu_coroutine_self(),
1629 (cluster_offset >> 9) + index_in_cluster);
1630 ret = bdrv_co_writev(bs->file->bs,
1631 (cluster_offset >> 9) + index_in_cluster,
1632 cur_nr_sectors, &hd_qiov);
1633 qemu_co_mutex_lock(&s->lock);
1634 if (ret < 0) {
1635 goto fail;
1638 while (l2meta != NULL) {
1639 QCowL2Meta *next;
1641 ret = qcow2_alloc_cluster_link_l2(bs, l2meta);
1642 if (ret < 0) {
1643 goto fail;
1646 /* Take the request off the list of running requests */
1647 if (l2meta->nb_clusters != 0) {
1648 QLIST_REMOVE(l2meta, next_in_flight);
1651 qemu_co_queue_restart_all(&l2meta->dependent_requests);
1653 next = l2meta->next;
1654 g_free(l2meta);
1655 l2meta = next;
1658 remaining_sectors -= cur_nr_sectors;
1659 sector_num += cur_nr_sectors;
1660 bytes_done += cur_nr_sectors * 512;
1661 trace_qcow2_writev_done_part(qemu_coroutine_self(), cur_nr_sectors);
1663 ret = 0;
1665 fail:
1666 qemu_co_mutex_unlock(&s->lock);
1668 while (l2meta != NULL) {
1669 QCowL2Meta *next;
1671 if (l2meta->nb_clusters != 0) {
1672 QLIST_REMOVE(l2meta, next_in_flight);
1674 qemu_co_queue_restart_all(&l2meta->dependent_requests);
1676 next = l2meta->next;
1677 g_free(l2meta);
1678 l2meta = next;
1681 qemu_iovec_destroy(&hd_qiov);
1682 qemu_vfree(cluster_data);
1683 trace_qcow2_writev_done_req(qemu_coroutine_self(), ret);
1685 return ret;
1688 static void qcow2_close(BlockDriverState *bs)
1690 BDRVQcow2State *s = bs->opaque;
1691 qemu_vfree(s->l1_table);
1692 /* else pre-write overlap checks in cache_destroy may crash */
1693 s->l1_table = NULL;
1695 if (!(bs->open_flags & BDRV_O_INCOMING)) {
1696 int ret1, ret2;
1698 ret1 = qcow2_cache_flush(bs, s->l2_table_cache);
1699 ret2 = qcow2_cache_flush(bs, s->refcount_block_cache);
1701 if (ret1) {
1702 error_report("Failed to flush the L2 table cache: %s",
1703 strerror(-ret1));
1705 if (ret2) {
1706 error_report("Failed to flush the refcount block cache: %s",
1707 strerror(-ret2));
1710 if (!ret1 && !ret2) {
1711 qcow2_mark_clean(bs);
1715 cache_clean_timer_del(bs);
1716 qcow2_cache_destroy(bs, s->l2_table_cache);
1717 qcow2_cache_destroy(bs, s->refcount_block_cache);
1719 qcrypto_cipher_free(s->cipher);
1720 s->cipher = NULL;
1722 g_free(s->unknown_header_fields);
1723 cleanup_unknown_header_ext(bs);
1725 g_free(s->image_backing_file);
1726 g_free(s->image_backing_format);
1728 g_free(s->cluster_cache);
1729 qemu_vfree(s->cluster_data);
1730 qcow2_refcount_close(bs);
1731 qcow2_free_snapshots(bs);
1734 static void qcow2_invalidate_cache(BlockDriverState *bs, Error **errp)
1736 BDRVQcow2State *s = bs->opaque;
1737 int flags = s->flags;
1738 QCryptoCipher *cipher = NULL;
1739 QDict *options;
1740 Error *local_err = NULL;
1741 int ret;
1744 * Backing files are read-only which makes all of their metadata immutable,
1745 * that means we don't have to worry about reopening them here.
1748 cipher = s->cipher;
1749 s->cipher = NULL;
1751 qcow2_close(bs);
1753 bdrv_invalidate_cache(bs->file->bs, &local_err);
1754 if (local_err) {
1755 error_propagate(errp, local_err);
1756 return;
1759 memset(s, 0, sizeof(BDRVQcow2State));
1760 options = qdict_clone_shallow(bs->options);
1762 ret = qcow2_open(bs, options, flags, &local_err);
1763 QDECREF(options);
1764 if (local_err) {
1765 error_setg(errp, "Could not reopen qcow2 layer: %s",
1766 error_get_pretty(local_err));
1767 error_free(local_err);
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 Qcow2Feature features[] = {
1900 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
1901 .bit = QCOW2_INCOMPAT_DIRTY_BITNR,
1902 .name = "dirty bit",
1905 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
1906 .bit = QCOW2_INCOMPAT_CORRUPT_BITNR,
1907 .name = "corrupt bit",
1910 .type = QCOW2_FEAT_TYPE_COMPATIBLE,
1911 .bit = QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR,
1912 .name = "lazy refcounts",
1916 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_FEATURE_TABLE,
1917 features, sizeof(features), buflen);
1918 if (ret < 0) {
1919 goto fail;
1921 buf += ret;
1922 buflen -= ret;
1924 /* Keep unknown header extensions */
1925 QLIST_FOREACH(uext, &s->unknown_header_ext, next) {
1926 ret = header_ext_add(buf, uext->magic, uext->data, uext->len, buflen);
1927 if (ret < 0) {
1928 goto fail;
1931 buf += ret;
1932 buflen -= ret;
1935 /* End of header extensions */
1936 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_END, NULL, 0, buflen);
1937 if (ret < 0) {
1938 goto fail;
1941 buf += ret;
1942 buflen -= ret;
1944 /* Backing file name */
1945 if (s->image_backing_file) {
1946 size_t backing_file_len = strlen(s->image_backing_file);
1948 if (buflen < backing_file_len) {
1949 ret = -ENOSPC;
1950 goto fail;
1953 /* Using strncpy is ok here, since buf is not NUL-terminated. */
1954 strncpy(buf, s->image_backing_file, buflen);
1956 header->backing_file_offset = cpu_to_be64(buf - ((char*) header));
1957 header->backing_file_size = cpu_to_be32(backing_file_len);
1960 /* Write the new header */
1961 ret = bdrv_pwrite(bs->file->bs, 0, header, s->cluster_size);
1962 if (ret < 0) {
1963 goto fail;
1966 ret = 0;
1967 fail:
1968 qemu_vfree(header);
1969 return ret;
1972 static int qcow2_change_backing_file(BlockDriverState *bs,
1973 const char *backing_file, const char *backing_fmt)
1975 BDRVQcow2State *s = bs->opaque;
1977 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
1978 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
1980 g_free(s->image_backing_file);
1981 g_free(s->image_backing_format);
1983 s->image_backing_file = backing_file ? g_strdup(bs->backing_file) : NULL;
1984 s->image_backing_format = backing_fmt ? g_strdup(bs->backing_format) : NULL;
1986 return qcow2_update_header(bs);
1989 static int preallocate(BlockDriverState *bs)
1991 uint64_t nb_sectors;
1992 uint64_t offset;
1993 uint64_t host_offset = 0;
1994 int num;
1995 int ret;
1996 QCowL2Meta *meta;
1998 nb_sectors = bdrv_nb_sectors(bs);
1999 offset = 0;
2001 while (nb_sectors) {
2002 num = MIN(nb_sectors, INT_MAX >> BDRV_SECTOR_BITS);
2003 ret = qcow2_alloc_cluster_offset(bs, offset, &num,
2004 &host_offset, &meta);
2005 if (ret < 0) {
2006 return ret;
2009 while (meta) {
2010 QCowL2Meta *next = meta->next;
2012 ret = qcow2_alloc_cluster_link_l2(bs, meta);
2013 if (ret < 0) {
2014 qcow2_free_any_clusters(bs, meta->alloc_offset,
2015 meta->nb_clusters, QCOW2_DISCARD_NEVER);
2016 return ret;
2019 /* There are no dependent requests, but we need to remove our
2020 * request from the list of in-flight requests */
2021 QLIST_REMOVE(meta, next_in_flight);
2023 g_free(meta);
2024 meta = next;
2027 /* TODO Preallocate data if requested */
2029 nb_sectors -= num;
2030 offset += num << BDRV_SECTOR_BITS;
2034 * It is expected that the image file is large enough to actually contain
2035 * all of the allocated clusters (otherwise we get failing reads after
2036 * EOF). Extend the image to the last allocated sector.
2038 if (host_offset != 0) {
2039 uint8_t buf[BDRV_SECTOR_SIZE];
2040 memset(buf, 0, BDRV_SECTOR_SIZE);
2041 ret = bdrv_write(bs->file->bs,
2042 (host_offset >> BDRV_SECTOR_BITS) + num - 1,
2043 buf, 1);
2044 if (ret < 0) {
2045 return ret;
2049 return 0;
2052 static int qcow2_create2(const char *filename, int64_t total_size,
2053 const char *backing_file, const char *backing_format,
2054 int flags, size_t cluster_size, PreallocMode prealloc,
2055 QemuOpts *opts, int version, int refcount_order,
2056 Error **errp)
2058 int cluster_bits;
2059 QDict *options;
2061 /* Calculate cluster_bits */
2062 cluster_bits = ctz32(cluster_size);
2063 if (cluster_bits < MIN_CLUSTER_BITS || cluster_bits > MAX_CLUSTER_BITS ||
2064 (1 << cluster_bits) != cluster_size)
2066 error_setg(errp, "Cluster size must be a power of two between %d and "
2067 "%dk", 1 << MIN_CLUSTER_BITS, 1 << (MAX_CLUSTER_BITS - 10));
2068 return -EINVAL;
2072 * Open the image file and write a minimal qcow2 header.
2074 * We keep things simple and start with a zero-sized image. We also
2075 * do without refcount blocks or a L1 table for now. We'll fix the
2076 * inconsistency later.
2078 * We do need a refcount table because growing the refcount table means
2079 * allocating two new refcount blocks - the seconds of which would be at
2080 * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
2081 * size for any qcow2 image.
2083 BlockDriverState* bs;
2084 QCowHeader *header;
2085 uint64_t* refcount_table;
2086 Error *local_err = NULL;
2087 int ret;
2089 if (prealloc == PREALLOC_MODE_FULL || prealloc == PREALLOC_MODE_FALLOC) {
2090 /* Note: The following calculation does not need to be exact; if it is a
2091 * bit off, either some bytes will be "leaked" (which is fine) or we
2092 * will need to increase the file size by some bytes (which is fine,
2093 * too, as long as the bulk is allocated here). Therefore, using
2094 * floating point arithmetic is fine. */
2095 int64_t meta_size = 0;
2096 uint64_t nreftablee, nrefblocke, nl1e, nl2e;
2097 int64_t aligned_total_size = align_offset(total_size, cluster_size);
2098 int refblock_bits, refblock_size;
2099 /* refcount entry size in bytes */
2100 double rces = (1 << refcount_order) / 8.;
2102 /* see qcow2_open() */
2103 refblock_bits = cluster_bits - (refcount_order - 3);
2104 refblock_size = 1 << refblock_bits;
2106 /* header: 1 cluster */
2107 meta_size += cluster_size;
2109 /* total size of L2 tables */
2110 nl2e = aligned_total_size / cluster_size;
2111 nl2e = align_offset(nl2e, cluster_size / sizeof(uint64_t));
2112 meta_size += nl2e * sizeof(uint64_t);
2114 /* total size of L1 tables */
2115 nl1e = nl2e * sizeof(uint64_t) / cluster_size;
2116 nl1e = align_offset(nl1e, cluster_size / sizeof(uint64_t));
2117 meta_size += nl1e * sizeof(uint64_t);
2119 /* total size of refcount blocks
2121 * note: every host cluster is reference-counted, including metadata
2122 * (even refcount blocks are recursively included).
2123 * Let:
2124 * a = total_size (this is the guest disk size)
2125 * m = meta size not including refcount blocks and refcount tables
2126 * c = cluster size
2127 * y1 = number of refcount blocks entries
2128 * y2 = meta size including everything
2129 * rces = refcount entry size in bytes
2130 * then,
2131 * y1 = (y2 + a)/c
2132 * y2 = y1 * rces + y1 * rces * sizeof(u64) / c + m
2133 * we can get y1:
2134 * y1 = (a + m) / (c - rces - rces * sizeof(u64) / c)
2136 nrefblocke = (aligned_total_size + meta_size + cluster_size)
2137 / (cluster_size - rces - rces * sizeof(uint64_t)
2138 / cluster_size);
2139 meta_size += DIV_ROUND_UP(nrefblocke, refblock_size) * cluster_size;
2141 /* total size of refcount tables */
2142 nreftablee = nrefblocke / refblock_size;
2143 nreftablee = align_offset(nreftablee, cluster_size / sizeof(uint64_t));
2144 meta_size += nreftablee * sizeof(uint64_t);
2146 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
2147 aligned_total_size + meta_size, &error_abort);
2148 qemu_opt_set(opts, BLOCK_OPT_PREALLOC, PreallocMode_lookup[prealloc],
2149 &error_abort);
2152 ret = bdrv_create_file(filename, opts, &local_err);
2153 if (ret < 0) {
2154 error_propagate(errp, local_err);
2155 return ret;
2158 bs = NULL;
2159 ret = bdrv_open(&bs, filename, NULL, NULL, BDRV_O_RDWR | BDRV_O_PROTOCOL,
2160 &local_err);
2161 if (ret < 0) {
2162 error_propagate(errp, local_err);
2163 return ret;
2166 /* Write the header */
2167 QEMU_BUILD_BUG_ON((1 << MIN_CLUSTER_BITS) < sizeof(*header));
2168 header = g_malloc0(cluster_size);
2169 *header = (QCowHeader) {
2170 .magic = cpu_to_be32(QCOW_MAGIC),
2171 .version = cpu_to_be32(version),
2172 .cluster_bits = cpu_to_be32(cluster_bits),
2173 .size = cpu_to_be64(0),
2174 .l1_table_offset = cpu_to_be64(0),
2175 .l1_size = cpu_to_be32(0),
2176 .refcount_table_offset = cpu_to_be64(cluster_size),
2177 .refcount_table_clusters = cpu_to_be32(1),
2178 .refcount_order = cpu_to_be32(refcount_order),
2179 .header_length = cpu_to_be32(sizeof(*header)),
2182 if (flags & BLOCK_FLAG_ENCRYPT) {
2183 header->crypt_method = cpu_to_be32(QCOW_CRYPT_AES);
2184 } else {
2185 header->crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
2188 if (flags & BLOCK_FLAG_LAZY_REFCOUNTS) {
2189 header->compatible_features |=
2190 cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS);
2193 ret = bdrv_pwrite(bs, 0, header, cluster_size);
2194 g_free(header);
2195 if (ret < 0) {
2196 error_setg_errno(errp, -ret, "Could not write qcow2 header");
2197 goto out;
2200 /* Write a refcount table with one refcount block */
2201 refcount_table = g_malloc0(2 * cluster_size);
2202 refcount_table[0] = cpu_to_be64(2 * cluster_size);
2203 ret = bdrv_pwrite(bs, cluster_size, refcount_table, 2 * cluster_size);
2204 g_free(refcount_table);
2206 if (ret < 0) {
2207 error_setg_errno(errp, -ret, "Could not write refcount table");
2208 goto out;
2211 bdrv_unref(bs);
2212 bs = NULL;
2215 * And now open the image and make it consistent first (i.e. increase the
2216 * refcount of the cluster that is occupied by the header and the refcount
2217 * table)
2219 options = qdict_new();
2220 qdict_put(options, "driver", qstring_from_str("qcow2"));
2221 ret = bdrv_open(&bs, filename, NULL, options,
2222 BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_NO_FLUSH,
2223 &local_err);
2224 if (ret < 0) {
2225 error_propagate(errp, local_err);
2226 goto out;
2229 ret = qcow2_alloc_clusters(bs, 3 * cluster_size);
2230 if (ret < 0) {
2231 error_setg_errno(errp, -ret, "Could not allocate clusters for qcow2 "
2232 "header and refcount table");
2233 goto out;
2235 } else if (ret != 0) {
2236 error_report("Huh, first cluster in empty image is already in use?");
2237 abort();
2240 /* Okay, now that we have a valid image, let's give it the right size */
2241 ret = bdrv_truncate(bs, total_size);
2242 if (ret < 0) {
2243 error_setg_errno(errp, -ret, "Could not resize image");
2244 goto out;
2247 /* Want a backing file? There you go.*/
2248 if (backing_file) {
2249 ret = bdrv_change_backing_file(bs, backing_file, backing_format);
2250 if (ret < 0) {
2251 error_setg_errno(errp, -ret, "Could not assign backing file '%s' "
2252 "with format '%s'", backing_file, backing_format);
2253 goto out;
2257 /* And if we're supposed to preallocate metadata, do that now */
2258 if (prealloc != PREALLOC_MODE_OFF) {
2259 BDRVQcow2State *s = bs->opaque;
2260 qemu_co_mutex_lock(&s->lock);
2261 ret = preallocate(bs);
2262 qemu_co_mutex_unlock(&s->lock);
2263 if (ret < 0) {
2264 error_setg_errno(errp, -ret, "Could not preallocate metadata");
2265 goto out;
2269 bdrv_unref(bs);
2270 bs = NULL;
2272 /* Reopen the image without BDRV_O_NO_FLUSH to flush it before returning */
2273 options = qdict_new();
2274 qdict_put(options, "driver", qstring_from_str("qcow2"));
2275 ret = bdrv_open(&bs, filename, NULL, options,
2276 BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_NO_BACKING,
2277 &local_err);
2278 if (local_err) {
2279 error_propagate(errp, local_err);
2280 goto out;
2283 ret = 0;
2284 out:
2285 if (bs) {
2286 bdrv_unref(bs);
2288 return ret;
2291 static int qcow2_create(const char *filename, QemuOpts *opts, Error **errp)
2293 char *backing_file = NULL;
2294 char *backing_fmt = NULL;
2295 char *buf = NULL;
2296 uint64_t size = 0;
2297 int flags = 0;
2298 size_t cluster_size = DEFAULT_CLUSTER_SIZE;
2299 PreallocMode prealloc;
2300 int version = 3;
2301 uint64_t refcount_bits = 16;
2302 int refcount_order;
2303 Error *local_err = NULL;
2304 int ret;
2306 /* Read out options */
2307 size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
2308 BDRV_SECTOR_SIZE);
2309 backing_file = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
2310 backing_fmt = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FMT);
2311 if (qemu_opt_get_bool_del(opts, BLOCK_OPT_ENCRYPT, false)) {
2312 flags |= BLOCK_FLAG_ENCRYPT;
2314 cluster_size = qemu_opt_get_size_del(opts, BLOCK_OPT_CLUSTER_SIZE,
2315 DEFAULT_CLUSTER_SIZE);
2316 buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
2317 prealloc = qapi_enum_parse(PreallocMode_lookup, buf,
2318 PREALLOC_MODE__MAX, PREALLOC_MODE_OFF,
2319 &local_err);
2320 if (local_err) {
2321 error_propagate(errp, local_err);
2322 ret = -EINVAL;
2323 goto finish;
2325 g_free(buf);
2326 buf = qemu_opt_get_del(opts, BLOCK_OPT_COMPAT_LEVEL);
2327 if (!buf) {
2328 /* keep the default */
2329 } else if (!strcmp(buf, "0.10")) {
2330 version = 2;
2331 } else if (!strcmp(buf, "1.1")) {
2332 version = 3;
2333 } else {
2334 error_setg(errp, "Invalid compatibility level: '%s'", buf);
2335 ret = -EINVAL;
2336 goto finish;
2339 if (qemu_opt_get_bool_del(opts, BLOCK_OPT_LAZY_REFCOUNTS, false)) {
2340 flags |= BLOCK_FLAG_LAZY_REFCOUNTS;
2343 if (backing_file && prealloc != PREALLOC_MODE_OFF) {
2344 error_setg(errp, "Backing file and preallocation cannot be used at "
2345 "the same time");
2346 ret = -EINVAL;
2347 goto finish;
2350 if (version < 3 && (flags & BLOCK_FLAG_LAZY_REFCOUNTS)) {
2351 error_setg(errp, "Lazy refcounts only supported with compatibility "
2352 "level 1.1 and above (use compat=1.1 or greater)");
2353 ret = -EINVAL;
2354 goto finish;
2357 refcount_bits = qemu_opt_get_number_del(opts, BLOCK_OPT_REFCOUNT_BITS,
2358 refcount_bits);
2359 if (refcount_bits > 64 || !is_power_of_2(refcount_bits)) {
2360 error_setg(errp, "Refcount width must be a power of two and may not "
2361 "exceed 64 bits");
2362 ret = -EINVAL;
2363 goto finish;
2366 if (version < 3 && refcount_bits != 16) {
2367 error_setg(errp, "Different refcount widths than 16 bits require "
2368 "compatibility level 1.1 or above (use compat=1.1 or "
2369 "greater)");
2370 ret = -EINVAL;
2371 goto finish;
2374 refcount_order = ctz32(refcount_bits);
2376 ret = qcow2_create2(filename, size, backing_file, backing_fmt, flags,
2377 cluster_size, prealloc, opts, version, refcount_order,
2378 &local_err);
2379 if (local_err) {
2380 error_propagate(errp, local_err);
2383 finish:
2384 g_free(backing_file);
2385 g_free(backing_fmt);
2386 g_free(buf);
2387 return ret;
2390 static coroutine_fn int qcow2_co_write_zeroes(BlockDriverState *bs,
2391 int64_t sector_num, int nb_sectors, BdrvRequestFlags flags)
2393 int ret;
2394 BDRVQcow2State *s = bs->opaque;
2396 /* Emulate misaligned zero writes */
2397 if (sector_num % s->cluster_sectors || nb_sectors % s->cluster_sectors) {
2398 return -ENOTSUP;
2401 /* Whatever is left can use real zero clusters */
2402 qemu_co_mutex_lock(&s->lock);
2403 ret = qcow2_zero_clusters(bs, sector_num << BDRV_SECTOR_BITS,
2404 nb_sectors);
2405 qemu_co_mutex_unlock(&s->lock);
2407 return ret;
2410 static coroutine_fn int qcow2_co_discard(BlockDriverState *bs,
2411 int64_t sector_num, int nb_sectors)
2413 int ret;
2414 BDRVQcow2State *s = bs->opaque;
2416 qemu_co_mutex_lock(&s->lock);
2417 ret = qcow2_discard_clusters(bs, sector_num << BDRV_SECTOR_BITS,
2418 nb_sectors, QCOW2_DISCARD_REQUEST, false);
2419 qemu_co_mutex_unlock(&s->lock);
2420 return ret;
2423 static int qcow2_truncate(BlockDriverState *bs, int64_t offset)
2425 BDRVQcow2State *s = bs->opaque;
2426 int64_t new_l1_size;
2427 int ret;
2429 if (offset & 511) {
2430 error_report("The new size must be a multiple of 512");
2431 return -EINVAL;
2434 /* cannot proceed if image has snapshots */
2435 if (s->nb_snapshots) {
2436 error_report("Can't resize an image which has snapshots");
2437 return -ENOTSUP;
2440 /* shrinking is currently not supported */
2441 if (offset < bs->total_sectors * 512) {
2442 error_report("qcow2 doesn't support shrinking images yet");
2443 return -ENOTSUP;
2446 new_l1_size = size_to_l1(s, offset);
2447 ret = qcow2_grow_l1_table(bs, new_l1_size, true);
2448 if (ret < 0) {
2449 return ret;
2452 /* write updated header.size */
2453 offset = cpu_to_be64(offset);
2454 ret = bdrv_pwrite_sync(bs->file->bs, offsetof(QCowHeader, size),
2455 &offset, sizeof(uint64_t));
2456 if (ret < 0) {
2457 return ret;
2460 s->l1_vm_state_index = new_l1_size;
2461 return 0;
2464 /* XXX: put compressed sectors first, then all the cluster aligned
2465 tables to avoid losing bytes in alignment */
2466 static int qcow2_write_compressed(BlockDriverState *bs, int64_t sector_num,
2467 const uint8_t *buf, int nb_sectors)
2469 BDRVQcow2State *s = bs->opaque;
2470 z_stream strm;
2471 int ret, out_len;
2472 uint8_t *out_buf;
2473 uint64_t cluster_offset;
2475 if (nb_sectors == 0) {
2476 /* align end of file to a sector boundary to ease reading with
2477 sector based I/Os */
2478 cluster_offset = bdrv_getlength(bs->file->bs);
2479 return bdrv_truncate(bs->file->bs, cluster_offset);
2482 if (nb_sectors != s->cluster_sectors) {
2483 ret = -EINVAL;
2485 /* Zero-pad last write if image size is not cluster aligned */
2486 if (sector_num + nb_sectors == bs->total_sectors &&
2487 nb_sectors < s->cluster_sectors) {
2488 uint8_t *pad_buf = qemu_blockalign(bs, s->cluster_size);
2489 memset(pad_buf, 0, s->cluster_size);
2490 memcpy(pad_buf, buf, nb_sectors * BDRV_SECTOR_SIZE);
2491 ret = qcow2_write_compressed(bs, sector_num,
2492 pad_buf, s->cluster_sectors);
2493 qemu_vfree(pad_buf);
2495 return ret;
2498 out_buf = g_malloc(s->cluster_size + (s->cluster_size / 1000) + 128);
2500 /* best compression, small window, no zlib header */
2501 memset(&strm, 0, sizeof(strm));
2502 ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
2503 Z_DEFLATED, -12,
2504 9, Z_DEFAULT_STRATEGY);
2505 if (ret != 0) {
2506 ret = -EINVAL;
2507 goto fail;
2510 strm.avail_in = s->cluster_size;
2511 strm.next_in = (uint8_t *)buf;
2512 strm.avail_out = s->cluster_size;
2513 strm.next_out = out_buf;
2515 ret = deflate(&strm, Z_FINISH);
2516 if (ret != Z_STREAM_END && ret != Z_OK) {
2517 deflateEnd(&strm);
2518 ret = -EINVAL;
2519 goto fail;
2521 out_len = strm.next_out - out_buf;
2523 deflateEnd(&strm);
2525 if (ret != Z_STREAM_END || out_len >= s->cluster_size) {
2526 /* could not compress: write normal cluster */
2527 ret = bdrv_write(bs, sector_num, buf, s->cluster_sectors);
2528 if (ret < 0) {
2529 goto fail;
2531 } else {
2532 cluster_offset = qcow2_alloc_compressed_cluster_offset(bs,
2533 sector_num << 9, out_len);
2534 if (!cluster_offset) {
2535 ret = -EIO;
2536 goto fail;
2538 cluster_offset &= s->cluster_offset_mask;
2540 ret = qcow2_pre_write_overlap_check(bs, 0, cluster_offset, out_len);
2541 if (ret < 0) {
2542 goto fail;
2545 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_COMPRESSED);
2546 ret = bdrv_pwrite(bs->file->bs, cluster_offset, out_buf, out_len);
2547 if (ret < 0) {
2548 goto fail;
2552 ret = 0;
2553 fail:
2554 g_free(out_buf);
2555 return ret;
2558 static int make_completely_empty(BlockDriverState *bs)
2560 BDRVQcow2State *s = bs->opaque;
2561 int ret, l1_clusters;
2562 int64_t offset;
2563 uint64_t *new_reftable = NULL;
2564 uint64_t rt_entry, l1_size2;
2565 struct {
2566 uint64_t l1_offset;
2567 uint64_t reftable_offset;
2568 uint32_t reftable_clusters;
2569 } QEMU_PACKED l1_ofs_rt_ofs_cls;
2571 ret = qcow2_cache_empty(bs, s->l2_table_cache);
2572 if (ret < 0) {
2573 goto fail;
2576 ret = qcow2_cache_empty(bs, s->refcount_block_cache);
2577 if (ret < 0) {
2578 goto fail;
2581 /* Refcounts will be broken utterly */
2582 ret = qcow2_mark_dirty(bs);
2583 if (ret < 0) {
2584 goto fail;
2587 BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
2589 l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / sizeof(uint64_t));
2590 l1_size2 = (uint64_t)s->l1_size * sizeof(uint64_t);
2592 /* After this call, neither the in-memory nor the on-disk refcount
2593 * information accurately describe the actual references */
2595 ret = bdrv_write_zeroes(bs->file->bs, s->l1_table_offset / BDRV_SECTOR_SIZE,
2596 l1_clusters * s->cluster_sectors, 0);
2597 if (ret < 0) {
2598 goto fail_broken_refcounts;
2600 memset(s->l1_table, 0, l1_size2);
2602 BLKDBG_EVENT(bs->file, BLKDBG_EMPTY_IMAGE_PREPARE);
2604 /* Overwrite enough clusters at the beginning of the sectors to place
2605 * the refcount table, a refcount block and the L1 table in; this may
2606 * overwrite parts of the existing refcount and L1 table, which is not
2607 * an issue because the dirty flag is set, complete data loss is in fact
2608 * desired and partial data loss is consequently fine as well */
2609 ret = bdrv_write_zeroes(bs->file->bs, s->cluster_size / BDRV_SECTOR_SIZE,
2610 (2 + l1_clusters) * s->cluster_size /
2611 BDRV_SECTOR_SIZE, 0);
2612 /* This call (even if it failed overall) may have overwritten on-disk
2613 * refcount structures; in that case, the in-memory refcount information
2614 * will probably differ from the on-disk information which makes the BDS
2615 * unusable */
2616 if (ret < 0) {
2617 goto fail_broken_refcounts;
2620 BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
2621 BLKDBG_EVENT(bs->file, BLKDBG_REFTABLE_UPDATE);
2623 /* "Create" an empty reftable (one cluster) directly after the image
2624 * header and an empty L1 table three clusters after the image header;
2625 * the cluster between those two will be used as the first refblock */
2626 cpu_to_be64w(&l1_ofs_rt_ofs_cls.l1_offset, 3 * s->cluster_size);
2627 cpu_to_be64w(&l1_ofs_rt_ofs_cls.reftable_offset, s->cluster_size);
2628 cpu_to_be32w(&l1_ofs_rt_ofs_cls.reftable_clusters, 1);
2629 ret = bdrv_pwrite_sync(bs->file->bs, offsetof(QCowHeader, l1_table_offset),
2630 &l1_ofs_rt_ofs_cls, sizeof(l1_ofs_rt_ofs_cls));
2631 if (ret < 0) {
2632 goto fail_broken_refcounts;
2635 s->l1_table_offset = 3 * s->cluster_size;
2637 new_reftable = g_try_new0(uint64_t, s->cluster_size / sizeof(uint64_t));
2638 if (!new_reftable) {
2639 ret = -ENOMEM;
2640 goto fail_broken_refcounts;
2643 s->refcount_table_offset = s->cluster_size;
2644 s->refcount_table_size = s->cluster_size / sizeof(uint64_t);
2646 g_free(s->refcount_table);
2647 s->refcount_table = new_reftable;
2648 new_reftable = NULL;
2650 /* Now the in-memory refcount information again corresponds to the on-disk
2651 * information (reftable is empty and no refblocks (the refblock cache is
2652 * empty)); however, this means some clusters (e.g. the image header) are
2653 * referenced, but not refcounted, but the normal qcow2 code assumes that
2654 * the in-memory information is always correct */
2656 BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_ALLOC);
2658 /* Enter the first refblock into the reftable */
2659 rt_entry = cpu_to_be64(2 * s->cluster_size);
2660 ret = bdrv_pwrite_sync(bs->file->bs, s->cluster_size,
2661 &rt_entry, sizeof(rt_entry));
2662 if (ret < 0) {
2663 goto fail_broken_refcounts;
2665 s->refcount_table[0] = 2 * s->cluster_size;
2667 s->free_cluster_index = 0;
2668 assert(3 + l1_clusters <= s->refcount_block_size);
2669 offset = qcow2_alloc_clusters(bs, 3 * s->cluster_size + l1_size2);
2670 if (offset < 0) {
2671 ret = offset;
2672 goto fail_broken_refcounts;
2673 } else if (offset > 0) {
2674 error_report("First cluster in emptied image is in use");
2675 abort();
2678 /* Now finally the in-memory information corresponds to the on-disk
2679 * structures and is correct */
2680 ret = qcow2_mark_clean(bs);
2681 if (ret < 0) {
2682 goto fail;
2685 ret = bdrv_truncate(bs->file->bs, (3 + l1_clusters) * s->cluster_size);
2686 if (ret < 0) {
2687 goto fail;
2690 return 0;
2692 fail_broken_refcounts:
2693 /* The BDS is unusable at this point. If we wanted to make it usable, we
2694 * would have to call qcow2_refcount_close(), qcow2_refcount_init(),
2695 * qcow2_check_refcounts(), qcow2_refcount_close() and qcow2_refcount_init()
2696 * again. However, because the functions which could have caused this error
2697 * path to be taken are used by those functions as well, it's very likely
2698 * that that sequence will fail as well. Therefore, just eject the BDS. */
2699 bs->drv = NULL;
2701 fail:
2702 g_free(new_reftable);
2703 return ret;
2706 static int qcow2_make_empty(BlockDriverState *bs)
2708 BDRVQcow2State *s = bs->opaque;
2709 uint64_t start_sector;
2710 int sector_step = INT_MAX / BDRV_SECTOR_SIZE;
2711 int l1_clusters, ret = 0;
2713 l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / sizeof(uint64_t));
2715 if (s->qcow_version >= 3 && !s->snapshots &&
2716 3 + l1_clusters <= s->refcount_block_size) {
2717 /* The following function only works for qcow2 v3 images (it requires
2718 * the dirty flag) and only as long as there are no snapshots (because
2719 * it completely empties the image). Furthermore, the L1 table and three
2720 * additional clusters (image header, refcount table, one refcount
2721 * block) have to fit inside one refcount block. */
2722 return make_completely_empty(bs);
2725 /* This fallback code simply discards every active cluster; this is slow,
2726 * but works in all cases */
2727 for (start_sector = 0; start_sector < bs->total_sectors;
2728 start_sector += sector_step)
2730 /* As this function is generally used after committing an external
2731 * snapshot, QCOW2_DISCARD_SNAPSHOT seems appropriate. Also, the
2732 * default action for this kind of discard is to pass the discard,
2733 * which will ideally result in an actually smaller image file, as
2734 * is probably desired. */
2735 ret = qcow2_discard_clusters(bs, start_sector * BDRV_SECTOR_SIZE,
2736 MIN(sector_step,
2737 bs->total_sectors - start_sector),
2738 QCOW2_DISCARD_SNAPSHOT, true);
2739 if (ret < 0) {
2740 break;
2744 return ret;
2747 static coroutine_fn int qcow2_co_flush_to_os(BlockDriverState *bs)
2749 BDRVQcow2State *s = bs->opaque;
2750 int ret;
2752 qemu_co_mutex_lock(&s->lock);
2753 ret = qcow2_cache_flush(bs, s->l2_table_cache);
2754 if (ret < 0) {
2755 qemu_co_mutex_unlock(&s->lock);
2756 return ret;
2759 if (qcow2_need_accurate_refcounts(s)) {
2760 ret = qcow2_cache_flush(bs, s->refcount_block_cache);
2761 if (ret < 0) {
2762 qemu_co_mutex_unlock(&s->lock);
2763 return ret;
2766 qemu_co_mutex_unlock(&s->lock);
2768 return 0;
2771 static int qcow2_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
2773 BDRVQcow2State *s = bs->opaque;
2774 bdi->unallocated_blocks_are_zero = true;
2775 bdi->can_write_zeroes_with_unmap = (s->qcow_version >= 3);
2776 bdi->cluster_size = s->cluster_size;
2777 bdi->vm_state_offset = qcow2_vm_state_offset(s);
2778 return 0;
2781 static ImageInfoSpecific *qcow2_get_specific_info(BlockDriverState *bs)
2783 BDRVQcow2State *s = bs->opaque;
2784 ImageInfoSpecific *spec_info = g_new(ImageInfoSpecific, 1);
2786 *spec_info = (ImageInfoSpecific){
2787 .type = IMAGE_INFO_SPECIFIC_KIND_QCOW2,
2788 .u.qcow2 = g_new(ImageInfoSpecificQCow2, 1),
2790 if (s->qcow_version == 2) {
2791 *spec_info->u.qcow2 = (ImageInfoSpecificQCow2){
2792 .compat = g_strdup("0.10"),
2793 .refcount_bits = s->refcount_bits,
2795 } else if (s->qcow_version == 3) {
2796 *spec_info->u.qcow2 = (ImageInfoSpecificQCow2){
2797 .compat = g_strdup("1.1"),
2798 .lazy_refcounts = s->compatible_features &
2799 QCOW2_COMPAT_LAZY_REFCOUNTS,
2800 .has_lazy_refcounts = true,
2801 .corrupt = s->incompatible_features &
2802 QCOW2_INCOMPAT_CORRUPT,
2803 .has_corrupt = true,
2804 .refcount_bits = s->refcount_bits,
2806 } else {
2807 /* if this assertion fails, this probably means a new version was
2808 * added without having it covered here */
2809 assert(false);
2812 return spec_info;
2815 #if 0
2816 static void dump_refcounts(BlockDriverState *bs)
2818 BDRVQcow2State *s = bs->opaque;
2819 int64_t nb_clusters, k, k1, size;
2820 int refcount;
2822 size = bdrv_getlength(bs->file->bs);
2823 nb_clusters = size_to_clusters(s, size);
2824 for(k = 0; k < nb_clusters;) {
2825 k1 = k;
2826 refcount = get_refcount(bs, k);
2827 k++;
2828 while (k < nb_clusters && get_refcount(bs, k) == refcount)
2829 k++;
2830 printf("%" PRId64 ": refcount=%d nb=%" PRId64 "\n", k, refcount,
2831 k - k1);
2834 #endif
2836 static int qcow2_save_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
2837 int64_t pos)
2839 BDRVQcow2State *s = bs->opaque;
2840 int64_t total_sectors = bs->total_sectors;
2841 bool zero_beyond_eof = bs->zero_beyond_eof;
2842 int ret;
2844 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_SAVE);
2845 bs->zero_beyond_eof = false;
2846 ret = bdrv_pwritev(bs, qcow2_vm_state_offset(s) + pos, qiov);
2847 bs->zero_beyond_eof = zero_beyond_eof;
2849 /* bdrv_co_do_writev will have increased the total_sectors value to include
2850 * the VM state - the VM state is however not an actual part of the block
2851 * device, therefore, we need to restore the old value. */
2852 bs->total_sectors = total_sectors;
2854 return ret;
2857 static int qcow2_load_vmstate(BlockDriverState *bs, uint8_t *buf,
2858 int64_t pos, int size)
2860 BDRVQcow2State *s = bs->opaque;
2861 bool zero_beyond_eof = bs->zero_beyond_eof;
2862 int ret;
2864 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_LOAD);
2865 bs->zero_beyond_eof = false;
2866 ret = bdrv_pread(bs, qcow2_vm_state_offset(s) + pos, buf, size);
2867 bs->zero_beyond_eof = zero_beyond_eof;
2869 return ret;
2873 * Downgrades an image's version. To achieve this, any incompatible features
2874 * have to be removed.
2876 static int qcow2_downgrade(BlockDriverState *bs, int target_version,
2877 BlockDriverAmendStatusCB *status_cb, void *cb_opaque)
2879 BDRVQcow2State *s = bs->opaque;
2880 int current_version = s->qcow_version;
2881 int ret;
2883 if (target_version == current_version) {
2884 return 0;
2885 } else if (target_version > current_version) {
2886 return -EINVAL;
2887 } else if (target_version != 2) {
2888 return -EINVAL;
2891 if (s->refcount_order != 4) {
2892 error_report("compat=0.10 requires refcount_bits=16");
2893 return -ENOTSUP;
2896 /* clear incompatible features */
2897 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
2898 ret = qcow2_mark_clean(bs);
2899 if (ret < 0) {
2900 return ret;
2904 /* with QCOW2_INCOMPAT_CORRUPT, it is pretty much impossible to get here in
2905 * the first place; if that happens nonetheless, returning -ENOTSUP is the
2906 * best thing to do anyway */
2908 if (s->incompatible_features) {
2909 return -ENOTSUP;
2912 /* since we can ignore compatible features, we can set them to 0 as well */
2913 s->compatible_features = 0;
2914 /* if lazy refcounts have been used, they have already been fixed through
2915 * clearing the dirty flag */
2917 /* clearing autoclear features is trivial */
2918 s->autoclear_features = 0;
2920 ret = qcow2_expand_zero_clusters(bs, status_cb, cb_opaque);
2921 if (ret < 0) {
2922 return ret;
2925 s->qcow_version = target_version;
2926 ret = qcow2_update_header(bs);
2927 if (ret < 0) {
2928 s->qcow_version = current_version;
2929 return ret;
2931 return 0;
2934 typedef enum Qcow2AmendOperation {
2935 /* This is the value Qcow2AmendHelperCBInfo::last_operation will be
2936 * statically initialized to so that the helper CB can discern the first
2937 * invocation from an operation change */
2938 QCOW2_NO_OPERATION = 0,
2940 QCOW2_CHANGING_REFCOUNT_ORDER,
2941 QCOW2_DOWNGRADING,
2942 } Qcow2AmendOperation;
2944 typedef struct Qcow2AmendHelperCBInfo {
2945 /* The code coordinating the amend operations should only modify
2946 * these four fields; the rest will be managed by the CB */
2947 BlockDriverAmendStatusCB *original_status_cb;
2948 void *original_cb_opaque;
2950 Qcow2AmendOperation current_operation;
2952 /* Total number of operations to perform (only set once) */
2953 int total_operations;
2955 /* The following fields are managed by the CB */
2957 /* Number of operations completed */
2958 int operations_completed;
2960 /* Cumulative offset of all completed operations */
2961 int64_t offset_completed;
2963 Qcow2AmendOperation last_operation;
2964 int64_t last_work_size;
2965 } Qcow2AmendHelperCBInfo;
2967 static void qcow2_amend_helper_cb(BlockDriverState *bs,
2968 int64_t operation_offset,
2969 int64_t operation_work_size, void *opaque)
2971 Qcow2AmendHelperCBInfo *info = opaque;
2972 int64_t current_work_size;
2973 int64_t projected_work_size;
2975 if (info->current_operation != info->last_operation) {
2976 if (info->last_operation != QCOW2_NO_OPERATION) {
2977 info->offset_completed += info->last_work_size;
2978 info->operations_completed++;
2981 info->last_operation = info->current_operation;
2984 assert(info->total_operations > 0);
2985 assert(info->operations_completed < info->total_operations);
2987 info->last_work_size = operation_work_size;
2989 current_work_size = info->offset_completed + operation_work_size;
2991 /* current_work_size is the total work size for (operations_completed + 1)
2992 * operations (which includes this one), so multiply it by the number of
2993 * operations not covered and divide it by the number of operations
2994 * covered to get a projection for the operations not covered */
2995 projected_work_size = current_work_size * (info->total_operations -
2996 info->operations_completed - 1)
2997 / (info->operations_completed + 1);
2999 info->original_status_cb(bs, info->offset_completed + operation_offset,
3000 current_work_size + projected_work_size,
3001 info->original_cb_opaque);
3004 static int qcow2_amend_options(BlockDriverState *bs, QemuOpts *opts,
3005 BlockDriverAmendStatusCB *status_cb,
3006 void *cb_opaque)
3008 BDRVQcow2State *s = bs->opaque;
3009 int old_version = s->qcow_version, new_version = old_version;
3010 uint64_t new_size = 0;
3011 const char *backing_file = NULL, *backing_format = NULL;
3012 bool lazy_refcounts = s->use_lazy_refcounts;
3013 const char *compat = NULL;
3014 uint64_t cluster_size = s->cluster_size;
3015 bool encrypt;
3016 int refcount_bits = s->refcount_bits;
3017 int ret;
3018 QemuOptDesc *desc = opts->list->desc;
3019 Qcow2AmendHelperCBInfo helper_cb_info;
3021 while (desc && desc->name) {
3022 if (!qemu_opt_find(opts, desc->name)) {
3023 /* only change explicitly defined options */
3024 desc++;
3025 continue;
3028 if (!strcmp(desc->name, BLOCK_OPT_COMPAT_LEVEL)) {
3029 compat = qemu_opt_get(opts, BLOCK_OPT_COMPAT_LEVEL);
3030 if (!compat) {
3031 /* preserve default */
3032 } else if (!strcmp(compat, "0.10")) {
3033 new_version = 2;
3034 } else if (!strcmp(compat, "1.1")) {
3035 new_version = 3;
3036 } else {
3037 error_report("Unknown compatibility level %s", compat);
3038 return -EINVAL;
3040 } else if (!strcmp(desc->name, BLOCK_OPT_PREALLOC)) {
3041 error_report("Cannot change preallocation mode");
3042 return -ENOTSUP;
3043 } else if (!strcmp(desc->name, BLOCK_OPT_SIZE)) {
3044 new_size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, 0);
3045 } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FILE)) {
3046 backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
3047 } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FMT)) {
3048 backing_format = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
3049 } else if (!strcmp(desc->name, BLOCK_OPT_ENCRYPT)) {
3050 encrypt = qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT,
3051 !!s->cipher);
3053 if (encrypt != !!s->cipher) {
3054 error_report("Changing the encryption flag is not supported");
3055 return -ENOTSUP;
3057 } else if (!strcmp(desc->name, BLOCK_OPT_CLUSTER_SIZE)) {
3058 cluster_size = qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE,
3059 cluster_size);
3060 if (cluster_size != s->cluster_size) {
3061 error_report("Changing the cluster size is not supported");
3062 return -ENOTSUP;
3064 } else if (!strcmp(desc->name, BLOCK_OPT_LAZY_REFCOUNTS)) {
3065 lazy_refcounts = qemu_opt_get_bool(opts, BLOCK_OPT_LAZY_REFCOUNTS,
3066 lazy_refcounts);
3067 } else if (!strcmp(desc->name, BLOCK_OPT_REFCOUNT_BITS)) {
3068 refcount_bits = qemu_opt_get_number(opts, BLOCK_OPT_REFCOUNT_BITS,
3069 refcount_bits);
3071 if (refcount_bits <= 0 || refcount_bits > 64 ||
3072 !is_power_of_2(refcount_bits))
3074 error_report("Refcount width must be a power of two and may "
3075 "not exceed 64 bits");
3076 return -EINVAL;
3078 } else {
3079 /* if this point is reached, this probably means a new option was
3080 * added without having it covered here */
3081 abort();
3084 desc++;
3087 helper_cb_info = (Qcow2AmendHelperCBInfo){
3088 .original_status_cb = status_cb,
3089 .original_cb_opaque = cb_opaque,
3090 .total_operations = (new_version < old_version)
3091 + (s->refcount_bits != refcount_bits)
3094 /* Upgrade first (some features may require compat=1.1) */
3095 if (new_version > old_version) {
3096 s->qcow_version = new_version;
3097 ret = qcow2_update_header(bs);
3098 if (ret < 0) {
3099 s->qcow_version = old_version;
3100 return ret;
3104 if (s->refcount_bits != refcount_bits) {
3105 int refcount_order = ctz32(refcount_bits);
3106 Error *local_error = NULL;
3108 if (new_version < 3 && refcount_bits != 16) {
3109 error_report("Different refcount widths than 16 bits require "
3110 "compatibility level 1.1 or above (use compat=1.1 or "
3111 "greater)");
3112 return -EINVAL;
3115 helper_cb_info.current_operation = QCOW2_CHANGING_REFCOUNT_ORDER;
3116 ret = qcow2_change_refcount_order(bs, refcount_order,
3117 &qcow2_amend_helper_cb,
3118 &helper_cb_info, &local_error);
3119 if (ret < 0) {
3120 error_report_err(local_error);
3121 return ret;
3125 if (backing_file || backing_format) {
3126 ret = qcow2_change_backing_file(bs,
3127 backing_file ?: s->image_backing_file,
3128 backing_format ?: s->image_backing_format);
3129 if (ret < 0) {
3130 return ret;
3134 if (s->use_lazy_refcounts != lazy_refcounts) {
3135 if (lazy_refcounts) {
3136 if (new_version < 3) {
3137 error_report("Lazy refcounts only supported with compatibility "
3138 "level 1.1 and above (use compat=1.1 or greater)");
3139 return -EINVAL;
3141 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
3142 ret = qcow2_update_header(bs);
3143 if (ret < 0) {
3144 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
3145 return ret;
3147 s->use_lazy_refcounts = true;
3148 } else {
3149 /* make image clean first */
3150 ret = qcow2_mark_clean(bs);
3151 if (ret < 0) {
3152 return ret;
3154 /* now disallow lazy refcounts */
3155 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
3156 ret = qcow2_update_header(bs);
3157 if (ret < 0) {
3158 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
3159 return ret;
3161 s->use_lazy_refcounts = false;
3165 if (new_size) {
3166 ret = bdrv_truncate(bs, new_size);
3167 if (ret < 0) {
3168 return ret;
3172 /* Downgrade last (so unsupported features can be removed before) */
3173 if (new_version < old_version) {
3174 helper_cb_info.current_operation = QCOW2_DOWNGRADING;
3175 ret = qcow2_downgrade(bs, new_version, &qcow2_amend_helper_cb,
3176 &helper_cb_info);
3177 if (ret < 0) {
3178 return ret;
3182 return 0;
3186 * If offset or size are negative, respectively, they will not be included in
3187 * the BLOCK_IMAGE_CORRUPTED event emitted.
3188 * fatal will be ignored for read-only BDS; corruptions found there will always
3189 * be considered non-fatal.
3191 void qcow2_signal_corruption(BlockDriverState *bs, bool fatal, int64_t offset,
3192 int64_t size, const char *message_format, ...)
3194 BDRVQcow2State *s = bs->opaque;
3195 const char *node_name;
3196 char *message;
3197 va_list ap;
3199 fatal = fatal && !bs->read_only;
3201 if (s->signaled_corruption &&
3202 (!fatal || (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT)))
3204 return;
3207 va_start(ap, message_format);
3208 message = g_strdup_vprintf(message_format, ap);
3209 va_end(ap);
3211 if (fatal) {
3212 fprintf(stderr, "qcow2: Marking image as corrupt: %s; further "
3213 "corruption events will be suppressed\n", message);
3214 } else {
3215 fprintf(stderr, "qcow2: Image is corrupt: %s; further non-fatal "
3216 "corruption events will be suppressed\n", message);
3219 node_name = bdrv_get_node_name(bs);
3220 qapi_event_send_block_image_corrupted(bdrv_get_device_name(bs),
3221 *node_name != '\0', node_name,
3222 message, offset >= 0, offset,
3223 size >= 0, size,
3224 fatal, &error_abort);
3225 g_free(message);
3227 if (fatal) {
3228 qcow2_mark_corrupt(bs);
3229 bs->drv = NULL; /* make BDS unusable */
3232 s->signaled_corruption = true;
3235 static QemuOptsList qcow2_create_opts = {
3236 .name = "qcow2-create-opts",
3237 .head = QTAILQ_HEAD_INITIALIZER(qcow2_create_opts.head),
3238 .desc = {
3240 .name = BLOCK_OPT_SIZE,
3241 .type = QEMU_OPT_SIZE,
3242 .help = "Virtual disk size"
3245 .name = BLOCK_OPT_COMPAT_LEVEL,
3246 .type = QEMU_OPT_STRING,
3247 .help = "Compatibility level (0.10 or 1.1)"
3250 .name = BLOCK_OPT_BACKING_FILE,
3251 .type = QEMU_OPT_STRING,
3252 .help = "File name of a base image"
3255 .name = BLOCK_OPT_BACKING_FMT,
3256 .type = QEMU_OPT_STRING,
3257 .help = "Image format of the base image"
3260 .name = BLOCK_OPT_ENCRYPT,
3261 .type = QEMU_OPT_BOOL,
3262 .help = "Encrypt the image",
3263 .def_value_str = "off"
3266 .name = BLOCK_OPT_CLUSTER_SIZE,
3267 .type = QEMU_OPT_SIZE,
3268 .help = "qcow2 cluster size",
3269 .def_value_str = stringify(DEFAULT_CLUSTER_SIZE)
3272 .name = BLOCK_OPT_PREALLOC,
3273 .type = QEMU_OPT_STRING,
3274 .help = "Preallocation mode (allowed values: off, metadata, "
3275 "falloc, full)"
3278 .name = BLOCK_OPT_LAZY_REFCOUNTS,
3279 .type = QEMU_OPT_BOOL,
3280 .help = "Postpone refcount updates",
3281 .def_value_str = "off"
3284 .name = BLOCK_OPT_REFCOUNT_BITS,
3285 .type = QEMU_OPT_NUMBER,
3286 .help = "Width of a reference count entry in bits",
3287 .def_value_str = "16"
3289 { /* end of list */ }
3293 BlockDriver bdrv_qcow2 = {
3294 .format_name = "qcow2",
3295 .instance_size = sizeof(BDRVQcow2State),
3296 .bdrv_probe = qcow2_probe,
3297 .bdrv_open = qcow2_open,
3298 .bdrv_close = qcow2_close,
3299 .bdrv_reopen_prepare = qcow2_reopen_prepare,
3300 .bdrv_reopen_commit = qcow2_reopen_commit,
3301 .bdrv_reopen_abort = qcow2_reopen_abort,
3302 .bdrv_join_options = qcow2_join_options,
3303 .bdrv_create = qcow2_create,
3304 .bdrv_has_zero_init = bdrv_has_zero_init_1,
3305 .bdrv_co_get_block_status = qcow2_co_get_block_status,
3306 .bdrv_set_key = qcow2_set_key,
3308 .bdrv_co_readv = qcow2_co_readv,
3309 .bdrv_co_writev = qcow2_co_writev,
3310 .bdrv_co_flush_to_os = qcow2_co_flush_to_os,
3312 .bdrv_co_write_zeroes = qcow2_co_write_zeroes,
3313 .bdrv_co_discard = qcow2_co_discard,
3314 .bdrv_truncate = qcow2_truncate,
3315 .bdrv_write_compressed = qcow2_write_compressed,
3316 .bdrv_make_empty = qcow2_make_empty,
3318 .bdrv_snapshot_create = qcow2_snapshot_create,
3319 .bdrv_snapshot_goto = qcow2_snapshot_goto,
3320 .bdrv_snapshot_delete = qcow2_snapshot_delete,
3321 .bdrv_snapshot_list = qcow2_snapshot_list,
3322 .bdrv_snapshot_load_tmp = qcow2_snapshot_load_tmp,
3323 .bdrv_get_info = qcow2_get_info,
3324 .bdrv_get_specific_info = qcow2_get_specific_info,
3326 .bdrv_save_vmstate = qcow2_save_vmstate,
3327 .bdrv_load_vmstate = qcow2_load_vmstate,
3329 .supports_backing = true,
3330 .bdrv_change_backing_file = qcow2_change_backing_file,
3332 .bdrv_refresh_limits = qcow2_refresh_limits,
3333 .bdrv_invalidate_cache = qcow2_invalidate_cache,
3335 .create_opts = &qcow2_create_opts,
3336 .bdrv_check = qcow2_check,
3337 .bdrv_amend_options = qcow2_amend_options,
3339 .bdrv_detach_aio_context = qcow2_detach_aio_context,
3340 .bdrv_attach_aio_context = qcow2_attach_aio_context,
3343 static void bdrv_qcow2_init(void)
3345 bdrv_register(&bdrv_qcow2);
3348 block_init(bdrv_qcow2_init);