qcow2: Check snapshot L1 table in qcow2_snapshot_goto()
[qemu/ar7.git] / block / qcow2.c
blob369e374a9b0445cf53abc35bf8af231492ec01f7
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.
25 #include "qemu/osdep.h"
26 #include "block/block_int.h"
27 #include "sysemu/block-backend.h"
28 #include "qemu/module.h"
29 #include <zlib.h>
30 #include "block/qcow2.h"
31 #include "qemu/error-report.h"
32 #include "qapi/error.h"
33 #include "qapi/qapi-events-block-core.h"
34 #include "qapi/qmp/qdict.h"
35 #include "qapi/qmp/qstring.h"
36 #include "trace.h"
37 #include "qemu/option_int.h"
38 #include "qemu/cutils.h"
39 #include "qemu/bswap.h"
40 #include "qapi/opts-visitor.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 = qcow2_flush_caches(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 = qcow2_flush_caches(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 coroutine_fn qcow2_co_check_locked(BlockDriverState *bs,
545 BdrvCheckResult *result,
546 BdrvCheckMode fix)
548 int ret = qcow2_check_refcounts(bs, result, fix);
549 if (ret < 0) {
550 return ret;
553 if (fix && result->check_errors == 0 && result->corruptions == 0) {
554 ret = qcow2_mark_clean(bs);
555 if (ret < 0) {
556 return ret;
558 return qcow2_mark_consistent(bs);
560 return ret;
563 static int coroutine_fn qcow2_co_check(BlockDriverState *bs,
564 BdrvCheckResult *result,
565 BdrvCheckMode fix)
567 BDRVQcow2State *s = bs->opaque;
568 int ret;
570 qemu_co_mutex_lock(&s->lock);
571 ret = qcow2_co_check_locked(bs, result, fix);
572 qemu_co_mutex_unlock(&s->lock);
573 return ret;
576 int qcow2_validate_table(BlockDriverState *bs, uint64_t offset,
577 uint64_t entries, size_t entry_len,
578 int64_t max_size_bytes, const char *table_name,
579 Error **errp)
581 BDRVQcow2State *s = bs->opaque;
583 if (entries > max_size_bytes / entry_len) {
584 error_setg(errp, "%s too large", table_name);
585 return -EFBIG;
588 /* Use signed INT64_MAX as the maximum even for uint64_t header fields,
589 * because values will be passed to qemu functions taking int64_t. */
590 if ((INT64_MAX - entries * entry_len < offset) ||
591 (offset_into_cluster(s, offset) != 0)) {
592 error_setg(errp, "%s offset invalid", table_name);
593 return -EINVAL;
596 return 0;
599 static QemuOptsList qcow2_runtime_opts = {
600 .name = "qcow2",
601 .head = QTAILQ_HEAD_INITIALIZER(qcow2_runtime_opts.head),
602 .desc = {
604 .name = QCOW2_OPT_LAZY_REFCOUNTS,
605 .type = QEMU_OPT_BOOL,
606 .help = "Postpone refcount updates",
609 .name = QCOW2_OPT_DISCARD_REQUEST,
610 .type = QEMU_OPT_BOOL,
611 .help = "Pass guest discard requests to the layer below",
614 .name = QCOW2_OPT_DISCARD_SNAPSHOT,
615 .type = QEMU_OPT_BOOL,
616 .help = "Generate discard requests when snapshot related space "
617 "is freed",
620 .name = QCOW2_OPT_DISCARD_OTHER,
621 .type = QEMU_OPT_BOOL,
622 .help = "Generate discard requests when other clusters are freed",
625 .name = QCOW2_OPT_OVERLAP,
626 .type = QEMU_OPT_STRING,
627 .help = "Selects which overlap checks to perform from a range of "
628 "templates (none, constant, cached, all)",
631 .name = QCOW2_OPT_OVERLAP_TEMPLATE,
632 .type = QEMU_OPT_STRING,
633 .help = "Selects which overlap checks to perform from a range of "
634 "templates (none, constant, cached, all)",
637 .name = QCOW2_OPT_OVERLAP_MAIN_HEADER,
638 .type = QEMU_OPT_BOOL,
639 .help = "Check for unintended writes into the main qcow2 header",
642 .name = QCOW2_OPT_OVERLAP_ACTIVE_L1,
643 .type = QEMU_OPT_BOOL,
644 .help = "Check for unintended writes into the active L1 table",
647 .name = QCOW2_OPT_OVERLAP_ACTIVE_L2,
648 .type = QEMU_OPT_BOOL,
649 .help = "Check for unintended writes into an active L2 table",
652 .name = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
653 .type = QEMU_OPT_BOOL,
654 .help = "Check for unintended writes into the refcount table",
657 .name = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
658 .type = QEMU_OPT_BOOL,
659 .help = "Check for unintended writes into a refcount block",
662 .name = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
663 .type = QEMU_OPT_BOOL,
664 .help = "Check for unintended writes into the snapshot table",
667 .name = QCOW2_OPT_OVERLAP_INACTIVE_L1,
668 .type = QEMU_OPT_BOOL,
669 .help = "Check for unintended writes into an inactive L1 table",
672 .name = QCOW2_OPT_OVERLAP_INACTIVE_L2,
673 .type = QEMU_OPT_BOOL,
674 .help = "Check for unintended writes into an inactive L2 table",
677 .name = QCOW2_OPT_CACHE_SIZE,
678 .type = QEMU_OPT_SIZE,
679 .help = "Maximum combined metadata (L2 tables and refcount blocks) "
680 "cache size",
683 .name = QCOW2_OPT_L2_CACHE_SIZE,
684 .type = QEMU_OPT_SIZE,
685 .help = "Maximum L2 table cache size",
688 .name = QCOW2_OPT_L2_CACHE_ENTRY_SIZE,
689 .type = QEMU_OPT_SIZE,
690 .help = "Size of each entry in the L2 cache",
693 .name = QCOW2_OPT_REFCOUNT_CACHE_SIZE,
694 .type = QEMU_OPT_SIZE,
695 .help = "Maximum refcount block cache size",
698 .name = QCOW2_OPT_CACHE_CLEAN_INTERVAL,
699 .type = QEMU_OPT_NUMBER,
700 .help = "Clean unused cache entries after this time (in seconds)",
702 BLOCK_CRYPTO_OPT_DEF_KEY_SECRET("encrypt.",
703 "ID of secret providing qcow2 AES key or LUKS passphrase"),
704 { /* end of list */ }
708 static const char *overlap_bool_option_names[QCOW2_OL_MAX_BITNR] = {
709 [QCOW2_OL_MAIN_HEADER_BITNR] = QCOW2_OPT_OVERLAP_MAIN_HEADER,
710 [QCOW2_OL_ACTIVE_L1_BITNR] = QCOW2_OPT_OVERLAP_ACTIVE_L1,
711 [QCOW2_OL_ACTIVE_L2_BITNR] = QCOW2_OPT_OVERLAP_ACTIVE_L2,
712 [QCOW2_OL_REFCOUNT_TABLE_BITNR] = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
713 [QCOW2_OL_REFCOUNT_BLOCK_BITNR] = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
714 [QCOW2_OL_SNAPSHOT_TABLE_BITNR] = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
715 [QCOW2_OL_INACTIVE_L1_BITNR] = QCOW2_OPT_OVERLAP_INACTIVE_L1,
716 [QCOW2_OL_INACTIVE_L2_BITNR] = QCOW2_OPT_OVERLAP_INACTIVE_L2,
719 static void cache_clean_timer_cb(void *opaque)
721 BlockDriverState *bs = opaque;
722 BDRVQcow2State *s = bs->opaque;
723 qcow2_cache_clean_unused(s->l2_table_cache);
724 qcow2_cache_clean_unused(s->refcount_block_cache);
725 timer_mod(s->cache_clean_timer, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) +
726 (int64_t) s->cache_clean_interval * 1000);
729 static void cache_clean_timer_init(BlockDriverState *bs, AioContext *context)
731 BDRVQcow2State *s = bs->opaque;
732 if (s->cache_clean_interval > 0) {
733 s->cache_clean_timer = aio_timer_new(context, QEMU_CLOCK_VIRTUAL,
734 SCALE_MS, cache_clean_timer_cb,
735 bs);
736 timer_mod(s->cache_clean_timer, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) +
737 (int64_t) s->cache_clean_interval * 1000);
741 static void cache_clean_timer_del(BlockDriverState *bs)
743 BDRVQcow2State *s = bs->opaque;
744 if (s->cache_clean_timer) {
745 timer_del(s->cache_clean_timer);
746 timer_free(s->cache_clean_timer);
747 s->cache_clean_timer = NULL;
751 static void qcow2_detach_aio_context(BlockDriverState *bs)
753 cache_clean_timer_del(bs);
756 static void qcow2_attach_aio_context(BlockDriverState *bs,
757 AioContext *new_context)
759 cache_clean_timer_init(bs, new_context);
762 static void read_cache_sizes(BlockDriverState *bs, QemuOpts *opts,
763 uint64_t *l2_cache_size,
764 uint64_t *l2_cache_entry_size,
765 uint64_t *refcount_cache_size, Error **errp)
767 BDRVQcow2State *s = bs->opaque;
768 uint64_t combined_cache_size;
769 bool l2_cache_size_set, refcount_cache_size_set, combined_cache_size_set;
771 combined_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_CACHE_SIZE);
772 l2_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_L2_CACHE_SIZE);
773 refcount_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
775 combined_cache_size = qemu_opt_get_size(opts, QCOW2_OPT_CACHE_SIZE, 0);
776 *l2_cache_size = qemu_opt_get_size(opts, QCOW2_OPT_L2_CACHE_SIZE, 0);
777 *refcount_cache_size = qemu_opt_get_size(opts,
778 QCOW2_OPT_REFCOUNT_CACHE_SIZE, 0);
780 *l2_cache_entry_size = qemu_opt_get_size(
781 opts, QCOW2_OPT_L2_CACHE_ENTRY_SIZE, s->cluster_size);
783 if (combined_cache_size_set) {
784 if (l2_cache_size_set && refcount_cache_size_set) {
785 error_setg(errp, QCOW2_OPT_CACHE_SIZE ", " QCOW2_OPT_L2_CACHE_SIZE
786 " and " QCOW2_OPT_REFCOUNT_CACHE_SIZE " may not be set "
787 "the same time");
788 return;
789 } else if (*l2_cache_size > combined_cache_size) {
790 error_setg(errp, QCOW2_OPT_L2_CACHE_SIZE " may not exceed "
791 QCOW2_OPT_CACHE_SIZE);
792 return;
793 } else if (*refcount_cache_size > combined_cache_size) {
794 error_setg(errp, QCOW2_OPT_REFCOUNT_CACHE_SIZE " may not exceed "
795 QCOW2_OPT_CACHE_SIZE);
796 return;
799 if (l2_cache_size_set) {
800 *refcount_cache_size = combined_cache_size - *l2_cache_size;
801 } else if (refcount_cache_size_set) {
802 *l2_cache_size = combined_cache_size - *refcount_cache_size;
803 } else {
804 *refcount_cache_size = combined_cache_size
805 / (DEFAULT_L2_REFCOUNT_SIZE_RATIO + 1);
806 *l2_cache_size = combined_cache_size - *refcount_cache_size;
808 } else {
809 if (!l2_cache_size_set && !refcount_cache_size_set) {
810 *l2_cache_size = MAX(DEFAULT_L2_CACHE_BYTE_SIZE,
811 (uint64_t)DEFAULT_L2_CACHE_CLUSTERS
812 * s->cluster_size);
813 *refcount_cache_size = *l2_cache_size
814 / DEFAULT_L2_REFCOUNT_SIZE_RATIO;
815 } else if (!l2_cache_size_set) {
816 *l2_cache_size = *refcount_cache_size
817 * DEFAULT_L2_REFCOUNT_SIZE_RATIO;
818 } else if (!refcount_cache_size_set) {
819 *refcount_cache_size = *l2_cache_size
820 / DEFAULT_L2_REFCOUNT_SIZE_RATIO;
824 if (*l2_cache_entry_size < (1 << MIN_CLUSTER_BITS) ||
825 *l2_cache_entry_size > s->cluster_size ||
826 !is_power_of_2(*l2_cache_entry_size)) {
827 error_setg(errp, "L2 cache entry size must be a power of two "
828 "between %d and the cluster size (%d)",
829 1 << MIN_CLUSTER_BITS, s->cluster_size);
830 return;
834 typedef struct Qcow2ReopenState {
835 Qcow2Cache *l2_table_cache;
836 Qcow2Cache *refcount_block_cache;
837 int l2_slice_size; /* Number of entries in a slice of the L2 table */
838 bool use_lazy_refcounts;
839 int overlap_check;
840 bool discard_passthrough[QCOW2_DISCARD_MAX];
841 uint64_t cache_clean_interval;
842 QCryptoBlockOpenOptions *crypto_opts; /* Disk encryption runtime options */
843 } Qcow2ReopenState;
845 static int qcow2_update_options_prepare(BlockDriverState *bs,
846 Qcow2ReopenState *r,
847 QDict *options, int flags,
848 Error **errp)
850 BDRVQcow2State *s = bs->opaque;
851 QemuOpts *opts = NULL;
852 const char *opt_overlap_check, *opt_overlap_check_template;
853 int overlap_check_template = 0;
854 uint64_t l2_cache_size, l2_cache_entry_size, refcount_cache_size;
855 int i;
856 const char *encryptfmt;
857 QDict *encryptopts = NULL;
858 Error *local_err = NULL;
859 int ret;
861 qdict_extract_subqdict(options, &encryptopts, "encrypt.");
862 encryptfmt = qdict_get_try_str(encryptopts, "format");
864 opts = qemu_opts_create(&qcow2_runtime_opts, NULL, 0, &error_abort);
865 qemu_opts_absorb_qdict(opts, options, &local_err);
866 if (local_err) {
867 error_propagate(errp, local_err);
868 ret = -EINVAL;
869 goto fail;
872 /* get L2 table/refcount block cache size from command line options */
873 read_cache_sizes(bs, opts, &l2_cache_size, &l2_cache_entry_size,
874 &refcount_cache_size, &local_err);
875 if (local_err) {
876 error_propagate(errp, local_err);
877 ret = -EINVAL;
878 goto fail;
881 l2_cache_size /= l2_cache_entry_size;
882 if (l2_cache_size < MIN_L2_CACHE_SIZE) {
883 l2_cache_size = MIN_L2_CACHE_SIZE;
885 if (l2_cache_size > INT_MAX) {
886 error_setg(errp, "L2 cache size too big");
887 ret = -EINVAL;
888 goto fail;
891 refcount_cache_size /= s->cluster_size;
892 if (refcount_cache_size < MIN_REFCOUNT_CACHE_SIZE) {
893 refcount_cache_size = MIN_REFCOUNT_CACHE_SIZE;
895 if (refcount_cache_size > INT_MAX) {
896 error_setg(errp, "Refcount cache size too big");
897 ret = -EINVAL;
898 goto fail;
901 /* alloc new L2 table/refcount block cache, flush old one */
902 if (s->l2_table_cache) {
903 ret = qcow2_cache_flush(bs, s->l2_table_cache);
904 if (ret) {
905 error_setg_errno(errp, -ret, "Failed to flush the L2 table cache");
906 goto fail;
910 if (s->refcount_block_cache) {
911 ret = qcow2_cache_flush(bs, s->refcount_block_cache);
912 if (ret) {
913 error_setg_errno(errp, -ret,
914 "Failed to flush the refcount block cache");
915 goto fail;
919 r->l2_slice_size = l2_cache_entry_size / sizeof(uint64_t);
920 r->l2_table_cache = qcow2_cache_create(bs, l2_cache_size,
921 l2_cache_entry_size);
922 r->refcount_block_cache = qcow2_cache_create(bs, refcount_cache_size,
923 s->cluster_size);
924 if (r->l2_table_cache == NULL || r->refcount_block_cache == NULL) {
925 error_setg(errp, "Could not allocate metadata caches");
926 ret = -ENOMEM;
927 goto fail;
930 /* New interval for cache cleanup timer */
931 r->cache_clean_interval =
932 qemu_opt_get_number(opts, QCOW2_OPT_CACHE_CLEAN_INTERVAL,
933 s->cache_clean_interval);
934 #ifndef CONFIG_LINUX
935 if (r->cache_clean_interval != 0) {
936 error_setg(errp, QCOW2_OPT_CACHE_CLEAN_INTERVAL
937 " not supported on this host");
938 ret = -EINVAL;
939 goto fail;
941 #endif
942 if (r->cache_clean_interval > UINT_MAX) {
943 error_setg(errp, "Cache clean interval too big");
944 ret = -EINVAL;
945 goto fail;
948 /* lazy-refcounts; flush if going from enabled to disabled */
949 r->use_lazy_refcounts = qemu_opt_get_bool(opts, QCOW2_OPT_LAZY_REFCOUNTS,
950 (s->compatible_features & QCOW2_COMPAT_LAZY_REFCOUNTS));
951 if (r->use_lazy_refcounts && s->qcow_version < 3) {
952 error_setg(errp, "Lazy refcounts require a qcow2 image with at least "
953 "qemu 1.1 compatibility level");
954 ret = -EINVAL;
955 goto fail;
958 if (s->use_lazy_refcounts && !r->use_lazy_refcounts) {
959 ret = qcow2_mark_clean(bs);
960 if (ret < 0) {
961 error_setg_errno(errp, -ret, "Failed to disable lazy refcounts");
962 goto fail;
966 /* Overlap check options */
967 opt_overlap_check = qemu_opt_get(opts, QCOW2_OPT_OVERLAP);
968 opt_overlap_check_template = qemu_opt_get(opts, QCOW2_OPT_OVERLAP_TEMPLATE);
969 if (opt_overlap_check_template && opt_overlap_check &&
970 strcmp(opt_overlap_check_template, opt_overlap_check))
972 error_setg(errp, "Conflicting values for qcow2 options '"
973 QCOW2_OPT_OVERLAP "' ('%s') and '" QCOW2_OPT_OVERLAP_TEMPLATE
974 "' ('%s')", opt_overlap_check, opt_overlap_check_template);
975 ret = -EINVAL;
976 goto fail;
978 if (!opt_overlap_check) {
979 opt_overlap_check = opt_overlap_check_template ?: "cached";
982 if (!strcmp(opt_overlap_check, "none")) {
983 overlap_check_template = 0;
984 } else if (!strcmp(opt_overlap_check, "constant")) {
985 overlap_check_template = QCOW2_OL_CONSTANT;
986 } else if (!strcmp(opt_overlap_check, "cached")) {
987 overlap_check_template = QCOW2_OL_CACHED;
988 } else if (!strcmp(opt_overlap_check, "all")) {
989 overlap_check_template = QCOW2_OL_ALL;
990 } else {
991 error_setg(errp, "Unsupported value '%s' for qcow2 option "
992 "'overlap-check'. Allowed are any of the following: "
993 "none, constant, cached, all", opt_overlap_check);
994 ret = -EINVAL;
995 goto fail;
998 r->overlap_check = 0;
999 for (i = 0; i < QCOW2_OL_MAX_BITNR; i++) {
1000 /* overlap-check defines a template bitmask, but every flag may be
1001 * overwritten through the associated boolean option */
1002 r->overlap_check |=
1003 qemu_opt_get_bool(opts, overlap_bool_option_names[i],
1004 overlap_check_template & (1 << i)) << i;
1007 r->discard_passthrough[QCOW2_DISCARD_NEVER] = false;
1008 r->discard_passthrough[QCOW2_DISCARD_ALWAYS] = true;
1009 r->discard_passthrough[QCOW2_DISCARD_REQUEST] =
1010 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_REQUEST,
1011 flags & BDRV_O_UNMAP);
1012 r->discard_passthrough[QCOW2_DISCARD_SNAPSHOT] =
1013 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_SNAPSHOT, true);
1014 r->discard_passthrough[QCOW2_DISCARD_OTHER] =
1015 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_OTHER, false);
1017 switch (s->crypt_method_header) {
1018 case QCOW_CRYPT_NONE:
1019 if (encryptfmt) {
1020 error_setg(errp, "No encryption in image header, but options "
1021 "specified format '%s'", encryptfmt);
1022 ret = -EINVAL;
1023 goto fail;
1025 break;
1027 case QCOW_CRYPT_AES:
1028 if (encryptfmt && !g_str_equal(encryptfmt, "aes")) {
1029 error_setg(errp,
1030 "Header reported 'aes' encryption format but "
1031 "options specify '%s'", encryptfmt);
1032 ret = -EINVAL;
1033 goto fail;
1035 qdict_del(encryptopts, "format");
1036 r->crypto_opts = block_crypto_open_opts_init(
1037 Q_CRYPTO_BLOCK_FORMAT_QCOW, encryptopts, errp);
1038 break;
1040 case QCOW_CRYPT_LUKS:
1041 if (encryptfmt && !g_str_equal(encryptfmt, "luks")) {
1042 error_setg(errp,
1043 "Header reported 'luks' encryption format but "
1044 "options specify '%s'", encryptfmt);
1045 ret = -EINVAL;
1046 goto fail;
1048 qdict_del(encryptopts, "format");
1049 r->crypto_opts = block_crypto_open_opts_init(
1050 Q_CRYPTO_BLOCK_FORMAT_LUKS, encryptopts, errp);
1051 break;
1053 default:
1054 error_setg(errp, "Unsupported encryption method %d",
1055 s->crypt_method_header);
1056 break;
1058 if (s->crypt_method_header != QCOW_CRYPT_NONE && !r->crypto_opts) {
1059 ret = -EINVAL;
1060 goto fail;
1063 ret = 0;
1064 fail:
1065 QDECREF(encryptopts);
1066 qemu_opts_del(opts);
1067 opts = NULL;
1068 return ret;
1071 static void qcow2_update_options_commit(BlockDriverState *bs,
1072 Qcow2ReopenState *r)
1074 BDRVQcow2State *s = bs->opaque;
1075 int i;
1077 if (s->l2_table_cache) {
1078 qcow2_cache_destroy(s->l2_table_cache);
1080 if (s->refcount_block_cache) {
1081 qcow2_cache_destroy(s->refcount_block_cache);
1083 s->l2_table_cache = r->l2_table_cache;
1084 s->refcount_block_cache = r->refcount_block_cache;
1085 s->l2_slice_size = r->l2_slice_size;
1087 s->overlap_check = r->overlap_check;
1088 s->use_lazy_refcounts = r->use_lazy_refcounts;
1090 for (i = 0; i < QCOW2_DISCARD_MAX; i++) {
1091 s->discard_passthrough[i] = r->discard_passthrough[i];
1094 if (s->cache_clean_interval != r->cache_clean_interval) {
1095 cache_clean_timer_del(bs);
1096 s->cache_clean_interval = r->cache_clean_interval;
1097 cache_clean_timer_init(bs, bdrv_get_aio_context(bs));
1100 qapi_free_QCryptoBlockOpenOptions(s->crypto_opts);
1101 s->crypto_opts = r->crypto_opts;
1104 static void qcow2_update_options_abort(BlockDriverState *bs,
1105 Qcow2ReopenState *r)
1107 if (r->l2_table_cache) {
1108 qcow2_cache_destroy(r->l2_table_cache);
1110 if (r->refcount_block_cache) {
1111 qcow2_cache_destroy(r->refcount_block_cache);
1113 qapi_free_QCryptoBlockOpenOptions(r->crypto_opts);
1116 static int qcow2_update_options(BlockDriverState *bs, QDict *options,
1117 int flags, Error **errp)
1119 Qcow2ReopenState r = {};
1120 int ret;
1122 ret = qcow2_update_options_prepare(bs, &r, options, flags, errp);
1123 if (ret >= 0) {
1124 qcow2_update_options_commit(bs, &r);
1125 } else {
1126 qcow2_update_options_abort(bs, &r);
1129 return ret;
1132 /* Called with s->lock held. */
1133 static int coroutine_fn qcow2_do_open(BlockDriverState *bs, QDict *options,
1134 int flags, Error **errp)
1136 BDRVQcow2State *s = bs->opaque;
1137 unsigned int len, i;
1138 int ret = 0;
1139 QCowHeader header;
1140 Error *local_err = NULL;
1141 uint64_t ext_end;
1142 uint64_t l1_vm_state_index;
1143 bool update_header = false;
1145 ret = bdrv_pread(bs->file, 0, &header, sizeof(header));
1146 if (ret < 0) {
1147 error_setg_errno(errp, -ret, "Could not read qcow2 header");
1148 goto fail;
1150 be32_to_cpus(&header.magic);
1151 be32_to_cpus(&header.version);
1152 be64_to_cpus(&header.backing_file_offset);
1153 be32_to_cpus(&header.backing_file_size);
1154 be64_to_cpus(&header.size);
1155 be32_to_cpus(&header.cluster_bits);
1156 be32_to_cpus(&header.crypt_method);
1157 be64_to_cpus(&header.l1_table_offset);
1158 be32_to_cpus(&header.l1_size);
1159 be64_to_cpus(&header.refcount_table_offset);
1160 be32_to_cpus(&header.refcount_table_clusters);
1161 be64_to_cpus(&header.snapshots_offset);
1162 be32_to_cpus(&header.nb_snapshots);
1164 if (header.magic != QCOW_MAGIC) {
1165 error_setg(errp, "Image is not in qcow2 format");
1166 ret = -EINVAL;
1167 goto fail;
1169 if (header.version < 2 || header.version > 3) {
1170 error_setg(errp, "Unsupported qcow2 version %" PRIu32, header.version);
1171 ret = -ENOTSUP;
1172 goto fail;
1175 s->qcow_version = header.version;
1177 /* Initialise cluster size */
1178 if (header.cluster_bits < MIN_CLUSTER_BITS ||
1179 header.cluster_bits > MAX_CLUSTER_BITS) {
1180 error_setg(errp, "Unsupported cluster size: 2^%" PRIu32,
1181 header.cluster_bits);
1182 ret = -EINVAL;
1183 goto fail;
1186 s->cluster_bits = header.cluster_bits;
1187 s->cluster_size = 1 << s->cluster_bits;
1188 s->cluster_sectors = 1 << (s->cluster_bits - BDRV_SECTOR_BITS);
1190 /* Initialise version 3 header fields */
1191 if (header.version == 2) {
1192 header.incompatible_features = 0;
1193 header.compatible_features = 0;
1194 header.autoclear_features = 0;
1195 header.refcount_order = 4;
1196 header.header_length = 72;
1197 } else {
1198 be64_to_cpus(&header.incompatible_features);
1199 be64_to_cpus(&header.compatible_features);
1200 be64_to_cpus(&header.autoclear_features);
1201 be32_to_cpus(&header.refcount_order);
1202 be32_to_cpus(&header.header_length);
1204 if (header.header_length < 104) {
1205 error_setg(errp, "qcow2 header too short");
1206 ret = -EINVAL;
1207 goto fail;
1211 if (header.header_length > s->cluster_size) {
1212 error_setg(errp, "qcow2 header exceeds cluster size");
1213 ret = -EINVAL;
1214 goto fail;
1217 if (header.header_length > sizeof(header)) {
1218 s->unknown_header_fields_size = header.header_length - sizeof(header);
1219 s->unknown_header_fields = g_malloc(s->unknown_header_fields_size);
1220 ret = bdrv_pread(bs->file, sizeof(header), s->unknown_header_fields,
1221 s->unknown_header_fields_size);
1222 if (ret < 0) {
1223 error_setg_errno(errp, -ret, "Could not read unknown qcow2 header "
1224 "fields");
1225 goto fail;
1229 if (header.backing_file_offset > s->cluster_size) {
1230 error_setg(errp, "Invalid backing file offset");
1231 ret = -EINVAL;
1232 goto fail;
1235 if (header.backing_file_offset) {
1236 ext_end = header.backing_file_offset;
1237 } else {
1238 ext_end = 1 << header.cluster_bits;
1241 /* Handle feature bits */
1242 s->incompatible_features = header.incompatible_features;
1243 s->compatible_features = header.compatible_features;
1244 s->autoclear_features = header.autoclear_features;
1246 if (s->incompatible_features & ~QCOW2_INCOMPAT_MASK) {
1247 void *feature_table = NULL;
1248 qcow2_read_extensions(bs, header.header_length, ext_end,
1249 &feature_table, flags, NULL, NULL);
1250 report_unsupported_feature(errp, feature_table,
1251 s->incompatible_features &
1252 ~QCOW2_INCOMPAT_MASK);
1253 ret = -ENOTSUP;
1254 g_free(feature_table);
1255 goto fail;
1258 if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
1259 /* Corrupt images may not be written to unless they are being repaired
1261 if ((flags & BDRV_O_RDWR) && !(flags & BDRV_O_CHECK)) {
1262 error_setg(errp, "qcow2: Image is corrupt; cannot be opened "
1263 "read/write");
1264 ret = -EACCES;
1265 goto fail;
1269 /* Check support for various header values */
1270 if (header.refcount_order > 6) {
1271 error_setg(errp, "Reference count entry width too large; may not "
1272 "exceed 64 bits");
1273 ret = -EINVAL;
1274 goto fail;
1276 s->refcount_order = header.refcount_order;
1277 s->refcount_bits = 1 << s->refcount_order;
1278 s->refcount_max = UINT64_C(1) << (s->refcount_bits - 1);
1279 s->refcount_max += s->refcount_max - 1;
1281 s->crypt_method_header = header.crypt_method;
1282 if (s->crypt_method_header) {
1283 if (bdrv_uses_whitelist() &&
1284 s->crypt_method_header == QCOW_CRYPT_AES) {
1285 error_setg(errp,
1286 "Use of AES-CBC encrypted qcow2 images is no longer "
1287 "supported in system emulators");
1288 error_append_hint(errp,
1289 "You can use 'qemu-img convert' to convert your "
1290 "image to an alternative supported format, such "
1291 "as unencrypted qcow2, or raw with the LUKS "
1292 "format instead.\n");
1293 ret = -ENOSYS;
1294 goto fail;
1297 if (s->crypt_method_header == QCOW_CRYPT_AES) {
1298 s->crypt_physical_offset = false;
1299 } else {
1300 /* Assuming LUKS and any future crypt methods we
1301 * add will all use physical offsets, due to the
1302 * fact that the alternative is insecure... */
1303 s->crypt_physical_offset = true;
1306 bs->encrypted = true;
1309 s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */
1310 s->l2_size = 1 << s->l2_bits;
1311 /* 2^(s->refcount_order - 3) is the refcount width in bytes */
1312 s->refcount_block_bits = s->cluster_bits - (s->refcount_order - 3);
1313 s->refcount_block_size = 1 << s->refcount_block_bits;
1314 bs->total_sectors = header.size / 512;
1315 s->csize_shift = (62 - (s->cluster_bits - 8));
1316 s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;
1317 s->cluster_offset_mask = (1LL << s->csize_shift) - 1;
1319 s->refcount_table_offset = header.refcount_table_offset;
1320 s->refcount_table_size =
1321 header.refcount_table_clusters << (s->cluster_bits - 3);
1323 if (header.refcount_table_clusters == 0 && !(flags & BDRV_O_CHECK)) {
1324 error_setg(errp, "Image does not contain a reference count table");
1325 ret = -EINVAL;
1326 goto fail;
1329 ret = qcow2_validate_table(bs, s->refcount_table_offset,
1330 header.refcount_table_clusters,
1331 s->cluster_size, QCOW_MAX_REFTABLE_SIZE,
1332 "Reference count table", errp);
1333 if (ret < 0) {
1334 goto fail;
1337 /* The total size in bytes of the snapshot table is checked in
1338 * qcow2_read_snapshots() because the size of each snapshot is
1339 * variable and we don't know it yet.
1340 * Here we only check the offset and number of snapshots. */
1341 ret = qcow2_validate_table(bs, header.snapshots_offset,
1342 header.nb_snapshots,
1343 sizeof(QCowSnapshotHeader),
1344 sizeof(QCowSnapshotHeader) * QCOW_MAX_SNAPSHOTS,
1345 "Snapshot table", errp);
1346 if (ret < 0) {
1347 goto fail;
1350 /* read the level 1 table */
1351 ret = qcow2_validate_table(bs, header.l1_table_offset,
1352 header.l1_size, sizeof(uint64_t),
1353 QCOW_MAX_L1_SIZE, "Active L1 table", errp);
1354 if (ret < 0) {
1355 goto fail;
1357 s->l1_size = header.l1_size;
1358 s->l1_table_offset = header.l1_table_offset;
1360 l1_vm_state_index = size_to_l1(s, header.size);
1361 if (l1_vm_state_index > INT_MAX) {
1362 error_setg(errp, "Image is too big");
1363 ret = -EFBIG;
1364 goto fail;
1366 s->l1_vm_state_index = l1_vm_state_index;
1368 /* the L1 table must contain at least enough entries to put
1369 header.size bytes */
1370 if (s->l1_size < s->l1_vm_state_index) {
1371 error_setg(errp, "L1 table is too small");
1372 ret = -EINVAL;
1373 goto fail;
1376 if (s->l1_size > 0) {
1377 s->l1_table = qemu_try_blockalign(bs->file->bs,
1378 ROUND_UP(s->l1_size * sizeof(uint64_t), 512));
1379 if (s->l1_table == NULL) {
1380 error_setg(errp, "Could not allocate L1 table");
1381 ret = -ENOMEM;
1382 goto fail;
1384 ret = bdrv_pread(bs->file, s->l1_table_offset, s->l1_table,
1385 s->l1_size * sizeof(uint64_t));
1386 if (ret < 0) {
1387 error_setg_errno(errp, -ret, "Could not read L1 table");
1388 goto fail;
1390 for(i = 0;i < s->l1_size; i++) {
1391 be64_to_cpus(&s->l1_table[i]);
1395 /* Parse driver-specific options */
1396 ret = qcow2_update_options(bs, options, flags, errp);
1397 if (ret < 0) {
1398 goto fail;
1401 s->cluster_cache_offset = -1;
1402 s->flags = flags;
1404 ret = qcow2_refcount_init(bs);
1405 if (ret != 0) {
1406 error_setg_errno(errp, -ret, "Could not initialize refcount handling");
1407 goto fail;
1410 QLIST_INIT(&s->cluster_allocs);
1411 QTAILQ_INIT(&s->discards);
1413 /* read qcow2 extensions */
1414 if (qcow2_read_extensions(bs, header.header_length, ext_end, NULL,
1415 flags, &update_header, &local_err)) {
1416 error_propagate(errp, local_err);
1417 ret = -EINVAL;
1418 goto fail;
1421 /* qcow2_read_extension may have set up the crypto context
1422 * if the crypt method needs a header region, some methods
1423 * don't need header extensions, so must check here
1425 if (s->crypt_method_header && !s->crypto) {
1426 if (s->crypt_method_header == QCOW_CRYPT_AES) {
1427 unsigned int cflags = 0;
1428 if (flags & BDRV_O_NO_IO) {
1429 cflags |= QCRYPTO_BLOCK_OPEN_NO_IO;
1431 s->crypto = qcrypto_block_open(s->crypto_opts, "encrypt.",
1432 NULL, NULL, cflags, errp);
1433 if (!s->crypto) {
1434 ret = -EINVAL;
1435 goto fail;
1437 } else if (!(flags & BDRV_O_NO_IO)) {
1438 error_setg(errp, "Missing CRYPTO header for crypt method %d",
1439 s->crypt_method_header);
1440 ret = -EINVAL;
1441 goto fail;
1445 /* read the backing file name */
1446 if (header.backing_file_offset != 0) {
1447 len = header.backing_file_size;
1448 if (len > MIN(1023, s->cluster_size - header.backing_file_offset) ||
1449 len >= sizeof(bs->backing_file)) {
1450 error_setg(errp, "Backing file name too long");
1451 ret = -EINVAL;
1452 goto fail;
1454 ret = bdrv_pread(bs->file, header.backing_file_offset,
1455 bs->backing_file, len);
1456 if (ret < 0) {
1457 error_setg_errno(errp, -ret, "Could not read backing file name");
1458 goto fail;
1460 bs->backing_file[len] = '\0';
1461 s->image_backing_file = g_strdup(bs->backing_file);
1464 /* Internal snapshots */
1465 s->snapshots_offset = header.snapshots_offset;
1466 s->nb_snapshots = header.nb_snapshots;
1468 ret = qcow2_read_snapshots(bs);
1469 if (ret < 0) {
1470 error_setg_errno(errp, -ret, "Could not read snapshots");
1471 goto fail;
1474 /* Clear unknown autoclear feature bits */
1475 update_header |= s->autoclear_features & ~QCOW2_AUTOCLEAR_MASK;
1476 update_header =
1477 update_header && !bs->read_only && !(flags & BDRV_O_INACTIVE);
1478 if (update_header) {
1479 s->autoclear_features &= QCOW2_AUTOCLEAR_MASK;
1482 if (qcow2_load_dirty_bitmaps(bs, &local_err)) {
1483 update_header = false;
1485 if (local_err != NULL) {
1486 error_propagate(errp, local_err);
1487 ret = -EINVAL;
1488 goto fail;
1491 if (update_header) {
1492 ret = qcow2_update_header(bs);
1493 if (ret < 0) {
1494 error_setg_errno(errp, -ret, "Could not update qcow2 header");
1495 goto fail;
1499 bs->supported_zero_flags = header.version >= 3 ? BDRV_REQ_MAY_UNMAP : 0;
1501 /* Repair image if dirty */
1502 if (!(flags & (BDRV_O_CHECK | BDRV_O_INACTIVE)) && !bs->read_only &&
1503 (s->incompatible_features & QCOW2_INCOMPAT_DIRTY)) {
1504 BdrvCheckResult result = {0};
1506 ret = qcow2_co_check_locked(bs, &result,
1507 BDRV_FIX_ERRORS | BDRV_FIX_LEAKS);
1508 if (ret < 0 || result.check_errors) {
1509 if (ret >= 0) {
1510 ret = -EIO;
1512 error_setg_errno(errp, -ret, "Could not repair dirty image");
1513 goto fail;
1517 #ifdef DEBUG_ALLOC
1519 BdrvCheckResult result = {0};
1520 qcow2_check_refcounts(bs, &result, 0);
1522 #endif
1523 return ret;
1525 fail:
1526 g_free(s->unknown_header_fields);
1527 cleanup_unknown_header_ext(bs);
1528 qcow2_free_snapshots(bs);
1529 qcow2_refcount_close(bs);
1530 qemu_vfree(s->l1_table);
1531 /* else pre-write overlap checks in cache_destroy may crash */
1532 s->l1_table = NULL;
1533 cache_clean_timer_del(bs);
1534 if (s->l2_table_cache) {
1535 qcow2_cache_destroy(s->l2_table_cache);
1537 if (s->refcount_block_cache) {
1538 qcow2_cache_destroy(s->refcount_block_cache);
1540 qcrypto_block_free(s->crypto);
1541 qapi_free_QCryptoBlockOpenOptions(s->crypto_opts);
1542 return ret;
1545 typedef struct QCow2OpenCo {
1546 BlockDriverState *bs;
1547 QDict *options;
1548 int flags;
1549 Error **errp;
1550 int ret;
1551 } QCow2OpenCo;
1553 static void coroutine_fn qcow2_open_entry(void *opaque)
1555 QCow2OpenCo *qoc = opaque;
1556 BDRVQcow2State *s = qoc->bs->opaque;
1558 qemu_co_mutex_lock(&s->lock);
1559 qoc->ret = qcow2_do_open(qoc->bs, qoc->options, qoc->flags, qoc->errp);
1560 qemu_co_mutex_unlock(&s->lock);
1563 static int qcow2_open(BlockDriverState *bs, QDict *options, int flags,
1564 Error **errp)
1566 BDRVQcow2State *s = bs->opaque;
1567 QCow2OpenCo qoc = {
1568 .bs = bs,
1569 .options = options,
1570 .flags = flags,
1571 .errp = errp,
1572 .ret = -EINPROGRESS
1575 bs->file = bdrv_open_child(NULL, options, "file", bs, &child_file,
1576 false, errp);
1577 if (!bs->file) {
1578 return -EINVAL;
1581 /* Initialise locks */
1582 qemu_co_mutex_init(&s->lock);
1584 if (qemu_in_coroutine()) {
1585 /* From bdrv_co_create. */
1586 qcow2_open_entry(&qoc);
1587 } else {
1588 qemu_coroutine_enter(qemu_coroutine_create(qcow2_open_entry, &qoc));
1589 BDRV_POLL_WHILE(bs, qoc.ret == -EINPROGRESS);
1591 return qoc.ret;
1594 static void qcow2_refresh_limits(BlockDriverState *bs, Error **errp)
1596 BDRVQcow2State *s = bs->opaque;
1598 if (bs->encrypted) {
1599 /* Encryption works on a sector granularity */
1600 bs->bl.request_alignment = BDRV_SECTOR_SIZE;
1602 bs->bl.pwrite_zeroes_alignment = s->cluster_size;
1603 bs->bl.pdiscard_alignment = s->cluster_size;
1606 static int qcow2_reopen_prepare(BDRVReopenState *state,
1607 BlockReopenQueue *queue, Error **errp)
1609 Qcow2ReopenState *r;
1610 int ret;
1612 r = g_new0(Qcow2ReopenState, 1);
1613 state->opaque = r;
1615 ret = qcow2_update_options_prepare(state->bs, r, state->options,
1616 state->flags, errp);
1617 if (ret < 0) {
1618 goto fail;
1621 /* We need to write out any unwritten data if we reopen read-only. */
1622 if ((state->flags & BDRV_O_RDWR) == 0) {
1623 ret = qcow2_reopen_bitmaps_ro(state->bs, errp);
1624 if (ret < 0) {
1625 goto fail;
1628 ret = bdrv_flush(state->bs);
1629 if (ret < 0) {
1630 goto fail;
1633 ret = qcow2_mark_clean(state->bs);
1634 if (ret < 0) {
1635 goto fail;
1639 return 0;
1641 fail:
1642 qcow2_update_options_abort(state->bs, r);
1643 g_free(r);
1644 return ret;
1647 static void qcow2_reopen_commit(BDRVReopenState *state)
1649 qcow2_update_options_commit(state->bs, state->opaque);
1650 g_free(state->opaque);
1653 static void qcow2_reopen_abort(BDRVReopenState *state)
1655 qcow2_update_options_abort(state->bs, state->opaque);
1656 g_free(state->opaque);
1659 static void qcow2_join_options(QDict *options, QDict *old_options)
1661 bool has_new_overlap_template =
1662 qdict_haskey(options, QCOW2_OPT_OVERLAP) ||
1663 qdict_haskey(options, QCOW2_OPT_OVERLAP_TEMPLATE);
1664 bool has_new_total_cache_size =
1665 qdict_haskey(options, QCOW2_OPT_CACHE_SIZE);
1666 bool has_all_cache_options;
1668 /* New overlap template overrides all old overlap options */
1669 if (has_new_overlap_template) {
1670 qdict_del(old_options, QCOW2_OPT_OVERLAP);
1671 qdict_del(old_options, QCOW2_OPT_OVERLAP_TEMPLATE);
1672 qdict_del(old_options, QCOW2_OPT_OVERLAP_MAIN_HEADER);
1673 qdict_del(old_options, QCOW2_OPT_OVERLAP_ACTIVE_L1);
1674 qdict_del(old_options, QCOW2_OPT_OVERLAP_ACTIVE_L2);
1675 qdict_del(old_options, QCOW2_OPT_OVERLAP_REFCOUNT_TABLE);
1676 qdict_del(old_options, QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK);
1677 qdict_del(old_options, QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE);
1678 qdict_del(old_options, QCOW2_OPT_OVERLAP_INACTIVE_L1);
1679 qdict_del(old_options, QCOW2_OPT_OVERLAP_INACTIVE_L2);
1682 /* New total cache size overrides all old options */
1683 if (qdict_haskey(options, QCOW2_OPT_CACHE_SIZE)) {
1684 qdict_del(old_options, QCOW2_OPT_L2_CACHE_SIZE);
1685 qdict_del(old_options, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
1688 qdict_join(options, old_options, false);
1691 * If after merging all cache size options are set, an old total size is
1692 * overwritten. Do keep all options, however, if all three are new. The
1693 * resulting error message is what we want to happen.
1695 has_all_cache_options =
1696 qdict_haskey(options, QCOW2_OPT_CACHE_SIZE) ||
1697 qdict_haskey(options, QCOW2_OPT_L2_CACHE_SIZE) ||
1698 qdict_haskey(options, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
1700 if (has_all_cache_options && !has_new_total_cache_size) {
1701 qdict_del(options, QCOW2_OPT_CACHE_SIZE);
1705 static int coroutine_fn qcow2_co_block_status(BlockDriverState *bs,
1706 bool want_zero,
1707 int64_t offset, int64_t count,
1708 int64_t *pnum, int64_t *map,
1709 BlockDriverState **file)
1711 BDRVQcow2State *s = bs->opaque;
1712 uint64_t cluster_offset;
1713 int index_in_cluster, ret;
1714 unsigned int bytes;
1715 int status = 0;
1717 bytes = MIN(INT_MAX, count);
1718 qemu_co_mutex_lock(&s->lock);
1719 ret = qcow2_get_cluster_offset(bs, offset, &bytes, &cluster_offset);
1720 qemu_co_mutex_unlock(&s->lock);
1721 if (ret < 0) {
1722 return ret;
1725 *pnum = bytes;
1727 if (cluster_offset != 0 && ret != QCOW2_CLUSTER_COMPRESSED &&
1728 !s->crypto) {
1729 index_in_cluster = offset & (s->cluster_size - 1);
1730 *map = cluster_offset | index_in_cluster;
1731 *file = bs->file->bs;
1732 status |= BDRV_BLOCK_OFFSET_VALID;
1734 if (ret == QCOW2_CLUSTER_ZERO_PLAIN || ret == QCOW2_CLUSTER_ZERO_ALLOC) {
1735 status |= BDRV_BLOCK_ZERO;
1736 } else if (ret != QCOW2_CLUSTER_UNALLOCATED) {
1737 status |= BDRV_BLOCK_DATA;
1739 return status;
1742 static coroutine_fn int qcow2_co_preadv(BlockDriverState *bs, uint64_t offset,
1743 uint64_t bytes, QEMUIOVector *qiov,
1744 int flags)
1746 BDRVQcow2State *s = bs->opaque;
1747 int offset_in_cluster;
1748 int ret;
1749 unsigned int cur_bytes; /* number of bytes in current iteration */
1750 uint64_t cluster_offset = 0;
1751 uint64_t bytes_done = 0;
1752 QEMUIOVector hd_qiov;
1753 uint8_t *cluster_data = NULL;
1755 qemu_iovec_init(&hd_qiov, qiov->niov);
1757 qemu_co_mutex_lock(&s->lock);
1759 while (bytes != 0) {
1761 /* prepare next request */
1762 cur_bytes = MIN(bytes, INT_MAX);
1763 if (s->crypto) {
1764 cur_bytes = MIN(cur_bytes,
1765 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
1768 ret = qcow2_get_cluster_offset(bs, offset, &cur_bytes, &cluster_offset);
1769 if (ret < 0) {
1770 goto fail;
1773 offset_in_cluster = offset_into_cluster(s, offset);
1775 qemu_iovec_reset(&hd_qiov);
1776 qemu_iovec_concat(&hd_qiov, qiov, bytes_done, cur_bytes);
1778 switch (ret) {
1779 case QCOW2_CLUSTER_UNALLOCATED:
1781 if (bs->backing) {
1782 BLKDBG_EVENT(bs->file, BLKDBG_READ_BACKING_AIO);
1783 qemu_co_mutex_unlock(&s->lock);
1784 ret = bdrv_co_preadv(bs->backing, offset, cur_bytes,
1785 &hd_qiov, 0);
1786 qemu_co_mutex_lock(&s->lock);
1787 if (ret < 0) {
1788 goto fail;
1790 } else {
1791 /* Note: in this case, no need to wait */
1792 qemu_iovec_memset(&hd_qiov, 0, 0, cur_bytes);
1794 break;
1796 case QCOW2_CLUSTER_ZERO_PLAIN:
1797 case QCOW2_CLUSTER_ZERO_ALLOC:
1798 qemu_iovec_memset(&hd_qiov, 0, 0, cur_bytes);
1799 break;
1801 case QCOW2_CLUSTER_COMPRESSED:
1802 /* add AIO support for compressed blocks ? */
1803 ret = qcow2_decompress_cluster(bs, cluster_offset);
1804 if (ret < 0) {
1805 goto fail;
1808 qemu_iovec_from_buf(&hd_qiov, 0,
1809 s->cluster_cache + offset_in_cluster,
1810 cur_bytes);
1811 break;
1813 case QCOW2_CLUSTER_NORMAL:
1814 if ((cluster_offset & 511) != 0) {
1815 ret = -EIO;
1816 goto fail;
1819 if (bs->encrypted) {
1820 assert(s->crypto);
1823 * For encrypted images, read everything into a temporary
1824 * contiguous buffer on which the AES functions can work.
1826 if (!cluster_data) {
1827 cluster_data =
1828 qemu_try_blockalign(bs->file->bs,
1829 QCOW_MAX_CRYPT_CLUSTERS
1830 * s->cluster_size);
1831 if (cluster_data == NULL) {
1832 ret = -ENOMEM;
1833 goto fail;
1837 assert(cur_bytes <= QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
1838 qemu_iovec_reset(&hd_qiov);
1839 qemu_iovec_add(&hd_qiov, cluster_data, cur_bytes);
1842 BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);
1843 qemu_co_mutex_unlock(&s->lock);
1844 ret = bdrv_co_preadv(bs->file,
1845 cluster_offset + offset_in_cluster,
1846 cur_bytes, &hd_qiov, 0);
1847 qemu_co_mutex_lock(&s->lock);
1848 if (ret < 0) {
1849 goto fail;
1851 if (bs->encrypted) {
1852 assert(s->crypto);
1853 assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);
1854 assert((cur_bytes & (BDRV_SECTOR_SIZE - 1)) == 0);
1855 if (qcrypto_block_decrypt(s->crypto,
1856 (s->crypt_physical_offset ?
1857 cluster_offset + offset_in_cluster :
1858 offset),
1859 cluster_data,
1860 cur_bytes,
1861 NULL) < 0) {
1862 ret = -EIO;
1863 goto fail;
1865 qemu_iovec_from_buf(qiov, bytes_done, cluster_data, cur_bytes);
1867 break;
1869 default:
1870 g_assert_not_reached();
1871 ret = -EIO;
1872 goto fail;
1875 bytes -= cur_bytes;
1876 offset += cur_bytes;
1877 bytes_done += cur_bytes;
1879 ret = 0;
1881 fail:
1882 qemu_co_mutex_unlock(&s->lock);
1884 qemu_iovec_destroy(&hd_qiov);
1885 qemu_vfree(cluster_data);
1887 return ret;
1890 /* Check if it's possible to merge a write request with the writing of
1891 * the data from the COW regions */
1892 static bool merge_cow(uint64_t offset, unsigned bytes,
1893 QEMUIOVector *hd_qiov, QCowL2Meta *l2meta)
1895 QCowL2Meta *m;
1897 for (m = l2meta; m != NULL; m = m->next) {
1898 /* If both COW regions are empty then there's nothing to merge */
1899 if (m->cow_start.nb_bytes == 0 && m->cow_end.nb_bytes == 0) {
1900 continue;
1903 /* The data (middle) region must be immediately after the
1904 * start region */
1905 if (l2meta_cow_start(m) + m->cow_start.nb_bytes != offset) {
1906 continue;
1909 /* The end region must be immediately after the data (middle)
1910 * region */
1911 if (m->offset + m->cow_end.offset != offset + bytes) {
1912 continue;
1915 /* Make sure that adding both COW regions to the QEMUIOVector
1916 * does not exceed IOV_MAX */
1917 if (hd_qiov->niov > IOV_MAX - 2) {
1918 continue;
1921 m->data_qiov = hd_qiov;
1922 return true;
1925 return false;
1928 static coroutine_fn int qcow2_co_pwritev(BlockDriverState *bs, uint64_t offset,
1929 uint64_t bytes, QEMUIOVector *qiov,
1930 int flags)
1932 BDRVQcow2State *s = bs->opaque;
1933 int offset_in_cluster;
1934 int ret;
1935 unsigned int cur_bytes; /* number of sectors in current iteration */
1936 uint64_t cluster_offset;
1937 QEMUIOVector hd_qiov;
1938 uint64_t bytes_done = 0;
1939 uint8_t *cluster_data = NULL;
1940 QCowL2Meta *l2meta = NULL;
1942 trace_qcow2_writev_start_req(qemu_coroutine_self(), offset, bytes);
1944 qemu_iovec_init(&hd_qiov, qiov->niov);
1946 s->cluster_cache_offset = -1; /* disable compressed cache */
1948 qemu_co_mutex_lock(&s->lock);
1950 while (bytes != 0) {
1952 l2meta = NULL;
1954 trace_qcow2_writev_start_part(qemu_coroutine_self());
1955 offset_in_cluster = offset_into_cluster(s, offset);
1956 cur_bytes = MIN(bytes, INT_MAX);
1957 if (bs->encrypted) {
1958 cur_bytes = MIN(cur_bytes,
1959 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size
1960 - offset_in_cluster);
1963 ret = qcow2_alloc_cluster_offset(bs, offset, &cur_bytes,
1964 &cluster_offset, &l2meta);
1965 if (ret < 0) {
1966 goto fail;
1969 assert((cluster_offset & 511) == 0);
1971 qemu_iovec_reset(&hd_qiov);
1972 qemu_iovec_concat(&hd_qiov, qiov, bytes_done, cur_bytes);
1974 if (bs->encrypted) {
1975 assert(s->crypto);
1976 if (!cluster_data) {
1977 cluster_data = qemu_try_blockalign(bs->file->bs,
1978 QCOW_MAX_CRYPT_CLUSTERS
1979 * s->cluster_size);
1980 if (cluster_data == NULL) {
1981 ret = -ENOMEM;
1982 goto fail;
1986 assert(hd_qiov.size <=
1987 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
1988 qemu_iovec_to_buf(&hd_qiov, 0, cluster_data, hd_qiov.size);
1990 if (qcrypto_block_encrypt(s->crypto,
1991 (s->crypt_physical_offset ?
1992 cluster_offset + offset_in_cluster :
1993 offset),
1994 cluster_data,
1995 cur_bytes, NULL) < 0) {
1996 ret = -EIO;
1997 goto fail;
2000 qemu_iovec_reset(&hd_qiov);
2001 qemu_iovec_add(&hd_qiov, cluster_data, cur_bytes);
2004 ret = qcow2_pre_write_overlap_check(bs, 0,
2005 cluster_offset + offset_in_cluster, cur_bytes);
2006 if (ret < 0) {
2007 goto fail;
2010 /* If we need to do COW, check if it's possible to merge the
2011 * writing of the guest data together with that of the COW regions.
2012 * If it's not possible (or not necessary) then write the
2013 * guest data now. */
2014 if (!merge_cow(offset, cur_bytes, &hd_qiov, l2meta)) {
2015 qemu_co_mutex_unlock(&s->lock);
2016 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO);
2017 trace_qcow2_writev_data(qemu_coroutine_self(),
2018 cluster_offset + offset_in_cluster);
2019 ret = bdrv_co_pwritev(bs->file,
2020 cluster_offset + offset_in_cluster,
2021 cur_bytes, &hd_qiov, 0);
2022 qemu_co_mutex_lock(&s->lock);
2023 if (ret < 0) {
2024 goto fail;
2028 while (l2meta != NULL) {
2029 QCowL2Meta *next;
2031 ret = qcow2_alloc_cluster_link_l2(bs, l2meta);
2032 if (ret < 0) {
2033 goto fail;
2036 /* Take the request off the list of running requests */
2037 if (l2meta->nb_clusters != 0) {
2038 QLIST_REMOVE(l2meta, next_in_flight);
2041 qemu_co_queue_restart_all(&l2meta->dependent_requests);
2043 next = l2meta->next;
2044 g_free(l2meta);
2045 l2meta = next;
2048 bytes -= cur_bytes;
2049 offset += cur_bytes;
2050 bytes_done += cur_bytes;
2051 trace_qcow2_writev_done_part(qemu_coroutine_self(), cur_bytes);
2053 ret = 0;
2055 fail:
2056 while (l2meta != NULL) {
2057 QCowL2Meta *next;
2059 if (l2meta->nb_clusters != 0) {
2060 QLIST_REMOVE(l2meta, next_in_flight);
2062 qemu_co_queue_restart_all(&l2meta->dependent_requests);
2064 next = l2meta->next;
2065 g_free(l2meta);
2066 l2meta = next;
2069 qemu_co_mutex_unlock(&s->lock);
2071 qemu_iovec_destroy(&hd_qiov);
2072 qemu_vfree(cluster_data);
2073 trace_qcow2_writev_done_req(qemu_coroutine_self(), ret);
2075 return ret;
2078 static int qcow2_inactivate(BlockDriverState *bs)
2080 BDRVQcow2State *s = bs->opaque;
2081 int ret, result = 0;
2082 Error *local_err = NULL;
2084 qcow2_store_persistent_dirty_bitmaps(bs, &local_err);
2085 if (local_err != NULL) {
2086 result = -EINVAL;
2087 error_report_err(local_err);
2088 error_report("Persistent bitmaps are lost for node '%s'",
2089 bdrv_get_device_or_node_name(bs));
2092 ret = qcow2_cache_flush(bs, s->l2_table_cache);
2093 if (ret) {
2094 result = ret;
2095 error_report("Failed to flush the L2 table cache: %s",
2096 strerror(-ret));
2099 ret = qcow2_cache_flush(bs, s->refcount_block_cache);
2100 if (ret) {
2101 result = ret;
2102 error_report("Failed to flush the refcount block cache: %s",
2103 strerror(-ret));
2106 if (result == 0) {
2107 qcow2_mark_clean(bs);
2110 return result;
2113 static void qcow2_close(BlockDriverState *bs)
2115 BDRVQcow2State *s = bs->opaque;
2116 qemu_vfree(s->l1_table);
2117 /* else pre-write overlap checks in cache_destroy may crash */
2118 s->l1_table = NULL;
2120 if (!(s->flags & BDRV_O_INACTIVE)) {
2121 qcow2_inactivate(bs);
2124 cache_clean_timer_del(bs);
2125 qcow2_cache_destroy(s->l2_table_cache);
2126 qcow2_cache_destroy(s->refcount_block_cache);
2128 qcrypto_block_free(s->crypto);
2129 s->crypto = NULL;
2131 g_free(s->unknown_header_fields);
2132 cleanup_unknown_header_ext(bs);
2134 g_free(s->image_backing_file);
2135 g_free(s->image_backing_format);
2137 g_free(s->cluster_cache);
2138 qemu_vfree(s->cluster_data);
2139 qcow2_refcount_close(bs);
2140 qcow2_free_snapshots(bs);
2143 static void coroutine_fn qcow2_co_invalidate_cache(BlockDriverState *bs,
2144 Error **errp)
2146 BDRVQcow2State *s = bs->opaque;
2147 int flags = s->flags;
2148 QCryptoBlock *crypto = NULL;
2149 QDict *options;
2150 Error *local_err = NULL;
2151 int ret;
2154 * Backing files are read-only which makes all of their metadata immutable,
2155 * that means we don't have to worry about reopening them here.
2158 crypto = s->crypto;
2159 s->crypto = NULL;
2161 qcow2_close(bs);
2163 memset(s, 0, sizeof(BDRVQcow2State));
2164 options = qdict_clone_shallow(bs->options);
2166 flags &= ~BDRV_O_INACTIVE;
2167 qemu_co_mutex_lock(&s->lock);
2168 ret = qcow2_do_open(bs, options, flags, &local_err);
2169 qemu_co_mutex_unlock(&s->lock);
2170 QDECREF(options);
2171 if (local_err) {
2172 error_propagate(errp, local_err);
2173 error_prepend(errp, "Could not reopen qcow2 layer: ");
2174 bs->drv = NULL;
2175 return;
2176 } else if (ret < 0) {
2177 error_setg_errno(errp, -ret, "Could not reopen qcow2 layer");
2178 bs->drv = NULL;
2179 return;
2182 s->crypto = crypto;
2185 static size_t header_ext_add(char *buf, uint32_t magic, const void *s,
2186 size_t len, size_t buflen)
2188 QCowExtension *ext_backing_fmt = (QCowExtension*) buf;
2189 size_t ext_len = sizeof(QCowExtension) + ((len + 7) & ~7);
2191 if (buflen < ext_len) {
2192 return -ENOSPC;
2195 *ext_backing_fmt = (QCowExtension) {
2196 .magic = cpu_to_be32(magic),
2197 .len = cpu_to_be32(len),
2200 if (len) {
2201 memcpy(buf + sizeof(QCowExtension), s, len);
2204 return ext_len;
2208 * Updates the qcow2 header, including the variable length parts of it, i.e.
2209 * the backing file name and all extensions. qcow2 was not designed to allow
2210 * such changes, so if we run out of space (we can only use the first cluster)
2211 * this function may fail.
2213 * Returns 0 on success, -errno in error cases.
2215 int qcow2_update_header(BlockDriverState *bs)
2217 BDRVQcow2State *s = bs->opaque;
2218 QCowHeader *header;
2219 char *buf;
2220 size_t buflen = s->cluster_size;
2221 int ret;
2222 uint64_t total_size;
2223 uint32_t refcount_table_clusters;
2224 size_t header_length;
2225 Qcow2UnknownHeaderExtension *uext;
2227 buf = qemu_blockalign(bs, buflen);
2229 /* Header structure */
2230 header = (QCowHeader*) buf;
2232 if (buflen < sizeof(*header)) {
2233 ret = -ENOSPC;
2234 goto fail;
2237 header_length = sizeof(*header) + s->unknown_header_fields_size;
2238 total_size = bs->total_sectors * BDRV_SECTOR_SIZE;
2239 refcount_table_clusters = s->refcount_table_size >> (s->cluster_bits - 3);
2241 *header = (QCowHeader) {
2242 /* Version 2 fields */
2243 .magic = cpu_to_be32(QCOW_MAGIC),
2244 .version = cpu_to_be32(s->qcow_version),
2245 .backing_file_offset = 0,
2246 .backing_file_size = 0,
2247 .cluster_bits = cpu_to_be32(s->cluster_bits),
2248 .size = cpu_to_be64(total_size),
2249 .crypt_method = cpu_to_be32(s->crypt_method_header),
2250 .l1_size = cpu_to_be32(s->l1_size),
2251 .l1_table_offset = cpu_to_be64(s->l1_table_offset),
2252 .refcount_table_offset = cpu_to_be64(s->refcount_table_offset),
2253 .refcount_table_clusters = cpu_to_be32(refcount_table_clusters),
2254 .nb_snapshots = cpu_to_be32(s->nb_snapshots),
2255 .snapshots_offset = cpu_to_be64(s->snapshots_offset),
2257 /* Version 3 fields */
2258 .incompatible_features = cpu_to_be64(s->incompatible_features),
2259 .compatible_features = cpu_to_be64(s->compatible_features),
2260 .autoclear_features = cpu_to_be64(s->autoclear_features),
2261 .refcount_order = cpu_to_be32(s->refcount_order),
2262 .header_length = cpu_to_be32(header_length),
2265 /* For older versions, write a shorter header */
2266 switch (s->qcow_version) {
2267 case 2:
2268 ret = offsetof(QCowHeader, incompatible_features);
2269 break;
2270 case 3:
2271 ret = sizeof(*header);
2272 break;
2273 default:
2274 ret = -EINVAL;
2275 goto fail;
2278 buf += ret;
2279 buflen -= ret;
2280 memset(buf, 0, buflen);
2282 /* Preserve any unknown field in the header */
2283 if (s->unknown_header_fields_size) {
2284 if (buflen < s->unknown_header_fields_size) {
2285 ret = -ENOSPC;
2286 goto fail;
2289 memcpy(buf, s->unknown_header_fields, s->unknown_header_fields_size);
2290 buf += s->unknown_header_fields_size;
2291 buflen -= s->unknown_header_fields_size;
2294 /* Backing file format header extension */
2295 if (s->image_backing_format) {
2296 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BACKING_FORMAT,
2297 s->image_backing_format,
2298 strlen(s->image_backing_format),
2299 buflen);
2300 if (ret < 0) {
2301 goto fail;
2304 buf += ret;
2305 buflen -= ret;
2308 /* Full disk encryption header pointer extension */
2309 if (s->crypto_header.offset != 0) {
2310 cpu_to_be64s(&s->crypto_header.offset);
2311 cpu_to_be64s(&s->crypto_header.length);
2312 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_CRYPTO_HEADER,
2313 &s->crypto_header, sizeof(s->crypto_header),
2314 buflen);
2315 be64_to_cpus(&s->crypto_header.offset);
2316 be64_to_cpus(&s->crypto_header.length);
2317 if (ret < 0) {
2318 goto fail;
2320 buf += ret;
2321 buflen -= ret;
2324 /* Feature table */
2325 if (s->qcow_version >= 3) {
2326 Qcow2Feature features[] = {
2328 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
2329 .bit = QCOW2_INCOMPAT_DIRTY_BITNR,
2330 .name = "dirty bit",
2333 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
2334 .bit = QCOW2_INCOMPAT_CORRUPT_BITNR,
2335 .name = "corrupt bit",
2338 .type = QCOW2_FEAT_TYPE_COMPATIBLE,
2339 .bit = QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR,
2340 .name = "lazy refcounts",
2344 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_FEATURE_TABLE,
2345 features, sizeof(features), buflen);
2346 if (ret < 0) {
2347 goto fail;
2349 buf += ret;
2350 buflen -= ret;
2353 /* Bitmap extension */
2354 if (s->nb_bitmaps > 0) {
2355 Qcow2BitmapHeaderExt bitmaps_header = {
2356 .nb_bitmaps = cpu_to_be32(s->nb_bitmaps),
2357 .bitmap_directory_size =
2358 cpu_to_be64(s->bitmap_directory_size),
2359 .bitmap_directory_offset =
2360 cpu_to_be64(s->bitmap_directory_offset)
2362 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BITMAPS,
2363 &bitmaps_header, sizeof(bitmaps_header),
2364 buflen);
2365 if (ret < 0) {
2366 goto fail;
2368 buf += ret;
2369 buflen -= ret;
2372 /* Keep unknown header extensions */
2373 QLIST_FOREACH(uext, &s->unknown_header_ext, next) {
2374 ret = header_ext_add(buf, uext->magic, uext->data, uext->len, buflen);
2375 if (ret < 0) {
2376 goto fail;
2379 buf += ret;
2380 buflen -= ret;
2383 /* End of header extensions */
2384 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_END, NULL, 0, buflen);
2385 if (ret < 0) {
2386 goto fail;
2389 buf += ret;
2390 buflen -= ret;
2392 /* Backing file name */
2393 if (s->image_backing_file) {
2394 size_t backing_file_len = strlen(s->image_backing_file);
2396 if (buflen < backing_file_len) {
2397 ret = -ENOSPC;
2398 goto fail;
2401 /* Using strncpy is ok here, since buf is not NUL-terminated. */
2402 strncpy(buf, s->image_backing_file, buflen);
2404 header->backing_file_offset = cpu_to_be64(buf - ((char*) header));
2405 header->backing_file_size = cpu_to_be32(backing_file_len);
2408 /* Write the new header */
2409 ret = bdrv_pwrite(bs->file, 0, header, s->cluster_size);
2410 if (ret < 0) {
2411 goto fail;
2414 ret = 0;
2415 fail:
2416 qemu_vfree(header);
2417 return ret;
2420 static int qcow2_change_backing_file(BlockDriverState *bs,
2421 const char *backing_file, const char *backing_fmt)
2423 BDRVQcow2State *s = bs->opaque;
2425 if (backing_file && strlen(backing_file) > 1023) {
2426 return -EINVAL;
2429 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
2430 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
2432 g_free(s->image_backing_file);
2433 g_free(s->image_backing_format);
2435 s->image_backing_file = backing_file ? g_strdup(bs->backing_file) : NULL;
2436 s->image_backing_format = backing_fmt ? g_strdup(bs->backing_format) : NULL;
2438 return qcow2_update_header(bs);
2441 static int qcow2_crypt_method_from_format(const char *encryptfmt)
2443 if (g_str_equal(encryptfmt, "luks")) {
2444 return QCOW_CRYPT_LUKS;
2445 } else if (g_str_equal(encryptfmt, "aes")) {
2446 return QCOW_CRYPT_AES;
2447 } else {
2448 return -EINVAL;
2452 static int qcow2_set_up_encryption(BlockDriverState *bs, const char *encryptfmt,
2453 QemuOpts *opts, Error **errp)
2455 BDRVQcow2State *s = bs->opaque;
2456 QCryptoBlockCreateOptions *cryptoopts = NULL;
2457 QCryptoBlock *crypto = NULL;
2458 int ret = -EINVAL;
2459 QDict *options, *encryptopts;
2460 int fmt;
2462 options = qemu_opts_to_qdict(opts, NULL);
2463 qdict_extract_subqdict(options, &encryptopts, "encrypt.");
2464 QDECREF(options);
2466 fmt = qcow2_crypt_method_from_format(encryptfmt);
2468 switch (fmt) {
2469 case QCOW_CRYPT_LUKS:
2470 cryptoopts = block_crypto_create_opts_init(
2471 Q_CRYPTO_BLOCK_FORMAT_LUKS, encryptopts, errp);
2472 break;
2473 case QCOW_CRYPT_AES:
2474 cryptoopts = block_crypto_create_opts_init(
2475 Q_CRYPTO_BLOCK_FORMAT_QCOW, encryptopts, errp);
2476 break;
2477 default:
2478 error_setg(errp, "Unknown encryption format '%s'", encryptfmt);
2479 break;
2481 if (!cryptoopts) {
2482 ret = -EINVAL;
2483 goto out;
2485 s->crypt_method_header = fmt;
2487 crypto = qcrypto_block_create(cryptoopts, "encrypt.",
2488 qcow2_crypto_hdr_init_func,
2489 qcow2_crypto_hdr_write_func,
2490 bs, errp);
2491 if (!crypto) {
2492 ret = -EINVAL;
2493 goto out;
2496 ret = qcow2_update_header(bs);
2497 if (ret < 0) {
2498 error_setg_errno(errp, -ret, "Could not write encryption header");
2499 goto out;
2502 out:
2503 QDECREF(encryptopts);
2504 qcrypto_block_free(crypto);
2505 qapi_free_QCryptoBlockCreateOptions(cryptoopts);
2506 return ret;
2510 typedef struct PreallocCo {
2511 BlockDriverState *bs;
2512 uint64_t offset;
2513 uint64_t new_length;
2515 int ret;
2516 } PreallocCo;
2519 * Preallocates metadata structures for data clusters between @offset (in the
2520 * guest disk) and @new_length (which is thus generally the new guest disk
2521 * size).
2523 * Returns: 0 on success, -errno on failure.
2525 static void coroutine_fn preallocate_co(void *opaque)
2527 PreallocCo *params = opaque;
2528 BlockDriverState *bs = params->bs;
2529 uint64_t offset = params->offset;
2530 uint64_t new_length = params->new_length;
2531 BDRVQcow2State *s = bs->opaque;
2532 uint64_t bytes;
2533 uint64_t host_offset = 0;
2534 unsigned int cur_bytes;
2535 int ret;
2536 QCowL2Meta *meta;
2538 qemu_co_mutex_lock(&s->lock);
2540 assert(offset <= new_length);
2541 bytes = new_length - offset;
2543 while (bytes) {
2544 cur_bytes = MIN(bytes, INT_MAX);
2545 ret = qcow2_alloc_cluster_offset(bs, offset, &cur_bytes,
2546 &host_offset, &meta);
2547 if (ret < 0) {
2548 goto done;
2551 while (meta) {
2552 QCowL2Meta *next = meta->next;
2554 ret = qcow2_alloc_cluster_link_l2(bs, meta);
2555 if (ret < 0) {
2556 qcow2_free_any_clusters(bs, meta->alloc_offset,
2557 meta->nb_clusters, QCOW2_DISCARD_NEVER);
2558 goto done;
2561 /* There are no dependent requests, but we need to remove our
2562 * request from the list of in-flight requests */
2563 QLIST_REMOVE(meta, next_in_flight);
2565 g_free(meta);
2566 meta = next;
2569 /* TODO Preallocate data if requested */
2571 bytes -= cur_bytes;
2572 offset += cur_bytes;
2576 * It is expected that the image file is large enough to actually contain
2577 * all of the allocated clusters (otherwise we get failing reads after
2578 * EOF). Extend the image to the last allocated sector.
2580 if (host_offset != 0) {
2581 uint8_t data = 0;
2582 ret = bdrv_pwrite(bs->file, (host_offset + cur_bytes) - 1,
2583 &data, 1);
2584 if (ret < 0) {
2585 goto done;
2589 ret = 0;
2591 done:
2592 qemu_co_mutex_unlock(&s->lock);
2593 params->ret = ret;
2596 static int preallocate(BlockDriverState *bs,
2597 uint64_t offset, uint64_t new_length)
2599 PreallocCo params = {
2600 .bs = bs,
2601 .offset = offset,
2602 .new_length = new_length,
2603 .ret = -EINPROGRESS,
2606 if (qemu_in_coroutine()) {
2607 preallocate_co(&params);
2608 } else {
2609 Coroutine *co = qemu_coroutine_create(preallocate_co, &params);
2610 bdrv_coroutine_enter(bs, co);
2611 BDRV_POLL_WHILE(bs, params.ret == -EINPROGRESS);
2613 return params.ret;
2616 /* qcow2_refcount_metadata_size:
2617 * @clusters: number of clusters to refcount (including data and L1/L2 tables)
2618 * @cluster_size: size of a cluster, in bytes
2619 * @refcount_order: refcount bits power-of-2 exponent
2620 * @generous_increase: allow for the refcount table to be 1.5x as large as it
2621 * needs to be
2623 * Returns: Number of bytes required for refcount blocks and table metadata.
2625 int64_t qcow2_refcount_metadata_size(int64_t clusters, size_t cluster_size,
2626 int refcount_order, bool generous_increase,
2627 uint64_t *refblock_count)
2630 * Every host cluster is reference-counted, including metadata (even
2631 * refcount metadata is recursively included).
2633 * An accurate formula for the size of refcount metadata size is difficult
2634 * to derive. An easier method of calculation is finding the fixed point
2635 * where no further refcount blocks or table clusters are required to
2636 * reference count every cluster.
2638 int64_t blocks_per_table_cluster = cluster_size / sizeof(uint64_t);
2639 int64_t refcounts_per_block = cluster_size * 8 / (1 << refcount_order);
2640 int64_t table = 0; /* number of refcount table clusters */
2641 int64_t blocks = 0; /* number of refcount block clusters */
2642 int64_t last;
2643 int64_t n = 0;
2645 do {
2646 last = n;
2647 blocks = DIV_ROUND_UP(clusters + table + blocks, refcounts_per_block);
2648 table = DIV_ROUND_UP(blocks, blocks_per_table_cluster);
2649 n = clusters + blocks + table;
2651 if (n == last && generous_increase) {
2652 clusters += DIV_ROUND_UP(table, 2);
2653 n = 0; /* force another loop */
2654 generous_increase = false;
2656 } while (n != last);
2658 if (refblock_count) {
2659 *refblock_count = blocks;
2662 return (blocks + table) * cluster_size;
2666 * qcow2_calc_prealloc_size:
2667 * @total_size: virtual disk size in bytes
2668 * @cluster_size: cluster size in bytes
2669 * @refcount_order: refcount bits power-of-2 exponent
2671 * Returns: Total number of bytes required for the fully allocated image
2672 * (including metadata).
2674 static int64_t qcow2_calc_prealloc_size(int64_t total_size,
2675 size_t cluster_size,
2676 int refcount_order)
2678 int64_t meta_size = 0;
2679 uint64_t nl1e, nl2e;
2680 int64_t aligned_total_size = ROUND_UP(total_size, cluster_size);
2682 /* header: 1 cluster */
2683 meta_size += cluster_size;
2685 /* total size of L2 tables */
2686 nl2e = aligned_total_size / cluster_size;
2687 nl2e = ROUND_UP(nl2e, cluster_size / sizeof(uint64_t));
2688 meta_size += nl2e * sizeof(uint64_t);
2690 /* total size of L1 tables */
2691 nl1e = nl2e * sizeof(uint64_t) / cluster_size;
2692 nl1e = ROUND_UP(nl1e, cluster_size / sizeof(uint64_t));
2693 meta_size += nl1e * sizeof(uint64_t);
2695 /* total size of refcount table and blocks */
2696 meta_size += qcow2_refcount_metadata_size(
2697 (meta_size + aligned_total_size) / cluster_size,
2698 cluster_size, refcount_order, false, NULL);
2700 return meta_size + aligned_total_size;
2703 static size_t qcow2_opt_get_cluster_size_del(QemuOpts *opts, Error **errp)
2705 size_t cluster_size;
2706 int cluster_bits;
2708 cluster_size = qemu_opt_get_size_del(opts, BLOCK_OPT_CLUSTER_SIZE,
2709 DEFAULT_CLUSTER_SIZE);
2710 cluster_bits = ctz32(cluster_size);
2711 if (cluster_bits < MIN_CLUSTER_BITS || cluster_bits > MAX_CLUSTER_BITS ||
2712 (1 << cluster_bits) != cluster_size)
2714 error_setg(errp, "Cluster size must be a power of two between %d and "
2715 "%dk", 1 << MIN_CLUSTER_BITS, 1 << (MAX_CLUSTER_BITS - 10));
2716 return 0;
2718 return cluster_size;
2721 static int qcow2_opt_get_version_del(QemuOpts *opts, Error **errp)
2723 char *buf;
2724 int ret;
2726 buf = qemu_opt_get_del(opts, BLOCK_OPT_COMPAT_LEVEL);
2727 if (!buf) {
2728 ret = 3; /* default */
2729 } else if (!strcmp(buf, "0.10")) {
2730 ret = 2;
2731 } else if (!strcmp(buf, "1.1")) {
2732 ret = 3;
2733 } else {
2734 error_setg(errp, "Invalid compatibility level: '%s'", buf);
2735 ret = -EINVAL;
2737 g_free(buf);
2738 return ret;
2741 static uint64_t qcow2_opt_get_refcount_bits_del(QemuOpts *opts, int version,
2742 Error **errp)
2744 uint64_t refcount_bits;
2746 refcount_bits = qemu_opt_get_number_del(opts, BLOCK_OPT_REFCOUNT_BITS, 16);
2747 if (refcount_bits > 64 || !is_power_of_2(refcount_bits)) {
2748 error_setg(errp, "Refcount width must be a power of two and may not "
2749 "exceed 64 bits");
2750 return 0;
2753 if (version < 3 && refcount_bits != 16) {
2754 error_setg(errp, "Different refcount widths than 16 bits require "
2755 "compatibility level 1.1 or above (use compat=1.1 or "
2756 "greater)");
2757 return 0;
2760 return refcount_bits;
2763 static int coroutine_fn
2764 qcow2_co_create2(const char *filename, int64_t total_size,
2765 const char *backing_file, const char *backing_format,
2766 int flags, size_t cluster_size, PreallocMode prealloc,
2767 QemuOpts *opts, int version, int refcount_order,
2768 const char *encryptfmt, Error **errp)
2770 QDict *options;
2773 * Open the image file and write a minimal qcow2 header.
2775 * We keep things simple and start with a zero-sized image. We also
2776 * do without refcount blocks or a L1 table for now. We'll fix the
2777 * inconsistency later.
2779 * We do need a refcount table because growing the refcount table means
2780 * allocating two new refcount blocks - the seconds of which would be at
2781 * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
2782 * size for any qcow2 image.
2784 BlockBackend *blk;
2785 QCowHeader *header;
2786 uint64_t* refcount_table;
2787 Error *local_err = NULL;
2788 int ret;
2790 if (prealloc == PREALLOC_MODE_FULL || prealloc == PREALLOC_MODE_FALLOC) {
2791 int64_t prealloc_size =
2792 qcow2_calc_prealloc_size(total_size, cluster_size, refcount_order);
2793 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, prealloc_size, &error_abort);
2794 qemu_opt_set(opts, BLOCK_OPT_PREALLOC, PreallocMode_str(prealloc),
2795 &error_abort);
2798 ret = bdrv_create_file(filename, opts, &local_err);
2799 if (ret < 0) {
2800 error_propagate(errp, local_err);
2801 return ret;
2804 blk = blk_new_open(filename, NULL, NULL,
2805 BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_PROTOCOL,
2806 &local_err);
2807 if (blk == NULL) {
2808 error_propagate(errp, local_err);
2809 return -EIO;
2812 blk_set_allow_write_beyond_eof(blk, true);
2814 /* Write the header */
2815 QEMU_BUILD_BUG_ON((1 << MIN_CLUSTER_BITS) < sizeof(*header));
2816 header = g_malloc0(cluster_size);
2817 *header = (QCowHeader) {
2818 .magic = cpu_to_be32(QCOW_MAGIC),
2819 .version = cpu_to_be32(version),
2820 .cluster_bits = cpu_to_be32(ctz32(cluster_size)),
2821 .size = cpu_to_be64(0),
2822 .l1_table_offset = cpu_to_be64(0),
2823 .l1_size = cpu_to_be32(0),
2824 .refcount_table_offset = cpu_to_be64(cluster_size),
2825 .refcount_table_clusters = cpu_to_be32(1),
2826 .refcount_order = cpu_to_be32(refcount_order),
2827 .header_length = cpu_to_be32(sizeof(*header)),
2830 /* We'll update this to correct value later */
2831 header->crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
2833 if (flags & BLOCK_FLAG_LAZY_REFCOUNTS) {
2834 header->compatible_features |=
2835 cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS);
2838 ret = blk_pwrite(blk, 0, header, cluster_size, 0);
2839 g_free(header);
2840 if (ret < 0) {
2841 error_setg_errno(errp, -ret, "Could not write qcow2 header");
2842 goto out;
2845 /* Write a refcount table with one refcount block */
2846 refcount_table = g_malloc0(2 * cluster_size);
2847 refcount_table[0] = cpu_to_be64(2 * cluster_size);
2848 ret = blk_pwrite(blk, cluster_size, refcount_table, 2 * cluster_size, 0);
2849 g_free(refcount_table);
2851 if (ret < 0) {
2852 error_setg_errno(errp, -ret, "Could not write refcount table");
2853 goto out;
2856 blk_unref(blk);
2857 blk = NULL;
2860 * And now open the image and make it consistent first (i.e. increase the
2861 * refcount of the cluster that is occupied by the header and the refcount
2862 * table)
2864 options = qdict_new();
2865 qdict_put_str(options, "driver", "qcow2");
2866 blk = blk_new_open(filename, NULL, options,
2867 BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_NO_FLUSH,
2868 &local_err);
2869 if (blk == NULL) {
2870 error_propagate(errp, local_err);
2871 ret = -EIO;
2872 goto out;
2875 ret = qcow2_alloc_clusters(blk_bs(blk), 3 * cluster_size);
2876 if (ret < 0) {
2877 error_setg_errno(errp, -ret, "Could not allocate clusters for qcow2 "
2878 "header and refcount table");
2879 goto out;
2881 } else if (ret != 0) {
2882 error_report("Huh, first cluster in empty image is already in use?");
2883 abort();
2886 /* Create a full header (including things like feature table) */
2887 ret = qcow2_update_header(blk_bs(blk));
2888 if (ret < 0) {
2889 error_setg_errno(errp, -ret, "Could not update qcow2 header");
2890 goto out;
2893 /* Okay, now that we have a valid image, let's give it the right size */
2894 ret = blk_truncate(blk, total_size, PREALLOC_MODE_OFF, errp);
2895 if (ret < 0) {
2896 error_prepend(errp, "Could not resize image: ");
2897 goto out;
2900 /* Want a backing file? There you go.*/
2901 if (backing_file) {
2902 ret = bdrv_change_backing_file(blk_bs(blk), backing_file, backing_format);
2903 if (ret < 0) {
2904 error_setg_errno(errp, -ret, "Could not assign backing file '%s' "
2905 "with format '%s'", backing_file, backing_format);
2906 goto out;
2910 /* Want encryption? There you go. */
2911 if (encryptfmt) {
2912 ret = qcow2_set_up_encryption(blk_bs(blk), encryptfmt, opts, errp);
2913 if (ret < 0) {
2914 goto out;
2918 /* And if we're supposed to preallocate metadata, do that now */
2919 if (prealloc != PREALLOC_MODE_OFF) {
2920 ret = preallocate(blk_bs(blk), 0, total_size);
2921 if (ret < 0) {
2922 error_setg_errno(errp, -ret, "Could not preallocate metadata");
2923 goto out;
2927 blk_unref(blk);
2928 blk = NULL;
2930 /* Reopen the image without BDRV_O_NO_FLUSH to flush it before returning.
2931 * Using BDRV_O_NO_IO, since encryption is now setup we don't want to
2932 * have to setup decryption context. We're not doing any I/O on the top
2933 * level BlockDriverState, only lower layers, where BDRV_O_NO_IO does
2934 * not have effect.
2936 options = qdict_new();
2937 qdict_put_str(options, "driver", "qcow2");
2938 blk = blk_new_open(filename, NULL, options,
2939 BDRV_O_RDWR | BDRV_O_NO_BACKING | BDRV_O_NO_IO,
2940 &local_err);
2941 if (blk == NULL) {
2942 error_propagate(errp, local_err);
2943 ret = -EIO;
2944 goto out;
2947 ret = 0;
2948 out:
2949 if (blk) {
2950 blk_unref(blk);
2952 return ret;
2955 static int coroutine_fn qcow2_co_create_opts(const char *filename, QemuOpts *opts,
2956 Error **errp)
2958 char *backing_file = NULL;
2959 char *backing_fmt = NULL;
2960 char *buf = NULL;
2961 uint64_t size = 0;
2962 int flags = 0;
2963 size_t cluster_size = DEFAULT_CLUSTER_SIZE;
2964 PreallocMode prealloc;
2965 int version;
2966 uint64_t refcount_bits;
2967 int refcount_order;
2968 char *encryptfmt = NULL;
2969 Error *local_err = NULL;
2970 int ret;
2972 /* Read out options */
2973 size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
2974 BDRV_SECTOR_SIZE);
2975 backing_file = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
2976 backing_fmt = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FMT);
2977 encryptfmt = qemu_opt_get_del(opts, BLOCK_OPT_ENCRYPT_FORMAT);
2978 if (encryptfmt) {
2979 if (qemu_opt_get(opts, BLOCK_OPT_ENCRYPT)) {
2980 error_setg(errp, "Options " BLOCK_OPT_ENCRYPT " and "
2981 BLOCK_OPT_ENCRYPT_FORMAT " are mutually exclusive");
2982 ret = -EINVAL;
2983 goto finish;
2985 } else if (qemu_opt_get_bool_del(opts, BLOCK_OPT_ENCRYPT, false)) {
2986 encryptfmt = g_strdup("aes");
2988 cluster_size = qcow2_opt_get_cluster_size_del(opts, &local_err);
2989 if (local_err) {
2990 error_propagate(errp, local_err);
2991 ret = -EINVAL;
2992 goto finish;
2994 buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
2995 prealloc = qapi_enum_parse(&PreallocMode_lookup, buf,
2996 PREALLOC_MODE_OFF, &local_err);
2997 if (local_err) {
2998 error_propagate(errp, local_err);
2999 ret = -EINVAL;
3000 goto finish;
3003 version = qcow2_opt_get_version_del(opts, &local_err);
3004 if (local_err) {
3005 error_propagate(errp, local_err);
3006 ret = -EINVAL;
3007 goto finish;
3010 if (qemu_opt_get_bool_del(opts, BLOCK_OPT_LAZY_REFCOUNTS, false)) {
3011 flags |= BLOCK_FLAG_LAZY_REFCOUNTS;
3014 if (backing_file && prealloc != PREALLOC_MODE_OFF) {
3015 error_setg(errp, "Backing file and preallocation cannot be used at "
3016 "the same time");
3017 ret = -EINVAL;
3018 goto finish;
3021 if (version < 3 && (flags & BLOCK_FLAG_LAZY_REFCOUNTS)) {
3022 error_setg(errp, "Lazy refcounts only supported with compatibility "
3023 "level 1.1 and above (use compat=1.1 or greater)");
3024 ret = -EINVAL;
3025 goto finish;
3028 refcount_bits = qcow2_opt_get_refcount_bits_del(opts, version, &local_err);
3029 if (local_err) {
3030 error_propagate(errp, local_err);
3031 ret = -EINVAL;
3032 goto finish;
3035 refcount_order = ctz32(refcount_bits);
3037 ret = qcow2_co_create2(filename, size, backing_file, backing_fmt, flags,
3038 cluster_size, prealloc, opts, version, refcount_order,
3039 encryptfmt, &local_err);
3040 error_propagate(errp, local_err);
3042 finish:
3043 g_free(backing_file);
3044 g_free(backing_fmt);
3045 g_free(encryptfmt);
3046 g_free(buf);
3047 return ret;
3051 static bool is_zero(BlockDriverState *bs, int64_t offset, int64_t bytes)
3053 int64_t nr;
3054 int res;
3056 /* Clamp to image length, before checking status of underlying sectors */
3057 if (offset + bytes > bs->total_sectors * BDRV_SECTOR_SIZE) {
3058 bytes = bs->total_sectors * BDRV_SECTOR_SIZE - offset;
3061 if (!bytes) {
3062 return true;
3064 res = bdrv_block_status_above(bs, NULL, offset, bytes, &nr, NULL, NULL);
3065 return res >= 0 && (res & BDRV_BLOCK_ZERO) && nr == bytes;
3068 static coroutine_fn int qcow2_co_pwrite_zeroes(BlockDriverState *bs,
3069 int64_t offset, int bytes, BdrvRequestFlags flags)
3071 int ret;
3072 BDRVQcow2State *s = bs->opaque;
3074 uint32_t head = offset % s->cluster_size;
3075 uint32_t tail = (offset + bytes) % s->cluster_size;
3077 trace_qcow2_pwrite_zeroes_start_req(qemu_coroutine_self(), offset, bytes);
3078 if (offset + bytes == bs->total_sectors * BDRV_SECTOR_SIZE) {
3079 tail = 0;
3082 if (head || tail) {
3083 uint64_t off;
3084 unsigned int nr;
3086 assert(head + bytes <= s->cluster_size);
3088 /* check whether remainder of cluster already reads as zero */
3089 if (!(is_zero(bs, offset - head, head) &&
3090 is_zero(bs, offset + bytes,
3091 tail ? s->cluster_size - tail : 0))) {
3092 return -ENOTSUP;
3095 qemu_co_mutex_lock(&s->lock);
3096 /* We can have new write after previous check */
3097 offset = QEMU_ALIGN_DOWN(offset, s->cluster_size);
3098 bytes = s->cluster_size;
3099 nr = s->cluster_size;
3100 ret = qcow2_get_cluster_offset(bs, offset, &nr, &off);
3101 if (ret != QCOW2_CLUSTER_UNALLOCATED &&
3102 ret != QCOW2_CLUSTER_ZERO_PLAIN &&
3103 ret != QCOW2_CLUSTER_ZERO_ALLOC) {
3104 qemu_co_mutex_unlock(&s->lock);
3105 return -ENOTSUP;
3107 } else {
3108 qemu_co_mutex_lock(&s->lock);
3111 trace_qcow2_pwrite_zeroes(qemu_coroutine_self(), offset, bytes);
3113 /* Whatever is left can use real zero clusters */
3114 ret = qcow2_cluster_zeroize(bs, offset, bytes, flags);
3115 qemu_co_mutex_unlock(&s->lock);
3117 return ret;
3120 static coroutine_fn int qcow2_co_pdiscard(BlockDriverState *bs,
3121 int64_t offset, int bytes)
3123 int ret;
3124 BDRVQcow2State *s = bs->opaque;
3126 if (!QEMU_IS_ALIGNED(offset | bytes, s->cluster_size)) {
3127 assert(bytes < s->cluster_size);
3128 /* Ignore partial clusters, except for the special case of the
3129 * complete partial cluster at the end of an unaligned file */
3130 if (!QEMU_IS_ALIGNED(offset, s->cluster_size) ||
3131 offset + bytes != bs->total_sectors * BDRV_SECTOR_SIZE) {
3132 return -ENOTSUP;
3136 qemu_co_mutex_lock(&s->lock);
3137 ret = qcow2_cluster_discard(bs, offset, bytes, QCOW2_DISCARD_REQUEST,
3138 false);
3139 qemu_co_mutex_unlock(&s->lock);
3140 return ret;
3143 static int qcow2_truncate(BlockDriverState *bs, int64_t offset,
3144 PreallocMode prealloc, Error **errp)
3146 BDRVQcow2State *s = bs->opaque;
3147 uint64_t old_length;
3148 int64_t new_l1_size;
3149 int ret;
3151 if (prealloc != PREALLOC_MODE_OFF && prealloc != PREALLOC_MODE_METADATA &&
3152 prealloc != PREALLOC_MODE_FALLOC && prealloc != PREALLOC_MODE_FULL)
3154 error_setg(errp, "Unsupported preallocation mode '%s'",
3155 PreallocMode_str(prealloc));
3156 return -ENOTSUP;
3159 if (offset & 511) {
3160 error_setg(errp, "The new size must be a multiple of 512");
3161 return -EINVAL;
3164 /* cannot proceed if image has snapshots */
3165 if (s->nb_snapshots) {
3166 error_setg(errp, "Can't resize an image which has snapshots");
3167 return -ENOTSUP;
3170 /* cannot proceed if image has bitmaps */
3171 if (s->nb_bitmaps) {
3172 /* TODO: resize bitmaps in the image */
3173 error_setg(errp, "Can't resize an image which has bitmaps");
3174 return -ENOTSUP;
3177 old_length = bs->total_sectors * 512;
3178 new_l1_size = size_to_l1(s, offset);
3180 if (offset < old_length) {
3181 int64_t last_cluster, old_file_size;
3182 if (prealloc != PREALLOC_MODE_OFF) {
3183 error_setg(errp,
3184 "Preallocation can't be used for shrinking an image");
3185 return -EINVAL;
3188 ret = qcow2_cluster_discard(bs, ROUND_UP(offset, s->cluster_size),
3189 old_length - ROUND_UP(offset,
3190 s->cluster_size),
3191 QCOW2_DISCARD_ALWAYS, true);
3192 if (ret < 0) {
3193 error_setg_errno(errp, -ret, "Failed to discard cropped clusters");
3194 return ret;
3197 ret = qcow2_shrink_l1_table(bs, new_l1_size);
3198 if (ret < 0) {
3199 error_setg_errno(errp, -ret,
3200 "Failed to reduce the number of L2 tables");
3201 return ret;
3204 ret = qcow2_shrink_reftable(bs);
3205 if (ret < 0) {
3206 error_setg_errno(errp, -ret,
3207 "Failed to discard unused refblocks");
3208 return ret;
3211 old_file_size = bdrv_getlength(bs->file->bs);
3212 if (old_file_size < 0) {
3213 error_setg_errno(errp, -old_file_size,
3214 "Failed to inquire current file length");
3215 return old_file_size;
3217 last_cluster = qcow2_get_last_cluster(bs, old_file_size);
3218 if (last_cluster < 0) {
3219 error_setg_errno(errp, -last_cluster,
3220 "Failed to find the last cluster");
3221 return last_cluster;
3223 if ((last_cluster + 1) * s->cluster_size < old_file_size) {
3224 Error *local_err = NULL;
3226 bdrv_truncate(bs->file, (last_cluster + 1) * s->cluster_size,
3227 PREALLOC_MODE_OFF, &local_err);
3228 if (local_err) {
3229 warn_reportf_err(local_err,
3230 "Failed to truncate the tail of the image: ");
3233 } else {
3234 ret = qcow2_grow_l1_table(bs, new_l1_size, true);
3235 if (ret < 0) {
3236 error_setg_errno(errp, -ret, "Failed to grow the L1 table");
3237 return ret;
3241 switch (prealloc) {
3242 case PREALLOC_MODE_OFF:
3243 break;
3245 case PREALLOC_MODE_METADATA:
3246 ret = preallocate(bs, old_length, offset);
3247 if (ret < 0) {
3248 error_setg_errno(errp, -ret, "Preallocation failed");
3249 return ret;
3251 break;
3253 case PREALLOC_MODE_FALLOC:
3254 case PREALLOC_MODE_FULL:
3256 int64_t allocation_start, host_offset, guest_offset;
3257 int64_t clusters_allocated;
3258 int64_t old_file_size, new_file_size;
3259 uint64_t nb_new_data_clusters, nb_new_l2_tables;
3261 old_file_size = bdrv_getlength(bs->file->bs);
3262 if (old_file_size < 0) {
3263 error_setg_errno(errp, -old_file_size,
3264 "Failed to inquire current file length");
3265 return old_file_size;
3267 old_file_size = ROUND_UP(old_file_size, s->cluster_size);
3269 nb_new_data_clusters = DIV_ROUND_UP(offset - old_length,
3270 s->cluster_size);
3272 /* This is an overestimation; we will not actually allocate space for
3273 * these in the file but just make sure the new refcount structures are
3274 * able to cover them so we will not have to allocate new refblocks
3275 * while entering the data blocks in the potentially new L2 tables.
3276 * (We do not actually care where the L2 tables are placed. Maybe they
3277 * are already allocated or they can be placed somewhere before
3278 * @old_file_size. It does not matter because they will be fully
3279 * allocated automatically, so they do not need to be covered by the
3280 * preallocation. All that matters is that we will not have to allocate
3281 * new refcount structures for them.) */
3282 nb_new_l2_tables = DIV_ROUND_UP(nb_new_data_clusters,
3283 s->cluster_size / sizeof(uint64_t));
3284 /* The cluster range may not be aligned to L2 boundaries, so add one L2
3285 * table for a potential head/tail */
3286 nb_new_l2_tables++;
3288 allocation_start = qcow2_refcount_area(bs, old_file_size,
3289 nb_new_data_clusters +
3290 nb_new_l2_tables,
3291 true, 0, 0);
3292 if (allocation_start < 0) {
3293 error_setg_errno(errp, -allocation_start,
3294 "Failed to resize refcount structures");
3295 return allocation_start;
3298 clusters_allocated = qcow2_alloc_clusters_at(bs, allocation_start,
3299 nb_new_data_clusters);
3300 if (clusters_allocated < 0) {
3301 error_setg_errno(errp, -clusters_allocated,
3302 "Failed to allocate data clusters");
3303 return -clusters_allocated;
3306 assert(clusters_allocated == nb_new_data_clusters);
3308 /* Allocate the data area */
3309 new_file_size = allocation_start +
3310 nb_new_data_clusters * s->cluster_size;
3311 ret = bdrv_truncate(bs->file, new_file_size, prealloc, errp);
3312 if (ret < 0) {
3313 error_prepend(errp, "Failed to resize underlying file: ");
3314 qcow2_free_clusters(bs, allocation_start,
3315 nb_new_data_clusters * s->cluster_size,
3316 QCOW2_DISCARD_OTHER);
3317 return ret;
3320 /* Create the necessary L2 entries */
3321 host_offset = allocation_start;
3322 guest_offset = old_length;
3323 while (nb_new_data_clusters) {
3324 int64_t nb_clusters = MIN(
3325 nb_new_data_clusters,
3326 s->l2_slice_size - offset_to_l2_slice_index(s, guest_offset));
3327 QCowL2Meta allocation = {
3328 .offset = guest_offset,
3329 .alloc_offset = host_offset,
3330 .nb_clusters = nb_clusters,
3332 qemu_co_queue_init(&allocation.dependent_requests);
3334 ret = qcow2_alloc_cluster_link_l2(bs, &allocation);
3335 if (ret < 0) {
3336 error_setg_errno(errp, -ret, "Failed to update L2 tables");
3337 qcow2_free_clusters(bs, host_offset,
3338 nb_new_data_clusters * s->cluster_size,
3339 QCOW2_DISCARD_OTHER);
3340 return ret;
3343 guest_offset += nb_clusters * s->cluster_size;
3344 host_offset += nb_clusters * s->cluster_size;
3345 nb_new_data_clusters -= nb_clusters;
3347 break;
3350 default:
3351 g_assert_not_reached();
3354 if (prealloc != PREALLOC_MODE_OFF) {
3355 /* Flush metadata before actually changing the image size */
3356 ret = bdrv_flush(bs);
3357 if (ret < 0) {
3358 error_setg_errno(errp, -ret,
3359 "Failed to flush the preallocated area to disk");
3360 return ret;
3364 /* write updated header.size */
3365 offset = cpu_to_be64(offset);
3366 ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, size),
3367 &offset, sizeof(uint64_t));
3368 if (ret < 0) {
3369 error_setg_errno(errp, -ret, "Failed to update the image size");
3370 return ret;
3373 s->l1_vm_state_index = new_l1_size;
3374 return 0;
3377 /* XXX: put compressed sectors first, then all the cluster aligned
3378 tables to avoid losing bytes in alignment */
3379 static coroutine_fn int
3380 qcow2_co_pwritev_compressed(BlockDriverState *bs, uint64_t offset,
3381 uint64_t bytes, QEMUIOVector *qiov)
3383 BDRVQcow2State *s = bs->opaque;
3384 QEMUIOVector hd_qiov;
3385 struct iovec iov;
3386 z_stream strm;
3387 int ret, out_len;
3388 uint8_t *buf, *out_buf;
3389 int64_t cluster_offset;
3391 if (bytes == 0) {
3392 /* align end of file to a sector boundary to ease reading with
3393 sector based I/Os */
3394 cluster_offset = bdrv_getlength(bs->file->bs);
3395 if (cluster_offset < 0) {
3396 return cluster_offset;
3398 return bdrv_truncate(bs->file, cluster_offset, PREALLOC_MODE_OFF, NULL);
3401 if (offset_into_cluster(s, offset)) {
3402 return -EINVAL;
3405 buf = qemu_blockalign(bs, s->cluster_size);
3406 if (bytes != s->cluster_size) {
3407 if (bytes > s->cluster_size ||
3408 offset + bytes != bs->total_sectors << BDRV_SECTOR_BITS)
3410 qemu_vfree(buf);
3411 return -EINVAL;
3413 /* Zero-pad last write if image size is not cluster aligned */
3414 memset(buf + bytes, 0, s->cluster_size - bytes);
3416 qemu_iovec_to_buf(qiov, 0, buf, bytes);
3418 out_buf = g_malloc(s->cluster_size);
3420 /* best compression, small window, no zlib header */
3421 memset(&strm, 0, sizeof(strm));
3422 ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
3423 Z_DEFLATED, -12,
3424 9, Z_DEFAULT_STRATEGY);
3425 if (ret != 0) {
3426 ret = -EINVAL;
3427 goto fail;
3430 strm.avail_in = s->cluster_size;
3431 strm.next_in = (uint8_t *)buf;
3432 strm.avail_out = s->cluster_size;
3433 strm.next_out = out_buf;
3435 ret = deflate(&strm, Z_FINISH);
3436 if (ret != Z_STREAM_END && ret != Z_OK) {
3437 deflateEnd(&strm);
3438 ret = -EINVAL;
3439 goto fail;
3441 out_len = strm.next_out - out_buf;
3443 deflateEnd(&strm);
3445 if (ret != Z_STREAM_END || out_len >= s->cluster_size) {
3446 /* could not compress: write normal cluster */
3447 ret = qcow2_co_pwritev(bs, offset, bytes, qiov, 0);
3448 if (ret < 0) {
3449 goto fail;
3451 goto success;
3454 qemu_co_mutex_lock(&s->lock);
3455 cluster_offset =
3456 qcow2_alloc_compressed_cluster_offset(bs, offset, out_len);
3457 if (!cluster_offset) {
3458 qemu_co_mutex_unlock(&s->lock);
3459 ret = -EIO;
3460 goto fail;
3462 cluster_offset &= s->cluster_offset_mask;
3464 ret = qcow2_pre_write_overlap_check(bs, 0, cluster_offset, out_len);
3465 qemu_co_mutex_unlock(&s->lock);
3466 if (ret < 0) {
3467 goto fail;
3470 iov = (struct iovec) {
3471 .iov_base = out_buf,
3472 .iov_len = out_len,
3474 qemu_iovec_init_external(&hd_qiov, &iov, 1);
3476 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_COMPRESSED);
3477 ret = bdrv_co_pwritev(bs->file, cluster_offset, out_len, &hd_qiov, 0);
3478 if (ret < 0) {
3479 goto fail;
3481 success:
3482 ret = 0;
3483 fail:
3484 qemu_vfree(buf);
3485 g_free(out_buf);
3486 return ret;
3489 static int make_completely_empty(BlockDriverState *bs)
3491 BDRVQcow2State *s = bs->opaque;
3492 Error *local_err = NULL;
3493 int ret, l1_clusters;
3494 int64_t offset;
3495 uint64_t *new_reftable = NULL;
3496 uint64_t rt_entry, l1_size2;
3497 struct {
3498 uint64_t l1_offset;
3499 uint64_t reftable_offset;
3500 uint32_t reftable_clusters;
3501 } QEMU_PACKED l1_ofs_rt_ofs_cls;
3503 ret = qcow2_cache_empty(bs, s->l2_table_cache);
3504 if (ret < 0) {
3505 goto fail;
3508 ret = qcow2_cache_empty(bs, s->refcount_block_cache);
3509 if (ret < 0) {
3510 goto fail;
3513 /* Refcounts will be broken utterly */
3514 ret = qcow2_mark_dirty(bs);
3515 if (ret < 0) {
3516 goto fail;
3519 BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
3521 l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / sizeof(uint64_t));
3522 l1_size2 = (uint64_t)s->l1_size * sizeof(uint64_t);
3524 /* After this call, neither the in-memory nor the on-disk refcount
3525 * information accurately describe the actual references */
3527 ret = bdrv_pwrite_zeroes(bs->file, s->l1_table_offset,
3528 l1_clusters * s->cluster_size, 0);
3529 if (ret < 0) {
3530 goto fail_broken_refcounts;
3532 memset(s->l1_table, 0, l1_size2);
3534 BLKDBG_EVENT(bs->file, BLKDBG_EMPTY_IMAGE_PREPARE);
3536 /* Overwrite enough clusters at the beginning of the sectors to place
3537 * the refcount table, a refcount block and the L1 table in; this may
3538 * overwrite parts of the existing refcount and L1 table, which is not
3539 * an issue because the dirty flag is set, complete data loss is in fact
3540 * desired and partial data loss is consequently fine as well */
3541 ret = bdrv_pwrite_zeroes(bs->file, s->cluster_size,
3542 (2 + l1_clusters) * s->cluster_size, 0);
3543 /* This call (even if it failed overall) may have overwritten on-disk
3544 * refcount structures; in that case, the in-memory refcount information
3545 * will probably differ from the on-disk information which makes the BDS
3546 * unusable */
3547 if (ret < 0) {
3548 goto fail_broken_refcounts;
3551 BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
3552 BLKDBG_EVENT(bs->file, BLKDBG_REFTABLE_UPDATE);
3554 /* "Create" an empty reftable (one cluster) directly after the image
3555 * header and an empty L1 table three clusters after the image header;
3556 * the cluster between those two will be used as the first refblock */
3557 l1_ofs_rt_ofs_cls.l1_offset = cpu_to_be64(3 * s->cluster_size);
3558 l1_ofs_rt_ofs_cls.reftable_offset = cpu_to_be64(s->cluster_size);
3559 l1_ofs_rt_ofs_cls.reftable_clusters = cpu_to_be32(1);
3560 ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, l1_table_offset),
3561 &l1_ofs_rt_ofs_cls, sizeof(l1_ofs_rt_ofs_cls));
3562 if (ret < 0) {
3563 goto fail_broken_refcounts;
3566 s->l1_table_offset = 3 * s->cluster_size;
3568 new_reftable = g_try_new0(uint64_t, s->cluster_size / sizeof(uint64_t));
3569 if (!new_reftable) {
3570 ret = -ENOMEM;
3571 goto fail_broken_refcounts;
3574 s->refcount_table_offset = s->cluster_size;
3575 s->refcount_table_size = s->cluster_size / sizeof(uint64_t);
3576 s->max_refcount_table_index = 0;
3578 g_free(s->refcount_table);
3579 s->refcount_table = new_reftable;
3580 new_reftable = NULL;
3582 /* Now the in-memory refcount information again corresponds to the on-disk
3583 * information (reftable is empty and no refblocks (the refblock cache is
3584 * empty)); however, this means some clusters (e.g. the image header) are
3585 * referenced, but not refcounted, but the normal qcow2 code assumes that
3586 * the in-memory information is always correct */
3588 BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_ALLOC);
3590 /* Enter the first refblock into the reftable */
3591 rt_entry = cpu_to_be64(2 * s->cluster_size);
3592 ret = bdrv_pwrite_sync(bs->file, s->cluster_size,
3593 &rt_entry, sizeof(rt_entry));
3594 if (ret < 0) {
3595 goto fail_broken_refcounts;
3597 s->refcount_table[0] = 2 * s->cluster_size;
3599 s->free_cluster_index = 0;
3600 assert(3 + l1_clusters <= s->refcount_block_size);
3601 offset = qcow2_alloc_clusters(bs, 3 * s->cluster_size + l1_size2);
3602 if (offset < 0) {
3603 ret = offset;
3604 goto fail_broken_refcounts;
3605 } else if (offset > 0) {
3606 error_report("First cluster in emptied image is in use");
3607 abort();
3610 /* Now finally the in-memory information corresponds to the on-disk
3611 * structures and is correct */
3612 ret = qcow2_mark_clean(bs);
3613 if (ret < 0) {
3614 goto fail;
3617 ret = bdrv_truncate(bs->file, (3 + l1_clusters) * s->cluster_size,
3618 PREALLOC_MODE_OFF, &local_err);
3619 if (ret < 0) {
3620 error_report_err(local_err);
3621 goto fail;
3624 return 0;
3626 fail_broken_refcounts:
3627 /* The BDS is unusable at this point. If we wanted to make it usable, we
3628 * would have to call qcow2_refcount_close(), qcow2_refcount_init(),
3629 * qcow2_check_refcounts(), qcow2_refcount_close() and qcow2_refcount_init()
3630 * again. However, because the functions which could have caused this error
3631 * path to be taken are used by those functions as well, it's very likely
3632 * that that sequence will fail as well. Therefore, just eject the BDS. */
3633 bs->drv = NULL;
3635 fail:
3636 g_free(new_reftable);
3637 return ret;
3640 static int qcow2_make_empty(BlockDriverState *bs)
3642 BDRVQcow2State *s = bs->opaque;
3643 uint64_t offset, end_offset;
3644 int step = QEMU_ALIGN_DOWN(INT_MAX, s->cluster_size);
3645 int l1_clusters, ret = 0;
3647 l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / sizeof(uint64_t));
3649 if (s->qcow_version >= 3 && !s->snapshots && !s->nb_bitmaps &&
3650 3 + l1_clusters <= s->refcount_block_size &&
3651 s->crypt_method_header != QCOW_CRYPT_LUKS) {
3652 /* The following function only works for qcow2 v3 images (it
3653 * requires the dirty flag) and only as long as there are no
3654 * features that reserve extra clusters (such as snapshots,
3655 * LUKS header, or persistent bitmaps), because it completely
3656 * empties the image. Furthermore, the L1 table and three
3657 * additional clusters (image header, refcount table, one
3658 * refcount block) have to fit inside one refcount block. */
3659 return make_completely_empty(bs);
3662 /* This fallback code simply discards every active cluster; this is slow,
3663 * but works in all cases */
3664 end_offset = bs->total_sectors * BDRV_SECTOR_SIZE;
3665 for (offset = 0; offset < end_offset; offset += step) {
3666 /* As this function is generally used after committing an external
3667 * snapshot, QCOW2_DISCARD_SNAPSHOT seems appropriate. Also, the
3668 * default action for this kind of discard is to pass the discard,
3669 * which will ideally result in an actually smaller image file, as
3670 * is probably desired. */
3671 ret = qcow2_cluster_discard(bs, offset, MIN(step, end_offset - offset),
3672 QCOW2_DISCARD_SNAPSHOT, true);
3673 if (ret < 0) {
3674 break;
3678 return ret;
3681 static coroutine_fn int qcow2_co_flush_to_os(BlockDriverState *bs)
3683 BDRVQcow2State *s = bs->opaque;
3684 int ret;
3686 qemu_co_mutex_lock(&s->lock);
3687 ret = qcow2_write_caches(bs);
3688 qemu_co_mutex_unlock(&s->lock);
3690 return ret;
3693 static BlockMeasureInfo *qcow2_measure(QemuOpts *opts, BlockDriverState *in_bs,
3694 Error **errp)
3696 Error *local_err = NULL;
3697 BlockMeasureInfo *info;
3698 uint64_t required = 0; /* bytes that contribute to required size */
3699 uint64_t virtual_size; /* disk size as seen by guest */
3700 uint64_t refcount_bits;
3701 uint64_t l2_tables;
3702 size_t cluster_size;
3703 int version;
3704 char *optstr;
3705 PreallocMode prealloc;
3706 bool has_backing_file;
3708 /* Parse image creation options */
3709 cluster_size = qcow2_opt_get_cluster_size_del(opts, &local_err);
3710 if (local_err) {
3711 goto err;
3714 version = qcow2_opt_get_version_del(opts, &local_err);
3715 if (local_err) {
3716 goto err;
3719 refcount_bits = qcow2_opt_get_refcount_bits_del(opts, version, &local_err);
3720 if (local_err) {
3721 goto err;
3724 optstr = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
3725 prealloc = qapi_enum_parse(&PreallocMode_lookup, optstr,
3726 PREALLOC_MODE_OFF, &local_err);
3727 g_free(optstr);
3728 if (local_err) {
3729 goto err;
3732 optstr = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
3733 has_backing_file = !!optstr;
3734 g_free(optstr);
3736 virtual_size = qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0);
3737 virtual_size = ROUND_UP(virtual_size, cluster_size);
3739 /* Check that virtual disk size is valid */
3740 l2_tables = DIV_ROUND_UP(virtual_size / cluster_size,
3741 cluster_size / sizeof(uint64_t));
3742 if (l2_tables * sizeof(uint64_t) > QCOW_MAX_L1_SIZE) {
3743 error_setg(&local_err, "The image size is too large "
3744 "(try using a larger cluster size)");
3745 goto err;
3748 /* Account for input image */
3749 if (in_bs) {
3750 int64_t ssize = bdrv_getlength(in_bs);
3751 if (ssize < 0) {
3752 error_setg_errno(&local_err, -ssize,
3753 "Unable to get image virtual_size");
3754 goto err;
3757 virtual_size = ROUND_UP(ssize, cluster_size);
3759 if (has_backing_file) {
3760 /* We don't how much of the backing chain is shared by the input
3761 * image and the new image file. In the worst case the new image's
3762 * backing file has nothing in common with the input image. Be
3763 * conservative and assume all clusters need to be written.
3765 required = virtual_size;
3766 } else {
3767 int64_t offset;
3768 int64_t pnum = 0;
3770 for (offset = 0; offset < ssize; offset += pnum) {
3771 int ret;
3773 ret = bdrv_block_status_above(in_bs, NULL, offset,
3774 ssize - offset, &pnum, NULL,
3775 NULL);
3776 if (ret < 0) {
3777 error_setg_errno(&local_err, -ret,
3778 "Unable to get block status");
3779 goto err;
3782 if (ret & BDRV_BLOCK_ZERO) {
3783 /* Skip zero regions (safe with no backing file) */
3784 } else if ((ret & (BDRV_BLOCK_DATA | BDRV_BLOCK_ALLOCATED)) ==
3785 (BDRV_BLOCK_DATA | BDRV_BLOCK_ALLOCATED)) {
3786 /* Extend pnum to end of cluster for next iteration */
3787 pnum = ROUND_UP(offset + pnum, cluster_size) - offset;
3789 /* Count clusters we've seen */
3790 required += offset % cluster_size + pnum;
3796 /* Take into account preallocation. Nothing special is needed for
3797 * PREALLOC_MODE_METADATA since metadata is always counted.
3799 if (prealloc == PREALLOC_MODE_FULL || prealloc == PREALLOC_MODE_FALLOC) {
3800 required = virtual_size;
3803 info = g_new(BlockMeasureInfo, 1);
3804 info->fully_allocated =
3805 qcow2_calc_prealloc_size(virtual_size, cluster_size,
3806 ctz32(refcount_bits));
3808 /* Remove data clusters that are not required. This overestimates the
3809 * required size because metadata needed for the fully allocated file is
3810 * still counted.
3812 info->required = info->fully_allocated - virtual_size + required;
3813 return info;
3815 err:
3816 error_propagate(errp, local_err);
3817 return NULL;
3820 static int qcow2_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
3822 BDRVQcow2State *s = bs->opaque;
3823 bdi->unallocated_blocks_are_zero = true;
3824 bdi->cluster_size = s->cluster_size;
3825 bdi->vm_state_offset = qcow2_vm_state_offset(s);
3826 return 0;
3829 static ImageInfoSpecific *qcow2_get_specific_info(BlockDriverState *bs)
3831 BDRVQcow2State *s = bs->opaque;
3832 ImageInfoSpecific *spec_info;
3833 QCryptoBlockInfo *encrypt_info = NULL;
3835 if (s->crypto != NULL) {
3836 encrypt_info = qcrypto_block_get_info(s->crypto, &error_abort);
3839 spec_info = g_new(ImageInfoSpecific, 1);
3840 *spec_info = (ImageInfoSpecific){
3841 .type = IMAGE_INFO_SPECIFIC_KIND_QCOW2,
3842 .u.qcow2.data = g_new(ImageInfoSpecificQCow2, 1),
3844 if (s->qcow_version == 2) {
3845 *spec_info->u.qcow2.data = (ImageInfoSpecificQCow2){
3846 .compat = g_strdup("0.10"),
3847 .refcount_bits = s->refcount_bits,
3849 } else if (s->qcow_version == 3) {
3850 *spec_info->u.qcow2.data = (ImageInfoSpecificQCow2){
3851 .compat = g_strdup("1.1"),
3852 .lazy_refcounts = s->compatible_features &
3853 QCOW2_COMPAT_LAZY_REFCOUNTS,
3854 .has_lazy_refcounts = true,
3855 .corrupt = s->incompatible_features &
3856 QCOW2_INCOMPAT_CORRUPT,
3857 .has_corrupt = true,
3858 .refcount_bits = s->refcount_bits,
3860 } else {
3861 /* if this assertion fails, this probably means a new version was
3862 * added without having it covered here */
3863 assert(false);
3866 if (encrypt_info) {
3867 ImageInfoSpecificQCow2Encryption *qencrypt =
3868 g_new(ImageInfoSpecificQCow2Encryption, 1);
3869 switch (encrypt_info->format) {
3870 case Q_CRYPTO_BLOCK_FORMAT_QCOW:
3871 qencrypt->format = BLOCKDEV_QCOW2_ENCRYPTION_FORMAT_AES;
3872 qencrypt->u.aes = encrypt_info->u.qcow;
3873 break;
3874 case Q_CRYPTO_BLOCK_FORMAT_LUKS:
3875 qencrypt->format = BLOCKDEV_QCOW2_ENCRYPTION_FORMAT_LUKS;
3876 qencrypt->u.luks = encrypt_info->u.luks;
3877 break;
3878 default:
3879 abort();
3881 /* Since we did shallow copy above, erase any pointers
3882 * in the original info */
3883 memset(&encrypt_info->u, 0, sizeof(encrypt_info->u));
3884 qapi_free_QCryptoBlockInfo(encrypt_info);
3886 spec_info->u.qcow2.data->has_encrypt = true;
3887 spec_info->u.qcow2.data->encrypt = qencrypt;
3890 return spec_info;
3893 static int qcow2_save_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
3894 int64_t pos)
3896 BDRVQcow2State *s = bs->opaque;
3898 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_SAVE);
3899 return bs->drv->bdrv_co_pwritev(bs, qcow2_vm_state_offset(s) + pos,
3900 qiov->size, qiov, 0);
3903 static int qcow2_load_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
3904 int64_t pos)
3906 BDRVQcow2State *s = bs->opaque;
3908 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_LOAD);
3909 return bs->drv->bdrv_co_preadv(bs, qcow2_vm_state_offset(s) + pos,
3910 qiov->size, qiov, 0);
3914 * Downgrades an image's version. To achieve this, any incompatible features
3915 * have to be removed.
3917 static int qcow2_downgrade(BlockDriverState *bs, int target_version,
3918 BlockDriverAmendStatusCB *status_cb, void *cb_opaque)
3920 BDRVQcow2State *s = bs->opaque;
3921 int current_version = s->qcow_version;
3922 int ret;
3924 if (target_version == current_version) {
3925 return 0;
3926 } else if (target_version > current_version) {
3927 return -EINVAL;
3928 } else if (target_version != 2) {
3929 return -EINVAL;
3932 if (s->refcount_order != 4) {
3933 error_report("compat=0.10 requires refcount_bits=16");
3934 return -ENOTSUP;
3937 /* clear incompatible features */
3938 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
3939 ret = qcow2_mark_clean(bs);
3940 if (ret < 0) {
3941 return ret;
3945 /* with QCOW2_INCOMPAT_CORRUPT, it is pretty much impossible to get here in
3946 * the first place; if that happens nonetheless, returning -ENOTSUP is the
3947 * best thing to do anyway */
3949 if (s->incompatible_features) {
3950 return -ENOTSUP;
3953 /* since we can ignore compatible features, we can set them to 0 as well */
3954 s->compatible_features = 0;
3955 /* if lazy refcounts have been used, they have already been fixed through
3956 * clearing the dirty flag */
3958 /* clearing autoclear features is trivial */
3959 s->autoclear_features = 0;
3961 ret = qcow2_expand_zero_clusters(bs, status_cb, cb_opaque);
3962 if (ret < 0) {
3963 return ret;
3966 s->qcow_version = target_version;
3967 ret = qcow2_update_header(bs);
3968 if (ret < 0) {
3969 s->qcow_version = current_version;
3970 return ret;
3972 return 0;
3975 typedef enum Qcow2AmendOperation {
3976 /* This is the value Qcow2AmendHelperCBInfo::last_operation will be
3977 * statically initialized to so that the helper CB can discern the first
3978 * invocation from an operation change */
3979 QCOW2_NO_OPERATION = 0,
3981 QCOW2_CHANGING_REFCOUNT_ORDER,
3982 QCOW2_DOWNGRADING,
3983 } Qcow2AmendOperation;
3985 typedef struct Qcow2AmendHelperCBInfo {
3986 /* The code coordinating the amend operations should only modify
3987 * these four fields; the rest will be managed by the CB */
3988 BlockDriverAmendStatusCB *original_status_cb;
3989 void *original_cb_opaque;
3991 Qcow2AmendOperation current_operation;
3993 /* Total number of operations to perform (only set once) */
3994 int total_operations;
3996 /* The following fields are managed by the CB */
3998 /* Number of operations completed */
3999 int operations_completed;
4001 /* Cumulative offset of all completed operations */
4002 int64_t offset_completed;
4004 Qcow2AmendOperation last_operation;
4005 int64_t last_work_size;
4006 } Qcow2AmendHelperCBInfo;
4008 static void qcow2_amend_helper_cb(BlockDriverState *bs,
4009 int64_t operation_offset,
4010 int64_t operation_work_size, void *opaque)
4012 Qcow2AmendHelperCBInfo *info = opaque;
4013 int64_t current_work_size;
4014 int64_t projected_work_size;
4016 if (info->current_operation != info->last_operation) {
4017 if (info->last_operation != QCOW2_NO_OPERATION) {
4018 info->offset_completed += info->last_work_size;
4019 info->operations_completed++;
4022 info->last_operation = info->current_operation;
4025 assert(info->total_operations > 0);
4026 assert(info->operations_completed < info->total_operations);
4028 info->last_work_size = operation_work_size;
4030 current_work_size = info->offset_completed + operation_work_size;
4032 /* current_work_size is the total work size for (operations_completed + 1)
4033 * operations (which includes this one), so multiply it by the number of
4034 * operations not covered and divide it by the number of operations
4035 * covered to get a projection for the operations not covered */
4036 projected_work_size = current_work_size * (info->total_operations -
4037 info->operations_completed - 1)
4038 / (info->operations_completed + 1);
4040 info->original_status_cb(bs, info->offset_completed + operation_offset,
4041 current_work_size + projected_work_size,
4042 info->original_cb_opaque);
4045 static int qcow2_amend_options(BlockDriverState *bs, QemuOpts *opts,
4046 BlockDriverAmendStatusCB *status_cb,
4047 void *cb_opaque)
4049 BDRVQcow2State *s = bs->opaque;
4050 int old_version = s->qcow_version, new_version = old_version;
4051 uint64_t new_size = 0;
4052 const char *backing_file = NULL, *backing_format = NULL;
4053 bool lazy_refcounts = s->use_lazy_refcounts;
4054 const char *compat = NULL;
4055 uint64_t cluster_size = s->cluster_size;
4056 bool encrypt;
4057 int encformat;
4058 int refcount_bits = s->refcount_bits;
4059 Error *local_err = NULL;
4060 int ret;
4061 QemuOptDesc *desc = opts->list->desc;
4062 Qcow2AmendHelperCBInfo helper_cb_info;
4064 while (desc && desc->name) {
4065 if (!qemu_opt_find(opts, desc->name)) {
4066 /* only change explicitly defined options */
4067 desc++;
4068 continue;
4071 if (!strcmp(desc->name, BLOCK_OPT_COMPAT_LEVEL)) {
4072 compat = qemu_opt_get(opts, BLOCK_OPT_COMPAT_LEVEL);
4073 if (!compat) {
4074 /* preserve default */
4075 } else if (!strcmp(compat, "0.10")) {
4076 new_version = 2;
4077 } else if (!strcmp(compat, "1.1")) {
4078 new_version = 3;
4079 } else {
4080 error_report("Unknown compatibility level %s", compat);
4081 return -EINVAL;
4083 } else if (!strcmp(desc->name, BLOCK_OPT_PREALLOC)) {
4084 error_report("Cannot change preallocation mode");
4085 return -ENOTSUP;
4086 } else if (!strcmp(desc->name, BLOCK_OPT_SIZE)) {
4087 new_size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, 0);
4088 } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FILE)) {
4089 backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
4090 } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FMT)) {
4091 backing_format = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
4092 } else if (!strcmp(desc->name, BLOCK_OPT_ENCRYPT)) {
4093 encrypt = qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT,
4094 !!s->crypto);
4096 if (encrypt != !!s->crypto) {
4097 error_report("Changing the encryption flag is not supported");
4098 return -ENOTSUP;
4100 } else if (!strcmp(desc->name, BLOCK_OPT_ENCRYPT_FORMAT)) {
4101 encformat = qcow2_crypt_method_from_format(
4102 qemu_opt_get(opts, BLOCK_OPT_ENCRYPT_FORMAT));
4104 if (encformat != s->crypt_method_header) {
4105 error_report("Changing the encryption format is not supported");
4106 return -ENOTSUP;
4108 } else if (g_str_has_prefix(desc->name, "encrypt.")) {
4109 error_report("Changing the encryption parameters is not supported");
4110 return -ENOTSUP;
4111 } else if (!strcmp(desc->name, BLOCK_OPT_CLUSTER_SIZE)) {
4112 cluster_size = qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE,
4113 cluster_size);
4114 if (cluster_size != s->cluster_size) {
4115 error_report("Changing the cluster size is not supported");
4116 return -ENOTSUP;
4118 } else if (!strcmp(desc->name, BLOCK_OPT_LAZY_REFCOUNTS)) {
4119 lazy_refcounts = qemu_opt_get_bool(opts, BLOCK_OPT_LAZY_REFCOUNTS,
4120 lazy_refcounts);
4121 } else if (!strcmp(desc->name, BLOCK_OPT_REFCOUNT_BITS)) {
4122 refcount_bits = qemu_opt_get_number(opts, BLOCK_OPT_REFCOUNT_BITS,
4123 refcount_bits);
4125 if (refcount_bits <= 0 || refcount_bits > 64 ||
4126 !is_power_of_2(refcount_bits))
4128 error_report("Refcount width must be a power of two and may "
4129 "not exceed 64 bits");
4130 return -EINVAL;
4132 } else {
4133 /* if this point is reached, this probably means a new option was
4134 * added without having it covered here */
4135 abort();
4138 desc++;
4141 helper_cb_info = (Qcow2AmendHelperCBInfo){
4142 .original_status_cb = status_cb,
4143 .original_cb_opaque = cb_opaque,
4144 .total_operations = (new_version < old_version)
4145 + (s->refcount_bits != refcount_bits)
4148 /* Upgrade first (some features may require compat=1.1) */
4149 if (new_version > old_version) {
4150 s->qcow_version = new_version;
4151 ret = qcow2_update_header(bs);
4152 if (ret < 0) {
4153 s->qcow_version = old_version;
4154 return ret;
4158 if (s->refcount_bits != refcount_bits) {
4159 int refcount_order = ctz32(refcount_bits);
4161 if (new_version < 3 && refcount_bits != 16) {
4162 error_report("Different refcount widths than 16 bits require "
4163 "compatibility level 1.1 or above (use compat=1.1 or "
4164 "greater)");
4165 return -EINVAL;
4168 helper_cb_info.current_operation = QCOW2_CHANGING_REFCOUNT_ORDER;
4169 ret = qcow2_change_refcount_order(bs, refcount_order,
4170 &qcow2_amend_helper_cb,
4171 &helper_cb_info, &local_err);
4172 if (ret < 0) {
4173 error_report_err(local_err);
4174 return ret;
4178 if (backing_file || backing_format) {
4179 ret = qcow2_change_backing_file(bs,
4180 backing_file ?: s->image_backing_file,
4181 backing_format ?: s->image_backing_format);
4182 if (ret < 0) {
4183 return ret;
4187 if (s->use_lazy_refcounts != lazy_refcounts) {
4188 if (lazy_refcounts) {
4189 if (new_version < 3) {
4190 error_report("Lazy refcounts only supported with compatibility "
4191 "level 1.1 and above (use compat=1.1 or greater)");
4192 return -EINVAL;
4194 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
4195 ret = qcow2_update_header(bs);
4196 if (ret < 0) {
4197 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
4198 return ret;
4200 s->use_lazy_refcounts = true;
4201 } else {
4202 /* make image clean first */
4203 ret = qcow2_mark_clean(bs);
4204 if (ret < 0) {
4205 return ret;
4207 /* now disallow lazy refcounts */
4208 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
4209 ret = qcow2_update_header(bs);
4210 if (ret < 0) {
4211 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
4212 return ret;
4214 s->use_lazy_refcounts = false;
4218 if (new_size) {
4219 BlockBackend *blk = blk_new(BLK_PERM_RESIZE, BLK_PERM_ALL);
4220 ret = blk_insert_bs(blk, bs, &local_err);
4221 if (ret < 0) {
4222 error_report_err(local_err);
4223 blk_unref(blk);
4224 return ret;
4227 ret = blk_truncate(blk, new_size, PREALLOC_MODE_OFF, &local_err);
4228 blk_unref(blk);
4229 if (ret < 0) {
4230 error_report_err(local_err);
4231 return ret;
4235 /* Downgrade last (so unsupported features can be removed before) */
4236 if (new_version < old_version) {
4237 helper_cb_info.current_operation = QCOW2_DOWNGRADING;
4238 ret = qcow2_downgrade(bs, new_version, &qcow2_amend_helper_cb,
4239 &helper_cb_info);
4240 if (ret < 0) {
4241 return ret;
4245 return 0;
4249 * If offset or size are negative, respectively, they will not be included in
4250 * the BLOCK_IMAGE_CORRUPTED event emitted.
4251 * fatal will be ignored for read-only BDS; corruptions found there will always
4252 * be considered non-fatal.
4254 void qcow2_signal_corruption(BlockDriverState *bs, bool fatal, int64_t offset,
4255 int64_t size, const char *message_format, ...)
4257 BDRVQcow2State *s = bs->opaque;
4258 const char *node_name;
4259 char *message;
4260 va_list ap;
4262 fatal = fatal && !bs->read_only;
4264 if (s->signaled_corruption &&
4265 (!fatal || (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT)))
4267 return;
4270 va_start(ap, message_format);
4271 message = g_strdup_vprintf(message_format, ap);
4272 va_end(ap);
4274 if (fatal) {
4275 fprintf(stderr, "qcow2: Marking image as corrupt: %s; further "
4276 "corruption events will be suppressed\n", message);
4277 } else {
4278 fprintf(stderr, "qcow2: Image is corrupt: %s; further non-fatal "
4279 "corruption events will be suppressed\n", message);
4282 node_name = bdrv_get_node_name(bs);
4283 qapi_event_send_block_image_corrupted(bdrv_get_device_name(bs),
4284 *node_name != '\0', node_name,
4285 message, offset >= 0, offset,
4286 size >= 0, size,
4287 fatal, &error_abort);
4288 g_free(message);
4290 if (fatal) {
4291 qcow2_mark_corrupt(bs);
4292 bs->drv = NULL; /* make BDS unusable */
4295 s->signaled_corruption = true;
4298 static QemuOptsList qcow2_create_opts = {
4299 .name = "qcow2-create-opts",
4300 .head = QTAILQ_HEAD_INITIALIZER(qcow2_create_opts.head),
4301 .desc = {
4303 .name = BLOCK_OPT_SIZE,
4304 .type = QEMU_OPT_SIZE,
4305 .help = "Virtual disk size"
4308 .name = BLOCK_OPT_COMPAT_LEVEL,
4309 .type = QEMU_OPT_STRING,
4310 .help = "Compatibility level (0.10 or 1.1)"
4313 .name = BLOCK_OPT_BACKING_FILE,
4314 .type = QEMU_OPT_STRING,
4315 .help = "File name of a base image"
4318 .name = BLOCK_OPT_BACKING_FMT,
4319 .type = QEMU_OPT_STRING,
4320 .help = "Image format of the base image"
4323 .name = BLOCK_OPT_ENCRYPT,
4324 .type = QEMU_OPT_BOOL,
4325 .help = "Encrypt the image with format 'aes'. (Deprecated "
4326 "in favor of " BLOCK_OPT_ENCRYPT_FORMAT "=aes)",
4329 .name = BLOCK_OPT_ENCRYPT_FORMAT,
4330 .type = QEMU_OPT_STRING,
4331 .help = "Encrypt the image, format choices: 'aes', 'luks'",
4333 BLOCK_CRYPTO_OPT_DEF_KEY_SECRET("encrypt.",
4334 "ID of secret providing qcow AES key or LUKS passphrase"),
4335 BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_ALG("encrypt."),
4336 BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_MODE("encrypt."),
4337 BLOCK_CRYPTO_OPT_DEF_LUKS_IVGEN_ALG("encrypt."),
4338 BLOCK_CRYPTO_OPT_DEF_LUKS_IVGEN_HASH_ALG("encrypt."),
4339 BLOCK_CRYPTO_OPT_DEF_LUKS_HASH_ALG("encrypt."),
4340 BLOCK_CRYPTO_OPT_DEF_LUKS_ITER_TIME("encrypt."),
4342 .name = BLOCK_OPT_CLUSTER_SIZE,
4343 .type = QEMU_OPT_SIZE,
4344 .help = "qcow2 cluster size",
4345 .def_value_str = stringify(DEFAULT_CLUSTER_SIZE)
4348 .name = BLOCK_OPT_PREALLOC,
4349 .type = QEMU_OPT_STRING,
4350 .help = "Preallocation mode (allowed values: off, metadata, "
4351 "falloc, full)"
4354 .name = BLOCK_OPT_LAZY_REFCOUNTS,
4355 .type = QEMU_OPT_BOOL,
4356 .help = "Postpone refcount updates",
4357 .def_value_str = "off"
4360 .name = BLOCK_OPT_REFCOUNT_BITS,
4361 .type = QEMU_OPT_NUMBER,
4362 .help = "Width of a reference count entry in bits",
4363 .def_value_str = "16"
4365 { /* end of list */ }
4369 BlockDriver bdrv_qcow2 = {
4370 .format_name = "qcow2",
4371 .instance_size = sizeof(BDRVQcow2State),
4372 .bdrv_probe = qcow2_probe,
4373 .bdrv_open = qcow2_open,
4374 .bdrv_close = qcow2_close,
4375 .bdrv_reopen_prepare = qcow2_reopen_prepare,
4376 .bdrv_reopen_commit = qcow2_reopen_commit,
4377 .bdrv_reopen_abort = qcow2_reopen_abort,
4378 .bdrv_join_options = qcow2_join_options,
4379 .bdrv_child_perm = bdrv_format_default_perms,
4380 .bdrv_co_create_opts = qcow2_co_create_opts,
4381 .bdrv_has_zero_init = bdrv_has_zero_init_1,
4382 .bdrv_co_block_status = qcow2_co_block_status,
4384 .bdrv_co_preadv = qcow2_co_preadv,
4385 .bdrv_co_pwritev = qcow2_co_pwritev,
4386 .bdrv_co_flush_to_os = qcow2_co_flush_to_os,
4388 .bdrv_co_pwrite_zeroes = qcow2_co_pwrite_zeroes,
4389 .bdrv_co_pdiscard = qcow2_co_pdiscard,
4390 .bdrv_truncate = qcow2_truncate,
4391 .bdrv_co_pwritev_compressed = qcow2_co_pwritev_compressed,
4392 .bdrv_make_empty = qcow2_make_empty,
4394 .bdrv_snapshot_create = qcow2_snapshot_create,
4395 .bdrv_snapshot_goto = qcow2_snapshot_goto,
4396 .bdrv_snapshot_delete = qcow2_snapshot_delete,
4397 .bdrv_snapshot_list = qcow2_snapshot_list,
4398 .bdrv_snapshot_load_tmp = qcow2_snapshot_load_tmp,
4399 .bdrv_measure = qcow2_measure,
4400 .bdrv_get_info = qcow2_get_info,
4401 .bdrv_get_specific_info = qcow2_get_specific_info,
4403 .bdrv_save_vmstate = qcow2_save_vmstate,
4404 .bdrv_load_vmstate = qcow2_load_vmstate,
4406 .supports_backing = true,
4407 .bdrv_change_backing_file = qcow2_change_backing_file,
4409 .bdrv_refresh_limits = qcow2_refresh_limits,
4410 .bdrv_co_invalidate_cache = qcow2_co_invalidate_cache,
4411 .bdrv_inactivate = qcow2_inactivate,
4413 .create_opts = &qcow2_create_opts,
4414 .bdrv_co_check = qcow2_co_check,
4415 .bdrv_amend_options = qcow2_amend_options,
4417 .bdrv_detach_aio_context = qcow2_detach_aio_context,
4418 .bdrv_attach_aio_context = qcow2_attach_aio_context,
4420 .bdrv_reopen_bitmaps_rw = qcow2_reopen_bitmaps_rw,
4421 .bdrv_can_store_new_dirty_bitmap = qcow2_can_store_new_dirty_bitmap,
4422 .bdrv_remove_persistent_dirty_bitmap = qcow2_remove_persistent_dirty_bitmap,
4425 static void bdrv_qcow2_init(void)
4427 bdrv_register(&bdrv_qcow2);
4430 block_init(bdrv_qcow2_init);