qcow2: do encryption in threads
[qemu/ar7.git] / block / qcow2.c
blobdea765b2f4dfb847d6a99dc2e88c2b75560f3eb7
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"
27 #include "block/qdict.h"
28 #include "sysemu/block-backend.h"
29 #include "qemu/module.h"
30 #include "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 "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
71 #define QCOW2_EXT_MAGIC_DATA_FILE 0x44415441
73 static int coroutine_fn
74 qcow2_co_preadv_compressed(BlockDriverState *bs,
75 uint64_t file_cluster_offset,
76 uint64_t offset,
77 uint64_t bytes,
78 QEMUIOVector *qiov);
80 static int qcow2_probe(const uint8_t *buf, int buf_size, const char *filename)
82 const QCowHeader *cow_header = (const void *)buf;
84 if (buf_size >= sizeof(QCowHeader) &&
85 be32_to_cpu(cow_header->magic) == QCOW_MAGIC &&
86 be32_to_cpu(cow_header->version) >= 2)
87 return 100;
88 else
89 return 0;
93 static ssize_t qcow2_crypto_hdr_read_func(QCryptoBlock *block, size_t offset,
94 uint8_t *buf, size_t buflen,
95 void *opaque, Error **errp)
97 BlockDriverState *bs = opaque;
98 BDRVQcow2State *s = bs->opaque;
99 ssize_t ret;
101 if ((offset + buflen) > s->crypto_header.length) {
102 error_setg(errp, "Request for data outside of extension header");
103 return -1;
106 ret = bdrv_pread(bs->file,
107 s->crypto_header.offset + offset, buf, buflen);
108 if (ret < 0) {
109 error_setg_errno(errp, -ret, "Could not read encryption header");
110 return -1;
112 return ret;
116 static ssize_t qcow2_crypto_hdr_init_func(QCryptoBlock *block, size_t headerlen,
117 void *opaque, Error **errp)
119 BlockDriverState *bs = opaque;
120 BDRVQcow2State *s = bs->opaque;
121 int64_t ret;
122 int64_t clusterlen;
124 ret = qcow2_alloc_clusters(bs, headerlen);
125 if (ret < 0) {
126 error_setg_errno(errp, -ret,
127 "Cannot allocate cluster for LUKS header size %zu",
128 headerlen);
129 return -1;
132 s->crypto_header.length = headerlen;
133 s->crypto_header.offset = ret;
135 /* Zero fill remaining space in cluster so it has predictable
136 * content in case of future spec changes */
137 clusterlen = size_to_clusters(s, headerlen) * s->cluster_size;
138 assert(qcow2_pre_write_overlap_check(bs, 0, ret, clusterlen, false) == 0);
139 ret = bdrv_pwrite_zeroes(bs->file,
140 ret + headerlen,
141 clusterlen - headerlen, 0);
142 if (ret < 0) {
143 error_setg_errno(errp, -ret, "Could not zero fill encryption header");
144 return -1;
147 return ret;
151 static ssize_t qcow2_crypto_hdr_write_func(QCryptoBlock *block, size_t offset,
152 const uint8_t *buf, size_t buflen,
153 void *opaque, Error **errp)
155 BlockDriverState *bs = opaque;
156 BDRVQcow2State *s = bs->opaque;
157 ssize_t ret;
159 if ((offset + buflen) > s->crypto_header.length) {
160 error_setg(errp, "Request for data outside of extension header");
161 return -1;
164 ret = bdrv_pwrite(bs->file,
165 s->crypto_header.offset + offset, buf, buflen);
166 if (ret < 0) {
167 error_setg_errno(errp, -ret, "Could not read encryption header");
168 return -1;
170 return ret;
175 * read qcow2 extension and fill bs
176 * start reading from start_offset
177 * finish reading upon magic of value 0 or when end_offset reached
178 * unknown magic is skipped (future extension this version knows nothing about)
179 * return 0 upon success, non-0 otherwise
181 static int qcow2_read_extensions(BlockDriverState *bs, uint64_t start_offset,
182 uint64_t end_offset, void **p_feature_table,
183 int flags, bool *need_update_header,
184 Error **errp)
186 BDRVQcow2State *s = bs->opaque;
187 QCowExtension ext;
188 uint64_t offset;
189 int ret;
190 Qcow2BitmapHeaderExt bitmaps_ext;
192 if (need_update_header != NULL) {
193 *need_update_header = false;
196 #ifdef DEBUG_EXT
197 printf("qcow2_read_extensions: start=%ld end=%ld\n", start_offset, end_offset);
198 #endif
199 offset = start_offset;
200 while (offset < end_offset) {
202 #ifdef DEBUG_EXT
203 /* Sanity check */
204 if (offset > s->cluster_size)
205 printf("qcow2_read_extension: suspicious offset %lu\n", offset);
207 printf("attempting to read extended header in offset %lu\n", offset);
208 #endif
210 ret = bdrv_pread(bs->file, offset, &ext, sizeof(ext));
211 if (ret < 0) {
212 error_setg_errno(errp, -ret, "qcow2_read_extension: ERROR: "
213 "pread fail from offset %" PRIu64, offset);
214 return 1;
216 ext.magic = be32_to_cpu(ext.magic);
217 ext.len = be32_to_cpu(ext.len);
218 offset += sizeof(ext);
219 #ifdef DEBUG_EXT
220 printf("ext.magic = 0x%x\n", ext.magic);
221 #endif
222 if (offset > end_offset || ext.len > end_offset - offset) {
223 error_setg(errp, "Header extension too large");
224 return -EINVAL;
227 switch (ext.magic) {
228 case QCOW2_EXT_MAGIC_END:
229 return 0;
231 case QCOW2_EXT_MAGIC_BACKING_FORMAT:
232 if (ext.len >= sizeof(bs->backing_format)) {
233 error_setg(errp, "ERROR: ext_backing_format: len=%" PRIu32
234 " too large (>=%zu)", ext.len,
235 sizeof(bs->backing_format));
236 return 2;
238 ret = bdrv_pread(bs->file, offset, bs->backing_format, ext.len);
239 if (ret < 0) {
240 error_setg_errno(errp, -ret, "ERROR: ext_backing_format: "
241 "Could not read format name");
242 return 3;
244 bs->backing_format[ext.len] = '\0';
245 s->image_backing_format = g_strdup(bs->backing_format);
246 #ifdef DEBUG_EXT
247 printf("Qcow2: Got format extension %s\n", bs->backing_format);
248 #endif
249 break;
251 case QCOW2_EXT_MAGIC_FEATURE_TABLE:
252 if (p_feature_table != NULL) {
253 void* feature_table = g_malloc0(ext.len + 2 * sizeof(Qcow2Feature));
254 ret = bdrv_pread(bs->file, offset , feature_table, ext.len);
255 if (ret < 0) {
256 error_setg_errno(errp, -ret, "ERROR: ext_feature_table: "
257 "Could not read table");
258 return ret;
261 *p_feature_table = feature_table;
263 break;
265 case QCOW2_EXT_MAGIC_CRYPTO_HEADER: {
266 unsigned int cflags = 0;
267 if (s->crypt_method_header != QCOW_CRYPT_LUKS) {
268 error_setg(errp, "CRYPTO header extension only "
269 "expected with LUKS encryption method");
270 return -EINVAL;
272 if (ext.len != sizeof(Qcow2CryptoHeaderExtension)) {
273 error_setg(errp, "CRYPTO header extension size %u, "
274 "but expected size %zu", ext.len,
275 sizeof(Qcow2CryptoHeaderExtension));
276 return -EINVAL;
279 ret = bdrv_pread(bs->file, offset, &s->crypto_header, ext.len);
280 if (ret < 0) {
281 error_setg_errno(errp, -ret,
282 "Unable to read CRYPTO header extension");
283 return ret;
285 s->crypto_header.offset = be64_to_cpu(s->crypto_header.offset);
286 s->crypto_header.length = be64_to_cpu(s->crypto_header.length);
288 if ((s->crypto_header.offset % s->cluster_size) != 0) {
289 error_setg(errp, "Encryption header offset '%" PRIu64 "' is "
290 "not a multiple of cluster size '%u'",
291 s->crypto_header.offset, s->cluster_size);
292 return -EINVAL;
295 if (flags & BDRV_O_NO_IO) {
296 cflags |= QCRYPTO_BLOCK_OPEN_NO_IO;
298 s->crypto = qcrypto_block_open(s->crypto_opts, "encrypt.",
299 qcow2_crypto_hdr_read_func,
300 bs, cflags, QCOW2_MAX_THREADS, errp);
301 if (!s->crypto) {
302 return -EINVAL;
304 } break;
306 case QCOW2_EXT_MAGIC_BITMAPS:
307 if (ext.len != sizeof(bitmaps_ext)) {
308 error_setg_errno(errp, -ret, "bitmaps_ext: "
309 "Invalid extension length");
310 return -EINVAL;
313 if (!(s->autoclear_features & QCOW2_AUTOCLEAR_BITMAPS)) {
314 if (s->qcow_version < 3) {
315 /* Let's be a bit more specific */
316 warn_report("This qcow2 v2 image contains bitmaps, but "
317 "they may have been modified by a program "
318 "without persistent bitmap support; so now "
319 "they must all be considered inconsistent");
320 } else {
321 warn_report("a program lacking bitmap support "
322 "modified this file, so all bitmaps are now "
323 "considered inconsistent");
325 error_printf("Some clusters may be leaked, "
326 "run 'qemu-img check -r' on the image "
327 "file to fix.");
328 if (need_update_header != NULL) {
329 /* Updating is needed to drop invalid bitmap extension. */
330 *need_update_header = true;
332 break;
335 ret = bdrv_pread(bs->file, offset, &bitmaps_ext, ext.len);
336 if (ret < 0) {
337 error_setg_errno(errp, -ret, "bitmaps_ext: "
338 "Could not read ext header");
339 return ret;
342 if (bitmaps_ext.reserved32 != 0) {
343 error_setg_errno(errp, -ret, "bitmaps_ext: "
344 "Reserved field is not zero");
345 return -EINVAL;
348 bitmaps_ext.nb_bitmaps = be32_to_cpu(bitmaps_ext.nb_bitmaps);
349 bitmaps_ext.bitmap_directory_size =
350 be64_to_cpu(bitmaps_ext.bitmap_directory_size);
351 bitmaps_ext.bitmap_directory_offset =
352 be64_to_cpu(bitmaps_ext.bitmap_directory_offset);
354 if (bitmaps_ext.nb_bitmaps > QCOW2_MAX_BITMAPS) {
355 error_setg(errp,
356 "bitmaps_ext: Image has %" PRIu32 " bitmaps, "
357 "exceeding the QEMU supported maximum of %d",
358 bitmaps_ext.nb_bitmaps, QCOW2_MAX_BITMAPS);
359 return -EINVAL;
362 if (bitmaps_ext.nb_bitmaps == 0) {
363 error_setg(errp, "found bitmaps extension with zero bitmaps");
364 return -EINVAL;
367 if (bitmaps_ext.bitmap_directory_offset & (s->cluster_size - 1)) {
368 error_setg(errp, "bitmaps_ext: "
369 "invalid bitmap directory offset");
370 return -EINVAL;
373 if (bitmaps_ext.bitmap_directory_size >
374 QCOW2_MAX_BITMAP_DIRECTORY_SIZE) {
375 error_setg(errp, "bitmaps_ext: "
376 "bitmap directory size (%" PRIu64 ") exceeds "
377 "the maximum supported size (%d)",
378 bitmaps_ext.bitmap_directory_size,
379 QCOW2_MAX_BITMAP_DIRECTORY_SIZE);
380 return -EINVAL;
383 s->nb_bitmaps = bitmaps_ext.nb_bitmaps;
384 s->bitmap_directory_offset =
385 bitmaps_ext.bitmap_directory_offset;
386 s->bitmap_directory_size =
387 bitmaps_ext.bitmap_directory_size;
389 #ifdef DEBUG_EXT
390 printf("Qcow2: Got bitmaps extension: "
391 "offset=%" PRIu64 " nb_bitmaps=%" PRIu32 "\n",
392 s->bitmap_directory_offset, s->nb_bitmaps);
393 #endif
394 break;
396 case QCOW2_EXT_MAGIC_DATA_FILE:
398 s->image_data_file = g_malloc0(ext.len + 1);
399 ret = bdrv_pread(bs->file, offset, s->image_data_file, ext.len);
400 if (ret < 0) {
401 error_setg_errno(errp, -ret,
402 "ERROR: Could not read data file name");
403 return ret;
405 #ifdef DEBUG_EXT
406 printf("Qcow2: Got external data file %s\n", s->image_data_file);
407 #endif
408 break;
411 default:
412 /* unknown magic - save it in case we need to rewrite the header */
413 /* If you add a new feature, make sure to also update the fast
414 * path of qcow2_make_empty() to deal with it. */
416 Qcow2UnknownHeaderExtension *uext;
418 uext = g_malloc0(sizeof(*uext) + ext.len);
419 uext->magic = ext.magic;
420 uext->len = ext.len;
421 QLIST_INSERT_HEAD(&s->unknown_header_ext, uext, next);
423 ret = bdrv_pread(bs->file, offset , uext->data, uext->len);
424 if (ret < 0) {
425 error_setg_errno(errp, -ret, "ERROR: unknown extension: "
426 "Could not read data");
427 return ret;
430 break;
433 offset += ((ext.len + 7) & ~7);
436 return 0;
439 static void cleanup_unknown_header_ext(BlockDriverState *bs)
441 BDRVQcow2State *s = bs->opaque;
442 Qcow2UnknownHeaderExtension *uext, *next;
444 QLIST_FOREACH_SAFE(uext, &s->unknown_header_ext, next, next) {
445 QLIST_REMOVE(uext, next);
446 g_free(uext);
450 static void report_unsupported_feature(Error **errp, Qcow2Feature *table,
451 uint64_t mask)
453 char *features = g_strdup("");
454 char *old;
456 while (table && table->name[0] != '\0') {
457 if (table->type == QCOW2_FEAT_TYPE_INCOMPATIBLE) {
458 if (mask & (1ULL << table->bit)) {
459 old = features;
460 features = g_strdup_printf("%s%s%.46s", old, *old ? ", " : "",
461 table->name);
462 g_free(old);
463 mask &= ~(1ULL << table->bit);
466 table++;
469 if (mask) {
470 old = features;
471 features = g_strdup_printf("%s%sUnknown incompatible feature: %" PRIx64,
472 old, *old ? ", " : "", mask);
473 g_free(old);
476 error_setg(errp, "Unsupported qcow2 feature(s): %s", features);
477 g_free(features);
481 * Sets the dirty bit and flushes afterwards if necessary.
483 * The incompatible_features bit is only set if the image file header was
484 * updated successfully. Therefore it is not required to check the return
485 * value of this function.
487 int qcow2_mark_dirty(BlockDriverState *bs)
489 BDRVQcow2State *s = bs->opaque;
490 uint64_t val;
491 int ret;
493 assert(s->qcow_version >= 3);
495 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
496 return 0; /* already dirty */
499 val = cpu_to_be64(s->incompatible_features | QCOW2_INCOMPAT_DIRTY);
500 ret = bdrv_pwrite(bs->file, offsetof(QCowHeader, incompatible_features),
501 &val, sizeof(val));
502 if (ret < 0) {
503 return ret;
505 ret = bdrv_flush(bs->file->bs);
506 if (ret < 0) {
507 return ret;
510 /* Only treat image as dirty if the header was updated successfully */
511 s->incompatible_features |= QCOW2_INCOMPAT_DIRTY;
512 return 0;
516 * Clears the dirty bit and flushes before if necessary. Only call this
517 * function when there are no pending requests, it does not guard against
518 * concurrent requests dirtying the image.
520 static int qcow2_mark_clean(BlockDriverState *bs)
522 BDRVQcow2State *s = bs->opaque;
524 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
525 int ret;
527 s->incompatible_features &= ~QCOW2_INCOMPAT_DIRTY;
529 ret = qcow2_flush_caches(bs);
530 if (ret < 0) {
531 return ret;
534 return qcow2_update_header(bs);
536 return 0;
540 * Marks the image as corrupt.
542 int qcow2_mark_corrupt(BlockDriverState *bs)
544 BDRVQcow2State *s = bs->opaque;
546 s->incompatible_features |= QCOW2_INCOMPAT_CORRUPT;
547 return qcow2_update_header(bs);
551 * Marks the image as consistent, i.e., unsets the corrupt bit, and flushes
552 * before if necessary.
554 int qcow2_mark_consistent(BlockDriverState *bs)
556 BDRVQcow2State *s = bs->opaque;
558 if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
559 int ret = qcow2_flush_caches(bs);
560 if (ret < 0) {
561 return ret;
564 s->incompatible_features &= ~QCOW2_INCOMPAT_CORRUPT;
565 return qcow2_update_header(bs);
567 return 0;
570 static int coroutine_fn qcow2_co_check_locked(BlockDriverState *bs,
571 BdrvCheckResult *result,
572 BdrvCheckMode fix)
574 int ret = qcow2_check_refcounts(bs, result, fix);
575 if (ret < 0) {
576 return ret;
579 if (fix && result->check_errors == 0 && result->corruptions == 0) {
580 ret = qcow2_mark_clean(bs);
581 if (ret < 0) {
582 return ret;
584 return qcow2_mark_consistent(bs);
586 return ret;
589 static int coroutine_fn qcow2_co_check(BlockDriverState *bs,
590 BdrvCheckResult *result,
591 BdrvCheckMode fix)
593 BDRVQcow2State *s = bs->opaque;
594 int ret;
596 qemu_co_mutex_lock(&s->lock);
597 ret = qcow2_co_check_locked(bs, result, fix);
598 qemu_co_mutex_unlock(&s->lock);
599 return ret;
602 int qcow2_validate_table(BlockDriverState *bs, uint64_t offset,
603 uint64_t entries, size_t entry_len,
604 int64_t max_size_bytes, const char *table_name,
605 Error **errp)
607 BDRVQcow2State *s = bs->opaque;
609 if (entries > max_size_bytes / entry_len) {
610 error_setg(errp, "%s too large", table_name);
611 return -EFBIG;
614 /* Use signed INT64_MAX as the maximum even for uint64_t header fields,
615 * because values will be passed to qemu functions taking int64_t. */
616 if ((INT64_MAX - entries * entry_len < offset) ||
617 (offset_into_cluster(s, offset) != 0)) {
618 error_setg(errp, "%s offset invalid", table_name);
619 return -EINVAL;
622 return 0;
625 static const char *const mutable_opts[] = {
626 QCOW2_OPT_LAZY_REFCOUNTS,
627 QCOW2_OPT_DISCARD_REQUEST,
628 QCOW2_OPT_DISCARD_SNAPSHOT,
629 QCOW2_OPT_DISCARD_OTHER,
630 QCOW2_OPT_OVERLAP,
631 QCOW2_OPT_OVERLAP_TEMPLATE,
632 QCOW2_OPT_OVERLAP_MAIN_HEADER,
633 QCOW2_OPT_OVERLAP_ACTIVE_L1,
634 QCOW2_OPT_OVERLAP_ACTIVE_L2,
635 QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
636 QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
637 QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
638 QCOW2_OPT_OVERLAP_INACTIVE_L1,
639 QCOW2_OPT_OVERLAP_INACTIVE_L2,
640 QCOW2_OPT_OVERLAP_BITMAP_DIRECTORY,
641 QCOW2_OPT_CACHE_SIZE,
642 QCOW2_OPT_L2_CACHE_SIZE,
643 QCOW2_OPT_L2_CACHE_ENTRY_SIZE,
644 QCOW2_OPT_REFCOUNT_CACHE_SIZE,
645 QCOW2_OPT_CACHE_CLEAN_INTERVAL,
646 NULL
649 static QemuOptsList qcow2_runtime_opts = {
650 .name = "qcow2",
651 .head = QTAILQ_HEAD_INITIALIZER(qcow2_runtime_opts.head),
652 .desc = {
654 .name = QCOW2_OPT_LAZY_REFCOUNTS,
655 .type = QEMU_OPT_BOOL,
656 .help = "Postpone refcount updates",
659 .name = QCOW2_OPT_DISCARD_REQUEST,
660 .type = QEMU_OPT_BOOL,
661 .help = "Pass guest discard requests to the layer below",
664 .name = QCOW2_OPT_DISCARD_SNAPSHOT,
665 .type = QEMU_OPT_BOOL,
666 .help = "Generate discard requests when snapshot related space "
667 "is freed",
670 .name = QCOW2_OPT_DISCARD_OTHER,
671 .type = QEMU_OPT_BOOL,
672 .help = "Generate discard requests when other clusters are freed",
675 .name = QCOW2_OPT_OVERLAP,
676 .type = QEMU_OPT_STRING,
677 .help = "Selects which overlap checks to perform from a range of "
678 "templates (none, constant, cached, all)",
681 .name = QCOW2_OPT_OVERLAP_TEMPLATE,
682 .type = QEMU_OPT_STRING,
683 .help = "Selects which overlap checks to perform from a range of "
684 "templates (none, constant, cached, all)",
687 .name = QCOW2_OPT_OVERLAP_MAIN_HEADER,
688 .type = QEMU_OPT_BOOL,
689 .help = "Check for unintended writes into the main qcow2 header",
692 .name = QCOW2_OPT_OVERLAP_ACTIVE_L1,
693 .type = QEMU_OPT_BOOL,
694 .help = "Check for unintended writes into the active L1 table",
697 .name = QCOW2_OPT_OVERLAP_ACTIVE_L2,
698 .type = QEMU_OPT_BOOL,
699 .help = "Check for unintended writes into an active L2 table",
702 .name = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
703 .type = QEMU_OPT_BOOL,
704 .help = "Check for unintended writes into the refcount table",
707 .name = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
708 .type = QEMU_OPT_BOOL,
709 .help = "Check for unintended writes into a refcount block",
712 .name = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
713 .type = QEMU_OPT_BOOL,
714 .help = "Check for unintended writes into the snapshot table",
717 .name = QCOW2_OPT_OVERLAP_INACTIVE_L1,
718 .type = QEMU_OPT_BOOL,
719 .help = "Check for unintended writes into an inactive L1 table",
722 .name = QCOW2_OPT_OVERLAP_INACTIVE_L2,
723 .type = QEMU_OPT_BOOL,
724 .help = "Check for unintended writes into an inactive L2 table",
727 .name = QCOW2_OPT_OVERLAP_BITMAP_DIRECTORY,
728 .type = QEMU_OPT_BOOL,
729 .help = "Check for unintended writes into the bitmap directory",
732 .name = QCOW2_OPT_CACHE_SIZE,
733 .type = QEMU_OPT_SIZE,
734 .help = "Maximum combined metadata (L2 tables and refcount blocks) "
735 "cache size",
738 .name = QCOW2_OPT_L2_CACHE_SIZE,
739 .type = QEMU_OPT_SIZE,
740 .help = "Maximum L2 table cache size",
743 .name = QCOW2_OPT_L2_CACHE_ENTRY_SIZE,
744 .type = QEMU_OPT_SIZE,
745 .help = "Size of each entry in the L2 cache",
748 .name = QCOW2_OPT_REFCOUNT_CACHE_SIZE,
749 .type = QEMU_OPT_SIZE,
750 .help = "Maximum refcount block cache size",
753 .name = QCOW2_OPT_CACHE_CLEAN_INTERVAL,
754 .type = QEMU_OPT_NUMBER,
755 .help = "Clean unused cache entries after this time (in seconds)",
757 BLOCK_CRYPTO_OPT_DEF_KEY_SECRET("encrypt.",
758 "ID of secret providing qcow2 AES key or LUKS passphrase"),
759 { /* end of list */ }
763 static const char *overlap_bool_option_names[QCOW2_OL_MAX_BITNR] = {
764 [QCOW2_OL_MAIN_HEADER_BITNR] = QCOW2_OPT_OVERLAP_MAIN_HEADER,
765 [QCOW2_OL_ACTIVE_L1_BITNR] = QCOW2_OPT_OVERLAP_ACTIVE_L1,
766 [QCOW2_OL_ACTIVE_L2_BITNR] = QCOW2_OPT_OVERLAP_ACTIVE_L2,
767 [QCOW2_OL_REFCOUNT_TABLE_BITNR] = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
768 [QCOW2_OL_REFCOUNT_BLOCK_BITNR] = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
769 [QCOW2_OL_SNAPSHOT_TABLE_BITNR] = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
770 [QCOW2_OL_INACTIVE_L1_BITNR] = QCOW2_OPT_OVERLAP_INACTIVE_L1,
771 [QCOW2_OL_INACTIVE_L2_BITNR] = QCOW2_OPT_OVERLAP_INACTIVE_L2,
772 [QCOW2_OL_BITMAP_DIRECTORY_BITNR] = QCOW2_OPT_OVERLAP_BITMAP_DIRECTORY,
775 static void cache_clean_timer_cb(void *opaque)
777 BlockDriverState *bs = opaque;
778 BDRVQcow2State *s = bs->opaque;
779 qcow2_cache_clean_unused(s->l2_table_cache);
780 qcow2_cache_clean_unused(s->refcount_block_cache);
781 timer_mod(s->cache_clean_timer, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) +
782 (int64_t) s->cache_clean_interval * 1000);
785 static void cache_clean_timer_init(BlockDriverState *bs, AioContext *context)
787 BDRVQcow2State *s = bs->opaque;
788 if (s->cache_clean_interval > 0) {
789 s->cache_clean_timer = aio_timer_new(context, QEMU_CLOCK_VIRTUAL,
790 SCALE_MS, cache_clean_timer_cb,
791 bs);
792 timer_mod(s->cache_clean_timer, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) +
793 (int64_t) s->cache_clean_interval * 1000);
797 static void cache_clean_timer_del(BlockDriverState *bs)
799 BDRVQcow2State *s = bs->opaque;
800 if (s->cache_clean_timer) {
801 timer_del(s->cache_clean_timer);
802 timer_free(s->cache_clean_timer);
803 s->cache_clean_timer = NULL;
807 static void qcow2_detach_aio_context(BlockDriverState *bs)
809 cache_clean_timer_del(bs);
812 static void qcow2_attach_aio_context(BlockDriverState *bs,
813 AioContext *new_context)
815 cache_clean_timer_init(bs, new_context);
818 static void read_cache_sizes(BlockDriverState *bs, QemuOpts *opts,
819 uint64_t *l2_cache_size,
820 uint64_t *l2_cache_entry_size,
821 uint64_t *refcount_cache_size, Error **errp)
823 BDRVQcow2State *s = bs->opaque;
824 uint64_t combined_cache_size, l2_cache_max_setting;
825 bool l2_cache_size_set, refcount_cache_size_set, combined_cache_size_set;
826 bool l2_cache_entry_size_set;
827 int min_refcount_cache = MIN_REFCOUNT_CACHE_SIZE * s->cluster_size;
828 uint64_t virtual_disk_size = bs->total_sectors * BDRV_SECTOR_SIZE;
829 uint64_t max_l2_cache = virtual_disk_size / (s->cluster_size / 8);
831 combined_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_CACHE_SIZE);
832 l2_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_L2_CACHE_SIZE);
833 refcount_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
834 l2_cache_entry_size_set = qemu_opt_get(opts, QCOW2_OPT_L2_CACHE_ENTRY_SIZE);
836 combined_cache_size = qemu_opt_get_size(opts, QCOW2_OPT_CACHE_SIZE, 0);
837 l2_cache_max_setting = qemu_opt_get_size(opts, QCOW2_OPT_L2_CACHE_SIZE,
838 DEFAULT_L2_CACHE_MAX_SIZE);
839 *refcount_cache_size = qemu_opt_get_size(opts,
840 QCOW2_OPT_REFCOUNT_CACHE_SIZE, 0);
842 *l2_cache_entry_size = qemu_opt_get_size(
843 opts, QCOW2_OPT_L2_CACHE_ENTRY_SIZE, s->cluster_size);
845 *l2_cache_size = MIN(max_l2_cache, l2_cache_max_setting);
847 if (combined_cache_size_set) {
848 if (l2_cache_size_set && refcount_cache_size_set) {
849 error_setg(errp, QCOW2_OPT_CACHE_SIZE ", " QCOW2_OPT_L2_CACHE_SIZE
850 " and " QCOW2_OPT_REFCOUNT_CACHE_SIZE " may not be set "
851 "at the same time");
852 return;
853 } else if (l2_cache_size_set &&
854 (l2_cache_max_setting > combined_cache_size)) {
855 error_setg(errp, QCOW2_OPT_L2_CACHE_SIZE " may not exceed "
856 QCOW2_OPT_CACHE_SIZE);
857 return;
858 } else if (*refcount_cache_size > combined_cache_size) {
859 error_setg(errp, QCOW2_OPT_REFCOUNT_CACHE_SIZE " may not exceed "
860 QCOW2_OPT_CACHE_SIZE);
861 return;
864 if (l2_cache_size_set) {
865 *refcount_cache_size = combined_cache_size - *l2_cache_size;
866 } else if (refcount_cache_size_set) {
867 *l2_cache_size = combined_cache_size - *refcount_cache_size;
868 } else {
869 /* Assign as much memory as possible to the L2 cache, and
870 * use the remainder for the refcount cache */
871 if (combined_cache_size >= max_l2_cache + min_refcount_cache) {
872 *l2_cache_size = max_l2_cache;
873 *refcount_cache_size = combined_cache_size - *l2_cache_size;
874 } else {
875 *refcount_cache_size =
876 MIN(combined_cache_size, min_refcount_cache);
877 *l2_cache_size = combined_cache_size - *refcount_cache_size;
883 * If the L2 cache is not enough to cover the whole disk then
884 * default to 4KB entries. Smaller entries reduce the cost of
885 * loads and evictions and increase I/O performance.
887 if (*l2_cache_size < max_l2_cache && !l2_cache_entry_size_set) {
888 *l2_cache_entry_size = MIN(s->cluster_size, 4096);
891 /* l2_cache_size and refcount_cache_size are ensured to have at least
892 * their minimum values in qcow2_update_options_prepare() */
894 if (*l2_cache_entry_size < (1 << MIN_CLUSTER_BITS) ||
895 *l2_cache_entry_size > s->cluster_size ||
896 !is_power_of_2(*l2_cache_entry_size)) {
897 error_setg(errp, "L2 cache entry size must be a power of two "
898 "between %d and the cluster size (%d)",
899 1 << MIN_CLUSTER_BITS, s->cluster_size);
900 return;
904 typedef struct Qcow2ReopenState {
905 Qcow2Cache *l2_table_cache;
906 Qcow2Cache *refcount_block_cache;
907 int l2_slice_size; /* Number of entries in a slice of the L2 table */
908 bool use_lazy_refcounts;
909 int overlap_check;
910 bool discard_passthrough[QCOW2_DISCARD_MAX];
911 uint64_t cache_clean_interval;
912 QCryptoBlockOpenOptions *crypto_opts; /* Disk encryption runtime options */
913 } Qcow2ReopenState;
915 static int qcow2_update_options_prepare(BlockDriverState *bs,
916 Qcow2ReopenState *r,
917 QDict *options, int flags,
918 Error **errp)
920 BDRVQcow2State *s = bs->opaque;
921 QemuOpts *opts = NULL;
922 const char *opt_overlap_check, *opt_overlap_check_template;
923 int overlap_check_template = 0;
924 uint64_t l2_cache_size, l2_cache_entry_size, refcount_cache_size;
925 int i;
926 const char *encryptfmt;
927 QDict *encryptopts = NULL;
928 Error *local_err = NULL;
929 int ret;
931 qdict_extract_subqdict(options, &encryptopts, "encrypt.");
932 encryptfmt = qdict_get_try_str(encryptopts, "format");
934 opts = qemu_opts_create(&qcow2_runtime_opts, NULL, 0, &error_abort);
935 qemu_opts_absorb_qdict(opts, options, &local_err);
936 if (local_err) {
937 error_propagate(errp, local_err);
938 ret = -EINVAL;
939 goto fail;
942 /* get L2 table/refcount block cache size from command line options */
943 read_cache_sizes(bs, opts, &l2_cache_size, &l2_cache_entry_size,
944 &refcount_cache_size, &local_err);
945 if (local_err) {
946 error_propagate(errp, local_err);
947 ret = -EINVAL;
948 goto fail;
951 l2_cache_size /= l2_cache_entry_size;
952 if (l2_cache_size < MIN_L2_CACHE_SIZE) {
953 l2_cache_size = MIN_L2_CACHE_SIZE;
955 if (l2_cache_size > INT_MAX) {
956 error_setg(errp, "L2 cache size too big");
957 ret = -EINVAL;
958 goto fail;
961 refcount_cache_size /= s->cluster_size;
962 if (refcount_cache_size < MIN_REFCOUNT_CACHE_SIZE) {
963 refcount_cache_size = MIN_REFCOUNT_CACHE_SIZE;
965 if (refcount_cache_size > INT_MAX) {
966 error_setg(errp, "Refcount cache size too big");
967 ret = -EINVAL;
968 goto fail;
971 /* alloc new L2 table/refcount block cache, flush old one */
972 if (s->l2_table_cache) {
973 ret = qcow2_cache_flush(bs, s->l2_table_cache);
974 if (ret) {
975 error_setg_errno(errp, -ret, "Failed to flush the L2 table cache");
976 goto fail;
980 if (s->refcount_block_cache) {
981 ret = qcow2_cache_flush(bs, s->refcount_block_cache);
982 if (ret) {
983 error_setg_errno(errp, -ret,
984 "Failed to flush the refcount block cache");
985 goto fail;
989 r->l2_slice_size = l2_cache_entry_size / sizeof(uint64_t);
990 r->l2_table_cache = qcow2_cache_create(bs, l2_cache_size,
991 l2_cache_entry_size);
992 r->refcount_block_cache = qcow2_cache_create(bs, refcount_cache_size,
993 s->cluster_size);
994 if (r->l2_table_cache == NULL || r->refcount_block_cache == NULL) {
995 error_setg(errp, "Could not allocate metadata caches");
996 ret = -ENOMEM;
997 goto fail;
1000 /* New interval for cache cleanup timer */
1001 r->cache_clean_interval =
1002 qemu_opt_get_number(opts, QCOW2_OPT_CACHE_CLEAN_INTERVAL,
1003 DEFAULT_CACHE_CLEAN_INTERVAL);
1004 #ifndef CONFIG_LINUX
1005 if (r->cache_clean_interval != 0) {
1006 error_setg(errp, QCOW2_OPT_CACHE_CLEAN_INTERVAL
1007 " not supported on this host");
1008 ret = -EINVAL;
1009 goto fail;
1011 #endif
1012 if (r->cache_clean_interval > UINT_MAX) {
1013 error_setg(errp, "Cache clean interval too big");
1014 ret = -EINVAL;
1015 goto fail;
1018 /* lazy-refcounts; flush if going from enabled to disabled */
1019 r->use_lazy_refcounts = qemu_opt_get_bool(opts, QCOW2_OPT_LAZY_REFCOUNTS,
1020 (s->compatible_features & QCOW2_COMPAT_LAZY_REFCOUNTS));
1021 if (r->use_lazy_refcounts && s->qcow_version < 3) {
1022 error_setg(errp, "Lazy refcounts require a qcow2 image with at least "
1023 "qemu 1.1 compatibility level");
1024 ret = -EINVAL;
1025 goto fail;
1028 if (s->use_lazy_refcounts && !r->use_lazy_refcounts) {
1029 ret = qcow2_mark_clean(bs);
1030 if (ret < 0) {
1031 error_setg_errno(errp, -ret, "Failed to disable lazy refcounts");
1032 goto fail;
1036 /* Overlap check options */
1037 opt_overlap_check = qemu_opt_get(opts, QCOW2_OPT_OVERLAP);
1038 opt_overlap_check_template = qemu_opt_get(opts, QCOW2_OPT_OVERLAP_TEMPLATE);
1039 if (opt_overlap_check_template && opt_overlap_check &&
1040 strcmp(opt_overlap_check_template, opt_overlap_check))
1042 error_setg(errp, "Conflicting values for qcow2 options '"
1043 QCOW2_OPT_OVERLAP "' ('%s') and '" QCOW2_OPT_OVERLAP_TEMPLATE
1044 "' ('%s')", opt_overlap_check, opt_overlap_check_template);
1045 ret = -EINVAL;
1046 goto fail;
1048 if (!opt_overlap_check) {
1049 opt_overlap_check = opt_overlap_check_template ?: "cached";
1052 if (!strcmp(opt_overlap_check, "none")) {
1053 overlap_check_template = 0;
1054 } else if (!strcmp(opt_overlap_check, "constant")) {
1055 overlap_check_template = QCOW2_OL_CONSTANT;
1056 } else if (!strcmp(opt_overlap_check, "cached")) {
1057 overlap_check_template = QCOW2_OL_CACHED;
1058 } else if (!strcmp(opt_overlap_check, "all")) {
1059 overlap_check_template = QCOW2_OL_ALL;
1060 } else {
1061 error_setg(errp, "Unsupported value '%s' for qcow2 option "
1062 "'overlap-check'. Allowed are any of the following: "
1063 "none, constant, cached, all", opt_overlap_check);
1064 ret = -EINVAL;
1065 goto fail;
1068 r->overlap_check = 0;
1069 for (i = 0; i < QCOW2_OL_MAX_BITNR; i++) {
1070 /* overlap-check defines a template bitmask, but every flag may be
1071 * overwritten through the associated boolean option */
1072 r->overlap_check |=
1073 qemu_opt_get_bool(opts, overlap_bool_option_names[i],
1074 overlap_check_template & (1 << i)) << i;
1077 r->discard_passthrough[QCOW2_DISCARD_NEVER] = false;
1078 r->discard_passthrough[QCOW2_DISCARD_ALWAYS] = true;
1079 r->discard_passthrough[QCOW2_DISCARD_REQUEST] =
1080 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_REQUEST,
1081 flags & BDRV_O_UNMAP);
1082 r->discard_passthrough[QCOW2_DISCARD_SNAPSHOT] =
1083 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_SNAPSHOT, true);
1084 r->discard_passthrough[QCOW2_DISCARD_OTHER] =
1085 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_OTHER, false);
1087 switch (s->crypt_method_header) {
1088 case QCOW_CRYPT_NONE:
1089 if (encryptfmt) {
1090 error_setg(errp, "No encryption in image header, but options "
1091 "specified format '%s'", encryptfmt);
1092 ret = -EINVAL;
1093 goto fail;
1095 break;
1097 case QCOW_CRYPT_AES:
1098 if (encryptfmt && !g_str_equal(encryptfmt, "aes")) {
1099 error_setg(errp,
1100 "Header reported 'aes' encryption format but "
1101 "options specify '%s'", encryptfmt);
1102 ret = -EINVAL;
1103 goto fail;
1105 qdict_put_str(encryptopts, "format", "qcow");
1106 r->crypto_opts = block_crypto_open_opts_init(encryptopts, errp);
1107 break;
1109 case QCOW_CRYPT_LUKS:
1110 if (encryptfmt && !g_str_equal(encryptfmt, "luks")) {
1111 error_setg(errp,
1112 "Header reported 'luks' encryption format but "
1113 "options specify '%s'", encryptfmt);
1114 ret = -EINVAL;
1115 goto fail;
1117 qdict_put_str(encryptopts, "format", "luks");
1118 r->crypto_opts = block_crypto_open_opts_init(encryptopts, errp);
1119 break;
1121 default:
1122 error_setg(errp, "Unsupported encryption method %d",
1123 s->crypt_method_header);
1124 break;
1126 if (s->crypt_method_header != QCOW_CRYPT_NONE && !r->crypto_opts) {
1127 ret = -EINVAL;
1128 goto fail;
1131 ret = 0;
1132 fail:
1133 qobject_unref(encryptopts);
1134 qemu_opts_del(opts);
1135 opts = NULL;
1136 return ret;
1139 static void qcow2_update_options_commit(BlockDriverState *bs,
1140 Qcow2ReopenState *r)
1142 BDRVQcow2State *s = bs->opaque;
1143 int i;
1145 if (s->l2_table_cache) {
1146 qcow2_cache_destroy(s->l2_table_cache);
1148 if (s->refcount_block_cache) {
1149 qcow2_cache_destroy(s->refcount_block_cache);
1151 s->l2_table_cache = r->l2_table_cache;
1152 s->refcount_block_cache = r->refcount_block_cache;
1153 s->l2_slice_size = r->l2_slice_size;
1155 s->overlap_check = r->overlap_check;
1156 s->use_lazy_refcounts = r->use_lazy_refcounts;
1158 for (i = 0; i < QCOW2_DISCARD_MAX; i++) {
1159 s->discard_passthrough[i] = r->discard_passthrough[i];
1162 if (s->cache_clean_interval != r->cache_clean_interval) {
1163 cache_clean_timer_del(bs);
1164 s->cache_clean_interval = r->cache_clean_interval;
1165 cache_clean_timer_init(bs, bdrv_get_aio_context(bs));
1168 qapi_free_QCryptoBlockOpenOptions(s->crypto_opts);
1169 s->crypto_opts = r->crypto_opts;
1172 static void qcow2_update_options_abort(BlockDriverState *bs,
1173 Qcow2ReopenState *r)
1175 if (r->l2_table_cache) {
1176 qcow2_cache_destroy(r->l2_table_cache);
1178 if (r->refcount_block_cache) {
1179 qcow2_cache_destroy(r->refcount_block_cache);
1181 qapi_free_QCryptoBlockOpenOptions(r->crypto_opts);
1184 static int qcow2_update_options(BlockDriverState *bs, QDict *options,
1185 int flags, Error **errp)
1187 Qcow2ReopenState r = {};
1188 int ret;
1190 ret = qcow2_update_options_prepare(bs, &r, options, flags, errp);
1191 if (ret >= 0) {
1192 qcow2_update_options_commit(bs, &r);
1193 } else {
1194 qcow2_update_options_abort(bs, &r);
1197 return ret;
1200 /* Called with s->lock held. */
1201 static int coroutine_fn qcow2_do_open(BlockDriverState *bs, QDict *options,
1202 int flags, Error **errp)
1204 BDRVQcow2State *s = bs->opaque;
1205 unsigned int len, i;
1206 int ret = 0;
1207 QCowHeader header;
1208 Error *local_err = NULL;
1209 uint64_t ext_end;
1210 uint64_t l1_vm_state_index;
1211 bool update_header = false;
1213 ret = bdrv_pread(bs->file, 0, &header, sizeof(header));
1214 if (ret < 0) {
1215 error_setg_errno(errp, -ret, "Could not read qcow2 header");
1216 goto fail;
1218 header.magic = be32_to_cpu(header.magic);
1219 header.version = be32_to_cpu(header.version);
1220 header.backing_file_offset = be64_to_cpu(header.backing_file_offset);
1221 header.backing_file_size = be32_to_cpu(header.backing_file_size);
1222 header.size = be64_to_cpu(header.size);
1223 header.cluster_bits = be32_to_cpu(header.cluster_bits);
1224 header.crypt_method = be32_to_cpu(header.crypt_method);
1225 header.l1_table_offset = be64_to_cpu(header.l1_table_offset);
1226 header.l1_size = be32_to_cpu(header.l1_size);
1227 header.refcount_table_offset = be64_to_cpu(header.refcount_table_offset);
1228 header.refcount_table_clusters =
1229 be32_to_cpu(header.refcount_table_clusters);
1230 header.snapshots_offset = be64_to_cpu(header.snapshots_offset);
1231 header.nb_snapshots = be32_to_cpu(header.nb_snapshots);
1233 if (header.magic != QCOW_MAGIC) {
1234 error_setg(errp, "Image is not in qcow2 format");
1235 ret = -EINVAL;
1236 goto fail;
1238 if (header.version < 2 || header.version > 3) {
1239 error_setg(errp, "Unsupported qcow2 version %" PRIu32, header.version);
1240 ret = -ENOTSUP;
1241 goto fail;
1244 s->qcow_version = header.version;
1246 /* Initialise cluster size */
1247 if (header.cluster_bits < MIN_CLUSTER_BITS ||
1248 header.cluster_bits > MAX_CLUSTER_BITS) {
1249 error_setg(errp, "Unsupported cluster size: 2^%" PRIu32,
1250 header.cluster_bits);
1251 ret = -EINVAL;
1252 goto fail;
1255 s->cluster_bits = header.cluster_bits;
1256 s->cluster_size = 1 << s->cluster_bits;
1258 /* Initialise version 3 header fields */
1259 if (header.version == 2) {
1260 header.incompatible_features = 0;
1261 header.compatible_features = 0;
1262 header.autoclear_features = 0;
1263 header.refcount_order = 4;
1264 header.header_length = 72;
1265 } else {
1266 header.incompatible_features =
1267 be64_to_cpu(header.incompatible_features);
1268 header.compatible_features = be64_to_cpu(header.compatible_features);
1269 header.autoclear_features = be64_to_cpu(header.autoclear_features);
1270 header.refcount_order = be32_to_cpu(header.refcount_order);
1271 header.header_length = be32_to_cpu(header.header_length);
1273 if (header.header_length < 104) {
1274 error_setg(errp, "qcow2 header too short");
1275 ret = -EINVAL;
1276 goto fail;
1280 if (header.header_length > s->cluster_size) {
1281 error_setg(errp, "qcow2 header exceeds cluster size");
1282 ret = -EINVAL;
1283 goto fail;
1286 if (header.header_length > sizeof(header)) {
1287 s->unknown_header_fields_size = header.header_length - sizeof(header);
1288 s->unknown_header_fields = g_malloc(s->unknown_header_fields_size);
1289 ret = bdrv_pread(bs->file, sizeof(header), s->unknown_header_fields,
1290 s->unknown_header_fields_size);
1291 if (ret < 0) {
1292 error_setg_errno(errp, -ret, "Could not read unknown qcow2 header "
1293 "fields");
1294 goto fail;
1298 if (header.backing_file_offset > s->cluster_size) {
1299 error_setg(errp, "Invalid backing file offset");
1300 ret = -EINVAL;
1301 goto fail;
1304 if (header.backing_file_offset) {
1305 ext_end = header.backing_file_offset;
1306 } else {
1307 ext_end = 1 << header.cluster_bits;
1310 /* Handle feature bits */
1311 s->incompatible_features = header.incompatible_features;
1312 s->compatible_features = header.compatible_features;
1313 s->autoclear_features = header.autoclear_features;
1315 if (s->incompatible_features & ~QCOW2_INCOMPAT_MASK) {
1316 void *feature_table = NULL;
1317 qcow2_read_extensions(bs, header.header_length, ext_end,
1318 &feature_table, flags, NULL, NULL);
1319 report_unsupported_feature(errp, feature_table,
1320 s->incompatible_features &
1321 ~QCOW2_INCOMPAT_MASK);
1322 ret = -ENOTSUP;
1323 g_free(feature_table);
1324 goto fail;
1327 if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
1328 /* Corrupt images may not be written to unless they are being repaired
1330 if ((flags & BDRV_O_RDWR) && !(flags & BDRV_O_CHECK)) {
1331 error_setg(errp, "qcow2: Image is corrupt; cannot be opened "
1332 "read/write");
1333 ret = -EACCES;
1334 goto fail;
1338 /* Check support for various header values */
1339 if (header.refcount_order > 6) {
1340 error_setg(errp, "Reference count entry width too large; may not "
1341 "exceed 64 bits");
1342 ret = -EINVAL;
1343 goto fail;
1345 s->refcount_order = header.refcount_order;
1346 s->refcount_bits = 1 << s->refcount_order;
1347 s->refcount_max = UINT64_C(1) << (s->refcount_bits - 1);
1348 s->refcount_max += s->refcount_max - 1;
1350 s->crypt_method_header = header.crypt_method;
1351 if (s->crypt_method_header) {
1352 if (bdrv_uses_whitelist() &&
1353 s->crypt_method_header == QCOW_CRYPT_AES) {
1354 error_setg(errp,
1355 "Use of AES-CBC encrypted qcow2 images is no longer "
1356 "supported in system emulators");
1357 error_append_hint(errp,
1358 "You can use 'qemu-img convert' to convert your "
1359 "image to an alternative supported format, such "
1360 "as unencrypted qcow2, or raw with the LUKS "
1361 "format instead.\n");
1362 ret = -ENOSYS;
1363 goto fail;
1366 if (s->crypt_method_header == QCOW_CRYPT_AES) {
1367 s->crypt_physical_offset = false;
1368 } else {
1369 /* Assuming LUKS and any future crypt methods we
1370 * add will all use physical offsets, due to the
1371 * fact that the alternative is insecure... */
1372 s->crypt_physical_offset = true;
1375 bs->encrypted = true;
1378 s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */
1379 s->l2_size = 1 << s->l2_bits;
1380 /* 2^(s->refcount_order - 3) is the refcount width in bytes */
1381 s->refcount_block_bits = s->cluster_bits - (s->refcount_order - 3);
1382 s->refcount_block_size = 1 << s->refcount_block_bits;
1383 bs->total_sectors = header.size / BDRV_SECTOR_SIZE;
1384 s->csize_shift = (62 - (s->cluster_bits - 8));
1385 s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;
1386 s->cluster_offset_mask = (1LL << s->csize_shift) - 1;
1388 s->refcount_table_offset = header.refcount_table_offset;
1389 s->refcount_table_size =
1390 header.refcount_table_clusters << (s->cluster_bits - 3);
1392 if (header.refcount_table_clusters == 0 && !(flags & BDRV_O_CHECK)) {
1393 error_setg(errp, "Image does not contain a reference count table");
1394 ret = -EINVAL;
1395 goto fail;
1398 ret = qcow2_validate_table(bs, s->refcount_table_offset,
1399 header.refcount_table_clusters,
1400 s->cluster_size, QCOW_MAX_REFTABLE_SIZE,
1401 "Reference count table", errp);
1402 if (ret < 0) {
1403 goto fail;
1406 /* The total size in bytes of the snapshot table is checked in
1407 * qcow2_read_snapshots() because the size of each snapshot is
1408 * variable and we don't know it yet.
1409 * Here we only check the offset and number of snapshots. */
1410 ret = qcow2_validate_table(bs, header.snapshots_offset,
1411 header.nb_snapshots,
1412 sizeof(QCowSnapshotHeader),
1413 sizeof(QCowSnapshotHeader) * QCOW_MAX_SNAPSHOTS,
1414 "Snapshot table", errp);
1415 if (ret < 0) {
1416 goto fail;
1419 /* read the level 1 table */
1420 ret = qcow2_validate_table(bs, header.l1_table_offset,
1421 header.l1_size, sizeof(uint64_t),
1422 QCOW_MAX_L1_SIZE, "Active L1 table", errp);
1423 if (ret < 0) {
1424 goto fail;
1426 s->l1_size = header.l1_size;
1427 s->l1_table_offset = header.l1_table_offset;
1429 l1_vm_state_index = size_to_l1(s, header.size);
1430 if (l1_vm_state_index > INT_MAX) {
1431 error_setg(errp, "Image is too big");
1432 ret = -EFBIG;
1433 goto fail;
1435 s->l1_vm_state_index = l1_vm_state_index;
1437 /* the L1 table must contain at least enough entries to put
1438 header.size bytes */
1439 if (s->l1_size < s->l1_vm_state_index) {
1440 error_setg(errp, "L1 table is too small");
1441 ret = -EINVAL;
1442 goto fail;
1445 if (s->l1_size > 0) {
1446 s->l1_table = qemu_try_blockalign(bs->file->bs,
1447 ROUND_UP(s->l1_size * sizeof(uint64_t), 512));
1448 if (s->l1_table == NULL) {
1449 error_setg(errp, "Could not allocate L1 table");
1450 ret = -ENOMEM;
1451 goto fail;
1453 ret = bdrv_pread(bs->file, s->l1_table_offset, s->l1_table,
1454 s->l1_size * sizeof(uint64_t));
1455 if (ret < 0) {
1456 error_setg_errno(errp, -ret, "Could not read L1 table");
1457 goto fail;
1459 for(i = 0;i < s->l1_size; i++) {
1460 s->l1_table[i] = be64_to_cpu(s->l1_table[i]);
1464 /* Parse driver-specific options */
1465 ret = qcow2_update_options(bs, options, flags, errp);
1466 if (ret < 0) {
1467 goto fail;
1470 s->flags = flags;
1472 ret = qcow2_refcount_init(bs);
1473 if (ret != 0) {
1474 error_setg_errno(errp, -ret, "Could not initialize refcount handling");
1475 goto fail;
1478 QLIST_INIT(&s->cluster_allocs);
1479 QTAILQ_INIT(&s->discards);
1481 /* read qcow2 extensions */
1482 if (qcow2_read_extensions(bs, header.header_length, ext_end, NULL,
1483 flags, &update_header, &local_err)) {
1484 error_propagate(errp, local_err);
1485 ret = -EINVAL;
1486 goto fail;
1489 /* Open external data file */
1490 s->data_file = bdrv_open_child(NULL, options, "data-file", bs, &child_file,
1491 true, &local_err);
1492 if (local_err) {
1493 error_propagate(errp, local_err);
1494 ret = -EINVAL;
1495 goto fail;
1498 if (s->incompatible_features & QCOW2_INCOMPAT_DATA_FILE) {
1499 if (!s->data_file && s->image_data_file) {
1500 s->data_file = bdrv_open_child(s->image_data_file, options,
1501 "data-file", bs, &child_file,
1502 false, errp);
1503 if (!s->data_file) {
1504 ret = -EINVAL;
1505 goto fail;
1508 if (!s->data_file) {
1509 error_setg(errp, "'data-file' is required for this image");
1510 ret = -EINVAL;
1511 goto fail;
1513 } else {
1514 if (s->data_file) {
1515 error_setg(errp, "'data-file' can only be set for images with an "
1516 "external data file");
1517 ret = -EINVAL;
1518 goto fail;
1521 s->data_file = bs->file;
1523 if (data_file_is_raw(bs)) {
1524 error_setg(errp, "data-file-raw requires a data file");
1525 ret = -EINVAL;
1526 goto fail;
1530 /* qcow2_read_extension may have set up the crypto context
1531 * if the crypt method needs a header region, some methods
1532 * don't need header extensions, so must check here
1534 if (s->crypt_method_header && !s->crypto) {
1535 if (s->crypt_method_header == QCOW_CRYPT_AES) {
1536 unsigned int cflags = 0;
1537 if (flags & BDRV_O_NO_IO) {
1538 cflags |= QCRYPTO_BLOCK_OPEN_NO_IO;
1540 s->crypto = qcrypto_block_open(s->crypto_opts, "encrypt.",
1541 NULL, NULL, cflags,
1542 QCOW2_MAX_THREADS, errp);
1543 if (!s->crypto) {
1544 ret = -EINVAL;
1545 goto fail;
1547 } else if (!(flags & BDRV_O_NO_IO)) {
1548 error_setg(errp, "Missing CRYPTO header for crypt method %d",
1549 s->crypt_method_header);
1550 ret = -EINVAL;
1551 goto fail;
1555 /* read the backing file name */
1556 if (header.backing_file_offset != 0) {
1557 len = header.backing_file_size;
1558 if (len > MIN(1023, s->cluster_size - header.backing_file_offset) ||
1559 len >= sizeof(bs->backing_file)) {
1560 error_setg(errp, "Backing file name too long");
1561 ret = -EINVAL;
1562 goto fail;
1564 ret = bdrv_pread(bs->file, header.backing_file_offset,
1565 bs->auto_backing_file, len);
1566 if (ret < 0) {
1567 error_setg_errno(errp, -ret, "Could not read backing file name");
1568 goto fail;
1570 bs->auto_backing_file[len] = '\0';
1571 pstrcpy(bs->backing_file, sizeof(bs->backing_file),
1572 bs->auto_backing_file);
1573 s->image_backing_file = g_strdup(bs->auto_backing_file);
1576 /* Internal snapshots */
1577 s->snapshots_offset = header.snapshots_offset;
1578 s->nb_snapshots = header.nb_snapshots;
1580 ret = qcow2_read_snapshots(bs);
1581 if (ret < 0) {
1582 error_setg_errno(errp, -ret, "Could not read snapshots");
1583 goto fail;
1586 /* Clear unknown autoclear feature bits */
1587 update_header |= s->autoclear_features & ~QCOW2_AUTOCLEAR_MASK;
1588 update_header =
1589 update_header && !bs->read_only && !(flags & BDRV_O_INACTIVE);
1590 if (update_header) {
1591 s->autoclear_features &= QCOW2_AUTOCLEAR_MASK;
1594 /* == Handle persistent dirty bitmaps ==
1596 * We want load dirty bitmaps in three cases:
1598 * 1. Normal open of the disk in active mode, not related to invalidation
1599 * after migration.
1601 * 2. Invalidation of the target vm after pre-copy phase of migration, if
1602 * bitmaps are _not_ migrating through migration channel, i.e.
1603 * 'dirty-bitmaps' capability is disabled.
1605 * 3. Invalidation of source vm after failed or canceled migration.
1606 * This is a very interesting case. There are two possible types of
1607 * bitmaps:
1609 * A. Stored on inactivation and removed. They should be loaded from the
1610 * image.
1612 * B. Not stored: not-persistent bitmaps and bitmaps, migrated through
1613 * the migration channel (with dirty-bitmaps capability).
1615 * On the other hand, there are two possible sub-cases:
1617 * 3.1 disk was changed by somebody else while were inactive. In this
1618 * case all in-RAM dirty bitmaps (both persistent and not) are
1619 * definitely invalid. And we don't have any method to determine
1620 * this.
1622 * Simple and safe thing is to just drop all the bitmaps of type B on
1623 * inactivation. But in this case we lose bitmaps in valid 4.2 case.
1625 * On the other hand, resuming source vm, if disk was already changed
1626 * is a bad thing anyway: not only bitmaps, the whole vm state is
1627 * out of sync with disk.
1629 * This means, that user or management tool, who for some reason
1630 * decided to resume source vm, after disk was already changed by
1631 * target vm, should at least drop all dirty bitmaps by hand.
1633 * So, we can ignore this case for now, but TODO: "generation"
1634 * extension for qcow2, to determine, that image was changed after
1635 * last inactivation. And if it is changed, we will drop (or at least
1636 * mark as 'invalid' all the bitmaps of type B, both persistent
1637 * and not).
1639 * 3.2 disk was _not_ changed while were inactive. Bitmaps may be saved
1640 * to disk ('dirty-bitmaps' capability disabled), or not saved
1641 * ('dirty-bitmaps' capability enabled), but we don't need to care
1642 * of: let's load bitmaps as always: stored bitmaps will be loaded,
1643 * and not stored has flag IN_USE=1 in the image and will be skipped
1644 * on loading.
1646 * One remaining possible case when we don't want load bitmaps:
1648 * 4. Open disk in inactive mode in target vm (bitmaps are migrating or
1649 * will be loaded on invalidation, no needs try loading them before)
1652 if (!(bdrv_get_flags(bs) & BDRV_O_INACTIVE)) {
1653 /* It's case 1, 2 or 3.2. Or 3.1 which is BUG in management layer. */
1654 bool header_updated = qcow2_load_dirty_bitmaps(bs, &local_err);
1656 update_header = update_header && !header_updated;
1658 if (local_err != NULL) {
1659 error_propagate(errp, local_err);
1660 ret = -EINVAL;
1661 goto fail;
1664 if (update_header) {
1665 ret = qcow2_update_header(bs);
1666 if (ret < 0) {
1667 error_setg_errno(errp, -ret, "Could not update qcow2 header");
1668 goto fail;
1672 bs->supported_zero_flags = header.version >= 3 ? BDRV_REQ_MAY_UNMAP : 0;
1674 /* Repair image if dirty */
1675 if (!(flags & (BDRV_O_CHECK | BDRV_O_INACTIVE)) && !bs->read_only &&
1676 (s->incompatible_features & QCOW2_INCOMPAT_DIRTY)) {
1677 BdrvCheckResult result = {0};
1679 ret = qcow2_co_check_locked(bs, &result,
1680 BDRV_FIX_ERRORS | BDRV_FIX_LEAKS);
1681 if (ret < 0 || result.check_errors) {
1682 if (ret >= 0) {
1683 ret = -EIO;
1685 error_setg_errno(errp, -ret, "Could not repair dirty image");
1686 goto fail;
1690 #ifdef DEBUG_ALLOC
1692 BdrvCheckResult result = {0};
1693 qcow2_check_refcounts(bs, &result, 0);
1695 #endif
1697 qemu_co_queue_init(&s->thread_task_queue);
1699 return ret;
1701 fail:
1702 g_free(s->image_data_file);
1703 if (has_data_file(bs)) {
1704 bdrv_unref_child(bs, s->data_file);
1706 g_free(s->unknown_header_fields);
1707 cleanup_unknown_header_ext(bs);
1708 qcow2_free_snapshots(bs);
1709 qcow2_refcount_close(bs);
1710 qemu_vfree(s->l1_table);
1711 /* else pre-write overlap checks in cache_destroy may crash */
1712 s->l1_table = NULL;
1713 cache_clean_timer_del(bs);
1714 if (s->l2_table_cache) {
1715 qcow2_cache_destroy(s->l2_table_cache);
1717 if (s->refcount_block_cache) {
1718 qcow2_cache_destroy(s->refcount_block_cache);
1720 qcrypto_block_free(s->crypto);
1721 qapi_free_QCryptoBlockOpenOptions(s->crypto_opts);
1722 return ret;
1725 typedef struct QCow2OpenCo {
1726 BlockDriverState *bs;
1727 QDict *options;
1728 int flags;
1729 Error **errp;
1730 int ret;
1731 } QCow2OpenCo;
1733 static void coroutine_fn qcow2_open_entry(void *opaque)
1735 QCow2OpenCo *qoc = opaque;
1736 BDRVQcow2State *s = qoc->bs->opaque;
1738 qemu_co_mutex_lock(&s->lock);
1739 qoc->ret = qcow2_do_open(qoc->bs, qoc->options, qoc->flags, qoc->errp);
1740 qemu_co_mutex_unlock(&s->lock);
1743 static int qcow2_open(BlockDriverState *bs, QDict *options, int flags,
1744 Error **errp)
1746 BDRVQcow2State *s = bs->opaque;
1747 QCow2OpenCo qoc = {
1748 .bs = bs,
1749 .options = options,
1750 .flags = flags,
1751 .errp = errp,
1752 .ret = -EINPROGRESS
1755 bs->file = bdrv_open_child(NULL, options, "file", bs, &child_file,
1756 false, errp);
1757 if (!bs->file) {
1758 return -EINVAL;
1761 /* Initialise locks */
1762 qemu_co_mutex_init(&s->lock);
1764 if (qemu_in_coroutine()) {
1765 /* From bdrv_co_create. */
1766 qcow2_open_entry(&qoc);
1767 } else {
1768 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
1769 qemu_coroutine_enter(qemu_coroutine_create(qcow2_open_entry, &qoc));
1770 BDRV_POLL_WHILE(bs, qoc.ret == -EINPROGRESS);
1772 return qoc.ret;
1775 static void qcow2_refresh_limits(BlockDriverState *bs, Error **errp)
1777 BDRVQcow2State *s = bs->opaque;
1779 if (bs->encrypted) {
1780 /* Encryption works on a sector granularity */
1781 bs->bl.request_alignment = qcrypto_block_get_sector_size(s->crypto);
1783 bs->bl.pwrite_zeroes_alignment = s->cluster_size;
1784 bs->bl.pdiscard_alignment = s->cluster_size;
1787 static int qcow2_reopen_prepare(BDRVReopenState *state,
1788 BlockReopenQueue *queue, Error **errp)
1790 Qcow2ReopenState *r;
1791 int ret;
1793 r = g_new0(Qcow2ReopenState, 1);
1794 state->opaque = r;
1796 ret = qcow2_update_options_prepare(state->bs, r, state->options,
1797 state->flags, errp);
1798 if (ret < 0) {
1799 goto fail;
1802 /* We need to write out any unwritten data if we reopen read-only. */
1803 if ((state->flags & BDRV_O_RDWR) == 0) {
1804 ret = qcow2_reopen_bitmaps_ro(state->bs, errp);
1805 if (ret < 0) {
1806 goto fail;
1809 ret = bdrv_flush(state->bs);
1810 if (ret < 0) {
1811 goto fail;
1814 ret = qcow2_mark_clean(state->bs);
1815 if (ret < 0) {
1816 goto fail;
1820 return 0;
1822 fail:
1823 qcow2_update_options_abort(state->bs, r);
1824 g_free(r);
1825 return ret;
1828 static void qcow2_reopen_commit(BDRVReopenState *state)
1830 qcow2_update_options_commit(state->bs, state->opaque);
1831 g_free(state->opaque);
1834 static void qcow2_reopen_abort(BDRVReopenState *state)
1836 qcow2_update_options_abort(state->bs, state->opaque);
1837 g_free(state->opaque);
1840 static void qcow2_join_options(QDict *options, QDict *old_options)
1842 bool has_new_overlap_template =
1843 qdict_haskey(options, QCOW2_OPT_OVERLAP) ||
1844 qdict_haskey(options, QCOW2_OPT_OVERLAP_TEMPLATE);
1845 bool has_new_total_cache_size =
1846 qdict_haskey(options, QCOW2_OPT_CACHE_SIZE);
1847 bool has_all_cache_options;
1849 /* New overlap template overrides all old overlap options */
1850 if (has_new_overlap_template) {
1851 qdict_del(old_options, QCOW2_OPT_OVERLAP);
1852 qdict_del(old_options, QCOW2_OPT_OVERLAP_TEMPLATE);
1853 qdict_del(old_options, QCOW2_OPT_OVERLAP_MAIN_HEADER);
1854 qdict_del(old_options, QCOW2_OPT_OVERLAP_ACTIVE_L1);
1855 qdict_del(old_options, QCOW2_OPT_OVERLAP_ACTIVE_L2);
1856 qdict_del(old_options, QCOW2_OPT_OVERLAP_REFCOUNT_TABLE);
1857 qdict_del(old_options, QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK);
1858 qdict_del(old_options, QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE);
1859 qdict_del(old_options, QCOW2_OPT_OVERLAP_INACTIVE_L1);
1860 qdict_del(old_options, QCOW2_OPT_OVERLAP_INACTIVE_L2);
1863 /* New total cache size overrides all old options */
1864 if (qdict_haskey(options, QCOW2_OPT_CACHE_SIZE)) {
1865 qdict_del(old_options, QCOW2_OPT_L2_CACHE_SIZE);
1866 qdict_del(old_options, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
1869 qdict_join(options, old_options, false);
1872 * If after merging all cache size options are set, an old total size is
1873 * overwritten. Do keep all options, however, if all three are new. The
1874 * resulting error message is what we want to happen.
1876 has_all_cache_options =
1877 qdict_haskey(options, QCOW2_OPT_CACHE_SIZE) ||
1878 qdict_haskey(options, QCOW2_OPT_L2_CACHE_SIZE) ||
1879 qdict_haskey(options, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
1881 if (has_all_cache_options && !has_new_total_cache_size) {
1882 qdict_del(options, QCOW2_OPT_CACHE_SIZE);
1886 static int coroutine_fn qcow2_co_block_status(BlockDriverState *bs,
1887 bool want_zero,
1888 int64_t offset, int64_t count,
1889 int64_t *pnum, int64_t *map,
1890 BlockDriverState **file)
1892 BDRVQcow2State *s = bs->opaque;
1893 uint64_t cluster_offset;
1894 int index_in_cluster, ret;
1895 unsigned int bytes;
1896 int status = 0;
1898 bytes = MIN(INT_MAX, count);
1899 qemu_co_mutex_lock(&s->lock);
1900 ret = qcow2_get_cluster_offset(bs, offset, &bytes, &cluster_offset);
1901 qemu_co_mutex_unlock(&s->lock);
1902 if (ret < 0) {
1903 return ret;
1906 *pnum = bytes;
1908 if ((ret == QCOW2_CLUSTER_NORMAL || ret == QCOW2_CLUSTER_ZERO_ALLOC) &&
1909 !s->crypto) {
1910 index_in_cluster = offset & (s->cluster_size - 1);
1911 *map = cluster_offset | index_in_cluster;
1912 *file = s->data_file->bs;
1913 status |= BDRV_BLOCK_OFFSET_VALID;
1915 if (ret == QCOW2_CLUSTER_ZERO_PLAIN || ret == QCOW2_CLUSTER_ZERO_ALLOC) {
1916 status |= BDRV_BLOCK_ZERO;
1917 } else if (ret != QCOW2_CLUSTER_UNALLOCATED) {
1918 status |= BDRV_BLOCK_DATA;
1920 return status;
1923 static coroutine_fn int qcow2_handle_l2meta(BlockDriverState *bs,
1924 QCowL2Meta **pl2meta,
1925 bool link_l2)
1927 int ret = 0;
1928 QCowL2Meta *l2meta = *pl2meta;
1930 while (l2meta != NULL) {
1931 QCowL2Meta *next;
1933 if (link_l2) {
1934 ret = qcow2_alloc_cluster_link_l2(bs, l2meta);
1935 if (ret) {
1936 goto out;
1938 } else {
1939 qcow2_alloc_cluster_abort(bs, l2meta);
1942 /* Take the request off the list of running requests */
1943 if (l2meta->nb_clusters != 0) {
1944 QLIST_REMOVE(l2meta, next_in_flight);
1947 qemu_co_queue_restart_all(&l2meta->dependent_requests);
1949 next = l2meta->next;
1950 g_free(l2meta);
1951 l2meta = next;
1953 out:
1954 *pl2meta = l2meta;
1955 return ret;
1958 static coroutine_fn int qcow2_co_preadv(BlockDriverState *bs, uint64_t offset,
1959 uint64_t bytes, QEMUIOVector *qiov,
1960 int flags)
1962 BDRVQcow2State *s = bs->opaque;
1963 int offset_in_cluster;
1964 int ret;
1965 unsigned int cur_bytes; /* number of bytes in current iteration */
1966 uint64_t cluster_offset = 0;
1967 uint64_t bytes_done = 0;
1968 QEMUIOVector hd_qiov;
1969 uint8_t *cluster_data = NULL;
1971 qemu_iovec_init(&hd_qiov, qiov->niov);
1973 while (bytes != 0) {
1975 /* prepare next request */
1976 cur_bytes = MIN(bytes, INT_MAX);
1977 if (s->crypto) {
1978 cur_bytes = MIN(cur_bytes,
1979 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
1982 qemu_co_mutex_lock(&s->lock);
1983 ret = qcow2_get_cluster_offset(bs, offset, &cur_bytes, &cluster_offset);
1984 qemu_co_mutex_unlock(&s->lock);
1985 if (ret < 0) {
1986 goto fail;
1989 offset_in_cluster = offset_into_cluster(s, offset);
1991 qemu_iovec_reset(&hd_qiov);
1992 qemu_iovec_concat(&hd_qiov, qiov, bytes_done, cur_bytes);
1994 switch (ret) {
1995 case QCOW2_CLUSTER_UNALLOCATED:
1997 if (bs->backing) {
1998 BLKDBG_EVENT(bs->file, BLKDBG_READ_BACKING_AIO);
1999 ret = bdrv_co_preadv(bs->backing, offset, cur_bytes,
2000 &hd_qiov, 0);
2001 if (ret < 0) {
2002 goto fail;
2004 } else {
2005 /* Note: in this case, no need to wait */
2006 qemu_iovec_memset(&hd_qiov, 0, 0, cur_bytes);
2008 break;
2010 case QCOW2_CLUSTER_ZERO_PLAIN:
2011 case QCOW2_CLUSTER_ZERO_ALLOC:
2012 qemu_iovec_memset(&hd_qiov, 0, 0, cur_bytes);
2013 break;
2015 case QCOW2_CLUSTER_COMPRESSED:
2016 ret = qcow2_co_preadv_compressed(bs, cluster_offset,
2017 offset, cur_bytes,
2018 &hd_qiov);
2019 if (ret < 0) {
2020 goto fail;
2023 break;
2025 case QCOW2_CLUSTER_NORMAL:
2026 if ((cluster_offset & 511) != 0) {
2027 ret = -EIO;
2028 goto fail;
2031 if (bs->encrypted) {
2032 assert(s->crypto);
2035 * For encrypted images, read everything into a temporary
2036 * contiguous buffer on which the AES functions can work.
2038 if (!cluster_data) {
2039 cluster_data =
2040 qemu_try_blockalign(s->data_file->bs,
2041 QCOW_MAX_CRYPT_CLUSTERS
2042 * s->cluster_size);
2043 if (cluster_data == NULL) {
2044 ret = -ENOMEM;
2045 goto fail;
2049 assert(cur_bytes <= QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
2050 qemu_iovec_reset(&hd_qiov);
2051 qemu_iovec_add(&hd_qiov, cluster_data, cur_bytes);
2054 BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);
2055 ret = bdrv_co_preadv(s->data_file,
2056 cluster_offset + offset_in_cluster,
2057 cur_bytes, &hd_qiov, 0);
2058 if (ret < 0) {
2059 goto fail;
2061 if (bs->encrypted) {
2062 assert(s->crypto);
2063 assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);
2064 assert((cur_bytes & (BDRV_SECTOR_SIZE - 1)) == 0);
2065 if (qcow2_co_decrypt(bs, cluster_offset, offset,
2066 cluster_data, cur_bytes) < 0) {
2067 ret = -EIO;
2068 goto fail;
2070 qemu_iovec_from_buf(qiov, bytes_done, cluster_data, cur_bytes);
2072 break;
2074 default:
2075 g_assert_not_reached();
2076 ret = -EIO;
2077 goto fail;
2080 bytes -= cur_bytes;
2081 offset += cur_bytes;
2082 bytes_done += cur_bytes;
2084 ret = 0;
2086 fail:
2087 qemu_iovec_destroy(&hd_qiov);
2088 qemu_vfree(cluster_data);
2090 return ret;
2093 /* Check if it's possible to merge a write request with the writing of
2094 * the data from the COW regions */
2095 static bool merge_cow(uint64_t offset, unsigned bytes,
2096 QEMUIOVector *hd_qiov, QCowL2Meta *l2meta)
2098 QCowL2Meta *m;
2100 for (m = l2meta; m != NULL; m = m->next) {
2101 /* If both COW regions are empty then there's nothing to merge */
2102 if (m->cow_start.nb_bytes == 0 && m->cow_end.nb_bytes == 0) {
2103 continue;
2106 /* The data (middle) region must be immediately after the
2107 * start region */
2108 if (l2meta_cow_start(m) + m->cow_start.nb_bytes != offset) {
2109 continue;
2112 /* The end region must be immediately after the data (middle)
2113 * region */
2114 if (m->offset + m->cow_end.offset != offset + bytes) {
2115 continue;
2118 /* Make sure that adding both COW regions to the QEMUIOVector
2119 * does not exceed IOV_MAX */
2120 if (hd_qiov->niov > IOV_MAX - 2) {
2121 continue;
2124 m->data_qiov = hd_qiov;
2125 return true;
2128 return false;
2131 static coroutine_fn int qcow2_co_pwritev(BlockDriverState *bs, uint64_t offset,
2132 uint64_t bytes, QEMUIOVector *qiov,
2133 int flags)
2135 BDRVQcow2State *s = bs->opaque;
2136 int offset_in_cluster;
2137 int ret;
2138 unsigned int cur_bytes; /* number of sectors in current iteration */
2139 uint64_t cluster_offset;
2140 QEMUIOVector hd_qiov;
2141 uint64_t bytes_done = 0;
2142 uint8_t *cluster_data = NULL;
2143 QCowL2Meta *l2meta = NULL;
2145 trace_qcow2_writev_start_req(qemu_coroutine_self(), offset, bytes);
2147 qemu_iovec_init(&hd_qiov, qiov->niov);
2149 qemu_co_mutex_lock(&s->lock);
2151 while (bytes != 0) {
2153 l2meta = NULL;
2155 trace_qcow2_writev_start_part(qemu_coroutine_self());
2156 offset_in_cluster = offset_into_cluster(s, offset);
2157 cur_bytes = MIN(bytes, INT_MAX);
2158 if (bs->encrypted) {
2159 cur_bytes = MIN(cur_bytes,
2160 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size
2161 - offset_in_cluster);
2164 ret = qcow2_alloc_cluster_offset(bs, offset, &cur_bytes,
2165 &cluster_offset, &l2meta);
2166 if (ret < 0) {
2167 goto out_locked;
2170 assert((cluster_offset & 511) == 0);
2172 ret = qcow2_pre_write_overlap_check(bs, 0,
2173 cluster_offset + offset_in_cluster,
2174 cur_bytes, true);
2175 if (ret < 0) {
2176 goto out_locked;
2179 qemu_co_mutex_unlock(&s->lock);
2181 qemu_iovec_reset(&hd_qiov);
2182 qemu_iovec_concat(&hd_qiov, qiov, bytes_done, cur_bytes);
2184 if (bs->encrypted) {
2185 assert(s->crypto);
2186 if (!cluster_data) {
2187 cluster_data = qemu_try_blockalign(bs->file->bs,
2188 QCOW_MAX_CRYPT_CLUSTERS
2189 * s->cluster_size);
2190 if (cluster_data == NULL) {
2191 ret = -ENOMEM;
2192 goto out_unlocked;
2196 assert(hd_qiov.size <=
2197 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
2198 qemu_iovec_to_buf(&hd_qiov, 0, cluster_data, hd_qiov.size);
2200 if (qcow2_co_encrypt(bs, cluster_offset, offset,
2201 cluster_data, cur_bytes) < 0) {
2202 ret = -EIO;
2203 goto out_unlocked;
2206 qemu_iovec_reset(&hd_qiov);
2207 qemu_iovec_add(&hd_qiov, cluster_data, cur_bytes);
2210 /* If we need to do COW, check if it's possible to merge the
2211 * writing of the guest data together with that of the COW regions.
2212 * If it's not possible (or not necessary) then write the
2213 * guest data now. */
2214 if (!merge_cow(offset, cur_bytes, &hd_qiov, l2meta)) {
2215 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO);
2216 trace_qcow2_writev_data(qemu_coroutine_self(),
2217 cluster_offset + offset_in_cluster);
2218 ret = bdrv_co_pwritev(s->data_file,
2219 cluster_offset + offset_in_cluster,
2220 cur_bytes, &hd_qiov, 0);
2221 if (ret < 0) {
2222 goto out_unlocked;
2226 qemu_co_mutex_lock(&s->lock);
2228 ret = qcow2_handle_l2meta(bs, &l2meta, true);
2229 if (ret) {
2230 goto out_locked;
2233 bytes -= cur_bytes;
2234 offset += cur_bytes;
2235 bytes_done += cur_bytes;
2236 trace_qcow2_writev_done_part(qemu_coroutine_self(), cur_bytes);
2238 ret = 0;
2239 goto out_locked;
2241 out_unlocked:
2242 qemu_co_mutex_lock(&s->lock);
2244 out_locked:
2245 qcow2_handle_l2meta(bs, &l2meta, false);
2247 qemu_co_mutex_unlock(&s->lock);
2249 qemu_iovec_destroy(&hd_qiov);
2250 qemu_vfree(cluster_data);
2251 trace_qcow2_writev_done_req(qemu_coroutine_self(), ret);
2253 return ret;
2256 static int qcow2_inactivate(BlockDriverState *bs)
2258 BDRVQcow2State *s = bs->opaque;
2259 int ret, result = 0;
2260 Error *local_err = NULL;
2262 qcow2_store_persistent_dirty_bitmaps(bs, &local_err);
2263 if (local_err != NULL) {
2264 result = -EINVAL;
2265 error_reportf_err(local_err, "Lost persistent bitmaps during "
2266 "inactivation of node '%s': ",
2267 bdrv_get_device_or_node_name(bs));
2270 ret = qcow2_cache_flush(bs, s->l2_table_cache);
2271 if (ret) {
2272 result = ret;
2273 error_report("Failed to flush the L2 table cache: %s",
2274 strerror(-ret));
2277 ret = qcow2_cache_flush(bs, s->refcount_block_cache);
2278 if (ret) {
2279 result = ret;
2280 error_report("Failed to flush the refcount block cache: %s",
2281 strerror(-ret));
2284 if (result == 0) {
2285 qcow2_mark_clean(bs);
2288 return result;
2291 static void qcow2_close(BlockDriverState *bs)
2293 BDRVQcow2State *s = bs->opaque;
2294 qemu_vfree(s->l1_table);
2295 /* else pre-write overlap checks in cache_destroy may crash */
2296 s->l1_table = NULL;
2298 if (!(s->flags & BDRV_O_INACTIVE)) {
2299 qcow2_inactivate(bs);
2302 cache_clean_timer_del(bs);
2303 qcow2_cache_destroy(s->l2_table_cache);
2304 qcow2_cache_destroy(s->refcount_block_cache);
2306 qcrypto_block_free(s->crypto);
2307 s->crypto = NULL;
2309 g_free(s->unknown_header_fields);
2310 cleanup_unknown_header_ext(bs);
2312 g_free(s->image_data_file);
2313 g_free(s->image_backing_file);
2314 g_free(s->image_backing_format);
2316 if (has_data_file(bs)) {
2317 bdrv_unref_child(bs, s->data_file);
2320 qcow2_refcount_close(bs);
2321 qcow2_free_snapshots(bs);
2324 static void coroutine_fn qcow2_co_invalidate_cache(BlockDriverState *bs,
2325 Error **errp)
2327 BDRVQcow2State *s = bs->opaque;
2328 int flags = s->flags;
2329 QCryptoBlock *crypto = NULL;
2330 QDict *options;
2331 Error *local_err = NULL;
2332 int ret;
2335 * Backing files are read-only which makes all of their metadata immutable,
2336 * that means we don't have to worry about reopening them here.
2339 crypto = s->crypto;
2340 s->crypto = NULL;
2342 qcow2_close(bs);
2344 memset(s, 0, sizeof(BDRVQcow2State));
2345 options = qdict_clone_shallow(bs->options);
2347 flags &= ~BDRV_O_INACTIVE;
2348 qemu_co_mutex_lock(&s->lock);
2349 ret = qcow2_do_open(bs, options, flags, &local_err);
2350 qemu_co_mutex_unlock(&s->lock);
2351 qobject_unref(options);
2352 if (local_err) {
2353 error_propagate_prepend(errp, local_err,
2354 "Could not reopen qcow2 layer: ");
2355 bs->drv = NULL;
2356 return;
2357 } else if (ret < 0) {
2358 error_setg_errno(errp, -ret, "Could not reopen qcow2 layer");
2359 bs->drv = NULL;
2360 return;
2363 s->crypto = crypto;
2366 static size_t header_ext_add(char *buf, uint32_t magic, const void *s,
2367 size_t len, size_t buflen)
2369 QCowExtension *ext_backing_fmt = (QCowExtension*) buf;
2370 size_t ext_len = sizeof(QCowExtension) + ((len + 7) & ~7);
2372 if (buflen < ext_len) {
2373 return -ENOSPC;
2376 *ext_backing_fmt = (QCowExtension) {
2377 .magic = cpu_to_be32(magic),
2378 .len = cpu_to_be32(len),
2381 if (len) {
2382 memcpy(buf + sizeof(QCowExtension), s, len);
2385 return ext_len;
2389 * Updates the qcow2 header, including the variable length parts of it, i.e.
2390 * the backing file name and all extensions. qcow2 was not designed to allow
2391 * such changes, so if we run out of space (we can only use the first cluster)
2392 * this function may fail.
2394 * Returns 0 on success, -errno in error cases.
2396 int qcow2_update_header(BlockDriverState *bs)
2398 BDRVQcow2State *s = bs->opaque;
2399 QCowHeader *header;
2400 char *buf;
2401 size_t buflen = s->cluster_size;
2402 int ret;
2403 uint64_t total_size;
2404 uint32_t refcount_table_clusters;
2405 size_t header_length;
2406 Qcow2UnknownHeaderExtension *uext;
2408 buf = qemu_blockalign(bs, buflen);
2410 /* Header structure */
2411 header = (QCowHeader*) buf;
2413 if (buflen < sizeof(*header)) {
2414 ret = -ENOSPC;
2415 goto fail;
2418 header_length = sizeof(*header) + s->unknown_header_fields_size;
2419 total_size = bs->total_sectors * BDRV_SECTOR_SIZE;
2420 refcount_table_clusters = s->refcount_table_size >> (s->cluster_bits - 3);
2422 *header = (QCowHeader) {
2423 /* Version 2 fields */
2424 .magic = cpu_to_be32(QCOW_MAGIC),
2425 .version = cpu_to_be32(s->qcow_version),
2426 .backing_file_offset = 0,
2427 .backing_file_size = 0,
2428 .cluster_bits = cpu_to_be32(s->cluster_bits),
2429 .size = cpu_to_be64(total_size),
2430 .crypt_method = cpu_to_be32(s->crypt_method_header),
2431 .l1_size = cpu_to_be32(s->l1_size),
2432 .l1_table_offset = cpu_to_be64(s->l1_table_offset),
2433 .refcount_table_offset = cpu_to_be64(s->refcount_table_offset),
2434 .refcount_table_clusters = cpu_to_be32(refcount_table_clusters),
2435 .nb_snapshots = cpu_to_be32(s->nb_snapshots),
2436 .snapshots_offset = cpu_to_be64(s->snapshots_offset),
2438 /* Version 3 fields */
2439 .incompatible_features = cpu_to_be64(s->incompatible_features),
2440 .compatible_features = cpu_to_be64(s->compatible_features),
2441 .autoclear_features = cpu_to_be64(s->autoclear_features),
2442 .refcount_order = cpu_to_be32(s->refcount_order),
2443 .header_length = cpu_to_be32(header_length),
2446 /* For older versions, write a shorter header */
2447 switch (s->qcow_version) {
2448 case 2:
2449 ret = offsetof(QCowHeader, incompatible_features);
2450 break;
2451 case 3:
2452 ret = sizeof(*header);
2453 break;
2454 default:
2455 ret = -EINVAL;
2456 goto fail;
2459 buf += ret;
2460 buflen -= ret;
2461 memset(buf, 0, buflen);
2463 /* Preserve any unknown field in the header */
2464 if (s->unknown_header_fields_size) {
2465 if (buflen < s->unknown_header_fields_size) {
2466 ret = -ENOSPC;
2467 goto fail;
2470 memcpy(buf, s->unknown_header_fields, s->unknown_header_fields_size);
2471 buf += s->unknown_header_fields_size;
2472 buflen -= s->unknown_header_fields_size;
2475 /* Backing file format header extension */
2476 if (s->image_backing_format) {
2477 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BACKING_FORMAT,
2478 s->image_backing_format,
2479 strlen(s->image_backing_format),
2480 buflen);
2481 if (ret < 0) {
2482 goto fail;
2485 buf += ret;
2486 buflen -= ret;
2489 /* External data file header extension */
2490 if (has_data_file(bs) && s->image_data_file) {
2491 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_DATA_FILE,
2492 s->image_data_file, strlen(s->image_data_file),
2493 buflen);
2494 if (ret < 0) {
2495 goto fail;
2498 buf += ret;
2499 buflen -= ret;
2502 /* Full disk encryption header pointer extension */
2503 if (s->crypto_header.offset != 0) {
2504 s->crypto_header.offset = cpu_to_be64(s->crypto_header.offset);
2505 s->crypto_header.length = cpu_to_be64(s->crypto_header.length);
2506 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_CRYPTO_HEADER,
2507 &s->crypto_header, sizeof(s->crypto_header),
2508 buflen);
2509 s->crypto_header.offset = be64_to_cpu(s->crypto_header.offset);
2510 s->crypto_header.length = be64_to_cpu(s->crypto_header.length);
2511 if (ret < 0) {
2512 goto fail;
2514 buf += ret;
2515 buflen -= ret;
2518 /* Feature table */
2519 if (s->qcow_version >= 3) {
2520 Qcow2Feature features[] = {
2522 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
2523 .bit = QCOW2_INCOMPAT_DIRTY_BITNR,
2524 .name = "dirty bit",
2527 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
2528 .bit = QCOW2_INCOMPAT_CORRUPT_BITNR,
2529 .name = "corrupt bit",
2532 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
2533 .bit = QCOW2_INCOMPAT_DATA_FILE_BITNR,
2534 .name = "external data file",
2537 .type = QCOW2_FEAT_TYPE_COMPATIBLE,
2538 .bit = QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR,
2539 .name = "lazy refcounts",
2543 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_FEATURE_TABLE,
2544 features, sizeof(features), buflen);
2545 if (ret < 0) {
2546 goto fail;
2548 buf += ret;
2549 buflen -= ret;
2552 /* Bitmap extension */
2553 if (s->nb_bitmaps > 0) {
2554 Qcow2BitmapHeaderExt bitmaps_header = {
2555 .nb_bitmaps = cpu_to_be32(s->nb_bitmaps),
2556 .bitmap_directory_size =
2557 cpu_to_be64(s->bitmap_directory_size),
2558 .bitmap_directory_offset =
2559 cpu_to_be64(s->bitmap_directory_offset)
2561 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BITMAPS,
2562 &bitmaps_header, sizeof(bitmaps_header),
2563 buflen);
2564 if (ret < 0) {
2565 goto fail;
2567 buf += ret;
2568 buflen -= ret;
2571 /* Keep unknown header extensions */
2572 QLIST_FOREACH(uext, &s->unknown_header_ext, next) {
2573 ret = header_ext_add(buf, uext->magic, uext->data, uext->len, buflen);
2574 if (ret < 0) {
2575 goto fail;
2578 buf += ret;
2579 buflen -= ret;
2582 /* End of header extensions */
2583 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_END, NULL, 0, buflen);
2584 if (ret < 0) {
2585 goto fail;
2588 buf += ret;
2589 buflen -= ret;
2591 /* Backing file name */
2592 if (s->image_backing_file) {
2593 size_t backing_file_len = strlen(s->image_backing_file);
2595 if (buflen < backing_file_len) {
2596 ret = -ENOSPC;
2597 goto fail;
2600 /* Using strncpy is ok here, since buf is not NUL-terminated. */
2601 strncpy(buf, s->image_backing_file, buflen);
2603 header->backing_file_offset = cpu_to_be64(buf - ((char*) header));
2604 header->backing_file_size = cpu_to_be32(backing_file_len);
2607 /* Write the new header */
2608 ret = bdrv_pwrite(bs->file, 0, header, s->cluster_size);
2609 if (ret < 0) {
2610 goto fail;
2613 ret = 0;
2614 fail:
2615 qemu_vfree(header);
2616 return ret;
2619 static int qcow2_change_backing_file(BlockDriverState *bs,
2620 const char *backing_file, const char *backing_fmt)
2622 BDRVQcow2State *s = bs->opaque;
2624 /* Adding a backing file means that the external data file alone won't be
2625 * enough to make sense of the content */
2626 if (backing_file && data_file_is_raw(bs)) {
2627 return -EINVAL;
2630 if (backing_file && strlen(backing_file) > 1023) {
2631 return -EINVAL;
2634 pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
2635 backing_file ?: "");
2636 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
2637 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
2639 g_free(s->image_backing_file);
2640 g_free(s->image_backing_format);
2642 s->image_backing_file = backing_file ? g_strdup(bs->backing_file) : NULL;
2643 s->image_backing_format = backing_fmt ? g_strdup(bs->backing_format) : NULL;
2645 return qcow2_update_header(bs);
2648 static int qcow2_crypt_method_from_format(const char *encryptfmt)
2650 if (g_str_equal(encryptfmt, "luks")) {
2651 return QCOW_CRYPT_LUKS;
2652 } else if (g_str_equal(encryptfmt, "aes")) {
2653 return QCOW_CRYPT_AES;
2654 } else {
2655 return -EINVAL;
2659 static int qcow2_set_up_encryption(BlockDriverState *bs,
2660 QCryptoBlockCreateOptions *cryptoopts,
2661 Error **errp)
2663 BDRVQcow2State *s = bs->opaque;
2664 QCryptoBlock *crypto = NULL;
2665 int fmt, ret;
2667 switch (cryptoopts->format) {
2668 case Q_CRYPTO_BLOCK_FORMAT_LUKS:
2669 fmt = QCOW_CRYPT_LUKS;
2670 break;
2671 case Q_CRYPTO_BLOCK_FORMAT_QCOW:
2672 fmt = QCOW_CRYPT_AES;
2673 break;
2674 default:
2675 error_setg(errp, "Crypto format not supported in qcow2");
2676 return -EINVAL;
2679 s->crypt_method_header = fmt;
2681 crypto = qcrypto_block_create(cryptoopts, "encrypt.",
2682 qcow2_crypto_hdr_init_func,
2683 qcow2_crypto_hdr_write_func,
2684 bs, errp);
2685 if (!crypto) {
2686 return -EINVAL;
2689 ret = qcow2_update_header(bs);
2690 if (ret < 0) {
2691 error_setg_errno(errp, -ret, "Could not write encryption header");
2692 goto out;
2695 ret = 0;
2696 out:
2697 qcrypto_block_free(crypto);
2698 return ret;
2702 * Preallocates metadata structures for data clusters between @offset (in the
2703 * guest disk) and @new_length (which is thus generally the new guest disk
2704 * size).
2706 * Returns: 0 on success, -errno on failure.
2708 static int coroutine_fn preallocate_co(BlockDriverState *bs, uint64_t offset,
2709 uint64_t new_length, PreallocMode mode,
2710 Error **errp)
2712 BDRVQcow2State *s = bs->opaque;
2713 uint64_t bytes;
2714 uint64_t host_offset = 0;
2715 int64_t file_length;
2716 unsigned int cur_bytes;
2717 int ret;
2718 QCowL2Meta *meta;
2720 assert(offset <= new_length);
2721 bytes = new_length - offset;
2723 while (bytes) {
2724 cur_bytes = MIN(bytes, QEMU_ALIGN_DOWN(INT_MAX, s->cluster_size));
2725 ret = qcow2_alloc_cluster_offset(bs, offset, &cur_bytes,
2726 &host_offset, &meta);
2727 if (ret < 0) {
2728 error_setg_errno(errp, -ret, "Allocating clusters failed");
2729 return ret;
2732 while (meta) {
2733 QCowL2Meta *next = meta->next;
2735 ret = qcow2_alloc_cluster_link_l2(bs, meta);
2736 if (ret < 0) {
2737 error_setg_errno(errp, -ret, "Mapping clusters failed");
2738 qcow2_free_any_clusters(bs, meta->alloc_offset,
2739 meta->nb_clusters, QCOW2_DISCARD_NEVER);
2740 return ret;
2743 /* There are no dependent requests, but we need to remove our
2744 * request from the list of in-flight requests */
2745 QLIST_REMOVE(meta, next_in_flight);
2747 g_free(meta);
2748 meta = next;
2751 /* TODO Preallocate data if requested */
2753 bytes -= cur_bytes;
2754 offset += cur_bytes;
2758 * It is expected that the image file is large enough to actually contain
2759 * all of the allocated clusters (otherwise we get failing reads after
2760 * EOF). Extend the image to the last allocated sector.
2762 file_length = bdrv_getlength(s->data_file->bs);
2763 if (file_length < 0) {
2764 error_setg_errno(errp, -file_length, "Could not get file size");
2765 return file_length;
2768 if (host_offset + cur_bytes > file_length) {
2769 if (mode == PREALLOC_MODE_METADATA) {
2770 mode = PREALLOC_MODE_OFF;
2772 ret = bdrv_co_truncate(s->data_file, host_offset + cur_bytes, mode,
2773 errp);
2774 if (ret < 0) {
2775 return ret;
2779 return 0;
2782 /* qcow2_refcount_metadata_size:
2783 * @clusters: number of clusters to refcount (including data and L1/L2 tables)
2784 * @cluster_size: size of a cluster, in bytes
2785 * @refcount_order: refcount bits power-of-2 exponent
2786 * @generous_increase: allow for the refcount table to be 1.5x as large as it
2787 * needs to be
2789 * Returns: Number of bytes required for refcount blocks and table metadata.
2791 int64_t qcow2_refcount_metadata_size(int64_t clusters, size_t cluster_size,
2792 int refcount_order, bool generous_increase,
2793 uint64_t *refblock_count)
2796 * Every host cluster is reference-counted, including metadata (even
2797 * refcount metadata is recursively included).
2799 * An accurate formula for the size of refcount metadata size is difficult
2800 * to derive. An easier method of calculation is finding the fixed point
2801 * where no further refcount blocks or table clusters are required to
2802 * reference count every cluster.
2804 int64_t blocks_per_table_cluster = cluster_size / sizeof(uint64_t);
2805 int64_t refcounts_per_block = cluster_size * 8 / (1 << refcount_order);
2806 int64_t table = 0; /* number of refcount table clusters */
2807 int64_t blocks = 0; /* number of refcount block clusters */
2808 int64_t last;
2809 int64_t n = 0;
2811 do {
2812 last = n;
2813 blocks = DIV_ROUND_UP(clusters + table + blocks, refcounts_per_block);
2814 table = DIV_ROUND_UP(blocks, blocks_per_table_cluster);
2815 n = clusters + blocks + table;
2817 if (n == last && generous_increase) {
2818 clusters += DIV_ROUND_UP(table, 2);
2819 n = 0; /* force another loop */
2820 generous_increase = false;
2822 } while (n != last);
2824 if (refblock_count) {
2825 *refblock_count = blocks;
2828 return (blocks + table) * cluster_size;
2832 * qcow2_calc_prealloc_size:
2833 * @total_size: virtual disk size in bytes
2834 * @cluster_size: cluster size in bytes
2835 * @refcount_order: refcount bits power-of-2 exponent
2837 * Returns: Total number of bytes required for the fully allocated image
2838 * (including metadata).
2840 static int64_t qcow2_calc_prealloc_size(int64_t total_size,
2841 size_t cluster_size,
2842 int refcount_order)
2844 int64_t meta_size = 0;
2845 uint64_t nl1e, nl2e;
2846 int64_t aligned_total_size = ROUND_UP(total_size, cluster_size);
2848 /* header: 1 cluster */
2849 meta_size += cluster_size;
2851 /* total size of L2 tables */
2852 nl2e = aligned_total_size / cluster_size;
2853 nl2e = ROUND_UP(nl2e, cluster_size / sizeof(uint64_t));
2854 meta_size += nl2e * sizeof(uint64_t);
2856 /* total size of L1 tables */
2857 nl1e = nl2e * sizeof(uint64_t) / cluster_size;
2858 nl1e = ROUND_UP(nl1e, cluster_size / sizeof(uint64_t));
2859 meta_size += nl1e * sizeof(uint64_t);
2861 /* total size of refcount table and blocks */
2862 meta_size += qcow2_refcount_metadata_size(
2863 (meta_size + aligned_total_size) / cluster_size,
2864 cluster_size, refcount_order, false, NULL);
2866 return meta_size + aligned_total_size;
2869 static bool validate_cluster_size(size_t cluster_size, Error **errp)
2871 int cluster_bits = ctz32(cluster_size);
2872 if (cluster_bits < MIN_CLUSTER_BITS || cluster_bits > MAX_CLUSTER_BITS ||
2873 (1 << cluster_bits) != cluster_size)
2875 error_setg(errp, "Cluster size must be a power of two between %d and "
2876 "%dk", 1 << MIN_CLUSTER_BITS, 1 << (MAX_CLUSTER_BITS - 10));
2877 return false;
2879 return true;
2882 static size_t qcow2_opt_get_cluster_size_del(QemuOpts *opts, Error **errp)
2884 size_t cluster_size;
2886 cluster_size = qemu_opt_get_size_del(opts, BLOCK_OPT_CLUSTER_SIZE,
2887 DEFAULT_CLUSTER_SIZE);
2888 if (!validate_cluster_size(cluster_size, errp)) {
2889 return 0;
2891 return cluster_size;
2894 static int qcow2_opt_get_version_del(QemuOpts *opts, Error **errp)
2896 char *buf;
2897 int ret;
2899 buf = qemu_opt_get_del(opts, BLOCK_OPT_COMPAT_LEVEL);
2900 if (!buf) {
2901 ret = 3; /* default */
2902 } else if (!strcmp(buf, "0.10")) {
2903 ret = 2;
2904 } else if (!strcmp(buf, "1.1")) {
2905 ret = 3;
2906 } else {
2907 error_setg(errp, "Invalid compatibility level: '%s'", buf);
2908 ret = -EINVAL;
2910 g_free(buf);
2911 return ret;
2914 static uint64_t qcow2_opt_get_refcount_bits_del(QemuOpts *opts, int version,
2915 Error **errp)
2917 uint64_t refcount_bits;
2919 refcount_bits = qemu_opt_get_number_del(opts, BLOCK_OPT_REFCOUNT_BITS, 16);
2920 if (refcount_bits > 64 || !is_power_of_2(refcount_bits)) {
2921 error_setg(errp, "Refcount width must be a power of two and may not "
2922 "exceed 64 bits");
2923 return 0;
2926 if (version < 3 && refcount_bits != 16) {
2927 error_setg(errp, "Different refcount widths than 16 bits require "
2928 "compatibility level 1.1 or above (use compat=1.1 or "
2929 "greater)");
2930 return 0;
2933 return refcount_bits;
2936 static int coroutine_fn
2937 qcow2_co_create(BlockdevCreateOptions *create_options, Error **errp)
2939 BlockdevCreateOptionsQcow2 *qcow2_opts;
2940 QDict *options;
2943 * Open the image file and write a minimal qcow2 header.
2945 * We keep things simple and start with a zero-sized image. We also
2946 * do without refcount blocks or a L1 table for now. We'll fix the
2947 * inconsistency later.
2949 * We do need a refcount table because growing the refcount table means
2950 * allocating two new refcount blocks - the seconds of which would be at
2951 * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
2952 * size for any qcow2 image.
2954 BlockBackend *blk = NULL;
2955 BlockDriverState *bs = NULL;
2956 BlockDriverState *data_bs = NULL;
2957 QCowHeader *header;
2958 size_t cluster_size;
2959 int version;
2960 int refcount_order;
2961 uint64_t* refcount_table;
2962 Error *local_err = NULL;
2963 int ret;
2965 assert(create_options->driver == BLOCKDEV_DRIVER_QCOW2);
2966 qcow2_opts = &create_options->u.qcow2;
2968 bs = bdrv_open_blockdev_ref(qcow2_opts->file, errp);
2969 if (bs == NULL) {
2970 return -EIO;
2973 /* Validate options and set default values */
2974 if (!QEMU_IS_ALIGNED(qcow2_opts->size, BDRV_SECTOR_SIZE)) {
2975 error_setg(errp, "Image size must be a multiple of 512 bytes");
2976 ret = -EINVAL;
2977 goto out;
2980 if (qcow2_opts->has_version) {
2981 switch (qcow2_opts->version) {
2982 case BLOCKDEV_QCOW2_VERSION_V2:
2983 version = 2;
2984 break;
2985 case BLOCKDEV_QCOW2_VERSION_V3:
2986 version = 3;
2987 break;
2988 default:
2989 g_assert_not_reached();
2991 } else {
2992 version = 3;
2995 if (qcow2_opts->has_cluster_size) {
2996 cluster_size = qcow2_opts->cluster_size;
2997 } else {
2998 cluster_size = DEFAULT_CLUSTER_SIZE;
3001 if (!validate_cluster_size(cluster_size, errp)) {
3002 ret = -EINVAL;
3003 goto out;
3006 if (!qcow2_opts->has_preallocation) {
3007 qcow2_opts->preallocation = PREALLOC_MODE_OFF;
3009 if (qcow2_opts->has_backing_file &&
3010 qcow2_opts->preallocation != PREALLOC_MODE_OFF)
3012 error_setg(errp, "Backing file and preallocation cannot be used at "
3013 "the same time");
3014 ret = -EINVAL;
3015 goto out;
3017 if (qcow2_opts->has_backing_fmt && !qcow2_opts->has_backing_file) {
3018 error_setg(errp, "Backing format cannot be used without backing file");
3019 ret = -EINVAL;
3020 goto out;
3023 if (!qcow2_opts->has_lazy_refcounts) {
3024 qcow2_opts->lazy_refcounts = false;
3026 if (version < 3 && qcow2_opts->lazy_refcounts) {
3027 error_setg(errp, "Lazy refcounts only supported with compatibility "
3028 "level 1.1 and above (use version=v3 or greater)");
3029 ret = -EINVAL;
3030 goto out;
3033 if (!qcow2_opts->has_refcount_bits) {
3034 qcow2_opts->refcount_bits = 16;
3036 if (qcow2_opts->refcount_bits > 64 ||
3037 !is_power_of_2(qcow2_opts->refcount_bits))
3039 error_setg(errp, "Refcount width must be a power of two and may not "
3040 "exceed 64 bits");
3041 ret = -EINVAL;
3042 goto out;
3044 if (version < 3 && qcow2_opts->refcount_bits != 16) {
3045 error_setg(errp, "Different refcount widths than 16 bits require "
3046 "compatibility level 1.1 or above (use version=v3 or "
3047 "greater)");
3048 ret = -EINVAL;
3049 goto out;
3051 refcount_order = ctz32(qcow2_opts->refcount_bits);
3053 if (qcow2_opts->data_file_raw && !qcow2_opts->data_file) {
3054 error_setg(errp, "data-file-raw requires data-file");
3055 ret = -EINVAL;
3056 goto out;
3058 if (qcow2_opts->data_file_raw && qcow2_opts->has_backing_file) {
3059 error_setg(errp, "Backing file and data-file-raw cannot be used at "
3060 "the same time");
3061 ret = -EINVAL;
3062 goto out;
3065 if (qcow2_opts->data_file) {
3066 if (version < 3) {
3067 error_setg(errp, "External data files are only supported with "
3068 "compatibility level 1.1 and above (use version=v3 or "
3069 "greater)");
3070 ret = -EINVAL;
3071 goto out;
3073 data_bs = bdrv_open_blockdev_ref(qcow2_opts->data_file, errp);
3074 if (data_bs == NULL) {
3075 ret = -EIO;
3076 goto out;
3080 /* Create BlockBackend to write to the image */
3081 blk = blk_new(BLK_PERM_WRITE | BLK_PERM_RESIZE, BLK_PERM_ALL);
3082 ret = blk_insert_bs(blk, bs, errp);
3083 if (ret < 0) {
3084 goto out;
3086 blk_set_allow_write_beyond_eof(blk, true);
3088 /* Clear the protocol layer and preallocate it if necessary */
3089 ret = blk_truncate(blk, 0, PREALLOC_MODE_OFF, errp);
3090 if (ret < 0) {
3091 goto out;
3094 /* Write the header */
3095 QEMU_BUILD_BUG_ON((1 << MIN_CLUSTER_BITS) < sizeof(*header));
3096 header = g_malloc0(cluster_size);
3097 *header = (QCowHeader) {
3098 .magic = cpu_to_be32(QCOW_MAGIC),
3099 .version = cpu_to_be32(version),
3100 .cluster_bits = cpu_to_be32(ctz32(cluster_size)),
3101 .size = cpu_to_be64(0),
3102 .l1_table_offset = cpu_to_be64(0),
3103 .l1_size = cpu_to_be32(0),
3104 .refcount_table_offset = cpu_to_be64(cluster_size),
3105 .refcount_table_clusters = cpu_to_be32(1),
3106 .refcount_order = cpu_to_be32(refcount_order),
3107 .header_length = cpu_to_be32(sizeof(*header)),
3110 /* We'll update this to correct value later */
3111 header->crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
3113 if (qcow2_opts->lazy_refcounts) {
3114 header->compatible_features |=
3115 cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS);
3117 if (data_bs) {
3118 header->incompatible_features |=
3119 cpu_to_be64(QCOW2_INCOMPAT_DATA_FILE);
3121 if (qcow2_opts->data_file_raw) {
3122 header->autoclear_features |=
3123 cpu_to_be64(QCOW2_AUTOCLEAR_DATA_FILE_RAW);
3126 ret = blk_pwrite(blk, 0, header, cluster_size, 0);
3127 g_free(header);
3128 if (ret < 0) {
3129 error_setg_errno(errp, -ret, "Could not write qcow2 header");
3130 goto out;
3133 /* Write a refcount table with one refcount block */
3134 refcount_table = g_malloc0(2 * cluster_size);
3135 refcount_table[0] = cpu_to_be64(2 * cluster_size);
3136 ret = blk_pwrite(blk, cluster_size, refcount_table, 2 * cluster_size, 0);
3137 g_free(refcount_table);
3139 if (ret < 0) {
3140 error_setg_errno(errp, -ret, "Could not write refcount table");
3141 goto out;
3144 blk_unref(blk);
3145 blk = NULL;
3148 * And now open the image and make it consistent first (i.e. increase the
3149 * refcount of the cluster that is occupied by the header and the refcount
3150 * table)
3152 options = qdict_new();
3153 qdict_put_str(options, "driver", "qcow2");
3154 qdict_put_str(options, "file", bs->node_name);
3155 if (data_bs) {
3156 qdict_put_str(options, "data-file", data_bs->node_name);
3158 blk = blk_new_open(NULL, NULL, options,
3159 BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_NO_FLUSH,
3160 &local_err);
3161 if (blk == NULL) {
3162 error_propagate(errp, local_err);
3163 ret = -EIO;
3164 goto out;
3167 ret = qcow2_alloc_clusters(blk_bs(blk), 3 * cluster_size);
3168 if (ret < 0) {
3169 error_setg_errno(errp, -ret, "Could not allocate clusters for qcow2 "
3170 "header and refcount table");
3171 goto out;
3173 } else if (ret != 0) {
3174 error_report("Huh, first cluster in empty image is already in use?");
3175 abort();
3178 /* Set the external data file if necessary */
3179 if (data_bs) {
3180 BDRVQcow2State *s = blk_bs(blk)->opaque;
3181 s->image_data_file = g_strdup(data_bs->filename);
3184 /* Create a full header (including things like feature table) */
3185 ret = qcow2_update_header(blk_bs(blk));
3186 if (ret < 0) {
3187 error_setg_errno(errp, -ret, "Could not update qcow2 header");
3188 goto out;
3191 /* Okay, now that we have a valid image, let's give it the right size */
3192 ret = blk_truncate(blk, qcow2_opts->size, qcow2_opts->preallocation, errp);
3193 if (ret < 0) {
3194 error_prepend(errp, "Could not resize image: ");
3195 goto out;
3198 /* Want a backing file? There you go.*/
3199 if (qcow2_opts->has_backing_file) {
3200 const char *backing_format = NULL;
3202 if (qcow2_opts->has_backing_fmt) {
3203 backing_format = BlockdevDriver_str(qcow2_opts->backing_fmt);
3206 ret = bdrv_change_backing_file(blk_bs(blk), qcow2_opts->backing_file,
3207 backing_format);
3208 if (ret < 0) {
3209 error_setg_errno(errp, -ret, "Could not assign backing file '%s' "
3210 "with format '%s'", qcow2_opts->backing_file,
3211 backing_format);
3212 goto out;
3216 /* Want encryption? There you go. */
3217 if (qcow2_opts->has_encrypt) {
3218 ret = qcow2_set_up_encryption(blk_bs(blk), qcow2_opts->encrypt, errp);
3219 if (ret < 0) {
3220 goto out;
3224 blk_unref(blk);
3225 blk = NULL;
3227 /* Reopen the image without BDRV_O_NO_FLUSH to flush it before returning.
3228 * Using BDRV_O_NO_IO, since encryption is now setup we don't want to
3229 * have to setup decryption context. We're not doing any I/O on the top
3230 * level BlockDriverState, only lower layers, where BDRV_O_NO_IO does
3231 * not have effect.
3233 options = qdict_new();
3234 qdict_put_str(options, "driver", "qcow2");
3235 qdict_put_str(options, "file", bs->node_name);
3236 if (data_bs) {
3237 qdict_put_str(options, "data-file", data_bs->node_name);
3239 blk = blk_new_open(NULL, NULL, options,
3240 BDRV_O_RDWR | BDRV_O_NO_BACKING | BDRV_O_NO_IO,
3241 &local_err);
3242 if (blk == NULL) {
3243 error_propagate(errp, local_err);
3244 ret = -EIO;
3245 goto out;
3248 ret = 0;
3249 out:
3250 blk_unref(blk);
3251 bdrv_unref(bs);
3252 bdrv_unref(data_bs);
3253 return ret;
3256 static int coroutine_fn qcow2_co_create_opts(const char *filename, QemuOpts *opts,
3257 Error **errp)
3259 BlockdevCreateOptions *create_options = NULL;
3260 QDict *qdict;
3261 Visitor *v;
3262 BlockDriverState *bs = NULL;
3263 BlockDriverState *data_bs = NULL;
3264 Error *local_err = NULL;
3265 const char *val;
3266 int ret;
3268 /* Only the keyval visitor supports the dotted syntax needed for
3269 * encryption, so go through a QDict before getting a QAPI type. Ignore
3270 * options meant for the protocol layer so that the visitor doesn't
3271 * complain. */
3272 qdict = qemu_opts_to_qdict_filtered(opts, NULL, bdrv_qcow2.create_opts,
3273 true);
3275 /* Handle encryption options */
3276 val = qdict_get_try_str(qdict, BLOCK_OPT_ENCRYPT);
3277 if (val && !strcmp(val, "on")) {
3278 qdict_put_str(qdict, BLOCK_OPT_ENCRYPT, "qcow");
3279 } else if (val && !strcmp(val, "off")) {
3280 qdict_del(qdict, BLOCK_OPT_ENCRYPT);
3283 val = qdict_get_try_str(qdict, BLOCK_OPT_ENCRYPT_FORMAT);
3284 if (val && !strcmp(val, "aes")) {
3285 qdict_put_str(qdict, BLOCK_OPT_ENCRYPT_FORMAT, "qcow");
3288 /* Convert compat=0.10/1.1 into compat=v2/v3, to be renamed into
3289 * version=v2/v3 below. */
3290 val = qdict_get_try_str(qdict, BLOCK_OPT_COMPAT_LEVEL);
3291 if (val && !strcmp(val, "0.10")) {
3292 qdict_put_str(qdict, BLOCK_OPT_COMPAT_LEVEL, "v2");
3293 } else if (val && !strcmp(val, "1.1")) {
3294 qdict_put_str(qdict, BLOCK_OPT_COMPAT_LEVEL, "v3");
3297 /* Change legacy command line options into QMP ones */
3298 static const QDictRenames opt_renames[] = {
3299 { BLOCK_OPT_BACKING_FILE, "backing-file" },
3300 { BLOCK_OPT_BACKING_FMT, "backing-fmt" },
3301 { BLOCK_OPT_CLUSTER_SIZE, "cluster-size" },
3302 { BLOCK_OPT_LAZY_REFCOUNTS, "lazy-refcounts" },
3303 { BLOCK_OPT_REFCOUNT_BITS, "refcount-bits" },
3304 { BLOCK_OPT_ENCRYPT, BLOCK_OPT_ENCRYPT_FORMAT },
3305 { BLOCK_OPT_COMPAT_LEVEL, "version" },
3306 { BLOCK_OPT_DATA_FILE_RAW, "data-file-raw" },
3307 { NULL, NULL },
3310 if (!qdict_rename_keys(qdict, opt_renames, errp)) {
3311 ret = -EINVAL;
3312 goto finish;
3315 /* Create and open the file (protocol layer) */
3316 ret = bdrv_create_file(filename, opts, errp);
3317 if (ret < 0) {
3318 goto finish;
3321 bs = bdrv_open(filename, NULL, NULL,
3322 BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_PROTOCOL, errp);
3323 if (bs == NULL) {
3324 ret = -EIO;
3325 goto finish;
3328 /* Create and open an external data file (protocol layer) */
3329 val = qdict_get_try_str(qdict, BLOCK_OPT_DATA_FILE);
3330 if (val) {
3331 ret = bdrv_create_file(val, opts, errp);
3332 if (ret < 0) {
3333 goto finish;
3336 data_bs = bdrv_open(val, NULL, NULL,
3337 BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_PROTOCOL,
3338 errp);
3339 if (data_bs == NULL) {
3340 ret = -EIO;
3341 goto finish;
3344 qdict_del(qdict, BLOCK_OPT_DATA_FILE);
3345 qdict_put_str(qdict, "data-file", data_bs->node_name);
3348 /* Set 'driver' and 'node' options */
3349 qdict_put_str(qdict, "driver", "qcow2");
3350 qdict_put_str(qdict, "file", bs->node_name);
3352 /* Now get the QAPI type BlockdevCreateOptions */
3353 v = qobject_input_visitor_new_flat_confused(qdict, errp);
3354 if (!v) {
3355 ret = -EINVAL;
3356 goto finish;
3359 visit_type_BlockdevCreateOptions(v, NULL, &create_options, &local_err);
3360 visit_free(v);
3362 if (local_err) {
3363 error_propagate(errp, local_err);
3364 ret = -EINVAL;
3365 goto finish;
3368 /* Silently round up size */
3369 create_options->u.qcow2.size = ROUND_UP(create_options->u.qcow2.size,
3370 BDRV_SECTOR_SIZE);
3372 /* Create the qcow2 image (format layer) */
3373 ret = qcow2_co_create(create_options, errp);
3374 if (ret < 0) {
3375 goto finish;
3378 ret = 0;
3379 finish:
3380 qobject_unref(qdict);
3381 bdrv_unref(bs);
3382 bdrv_unref(data_bs);
3383 qapi_free_BlockdevCreateOptions(create_options);
3384 return ret;
3388 static bool is_zero(BlockDriverState *bs, int64_t offset, int64_t bytes)
3390 int64_t nr;
3391 int res;
3393 /* Clamp to image length, before checking status of underlying sectors */
3394 if (offset + bytes > bs->total_sectors * BDRV_SECTOR_SIZE) {
3395 bytes = bs->total_sectors * BDRV_SECTOR_SIZE - offset;
3398 if (!bytes) {
3399 return true;
3401 res = bdrv_block_status_above(bs, NULL, offset, bytes, &nr, NULL, NULL);
3402 return res >= 0 && (res & BDRV_BLOCK_ZERO) && nr == bytes;
3405 static coroutine_fn int qcow2_co_pwrite_zeroes(BlockDriverState *bs,
3406 int64_t offset, int bytes, BdrvRequestFlags flags)
3408 int ret;
3409 BDRVQcow2State *s = bs->opaque;
3411 uint32_t head = offset % s->cluster_size;
3412 uint32_t tail = (offset + bytes) % s->cluster_size;
3414 trace_qcow2_pwrite_zeroes_start_req(qemu_coroutine_self(), offset, bytes);
3415 if (offset + bytes == bs->total_sectors * BDRV_SECTOR_SIZE) {
3416 tail = 0;
3419 if (head || tail) {
3420 uint64_t off;
3421 unsigned int nr;
3423 assert(head + bytes <= s->cluster_size);
3425 /* check whether remainder of cluster already reads as zero */
3426 if (!(is_zero(bs, offset - head, head) &&
3427 is_zero(bs, offset + bytes,
3428 tail ? s->cluster_size - tail : 0))) {
3429 return -ENOTSUP;
3432 qemu_co_mutex_lock(&s->lock);
3433 /* We can have new write after previous check */
3434 offset = QEMU_ALIGN_DOWN(offset, s->cluster_size);
3435 bytes = s->cluster_size;
3436 nr = s->cluster_size;
3437 ret = qcow2_get_cluster_offset(bs, offset, &nr, &off);
3438 if (ret != QCOW2_CLUSTER_UNALLOCATED &&
3439 ret != QCOW2_CLUSTER_ZERO_PLAIN &&
3440 ret != QCOW2_CLUSTER_ZERO_ALLOC) {
3441 qemu_co_mutex_unlock(&s->lock);
3442 return -ENOTSUP;
3444 } else {
3445 qemu_co_mutex_lock(&s->lock);
3448 trace_qcow2_pwrite_zeroes(qemu_coroutine_self(), offset, bytes);
3450 /* Whatever is left can use real zero clusters */
3451 ret = qcow2_cluster_zeroize(bs, offset, bytes, flags);
3452 qemu_co_mutex_unlock(&s->lock);
3454 return ret;
3457 static coroutine_fn int qcow2_co_pdiscard(BlockDriverState *bs,
3458 int64_t offset, int bytes)
3460 int ret;
3461 BDRVQcow2State *s = bs->opaque;
3463 if (!QEMU_IS_ALIGNED(offset | bytes, s->cluster_size)) {
3464 assert(bytes < s->cluster_size);
3465 /* Ignore partial clusters, except for the special case of the
3466 * complete partial cluster at the end of an unaligned file */
3467 if (!QEMU_IS_ALIGNED(offset, s->cluster_size) ||
3468 offset + bytes != bs->total_sectors * BDRV_SECTOR_SIZE) {
3469 return -ENOTSUP;
3473 qemu_co_mutex_lock(&s->lock);
3474 ret = qcow2_cluster_discard(bs, offset, bytes, QCOW2_DISCARD_REQUEST,
3475 false);
3476 qemu_co_mutex_unlock(&s->lock);
3477 return ret;
3480 static int coroutine_fn
3481 qcow2_co_copy_range_from(BlockDriverState *bs,
3482 BdrvChild *src, uint64_t src_offset,
3483 BdrvChild *dst, uint64_t dst_offset,
3484 uint64_t bytes, BdrvRequestFlags read_flags,
3485 BdrvRequestFlags write_flags)
3487 BDRVQcow2State *s = bs->opaque;
3488 int ret;
3489 unsigned int cur_bytes; /* number of bytes in current iteration */
3490 BdrvChild *child = NULL;
3491 BdrvRequestFlags cur_write_flags;
3493 assert(!bs->encrypted);
3494 qemu_co_mutex_lock(&s->lock);
3496 while (bytes != 0) {
3497 uint64_t copy_offset = 0;
3498 /* prepare next request */
3499 cur_bytes = MIN(bytes, INT_MAX);
3500 cur_write_flags = write_flags;
3502 ret = qcow2_get_cluster_offset(bs, src_offset, &cur_bytes, &copy_offset);
3503 if (ret < 0) {
3504 goto out;
3507 switch (ret) {
3508 case QCOW2_CLUSTER_UNALLOCATED:
3509 if (bs->backing && bs->backing->bs) {
3510 int64_t backing_length = bdrv_getlength(bs->backing->bs);
3511 if (src_offset >= backing_length) {
3512 cur_write_flags |= BDRV_REQ_ZERO_WRITE;
3513 } else {
3514 child = bs->backing;
3515 cur_bytes = MIN(cur_bytes, backing_length - src_offset);
3516 copy_offset = src_offset;
3518 } else {
3519 cur_write_flags |= BDRV_REQ_ZERO_WRITE;
3521 break;
3523 case QCOW2_CLUSTER_ZERO_PLAIN:
3524 case QCOW2_CLUSTER_ZERO_ALLOC:
3525 cur_write_flags |= BDRV_REQ_ZERO_WRITE;
3526 break;
3528 case QCOW2_CLUSTER_COMPRESSED:
3529 ret = -ENOTSUP;
3530 goto out;
3532 case QCOW2_CLUSTER_NORMAL:
3533 child = s->data_file;
3534 copy_offset += offset_into_cluster(s, src_offset);
3535 if ((copy_offset & 511) != 0) {
3536 ret = -EIO;
3537 goto out;
3539 break;
3541 default:
3542 abort();
3544 qemu_co_mutex_unlock(&s->lock);
3545 ret = bdrv_co_copy_range_from(child,
3546 copy_offset,
3547 dst, dst_offset,
3548 cur_bytes, read_flags, cur_write_flags);
3549 qemu_co_mutex_lock(&s->lock);
3550 if (ret < 0) {
3551 goto out;
3554 bytes -= cur_bytes;
3555 src_offset += cur_bytes;
3556 dst_offset += cur_bytes;
3558 ret = 0;
3560 out:
3561 qemu_co_mutex_unlock(&s->lock);
3562 return ret;
3565 static int coroutine_fn
3566 qcow2_co_copy_range_to(BlockDriverState *bs,
3567 BdrvChild *src, uint64_t src_offset,
3568 BdrvChild *dst, uint64_t dst_offset,
3569 uint64_t bytes, BdrvRequestFlags read_flags,
3570 BdrvRequestFlags write_flags)
3572 BDRVQcow2State *s = bs->opaque;
3573 int offset_in_cluster;
3574 int ret;
3575 unsigned int cur_bytes; /* number of sectors in current iteration */
3576 uint64_t cluster_offset;
3577 QCowL2Meta *l2meta = NULL;
3579 assert(!bs->encrypted);
3581 qemu_co_mutex_lock(&s->lock);
3583 while (bytes != 0) {
3585 l2meta = NULL;
3587 offset_in_cluster = offset_into_cluster(s, dst_offset);
3588 cur_bytes = MIN(bytes, INT_MAX);
3590 /* TODO:
3591 * If src->bs == dst->bs, we could simply copy by incrementing
3592 * the refcnt, without copying user data.
3593 * Or if src->bs == dst->bs->backing->bs, we could copy by discarding. */
3594 ret = qcow2_alloc_cluster_offset(bs, dst_offset, &cur_bytes,
3595 &cluster_offset, &l2meta);
3596 if (ret < 0) {
3597 goto fail;
3600 assert((cluster_offset & 511) == 0);
3602 ret = qcow2_pre_write_overlap_check(bs, 0,
3603 cluster_offset + offset_in_cluster, cur_bytes, true);
3604 if (ret < 0) {
3605 goto fail;
3608 qemu_co_mutex_unlock(&s->lock);
3609 ret = bdrv_co_copy_range_to(src, src_offset,
3610 s->data_file,
3611 cluster_offset + offset_in_cluster,
3612 cur_bytes, read_flags, write_flags);
3613 qemu_co_mutex_lock(&s->lock);
3614 if (ret < 0) {
3615 goto fail;
3618 ret = qcow2_handle_l2meta(bs, &l2meta, true);
3619 if (ret) {
3620 goto fail;
3623 bytes -= cur_bytes;
3624 src_offset += cur_bytes;
3625 dst_offset += cur_bytes;
3627 ret = 0;
3629 fail:
3630 qcow2_handle_l2meta(bs, &l2meta, false);
3632 qemu_co_mutex_unlock(&s->lock);
3634 trace_qcow2_writev_done_req(qemu_coroutine_self(), ret);
3636 return ret;
3639 static int coroutine_fn qcow2_co_truncate(BlockDriverState *bs, int64_t offset,
3640 PreallocMode prealloc, Error **errp)
3642 BDRVQcow2State *s = bs->opaque;
3643 uint64_t old_length;
3644 int64_t new_l1_size;
3645 int ret;
3646 QDict *options;
3648 if (prealloc != PREALLOC_MODE_OFF && prealloc != PREALLOC_MODE_METADATA &&
3649 prealloc != PREALLOC_MODE_FALLOC && prealloc != PREALLOC_MODE_FULL)
3651 error_setg(errp, "Unsupported preallocation mode '%s'",
3652 PreallocMode_str(prealloc));
3653 return -ENOTSUP;
3656 if (offset & 511) {
3657 error_setg(errp, "The new size must be a multiple of 512");
3658 return -EINVAL;
3661 qemu_co_mutex_lock(&s->lock);
3663 /* cannot proceed if image has snapshots */
3664 if (s->nb_snapshots) {
3665 error_setg(errp, "Can't resize an image which has snapshots");
3666 ret = -ENOTSUP;
3667 goto fail;
3670 /* cannot proceed if image has bitmaps */
3671 if (qcow2_truncate_bitmaps_check(bs, errp)) {
3672 ret = -ENOTSUP;
3673 goto fail;
3676 old_length = bs->total_sectors * BDRV_SECTOR_SIZE;
3677 new_l1_size = size_to_l1(s, offset);
3679 if (offset < old_length) {
3680 int64_t last_cluster, old_file_size;
3681 if (prealloc != PREALLOC_MODE_OFF) {
3682 error_setg(errp,
3683 "Preallocation can't be used for shrinking an image");
3684 ret = -EINVAL;
3685 goto fail;
3688 ret = qcow2_cluster_discard(bs, ROUND_UP(offset, s->cluster_size),
3689 old_length - ROUND_UP(offset,
3690 s->cluster_size),
3691 QCOW2_DISCARD_ALWAYS, true);
3692 if (ret < 0) {
3693 error_setg_errno(errp, -ret, "Failed to discard cropped clusters");
3694 goto fail;
3697 ret = qcow2_shrink_l1_table(bs, new_l1_size);
3698 if (ret < 0) {
3699 error_setg_errno(errp, -ret,
3700 "Failed to reduce the number of L2 tables");
3701 goto fail;
3704 ret = qcow2_shrink_reftable(bs);
3705 if (ret < 0) {
3706 error_setg_errno(errp, -ret,
3707 "Failed to discard unused refblocks");
3708 goto fail;
3711 old_file_size = bdrv_getlength(bs->file->bs);
3712 if (old_file_size < 0) {
3713 error_setg_errno(errp, -old_file_size,
3714 "Failed to inquire current file length");
3715 ret = old_file_size;
3716 goto fail;
3718 last_cluster = qcow2_get_last_cluster(bs, old_file_size);
3719 if (last_cluster < 0) {
3720 error_setg_errno(errp, -last_cluster,
3721 "Failed to find the last cluster");
3722 ret = last_cluster;
3723 goto fail;
3725 if ((last_cluster + 1) * s->cluster_size < old_file_size) {
3726 Error *local_err = NULL;
3728 bdrv_co_truncate(bs->file, (last_cluster + 1) * s->cluster_size,
3729 PREALLOC_MODE_OFF, &local_err);
3730 if (local_err) {
3731 warn_reportf_err(local_err,
3732 "Failed to truncate the tail of the image: ");
3735 } else {
3736 ret = qcow2_grow_l1_table(bs, new_l1_size, true);
3737 if (ret < 0) {
3738 error_setg_errno(errp, -ret, "Failed to grow the L1 table");
3739 goto fail;
3743 switch (prealloc) {
3744 case PREALLOC_MODE_OFF:
3745 if (has_data_file(bs)) {
3746 ret = bdrv_co_truncate(s->data_file, offset, prealloc, errp);
3747 if (ret < 0) {
3748 goto fail;
3751 break;
3753 case PREALLOC_MODE_METADATA:
3754 ret = preallocate_co(bs, old_length, offset, prealloc, errp);
3755 if (ret < 0) {
3756 goto fail;
3758 break;
3760 case PREALLOC_MODE_FALLOC:
3761 case PREALLOC_MODE_FULL:
3763 int64_t allocation_start, host_offset, guest_offset;
3764 int64_t clusters_allocated;
3765 int64_t old_file_size, new_file_size;
3766 uint64_t nb_new_data_clusters, nb_new_l2_tables;
3768 /* With a data file, preallocation means just allocating the metadata
3769 * and forwarding the truncate request to the data file */
3770 if (has_data_file(bs)) {
3771 ret = preallocate_co(bs, old_length, offset, prealloc, errp);
3772 if (ret < 0) {
3773 goto fail;
3775 break;
3778 old_file_size = bdrv_getlength(bs->file->bs);
3779 if (old_file_size < 0) {
3780 error_setg_errno(errp, -old_file_size,
3781 "Failed to inquire current file length");
3782 ret = old_file_size;
3783 goto fail;
3785 old_file_size = ROUND_UP(old_file_size, s->cluster_size);
3787 nb_new_data_clusters = DIV_ROUND_UP(offset - old_length,
3788 s->cluster_size);
3790 /* This is an overestimation; we will not actually allocate space for
3791 * these in the file but just make sure the new refcount structures are
3792 * able to cover them so we will not have to allocate new refblocks
3793 * while entering the data blocks in the potentially new L2 tables.
3794 * (We do not actually care where the L2 tables are placed. Maybe they
3795 * are already allocated or they can be placed somewhere before
3796 * @old_file_size. It does not matter because they will be fully
3797 * allocated automatically, so they do not need to be covered by the
3798 * preallocation. All that matters is that we will not have to allocate
3799 * new refcount structures for them.) */
3800 nb_new_l2_tables = DIV_ROUND_UP(nb_new_data_clusters,
3801 s->cluster_size / sizeof(uint64_t));
3802 /* The cluster range may not be aligned to L2 boundaries, so add one L2
3803 * table for a potential head/tail */
3804 nb_new_l2_tables++;
3806 allocation_start = qcow2_refcount_area(bs, old_file_size,
3807 nb_new_data_clusters +
3808 nb_new_l2_tables,
3809 true, 0, 0);
3810 if (allocation_start < 0) {
3811 error_setg_errno(errp, -allocation_start,
3812 "Failed to resize refcount structures");
3813 ret = allocation_start;
3814 goto fail;
3817 clusters_allocated = qcow2_alloc_clusters_at(bs, allocation_start,
3818 nb_new_data_clusters);
3819 if (clusters_allocated < 0) {
3820 error_setg_errno(errp, -clusters_allocated,
3821 "Failed to allocate data clusters");
3822 ret = clusters_allocated;
3823 goto fail;
3826 assert(clusters_allocated == nb_new_data_clusters);
3828 /* Allocate the data area */
3829 new_file_size = allocation_start +
3830 nb_new_data_clusters * s->cluster_size;
3831 ret = bdrv_co_truncate(bs->file, new_file_size, prealloc, errp);
3832 if (ret < 0) {
3833 error_prepend(errp, "Failed to resize underlying file: ");
3834 qcow2_free_clusters(bs, allocation_start,
3835 nb_new_data_clusters * s->cluster_size,
3836 QCOW2_DISCARD_OTHER);
3837 goto fail;
3840 /* Create the necessary L2 entries */
3841 host_offset = allocation_start;
3842 guest_offset = old_length;
3843 while (nb_new_data_clusters) {
3844 int64_t nb_clusters = MIN(
3845 nb_new_data_clusters,
3846 s->l2_slice_size - offset_to_l2_slice_index(s, guest_offset));
3847 QCowL2Meta allocation = {
3848 .offset = guest_offset,
3849 .alloc_offset = host_offset,
3850 .nb_clusters = nb_clusters,
3852 qemu_co_queue_init(&allocation.dependent_requests);
3854 ret = qcow2_alloc_cluster_link_l2(bs, &allocation);
3855 if (ret < 0) {
3856 error_setg_errno(errp, -ret, "Failed to update L2 tables");
3857 qcow2_free_clusters(bs, host_offset,
3858 nb_new_data_clusters * s->cluster_size,
3859 QCOW2_DISCARD_OTHER);
3860 goto fail;
3863 guest_offset += nb_clusters * s->cluster_size;
3864 host_offset += nb_clusters * s->cluster_size;
3865 nb_new_data_clusters -= nb_clusters;
3867 break;
3870 default:
3871 g_assert_not_reached();
3874 if (prealloc != PREALLOC_MODE_OFF) {
3875 /* Flush metadata before actually changing the image size */
3876 ret = qcow2_write_caches(bs);
3877 if (ret < 0) {
3878 error_setg_errno(errp, -ret,
3879 "Failed to flush the preallocated area to disk");
3880 goto fail;
3884 bs->total_sectors = offset / BDRV_SECTOR_SIZE;
3886 /* write updated header.size */
3887 offset = cpu_to_be64(offset);
3888 ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, size),
3889 &offset, sizeof(uint64_t));
3890 if (ret < 0) {
3891 error_setg_errno(errp, -ret, "Failed to update the image size");
3892 goto fail;
3895 s->l1_vm_state_index = new_l1_size;
3897 /* Update cache sizes */
3898 options = qdict_clone_shallow(bs->options);
3899 ret = qcow2_update_options(bs, options, s->flags, errp);
3900 qobject_unref(options);
3901 if (ret < 0) {
3902 goto fail;
3904 ret = 0;
3905 fail:
3906 qemu_co_mutex_unlock(&s->lock);
3907 return ret;
3910 /* XXX: put compressed sectors first, then all the cluster aligned
3911 tables to avoid losing bytes in alignment */
3912 static coroutine_fn int
3913 qcow2_co_pwritev_compressed(BlockDriverState *bs, uint64_t offset,
3914 uint64_t bytes, QEMUIOVector *qiov)
3916 BDRVQcow2State *s = bs->opaque;
3917 int ret;
3918 ssize_t out_len;
3919 uint8_t *buf, *out_buf;
3920 uint64_t cluster_offset;
3922 if (has_data_file(bs)) {
3923 return -ENOTSUP;
3926 if (bytes == 0) {
3927 /* align end of file to a sector boundary to ease reading with
3928 sector based I/Os */
3929 int64_t len = bdrv_getlength(bs->file->bs);
3930 if (len < 0) {
3931 return len;
3933 return bdrv_co_truncate(bs->file, len, PREALLOC_MODE_OFF, NULL);
3936 if (offset_into_cluster(s, offset)) {
3937 return -EINVAL;
3940 buf = qemu_blockalign(bs, s->cluster_size);
3941 if (bytes != s->cluster_size) {
3942 if (bytes > s->cluster_size ||
3943 offset + bytes != bs->total_sectors << BDRV_SECTOR_BITS)
3945 qemu_vfree(buf);
3946 return -EINVAL;
3948 /* Zero-pad last write if image size is not cluster aligned */
3949 memset(buf + bytes, 0, s->cluster_size - bytes);
3951 qemu_iovec_to_buf(qiov, 0, buf, bytes);
3953 out_buf = g_malloc(s->cluster_size);
3955 out_len = qcow2_co_compress(bs, out_buf, s->cluster_size - 1,
3956 buf, s->cluster_size);
3957 if (out_len == -ENOMEM) {
3958 /* could not compress: write normal cluster */
3959 ret = qcow2_co_pwritev(bs, offset, bytes, qiov, 0);
3960 if (ret < 0) {
3961 goto fail;
3963 goto success;
3964 } else if (out_len < 0) {
3965 ret = -EINVAL;
3966 goto fail;
3969 qemu_co_mutex_lock(&s->lock);
3970 ret = qcow2_alloc_compressed_cluster_offset(bs, offset, out_len,
3971 &cluster_offset);
3972 if (ret < 0) {
3973 qemu_co_mutex_unlock(&s->lock);
3974 goto fail;
3977 ret = qcow2_pre_write_overlap_check(bs, 0, cluster_offset, out_len, true);
3978 qemu_co_mutex_unlock(&s->lock);
3979 if (ret < 0) {
3980 goto fail;
3983 BLKDBG_EVENT(s->data_file, BLKDBG_WRITE_COMPRESSED);
3984 ret = bdrv_co_pwrite(s->data_file, cluster_offset, out_len, out_buf, 0);
3985 if (ret < 0) {
3986 goto fail;
3988 success:
3989 ret = 0;
3990 fail:
3991 qemu_vfree(buf);
3992 g_free(out_buf);
3993 return ret;
3996 static int coroutine_fn
3997 qcow2_co_preadv_compressed(BlockDriverState *bs,
3998 uint64_t file_cluster_offset,
3999 uint64_t offset,
4000 uint64_t bytes,
4001 QEMUIOVector *qiov)
4003 BDRVQcow2State *s = bs->opaque;
4004 int ret = 0, csize, nb_csectors;
4005 uint64_t coffset;
4006 uint8_t *buf, *out_buf;
4007 int offset_in_cluster = offset_into_cluster(s, offset);
4009 coffset = file_cluster_offset & s->cluster_offset_mask;
4010 nb_csectors = ((file_cluster_offset >> s->csize_shift) & s->csize_mask) + 1;
4011 csize = nb_csectors * QCOW2_COMPRESSED_SECTOR_SIZE -
4012 (coffset & ~QCOW2_COMPRESSED_SECTOR_MASK);
4014 buf = g_try_malloc(csize);
4015 if (!buf) {
4016 return -ENOMEM;
4019 out_buf = qemu_blockalign(bs, s->cluster_size);
4021 BLKDBG_EVENT(bs->file, BLKDBG_READ_COMPRESSED);
4022 ret = bdrv_co_pread(bs->file, coffset, csize, buf, 0);
4023 if (ret < 0) {
4024 goto fail;
4027 if (qcow2_co_decompress(bs, out_buf, s->cluster_size, buf, csize) < 0) {
4028 ret = -EIO;
4029 goto fail;
4032 qemu_iovec_from_buf(qiov, 0, out_buf + offset_in_cluster, bytes);
4034 fail:
4035 qemu_vfree(out_buf);
4036 g_free(buf);
4038 return ret;
4041 static int make_completely_empty(BlockDriverState *bs)
4043 BDRVQcow2State *s = bs->opaque;
4044 Error *local_err = NULL;
4045 int ret, l1_clusters;
4046 int64_t offset;
4047 uint64_t *new_reftable = NULL;
4048 uint64_t rt_entry, l1_size2;
4049 struct {
4050 uint64_t l1_offset;
4051 uint64_t reftable_offset;
4052 uint32_t reftable_clusters;
4053 } QEMU_PACKED l1_ofs_rt_ofs_cls;
4055 ret = qcow2_cache_empty(bs, s->l2_table_cache);
4056 if (ret < 0) {
4057 goto fail;
4060 ret = qcow2_cache_empty(bs, s->refcount_block_cache);
4061 if (ret < 0) {
4062 goto fail;
4065 /* Refcounts will be broken utterly */
4066 ret = qcow2_mark_dirty(bs);
4067 if (ret < 0) {
4068 goto fail;
4071 BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
4073 l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / sizeof(uint64_t));
4074 l1_size2 = (uint64_t)s->l1_size * sizeof(uint64_t);
4076 /* After this call, neither the in-memory nor the on-disk refcount
4077 * information accurately describe the actual references */
4079 ret = bdrv_pwrite_zeroes(bs->file, s->l1_table_offset,
4080 l1_clusters * s->cluster_size, 0);
4081 if (ret < 0) {
4082 goto fail_broken_refcounts;
4084 memset(s->l1_table, 0, l1_size2);
4086 BLKDBG_EVENT(bs->file, BLKDBG_EMPTY_IMAGE_PREPARE);
4088 /* Overwrite enough clusters at the beginning of the sectors to place
4089 * the refcount table, a refcount block and the L1 table in; this may
4090 * overwrite parts of the existing refcount and L1 table, which is not
4091 * an issue because the dirty flag is set, complete data loss is in fact
4092 * desired and partial data loss is consequently fine as well */
4093 ret = bdrv_pwrite_zeroes(bs->file, s->cluster_size,
4094 (2 + l1_clusters) * s->cluster_size, 0);
4095 /* This call (even if it failed overall) may have overwritten on-disk
4096 * refcount structures; in that case, the in-memory refcount information
4097 * will probably differ from the on-disk information which makes the BDS
4098 * unusable */
4099 if (ret < 0) {
4100 goto fail_broken_refcounts;
4103 BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
4104 BLKDBG_EVENT(bs->file, BLKDBG_REFTABLE_UPDATE);
4106 /* "Create" an empty reftable (one cluster) directly after the image
4107 * header and an empty L1 table three clusters after the image header;
4108 * the cluster between those two will be used as the first refblock */
4109 l1_ofs_rt_ofs_cls.l1_offset = cpu_to_be64(3 * s->cluster_size);
4110 l1_ofs_rt_ofs_cls.reftable_offset = cpu_to_be64(s->cluster_size);
4111 l1_ofs_rt_ofs_cls.reftable_clusters = cpu_to_be32(1);
4112 ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, l1_table_offset),
4113 &l1_ofs_rt_ofs_cls, sizeof(l1_ofs_rt_ofs_cls));
4114 if (ret < 0) {
4115 goto fail_broken_refcounts;
4118 s->l1_table_offset = 3 * s->cluster_size;
4120 new_reftable = g_try_new0(uint64_t, s->cluster_size / sizeof(uint64_t));
4121 if (!new_reftable) {
4122 ret = -ENOMEM;
4123 goto fail_broken_refcounts;
4126 s->refcount_table_offset = s->cluster_size;
4127 s->refcount_table_size = s->cluster_size / sizeof(uint64_t);
4128 s->max_refcount_table_index = 0;
4130 g_free(s->refcount_table);
4131 s->refcount_table = new_reftable;
4132 new_reftable = NULL;
4134 /* Now the in-memory refcount information again corresponds to the on-disk
4135 * information (reftable is empty and no refblocks (the refblock cache is
4136 * empty)); however, this means some clusters (e.g. the image header) are
4137 * referenced, but not refcounted, but the normal qcow2 code assumes that
4138 * the in-memory information is always correct */
4140 BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_ALLOC);
4142 /* Enter the first refblock into the reftable */
4143 rt_entry = cpu_to_be64(2 * s->cluster_size);
4144 ret = bdrv_pwrite_sync(bs->file, s->cluster_size,
4145 &rt_entry, sizeof(rt_entry));
4146 if (ret < 0) {
4147 goto fail_broken_refcounts;
4149 s->refcount_table[0] = 2 * s->cluster_size;
4151 s->free_cluster_index = 0;
4152 assert(3 + l1_clusters <= s->refcount_block_size);
4153 offset = qcow2_alloc_clusters(bs, 3 * s->cluster_size + l1_size2);
4154 if (offset < 0) {
4155 ret = offset;
4156 goto fail_broken_refcounts;
4157 } else if (offset > 0) {
4158 error_report("First cluster in emptied image is in use");
4159 abort();
4162 /* Now finally the in-memory information corresponds to the on-disk
4163 * structures and is correct */
4164 ret = qcow2_mark_clean(bs);
4165 if (ret < 0) {
4166 goto fail;
4169 ret = bdrv_truncate(bs->file, (3 + l1_clusters) * s->cluster_size,
4170 PREALLOC_MODE_OFF, &local_err);
4171 if (ret < 0) {
4172 error_report_err(local_err);
4173 goto fail;
4176 return 0;
4178 fail_broken_refcounts:
4179 /* The BDS is unusable at this point. If we wanted to make it usable, we
4180 * would have to call qcow2_refcount_close(), qcow2_refcount_init(),
4181 * qcow2_check_refcounts(), qcow2_refcount_close() and qcow2_refcount_init()
4182 * again. However, because the functions which could have caused this error
4183 * path to be taken are used by those functions as well, it's very likely
4184 * that that sequence will fail as well. Therefore, just eject the BDS. */
4185 bs->drv = NULL;
4187 fail:
4188 g_free(new_reftable);
4189 return ret;
4192 static int qcow2_make_empty(BlockDriverState *bs)
4194 BDRVQcow2State *s = bs->opaque;
4195 uint64_t offset, end_offset;
4196 int step = QEMU_ALIGN_DOWN(INT_MAX, s->cluster_size);
4197 int l1_clusters, ret = 0;
4199 l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / sizeof(uint64_t));
4201 if (s->qcow_version >= 3 && !s->snapshots && !s->nb_bitmaps &&
4202 3 + l1_clusters <= s->refcount_block_size &&
4203 s->crypt_method_header != QCOW_CRYPT_LUKS &&
4204 !has_data_file(bs)) {
4205 /* The following function only works for qcow2 v3 images (it
4206 * requires the dirty flag) and only as long as there are no
4207 * features that reserve extra clusters (such as snapshots,
4208 * LUKS header, or persistent bitmaps), because it completely
4209 * empties the image. Furthermore, the L1 table and three
4210 * additional clusters (image header, refcount table, one
4211 * refcount block) have to fit inside one refcount block. It
4212 * only resets the image file, i.e. does not work with an
4213 * external data file. */
4214 return make_completely_empty(bs);
4217 /* This fallback code simply discards every active cluster; this is slow,
4218 * but works in all cases */
4219 end_offset = bs->total_sectors * BDRV_SECTOR_SIZE;
4220 for (offset = 0; offset < end_offset; offset += step) {
4221 /* As this function is generally used after committing an external
4222 * snapshot, QCOW2_DISCARD_SNAPSHOT seems appropriate. Also, the
4223 * default action for this kind of discard is to pass the discard,
4224 * which will ideally result in an actually smaller image file, as
4225 * is probably desired. */
4226 ret = qcow2_cluster_discard(bs, offset, MIN(step, end_offset - offset),
4227 QCOW2_DISCARD_SNAPSHOT, true);
4228 if (ret < 0) {
4229 break;
4233 return ret;
4236 static coroutine_fn int qcow2_co_flush_to_os(BlockDriverState *bs)
4238 BDRVQcow2State *s = bs->opaque;
4239 int ret;
4241 qemu_co_mutex_lock(&s->lock);
4242 ret = qcow2_write_caches(bs);
4243 qemu_co_mutex_unlock(&s->lock);
4245 return ret;
4248 static ssize_t qcow2_measure_crypto_hdr_init_func(QCryptoBlock *block,
4249 size_t headerlen, void *opaque, Error **errp)
4251 size_t *headerlenp = opaque;
4253 /* Stash away the payload size */
4254 *headerlenp = headerlen;
4255 return 0;
4258 static ssize_t qcow2_measure_crypto_hdr_write_func(QCryptoBlock *block,
4259 size_t offset, const uint8_t *buf, size_t buflen,
4260 void *opaque, Error **errp)
4262 /* Discard the bytes, we're not actually writing to an image */
4263 return buflen;
4266 /* Determine the number of bytes for the LUKS payload */
4267 static bool qcow2_measure_luks_headerlen(QemuOpts *opts, size_t *len,
4268 Error **errp)
4270 QDict *opts_qdict;
4271 QDict *cryptoopts_qdict;
4272 QCryptoBlockCreateOptions *cryptoopts;
4273 QCryptoBlock *crypto;
4275 /* Extract "encrypt." options into a qdict */
4276 opts_qdict = qemu_opts_to_qdict(opts, NULL);
4277 qdict_extract_subqdict(opts_qdict, &cryptoopts_qdict, "encrypt.");
4278 qobject_unref(opts_qdict);
4280 /* Build QCryptoBlockCreateOptions object from qdict */
4281 qdict_put_str(cryptoopts_qdict, "format", "luks");
4282 cryptoopts = block_crypto_create_opts_init(cryptoopts_qdict, errp);
4283 qobject_unref(cryptoopts_qdict);
4284 if (!cryptoopts) {
4285 return false;
4288 /* Fake LUKS creation in order to determine the payload size */
4289 crypto = qcrypto_block_create(cryptoopts, "encrypt.",
4290 qcow2_measure_crypto_hdr_init_func,
4291 qcow2_measure_crypto_hdr_write_func,
4292 len, errp);
4293 qapi_free_QCryptoBlockCreateOptions(cryptoopts);
4294 if (!crypto) {
4295 return false;
4298 qcrypto_block_free(crypto);
4299 return true;
4302 static BlockMeasureInfo *qcow2_measure(QemuOpts *opts, BlockDriverState *in_bs,
4303 Error **errp)
4305 Error *local_err = NULL;
4306 BlockMeasureInfo *info;
4307 uint64_t required = 0; /* bytes that contribute to required size */
4308 uint64_t virtual_size; /* disk size as seen by guest */
4309 uint64_t refcount_bits;
4310 uint64_t l2_tables;
4311 uint64_t luks_payload_size = 0;
4312 size_t cluster_size;
4313 int version;
4314 char *optstr;
4315 PreallocMode prealloc;
4316 bool has_backing_file;
4317 bool has_luks;
4319 /* Parse image creation options */
4320 cluster_size = qcow2_opt_get_cluster_size_del(opts, &local_err);
4321 if (local_err) {
4322 goto err;
4325 version = qcow2_opt_get_version_del(opts, &local_err);
4326 if (local_err) {
4327 goto err;
4330 refcount_bits = qcow2_opt_get_refcount_bits_del(opts, version, &local_err);
4331 if (local_err) {
4332 goto err;
4335 optstr = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
4336 prealloc = qapi_enum_parse(&PreallocMode_lookup, optstr,
4337 PREALLOC_MODE_OFF, &local_err);
4338 g_free(optstr);
4339 if (local_err) {
4340 goto err;
4343 optstr = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
4344 has_backing_file = !!optstr;
4345 g_free(optstr);
4347 optstr = qemu_opt_get_del(opts, BLOCK_OPT_ENCRYPT_FORMAT);
4348 has_luks = optstr && strcmp(optstr, "luks") == 0;
4349 g_free(optstr);
4351 if (has_luks) {
4352 size_t headerlen;
4354 if (!qcow2_measure_luks_headerlen(opts, &headerlen, &local_err)) {
4355 goto err;
4358 luks_payload_size = ROUND_UP(headerlen, cluster_size);
4361 virtual_size = qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0);
4362 virtual_size = ROUND_UP(virtual_size, cluster_size);
4364 /* Check that virtual disk size is valid */
4365 l2_tables = DIV_ROUND_UP(virtual_size / cluster_size,
4366 cluster_size / sizeof(uint64_t));
4367 if (l2_tables * sizeof(uint64_t) > QCOW_MAX_L1_SIZE) {
4368 error_setg(&local_err, "The image size is too large "
4369 "(try using a larger cluster size)");
4370 goto err;
4373 /* Account for input image */
4374 if (in_bs) {
4375 int64_t ssize = bdrv_getlength(in_bs);
4376 if (ssize < 0) {
4377 error_setg_errno(&local_err, -ssize,
4378 "Unable to get image virtual_size");
4379 goto err;
4382 virtual_size = ROUND_UP(ssize, cluster_size);
4384 if (has_backing_file) {
4385 /* We don't how much of the backing chain is shared by the input
4386 * image and the new image file. In the worst case the new image's
4387 * backing file has nothing in common with the input image. Be
4388 * conservative and assume all clusters need to be written.
4390 required = virtual_size;
4391 } else {
4392 int64_t offset;
4393 int64_t pnum = 0;
4395 for (offset = 0; offset < ssize; offset += pnum) {
4396 int ret;
4398 ret = bdrv_block_status_above(in_bs, NULL, offset,
4399 ssize - offset, &pnum, NULL,
4400 NULL);
4401 if (ret < 0) {
4402 error_setg_errno(&local_err, -ret,
4403 "Unable to get block status");
4404 goto err;
4407 if (ret & BDRV_BLOCK_ZERO) {
4408 /* Skip zero regions (safe with no backing file) */
4409 } else if ((ret & (BDRV_BLOCK_DATA | BDRV_BLOCK_ALLOCATED)) ==
4410 (BDRV_BLOCK_DATA | BDRV_BLOCK_ALLOCATED)) {
4411 /* Extend pnum to end of cluster for next iteration */
4412 pnum = ROUND_UP(offset + pnum, cluster_size) - offset;
4414 /* Count clusters we've seen */
4415 required += offset % cluster_size + pnum;
4421 /* Take into account preallocation. Nothing special is needed for
4422 * PREALLOC_MODE_METADATA since metadata is always counted.
4424 if (prealloc == PREALLOC_MODE_FULL || prealloc == PREALLOC_MODE_FALLOC) {
4425 required = virtual_size;
4428 info = g_new(BlockMeasureInfo, 1);
4429 info->fully_allocated =
4430 qcow2_calc_prealloc_size(virtual_size, cluster_size,
4431 ctz32(refcount_bits)) + luks_payload_size;
4433 /* Remove data clusters that are not required. This overestimates the
4434 * required size because metadata needed for the fully allocated file is
4435 * still counted.
4437 info->required = info->fully_allocated - virtual_size + required;
4438 return info;
4440 err:
4441 error_propagate(errp, local_err);
4442 return NULL;
4445 static int qcow2_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
4447 BDRVQcow2State *s = bs->opaque;
4448 bdi->unallocated_blocks_are_zero = true;
4449 bdi->cluster_size = s->cluster_size;
4450 bdi->vm_state_offset = qcow2_vm_state_offset(s);
4451 return 0;
4454 static ImageInfoSpecific *qcow2_get_specific_info(BlockDriverState *bs,
4455 Error **errp)
4457 BDRVQcow2State *s = bs->opaque;
4458 ImageInfoSpecific *spec_info;
4459 QCryptoBlockInfo *encrypt_info = NULL;
4460 Error *local_err = NULL;
4462 if (s->crypto != NULL) {
4463 encrypt_info = qcrypto_block_get_info(s->crypto, &local_err);
4464 if (local_err) {
4465 error_propagate(errp, local_err);
4466 return NULL;
4470 spec_info = g_new(ImageInfoSpecific, 1);
4471 *spec_info = (ImageInfoSpecific){
4472 .type = IMAGE_INFO_SPECIFIC_KIND_QCOW2,
4473 .u.qcow2.data = g_new0(ImageInfoSpecificQCow2, 1),
4475 if (s->qcow_version == 2) {
4476 *spec_info->u.qcow2.data = (ImageInfoSpecificQCow2){
4477 .compat = g_strdup("0.10"),
4478 .refcount_bits = s->refcount_bits,
4480 } else if (s->qcow_version == 3) {
4481 Qcow2BitmapInfoList *bitmaps;
4482 bitmaps = qcow2_get_bitmap_info_list(bs, &local_err);
4483 if (local_err) {
4484 error_propagate(errp, local_err);
4485 qapi_free_ImageInfoSpecific(spec_info);
4486 return NULL;
4488 *spec_info->u.qcow2.data = (ImageInfoSpecificQCow2){
4489 .compat = g_strdup("1.1"),
4490 .lazy_refcounts = s->compatible_features &
4491 QCOW2_COMPAT_LAZY_REFCOUNTS,
4492 .has_lazy_refcounts = true,
4493 .corrupt = s->incompatible_features &
4494 QCOW2_INCOMPAT_CORRUPT,
4495 .has_corrupt = true,
4496 .refcount_bits = s->refcount_bits,
4497 .has_bitmaps = !!bitmaps,
4498 .bitmaps = bitmaps,
4499 .has_data_file = !!s->image_data_file,
4500 .data_file = g_strdup(s->image_data_file),
4501 .has_data_file_raw = has_data_file(bs),
4502 .data_file_raw = data_file_is_raw(bs),
4504 } else {
4505 /* if this assertion fails, this probably means a new version was
4506 * added without having it covered here */
4507 assert(false);
4510 if (encrypt_info) {
4511 ImageInfoSpecificQCow2Encryption *qencrypt =
4512 g_new(ImageInfoSpecificQCow2Encryption, 1);
4513 switch (encrypt_info->format) {
4514 case Q_CRYPTO_BLOCK_FORMAT_QCOW:
4515 qencrypt->format = BLOCKDEV_QCOW2_ENCRYPTION_FORMAT_AES;
4516 break;
4517 case Q_CRYPTO_BLOCK_FORMAT_LUKS:
4518 qencrypt->format = BLOCKDEV_QCOW2_ENCRYPTION_FORMAT_LUKS;
4519 qencrypt->u.luks = encrypt_info->u.luks;
4520 break;
4521 default:
4522 abort();
4524 /* Since we did shallow copy above, erase any pointers
4525 * in the original info */
4526 memset(&encrypt_info->u, 0, sizeof(encrypt_info->u));
4527 qapi_free_QCryptoBlockInfo(encrypt_info);
4529 spec_info->u.qcow2.data->has_encrypt = true;
4530 spec_info->u.qcow2.data->encrypt = qencrypt;
4533 return spec_info;
4536 static int qcow2_save_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
4537 int64_t pos)
4539 BDRVQcow2State *s = bs->opaque;
4541 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_SAVE);
4542 return bs->drv->bdrv_co_pwritev(bs, qcow2_vm_state_offset(s) + pos,
4543 qiov->size, qiov, 0);
4546 static int qcow2_load_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
4547 int64_t pos)
4549 BDRVQcow2State *s = bs->opaque;
4551 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_LOAD);
4552 return bs->drv->bdrv_co_preadv(bs, qcow2_vm_state_offset(s) + pos,
4553 qiov->size, qiov, 0);
4557 * Downgrades an image's version. To achieve this, any incompatible features
4558 * have to be removed.
4560 static int qcow2_downgrade(BlockDriverState *bs, int target_version,
4561 BlockDriverAmendStatusCB *status_cb, void *cb_opaque,
4562 Error **errp)
4564 BDRVQcow2State *s = bs->opaque;
4565 int current_version = s->qcow_version;
4566 int ret;
4568 /* This is qcow2_downgrade(), not qcow2_upgrade() */
4569 assert(target_version < current_version);
4571 /* There are no other versions (now) that you can downgrade to */
4572 assert(target_version == 2);
4574 if (s->refcount_order != 4) {
4575 error_setg(errp, "compat=0.10 requires refcount_bits=16");
4576 return -ENOTSUP;
4579 if (has_data_file(bs)) {
4580 error_setg(errp, "Cannot downgrade an image with a data file");
4581 return -ENOTSUP;
4584 /* clear incompatible features */
4585 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
4586 ret = qcow2_mark_clean(bs);
4587 if (ret < 0) {
4588 error_setg_errno(errp, -ret, "Failed to make the image clean");
4589 return ret;
4593 /* with QCOW2_INCOMPAT_CORRUPT, it is pretty much impossible to get here in
4594 * the first place; if that happens nonetheless, returning -ENOTSUP is the
4595 * best thing to do anyway */
4597 if (s->incompatible_features) {
4598 error_setg(errp, "Cannot downgrade an image with incompatible features "
4599 "%#" PRIx64 " set", s->incompatible_features);
4600 return -ENOTSUP;
4603 /* since we can ignore compatible features, we can set them to 0 as well */
4604 s->compatible_features = 0;
4605 /* if lazy refcounts have been used, they have already been fixed through
4606 * clearing the dirty flag */
4608 /* clearing autoclear features is trivial */
4609 s->autoclear_features = 0;
4611 ret = qcow2_expand_zero_clusters(bs, status_cb, cb_opaque);
4612 if (ret < 0) {
4613 error_setg_errno(errp, -ret, "Failed to turn zero into data clusters");
4614 return ret;
4617 s->qcow_version = target_version;
4618 ret = qcow2_update_header(bs);
4619 if (ret < 0) {
4620 s->qcow_version = current_version;
4621 error_setg_errno(errp, -ret, "Failed to update the image header");
4622 return ret;
4624 return 0;
4627 typedef enum Qcow2AmendOperation {
4628 /* This is the value Qcow2AmendHelperCBInfo::last_operation will be
4629 * statically initialized to so that the helper CB can discern the first
4630 * invocation from an operation change */
4631 QCOW2_NO_OPERATION = 0,
4633 QCOW2_CHANGING_REFCOUNT_ORDER,
4634 QCOW2_DOWNGRADING,
4635 } Qcow2AmendOperation;
4637 typedef struct Qcow2AmendHelperCBInfo {
4638 /* The code coordinating the amend operations should only modify
4639 * these four fields; the rest will be managed by the CB */
4640 BlockDriverAmendStatusCB *original_status_cb;
4641 void *original_cb_opaque;
4643 Qcow2AmendOperation current_operation;
4645 /* Total number of operations to perform (only set once) */
4646 int total_operations;
4648 /* The following fields are managed by the CB */
4650 /* Number of operations completed */
4651 int operations_completed;
4653 /* Cumulative offset of all completed operations */
4654 int64_t offset_completed;
4656 Qcow2AmendOperation last_operation;
4657 int64_t last_work_size;
4658 } Qcow2AmendHelperCBInfo;
4660 static void qcow2_amend_helper_cb(BlockDriverState *bs,
4661 int64_t operation_offset,
4662 int64_t operation_work_size, void *opaque)
4664 Qcow2AmendHelperCBInfo *info = opaque;
4665 int64_t current_work_size;
4666 int64_t projected_work_size;
4668 if (info->current_operation != info->last_operation) {
4669 if (info->last_operation != QCOW2_NO_OPERATION) {
4670 info->offset_completed += info->last_work_size;
4671 info->operations_completed++;
4674 info->last_operation = info->current_operation;
4677 assert(info->total_operations > 0);
4678 assert(info->operations_completed < info->total_operations);
4680 info->last_work_size = operation_work_size;
4682 current_work_size = info->offset_completed + operation_work_size;
4684 /* current_work_size is the total work size for (operations_completed + 1)
4685 * operations (which includes this one), so multiply it by the number of
4686 * operations not covered and divide it by the number of operations
4687 * covered to get a projection for the operations not covered */
4688 projected_work_size = current_work_size * (info->total_operations -
4689 info->operations_completed - 1)
4690 / (info->operations_completed + 1);
4692 info->original_status_cb(bs, info->offset_completed + operation_offset,
4693 current_work_size + projected_work_size,
4694 info->original_cb_opaque);
4697 static int qcow2_amend_options(BlockDriverState *bs, QemuOpts *opts,
4698 BlockDriverAmendStatusCB *status_cb,
4699 void *cb_opaque,
4700 Error **errp)
4702 BDRVQcow2State *s = bs->opaque;
4703 int old_version = s->qcow_version, new_version = old_version;
4704 uint64_t new_size = 0;
4705 const char *backing_file = NULL, *backing_format = NULL, *data_file = NULL;
4706 bool lazy_refcounts = s->use_lazy_refcounts;
4707 bool data_file_raw = data_file_is_raw(bs);
4708 const char *compat = NULL;
4709 uint64_t cluster_size = s->cluster_size;
4710 bool encrypt;
4711 int encformat;
4712 int refcount_bits = s->refcount_bits;
4713 int ret;
4714 QemuOptDesc *desc = opts->list->desc;
4715 Qcow2AmendHelperCBInfo helper_cb_info;
4717 while (desc && desc->name) {
4718 if (!qemu_opt_find(opts, desc->name)) {
4719 /* only change explicitly defined options */
4720 desc++;
4721 continue;
4724 if (!strcmp(desc->name, BLOCK_OPT_COMPAT_LEVEL)) {
4725 compat = qemu_opt_get(opts, BLOCK_OPT_COMPAT_LEVEL);
4726 if (!compat) {
4727 /* preserve default */
4728 } else if (!strcmp(compat, "0.10")) {
4729 new_version = 2;
4730 } else if (!strcmp(compat, "1.1")) {
4731 new_version = 3;
4732 } else {
4733 error_setg(errp, "Unknown compatibility level %s", compat);
4734 return -EINVAL;
4736 } else if (!strcmp(desc->name, BLOCK_OPT_PREALLOC)) {
4737 error_setg(errp, "Cannot change preallocation mode");
4738 return -ENOTSUP;
4739 } else if (!strcmp(desc->name, BLOCK_OPT_SIZE)) {
4740 new_size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, 0);
4741 } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FILE)) {
4742 backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
4743 } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FMT)) {
4744 backing_format = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
4745 } else if (!strcmp(desc->name, BLOCK_OPT_ENCRYPT)) {
4746 encrypt = qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT,
4747 !!s->crypto);
4749 if (encrypt != !!s->crypto) {
4750 error_setg(errp,
4751 "Changing the encryption flag is not supported");
4752 return -ENOTSUP;
4754 } else if (!strcmp(desc->name, BLOCK_OPT_ENCRYPT_FORMAT)) {
4755 encformat = qcow2_crypt_method_from_format(
4756 qemu_opt_get(opts, BLOCK_OPT_ENCRYPT_FORMAT));
4758 if (encformat != s->crypt_method_header) {
4759 error_setg(errp,
4760 "Changing the encryption format is not supported");
4761 return -ENOTSUP;
4763 } else if (g_str_has_prefix(desc->name, "encrypt.")) {
4764 error_setg(errp,
4765 "Changing the encryption parameters is not supported");
4766 return -ENOTSUP;
4767 } else if (!strcmp(desc->name, BLOCK_OPT_CLUSTER_SIZE)) {
4768 cluster_size = qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE,
4769 cluster_size);
4770 if (cluster_size != s->cluster_size) {
4771 error_setg(errp, "Changing the cluster size is not supported");
4772 return -ENOTSUP;
4774 } else if (!strcmp(desc->name, BLOCK_OPT_LAZY_REFCOUNTS)) {
4775 lazy_refcounts = qemu_opt_get_bool(opts, BLOCK_OPT_LAZY_REFCOUNTS,
4776 lazy_refcounts);
4777 } else if (!strcmp(desc->name, BLOCK_OPT_REFCOUNT_BITS)) {
4778 refcount_bits = qemu_opt_get_number(opts, BLOCK_OPT_REFCOUNT_BITS,
4779 refcount_bits);
4781 if (refcount_bits <= 0 || refcount_bits > 64 ||
4782 !is_power_of_2(refcount_bits))
4784 error_setg(errp, "Refcount width must be a power of two and "
4785 "may not exceed 64 bits");
4786 return -EINVAL;
4788 } else if (!strcmp(desc->name, BLOCK_OPT_DATA_FILE)) {
4789 data_file = qemu_opt_get(opts, BLOCK_OPT_DATA_FILE);
4790 if (data_file && !has_data_file(bs)) {
4791 error_setg(errp, "data-file can only be set for images that "
4792 "use an external data file");
4793 return -EINVAL;
4795 } else if (!strcmp(desc->name, BLOCK_OPT_DATA_FILE_RAW)) {
4796 data_file_raw = qemu_opt_get_bool(opts, BLOCK_OPT_DATA_FILE_RAW,
4797 data_file_raw);
4798 if (data_file_raw && !data_file_is_raw(bs)) {
4799 error_setg(errp, "data-file-raw cannot be set on existing "
4800 "images");
4801 return -EINVAL;
4803 } else {
4804 /* if this point is reached, this probably means a new option was
4805 * added without having it covered here */
4806 abort();
4809 desc++;
4812 helper_cb_info = (Qcow2AmendHelperCBInfo){
4813 .original_status_cb = status_cb,
4814 .original_cb_opaque = cb_opaque,
4815 .total_operations = (new_version < old_version)
4816 + (s->refcount_bits != refcount_bits)
4819 /* Upgrade first (some features may require compat=1.1) */
4820 if (new_version > old_version) {
4821 s->qcow_version = new_version;
4822 ret = qcow2_update_header(bs);
4823 if (ret < 0) {
4824 s->qcow_version = old_version;
4825 error_setg_errno(errp, -ret, "Failed to update the image header");
4826 return ret;
4830 if (s->refcount_bits != refcount_bits) {
4831 int refcount_order = ctz32(refcount_bits);
4833 if (new_version < 3 && refcount_bits != 16) {
4834 error_setg(errp, "Refcount widths other than 16 bits require "
4835 "compatibility level 1.1 or above (use compat=1.1 or "
4836 "greater)");
4837 return -EINVAL;
4840 helper_cb_info.current_operation = QCOW2_CHANGING_REFCOUNT_ORDER;
4841 ret = qcow2_change_refcount_order(bs, refcount_order,
4842 &qcow2_amend_helper_cb,
4843 &helper_cb_info, errp);
4844 if (ret < 0) {
4845 return ret;
4849 /* data-file-raw blocks backing files, so clear it first if requested */
4850 if (data_file_raw) {
4851 s->autoclear_features |= QCOW2_AUTOCLEAR_DATA_FILE_RAW;
4852 } else {
4853 s->autoclear_features &= ~QCOW2_AUTOCLEAR_DATA_FILE_RAW;
4856 if (data_file) {
4857 g_free(s->image_data_file);
4858 s->image_data_file = *data_file ? g_strdup(data_file) : NULL;
4861 ret = qcow2_update_header(bs);
4862 if (ret < 0) {
4863 error_setg_errno(errp, -ret, "Failed to update the image header");
4864 return ret;
4867 if (backing_file || backing_format) {
4868 ret = qcow2_change_backing_file(bs,
4869 backing_file ?: s->image_backing_file,
4870 backing_format ?: s->image_backing_format);
4871 if (ret < 0) {
4872 error_setg_errno(errp, -ret, "Failed to change the backing file");
4873 return ret;
4877 if (s->use_lazy_refcounts != lazy_refcounts) {
4878 if (lazy_refcounts) {
4879 if (new_version < 3) {
4880 error_setg(errp, "Lazy refcounts only supported with "
4881 "compatibility level 1.1 and above (use compat=1.1 "
4882 "or greater)");
4883 return -EINVAL;
4885 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
4886 ret = qcow2_update_header(bs);
4887 if (ret < 0) {
4888 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
4889 error_setg_errno(errp, -ret, "Failed to update the image header");
4890 return ret;
4892 s->use_lazy_refcounts = true;
4893 } else {
4894 /* make image clean first */
4895 ret = qcow2_mark_clean(bs);
4896 if (ret < 0) {
4897 error_setg_errno(errp, -ret, "Failed to make the image clean");
4898 return ret;
4900 /* now disallow lazy refcounts */
4901 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
4902 ret = qcow2_update_header(bs);
4903 if (ret < 0) {
4904 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
4905 error_setg_errno(errp, -ret, "Failed to update the image header");
4906 return ret;
4908 s->use_lazy_refcounts = false;
4912 if (new_size) {
4913 BlockBackend *blk = blk_new(BLK_PERM_RESIZE, BLK_PERM_ALL);
4914 ret = blk_insert_bs(blk, bs, errp);
4915 if (ret < 0) {
4916 blk_unref(blk);
4917 return ret;
4920 ret = blk_truncate(blk, new_size, PREALLOC_MODE_OFF, errp);
4921 blk_unref(blk);
4922 if (ret < 0) {
4923 return ret;
4927 /* Downgrade last (so unsupported features can be removed before) */
4928 if (new_version < old_version) {
4929 helper_cb_info.current_operation = QCOW2_DOWNGRADING;
4930 ret = qcow2_downgrade(bs, new_version, &qcow2_amend_helper_cb,
4931 &helper_cb_info, errp);
4932 if (ret < 0) {
4933 return ret;
4937 return 0;
4941 * If offset or size are negative, respectively, they will not be included in
4942 * the BLOCK_IMAGE_CORRUPTED event emitted.
4943 * fatal will be ignored for read-only BDS; corruptions found there will always
4944 * be considered non-fatal.
4946 void qcow2_signal_corruption(BlockDriverState *bs, bool fatal, int64_t offset,
4947 int64_t size, const char *message_format, ...)
4949 BDRVQcow2State *s = bs->opaque;
4950 const char *node_name;
4951 char *message;
4952 va_list ap;
4954 fatal = fatal && bdrv_is_writable(bs);
4956 if (s->signaled_corruption &&
4957 (!fatal || (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT)))
4959 return;
4962 va_start(ap, message_format);
4963 message = g_strdup_vprintf(message_format, ap);
4964 va_end(ap);
4966 if (fatal) {
4967 fprintf(stderr, "qcow2: Marking image as corrupt: %s; further "
4968 "corruption events will be suppressed\n", message);
4969 } else {
4970 fprintf(stderr, "qcow2: Image is corrupt: %s; further non-fatal "
4971 "corruption events will be suppressed\n", message);
4974 node_name = bdrv_get_node_name(bs);
4975 qapi_event_send_block_image_corrupted(bdrv_get_device_name(bs),
4976 *node_name != '\0', node_name,
4977 message, offset >= 0, offset,
4978 size >= 0, size,
4979 fatal);
4980 g_free(message);
4982 if (fatal) {
4983 qcow2_mark_corrupt(bs);
4984 bs->drv = NULL; /* make BDS unusable */
4987 s->signaled_corruption = true;
4990 static QemuOptsList qcow2_create_opts = {
4991 .name = "qcow2-create-opts",
4992 .head = QTAILQ_HEAD_INITIALIZER(qcow2_create_opts.head),
4993 .desc = {
4995 .name = BLOCK_OPT_SIZE,
4996 .type = QEMU_OPT_SIZE,
4997 .help = "Virtual disk size"
5000 .name = BLOCK_OPT_COMPAT_LEVEL,
5001 .type = QEMU_OPT_STRING,
5002 .help = "Compatibility level (0.10 or 1.1)"
5005 .name = BLOCK_OPT_BACKING_FILE,
5006 .type = QEMU_OPT_STRING,
5007 .help = "File name of a base image"
5010 .name = BLOCK_OPT_BACKING_FMT,
5011 .type = QEMU_OPT_STRING,
5012 .help = "Image format of the base image"
5015 .name = BLOCK_OPT_DATA_FILE,
5016 .type = QEMU_OPT_STRING,
5017 .help = "File name of an external data file"
5020 .name = BLOCK_OPT_DATA_FILE_RAW,
5021 .type = QEMU_OPT_BOOL,
5022 .help = "The external data file must stay valid as a raw image"
5025 .name = BLOCK_OPT_ENCRYPT,
5026 .type = QEMU_OPT_BOOL,
5027 .help = "Encrypt the image with format 'aes'. (Deprecated "
5028 "in favor of " BLOCK_OPT_ENCRYPT_FORMAT "=aes)",
5031 .name = BLOCK_OPT_ENCRYPT_FORMAT,
5032 .type = QEMU_OPT_STRING,
5033 .help = "Encrypt the image, format choices: 'aes', 'luks'",
5035 BLOCK_CRYPTO_OPT_DEF_KEY_SECRET("encrypt.",
5036 "ID of secret providing qcow AES key or LUKS passphrase"),
5037 BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_ALG("encrypt."),
5038 BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_MODE("encrypt."),
5039 BLOCK_CRYPTO_OPT_DEF_LUKS_IVGEN_ALG("encrypt."),
5040 BLOCK_CRYPTO_OPT_DEF_LUKS_IVGEN_HASH_ALG("encrypt."),
5041 BLOCK_CRYPTO_OPT_DEF_LUKS_HASH_ALG("encrypt."),
5042 BLOCK_CRYPTO_OPT_DEF_LUKS_ITER_TIME("encrypt."),
5044 .name = BLOCK_OPT_CLUSTER_SIZE,
5045 .type = QEMU_OPT_SIZE,
5046 .help = "qcow2 cluster size",
5047 .def_value_str = stringify(DEFAULT_CLUSTER_SIZE)
5050 .name = BLOCK_OPT_PREALLOC,
5051 .type = QEMU_OPT_STRING,
5052 .help = "Preallocation mode (allowed values: off, metadata, "
5053 "falloc, full)"
5056 .name = BLOCK_OPT_LAZY_REFCOUNTS,
5057 .type = QEMU_OPT_BOOL,
5058 .help = "Postpone refcount updates",
5059 .def_value_str = "off"
5062 .name = BLOCK_OPT_REFCOUNT_BITS,
5063 .type = QEMU_OPT_NUMBER,
5064 .help = "Width of a reference count entry in bits",
5065 .def_value_str = "16"
5067 { /* end of list */ }
5071 static const char *const qcow2_strong_runtime_opts[] = {
5072 "encrypt." BLOCK_CRYPTO_OPT_QCOW_KEY_SECRET,
5074 NULL
5077 BlockDriver bdrv_qcow2 = {
5078 .format_name = "qcow2",
5079 .instance_size = sizeof(BDRVQcow2State),
5080 .bdrv_probe = qcow2_probe,
5081 .bdrv_open = qcow2_open,
5082 .bdrv_close = qcow2_close,
5083 .bdrv_reopen_prepare = qcow2_reopen_prepare,
5084 .bdrv_reopen_commit = qcow2_reopen_commit,
5085 .bdrv_reopen_abort = qcow2_reopen_abort,
5086 .bdrv_join_options = qcow2_join_options,
5087 .bdrv_child_perm = bdrv_format_default_perms,
5088 .bdrv_co_create_opts = qcow2_co_create_opts,
5089 .bdrv_co_create = qcow2_co_create,
5090 .bdrv_has_zero_init = bdrv_has_zero_init_1,
5091 .bdrv_co_block_status = qcow2_co_block_status,
5093 .bdrv_co_preadv = qcow2_co_preadv,
5094 .bdrv_co_pwritev = qcow2_co_pwritev,
5095 .bdrv_co_flush_to_os = qcow2_co_flush_to_os,
5097 .bdrv_co_pwrite_zeroes = qcow2_co_pwrite_zeroes,
5098 .bdrv_co_pdiscard = qcow2_co_pdiscard,
5099 .bdrv_co_copy_range_from = qcow2_co_copy_range_from,
5100 .bdrv_co_copy_range_to = qcow2_co_copy_range_to,
5101 .bdrv_co_truncate = qcow2_co_truncate,
5102 .bdrv_co_pwritev_compressed = qcow2_co_pwritev_compressed,
5103 .bdrv_make_empty = qcow2_make_empty,
5105 .bdrv_snapshot_create = qcow2_snapshot_create,
5106 .bdrv_snapshot_goto = qcow2_snapshot_goto,
5107 .bdrv_snapshot_delete = qcow2_snapshot_delete,
5108 .bdrv_snapshot_list = qcow2_snapshot_list,
5109 .bdrv_snapshot_load_tmp = qcow2_snapshot_load_tmp,
5110 .bdrv_measure = qcow2_measure,
5111 .bdrv_get_info = qcow2_get_info,
5112 .bdrv_get_specific_info = qcow2_get_specific_info,
5114 .bdrv_save_vmstate = qcow2_save_vmstate,
5115 .bdrv_load_vmstate = qcow2_load_vmstate,
5117 .supports_backing = true,
5118 .bdrv_change_backing_file = qcow2_change_backing_file,
5120 .bdrv_refresh_limits = qcow2_refresh_limits,
5121 .bdrv_co_invalidate_cache = qcow2_co_invalidate_cache,
5122 .bdrv_inactivate = qcow2_inactivate,
5124 .create_opts = &qcow2_create_opts,
5125 .strong_runtime_opts = qcow2_strong_runtime_opts,
5126 .mutable_opts = mutable_opts,
5127 .bdrv_co_check = qcow2_co_check,
5128 .bdrv_amend_options = qcow2_amend_options,
5130 .bdrv_detach_aio_context = qcow2_detach_aio_context,
5131 .bdrv_attach_aio_context = qcow2_attach_aio_context,
5133 .bdrv_reopen_bitmaps_rw = qcow2_reopen_bitmaps_rw,
5134 .bdrv_can_store_new_dirty_bitmap = qcow2_can_store_new_dirty_bitmap,
5135 .bdrv_remove_persistent_dirty_bitmap = qcow2_remove_persistent_dirty_bitmap,
5138 static void bdrv_qcow2_init(void)
5140 bdrv_register(&bdrv_qcow2);
5143 block_init(bdrv_qcow2_init);