tpm_emulator: Translate TPM error codes to strings
[qemu/ar7.git] / block / qcow2.c
blob6ddaf9a1f8baf1a7cdf87d9cfd0a1987e3111259
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 #define ZLIB_CONST
28 #include <zlib.h>
30 #include "block/block_int.h"
31 #include "block/qdict.h"
32 #include "sysemu/block-backend.h"
33 #include "qemu/module.h"
34 #include "qcow2.h"
35 #include "qemu/error-report.h"
36 #include "qapi/error.h"
37 #include "qapi/qapi-events-block-core.h"
38 #include "qapi/qmp/qdict.h"
39 #include "qapi/qmp/qstring.h"
40 #include "trace.h"
41 #include "qemu/option_int.h"
42 #include "qemu/cutils.h"
43 #include "qemu/bswap.h"
44 #include "qapi/qobject-input-visitor.h"
45 #include "qapi/qapi-visit-block-core.h"
46 #include "crypto.h"
47 #include "block/thread-pool.h"
50 Differences with QCOW:
52 - Support for multiple incremental snapshots.
53 - Memory management by reference counts.
54 - Clusters which have a reference count of one have the bit
55 QCOW_OFLAG_COPIED to optimize write performance.
56 - Size of compressed clusters is stored in sectors to reduce bit usage
57 in the cluster offsets.
58 - Support for storing additional data (such as the VM state) in the
59 snapshots.
60 - If a backing store is used, the cluster size is not constrained
61 (could be backported to QCOW).
62 - L2 tables have always a size of one cluster.
66 typedef struct {
67 uint32_t magic;
68 uint32_t len;
69 } QEMU_PACKED QCowExtension;
71 #define QCOW2_EXT_MAGIC_END 0
72 #define QCOW2_EXT_MAGIC_BACKING_FORMAT 0xE2792ACA
73 #define QCOW2_EXT_MAGIC_FEATURE_TABLE 0x6803f857
74 #define QCOW2_EXT_MAGIC_CRYPTO_HEADER 0x0537be77
75 #define QCOW2_EXT_MAGIC_BITMAPS 0x23852875
77 static int qcow2_probe(const uint8_t *buf, int buf_size, const char *filename)
79 const QCowHeader *cow_header = (const void *)buf;
81 if (buf_size >= sizeof(QCowHeader) &&
82 be32_to_cpu(cow_header->magic) == QCOW_MAGIC &&
83 be32_to_cpu(cow_header->version) >= 2)
84 return 100;
85 else
86 return 0;
90 static ssize_t qcow2_crypto_hdr_read_func(QCryptoBlock *block, size_t offset,
91 uint8_t *buf, size_t buflen,
92 void *opaque, Error **errp)
94 BlockDriverState *bs = opaque;
95 BDRVQcow2State *s = bs->opaque;
96 ssize_t ret;
98 if ((offset + buflen) > s->crypto_header.length) {
99 error_setg(errp, "Request for data outside of extension header");
100 return -1;
103 ret = bdrv_pread(bs->file,
104 s->crypto_header.offset + offset, buf, buflen);
105 if (ret < 0) {
106 error_setg_errno(errp, -ret, "Could not read encryption header");
107 return -1;
109 return ret;
113 static ssize_t qcow2_crypto_hdr_init_func(QCryptoBlock *block, size_t headerlen,
114 void *opaque, Error **errp)
116 BlockDriverState *bs = opaque;
117 BDRVQcow2State *s = bs->opaque;
118 int64_t ret;
119 int64_t clusterlen;
121 ret = qcow2_alloc_clusters(bs, headerlen);
122 if (ret < 0) {
123 error_setg_errno(errp, -ret,
124 "Cannot allocate cluster for LUKS header size %zu",
125 headerlen);
126 return -1;
129 s->crypto_header.length = headerlen;
130 s->crypto_header.offset = ret;
132 /* Zero fill remaining space in cluster so it has predictable
133 * content in case of future spec changes */
134 clusterlen = size_to_clusters(s, headerlen) * s->cluster_size;
135 assert(qcow2_pre_write_overlap_check(bs, 0, ret, clusterlen) == 0);
136 ret = bdrv_pwrite_zeroes(bs->file,
137 ret + headerlen,
138 clusterlen - headerlen, 0);
139 if (ret < 0) {
140 error_setg_errno(errp, -ret, "Could not zero fill encryption header");
141 return -1;
144 return ret;
148 static ssize_t qcow2_crypto_hdr_write_func(QCryptoBlock *block, size_t offset,
149 const uint8_t *buf, size_t buflen,
150 void *opaque, Error **errp)
152 BlockDriverState *bs = opaque;
153 BDRVQcow2State *s = bs->opaque;
154 ssize_t ret;
156 if ((offset + buflen) > s->crypto_header.length) {
157 error_setg(errp, "Request for data outside of extension header");
158 return -1;
161 ret = bdrv_pwrite(bs->file,
162 s->crypto_header.offset + offset, buf, buflen);
163 if (ret < 0) {
164 error_setg_errno(errp, -ret, "Could not read encryption header");
165 return -1;
167 return ret;
172 * read qcow2 extension and fill bs
173 * start reading from start_offset
174 * finish reading upon magic of value 0 or when end_offset reached
175 * unknown magic is skipped (future extension this version knows nothing about)
176 * return 0 upon success, non-0 otherwise
178 static int qcow2_read_extensions(BlockDriverState *bs, uint64_t start_offset,
179 uint64_t end_offset, void **p_feature_table,
180 int flags, bool *need_update_header,
181 Error **errp)
183 BDRVQcow2State *s = bs->opaque;
184 QCowExtension ext;
185 uint64_t offset;
186 int ret;
187 Qcow2BitmapHeaderExt bitmaps_ext;
189 if (need_update_header != NULL) {
190 *need_update_header = false;
193 #ifdef DEBUG_EXT
194 printf("qcow2_read_extensions: start=%ld end=%ld\n", start_offset, end_offset);
195 #endif
196 offset = start_offset;
197 while (offset < end_offset) {
199 #ifdef DEBUG_EXT
200 /* Sanity check */
201 if (offset > s->cluster_size)
202 printf("qcow2_read_extension: suspicious offset %lu\n", offset);
204 printf("attempting to read extended header in offset %lu\n", offset);
205 #endif
207 ret = bdrv_pread(bs->file, offset, &ext, sizeof(ext));
208 if (ret < 0) {
209 error_setg_errno(errp, -ret, "qcow2_read_extension: ERROR: "
210 "pread fail from offset %" PRIu64, offset);
211 return 1;
213 ext.magic = be32_to_cpu(ext.magic);
214 ext.len = be32_to_cpu(ext.len);
215 offset += sizeof(ext);
216 #ifdef DEBUG_EXT
217 printf("ext.magic = 0x%x\n", ext.magic);
218 #endif
219 if (offset > end_offset || ext.len > end_offset - offset) {
220 error_setg(errp, "Header extension too large");
221 return -EINVAL;
224 switch (ext.magic) {
225 case QCOW2_EXT_MAGIC_END:
226 return 0;
228 case QCOW2_EXT_MAGIC_BACKING_FORMAT:
229 if (ext.len >= sizeof(bs->backing_format)) {
230 error_setg(errp, "ERROR: ext_backing_format: len=%" PRIu32
231 " too large (>=%zu)", ext.len,
232 sizeof(bs->backing_format));
233 return 2;
235 ret = bdrv_pread(bs->file, offset, bs->backing_format, ext.len);
236 if (ret < 0) {
237 error_setg_errno(errp, -ret, "ERROR: ext_backing_format: "
238 "Could not read format name");
239 return 3;
241 bs->backing_format[ext.len] = '\0';
242 s->image_backing_format = g_strdup(bs->backing_format);
243 #ifdef DEBUG_EXT
244 printf("Qcow2: Got format extension %s\n", bs->backing_format);
245 #endif
246 break;
248 case QCOW2_EXT_MAGIC_FEATURE_TABLE:
249 if (p_feature_table != NULL) {
250 void* feature_table = g_malloc0(ext.len + 2 * sizeof(Qcow2Feature));
251 ret = bdrv_pread(bs->file, offset , feature_table, ext.len);
252 if (ret < 0) {
253 error_setg_errno(errp, -ret, "ERROR: ext_feature_table: "
254 "Could not read table");
255 return ret;
258 *p_feature_table = feature_table;
260 break;
262 case QCOW2_EXT_MAGIC_CRYPTO_HEADER: {
263 unsigned int cflags = 0;
264 if (s->crypt_method_header != QCOW_CRYPT_LUKS) {
265 error_setg(errp, "CRYPTO header extension only "
266 "expected with LUKS encryption method");
267 return -EINVAL;
269 if (ext.len != sizeof(Qcow2CryptoHeaderExtension)) {
270 error_setg(errp, "CRYPTO header extension size %u, "
271 "but expected size %zu", ext.len,
272 sizeof(Qcow2CryptoHeaderExtension));
273 return -EINVAL;
276 ret = bdrv_pread(bs->file, offset, &s->crypto_header, ext.len);
277 if (ret < 0) {
278 error_setg_errno(errp, -ret,
279 "Unable to read CRYPTO header extension");
280 return ret;
282 s->crypto_header.offset = be64_to_cpu(s->crypto_header.offset);
283 s->crypto_header.length = be64_to_cpu(s->crypto_header.length);
285 if ((s->crypto_header.offset % s->cluster_size) != 0) {
286 error_setg(errp, "Encryption header offset '%" PRIu64 "' is "
287 "not a multiple of cluster size '%u'",
288 s->crypto_header.offset, s->cluster_size);
289 return -EINVAL;
292 if (flags & BDRV_O_NO_IO) {
293 cflags |= QCRYPTO_BLOCK_OPEN_NO_IO;
295 s->crypto = qcrypto_block_open(s->crypto_opts, "encrypt.",
296 qcow2_crypto_hdr_read_func,
297 bs, cflags, errp);
298 if (!s->crypto) {
299 return -EINVAL;
301 } break;
303 case QCOW2_EXT_MAGIC_BITMAPS:
304 if (ext.len != sizeof(bitmaps_ext)) {
305 error_setg_errno(errp, -ret, "bitmaps_ext: "
306 "Invalid extension length");
307 return -EINVAL;
310 if (!(s->autoclear_features & QCOW2_AUTOCLEAR_BITMAPS)) {
311 if (s->qcow_version < 3) {
312 /* Let's be a bit more specific */
313 warn_report("This qcow2 v2 image contains bitmaps, but "
314 "they may have been modified by a program "
315 "without persistent bitmap support; so now "
316 "they must all be considered inconsistent");
317 } else {
318 warn_report("a program lacking bitmap support "
319 "modified this file, so all bitmaps are now "
320 "considered inconsistent");
322 error_printf("Some clusters may be leaked, "
323 "run 'qemu-img check -r' on the image "
324 "file to fix.");
325 if (need_update_header != NULL) {
326 /* Updating is needed to drop invalid bitmap extension. */
327 *need_update_header = true;
329 break;
332 ret = bdrv_pread(bs->file, offset, &bitmaps_ext, ext.len);
333 if (ret < 0) {
334 error_setg_errno(errp, -ret, "bitmaps_ext: "
335 "Could not read ext header");
336 return ret;
339 if (bitmaps_ext.reserved32 != 0) {
340 error_setg_errno(errp, -ret, "bitmaps_ext: "
341 "Reserved field is not zero");
342 return -EINVAL;
345 bitmaps_ext.nb_bitmaps = be32_to_cpu(bitmaps_ext.nb_bitmaps);
346 bitmaps_ext.bitmap_directory_size =
347 be64_to_cpu(bitmaps_ext.bitmap_directory_size);
348 bitmaps_ext.bitmap_directory_offset =
349 be64_to_cpu(bitmaps_ext.bitmap_directory_offset);
351 if (bitmaps_ext.nb_bitmaps > QCOW2_MAX_BITMAPS) {
352 error_setg(errp,
353 "bitmaps_ext: Image has %" PRIu32 " bitmaps, "
354 "exceeding the QEMU supported maximum of %d",
355 bitmaps_ext.nb_bitmaps, QCOW2_MAX_BITMAPS);
356 return -EINVAL;
359 if (bitmaps_ext.nb_bitmaps == 0) {
360 error_setg(errp, "found bitmaps extension with zero bitmaps");
361 return -EINVAL;
364 if (bitmaps_ext.bitmap_directory_offset & (s->cluster_size - 1)) {
365 error_setg(errp, "bitmaps_ext: "
366 "invalid bitmap directory offset");
367 return -EINVAL;
370 if (bitmaps_ext.bitmap_directory_size >
371 QCOW2_MAX_BITMAP_DIRECTORY_SIZE) {
372 error_setg(errp, "bitmaps_ext: "
373 "bitmap directory size (%" PRIu64 ") exceeds "
374 "the maximum supported size (%d)",
375 bitmaps_ext.bitmap_directory_size,
376 QCOW2_MAX_BITMAP_DIRECTORY_SIZE);
377 return -EINVAL;
380 s->nb_bitmaps = bitmaps_ext.nb_bitmaps;
381 s->bitmap_directory_offset =
382 bitmaps_ext.bitmap_directory_offset;
383 s->bitmap_directory_size =
384 bitmaps_ext.bitmap_directory_size;
386 #ifdef DEBUG_EXT
387 printf("Qcow2: Got bitmaps extension: "
388 "offset=%" PRIu64 " nb_bitmaps=%" PRIu32 "\n",
389 s->bitmap_directory_offset, s->nb_bitmaps);
390 #endif
391 break;
393 default:
394 /* unknown magic - save it in case we need to rewrite the header */
395 /* If you add a new feature, make sure to also update the fast
396 * path of qcow2_make_empty() to deal with it. */
398 Qcow2UnknownHeaderExtension *uext;
400 uext = g_malloc0(sizeof(*uext) + ext.len);
401 uext->magic = ext.magic;
402 uext->len = ext.len;
403 QLIST_INSERT_HEAD(&s->unknown_header_ext, uext, next);
405 ret = bdrv_pread(bs->file, offset , uext->data, uext->len);
406 if (ret < 0) {
407 error_setg_errno(errp, -ret, "ERROR: unknown extension: "
408 "Could not read data");
409 return ret;
412 break;
415 offset += ((ext.len + 7) & ~7);
418 return 0;
421 static void cleanup_unknown_header_ext(BlockDriverState *bs)
423 BDRVQcow2State *s = bs->opaque;
424 Qcow2UnknownHeaderExtension *uext, *next;
426 QLIST_FOREACH_SAFE(uext, &s->unknown_header_ext, next, next) {
427 QLIST_REMOVE(uext, next);
428 g_free(uext);
432 static void report_unsupported_feature(Error **errp, Qcow2Feature *table,
433 uint64_t mask)
435 char *features = g_strdup("");
436 char *old;
438 while (table && table->name[0] != '\0') {
439 if (table->type == QCOW2_FEAT_TYPE_INCOMPATIBLE) {
440 if (mask & (1ULL << table->bit)) {
441 old = features;
442 features = g_strdup_printf("%s%s%.46s", old, *old ? ", " : "",
443 table->name);
444 g_free(old);
445 mask &= ~(1ULL << table->bit);
448 table++;
451 if (mask) {
452 old = features;
453 features = g_strdup_printf("%s%sUnknown incompatible feature: %" PRIx64,
454 old, *old ? ", " : "", mask);
455 g_free(old);
458 error_setg(errp, "Unsupported qcow2 feature(s): %s", features);
459 g_free(features);
463 * Sets the dirty bit and flushes afterwards if necessary.
465 * The incompatible_features bit is only set if the image file header was
466 * updated successfully. Therefore it is not required to check the return
467 * value of this function.
469 int qcow2_mark_dirty(BlockDriverState *bs)
471 BDRVQcow2State *s = bs->opaque;
472 uint64_t val;
473 int ret;
475 assert(s->qcow_version >= 3);
477 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
478 return 0; /* already dirty */
481 val = cpu_to_be64(s->incompatible_features | QCOW2_INCOMPAT_DIRTY);
482 ret = bdrv_pwrite(bs->file, offsetof(QCowHeader, incompatible_features),
483 &val, sizeof(val));
484 if (ret < 0) {
485 return ret;
487 ret = bdrv_flush(bs->file->bs);
488 if (ret < 0) {
489 return ret;
492 /* Only treat image as dirty if the header was updated successfully */
493 s->incompatible_features |= QCOW2_INCOMPAT_DIRTY;
494 return 0;
498 * Clears the dirty bit and flushes before if necessary. Only call this
499 * function when there are no pending requests, it does not guard against
500 * concurrent requests dirtying the image.
502 static int qcow2_mark_clean(BlockDriverState *bs)
504 BDRVQcow2State *s = bs->opaque;
506 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
507 int ret;
509 s->incompatible_features &= ~QCOW2_INCOMPAT_DIRTY;
511 ret = qcow2_flush_caches(bs);
512 if (ret < 0) {
513 return ret;
516 return qcow2_update_header(bs);
518 return 0;
522 * Marks the image as corrupt.
524 int qcow2_mark_corrupt(BlockDriverState *bs)
526 BDRVQcow2State *s = bs->opaque;
528 s->incompatible_features |= QCOW2_INCOMPAT_CORRUPT;
529 return qcow2_update_header(bs);
533 * Marks the image as consistent, i.e., unsets the corrupt bit, and flushes
534 * before if necessary.
536 int qcow2_mark_consistent(BlockDriverState *bs)
538 BDRVQcow2State *s = bs->opaque;
540 if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
541 int ret = qcow2_flush_caches(bs);
542 if (ret < 0) {
543 return ret;
546 s->incompatible_features &= ~QCOW2_INCOMPAT_CORRUPT;
547 return qcow2_update_header(bs);
549 return 0;
552 static int coroutine_fn qcow2_co_check_locked(BlockDriverState *bs,
553 BdrvCheckResult *result,
554 BdrvCheckMode fix)
556 int ret = qcow2_check_refcounts(bs, result, fix);
557 if (ret < 0) {
558 return ret;
561 if (fix && result->check_errors == 0 && result->corruptions == 0) {
562 ret = qcow2_mark_clean(bs);
563 if (ret < 0) {
564 return ret;
566 return qcow2_mark_consistent(bs);
568 return ret;
571 static int coroutine_fn qcow2_co_check(BlockDriverState *bs,
572 BdrvCheckResult *result,
573 BdrvCheckMode fix)
575 BDRVQcow2State *s = bs->opaque;
576 int ret;
578 qemu_co_mutex_lock(&s->lock);
579 ret = qcow2_co_check_locked(bs, result, fix);
580 qemu_co_mutex_unlock(&s->lock);
581 return ret;
584 int qcow2_validate_table(BlockDriverState *bs, uint64_t offset,
585 uint64_t entries, size_t entry_len,
586 int64_t max_size_bytes, const char *table_name,
587 Error **errp)
589 BDRVQcow2State *s = bs->opaque;
591 if (entries > max_size_bytes / entry_len) {
592 error_setg(errp, "%s too large", table_name);
593 return -EFBIG;
596 /* Use signed INT64_MAX as the maximum even for uint64_t header fields,
597 * because values will be passed to qemu functions taking int64_t. */
598 if ((INT64_MAX - entries * entry_len < offset) ||
599 (offset_into_cluster(s, offset) != 0)) {
600 error_setg(errp, "%s offset invalid", table_name);
601 return -EINVAL;
604 return 0;
607 static QemuOptsList qcow2_runtime_opts = {
608 .name = "qcow2",
609 .head = QTAILQ_HEAD_INITIALIZER(qcow2_runtime_opts.head),
610 .desc = {
612 .name = QCOW2_OPT_LAZY_REFCOUNTS,
613 .type = QEMU_OPT_BOOL,
614 .help = "Postpone refcount updates",
617 .name = QCOW2_OPT_DISCARD_REQUEST,
618 .type = QEMU_OPT_BOOL,
619 .help = "Pass guest discard requests to the layer below",
622 .name = QCOW2_OPT_DISCARD_SNAPSHOT,
623 .type = QEMU_OPT_BOOL,
624 .help = "Generate discard requests when snapshot related space "
625 "is freed",
628 .name = QCOW2_OPT_DISCARD_OTHER,
629 .type = QEMU_OPT_BOOL,
630 .help = "Generate discard requests when other clusters are freed",
633 .name = QCOW2_OPT_OVERLAP,
634 .type = QEMU_OPT_STRING,
635 .help = "Selects which overlap checks to perform from a range of "
636 "templates (none, constant, cached, all)",
639 .name = QCOW2_OPT_OVERLAP_TEMPLATE,
640 .type = QEMU_OPT_STRING,
641 .help = "Selects which overlap checks to perform from a range of "
642 "templates (none, constant, cached, all)",
645 .name = QCOW2_OPT_OVERLAP_MAIN_HEADER,
646 .type = QEMU_OPT_BOOL,
647 .help = "Check for unintended writes into the main qcow2 header",
650 .name = QCOW2_OPT_OVERLAP_ACTIVE_L1,
651 .type = QEMU_OPT_BOOL,
652 .help = "Check for unintended writes into the active L1 table",
655 .name = QCOW2_OPT_OVERLAP_ACTIVE_L2,
656 .type = QEMU_OPT_BOOL,
657 .help = "Check for unintended writes into an active L2 table",
660 .name = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
661 .type = QEMU_OPT_BOOL,
662 .help = "Check for unintended writes into the refcount table",
665 .name = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
666 .type = QEMU_OPT_BOOL,
667 .help = "Check for unintended writes into a refcount block",
670 .name = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
671 .type = QEMU_OPT_BOOL,
672 .help = "Check for unintended writes into the snapshot table",
675 .name = QCOW2_OPT_OVERLAP_INACTIVE_L1,
676 .type = QEMU_OPT_BOOL,
677 .help = "Check for unintended writes into an inactive L1 table",
680 .name = QCOW2_OPT_OVERLAP_INACTIVE_L2,
681 .type = QEMU_OPT_BOOL,
682 .help = "Check for unintended writes into an inactive L2 table",
685 .name = QCOW2_OPT_OVERLAP_BITMAP_DIRECTORY,
686 .type = QEMU_OPT_BOOL,
687 .help = "Check for unintended writes into the bitmap directory",
690 .name = QCOW2_OPT_CACHE_SIZE,
691 .type = QEMU_OPT_SIZE,
692 .help = "Maximum combined metadata (L2 tables and refcount blocks) "
693 "cache size",
696 .name = QCOW2_OPT_L2_CACHE_SIZE,
697 .type = QEMU_OPT_SIZE,
698 .help = "Maximum L2 table cache size",
701 .name = QCOW2_OPT_L2_CACHE_ENTRY_SIZE,
702 .type = QEMU_OPT_SIZE,
703 .help = "Size of each entry in the L2 cache",
706 .name = QCOW2_OPT_REFCOUNT_CACHE_SIZE,
707 .type = QEMU_OPT_SIZE,
708 .help = "Maximum refcount block cache size",
711 .name = QCOW2_OPT_CACHE_CLEAN_INTERVAL,
712 .type = QEMU_OPT_NUMBER,
713 .help = "Clean unused cache entries after this time (in seconds)",
715 BLOCK_CRYPTO_OPT_DEF_KEY_SECRET("encrypt.",
716 "ID of secret providing qcow2 AES key or LUKS passphrase"),
717 { /* end of list */ }
721 static const char *overlap_bool_option_names[QCOW2_OL_MAX_BITNR] = {
722 [QCOW2_OL_MAIN_HEADER_BITNR] = QCOW2_OPT_OVERLAP_MAIN_HEADER,
723 [QCOW2_OL_ACTIVE_L1_BITNR] = QCOW2_OPT_OVERLAP_ACTIVE_L1,
724 [QCOW2_OL_ACTIVE_L2_BITNR] = QCOW2_OPT_OVERLAP_ACTIVE_L2,
725 [QCOW2_OL_REFCOUNT_TABLE_BITNR] = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
726 [QCOW2_OL_REFCOUNT_BLOCK_BITNR] = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
727 [QCOW2_OL_SNAPSHOT_TABLE_BITNR] = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
728 [QCOW2_OL_INACTIVE_L1_BITNR] = QCOW2_OPT_OVERLAP_INACTIVE_L1,
729 [QCOW2_OL_INACTIVE_L2_BITNR] = QCOW2_OPT_OVERLAP_INACTIVE_L2,
730 [QCOW2_OL_BITMAP_DIRECTORY_BITNR] = QCOW2_OPT_OVERLAP_BITMAP_DIRECTORY,
733 static void cache_clean_timer_cb(void *opaque)
735 BlockDriverState *bs = opaque;
736 BDRVQcow2State *s = bs->opaque;
737 qcow2_cache_clean_unused(s->l2_table_cache);
738 qcow2_cache_clean_unused(s->refcount_block_cache);
739 timer_mod(s->cache_clean_timer, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) +
740 (int64_t) s->cache_clean_interval * 1000);
743 static void cache_clean_timer_init(BlockDriverState *bs, AioContext *context)
745 BDRVQcow2State *s = bs->opaque;
746 if (s->cache_clean_interval > 0) {
747 s->cache_clean_timer = aio_timer_new(context, QEMU_CLOCK_VIRTUAL,
748 SCALE_MS, cache_clean_timer_cb,
749 bs);
750 timer_mod(s->cache_clean_timer, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) +
751 (int64_t) s->cache_clean_interval * 1000);
755 static void cache_clean_timer_del(BlockDriverState *bs)
757 BDRVQcow2State *s = bs->opaque;
758 if (s->cache_clean_timer) {
759 timer_del(s->cache_clean_timer);
760 timer_free(s->cache_clean_timer);
761 s->cache_clean_timer = NULL;
765 static void qcow2_detach_aio_context(BlockDriverState *bs)
767 cache_clean_timer_del(bs);
770 static void qcow2_attach_aio_context(BlockDriverState *bs,
771 AioContext *new_context)
773 cache_clean_timer_init(bs, new_context);
776 static void read_cache_sizes(BlockDriverState *bs, QemuOpts *opts,
777 uint64_t *l2_cache_size,
778 uint64_t *l2_cache_entry_size,
779 uint64_t *refcount_cache_size, Error **errp)
781 BDRVQcow2State *s = bs->opaque;
782 uint64_t combined_cache_size, l2_cache_max_setting;
783 bool l2_cache_size_set, refcount_cache_size_set, combined_cache_size_set;
784 int min_refcount_cache = MIN_REFCOUNT_CACHE_SIZE * s->cluster_size;
785 uint64_t virtual_disk_size = bs->total_sectors * BDRV_SECTOR_SIZE;
786 uint64_t max_l2_cache = virtual_disk_size / (s->cluster_size / 8);
788 combined_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_CACHE_SIZE);
789 l2_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_L2_CACHE_SIZE);
790 refcount_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
792 combined_cache_size = qemu_opt_get_size(opts, QCOW2_OPT_CACHE_SIZE, 0);
793 l2_cache_max_setting = qemu_opt_get_size(opts, QCOW2_OPT_L2_CACHE_SIZE,
794 DEFAULT_L2_CACHE_MAX_SIZE);
795 *refcount_cache_size = qemu_opt_get_size(opts,
796 QCOW2_OPT_REFCOUNT_CACHE_SIZE, 0);
798 *l2_cache_entry_size = qemu_opt_get_size(
799 opts, QCOW2_OPT_L2_CACHE_ENTRY_SIZE, s->cluster_size);
801 *l2_cache_size = MIN(max_l2_cache, l2_cache_max_setting);
803 if (combined_cache_size_set) {
804 if (l2_cache_size_set && refcount_cache_size_set) {
805 error_setg(errp, QCOW2_OPT_CACHE_SIZE ", " QCOW2_OPT_L2_CACHE_SIZE
806 " and " QCOW2_OPT_REFCOUNT_CACHE_SIZE " may not be set "
807 "at the same time");
808 return;
809 } else if (l2_cache_size_set &&
810 (l2_cache_max_setting > combined_cache_size)) {
811 error_setg(errp, QCOW2_OPT_L2_CACHE_SIZE " may not exceed "
812 QCOW2_OPT_CACHE_SIZE);
813 return;
814 } else if (*refcount_cache_size > combined_cache_size) {
815 error_setg(errp, QCOW2_OPT_REFCOUNT_CACHE_SIZE " may not exceed "
816 QCOW2_OPT_CACHE_SIZE);
817 return;
820 if (l2_cache_size_set) {
821 *refcount_cache_size = combined_cache_size - *l2_cache_size;
822 } else if (refcount_cache_size_set) {
823 *l2_cache_size = combined_cache_size - *refcount_cache_size;
824 } else {
825 /* Assign as much memory as possible to the L2 cache, and
826 * use the remainder for the refcount cache */
827 if (combined_cache_size >= max_l2_cache + min_refcount_cache) {
828 *l2_cache_size = max_l2_cache;
829 *refcount_cache_size = combined_cache_size - *l2_cache_size;
830 } else {
831 *refcount_cache_size =
832 MIN(combined_cache_size, min_refcount_cache);
833 *l2_cache_size = combined_cache_size - *refcount_cache_size;
837 /* l2_cache_size and refcount_cache_size are ensured to have at least
838 * their minimum values in qcow2_update_options_prepare() */
840 if (*l2_cache_entry_size < (1 << MIN_CLUSTER_BITS) ||
841 *l2_cache_entry_size > s->cluster_size ||
842 !is_power_of_2(*l2_cache_entry_size)) {
843 error_setg(errp, "L2 cache entry size must be a power of two "
844 "between %d and the cluster size (%d)",
845 1 << MIN_CLUSTER_BITS, s->cluster_size);
846 return;
850 typedef struct Qcow2ReopenState {
851 Qcow2Cache *l2_table_cache;
852 Qcow2Cache *refcount_block_cache;
853 int l2_slice_size; /* Number of entries in a slice of the L2 table */
854 bool use_lazy_refcounts;
855 int overlap_check;
856 bool discard_passthrough[QCOW2_DISCARD_MAX];
857 uint64_t cache_clean_interval;
858 QCryptoBlockOpenOptions *crypto_opts; /* Disk encryption runtime options */
859 } Qcow2ReopenState;
861 static int qcow2_update_options_prepare(BlockDriverState *bs,
862 Qcow2ReopenState *r,
863 QDict *options, int flags,
864 Error **errp)
866 BDRVQcow2State *s = bs->opaque;
867 QemuOpts *opts = NULL;
868 const char *opt_overlap_check, *opt_overlap_check_template;
869 int overlap_check_template = 0;
870 uint64_t l2_cache_size, l2_cache_entry_size, refcount_cache_size;
871 int i;
872 const char *encryptfmt;
873 QDict *encryptopts = NULL;
874 Error *local_err = NULL;
875 int ret;
877 qdict_extract_subqdict(options, &encryptopts, "encrypt.");
878 encryptfmt = qdict_get_try_str(encryptopts, "format");
880 opts = qemu_opts_create(&qcow2_runtime_opts, NULL, 0, &error_abort);
881 qemu_opts_absorb_qdict(opts, options, &local_err);
882 if (local_err) {
883 error_propagate(errp, local_err);
884 ret = -EINVAL;
885 goto fail;
888 /* get L2 table/refcount block cache size from command line options */
889 read_cache_sizes(bs, opts, &l2_cache_size, &l2_cache_entry_size,
890 &refcount_cache_size, &local_err);
891 if (local_err) {
892 error_propagate(errp, local_err);
893 ret = -EINVAL;
894 goto fail;
897 l2_cache_size /= l2_cache_entry_size;
898 if (l2_cache_size < MIN_L2_CACHE_SIZE) {
899 l2_cache_size = MIN_L2_CACHE_SIZE;
901 if (l2_cache_size > INT_MAX) {
902 error_setg(errp, "L2 cache size too big");
903 ret = -EINVAL;
904 goto fail;
907 refcount_cache_size /= s->cluster_size;
908 if (refcount_cache_size < MIN_REFCOUNT_CACHE_SIZE) {
909 refcount_cache_size = MIN_REFCOUNT_CACHE_SIZE;
911 if (refcount_cache_size > INT_MAX) {
912 error_setg(errp, "Refcount cache size too big");
913 ret = -EINVAL;
914 goto fail;
917 /* alloc new L2 table/refcount block cache, flush old one */
918 if (s->l2_table_cache) {
919 ret = qcow2_cache_flush(bs, s->l2_table_cache);
920 if (ret) {
921 error_setg_errno(errp, -ret, "Failed to flush the L2 table cache");
922 goto fail;
926 if (s->refcount_block_cache) {
927 ret = qcow2_cache_flush(bs, s->refcount_block_cache);
928 if (ret) {
929 error_setg_errno(errp, -ret,
930 "Failed to flush the refcount block cache");
931 goto fail;
935 r->l2_slice_size = l2_cache_entry_size / sizeof(uint64_t);
936 r->l2_table_cache = qcow2_cache_create(bs, l2_cache_size,
937 l2_cache_entry_size);
938 r->refcount_block_cache = qcow2_cache_create(bs, refcount_cache_size,
939 s->cluster_size);
940 if (r->l2_table_cache == NULL || r->refcount_block_cache == NULL) {
941 error_setg(errp, "Could not allocate metadata caches");
942 ret = -ENOMEM;
943 goto fail;
946 /* New interval for cache cleanup timer */
947 r->cache_clean_interval =
948 qemu_opt_get_number(opts, QCOW2_OPT_CACHE_CLEAN_INTERVAL,
949 DEFAULT_CACHE_CLEAN_INTERVAL);
950 #ifndef CONFIG_LINUX
951 if (r->cache_clean_interval != 0) {
952 error_setg(errp, QCOW2_OPT_CACHE_CLEAN_INTERVAL
953 " not supported on this host");
954 ret = -EINVAL;
955 goto fail;
957 #endif
958 if (r->cache_clean_interval > UINT_MAX) {
959 error_setg(errp, "Cache clean interval too big");
960 ret = -EINVAL;
961 goto fail;
964 /* lazy-refcounts; flush if going from enabled to disabled */
965 r->use_lazy_refcounts = qemu_opt_get_bool(opts, QCOW2_OPT_LAZY_REFCOUNTS,
966 (s->compatible_features & QCOW2_COMPAT_LAZY_REFCOUNTS));
967 if (r->use_lazy_refcounts && s->qcow_version < 3) {
968 error_setg(errp, "Lazy refcounts require a qcow2 image with at least "
969 "qemu 1.1 compatibility level");
970 ret = -EINVAL;
971 goto fail;
974 if (s->use_lazy_refcounts && !r->use_lazy_refcounts) {
975 ret = qcow2_mark_clean(bs);
976 if (ret < 0) {
977 error_setg_errno(errp, -ret, "Failed to disable lazy refcounts");
978 goto fail;
982 /* Overlap check options */
983 opt_overlap_check = qemu_opt_get(opts, QCOW2_OPT_OVERLAP);
984 opt_overlap_check_template = qemu_opt_get(opts, QCOW2_OPT_OVERLAP_TEMPLATE);
985 if (opt_overlap_check_template && opt_overlap_check &&
986 strcmp(opt_overlap_check_template, opt_overlap_check))
988 error_setg(errp, "Conflicting values for qcow2 options '"
989 QCOW2_OPT_OVERLAP "' ('%s') and '" QCOW2_OPT_OVERLAP_TEMPLATE
990 "' ('%s')", opt_overlap_check, opt_overlap_check_template);
991 ret = -EINVAL;
992 goto fail;
994 if (!opt_overlap_check) {
995 opt_overlap_check = opt_overlap_check_template ?: "cached";
998 if (!strcmp(opt_overlap_check, "none")) {
999 overlap_check_template = 0;
1000 } else if (!strcmp(opt_overlap_check, "constant")) {
1001 overlap_check_template = QCOW2_OL_CONSTANT;
1002 } else if (!strcmp(opt_overlap_check, "cached")) {
1003 overlap_check_template = QCOW2_OL_CACHED;
1004 } else if (!strcmp(opt_overlap_check, "all")) {
1005 overlap_check_template = QCOW2_OL_ALL;
1006 } else {
1007 error_setg(errp, "Unsupported value '%s' for qcow2 option "
1008 "'overlap-check'. Allowed are any of the following: "
1009 "none, constant, cached, all", opt_overlap_check);
1010 ret = -EINVAL;
1011 goto fail;
1014 r->overlap_check = 0;
1015 for (i = 0; i < QCOW2_OL_MAX_BITNR; i++) {
1016 /* overlap-check defines a template bitmask, but every flag may be
1017 * overwritten through the associated boolean option */
1018 r->overlap_check |=
1019 qemu_opt_get_bool(opts, overlap_bool_option_names[i],
1020 overlap_check_template & (1 << i)) << i;
1023 r->discard_passthrough[QCOW2_DISCARD_NEVER] = false;
1024 r->discard_passthrough[QCOW2_DISCARD_ALWAYS] = true;
1025 r->discard_passthrough[QCOW2_DISCARD_REQUEST] =
1026 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_REQUEST,
1027 flags & BDRV_O_UNMAP);
1028 r->discard_passthrough[QCOW2_DISCARD_SNAPSHOT] =
1029 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_SNAPSHOT, true);
1030 r->discard_passthrough[QCOW2_DISCARD_OTHER] =
1031 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_OTHER, false);
1033 switch (s->crypt_method_header) {
1034 case QCOW_CRYPT_NONE:
1035 if (encryptfmt) {
1036 error_setg(errp, "No encryption in image header, but options "
1037 "specified format '%s'", encryptfmt);
1038 ret = -EINVAL;
1039 goto fail;
1041 break;
1043 case QCOW_CRYPT_AES:
1044 if (encryptfmt && !g_str_equal(encryptfmt, "aes")) {
1045 error_setg(errp,
1046 "Header reported 'aes' encryption format but "
1047 "options specify '%s'", encryptfmt);
1048 ret = -EINVAL;
1049 goto fail;
1051 qdict_put_str(encryptopts, "format", "qcow");
1052 r->crypto_opts = block_crypto_open_opts_init(encryptopts, errp);
1053 break;
1055 case QCOW_CRYPT_LUKS:
1056 if (encryptfmt && !g_str_equal(encryptfmt, "luks")) {
1057 error_setg(errp,
1058 "Header reported 'luks' encryption format but "
1059 "options specify '%s'", encryptfmt);
1060 ret = -EINVAL;
1061 goto fail;
1063 qdict_put_str(encryptopts, "format", "luks");
1064 r->crypto_opts = block_crypto_open_opts_init(encryptopts, errp);
1065 break;
1067 default:
1068 error_setg(errp, "Unsupported encryption method %d",
1069 s->crypt_method_header);
1070 break;
1072 if (s->crypt_method_header != QCOW_CRYPT_NONE && !r->crypto_opts) {
1073 ret = -EINVAL;
1074 goto fail;
1077 ret = 0;
1078 fail:
1079 qobject_unref(encryptopts);
1080 qemu_opts_del(opts);
1081 opts = NULL;
1082 return ret;
1085 static void qcow2_update_options_commit(BlockDriverState *bs,
1086 Qcow2ReopenState *r)
1088 BDRVQcow2State *s = bs->opaque;
1089 int i;
1091 if (s->l2_table_cache) {
1092 qcow2_cache_destroy(s->l2_table_cache);
1094 if (s->refcount_block_cache) {
1095 qcow2_cache_destroy(s->refcount_block_cache);
1097 s->l2_table_cache = r->l2_table_cache;
1098 s->refcount_block_cache = r->refcount_block_cache;
1099 s->l2_slice_size = r->l2_slice_size;
1101 s->overlap_check = r->overlap_check;
1102 s->use_lazy_refcounts = r->use_lazy_refcounts;
1104 for (i = 0; i < QCOW2_DISCARD_MAX; i++) {
1105 s->discard_passthrough[i] = r->discard_passthrough[i];
1108 if (s->cache_clean_interval != r->cache_clean_interval) {
1109 cache_clean_timer_del(bs);
1110 s->cache_clean_interval = r->cache_clean_interval;
1111 cache_clean_timer_init(bs, bdrv_get_aio_context(bs));
1114 qapi_free_QCryptoBlockOpenOptions(s->crypto_opts);
1115 s->crypto_opts = r->crypto_opts;
1118 static void qcow2_update_options_abort(BlockDriverState *bs,
1119 Qcow2ReopenState *r)
1121 if (r->l2_table_cache) {
1122 qcow2_cache_destroy(r->l2_table_cache);
1124 if (r->refcount_block_cache) {
1125 qcow2_cache_destroy(r->refcount_block_cache);
1127 qapi_free_QCryptoBlockOpenOptions(r->crypto_opts);
1130 static int qcow2_update_options(BlockDriverState *bs, QDict *options,
1131 int flags, Error **errp)
1133 Qcow2ReopenState r = {};
1134 int ret;
1136 ret = qcow2_update_options_prepare(bs, &r, options, flags, errp);
1137 if (ret >= 0) {
1138 qcow2_update_options_commit(bs, &r);
1139 } else {
1140 qcow2_update_options_abort(bs, &r);
1143 return ret;
1146 /* Called with s->lock held. */
1147 static int coroutine_fn qcow2_do_open(BlockDriverState *bs, QDict *options,
1148 int flags, Error **errp)
1150 BDRVQcow2State *s = bs->opaque;
1151 unsigned int len, i;
1152 int ret = 0;
1153 QCowHeader header;
1154 Error *local_err = NULL;
1155 uint64_t ext_end;
1156 uint64_t l1_vm_state_index;
1157 bool update_header = false;
1159 ret = bdrv_pread(bs->file, 0, &header, sizeof(header));
1160 if (ret < 0) {
1161 error_setg_errno(errp, -ret, "Could not read qcow2 header");
1162 goto fail;
1164 header.magic = be32_to_cpu(header.magic);
1165 header.version = be32_to_cpu(header.version);
1166 header.backing_file_offset = be64_to_cpu(header.backing_file_offset);
1167 header.backing_file_size = be32_to_cpu(header.backing_file_size);
1168 header.size = be64_to_cpu(header.size);
1169 header.cluster_bits = be32_to_cpu(header.cluster_bits);
1170 header.crypt_method = be32_to_cpu(header.crypt_method);
1171 header.l1_table_offset = be64_to_cpu(header.l1_table_offset);
1172 header.l1_size = be32_to_cpu(header.l1_size);
1173 header.refcount_table_offset = be64_to_cpu(header.refcount_table_offset);
1174 header.refcount_table_clusters =
1175 be32_to_cpu(header.refcount_table_clusters);
1176 header.snapshots_offset = be64_to_cpu(header.snapshots_offset);
1177 header.nb_snapshots = be32_to_cpu(header.nb_snapshots);
1179 if (header.magic != QCOW_MAGIC) {
1180 error_setg(errp, "Image is not in qcow2 format");
1181 ret = -EINVAL;
1182 goto fail;
1184 if (header.version < 2 || header.version > 3) {
1185 error_setg(errp, "Unsupported qcow2 version %" PRIu32, header.version);
1186 ret = -ENOTSUP;
1187 goto fail;
1190 s->qcow_version = header.version;
1192 /* Initialise cluster size */
1193 if (header.cluster_bits < MIN_CLUSTER_BITS ||
1194 header.cluster_bits > MAX_CLUSTER_BITS) {
1195 error_setg(errp, "Unsupported cluster size: 2^%" PRIu32,
1196 header.cluster_bits);
1197 ret = -EINVAL;
1198 goto fail;
1201 s->cluster_bits = header.cluster_bits;
1202 s->cluster_size = 1 << s->cluster_bits;
1203 s->cluster_sectors = 1 << (s->cluster_bits - BDRV_SECTOR_BITS);
1205 /* Initialise version 3 header fields */
1206 if (header.version == 2) {
1207 header.incompatible_features = 0;
1208 header.compatible_features = 0;
1209 header.autoclear_features = 0;
1210 header.refcount_order = 4;
1211 header.header_length = 72;
1212 } else {
1213 header.incompatible_features =
1214 be64_to_cpu(header.incompatible_features);
1215 header.compatible_features = be64_to_cpu(header.compatible_features);
1216 header.autoclear_features = be64_to_cpu(header.autoclear_features);
1217 header.refcount_order = be32_to_cpu(header.refcount_order);
1218 header.header_length = be32_to_cpu(header.header_length);
1220 if (header.header_length < 104) {
1221 error_setg(errp, "qcow2 header too short");
1222 ret = -EINVAL;
1223 goto fail;
1227 if (header.header_length > s->cluster_size) {
1228 error_setg(errp, "qcow2 header exceeds cluster size");
1229 ret = -EINVAL;
1230 goto fail;
1233 if (header.header_length > sizeof(header)) {
1234 s->unknown_header_fields_size = header.header_length - sizeof(header);
1235 s->unknown_header_fields = g_malloc(s->unknown_header_fields_size);
1236 ret = bdrv_pread(bs->file, sizeof(header), s->unknown_header_fields,
1237 s->unknown_header_fields_size);
1238 if (ret < 0) {
1239 error_setg_errno(errp, -ret, "Could not read unknown qcow2 header "
1240 "fields");
1241 goto fail;
1245 if (header.backing_file_offset > s->cluster_size) {
1246 error_setg(errp, "Invalid backing file offset");
1247 ret = -EINVAL;
1248 goto fail;
1251 if (header.backing_file_offset) {
1252 ext_end = header.backing_file_offset;
1253 } else {
1254 ext_end = 1 << header.cluster_bits;
1257 /* Handle feature bits */
1258 s->incompatible_features = header.incompatible_features;
1259 s->compatible_features = header.compatible_features;
1260 s->autoclear_features = header.autoclear_features;
1262 if (s->incompatible_features & ~QCOW2_INCOMPAT_MASK) {
1263 void *feature_table = NULL;
1264 qcow2_read_extensions(bs, header.header_length, ext_end,
1265 &feature_table, flags, NULL, NULL);
1266 report_unsupported_feature(errp, feature_table,
1267 s->incompatible_features &
1268 ~QCOW2_INCOMPAT_MASK);
1269 ret = -ENOTSUP;
1270 g_free(feature_table);
1271 goto fail;
1274 if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
1275 /* Corrupt images may not be written to unless they are being repaired
1277 if ((flags & BDRV_O_RDWR) && !(flags & BDRV_O_CHECK)) {
1278 error_setg(errp, "qcow2: Image is corrupt; cannot be opened "
1279 "read/write");
1280 ret = -EACCES;
1281 goto fail;
1285 /* Check support for various header values */
1286 if (header.refcount_order > 6) {
1287 error_setg(errp, "Reference count entry width too large; may not "
1288 "exceed 64 bits");
1289 ret = -EINVAL;
1290 goto fail;
1292 s->refcount_order = header.refcount_order;
1293 s->refcount_bits = 1 << s->refcount_order;
1294 s->refcount_max = UINT64_C(1) << (s->refcount_bits - 1);
1295 s->refcount_max += s->refcount_max - 1;
1297 s->crypt_method_header = header.crypt_method;
1298 if (s->crypt_method_header) {
1299 if (bdrv_uses_whitelist() &&
1300 s->crypt_method_header == QCOW_CRYPT_AES) {
1301 error_setg(errp,
1302 "Use of AES-CBC encrypted qcow2 images is no longer "
1303 "supported in system emulators");
1304 error_append_hint(errp,
1305 "You can use 'qemu-img convert' to convert your "
1306 "image to an alternative supported format, such "
1307 "as unencrypted qcow2, or raw with the LUKS "
1308 "format instead.\n");
1309 ret = -ENOSYS;
1310 goto fail;
1313 if (s->crypt_method_header == QCOW_CRYPT_AES) {
1314 s->crypt_physical_offset = false;
1315 } else {
1316 /* Assuming LUKS and any future crypt methods we
1317 * add will all use physical offsets, due to the
1318 * fact that the alternative is insecure... */
1319 s->crypt_physical_offset = true;
1322 bs->encrypted = true;
1325 s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */
1326 s->l2_size = 1 << s->l2_bits;
1327 /* 2^(s->refcount_order - 3) is the refcount width in bytes */
1328 s->refcount_block_bits = s->cluster_bits - (s->refcount_order - 3);
1329 s->refcount_block_size = 1 << s->refcount_block_bits;
1330 bs->total_sectors = header.size / BDRV_SECTOR_SIZE;
1331 s->csize_shift = (62 - (s->cluster_bits - 8));
1332 s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;
1333 s->cluster_offset_mask = (1LL << s->csize_shift) - 1;
1335 s->refcount_table_offset = header.refcount_table_offset;
1336 s->refcount_table_size =
1337 header.refcount_table_clusters << (s->cluster_bits - 3);
1339 if (header.refcount_table_clusters == 0 && !(flags & BDRV_O_CHECK)) {
1340 error_setg(errp, "Image does not contain a reference count table");
1341 ret = -EINVAL;
1342 goto fail;
1345 ret = qcow2_validate_table(bs, s->refcount_table_offset,
1346 header.refcount_table_clusters,
1347 s->cluster_size, QCOW_MAX_REFTABLE_SIZE,
1348 "Reference count table", errp);
1349 if (ret < 0) {
1350 goto fail;
1353 /* The total size in bytes of the snapshot table is checked in
1354 * qcow2_read_snapshots() because the size of each snapshot is
1355 * variable and we don't know it yet.
1356 * Here we only check the offset and number of snapshots. */
1357 ret = qcow2_validate_table(bs, header.snapshots_offset,
1358 header.nb_snapshots,
1359 sizeof(QCowSnapshotHeader),
1360 sizeof(QCowSnapshotHeader) * QCOW_MAX_SNAPSHOTS,
1361 "Snapshot table", errp);
1362 if (ret < 0) {
1363 goto fail;
1366 /* read the level 1 table */
1367 ret = qcow2_validate_table(bs, header.l1_table_offset,
1368 header.l1_size, sizeof(uint64_t),
1369 QCOW_MAX_L1_SIZE, "Active L1 table", errp);
1370 if (ret < 0) {
1371 goto fail;
1373 s->l1_size = header.l1_size;
1374 s->l1_table_offset = header.l1_table_offset;
1376 l1_vm_state_index = size_to_l1(s, header.size);
1377 if (l1_vm_state_index > INT_MAX) {
1378 error_setg(errp, "Image is too big");
1379 ret = -EFBIG;
1380 goto fail;
1382 s->l1_vm_state_index = l1_vm_state_index;
1384 /* the L1 table must contain at least enough entries to put
1385 header.size bytes */
1386 if (s->l1_size < s->l1_vm_state_index) {
1387 error_setg(errp, "L1 table is too small");
1388 ret = -EINVAL;
1389 goto fail;
1392 if (s->l1_size > 0) {
1393 s->l1_table = qemu_try_blockalign(bs->file->bs,
1394 ROUND_UP(s->l1_size * sizeof(uint64_t), 512));
1395 if (s->l1_table == NULL) {
1396 error_setg(errp, "Could not allocate L1 table");
1397 ret = -ENOMEM;
1398 goto fail;
1400 ret = bdrv_pread(bs->file, s->l1_table_offset, s->l1_table,
1401 s->l1_size * sizeof(uint64_t));
1402 if (ret < 0) {
1403 error_setg_errno(errp, -ret, "Could not read L1 table");
1404 goto fail;
1406 for(i = 0;i < s->l1_size; i++) {
1407 s->l1_table[i] = be64_to_cpu(s->l1_table[i]);
1411 /* Parse driver-specific options */
1412 ret = qcow2_update_options(bs, options, flags, errp);
1413 if (ret < 0) {
1414 goto fail;
1417 s->cluster_cache_offset = -1;
1418 s->flags = flags;
1420 ret = qcow2_refcount_init(bs);
1421 if (ret != 0) {
1422 error_setg_errno(errp, -ret, "Could not initialize refcount handling");
1423 goto fail;
1426 QLIST_INIT(&s->cluster_allocs);
1427 QTAILQ_INIT(&s->discards);
1429 /* read qcow2 extensions */
1430 if (qcow2_read_extensions(bs, header.header_length, ext_end, NULL,
1431 flags, &update_header, &local_err)) {
1432 error_propagate(errp, local_err);
1433 ret = -EINVAL;
1434 goto fail;
1437 /* qcow2_read_extension may have set up the crypto context
1438 * if the crypt method needs a header region, some methods
1439 * don't need header extensions, so must check here
1441 if (s->crypt_method_header && !s->crypto) {
1442 if (s->crypt_method_header == QCOW_CRYPT_AES) {
1443 unsigned int cflags = 0;
1444 if (flags & BDRV_O_NO_IO) {
1445 cflags |= QCRYPTO_BLOCK_OPEN_NO_IO;
1447 s->crypto = qcrypto_block_open(s->crypto_opts, "encrypt.",
1448 NULL, NULL, cflags, errp);
1449 if (!s->crypto) {
1450 ret = -EINVAL;
1451 goto fail;
1453 } else if (!(flags & BDRV_O_NO_IO)) {
1454 error_setg(errp, "Missing CRYPTO header for crypt method %d",
1455 s->crypt_method_header);
1456 ret = -EINVAL;
1457 goto fail;
1461 /* read the backing file name */
1462 if (header.backing_file_offset != 0) {
1463 len = header.backing_file_size;
1464 if (len > MIN(1023, s->cluster_size - header.backing_file_offset) ||
1465 len >= sizeof(bs->backing_file)) {
1466 error_setg(errp, "Backing file name too long");
1467 ret = -EINVAL;
1468 goto fail;
1470 ret = bdrv_pread(bs->file, header.backing_file_offset,
1471 bs->backing_file, len);
1472 if (ret < 0) {
1473 error_setg_errno(errp, -ret, "Could not read backing file name");
1474 goto fail;
1476 bs->backing_file[len] = '\0';
1477 s->image_backing_file = g_strdup(bs->backing_file);
1480 /* Internal snapshots */
1481 s->snapshots_offset = header.snapshots_offset;
1482 s->nb_snapshots = header.nb_snapshots;
1484 ret = qcow2_read_snapshots(bs);
1485 if (ret < 0) {
1486 error_setg_errno(errp, -ret, "Could not read snapshots");
1487 goto fail;
1490 /* Clear unknown autoclear feature bits */
1491 update_header |= s->autoclear_features & ~QCOW2_AUTOCLEAR_MASK;
1492 update_header =
1493 update_header && !bs->read_only && !(flags & BDRV_O_INACTIVE);
1494 if (update_header) {
1495 s->autoclear_features &= QCOW2_AUTOCLEAR_MASK;
1498 /* == Handle persistent dirty bitmaps ==
1500 * We want load dirty bitmaps in three cases:
1502 * 1. Normal open of the disk in active mode, not related to invalidation
1503 * after migration.
1505 * 2. Invalidation of the target vm after pre-copy phase of migration, if
1506 * bitmaps are _not_ migrating through migration channel, i.e.
1507 * 'dirty-bitmaps' capability is disabled.
1509 * 3. Invalidation of source vm after failed or canceled migration.
1510 * This is a very interesting case. There are two possible types of
1511 * bitmaps:
1513 * A. Stored on inactivation and removed. They should be loaded from the
1514 * image.
1516 * B. Not stored: not-persistent bitmaps and bitmaps, migrated through
1517 * the migration channel (with dirty-bitmaps capability).
1519 * On the other hand, there are two possible sub-cases:
1521 * 3.1 disk was changed by somebody else while were inactive. In this
1522 * case all in-RAM dirty bitmaps (both persistent and not) are
1523 * definitely invalid. And we don't have any method to determine
1524 * this.
1526 * Simple and safe thing is to just drop all the bitmaps of type B on
1527 * inactivation. But in this case we lose bitmaps in valid 4.2 case.
1529 * On the other hand, resuming source vm, if disk was already changed
1530 * is a bad thing anyway: not only bitmaps, the whole vm state is
1531 * out of sync with disk.
1533 * This means, that user or management tool, who for some reason
1534 * decided to resume source vm, after disk was already changed by
1535 * target vm, should at least drop all dirty bitmaps by hand.
1537 * So, we can ignore this case for now, but TODO: "generation"
1538 * extension for qcow2, to determine, that image was changed after
1539 * last inactivation. And if it is changed, we will drop (or at least
1540 * mark as 'invalid' all the bitmaps of type B, both persistent
1541 * and not).
1543 * 3.2 disk was _not_ changed while were inactive. Bitmaps may be saved
1544 * to disk ('dirty-bitmaps' capability disabled), or not saved
1545 * ('dirty-bitmaps' capability enabled), but we don't need to care
1546 * of: let's load bitmaps as always: stored bitmaps will be loaded,
1547 * and not stored has flag IN_USE=1 in the image and will be skipped
1548 * on loading.
1550 * One remaining possible case when we don't want load bitmaps:
1552 * 4. Open disk in inactive mode in target vm (bitmaps are migrating or
1553 * will be loaded on invalidation, no needs try loading them before)
1556 if (!(bdrv_get_flags(bs) & BDRV_O_INACTIVE)) {
1557 /* It's case 1, 2 or 3.2. Or 3.1 which is BUG in management layer. */
1558 bool header_updated = qcow2_load_dirty_bitmaps(bs, &local_err);
1560 update_header = update_header && !header_updated;
1562 if (local_err != NULL) {
1563 error_propagate(errp, local_err);
1564 ret = -EINVAL;
1565 goto fail;
1568 if (update_header) {
1569 ret = qcow2_update_header(bs);
1570 if (ret < 0) {
1571 error_setg_errno(errp, -ret, "Could not update qcow2 header");
1572 goto fail;
1576 bs->supported_zero_flags = header.version >= 3 ? BDRV_REQ_MAY_UNMAP : 0;
1578 /* Repair image if dirty */
1579 if (!(flags & (BDRV_O_CHECK | BDRV_O_INACTIVE)) && !bs->read_only &&
1580 (s->incompatible_features & QCOW2_INCOMPAT_DIRTY)) {
1581 BdrvCheckResult result = {0};
1583 ret = qcow2_co_check_locked(bs, &result,
1584 BDRV_FIX_ERRORS | BDRV_FIX_LEAKS);
1585 if (ret < 0 || result.check_errors) {
1586 if (ret >= 0) {
1587 ret = -EIO;
1589 error_setg_errno(errp, -ret, "Could not repair dirty image");
1590 goto fail;
1594 #ifdef DEBUG_ALLOC
1596 BdrvCheckResult result = {0};
1597 qcow2_check_refcounts(bs, &result, 0);
1599 #endif
1601 qemu_co_queue_init(&s->compress_wait_queue);
1603 return ret;
1605 fail:
1606 g_free(s->unknown_header_fields);
1607 cleanup_unknown_header_ext(bs);
1608 qcow2_free_snapshots(bs);
1609 qcow2_refcount_close(bs);
1610 qemu_vfree(s->l1_table);
1611 /* else pre-write overlap checks in cache_destroy may crash */
1612 s->l1_table = NULL;
1613 cache_clean_timer_del(bs);
1614 if (s->l2_table_cache) {
1615 qcow2_cache_destroy(s->l2_table_cache);
1617 if (s->refcount_block_cache) {
1618 qcow2_cache_destroy(s->refcount_block_cache);
1620 qcrypto_block_free(s->crypto);
1621 qapi_free_QCryptoBlockOpenOptions(s->crypto_opts);
1622 return ret;
1625 typedef struct QCow2OpenCo {
1626 BlockDriverState *bs;
1627 QDict *options;
1628 int flags;
1629 Error **errp;
1630 int ret;
1631 } QCow2OpenCo;
1633 static void coroutine_fn qcow2_open_entry(void *opaque)
1635 QCow2OpenCo *qoc = opaque;
1636 BDRVQcow2State *s = qoc->bs->opaque;
1638 qemu_co_mutex_lock(&s->lock);
1639 qoc->ret = qcow2_do_open(qoc->bs, qoc->options, qoc->flags, qoc->errp);
1640 qemu_co_mutex_unlock(&s->lock);
1643 static int qcow2_open(BlockDriverState *bs, QDict *options, int flags,
1644 Error **errp)
1646 BDRVQcow2State *s = bs->opaque;
1647 QCow2OpenCo qoc = {
1648 .bs = bs,
1649 .options = options,
1650 .flags = flags,
1651 .errp = errp,
1652 .ret = -EINPROGRESS
1655 bs->file = bdrv_open_child(NULL, options, "file", bs, &child_file,
1656 false, errp);
1657 if (!bs->file) {
1658 return -EINVAL;
1661 /* Initialise locks */
1662 qemu_co_mutex_init(&s->lock);
1664 if (qemu_in_coroutine()) {
1665 /* From bdrv_co_create. */
1666 qcow2_open_entry(&qoc);
1667 } else {
1668 qemu_coroutine_enter(qemu_coroutine_create(qcow2_open_entry, &qoc));
1669 BDRV_POLL_WHILE(bs, qoc.ret == -EINPROGRESS);
1671 return qoc.ret;
1674 static void qcow2_refresh_limits(BlockDriverState *bs, Error **errp)
1676 BDRVQcow2State *s = bs->opaque;
1678 if (bs->encrypted) {
1679 /* Encryption works on a sector granularity */
1680 bs->bl.request_alignment = qcrypto_block_get_sector_size(s->crypto);
1682 bs->bl.pwrite_zeroes_alignment = s->cluster_size;
1683 bs->bl.pdiscard_alignment = s->cluster_size;
1686 static int qcow2_reopen_prepare(BDRVReopenState *state,
1687 BlockReopenQueue *queue, Error **errp)
1689 Qcow2ReopenState *r;
1690 int ret;
1692 r = g_new0(Qcow2ReopenState, 1);
1693 state->opaque = r;
1695 ret = qcow2_update_options_prepare(state->bs, r, state->options,
1696 state->flags, errp);
1697 if (ret < 0) {
1698 goto fail;
1701 /* We need to write out any unwritten data if we reopen read-only. */
1702 if ((state->flags & BDRV_O_RDWR) == 0) {
1703 ret = qcow2_reopen_bitmaps_ro(state->bs, errp);
1704 if (ret < 0) {
1705 goto fail;
1708 ret = bdrv_flush(state->bs);
1709 if (ret < 0) {
1710 goto fail;
1713 ret = qcow2_mark_clean(state->bs);
1714 if (ret < 0) {
1715 goto fail;
1719 return 0;
1721 fail:
1722 qcow2_update_options_abort(state->bs, r);
1723 g_free(r);
1724 return ret;
1727 static void qcow2_reopen_commit(BDRVReopenState *state)
1729 qcow2_update_options_commit(state->bs, state->opaque);
1730 g_free(state->opaque);
1733 static void qcow2_reopen_abort(BDRVReopenState *state)
1735 qcow2_update_options_abort(state->bs, state->opaque);
1736 g_free(state->opaque);
1739 static void qcow2_join_options(QDict *options, QDict *old_options)
1741 bool has_new_overlap_template =
1742 qdict_haskey(options, QCOW2_OPT_OVERLAP) ||
1743 qdict_haskey(options, QCOW2_OPT_OVERLAP_TEMPLATE);
1744 bool has_new_total_cache_size =
1745 qdict_haskey(options, QCOW2_OPT_CACHE_SIZE);
1746 bool has_all_cache_options;
1748 /* New overlap template overrides all old overlap options */
1749 if (has_new_overlap_template) {
1750 qdict_del(old_options, QCOW2_OPT_OVERLAP);
1751 qdict_del(old_options, QCOW2_OPT_OVERLAP_TEMPLATE);
1752 qdict_del(old_options, QCOW2_OPT_OVERLAP_MAIN_HEADER);
1753 qdict_del(old_options, QCOW2_OPT_OVERLAP_ACTIVE_L1);
1754 qdict_del(old_options, QCOW2_OPT_OVERLAP_ACTIVE_L2);
1755 qdict_del(old_options, QCOW2_OPT_OVERLAP_REFCOUNT_TABLE);
1756 qdict_del(old_options, QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK);
1757 qdict_del(old_options, QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE);
1758 qdict_del(old_options, QCOW2_OPT_OVERLAP_INACTIVE_L1);
1759 qdict_del(old_options, QCOW2_OPT_OVERLAP_INACTIVE_L2);
1762 /* New total cache size overrides all old options */
1763 if (qdict_haskey(options, QCOW2_OPT_CACHE_SIZE)) {
1764 qdict_del(old_options, QCOW2_OPT_L2_CACHE_SIZE);
1765 qdict_del(old_options, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
1768 qdict_join(options, old_options, false);
1771 * If after merging all cache size options are set, an old total size is
1772 * overwritten. Do keep all options, however, if all three are new. The
1773 * resulting error message is what we want to happen.
1775 has_all_cache_options =
1776 qdict_haskey(options, QCOW2_OPT_CACHE_SIZE) ||
1777 qdict_haskey(options, QCOW2_OPT_L2_CACHE_SIZE) ||
1778 qdict_haskey(options, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
1780 if (has_all_cache_options && !has_new_total_cache_size) {
1781 qdict_del(options, QCOW2_OPT_CACHE_SIZE);
1785 static int coroutine_fn qcow2_co_block_status(BlockDriverState *bs,
1786 bool want_zero,
1787 int64_t offset, int64_t count,
1788 int64_t *pnum, int64_t *map,
1789 BlockDriverState **file)
1791 BDRVQcow2State *s = bs->opaque;
1792 uint64_t cluster_offset;
1793 int index_in_cluster, ret;
1794 unsigned int bytes;
1795 int status = 0;
1797 bytes = MIN(INT_MAX, count);
1798 qemu_co_mutex_lock(&s->lock);
1799 ret = qcow2_get_cluster_offset(bs, offset, &bytes, &cluster_offset);
1800 qemu_co_mutex_unlock(&s->lock);
1801 if (ret < 0) {
1802 return ret;
1805 *pnum = bytes;
1807 if (cluster_offset != 0 && ret != QCOW2_CLUSTER_COMPRESSED &&
1808 !s->crypto) {
1809 index_in_cluster = offset & (s->cluster_size - 1);
1810 *map = cluster_offset | index_in_cluster;
1811 *file = bs->file->bs;
1812 status |= BDRV_BLOCK_OFFSET_VALID;
1814 if (ret == QCOW2_CLUSTER_ZERO_PLAIN || ret == QCOW2_CLUSTER_ZERO_ALLOC) {
1815 status |= BDRV_BLOCK_ZERO;
1816 } else if (ret != QCOW2_CLUSTER_UNALLOCATED) {
1817 status |= BDRV_BLOCK_DATA;
1819 return status;
1822 static coroutine_fn int qcow2_handle_l2meta(BlockDriverState *bs,
1823 QCowL2Meta **pl2meta,
1824 bool link_l2)
1826 int ret = 0;
1827 QCowL2Meta *l2meta = *pl2meta;
1829 while (l2meta != NULL) {
1830 QCowL2Meta *next;
1832 if (link_l2) {
1833 ret = qcow2_alloc_cluster_link_l2(bs, l2meta);
1834 if (ret) {
1835 goto out;
1837 } else {
1838 qcow2_alloc_cluster_abort(bs, l2meta);
1841 /* Take the request off the list of running requests */
1842 if (l2meta->nb_clusters != 0) {
1843 QLIST_REMOVE(l2meta, next_in_flight);
1846 qemu_co_queue_restart_all(&l2meta->dependent_requests);
1848 next = l2meta->next;
1849 g_free(l2meta);
1850 l2meta = next;
1852 out:
1853 *pl2meta = l2meta;
1854 return ret;
1857 static coroutine_fn int qcow2_co_preadv(BlockDriverState *bs, uint64_t offset,
1858 uint64_t bytes, QEMUIOVector *qiov,
1859 int flags)
1861 BDRVQcow2State *s = bs->opaque;
1862 int offset_in_cluster;
1863 int ret;
1864 unsigned int cur_bytes; /* number of bytes in current iteration */
1865 uint64_t cluster_offset = 0;
1866 uint64_t bytes_done = 0;
1867 QEMUIOVector hd_qiov;
1868 uint8_t *cluster_data = NULL;
1870 qemu_iovec_init(&hd_qiov, qiov->niov);
1872 qemu_co_mutex_lock(&s->lock);
1874 while (bytes != 0) {
1876 /* prepare next request */
1877 cur_bytes = MIN(bytes, INT_MAX);
1878 if (s->crypto) {
1879 cur_bytes = MIN(cur_bytes,
1880 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
1883 ret = qcow2_get_cluster_offset(bs, offset, &cur_bytes, &cluster_offset);
1884 if (ret < 0) {
1885 goto fail;
1888 offset_in_cluster = offset_into_cluster(s, offset);
1890 qemu_iovec_reset(&hd_qiov);
1891 qemu_iovec_concat(&hd_qiov, qiov, bytes_done, cur_bytes);
1893 switch (ret) {
1894 case QCOW2_CLUSTER_UNALLOCATED:
1896 if (bs->backing) {
1897 BLKDBG_EVENT(bs->file, BLKDBG_READ_BACKING_AIO);
1898 qemu_co_mutex_unlock(&s->lock);
1899 ret = bdrv_co_preadv(bs->backing, offset, cur_bytes,
1900 &hd_qiov, 0);
1901 qemu_co_mutex_lock(&s->lock);
1902 if (ret < 0) {
1903 goto fail;
1905 } else {
1906 /* Note: in this case, no need to wait */
1907 qemu_iovec_memset(&hd_qiov, 0, 0, cur_bytes);
1909 break;
1911 case QCOW2_CLUSTER_ZERO_PLAIN:
1912 case QCOW2_CLUSTER_ZERO_ALLOC:
1913 qemu_iovec_memset(&hd_qiov, 0, 0, cur_bytes);
1914 break;
1916 case QCOW2_CLUSTER_COMPRESSED:
1917 /* add AIO support for compressed blocks ? */
1918 ret = qcow2_decompress_cluster(bs, cluster_offset);
1919 if (ret < 0) {
1920 goto fail;
1923 qemu_iovec_from_buf(&hd_qiov, 0,
1924 s->cluster_cache + offset_in_cluster,
1925 cur_bytes);
1926 break;
1928 case QCOW2_CLUSTER_NORMAL:
1929 if ((cluster_offset & 511) != 0) {
1930 ret = -EIO;
1931 goto fail;
1934 if (bs->encrypted) {
1935 assert(s->crypto);
1938 * For encrypted images, read everything into a temporary
1939 * contiguous buffer on which the AES functions can work.
1941 if (!cluster_data) {
1942 cluster_data =
1943 qemu_try_blockalign(bs->file->bs,
1944 QCOW_MAX_CRYPT_CLUSTERS
1945 * s->cluster_size);
1946 if (cluster_data == NULL) {
1947 ret = -ENOMEM;
1948 goto fail;
1952 assert(cur_bytes <= QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
1953 qemu_iovec_reset(&hd_qiov);
1954 qemu_iovec_add(&hd_qiov, cluster_data, cur_bytes);
1957 BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);
1958 qemu_co_mutex_unlock(&s->lock);
1959 ret = bdrv_co_preadv(bs->file,
1960 cluster_offset + offset_in_cluster,
1961 cur_bytes, &hd_qiov, 0);
1962 qemu_co_mutex_lock(&s->lock);
1963 if (ret < 0) {
1964 goto fail;
1966 if (bs->encrypted) {
1967 assert(s->crypto);
1968 assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);
1969 assert((cur_bytes & (BDRV_SECTOR_SIZE - 1)) == 0);
1970 if (qcrypto_block_decrypt(s->crypto,
1971 (s->crypt_physical_offset ?
1972 cluster_offset + offset_in_cluster :
1973 offset),
1974 cluster_data,
1975 cur_bytes,
1976 NULL) < 0) {
1977 ret = -EIO;
1978 goto fail;
1980 qemu_iovec_from_buf(qiov, bytes_done, cluster_data, cur_bytes);
1982 break;
1984 default:
1985 g_assert_not_reached();
1986 ret = -EIO;
1987 goto fail;
1990 bytes -= cur_bytes;
1991 offset += cur_bytes;
1992 bytes_done += cur_bytes;
1994 ret = 0;
1996 fail:
1997 qemu_co_mutex_unlock(&s->lock);
1999 qemu_iovec_destroy(&hd_qiov);
2000 qemu_vfree(cluster_data);
2002 return ret;
2005 /* Check if it's possible to merge a write request with the writing of
2006 * the data from the COW regions */
2007 static bool merge_cow(uint64_t offset, unsigned bytes,
2008 QEMUIOVector *hd_qiov, QCowL2Meta *l2meta)
2010 QCowL2Meta *m;
2012 for (m = l2meta; m != NULL; m = m->next) {
2013 /* If both COW regions are empty then there's nothing to merge */
2014 if (m->cow_start.nb_bytes == 0 && m->cow_end.nb_bytes == 0) {
2015 continue;
2018 /* The data (middle) region must be immediately after the
2019 * start region */
2020 if (l2meta_cow_start(m) + m->cow_start.nb_bytes != offset) {
2021 continue;
2024 /* The end region must be immediately after the data (middle)
2025 * region */
2026 if (m->offset + m->cow_end.offset != offset + bytes) {
2027 continue;
2030 /* Make sure that adding both COW regions to the QEMUIOVector
2031 * does not exceed IOV_MAX */
2032 if (hd_qiov->niov > IOV_MAX - 2) {
2033 continue;
2036 m->data_qiov = hd_qiov;
2037 return true;
2040 return false;
2043 static coroutine_fn int qcow2_co_pwritev(BlockDriverState *bs, uint64_t offset,
2044 uint64_t bytes, QEMUIOVector *qiov,
2045 int flags)
2047 BDRVQcow2State *s = bs->opaque;
2048 int offset_in_cluster;
2049 int ret;
2050 unsigned int cur_bytes; /* number of sectors in current iteration */
2051 uint64_t cluster_offset;
2052 QEMUIOVector hd_qiov;
2053 uint64_t bytes_done = 0;
2054 uint8_t *cluster_data = NULL;
2055 QCowL2Meta *l2meta = NULL;
2057 trace_qcow2_writev_start_req(qemu_coroutine_self(), offset, bytes);
2059 qemu_iovec_init(&hd_qiov, qiov->niov);
2061 s->cluster_cache_offset = -1; /* disable compressed cache */
2063 qemu_co_mutex_lock(&s->lock);
2065 while (bytes != 0) {
2067 l2meta = NULL;
2069 trace_qcow2_writev_start_part(qemu_coroutine_self());
2070 offset_in_cluster = offset_into_cluster(s, offset);
2071 cur_bytes = MIN(bytes, INT_MAX);
2072 if (bs->encrypted) {
2073 cur_bytes = MIN(cur_bytes,
2074 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size
2075 - offset_in_cluster);
2078 ret = qcow2_alloc_cluster_offset(bs, offset, &cur_bytes,
2079 &cluster_offset, &l2meta);
2080 if (ret < 0) {
2081 goto fail;
2084 assert((cluster_offset & 511) == 0);
2086 qemu_iovec_reset(&hd_qiov);
2087 qemu_iovec_concat(&hd_qiov, qiov, bytes_done, cur_bytes);
2089 if (bs->encrypted) {
2090 assert(s->crypto);
2091 if (!cluster_data) {
2092 cluster_data = qemu_try_blockalign(bs->file->bs,
2093 QCOW_MAX_CRYPT_CLUSTERS
2094 * s->cluster_size);
2095 if (cluster_data == NULL) {
2096 ret = -ENOMEM;
2097 goto fail;
2101 assert(hd_qiov.size <=
2102 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
2103 qemu_iovec_to_buf(&hd_qiov, 0, cluster_data, hd_qiov.size);
2105 if (qcrypto_block_encrypt(s->crypto,
2106 (s->crypt_physical_offset ?
2107 cluster_offset + offset_in_cluster :
2108 offset),
2109 cluster_data,
2110 cur_bytes, NULL) < 0) {
2111 ret = -EIO;
2112 goto fail;
2115 qemu_iovec_reset(&hd_qiov);
2116 qemu_iovec_add(&hd_qiov, cluster_data, cur_bytes);
2119 ret = qcow2_pre_write_overlap_check(bs, 0,
2120 cluster_offset + offset_in_cluster, cur_bytes);
2121 if (ret < 0) {
2122 goto fail;
2125 /* If we need to do COW, check if it's possible to merge the
2126 * writing of the guest data together with that of the COW regions.
2127 * If it's not possible (or not necessary) then write the
2128 * guest data now. */
2129 if (!merge_cow(offset, cur_bytes, &hd_qiov, l2meta)) {
2130 qemu_co_mutex_unlock(&s->lock);
2131 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO);
2132 trace_qcow2_writev_data(qemu_coroutine_self(),
2133 cluster_offset + offset_in_cluster);
2134 ret = bdrv_co_pwritev(bs->file,
2135 cluster_offset + offset_in_cluster,
2136 cur_bytes, &hd_qiov, 0);
2137 qemu_co_mutex_lock(&s->lock);
2138 if (ret < 0) {
2139 goto fail;
2143 ret = qcow2_handle_l2meta(bs, &l2meta, true);
2144 if (ret) {
2145 goto fail;
2148 bytes -= cur_bytes;
2149 offset += cur_bytes;
2150 bytes_done += cur_bytes;
2151 trace_qcow2_writev_done_part(qemu_coroutine_self(), cur_bytes);
2153 ret = 0;
2155 fail:
2156 qcow2_handle_l2meta(bs, &l2meta, false);
2158 qemu_co_mutex_unlock(&s->lock);
2160 qemu_iovec_destroy(&hd_qiov);
2161 qemu_vfree(cluster_data);
2162 trace_qcow2_writev_done_req(qemu_coroutine_self(), ret);
2164 return ret;
2167 static int qcow2_inactivate(BlockDriverState *bs)
2169 BDRVQcow2State *s = bs->opaque;
2170 int ret, result = 0;
2171 Error *local_err = NULL;
2173 qcow2_store_persistent_dirty_bitmaps(bs, &local_err);
2174 if (local_err != NULL) {
2175 result = -EINVAL;
2176 error_reportf_err(local_err, "Lost persistent bitmaps during "
2177 "inactivation of node '%s': ",
2178 bdrv_get_device_or_node_name(bs));
2181 ret = qcow2_cache_flush(bs, s->l2_table_cache);
2182 if (ret) {
2183 result = ret;
2184 error_report("Failed to flush the L2 table cache: %s",
2185 strerror(-ret));
2188 ret = qcow2_cache_flush(bs, s->refcount_block_cache);
2189 if (ret) {
2190 result = ret;
2191 error_report("Failed to flush the refcount block cache: %s",
2192 strerror(-ret));
2195 if (result == 0) {
2196 qcow2_mark_clean(bs);
2199 return result;
2202 static void qcow2_close(BlockDriverState *bs)
2204 BDRVQcow2State *s = bs->opaque;
2205 qemu_vfree(s->l1_table);
2206 /* else pre-write overlap checks in cache_destroy may crash */
2207 s->l1_table = NULL;
2209 if (!(s->flags & BDRV_O_INACTIVE)) {
2210 qcow2_inactivate(bs);
2213 cache_clean_timer_del(bs);
2214 qcow2_cache_destroy(s->l2_table_cache);
2215 qcow2_cache_destroy(s->refcount_block_cache);
2217 qcrypto_block_free(s->crypto);
2218 s->crypto = NULL;
2220 g_free(s->unknown_header_fields);
2221 cleanup_unknown_header_ext(bs);
2223 g_free(s->image_backing_file);
2224 g_free(s->image_backing_format);
2226 g_free(s->cluster_cache);
2227 qemu_vfree(s->cluster_data);
2228 qcow2_refcount_close(bs);
2229 qcow2_free_snapshots(bs);
2232 static void coroutine_fn qcow2_co_invalidate_cache(BlockDriverState *bs,
2233 Error **errp)
2235 BDRVQcow2State *s = bs->opaque;
2236 int flags = s->flags;
2237 QCryptoBlock *crypto = NULL;
2238 QDict *options;
2239 Error *local_err = NULL;
2240 int ret;
2243 * Backing files are read-only which makes all of their metadata immutable,
2244 * that means we don't have to worry about reopening them here.
2247 crypto = s->crypto;
2248 s->crypto = NULL;
2250 qcow2_close(bs);
2252 memset(s, 0, sizeof(BDRVQcow2State));
2253 options = qdict_clone_shallow(bs->options);
2255 flags &= ~BDRV_O_INACTIVE;
2256 qemu_co_mutex_lock(&s->lock);
2257 ret = qcow2_do_open(bs, options, flags, &local_err);
2258 qemu_co_mutex_unlock(&s->lock);
2259 qobject_unref(options);
2260 if (local_err) {
2261 error_propagate_prepend(errp, local_err,
2262 "Could not reopen qcow2 layer: ");
2263 bs->drv = NULL;
2264 return;
2265 } else if (ret < 0) {
2266 error_setg_errno(errp, -ret, "Could not reopen qcow2 layer");
2267 bs->drv = NULL;
2268 return;
2271 s->crypto = crypto;
2274 static size_t header_ext_add(char *buf, uint32_t magic, const void *s,
2275 size_t len, size_t buflen)
2277 QCowExtension *ext_backing_fmt = (QCowExtension*) buf;
2278 size_t ext_len = sizeof(QCowExtension) + ((len + 7) & ~7);
2280 if (buflen < ext_len) {
2281 return -ENOSPC;
2284 *ext_backing_fmt = (QCowExtension) {
2285 .magic = cpu_to_be32(magic),
2286 .len = cpu_to_be32(len),
2289 if (len) {
2290 memcpy(buf + sizeof(QCowExtension), s, len);
2293 return ext_len;
2297 * Updates the qcow2 header, including the variable length parts of it, i.e.
2298 * the backing file name and all extensions. qcow2 was not designed to allow
2299 * such changes, so if we run out of space (we can only use the first cluster)
2300 * this function may fail.
2302 * Returns 0 on success, -errno in error cases.
2304 int qcow2_update_header(BlockDriverState *bs)
2306 BDRVQcow2State *s = bs->opaque;
2307 QCowHeader *header;
2308 char *buf;
2309 size_t buflen = s->cluster_size;
2310 int ret;
2311 uint64_t total_size;
2312 uint32_t refcount_table_clusters;
2313 size_t header_length;
2314 Qcow2UnknownHeaderExtension *uext;
2316 buf = qemu_blockalign(bs, buflen);
2318 /* Header structure */
2319 header = (QCowHeader*) buf;
2321 if (buflen < sizeof(*header)) {
2322 ret = -ENOSPC;
2323 goto fail;
2326 header_length = sizeof(*header) + s->unknown_header_fields_size;
2327 total_size = bs->total_sectors * BDRV_SECTOR_SIZE;
2328 refcount_table_clusters = s->refcount_table_size >> (s->cluster_bits - 3);
2330 *header = (QCowHeader) {
2331 /* Version 2 fields */
2332 .magic = cpu_to_be32(QCOW_MAGIC),
2333 .version = cpu_to_be32(s->qcow_version),
2334 .backing_file_offset = 0,
2335 .backing_file_size = 0,
2336 .cluster_bits = cpu_to_be32(s->cluster_bits),
2337 .size = cpu_to_be64(total_size),
2338 .crypt_method = cpu_to_be32(s->crypt_method_header),
2339 .l1_size = cpu_to_be32(s->l1_size),
2340 .l1_table_offset = cpu_to_be64(s->l1_table_offset),
2341 .refcount_table_offset = cpu_to_be64(s->refcount_table_offset),
2342 .refcount_table_clusters = cpu_to_be32(refcount_table_clusters),
2343 .nb_snapshots = cpu_to_be32(s->nb_snapshots),
2344 .snapshots_offset = cpu_to_be64(s->snapshots_offset),
2346 /* Version 3 fields */
2347 .incompatible_features = cpu_to_be64(s->incompatible_features),
2348 .compatible_features = cpu_to_be64(s->compatible_features),
2349 .autoclear_features = cpu_to_be64(s->autoclear_features),
2350 .refcount_order = cpu_to_be32(s->refcount_order),
2351 .header_length = cpu_to_be32(header_length),
2354 /* For older versions, write a shorter header */
2355 switch (s->qcow_version) {
2356 case 2:
2357 ret = offsetof(QCowHeader, incompatible_features);
2358 break;
2359 case 3:
2360 ret = sizeof(*header);
2361 break;
2362 default:
2363 ret = -EINVAL;
2364 goto fail;
2367 buf += ret;
2368 buflen -= ret;
2369 memset(buf, 0, buflen);
2371 /* Preserve any unknown field in the header */
2372 if (s->unknown_header_fields_size) {
2373 if (buflen < s->unknown_header_fields_size) {
2374 ret = -ENOSPC;
2375 goto fail;
2378 memcpy(buf, s->unknown_header_fields, s->unknown_header_fields_size);
2379 buf += s->unknown_header_fields_size;
2380 buflen -= s->unknown_header_fields_size;
2383 /* Backing file format header extension */
2384 if (s->image_backing_format) {
2385 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BACKING_FORMAT,
2386 s->image_backing_format,
2387 strlen(s->image_backing_format),
2388 buflen);
2389 if (ret < 0) {
2390 goto fail;
2393 buf += ret;
2394 buflen -= ret;
2397 /* Full disk encryption header pointer extension */
2398 if (s->crypto_header.offset != 0) {
2399 s->crypto_header.offset = cpu_to_be64(s->crypto_header.offset);
2400 s->crypto_header.length = cpu_to_be64(s->crypto_header.length);
2401 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_CRYPTO_HEADER,
2402 &s->crypto_header, sizeof(s->crypto_header),
2403 buflen);
2404 s->crypto_header.offset = be64_to_cpu(s->crypto_header.offset);
2405 s->crypto_header.length = be64_to_cpu(s->crypto_header.length);
2406 if (ret < 0) {
2407 goto fail;
2409 buf += ret;
2410 buflen -= ret;
2413 /* Feature table */
2414 if (s->qcow_version >= 3) {
2415 Qcow2Feature features[] = {
2417 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
2418 .bit = QCOW2_INCOMPAT_DIRTY_BITNR,
2419 .name = "dirty bit",
2422 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
2423 .bit = QCOW2_INCOMPAT_CORRUPT_BITNR,
2424 .name = "corrupt bit",
2427 .type = QCOW2_FEAT_TYPE_COMPATIBLE,
2428 .bit = QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR,
2429 .name = "lazy refcounts",
2433 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_FEATURE_TABLE,
2434 features, sizeof(features), buflen);
2435 if (ret < 0) {
2436 goto fail;
2438 buf += ret;
2439 buflen -= ret;
2442 /* Bitmap extension */
2443 if (s->nb_bitmaps > 0) {
2444 Qcow2BitmapHeaderExt bitmaps_header = {
2445 .nb_bitmaps = cpu_to_be32(s->nb_bitmaps),
2446 .bitmap_directory_size =
2447 cpu_to_be64(s->bitmap_directory_size),
2448 .bitmap_directory_offset =
2449 cpu_to_be64(s->bitmap_directory_offset)
2451 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BITMAPS,
2452 &bitmaps_header, sizeof(bitmaps_header),
2453 buflen);
2454 if (ret < 0) {
2455 goto fail;
2457 buf += ret;
2458 buflen -= ret;
2461 /* Keep unknown header extensions */
2462 QLIST_FOREACH(uext, &s->unknown_header_ext, next) {
2463 ret = header_ext_add(buf, uext->magic, uext->data, uext->len, buflen);
2464 if (ret < 0) {
2465 goto fail;
2468 buf += ret;
2469 buflen -= ret;
2472 /* End of header extensions */
2473 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_END, NULL, 0, buflen);
2474 if (ret < 0) {
2475 goto fail;
2478 buf += ret;
2479 buflen -= ret;
2481 /* Backing file name */
2482 if (s->image_backing_file) {
2483 size_t backing_file_len = strlen(s->image_backing_file);
2485 if (buflen < backing_file_len) {
2486 ret = -ENOSPC;
2487 goto fail;
2490 /* Using strncpy is ok here, since buf is not NUL-terminated. */
2491 strncpy(buf, s->image_backing_file, buflen);
2493 header->backing_file_offset = cpu_to_be64(buf - ((char*) header));
2494 header->backing_file_size = cpu_to_be32(backing_file_len);
2497 /* Write the new header */
2498 ret = bdrv_pwrite(bs->file, 0, header, s->cluster_size);
2499 if (ret < 0) {
2500 goto fail;
2503 ret = 0;
2504 fail:
2505 qemu_vfree(header);
2506 return ret;
2509 static int qcow2_change_backing_file(BlockDriverState *bs,
2510 const char *backing_file, const char *backing_fmt)
2512 BDRVQcow2State *s = bs->opaque;
2514 if (backing_file && strlen(backing_file) > 1023) {
2515 return -EINVAL;
2518 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
2519 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
2521 g_free(s->image_backing_file);
2522 g_free(s->image_backing_format);
2524 s->image_backing_file = backing_file ? g_strdup(bs->backing_file) : NULL;
2525 s->image_backing_format = backing_fmt ? g_strdup(bs->backing_format) : NULL;
2527 return qcow2_update_header(bs);
2530 static int qcow2_crypt_method_from_format(const char *encryptfmt)
2532 if (g_str_equal(encryptfmt, "luks")) {
2533 return QCOW_CRYPT_LUKS;
2534 } else if (g_str_equal(encryptfmt, "aes")) {
2535 return QCOW_CRYPT_AES;
2536 } else {
2537 return -EINVAL;
2541 static int qcow2_set_up_encryption(BlockDriverState *bs,
2542 QCryptoBlockCreateOptions *cryptoopts,
2543 Error **errp)
2545 BDRVQcow2State *s = bs->opaque;
2546 QCryptoBlock *crypto = NULL;
2547 int fmt, ret;
2549 switch (cryptoopts->format) {
2550 case Q_CRYPTO_BLOCK_FORMAT_LUKS:
2551 fmt = QCOW_CRYPT_LUKS;
2552 break;
2553 case Q_CRYPTO_BLOCK_FORMAT_QCOW:
2554 fmt = QCOW_CRYPT_AES;
2555 break;
2556 default:
2557 error_setg(errp, "Crypto format not supported in qcow2");
2558 return -EINVAL;
2561 s->crypt_method_header = fmt;
2563 crypto = qcrypto_block_create(cryptoopts, "encrypt.",
2564 qcow2_crypto_hdr_init_func,
2565 qcow2_crypto_hdr_write_func,
2566 bs, errp);
2567 if (!crypto) {
2568 return -EINVAL;
2571 ret = qcow2_update_header(bs);
2572 if (ret < 0) {
2573 error_setg_errno(errp, -ret, "Could not write encryption header");
2574 goto out;
2577 ret = 0;
2578 out:
2579 qcrypto_block_free(crypto);
2580 return ret;
2584 * Preallocates metadata structures for data clusters between @offset (in the
2585 * guest disk) and @new_length (which is thus generally the new guest disk
2586 * size).
2588 * Returns: 0 on success, -errno on failure.
2590 static int coroutine_fn preallocate_co(BlockDriverState *bs, uint64_t offset,
2591 uint64_t new_length)
2593 BDRVQcow2State *s = bs->opaque;
2594 uint64_t bytes;
2595 uint64_t host_offset = 0;
2596 unsigned int cur_bytes;
2597 int ret;
2598 QCowL2Meta *meta;
2600 assert(offset <= new_length);
2601 bytes = new_length - offset;
2603 while (bytes) {
2604 cur_bytes = MIN(bytes, QEMU_ALIGN_DOWN(INT_MAX, s->cluster_size));
2605 ret = qcow2_alloc_cluster_offset(bs, offset, &cur_bytes,
2606 &host_offset, &meta);
2607 if (ret < 0) {
2608 return ret;
2611 while (meta) {
2612 QCowL2Meta *next = meta->next;
2614 ret = qcow2_alloc_cluster_link_l2(bs, meta);
2615 if (ret < 0) {
2616 qcow2_free_any_clusters(bs, meta->alloc_offset,
2617 meta->nb_clusters, QCOW2_DISCARD_NEVER);
2618 return ret;
2621 /* There are no dependent requests, but we need to remove our
2622 * request from the list of in-flight requests */
2623 QLIST_REMOVE(meta, next_in_flight);
2625 g_free(meta);
2626 meta = next;
2629 /* TODO Preallocate data if requested */
2631 bytes -= cur_bytes;
2632 offset += cur_bytes;
2636 * It is expected that the image file is large enough to actually contain
2637 * all of the allocated clusters (otherwise we get failing reads after
2638 * EOF). Extend the image to the last allocated sector.
2640 if (host_offset != 0) {
2641 uint8_t data = 0;
2642 ret = bdrv_pwrite(bs->file, (host_offset + cur_bytes) - 1,
2643 &data, 1);
2644 if (ret < 0) {
2645 return ret;
2649 return 0;
2652 /* qcow2_refcount_metadata_size:
2653 * @clusters: number of clusters to refcount (including data and L1/L2 tables)
2654 * @cluster_size: size of a cluster, in bytes
2655 * @refcount_order: refcount bits power-of-2 exponent
2656 * @generous_increase: allow for the refcount table to be 1.5x as large as it
2657 * needs to be
2659 * Returns: Number of bytes required for refcount blocks and table metadata.
2661 int64_t qcow2_refcount_metadata_size(int64_t clusters, size_t cluster_size,
2662 int refcount_order, bool generous_increase,
2663 uint64_t *refblock_count)
2666 * Every host cluster is reference-counted, including metadata (even
2667 * refcount metadata is recursively included).
2669 * An accurate formula for the size of refcount metadata size is difficult
2670 * to derive. An easier method of calculation is finding the fixed point
2671 * where no further refcount blocks or table clusters are required to
2672 * reference count every cluster.
2674 int64_t blocks_per_table_cluster = cluster_size / sizeof(uint64_t);
2675 int64_t refcounts_per_block = cluster_size * 8 / (1 << refcount_order);
2676 int64_t table = 0; /* number of refcount table clusters */
2677 int64_t blocks = 0; /* number of refcount block clusters */
2678 int64_t last;
2679 int64_t n = 0;
2681 do {
2682 last = n;
2683 blocks = DIV_ROUND_UP(clusters + table + blocks, refcounts_per_block);
2684 table = DIV_ROUND_UP(blocks, blocks_per_table_cluster);
2685 n = clusters + blocks + table;
2687 if (n == last && generous_increase) {
2688 clusters += DIV_ROUND_UP(table, 2);
2689 n = 0; /* force another loop */
2690 generous_increase = false;
2692 } while (n != last);
2694 if (refblock_count) {
2695 *refblock_count = blocks;
2698 return (blocks + table) * cluster_size;
2702 * qcow2_calc_prealloc_size:
2703 * @total_size: virtual disk size in bytes
2704 * @cluster_size: cluster size in bytes
2705 * @refcount_order: refcount bits power-of-2 exponent
2707 * Returns: Total number of bytes required for the fully allocated image
2708 * (including metadata).
2710 static int64_t qcow2_calc_prealloc_size(int64_t total_size,
2711 size_t cluster_size,
2712 int refcount_order)
2714 int64_t meta_size = 0;
2715 uint64_t nl1e, nl2e;
2716 int64_t aligned_total_size = ROUND_UP(total_size, cluster_size);
2718 /* header: 1 cluster */
2719 meta_size += cluster_size;
2721 /* total size of L2 tables */
2722 nl2e = aligned_total_size / cluster_size;
2723 nl2e = ROUND_UP(nl2e, cluster_size / sizeof(uint64_t));
2724 meta_size += nl2e * sizeof(uint64_t);
2726 /* total size of L1 tables */
2727 nl1e = nl2e * sizeof(uint64_t) / cluster_size;
2728 nl1e = ROUND_UP(nl1e, cluster_size / sizeof(uint64_t));
2729 meta_size += nl1e * sizeof(uint64_t);
2731 /* total size of refcount table and blocks */
2732 meta_size += qcow2_refcount_metadata_size(
2733 (meta_size + aligned_total_size) / cluster_size,
2734 cluster_size, refcount_order, false, NULL);
2736 return meta_size + aligned_total_size;
2739 static bool validate_cluster_size(size_t cluster_size, Error **errp)
2741 int cluster_bits = ctz32(cluster_size);
2742 if (cluster_bits < MIN_CLUSTER_BITS || cluster_bits > MAX_CLUSTER_BITS ||
2743 (1 << cluster_bits) != cluster_size)
2745 error_setg(errp, "Cluster size must be a power of two between %d and "
2746 "%dk", 1 << MIN_CLUSTER_BITS, 1 << (MAX_CLUSTER_BITS - 10));
2747 return false;
2749 return true;
2752 static size_t qcow2_opt_get_cluster_size_del(QemuOpts *opts, Error **errp)
2754 size_t cluster_size;
2756 cluster_size = qemu_opt_get_size_del(opts, BLOCK_OPT_CLUSTER_SIZE,
2757 DEFAULT_CLUSTER_SIZE);
2758 if (!validate_cluster_size(cluster_size, errp)) {
2759 return 0;
2761 return cluster_size;
2764 static int qcow2_opt_get_version_del(QemuOpts *opts, Error **errp)
2766 char *buf;
2767 int ret;
2769 buf = qemu_opt_get_del(opts, BLOCK_OPT_COMPAT_LEVEL);
2770 if (!buf) {
2771 ret = 3; /* default */
2772 } else if (!strcmp(buf, "0.10")) {
2773 ret = 2;
2774 } else if (!strcmp(buf, "1.1")) {
2775 ret = 3;
2776 } else {
2777 error_setg(errp, "Invalid compatibility level: '%s'", buf);
2778 ret = -EINVAL;
2780 g_free(buf);
2781 return ret;
2784 static uint64_t qcow2_opt_get_refcount_bits_del(QemuOpts *opts, int version,
2785 Error **errp)
2787 uint64_t refcount_bits;
2789 refcount_bits = qemu_opt_get_number_del(opts, BLOCK_OPT_REFCOUNT_BITS, 16);
2790 if (refcount_bits > 64 || !is_power_of_2(refcount_bits)) {
2791 error_setg(errp, "Refcount width must be a power of two and may not "
2792 "exceed 64 bits");
2793 return 0;
2796 if (version < 3 && refcount_bits != 16) {
2797 error_setg(errp, "Different refcount widths than 16 bits require "
2798 "compatibility level 1.1 or above (use compat=1.1 or "
2799 "greater)");
2800 return 0;
2803 return refcount_bits;
2806 static int coroutine_fn
2807 qcow2_co_create(BlockdevCreateOptions *create_options, Error **errp)
2809 BlockdevCreateOptionsQcow2 *qcow2_opts;
2810 QDict *options;
2813 * Open the image file and write a minimal qcow2 header.
2815 * We keep things simple and start with a zero-sized image. We also
2816 * do without refcount blocks or a L1 table for now. We'll fix the
2817 * inconsistency later.
2819 * We do need a refcount table because growing the refcount table means
2820 * allocating two new refcount blocks - the seconds of which would be at
2821 * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
2822 * size for any qcow2 image.
2824 BlockBackend *blk = NULL;
2825 BlockDriverState *bs = NULL;
2826 QCowHeader *header;
2827 size_t cluster_size;
2828 int version;
2829 int refcount_order;
2830 uint64_t* refcount_table;
2831 Error *local_err = NULL;
2832 int ret;
2834 assert(create_options->driver == BLOCKDEV_DRIVER_QCOW2);
2835 qcow2_opts = &create_options->u.qcow2;
2837 bs = bdrv_open_blockdev_ref(qcow2_opts->file, errp);
2838 if (bs == NULL) {
2839 return -EIO;
2842 /* Validate options and set default values */
2843 if (!QEMU_IS_ALIGNED(qcow2_opts->size, BDRV_SECTOR_SIZE)) {
2844 error_setg(errp, "Image size must be a multiple of 512 bytes");
2845 ret = -EINVAL;
2846 goto out;
2849 if (qcow2_opts->has_version) {
2850 switch (qcow2_opts->version) {
2851 case BLOCKDEV_QCOW2_VERSION_V2:
2852 version = 2;
2853 break;
2854 case BLOCKDEV_QCOW2_VERSION_V3:
2855 version = 3;
2856 break;
2857 default:
2858 g_assert_not_reached();
2860 } else {
2861 version = 3;
2864 if (qcow2_opts->has_cluster_size) {
2865 cluster_size = qcow2_opts->cluster_size;
2866 } else {
2867 cluster_size = DEFAULT_CLUSTER_SIZE;
2870 if (!validate_cluster_size(cluster_size, errp)) {
2871 ret = -EINVAL;
2872 goto out;
2875 if (!qcow2_opts->has_preallocation) {
2876 qcow2_opts->preallocation = PREALLOC_MODE_OFF;
2878 if (qcow2_opts->has_backing_file &&
2879 qcow2_opts->preallocation != PREALLOC_MODE_OFF)
2881 error_setg(errp, "Backing file and preallocation cannot be used at "
2882 "the same time");
2883 ret = -EINVAL;
2884 goto out;
2886 if (qcow2_opts->has_backing_fmt && !qcow2_opts->has_backing_file) {
2887 error_setg(errp, "Backing format cannot be used without backing file");
2888 ret = -EINVAL;
2889 goto out;
2892 if (!qcow2_opts->has_lazy_refcounts) {
2893 qcow2_opts->lazy_refcounts = false;
2895 if (version < 3 && qcow2_opts->lazy_refcounts) {
2896 error_setg(errp, "Lazy refcounts only supported with compatibility "
2897 "level 1.1 and above (use version=v3 or greater)");
2898 ret = -EINVAL;
2899 goto out;
2902 if (!qcow2_opts->has_refcount_bits) {
2903 qcow2_opts->refcount_bits = 16;
2905 if (qcow2_opts->refcount_bits > 64 ||
2906 !is_power_of_2(qcow2_opts->refcount_bits))
2908 error_setg(errp, "Refcount width must be a power of two and may not "
2909 "exceed 64 bits");
2910 ret = -EINVAL;
2911 goto out;
2913 if (version < 3 && qcow2_opts->refcount_bits != 16) {
2914 error_setg(errp, "Different refcount widths than 16 bits require "
2915 "compatibility level 1.1 or above (use version=v3 or "
2916 "greater)");
2917 ret = -EINVAL;
2918 goto out;
2920 refcount_order = ctz32(qcow2_opts->refcount_bits);
2923 /* Create BlockBackend to write to the image */
2924 blk = blk_new(BLK_PERM_WRITE | BLK_PERM_RESIZE, BLK_PERM_ALL);
2925 ret = blk_insert_bs(blk, bs, errp);
2926 if (ret < 0) {
2927 goto out;
2929 blk_set_allow_write_beyond_eof(blk, true);
2931 /* Clear the protocol layer and preallocate it if necessary */
2932 ret = blk_truncate(blk, 0, PREALLOC_MODE_OFF, errp);
2933 if (ret < 0) {
2934 goto out;
2937 if (qcow2_opts->preallocation == PREALLOC_MODE_FULL ||
2938 qcow2_opts->preallocation == PREALLOC_MODE_FALLOC)
2940 int64_t prealloc_size =
2941 qcow2_calc_prealloc_size(qcow2_opts->size, cluster_size,
2942 refcount_order);
2944 ret = blk_truncate(blk, prealloc_size, qcow2_opts->preallocation, errp);
2945 if (ret < 0) {
2946 goto out;
2950 /* Write the header */
2951 QEMU_BUILD_BUG_ON((1 << MIN_CLUSTER_BITS) < sizeof(*header));
2952 header = g_malloc0(cluster_size);
2953 *header = (QCowHeader) {
2954 .magic = cpu_to_be32(QCOW_MAGIC),
2955 .version = cpu_to_be32(version),
2956 .cluster_bits = cpu_to_be32(ctz32(cluster_size)),
2957 .size = cpu_to_be64(0),
2958 .l1_table_offset = cpu_to_be64(0),
2959 .l1_size = cpu_to_be32(0),
2960 .refcount_table_offset = cpu_to_be64(cluster_size),
2961 .refcount_table_clusters = cpu_to_be32(1),
2962 .refcount_order = cpu_to_be32(refcount_order),
2963 .header_length = cpu_to_be32(sizeof(*header)),
2966 /* We'll update this to correct value later */
2967 header->crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
2969 if (qcow2_opts->lazy_refcounts) {
2970 header->compatible_features |=
2971 cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS);
2974 ret = blk_pwrite(blk, 0, header, cluster_size, 0);
2975 g_free(header);
2976 if (ret < 0) {
2977 error_setg_errno(errp, -ret, "Could not write qcow2 header");
2978 goto out;
2981 /* Write a refcount table with one refcount block */
2982 refcount_table = g_malloc0(2 * cluster_size);
2983 refcount_table[0] = cpu_to_be64(2 * cluster_size);
2984 ret = blk_pwrite(blk, cluster_size, refcount_table, 2 * cluster_size, 0);
2985 g_free(refcount_table);
2987 if (ret < 0) {
2988 error_setg_errno(errp, -ret, "Could not write refcount table");
2989 goto out;
2992 blk_unref(blk);
2993 blk = NULL;
2996 * And now open the image and make it consistent first (i.e. increase the
2997 * refcount of the cluster that is occupied by the header and the refcount
2998 * table)
3000 options = qdict_new();
3001 qdict_put_str(options, "driver", "qcow2");
3002 qdict_put_str(options, "file", bs->node_name);
3003 blk = blk_new_open(NULL, NULL, options,
3004 BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_NO_FLUSH,
3005 &local_err);
3006 if (blk == NULL) {
3007 error_propagate(errp, local_err);
3008 ret = -EIO;
3009 goto out;
3012 ret = qcow2_alloc_clusters(blk_bs(blk), 3 * cluster_size);
3013 if (ret < 0) {
3014 error_setg_errno(errp, -ret, "Could not allocate clusters for qcow2 "
3015 "header and refcount table");
3016 goto out;
3018 } else if (ret != 0) {
3019 error_report("Huh, first cluster in empty image is already in use?");
3020 abort();
3023 /* Create a full header (including things like feature table) */
3024 ret = qcow2_update_header(blk_bs(blk));
3025 if (ret < 0) {
3026 error_setg_errno(errp, -ret, "Could not update qcow2 header");
3027 goto out;
3030 /* Okay, now that we have a valid image, let's give it the right size */
3031 ret = blk_truncate(blk, qcow2_opts->size, PREALLOC_MODE_OFF, errp);
3032 if (ret < 0) {
3033 error_prepend(errp, "Could not resize image: ");
3034 goto out;
3037 /* Want a backing file? There you go.*/
3038 if (qcow2_opts->has_backing_file) {
3039 const char *backing_format = NULL;
3041 if (qcow2_opts->has_backing_fmt) {
3042 backing_format = BlockdevDriver_str(qcow2_opts->backing_fmt);
3045 ret = bdrv_change_backing_file(blk_bs(blk), qcow2_opts->backing_file,
3046 backing_format);
3047 if (ret < 0) {
3048 error_setg_errno(errp, -ret, "Could not assign backing file '%s' "
3049 "with format '%s'", qcow2_opts->backing_file,
3050 backing_format);
3051 goto out;
3055 /* Want encryption? There you go. */
3056 if (qcow2_opts->has_encrypt) {
3057 ret = qcow2_set_up_encryption(blk_bs(blk), qcow2_opts->encrypt, errp);
3058 if (ret < 0) {
3059 goto out;
3063 /* And if we're supposed to preallocate metadata, do that now */
3064 if (qcow2_opts->preallocation != PREALLOC_MODE_OFF) {
3065 BDRVQcow2State *s = blk_bs(blk)->opaque;
3066 qemu_co_mutex_lock(&s->lock);
3067 ret = preallocate_co(blk_bs(blk), 0, qcow2_opts->size);
3068 qemu_co_mutex_unlock(&s->lock);
3070 if (ret < 0) {
3071 error_setg_errno(errp, -ret, "Could not preallocate metadata");
3072 goto out;
3076 blk_unref(blk);
3077 blk = NULL;
3079 /* Reopen the image without BDRV_O_NO_FLUSH to flush it before returning.
3080 * Using BDRV_O_NO_IO, since encryption is now setup we don't want to
3081 * have to setup decryption context. We're not doing any I/O on the top
3082 * level BlockDriverState, only lower layers, where BDRV_O_NO_IO does
3083 * not have effect.
3085 options = qdict_new();
3086 qdict_put_str(options, "driver", "qcow2");
3087 qdict_put_str(options, "file", bs->node_name);
3088 blk = blk_new_open(NULL, NULL, options,
3089 BDRV_O_RDWR | BDRV_O_NO_BACKING | BDRV_O_NO_IO,
3090 &local_err);
3091 if (blk == NULL) {
3092 error_propagate(errp, local_err);
3093 ret = -EIO;
3094 goto out;
3097 ret = 0;
3098 out:
3099 blk_unref(blk);
3100 bdrv_unref(bs);
3101 return ret;
3104 static int coroutine_fn qcow2_co_create_opts(const char *filename, QemuOpts *opts,
3105 Error **errp)
3107 BlockdevCreateOptions *create_options = NULL;
3108 QDict *qdict;
3109 Visitor *v;
3110 BlockDriverState *bs = NULL;
3111 Error *local_err = NULL;
3112 const char *val;
3113 int ret;
3115 /* Only the keyval visitor supports the dotted syntax needed for
3116 * encryption, so go through a QDict before getting a QAPI type. Ignore
3117 * options meant for the protocol layer so that the visitor doesn't
3118 * complain. */
3119 qdict = qemu_opts_to_qdict_filtered(opts, NULL, bdrv_qcow2.create_opts,
3120 true);
3122 /* Handle encryption options */
3123 val = qdict_get_try_str(qdict, BLOCK_OPT_ENCRYPT);
3124 if (val && !strcmp(val, "on")) {
3125 qdict_put_str(qdict, BLOCK_OPT_ENCRYPT, "qcow");
3126 } else if (val && !strcmp(val, "off")) {
3127 qdict_del(qdict, BLOCK_OPT_ENCRYPT);
3130 val = qdict_get_try_str(qdict, BLOCK_OPT_ENCRYPT_FORMAT);
3131 if (val && !strcmp(val, "aes")) {
3132 qdict_put_str(qdict, BLOCK_OPT_ENCRYPT_FORMAT, "qcow");
3135 /* Convert compat=0.10/1.1 into compat=v2/v3, to be renamed into
3136 * version=v2/v3 below. */
3137 val = qdict_get_try_str(qdict, BLOCK_OPT_COMPAT_LEVEL);
3138 if (val && !strcmp(val, "0.10")) {
3139 qdict_put_str(qdict, BLOCK_OPT_COMPAT_LEVEL, "v2");
3140 } else if (val && !strcmp(val, "1.1")) {
3141 qdict_put_str(qdict, BLOCK_OPT_COMPAT_LEVEL, "v3");
3144 /* Change legacy command line options into QMP ones */
3145 static const QDictRenames opt_renames[] = {
3146 { BLOCK_OPT_BACKING_FILE, "backing-file" },
3147 { BLOCK_OPT_BACKING_FMT, "backing-fmt" },
3148 { BLOCK_OPT_CLUSTER_SIZE, "cluster-size" },
3149 { BLOCK_OPT_LAZY_REFCOUNTS, "lazy-refcounts" },
3150 { BLOCK_OPT_REFCOUNT_BITS, "refcount-bits" },
3151 { BLOCK_OPT_ENCRYPT, BLOCK_OPT_ENCRYPT_FORMAT },
3152 { BLOCK_OPT_COMPAT_LEVEL, "version" },
3153 { NULL, NULL },
3156 if (!qdict_rename_keys(qdict, opt_renames, errp)) {
3157 ret = -EINVAL;
3158 goto finish;
3161 /* Create and open the file (protocol layer) */
3162 ret = bdrv_create_file(filename, opts, errp);
3163 if (ret < 0) {
3164 goto finish;
3167 bs = bdrv_open(filename, NULL, NULL,
3168 BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_PROTOCOL, errp);
3169 if (bs == NULL) {
3170 ret = -EIO;
3171 goto finish;
3174 /* Set 'driver' and 'node' options */
3175 qdict_put_str(qdict, "driver", "qcow2");
3176 qdict_put_str(qdict, "file", bs->node_name);
3178 /* Now get the QAPI type BlockdevCreateOptions */
3179 v = qobject_input_visitor_new_flat_confused(qdict, errp);
3180 if (!v) {
3181 ret = -EINVAL;
3182 goto finish;
3185 visit_type_BlockdevCreateOptions(v, NULL, &create_options, &local_err);
3186 visit_free(v);
3188 if (local_err) {
3189 error_propagate(errp, local_err);
3190 ret = -EINVAL;
3191 goto finish;
3194 /* Silently round up size */
3195 create_options->u.qcow2.size = ROUND_UP(create_options->u.qcow2.size,
3196 BDRV_SECTOR_SIZE);
3198 /* Create the qcow2 image (format layer) */
3199 ret = qcow2_co_create(create_options, errp);
3200 if (ret < 0) {
3201 goto finish;
3204 ret = 0;
3205 finish:
3206 qobject_unref(qdict);
3207 bdrv_unref(bs);
3208 qapi_free_BlockdevCreateOptions(create_options);
3209 return ret;
3213 static bool is_zero(BlockDriverState *bs, int64_t offset, int64_t bytes)
3215 int64_t nr;
3216 int res;
3218 /* Clamp to image length, before checking status of underlying sectors */
3219 if (offset + bytes > bs->total_sectors * BDRV_SECTOR_SIZE) {
3220 bytes = bs->total_sectors * BDRV_SECTOR_SIZE - offset;
3223 if (!bytes) {
3224 return true;
3226 res = bdrv_block_status_above(bs, NULL, offset, bytes, &nr, NULL, NULL);
3227 return res >= 0 && (res & BDRV_BLOCK_ZERO) && nr == bytes;
3230 static coroutine_fn int qcow2_co_pwrite_zeroes(BlockDriverState *bs,
3231 int64_t offset, int bytes, BdrvRequestFlags flags)
3233 int ret;
3234 BDRVQcow2State *s = bs->opaque;
3236 uint32_t head = offset % s->cluster_size;
3237 uint32_t tail = (offset + bytes) % s->cluster_size;
3239 trace_qcow2_pwrite_zeroes_start_req(qemu_coroutine_self(), offset, bytes);
3240 if (offset + bytes == bs->total_sectors * BDRV_SECTOR_SIZE) {
3241 tail = 0;
3244 if (head || tail) {
3245 uint64_t off;
3246 unsigned int nr;
3248 assert(head + bytes <= s->cluster_size);
3250 /* check whether remainder of cluster already reads as zero */
3251 if (!(is_zero(bs, offset - head, head) &&
3252 is_zero(bs, offset + bytes,
3253 tail ? s->cluster_size - tail : 0))) {
3254 return -ENOTSUP;
3257 qemu_co_mutex_lock(&s->lock);
3258 /* We can have new write after previous check */
3259 offset = QEMU_ALIGN_DOWN(offset, s->cluster_size);
3260 bytes = s->cluster_size;
3261 nr = s->cluster_size;
3262 ret = qcow2_get_cluster_offset(bs, offset, &nr, &off);
3263 if (ret != QCOW2_CLUSTER_UNALLOCATED &&
3264 ret != QCOW2_CLUSTER_ZERO_PLAIN &&
3265 ret != QCOW2_CLUSTER_ZERO_ALLOC) {
3266 qemu_co_mutex_unlock(&s->lock);
3267 return -ENOTSUP;
3269 } else {
3270 qemu_co_mutex_lock(&s->lock);
3273 trace_qcow2_pwrite_zeroes(qemu_coroutine_self(), offset, bytes);
3275 /* Whatever is left can use real zero clusters */
3276 ret = qcow2_cluster_zeroize(bs, offset, bytes, flags);
3277 qemu_co_mutex_unlock(&s->lock);
3279 return ret;
3282 static coroutine_fn int qcow2_co_pdiscard(BlockDriverState *bs,
3283 int64_t offset, int bytes)
3285 int ret;
3286 BDRVQcow2State *s = bs->opaque;
3288 if (!QEMU_IS_ALIGNED(offset | bytes, s->cluster_size)) {
3289 assert(bytes < s->cluster_size);
3290 /* Ignore partial clusters, except for the special case of the
3291 * complete partial cluster at the end of an unaligned file */
3292 if (!QEMU_IS_ALIGNED(offset, s->cluster_size) ||
3293 offset + bytes != bs->total_sectors * BDRV_SECTOR_SIZE) {
3294 return -ENOTSUP;
3298 qemu_co_mutex_lock(&s->lock);
3299 ret = qcow2_cluster_discard(bs, offset, bytes, QCOW2_DISCARD_REQUEST,
3300 false);
3301 qemu_co_mutex_unlock(&s->lock);
3302 return ret;
3305 static int coroutine_fn
3306 qcow2_co_copy_range_from(BlockDriverState *bs,
3307 BdrvChild *src, uint64_t src_offset,
3308 BdrvChild *dst, uint64_t dst_offset,
3309 uint64_t bytes, BdrvRequestFlags read_flags,
3310 BdrvRequestFlags write_flags)
3312 BDRVQcow2State *s = bs->opaque;
3313 int ret;
3314 unsigned int cur_bytes; /* number of bytes in current iteration */
3315 BdrvChild *child = NULL;
3316 BdrvRequestFlags cur_write_flags;
3318 assert(!bs->encrypted);
3319 qemu_co_mutex_lock(&s->lock);
3321 while (bytes != 0) {
3322 uint64_t copy_offset = 0;
3323 /* prepare next request */
3324 cur_bytes = MIN(bytes, INT_MAX);
3325 cur_write_flags = write_flags;
3327 ret = qcow2_get_cluster_offset(bs, src_offset, &cur_bytes, &copy_offset);
3328 if (ret < 0) {
3329 goto out;
3332 switch (ret) {
3333 case QCOW2_CLUSTER_UNALLOCATED:
3334 if (bs->backing && bs->backing->bs) {
3335 int64_t backing_length = bdrv_getlength(bs->backing->bs);
3336 if (src_offset >= backing_length) {
3337 cur_write_flags |= BDRV_REQ_ZERO_WRITE;
3338 } else {
3339 child = bs->backing;
3340 cur_bytes = MIN(cur_bytes, backing_length - src_offset);
3341 copy_offset = src_offset;
3343 } else {
3344 cur_write_flags |= BDRV_REQ_ZERO_WRITE;
3346 break;
3348 case QCOW2_CLUSTER_ZERO_PLAIN:
3349 case QCOW2_CLUSTER_ZERO_ALLOC:
3350 cur_write_flags |= BDRV_REQ_ZERO_WRITE;
3351 break;
3353 case QCOW2_CLUSTER_COMPRESSED:
3354 ret = -ENOTSUP;
3355 goto out;
3357 case QCOW2_CLUSTER_NORMAL:
3358 child = bs->file;
3359 copy_offset += offset_into_cluster(s, src_offset);
3360 if ((copy_offset & 511) != 0) {
3361 ret = -EIO;
3362 goto out;
3364 break;
3366 default:
3367 abort();
3369 qemu_co_mutex_unlock(&s->lock);
3370 ret = bdrv_co_copy_range_from(child,
3371 copy_offset,
3372 dst, dst_offset,
3373 cur_bytes, read_flags, cur_write_flags);
3374 qemu_co_mutex_lock(&s->lock);
3375 if (ret < 0) {
3376 goto out;
3379 bytes -= cur_bytes;
3380 src_offset += cur_bytes;
3381 dst_offset += cur_bytes;
3383 ret = 0;
3385 out:
3386 qemu_co_mutex_unlock(&s->lock);
3387 return ret;
3390 static int coroutine_fn
3391 qcow2_co_copy_range_to(BlockDriverState *bs,
3392 BdrvChild *src, uint64_t src_offset,
3393 BdrvChild *dst, uint64_t dst_offset,
3394 uint64_t bytes, BdrvRequestFlags read_flags,
3395 BdrvRequestFlags write_flags)
3397 BDRVQcow2State *s = bs->opaque;
3398 int offset_in_cluster;
3399 int ret;
3400 unsigned int cur_bytes; /* number of sectors in current iteration */
3401 uint64_t cluster_offset;
3402 QCowL2Meta *l2meta = NULL;
3404 assert(!bs->encrypted);
3405 s->cluster_cache_offset = -1; /* disable compressed cache */
3407 qemu_co_mutex_lock(&s->lock);
3409 while (bytes != 0) {
3411 l2meta = NULL;
3413 offset_in_cluster = offset_into_cluster(s, dst_offset);
3414 cur_bytes = MIN(bytes, INT_MAX);
3416 /* TODO:
3417 * If src->bs == dst->bs, we could simply copy by incrementing
3418 * the refcnt, without copying user data.
3419 * Or if src->bs == dst->bs->backing->bs, we could copy by discarding. */
3420 ret = qcow2_alloc_cluster_offset(bs, dst_offset, &cur_bytes,
3421 &cluster_offset, &l2meta);
3422 if (ret < 0) {
3423 goto fail;
3426 assert((cluster_offset & 511) == 0);
3428 ret = qcow2_pre_write_overlap_check(bs, 0,
3429 cluster_offset + offset_in_cluster, cur_bytes);
3430 if (ret < 0) {
3431 goto fail;
3434 qemu_co_mutex_unlock(&s->lock);
3435 ret = bdrv_co_copy_range_to(src, src_offset,
3436 bs->file,
3437 cluster_offset + offset_in_cluster,
3438 cur_bytes, read_flags, write_flags);
3439 qemu_co_mutex_lock(&s->lock);
3440 if (ret < 0) {
3441 goto fail;
3444 ret = qcow2_handle_l2meta(bs, &l2meta, true);
3445 if (ret) {
3446 goto fail;
3449 bytes -= cur_bytes;
3450 src_offset += cur_bytes;
3451 dst_offset += cur_bytes;
3453 ret = 0;
3455 fail:
3456 qcow2_handle_l2meta(bs, &l2meta, false);
3458 qemu_co_mutex_unlock(&s->lock);
3460 trace_qcow2_writev_done_req(qemu_coroutine_self(), ret);
3462 return ret;
3465 static int coroutine_fn qcow2_co_truncate(BlockDriverState *bs, int64_t offset,
3466 PreallocMode prealloc, Error **errp)
3468 BDRVQcow2State *s = bs->opaque;
3469 uint64_t old_length;
3470 int64_t new_l1_size;
3471 int ret;
3472 QDict *options;
3474 if (prealloc != PREALLOC_MODE_OFF && prealloc != PREALLOC_MODE_METADATA &&
3475 prealloc != PREALLOC_MODE_FALLOC && prealloc != PREALLOC_MODE_FULL)
3477 error_setg(errp, "Unsupported preallocation mode '%s'",
3478 PreallocMode_str(prealloc));
3479 return -ENOTSUP;
3482 if (offset & 511) {
3483 error_setg(errp, "The new size must be a multiple of 512");
3484 return -EINVAL;
3487 qemu_co_mutex_lock(&s->lock);
3489 /* cannot proceed if image has snapshots */
3490 if (s->nb_snapshots) {
3491 error_setg(errp, "Can't resize an image which has snapshots");
3492 ret = -ENOTSUP;
3493 goto fail;
3496 /* cannot proceed if image has bitmaps */
3497 if (s->nb_bitmaps) {
3498 /* TODO: resize bitmaps in the image */
3499 error_setg(errp, "Can't resize an image which has bitmaps");
3500 ret = -ENOTSUP;
3501 goto fail;
3504 old_length = bs->total_sectors * BDRV_SECTOR_SIZE;
3505 new_l1_size = size_to_l1(s, offset);
3507 if (offset < old_length) {
3508 int64_t last_cluster, old_file_size;
3509 if (prealloc != PREALLOC_MODE_OFF) {
3510 error_setg(errp,
3511 "Preallocation can't be used for shrinking an image");
3512 ret = -EINVAL;
3513 goto fail;
3516 ret = qcow2_cluster_discard(bs, ROUND_UP(offset, s->cluster_size),
3517 old_length - ROUND_UP(offset,
3518 s->cluster_size),
3519 QCOW2_DISCARD_ALWAYS, true);
3520 if (ret < 0) {
3521 error_setg_errno(errp, -ret, "Failed to discard cropped clusters");
3522 goto fail;
3525 ret = qcow2_shrink_l1_table(bs, new_l1_size);
3526 if (ret < 0) {
3527 error_setg_errno(errp, -ret,
3528 "Failed to reduce the number of L2 tables");
3529 goto fail;
3532 ret = qcow2_shrink_reftable(bs);
3533 if (ret < 0) {
3534 error_setg_errno(errp, -ret,
3535 "Failed to discard unused refblocks");
3536 goto fail;
3539 old_file_size = bdrv_getlength(bs->file->bs);
3540 if (old_file_size < 0) {
3541 error_setg_errno(errp, -old_file_size,
3542 "Failed to inquire current file length");
3543 ret = old_file_size;
3544 goto fail;
3546 last_cluster = qcow2_get_last_cluster(bs, old_file_size);
3547 if (last_cluster < 0) {
3548 error_setg_errno(errp, -last_cluster,
3549 "Failed to find the last cluster");
3550 ret = last_cluster;
3551 goto fail;
3553 if ((last_cluster + 1) * s->cluster_size < old_file_size) {
3554 Error *local_err = NULL;
3556 bdrv_co_truncate(bs->file, (last_cluster + 1) * s->cluster_size,
3557 PREALLOC_MODE_OFF, &local_err);
3558 if (local_err) {
3559 warn_reportf_err(local_err,
3560 "Failed to truncate the tail of the image: ");
3563 } else {
3564 ret = qcow2_grow_l1_table(bs, new_l1_size, true);
3565 if (ret < 0) {
3566 error_setg_errno(errp, -ret, "Failed to grow the L1 table");
3567 goto fail;
3571 switch (prealloc) {
3572 case PREALLOC_MODE_OFF:
3573 break;
3575 case PREALLOC_MODE_METADATA:
3576 ret = preallocate_co(bs, old_length, offset);
3577 if (ret < 0) {
3578 error_setg_errno(errp, -ret, "Preallocation failed");
3579 goto fail;
3581 break;
3583 case PREALLOC_MODE_FALLOC:
3584 case PREALLOC_MODE_FULL:
3586 int64_t allocation_start, host_offset, guest_offset;
3587 int64_t clusters_allocated;
3588 int64_t old_file_size, new_file_size;
3589 uint64_t nb_new_data_clusters, nb_new_l2_tables;
3591 old_file_size = bdrv_getlength(bs->file->bs);
3592 if (old_file_size < 0) {
3593 error_setg_errno(errp, -old_file_size,
3594 "Failed to inquire current file length");
3595 ret = old_file_size;
3596 goto fail;
3598 old_file_size = ROUND_UP(old_file_size, s->cluster_size);
3600 nb_new_data_clusters = DIV_ROUND_UP(offset - old_length,
3601 s->cluster_size);
3603 /* This is an overestimation; we will not actually allocate space for
3604 * these in the file but just make sure the new refcount structures are
3605 * able to cover them so we will not have to allocate new refblocks
3606 * while entering the data blocks in the potentially new L2 tables.
3607 * (We do not actually care where the L2 tables are placed. Maybe they
3608 * are already allocated or they can be placed somewhere before
3609 * @old_file_size. It does not matter because they will be fully
3610 * allocated automatically, so they do not need to be covered by the
3611 * preallocation. All that matters is that we will not have to allocate
3612 * new refcount structures for them.) */
3613 nb_new_l2_tables = DIV_ROUND_UP(nb_new_data_clusters,
3614 s->cluster_size / sizeof(uint64_t));
3615 /* The cluster range may not be aligned to L2 boundaries, so add one L2
3616 * table for a potential head/tail */
3617 nb_new_l2_tables++;
3619 allocation_start = qcow2_refcount_area(bs, old_file_size,
3620 nb_new_data_clusters +
3621 nb_new_l2_tables,
3622 true, 0, 0);
3623 if (allocation_start < 0) {
3624 error_setg_errno(errp, -allocation_start,
3625 "Failed to resize refcount structures");
3626 ret = allocation_start;
3627 goto fail;
3630 clusters_allocated = qcow2_alloc_clusters_at(bs, allocation_start,
3631 nb_new_data_clusters);
3632 if (clusters_allocated < 0) {
3633 error_setg_errno(errp, -clusters_allocated,
3634 "Failed to allocate data clusters");
3635 ret = clusters_allocated;
3636 goto fail;
3639 assert(clusters_allocated == nb_new_data_clusters);
3641 /* Allocate the data area */
3642 new_file_size = allocation_start +
3643 nb_new_data_clusters * s->cluster_size;
3644 ret = bdrv_co_truncate(bs->file, new_file_size, prealloc, errp);
3645 if (ret < 0) {
3646 error_prepend(errp, "Failed to resize underlying file: ");
3647 qcow2_free_clusters(bs, allocation_start,
3648 nb_new_data_clusters * s->cluster_size,
3649 QCOW2_DISCARD_OTHER);
3650 goto fail;
3653 /* Create the necessary L2 entries */
3654 host_offset = allocation_start;
3655 guest_offset = old_length;
3656 while (nb_new_data_clusters) {
3657 int64_t nb_clusters = MIN(
3658 nb_new_data_clusters,
3659 s->l2_slice_size - offset_to_l2_slice_index(s, guest_offset));
3660 QCowL2Meta allocation = {
3661 .offset = guest_offset,
3662 .alloc_offset = host_offset,
3663 .nb_clusters = nb_clusters,
3665 qemu_co_queue_init(&allocation.dependent_requests);
3667 ret = qcow2_alloc_cluster_link_l2(bs, &allocation);
3668 if (ret < 0) {
3669 error_setg_errno(errp, -ret, "Failed to update L2 tables");
3670 qcow2_free_clusters(bs, host_offset,
3671 nb_new_data_clusters * s->cluster_size,
3672 QCOW2_DISCARD_OTHER);
3673 goto fail;
3676 guest_offset += nb_clusters * s->cluster_size;
3677 host_offset += nb_clusters * s->cluster_size;
3678 nb_new_data_clusters -= nb_clusters;
3680 break;
3683 default:
3684 g_assert_not_reached();
3687 if (prealloc != PREALLOC_MODE_OFF) {
3688 /* Flush metadata before actually changing the image size */
3689 ret = qcow2_write_caches(bs);
3690 if (ret < 0) {
3691 error_setg_errno(errp, -ret,
3692 "Failed to flush the preallocated area to disk");
3693 goto fail;
3697 bs->total_sectors = offset / BDRV_SECTOR_SIZE;
3699 /* write updated header.size */
3700 offset = cpu_to_be64(offset);
3701 ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, size),
3702 &offset, sizeof(uint64_t));
3703 if (ret < 0) {
3704 error_setg_errno(errp, -ret, "Failed to update the image size");
3705 goto fail;
3708 s->l1_vm_state_index = new_l1_size;
3710 /* Update cache sizes */
3711 options = qdict_clone_shallow(bs->options);
3712 ret = qcow2_update_options(bs, options, s->flags, errp);
3713 qobject_unref(options);
3714 if (ret < 0) {
3715 goto fail;
3717 ret = 0;
3718 fail:
3719 qemu_co_mutex_unlock(&s->lock);
3720 return ret;
3724 * qcow2_compress()
3726 * @dest - destination buffer, at least of @size-1 bytes
3727 * @src - source buffer, @size bytes
3729 * Returns: compressed size on success
3730 * -1 if compression is inefficient
3731 * -2 on any other error
3733 static ssize_t qcow2_compress(void *dest, const void *src, size_t size)
3735 ssize_t ret;
3736 z_stream strm;
3738 /* best compression, small window, no zlib header */
3739 memset(&strm, 0, sizeof(strm));
3740 ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION, Z_DEFLATED,
3741 -12, 9, Z_DEFAULT_STRATEGY);
3742 if (ret != 0) {
3743 return -2;
3746 /* strm.next_in is not const in old zlib versions, such as those used on
3747 * OpenBSD/NetBSD, so cast the const away */
3748 strm.avail_in = size;
3749 strm.next_in = (void *) src;
3750 strm.avail_out = size - 1;
3751 strm.next_out = dest;
3753 ret = deflate(&strm, Z_FINISH);
3754 if (ret == Z_STREAM_END) {
3755 ret = size - 1 - strm.avail_out;
3756 } else {
3757 ret = (ret == Z_OK ? -1 : -2);
3760 deflateEnd(&strm);
3762 return ret;
3765 #define MAX_COMPRESS_THREADS 4
3767 typedef struct Qcow2CompressData {
3768 void *dest;
3769 const void *src;
3770 size_t size;
3771 ssize_t ret;
3772 } Qcow2CompressData;
3774 static int qcow2_compress_pool_func(void *opaque)
3776 Qcow2CompressData *data = opaque;
3778 data->ret = qcow2_compress(data->dest, data->src, data->size);
3780 return 0;
3783 static void qcow2_compress_complete(void *opaque, int ret)
3785 qemu_coroutine_enter(opaque);
3788 /* See qcow2_compress definition for parameters description */
3789 static ssize_t qcow2_co_compress(BlockDriverState *bs,
3790 void *dest, const void *src, size_t size)
3792 BDRVQcow2State *s = bs->opaque;
3793 BlockAIOCB *acb;
3794 ThreadPool *pool = aio_get_thread_pool(bdrv_get_aio_context(bs));
3795 Qcow2CompressData arg = {
3796 .dest = dest,
3797 .src = src,
3798 .size = size,
3801 while (s->nb_compress_threads >= MAX_COMPRESS_THREADS) {
3802 qemu_co_queue_wait(&s->compress_wait_queue, NULL);
3805 s->nb_compress_threads++;
3806 acb = thread_pool_submit_aio(pool, qcow2_compress_pool_func, &arg,
3807 qcow2_compress_complete,
3808 qemu_coroutine_self());
3810 if (!acb) {
3811 s->nb_compress_threads--;
3812 return -EINVAL;
3814 qemu_coroutine_yield();
3815 s->nb_compress_threads--;
3816 qemu_co_queue_next(&s->compress_wait_queue);
3818 return arg.ret;
3821 /* XXX: put compressed sectors first, then all the cluster aligned
3822 tables to avoid losing bytes in alignment */
3823 static coroutine_fn int
3824 qcow2_co_pwritev_compressed(BlockDriverState *bs, uint64_t offset,
3825 uint64_t bytes, QEMUIOVector *qiov)
3827 BDRVQcow2State *s = bs->opaque;
3828 QEMUIOVector hd_qiov;
3829 struct iovec iov;
3830 int ret;
3831 size_t out_len;
3832 uint8_t *buf, *out_buf;
3833 int64_t cluster_offset;
3835 if (bytes == 0) {
3836 /* align end of file to a sector boundary to ease reading with
3837 sector based I/Os */
3838 cluster_offset = bdrv_getlength(bs->file->bs);
3839 if (cluster_offset < 0) {
3840 return cluster_offset;
3842 return bdrv_co_truncate(bs->file, cluster_offset, PREALLOC_MODE_OFF,
3843 NULL);
3846 if (offset_into_cluster(s, offset)) {
3847 return -EINVAL;
3850 buf = qemu_blockalign(bs, s->cluster_size);
3851 if (bytes != s->cluster_size) {
3852 if (bytes > s->cluster_size ||
3853 offset + bytes != bs->total_sectors << BDRV_SECTOR_BITS)
3855 qemu_vfree(buf);
3856 return -EINVAL;
3858 /* Zero-pad last write if image size is not cluster aligned */
3859 memset(buf + bytes, 0, s->cluster_size - bytes);
3861 qemu_iovec_to_buf(qiov, 0, buf, bytes);
3863 out_buf = g_malloc(s->cluster_size);
3865 out_len = qcow2_co_compress(bs, out_buf, buf, s->cluster_size);
3866 if (out_len == -2) {
3867 ret = -EINVAL;
3868 goto fail;
3869 } else if (out_len == -1) {
3870 /* could not compress: write normal cluster */
3871 ret = qcow2_co_pwritev(bs, offset, bytes, qiov, 0);
3872 if (ret < 0) {
3873 goto fail;
3875 goto success;
3878 qemu_co_mutex_lock(&s->lock);
3879 cluster_offset =
3880 qcow2_alloc_compressed_cluster_offset(bs, offset, out_len);
3881 if (!cluster_offset) {
3882 qemu_co_mutex_unlock(&s->lock);
3883 ret = -EIO;
3884 goto fail;
3886 cluster_offset &= s->cluster_offset_mask;
3888 ret = qcow2_pre_write_overlap_check(bs, 0, cluster_offset, out_len);
3889 qemu_co_mutex_unlock(&s->lock);
3890 if (ret < 0) {
3891 goto fail;
3894 iov = (struct iovec) {
3895 .iov_base = out_buf,
3896 .iov_len = out_len,
3898 qemu_iovec_init_external(&hd_qiov, &iov, 1);
3900 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_COMPRESSED);
3901 ret = bdrv_co_pwritev(bs->file, cluster_offset, out_len, &hd_qiov, 0);
3902 if (ret < 0) {
3903 goto fail;
3905 success:
3906 ret = 0;
3907 fail:
3908 qemu_vfree(buf);
3909 g_free(out_buf);
3910 return ret;
3913 static int make_completely_empty(BlockDriverState *bs)
3915 BDRVQcow2State *s = bs->opaque;
3916 Error *local_err = NULL;
3917 int ret, l1_clusters;
3918 int64_t offset;
3919 uint64_t *new_reftable = NULL;
3920 uint64_t rt_entry, l1_size2;
3921 struct {
3922 uint64_t l1_offset;
3923 uint64_t reftable_offset;
3924 uint32_t reftable_clusters;
3925 } QEMU_PACKED l1_ofs_rt_ofs_cls;
3927 ret = qcow2_cache_empty(bs, s->l2_table_cache);
3928 if (ret < 0) {
3929 goto fail;
3932 ret = qcow2_cache_empty(bs, s->refcount_block_cache);
3933 if (ret < 0) {
3934 goto fail;
3937 /* Refcounts will be broken utterly */
3938 ret = qcow2_mark_dirty(bs);
3939 if (ret < 0) {
3940 goto fail;
3943 BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
3945 l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / sizeof(uint64_t));
3946 l1_size2 = (uint64_t)s->l1_size * sizeof(uint64_t);
3948 /* After this call, neither the in-memory nor the on-disk refcount
3949 * information accurately describe the actual references */
3951 ret = bdrv_pwrite_zeroes(bs->file, s->l1_table_offset,
3952 l1_clusters * s->cluster_size, 0);
3953 if (ret < 0) {
3954 goto fail_broken_refcounts;
3956 memset(s->l1_table, 0, l1_size2);
3958 BLKDBG_EVENT(bs->file, BLKDBG_EMPTY_IMAGE_PREPARE);
3960 /* Overwrite enough clusters at the beginning of the sectors to place
3961 * the refcount table, a refcount block and the L1 table in; this may
3962 * overwrite parts of the existing refcount and L1 table, which is not
3963 * an issue because the dirty flag is set, complete data loss is in fact
3964 * desired and partial data loss is consequently fine as well */
3965 ret = bdrv_pwrite_zeroes(bs->file, s->cluster_size,
3966 (2 + l1_clusters) * s->cluster_size, 0);
3967 /* This call (even if it failed overall) may have overwritten on-disk
3968 * refcount structures; in that case, the in-memory refcount information
3969 * will probably differ from the on-disk information which makes the BDS
3970 * unusable */
3971 if (ret < 0) {
3972 goto fail_broken_refcounts;
3975 BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
3976 BLKDBG_EVENT(bs->file, BLKDBG_REFTABLE_UPDATE);
3978 /* "Create" an empty reftable (one cluster) directly after the image
3979 * header and an empty L1 table three clusters after the image header;
3980 * the cluster between those two will be used as the first refblock */
3981 l1_ofs_rt_ofs_cls.l1_offset = cpu_to_be64(3 * s->cluster_size);
3982 l1_ofs_rt_ofs_cls.reftable_offset = cpu_to_be64(s->cluster_size);
3983 l1_ofs_rt_ofs_cls.reftable_clusters = cpu_to_be32(1);
3984 ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, l1_table_offset),
3985 &l1_ofs_rt_ofs_cls, sizeof(l1_ofs_rt_ofs_cls));
3986 if (ret < 0) {
3987 goto fail_broken_refcounts;
3990 s->l1_table_offset = 3 * s->cluster_size;
3992 new_reftable = g_try_new0(uint64_t, s->cluster_size / sizeof(uint64_t));
3993 if (!new_reftable) {
3994 ret = -ENOMEM;
3995 goto fail_broken_refcounts;
3998 s->refcount_table_offset = s->cluster_size;
3999 s->refcount_table_size = s->cluster_size / sizeof(uint64_t);
4000 s->max_refcount_table_index = 0;
4002 g_free(s->refcount_table);
4003 s->refcount_table = new_reftable;
4004 new_reftable = NULL;
4006 /* Now the in-memory refcount information again corresponds to the on-disk
4007 * information (reftable is empty and no refblocks (the refblock cache is
4008 * empty)); however, this means some clusters (e.g. the image header) are
4009 * referenced, but not refcounted, but the normal qcow2 code assumes that
4010 * the in-memory information is always correct */
4012 BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_ALLOC);
4014 /* Enter the first refblock into the reftable */
4015 rt_entry = cpu_to_be64(2 * s->cluster_size);
4016 ret = bdrv_pwrite_sync(bs->file, s->cluster_size,
4017 &rt_entry, sizeof(rt_entry));
4018 if (ret < 0) {
4019 goto fail_broken_refcounts;
4021 s->refcount_table[0] = 2 * s->cluster_size;
4023 s->free_cluster_index = 0;
4024 assert(3 + l1_clusters <= s->refcount_block_size);
4025 offset = qcow2_alloc_clusters(bs, 3 * s->cluster_size + l1_size2);
4026 if (offset < 0) {
4027 ret = offset;
4028 goto fail_broken_refcounts;
4029 } else if (offset > 0) {
4030 error_report("First cluster in emptied image is in use");
4031 abort();
4034 /* Now finally the in-memory information corresponds to the on-disk
4035 * structures and is correct */
4036 ret = qcow2_mark_clean(bs);
4037 if (ret < 0) {
4038 goto fail;
4041 ret = bdrv_truncate(bs->file, (3 + l1_clusters) * s->cluster_size,
4042 PREALLOC_MODE_OFF, &local_err);
4043 if (ret < 0) {
4044 error_report_err(local_err);
4045 goto fail;
4048 return 0;
4050 fail_broken_refcounts:
4051 /* The BDS is unusable at this point. If we wanted to make it usable, we
4052 * would have to call qcow2_refcount_close(), qcow2_refcount_init(),
4053 * qcow2_check_refcounts(), qcow2_refcount_close() and qcow2_refcount_init()
4054 * again. However, because the functions which could have caused this error
4055 * path to be taken are used by those functions as well, it's very likely
4056 * that that sequence will fail as well. Therefore, just eject the BDS. */
4057 bs->drv = NULL;
4059 fail:
4060 g_free(new_reftable);
4061 return ret;
4064 static int qcow2_make_empty(BlockDriverState *bs)
4066 BDRVQcow2State *s = bs->opaque;
4067 uint64_t offset, end_offset;
4068 int step = QEMU_ALIGN_DOWN(INT_MAX, s->cluster_size);
4069 int l1_clusters, ret = 0;
4071 l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / sizeof(uint64_t));
4073 if (s->qcow_version >= 3 && !s->snapshots && !s->nb_bitmaps &&
4074 3 + l1_clusters <= s->refcount_block_size &&
4075 s->crypt_method_header != QCOW_CRYPT_LUKS) {
4076 /* The following function only works for qcow2 v3 images (it
4077 * requires the dirty flag) and only as long as there are no
4078 * features that reserve extra clusters (such as snapshots,
4079 * LUKS header, or persistent bitmaps), because it completely
4080 * empties the image. Furthermore, the L1 table and three
4081 * additional clusters (image header, refcount table, one
4082 * refcount block) have to fit inside one refcount block. */
4083 return make_completely_empty(bs);
4086 /* This fallback code simply discards every active cluster; this is slow,
4087 * but works in all cases */
4088 end_offset = bs->total_sectors * BDRV_SECTOR_SIZE;
4089 for (offset = 0; offset < end_offset; offset += step) {
4090 /* As this function is generally used after committing an external
4091 * snapshot, QCOW2_DISCARD_SNAPSHOT seems appropriate. Also, the
4092 * default action for this kind of discard is to pass the discard,
4093 * which will ideally result in an actually smaller image file, as
4094 * is probably desired. */
4095 ret = qcow2_cluster_discard(bs, offset, MIN(step, end_offset - offset),
4096 QCOW2_DISCARD_SNAPSHOT, true);
4097 if (ret < 0) {
4098 break;
4102 return ret;
4105 static coroutine_fn int qcow2_co_flush_to_os(BlockDriverState *bs)
4107 BDRVQcow2State *s = bs->opaque;
4108 int ret;
4110 qemu_co_mutex_lock(&s->lock);
4111 ret = qcow2_write_caches(bs);
4112 qemu_co_mutex_unlock(&s->lock);
4114 return ret;
4117 static BlockMeasureInfo *qcow2_measure(QemuOpts *opts, BlockDriverState *in_bs,
4118 Error **errp)
4120 Error *local_err = NULL;
4121 BlockMeasureInfo *info;
4122 uint64_t required = 0; /* bytes that contribute to required size */
4123 uint64_t virtual_size; /* disk size as seen by guest */
4124 uint64_t refcount_bits;
4125 uint64_t l2_tables;
4126 size_t cluster_size;
4127 int version;
4128 char *optstr;
4129 PreallocMode prealloc;
4130 bool has_backing_file;
4132 /* Parse image creation options */
4133 cluster_size = qcow2_opt_get_cluster_size_del(opts, &local_err);
4134 if (local_err) {
4135 goto err;
4138 version = qcow2_opt_get_version_del(opts, &local_err);
4139 if (local_err) {
4140 goto err;
4143 refcount_bits = qcow2_opt_get_refcount_bits_del(opts, version, &local_err);
4144 if (local_err) {
4145 goto err;
4148 optstr = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
4149 prealloc = qapi_enum_parse(&PreallocMode_lookup, optstr,
4150 PREALLOC_MODE_OFF, &local_err);
4151 g_free(optstr);
4152 if (local_err) {
4153 goto err;
4156 optstr = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
4157 has_backing_file = !!optstr;
4158 g_free(optstr);
4160 virtual_size = qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0);
4161 virtual_size = ROUND_UP(virtual_size, cluster_size);
4163 /* Check that virtual disk size is valid */
4164 l2_tables = DIV_ROUND_UP(virtual_size / cluster_size,
4165 cluster_size / sizeof(uint64_t));
4166 if (l2_tables * sizeof(uint64_t) > QCOW_MAX_L1_SIZE) {
4167 error_setg(&local_err, "The image size is too large "
4168 "(try using a larger cluster size)");
4169 goto err;
4172 /* Account for input image */
4173 if (in_bs) {
4174 int64_t ssize = bdrv_getlength(in_bs);
4175 if (ssize < 0) {
4176 error_setg_errno(&local_err, -ssize,
4177 "Unable to get image virtual_size");
4178 goto err;
4181 virtual_size = ROUND_UP(ssize, cluster_size);
4183 if (has_backing_file) {
4184 /* We don't how much of the backing chain is shared by the input
4185 * image and the new image file. In the worst case the new image's
4186 * backing file has nothing in common with the input image. Be
4187 * conservative and assume all clusters need to be written.
4189 required = virtual_size;
4190 } else {
4191 int64_t offset;
4192 int64_t pnum = 0;
4194 for (offset = 0; offset < ssize; offset += pnum) {
4195 int ret;
4197 ret = bdrv_block_status_above(in_bs, NULL, offset,
4198 ssize - offset, &pnum, NULL,
4199 NULL);
4200 if (ret < 0) {
4201 error_setg_errno(&local_err, -ret,
4202 "Unable to get block status");
4203 goto err;
4206 if (ret & BDRV_BLOCK_ZERO) {
4207 /* Skip zero regions (safe with no backing file) */
4208 } else if ((ret & (BDRV_BLOCK_DATA | BDRV_BLOCK_ALLOCATED)) ==
4209 (BDRV_BLOCK_DATA | BDRV_BLOCK_ALLOCATED)) {
4210 /* Extend pnum to end of cluster for next iteration */
4211 pnum = ROUND_UP(offset + pnum, cluster_size) - offset;
4213 /* Count clusters we've seen */
4214 required += offset % cluster_size + pnum;
4220 /* Take into account preallocation. Nothing special is needed for
4221 * PREALLOC_MODE_METADATA since metadata is always counted.
4223 if (prealloc == PREALLOC_MODE_FULL || prealloc == PREALLOC_MODE_FALLOC) {
4224 required = virtual_size;
4227 info = g_new(BlockMeasureInfo, 1);
4228 info->fully_allocated =
4229 qcow2_calc_prealloc_size(virtual_size, cluster_size,
4230 ctz32(refcount_bits));
4232 /* Remove data clusters that are not required. This overestimates the
4233 * required size because metadata needed for the fully allocated file is
4234 * still counted.
4236 info->required = info->fully_allocated - virtual_size + required;
4237 return info;
4239 err:
4240 error_propagate(errp, local_err);
4241 return NULL;
4244 static int qcow2_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
4246 BDRVQcow2State *s = bs->opaque;
4247 bdi->unallocated_blocks_are_zero = true;
4248 bdi->cluster_size = s->cluster_size;
4249 bdi->vm_state_offset = qcow2_vm_state_offset(s);
4250 return 0;
4253 static ImageInfoSpecific *qcow2_get_specific_info(BlockDriverState *bs)
4255 BDRVQcow2State *s = bs->opaque;
4256 ImageInfoSpecific *spec_info;
4257 QCryptoBlockInfo *encrypt_info = NULL;
4259 if (s->crypto != NULL) {
4260 encrypt_info = qcrypto_block_get_info(s->crypto, &error_abort);
4263 spec_info = g_new(ImageInfoSpecific, 1);
4264 *spec_info = (ImageInfoSpecific){
4265 .type = IMAGE_INFO_SPECIFIC_KIND_QCOW2,
4266 .u.qcow2.data = g_new(ImageInfoSpecificQCow2, 1),
4268 if (s->qcow_version == 2) {
4269 *spec_info->u.qcow2.data = (ImageInfoSpecificQCow2){
4270 .compat = g_strdup("0.10"),
4271 .refcount_bits = s->refcount_bits,
4273 } else if (s->qcow_version == 3) {
4274 *spec_info->u.qcow2.data = (ImageInfoSpecificQCow2){
4275 .compat = g_strdup("1.1"),
4276 .lazy_refcounts = s->compatible_features &
4277 QCOW2_COMPAT_LAZY_REFCOUNTS,
4278 .has_lazy_refcounts = true,
4279 .corrupt = s->incompatible_features &
4280 QCOW2_INCOMPAT_CORRUPT,
4281 .has_corrupt = true,
4282 .refcount_bits = s->refcount_bits,
4284 } else {
4285 /* if this assertion fails, this probably means a new version was
4286 * added without having it covered here */
4287 assert(false);
4290 if (encrypt_info) {
4291 ImageInfoSpecificQCow2Encryption *qencrypt =
4292 g_new(ImageInfoSpecificQCow2Encryption, 1);
4293 switch (encrypt_info->format) {
4294 case Q_CRYPTO_BLOCK_FORMAT_QCOW:
4295 qencrypt->format = BLOCKDEV_QCOW2_ENCRYPTION_FORMAT_AES;
4296 break;
4297 case Q_CRYPTO_BLOCK_FORMAT_LUKS:
4298 qencrypt->format = BLOCKDEV_QCOW2_ENCRYPTION_FORMAT_LUKS;
4299 qencrypt->u.luks = encrypt_info->u.luks;
4300 break;
4301 default:
4302 abort();
4304 /* Since we did shallow copy above, erase any pointers
4305 * in the original info */
4306 memset(&encrypt_info->u, 0, sizeof(encrypt_info->u));
4307 qapi_free_QCryptoBlockInfo(encrypt_info);
4309 spec_info->u.qcow2.data->has_encrypt = true;
4310 spec_info->u.qcow2.data->encrypt = qencrypt;
4313 return spec_info;
4316 static int qcow2_save_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
4317 int64_t pos)
4319 BDRVQcow2State *s = bs->opaque;
4321 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_SAVE);
4322 return bs->drv->bdrv_co_pwritev(bs, qcow2_vm_state_offset(s) + pos,
4323 qiov->size, qiov, 0);
4326 static int qcow2_load_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
4327 int64_t pos)
4329 BDRVQcow2State *s = bs->opaque;
4331 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_LOAD);
4332 return bs->drv->bdrv_co_preadv(bs, qcow2_vm_state_offset(s) + pos,
4333 qiov->size, qiov, 0);
4337 * Downgrades an image's version. To achieve this, any incompatible features
4338 * have to be removed.
4340 static int qcow2_downgrade(BlockDriverState *bs, int target_version,
4341 BlockDriverAmendStatusCB *status_cb, void *cb_opaque,
4342 Error **errp)
4344 BDRVQcow2State *s = bs->opaque;
4345 int current_version = s->qcow_version;
4346 int ret;
4348 /* This is qcow2_downgrade(), not qcow2_upgrade() */
4349 assert(target_version < current_version);
4351 /* There are no other versions (now) that you can downgrade to */
4352 assert(target_version == 2);
4354 if (s->refcount_order != 4) {
4355 error_setg(errp, "compat=0.10 requires refcount_bits=16");
4356 return -ENOTSUP;
4359 /* clear incompatible features */
4360 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
4361 ret = qcow2_mark_clean(bs);
4362 if (ret < 0) {
4363 error_setg_errno(errp, -ret, "Failed to make the image clean");
4364 return ret;
4368 /* with QCOW2_INCOMPAT_CORRUPT, it is pretty much impossible to get here in
4369 * the first place; if that happens nonetheless, returning -ENOTSUP is the
4370 * best thing to do anyway */
4372 if (s->incompatible_features) {
4373 error_setg(errp, "Cannot downgrade an image with incompatible features "
4374 "%#" PRIx64 " set", s->incompatible_features);
4375 return -ENOTSUP;
4378 /* since we can ignore compatible features, we can set them to 0 as well */
4379 s->compatible_features = 0;
4380 /* if lazy refcounts have been used, they have already been fixed through
4381 * clearing the dirty flag */
4383 /* clearing autoclear features is trivial */
4384 s->autoclear_features = 0;
4386 ret = qcow2_expand_zero_clusters(bs, status_cb, cb_opaque);
4387 if (ret < 0) {
4388 error_setg_errno(errp, -ret, "Failed to turn zero into data clusters");
4389 return ret;
4392 s->qcow_version = target_version;
4393 ret = qcow2_update_header(bs);
4394 if (ret < 0) {
4395 s->qcow_version = current_version;
4396 error_setg_errno(errp, -ret, "Failed to update the image header");
4397 return ret;
4399 return 0;
4402 typedef enum Qcow2AmendOperation {
4403 /* This is the value Qcow2AmendHelperCBInfo::last_operation will be
4404 * statically initialized to so that the helper CB can discern the first
4405 * invocation from an operation change */
4406 QCOW2_NO_OPERATION = 0,
4408 QCOW2_CHANGING_REFCOUNT_ORDER,
4409 QCOW2_DOWNGRADING,
4410 } Qcow2AmendOperation;
4412 typedef struct Qcow2AmendHelperCBInfo {
4413 /* The code coordinating the amend operations should only modify
4414 * these four fields; the rest will be managed by the CB */
4415 BlockDriverAmendStatusCB *original_status_cb;
4416 void *original_cb_opaque;
4418 Qcow2AmendOperation current_operation;
4420 /* Total number of operations to perform (only set once) */
4421 int total_operations;
4423 /* The following fields are managed by the CB */
4425 /* Number of operations completed */
4426 int operations_completed;
4428 /* Cumulative offset of all completed operations */
4429 int64_t offset_completed;
4431 Qcow2AmendOperation last_operation;
4432 int64_t last_work_size;
4433 } Qcow2AmendHelperCBInfo;
4435 static void qcow2_amend_helper_cb(BlockDriverState *bs,
4436 int64_t operation_offset,
4437 int64_t operation_work_size, void *opaque)
4439 Qcow2AmendHelperCBInfo *info = opaque;
4440 int64_t current_work_size;
4441 int64_t projected_work_size;
4443 if (info->current_operation != info->last_operation) {
4444 if (info->last_operation != QCOW2_NO_OPERATION) {
4445 info->offset_completed += info->last_work_size;
4446 info->operations_completed++;
4449 info->last_operation = info->current_operation;
4452 assert(info->total_operations > 0);
4453 assert(info->operations_completed < info->total_operations);
4455 info->last_work_size = operation_work_size;
4457 current_work_size = info->offset_completed + operation_work_size;
4459 /* current_work_size is the total work size for (operations_completed + 1)
4460 * operations (which includes this one), so multiply it by the number of
4461 * operations not covered and divide it by the number of operations
4462 * covered to get a projection for the operations not covered */
4463 projected_work_size = current_work_size * (info->total_operations -
4464 info->operations_completed - 1)
4465 / (info->operations_completed + 1);
4467 info->original_status_cb(bs, info->offset_completed + operation_offset,
4468 current_work_size + projected_work_size,
4469 info->original_cb_opaque);
4472 static int qcow2_amend_options(BlockDriverState *bs, QemuOpts *opts,
4473 BlockDriverAmendStatusCB *status_cb,
4474 void *cb_opaque,
4475 Error **errp)
4477 BDRVQcow2State *s = bs->opaque;
4478 int old_version = s->qcow_version, new_version = old_version;
4479 uint64_t new_size = 0;
4480 const char *backing_file = NULL, *backing_format = NULL;
4481 bool lazy_refcounts = s->use_lazy_refcounts;
4482 const char *compat = NULL;
4483 uint64_t cluster_size = s->cluster_size;
4484 bool encrypt;
4485 int encformat;
4486 int refcount_bits = s->refcount_bits;
4487 int ret;
4488 QemuOptDesc *desc = opts->list->desc;
4489 Qcow2AmendHelperCBInfo helper_cb_info;
4491 while (desc && desc->name) {
4492 if (!qemu_opt_find(opts, desc->name)) {
4493 /* only change explicitly defined options */
4494 desc++;
4495 continue;
4498 if (!strcmp(desc->name, BLOCK_OPT_COMPAT_LEVEL)) {
4499 compat = qemu_opt_get(opts, BLOCK_OPT_COMPAT_LEVEL);
4500 if (!compat) {
4501 /* preserve default */
4502 } else if (!strcmp(compat, "0.10")) {
4503 new_version = 2;
4504 } else if (!strcmp(compat, "1.1")) {
4505 new_version = 3;
4506 } else {
4507 error_setg(errp, "Unknown compatibility level %s", compat);
4508 return -EINVAL;
4510 } else if (!strcmp(desc->name, BLOCK_OPT_PREALLOC)) {
4511 error_setg(errp, "Cannot change preallocation mode");
4512 return -ENOTSUP;
4513 } else if (!strcmp(desc->name, BLOCK_OPT_SIZE)) {
4514 new_size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, 0);
4515 } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FILE)) {
4516 backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
4517 } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FMT)) {
4518 backing_format = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
4519 } else if (!strcmp(desc->name, BLOCK_OPT_ENCRYPT)) {
4520 encrypt = qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT,
4521 !!s->crypto);
4523 if (encrypt != !!s->crypto) {
4524 error_setg(errp,
4525 "Changing the encryption flag is not supported");
4526 return -ENOTSUP;
4528 } else if (!strcmp(desc->name, BLOCK_OPT_ENCRYPT_FORMAT)) {
4529 encformat = qcow2_crypt_method_from_format(
4530 qemu_opt_get(opts, BLOCK_OPT_ENCRYPT_FORMAT));
4532 if (encformat != s->crypt_method_header) {
4533 error_setg(errp,
4534 "Changing the encryption format is not supported");
4535 return -ENOTSUP;
4537 } else if (g_str_has_prefix(desc->name, "encrypt.")) {
4538 error_setg(errp,
4539 "Changing the encryption parameters is not supported");
4540 return -ENOTSUP;
4541 } else if (!strcmp(desc->name, BLOCK_OPT_CLUSTER_SIZE)) {
4542 cluster_size = qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE,
4543 cluster_size);
4544 if (cluster_size != s->cluster_size) {
4545 error_setg(errp, "Changing the cluster size is not supported");
4546 return -ENOTSUP;
4548 } else if (!strcmp(desc->name, BLOCK_OPT_LAZY_REFCOUNTS)) {
4549 lazy_refcounts = qemu_opt_get_bool(opts, BLOCK_OPT_LAZY_REFCOUNTS,
4550 lazy_refcounts);
4551 } else if (!strcmp(desc->name, BLOCK_OPT_REFCOUNT_BITS)) {
4552 refcount_bits = qemu_opt_get_number(opts, BLOCK_OPT_REFCOUNT_BITS,
4553 refcount_bits);
4555 if (refcount_bits <= 0 || refcount_bits > 64 ||
4556 !is_power_of_2(refcount_bits))
4558 error_setg(errp, "Refcount width must be a power of two and "
4559 "may not exceed 64 bits");
4560 return -EINVAL;
4562 } else {
4563 /* if this point is reached, this probably means a new option was
4564 * added without having it covered here */
4565 abort();
4568 desc++;
4571 helper_cb_info = (Qcow2AmendHelperCBInfo){
4572 .original_status_cb = status_cb,
4573 .original_cb_opaque = cb_opaque,
4574 .total_operations = (new_version < old_version)
4575 + (s->refcount_bits != refcount_bits)
4578 /* Upgrade first (some features may require compat=1.1) */
4579 if (new_version > old_version) {
4580 s->qcow_version = new_version;
4581 ret = qcow2_update_header(bs);
4582 if (ret < 0) {
4583 s->qcow_version = old_version;
4584 error_setg_errno(errp, -ret, "Failed to update the image header");
4585 return ret;
4589 if (s->refcount_bits != refcount_bits) {
4590 int refcount_order = ctz32(refcount_bits);
4592 if (new_version < 3 && refcount_bits != 16) {
4593 error_setg(errp, "Refcount widths other than 16 bits require "
4594 "compatibility level 1.1 or above (use compat=1.1 or "
4595 "greater)");
4596 return -EINVAL;
4599 helper_cb_info.current_operation = QCOW2_CHANGING_REFCOUNT_ORDER;
4600 ret = qcow2_change_refcount_order(bs, refcount_order,
4601 &qcow2_amend_helper_cb,
4602 &helper_cb_info, errp);
4603 if (ret < 0) {
4604 return ret;
4608 if (backing_file || backing_format) {
4609 ret = qcow2_change_backing_file(bs,
4610 backing_file ?: s->image_backing_file,
4611 backing_format ?: s->image_backing_format);
4612 if (ret < 0) {
4613 error_setg_errno(errp, -ret, "Failed to change the backing file");
4614 return ret;
4618 if (s->use_lazy_refcounts != lazy_refcounts) {
4619 if (lazy_refcounts) {
4620 if (new_version < 3) {
4621 error_setg(errp, "Lazy refcounts only supported with "
4622 "compatibility level 1.1 and above (use compat=1.1 "
4623 "or greater)");
4624 return -EINVAL;
4626 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
4627 ret = qcow2_update_header(bs);
4628 if (ret < 0) {
4629 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
4630 error_setg_errno(errp, -ret, "Failed to update the image header");
4631 return ret;
4633 s->use_lazy_refcounts = true;
4634 } else {
4635 /* make image clean first */
4636 ret = qcow2_mark_clean(bs);
4637 if (ret < 0) {
4638 error_setg_errno(errp, -ret, "Failed to make the image clean");
4639 return ret;
4641 /* now disallow lazy refcounts */
4642 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
4643 ret = qcow2_update_header(bs);
4644 if (ret < 0) {
4645 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
4646 error_setg_errno(errp, -ret, "Failed to update the image header");
4647 return ret;
4649 s->use_lazy_refcounts = false;
4653 if (new_size) {
4654 BlockBackend *blk = blk_new(BLK_PERM_RESIZE, BLK_PERM_ALL);
4655 ret = blk_insert_bs(blk, bs, errp);
4656 if (ret < 0) {
4657 blk_unref(blk);
4658 return ret;
4661 ret = blk_truncate(blk, new_size, PREALLOC_MODE_OFF, errp);
4662 blk_unref(blk);
4663 if (ret < 0) {
4664 return ret;
4668 /* Downgrade last (so unsupported features can be removed before) */
4669 if (new_version < old_version) {
4670 helper_cb_info.current_operation = QCOW2_DOWNGRADING;
4671 ret = qcow2_downgrade(bs, new_version, &qcow2_amend_helper_cb,
4672 &helper_cb_info, errp);
4673 if (ret < 0) {
4674 return ret;
4678 return 0;
4682 * If offset or size are negative, respectively, they will not be included in
4683 * the BLOCK_IMAGE_CORRUPTED event emitted.
4684 * fatal will be ignored for read-only BDS; corruptions found there will always
4685 * be considered non-fatal.
4687 void qcow2_signal_corruption(BlockDriverState *bs, bool fatal, int64_t offset,
4688 int64_t size, const char *message_format, ...)
4690 BDRVQcow2State *s = bs->opaque;
4691 const char *node_name;
4692 char *message;
4693 va_list ap;
4695 fatal = fatal && bdrv_is_writable(bs);
4697 if (s->signaled_corruption &&
4698 (!fatal || (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT)))
4700 return;
4703 va_start(ap, message_format);
4704 message = g_strdup_vprintf(message_format, ap);
4705 va_end(ap);
4707 if (fatal) {
4708 fprintf(stderr, "qcow2: Marking image as corrupt: %s; further "
4709 "corruption events will be suppressed\n", message);
4710 } else {
4711 fprintf(stderr, "qcow2: Image is corrupt: %s; further non-fatal "
4712 "corruption events will be suppressed\n", message);
4715 node_name = bdrv_get_node_name(bs);
4716 qapi_event_send_block_image_corrupted(bdrv_get_device_name(bs),
4717 *node_name != '\0', node_name,
4718 message, offset >= 0, offset,
4719 size >= 0, size,
4720 fatal);
4721 g_free(message);
4723 if (fatal) {
4724 qcow2_mark_corrupt(bs);
4725 bs->drv = NULL; /* make BDS unusable */
4728 s->signaled_corruption = true;
4731 static QemuOptsList qcow2_create_opts = {
4732 .name = "qcow2-create-opts",
4733 .head = QTAILQ_HEAD_INITIALIZER(qcow2_create_opts.head),
4734 .desc = {
4736 .name = BLOCK_OPT_SIZE,
4737 .type = QEMU_OPT_SIZE,
4738 .help = "Virtual disk size"
4741 .name = BLOCK_OPT_COMPAT_LEVEL,
4742 .type = QEMU_OPT_STRING,
4743 .help = "Compatibility level (0.10 or 1.1)"
4746 .name = BLOCK_OPT_BACKING_FILE,
4747 .type = QEMU_OPT_STRING,
4748 .help = "File name of a base image"
4751 .name = BLOCK_OPT_BACKING_FMT,
4752 .type = QEMU_OPT_STRING,
4753 .help = "Image format of the base image"
4756 .name = BLOCK_OPT_ENCRYPT,
4757 .type = QEMU_OPT_BOOL,
4758 .help = "Encrypt the image with format 'aes'. (Deprecated "
4759 "in favor of " BLOCK_OPT_ENCRYPT_FORMAT "=aes)",
4762 .name = BLOCK_OPT_ENCRYPT_FORMAT,
4763 .type = QEMU_OPT_STRING,
4764 .help = "Encrypt the image, format choices: 'aes', 'luks'",
4766 BLOCK_CRYPTO_OPT_DEF_KEY_SECRET("encrypt.",
4767 "ID of secret providing qcow AES key or LUKS passphrase"),
4768 BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_ALG("encrypt."),
4769 BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_MODE("encrypt."),
4770 BLOCK_CRYPTO_OPT_DEF_LUKS_IVGEN_ALG("encrypt."),
4771 BLOCK_CRYPTO_OPT_DEF_LUKS_IVGEN_HASH_ALG("encrypt."),
4772 BLOCK_CRYPTO_OPT_DEF_LUKS_HASH_ALG("encrypt."),
4773 BLOCK_CRYPTO_OPT_DEF_LUKS_ITER_TIME("encrypt."),
4775 .name = BLOCK_OPT_CLUSTER_SIZE,
4776 .type = QEMU_OPT_SIZE,
4777 .help = "qcow2 cluster size",
4778 .def_value_str = stringify(DEFAULT_CLUSTER_SIZE)
4781 .name = BLOCK_OPT_PREALLOC,
4782 .type = QEMU_OPT_STRING,
4783 .help = "Preallocation mode (allowed values: off, metadata, "
4784 "falloc, full)"
4787 .name = BLOCK_OPT_LAZY_REFCOUNTS,
4788 .type = QEMU_OPT_BOOL,
4789 .help = "Postpone refcount updates",
4790 .def_value_str = "off"
4793 .name = BLOCK_OPT_REFCOUNT_BITS,
4794 .type = QEMU_OPT_NUMBER,
4795 .help = "Width of a reference count entry in bits",
4796 .def_value_str = "16"
4798 { /* end of list */ }
4802 BlockDriver bdrv_qcow2 = {
4803 .format_name = "qcow2",
4804 .instance_size = sizeof(BDRVQcow2State),
4805 .bdrv_probe = qcow2_probe,
4806 .bdrv_open = qcow2_open,
4807 .bdrv_close = qcow2_close,
4808 .bdrv_reopen_prepare = qcow2_reopen_prepare,
4809 .bdrv_reopen_commit = qcow2_reopen_commit,
4810 .bdrv_reopen_abort = qcow2_reopen_abort,
4811 .bdrv_join_options = qcow2_join_options,
4812 .bdrv_child_perm = bdrv_format_default_perms,
4813 .bdrv_co_create_opts = qcow2_co_create_opts,
4814 .bdrv_co_create = qcow2_co_create,
4815 .bdrv_has_zero_init = bdrv_has_zero_init_1,
4816 .bdrv_co_block_status = qcow2_co_block_status,
4818 .bdrv_co_preadv = qcow2_co_preadv,
4819 .bdrv_co_pwritev = qcow2_co_pwritev,
4820 .bdrv_co_flush_to_os = qcow2_co_flush_to_os,
4822 .bdrv_co_pwrite_zeroes = qcow2_co_pwrite_zeroes,
4823 .bdrv_co_pdiscard = qcow2_co_pdiscard,
4824 .bdrv_co_copy_range_from = qcow2_co_copy_range_from,
4825 .bdrv_co_copy_range_to = qcow2_co_copy_range_to,
4826 .bdrv_co_truncate = qcow2_co_truncate,
4827 .bdrv_co_pwritev_compressed = qcow2_co_pwritev_compressed,
4828 .bdrv_make_empty = qcow2_make_empty,
4830 .bdrv_snapshot_create = qcow2_snapshot_create,
4831 .bdrv_snapshot_goto = qcow2_snapshot_goto,
4832 .bdrv_snapshot_delete = qcow2_snapshot_delete,
4833 .bdrv_snapshot_list = qcow2_snapshot_list,
4834 .bdrv_snapshot_load_tmp = qcow2_snapshot_load_tmp,
4835 .bdrv_measure = qcow2_measure,
4836 .bdrv_get_info = qcow2_get_info,
4837 .bdrv_get_specific_info = qcow2_get_specific_info,
4839 .bdrv_save_vmstate = qcow2_save_vmstate,
4840 .bdrv_load_vmstate = qcow2_load_vmstate,
4842 .supports_backing = true,
4843 .bdrv_change_backing_file = qcow2_change_backing_file,
4845 .bdrv_refresh_limits = qcow2_refresh_limits,
4846 .bdrv_co_invalidate_cache = qcow2_co_invalidate_cache,
4847 .bdrv_inactivate = qcow2_inactivate,
4849 .create_opts = &qcow2_create_opts,
4850 .bdrv_co_check = qcow2_co_check,
4851 .bdrv_amend_options = qcow2_amend_options,
4853 .bdrv_detach_aio_context = qcow2_detach_aio_context,
4854 .bdrv_attach_aio_context = qcow2_attach_aio_context,
4856 .bdrv_reopen_bitmaps_rw = qcow2_reopen_bitmaps_rw,
4857 .bdrv_can_store_new_dirty_bitmap = qcow2_can_store_new_dirty_bitmap,
4858 .bdrv_remove_persistent_dirty_bitmap = qcow2_remove_persistent_dirty_bitmap,
4861 static void bdrv_qcow2_init(void)
4863 bdrv_register(&bdrv_qcow2);
4866 block_init(bdrv_qcow2_init);