block/amend: refactor qcow2 amend options
[qemu/ar7.git] / block / qcow2.c
blob389205dffd960a2acf4f3cab946d97e93d13b76b
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;
139 * Zero fill all space in cluster so it has predictable
140 * content, as we may not initialize some regions of the
141 * header (eg only 1 out of 8 key slots will be initialized)
143 clusterlen = size_to_clusters(s, headerlen) * s->cluster_size;
144 assert(qcow2_pre_write_overlap_check(bs, 0, ret, clusterlen, false) == 0);
145 ret = bdrv_pwrite_zeroes(bs->file,
146 ret,
147 clusterlen, 0);
148 if (ret < 0) {
149 error_setg_errno(errp, -ret, "Could not zero fill encryption header");
150 return -1;
153 return ret;
157 static ssize_t qcow2_crypto_hdr_write_func(QCryptoBlock *block, size_t offset,
158 const uint8_t *buf, size_t buflen,
159 void *opaque, Error **errp)
161 BlockDriverState *bs = opaque;
162 BDRVQcow2State *s = bs->opaque;
163 ssize_t ret;
165 if ((offset + buflen) > s->crypto_header.length) {
166 error_setg(errp, "Request for data outside of extension header");
167 return -1;
170 ret = bdrv_pwrite(bs->file,
171 s->crypto_header.offset + offset, buf, buflen);
172 if (ret < 0) {
173 error_setg_errno(errp, -ret, "Could not read encryption header");
174 return -1;
176 return ret;
181 * read qcow2 extension and fill bs
182 * start reading from start_offset
183 * finish reading upon magic of value 0 or when end_offset reached
184 * unknown magic is skipped (future extension this version knows nothing about)
185 * return 0 upon success, non-0 otherwise
187 static int qcow2_read_extensions(BlockDriverState *bs, uint64_t start_offset,
188 uint64_t end_offset, void **p_feature_table,
189 int flags, bool *need_update_header,
190 Error **errp)
192 BDRVQcow2State *s = bs->opaque;
193 QCowExtension ext;
194 uint64_t offset;
195 int ret;
196 Qcow2BitmapHeaderExt bitmaps_ext;
198 if (need_update_header != NULL) {
199 *need_update_header = false;
202 #ifdef DEBUG_EXT
203 printf("qcow2_read_extensions: start=%ld end=%ld\n", start_offset, end_offset);
204 #endif
205 offset = start_offset;
206 while (offset < end_offset) {
208 #ifdef DEBUG_EXT
209 /* Sanity check */
210 if (offset > s->cluster_size)
211 printf("qcow2_read_extension: suspicious offset %lu\n", offset);
213 printf("attempting to read extended header in offset %lu\n", offset);
214 #endif
216 ret = bdrv_pread(bs->file, offset, &ext, sizeof(ext));
217 if (ret < 0) {
218 error_setg_errno(errp, -ret, "qcow2_read_extension: ERROR: "
219 "pread fail from offset %" PRIu64, offset);
220 return 1;
222 ext.magic = be32_to_cpu(ext.magic);
223 ext.len = be32_to_cpu(ext.len);
224 offset += sizeof(ext);
225 #ifdef DEBUG_EXT
226 printf("ext.magic = 0x%x\n", ext.magic);
227 #endif
228 if (offset > end_offset || ext.len > end_offset - offset) {
229 error_setg(errp, "Header extension too large");
230 return -EINVAL;
233 switch (ext.magic) {
234 case QCOW2_EXT_MAGIC_END:
235 return 0;
237 case QCOW2_EXT_MAGIC_BACKING_FORMAT:
238 if (ext.len >= sizeof(bs->backing_format)) {
239 error_setg(errp, "ERROR: ext_backing_format: len=%" PRIu32
240 " too large (>=%zu)", ext.len,
241 sizeof(bs->backing_format));
242 return 2;
244 ret = bdrv_pread(bs->file, offset, bs->backing_format, ext.len);
245 if (ret < 0) {
246 error_setg_errno(errp, -ret, "ERROR: ext_backing_format: "
247 "Could not read format name");
248 return 3;
250 bs->backing_format[ext.len] = '\0';
251 s->image_backing_format = g_strdup(bs->backing_format);
252 #ifdef DEBUG_EXT
253 printf("Qcow2: Got format extension %s\n", bs->backing_format);
254 #endif
255 break;
257 case QCOW2_EXT_MAGIC_FEATURE_TABLE:
258 if (p_feature_table != NULL) {
259 void* feature_table = g_malloc0(ext.len + 2 * sizeof(Qcow2Feature));
260 ret = bdrv_pread(bs->file, offset , feature_table, ext.len);
261 if (ret < 0) {
262 error_setg_errno(errp, -ret, "ERROR: ext_feature_table: "
263 "Could not read table");
264 return ret;
267 *p_feature_table = feature_table;
269 break;
271 case QCOW2_EXT_MAGIC_CRYPTO_HEADER: {
272 unsigned int cflags = 0;
273 if (s->crypt_method_header != QCOW_CRYPT_LUKS) {
274 error_setg(errp, "CRYPTO header extension only "
275 "expected with LUKS encryption method");
276 return -EINVAL;
278 if (ext.len != sizeof(Qcow2CryptoHeaderExtension)) {
279 error_setg(errp, "CRYPTO header extension size %u, "
280 "but expected size %zu", ext.len,
281 sizeof(Qcow2CryptoHeaderExtension));
282 return -EINVAL;
285 ret = bdrv_pread(bs->file, offset, &s->crypto_header, ext.len);
286 if (ret < 0) {
287 error_setg_errno(errp, -ret,
288 "Unable to read CRYPTO header extension");
289 return ret;
291 s->crypto_header.offset = be64_to_cpu(s->crypto_header.offset);
292 s->crypto_header.length = be64_to_cpu(s->crypto_header.length);
294 if ((s->crypto_header.offset % s->cluster_size) != 0) {
295 error_setg(errp, "Encryption header offset '%" PRIu64 "' is "
296 "not a multiple of cluster size '%u'",
297 s->crypto_header.offset, s->cluster_size);
298 return -EINVAL;
301 if (flags & BDRV_O_NO_IO) {
302 cflags |= QCRYPTO_BLOCK_OPEN_NO_IO;
304 s->crypto = qcrypto_block_open(s->crypto_opts, "encrypt.",
305 qcow2_crypto_hdr_read_func,
306 bs, cflags, QCOW2_MAX_THREADS, errp);
307 if (!s->crypto) {
308 return -EINVAL;
310 } break;
312 case QCOW2_EXT_MAGIC_BITMAPS:
313 if (ext.len != sizeof(bitmaps_ext)) {
314 error_setg_errno(errp, -ret, "bitmaps_ext: "
315 "Invalid extension length");
316 return -EINVAL;
319 if (!(s->autoclear_features & QCOW2_AUTOCLEAR_BITMAPS)) {
320 if (s->qcow_version < 3) {
321 /* Let's be a bit more specific */
322 warn_report("This qcow2 v2 image contains bitmaps, but "
323 "they may have been modified by a program "
324 "without persistent bitmap support; so now "
325 "they must all be considered inconsistent");
326 } else {
327 warn_report("a program lacking bitmap support "
328 "modified this file, so all bitmaps are now "
329 "considered inconsistent");
331 error_printf("Some clusters may be leaked, "
332 "run 'qemu-img check -r' on the image "
333 "file to fix.");
334 if (need_update_header != NULL) {
335 /* Updating is needed to drop invalid bitmap extension. */
336 *need_update_header = true;
338 break;
341 ret = bdrv_pread(bs->file, offset, &bitmaps_ext, ext.len);
342 if (ret < 0) {
343 error_setg_errno(errp, -ret, "bitmaps_ext: "
344 "Could not read ext header");
345 return ret;
348 if (bitmaps_ext.reserved32 != 0) {
349 error_setg_errno(errp, -ret, "bitmaps_ext: "
350 "Reserved field is not zero");
351 return -EINVAL;
354 bitmaps_ext.nb_bitmaps = be32_to_cpu(bitmaps_ext.nb_bitmaps);
355 bitmaps_ext.bitmap_directory_size =
356 be64_to_cpu(bitmaps_ext.bitmap_directory_size);
357 bitmaps_ext.bitmap_directory_offset =
358 be64_to_cpu(bitmaps_ext.bitmap_directory_offset);
360 if (bitmaps_ext.nb_bitmaps > QCOW2_MAX_BITMAPS) {
361 error_setg(errp,
362 "bitmaps_ext: Image has %" PRIu32 " bitmaps, "
363 "exceeding the QEMU supported maximum of %d",
364 bitmaps_ext.nb_bitmaps, QCOW2_MAX_BITMAPS);
365 return -EINVAL;
368 if (bitmaps_ext.nb_bitmaps == 0) {
369 error_setg(errp, "found bitmaps extension with zero bitmaps");
370 return -EINVAL;
373 if (offset_into_cluster(s, bitmaps_ext.bitmap_directory_offset)) {
374 error_setg(errp, "bitmaps_ext: "
375 "invalid bitmap directory offset");
376 return -EINVAL;
379 if (bitmaps_ext.bitmap_directory_size >
380 QCOW2_MAX_BITMAP_DIRECTORY_SIZE) {
381 error_setg(errp, "bitmaps_ext: "
382 "bitmap directory size (%" PRIu64 ") exceeds "
383 "the maximum supported size (%d)",
384 bitmaps_ext.bitmap_directory_size,
385 QCOW2_MAX_BITMAP_DIRECTORY_SIZE);
386 return -EINVAL;
389 s->nb_bitmaps = bitmaps_ext.nb_bitmaps;
390 s->bitmap_directory_offset =
391 bitmaps_ext.bitmap_directory_offset;
392 s->bitmap_directory_size =
393 bitmaps_ext.bitmap_directory_size;
395 #ifdef DEBUG_EXT
396 printf("Qcow2: Got bitmaps extension: "
397 "offset=%" PRIu64 " nb_bitmaps=%" PRIu32 "\n",
398 s->bitmap_directory_offset, s->nb_bitmaps);
399 #endif
400 break;
402 case QCOW2_EXT_MAGIC_DATA_FILE:
404 s->image_data_file = g_malloc0(ext.len + 1);
405 ret = bdrv_pread(bs->file, offset, s->image_data_file, ext.len);
406 if (ret < 0) {
407 error_setg_errno(errp, -ret,
408 "ERROR: Could not read data file name");
409 return ret;
411 #ifdef DEBUG_EXT
412 printf("Qcow2: Got external data file %s\n", s->image_data_file);
413 #endif
414 break;
417 default:
418 /* unknown magic - save it in case we need to rewrite the header */
419 /* If you add a new feature, make sure to also update the fast
420 * path of qcow2_make_empty() to deal with it. */
422 Qcow2UnknownHeaderExtension *uext;
424 uext = g_malloc0(sizeof(*uext) + ext.len);
425 uext->magic = ext.magic;
426 uext->len = ext.len;
427 QLIST_INSERT_HEAD(&s->unknown_header_ext, uext, next);
429 ret = bdrv_pread(bs->file, offset , uext->data, uext->len);
430 if (ret < 0) {
431 error_setg_errno(errp, -ret, "ERROR: unknown extension: "
432 "Could not read data");
433 return ret;
436 break;
439 offset += ((ext.len + 7) & ~7);
442 return 0;
445 static void cleanup_unknown_header_ext(BlockDriverState *bs)
447 BDRVQcow2State *s = bs->opaque;
448 Qcow2UnknownHeaderExtension *uext, *next;
450 QLIST_FOREACH_SAFE(uext, &s->unknown_header_ext, next, next) {
451 QLIST_REMOVE(uext, next);
452 g_free(uext);
456 static void report_unsupported_feature(Error **errp, Qcow2Feature *table,
457 uint64_t mask)
459 g_autoptr(GString) features = g_string_sized_new(60);
461 while (table && table->name[0] != '\0') {
462 if (table->type == QCOW2_FEAT_TYPE_INCOMPATIBLE) {
463 if (mask & (1ULL << table->bit)) {
464 if (features->len > 0) {
465 g_string_append(features, ", ");
467 g_string_append_printf(features, "%.46s", table->name);
468 mask &= ~(1ULL << table->bit);
471 table++;
474 if (mask) {
475 if (features->len > 0) {
476 g_string_append(features, ", ");
478 g_string_append_printf(features,
479 "Unknown incompatible feature: %" PRIx64, mask);
482 error_setg(errp, "Unsupported qcow2 feature(s): %s", features->str);
486 * Sets the dirty bit and flushes afterwards if necessary.
488 * The incompatible_features bit is only set if the image file header was
489 * updated successfully. Therefore it is not required to check the return
490 * value of this function.
492 int qcow2_mark_dirty(BlockDriverState *bs)
494 BDRVQcow2State *s = bs->opaque;
495 uint64_t val;
496 int ret;
498 assert(s->qcow_version >= 3);
500 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
501 return 0; /* already dirty */
504 val = cpu_to_be64(s->incompatible_features | QCOW2_INCOMPAT_DIRTY);
505 ret = bdrv_pwrite(bs->file, offsetof(QCowHeader, incompatible_features),
506 &val, sizeof(val));
507 if (ret < 0) {
508 return ret;
510 ret = bdrv_flush(bs->file->bs);
511 if (ret < 0) {
512 return ret;
515 /* Only treat image as dirty if the header was updated successfully */
516 s->incompatible_features |= QCOW2_INCOMPAT_DIRTY;
517 return 0;
521 * Clears the dirty bit and flushes before if necessary. Only call this
522 * function when there are no pending requests, it does not guard against
523 * concurrent requests dirtying the image.
525 static int qcow2_mark_clean(BlockDriverState *bs)
527 BDRVQcow2State *s = bs->opaque;
529 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
530 int ret;
532 s->incompatible_features &= ~QCOW2_INCOMPAT_DIRTY;
534 ret = qcow2_flush_caches(bs);
535 if (ret < 0) {
536 return ret;
539 return qcow2_update_header(bs);
541 return 0;
545 * Marks the image as corrupt.
547 int qcow2_mark_corrupt(BlockDriverState *bs)
549 BDRVQcow2State *s = bs->opaque;
551 s->incompatible_features |= QCOW2_INCOMPAT_CORRUPT;
552 return qcow2_update_header(bs);
556 * Marks the image as consistent, i.e., unsets the corrupt bit, and flushes
557 * before if necessary.
559 int qcow2_mark_consistent(BlockDriverState *bs)
561 BDRVQcow2State *s = bs->opaque;
563 if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
564 int ret = qcow2_flush_caches(bs);
565 if (ret < 0) {
566 return ret;
569 s->incompatible_features &= ~QCOW2_INCOMPAT_CORRUPT;
570 return qcow2_update_header(bs);
572 return 0;
575 static void qcow2_add_check_result(BdrvCheckResult *out,
576 const BdrvCheckResult *src,
577 bool set_allocation_info)
579 out->corruptions += src->corruptions;
580 out->leaks += src->leaks;
581 out->check_errors += src->check_errors;
582 out->corruptions_fixed += src->corruptions_fixed;
583 out->leaks_fixed += src->leaks_fixed;
585 if (set_allocation_info) {
586 out->image_end_offset = src->image_end_offset;
587 out->bfi = src->bfi;
591 static int coroutine_fn qcow2_co_check_locked(BlockDriverState *bs,
592 BdrvCheckResult *result,
593 BdrvCheckMode fix)
595 BdrvCheckResult snapshot_res = {};
596 BdrvCheckResult refcount_res = {};
597 int ret;
599 memset(result, 0, sizeof(*result));
601 ret = qcow2_check_read_snapshot_table(bs, &snapshot_res, fix);
602 if (ret < 0) {
603 qcow2_add_check_result(result, &snapshot_res, false);
604 return ret;
607 ret = qcow2_check_refcounts(bs, &refcount_res, fix);
608 qcow2_add_check_result(result, &refcount_res, true);
609 if (ret < 0) {
610 qcow2_add_check_result(result, &snapshot_res, false);
611 return ret;
614 ret = qcow2_check_fix_snapshot_table(bs, &snapshot_res, fix);
615 qcow2_add_check_result(result, &snapshot_res, false);
616 if (ret < 0) {
617 return ret;
620 if (fix && result->check_errors == 0 && result->corruptions == 0) {
621 ret = qcow2_mark_clean(bs);
622 if (ret < 0) {
623 return ret;
625 return qcow2_mark_consistent(bs);
627 return ret;
630 static int coroutine_fn qcow2_co_check(BlockDriverState *bs,
631 BdrvCheckResult *result,
632 BdrvCheckMode fix)
634 BDRVQcow2State *s = bs->opaque;
635 int ret;
637 qemu_co_mutex_lock(&s->lock);
638 ret = qcow2_co_check_locked(bs, result, fix);
639 qemu_co_mutex_unlock(&s->lock);
640 return ret;
643 int qcow2_validate_table(BlockDriverState *bs, uint64_t offset,
644 uint64_t entries, size_t entry_len,
645 int64_t max_size_bytes, const char *table_name,
646 Error **errp)
648 BDRVQcow2State *s = bs->opaque;
650 if (entries > max_size_bytes / entry_len) {
651 error_setg(errp, "%s too large", table_name);
652 return -EFBIG;
655 /* Use signed INT64_MAX as the maximum even for uint64_t header fields,
656 * because values will be passed to qemu functions taking int64_t. */
657 if ((INT64_MAX - entries * entry_len < offset) ||
658 (offset_into_cluster(s, offset) != 0)) {
659 error_setg(errp, "%s offset invalid", table_name);
660 return -EINVAL;
663 return 0;
666 static const char *const mutable_opts[] = {
667 QCOW2_OPT_LAZY_REFCOUNTS,
668 QCOW2_OPT_DISCARD_REQUEST,
669 QCOW2_OPT_DISCARD_SNAPSHOT,
670 QCOW2_OPT_DISCARD_OTHER,
671 QCOW2_OPT_OVERLAP,
672 QCOW2_OPT_OVERLAP_TEMPLATE,
673 QCOW2_OPT_OVERLAP_MAIN_HEADER,
674 QCOW2_OPT_OVERLAP_ACTIVE_L1,
675 QCOW2_OPT_OVERLAP_ACTIVE_L2,
676 QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
677 QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
678 QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
679 QCOW2_OPT_OVERLAP_INACTIVE_L1,
680 QCOW2_OPT_OVERLAP_INACTIVE_L2,
681 QCOW2_OPT_OVERLAP_BITMAP_DIRECTORY,
682 QCOW2_OPT_CACHE_SIZE,
683 QCOW2_OPT_L2_CACHE_SIZE,
684 QCOW2_OPT_L2_CACHE_ENTRY_SIZE,
685 QCOW2_OPT_REFCOUNT_CACHE_SIZE,
686 QCOW2_OPT_CACHE_CLEAN_INTERVAL,
687 NULL
690 static QemuOptsList qcow2_runtime_opts = {
691 .name = "qcow2",
692 .head = QTAILQ_HEAD_INITIALIZER(qcow2_runtime_opts.head),
693 .desc = {
695 .name = QCOW2_OPT_LAZY_REFCOUNTS,
696 .type = QEMU_OPT_BOOL,
697 .help = "Postpone refcount updates",
700 .name = QCOW2_OPT_DISCARD_REQUEST,
701 .type = QEMU_OPT_BOOL,
702 .help = "Pass guest discard requests to the layer below",
705 .name = QCOW2_OPT_DISCARD_SNAPSHOT,
706 .type = QEMU_OPT_BOOL,
707 .help = "Generate discard requests when snapshot related space "
708 "is freed",
711 .name = QCOW2_OPT_DISCARD_OTHER,
712 .type = QEMU_OPT_BOOL,
713 .help = "Generate discard requests when other clusters are freed",
716 .name = QCOW2_OPT_OVERLAP,
717 .type = QEMU_OPT_STRING,
718 .help = "Selects which overlap checks to perform from a range of "
719 "templates (none, constant, cached, all)",
722 .name = QCOW2_OPT_OVERLAP_TEMPLATE,
723 .type = QEMU_OPT_STRING,
724 .help = "Selects which overlap checks to perform from a range of "
725 "templates (none, constant, cached, all)",
728 .name = QCOW2_OPT_OVERLAP_MAIN_HEADER,
729 .type = QEMU_OPT_BOOL,
730 .help = "Check for unintended writes into the main qcow2 header",
733 .name = QCOW2_OPT_OVERLAP_ACTIVE_L1,
734 .type = QEMU_OPT_BOOL,
735 .help = "Check for unintended writes into the active L1 table",
738 .name = QCOW2_OPT_OVERLAP_ACTIVE_L2,
739 .type = QEMU_OPT_BOOL,
740 .help = "Check for unintended writes into an active L2 table",
743 .name = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
744 .type = QEMU_OPT_BOOL,
745 .help = "Check for unintended writes into the refcount table",
748 .name = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
749 .type = QEMU_OPT_BOOL,
750 .help = "Check for unintended writes into a refcount block",
753 .name = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
754 .type = QEMU_OPT_BOOL,
755 .help = "Check for unintended writes into the snapshot table",
758 .name = QCOW2_OPT_OVERLAP_INACTIVE_L1,
759 .type = QEMU_OPT_BOOL,
760 .help = "Check for unintended writes into an inactive L1 table",
763 .name = QCOW2_OPT_OVERLAP_INACTIVE_L2,
764 .type = QEMU_OPT_BOOL,
765 .help = "Check for unintended writes into an inactive L2 table",
768 .name = QCOW2_OPT_OVERLAP_BITMAP_DIRECTORY,
769 .type = QEMU_OPT_BOOL,
770 .help = "Check for unintended writes into the bitmap directory",
773 .name = QCOW2_OPT_CACHE_SIZE,
774 .type = QEMU_OPT_SIZE,
775 .help = "Maximum combined metadata (L2 tables and refcount blocks) "
776 "cache size",
779 .name = QCOW2_OPT_L2_CACHE_SIZE,
780 .type = QEMU_OPT_SIZE,
781 .help = "Maximum L2 table cache size",
784 .name = QCOW2_OPT_L2_CACHE_ENTRY_SIZE,
785 .type = QEMU_OPT_SIZE,
786 .help = "Size of each entry in the L2 cache",
789 .name = QCOW2_OPT_REFCOUNT_CACHE_SIZE,
790 .type = QEMU_OPT_SIZE,
791 .help = "Maximum refcount block cache size",
794 .name = QCOW2_OPT_CACHE_CLEAN_INTERVAL,
795 .type = QEMU_OPT_NUMBER,
796 .help = "Clean unused cache entries after this time (in seconds)",
798 BLOCK_CRYPTO_OPT_DEF_KEY_SECRET("encrypt.",
799 "ID of secret providing qcow2 AES key or LUKS passphrase"),
800 { /* end of list */ }
804 static const char *overlap_bool_option_names[QCOW2_OL_MAX_BITNR] = {
805 [QCOW2_OL_MAIN_HEADER_BITNR] = QCOW2_OPT_OVERLAP_MAIN_HEADER,
806 [QCOW2_OL_ACTIVE_L1_BITNR] = QCOW2_OPT_OVERLAP_ACTIVE_L1,
807 [QCOW2_OL_ACTIVE_L2_BITNR] = QCOW2_OPT_OVERLAP_ACTIVE_L2,
808 [QCOW2_OL_REFCOUNT_TABLE_BITNR] = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
809 [QCOW2_OL_REFCOUNT_BLOCK_BITNR] = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
810 [QCOW2_OL_SNAPSHOT_TABLE_BITNR] = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
811 [QCOW2_OL_INACTIVE_L1_BITNR] = QCOW2_OPT_OVERLAP_INACTIVE_L1,
812 [QCOW2_OL_INACTIVE_L2_BITNR] = QCOW2_OPT_OVERLAP_INACTIVE_L2,
813 [QCOW2_OL_BITMAP_DIRECTORY_BITNR] = QCOW2_OPT_OVERLAP_BITMAP_DIRECTORY,
816 static void cache_clean_timer_cb(void *opaque)
818 BlockDriverState *bs = opaque;
819 BDRVQcow2State *s = bs->opaque;
820 qcow2_cache_clean_unused(s->l2_table_cache);
821 qcow2_cache_clean_unused(s->refcount_block_cache);
822 timer_mod(s->cache_clean_timer, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) +
823 (int64_t) s->cache_clean_interval * 1000);
826 static void cache_clean_timer_init(BlockDriverState *bs, AioContext *context)
828 BDRVQcow2State *s = bs->opaque;
829 if (s->cache_clean_interval > 0) {
830 s->cache_clean_timer = aio_timer_new(context, QEMU_CLOCK_VIRTUAL,
831 SCALE_MS, cache_clean_timer_cb,
832 bs);
833 timer_mod(s->cache_clean_timer, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) +
834 (int64_t) s->cache_clean_interval * 1000);
838 static void cache_clean_timer_del(BlockDriverState *bs)
840 BDRVQcow2State *s = bs->opaque;
841 if (s->cache_clean_timer) {
842 timer_del(s->cache_clean_timer);
843 timer_free(s->cache_clean_timer);
844 s->cache_clean_timer = NULL;
848 static void qcow2_detach_aio_context(BlockDriverState *bs)
850 cache_clean_timer_del(bs);
853 static void qcow2_attach_aio_context(BlockDriverState *bs,
854 AioContext *new_context)
856 cache_clean_timer_init(bs, new_context);
859 static void read_cache_sizes(BlockDriverState *bs, QemuOpts *opts,
860 uint64_t *l2_cache_size,
861 uint64_t *l2_cache_entry_size,
862 uint64_t *refcount_cache_size, Error **errp)
864 BDRVQcow2State *s = bs->opaque;
865 uint64_t combined_cache_size, l2_cache_max_setting;
866 bool l2_cache_size_set, refcount_cache_size_set, combined_cache_size_set;
867 bool l2_cache_entry_size_set;
868 int min_refcount_cache = MIN_REFCOUNT_CACHE_SIZE * s->cluster_size;
869 uint64_t virtual_disk_size = bs->total_sectors * BDRV_SECTOR_SIZE;
870 uint64_t max_l2_entries = DIV_ROUND_UP(virtual_disk_size, s->cluster_size);
871 /* An L2 table is always one cluster in size so the max cache size
872 * should be a multiple of the cluster size. */
873 uint64_t max_l2_cache = ROUND_UP(max_l2_entries * sizeof(uint64_t),
874 s->cluster_size);
876 combined_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_CACHE_SIZE);
877 l2_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_L2_CACHE_SIZE);
878 refcount_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
879 l2_cache_entry_size_set = qemu_opt_get(opts, QCOW2_OPT_L2_CACHE_ENTRY_SIZE);
881 combined_cache_size = qemu_opt_get_size(opts, QCOW2_OPT_CACHE_SIZE, 0);
882 l2_cache_max_setting = qemu_opt_get_size(opts, QCOW2_OPT_L2_CACHE_SIZE,
883 DEFAULT_L2_CACHE_MAX_SIZE);
884 *refcount_cache_size = qemu_opt_get_size(opts,
885 QCOW2_OPT_REFCOUNT_CACHE_SIZE, 0);
887 *l2_cache_entry_size = qemu_opt_get_size(
888 opts, QCOW2_OPT_L2_CACHE_ENTRY_SIZE, s->cluster_size);
890 *l2_cache_size = MIN(max_l2_cache, l2_cache_max_setting);
892 if (combined_cache_size_set) {
893 if (l2_cache_size_set && refcount_cache_size_set) {
894 error_setg(errp, QCOW2_OPT_CACHE_SIZE ", " QCOW2_OPT_L2_CACHE_SIZE
895 " and " QCOW2_OPT_REFCOUNT_CACHE_SIZE " may not be set "
896 "at the same time");
897 return;
898 } else if (l2_cache_size_set &&
899 (l2_cache_max_setting > combined_cache_size)) {
900 error_setg(errp, QCOW2_OPT_L2_CACHE_SIZE " may not exceed "
901 QCOW2_OPT_CACHE_SIZE);
902 return;
903 } else if (*refcount_cache_size > combined_cache_size) {
904 error_setg(errp, QCOW2_OPT_REFCOUNT_CACHE_SIZE " may not exceed "
905 QCOW2_OPT_CACHE_SIZE);
906 return;
909 if (l2_cache_size_set) {
910 *refcount_cache_size = combined_cache_size - *l2_cache_size;
911 } else if (refcount_cache_size_set) {
912 *l2_cache_size = combined_cache_size - *refcount_cache_size;
913 } else {
914 /* Assign as much memory as possible to the L2 cache, and
915 * use the remainder for the refcount cache */
916 if (combined_cache_size >= max_l2_cache + min_refcount_cache) {
917 *l2_cache_size = max_l2_cache;
918 *refcount_cache_size = combined_cache_size - *l2_cache_size;
919 } else {
920 *refcount_cache_size =
921 MIN(combined_cache_size, min_refcount_cache);
922 *l2_cache_size = combined_cache_size - *refcount_cache_size;
928 * If the L2 cache is not enough to cover the whole disk then
929 * default to 4KB entries. Smaller entries reduce the cost of
930 * loads and evictions and increase I/O performance.
932 if (*l2_cache_size < max_l2_cache && !l2_cache_entry_size_set) {
933 *l2_cache_entry_size = MIN(s->cluster_size, 4096);
936 /* l2_cache_size and refcount_cache_size are ensured to have at least
937 * their minimum values in qcow2_update_options_prepare() */
939 if (*l2_cache_entry_size < (1 << MIN_CLUSTER_BITS) ||
940 *l2_cache_entry_size > s->cluster_size ||
941 !is_power_of_2(*l2_cache_entry_size)) {
942 error_setg(errp, "L2 cache entry size must be a power of two "
943 "between %d and the cluster size (%d)",
944 1 << MIN_CLUSTER_BITS, s->cluster_size);
945 return;
949 typedef struct Qcow2ReopenState {
950 Qcow2Cache *l2_table_cache;
951 Qcow2Cache *refcount_block_cache;
952 int l2_slice_size; /* Number of entries in a slice of the L2 table */
953 bool use_lazy_refcounts;
954 int overlap_check;
955 bool discard_passthrough[QCOW2_DISCARD_MAX];
956 uint64_t cache_clean_interval;
957 QCryptoBlockOpenOptions *crypto_opts; /* Disk encryption runtime options */
958 } Qcow2ReopenState;
960 static int qcow2_update_options_prepare(BlockDriverState *bs,
961 Qcow2ReopenState *r,
962 QDict *options, int flags,
963 Error **errp)
965 BDRVQcow2State *s = bs->opaque;
966 QemuOpts *opts = NULL;
967 const char *opt_overlap_check, *opt_overlap_check_template;
968 int overlap_check_template = 0;
969 uint64_t l2_cache_size, l2_cache_entry_size, refcount_cache_size;
970 int i;
971 const char *encryptfmt;
972 QDict *encryptopts = NULL;
973 Error *local_err = NULL;
974 int ret;
976 qdict_extract_subqdict(options, &encryptopts, "encrypt.");
977 encryptfmt = qdict_get_try_str(encryptopts, "format");
979 opts = qemu_opts_create(&qcow2_runtime_opts, NULL, 0, &error_abort);
980 qemu_opts_absorb_qdict(opts, options, &local_err);
981 if (local_err) {
982 error_propagate(errp, local_err);
983 ret = -EINVAL;
984 goto fail;
987 /* get L2 table/refcount block cache size from command line options */
988 read_cache_sizes(bs, opts, &l2_cache_size, &l2_cache_entry_size,
989 &refcount_cache_size, &local_err);
990 if (local_err) {
991 error_propagate(errp, local_err);
992 ret = -EINVAL;
993 goto fail;
996 l2_cache_size /= l2_cache_entry_size;
997 if (l2_cache_size < MIN_L2_CACHE_SIZE) {
998 l2_cache_size = MIN_L2_CACHE_SIZE;
1000 if (l2_cache_size > INT_MAX) {
1001 error_setg(errp, "L2 cache size too big");
1002 ret = -EINVAL;
1003 goto fail;
1006 refcount_cache_size /= s->cluster_size;
1007 if (refcount_cache_size < MIN_REFCOUNT_CACHE_SIZE) {
1008 refcount_cache_size = MIN_REFCOUNT_CACHE_SIZE;
1010 if (refcount_cache_size > INT_MAX) {
1011 error_setg(errp, "Refcount cache size too big");
1012 ret = -EINVAL;
1013 goto fail;
1016 /* alloc new L2 table/refcount block cache, flush old one */
1017 if (s->l2_table_cache) {
1018 ret = qcow2_cache_flush(bs, s->l2_table_cache);
1019 if (ret) {
1020 error_setg_errno(errp, -ret, "Failed to flush the L2 table cache");
1021 goto fail;
1025 if (s->refcount_block_cache) {
1026 ret = qcow2_cache_flush(bs, s->refcount_block_cache);
1027 if (ret) {
1028 error_setg_errno(errp, -ret,
1029 "Failed to flush the refcount block cache");
1030 goto fail;
1034 r->l2_slice_size = l2_cache_entry_size / sizeof(uint64_t);
1035 r->l2_table_cache = qcow2_cache_create(bs, l2_cache_size,
1036 l2_cache_entry_size);
1037 r->refcount_block_cache = qcow2_cache_create(bs, refcount_cache_size,
1038 s->cluster_size);
1039 if (r->l2_table_cache == NULL || r->refcount_block_cache == NULL) {
1040 error_setg(errp, "Could not allocate metadata caches");
1041 ret = -ENOMEM;
1042 goto fail;
1045 /* New interval for cache cleanup timer */
1046 r->cache_clean_interval =
1047 qemu_opt_get_number(opts, QCOW2_OPT_CACHE_CLEAN_INTERVAL,
1048 DEFAULT_CACHE_CLEAN_INTERVAL);
1049 #ifndef CONFIG_LINUX
1050 if (r->cache_clean_interval != 0) {
1051 error_setg(errp, QCOW2_OPT_CACHE_CLEAN_INTERVAL
1052 " not supported on this host");
1053 ret = -EINVAL;
1054 goto fail;
1056 #endif
1057 if (r->cache_clean_interval > UINT_MAX) {
1058 error_setg(errp, "Cache clean interval too big");
1059 ret = -EINVAL;
1060 goto fail;
1063 /* lazy-refcounts; flush if going from enabled to disabled */
1064 r->use_lazy_refcounts = qemu_opt_get_bool(opts, QCOW2_OPT_LAZY_REFCOUNTS,
1065 (s->compatible_features & QCOW2_COMPAT_LAZY_REFCOUNTS));
1066 if (r->use_lazy_refcounts && s->qcow_version < 3) {
1067 error_setg(errp, "Lazy refcounts require a qcow2 image with at least "
1068 "qemu 1.1 compatibility level");
1069 ret = -EINVAL;
1070 goto fail;
1073 if (s->use_lazy_refcounts && !r->use_lazy_refcounts) {
1074 ret = qcow2_mark_clean(bs);
1075 if (ret < 0) {
1076 error_setg_errno(errp, -ret, "Failed to disable lazy refcounts");
1077 goto fail;
1081 /* Overlap check options */
1082 opt_overlap_check = qemu_opt_get(opts, QCOW2_OPT_OVERLAP);
1083 opt_overlap_check_template = qemu_opt_get(opts, QCOW2_OPT_OVERLAP_TEMPLATE);
1084 if (opt_overlap_check_template && opt_overlap_check &&
1085 strcmp(opt_overlap_check_template, opt_overlap_check))
1087 error_setg(errp, "Conflicting values for qcow2 options '"
1088 QCOW2_OPT_OVERLAP "' ('%s') and '" QCOW2_OPT_OVERLAP_TEMPLATE
1089 "' ('%s')", opt_overlap_check, opt_overlap_check_template);
1090 ret = -EINVAL;
1091 goto fail;
1093 if (!opt_overlap_check) {
1094 opt_overlap_check = opt_overlap_check_template ?: "cached";
1097 if (!strcmp(opt_overlap_check, "none")) {
1098 overlap_check_template = 0;
1099 } else if (!strcmp(opt_overlap_check, "constant")) {
1100 overlap_check_template = QCOW2_OL_CONSTANT;
1101 } else if (!strcmp(opt_overlap_check, "cached")) {
1102 overlap_check_template = QCOW2_OL_CACHED;
1103 } else if (!strcmp(opt_overlap_check, "all")) {
1104 overlap_check_template = QCOW2_OL_ALL;
1105 } else {
1106 error_setg(errp, "Unsupported value '%s' for qcow2 option "
1107 "'overlap-check'. Allowed are any of the following: "
1108 "none, constant, cached, all", opt_overlap_check);
1109 ret = -EINVAL;
1110 goto fail;
1113 r->overlap_check = 0;
1114 for (i = 0; i < QCOW2_OL_MAX_BITNR; i++) {
1115 /* overlap-check defines a template bitmask, but every flag may be
1116 * overwritten through the associated boolean option */
1117 r->overlap_check |=
1118 qemu_opt_get_bool(opts, overlap_bool_option_names[i],
1119 overlap_check_template & (1 << i)) << i;
1122 r->discard_passthrough[QCOW2_DISCARD_NEVER] = false;
1123 r->discard_passthrough[QCOW2_DISCARD_ALWAYS] = true;
1124 r->discard_passthrough[QCOW2_DISCARD_REQUEST] =
1125 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_REQUEST,
1126 flags & BDRV_O_UNMAP);
1127 r->discard_passthrough[QCOW2_DISCARD_SNAPSHOT] =
1128 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_SNAPSHOT, true);
1129 r->discard_passthrough[QCOW2_DISCARD_OTHER] =
1130 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_OTHER, false);
1132 switch (s->crypt_method_header) {
1133 case QCOW_CRYPT_NONE:
1134 if (encryptfmt) {
1135 error_setg(errp, "No encryption in image header, but options "
1136 "specified format '%s'", encryptfmt);
1137 ret = -EINVAL;
1138 goto fail;
1140 break;
1142 case QCOW_CRYPT_AES:
1143 if (encryptfmt && !g_str_equal(encryptfmt, "aes")) {
1144 error_setg(errp,
1145 "Header reported 'aes' encryption format but "
1146 "options specify '%s'", encryptfmt);
1147 ret = -EINVAL;
1148 goto fail;
1150 qdict_put_str(encryptopts, "format", "qcow");
1151 r->crypto_opts = block_crypto_open_opts_init(encryptopts, errp);
1152 break;
1154 case QCOW_CRYPT_LUKS:
1155 if (encryptfmt && !g_str_equal(encryptfmt, "luks")) {
1156 error_setg(errp,
1157 "Header reported 'luks' encryption format but "
1158 "options specify '%s'", encryptfmt);
1159 ret = -EINVAL;
1160 goto fail;
1162 qdict_put_str(encryptopts, "format", "luks");
1163 r->crypto_opts = block_crypto_open_opts_init(encryptopts, errp);
1164 break;
1166 default:
1167 error_setg(errp, "Unsupported encryption method %d",
1168 s->crypt_method_header);
1169 break;
1171 if (s->crypt_method_header != QCOW_CRYPT_NONE && !r->crypto_opts) {
1172 ret = -EINVAL;
1173 goto fail;
1176 ret = 0;
1177 fail:
1178 qobject_unref(encryptopts);
1179 qemu_opts_del(opts);
1180 opts = NULL;
1181 return ret;
1184 static void qcow2_update_options_commit(BlockDriverState *bs,
1185 Qcow2ReopenState *r)
1187 BDRVQcow2State *s = bs->opaque;
1188 int i;
1190 if (s->l2_table_cache) {
1191 qcow2_cache_destroy(s->l2_table_cache);
1193 if (s->refcount_block_cache) {
1194 qcow2_cache_destroy(s->refcount_block_cache);
1196 s->l2_table_cache = r->l2_table_cache;
1197 s->refcount_block_cache = r->refcount_block_cache;
1198 s->l2_slice_size = r->l2_slice_size;
1200 s->overlap_check = r->overlap_check;
1201 s->use_lazy_refcounts = r->use_lazy_refcounts;
1203 for (i = 0; i < QCOW2_DISCARD_MAX; i++) {
1204 s->discard_passthrough[i] = r->discard_passthrough[i];
1207 if (s->cache_clean_interval != r->cache_clean_interval) {
1208 cache_clean_timer_del(bs);
1209 s->cache_clean_interval = r->cache_clean_interval;
1210 cache_clean_timer_init(bs, bdrv_get_aio_context(bs));
1213 qapi_free_QCryptoBlockOpenOptions(s->crypto_opts);
1214 s->crypto_opts = r->crypto_opts;
1217 static void qcow2_update_options_abort(BlockDriverState *bs,
1218 Qcow2ReopenState *r)
1220 if (r->l2_table_cache) {
1221 qcow2_cache_destroy(r->l2_table_cache);
1223 if (r->refcount_block_cache) {
1224 qcow2_cache_destroy(r->refcount_block_cache);
1226 qapi_free_QCryptoBlockOpenOptions(r->crypto_opts);
1229 static int qcow2_update_options(BlockDriverState *bs, QDict *options,
1230 int flags, Error **errp)
1232 Qcow2ReopenState r = {};
1233 int ret;
1235 ret = qcow2_update_options_prepare(bs, &r, options, flags, errp);
1236 if (ret >= 0) {
1237 qcow2_update_options_commit(bs, &r);
1238 } else {
1239 qcow2_update_options_abort(bs, &r);
1242 return ret;
1245 static int validate_compression_type(BDRVQcow2State *s, Error **errp)
1247 switch (s->compression_type) {
1248 case QCOW2_COMPRESSION_TYPE_ZLIB:
1249 #ifdef CONFIG_ZSTD
1250 case QCOW2_COMPRESSION_TYPE_ZSTD:
1251 #endif
1252 break;
1254 default:
1255 error_setg(errp, "qcow2: unknown compression type: %u",
1256 s->compression_type);
1257 return -ENOTSUP;
1261 * if the compression type differs from QCOW2_COMPRESSION_TYPE_ZLIB
1262 * the incompatible feature flag must be set
1264 if (s->compression_type == QCOW2_COMPRESSION_TYPE_ZLIB) {
1265 if (s->incompatible_features & QCOW2_INCOMPAT_COMPRESSION) {
1266 error_setg(errp, "qcow2: Compression type incompatible feature "
1267 "bit must not be set");
1268 return -EINVAL;
1270 } else {
1271 if (!(s->incompatible_features & QCOW2_INCOMPAT_COMPRESSION)) {
1272 error_setg(errp, "qcow2: Compression type incompatible feature "
1273 "bit must be set");
1274 return -EINVAL;
1278 return 0;
1281 /* Called with s->lock held. */
1282 static int coroutine_fn qcow2_do_open(BlockDriverState *bs, QDict *options,
1283 int flags, Error **errp)
1285 BDRVQcow2State *s = bs->opaque;
1286 unsigned int len, i;
1287 int ret = 0;
1288 QCowHeader header;
1289 Error *local_err = NULL;
1290 uint64_t ext_end;
1291 uint64_t l1_vm_state_index;
1292 bool update_header = false;
1294 ret = bdrv_pread(bs->file, 0, &header, sizeof(header));
1295 if (ret < 0) {
1296 error_setg_errno(errp, -ret, "Could not read qcow2 header");
1297 goto fail;
1299 header.magic = be32_to_cpu(header.magic);
1300 header.version = be32_to_cpu(header.version);
1301 header.backing_file_offset = be64_to_cpu(header.backing_file_offset);
1302 header.backing_file_size = be32_to_cpu(header.backing_file_size);
1303 header.size = be64_to_cpu(header.size);
1304 header.cluster_bits = be32_to_cpu(header.cluster_bits);
1305 header.crypt_method = be32_to_cpu(header.crypt_method);
1306 header.l1_table_offset = be64_to_cpu(header.l1_table_offset);
1307 header.l1_size = be32_to_cpu(header.l1_size);
1308 header.refcount_table_offset = be64_to_cpu(header.refcount_table_offset);
1309 header.refcount_table_clusters =
1310 be32_to_cpu(header.refcount_table_clusters);
1311 header.snapshots_offset = be64_to_cpu(header.snapshots_offset);
1312 header.nb_snapshots = be32_to_cpu(header.nb_snapshots);
1314 if (header.magic != QCOW_MAGIC) {
1315 error_setg(errp, "Image is not in qcow2 format");
1316 ret = -EINVAL;
1317 goto fail;
1319 if (header.version < 2 || header.version > 3) {
1320 error_setg(errp, "Unsupported qcow2 version %" PRIu32, header.version);
1321 ret = -ENOTSUP;
1322 goto fail;
1325 s->qcow_version = header.version;
1327 /* Initialise cluster size */
1328 if (header.cluster_bits < MIN_CLUSTER_BITS ||
1329 header.cluster_bits > MAX_CLUSTER_BITS) {
1330 error_setg(errp, "Unsupported cluster size: 2^%" PRIu32,
1331 header.cluster_bits);
1332 ret = -EINVAL;
1333 goto fail;
1336 s->cluster_bits = header.cluster_bits;
1337 s->cluster_size = 1 << s->cluster_bits;
1339 /* Initialise version 3 header fields */
1340 if (header.version == 2) {
1341 header.incompatible_features = 0;
1342 header.compatible_features = 0;
1343 header.autoclear_features = 0;
1344 header.refcount_order = 4;
1345 header.header_length = 72;
1346 } else {
1347 header.incompatible_features =
1348 be64_to_cpu(header.incompatible_features);
1349 header.compatible_features = be64_to_cpu(header.compatible_features);
1350 header.autoclear_features = be64_to_cpu(header.autoclear_features);
1351 header.refcount_order = be32_to_cpu(header.refcount_order);
1352 header.header_length = be32_to_cpu(header.header_length);
1354 if (header.header_length < 104) {
1355 error_setg(errp, "qcow2 header too short");
1356 ret = -EINVAL;
1357 goto fail;
1361 if (header.header_length > s->cluster_size) {
1362 error_setg(errp, "qcow2 header exceeds cluster size");
1363 ret = -EINVAL;
1364 goto fail;
1367 if (header.header_length > sizeof(header)) {
1368 s->unknown_header_fields_size = header.header_length - sizeof(header);
1369 s->unknown_header_fields = g_malloc(s->unknown_header_fields_size);
1370 ret = bdrv_pread(bs->file, sizeof(header), s->unknown_header_fields,
1371 s->unknown_header_fields_size);
1372 if (ret < 0) {
1373 error_setg_errno(errp, -ret, "Could not read unknown qcow2 header "
1374 "fields");
1375 goto fail;
1379 if (header.backing_file_offset > s->cluster_size) {
1380 error_setg(errp, "Invalid backing file offset");
1381 ret = -EINVAL;
1382 goto fail;
1385 if (header.backing_file_offset) {
1386 ext_end = header.backing_file_offset;
1387 } else {
1388 ext_end = 1 << header.cluster_bits;
1391 /* Handle feature bits */
1392 s->incompatible_features = header.incompatible_features;
1393 s->compatible_features = header.compatible_features;
1394 s->autoclear_features = header.autoclear_features;
1397 * Handle compression type
1398 * Older qcow2 images don't contain the compression type header.
1399 * Distinguish them by the header length and use
1400 * the only valid (default) compression type in that case
1402 if (header.header_length > offsetof(QCowHeader, compression_type)) {
1403 s->compression_type = header.compression_type;
1404 } else {
1405 s->compression_type = QCOW2_COMPRESSION_TYPE_ZLIB;
1408 ret = validate_compression_type(s, errp);
1409 if (ret) {
1410 goto fail;
1413 if (s->incompatible_features & ~QCOW2_INCOMPAT_MASK) {
1414 void *feature_table = NULL;
1415 qcow2_read_extensions(bs, header.header_length, ext_end,
1416 &feature_table, flags, NULL, NULL);
1417 report_unsupported_feature(errp, feature_table,
1418 s->incompatible_features &
1419 ~QCOW2_INCOMPAT_MASK);
1420 ret = -ENOTSUP;
1421 g_free(feature_table);
1422 goto fail;
1425 if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
1426 /* Corrupt images may not be written to unless they are being repaired
1428 if ((flags & BDRV_O_RDWR) && !(flags & BDRV_O_CHECK)) {
1429 error_setg(errp, "qcow2: Image is corrupt; cannot be opened "
1430 "read/write");
1431 ret = -EACCES;
1432 goto fail;
1436 /* Check support for various header values */
1437 if (header.refcount_order > 6) {
1438 error_setg(errp, "Reference count entry width too large; may not "
1439 "exceed 64 bits");
1440 ret = -EINVAL;
1441 goto fail;
1443 s->refcount_order = header.refcount_order;
1444 s->refcount_bits = 1 << s->refcount_order;
1445 s->refcount_max = UINT64_C(1) << (s->refcount_bits - 1);
1446 s->refcount_max += s->refcount_max - 1;
1448 s->crypt_method_header = header.crypt_method;
1449 if (s->crypt_method_header) {
1450 if (bdrv_uses_whitelist() &&
1451 s->crypt_method_header == QCOW_CRYPT_AES) {
1452 error_setg(errp,
1453 "Use of AES-CBC encrypted qcow2 images is no longer "
1454 "supported in system emulators");
1455 error_append_hint(errp,
1456 "You can use 'qemu-img convert' to convert your "
1457 "image to an alternative supported format, such "
1458 "as unencrypted qcow2, or raw with the LUKS "
1459 "format instead.\n");
1460 ret = -ENOSYS;
1461 goto fail;
1464 if (s->crypt_method_header == QCOW_CRYPT_AES) {
1465 s->crypt_physical_offset = false;
1466 } else {
1467 /* Assuming LUKS and any future crypt methods we
1468 * add will all use physical offsets, due to the
1469 * fact that the alternative is insecure... */
1470 s->crypt_physical_offset = true;
1473 bs->encrypted = true;
1476 s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */
1477 s->l2_size = 1 << s->l2_bits;
1478 /* 2^(s->refcount_order - 3) is the refcount width in bytes */
1479 s->refcount_block_bits = s->cluster_bits - (s->refcount_order - 3);
1480 s->refcount_block_size = 1 << s->refcount_block_bits;
1481 bs->total_sectors = header.size / BDRV_SECTOR_SIZE;
1482 s->csize_shift = (62 - (s->cluster_bits - 8));
1483 s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;
1484 s->cluster_offset_mask = (1LL << s->csize_shift) - 1;
1486 s->refcount_table_offset = header.refcount_table_offset;
1487 s->refcount_table_size =
1488 header.refcount_table_clusters << (s->cluster_bits - 3);
1490 if (header.refcount_table_clusters == 0 && !(flags & BDRV_O_CHECK)) {
1491 error_setg(errp, "Image does not contain a reference count table");
1492 ret = -EINVAL;
1493 goto fail;
1496 ret = qcow2_validate_table(bs, s->refcount_table_offset,
1497 header.refcount_table_clusters,
1498 s->cluster_size, QCOW_MAX_REFTABLE_SIZE,
1499 "Reference count table", errp);
1500 if (ret < 0) {
1501 goto fail;
1504 if (!(flags & BDRV_O_CHECK)) {
1506 * The total size in bytes of the snapshot table is checked in
1507 * qcow2_read_snapshots() because the size of each snapshot is
1508 * variable and we don't know it yet.
1509 * Here we only check the offset and number of snapshots.
1511 ret = qcow2_validate_table(bs, header.snapshots_offset,
1512 header.nb_snapshots,
1513 sizeof(QCowSnapshotHeader),
1514 sizeof(QCowSnapshotHeader) *
1515 QCOW_MAX_SNAPSHOTS,
1516 "Snapshot table", errp);
1517 if (ret < 0) {
1518 goto fail;
1522 /* read the level 1 table */
1523 ret = qcow2_validate_table(bs, header.l1_table_offset,
1524 header.l1_size, sizeof(uint64_t),
1525 QCOW_MAX_L1_SIZE, "Active L1 table", errp);
1526 if (ret < 0) {
1527 goto fail;
1529 s->l1_size = header.l1_size;
1530 s->l1_table_offset = header.l1_table_offset;
1532 l1_vm_state_index = size_to_l1(s, header.size);
1533 if (l1_vm_state_index > INT_MAX) {
1534 error_setg(errp, "Image is too big");
1535 ret = -EFBIG;
1536 goto fail;
1538 s->l1_vm_state_index = l1_vm_state_index;
1540 /* the L1 table must contain at least enough entries to put
1541 header.size bytes */
1542 if (s->l1_size < s->l1_vm_state_index) {
1543 error_setg(errp, "L1 table is too small");
1544 ret = -EINVAL;
1545 goto fail;
1548 if (s->l1_size > 0) {
1549 s->l1_table = qemu_try_blockalign(bs->file->bs,
1550 s->l1_size * sizeof(uint64_t));
1551 if (s->l1_table == NULL) {
1552 error_setg(errp, "Could not allocate L1 table");
1553 ret = -ENOMEM;
1554 goto fail;
1556 ret = bdrv_pread(bs->file, s->l1_table_offset, s->l1_table,
1557 s->l1_size * sizeof(uint64_t));
1558 if (ret < 0) {
1559 error_setg_errno(errp, -ret, "Could not read L1 table");
1560 goto fail;
1562 for(i = 0;i < s->l1_size; i++) {
1563 s->l1_table[i] = be64_to_cpu(s->l1_table[i]);
1567 /* Parse driver-specific options */
1568 ret = qcow2_update_options(bs, options, flags, errp);
1569 if (ret < 0) {
1570 goto fail;
1573 s->flags = flags;
1575 ret = qcow2_refcount_init(bs);
1576 if (ret != 0) {
1577 error_setg_errno(errp, -ret, "Could not initialize refcount handling");
1578 goto fail;
1581 QLIST_INIT(&s->cluster_allocs);
1582 QTAILQ_INIT(&s->discards);
1584 /* read qcow2 extensions */
1585 if (qcow2_read_extensions(bs, header.header_length, ext_end, NULL,
1586 flags, &update_header, &local_err)) {
1587 error_propagate(errp, local_err);
1588 ret = -EINVAL;
1589 goto fail;
1592 /* Open external data file */
1593 s->data_file = bdrv_open_child(NULL, options, "data-file", bs,
1594 &child_of_bds, BDRV_CHILD_DATA,
1595 true, &local_err);
1596 if (local_err) {
1597 error_propagate(errp, local_err);
1598 ret = -EINVAL;
1599 goto fail;
1602 if (s->incompatible_features & QCOW2_INCOMPAT_DATA_FILE) {
1603 if (!s->data_file && s->image_data_file) {
1604 s->data_file = bdrv_open_child(s->image_data_file, options,
1605 "data-file", bs, &child_of_bds,
1606 BDRV_CHILD_DATA, false, errp);
1607 if (!s->data_file) {
1608 ret = -EINVAL;
1609 goto fail;
1612 if (!s->data_file) {
1613 error_setg(errp, "'data-file' is required for this image");
1614 ret = -EINVAL;
1615 goto fail;
1618 /* No data here */
1619 bs->file->role &= ~BDRV_CHILD_DATA;
1621 /* Must succeed because we have given up permissions if anything */
1622 bdrv_child_refresh_perms(bs, bs->file, &error_abort);
1623 } else {
1624 if (s->data_file) {
1625 error_setg(errp, "'data-file' can only be set for images with an "
1626 "external data file");
1627 ret = -EINVAL;
1628 goto fail;
1631 s->data_file = bs->file;
1633 if (data_file_is_raw(bs)) {
1634 error_setg(errp, "data-file-raw requires a data file");
1635 ret = -EINVAL;
1636 goto fail;
1640 /* qcow2_read_extension may have set up the crypto context
1641 * if the crypt method needs a header region, some methods
1642 * don't need header extensions, so must check here
1644 if (s->crypt_method_header && !s->crypto) {
1645 if (s->crypt_method_header == QCOW_CRYPT_AES) {
1646 unsigned int cflags = 0;
1647 if (flags & BDRV_O_NO_IO) {
1648 cflags |= QCRYPTO_BLOCK_OPEN_NO_IO;
1650 s->crypto = qcrypto_block_open(s->crypto_opts, "encrypt.",
1651 NULL, NULL, cflags,
1652 QCOW2_MAX_THREADS, errp);
1653 if (!s->crypto) {
1654 ret = -EINVAL;
1655 goto fail;
1657 } else if (!(flags & BDRV_O_NO_IO)) {
1658 error_setg(errp, "Missing CRYPTO header for crypt method %d",
1659 s->crypt_method_header);
1660 ret = -EINVAL;
1661 goto fail;
1665 /* read the backing file name */
1666 if (header.backing_file_offset != 0) {
1667 len = header.backing_file_size;
1668 if (len > MIN(1023, s->cluster_size - header.backing_file_offset) ||
1669 len >= sizeof(bs->backing_file)) {
1670 error_setg(errp, "Backing file name too long");
1671 ret = -EINVAL;
1672 goto fail;
1674 ret = bdrv_pread(bs->file, header.backing_file_offset,
1675 bs->auto_backing_file, len);
1676 if (ret < 0) {
1677 error_setg_errno(errp, -ret, "Could not read backing file name");
1678 goto fail;
1680 bs->auto_backing_file[len] = '\0';
1681 pstrcpy(bs->backing_file, sizeof(bs->backing_file),
1682 bs->auto_backing_file);
1683 s->image_backing_file = g_strdup(bs->auto_backing_file);
1687 * Internal snapshots; skip reading them in check mode, because
1688 * we do not need them then, and we do not want to abort because
1689 * of a broken table.
1691 if (!(flags & BDRV_O_CHECK)) {
1692 s->snapshots_offset = header.snapshots_offset;
1693 s->nb_snapshots = header.nb_snapshots;
1695 ret = qcow2_read_snapshots(bs, errp);
1696 if (ret < 0) {
1697 goto fail;
1701 /* Clear unknown autoclear feature bits */
1702 update_header |= s->autoclear_features & ~QCOW2_AUTOCLEAR_MASK;
1703 update_header =
1704 update_header && !bs->read_only && !(flags & BDRV_O_INACTIVE);
1705 if (update_header) {
1706 s->autoclear_features &= QCOW2_AUTOCLEAR_MASK;
1709 /* == Handle persistent dirty bitmaps ==
1711 * We want load dirty bitmaps in three cases:
1713 * 1. Normal open of the disk in active mode, not related to invalidation
1714 * after migration.
1716 * 2. Invalidation of the target vm after pre-copy phase of migration, if
1717 * bitmaps are _not_ migrating through migration channel, i.e.
1718 * 'dirty-bitmaps' capability is disabled.
1720 * 3. Invalidation of source vm after failed or canceled migration.
1721 * This is a very interesting case. There are two possible types of
1722 * bitmaps:
1724 * A. Stored on inactivation and removed. They should be loaded from the
1725 * image.
1727 * B. Not stored: not-persistent bitmaps and bitmaps, migrated through
1728 * the migration channel (with dirty-bitmaps capability).
1730 * On the other hand, there are two possible sub-cases:
1732 * 3.1 disk was changed by somebody else while were inactive. In this
1733 * case all in-RAM dirty bitmaps (both persistent and not) are
1734 * definitely invalid. And we don't have any method to determine
1735 * this.
1737 * Simple and safe thing is to just drop all the bitmaps of type B on
1738 * inactivation. But in this case we lose bitmaps in valid 4.2 case.
1740 * On the other hand, resuming source vm, if disk was already changed
1741 * is a bad thing anyway: not only bitmaps, the whole vm state is
1742 * out of sync with disk.
1744 * This means, that user or management tool, who for some reason
1745 * decided to resume source vm, after disk was already changed by
1746 * target vm, should at least drop all dirty bitmaps by hand.
1748 * So, we can ignore this case for now, but TODO: "generation"
1749 * extension for qcow2, to determine, that image was changed after
1750 * last inactivation. And if it is changed, we will drop (or at least
1751 * mark as 'invalid' all the bitmaps of type B, both persistent
1752 * and not).
1754 * 3.2 disk was _not_ changed while were inactive. Bitmaps may be saved
1755 * to disk ('dirty-bitmaps' capability disabled), or not saved
1756 * ('dirty-bitmaps' capability enabled), but we don't need to care
1757 * of: let's load bitmaps as always: stored bitmaps will be loaded,
1758 * and not stored has flag IN_USE=1 in the image and will be skipped
1759 * on loading.
1761 * One remaining possible case when we don't want load bitmaps:
1763 * 4. Open disk in inactive mode in target vm (bitmaps are migrating or
1764 * will be loaded on invalidation, no needs try loading them before)
1767 if (!(bdrv_get_flags(bs) & BDRV_O_INACTIVE)) {
1768 /* It's case 1, 2 or 3.2. Or 3.1 which is BUG in management layer. */
1769 bool header_updated = qcow2_load_dirty_bitmaps(bs, &local_err);
1770 if (local_err != NULL) {
1771 error_propagate(errp, local_err);
1772 ret = -EINVAL;
1773 goto fail;
1776 update_header = update_header && !header_updated;
1779 if (update_header) {
1780 ret = qcow2_update_header(bs);
1781 if (ret < 0) {
1782 error_setg_errno(errp, -ret, "Could not update qcow2 header");
1783 goto fail;
1787 bs->supported_zero_flags = header.version >= 3 ?
1788 BDRV_REQ_MAY_UNMAP | BDRV_REQ_NO_FALLBACK : 0;
1789 bs->supported_truncate_flags = BDRV_REQ_ZERO_WRITE;
1791 /* Repair image if dirty */
1792 if (!(flags & (BDRV_O_CHECK | BDRV_O_INACTIVE)) && !bs->read_only &&
1793 (s->incompatible_features & QCOW2_INCOMPAT_DIRTY)) {
1794 BdrvCheckResult result = {0};
1796 ret = qcow2_co_check_locked(bs, &result,
1797 BDRV_FIX_ERRORS | BDRV_FIX_LEAKS);
1798 if (ret < 0 || result.check_errors) {
1799 if (ret >= 0) {
1800 ret = -EIO;
1802 error_setg_errno(errp, -ret, "Could not repair dirty image");
1803 goto fail;
1807 #ifdef DEBUG_ALLOC
1809 BdrvCheckResult result = {0};
1810 qcow2_check_refcounts(bs, &result, 0);
1812 #endif
1814 qemu_co_queue_init(&s->thread_task_queue);
1816 return ret;
1818 fail:
1819 g_free(s->image_data_file);
1820 if (has_data_file(bs)) {
1821 bdrv_unref_child(bs, s->data_file);
1822 s->data_file = NULL;
1824 g_free(s->unknown_header_fields);
1825 cleanup_unknown_header_ext(bs);
1826 qcow2_free_snapshots(bs);
1827 qcow2_refcount_close(bs);
1828 qemu_vfree(s->l1_table);
1829 /* else pre-write overlap checks in cache_destroy may crash */
1830 s->l1_table = NULL;
1831 cache_clean_timer_del(bs);
1832 if (s->l2_table_cache) {
1833 qcow2_cache_destroy(s->l2_table_cache);
1835 if (s->refcount_block_cache) {
1836 qcow2_cache_destroy(s->refcount_block_cache);
1838 qcrypto_block_free(s->crypto);
1839 qapi_free_QCryptoBlockOpenOptions(s->crypto_opts);
1840 return ret;
1843 typedef struct QCow2OpenCo {
1844 BlockDriverState *bs;
1845 QDict *options;
1846 int flags;
1847 Error **errp;
1848 int ret;
1849 } QCow2OpenCo;
1851 static void coroutine_fn qcow2_open_entry(void *opaque)
1853 QCow2OpenCo *qoc = opaque;
1854 BDRVQcow2State *s = qoc->bs->opaque;
1856 qemu_co_mutex_lock(&s->lock);
1857 qoc->ret = qcow2_do_open(qoc->bs, qoc->options, qoc->flags, qoc->errp);
1858 qemu_co_mutex_unlock(&s->lock);
1861 static int qcow2_open(BlockDriverState *bs, QDict *options, int flags,
1862 Error **errp)
1864 BDRVQcow2State *s = bs->opaque;
1865 QCow2OpenCo qoc = {
1866 .bs = bs,
1867 .options = options,
1868 .flags = flags,
1869 .errp = errp,
1870 .ret = -EINPROGRESS
1873 bs->file = bdrv_open_child(NULL, options, "file", bs, &child_of_bds,
1874 BDRV_CHILD_IMAGE, false, errp);
1875 if (!bs->file) {
1876 return -EINVAL;
1879 /* Initialise locks */
1880 qemu_co_mutex_init(&s->lock);
1882 if (qemu_in_coroutine()) {
1883 /* From bdrv_co_create. */
1884 qcow2_open_entry(&qoc);
1885 } else {
1886 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
1887 qemu_coroutine_enter(qemu_coroutine_create(qcow2_open_entry, &qoc));
1888 BDRV_POLL_WHILE(bs, qoc.ret == -EINPROGRESS);
1890 return qoc.ret;
1893 static void qcow2_refresh_limits(BlockDriverState *bs, Error **errp)
1895 BDRVQcow2State *s = bs->opaque;
1897 if (bs->encrypted) {
1898 /* Encryption works on a sector granularity */
1899 bs->bl.request_alignment = qcrypto_block_get_sector_size(s->crypto);
1901 bs->bl.pwrite_zeroes_alignment = s->cluster_size;
1902 bs->bl.pdiscard_alignment = s->cluster_size;
1905 static int qcow2_reopen_prepare(BDRVReopenState *state,
1906 BlockReopenQueue *queue, Error **errp)
1908 Qcow2ReopenState *r;
1909 int ret;
1911 r = g_new0(Qcow2ReopenState, 1);
1912 state->opaque = r;
1914 ret = qcow2_update_options_prepare(state->bs, r, state->options,
1915 state->flags, errp);
1916 if (ret < 0) {
1917 goto fail;
1920 /* We need to write out any unwritten data if we reopen read-only. */
1921 if ((state->flags & BDRV_O_RDWR) == 0) {
1922 ret = qcow2_reopen_bitmaps_ro(state->bs, errp);
1923 if (ret < 0) {
1924 goto fail;
1927 ret = bdrv_flush(state->bs);
1928 if (ret < 0) {
1929 goto fail;
1932 ret = qcow2_mark_clean(state->bs);
1933 if (ret < 0) {
1934 goto fail;
1938 return 0;
1940 fail:
1941 qcow2_update_options_abort(state->bs, r);
1942 g_free(r);
1943 return ret;
1946 static void qcow2_reopen_commit(BDRVReopenState *state)
1948 qcow2_update_options_commit(state->bs, state->opaque);
1949 g_free(state->opaque);
1952 static void qcow2_reopen_commit_post(BDRVReopenState *state)
1954 if (state->flags & BDRV_O_RDWR) {
1955 Error *local_err = NULL;
1957 if (qcow2_reopen_bitmaps_rw(state->bs, &local_err) < 0) {
1959 * This is not fatal, bitmaps just left read-only, so all following
1960 * writes will fail. User can remove read-only bitmaps to unblock
1961 * writes or retry reopen.
1963 error_reportf_err(local_err,
1964 "%s: Failed to make dirty bitmaps writable: ",
1965 bdrv_get_node_name(state->bs));
1970 static void qcow2_reopen_abort(BDRVReopenState *state)
1972 qcow2_update_options_abort(state->bs, state->opaque);
1973 g_free(state->opaque);
1976 static void qcow2_join_options(QDict *options, QDict *old_options)
1978 bool has_new_overlap_template =
1979 qdict_haskey(options, QCOW2_OPT_OVERLAP) ||
1980 qdict_haskey(options, QCOW2_OPT_OVERLAP_TEMPLATE);
1981 bool has_new_total_cache_size =
1982 qdict_haskey(options, QCOW2_OPT_CACHE_SIZE);
1983 bool has_all_cache_options;
1985 /* New overlap template overrides all old overlap options */
1986 if (has_new_overlap_template) {
1987 qdict_del(old_options, QCOW2_OPT_OVERLAP);
1988 qdict_del(old_options, QCOW2_OPT_OVERLAP_TEMPLATE);
1989 qdict_del(old_options, QCOW2_OPT_OVERLAP_MAIN_HEADER);
1990 qdict_del(old_options, QCOW2_OPT_OVERLAP_ACTIVE_L1);
1991 qdict_del(old_options, QCOW2_OPT_OVERLAP_ACTIVE_L2);
1992 qdict_del(old_options, QCOW2_OPT_OVERLAP_REFCOUNT_TABLE);
1993 qdict_del(old_options, QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK);
1994 qdict_del(old_options, QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE);
1995 qdict_del(old_options, QCOW2_OPT_OVERLAP_INACTIVE_L1);
1996 qdict_del(old_options, QCOW2_OPT_OVERLAP_INACTIVE_L2);
1999 /* New total cache size overrides all old options */
2000 if (qdict_haskey(options, QCOW2_OPT_CACHE_SIZE)) {
2001 qdict_del(old_options, QCOW2_OPT_L2_CACHE_SIZE);
2002 qdict_del(old_options, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
2005 qdict_join(options, old_options, false);
2008 * If after merging all cache size options are set, an old total size is
2009 * overwritten. Do keep all options, however, if all three are new. The
2010 * resulting error message is what we want to happen.
2012 has_all_cache_options =
2013 qdict_haskey(options, QCOW2_OPT_CACHE_SIZE) ||
2014 qdict_haskey(options, QCOW2_OPT_L2_CACHE_SIZE) ||
2015 qdict_haskey(options, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
2017 if (has_all_cache_options && !has_new_total_cache_size) {
2018 qdict_del(options, QCOW2_OPT_CACHE_SIZE);
2022 static int coroutine_fn qcow2_co_block_status(BlockDriverState *bs,
2023 bool want_zero,
2024 int64_t offset, int64_t count,
2025 int64_t *pnum, int64_t *map,
2026 BlockDriverState **file)
2028 BDRVQcow2State *s = bs->opaque;
2029 uint64_t cluster_offset;
2030 unsigned int bytes;
2031 int ret, status = 0;
2033 qemu_co_mutex_lock(&s->lock);
2035 if (!s->metadata_preallocation_checked) {
2036 ret = qcow2_detect_metadata_preallocation(bs);
2037 s->metadata_preallocation = (ret == 1);
2038 s->metadata_preallocation_checked = true;
2041 bytes = MIN(INT_MAX, count);
2042 ret = qcow2_get_cluster_offset(bs, offset, &bytes, &cluster_offset);
2043 qemu_co_mutex_unlock(&s->lock);
2044 if (ret < 0) {
2045 return ret;
2048 *pnum = bytes;
2050 if ((ret == QCOW2_CLUSTER_NORMAL || ret == QCOW2_CLUSTER_ZERO_ALLOC) &&
2051 !s->crypto) {
2052 *map = cluster_offset | offset_into_cluster(s, offset);
2053 *file = s->data_file->bs;
2054 status |= BDRV_BLOCK_OFFSET_VALID;
2056 if (ret == QCOW2_CLUSTER_ZERO_PLAIN || ret == QCOW2_CLUSTER_ZERO_ALLOC) {
2057 status |= BDRV_BLOCK_ZERO;
2058 } else if (ret != QCOW2_CLUSTER_UNALLOCATED) {
2059 status |= BDRV_BLOCK_DATA;
2061 if (s->metadata_preallocation && (status & BDRV_BLOCK_DATA) &&
2062 (status & BDRV_BLOCK_OFFSET_VALID))
2064 status |= BDRV_BLOCK_RECURSE;
2066 return status;
2069 static coroutine_fn int qcow2_handle_l2meta(BlockDriverState *bs,
2070 QCowL2Meta **pl2meta,
2071 bool link_l2)
2073 int ret = 0;
2074 QCowL2Meta *l2meta = *pl2meta;
2076 while (l2meta != NULL) {
2077 QCowL2Meta *next;
2079 if (link_l2) {
2080 ret = qcow2_alloc_cluster_link_l2(bs, l2meta);
2081 if (ret) {
2082 goto out;
2084 } else {
2085 qcow2_alloc_cluster_abort(bs, l2meta);
2088 /* Take the request off the list of running requests */
2089 if (l2meta->nb_clusters != 0) {
2090 QLIST_REMOVE(l2meta, next_in_flight);
2093 qemu_co_queue_restart_all(&l2meta->dependent_requests);
2095 next = l2meta->next;
2096 g_free(l2meta);
2097 l2meta = next;
2099 out:
2100 *pl2meta = l2meta;
2101 return ret;
2104 static coroutine_fn int
2105 qcow2_co_preadv_encrypted(BlockDriverState *bs,
2106 uint64_t file_cluster_offset,
2107 uint64_t offset,
2108 uint64_t bytes,
2109 QEMUIOVector *qiov,
2110 uint64_t qiov_offset)
2112 int ret;
2113 BDRVQcow2State *s = bs->opaque;
2114 uint8_t *buf;
2116 assert(bs->encrypted && s->crypto);
2117 assert(bytes <= QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
2120 * For encrypted images, read everything into a temporary
2121 * contiguous buffer on which the AES functions can work.
2122 * Also, decryption in a separate buffer is better as it
2123 * prevents the guest from learning information about the
2124 * encrypted nature of the virtual disk.
2127 buf = qemu_try_blockalign(s->data_file->bs, bytes);
2128 if (buf == NULL) {
2129 return -ENOMEM;
2132 BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);
2133 ret = bdrv_co_pread(s->data_file,
2134 file_cluster_offset + offset_into_cluster(s, offset),
2135 bytes, buf, 0);
2136 if (ret < 0) {
2137 goto fail;
2140 if (qcow2_co_decrypt(bs,
2141 file_cluster_offset + offset_into_cluster(s, offset),
2142 offset, buf, bytes) < 0)
2144 ret = -EIO;
2145 goto fail;
2147 qemu_iovec_from_buf(qiov, qiov_offset, buf, bytes);
2149 fail:
2150 qemu_vfree(buf);
2152 return ret;
2155 typedef struct Qcow2AioTask {
2156 AioTask task;
2158 BlockDriverState *bs;
2159 QCow2ClusterType cluster_type; /* only for read */
2160 uint64_t file_cluster_offset;
2161 uint64_t offset;
2162 uint64_t bytes;
2163 QEMUIOVector *qiov;
2164 uint64_t qiov_offset;
2165 QCowL2Meta *l2meta; /* only for write */
2166 } Qcow2AioTask;
2168 static coroutine_fn int qcow2_co_preadv_task_entry(AioTask *task);
2169 static coroutine_fn int qcow2_add_task(BlockDriverState *bs,
2170 AioTaskPool *pool,
2171 AioTaskFunc func,
2172 QCow2ClusterType cluster_type,
2173 uint64_t file_cluster_offset,
2174 uint64_t offset,
2175 uint64_t bytes,
2176 QEMUIOVector *qiov,
2177 size_t qiov_offset,
2178 QCowL2Meta *l2meta)
2180 Qcow2AioTask local_task;
2181 Qcow2AioTask *task = pool ? g_new(Qcow2AioTask, 1) : &local_task;
2183 *task = (Qcow2AioTask) {
2184 .task.func = func,
2185 .bs = bs,
2186 .cluster_type = cluster_type,
2187 .qiov = qiov,
2188 .file_cluster_offset = file_cluster_offset,
2189 .offset = offset,
2190 .bytes = bytes,
2191 .qiov_offset = qiov_offset,
2192 .l2meta = l2meta,
2195 trace_qcow2_add_task(qemu_coroutine_self(), bs, pool,
2196 func == qcow2_co_preadv_task_entry ? "read" : "write",
2197 cluster_type, file_cluster_offset, offset, bytes,
2198 qiov, qiov_offset);
2200 if (!pool) {
2201 return func(&task->task);
2204 aio_task_pool_start_task(pool, &task->task);
2206 return 0;
2209 static coroutine_fn int qcow2_co_preadv_task(BlockDriverState *bs,
2210 QCow2ClusterType cluster_type,
2211 uint64_t file_cluster_offset,
2212 uint64_t offset, uint64_t bytes,
2213 QEMUIOVector *qiov,
2214 size_t qiov_offset)
2216 BDRVQcow2State *s = bs->opaque;
2217 int offset_in_cluster = offset_into_cluster(s, offset);
2219 switch (cluster_type) {
2220 case QCOW2_CLUSTER_ZERO_PLAIN:
2221 case QCOW2_CLUSTER_ZERO_ALLOC:
2222 /* Both zero types are handled in qcow2_co_preadv_part */
2223 g_assert_not_reached();
2225 case QCOW2_CLUSTER_UNALLOCATED:
2226 assert(bs->backing); /* otherwise handled in qcow2_co_preadv_part */
2228 BLKDBG_EVENT(bs->file, BLKDBG_READ_BACKING_AIO);
2229 return bdrv_co_preadv_part(bs->backing, offset, bytes,
2230 qiov, qiov_offset, 0);
2232 case QCOW2_CLUSTER_COMPRESSED:
2233 return qcow2_co_preadv_compressed(bs, file_cluster_offset,
2234 offset, bytes, qiov, qiov_offset);
2236 case QCOW2_CLUSTER_NORMAL:
2237 assert(offset_into_cluster(s, file_cluster_offset) == 0);
2238 if (bs->encrypted) {
2239 return qcow2_co_preadv_encrypted(bs, file_cluster_offset,
2240 offset, bytes, qiov, qiov_offset);
2243 BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);
2244 return bdrv_co_preadv_part(s->data_file,
2245 file_cluster_offset + offset_in_cluster,
2246 bytes, qiov, qiov_offset, 0);
2248 default:
2249 g_assert_not_reached();
2252 g_assert_not_reached();
2255 static coroutine_fn int qcow2_co_preadv_task_entry(AioTask *task)
2257 Qcow2AioTask *t = container_of(task, Qcow2AioTask, task);
2259 assert(!t->l2meta);
2261 return qcow2_co_preadv_task(t->bs, t->cluster_type, t->file_cluster_offset,
2262 t->offset, t->bytes, t->qiov, t->qiov_offset);
2265 static coroutine_fn int qcow2_co_preadv_part(BlockDriverState *bs,
2266 uint64_t offset, uint64_t bytes,
2267 QEMUIOVector *qiov,
2268 size_t qiov_offset, int flags)
2270 BDRVQcow2State *s = bs->opaque;
2271 int ret = 0;
2272 unsigned int cur_bytes; /* number of bytes in current iteration */
2273 uint64_t cluster_offset = 0;
2274 AioTaskPool *aio = NULL;
2276 while (bytes != 0 && aio_task_pool_status(aio) == 0) {
2277 /* prepare next request */
2278 cur_bytes = MIN(bytes, INT_MAX);
2279 if (s->crypto) {
2280 cur_bytes = MIN(cur_bytes,
2281 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
2284 qemu_co_mutex_lock(&s->lock);
2285 ret = qcow2_get_cluster_offset(bs, offset, &cur_bytes, &cluster_offset);
2286 qemu_co_mutex_unlock(&s->lock);
2287 if (ret < 0) {
2288 goto out;
2291 if (ret == QCOW2_CLUSTER_ZERO_PLAIN ||
2292 ret == QCOW2_CLUSTER_ZERO_ALLOC ||
2293 (ret == QCOW2_CLUSTER_UNALLOCATED && !bs->backing))
2295 qemu_iovec_memset(qiov, qiov_offset, 0, cur_bytes);
2296 } else {
2297 if (!aio && cur_bytes != bytes) {
2298 aio = aio_task_pool_new(QCOW2_MAX_WORKERS);
2300 ret = qcow2_add_task(bs, aio, qcow2_co_preadv_task_entry, ret,
2301 cluster_offset, offset, cur_bytes,
2302 qiov, qiov_offset, NULL);
2303 if (ret < 0) {
2304 goto out;
2308 bytes -= cur_bytes;
2309 offset += cur_bytes;
2310 qiov_offset += cur_bytes;
2313 out:
2314 if (aio) {
2315 aio_task_pool_wait_all(aio);
2316 if (ret == 0) {
2317 ret = aio_task_pool_status(aio);
2319 g_free(aio);
2322 return ret;
2325 /* Check if it's possible to merge a write request with the writing of
2326 * the data from the COW regions */
2327 static bool merge_cow(uint64_t offset, unsigned bytes,
2328 QEMUIOVector *qiov, size_t qiov_offset,
2329 QCowL2Meta *l2meta)
2331 QCowL2Meta *m;
2333 for (m = l2meta; m != NULL; m = m->next) {
2334 /* If both COW regions are empty then there's nothing to merge */
2335 if (m->cow_start.nb_bytes == 0 && m->cow_end.nb_bytes == 0) {
2336 continue;
2339 /* If COW regions are handled already, skip this too */
2340 if (m->skip_cow) {
2341 continue;
2344 /* The data (middle) region must be immediately after the
2345 * start region */
2346 if (l2meta_cow_start(m) + m->cow_start.nb_bytes != offset) {
2347 continue;
2350 /* The end region must be immediately after the data (middle)
2351 * region */
2352 if (m->offset + m->cow_end.offset != offset + bytes) {
2353 continue;
2356 /* Make sure that adding both COW regions to the QEMUIOVector
2357 * does not exceed IOV_MAX */
2358 if (qemu_iovec_subvec_niov(qiov, qiov_offset, bytes) > IOV_MAX - 2) {
2359 continue;
2362 m->data_qiov = qiov;
2363 m->data_qiov_offset = qiov_offset;
2364 return true;
2367 return false;
2370 static bool is_unallocated(BlockDriverState *bs, int64_t offset, int64_t bytes)
2372 int64_t nr;
2373 return !bytes ||
2374 (!bdrv_is_allocated_above(bs, NULL, false, offset, bytes, &nr) &&
2375 nr == bytes);
2378 static bool is_zero_cow(BlockDriverState *bs, QCowL2Meta *m)
2381 * This check is designed for optimization shortcut so it must be
2382 * efficient.
2383 * Instead of is_zero(), use is_unallocated() as it is faster (but not
2384 * as accurate and can result in false negatives).
2386 return is_unallocated(bs, m->offset + m->cow_start.offset,
2387 m->cow_start.nb_bytes) &&
2388 is_unallocated(bs, m->offset + m->cow_end.offset,
2389 m->cow_end.nb_bytes);
2392 static int handle_alloc_space(BlockDriverState *bs, QCowL2Meta *l2meta)
2394 BDRVQcow2State *s = bs->opaque;
2395 QCowL2Meta *m;
2397 if (!(s->data_file->bs->supported_zero_flags & BDRV_REQ_NO_FALLBACK)) {
2398 return 0;
2401 if (bs->encrypted) {
2402 return 0;
2405 for (m = l2meta; m != NULL; m = m->next) {
2406 int ret;
2408 if (!m->cow_start.nb_bytes && !m->cow_end.nb_bytes) {
2409 continue;
2412 if (!is_zero_cow(bs, m)) {
2413 continue;
2417 * instead of writing zero COW buffers,
2418 * efficiently zero out the whole clusters
2421 ret = qcow2_pre_write_overlap_check(bs, 0, m->alloc_offset,
2422 m->nb_clusters * s->cluster_size,
2423 true);
2424 if (ret < 0) {
2425 return ret;
2428 BLKDBG_EVENT(bs->file, BLKDBG_CLUSTER_ALLOC_SPACE);
2429 ret = bdrv_co_pwrite_zeroes(s->data_file, m->alloc_offset,
2430 m->nb_clusters * s->cluster_size,
2431 BDRV_REQ_NO_FALLBACK);
2432 if (ret < 0) {
2433 if (ret != -ENOTSUP && ret != -EAGAIN) {
2434 return ret;
2436 continue;
2439 trace_qcow2_skip_cow(qemu_coroutine_self(), m->offset, m->nb_clusters);
2440 m->skip_cow = true;
2442 return 0;
2446 * qcow2_co_pwritev_task
2447 * Called with s->lock unlocked
2448 * l2meta - if not NULL, qcow2_co_pwritev_task() will consume it. Caller must
2449 * not use it somehow after qcow2_co_pwritev_task() call
2451 static coroutine_fn int qcow2_co_pwritev_task(BlockDriverState *bs,
2452 uint64_t file_cluster_offset,
2453 uint64_t offset, uint64_t bytes,
2454 QEMUIOVector *qiov,
2455 uint64_t qiov_offset,
2456 QCowL2Meta *l2meta)
2458 int ret;
2459 BDRVQcow2State *s = bs->opaque;
2460 void *crypt_buf = NULL;
2461 int offset_in_cluster = offset_into_cluster(s, offset);
2462 QEMUIOVector encrypted_qiov;
2464 if (bs->encrypted) {
2465 assert(s->crypto);
2466 assert(bytes <= QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
2467 crypt_buf = qemu_try_blockalign(bs->file->bs, bytes);
2468 if (crypt_buf == NULL) {
2469 ret = -ENOMEM;
2470 goto out_unlocked;
2472 qemu_iovec_to_buf(qiov, qiov_offset, crypt_buf, bytes);
2474 if (qcow2_co_encrypt(bs, file_cluster_offset + offset_in_cluster,
2475 offset, crypt_buf, bytes) < 0)
2477 ret = -EIO;
2478 goto out_unlocked;
2481 qemu_iovec_init_buf(&encrypted_qiov, crypt_buf, bytes);
2482 qiov = &encrypted_qiov;
2483 qiov_offset = 0;
2486 /* Try to efficiently initialize the physical space with zeroes */
2487 ret = handle_alloc_space(bs, l2meta);
2488 if (ret < 0) {
2489 goto out_unlocked;
2493 * If we need to do COW, check if it's possible to merge the
2494 * writing of the guest data together with that of the COW regions.
2495 * If it's not possible (or not necessary) then write the
2496 * guest data now.
2498 if (!merge_cow(offset, bytes, qiov, qiov_offset, l2meta)) {
2499 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO);
2500 trace_qcow2_writev_data(qemu_coroutine_self(),
2501 file_cluster_offset + offset_in_cluster);
2502 ret = bdrv_co_pwritev_part(s->data_file,
2503 file_cluster_offset + offset_in_cluster,
2504 bytes, qiov, qiov_offset, 0);
2505 if (ret < 0) {
2506 goto out_unlocked;
2510 qemu_co_mutex_lock(&s->lock);
2512 ret = qcow2_handle_l2meta(bs, &l2meta, true);
2513 goto out_locked;
2515 out_unlocked:
2516 qemu_co_mutex_lock(&s->lock);
2518 out_locked:
2519 qcow2_handle_l2meta(bs, &l2meta, false);
2520 qemu_co_mutex_unlock(&s->lock);
2522 qemu_vfree(crypt_buf);
2524 return ret;
2527 static coroutine_fn int qcow2_co_pwritev_task_entry(AioTask *task)
2529 Qcow2AioTask *t = container_of(task, Qcow2AioTask, task);
2531 assert(!t->cluster_type);
2533 return qcow2_co_pwritev_task(t->bs, t->file_cluster_offset,
2534 t->offset, t->bytes, t->qiov, t->qiov_offset,
2535 t->l2meta);
2538 static coroutine_fn int qcow2_co_pwritev_part(
2539 BlockDriverState *bs, uint64_t offset, uint64_t bytes,
2540 QEMUIOVector *qiov, size_t qiov_offset, int flags)
2542 BDRVQcow2State *s = bs->opaque;
2543 int offset_in_cluster;
2544 int ret;
2545 unsigned int cur_bytes; /* number of sectors in current iteration */
2546 uint64_t cluster_offset;
2547 QCowL2Meta *l2meta = NULL;
2548 AioTaskPool *aio = NULL;
2550 trace_qcow2_writev_start_req(qemu_coroutine_self(), offset, bytes);
2552 while (bytes != 0 && aio_task_pool_status(aio) == 0) {
2554 l2meta = NULL;
2556 trace_qcow2_writev_start_part(qemu_coroutine_self());
2557 offset_in_cluster = offset_into_cluster(s, offset);
2558 cur_bytes = MIN(bytes, INT_MAX);
2559 if (bs->encrypted) {
2560 cur_bytes = MIN(cur_bytes,
2561 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size
2562 - offset_in_cluster);
2565 qemu_co_mutex_lock(&s->lock);
2567 ret = qcow2_alloc_cluster_offset(bs, offset, &cur_bytes,
2568 &cluster_offset, &l2meta);
2569 if (ret < 0) {
2570 goto out_locked;
2573 assert(offset_into_cluster(s, cluster_offset) == 0);
2575 ret = qcow2_pre_write_overlap_check(bs, 0,
2576 cluster_offset + offset_in_cluster,
2577 cur_bytes, true);
2578 if (ret < 0) {
2579 goto out_locked;
2582 qemu_co_mutex_unlock(&s->lock);
2584 if (!aio && cur_bytes != bytes) {
2585 aio = aio_task_pool_new(QCOW2_MAX_WORKERS);
2587 ret = qcow2_add_task(bs, aio, qcow2_co_pwritev_task_entry, 0,
2588 cluster_offset, offset, cur_bytes,
2589 qiov, qiov_offset, l2meta);
2590 l2meta = NULL; /* l2meta is consumed by qcow2_co_pwritev_task() */
2591 if (ret < 0) {
2592 goto fail_nometa;
2595 bytes -= cur_bytes;
2596 offset += cur_bytes;
2597 qiov_offset += cur_bytes;
2598 trace_qcow2_writev_done_part(qemu_coroutine_self(), cur_bytes);
2600 ret = 0;
2602 qemu_co_mutex_lock(&s->lock);
2604 out_locked:
2605 qcow2_handle_l2meta(bs, &l2meta, false);
2607 qemu_co_mutex_unlock(&s->lock);
2609 fail_nometa:
2610 if (aio) {
2611 aio_task_pool_wait_all(aio);
2612 if (ret == 0) {
2613 ret = aio_task_pool_status(aio);
2615 g_free(aio);
2618 trace_qcow2_writev_done_req(qemu_coroutine_self(), ret);
2620 return ret;
2623 static int qcow2_inactivate(BlockDriverState *bs)
2625 BDRVQcow2State *s = bs->opaque;
2626 int ret, result = 0;
2627 Error *local_err = NULL;
2629 qcow2_store_persistent_dirty_bitmaps(bs, true, &local_err);
2630 if (local_err != NULL) {
2631 result = -EINVAL;
2632 error_reportf_err(local_err, "Lost persistent bitmaps during "
2633 "inactivation of node '%s': ",
2634 bdrv_get_device_or_node_name(bs));
2637 ret = qcow2_cache_flush(bs, s->l2_table_cache);
2638 if (ret) {
2639 result = ret;
2640 error_report("Failed to flush the L2 table cache: %s",
2641 strerror(-ret));
2644 ret = qcow2_cache_flush(bs, s->refcount_block_cache);
2645 if (ret) {
2646 result = ret;
2647 error_report("Failed to flush the refcount block cache: %s",
2648 strerror(-ret));
2651 if (result == 0) {
2652 qcow2_mark_clean(bs);
2655 return result;
2658 static void qcow2_close(BlockDriverState *bs)
2660 BDRVQcow2State *s = bs->opaque;
2661 qemu_vfree(s->l1_table);
2662 /* else pre-write overlap checks in cache_destroy may crash */
2663 s->l1_table = NULL;
2665 if (!(s->flags & BDRV_O_INACTIVE)) {
2666 qcow2_inactivate(bs);
2669 cache_clean_timer_del(bs);
2670 qcow2_cache_destroy(s->l2_table_cache);
2671 qcow2_cache_destroy(s->refcount_block_cache);
2673 qcrypto_block_free(s->crypto);
2674 s->crypto = NULL;
2675 qapi_free_QCryptoBlockOpenOptions(s->crypto_opts);
2677 g_free(s->unknown_header_fields);
2678 cleanup_unknown_header_ext(bs);
2680 g_free(s->image_data_file);
2681 g_free(s->image_backing_file);
2682 g_free(s->image_backing_format);
2684 if (has_data_file(bs)) {
2685 bdrv_unref_child(bs, s->data_file);
2686 s->data_file = NULL;
2689 qcow2_refcount_close(bs);
2690 qcow2_free_snapshots(bs);
2693 static void coroutine_fn qcow2_co_invalidate_cache(BlockDriverState *bs,
2694 Error **errp)
2696 BDRVQcow2State *s = bs->opaque;
2697 int flags = s->flags;
2698 QCryptoBlock *crypto = NULL;
2699 QDict *options;
2700 Error *local_err = NULL;
2701 int ret;
2704 * Backing files are read-only which makes all of their metadata immutable,
2705 * that means we don't have to worry about reopening them here.
2708 crypto = s->crypto;
2709 s->crypto = NULL;
2711 qcow2_close(bs);
2713 memset(s, 0, sizeof(BDRVQcow2State));
2714 options = qdict_clone_shallow(bs->options);
2716 flags &= ~BDRV_O_INACTIVE;
2717 qemu_co_mutex_lock(&s->lock);
2718 ret = qcow2_do_open(bs, options, flags, &local_err);
2719 qemu_co_mutex_unlock(&s->lock);
2720 qobject_unref(options);
2721 if (local_err) {
2722 error_propagate_prepend(errp, local_err,
2723 "Could not reopen qcow2 layer: ");
2724 bs->drv = NULL;
2725 return;
2726 } else if (ret < 0) {
2727 error_setg_errno(errp, -ret, "Could not reopen qcow2 layer");
2728 bs->drv = NULL;
2729 return;
2732 s->crypto = crypto;
2735 static size_t header_ext_add(char *buf, uint32_t magic, const void *s,
2736 size_t len, size_t buflen)
2738 QCowExtension *ext_backing_fmt = (QCowExtension*) buf;
2739 size_t ext_len = sizeof(QCowExtension) + ((len + 7) & ~7);
2741 if (buflen < ext_len) {
2742 return -ENOSPC;
2745 *ext_backing_fmt = (QCowExtension) {
2746 .magic = cpu_to_be32(magic),
2747 .len = cpu_to_be32(len),
2750 if (len) {
2751 memcpy(buf + sizeof(QCowExtension), s, len);
2754 return ext_len;
2758 * Updates the qcow2 header, including the variable length parts of it, i.e.
2759 * the backing file name and all extensions. qcow2 was not designed to allow
2760 * such changes, so if we run out of space (we can only use the first cluster)
2761 * this function may fail.
2763 * Returns 0 on success, -errno in error cases.
2765 int qcow2_update_header(BlockDriverState *bs)
2767 BDRVQcow2State *s = bs->opaque;
2768 QCowHeader *header;
2769 char *buf;
2770 size_t buflen = s->cluster_size;
2771 int ret;
2772 uint64_t total_size;
2773 uint32_t refcount_table_clusters;
2774 size_t header_length;
2775 Qcow2UnknownHeaderExtension *uext;
2777 buf = qemu_blockalign(bs, buflen);
2779 /* Header structure */
2780 header = (QCowHeader*) buf;
2782 if (buflen < sizeof(*header)) {
2783 ret = -ENOSPC;
2784 goto fail;
2787 header_length = sizeof(*header) + s->unknown_header_fields_size;
2788 total_size = bs->total_sectors * BDRV_SECTOR_SIZE;
2789 refcount_table_clusters = s->refcount_table_size >> (s->cluster_bits - 3);
2791 ret = validate_compression_type(s, NULL);
2792 if (ret) {
2793 goto fail;
2796 *header = (QCowHeader) {
2797 /* Version 2 fields */
2798 .magic = cpu_to_be32(QCOW_MAGIC),
2799 .version = cpu_to_be32(s->qcow_version),
2800 .backing_file_offset = 0,
2801 .backing_file_size = 0,
2802 .cluster_bits = cpu_to_be32(s->cluster_bits),
2803 .size = cpu_to_be64(total_size),
2804 .crypt_method = cpu_to_be32(s->crypt_method_header),
2805 .l1_size = cpu_to_be32(s->l1_size),
2806 .l1_table_offset = cpu_to_be64(s->l1_table_offset),
2807 .refcount_table_offset = cpu_to_be64(s->refcount_table_offset),
2808 .refcount_table_clusters = cpu_to_be32(refcount_table_clusters),
2809 .nb_snapshots = cpu_to_be32(s->nb_snapshots),
2810 .snapshots_offset = cpu_to_be64(s->snapshots_offset),
2812 /* Version 3 fields */
2813 .incompatible_features = cpu_to_be64(s->incompatible_features),
2814 .compatible_features = cpu_to_be64(s->compatible_features),
2815 .autoclear_features = cpu_to_be64(s->autoclear_features),
2816 .refcount_order = cpu_to_be32(s->refcount_order),
2817 .header_length = cpu_to_be32(header_length),
2818 .compression_type = s->compression_type,
2821 /* For older versions, write a shorter header */
2822 switch (s->qcow_version) {
2823 case 2:
2824 ret = offsetof(QCowHeader, incompatible_features);
2825 break;
2826 case 3:
2827 ret = sizeof(*header);
2828 break;
2829 default:
2830 ret = -EINVAL;
2831 goto fail;
2834 buf += ret;
2835 buflen -= ret;
2836 memset(buf, 0, buflen);
2838 /* Preserve any unknown field in the header */
2839 if (s->unknown_header_fields_size) {
2840 if (buflen < s->unknown_header_fields_size) {
2841 ret = -ENOSPC;
2842 goto fail;
2845 memcpy(buf, s->unknown_header_fields, s->unknown_header_fields_size);
2846 buf += s->unknown_header_fields_size;
2847 buflen -= s->unknown_header_fields_size;
2850 /* Backing file format header extension */
2851 if (s->image_backing_format) {
2852 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BACKING_FORMAT,
2853 s->image_backing_format,
2854 strlen(s->image_backing_format),
2855 buflen);
2856 if (ret < 0) {
2857 goto fail;
2860 buf += ret;
2861 buflen -= ret;
2864 /* External data file header extension */
2865 if (has_data_file(bs) && s->image_data_file) {
2866 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_DATA_FILE,
2867 s->image_data_file, strlen(s->image_data_file),
2868 buflen);
2869 if (ret < 0) {
2870 goto fail;
2873 buf += ret;
2874 buflen -= ret;
2877 /* Full disk encryption header pointer extension */
2878 if (s->crypto_header.offset != 0) {
2879 s->crypto_header.offset = cpu_to_be64(s->crypto_header.offset);
2880 s->crypto_header.length = cpu_to_be64(s->crypto_header.length);
2881 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_CRYPTO_HEADER,
2882 &s->crypto_header, sizeof(s->crypto_header),
2883 buflen);
2884 s->crypto_header.offset = be64_to_cpu(s->crypto_header.offset);
2885 s->crypto_header.length = be64_to_cpu(s->crypto_header.length);
2886 if (ret < 0) {
2887 goto fail;
2889 buf += ret;
2890 buflen -= ret;
2894 * Feature table. A mere 8 feature names occupies 392 bytes, and
2895 * when coupled with the v3 minimum header of 104 bytes plus the
2896 * 8-byte end-of-extension marker, that would leave only 8 bytes
2897 * for a backing file name in an image with 512-byte clusters.
2898 * Thus, we choose to omit this header for cluster sizes 4k and
2899 * smaller.
2901 if (s->qcow_version >= 3 && s->cluster_size > 4096) {
2902 static const Qcow2Feature features[] = {
2904 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
2905 .bit = QCOW2_INCOMPAT_DIRTY_BITNR,
2906 .name = "dirty bit",
2909 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
2910 .bit = QCOW2_INCOMPAT_CORRUPT_BITNR,
2911 .name = "corrupt bit",
2914 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
2915 .bit = QCOW2_INCOMPAT_DATA_FILE_BITNR,
2916 .name = "external data file",
2919 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
2920 .bit = QCOW2_INCOMPAT_COMPRESSION_BITNR,
2921 .name = "compression type",
2924 .type = QCOW2_FEAT_TYPE_COMPATIBLE,
2925 .bit = QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR,
2926 .name = "lazy refcounts",
2929 .type = QCOW2_FEAT_TYPE_AUTOCLEAR,
2930 .bit = QCOW2_AUTOCLEAR_BITMAPS_BITNR,
2931 .name = "bitmaps",
2934 .type = QCOW2_FEAT_TYPE_AUTOCLEAR,
2935 .bit = QCOW2_AUTOCLEAR_DATA_FILE_RAW_BITNR,
2936 .name = "raw external data",
2940 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_FEATURE_TABLE,
2941 features, sizeof(features), buflen);
2942 if (ret < 0) {
2943 goto fail;
2945 buf += ret;
2946 buflen -= ret;
2949 /* Bitmap extension */
2950 if (s->nb_bitmaps > 0) {
2951 Qcow2BitmapHeaderExt bitmaps_header = {
2952 .nb_bitmaps = cpu_to_be32(s->nb_bitmaps),
2953 .bitmap_directory_size =
2954 cpu_to_be64(s->bitmap_directory_size),
2955 .bitmap_directory_offset =
2956 cpu_to_be64(s->bitmap_directory_offset)
2958 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BITMAPS,
2959 &bitmaps_header, sizeof(bitmaps_header),
2960 buflen);
2961 if (ret < 0) {
2962 goto fail;
2964 buf += ret;
2965 buflen -= ret;
2968 /* Keep unknown header extensions */
2969 QLIST_FOREACH(uext, &s->unknown_header_ext, next) {
2970 ret = header_ext_add(buf, uext->magic, uext->data, uext->len, buflen);
2971 if (ret < 0) {
2972 goto fail;
2975 buf += ret;
2976 buflen -= ret;
2979 /* End of header extensions */
2980 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_END, NULL, 0, buflen);
2981 if (ret < 0) {
2982 goto fail;
2985 buf += ret;
2986 buflen -= ret;
2988 /* Backing file name */
2989 if (s->image_backing_file) {
2990 size_t backing_file_len = strlen(s->image_backing_file);
2992 if (buflen < backing_file_len) {
2993 ret = -ENOSPC;
2994 goto fail;
2997 /* Using strncpy is ok here, since buf is not NUL-terminated. */
2998 strncpy(buf, s->image_backing_file, buflen);
3000 header->backing_file_offset = cpu_to_be64(buf - ((char*) header));
3001 header->backing_file_size = cpu_to_be32(backing_file_len);
3004 /* Write the new header */
3005 ret = bdrv_pwrite(bs->file, 0, header, s->cluster_size);
3006 if (ret < 0) {
3007 goto fail;
3010 ret = 0;
3011 fail:
3012 qemu_vfree(header);
3013 return ret;
3016 static int qcow2_change_backing_file(BlockDriverState *bs,
3017 const char *backing_file, const char *backing_fmt)
3019 BDRVQcow2State *s = bs->opaque;
3021 /* Adding a backing file means that the external data file alone won't be
3022 * enough to make sense of the content */
3023 if (backing_file && data_file_is_raw(bs)) {
3024 return -EINVAL;
3027 if (backing_file && strlen(backing_file) > 1023) {
3028 return -EINVAL;
3031 pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
3032 backing_file ?: "");
3033 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
3034 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
3036 g_free(s->image_backing_file);
3037 g_free(s->image_backing_format);
3039 s->image_backing_file = backing_file ? g_strdup(bs->backing_file) : NULL;
3040 s->image_backing_format = backing_fmt ? g_strdup(bs->backing_format) : NULL;
3042 return qcow2_update_header(bs);
3045 static int qcow2_set_up_encryption(BlockDriverState *bs,
3046 QCryptoBlockCreateOptions *cryptoopts,
3047 Error **errp)
3049 BDRVQcow2State *s = bs->opaque;
3050 QCryptoBlock *crypto = NULL;
3051 int fmt, ret;
3053 switch (cryptoopts->format) {
3054 case Q_CRYPTO_BLOCK_FORMAT_LUKS:
3055 fmt = QCOW_CRYPT_LUKS;
3056 break;
3057 case Q_CRYPTO_BLOCK_FORMAT_QCOW:
3058 fmt = QCOW_CRYPT_AES;
3059 break;
3060 default:
3061 error_setg(errp, "Crypto format not supported in qcow2");
3062 return -EINVAL;
3065 s->crypt_method_header = fmt;
3067 crypto = qcrypto_block_create(cryptoopts, "encrypt.",
3068 qcow2_crypto_hdr_init_func,
3069 qcow2_crypto_hdr_write_func,
3070 bs, errp);
3071 if (!crypto) {
3072 return -EINVAL;
3075 ret = qcow2_update_header(bs);
3076 if (ret < 0) {
3077 error_setg_errno(errp, -ret, "Could not write encryption header");
3078 goto out;
3081 ret = 0;
3082 out:
3083 qcrypto_block_free(crypto);
3084 return ret;
3088 * Preallocates metadata structures for data clusters between @offset (in the
3089 * guest disk) and @new_length (which is thus generally the new guest disk
3090 * size).
3092 * Returns: 0 on success, -errno on failure.
3094 static int coroutine_fn preallocate_co(BlockDriverState *bs, uint64_t offset,
3095 uint64_t new_length, PreallocMode mode,
3096 Error **errp)
3098 BDRVQcow2State *s = bs->opaque;
3099 uint64_t bytes;
3100 uint64_t host_offset = 0;
3101 int64_t file_length;
3102 unsigned int cur_bytes;
3103 int ret;
3104 QCowL2Meta *meta;
3106 assert(offset <= new_length);
3107 bytes = new_length - offset;
3109 while (bytes) {
3110 cur_bytes = MIN(bytes, QEMU_ALIGN_DOWN(INT_MAX, s->cluster_size));
3111 ret = qcow2_alloc_cluster_offset(bs, offset, &cur_bytes,
3112 &host_offset, &meta);
3113 if (ret < 0) {
3114 error_setg_errno(errp, -ret, "Allocating clusters failed");
3115 return ret;
3118 while (meta) {
3119 QCowL2Meta *next = meta->next;
3121 ret = qcow2_alloc_cluster_link_l2(bs, meta);
3122 if (ret < 0) {
3123 error_setg_errno(errp, -ret, "Mapping clusters failed");
3124 qcow2_free_any_clusters(bs, meta->alloc_offset,
3125 meta->nb_clusters, QCOW2_DISCARD_NEVER);
3126 return ret;
3129 /* There are no dependent requests, but we need to remove our
3130 * request from the list of in-flight requests */
3131 QLIST_REMOVE(meta, next_in_flight);
3133 g_free(meta);
3134 meta = next;
3137 /* TODO Preallocate data if requested */
3139 bytes -= cur_bytes;
3140 offset += cur_bytes;
3144 * It is expected that the image file is large enough to actually contain
3145 * all of the allocated clusters (otherwise we get failing reads after
3146 * EOF). Extend the image to the last allocated sector.
3148 file_length = bdrv_getlength(s->data_file->bs);
3149 if (file_length < 0) {
3150 error_setg_errno(errp, -file_length, "Could not get file size");
3151 return file_length;
3154 if (host_offset + cur_bytes > file_length) {
3155 if (mode == PREALLOC_MODE_METADATA) {
3156 mode = PREALLOC_MODE_OFF;
3158 ret = bdrv_co_truncate(s->data_file, host_offset + cur_bytes, false,
3159 mode, 0, errp);
3160 if (ret < 0) {
3161 return ret;
3165 return 0;
3168 /* qcow2_refcount_metadata_size:
3169 * @clusters: number of clusters to refcount (including data and L1/L2 tables)
3170 * @cluster_size: size of a cluster, in bytes
3171 * @refcount_order: refcount bits power-of-2 exponent
3172 * @generous_increase: allow for the refcount table to be 1.5x as large as it
3173 * needs to be
3175 * Returns: Number of bytes required for refcount blocks and table metadata.
3177 int64_t qcow2_refcount_metadata_size(int64_t clusters, size_t cluster_size,
3178 int refcount_order, bool generous_increase,
3179 uint64_t *refblock_count)
3182 * Every host cluster is reference-counted, including metadata (even
3183 * refcount metadata is recursively included).
3185 * An accurate formula for the size of refcount metadata size is difficult
3186 * to derive. An easier method of calculation is finding the fixed point
3187 * where no further refcount blocks or table clusters are required to
3188 * reference count every cluster.
3190 int64_t blocks_per_table_cluster = cluster_size / sizeof(uint64_t);
3191 int64_t refcounts_per_block = cluster_size * 8 / (1 << refcount_order);
3192 int64_t table = 0; /* number of refcount table clusters */
3193 int64_t blocks = 0; /* number of refcount block clusters */
3194 int64_t last;
3195 int64_t n = 0;
3197 do {
3198 last = n;
3199 blocks = DIV_ROUND_UP(clusters + table + blocks, refcounts_per_block);
3200 table = DIV_ROUND_UP(blocks, blocks_per_table_cluster);
3201 n = clusters + blocks + table;
3203 if (n == last && generous_increase) {
3204 clusters += DIV_ROUND_UP(table, 2);
3205 n = 0; /* force another loop */
3206 generous_increase = false;
3208 } while (n != last);
3210 if (refblock_count) {
3211 *refblock_count = blocks;
3214 return (blocks + table) * cluster_size;
3218 * qcow2_calc_prealloc_size:
3219 * @total_size: virtual disk size in bytes
3220 * @cluster_size: cluster size in bytes
3221 * @refcount_order: refcount bits power-of-2 exponent
3223 * Returns: Total number of bytes required for the fully allocated image
3224 * (including metadata).
3226 static int64_t qcow2_calc_prealloc_size(int64_t total_size,
3227 size_t cluster_size,
3228 int refcount_order)
3230 int64_t meta_size = 0;
3231 uint64_t nl1e, nl2e;
3232 int64_t aligned_total_size = ROUND_UP(total_size, cluster_size);
3234 /* header: 1 cluster */
3235 meta_size += cluster_size;
3237 /* total size of L2 tables */
3238 nl2e = aligned_total_size / cluster_size;
3239 nl2e = ROUND_UP(nl2e, cluster_size / sizeof(uint64_t));
3240 meta_size += nl2e * sizeof(uint64_t);
3242 /* total size of L1 tables */
3243 nl1e = nl2e * sizeof(uint64_t) / cluster_size;
3244 nl1e = ROUND_UP(nl1e, cluster_size / sizeof(uint64_t));
3245 meta_size += nl1e * sizeof(uint64_t);
3247 /* total size of refcount table and blocks */
3248 meta_size += qcow2_refcount_metadata_size(
3249 (meta_size + aligned_total_size) / cluster_size,
3250 cluster_size, refcount_order, false, NULL);
3252 return meta_size + aligned_total_size;
3255 static bool validate_cluster_size(size_t cluster_size, Error **errp)
3257 int cluster_bits = ctz32(cluster_size);
3258 if (cluster_bits < MIN_CLUSTER_BITS || cluster_bits > MAX_CLUSTER_BITS ||
3259 (1 << cluster_bits) != cluster_size)
3261 error_setg(errp, "Cluster size must be a power of two between %d and "
3262 "%dk", 1 << MIN_CLUSTER_BITS, 1 << (MAX_CLUSTER_BITS - 10));
3263 return false;
3265 return true;
3268 static size_t qcow2_opt_get_cluster_size_del(QemuOpts *opts, Error **errp)
3270 size_t cluster_size;
3272 cluster_size = qemu_opt_get_size_del(opts, BLOCK_OPT_CLUSTER_SIZE,
3273 DEFAULT_CLUSTER_SIZE);
3274 if (!validate_cluster_size(cluster_size, errp)) {
3275 return 0;
3277 return cluster_size;
3280 static int qcow2_opt_get_version_del(QemuOpts *opts, Error **errp)
3282 char *buf;
3283 int ret;
3285 buf = qemu_opt_get_del(opts, BLOCK_OPT_COMPAT_LEVEL);
3286 if (!buf) {
3287 ret = 3; /* default */
3288 } else if (!strcmp(buf, "0.10")) {
3289 ret = 2;
3290 } else if (!strcmp(buf, "1.1")) {
3291 ret = 3;
3292 } else {
3293 error_setg(errp, "Invalid compatibility level: '%s'", buf);
3294 ret = -EINVAL;
3296 g_free(buf);
3297 return ret;
3300 static uint64_t qcow2_opt_get_refcount_bits_del(QemuOpts *opts, int version,
3301 Error **errp)
3303 uint64_t refcount_bits;
3305 refcount_bits = qemu_opt_get_number_del(opts, BLOCK_OPT_REFCOUNT_BITS, 16);
3306 if (refcount_bits > 64 || !is_power_of_2(refcount_bits)) {
3307 error_setg(errp, "Refcount width must be a power of two and may not "
3308 "exceed 64 bits");
3309 return 0;
3312 if (version < 3 && refcount_bits != 16) {
3313 error_setg(errp, "Different refcount widths than 16 bits require "
3314 "compatibility level 1.1 or above (use compat=1.1 or "
3315 "greater)");
3316 return 0;
3319 return refcount_bits;
3322 static int coroutine_fn
3323 qcow2_co_create(BlockdevCreateOptions *create_options, Error **errp)
3325 BlockdevCreateOptionsQcow2 *qcow2_opts;
3326 QDict *options;
3329 * Open the image file and write a minimal qcow2 header.
3331 * We keep things simple and start with a zero-sized image. We also
3332 * do without refcount blocks or a L1 table for now. We'll fix the
3333 * inconsistency later.
3335 * We do need a refcount table because growing the refcount table means
3336 * allocating two new refcount blocks - the second of which would be at
3337 * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
3338 * size for any qcow2 image.
3340 BlockBackend *blk = NULL;
3341 BlockDriverState *bs = NULL;
3342 BlockDriverState *data_bs = NULL;
3343 QCowHeader *header;
3344 size_t cluster_size;
3345 int version;
3346 int refcount_order;
3347 uint64_t* refcount_table;
3348 Error *local_err = NULL;
3349 int ret;
3350 uint8_t compression_type = QCOW2_COMPRESSION_TYPE_ZLIB;
3352 assert(create_options->driver == BLOCKDEV_DRIVER_QCOW2);
3353 qcow2_opts = &create_options->u.qcow2;
3355 bs = bdrv_open_blockdev_ref(qcow2_opts->file, errp);
3356 if (bs == NULL) {
3357 return -EIO;
3360 /* Validate options and set default values */
3361 if (!QEMU_IS_ALIGNED(qcow2_opts->size, BDRV_SECTOR_SIZE)) {
3362 error_setg(errp, "Image size must be a multiple of %u bytes",
3363 (unsigned) BDRV_SECTOR_SIZE);
3364 ret = -EINVAL;
3365 goto out;
3368 if (qcow2_opts->has_version) {
3369 switch (qcow2_opts->version) {
3370 case BLOCKDEV_QCOW2_VERSION_V2:
3371 version = 2;
3372 break;
3373 case BLOCKDEV_QCOW2_VERSION_V3:
3374 version = 3;
3375 break;
3376 default:
3377 g_assert_not_reached();
3379 } else {
3380 version = 3;
3383 if (qcow2_opts->has_cluster_size) {
3384 cluster_size = qcow2_opts->cluster_size;
3385 } else {
3386 cluster_size = DEFAULT_CLUSTER_SIZE;
3389 if (!validate_cluster_size(cluster_size, errp)) {
3390 ret = -EINVAL;
3391 goto out;
3394 if (!qcow2_opts->has_preallocation) {
3395 qcow2_opts->preallocation = PREALLOC_MODE_OFF;
3397 if (qcow2_opts->has_backing_file &&
3398 qcow2_opts->preallocation != PREALLOC_MODE_OFF)
3400 error_setg(errp, "Backing file and preallocation cannot be used at "
3401 "the same time");
3402 ret = -EINVAL;
3403 goto out;
3405 if (qcow2_opts->has_backing_fmt && !qcow2_opts->has_backing_file) {
3406 error_setg(errp, "Backing format cannot be used without backing file");
3407 ret = -EINVAL;
3408 goto out;
3411 if (!qcow2_opts->has_lazy_refcounts) {
3412 qcow2_opts->lazy_refcounts = false;
3414 if (version < 3 && qcow2_opts->lazy_refcounts) {
3415 error_setg(errp, "Lazy refcounts only supported with compatibility "
3416 "level 1.1 and above (use version=v3 or greater)");
3417 ret = -EINVAL;
3418 goto out;
3421 if (!qcow2_opts->has_refcount_bits) {
3422 qcow2_opts->refcount_bits = 16;
3424 if (qcow2_opts->refcount_bits > 64 ||
3425 !is_power_of_2(qcow2_opts->refcount_bits))
3427 error_setg(errp, "Refcount width must be a power of two and may not "
3428 "exceed 64 bits");
3429 ret = -EINVAL;
3430 goto out;
3432 if (version < 3 && qcow2_opts->refcount_bits != 16) {
3433 error_setg(errp, "Different refcount widths than 16 bits require "
3434 "compatibility level 1.1 or above (use version=v3 or "
3435 "greater)");
3436 ret = -EINVAL;
3437 goto out;
3439 refcount_order = ctz32(qcow2_opts->refcount_bits);
3441 if (qcow2_opts->data_file_raw && !qcow2_opts->data_file) {
3442 error_setg(errp, "data-file-raw requires data-file");
3443 ret = -EINVAL;
3444 goto out;
3446 if (qcow2_opts->data_file_raw && qcow2_opts->has_backing_file) {
3447 error_setg(errp, "Backing file and data-file-raw cannot be used at "
3448 "the same time");
3449 ret = -EINVAL;
3450 goto out;
3453 if (qcow2_opts->data_file) {
3454 if (version < 3) {
3455 error_setg(errp, "External data files are only supported with "
3456 "compatibility level 1.1 and above (use version=v3 or "
3457 "greater)");
3458 ret = -EINVAL;
3459 goto out;
3461 data_bs = bdrv_open_blockdev_ref(qcow2_opts->data_file, errp);
3462 if (data_bs == NULL) {
3463 ret = -EIO;
3464 goto out;
3468 if (qcow2_opts->has_compression_type &&
3469 qcow2_opts->compression_type != QCOW2_COMPRESSION_TYPE_ZLIB) {
3471 ret = -EINVAL;
3473 if (version < 3) {
3474 error_setg(errp, "Non-zlib compression type is only supported with "
3475 "compatibility level 1.1 and above (use version=v3 or "
3476 "greater)");
3477 goto out;
3480 switch (qcow2_opts->compression_type) {
3481 #ifdef CONFIG_ZSTD
3482 case QCOW2_COMPRESSION_TYPE_ZSTD:
3483 break;
3484 #endif
3485 default:
3486 error_setg(errp, "Unknown compression type");
3487 goto out;
3490 compression_type = qcow2_opts->compression_type;
3493 /* Create BlockBackend to write to the image */
3494 blk = blk_new_with_bs(bs, BLK_PERM_WRITE | BLK_PERM_RESIZE, BLK_PERM_ALL,
3495 errp);
3496 if (!blk) {
3497 ret = -EPERM;
3498 goto out;
3500 blk_set_allow_write_beyond_eof(blk, true);
3502 /* Write the header */
3503 QEMU_BUILD_BUG_ON((1 << MIN_CLUSTER_BITS) < sizeof(*header));
3504 header = g_malloc0(cluster_size);
3505 *header = (QCowHeader) {
3506 .magic = cpu_to_be32(QCOW_MAGIC),
3507 .version = cpu_to_be32(version),
3508 .cluster_bits = cpu_to_be32(ctz32(cluster_size)),
3509 .size = cpu_to_be64(0),
3510 .l1_table_offset = cpu_to_be64(0),
3511 .l1_size = cpu_to_be32(0),
3512 .refcount_table_offset = cpu_to_be64(cluster_size),
3513 .refcount_table_clusters = cpu_to_be32(1),
3514 .refcount_order = cpu_to_be32(refcount_order),
3515 /* don't deal with endianness since compression_type is 1 byte long */
3516 .compression_type = compression_type,
3517 .header_length = cpu_to_be32(sizeof(*header)),
3520 /* We'll update this to correct value later */
3521 header->crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
3523 if (qcow2_opts->lazy_refcounts) {
3524 header->compatible_features |=
3525 cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS);
3527 if (data_bs) {
3528 header->incompatible_features |=
3529 cpu_to_be64(QCOW2_INCOMPAT_DATA_FILE);
3531 if (qcow2_opts->data_file_raw) {
3532 header->autoclear_features |=
3533 cpu_to_be64(QCOW2_AUTOCLEAR_DATA_FILE_RAW);
3535 if (compression_type != QCOW2_COMPRESSION_TYPE_ZLIB) {
3536 header->incompatible_features |=
3537 cpu_to_be64(QCOW2_INCOMPAT_COMPRESSION);
3540 ret = blk_pwrite(blk, 0, header, cluster_size, 0);
3541 g_free(header);
3542 if (ret < 0) {
3543 error_setg_errno(errp, -ret, "Could not write qcow2 header");
3544 goto out;
3547 /* Write a refcount table with one refcount block */
3548 refcount_table = g_malloc0(2 * cluster_size);
3549 refcount_table[0] = cpu_to_be64(2 * cluster_size);
3550 ret = blk_pwrite(blk, cluster_size, refcount_table, 2 * cluster_size, 0);
3551 g_free(refcount_table);
3553 if (ret < 0) {
3554 error_setg_errno(errp, -ret, "Could not write refcount table");
3555 goto out;
3558 blk_unref(blk);
3559 blk = NULL;
3562 * And now open the image and make it consistent first (i.e. increase the
3563 * refcount of the cluster that is occupied by the header and the refcount
3564 * table)
3566 options = qdict_new();
3567 qdict_put_str(options, "driver", "qcow2");
3568 qdict_put_str(options, "file", bs->node_name);
3569 if (data_bs) {
3570 qdict_put_str(options, "data-file", data_bs->node_name);
3572 blk = blk_new_open(NULL, NULL, options,
3573 BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_NO_FLUSH,
3574 &local_err);
3575 if (blk == NULL) {
3576 error_propagate(errp, local_err);
3577 ret = -EIO;
3578 goto out;
3581 ret = qcow2_alloc_clusters(blk_bs(blk), 3 * cluster_size);
3582 if (ret < 0) {
3583 error_setg_errno(errp, -ret, "Could not allocate clusters for qcow2 "
3584 "header and refcount table");
3585 goto out;
3587 } else if (ret != 0) {
3588 error_report("Huh, first cluster in empty image is already in use?");
3589 abort();
3592 /* Set the external data file if necessary */
3593 if (data_bs) {
3594 BDRVQcow2State *s = blk_bs(blk)->opaque;
3595 s->image_data_file = g_strdup(data_bs->filename);
3598 /* Create a full header (including things like feature table) */
3599 ret = qcow2_update_header(blk_bs(blk));
3600 if (ret < 0) {
3601 error_setg_errno(errp, -ret, "Could not update qcow2 header");
3602 goto out;
3605 /* Okay, now that we have a valid image, let's give it the right size */
3606 ret = blk_truncate(blk, qcow2_opts->size, false, qcow2_opts->preallocation,
3607 0, errp);
3608 if (ret < 0) {
3609 error_prepend(errp, "Could not resize image: ");
3610 goto out;
3613 /* Want a backing file? There you go. */
3614 if (qcow2_opts->has_backing_file) {
3615 const char *backing_format = NULL;
3617 if (qcow2_opts->has_backing_fmt) {
3618 backing_format = BlockdevDriver_str(qcow2_opts->backing_fmt);
3621 ret = bdrv_change_backing_file(blk_bs(blk), qcow2_opts->backing_file,
3622 backing_format);
3623 if (ret < 0) {
3624 error_setg_errno(errp, -ret, "Could not assign backing file '%s' "
3625 "with format '%s'", qcow2_opts->backing_file,
3626 backing_format);
3627 goto out;
3631 /* Want encryption? There you go. */
3632 if (qcow2_opts->has_encrypt) {
3633 ret = qcow2_set_up_encryption(blk_bs(blk), qcow2_opts->encrypt, errp);
3634 if (ret < 0) {
3635 goto out;
3639 blk_unref(blk);
3640 blk = NULL;
3642 /* Reopen the image without BDRV_O_NO_FLUSH to flush it before returning.
3643 * Using BDRV_O_NO_IO, since encryption is now setup we don't want to
3644 * have to setup decryption context. We're not doing any I/O on the top
3645 * level BlockDriverState, only lower layers, where BDRV_O_NO_IO does
3646 * not have effect.
3648 options = qdict_new();
3649 qdict_put_str(options, "driver", "qcow2");
3650 qdict_put_str(options, "file", bs->node_name);
3651 if (data_bs) {
3652 qdict_put_str(options, "data-file", data_bs->node_name);
3654 blk = blk_new_open(NULL, NULL, options,
3655 BDRV_O_RDWR | BDRV_O_NO_BACKING | BDRV_O_NO_IO,
3656 &local_err);
3657 if (blk == NULL) {
3658 error_propagate(errp, local_err);
3659 ret = -EIO;
3660 goto out;
3663 ret = 0;
3664 out:
3665 blk_unref(blk);
3666 bdrv_unref(bs);
3667 bdrv_unref(data_bs);
3668 return ret;
3671 static int coroutine_fn qcow2_co_create_opts(BlockDriver *drv,
3672 const char *filename,
3673 QemuOpts *opts,
3674 Error **errp)
3676 BlockdevCreateOptions *create_options = NULL;
3677 QDict *qdict;
3678 Visitor *v;
3679 BlockDriverState *bs = NULL;
3680 BlockDriverState *data_bs = NULL;
3681 Error *local_err = NULL;
3682 const char *val;
3683 int ret;
3685 /* Only the keyval visitor supports the dotted syntax needed for
3686 * encryption, so go through a QDict before getting a QAPI type. Ignore
3687 * options meant for the protocol layer so that the visitor doesn't
3688 * complain. */
3689 qdict = qemu_opts_to_qdict_filtered(opts, NULL, bdrv_qcow2.create_opts,
3690 true);
3692 /* Handle encryption options */
3693 val = qdict_get_try_str(qdict, BLOCK_OPT_ENCRYPT);
3694 if (val && !strcmp(val, "on")) {
3695 qdict_put_str(qdict, BLOCK_OPT_ENCRYPT, "qcow");
3696 } else if (val && !strcmp(val, "off")) {
3697 qdict_del(qdict, BLOCK_OPT_ENCRYPT);
3700 val = qdict_get_try_str(qdict, BLOCK_OPT_ENCRYPT_FORMAT);
3701 if (val && !strcmp(val, "aes")) {
3702 qdict_put_str(qdict, BLOCK_OPT_ENCRYPT_FORMAT, "qcow");
3705 /* Convert compat=0.10/1.1 into compat=v2/v3, to be renamed into
3706 * version=v2/v3 below. */
3707 val = qdict_get_try_str(qdict, BLOCK_OPT_COMPAT_LEVEL);
3708 if (val && !strcmp(val, "0.10")) {
3709 qdict_put_str(qdict, BLOCK_OPT_COMPAT_LEVEL, "v2");
3710 } else if (val && !strcmp(val, "1.1")) {
3711 qdict_put_str(qdict, BLOCK_OPT_COMPAT_LEVEL, "v3");
3714 /* Change legacy command line options into QMP ones */
3715 static const QDictRenames opt_renames[] = {
3716 { BLOCK_OPT_BACKING_FILE, "backing-file" },
3717 { BLOCK_OPT_BACKING_FMT, "backing-fmt" },
3718 { BLOCK_OPT_CLUSTER_SIZE, "cluster-size" },
3719 { BLOCK_OPT_LAZY_REFCOUNTS, "lazy-refcounts" },
3720 { BLOCK_OPT_REFCOUNT_BITS, "refcount-bits" },
3721 { BLOCK_OPT_ENCRYPT, BLOCK_OPT_ENCRYPT_FORMAT },
3722 { BLOCK_OPT_COMPAT_LEVEL, "version" },
3723 { BLOCK_OPT_DATA_FILE_RAW, "data-file-raw" },
3724 { BLOCK_OPT_COMPRESSION_TYPE, "compression-type" },
3725 { NULL, NULL },
3728 if (!qdict_rename_keys(qdict, opt_renames, errp)) {
3729 ret = -EINVAL;
3730 goto finish;
3733 /* Create and open the file (protocol layer) */
3734 ret = bdrv_create_file(filename, opts, errp);
3735 if (ret < 0) {
3736 goto finish;
3739 bs = bdrv_open(filename, NULL, NULL,
3740 BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_PROTOCOL, errp);
3741 if (bs == NULL) {
3742 ret = -EIO;
3743 goto finish;
3746 /* Create and open an external data file (protocol layer) */
3747 val = qdict_get_try_str(qdict, BLOCK_OPT_DATA_FILE);
3748 if (val) {
3749 ret = bdrv_create_file(val, opts, errp);
3750 if (ret < 0) {
3751 goto finish;
3754 data_bs = bdrv_open(val, NULL, NULL,
3755 BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_PROTOCOL,
3756 errp);
3757 if (data_bs == NULL) {
3758 ret = -EIO;
3759 goto finish;
3762 qdict_del(qdict, BLOCK_OPT_DATA_FILE);
3763 qdict_put_str(qdict, "data-file", data_bs->node_name);
3766 /* Set 'driver' and 'node' options */
3767 qdict_put_str(qdict, "driver", "qcow2");
3768 qdict_put_str(qdict, "file", bs->node_name);
3770 /* Now get the QAPI type BlockdevCreateOptions */
3771 v = qobject_input_visitor_new_flat_confused(qdict, errp);
3772 if (!v) {
3773 ret = -EINVAL;
3774 goto finish;
3777 visit_type_BlockdevCreateOptions(v, NULL, &create_options, &local_err);
3778 visit_free(v);
3780 if (local_err) {
3781 error_propagate(errp, local_err);
3782 ret = -EINVAL;
3783 goto finish;
3786 /* Silently round up size */
3787 create_options->u.qcow2.size = ROUND_UP(create_options->u.qcow2.size,
3788 BDRV_SECTOR_SIZE);
3790 /* Create the qcow2 image (format layer) */
3791 ret = qcow2_co_create(create_options, errp);
3792 if (ret < 0) {
3793 goto finish;
3796 ret = 0;
3797 finish:
3798 qobject_unref(qdict);
3799 bdrv_unref(bs);
3800 bdrv_unref(data_bs);
3801 qapi_free_BlockdevCreateOptions(create_options);
3802 return ret;
3806 static bool is_zero(BlockDriverState *bs, int64_t offset, int64_t bytes)
3808 int64_t nr;
3809 int res;
3811 /* Clamp to image length, before checking status of underlying sectors */
3812 if (offset + bytes > bs->total_sectors * BDRV_SECTOR_SIZE) {
3813 bytes = bs->total_sectors * BDRV_SECTOR_SIZE - offset;
3816 if (!bytes) {
3817 return true;
3819 res = bdrv_block_status_above(bs, NULL, offset, bytes, &nr, NULL, NULL);
3820 return res >= 0 && (res & BDRV_BLOCK_ZERO) && nr == bytes;
3823 static coroutine_fn int qcow2_co_pwrite_zeroes(BlockDriverState *bs,
3824 int64_t offset, int bytes, BdrvRequestFlags flags)
3826 int ret;
3827 BDRVQcow2State *s = bs->opaque;
3829 uint32_t head = offset % s->cluster_size;
3830 uint32_t tail = (offset + bytes) % s->cluster_size;
3832 trace_qcow2_pwrite_zeroes_start_req(qemu_coroutine_self(), offset, bytes);
3833 if (offset + bytes == bs->total_sectors * BDRV_SECTOR_SIZE) {
3834 tail = 0;
3837 if (head || tail) {
3838 uint64_t off;
3839 unsigned int nr;
3841 assert(head + bytes <= s->cluster_size);
3843 /* check whether remainder of cluster already reads as zero */
3844 if (!(is_zero(bs, offset - head, head) &&
3845 is_zero(bs, offset + bytes,
3846 tail ? s->cluster_size - tail : 0))) {
3847 return -ENOTSUP;
3850 qemu_co_mutex_lock(&s->lock);
3851 /* We can have new write after previous check */
3852 offset = QEMU_ALIGN_DOWN(offset, s->cluster_size);
3853 bytes = s->cluster_size;
3854 nr = s->cluster_size;
3855 ret = qcow2_get_cluster_offset(bs, offset, &nr, &off);
3856 if (ret != QCOW2_CLUSTER_UNALLOCATED &&
3857 ret != QCOW2_CLUSTER_ZERO_PLAIN &&
3858 ret != QCOW2_CLUSTER_ZERO_ALLOC) {
3859 qemu_co_mutex_unlock(&s->lock);
3860 return -ENOTSUP;
3862 } else {
3863 qemu_co_mutex_lock(&s->lock);
3866 trace_qcow2_pwrite_zeroes(qemu_coroutine_self(), offset, bytes);
3868 /* Whatever is left can use real zero clusters */
3869 ret = qcow2_cluster_zeroize(bs, offset, bytes, flags);
3870 qemu_co_mutex_unlock(&s->lock);
3872 return ret;
3875 static coroutine_fn int qcow2_co_pdiscard(BlockDriverState *bs,
3876 int64_t offset, int bytes)
3878 int ret;
3879 BDRVQcow2State *s = bs->opaque;
3881 /* If the image does not support QCOW_OFLAG_ZERO then discarding
3882 * clusters could expose stale data from the backing file. */
3883 if (s->qcow_version < 3 && bs->backing) {
3884 return -ENOTSUP;
3887 if (!QEMU_IS_ALIGNED(offset | bytes, s->cluster_size)) {
3888 assert(bytes < s->cluster_size);
3889 /* Ignore partial clusters, except for the special case of the
3890 * complete partial cluster at the end of an unaligned file */
3891 if (!QEMU_IS_ALIGNED(offset, s->cluster_size) ||
3892 offset + bytes != bs->total_sectors * BDRV_SECTOR_SIZE) {
3893 return -ENOTSUP;
3897 qemu_co_mutex_lock(&s->lock);
3898 ret = qcow2_cluster_discard(bs, offset, bytes, QCOW2_DISCARD_REQUEST,
3899 false);
3900 qemu_co_mutex_unlock(&s->lock);
3901 return ret;
3904 static int coroutine_fn
3905 qcow2_co_copy_range_from(BlockDriverState *bs,
3906 BdrvChild *src, uint64_t src_offset,
3907 BdrvChild *dst, uint64_t dst_offset,
3908 uint64_t bytes, BdrvRequestFlags read_flags,
3909 BdrvRequestFlags write_flags)
3911 BDRVQcow2State *s = bs->opaque;
3912 int ret;
3913 unsigned int cur_bytes; /* number of bytes in current iteration */
3914 BdrvChild *child = NULL;
3915 BdrvRequestFlags cur_write_flags;
3917 assert(!bs->encrypted);
3918 qemu_co_mutex_lock(&s->lock);
3920 while (bytes != 0) {
3921 uint64_t copy_offset = 0;
3922 /* prepare next request */
3923 cur_bytes = MIN(bytes, INT_MAX);
3924 cur_write_flags = write_flags;
3926 ret = qcow2_get_cluster_offset(bs, src_offset, &cur_bytes, &copy_offset);
3927 if (ret < 0) {
3928 goto out;
3931 switch (ret) {
3932 case QCOW2_CLUSTER_UNALLOCATED:
3933 if (bs->backing && bs->backing->bs) {
3934 int64_t backing_length = bdrv_getlength(bs->backing->bs);
3935 if (src_offset >= backing_length) {
3936 cur_write_flags |= BDRV_REQ_ZERO_WRITE;
3937 } else {
3938 child = bs->backing;
3939 cur_bytes = MIN(cur_bytes, backing_length - src_offset);
3940 copy_offset = src_offset;
3942 } else {
3943 cur_write_flags |= BDRV_REQ_ZERO_WRITE;
3945 break;
3947 case QCOW2_CLUSTER_ZERO_PLAIN:
3948 case QCOW2_CLUSTER_ZERO_ALLOC:
3949 cur_write_flags |= BDRV_REQ_ZERO_WRITE;
3950 break;
3952 case QCOW2_CLUSTER_COMPRESSED:
3953 ret = -ENOTSUP;
3954 goto out;
3956 case QCOW2_CLUSTER_NORMAL:
3957 child = s->data_file;
3958 copy_offset += offset_into_cluster(s, src_offset);
3959 break;
3961 default:
3962 abort();
3964 qemu_co_mutex_unlock(&s->lock);
3965 ret = bdrv_co_copy_range_from(child,
3966 copy_offset,
3967 dst, dst_offset,
3968 cur_bytes, read_flags, cur_write_flags);
3969 qemu_co_mutex_lock(&s->lock);
3970 if (ret < 0) {
3971 goto out;
3974 bytes -= cur_bytes;
3975 src_offset += cur_bytes;
3976 dst_offset += cur_bytes;
3978 ret = 0;
3980 out:
3981 qemu_co_mutex_unlock(&s->lock);
3982 return ret;
3985 static int coroutine_fn
3986 qcow2_co_copy_range_to(BlockDriverState *bs,
3987 BdrvChild *src, uint64_t src_offset,
3988 BdrvChild *dst, uint64_t dst_offset,
3989 uint64_t bytes, BdrvRequestFlags read_flags,
3990 BdrvRequestFlags write_flags)
3992 BDRVQcow2State *s = bs->opaque;
3993 int offset_in_cluster;
3994 int ret;
3995 unsigned int cur_bytes; /* number of sectors in current iteration */
3996 uint64_t cluster_offset;
3997 QCowL2Meta *l2meta = NULL;
3999 assert(!bs->encrypted);
4001 qemu_co_mutex_lock(&s->lock);
4003 while (bytes != 0) {
4005 l2meta = NULL;
4007 offset_in_cluster = offset_into_cluster(s, dst_offset);
4008 cur_bytes = MIN(bytes, INT_MAX);
4010 /* TODO:
4011 * If src->bs == dst->bs, we could simply copy by incrementing
4012 * the refcnt, without copying user data.
4013 * Or if src->bs == dst->bs->backing->bs, we could copy by discarding. */
4014 ret = qcow2_alloc_cluster_offset(bs, dst_offset, &cur_bytes,
4015 &cluster_offset, &l2meta);
4016 if (ret < 0) {
4017 goto fail;
4020 assert(offset_into_cluster(s, cluster_offset) == 0);
4022 ret = qcow2_pre_write_overlap_check(bs, 0,
4023 cluster_offset + offset_in_cluster, cur_bytes, true);
4024 if (ret < 0) {
4025 goto fail;
4028 qemu_co_mutex_unlock(&s->lock);
4029 ret = bdrv_co_copy_range_to(src, src_offset,
4030 s->data_file,
4031 cluster_offset + offset_in_cluster,
4032 cur_bytes, read_flags, write_flags);
4033 qemu_co_mutex_lock(&s->lock);
4034 if (ret < 0) {
4035 goto fail;
4038 ret = qcow2_handle_l2meta(bs, &l2meta, true);
4039 if (ret) {
4040 goto fail;
4043 bytes -= cur_bytes;
4044 src_offset += cur_bytes;
4045 dst_offset += cur_bytes;
4047 ret = 0;
4049 fail:
4050 qcow2_handle_l2meta(bs, &l2meta, false);
4052 qemu_co_mutex_unlock(&s->lock);
4054 trace_qcow2_writev_done_req(qemu_coroutine_self(), ret);
4056 return ret;
4059 static int coroutine_fn qcow2_co_truncate(BlockDriverState *bs, int64_t offset,
4060 bool exact, PreallocMode prealloc,
4061 BdrvRequestFlags flags, Error **errp)
4063 BDRVQcow2State *s = bs->opaque;
4064 uint64_t old_length;
4065 int64_t new_l1_size;
4066 int ret;
4067 QDict *options;
4069 if (prealloc != PREALLOC_MODE_OFF && prealloc != PREALLOC_MODE_METADATA &&
4070 prealloc != PREALLOC_MODE_FALLOC && prealloc != PREALLOC_MODE_FULL)
4072 error_setg(errp, "Unsupported preallocation mode '%s'",
4073 PreallocMode_str(prealloc));
4074 return -ENOTSUP;
4077 if (!QEMU_IS_ALIGNED(offset, BDRV_SECTOR_SIZE)) {
4078 error_setg(errp, "The new size must be a multiple of %u",
4079 (unsigned) BDRV_SECTOR_SIZE);
4080 return -EINVAL;
4083 qemu_co_mutex_lock(&s->lock);
4086 * Even though we store snapshot size for all images, it was not
4087 * required until v3, so it is not safe to proceed for v2.
4089 if (s->nb_snapshots && s->qcow_version < 3) {
4090 error_setg(errp, "Can't resize a v2 image which has snapshots");
4091 ret = -ENOTSUP;
4092 goto fail;
4095 /* See qcow2-bitmap.c for which bitmap scenarios prevent a resize. */
4096 if (qcow2_truncate_bitmaps_check(bs, errp)) {
4097 ret = -ENOTSUP;
4098 goto fail;
4101 old_length = bs->total_sectors * BDRV_SECTOR_SIZE;
4102 new_l1_size = size_to_l1(s, offset);
4104 if (offset < old_length) {
4105 int64_t last_cluster, old_file_size;
4106 if (prealloc != PREALLOC_MODE_OFF) {
4107 error_setg(errp,
4108 "Preallocation can't be used for shrinking an image");
4109 ret = -EINVAL;
4110 goto fail;
4113 ret = qcow2_cluster_discard(bs, ROUND_UP(offset, s->cluster_size),
4114 old_length - ROUND_UP(offset,
4115 s->cluster_size),
4116 QCOW2_DISCARD_ALWAYS, true);
4117 if (ret < 0) {
4118 error_setg_errno(errp, -ret, "Failed to discard cropped clusters");
4119 goto fail;
4122 ret = qcow2_shrink_l1_table(bs, new_l1_size);
4123 if (ret < 0) {
4124 error_setg_errno(errp, -ret,
4125 "Failed to reduce the number of L2 tables");
4126 goto fail;
4129 ret = qcow2_shrink_reftable(bs);
4130 if (ret < 0) {
4131 error_setg_errno(errp, -ret,
4132 "Failed to discard unused refblocks");
4133 goto fail;
4136 old_file_size = bdrv_getlength(bs->file->bs);
4137 if (old_file_size < 0) {
4138 error_setg_errno(errp, -old_file_size,
4139 "Failed to inquire current file length");
4140 ret = old_file_size;
4141 goto fail;
4143 last_cluster = qcow2_get_last_cluster(bs, old_file_size);
4144 if (last_cluster < 0) {
4145 error_setg_errno(errp, -last_cluster,
4146 "Failed to find the last cluster");
4147 ret = last_cluster;
4148 goto fail;
4150 if ((last_cluster + 1) * s->cluster_size < old_file_size) {
4151 Error *local_err = NULL;
4154 * Do not pass @exact here: It will not help the user if
4155 * we get an error here just because they wanted to shrink
4156 * their qcow2 image (on a block device) with qemu-img.
4157 * (And on the qcow2 layer, the @exact requirement is
4158 * always fulfilled, so there is no need to pass it on.)
4160 bdrv_co_truncate(bs->file, (last_cluster + 1) * s->cluster_size,
4161 false, PREALLOC_MODE_OFF, 0, &local_err);
4162 if (local_err) {
4163 warn_reportf_err(local_err,
4164 "Failed to truncate the tail of the image: ");
4167 } else {
4168 ret = qcow2_grow_l1_table(bs, new_l1_size, true);
4169 if (ret < 0) {
4170 error_setg_errno(errp, -ret, "Failed to grow the L1 table");
4171 goto fail;
4175 switch (prealloc) {
4176 case PREALLOC_MODE_OFF:
4177 if (has_data_file(bs)) {
4179 * If the caller wants an exact resize, the external data
4180 * file should be resized to the exact target size, too,
4181 * so we pass @exact here.
4183 ret = bdrv_co_truncate(s->data_file, offset, exact, prealloc, 0,
4184 errp);
4185 if (ret < 0) {
4186 goto fail;
4189 break;
4191 case PREALLOC_MODE_METADATA:
4192 ret = preallocate_co(bs, old_length, offset, prealloc, errp);
4193 if (ret < 0) {
4194 goto fail;
4196 break;
4198 case PREALLOC_MODE_FALLOC:
4199 case PREALLOC_MODE_FULL:
4201 int64_t allocation_start, host_offset, guest_offset;
4202 int64_t clusters_allocated;
4203 int64_t old_file_size, last_cluster, new_file_size;
4204 uint64_t nb_new_data_clusters, nb_new_l2_tables;
4206 /* With a data file, preallocation means just allocating the metadata
4207 * and forwarding the truncate request to the data file */
4208 if (has_data_file(bs)) {
4209 ret = preallocate_co(bs, old_length, offset, prealloc, errp);
4210 if (ret < 0) {
4211 goto fail;
4213 break;
4216 old_file_size = bdrv_getlength(bs->file->bs);
4217 if (old_file_size < 0) {
4218 error_setg_errno(errp, -old_file_size,
4219 "Failed to inquire current file length");
4220 ret = old_file_size;
4221 goto fail;
4224 last_cluster = qcow2_get_last_cluster(bs, old_file_size);
4225 if (last_cluster >= 0) {
4226 old_file_size = (last_cluster + 1) * s->cluster_size;
4227 } else {
4228 old_file_size = ROUND_UP(old_file_size, s->cluster_size);
4231 nb_new_data_clusters = (ROUND_UP(offset, s->cluster_size) -
4232 start_of_cluster(s, old_length)) >> s->cluster_bits;
4234 /* This is an overestimation; we will not actually allocate space for
4235 * these in the file but just make sure the new refcount structures are
4236 * able to cover them so we will not have to allocate new refblocks
4237 * while entering the data blocks in the potentially new L2 tables.
4238 * (We do not actually care where the L2 tables are placed. Maybe they
4239 * are already allocated or they can be placed somewhere before
4240 * @old_file_size. It does not matter because they will be fully
4241 * allocated automatically, so they do not need to be covered by the
4242 * preallocation. All that matters is that we will not have to allocate
4243 * new refcount structures for them.) */
4244 nb_new_l2_tables = DIV_ROUND_UP(nb_new_data_clusters,
4245 s->cluster_size / sizeof(uint64_t));
4246 /* The cluster range may not be aligned to L2 boundaries, so add one L2
4247 * table for a potential head/tail */
4248 nb_new_l2_tables++;
4250 allocation_start = qcow2_refcount_area(bs, old_file_size,
4251 nb_new_data_clusters +
4252 nb_new_l2_tables,
4253 true, 0, 0);
4254 if (allocation_start < 0) {
4255 error_setg_errno(errp, -allocation_start,
4256 "Failed to resize refcount structures");
4257 ret = allocation_start;
4258 goto fail;
4261 clusters_allocated = qcow2_alloc_clusters_at(bs, allocation_start,
4262 nb_new_data_clusters);
4263 if (clusters_allocated < 0) {
4264 error_setg_errno(errp, -clusters_allocated,
4265 "Failed to allocate data clusters");
4266 ret = clusters_allocated;
4267 goto fail;
4270 assert(clusters_allocated == nb_new_data_clusters);
4272 /* Allocate the data area */
4273 new_file_size = allocation_start +
4274 nb_new_data_clusters * s->cluster_size;
4276 * Image file grows, so @exact does not matter.
4278 * If we need to zero out the new area, try first whether the protocol
4279 * driver can already take care of this.
4281 if (flags & BDRV_REQ_ZERO_WRITE) {
4282 ret = bdrv_co_truncate(bs->file, new_file_size, false, prealloc,
4283 BDRV_REQ_ZERO_WRITE, NULL);
4284 if (ret >= 0) {
4285 flags &= ~BDRV_REQ_ZERO_WRITE;
4287 } else {
4288 ret = -1;
4290 if (ret < 0) {
4291 ret = bdrv_co_truncate(bs->file, new_file_size, false, prealloc, 0,
4292 errp);
4294 if (ret < 0) {
4295 error_prepend(errp, "Failed to resize underlying file: ");
4296 qcow2_free_clusters(bs, allocation_start,
4297 nb_new_data_clusters * s->cluster_size,
4298 QCOW2_DISCARD_OTHER);
4299 goto fail;
4302 /* Create the necessary L2 entries */
4303 host_offset = allocation_start;
4304 guest_offset = old_length;
4305 while (nb_new_data_clusters) {
4306 int64_t nb_clusters = MIN(
4307 nb_new_data_clusters,
4308 s->l2_slice_size - offset_to_l2_slice_index(s, guest_offset));
4309 unsigned cow_start_length = offset_into_cluster(s, guest_offset);
4310 QCowL2Meta allocation;
4311 guest_offset = start_of_cluster(s, guest_offset);
4312 allocation = (QCowL2Meta) {
4313 .offset = guest_offset,
4314 .alloc_offset = host_offset,
4315 .nb_clusters = nb_clusters,
4316 .cow_start = {
4317 .offset = 0,
4318 .nb_bytes = cow_start_length,
4320 .cow_end = {
4321 .offset = nb_clusters << s->cluster_bits,
4322 .nb_bytes = 0,
4325 qemu_co_queue_init(&allocation.dependent_requests);
4327 ret = qcow2_alloc_cluster_link_l2(bs, &allocation);
4328 if (ret < 0) {
4329 error_setg_errno(errp, -ret, "Failed to update L2 tables");
4330 qcow2_free_clusters(bs, host_offset,
4331 nb_new_data_clusters * s->cluster_size,
4332 QCOW2_DISCARD_OTHER);
4333 goto fail;
4336 guest_offset += nb_clusters * s->cluster_size;
4337 host_offset += nb_clusters * s->cluster_size;
4338 nb_new_data_clusters -= nb_clusters;
4340 break;
4343 default:
4344 g_assert_not_reached();
4347 if ((flags & BDRV_REQ_ZERO_WRITE) && offset > old_length) {
4348 uint64_t zero_start = QEMU_ALIGN_UP(old_length, s->cluster_size);
4351 * Use zero clusters as much as we can. qcow2_cluster_zeroize()
4352 * requires a cluster-aligned start. The end may be unaligned if it is
4353 * at the end of the image (which it is here).
4355 if (offset > zero_start) {
4356 ret = qcow2_cluster_zeroize(bs, zero_start, offset - zero_start, 0);
4357 if (ret < 0) {
4358 error_setg_errno(errp, -ret, "Failed to zero out new clusters");
4359 goto fail;
4363 /* Write explicit zeros for the unaligned head */
4364 if (zero_start > old_length) {
4365 uint64_t len = MIN(zero_start, offset) - old_length;
4366 uint8_t *buf = qemu_blockalign0(bs, len);
4367 QEMUIOVector qiov;
4368 qemu_iovec_init_buf(&qiov, buf, len);
4370 qemu_co_mutex_unlock(&s->lock);
4371 ret = qcow2_co_pwritev_part(bs, old_length, len, &qiov, 0, 0);
4372 qemu_co_mutex_lock(&s->lock);
4374 qemu_vfree(buf);
4375 if (ret < 0) {
4376 error_setg_errno(errp, -ret, "Failed to zero out the new area");
4377 goto fail;
4382 if (prealloc != PREALLOC_MODE_OFF) {
4383 /* Flush metadata before actually changing the image size */
4384 ret = qcow2_write_caches(bs);
4385 if (ret < 0) {
4386 error_setg_errno(errp, -ret,
4387 "Failed to flush the preallocated area to disk");
4388 goto fail;
4392 bs->total_sectors = offset / BDRV_SECTOR_SIZE;
4394 /* write updated header.size */
4395 offset = cpu_to_be64(offset);
4396 ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, size),
4397 &offset, sizeof(uint64_t));
4398 if (ret < 0) {
4399 error_setg_errno(errp, -ret, "Failed to update the image size");
4400 goto fail;
4403 s->l1_vm_state_index = new_l1_size;
4405 /* Update cache sizes */
4406 options = qdict_clone_shallow(bs->options);
4407 ret = qcow2_update_options(bs, options, s->flags, errp);
4408 qobject_unref(options);
4409 if (ret < 0) {
4410 goto fail;
4412 ret = 0;
4413 fail:
4414 qemu_co_mutex_unlock(&s->lock);
4415 return ret;
4418 static coroutine_fn int
4419 qcow2_co_pwritev_compressed_task(BlockDriverState *bs,
4420 uint64_t offset, uint64_t bytes,
4421 QEMUIOVector *qiov, size_t qiov_offset)
4423 BDRVQcow2State *s = bs->opaque;
4424 int ret;
4425 ssize_t out_len;
4426 uint8_t *buf, *out_buf;
4427 uint64_t cluster_offset;
4429 assert(bytes == s->cluster_size || (bytes < s->cluster_size &&
4430 (offset + bytes == bs->total_sectors << BDRV_SECTOR_BITS)));
4432 buf = qemu_blockalign(bs, s->cluster_size);
4433 if (bytes < s->cluster_size) {
4434 /* Zero-pad last write if image size is not cluster aligned */
4435 memset(buf + bytes, 0, s->cluster_size - bytes);
4437 qemu_iovec_to_buf(qiov, qiov_offset, buf, bytes);
4439 out_buf = g_malloc(s->cluster_size);
4441 out_len = qcow2_co_compress(bs, out_buf, s->cluster_size - 1,
4442 buf, s->cluster_size);
4443 if (out_len == -ENOMEM) {
4444 /* could not compress: write normal cluster */
4445 ret = qcow2_co_pwritev_part(bs, offset, bytes, qiov, qiov_offset, 0);
4446 if (ret < 0) {
4447 goto fail;
4449 goto success;
4450 } else if (out_len < 0) {
4451 ret = -EINVAL;
4452 goto fail;
4455 qemu_co_mutex_lock(&s->lock);
4456 ret = qcow2_alloc_compressed_cluster_offset(bs, offset, out_len,
4457 &cluster_offset);
4458 if (ret < 0) {
4459 qemu_co_mutex_unlock(&s->lock);
4460 goto fail;
4463 ret = qcow2_pre_write_overlap_check(bs, 0, cluster_offset, out_len, true);
4464 qemu_co_mutex_unlock(&s->lock);
4465 if (ret < 0) {
4466 goto fail;
4469 BLKDBG_EVENT(s->data_file, BLKDBG_WRITE_COMPRESSED);
4470 ret = bdrv_co_pwrite(s->data_file, cluster_offset, out_len, out_buf, 0);
4471 if (ret < 0) {
4472 goto fail;
4474 success:
4475 ret = 0;
4476 fail:
4477 qemu_vfree(buf);
4478 g_free(out_buf);
4479 return ret;
4482 static coroutine_fn int qcow2_co_pwritev_compressed_task_entry(AioTask *task)
4484 Qcow2AioTask *t = container_of(task, Qcow2AioTask, task);
4486 assert(!t->cluster_type && !t->l2meta);
4488 return qcow2_co_pwritev_compressed_task(t->bs, t->offset, t->bytes, t->qiov,
4489 t->qiov_offset);
4493 * XXX: put compressed sectors first, then all the cluster aligned
4494 * tables to avoid losing bytes in alignment
4496 static coroutine_fn int
4497 qcow2_co_pwritev_compressed_part(BlockDriverState *bs,
4498 uint64_t offset, uint64_t bytes,
4499 QEMUIOVector *qiov, size_t qiov_offset)
4501 BDRVQcow2State *s = bs->opaque;
4502 AioTaskPool *aio = NULL;
4503 int ret = 0;
4505 if (has_data_file(bs)) {
4506 return -ENOTSUP;
4509 if (bytes == 0) {
4511 * align end of file to a sector boundary to ease reading with
4512 * sector based I/Os
4514 int64_t len = bdrv_getlength(bs->file->bs);
4515 if (len < 0) {
4516 return len;
4518 return bdrv_co_truncate(bs->file, len, false, PREALLOC_MODE_OFF, 0,
4519 NULL);
4522 if (offset_into_cluster(s, offset)) {
4523 return -EINVAL;
4526 if (offset_into_cluster(s, bytes) &&
4527 (offset + bytes) != (bs->total_sectors << BDRV_SECTOR_BITS)) {
4528 return -EINVAL;
4531 while (bytes && aio_task_pool_status(aio) == 0) {
4532 uint64_t chunk_size = MIN(bytes, s->cluster_size);
4534 if (!aio && chunk_size != bytes) {
4535 aio = aio_task_pool_new(QCOW2_MAX_WORKERS);
4538 ret = qcow2_add_task(bs, aio, qcow2_co_pwritev_compressed_task_entry,
4539 0, 0, offset, chunk_size, qiov, qiov_offset, NULL);
4540 if (ret < 0) {
4541 break;
4543 qiov_offset += chunk_size;
4544 offset += chunk_size;
4545 bytes -= chunk_size;
4548 if (aio) {
4549 aio_task_pool_wait_all(aio);
4550 if (ret == 0) {
4551 ret = aio_task_pool_status(aio);
4553 g_free(aio);
4556 return ret;
4559 static int coroutine_fn
4560 qcow2_co_preadv_compressed(BlockDriverState *bs,
4561 uint64_t file_cluster_offset,
4562 uint64_t offset,
4563 uint64_t bytes,
4564 QEMUIOVector *qiov,
4565 size_t qiov_offset)
4567 BDRVQcow2State *s = bs->opaque;
4568 int ret = 0, csize, nb_csectors;
4569 uint64_t coffset;
4570 uint8_t *buf, *out_buf;
4571 int offset_in_cluster = offset_into_cluster(s, offset);
4573 coffset = file_cluster_offset & s->cluster_offset_mask;
4574 nb_csectors = ((file_cluster_offset >> s->csize_shift) & s->csize_mask) + 1;
4575 csize = nb_csectors * QCOW2_COMPRESSED_SECTOR_SIZE -
4576 (coffset & ~QCOW2_COMPRESSED_SECTOR_MASK);
4578 buf = g_try_malloc(csize);
4579 if (!buf) {
4580 return -ENOMEM;
4583 out_buf = qemu_blockalign(bs, s->cluster_size);
4585 BLKDBG_EVENT(bs->file, BLKDBG_READ_COMPRESSED);
4586 ret = bdrv_co_pread(bs->file, coffset, csize, buf, 0);
4587 if (ret < 0) {
4588 goto fail;
4591 if (qcow2_co_decompress(bs, out_buf, s->cluster_size, buf, csize) < 0) {
4592 ret = -EIO;
4593 goto fail;
4596 qemu_iovec_from_buf(qiov, qiov_offset, out_buf + offset_in_cluster, bytes);
4598 fail:
4599 qemu_vfree(out_buf);
4600 g_free(buf);
4602 return ret;
4605 static int make_completely_empty(BlockDriverState *bs)
4607 BDRVQcow2State *s = bs->opaque;
4608 Error *local_err = NULL;
4609 int ret, l1_clusters;
4610 int64_t offset;
4611 uint64_t *new_reftable = NULL;
4612 uint64_t rt_entry, l1_size2;
4613 struct {
4614 uint64_t l1_offset;
4615 uint64_t reftable_offset;
4616 uint32_t reftable_clusters;
4617 } QEMU_PACKED l1_ofs_rt_ofs_cls;
4619 ret = qcow2_cache_empty(bs, s->l2_table_cache);
4620 if (ret < 0) {
4621 goto fail;
4624 ret = qcow2_cache_empty(bs, s->refcount_block_cache);
4625 if (ret < 0) {
4626 goto fail;
4629 /* Refcounts will be broken utterly */
4630 ret = qcow2_mark_dirty(bs);
4631 if (ret < 0) {
4632 goto fail;
4635 BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
4637 l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / sizeof(uint64_t));
4638 l1_size2 = (uint64_t)s->l1_size * sizeof(uint64_t);
4640 /* After this call, neither the in-memory nor the on-disk refcount
4641 * information accurately describe the actual references */
4643 ret = bdrv_pwrite_zeroes(bs->file, s->l1_table_offset,
4644 l1_clusters * s->cluster_size, 0);
4645 if (ret < 0) {
4646 goto fail_broken_refcounts;
4648 memset(s->l1_table, 0, l1_size2);
4650 BLKDBG_EVENT(bs->file, BLKDBG_EMPTY_IMAGE_PREPARE);
4652 /* Overwrite enough clusters at the beginning of the sectors to place
4653 * the refcount table, a refcount block and the L1 table in; this may
4654 * overwrite parts of the existing refcount and L1 table, which is not
4655 * an issue because the dirty flag is set, complete data loss is in fact
4656 * desired and partial data loss is consequently fine as well */
4657 ret = bdrv_pwrite_zeroes(bs->file, s->cluster_size,
4658 (2 + l1_clusters) * s->cluster_size, 0);
4659 /* This call (even if it failed overall) may have overwritten on-disk
4660 * refcount structures; in that case, the in-memory refcount information
4661 * will probably differ from the on-disk information which makes the BDS
4662 * unusable */
4663 if (ret < 0) {
4664 goto fail_broken_refcounts;
4667 BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
4668 BLKDBG_EVENT(bs->file, BLKDBG_REFTABLE_UPDATE);
4670 /* "Create" an empty reftable (one cluster) directly after the image
4671 * header and an empty L1 table three clusters after the image header;
4672 * the cluster between those two will be used as the first refblock */
4673 l1_ofs_rt_ofs_cls.l1_offset = cpu_to_be64(3 * s->cluster_size);
4674 l1_ofs_rt_ofs_cls.reftable_offset = cpu_to_be64(s->cluster_size);
4675 l1_ofs_rt_ofs_cls.reftable_clusters = cpu_to_be32(1);
4676 ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, l1_table_offset),
4677 &l1_ofs_rt_ofs_cls, sizeof(l1_ofs_rt_ofs_cls));
4678 if (ret < 0) {
4679 goto fail_broken_refcounts;
4682 s->l1_table_offset = 3 * s->cluster_size;
4684 new_reftable = g_try_new0(uint64_t, s->cluster_size / sizeof(uint64_t));
4685 if (!new_reftable) {
4686 ret = -ENOMEM;
4687 goto fail_broken_refcounts;
4690 s->refcount_table_offset = s->cluster_size;
4691 s->refcount_table_size = s->cluster_size / sizeof(uint64_t);
4692 s->max_refcount_table_index = 0;
4694 g_free(s->refcount_table);
4695 s->refcount_table = new_reftable;
4696 new_reftable = NULL;
4698 /* Now the in-memory refcount information again corresponds to the on-disk
4699 * information (reftable is empty and no refblocks (the refblock cache is
4700 * empty)); however, this means some clusters (e.g. the image header) are
4701 * referenced, but not refcounted, but the normal qcow2 code assumes that
4702 * the in-memory information is always correct */
4704 BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_ALLOC);
4706 /* Enter the first refblock into the reftable */
4707 rt_entry = cpu_to_be64(2 * s->cluster_size);
4708 ret = bdrv_pwrite_sync(bs->file, s->cluster_size,
4709 &rt_entry, sizeof(rt_entry));
4710 if (ret < 0) {
4711 goto fail_broken_refcounts;
4713 s->refcount_table[0] = 2 * s->cluster_size;
4715 s->free_cluster_index = 0;
4716 assert(3 + l1_clusters <= s->refcount_block_size);
4717 offset = qcow2_alloc_clusters(bs, 3 * s->cluster_size + l1_size2);
4718 if (offset < 0) {
4719 ret = offset;
4720 goto fail_broken_refcounts;
4721 } else if (offset > 0) {
4722 error_report("First cluster in emptied image is in use");
4723 abort();
4726 /* Now finally the in-memory information corresponds to the on-disk
4727 * structures and is correct */
4728 ret = qcow2_mark_clean(bs);
4729 if (ret < 0) {
4730 goto fail;
4733 ret = bdrv_truncate(bs->file, (3 + l1_clusters) * s->cluster_size, false,
4734 PREALLOC_MODE_OFF, 0, &local_err);
4735 if (ret < 0) {
4736 error_report_err(local_err);
4737 goto fail;
4740 return 0;
4742 fail_broken_refcounts:
4743 /* The BDS is unusable at this point. If we wanted to make it usable, we
4744 * would have to call qcow2_refcount_close(), qcow2_refcount_init(),
4745 * qcow2_check_refcounts(), qcow2_refcount_close() and qcow2_refcount_init()
4746 * again. However, because the functions which could have caused this error
4747 * path to be taken are used by those functions as well, it's very likely
4748 * that that sequence will fail as well. Therefore, just eject the BDS. */
4749 bs->drv = NULL;
4751 fail:
4752 g_free(new_reftable);
4753 return ret;
4756 static int qcow2_make_empty(BlockDriverState *bs)
4758 BDRVQcow2State *s = bs->opaque;
4759 uint64_t offset, end_offset;
4760 int step = QEMU_ALIGN_DOWN(INT_MAX, s->cluster_size);
4761 int l1_clusters, ret = 0;
4763 l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / sizeof(uint64_t));
4765 if (s->qcow_version >= 3 && !s->snapshots && !s->nb_bitmaps &&
4766 3 + l1_clusters <= s->refcount_block_size &&
4767 s->crypt_method_header != QCOW_CRYPT_LUKS &&
4768 !has_data_file(bs)) {
4769 /* The following function only works for qcow2 v3 images (it
4770 * requires the dirty flag) and only as long as there are no
4771 * features that reserve extra clusters (such as snapshots,
4772 * LUKS header, or persistent bitmaps), because it completely
4773 * empties the image. Furthermore, the L1 table and three
4774 * additional clusters (image header, refcount table, one
4775 * refcount block) have to fit inside one refcount block. It
4776 * only resets the image file, i.e. does not work with an
4777 * external data file. */
4778 return make_completely_empty(bs);
4781 /* This fallback code simply discards every active cluster; this is slow,
4782 * but works in all cases */
4783 end_offset = bs->total_sectors * BDRV_SECTOR_SIZE;
4784 for (offset = 0; offset < end_offset; offset += step) {
4785 /* As this function is generally used after committing an external
4786 * snapshot, QCOW2_DISCARD_SNAPSHOT seems appropriate. Also, the
4787 * default action for this kind of discard is to pass the discard,
4788 * which will ideally result in an actually smaller image file, as
4789 * is probably desired. */
4790 ret = qcow2_cluster_discard(bs, offset, MIN(step, end_offset - offset),
4791 QCOW2_DISCARD_SNAPSHOT, true);
4792 if (ret < 0) {
4793 break;
4797 return ret;
4800 static coroutine_fn int qcow2_co_flush_to_os(BlockDriverState *bs)
4802 BDRVQcow2State *s = bs->opaque;
4803 int ret;
4805 qemu_co_mutex_lock(&s->lock);
4806 ret = qcow2_write_caches(bs);
4807 qemu_co_mutex_unlock(&s->lock);
4809 return ret;
4812 static BlockMeasureInfo *qcow2_measure(QemuOpts *opts, BlockDriverState *in_bs,
4813 Error **errp)
4815 Error *local_err = NULL;
4816 BlockMeasureInfo *info;
4817 uint64_t required = 0; /* bytes that contribute to required size */
4818 uint64_t virtual_size; /* disk size as seen by guest */
4819 uint64_t refcount_bits;
4820 uint64_t l2_tables;
4821 uint64_t luks_payload_size = 0;
4822 size_t cluster_size;
4823 int version;
4824 char *optstr;
4825 PreallocMode prealloc;
4826 bool has_backing_file;
4827 bool has_luks;
4829 /* Parse image creation options */
4830 cluster_size = qcow2_opt_get_cluster_size_del(opts, &local_err);
4831 if (local_err) {
4832 goto err;
4835 version = qcow2_opt_get_version_del(opts, &local_err);
4836 if (local_err) {
4837 goto err;
4840 refcount_bits = qcow2_opt_get_refcount_bits_del(opts, version, &local_err);
4841 if (local_err) {
4842 goto err;
4845 optstr = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
4846 prealloc = qapi_enum_parse(&PreallocMode_lookup, optstr,
4847 PREALLOC_MODE_OFF, &local_err);
4848 g_free(optstr);
4849 if (local_err) {
4850 goto err;
4853 optstr = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
4854 has_backing_file = !!optstr;
4855 g_free(optstr);
4857 optstr = qemu_opt_get_del(opts, BLOCK_OPT_ENCRYPT_FORMAT);
4858 has_luks = optstr && strcmp(optstr, "luks") == 0;
4859 g_free(optstr);
4861 if (has_luks) {
4862 g_autoptr(QCryptoBlockCreateOptions) create_opts = NULL;
4863 QDict *opts_qdict;
4864 QDict *cryptoopts;
4865 size_t headerlen;
4867 opts_qdict = qemu_opts_to_qdict(opts, NULL);
4868 qdict_extract_subqdict(opts_qdict, &cryptoopts, "encrypt.");
4869 qobject_unref(opts_qdict);
4871 qdict_put_str(cryptoopts, "format", "luks");
4873 create_opts = block_crypto_create_opts_init(cryptoopts, errp);
4874 qobject_unref(cryptoopts);
4875 if (!create_opts) {
4876 goto err;
4879 if (!qcrypto_block_calculate_payload_offset(create_opts,
4880 "encrypt.",
4881 &headerlen,
4882 &local_err)) {
4883 goto err;
4886 luks_payload_size = ROUND_UP(headerlen, cluster_size);
4889 virtual_size = qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0);
4890 virtual_size = ROUND_UP(virtual_size, cluster_size);
4892 /* Check that virtual disk size is valid */
4893 l2_tables = DIV_ROUND_UP(virtual_size / cluster_size,
4894 cluster_size / sizeof(uint64_t));
4895 if (l2_tables * sizeof(uint64_t) > QCOW_MAX_L1_SIZE) {
4896 error_setg(&local_err, "The image size is too large "
4897 "(try using a larger cluster size)");
4898 goto err;
4901 /* Account for input image */
4902 if (in_bs) {
4903 int64_t ssize = bdrv_getlength(in_bs);
4904 if (ssize < 0) {
4905 error_setg_errno(&local_err, -ssize,
4906 "Unable to get image virtual_size");
4907 goto err;
4910 virtual_size = ROUND_UP(ssize, cluster_size);
4912 if (has_backing_file) {
4913 /* We don't how much of the backing chain is shared by the input
4914 * image and the new image file. In the worst case the new image's
4915 * backing file has nothing in common with the input image. Be
4916 * conservative and assume all clusters need to be written.
4918 required = virtual_size;
4919 } else {
4920 int64_t offset;
4921 int64_t pnum = 0;
4923 for (offset = 0; offset < ssize; offset += pnum) {
4924 int ret;
4926 ret = bdrv_block_status_above(in_bs, NULL, offset,
4927 ssize - offset, &pnum, NULL,
4928 NULL);
4929 if (ret < 0) {
4930 error_setg_errno(&local_err, -ret,
4931 "Unable to get block status");
4932 goto err;
4935 if (ret & BDRV_BLOCK_ZERO) {
4936 /* Skip zero regions (safe with no backing file) */
4937 } else if ((ret & (BDRV_BLOCK_DATA | BDRV_BLOCK_ALLOCATED)) ==
4938 (BDRV_BLOCK_DATA | BDRV_BLOCK_ALLOCATED)) {
4939 /* Extend pnum to end of cluster for next iteration */
4940 pnum = ROUND_UP(offset + pnum, cluster_size) - offset;
4942 /* Count clusters we've seen */
4943 required += offset % cluster_size + pnum;
4949 /* Take into account preallocation. Nothing special is needed for
4950 * PREALLOC_MODE_METADATA since metadata is always counted.
4952 if (prealloc == PREALLOC_MODE_FULL || prealloc == PREALLOC_MODE_FALLOC) {
4953 required = virtual_size;
4956 info = g_new0(BlockMeasureInfo, 1);
4957 info->fully_allocated =
4958 qcow2_calc_prealloc_size(virtual_size, cluster_size,
4959 ctz32(refcount_bits)) + luks_payload_size;
4962 * Remove data clusters that are not required. This overestimates the
4963 * required size because metadata needed for the fully allocated file is
4964 * still counted. Show bitmaps only if both source and destination
4965 * would support them.
4967 info->required = info->fully_allocated - virtual_size + required;
4968 info->has_bitmaps = version >= 3 && in_bs &&
4969 bdrv_supports_persistent_dirty_bitmap(in_bs);
4970 if (info->has_bitmaps) {
4971 info->bitmaps = qcow2_get_persistent_dirty_bitmap_size(in_bs,
4972 cluster_size);
4974 return info;
4976 err:
4977 error_propagate(errp, local_err);
4978 return NULL;
4981 static int qcow2_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
4983 BDRVQcow2State *s = bs->opaque;
4984 bdi->unallocated_blocks_are_zero = true;
4985 bdi->cluster_size = s->cluster_size;
4986 bdi->vm_state_offset = qcow2_vm_state_offset(s);
4987 return 0;
4990 static ImageInfoSpecific *qcow2_get_specific_info(BlockDriverState *bs,
4991 Error **errp)
4993 BDRVQcow2State *s = bs->opaque;
4994 ImageInfoSpecific *spec_info;
4995 QCryptoBlockInfo *encrypt_info = NULL;
4996 Error *local_err = NULL;
4998 if (s->crypto != NULL) {
4999 encrypt_info = qcrypto_block_get_info(s->crypto, &local_err);
5000 if (local_err) {
5001 error_propagate(errp, local_err);
5002 return NULL;
5006 spec_info = g_new(ImageInfoSpecific, 1);
5007 *spec_info = (ImageInfoSpecific){
5008 .type = IMAGE_INFO_SPECIFIC_KIND_QCOW2,
5009 .u.qcow2.data = g_new0(ImageInfoSpecificQCow2, 1),
5011 if (s->qcow_version == 2) {
5012 *spec_info->u.qcow2.data = (ImageInfoSpecificQCow2){
5013 .compat = g_strdup("0.10"),
5014 .refcount_bits = s->refcount_bits,
5016 } else if (s->qcow_version == 3) {
5017 Qcow2BitmapInfoList *bitmaps;
5018 bitmaps = qcow2_get_bitmap_info_list(bs, &local_err);
5019 if (local_err) {
5020 error_propagate(errp, local_err);
5021 qapi_free_ImageInfoSpecific(spec_info);
5022 qapi_free_QCryptoBlockInfo(encrypt_info);
5023 return NULL;
5025 *spec_info->u.qcow2.data = (ImageInfoSpecificQCow2){
5026 .compat = g_strdup("1.1"),
5027 .lazy_refcounts = s->compatible_features &
5028 QCOW2_COMPAT_LAZY_REFCOUNTS,
5029 .has_lazy_refcounts = true,
5030 .corrupt = s->incompatible_features &
5031 QCOW2_INCOMPAT_CORRUPT,
5032 .has_corrupt = true,
5033 .refcount_bits = s->refcount_bits,
5034 .has_bitmaps = !!bitmaps,
5035 .bitmaps = bitmaps,
5036 .has_data_file = !!s->image_data_file,
5037 .data_file = g_strdup(s->image_data_file),
5038 .has_data_file_raw = has_data_file(bs),
5039 .data_file_raw = data_file_is_raw(bs),
5040 .compression_type = s->compression_type,
5042 } else {
5043 /* if this assertion fails, this probably means a new version was
5044 * added without having it covered here */
5045 assert(false);
5048 if (encrypt_info) {
5049 ImageInfoSpecificQCow2Encryption *qencrypt =
5050 g_new(ImageInfoSpecificQCow2Encryption, 1);
5051 switch (encrypt_info->format) {
5052 case Q_CRYPTO_BLOCK_FORMAT_QCOW:
5053 qencrypt->format = BLOCKDEV_QCOW2_ENCRYPTION_FORMAT_AES;
5054 break;
5055 case Q_CRYPTO_BLOCK_FORMAT_LUKS:
5056 qencrypt->format = BLOCKDEV_QCOW2_ENCRYPTION_FORMAT_LUKS;
5057 qencrypt->u.luks = encrypt_info->u.luks;
5058 break;
5059 default:
5060 abort();
5062 /* Since we did shallow copy above, erase any pointers
5063 * in the original info */
5064 memset(&encrypt_info->u, 0, sizeof(encrypt_info->u));
5065 qapi_free_QCryptoBlockInfo(encrypt_info);
5067 spec_info->u.qcow2.data->has_encrypt = true;
5068 spec_info->u.qcow2.data->encrypt = qencrypt;
5071 return spec_info;
5074 static int qcow2_has_zero_init(BlockDriverState *bs)
5076 BDRVQcow2State *s = bs->opaque;
5077 bool preallocated;
5079 if (qemu_in_coroutine()) {
5080 qemu_co_mutex_lock(&s->lock);
5083 * Check preallocation status: Preallocated images have all L2
5084 * tables allocated, nonpreallocated images have none. It is
5085 * therefore enough to check the first one.
5087 preallocated = s->l1_size > 0 && s->l1_table[0] != 0;
5088 if (qemu_in_coroutine()) {
5089 qemu_co_mutex_unlock(&s->lock);
5092 if (!preallocated) {
5093 return 1;
5094 } else if (bs->encrypted) {
5095 return 0;
5096 } else {
5097 return bdrv_has_zero_init(s->data_file->bs);
5101 static int qcow2_save_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
5102 int64_t pos)
5104 BDRVQcow2State *s = bs->opaque;
5106 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_SAVE);
5107 return bs->drv->bdrv_co_pwritev_part(bs, qcow2_vm_state_offset(s) + pos,
5108 qiov->size, qiov, 0, 0);
5111 static int qcow2_load_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
5112 int64_t pos)
5114 BDRVQcow2State *s = bs->opaque;
5116 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_LOAD);
5117 return bs->drv->bdrv_co_preadv_part(bs, qcow2_vm_state_offset(s) + pos,
5118 qiov->size, qiov, 0, 0);
5122 * Downgrades an image's version. To achieve this, any incompatible features
5123 * have to be removed.
5125 static int qcow2_downgrade(BlockDriverState *bs, int target_version,
5126 BlockDriverAmendStatusCB *status_cb, void *cb_opaque,
5127 Error **errp)
5129 BDRVQcow2State *s = bs->opaque;
5130 int current_version = s->qcow_version;
5131 int ret;
5132 int i;
5134 /* This is qcow2_downgrade(), not qcow2_upgrade() */
5135 assert(target_version < current_version);
5137 /* There are no other versions (now) that you can downgrade to */
5138 assert(target_version == 2);
5140 if (s->refcount_order != 4) {
5141 error_setg(errp, "compat=0.10 requires refcount_bits=16");
5142 return -ENOTSUP;
5145 if (has_data_file(bs)) {
5146 error_setg(errp, "Cannot downgrade an image with a data file");
5147 return -ENOTSUP;
5151 * If any internal snapshot has a different size than the current
5152 * image size, or VM state size that exceeds 32 bits, downgrading
5153 * is unsafe. Even though we would still use v3-compliant output
5154 * to preserve that data, other v2 programs might not realize
5155 * those optional fields are important.
5157 for (i = 0; i < s->nb_snapshots; i++) {
5158 if (s->snapshots[i].vm_state_size > UINT32_MAX ||
5159 s->snapshots[i].disk_size != bs->total_sectors * BDRV_SECTOR_SIZE) {
5160 error_setg(errp, "Internal snapshots prevent downgrade of image");
5161 return -ENOTSUP;
5165 /* clear incompatible features */
5166 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
5167 ret = qcow2_mark_clean(bs);
5168 if (ret < 0) {
5169 error_setg_errno(errp, -ret, "Failed to make the image clean");
5170 return ret;
5174 /* with QCOW2_INCOMPAT_CORRUPT, it is pretty much impossible to get here in
5175 * the first place; if that happens nonetheless, returning -ENOTSUP is the
5176 * best thing to do anyway */
5178 if (s->incompatible_features) {
5179 error_setg(errp, "Cannot downgrade an image with incompatible features "
5180 "%#" PRIx64 " set", s->incompatible_features);
5181 return -ENOTSUP;
5184 /* since we can ignore compatible features, we can set them to 0 as well */
5185 s->compatible_features = 0;
5186 /* if lazy refcounts have been used, they have already been fixed through
5187 * clearing the dirty flag */
5189 /* clearing autoclear features is trivial */
5190 s->autoclear_features = 0;
5192 ret = qcow2_expand_zero_clusters(bs, status_cb, cb_opaque);
5193 if (ret < 0) {
5194 error_setg_errno(errp, -ret, "Failed to turn zero into data clusters");
5195 return ret;
5198 s->qcow_version = target_version;
5199 ret = qcow2_update_header(bs);
5200 if (ret < 0) {
5201 s->qcow_version = current_version;
5202 error_setg_errno(errp, -ret, "Failed to update the image header");
5203 return ret;
5205 return 0;
5209 * Upgrades an image's version. While newer versions encompass all
5210 * features of older versions, some things may have to be presented
5211 * differently.
5213 static int qcow2_upgrade(BlockDriverState *bs, int target_version,
5214 BlockDriverAmendStatusCB *status_cb, void *cb_opaque,
5215 Error **errp)
5217 BDRVQcow2State *s = bs->opaque;
5218 bool need_snapshot_update;
5219 int current_version = s->qcow_version;
5220 int i;
5221 int ret;
5223 /* This is qcow2_upgrade(), not qcow2_downgrade() */
5224 assert(target_version > current_version);
5226 /* There are no other versions (yet) that you can upgrade to */
5227 assert(target_version == 3);
5229 status_cb(bs, 0, 2, cb_opaque);
5232 * In v2, snapshots do not need to have extra data. v3 requires
5233 * the 64-bit VM state size and the virtual disk size to be
5234 * present.
5235 * qcow2_write_snapshots() will always write the list in the
5236 * v3-compliant format.
5238 need_snapshot_update = false;
5239 for (i = 0; i < s->nb_snapshots; i++) {
5240 if (s->snapshots[i].extra_data_size <
5241 sizeof_field(QCowSnapshotExtraData, vm_state_size_large) +
5242 sizeof_field(QCowSnapshotExtraData, disk_size))
5244 need_snapshot_update = true;
5245 break;
5248 if (need_snapshot_update) {
5249 ret = qcow2_write_snapshots(bs);
5250 if (ret < 0) {
5251 error_setg_errno(errp, -ret, "Failed to update the snapshot table");
5252 return ret;
5255 status_cb(bs, 1, 2, cb_opaque);
5257 s->qcow_version = target_version;
5258 ret = qcow2_update_header(bs);
5259 if (ret < 0) {
5260 s->qcow_version = current_version;
5261 error_setg_errno(errp, -ret, "Failed to update the image header");
5262 return ret;
5264 status_cb(bs, 2, 2, cb_opaque);
5266 return 0;
5269 typedef enum Qcow2AmendOperation {
5270 /* This is the value Qcow2AmendHelperCBInfo::last_operation will be
5271 * statically initialized to so that the helper CB can discern the first
5272 * invocation from an operation change */
5273 QCOW2_NO_OPERATION = 0,
5275 QCOW2_UPGRADING,
5276 QCOW2_CHANGING_REFCOUNT_ORDER,
5277 QCOW2_DOWNGRADING,
5278 } Qcow2AmendOperation;
5280 typedef struct Qcow2AmendHelperCBInfo {
5281 /* The code coordinating the amend operations should only modify
5282 * these four fields; the rest will be managed by the CB */
5283 BlockDriverAmendStatusCB *original_status_cb;
5284 void *original_cb_opaque;
5286 Qcow2AmendOperation current_operation;
5288 /* Total number of operations to perform (only set once) */
5289 int total_operations;
5291 /* The following fields are managed by the CB */
5293 /* Number of operations completed */
5294 int operations_completed;
5296 /* Cumulative offset of all completed operations */
5297 int64_t offset_completed;
5299 Qcow2AmendOperation last_operation;
5300 int64_t last_work_size;
5301 } Qcow2AmendHelperCBInfo;
5303 static void qcow2_amend_helper_cb(BlockDriverState *bs,
5304 int64_t operation_offset,
5305 int64_t operation_work_size, void *opaque)
5307 Qcow2AmendHelperCBInfo *info = opaque;
5308 int64_t current_work_size;
5309 int64_t projected_work_size;
5311 if (info->current_operation != info->last_operation) {
5312 if (info->last_operation != QCOW2_NO_OPERATION) {
5313 info->offset_completed += info->last_work_size;
5314 info->operations_completed++;
5317 info->last_operation = info->current_operation;
5320 assert(info->total_operations > 0);
5321 assert(info->operations_completed < info->total_operations);
5323 info->last_work_size = operation_work_size;
5325 current_work_size = info->offset_completed + operation_work_size;
5327 /* current_work_size is the total work size for (operations_completed + 1)
5328 * operations (which includes this one), so multiply it by the number of
5329 * operations not covered and divide it by the number of operations
5330 * covered to get a projection for the operations not covered */
5331 projected_work_size = current_work_size * (info->total_operations -
5332 info->operations_completed - 1)
5333 / (info->operations_completed + 1);
5335 info->original_status_cb(bs, info->offset_completed + operation_offset,
5336 current_work_size + projected_work_size,
5337 info->original_cb_opaque);
5340 static int qcow2_amend_options(BlockDriverState *bs, QemuOpts *opts,
5341 BlockDriverAmendStatusCB *status_cb,
5342 void *cb_opaque,
5343 bool force,
5344 Error **errp)
5346 BDRVQcow2State *s = bs->opaque;
5347 int old_version = s->qcow_version, new_version = old_version;
5348 uint64_t new_size = 0;
5349 const char *backing_file = NULL, *backing_format = NULL, *data_file = NULL;
5350 bool lazy_refcounts = s->use_lazy_refcounts;
5351 bool data_file_raw = data_file_is_raw(bs);
5352 const char *compat = NULL;
5353 int refcount_bits = s->refcount_bits;
5354 int ret;
5355 QemuOptDesc *desc = opts->list->desc;
5356 Qcow2AmendHelperCBInfo helper_cb_info;
5358 while (desc && desc->name) {
5359 if (!qemu_opt_find(opts, desc->name)) {
5360 /* only change explicitly defined options */
5361 desc++;
5362 continue;
5365 if (!strcmp(desc->name, BLOCK_OPT_COMPAT_LEVEL)) {
5366 compat = qemu_opt_get(opts, BLOCK_OPT_COMPAT_LEVEL);
5367 if (!compat) {
5368 /* preserve default */
5369 } else if (!strcmp(compat, "0.10") || !strcmp(compat, "v2")) {
5370 new_version = 2;
5371 } else if (!strcmp(compat, "1.1") || !strcmp(compat, "v3")) {
5372 new_version = 3;
5373 } else {
5374 error_setg(errp, "Unknown compatibility level %s", compat);
5375 return -EINVAL;
5377 } else if (!strcmp(desc->name, BLOCK_OPT_SIZE)) {
5378 new_size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, 0);
5379 } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FILE)) {
5380 backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
5381 } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FMT)) {
5382 backing_format = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
5383 } else if (!strcmp(desc->name, BLOCK_OPT_LAZY_REFCOUNTS)) {
5384 lazy_refcounts = qemu_opt_get_bool(opts, BLOCK_OPT_LAZY_REFCOUNTS,
5385 lazy_refcounts);
5386 } else if (!strcmp(desc->name, BLOCK_OPT_REFCOUNT_BITS)) {
5387 refcount_bits = qemu_opt_get_number(opts, BLOCK_OPT_REFCOUNT_BITS,
5388 refcount_bits);
5390 if (refcount_bits <= 0 || refcount_bits > 64 ||
5391 !is_power_of_2(refcount_bits))
5393 error_setg(errp, "Refcount width must be a power of two and "
5394 "may not exceed 64 bits");
5395 return -EINVAL;
5397 } else if (!strcmp(desc->name, BLOCK_OPT_DATA_FILE)) {
5398 data_file = qemu_opt_get(opts, BLOCK_OPT_DATA_FILE);
5399 if (data_file && !has_data_file(bs)) {
5400 error_setg(errp, "data-file can only be set for images that "
5401 "use an external data file");
5402 return -EINVAL;
5404 } else if (!strcmp(desc->name, BLOCK_OPT_DATA_FILE_RAW)) {
5405 data_file_raw = qemu_opt_get_bool(opts, BLOCK_OPT_DATA_FILE_RAW,
5406 data_file_raw);
5407 if (data_file_raw && !data_file_is_raw(bs)) {
5408 error_setg(errp, "data-file-raw cannot be set on existing "
5409 "images");
5410 return -EINVAL;
5412 } else {
5413 /* if this point is reached, this probably means a new option was
5414 * added without having it covered here */
5415 abort();
5418 desc++;
5421 helper_cb_info = (Qcow2AmendHelperCBInfo){
5422 .original_status_cb = status_cb,
5423 .original_cb_opaque = cb_opaque,
5424 .total_operations = (new_version != old_version)
5425 + (s->refcount_bits != refcount_bits)
5428 /* Upgrade first (some features may require compat=1.1) */
5429 if (new_version > old_version) {
5430 helper_cb_info.current_operation = QCOW2_UPGRADING;
5431 ret = qcow2_upgrade(bs, new_version, &qcow2_amend_helper_cb,
5432 &helper_cb_info, errp);
5433 if (ret < 0) {
5434 return ret;
5438 if (s->refcount_bits != refcount_bits) {
5439 int refcount_order = ctz32(refcount_bits);
5441 if (new_version < 3 && refcount_bits != 16) {
5442 error_setg(errp, "Refcount widths other than 16 bits require "
5443 "compatibility level 1.1 or above (use compat=1.1 or "
5444 "greater)");
5445 return -EINVAL;
5448 helper_cb_info.current_operation = QCOW2_CHANGING_REFCOUNT_ORDER;
5449 ret = qcow2_change_refcount_order(bs, refcount_order,
5450 &qcow2_amend_helper_cb,
5451 &helper_cb_info, errp);
5452 if (ret < 0) {
5453 return ret;
5457 /* data-file-raw blocks backing files, so clear it first if requested */
5458 if (data_file_raw) {
5459 s->autoclear_features |= QCOW2_AUTOCLEAR_DATA_FILE_RAW;
5460 } else {
5461 s->autoclear_features &= ~QCOW2_AUTOCLEAR_DATA_FILE_RAW;
5464 if (data_file) {
5465 g_free(s->image_data_file);
5466 s->image_data_file = *data_file ? g_strdup(data_file) : NULL;
5469 ret = qcow2_update_header(bs);
5470 if (ret < 0) {
5471 error_setg_errno(errp, -ret, "Failed to update the image header");
5472 return ret;
5475 if (backing_file || backing_format) {
5476 ret = qcow2_change_backing_file(bs,
5477 backing_file ?: s->image_backing_file,
5478 backing_format ?: s->image_backing_format);
5479 if (ret < 0) {
5480 error_setg_errno(errp, -ret, "Failed to change the backing file");
5481 return ret;
5485 if (s->use_lazy_refcounts != lazy_refcounts) {
5486 if (lazy_refcounts) {
5487 if (new_version < 3) {
5488 error_setg(errp, "Lazy refcounts only supported with "
5489 "compatibility level 1.1 and above (use compat=1.1 "
5490 "or greater)");
5491 return -EINVAL;
5493 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
5494 ret = qcow2_update_header(bs);
5495 if (ret < 0) {
5496 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
5497 error_setg_errno(errp, -ret, "Failed to update the image header");
5498 return ret;
5500 s->use_lazy_refcounts = true;
5501 } else {
5502 /* make image clean first */
5503 ret = qcow2_mark_clean(bs);
5504 if (ret < 0) {
5505 error_setg_errno(errp, -ret, "Failed to make the image clean");
5506 return ret;
5508 /* now disallow lazy refcounts */
5509 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
5510 ret = qcow2_update_header(bs);
5511 if (ret < 0) {
5512 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
5513 error_setg_errno(errp, -ret, "Failed to update the image header");
5514 return ret;
5516 s->use_lazy_refcounts = false;
5520 if (new_size) {
5521 BlockBackend *blk = blk_new_with_bs(bs, BLK_PERM_RESIZE, BLK_PERM_ALL,
5522 errp);
5523 if (!blk) {
5524 return -EPERM;
5528 * Amending image options should ensure that the image has
5529 * exactly the given new values, so pass exact=true here.
5531 ret = blk_truncate(blk, new_size, true, PREALLOC_MODE_OFF, 0, errp);
5532 blk_unref(blk);
5533 if (ret < 0) {
5534 return ret;
5538 /* Downgrade last (so unsupported features can be removed before) */
5539 if (new_version < old_version) {
5540 helper_cb_info.current_operation = QCOW2_DOWNGRADING;
5541 ret = qcow2_downgrade(bs, new_version, &qcow2_amend_helper_cb,
5542 &helper_cb_info, errp);
5543 if (ret < 0) {
5544 return ret;
5548 return 0;
5552 * If offset or size are negative, respectively, they will not be included in
5553 * the BLOCK_IMAGE_CORRUPTED event emitted.
5554 * fatal will be ignored for read-only BDS; corruptions found there will always
5555 * be considered non-fatal.
5557 void qcow2_signal_corruption(BlockDriverState *bs, bool fatal, int64_t offset,
5558 int64_t size, const char *message_format, ...)
5560 BDRVQcow2State *s = bs->opaque;
5561 const char *node_name;
5562 char *message;
5563 va_list ap;
5565 fatal = fatal && bdrv_is_writable(bs);
5567 if (s->signaled_corruption &&
5568 (!fatal || (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT)))
5570 return;
5573 va_start(ap, message_format);
5574 message = g_strdup_vprintf(message_format, ap);
5575 va_end(ap);
5577 if (fatal) {
5578 fprintf(stderr, "qcow2: Marking image as corrupt: %s; further "
5579 "corruption events will be suppressed\n", message);
5580 } else {
5581 fprintf(stderr, "qcow2: Image is corrupt: %s; further non-fatal "
5582 "corruption events will be suppressed\n", message);
5585 node_name = bdrv_get_node_name(bs);
5586 qapi_event_send_block_image_corrupted(bdrv_get_device_name(bs),
5587 *node_name != '\0', node_name,
5588 message, offset >= 0, offset,
5589 size >= 0, size,
5590 fatal);
5591 g_free(message);
5593 if (fatal) {
5594 qcow2_mark_corrupt(bs);
5595 bs->drv = NULL; /* make BDS unusable */
5598 s->signaled_corruption = true;
5601 #define QCOW_COMMON_OPTIONS \
5603 .name = BLOCK_OPT_SIZE, \
5604 .type = QEMU_OPT_SIZE, \
5605 .help = "Virtual disk size" \
5606 }, \
5608 .name = BLOCK_OPT_COMPAT_LEVEL, \
5609 .type = QEMU_OPT_STRING, \
5610 .help = "Compatibility level (v2 [0.10] or v3 [1.1])" \
5611 }, \
5613 .name = BLOCK_OPT_BACKING_FILE, \
5614 .type = QEMU_OPT_STRING, \
5615 .help = "File name of a base image" \
5616 }, \
5618 .name = BLOCK_OPT_BACKING_FMT, \
5619 .type = QEMU_OPT_STRING, \
5620 .help = "Image format of the base image" \
5621 }, \
5623 .name = BLOCK_OPT_DATA_FILE, \
5624 .type = QEMU_OPT_STRING, \
5625 .help = "File name of an external data file" \
5626 }, \
5628 .name = BLOCK_OPT_DATA_FILE_RAW, \
5629 .type = QEMU_OPT_BOOL, \
5630 .help = "The external data file must stay valid " \
5631 "as a raw image" \
5632 }, \
5634 .name = BLOCK_OPT_LAZY_REFCOUNTS, \
5635 .type = QEMU_OPT_BOOL, \
5636 .help = "Postpone refcount updates", \
5637 .def_value_str = "off" \
5638 }, \
5640 .name = BLOCK_OPT_REFCOUNT_BITS, \
5641 .type = QEMU_OPT_NUMBER, \
5642 .help = "Width of a reference count entry in bits", \
5643 .def_value_str = "16" \
5646 static QemuOptsList qcow2_create_opts = {
5647 .name = "qcow2-create-opts",
5648 .head = QTAILQ_HEAD_INITIALIZER(qcow2_create_opts.head),
5649 .desc = {
5651 .name = BLOCK_OPT_ENCRYPT, \
5652 .type = QEMU_OPT_BOOL, \
5653 .help = "Encrypt the image with format 'aes'. (Deprecated " \
5654 "in favor of " BLOCK_OPT_ENCRYPT_FORMAT "=aes)", \
5655 }, \
5657 .name = BLOCK_OPT_ENCRYPT_FORMAT, \
5658 .type = QEMU_OPT_STRING, \
5659 .help = "Encrypt the image, format choices: 'aes', 'luks'", \
5660 }, \
5661 BLOCK_CRYPTO_OPT_DEF_KEY_SECRET("encrypt.", \
5662 "ID of secret providing qcow AES key or LUKS passphrase"), \
5663 BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_ALG("encrypt."), \
5664 BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_MODE("encrypt."), \
5665 BLOCK_CRYPTO_OPT_DEF_LUKS_IVGEN_ALG("encrypt."), \
5666 BLOCK_CRYPTO_OPT_DEF_LUKS_IVGEN_HASH_ALG("encrypt."), \
5667 BLOCK_CRYPTO_OPT_DEF_LUKS_HASH_ALG("encrypt."), \
5668 BLOCK_CRYPTO_OPT_DEF_LUKS_ITER_TIME("encrypt."), \
5670 .name = BLOCK_OPT_CLUSTER_SIZE, \
5671 .type = QEMU_OPT_SIZE, \
5672 .help = "qcow2 cluster size", \
5673 .def_value_str = stringify(DEFAULT_CLUSTER_SIZE) \
5674 }, \
5676 .name = BLOCK_OPT_PREALLOC, \
5677 .type = QEMU_OPT_STRING, \
5678 .help = "Preallocation mode (allowed values: off, " \
5679 "metadata, falloc, full)" \
5680 }, \
5682 .name = BLOCK_OPT_COMPRESSION_TYPE, \
5683 .type = QEMU_OPT_STRING, \
5684 .help = "Compression method used for image cluster " \
5685 "compression", \
5686 .def_value_str = "zlib" \
5688 QCOW_COMMON_OPTIONS,
5689 { /* end of list */ }
5693 static QemuOptsList qcow2_amend_opts = {
5694 .name = "qcow2-amend-opts",
5695 .head = QTAILQ_HEAD_INITIALIZER(qcow2_amend_opts.head),
5696 .desc = {
5697 QCOW_COMMON_OPTIONS,
5698 { /* end of list */ }
5702 static const char *const qcow2_strong_runtime_opts[] = {
5703 "encrypt." BLOCK_CRYPTO_OPT_QCOW_KEY_SECRET,
5705 NULL
5708 BlockDriver bdrv_qcow2 = {
5709 .format_name = "qcow2",
5710 .instance_size = sizeof(BDRVQcow2State),
5711 .bdrv_probe = qcow2_probe,
5712 .bdrv_open = qcow2_open,
5713 .bdrv_close = qcow2_close,
5714 .bdrv_reopen_prepare = qcow2_reopen_prepare,
5715 .bdrv_reopen_commit = qcow2_reopen_commit,
5716 .bdrv_reopen_commit_post = qcow2_reopen_commit_post,
5717 .bdrv_reopen_abort = qcow2_reopen_abort,
5718 .bdrv_join_options = qcow2_join_options,
5719 .bdrv_child_perm = bdrv_default_perms,
5720 .bdrv_co_create_opts = qcow2_co_create_opts,
5721 .bdrv_co_create = qcow2_co_create,
5722 .bdrv_has_zero_init = qcow2_has_zero_init,
5723 .bdrv_co_block_status = qcow2_co_block_status,
5725 .bdrv_co_preadv_part = qcow2_co_preadv_part,
5726 .bdrv_co_pwritev_part = qcow2_co_pwritev_part,
5727 .bdrv_co_flush_to_os = qcow2_co_flush_to_os,
5729 .bdrv_co_pwrite_zeroes = qcow2_co_pwrite_zeroes,
5730 .bdrv_co_pdiscard = qcow2_co_pdiscard,
5731 .bdrv_co_copy_range_from = qcow2_co_copy_range_from,
5732 .bdrv_co_copy_range_to = qcow2_co_copy_range_to,
5733 .bdrv_co_truncate = qcow2_co_truncate,
5734 .bdrv_co_pwritev_compressed_part = qcow2_co_pwritev_compressed_part,
5735 .bdrv_make_empty = qcow2_make_empty,
5737 .bdrv_snapshot_create = qcow2_snapshot_create,
5738 .bdrv_snapshot_goto = qcow2_snapshot_goto,
5739 .bdrv_snapshot_delete = qcow2_snapshot_delete,
5740 .bdrv_snapshot_list = qcow2_snapshot_list,
5741 .bdrv_snapshot_load_tmp = qcow2_snapshot_load_tmp,
5742 .bdrv_measure = qcow2_measure,
5743 .bdrv_get_info = qcow2_get_info,
5744 .bdrv_get_specific_info = qcow2_get_specific_info,
5746 .bdrv_save_vmstate = qcow2_save_vmstate,
5747 .bdrv_load_vmstate = qcow2_load_vmstate,
5749 .is_format = true,
5750 .supports_backing = true,
5751 .bdrv_change_backing_file = qcow2_change_backing_file,
5753 .bdrv_refresh_limits = qcow2_refresh_limits,
5754 .bdrv_co_invalidate_cache = qcow2_co_invalidate_cache,
5755 .bdrv_inactivate = qcow2_inactivate,
5757 .create_opts = &qcow2_create_opts,
5758 .amend_opts = &qcow2_amend_opts,
5759 .strong_runtime_opts = qcow2_strong_runtime_opts,
5760 .mutable_opts = mutable_opts,
5761 .bdrv_co_check = qcow2_co_check,
5762 .bdrv_amend_options = qcow2_amend_options,
5764 .bdrv_detach_aio_context = qcow2_detach_aio_context,
5765 .bdrv_attach_aio_context = qcow2_attach_aio_context,
5767 .bdrv_supports_persistent_dirty_bitmap =
5768 qcow2_supports_persistent_dirty_bitmap,
5769 .bdrv_co_can_store_new_dirty_bitmap = qcow2_co_can_store_new_dirty_bitmap,
5770 .bdrv_co_remove_persistent_dirty_bitmap =
5771 qcow2_co_remove_persistent_dirty_bitmap,
5774 static void bdrv_qcow2_init(void)
5776 bdrv_register(&bdrv_qcow2);
5779 block_init(bdrv_qcow2_init);