qcow2: Use a GString in report_unsupported_feature()
[qemu/ar7.git] / block / qcow2.c
blobe29fc0706815fbcc2754f8b62a9de8e59c13888e
1 /*
2 * Block driver for the QCOW version 2 format
4 * Copyright (c) 2004-2006 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
25 #include "qemu/osdep.h"
27 #include "block/qdict.h"
28 #include "sysemu/block-backend.h"
29 #include "qemu/main-loop.h"
30 #include "qemu/module.h"
31 #include "qcow2.h"
32 #include "qemu/error-report.h"
33 #include "qapi/error.h"
34 #include "qapi/qapi-events-block-core.h"
35 #include "qapi/qmp/qdict.h"
36 #include "qapi/qmp/qstring.h"
37 #include "trace.h"
38 #include "qemu/option_int.h"
39 #include "qemu/cutils.h"
40 #include "qemu/bswap.h"
41 #include "qapi/qobject-input-visitor.h"
42 #include "qapi/qapi-visit-block-core.h"
43 #include "crypto.h"
44 #include "block/aio_task.h"
47 Differences with QCOW:
49 - Support for multiple incremental snapshots.
50 - Memory management by reference counts.
51 - Clusters which have a reference count of one have the bit
52 QCOW_OFLAG_COPIED to optimize write performance.
53 - Size of compressed clusters is stored in sectors to reduce bit usage
54 in the cluster offsets.
55 - Support for storing additional data (such as the VM state) in the
56 snapshots.
57 - If a backing store is used, the cluster size is not constrained
58 (could be backported to QCOW).
59 - L2 tables have always a size of one cluster.
63 typedef struct {
64 uint32_t magic;
65 uint32_t len;
66 } QEMU_PACKED QCowExtension;
68 #define QCOW2_EXT_MAGIC_END 0
69 #define QCOW2_EXT_MAGIC_BACKING_FORMAT 0xE2792ACA
70 #define QCOW2_EXT_MAGIC_FEATURE_TABLE 0x6803f857
71 #define QCOW2_EXT_MAGIC_CRYPTO_HEADER 0x0537be77
72 #define QCOW2_EXT_MAGIC_BITMAPS 0x23852875
73 #define QCOW2_EXT_MAGIC_DATA_FILE 0x44415441
75 static int coroutine_fn
76 qcow2_co_preadv_compressed(BlockDriverState *bs,
77 uint64_t file_cluster_offset,
78 uint64_t offset,
79 uint64_t bytes,
80 QEMUIOVector *qiov,
81 size_t qiov_offset);
83 static int qcow2_probe(const uint8_t *buf, int buf_size, const char *filename)
85 const QCowHeader *cow_header = (const void *)buf;
87 if (buf_size >= sizeof(QCowHeader) &&
88 be32_to_cpu(cow_header->magic) == QCOW_MAGIC &&
89 be32_to_cpu(cow_header->version) >= 2)
90 return 100;
91 else
92 return 0;
96 static ssize_t qcow2_crypto_hdr_read_func(QCryptoBlock *block, size_t offset,
97 uint8_t *buf, size_t buflen,
98 void *opaque, Error **errp)
100 BlockDriverState *bs = opaque;
101 BDRVQcow2State *s = bs->opaque;
102 ssize_t ret;
104 if ((offset + buflen) > s->crypto_header.length) {
105 error_setg(errp, "Request for data outside of extension header");
106 return -1;
109 ret = bdrv_pread(bs->file,
110 s->crypto_header.offset + offset, buf, buflen);
111 if (ret < 0) {
112 error_setg_errno(errp, -ret, "Could not read encryption header");
113 return -1;
115 return ret;
119 static ssize_t qcow2_crypto_hdr_init_func(QCryptoBlock *block, size_t headerlen,
120 void *opaque, Error **errp)
122 BlockDriverState *bs = opaque;
123 BDRVQcow2State *s = bs->opaque;
124 int64_t ret;
125 int64_t clusterlen;
127 ret = qcow2_alloc_clusters(bs, headerlen);
128 if (ret < 0) {
129 error_setg_errno(errp, -ret,
130 "Cannot allocate cluster for LUKS header size %zu",
131 headerlen);
132 return -1;
135 s->crypto_header.length = headerlen;
136 s->crypto_header.offset = ret;
138 /* Zero fill remaining space in cluster so it has predictable
139 * content in case of future spec changes */
140 clusterlen = size_to_clusters(s, headerlen) * s->cluster_size;
141 assert(qcow2_pre_write_overlap_check(bs, 0, ret, clusterlen, false) == 0);
142 ret = bdrv_pwrite_zeroes(bs->file,
143 ret + headerlen,
144 clusterlen - headerlen, 0);
145 if (ret < 0) {
146 error_setg_errno(errp, -ret, "Could not zero fill encryption header");
147 return -1;
150 return ret;
154 static ssize_t qcow2_crypto_hdr_write_func(QCryptoBlock *block, size_t offset,
155 const uint8_t *buf, size_t buflen,
156 void *opaque, Error **errp)
158 BlockDriverState *bs = opaque;
159 BDRVQcow2State *s = bs->opaque;
160 ssize_t ret;
162 if ((offset + buflen) > s->crypto_header.length) {
163 error_setg(errp, "Request for data outside of extension header");
164 return -1;
167 ret = bdrv_pwrite(bs->file,
168 s->crypto_header.offset + offset, buf, buflen);
169 if (ret < 0) {
170 error_setg_errno(errp, -ret, "Could not read encryption header");
171 return -1;
173 return ret;
178 * read qcow2 extension and fill bs
179 * start reading from start_offset
180 * finish reading upon magic of value 0 or when end_offset reached
181 * unknown magic is skipped (future extension this version knows nothing about)
182 * return 0 upon success, non-0 otherwise
184 static int qcow2_read_extensions(BlockDriverState *bs, uint64_t start_offset,
185 uint64_t end_offset, void **p_feature_table,
186 int flags, bool *need_update_header,
187 Error **errp)
189 BDRVQcow2State *s = bs->opaque;
190 QCowExtension ext;
191 uint64_t offset;
192 int ret;
193 Qcow2BitmapHeaderExt bitmaps_ext;
195 if (need_update_header != NULL) {
196 *need_update_header = false;
199 #ifdef DEBUG_EXT
200 printf("qcow2_read_extensions: start=%ld end=%ld\n", start_offset, end_offset);
201 #endif
202 offset = start_offset;
203 while (offset < end_offset) {
205 #ifdef DEBUG_EXT
206 /* Sanity check */
207 if (offset > s->cluster_size)
208 printf("qcow2_read_extension: suspicious offset %lu\n", offset);
210 printf("attempting to read extended header in offset %lu\n", offset);
211 #endif
213 ret = bdrv_pread(bs->file, offset, &ext, sizeof(ext));
214 if (ret < 0) {
215 error_setg_errno(errp, -ret, "qcow2_read_extension: ERROR: "
216 "pread fail from offset %" PRIu64, offset);
217 return 1;
219 ext.magic = be32_to_cpu(ext.magic);
220 ext.len = be32_to_cpu(ext.len);
221 offset += sizeof(ext);
222 #ifdef DEBUG_EXT
223 printf("ext.magic = 0x%x\n", ext.magic);
224 #endif
225 if (offset > end_offset || ext.len > end_offset - offset) {
226 error_setg(errp, "Header extension too large");
227 return -EINVAL;
230 switch (ext.magic) {
231 case QCOW2_EXT_MAGIC_END:
232 return 0;
234 case QCOW2_EXT_MAGIC_BACKING_FORMAT:
235 if (ext.len >= sizeof(bs->backing_format)) {
236 error_setg(errp, "ERROR: ext_backing_format: len=%" PRIu32
237 " too large (>=%zu)", ext.len,
238 sizeof(bs->backing_format));
239 return 2;
241 ret = bdrv_pread(bs->file, offset, bs->backing_format, ext.len);
242 if (ret < 0) {
243 error_setg_errno(errp, -ret, "ERROR: ext_backing_format: "
244 "Could not read format name");
245 return 3;
247 bs->backing_format[ext.len] = '\0';
248 s->image_backing_format = g_strdup(bs->backing_format);
249 #ifdef DEBUG_EXT
250 printf("Qcow2: Got format extension %s\n", bs->backing_format);
251 #endif
252 break;
254 case QCOW2_EXT_MAGIC_FEATURE_TABLE:
255 if (p_feature_table != NULL) {
256 void* feature_table = g_malloc0(ext.len + 2 * sizeof(Qcow2Feature));
257 ret = bdrv_pread(bs->file, offset , feature_table, ext.len);
258 if (ret < 0) {
259 error_setg_errno(errp, -ret, "ERROR: ext_feature_table: "
260 "Could not read table");
261 return ret;
264 *p_feature_table = feature_table;
266 break;
268 case QCOW2_EXT_MAGIC_CRYPTO_HEADER: {
269 unsigned int cflags = 0;
270 if (s->crypt_method_header != QCOW_CRYPT_LUKS) {
271 error_setg(errp, "CRYPTO header extension only "
272 "expected with LUKS encryption method");
273 return -EINVAL;
275 if (ext.len != sizeof(Qcow2CryptoHeaderExtension)) {
276 error_setg(errp, "CRYPTO header extension size %u, "
277 "but expected size %zu", ext.len,
278 sizeof(Qcow2CryptoHeaderExtension));
279 return -EINVAL;
282 ret = bdrv_pread(bs->file, offset, &s->crypto_header, ext.len);
283 if (ret < 0) {
284 error_setg_errno(errp, -ret,
285 "Unable to read CRYPTO header extension");
286 return ret;
288 s->crypto_header.offset = be64_to_cpu(s->crypto_header.offset);
289 s->crypto_header.length = be64_to_cpu(s->crypto_header.length);
291 if ((s->crypto_header.offset % s->cluster_size) != 0) {
292 error_setg(errp, "Encryption header offset '%" PRIu64 "' is "
293 "not a multiple of cluster size '%u'",
294 s->crypto_header.offset, s->cluster_size);
295 return -EINVAL;
298 if (flags & BDRV_O_NO_IO) {
299 cflags |= QCRYPTO_BLOCK_OPEN_NO_IO;
301 s->crypto = qcrypto_block_open(s->crypto_opts, "encrypt.",
302 qcow2_crypto_hdr_read_func,
303 bs, cflags, QCOW2_MAX_THREADS, errp);
304 if (!s->crypto) {
305 return -EINVAL;
307 } break;
309 case QCOW2_EXT_MAGIC_BITMAPS:
310 if (ext.len != sizeof(bitmaps_ext)) {
311 error_setg_errno(errp, -ret, "bitmaps_ext: "
312 "Invalid extension length");
313 return -EINVAL;
316 if (!(s->autoclear_features & QCOW2_AUTOCLEAR_BITMAPS)) {
317 if (s->qcow_version < 3) {
318 /* Let's be a bit more specific */
319 warn_report("This qcow2 v2 image contains bitmaps, but "
320 "they may have been modified by a program "
321 "without persistent bitmap support; so now "
322 "they must all be considered inconsistent");
323 } else {
324 warn_report("a program lacking bitmap support "
325 "modified this file, so all bitmaps are now "
326 "considered inconsistent");
328 error_printf("Some clusters may be leaked, "
329 "run 'qemu-img check -r' on the image "
330 "file to fix.");
331 if (need_update_header != NULL) {
332 /* Updating is needed to drop invalid bitmap extension. */
333 *need_update_header = true;
335 break;
338 ret = bdrv_pread(bs->file, offset, &bitmaps_ext, ext.len);
339 if (ret < 0) {
340 error_setg_errno(errp, -ret, "bitmaps_ext: "
341 "Could not read ext header");
342 return ret;
345 if (bitmaps_ext.reserved32 != 0) {
346 error_setg_errno(errp, -ret, "bitmaps_ext: "
347 "Reserved field is not zero");
348 return -EINVAL;
351 bitmaps_ext.nb_bitmaps = be32_to_cpu(bitmaps_ext.nb_bitmaps);
352 bitmaps_ext.bitmap_directory_size =
353 be64_to_cpu(bitmaps_ext.bitmap_directory_size);
354 bitmaps_ext.bitmap_directory_offset =
355 be64_to_cpu(bitmaps_ext.bitmap_directory_offset);
357 if (bitmaps_ext.nb_bitmaps > QCOW2_MAX_BITMAPS) {
358 error_setg(errp,
359 "bitmaps_ext: Image has %" PRIu32 " bitmaps, "
360 "exceeding the QEMU supported maximum of %d",
361 bitmaps_ext.nb_bitmaps, QCOW2_MAX_BITMAPS);
362 return -EINVAL;
365 if (bitmaps_ext.nb_bitmaps == 0) {
366 error_setg(errp, "found bitmaps extension with zero bitmaps");
367 return -EINVAL;
370 if (offset_into_cluster(s, bitmaps_ext.bitmap_directory_offset)) {
371 error_setg(errp, "bitmaps_ext: "
372 "invalid bitmap directory offset");
373 return -EINVAL;
376 if (bitmaps_ext.bitmap_directory_size >
377 QCOW2_MAX_BITMAP_DIRECTORY_SIZE) {
378 error_setg(errp, "bitmaps_ext: "
379 "bitmap directory size (%" PRIu64 ") exceeds "
380 "the maximum supported size (%d)",
381 bitmaps_ext.bitmap_directory_size,
382 QCOW2_MAX_BITMAP_DIRECTORY_SIZE);
383 return -EINVAL;
386 s->nb_bitmaps = bitmaps_ext.nb_bitmaps;
387 s->bitmap_directory_offset =
388 bitmaps_ext.bitmap_directory_offset;
389 s->bitmap_directory_size =
390 bitmaps_ext.bitmap_directory_size;
392 #ifdef DEBUG_EXT
393 printf("Qcow2: Got bitmaps extension: "
394 "offset=%" PRIu64 " nb_bitmaps=%" PRIu32 "\n",
395 s->bitmap_directory_offset, s->nb_bitmaps);
396 #endif
397 break;
399 case QCOW2_EXT_MAGIC_DATA_FILE:
401 s->image_data_file = g_malloc0(ext.len + 1);
402 ret = bdrv_pread(bs->file, offset, s->image_data_file, ext.len);
403 if (ret < 0) {
404 error_setg_errno(errp, -ret,
405 "ERROR: Could not read data file name");
406 return ret;
408 #ifdef DEBUG_EXT
409 printf("Qcow2: Got external data file %s\n", s->image_data_file);
410 #endif
411 break;
414 default:
415 /* unknown magic - save it in case we need to rewrite the header */
416 /* If you add a new feature, make sure to also update the fast
417 * path of qcow2_make_empty() to deal with it. */
419 Qcow2UnknownHeaderExtension *uext;
421 uext = g_malloc0(sizeof(*uext) + ext.len);
422 uext->magic = ext.magic;
423 uext->len = ext.len;
424 QLIST_INSERT_HEAD(&s->unknown_header_ext, uext, next);
426 ret = bdrv_pread(bs->file, offset , uext->data, uext->len);
427 if (ret < 0) {
428 error_setg_errno(errp, -ret, "ERROR: unknown extension: "
429 "Could not read data");
430 return ret;
433 break;
436 offset += ((ext.len + 7) & ~7);
439 return 0;
442 static void cleanup_unknown_header_ext(BlockDriverState *bs)
444 BDRVQcow2State *s = bs->opaque;
445 Qcow2UnknownHeaderExtension *uext, *next;
447 QLIST_FOREACH_SAFE(uext, &s->unknown_header_ext, next, next) {
448 QLIST_REMOVE(uext, next);
449 g_free(uext);
453 static void report_unsupported_feature(Error **errp, Qcow2Feature *table,
454 uint64_t mask)
456 g_autoptr(GString) features = g_string_sized_new(60);
458 while (table && table->name[0] != '\0') {
459 if (table->type == QCOW2_FEAT_TYPE_INCOMPATIBLE) {
460 if (mask & (1ULL << table->bit)) {
461 if (features->len > 0) {
462 g_string_append(features, ", ");
464 g_string_append_printf(features, "%.46s", table->name);
465 mask &= ~(1ULL << table->bit);
468 table++;
471 if (mask) {
472 if (features->len > 0) {
473 g_string_append(features, ", ");
475 g_string_append_printf(features,
476 "Unknown incompatible feature: %" PRIx64, mask);
479 error_setg(errp, "Unsupported qcow2 feature(s): %s", features->str);
483 * Sets the dirty bit and flushes afterwards if necessary.
485 * The incompatible_features bit is only set if the image file header was
486 * updated successfully. Therefore it is not required to check the return
487 * value of this function.
489 int qcow2_mark_dirty(BlockDriverState *bs)
491 BDRVQcow2State *s = bs->opaque;
492 uint64_t val;
493 int ret;
495 assert(s->qcow_version >= 3);
497 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
498 return 0; /* already dirty */
501 val = cpu_to_be64(s->incompatible_features | QCOW2_INCOMPAT_DIRTY);
502 ret = bdrv_pwrite(bs->file, offsetof(QCowHeader, incompatible_features),
503 &val, sizeof(val));
504 if (ret < 0) {
505 return ret;
507 ret = bdrv_flush(bs->file->bs);
508 if (ret < 0) {
509 return ret;
512 /* Only treat image as dirty if the header was updated successfully */
513 s->incompatible_features |= QCOW2_INCOMPAT_DIRTY;
514 return 0;
518 * Clears the dirty bit and flushes before if necessary. Only call this
519 * function when there are no pending requests, it does not guard against
520 * concurrent requests dirtying the image.
522 static int qcow2_mark_clean(BlockDriverState *bs)
524 BDRVQcow2State *s = bs->opaque;
526 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
527 int ret;
529 s->incompatible_features &= ~QCOW2_INCOMPAT_DIRTY;
531 ret = qcow2_flush_caches(bs);
532 if (ret < 0) {
533 return ret;
536 return qcow2_update_header(bs);
538 return 0;
542 * Marks the image as corrupt.
544 int qcow2_mark_corrupt(BlockDriverState *bs)
546 BDRVQcow2State *s = bs->opaque;
548 s->incompatible_features |= QCOW2_INCOMPAT_CORRUPT;
549 return qcow2_update_header(bs);
553 * Marks the image as consistent, i.e., unsets the corrupt bit, and flushes
554 * before if necessary.
556 int qcow2_mark_consistent(BlockDriverState *bs)
558 BDRVQcow2State *s = bs->opaque;
560 if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
561 int ret = qcow2_flush_caches(bs);
562 if (ret < 0) {
563 return ret;
566 s->incompatible_features &= ~QCOW2_INCOMPAT_CORRUPT;
567 return qcow2_update_header(bs);
569 return 0;
572 static void qcow2_add_check_result(BdrvCheckResult *out,
573 const BdrvCheckResult *src,
574 bool set_allocation_info)
576 out->corruptions += src->corruptions;
577 out->leaks += src->leaks;
578 out->check_errors += src->check_errors;
579 out->corruptions_fixed += src->corruptions_fixed;
580 out->leaks_fixed += src->leaks_fixed;
582 if (set_allocation_info) {
583 out->image_end_offset = src->image_end_offset;
584 out->bfi = src->bfi;
588 static int coroutine_fn qcow2_co_check_locked(BlockDriverState *bs,
589 BdrvCheckResult *result,
590 BdrvCheckMode fix)
592 BdrvCheckResult snapshot_res = {};
593 BdrvCheckResult refcount_res = {};
594 int ret;
596 memset(result, 0, sizeof(*result));
598 ret = qcow2_check_read_snapshot_table(bs, &snapshot_res, fix);
599 if (ret < 0) {
600 qcow2_add_check_result(result, &snapshot_res, false);
601 return ret;
604 ret = qcow2_check_refcounts(bs, &refcount_res, fix);
605 qcow2_add_check_result(result, &refcount_res, true);
606 if (ret < 0) {
607 qcow2_add_check_result(result, &snapshot_res, false);
608 return ret;
611 ret = qcow2_check_fix_snapshot_table(bs, &snapshot_res, fix);
612 qcow2_add_check_result(result, &snapshot_res, false);
613 if (ret < 0) {
614 return ret;
617 if (fix && result->check_errors == 0 && result->corruptions == 0) {
618 ret = qcow2_mark_clean(bs);
619 if (ret < 0) {
620 return ret;
622 return qcow2_mark_consistent(bs);
624 return ret;
627 static int coroutine_fn qcow2_co_check(BlockDriverState *bs,
628 BdrvCheckResult *result,
629 BdrvCheckMode fix)
631 BDRVQcow2State *s = bs->opaque;
632 int ret;
634 qemu_co_mutex_lock(&s->lock);
635 ret = qcow2_co_check_locked(bs, result, fix);
636 qemu_co_mutex_unlock(&s->lock);
637 return ret;
640 int qcow2_validate_table(BlockDriverState *bs, uint64_t offset,
641 uint64_t entries, size_t entry_len,
642 int64_t max_size_bytes, const char *table_name,
643 Error **errp)
645 BDRVQcow2State *s = bs->opaque;
647 if (entries > max_size_bytes / entry_len) {
648 error_setg(errp, "%s too large", table_name);
649 return -EFBIG;
652 /* Use signed INT64_MAX as the maximum even for uint64_t header fields,
653 * because values will be passed to qemu functions taking int64_t. */
654 if ((INT64_MAX - entries * entry_len < offset) ||
655 (offset_into_cluster(s, offset) != 0)) {
656 error_setg(errp, "%s offset invalid", table_name);
657 return -EINVAL;
660 return 0;
663 static const char *const mutable_opts[] = {
664 QCOW2_OPT_LAZY_REFCOUNTS,
665 QCOW2_OPT_DISCARD_REQUEST,
666 QCOW2_OPT_DISCARD_SNAPSHOT,
667 QCOW2_OPT_DISCARD_OTHER,
668 QCOW2_OPT_OVERLAP,
669 QCOW2_OPT_OVERLAP_TEMPLATE,
670 QCOW2_OPT_OVERLAP_MAIN_HEADER,
671 QCOW2_OPT_OVERLAP_ACTIVE_L1,
672 QCOW2_OPT_OVERLAP_ACTIVE_L2,
673 QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
674 QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
675 QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
676 QCOW2_OPT_OVERLAP_INACTIVE_L1,
677 QCOW2_OPT_OVERLAP_INACTIVE_L2,
678 QCOW2_OPT_OVERLAP_BITMAP_DIRECTORY,
679 QCOW2_OPT_CACHE_SIZE,
680 QCOW2_OPT_L2_CACHE_SIZE,
681 QCOW2_OPT_L2_CACHE_ENTRY_SIZE,
682 QCOW2_OPT_REFCOUNT_CACHE_SIZE,
683 QCOW2_OPT_CACHE_CLEAN_INTERVAL,
684 NULL
687 static QemuOptsList qcow2_runtime_opts = {
688 .name = "qcow2",
689 .head = QTAILQ_HEAD_INITIALIZER(qcow2_runtime_opts.head),
690 .desc = {
692 .name = QCOW2_OPT_LAZY_REFCOUNTS,
693 .type = QEMU_OPT_BOOL,
694 .help = "Postpone refcount updates",
697 .name = QCOW2_OPT_DISCARD_REQUEST,
698 .type = QEMU_OPT_BOOL,
699 .help = "Pass guest discard requests to the layer below",
702 .name = QCOW2_OPT_DISCARD_SNAPSHOT,
703 .type = QEMU_OPT_BOOL,
704 .help = "Generate discard requests when snapshot related space "
705 "is freed",
708 .name = QCOW2_OPT_DISCARD_OTHER,
709 .type = QEMU_OPT_BOOL,
710 .help = "Generate discard requests when other clusters are freed",
713 .name = QCOW2_OPT_OVERLAP,
714 .type = QEMU_OPT_STRING,
715 .help = "Selects which overlap checks to perform from a range of "
716 "templates (none, constant, cached, all)",
719 .name = QCOW2_OPT_OVERLAP_TEMPLATE,
720 .type = QEMU_OPT_STRING,
721 .help = "Selects which overlap checks to perform from a range of "
722 "templates (none, constant, cached, all)",
725 .name = QCOW2_OPT_OVERLAP_MAIN_HEADER,
726 .type = QEMU_OPT_BOOL,
727 .help = "Check for unintended writes into the main qcow2 header",
730 .name = QCOW2_OPT_OVERLAP_ACTIVE_L1,
731 .type = QEMU_OPT_BOOL,
732 .help = "Check for unintended writes into the active L1 table",
735 .name = QCOW2_OPT_OVERLAP_ACTIVE_L2,
736 .type = QEMU_OPT_BOOL,
737 .help = "Check for unintended writes into an active L2 table",
740 .name = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
741 .type = QEMU_OPT_BOOL,
742 .help = "Check for unintended writes into the refcount table",
745 .name = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
746 .type = QEMU_OPT_BOOL,
747 .help = "Check for unintended writes into a refcount block",
750 .name = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
751 .type = QEMU_OPT_BOOL,
752 .help = "Check for unintended writes into the snapshot table",
755 .name = QCOW2_OPT_OVERLAP_INACTIVE_L1,
756 .type = QEMU_OPT_BOOL,
757 .help = "Check for unintended writes into an inactive L1 table",
760 .name = QCOW2_OPT_OVERLAP_INACTIVE_L2,
761 .type = QEMU_OPT_BOOL,
762 .help = "Check for unintended writes into an inactive L2 table",
765 .name = QCOW2_OPT_OVERLAP_BITMAP_DIRECTORY,
766 .type = QEMU_OPT_BOOL,
767 .help = "Check for unintended writes into the bitmap directory",
770 .name = QCOW2_OPT_CACHE_SIZE,
771 .type = QEMU_OPT_SIZE,
772 .help = "Maximum combined metadata (L2 tables and refcount blocks) "
773 "cache size",
776 .name = QCOW2_OPT_L2_CACHE_SIZE,
777 .type = QEMU_OPT_SIZE,
778 .help = "Maximum L2 table cache size",
781 .name = QCOW2_OPT_L2_CACHE_ENTRY_SIZE,
782 .type = QEMU_OPT_SIZE,
783 .help = "Size of each entry in the L2 cache",
786 .name = QCOW2_OPT_REFCOUNT_CACHE_SIZE,
787 .type = QEMU_OPT_SIZE,
788 .help = "Maximum refcount block cache size",
791 .name = QCOW2_OPT_CACHE_CLEAN_INTERVAL,
792 .type = QEMU_OPT_NUMBER,
793 .help = "Clean unused cache entries after this time (in seconds)",
795 BLOCK_CRYPTO_OPT_DEF_KEY_SECRET("encrypt.",
796 "ID of secret providing qcow2 AES key or LUKS passphrase"),
797 { /* end of list */ }
801 static const char *overlap_bool_option_names[QCOW2_OL_MAX_BITNR] = {
802 [QCOW2_OL_MAIN_HEADER_BITNR] = QCOW2_OPT_OVERLAP_MAIN_HEADER,
803 [QCOW2_OL_ACTIVE_L1_BITNR] = QCOW2_OPT_OVERLAP_ACTIVE_L1,
804 [QCOW2_OL_ACTIVE_L2_BITNR] = QCOW2_OPT_OVERLAP_ACTIVE_L2,
805 [QCOW2_OL_REFCOUNT_TABLE_BITNR] = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
806 [QCOW2_OL_REFCOUNT_BLOCK_BITNR] = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
807 [QCOW2_OL_SNAPSHOT_TABLE_BITNR] = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
808 [QCOW2_OL_INACTIVE_L1_BITNR] = QCOW2_OPT_OVERLAP_INACTIVE_L1,
809 [QCOW2_OL_INACTIVE_L2_BITNR] = QCOW2_OPT_OVERLAP_INACTIVE_L2,
810 [QCOW2_OL_BITMAP_DIRECTORY_BITNR] = QCOW2_OPT_OVERLAP_BITMAP_DIRECTORY,
813 static void cache_clean_timer_cb(void *opaque)
815 BlockDriverState *bs = opaque;
816 BDRVQcow2State *s = bs->opaque;
817 qcow2_cache_clean_unused(s->l2_table_cache);
818 qcow2_cache_clean_unused(s->refcount_block_cache);
819 timer_mod(s->cache_clean_timer, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) +
820 (int64_t) s->cache_clean_interval * 1000);
823 static void cache_clean_timer_init(BlockDriverState *bs, AioContext *context)
825 BDRVQcow2State *s = bs->opaque;
826 if (s->cache_clean_interval > 0) {
827 s->cache_clean_timer = aio_timer_new(context, QEMU_CLOCK_VIRTUAL,
828 SCALE_MS, cache_clean_timer_cb,
829 bs);
830 timer_mod(s->cache_clean_timer, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) +
831 (int64_t) s->cache_clean_interval * 1000);
835 static void cache_clean_timer_del(BlockDriverState *bs)
837 BDRVQcow2State *s = bs->opaque;
838 if (s->cache_clean_timer) {
839 timer_del(s->cache_clean_timer);
840 timer_free(s->cache_clean_timer);
841 s->cache_clean_timer = NULL;
845 static void qcow2_detach_aio_context(BlockDriverState *bs)
847 cache_clean_timer_del(bs);
850 static void qcow2_attach_aio_context(BlockDriverState *bs,
851 AioContext *new_context)
853 cache_clean_timer_init(bs, new_context);
856 static void read_cache_sizes(BlockDriverState *bs, QemuOpts *opts,
857 uint64_t *l2_cache_size,
858 uint64_t *l2_cache_entry_size,
859 uint64_t *refcount_cache_size, Error **errp)
861 BDRVQcow2State *s = bs->opaque;
862 uint64_t combined_cache_size, l2_cache_max_setting;
863 bool l2_cache_size_set, refcount_cache_size_set, combined_cache_size_set;
864 bool l2_cache_entry_size_set;
865 int min_refcount_cache = MIN_REFCOUNT_CACHE_SIZE * s->cluster_size;
866 uint64_t virtual_disk_size = bs->total_sectors * BDRV_SECTOR_SIZE;
867 uint64_t max_l2_entries = DIV_ROUND_UP(virtual_disk_size, s->cluster_size);
868 /* An L2 table is always one cluster in size so the max cache size
869 * should be a multiple of the cluster size. */
870 uint64_t max_l2_cache = ROUND_UP(max_l2_entries * sizeof(uint64_t),
871 s->cluster_size);
873 combined_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_CACHE_SIZE);
874 l2_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_L2_CACHE_SIZE);
875 refcount_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
876 l2_cache_entry_size_set = qemu_opt_get(opts, QCOW2_OPT_L2_CACHE_ENTRY_SIZE);
878 combined_cache_size = qemu_opt_get_size(opts, QCOW2_OPT_CACHE_SIZE, 0);
879 l2_cache_max_setting = qemu_opt_get_size(opts, QCOW2_OPT_L2_CACHE_SIZE,
880 DEFAULT_L2_CACHE_MAX_SIZE);
881 *refcount_cache_size = qemu_opt_get_size(opts,
882 QCOW2_OPT_REFCOUNT_CACHE_SIZE, 0);
884 *l2_cache_entry_size = qemu_opt_get_size(
885 opts, QCOW2_OPT_L2_CACHE_ENTRY_SIZE, s->cluster_size);
887 *l2_cache_size = MIN(max_l2_cache, l2_cache_max_setting);
889 if (combined_cache_size_set) {
890 if (l2_cache_size_set && refcount_cache_size_set) {
891 error_setg(errp, QCOW2_OPT_CACHE_SIZE ", " QCOW2_OPT_L2_CACHE_SIZE
892 " and " QCOW2_OPT_REFCOUNT_CACHE_SIZE " may not be set "
893 "at the same time");
894 return;
895 } else if (l2_cache_size_set &&
896 (l2_cache_max_setting > combined_cache_size)) {
897 error_setg(errp, QCOW2_OPT_L2_CACHE_SIZE " may not exceed "
898 QCOW2_OPT_CACHE_SIZE);
899 return;
900 } else if (*refcount_cache_size > combined_cache_size) {
901 error_setg(errp, QCOW2_OPT_REFCOUNT_CACHE_SIZE " may not exceed "
902 QCOW2_OPT_CACHE_SIZE);
903 return;
906 if (l2_cache_size_set) {
907 *refcount_cache_size = combined_cache_size - *l2_cache_size;
908 } else if (refcount_cache_size_set) {
909 *l2_cache_size = combined_cache_size - *refcount_cache_size;
910 } else {
911 /* Assign as much memory as possible to the L2 cache, and
912 * use the remainder for the refcount cache */
913 if (combined_cache_size >= max_l2_cache + min_refcount_cache) {
914 *l2_cache_size = max_l2_cache;
915 *refcount_cache_size = combined_cache_size - *l2_cache_size;
916 } else {
917 *refcount_cache_size =
918 MIN(combined_cache_size, min_refcount_cache);
919 *l2_cache_size = combined_cache_size - *refcount_cache_size;
925 * If the L2 cache is not enough to cover the whole disk then
926 * default to 4KB entries. Smaller entries reduce the cost of
927 * loads and evictions and increase I/O performance.
929 if (*l2_cache_size < max_l2_cache && !l2_cache_entry_size_set) {
930 *l2_cache_entry_size = MIN(s->cluster_size, 4096);
933 /* l2_cache_size and refcount_cache_size are ensured to have at least
934 * their minimum values in qcow2_update_options_prepare() */
936 if (*l2_cache_entry_size < (1 << MIN_CLUSTER_BITS) ||
937 *l2_cache_entry_size > s->cluster_size ||
938 !is_power_of_2(*l2_cache_entry_size)) {
939 error_setg(errp, "L2 cache entry size must be a power of two "
940 "between %d and the cluster size (%d)",
941 1 << MIN_CLUSTER_BITS, s->cluster_size);
942 return;
946 typedef struct Qcow2ReopenState {
947 Qcow2Cache *l2_table_cache;
948 Qcow2Cache *refcount_block_cache;
949 int l2_slice_size; /* Number of entries in a slice of the L2 table */
950 bool use_lazy_refcounts;
951 int overlap_check;
952 bool discard_passthrough[QCOW2_DISCARD_MAX];
953 uint64_t cache_clean_interval;
954 QCryptoBlockOpenOptions *crypto_opts; /* Disk encryption runtime options */
955 } Qcow2ReopenState;
957 static int qcow2_update_options_prepare(BlockDriverState *bs,
958 Qcow2ReopenState *r,
959 QDict *options, int flags,
960 Error **errp)
962 BDRVQcow2State *s = bs->opaque;
963 QemuOpts *opts = NULL;
964 const char *opt_overlap_check, *opt_overlap_check_template;
965 int overlap_check_template = 0;
966 uint64_t l2_cache_size, l2_cache_entry_size, refcount_cache_size;
967 int i;
968 const char *encryptfmt;
969 QDict *encryptopts = NULL;
970 Error *local_err = NULL;
971 int ret;
973 qdict_extract_subqdict(options, &encryptopts, "encrypt.");
974 encryptfmt = qdict_get_try_str(encryptopts, "format");
976 opts = qemu_opts_create(&qcow2_runtime_opts, NULL, 0, &error_abort);
977 qemu_opts_absorb_qdict(opts, options, &local_err);
978 if (local_err) {
979 error_propagate(errp, local_err);
980 ret = -EINVAL;
981 goto fail;
984 /* get L2 table/refcount block cache size from command line options */
985 read_cache_sizes(bs, opts, &l2_cache_size, &l2_cache_entry_size,
986 &refcount_cache_size, &local_err);
987 if (local_err) {
988 error_propagate(errp, local_err);
989 ret = -EINVAL;
990 goto fail;
993 l2_cache_size /= l2_cache_entry_size;
994 if (l2_cache_size < MIN_L2_CACHE_SIZE) {
995 l2_cache_size = MIN_L2_CACHE_SIZE;
997 if (l2_cache_size > INT_MAX) {
998 error_setg(errp, "L2 cache size too big");
999 ret = -EINVAL;
1000 goto fail;
1003 refcount_cache_size /= s->cluster_size;
1004 if (refcount_cache_size < MIN_REFCOUNT_CACHE_SIZE) {
1005 refcount_cache_size = MIN_REFCOUNT_CACHE_SIZE;
1007 if (refcount_cache_size > INT_MAX) {
1008 error_setg(errp, "Refcount cache size too big");
1009 ret = -EINVAL;
1010 goto fail;
1013 /* alloc new L2 table/refcount block cache, flush old one */
1014 if (s->l2_table_cache) {
1015 ret = qcow2_cache_flush(bs, s->l2_table_cache);
1016 if (ret) {
1017 error_setg_errno(errp, -ret, "Failed to flush the L2 table cache");
1018 goto fail;
1022 if (s->refcount_block_cache) {
1023 ret = qcow2_cache_flush(bs, s->refcount_block_cache);
1024 if (ret) {
1025 error_setg_errno(errp, -ret,
1026 "Failed to flush the refcount block cache");
1027 goto fail;
1031 r->l2_slice_size = l2_cache_entry_size / sizeof(uint64_t);
1032 r->l2_table_cache = qcow2_cache_create(bs, l2_cache_size,
1033 l2_cache_entry_size);
1034 r->refcount_block_cache = qcow2_cache_create(bs, refcount_cache_size,
1035 s->cluster_size);
1036 if (r->l2_table_cache == NULL || r->refcount_block_cache == NULL) {
1037 error_setg(errp, "Could not allocate metadata caches");
1038 ret = -ENOMEM;
1039 goto fail;
1042 /* New interval for cache cleanup timer */
1043 r->cache_clean_interval =
1044 qemu_opt_get_number(opts, QCOW2_OPT_CACHE_CLEAN_INTERVAL,
1045 DEFAULT_CACHE_CLEAN_INTERVAL);
1046 #ifndef CONFIG_LINUX
1047 if (r->cache_clean_interval != 0) {
1048 error_setg(errp, QCOW2_OPT_CACHE_CLEAN_INTERVAL
1049 " not supported on this host");
1050 ret = -EINVAL;
1051 goto fail;
1053 #endif
1054 if (r->cache_clean_interval > UINT_MAX) {
1055 error_setg(errp, "Cache clean interval too big");
1056 ret = -EINVAL;
1057 goto fail;
1060 /* lazy-refcounts; flush if going from enabled to disabled */
1061 r->use_lazy_refcounts = qemu_opt_get_bool(opts, QCOW2_OPT_LAZY_REFCOUNTS,
1062 (s->compatible_features & QCOW2_COMPAT_LAZY_REFCOUNTS));
1063 if (r->use_lazy_refcounts && s->qcow_version < 3) {
1064 error_setg(errp, "Lazy refcounts require a qcow2 image with at least "
1065 "qemu 1.1 compatibility level");
1066 ret = -EINVAL;
1067 goto fail;
1070 if (s->use_lazy_refcounts && !r->use_lazy_refcounts) {
1071 ret = qcow2_mark_clean(bs);
1072 if (ret < 0) {
1073 error_setg_errno(errp, -ret, "Failed to disable lazy refcounts");
1074 goto fail;
1078 /* Overlap check options */
1079 opt_overlap_check = qemu_opt_get(opts, QCOW2_OPT_OVERLAP);
1080 opt_overlap_check_template = qemu_opt_get(opts, QCOW2_OPT_OVERLAP_TEMPLATE);
1081 if (opt_overlap_check_template && opt_overlap_check &&
1082 strcmp(opt_overlap_check_template, opt_overlap_check))
1084 error_setg(errp, "Conflicting values for qcow2 options '"
1085 QCOW2_OPT_OVERLAP "' ('%s') and '" QCOW2_OPT_OVERLAP_TEMPLATE
1086 "' ('%s')", opt_overlap_check, opt_overlap_check_template);
1087 ret = -EINVAL;
1088 goto fail;
1090 if (!opt_overlap_check) {
1091 opt_overlap_check = opt_overlap_check_template ?: "cached";
1094 if (!strcmp(opt_overlap_check, "none")) {
1095 overlap_check_template = 0;
1096 } else if (!strcmp(opt_overlap_check, "constant")) {
1097 overlap_check_template = QCOW2_OL_CONSTANT;
1098 } else if (!strcmp(opt_overlap_check, "cached")) {
1099 overlap_check_template = QCOW2_OL_CACHED;
1100 } else if (!strcmp(opt_overlap_check, "all")) {
1101 overlap_check_template = QCOW2_OL_ALL;
1102 } else {
1103 error_setg(errp, "Unsupported value '%s' for qcow2 option "
1104 "'overlap-check'. Allowed are any of the following: "
1105 "none, constant, cached, all", opt_overlap_check);
1106 ret = -EINVAL;
1107 goto fail;
1110 r->overlap_check = 0;
1111 for (i = 0; i < QCOW2_OL_MAX_BITNR; i++) {
1112 /* overlap-check defines a template bitmask, but every flag may be
1113 * overwritten through the associated boolean option */
1114 r->overlap_check |=
1115 qemu_opt_get_bool(opts, overlap_bool_option_names[i],
1116 overlap_check_template & (1 << i)) << i;
1119 r->discard_passthrough[QCOW2_DISCARD_NEVER] = false;
1120 r->discard_passthrough[QCOW2_DISCARD_ALWAYS] = true;
1121 r->discard_passthrough[QCOW2_DISCARD_REQUEST] =
1122 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_REQUEST,
1123 flags & BDRV_O_UNMAP);
1124 r->discard_passthrough[QCOW2_DISCARD_SNAPSHOT] =
1125 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_SNAPSHOT, true);
1126 r->discard_passthrough[QCOW2_DISCARD_OTHER] =
1127 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_OTHER, false);
1129 switch (s->crypt_method_header) {
1130 case QCOW_CRYPT_NONE:
1131 if (encryptfmt) {
1132 error_setg(errp, "No encryption in image header, but options "
1133 "specified format '%s'", encryptfmt);
1134 ret = -EINVAL;
1135 goto fail;
1137 break;
1139 case QCOW_CRYPT_AES:
1140 if (encryptfmt && !g_str_equal(encryptfmt, "aes")) {
1141 error_setg(errp,
1142 "Header reported 'aes' encryption format but "
1143 "options specify '%s'", encryptfmt);
1144 ret = -EINVAL;
1145 goto fail;
1147 qdict_put_str(encryptopts, "format", "qcow");
1148 r->crypto_opts = block_crypto_open_opts_init(encryptopts, errp);
1149 break;
1151 case QCOW_CRYPT_LUKS:
1152 if (encryptfmt && !g_str_equal(encryptfmt, "luks")) {
1153 error_setg(errp,
1154 "Header reported 'luks' encryption format but "
1155 "options specify '%s'", encryptfmt);
1156 ret = -EINVAL;
1157 goto fail;
1159 qdict_put_str(encryptopts, "format", "luks");
1160 r->crypto_opts = block_crypto_open_opts_init(encryptopts, errp);
1161 break;
1163 default:
1164 error_setg(errp, "Unsupported encryption method %d",
1165 s->crypt_method_header);
1166 break;
1168 if (s->crypt_method_header != QCOW_CRYPT_NONE && !r->crypto_opts) {
1169 ret = -EINVAL;
1170 goto fail;
1173 ret = 0;
1174 fail:
1175 qobject_unref(encryptopts);
1176 qemu_opts_del(opts);
1177 opts = NULL;
1178 return ret;
1181 static void qcow2_update_options_commit(BlockDriverState *bs,
1182 Qcow2ReopenState *r)
1184 BDRVQcow2State *s = bs->opaque;
1185 int i;
1187 if (s->l2_table_cache) {
1188 qcow2_cache_destroy(s->l2_table_cache);
1190 if (s->refcount_block_cache) {
1191 qcow2_cache_destroy(s->refcount_block_cache);
1193 s->l2_table_cache = r->l2_table_cache;
1194 s->refcount_block_cache = r->refcount_block_cache;
1195 s->l2_slice_size = r->l2_slice_size;
1197 s->overlap_check = r->overlap_check;
1198 s->use_lazy_refcounts = r->use_lazy_refcounts;
1200 for (i = 0; i < QCOW2_DISCARD_MAX; i++) {
1201 s->discard_passthrough[i] = r->discard_passthrough[i];
1204 if (s->cache_clean_interval != r->cache_clean_interval) {
1205 cache_clean_timer_del(bs);
1206 s->cache_clean_interval = r->cache_clean_interval;
1207 cache_clean_timer_init(bs, bdrv_get_aio_context(bs));
1210 qapi_free_QCryptoBlockOpenOptions(s->crypto_opts);
1211 s->crypto_opts = r->crypto_opts;
1214 static void qcow2_update_options_abort(BlockDriverState *bs,
1215 Qcow2ReopenState *r)
1217 if (r->l2_table_cache) {
1218 qcow2_cache_destroy(r->l2_table_cache);
1220 if (r->refcount_block_cache) {
1221 qcow2_cache_destroy(r->refcount_block_cache);
1223 qapi_free_QCryptoBlockOpenOptions(r->crypto_opts);
1226 static int qcow2_update_options(BlockDriverState *bs, QDict *options,
1227 int flags, Error **errp)
1229 Qcow2ReopenState r = {};
1230 int ret;
1232 ret = qcow2_update_options_prepare(bs, &r, options, flags, errp);
1233 if (ret >= 0) {
1234 qcow2_update_options_commit(bs, &r);
1235 } else {
1236 qcow2_update_options_abort(bs, &r);
1239 return ret;
1242 /* Called with s->lock held. */
1243 static int coroutine_fn qcow2_do_open(BlockDriverState *bs, QDict *options,
1244 int flags, Error **errp)
1246 BDRVQcow2State *s = bs->opaque;
1247 unsigned int len, i;
1248 int ret = 0;
1249 QCowHeader header;
1250 Error *local_err = NULL;
1251 uint64_t ext_end;
1252 uint64_t l1_vm_state_index;
1253 bool update_header = false;
1255 ret = bdrv_pread(bs->file, 0, &header, sizeof(header));
1256 if (ret < 0) {
1257 error_setg_errno(errp, -ret, "Could not read qcow2 header");
1258 goto fail;
1260 header.magic = be32_to_cpu(header.magic);
1261 header.version = be32_to_cpu(header.version);
1262 header.backing_file_offset = be64_to_cpu(header.backing_file_offset);
1263 header.backing_file_size = be32_to_cpu(header.backing_file_size);
1264 header.size = be64_to_cpu(header.size);
1265 header.cluster_bits = be32_to_cpu(header.cluster_bits);
1266 header.crypt_method = be32_to_cpu(header.crypt_method);
1267 header.l1_table_offset = be64_to_cpu(header.l1_table_offset);
1268 header.l1_size = be32_to_cpu(header.l1_size);
1269 header.refcount_table_offset = be64_to_cpu(header.refcount_table_offset);
1270 header.refcount_table_clusters =
1271 be32_to_cpu(header.refcount_table_clusters);
1272 header.snapshots_offset = be64_to_cpu(header.snapshots_offset);
1273 header.nb_snapshots = be32_to_cpu(header.nb_snapshots);
1275 if (header.magic != QCOW_MAGIC) {
1276 error_setg(errp, "Image is not in qcow2 format");
1277 ret = -EINVAL;
1278 goto fail;
1280 if (header.version < 2 || header.version > 3) {
1281 error_setg(errp, "Unsupported qcow2 version %" PRIu32, header.version);
1282 ret = -ENOTSUP;
1283 goto fail;
1286 s->qcow_version = header.version;
1288 /* Initialise cluster size */
1289 if (header.cluster_bits < MIN_CLUSTER_BITS ||
1290 header.cluster_bits > MAX_CLUSTER_BITS) {
1291 error_setg(errp, "Unsupported cluster size: 2^%" PRIu32,
1292 header.cluster_bits);
1293 ret = -EINVAL;
1294 goto fail;
1297 s->cluster_bits = header.cluster_bits;
1298 s->cluster_size = 1 << s->cluster_bits;
1300 /* Initialise version 3 header fields */
1301 if (header.version == 2) {
1302 header.incompatible_features = 0;
1303 header.compatible_features = 0;
1304 header.autoclear_features = 0;
1305 header.refcount_order = 4;
1306 header.header_length = 72;
1307 } else {
1308 header.incompatible_features =
1309 be64_to_cpu(header.incompatible_features);
1310 header.compatible_features = be64_to_cpu(header.compatible_features);
1311 header.autoclear_features = be64_to_cpu(header.autoclear_features);
1312 header.refcount_order = be32_to_cpu(header.refcount_order);
1313 header.header_length = be32_to_cpu(header.header_length);
1315 if (header.header_length < 104) {
1316 error_setg(errp, "qcow2 header too short");
1317 ret = -EINVAL;
1318 goto fail;
1322 if (header.header_length > s->cluster_size) {
1323 error_setg(errp, "qcow2 header exceeds cluster size");
1324 ret = -EINVAL;
1325 goto fail;
1328 if (header.header_length > sizeof(header)) {
1329 s->unknown_header_fields_size = header.header_length - sizeof(header);
1330 s->unknown_header_fields = g_malloc(s->unknown_header_fields_size);
1331 ret = bdrv_pread(bs->file, sizeof(header), s->unknown_header_fields,
1332 s->unknown_header_fields_size);
1333 if (ret < 0) {
1334 error_setg_errno(errp, -ret, "Could not read unknown qcow2 header "
1335 "fields");
1336 goto fail;
1340 if (header.backing_file_offset > s->cluster_size) {
1341 error_setg(errp, "Invalid backing file offset");
1342 ret = -EINVAL;
1343 goto fail;
1346 if (header.backing_file_offset) {
1347 ext_end = header.backing_file_offset;
1348 } else {
1349 ext_end = 1 << header.cluster_bits;
1352 /* Handle feature bits */
1353 s->incompatible_features = header.incompatible_features;
1354 s->compatible_features = header.compatible_features;
1355 s->autoclear_features = header.autoclear_features;
1357 if (s->incompatible_features & ~QCOW2_INCOMPAT_MASK) {
1358 void *feature_table = NULL;
1359 qcow2_read_extensions(bs, header.header_length, ext_end,
1360 &feature_table, flags, NULL, NULL);
1361 report_unsupported_feature(errp, feature_table,
1362 s->incompatible_features &
1363 ~QCOW2_INCOMPAT_MASK);
1364 ret = -ENOTSUP;
1365 g_free(feature_table);
1366 goto fail;
1369 if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
1370 /* Corrupt images may not be written to unless they are being repaired
1372 if ((flags & BDRV_O_RDWR) && !(flags & BDRV_O_CHECK)) {
1373 error_setg(errp, "qcow2: Image is corrupt; cannot be opened "
1374 "read/write");
1375 ret = -EACCES;
1376 goto fail;
1380 /* Check support for various header values */
1381 if (header.refcount_order > 6) {
1382 error_setg(errp, "Reference count entry width too large; may not "
1383 "exceed 64 bits");
1384 ret = -EINVAL;
1385 goto fail;
1387 s->refcount_order = header.refcount_order;
1388 s->refcount_bits = 1 << s->refcount_order;
1389 s->refcount_max = UINT64_C(1) << (s->refcount_bits - 1);
1390 s->refcount_max += s->refcount_max - 1;
1392 s->crypt_method_header = header.crypt_method;
1393 if (s->crypt_method_header) {
1394 if (bdrv_uses_whitelist() &&
1395 s->crypt_method_header == QCOW_CRYPT_AES) {
1396 error_setg(errp,
1397 "Use of AES-CBC encrypted qcow2 images is no longer "
1398 "supported in system emulators");
1399 error_append_hint(errp,
1400 "You can use 'qemu-img convert' to convert your "
1401 "image to an alternative supported format, such "
1402 "as unencrypted qcow2, or raw with the LUKS "
1403 "format instead.\n");
1404 ret = -ENOSYS;
1405 goto fail;
1408 if (s->crypt_method_header == QCOW_CRYPT_AES) {
1409 s->crypt_physical_offset = false;
1410 } else {
1411 /* Assuming LUKS and any future crypt methods we
1412 * add will all use physical offsets, due to the
1413 * fact that the alternative is insecure... */
1414 s->crypt_physical_offset = true;
1417 bs->encrypted = true;
1420 s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */
1421 s->l2_size = 1 << s->l2_bits;
1422 /* 2^(s->refcount_order - 3) is the refcount width in bytes */
1423 s->refcount_block_bits = s->cluster_bits - (s->refcount_order - 3);
1424 s->refcount_block_size = 1 << s->refcount_block_bits;
1425 bs->total_sectors = header.size / BDRV_SECTOR_SIZE;
1426 s->csize_shift = (62 - (s->cluster_bits - 8));
1427 s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;
1428 s->cluster_offset_mask = (1LL << s->csize_shift) - 1;
1430 s->refcount_table_offset = header.refcount_table_offset;
1431 s->refcount_table_size =
1432 header.refcount_table_clusters << (s->cluster_bits - 3);
1434 if (header.refcount_table_clusters == 0 && !(flags & BDRV_O_CHECK)) {
1435 error_setg(errp, "Image does not contain a reference count table");
1436 ret = -EINVAL;
1437 goto fail;
1440 ret = qcow2_validate_table(bs, s->refcount_table_offset,
1441 header.refcount_table_clusters,
1442 s->cluster_size, QCOW_MAX_REFTABLE_SIZE,
1443 "Reference count table", errp);
1444 if (ret < 0) {
1445 goto fail;
1448 if (!(flags & BDRV_O_CHECK)) {
1450 * The total size in bytes of the snapshot table is checked in
1451 * qcow2_read_snapshots() because the size of each snapshot is
1452 * variable and we don't know it yet.
1453 * Here we only check the offset and number of snapshots.
1455 ret = qcow2_validate_table(bs, header.snapshots_offset,
1456 header.nb_snapshots,
1457 sizeof(QCowSnapshotHeader),
1458 sizeof(QCowSnapshotHeader) *
1459 QCOW_MAX_SNAPSHOTS,
1460 "Snapshot table", errp);
1461 if (ret < 0) {
1462 goto fail;
1466 /* read the level 1 table */
1467 ret = qcow2_validate_table(bs, header.l1_table_offset,
1468 header.l1_size, sizeof(uint64_t),
1469 QCOW_MAX_L1_SIZE, "Active L1 table", errp);
1470 if (ret < 0) {
1471 goto fail;
1473 s->l1_size = header.l1_size;
1474 s->l1_table_offset = header.l1_table_offset;
1476 l1_vm_state_index = size_to_l1(s, header.size);
1477 if (l1_vm_state_index > INT_MAX) {
1478 error_setg(errp, "Image is too big");
1479 ret = -EFBIG;
1480 goto fail;
1482 s->l1_vm_state_index = l1_vm_state_index;
1484 /* the L1 table must contain at least enough entries to put
1485 header.size bytes */
1486 if (s->l1_size < s->l1_vm_state_index) {
1487 error_setg(errp, "L1 table is too small");
1488 ret = -EINVAL;
1489 goto fail;
1492 if (s->l1_size > 0) {
1493 s->l1_table = qemu_try_blockalign(bs->file->bs,
1494 ROUND_UP(s->l1_size * sizeof(uint64_t), 512));
1495 if (s->l1_table == NULL) {
1496 error_setg(errp, "Could not allocate L1 table");
1497 ret = -ENOMEM;
1498 goto fail;
1500 ret = bdrv_pread(bs->file, s->l1_table_offset, s->l1_table,
1501 s->l1_size * sizeof(uint64_t));
1502 if (ret < 0) {
1503 error_setg_errno(errp, -ret, "Could not read L1 table");
1504 goto fail;
1506 for(i = 0;i < s->l1_size; i++) {
1507 s->l1_table[i] = be64_to_cpu(s->l1_table[i]);
1511 /* Parse driver-specific options */
1512 ret = qcow2_update_options(bs, options, flags, errp);
1513 if (ret < 0) {
1514 goto fail;
1517 s->flags = flags;
1519 ret = qcow2_refcount_init(bs);
1520 if (ret != 0) {
1521 error_setg_errno(errp, -ret, "Could not initialize refcount handling");
1522 goto fail;
1525 QLIST_INIT(&s->cluster_allocs);
1526 QTAILQ_INIT(&s->discards);
1528 /* read qcow2 extensions */
1529 if (qcow2_read_extensions(bs, header.header_length, ext_end, NULL,
1530 flags, &update_header, &local_err)) {
1531 error_propagate(errp, local_err);
1532 ret = -EINVAL;
1533 goto fail;
1536 /* Open external data file */
1537 s->data_file = bdrv_open_child(NULL, options, "data-file", bs, &child_file,
1538 true, &local_err);
1539 if (local_err) {
1540 error_propagate(errp, local_err);
1541 ret = -EINVAL;
1542 goto fail;
1545 if (s->incompatible_features & QCOW2_INCOMPAT_DATA_FILE) {
1546 if (!s->data_file && s->image_data_file) {
1547 s->data_file = bdrv_open_child(s->image_data_file, options,
1548 "data-file", bs, &child_file,
1549 false, errp);
1550 if (!s->data_file) {
1551 ret = -EINVAL;
1552 goto fail;
1555 if (!s->data_file) {
1556 error_setg(errp, "'data-file' is required for this image");
1557 ret = -EINVAL;
1558 goto fail;
1560 } else {
1561 if (s->data_file) {
1562 error_setg(errp, "'data-file' can only be set for images with an "
1563 "external data file");
1564 ret = -EINVAL;
1565 goto fail;
1568 s->data_file = bs->file;
1570 if (data_file_is_raw(bs)) {
1571 error_setg(errp, "data-file-raw requires a data file");
1572 ret = -EINVAL;
1573 goto fail;
1577 /* qcow2_read_extension may have set up the crypto context
1578 * if the crypt method needs a header region, some methods
1579 * don't need header extensions, so must check here
1581 if (s->crypt_method_header && !s->crypto) {
1582 if (s->crypt_method_header == QCOW_CRYPT_AES) {
1583 unsigned int cflags = 0;
1584 if (flags & BDRV_O_NO_IO) {
1585 cflags |= QCRYPTO_BLOCK_OPEN_NO_IO;
1587 s->crypto = qcrypto_block_open(s->crypto_opts, "encrypt.",
1588 NULL, NULL, cflags,
1589 QCOW2_MAX_THREADS, errp);
1590 if (!s->crypto) {
1591 ret = -EINVAL;
1592 goto fail;
1594 } else if (!(flags & BDRV_O_NO_IO)) {
1595 error_setg(errp, "Missing CRYPTO header for crypt method %d",
1596 s->crypt_method_header);
1597 ret = -EINVAL;
1598 goto fail;
1602 /* read the backing file name */
1603 if (header.backing_file_offset != 0) {
1604 len = header.backing_file_size;
1605 if (len > MIN(1023, s->cluster_size - header.backing_file_offset) ||
1606 len >= sizeof(bs->backing_file)) {
1607 error_setg(errp, "Backing file name too long");
1608 ret = -EINVAL;
1609 goto fail;
1611 ret = bdrv_pread(bs->file, header.backing_file_offset,
1612 bs->auto_backing_file, len);
1613 if (ret < 0) {
1614 error_setg_errno(errp, -ret, "Could not read backing file name");
1615 goto fail;
1617 bs->auto_backing_file[len] = '\0';
1618 pstrcpy(bs->backing_file, sizeof(bs->backing_file),
1619 bs->auto_backing_file);
1620 s->image_backing_file = g_strdup(bs->auto_backing_file);
1624 * Internal snapshots; skip reading them in check mode, because
1625 * we do not need them then, and we do not want to abort because
1626 * of a broken table.
1628 if (!(flags & BDRV_O_CHECK)) {
1629 s->snapshots_offset = header.snapshots_offset;
1630 s->nb_snapshots = header.nb_snapshots;
1632 ret = qcow2_read_snapshots(bs, errp);
1633 if (ret < 0) {
1634 goto fail;
1638 /* Clear unknown autoclear feature bits */
1639 update_header |= s->autoclear_features & ~QCOW2_AUTOCLEAR_MASK;
1640 update_header =
1641 update_header && !bs->read_only && !(flags & BDRV_O_INACTIVE);
1642 if (update_header) {
1643 s->autoclear_features &= QCOW2_AUTOCLEAR_MASK;
1646 /* == Handle persistent dirty bitmaps ==
1648 * We want load dirty bitmaps in three cases:
1650 * 1. Normal open of the disk in active mode, not related to invalidation
1651 * after migration.
1653 * 2. Invalidation of the target vm after pre-copy phase of migration, if
1654 * bitmaps are _not_ migrating through migration channel, i.e.
1655 * 'dirty-bitmaps' capability is disabled.
1657 * 3. Invalidation of source vm after failed or canceled migration.
1658 * This is a very interesting case. There are two possible types of
1659 * bitmaps:
1661 * A. Stored on inactivation and removed. They should be loaded from the
1662 * image.
1664 * B. Not stored: not-persistent bitmaps and bitmaps, migrated through
1665 * the migration channel (with dirty-bitmaps capability).
1667 * On the other hand, there are two possible sub-cases:
1669 * 3.1 disk was changed by somebody else while were inactive. In this
1670 * case all in-RAM dirty bitmaps (both persistent and not) are
1671 * definitely invalid. And we don't have any method to determine
1672 * this.
1674 * Simple and safe thing is to just drop all the bitmaps of type B on
1675 * inactivation. But in this case we lose bitmaps in valid 4.2 case.
1677 * On the other hand, resuming source vm, if disk was already changed
1678 * is a bad thing anyway: not only bitmaps, the whole vm state is
1679 * out of sync with disk.
1681 * This means, that user or management tool, who for some reason
1682 * decided to resume source vm, after disk was already changed by
1683 * target vm, should at least drop all dirty bitmaps by hand.
1685 * So, we can ignore this case for now, but TODO: "generation"
1686 * extension for qcow2, to determine, that image was changed after
1687 * last inactivation. And if it is changed, we will drop (or at least
1688 * mark as 'invalid' all the bitmaps of type B, both persistent
1689 * and not).
1691 * 3.2 disk was _not_ changed while were inactive. Bitmaps may be saved
1692 * to disk ('dirty-bitmaps' capability disabled), or not saved
1693 * ('dirty-bitmaps' capability enabled), but we don't need to care
1694 * of: let's load bitmaps as always: stored bitmaps will be loaded,
1695 * and not stored has flag IN_USE=1 in the image and will be skipped
1696 * on loading.
1698 * One remaining possible case when we don't want load bitmaps:
1700 * 4. Open disk in inactive mode in target vm (bitmaps are migrating or
1701 * will be loaded on invalidation, no needs try loading them before)
1704 if (!(bdrv_get_flags(bs) & BDRV_O_INACTIVE)) {
1705 /* It's case 1, 2 or 3.2. Or 3.1 which is BUG in management layer. */
1706 bool header_updated = qcow2_load_dirty_bitmaps(bs, &local_err);
1707 if (local_err != NULL) {
1708 error_propagate(errp, local_err);
1709 ret = -EINVAL;
1710 goto fail;
1713 update_header = update_header && !header_updated;
1716 if (update_header) {
1717 ret = qcow2_update_header(bs);
1718 if (ret < 0) {
1719 error_setg_errno(errp, -ret, "Could not update qcow2 header");
1720 goto fail;
1724 bs->supported_zero_flags = header.version >= 3 ?
1725 BDRV_REQ_MAY_UNMAP | BDRV_REQ_NO_FALLBACK : 0;
1727 /* Repair image if dirty */
1728 if (!(flags & (BDRV_O_CHECK | BDRV_O_INACTIVE)) && !bs->read_only &&
1729 (s->incompatible_features & QCOW2_INCOMPAT_DIRTY)) {
1730 BdrvCheckResult result = {0};
1732 ret = qcow2_co_check_locked(bs, &result,
1733 BDRV_FIX_ERRORS | BDRV_FIX_LEAKS);
1734 if (ret < 0 || result.check_errors) {
1735 if (ret >= 0) {
1736 ret = -EIO;
1738 error_setg_errno(errp, -ret, "Could not repair dirty image");
1739 goto fail;
1743 #ifdef DEBUG_ALLOC
1745 BdrvCheckResult result = {0};
1746 qcow2_check_refcounts(bs, &result, 0);
1748 #endif
1750 qemu_co_queue_init(&s->thread_task_queue);
1752 return ret;
1754 fail:
1755 g_free(s->image_data_file);
1756 if (has_data_file(bs)) {
1757 bdrv_unref_child(bs, s->data_file);
1759 g_free(s->unknown_header_fields);
1760 cleanup_unknown_header_ext(bs);
1761 qcow2_free_snapshots(bs);
1762 qcow2_refcount_close(bs);
1763 qemu_vfree(s->l1_table);
1764 /* else pre-write overlap checks in cache_destroy may crash */
1765 s->l1_table = NULL;
1766 cache_clean_timer_del(bs);
1767 if (s->l2_table_cache) {
1768 qcow2_cache_destroy(s->l2_table_cache);
1770 if (s->refcount_block_cache) {
1771 qcow2_cache_destroy(s->refcount_block_cache);
1773 qcrypto_block_free(s->crypto);
1774 qapi_free_QCryptoBlockOpenOptions(s->crypto_opts);
1775 return ret;
1778 typedef struct QCow2OpenCo {
1779 BlockDriverState *bs;
1780 QDict *options;
1781 int flags;
1782 Error **errp;
1783 int ret;
1784 } QCow2OpenCo;
1786 static void coroutine_fn qcow2_open_entry(void *opaque)
1788 QCow2OpenCo *qoc = opaque;
1789 BDRVQcow2State *s = qoc->bs->opaque;
1791 qemu_co_mutex_lock(&s->lock);
1792 qoc->ret = qcow2_do_open(qoc->bs, qoc->options, qoc->flags, qoc->errp);
1793 qemu_co_mutex_unlock(&s->lock);
1796 static int qcow2_open(BlockDriverState *bs, QDict *options, int flags,
1797 Error **errp)
1799 BDRVQcow2State *s = bs->opaque;
1800 QCow2OpenCo qoc = {
1801 .bs = bs,
1802 .options = options,
1803 .flags = flags,
1804 .errp = errp,
1805 .ret = -EINPROGRESS
1808 bs->file = bdrv_open_child(NULL, options, "file", bs, &child_file,
1809 false, errp);
1810 if (!bs->file) {
1811 return -EINVAL;
1814 /* Initialise locks */
1815 qemu_co_mutex_init(&s->lock);
1817 if (qemu_in_coroutine()) {
1818 /* From bdrv_co_create. */
1819 qcow2_open_entry(&qoc);
1820 } else {
1821 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
1822 qemu_coroutine_enter(qemu_coroutine_create(qcow2_open_entry, &qoc));
1823 BDRV_POLL_WHILE(bs, qoc.ret == -EINPROGRESS);
1825 return qoc.ret;
1828 static void qcow2_refresh_limits(BlockDriverState *bs, Error **errp)
1830 BDRVQcow2State *s = bs->opaque;
1832 if (bs->encrypted) {
1833 /* Encryption works on a sector granularity */
1834 bs->bl.request_alignment = qcrypto_block_get_sector_size(s->crypto);
1836 bs->bl.pwrite_zeroes_alignment = s->cluster_size;
1837 bs->bl.pdiscard_alignment = s->cluster_size;
1840 static int qcow2_reopen_prepare(BDRVReopenState *state,
1841 BlockReopenQueue *queue, Error **errp)
1843 Qcow2ReopenState *r;
1844 int ret;
1846 r = g_new0(Qcow2ReopenState, 1);
1847 state->opaque = r;
1849 ret = qcow2_update_options_prepare(state->bs, r, state->options,
1850 state->flags, errp);
1851 if (ret < 0) {
1852 goto fail;
1855 /* We need to write out any unwritten data if we reopen read-only. */
1856 if ((state->flags & BDRV_O_RDWR) == 0) {
1857 ret = qcow2_reopen_bitmaps_ro(state->bs, errp);
1858 if (ret < 0) {
1859 goto fail;
1862 ret = bdrv_flush(state->bs);
1863 if (ret < 0) {
1864 goto fail;
1867 ret = qcow2_mark_clean(state->bs);
1868 if (ret < 0) {
1869 goto fail;
1873 return 0;
1875 fail:
1876 qcow2_update_options_abort(state->bs, r);
1877 g_free(r);
1878 return ret;
1881 static void qcow2_reopen_commit(BDRVReopenState *state)
1883 qcow2_update_options_commit(state->bs, state->opaque);
1884 if (state->flags & BDRV_O_RDWR) {
1885 Error *local_err = NULL;
1887 if (qcow2_reopen_bitmaps_rw(state->bs, &local_err) < 0) {
1889 * This is not fatal, bitmaps just left read-only, so all following
1890 * writes will fail. User can remove read-only bitmaps to unblock
1891 * writes or retry reopen.
1893 error_reportf_err(local_err,
1894 "%s: Failed to make dirty bitmaps writable: ",
1895 bdrv_get_node_name(state->bs));
1898 g_free(state->opaque);
1901 static void qcow2_reopen_abort(BDRVReopenState *state)
1903 qcow2_update_options_abort(state->bs, state->opaque);
1904 g_free(state->opaque);
1907 static void qcow2_join_options(QDict *options, QDict *old_options)
1909 bool has_new_overlap_template =
1910 qdict_haskey(options, QCOW2_OPT_OVERLAP) ||
1911 qdict_haskey(options, QCOW2_OPT_OVERLAP_TEMPLATE);
1912 bool has_new_total_cache_size =
1913 qdict_haskey(options, QCOW2_OPT_CACHE_SIZE);
1914 bool has_all_cache_options;
1916 /* New overlap template overrides all old overlap options */
1917 if (has_new_overlap_template) {
1918 qdict_del(old_options, QCOW2_OPT_OVERLAP);
1919 qdict_del(old_options, QCOW2_OPT_OVERLAP_TEMPLATE);
1920 qdict_del(old_options, QCOW2_OPT_OVERLAP_MAIN_HEADER);
1921 qdict_del(old_options, QCOW2_OPT_OVERLAP_ACTIVE_L1);
1922 qdict_del(old_options, QCOW2_OPT_OVERLAP_ACTIVE_L2);
1923 qdict_del(old_options, QCOW2_OPT_OVERLAP_REFCOUNT_TABLE);
1924 qdict_del(old_options, QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK);
1925 qdict_del(old_options, QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE);
1926 qdict_del(old_options, QCOW2_OPT_OVERLAP_INACTIVE_L1);
1927 qdict_del(old_options, QCOW2_OPT_OVERLAP_INACTIVE_L2);
1930 /* New total cache size overrides all old options */
1931 if (qdict_haskey(options, QCOW2_OPT_CACHE_SIZE)) {
1932 qdict_del(old_options, QCOW2_OPT_L2_CACHE_SIZE);
1933 qdict_del(old_options, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
1936 qdict_join(options, old_options, false);
1939 * If after merging all cache size options are set, an old total size is
1940 * overwritten. Do keep all options, however, if all three are new. The
1941 * resulting error message is what we want to happen.
1943 has_all_cache_options =
1944 qdict_haskey(options, QCOW2_OPT_CACHE_SIZE) ||
1945 qdict_haskey(options, QCOW2_OPT_L2_CACHE_SIZE) ||
1946 qdict_haskey(options, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
1948 if (has_all_cache_options && !has_new_total_cache_size) {
1949 qdict_del(options, QCOW2_OPT_CACHE_SIZE);
1953 static int coroutine_fn qcow2_co_block_status(BlockDriverState *bs,
1954 bool want_zero,
1955 int64_t offset, int64_t count,
1956 int64_t *pnum, int64_t *map,
1957 BlockDriverState **file)
1959 BDRVQcow2State *s = bs->opaque;
1960 uint64_t cluster_offset;
1961 unsigned int bytes;
1962 int ret, status = 0;
1964 qemu_co_mutex_lock(&s->lock);
1966 if (!s->metadata_preallocation_checked) {
1967 ret = qcow2_detect_metadata_preallocation(bs);
1968 s->metadata_preallocation = (ret == 1);
1969 s->metadata_preallocation_checked = true;
1972 bytes = MIN(INT_MAX, count);
1973 ret = qcow2_get_cluster_offset(bs, offset, &bytes, &cluster_offset);
1974 qemu_co_mutex_unlock(&s->lock);
1975 if (ret < 0) {
1976 return ret;
1979 *pnum = bytes;
1981 if ((ret == QCOW2_CLUSTER_NORMAL || ret == QCOW2_CLUSTER_ZERO_ALLOC) &&
1982 !s->crypto) {
1983 *map = cluster_offset | offset_into_cluster(s, offset);
1984 *file = s->data_file->bs;
1985 status |= BDRV_BLOCK_OFFSET_VALID;
1987 if (ret == QCOW2_CLUSTER_ZERO_PLAIN || ret == QCOW2_CLUSTER_ZERO_ALLOC) {
1988 status |= BDRV_BLOCK_ZERO;
1989 } else if (ret != QCOW2_CLUSTER_UNALLOCATED) {
1990 status |= BDRV_BLOCK_DATA;
1992 if (s->metadata_preallocation && (status & BDRV_BLOCK_DATA) &&
1993 (status & BDRV_BLOCK_OFFSET_VALID))
1995 status |= BDRV_BLOCK_RECURSE;
1997 return status;
2000 static coroutine_fn int qcow2_handle_l2meta(BlockDriverState *bs,
2001 QCowL2Meta **pl2meta,
2002 bool link_l2)
2004 int ret = 0;
2005 QCowL2Meta *l2meta = *pl2meta;
2007 while (l2meta != NULL) {
2008 QCowL2Meta *next;
2010 if (link_l2) {
2011 ret = qcow2_alloc_cluster_link_l2(bs, l2meta);
2012 if (ret) {
2013 goto out;
2015 } else {
2016 qcow2_alloc_cluster_abort(bs, l2meta);
2019 /* Take the request off the list of running requests */
2020 if (l2meta->nb_clusters != 0) {
2021 QLIST_REMOVE(l2meta, next_in_flight);
2024 qemu_co_queue_restart_all(&l2meta->dependent_requests);
2026 next = l2meta->next;
2027 g_free(l2meta);
2028 l2meta = next;
2030 out:
2031 *pl2meta = l2meta;
2032 return ret;
2035 static coroutine_fn int
2036 qcow2_co_preadv_encrypted(BlockDriverState *bs,
2037 uint64_t file_cluster_offset,
2038 uint64_t offset,
2039 uint64_t bytes,
2040 QEMUIOVector *qiov,
2041 uint64_t qiov_offset)
2043 int ret;
2044 BDRVQcow2State *s = bs->opaque;
2045 uint8_t *buf;
2047 assert(bs->encrypted && s->crypto);
2048 assert(bytes <= QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
2051 * For encrypted images, read everything into a temporary
2052 * contiguous buffer on which the AES functions can work.
2053 * Also, decryption in a separate buffer is better as it
2054 * prevents the guest from learning information about the
2055 * encrypted nature of the virtual disk.
2058 buf = qemu_try_blockalign(s->data_file->bs, bytes);
2059 if (buf == NULL) {
2060 return -ENOMEM;
2063 BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);
2064 ret = bdrv_co_pread(s->data_file,
2065 file_cluster_offset + offset_into_cluster(s, offset),
2066 bytes, buf, 0);
2067 if (ret < 0) {
2068 goto fail;
2071 assert(QEMU_IS_ALIGNED(offset, BDRV_SECTOR_SIZE));
2072 assert(QEMU_IS_ALIGNED(bytes, BDRV_SECTOR_SIZE));
2073 if (qcow2_co_decrypt(bs,
2074 file_cluster_offset + offset_into_cluster(s, offset),
2075 offset, buf, bytes) < 0)
2077 ret = -EIO;
2078 goto fail;
2080 qemu_iovec_from_buf(qiov, qiov_offset, buf, bytes);
2082 fail:
2083 qemu_vfree(buf);
2085 return ret;
2088 typedef struct Qcow2AioTask {
2089 AioTask task;
2091 BlockDriverState *bs;
2092 QCow2ClusterType cluster_type; /* only for read */
2093 uint64_t file_cluster_offset;
2094 uint64_t offset;
2095 uint64_t bytes;
2096 QEMUIOVector *qiov;
2097 uint64_t qiov_offset;
2098 QCowL2Meta *l2meta; /* only for write */
2099 } Qcow2AioTask;
2101 static coroutine_fn int qcow2_co_preadv_task_entry(AioTask *task);
2102 static coroutine_fn int qcow2_add_task(BlockDriverState *bs,
2103 AioTaskPool *pool,
2104 AioTaskFunc func,
2105 QCow2ClusterType cluster_type,
2106 uint64_t file_cluster_offset,
2107 uint64_t offset,
2108 uint64_t bytes,
2109 QEMUIOVector *qiov,
2110 size_t qiov_offset,
2111 QCowL2Meta *l2meta)
2113 Qcow2AioTask local_task;
2114 Qcow2AioTask *task = pool ? g_new(Qcow2AioTask, 1) : &local_task;
2116 *task = (Qcow2AioTask) {
2117 .task.func = func,
2118 .bs = bs,
2119 .cluster_type = cluster_type,
2120 .qiov = qiov,
2121 .file_cluster_offset = file_cluster_offset,
2122 .offset = offset,
2123 .bytes = bytes,
2124 .qiov_offset = qiov_offset,
2125 .l2meta = l2meta,
2128 trace_qcow2_add_task(qemu_coroutine_self(), bs, pool,
2129 func == qcow2_co_preadv_task_entry ? "read" : "write",
2130 cluster_type, file_cluster_offset, offset, bytes,
2131 qiov, qiov_offset);
2133 if (!pool) {
2134 return func(&task->task);
2137 aio_task_pool_start_task(pool, &task->task);
2139 return 0;
2142 static coroutine_fn int qcow2_co_preadv_task(BlockDriverState *bs,
2143 QCow2ClusterType cluster_type,
2144 uint64_t file_cluster_offset,
2145 uint64_t offset, uint64_t bytes,
2146 QEMUIOVector *qiov,
2147 size_t qiov_offset)
2149 BDRVQcow2State *s = bs->opaque;
2150 int offset_in_cluster = offset_into_cluster(s, offset);
2152 switch (cluster_type) {
2153 case QCOW2_CLUSTER_ZERO_PLAIN:
2154 case QCOW2_CLUSTER_ZERO_ALLOC:
2155 /* Both zero types are handled in qcow2_co_preadv_part */
2156 g_assert_not_reached();
2158 case QCOW2_CLUSTER_UNALLOCATED:
2159 assert(bs->backing); /* otherwise handled in qcow2_co_preadv_part */
2161 BLKDBG_EVENT(bs->file, BLKDBG_READ_BACKING_AIO);
2162 return bdrv_co_preadv_part(bs->backing, offset, bytes,
2163 qiov, qiov_offset, 0);
2165 case QCOW2_CLUSTER_COMPRESSED:
2166 return qcow2_co_preadv_compressed(bs, file_cluster_offset,
2167 offset, bytes, qiov, qiov_offset);
2169 case QCOW2_CLUSTER_NORMAL:
2170 if ((file_cluster_offset & 511) != 0) {
2171 return -EIO;
2174 if (bs->encrypted) {
2175 return qcow2_co_preadv_encrypted(bs, file_cluster_offset,
2176 offset, bytes, qiov, qiov_offset);
2179 BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);
2180 return bdrv_co_preadv_part(s->data_file,
2181 file_cluster_offset + offset_in_cluster,
2182 bytes, qiov, qiov_offset, 0);
2184 default:
2185 g_assert_not_reached();
2188 g_assert_not_reached();
2191 static coroutine_fn int qcow2_co_preadv_task_entry(AioTask *task)
2193 Qcow2AioTask *t = container_of(task, Qcow2AioTask, task);
2195 assert(!t->l2meta);
2197 return qcow2_co_preadv_task(t->bs, t->cluster_type, t->file_cluster_offset,
2198 t->offset, t->bytes, t->qiov, t->qiov_offset);
2201 static coroutine_fn int qcow2_co_preadv_part(BlockDriverState *bs,
2202 uint64_t offset, uint64_t bytes,
2203 QEMUIOVector *qiov,
2204 size_t qiov_offset, int flags)
2206 BDRVQcow2State *s = bs->opaque;
2207 int ret = 0;
2208 unsigned int cur_bytes; /* number of bytes in current iteration */
2209 uint64_t cluster_offset = 0;
2210 AioTaskPool *aio = NULL;
2212 while (bytes != 0 && aio_task_pool_status(aio) == 0) {
2213 /* prepare next request */
2214 cur_bytes = MIN(bytes, INT_MAX);
2215 if (s->crypto) {
2216 cur_bytes = MIN(cur_bytes,
2217 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
2220 qemu_co_mutex_lock(&s->lock);
2221 ret = qcow2_get_cluster_offset(bs, offset, &cur_bytes, &cluster_offset);
2222 qemu_co_mutex_unlock(&s->lock);
2223 if (ret < 0) {
2224 goto out;
2227 if (ret == QCOW2_CLUSTER_ZERO_PLAIN ||
2228 ret == QCOW2_CLUSTER_ZERO_ALLOC ||
2229 (ret == QCOW2_CLUSTER_UNALLOCATED && !bs->backing))
2231 qemu_iovec_memset(qiov, qiov_offset, 0, cur_bytes);
2232 } else {
2233 if (!aio && cur_bytes != bytes) {
2234 aio = aio_task_pool_new(QCOW2_MAX_WORKERS);
2236 ret = qcow2_add_task(bs, aio, qcow2_co_preadv_task_entry, ret,
2237 cluster_offset, offset, cur_bytes,
2238 qiov, qiov_offset, NULL);
2239 if (ret < 0) {
2240 goto out;
2244 bytes -= cur_bytes;
2245 offset += cur_bytes;
2246 qiov_offset += cur_bytes;
2249 out:
2250 if (aio) {
2251 aio_task_pool_wait_all(aio);
2252 if (ret == 0) {
2253 ret = aio_task_pool_status(aio);
2255 g_free(aio);
2258 return ret;
2261 /* Check if it's possible to merge a write request with the writing of
2262 * the data from the COW regions */
2263 static bool merge_cow(uint64_t offset, unsigned bytes,
2264 QEMUIOVector *qiov, size_t qiov_offset,
2265 QCowL2Meta *l2meta)
2267 QCowL2Meta *m;
2269 for (m = l2meta; m != NULL; m = m->next) {
2270 /* If both COW regions are empty then there's nothing to merge */
2271 if (m->cow_start.nb_bytes == 0 && m->cow_end.nb_bytes == 0) {
2272 continue;
2275 /* If COW regions are handled already, skip this too */
2276 if (m->skip_cow) {
2277 continue;
2280 /* The data (middle) region must be immediately after the
2281 * start region */
2282 if (l2meta_cow_start(m) + m->cow_start.nb_bytes != offset) {
2283 continue;
2286 /* The end region must be immediately after the data (middle)
2287 * region */
2288 if (m->offset + m->cow_end.offset != offset + bytes) {
2289 continue;
2292 /* Make sure that adding both COW regions to the QEMUIOVector
2293 * does not exceed IOV_MAX */
2294 if (qemu_iovec_subvec_niov(qiov, qiov_offset, bytes) > IOV_MAX - 2) {
2295 continue;
2298 m->data_qiov = qiov;
2299 m->data_qiov_offset = qiov_offset;
2300 return true;
2303 return false;
2306 static bool is_unallocated(BlockDriverState *bs, int64_t offset, int64_t bytes)
2308 int64_t nr;
2309 return !bytes ||
2310 (!bdrv_is_allocated_above(bs, NULL, false, offset, bytes, &nr) &&
2311 nr == bytes);
2314 static bool is_zero_cow(BlockDriverState *bs, QCowL2Meta *m)
2317 * This check is designed for optimization shortcut so it must be
2318 * efficient.
2319 * Instead of is_zero(), use is_unallocated() as it is faster (but not
2320 * as accurate and can result in false negatives).
2322 return is_unallocated(bs, m->offset + m->cow_start.offset,
2323 m->cow_start.nb_bytes) &&
2324 is_unallocated(bs, m->offset + m->cow_end.offset,
2325 m->cow_end.nb_bytes);
2328 static int handle_alloc_space(BlockDriverState *bs, QCowL2Meta *l2meta)
2330 BDRVQcow2State *s = bs->opaque;
2331 QCowL2Meta *m;
2333 if (!(s->data_file->bs->supported_zero_flags & BDRV_REQ_NO_FALLBACK)) {
2334 return 0;
2337 if (bs->encrypted) {
2338 return 0;
2341 for (m = l2meta; m != NULL; m = m->next) {
2342 int ret;
2344 if (!m->cow_start.nb_bytes && !m->cow_end.nb_bytes) {
2345 continue;
2348 if (!is_zero_cow(bs, m)) {
2349 continue;
2353 * instead of writing zero COW buffers,
2354 * efficiently zero out the whole clusters
2357 ret = qcow2_pre_write_overlap_check(bs, 0, m->alloc_offset,
2358 m->nb_clusters * s->cluster_size,
2359 true);
2360 if (ret < 0) {
2361 return ret;
2364 BLKDBG_EVENT(bs->file, BLKDBG_CLUSTER_ALLOC_SPACE);
2365 ret = bdrv_co_pwrite_zeroes(s->data_file, m->alloc_offset,
2366 m->nb_clusters * s->cluster_size,
2367 BDRV_REQ_NO_FALLBACK);
2368 if (ret < 0) {
2369 if (ret != -ENOTSUP && ret != -EAGAIN) {
2370 return ret;
2372 continue;
2375 trace_qcow2_skip_cow(qemu_coroutine_self(), m->offset, m->nb_clusters);
2376 m->skip_cow = true;
2378 return 0;
2382 * qcow2_co_pwritev_task
2383 * Called with s->lock unlocked
2384 * l2meta - if not NULL, qcow2_co_pwritev_task() will consume it. Caller must
2385 * not use it somehow after qcow2_co_pwritev_task() call
2387 static coroutine_fn int qcow2_co_pwritev_task(BlockDriverState *bs,
2388 uint64_t file_cluster_offset,
2389 uint64_t offset, uint64_t bytes,
2390 QEMUIOVector *qiov,
2391 uint64_t qiov_offset,
2392 QCowL2Meta *l2meta)
2394 int ret;
2395 BDRVQcow2State *s = bs->opaque;
2396 void *crypt_buf = NULL;
2397 int offset_in_cluster = offset_into_cluster(s, offset);
2398 QEMUIOVector encrypted_qiov;
2400 if (bs->encrypted) {
2401 assert(s->crypto);
2402 assert(bytes <= QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
2403 crypt_buf = qemu_try_blockalign(bs->file->bs, bytes);
2404 if (crypt_buf == NULL) {
2405 ret = -ENOMEM;
2406 goto out_unlocked;
2408 qemu_iovec_to_buf(qiov, qiov_offset, crypt_buf, bytes);
2410 if (qcow2_co_encrypt(bs, file_cluster_offset + offset_in_cluster,
2411 offset, crypt_buf, bytes) < 0)
2413 ret = -EIO;
2414 goto out_unlocked;
2417 qemu_iovec_init_buf(&encrypted_qiov, crypt_buf, bytes);
2418 qiov = &encrypted_qiov;
2419 qiov_offset = 0;
2422 /* Try to efficiently initialize the physical space with zeroes */
2423 ret = handle_alloc_space(bs, l2meta);
2424 if (ret < 0) {
2425 goto out_unlocked;
2429 * If we need to do COW, check if it's possible to merge the
2430 * writing of the guest data together with that of the COW regions.
2431 * If it's not possible (or not necessary) then write the
2432 * guest data now.
2434 if (!merge_cow(offset, bytes, qiov, qiov_offset, l2meta)) {
2435 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO);
2436 trace_qcow2_writev_data(qemu_coroutine_self(),
2437 file_cluster_offset + offset_in_cluster);
2438 ret = bdrv_co_pwritev_part(s->data_file,
2439 file_cluster_offset + offset_in_cluster,
2440 bytes, qiov, qiov_offset, 0);
2441 if (ret < 0) {
2442 goto out_unlocked;
2446 qemu_co_mutex_lock(&s->lock);
2448 ret = qcow2_handle_l2meta(bs, &l2meta, true);
2449 goto out_locked;
2451 out_unlocked:
2452 qemu_co_mutex_lock(&s->lock);
2454 out_locked:
2455 qcow2_handle_l2meta(bs, &l2meta, false);
2456 qemu_co_mutex_unlock(&s->lock);
2458 qemu_vfree(crypt_buf);
2460 return ret;
2463 static coroutine_fn int qcow2_co_pwritev_task_entry(AioTask *task)
2465 Qcow2AioTask *t = container_of(task, Qcow2AioTask, task);
2467 assert(!t->cluster_type);
2469 return qcow2_co_pwritev_task(t->bs, t->file_cluster_offset,
2470 t->offset, t->bytes, t->qiov, t->qiov_offset,
2471 t->l2meta);
2474 static coroutine_fn int qcow2_co_pwritev_part(
2475 BlockDriverState *bs, uint64_t offset, uint64_t bytes,
2476 QEMUIOVector *qiov, size_t qiov_offset, int flags)
2478 BDRVQcow2State *s = bs->opaque;
2479 int offset_in_cluster;
2480 int ret;
2481 unsigned int cur_bytes; /* number of sectors in current iteration */
2482 uint64_t cluster_offset;
2483 QCowL2Meta *l2meta = NULL;
2484 AioTaskPool *aio = NULL;
2486 trace_qcow2_writev_start_req(qemu_coroutine_self(), offset, bytes);
2488 while (bytes != 0 && aio_task_pool_status(aio) == 0) {
2490 l2meta = NULL;
2492 trace_qcow2_writev_start_part(qemu_coroutine_self());
2493 offset_in_cluster = offset_into_cluster(s, offset);
2494 cur_bytes = MIN(bytes, INT_MAX);
2495 if (bs->encrypted) {
2496 cur_bytes = MIN(cur_bytes,
2497 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size
2498 - offset_in_cluster);
2501 qemu_co_mutex_lock(&s->lock);
2503 ret = qcow2_alloc_cluster_offset(bs, offset, &cur_bytes,
2504 &cluster_offset, &l2meta);
2505 if (ret < 0) {
2506 goto out_locked;
2509 assert((cluster_offset & 511) == 0);
2511 ret = qcow2_pre_write_overlap_check(bs, 0,
2512 cluster_offset + offset_in_cluster,
2513 cur_bytes, true);
2514 if (ret < 0) {
2515 goto out_locked;
2518 qemu_co_mutex_unlock(&s->lock);
2520 if (!aio && cur_bytes != bytes) {
2521 aio = aio_task_pool_new(QCOW2_MAX_WORKERS);
2523 ret = qcow2_add_task(bs, aio, qcow2_co_pwritev_task_entry, 0,
2524 cluster_offset, offset, cur_bytes,
2525 qiov, qiov_offset, l2meta);
2526 l2meta = NULL; /* l2meta is consumed by qcow2_co_pwritev_task() */
2527 if (ret < 0) {
2528 goto fail_nometa;
2531 bytes -= cur_bytes;
2532 offset += cur_bytes;
2533 qiov_offset += cur_bytes;
2534 trace_qcow2_writev_done_part(qemu_coroutine_self(), cur_bytes);
2536 ret = 0;
2538 qemu_co_mutex_lock(&s->lock);
2540 out_locked:
2541 qcow2_handle_l2meta(bs, &l2meta, false);
2543 qemu_co_mutex_unlock(&s->lock);
2545 fail_nometa:
2546 if (aio) {
2547 aio_task_pool_wait_all(aio);
2548 if (ret == 0) {
2549 ret = aio_task_pool_status(aio);
2551 g_free(aio);
2554 trace_qcow2_writev_done_req(qemu_coroutine_self(), ret);
2556 return ret;
2559 static int qcow2_inactivate(BlockDriverState *bs)
2561 BDRVQcow2State *s = bs->opaque;
2562 int ret, result = 0;
2563 Error *local_err = NULL;
2565 qcow2_store_persistent_dirty_bitmaps(bs, true, &local_err);
2566 if (local_err != NULL) {
2567 result = -EINVAL;
2568 error_reportf_err(local_err, "Lost persistent bitmaps during "
2569 "inactivation of node '%s': ",
2570 bdrv_get_device_or_node_name(bs));
2573 ret = qcow2_cache_flush(bs, s->l2_table_cache);
2574 if (ret) {
2575 result = ret;
2576 error_report("Failed to flush the L2 table cache: %s",
2577 strerror(-ret));
2580 ret = qcow2_cache_flush(bs, s->refcount_block_cache);
2581 if (ret) {
2582 result = ret;
2583 error_report("Failed to flush the refcount block cache: %s",
2584 strerror(-ret));
2587 if (result == 0) {
2588 qcow2_mark_clean(bs);
2591 return result;
2594 static void qcow2_close(BlockDriverState *bs)
2596 BDRVQcow2State *s = bs->opaque;
2597 qemu_vfree(s->l1_table);
2598 /* else pre-write overlap checks in cache_destroy may crash */
2599 s->l1_table = NULL;
2601 if (!(s->flags & BDRV_O_INACTIVE)) {
2602 qcow2_inactivate(bs);
2605 cache_clean_timer_del(bs);
2606 qcow2_cache_destroy(s->l2_table_cache);
2607 qcow2_cache_destroy(s->refcount_block_cache);
2609 qcrypto_block_free(s->crypto);
2610 s->crypto = NULL;
2612 g_free(s->unknown_header_fields);
2613 cleanup_unknown_header_ext(bs);
2615 g_free(s->image_data_file);
2616 g_free(s->image_backing_file);
2617 g_free(s->image_backing_format);
2619 if (has_data_file(bs)) {
2620 bdrv_unref_child(bs, s->data_file);
2623 qcow2_refcount_close(bs);
2624 qcow2_free_snapshots(bs);
2627 static void coroutine_fn qcow2_co_invalidate_cache(BlockDriverState *bs,
2628 Error **errp)
2630 BDRVQcow2State *s = bs->opaque;
2631 int flags = s->flags;
2632 QCryptoBlock *crypto = NULL;
2633 QDict *options;
2634 Error *local_err = NULL;
2635 int ret;
2638 * Backing files are read-only which makes all of their metadata immutable,
2639 * that means we don't have to worry about reopening them here.
2642 crypto = s->crypto;
2643 s->crypto = NULL;
2645 qcow2_close(bs);
2647 memset(s, 0, sizeof(BDRVQcow2State));
2648 options = qdict_clone_shallow(bs->options);
2650 flags &= ~BDRV_O_INACTIVE;
2651 qemu_co_mutex_lock(&s->lock);
2652 ret = qcow2_do_open(bs, options, flags, &local_err);
2653 qemu_co_mutex_unlock(&s->lock);
2654 qobject_unref(options);
2655 if (local_err) {
2656 error_propagate_prepend(errp, local_err,
2657 "Could not reopen qcow2 layer: ");
2658 bs->drv = NULL;
2659 return;
2660 } else if (ret < 0) {
2661 error_setg_errno(errp, -ret, "Could not reopen qcow2 layer");
2662 bs->drv = NULL;
2663 return;
2666 s->crypto = crypto;
2669 static size_t header_ext_add(char *buf, uint32_t magic, const void *s,
2670 size_t len, size_t buflen)
2672 QCowExtension *ext_backing_fmt = (QCowExtension*) buf;
2673 size_t ext_len = sizeof(QCowExtension) + ((len + 7) & ~7);
2675 if (buflen < ext_len) {
2676 return -ENOSPC;
2679 *ext_backing_fmt = (QCowExtension) {
2680 .magic = cpu_to_be32(magic),
2681 .len = cpu_to_be32(len),
2684 if (len) {
2685 memcpy(buf + sizeof(QCowExtension), s, len);
2688 return ext_len;
2692 * Updates the qcow2 header, including the variable length parts of it, i.e.
2693 * the backing file name and all extensions. qcow2 was not designed to allow
2694 * such changes, so if we run out of space (we can only use the first cluster)
2695 * this function may fail.
2697 * Returns 0 on success, -errno in error cases.
2699 int qcow2_update_header(BlockDriverState *bs)
2701 BDRVQcow2State *s = bs->opaque;
2702 QCowHeader *header;
2703 char *buf;
2704 size_t buflen = s->cluster_size;
2705 int ret;
2706 uint64_t total_size;
2707 uint32_t refcount_table_clusters;
2708 size_t header_length;
2709 Qcow2UnknownHeaderExtension *uext;
2711 buf = qemu_blockalign(bs, buflen);
2713 /* Header structure */
2714 header = (QCowHeader*) buf;
2716 if (buflen < sizeof(*header)) {
2717 ret = -ENOSPC;
2718 goto fail;
2721 header_length = sizeof(*header) + s->unknown_header_fields_size;
2722 total_size = bs->total_sectors * BDRV_SECTOR_SIZE;
2723 refcount_table_clusters = s->refcount_table_size >> (s->cluster_bits - 3);
2725 *header = (QCowHeader) {
2726 /* Version 2 fields */
2727 .magic = cpu_to_be32(QCOW_MAGIC),
2728 .version = cpu_to_be32(s->qcow_version),
2729 .backing_file_offset = 0,
2730 .backing_file_size = 0,
2731 .cluster_bits = cpu_to_be32(s->cluster_bits),
2732 .size = cpu_to_be64(total_size),
2733 .crypt_method = cpu_to_be32(s->crypt_method_header),
2734 .l1_size = cpu_to_be32(s->l1_size),
2735 .l1_table_offset = cpu_to_be64(s->l1_table_offset),
2736 .refcount_table_offset = cpu_to_be64(s->refcount_table_offset),
2737 .refcount_table_clusters = cpu_to_be32(refcount_table_clusters),
2738 .nb_snapshots = cpu_to_be32(s->nb_snapshots),
2739 .snapshots_offset = cpu_to_be64(s->snapshots_offset),
2741 /* Version 3 fields */
2742 .incompatible_features = cpu_to_be64(s->incompatible_features),
2743 .compatible_features = cpu_to_be64(s->compatible_features),
2744 .autoclear_features = cpu_to_be64(s->autoclear_features),
2745 .refcount_order = cpu_to_be32(s->refcount_order),
2746 .header_length = cpu_to_be32(header_length),
2749 /* For older versions, write a shorter header */
2750 switch (s->qcow_version) {
2751 case 2:
2752 ret = offsetof(QCowHeader, incompatible_features);
2753 break;
2754 case 3:
2755 ret = sizeof(*header);
2756 break;
2757 default:
2758 ret = -EINVAL;
2759 goto fail;
2762 buf += ret;
2763 buflen -= ret;
2764 memset(buf, 0, buflen);
2766 /* Preserve any unknown field in the header */
2767 if (s->unknown_header_fields_size) {
2768 if (buflen < s->unknown_header_fields_size) {
2769 ret = -ENOSPC;
2770 goto fail;
2773 memcpy(buf, s->unknown_header_fields, s->unknown_header_fields_size);
2774 buf += s->unknown_header_fields_size;
2775 buflen -= s->unknown_header_fields_size;
2778 /* Backing file format header extension */
2779 if (s->image_backing_format) {
2780 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BACKING_FORMAT,
2781 s->image_backing_format,
2782 strlen(s->image_backing_format),
2783 buflen);
2784 if (ret < 0) {
2785 goto fail;
2788 buf += ret;
2789 buflen -= ret;
2792 /* External data file header extension */
2793 if (has_data_file(bs) && s->image_data_file) {
2794 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_DATA_FILE,
2795 s->image_data_file, strlen(s->image_data_file),
2796 buflen);
2797 if (ret < 0) {
2798 goto fail;
2801 buf += ret;
2802 buflen -= ret;
2805 /* Full disk encryption header pointer extension */
2806 if (s->crypto_header.offset != 0) {
2807 s->crypto_header.offset = cpu_to_be64(s->crypto_header.offset);
2808 s->crypto_header.length = cpu_to_be64(s->crypto_header.length);
2809 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_CRYPTO_HEADER,
2810 &s->crypto_header, sizeof(s->crypto_header),
2811 buflen);
2812 s->crypto_header.offset = be64_to_cpu(s->crypto_header.offset);
2813 s->crypto_header.length = be64_to_cpu(s->crypto_header.length);
2814 if (ret < 0) {
2815 goto fail;
2817 buf += ret;
2818 buflen -= ret;
2821 /* Feature table */
2822 if (s->qcow_version >= 3) {
2823 Qcow2Feature features[] = {
2825 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
2826 .bit = QCOW2_INCOMPAT_DIRTY_BITNR,
2827 .name = "dirty bit",
2830 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
2831 .bit = QCOW2_INCOMPAT_CORRUPT_BITNR,
2832 .name = "corrupt bit",
2835 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
2836 .bit = QCOW2_INCOMPAT_DATA_FILE_BITNR,
2837 .name = "external data file",
2840 .type = QCOW2_FEAT_TYPE_COMPATIBLE,
2841 .bit = QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR,
2842 .name = "lazy refcounts",
2846 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_FEATURE_TABLE,
2847 features, sizeof(features), buflen);
2848 if (ret < 0) {
2849 goto fail;
2851 buf += ret;
2852 buflen -= ret;
2855 /* Bitmap extension */
2856 if (s->nb_bitmaps > 0) {
2857 Qcow2BitmapHeaderExt bitmaps_header = {
2858 .nb_bitmaps = cpu_to_be32(s->nb_bitmaps),
2859 .bitmap_directory_size =
2860 cpu_to_be64(s->bitmap_directory_size),
2861 .bitmap_directory_offset =
2862 cpu_to_be64(s->bitmap_directory_offset)
2864 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BITMAPS,
2865 &bitmaps_header, sizeof(bitmaps_header),
2866 buflen);
2867 if (ret < 0) {
2868 goto fail;
2870 buf += ret;
2871 buflen -= ret;
2874 /* Keep unknown header extensions */
2875 QLIST_FOREACH(uext, &s->unknown_header_ext, next) {
2876 ret = header_ext_add(buf, uext->magic, uext->data, uext->len, buflen);
2877 if (ret < 0) {
2878 goto fail;
2881 buf += ret;
2882 buflen -= ret;
2885 /* End of header extensions */
2886 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_END, NULL, 0, buflen);
2887 if (ret < 0) {
2888 goto fail;
2891 buf += ret;
2892 buflen -= ret;
2894 /* Backing file name */
2895 if (s->image_backing_file) {
2896 size_t backing_file_len = strlen(s->image_backing_file);
2898 if (buflen < backing_file_len) {
2899 ret = -ENOSPC;
2900 goto fail;
2903 /* Using strncpy is ok here, since buf is not NUL-terminated. */
2904 strncpy(buf, s->image_backing_file, buflen);
2906 header->backing_file_offset = cpu_to_be64(buf - ((char*) header));
2907 header->backing_file_size = cpu_to_be32(backing_file_len);
2910 /* Write the new header */
2911 ret = bdrv_pwrite(bs->file, 0, header, s->cluster_size);
2912 if (ret < 0) {
2913 goto fail;
2916 ret = 0;
2917 fail:
2918 qemu_vfree(header);
2919 return ret;
2922 static int qcow2_change_backing_file(BlockDriverState *bs,
2923 const char *backing_file, const char *backing_fmt)
2925 BDRVQcow2State *s = bs->opaque;
2927 /* Adding a backing file means that the external data file alone won't be
2928 * enough to make sense of the content */
2929 if (backing_file && data_file_is_raw(bs)) {
2930 return -EINVAL;
2933 if (backing_file && strlen(backing_file) > 1023) {
2934 return -EINVAL;
2937 pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
2938 backing_file ?: "");
2939 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
2940 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
2942 g_free(s->image_backing_file);
2943 g_free(s->image_backing_format);
2945 s->image_backing_file = backing_file ? g_strdup(bs->backing_file) : NULL;
2946 s->image_backing_format = backing_fmt ? g_strdup(bs->backing_format) : NULL;
2948 return qcow2_update_header(bs);
2951 static int qcow2_crypt_method_from_format(const char *encryptfmt)
2953 if (g_str_equal(encryptfmt, "luks")) {
2954 return QCOW_CRYPT_LUKS;
2955 } else if (g_str_equal(encryptfmt, "aes")) {
2956 return QCOW_CRYPT_AES;
2957 } else {
2958 return -EINVAL;
2962 static int qcow2_set_up_encryption(BlockDriverState *bs,
2963 QCryptoBlockCreateOptions *cryptoopts,
2964 Error **errp)
2966 BDRVQcow2State *s = bs->opaque;
2967 QCryptoBlock *crypto = NULL;
2968 int fmt, ret;
2970 switch (cryptoopts->format) {
2971 case Q_CRYPTO_BLOCK_FORMAT_LUKS:
2972 fmt = QCOW_CRYPT_LUKS;
2973 break;
2974 case Q_CRYPTO_BLOCK_FORMAT_QCOW:
2975 fmt = QCOW_CRYPT_AES;
2976 break;
2977 default:
2978 error_setg(errp, "Crypto format not supported in qcow2");
2979 return -EINVAL;
2982 s->crypt_method_header = fmt;
2984 crypto = qcrypto_block_create(cryptoopts, "encrypt.",
2985 qcow2_crypto_hdr_init_func,
2986 qcow2_crypto_hdr_write_func,
2987 bs, errp);
2988 if (!crypto) {
2989 return -EINVAL;
2992 ret = qcow2_update_header(bs);
2993 if (ret < 0) {
2994 error_setg_errno(errp, -ret, "Could not write encryption header");
2995 goto out;
2998 ret = 0;
2999 out:
3000 qcrypto_block_free(crypto);
3001 return ret;
3005 * Preallocates metadata structures for data clusters between @offset (in the
3006 * guest disk) and @new_length (which is thus generally the new guest disk
3007 * size).
3009 * Returns: 0 on success, -errno on failure.
3011 static int coroutine_fn preallocate_co(BlockDriverState *bs, uint64_t offset,
3012 uint64_t new_length, PreallocMode mode,
3013 Error **errp)
3015 BDRVQcow2State *s = bs->opaque;
3016 uint64_t bytes;
3017 uint64_t host_offset = 0;
3018 int64_t file_length;
3019 unsigned int cur_bytes;
3020 int ret;
3021 QCowL2Meta *meta;
3023 assert(offset <= new_length);
3024 bytes = new_length - offset;
3026 while (bytes) {
3027 cur_bytes = MIN(bytes, QEMU_ALIGN_DOWN(INT_MAX, s->cluster_size));
3028 ret = qcow2_alloc_cluster_offset(bs, offset, &cur_bytes,
3029 &host_offset, &meta);
3030 if (ret < 0) {
3031 error_setg_errno(errp, -ret, "Allocating clusters failed");
3032 return ret;
3035 while (meta) {
3036 QCowL2Meta *next = meta->next;
3038 ret = qcow2_alloc_cluster_link_l2(bs, meta);
3039 if (ret < 0) {
3040 error_setg_errno(errp, -ret, "Mapping clusters failed");
3041 qcow2_free_any_clusters(bs, meta->alloc_offset,
3042 meta->nb_clusters, QCOW2_DISCARD_NEVER);
3043 return ret;
3046 /* There are no dependent requests, but we need to remove our
3047 * request from the list of in-flight requests */
3048 QLIST_REMOVE(meta, next_in_flight);
3050 g_free(meta);
3051 meta = next;
3054 /* TODO Preallocate data if requested */
3056 bytes -= cur_bytes;
3057 offset += cur_bytes;
3061 * It is expected that the image file is large enough to actually contain
3062 * all of the allocated clusters (otherwise we get failing reads after
3063 * EOF). Extend the image to the last allocated sector.
3065 file_length = bdrv_getlength(s->data_file->bs);
3066 if (file_length < 0) {
3067 error_setg_errno(errp, -file_length, "Could not get file size");
3068 return file_length;
3071 if (host_offset + cur_bytes > file_length) {
3072 if (mode == PREALLOC_MODE_METADATA) {
3073 mode = PREALLOC_MODE_OFF;
3075 ret = bdrv_co_truncate(s->data_file, host_offset + cur_bytes, false,
3076 mode, errp);
3077 if (ret < 0) {
3078 return ret;
3082 return 0;
3085 /* qcow2_refcount_metadata_size:
3086 * @clusters: number of clusters to refcount (including data and L1/L2 tables)
3087 * @cluster_size: size of a cluster, in bytes
3088 * @refcount_order: refcount bits power-of-2 exponent
3089 * @generous_increase: allow for the refcount table to be 1.5x as large as it
3090 * needs to be
3092 * Returns: Number of bytes required for refcount blocks and table metadata.
3094 int64_t qcow2_refcount_metadata_size(int64_t clusters, size_t cluster_size,
3095 int refcount_order, bool generous_increase,
3096 uint64_t *refblock_count)
3099 * Every host cluster is reference-counted, including metadata (even
3100 * refcount metadata is recursively included).
3102 * An accurate formula for the size of refcount metadata size is difficult
3103 * to derive. An easier method of calculation is finding the fixed point
3104 * where no further refcount blocks or table clusters are required to
3105 * reference count every cluster.
3107 int64_t blocks_per_table_cluster = cluster_size / sizeof(uint64_t);
3108 int64_t refcounts_per_block = cluster_size * 8 / (1 << refcount_order);
3109 int64_t table = 0; /* number of refcount table clusters */
3110 int64_t blocks = 0; /* number of refcount block clusters */
3111 int64_t last;
3112 int64_t n = 0;
3114 do {
3115 last = n;
3116 blocks = DIV_ROUND_UP(clusters + table + blocks, refcounts_per_block);
3117 table = DIV_ROUND_UP(blocks, blocks_per_table_cluster);
3118 n = clusters + blocks + table;
3120 if (n == last && generous_increase) {
3121 clusters += DIV_ROUND_UP(table, 2);
3122 n = 0; /* force another loop */
3123 generous_increase = false;
3125 } while (n != last);
3127 if (refblock_count) {
3128 *refblock_count = blocks;
3131 return (blocks + table) * cluster_size;
3135 * qcow2_calc_prealloc_size:
3136 * @total_size: virtual disk size in bytes
3137 * @cluster_size: cluster size in bytes
3138 * @refcount_order: refcount bits power-of-2 exponent
3140 * Returns: Total number of bytes required for the fully allocated image
3141 * (including metadata).
3143 static int64_t qcow2_calc_prealloc_size(int64_t total_size,
3144 size_t cluster_size,
3145 int refcount_order)
3147 int64_t meta_size = 0;
3148 uint64_t nl1e, nl2e;
3149 int64_t aligned_total_size = ROUND_UP(total_size, cluster_size);
3151 /* header: 1 cluster */
3152 meta_size += cluster_size;
3154 /* total size of L2 tables */
3155 nl2e = aligned_total_size / cluster_size;
3156 nl2e = ROUND_UP(nl2e, cluster_size / sizeof(uint64_t));
3157 meta_size += nl2e * sizeof(uint64_t);
3159 /* total size of L1 tables */
3160 nl1e = nl2e * sizeof(uint64_t) / cluster_size;
3161 nl1e = ROUND_UP(nl1e, cluster_size / sizeof(uint64_t));
3162 meta_size += nl1e * sizeof(uint64_t);
3164 /* total size of refcount table and blocks */
3165 meta_size += qcow2_refcount_metadata_size(
3166 (meta_size + aligned_total_size) / cluster_size,
3167 cluster_size, refcount_order, false, NULL);
3169 return meta_size + aligned_total_size;
3172 static bool validate_cluster_size(size_t cluster_size, Error **errp)
3174 int cluster_bits = ctz32(cluster_size);
3175 if (cluster_bits < MIN_CLUSTER_BITS || cluster_bits > MAX_CLUSTER_BITS ||
3176 (1 << cluster_bits) != cluster_size)
3178 error_setg(errp, "Cluster size must be a power of two between %d and "
3179 "%dk", 1 << MIN_CLUSTER_BITS, 1 << (MAX_CLUSTER_BITS - 10));
3180 return false;
3182 return true;
3185 static size_t qcow2_opt_get_cluster_size_del(QemuOpts *opts, Error **errp)
3187 size_t cluster_size;
3189 cluster_size = qemu_opt_get_size_del(opts, BLOCK_OPT_CLUSTER_SIZE,
3190 DEFAULT_CLUSTER_SIZE);
3191 if (!validate_cluster_size(cluster_size, errp)) {
3192 return 0;
3194 return cluster_size;
3197 static int qcow2_opt_get_version_del(QemuOpts *opts, Error **errp)
3199 char *buf;
3200 int ret;
3202 buf = qemu_opt_get_del(opts, BLOCK_OPT_COMPAT_LEVEL);
3203 if (!buf) {
3204 ret = 3; /* default */
3205 } else if (!strcmp(buf, "0.10")) {
3206 ret = 2;
3207 } else if (!strcmp(buf, "1.1")) {
3208 ret = 3;
3209 } else {
3210 error_setg(errp, "Invalid compatibility level: '%s'", buf);
3211 ret = -EINVAL;
3213 g_free(buf);
3214 return ret;
3217 static uint64_t qcow2_opt_get_refcount_bits_del(QemuOpts *opts, int version,
3218 Error **errp)
3220 uint64_t refcount_bits;
3222 refcount_bits = qemu_opt_get_number_del(opts, BLOCK_OPT_REFCOUNT_BITS, 16);
3223 if (refcount_bits > 64 || !is_power_of_2(refcount_bits)) {
3224 error_setg(errp, "Refcount width must be a power of two and may not "
3225 "exceed 64 bits");
3226 return 0;
3229 if (version < 3 && refcount_bits != 16) {
3230 error_setg(errp, "Different refcount widths than 16 bits require "
3231 "compatibility level 1.1 or above (use compat=1.1 or "
3232 "greater)");
3233 return 0;
3236 return refcount_bits;
3239 static int coroutine_fn
3240 qcow2_co_create(BlockdevCreateOptions *create_options, Error **errp)
3242 BlockdevCreateOptionsQcow2 *qcow2_opts;
3243 QDict *options;
3246 * Open the image file and write a minimal qcow2 header.
3248 * We keep things simple and start with a zero-sized image. We also
3249 * do without refcount blocks or a L1 table for now. We'll fix the
3250 * inconsistency later.
3252 * We do need a refcount table because growing the refcount table means
3253 * allocating two new refcount blocks - the seconds of which would be at
3254 * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
3255 * size for any qcow2 image.
3257 BlockBackend *blk = NULL;
3258 BlockDriverState *bs = NULL;
3259 BlockDriverState *data_bs = NULL;
3260 QCowHeader *header;
3261 size_t cluster_size;
3262 int version;
3263 int refcount_order;
3264 uint64_t* refcount_table;
3265 Error *local_err = NULL;
3266 int ret;
3268 assert(create_options->driver == BLOCKDEV_DRIVER_QCOW2);
3269 qcow2_opts = &create_options->u.qcow2;
3271 bs = bdrv_open_blockdev_ref(qcow2_opts->file, errp);
3272 if (bs == NULL) {
3273 return -EIO;
3276 /* Validate options and set default values */
3277 if (!QEMU_IS_ALIGNED(qcow2_opts->size, BDRV_SECTOR_SIZE)) {
3278 error_setg(errp, "Image size must be a multiple of 512 bytes");
3279 ret = -EINVAL;
3280 goto out;
3283 if (qcow2_opts->has_version) {
3284 switch (qcow2_opts->version) {
3285 case BLOCKDEV_QCOW2_VERSION_V2:
3286 version = 2;
3287 break;
3288 case BLOCKDEV_QCOW2_VERSION_V3:
3289 version = 3;
3290 break;
3291 default:
3292 g_assert_not_reached();
3294 } else {
3295 version = 3;
3298 if (qcow2_opts->has_cluster_size) {
3299 cluster_size = qcow2_opts->cluster_size;
3300 } else {
3301 cluster_size = DEFAULT_CLUSTER_SIZE;
3304 if (!validate_cluster_size(cluster_size, errp)) {
3305 ret = -EINVAL;
3306 goto out;
3309 if (!qcow2_opts->has_preallocation) {
3310 qcow2_opts->preallocation = PREALLOC_MODE_OFF;
3312 if (qcow2_opts->has_backing_file &&
3313 qcow2_opts->preallocation != PREALLOC_MODE_OFF)
3315 error_setg(errp, "Backing file and preallocation cannot be used at "
3316 "the same time");
3317 ret = -EINVAL;
3318 goto out;
3320 if (qcow2_opts->has_backing_fmt && !qcow2_opts->has_backing_file) {
3321 error_setg(errp, "Backing format cannot be used without backing file");
3322 ret = -EINVAL;
3323 goto out;
3326 if (!qcow2_opts->has_lazy_refcounts) {
3327 qcow2_opts->lazy_refcounts = false;
3329 if (version < 3 && qcow2_opts->lazy_refcounts) {
3330 error_setg(errp, "Lazy refcounts only supported with compatibility "
3331 "level 1.1 and above (use version=v3 or greater)");
3332 ret = -EINVAL;
3333 goto out;
3336 if (!qcow2_opts->has_refcount_bits) {
3337 qcow2_opts->refcount_bits = 16;
3339 if (qcow2_opts->refcount_bits > 64 ||
3340 !is_power_of_2(qcow2_opts->refcount_bits))
3342 error_setg(errp, "Refcount width must be a power of two and may not "
3343 "exceed 64 bits");
3344 ret = -EINVAL;
3345 goto out;
3347 if (version < 3 && qcow2_opts->refcount_bits != 16) {
3348 error_setg(errp, "Different refcount widths than 16 bits require "
3349 "compatibility level 1.1 or above (use version=v3 or "
3350 "greater)");
3351 ret = -EINVAL;
3352 goto out;
3354 refcount_order = ctz32(qcow2_opts->refcount_bits);
3356 if (qcow2_opts->data_file_raw && !qcow2_opts->data_file) {
3357 error_setg(errp, "data-file-raw requires data-file");
3358 ret = -EINVAL;
3359 goto out;
3361 if (qcow2_opts->data_file_raw && qcow2_opts->has_backing_file) {
3362 error_setg(errp, "Backing file and data-file-raw cannot be used at "
3363 "the same time");
3364 ret = -EINVAL;
3365 goto out;
3368 if (qcow2_opts->data_file) {
3369 if (version < 3) {
3370 error_setg(errp, "External data files are only supported with "
3371 "compatibility level 1.1 and above (use version=v3 or "
3372 "greater)");
3373 ret = -EINVAL;
3374 goto out;
3376 data_bs = bdrv_open_blockdev_ref(qcow2_opts->data_file, errp);
3377 if (data_bs == NULL) {
3378 ret = -EIO;
3379 goto out;
3383 /* Create BlockBackend to write to the image */
3384 blk = blk_new(bdrv_get_aio_context(bs),
3385 BLK_PERM_WRITE | BLK_PERM_RESIZE, BLK_PERM_ALL);
3386 ret = blk_insert_bs(blk, bs, errp);
3387 if (ret < 0) {
3388 goto out;
3390 blk_set_allow_write_beyond_eof(blk, true);
3392 /* Write the header */
3393 QEMU_BUILD_BUG_ON((1 << MIN_CLUSTER_BITS) < sizeof(*header));
3394 header = g_malloc0(cluster_size);
3395 *header = (QCowHeader) {
3396 .magic = cpu_to_be32(QCOW_MAGIC),
3397 .version = cpu_to_be32(version),
3398 .cluster_bits = cpu_to_be32(ctz32(cluster_size)),
3399 .size = cpu_to_be64(0),
3400 .l1_table_offset = cpu_to_be64(0),
3401 .l1_size = cpu_to_be32(0),
3402 .refcount_table_offset = cpu_to_be64(cluster_size),
3403 .refcount_table_clusters = cpu_to_be32(1),
3404 .refcount_order = cpu_to_be32(refcount_order),
3405 .header_length = cpu_to_be32(sizeof(*header)),
3408 /* We'll update this to correct value later */
3409 header->crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
3411 if (qcow2_opts->lazy_refcounts) {
3412 header->compatible_features |=
3413 cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS);
3415 if (data_bs) {
3416 header->incompatible_features |=
3417 cpu_to_be64(QCOW2_INCOMPAT_DATA_FILE);
3419 if (qcow2_opts->data_file_raw) {
3420 header->autoclear_features |=
3421 cpu_to_be64(QCOW2_AUTOCLEAR_DATA_FILE_RAW);
3424 ret = blk_pwrite(blk, 0, header, cluster_size, 0);
3425 g_free(header);
3426 if (ret < 0) {
3427 error_setg_errno(errp, -ret, "Could not write qcow2 header");
3428 goto out;
3431 /* Write a refcount table with one refcount block */
3432 refcount_table = g_malloc0(2 * cluster_size);
3433 refcount_table[0] = cpu_to_be64(2 * cluster_size);
3434 ret = blk_pwrite(blk, cluster_size, refcount_table, 2 * cluster_size, 0);
3435 g_free(refcount_table);
3437 if (ret < 0) {
3438 error_setg_errno(errp, -ret, "Could not write refcount table");
3439 goto out;
3442 blk_unref(blk);
3443 blk = NULL;
3446 * And now open the image and make it consistent first (i.e. increase the
3447 * refcount of the cluster that is occupied by the header and the refcount
3448 * table)
3450 options = qdict_new();
3451 qdict_put_str(options, "driver", "qcow2");
3452 qdict_put_str(options, "file", bs->node_name);
3453 if (data_bs) {
3454 qdict_put_str(options, "data-file", data_bs->node_name);
3456 blk = blk_new_open(NULL, NULL, options,
3457 BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_NO_FLUSH,
3458 &local_err);
3459 if (blk == NULL) {
3460 error_propagate(errp, local_err);
3461 ret = -EIO;
3462 goto out;
3465 ret = qcow2_alloc_clusters(blk_bs(blk), 3 * cluster_size);
3466 if (ret < 0) {
3467 error_setg_errno(errp, -ret, "Could not allocate clusters for qcow2 "
3468 "header and refcount table");
3469 goto out;
3471 } else if (ret != 0) {
3472 error_report("Huh, first cluster in empty image is already in use?");
3473 abort();
3476 /* Set the external data file if necessary */
3477 if (data_bs) {
3478 BDRVQcow2State *s = blk_bs(blk)->opaque;
3479 s->image_data_file = g_strdup(data_bs->filename);
3482 /* Create a full header (including things like feature table) */
3483 ret = qcow2_update_header(blk_bs(blk));
3484 if (ret < 0) {
3485 error_setg_errno(errp, -ret, "Could not update qcow2 header");
3486 goto out;
3489 /* Okay, now that we have a valid image, let's give it the right size */
3490 ret = blk_truncate(blk, qcow2_opts->size, false, qcow2_opts->preallocation,
3491 errp);
3492 if (ret < 0) {
3493 error_prepend(errp, "Could not resize image: ");
3494 goto out;
3497 /* Want a backing file? There you go.*/
3498 if (qcow2_opts->has_backing_file) {
3499 const char *backing_format = NULL;
3501 if (qcow2_opts->has_backing_fmt) {
3502 backing_format = BlockdevDriver_str(qcow2_opts->backing_fmt);
3505 ret = bdrv_change_backing_file(blk_bs(blk), qcow2_opts->backing_file,
3506 backing_format);
3507 if (ret < 0) {
3508 error_setg_errno(errp, -ret, "Could not assign backing file '%s' "
3509 "with format '%s'", qcow2_opts->backing_file,
3510 backing_format);
3511 goto out;
3515 /* Want encryption? There you go. */
3516 if (qcow2_opts->has_encrypt) {
3517 ret = qcow2_set_up_encryption(blk_bs(blk), qcow2_opts->encrypt, errp);
3518 if (ret < 0) {
3519 goto out;
3523 blk_unref(blk);
3524 blk = NULL;
3526 /* Reopen the image without BDRV_O_NO_FLUSH to flush it before returning.
3527 * Using BDRV_O_NO_IO, since encryption is now setup we don't want to
3528 * have to setup decryption context. We're not doing any I/O on the top
3529 * level BlockDriverState, only lower layers, where BDRV_O_NO_IO does
3530 * not have effect.
3532 options = qdict_new();
3533 qdict_put_str(options, "driver", "qcow2");
3534 qdict_put_str(options, "file", bs->node_name);
3535 if (data_bs) {
3536 qdict_put_str(options, "data-file", data_bs->node_name);
3538 blk = blk_new_open(NULL, NULL, options,
3539 BDRV_O_RDWR | BDRV_O_NO_BACKING | BDRV_O_NO_IO,
3540 &local_err);
3541 if (blk == NULL) {
3542 error_propagate(errp, local_err);
3543 ret = -EIO;
3544 goto out;
3547 ret = 0;
3548 out:
3549 blk_unref(blk);
3550 bdrv_unref(bs);
3551 bdrv_unref(data_bs);
3552 return ret;
3555 static int coroutine_fn qcow2_co_create_opts(const char *filename, QemuOpts *opts,
3556 Error **errp)
3558 BlockdevCreateOptions *create_options = NULL;
3559 QDict *qdict;
3560 Visitor *v;
3561 BlockDriverState *bs = NULL;
3562 BlockDriverState *data_bs = NULL;
3563 Error *local_err = NULL;
3564 const char *val;
3565 int ret;
3567 /* Only the keyval visitor supports the dotted syntax needed for
3568 * encryption, so go through a QDict before getting a QAPI type. Ignore
3569 * options meant for the protocol layer so that the visitor doesn't
3570 * complain. */
3571 qdict = qemu_opts_to_qdict_filtered(opts, NULL, bdrv_qcow2.create_opts,
3572 true);
3574 /* Handle encryption options */
3575 val = qdict_get_try_str(qdict, BLOCK_OPT_ENCRYPT);
3576 if (val && !strcmp(val, "on")) {
3577 qdict_put_str(qdict, BLOCK_OPT_ENCRYPT, "qcow");
3578 } else if (val && !strcmp(val, "off")) {
3579 qdict_del(qdict, BLOCK_OPT_ENCRYPT);
3582 val = qdict_get_try_str(qdict, BLOCK_OPT_ENCRYPT_FORMAT);
3583 if (val && !strcmp(val, "aes")) {
3584 qdict_put_str(qdict, BLOCK_OPT_ENCRYPT_FORMAT, "qcow");
3587 /* Convert compat=0.10/1.1 into compat=v2/v3, to be renamed into
3588 * version=v2/v3 below. */
3589 val = qdict_get_try_str(qdict, BLOCK_OPT_COMPAT_LEVEL);
3590 if (val && !strcmp(val, "0.10")) {
3591 qdict_put_str(qdict, BLOCK_OPT_COMPAT_LEVEL, "v2");
3592 } else if (val && !strcmp(val, "1.1")) {
3593 qdict_put_str(qdict, BLOCK_OPT_COMPAT_LEVEL, "v3");
3596 /* Change legacy command line options into QMP ones */
3597 static const QDictRenames opt_renames[] = {
3598 { BLOCK_OPT_BACKING_FILE, "backing-file" },
3599 { BLOCK_OPT_BACKING_FMT, "backing-fmt" },
3600 { BLOCK_OPT_CLUSTER_SIZE, "cluster-size" },
3601 { BLOCK_OPT_LAZY_REFCOUNTS, "lazy-refcounts" },
3602 { BLOCK_OPT_REFCOUNT_BITS, "refcount-bits" },
3603 { BLOCK_OPT_ENCRYPT, BLOCK_OPT_ENCRYPT_FORMAT },
3604 { BLOCK_OPT_COMPAT_LEVEL, "version" },
3605 { BLOCK_OPT_DATA_FILE_RAW, "data-file-raw" },
3606 { NULL, NULL },
3609 if (!qdict_rename_keys(qdict, opt_renames, errp)) {
3610 ret = -EINVAL;
3611 goto finish;
3614 /* Create and open the file (protocol layer) */
3615 ret = bdrv_create_file(filename, opts, errp);
3616 if (ret < 0) {
3617 goto finish;
3620 bs = bdrv_open(filename, NULL, NULL,
3621 BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_PROTOCOL, errp);
3622 if (bs == NULL) {
3623 ret = -EIO;
3624 goto finish;
3627 /* Create and open an external data file (protocol layer) */
3628 val = qdict_get_try_str(qdict, BLOCK_OPT_DATA_FILE);
3629 if (val) {
3630 ret = bdrv_create_file(val, opts, errp);
3631 if (ret < 0) {
3632 goto finish;
3635 data_bs = bdrv_open(val, NULL, NULL,
3636 BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_PROTOCOL,
3637 errp);
3638 if (data_bs == NULL) {
3639 ret = -EIO;
3640 goto finish;
3643 qdict_del(qdict, BLOCK_OPT_DATA_FILE);
3644 qdict_put_str(qdict, "data-file", data_bs->node_name);
3647 /* Set 'driver' and 'node' options */
3648 qdict_put_str(qdict, "driver", "qcow2");
3649 qdict_put_str(qdict, "file", bs->node_name);
3651 /* Now get the QAPI type BlockdevCreateOptions */
3652 v = qobject_input_visitor_new_flat_confused(qdict, errp);
3653 if (!v) {
3654 ret = -EINVAL;
3655 goto finish;
3658 visit_type_BlockdevCreateOptions(v, NULL, &create_options, &local_err);
3659 visit_free(v);
3661 if (local_err) {
3662 error_propagate(errp, local_err);
3663 ret = -EINVAL;
3664 goto finish;
3667 /* Silently round up size */
3668 create_options->u.qcow2.size = ROUND_UP(create_options->u.qcow2.size,
3669 BDRV_SECTOR_SIZE);
3671 /* Create the qcow2 image (format layer) */
3672 ret = qcow2_co_create(create_options, errp);
3673 if (ret < 0) {
3674 goto finish;
3677 ret = 0;
3678 finish:
3679 qobject_unref(qdict);
3680 bdrv_unref(bs);
3681 bdrv_unref(data_bs);
3682 qapi_free_BlockdevCreateOptions(create_options);
3683 return ret;
3687 static bool is_zero(BlockDriverState *bs, int64_t offset, int64_t bytes)
3689 int64_t nr;
3690 int res;
3692 /* Clamp to image length, before checking status of underlying sectors */
3693 if (offset + bytes > bs->total_sectors * BDRV_SECTOR_SIZE) {
3694 bytes = bs->total_sectors * BDRV_SECTOR_SIZE - offset;
3697 if (!bytes) {
3698 return true;
3700 res = bdrv_block_status_above(bs, NULL, offset, bytes, &nr, NULL, NULL);
3701 return res >= 0 && (res & BDRV_BLOCK_ZERO) && nr == bytes;
3704 static coroutine_fn int qcow2_co_pwrite_zeroes(BlockDriverState *bs,
3705 int64_t offset, int bytes, BdrvRequestFlags flags)
3707 int ret;
3708 BDRVQcow2State *s = bs->opaque;
3710 uint32_t head = offset % s->cluster_size;
3711 uint32_t tail = (offset + bytes) % s->cluster_size;
3713 trace_qcow2_pwrite_zeroes_start_req(qemu_coroutine_self(), offset, bytes);
3714 if (offset + bytes == bs->total_sectors * BDRV_SECTOR_SIZE) {
3715 tail = 0;
3718 if (head || tail) {
3719 uint64_t off;
3720 unsigned int nr;
3722 assert(head + bytes <= s->cluster_size);
3724 /* check whether remainder of cluster already reads as zero */
3725 if (!(is_zero(bs, offset - head, head) &&
3726 is_zero(bs, offset + bytes,
3727 tail ? s->cluster_size - tail : 0))) {
3728 return -ENOTSUP;
3731 qemu_co_mutex_lock(&s->lock);
3732 /* We can have new write after previous check */
3733 offset = QEMU_ALIGN_DOWN(offset, s->cluster_size);
3734 bytes = s->cluster_size;
3735 nr = s->cluster_size;
3736 ret = qcow2_get_cluster_offset(bs, offset, &nr, &off);
3737 if (ret != QCOW2_CLUSTER_UNALLOCATED &&
3738 ret != QCOW2_CLUSTER_ZERO_PLAIN &&
3739 ret != QCOW2_CLUSTER_ZERO_ALLOC) {
3740 qemu_co_mutex_unlock(&s->lock);
3741 return -ENOTSUP;
3743 } else {
3744 qemu_co_mutex_lock(&s->lock);
3747 trace_qcow2_pwrite_zeroes(qemu_coroutine_self(), offset, bytes);
3749 /* Whatever is left can use real zero clusters */
3750 ret = qcow2_cluster_zeroize(bs, offset, bytes, flags);
3751 qemu_co_mutex_unlock(&s->lock);
3753 return ret;
3756 static coroutine_fn int qcow2_co_pdiscard(BlockDriverState *bs,
3757 int64_t offset, int bytes)
3759 int ret;
3760 BDRVQcow2State *s = bs->opaque;
3762 if (!QEMU_IS_ALIGNED(offset | bytes, s->cluster_size)) {
3763 assert(bytes < s->cluster_size);
3764 /* Ignore partial clusters, except for the special case of the
3765 * complete partial cluster at the end of an unaligned file */
3766 if (!QEMU_IS_ALIGNED(offset, s->cluster_size) ||
3767 offset + bytes != bs->total_sectors * BDRV_SECTOR_SIZE) {
3768 return -ENOTSUP;
3772 qemu_co_mutex_lock(&s->lock);
3773 ret = qcow2_cluster_discard(bs, offset, bytes, QCOW2_DISCARD_REQUEST,
3774 false);
3775 qemu_co_mutex_unlock(&s->lock);
3776 return ret;
3779 static int coroutine_fn
3780 qcow2_co_copy_range_from(BlockDriverState *bs,
3781 BdrvChild *src, uint64_t src_offset,
3782 BdrvChild *dst, uint64_t dst_offset,
3783 uint64_t bytes, BdrvRequestFlags read_flags,
3784 BdrvRequestFlags write_flags)
3786 BDRVQcow2State *s = bs->opaque;
3787 int ret;
3788 unsigned int cur_bytes; /* number of bytes in current iteration */
3789 BdrvChild *child = NULL;
3790 BdrvRequestFlags cur_write_flags;
3792 assert(!bs->encrypted);
3793 qemu_co_mutex_lock(&s->lock);
3795 while (bytes != 0) {
3796 uint64_t copy_offset = 0;
3797 /* prepare next request */
3798 cur_bytes = MIN(bytes, INT_MAX);
3799 cur_write_flags = write_flags;
3801 ret = qcow2_get_cluster_offset(bs, src_offset, &cur_bytes, &copy_offset);
3802 if (ret < 0) {
3803 goto out;
3806 switch (ret) {
3807 case QCOW2_CLUSTER_UNALLOCATED:
3808 if (bs->backing && bs->backing->bs) {
3809 int64_t backing_length = bdrv_getlength(bs->backing->bs);
3810 if (src_offset >= backing_length) {
3811 cur_write_flags |= BDRV_REQ_ZERO_WRITE;
3812 } else {
3813 child = bs->backing;
3814 cur_bytes = MIN(cur_bytes, backing_length - src_offset);
3815 copy_offset = src_offset;
3817 } else {
3818 cur_write_flags |= BDRV_REQ_ZERO_WRITE;
3820 break;
3822 case QCOW2_CLUSTER_ZERO_PLAIN:
3823 case QCOW2_CLUSTER_ZERO_ALLOC:
3824 cur_write_flags |= BDRV_REQ_ZERO_WRITE;
3825 break;
3827 case QCOW2_CLUSTER_COMPRESSED:
3828 ret = -ENOTSUP;
3829 goto out;
3831 case QCOW2_CLUSTER_NORMAL:
3832 child = s->data_file;
3833 copy_offset += offset_into_cluster(s, src_offset);
3834 if ((copy_offset & 511) != 0) {
3835 ret = -EIO;
3836 goto out;
3838 break;
3840 default:
3841 abort();
3843 qemu_co_mutex_unlock(&s->lock);
3844 ret = bdrv_co_copy_range_from(child,
3845 copy_offset,
3846 dst, dst_offset,
3847 cur_bytes, read_flags, cur_write_flags);
3848 qemu_co_mutex_lock(&s->lock);
3849 if (ret < 0) {
3850 goto out;
3853 bytes -= cur_bytes;
3854 src_offset += cur_bytes;
3855 dst_offset += cur_bytes;
3857 ret = 0;
3859 out:
3860 qemu_co_mutex_unlock(&s->lock);
3861 return ret;
3864 static int coroutine_fn
3865 qcow2_co_copy_range_to(BlockDriverState *bs,
3866 BdrvChild *src, uint64_t src_offset,
3867 BdrvChild *dst, uint64_t dst_offset,
3868 uint64_t bytes, BdrvRequestFlags read_flags,
3869 BdrvRequestFlags write_flags)
3871 BDRVQcow2State *s = bs->opaque;
3872 int offset_in_cluster;
3873 int ret;
3874 unsigned int cur_bytes; /* number of sectors in current iteration */
3875 uint64_t cluster_offset;
3876 QCowL2Meta *l2meta = NULL;
3878 assert(!bs->encrypted);
3880 qemu_co_mutex_lock(&s->lock);
3882 while (bytes != 0) {
3884 l2meta = NULL;
3886 offset_in_cluster = offset_into_cluster(s, dst_offset);
3887 cur_bytes = MIN(bytes, INT_MAX);
3889 /* TODO:
3890 * If src->bs == dst->bs, we could simply copy by incrementing
3891 * the refcnt, without copying user data.
3892 * Or if src->bs == dst->bs->backing->bs, we could copy by discarding. */
3893 ret = qcow2_alloc_cluster_offset(bs, dst_offset, &cur_bytes,
3894 &cluster_offset, &l2meta);
3895 if (ret < 0) {
3896 goto fail;
3899 assert((cluster_offset & 511) == 0);
3901 ret = qcow2_pre_write_overlap_check(bs, 0,
3902 cluster_offset + offset_in_cluster, cur_bytes, true);
3903 if (ret < 0) {
3904 goto fail;
3907 qemu_co_mutex_unlock(&s->lock);
3908 ret = bdrv_co_copy_range_to(src, src_offset,
3909 s->data_file,
3910 cluster_offset + offset_in_cluster,
3911 cur_bytes, read_flags, write_flags);
3912 qemu_co_mutex_lock(&s->lock);
3913 if (ret < 0) {
3914 goto fail;
3917 ret = qcow2_handle_l2meta(bs, &l2meta, true);
3918 if (ret) {
3919 goto fail;
3922 bytes -= cur_bytes;
3923 src_offset += cur_bytes;
3924 dst_offset += cur_bytes;
3926 ret = 0;
3928 fail:
3929 qcow2_handle_l2meta(bs, &l2meta, false);
3931 qemu_co_mutex_unlock(&s->lock);
3933 trace_qcow2_writev_done_req(qemu_coroutine_self(), ret);
3935 return ret;
3938 static int coroutine_fn qcow2_co_truncate(BlockDriverState *bs, int64_t offset,
3939 bool exact, PreallocMode prealloc,
3940 Error **errp)
3942 BDRVQcow2State *s = bs->opaque;
3943 uint64_t old_length;
3944 int64_t new_l1_size;
3945 int ret;
3946 QDict *options;
3948 if (prealloc != PREALLOC_MODE_OFF && prealloc != PREALLOC_MODE_METADATA &&
3949 prealloc != PREALLOC_MODE_FALLOC && prealloc != PREALLOC_MODE_FULL)
3951 error_setg(errp, "Unsupported preallocation mode '%s'",
3952 PreallocMode_str(prealloc));
3953 return -ENOTSUP;
3956 if (offset & 511) {
3957 error_setg(errp, "The new size must be a multiple of 512");
3958 return -EINVAL;
3961 qemu_co_mutex_lock(&s->lock);
3963 /* cannot proceed if image has snapshots */
3964 if (s->nb_snapshots) {
3965 error_setg(errp, "Can't resize an image which has snapshots");
3966 ret = -ENOTSUP;
3967 goto fail;
3970 /* cannot proceed if image has bitmaps */
3971 if (qcow2_truncate_bitmaps_check(bs, errp)) {
3972 ret = -ENOTSUP;
3973 goto fail;
3976 old_length = bs->total_sectors * BDRV_SECTOR_SIZE;
3977 new_l1_size = size_to_l1(s, offset);
3979 if (offset < old_length) {
3980 int64_t last_cluster, old_file_size;
3981 if (prealloc != PREALLOC_MODE_OFF) {
3982 error_setg(errp,
3983 "Preallocation can't be used for shrinking an image");
3984 ret = -EINVAL;
3985 goto fail;
3988 ret = qcow2_cluster_discard(bs, ROUND_UP(offset, s->cluster_size),
3989 old_length - ROUND_UP(offset,
3990 s->cluster_size),
3991 QCOW2_DISCARD_ALWAYS, true);
3992 if (ret < 0) {
3993 error_setg_errno(errp, -ret, "Failed to discard cropped clusters");
3994 goto fail;
3997 ret = qcow2_shrink_l1_table(bs, new_l1_size);
3998 if (ret < 0) {
3999 error_setg_errno(errp, -ret,
4000 "Failed to reduce the number of L2 tables");
4001 goto fail;
4004 ret = qcow2_shrink_reftable(bs);
4005 if (ret < 0) {
4006 error_setg_errno(errp, -ret,
4007 "Failed to discard unused refblocks");
4008 goto fail;
4011 old_file_size = bdrv_getlength(bs->file->bs);
4012 if (old_file_size < 0) {
4013 error_setg_errno(errp, -old_file_size,
4014 "Failed to inquire current file length");
4015 ret = old_file_size;
4016 goto fail;
4018 last_cluster = qcow2_get_last_cluster(bs, old_file_size);
4019 if (last_cluster < 0) {
4020 error_setg_errno(errp, -last_cluster,
4021 "Failed to find the last cluster");
4022 ret = last_cluster;
4023 goto fail;
4025 if ((last_cluster + 1) * s->cluster_size < old_file_size) {
4026 Error *local_err = NULL;
4029 * Do not pass @exact here: It will not help the user if
4030 * we get an error here just because they wanted to shrink
4031 * their qcow2 image (on a block device) with qemu-img.
4032 * (And on the qcow2 layer, the @exact requirement is
4033 * always fulfilled, so there is no need to pass it on.)
4035 bdrv_co_truncate(bs->file, (last_cluster + 1) * s->cluster_size,
4036 false, PREALLOC_MODE_OFF, &local_err);
4037 if (local_err) {
4038 warn_reportf_err(local_err,
4039 "Failed to truncate the tail of the image: ");
4042 } else {
4043 ret = qcow2_grow_l1_table(bs, new_l1_size, true);
4044 if (ret < 0) {
4045 error_setg_errno(errp, -ret, "Failed to grow the L1 table");
4046 goto fail;
4050 switch (prealloc) {
4051 case PREALLOC_MODE_OFF:
4052 if (has_data_file(bs)) {
4054 * If the caller wants an exact resize, the external data
4055 * file should be resized to the exact target size, too,
4056 * so we pass @exact here.
4058 ret = bdrv_co_truncate(s->data_file, offset, exact, prealloc, errp);
4059 if (ret < 0) {
4060 goto fail;
4063 break;
4065 case PREALLOC_MODE_METADATA:
4066 ret = preallocate_co(bs, old_length, offset, prealloc, errp);
4067 if (ret < 0) {
4068 goto fail;
4070 break;
4072 case PREALLOC_MODE_FALLOC:
4073 case PREALLOC_MODE_FULL:
4075 int64_t allocation_start, host_offset, guest_offset;
4076 int64_t clusters_allocated;
4077 int64_t old_file_size, new_file_size;
4078 uint64_t nb_new_data_clusters, nb_new_l2_tables;
4080 /* With a data file, preallocation means just allocating the metadata
4081 * and forwarding the truncate request to the data file */
4082 if (has_data_file(bs)) {
4083 ret = preallocate_co(bs, old_length, offset, prealloc, errp);
4084 if (ret < 0) {
4085 goto fail;
4087 break;
4090 old_file_size = bdrv_getlength(bs->file->bs);
4091 if (old_file_size < 0) {
4092 error_setg_errno(errp, -old_file_size,
4093 "Failed to inquire current file length");
4094 ret = old_file_size;
4095 goto fail;
4097 old_file_size = ROUND_UP(old_file_size, s->cluster_size);
4099 nb_new_data_clusters = DIV_ROUND_UP(offset - old_length,
4100 s->cluster_size);
4102 /* This is an overestimation; we will not actually allocate space for
4103 * these in the file but just make sure the new refcount structures are
4104 * able to cover them so we will not have to allocate new refblocks
4105 * while entering the data blocks in the potentially new L2 tables.
4106 * (We do not actually care where the L2 tables are placed. Maybe they
4107 * are already allocated or they can be placed somewhere before
4108 * @old_file_size. It does not matter because they will be fully
4109 * allocated automatically, so they do not need to be covered by the
4110 * preallocation. All that matters is that we will not have to allocate
4111 * new refcount structures for them.) */
4112 nb_new_l2_tables = DIV_ROUND_UP(nb_new_data_clusters,
4113 s->cluster_size / sizeof(uint64_t));
4114 /* The cluster range may not be aligned to L2 boundaries, so add one L2
4115 * table for a potential head/tail */
4116 nb_new_l2_tables++;
4118 allocation_start = qcow2_refcount_area(bs, old_file_size,
4119 nb_new_data_clusters +
4120 nb_new_l2_tables,
4121 true, 0, 0);
4122 if (allocation_start < 0) {
4123 error_setg_errno(errp, -allocation_start,
4124 "Failed to resize refcount structures");
4125 ret = allocation_start;
4126 goto fail;
4129 clusters_allocated = qcow2_alloc_clusters_at(bs, allocation_start,
4130 nb_new_data_clusters);
4131 if (clusters_allocated < 0) {
4132 error_setg_errno(errp, -clusters_allocated,
4133 "Failed to allocate data clusters");
4134 ret = clusters_allocated;
4135 goto fail;
4138 assert(clusters_allocated == nb_new_data_clusters);
4140 /* Allocate the data area */
4141 new_file_size = allocation_start +
4142 nb_new_data_clusters * s->cluster_size;
4143 /* Image file grows, so @exact does not matter */
4144 ret = bdrv_co_truncate(bs->file, new_file_size, false, prealloc, errp);
4145 if (ret < 0) {
4146 error_prepend(errp, "Failed to resize underlying file: ");
4147 qcow2_free_clusters(bs, allocation_start,
4148 nb_new_data_clusters * s->cluster_size,
4149 QCOW2_DISCARD_OTHER);
4150 goto fail;
4153 /* Create the necessary L2 entries */
4154 host_offset = allocation_start;
4155 guest_offset = old_length;
4156 while (nb_new_data_clusters) {
4157 int64_t nb_clusters = MIN(
4158 nb_new_data_clusters,
4159 s->l2_slice_size - offset_to_l2_slice_index(s, guest_offset));
4160 QCowL2Meta allocation = {
4161 .offset = guest_offset,
4162 .alloc_offset = host_offset,
4163 .nb_clusters = nb_clusters,
4165 qemu_co_queue_init(&allocation.dependent_requests);
4167 ret = qcow2_alloc_cluster_link_l2(bs, &allocation);
4168 if (ret < 0) {
4169 error_setg_errno(errp, -ret, "Failed to update L2 tables");
4170 qcow2_free_clusters(bs, host_offset,
4171 nb_new_data_clusters * s->cluster_size,
4172 QCOW2_DISCARD_OTHER);
4173 goto fail;
4176 guest_offset += nb_clusters * s->cluster_size;
4177 host_offset += nb_clusters * s->cluster_size;
4178 nb_new_data_clusters -= nb_clusters;
4180 break;
4183 default:
4184 g_assert_not_reached();
4187 if (prealloc != PREALLOC_MODE_OFF) {
4188 /* Flush metadata before actually changing the image size */
4189 ret = qcow2_write_caches(bs);
4190 if (ret < 0) {
4191 error_setg_errno(errp, -ret,
4192 "Failed to flush the preallocated area to disk");
4193 goto fail;
4197 bs->total_sectors = offset / BDRV_SECTOR_SIZE;
4199 /* write updated header.size */
4200 offset = cpu_to_be64(offset);
4201 ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, size),
4202 &offset, sizeof(uint64_t));
4203 if (ret < 0) {
4204 error_setg_errno(errp, -ret, "Failed to update the image size");
4205 goto fail;
4208 s->l1_vm_state_index = new_l1_size;
4210 /* Update cache sizes */
4211 options = qdict_clone_shallow(bs->options);
4212 ret = qcow2_update_options(bs, options, s->flags, errp);
4213 qobject_unref(options);
4214 if (ret < 0) {
4215 goto fail;
4217 ret = 0;
4218 fail:
4219 qemu_co_mutex_unlock(&s->lock);
4220 return ret;
4223 static coroutine_fn int
4224 qcow2_co_pwritev_compressed_task(BlockDriverState *bs,
4225 uint64_t offset, uint64_t bytes,
4226 QEMUIOVector *qiov, size_t qiov_offset)
4228 BDRVQcow2State *s = bs->opaque;
4229 int ret;
4230 ssize_t out_len;
4231 uint8_t *buf, *out_buf;
4232 uint64_t cluster_offset;
4234 assert(bytes == s->cluster_size || (bytes < s->cluster_size &&
4235 (offset + bytes == bs->total_sectors << BDRV_SECTOR_BITS)));
4237 buf = qemu_blockalign(bs, s->cluster_size);
4238 if (bytes < s->cluster_size) {
4239 /* Zero-pad last write if image size is not cluster aligned */
4240 memset(buf + bytes, 0, s->cluster_size - bytes);
4242 qemu_iovec_to_buf(qiov, qiov_offset, buf, bytes);
4244 out_buf = g_malloc(s->cluster_size);
4246 out_len = qcow2_co_compress(bs, out_buf, s->cluster_size - 1,
4247 buf, s->cluster_size);
4248 if (out_len == -ENOMEM) {
4249 /* could not compress: write normal cluster */
4250 ret = qcow2_co_pwritev_part(bs, offset, bytes, qiov, qiov_offset, 0);
4251 if (ret < 0) {
4252 goto fail;
4254 goto success;
4255 } else if (out_len < 0) {
4256 ret = -EINVAL;
4257 goto fail;
4260 qemu_co_mutex_lock(&s->lock);
4261 ret = qcow2_alloc_compressed_cluster_offset(bs, offset, out_len,
4262 &cluster_offset);
4263 if (ret < 0) {
4264 qemu_co_mutex_unlock(&s->lock);
4265 goto fail;
4268 ret = qcow2_pre_write_overlap_check(bs, 0, cluster_offset, out_len, true);
4269 qemu_co_mutex_unlock(&s->lock);
4270 if (ret < 0) {
4271 goto fail;
4274 BLKDBG_EVENT(s->data_file, BLKDBG_WRITE_COMPRESSED);
4275 ret = bdrv_co_pwrite(s->data_file, cluster_offset, out_len, out_buf, 0);
4276 if (ret < 0) {
4277 goto fail;
4279 success:
4280 ret = 0;
4281 fail:
4282 qemu_vfree(buf);
4283 g_free(out_buf);
4284 return ret;
4287 static coroutine_fn int qcow2_co_pwritev_compressed_task_entry(AioTask *task)
4289 Qcow2AioTask *t = container_of(task, Qcow2AioTask, task);
4291 assert(!t->cluster_type && !t->l2meta);
4293 return qcow2_co_pwritev_compressed_task(t->bs, t->offset, t->bytes, t->qiov,
4294 t->qiov_offset);
4298 * XXX: put compressed sectors first, then all the cluster aligned
4299 * tables to avoid losing bytes in alignment
4301 static coroutine_fn int
4302 qcow2_co_pwritev_compressed_part(BlockDriverState *bs,
4303 uint64_t offset, uint64_t bytes,
4304 QEMUIOVector *qiov, size_t qiov_offset)
4306 BDRVQcow2State *s = bs->opaque;
4307 AioTaskPool *aio = NULL;
4308 int ret = 0;
4310 if (has_data_file(bs)) {
4311 return -ENOTSUP;
4314 if (bytes == 0) {
4316 * align end of file to a sector boundary to ease reading with
4317 * sector based I/Os
4319 int64_t len = bdrv_getlength(bs->file->bs);
4320 if (len < 0) {
4321 return len;
4323 return bdrv_co_truncate(bs->file, len, false, PREALLOC_MODE_OFF, NULL);
4326 if (offset_into_cluster(s, offset)) {
4327 return -EINVAL;
4330 while (bytes && aio_task_pool_status(aio) == 0) {
4331 uint64_t chunk_size = MIN(bytes, s->cluster_size);
4333 if (!aio && chunk_size != bytes) {
4334 aio = aio_task_pool_new(QCOW2_MAX_WORKERS);
4337 ret = qcow2_add_task(bs, aio, qcow2_co_pwritev_compressed_task_entry,
4338 0, 0, offset, chunk_size, qiov, qiov_offset, NULL);
4339 if (ret < 0) {
4340 break;
4342 qiov_offset += chunk_size;
4343 offset += chunk_size;
4344 bytes -= chunk_size;
4347 if (aio) {
4348 aio_task_pool_wait_all(aio);
4349 if (ret == 0) {
4350 ret = aio_task_pool_status(aio);
4352 g_free(aio);
4355 return ret;
4358 static int coroutine_fn
4359 qcow2_co_preadv_compressed(BlockDriverState *bs,
4360 uint64_t file_cluster_offset,
4361 uint64_t offset,
4362 uint64_t bytes,
4363 QEMUIOVector *qiov,
4364 size_t qiov_offset)
4366 BDRVQcow2State *s = bs->opaque;
4367 int ret = 0, csize, nb_csectors;
4368 uint64_t coffset;
4369 uint8_t *buf, *out_buf;
4370 int offset_in_cluster = offset_into_cluster(s, offset);
4372 coffset = file_cluster_offset & s->cluster_offset_mask;
4373 nb_csectors = ((file_cluster_offset >> s->csize_shift) & s->csize_mask) + 1;
4374 csize = nb_csectors * QCOW2_COMPRESSED_SECTOR_SIZE -
4375 (coffset & ~QCOW2_COMPRESSED_SECTOR_MASK);
4377 buf = g_try_malloc(csize);
4378 if (!buf) {
4379 return -ENOMEM;
4382 out_buf = qemu_blockalign(bs, s->cluster_size);
4384 BLKDBG_EVENT(bs->file, BLKDBG_READ_COMPRESSED);
4385 ret = bdrv_co_pread(bs->file, coffset, csize, buf, 0);
4386 if (ret < 0) {
4387 goto fail;
4390 if (qcow2_co_decompress(bs, out_buf, s->cluster_size, buf, csize) < 0) {
4391 ret = -EIO;
4392 goto fail;
4395 qemu_iovec_from_buf(qiov, qiov_offset, out_buf + offset_in_cluster, bytes);
4397 fail:
4398 qemu_vfree(out_buf);
4399 g_free(buf);
4401 return ret;
4404 static int make_completely_empty(BlockDriverState *bs)
4406 BDRVQcow2State *s = bs->opaque;
4407 Error *local_err = NULL;
4408 int ret, l1_clusters;
4409 int64_t offset;
4410 uint64_t *new_reftable = NULL;
4411 uint64_t rt_entry, l1_size2;
4412 struct {
4413 uint64_t l1_offset;
4414 uint64_t reftable_offset;
4415 uint32_t reftable_clusters;
4416 } QEMU_PACKED l1_ofs_rt_ofs_cls;
4418 ret = qcow2_cache_empty(bs, s->l2_table_cache);
4419 if (ret < 0) {
4420 goto fail;
4423 ret = qcow2_cache_empty(bs, s->refcount_block_cache);
4424 if (ret < 0) {
4425 goto fail;
4428 /* Refcounts will be broken utterly */
4429 ret = qcow2_mark_dirty(bs);
4430 if (ret < 0) {
4431 goto fail;
4434 BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
4436 l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / sizeof(uint64_t));
4437 l1_size2 = (uint64_t)s->l1_size * sizeof(uint64_t);
4439 /* After this call, neither the in-memory nor the on-disk refcount
4440 * information accurately describe the actual references */
4442 ret = bdrv_pwrite_zeroes(bs->file, s->l1_table_offset,
4443 l1_clusters * s->cluster_size, 0);
4444 if (ret < 0) {
4445 goto fail_broken_refcounts;
4447 memset(s->l1_table, 0, l1_size2);
4449 BLKDBG_EVENT(bs->file, BLKDBG_EMPTY_IMAGE_PREPARE);
4451 /* Overwrite enough clusters at the beginning of the sectors to place
4452 * the refcount table, a refcount block and the L1 table in; this may
4453 * overwrite parts of the existing refcount and L1 table, which is not
4454 * an issue because the dirty flag is set, complete data loss is in fact
4455 * desired and partial data loss is consequently fine as well */
4456 ret = bdrv_pwrite_zeroes(bs->file, s->cluster_size,
4457 (2 + l1_clusters) * s->cluster_size, 0);
4458 /* This call (even if it failed overall) may have overwritten on-disk
4459 * refcount structures; in that case, the in-memory refcount information
4460 * will probably differ from the on-disk information which makes the BDS
4461 * unusable */
4462 if (ret < 0) {
4463 goto fail_broken_refcounts;
4466 BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
4467 BLKDBG_EVENT(bs->file, BLKDBG_REFTABLE_UPDATE);
4469 /* "Create" an empty reftable (one cluster) directly after the image
4470 * header and an empty L1 table three clusters after the image header;
4471 * the cluster between those two will be used as the first refblock */
4472 l1_ofs_rt_ofs_cls.l1_offset = cpu_to_be64(3 * s->cluster_size);
4473 l1_ofs_rt_ofs_cls.reftable_offset = cpu_to_be64(s->cluster_size);
4474 l1_ofs_rt_ofs_cls.reftable_clusters = cpu_to_be32(1);
4475 ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, l1_table_offset),
4476 &l1_ofs_rt_ofs_cls, sizeof(l1_ofs_rt_ofs_cls));
4477 if (ret < 0) {
4478 goto fail_broken_refcounts;
4481 s->l1_table_offset = 3 * s->cluster_size;
4483 new_reftable = g_try_new0(uint64_t, s->cluster_size / sizeof(uint64_t));
4484 if (!new_reftable) {
4485 ret = -ENOMEM;
4486 goto fail_broken_refcounts;
4489 s->refcount_table_offset = s->cluster_size;
4490 s->refcount_table_size = s->cluster_size / sizeof(uint64_t);
4491 s->max_refcount_table_index = 0;
4493 g_free(s->refcount_table);
4494 s->refcount_table = new_reftable;
4495 new_reftable = NULL;
4497 /* Now the in-memory refcount information again corresponds to the on-disk
4498 * information (reftable is empty and no refblocks (the refblock cache is
4499 * empty)); however, this means some clusters (e.g. the image header) are
4500 * referenced, but not refcounted, but the normal qcow2 code assumes that
4501 * the in-memory information is always correct */
4503 BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_ALLOC);
4505 /* Enter the first refblock into the reftable */
4506 rt_entry = cpu_to_be64(2 * s->cluster_size);
4507 ret = bdrv_pwrite_sync(bs->file, s->cluster_size,
4508 &rt_entry, sizeof(rt_entry));
4509 if (ret < 0) {
4510 goto fail_broken_refcounts;
4512 s->refcount_table[0] = 2 * s->cluster_size;
4514 s->free_cluster_index = 0;
4515 assert(3 + l1_clusters <= s->refcount_block_size);
4516 offset = qcow2_alloc_clusters(bs, 3 * s->cluster_size + l1_size2);
4517 if (offset < 0) {
4518 ret = offset;
4519 goto fail_broken_refcounts;
4520 } else if (offset > 0) {
4521 error_report("First cluster in emptied image is in use");
4522 abort();
4525 /* Now finally the in-memory information corresponds to the on-disk
4526 * structures and is correct */
4527 ret = qcow2_mark_clean(bs);
4528 if (ret < 0) {
4529 goto fail;
4532 ret = bdrv_truncate(bs->file, (3 + l1_clusters) * s->cluster_size, false,
4533 PREALLOC_MODE_OFF, &local_err);
4534 if (ret < 0) {
4535 error_report_err(local_err);
4536 goto fail;
4539 return 0;
4541 fail_broken_refcounts:
4542 /* The BDS is unusable at this point. If we wanted to make it usable, we
4543 * would have to call qcow2_refcount_close(), qcow2_refcount_init(),
4544 * qcow2_check_refcounts(), qcow2_refcount_close() and qcow2_refcount_init()
4545 * again. However, because the functions which could have caused this error
4546 * path to be taken are used by those functions as well, it's very likely
4547 * that that sequence will fail as well. Therefore, just eject the BDS. */
4548 bs->drv = NULL;
4550 fail:
4551 g_free(new_reftable);
4552 return ret;
4555 static int qcow2_make_empty(BlockDriverState *bs)
4557 BDRVQcow2State *s = bs->opaque;
4558 uint64_t offset, end_offset;
4559 int step = QEMU_ALIGN_DOWN(INT_MAX, s->cluster_size);
4560 int l1_clusters, ret = 0;
4562 l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / sizeof(uint64_t));
4564 if (s->qcow_version >= 3 && !s->snapshots && !s->nb_bitmaps &&
4565 3 + l1_clusters <= s->refcount_block_size &&
4566 s->crypt_method_header != QCOW_CRYPT_LUKS &&
4567 !has_data_file(bs)) {
4568 /* The following function only works for qcow2 v3 images (it
4569 * requires the dirty flag) and only as long as there are no
4570 * features that reserve extra clusters (such as snapshots,
4571 * LUKS header, or persistent bitmaps), because it completely
4572 * empties the image. Furthermore, the L1 table and three
4573 * additional clusters (image header, refcount table, one
4574 * refcount block) have to fit inside one refcount block. It
4575 * only resets the image file, i.e. does not work with an
4576 * external data file. */
4577 return make_completely_empty(bs);
4580 /* This fallback code simply discards every active cluster; this is slow,
4581 * but works in all cases */
4582 end_offset = bs->total_sectors * BDRV_SECTOR_SIZE;
4583 for (offset = 0; offset < end_offset; offset += step) {
4584 /* As this function is generally used after committing an external
4585 * snapshot, QCOW2_DISCARD_SNAPSHOT seems appropriate. Also, the
4586 * default action for this kind of discard is to pass the discard,
4587 * which will ideally result in an actually smaller image file, as
4588 * is probably desired. */
4589 ret = qcow2_cluster_discard(bs, offset, MIN(step, end_offset - offset),
4590 QCOW2_DISCARD_SNAPSHOT, true);
4591 if (ret < 0) {
4592 break;
4596 return ret;
4599 static coroutine_fn int qcow2_co_flush_to_os(BlockDriverState *bs)
4601 BDRVQcow2State *s = bs->opaque;
4602 int ret;
4604 qemu_co_mutex_lock(&s->lock);
4605 ret = qcow2_write_caches(bs);
4606 qemu_co_mutex_unlock(&s->lock);
4608 return ret;
4611 static ssize_t qcow2_measure_crypto_hdr_init_func(QCryptoBlock *block,
4612 size_t headerlen, void *opaque, Error **errp)
4614 size_t *headerlenp = opaque;
4616 /* Stash away the payload size */
4617 *headerlenp = headerlen;
4618 return 0;
4621 static ssize_t qcow2_measure_crypto_hdr_write_func(QCryptoBlock *block,
4622 size_t offset, const uint8_t *buf, size_t buflen,
4623 void *opaque, Error **errp)
4625 /* Discard the bytes, we're not actually writing to an image */
4626 return buflen;
4629 /* Determine the number of bytes for the LUKS payload */
4630 static bool qcow2_measure_luks_headerlen(QemuOpts *opts, size_t *len,
4631 Error **errp)
4633 QDict *opts_qdict;
4634 QDict *cryptoopts_qdict;
4635 QCryptoBlockCreateOptions *cryptoopts;
4636 QCryptoBlock *crypto;
4638 /* Extract "encrypt." options into a qdict */
4639 opts_qdict = qemu_opts_to_qdict(opts, NULL);
4640 qdict_extract_subqdict(opts_qdict, &cryptoopts_qdict, "encrypt.");
4641 qobject_unref(opts_qdict);
4643 /* Build QCryptoBlockCreateOptions object from qdict */
4644 qdict_put_str(cryptoopts_qdict, "format", "luks");
4645 cryptoopts = block_crypto_create_opts_init(cryptoopts_qdict, errp);
4646 qobject_unref(cryptoopts_qdict);
4647 if (!cryptoopts) {
4648 return false;
4651 /* Fake LUKS creation in order to determine the payload size */
4652 crypto = qcrypto_block_create(cryptoopts, "encrypt.",
4653 qcow2_measure_crypto_hdr_init_func,
4654 qcow2_measure_crypto_hdr_write_func,
4655 len, errp);
4656 qapi_free_QCryptoBlockCreateOptions(cryptoopts);
4657 if (!crypto) {
4658 return false;
4661 qcrypto_block_free(crypto);
4662 return true;
4665 static BlockMeasureInfo *qcow2_measure(QemuOpts *opts, BlockDriverState *in_bs,
4666 Error **errp)
4668 Error *local_err = NULL;
4669 BlockMeasureInfo *info;
4670 uint64_t required = 0; /* bytes that contribute to required size */
4671 uint64_t virtual_size; /* disk size as seen by guest */
4672 uint64_t refcount_bits;
4673 uint64_t l2_tables;
4674 uint64_t luks_payload_size = 0;
4675 size_t cluster_size;
4676 int version;
4677 char *optstr;
4678 PreallocMode prealloc;
4679 bool has_backing_file;
4680 bool has_luks;
4682 /* Parse image creation options */
4683 cluster_size = qcow2_opt_get_cluster_size_del(opts, &local_err);
4684 if (local_err) {
4685 goto err;
4688 version = qcow2_opt_get_version_del(opts, &local_err);
4689 if (local_err) {
4690 goto err;
4693 refcount_bits = qcow2_opt_get_refcount_bits_del(opts, version, &local_err);
4694 if (local_err) {
4695 goto err;
4698 optstr = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
4699 prealloc = qapi_enum_parse(&PreallocMode_lookup, optstr,
4700 PREALLOC_MODE_OFF, &local_err);
4701 g_free(optstr);
4702 if (local_err) {
4703 goto err;
4706 optstr = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
4707 has_backing_file = !!optstr;
4708 g_free(optstr);
4710 optstr = qemu_opt_get_del(opts, BLOCK_OPT_ENCRYPT_FORMAT);
4711 has_luks = optstr && strcmp(optstr, "luks") == 0;
4712 g_free(optstr);
4714 if (has_luks) {
4715 size_t headerlen;
4717 if (!qcow2_measure_luks_headerlen(opts, &headerlen, &local_err)) {
4718 goto err;
4721 luks_payload_size = ROUND_UP(headerlen, cluster_size);
4724 virtual_size = qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0);
4725 virtual_size = ROUND_UP(virtual_size, cluster_size);
4727 /* Check that virtual disk size is valid */
4728 l2_tables = DIV_ROUND_UP(virtual_size / cluster_size,
4729 cluster_size / sizeof(uint64_t));
4730 if (l2_tables * sizeof(uint64_t) > QCOW_MAX_L1_SIZE) {
4731 error_setg(&local_err, "The image size is too large "
4732 "(try using a larger cluster size)");
4733 goto err;
4736 /* Account for input image */
4737 if (in_bs) {
4738 int64_t ssize = bdrv_getlength(in_bs);
4739 if (ssize < 0) {
4740 error_setg_errno(&local_err, -ssize,
4741 "Unable to get image virtual_size");
4742 goto err;
4745 virtual_size = ROUND_UP(ssize, cluster_size);
4747 if (has_backing_file) {
4748 /* We don't how much of the backing chain is shared by the input
4749 * image and the new image file. In the worst case the new image's
4750 * backing file has nothing in common with the input image. Be
4751 * conservative and assume all clusters need to be written.
4753 required = virtual_size;
4754 } else {
4755 int64_t offset;
4756 int64_t pnum = 0;
4758 for (offset = 0; offset < ssize; offset += pnum) {
4759 int ret;
4761 ret = bdrv_block_status_above(in_bs, NULL, offset,
4762 ssize - offset, &pnum, NULL,
4763 NULL);
4764 if (ret < 0) {
4765 error_setg_errno(&local_err, -ret,
4766 "Unable to get block status");
4767 goto err;
4770 if (ret & BDRV_BLOCK_ZERO) {
4771 /* Skip zero regions (safe with no backing file) */
4772 } else if ((ret & (BDRV_BLOCK_DATA | BDRV_BLOCK_ALLOCATED)) ==
4773 (BDRV_BLOCK_DATA | BDRV_BLOCK_ALLOCATED)) {
4774 /* Extend pnum to end of cluster for next iteration */
4775 pnum = ROUND_UP(offset + pnum, cluster_size) - offset;
4777 /* Count clusters we've seen */
4778 required += offset % cluster_size + pnum;
4784 /* Take into account preallocation. Nothing special is needed for
4785 * PREALLOC_MODE_METADATA since metadata is always counted.
4787 if (prealloc == PREALLOC_MODE_FULL || prealloc == PREALLOC_MODE_FALLOC) {
4788 required = virtual_size;
4791 info = g_new(BlockMeasureInfo, 1);
4792 info->fully_allocated =
4793 qcow2_calc_prealloc_size(virtual_size, cluster_size,
4794 ctz32(refcount_bits)) + luks_payload_size;
4796 /* Remove data clusters that are not required. This overestimates the
4797 * required size because metadata needed for the fully allocated file is
4798 * still counted.
4800 info->required = info->fully_allocated - virtual_size + required;
4801 return info;
4803 err:
4804 error_propagate(errp, local_err);
4805 return NULL;
4808 static int qcow2_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
4810 BDRVQcow2State *s = bs->opaque;
4811 bdi->unallocated_blocks_are_zero = true;
4812 bdi->cluster_size = s->cluster_size;
4813 bdi->vm_state_offset = qcow2_vm_state_offset(s);
4814 return 0;
4817 static ImageInfoSpecific *qcow2_get_specific_info(BlockDriverState *bs,
4818 Error **errp)
4820 BDRVQcow2State *s = bs->opaque;
4821 ImageInfoSpecific *spec_info;
4822 QCryptoBlockInfo *encrypt_info = NULL;
4823 Error *local_err = NULL;
4825 if (s->crypto != NULL) {
4826 encrypt_info = qcrypto_block_get_info(s->crypto, &local_err);
4827 if (local_err) {
4828 error_propagate(errp, local_err);
4829 return NULL;
4833 spec_info = g_new(ImageInfoSpecific, 1);
4834 *spec_info = (ImageInfoSpecific){
4835 .type = IMAGE_INFO_SPECIFIC_KIND_QCOW2,
4836 .u.qcow2.data = g_new0(ImageInfoSpecificQCow2, 1),
4838 if (s->qcow_version == 2) {
4839 *spec_info->u.qcow2.data = (ImageInfoSpecificQCow2){
4840 .compat = g_strdup("0.10"),
4841 .refcount_bits = s->refcount_bits,
4843 } else if (s->qcow_version == 3) {
4844 Qcow2BitmapInfoList *bitmaps;
4845 bitmaps = qcow2_get_bitmap_info_list(bs, &local_err);
4846 if (local_err) {
4847 error_propagate(errp, local_err);
4848 qapi_free_ImageInfoSpecific(spec_info);
4849 return NULL;
4851 *spec_info->u.qcow2.data = (ImageInfoSpecificQCow2){
4852 .compat = g_strdup("1.1"),
4853 .lazy_refcounts = s->compatible_features &
4854 QCOW2_COMPAT_LAZY_REFCOUNTS,
4855 .has_lazy_refcounts = true,
4856 .corrupt = s->incompatible_features &
4857 QCOW2_INCOMPAT_CORRUPT,
4858 .has_corrupt = true,
4859 .refcount_bits = s->refcount_bits,
4860 .has_bitmaps = !!bitmaps,
4861 .bitmaps = bitmaps,
4862 .has_data_file = !!s->image_data_file,
4863 .data_file = g_strdup(s->image_data_file),
4864 .has_data_file_raw = has_data_file(bs),
4865 .data_file_raw = data_file_is_raw(bs),
4867 } else {
4868 /* if this assertion fails, this probably means a new version was
4869 * added without having it covered here */
4870 assert(false);
4873 if (encrypt_info) {
4874 ImageInfoSpecificQCow2Encryption *qencrypt =
4875 g_new(ImageInfoSpecificQCow2Encryption, 1);
4876 switch (encrypt_info->format) {
4877 case Q_CRYPTO_BLOCK_FORMAT_QCOW:
4878 qencrypt->format = BLOCKDEV_QCOW2_ENCRYPTION_FORMAT_AES;
4879 break;
4880 case Q_CRYPTO_BLOCK_FORMAT_LUKS:
4881 qencrypt->format = BLOCKDEV_QCOW2_ENCRYPTION_FORMAT_LUKS;
4882 qencrypt->u.luks = encrypt_info->u.luks;
4883 break;
4884 default:
4885 abort();
4887 /* Since we did shallow copy above, erase any pointers
4888 * in the original info */
4889 memset(&encrypt_info->u, 0, sizeof(encrypt_info->u));
4890 qapi_free_QCryptoBlockInfo(encrypt_info);
4892 spec_info->u.qcow2.data->has_encrypt = true;
4893 spec_info->u.qcow2.data->encrypt = qencrypt;
4896 return spec_info;
4899 static int qcow2_has_zero_init(BlockDriverState *bs)
4901 BDRVQcow2State *s = bs->opaque;
4902 bool preallocated;
4904 if (qemu_in_coroutine()) {
4905 qemu_co_mutex_lock(&s->lock);
4908 * Check preallocation status: Preallocated images have all L2
4909 * tables allocated, nonpreallocated images have none. It is
4910 * therefore enough to check the first one.
4912 preallocated = s->l1_size > 0 && s->l1_table[0] != 0;
4913 if (qemu_in_coroutine()) {
4914 qemu_co_mutex_unlock(&s->lock);
4917 if (!preallocated) {
4918 return 1;
4919 } else if (bs->encrypted) {
4920 return 0;
4921 } else {
4922 return bdrv_has_zero_init(s->data_file->bs);
4926 static int qcow2_save_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
4927 int64_t pos)
4929 BDRVQcow2State *s = bs->opaque;
4931 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_SAVE);
4932 return bs->drv->bdrv_co_pwritev_part(bs, qcow2_vm_state_offset(s) + pos,
4933 qiov->size, qiov, 0, 0);
4936 static int qcow2_load_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
4937 int64_t pos)
4939 BDRVQcow2State *s = bs->opaque;
4941 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_LOAD);
4942 return bs->drv->bdrv_co_preadv_part(bs, qcow2_vm_state_offset(s) + pos,
4943 qiov->size, qiov, 0, 0);
4947 * Downgrades an image's version. To achieve this, any incompatible features
4948 * have to be removed.
4950 static int qcow2_downgrade(BlockDriverState *bs, int target_version,
4951 BlockDriverAmendStatusCB *status_cb, void *cb_opaque,
4952 Error **errp)
4954 BDRVQcow2State *s = bs->opaque;
4955 int current_version = s->qcow_version;
4956 int ret;
4958 /* This is qcow2_downgrade(), not qcow2_upgrade() */
4959 assert(target_version < current_version);
4961 /* There are no other versions (now) that you can downgrade to */
4962 assert(target_version == 2);
4964 if (s->refcount_order != 4) {
4965 error_setg(errp, "compat=0.10 requires refcount_bits=16");
4966 return -ENOTSUP;
4969 if (has_data_file(bs)) {
4970 error_setg(errp, "Cannot downgrade an image with a data file");
4971 return -ENOTSUP;
4974 /* clear incompatible features */
4975 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
4976 ret = qcow2_mark_clean(bs);
4977 if (ret < 0) {
4978 error_setg_errno(errp, -ret, "Failed to make the image clean");
4979 return ret;
4983 /* with QCOW2_INCOMPAT_CORRUPT, it is pretty much impossible to get here in
4984 * the first place; if that happens nonetheless, returning -ENOTSUP is the
4985 * best thing to do anyway */
4987 if (s->incompatible_features) {
4988 error_setg(errp, "Cannot downgrade an image with incompatible features "
4989 "%#" PRIx64 " set", s->incompatible_features);
4990 return -ENOTSUP;
4993 /* since we can ignore compatible features, we can set them to 0 as well */
4994 s->compatible_features = 0;
4995 /* if lazy refcounts have been used, they have already been fixed through
4996 * clearing the dirty flag */
4998 /* clearing autoclear features is trivial */
4999 s->autoclear_features = 0;
5001 ret = qcow2_expand_zero_clusters(bs, status_cb, cb_opaque);
5002 if (ret < 0) {
5003 error_setg_errno(errp, -ret, "Failed to turn zero into data clusters");
5004 return ret;
5007 s->qcow_version = target_version;
5008 ret = qcow2_update_header(bs);
5009 if (ret < 0) {
5010 s->qcow_version = current_version;
5011 error_setg_errno(errp, -ret, "Failed to update the image header");
5012 return ret;
5014 return 0;
5018 * Upgrades an image's version. While newer versions encompass all
5019 * features of older versions, some things may have to be presented
5020 * differently.
5022 static int qcow2_upgrade(BlockDriverState *bs, int target_version,
5023 BlockDriverAmendStatusCB *status_cb, void *cb_opaque,
5024 Error **errp)
5026 BDRVQcow2State *s = bs->opaque;
5027 bool need_snapshot_update;
5028 int current_version = s->qcow_version;
5029 int i;
5030 int ret;
5032 /* This is qcow2_upgrade(), not qcow2_downgrade() */
5033 assert(target_version > current_version);
5035 /* There are no other versions (yet) that you can upgrade to */
5036 assert(target_version == 3);
5038 status_cb(bs, 0, 2, cb_opaque);
5041 * In v2, snapshots do not need to have extra data. v3 requires
5042 * the 64-bit VM state size and the virtual disk size to be
5043 * present.
5044 * qcow2_write_snapshots() will always write the list in the
5045 * v3-compliant format.
5047 need_snapshot_update = false;
5048 for (i = 0; i < s->nb_snapshots; i++) {
5049 if (s->snapshots[i].extra_data_size <
5050 sizeof_field(QCowSnapshotExtraData, vm_state_size_large) +
5051 sizeof_field(QCowSnapshotExtraData, disk_size))
5053 need_snapshot_update = true;
5054 break;
5057 if (need_snapshot_update) {
5058 ret = qcow2_write_snapshots(bs);
5059 if (ret < 0) {
5060 error_setg_errno(errp, -ret, "Failed to update the snapshot table");
5061 return ret;
5064 status_cb(bs, 1, 2, cb_opaque);
5066 s->qcow_version = target_version;
5067 ret = qcow2_update_header(bs);
5068 if (ret < 0) {
5069 s->qcow_version = current_version;
5070 error_setg_errno(errp, -ret, "Failed to update the image header");
5071 return ret;
5073 status_cb(bs, 2, 2, cb_opaque);
5075 return 0;
5078 typedef enum Qcow2AmendOperation {
5079 /* This is the value Qcow2AmendHelperCBInfo::last_operation will be
5080 * statically initialized to so that the helper CB can discern the first
5081 * invocation from an operation change */
5082 QCOW2_NO_OPERATION = 0,
5084 QCOW2_UPGRADING,
5085 QCOW2_CHANGING_REFCOUNT_ORDER,
5086 QCOW2_DOWNGRADING,
5087 } Qcow2AmendOperation;
5089 typedef struct Qcow2AmendHelperCBInfo {
5090 /* The code coordinating the amend operations should only modify
5091 * these four fields; the rest will be managed by the CB */
5092 BlockDriverAmendStatusCB *original_status_cb;
5093 void *original_cb_opaque;
5095 Qcow2AmendOperation current_operation;
5097 /* Total number of operations to perform (only set once) */
5098 int total_operations;
5100 /* The following fields are managed by the CB */
5102 /* Number of operations completed */
5103 int operations_completed;
5105 /* Cumulative offset of all completed operations */
5106 int64_t offset_completed;
5108 Qcow2AmendOperation last_operation;
5109 int64_t last_work_size;
5110 } Qcow2AmendHelperCBInfo;
5112 static void qcow2_amend_helper_cb(BlockDriverState *bs,
5113 int64_t operation_offset,
5114 int64_t operation_work_size, void *opaque)
5116 Qcow2AmendHelperCBInfo *info = opaque;
5117 int64_t current_work_size;
5118 int64_t projected_work_size;
5120 if (info->current_operation != info->last_operation) {
5121 if (info->last_operation != QCOW2_NO_OPERATION) {
5122 info->offset_completed += info->last_work_size;
5123 info->operations_completed++;
5126 info->last_operation = info->current_operation;
5129 assert(info->total_operations > 0);
5130 assert(info->operations_completed < info->total_operations);
5132 info->last_work_size = operation_work_size;
5134 current_work_size = info->offset_completed + operation_work_size;
5136 /* current_work_size is the total work size for (operations_completed + 1)
5137 * operations (which includes this one), so multiply it by the number of
5138 * operations not covered and divide it by the number of operations
5139 * covered to get a projection for the operations not covered */
5140 projected_work_size = current_work_size * (info->total_operations -
5141 info->operations_completed - 1)
5142 / (info->operations_completed + 1);
5144 info->original_status_cb(bs, info->offset_completed + operation_offset,
5145 current_work_size + projected_work_size,
5146 info->original_cb_opaque);
5149 static int qcow2_amend_options(BlockDriverState *bs, QemuOpts *opts,
5150 BlockDriverAmendStatusCB *status_cb,
5151 void *cb_opaque,
5152 Error **errp)
5154 BDRVQcow2State *s = bs->opaque;
5155 int old_version = s->qcow_version, new_version = old_version;
5156 uint64_t new_size = 0;
5157 const char *backing_file = NULL, *backing_format = NULL, *data_file = NULL;
5158 bool lazy_refcounts = s->use_lazy_refcounts;
5159 bool data_file_raw = data_file_is_raw(bs);
5160 const char *compat = NULL;
5161 uint64_t cluster_size = s->cluster_size;
5162 bool encrypt;
5163 int encformat;
5164 int refcount_bits = s->refcount_bits;
5165 int ret;
5166 QemuOptDesc *desc = opts->list->desc;
5167 Qcow2AmendHelperCBInfo helper_cb_info;
5169 while (desc && desc->name) {
5170 if (!qemu_opt_find(opts, desc->name)) {
5171 /* only change explicitly defined options */
5172 desc++;
5173 continue;
5176 if (!strcmp(desc->name, BLOCK_OPT_COMPAT_LEVEL)) {
5177 compat = qemu_opt_get(opts, BLOCK_OPT_COMPAT_LEVEL);
5178 if (!compat) {
5179 /* preserve default */
5180 } else if (!strcmp(compat, "0.10") || !strcmp(compat, "v2")) {
5181 new_version = 2;
5182 } else if (!strcmp(compat, "1.1") || !strcmp(compat, "v3")) {
5183 new_version = 3;
5184 } else {
5185 error_setg(errp, "Unknown compatibility level %s", compat);
5186 return -EINVAL;
5188 } else if (!strcmp(desc->name, BLOCK_OPT_PREALLOC)) {
5189 error_setg(errp, "Cannot change preallocation mode");
5190 return -ENOTSUP;
5191 } else if (!strcmp(desc->name, BLOCK_OPT_SIZE)) {
5192 new_size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, 0);
5193 } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FILE)) {
5194 backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
5195 } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FMT)) {
5196 backing_format = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
5197 } else if (!strcmp(desc->name, BLOCK_OPT_ENCRYPT)) {
5198 encrypt = qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT,
5199 !!s->crypto);
5201 if (encrypt != !!s->crypto) {
5202 error_setg(errp,
5203 "Changing the encryption flag is not supported");
5204 return -ENOTSUP;
5206 } else if (!strcmp(desc->name, BLOCK_OPT_ENCRYPT_FORMAT)) {
5207 encformat = qcow2_crypt_method_from_format(
5208 qemu_opt_get(opts, BLOCK_OPT_ENCRYPT_FORMAT));
5210 if (encformat != s->crypt_method_header) {
5211 error_setg(errp,
5212 "Changing the encryption format is not supported");
5213 return -ENOTSUP;
5215 } else if (g_str_has_prefix(desc->name, "encrypt.")) {
5216 error_setg(errp,
5217 "Changing the encryption parameters is not supported");
5218 return -ENOTSUP;
5219 } else if (!strcmp(desc->name, BLOCK_OPT_CLUSTER_SIZE)) {
5220 cluster_size = qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE,
5221 cluster_size);
5222 if (cluster_size != s->cluster_size) {
5223 error_setg(errp, "Changing the cluster size is not supported");
5224 return -ENOTSUP;
5226 } else if (!strcmp(desc->name, BLOCK_OPT_LAZY_REFCOUNTS)) {
5227 lazy_refcounts = qemu_opt_get_bool(opts, BLOCK_OPT_LAZY_REFCOUNTS,
5228 lazy_refcounts);
5229 } else if (!strcmp(desc->name, BLOCK_OPT_REFCOUNT_BITS)) {
5230 refcount_bits = qemu_opt_get_number(opts, BLOCK_OPT_REFCOUNT_BITS,
5231 refcount_bits);
5233 if (refcount_bits <= 0 || refcount_bits > 64 ||
5234 !is_power_of_2(refcount_bits))
5236 error_setg(errp, "Refcount width must be a power of two and "
5237 "may not exceed 64 bits");
5238 return -EINVAL;
5240 } else if (!strcmp(desc->name, BLOCK_OPT_DATA_FILE)) {
5241 data_file = qemu_opt_get(opts, BLOCK_OPT_DATA_FILE);
5242 if (data_file && !has_data_file(bs)) {
5243 error_setg(errp, "data-file can only be set for images that "
5244 "use an external data file");
5245 return -EINVAL;
5247 } else if (!strcmp(desc->name, BLOCK_OPT_DATA_FILE_RAW)) {
5248 data_file_raw = qemu_opt_get_bool(opts, BLOCK_OPT_DATA_FILE_RAW,
5249 data_file_raw);
5250 if (data_file_raw && !data_file_is_raw(bs)) {
5251 error_setg(errp, "data-file-raw cannot be set on existing "
5252 "images");
5253 return -EINVAL;
5255 } else {
5256 /* if this point is reached, this probably means a new option was
5257 * added without having it covered here */
5258 abort();
5261 desc++;
5264 helper_cb_info = (Qcow2AmendHelperCBInfo){
5265 .original_status_cb = status_cb,
5266 .original_cb_opaque = cb_opaque,
5267 .total_operations = (new_version != old_version)
5268 + (s->refcount_bits != refcount_bits)
5271 /* Upgrade first (some features may require compat=1.1) */
5272 if (new_version > old_version) {
5273 helper_cb_info.current_operation = QCOW2_UPGRADING;
5274 ret = qcow2_upgrade(bs, new_version, &qcow2_amend_helper_cb,
5275 &helper_cb_info, errp);
5276 if (ret < 0) {
5277 return ret;
5281 if (s->refcount_bits != refcount_bits) {
5282 int refcount_order = ctz32(refcount_bits);
5284 if (new_version < 3 && refcount_bits != 16) {
5285 error_setg(errp, "Refcount widths other than 16 bits require "
5286 "compatibility level 1.1 or above (use compat=1.1 or "
5287 "greater)");
5288 return -EINVAL;
5291 helper_cb_info.current_operation = QCOW2_CHANGING_REFCOUNT_ORDER;
5292 ret = qcow2_change_refcount_order(bs, refcount_order,
5293 &qcow2_amend_helper_cb,
5294 &helper_cb_info, errp);
5295 if (ret < 0) {
5296 return ret;
5300 /* data-file-raw blocks backing files, so clear it first if requested */
5301 if (data_file_raw) {
5302 s->autoclear_features |= QCOW2_AUTOCLEAR_DATA_FILE_RAW;
5303 } else {
5304 s->autoclear_features &= ~QCOW2_AUTOCLEAR_DATA_FILE_RAW;
5307 if (data_file) {
5308 g_free(s->image_data_file);
5309 s->image_data_file = *data_file ? g_strdup(data_file) : NULL;
5312 ret = qcow2_update_header(bs);
5313 if (ret < 0) {
5314 error_setg_errno(errp, -ret, "Failed to update the image header");
5315 return ret;
5318 if (backing_file || backing_format) {
5319 ret = qcow2_change_backing_file(bs,
5320 backing_file ?: s->image_backing_file,
5321 backing_format ?: s->image_backing_format);
5322 if (ret < 0) {
5323 error_setg_errno(errp, -ret, "Failed to change the backing file");
5324 return ret;
5328 if (s->use_lazy_refcounts != lazy_refcounts) {
5329 if (lazy_refcounts) {
5330 if (new_version < 3) {
5331 error_setg(errp, "Lazy refcounts only supported with "
5332 "compatibility level 1.1 and above (use compat=1.1 "
5333 "or greater)");
5334 return -EINVAL;
5336 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
5337 ret = qcow2_update_header(bs);
5338 if (ret < 0) {
5339 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
5340 error_setg_errno(errp, -ret, "Failed to update the image header");
5341 return ret;
5343 s->use_lazy_refcounts = true;
5344 } else {
5345 /* make image clean first */
5346 ret = qcow2_mark_clean(bs);
5347 if (ret < 0) {
5348 error_setg_errno(errp, -ret, "Failed to make the image clean");
5349 return ret;
5351 /* now disallow lazy refcounts */
5352 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
5353 ret = qcow2_update_header(bs);
5354 if (ret < 0) {
5355 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
5356 error_setg_errno(errp, -ret, "Failed to update the image header");
5357 return ret;
5359 s->use_lazy_refcounts = false;
5363 if (new_size) {
5364 BlockBackend *blk = blk_new(bdrv_get_aio_context(bs),
5365 BLK_PERM_RESIZE, BLK_PERM_ALL);
5366 ret = blk_insert_bs(blk, bs, errp);
5367 if (ret < 0) {
5368 blk_unref(blk);
5369 return ret;
5373 * Amending image options should ensure that the image has
5374 * exactly the given new values, so pass exact=true here.
5376 ret = blk_truncate(blk, new_size, true, PREALLOC_MODE_OFF, errp);
5377 blk_unref(blk);
5378 if (ret < 0) {
5379 return ret;
5383 /* Downgrade last (so unsupported features can be removed before) */
5384 if (new_version < old_version) {
5385 helper_cb_info.current_operation = QCOW2_DOWNGRADING;
5386 ret = qcow2_downgrade(bs, new_version, &qcow2_amend_helper_cb,
5387 &helper_cb_info, errp);
5388 if (ret < 0) {
5389 return ret;
5393 return 0;
5397 * If offset or size are negative, respectively, they will not be included in
5398 * the BLOCK_IMAGE_CORRUPTED event emitted.
5399 * fatal will be ignored for read-only BDS; corruptions found there will always
5400 * be considered non-fatal.
5402 void qcow2_signal_corruption(BlockDriverState *bs, bool fatal, int64_t offset,
5403 int64_t size, const char *message_format, ...)
5405 BDRVQcow2State *s = bs->opaque;
5406 const char *node_name;
5407 char *message;
5408 va_list ap;
5410 fatal = fatal && bdrv_is_writable(bs);
5412 if (s->signaled_corruption &&
5413 (!fatal || (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT)))
5415 return;
5418 va_start(ap, message_format);
5419 message = g_strdup_vprintf(message_format, ap);
5420 va_end(ap);
5422 if (fatal) {
5423 fprintf(stderr, "qcow2: Marking image as corrupt: %s; further "
5424 "corruption events will be suppressed\n", message);
5425 } else {
5426 fprintf(stderr, "qcow2: Image is corrupt: %s; further non-fatal "
5427 "corruption events will be suppressed\n", message);
5430 node_name = bdrv_get_node_name(bs);
5431 qapi_event_send_block_image_corrupted(bdrv_get_device_name(bs),
5432 *node_name != '\0', node_name,
5433 message, offset >= 0, offset,
5434 size >= 0, size,
5435 fatal);
5436 g_free(message);
5438 if (fatal) {
5439 qcow2_mark_corrupt(bs);
5440 bs->drv = NULL; /* make BDS unusable */
5443 s->signaled_corruption = true;
5446 static QemuOptsList qcow2_create_opts = {
5447 .name = "qcow2-create-opts",
5448 .head = QTAILQ_HEAD_INITIALIZER(qcow2_create_opts.head),
5449 .desc = {
5451 .name = BLOCK_OPT_SIZE,
5452 .type = QEMU_OPT_SIZE,
5453 .help = "Virtual disk size"
5456 .name = BLOCK_OPT_COMPAT_LEVEL,
5457 .type = QEMU_OPT_STRING,
5458 .help = "Compatibility level (v2 [0.10] or v3 [1.1])"
5461 .name = BLOCK_OPT_BACKING_FILE,
5462 .type = QEMU_OPT_STRING,
5463 .help = "File name of a base image"
5466 .name = BLOCK_OPT_BACKING_FMT,
5467 .type = QEMU_OPT_STRING,
5468 .help = "Image format of the base image"
5471 .name = BLOCK_OPT_DATA_FILE,
5472 .type = QEMU_OPT_STRING,
5473 .help = "File name of an external data file"
5476 .name = BLOCK_OPT_DATA_FILE_RAW,
5477 .type = QEMU_OPT_BOOL,
5478 .help = "The external data file must stay valid as a raw image"
5481 .name = BLOCK_OPT_ENCRYPT,
5482 .type = QEMU_OPT_BOOL,
5483 .help = "Encrypt the image with format 'aes'. (Deprecated "
5484 "in favor of " BLOCK_OPT_ENCRYPT_FORMAT "=aes)",
5487 .name = BLOCK_OPT_ENCRYPT_FORMAT,
5488 .type = QEMU_OPT_STRING,
5489 .help = "Encrypt the image, format choices: 'aes', 'luks'",
5491 BLOCK_CRYPTO_OPT_DEF_KEY_SECRET("encrypt.",
5492 "ID of secret providing qcow AES key or LUKS passphrase"),
5493 BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_ALG("encrypt."),
5494 BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_MODE("encrypt."),
5495 BLOCK_CRYPTO_OPT_DEF_LUKS_IVGEN_ALG("encrypt."),
5496 BLOCK_CRYPTO_OPT_DEF_LUKS_IVGEN_HASH_ALG("encrypt."),
5497 BLOCK_CRYPTO_OPT_DEF_LUKS_HASH_ALG("encrypt."),
5498 BLOCK_CRYPTO_OPT_DEF_LUKS_ITER_TIME("encrypt."),
5500 .name = BLOCK_OPT_CLUSTER_SIZE,
5501 .type = QEMU_OPT_SIZE,
5502 .help = "qcow2 cluster size",
5503 .def_value_str = stringify(DEFAULT_CLUSTER_SIZE)
5506 .name = BLOCK_OPT_PREALLOC,
5507 .type = QEMU_OPT_STRING,
5508 .help = "Preallocation mode (allowed values: off, metadata, "
5509 "falloc, full)"
5512 .name = BLOCK_OPT_LAZY_REFCOUNTS,
5513 .type = QEMU_OPT_BOOL,
5514 .help = "Postpone refcount updates",
5515 .def_value_str = "off"
5518 .name = BLOCK_OPT_REFCOUNT_BITS,
5519 .type = QEMU_OPT_NUMBER,
5520 .help = "Width of a reference count entry in bits",
5521 .def_value_str = "16"
5523 { /* end of list */ }
5527 static const char *const qcow2_strong_runtime_opts[] = {
5528 "encrypt." BLOCK_CRYPTO_OPT_QCOW_KEY_SECRET,
5530 NULL
5533 BlockDriver bdrv_qcow2 = {
5534 .format_name = "qcow2",
5535 .instance_size = sizeof(BDRVQcow2State),
5536 .bdrv_probe = qcow2_probe,
5537 .bdrv_open = qcow2_open,
5538 .bdrv_close = qcow2_close,
5539 .bdrv_reopen_prepare = qcow2_reopen_prepare,
5540 .bdrv_reopen_commit = qcow2_reopen_commit,
5541 .bdrv_reopen_abort = qcow2_reopen_abort,
5542 .bdrv_join_options = qcow2_join_options,
5543 .bdrv_child_perm = bdrv_format_default_perms,
5544 .bdrv_co_create_opts = qcow2_co_create_opts,
5545 .bdrv_co_create = qcow2_co_create,
5546 .bdrv_has_zero_init = qcow2_has_zero_init,
5547 .bdrv_has_zero_init_truncate = bdrv_has_zero_init_1,
5548 .bdrv_co_block_status = qcow2_co_block_status,
5550 .bdrv_co_preadv_part = qcow2_co_preadv_part,
5551 .bdrv_co_pwritev_part = qcow2_co_pwritev_part,
5552 .bdrv_co_flush_to_os = qcow2_co_flush_to_os,
5554 .bdrv_co_pwrite_zeroes = qcow2_co_pwrite_zeroes,
5555 .bdrv_co_pdiscard = qcow2_co_pdiscard,
5556 .bdrv_co_copy_range_from = qcow2_co_copy_range_from,
5557 .bdrv_co_copy_range_to = qcow2_co_copy_range_to,
5558 .bdrv_co_truncate = qcow2_co_truncate,
5559 .bdrv_co_pwritev_compressed_part = qcow2_co_pwritev_compressed_part,
5560 .bdrv_make_empty = qcow2_make_empty,
5562 .bdrv_snapshot_create = qcow2_snapshot_create,
5563 .bdrv_snapshot_goto = qcow2_snapshot_goto,
5564 .bdrv_snapshot_delete = qcow2_snapshot_delete,
5565 .bdrv_snapshot_list = qcow2_snapshot_list,
5566 .bdrv_snapshot_load_tmp = qcow2_snapshot_load_tmp,
5567 .bdrv_measure = qcow2_measure,
5568 .bdrv_get_info = qcow2_get_info,
5569 .bdrv_get_specific_info = qcow2_get_specific_info,
5571 .bdrv_save_vmstate = qcow2_save_vmstate,
5572 .bdrv_load_vmstate = qcow2_load_vmstate,
5574 .supports_backing = true,
5575 .bdrv_change_backing_file = qcow2_change_backing_file,
5577 .bdrv_refresh_limits = qcow2_refresh_limits,
5578 .bdrv_co_invalidate_cache = qcow2_co_invalidate_cache,
5579 .bdrv_inactivate = qcow2_inactivate,
5581 .create_opts = &qcow2_create_opts,
5582 .strong_runtime_opts = qcow2_strong_runtime_opts,
5583 .mutable_opts = mutable_opts,
5584 .bdrv_co_check = qcow2_co_check,
5585 .bdrv_amend_options = qcow2_amend_options,
5587 .bdrv_detach_aio_context = qcow2_detach_aio_context,
5588 .bdrv_attach_aio_context = qcow2_attach_aio_context,
5590 .bdrv_co_can_store_new_dirty_bitmap = qcow2_co_can_store_new_dirty_bitmap,
5591 .bdrv_co_remove_persistent_dirty_bitmap =
5592 qcow2_co_remove_persistent_dirty_bitmap,
5595 static void bdrv_qcow2_init(void)
5597 bdrv_register(&bdrv_qcow2);
5600 block_init(bdrv_qcow2_init);