m25p80: fix test on blk_pread() return value
[qemu/ar7.git] / block / qcow2.c
blobcb55e2d8978127c20b21358ba56d2b2e509726be
1 /*
2 * Block driver for the QCOW version 2 format
4 * Copyright (c) 2004-2006 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
24 #include "qemu/osdep.h"
25 #include "block/block_int.h"
26 #include "sysemu/block-backend.h"
27 #include "qemu/module.h"
28 #include <zlib.h>
29 #include "block/qcow2.h"
30 #include "qemu/error-report.h"
31 #include "qapi/qmp/qerror.h"
32 #include "qapi/qmp/qbool.h"
33 #include "qapi/util.h"
34 #include "qapi/qmp/types.h"
35 #include "qapi-event.h"
36 #include "trace.h"
37 #include "qemu/option_int.h"
38 #include "qemu/cutils.h"
39 #include "qemu/bswap.h"
42 Differences with QCOW:
44 - Support for multiple incremental snapshots.
45 - Memory management by reference counts.
46 - Clusters which have a reference count of one have the bit
47 QCOW_OFLAG_COPIED to optimize write performance.
48 - Size of compressed clusters is stored in sectors to reduce bit usage
49 in the cluster offsets.
50 - Support for storing additional data (such as the VM state) in the
51 snapshots.
52 - If a backing store is used, the cluster size is not constrained
53 (could be backported to QCOW).
54 - L2 tables have always a size of one cluster.
58 typedef struct {
59 uint32_t magic;
60 uint32_t len;
61 } QEMU_PACKED QCowExtension;
63 #define QCOW2_EXT_MAGIC_END 0
64 #define QCOW2_EXT_MAGIC_BACKING_FORMAT 0xE2792ACA
65 #define QCOW2_EXT_MAGIC_FEATURE_TABLE 0x6803f857
67 static int qcow2_probe(const uint8_t *buf, int buf_size, const char *filename)
69 const QCowHeader *cow_header = (const void *)buf;
71 if (buf_size >= sizeof(QCowHeader) &&
72 be32_to_cpu(cow_header->magic) == QCOW_MAGIC &&
73 be32_to_cpu(cow_header->version) >= 2)
74 return 100;
75 else
76 return 0;
80 /*
81 * read qcow2 extension and fill bs
82 * start reading from start_offset
83 * finish reading upon magic of value 0 or when end_offset reached
84 * unknown magic is skipped (future extension this version knows nothing about)
85 * return 0 upon success, non-0 otherwise
87 static int qcow2_read_extensions(BlockDriverState *bs, uint64_t start_offset,
88 uint64_t end_offset, void **p_feature_table,
89 Error **errp)
91 BDRVQcow2State *s = bs->opaque;
92 QCowExtension ext;
93 uint64_t offset;
94 int ret;
96 #ifdef DEBUG_EXT
97 printf("qcow2_read_extensions: start=%ld end=%ld\n", start_offset, end_offset);
98 #endif
99 offset = start_offset;
100 while (offset < end_offset) {
102 #ifdef DEBUG_EXT
103 /* Sanity check */
104 if (offset > s->cluster_size)
105 printf("qcow2_read_extension: suspicious offset %lu\n", offset);
107 printf("attempting to read extended header in offset %lu\n", offset);
108 #endif
110 ret = bdrv_pread(bs->file->bs, offset, &ext, sizeof(ext));
111 if (ret < 0) {
112 error_setg_errno(errp, -ret, "qcow2_read_extension: ERROR: "
113 "pread fail from offset %" PRIu64, offset);
114 return 1;
116 be32_to_cpus(&ext.magic);
117 be32_to_cpus(&ext.len);
118 offset += sizeof(ext);
119 #ifdef DEBUG_EXT
120 printf("ext.magic = 0x%x\n", ext.magic);
121 #endif
122 if (offset > end_offset || ext.len > end_offset - offset) {
123 error_setg(errp, "Header extension too large");
124 return -EINVAL;
127 switch (ext.magic) {
128 case QCOW2_EXT_MAGIC_END:
129 return 0;
131 case QCOW2_EXT_MAGIC_BACKING_FORMAT:
132 if (ext.len >= sizeof(bs->backing_format)) {
133 error_setg(errp, "ERROR: ext_backing_format: len=%" PRIu32
134 " too large (>=%zu)", ext.len,
135 sizeof(bs->backing_format));
136 return 2;
138 ret = bdrv_pread(bs->file->bs, offset, bs->backing_format, ext.len);
139 if (ret < 0) {
140 error_setg_errno(errp, -ret, "ERROR: ext_backing_format: "
141 "Could not read format name");
142 return 3;
144 bs->backing_format[ext.len] = '\0';
145 s->image_backing_format = g_strdup(bs->backing_format);
146 #ifdef DEBUG_EXT
147 printf("Qcow2: Got format extension %s\n", bs->backing_format);
148 #endif
149 break;
151 case QCOW2_EXT_MAGIC_FEATURE_TABLE:
152 if (p_feature_table != NULL) {
153 void* feature_table = g_malloc0(ext.len + 2 * sizeof(Qcow2Feature));
154 ret = bdrv_pread(bs->file->bs, offset , feature_table, ext.len);
155 if (ret < 0) {
156 error_setg_errno(errp, -ret, "ERROR: ext_feature_table: "
157 "Could not read table");
158 return ret;
161 *p_feature_table = feature_table;
163 break;
165 default:
166 /* unknown magic - save it in case we need to rewrite the header */
168 Qcow2UnknownHeaderExtension *uext;
170 uext = g_malloc0(sizeof(*uext) + ext.len);
171 uext->magic = ext.magic;
172 uext->len = ext.len;
173 QLIST_INSERT_HEAD(&s->unknown_header_ext, uext, next);
175 ret = bdrv_pread(bs->file->bs, offset , uext->data, uext->len);
176 if (ret < 0) {
177 error_setg_errno(errp, -ret, "ERROR: unknown extension: "
178 "Could not read data");
179 return ret;
182 break;
185 offset += ((ext.len + 7) & ~7);
188 return 0;
191 static void cleanup_unknown_header_ext(BlockDriverState *bs)
193 BDRVQcow2State *s = bs->opaque;
194 Qcow2UnknownHeaderExtension *uext, *next;
196 QLIST_FOREACH_SAFE(uext, &s->unknown_header_ext, next, next) {
197 QLIST_REMOVE(uext, next);
198 g_free(uext);
202 static void report_unsupported_feature(Error **errp, Qcow2Feature *table,
203 uint64_t mask)
205 char *features = g_strdup("");
206 char *old;
208 while (table && table->name[0] != '\0') {
209 if (table->type == QCOW2_FEAT_TYPE_INCOMPATIBLE) {
210 if (mask & (1ULL << table->bit)) {
211 old = features;
212 features = g_strdup_printf("%s%s%.46s", old, *old ? ", " : "",
213 table->name);
214 g_free(old);
215 mask &= ~(1ULL << table->bit);
218 table++;
221 if (mask) {
222 old = features;
223 features = g_strdup_printf("%s%sUnknown incompatible feature: %" PRIx64,
224 old, *old ? ", " : "", mask);
225 g_free(old);
228 error_setg(errp, "Unsupported qcow2 feature(s): %s", features);
229 g_free(features);
233 * Sets the dirty bit and flushes afterwards if necessary.
235 * The incompatible_features bit is only set if the image file header was
236 * updated successfully. Therefore it is not required to check the return
237 * value of this function.
239 int qcow2_mark_dirty(BlockDriverState *bs)
241 BDRVQcow2State *s = bs->opaque;
242 uint64_t val;
243 int ret;
245 assert(s->qcow_version >= 3);
247 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
248 return 0; /* already dirty */
251 val = cpu_to_be64(s->incompatible_features | QCOW2_INCOMPAT_DIRTY);
252 ret = bdrv_pwrite(bs->file->bs, offsetof(QCowHeader, incompatible_features),
253 &val, sizeof(val));
254 if (ret < 0) {
255 return ret;
257 ret = bdrv_flush(bs->file->bs);
258 if (ret < 0) {
259 return ret;
262 /* Only treat image as dirty if the header was updated successfully */
263 s->incompatible_features |= QCOW2_INCOMPAT_DIRTY;
264 return 0;
268 * Clears the dirty bit and flushes before if necessary. Only call this
269 * function when there are no pending requests, it does not guard against
270 * concurrent requests dirtying the image.
272 static int qcow2_mark_clean(BlockDriverState *bs)
274 BDRVQcow2State *s = bs->opaque;
276 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
277 int ret;
279 s->incompatible_features &= ~QCOW2_INCOMPAT_DIRTY;
281 ret = bdrv_flush(bs);
282 if (ret < 0) {
283 return ret;
286 return qcow2_update_header(bs);
288 return 0;
292 * Marks the image as corrupt.
294 int qcow2_mark_corrupt(BlockDriverState *bs)
296 BDRVQcow2State *s = bs->opaque;
298 s->incompatible_features |= QCOW2_INCOMPAT_CORRUPT;
299 return qcow2_update_header(bs);
303 * Marks the image as consistent, i.e., unsets the corrupt bit, and flushes
304 * before if necessary.
306 int qcow2_mark_consistent(BlockDriverState *bs)
308 BDRVQcow2State *s = bs->opaque;
310 if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
311 int ret = bdrv_flush(bs);
312 if (ret < 0) {
313 return ret;
316 s->incompatible_features &= ~QCOW2_INCOMPAT_CORRUPT;
317 return qcow2_update_header(bs);
319 return 0;
322 static int qcow2_check(BlockDriverState *bs, BdrvCheckResult *result,
323 BdrvCheckMode fix)
325 int ret = qcow2_check_refcounts(bs, result, fix);
326 if (ret < 0) {
327 return ret;
330 if (fix && result->check_errors == 0 && result->corruptions == 0) {
331 ret = qcow2_mark_clean(bs);
332 if (ret < 0) {
333 return ret;
335 return qcow2_mark_consistent(bs);
337 return ret;
340 static int validate_table_offset(BlockDriverState *bs, uint64_t offset,
341 uint64_t entries, size_t entry_len)
343 BDRVQcow2State *s = bs->opaque;
344 uint64_t size;
346 /* Use signed INT64_MAX as the maximum even for uint64_t header fields,
347 * because values will be passed to qemu functions taking int64_t. */
348 if (entries > INT64_MAX / entry_len) {
349 return -EINVAL;
352 size = entries * entry_len;
354 if (INT64_MAX - size < offset) {
355 return -EINVAL;
358 /* Tables must be cluster aligned */
359 if (offset & (s->cluster_size - 1)) {
360 return -EINVAL;
363 return 0;
366 static QemuOptsList qcow2_runtime_opts = {
367 .name = "qcow2",
368 .head = QTAILQ_HEAD_INITIALIZER(qcow2_runtime_opts.head),
369 .desc = {
371 .name = QCOW2_OPT_LAZY_REFCOUNTS,
372 .type = QEMU_OPT_BOOL,
373 .help = "Postpone refcount updates",
376 .name = QCOW2_OPT_DISCARD_REQUEST,
377 .type = QEMU_OPT_BOOL,
378 .help = "Pass guest discard requests to the layer below",
381 .name = QCOW2_OPT_DISCARD_SNAPSHOT,
382 .type = QEMU_OPT_BOOL,
383 .help = "Generate discard requests when snapshot related space "
384 "is freed",
387 .name = QCOW2_OPT_DISCARD_OTHER,
388 .type = QEMU_OPT_BOOL,
389 .help = "Generate discard requests when other clusters are freed",
392 .name = QCOW2_OPT_OVERLAP,
393 .type = QEMU_OPT_STRING,
394 .help = "Selects which overlap checks to perform from a range of "
395 "templates (none, constant, cached, all)",
398 .name = QCOW2_OPT_OVERLAP_TEMPLATE,
399 .type = QEMU_OPT_STRING,
400 .help = "Selects which overlap checks to perform from a range of "
401 "templates (none, constant, cached, all)",
404 .name = QCOW2_OPT_OVERLAP_MAIN_HEADER,
405 .type = QEMU_OPT_BOOL,
406 .help = "Check for unintended writes into the main qcow2 header",
409 .name = QCOW2_OPT_OVERLAP_ACTIVE_L1,
410 .type = QEMU_OPT_BOOL,
411 .help = "Check for unintended writes into the active L1 table",
414 .name = QCOW2_OPT_OVERLAP_ACTIVE_L2,
415 .type = QEMU_OPT_BOOL,
416 .help = "Check for unintended writes into an active L2 table",
419 .name = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
420 .type = QEMU_OPT_BOOL,
421 .help = "Check for unintended writes into the refcount table",
424 .name = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
425 .type = QEMU_OPT_BOOL,
426 .help = "Check for unintended writes into a refcount block",
429 .name = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
430 .type = QEMU_OPT_BOOL,
431 .help = "Check for unintended writes into the snapshot table",
434 .name = QCOW2_OPT_OVERLAP_INACTIVE_L1,
435 .type = QEMU_OPT_BOOL,
436 .help = "Check for unintended writes into an inactive L1 table",
439 .name = QCOW2_OPT_OVERLAP_INACTIVE_L2,
440 .type = QEMU_OPT_BOOL,
441 .help = "Check for unintended writes into an inactive L2 table",
444 .name = QCOW2_OPT_CACHE_SIZE,
445 .type = QEMU_OPT_SIZE,
446 .help = "Maximum combined metadata (L2 tables and refcount blocks) "
447 "cache size",
450 .name = QCOW2_OPT_L2_CACHE_SIZE,
451 .type = QEMU_OPT_SIZE,
452 .help = "Maximum L2 table cache size",
455 .name = QCOW2_OPT_REFCOUNT_CACHE_SIZE,
456 .type = QEMU_OPT_SIZE,
457 .help = "Maximum refcount block cache size",
460 .name = QCOW2_OPT_CACHE_CLEAN_INTERVAL,
461 .type = QEMU_OPT_NUMBER,
462 .help = "Clean unused cache entries after this time (in seconds)",
464 { /* end of list */ }
468 static const char *overlap_bool_option_names[QCOW2_OL_MAX_BITNR] = {
469 [QCOW2_OL_MAIN_HEADER_BITNR] = QCOW2_OPT_OVERLAP_MAIN_HEADER,
470 [QCOW2_OL_ACTIVE_L1_BITNR] = QCOW2_OPT_OVERLAP_ACTIVE_L1,
471 [QCOW2_OL_ACTIVE_L2_BITNR] = QCOW2_OPT_OVERLAP_ACTIVE_L2,
472 [QCOW2_OL_REFCOUNT_TABLE_BITNR] = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
473 [QCOW2_OL_REFCOUNT_BLOCK_BITNR] = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
474 [QCOW2_OL_SNAPSHOT_TABLE_BITNR] = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
475 [QCOW2_OL_INACTIVE_L1_BITNR] = QCOW2_OPT_OVERLAP_INACTIVE_L1,
476 [QCOW2_OL_INACTIVE_L2_BITNR] = QCOW2_OPT_OVERLAP_INACTIVE_L2,
479 static void cache_clean_timer_cb(void *opaque)
481 BlockDriverState *bs = opaque;
482 BDRVQcow2State *s = bs->opaque;
483 qcow2_cache_clean_unused(bs, s->l2_table_cache);
484 qcow2_cache_clean_unused(bs, s->refcount_block_cache);
485 timer_mod(s->cache_clean_timer, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) +
486 (int64_t) s->cache_clean_interval * 1000);
489 static void cache_clean_timer_init(BlockDriverState *bs, AioContext *context)
491 BDRVQcow2State *s = bs->opaque;
492 if (s->cache_clean_interval > 0) {
493 s->cache_clean_timer = aio_timer_new(context, QEMU_CLOCK_VIRTUAL,
494 SCALE_MS, cache_clean_timer_cb,
495 bs);
496 timer_mod(s->cache_clean_timer, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) +
497 (int64_t) s->cache_clean_interval * 1000);
501 static void cache_clean_timer_del(BlockDriverState *bs)
503 BDRVQcow2State *s = bs->opaque;
504 if (s->cache_clean_timer) {
505 timer_del(s->cache_clean_timer);
506 timer_free(s->cache_clean_timer);
507 s->cache_clean_timer = NULL;
511 static void qcow2_detach_aio_context(BlockDriverState *bs)
513 cache_clean_timer_del(bs);
516 static void qcow2_attach_aio_context(BlockDriverState *bs,
517 AioContext *new_context)
519 cache_clean_timer_init(bs, new_context);
522 static void read_cache_sizes(BlockDriverState *bs, QemuOpts *opts,
523 uint64_t *l2_cache_size,
524 uint64_t *refcount_cache_size, Error **errp)
526 BDRVQcow2State *s = bs->opaque;
527 uint64_t combined_cache_size;
528 bool l2_cache_size_set, refcount_cache_size_set, combined_cache_size_set;
530 combined_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_CACHE_SIZE);
531 l2_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_L2_CACHE_SIZE);
532 refcount_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
534 combined_cache_size = qemu_opt_get_size(opts, QCOW2_OPT_CACHE_SIZE, 0);
535 *l2_cache_size = qemu_opt_get_size(opts, QCOW2_OPT_L2_CACHE_SIZE, 0);
536 *refcount_cache_size = qemu_opt_get_size(opts,
537 QCOW2_OPT_REFCOUNT_CACHE_SIZE, 0);
539 if (combined_cache_size_set) {
540 if (l2_cache_size_set && refcount_cache_size_set) {
541 error_setg(errp, QCOW2_OPT_CACHE_SIZE ", " QCOW2_OPT_L2_CACHE_SIZE
542 " and " QCOW2_OPT_REFCOUNT_CACHE_SIZE " may not be set "
543 "the same time");
544 return;
545 } else if (*l2_cache_size > combined_cache_size) {
546 error_setg(errp, QCOW2_OPT_L2_CACHE_SIZE " may not exceed "
547 QCOW2_OPT_CACHE_SIZE);
548 return;
549 } else if (*refcount_cache_size > combined_cache_size) {
550 error_setg(errp, QCOW2_OPT_REFCOUNT_CACHE_SIZE " may not exceed "
551 QCOW2_OPT_CACHE_SIZE);
552 return;
555 if (l2_cache_size_set) {
556 *refcount_cache_size = combined_cache_size - *l2_cache_size;
557 } else if (refcount_cache_size_set) {
558 *l2_cache_size = combined_cache_size - *refcount_cache_size;
559 } else {
560 *refcount_cache_size = combined_cache_size
561 / (DEFAULT_L2_REFCOUNT_SIZE_RATIO + 1);
562 *l2_cache_size = combined_cache_size - *refcount_cache_size;
564 } else {
565 if (!l2_cache_size_set && !refcount_cache_size_set) {
566 *l2_cache_size = MAX(DEFAULT_L2_CACHE_BYTE_SIZE,
567 (uint64_t)DEFAULT_L2_CACHE_CLUSTERS
568 * s->cluster_size);
569 *refcount_cache_size = *l2_cache_size
570 / DEFAULT_L2_REFCOUNT_SIZE_RATIO;
571 } else if (!l2_cache_size_set) {
572 *l2_cache_size = *refcount_cache_size
573 * DEFAULT_L2_REFCOUNT_SIZE_RATIO;
574 } else if (!refcount_cache_size_set) {
575 *refcount_cache_size = *l2_cache_size
576 / DEFAULT_L2_REFCOUNT_SIZE_RATIO;
581 typedef struct Qcow2ReopenState {
582 Qcow2Cache *l2_table_cache;
583 Qcow2Cache *refcount_block_cache;
584 bool use_lazy_refcounts;
585 int overlap_check;
586 bool discard_passthrough[QCOW2_DISCARD_MAX];
587 uint64_t cache_clean_interval;
588 } Qcow2ReopenState;
590 static int qcow2_update_options_prepare(BlockDriverState *bs,
591 Qcow2ReopenState *r,
592 QDict *options, int flags,
593 Error **errp)
595 BDRVQcow2State *s = bs->opaque;
596 QemuOpts *opts = NULL;
597 const char *opt_overlap_check, *opt_overlap_check_template;
598 int overlap_check_template = 0;
599 uint64_t l2_cache_size, refcount_cache_size;
600 int i;
601 Error *local_err = NULL;
602 int ret;
604 opts = qemu_opts_create(&qcow2_runtime_opts, NULL, 0, &error_abort);
605 qemu_opts_absorb_qdict(opts, options, &local_err);
606 if (local_err) {
607 error_propagate(errp, local_err);
608 ret = -EINVAL;
609 goto fail;
612 /* get L2 table/refcount block cache size from command line options */
613 read_cache_sizes(bs, opts, &l2_cache_size, &refcount_cache_size,
614 &local_err);
615 if (local_err) {
616 error_propagate(errp, local_err);
617 ret = -EINVAL;
618 goto fail;
621 l2_cache_size /= s->cluster_size;
622 if (l2_cache_size < MIN_L2_CACHE_SIZE) {
623 l2_cache_size = MIN_L2_CACHE_SIZE;
625 if (l2_cache_size > INT_MAX) {
626 error_setg(errp, "L2 cache size too big");
627 ret = -EINVAL;
628 goto fail;
631 refcount_cache_size /= s->cluster_size;
632 if (refcount_cache_size < MIN_REFCOUNT_CACHE_SIZE) {
633 refcount_cache_size = MIN_REFCOUNT_CACHE_SIZE;
635 if (refcount_cache_size > INT_MAX) {
636 error_setg(errp, "Refcount cache size too big");
637 ret = -EINVAL;
638 goto fail;
641 /* alloc new L2 table/refcount block cache, flush old one */
642 if (s->l2_table_cache) {
643 ret = qcow2_cache_flush(bs, s->l2_table_cache);
644 if (ret) {
645 error_setg_errno(errp, -ret, "Failed to flush the L2 table cache");
646 goto fail;
650 if (s->refcount_block_cache) {
651 ret = qcow2_cache_flush(bs, s->refcount_block_cache);
652 if (ret) {
653 error_setg_errno(errp, -ret,
654 "Failed to flush the refcount block cache");
655 goto fail;
659 r->l2_table_cache = qcow2_cache_create(bs, l2_cache_size);
660 r->refcount_block_cache = qcow2_cache_create(bs, refcount_cache_size);
661 if (r->l2_table_cache == NULL || r->refcount_block_cache == NULL) {
662 error_setg(errp, "Could not allocate metadata caches");
663 ret = -ENOMEM;
664 goto fail;
667 /* New interval for cache cleanup timer */
668 r->cache_clean_interval =
669 qemu_opt_get_number(opts, QCOW2_OPT_CACHE_CLEAN_INTERVAL,
670 s->cache_clean_interval);
671 if (r->cache_clean_interval > UINT_MAX) {
672 error_setg(errp, "Cache clean interval too big");
673 ret = -EINVAL;
674 goto fail;
677 /* lazy-refcounts; flush if going from enabled to disabled */
678 r->use_lazy_refcounts = qemu_opt_get_bool(opts, QCOW2_OPT_LAZY_REFCOUNTS,
679 (s->compatible_features & QCOW2_COMPAT_LAZY_REFCOUNTS));
680 if (r->use_lazy_refcounts && s->qcow_version < 3) {
681 error_setg(errp, "Lazy refcounts require a qcow2 image with at least "
682 "qemu 1.1 compatibility level");
683 ret = -EINVAL;
684 goto fail;
687 if (s->use_lazy_refcounts && !r->use_lazy_refcounts) {
688 ret = qcow2_mark_clean(bs);
689 if (ret < 0) {
690 error_setg_errno(errp, -ret, "Failed to disable lazy refcounts");
691 goto fail;
695 /* Overlap check options */
696 opt_overlap_check = qemu_opt_get(opts, QCOW2_OPT_OVERLAP);
697 opt_overlap_check_template = qemu_opt_get(opts, QCOW2_OPT_OVERLAP_TEMPLATE);
698 if (opt_overlap_check_template && opt_overlap_check &&
699 strcmp(opt_overlap_check_template, opt_overlap_check))
701 error_setg(errp, "Conflicting values for qcow2 options '"
702 QCOW2_OPT_OVERLAP "' ('%s') and '" QCOW2_OPT_OVERLAP_TEMPLATE
703 "' ('%s')", opt_overlap_check, opt_overlap_check_template);
704 ret = -EINVAL;
705 goto fail;
707 if (!opt_overlap_check) {
708 opt_overlap_check = opt_overlap_check_template ?: "cached";
711 if (!strcmp(opt_overlap_check, "none")) {
712 overlap_check_template = 0;
713 } else if (!strcmp(opt_overlap_check, "constant")) {
714 overlap_check_template = QCOW2_OL_CONSTANT;
715 } else if (!strcmp(opt_overlap_check, "cached")) {
716 overlap_check_template = QCOW2_OL_CACHED;
717 } else if (!strcmp(opt_overlap_check, "all")) {
718 overlap_check_template = QCOW2_OL_ALL;
719 } else {
720 error_setg(errp, "Unsupported value '%s' for qcow2 option "
721 "'overlap-check'. Allowed are any of the following: "
722 "none, constant, cached, all", opt_overlap_check);
723 ret = -EINVAL;
724 goto fail;
727 r->overlap_check = 0;
728 for (i = 0; i < QCOW2_OL_MAX_BITNR; i++) {
729 /* overlap-check defines a template bitmask, but every flag may be
730 * overwritten through the associated boolean option */
731 r->overlap_check |=
732 qemu_opt_get_bool(opts, overlap_bool_option_names[i],
733 overlap_check_template & (1 << i)) << i;
736 r->discard_passthrough[QCOW2_DISCARD_NEVER] = false;
737 r->discard_passthrough[QCOW2_DISCARD_ALWAYS] = true;
738 r->discard_passthrough[QCOW2_DISCARD_REQUEST] =
739 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_REQUEST,
740 flags & BDRV_O_UNMAP);
741 r->discard_passthrough[QCOW2_DISCARD_SNAPSHOT] =
742 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_SNAPSHOT, true);
743 r->discard_passthrough[QCOW2_DISCARD_OTHER] =
744 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_OTHER, false);
746 ret = 0;
747 fail:
748 qemu_opts_del(opts);
749 opts = NULL;
750 return ret;
753 static void qcow2_update_options_commit(BlockDriverState *bs,
754 Qcow2ReopenState *r)
756 BDRVQcow2State *s = bs->opaque;
757 int i;
759 if (s->l2_table_cache) {
760 qcow2_cache_destroy(bs, s->l2_table_cache);
762 if (s->refcount_block_cache) {
763 qcow2_cache_destroy(bs, s->refcount_block_cache);
765 s->l2_table_cache = r->l2_table_cache;
766 s->refcount_block_cache = r->refcount_block_cache;
768 s->overlap_check = r->overlap_check;
769 s->use_lazy_refcounts = r->use_lazy_refcounts;
771 for (i = 0; i < QCOW2_DISCARD_MAX; i++) {
772 s->discard_passthrough[i] = r->discard_passthrough[i];
775 if (s->cache_clean_interval != r->cache_clean_interval) {
776 cache_clean_timer_del(bs);
777 s->cache_clean_interval = r->cache_clean_interval;
778 cache_clean_timer_init(bs, bdrv_get_aio_context(bs));
782 static void qcow2_update_options_abort(BlockDriverState *bs,
783 Qcow2ReopenState *r)
785 if (r->l2_table_cache) {
786 qcow2_cache_destroy(bs, r->l2_table_cache);
788 if (r->refcount_block_cache) {
789 qcow2_cache_destroy(bs, r->refcount_block_cache);
793 static int qcow2_update_options(BlockDriverState *bs, QDict *options,
794 int flags, Error **errp)
796 Qcow2ReopenState r = {};
797 int ret;
799 ret = qcow2_update_options_prepare(bs, &r, options, flags, errp);
800 if (ret >= 0) {
801 qcow2_update_options_commit(bs, &r);
802 } else {
803 qcow2_update_options_abort(bs, &r);
806 return ret;
809 static int qcow2_open(BlockDriverState *bs, QDict *options, int flags,
810 Error **errp)
812 BDRVQcow2State *s = bs->opaque;
813 unsigned int len, i;
814 int ret = 0;
815 QCowHeader header;
816 Error *local_err = NULL;
817 uint64_t ext_end;
818 uint64_t l1_vm_state_index;
820 ret = bdrv_pread(bs->file->bs, 0, &header, sizeof(header));
821 if (ret < 0) {
822 error_setg_errno(errp, -ret, "Could not read qcow2 header");
823 goto fail;
825 be32_to_cpus(&header.magic);
826 be32_to_cpus(&header.version);
827 be64_to_cpus(&header.backing_file_offset);
828 be32_to_cpus(&header.backing_file_size);
829 be64_to_cpus(&header.size);
830 be32_to_cpus(&header.cluster_bits);
831 be32_to_cpus(&header.crypt_method);
832 be64_to_cpus(&header.l1_table_offset);
833 be32_to_cpus(&header.l1_size);
834 be64_to_cpus(&header.refcount_table_offset);
835 be32_to_cpus(&header.refcount_table_clusters);
836 be64_to_cpus(&header.snapshots_offset);
837 be32_to_cpus(&header.nb_snapshots);
839 if (header.magic != QCOW_MAGIC) {
840 error_setg(errp, "Image is not in qcow2 format");
841 ret = -EINVAL;
842 goto fail;
844 if (header.version < 2 || header.version > 3) {
845 error_setg(errp, "Unsupported qcow2 version %" PRIu32, header.version);
846 ret = -ENOTSUP;
847 goto fail;
850 s->qcow_version = header.version;
852 /* Initialise cluster size */
853 if (header.cluster_bits < MIN_CLUSTER_BITS ||
854 header.cluster_bits > MAX_CLUSTER_BITS) {
855 error_setg(errp, "Unsupported cluster size: 2^%" PRIu32,
856 header.cluster_bits);
857 ret = -EINVAL;
858 goto fail;
861 s->cluster_bits = header.cluster_bits;
862 s->cluster_size = 1 << s->cluster_bits;
863 s->cluster_sectors = 1 << (s->cluster_bits - 9);
865 /* Initialise version 3 header fields */
866 if (header.version == 2) {
867 header.incompatible_features = 0;
868 header.compatible_features = 0;
869 header.autoclear_features = 0;
870 header.refcount_order = 4;
871 header.header_length = 72;
872 } else {
873 be64_to_cpus(&header.incompatible_features);
874 be64_to_cpus(&header.compatible_features);
875 be64_to_cpus(&header.autoclear_features);
876 be32_to_cpus(&header.refcount_order);
877 be32_to_cpus(&header.header_length);
879 if (header.header_length < 104) {
880 error_setg(errp, "qcow2 header too short");
881 ret = -EINVAL;
882 goto fail;
886 if (header.header_length > s->cluster_size) {
887 error_setg(errp, "qcow2 header exceeds cluster size");
888 ret = -EINVAL;
889 goto fail;
892 if (header.header_length > sizeof(header)) {
893 s->unknown_header_fields_size = header.header_length - sizeof(header);
894 s->unknown_header_fields = g_malloc(s->unknown_header_fields_size);
895 ret = bdrv_pread(bs->file->bs, sizeof(header), s->unknown_header_fields,
896 s->unknown_header_fields_size);
897 if (ret < 0) {
898 error_setg_errno(errp, -ret, "Could not read unknown qcow2 header "
899 "fields");
900 goto fail;
904 if (header.backing_file_offset > s->cluster_size) {
905 error_setg(errp, "Invalid backing file offset");
906 ret = -EINVAL;
907 goto fail;
910 if (header.backing_file_offset) {
911 ext_end = header.backing_file_offset;
912 } else {
913 ext_end = 1 << header.cluster_bits;
916 /* Handle feature bits */
917 s->incompatible_features = header.incompatible_features;
918 s->compatible_features = header.compatible_features;
919 s->autoclear_features = header.autoclear_features;
921 if (s->incompatible_features & ~QCOW2_INCOMPAT_MASK) {
922 void *feature_table = NULL;
923 qcow2_read_extensions(bs, header.header_length, ext_end,
924 &feature_table, NULL);
925 report_unsupported_feature(errp, feature_table,
926 s->incompatible_features &
927 ~QCOW2_INCOMPAT_MASK);
928 ret = -ENOTSUP;
929 g_free(feature_table);
930 goto fail;
933 if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
934 /* Corrupt images may not be written to unless they are being repaired
936 if ((flags & BDRV_O_RDWR) && !(flags & BDRV_O_CHECK)) {
937 error_setg(errp, "qcow2: Image is corrupt; cannot be opened "
938 "read/write");
939 ret = -EACCES;
940 goto fail;
944 /* Check support for various header values */
945 if (header.refcount_order > 6) {
946 error_setg(errp, "Reference count entry width too large; may not "
947 "exceed 64 bits");
948 ret = -EINVAL;
949 goto fail;
951 s->refcount_order = header.refcount_order;
952 s->refcount_bits = 1 << s->refcount_order;
953 s->refcount_max = UINT64_C(1) << (s->refcount_bits - 1);
954 s->refcount_max += s->refcount_max - 1;
956 if (header.crypt_method > QCOW_CRYPT_AES) {
957 error_setg(errp, "Unsupported encryption method: %" PRIu32,
958 header.crypt_method);
959 ret = -EINVAL;
960 goto fail;
962 if (!qcrypto_cipher_supports(QCRYPTO_CIPHER_ALG_AES_128)) {
963 error_setg(errp, "AES cipher not available");
964 ret = -EINVAL;
965 goto fail;
967 s->crypt_method_header = header.crypt_method;
968 if (s->crypt_method_header) {
969 if (bdrv_uses_whitelist() &&
970 s->crypt_method_header == QCOW_CRYPT_AES) {
971 error_report("qcow2 built-in AES encryption is deprecated");
972 error_printf("Support for it will be removed in a future release.\n"
973 "You can use 'qemu-img convert' to switch to an\n"
974 "unencrypted qcow2 image, or a LUKS raw image.\n");
977 bs->encrypted = 1;
979 /* Encryption works on a sector granularity */
980 bs->request_alignment = BDRV_SECTOR_SIZE;
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_INACTIVE) && 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_INACTIVE)) && !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.pwrite_zeroes_alignment = s->cluster_size;
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, BlockDriverState **file)
1334 BDRVQcow2State *s = bs->opaque;
1335 uint64_t cluster_offset;
1336 int index_in_cluster, ret;
1337 unsigned int bytes;
1338 int64_t status = 0;
1340 bytes = MIN(INT_MAX, nb_sectors * BDRV_SECTOR_SIZE);
1341 qemu_co_mutex_lock(&s->lock);
1342 ret = qcow2_get_cluster_offset(bs, sector_num << 9, &bytes,
1343 &cluster_offset);
1344 qemu_co_mutex_unlock(&s->lock);
1345 if (ret < 0) {
1346 return ret;
1349 *pnum = bytes >> BDRV_SECTOR_BITS;
1351 if (cluster_offset != 0 && ret != QCOW2_CLUSTER_COMPRESSED &&
1352 !s->cipher) {
1353 index_in_cluster = sector_num & (s->cluster_sectors - 1);
1354 cluster_offset |= (index_in_cluster << BDRV_SECTOR_BITS);
1355 *file = bs->file->bs;
1356 status |= BDRV_BLOCK_OFFSET_VALID | cluster_offset;
1358 if (ret == QCOW2_CLUSTER_ZERO) {
1359 status |= BDRV_BLOCK_ZERO;
1360 } else if (ret != QCOW2_CLUSTER_UNALLOCATED) {
1361 status |= BDRV_BLOCK_DATA;
1363 return status;
1366 /* handle reading after the end of the backing file */
1367 int qcow2_backing_read1(BlockDriverState *bs, QEMUIOVector *qiov,
1368 int64_t offset, int bytes)
1370 uint64_t bs_size = bs->total_sectors * BDRV_SECTOR_SIZE;
1371 int n1;
1373 if ((offset + bytes) <= bs_size) {
1374 return bytes;
1377 if (offset >= bs_size) {
1378 n1 = 0;
1379 } else {
1380 n1 = bs_size - offset;
1383 qemu_iovec_memset(qiov, n1, 0, bytes - n1);
1385 return n1;
1388 static coroutine_fn int qcow2_co_preadv(BlockDriverState *bs, uint64_t offset,
1389 uint64_t bytes, QEMUIOVector *qiov,
1390 int flags)
1392 BDRVQcow2State *s = bs->opaque;
1393 int offset_in_cluster, n1;
1394 int ret;
1395 unsigned int cur_bytes; /* number of bytes in current iteration */
1396 uint64_t cluster_offset = 0;
1397 uint64_t bytes_done = 0;
1398 QEMUIOVector hd_qiov;
1399 uint8_t *cluster_data = NULL;
1401 qemu_iovec_init(&hd_qiov, qiov->niov);
1403 qemu_co_mutex_lock(&s->lock);
1405 while (bytes != 0) {
1407 /* prepare next request */
1408 cur_bytes = MIN(bytes, INT_MAX);
1409 if (s->cipher) {
1410 cur_bytes = MIN(cur_bytes,
1411 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
1414 ret = qcow2_get_cluster_offset(bs, offset, &cur_bytes, &cluster_offset);
1415 if (ret < 0) {
1416 goto fail;
1419 offset_in_cluster = offset_into_cluster(s, offset);
1421 qemu_iovec_reset(&hd_qiov);
1422 qemu_iovec_concat(&hd_qiov, qiov, bytes_done, cur_bytes);
1424 switch (ret) {
1425 case QCOW2_CLUSTER_UNALLOCATED:
1427 if (bs->backing) {
1428 /* read from the base image */
1429 n1 = qcow2_backing_read1(bs->backing->bs, &hd_qiov,
1430 offset, cur_bytes);
1431 if (n1 > 0) {
1432 QEMUIOVector local_qiov;
1434 qemu_iovec_init(&local_qiov, hd_qiov.niov);
1435 qemu_iovec_concat(&local_qiov, &hd_qiov, 0, n1);
1437 BLKDBG_EVENT(bs->file, BLKDBG_READ_BACKING_AIO);
1438 qemu_co_mutex_unlock(&s->lock);
1439 ret = bdrv_co_preadv(bs->backing->bs, offset, n1,
1440 &local_qiov, 0);
1441 qemu_co_mutex_lock(&s->lock);
1443 qemu_iovec_destroy(&local_qiov);
1445 if (ret < 0) {
1446 goto fail;
1449 } else {
1450 /* Note: in this case, no need to wait */
1451 qemu_iovec_memset(&hd_qiov, 0, 0, cur_bytes);
1453 break;
1455 case QCOW2_CLUSTER_ZERO:
1456 qemu_iovec_memset(&hd_qiov, 0, 0, cur_bytes);
1457 break;
1459 case QCOW2_CLUSTER_COMPRESSED:
1460 /* add AIO support for compressed blocks ? */
1461 ret = qcow2_decompress_cluster(bs, cluster_offset);
1462 if (ret < 0) {
1463 goto fail;
1466 qemu_iovec_from_buf(&hd_qiov, 0,
1467 s->cluster_cache + offset_in_cluster,
1468 cur_bytes);
1469 break;
1471 case QCOW2_CLUSTER_NORMAL:
1472 if ((cluster_offset & 511) != 0) {
1473 ret = -EIO;
1474 goto fail;
1477 if (bs->encrypted) {
1478 assert(s->cipher);
1481 * For encrypted images, read everything into a temporary
1482 * contiguous buffer on which the AES functions can work.
1484 if (!cluster_data) {
1485 cluster_data =
1486 qemu_try_blockalign(bs->file->bs,
1487 QCOW_MAX_CRYPT_CLUSTERS
1488 * s->cluster_size);
1489 if (cluster_data == NULL) {
1490 ret = -ENOMEM;
1491 goto fail;
1495 assert(cur_bytes <= QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
1496 qemu_iovec_reset(&hd_qiov);
1497 qemu_iovec_add(&hd_qiov, cluster_data, cur_bytes);
1500 BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);
1501 qemu_co_mutex_unlock(&s->lock);
1502 ret = bdrv_co_preadv(bs->file->bs,
1503 cluster_offset + offset_in_cluster,
1504 cur_bytes, &hd_qiov, 0);
1505 qemu_co_mutex_lock(&s->lock);
1506 if (ret < 0) {
1507 goto fail;
1509 if (bs->encrypted) {
1510 assert(s->cipher);
1511 assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);
1512 assert((cur_bytes & (BDRV_SECTOR_SIZE - 1)) == 0);
1513 Error *err = NULL;
1514 if (qcow2_encrypt_sectors(s, offset >> BDRV_SECTOR_BITS,
1515 cluster_data, cluster_data,
1516 cur_bytes >> BDRV_SECTOR_BITS,
1517 false, &err) < 0) {
1518 error_free(err);
1519 ret = -EIO;
1520 goto fail;
1522 qemu_iovec_from_buf(qiov, bytes_done, cluster_data, cur_bytes);
1524 break;
1526 default:
1527 g_assert_not_reached();
1528 ret = -EIO;
1529 goto fail;
1532 bytes -= cur_bytes;
1533 offset += cur_bytes;
1534 bytes_done += cur_bytes;
1536 ret = 0;
1538 fail:
1539 qemu_co_mutex_unlock(&s->lock);
1541 qemu_iovec_destroy(&hd_qiov);
1542 qemu_vfree(cluster_data);
1544 return ret;
1547 static coroutine_fn int qcow2_co_pwritev(BlockDriverState *bs, uint64_t offset,
1548 uint64_t bytes, QEMUIOVector *qiov,
1549 int flags)
1551 BDRVQcow2State *s = bs->opaque;
1552 int offset_in_cluster;
1553 int ret;
1554 unsigned int cur_bytes; /* number of sectors in current iteration */
1555 uint64_t cluster_offset;
1556 QEMUIOVector hd_qiov;
1557 uint64_t bytes_done = 0;
1558 uint8_t *cluster_data = NULL;
1559 QCowL2Meta *l2meta = NULL;
1561 trace_qcow2_writev_start_req(qemu_coroutine_self(), offset, bytes);
1563 qemu_iovec_init(&hd_qiov, qiov->niov);
1565 s->cluster_cache_offset = -1; /* disable compressed cache */
1567 qemu_co_mutex_lock(&s->lock);
1569 while (bytes != 0) {
1571 l2meta = NULL;
1573 trace_qcow2_writev_start_part(qemu_coroutine_self());
1574 offset_in_cluster = offset_into_cluster(s, offset);
1575 cur_bytes = MIN(bytes, INT_MAX);
1576 if (bs->encrypted) {
1577 cur_bytes = MIN(cur_bytes,
1578 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size
1579 - offset_in_cluster);
1582 ret = qcow2_alloc_cluster_offset(bs, offset, &cur_bytes,
1583 &cluster_offset, &l2meta);
1584 if (ret < 0) {
1585 goto fail;
1588 assert((cluster_offset & 511) == 0);
1590 qemu_iovec_reset(&hd_qiov);
1591 qemu_iovec_concat(&hd_qiov, qiov, bytes_done, cur_bytes);
1593 if (bs->encrypted) {
1594 Error *err = NULL;
1595 assert(s->cipher);
1596 if (!cluster_data) {
1597 cluster_data = qemu_try_blockalign(bs->file->bs,
1598 QCOW_MAX_CRYPT_CLUSTERS
1599 * s->cluster_size);
1600 if (cluster_data == NULL) {
1601 ret = -ENOMEM;
1602 goto fail;
1606 assert(hd_qiov.size <=
1607 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
1608 qemu_iovec_to_buf(&hd_qiov, 0, cluster_data, hd_qiov.size);
1610 if (qcow2_encrypt_sectors(s, offset >> BDRV_SECTOR_BITS,
1611 cluster_data, cluster_data,
1612 cur_bytes >>BDRV_SECTOR_BITS,
1613 true, &err) < 0) {
1614 error_free(err);
1615 ret = -EIO;
1616 goto fail;
1619 qemu_iovec_reset(&hd_qiov);
1620 qemu_iovec_add(&hd_qiov, cluster_data, cur_bytes);
1623 ret = qcow2_pre_write_overlap_check(bs, 0,
1624 cluster_offset + offset_in_cluster, cur_bytes);
1625 if (ret < 0) {
1626 goto fail;
1629 qemu_co_mutex_unlock(&s->lock);
1630 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO);
1631 trace_qcow2_writev_data(qemu_coroutine_self(),
1632 cluster_offset + offset_in_cluster);
1633 ret = bdrv_co_pwritev(bs->file->bs,
1634 cluster_offset + offset_in_cluster,
1635 cur_bytes, &hd_qiov, 0);
1636 qemu_co_mutex_lock(&s->lock);
1637 if (ret < 0) {
1638 goto fail;
1641 while (l2meta != NULL) {
1642 QCowL2Meta *next;
1644 ret = qcow2_alloc_cluster_link_l2(bs, l2meta);
1645 if (ret < 0) {
1646 goto fail;
1649 /* Take the request off the list of running requests */
1650 if (l2meta->nb_clusters != 0) {
1651 QLIST_REMOVE(l2meta, next_in_flight);
1654 qemu_co_queue_restart_all(&l2meta->dependent_requests);
1656 next = l2meta->next;
1657 g_free(l2meta);
1658 l2meta = next;
1661 bytes -= cur_bytes;
1662 offset += cur_bytes;
1663 bytes_done += cur_bytes;
1664 trace_qcow2_writev_done_part(qemu_coroutine_self(), cur_bytes);
1666 ret = 0;
1668 fail:
1669 qemu_co_mutex_unlock(&s->lock);
1671 while (l2meta != NULL) {
1672 QCowL2Meta *next;
1674 if (l2meta->nb_clusters != 0) {
1675 QLIST_REMOVE(l2meta, next_in_flight);
1677 qemu_co_queue_restart_all(&l2meta->dependent_requests);
1679 next = l2meta->next;
1680 g_free(l2meta);
1681 l2meta = next;
1684 qemu_iovec_destroy(&hd_qiov);
1685 qemu_vfree(cluster_data);
1686 trace_qcow2_writev_done_req(qemu_coroutine_self(), ret);
1688 return ret;
1691 static int qcow2_inactivate(BlockDriverState *bs)
1693 BDRVQcow2State *s = bs->opaque;
1694 int ret, result = 0;
1696 ret = qcow2_cache_flush(bs, s->l2_table_cache);
1697 if (ret) {
1698 result = ret;
1699 error_report("Failed to flush the L2 table cache: %s",
1700 strerror(-ret));
1703 ret = qcow2_cache_flush(bs, s->refcount_block_cache);
1704 if (ret) {
1705 result = ret;
1706 error_report("Failed to flush the refcount block cache: %s",
1707 strerror(-ret));
1710 if (result == 0) {
1711 qcow2_mark_clean(bs);
1714 return result;
1717 static void qcow2_close(BlockDriverState *bs)
1719 BDRVQcow2State *s = bs->opaque;
1720 qemu_vfree(s->l1_table);
1721 /* else pre-write overlap checks in cache_destroy may crash */
1722 s->l1_table = NULL;
1724 if (!(s->flags & BDRV_O_INACTIVE)) {
1725 qcow2_inactivate(bs);
1728 cache_clean_timer_del(bs);
1729 qcow2_cache_destroy(bs, s->l2_table_cache);
1730 qcow2_cache_destroy(bs, s->refcount_block_cache);
1732 qcrypto_cipher_free(s->cipher);
1733 s->cipher = NULL;
1735 g_free(s->unknown_header_fields);
1736 cleanup_unknown_header_ext(bs);
1738 g_free(s->image_backing_file);
1739 g_free(s->image_backing_format);
1741 g_free(s->cluster_cache);
1742 qemu_vfree(s->cluster_data);
1743 qcow2_refcount_close(bs);
1744 qcow2_free_snapshots(bs);
1747 static void qcow2_invalidate_cache(BlockDriverState *bs, Error **errp)
1749 BDRVQcow2State *s = bs->opaque;
1750 int flags = s->flags;
1751 QCryptoCipher *cipher = NULL;
1752 QDict *options;
1753 Error *local_err = NULL;
1754 int ret;
1757 * Backing files are read-only which makes all of their metadata immutable,
1758 * that means we don't have to worry about reopening them here.
1761 cipher = s->cipher;
1762 s->cipher = NULL;
1764 qcow2_close(bs);
1766 memset(s, 0, sizeof(BDRVQcow2State));
1767 options = qdict_clone_shallow(bs->options);
1769 flags &= ~BDRV_O_INACTIVE;
1770 ret = qcow2_open(bs, options, flags, &local_err);
1771 QDECREF(options);
1772 if (local_err) {
1773 error_propagate(errp, local_err);
1774 error_prepend(errp, "Could not reopen qcow2 layer: ");
1775 bs->drv = NULL;
1776 return;
1777 } else if (ret < 0) {
1778 error_setg_errno(errp, -ret, "Could not reopen qcow2 layer");
1779 bs->drv = NULL;
1780 return;
1783 s->cipher = cipher;
1786 static size_t header_ext_add(char *buf, uint32_t magic, const void *s,
1787 size_t len, size_t buflen)
1789 QCowExtension *ext_backing_fmt = (QCowExtension*) buf;
1790 size_t ext_len = sizeof(QCowExtension) + ((len + 7) & ~7);
1792 if (buflen < ext_len) {
1793 return -ENOSPC;
1796 *ext_backing_fmt = (QCowExtension) {
1797 .magic = cpu_to_be32(magic),
1798 .len = cpu_to_be32(len),
1800 memcpy(buf + sizeof(QCowExtension), s, len);
1802 return ext_len;
1806 * Updates the qcow2 header, including the variable length parts of it, i.e.
1807 * the backing file name and all extensions. qcow2 was not designed to allow
1808 * such changes, so if we run out of space (we can only use the first cluster)
1809 * this function may fail.
1811 * Returns 0 on success, -errno in error cases.
1813 int qcow2_update_header(BlockDriverState *bs)
1815 BDRVQcow2State *s = bs->opaque;
1816 QCowHeader *header;
1817 char *buf;
1818 size_t buflen = s->cluster_size;
1819 int ret;
1820 uint64_t total_size;
1821 uint32_t refcount_table_clusters;
1822 size_t header_length;
1823 Qcow2UnknownHeaderExtension *uext;
1825 buf = qemu_blockalign(bs, buflen);
1827 /* Header structure */
1828 header = (QCowHeader*) buf;
1830 if (buflen < sizeof(*header)) {
1831 ret = -ENOSPC;
1832 goto fail;
1835 header_length = sizeof(*header) + s->unknown_header_fields_size;
1836 total_size = bs->total_sectors * BDRV_SECTOR_SIZE;
1837 refcount_table_clusters = s->refcount_table_size >> (s->cluster_bits - 3);
1839 *header = (QCowHeader) {
1840 /* Version 2 fields */
1841 .magic = cpu_to_be32(QCOW_MAGIC),
1842 .version = cpu_to_be32(s->qcow_version),
1843 .backing_file_offset = 0,
1844 .backing_file_size = 0,
1845 .cluster_bits = cpu_to_be32(s->cluster_bits),
1846 .size = cpu_to_be64(total_size),
1847 .crypt_method = cpu_to_be32(s->crypt_method_header),
1848 .l1_size = cpu_to_be32(s->l1_size),
1849 .l1_table_offset = cpu_to_be64(s->l1_table_offset),
1850 .refcount_table_offset = cpu_to_be64(s->refcount_table_offset),
1851 .refcount_table_clusters = cpu_to_be32(refcount_table_clusters),
1852 .nb_snapshots = cpu_to_be32(s->nb_snapshots),
1853 .snapshots_offset = cpu_to_be64(s->snapshots_offset),
1855 /* Version 3 fields */
1856 .incompatible_features = cpu_to_be64(s->incompatible_features),
1857 .compatible_features = cpu_to_be64(s->compatible_features),
1858 .autoclear_features = cpu_to_be64(s->autoclear_features),
1859 .refcount_order = cpu_to_be32(s->refcount_order),
1860 .header_length = cpu_to_be32(header_length),
1863 /* For older versions, write a shorter header */
1864 switch (s->qcow_version) {
1865 case 2:
1866 ret = offsetof(QCowHeader, incompatible_features);
1867 break;
1868 case 3:
1869 ret = sizeof(*header);
1870 break;
1871 default:
1872 ret = -EINVAL;
1873 goto fail;
1876 buf += ret;
1877 buflen -= ret;
1878 memset(buf, 0, buflen);
1880 /* Preserve any unknown field in the header */
1881 if (s->unknown_header_fields_size) {
1882 if (buflen < s->unknown_header_fields_size) {
1883 ret = -ENOSPC;
1884 goto fail;
1887 memcpy(buf, s->unknown_header_fields, s->unknown_header_fields_size);
1888 buf += s->unknown_header_fields_size;
1889 buflen -= s->unknown_header_fields_size;
1892 /* Backing file format header extension */
1893 if (s->image_backing_format) {
1894 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BACKING_FORMAT,
1895 s->image_backing_format,
1896 strlen(s->image_backing_format),
1897 buflen);
1898 if (ret < 0) {
1899 goto fail;
1902 buf += ret;
1903 buflen -= ret;
1906 /* Feature table */
1907 if (s->qcow_version >= 3) {
1908 Qcow2Feature features[] = {
1910 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
1911 .bit = QCOW2_INCOMPAT_DIRTY_BITNR,
1912 .name = "dirty bit",
1915 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
1916 .bit = QCOW2_INCOMPAT_CORRUPT_BITNR,
1917 .name = "corrupt bit",
1920 .type = QCOW2_FEAT_TYPE_COMPATIBLE,
1921 .bit = QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR,
1922 .name = "lazy refcounts",
1926 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_FEATURE_TABLE,
1927 features, sizeof(features), buflen);
1928 if (ret < 0) {
1929 goto fail;
1931 buf += ret;
1932 buflen -= ret;
1935 /* Keep unknown header extensions */
1936 QLIST_FOREACH(uext, &s->unknown_header_ext, next) {
1937 ret = header_ext_add(buf, uext->magic, uext->data, uext->len, buflen);
1938 if (ret < 0) {
1939 goto fail;
1942 buf += ret;
1943 buflen -= ret;
1946 /* End of header extensions */
1947 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_END, NULL, 0, buflen);
1948 if (ret < 0) {
1949 goto fail;
1952 buf += ret;
1953 buflen -= ret;
1955 /* Backing file name */
1956 if (s->image_backing_file) {
1957 size_t backing_file_len = strlen(s->image_backing_file);
1959 if (buflen < backing_file_len) {
1960 ret = -ENOSPC;
1961 goto fail;
1964 /* Using strncpy is ok here, since buf is not NUL-terminated. */
1965 strncpy(buf, s->image_backing_file, buflen);
1967 header->backing_file_offset = cpu_to_be64(buf - ((char*) header));
1968 header->backing_file_size = cpu_to_be32(backing_file_len);
1971 /* Write the new header */
1972 ret = bdrv_pwrite(bs->file->bs, 0, header, s->cluster_size);
1973 if (ret < 0) {
1974 goto fail;
1977 ret = 0;
1978 fail:
1979 qemu_vfree(header);
1980 return ret;
1983 static int qcow2_change_backing_file(BlockDriverState *bs,
1984 const char *backing_file, const char *backing_fmt)
1986 BDRVQcow2State *s = bs->opaque;
1988 if (backing_file && strlen(backing_file) > 1023) {
1989 return -EINVAL;
1992 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
1993 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
1995 g_free(s->image_backing_file);
1996 g_free(s->image_backing_format);
1998 s->image_backing_file = backing_file ? g_strdup(bs->backing_file) : NULL;
1999 s->image_backing_format = backing_fmt ? g_strdup(bs->backing_format) : NULL;
2001 return qcow2_update_header(bs);
2004 static int preallocate(BlockDriverState *bs)
2006 uint64_t bytes;
2007 uint64_t offset;
2008 uint64_t host_offset = 0;
2009 unsigned int cur_bytes;
2010 int ret;
2011 QCowL2Meta *meta;
2013 bytes = bdrv_getlength(bs);
2014 offset = 0;
2016 while (bytes) {
2017 cur_bytes = MIN(bytes, INT_MAX);
2018 ret = qcow2_alloc_cluster_offset(bs, offset, &cur_bytes,
2019 &host_offset, &meta);
2020 if (ret < 0) {
2021 return ret;
2024 while (meta) {
2025 QCowL2Meta *next = meta->next;
2027 ret = qcow2_alloc_cluster_link_l2(bs, meta);
2028 if (ret < 0) {
2029 qcow2_free_any_clusters(bs, meta->alloc_offset,
2030 meta->nb_clusters, QCOW2_DISCARD_NEVER);
2031 return ret;
2034 /* There are no dependent requests, but we need to remove our
2035 * request from the list of in-flight requests */
2036 QLIST_REMOVE(meta, next_in_flight);
2038 g_free(meta);
2039 meta = next;
2042 /* TODO Preallocate data if requested */
2044 bytes -= cur_bytes;
2045 offset += cur_bytes;
2049 * It is expected that the image file is large enough to actually contain
2050 * all of the allocated clusters (otherwise we get failing reads after
2051 * EOF). Extend the image to the last allocated sector.
2053 if (host_offset != 0) {
2054 uint8_t data = 0;
2055 ret = bdrv_pwrite(bs->file->bs, (host_offset + cur_bytes) - 1,
2056 &data, 1);
2057 if (ret < 0) {
2058 return ret;
2062 return 0;
2065 static int qcow2_create2(const char *filename, int64_t total_size,
2066 const char *backing_file, const char *backing_format,
2067 int flags, size_t cluster_size, PreallocMode prealloc,
2068 QemuOpts *opts, int version, int refcount_order,
2069 Error **errp)
2071 int cluster_bits;
2072 QDict *options;
2074 /* Calculate cluster_bits */
2075 cluster_bits = ctz32(cluster_size);
2076 if (cluster_bits < MIN_CLUSTER_BITS || cluster_bits > MAX_CLUSTER_BITS ||
2077 (1 << cluster_bits) != cluster_size)
2079 error_setg(errp, "Cluster size must be a power of two between %d and "
2080 "%dk", 1 << MIN_CLUSTER_BITS, 1 << (MAX_CLUSTER_BITS - 10));
2081 return -EINVAL;
2085 * Open the image file and write a minimal qcow2 header.
2087 * We keep things simple and start with a zero-sized image. We also
2088 * do without refcount blocks or a L1 table for now. We'll fix the
2089 * inconsistency later.
2091 * We do need a refcount table because growing the refcount table means
2092 * allocating two new refcount blocks - the seconds of which would be at
2093 * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
2094 * size for any qcow2 image.
2096 BlockBackend *blk;
2097 QCowHeader *header;
2098 uint64_t* refcount_table;
2099 Error *local_err = NULL;
2100 int ret;
2102 if (prealloc == PREALLOC_MODE_FULL || prealloc == PREALLOC_MODE_FALLOC) {
2103 /* Note: The following calculation does not need to be exact; if it is a
2104 * bit off, either some bytes will be "leaked" (which is fine) or we
2105 * will need to increase the file size by some bytes (which is fine,
2106 * too, as long as the bulk is allocated here). Therefore, using
2107 * floating point arithmetic is fine. */
2108 int64_t meta_size = 0;
2109 uint64_t nreftablee, nrefblocke, nl1e, nl2e;
2110 int64_t aligned_total_size = align_offset(total_size, cluster_size);
2111 int refblock_bits, refblock_size;
2112 /* refcount entry size in bytes */
2113 double rces = (1 << refcount_order) / 8.;
2115 /* see qcow2_open() */
2116 refblock_bits = cluster_bits - (refcount_order - 3);
2117 refblock_size = 1 << refblock_bits;
2119 /* header: 1 cluster */
2120 meta_size += cluster_size;
2122 /* total size of L2 tables */
2123 nl2e = aligned_total_size / cluster_size;
2124 nl2e = align_offset(nl2e, cluster_size / sizeof(uint64_t));
2125 meta_size += nl2e * sizeof(uint64_t);
2127 /* total size of L1 tables */
2128 nl1e = nl2e * sizeof(uint64_t) / cluster_size;
2129 nl1e = align_offset(nl1e, cluster_size / sizeof(uint64_t));
2130 meta_size += nl1e * sizeof(uint64_t);
2132 /* total size of refcount blocks
2134 * note: every host cluster is reference-counted, including metadata
2135 * (even refcount blocks are recursively included).
2136 * Let:
2137 * a = total_size (this is the guest disk size)
2138 * m = meta size not including refcount blocks and refcount tables
2139 * c = cluster size
2140 * y1 = number of refcount blocks entries
2141 * y2 = meta size including everything
2142 * rces = refcount entry size in bytes
2143 * then,
2144 * y1 = (y2 + a)/c
2145 * y2 = y1 * rces + y1 * rces * sizeof(u64) / c + m
2146 * we can get y1:
2147 * y1 = (a + m) / (c - rces - rces * sizeof(u64) / c)
2149 nrefblocke = (aligned_total_size + meta_size + cluster_size)
2150 / (cluster_size - rces - rces * sizeof(uint64_t)
2151 / cluster_size);
2152 meta_size += DIV_ROUND_UP(nrefblocke, refblock_size) * cluster_size;
2154 /* total size of refcount tables */
2155 nreftablee = nrefblocke / refblock_size;
2156 nreftablee = align_offset(nreftablee, cluster_size / sizeof(uint64_t));
2157 meta_size += nreftablee * sizeof(uint64_t);
2159 qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
2160 aligned_total_size + meta_size, &error_abort);
2161 qemu_opt_set(opts, BLOCK_OPT_PREALLOC, PreallocMode_lookup[prealloc],
2162 &error_abort);
2165 ret = bdrv_create_file(filename, opts, &local_err);
2166 if (ret < 0) {
2167 error_propagate(errp, local_err);
2168 return ret;
2171 blk = blk_new_open(filename, NULL, NULL,
2172 BDRV_O_RDWR | BDRV_O_PROTOCOL, &local_err);
2173 if (blk == NULL) {
2174 error_propagate(errp, local_err);
2175 return -EIO;
2178 blk_set_allow_write_beyond_eof(blk, true);
2180 /* Write the header */
2181 QEMU_BUILD_BUG_ON((1 << MIN_CLUSTER_BITS) < sizeof(*header));
2182 header = g_malloc0(cluster_size);
2183 *header = (QCowHeader) {
2184 .magic = cpu_to_be32(QCOW_MAGIC),
2185 .version = cpu_to_be32(version),
2186 .cluster_bits = cpu_to_be32(cluster_bits),
2187 .size = cpu_to_be64(0),
2188 .l1_table_offset = cpu_to_be64(0),
2189 .l1_size = cpu_to_be32(0),
2190 .refcount_table_offset = cpu_to_be64(cluster_size),
2191 .refcount_table_clusters = cpu_to_be32(1),
2192 .refcount_order = cpu_to_be32(refcount_order),
2193 .header_length = cpu_to_be32(sizeof(*header)),
2196 if (flags & BLOCK_FLAG_ENCRYPT) {
2197 header->crypt_method = cpu_to_be32(QCOW_CRYPT_AES);
2198 } else {
2199 header->crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
2202 if (flags & BLOCK_FLAG_LAZY_REFCOUNTS) {
2203 header->compatible_features |=
2204 cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS);
2207 ret = blk_pwrite(blk, 0, header, cluster_size, 0);
2208 g_free(header);
2209 if (ret < 0) {
2210 error_setg_errno(errp, -ret, "Could not write qcow2 header");
2211 goto out;
2214 /* Write a refcount table with one refcount block */
2215 refcount_table = g_malloc0(2 * cluster_size);
2216 refcount_table[0] = cpu_to_be64(2 * cluster_size);
2217 ret = blk_pwrite(blk, cluster_size, refcount_table, 2 * cluster_size, 0);
2218 g_free(refcount_table);
2220 if (ret < 0) {
2221 error_setg_errno(errp, -ret, "Could not write refcount table");
2222 goto out;
2225 blk_unref(blk);
2226 blk = NULL;
2229 * And now open the image and make it consistent first (i.e. increase the
2230 * refcount of the cluster that is occupied by the header and the refcount
2231 * table)
2233 options = qdict_new();
2234 qdict_put(options, "driver", qstring_from_str("qcow2"));
2235 blk = blk_new_open(filename, NULL, options,
2236 BDRV_O_RDWR | BDRV_O_NO_FLUSH, &local_err);
2237 if (blk == NULL) {
2238 error_propagate(errp, local_err);
2239 ret = -EIO;
2240 goto out;
2243 ret = qcow2_alloc_clusters(blk_bs(blk), 3 * cluster_size);
2244 if (ret < 0) {
2245 error_setg_errno(errp, -ret, "Could not allocate clusters for qcow2 "
2246 "header and refcount table");
2247 goto out;
2249 } else if (ret != 0) {
2250 error_report("Huh, first cluster in empty image is already in use?");
2251 abort();
2254 /* Create a full header (including things like feature table) */
2255 ret = qcow2_update_header(blk_bs(blk));
2256 if (ret < 0) {
2257 error_setg_errno(errp, -ret, "Could not update qcow2 header");
2258 goto out;
2261 /* Okay, now that we have a valid image, let's give it the right size */
2262 ret = blk_truncate(blk, total_size);
2263 if (ret < 0) {
2264 error_setg_errno(errp, -ret, "Could not resize image");
2265 goto out;
2268 /* Want a backing file? There you go.*/
2269 if (backing_file) {
2270 ret = bdrv_change_backing_file(blk_bs(blk), backing_file, backing_format);
2271 if (ret < 0) {
2272 error_setg_errno(errp, -ret, "Could not assign backing file '%s' "
2273 "with format '%s'", backing_file, backing_format);
2274 goto out;
2278 /* And if we're supposed to preallocate metadata, do that now */
2279 if (prealloc != PREALLOC_MODE_OFF) {
2280 BDRVQcow2State *s = blk_bs(blk)->opaque;
2281 qemu_co_mutex_lock(&s->lock);
2282 ret = preallocate(blk_bs(blk));
2283 qemu_co_mutex_unlock(&s->lock);
2284 if (ret < 0) {
2285 error_setg_errno(errp, -ret, "Could not preallocate metadata");
2286 goto out;
2290 blk_unref(blk);
2291 blk = NULL;
2293 /* Reopen the image without BDRV_O_NO_FLUSH to flush it before returning */
2294 options = qdict_new();
2295 qdict_put(options, "driver", qstring_from_str("qcow2"));
2296 blk = blk_new_open(filename, NULL, options,
2297 BDRV_O_RDWR | BDRV_O_NO_BACKING, &local_err);
2298 if (blk == NULL) {
2299 error_propagate(errp, local_err);
2300 ret = -EIO;
2301 goto out;
2304 ret = 0;
2305 out:
2306 if (blk) {
2307 blk_unref(blk);
2309 return ret;
2312 static int qcow2_create(const char *filename, QemuOpts *opts, Error **errp)
2314 char *backing_file = NULL;
2315 char *backing_fmt = NULL;
2316 char *buf = NULL;
2317 uint64_t size = 0;
2318 int flags = 0;
2319 size_t cluster_size = DEFAULT_CLUSTER_SIZE;
2320 PreallocMode prealloc;
2321 int version = 3;
2322 uint64_t refcount_bits = 16;
2323 int refcount_order;
2324 Error *local_err = NULL;
2325 int ret;
2327 /* Read out options */
2328 size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
2329 BDRV_SECTOR_SIZE);
2330 backing_file = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
2331 backing_fmt = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FMT);
2332 if (qemu_opt_get_bool_del(opts, BLOCK_OPT_ENCRYPT, false)) {
2333 flags |= BLOCK_FLAG_ENCRYPT;
2335 cluster_size = qemu_opt_get_size_del(opts, BLOCK_OPT_CLUSTER_SIZE,
2336 DEFAULT_CLUSTER_SIZE);
2337 buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
2338 prealloc = qapi_enum_parse(PreallocMode_lookup, buf,
2339 PREALLOC_MODE__MAX, PREALLOC_MODE_OFF,
2340 &local_err);
2341 if (local_err) {
2342 error_propagate(errp, local_err);
2343 ret = -EINVAL;
2344 goto finish;
2346 g_free(buf);
2347 buf = qemu_opt_get_del(opts, BLOCK_OPT_COMPAT_LEVEL);
2348 if (!buf) {
2349 /* keep the default */
2350 } else if (!strcmp(buf, "0.10")) {
2351 version = 2;
2352 } else if (!strcmp(buf, "1.1")) {
2353 version = 3;
2354 } else {
2355 error_setg(errp, "Invalid compatibility level: '%s'", buf);
2356 ret = -EINVAL;
2357 goto finish;
2360 if (qemu_opt_get_bool_del(opts, BLOCK_OPT_LAZY_REFCOUNTS, false)) {
2361 flags |= BLOCK_FLAG_LAZY_REFCOUNTS;
2364 if (backing_file && prealloc != PREALLOC_MODE_OFF) {
2365 error_setg(errp, "Backing file and preallocation cannot be used at "
2366 "the same time");
2367 ret = -EINVAL;
2368 goto finish;
2371 if (version < 3 && (flags & BLOCK_FLAG_LAZY_REFCOUNTS)) {
2372 error_setg(errp, "Lazy refcounts only supported with compatibility "
2373 "level 1.1 and above (use compat=1.1 or greater)");
2374 ret = -EINVAL;
2375 goto finish;
2378 refcount_bits = qemu_opt_get_number_del(opts, BLOCK_OPT_REFCOUNT_BITS,
2379 refcount_bits);
2380 if (refcount_bits > 64 || !is_power_of_2(refcount_bits)) {
2381 error_setg(errp, "Refcount width must be a power of two and may not "
2382 "exceed 64 bits");
2383 ret = -EINVAL;
2384 goto finish;
2387 if (version < 3 && refcount_bits != 16) {
2388 error_setg(errp, "Different refcount widths than 16 bits require "
2389 "compatibility level 1.1 or above (use compat=1.1 or "
2390 "greater)");
2391 ret = -EINVAL;
2392 goto finish;
2395 refcount_order = ctz32(refcount_bits);
2397 ret = qcow2_create2(filename, size, backing_file, backing_fmt, flags,
2398 cluster_size, prealloc, opts, version, refcount_order,
2399 &local_err);
2400 if (local_err) {
2401 error_propagate(errp, local_err);
2404 finish:
2405 g_free(backing_file);
2406 g_free(backing_fmt);
2407 g_free(buf);
2408 return ret;
2412 static bool is_zero_sectors(BlockDriverState *bs, int64_t start,
2413 uint32_t count)
2415 int nr;
2416 BlockDriverState *file;
2417 int64_t res;
2419 if (!count) {
2420 return true;
2422 res = bdrv_get_block_status_above(bs, NULL, start, count,
2423 &nr, &file);
2424 return res >= 0 && (res & BDRV_BLOCK_ZERO) && nr == count;
2427 static coroutine_fn int qcow2_co_pwrite_zeroes(BlockDriverState *bs,
2428 int64_t offset, int count, BdrvRequestFlags flags)
2430 int ret;
2431 BDRVQcow2State *s = bs->opaque;
2433 uint32_t head = offset % s->cluster_size;
2434 uint32_t tail = (offset + count) % s->cluster_size;
2436 trace_qcow2_pwrite_zeroes_start_req(qemu_coroutine_self(), offset, count);
2438 if (head || tail) {
2439 int64_t cl_start = (offset - head) >> BDRV_SECTOR_BITS;
2440 uint64_t off;
2441 unsigned int nr;
2443 assert(head + count <= s->cluster_size);
2445 /* check whether remainder of cluster already reads as zero */
2446 if (!(is_zero_sectors(bs, cl_start,
2447 DIV_ROUND_UP(head, BDRV_SECTOR_SIZE)) &&
2448 is_zero_sectors(bs, (offset + count) >> BDRV_SECTOR_BITS,
2449 DIV_ROUND_UP(-tail & (s->cluster_size - 1),
2450 BDRV_SECTOR_SIZE)))) {
2451 return -ENOTSUP;
2454 qemu_co_mutex_lock(&s->lock);
2455 /* We can have new write after previous check */
2456 offset = cl_start << BDRV_SECTOR_BITS;
2457 count = s->cluster_size;
2458 nr = s->cluster_size;
2459 ret = qcow2_get_cluster_offset(bs, offset, &nr, &off);
2460 if (ret != QCOW2_CLUSTER_UNALLOCATED && ret != QCOW2_CLUSTER_ZERO) {
2461 qemu_co_mutex_unlock(&s->lock);
2462 return -ENOTSUP;
2464 } else {
2465 qemu_co_mutex_lock(&s->lock);
2468 trace_qcow2_pwrite_zeroes(qemu_coroutine_self(), offset, count);
2470 /* Whatever is left can use real zero clusters */
2471 ret = qcow2_zero_clusters(bs, offset, count >> BDRV_SECTOR_BITS);
2472 qemu_co_mutex_unlock(&s->lock);
2474 return ret;
2477 static coroutine_fn int qcow2_co_discard(BlockDriverState *bs,
2478 int64_t sector_num, int nb_sectors)
2480 int ret;
2481 BDRVQcow2State *s = bs->opaque;
2483 qemu_co_mutex_lock(&s->lock);
2484 ret = qcow2_discard_clusters(bs, sector_num << BDRV_SECTOR_BITS,
2485 nb_sectors, QCOW2_DISCARD_REQUEST, false);
2486 qemu_co_mutex_unlock(&s->lock);
2487 return ret;
2490 static int qcow2_truncate(BlockDriverState *bs, int64_t offset)
2492 BDRVQcow2State *s = bs->opaque;
2493 int64_t new_l1_size;
2494 int ret;
2496 if (offset & 511) {
2497 error_report("The new size must be a multiple of 512");
2498 return -EINVAL;
2501 /* cannot proceed if image has snapshots */
2502 if (s->nb_snapshots) {
2503 error_report("Can't resize an image which has snapshots");
2504 return -ENOTSUP;
2507 /* shrinking is currently not supported */
2508 if (offset < bs->total_sectors * 512) {
2509 error_report("qcow2 doesn't support shrinking images yet");
2510 return -ENOTSUP;
2513 new_l1_size = size_to_l1(s, offset);
2514 ret = qcow2_grow_l1_table(bs, new_l1_size, true);
2515 if (ret < 0) {
2516 return ret;
2519 /* write updated header.size */
2520 offset = cpu_to_be64(offset);
2521 ret = bdrv_pwrite_sync(bs->file->bs, offsetof(QCowHeader, size),
2522 &offset, sizeof(uint64_t));
2523 if (ret < 0) {
2524 return ret;
2527 s->l1_vm_state_index = new_l1_size;
2528 return 0;
2531 /* XXX: put compressed sectors first, then all the cluster aligned
2532 tables to avoid losing bytes in alignment */
2533 static int qcow2_write_compressed(BlockDriverState *bs, int64_t sector_num,
2534 const uint8_t *buf, int nb_sectors)
2536 BDRVQcow2State *s = bs->opaque;
2537 z_stream strm;
2538 int ret, out_len;
2539 uint8_t *out_buf;
2540 uint64_t cluster_offset;
2542 if (nb_sectors == 0) {
2543 /* align end of file to a sector boundary to ease reading with
2544 sector based I/Os */
2545 cluster_offset = bdrv_getlength(bs->file->bs);
2546 return bdrv_truncate(bs->file->bs, cluster_offset);
2549 if (nb_sectors != s->cluster_sectors) {
2550 ret = -EINVAL;
2552 /* Zero-pad last write if image size is not cluster aligned */
2553 if (sector_num + nb_sectors == bs->total_sectors &&
2554 nb_sectors < s->cluster_sectors) {
2555 uint8_t *pad_buf = qemu_blockalign(bs, s->cluster_size);
2556 memset(pad_buf, 0, s->cluster_size);
2557 memcpy(pad_buf, buf, nb_sectors * BDRV_SECTOR_SIZE);
2558 ret = qcow2_write_compressed(bs, sector_num,
2559 pad_buf, s->cluster_sectors);
2560 qemu_vfree(pad_buf);
2562 return ret;
2565 out_buf = g_malloc(s->cluster_size + (s->cluster_size / 1000) + 128);
2567 /* best compression, small window, no zlib header */
2568 memset(&strm, 0, sizeof(strm));
2569 ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
2570 Z_DEFLATED, -12,
2571 9, Z_DEFAULT_STRATEGY);
2572 if (ret != 0) {
2573 ret = -EINVAL;
2574 goto fail;
2577 strm.avail_in = s->cluster_size;
2578 strm.next_in = (uint8_t *)buf;
2579 strm.avail_out = s->cluster_size;
2580 strm.next_out = out_buf;
2582 ret = deflate(&strm, Z_FINISH);
2583 if (ret != Z_STREAM_END && ret != Z_OK) {
2584 deflateEnd(&strm);
2585 ret = -EINVAL;
2586 goto fail;
2588 out_len = strm.next_out - out_buf;
2590 deflateEnd(&strm);
2592 if (ret != Z_STREAM_END || out_len >= s->cluster_size) {
2593 /* could not compress: write normal cluster */
2594 ret = bdrv_write(bs, sector_num, buf, s->cluster_sectors);
2595 if (ret < 0) {
2596 goto fail;
2598 } else {
2599 cluster_offset = qcow2_alloc_compressed_cluster_offset(bs,
2600 sector_num << 9, out_len);
2601 if (!cluster_offset) {
2602 ret = -EIO;
2603 goto fail;
2605 cluster_offset &= s->cluster_offset_mask;
2607 ret = qcow2_pre_write_overlap_check(bs, 0, cluster_offset, out_len);
2608 if (ret < 0) {
2609 goto fail;
2612 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_COMPRESSED);
2613 ret = bdrv_pwrite(bs->file->bs, cluster_offset, out_buf, out_len);
2614 if (ret < 0) {
2615 goto fail;
2619 ret = 0;
2620 fail:
2621 g_free(out_buf);
2622 return ret;
2625 static int make_completely_empty(BlockDriverState *bs)
2627 BDRVQcow2State *s = bs->opaque;
2628 int ret, l1_clusters;
2629 int64_t offset;
2630 uint64_t *new_reftable = NULL;
2631 uint64_t rt_entry, l1_size2;
2632 struct {
2633 uint64_t l1_offset;
2634 uint64_t reftable_offset;
2635 uint32_t reftable_clusters;
2636 } QEMU_PACKED l1_ofs_rt_ofs_cls;
2638 ret = qcow2_cache_empty(bs, s->l2_table_cache);
2639 if (ret < 0) {
2640 goto fail;
2643 ret = qcow2_cache_empty(bs, s->refcount_block_cache);
2644 if (ret < 0) {
2645 goto fail;
2648 /* Refcounts will be broken utterly */
2649 ret = qcow2_mark_dirty(bs);
2650 if (ret < 0) {
2651 goto fail;
2654 BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
2656 l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / sizeof(uint64_t));
2657 l1_size2 = (uint64_t)s->l1_size * sizeof(uint64_t);
2659 /* After this call, neither the in-memory nor the on-disk refcount
2660 * information accurately describe the actual references */
2662 ret = bdrv_pwrite_zeroes(bs->file->bs, s->l1_table_offset,
2663 l1_clusters * s->cluster_size, 0);
2664 if (ret < 0) {
2665 goto fail_broken_refcounts;
2667 memset(s->l1_table, 0, l1_size2);
2669 BLKDBG_EVENT(bs->file, BLKDBG_EMPTY_IMAGE_PREPARE);
2671 /* Overwrite enough clusters at the beginning of the sectors to place
2672 * the refcount table, a refcount block and the L1 table in; this may
2673 * overwrite parts of the existing refcount and L1 table, which is not
2674 * an issue because the dirty flag is set, complete data loss is in fact
2675 * desired and partial data loss is consequently fine as well */
2676 ret = bdrv_pwrite_zeroes(bs->file->bs, s->cluster_size,
2677 (2 + l1_clusters) * s->cluster_size, 0);
2678 /* This call (even if it failed overall) may have overwritten on-disk
2679 * refcount structures; in that case, the in-memory refcount information
2680 * will probably differ from the on-disk information which makes the BDS
2681 * unusable */
2682 if (ret < 0) {
2683 goto fail_broken_refcounts;
2686 BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
2687 BLKDBG_EVENT(bs->file, BLKDBG_REFTABLE_UPDATE);
2689 /* "Create" an empty reftable (one cluster) directly after the image
2690 * header and an empty L1 table three clusters after the image header;
2691 * the cluster between those two will be used as the first refblock */
2692 cpu_to_be64w(&l1_ofs_rt_ofs_cls.l1_offset, 3 * s->cluster_size);
2693 cpu_to_be64w(&l1_ofs_rt_ofs_cls.reftable_offset, s->cluster_size);
2694 cpu_to_be32w(&l1_ofs_rt_ofs_cls.reftable_clusters, 1);
2695 ret = bdrv_pwrite_sync(bs->file->bs, offsetof(QCowHeader, l1_table_offset),
2696 &l1_ofs_rt_ofs_cls, sizeof(l1_ofs_rt_ofs_cls));
2697 if (ret < 0) {
2698 goto fail_broken_refcounts;
2701 s->l1_table_offset = 3 * s->cluster_size;
2703 new_reftable = g_try_new0(uint64_t, s->cluster_size / sizeof(uint64_t));
2704 if (!new_reftable) {
2705 ret = -ENOMEM;
2706 goto fail_broken_refcounts;
2709 s->refcount_table_offset = s->cluster_size;
2710 s->refcount_table_size = s->cluster_size / sizeof(uint64_t);
2712 g_free(s->refcount_table);
2713 s->refcount_table = new_reftable;
2714 new_reftable = NULL;
2716 /* Now the in-memory refcount information again corresponds to the on-disk
2717 * information (reftable is empty and no refblocks (the refblock cache is
2718 * empty)); however, this means some clusters (e.g. the image header) are
2719 * referenced, but not refcounted, but the normal qcow2 code assumes that
2720 * the in-memory information is always correct */
2722 BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_ALLOC);
2724 /* Enter the first refblock into the reftable */
2725 rt_entry = cpu_to_be64(2 * s->cluster_size);
2726 ret = bdrv_pwrite_sync(bs->file->bs, s->cluster_size,
2727 &rt_entry, sizeof(rt_entry));
2728 if (ret < 0) {
2729 goto fail_broken_refcounts;
2731 s->refcount_table[0] = 2 * s->cluster_size;
2733 s->free_cluster_index = 0;
2734 assert(3 + l1_clusters <= s->refcount_block_size);
2735 offset = qcow2_alloc_clusters(bs, 3 * s->cluster_size + l1_size2);
2736 if (offset < 0) {
2737 ret = offset;
2738 goto fail_broken_refcounts;
2739 } else if (offset > 0) {
2740 error_report("First cluster in emptied image is in use");
2741 abort();
2744 /* Now finally the in-memory information corresponds to the on-disk
2745 * structures and is correct */
2746 ret = qcow2_mark_clean(bs);
2747 if (ret < 0) {
2748 goto fail;
2751 ret = bdrv_truncate(bs->file->bs, (3 + l1_clusters) * s->cluster_size);
2752 if (ret < 0) {
2753 goto fail;
2756 return 0;
2758 fail_broken_refcounts:
2759 /* The BDS is unusable at this point. If we wanted to make it usable, we
2760 * would have to call qcow2_refcount_close(), qcow2_refcount_init(),
2761 * qcow2_check_refcounts(), qcow2_refcount_close() and qcow2_refcount_init()
2762 * again. However, because the functions which could have caused this error
2763 * path to be taken are used by those functions as well, it's very likely
2764 * that that sequence will fail as well. Therefore, just eject the BDS. */
2765 bs->drv = NULL;
2767 fail:
2768 g_free(new_reftable);
2769 return ret;
2772 static int qcow2_make_empty(BlockDriverState *bs)
2774 BDRVQcow2State *s = bs->opaque;
2775 uint64_t start_sector;
2776 int sector_step = INT_MAX / BDRV_SECTOR_SIZE;
2777 int l1_clusters, ret = 0;
2779 l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / sizeof(uint64_t));
2781 if (s->qcow_version >= 3 && !s->snapshots &&
2782 3 + l1_clusters <= s->refcount_block_size) {
2783 /* The following function only works for qcow2 v3 images (it requires
2784 * the dirty flag) and only as long as there are no snapshots (because
2785 * it completely empties the image). Furthermore, the L1 table and three
2786 * additional clusters (image header, refcount table, one refcount
2787 * block) have to fit inside one refcount block. */
2788 return make_completely_empty(bs);
2791 /* This fallback code simply discards every active cluster; this is slow,
2792 * but works in all cases */
2793 for (start_sector = 0; start_sector < bs->total_sectors;
2794 start_sector += sector_step)
2796 /* As this function is generally used after committing an external
2797 * snapshot, QCOW2_DISCARD_SNAPSHOT seems appropriate. Also, the
2798 * default action for this kind of discard is to pass the discard,
2799 * which will ideally result in an actually smaller image file, as
2800 * is probably desired. */
2801 ret = qcow2_discard_clusters(bs, start_sector * BDRV_SECTOR_SIZE,
2802 MIN(sector_step,
2803 bs->total_sectors - start_sector),
2804 QCOW2_DISCARD_SNAPSHOT, true);
2805 if (ret < 0) {
2806 break;
2810 return ret;
2813 static coroutine_fn int qcow2_co_flush_to_os(BlockDriverState *bs)
2815 BDRVQcow2State *s = bs->opaque;
2816 int ret;
2818 qemu_co_mutex_lock(&s->lock);
2819 ret = qcow2_cache_write(bs, s->l2_table_cache);
2820 if (ret < 0) {
2821 qemu_co_mutex_unlock(&s->lock);
2822 return ret;
2825 if (qcow2_need_accurate_refcounts(s)) {
2826 ret = qcow2_cache_write(bs, s->refcount_block_cache);
2827 if (ret < 0) {
2828 qemu_co_mutex_unlock(&s->lock);
2829 return ret;
2832 qemu_co_mutex_unlock(&s->lock);
2834 return 0;
2837 static int qcow2_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
2839 BDRVQcow2State *s = bs->opaque;
2840 bdi->unallocated_blocks_are_zero = true;
2841 bdi->can_write_zeroes_with_unmap = (s->qcow_version >= 3);
2842 bdi->cluster_size = s->cluster_size;
2843 bdi->vm_state_offset = qcow2_vm_state_offset(s);
2844 return 0;
2847 static ImageInfoSpecific *qcow2_get_specific_info(BlockDriverState *bs)
2849 BDRVQcow2State *s = bs->opaque;
2850 ImageInfoSpecific *spec_info = g_new(ImageInfoSpecific, 1);
2852 *spec_info = (ImageInfoSpecific){
2853 .type = IMAGE_INFO_SPECIFIC_KIND_QCOW2,
2854 .u.qcow2.data = g_new(ImageInfoSpecificQCow2, 1),
2856 if (s->qcow_version == 2) {
2857 *spec_info->u.qcow2.data = (ImageInfoSpecificQCow2){
2858 .compat = g_strdup("0.10"),
2859 .refcount_bits = s->refcount_bits,
2861 } else if (s->qcow_version == 3) {
2862 *spec_info->u.qcow2.data = (ImageInfoSpecificQCow2){
2863 .compat = g_strdup("1.1"),
2864 .lazy_refcounts = s->compatible_features &
2865 QCOW2_COMPAT_LAZY_REFCOUNTS,
2866 .has_lazy_refcounts = true,
2867 .corrupt = s->incompatible_features &
2868 QCOW2_INCOMPAT_CORRUPT,
2869 .has_corrupt = true,
2870 .refcount_bits = s->refcount_bits,
2872 } else {
2873 /* if this assertion fails, this probably means a new version was
2874 * added without having it covered here */
2875 assert(false);
2878 return spec_info;
2881 #if 0
2882 static void dump_refcounts(BlockDriverState *bs)
2884 BDRVQcow2State *s = bs->opaque;
2885 int64_t nb_clusters, k, k1, size;
2886 int refcount;
2888 size = bdrv_getlength(bs->file->bs);
2889 nb_clusters = size_to_clusters(s, size);
2890 for(k = 0; k < nb_clusters;) {
2891 k1 = k;
2892 refcount = get_refcount(bs, k);
2893 k++;
2894 while (k < nb_clusters && get_refcount(bs, k) == refcount)
2895 k++;
2896 printf("%" PRId64 ": refcount=%d nb=%" PRId64 "\n", k, refcount,
2897 k - k1);
2900 #endif
2902 static int qcow2_save_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
2903 int64_t pos)
2905 BDRVQcow2State *s = bs->opaque;
2906 int64_t total_sectors = bs->total_sectors;
2907 bool zero_beyond_eof = bs->zero_beyond_eof;
2908 int ret;
2910 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_SAVE);
2911 bs->zero_beyond_eof = false;
2912 ret = bdrv_pwritev(bs, qcow2_vm_state_offset(s) + pos, qiov);
2913 bs->zero_beyond_eof = zero_beyond_eof;
2915 /* bdrv_co_do_writev will have increased the total_sectors value to include
2916 * the VM state - the VM state is however not an actual part of the block
2917 * device, therefore, we need to restore the old value. */
2918 bs->total_sectors = total_sectors;
2920 return ret;
2923 static int qcow2_load_vmstate(BlockDriverState *bs, uint8_t *buf,
2924 int64_t pos, int size)
2926 BDRVQcow2State *s = bs->opaque;
2927 bool zero_beyond_eof = bs->zero_beyond_eof;
2928 int ret;
2930 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_LOAD);
2931 bs->zero_beyond_eof = false;
2932 ret = bdrv_pread(bs, qcow2_vm_state_offset(s) + pos, buf, size);
2933 bs->zero_beyond_eof = zero_beyond_eof;
2935 return ret;
2939 * Downgrades an image's version. To achieve this, any incompatible features
2940 * have to be removed.
2942 static int qcow2_downgrade(BlockDriverState *bs, int target_version,
2943 BlockDriverAmendStatusCB *status_cb, void *cb_opaque)
2945 BDRVQcow2State *s = bs->opaque;
2946 int current_version = s->qcow_version;
2947 int ret;
2949 if (target_version == current_version) {
2950 return 0;
2951 } else if (target_version > current_version) {
2952 return -EINVAL;
2953 } else if (target_version != 2) {
2954 return -EINVAL;
2957 if (s->refcount_order != 4) {
2958 error_report("compat=0.10 requires refcount_bits=16");
2959 return -ENOTSUP;
2962 /* clear incompatible features */
2963 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
2964 ret = qcow2_mark_clean(bs);
2965 if (ret < 0) {
2966 return ret;
2970 /* with QCOW2_INCOMPAT_CORRUPT, it is pretty much impossible to get here in
2971 * the first place; if that happens nonetheless, returning -ENOTSUP is the
2972 * best thing to do anyway */
2974 if (s->incompatible_features) {
2975 return -ENOTSUP;
2978 /* since we can ignore compatible features, we can set them to 0 as well */
2979 s->compatible_features = 0;
2980 /* if lazy refcounts have been used, they have already been fixed through
2981 * clearing the dirty flag */
2983 /* clearing autoclear features is trivial */
2984 s->autoclear_features = 0;
2986 ret = qcow2_expand_zero_clusters(bs, status_cb, cb_opaque);
2987 if (ret < 0) {
2988 return ret;
2991 s->qcow_version = target_version;
2992 ret = qcow2_update_header(bs);
2993 if (ret < 0) {
2994 s->qcow_version = current_version;
2995 return ret;
2997 return 0;
3000 typedef enum Qcow2AmendOperation {
3001 /* This is the value Qcow2AmendHelperCBInfo::last_operation will be
3002 * statically initialized to so that the helper CB can discern the first
3003 * invocation from an operation change */
3004 QCOW2_NO_OPERATION = 0,
3006 QCOW2_CHANGING_REFCOUNT_ORDER,
3007 QCOW2_DOWNGRADING,
3008 } Qcow2AmendOperation;
3010 typedef struct Qcow2AmendHelperCBInfo {
3011 /* The code coordinating the amend operations should only modify
3012 * these four fields; the rest will be managed by the CB */
3013 BlockDriverAmendStatusCB *original_status_cb;
3014 void *original_cb_opaque;
3016 Qcow2AmendOperation current_operation;
3018 /* Total number of operations to perform (only set once) */
3019 int total_operations;
3021 /* The following fields are managed by the CB */
3023 /* Number of operations completed */
3024 int operations_completed;
3026 /* Cumulative offset of all completed operations */
3027 int64_t offset_completed;
3029 Qcow2AmendOperation last_operation;
3030 int64_t last_work_size;
3031 } Qcow2AmendHelperCBInfo;
3033 static void qcow2_amend_helper_cb(BlockDriverState *bs,
3034 int64_t operation_offset,
3035 int64_t operation_work_size, void *opaque)
3037 Qcow2AmendHelperCBInfo *info = opaque;
3038 int64_t current_work_size;
3039 int64_t projected_work_size;
3041 if (info->current_operation != info->last_operation) {
3042 if (info->last_operation != QCOW2_NO_OPERATION) {
3043 info->offset_completed += info->last_work_size;
3044 info->operations_completed++;
3047 info->last_operation = info->current_operation;
3050 assert(info->total_operations > 0);
3051 assert(info->operations_completed < info->total_operations);
3053 info->last_work_size = operation_work_size;
3055 current_work_size = info->offset_completed + operation_work_size;
3057 /* current_work_size is the total work size for (operations_completed + 1)
3058 * operations (which includes this one), so multiply it by the number of
3059 * operations not covered and divide it by the number of operations
3060 * covered to get a projection for the operations not covered */
3061 projected_work_size = current_work_size * (info->total_operations -
3062 info->operations_completed - 1)
3063 / (info->operations_completed + 1);
3065 info->original_status_cb(bs, info->offset_completed + operation_offset,
3066 current_work_size + projected_work_size,
3067 info->original_cb_opaque);
3070 static int qcow2_amend_options(BlockDriverState *bs, QemuOpts *opts,
3071 BlockDriverAmendStatusCB *status_cb,
3072 void *cb_opaque)
3074 BDRVQcow2State *s = bs->opaque;
3075 int old_version = s->qcow_version, new_version = old_version;
3076 uint64_t new_size = 0;
3077 const char *backing_file = NULL, *backing_format = NULL;
3078 bool lazy_refcounts = s->use_lazy_refcounts;
3079 const char *compat = NULL;
3080 uint64_t cluster_size = s->cluster_size;
3081 bool encrypt;
3082 int refcount_bits = s->refcount_bits;
3083 int ret;
3084 QemuOptDesc *desc = opts->list->desc;
3085 Qcow2AmendHelperCBInfo helper_cb_info;
3087 while (desc && desc->name) {
3088 if (!qemu_opt_find(opts, desc->name)) {
3089 /* only change explicitly defined options */
3090 desc++;
3091 continue;
3094 if (!strcmp(desc->name, BLOCK_OPT_COMPAT_LEVEL)) {
3095 compat = qemu_opt_get(opts, BLOCK_OPT_COMPAT_LEVEL);
3096 if (!compat) {
3097 /* preserve default */
3098 } else if (!strcmp(compat, "0.10")) {
3099 new_version = 2;
3100 } else if (!strcmp(compat, "1.1")) {
3101 new_version = 3;
3102 } else {
3103 error_report("Unknown compatibility level %s", compat);
3104 return -EINVAL;
3106 } else if (!strcmp(desc->name, BLOCK_OPT_PREALLOC)) {
3107 error_report("Cannot change preallocation mode");
3108 return -ENOTSUP;
3109 } else if (!strcmp(desc->name, BLOCK_OPT_SIZE)) {
3110 new_size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, 0);
3111 } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FILE)) {
3112 backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
3113 } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FMT)) {
3114 backing_format = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
3115 } else if (!strcmp(desc->name, BLOCK_OPT_ENCRYPT)) {
3116 encrypt = qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT,
3117 !!s->cipher);
3119 if (encrypt != !!s->cipher) {
3120 error_report("Changing the encryption flag is not supported");
3121 return -ENOTSUP;
3123 } else if (!strcmp(desc->name, BLOCK_OPT_CLUSTER_SIZE)) {
3124 cluster_size = qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE,
3125 cluster_size);
3126 if (cluster_size != s->cluster_size) {
3127 error_report("Changing the cluster size is not supported");
3128 return -ENOTSUP;
3130 } else if (!strcmp(desc->name, BLOCK_OPT_LAZY_REFCOUNTS)) {
3131 lazy_refcounts = qemu_opt_get_bool(opts, BLOCK_OPT_LAZY_REFCOUNTS,
3132 lazy_refcounts);
3133 } else if (!strcmp(desc->name, BLOCK_OPT_REFCOUNT_BITS)) {
3134 refcount_bits = qemu_opt_get_number(opts, BLOCK_OPT_REFCOUNT_BITS,
3135 refcount_bits);
3137 if (refcount_bits <= 0 || refcount_bits > 64 ||
3138 !is_power_of_2(refcount_bits))
3140 error_report("Refcount width must be a power of two and may "
3141 "not exceed 64 bits");
3142 return -EINVAL;
3144 } else {
3145 /* if this point is reached, this probably means a new option was
3146 * added without having it covered here */
3147 abort();
3150 desc++;
3153 helper_cb_info = (Qcow2AmendHelperCBInfo){
3154 .original_status_cb = status_cb,
3155 .original_cb_opaque = cb_opaque,
3156 .total_operations = (new_version < old_version)
3157 + (s->refcount_bits != refcount_bits)
3160 /* Upgrade first (some features may require compat=1.1) */
3161 if (new_version > old_version) {
3162 s->qcow_version = new_version;
3163 ret = qcow2_update_header(bs);
3164 if (ret < 0) {
3165 s->qcow_version = old_version;
3166 return ret;
3170 if (s->refcount_bits != refcount_bits) {
3171 int refcount_order = ctz32(refcount_bits);
3172 Error *local_error = NULL;
3174 if (new_version < 3 && refcount_bits != 16) {
3175 error_report("Different refcount widths than 16 bits require "
3176 "compatibility level 1.1 or above (use compat=1.1 or "
3177 "greater)");
3178 return -EINVAL;
3181 helper_cb_info.current_operation = QCOW2_CHANGING_REFCOUNT_ORDER;
3182 ret = qcow2_change_refcount_order(bs, refcount_order,
3183 &qcow2_amend_helper_cb,
3184 &helper_cb_info, &local_error);
3185 if (ret < 0) {
3186 error_report_err(local_error);
3187 return ret;
3191 if (backing_file || backing_format) {
3192 ret = qcow2_change_backing_file(bs,
3193 backing_file ?: s->image_backing_file,
3194 backing_format ?: s->image_backing_format);
3195 if (ret < 0) {
3196 return ret;
3200 if (s->use_lazy_refcounts != lazy_refcounts) {
3201 if (lazy_refcounts) {
3202 if (new_version < 3) {
3203 error_report("Lazy refcounts only supported with compatibility "
3204 "level 1.1 and above (use compat=1.1 or greater)");
3205 return -EINVAL;
3207 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
3208 ret = qcow2_update_header(bs);
3209 if (ret < 0) {
3210 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
3211 return ret;
3213 s->use_lazy_refcounts = true;
3214 } else {
3215 /* make image clean first */
3216 ret = qcow2_mark_clean(bs);
3217 if (ret < 0) {
3218 return ret;
3220 /* now disallow lazy refcounts */
3221 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
3222 ret = qcow2_update_header(bs);
3223 if (ret < 0) {
3224 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
3225 return ret;
3227 s->use_lazy_refcounts = false;
3231 if (new_size) {
3232 ret = bdrv_truncate(bs, new_size);
3233 if (ret < 0) {
3234 return ret;
3238 /* Downgrade last (so unsupported features can be removed before) */
3239 if (new_version < old_version) {
3240 helper_cb_info.current_operation = QCOW2_DOWNGRADING;
3241 ret = qcow2_downgrade(bs, new_version, &qcow2_amend_helper_cb,
3242 &helper_cb_info);
3243 if (ret < 0) {
3244 return ret;
3248 return 0;
3252 * If offset or size are negative, respectively, they will not be included in
3253 * the BLOCK_IMAGE_CORRUPTED event emitted.
3254 * fatal will be ignored for read-only BDS; corruptions found there will always
3255 * be considered non-fatal.
3257 void qcow2_signal_corruption(BlockDriverState *bs, bool fatal, int64_t offset,
3258 int64_t size, const char *message_format, ...)
3260 BDRVQcow2State *s = bs->opaque;
3261 const char *node_name;
3262 char *message;
3263 va_list ap;
3265 fatal = fatal && !bs->read_only;
3267 if (s->signaled_corruption &&
3268 (!fatal || (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT)))
3270 return;
3273 va_start(ap, message_format);
3274 message = g_strdup_vprintf(message_format, ap);
3275 va_end(ap);
3277 if (fatal) {
3278 fprintf(stderr, "qcow2: Marking image as corrupt: %s; further "
3279 "corruption events will be suppressed\n", message);
3280 } else {
3281 fprintf(stderr, "qcow2: Image is corrupt: %s; further non-fatal "
3282 "corruption events will be suppressed\n", message);
3285 node_name = bdrv_get_node_name(bs);
3286 qapi_event_send_block_image_corrupted(bdrv_get_device_name(bs),
3287 *node_name != '\0', node_name,
3288 message, offset >= 0, offset,
3289 size >= 0, size,
3290 fatal, &error_abort);
3291 g_free(message);
3293 if (fatal) {
3294 qcow2_mark_corrupt(bs);
3295 bs->drv = NULL; /* make BDS unusable */
3298 s->signaled_corruption = true;
3301 static QemuOptsList qcow2_create_opts = {
3302 .name = "qcow2-create-opts",
3303 .head = QTAILQ_HEAD_INITIALIZER(qcow2_create_opts.head),
3304 .desc = {
3306 .name = BLOCK_OPT_SIZE,
3307 .type = QEMU_OPT_SIZE,
3308 .help = "Virtual disk size"
3311 .name = BLOCK_OPT_COMPAT_LEVEL,
3312 .type = QEMU_OPT_STRING,
3313 .help = "Compatibility level (0.10 or 1.1)"
3316 .name = BLOCK_OPT_BACKING_FILE,
3317 .type = QEMU_OPT_STRING,
3318 .help = "File name of a base image"
3321 .name = BLOCK_OPT_BACKING_FMT,
3322 .type = QEMU_OPT_STRING,
3323 .help = "Image format of the base image"
3326 .name = BLOCK_OPT_ENCRYPT,
3327 .type = QEMU_OPT_BOOL,
3328 .help = "Encrypt the image",
3329 .def_value_str = "off"
3332 .name = BLOCK_OPT_CLUSTER_SIZE,
3333 .type = QEMU_OPT_SIZE,
3334 .help = "qcow2 cluster size",
3335 .def_value_str = stringify(DEFAULT_CLUSTER_SIZE)
3338 .name = BLOCK_OPT_PREALLOC,
3339 .type = QEMU_OPT_STRING,
3340 .help = "Preallocation mode (allowed values: off, metadata, "
3341 "falloc, full)"
3344 .name = BLOCK_OPT_LAZY_REFCOUNTS,
3345 .type = QEMU_OPT_BOOL,
3346 .help = "Postpone refcount updates",
3347 .def_value_str = "off"
3350 .name = BLOCK_OPT_REFCOUNT_BITS,
3351 .type = QEMU_OPT_NUMBER,
3352 .help = "Width of a reference count entry in bits",
3353 .def_value_str = "16"
3355 { /* end of list */ }
3359 BlockDriver bdrv_qcow2 = {
3360 .format_name = "qcow2",
3361 .instance_size = sizeof(BDRVQcow2State),
3362 .bdrv_probe = qcow2_probe,
3363 .bdrv_open = qcow2_open,
3364 .bdrv_close = qcow2_close,
3365 .bdrv_reopen_prepare = qcow2_reopen_prepare,
3366 .bdrv_reopen_commit = qcow2_reopen_commit,
3367 .bdrv_reopen_abort = qcow2_reopen_abort,
3368 .bdrv_join_options = qcow2_join_options,
3369 .bdrv_create = qcow2_create,
3370 .bdrv_has_zero_init = bdrv_has_zero_init_1,
3371 .bdrv_co_get_block_status = qcow2_co_get_block_status,
3372 .bdrv_set_key = qcow2_set_key,
3374 .bdrv_co_preadv = qcow2_co_preadv,
3375 .bdrv_co_pwritev = qcow2_co_pwritev,
3376 .bdrv_co_flush_to_os = qcow2_co_flush_to_os,
3378 .bdrv_co_pwrite_zeroes = qcow2_co_pwrite_zeroes,
3379 .bdrv_co_discard = qcow2_co_discard,
3380 .bdrv_truncate = qcow2_truncate,
3381 .bdrv_write_compressed = qcow2_write_compressed,
3382 .bdrv_make_empty = qcow2_make_empty,
3384 .bdrv_snapshot_create = qcow2_snapshot_create,
3385 .bdrv_snapshot_goto = qcow2_snapshot_goto,
3386 .bdrv_snapshot_delete = qcow2_snapshot_delete,
3387 .bdrv_snapshot_list = qcow2_snapshot_list,
3388 .bdrv_snapshot_load_tmp = qcow2_snapshot_load_tmp,
3389 .bdrv_get_info = qcow2_get_info,
3390 .bdrv_get_specific_info = qcow2_get_specific_info,
3392 .bdrv_save_vmstate = qcow2_save_vmstate,
3393 .bdrv_load_vmstate = qcow2_load_vmstate,
3395 .supports_backing = true,
3396 .bdrv_change_backing_file = qcow2_change_backing_file,
3398 .bdrv_refresh_limits = qcow2_refresh_limits,
3399 .bdrv_invalidate_cache = qcow2_invalidate_cache,
3400 .bdrv_inactivate = qcow2_inactivate,
3402 .create_opts = &qcow2_create_opts,
3403 .bdrv_check = qcow2_check,
3404 .bdrv_amend_options = qcow2_amend_options,
3406 .bdrv_detach_aio_context = qcow2_detach_aio_context,
3407 .bdrv_attach_aio_context = qcow2_attach_aio_context,
3410 static void bdrv_qcow2_init(void)
3412 bdrv_register(&bdrv_qcow2);
3415 block_init(bdrv_qcow2_init);