vfio/pci: Allow relocating MSI-X MMIO
[qemu/ar7.git] / block / qcow2.c
blob1f80961e1b97bc315c04da298f1be02e893d6ef0
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/qmp/types.h"
34 #include "qapi-event.h"
35 #include "trace.h"
36 #include "qemu/option_int.h"
37 #include "qemu/cutils.h"
38 #include "qemu/bswap.h"
39 #include "qapi/opts-visitor.h"
40 #include "qapi-visit.h"
41 #include "block/crypto.h"
44 Differences with QCOW:
46 - Support for multiple incremental snapshots.
47 - Memory management by reference counts.
48 - Clusters which have a reference count of one have the bit
49 QCOW_OFLAG_COPIED to optimize write performance.
50 - Size of compressed clusters is stored in sectors to reduce bit usage
51 in the cluster offsets.
52 - Support for storing additional data (such as the VM state) in the
53 snapshots.
54 - If a backing store is used, the cluster size is not constrained
55 (could be backported to QCOW).
56 - L2 tables have always a size of one cluster.
60 typedef struct {
61 uint32_t magic;
62 uint32_t len;
63 } QEMU_PACKED QCowExtension;
65 #define QCOW2_EXT_MAGIC_END 0
66 #define QCOW2_EXT_MAGIC_BACKING_FORMAT 0xE2792ACA
67 #define QCOW2_EXT_MAGIC_FEATURE_TABLE 0x6803f857
68 #define QCOW2_EXT_MAGIC_CRYPTO_HEADER 0x0537be77
69 #define QCOW2_EXT_MAGIC_BITMAPS 0x23852875
71 static int qcow2_probe(const uint8_t *buf, int buf_size, const char *filename)
73 const QCowHeader *cow_header = (const void *)buf;
75 if (buf_size >= sizeof(QCowHeader) &&
76 be32_to_cpu(cow_header->magic) == QCOW_MAGIC &&
77 be32_to_cpu(cow_header->version) >= 2)
78 return 100;
79 else
80 return 0;
84 static ssize_t qcow2_crypto_hdr_read_func(QCryptoBlock *block, size_t offset,
85 uint8_t *buf, size_t buflen,
86 void *opaque, Error **errp)
88 BlockDriverState *bs = opaque;
89 BDRVQcow2State *s = bs->opaque;
90 ssize_t ret;
92 if ((offset + buflen) > s->crypto_header.length) {
93 error_setg(errp, "Request for data outside of extension header");
94 return -1;
97 ret = bdrv_pread(bs->file,
98 s->crypto_header.offset + offset, buf, buflen);
99 if (ret < 0) {
100 error_setg_errno(errp, -ret, "Could not read encryption header");
101 return -1;
103 return ret;
107 static ssize_t qcow2_crypto_hdr_init_func(QCryptoBlock *block, size_t headerlen,
108 void *opaque, Error **errp)
110 BlockDriverState *bs = opaque;
111 BDRVQcow2State *s = bs->opaque;
112 int64_t ret;
113 int64_t clusterlen;
115 ret = qcow2_alloc_clusters(bs, headerlen);
116 if (ret < 0) {
117 error_setg_errno(errp, -ret,
118 "Cannot allocate cluster for LUKS header size %zu",
119 headerlen);
120 return -1;
123 s->crypto_header.length = headerlen;
124 s->crypto_header.offset = ret;
126 /* Zero fill remaining space in cluster so it has predictable
127 * content in case of future spec changes */
128 clusterlen = size_to_clusters(s, headerlen) * s->cluster_size;
129 assert(qcow2_pre_write_overlap_check(bs, 0, ret, clusterlen) == 0);
130 ret = bdrv_pwrite_zeroes(bs->file,
131 ret + headerlen,
132 clusterlen - headerlen, 0);
133 if (ret < 0) {
134 error_setg_errno(errp, -ret, "Could not zero fill encryption header");
135 return -1;
138 return ret;
142 static ssize_t qcow2_crypto_hdr_write_func(QCryptoBlock *block, size_t offset,
143 const uint8_t *buf, size_t buflen,
144 void *opaque, Error **errp)
146 BlockDriverState *bs = opaque;
147 BDRVQcow2State *s = bs->opaque;
148 ssize_t ret;
150 if ((offset + buflen) > s->crypto_header.length) {
151 error_setg(errp, "Request for data outside of extension header");
152 return -1;
155 ret = bdrv_pwrite(bs->file,
156 s->crypto_header.offset + offset, buf, buflen);
157 if (ret < 0) {
158 error_setg_errno(errp, -ret, "Could not read encryption header");
159 return -1;
161 return ret;
166 * read qcow2 extension and fill bs
167 * start reading from start_offset
168 * finish reading upon magic of value 0 or when end_offset reached
169 * unknown magic is skipped (future extension this version knows nothing about)
170 * return 0 upon success, non-0 otherwise
172 static int qcow2_read_extensions(BlockDriverState *bs, uint64_t start_offset,
173 uint64_t end_offset, void **p_feature_table,
174 int flags, bool *need_update_header,
175 Error **errp)
177 BDRVQcow2State *s = bs->opaque;
178 QCowExtension ext;
179 uint64_t offset;
180 int ret;
181 Qcow2BitmapHeaderExt bitmaps_ext;
183 if (need_update_header != NULL) {
184 *need_update_header = false;
187 #ifdef DEBUG_EXT
188 printf("qcow2_read_extensions: start=%ld end=%ld\n", start_offset, end_offset);
189 #endif
190 offset = start_offset;
191 while (offset < end_offset) {
193 #ifdef DEBUG_EXT
194 /* Sanity check */
195 if (offset > s->cluster_size)
196 printf("qcow2_read_extension: suspicious offset %lu\n", offset);
198 printf("attempting to read extended header in offset %lu\n", offset);
199 #endif
201 ret = bdrv_pread(bs->file, offset, &ext, sizeof(ext));
202 if (ret < 0) {
203 error_setg_errno(errp, -ret, "qcow2_read_extension: ERROR: "
204 "pread fail from offset %" PRIu64, offset);
205 return 1;
207 be32_to_cpus(&ext.magic);
208 be32_to_cpus(&ext.len);
209 offset += sizeof(ext);
210 #ifdef DEBUG_EXT
211 printf("ext.magic = 0x%x\n", ext.magic);
212 #endif
213 if (offset > end_offset || ext.len > end_offset - offset) {
214 error_setg(errp, "Header extension too large");
215 return -EINVAL;
218 switch (ext.magic) {
219 case QCOW2_EXT_MAGIC_END:
220 return 0;
222 case QCOW2_EXT_MAGIC_BACKING_FORMAT:
223 if (ext.len >= sizeof(bs->backing_format)) {
224 error_setg(errp, "ERROR: ext_backing_format: len=%" PRIu32
225 " too large (>=%zu)", ext.len,
226 sizeof(bs->backing_format));
227 return 2;
229 ret = bdrv_pread(bs->file, offset, bs->backing_format, ext.len);
230 if (ret < 0) {
231 error_setg_errno(errp, -ret, "ERROR: ext_backing_format: "
232 "Could not read format name");
233 return 3;
235 bs->backing_format[ext.len] = '\0';
236 s->image_backing_format = g_strdup(bs->backing_format);
237 #ifdef DEBUG_EXT
238 printf("Qcow2: Got format extension %s\n", bs->backing_format);
239 #endif
240 break;
242 case QCOW2_EXT_MAGIC_FEATURE_TABLE:
243 if (p_feature_table != NULL) {
244 void* feature_table = g_malloc0(ext.len + 2 * sizeof(Qcow2Feature));
245 ret = bdrv_pread(bs->file, offset , feature_table, ext.len);
246 if (ret < 0) {
247 error_setg_errno(errp, -ret, "ERROR: ext_feature_table: "
248 "Could not read table");
249 return ret;
252 *p_feature_table = feature_table;
254 break;
256 case QCOW2_EXT_MAGIC_CRYPTO_HEADER: {
257 unsigned int cflags = 0;
258 if (s->crypt_method_header != QCOW_CRYPT_LUKS) {
259 error_setg(errp, "CRYPTO header extension only "
260 "expected with LUKS encryption method");
261 return -EINVAL;
263 if (ext.len != sizeof(Qcow2CryptoHeaderExtension)) {
264 error_setg(errp, "CRYPTO header extension size %u, "
265 "but expected size %zu", ext.len,
266 sizeof(Qcow2CryptoHeaderExtension));
267 return -EINVAL;
270 ret = bdrv_pread(bs->file, offset, &s->crypto_header, ext.len);
271 if (ret < 0) {
272 error_setg_errno(errp, -ret,
273 "Unable to read CRYPTO header extension");
274 return ret;
276 be64_to_cpus(&s->crypto_header.offset);
277 be64_to_cpus(&s->crypto_header.length);
279 if ((s->crypto_header.offset % s->cluster_size) != 0) {
280 error_setg(errp, "Encryption header offset '%" PRIu64 "' is "
281 "not a multiple of cluster size '%u'",
282 s->crypto_header.offset, s->cluster_size);
283 return -EINVAL;
286 if (flags & BDRV_O_NO_IO) {
287 cflags |= QCRYPTO_BLOCK_OPEN_NO_IO;
289 s->crypto = qcrypto_block_open(s->crypto_opts, "encrypt.",
290 qcow2_crypto_hdr_read_func,
291 bs, cflags, errp);
292 if (!s->crypto) {
293 return -EINVAL;
295 } break;
297 case QCOW2_EXT_MAGIC_BITMAPS:
298 if (ext.len != sizeof(bitmaps_ext)) {
299 error_setg_errno(errp, -ret, "bitmaps_ext: "
300 "Invalid extension length");
301 return -EINVAL;
304 if (!(s->autoclear_features & QCOW2_AUTOCLEAR_BITMAPS)) {
305 if (s->qcow_version < 3) {
306 /* Let's be a bit more specific */
307 warn_report("This qcow2 v2 image contains bitmaps, but "
308 "they may have been modified by a program "
309 "without persistent bitmap support; so now "
310 "they must all be considered inconsistent");
311 } else {
312 warn_report("a program lacking bitmap support "
313 "modified this file, so all bitmaps are now "
314 "considered inconsistent");
316 error_printf("Some clusters may be leaked, "
317 "run 'qemu-img check -r' on the image "
318 "file to fix.");
319 if (need_update_header != NULL) {
320 /* Updating is needed to drop invalid bitmap extension. */
321 *need_update_header = true;
323 break;
326 ret = bdrv_pread(bs->file, offset, &bitmaps_ext, ext.len);
327 if (ret < 0) {
328 error_setg_errno(errp, -ret, "bitmaps_ext: "
329 "Could not read ext header");
330 return ret;
333 if (bitmaps_ext.reserved32 != 0) {
334 error_setg_errno(errp, -ret, "bitmaps_ext: "
335 "Reserved field is not zero");
336 return -EINVAL;
339 be32_to_cpus(&bitmaps_ext.nb_bitmaps);
340 be64_to_cpus(&bitmaps_ext.bitmap_directory_size);
341 be64_to_cpus(&bitmaps_ext.bitmap_directory_offset);
343 if (bitmaps_ext.nb_bitmaps > QCOW2_MAX_BITMAPS) {
344 error_setg(errp,
345 "bitmaps_ext: Image has %" PRIu32 " bitmaps, "
346 "exceeding the QEMU supported maximum of %d",
347 bitmaps_ext.nb_bitmaps, QCOW2_MAX_BITMAPS);
348 return -EINVAL;
351 if (bitmaps_ext.nb_bitmaps == 0) {
352 error_setg(errp, "found bitmaps extension with zero bitmaps");
353 return -EINVAL;
356 if (bitmaps_ext.bitmap_directory_offset & (s->cluster_size - 1)) {
357 error_setg(errp, "bitmaps_ext: "
358 "invalid bitmap directory offset");
359 return -EINVAL;
362 if (bitmaps_ext.bitmap_directory_size >
363 QCOW2_MAX_BITMAP_DIRECTORY_SIZE) {
364 error_setg(errp, "bitmaps_ext: "
365 "bitmap directory size (%" PRIu64 ") exceeds "
366 "the maximum supported size (%d)",
367 bitmaps_ext.bitmap_directory_size,
368 QCOW2_MAX_BITMAP_DIRECTORY_SIZE);
369 return -EINVAL;
372 s->nb_bitmaps = bitmaps_ext.nb_bitmaps;
373 s->bitmap_directory_offset =
374 bitmaps_ext.bitmap_directory_offset;
375 s->bitmap_directory_size =
376 bitmaps_ext.bitmap_directory_size;
378 #ifdef DEBUG_EXT
379 printf("Qcow2: Got bitmaps extension: "
380 "offset=%" PRIu64 " nb_bitmaps=%" PRIu32 "\n",
381 s->bitmap_directory_offset, s->nb_bitmaps);
382 #endif
383 break;
385 default:
386 /* unknown magic - save it in case we need to rewrite the header */
387 /* If you add a new feature, make sure to also update the fast
388 * path of qcow2_make_empty() to deal with it. */
390 Qcow2UnknownHeaderExtension *uext;
392 uext = g_malloc0(sizeof(*uext) + ext.len);
393 uext->magic = ext.magic;
394 uext->len = ext.len;
395 QLIST_INSERT_HEAD(&s->unknown_header_ext, uext, next);
397 ret = bdrv_pread(bs->file, offset , uext->data, uext->len);
398 if (ret < 0) {
399 error_setg_errno(errp, -ret, "ERROR: unknown extension: "
400 "Could not read data");
401 return ret;
404 break;
407 offset += ((ext.len + 7) & ~7);
410 return 0;
413 static void cleanup_unknown_header_ext(BlockDriverState *bs)
415 BDRVQcow2State *s = bs->opaque;
416 Qcow2UnknownHeaderExtension *uext, *next;
418 QLIST_FOREACH_SAFE(uext, &s->unknown_header_ext, next, next) {
419 QLIST_REMOVE(uext, next);
420 g_free(uext);
424 static void report_unsupported_feature(Error **errp, Qcow2Feature *table,
425 uint64_t mask)
427 char *features = g_strdup("");
428 char *old;
430 while (table && table->name[0] != '\0') {
431 if (table->type == QCOW2_FEAT_TYPE_INCOMPATIBLE) {
432 if (mask & (1ULL << table->bit)) {
433 old = features;
434 features = g_strdup_printf("%s%s%.46s", old, *old ? ", " : "",
435 table->name);
436 g_free(old);
437 mask &= ~(1ULL << table->bit);
440 table++;
443 if (mask) {
444 old = features;
445 features = g_strdup_printf("%s%sUnknown incompatible feature: %" PRIx64,
446 old, *old ? ", " : "", mask);
447 g_free(old);
450 error_setg(errp, "Unsupported qcow2 feature(s): %s", features);
451 g_free(features);
455 * Sets the dirty bit and flushes afterwards if necessary.
457 * The incompatible_features bit is only set if the image file header was
458 * updated successfully. Therefore it is not required to check the return
459 * value of this function.
461 int qcow2_mark_dirty(BlockDriverState *bs)
463 BDRVQcow2State *s = bs->opaque;
464 uint64_t val;
465 int ret;
467 assert(s->qcow_version >= 3);
469 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
470 return 0; /* already dirty */
473 val = cpu_to_be64(s->incompatible_features | QCOW2_INCOMPAT_DIRTY);
474 ret = bdrv_pwrite(bs->file, offsetof(QCowHeader, incompatible_features),
475 &val, sizeof(val));
476 if (ret < 0) {
477 return ret;
479 ret = bdrv_flush(bs->file->bs);
480 if (ret < 0) {
481 return ret;
484 /* Only treat image as dirty if the header was updated successfully */
485 s->incompatible_features |= QCOW2_INCOMPAT_DIRTY;
486 return 0;
490 * Clears the dirty bit and flushes before if necessary. Only call this
491 * function when there are no pending requests, it does not guard against
492 * concurrent requests dirtying the image.
494 static int qcow2_mark_clean(BlockDriverState *bs)
496 BDRVQcow2State *s = bs->opaque;
498 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
499 int ret;
501 s->incompatible_features &= ~QCOW2_INCOMPAT_DIRTY;
503 ret = bdrv_flush(bs);
504 if (ret < 0) {
505 return ret;
508 return qcow2_update_header(bs);
510 return 0;
514 * Marks the image as corrupt.
516 int qcow2_mark_corrupt(BlockDriverState *bs)
518 BDRVQcow2State *s = bs->opaque;
520 s->incompatible_features |= QCOW2_INCOMPAT_CORRUPT;
521 return qcow2_update_header(bs);
525 * Marks the image as consistent, i.e., unsets the corrupt bit, and flushes
526 * before if necessary.
528 int qcow2_mark_consistent(BlockDriverState *bs)
530 BDRVQcow2State *s = bs->opaque;
532 if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
533 int ret = bdrv_flush(bs);
534 if (ret < 0) {
535 return ret;
538 s->incompatible_features &= ~QCOW2_INCOMPAT_CORRUPT;
539 return qcow2_update_header(bs);
541 return 0;
544 static int qcow2_check(BlockDriverState *bs, BdrvCheckResult *result,
545 BdrvCheckMode fix)
547 int ret = qcow2_check_refcounts(bs, result, fix);
548 if (ret < 0) {
549 return ret;
552 if (fix && result->check_errors == 0 && result->corruptions == 0) {
553 ret = qcow2_mark_clean(bs);
554 if (ret < 0) {
555 return ret;
557 return qcow2_mark_consistent(bs);
559 return ret;
562 static int validate_table_offset(BlockDriverState *bs, uint64_t offset,
563 uint64_t entries, size_t entry_len)
565 BDRVQcow2State *s = bs->opaque;
566 uint64_t size;
568 /* Use signed INT64_MAX as the maximum even for uint64_t header fields,
569 * because values will be passed to qemu functions taking int64_t. */
570 if (entries > INT64_MAX / entry_len) {
571 return -EINVAL;
574 size = entries * entry_len;
576 if (INT64_MAX - size < offset) {
577 return -EINVAL;
580 /* Tables must be cluster aligned */
581 if (offset_into_cluster(s, offset) != 0) {
582 return -EINVAL;
585 return 0;
588 static QemuOptsList qcow2_runtime_opts = {
589 .name = "qcow2",
590 .head = QTAILQ_HEAD_INITIALIZER(qcow2_runtime_opts.head),
591 .desc = {
593 .name = QCOW2_OPT_LAZY_REFCOUNTS,
594 .type = QEMU_OPT_BOOL,
595 .help = "Postpone refcount updates",
598 .name = QCOW2_OPT_DISCARD_REQUEST,
599 .type = QEMU_OPT_BOOL,
600 .help = "Pass guest discard requests to the layer below",
603 .name = QCOW2_OPT_DISCARD_SNAPSHOT,
604 .type = QEMU_OPT_BOOL,
605 .help = "Generate discard requests when snapshot related space "
606 "is freed",
609 .name = QCOW2_OPT_DISCARD_OTHER,
610 .type = QEMU_OPT_BOOL,
611 .help = "Generate discard requests when other clusters are freed",
614 .name = QCOW2_OPT_OVERLAP,
615 .type = QEMU_OPT_STRING,
616 .help = "Selects which overlap checks to perform from a range of "
617 "templates (none, constant, cached, all)",
620 .name = QCOW2_OPT_OVERLAP_TEMPLATE,
621 .type = QEMU_OPT_STRING,
622 .help = "Selects which overlap checks to perform from a range of "
623 "templates (none, constant, cached, all)",
626 .name = QCOW2_OPT_OVERLAP_MAIN_HEADER,
627 .type = QEMU_OPT_BOOL,
628 .help = "Check for unintended writes into the main qcow2 header",
631 .name = QCOW2_OPT_OVERLAP_ACTIVE_L1,
632 .type = QEMU_OPT_BOOL,
633 .help = "Check for unintended writes into the active L1 table",
636 .name = QCOW2_OPT_OVERLAP_ACTIVE_L2,
637 .type = QEMU_OPT_BOOL,
638 .help = "Check for unintended writes into an active L2 table",
641 .name = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
642 .type = QEMU_OPT_BOOL,
643 .help = "Check for unintended writes into the refcount table",
646 .name = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
647 .type = QEMU_OPT_BOOL,
648 .help = "Check for unintended writes into a refcount block",
651 .name = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
652 .type = QEMU_OPT_BOOL,
653 .help = "Check for unintended writes into the snapshot table",
656 .name = QCOW2_OPT_OVERLAP_INACTIVE_L1,
657 .type = QEMU_OPT_BOOL,
658 .help = "Check for unintended writes into an inactive L1 table",
661 .name = QCOW2_OPT_OVERLAP_INACTIVE_L2,
662 .type = QEMU_OPT_BOOL,
663 .help = "Check for unintended writes into an inactive L2 table",
666 .name = QCOW2_OPT_CACHE_SIZE,
667 .type = QEMU_OPT_SIZE,
668 .help = "Maximum combined metadata (L2 tables and refcount blocks) "
669 "cache size",
672 .name = QCOW2_OPT_L2_CACHE_SIZE,
673 .type = QEMU_OPT_SIZE,
674 .help = "Maximum L2 table cache size",
677 .name = QCOW2_OPT_REFCOUNT_CACHE_SIZE,
678 .type = QEMU_OPT_SIZE,
679 .help = "Maximum refcount block cache size",
682 .name = QCOW2_OPT_CACHE_CLEAN_INTERVAL,
683 .type = QEMU_OPT_NUMBER,
684 .help = "Clean unused cache entries after this time (in seconds)",
686 BLOCK_CRYPTO_OPT_DEF_KEY_SECRET("encrypt.",
687 "ID of secret providing qcow2 AES key or LUKS passphrase"),
688 { /* end of list */ }
692 static const char *overlap_bool_option_names[QCOW2_OL_MAX_BITNR] = {
693 [QCOW2_OL_MAIN_HEADER_BITNR] = QCOW2_OPT_OVERLAP_MAIN_HEADER,
694 [QCOW2_OL_ACTIVE_L1_BITNR] = QCOW2_OPT_OVERLAP_ACTIVE_L1,
695 [QCOW2_OL_ACTIVE_L2_BITNR] = QCOW2_OPT_OVERLAP_ACTIVE_L2,
696 [QCOW2_OL_REFCOUNT_TABLE_BITNR] = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
697 [QCOW2_OL_REFCOUNT_BLOCK_BITNR] = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
698 [QCOW2_OL_SNAPSHOT_TABLE_BITNR] = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
699 [QCOW2_OL_INACTIVE_L1_BITNR] = QCOW2_OPT_OVERLAP_INACTIVE_L1,
700 [QCOW2_OL_INACTIVE_L2_BITNR] = QCOW2_OPT_OVERLAP_INACTIVE_L2,
703 static void cache_clean_timer_cb(void *opaque)
705 BlockDriverState *bs = opaque;
706 BDRVQcow2State *s = bs->opaque;
707 qcow2_cache_clean_unused(bs, s->l2_table_cache);
708 qcow2_cache_clean_unused(bs, s->refcount_block_cache);
709 timer_mod(s->cache_clean_timer, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) +
710 (int64_t) s->cache_clean_interval * 1000);
713 static void cache_clean_timer_init(BlockDriverState *bs, AioContext *context)
715 BDRVQcow2State *s = bs->opaque;
716 if (s->cache_clean_interval > 0) {
717 s->cache_clean_timer = aio_timer_new(context, QEMU_CLOCK_VIRTUAL,
718 SCALE_MS, cache_clean_timer_cb,
719 bs);
720 timer_mod(s->cache_clean_timer, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) +
721 (int64_t) s->cache_clean_interval * 1000);
725 static void cache_clean_timer_del(BlockDriverState *bs)
727 BDRVQcow2State *s = bs->opaque;
728 if (s->cache_clean_timer) {
729 timer_del(s->cache_clean_timer);
730 timer_free(s->cache_clean_timer);
731 s->cache_clean_timer = NULL;
735 static void qcow2_detach_aio_context(BlockDriverState *bs)
737 cache_clean_timer_del(bs);
740 static void qcow2_attach_aio_context(BlockDriverState *bs,
741 AioContext *new_context)
743 cache_clean_timer_init(bs, new_context);
746 static void read_cache_sizes(BlockDriverState *bs, QemuOpts *opts,
747 uint64_t *l2_cache_size,
748 uint64_t *refcount_cache_size, Error **errp)
750 BDRVQcow2State *s = bs->opaque;
751 uint64_t combined_cache_size;
752 bool l2_cache_size_set, refcount_cache_size_set, combined_cache_size_set;
754 combined_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_CACHE_SIZE);
755 l2_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_L2_CACHE_SIZE);
756 refcount_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
758 combined_cache_size = qemu_opt_get_size(opts, QCOW2_OPT_CACHE_SIZE, 0);
759 *l2_cache_size = qemu_opt_get_size(opts, QCOW2_OPT_L2_CACHE_SIZE, 0);
760 *refcount_cache_size = qemu_opt_get_size(opts,
761 QCOW2_OPT_REFCOUNT_CACHE_SIZE, 0);
763 if (combined_cache_size_set) {
764 if (l2_cache_size_set && refcount_cache_size_set) {
765 error_setg(errp, QCOW2_OPT_CACHE_SIZE ", " QCOW2_OPT_L2_CACHE_SIZE
766 " and " QCOW2_OPT_REFCOUNT_CACHE_SIZE " may not be set "
767 "the same time");
768 return;
769 } else if (*l2_cache_size > combined_cache_size) {
770 error_setg(errp, QCOW2_OPT_L2_CACHE_SIZE " may not exceed "
771 QCOW2_OPT_CACHE_SIZE);
772 return;
773 } else if (*refcount_cache_size > combined_cache_size) {
774 error_setg(errp, QCOW2_OPT_REFCOUNT_CACHE_SIZE " may not exceed "
775 QCOW2_OPT_CACHE_SIZE);
776 return;
779 if (l2_cache_size_set) {
780 *refcount_cache_size = combined_cache_size - *l2_cache_size;
781 } else if (refcount_cache_size_set) {
782 *l2_cache_size = combined_cache_size - *refcount_cache_size;
783 } else {
784 *refcount_cache_size = combined_cache_size
785 / (DEFAULT_L2_REFCOUNT_SIZE_RATIO + 1);
786 *l2_cache_size = combined_cache_size - *refcount_cache_size;
788 } else {
789 if (!l2_cache_size_set && !refcount_cache_size_set) {
790 *l2_cache_size = MAX(DEFAULT_L2_CACHE_BYTE_SIZE,
791 (uint64_t)DEFAULT_L2_CACHE_CLUSTERS
792 * s->cluster_size);
793 *refcount_cache_size = *l2_cache_size
794 / DEFAULT_L2_REFCOUNT_SIZE_RATIO;
795 } else if (!l2_cache_size_set) {
796 *l2_cache_size = *refcount_cache_size
797 * DEFAULT_L2_REFCOUNT_SIZE_RATIO;
798 } else if (!refcount_cache_size_set) {
799 *refcount_cache_size = *l2_cache_size
800 / DEFAULT_L2_REFCOUNT_SIZE_RATIO;
805 typedef struct Qcow2ReopenState {
806 Qcow2Cache *l2_table_cache;
807 Qcow2Cache *refcount_block_cache;
808 bool use_lazy_refcounts;
809 int overlap_check;
810 bool discard_passthrough[QCOW2_DISCARD_MAX];
811 uint64_t cache_clean_interval;
812 QCryptoBlockOpenOptions *crypto_opts; /* Disk encryption runtime options */
813 } Qcow2ReopenState;
815 static int qcow2_update_options_prepare(BlockDriverState *bs,
816 Qcow2ReopenState *r,
817 QDict *options, int flags,
818 Error **errp)
820 BDRVQcow2State *s = bs->opaque;
821 QemuOpts *opts = NULL;
822 const char *opt_overlap_check, *opt_overlap_check_template;
823 int overlap_check_template = 0;
824 uint64_t l2_cache_size, refcount_cache_size;
825 int i;
826 const char *encryptfmt;
827 QDict *encryptopts = NULL;
828 Error *local_err = NULL;
829 int ret;
831 qdict_extract_subqdict(options, &encryptopts, "encrypt.");
832 encryptfmt = qdict_get_try_str(encryptopts, "format");
834 opts = qemu_opts_create(&qcow2_runtime_opts, NULL, 0, &error_abort);
835 qemu_opts_absorb_qdict(opts, options, &local_err);
836 if (local_err) {
837 error_propagate(errp, local_err);
838 ret = -EINVAL;
839 goto fail;
842 /* get L2 table/refcount block cache size from command line options */
843 read_cache_sizes(bs, opts, &l2_cache_size, &refcount_cache_size,
844 &local_err);
845 if (local_err) {
846 error_propagate(errp, local_err);
847 ret = -EINVAL;
848 goto fail;
851 l2_cache_size /= s->cluster_size;
852 if (l2_cache_size < MIN_L2_CACHE_SIZE) {
853 l2_cache_size = MIN_L2_CACHE_SIZE;
855 if (l2_cache_size > INT_MAX) {
856 error_setg(errp, "L2 cache size too big");
857 ret = -EINVAL;
858 goto fail;
861 refcount_cache_size /= s->cluster_size;
862 if (refcount_cache_size < MIN_REFCOUNT_CACHE_SIZE) {
863 refcount_cache_size = MIN_REFCOUNT_CACHE_SIZE;
865 if (refcount_cache_size > INT_MAX) {
866 error_setg(errp, "Refcount cache size too big");
867 ret = -EINVAL;
868 goto fail;
871 /* alloc new L2 table/refcount block cache, flush old one */
872 if (s->l2_table_cache) {
873 ret = qcow2_cache_flush(bs, s->l2_table_cache);
874 if (ret) {
875 error_setg_errno(errp, -ret, "Failed to flush the L2 table cache");
876 goto fail;
880 if (s->refcount_block_cache) {
881 ret = qcow2_cache_flush(bs, s->refcount_block_cache);
882 if (ret) {
883 error_setg_errno(errp, -ret,
884 "Failed to flush the refcount block cache");
885 goto fail;
889 r->l2_table_cache = qcow2_cache_create(bs, l2_cache_size);
890 r->refcount_block_cache = qcow2_cache_create(bs, refcount_cache_size);
891 if (r->l2_table_cache == NULL || r->refcount_block_cache == NULL) {
892 error_setg(errp, "Could not allocate metadata caches");
893 ret = -ENOMEM;
894 goto fail;
897 /* New interval for cache cleanup timer */
898 r->cache_clean_interval =
899 qemu_opt_get_number(opts, QCOW2_OPT_CACHE_CLEAN_INTERVAL,
900 s->cache_clean_interval);
901 #ifndef CONFIG_LINUX
902 if (r->cache_clean_interval != 0) {
903 error_setg(errp, QCOW2_OPT_CACHE_CLEAN_INTERVAL
904 " not supported on this host");
905 ret = -EINVAL;
906 goto fail;
908 #endif
909 if (r->cache_clean_interval > UINT_MAX) {
910 error_setg(errp, "Cache clean interval too big");
911 ret = -EINVAL;
912 goto fail;
915 /* lazy-refcounts; flush if going from enabled to disabled */
916 r->use_lazy_refcounts = qemu_opt_get_bool(opts, QCOW2_OPT_LAZY_REFCOUNTS,
917 (s->compatible_features & QCOW2_COMPAT_LAZY_REFCOUNTS));
918 if (r->use_lazy_refcounts && s->qcow_version < 3) {
919 error_setg(errp, "Lazy refcounts require a qcow2 image with at least "
920 "qemu 1.1 compatibility level");
921 ret = -EINVAL;
922 goto fail;
925 if (s->use_lazy_refcounts && !r->use_lazy_refcounts) {
926 ret = qcow2_mark_clean(bs);
927 if (ret < 0) {
928 error_setg_errno(errp, -ret, "Failed to disable lazy refcounts");
929 goto fail;
933 /* Overlap check options */
934 opt_overlap_check = qemu_opt_get(opts, QCOW2_OPT_OVERLAP);
935 opt_overlap_check_template = qemu_opt_get(opts, QCOW2_OPT_OVERLAP_TEMPLATE);
936 if (opt_overlap_check_template && opt_overlap_check &&
937 strcmp(opt_overlap_check_template, opt_overlap_check))
939 error_setg(errp, "Conflicting values for qcow2 options '"
940 QCOW2_OPT_OVERLAP "' ('%s') and '" QCOW2_OPT_OVERLAP_TEMPLATE
941 "' ('%s')", opt_overlap_check, opt_overlap_check_template);
942 ret = -EINVAL;
943 goto fail;
945 if (!opt_overlap_check) {
946 opt_overlap_check = opt_overlap_check_template ?: "cached";
949 if (!strcmp(opt_overlap_check, "none")) {
950 overlap_check_template = 0;
951 } else if (!strcmp(opt_overlap_check, "constant")) {
952 overlap_check_template = QCOW2_OL_CONSTANT;
953 } else if (!strcmp(opt_overlap_check, "cached")) {
954 overlap_check_template = QCOW2_OL_CACHED;
955 } else if (!strcmp(opt_overlap_check, "all")) {
956 overlap_check_template = QCOW2_OL_ALL;
957 } else {
958 error_setg(errp, "Unsupported value '%s' for qcow2 option "
959 "'overlap-check'. Allowed are any of the following: "
960 "none, constant, cached, all", opt_overlap_check);
961 ret = -EINVAL;
962 goto fail;
965 r->overlap_check = 0;
966 for (i = 0; i < QCOW2_OL_MAX_BITNR; i++) {
967 /* overlap-check defines a template bitmask, but every flag may be
968 * overwritten through the associated boolean option */
969 r->overlap_check |=
970 qemu_opt_get_bool(opts, overlap_bool_option_names[i],
971 overlap_check_template & (1 << i)) << i;
974 r->discard_passthrough[QCOW2_DISCARD_NEVER] = false;
975 r->discard_passthrough[QCOW2_DISCARD_ALWAYS] = true;
976 r->discard_passthrough[QCOW2_DISCARD_REQUEST] =
977 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_REQUEST,
978 flags & BDRV_O_UNMAP);
979 r->discard_passthrough[QCOW2_DISCARD_SNAPSHOT] =
980 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_SNAPSHOT, true);
981 r->discard_passthrough[QCOW2_DISCARD_OTHER] =
982 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_OTHER, false);
984 switch (s->crypt_method_header) {
985 case QCOW_CRYPT_NONE:
986 if (encryptfmt) {
987 error_setg(errp, "No encryption in image header, but options "
988 "specified format '%s'", encryptfmt);
989 ret = -EINVAL;
990 goto fail;
992 break;
994 case QCOW_CRYPT_AES:
995 if (encryptfmt && !g_str_equal(encryptfmt, "aes")) {
996 error_setg(errp,
997 "Header reported 'aes' encryption format but "
998 "options specify '%s'", encryptfmt);
999 ret = -EINVAL;
1000 goto fail;
1002 qdict_del(encryptopts, "format");
1003 r->crypto_opts = block_crypto_open_opts_init(
1004 Q_CRYPTO_BLOCK_FORMAT_QCOW, encryptopts, errp);
1005 break;
1007 case QCOW_CRYPT_LUKS:
1008 if (encryptfmt && !g_str_equal(encryptfmt, "luks")) {
1009 error_setg(errp,
1010 "Header reported 'luks' encryption format but "
1011 "options specify '%s'", encryptfmt);
1012 ret = -EINVAL;
1013 goto fail;
1015 qdict_del(encryptopts, "format");
1016 r->crypto_opts = block_crypto_open_opts_init(
1017 Q_CRYPTO_BLOCK_FORMAT_LUKS, encryptopts, errp);
1018 break;
1020 default:
1021 error_setg(errp, "Unsupported encryption method %d",
1022 s->crypt_method_header);
1023 break;
1025 if (s->crypt_method_header != QCOW_CRYPT_NONE && !r->crypto_opts) {
1026 ret = -EINVAL;
1027 goto fail;
1030 ret = 0;
1031 fail:
1032 QDECREF(encryptopts);
1033 qemu_opts_del(opts);
1034 opts = NULL;
1035 return ret;
1038 static void qcow2_update_options_commit(BlockDriverState *bs,
1039 Qcow2ReopenState *r)
1041 BDRVQcow2State *s = bs->opaque;
1042 int i;
1044 if (s->l2_table_cache) {
1045 qcow2_cache_destroy(bs, s->l2_table_cache);
1047 if (s->refcount_block_cache) {
1048 qcow2_cache_destroy(bs, s->refcount_block_cache);
1050 s->l2_table_cache = r->l2_table_cache;
1051 s->refcount_block_cache = r->refcount_block_cache;
1053 s->overlap_check = r->overlap_check;
1054 s->use_lazy_refcounts = r->use_lazy_refcounts;
1056 for (i = 0; i < QCOW2_DISCARD_MAX; i++) {
1057 s->discard_passthrough[i] = r->discard_passthrough[i];
1060 if (s->cache_clean_interval != r->cache_clean_interval) {
1061 cache_clean_timer_del(bs);
1062 s->cache_clean_interval = r->cache_clean_interval;
1063 cache_clean_timer_init(bs, bdrv_get_aio_context(bs));
1066 qapi_free_QCryptoBlockOpenOptions(s->crypto_opts);
1067 s->crypto_opts = r->crypto_opts;
1070 static void qcow2_update_options_abort(BlockDriverState *bs,
1071 Qcow2ReopenState *r)
1073 if (r->l2_table_cache) {
1074 qcow2_cache_destroy(bs, r->l2_table_cache);
1076 if (r->refcount_block_cache) {
1077 qcow2_cache_destroy(bs, r->refcount_block_cache);
1079 qapi_free_QCryptoBlockOpenOptions(r->crypto_opts);
1082 static int qcow2_update_options(BlockDriverState *bs, QDict *options,
1083 int flags, Error **errp)
1085 Qcow2ReopenState r = {};
1086 int ret;
1088 ret = qcow2_update_options_prepare(bs, &r, options, flags, errp);
1089 if (ret >= 0) {
1090 qcow2_update_options_commit(bs, &r);
1091 } else {
1092 qcow2_update_options_abort(bs, &r);
1095 return ret;
1098 static int qcow2_do_open(BlockDriverState *bs, QDict *options, int flags,
1099 Error **errp)
1101 BDRVQcow2State *s = bs->opaque;
1102 unsigned int len, i;
1103 int ret = 0;
1104 QCowHeader header;
1105 Error *local_err = NULL;
1106 uint64_t ext_end;
1107 uint64_t l1_vm_state_index;
1108 bool update_header = false;
1110 ret = bdrv_pread(bs->file, 0, &header, sizeof(header));
1111 if (ret < 0) {
1112 error_setg_errno(errp, -ret, "Could not read qcow2 header");
1113 goto fail;
1115 be32_to_cpus(&header.magic);
1116 be32_to_cpus(&header.version);
1117 be64_to_cpus(&header.backing_file_offset);
1118 be32_to_cpus(&header.backing_file_size);
1119 be64_to_cpus(&header.size);
1120 be32_to_cpus(&header.cluster_bits);
1121 be32_to_cpus(&header.crypt_method);
1122 be64_to_cpus(&header.l1_table_offset);
1123 be32_to_cpus(&header.l1_size);
1124 be64_to_cpus(&header.refcount_table_offset);
1125 be32_to_cpus(&header.refcount_table_clusters);
1126 be64_to_cpus(&header.snapshots_offset);
1127 be32_to_cpus(&header.nb_snapshots);
1129 if (header.magic != QCOW_MAGIC) {
1130 error_setg(errp, "Image is not in qcow2 format");
1131 ret = -EINVAL;
1132 goto fail;
1134 if (header.version < 2 || header.version > 3) {
1135 error_setg(errp, "Unsupported qcow2 version %" PRIu32, header.version);
1136 ret = -ENOTSUP;
1137 goto fail;
1140 s->qcow_version = header.version;
1142 /* Initialise cluster size */
1143 if (header.cluster_bits < MIN_CLUSTER_BITS ||
1144 header.cluster_bits > MAX_CLUSTER_BITS) {
1145 error_setg(errp, "Unsupported cluster size: 2^%" PRIu32,
1146 header.cluster_bits);
1147 ret = -EINVAL;
1148 goto fail;
1151 s->cluster_bits = header.cluster_bits;
1152 s->cluster_size = 1 << s->cluster_bits;
1153 s->cluster_sectors = 1 << (s->cluster_bits - BDRV_SECTOR_BITS);
1155 /* Initialise version 3 header fields */
1156 if (header.version == 2) {
1157 header.incompatible_features = 0;
1158 header.compatible_features = 0;
1159 header.autoclear_features = 0;
1160 header.refcount_order = 4;
1161 header.header_length = 72;
1162 } else {
1163 be64_to_cpus(&header.incompatible_features);
1164 be64_to_cpus(&header.compatible_features);
1165 be64_to_cpus(&header.autoclear_features);
1166 be32_to_cpus(&header.refcount_order);
1167 be32_to_cpus(&header.header_length);
1169 if (header.header_length < 104) {
1170 error_setg(errp, "qcow2 header too short");
1171 ret = -EINVAL;
1172 goto fail;
1176 if (header.header_length > s->cluster_size) {
1177 error_setg(errp, "qcow2 header exceeds cluster size");
1178 ret = -EINVAL;
1179 goto fail;
1182 if (header.header_length > sizeof(header)) {
1183 s->unknown_header_fields_size = header.header_length - sizeof(header);
1184 s->unknown_header_fields = g_malloc(s->unknown_header_fields_size);
1185 ret = bdrv_pread(bs->file, sizeof(header), s->unknown_header_fields,
1186 s->unknown_header_fields_size);
1187 if (ret < 0) {
1188 error_setg_errno(errp, -ret, "Could not read unknown qcow2 header "
1189 "fields");
1190 goto fail;
1194 if (header.backing_file_offset > s->cluster_size) {
1195 error_setg(errp, "Invalid backing file offset");
1196 ret = -EINVAL;
1197 goto fail;
1200 if (header.backing_file_offset) {
1201 ext_end = header.backing_file_offset;
1202 } else {
1203 ext_end = 1 << header.cluster_bits;
1206 /* Handle feature bits */
1207 s->incompatible_features = header.incompatible_features;
1208 s->compatible_features = header.compatible_features;
1209 s->autoclear_features = header.autoclear_features;
1211 if (s->incompatible_features & ~QCOW2_INCOMPAT_MASK) {
1212 void *feature_table = NULL;
1213 qcow2_read_extensions(bs, header.header_length, ext_end,
1214 &feature_table, flags, NULL, NULL);
1215 report_unsupported_feature(errp, feature_table,
1216 s->incompatible_features &
1217 ~QCOW2_INCOMPAT_MASK);
1218 ret = -ENOTSUP;
1219 g_free(feature_table);
1220 goto fail;
1223 if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
1224 /* Corrupt images may not be written to unless they are being repaired
1226 if ((flags & BDRV_O_RDWR) && !(flags & BDRV_O_CHECK)) {
1227 error_setg(errp, "qcow2: Image is corrupt; cannot be opened "
1228 "read/write");
1229 ret = -EACCES;
1230 goto fail;
1234 /* Check support for various header values */
1235 if (header.refcount_order > 6) {
1236 error_setg(errp, "Reference count entry width too large; may not "
1237 "exceed 64 bits");
1238 ret = -EINVAL;
1239 goto fail;
1241 s->refcount_order = header.refcount_order;
1242 s->refcount_bits = 1 << s->refcount_order;
1243 s->refcount_max = UINT64_C(1) << (s->refcount_bits - 1);
1244 s->refcount_max += s->refcount_max - 1;
1246 s->crypt_method_header = header.crypt_method;
1247 if (s->crypt_method_header) {
1248 if (bdrv_uses_whitelist() &&
1249 s->crypt_method_header == QCOW_CRYPT_AES) {
1250 error_setg(errp,
1251 "Use of AES-CBC encrypted qcow2 images is no longer "
1252 "supported in system emulators");
1253 error_append_hint(errp,
1254 "You can use 'qemu-img convert' to convert your "
1255 "image to an alternative supported format, such "
1256 "as unencrypted qcow2, or raw with the LUKS "
1257 "format instead.\n");
1258 ret = -ENOSYS;
1259 goto fail;
1262 if (s->crypt_method_header == QCOW_CRYPT_AES) {
1263 s->crypt_physical_offset = false;
1264 } else {
1265 /* Assuming LUKS and any future crypt methods we
1266 * add will all use physical offsets, due to the
1267 * fact that the alternative is insecure... */
1268 s->crypt_physical_offset = true;
1271 bs->encrypted = true;
1274 s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */
1275 s->l2_size = 1 << s->l2_bits;
1276 /* 2^(s->refcount_order - 3) is the refcount width in bytes */
1277 s->refcount_block_bits = s->cluster_bits - (s->refcount_order - 3);
1278 s->refcount_block_size = 1 << s->refcount_block_bits;
1279 bs->total_sectors = header.size / 512;
1280 s->csize_shift = (62 - (s->cluster_bits - 8));
1281 s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;
1282 s->cluster_offset_mask = (1LL << s->csize_shift) - 1;
1284 s->refcount_table_offset = header.refcount_table_offset;
1285 s->refcount_table_size =
1286 header.refcount_table_clusters << (s->cluster_bits - 3);
1288 if (header.refcount_table_clusters > qcow2_max_refcount_clusters(s)) {
1289 error_setg(errp, "Reference count table too large");
1290 ret = -EINVAL;
1291 goto fail;
1294 if (header.refcount_table_clusters == 0 && !(flags & BDRV_O_CHECK)) {
1295 error_setg(errp, "Image does not contain a reference count table");
1296 ret = -EINVAL;
1297 goto fail;
1300 ret = validate_table_offset(bs, s->refcount_table_offset,
1301 s->refcount_table_size, sizeof(uint64_t));
1302 if (ret < 0) {
1303 error_setg(errp, "Invalid reference count table offset");
1304 goto fail;
1307 /* Snapshot table offset/length */
1308 if (header.nb_snapshots > QCOW_MAX_SNAPSHOTS) {
1309 error_setg(errp, "Too many snapshots");
1310 ret = -EINVAL;
1311 goto fail;
1314 ret = validate_table_offset(bs, header.snapshots_offset,
1315 header.nb_snapshots,
1316 sizeof(QCowSnapshotHeader));
1317 if (ret < 0) {
1318 error_setg(errp, "Invalid snapshot table offset");
1319 goto fail;
1322 /* read the level 1 table */
1323 if (header.l1_size > QCOW_MAX_L1_SIZE / sizeof(uint64_t)) {
1324 error_setg(errp, "Active L1 table too large");
1325 ret = -EFBIG;
1326 goto fail;
1328 s->l1_size = header.l1_size;
1330 l1_vm_state_index = size_to_l1(s, header.size);
1331 if (l1_vm_state_index > INT_MAX) {
1332 error_setg(errp, "Image is too big");
1333 ret = -EFBIG;
1334 goto fail;
1336 s->l1_vm_state_index = l1_vm_state_index;
1338 /* the L1 table must contain at least enough entries to put
1339 header.size bytes */
1340 if (s->l1_size < s->l1_vm_state_index) {
1341 error_setg(errp, "L1 table is too small");
1342 ret = -EINVAL;
1343 goto fail;
1346 ret = validate_table_offset(bs, header.l1_table_offset,
1347 header.l1_size, sizeof(uint64_t));
1348 if (ret < 0) {
1349 error_setg(errp, "Invalid L1 table offset");
1350 goto fail;
1352 s->l1_table_offset = header.l1_table_offset;
1355 if (s->l1_size > 0) {
1356 s->l1_table = qemu_try_blockalign(bs->file->bs,
1357 align_offset(s->l1_size * sizeof(uint64_t), 512));
1358 if (s->l1_table == NULL) {
1359 error_setg(errp, "Could not allocate L1 table");
1360 ret = -ENOMEM;
1361 goto fail;
1363 ret = bdrv_pread(bs->file, s->l1_table_offset, s->l1_table,
1364 s->l1_size * sizeof(uint64_t));
1365 if (ret < 0) {
1366 error_setg_errno(errp, -ret, "Could not read L1 table");
1367 goto fail;
1369 for(i = 0;i < s->l1_size; i++) {
1370 be64_to_cpus(&s->l1_table[i]);
1374 /* Parse driver-specific options */
1375 ret = qcow2_update_options(bs, options, flags, errp);
1376 if (ret < 0) {
1377 goto fail;
1380 s->cluster_cache_offset = -1;
1381 s->flags = flags;
1383 ret = qcow2_refcount_init(bs);
1384 if (ret != 0) {
1385 error_setg_errno(errp, -ret, "Could not initialize refcount handling");
1386 goto fail;
1389 QLIST_INIT(&s->cluster_allocs);
1390 QTAILQ_INIT(&s->discards);
1392 /* read qcow2 extensions */
1393 if (qcow2_read_extensions(bs, header.header_length, ext_end, NULL,
1394 flags, &update_header, &local_err)) {
1395 error_propagate(errp, local_err);
1396 ret = -EINVAL;
1397 goto fail;
1400 /* qcow2_read_extension may have set up the crypto context
1401 * if the crypt method needs a header region, some methods
1402 * don't need header extensions, so must check here
1404 if (s->crypt_method_header && !s->crypto) {
1405 if (s->crypt_method_header == QCOW_CRYPT_AES) {
1406 unsigned int cflags = 0;
1407 if (flags & BDRV_O_NO_IO) {
1408 cflags |= QCRYPTO_BLOCK_OPEN_NO_IO;
1410 s->crypto = qcrypto_block_open(s->crypto_opts, "encrypt.",
1411 NULL, NULL, cflags, errp);
1412 if (!s->crypto) {
1413 ret = -EINVAL;
1414 goto fail;
1416 } else if (!(flags & BDRV_O_NO_IO)) {
1417 error_setg(errp, "Missing CRYPTO header for crypt method %d",
1418 s->crypt_method_header);
1419 ret = -EINVAL;
1420 goto fail;
1424 /* read the backing file name */
1425 if (header.backing_file_offset != 0) {
1426 len = header.backing_file_size;
1427 if (len > MIN(1023, s->cluster_size - header.backing_file_offset) ||
1428 len >= sizeof(bs->backing_file)) {
1429 error_setg(errp, "Backing file name too long");
1430 ret = -EINVAL;
1431 goto fail;
1433 ret = bdrv_pread(bs->file, header.backing_file_offset,
1434 bs->backing_file, len);
1435 if (ret < 0) {
1436 error_setg_errno(errp, -ret, "Could not read backing file name");
1437 goto fail;
1439 bs->backing_file[len] = '\0';
1440 s->image_backing_file = g_strdup(bs->backing_file);
1443 /* Internal snapshots */
1444 s->snapshots_offset = header.snapshots_offset;
1445 s->nb_snapshots = header.nb_snapshots;
1447 ret = qcow2_read_snapshots(bs);
1448 if (ret < 0) {
1449 error_setg_errno(errp, -ret, "Could not read snapshots");
1450 goto fail;
1453 /* Clear unknown autoclear feature bits */
1454 update_header |= s->autoclear_features & ~QCOW2_AUTOCLEAR_MASK;
1455 update_header =
1456 update_header && !bs->read_only && !(flags & BDRV_O_INACTIVE);
1457 if (update_header) {
1458 s->autoclear_features &= QCOW2_AUTOCLEAR_MASK;
1461 if (qcow2_load_autoloading_dirty_bitmaps(bs, &local_err)) {
1462 update_header = false;
1464 if (local_err != NULL) {
1465 error_propagate(errp, local_err);
1466 ret = -EINVAL;
1467 goto fail;
1470 if (update_header) {
1471 ret = qcow2_update_header(bs);
1472 if (ret < 0) {
1473 error_setg_errno(errp, -ret, "Could not update qcow2 header");
1474 goto fail;
1478 /* Initialise locks */
1479 qemu_co_mutex_init(&s->lock);
1480 bs->supported_zero_flags = BDRV_REQ_MAY_UNMAP;
1482 /* Repair image if dirty */
1483 if (!(flags & (BDRV_O_CHECK | BDRV_O_INACTIVE)) && !bs->read_only &&
1484 (s->incompatible_features & QCOW2_INCOMPAT_DIRTY)) {
1485 BdrvCheckResult result = {0};
1487 ret = qcow2_check(bs, &result, BDRV_FIX_ERRORS | BDRV_FIX_LEAKS);
1488 if (ret < 0 || result.check_errors) {
1489 if (ret >= 0) {
1490 ret = -EIO;
1492 error_setg_errno(errp, -ret, "Could not repair dirty image");
1493 goto fail;
1497 #ifdef DEBUG_ALLOC
1499 BdrvCheckResult result = {0};
1500 qcow2_check_refcounts(bs, &result, 0);
1502 #endif
1503 return ret;
1505 fail:
1506 g_free(s->unknown_header_fields);
1507 cleanup_unknown_header_ext(bs);
1508 qcow2_free_snapshots(bs);
1509 qcow2_refcount_close(bs);
1510 qemu_vfree(s->l1_table);
1511 /* else pre-write overlap checks in cache_destroy may crash */
1512 s->l1_table = NULL;
1513 cache_clean_timer_del(bs);
1514 if (s->l2_table_cache) {
1515 qcow2_cache_destroy(bs, s->l2_table_cache);
1517 if (s->refcount_block_cache) {
1518 qcow2_cache_destroy(bs, s->refcount_block_cache);
1520 qcrypto_block_free(s->crypto);
1521 qapi_free_QCryptoBlockOpenOptions(s->crypto_opts);
1522 return ret;
1525 static int qcow2_open(BlockDriverState *bs, QDict *options, int flags,
1526 Error **errp)
1528 bs->file = bdrv_open_child(NULL, options, "file", bs, &child_file,
1529 false, errp);
1530 if (!bs->file) {
1531 return -EINVAL;
1534 return qcow2_do_open(bs, options, flags, errp);
1537 static void qcow2_refresh_limits(BlockDriverState *bs, Error **errp)
1539 BDRVQcow2State *s = bs->opaque;
1541 if (bs->encrypted) {
1542 /* Encryption works on a sector granularity */
1543 bs->bl.request_alignment = BDRV_SECTOR_SIZE;
1545 bs->bl.pwrite_zeroes_alignment = s->cluster_size;
1546 bs->bl.pdiscard_alignment = s->cluster_size;
1549 static int qcow2_reopen_prepare(BDRVReopenState *state,
1550 BlockReopenQueue *queue, Error **errp)
1552 Qcow2ReopenState *r;
1553 int ret;
1555 r = g_new0(Qcow2ReopenState, 1);
1556 state->opaque = r;
1558 ret = qcow2_update_options_prepare(state->bs, r, state->options,
1559 state->flags, errp);
1560 if (ret < 0) {
1561 goto fail;
1564 /* We need to write out any unwritten data if we reopen read-only. */
1565 if ((state->flags & BDRV_O_RDWR) == 0) {
1566 ret = qcow2_reopen_bitmaps_ro(state->bs, errp);
1567 if (ret < 0) {
1568 goto fail;
1571 ret = bdrv_flush(state->bs);
1572 if (ret < 0) {
1573 goto fail;
1576 ret = qcow2_mark_clean(state->bs);
1577 if (ret < 0) {
1578 goto fail;
1582 return 0;
1584 fail:
1585 qcow2_update_options_abort(state->bs, r);
1586 g_free(r);
1587 return ret;
1590 static void qcow2_reopen_commit(BDRVReopenState *state)
1592 qcow2_update_options_commit(state->bs, state->opaque);
1593 g_free(state->opaque);
1596 static void qcow2_reopen_abort(BDRVReopenState *state)
1598 qcow2_update_options_abort(state->bs, state->opaque);
1599 g_free(state->opaque);
1602 static void qcow2_join_options(QDict *options, QDict *old_options)
1604 bool has_new_overlap_template =
1605 qdict_haskey(options, QCOW2_OPT_OVERLAP) ||
1606 qdict_haskey(options, QCOW2_OPT_OVERLAP_TEMPLATE);
1607 bool has_new_total_cache_size =
1608 qdict_haskey(options, QCOW2_OPT_CACHE_SIZE);
1609 bool has_all_cache_options;
1611 /* New overlap template overrides all old overlap options */
1612 if (has_new_overlap_template) {
1613 qdict_del(old_options, QCOW2_OPT_OVERLAP);
1614 qdict_del(old_options, QCOW2_OPT_OVERLAP_TEMPLATE);
1615 qdict_del(old_options, QCOW2_OPT_OVERLAP_MAIN_HEADER);
1616 qdict_del(old_options, QCOW2_OPT_OVERLAP_ACTIVE_L1);
1617 qdict_del(old_options, QCOW2_OPT_OVERLAP_ACTIVE_L2);
1618 qdict_del(old_options, QCOW2_OPT_OVERLAP_REFCOUNT_TABLE);
1619 qdict_del(old_options, QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK);
1620 qdict_del(old_options, QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE);
1621 qdict_del(old_options, QCOW2_OPT_OVERLAP_INACTIVE_L1);
1622 qdict_del(old_options, QCOW2_OPT_OVERLAP_INACTIVE_L2);
1625 /* New total cache size overrides all old options */
1626 if (qdict_haskey(options, QCOW2_OPT_CACHE_SIZE)) {
1627 qdict_del(old_options, QCOW2_OPT_L2_CACHE_SIZE);
1628 qdict_del(old_options, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
1631 qdict_join(options, old_options, false);
1634 * If after merging all cache size options are set, an old total size is
1635 * overwritten. Do keep all options, however, if all three are new. The
1636 * resulting error message is what we want to happen.
1638 has_all_cache_options =
1639 qdict_haskey(options, QCOW2_OPT_CACHE_SIZE) ||
1640 qdict_haskey(options, QCOW2_OPT_L2_CACHE_SIZE) ||
1641 qdict_haskey(options, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
1643 if (has_all_cache_options && !has_new_total_cache_size) {
1644 qdict_del(options, QCOW2_OPT_CACHE_SIZE);
1648 static int64_t coroutine_fn qcow2_co_get_block_status(BlockDriverState *bs,
1649 int64_t sector_num, int nb_sectors, int *pnum, BlockDriverState **file)
1651 BDRVQcow2State *s = bs->opaque;
1652 uint64_t cluster_offset;
1653 int index_in_cluster, ret;
1654 unsigned int bytes;
1655 int64_t status = 0;
1657 bytes = MIN(INT_MAX, nb_sectors * BDRV_SECTOR_SIZE);
1658 qemu_co_mutex_lock(&s->lock);
1659 ret = qcow2_get_cluster_offset(bs, sector_num << BDRV_SECTOR_BITS, &bytes,
1660 &cluster_offset);
1661 qemu_co_mutex_unlock(&s->lock);
1662 if (ret < 0) {
1663 return ret;
1666 *pnum = bytes >> BDRV_SECTOR_BITS;
1668 if (cluster_offset != 0 && ret != QCOW2_CLUSTER_COMPRESSED &&
1669 !s->crypto) {
1670 index_in_cluster = sector_num & (s->cluster_sectors - 1);
1671 cluster_offset |= (index_in_cluster << BDRV_SECTOR_BITS);
1672 *file = bs->file->bs;
1673 status |= BDRV_BLOCK_OFFSET_VALID | cluster_offset;
1675 if (ret == QCOW2_CLUSTER_ZERO_PLAIN || ret == QCOW2_CLUSTER_ZERO_ALLOC) {
1676 status |= BDRV_BLOCK_ZERO;
1677 } else if (ret != QCOW2_CLUSTER_UNALLOCATED) {
1678 status |= BDRV_BLOCK_DATA;
1680 return status;
1683 static coroutine_fn int qcow2_co_preadv(BlockDriverState *bs, uint64_t offset,
1684 uint64_t bytes, QEMUIOVector *qiov,
1685 int flags)
1687 BDRVQcow2State *s = bs->opaque;
1688 int offset_in_cluster;
1689 int ret;
1690 unsigned int cur_bytes; /* number of bytes in current iteration */
1691 uint64_t cluster_offset = 0;
1692 uint64_t bytes_done = 0;
1693 QEMUIOVector hd_qiov;
1694 uint8_t *cluster_data = NULL;
1696 qemu_iovec_init(&hd_qiov, qiov->niov);
1698 qemu_co_mutex_lock(&s->lock);
1700 while (bytes != 0) {
1702 /* prepare next request */
1703 cur_bytes = MIN(bytes, INT_MAX);
1704 if (s->crypto) {
1705 cur_bytes = MIN(cur_bytes,
1706 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
1709 ret = qcow2_get_cluster_offset(bs, offset, &cur_bytes, &cluster_offset);
1710 if (ret < 0) {
1711 goto fail;
1714 offset_in_cluster = offset_into_cluster(s, offset);
1716 qemu_iovec_reset(&hd_qiov);
1717 qemu_iovec_concat(&hd_qiov, qiov, bytes_done, cur_bytes);
1719 switch (ret) {
1720 case QCOW2_CLUSTER_UNALLOCATED:
1722 if (bs->backing) {
1723 BLKDBG_EVENT(bs->file, BLKDBG_READ_BACKING_AIO);
1724 qemu_co_mutex_unlock(&s->lock);
1725 ret = bdrv_co_preadv(bs->backing, offset, cur_bytes,
1726 &hd_qiov, 0);
1727 qemu_co_mutex_lock(&s->lock);
1728 if (ret < 0) {
1729 goto fail;
1731 } else {
1732 /* Note: in this case, no need to wait */
1733 qemu_iovec_memset(&hd_qiov, 0, 0, cur_bytes);
1735 break;
1737 case QCOW2_CLUSTER_ZERO_PLAIN:
1738 case QCOW2_CLUSTER_ZERO_ALLOC:
1739 qemu_iovec_memset(&hd_qiov, 0, 0, cur_bytes);
1740 break;
1742 case QCOW2_CLUSTER_COMPRESSED:
1743 /* add AIO support for compressed blocks ? */
1744 ret = qcow2_decompress_cluster(bs, cluster_offset);
1745 if (ret < 0) {
1746 goto fail;
1749 qemu_iovec_from_buf(&hd_qiov, 0,
1750 s->cluster_cache + offset_in_cluster,
1751 cur_bytes);
1752 break;
1754 case QCOW2_CLUSTER_NORMAL:
1755 if ((cluster_offset & 511) != 0) {
1756 ret = -EIO;
1757 goto fail;
1760 if (bs->encrypted) {
1761 assert(s->crypto);
1764 * For encrypted images, read everything into a temporary
1765 * contiguous buffer on which the AES functions can work.
1767 if (!cluster_data) {
1768 cluster_data =
1769 qemu_try_blockalign(bs->file->bs,
1770 QCOW_MAX_CRYPT_CLUSTERS
1771 * s->cluster_size);
1772 if (cluster_data == NULL) {
1773 ret = -ENOMEM;
1774 goto fail;
1778 assert(cur_bytes <= QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
1779 qemu_iovec_reset(&hd_qiov);
1780 qemu_iovec_add(&hd_qiov, cluster_data, cur_bytes);
1783 BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);
1784 qemu_co_mutex_unlock(&s->lock);
1785 ret = bdrv_co_preadv(bs->file,
1786 cluster_offset + offset_in_cluster,
1787 cur_bytes, &hd_qiov, 0);
1788 qemu_co_mutex_lock(&s->lock);
1789 if (ret < 0) {
1790 goto fail;
1792 if (bs->encrypted) {
1793 assert(s->crypto);
1794 assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);
1795 assert((cur_bytes & (BDRV_SECTOR_SIZE - 1)) == 0);
1796 if (qcrypto_block_decrypt(s->crypto,
1797 (s->crypt_physical_offset ?
1798 cluster_offset + offset_in_cluster :
1799 offset),
1800 cluster_data,
1801 cur_bytes,
1802 NULL) < 0) {
1803 ret = -EIO;
1804 goto fail;
1806 qemu_iovec_from_buf(qiov, bytes_done, cluster_data, cur_bytes);
1808 break;
1810 default:
1811 g_assert_not_reached();
1812 ret = -EIO;
1813 goto fail;
1816 bytes -= cur_bytes;
1817 offset += cur_bytes;
1818 bytes_done += cur_bytes;
1820 ret = 0;
1822 fail:
1823 qemu_co_mutex_unlock(&s->lock);
1825 qemu_iovec_destroy(&hd_qiov);
1826 qemu_vfree(cluster_data);
1828 return ret;
1831 /* Check if it's possible to merge a write request with the writing of
1832 * the data from the COW regions */
1833 static bool merge_cow(uint64_t offset, unsigned bytes,
1834 QEMUIOVector *hd_qiov, QCowL2Meta *l2meta)
1836 QCowL2Meta *m;
1838 for (m = l2meta; m != NULL; m = m->next) {
1839 /* If both COW regions are empty then there's nothing to merge */
1840 if (m->cow_start.nb_bytes == 0 && m->cow_end.nb_bytes == 0) {
1841 continue;
1844 /* The data (middle) region must be immediately after the
1845 * start region */
1846 if (l2meta_cow_start(m) + m->cow_start.nb_bytes != offset) {
1847 continue;
1850 /* The end region must be immediately after the data (middle)
1851 * region */
1852 if (m->offset + m->cow_end.offset != offset + bytes) {
1853 continue;
1856 /* Make sure that adding both COW regions to the QEMUIOVector
1857 * does not exceed IOV_MAX */
1858 if (hd_qiov->niov > IOV_MAX - 2) {
1859 continue;
1862 m->data_qiov = hd_qiov;
1863 return true;
1866 return false;
1869 static coroutine_fn int qcow2_co_pwritev(BlockDriverState *bs, uint64_t offset,
1870 uint64_t bytes, QEMUIOVector *qiov,
1871 int flags)
1873 BDRVQcow2State *s = bs->opaque;
1874 int offset_in_cluster;
1875 int ret;
1876 unsigned int cur_bytes; /* number of sectors in current iteration */
1877 uint64_t cluster_offset;
1878 QEMUIOVector hd_qiov;
1879 uint64_t bytes_done = 0;
1880 uint8_t *cluster_data = NULL;
1881 QCowL2Meta *l2meta = NULL;
1883 trace_qcow2_writev_start_req(qemu_coroutine_self(), offset, bytes);
1885 qemu_iovec_init(&hd_qiov, qiov->niov);
1887 s->cluster_cache_offset = -1; /* disable compressed cache */
1889 qemu_co_mutex_lock(&s->lock);
1891 while (bytes != 0) {
1893 l2meta = NULL;
1895 trace_qcow2_writev_start_part(qemu_coroutine_self());
1896 offset_in_cluster = offset_into_cluster(s, offset);
1897 cur_bytes = MIN(bytes, INT_MAX);
1898 if (bs->encrypted) {
1899 cur_bytes = MIN(cur_bytes,
1900 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size
1901 - offset_in_cluster);
1904 ret = qcow2_alloc_cluster_offset(bs, offset, &cur_bytes,
1905 &cluster_offset, &l2meta);
1906 if (ret < 0) {
1907 goto fail;
1910 assert((cluster_offset & 511) == 0);
1912 qemu_iovec_reset(&hd_qiov);
1913 qemu_iovec_concat(&hd_qiov, qiov, bytes_done, cur_bytes);
1915 if (bs->encrypted) {
1916 assert(s->crypto);
1917 if (!cluster_data) {
1918 cluster_data = qemu_try_blockalign(bs->file->bs,
1919 QCOW_MAX_CRYPT_CLUSTERS
1920 * s->cluster_size);
1921 if (cluster_data == NULL) {
1922 ret = -ENOMEM;
1923 goto fail;
1927 assert(hd_qiov.size <=
1928 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
1929 qemu_iovec_to_buf(&hd_qiov, 0, cluster_data, hd_qiov.size);
1931 if (qcrypto_block_encrypt(s->crypto,
1932 (s->crypt_physical_offset ?
1933 cluster_offset + offset_in_cluster :
1934 offset),
1935 cluster_data,
1936 cur_bytes, NULL) < 0) {
1937 ret = -EIO;
1938 goto fail;
1941 qemu_iovec_reset(&hd_qiov);
1942 qemu_iovec_add(&hd_qiov, cluster_data, cur_bytes);
1945 ret = qcow2_pre_write_overlap_check(bs, 0,
1946 cluster_offset + offset_in_cluster, cur_bytes);
1947 if (ret < 0) {
1948 goto fail;
1951 /* If we need to do COW, check if it's possible to merge the
1952 * writing of the guest data together with that of the COW regions.
1953 * If it's not possible (or not necessary) then write the
1954 * guest data now. */
1955 if (!merge_cow(offset, cur_bytes, &hd_qiov, l2meta)) {
1956 qemu_co_mutex_unlock(&s->lock);
1957 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO);
1958 trace_qcow2_writev_data(qemu_coroutine_self(),
1959 cluster_offset + offset_in_cluster);
1960 ret = bdrv_co_pwritev(bs->file,
1961 cluster_offset + offset_in_cluster,
1962 cur_bytes, &hd_qiov, 0);
1963 qemu_co_mutex_lock(&s->lock);
1964 if (ret < 0) {
1965 goto fail;
1969 while (l2meta != NULL) {
1970 QCowL2Meta *next;
1972 ret = qcow2_alloc_cluster_link_l2(bs, l2meta);
1973 if (ret < 0) {
1974 goto fail;
1977 /* Take the request off the list of running requests */
1978 if (l2meta->nb_clusters != 0) {
1979 QLIST_REMOVE(l2meta, next_in_flight);
1982 qemu_co_queue_restart_all(&l2meta->dependent_requests);
1984 next = l2meta->next;
1985 g_free(l2meta);
1986 l2meta = next;
1989 bytes -= cur_bytes;
1990 offset += cur_bytes;
1991 bytes_done += cur_bytes;
1992 trace_qcow2_writev_done_part(qemu_coroutine_self(), cur_bytes);
1994 ret = 0;
1996 fail:
1997 while (l2meta != NULL) {
1998 QCowL2Meta *next;
2000 if (l2meta->nb_clusters != 0) {
2001 QLIST_REMOVE(l2meta, next_in_flight);
2003 qemu_co_queue_restart_all(&l2meta->dependent_requests);
2005 next = l2meta->next;
2006 g_free(l2meta);
2007 l2meta = next;
2010 qemu_co_mutex_unlock(&s->lock);
2012 qemu_iovec_destroy(&hd_qiov);
2013 qemu_vfree(cluster_data);
2014 trace_qcow2_writev_done_req(qemu_coroutine_self(), ret);
2016 return ret;
2019 static int qcow2_inactivate(BlockDriverState *bs)
2021 BDRVQcow2State *s = bs->opaque;
2022 int ret, result = 0;
2023 Error *local_err = NULL;
2025 qcow2_store_persistent_dirty_bitmaps(bs, &local_err);
2026 if (local_err != NULL) {
2027 result = -EINVAL;
2028 error_report_err(local_err);
2029 error_report("Persistent bitmaps are lost for node '%s'",
2030 bdrv_get_device_or_node_name(bs));
2033 ret = qcow2_cache_flush(bs, s->l2_table_cache);
2034 if (ret) {
2035 result = ret;
2036 error_report("Failed to flush the L2 table cache: %s",
2037 strerror(-ret));
2040 ret = qcow2_cache_flush(bs, s->refcount_block_cache);
2041 if (ret) {
2042 result = ret;
2043 error_report("Failed to flush the refcount block cache: %s",
2044 strerror(-ret));
2047 if (result == 0) {
2048 qcow2_mark_clean(bs);
2051 return result;
2054 static void qcow2_close(BlockDriverState *bs)
2056 BDRVQcow2State *s = bs->opaque;
2057 qemu_vfree(s->l1_table);
2058 /* else pre-write overlap checks in cache_destroy may crash */
2059 s->l1_table = NULL;
2061 if (!(s->flags & BDRV_O_INACTIVE)) {
2062 qcow2_inactivate(bs);
2065 cache_clean_timer_del(bs);
2066 qcow2_cache_destroy(bs, s->l2_table_cache);
2067 qcow2_cache_destroy(bs, s->refcount_block_cache);
2069 qcrypto_block_free(s->crypto);
2070 s->crypto = NULL;
2072 g_free(s->unknown_header_fields);
2073 cleanup_unknown_header_ext(bs);
2075 g_free(s->image_backing_file);
2076 g_free(s->image_backing_format);
2078 g_free(s->cluster_cache);
2079 qemu_vfree(s->cluster_data);
2080 qcow2_refcount_close(bs);
2081 qcow2_free_snapshots(bs);
2084 static void qcow2_invalidate_cache(BlockDriverState *bs, Error **errp)
2086 BDRVQcow2State *s = bs->opaque;
2087 int flags = s->flags;
2088 QCryptoBlock *crypto = NULL;
2089 QDict *options;
2090 Error *local_err = NULL;
2091 int ret;
2094 * Backing files are read-only which makes all of their metadata immutable,
2095 * that means we don't have to worry about reopening them here.
2098 crypto = s->crypto;
2099 s->crypto = NULL;
2101 qcow2_close(bs);
2103 memset(s, 0, sizeof(BDRVQcow2State));
2104 options = qdict_clone_shallow(bs->options);
2106 flags &= ~BDRV_O_INACTIVE;
2107 ret = qcow2_do_open(bs, options, flags, &local_err);
2108 QDECREF(options);
2109 if (local_err) {
2110 error_propagate(errp, local_err);
2111 error_prepend(errp, "Could not reopen qcow2 layer: ");
2112 bs->drv = NULL;
2113 return;
2114 } else if (ret < 0) {
2115 error_setg_errno(errp, -ret, "Could not reopen qcow2 layer");
2116 bs->drv = NULL;
2117 return;
2120 s->crypto = crypto;
2123 static size_t header_ext_add(char *buf, uint32_t magic, const void *s,
2124 size_t len, size_t buflen)
2126 QCowExtension *ext_backing_fmt = (QCowExtension*) buf;
2127 size_t ext_len = sizeof(QCowExtension) + ((len + 7) & ~7);
2129 if (buflen < ext_len) {
2130 return -ENOSPC;
2133 *ext_backing_fmt = (QCowExtension) {
2134 .magic = cpu_to_be32(magic),
2135 .len = cpu_to_be32(len),
2138 if (len) {
2139 memcpy(buf + sizeof(QCowExtension), s, len);
2142 return ext_len;
2146 * Updates the qcow2 header, including the variable length parts of it, i.e.
2147 * the backing file name and all extensions. qcow2 was not designed to allow
2148 * such changes, so if we run out of space (we can only use the first cluster)
2149 * this function may fail.
2151 * Returns 0 on success, -errno in error cases.
2153 int qcow2_update_header(BlockDriverState *bs)
2155 BDRVQcow2State *s = bs->opaque;
2156 QCowHeader *header;
2157 char *buf;
2158 size_t buflen = s->cluster_size;
2159 int ret;
2160 uint64_t total_size;
2161 uint32_t refcount_table_clusters;
2162 size_t header_length;
2163 Qcow2UnknownHeaderExtension *uext;
2165 buf = qemu_blockalign(bs, buflen);
2167 /* Header structure */
2168 header = (QCowHeader*) buf;
2170 if (buflen < sizeof(*header)) {
2171 ret = -ENOSPC;
2172 goto fail;
2175 header_length = sizeof(*header) + s->unknown_header_fields_size;
2176 total_size = bs->total_sectors * BDRV_SECTOR_SIZE;
2177 refcount_table_clusters = s->refcount_table_size >> (s->cluster_bits - 3);
2179 *header = (QCowHeader) {
2180 /* Version 2 fields */
2181 .magic = cpu_to_be32(QCOW_MAGIC),
2182 .version = cpu_to_be32(s->qcow_version),
2183 .backing_file_offset = 0,
2184 .backing_file_size = 0,
2185 .cluster_bits = cpu_to_be32(s->cluster_bits),
2186 .size = cpu_to_be64(total_size),
2187 .crypt_method = cpu_to_be32(s->crypt_method_header),
2188 .l1_size = cpu_to_be32(s->l1_size),
2189 .l1_table_offset = cpu_to_be64(s->l1_table_offset),
2190 .refcount_table_offset = cpu_to_be64(s->refcount_table_offset),
2191 .refcount_table_clusters = cpu_to_be32(refcount_table_clusters),
2192 .nb_snapshots = cpu_to_be32(s->nb_snapshots),
2193 .snapshots_offset = cpu_to_be64(s->snapshots_offset),
2195 /* Version 3 fields */
2196 .incompatible_features = cpu_to_be64(s->incompatible_features),
2197 .compatible_features = cpu_to_be64(s->compatible_features),
2198 .autoclear_features = cpu_to_be64(s->autoclear_features),
2199 .refcount_order = cpu_to_be32(s->refcount_order),
2200 .header_length = cpu_to_be32(header_length),
2203 /* For older versions, write a shorter header */
2204 switch (s->qcow_version) {
2205 case 2:
2206 ret = offsetof(QCowHeader, incompatible_features);
2207 break;
2208 case 3:
2209 ret = sizeof(*header);
2210 break;
2211 default:
2212 ret = -EINVAL;
2213 goto fail;
2216 buf += ret;
2217 buflen -= ret;
2218 memset(buf, 0, buflen);
2220 /* Preserve any unknown field in the header */
2221 if (s->unknown_header_fields_size) {
2222 if (buflen < s->unknown_header_fields_size) {
2223 ret = -ENOSPC;
2224 goto fail;
2227 memcpy(buf, s->unknown_header_fields, s->unknown_header_fields_size);
2228 buf += s->unknown_header_fields_size;
2229 buflen -= s->unknown_header_fields_size;
2232 /* Backing file format header extension */
2233 if (s->image_backing_format) {
2234 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BACKING_FORMAT,
2235 s->image_backing_format,
2236 strlen(s->image_backing_format),
2237 buflen);
2238 if (ret < 0) {
2239 goto fail;
2242 buf += ret;
2243 buflen -= ret;
2246 /* Full disk encryption header pointer extension */
2247 if (s->crypto_header.offset != 0) {
2248 cpu_to_be64s(&s->crypto_header.offset);
2249 cpu_to_be64s(&s->crypto_header.length);
2250 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_CRYPTO_HEADER,
2251 &s->crypto_header, sizeof(s->crypto_header),
2252 buflen);
2253 be64_to_cpus(&s->crypto_header.offset);
2254 be64_to_cpus(&s->crypto_header.length);
2255 if (ret < 0) {
2256 goto fail;
2258 buf += ret;
2259 buflen -= ret;
2262 /* Feature table */
2263 if (s->qcow_version >= 3) {
2264 Qcow2Feature features[] = {
2266 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
2267 .bit = QCOW2_INCOMPAT_DIRTY_BITNR,
2268 .name = "dirty bit",
2271 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
2272 .bit = QCOW2_INCOMPAT_CORRUPT_BITNR,
2273 .name = "corrupt bit",
2276 .type = QCOW2_FEAT_TYPE_COMPATIBLE,
2277 .bit = QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR,
2278 .name = "lazy refcounts",
2282 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_FEATURE_TABLE,
2283 features, sizeof(features), buflen);
2284 if (ret < 0) {
2285 goto fail;
2287 buf += ret;
2288 buflen -= ret;
2291 /* Bitmap extension */
2292 if (s->nb_bitmaps > 0) {
2293 Qcow2BitmapHeaderExt bitmaps_header = {
2294 .nb_bitmaps = cpu_to_be32(s->nb_bitmaps),
2295 .bitmap_directory_size =
2296 cpu_to_be64(s->bitmap_directory_size),
2297 .bitmap_directory_offset =
2298 cpu_to_be64(s->bitmap_directory_offset)
2300 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BITMAPS,
2301 &bitmaps_header, sizeof(bitmaps_header),
2302 buflen);
2303 if (ret < 0) {
2304 goto fail;
2306 buf += ret;
2307 buflen -= ret;
2310 /* Keep unknown header extensions */
2311 QLIST_FOREACH(uext, &s->unknown_header_ext, next) {
2312 ret = header_ext_add(buf, uext->magic, uext->data, uext->len, buflen);
2313 if (ret < 0) {
2314 goto fail;
2317 buf += ret;
2318 buflen -= ret;
2321 /* End of header extensions */
2322 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_END, NULL, 0, buflen);
2323 if (ret < 0) {
2324 goto fail;
2327 buf += ret;
2328 buflen -= ret;
2330 /* Backing file name */
2331 if (s->image_backing_file) {
2332 size_t backing_file_len = strlen(s->image_backing_file);
2334 if (buflen < backing_file_len) {
2335 ret = -ENOSPC;
2336 goto fail;
2339 /* Using strncpy is ok here, since buf is not NUL-terminated. */
2340 strncpy(buf, s->image_backing_file, buflen);
2342 header->backing_file_offset = cpu_to_be64(buf - ((char*) header));
2343 header->backing_file_size = cpu_to_be32(backing_file_len);
2346 /* Write the new header */
2347 ret = bdrv_pwrite(bs->file, 0, header, s->cluster_size);
2348 if (ret < 0) {
2349 goto fail;
2352 ret = 0;
2353 fail:
2354 qemu_vfree(header);
2355 return ret;
2358 static int qcow2_change_backing_file(BlockDriverState *bs,
2359 const char *backing_file, const char *backing_fmt)
2361 BDRVQcow2State *s = bs->opaque;
2363 if (backing_file && strlen(backing_file) > 1023) {
2364 return -EINVAL;
2367 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
2368 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
2370 g_free(s->image_backing_file);
2371 g_free(s->image_backing_format);
2373 s->image_backing_file = backing_file ? g_strdup(bs->backing_file) : NULL;
2374 s->image_backing_format = backing_fmt ? g_strdup(bs->backing_format) : NULL;
2376 return qcow2_update_header(bs);
2379 static int qcow2_crypt_method_from_format(const char *encryptfmt)
2381 if (g_str_equal(encryptfmt, "luks")) {
2382 return QCOW_CRYPT_LUKS;
2383 } else if (g_str_equal(encryptfmt, "aes")) {
2384 return QCOW_CRYPT_AES;
2385 } else {
2386 return -EINVAL;
2390 static int qcow2_set_up_encryption(BlockDriverState *bs, const char *encryptfmt,
2391 QemuOpts *opts, Error **errp)
2393 BDRVQcow2State *s = bs->opaque;
2394 QCryptoBlockCreateOptions *cryptoopts = NULL;
2395 QCryptoBlock *crypto = NULL;
2396 int ret = -EINVAL;
2397 QDict *options, *encryptopts;
2398 int fmt;
2400 options = qemu_opts_to_qdict(opts, NULL);
2401 qdict_extract_subqdict(options, &encryptopts, "encrypt.");
2402 QDECREF(options);
2404 fmt = qcow2_crypt_method_from_format(encryptfmt);
2406 switch (fmt) {
2407 case QCOW_CRYPT_LUKS:
2408 cryptoopts = block_crypto_create_opts_init(
2409 Q_CRYPTO_BLOCK_FORMAT_LUKS, encryptopts, errp);
2410 break;
2411 case QCOW_CRYPT_AES:
2412 cryptoopts = block_crypto_create_opts_init(
2413 Q_CRYPTO_BLOCK_FORMAT_QCOW, encryptopts, errp);
2414 break;
2415 default:
2416 error_setg(errp, "Unknown encryption format '%s'", encryptfmt);
2417 break;
2419 if (!cryptoopts) {
2420 ret = -EINVAL;
2421 goto out;
2423 s->crypt_method_header = fmt;
2425 crypto = qcrypto_block_create(cryptoopts, "encrypt.",
2426 qcow2_crypto_hdr_init_func,
2427 qcow2_crypto_hdr_write_func,
2428 bs, errp);
2429 if (!crypto) {
2430 ret = -EINVAL;
2431 goto out;
2434 ret = qcow2_update_header(bs);
2435 if (ret < 0) {
2436 error_setg_errno(errp, -ret, "Could not write encryption header");
2437 goto out;
2440 out:
2441 QDECREF(encryptopts);
2442 qcrypto_block_free(crypto);
2443 qapi_free_QCryptoBlockCreateOptions(cryptoopts);
2444 return ret;
2448 typedef struct PreallocCo {
2449 BlockDriverState *bs;
2450 uint64_t offset;
2451 uint64_t new_length;
2453 int ret;
2454 } PreallocCo;
2457 * Preallocates metadata structures for data clusters between @offset (in the
2458 * guest disk) and @new_length (which is thus generally the new guest disk
2459 * size).
2461 * Returns: 0 on success, -errno on failure.
2463 static void coroutine_fn preallocate_co(void *opaque)
2465 PreallocCo *params = opaque;
2466 BlockDriverState *bs = params->bs;
2467 uint64_t offset = params->offset;
2468 uint64_t new_length = params->new_length;
2469 BDRVQcow2State *s = bs->opaque;
2470 uint64_t bytes;
2471 uint64_t host_offset = 0;
2472 unsigned int cur_bytes;
2473 int ret;
2474 QCowL2Meta *meta;
2476 qemu_co_mutex_lock(&s->lock);
2478 assert(offset <= new_length);
2479 bytes = new_length - offset;
2481 while (bytes) {
2482 cur_bytes = MIN(bytes, INT_MAX);
2483 ret = qcow2_alloc_cluster_offset(bs, offset, &cur_bytes,
2484 &host_offset, &meta);
2485 if (ret < 0) {
2486 goto done;
2489 while (meta) {
2490 QCowL2Meta *next = meta->next;
2492 ret = qcow2_alloc_cluster_link_l2(bs, meta);
2493 if (ret < 0) {
2494 qcow2_free_any_clusters(bs, meta->alloc_offset,
2495 meta->nb_clusters, QCOW2_DISCARD_NEVER);
2496 goto done;
2499 /* There are no dependent requests, but we need to remove our
2500 * request from the list of in-flight requests */
2501 QLIST_REMOVE(meta, next_in_flight);
2503 g_free(meta);
2504 meta = next;
2507 /* TODO Preallocate data if requested */
2509 bytes -= cur_bytes;
2510 offset += cur_bytes;
2514 * It is expected that the image file is large enough to actually contain
2515 * all of the allocated clusters (otherwise we get failing reads after
2516 * EOF). Extend the image to the last allocated sector.
2518 if (host_offset != 0) {
2519 uint8_t data = 0;
2520 ret = bdrv_pwrite(bs->file, (host_offset + cur_bytes) - 1,
2521 &data, 1);
2522 if (ret < 0) {
2523 goto done;
2527 ret = 0;
2529 done:
2530 qemu_co_mutex_unlock(&s->lock);
2531 params->ret = ret;
2534 static int preallocate(BlockDriverState *bs,
2535 uint64_t offset, uint64_t new_length)
2537 PreallocCo params = {
2538 .bs = bs,
2539 .offset = offset,
2540 .new_length = new_length,
2541 .ret = -EINPROGRESS,
2544 if (qemu_in_coroutine()) {
2545 preallocate_co(&params);
2546 } else {
2547 Coroutine *co = qemu_coroutine_create(preallocate_co, &params);
2548 bdrv_coroutine_enter(bs, co);
2549 BDRV_POLL_WHILE(bs, params.ret == -EINPROGRESS);
2551 return params.ret;
2554 /* qcow2_refcount_metadata_size:
2555 * @clusters: number of clusters to refcount (including data and L1/L2 tables)
2556 * @cluster_size: size of a cluster, in bytes
2557 * @refcount_order: refcount bits power-of-2 exponent
2558 * @generous_increase: allow for the refcount table to be 1.5x as large as it
2559 * needs to be
2561 * Returns: Number of bytes required for refcount blocks and table metadata.
2563 int64_t qcow2_refcount_metadata_size(int64_t clusters, size_t cluster_size,
2564 int refcount_order, bool generous_increase,
2565 uint64_t *refblock_count)
2568 * Every host cluster is reference-counted, including metadata (even
2569 * refcount metadata is recursively included).
2571 * An accurate formula for the size of refcount metadata size is difficult
2572 * to derive. An easier method of calculation is finding the fixed point
2573 * where no further refcount blocks or table clusters are required to
2574 * reference count every cluster.
2576 int64_t blocks_per_table_cluster = cluster_size / sizeof(uint64_t);
2577 int64_t refcounts_per_block = cluster_size * 8 / (1 << refcount_order);
2578 int64_t table = 0; /* number of refcount table clusters */
2579 int64_t blocks = 0; /* number of refcount block clusters */
2580 int64_t last;
2581 int64_t n = 0;
2583 do {
2584 last = n;
2585 blocks = DIV_ROUND_UP(clusters + table + blocks, refcounts_per_block);
2586 table = DIV_ROUND_UP(blocks, blocks_per_table_cluster);
2587 n = clusters + blocks + table;
2589 if (n == last && generous_increase) {
2590 clusters += DIV_ROUND_UP(table, 2);
2591 n = 0; /* force another loop */
2592 generous_increase = false;
2594 } while (n != last);
2596 if (refblock_count) {
2597 *refblock_count = blocks;
2600 return (blocks + table) * cluster_size;
2604 * qcow2_calc_prealloc_size:
2605 * @total_size: virtual disk size in bytes
2606 * @cluster_size: cluster size in bytes
2607 * @refcount_order: refcount bits power-of-2 exponent
2609 * Returns: Total number of bytes required for the fully allocated image
2610 * (including metadata).
2612 static int64_t qcow2_calc_prealloc_size(int64_t total_size,
2613 size_t cluster_size,
2614 int refcount_order)
2616 int64_t meta_size = 0;
2617 uint64_t nl1e, nl2e;
2618 int64_t aligned_total_size = align_offset(total_size, cluster_size);
2620 /* header: 1 cluster */
2621 meta_size += cluster_size;
2623 /* total size of L2 tables */
2624 nl2e = aligned_total_size / cluster_size;
2625 nl2e = align_offset(nl2e, cluster_size / sizeof(uint64_t));
2626 meta_size += nl2e * sizeof(uint64_t);
2628 /* total size of L1 tables */
2629 nl1e = nl2e * sizeof(uint64_t) / cluster_size;
2630 nl1e = align_offset(nl1e, cluster_size / sizeof(uint64_t));
2631 meta_size += nl1e * sizeof(uint64_t);
2633 /* total size of refcount table and blocks */
2634 meta_size += qcow2_refcount_metadata_size(
2635 (meta_size + aligned_total_size) / cluster_size,
2636 cluster_size, refcount_order, false, NULL);
2638 return meta_size + aligned_total_size;
2641 static size_t qcow2_opt_get_cluster_size_del(QemuOpts *opts, Error **errp)
2643 size_t cluster_size;
2644 int cluster_bits;
2646 cluster_size = qemu_opt_get_size_del(opts, BLOCK_OPT_CLUSTER_SIZE,
2647 DEFAULT_CLUSTER_SIZE);
2648 cluster_bits = ctz32(cluster_size);
2649 if (cluster_bits < MIN_CLUSTER_BITS || cluster_bits > MAX_CLUSTER_BITS ||
2650 (1 << cluster_bits) != cluster_size)
2652 error_setg(errp, "Cluster size must be a power of two between %d and "
2653 "%dk", 1 << MIN_CLUSTER_BITS, 1 << (MAX_CLUSTER_BITS - 10));
2654 return 0;
2656 return cluster_size;
2659 static int qcow2_opt_get_version_del(QemuOpts *opts, Error **errp)
2661 char *buf;
2662 int ret;
2664 buf = qemu_opt_get_del(opts, BLOCK_OPT_COMPAT_LEVEL);
2665 if (!buf) {
2666 ret = 3; /* default */
2667 } else if (!strcmp(buf, "0.10")) {
2668 ret = 2;
2669 } else if (!strcmp(buf, "1.1")) {
2670 ret = 3;
2671 } else {
2672 error_setg(errp, "Invalid compatibility level: '%s'", buf);
2673 ret = -EINVAL;
2675 g_free(buf);
2676 return ret;
2679 static uint64_t qcow2_opt_get_refcount_bits_del(QemuOpts *opts, int version,
2680 Error **errp)
2682 uint64_t refcount_bits;
2684 refcount_bits = qemu_opt_get_number_del(opts, BLOCK_OPT_REFCOUNT_BITS, 16);
2685 if (refcount_bits > 64 || !is_power_of_2(refcount_bits)) {
2686 error_setg(errp, "Refcount width must be a power of two and may not "
2687 "exceed 64 bits");
2688 return 0;
2691 if (version < 3 && refcount_bits != 16) {
2692 error_setg(errp, "Different refcount widths than 16 bits require "
2693 "compatibility level 1.1 or above (use compat=1.1 or "
2694 "greater)");
2695 return 0;
2698 return refcount_bits;
2701 static int qcow2_create2(const char *filename, int64_t total_size,
2702 const char *backing_file, const char *backing_format,
2703 int flags, size_t cluster_size, PreallocMode prealloc,
2704 QemuOpts *opts, int version, int refcount_order,
2705 const char *encryptfmt, Error **errp)
2707 QDict *options;
2710 * Open the image file and write a minimal qcow2 header.
2712 * We keep things simple and start with a zero-sized image. We also
2713 * do without refcount blocks or a L1 table for now. We'll fix the
2714 * inconsistency later.
2716 * We do need a refcount table because growing the refcount table means
2717 * allocating two new refcount blocks - the seconds of which would be at
2718 * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
2719 * size for any qcow2 image.
2721 BlockBackend *blk;
2722 QCowHeader *header;
2723 uint64_t* refcount_table;
2724 Error *local_err = NULL;
2725 int ret;
2727 if (prealloc == PREALLOC_MODE_FULL || prealloc == PREALLOC_MODE_FALLOC) {
2728 int64_t prealloc_size =
2729 qcow2_calc_prealloc_size(total_size, cluster_size, refcount_order);
2730 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, prealloc_size, &error_abort);
2731 qemu_opt_set(opts, BLOCK_OPT_PREALLOC, PreallocMode_str(prealloc),
2732 &error_abort);
2735 ret = bdrv_create_file(filename, opts, &local_err);
2736 if (ret < 0) {
2737 error_propagate(errp, local_err);
2738 return ret;
2741 blk = blk_new_open(filename, NULL, NULL,
2742 BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_PROTOCOL,
2743 &local_err);
2744 if (blk == NULL) {
2745 error_propagate(errp, local_err);
2746 return -EIO;
2749 blk_set_allow_write_beyond_eof(blk, true);
2751 /* Write the header */
2752 QEMU_BUILD_BUG_ON((1 << MIN_CLUSTER_BITS) < sizeof(*header));
2753 header = g_malloc0(cluster_size);
2754 *header = (QCowHeader) {
2755 .magic = cpu_to_be32(QCOW_MAGIC),
2756 .version = cpu_to_be32(version),
2757 .cluster_bits = cpu_to_be32(ctz32(cluster_size)),
2758 .size = cpu_to_be64(0),
2759 .l1_table_offset = cpu_to_be64(0),
2760 .l1_size = cpu_to_be32(0),
2761 .refcount_table_offset = cpu_to_be64(cluster_size),
2762 .refcount_table_clusters = cpu_to_be32(1),
2763 .refcount_order = cpu_to_be32(refcount_order),
2764 .header_length = cpu_to_be32(sizeof(*header)),
2767 /* We'll update this to correct value later */
2768 header->crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
2770 if (flags & BLOCK_FLAG_LAZY_REFCOUNTS) {
2771 header->compatible_features |=
2772 cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS);
2775 ret = blk_pwrite(blk, 0, header, cluster_size, 0);
2776 g_free(header);
2777 if (ret < 0) {
2778 error_setg_errno(errp, -ret, "Could not write qcow2 header");
2779 goto out;
2782 /* Write a refcount table with one refcount block */
2783 refcount_table = g_malloc0(2 * cluster_size);
2784 refcount_table[0] = cpu_to_be64(2 * cluster_size);
2785 ret = blk_pwrite(blk, cluster_size, refcount_table, 2 * cluster_size, 0);
2786 g_free(refcount_table);
2788 if (ret < 0) {
2789 error_setg_errno(errp, -ret, "Could not write refcount table");
2790 goto out;
2793 blk_unref(blk);
2794 blk = NULL;
2797 * And now open the image and make it consistent first (i.e. increase the
2798 * refcount of the cluster that is occupied by the header and the refcount
2799 * table)
2801 options = qdict_new();
2802 qdict_put_str(options, "driver", "qcow2");
2803 blk = blk_new_open(filename, NULL, options,
2804 BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_NO_FLUSH,
2805 &local_err);
2806 if (blk == NULL) {
2807 error_propagate(errp, local_err);
2808 ret = -EIO;
2809 goto out;
2812 ret = qcow2_alloc_clusters(blk_bs(blk), 3 * cluster_size);
2813 if (ret < 0) {
2814 error_setg_errno(errp, -ret, "Could not allocate clusters for qcow2 "
2815 "header and refcount table");
2816 goto out;
2818 } else if (ret != 0) {
2819 error_report("Huh, first cluster in empty image is already in use?");
2820 abort();
2823 /* Create a full header (including things like feature table) */
2824 ret = qcow2_update_header(blk_bs(blk));
2825 if (ret < 0) {
2826 error_setg_errno(errp, -ret, "Could not update qcow2 header");
2827 goto out;
2830 /* Okay, now that we have a valid image, let's give it the right size */
2831 ret = blk_truncate(blk, total_size, PREALLOC_MODE_OFF, errp);
2832 if (ret < 0) {
2833 error_prepend(errp, "Could not resize image: ");
2834 goto out;
2837 /* Want a backing file? There you go.*/
2838 if (backing_file) {
2839 ret = bdrv_change_backing_file(blk_bs(blk), backing_file, backing_format);
2840 if (ret < 0) {
2841 error_setg_errno(errp, -ret, "Could not assign backing file '%s' "
2842 "with format '%s'", backing_file, backing_format);
2843 goto out;
2847 /* Want encryption? There you go. */
2848 if (encryptfmt) {
2849 ret = qcow2_set_up_encryption(blk_bs(blk), encryptfmt, opts, errp);
2850 if (ret < 0) {
2851 goto out;
2855 /* And if we're supposed to preallocate metadata, do that now */
2856 if (prealloc != PREALLOC_MODE_OFF) {
2857 ret = preallocate(blk_bs(blk), 0, total_size);
2858 if (ret < 0) {
2859 error_setg_errno(errp, -ret, "Could not preallocate metadata");
2860 goto out;
2864 blk_unref(blk);
2865 blk = NULL;
2867 /* Reopen the image without BDRV_O_NO_FLUSH to flush it before returning.
2868 * Using BDRV_O_NO_IO, since encryption is now setup we don't want to
2869 * have to setup decryption context. We're not doing any I/O on the top
2870 * level BlockDriverState, only lower layers, where BDRV_O_NO_IO does
2871 * not have effect.
2873 options = qdict_new();
2874 qdict_put_str(options, "driver", "qcow2");
2875 blk = blk_new_open(filename, NULL, options,
2876 BDRV_O_RDWR | BDRV_O_NO_BACKING | BDRV_O_NO_IO,
2877 &local_err);
2878 if (blk == NULL) {
2879 error_propagate(errp, local_err);
2880 ret = -EIO;
2881 goto out;
2884 ret = 0;
2885 out:
2886 if (blk) {
2887 blk_unref(blk);
2889 return ret;
2892 static int qcow2_create(const char *filename, QemuOpts *opts, Error **errp)
2894 char *backing_file = NULL;
2895 char *backing_fmt = NULL;
2896 char *buf = NULL;
2897 uint64_t size = 0;
2898 int flags = 0;
2899 size_t cluster_size = DEFAULT_CLUSTER_SIZE;
2900 PreallocMode prealloc;
2901 int version;
2902 uint64_t refcount_bits;
2903 int refcount_order;
2904 char *encryptfmt = NULL;
2905 Error *local_err = NULL;
2906 int ret;
2908 /* Read out options */
2909 size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
2910 BDRV_SECTOR_SIZE);
2911 backing_file = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
2912 backing_fmt = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FMT);
2913 encryptfmt = qemu_opt_get_del(opts, BLOCK_OPT_ENCRYPT_FORMAT);
2914 if (encryptfmt) {
2915 if (qemu_opt_get(opts, BLOCK_OPT_ENCRYPT)) {
2916 error_setg(errp, "Options " BLOCK_OPT_ENCRYPT " and "
2917 BLOCK_OPT_ENCRYPT_FORMAT " are mutually exclusive");
2918 ret = -EINVAL;
2919 goto finish;
2921 } else if (qemu_opt_get_bool_del(opts, BLOCK_OPT_ENCRYPT, false)) {
2922 encryptfmt = g_strdup("aes");
2924 cluster_size = qcow2_opt_get_cluster_size_del(opts, &local_err);
2925 if (local_err) {
2926 error_propagate(errp, local_err);
2927 ret = -EINVAL;
2928 goto finish;
2930 buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
2931 prealloc = qapi_enum_parse(&PreallocMode_lookup, buf,
2932 PREALLOC_MODE_OFF, &local_err);
2933 if (local_err) {
2934 error_propagate(errp, local_err);
2935 ret = -EINVAL;
2936 goto finish;
2939 version = qcow2_opt_get_version_del(opts, &local_err);
2940 if (local_err) {
2941 error_propagate(errp, local_err);
2942 ret = -EINVAL;
2943 goto finish;
2946 if (qemu_opt_get_bool_del(opts, BLOCK_OPT_LAZY_REFCOUNTS, false)) {
2947 flags |= BLOCK_FLAG_LAZY_REFCOUNTS;
2950 if (backing_file && prealloc != PREALLOC_MODE_OFF) {
2951 error_setg(errp, "Backing file and preallocation cannot be used at "
2952 "the same time");
2953 ret = -EINVAL;
2954 goto finish;
2957 if (version < 3 && (flags & BLOCK_FLAG_LAZY_REFCOUNTS)) {
2958 error_setg(errp, "Lazy refcounts only supported with compatibility "
2959 "level 1.1 and above (use compat=1.1 or greater)");
2960 ret = -EINVAL;
2961 goto finish;
2964 refcount_bits = qcow2_opt_get_refcount_bits_del(opts, version, &local_err);
2965 if (local_err) {
2966 error_propagate(errp, local_err);
2967 ret = -EINVAL;
2968 goto finish;
2971 refcount_order = ctz32(refcount_bits);
2973 ret = qcow2_create2(filename, size, backing_file, backing_fmt, flags,
2974 cluster_size, prealloc, opts, version, refcount_order,
2975 encryptfmt, &local_err);
2976 error_propagate(errp, local_err);
2978 finish:
2979 g_free(backing_file);
2980 g_free(backing_fmt);
2981 g_free(encryptfmt);
2982 g_free(buf);
2983 return ret;
2987 static bool is_zero(BlockDriverState *bs, int64_t offset, int64_t bytes)
2989 int64_t nr;
2990 int res;
2992 /* Clamp to image length, before checking status of underlying sectors */
2993 if (offset + bytes > bs->total_sectors * BDRV_SECTOR_SIZE) {
2994 bytes = bs->total_sectors * BDRV_SECTOR_SIZE - offset;
2997 if (!bytes) {
2998 return true;
3000 res = bdrv_block_status_above(bs, NULL, offset, bytes, &nr, NULL, NULL);
3001 return res >= 0 && (res & BDRV_BLOCK_ZERO) && nr == bytes;
3004 static coroutine_fn int qcow2_co_pwrite_zeroes(BlockDriverState *bs,
3005 int64_t offset, int bytes, BdrvRequestFlags flags)
3007 int ret;
3008 BDRVQcow2State *s = bs->opaque;
3010 uint32_t head = offset % s->cluster_size;
3011 uint32_t tail = (offset + bytes) % s->cluster_size;
3013 trace_qcow2_pwrite_zeroes_start_req(qemu_coroutine_self(), offset, bytes);
3014 if (offset + bytes == bs->total_sectors * BDRV_SECTOR_SIZE) {
3015 tail = 0;
3018 if (head || tail) {
3019 uint64_t off;
3020 unsigned int nr;
3022 assert(head + bytes <= s->cluster_size);
3024 /* check whether remainder of cluster already reads as zero */
3025 if (!(is_zero(bs, offset - head, head) &&
3026 is_zero(bs, offset + bytes,
3027 tail ? s->cluster_size - tail : 0))) {
3028 return -ENOTSUP;
3031 qemu_co_mutex_lock(&s->lock);
3032 /* We can have new write after previous check */
3033 offset = QEMU_ALIGN_DOWN(offset, s->cluster_size);
3034 bytes = s->cluster_size;
3035 nr = s->cluster_size;
3036 ret = qcow2_get_cluster_offset(bs, offset, &nr, &off);
3037 if (ret != QCOW2_CLUSTER_UNALLOCATED &&
3038 ret != QCOW2_CLUSTER_ZERO_PLAIN &&
3039 ret != QCOW2_CLUSTER_ZERO_ALLOC) {
3040 qemu_co_mutex_unlock(&s->lock);
3041 return -ENOTSUP;
3043 } else {
3044 qemu_co_mutex_lock(&s->lock);
3047 trace_qcow2_pwrite_zeroes(qemu_coroutine_self(), offset, bytes);
3049 /* Whatever is left can use real zero clusters */
3050 ret = qcow2_cluster_zeroize(bs, offset, bytes, flags);
3051 qemu_co_mutex_unlock(&s->lock);
3053 return ret;
3056 static coroutine_fn int qcow2_co_pdiscard(BlockDriverState *bs,
3057 int64_t offset, int bytes)
3059 int ret;
3060 BDRVQcow2State *s = bs->opaque;
3062 if (!QEMU_IS_ALIGNED(offset | bytes, s->cluster_size)) {
3063 assert(bytes < s->cluster_size);
3064 /* Ignore partial clusters, except for the special case of the
3065 * complete partial cluster at the end of an unaligned file */
3066 if (!QEMU_IS_ALIGNED(offset, s->cluster_size) ||
3067 offset + bytes != bs->total_sectors * BDRV_SECTOR_SIZE) {
3068 return -ENOTSUP;
3072 qemu_co_mutex_lock(&s->lock);
3073 ret = qcow2_cluster_discard(bs, offset, bytes, QCOW2_DISCARD_REQUEST,
3074 false);
3075 qemu_co_mutex_unlock(&s->lock);
3076 return ret;
3079 static int qcow2_truncate(BlockDriverState *bs, int64_t offset,
3080 PreallocMode prealloc, Error **errp)
3082 BDRVQcow2State *s = bs->opaque;
3083 uint64_t old_length;
3084 int64_t new_l1_size;
3085 int ret;
3087 if (prealloc != PREALLOC_MODE_OFF && prealloc != PREALLOC_MODE_METADATA &&
3088 prealloc != PREALLOC_MODE_FALLOC && prealloc != PREALLOC_MODE_FULL)
3090 error_setg(errp, "Unsupported preallocation mode '%s'",
3091 PreallocMode_str(prealloc));
3092 return -ENOTSUP;
3095 if (offset & 511) {
3096 error_setg(errp, "The new size must be a multiple of 512");
3097 return -EINVAL;
3100 /* cannot proceed if image has snapshots */
3101 if (s->nb_snapshots) {
3102 error_setg(errp, "Can't resize an image which has snapshots");
3103 return -ENOTSUP;
3106 /* cannot proceed if image has bitmaps */
3107 if (s->nb_bitmaps) {
3108 /* TODO: resize bitmaps in the image */
3109 error_setg(errp, "Can't resize an image which has bitmaps");
3110 return -ENOTSUP;
3113 old_length = bs->total_sectors * 512;
3114 new_l1_size = size_to_l1(s, offset);
3116 if (offset < old_length) {
3117 int64_t last_cluster, old_file_size;
3118 if (prealloc != PREALLOC_MODE_OFF) {
3119 error_setg(errp,
3120 "Preallocation can't be used for shrinking an image");
3121 return -EINVAL;
3124 ret = qcow2_cluster_discard(bs, ROUND_UP(offset, s->cluster_size),
3125 old_length - ROUND_UP(offset,
3126 s->cluster_size),
3127 QCOW2_DISCARD_ALWAYS, true);
3128 if (ret < 0) {
3129 error_setg_errno(errp, -ret, "Failed to discard cropped clusters");
3130 return ret;
3133 ret = qcow2_shrink_l1_table(bs, new_l1_size);
3134 if (ret < 0) {
3135 error_setg_errno(errp, -ret,
3136 "Failed to reduce the number of L2 tables");
3137 return ret;
3140 ret = qcow2_shrink_reftable(bs);
3141 if (ret < 0) {
3142 error_setg_errno(errp, -ret,
3143 "Failed to discard unused refblocks");
3144 return ret;
3147 old_file_size = bdrv_getlength(bs->file->bs);
3148 if (old_file_size < 0) {
3149 error_setg_errno(errp, -old_file_size,
3150 "Failed to inquire current file length");
3151 return old_file_size;
3153 last_cluster = qcow2_get_last_cluster(bs, old_file_size);
3154 if (last_cluster < 0) {
3155 error_setg_errno(errp, -last_cluster,
3156 "Failed to find the last cluster");
3157 return last_cluster;
3159 if ((last_cluster + 1) * s->cluster_size < old_file_size) {
3160 Error *local_err = NULL;
3162 bdrv_truncate(bs->file, (last_cluster + 1) * s->cluster_size,
3163 PREALLOC_MODE_OFF, &local_err);
3164 if (local_err) {
3165 warn_reportf_err(local_err,
3166 "Failed to truncate the tail of the image: ");
3169 } else {
3170 ret = qcow2_grow_l1_table(bs, new_l1_size, true);
3171 if (ret < 0) {
3172 error_setg_errno(errp, -ret, "Failed to grow the L1 table");
3173 return ret;
3177 switch (prealloc) {
3178 case PREALLOC_MODE_OFF:
3179 break;
3181 case PREALLOC_MODE_METADATA:
3182 ret = preallocate(bs, old_length, offset);
3183 if (ret < 0) {
3184 error_setg_errno(errp, -ret, "Preallocation failed");
3185 return ret;
3187 break;
3189 case PREALLOC_MODE_FALLOC:
3190 case PREALLOC_MODE_FULL:
3192 int64_t allocation_start, host_offset, guest_offset;
3193 int64_t clusters_allocated;
3194 int64_t old_file_size, new_file_size;
3195 uint64_t nb_new_data_clusters, nb_new_l2_tables;
3197 old_file_size = bdrv_getlength(bs->file->bs);
3198 if (old_file_size < 0) {
3199 error_setg_errno(errp, -old_file_size,
3200 "Failed to inquire current file length");
3201 return old_file_size;
3203 old_file_size = ROUND_UP(old_file_size, s->cluster_size);
3205 nb_new_data_clusters = DIV_ROUND_UP(offset - old_length,
3206 s->cluster_size);
3208 /* This is an overestimation; we will not actually allocate space for
3209 * these in the file but just make sure the new refcount structures are
3210 * able to cover them so we will not have to allocate new refblocks
3211 * while entering the data blocks in the potentially new L2 tables.
3212 * (We do not actually care where the L2 tables are placed. Maybe they
3213 * are already allocated or they can be placed somewhere before
3214 * @old_file_size. It does not matter because they will be fully
3215 * allocated automatically, so they do not need to be covered by the
3216 * preallocation. All that matters is that we will not have to allocate
3217 * new refcount structures for them.) */
3218 nb_new_l2_tables = DIV_ROUND_UP(nb_new_data_clusters,
3219 s->cluster_size / sizeof(uint64_t));
3220 /* The cluster range may not be aligned to L2 boundaries, so add one L2
3221 * table for a potential head/tail */
3222 nb_new_l2_tables++;
3224 allocation_start = qcow2_refcount_area(bs, old_file_size,
3225 nb_new_data_clusters +
3226 nb_new_l2_tables,
3227 true, 0, 0);
3228 if (allocation_start < 0) {
3229 error_setg_errno(errp, -allocation_start,
3230 "Failed to resize refcount structures");
3231 return allocation_start;
3234 clusters_allocated = qcow2_alloc_clusters_at(bs, allocation_start,
3235 nb_new_data_clusters);
3236 if (clusters_allocated < 0) {
3237 error_setg_errno(errp, -clusters_allocated,
3238 "Failed to allocate data clusters");
3239 return -clusters_allocated;
3242 assert(clusters_allocated == nb_new_data_clusters);
3244 /* Allocate the data area */
3245 new_file_size = allocation_start +
3246 nb_new_data_clusters * s->cluster_size;
3247 ret = bdrv_truncate(bs->file, new_file_size, prealloc, errp);
3248 if (ret < 0) {
3249 error_prepend(errp, "Failed to resize underlying file: ");
3250 qcow2_free_clusters(bs, allocation_start,
3251 nb_new_data_clusters * s->cluster_size,
3252 QCOW2_DISCARD_OTHER);
3253 return ret;
3256 /* Create the necessary L2 entries */
3257 host_offset = allocation_start;
3258 guest_offset = old_length;
3259 while (nb_new_data_clusters) {
3260 int64_t guest_cluster = guest_offset >> s->cluster_bits;
3261 int64_t nb_clusters = MIN(nb_new_data_clusters,
3262 s->l2_size - guest_cluster % s->l2_size);
3263 QCowL2Meta allocation = {
3264 .offset = guest_offset,
3265 .alloc_offset = host_offset,
3266 .nb_clusters = nb_clusters,
3268 qemu_co_queue_init(&allocation.dependent_requests);
3270 ret = qcow2_alloc_cluster_link_l2(bs, &allocation);
3271 if (ret < 0) {
3272 error_setg_errno(errp, -ret, "Failed to update L2 tables");
3273 qcow2_free_clusters(bs, host_offset,
3274 nb_new_data_clusters * s->cluster_size,
3275 QCOW2_DISCARD_OTHER);
3276 return ret;
3279 guest_offset += nb_clusters * s->cluster_size;
3280 host_offset += nb_clusters * s->cluster_size;
3281 nb_new_data_clusters -= nb_clusters;
3283 break;
3286 default:
3287 g_assert_not_reached();
3290 if (prealloc != PREALLOC_MODE_OFF) {
3291 /* Flush metadata before actually changing the image size */
3292 ret = bdrv_flush(bs);
3293 if (ret < 0) {
3294 error_setg_errno(errp, -ret,
3295 "Failed to flush the preallocated area to disk");
3296 return ret;
3300 /* write updated header.size */
3301 offset = cpu_to_be64(offset);
3302 ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, size),
3303 &offset, sizeof(uint64_t));
3304 if (ret < 0) {
3305 error_setg_errno(errp, -ret, "Failed to update the image size");
3306 return ret;
3309 s->l1_vm_state_index = new_l1_size;
3310 return 0;
3313 /* XXX: put compressed sectors first, then all the cluster aligned
3314 tables to avoid losing bytes in alignment */
3315 static coroutine_fn int
3316 qcow2_co_pwritev_compressed(BlockDriverState *bs, uint64_t offset,
3317 uint64_t bytes, QEMUIOVector *qiov)
3319 BDRVQcow2State *s = bs->opaque;
3320 QEMUIOVector hd_qiov;
3321 struct iovec iov;
3322 z_stream strm;
3323 int ret, out_len;
3324 uint8_t *buf, *out_buf;
3325 int64_t cluster_offset;
3327 if (bytes == 0) {
3328 /* align end of file to a sector boundary to ease reading with
3329 sector based I/Os */
3330 cluster_offset = bdrv_getlength(bs->file->bs);
3331 if (cluster_offset < 0) {
3332 return cluster_offset;
3334 return bdrv_truncate(bs->file, cluster_offset, PREALLOC_MODE_OFF, NULL);
3337 if (offset_into_cluster(s, offset)) {
3338 return -EINVAL;
3341 buf = qemu_blockalign(bs, s->cluster_size);
3342 if (bytes != s->cluster_size) {
3343 if (bytes > s->cluster_size ||
3344 offset + bytes != bs->total_sectors << BDRV_SECTOR_BITS)
3346 qemu_vfree(buf);
3347 return -EINVAL;
3349 /* Zero-pad last write if image size is not cluster aligned */
3350 memset(buf + bytes, 0, s->cluster_size - bytes);
3352 qemu_iovec_to_buf(qiov, 0, buf, bytes);
3354 out_buf = g_malloc(s->cluster_size);
3356 /* best compression, small window, no zlib header */
3357 memset(&strm, 0, sizeof(strm));
3358 ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
3359 Z_DEFLATED, -12,
3360 9, Z_DEFAULT_STRATEGY);
3361 if (ret != 0) {
3362 ret = -EINVAL;
3363 goto fail;
3366 strm.avail_in = s->cluster_size;
3367 strm.next_in = (uint8_t *)buf;
3368 strm.avail_out = s->cluster_size;
3369 strm.next_out = out_buf;
3371 ret = deflate(&strm, Z_FINISH);
3372 if (ret != Z_STREAM_END && ret != Z_OK) {
3373 deflateEnd(&strm);
3374 ret = -EINVAL;
3375 goto fail;
3377 out_len = strm.next_out - out_buf;
3379 deflateEnd(&strm);
3381 if (ret != Z_STREAM_END || out_len >= s->cluster_size) {
3382 /* could not compress: write normal cluster */
3383 ret = qcow2_co_pwritev(bs, offset, bytes, qiov, 0);
3384 if (ret < 0) {
3385 goto fail;
3387 goto success;
3390 qemu_co_mutex_lock(&s->lock);
3391 cluster_offset =
3392 qcow2_alloc_compressed_cluster_offset(bs, offset, out_len);
3393 if (!cluster_offset) {
3394 qemu_co_mutex_unlock(&s->lock);
3395 ret = -EIO;
3396 goto fail;
3398 cluster_offset &= s->cluster_offset_mask;
3400 ret = qcow2_pre_write_overlap_check(bs, 0, cluster_offset, out_len);
3401 qemu_co_mutex_unlock(&s->lock);
3402 if (ret < 0) {
3403 goto fail;
3406 iov = (struct iovec) {
3407 .iov_base = out_buf,
3408 .iov_len = out_len,
3410 qemu_iovec_init_external(&hd_qiov, &iov, 1);
3412 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_COMPRESSED);
3413 ret = bdrv_co_pwritev(bs->file, cluster_offset, out_len, &hd_qiov, 0);
3414 if (ret < 0) {
3415 goto fail;
3417 success:
3418 ret = 0;
3419 fail:
3420 qemu_vfree(buf);
3421 g_free(out_buf);
3422 return ret;
3425 static int make_completely_empty(BlockDriverState *bs)
3427 BDRVQcow2State *s = bs->opaque;
3428 Error *local_err = NULL;
3429 int ret, l1_clusters;
3430 int64_t offset;
3431 uint64_t *new_reftable = NULL;
3432 uint64_t rt_entry, l1_size2;
3433 struct {
3434 uint64_t l1_offset;
3435 uint64_t reftable_offset;
3436 uint32_t reftable_clusters;
3437 } QEMU_PACKED l1_ofs_rt_ofs_cls;
3439 ret = qcow2_cache_empty(bs, s->l2_table_cache);
3440 if (ret < 0) {
3441 goto fail;
3444 ret = qcow2_cache_empty(bs, s->refcount_block_cache);
3445 if (ret < 0) {
3446 goto fail;
3449 /* Refcounts will be broken utterly */
3450 ret = qcow2_mark_dirty(bs);
3451 if (ret < 0) {
3452 goto fail;
3455 BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
3457 l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / sizeof(uint64_t));
3458 l1_size2 = (uint64_t)s->l1_size * sizeof(uint64_t);
3460 /* After this call, neither the in-memory nor the on-disk refcount
3461 * information accurately describe the actual references */
3463 ret = bdrv_pwrite_zeroes(bs->file, s->l1_table_offset,
3464 l1_clusters * s->cluster_size, 0);
3465 if (ret < 0) {
3466 goto fail_broken_refcounts;
3468 memset(s->l1_table, 0, l1_size2);
3470 BLKDBG_EVENT(bs->file, BLKDBG_EMPTY_IMAGE_PREPARE);
3472 /* Overwrite enough clusters at the beginning of the sectors to place
3473 * the refcount table, a refcount block and the L1 table in; this may
3474 * overwrite parts of the existing refcount and L1 table, which is not
3475 * an issue because the dirty flag is set, complete data loss is in fact
3476 * desired and partial data loss is consequently fine as well */
3477 ret = bdrv_pwrite_zeroes(bs->file, s->cluster_size,
3478 (2 + l1_clusters) * s->cluster_size, 0);
3479 /* This call (even if it failed overall) may have overwritten on-disk
3480 * refcount structures; in that case, the in-memory refcount information
3481 * will probably differ from the on-disk information which makes the BDS
3482 * unusable */
3483 if (ret < 0) {
3484 goto fail_broken_refcounts;
3487 BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
3488 BLKDBG_EVENT(bs->file, BLKDBG_REFTABLE_UPDATE);
3490 /* "Create" an empty reftable (one cluster) directly after the image
3491 * header and an empty L1 table three clusters after the image header;
3492 * the cluster between those two will be used as the first refblock */
3493 l1_ofs_rt_ofs_cls.l1_offset = cpu_to_be64(3 * s->cluster_size);
3494 l1_ofs_rt_ofs_cls.reftable_offset = cpu_to_be64(s->cluster_size);
3495 l1_ofs_rt_ofs_cls.reftable_clusters = cpu_to_be32(1);
3496 ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, l1_table_offset),
3497 &l1_ofs_rt_ofs_cls, sizeof(l1_ofs_rt_ofs_cls));
3498 if (ret < 0) {
3499 goto fail_broken_refcounts;
3502 s->l1_table_offset = 3 * s->cluster_size;
3504 new_reftable = g_try_new0(uint64_t, s->cluster_size / sizeof(uint64_t));
3505 if (!new_reftable) {
3506 ret = -ENOMEM;
3507 goto fail_broken_refcounts;
3510 s->refcount_table_offset = s->cluster_size;
3511 s->refcount_table_size = s->cluster_size / sizeof(uint64_t);
3512 s->max_refcount_table_index = 0;
3514 g_free(s->refcount_table);
3515 s->refcount_table = new_reftable;
3516 new_reftable = NULL;
3518 /* Now the in-memory refcount information again corresponds to the on-disk
3519 * information (reftable is empty and no refblocks (the refblock cache is
3520 * empty)); however, this means some clusters (e.g. the image header) are
3521 * referenced, but not refcounted, but the normal qcow2 code assumes that
3522 * the in-memory information is always correct */
3524 BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_ALLOC);
3526 /* Enter the first refblock into the reftable */
3527 rt_entry = cpu_to_be64(2 * s->cluster_size);
3528 ret = bdrv_pwrite_sync(bs->file, s->cluster_size,
3529 &rt_entry, sizeof(rt_entry));
3530 if (ret < 0) {
3531 goto fail_broken_refcounts;
3533 s->refcount_table[0] = 2 * s->cluster_size;
3535 s->free_cluster_index = 0;
3536 assert(3 + l1_clusters <= s->refcount_block_size);
3537 offset = qcow2_alloc_clusters(bs, 3 * s->cluster_size + l1_size2);
3538 if (offset < 0) {
3539 ret = offset;
3540 goto fail_broken_refcounts;
3541 } else if (offset > 0) {
3542 error_report("First cluster in emptied image is in use");
3543 abort();
3546 /* Now finally the in-memory information corresponds to the on-disk
3547 * structures and is correct */
3548 ret = qcow2_mark_clean(bs);
3549 if (ret < 0) {
3550 goto fail;
3553 ret = bdrv_truncate(bs->file, (3 + l1_clusters) * s->cluster_size,
3554 PREALLOC_MODE_OFF, &local_err);
3555 if (ret < 0) {
3556 error_report_err(local_err);
3557 goto fail;
3560 return 0;
3562 fail_broken_refcounts:
3563 /* The BDS is unusable at this point. If we wanted to make it usable, we
3564 * would have to call qcow2_refcount_close(), qcow2_refcount_init(),
3565 * qcow2_check_refcounts(), qcow2_refcount_close() and qcow2_refcount_init()
3566 * again. However, because the functions which could have caused this error
3567 * path to be taken are used by those functions as well, it's very likely
3568 * that that sequence will fail as well. Therefore, just eject the BDS. */
3569 bs->drv = NULL;
3571 fail:
3572 g_free(new_reftable);
3573 return ret;
3576 static int qcow2_make_empty(BlockDriverState *bs)
3578 BDRVQcow2State *s = bs->opaque;
3579 uint64_t offset, end_offset;
3580 int step = QEMU_ALIGN_DOWN(INT_MAX, s->cluster_size);
3581 int l1_clusters, ret = 0;
3583 l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / sizeof(uint64_t));
3585 if (s->qcow_version >= 3 && !s->snapshots && !s->nb_bitmaps &&
3586 3 + l1_clusters <= s->refcount_block_size &&
3587 s->crypt_method_header != QCOW_CRYPT_LUKS) {
3588 /* The following function only works for qcow2 v3 images (it
3589 * requires the dirty flag) and only as long as there are no
3590 * features that reserve extra clusters (such as snapshots,
3591 * LUKS header, or persistent bitmaps), because it completely
3592 * empties the image. Furthermore, the L1 table and three
3593 * additional clusters (image header, refcount table, one
3594 * refcount block) have to fit inside one refcount block. */
3595 return make_completely_empty(bs);
3598 /* This fallback code simply discards every active cluster; this is slow,
3599 * but works in all cases */
3600 end_offset = bs->total_sectors * BDRV_SECTOR_SIZE;
3601 for (offset = 0; offset < end_offset; offset += step) {
3602 /* As this function is generally used after committing an external
3603 * snapshot, QCOW2_DISCARD_SNAPSHOT seems appropriate. Also, the
3604 * default action for this kind of discard is to pass the discard,
3605 * which will ideally result in an actually smaller image file, as
3606 * is probably desired. */
3607 ret = qcow2_cluster_discard(bs, offset, MIN(step, end_offset - offset),
3608 QCOW2_DISCARD_SNAPSHOT, true);
3609 if (ret < 0) {
3610 break;
3614 return ret;
3617 static coroutine_fn int qcow2_co_flush_to_os(BlockDriverState *bs)
3619 BDRVQcow2State *s = bs->opaque;
3620 int ret;
3622 qemu_co_mutex_lock(&s->lock);
3623 ret = qcow2_cache_write(bs, s->l2_table_cache);
3624 if (ret < 0) {
3625 qemu_co_mutex_unlock(&s->lock);
3626 return ret;
3629 if (qcow2_need_accurate_refcounts(s)) {
3630 ret = qcow2_cache_write(bs, s->refcount_block_cache);
3631 if (ret < 0) {
3632 qemu_co_mutex_unlock(&s->lock);
3633 return ret;
3636 qemu_co_mutex_unlock(&s->lock);
3638 return 0;
3641 static BlockMeasureInfo *qcow2_measure(QemuOpts *opts, BlockDriverState *in_bs,
3642 Error **errp)
3644 Error *local_err = NULL;
3645 BlockMeasureInfo *info;
3646 uint64_t required = 0; /* bytes that contribute to required size */
3647 uint64_t virtual_size; /* disk size as seen by guest */
3648 uint64_t refcount_bits;
3649 uint64_t l2_tables;
3650 size_t cluster_size;
3651 int version;
3652 char *optstr;
3653 PreallocMode prealloc;
3654 bool has_backing_file;
3656 /* Parse image creation options */
3657 cluster_size = qcow2_opt_get_cluster_size_del(opts, &local_err);
3658 if (local_err) {
3659 goto err;
3662 version = qcow2_opt_get_version_del(opts, &local_err);
3663 if (local_err) {
3664 goto err;
3667 refcount_bits = qcow2_opt_get_refcount_bits_del(opts, version, &local_err);
3668 if (local_err) {
3669 goto err;
3672 optstr = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
3673 prealloc = qapi_enum_parse(&PreallocMode_lookup, optstr,
3674 PREALLOC_MODE_OFF, &local_err);
3675 g_free(optstr);
3676 if (local_err) {
3677 goto err;
3680 optstr = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
3681 has_backing_file = !!optstr;
3682 g_free(optstr);
3684 virtual_size = align_offset(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
3685 cluster_size);
3687 /* Check that virtual disk size is valid */
3688 l2_tables = DIV_ROUND_UP(virtual_size / cluster_size,
3689 cluster_size / sizeof(uint64_t));
3690 if (l2_tables * sizeof(uint64_t) > QCOW_MAX_L1_SIZE) {
3691 error_setg(&local_err, "The image size is too large "
3692 "(try using a larger cluster size)");
3693 goto err;
3696 /* Account for input image */
3697 if (in_bs) {
3698 int64_t ssize = bdrv_getlength(in_bs);
3699 if (ssize < 0) {
3700 error_setg_errno(&local_err, -ssize,
3701 "Unable to get image virtual_size");
3702 goto err;
3705 virtual_size = align_offset(ssize, cluster_size);
3707 if (has_backing_file) {
3708 /* We don't how much of the backing chain is shared by the input
3709 * image and the new image file. In the worst case the new image's
3710 * backing file has nothing in common with the input image. Be
3711 * conservative and assume all clusters need to be written.
3713 required = virtual_size;
3714 } else {
3715 int64_t offset;
3716 int64_t pnum = 0;
3718 for (offset = 0; offset < ssize; offset += pnum) {
3719 int ret;
3721 ret = bdrv_block_status_above(in_bs, NULL, offset,
3722 ssize - offset, &pnum, NULL,
3723 NULL);
3724 if (ret < 0) {
3725 error_setg_errno(&local_err, -ret,
3726 "Unable to get block status");
3727 goto err;
3730 if (ret & BDRV_BLOCK_ZERO) {
3731 /* Skip zero regions (safe with no backing file) */
3732 } else if ((ret & (BDRV_BLOCK_DATA | BDRV_BLOCK_ALLOCATED)) ==
3733 (BDRV_BLOCK_DATA | BDRV_BLOCK_ALLOCATED)) {
3734 /* Extend pnum to end of cluster for next iteration */
3735 pnum = ROUND_UP(offset + pnum, cluster_size) - offset;
3737 /* Count clusters we've seen */
3738 required += offset % cluster_size + pnum;
3744 /* Take into account preallocation. Nothing special is needed for
3745 * PREALLOC_MODE_METADATA since metadata is always counted.
3747 if (prealloc == PREALLOC_MODE_FULL || prealloc == PREALLOC_MODE_FALLOC) {
3748 required = virtual_size;
3751 info = g_new(BlockMeasureInfo, 1);
3752 info->fully_allocated =
3753 qcow2_calc_prealloc_size(virtual_size, cluster_size,
3754 ctz32(refcount_bits));
3756 /* Remove data clusters that are not required. This overestimates the
3757 * required size because metadata needed for the fully allocated file is
3758 * still counted.
3760 info->required = info->fully_allocated - virtual_size + required;
3761 return info;
3763 err:
3764 error_propagate(errp, local_err);
3765 return NULL;
3768 static int qcow2_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
3770 BDRVQcow2State *s = bs->opaque;
3771 bdi->unallocated_blocks_are_zero = true;
3772 bdi->can_write_zeroes_with_unmap = (s->qcow_version >= 3);
3773 bdi->cluster_size = s->cluster_size;
3774 bdi->vm_state_offset = qcow2_vm_state_offset(s);
3775 return 0;
3778 static ImageInfoSpecific *qcow2_get_specific_info(BlockDriverState *bs)
3780 BDRVQcow2State *s = bs->opaque;
3781 ImageInfoSpecific *spec_info;
3782 QCryptoBlockInfo *encrypt_info = NULL;
3784 if (s->crypto != NULL) {
3785 encrypt_info = qcrypto_block_get_info(s->crypto, &error_abort);
3788 spec_info = g_new(ImageInfoSpecific, 1);
3789 *spec_info = (ImageInfoSpecific){
3790 .type = IMAGE_INFO_SPECIFIC_KIND_QCOW2,
3791 .u.qcow2.data = g_new(ImageInfoSpecificQCow2, 1),
3793 if (s->qcow_version == 2) {
3794 *spec_info->u.qcow2.data = (ImageInfoSpecificQCow2){
3795 .compat = g_strdup("0.10"),
3796 .refcount_bits = s->refcount_bits,
3798 } else if (s->qcow_version == 3) {
3799 *spec_info->u.qcow2.data = (ImageInfoSpecificQCow2){
3800 .compat = g_strdup("1.1"),
3801 .lazy_refcounts = s->compatible_features &
3802 QCOW2_COMPAT_LAZY_REFCOUNTS,
3803 .has_lazy_refcounts = true,
3804 .corrupt = s->incompatible_features &
3805 QCOW2_INCOMPAT_CORRUPT,
3806 .has_corrupt = true,
3807 .refcount_bits = s->refcount_bits,
3809 } else {
3810 /* if this assertion fails, this probably means a new version was
3811 * added without having it covered here */
3812 assert(false);
3815 if (encrypt_info) {
3816 ImageInfoSpecificQCow2Encryption *qencrypt =
3817 g_new(ImageInfoSpecificQCow2Encryption, 1);
3818 switch (encrypt_info->format) {
3819 case Q_CRYPTO_BLOCK_FORMAT_QCOW:
3820 qencrypt->format = BLOCKDEV_QCOW2_ENCRYPTION_FORMAT_AES;
3821 qencrypt->u.aes = encrypt_info->u.qcow;
3822 break;
3823 case Q_CRYPTO_BLOCK_FORMAT_LUKS:
3824 qencrypt->format = BLOCKDEV_QCOW2_ENCRYPTION_FORMAT_LUKS;
3825 qencrypt->u.luks = encrypt_info->u.luks;
3826 break;
3827 default:
3828 abort();
3830 /* Since we did shallow copy above, erase any pointers
3831 * in the original info */
3832 memset(&encrypt_info->u, 0, sizeof(encrypt_info->u));
3833 qapi_free_QCryptoBlockInfo(encrypt_info);
3835 spec_info->u.qcow2.data->has_encrypt = true;
3836 spec_info->u.qcow2.data->encrypt = qencrypt;
3839 return spec_info;
3842 static int qcow2_save_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
3843 int64_t pos)
3845 BDRVQcow2State *s = bs->opaque;
3847 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_SAVE);
3848 return bs->drv->bdrv_co_pwritev(bs, qcow2_vm_state_offset(s) + pos,
3849 qiov->size, qiov, 0);
3852 static int qcow2_load_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
3853 int64_t pos)
3855 BDRVQcow2State *s = bs->opaque;
3857 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_LOAD);
3858 return bs->drv->bdrv_co_preadv(bs, qcow2_vm_state_offset(s) + pos,
3859 qiov->size, qiov, 0);
3863 * Downgrades an image's version. To achieve this, any incompatible features
3864 * have to be removed.
3866 static int qcow2_downgrade(BlockDriverState *bs, int target_version,
3867 BlockDriverAmendStatusCB *status_cb, void *cb_opaque)
3869 BDRVQcow2State *s = bs->opaque;
3870 int current_version = s->qcow_version;
3871 int ret;
3873 if (target_version == current_version) {
3874 return 0;
3875 } else if (target_version > current_version) {
3876 return -EINVAL;
3877 } else if (target_version != 2) {
3878 return -EINVAL;
3881 if (s->refcount_order != 4) {
3882 error_report("compat=0.10 requires refcount_bits=16");
3883 return -ENOTSUP;
3886 /* clear incompatible features */
3887 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
3888 ret = qcow2_mark_clean(bs);
3889 if (ret < 0) {
3890 return ret;
3894 /* with QCOW2_INCOMPAT_CORRUPT, it is pretty much impossible to get here in
3895 * the first place; if that happens nonetheless, returning -ENOTSUP is the
3896 * best thing to do anyway */
3898 if (s->incompatible_features) {
3899 return -ENOTSUP;
3902 /* since we can ignore compatible features, we can set them to 0 as well */
3903 s->compatible_features = 0;
3904 /* if lazy refcounts have been used, they have already been fixed through
3905 * clearing the dirty flag */
3907 /* clearing autoclear features is trivial */
3908 s->autoclear_features = 0;
3910 ret = qcow2_expand_zero_clusters(bs, status_cb, cb_opaque);
3911 if (ret < 0) {
3912 return ret;
3915 s->qcow_version = target_version;
3916 ret = qcow2_update_header(bs);
3917 if (ret < 0) {
3918 s->qcow_version = current_version;
3919 return ret;
3921 return 0;
3924 typedef enum Qcow2AmendOperation {
3925 /* This is the value Qcow2AmendHelperCBInfo::last_operation will be
3926 * statically initialized to so that the helper CB can discern the first
3927 * invocation from an operation change */
3928 QCOW2_NO_OPERATION = 0,
3930 QCOW2_CHANGING_REFCOUNT_ORDER,
3931 QCOW2_DOWNGRADING,
3932 } Qcow2AmendOperation;
3934 typedef struct Qcow2AmendHelperCBInfo {
3935 /* The code coordinating the amend operations should only modify
3936 * these four fields; the rest will be managed by the CB */
3937 BlockDriverAmendStatusCB *original_status_cb;
3938 void *original_cb_opaque;
3940 Qcow2AmendOperation current_operation;
3942 /* Total number of operations to perform (only set once) */
3943 int total_operations;
3945 /* The following fields are managed by the CB */
3947 /* Number of operations completed */
3948 int operations_completed;
3950 /* Cumulative offset of all completed operations */
3951 int64_t offset_completed;
3953 Qcow2AmendOperation last_operation;
3954 int64_t last_work_size;
3955 } Qcow2AmendHelperCBInfo;
3957 static void qcow2_amend_helper_cb(BlockDriverState *bs,
3958 int64_t operation_offset,
3959 int64_t operation_work_size, void *opaque)
3961 Qcow2AmendHelperCBInfo *info = opaque;
3962 int64_t current_work_size;
3963 int64_t projected_work_size;
3965 if (info->current_operation != info->last_operation) {
3966 if (info->last_operation != QCOW2_NO_OPERATION) {
3967 info->offset_completed += info->last_work_size;
3968 info->operations_completed++;
3971 info->last_operation = info->current_operation;
3974 assert(info->total_operations > 0);
3975 assert(info->operations_completed < info->total_operations);
3977 info->last_work_size = operation_work_size;
3979 current_work_size = info->offset_completed + operation_work_size;
3981 /* current_work_size is the total work size for (operations_completed + 1)
3982 * operations (which includes this one), so multiply it by the number of
3983 * operations not covered and divide it by the number of operations
3984 * covered to get a projection for the operations not covered */
3985 projected_work_size = current_work_size * (info->total_operations -
3986 info->operations_completed - 1)
3987 / (info->operations_completed + 1);
3989 info->original_status_cb(bs, info->offset_completed + operation_offset,
3990 current_work_size + projected_work_size,
3991 info->original_cb_opaque);
3994 static int qcow2_amend_options(BlockDriverState *bs, QemuOpts *opts,
3995 BlockDriverAmendStatusCB *status_cb,
3996 void *cb_opaque)
3998 BDRVQcow2State *s = bs->opaque;
3999 int old_version = s->qcow_version, new_version = old_version;
4000 uint64_t new_size = 0;
4001 const char *backing_file = NULL, *backing_format = NULL;
4002 bool lazy_refcounts = s->use_lazy_refcounts;
4003 const char *compat = NULL;
4004 uint64_t cluster_size = s->cluster_size;
4005 bool encrypt;
4006 int encformat;
4007 int refcount_bits = s->refcount_bits;
4008 Error *local_err = NULL;
4009 int ret;
4010 QemuOptDesc *desc = opts->list->desc;
4011 Qcow2AmendHelperCBInfo helper_cb_info;
4013 while (desc && desc->name) {
4014 if (!qemu_opt_find(opts, desc->name)) {
4015 /* only change explicitly defined options */
4016 desc++;
4017 continue;
4020 if (!strcmp(desc->name, BLOCK_OPT_COMPAT_LEVEL)) {
4021 compat = qemu_opt_get(opts, BLOCK_OPT_COMPAT_LEVEL);
4022 if (!compat) {
4023 /* preserve default */
4024 } else if (!strcmp(compat, "0.10")) {
4025 new_version = 2;
4026 } else if (!strcmp(compat, "1.1")) {
4027 new_version = 3;
4028 } else {
4029 error_report("Unknown compatibility level %s", compat);
4030 return -EINVAL;
4032 } else if (!strcmp(desc->name, BLOCK_OPT_PREALLOC)) {
4033 error_report("Cannot change preallocation mode");
4034 return -ENOTSUP;
4035 } else if (!strcmp(desc->name, BLOCK_OPT_SIZE)) {
4036 new_size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, 0);
4037 } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FILE)) {
4038 backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
4039 } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FMT)) {
4040 backing_format = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
4041 } else if (!strcmp(desc->name, BLOCK_OPT_ENCRYPT)) {
4042 encrypt = qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT,
4043 !!s->crypto);
4045 if (encrypt != !!s->crypto) {
4046 error_report("Changing the encryption flag is not supported");
4047 return -ENOTSUP;
4049 } else if (!strcmp(desc->name, BLOCK_OPT_ENCRYPT_FORMAT)) {
4050 encformat = qcow2_crypt_method_from_format(
4051 qemu_opt_get(opts, BLOCK_OPT_ENCRYPT_FORMAT));
4053 if (encformat != s->crypt_method_header) {
4054 error_report("Changing the encryption format is not supported");
4055 return -ENOTSUP;
4057 } else if (g_str_has_prefix(desc->name, "encrypt.")) {
4058 error_report("Changing the encryption parameters is not supported");
4059 return -ENOTSUP;
4060 } else if (!strcmp(desc->name, BLOCK_OPT_CLUSTER_SIZE)) {
4061 cluster_size = qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE,
4062 cluster_size);
4063 if (cluster_size != s->cluster_size) {
4064 error_report("Changing the cluster size is not supported");
4065 return -ENOTSUP;
4067 } else if (!strcmp(desc->name, BLOCK_OPT_LAZY_REFCOUNTS)) {
4068 lazy_refcounts = qemu_opt_get_bool(opts, BLOCK_OPT_LAZY_REFCOUNTS,
4069 lazy_refcounts);
4070 } else if (!strcmp(desc->name, BLOCK_OPT_REFCOUNT_BITS)) {
4071 refcount_bits = qemu_opt_get_number(opts, BLOCK_OPT_REFCOUNT_BITS,
4072 refcount_bits);
4074 if (refcount_bits <= 0 || refcount_bits > 64 ||
4075 !is_power_of_2(refcount_bits))
4077 error_report("Refcount width must be a power of two and may "
4078 "not exceed 64 bits");
4079 return -EINVAL;
4081 } else {
4082 /* if this point is reached, this probably means a new option was
4083 * added without having it covered here */
4084 abort();
4087 desc++;
4090 helper_cb_info = (Qcow2AmendHelperCBInfo){
4091 .original_status_cb = status_cb,
4092 .original_cb_opaque = cb_opaque,
4093 .total_operations = (new_version < old_version)
4094 + (s->refcount_bits != refcount_bits)
4097 /* Upgrade first (some features may require compat=1.1) */
4098 if (new_version > old_version) {
4099 s->qcow_version = new_version;
4100 ret = qcow2_update_header(bs);
4101 if (ret < 0) {
4102 s->qcow_version = old_version;
4103 return ret;
4107 if (s->refcount_bits != refcount_bits) {
4108 int refcount_order = ctz32(refcount_bits);
4110 if (new_version < 3 && refcount_bits != 16) {
4111 error_report("Different refcount widths than 16 bits require "
4112 "compatibility level 1.1 or above (use compat=1.1 or "
4113 "greater)");
4114 return -EINVAL;
4117 helper_cb_info.current_operation = QCOW2_CHANGING_REFCOUNT_ORDER;
4118 ret = qcow2_change_refcount_order(bs, refcount_order,
4119 &qcow2_amend_helper_cb,
4120 &helper_cb_info, &local_err);
4121 if (ret < 0) {
4122 error_report_err(local_err);
4123 return ret;
4127 if (backing_file || backing_format) {
4128 ret = qcow2_change_backing_file(bs,
4129 backing_file ?: s->image_backing_file,
4130 backing_format ?: s->image_backing_format);
4131 if (ret < 0) {
4132 return ret;
4136 if (s->use_lazy_refcounts != lazy_refcounts) {
4137 if (lazy_refcounts) {
4138 if (new_version < 3) {
4139 error_report("Lazy refcounts only supported with compatibility "
4140 "level 1.1 and above (use compat=1.1 or greater)");
4141 return -EINVAL;
4143 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
4144 ret = qcow2_update_header(bs);
4145 if (ret < 0) {
4146 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
4147 return ret;
4149 s->use_lazy_refcounts = true;
4150 } else {
4151 /* make image clean first */
4152 ret = qcow2_mark_clean(bs);
4153 if (ret < 0) {
4154 return ret;
4156 /* now disallow lazy refcounts */
4157 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
4158 ret = qcow2_update_header(bs);
4159 if (ret < 0) {
4160 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
4161 return ret;
4163 s->use_lazy_refcounts = false;
4167 if (new_size) {
4168 BlockBackend *blk = blk_new(BLK_PERM_RESIZE, BLK_PERM_ALL);
4169 ret = blk_insert_bs(blk, bs, &local_err);
4170 if (ret < 0) {
4171 error_report_err(local_err);
4172 blk_unref(blk);
4173 return ret;
4176 ret = blk_truncate(blk, new_size, PREALLOC_MODE_OFF, &local_err);
4177 blk_unref(blk);
4178 if (ret < 0) {
4179 error_report_err(local_err);
4180 return ret;
4184 /* Downgrade last (so unsupported features can be removed before) */
4185 if (new_version < old_version) {
4186 helper_cb_info.current_operation = QCOW2_DOWNGRADING;
4187 ret = qcow2_downgrade(bs, new_version, &qcow2_amend_helper_cb,
4188 &helper_cb_info);
4189 if (ret < 0) {
4190 return ret;
4194 return 0;
4198 * If offset or size are negative, respectively, they will not be included in
4199 * the BLOCK_IMAGE_CORRUPTED event emitted.
4200 * fatal will be ignored for read-only BDS; corruptions found there will always
4201 * be considered non-fatal.
4203 void qcow2_signal_corruption(BlockDriverState *bs, bool fatal, int64_t offset,
4204 int64_t size, const char *message_format, ...)
4206 BDRVQcow2State *s = bs->opaque;
4207 const char *node_name;
4208 char *message;
4209 va_list ap;
4211 fatal = fatal && !bs->read_only;
4213 if (s->signaled_corruption &&
4214 (!fatal || (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT)))
4216 return;
4219 va_start(ap, message_format);
4220 message = g_strdup_vprintf(message_format, ap);
4221 va_end(ap);
4223 if (fatal) {
4224 fprintf(stderr, "qcow2: Marking image as corrupt: %s; further "
4225 "corruption events will be suppressed\n", message);
4226 } else {
4227 fprintf(stderr, "qcow2: Image is corrupt: %s; further non-fatal "
4228 "corruption events will be suppressed\n", message);
4231 node_name = bdrv_get_node_name(bs);
4232 qapi_event_send_block_image_corrupted(bdrv_get_device_name(bs),
4233 *node_name != '\0', node_name,
4234 message, offset >= 0, offset,
4235 size >= 0, size,
4236 fatal, &error_abort);
4237 g_free(message);
4239 if (fatal) {
4240 qcow2_mark_corrupt(bs);
4241 bs->drv = NULL; /* make BDS unusable */
4244 s->signaled_corruption = true;
4247 static QemuOptsList qcow2_create_opts = {
4248 .name = "qcow2-create-opts",
4249 .head = QTAILQ_HEAD_INITIALIZER(qcow2_create_opts.head),
4250 .desc = {
4252 .name = BLOCK_OPT_SIZE,
4253 .type = QEMU_OPT_SIZE,
4254 .help = "Virtual disk size"
4257 .name = BLOCK_OPT_COMPAT_LEVEL,
4258 .type = QEMU_OPT_STRING,
4259 .help = "Compatibility level (0.10 or 1.1)"
4262 .name = BLOCK_OPT_BACKING_FILE,
4263 .type = QEMU_OPT_STRING,
4264 .help = "File name of a base image"
4267 .name = BLOCK_OPT_BACKING_FMT,
4268 .type = QEMU_OPT_STRING,
4269 .help = "Image format of the base image"
4272 .name = BLOCK_OPT_ENCRYPT,
4273 .type = QEMU_OPT_BOOL,
4274 .help = "Encrypt the image with format 'aes'. (Deprecated "
4275 "in favor of " BLOCK_OPT_ENCRYPT_FORMAT "=aes)",
4278 .name = BLOCK_OPT_ENCRYPT_FORMAT,
4279 .type = QEMU_OPT_STRING,
4280 .help = "Encrypt the image, format choices: 'aes', 'luks'",
4282 BLOCK_CRYPTO_OPT_DEF_KEY_SECRET("encrypt.",
4283 "ID of secret providing qcow AES key or LUKS passphrase"),
4284 BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_ALG("encrypt."),
4285 BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_MODE("encrypt."),
4286 BLOCK_CRYPTO_OPT_DEF_LUKS_IVGEN_ALG("encrypt."),
4287 BLOCK_CRYPTO_OPT_DEF_LUKS_IVGEN_HASH_ALG("encrypt."),
4288 BLOCK_CRYPTO_OPT_DEF_LUKS_HASH_ALG("encrypt."),
4289 BLOCK_CRYPTO_OPT_DEF_LUKS_ITER_TIME("encrypt."),
4291 .name = BLOCK_OPT_CLUSTER_SIZE,
4292 .type = QEMU_OPT_SIZE,
4293 .help = "qcow2 cluster size",
4294 .def_value_str = stringify(DEFAULT_CLUSTER_SIZE)
4297 .name = BLOCK_OPT_PREALLOC,
4298 .type = QEMU_OPT_STRING,
4299 .help = "Preallocation mode (allowed values: off, metadata, "
4300 "falloc, full)"
4303 .name = BLOCK_OPT_LAZY_REFCOUNTS,
4304 .type = QEMU_OPT_BOOL,
4305 .help = "Postpone refcount updates",
4306 .def_value_str = "off"
4309 .name = BLOCK_OPT_REFCOUNT_BITS,
4310 .type = QEMU_OPT_NUMBER,
4311 .help = "Width of a reference count entry in bits",
4312 .def_value_str = "16"
4314 { /* end of list */ }
4318 BlockDriver bdrv_qcow2 = {
4319 .format_name = "qcow2",
4320 .instance_size = sizeof(BDRVQcow2State),
4321 .bdrv_probe = qcow2_probe,
4322 .bdrv_open = qcow2_open,
4323 .bdrv_close = qcow2_close,
4324 .bdrv_reopen_prepare = qcow2_reopen_prepare,
4325 .bdrv_reopen_commit = qcow2_reopen_commit,
4326 .bdrv_reopen_abort = qcow2_reopen_abort,
4327 .bdrv_join_options = qcow2_join_options,
4328 .bdrv_child_perm = bdrv_format_default_perms,
4329 .bdrv_create = qcow2_create,
4330 .bdrv_has_zero_init = bdrv_has_zero_init_1,
4331 .bdrv_co_get_block_status = qcow2_co_get_block_status,
4333 .bdrv_co_preadv = qcow2_co_preadv,
4334 .bdrv_co_pwritev = qcow2_co_pwritev,
4335 .bdrv_co_flush_to_os = qcow2_co_flush_to_os,
4337 .bdrv_co_pwrite_zeroes = qcow2_co_pwrite_zeroes,
4338 .bdrv_co_pdiscard = qcow2_co_pdiscard,
4339 .bdrv_truncate = qcow2_truncate,
4340 .bdrv_co_pwritev_compressed = qcow2_co_pwritev_compressed,
4341 .bdrv_make_empty = qcow2_make_empty,
4343 .bdrv_snapshot_create = qcow2_snapshot_create,
4344 .bdrv_snapshot_goto = qcow2_snapshot_goto,
4345 .bdrv_snapshot_delete = qcow2_snapshot_delete,
4346 .bdrv_snapshot_list = qcow2_snapshot_list,
4347 .bdrv_snapshot_load_tmp = qcow2_snapshot_load_tmp,
4348 .bdrv_measure = qcow2_measure,
4349 .bdrv_get_info = qcow2_get_info,
4350 .bdrv_get_specific_info = qcow2_get_specific_info,
4352 .bdrv_save_vmstate = qcow2_save_vmstate,
4353 .bdrv_load_vmstate = qcow2_load_vmstate,
4355 .supports_backing = true,
4356 .bdrv_change_backing_file = qcow2_change_backing_file,
4358 .bdrv_refresh_limits = qcow2_refresh_limits,
4359 .bdrv_invalidate_cache = qcow2_invalidate_cache,
4360 .bdrv_inactivate = qcow2_inactivate,
4362 .create_opts = &qcow2_create_opts,
4363 .bdrv_check = qcow2_check,
4364 .bdrv_amend_options = qcow2_amend_options,
4366 .bdrv_detach_aio_context = qcow2_detach_aio_context,
4367 .bdrv_attach_aio_context = qcow2_attach_aio_context,
4369 .bdrv_reopen_bitmaps_rw = qcow2_reopen_bitmaps_rw,
4370 .bdrv_can_store_new_dirty_bitmap = qcow2_can_store_new_dirty_bitmap,
4371 .bdrv_remove_persistent_dirty_bitmap = qcow2_remove_persistent_dirty_bitmap,
4374 static void bdrv_qcow2_init(void)
4376 bdrv_register(&bdrv_qcow2);
4379 block_init(bdrv_qcow2_init);