qcow2: try load bitmaps only once
[qemu/kevin.git] / block / qcow2.c
blobef68772acad052b1321cefa98bcdb6422c1d09c2
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/qobject-input-visitor.h"
41 #include "qapi/qapi-visit-block-core.h"
42 #include "block/crypto.h"
45 Differences with QCOW:
47 - Support for multiple incremental snapshots.
48 - Memory management by reference counts.
49 - Clusters which have a reference count of one have the bit
50 QCOW_OFLAG_COPIED to optimize write performance.
51 - Size of compressed clusters is stored in sectors to reduce bit usage
52 in the cluster offsets.
53 - Support for storing additional data (such as the VM state) in the
54 snapshots.
55 - If a backing store is used, the cluster size is not constrained
56 (could be backported to QCOW).
57 - L2 tables have always a size of one cluster.
61 typedef struct {
62 uint32_t magic;
63 uint32_t len;
64 } QEMU_PACKED QCowExtension;
66 #define QCOW2_EXT_MAGIC_END 0
67 #define QCOW2_EXT_MAGIC_BACKING_FORMAT 0xE2792ACA
68 #define QCOW2_EXT_MAGIC_FEATURE_TABLE 0x6803f857
69 #define QCOW2_EXT_MAGIC_CRYPTO_HEADER 0x0537be77
70 #define QCOW2_EXT_MAGIC_BITMAPS 0x23852875
72 static int qcow2_probe(const uint8_t *buf, int buf_size, const char *filename)
74 const QCowHeader *cow_header = (const void *)buf;
76 if (buf_size >= sizeof(QCowHeader) &&
77 be32_to_cpu(cow_header->magic) == QCOW_MAGIC &&
78 be32_to_cpu(cow_header->version) >= 2)
79 return 100;
80 else
81 return 0;
85 static ssize_t qcow2_crypto_hdr_read_func(QCryptoBlock *block, size_t offset,
86 uint8_t *buf, size_t buflen,
87 void *opaque, Error **errp)
89 BlockDriverState *bs = opaque;
90 BDRVQcow2State *s = bs->opaque;
91 ssize_t ret;
93 if ((offset + buflen) > s->crypto_header.length) {
94 error_setg(errp, "Request for data outside of extension header");
95 return -1;
98 ret = bdrv_pread(bs->file,
99 s->crypto_header.offset + offset, buf, buflen);
100 if (ret < 0) {
101 error_setg_errno(errp, -ret, "Could not read encryption header");
102 return -1;
104 return ret;
108 static ssize_t qcow2_crypto_hdr_init_func(QCryptoBlock *block, size_t headerlen,
109 void *opaque, Error **errp)
111 BlockDriverState *bs = opaque;
112 BDRVQcow2State *s = bs->opaque;
113 int64_t ret;
114 int64_t clusterlen;
116 ret = qcow2_alloc_clusters(bs, headerlen);
117 if (ret < 0) {
118 error_setg_errno(errp, -ret,
119 "Cannot allocate cluster for LUKS header size %zu",
120 headerlen);
121 return -1;
124 s->crypto_header.length = headerlen;
125 s->crypto_header.offset = ret;
127 /* Zero fill remaining space in cluster so it has predictable
128 * content in case of future spec changes */
129 clusterlen = size_to_clusters(s, headerlen) * s->cluster_size;
130 assert(qcow2_pre_write_overlap_check(bs, 0, ret, clusterlen) == 0);
131 ret = bdrv_pwrite_zeroes(bs->file,
132 ret + headerlen,
133 clusterlen - headerlen, 0);
134 if (ret < 0) {
135 error_setg_errno(errp, -ret, "Could not zero fill encryption header");
136 return -1;
139 return ret;
143 static ssize_t qcow2_crypto_hdr_write_func(QCryptoBlock *block, size_t offset,
144 const uint8_t *buf, size_t buflen,
145 void *opaque, Error **errp)
147 BlockDriverState *bs = opaque;
148 BDRVQcow2State *s = bs->opaque;
149 ssize_t ret;
151 if ((offset + buflen) > s->crypto_header.length) {
152 error_setg(errp, "Request for data outside of extension header");
153 return -1;
156 ret = bdrv_pwrite(bs->file,
157 s->crypto_header.offset + offset, buf, buflen);
158 if (ret < 0) {
159 error_setg_errno(errp, -ret, "Could not read encryption header");
160 return -1;
162 return ret;
167 * read qcow2 extension and fill bs
168 * start reading from start_offset
169 * finish reading upon magic of value 0 or when end_offset reached
170 * unknown magic is skipped (future extension this version knows nothing about)
171 * return 0 upon success, non-0 otherwise
173 static int qcow2_read_extensions(BlockDriverState *bs, uint64_t start_offset,
174 uint64_t end_offset, void **p_feature_table,
175 int flags, bool *need_update_header,
176 Error **errp)
178 BDRVQcow2State *s = bs->opaque;
179 QCowExtension ext;
180 uint64_t offset;
181 int ret;
182 Qcow2BitmapHeaderExt bitmaps_ext;
184 if (need_update_header != NULL) {
185 *need_update_header = false;
188 #ifdef DEBUG_EXT
189 printf("qcow2_read_extensions: start=%ld end=%ld\n", start_offset, end_offset);
190 #endif
191 offset = start_offset;
192 while (offset < end_offset) {
194 #ifdef DEBUG_EXT
195 /* Sanity check */
196 if (offset > s->cluster_size)
197 printf("qcow2_read_extension: suspicious offset %lu\n", offset);
199 printf("attempting to read extended header in offset %lu\n", offset);
200 #endif
202 ret = bdrv_pread(bs->file, offset, &ext, sizeof(ext));
203 if (ret < 0) {
204 error_setg_errno(errp, -ret, "qcow2_read_extension: ERROR: "
205 "pread fail from offset %" PRIu64, offset);
206 return 1;
208 be32_to_cpus(&ext.magic);
209 be32_to_cpus(&ext.len);
210 offset += sizeof(ext);
211 #ifdef DEBUG_EXT
212 printf("ext.magic = 0x%x\n", ext.magic);
213 #endif
214 if (offset > end_offset || ext.len > end_offset - offset) {
215 error_setg(errp, "Header extension too large");
216 return -EINVAL;
219 switch (ext.magic) {
220 case QCOW2_EXT_MAGIC_END:
221 return 0;
223 case QCOW2_EXT_MAGIC_BACKING_FORMAT:
224 if (ext.len >= sizeof(bs->backing_format)) {
225 error_setg(errp, "ERROR: ext_backing_format: len=%" PRIu32
226 " too large (>=%zu)", ext.len,
227 sizeof(bs->backing_format));
228 return 2;
230 ret = bdrv_pread(bs->file, offset, bs->backing_format, ext.len);
231 if (ret < 0) {
232 error_setg_errno(errp, -ret, "ERROR: ext_backing_format: "
233 "Could not read format name");
234 return 3;
236 bs->backing_format[ext.len] = '\0';
237 s->image_backing_format = g_strdup(bs->backing_format);
238 #ifdef DEBUG_EXT
239 printf("Qcow2: Got format extension %s\n", bs->backing_format);
240 #endif
241 break;
243 case QCOW2_EXT_MAGIC_FEATURE_TABLE:
244 if (p_feature_table != NULL) {
245 void* feature_table = g_malloc0(ext.len + 2 * sizeof(Qcow2Feature));
246 ret = bdrv_pread(bs->file, offset , feature_table, ext.len);
247 if (ret < 0) {
248 error_setg_errno(errp, -ret, "ERROR: ext_feature_table: "
249 "Could not read table");
250 return ret;
253 *p_feature_table = feature_table;
255 break;
257 case QCOW2_EXT_MAGIC_CRYPTO_HEADER: {
258 unsigned int cflags = 0;
259 if (s->crypt_method_header != QCOW_CRYPT_LUKS) {
260 error_setg(errp, "CRYPTO header extension only "
261 "expected with LUKS encryption method");
262 return -EINVAL;
264 if (ext.len != sizeof(Qcow2CryptoHeaderExtension)) {
265 error_setg(errp, "CRYPTO header extension size %u, "
266 "but expected size %zu", ext.len,
267 sizeof(Qcow2CryptoHeaderExtension));
268 return -EINVAL;
271 ret = bdrv_pread(bs->file, offset, &s->crypto_header, ext.len);
272 if (ret < 0) {
273 error_setg_errno(errp, -ret,
274 "Unable to read CRYPTO header extension");
275 return ret;
277 be64_to_cpus(&s->crypto_header.offset);
278 be64_to_cpus(&s->crypto_header.length);
280 if ((s->crypto_header.offset % s->cluster_size) != 0) {
281 error_setg(errp, "Encryption header offset '%" PRIu64 "' is "
282 "not a multiple of cluster size '%u'",
283 s->crypto_header.offset, s->cluster_size);
284 return -EINVAL;
287 if (flags & BDRV_O_NO_IO) {
288 cflags |= QCRYPTO_BLOCK_OPEN_NO_IO;
290 s->crypto = qcrypto_block_open(s->crypto_opts, "encrypt.",
291 qcow2_crypto_hdr_read_func,
292 bs, cflags, errp);
293 if (!s->crypto) {
294 return -EINVAL;
296 } break;
298 case QCOW2_EXT_MAGIC_BITMAPS:
299 if (ext.len != sizeof(bitmaps_ext)) {
300 error_setg_errno(errp, -ret, "bitmaps_ext: "
301 "Invalid extension length");
302 return -EINVAL;
305 if (!(s->autoclear_features & QCOW2_AUTOCLEAR_BITMAPS)) {
306 if (s->qcow_version < 3) {
307 /* Let's be a bit more specific */
308 warn_report("This qcow2 v2 image contains bitmaps, but "
309 "they may have been modified by a program "
310 "without persistent bitmap support; so now "
311 "they must all be considered inconsistent");
312 } else {
313 warn_report("a program lacking bitmap support "
314 "modified this file, so all bitmaps are now "
315 "considered inconsistent");
317 error_printf("Some clusters may be leaked, "
318 "run 'qemu-img check -r' on the image "
319 "file to fix.");
320 if (need_update_header != NULL) {
321 /* Updating is needed to drop invalid bitmap extension. */
322 *need_update_header = true;
324 break;
327 ret = bdrv_pread(bs->file, offset, &bitmaps_ext, ext.len);
328 if (ret < 0) {
329 error_setg_errno(errp, -ret, "bitmaps_ext: "
330 "Could not read ext header");
331 return ret;
334 if (bitmaps_ext.reserved32 != 0) {
335 error_setg_errno(errp, -ret, "bitmaps_ext: "
336 "Reserved field is not zero");
337 return -EINVAL;
340 be32_to_cpus(&bitmaps_ext.nb_bitmaps);
341 be64_to_cpus(&bitmaps_ext.bitmap_directory_size);
342 be64_to_cpus(&bitmaps_ext.bitmap_directory_offset);
344 if (bitmaps_ext.nb_bitmaps > QCOW2_MAX_BITMAPS) {
345 error_setg(errp,
346 "bitmaps_ext: Image has %" PRIu32 " bitmaps, "
347 "exceeding the QEMU supported maximum of %d",
348 bitmaps_ext.nb_bitmaps, QCOW2_MAX_BITMAPS);
349 return -EINVAL;
352 if (bitmaps_ext.nb_bitmaps == 0) {
353 error_setg(errp, "found bitmaps extension with zero bitmaps");
354 return -EINVAL;
357 if (bitmaps_ext.bitmap_directory_offset & (s->cluster_size - 1)) {
358 error_setg(errp, "bitmaps_ext: "
359 "invalid bitmap directory offset");
360 return -EINVAL;
363 if (bitmaps_ext.bitmap_directory_size >
364 QCOW2_MAX_BITMAP_DIRECTORY_SIZE) {
365 error_setg(errp, "bitmaps_ext: "
366 "bitmap directory size (%" PRIu64 ") exceeds "
367 "the maximum supported size (%d)",
368 bitmaps_ext.bitmap_directory_size,
369 QCOW2_MAX_BITMAP_DIRECTORY_SIZE);
370 return -EINVAL;
373 s->nb_bitmaps = bitmaps_ext.nb_bitmaps;
374 s->bitmap_directory_offset =
375 bitmaps_ext.bitmap_directory_offset;
376 s->bitmap_directory_size =
377 bitmaps_ext.bitmap_directory_size;
379 #ifdef DEBUG_EXT
380 printf("Qcow2: Got bitmaps extension: "
381 "offset=%" PRIu64 " nb_bitmaps=%" PRIu32 "\n",
382 s->bitmap_directory_offset, s->nb_bitmaps);
383 #endif
384 break;
386 default:
387 /* unknown magic - save it in case we need to rewrite the header */
388 /* If you add a new feature, make sure to also update the fast
389 * path of qcow2_make_empty() to deal with it. */
391 Qcow2UnknownHeaderExtension *uext;
393 uext = g_malloc0(sizeof(*uext) + ext.len);
394 uext->magic = ext.magic;
395 uext->len = ext.len;
396 QLIST_INSERT_HEAD(&s->unknown_header_ext, uext, next);
398 ret = bdrv_pread(bs->file, offset , uext->data, uext->len);
399 if (ret < 0) {
400 error_setg_errno(errp, -ret, "ERROR: unknown extension: "
401 "Could not read data");
402 return ret;
405 break;
408 offset += ((ext.len + 7) & ~7);
411 return 0;
414 static void cleanup_unknown_header_ext(BlockDriverState *bs)
416 BDRVQcow2State *s = bs->opaque;
417 Qcow2UnknownHeaderExtension *uext, *next;
419 QLIST_FOREACH_SAFE(uext, &s->unknown_header_ext, next, next) {
420 QLIST_REMOVE(uext, next);
421 g_free(uext);
425 static void report_unsupported_feature(Error **errp, Qcow2Feature *table,
426 uint64_t mask)
428 char *features = g_strdup("");
429 char *old;
431 while (table && table->name[0] != '\0') {
432 if (table->type == QCOW2_FEAT_TYPE_INCOMPATIBLE) {
433 if (mask & (1ULL << table->bit)) {
434 old = features;
435 features = g_strdup_printf("%s%s%.46s", old, *old ? ", " : "",
436 table->name);
437 g_free(old);
438 mask &= ~(1ULL << table->bit);
441 table++;
444 if (mask) {
445 old = features;
446 features = g_strdup_printf("%s%sUnknown incompatible feature: %" PRIx64,
447 old, *old ? ", " : "", mask);
448 g_free(old);
451 error_setg(errp, "Unsupported qcow2 feature(s): %s", features);
452 g_free(features);
456 * Sets the dirty bit and flushes afterwards if necessary.
458 * The incompatible_features bit is only set if the image file header was
459 * updated successfully. Therefore it is not required to check the return
460 * value of this function.
462 int qcow2_mark_dirty(BlockDriverState *bs)
464 BDRVQcow2State *s = bs->opaque;
465 uint64_t val;
466 int ret;
468 assert(s->qcow_version >= 3);
470 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
471 return 0; /* already dirty */
474 val = cpu_to_be64(s->incompatible_features | QCOW2_INCOMPAT_DIRTY);
475 ret = bdrv_pwrite(bs->file, offsetof(QCowHeader, incompatible_features),
476 &val, sizeof(val));
477 if (ret < 0) {
478 return ret;
480 ret = bdrv_flush(bs->file->bs);
481 if (ret < 0) {
482 return ret;
485 /* Only treat image as dirty if the header was updated successfully */
486 s->incompatible_features |= QCOW2_INCOMPAT_DIRTY;
487 return 0;
491 * Clears the dirty bit and flushes before if necessary. Only call this
492 * function when there are no pending requests, it does not guard against
493 * concurrent requests dirtying the image.
495 static int qcow2_mark_clean(BlockDriverState *bs)
497 BDRVQcow2State *s = bs->opaque;
499 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
500 int ret;
502 s->incompatible_features &= ~QCOW2_INCOMPAT_DIRTY;
504 ret = qcow2_flush_caches(bs);
505 if (ret < 0) {
506 return ret;
509 return qcow2_update_header(bs);
511 return 0;
515 * Marks the image as corrupt.
517 int qcow2_mark_corrupt(BlockDriverState *bs)
519 BDRVQcow2State *s = bs->opaque;
521 s->incompatible_features |= QCOW2_INCOMPAT_CORRUPT;
522 return qcow2_update_header(bs);
526 * Marks the image as consistent, i.e., unsets the corrupt bit, and flushes
527 * before if necessary.
529 int qcow2_mark_consistent(BlockDriverState *bs)
531 BDRVQcow2State *s = bs->opaque;
533 if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
534 int ret = qcow2_flush_caches(bs);
535 if (ret < 0) {
536 return ret;
539 s->incompatible_features &= ~QCOW2_INCOMPAT_CORRUPT;
540 return qcow2_update_header(bs);
542 return 0;
545 static int coroutine_fn qcow2_co_check_locked(BlockDriverState *bs,
546 BdrvCheckResult *result,
547 BdrvCheckMode fix)
549 int ret = qcow2_check_refcounts(bs, result, fix);
550 if (ret < 0) {
551 return ret;
554 if (fix && result->check_errors == 0 && result->corruptions == 0) {
555 ret = qcow2_mark_clean(bs);
556 if (ret < 0) {
557 return ret;
559 return qcow2_mark_consistent(bs);
561 return ret;
564 static int coroutine_fn qcow2_co_check(BlockDriverState *bs,
565 BdrvCheckResult *result,
566 BdrvCheckMode fix)
568 BDRVQcow2State *s = bs->opaque;
569 int ret;
571 qemu_co_mutex_lock(&s->lock);
572 ret = qcow2_co_check_locked(bs, result, fix);
573 qemu_co_mutex_unlock(&s->lock);
574 return ret;
577 int qcow2_validate_table(BlockDriverState *bs, uint64_t offset,
578 uint64_t entries, size_t entry_len,
579 int64_t max_size_bytes, const char *table_name,
580 Error **errp)
582 BDRVQcow2State *s = bs->opaque;
584 if (entries > max_size_bytes / entry_len) {
585 error_setg(errp, "%s too large", table_name);
586 return -EFBIG;
589 /* Use signed INT64_MAX as the maximum even for uint64_t header fields,
590 * because values will be passed to qemu functions taking int64_t. */
591 if ((INT64_MAX - entries * entry_len < offset) ||
592 (offset_into_cluster(s, offset) != 0)) {
593 error_setg(errp, "%s offset invalid", table_name);
594 return -EINVAL;
597 return 0;
600 static QemuOptsList qcow2_runtime_opts = {
601 .name = "qcow2",
602 .head = QTAILQ_HEAD_INITIALIZER(qcow2_runtime_opts.head),
603 .desc = {
605 .name = QCOW2_OPT_LAZY_REFCOUNTS,
606 .type = QEMU_OPT_BOOL,
607 .help = "Postpone refcount updates",
610 .name = QCOW2_OPT_DISCARD_REQUEST,
611 .type = QEMU_OPT_BOOL,
612 .help = "Pass guest discard requests to the layer below",
615 .name = QCOW2_OPT_DISCARD_SNAPSHOT,
616 .type = QEMU_OPT_BOOL,
617 .help = "Generate discard requests when snapshot related space "
618 "is freed",
621 .name = QCOW2_OPT_DISCARD_OTHER,
622 .type = QEMU_OPT_BOOL,
623 .help = "Generate discard requests when other clusters are freed",
626 .name = QCOW2_OPT_OVERLAP,
627 .type = QEMU_OPT_STRING,
628 .help = "Selects which overlap checks to perform from a range of "
629 "templates (none, constant, cached, all)",
632 .name = QCOW2_OPT_OVERLAP_TEMPLATE,
633 .type = QEMU_OPT_STRING,
634 .help = "Selects which overlap checks to perform from a range of "
635 "templates (none, constant, cached, all)",
638 .name = QCOW2_OPT_OVERLAP_MAIN_HEADER,
639 .type = QEMU_OPT_BOOL,
640 .help = "Check for unintended writes into the main qcow2 header",
643 .name = QCOW2_OPT_OVERLAP_ACTIVE_L1,
644 .type = QEMU_OPT_BOOL,
645 .help = "Check for unintended writes into the active L1 table",
648 .name = QCOW2_OPT_OVERLAP_ACTIVE_L2,
649 .type = QEMU_OPT_BOOL,
650 .help = "Check for unintended writes into an active L2 table",
653 .name = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
654 .type = QEMU_OPT_BOOL,
655 .help = "Check for unintended writes into the refcount table",
658 .name = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
659 .type = QEMU_OPT_BOOL,
660 .help = "Check for unintended writes into a refcount block",
663 .name = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
664 .type = QEMU_OPT_BOOL,
665 .help = "Check for unintended writes into the snapshot table",
668 .name = QCOW2_OPT_OVERLAP_INACTIVE_L1,
669 .type = QEMU_OPT_BOOL,
670 .help = "Check for unintended writes into an inactive L1 table",
673 .name = QCOW2_OPT_OVERLAP_INACTIVE_L2,
674 .type = QEMU_OPT_BOOL,
675 .help = "Check for unintended writes into an inactive L2 table",
678 .name = QCOW2_OPT_CACHE_SIZE,
679 .type = QEMU_OPT_SIZE,
680 .help = "Maximum combined metadata (L2 tables and refcount blocks) "
681 "cache size",
684 .name = QCOW2_OPT_L2_CACHE_SIZE,
685 .type = QEMU_OPT_SIZE,
686 .help = "Maximum L2 table cache size",
689 .name = QCOW2_OPT_L2_CACHE_ENTRY_SIZE,
690 .type = QEMU_OPT_SIZE,
691 .help = "Size of each entry in the L2 cache",
694 .name = QCOW2_OPT_REFCOUNT_CACHE_SIZE,
695 .type = QEMU_OPT_SIZE,
696 .help = "Maximum refcount block cache size",
699 .name = QCOW2_OPT_CACHE_CLEAN_INTERVAL,
700 .type = QEMU_OPT_NUMBER,
701 .help = "Clean unused cache entries after this time (in seconds)",
703 BLOCK_CRYPTO_OPT_DEF_KEY_SECRET("encrypt.",
704 "ID of secret providing qcow2 AES key or LUKS passphrase"),
705 { /* end of list */ }
709 static const char *overlap_bool_option_names[QCOW2_OL_MAX_BITNR] = {
710 [QCOW2_OL_MAIN_HEADER_BITNR] = QCOW2_OPT_OVERLAP_MAIN_HEADER,
711 [QCOW2_OL_ACTIVE_L1_BITNR] = QCOW2_OPT_OVERLAP_ACTIVE_L1,
712 [QCOW2_OL_ACTIVE_L2_BITNR] = QCOW2_OPT_OVERLAP_ACTIVE_L2,
713 [QCOW2_OL_REFCOUNT_TABLE_BITNR] = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
714 [QCOW2_OL_REFCOUNT_BLOCK_BITNR] = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
715 [QCOW2_OL_SNAPSHOT_TABLE_BITNR] = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
716 [QCOW2_OL_INACTIVE_L1_BITNR] = QCOW2_OPT_OVERLAP_INACTIVE_L1,
717 [QCOW2_OL_INACTIVE_L2_BITNR] = QCOW2_OPT_OVERLAP_INACTIVE_L2,
720 static void cache_clean_timer_cb(void *opaque)
722 BlockDriverState *bs = opaque;
723 BDRVQcow2State *s = bs->opaque;
724 qcow2_cache_clean_unused(s->l2_table_cache);
725 qcow2_cache_clean_unused(s->refcount_block_cache);
726 timer_mod(s->cache_clean_timer, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) +
727 (int64_t) s->cache_clean_interval * 1000);
730 static void cache_clean_timer_init(BlockDriverState *bs, AioContext *context)
732 BDRVQcow2State *s = bs->opaque;
733 if (s->cache_clean_interval > 0) {
734 s->cache_clean_timer = aio_timer_new(context, QEMU_CLOCK_VIRTUAL,
735 SCALE_MS, cache_clean_timer_cb,
736 bs);
737 timer_mod(s->cache_clean_timer, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) +
738 (int64_t) s->cache_clean_interval * 1000);
742 static void cache_clean_timer_del(BlockDriverState *bs)
744 BDRVQcow2State *s = bs->opaque;
745 if (s->cache_clean_timer) {
746 timer_del(s->cache_clean_timer);
747 timer_free(s->cache_clean_timer);
748 s->cache_clean_timer = NULL;
752 static void qcow2_detach_aio_context(BlockDriverState *bs)
754 cache_clean_timer_del(bs);
757 static void qcow2_attach_aio_context(BlockDriverState *bs,
758 AioContext *new_context)
760 cache_clean_timer_init(bs, new_context);
763 static void read_cache_sizes(BlockDriverState *bs, QemuOpts *opts,
764 uint64_t *l2_cache_size,
765 uint64_t *l2_cache_entry_size,
766 uint64_t *refcount_cache_size, Error **errp)
768 BDRVQcow2State *s = bs->opaque;
769 uint64_t combined_cache_size;
770 bool l2_cache_size_set, refcount_cache_size_set, combined_cache_size_set;
772 combined_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_CACHE_SIZE);
773 l2_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_L2_CACHE_SIZE);
774 refcount_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
776 combined_cache_size = qemu_opt_get_size(opts, QCOW2_OPT_CACHE_SIZE, 0);
777 *l2_cache_size = qemu_opt_get_size(opts, QCOW2_OPT_L2_CACHE_SIZE, 0);
778 *refcount_cache_size = qemu_opt_get_size(opts,
779 QCOW2_OPT_REFCOUNT_CACHE_SIZE, 0);
781 *l2_cache_entry_size = qemu_opt_get_size(
782 opts, QCOW2_OPT_L2_CACHE_ENTRY_SIZE, s->cluster_size);
784 if (combined_cache_size_set) {
785 if (l2_cache_size_set && refcount_cache_size_set) {
786 error_setg(errp, QCOW2_OPT_CACHE_SIZE ", " QCOW2_OPT_L2_CACHE_SIZE
787 " and " QCOW2_OPT_REFCOUNT_CACHE_SIZE " may not be set "
788 "the same time");
789 return;
790 } else if (*l2_cache_size > combined_cache_size) {
791 error_setg(errp, QCOW2_OPT_L2_CACHE_SIZE " may not exceed "
792 QCOW2_OPT_CACHE_SIZE);
793 return;
794 } else if (*refcount_cache_size > combined_cache_size) {
795 error_setg(errp, QCOW2_OPT_REFCOUNT_CACHE_SIZE " may not exceed "
796 QCOW2_OPT_CACHE_SIZE);
797 return;
800 if (l2_cache_size_set) {
801 *refcount_cache_size = combined_cache_size - *l2_cache_size;
802 } else if (refcount_cache_size_set) {
803 *l2_cache_size = combined_cache_size - *refcount_cache_size;
804 } else {
805 *refcount_cache_size = combined_cache_size
806 / (DEFAULT_L2_REFCOUNT_SIZE_RATIO + 1);
807 *l2_cache_size = combined_cache_size - *refcount_cache_size;
809 } else {
810 if (!l2_cache_size_set && !refcount_cache_size_set) {
811 *l2_cache_size = MAX(DEFAULT_L2_CACHE_BYTE_SIZE,
812 (uint64_t)DEFAULT_L2_CACHE_CLUSTERS
813 * s->cluster_size);
814 *refcount_cache_size = *l2_cache_size
815 / DEFAULT_L2_REFCOUNT_SIZE_RATIO;
816 } else if (!l2_cache_size_set) {
817 *l2_cache_size = *refcount_cache_size
818 * DEFAULT_L2_REFCOUNT_SIZE_RATIO;
819 } else if (!refcount_cache_size_set) {
820 *refcount_cache_size = *l2_cache_size
821 / DEFAULT_L2_REFCOUNT_SIZE_RATIO;
825 if (*l2_cache_entry_size < (1 << MIN_CLUSTER_BITS) ||
826 *l2_cache_entry_size > s->cluster_size ||
827 !is_power_of_2(*l2_cache_entry_size)) {
828 error_setg(errp, "L2 cache entry size must be a power of two "
829 "between %d and the cluster size (%d)",
830 1 << MIN_CLUSTER_BITS, s->cluster_size);
831 return;
835 typedef struct Qcow2ReopenState {
836 Qcow2Cache *l2_table_cache;
837 Qcow2Cache *refcount_block_cache;
838 int l2_slice_size; /* Number of entries in a slice of the L2 table */
839 bool use_lazy_refcounts;
840 int overlap_check;
841 bool discard_passthrough[QCOW2_DISCARD_MAX];
842 uint64_t cache_clean_interval;
843 QCryptoBlockOpenOptions *crypto_opts; /* Disk encryption runtime options */
844 } Qcow2ReopenState;
846 static int qcow2_update_options_prepare(BlockDriverState *bs,
847 Qcow2ReopenState *r,
848 QDict *options, int flags,
849 Error **errp)
851 BDRVQcow2State *s = bs->opaque;
852 QemuOpts *opts = NULL;
853 const char *opt_overlap_check, *opt_overlap_check_template;
854 int overlap_check_template = 0;
855 uint64_t l2_cache_size, l2_cache_entry_size, refcount_cache_size;
856 int i;
857 const char *encryptfmt;
858 QDict *encryptopts = NULL;
859 Error *local_err = NULL;
860 int ret;
862 qdict_extract_subqdict(options, &encryptopts, "encrypt.");
863 encryptfmt = qdict_get_try_str(encryptopts, "format");
865 opts = qemu_opts_create(&qcow2_runtime_opts, NULL, 0, &error_abort);
866 qemu_opts_absorb_qdict(opts, options, &local_err);
867 if (local_err) {
868 error_propagate(errp, local_err);
869 ret = -EINVAL;
870 goto fail;
873 /* get L2 table/refcount block cache size from command line options */
874 read_cache_sizes(bs, opts, &l2_cache_size, &l2_cache_entry_size,
875 &refcount_cache_size, &local_err);
876 if (local_err) {
877 error_propagate(errp, local_err);
878 ret = -EINVAL;
879 goto fail;
882 l2_cache_size /= l2_cache_entry_size;
883 if (l2_cache_size < MIN_L2_CACHE_SIZE) {
884 l2_cache_size = MIN_L2_CACHE_SIZE;
886 if (l2_cache_size > INT_MAX) {
887 error_setg(errp, "L2 cache size too big");
888 ret = -EINVAL;
889 goto fail;
892 refcount_cache_size /= s->cluster_size;
893 if (refcount_cache_size < MIN_REFCOUNT_CACHE_SIZE) {
894 refcount_cache_size = MIN_REFCOUNT_CACHE_SIZE;
896 if (refcount_cache_size > INT_MAX) {
897 error_setg(errp, "Refcount cache size too big");
898 ret = -EINVAL;
899 goto fail;
902 /* alloc new L2 table/refcount block cache, flush old one */
903 if (s->l2_table_cache) {
904 ret = qcow2_cache_flush(bs, s->l2_table_cache);
905 if (ret) {
906 error_setg_errno(errp, -ret, "Failed to flush the L2 table cache");
907 goto fail;
911 if (s->refcount_block_cache) {
912 ret = qcow2_cache_flush(bs, s->refcount_block_cache);
913 if (ret) {
914 error_setg_errno(errp, -ret,
915 "Failed to flush the refcount block cache");
916 goto fail;
920 r->l2_slice_size = l2_cache_entry_size / sizeof(uint64_t);
921 r->l2_table_cache = qcow2_cache_create(bs, l2_cache_size,
922 l2_cache_entry_size);
923 r->refcount_block_cache = qcow2_cache_create(bs, refcount_cache_size,
924 s->cluster_size);
925 if (r->l2_table_cache == NULL || r->refcount_block_cache == NULL) {
926 error_setg(errp, "Could not allocate metadata caches");
927 ret = -ENOMEM;
928 goto fail;
931 /* New interval for cache cleanup timer */
932 r->cache_clean_interval =
933 qemu_opt_get_number(opts, QCOW2_OPT_CACHE_CLEAN_INTERVAL,
934 s->cache_clean_interval);
935 #ifndef CONFIG_LINUX
936 if (r->cache_clean_interval != 0) {
937 error_setg(errp, QCOW2_OPT_CACHE_CLEAN_INTERVAL
938 " not supported on this host");
939 ret = -EINVAL;
940 goto fail;
942 #endif
943 if (r->cache_clean_interval > UINT_MAX) {
944 error_setg(errp, "Cache clean interval too big");
945 ret = -EINVAL;
946 goto fail;
949 /* lazy-refcounts; flush if going from enabled to disabled */
950 r->use_lazy_refcounts = qemu_opt_get_bool(opts, QCOW2_OPT_LAZY_REFCOUNTS,
951 (s->compatible_features & QCOW2_COMPAT_LAZY_REFCOUNTS));
952 if (r->use_lazy_refcounts && s->qcow_version < 3) {
953 error_setg(errp, "Lazy refcounts require a qcow2 image with at least "
954 "qemu 1.1 compatibility level");
955 ret = -EINVAL;
956 goto fail;
959 if (s->use_lazy_refcounts && !r->use_lazy_refcounts) {
960 ret = qcow2_mark_clean(bs);
961 if (ret < 0) {
962 error_setg_errno(errp, -ret, "Failed to disable lazy refcounts");
963 goto fail;
967 /* Overlap check options */
968 opt_overlap_check = qemu_opt_get(opts, QCOW2_OPT_OVERLAP);
969 opt_overlap_check_template = qemu_opt_get(opts, QCOW2_OPT_OVERLAP_TEMPLATE);
970 if (opt_overlap_check_template && opt_overlap_check &&
971 strcmp(opt_overlap_check_template, opt_overlap_check))
973 error_setg(errp, "Conflicting values for qcow2 options '"
974 QCOW2_OPT_OVERLAP "' ('%s') and '" QCOW2_OPT_OVERLAP_TEMPLATE
975 "' ('%s')", opt_overlap_check, opt_overlap_check_template);
976 ret = -EINVAL;
977 goto fail;
979 if (!opt_overlap_check) {
980 opt_overlap_check = opt_overlap_check_template ?: "cached";
983 if (!strcmp(opt_overlap_check, "none")) {
984 overlap_check_template = 0;
985 } else if (!strcmp(opt_overlap_check, "constant")) {
986 overlap_check_template = QCOW2_OL_CONSTANT;
987 } else if (!strcmp(opt_overlap_check, "cached")) {
988 overlap_check_template = QCOW2_OL_CACHED;
989 } else if (!strcmp(opt_overlap_check, "all")) {
990 overlap_check_template = QCOW2_OL_ALL;
991 } else {
992 error_setg(errp, "Unsupported value '%s' for qcow2 option "
993 "'overlap-check'. Allowed are any of the following: "
994 "none, constant, cached, all", opt_overlap_check);
995 ret = -EINVAL;
996 goto fail;
999 r->overlap_check = 0;
1000 for (i = 0; i < QCOW2_OL_MAX_BITNR; i++) {
1001 /* overlap-check defines a template bitmask, but every flag may be
1002 * overwritten through the associated boolean option */
1003 r->overlap_check |=
1004 qemu_opt_get_bool(opts, overlap_bool_option_names[i],
1005 overlap_check_template & (1 << i)) << i;
1008 r->discard_passthrough[QCOW2_DISCARD_NEVER] = false;
1009 r->discard_passthrough[QCOW2_DISCARD_ALWAYS] = true;
1010 r->discard_passthrough[QCOW2_DISCARD_REQUEST] =
1011 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_REQUEST,
1012 flags & BDRV_O_UNMAP);
1013 r->discard_passthrough[QCOW2_DISCARD_SNAPSHOT] =
1014 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_SNAPSHOT, true);
1015 r->discard_passthrough[QCOW2_DISCARD_OTHER] =
1016 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_OTHER, false);
1018 switch (s->crypt_method_header) {
1019 case QCOW_CRYPT_NONE:
1020 if (encryptfmt) {
1021 error_setg(errp, "No encryption in image header, but options "
1022 "specified format '%s'", encryptfmt);
1023 ret = -EINVAL;
1024 goto fail;
1026 break;
1028 case QCOW_CRYPT_AES:
1029 if (encryptfmt && !g_str_equal(encryptfmt, "aes")) {
1030 error_setg(errp,
1031 "Header reported 'aes' encryption format but "
1032 "options specify '%s'", encryptfmt);
1033 ret = -EINVAL;
1034 goto fail;
1036 qdict_del(encryptopts, "format");
1037 r->crypto_opts = block_crypto_open_opts_init(
1038 Q_CRYPTO_BLOCK_FORMAT_QCOW, encryptopts, errp);
1039 break;
1041 case QCOW_CRYPT_LUKS:
1042 if (encryptfmt && !g_str_equal(encryptfmt, "luks")) {
1043 error_setg(errp,
1044 "Header reported 'luks' encryption format but "
1045 "options specify '%s'", encryptfmt);
1046 ret = -EINVAL;
1047 goto fail;
1049 qdict_del(encryptopts, "format");
1050 r->crypto_opts = block_crypto_open_opts_init(
1051 Q_CRYPTO_BLOCK_FORMAT_LUKS, encryptopts, errp);
1052 break;
1054 default:
1055 error_setg(errp, "Unsupported encryption method %d",
1056 s->crypt_method_header);
1057 break;
1059 if (s->crypt_method_header != QCOW_CRYPT_NONE && !r->crypto_opts) {
1060 ret = -EINVAL;
1061 goto fail;
1064 ret = 0;
1065 fail:
1066 QDECREF(encryptopts);
1067 qemu_opts_del(opts);
1068 opts = NULL;
1069 return ret;
1072 static void qcow2_update_options_commit(BlockDriverState *bs,
1073 Qcow2ReopenState *r)
1075 BDRVQcow2State *s = bs->opaque;
1076 int i;
1078 if (s->l2_table_cache) {
1079 qcow2_cache_destroy(s->l2_table_cache);
1081 if (s->refcount_block_cache) {
1082 qcow2_cache_destroy(s->refcount_block_cache);
1084 s->l2_table_cache = r->l2_table_cache;
1085 s->refcount_block_cache = r->refcount_block_cache;
1086 s->l2_slice_size = r->l2_slice_size;
1088 s->overlap_check = r->overlap_check;
1089 s->use_lazy_refcounts = r->use_lazy_refcounts;
1091 for (i = 0; i < QCOW2_DISCARD_MAX; i++) {
1092 s->discard_passthrough[i] = r->discard_passthrough[i];
1095 if (s->cache_clean_interval != r->cache_clean_interval) {
1096 cache_clean_timer_del(bs);
1097 s->cache_clean_interval = r->cache_clean_interval;
1098 cache_clean_timer_init(bs, bdrv_get_aio_context(bs));
1101 qapi_free_QCryptoBlockOpenOptions(s->crypto_opts);
1102 s->crypto_opts = r->crypto_opts;
1105 static void qcow2_update_options_abort(BlockDriverState *bs,
1106 Qcow2ReopenState *r)
1108 if (r->l2_table_cache) {
1109 qcow2_cache_destroy(r->l2_table_cache);
1111 if (r->refcount_block_cache) {
1112 qcow2_cache_destroy(r->refcount_block_cache);
1114 qapi_free_QCryptoBlockOpenOptions(r->crypto_opts);
1117 static int qcow2_update_options(BlockDriverState *bs, QDict *options,
1118 int flags, Error **errp)
1120 Qcow2ReopenState r = {};
1121 int ret;
1123 ret = qcow2_update_options_prepare(bs, &r, options, flags, errp);
1124 if (ret >= 0) {
1125 qcow2_update_options_commit(bs, &r);
1126 } else {
1127 qcow2_update_options_abort(bs, &r);
1130 return ret;
1133 /* Called with s->lock held. */
1134 static int coroutine_fn qcow2_do_open(BlockDriverState *bs, QDict *options,
1135 int flags, Error **errp)
1137 BDRVQcow2State *s = bs->opaque;
1138 unsigned int len, i;
1139 int ret = 0;
1140 QCowHeader header;
1141 Error *local_err = NULL;
1142 uint64_t ext_end;
1143 uint64_t l1_vm_state_index;
1144 bool update_header = false;
1145 bool header_updated = false;
1147 ret = bdrv_pread(bs->file, 0, &header, sizeof(header));
1148 if (ret < 0) {
1149 error_setg_errno(errp, -ret, "Could not read qcow2 header");
1150 goto fail;
1152 be32_to_cpus(&header.magic);
1153 be32_to_cpus(&header.version);
1154 be64_to_cpus(&header.backing_file_offset);
1155 be32_to_cpus(&header.backing_file_size);
1156 be64_to_cpus(&header.size);
1157 be32_to_cpus(&header.cluster_bits);
1158 be32_to_cpus(&header.crypt_method);
1159 be64_to_cpus(&header.l1_table_offset);
1160 be32_to_cpus(&header.l1_size);
1161 be64_to_cpus(&header.refcount_table_offset);
1162 be32_to_cpus(&header.refcount_table_clusters);
1163 be64_to_cpus(&header.snapshots_offset);
1164 be32_to_cpus(&header.nb_snapshots);
1166 if (header.magic != QCOW_MAGIC) {
1167 error_setg(errp, "Image is not in qcow2 format");
1168 ret = -EINVAL;
1169 goto fail;
1171 if (header.version < 2 || header.version > 3) {
1172 error_setg(errp, "Unsupported qcow2 version %" PRIu32, header.version);
1173 ret = -ENOTSUP;
1174 goto fail;
1177 s->qcow_version = header.version;
1179 /* Initialise cluster size */
1180 if (header.cluster_bits < MIN_CLUSTER_BITS ||
1181 header.cluster_bits > MAX_CLUSTER_BITS) {
1182 error_setg(errp, "Unsupported cluster size: 2^%" PRIu32,
1183 header.cluster_bits);
1184 ret = -EINVAL;
1185 goto fail;
1188 s->cluster_bits = header.cluster_bits;
1189 s->cluster_size = 1 << s->cluster_bits;
1190 s->cluster_sectors = 1 << (s->cluster_bits - BDRV_SECTOR_BITS);
1192 /* Initialise version 3 header fields */
1193 if (header.version == 2) {
1194 header.incompatible_features = 0;
1195 header.compatible_features = 0;
1196 header.autoclear_features = 0;
1197 header.refcount_order = 4;
1198 header.header_length = 72;
1199 } else {
1200 be64_to_cpus(&header.incompatible_features);
1201 be64_to_cpus(&header.compatible_features);
1202 be64_to_cpus(&header.autoclear_features);
1203 be32_to_cpus(&header.refcount_order);
1204 be32_to_cpus(&header.header_length);
1206 if (header.header_length < 104) {
1207 error_setg(errp, "qcow2 header too short");
1208 ret = -EINVAL;
1209 goto fail;
1213 if (header.header_length > s->cluster_size) {
1214 error_setg(errp, "qcow2 header exceeds cluster size");
1215 ret = -EINVAL;
1216 goto fail;
1219 if (header.header_length > sizeof(header)) {
1220 s->unknown_header_fields_size = header.header_length - sizeof(header);
1221 s->unknown_header_fields = g_malloc(s->unknown_header_fields_size);
1222 ret = bdrv_pread(bs->file, sizeof(header), s->unknown_header_fields,
1223 s->unknown_header_fields_size);
1224 if (ret < 0) {
1225 error_setg_errno(errp, -ret, "Could not read unknown qcow2 header "
1226 "fields");
1227 goto fail;
1231 if (header.backing_file_offset > s->cluster_size) {
1232 error_setg(errp, "Invalid backing file offset");
1233 ret = -EINVAL;
1234 goto fail;
1237 if (header.backing_file_offset) {
1238 ext_end = header.backing_file_offset;
1239 } else {
1240 ext_end = 1 << header.cluster_bits;
1243 /* Handle feature bits */
1244 s->incompatible_features = header.incompatible_features;
1245 s->compatible_features = header.compatible_features;
1246 s->autoclear_features = header.autoclear_features;
1248 if (s->incompatible_features & ~QCOW2_INCOMPAT_MASK) {
1249 void *feature_table = NULL;
1250 qcow2_read_extensions(bs, header.header_length, ext_end,
1251 &feature_table, flags, NULL, NULL);
1252 report_unsupported_feature(errp, feature_table,
1253 s->incompatible_features &
1254 ~QCOW2_INCOMPAT_MASK);
1255 ret = -ENOTSUP;
1256 g_free(feature_table);
1257 goto fail;
1260 if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
1261 /* Corrupt images may not be written to unless they are being repaired
1263 if ((flags & BDRV_O_RDWR) && !(flags & BDRV_O_CHECK)) {
1264 error_setg(errp, "qcow2: Image is corrupt; cannot be opened "
1265 "read/write");
1266 ret = -EACCES;
1267 goto fail;
1271 /* Check support for various header values */
1272 if (header.refcount_order > 6) {
1273 error_setg(errp, "Reference count entry width too large; may not "
1274 "exceed 64 bits");
1275 ret = -EINVAL;
1276 goto fail;
1278 s->refcount_order = header.refcount_order;
1279 s->refcount_bits = 1 << s->refcount_order;
1280 s->refcount_max = UINT64_C(1) << (s->refcount_bits - 1);
1281 s->refcount_max += s->refcount_max - 1;
1283 s->crypt_method_header = header.crypt_method;
1284 if (s->crypt_method_header) {
1285 if (bdrv_uses_whitelist() &&
1286 s->crypt_method_header == QCOW_CRYPT_AES) {
1287 error_setg(errp,
1288 "Use of AES-CBC encrypted qcow2 images is no longer "
1289 "supported in system emulators");
1290 error_append_hint(errp,
1291 "You can use 'qemu-img convert' to convert your "
1292 "image to an alternative supported format, such "
1293 "as unencrypted qcow2, or raw with the LUKS "
1294 "format instead.\n");
1295 ret = -ENOSYS;
1296 goto fail;
1299 if (s->crypt_method_header == QCOW_CRYPT_AES) {
1300 s->crypt_physical_offset = false;
1301 } else {
1302 /* Assuming LUKS and any future crypt methods we
1303 * add will all use physical offsets, due to the
1304 * fact that the alternative is insecure... */
1305 s->crypt_physical_offset = true;
1308 bs->encrypted = true;
1311 s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */
1312 s->l2_size = 1 << s->l2_bits;
1313 /* 2^(s->refcount_order - 3) is the refcount width in bytes */
1314 s->refcount_block_bits = s->cluster_bits - (s->refcount_order - 3);
1315 s->refcount_block_size = 1 << s->refcount_block_bits;
1316 bs->total_sectors = header.size / 512;
1317 s->csize_shift = (62 - (s->cluster_bits - 8));
1318 s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;
1319 s->cluster_offset_mask = (1LL << s->csize_shift) - 1;
1321 s->refcount_table_offset = header.refcount_table_offset;
1322 s->refcount_table_size =
1323 header.refcount_table_clusters << (s->cluster_bits - 3);
1325 if (header.refcount_table_clusters == 0 && !(flags & BDRV_O_CHECK)) {
1326 error_setg(errp, "Image does not contain a reference count table");
1327 ret = -EINVAL;
1328 goto fail;
1331 ret = qcow2_validate_table(bs, s->refcount_table_offset,
1332 header.refcount_table_clusters,
1333 s->cluster_size, QCOW_MAX_REFTABLE_SIZE,
1334 "Reference count table", errp);
1335 if (ret < 0) {
1336 goto fail;
1339 /* The total size in bytes of the snapshot table is checked in
1340 * qcow2_read_snapshots() because the size of each snapshot is
1341 * variable and we don't know it yet.
1342 * Here we only check the offset and number of snapshots. */
1343 ret = qcow2_validate_table(bs, header.snapshots_offset,
1344 header.nb_snapshots,
1345 sizeof(QCowSnapshotHeader),
1346 sizeof(QCowSnapshotHeader) * QCOW_MAX_SNAPSHOTS,
1347 "Snapshot table", errp);
1348 if (ret < 0) {
1349 goto fail;
1352 /* read the level 1 table */
1353 ret = qcow2_validate_table(bs, header.l1_table_offset,
1354 header.l1_size, sizeof(uint64_t),
1355 QCOW_MAX_L1_SIZE, "Active L1 table", errp);
1356 if (ret < 0) {
1357 goto fail;
1359 s->l1_size = header.l1_size;
1360 s->l1_table_offset = header.l1_table_offset;
1362 l1_vm_state_index = size_to_l1(s, header.size);
1363 if (l1_vm_state_index > INT_MAX) {
1364 error_setg(errp, "Image is too big");
1365 ret = -EFBIG;
1366 goto fail;
1368 s->l1_vm_state_index = l1_vm_state_index;
1370 /* the L1 table must contain at least enough entries to put
1371 header.size bytes */
1372 if (s->l1_size < s->l1_vm_state_index) {
1373 error_setg(errp, "L1 table is too small");
1374 ret = -EINVAL;
1375 goto fail;
1378 if (s->l1_size > 0) {
1379 s->l1_table = qemu_try_blockalign(bs->file->bs,
1380 ROUND_UP(s->l1_size * sizeof(uint64_t), 512));
1381 if (s->l1_table == NULL) {
1382 error_setg(errp, "Could not allocate L1 table");
1383 ret = -ENOMEM;
1384 goto fail;
1386 ret = bdrv_pread(bs->file, s->l1_table_offset, s->l1_table,
1387 s->l1_size * sizeof(uint64_t));
1388 if (ret < 0) {
1389 error_setg_errno(errp, -ret, "Could not read L1 table");
1390 goto fail;
1392 for(i = 0;i < s->l1_size; i++) {
1393 be64_to_cpus(&s->l1_table[i]);
1397 /* Parse driver-specific options */
1398 ret = qcow2_update_options(bs, options, flags, errp);
1399 if (ret < 0) {
1400 goto fail;
1403 s->cluster_cache_offset = -1;
1404 s->flags = flags;
1406 ret = qcow2_refcount_init(bs);
1407 if (ret != 0) {
1408 error_setg_errno(errp, -ret, "Could not initialize refcount handling");
1409 goto fail;
1412 QLIST_INIT(&s->cluster_allocs);
1413 QTAILQ_INIT(&s->discards);
1415 /* read qcow2 extensions */
1416 if (qcow2_read_extensions(bs, header.header_length, ext_end, NULL,
1417 flags, &update_header, &local_err)) {
1418 error_propagate(errp, local_err);
1419 ret = -EINVAL;
1420 goto fail;
1423 /* qcow2_read_extension may have set up the crypto context
1424 * if the crypt method needs a header region, some methods
1425 * don't need header extensions, so must check here
1427 if (s->crypt_method_header && !s->crypto) {
1428 if (s->crypt_method_header == QCOW_CRYPT_AES) {
1429 unsigned int cflags = 0;
1430 if (flags & BDRV_O_NO_IO) {
1431 cflags |= QCRYPTO_BLOCK_OPEN_NO_IO;
1433 s->crypto = qcrypto_block_open(s->crypto_opts, "encrypt.",
1434 NULL, NULL, cflags, errp);
1435 if (!s->crypto) {
1436 ret = -EINVAL;
1437 goto fail;
1439 } else if (!(flags & BDRV_O_NO_IO)) {
1440 error_setg(errp, "Missing CRYPTO header for crypt method %d",
1441 s->crypt_method_header);
1442 ret = -EINVAL;
1443 goto fail;
1447 /* read the backing file name */
1448 if (header.backing_file_offset != 0) {
1449 len = header.backing_file_size;
1450 if (len > MIN(1023, s->cluster_size - header.backing_file_offset) ||
1451 len >= sizeof(bs->backing_file)) {
1452 error_setg(errp, "Backing file name too long");
1453 ret = -EINVAL;
1454 goto fail;
1456 ret = bdrv_pread(bs->file, header.backing_file_offset,
1457 bs->backing_file, len);
1458 if (ret < 0) {
1459 error_setg_errno(errp, -ret, "Could not read backing file name");
1460 goto fail;
1462 bs->backing_file[len] = '\0';
1463 s->image_backing_file = g_strdup(bs->backing_file);
1466 /* Internal snapshots */
1467 s->snapshots_offset = header.snapshots_offset;
1468 s->nb_snapshots = header.nb_snapshots;
1470 ret = qcow2_read_snapshots(bs);
1471 if (ret < 0) {
1472 error_setg_errno(errp, -ret, "Could not read snapshots");
1473 goto fail;
1476 /* Clear unknown autoclear feature bits */
1477 update_header |= s->autoclear_features & ~QCOW2_AUTOCLEAR_MASK;
1478 update_header =
1479 update_header && !bs->read_only && !(flags & BDRV_O_INACTIVE);
1480 if (update_header) {
1481 s->autoclear_features &= QCOW2_AUTOCLEAR_MASK;
1484 if (s->dirty_bitmaps_loaded) {
1485 /* It's some kind of reopen. There are no known cases where we need to
1486 * reload bitmaps in such a situation, so it's safer to skip them.
1488 * Moreover, if we have some readonly bitmaps and we are reopening for
1489 * rw we should reopen bitmaps correspondingly.
1491 if (bdrv_has_readonly_bitmaps(bs) &&
1492 !bdrv_is_read_only(bs) && !(bdrv_get_flags(bs) & BDRV_O_INACTIVE))
1494 qcow2_reopen_bitmaps_rw_hint(bs, &header_updated, &local_err);
1496 } else {
1497 header_updated = qcow2_load_dirty_bitmaps(bs, &local_err);
1498 s->dirty_bitmaps_loaded = true;
1500 update_header = update_header && !header_updated;
1501 if (local_err != NULL) {
1502 error_propagate(errp, local_err);
1503 ret = -EINVAL;
1504 goto fail;
1507 if (update_header) {
1508 ret = qcow2_update_header(bs);
1509 if (ret < 0) {
1510 error_setg_errno(errp, -ret, "Could not update qcow2 header");
1511 goto fail;
1515 bs->supported_zero_flags = header.version >= 3 ? BDRV_REQ_MAY_UNMAP : 0;
1517 /* Repair image if dirty */
1518 if (!(flags & (BDRV_O_CHECK | BDRV_O_INACTIVE)) && !bs->read_only &&
1519 (s->incompatible_features & QCOW2_INCOMPAT_DIRTY)) {
1520 BdrvCheckResult result = {0};
1522 ret = qcow2_co_check_locked(bs, &result,
1523 BDRV_FIX_ERRORS | BDRV_FIX_LEAKS);
1524 if (ret < 0 || result.check_errors) {
1525 if (ret >= 0) {
1526 ret = -EIO;
1528 error_setg_errno(errp, -ret, "Could not repair dirty image");
1529 goto fail;
1533 #ifdef DEBUG_ALLOC
1535 BdrvCheckResult result = {0};
1536 qcow2_check_refcounts(bs, &result, 0);
1538 #endif
1539 return ret;
1541 fail:
1542 g_free(s->unknown_header_fields);
1543 cleanup_unknown_header_ext(bs);
1544 qcow2_free_snapshots(bs);
1545 qcow2_refcount_close(bs);
1546 qemu_vfree(s->l1_table);
1547 /* else pre-write overlap checks in cache_destroy may crash */
1548 s->l1_table = NULL;
1549 cache_clean_timer_del(bs);
1550 if (s->l2_table_cache) {
1551 qcow2_cache_destroy(s->l2_table_cache);
1553 if (s->refcount_block_cache) {
1554 qcow2_cache_destroy(s->refcount_block_cache);
1556 qcrypto_block_free(s->crypto);
1557 qapi_free_QCryptoBlockOpenOptions(s->crypto_opts);
1558 return ret;
1561 typedef struct QCow2OpenCo {
1562 BlockDriverState *bs;
1563 QDict *options;
1564 int flags;
1565 Error **errp;
1566 int ret;
1567 } QCow2OpenCo;
1569 static void coroutine_fn qcow2_open_entry(void *opaque)
1571 QCow2OpenCo *qoc = opaque;
1572 BDRVQcow2State *s = qoc->bs->opaque;
1574 qemu_co_mutex_lock(&s->lock);
1575 qoc->ret = qcow2_do_open(qoc->bs, qoc->options, qoc->flags, qoc->errp);
1576 qemu_co_mutex_unlock(&s->lock);
1579 static int qcow2_open(BlockDriverState *bs, QDict *options, int flags,
1580 Error **errp)
1582 BDRVQcow2State *s = bs->opaque;
1583 QCow2OpenCo qoc = {
1584 .bs = bs,
1585 .options = options,
1586 .flags = flags,
1587 .errp = errp,
1588 .ret = -EINPROGRESS
1591 bs->file = bdrv_open_child(NULL, options, "file", bs, &child_file,
1592 false, errp);
1593 if (!bs->file) {
1594 return -EINVAL;
1597 /* Initialise locks */
1598 qemu_co_mutex_init(&s->lock);
1600 if (qemu_in_coroutine()) {
1601 /* From bdrv_co_create. */
1602 qcow2_open_entry(&qoc);
1603 } else {
1604 qemu_coroutine_enter(qemu_coroutine_create(qcow2_open_entry, &qoc));
1605 BDRV_POLL_WHILE(bs, qoc.ret == -EINPROGRESS);
1607 return qoc.ret;
1610 static void qcow2_refresh_limits(BlockDriverState *bs, Error **errp)
1612 BDRVQcow2State *s = bs->opaque;
1614 if (bs->encrypted) {
1615 /* Encryption works on a sector granularity */
1616 bs->bl.request_alignment = BDRV_SECTOR_SIZE;
1618 bs->bl.pwrite_zeroes_alignment = s->cluster_size;
1619 bs->bl.pdiscard_alignment = s->cluster_size;
1622 static int qcow2_reopen_prepare(BDRVReopenState *state,
1623 BlockReopenQueue *queue, Error **errp)
1625 Qcow2ReopenState *r;
1626 int ret;
1628 r = g_new0(Qcow2ReopenState, 1);
1629 state->opaque = r;
1631 ret = qcow2_update_options_prepare(state->bs, r, state->options,
1632 state->flags, errp);
1633 if (ret < 0) {
1634 goto fail;
1637 /* We need to write out any unwritten data if we reopen read-only. */
1638 if ((state->flags & BDRV_O_RDWR) == 0) {
1639 ret = qcow2_reopen_bitmaps_ro(state->bs, errp);
1640 if (ret < 0) {
1641 goto fail;
1644 ret = bdrv_flush(state->bs);
1645 if (ret < 0) {
1646 goto fail;
1649 ret = qcow2_mark_clean(state->bs);
1650 if (ret < 0) {
1651 goto fail;
1655 return 0;
1657 fail:
1658 qcow2_update_options_abort(state->bs, r);
1659 g_free(r);
1660 return ret;
1663 static void qcow2_reopen_commit(BDRVReopenState *state)
1665 qcow2_update_options_commit(state->bs, state->opaque);
1666 g_free(state->opaque);
1669 static void qcow2_reopen_abort(BDRVReopenState *state)
1671 qcow2_update_options_abort(state->bs, state->opaque);
1672 g_free(state->opaque);
1675 static void qcow2_join_options(QDict *options, QDict *old_options)
1677 bool has_new_overlap_template =
1678 qdict_haskey(options, QCOW2_OPT_OVERLAP) ||
1679 qdict_haskey(options, QCOW2_OPT_OVERLAP_TEMPLATE);
1680 bool has_new_total_cache_size =
1681 qdict_haskey(options, QCOW2_OPT_CACHE_SIZE);
1682 bool has_all_cache_options;
1684 /* New overlap template overrides all old overlap options */
1685 if (has_new_overlap_template) {
1686 qdict_del(old_options, QCOW2_OPT_OVERLAP);
1687 qdict_del(old_options, QCOW2_OPT_OVERLAP_TEMPLATE);
1688 qdict_del(old_options, QCOW2_OPT_OVERLAP_MAIN_HEADER);
1689 qdict_del(old_options, QCOW2_OPT_OVERLAP_ACTIVE_L1);
1690 qdict_del(old_options, QCOW2_OPT_OVERLAP_ACTIVE_L2);
1691 qdict_del(old_options, QCOW2_OPT_OVERLAP_REFCOUNT_TABLE);
1692 qdict_del(old_options, QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK);
1693 qdict_del(old_options, QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE);
1694 qdict_del(old_options, QCOW2_OPT_OVERLAP_INACTIVE_L1);
1695 qdict_del(old_options, QCOW2_OPT_OVERLAP_INACTIVE_L2);
1698 /* New total cache size overrides all old options */
1699 if (qdict_haskey(options, QCOW2_OPT_CACHE_SIZE)) {
1700 qdict_del(old_options, QCOW2_OPT_L2_CACHE_SIZE);
1701 qdict_del(old_options, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
1704 qdict_join(options, old_options, false);
1707 * If after merging all cache size options are set, an old total size is
1708 * overwritten. Do keep all options, however, if all three are new. The
1709 * resulting error message is what we want to happen.
1711 has_all_cache_options =
1712 qdict_haskey(options, QCOW2_OPT_CACHE_SIZE) ||
1713 qdict_haskey(options, QCOW2_OPT_L2_CACHE_SIZE) ||
1714 qdict_haskey(options, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
1716 if (has_all_cache_options && !has_new_total_cache_size) {
1717 qdict_del(options, QCOW2_OPT_CACHE_SIZE);
1721 static int coroutine_fn qcow2_co_block_status(BlockDriverState *bs,
1722 bool want_zero,
1723 int64_t offset, int64_t count,
1724 int64_t *pnum, int64_t *map,
1725 BlockDriverState **file)
1727 BDRVQcow2State *s = bs->opaque;
1728 uint64_t cluster_offset;
1729 int index_in_cluster, ret;
1730 unsigned int bytes;
1731 int status = 0;
1733 bytes = MIN(INT_MAX, count);
1734 qemu_co_mutex_lock(&s->lock);
1735 ret = qcow2_get_cluster_offset(bs, offset, &bytes, &cluster_offset);
1736 qemu_co_mutex_unlock(&s->lock);
1737 if (ret < 0) {
1738 return ret;
1741 *pnum = bytes;
1743 if (cluster_offset != 0 && ret != QCOW2_CLUSTER_COMPRESSED &&
1744 !s->crypto) {
1745 index_in_cluster = offset & (s->cluster_size - 1);
1746 *map = cluster_offset | index_in_cluster;
1747 *file = bs->file->bs;
1748 status |= BDRV_BLOCK_OFFSET_VALID;
1750 if (ret == QCOW2_CLUSTER_ZERO_PLAIN || ret == QCOW2_CLUSTER_ZERO_ALLOC) {
1751 status |= BDRV_BLOCK_ZERO;
1752 } else if (ret != QCOW2_CLUSTER_UNALLOCATED) {
1753 status |= BDRV_BLOCK_DATA;
1755 return status;
1758 static coroutine_fn int qcow2_co_preadv(BlockDriverState *bs, uint64_t offset,
1759 uint64_t bytes, QEMUIOVector *qiov,
1760 int flags)
1762 BDRVQcow2State *s = bs->opaque;
1763 int offset_in_cluster;
1764 int ret;
1765 unsigned int cur_bytes; /* number of bytes in current iteration */
1766 uint64_t cluster_offset = 0;
1767 uint64_t bytes_done = 0;
1768 QEMUIOVector hd_qiov;
1769 uint8_t *cluster_data = NULL;
1771 qemu_iovec_init(&hd_qiov, qiov->niov);
1773 qemu_co_mutex_lock(&s->lock);
1775 while (bytes != 0) {
1777 /* prepare next request */
1778 cur_bytes = MIN(bytes, INT_MAX);
1779 if (s->crypto) {
1780 cur_bytes = MIN(cur_bytes,
1781 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
1784 ret = qcow2_get_cluster_offset(bs, offset, &cur_bytes, &cluster_offset);
1785 if (ret < 0) {
1786 goto fail;
1789 offset_in_cluster = offset_into_cluster(s, offset);
1791 qemu_iovec_reset(&hd_qiov);
1792 qemu_iovec_concat(&hd_qiov, qiov, bytes_done, cur_bytes);
1794 switch (ret) {
1795 case QCOW2_CLUSTER_UNALLOCATED:
1797 if (bs->backing) {
1798 BLKDBG_EVENT(bs->file, BLKDBG_READ_BACKING_AIO);
1799 qemu_co_mutex_unlock(&s->lock);
1800 ret = bdrv_co_preadv(bs->backing, offset, cur_bytes,
1801 &hd_qiov, 0);
1802 qemu_co_mutex_lock(&s->lock);
1803 if (ret < 0) {
1804 goto fail;
1806 } else {
1807 /* Note: in this case, no need to wait */
1808 qemu_iovec_memset(&hd_qiov, 0, 0, cur_bytes);
1810 break;
1812 case QCOW2_CLUSTER_ZERO_PLAIN:
1813 case QCOW2_CLUSTER_ZERO_ALLOC:
1814 qemu_iovec_memset(&hd_qiov, 0, 0, cur_bytes);
1815 break;
1817 case QCOW2_CLUSTER_COMPRESSED:
1818 /* add AIO support for compressed blocks ? */
1819 ret = qcow2_decompress_cluster(bs, cluster_offset);
1820 if (ret < 0) {
1821 goto fail;
1824 qemu_iovec_from_buf(&hd_qiov, 0,
1825 s->cluster_cache + offset_in_cluster,
1826 cur_bytes);
1827 break;
1829 case QCOW2_CLUSTER_NORMAL:
1830 if ((cluster_offset & 511) != 0) {
1831 ret = -EIO;
1832 goto fail;
1835 if (bs->encrypted) {
1836 assert(s->crypto);
1839 * For encrypted images, read everything into a temporary
1840 * contiguous buffer on which the AES functions can work.
1842 if (!cluster_data) {
1843 cluster_data =
1844 qemu_try_blockalign(bs->file->bs,
1845 QCOW_MAX_CRYPT_CLUSTERS
1846 * s->cluster_size);
1847 if (cluster_data == NULL) {
1848 ret = -ENOMEM;
1849 goto fail;
1853 assert(cur_bytes <= QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
1854 qemu_iovec_reset(&hd_qiov);
1855 qemu_iovec_add(&hd_qiov, cluster_data, cur_bytes);
1858 BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);
1859 qemu_co_mutex_unlock(&s->lock);
1860 ret = bdrv_co_preadv(bs->file,
1861 cluster_offset + offset_in_cluster,
1862 cur_bytes, &hd_qiov, 0);
1863 qemu_co_mutex_lock(&s->lock);
1864 if (ret < 0) {
1865 goto fail;
1867 if (bs->encrypted) {
1868 assert(s->crypto);
1869 assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);
1870 assert((cur_bytes & (BDRV_SECTOR_SIZE - 1)) == 0);
1871 if (qcrypto_block_decrypt(s->crypto,
1872 (s->crypt_physical_offset ?
1873 cluster_offset + offset_in_cluster :
1874 offset),
1875 cluster_data,
1876 cur_bytes,
1877 NULL) < 0) {
1878 ret = -EIO;
1879 goto fail;
1881 qemu_iovec_from_buf(qiov, bytes_done, cluster_data, cur_bytes);
1883 break;
1885 default:
1886 g_assert_not_reached();
1887 ret = -EIO;
1888 goto fail;
1891 bytes -= cur_bytes;
1892 offset += cur_bytes;
1893 bytes_done += cur_bytes;
1895 ret = 0;
1897 fail:
1898 qemu_co_mutex_unlock(&s->lock);
1900 qemu_iovec_destroy(&hd_qiov);
1901 qemu_vfree(cluster_data);
1903 return ret;
1906 /* Check if it's possible to merge a write request with the writing of
1907 * the data from the COW regions */
1908 static bool merge_cow(uint64_t offset, unsigned bytes,
1909 QEMUIOVector *hd_qiov, QCowL2Meta *l2meta)
1911 QCowL2Meta *m;
1913 for (m = l2meta; m != NULL; m = m->next) {
1914 /* If both COW regions are empty then there's nothing to merge */
1915 if (m->cow_start.nb_bytes == 0 && m->cow_end.nb_bytes == 0) {
1916 continue;
1919 /* The data (middle) region must be immediately after the
1920 * start region */
1921 if (l2meta_cow_start(m) + m->cow_start.nb_bytes != offset) {
1922 continue;
1925 /* The end region must be immediately after the data (middle)
1926 * region */
1927 if (m->offset + m->cow_end.offset != offset + bytes) {
1928 continue;
1931 /* Make sure that adding both COW regions to the QEMUIOVector
1932 * does not exceed IOV_MAX */
1933 if (hd_qiov->niov > IOV_MAX - 2) {
1934 continue;
1937 m->data_qiov = hd_qiov;
1938 return true;
1941 return false;
1944 static coroutine_fn int qcow2_co_pwritev(BlockDriverState *bs, uint64_t offset,
1945 uint64_t bytes, QEMUIOVector *qiov,
1946 int flags)
1948 BDRVQcow2State *s = bs->opaque;
1949 int offset_in_cluster;
1950 int ret;
1951 unsigned int cur_bytes; /* number of sectors in current iteration */
1952 uint64_t cluster_offset;
1953 QEMUIOVector hd_qiov;
1954 uint64_t bytes_done = 0;
1955 uint8_t *cluster_data = NULL;
1956 QCowL2Meta *l2meta = NULL;
1958 trace_qcow2_writev_start_req(qemu_coroutine_self(), offset, bytes);
1960 qemu_iovec_init(&hd_qiov, qiov->niov);
1962 s->cluster_cache_offset = -1; /* disable compressed cache */
1964 qemu_co_mutex_lock(&s->lock);
1966 while (bytes != 0) {
1968 l2meta = NULL;
1970 trace_qcow2_writev_start_part(qemu_coroutine_self());
1971 offset_in_cluster = offset_into_cluster(s, offset);
1972 cur_bytes = MIN(bytes, INT_MAX);
1973 if (bs->encrypted) {
1974 cur_bytes = MIN(cur_bytes,
1975 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size
1976 - offset_in_cluster);
1979 ret = qcow2_alloc_cluster_offset(bs, offset, &cur_bytes,
1980 &cluster_offset, &l2meta);
1981 if (ret < 0) {
1982 goto fail;
1985 assert((cluster_offset & 511) == 0);
1987 qemu_iovec_reset(&hd_qiov);
1988 qemu_iovec_concat(&hd_qiov, qiov, bytes_done, cur_bytes);
1990 if (bs->encrypted) {
1991 assert(s->crypto);
1992 if (!cluster_data) {
1993 cluster_data = qemu_try_blockalign(bs->file->bs,
1994 QCOW_MAX_CRYPT_CLUSTERS
1995 * s->cluster_size);
1996 if (cluster_data == NULL) {
1997 ret = -ENOMEM;
1998 goto fail;
2002 assert(hd_qiov.size <=
2003 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
2004 qemu_iovec_to_buf(&hd_qiov, 0, cluster_data, hd_qiov.size);
2006 if (qcrypto_block_encrypt(s->crypto,
2007 (s->crypt_physical_offset ?
2008 cluster_offset + offset_in_cluster :
2009 offset),
2010 cluster_data,
2011 cur_bytes, NULL) < 0) {
2012 ret = -EIO;
2013 goto fail;
2016 qemu_iovec_reset(&hd_qiov);
2017 qemu_iovec_add(&hd_qiov, cluster_data, cur_bytes);
2020 ret = qcow2_pre_write_overlap_check(bs, 0,
2021 cluster_offset + offset_in_cluster, cur_bytes);
2022 if (ret < 0) {
2023 goto fail;
2026 /* If we need to do COW, check if it's possible to merge the
2027 * writing of the guest data together with that of the COW regions.
2028 * If it's not possible (or not necessary) then write the
2029 * guest data now. */
2030 if (!merge_cow(offset, cur_bytes, &hd_qiov, l2meta)) {
2031 qemu_co_mutex_unlock(&s->lock);
2032 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO);
2033 trace_qcow2_writev_data(qemu_coroutine_self(),
2034 cluster_offset + offset_in_cluster);
2035 ret = bdrv_co_pwritev(bs->file,
2036 cluster_offset + offset_in_cluster,
2037 cur_bytes, &hd_qiov, 0);
2038 qemu_co_mutex_lock(&s->lock);
2039 if (ret < 0) {
2040 goto fail;
2044 while (l2meta != NULL) {
2045 QCowL2Meta *next;
2047 ret = qcow2_alloc_cluster_link_l2(bs, l2meta);
2048 if (ret < 0) {
2049 goto fail;
2052 /* Take the request off the list of running requests */
2053 if (l2meta->nb_clusters != 0) {
2054 QLIST_REMOVE(l2meta, next_in_flight);
2057 qemu_co_queue_restart_all(&l2meta->dependent_requests);
2059 next = l2meta->next;
2060 g_free(l2meta);
2061 l2meta = next;
2064 bytes -= cur_bytes;
2065 offset += cur_bytes;
2066 bytes_done += cur_bytes;
2067 trace_qcow2_writev_done_part(qemu_coroutine_self(), cur_bytes);
2069 ret = 0;
2071 fail:
2072 while (l2meta != NULL) {
2073 QCowL2Meta *next;
2075 if (l2meta->nb_clusters != 0) {
2076 QLIST_REMOVE(l2meta, next_in_flight);
2078 qemu_co_queue_restart_all(&l2meta->dependent_requests);
2080 next = l2meta->next;
2081 g_free(l2meta);
2082 l2meta = next;
2085 qemu_co_mutex_unlock(&s->lock);
2087 qemu_iovec_destroy(&hd_qiov);
2088 qemu_vfree(cluster_data);
2089 trace_qcow2_writev_done_req(qemu_coroutine_self(), ret);
2091 return ret;
2094 static int qcow2_inactivate(BlockDriverState *bs)
2096 BDRVQcow2State *s = bs->opaque;
2097 int ret, result = 0;
2098 Error *local_err = NULL;
2100 qcow2_store_persistent_dirty_bitmaps(bs, &local_err);
2101 if (local_err != NULL) {
2102 result = -EINVAL;
2103 error_report_err(local_err);
2104 error_report("Persistent bitmaps are lost for node '%s'",
2105 bdrv_get_device_or_node_name(bs));
2108 ret = qcow2_cache_flush(bs, s->l2_table_cache);
2109 if (ret) {
2110 result = ret;
2111 error_report("Failed to flush the L2 table cache: %s",
2112 strerror(-ret));
2115 ret = qcow2_cache_flush(bs, s->refcount_block_cache);
2116 if (ret) {
2117 result = ret;
2118 error_report("Failed to flush the refcount block cache: %s",
2119 strerror(-ret));
2122 if (result == 0) {
2123 qcow2_mark_clean(bs);
2126 return result;
2129 static void qcow2_close(BlockDriverState *bs)
2131 BDRVQcow2State *s = bs->opaque;
2132 qemu_vfree(s->l1_table);
2133 /* else pre-write overlap checks in cache_destroy may crash */
2134 s->l1_table = NULL;
2136 if (!(s->flags & BDRV_O_INACTIVE)) {
2137 qcow2_inactivate(bs);
2140 cache_clean_timer_del(bs);
2141 qcow2_cache_destroy(s->l2_table_cache);
2142 qcow2_cache_destroy(s->refcount_block_cache);
2144 qcrypto_block_free(s->crypto);
2145 s->crypto = NULL;
2147 g_free(s->unknown_header_fields);
2148 cleanup_unknown_header_ext(bs);
2150 g_free(s->image_backing_file);
2151 g_free(s->image_backing_format);
2153 g_free(s->cluster_cache);
2154 qemu_vfree(s->cluster_data);
2155 qcow2_refcount_close(bs);
2156 qcow2_free_snapshots(bs);
2159 static void coroutine_fn qcow2_co_invalidate_cache(BlockDriverState *bs,
2160 Error **errp)
2162 BDRVQcow2State *s = bs->opaque;
2163 int flags = s->flags;
2164 QCryptoBlock *crypto = NULL;
2165 QDict *options;
2166 Error *local_err = NULL;
2167 int ret;
2170 * Backing files are read-only which makes all of their metadata immutable,
2171 * that means we don't have to worry about reopening them here.
2174 crypto = s->crypto;
2175 s->crypto = NULL;
2177 qcow2_close(bs);
2179 memset(s, 0, sizeof(BDRVQcow2State));
2180 options = qdict_clone_shallow(bs->options);
2182 flags &= ~BDRV_O_INACTIVE;
2183 qemu_co_mutex_lock(&s->lock);
2184 ret = qcow2_do_open(bs, options, flags, &local_err);
2185 qemu_co_mutex_unlock(&s->lock);
2186 QDECREF(options);
2187 if (local_err) {
2188 error_propagate(errp, local_err);
2189 error_prepend(errp, "Could not reopen qcow2 layer: ");
2190 bs->drv = NULL;
2191 return;
2192 } else if (ret < 0) {
2193 error_setg_errno(errp, -ret, "Could not reopen qcow2 layer");
2194 bs->drv = NULL;
2195 return;
2198 s->crypto = crypto;
2201 static size_t header_ext_add(char *buf, uint32_t magic, const void *s,
2202 size_t len, size_t buflen)
2204 QCowExtension *ext_backing_fmt = (QCowExtension*) buf;
2205 size_t ext_len = sizeof(QCowExtension) + ((len + 7) & ~7);
2207 if (buflen < ext_len) {
2208 return -ENOSPC;
2211 *ext_backing_fmt = (QCowExtension) {
2212 .magic = cpu_to_be32(magic),
2213 .len = cpu_to_be32(len),
2216 if (len) {
2217 memcpy(buf + sizeof(QCowExtension), s, len);
2220 return ext_len;
2224 * Updates the qcow2 header, including the variable length parts of it, i.e.
2225 * the backing file name and all extensions. qcow2 was not designed to allow
2226 * such changes, so if we run out of space (we can only use the first cluster)
2227 * this function may fail.
2229 * Returns 0 on success, -errno in error cases.
2231 int qcow2_update_header(BlockDriverState *bs)
2233 BDRVQcow2State *s = bs->opaque;
2234 QCowHeader *header;
2235 char *buf;
2236 size_t buflen = s->cluster_size;
2237 int ret;
2238 uint64_t total_size;
2239 uint32_t refcount_table_clusters;
2240 size_t header_length;
2241 Qcow2UnknownHeaderExtension *uext;
2243 buf = qemu_blockalign(bs, buflen);
2245 /* Header structure */
2246 header = (QCowHeader*) buf;
2248 if (buflen < sizeof(*header)) {
2249 ret = -ENOSPC;
2250 goto fail;
2253 header_length = sizeof(*header) + s->unknown_header_fields_size;
2254 total_size = bs->total_sectors * BDRV_SECTOR_SIZE;
2255 refcount_table_clusters = s->refcount_table_size >> (s->cluster_bits - 3);
2257 *header = (QCowHeader) {
2258 /* Version 2 fields */
2259 .magic = cpu_to_be32(QCOW_MAGIC),
2260 .version = cpu_to_be32(s->qcow_version),
2261 .backing_file_offset = 0,
2262 .backing_file_size = 0,
2263 .cluster_bits = cpu_to_be32(s->cluster_bits),
2264 .size = cpu_to_be64(total_size),
2265 .crypt_method = cpu_to_be32(s->crypt_method_header),
2266 .l1_size = cpu_to_be32(s->l1_size),
2267 .l1_table_offset = cpu_to_be64(s->l1_table_offset),
2268 .refcount_table_offset = cpu_to_be64(s->refcount_table_offset),
2269 .refcount_table_clusters = cpu_to_be32(refcount_table_clusters),
2270 .nb_snapshots = cpu_to_be32(s->nb_snapshots),
2271 .snapshots_offset = cpu_to_be64(s->snapshots_offset),
2273 /* Version 3 fields */
2274 .incompatible_features = cpu_to_be64(s->incompatible_features),
2275 .compatible_features = cpu_to_be64(s->compatible_features),
2276 .autoclear_features = cpu_to_be64(s->autoclear_features),
2277 .refcount_order = cpu_to_be32(s->refcount_order),
2278 .header_length = cpu_to_be32(header_length),
2281 /* For older versions, write a shorter header */
2282 switch (s->qcow_version) {
2283 case 2:
2284 ret = offsetof(QCowHeader, incompatible_features);
2285 break;
2286 case 3:
2287 ret = sizeof(*header);
2288 break;
2289 default:
2290 ret = -EINVAL;
2291 goto fail;
2294 buf += ret;
2295 buflen -= ret;
2296 memset(buf, 0, buflen);
2298 /* Preserve any unknown field in the header */
2299 if (s->unknown_header_fields_size) {
2300 if (buflen < s->unknown_header_fields_size) {
2301 ret = -ENOSPC;
2302 goto fail;
2305 memcpy(buf, s->unknown_header_fields, s->unknown_header_fields_size);
2306 buf += s->unknown_header_fields_size;
2307 buflen -= s->unknown_header_fields_size;
2310 /* Backing file format header extension */
2311 if (s->image_backing_format) {
2312 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BACKING_FORMAT,
2313 s->image_backing_format,
2314 strlen(s->image_backing_format),
2315 buflen);
2316 if (ret < 0) {
2317 goto fail;
2320 buf += ret;
2321 buflen -= ret;
2324 /* Full disk encryption header pointer extension */
2325 if (s->crypto_header.offset != 0) {
2326 cpu_to_be64s(&s->crypto_header.offset);
2327 cpu_to_be64s(&s->crypto_header.length);
2328 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_CRYPTO_HEADER,
2329 &s->crypto_header, sizeof(s->crypto_header),
2330 buflen);
2331 be64_to_cpus(&s->crypto_header.offset);
2332 be64_to_cpus(&s->crypto_header.length);
2333 if (ret < 0) {
2334 goto fail;
2336 buf += ret;
2337 buflen -= ret;
2340 /* Feature table */
2341 if (s->qcow_version >= 3) {
2342 Qcow2Feature features[] = {
2344 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
2345 .bit = QCOW2_INCOMPAT_DIRTY_BITNR,
2346 .name = "dirty bit",
2349 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
2350 .bit = QCOW2_INCOMPAT_CORRUPT_BITNR,
2351 .name = "corrupt bit",
2354 .type = QCOW2_FEAT_TYPE_COMPATIBLE,
2355 .bit = QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR,
2356 .name = "lazy refcounts",
2360 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_FEATURE_TABLE,
2361 features, sizeof(features), buflen);
2362 if (ret < 0) {
2363 goto fail;
2365 buf += ret;
2366 buflen -= ret;
2369 /* Bitmap extension */
2370 if (s->nb_bitmaps > 0) {
2371 Qcow2BitmapHeaderExt bitmaps_header = {
2372 .nb_bitmaps = cpu_to_be32(s->nb_bitmaps),
2373 .bitmap_directory_size =
2374 cpu_to_be64(s->bitmap_directory_size),
2375 .bitmap_directory_offset =
2376 cpu_to_be64(s->bitmap_directory_offset)
2378 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BITMAPS,
2379 &bitmaps_header, sizeof(bitmaps_header),
2380 buflen);
2381 if (ret < 0) {
2382 goto fail;
2384 buf += ret;
2385 buflen -= ret;
2388 /* Keep unknown header extensions */
2389 QLIST_FOREACH(uext, &s->unknown_header_ext, next) {
2390 ret = header_ext_add(buf, uext->magic, uext->data, uext->len, buflen);
2391 if (ret < 0) {
2392 goto fail;
2395 buf += ret;
2396 buflen -= ret;
2399 /* End of header extensions */
2400 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_END, NULL, 0, buflen);
2401 if (ret < 0) {
2402 goto fail;
2405 buf += ret;
2406 buflen -= ret;
2408 /* Backing file name */
2409 if (s->image_backing_file) {
2410 size_t backing_file_len = strlen(s->image_backing_file);
2412 if (buflen < backing_file_len) {
2413 ret = -ENOSPC;
2414 goto fail;
2417 /* Using strncpy is ok here, since buf is not NUL-terminated. */
2418 strncpy(buf, s->image_backing_file, buflen);
2420 header->backing_file_offset = cpu_to_be64(buf - ((char*) header));
2421 header->backing_file_size = cpu_to_be32(backing_file_len);
2424 /* Write the new header */
2425 ret = bdrv_pwrite(bs->file, 0, header, s->cluster_size);
2426 if (ret < 0) {
2427 goto fail;
2430 ret = 0;
2431 fail:
2432 qemu_vfree(header);
2433 return ret;
2436 static int qcow2_change_backing_file(BlockDriverState *bs,
2437 const char *backing_file, const char *backing_fmt)
2439 BDRVQcow2State *s = bs->opaque;
2441 if (backing_file && strlen(backing_file) > 1023) {
2442 return -EINVAL;
2445 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
2446 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
2448 g_free(s->image_backing_file);
2449 g_free(s->image_backing_format);
2451 s->image_backing_file = backing_file ? g_strdup(bs->backing_file) : NULL;
2452 s->image_backing_format = backing_fmt ? g_strdup(bs->backing_format) : NULL;
2454 return qcow2_update_header(bs);
2457 static int qcow2_crypt_method_from_format(const char *encryptfmt)
2459 if (g_str_equal(encryptfmt, "luks")) {
2460 return QCOW_CRYPT_LUKS;
2461 } else if (g_str_equal(encryptfmt, "aes")) {
2462 return QCOW_CRYPT_AES;
2463 } else {
2464 return -EINVAL;
2468 static int qcow2_set_up_encryption(BlockDriverState *bs,
2469 QCryptoBlockCreateOptions *cryptoopts,
2470 Error **errp)
2472 BDRVQcow2State *s = bs->opaque;
2473 QCryptoBlock *crypto = NULL;
2474 int fmt, ret;
2476 switch (cryptoopts->format) {
2477 case Q_CRYPTO_BLOCK_FORMAT_LUKS:
2478 fmt = QCOW_CRYPT_LUKS;
2479 break;
2480 case Q_CRYPTO_BLOCK_FORMAT_QCOW:
2481 fmt = QCOW_CRYPT_AES;
2482 break;
2483 default:
2484 error_setg(errp, "Crypto format not supported in qcow2");
2485 return -EINVAL;
2488 s->crypt_method_header = fmt;
2490 crypto = qcrypto_block_create(cryptoopts, "encrypt.",
2491 qcow2_crypto_hdr_init_func,
2492 qcow2_crypto_hdr_write_func,
2493 bs, errp);
2494 if (!crypto) {
2495 return -EINVAL;
2498 ret = qcow2_update_header(bs);
2499 if (ret < 0) {
2500 error_setg_errno(errp, -ret, "Could not write encryption header");
2501 goto out;
2504 ret = 0;
2505 out:
2506 qcrypto_block_free(crypto);
2507 return ret;
2511 typedef struct PreallocCo {
2512 BlockDriverState *bs;
2513 uint64_t offset;
2514 uint64_t new_length;
2516 int ret;
2517 } PreallocCo;
2520 * Preallocates metadata structures for data clusters between @offset (in the
2521 * guest disk) and @new_length (which is thus generally the new guest disk
2522 * size).
2524 * Returns: 0 on success, -errno on failure.
2526 static void coroutine_fn preallocate_co(void *opaque)
2528 PreallocCo *params = opaque;
2529 BlockDriverState *bs = params->bs;
2530 uint64_t offset = params->offset;
2531 uint64_t new_length = params->new_length;
2532 BDRVQcow2State *s = bs->opaque;
2533 uint64_t bytes;
2534 uint64_t host_offset = 0;
2535 unsigned int cur_bytes;
2536 int ret;
2537 QCowL2Meta *meta;
2539 qemu_co_mutex_lock(&s->lock);
2541 assert(offset <= new_length);
2542 bytes = new_length - offset;
2544 while (bytes) {
2545 cur_bytes = MIN(bytes, INT_MAX);
2546 ret = qcow2_alloc_cluster_offset(bs, offset, &cur_bytes,
2547 &host_offset, &meta);
2548 if (ret < 0) {
2549 goto done;
2552 while (meta) {
2553 QCowL2Meta *next = meta->next;
2555 ret = qcow2_alloc_cluster_link_l2(bs, meta);
2556 if (ret < 0) {
2557 qcow2_free_any_clusters(bs, meta->alloc_offset,
2558 meta->nb_clusters, QCOW2_DISCARD_NEVER);
2559 goto done;
2562 /* There are no dependent requests, but we need to remove our
2563 * request from the list of in-flight requests */
2564 QLIST_REMOVE(meta, next_in_flight);
2566 g_free(meta);
2567 meta = next;
2570 /* TODO Preallocate data if requested */
2572 bytes -= cur_bytes;
2573 offset += cur_bytes;
2577 * It is expected that the image file is large enough to actually contain
2578 * all of the allocated clusters (otherwise we get failing reads after
2579 * EOF). Extend the image to the last allocated sector.
2581 if (host_offset != 0) {
2582 uint8_t data = 0;
2583 ret = bdrv_pwrite(bs->file, (host_offset + cur_bytes) - 1,
2584 &data, 1);
2585 if (ret < 0) {
2586 goto done;
2590 ret = 0;
2592 done:
2593 qemu_co_mutex_unlock(&s->lock);
2594 params->ret = ret;
2597 static int preallocate(BlockDriverState *bs,
2598 uint64_t offset, uint64_t new_length)
2600 PreallocCo params = {
2601 .bs = bs,
2602 .offset = offset,
2603 .new_length = new_length,
2604 .ret = -EINPROGRESS,
2607 if (qemu_in_coroutine()) {
2608 preallocate_co(&params);
2609 } else {
2610 Coroutine *co = qemu_coroutine_create(preallocate_co, &params);
2611 bdrv_coroutine_enter(bs, co);
2612 BDRV_POLL_WHILE(bs, params.ret == -EINPROGRESS);
2614 return params.ret;
2617 /* qcow2_refcount_metadata_size:
2618 * @clusters: number of clusters to refcount (including data and L1/L2 tables)
2619 * @cluster_size: size of a cluster, in bytes
2620 * @refcount_order: refcount bits power-of-2 exponent
2621 * @generous_increase: allow for the refcount table to be 1.5x as large as it
2622 * needs to be
2624 * Returns: Number of bytes required for refcount blocks and table metadata.
2626 int64_t qcow2_refcount_metadata_size(int64_t clusters, size_t cluster_size,
2627 int refcount_order, bool generous_increase,
2628 uint64_t *refblock_count)
2631 * Every host cluster is reference-counted, including metadata (even
2632 * refcount metadata is recursively included).
2634 * An accurate formula for the size of refcount metadata size is difficult
2635 * to derive. An easier method of calculation is finding the fixed point
2636 * where no further refcount blocks or table clusters are required to
2637 * reference count every cluster.
2639 int64_t blocks_per_table_cluster = cluster_size / sizeof(uint64_t);
2640 int64_t refcounts_per_block = cluster_size * 8 / (1 << refcount_order);
2641 int64_t table = 0; /* number of refcount table clusters */
2642 int64_t blocks = 0; /* number of refcount block clusters */
2643 int64_t last;
2644 int64_t n = 0;
2646 do {
2647 last = n;
2648 blocks = DIV_ROUND_UP(clusters + table + blocks, refcounts_per_block);
2649 table = DIV_ROUND_UP(blocks, blocks_per_table_cluster);
2650 n = clusters + blocks + table;
2652 if (n == last && generous_increase) {
2653 clusters += DIV_ROUND_UP(table, 2);
2654 n = 0; /* force another loop */
2655 generous_increase = false;
2657 } while (n != last);
2659 if (refblock_count) {
2660 *refblock_count = blocks;
2663 return (blocks + table) * cluster_size;
2667 * qcow2_calc_prealloc_size:
2668 * @total_size: virtual disk size in bytes
2669 * @cluster_size: cluster size in bytes
2670 * @refcount_order: refcount bits power-of-2 exponent
2672 * Returns: Total number of bytes required for the fully allocated image
2673 * (including metadata).
2675 static int64_t qcow2_calc_prealloc_size(int64_t total_size,
2676 size_t cluster_size,
2677 int refcount_order)
2679 int64_t meta_size = 0;
2680 uint64_t nl1e, nl2e;
2681 int64_t aligned_total_size = ROUND_UP(total_size, cluster_size);
2683 /* header: 1 cluster */
2684 meta_size += cluster_size;
2686 /* total size of L2 tables */
2687 nl2e = aligned_total_size / cluster_size;
2688 nl2e = ROUND_UP(nl2e, cluster_size / sizeof(uint64_t));
2689 meta_size += nl2e * sizeof(uint64_t);
2691 /* total size of L1 tables */
2692 nl1e = nl2e * sizeof(uint64_t) / cluster_size;
2693 nl1e = ROUND_UP(nl1e, cluster_size / sizeof(uint64_t));
2694 meta_size += nl1e * sizeof(uint64_t);
2696 /* total size of refcount table and blocks */
2697 meta_size += qcow2_refcount_metadata_size(
2698 (meta_size + aligned_total_size) / cluster_size,
2699 cluster_size, refcount_order, false, NULL);
2701 return meta_size + aligned_total_size;
2704 static bool validate_cluster_size(size_t cluster_size, Error **errp)
2706 int cluster_bits = ctz32(cluster_size);
2707 if (cluster_bits < MIN_CLUSTER_BITS || cluster_bits > MAX_CLUSTER_BITS ||
2708 (1 << cluster_bits) != cluster_size)
2710 error_setg(errp, "Cluster size must be a power of two between %d and "
2711 "%dk", 1 << MIN_CLUSTER_BITS, 1 << (MAX_CLUSTER_BITS - 10));
2712 return false;
2714 return true;
2717 static size_t qcow2_opt_get_cluster_size_del(QemuOpts *opts, Error **errp)
2719 size_t cluster_size;
2721 cluster_size = qemu_opt_get_size_del(opts, BLOCK_OPT_CLUSTER_SIZE,
2722 DEFAULT_CLUSTER_SIZE);
2723 if (!validate_cluster_size(cluster_size, errp)) {
2724 return 0;
2726 return cluster_size;
2729 static int qcow2_opt_get_version_del(QemuOpts *opts, Error **errp)
2731 char *buf;
2732 int ret;
2734 buf = qemu_opt_get_del(opts, BLOCK_OPT_COMPAT_LEVEL);
2735 if (!buf) {
2736 ret = 3; /* default */
2737 } else if (!strcmp(buf, "0.10")) {
2738 ret = 2;
2739 } else if (!strcmp(buf, "1.1")) {
2740 ret = 3;
2741 } else {
2742 error_setg(errp, "Invalid compatibility level: '%s'", buf);
2743 ret = -EINVAL;
2745 g_free(buf);
2746 return ret;
2749 static uint64_t qcow2_opt_get_refcount_bits_del(QemuOpts *opts, int version,
2750 Error **errp)
2752 uint64_t refcount_bits;
2754 refcount_bits = qemu_opt_get_number_del(opts, BLOCK_OPT_REFCOUNT_BITS, 16);
2755 if (refcount_bits > 64 || !is_power_of_2(refcount_bits)) {
2756 error_setg(errp, "Refcount width must be a power of two and may not "
2757 "exceed 64 bits");
2758 return 0;
2761 if (version < 3 && refcount_bits != 16) {
2762 error_setg(errp, "Different refcount widths than 16 bits require "
2763 "compatibility level 1.1 or above (use compat=1.1 or "
2764 "greater)");
2765 return 0;
2768 return refcount_bits;
2771 static int coroutine_fn
2772 qcow2_co_create(BlockdevCreateOptions *create_options, Error **errp)
2774 BlockdevCreateOptionsQcow2 *qcow2_opts;
2775 QDict *options;
2778 * Open the image file and write a minimal qcow2 header.
2780 * We keep things simple and start with a zero-sized image. We also
2781 * do without refcount blocks or a L1 table for now. We'll fix the
2782 * inconsistency later.
2784 * We do need a refcount table because growing the refcount table means
2785 * allocating two new refcount blocks - the seconds of which would be at
2786 * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
2787 * size for any qcow2 image.
2789 BlockBackend *blk = NULL;
2790 BlockDriverState *bs = NULL;
2791 QCowHeader *header;
2792 size_t cluster_size;
2793 int version;
2794 int refcount_order;
2795 uint64_t* refcount_table;
2796 Error *local_err = NULL;
2797 int ret;
2799 assert(create_options->driver == BLOCKDEV_DRIVER_QCOW2);
2800 qcow2_opts = &create_options->u.qcow2;
2802 bs = bdrv_open_blockdev_ref(qcow2_opts->file, errp);
2803 if (bs == NULL) {
2804 return -EIO;
2807 /* Validate options and set default values */
2808 if (!QEMU_IS_ALIGNED(qcow2_opts->size, BDRV_SECTOR_SIZE)) {
2809 error_setg(errp, "Image size must be a multiple of 512 bytes");
2810 ret = -EINVAL;
2811 goto out;
2814 if (qcow2_opts->has_version) {
2815 switch (qcow2_opts->version) {
2816 case BLOCKDEV_QCOW2_VERSION_V2:
2817 version = 2;
2818 break;
2819 case BLOCKDEV_QCOW2_VERSION_V3:
2820 version = 3;
2821 break;
2822 default:
2823 g_assert_not_reached();
2825 } else {
2826 version = 3;
2829 if (qcow2_opts->has_cluster_size) {
2830 cluster_size = qcow2_opts->cluster_size;
2831 } else {
2832 cluster_size = DEFAULT_CLUSTER_SIZE;
2835 if (!validate_cluster_size(cluster_size, errp)) {
2836 ret = -EINVAL;
2837 goto out;
2840 if (!qcow2_opts->has_preallocation) {
2841 qcow2_opts->preallocation = PREALLOC_MODE_OFF;
2843 if (qcow2_opts->has_backing_file &&
2844 qcow2_opts->preallocation != PREALLOC_MODE_OFF)
2846 error_setg(errp, "Backing file and preallocation cannot be used at "
2847 "the same time");
2848 ret = -EINVAL;
2849 goto out;
2851 if (qcow2_opts->has_backing_fmt && !qcow2_opts->has_backing_file) {
2852 error_setg(errp, "Backing format cannot be used without backing file");
2853 ret = -EINVAL;
2854 goto out;
2857 if (!qcow2_opts->has_lazy_refcounts) {
2858 qcow2_opts->lazy_refcounts = false;
2860 if (version < 3 && qcow2_opts->lazy_refcounts) {
2861 error_setg(errp, "Lazy refcounts only supported with compatibility "
2862 "level 1.1 and above (use version=v3 or greater)");
2863 ret = -EINVAL;
2864 goto out;
2867 if (!qcow2_opts->has_refcount_bits) {
2868 qcow2_opts->refcount_bits = 16;
2870 if (qcow2_opts->refcount_bits > 64 ||
2871 !is_power_of_2(qcow2_opts->refcount_bits))
2873 error_setg(errp, "Refcount width must be a power of two and may not "
2874 "exceed 64 bits");
2875 ret = -EINVAL;
2876 goto out;
2878 if (version < 3 && qcow2_opts->refcount_bits != 16) {
2879 error_setg(errp, "Different refcount widths than 16 bits require "
2880 "compatibility level 1.1 or above (use version=v3 or "
2881 "greater)");
2882 ret = -EINVAL;
2883 goto out;
2885 refcount_order = ctz32(qcow2_opts->refcount_bits);
2888 /* Create BlockBackend to write to the image */
2889 blk = blk_new(BLK_PERM_WRITE | BLK_PERM_RESIZE, BLK_PERM_ALL);
2890 ret = blk_insert_bs(blk, bs, errp);
2891 if (ret < 0) {
2892 goto out;
2894 blk_set_allow_write_beyond_eof(blk, true);
2896 /* Clear the protocol layer and preallocate it if necessary */
2897 ret = blk_truncate(blk, 0, PREALLOC_MODE_OFF, errp);
2898 if (ret < 0) {
2899 goto out;
2902 if (qcow2_opts->preallocation == PREALLOC_MODE_FULL ||
2903 qcow2_opts->preallocation == PREALLOC_MODE_FALLOC)
2905 int64_t prealloc_size =
2906 qcow2_calc_prealloc_size(qcow2_opts->size, cluster_size,
2907 refcount_order);
2909 ret = blk_truncate(blk, prealloc_size, qcow2_opts->preallocation, errp);
2910 if (ret < 0) {
2911 goto out;
2915 /* Write the header */
2916 QEMU_BUILD_BUG_ON((1 << MIN_CLUSTER_BITS) < sizeof(*header));
2917 header = g_malloc0(cluster_size);
2918 *header = (QCowHeader) {
2919 .magic = cpu_to_be32(QCOW_MAGIC),
2920 .version = cpu_to_be32(version),
2921 .cluster_bits = cpu_to_be32(ctz32(cluster_size)),
2922 .size = cpu_to_be64(0),
2923 .l1_table_offset = cpu_to_be64(0),
2924 .l1_size = cpu_to_be32(0),
2925 .refcount_table_offset = cpu_to_be64(cluster_size),
2926 .refcount_table_clusters = cpu_to_be32(1),
2927 .refcount_order = cpu_to_be32(refcount_order),
2928 .header_length = cpu_to_be32(sizeof(*header)),
2931 /* We'll update this to correct value later */
2932 header->crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
2934 if (qcow2_opts->lazy_refcounts) {
2935 header->compatible_features |=
2936 cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS);
2939 ret = blk_pwrite(blk, 0, header, cluster_size, 0);
2940 g_free(header);
2941 if (ret < 0) {
2942 error_setg_errno(errp, -ret, "Could not write qcow2 header");
2943 goto out;
2946 /* Write a refcount table with one refcount block */
2947 refcount_table = g_malloc0(2 * cluster_size);
2948 refcount_table[0] = cpu_to_be64(2 * cluster_size);
2949 ret = blk_pwrite(blk, cluster_size, refcount_table, 2 * cluster_size, 0);
2950 g_free(refcount_table);
2952 if (ret < 0) {
2953 error_setg_errno(errp, -ret, "Could not write refcount table");
2954 goto out;
2957 blk_unref(blk);
2958 blk = NULL;
2961 * And now open the image and make it consistent first (i.e. increase the
2962 * refcount of the cluster that is occupied by the header and the refcount
2963 * table)
2965 options = qdict_new();
2966 qdict_put_str(options, "driver", "qcow2");
2967 qdict_put_str(options, "file", bs->node_name);
2968 blk = blk_new_open(NULL, NULL, options,
2969 BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_NO_FLUSH,
2970 &local_err);
2971 if (blk == NULL) {
2972 error_propagate(errp, local_err);
2973 ret = -EIO;
2974 goto out;
2977 ret = qcow2_alloc_clusters(blk_bs(blk), 3 * cluster_size);
2978 if (ret < 0) {
2979 error_setg_errno(errp, -ret, "Could not allocate clusters for qcow2 "
2980 "header and refcount table");
2981 goto out;
2983 } else if (ret != 0) {
2984 error_report("Huh, first cluster in empty image is already in use?");
2985 abort();
2988 /* Create a full header (including things like feature table) */
2989 ret = qcow2_update_header(blk_bs(blk));
2990 if (ret < 0) {
2991 error_setg_errno(errp, -ret, "Could not update qcow2 header");
2992 goto out;
2995 /* Okay, now that we have a valid image, let's give it the right size */
2996 ret = blk_truncate(blk, qcow2_opts->size, PREALLOC_MODE_OFF, errp);
2997 if (ret < 0) {
2998 error_prepend(errp, "Could not resize image: ");
2999 goto out;
3002 /* Want a backing file? There you go.*/
3003 if (qcow2_opts->has_backing_file) {
3004 const char *backing_format = NULL;
3006 if (qcow2_opts->has_backing_fmt) {
3007 backing_format = BlockdevDriver_str(qcow2_opts->backing_fmt);
3010 ret = bdrv_change_backing_file(blk_bs(blk), qcow2_opts->backing_file,
3011 backing_format);
3012 if (ret < 0) {
3013 error_setg_errno(errp, -ret, "Could not assign backing file '%s' "
3014 "with format '%s'", qcow2_opts->backing_file,
3015 backing_format);
3016 goto out;
3020 /* Want encryption? There you go. */
3021 if (qcow2_opts->has_encrypt) {
3022 ret = qcow2_set_up_encryption(blk_bs(blk), qcow2_opts->encrypt, errp);
3023 if (ret < 0) {
3024 goto out;
3028 /* And if we're supposed to preallocate metadata, do that now */
3029 if (qcow2_opts->preallocation != PREALLOC_MODE_OFF) {
3030 ret = preallocate(blk_bs(blk), 0, qcow2_opts->size);
3031 if (ret < 0) {
3032 error_setg_errno(errp, -ret, "Could not preallocate metadata");
3033 goto out;
3037 blk_unref(blk);
3038 blk = NULL;
3040 /* Reopen the image without BDRV_O_NO_FLUSH to flush it before returning.
3041 * Using BDRV_O_NO_IO, since encryption is now setup we don't want to
3042 * have to setup decryption context. We're not doing any I/O on the top
3043 * level BlockDriverState, only lower layers, where BDRV_O_NO_IO does
3044 * not have effect.
3046 options = qdict_new();
3047 qdict_put_str(options, "driver", "qcow2");
3048 qdict_put_str(options, "file", bs->node_name);
3049 blk = blk_new_open(NULL, NULL, options,
3050 BDRV_O_RDWR | BDRV_O_NO_BACKING | BDRV_O_NO_IO,
3051 &local_err);
3052 if (blk == NULL) {
3053 error_propagate(errp, local_err);
3054 ret = -EIO;
3055 goto out;
3058 ret = 0;
3059 out:
3060 blk_unref(blk);
3061 bdrv_unref(bs);
3062 return ret;
3065 static int coroutine_fn qcow2_co_create_opts(const char *filename, QemuOpts *opts,
3066 Error **errp)
3068 BlockdevCreateOptions *create_options = NULL;
3069 QDict *qdict = NULL;
3070 QObject *qobj;
3071 Visitor *v;
3072 BlockDriverState *bs = NULL;
3073 Error *local_err = NULL;
3074 const char *val;
3075 int ret;
3077 /* Only the keyval visitor supports the dotted syntax needed for
3078 * encryption, so go through a QDict before getting a QAPI type. Ignore
3079 * options meant for the protocol layer so that the visitor doesn't
3080 * complain. */
3081 qdict = qemu_opts_to_qdict_filtered(opts, NULL, bdrv_qcow2.create_opts,
3082 true);
3084 /* Handle encryption options */
3085 val = qdict_get_try_str(qdict, BLOCK_OPT_ENCRYPT);
3086 if (val && !strcmp(val, "on")) {
3087 qdict_put_str(qdict, BLOCK_OPT_ENCRYPT, "qcow");
3088 } else if (val && !strcmp(val, "off")) {
3089 qdict_del(qdict, BLOCK_OPT_ENCRYPT);
3092 val = qdict_get_try_str(qdict, BLOCK_OPT_ENCRYPT_FORMAT);
3093 if (val && !strcmp(val, "aes")) {
3094 qdict_put_str(qdict, BLOCK_OPT_ENCRYPT_FORMAT, "qcow");
3097 /* Convert compat=0.10/1.1 into compat=v2/v3, to be renamed into
3098 * version=v2/v3 below. */
3099 val = qdict_get_try_str(qdict, BLOCK_OPT_COMPAT_LEVEL);
3100 if (val && !strcmp(val, "0.10")) {
3101 qdict_put_str(qdict, BLOCK_OPT_COMPAT_LEVEL, "v2");
3102 } else if (val && !strcmp(val, "1.1")) {
3103 qdict_put_str(qdict, BLOCK_OPT_COMPAT_LEVEL, "v3");
3106 /* Change legacy command line options into QMP ones */
3107 static const QDictRenames opt_renames[] = {
3108 { BLOCK_OPT_BACKING_FILE, "backing-file" },
3109 { BLOCK_OPT_BACKING_FMT, "backing-fmt" },
3110 { BLOCK_OPT_CLUSTER_SIZE, "cluster-size" },
3111 { BLOCK_OPT_LAZY_REFCOUNTS, "lazy-refcounts" },
3112 { BLOCK_OPT_REFCOUNT_BITS, "refcount-bits" },
3113 { BLOCK_OPT_ENCRYPT, BLOCK_OPT_ENCRYPT_FORMAT },
3114 { BLOCK_OPT_COMPAT_LEVEL, "version" },
3115 { NULL, NULL },
3118 if (!qdict_rename_keys(qdict, opt_renames, errp)) {
3119 ret = -EINVAL;
3120 goto finish;
3123 /* Create and open the file (protocol layer) */
3124 ret = bdrv_create_file(filename, opts, errp);
3125 if (ret < 0) {
3126 goto finish;
3129 bs = bdrv_open(filename, NULL, NULL,
3130 BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_PROTOCOL, errp);
3131 if (bs == NULL) {
3132 ret = -EIO;
3133 goto finish;
3136 /* Set 'driver' and 'node' options */
3137 qdict_put_str(qdict, "driver", "qcow2");
3138 qdict_put_str(qdict, "file", bs->node_name);
3140 /* Now get the QAPI type BlockdevCreateOptions */
3141 qobj = qdict_crumple(qdict, errp);
3142 QDECREF(qdict);
3143 qdict = qobject_to(QDict, qobj);
3144 if (qdict == NULL) {
3145 ret = -EINVAL;
3146 goto finish;
3149 v = qobject_input_visitor_new_keyval(QOBJECT(qdict));
3150 visit_type_BlockdevCreateOptions(v, NULL, &create_options, &local_err);
3151 visit_free(v);
3153 if (local_err) {
3154 error_propagate(errp, local_err);
3155 ret = -EINVAL;
3156 goto finish;
3159 /* Silently round up size */
3160 create_options->u.qcow2.size = ROUND_UP(create_options->u.qcow2.size,
3161 BDRV_SECTOR_SIZE);
3163 /* Create the qcow2 image (format layer) */
3164 ret = qcow2_co_create(create_options, errp);
3165 if (ret < 0) {
3166 goto finish;
3169 ret = 0;
3170 finish:
3171 QDECREF(qdict);
3172 bdrv_unref(bs);
3173 qapi_free_BlockdevCreateOptions(create_options);
3174 return ret;
3178 static bool is_zero(BlockDriverState *bs, int64_t offset, int64_t bytes)
3180 int64_t nr;
3181 int res;
3183 /* Clamp to image length, before checking status of underlying sectors */
3184 if (offset + bytes > bs->total_sectors * BDRV_SECTOR_SIZE) {
3185 bytes = bs->total_sectors * BDRV_SECTOR_SIZE - offset;
3188 if (!bytes) {
3189 return true;
3191 res = bdrv_block_status_above(bs, NULL, offset, bytes, &nr, NULL, NULL);
3192 return res >= 0 && (res & BDRV_BLOCK_ZERO) && nr == bytes;
3195 static coroutine_fn int qcow2_co_pwrite_zeroes(BlockDriverState *bs,
3196 int64_t offset, int bytes, BdrvRequestFlags flags)
3198 int ret;
3199 BDRVQcow2State *s = bs->opaque;
3201 uint32_t head = offset % s->cluster_size;
3202 uint32_t tail = (offset + bytes) % s->cluster_size;
3204 trace_qcow2_pwrite_zeroes_start_req(qemu_coroutine_self(), offset, bytes);
3205 if (offset + bytes == bs->total_sectors * BDRV_SECTOR_SIZE) {
3206 tail = 0;
3209 if (head || tail) {
3210 uint64_t off;
3211 unsigned int nr;
3213 assert(head + bytes <= s->cluster_size);
3215 /* check whether remainder of cluster already reads as zero */
3216 if (!(is_zero(bs, offset - head, head) &&
3217 is_zero(bs, offset + bytes,
3218 tail ? s->cluster_size - tail : 0))) {
3219 return -ENOTSUP;
3222 qemu_co_mutex_lock(&s->lock);
3223 /* We can have new write after previous check */
3224 offset = QEMU_ALIGN_DOWN(offset, s->cluster_size);
3225 bytes = s->cluster_size;
3226 nr = s->cluster_size;
3227 ret = qcow2_get_cluster_offset(bs, offset, &nr, &off);
3228 if (ret != QCOW2_CLUSTER_UNALLOCATED &&
3229 ret != QCOW2_CLUSTER_ZERO_PLAIN &&
3230 ret != QCOW2_CLUSTER_ZERO_ALLOC) {
3231 qemu_co_mutex_unlock(&s->lock);
3232 return -ENOTSUP;
3234 } else {
3235 qemu_co_mutex_lock(&s->lock);
3238 trace_qcow2_pwrite_zeroes(qemu_coroutine_self(), offset, bytes);
3240 /* Whatever is left can use real zero clusters */
3241 ret = qcow2_cluster_zeroize(bs, offset, bytes, flags);
3242 qemu_co_mutex_unlock(&s->lock);
3244 return ret;
3247 static coroutine_fn int qcow2_co_pdiscard(BlockDriverState *bs,
3248 int64_t offset, int bytes)
3250 int ret;
3251 BDRVQcow2State *s = bs->opaque;
3253 if (!QEMU_IS_ALIGNED(offset | bytes, s->cluster_size)) {
3254 assert(bytes < s->cluster_size);
3255 /* Ignore partial clusters, except for the special case of the
3256 * complete partial cluster at the end of an unaligned file */
3257 if (!QEMU_IS_ALIGNED(offset, s->cluster_size) ||
3258 offset + bytes != bs->total_sectors * BDRV_SECTOR_SIZE) {
3259 return -ENOTSUP;
3263 qemu_co_mutex_lock(&s->lock);
3264 ret = qcow2_cluster_discard(bs, offset, bytes, QCOW2_DISCARD_REQUEST,
3265 false);
3266 qemu_co_mutex_unlock(&s->lock);
3267 return ret;
3270 static int qcow2_truncate(BlockDriverState *bs, int64_t offset,
3271 PreallocMode prealloc, Error **errp)
3273 BDRVQcow2State *s = bs->opaque;
3274 uint64_t old_length;
3275 int64_t new_l1_size;
3276 int ret;
3278 if (prealloc != PREALLOC_MODE_OFF && prealloc != PREALLOC_MODE_METADATA &&
3279 prealloc != PREALLOC_MODE_FALLOC && prealloc != PREALLOC_MODE_FULL)
3281 error_setg(errp, "Unsupported preallocation mode '%s'",
3282 PreallocMode_str(prealloc));
3283 return -ENOTSUP;
3286 if (offset & 511) {
3287 error_setg(errp, "The new size must be a multiple of 512");
3288 return -EINVAL;
3291 /* cannot proceed if image has snapshots */
3292 if (s->nb_snapshots) {
3293 error_setg(errp, "Can't resize an image which has snapshots");
3294 return -ENOTSUP;
3297 /* cannot proceed if image has bitmaps */
3298 if (s->nb_bitmaps) {
3299 /* TODO: resize bitmaps in the image */
3300 error_setg(errp, "Can't resize an image which has bitmaps");
3301 return -ENOTSUP;
3304 old_length = bs->total_sectors * 512;
3305 new_l1_size = size_to_l1(s, offset);
3307 if (offset < old_length) {
3308 int64_t last_cluster, old_file_size;
3309 if (prealloc != PREALLOC_MODE_OFF) {
3310 error_setg(errp,
3311 "Preallocation can't be used for shrinking an image");
3312 return -EINVAL;
3315 ret = qcow2_cluster_discard(bs, ROUND_UP(offset, s->cluster_size),
3316 old_length - ROUND_UP(offset,
3317 s->cluster_size),
3318 QCOW2_DISCARD_ALWAYS, true);
3319 if (ret < 0) {
3320 error_setg_errno(errp, -ret, "Failed to discard cropped clusters");
3321 return ret;
3324 ret = qcow2_shrink_l1_table(bs, new_l1_size);
3325 if (ret < 0) {
3326 error_setg_errno(errp, -ret,
3327 "Failed to reduce the number of L2 tables");
3328 return ret;
3331 ret = qcow2_shrink_reftable(bs);
3332 if (ret < 0) {
3333 error_setg_errno(errp, -ret,
3334 "Failed to discard unused refblocks");
3335 return ret;
3338 old_file_size = bdrv_getlength(bs->file->bs);
3339 if (old_file_size < 0) {
3340 error_setg_errno(errp, -old_file_size,
3341 "Failed to inquire current file length");
3342 return old_file_size;
3344 last_cluster = qcow2_get_last_cluster(bs, old_file_size);
3345 if (last_cluster < 0) {
3346 error_setg_errno(errp, -last_cluster,
3347 "Failed to find the last cluster");
3348 return last_cluster;
3350 if ((last_cluster + 1) * s->cluster_size < old_file_size) {
3351 Error *local_err = NULL;
3353 bdrv_truncate(bs->file, (last_cluster + 1) * s->cluster_size,
3354 PREALLOC_MODE_OFF, &local_err);
3355 if (local_err) {
3356 warn_reportf_err(local_err,
3357 "Failed to truncate the tail of the image: ");
3360 } else {
3361 ret = qcow2_grow_l1_table(bs, new_l1_size, true);
3362 if (ret < 0) {
3363 error_setg_errno(errp, -ret, "Failed to grow the L1 table");
3364 return ret;
3368 switch (prealloc) {
3369 case PREALLOC_MODE_OFF:
3370 break;
3372 case PREALLOC_MODE_METADATA:
3373 ret = preallocate(bs, old_length, offset);
3374 if (ret < 0) {
3375 error_setg_errno(errp, -ret, "Preallocation failed");
3376 return ret;
3378 break;
3380 case PREALLOC_MODE_FALLOC:
3381 case PREALLOC_MODE_FULL:
3383 int64_t allocation_start, host_offset, guest_offset;
3384 int64_t clusters_allocated;
3385 int64_t old_file_size, new_file_size;
3386 uint64_t nb_new_data_clusters, nb_new_l2_tables;
3388 old_file_size = bdrv_getlength(bs->file->bs);
3389 if (old_file_size < 0) {
3390 error_setg_errno(errp, -old_file_size,
3391 "Failed to inquire current file length");
3392 return old_file_size;
3394 old_file_size = ROUND_UP(old_file_size, s->cluster_size);
3396 nb_new_data_clusters = DIV_ROUND_UP(offset - old_length,
3397 s->cluster_size);
3399 /* This is an overestimation; we will not actually allocate space for
3400 * these in the file but just make sure the new refcount structures are
3401 * able to cover them so we will not have to allocate new refblocks
3402 * while entering the data blocks in the potentially new L2 tables.
3403 * (We do not actually care where the L2 tables are placed. Maybe they
3404 * are already allocated or they can be placed somewhere before
3405 * @old_file_size. It does not matter because they will be fully
3406 * allocated automatically, so they do not need to be covered by the
3407 * preallocation. All that matters is that we will not have to allocate
3408 * new refcount structures for them.) */
3409 nb_new_l2_tables = DIV_ROUND_UP(nb_new_data_clusters,
3410 s->cluster_size / sizeof(uint64_t));
3411 /* The cluster range may not be aligned to L2 boundaries, so add one L2
3412 * table for a potential head/tail */
3413 nb_new_l2_tables++;
3415 allocation_start = qcow2_refcount_area(bs, old_file_size,
3416 nb_new_data_clusters +
3417 nb_new_l2_tables,
3418 true, 0, 0);
3419 if (allocation_start < 0) {
3420 error_setg_errno(errp, -allocation_start,
3421 "Failed to resize refcount structures");
3422 return allocation_start;
3425 clusters_allocated = qcow2_alloc_clusters_at(bs, allocation_start,
3426 nb_new_data_clusters);
3427 if (clusters_allocated < 0) {
3428 error_setg_errno(errp, -clusters_allocated,
3429 "Failed to allocate data clusters");
3430 return -clusters_allocated;
3433 assert(clusters_allocated == nb_new_data_clusters);
3435 /* Allocate the data area */
3436 new_file_size = allocation_start +
3437 nb_new_data_clusters * s->cluster_size;
3438 ret = bdrv_truncate(bs->file, new_file_size, prealloc, errp);
3439 if (ret < 0) {
3440 error_prepend(errp, "Failed to resize underlying file: ");
3441 qcow2_free_clusters(bs, allocation_start,
3442 nb_new_data_clusters * s->cluster_size,
3443 QCOW2_DISCARD_OTHER);
3444 return ret;
3447 /* Create the necessary L2 entries */
3448 host_offset = allocation_start;
3449 guest_offset = old_length;
3450 while (nb_new_data_clusters) {
3451 int64_t nb_clusters = MIN(
3452 nb_new_data_clusters,
3453 s->l2_slice_size - offset_to_l2_slice_index(s, guest_offset));
3454 QCowL2Meta allocation = {
3455 .offset = guest_offset,
3456 .alloc_offset = host_offset,
3457 .nb_clusters = nb_clusters,
3459 qemu_co_queue_init(&allocation.dependent_requests);
3461 ret = qcow2_alloc_cluster_link_l2(bs, &allocation);
3462 if (ret < 0) {
3463 error_setg_errno(errp, -ret, "Failed to update L2 tables");
3464 qcow2_free_clusters(bs, host_offset,
3465 nb_new_data_clusters * s->cluster_size,
3466 QCOW2_DISCARD_OTHER);
3467 return ret;
3470 guest_offset += nb_clusters * s->cluster_size;
3471 host_offset += nb_clusters * s->cluster_size;
3472 nb_new_data_clusters -= nb_clusters;
3474 break;
3477 default:
3478 g_assert_not_reached();
3481 if (prealloc != PREALLOC_MODE_OFF) {
3482 /* Flush metadata before actually changing the image size */
3483 ret = bdrv_flush(bs);
3484 if (ret < 0) {
3485 error_setg_errno(errp, -ret,
3486 "Failed to flush the preallocated area to disk");
3487 return ret;
3491 /* write updated header.size */
3492 offset = cpu_to_be64(offset);
3493 ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, size),
3494 &offset, sizeof(uint64_t));
3495 if (ret < 0) {
3496 error_setg_errno(errp, -ret, "Failed to update the image size");
3497 return ret;
3500 s->l1_vm_state_index = new_l1_size;
3501 return 0;
3504 /* XXX: put compressed sectors first, then all the cluster aligned
3505 tables to avoid losing bytes in alignment */
3506 static coroutine_fn int
3507 qcow2_co_pwritev_compressed(BlockDriverState *bs, uint64_t offset,
3508 uint64_t bytes, QEMUIOVector *qiov)
3510 BDRVQcow2State *s = bs->opaque;
3511 QEMUIOVector hd_qiov;
3512 struct iovec iov;
3513 z_stream strm;
3514 int ret, out_len;
3515 uint8_t *buf, *out_buf;
3516 int64_t cluster_offset;
3518 if (bytes == 0) {
3519 /* align end of file to a sector boundary to ease reading with
3520 sector based I/Os */
3521 cluster_offset = bdrv_getlength(bs->file->bs);
3522 if (cluster_offset < 0) {
3523 return cluster_offset;
3525 return bdrv_truncate(bs->file, cluster_offset, PREALLOC_MODE_OFF, NULL);
3528 if (offset_into_cluster(s, offset)) {
3529 return -EINVAL;
3532 buf = qemu_blockalign(bs, s->cluster_size);
3533 if (bytes != s->cluster_size) {
3534 if (bytes > s->cluster_size ||
3535 offset + bytes != bs->total_sectors << BDRV_SECTOR_BITS)
3537 qemu_vfree(buf);
3538 return -EINVAL;
3540 /* Zero-pad last write if image size is not cluster aligned */
3541 memset(buf + bytes, 0, s->cluster_size - bytes);
3543 qemu_iovec_to_buf(qiov, 0, buf, bytes);
3545 out_buf = g_malloc(s->cluster_size);
3547 /* best compression, small window, no zlib header */
3548 memset(&strm, 0, sizeof(strm));
3549 ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
3550 Z_DEFLATED, -12,
3551 9, Z_DEFAULT_STRATEGY);
3552 if (ret != 0) {
3553 ret = -EINVAL;
3554 goto fail;
3557 strm.avail_in = s->cluster_size;
3558 strm.next_in = (uint8_t *)buf;
3559 strm.avail_out = s->cluster_size;
3560 strm.next_out = out_buf;
3562 ret = deflate(&strm, Z_FINISH);
3563 if (ret != Z_STREAM_END && ret != Z_OK) {
3564 deflateEnd(&strm);
3565 ret = -EINVAL;
3566 goto fail;
3568 out_len = strm.next_out - out_buf;
3570 deflateEnd(&strm);
3572 if (ret != Z_STREAM_END || out_len >= s->cluster_size) {
3573 /* could not compress: write normal cluster */
3574 ret = qcow2_co_pwritev(bs, offset, bytes, qiov, 0);
3575 if (ret < 0) {
3576 goto fail;
3578 goto success;
3581 qemu_co_mutex_lock(&s->lock);
3582 cluster_offset =
3583 qcow2_alloc_compressed_cluster_offset(bs, offset, out_len);
3584 if (!cluster_offset) {
3585 qemu_co_mutex_unlock(&s->lock);
3586 ret = -EIO;
3587 goto fail;
3589 cluster_offset &= s->cluster_offset_mask;
3591 ret = qcow2_pre_write_overlap_check(bs, 0, cluster_offset, out_len);
3592 qemu_co_mutex_unlock(&s->lock);
3593 if (ret < 0) {
3594 goto fail;
3597 iov = (struct iovec) {
3598 .iov_base = out_buf,
3599 .iov_len = out_len,
3601 qemu_iovec_init_external(&hd_qiov, &iov, 1);
3603 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_COMPRESSED);
3604 ret = bdrv_co_pwritev(bs->file, cluster_offset, out_len, &hd_qiov, 0);
3605 if (ret < 0) {
3606 goto fail;
3608 success:
3609 ret = 0;
3610 fail:
3611 qemu_vfree(buf);
3612 g_free(out_buf);
3613 return ret;
3616 static int make_completely_empty(BlockDriverState *bs)
3618 BDRVQcow2State *s = bs->opaque;
3619 Error *local_err = NULL;
3620 int ret, l1_clusters;
3621 int64_t offset;
3622 uint64_t *new_reftable = NULL;
3623 uint64_t rt_entry, l1_size2;
3624 struct {
3625 uint64_t l1_offset;
3626 uint64_t reftable_offset;
3627 uint32_t reftable_clusters;
3628 } QEMU_PACKED l1_ofs_rt_ofs_cls;
3630 ret = qcow2_cache_empty(bs, s->l2_table_cache);
3631 if (ret < 0) {
3632 goto fail;
3635 ret = qcow2_cache_empty(bs, s->refcount_block_cache);
3636 if (ret < 0) {
3637 goto fail;
3640 /* Refcounts will be broken utterly */
3641 ret = qcow2_mark_dirty(bs);
3642 if (ret < 0) {
3643 goto fail;
3646 BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
3648 l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / sizeof(uint64_t));
3649 l1_size2 = (uint64_t)s->l1_size * sizeof(uint64_t);
3651 /* After this call, neither the in-memory nor the on-disk refcount
3652 * information accurately describe the actual references */
3654 ret = bdrv_pwrite_zeroes(bs->file, s->l1_table_offset,
3655 l1_clusters * s->cluster_size, 0);
3656 if (ret < 0) {
3657 goto fail_broken_refcounts;
3659 memset(s->l1_table, 0, l1_size2);
3661 BLKDBG_EVENT(bs->file, BLKDBG_EMPTY_IMAGE_PREPARE);
3663 /* Overwrite enough clusters at the beginning of the sectors to place
3664 * the refcount table, a refcount block and the L1 table in; this may
3665 * overwrite parts of the existing refcount and L1 table, which is not
3666 * an issue because the dirty flag is set, complete data loss is in fact
3667 * desired and partial data loss is consequently fine as well */
3668 ret = bdrv_pwrite_zeroes(bs->file, s->cluster_size,
3669 (2 + l1_clusters) * s->cluster_size, 0);
3670 /* This call (even if it failed overall) may have overwritten on-disk
3671 * refcount structures; in that case, the in-memory refcount information
3672 * will probably differ from the on-disk information which makes the BDS
3673 * unusable */
3674 if (ret < 0) {
3675 goto fail_broken_refcounts;
3678 BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
3679 BLKDBG_EVENT(bs->file, BLKDBG_REFTABLE_UPDATE);
3681 /* "Create" an empty reftable (one cluster) directly after the image
3682 * header and an empty L1 table three clusters after the image header;
3683 * the cluster between those two will be used as the first refblock */
3684 l1_ofs_rt_ofs_cls.l1_offset = cpu_to_be64(3 * s->cluster_size);
3685 l1_ofs_rt_ofs_cls.reftable_offset = cpu_to_be64(s->cluster_size);
3686 l1_ofs_rt_ofs_cls.reftable_clusters = cpu_to_be32(1);
3687 ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, l1_table_offset),
3688 &l1_ofs_rt_ofs_cls, sizeof(l1_ofs_rt_ofs_cls));
3689 if (ret < 0) {
3690 goto fail_broken_refcounts;
3693 s->l1_table_offset = 3 * s->cluster_size;
3695 new_reftable = g_try_new0(uint64_t, s->cluster_size / sizeof(uint64_t));
3696 if (!new_reftable) {
3697 ret = -ENOMEM;
3698 goto fail_broken_refcounts;
3701 s->refcount_table_offset = s->cluster_size;
3702 s->refcount_table_size = s->cluster_size / sizeof(uint64_t);
3703 s->max_refcount_table_index = 0;
3705 g_free(s->refcount_table);
3706 s->refcount_table = new_reftable;
3707 new_reftable = NULL;
3709 /* Now the in-memory refcount information again corresponds to the on-disk
3710 * information (reftable is empty and no refblocks (the refblock cache is
3711 * empty)); however, this means some clusters (e.g. the image header) are
3712 * referenced, but not refcounted, but the normal qcow2 code assumes that
3713 * the in-memory information is always correct */
3715 BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_ALLOC);
3717 /* Enter the first refblock into the reftable */
3718 rt_entry = cpu_to_be64(2 * s->cluster_size);
3719 ret = bdrv_pwrite_sync(bs->file, s->cluster_size,
3720 &rt_entry, sizeof(rt_entry));
3721 if (ret < 0) {
3722 goto fail_broken_refcounts;
3724 s->refcount_table[0] = 2 * s->cluster_size;
3726 s->free_cluster_index = 0;
3727 assert(3 + l1_clusters <= s->refcount_block_size);
3728 offset = qcow2_alloc_clusters(bs, 3 * s->cluster_size + l1_size2);
3729 if (offset < 0) {
3730 ret = offset;
3731 goto fail_broken_refcounts;
3732 } else if (offset > 0) {
3733 error_report("First cluster in emptied image is in use");
3734 abort();
3737 /* Now finally the in-memory information corresponds to the on-disk
3738 * structures and is correct */
3739 ret = qcow2_mark_clean(bs);
3740 if (ret < 0) {
3741 goto fail;
3744 ret = bdrv_truncate(bs->file, (3 + l1_clusters) * s->cluster_size,
3745 PREALLOC_MODE_OFF, &local_err);
3746 if (ret < 0) {
3747 error_report_err(local_err);
3748 goto fail;
3751 return 0;
3753 fail_broken_refcounts:
3754 /* The BDS is unusable at this point. If we wanted to make it usable, we
3755 * would have to call qcow2_refcount_close(), qcow2_refcount_init(),
3756 * qcow2_check_refcounts(), qcow2_refcount_close() and qcow2_refcount_init()
3757 * again. However, because the functions which could have caused this error
3758 * path to be taken are used by those functions as well, it's very likely
3759 * that that sequence will fail as well. Therefore, just eject the BDS. */
3760 bs->drv = NULL;
3762 fail:
3763 g_free(new_reftable);
3764 return ret;
3767 static int qcow2_make_empty(BlockDriverState *bs)
3769 BDRVQcow2State *s = bs->opaque;
3770 uint64_t offset, end_offset;
3771 int step = QEMU_ALIGN_DOWN(INT_MAX, s->cluster_size);
3772 int l1_clusters, ret = 0;
3774 l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / sizeof(uint64_t));
3776 if (s->qcow_version >= 3 && !s->snapshots && !s->nb_bitmaps &&
3777 3 + l1_clusters <= s->refcount_block_size &&
3778 s->crypt_method_header != QCOW_CRYPT_LUKS) {
3779 /* The following function only works for qcow2 v3 images (it
3780 * requires the dirty flag) and only as long as there are no
3781 * features that reserve extra clusters (such as snapshots,
3782 * LUKS header, or persistent bitmaps), because it completely
3783 * empties the image. Furthermore, the L1 table and three
3784 * additional clusters (image header, refcount table, one
3785 * refcount block) have to fit inside one refcount block. */
3786 return make_completely_empty(bs);
3789 /* This fallback code simply discards every active cluster; this is slow,
3790 * but works in all cases */
3791 end_offset = bs->total_sectors * BDRV_SECTOR_SIZE;
3792 for (offset = 0; offset < end_offset; offset += step) {
3793 /* As this function is generally used after committing an external
3794 * snapshot, QCOW2_DISCARD_SNAPSHOT seems appropriate. Also, the
3795 * default action for this kind of discard is to pass the discard,
3796 * which will ideally result in an actually smaller image file, as
3797 * is probably desired. */
3798 ret = qcow2_cluster_discard(bs, offset, MIN(step, end_offset - offset),
3799 QCOW2_DISCARD_SNAPSHOT, true);
3800 if (ret < 0) {
3801 break;
3805 return ret;
3808 static coroutine_fn int qcow2_co_flush_to_os(BlockDriverState *bs)
3810 BDRVQcow2State *s = bs->opaque;
3811 int ret;
3813 qemu_co_mutex_lock(&s->lock);
3814 ret = qcow2_write_caches(bs);
3815 qemu_co_mutex_unlock(&s->lock);
3817 return ret;
3820 static BlockMeasureInfo *qcow2_measure(QemuOpts *opts, BlockDriverState *in_bs,
3821 Error **errp)
3823 Error *local_err = NULL;
3824 BlockMeasureInfo *info;
3825 uint64_t required = 0; /* bytes that contribute to required size */
3826 uint64_t virtual_size; /* disk size as seen by guest */
3827 uint64_t refcount_bits;
3828 uint64_t l2_tables;
3829 size_t cluster_size;
3830 int version;
3831 char *optstr;
3832 PreallocMode prealloc;
3833 bool has_backing_file;
3835 /* Parse image creation options */
3836 cluster_size = qcow2_opt_get_cluster_size_del(opts, &local_err);
3837 if (local_err) {
3838 goto err;
3841 version = qcow2_opt_get_version_del(opts, &local_err);
3842 if (local_err) {
3843 goto err;
3846 refcount_bits = qcow2_opt_get_refcount_bits_del(opts, version, &local_err);
3847 if (local_err) {
3848 goto err;
3851 optstr = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
3852 prealloc = qapi_enum_parse(&PreallocMode_lookup, optstr,
3853 PREALLOC_MODE_OFF, &local_err);
3854 g_free(optstr);
3855 if (local_err) {
3856 goto err;
3859 optstr = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
3860 has_backing_file = !!optstr;
3861 g_free(optstr);
3863 virtual_size = qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0);
3864 virtual_size = ROUND_UP(virtual_size, cluster_size);
3866 /* Check that virtual disk size is valid */
3867 l2_tables = DIV_ROUND_UP(virtual_size / cluster_size,
3868 cluster_size / sizeof(uint64_t));
3869 if (l2_tables * sizeof(uint64_t) > QCOW_MAX_L1_SIZE) {
3870 error_setg(&local_err, "The image size is too large "
3871 "(try using a larger cluster size)");
3872 goto err;
3875 /* Account for input image */
3876 if (in_bs) {
3877 int64_t ssize = bdrv_getlength(in_bs);
3878 if (ssize < 0) {
3879 error_setg_errno(&local_err, -ssize,
3880 "Unable to get image virtual_size");
3881 goto err;
3884 virtual_size = ROUND_UP(ssize, cluster_size);
3886 if (has_backing_file) {
3887 /* We don't how much of the backing chain is shared by the input
3888 * image and the new image file. In the worst case the new image's
3889 * backing file has nothing in common with the input image. Be
3890 * conservative and assume all clusters need to be written.
3892 required = virtual_size;
3893 } else {
3894 int64_t offset;
3895 int64_t pnum = 0;
3897 for (offset = 0; offset < ssize; offset += pnum) {
3898 int ret;
3900 ret = bdrv_block_status_above(in_bs, NULL, offset,
3901 ssize - offset, &pnum, NULL,
3902 NULL);
3903 if (ret < 0) {
3904 error_setg_errno(&local_err, -ret,
3905 "Unable to get block status");
3906 goto err;
3909 if (ret & BDRV_BLOCK_ZERO) {
3910 /* Skip zero regions (safe with no backing file) */
3911 } else if ((ret & (BDRV_BLOCK_DATA | BDRV_BLOCK_ALLOCATED)) ==
3912 (BDRV_BLOCK_DATA | BDRV_BLOCK_ALLOCATED)) {
3913 /* Extend pnum to end of cluster for next iteration */
3914 pnum = ROUND_UP(offset + pnum, cluster_size) - offset;
3916 /* Count clusters we've seen */
3917 required += offset % cluster_size + pnum;
3923 /* Take into account preallocation. Nothing special is needed for
3924 * PREALLOC_MODE_METADATA since metadata is always counted.
3926 if (prealloc == PREALLOC_MODE_FULL || prealloc == PREALLOC_MODE_FALLOC) {
3927 required = virtual_size;
3930 info = g_new(BlockMeasureInfo, 1);
3931 info->fully_allocated =
3932 qcow2_calc_prealloc_size(virtual_size, cluster_size,
3933 ctz32(refcount_bits));
3935 /* Remove data clusters that are not required. This overestimates the
3936 * required size because metadata needed for the fully allocated file is
3937 * still counted.
3939 info->required = info->fully_allocated - virtual_size + required;
3940 return info;
3942 err:
3943 error_propagate(errp, local_err);
3944 return NULL;
3947 static int qcow2_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
3949 BDRVQcow2State *s = bs->opaque;
3950 bdi->unallocated_blocks_are_zero = true;
3951 bdi->cluster_size = s->cluster_size;
3952 bdi->vm_state_offset = qcow2_vm_state_offset(s);
3953 return 0;
3956 static ImageInfoSpecific *qcow2_get_specific_info(BlockDriverState *bs)
3958 BDRVQcow2State *s = bs->opaque;
3959 ImageInfoSpecific *spec_info;
3960 QCryptoBlockInfo *encrypt_info = NULL;
3962 if (s->crypto != NULL) {
3963 encrypt_info = qcrypto_block_get_info(s->crypto, &error_abort);
3966 spec_info = g_new(ImageInfoSpecific, 1);
3967 *spec_info = (ImageInfoSpecific){
3968 .type = IMAGE_INFO_SPECIFIC_KIND_QCOW2,
3969 .u.qcow2.data = g_new(ImageInfoSpecificQCow2, 1),
3971 if (s->qcow_version == 2) {
3972 *spec_info->u.qcow2.data = (ImageInfoSpecificQCow2){
3973 .compat = g_strdup("0.10"),
3974 .refcount_bits = s->refcount_bits,
3976 } else if (s->qcow_version == 3) {
3977 *spec_info->u.qcow2.data = (ImageInfoSpecificQCow2){
3978 .compat = g_strdup("1.1"),
3979 .lazy_refcounts = s->compatible_features &
3980 QCOW2_COMPAT_LAZY_REFCOUNTS,
3981 .has_lazy_refcounts = true,
3982 .corrupt = s->incompatible_features &
3983 QCOW2_INCOMPAT_CORRUPT,
3984 .has_corrupt = true,
3985 .refcount_bits = s->refcount_bits,
3987 } else {
3988 /* if this assertion fails, this probably means a new version was
3989 * added without having it covered here */
3990 assert(false);
3993 if (encrypt_info) {
3994 ImageInfoSpecificQCow2Encryption *qencrypt =
3995 g_new(ImageInfoSpecificQCow2Encryption, 1);
3996 switch (encrypt_info->format) {
3997 case Q_CRYPTO_BLOCK_FORMAT_QCOW:
3998 qencrypt->format = BLOCKDEV_QCOW2_ENCRYPTION_FORMAT_AES;
3999 qencrypt->u.aes = encrypt_info->u.qcow;
4000 break;
4001 case Q_CRYPTO_BLOCK_FORMAT_LUKS:
4002 qencrypt->format = BLOCKDEV_QCOW2_ENCRYPTION_FORMAT_LUKS;
4003 qencrypt->u.luks = encrypt_info->u.luks;
4004 break;
4005 default:
4006 abort();
4008 /* Since we did shallow copy above, erase any pointers
4009 * in the original info */
4010 memset(&encrypt_info->u, 0, sizeof(encrypt_info->u));
4011 qapi_free_QCryptoBlockInfo(encrypt_info);
4013 spec_info->u.qcow2.data->has_encrypt = true;
4014 spec_info->u.qcow2.data->encrypt = qencrypt;
4017 return spec_info;
4020 static int qcow2_save_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
4021 int64_t pos)
4023 BDRVQcow2State *s = bs->opaque;
4025 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_SAVE);
4026 return bs->drv->bdrv_co_pwritev(bs, qcow2_vm_state_offset(s) + pos,
4027 qiov->size, qiov, 0);
4030 static int qcow2_load_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
4031 int64_t pos)
4033 BDRVQcow2State *s = bs->opaque;
4035 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_LOAD);
4036 return bs->drv->bdrv_co_preadv(bs, qcow2_vm_state_offset(s) + pos,
4037 qiov->size, qiov, 0);
4041 * Downgrades an image's version. To achieve this, any incompatible features
4042 * have to be removed.
4044 static int qcow2_downgrade(BlockDriverState *bs, int target_version,
4045 BlockDriverAmendStatusCB *status_cb, void *cb_opaque)
4047 BDRVQcow2State *s = bs->opaque;
4048 int current_version = s->qcow_version;
4049 int ret;
4051 if (target_version == current_version) {
4052 return 0;
4053 } else if (target_version > current_version) {
4054 return -EINVAL;
4055 } else if (target_version != 2) {
4056 return -EINVAL;
4059 if (s->refcount_order != 4) {
4060 error_report("compat=0.10 requires refcount_bits=16");
4061 return -ENOTSUP;
4064 /* clear incompatible features */
4065 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
4066 ret = qcow2_mark_clean(bs);
4067 if (ret < 0) {
4068 return ret;
4072 /* with QCOW2_INCOMPAT_CORRUPT, it is pretty much impossible to get here in
4073 * the first place; if that happens nonetheless, returning -ENOTSUP is the
4074 * best thing to do anyway */
4076 if (s->incompatible_features) {
4077 return -ENOTSUP;
4080 /* since we can ignore compatible features, we can set them to 0 as well */
4081 s->compatible_features = 0;
4082 /* if lazy refcounts have been used, they have already been fixed through
4083 * clearing the dirty flag */
4085 /* clearing autoclear features is trivial */
4086 s->autoclear_features = 0;
4088 ret = qcow2_expand_zero_clusters(bs, status_cb, cb_opaque);
4089 if (ret < 0) {
4090 return ret;
4093 s->qcow_version = target_version;
4094 ret = qcow2_update_header(bs);
4095 if (ret < 0) {
4096 s->qcow_version = current_version;
4097 return ret;
4099 return 0;
4102 typedef enum Qcow2AmendOperation {
4103 /* This is the value Qcow2AmendHelperCBInfo::last_operation will be
4104 * statically initialized to so that the helper CB can discern the first
4105 * invocation from an operation change */
4106 QCOW2_NO_OPERATION = 0,
4108 QCOW2_CHANGING_REFCOUNT_ORDER,
4109 QCOW2_DOWNGRADING,
4110 } Qcow2AmendOperation;
4112 typedef struct Qcow2AmendHelperCBInfo {
4113 /* The code coordinating the amend operations should only modify
4114 * these four fields; the rest will be managed by the CB */
4115 BlockDriverAmendStatusCB *original_status_cb;
4116 void *original_cb_opaque;
4118 Qcow2AmendOperation current_operation;
4120 /* Total number of operations to perform (only set once) */
4121 int total_operations;
4123 /* The following fields are managed by the CB */
4125 /* Number of operations completed */
4126 int operations_completed;
4128 /* Cumulative offset of all completed operations */
4129 int64_t offset_completed;
4131 Qcow2AmendOperation last_operation;
4132 int64_t last_work_size;
4133 } Qcow2AmendHelperCBInfo;
4135 static void qcow2_amend_helper_cb(BlockDriverState *bs,
4136 int64_t operation_offset,
4137 int64_t operation_work_size, void *opaque)
4139 Qcow2AmendHelperCBInfo *info = opaque;
4140 int64_t current_work_size;
4141 int64_t projected_work_size;
4143 if (info->current_operation != info->last_operation) {
4144 if (info->last_operation != QCOW2_NO_OPERATION) {
4145 info->offset_completed += info->last_work_size;
4146 info->operations_completed++;
4149 info->last_operation = info->current_operation;
4152 assert(info->total_operations > 0);
4153 assert(info->operations_completed < info->total_operations);
4155 info->last_work_size = operation_work_size;
4157 current_work_size = info->offset_completed + operation_work_size;
4159 /* current_work_size is the total work size for (operations_completed + 1)
4160 * operations (which includes this one), so multiply it by the number of
4161 * operations not covered and divide it by the number of operations
4162 * covered to get a projection for the operations not covered */
4163 projected_work_size = current_work_size * (info->total_operations -
4164 info->operations_completed - 1)
4165 / (info->operations_completed + 1);
4167 info->original_status_cb(bs, info->offset_completed + operation_offset,
4168 current_work_size + projected_work_size,
4169 info->original_cb_opaque);
4172 static int qcow2_amend_options(BlockDriverState *bs, QemuOpts *opts,
4173 BlockDriverAmendStatusCB *status_cb,
4174 void *cb_opaque)
4176 BDRVQcow2State *s = bs->opaque;
4177 int old_version = s->qcow_version, new_version = old_version;
4178 uint64_t new_size = 0;
4179 const char *backing_file = NULL, *backing_format = NULL;
4180 bool lazy_refcounts = s->use_lazy_refcounts;
4181 const char *compat = NULL;
4182 uint64_t cluster_size = s->cluster_size;
4183 bool encrypt;
4184 int encformat;
4185 int refcount_bits = s->refcount_bits;
4186 Error *local_err = NULL;
4187 int ret;
4188 QemuOptDesc *desc = opts->list->desc;
4189 Qcow2AmendHelperCBInfo helper_cb_info;
4191 while (desc && desc->name) {
4192 if (!qemu_opt_find(opts, desc->name)) {
4193 /* only change explicitly defined options */
4194 desc++;
4195 continue;
4198 if (!strcmp(desc->name, BLOCK_OPT_COMPAT_LEVEL)) {
4199 compat = qemu_opt_get(opts, BLOCK_OPT_COMPAT_LEVEL);
4200 if (!compat) {
4201 /* preserve default */
4202 } else if (!strcmp(compat, "0.10")) {
4203 new_version = 2;
4204 } else if (!strcmp(compat, "1.1")) {
4205 new_version = 3;
4206 } else {
4207 error_report("Unknown compatibility level %s", compat);
4208 return -EINVAL;
4210 } else if (!strcmp(desc->name, BLOCK_OPT_PREALLOC)) {
4211 error_report("Cannot change preallocation mode");
4212 return -ENOTSUP;
4213 } else if (!strcmp(desc->name, BLOCK_OPT_SIZE)) {
4214 new_size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, 0);
4215 } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FILE)) {
4216 backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
4217 } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FMT)) {
4218 backing_format = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
4219 } else if (!strcmp(desc->name, BLOCK_OPT_ENCRYPT)) {
4220 encrypt = qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT,
4221 !!s->crypto);
4223 if (encrypt != !!s->crypto) {
4224 error_report("Changing the encryption flag is not supported");
4225 return -ENOTSUP;
4227 } else if (!strcmp(desc->name, BLOCK_OPT_ENCRYPT_FORMAT)) {
4228 encformat = qcow2_crypt_method_from_format(
4229 qemu_opt_get(opts, BLOCK_OPT_ENCRYPT_FORMAT));
4231 if (encformat != s->crypt_method_header) {
4232 error_report("Changing the encryption format is not supported");
4233 return -ENOTSUP;
4235 } else if (g_str_has_prefix(desc->name, "encrypt.")) {
4236 error_report("Changing the encryption parameters is not supported");
4237 return -ENOTSUP;
4238 } else if (!strcmp(desc->name, BLOCK_OPT_CLUSTER_SIZE)) {
4239 cluster_size = qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE,
4240 cluster_size);
4241 if (cluster_size != s->cluster_size) {
4242 error_report("Changing the cluster size is not supported");
4243 return -ENOTSUP;
4245 } else if (!strcmp(desc->name, BLOCK_OPT_LAZY_REFCOUNTS)) {
4246 lazy_refcounts = qemu_opt_get_bool(opts, BLOCK_OPT_LAZY_REFCOUNTS,
4247 lazy_refcounts);
4248 } else if (!strcmp(desc->name, BLOCK_OPT_REFCOUNT_BITS)) {
4249 refcount_bits = qemu_opt_get_number(opts, BLOCK_OPT_REFCOUNT_BITS,
4250 refcount_bits);
4252 if (refcount_bits <= 0 || refcount_bits > 64 ||
4253 !is_power_of_2(refcount_bits))
4255 error_report("Refcount width must be a power of two and may "
4256 "not exceed 64 bits");
4257 return -EINVAL;
4259 } else {
4260 /* if this point is reached, this probably means a new option was
4261 * added without having it covered here */
4262 abort();
4265 desc++;
4268 helper_cb_info = (Qcow2AmendHelperCBInfo){
4269 .original_status_cb = status_cb,
4270 .original_cb_opaque = cb_opaque,
4271 .total_operations = (new_version < old_version)
4272 + (s->refcount_bits != refcount_bits)
4275 /* Upgrade first (some features may require compat=1.1) */
4276 if (new_version > old_version) {
4277 s->qcow_version = new_version;
4278 ret = qcow2_update_header(bs);
4279 if (ret < 0) {
4280 s->qcow_version = old_version;
4281 return ret;
4285 if (s->refcount_bits != refcount_bits) {
4286 int refcount_order = ctz32(refcount_bits);
4288 if (new_version < 3 && refcount_bits != 16) {
4289 error_report("Different refcount widths than 16 bits require "
4290 "compatibility level 1.1 or above (use compat=1.1 or "
4291 "greater)");
4292 return -EINVAL;
4295 helper_cb_info.current_operation = QCOW2_CHANGING_REFCOUNT_ORDER;
4296 ret = qcow2_change_refcount_order(bs, refcount_order,
4297 &qcow2_amend_helper_cb,
4298 &helper_cb_info, &local_err);
4299 if (ret < 0) {
4300 error_report_err(local_err);
4301 return ret;
4305 if (backing_file || backing_format) {
4306 ret = qcow2_change_backing_file(bs,
4307 backing_file ?: s->image_backing_file,
4308 backing_format ?: s->image_backing_format);
4309 if (ret < 0) {
4310 return ret;
4314 if (s->use_lazy_refcounts != lazy_refcounts) {
4315 if (lazy_refcounts) {
4316 if (new_version < 3) {
4317 error_report("Lazy refcounts only supported with compatibility "
4318 "level 1.1 and above (use compat=1.1 or greater)");
4319 return -EINVAL;
4321 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
4322 ret = qcow2_update_header(bs);
4323 if (ret < 0) {
4324 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
4325 return ret;
4327 s->use_lazy_refcounts = true;
4328 } else {
4329 /* make image clean first */
4330 ret = qcow2_mark_clean(bs);
4331 if (ret < 0) {
4332 return ret;
4334 /* now disallow lazy refcounts */
4335 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
4336 ret = qcow2_update_header(bs);
4337 if (ret < 0) {
4338 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
4339 return ret;
4341 s->use_lazy_refcounts = false;
4345 if (new_size) {
4346 BlockBackend *blk = blk_new(BLK_PERM_RESIZE, BLK_PERM_ALL);
4347 ret = blk_insert_bs(blk, bs, &local_err);
4348 if (ret < 0) {
4349 error_report_err(local_err);
4350 blk_unref(blk);
4351 return ret;
4354 ret = blk_truncate(blk, new_size, PREALLOC_MODE_OFF, &local_err);
4355 blk_unref(blk);
4356 if (ret < 0) {
4357 error_report_err(local_err);
4358 return ret;
4362 /* Downgrade last (so unsupported features can be removed before) */
4363 if (new_version < old_version) {
4364 helper_cb_info.current_operation = QCOW2_DOWNGRADING;
4365 ret = qcow2_downgrade(bs, new_version, &qcow2_amend_helper_cb,
4366 &helper_cb_info);
4367 if (ret < 0) {
4368 return ret;
4372 return 0;
4376 * If offset or size are negative, respectively, they will not be included in
4377 * the BLOCK_IMAGE_CORRUPTED event emitted.
4378 * fatal will be ignored for read-only BDS; corruptions found there will always
4379 * be considered non-fatal.
4381 void qcow2_signal_corruption(BlockDriverState *bs, bool fatal, int64_t offset,
4382 int64_t size, const char *message_format, ...)
4384 BDRVQcow2State *s = bs->opaque;
4385 const char *node_name;
4386 char *message;
4387 va_list ap;
4389 fatal = fatal && !bs->read_only;
4391 if (s->signaled_corruption &&
4392 (!fatal || (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT)))
4394 return;
4397 va_start(ap, message_format);
4398 message = g_strdup_vprintf(message_format, ap);
4399 va_end(ap);
4401 if (fatal) {
4402 fprintf(stderr, "qcow2: Marking image as corrupt: %s; further "
4403 "corruption events will be suppressed\n", message);
4404 } else {
4405 fprintf(stderr, "qcow2: Image is corrupt: %s; further non-fatal "
4406 "corruption events will be suppressed\n", message);
4409 node_name = bdrv_get_node_name(bs);
4410 qapi_event_send_block_image_corrupted(bdrv_get_device_name(bs),
4411 *node_name != '\0', node_name,
4412 message, offset >= 0, offset,
4413 size >= 0, size,
4414 fatal, &error_abort);
4415 g_free(message);
4417 if (fatal) {
4418 qcow2_mark_corrupt(bs);
4419 bs->drv = NULL; /* make BDS unusable */
4422 s->signaled_corruption = true;
4425 static QemuOptsList qcow2_create_opts = {
4426 .name = "qcow2-create-opts",
4427 .head = QTAILQ_HEAD_INITIALIZER(qcow2_create_opts.head),
4428 .desc = {
4430 .name = BLOCK_OPT_SIZE,
4431 .type = QEMU_OPT_SIZE,
4432 .help = "Virtual disk size"
4435 .name = BLOCK_OPT_COMPAT_LEVEL,
4436 .type = QEMU_OPT_STRING,
4437 .help = "Compatibility level (0.10 or 1.1)"
4440 .name = BLOCK_OPT_BACKING_FILE,
4441 .type = QEMU_OPT_STRING,
4442 .help = "File name of a base image"
4445 .name = BLOCK_OPT_BACKING_FMT,
4446 .type = QEMU_OPT_STRING,
4447 .help = "Image format of the base image"
4450 .name = BLOCK_OPT_ENCRYPT,
4451 .type = QEMU_OPT_BOOL,
4452 .help = "Encrypt the image with format 'aes'. (Deprecated "
4453 "in favor of " BLOCK_OPT_ENCRYPT_FORMAT "=aes)",
4456 .name = BLOCK_OPT_ENCRYPT_FORMAT,
4457 .type = QEMU_OPT_STRING,
4458 .help = "Encrypt the image, format choices: 'aes', 'luks'",
4460 BLOCK_CRYPTO_OPT_DEF_KEY_SECRET("encrypt.",
4461 "ID of secret providing qcow AES key or LUKS passphrase"),
4462 BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_ALG("encrypt."),
4463 BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_MODE("encrypt."),
4464 BLOCK_CRYPTO_OPT_DEF_LUKS_IVGEN_ALG("encrypt."),
4465 BLOCK_CRYPTO_OPT_DEF_LUKS_IVGEN_HASH_ALG("encrypt."),
4466 BLOCK_CRYPTO_OPT_DEF_LUKS_HASH_ALG("encrypt."),
4467 BLOCK_CRYPTO_OPT_DEF_LUKS_ITER_TIME("encrypt."),
4469 .name = BLOCK_OPT_CLUSTER_SIZE,
4470 .type = QEMU_OPT_SIZE,
4471 .help = "qcow2 cluster size",
4472 .def_value_str = stringify(DEFAULT_CLUSTER_SIZE)
4475 .name = BLOCK_OPT_PREALLOC,
4476 .type = QEMU_OPT_STRING,
4477 .help = "Preallocation mode (allowed values: off, metadata, "
4478 "falloc, full)"
4481 .name = BLOCK_OPT_LAZY_REFCOUNTS,
4482 .type = QEMU_OPT_BOOL,
4483 .help = "Postpone refcount updates",
4484 .def_value_str = "off"
4487 .name = BLOCK_OPT_REFCOUNT_BITS,
4488 .type = QEMU_OPT_NUMBER,
4489 .help = "Width of a reference count entry in bits",
4490 .def_value_str = "16"
4492 { /* end of list */ }
4496 BlockDriver bdrv_qcow2 = {
4497 .format_name = "qcow2",
4498 .instance_size = sizeof(BDRVQcow2State),
4499 .bdrv_probe = qcow2_probe,
4500 .bdrv_open = qcow2_open,
4501 .bdrv_close = qcow2_close,
4502 .bdrv_reopen_prepare = qcow2_reopen_prepare,
4503 .bdrv_reopen_commit = qcow2_reopen_commit,
4504 .bdrv_reopen_abort = qcow2_reopen_abort,
4505 .bdrv_join_options = qcow2_join_options,
4506 .bdrv_child_perm = bdrv_format_default_perms,
4507 .bdrv_co_create_opts = qcow2_co_create_opts,
4508 .bdrv_co_create = qcow2_co_create,
4509 .bdrv_has_zero_init = bdrv_has_zero_init_1,
4510 .bdrv_co_block_status = qcow2_co_block_status,
4512 .bdrv_co_preadv = qcow2_co_preadv,
4513 .bdrv_co_pwritev = qcow2_co_pwritev,
4514 .bdrv_co_flush_to_os = qcow2_co_flush_to_os,
4516 .bdrv_co_pwrite_zeroes = qcow2_co_pwrite_zeroes,
4517 .bdrv_co_pdiscard = qcow2_co_pdiscard,
4518 .bdrv_truncate = qcow2_truncate,
4519 .bdrv_co_pwritev_compressed = qcow2_co_pwritev_compressed,
4520 .bdrv_make_empty = qcow2_make_empty,
4522 .bdrv_snapshot_create = qcow2_snapshot_create,
4523 .bdrv_snapshot_goto = qcow2_snapshot_goto,
4524 .bdrv_snapshot_delete = qcow2_snapshot_delete,
4525 .bdrv_snapshot_list = qcow2_snapshot_list,
4526 .bdrv_snapshot_load_tmp = qcow2_snapshot_load_tmp,
4527 .bdrv_measure = qcow2_measure,
4528 .bdrv_get_info = qcow2_get_info,
4529 .bdrv_get_specific_info = qcow2_get_specific_info,
4531 .bdrv_save_vmstate = qcow2_save_vmstate,
4532 .bdrv_load_vmstate = qcow2_load_vmstate,
4534 .supports_backing = true,
4535 .bdrv_change_backing_file = qcow2_change_backing_file,
4537 .bdrv_refresh_limits = qcow2_refresh_limits,
4538 .bdrv_co_invalidate_cache = qcow2_co_invalidate_cache,
4539 .bdrv_inactivate = qcow2_inactivate,
4541 .create_opts = &qcow2_create_opts,
4542 .bdrv_co_check = qcow2_co_check,
4543 .bdrv_amend_options = qcow2_amend_options,
4545 .bdrv_detach_aio_context = qcow2_detach_aio_context,
4546 .bdrv_attach_aio_context = qcow2_attach_aio_context,
4548 .bdrv_reopen_bitmaps_rw = qcow2_reopen_bitmaps_rw,
4549 .bdrv_can_store_new_dirty_bitmap = qcow2_can_store_new_dirty_bitmap,
4550 .bdrv_remove_persistent_dirty_bitmap = qcow2_remove_persistent_dirty_bitmap,
4553 static void bdrv_qcow2_init(void)
4555 bdrv_register(&bdrv_qcow2);
4558 block_init(bdrv_qcow2_init);