block/qcow2: implement blockdev-amend
[qemu/ar7.git] / block / qcow2.c
blob30f073cf2aba758d5e03356e5fcbcad3d5106a2c
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;
179 static QDict*
180 qcow2_extract_crypto_opts(QemuOpts *opts, const char *fmt, Error **errp)
182 QDict *cryptoopts_qdict;
183 QDict *opts_qdict;
185 /* Extract "encrypt." options into a qdict */
186 opts_qdict = qemu_opts_to_qdict(opts, NULL);
187 qdict_extract_subqdict(opts_qdict, &cryptoopts_qdict, "encrypt.");
188 qobject_unref(opts_qdict);
189 qdict_put_str(cryptoopts_qdict, "format", fmt);
190 return cryptoopts_qdict;
194 * read qcow2 extension and fill bs
195 * start reading from start_offset
196 * finish reading upon magic of value 0 or when end_offset reached
197 * unknown magic is skipped (future extension this version knows nothing about)
198 * return 0 upon success, non-0 otherwise
200 static int qcow2_read_extensions(BlockDriverState *bs, uint64_t start_offset,
201 uint64_t end_offset, void **p_feature_table,
202 int flags, bool *need_update_header,
203 Error **errp)
205 BDRVQcow2State *s = bs->opaque;
206 QCowExtension ext;
207 uint64_t offset;
208 int ret;
209 Qcow2BitmapHeaderExt bitmaps_ext;
211 if (need_update_header != NULL) {
212 *need_update_header = false;
215 #ifdef DEBUG_EXT
216 printf("qcow2_read_extensions: start=%ld end=%ld\n", start_offset, end_offset);
217 #endif
218 offset = start_offset;
219 while (offset < end_offset) {
221 #ifdef DEBUG_EXT
222 /* Sanity check */
223 if (offset > s->cluster_size)
224 printf("qcow2_read_extension: suspicious offset %lu\n", offset);
226 printf("attempting to read extended header in offset %lu\n", offset);
227 #endif
229 ret = bdrv_pread(bs->file, offset, &ext, sizeof(ext));
230 if (ret < 0) {
231 error_setg_errno(errp, -ret, "qcow2_read_extension: ERROR: "
232 "pread fail from offset %" PRIu64, offset);
233 return 1;
235 ext.magic = be32_to_cpu(ext.magic);
236 ext.len = be32_to_cpu(ext.len);
237 offset += sizeof(ext);
238 #ifdef DEBUG_EXT
239 printf("ext.magic = 0x%x\n", ext.magic);
240 #endif
241 if (offset > end_offset || ext.len > end_offset - offset) {
242 error_setg(errp, "Header extension too large");
243 return -EINVAL;
246 switch (ext.magic) {
247 case QCOW2_EXT_MAGIC_END:
248 return 0;
250 case QCOW2_EXT_MAGIC_BACKING_FORMAT:
251 if (ext.len >= sizeof(bs->backing_format)) {
252 error_setg(errp, "ERROR: ext_backing_format: len=%" PRIu32
253 " too large (>=%zu)", ext.len,
254 sizeof(bs->backing_format));
255 return 2;
257 ret = bdrv_pread(bs->file, offset, bs->backing_format, ext.len);
258 if (ret < 0) {
259 error_setg_errno(errp, -ret, "ERROR: ext_backing_format: "
260 "Could not read format name");
261 return 3;
263 bs->backing_format[ext.len] = '\0';
264 s->image_backing_format = g_strdup(bs->backing_format);
265 #ifdef DEBUG_EXT
266 printf("Qcow2: Got format extension %s\n", bs->backing_format);
267 #endif
268 break;
270 case QCOW2_EXT_MAGIC_FEATURE_TABLE:
271 if (p_feature_table != NULL) {
272 void* feature_table = g_malloc0(ext.len + 2 * sizeof(Qcow2Feature));
273 ret = bdrv_pread(bs->file, offset , feature_table, ext.len);
274 if (ret < 0) {
275 error_setg_errno(errp, -ret, "ERROR: ext_feature_table: "
276 "Could not read table");
277 return ret;
280 *p_feature_table = feature_table;
282 break;
284 case QCOW2_EXT_MAGIC_CRYPTO_HEADER: {
285 unsigned int cflags = 0;
286 if (s->crypt_method_header != QCOW_CRYPT_LUKS) {
287 error_setg(errp, "CRYPTO header extension only "
288 "expected with LUKS encryption method");
289 return -EINVAL;
291 if (ext.len != sizeof(Qcow2CryptoHeaderExtension)) {
292 error_setg(errp, "CRYPTO header extension size %u, "
293 "but expected size %zu", ext.len,
294 sizeof(Qcow2CryptoHeaderExtension));
295 return -EINVAL;
298 ret = bdrv_pread(bs->file, offset, &s->crypto_header, ext.len);
299 if (ret < 0) {
300 error_setg_errno(errp, -ret,
301 "Unable to read CRYPTO header extension");
302 return ret;
304 s->crypto_header.offset = be64_to_cpu(s->crypto_header.offset);
305 s->crypto_header.length = be64_to_cpu(s->crypto_header.length);
307 if ((s->crypto_header.offset % s->cluster_size) != 0) {
308 error_setg(errp, "Encryption header offset '%" PRIu64 "' is "
309 "not a multiple of cluster size '%u'",
310 s->crypto_header.offset, s->cluster_size);
311 return -EINVAL;
314 if (flags & BDRV_O_NO_IO) {
315 cflags |= QCRYPTO_BLOCK_OPEN_NO_IO;
317 s->crypto = qcrypto_block_open(s->crypto_opts, "encrypt.",
318 qcow2_crypto_hdr_read_func,
319 bs, cflags, QCOW2_MAX_THREADS, errp);
320 if (!s->crypto) {
321 return -EINVAL;
323 } break;
325 case QCOW2_EXT_MAGIC_BITMAPS:
326 if (ext.len != sizeof(bitmaps_ext)) {
327 error_setg_errno(errp, -ret, "bitmaps_ext: "
328 "Invalid extension length");
329 return -EINVAL;
332 if (!(s->autoclear_features & QCOW2_AUTOCLEAR_BITMAPS)) {
333 if (s->qcow_version < 3) {
334 /* Let's be a bit more specific */
335 warn_report("This qcow2 v2 image contains bitmaps, but "
336 "they may have been modified by a program "
337 "without persistent bitmap support; so now "
338 "they must all be considered inconsistent");
339 } else {
340 warn_report("a program lacking bitmap support "
341 "modified this file, so all bitmaps are now "
342 "considered inconsistent");
344 error_printf("Some clusters may be leaked, "
345 "run 'qemu-img check -r' on the image "
346 "file to fix.");
347 if (need_update_header != NULL) {
348 /* Updating is needed to drop invalid bitmap extension. */
349 *need_update_header = true;
351 break;
354 ret = bdrv_pread(bs->file, offset, &bitmaps_ext, ext.len);
355 if (ret < 0) {
356 error_setg_errno(errp, -ret, "bitmaps_ext: "
357 "Could not read ext header");
358 return ret;
361 if (bitmaps_ext.reserved32 != 0) {
362 error_setg_errno(errp, -ret, "bitmaps_ext: "
363 "Reserved field is not zero");
364 return -EINVAL;
367 bitmaps_ext.nb_bitmaps = be32_to_cpu(bitmaps_ext.nb_bitmaps);
368 bitmaps_ext.bitmap_directory_size =
369 be64_to_cpu(bitmaps_ext.bitmap_directory_size);
370 bitmaps_ext.bitmap_directory_offset =
371 be64_to_cpu(bitmaps_ext.bitmap_directory_offset);
373 if (bitmaps_ext.nb_bitmaps > QCOW2_MAX_BITMAPS) {
374 error_setg(errp,
375 "bitmaps_ext: Image has %" PRIu32 " bitmaps, "
376 "exceeding the QEMU supported maximum of %d",
377 bitmaps_ext.nb_bitmaps, QCOW2_MAX_BITMAPS);
378 return -EINVAL;
381 if (bitmaps_ext.nb_bitmaps == 0) {
382 error_setg(errp, "found bitmaps extension with zero bitmaps");
383 return -EINVAL;
386 if (offset_into_cluster(s, bitmaps_ext.bitmap_directory_offset)) {
387 error_setg(errp, "bitmaps_ext: "
388 "invalid bitmap directory offset");
389 return -EINVAL;
392 if (bitmaps_ext.bitmap_directory_size >
393 QCOW2_MAX_BITMAP_DIRECTORY_SIZE) {
394 error_setg(errp, "bitmaps_ext: "
395 "bitmap directory size (%" PRIu64 ") exceeds "
396 "the maximum supported size (%d)",
397 bitmaps_ext.bitmap_directory_size,
398 QCOW2_MAX_BITMAP_DIRECTORY_SIZE);
399 return -EINVAL;
402 s->nb_bitmaps = bitmaps_ext.nb_bitmaps;
403 s->bitmap_directory_offset =
404 bitmaps_ext.bitmap_directory_offset;
405 s->bitmap_directory_size =
406 bitmaps_ext.bitmap_directory_size;
408 #ifdef DEBUG_EXT
409 printf("Qcow2: Got bitmaps extension: "
410 "offset=%" PRIu64 " nb_bitmaps=%" PRIu32 "\n",
411 s->bitmap_directory_offset, s->nb_bitmaps);
412 #endif
413 break;
415 case QCOW2_EXT_MAGIC_DATA_FILE:
417 s->image_data_file = g_malloc0(ext.len + 1);
418 ret = bdrv_pread(bs->file, offset, s->image_data_file, ext.len);
419 if (ret < 0) {
420 error_setg_errno(errp, -ret,
421 "ERROR: Could not read data file name");
422 return ret;
424 #ifdef DEBUG_EXT
425 printf("Qcow2: Got external data file %s\n", s->image_data_file);
426 #endif
427 break;
430 default:
431 /* unknown magic - save it in case we need to rewrite the header */
432 /* If you add a new feature, make sure to also update the fast
433 * path of qcow2_make_empty() to deal with it. */
435 Qcow2UnknownHeaderExtension *uext;
437 uext = g_malloc0(sizeof(*uext) + ext.len);
438 uext->magic = ext.magic;
439 uext->len = ext.len;
440 QLIST_INSERT_HEAD(&s->unknown_header_ext, uext, next);
442 ret = bdrv_pread(bs->file, offset , uext->data, uext->len);
443 if (ret < 0) {
444 error_setg_errno(errp, -ret, "ERROR: unknown extension: "
445 "Could not read data");
446 return ret;
449 break;
452 offset += ((ext.len + 7) & ~7);
455 return 0;
458 static void cleanup_unknown_header_ext(BlockDriverState *bs)
460 BDRVQcow2State *s = bs->opaque;
461 Qcow2UnknownHeaderExtension *uext, *next;
463 QLIST_FOREACH_SAFE(uext, &s->unknown_header_ext, next, next) {
464 QLIST_REMOVE(uext, next);
465 g_free(uext);
469 static void report_unsupported_feature(Error **errp, Qcow2Feature *table,
470 uint64_t mask)
472 g_autoptr(GString) features = g_string_sized_new(60);
474 while (table && table->name[0] != '\0') {
475 if (table->type == QCOW2_FEAT_TYPE_INCOMPATIBLE) {
476 if (mask & (1ULL << table->bit)) {
477 if (features->len > 0) {
478 g_string_append(features, ", ");
480 g_string_append_printf(features, "%.46s", table->name);
481 mask &= ~(1ULL << table->bit);
484 table++;
487 if (mask) {
488 if (features->len > 0) {
489 g_string_append(features, ", ");
491 g_string_append_printf(features,
492 "Unknown incompatible feature: %" PRIx64, mask);
495 error_setg(errp, "Unsupported qcow2 feature(s): %s", features->str);
499 * Sets the dirty bit and flushes afterwards if necessary.
501 * The incompatible_features bit is only set if the image file header was
502 * updated successfully. Therefore it is not required to check the return
503 * value of this function.
505 int qcow2_mark_dirty(BlockDriverState *bs)
507 BDRVQcow2State *s = bs->opaque;
508 uint64_t val;
509 int ret;
511 assert(s->qcow_version >= 3);
513 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
514 return 0; /* already dirty */
517 val = cpu_to_be64(s->incompatible_features | QCOW2_INCOMPAT_DIRTY);
518 ret = bdrv_pwrite(bs->file, offsetof(QCowHeader, incompatible_features),
519 &val, sizeof(val));
520 if (ret < 0) {
521 return ret;
523 ret = bdrv_flush(bs->file->bs);
524 if (ret < 0) {
525 return ret;
528 /* Only treat image as dirty if the header was updated successfully */
529 s->incompatible_features |= QCOW2_INCOMPAT_DIRTY;
530 return 0;
534 * Clears the dirty bit and flushes before if necessary. Only call this
535 * function when there are no pending requests, it does not guard against
536 * concurrent requests dirtying the image.
538 static int qcow2_mark_clean(BlockDriverState *bs)
540 BDRVQcow2State *s = bs->opaque;
542 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
543 int ret;
545 s->incompatible_features &= ~QCOW2_INCOMPAT_DIRTY;
547 ret = qcow2_flush_caches(bs);
548 if (ret < 0) {
549 return ret;
552 return qcow2_update_header(bs);
554 return 0;
558 * Marks the image as corrupt.
560 int qcow2_mark_corrupt(BlockDriverState *bs)
562 BDRVQcow2State *s = bs->opaque;
564 s->incompatible_features |= QCOW2_INCOMPAT_CORRUPT;
565 return qcow2_update_header(bs);
569 * Marks the image as consistent, i.e., unsets the corrupt bit, and flushes
570 * before if necessary.
572 int qcow2_mark_consistent(BlockDriverState *bs)
574 BDRVQcow2State *s = bs->opaque;
576 if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
577 int ret = qcow2_flush_caches(bs);
578 if (ret < 0) {
579 return ret;
582 s->incompatible_features &= ~QCOW2_INCOMPAT_CORRUPT;
583 return qcow2_update_header(bs);
585 return 0;
588 static void qcow2_add_check_result(BdrvCheckResult *out,
589 const BdrvCheckResult *src,
590 bool set_allocation_info)
592 out->corruptions += src->corruptions;
593 out->leaks += src->leaks;
594 out->check_errors += src->check_errors;
595 out->corruptions_fixed += src->corruptions_fixed;
596 out->leaks_fixed += src->leaks_fixed;
598 if (set_allocation_info) {
599 out->image_end_offset = src->image_end_offset;
600 out->bfi = src->bfi;
604 static int coroutine_fn qcow2_co_check_locked(BlockDriverState *bs,
605 BdrvCheckResult *result,
606 BdrvCheckMode fix)
608 BdrvCheckResult snapshot_res = {};
609 BdrvCheckResult refcount_res = {};
610 int ret;
612 memset(result, 0, sizeof(*result));
614 ret = qcow2_check_read_snapshot_table(bs, &snapshot_res, fix);
615 if (ret < 0) {
616 qcow2_add_check_result(result, &snapshot_res, false);
617 return ret;
620 ret = qcow2_check_refcounts(bs, &refcount_res, fix);
621 qcow2_add_check_result(result, &refcount_res, true);
622 if (ret < 0) {
623 qcow2_add_check_result(result, &snapshot_res, false);
624 return ret;
627 ret = qcow2_check_fix_snapshot_table(bs, &snapshot_res, fix);
628 qcow2_add_check_result(result, &snapshot_res, false);
629 if (ret < 0) {
630 return ret;
633 if (fix && result->check_errors == 0 && result->corruptions == 0) {
634 ret = qcow2_mark_clean(bs);
635 if (ret < 0) {
636 return ret;
638 return qcow2_mark_consistent(bs);
640 return ret;
643 static int coroutine_fn qcow2_co_check(BlockDriverState *bs,
644 BdrvCheckResult *result,
645 BdrvCheckMode fix)
647 BDRVQcow2State *s = bs->opaque;
648 int ret;
650 qemu_co_mutex_lock(&s->lock);
651 ret = qcow2_co_check_locked(bs, result, fix);
652 qemu_co_mutex_unlock(&s->lock);
653 return ret;
656 int qcow2_validate_table(BlockDriverState *bs, uint64_t offset,
657 uint64_t entries, size_t entry_len,
658 int64_t max_size_bytes, const char *table_name,
659 Error **errp)
661 BDRVQcow2State *s = bs->opaque;
663 if (entries > max_size_bytes / entry_len) {
664 error_setg(errp, "%s too large", table_name);
665 return -EFBIG;
668 /* Use signed INT64_MAX as the maximum even for uint64_t header fields,
669 * because values will be passed to qemu functions taking int64_t. */
670 if ((INT64_MAX - entries * entry_len < offset) ||
671 (offset_into_cluster(s, offset) != 0)) {
672 error_setg(errp, "%s offset invalid", table_name);
673 return -EINVAL;
676 return 0;
679 static const char *const mutable_opts[] = {
680 QCOW2_OPT_LAZY_REFCOUNTS,
681 QCOW2_OPT_DISCARD_REQUEST,
682 QCOW2_OPT_DISCARD_SNAPSHOT,
683 QCOW2_OPT_DISCARD_OTHER,
684 QCOW2_OPT_OVERLAP,
685 QCOW2_OPT_OVERLAP_TEMPLATE,
686 QCOW2_OPT_OVERLAP_MAIN_HEADER,
687 QCOW2_OPT_OVERLAP_ACTIVE_L1,
688 QCOW2_OPT_OVERLAP_ACTIVE_L2,
689 QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
690 QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
691 QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
692 QCOW2_OPT_OVERLAP_INACTIVE_L1,
693 QCOW2_OPT_OVERLAP_INACTIVE_L2,
694 QCOW2_OPT_OVERLAP_BITMAP_DIRECTORY,
695 QCOW2_OPT_CACHE_SIZE,
696 QCOW2_OPT_L2_CACHE_SIZE,
697 QCOW2_OPT_L2_CACHE_ENTRY_SIZE,
698 QCOW2_OPT_REFCOUNT_CACHE_SIZE,
699 QCOW2_OPT_CACHE_CLEAN_INTERVAL,
700 NULL
703 static QemuOptsList qcow2_runtime_opts = {
704 .name = "qcow2",
705 .head = QTAILQ_HEAD_INITIALIZER(qcow2_runtime_opts.head),
706 .desc = {
708 .name = QCOW2_OPT_LAZY_REFCOUNTS,
709 .type = QEMU_OPT_BOOL,
710 .help = "Postpone refcount updates",
713 .name = QCOW2_OPT_DISCARD_REQUEST,
714 .type = QEMU_OPT_BOOL,
715 .help = "Pass guest discard requests to the layer below",
718 .name = QCOW2_OPT_DISCARD_SNAPSHOT,
719 .type = QEMU_OPT_BOOL,
720 .help = "Generate discard requests when snapshot related space "
721 "is freed",
724 .name = QCOW2_OPT_DISCARD_OTHER,
725 .type = QEMU_OPT_BOOL,
726 .help = "Generate discard requests when other clusters are freed",
729 .name = QCOW2_OPT_OVERLAP,
730 .type = QEMU_OPT_STRING,
731 .help = "Selects which overlap checks to perform from a range of "
732 "templates (none, constant, cached, all)",
735 .name = QCOW2_OPT_OVERLAP_TEMPLATE,
736 .type = QEMU_OPT_STRING,
737 .help = "Selects which overlap checks to perform from a range of "
738 "templates (none, constant, cached, all)",
741 .name = QCOW2_OPT_OVERLAP_MAIN_HEADER,
742 .type = QEMU_OPT_BOOL,
743 .help = "Check for unintended writes into the main qcow2 header",
746 .name = QCOW2_OPT_OVERLAP_ACTIVE_L1,
747 .type = QEMU_OPT_BOOL,
748 .help = "Check for unintended writes into the active L1 table",
751 .name = QCOW2_OPT_OVERLAP_ACTIVE_L2,
752 .type = QEMU_OPT_BOOL,
753 .help = "Check for unintended writes into an active L2 table",
756 .name = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
757 .type = QEMU_OPT_BOOL,
758 .help = "Check for unintended writes into the refcount table",
761 .name = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
762 .type = QEMU_OPT_BOOL,
763 .help = "Check for unintended writes into a refcount block",
766 .name = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
767 .type = QEMU_OPT_BOOL,
768 .help = "Check for unintended writes into the snapshot table",
771 .name = QCOW2_OPT_OVERLAP_INACTIVE_L1,
772 .type = QEMU_OPT_BOOL,
773 .help = "Check for unintended writes into an inactive L1 table",
776 .name = QCOW2_OPT_OVERLAP_INACTIVE_L2,
777 .type = QEMU_OPT_BOOL,
778 .help = "Check for unintended writes into an inactive L2 table",
781 .name = QCOW2_OPT_OVERLAP_BITMAP_DIRECTORY,
782 .type = QEMU_OPT_BOOL,
783 .help = "Check for unintended writes into the bitmap directory",
786 .name = QCOW2_OPT_CACHE_SIZE,
787 .type = QEMU_OPT_SIZE,
788 .help = "Maximum combined metadata (L2 tables and refcount blocks) "
789 "cache size",
792 .name = QCOW2_OPT_L2_CACHE_SIZE,
793 .type = QEMU_OPT_SIZE,
794 .help = "Maximum L2 table cache size",
797 .name = QCOW2_OPT_L2_CACHE_ENTRY_SIZE,
798 .type = QEMU_OPT_SIZE,
799 .help = "Size of each entry in the L2 cache",
802 .name = QCOW2_OPT_REFCOUNT_CACHE_SIZE,
803 .type = QEMU_OPT_SIZE,
804 .help = "Maximum refcount block cache size",
807 .name = QCOW2_OPT_CACHE_CLEAN_INTERVAL,
808 .type = QEMU_OPT_NUMBER,
809 .help = "Clean unused cache entries after this time (in seconds)",
811 BLOCK_CRYPTO_OPT_DEF_KEY_SECRET("encrypt.",
812 "ID of secret providing qcow2 AES key or LUKS passphrase"),
813 { /* end of list */ }
817 static const char *overlap_bool_option_names[QCOW2_OL_MAX_BITNR] = {
818 [QCOW2_OL_MAIN_HEADER_BITNR] = QCOW2_OPT_OVERLAP_MAIN_HEADER,
819 [QCOW2_OL_ACTIVE_L1_BITNR] = QCOW2_OPT_OVERLAP_ACTIVE_L1,
820 [QCOW2_OL_ACTIVE_L2_BITNR] = QCOW2_OPT_OVERLAP_ACTIVE_L2,
821 [QCOW2_OL_REFCOUNT_TABLE_BITNR] = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
822 [QCOW2_OL_REFCOUNT_BLOCK_BITNR] = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
823 [QCOW2_OL_SNAPSHOT_TABLE_BITNR] = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
824 [QCOW2_OL_INACTIVE_L1_BITNR] = QCOW2_OPT_OVERLAP_INACTIVE_L1,
825 [QCOW2_OL_INACTIVE_L2_BITNR] = QCOW2_OPT_OVERLAP_INACTIVE_L2,
826 [QCOW2_OL_BITMAP_DIRECTORY_BITNR] = QCOW2_OPT_OVERLAP_BITMAP_DIRECTORY,
829 static void cache_clean_timer_cb(void *opaque)
831 BlockDriverState *bs = opaque;
832 BDRVQcow2State *s = bs->opaque;
833 qcow2_cache_clean_unused(s->l2_table_cache);
834 qcow2_cache_clean_unused(s->refcount_block_cache);
835 timer_mod(s->cache_clean_timer, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) +
836 (int64_t) s->cache_clean_interval * 1000);
839 static void cache_clean_timer_init(BlockDriverState *bs, AioContext *context)
841 BDRVQcow2State *s = bs->opaque;
842 if (s->cache_clean_interval > 0) {
843 s->cache_clean_timer = aio_timer_new(context, QEMU_CLOCK_VIRTUAL,
844 SCALE_MS, cache_clean_timer_cb,
845 bs);
846 timer_mod(s->cache_clean_timer, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) +
847 (int64_t) s->cache_clean_interval * 1000);
851 static void cache_clean_timer_del(BlockDriverState *bs)
853 BDRVQcow2State *s = bs->opaque;
854 if (s->cache_clean_timer) {
855 timer_del(s->cache_clean_timer);
856 timer_free(s->cache_clean_timer);
857 s->cache_clean_timer = NULL;
861 static void qcow2_detach_aio_context(BlockDriverState *bs)
863 cache_clean_timer_del(bs);
866 static void qcow2_attach_aio_context(BlockDriverState *bs,
867 AioContext *new_context)
869 cache_clean_timer_init(bs, new_context);
872 static void read_cache_sizes(BlockDriverState *bs, QemuOpts *opts,
873 uint64_t *l2_cache_size,
874 uint64_t *l2_cache_entry_size,
875 uint64_t *refcount_cache_size, Error **errp)
877 BDRVQcow2State *s = bs->opaque;
878 uint64_t combined_cache_size, l2_cache_max_setting;
879 bool l2_cache_size_set, refcount_cache_size_set, combined_cache_size_set;
880 bool l2_cache_entry_size_set;
881 int min_refcount_cache = MIN_REFCOUNT_CACHE_SIZE * s->cluster_size;
882 uint64_t virtual_disk_size = bs->total_sectors * BDRV_SECTOR_SIZE;
883 uint64_t max_l2_entries = DIV_ROUND_UP(virtual_disk_size, s->cluster_size);
884 /* An L2 table is always one cluster in size so the max cache size
885 * should be a multiple of the cluster size. */
886 uint64_t max_l2_cache = ROUND_UP(max_l2_entries * sizeof(uint64_t),
887 s->cluster_size);
889 combined_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_CACHE_SIZE);
890 l2_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_L2_CACHE_SIZE);
891 refcount_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
892 l2_cache_entry_size_set = qemu_opt_get(opts, QCOW2_OPT_L2_CACHE_ENTRY_SIZE);
894 combined_cache_size = qemu_opt_get_size(opts, QCOW2_OPT_CACHE_SIZE, 0);
895 l2_cache_max_setting = qemu_opt_get_size(opts, QCOW2_OPT_L2_CACHE_SIZE,
896 DEFAULT_L2_CACHE_MAX_SIZE);
897 *refcount_cache_size = qemu_opt_get_size(opts,
898 QCOW2_OPT_REFCOUNT_CACHE_SIZE, 0);
900 *l2_cache_entry_size = qemu_opt_get_size(
901 opts, QCOW2_OPT_L2_CACHE_ENTRY_SIZE, s->cluster_size);
903 *l2_cache_size = MIN(max_l2_cache, l2_cache_max_setting);
905 if (combined_cache_size_set) {
906 if (l2_cache_size_set && refcount_cache_size_set) {
907 error_setg(errp, QCOW2_OPT_CACHE_SIZE ", " QCOW2_OPT_L2_CACHE_SIZE
908 " and " QCOW2_OPT_REFCOUNT_CACHE_SIZE " may not be set "
909 "at the same time");
910 return;
911 } else if (l2_cache_size_set &&
912 (l2_cache_max_setting > combined_cache_size)) {
913 error_setg(errp, QCOW2_OPT_L2_CACHE_SIZE " may not exceed "
914 QCOW2_OPT_CACHE_SIZE);
915 return;
916 } else if (*refcount_cache_size > combined_cache_size) {
917 error_setg(errp, QCOW2_OPT_REFCOUNT_CACHE_SIZE " may not exceed "
918 QCOW2_OPT_CACHE_SIZE);
919 return;
922 if (l2_cache_size_set) {
923 *refcount_cache_size = combined_cache_size - *l2_cache_size;
924 } else if (refcount_cache_size_set) {
925 *l2_cache_size = combined_cache_size - *refcount_cache_size;
926 } else {
927 /* Assign as much memory as possible to the L2 cache, and
928 * use the remainder for the refcount cache */
929 if (combined_cache_size >= max_l2_cache + min_refcount_cache) {
930 *l2_cache_size = max_l2_cache;
931 *refcount_cache_size = combined_cache_size - *l2_cache_size;
932 } else {
933 *refcount_cache_size =
934 MIN(combined_cache_size, min_refcount_cache);
935 *l2_cache_size = combined_cache_size - *refcount_cache_size;
941 * If the L2 cache is not enough to cover the whole disk then
942 * default to 4KB entries. Smaller entries reduce the cost of
943 * loads and evictions and increase I/O performance.
945 if (*l2_cache_size < max_l2_cache && !l2_cache_entry_size_set) {
946 *l2_cache_entry_size = MIN(s->cluster_size, 4096);
949 /* l2_cache_size and refcount_cache_size are ensured to have at least
950 * their minimum values in qcow2_update_options_prepare() */
952 if (*l2_cache_entry_size < (1 << MIN_CLUSTER_BITS) ||
953 *l2_cache_entry_size > s->cluster_size ||
954 !is_power_of_2(*l2_cache_entry_size)) {
955 error_setg(errp, "L2 cache entry size must be a power of two "
956 "between %d and the cluster size (%d)",
957 1 << MIN_CLUSTER_BITS, s->cluster_size);
958 return;
962 typedef struct Qcow2ReopenState {
963 Qcow2Cache *l2_table_cache;
964 Qcow2Cache *refcount_block_cache;
965 int l2_slice_size; /* Number of entries in a slice of the L2 table */
966 bool use_lazy_refcounts;
967 int overlap_check;
968 bool discard_passthrough[QCOW2_DISCARD_MAX];
969 uint64_t cache_clean_interval;
970 QCryptoBlockOpenOptions *crypto_opts; /* Disk encryption runtime options */
971 } Qcow2ReopenState;
973 static int qcow2_update_options_prepare(BlockDriverState *bs,
974 Qcow2ReopenState *r,
975 QDict *options, int flags,
976 Error **errp)
978 BDRVQcow2State *s = bs->opaque;
979 QemuOpts *opts = NULL;
980 const char *opt_overlap_check, *opt_overlap_check_template;
981 int overlap_check_template = 0;
982 uint64_t l2_cache_size, l2_cache_entry_size, refcount_cache_size;
983 int i;
984 const char *encryptfmt;
985 QDict *encryptopts = NULL;
986 Error *local_err = NULL;
987 int ret;
989 qdict_extract_subqdict(options, &encryptopts, "encrypt.");
990 encryptfmt = qdict_get_try_str(encryptopts, "format");
992 opts = qemu_opts_create(&qcow2_runtime_opts, NULL, 0, &error_abort);
993 qemu_opts_absorb_qdict(opts, options, &local_err);
994 if (local_err) {
995 error_propagate(errp, local_err);
996 ret = -EINVAL;
997 goto fail;
1000 /* get L2 table/refcount block cache size from command line options */
1001 read_cache_sizes(bs, opts, &l2_cache_size, &l2_cache_entry_size,
1002 &refcount_cache_size, &local_err);
1003 if (local_err) {
1004 error_propagate(errp, local_err);
1005 ret = -EINVAL;
1006 goto fail;
1009 l2_cache_size /= l2_cache_entry_size;
1010 if (l2_cache_size < MIN_L2_CACHE_SIZE) {
1011 l2_cache_size = MIN_L2_CACHE_SIZE;
1013 if (l2_cache_size > INT_MAX) {
1014 error_setg(errp, "L2 cache size too big");
1015 ret = -EINVAL;
1016 goto fail;
1019 refcount_cache_size /= s->cluster_size;
1020 if (refcount_cache_size < MIN_REFCOUNT_CACHE_SIZE) {
1021 refcount_cache_size = MIN_REFCOUNT_CACHE_SIZE;
1023 if (refcount_cache_size > INT_MAX) {
1024 error_setg(errp, "Refcount cache size too big");
1025 ret = -EINVAL;
1026 goto fail;
1029 /* alloc new L2 table/refcount block cache, flush old one */
1030 if (s->l2_table_cache) {
1031 ret = qcow2_cache_flush(bs, s->l2_table_cache);
1032 if (ret) {
1033 error_setg_errno(errp, -ret, "Failed to flush the L2 table cache");
1034 goto fail;
1038 if (s->refcount_block_cache) {
1039 ret = qcow2_cache_flush(bs, s->refcount_block_cache);
1040 if (ret) {
1041 error_setg_errno(errp, -ret,
1042 "Failed to flush the refcount block cache");
1043 goto fail;
1047 r->l2_slice_size = l2_cache_entry_size / sizeof(uint64_t);
1048 r->l2_table_cache = qcow2_cache_create(bs, l2_cache_size,
1049 l2_cache_entry_size);
1050 r->refcount_block_cache = qcow2_cache_create(bs, refcount_cache_size,
1051 s->cluster_size);
1052 if (r->l2_table_cache == NULL || r->refcount_block_cache == NULL) {
1053 error_setg(errp, "Could not allocate metadata caches");
1054 ret = -ENOMEM;
1055 goto fail;
1058 /* New interval for cache cleanup timer */
1059 r->cache_clean_interval =
1060 qemu_opt_get_number(opts, QCOW2_OPT_CACHE_CLEAN_INTERVAL,
1061 DEFAULT_CACHE_CLEAN_INTERVAL);
1062 #ifndef CONFIG_LINUX
1063 if (r->cache_clean_interval != 0) {
1064 error_setg(errp, QCOW2_OPT_CACHE_CLEAN_INTERVAL
1065 " not supported on this host");
1066 ret = -EINVAL;
1067 goto fail;
1069 #endif
1070 if (r->cache_clean_interval > UINT_MAX) {
1071 error_setg(errp, "Cache clean interval too big");
1072 ret = -EINVAL;
1073 goto fail;
1076 /* lazy-refcounts; flush if going from enabled to disabled */
1077 r->use_lazy_refcounts = qemu_opt_get_bool(opts, QCOW2_OPT_LAZY_REFCOUNTS,
1078 (s->compatible_features & QCOW2_COMPAT_LAZY_REFCOUNTS));
1079 if (r->use_lazy_refcounts && s->qcow_version < 3) {
1080 error_setg(errp, "Lazy refcounts require a qcow2 image with at least "
1081 "qemu 1.1 compatibility level");
1082 ret = -EINVAL;
1083 goto fail;
1086 if (s->use_lazy_refcounts && !r->use_lazy_refcounts) {
1087 ret = qcow2_mark_clean(bs);
1088 if (ret < 0) {
1089 error_setg_errno(errp, -ret, "Failed to disable lazy refcounts");
1090 goto fail;
1094 /* Overlap check options */
1095 opt_overlap_check = qemu_opt_get(opts, QCOW2_OPT_OVERLAP);
1096 opt_overlap_check_template = qemu_opt_get(opts, QCOW2_OPT_OVERLAP_TEMPLATE);
1097 if (opt_overlap_check_template && opt_overlap_check &&
1098 strcmp(opt_overlap_check_template, opt_overlap_check))
1100 error_setg(errp, "Conflicting values for qcow2 options '"
1101 QCOW2_OPT_OVERLAP "' ('%s') and '" QCOW2_OPT_OVERLAP_TEMPLATE
1102 "' ('%s')", opt_overlap_check, opt_overlap_check_template);
1103 ret = -EINVAL;
1104 goto fail;
1106 if (!opt_overlap_check) {
1107 opt_overlap_check = opt_overlap_check_template ?: "cached";
1110 if (!strcmp(opt_overlap_check, "none")) {
1111 overlap_check_template = 0;
1112 } else if (!strcmp(opt_overlap_check, "constant")) {
1113 overlap_check_template = QCOW2_OL_CONSTANT;
1114 } else if (!strcmp(opt_overlap_check, "cached")) {
1115 overlap_check_template = QCOW2_OL_CACHED;
1116 } else if (!strcmp(opt_overlap_check, "all")) {
1117 overlap_check_template = QCOW2_OL_ALL;
1118 } else {
1119 error_setg(errp, "Unsupported value '%s' for qcow2 option "
1120 "'overlap-check'. Allowed are any of the following: "
1121 "none, constant, cached, all", opt_overlap_check);
1122 ret = -EINVAL;
1123 goto fail;
1126 r->overlap_check = 0;
1127 for (i = 0; i < QCOW2_OL_MAX_BITNR; i++) {
1128 /* overlap-check defines a template bitmask, but every flag may be
1129 * overwritten through the associated boolean option */
1130 r->overlap_check |=
1131 qemu_opt_get_bool(opts, overlap_bool_option_names[i],
1132 overlap_check_template & (1 << i)) << i;
1135 r->discard_passthrough[QCOW2_DISCARD_NEVER] = false;
1136 r->discard_passthrough[QCOW2_DISCARD_ALWAYS] = true;
1137 r->discard_passthrough[QCOW2_DISCARD_REQUEST] =
1138 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_REQUEST,
1139 flags & BDRV_O_UNMAP);
1140 r->discard_passthrough[QCOW2_DISCARD_SNAPSHOT] =
1141 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_SNAPSHOT, true);
1142 r->discard_passthrough[QCOW2_DISCARD_OTHER] =
1143 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_OTHER, false);
1145 switch (s->crypt_method_header) {
1146 case QCOW_CRYPT_NONE:
1147 if (encryptfmt) {
1148 error_setg(errp, "No encryption in image header, but options "
1149 "specified format '%s'", encryptfmt);
1150 ret = -EINVAL;
1151 goto fail;
1153 break;
1155 case QCOW_CRYPT_AES:
1156 if (encryptfmt && !g_str_equal(encryptfmt, "aes")) {
1157 error_setg(errp,
1158 "Header reported 'aes' encryption format but "
1159 "options specify '%s'", encryptfmt);
1160 ret = -EINVAL;
1161 goto fail;
1163 qdict_put_str(encryptopts, "format", "qcow");
1164 r->crypto_opts = block_crypto_open_opts_init(encryptopts, errp);
1165 break;
1167 case QCOW_CRYPT_LUKS:
1168 if (encryptfmt && !g_str_equal(encryptfmt, "luks")) {
1169 error_setg(errp,
1170 "Header reported 'luks' encryption format but "
1171 "options specify '%s'", encryptfmt);
1172 ret = -EINVAL;
1173 goto fail;
1175 qdict_put_str(encryptopts, "format", "luks");
1176 r->crypto_opts = block_crypto_open_opts_init(encryptopts, errp);
1177 break;
1179 default:
1180 error_setg(errp, "Unsupported encryption method %d",
1181 s->crypt_method_header);
1182 break;
1184 if (s->crypt_method_header != QCOW_CRYPT_NONE && !r->crypto_opts) {
1185 ret = -EINVAL;
1186 goto fail;
1189 ret = 0;
1190 fail:
1191 qobject_unref(encryptopts);
1192 qemu_opts_del(opts);
1193 opts = NULL;
1194 return ret;
1197 static void qcow2_update_options_commit(BlockDriverState *bs,
1198 Qcow2ReopenState *r)
1200 BDRVQcow2State *s = bs->opaque;
1201 int i;
1203 if (s->l2_table_cache) {
1204 qcow2_cache_destroy(s->l2_table_cache);
1206 if (s->refcount_block_cache) {
1207 qcow2_cache_destroy(s->refcount_block_cache);
1209 s->l2_table_cache = r->l2_table_cache;
1210 s->refcount_block_cache = r->refcount_block_cache;
1211 s->l2_slice_size = r->l2_slice_size;
1213 s->overlap_check = r->overlap_check;
1214 s->use_lazy_refcounts = r->use_lazy_refcounts;
1216 for (i = 0; i < QCOW2_DISCARD_MAX; i++) {
1217 s->discard_passthrough[i] = r->discard_passthrough[i];
1220 if (s->cache_clean_interval != r->cache_clean_interval) {
1221 cache_clean_timer_del(bs);
1222 s->cache_clean_interval = r->cache_clean_interval;
1223 cache_clean_timer_init(bs, bdrv_get_aio_context(bs));
1226 qapi_free_QCryptoBlockOpenOptions(s->crypto_opts);
1227 s->crypto_opts = r->crypto_opts;
1230 static void qcow2_update_options_abort(BlockDriverState *bs,
1231 Qcow2ReopenState *r)
1233 if (r->l2_table_cache) {
1234 qcow2_cache_destroy(r->l2_table_cache);
1236 if (r->refcount_block_cache) {
1237 qcow2_cache_destroy(r->refcount_block_cache);
1239 qapi_free_QCryptoBlockOpenOptions(r->crypto_opts);
1242 static int qcow2_update_options(BlockDriverState *bs, QDict *options,
1243 int flags, Error **errp)
1245 Qcow2ReopenState r = {};
1246 int ret;
1248 ret = qcow2_update_options_prepare(bs, &r, options, flags, errp);
1249 if (ret >= 0) {
1250 qcow2_update_options_commit(bs, &r);
1251 } else {
1252 qcow2_update_options_abort(bs, &r);
1255 return ret;
1258 static int validate_compression_type(BDRVQcow2State *s, Error **errp)
1260 switch (s->compression_type) {
1261 case QCOW2_COMPRESSION_TYPE_ZLIB:
1262 #ifdef CONFIG_ZSTD
1263 case QCOW2_COMPRESSION_TYPE_ZSTD:
1264 #endif
1265 break;
1267 default:
1268 error_setg(errp, "qcow2: unknown compression type: %u",
1269 s->compression_type);
1270 return -ENOTSUP;
1274 * if the compression type differs from QCOW2_COMPRESSION_TYPE_ZLIB
1275 * the incompatible feature flag must be set
1277 if (s->compression_type == QCOW2_COMPRESSION_TYPE_ZLIB) {
1278 if (s->incompatible_features & QCOW2_INCOMPAT_COMPRESSION) {
1279 error_setg(errp, "qcow2: Compression type incompatible feature "
1280 "bit must not be set");
1281 return -EINVAL;
1283 } else {
1284 if (!(s->incompatible_features & QCOW2_INCOMPAT_COMPRESSION)) {
1285 error_setg(errp, "qcow2: Compression type incompatible feature "
1286 "bit must be set");
1287 return -EINVAL;
1291 return 0;
1294 /* Called with s->lock held. */
1295 static int coroutine_fn qcow2_do_open(BlockDriverState *bs, QDict *options,
1296 int flags, Error **errp)
1298 BDRVQcow2State *s = bs->opaque;
1299 unsigned int len, i;
1300 int ret = 0;
1301 QCowHeader header;
1302 Error *local_err = NULL;
1303 uint64_t ext_end;
1304 uint64_t l1_vm_state_index;
1305 bool update_header = false;
1307 ret = bdrv_pread(bs->file, 0, &header, sizeof(header));
1308 if (ret < 0) {
1309 error_setg_errno(errp, -ret, "Could not read qcow2 header");
1310 goto fail;
1312 header.magic = be32_to_cpu(header.magic);
1313 header.version = be32_to_cpu(header.version);
1314 header.backing_file_offset = be64_to_cpu(header.backing_file_offset);
1315 header.backing_file_size = be32_to_cpu(header.backing_file_size);
1316 header.size = be64_to_cpu(header.size);
1317 header.cluster_bits = be32_to_cpu(header.cluster_bits);
1318 header.crypt_method = be32_to_cpu(header.crypt_method);
1319 header.l1_table_offset = be64_to_cpu(header.l1_table_offset);
1320 header.l1_size = be32_to_cpu(header.l1_size);
1321 header.refcount_table_offset = be64_to_cpu(header.refcount_table_offset);
1322 header.refcount_table_clusters =
1323 be32_to_cpu(header.refcount_table_clusters);
1324 header.snapshots_offset = be64_to_cpu(header.snapshots_offset);
1325 header.nb_snapshots = be32_to_cpu(header.nb_snapshots);
1327 if (header.magic != QCOW_MAGIC) {
1328 error_setg(errp, "Image is not in qcow2 format");
1329 ret = -EINVAL;
1330 goto fail;
1332 if (header.version < 2 || header.version > 3) {
1333 error_setg(errp, "Unsupported qcow2 version %" PRIu32, header.version);
1334 ret = -ENOTSUP;
1335 goto fail;
1338 s->qcow_version = header.version;
1340 /* Initialise cluster size */
1341 if (header.cluster_bits < MIN_CLUSTER_BITS ||
1342 header.cluster_bits > MAX_CLUSTER_BITS) {
1343 error_setg(errp, "Unsupported cluster size: 2^%" PRIu32,
1344 header.cluster_bits);
1345 ret = -EINVAL;
1346 goto fail;
1349 s->cluster_bits = header.cluster_bits;
1350 s->cluster_size = 1 << s->cluster_bits;
1352 /* Initialise version 3 header fields */
1353 if (header.version == 2) {
1354 header.incompatible_features = 0;
1355 header.compatible_features = 0;
1356 header.autoclear_features = 0;
1357 header.refcount_order = 4;
1358 header.header_length = 72;
1359 } else {
1360 header.incompatible_features =
1361 be64_to_cpu(header.incompatible_features);
1362 header.compatible_features = be64_to_cpu(header.compatible_features);
1363 header.autoclear_features = be64_to_cpu(header.autoclear_features);
1364 header.refcount_order = be32_to_cpu(header.refcount_order);
1365 header.header_length = be32_to_cpu(header.header_length);
1367 if (header.header_length < 104) {
1368 error_setg(errp, "qcow2 header too short");
1369 ret = -EINVAL;
1370 goto fail;
1374 if (header.header_length > s->cluster_size) {
1375 error_setg(errp, "qcow2 header exceeds cluster size");
1376 ret = -EINVAL;
1377 goto fail;
1380 if (header.header_length > sizeof(header)) {
1381 s->unknown_header_fields_size = header.header_length - sizeof(header);
1382 s->unknown_header_fields = g_malloc(s->unknown_header_fields_size);
1383 ret = bdrv_pread(bs->file, sizeof(header), s->unknown_header_fields,
1384 s->unknown_header_fields_size);
1385 if (ret < 0) {
1386 error_setg_errno(errp, -ret, "Could not read unknown qcow2 header "
1387 "fields");
1388 goto fail;
1392 if (header.backing_file_offset > s->cluster_size) {
1393 error_setg(errp, "Invalid backing file offset");
1394 ret = -EINVAL;
1395 goto fail;
1398 if (header.backing_file_offset) {
1399 ext_end = header.backing_file_offset;
1400 } else {
1401 ext_end = 1 << header.cluster_bits;
1404 /* Handle feature bits */
1405 s->incompatible_features = header.incompatible_features;
1406 s->compatible_features = header.compatible_features;
1407 s->autoclear_features = header.autoclear_features;
1410 * Handle compression type
1411 * Older qcow2 images don't contain the compression type header.
1412 * Distinguish them by the header length and use
1413 * the only valid (default) compression type in that case
1415 if (header.header_length > offsetof(QCowHeader, compression_type)) {
1416 s->compression_type = header.compression_type;
1417 } else {
1418 s->compression_type = QCOW2_COMPRESSION_TYPE_ZLIB;
1421 ret = validate_compression_type(s, errp);
1422 if (ret) {
1423 goto fail;
1426 if (s->incompatible_features & ~QCOW2_INCOMPAT_MASK) {
1427 void *feature_table = NULL;
1428 qcow2_read_extensions(bs, header.header_length, ext_end,
1429 &feature_table, flags, NULL, NULL);
1430 report_unsupported_feature(errp, feature_table,
1431 s->incompatible_features &
1432 ~QCOW2_INCOMPAT_MASK);
1433 ret = -ENOTSUP;
1434 g_free(feature_table);
1435 goto fail;
1438 if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
1439 /* Corrupt images may not be written to unless they are being repaired
1441 if ((flags & BDRV_O_RDWR) && !(flags & BDRV_O_CHECK)) {
1442 error_setg(errp, "qcow2: Image is corrupt; cannot be opened "
1443 "read/write");
1444 ret = -EACCES;
1445 goto fail;
1449 /* Check support for various header values */
1450 if (header.refcount_order > 6) {
1451 error_setg(errp, "Reference count entry width too large; may not "
1452 "exceed 64 bits");
1453 ret = -EINVAL;
1454 goto fail;
1456 s->refcount_order = header.refcount_order;
1457 s->refcount_bits = 1 << s->refcount_order;
1458 s->refcount_max = UINT64_C(1) << (s->refcount_bits - 1);
1459 s->refcount_max += s->refcount_max - 1;
1461 s->crypt_method_header = header.crypt_method;
1462 if (s->crypt_method_header) {
1463 if (bdrv_uses_whitelist() &&
1464 s->crypt_method_header == QCOW_CRYPT_AES) {
1465 error_setg(errp,
1466 "Use of AES-CBC encrypted qcow2 images is no longer "
1467 "supported in system emulators");
1468 error_append_hint(errp,
1469 "You can use 'qemu-img convert' to convert your "
1470 "image to an alternative supported format, such "
1471 "as unencrypted qcow2, or raw with the LUKS "
1472 "format instead.\n");
1473 ret = -ENOSYS;
1474 goto fail;
1477 if (s->crypt_method_header == QCOW_CRYPT_AES) {
1478 s->crypt_physical_offset = false;
1479 } else {
1480 /* Assuming LUKS and any future crypt methods we
1481 * add will all use physical offsets, due to the
1482 * fact that the alternative is insecure... */
1483 s->crypt_physical_offset = true;
1486 bs->encrypted = true;
1489 s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */
1490 s->l2_size = 1 << s->l2_bits;
1491 /* 2^(s->refcount_order - 3) is the refcount width in bytes */
1492 s->refcount_block_bits = s->cluster_bits - (s->refcount_order - 3);
1493 s->refcount_block_size = 1 << s->refcount_block_bits;
1494 bs->total_sectors = header.size / BDRV_SECTOR_SIZE;
1495 s->csize_shift = (62 - (s->cluster_bits - 8));
1496 s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;
1497 s->cluster_offset_mask = (1LL << s->csize_shift) - 1;
1499 s->refcount_table_offset = header.refcount_table_offset;
1500 s->refcount_table_size =
1501 header.refcount_table_clusters << (s->cluster_bits - 3);
1503 if (header.refcount_table_clusters == 0 && !(flags & BDRV_O_CHECK)) {
1504 error_setg(errp, "Image does not contain a reference count table");
1505 ret = -EINVAL;
1506 goto fail;
1509 ret = qcow2_validate_table(bs, s->refcount_table_offset,
1510 header.refcount_table_clusters,
1511 s->cluster_size, QCOW_MAX_REFTABLE_SIZE,
1512 "Reference count table", errp);
1513 if (ret < 0) {
1514 goto fail;
1517 if (!(flags & BDRV_O_CHECK)) {
1519 * The total size in bytes of the snapshot table is checked in
1520 * qcow2_read_snapshots() because the size of each snapshot is
1521 * variable and we don't know it yet.
1522 * Here we only check the offset and number of snapshots.
1524 ret = qcow2_validate_table(bs, header.snapshots_offset,
1525 header.nb_snapshots,
1526 sizeof(QCowSnapshotHeader),
1527 sizeof(QCowSnapshotHeader) *
1528 QCOW_MAX_SNAPSHOTS,
1529 "Snapshot table", errp);
1530 if (ret < 0) {
1531 goto fail;
1535 /* read the level 1 table */
1536 ret = qcow2_validate_table(bs, header.l1_table_offset,
1537 header.l1_size, sizeof(uint64_t),
1538 QCOW_MAX_L1_SIZE, "Active L1 table", errp);
1539 if (ret < 0) {
1540 goto fail;
1542 s->l1_size = header.l1_size;
1543 s->l1_table_offset = header.l1_table_offset;
1545 l1_vm_state_index = size_to_l1(s, header.size);
1546 if (l1_vm_state_index > INT_MAX) {
1547 error_setg(errp, "Image is too big");
1548 ret = -EFBIG;
1549 goto fail;
1551 s->l1_vm_state_index = l1_vm_state_index;
1553 /* the L1 table must contain at least enough entries to put
1554 header.size bytes */
1555 if (s->l1_size < s->l1_vm_state_index) {
1556 error_setg(errp, "L1 table is too small");
1557 ret = -EINVAL;
1558 goto fail;
1561 if (s->l1_size > 0) {
1562 s->l1_table = qemu_try_blockalign(bs->file->bs,
1563 s->l1_size * sizeof(uint64_t));
1564 if (s->l1_table == NULL) {
1565 error_setg(errp, "Could not allocate L1 table");
1566 ret = -ENOMEM;
1567 goto fail;
1569 ret = bdrv_pread(bs->file, s->l1_table_offset, s->l1_table,
1570 s->l1_size * sizeof(uint64_t));
1571 if (ret < 0) {
1572 error_setg_errno(errp, -ret, "Could not read L1 table");
1573 goto fail;
1575 for(i = 0;i < s->l1_size; i++) {
1576 s->l1_table[i] = be64_to_cpu(s->l1_table[i]);
1580 /* Parse driver-specific options */
1581 ret = qcow2_update_options(bs, options, flags, errp);
1582 if (ret < 0) {
1583 goto fail;
1586 s->flags = flags;
1588 ret = qcow2_refcount_init(bs);
1589 if (ret != 0) {
1590 error_setg_errno(errp, -ret, "Could not initialize refcount handling");
1591 goto fail;
1594 QLIST_INIT(&s->cluster_allocs);
1595 QTAILQ_INIT(&s->discards);
1597 /* read qcow2 extensions */
1598 if (qcow2_read_extensions(bs, header.header_length, ext_end, NULL,
1599 flags, &update_header, &local_err)) {
1600 error_propagate(errp, local_err);
1601 ret = -EINVAL;
1602 goto fail;
1605 /* Open external data file */
1606 s->data_file = bdrv_open_child(NULL, options, "data-file", bs,
1607 &child_of_bds, BDRV_CHILD_DATA,
1608 true, &local_err);
1609 if (local_err) {
1610 error_propagate(errp, local_err);
1611 ret = -EINVAL;
1612 goto fail;
1615 if (s->incompatible_features & QCOW2_INCOMPAT_DATA_FILE) {
1616 if (!s->data_file && s->image_data_file) {
1617 s->data_file = bdrv_open_child(s->image_data_file, options,
1618 "data-file", bs, &child_of_bds,
1619 BDRV_CHILD_DATA, false, errp);
1620 if (!s->data_file) {
1621 ret = -EINVAL;
1622 goto fail;
1625 if (!s->data_file) {
1626 error_setg(errp, "'data-file' is required for this image");
1627 ret = -EINVAL;
1628 goto fail;
1631 /* No data here */
1632 bs->file->role &= ~BDRV_CHILD_DATA;
1634 /* Must succeed because we have given up permissions if anything */
1635 bdrv_child_refresh_perms(bs, bs->file, &error_abort);
1636 } else {
1637 if (s->data_file) {
1638 error_setg(errp, "'data-file' can only be set for images with an "
1639 "external data file");
1640 ret = -EINVAL;
1641 goto fail;
1644 s->data_file = bs->file;
1646 if (data_file_is_raw(bs)) {
1647 error_setg(errp, "data-file-raw requires a data file");
1648 ret = -EINVAL;
1649 goto fail;
1653 /* qcow2_read_extension may have set up the crypto context
1654 * if the crypt method needs a header region, some methods
1655 * don't need header extensions, so must check here
1657 if (s->crypt_method_header && !s->crypto) {
1658 if (s->crypt_method_header == QCOW_CRYPT_AES) {
1659 unsigned int cflags = 0;
1660 if (flags & BDRV_O_NO_IO) {
1661 cflags |= QCRYPTO_BLOCK_OPEN_NO_IO;
1663 s->crypto = qcrypto_block_open(s->crypto_opts, "encrypt.",
1664 NULL, NULL, cflags,
1665 QCOW2_MAX_THREADS, errp);
1666 if (!s->crypto) {
1667 ret = -EINVAL;
1668 goto fail;
1670 } else if (!(flags & BDRV_O_NO_IO)) {
1671 error_setg(errp, "Missing CRYPTO header for crypt method %d",
1672 s->crypt_method_header);
1673 ret = -EINVAL;
1674 goto fail;
1678 /* read the backing file name */
1679 if (header.backing_file_offset != 0) {
1680 len = header.backing_file_size;
1681 if (len > MIN(1023, s->cluster_size - header.backing_file_offset) ||
1682 len >= sizeof(bs->backing_file)) {
1683 error_setg(errp, "Backing file name too long");
1684 ret = -EINVAL;
1685 goto fail;
1687 ret = bdrv_pread(bs->file, header.backing_file_offset,
1688 bs->auto_backing_file, len);
1689 if (ret < 0) {
1690 error_setg_errno(errp, -ret, "Could not read backing file name");
1691 goto fail;
1693 bs->auto_backing_file[len] = '\0';
1694 pstrcpy(bs->backing_file, sizeof(bs->backing_file),
1695 bs->auto_backing_file);
1696 s->image_backing_file = g_strdup(bs->auto_backing_file);
1700 * Internal snapshots; skip reading them in check mode, because
1701 * we do not need them then, and we do not want to abort because
1702 * of a broken table.
1704 if (!(flags & BDRV_O_CHECK)) {
1705 s->snapshots_offset = header.snapshots_offset;
1706 s->nb_snapshots = header.nb_snapshots;
1708 ret = qcow2_read_snapshots(bs, errp);
1709 if (ret < 0) {
1710 goto fail;
1714 /* Clear unknown autoclear feature bits */
1715 update_header |= s->autoclear_features & ~QCOW2_AUTOCLEAR_MASK;
1716 update_header =
1717 update_header && !bs->read_only && !(flags & BDRV_O_INACTIVE);
1718 if (update_header) {
1719 s->autoclear_features &= QCOW2_AUTOCLEAR_MASK;
1722 /* == Handle persistent dirty bitmaps ==
1724 * We want load dirty bitmaps in three cases:
1726 * 1. Normal open of the disk in active mode, not related to invalidation
1727 * after migration.
1729 * 2. Invalidation of the target vm after pre-copy phase of migration, if
1730 * bitmaps are _not_ migrating through migration channel, i.e.
1731 * 'dirty-bitmaps' capability is disabled.
1733 * 3. Invalidation of source vm after failed or canceled migration.
1734 * This is a very interesting case. There are two possible types of
1735 * bitmaps:
1737 * A. Stored on inactivation and removed. They should be loaded from the
1738 * image.
1740 * B. Not stored: not-persistent bitmaps and bitmaps, migrated through
1741 * the migration channel (with dirty-bitmaps capability).
1743 * On the other hand, there are two possible sub-cases:
1745 * 3.1 disk was changed by somebody else while were inactive. In this
1746 * case all in-RAM dirty bitmaps (both persistent and not) are
1747 * definitely invalid. And we don't have any method to determine
1748 * this.
1750 * Simple and safe thing is to just drop all the bitmaps of type B on
1751 * inactivation. But in this case we lose bitmaps in valid 4.2 case.
1753 * On the other hand, resuming source vm, if disk was already changed
1754 * is a bad thing anyway: not only bitmaps, the whole vm state is
1755 * out of sync with disk.
1757 * This means, that user or management tool, who for some reason
1758 * decided to resume source vm, after disk was already changed by
1759 * target vm, should at least drop all dirty bitmaps by hand.
1761 * So, we can ignore this case for now, but TODO: "generation"
1762 * extension for qcow2, to determine, that image was changed after
1763 * last inactivation. And if it is changed, we will drop (or at least
1764 * mark as 'invalid' all the bitmaps of type B, both persistent
1765 * and not).
1767 * 3.2 disk was _not_ changed while were inactive. Bitmaps may be saved
1768 * to disk ('dirty-bitmaps' capability disabled), or not saved
1769 * ('dirty-bitmaps' capability enabled), but we don't need to care
1770 * of: let's load bitmaps as always: stored bitmaps will be loaded,
1771 * and not stored has flag IN_USE=1 in the image and will be skipped
1772 * on loading.
1774 * One remaining possible case when we don't want load bitmaps:
1776 * 4. Open disk in inactive mode in target vm (bitmaps are migrating or
1777 * will be loaded on invalidation, no needs try loading them before)
1780 if (!(bdrv_get_flags(bs) & BDRV_O_INACTIVE)) {
1781 /* It's case 1, 2 or 3.2. Or 3.1 which is BUG in management layer. */
1782 bool header_updated = qcow2_load_dirty_bitmaps(bs, &local_err);
1783 if (local_err != NULL) {
1784 error_propagate(errp, local_err);
1785 ret = -EINVAL;
1786 goto fail;
1789 update_header = update_header && !header_updated;
1792 if (update_header) {
1793 ret = qcow2_update_header(bs);
1794 if (ret < 0) {
1795 error_setg_errno(errp, -ret, "Could not update qcow2 header");
1796 goto fail;
1800 bs->supported_zero_flags = header.version >= 3 ?
1801 BDRV_REQ_MAY_UNMAP | BDRV_REQ_NO_FALLBACK : 0;
1802 bs->supported_truncate_flags = BDRV_REQ_ZERO_WRITE;
1804 /* Repair image if dirty */
1805 if (!(flags & (BDRV_O_CHECK | BDRV_O_INACTIVE)) && !bs->read_only &&
1806 (s->incompatible_features & QCOW2_INCOMPAT_DIRTY)) {
1807 BdrvCheckResult result = {0};
1809 ret = qcow2_co_check_locked(bs, &result,
1810 BDRV_FIX_ERRORS | BDRV_FIX_LEAKS);
1811 if (ret < 0 || result.check_errors) {
1812 if (ret >= 0) {
1813 ret = -EIO;
1815 error_setg_errno(errp, -ret, "Could not repair dirty image");
1816 goto fail;
1820 #ifdef DEBUG_ALLOC
1822 BdrvCheckResult result = {0};
1823 qcow2_check_refcounts(bs, &result, 0);
1825 #endif
1827 qemu_co_queue_init(&s->thread_task_queue);
1829 return ret;
1831 fail:
1832 g_free(s->image_data_file);
1833 if (has_data_file(bs)) {
1834 bdrv_unref_child(bs, s->data_file);
1835 s->data_file = NULL;
1837 g_free(s->unknown_header_fields);
1838 cleanup_unknown_header_ext(bs);
1839 qcow2_free_snapshots(bs);
1840 qcow2_refcount_close(bs);
1841 qemu_vfree(s->l1_table);
1842 /* else pre-write overlap checks in cache_destroy may crash */
1843 s->l1_table = NULL;
1844 cache_clean_timer_del(bs);
1845 if (s->l2_table_cache) {
1846 qcow2_cache_destroy(s->l2_table_cache);
1848 if (s->refcount_block_cache) {
1849 qcow2_cache_destroy(s->refcount_block_cache);
1851 qcrypto_block_free(s->crypto);
1852 qapi_free_QCryptoBlockOpenOptions(s->crypto_opts);
1853 return ret;
1856 typedef struct QCow2OpenCo {
1857 BlockDriverState *bs;
1858 QDict *options;
1859 int flags;
1860 Error **errp;
1861 int ret;
1862 } QCow2OpenCo;
1864 static void coroutine_fn qcow2_open_entry(void *opaque)
1866 QCow2OpenCo *qoc = opaque;
1867 BDRVQcow2State *s = qoc->bs->opaque;
1869 qemu_co_mutex_lock(&s->lock);
1870 qoc->ret = qcow2_do_open(qoc->bs, qoc->options, qoc->flags, qoc->errp);
1871 qemu_co_mutex_unlock(&s->lock);
1874 static int qcow2_open(BlockDriverState *bs, QDict *options, int flags,
1875 Error **errp)
1877 BDRVQcow2State *s = bs->opaque;
1878 QCow2OpenCo qoc = {
1879 .bs = bs,
1880 .options = options,
1881 .flags = flags,
1882 .errp = errp,
1883 .ret = -EINPROGRESS
1886 bs->file = bdrv_open_child(NULL, options, "file", bs, &child_of_bds,
1887 BDRV_CHILD_IMAGE, false, errp);
1888 if (!bs->file) {
1889 return -EINVAL;
1892 /* Initialise locks */
1893 qemu_co_mutex_init(&s->lock);
1895 if (qemu_in_coroutine()) {
1896 /* From bdrv_co_create. */
1897 qcow2_open_entry(&qoc);
1898 } else {
1899 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
1900 qemu_coroutine_enter(qemu_coroutine_create(qcow2_open_entry, &qoc));
1901 BDRV_POLL_WHILE(bs, qoc.ret == -EINPROGRESS);
1903 return qoc.ret;
1906 static void qcow2_refresh_limits(BlockDriverState *bs, Error **errp)
1908 BDRVQcow2State *s = bs->opaque;
1910 if (bs->encrypted) {
1911 /* Encryption works on a sector granularity */
1912 bs->bl.request_alignment = qcrypto_block_get_sector_size(s->crypto);
1914 bs->bl.pwrite_zeroes_alignment = s->cluster_size;
1915 bs->bl.pdiscard_alignment = s->cluster_size;
1918 static int qcow2_reopen_prepare(BDRVReopenState *state,
1919 BlockReopenQueue *queue, Error **errp)
1921 Qcow2ReopenState *r;
1922 int ret;
1924 r = g_new0(Qcow2ReopenState, 1);
1925 state->opaque = r;
1927 ret = qcow2_update_options_prepare(state->bs, r, state->options,
1928 state->flags, errp);
1929 if (ret < 0) {
1930 goto fail;
1933 /* We need to write out any unwritten data if we reopen read-only. */
1934 if ((state->flags & BDRV_O_RDWR) == 0) {
1935 ret = qcow2_reopen_bitmaps_ro(state->bs, errp);
1936 if (ret < 0) {
1937 goto fail;
1940 ret = bdrv_flush(state->bs);
1941 if (ret < 0) {
1942 goto fail;
1945 ret = qcow2_mark_clean(state->bs);
1946 if (ret < 0) {
1947 goto fail;
1951 return 0;
1953 fail:
1954 qcow2_update_options_abort(state->bs, r);
1955 g_free(r);
1956 return ret;
1959 static void qcow2_reopen_commit(BDRVReopenState *state)
1961 qcow2_update_options_commit(state->bs, state->opaque);
1962 g_free(state->opaque);
1965 static void qcow2_reopen_commit_post(BDRVReopenState *state)
1967 if (state->flags & BDRV_O_RDWR) {
1968 Error *local_err = NULL;
1970 if (qcow2_reopen_bitmaps_rw(state->bs, &local_err) < 0) {
1972 * This is not fatal, bitmaps just left read-only, so all following
1973 * writes will fail. User can remove read-only bitmaps to unblock
1974 * writes or retry reopen.
1976 error_reportf_err(local_err,
1977 "%s: Failed to make dirty bitmaps writable: ",
1978 bdrv_get_node_name(state->bs));
1983 static void qcow2_reopen_abort(BDRVReopenState *state)
1985 qcow2_update_options_abort(state->bs, state->opaque);
1986 g_free(state->opaque);
1989 static void qcow2_join_options(QDict *options, QDict *old_options)
1991 bool has_new_overlap_template =
1992 qdict_haskey(options, QCOW2_OPT_OVERLAP) ||
1993 qdict_haskey(options, QCOW2_OPT_OVERLAP_TEMPLATE);
1994 bool has_new_total_cache_size =
1995 qdict_haskey(options, QCOW2_OPT_CACHE_SIZE);
1996 bool has_all_cache_options;
1998 /* New overlap template overrides all old overlap options */
1999 if (has_new_overlap_template) {
2000 qdict_del(old_options, QCOW2_OPT_OVERLAP);
2001 qdict_del(old_options, QCOW2_OPT_OVERLAP_TEMPLATE);
2002 qdict_del(old_options, QCOW2_OPT_OVERLAP_MAIN_HEADER);
2003 qdict_del(old_options, QCOW2_OPT_OVERLAP_ACTIVE_L1);
2004 qdict_del(old_options, QCOW2_OPT_OVERLAP_ACTIVE_L2);
2005 qdict_del(old_options, QCOW2_OPT_OVERLAP_REFCOUNT_TABLE);
2006 qdict_del(old_options, QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK);
2007 qdict_del(old_options, QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE);
2008 qdict_del(old_options, QCOW2_OPT_OVERLAP_INACTIVE_L1);
2009 qdict_del(old_options, QCOW2_OPT_OVERLAP_INACTIVE_L2);
2012 /* New total cache size overrides all old options */
2013 if (qdict_haskey(options, QCOW2_OPT_CACHE_SIZE)) {
2014 qdict_del(old_options, QCOW2_OPT_L2_CACHE_SIZE);
2015 qdict_del(old_options, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
2018 qdict_join(options, old_options, false);
2021 * If after merging all cache size options are set, an old total size is
2022 * overwritten. Do keep all options, however, if all three are new. The
2023 * resulting error message is what we want to happen.
2025 has_all_cache_options =
2026 qdict_haskey(options, QCOW2_OPT_CACHE_SIZE) ||
2027 qdict_haskey(options, QCOW2_OPT_L2_CACHE_SIZE) ||
2028 qdict_haskey(options, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
2030 if (has_all_cache_options && !has_new_total_cache_size) {
2031 qdict_del(options, QCOW2_OPT_CACHE_SIZE);
2035 static int coroutine_fn qcow2_co_block_status(BlockDriverState *bs,
2036 bool want_zero,
2037 int64_t offset, int64_t count,
2038 int64_t *pnum, int64_t *map,
2039 BlockDriverState **file)
2041 BDRVQcow2State *s = bs->opaque;
2042 uint64_t cluster_offset;
2043 unsigned int bytes;
2044 int ret, status = 0;
2046 qemu_co_mutex_lock(&s->lock);
2048 if (!s->metadata_preallocation_checked) {
2049 ret = qcow2_detect_metadata_preallocation(bs);
2050 s->metadata_preallocation = (ret == 1);
2051 s->metadata_preallocation_checked = true;
2054 bytes = MIN(INT_MAX, count);
2055 ret = qcow2_get_cluster_offset(bs, offset, &bytes, &cluster_offset);
2056 qemu_co_mutex_unlock(&s->lock);
2057 if (ret < 0) {
2058 return ret;
2061 *pnum = bytes;
2063 if ((ret == QCOW2_CLUSTER_NORMAL || ret == QCOW2_CLUSTER_ZERO_ALLOC) &&
2064 !s->crypto) {
2065 *map = cluster_offset | offset_into_cluster(s, offset);
2066 *file = s->data_file->bs;
2067 status |= BDRV_BLOCK_OFFSET_VALID;
2069 if (ret == QCOW2_CLUSTER_ZERO_PLAIN || ret == QCOW2_CLUSTER_ZERO_ALLOC) {
2070 status |= BDRV_BLOCK_ZERO;
2071 } else if (ret != QCOW2_CLUSTER_UNALLOCATED) {
2072 status |= BDRV_BLOCK_DATA;
2074 if (s->metadata_preallocation && (status & BDRV_BLOCK_DATA) &&
2075 (status & BDRV_BLOCK_OFFSET_VALID))
2077 status |= BDRV_BLOCK_RECURSE;
2079 return status;
2082 static coroutine_fn int qcow2_handle_l2meta(BlockDriverState *bs,
2083 QCowL2Meta **pl2meta,
2084 bool link_l2)
2086 int ret = 0;
2087 QCowL2Meta *l2meta = *pl2meta;
2089 while (l2meta != NULL) {
2090 QCowL2Meta *next;
2092 if (link_l2) {
2093 ret = qcow2_alloc_cluster_link_l2(bs, l2meta);
2094 if (ret) {
2095 goto out;
2097 } else {
2098 qcow2_alloc_cluster_abort(bs, l2meta);
2101 /* Take the request off the list of running requests */
2102 if (l2meta->nb_clusters != 0) {
2103 QLIST_REMOVE(l2meta, next_in_flight);
2106 qemu_co_queue_restart_all(&l2meta->dependent_requests);
2108 next = l2meta->next;
2109 g_free(l2meta);
2110 l2meta = next;
2112 out:
2113 *pl2meta = l2meta;
2114 return ret;
2117 static coroutine_fn int
2118 qcow2_co_preadv_encrypted(BlockDriverState *bs,
2119 uint64_t file_cluster_offset,
2120 uint64_t offset,
2121 uint64_t bytes,
2122 QEMUIOVector *qiov,
2123 uint64_t qiov_offset)
2125 int ret;
2126 BDRVQcow2State *s = bs->opaque;
2127 uint8_t *buf;
2129 assert(bs->encrypted && s->crypto);
2130 assert(bytes <= QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
2133 * For encrypted images, read everything into a temporary
2134 * contiguous buffer on which the AES functions can work.
2135 * Also, decryption in a separate buffer is better as it
2136 * prevents the guest from learning information about the
2137 * encrypted nature of the virtual disk.
2140 buf = qemu_try_blockalign(s->data_file->bs, bytes);
2141 if (buf == NULL) {
2142 return -ENOMEM;
2145 BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);
2146 ret = bdrv_co_pread(s->data_file,
2147 file_cluster_offset + offset_into_cluster(s, offset),
2148 bytes, buf, 0);
2149 if (ret < 0) {
2150 goto fail;
2153 if (qcow2_co_decrypt(bs,
2154 file_cluster_offset + offset_into_cluster(s, offset),
2155 offset, buf, bytes) < 0)
2157 ret = -EIO;
2158 goto fail;
2160 qemu_iovec_from_buf(qiov, qiov_offset, buf, bytes);
2162 fail:
2163 qemu_vfree(buf);
2165 return ret;
2168 typedef struct Qcow2AioTask {
2169 AioTask task;
2171 BlockDriverState *bs;
2172 QCow2ClusterType cluster_type; /* only for read */
2173 uint64_t file_cluster_offset;
2174 uint64_t offset;
2175 uint64_t bytes;
2176 QEMUIOVector *qiov;
2177 uint64_t qiov_offset;
2178 QCowL2Meta *l2meta; /* only for write */
2179 } Qcow2AioTask;
2181 static coroutine_fn int qcow2_co_preadv_task_entry(AioTask *task);
2182 static coroutine_fn int qcow2_add_task(BlockDriverState *bs,
2183 AioTaskPool *pool,
2184 AioTaskFunc func,
2185 QCow2ClusterType cluster_type,
2186 uint64_t file_cluster_offset,
2187 uint64_t offset,
2188 uint64_t bytes,
2189 QEMUIOVector *qiov,
2190 size_t qiov_offset,
2191 QCowL2Meta *l2meta)
2193 Qcow2AioTask local_task;
2194 Qcow2AioTask *task = pool ? g_new(Qcow2AioTask, 1) : &local_task;
2196 *task = (Qcow2AioTask) {
2197 .task.func = func,
2198 .bs = bs,
2199 .cluster_type = cluster_type,
2200 .qiov = qiov,
2201 .file_cluster_offset = file_cluster_offset,
2202 .offset = offset,
2203 .bytes = bytes,
2204 .qiov_offset = qiov_offset,
2205 .l2meta = l2meta,
2208 trace_qcow2_add_task(qemu_coroutine_self(), bs, pool,
2209 func == qcow2_co_preadv_task_entry ? "read" : "write",
2210 cluster_type, file_cluster_offset, offset, bytes,
2211 qiov, qiov_offset);
2213 if (!pool) {
2214 return func(&task->task);
2217 aio_task_pool_start_task(pool, &task->task);
2219 return 0;
2222 static coroutine_fn int qcow2_co_preadv_task(BlockDriverState *bs,
2223 QCow2ClusterType cluster_type,
2224 uint64_t file_cluster_offset,
2225 uint64_t offset, uint64_t bytes,
2226 QEMUIOVector *qiov,
2227 size_t qiov_offset)
2229 BDRVQcow2State *s = bs->opaque;
2230 int offset_in_cluster = offset_into_cluster(s, offset);
2232 switch (cluster_type) {
2233 case QCOW2_CLUSTER_ZERO_PLAIN:
2234 case QCOW2_CLUSTER_ZERO_ALLOC:
2235 /* Both zero types are handled in qcow2_co_preadv_part */
2236 g_assert_not_reached();
2238 case QCOW2_CLUSTER_UNALLOCATED:
2239 assert(bs->backing); /* otherwise handled in qcow2_co_preadv_part */
2241 BLKDBG_EVENT(bs->file, BLKDBG_READ_BACKING_AIO);
2242 return bdrv_co_preadv_part(bs->backing, offset, bytes,
2243 qiov, qiov_offset, 0);
2245 case QCOW2_CLUSTER_COMPRESSED:
2246 return qcow2_co_preadv_compressed(bs, file_cluster_offset,
2247 offset, bytes, qiov, qiov_offset);
2249 case QCOW2_CLUSTER_NORMAL:
2250 assert(offset_into_cluster(s, file_cluster_offset) == 0);
2251 if (bs->encrypted) {
2252 return qcow2_co_preadv_encrypted(bs, file_cluster_offset,
2253 offset, bytes, qiov, qiov_offset);
2256 BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);
2257 return bdrv_co_preadv_part(s->data_file,
2258 file_cluster_offset + offset_in_cluster,
2259 bytes, qiov, qiov_offset, 0);
2261 default:
2262 g_assert_not_reached();
2265 g_assert_not_reached();
2268 static coroutine_fn int qcow2_co_preadv_task_entry(AioTask *task)
2270 Qcow2AioTask *t = container_of(task, Qcow2AioTask, task);
2272 assert(!t->l2meta);
2274 return qcow2_co_preadv_task(t->bs, t->cluster_type, t->file_cluster_offset,
2275 t->offset, t->bytes, t->qiov, t->qiov_offset);
2278 static coroutine_fn int qcow2_co_preadv_part(BlockDriverState *bs,
2279 uint64_t offset, uint64_t bytes,
2280 QEMUIOVector *qiov,
2281 size_t qiov_offset, int flags)
2283 BDRVQcow2State *s = bs->opaque;
2284 int ret = 0;
2285 unsigned int cur_bytes; /* number of bytes in current iteration */
2286 uint64_t cluster_offset = 0;
2287 AioTaskPool *aio = NULL;
2289 while (bytes != 0 && aio_task_pool_status(aio) == 0) {
2290 /* prepare next request */
2291 cur_bytes = MIN(bytes, INT_MAX);
2292 if (s->crypto) {
2293 cur_bytes = MIN(cur_bytes,
2294 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
2297 qemu_co_mutex_lock(&s->lock);
2298 ret = qcow2_get_cluster_offset(bs, offset, &cur_bytes, &cluster_offset);
2299 qemu_co_mutex_unlock(&s->lock);
2300 if (ret < 0) {
2301 goto out;
2304 if (ret == QCOW2_CLUSTER_ZERO_PLAIN ||
2305 ret == QCOW2_CLUSTER_ZERO_ALLOC ||
2306 (ret == QCOW2_CLUSTER_UNALLOCATED && !bs->backing))
2308 qemu_iovec_memset(qiov, qiov_offset, 0, cur_bytes);
2309 } else {
2310 if (!aio && cur_bytes != bytes) {
2311 aio = aio_task_pool_new(QCOW2_MAX_WORKERS);
2313 ret = qcow2_add_task(bs, aio, qcow2_co_preadv_task_entry, ret,
2314 cluster_offset, offset, cur_bytes,
2315 qiov, qiov_offset, NULL);
2316 if (ret < 0) {
2317 goto out;
2321 bytes -= cur_bytes;
2322 offset += cur_bytes;
2323 qiov_offset += cur_bytes;
2326 out:
2327 if (aio) {
2328 aio_task_pool_wait_all(aio);
2329 if (ret == 0) {
2330 ret = aio_task_pool_status(aio);
2332 g_free(aio);
2335 return ret;
2338 /* Check if it's possible to merge a write request with the writing of
2339 * the data from the COW regions */
2340 static bool merge_cow(uint64_t offset, unsigned bytes,
2341 QEMUIOVector *qiov, size_t qiov_offset,
2342 QCowL2Meta *l2meta)
2344 QCowL2Meta *m;
2346 for (m = l2meta; m != NULL; m = m->next) {
2347 /* If both COW regions are empty then there's nothing to merge */
2348 if (m->cow_start.nb_bytes == 0 && m->cow_end.nb_bytes == 0) {
2349 continue;
2352 /* If COW regions are handled already, skip this too */
2353 if (m->skip_cow) {
2354 continue;
2357 /* The data (middle) region must be immediately after the
2358 * start region */
2359 if (l2meta_cow_start(m) + m->cow_start.nb_bytes != offset) {
2360 continue;
2363 /* The end region must be immediately after the data (middle)
2364 * region */
2365 if (m->offset + m->cow_end.offset != offset + bytes) {
2366 continue;
2369 /* Make sure that adding both COW regions to the QEMUIOVector
2370 * does not exceed IOV_MAX */
2371 if (qemu_iovec_subvec_niov(qiov, qiov_offset, bytes) > IOV_MAX - 2) {
2372 continue;
2375 m->data_qiov = qiov;
2376 m->data_qiov_offset = qiov_offset;
2377 return true;
2380 return false;
2383 static bool is_unallocated(BlockDriverState *bs, int64_t offset, int64_t bytes)
2385 int64_t nr;
2386 return !bytes ||
2387 (!bdrv_is_allocated_above(bs, NULL, false, offset, bytes, &nr) &&
2388 nr == bytes);
2391 static bool is_zero_cow(BlockDriverState *bs, QCowL2Meta *m)
2394 * This check is designed for optimization shortcut so it must be
2395 * efficient.
2396 * Instead of is_zero(), use is_unallocated() as it is faster (but not
2397 * as accurate and can result in false negatives).
2399 return is_unallocated(bs, m->offset + m->cow_start.offset,
2400 m->cow_start.nb_bytes) &&
2401 is_unallocated(bs, m->offset + m->cow_end.offset,
2402 m->cow_end.nb_bytes);
2405 static int handle_alloc_space(BlockDriverState *bs, QCowL2Meta *l2meta)
2407 BDRVQcow2State *s = bs->opaque;
2408 QCowL2Meta *m;
2410 if (!(s->data_file->bs->supported_zero_flags & BDRV_REQ_NO_FALLBACK)) {
2411 return 0;
2414 if (bs->encrypted) {
2415 return 0;
2418 for (m = l2meta; m != NULL; m = m->next) {
2419 int ret;
2421 if (!m->cow_start.nb_bytes && !m->cow_end.nb_bytes) {
2422 continue;
2425 if (!is_zero_cow(bs, m)) {
2426 continue;
2430 * instead of writing zero COW buffers,
2431 * efficiently zero out the whole clusters
2434 ret = qcow2_pre_write_overlap_check(bs, 0, m->alloc_offset,
2435 m->nb_clusters * s->cluster_size,
2436 true);
2437 if (ret < 0) {
2438 return ret;
2441 BLKDBG_EVENT(bs->file, BLKDBG_CLUSTER_ALLOC_SPACE);
2442 ret = bdrv_co_pwrite_zeroes(s->data_file, m->alloc_offset,
2443 m->nb_clusters * s->cluster_size,
2444 BDRV_REQ_NO_FALLBACK);
2445 if (ret < 0) {
2446 if (ret != -ENOTSUP && ret != -EAGAIN) {
2447 return ret;
2449 continue;
2452 trace_qcow2_skip_cow(qemu_coroutine_self(), m->offset, m->nb_clusters);
2453 m->skip_cow = true;
2455 return 0;
2459 * qcow2_co_pwritev_task
2460 * Called with s->lock unlocked
2461 * l2meta - if not NULL, qcow2_co_pwritev_task() will consume it. Caller must
2462 * not use it somehow after qcow2_co_pwritev_task() call
2464 static coroutine_fn int qcow2_co_pwritev_task(BlockDriverState *bs,
2465 uint64_t file_cluster_offset,
2466 uint64_t offset, uint64_t bytes,
2467 QEMUIOVector *qiov,
2468 uint64_t qiov_offset,
2469 QCowL2Meta *l2meta)
2471 int ret;
2472 BDRVQcow2State *s = bs->opaque;
2473 void *crypt_buf = NULL;
2474 int offset_in_cluster = offset_into_cluster(s, offset);
2475 QEMUIOVector encrypted_qiov;
2477 if (bs->encrypted) {
2478 assert(s->crypto);
2479 assert(bytes <= QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
2480 crypt_buf = qemu_try_blockalign(bs->file->bs, bytes);
2481 if (crypt_buf == NULL) {
2482 ret = -ENOMEM;
2483 goto out_unlocked;
2485 qemu_iovec_to_buf(qiov, qiov_offset, crypt_buf, bytes);
2487 if (qcow2_co_encrypt(bs, file_cluster_offset + offset_in_cluster,
2488 offset, crypt_buf, bytes) < 0)
2490 ret = -EIO;
2491 goto out_unlocked;
2494 qemu_iovec_init_buf(&encrypted_qiov, crypt_buf, bytes);
2495 qiov = &encrypted_qiov;
2496 qiov_offset = 0;
2499 /* Try to efficiently initialize the physical space with zeroes */
2500 ret = handle_alloc_space(bs, l2meta);
2501 if (ret < 0) {
2502 goto out_unlocked;
2506 * If we need to do COW, check if it's possible to merge the
2507 * writing of the guest data together with that of the COW regions.
2508 * If it's not possible (or not necessary) then write the
2509 * guest data now.
2511 if (!merge_cow(offset, bytes, qiov, qiov_offset, l2meta)) {
2512 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO);
2513 trace_qcow2_writev_data(qemu_coroutine_self(),
2514 file_cluster_offset + offset_in_cluster);
2515 ret = bdrv_co_pwritev_part(s->data_file,
2516 file_cluster_offset + offset_in_cluster,
2517 bytes, qiov, qiov_offset, 0);
2518 if (ret < 0) {
2519 goto out_unlocked;
2523 qemu_co_mutex_lock(&s->lock);
2525 ret = qcow2_handle_l2meta(bs, &l2meta, true);
2526 goto out_locked;
2528 out_unlocked:
2529 qemu_co_mutex_lock(&s->lock);
2531 out_locked:
2532 qcow2_handle_l2meta(bs, &l2meta, false);
2533 qemu_co_mutex_unlock(&s->lock);
2535 qemu_vfree(crypt_buf);
2537 return ret;
2540 static coroutine_fn int qcow2_co_pwritev_task_entry(AioTask *task)
2542 Qcow2AioTask *t = container_of(task, Qcow2AioTask, task);
2544 assert(!t->cluster_type);
2546 return qcow2_co_pwritev_task(t->bs, t->file_cluster_offset,
2547 t->offset, t->bytes, t->qiov, t->qiov_offset,
2548 t->l2meta);
2551 static coroutine_fn int qcow2_co_pwritev_part(
2552 BlockDriverState *bs, uint64_t offset, uint64_t bytes,
2553 QEMUIOVector *qiov, size_t qiov_offset, int flags)
2555 BDRVQcow2State *s = bs->opaque;
2556 int offset_in_cluster;
2557 int ret;
2558 unsigned int cur_bytes; /* number of sectors in current iteration */
2559 uint64_t cluster_offset;
2560 QCowL2Meta *l2meta = NULL;
2561 AioTaskPool *aio = NULL;
2563 trace_qcow2_writev_start_req(qemu_coroutine_self(), offset, bytes);
2565 while (bytes != 0 && aio_task_pool_status(aio) == 0) {
2567 l2meta = NULL;
2569 trace_qcow2_writev_start_part(qemu_coroutine_self());
2570 offset_in_cluster = offset_into_cluster(s, offset);
2571 cur_bytes = MIN(bytes, INT_MAX);
2572 if (bs->encrypted) {
2573 cur_bytes = MIN(cur_bytes,
2574 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size
2575 - offset_in_cluster);
2578 qemu_co_mutex_lock(&s->lock);
2580 ret = qcow2_alloc_cluster_offset(bs, offset, &cur_bytes,
2581 &cluster_offset, &l2meta);
2582 if (ret < 0) {
2583 goto out_locked;
2586 assert(offset_into_cluster(s, cluster_offset) == 0);
2588 ret = qcow2_pre_write_overlap_check(bs, 0,
2589 cluster_offset + offset_in_cluster,
2590 cur_bytes, true);
2591 if (ret < 0) {
2592 goto out_locked;
2595 qemu_co_mutex_unlock(&s->lock);
2597 if (!aio && cur_bytes != bytes) {
2598 aio = aio_task_pool_new(QCOW2_MAX_WORKERS);
2600 ret = qcow2_add_task(bs, aio, qcow2_co_pwritev_task_entry, 0,
2601 cluster_offset, offset, cur_bytes,
2602 qiov, qiov_offset, l2meta);
2603 l2meta = NULL; /* l2meta is consumed by qcow2_co_pwritev_task() */
2604 if (ret < 0) {
2605 goto fail_nometa;
2608 bytes -= cur_bytes;
2609 offset += cur_bytes;
2610 qiov_offset += cur_bytes;
2611 trace_qcow2_writev_done_part(qemu_coroutine_self(), cur_bytes);
2613 ret = 0;
2615 qemu_co_mutex_lock(&s->lock);
2617 out_locked:
2618 qcow2_handle_l2meta(bs, &l2meta, false);
2620 qemu_co_mutex_unlock(&s->lock);
2622 fail_nometa:
2623 if (aio) {
2624 aio_task_pool_wait_all(aio);
2625 if (ret == 0) {
2626 ret = aio_task_pool_status(aio);
2628 g_free(aio);
2631 trace_qcow2_writev_done_req(qemu_coroutine_self(), ret);
2633 return ret;
2636 static int qcow2_inactivate(BlockDriverState *bs)
2638 BDRVQcow2State *s = bs->opaque;
2639 int ret, result = 0;
2640 Error *local_err = NULL;
2642 qcow2_store_persistent_dirty_bitmaps(bs, true, &local_err);
2643 if (local_err != NULL) {
2644 result = -EINVAL;
2645 error_reportf_err(local_err, "Lost persistent bitmaps during "
2646 "inactivation of node '%s': ",
2647 bdrv_get_device_or_node_name(bs));
2650 ret = qcow2_cache_flush(bs, s->l2_table_cache);
2651 if (ret) {
2652 result = ret;
2653 error_report("Failed to flush the L2 table cache: %s",
2654 strerror(-ret));
2657 ret = qcow2_cache_flush(bs, s->refcount_block_cache);
2658 if (ret) {
2659 result = ret;
2660 error_report("Failed to flush the refcount block cache: %s",
2661 strerror(-ret));
2664 if (result == 0) {
2665 qcow2_mark_clean(bs);
2668 return result;
2671 static void qcow2_close(BlockDriverState *bs)
2673 BDRVQcow2State *s = bs->opaque;
2674 qemu_vfree(s->l1_table);
2675 /* else pre-write overlap checks in cache_destroy may crash */
2676 s->l1_table = NULL;
2678 if (!(s->flags & BDRV_O_INACTIVE)) {
2679 qcow2_inactivate(bs);
2682 cache_clean_timer_del(bs);
2683 qcow2_cache_destroy(s->l2_table_cache);
2684 qcow2_cache_destroy(s->refcount_block_cache);
2686 qcrypto_block_free(s->crypto);
2687 s->crypto = NULL;
2688 qapi_free_QCryptoBlockOpenOptions(s->crypto_opts);
2690 g_free(s->unknown_header_fields);
2691 cleanup_unknown_header_ext(bs);
2693 g_free(s->image_data_file);
2694 g_free(s->image_backing_file);
2695 g_free(s->image_backing_format);
2697 if (has_data_file(bs)) {
2698 bdrv_unref_child(bs, s->data_file);
2699 s->data_file = NULL;
2702 qcow2_refcount_close(bs);
2703 qcow2_free_snapshots(bs);
2706 static void coroutine_fn qcow2_co_invalidate_cache(BlockDriverState *bs,
2707 Error **errp)
2709 BDRVQcow2State *s = bs->opaque;
2710 int flags = s->flags;
2711 QCryptoBlock *crypto = NULL;
2712 QDict *options;
2713 Error *local_err = NULL;
2714 int ret;
2717 * Backing files are read-only which makes all of their metadata immutable,
2718 * that means we don't have to worry about reopening them here.
2721 crypto = s->crypto;
2722 s->crypto = NULL;
2724 qcow2_close(bs);
2726 memset(s, 0, sizeof(BDRVQcow2State));
2727 options = qdict_clone_shallow(bs->options);
2729 flags &= ~BDRV_O_INACTIVE;
2730 qemu_co_mutex_lock(&s->lock);
2731 ret = qcow2_do_open(bs, options, flags, &local_err);
2732 qemu_co_mutex_unlock(&s->lock);
2733 qobject_unref(options);
2734 if (local_err) {
2735 error_propagate_prepend(errp, local_err,
2736 "Could not reopen qcow2 layer: ");
2737 bs->drv = NULL;
2738 return;
2739 } else if (ret < 0) {
2740 error_setg_errno(errp, -ret, "Could not reopen qcow2 layer");
2741 bs->drv = NULL;
2742 return;
2745 s->crypto = crypto;
2748 static size_t header_ext_add(char *buf, uint32_t magic, const void *s,
2749 size_t len, size_t buflen)
2751 QCowExtension *ext_backing_fmt = (QCowExtension*) buf;
2752 size_t ext_len = sizeof(QCowExtension) + ((len + 7) & ~7);
2754 if (buflen < ext_len) {
2755 return -ENOSPC;
2758 *ext_backing_fmt = (QCowExtension) {
2759 .magic = cpu_to_be32(magic),
2760 .len = cpu_to_be32(len),
2763 if (len) {
2764 memcpy(buf + sizeof(QCowExtension), s, len);
2767 return ext_len;
2771 * Updates the qcow2 header, including the variable length parts of it, i.e.
2772 * the backing file name and all extensions. qcow2 was not designed to allow
2773 * such changes, so if we run out of space (we can only use the first cluster)
2774 * this function may fail.
2776 * Returns 0 on success, -errno in error cases.
2778 int qcow2_update_header(BlockDriverState *bs)
2780 BDRVQcow2State *s = bs->opaque;
2781 QCowHeader *header;
2782 char *buf;
2783 size_t buflen = s->cluster_size;
2784 int ret;
2785 uint64_t total_size;
2786 uint32_t refcount_table_clusters;
2787 size_t header_length;
2788 Qcow2UnknownHeaderExtension *uext;
2790 buf = qemu_blockalign(bs, buflen);
2792 /* Header structure */
2793 header = (QCowHeader*) buf;
2795 if (buflen < sizeof(*header)) {
2796 ret = -ENOSPC;
2797 goto fail;
2800 header_length = sizeof(*header) + s->unknown_header_fields_size;
2801 total_size = bs->total_sectors * BDRV_SECTOR_SIZE;
2802 refcount_table_clusters = s->refcount_table_size >> (s->cluster_bits - 3);
2804 ret = validate_compression_type(s, NULL);
2805 if (ret) {
2806 goto fail;
2809 *header = (QCowHeader) {
2810 /* Version 2 fields */
2811 .magic = cpu_to_be32(QCOW_MAGIC),
2812 .version = cpu_to_be32(s->qcow_version),
2813 .backing_file_offset = 0,
2814 .backing_file_size = 0,
2815 .cluster_bits = cpu_to_be32(s->cluster_bits),
2816 .size = cpu_to_be64(total_size),
2817 .crypt_method = cpu_to_be32(s->crypt_method_header),
2818 .l1_size = cpu_to_be32(s->l1_size),
2819 .l1_table_offset = cpu_to_be64(s->l1_table_offset),
2820 .refcount_table_offset = cpu_to_be64(s->refcount_table_offset),
2821 .refcount_table_clusters = cpu_to_be32(refcount_table_clusters),
2822 .nb_snapshots = cpu_to_be32(s->nb_snapshots),
2823 .snapshots_offset = cpu_to_be64(s->snapshots_offset),
2825 /* Version 3 fields */
2826 .incompatible_features = cpu_to_be64(s->incompatible_features),
2827 .compatible_features = cpu_to_be64(s->compatible_features),
2828 .autoclear_features = cpu_to_be64(s->autoclear_features),
2829 .refcount_order = cpu_to_be32(s->refcount_order),
2830 .header_length = cpu_to_be32(header_length),
2831 .compression_type = s->compression_type,
2834 /* For older versions, write a shorter header */
2835 switch (s->qcow_version) {
2836 case 2:
2837 ret = offsetof(QCowHeader, incompatible_features);
2838 break;
2839 case 3:
2840 ret = sizeof(*header);
2841 break;
2842 default:
2843 ret = -EINVAL;
2844 goto fail;
2847 buf += ret;
2848 buflen -= ret;
2849 memset(buf, 0, buflen);
2851 /* Preserve any unknown field in the header */
2852 if (s->unknown_header_fields_size) {
2853 if (buflen < s->unknown_header_fields_size) {
2854 ret = -ENOSPC;
2855 goto fail;
2858 memcpy(buf, s->unknown_header_fields, s->unknown_header_fields_size);
2859 buf += s->unknown_header_fields_size;
2860 buflen -= s->unknown_header_fields_size;
2863 /* Backing file format header extension */
2864 if (s->image_backing_format) {
2865 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BACKING_FORMAT,
2866 s->image_backing_format,
2867 strlen(s->image_backing_format),
2868 buflen);
2869 if (ret < 0) {
2870 goto fail;
2873 buf += ret;
2874 buflen -= ret;
2877 /* External data file header extension */
2878 if (has_data_file(bs) && s->image_data_file) {
2879 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_DATA_FILE,
2880 s->image_data_file, strlen(s->image_data_file),
2881 buflen);
2882 if (ret < 0) {
2883 goto fail;
2886 buf += ret;
2887 buflen -= ret;
2890 /* Full disk encryption header pointer extension */
2891 if (s->crypto_header.offset != 0) {
2892 s->crypto_header.offset = cpu_to_be64(s->crypto_header.offset);
2893 s->crypto_header.length = cpu_to_be64(s->crypto_header.length);
2894 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_CRYPTO_HEADER,
2895 &s->crypto_header, sizeof(s->crypto_header),
2896 buflen);
2897 s->crypto_header.offset = be64_to_cpu(s->crypto_header.offset);
2898 s->crypto_header.length = be64_to_cpu(s->crypto_header.length);
2899 if (ret < 0) {
2900 goto fail;
2902 buf += ret;
2903 buflen -= ret;
2907 * Feature table. A mere 8 feature names occupies 392 bytes, and
2908 * when coupled with the v3 minimum header of 104 bytes plus the
2909 * 8-byte end-of-extension marker, that would leave only 8 bytes
2910 * for a backing file name in an image with 512-byte clusters.
2911 * Thus, we choose to omit this header for cluster sizes 4k and
2912 * smaller.
2914 if (s->qcow_version >= 3 && s->cluster_size > 4096) {
2915 static const Qcow2Feature features[] = {
2917 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
2918 .bit = QCOW2_INCOMPAT_DIRTY_BITNR,
2919 .name = "dirty bit",
2922 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
2923 .bit = QCOW2_INCOMPAT_CORRUPT_BITNR,
2924 .name = "corrupt bit",
2927 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
2928 .bit = QCOW2_INCOMPAT_DATA_FILE_BITNR,
2929 .name = "external data file",
2932 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
2933 .bit = QCOW2_INCOMPAT_COMPRESSION_BITNR,
2934 .name = "compression type",
2937 .type = QCOW2_FEAT_TYPE_COMPATIBLE,
2938 .bit = QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR,
2939 .name = "lazy refcounts",
2942 .type = QCOW2_FEAT_TYPE_AUTOCLEAR,
2943 .bit = QCOW2_AUTOCLEAR_BITMAPS_BITNR,
2944 .name = "bitmaps",
2947 .type = QCOW2_FEAT_TYPE_AUTOCLEAR,
2948 .bit = QCOW2_AUTOCLEAR_DATA_FILE_RAW_BITNR,
2949 .name = "raw external data",
2953 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_FEATURE_TABLE,
2954 features, sizeof(features), buflen);
2955 if (ret < 0) {
2956 goto fail;
2958 buf += ret;
2959 buflen -= ret;
2962 /* Bitmap extension */
2963 if (s->nb_bitmaps > 0) {
2964 Qcow2BitmapHeaderExt bitmaps_header = {
2965 .nb_bitmaps = cpu_to_be32(s->nb_bitmaps),
2966 .bitmap_directory_size =
2967 cpu_to_be64(s->bitmap_directory_size),
2968 .bitmap_directory_offset =
2969 cpu_to_be64(s->bitmap_directory_offset)
2971 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BITMAPS,
2972 &bitmaps_header, sizeof(bitmaps_header),
2973 buflen);
2974 if (ret < 0) {
2975 goto fail;
2977 buf += ret;
2978 buflen -= ret;
2981 /* Keep unknown header extensions */
2982 QLIST_FOREACH(uext, &s->unknown_header_ext, next) {
2983 ret = header_ext_add(buf, uext->magic, uext->data, uext->len, buflen);
2984 if (ret < 0) {
2985 goto fail;
2988 buf += ret;
2989 buflen -= ret;
2992 /* End of header extensions */
2993 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_END, NULL, 0, buflen);
2994 if (ret < 0) {
2995 goto fail;
2998 buf += ret;
2999 buflen -= ret;
3001 /* Backing file name */
3002 if (s->image_backing_file) {
3003 size_t backing_file_len = strlen(s->image_backing_file);
3005 if (buflen < backing_file_len) {
3006 ret = -ENOSPC;
3007 goto fail;
3010 /* Using strncpy is ok here, since buf is not NUL-terminated. */
3011 strncpy(buf, s->image_backing_file, buflen);
3013 header->backing_file_offset = cpu_to_be64(buf - ((char*) header));
3014 header->backing_file_size = cpu_to_be32(backing_file_len);
3017 /* Write the new header */
3018 ret = bdrv_pwrite(bs->file, 0, header, s->cluster_size);
3019 if (ret < 0) {
3020 goto fail;
3023 ret = 0;
3024 fail:
3025 qemu_vfree(header);
3026 return ret;
3029 static int qcow2_change_backing_file(BlockDriverState *bs,
3030 const char *backing_file, const char *backing_fmt)
3032 BDRVQcow2State *s = bs->opaque;
3034 /* Adding a backing file means that the external data file alone won't be
3035 * enough to make sense of the content */
3036 if (backing_file && data_file_is_raw(bs)) {
3037 return -EINVAL;
3040 if (backing_file && strlen(backing_file) > 1023) {
3041 return -EINVAL;
3044 pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
3045 backing_file ?: "");
3046 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
3047 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
3049 g_free(s->image_backing_file);
3050 g_free(s->image_backing_format);
3052 s->image_backing_file = backing_file ? g_strdup(bs->backing_file) : NULL;
3053 s->image_backing_format = backing_fmt ? g_strdup(bs->backing_format) : NULL;
3055 return qcow2_update_header(bs);
3058 static int qcow2_set_up_encryption(BlockDriverState *bs,
3059 QCryptoBlockCreateOptions *cryptoopts,
3060 Error **errp)
3062 BDRVQcow2State *s = bs->opaque;
3063 QCryptoBlock *crypto = NULL;
3064 int fmt, ret;
3066 switch (cryptoopts->format) {
3067 case Q_CRYPTO_BLOCK_FORMAT_LUKS:
3068 fmt = QCOW_CRYPT_LUKS;
3069 break;
3070 case Q_CRYPTO_BLOCK_FORMAT_QCOW:
3071 fmt = QCOW_CRYPT_AES;
3072 break;
3073 default:
3074 error_setg(errp, "Crypto format not supported in qcow2");
3075 return -EINVAL;
3078 s->crypt_method_header = fmt;
3080 crypto = qcrypto_block_create(cryptoopts, "encrypt.",
3081 qcow2_crypto_hdr_init_func,
3082 qcow2_crypto_hdr_write_func,
3083 bs, errp);
3084 if (!crypto) {
3085 return -EINVAL;
3088 ret = qcow2_update_header(bs);
3089 if (ret < 0) {
3090 error_setg_errno(errp, -ret, "Could not write encryption header");
3091 goto out;
3094 ret = 0;
3095 out:
3096 qcrypto_block_free(crypto);
3097 return ret;
3101 * Preallocates metadata structures for data clusters between @offset (in the
3102 * guest disk) and @new_length (which is thus generally the new guest disk
3103 * size).
3105 * Returns: 0 on success, -errno on failure.
3107 static int coroutine_fn preallocate_co(BlockDriverState *bs, uint64_t offset,
3108 uint64_t new_length, PreallocMode mode,
3109 Error **errp)
3111 BDRVQcow2State *s = bs->opaque;
3112 uint64_t bytes;
3113 uint64_t host_offset = 0;
3114 int64_t file_length;
3115 unsigned int cur_bytes;
3116 int ret;
3117 QCowL2Meta *meta;
3119 assert(offset <= new_length);
3120 bytes = new_length - offset;
3122 while (bytes) {
3123 cur_bytes = MIN(bytes, QEMU_ALIGN_DOWN(INT_MAX, s->cluster_size));
3124 ret = qcow2_alloc_cluster_offset(bs, offset, &cur_bytes,
3125 &host_offset, &meta);
3126 if (ret < 0) {
3127 error_setg_errno(errp, -ret, "Allocating clusters failed");
3128 return ret;
3131 while (meta) {
3132 QCowL2Meta *next = meta->next;
3134 ret = qcow2_alloc_cluster_link_l2(bs, meta);
3135 if (ret < 0) {
3136 error_setg_errno(errp, -ret, "Mapping clusters failed");
3137 qcow2_free_any_clusters(bs, meta->alloc_offset,
3138 meta->nb_clusters, QCOW2_DISCARD_NEVER);
3139 return ret;
3142 /* There are no dependent requests, but we need to remove our
3143 * request from the list of in-flight requests */
3144 QLIST_REMOVE(meta, next_in_flight);
3146 g_free(meta);
3147 meta = next;
3150 /* TODO Preallocate data if requested */
3152 bytes -= cur_bytes;
3153 offset += cur_bytes;
3157 * It is expected that the image file is large enough to actually contain
3158 * all of the allocated clusters (otherwise we get failing reads after
3159 * EOF). Extend the image to the last allocated sector.
3161 file_length = bdrv_getlength(s->data_file->bs);
3162 if (file_length < 0) {
3163 error_setg_errno(errp, -file_length, "Could not get file size");
3164 return file_length;
3167 if (host_offset + cur_bytes > file_length) {
3168 if (mode == PREALLOC_MODE_METADATA) {
3169 mode = PREALLOC_MODE_OFF;
3171 ret = bdrv_co_truncate(s->data_file, host_offset + cur_bytes, false,
3172 mode, 0, errp);
3173 if (ret < 0) {
3174 return ret;
3178 return 0;
3181 /* qcow2_refcount_metadata_size:
3182 * @clusters: number of clusters to refcount (including data and L1/L2 tables)
3183 * @cluster_size: size of a cluster, in bytes
3184 * @refcount_order: refcount bits power-of-2 exponent
3185 * @generous_increase: allow for the refcount table to be 1.5x as large as it
3186 * needs to be
3188 * Returns: Number of bytes required for refcount blocks and table metadata.
3190 int64_t qcow2_refcount_metadata_size(int64_t clusters, size_t cluster_size,
3191 int refcount_order, bool generous_increase,
3192 uint64_t *refblock_count)
3195 * Every host cluster is reference-counted, including metadata (even
3196 * refcount metadata is recursively included).
3198 * An accurate formula for the size of refcount metadata size is difficult
3199 * to derive. An easier method of calculation is finding the fixed point
3200 * where no further refcount blocks or table clusters are required to
3201 * reference count every cluster.
3203 int64_t blocks_per_table_cluster = cluster_size / sizeof(uint64_t);
3204 int64_t refcounts_per_block = cluster_size * 8 / (1 << refcount_order);
3205 int64_t table = 0; /* number of refcount table clusters */
3206 int64_t blocks = 0; /* number of refcount block clusters */
3207 int64_t last;
3208 int64_t n = 0;
3210 do {
3211 last = n;
3212 blocks = DIV_ROUND_UP(clusters + table + blocks, refcounts_per_block);
3213 table = DIV_ROUND_UP(blocks, blocks_per_table_cluster);
3214 n = clusters + blocks + table;
3216 if (n == last && generous_increase) {
3217 clusters += DIV_ROUND_UP(table, 2);
3218 n = 0; /* force another loop */
3219 generous_increase = false;
3221 } while (n != last);
3223 if (refblock_count) {
3224 *refblock_count = blocks;
3227 return (blocks + table) * cluster_size;
3231 * qcow2_calc_prealloc_size:
3232 * @total_size: virtual disk size in bytes
3233 * @cluster_size: cluster size in bytes
3234 * @refcount_order: refcount bits power-of-2 exponent
3236 * Returns: Total number of bytes required for the fully allocated image
3237 * (including metadata).
3239 static int64_t qcow2_calc_prealloc_size(int64_t total_size,
3240 size_t cluster_size,
3241 int refcount_order)
3243 int64_t meta_size = 0;
3244 uint64_t nl1e, nl2e;
3245 int64_t aligned_total_size = ROUND_UP(total_size, cluster_size);
3247 /* header: 1 cluster */
3248 meta_size += cluster_size;
3250 /* total size of L2 tables */
3251 nl2e = aligned_total_size / cluster_size;
3252 nl2e = ROUND_UP(nl2e, cluster_size / sizeof(uint64_t));
3253 meta_size += nl2e * sizeof(uint64_t);
3255 /* total size of L1 tables */
3256 nl1e = nl2e * sizeof(uint64_t) / cluster_size;
3257 nl1e = ROUND_UP(nl1e, cluster_size / sizeof(uint64_t));
3258 meta_size += nl1e * sizeof(uint64_t);
3260 /* total size of refcount table and blocks */
3261 meta_size += qcow2_refcount_metadata_size(
3262 (meta_size + aligned_total_size) / cluster_size,
3263 cluster_size, refcount_order, false, NULL);
3265 return meta_size + aligned_total_size;
3268 static bool validate_cluster_size(size_t cluster_size, Error **errp)
3270 int cluster_bits = ctz32(cluster_size);
3271 if (cluster_bits < MIN_CLUSTER_BITS || cluster_bits > MAX_CLUSTER_BITS ||
3272 (1 << cluster_bits) != cluster_size)
3274 error_setg(errp, "Cluster size must be a power of two between %d and "
3275 "%dk", 1 << MIN_CLUSTER_BITS, 1 << (MAX_CLUSTER_BITS - 10));
3276 return false;
3278 return true;
3281 static size_t qcow2_opt_get_cluster_size_del(QemuOpts *opts, Error **errp)
3283 size_t cluster_size;
3285 cluster_size = qemu_opt_get_size_del(opts, BLOCK_OPT_CLUSTER_SIZE,
3286 DEFAULT_CLUSTER_SIZE);
3287 if (!validate_cluster_size(cluster_size, errp)) {
3288 return 0;
3290 return cluster_size;
3293 static int qcow2_opt_get_version_del(QemuOpts *opts, Error **errp)
3295 char *buf;
3296 int ret;
3298 buf = qemu_opt_get_del(opts, BLOCK_OPT_COMPAT_LEVEL);
3299 if (!buf) {
3300 ret = 3; /* default */
3301 } else if (!strcmp(buf, "0.10")) {
3302 ret = 2;
3303 } else if (!strcmp(buf, "1.1")) {
3304 ret = 3;
3305 } else {
3306 error_setg(errp, "Invalid compatibility level: '%s'", buf);
3307 ret = -EINVAL;
3309 g_free(buf);
3310 return ret;
3313 static uint64_t qcow2_opt_get_refcount_bits_del(QemuOpts *opts, int version,
3314 Error **errp)
3316 uint64_t refcount_bits;
3318 refcount_bits = qemu_opt_get_number_del(opts, BLOCK_OPT_REFCOUNT_BITS, 16);
3319 if (refcount_bits > 64 || !is_power_of_2(refcount_bits)) {
3320 error_setg(errp, "Refcount width must be a power of two and may not "
3321 "exceed 64 bits");
3322 return 0;
3325 if (version < 3 && refcount_bits != 16) {
3326 error_setg(errp, "Different refcount widths than 16 bits require "
3327 "compatibility level 1.1 or above (use compat=1.1 or "
3328 "greater)");
3329 return 0;
3332 return refcount_bits;
3335 static int coroutine_fn
3336 qcow2_co_create(BlockdevCreateOptions *create_options, Error **errp)
3338 BlockdevCreateOptionsQcow2 *qcow2_opts;
3339 QDict *options;
3342 * Open the image file and write a minimal qcow2 header.
3344 * We keep things simple and start with a zero-sized image. We also
3345 * do without refcount blocks or a L1 table for now. We'll fix the
3346 * inconsistency later.
3348 * We do need a refcount table because growing the refcount table means
3349 * allocating two new refcount blocks - the second of which would be at
3350 * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
3351 * size for any qcow2 image.
3353 BlockBackend *blk = NULL;
3354 BlockDriverState *bs = NULL;
3355 BlockDriverState *data_bs = NULL;
3356 QCowHeader *header;
3357 size_t cluster_size;
3358 int version;
3359 int refcount_order;
3360 uint64_t* refcount_table;
3361 Error *local_err = NULL;
3362 int ret;
3363 uint8_t compression_type = QCOW2_COMPRESSION_TYPE_ZLIB;
3365 assert(create_options->driver == BLOCKDEV_DRIVER_QCOW2);
3366 qcow2_opts = &create_options->u.qcow2;
3368 bs = bdrv_open_blockdev_ref(qcow2_opts->file, errp);
3369 if (bs == NULL) {
3370 return -EIO;
3373 /* Validate options and set default values */
3374 if (!QEMU_IS_ALIGNED(qcow2_opts->size, BDRV_SECTOR_SIZE)) {
3375 error_setg(errp, "Image size must be a multiple of %u bytes",
3376 (unsigned) BDRV_SECTOR_SIZE);
3377 ret = -EINVAL;
3378 goto out;
3381 if (qcow2_opts->has_version) {
3382 switch (qcow2_opts->version) {
3383 case BLOCKDEV_QCOW2_VERSION_V2:
3384 version = 2;
3385 break;
3386 case BLOCKDEV_QCOW2_VERSION_V3:
3387 version = 3;
3388 break;
3389 default:
3390 g_assert_not_reached();
3392 } else {
3393 version = 3;
3396 if (qcow2_opts->has_cluster_size) {
3397 cluster_size = qcow2_opts->cluster_size;
3398 } else {
3399 cluster_size = DEFAULT_CLUSTER_SIZE;
3402 if (!validate_cluster_size(cluster_size, errp)) {
3403 ret = -EINVAL;
3404 goto out;
3407 if (!qcow2_opts->has_preallocation) {
3408 qcow2_opts->preallocation = PREALLOC_MODE_OFF;
3410 if (qcow2_opts->has_backing_file &&
3411 qcow2_opts->preallocation != PREALLOC_MODE_OFF)
3413 error_setg(errp, "Backing file and preallocation cannot be used at "
3414 "the same time");
3415 ret = -EINVAL;
3416 goto out;
3418 if (qcow2_opts->has_backing_fmt && !qcow2_opts->has_backing_file) {
3419 error_setg(errp, "Backing format cannot be used without backing file");
3420 ret = -EINVAL;
3421 goto out;
3424 if (!qcow2_opts->has_lazy_refcounts) {
3425 qcow2_opts->lazy_refcounts = false;
3427 if (version < 3 && qcow2_opts->lazy_refcounts) {
3428 error_setg(errp, "Lazy refcounts only supported with compatibility "
3429 "level 1.1 and above (use version=v3 or greater)");
3430 ret = -EINVAL;
3431 goto out;
3434 if (!qcow2_opts->has_refcount_bits) {
3435 qcow2_opts->refcount_bits = 16;
3437 if (qcow2_opts->refcount_bits > 64 ||
3438 !is_power_of_2(qcow2_opts->refcount_bits))
3440 error_setg(errp, "Refcount width must be a power of two and may not "
3441 "exceed 64 bits");
3442 ret = -EINVAL;
3443 goto out;
3445 if (version < 3 && qcow2_opts->refcount_bits != 16) {
3446 error_setg(errp, "Different refcount widths than 16 bits require "
3447 "compatibility level 1.1 or above (use version=v3 or "
3448 "greater)");
3449 ret = -EINVAL;
3450 goto out;
3452 refcount_order = ctz32(qcow2_opts->refcount_bits);
3454 if (qcow2_opts->data_file_raw && !qcow2_opts->data_file) {
3455 error_setg(errp, "data-file-raw requires data-file");
3456 ret = -EINVAL;
3457 goto out;
3459 if (qcow2_opts->data_file_raw && qcow2_opts->has_backing_file) {
3460 error_setg(errp, "Backing file and data-file-raw cannot be used at "
3461 "the same time");
3462 ret = -EINVAL;
3463 goto out;
3466 if (qcow2_opts->data_file) {
3467 if (version < 3) {
3468 error_setg(errp, "External data files are only supported with "
3469 "compatibility level 1.1 and above (use version=v3 or "
3470 "greater)");
3471 ret = -EINVAL;
3472 goto out;
3474 data_bs = bdrv_open_blockdev_ref(qcow2_opts->data_file, errp);
3475 if (data_bs == NULL) {
3476 ret = -EIO;
3477 goto out;
3481 if (qcow2_opts->has_compression_type &&
3482 qcow2_opts->compression_type != QCOW2_COMPRESSION_TYPE_ZLIB) {
3484 ret = -EINVAL;
3486 if (version < 3) {
3487 error_setg(errp, "Non-zlib compression type is only supported with "
3488 "compatibility level 1.1 and above (use version=v3 or "
3489 "greater)");
3490 goto out;
3493 switch (qcow2_opts->compression_type) {
3494 #ifdef CONFIG_ZSTD
3495 case QCOW2_COMPRESSION_TYPE_ZSTD:
3496 break;
3497 #endif
3498 default:
3499 error_setg(errp, "Unknown compression type");
3500 goto out;
3503 compression_type = qcow2_opts->compression_type;
3506 /* Create BlockBackend to write to the image */
3507 blk = blk_new_with_bs(bs, BLK_PERM_WRITE | BLK_PERM_RESIZE, BLK_PERM_ALL,
3508 errp);
3509 if (!blk) {
3510 ret = -EPERM;
3511 goto out;
3513 blk_set_allow_write_beyond_eof(blk, true);
3515 /* Write the header */
3516 QEMU_BUILD_BUG_ON((1 << MIN_CLUSTER_BITS) < sizeof(*header));
3517 header = g_malloc0(cluster_size);
3518 *header = (QCowHeader) {
3519 .magic = cpu_to_be32(QCOW_MAGIC),
3520 .version = cpu_to_be32(version),
3521 .cluster_bits = cpu_to_be32(ctz32(cluster_size)),
3522 .size = cpu_to_be64(0),
3523 .l1_table_offset = cpu_to_be64(0),
3524 .l1_size = cpu_to_be32(0),
3525 .refcount_table_offset = cpu_to_be64(cluster_size),
3526 .refcount_table_clusters = cpu_to_be32(1),
3527 .refcount_order = cpu_to_be32(refcount_order),
3528 /* don't deal with endianness since compression_type is 1 byte long */
3529 .compression_type = compression_type,
3530 .header_length = cpu_to_be32(sizeof(*header)),
3533 /* We'll update this to correct value later */
3534 header->crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
3536 if (qcow2_opts->lazy_refcounts) {
3537 header->compatible_features |=
3538 cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS);
3540 if (data_bs) {
3541 header->incompatible_features |=
3542 cpu_to_be64(QCOW2_INCOMPAT_DATA_FILE);
3544 if (qcow2_opts->data_file_raw) {
3545 header->autoclear_features |=
3546 cpu_to_be64(QCOW2_AUTOCLEAR_DATA_FILE_RAW);
3548 if (compression_type != QCOW2_COMPRESSION_TYPE_ZLIB) {
3549 header->incompatible_features |=
3550 cpu_to_be64(QCOW2_INCOMPAT_COMPRESSION);
3553 ret = blk_pwrite(blk, 0, header, cluster_size, 0);
3554 g_free(header);
3555 if (ret < 0) {
3556 error_setg_errno(errp, -ret, "Could not write qcow2 header");
3557 goto out;
3560 /* Write a refcount table with one refcount block */
3561 refcount_table = g_malloc0(2 * cluster_size);
3562 refcount_table[0] = cpu_to_be64(2 * cluster_size);
3563 ret = blk_pwrite(blk, cluster_size, refcount_table, 2 * cluster_size, 0);
3564 g_free(refcount_table);
3566 if (ret < 0) {
3567 error_setg_errno(errp, -ret, "Could not write refcount table");
3568 goto out;
3571 blk_unref(blk);
3572 blk = NULL;
3575 * And now open the image and make it consistent first (i.e. increase the
3576 * refcount of the cluster that is occupied by the header and the refcount
3577 * table)
3579 options = qdict_new();
3580 qdict_put_str(options, "driver", "qcow2");
3581 qdict_put_str(options, "file", bs->node_name);
3582 if (data_bs) {
3583 qdict_put_str(options, "data-file", data_bs->node_name);
3585 blk = blk_new_open(NULL, NULL, options,
3586 BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_NO_FLUSH,
3587 &local_err);
3588 if (blk == NULL) {
3589 error_propagate(errp, local_err);
3590 ret = -EIO;
3591 goto out;
3594 ret = qcow2_alloc_clusters(blk_bs(blk), 3 * cluster_size);
3595 if (ret < 0) {
3596 error_setg_errno(errp, -ret, "Could not allocate clusters for qcow2 "
3597 "header and refcount table");
3598 goto out;
3600 } else if (ret != 0) {
3601 error_report("Huh, first cluster in empty image is already in use?");
3602 abort();
3605 /* Set the external data file if necessary */
3606 if (data_bs) {
3607 BDRVQcow2State *s = blk_bs(blk)->opaque;
3608 s->image_data_file = g_strdup(data_bs->filename);
3611 /* Create a full header (including things like feature table) */
3612 ret = qcow2_update_header(blk_bs(blk));
3613 if (ret < 0) {
3614 error_setg_errno(errp, -ret, "Could not update qcow2 header");
3615 goto out;
3618 /* Okay, now that we have a valid image, let's give it the right size */
3619 ret = blk_truncate(blk, qcow2_opts->size, false, qcow2_opts->preallocation,
3620 0, errp);
3621 if (ret < 0) {
3622 error_prepend(errp, "Could not resize image: ");
3623 goto out;
3626 /* Want a backing file? There you go. */
3627 if (qcow2_opts->has_backing_file) {
3628 const char *backing_format = NULL;
3630 if (qcow2_opts->has_backing_fmt) {
3631 backing_format = BlockdevDriver_str(qcow2_opts->backing_fmt);
3634 ret = bdrv_change_backing_file(blk_bs(blk), qcow2_opts->backing_file,
3635 backing_format);
3636 if (ret < 0) {
3637 error_setg_errno(errp, -ret, "Could not assign backing file '%s' "
3638 "with format '%s'", qcow2_opts->backing_file,
3639 backing_format);
3640 goto out;
3644 /* Want encryption? There you go. */
3645 if (qcow2_opts->has_encrypt) {
3646 ret = qcow2_set_up_encryption(blk_bs(blk), qcow2_opts->encrypt, errp);
3647 if (ret < 0) {
3648 goto out;
3652 blk_unref(blk);
3653 blk = NULL;
3655 /* Reopen the image without BDRV_O_NO_FLUSH to flush it before returning.
3656 * Using BDRV_O_NO_IO, since encryption is now setup we don't want to
3657 * have to setup decryption context. We're not doing any I/O on the top
3658 * level BlockDriverState, only lower layers, where BDRV_O_NO_IO does
3659 * not have effect.
3661 options = qdict_new();
3662 qdict_put_str(options, "driver", "qcow2");
3663 qdict_put_str(options, "file", bs->node_name);
3664 if (data_bs) {
3665 qdict_put_str(options, "data-file", data_bs->node_name);
3667 blk = blk_new_open(NULL, NULL, options,
3668 BDRV_O_RDWR | BDRV_O_NO_BACKING | BDRV_O_NO_IO,
3669 &local_err);
3670 if (blk == NULL) {
3671 error_propagate(errp, local_err);
3672 ret = -EIO;
3673 goto out;
3676 ret = 0;
3677 out:
3678 blk_unref(blk);
3679 bdrv_unref(bs);
3680 bdrv_unref(data_bs);
3681 return ret;
3684 static int coroutine_fn qcow2_co_create_opts(BlockDriver *drv,
3685 const char *filename,
3686 QemuOpts *opts,
3687 Error **errp)
3689 BlockdevCreateOptions *create_options = NULL;
3690 QDict *qdict;
3691 Visitor *v;
3692 BlockDriverState *bs = NULL;
3693 BlockDriverState *data_bs = NULL;
3694 Error *local_err = NULL;
3695 const char *val;
3696 int ret;
3698 /* Only the keyval visitor supports the dotted syntax needed for
3699 * encryption, so go through a QDict before getting a QAPI type. Ignore
3700 * options meant for the protocol layer so that the visitor doesn't
3701 * complain. */
3702 qdict = qemu_opts_to_qdict_filtered(opts, NULL, bdrv_qcow2.create_opts,
3703 true);
3705 /* Handle encryption options */
3706 val = qdict_get_try_str(qdict, BLOCK_OPT_ENCRYPT);
3707 if (val && !strcmp(val, "on")) {
3708 qdict_put_str(qdict, BLOCK_OPT_ENCRYPT, "qcow");
3709 } else if (val && !strcmp(val, "off")) {
3710 qdict_del(qdict, BLOCK_OPT_ENCRYPT);
3713 val = qdict_get_try_str(qdict, BLOCK_OPT_ENCRYPT_FORMAT);
3714 if (val && !strcmp(val, "aes")) {
3715 qdict_put_str(qdict, BLOCK_OPT_ENCRYPT_FORMAT, "qcow");
3718 /* Convert compat=0.10/1.1 into compat=v2/v3, to be renamed into
3719 * version=v2/v3 below. */
3720 val = qdict_get_try_str(qdict, BLOCK_OPT_COMPAT_LEVEL);
3721 if (val && !strcmp(val, "0.10")) {
3722 qdict_put_str(qdict, BLOCK_OPT_COMPAT_LEVEL, "v2");
3723 } else if (val && !strcmp(val, "1.1")) {
3724 qdict_put_str(qdict, BLOCK_OPT_COMPAT_LEVEL, "v3");
3727 /* Change legacy command line options into QMP ones */
3728 static const QDictRenames opt_renames[] = {
3729 { BLOCK_OPT_BACKING_FILE, "backing-file" },
3730 { BLOCK_OPT_BACKING_FMT, "backing-fmt" },
3731 { BLOCK_OPT_CLUSTER_SIZE, "cluster-size" },
3732 { BLOCK_OPT_LAZY_REFCOUNTS, "lazy-refcounts" },
3733 { BLOCK_OPT_REFCOUNT_BITS, "refcount-bits" },
3734 { BLOCK_OPT_ENCRYPT, BLOCK_OPT_ENCRYPT_FORMAT },
3735 { BLOCK_OPT_COMPAT_LEVEL, "version" },
3736 { BLOCK_OPT_DATA_FILE_RAW, "data-file-raw" },
3737 { BLOCK_OPT_COMPRESSION_TYPE, "compression-type" },
3738 { NULL, NULL },
3741 if (!qdict_rename_keys(qdict, opt_renames, errp)) {
3742 ret = -EINVAL;
3743 goto finish;
3746 /* Create and open the file (protocol layer) */
3747 ret = bdrv_create_file(filename, opts, errp);
3748 if (ret < 0) {
3749 goto finish;
3752 bs = bdrv_open(filename, NULL, NULL,
3753 BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_PROTOCOL, errp);
3754 if (bs == NULL) {
3755 ret = -EIO;
3756 goto finish;
3759 /* Create and open an external data file (protocol layer) */
3760 val = qdict_get_try_str(qdict, BLOCK_OPT_DATA_FILE);
3761 if (val) {
3762 ret = bdrv_create_file(val, opts, errp);
3763 if (ret < 0) {
3764 goto finish;
3767 data_bs = bdrv_open(val, NULL, NULL,
3768 BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_PROTOCOL,
3769 errp);
3770 if (data_bs == NULL) {
3771 ret = -EIO;
3772 goto finish;
3775 qdict_del(qdict, BLOCK_OPT_DATA_FILE);
3776 qdict_put_str(qdict, "data-file", data_bs->node_name);
3779 /* Set 'driver' and 'node' options */
3780 qdict_put_str(qdict, "driver", "qcow2");
3781 qdict_put_str(qdict, "file", bs->node_name);
3783 /* Now get the QAPI type BlockdevCreateOptions */
3784 v = qobject_input_visitor_new_flat_confused(qdict, errp);
3785 if (!v) {
3786 ret = -EINVAL;
3787 goto finish;
3790 visit_type_BlockdevCreateOptions(v, NULL, &create_options, &local_err);
3791 visit_free(v);
3793 if (local_err) {
3794 error_propagate(errp, local_err);
3795 ret = -EINVAL;
3796 goto finish;
3799 /* Silently round up size */
3800 create_options->u.qcow2.size = ROUND_UP(create_options->u.qcow2.size,
3801 BDRV_SECTOR_SIZE);
3803 /* Create the qcow2 image (format layer) */
3804 ret = qcow2_co_create(create_options, errp);
3805 if (ret < 0) {
3806 goto finish;
3809 ret = 0;
3810 finish:
3811 qobject_unref(qdict);
3812 bdrv_unref(bs);
3813 bdrv_unref(data_bs);
3814 qapi_free_BlockdevCreateOptions(create_options);
3815 return ret;
3819 static bool is_zero(BlockDriverState *bs, int64_t offset, int64_t bytes)
3821 int64_t nr;
3822 int res;
3824 /* Clamp to image length, before checking status of underlying sectors */
3825 if (offset + bytes > bs->total_sectors * BDRV_SECTOR_SIZE) {
3826 bytes = bs->total_sectors * BDRV_SECTOR_SIZE - offset;
3829 if (!bytes) {
3830 return true;
3832 res = bdrv_block_status_above(bs, NULL, offset, bytes, &nr, NULL, NULL);
3833 return res >= 0 && (res & BDRV_BLOCK_ZERO) && nr == bytes;
3836 static coroutine_fn int qcow2_co_pwrite_zeroes(BlockDriverState *bs,
3837 int64_t offset, int bytes, BdrvRequestFlags flags)
3839 int ret;
3840 BDRVQcow2State *s = bs->opaque;
3842 uint32_t head = offset % s->cluster_size;
3843 uint32_t tail = (offset + bytes) % s->cluster_size;
3845 trace_qcow2_pwrite_zeroes_start_req(qemu_coroutine_self(), offset, bytes);
3846 if (offset + bytes == bs->total_sectors * BDRV_SECTOR_SIZE) {
3847 tail = 0;
3850 if (head || tail) {
3851 uint64_t off;
3852 unsigned int nr;
3854 assert(head + bytes <= s->cluster_size);
3856 /* check whether remainder of cluster already reads as zero */
3857 if (!(is_zero(bs, offset - head, head) &&
3858 is_zero(bs, offset + bytes,
3859 tail ? s->cluster_size - tail : 0))) {
3860 return -ENOTSUP;
3863 qemu_co_mutex_lock(&s->lock);
3864 /* We can have new write after previous check */
3865 offset = QEMU_ALIGN_DOWN(offset, s->cluster_size);
3866 bytes = s->cluster_size;
3867 nr = s->cluster_size;
3868 ret = qcow2_get_cluster_offset(bs, offset, &nr, &off);
3869 if (ret != QCOW2_CLUSTER_UNALLOCATED &&
3870 ret != QCOW2_CLUSTER_ZERO_PLAIN &&
3871 ret != QCOW2_CLUSTER_ZERO_ALLOC) {
3872 qemu_co_mutex_unlock(&s->lock);
3873 return -ENOTSUP;
3875 } else {
3876 qemu_co_mutex_lock(&s->lock);
3879 trace_qcow2_pwrite_zeroes(qemu_coroutine_self(), offset, bytes);
3881 /* Whatever is left can use real zero clusters */
3882 ret = qcow2_cluster_zeroize(bs, offset, bytes, flags);
3883 qemu_co_mutex_unlock(&s->lock);
3885 return ret;
3888 static coroutine_fn int qcow2_co_pdiscard(BlockDriverState *bs,
3889 int64_t offset, int bytes)
3891 int ret;
3892 BDRVQcow2State *s = bs->opaque;
3894 /* If the image does not support QCOW_OFLAG_ZERO then discarding
3895 * clusters could expose stale data from the backing file. */
3896 if (s->qcow_version < 3 && bs->backing) {
3897 return -ENOTSUP;
3900 if (!QEMU_IS_ALIGNED(offset | bytes, s->cluster_size)) {
3901 assert(bytes < s->cluster_size);
3902 /* Ignore partial clusters, except for the special case of the
3903 * complete partial cluster at the end of an unaligned file */
3904 if (!QEMU_IS_ALIGNED(offset, s->cluster_size) ||
3905 offset + bytes != bs->total_sectors * BDRV_SECTOR_SIZE) {
3906 return -ENOTSUP;
3910 qemu_co_mutex_lock(&s->lock);
3911 ret = qcow2_cluster_discard(bs, offset, bytes, QCOW2_DISCARD_REQUEST,
3912 false);
3913 qemu_co_mutex_unlock(&s->lock);
3914 return ret;
3917 static int coroutine_fn
3918 qcow2_co_copy_range_from(BlockDriverState *bs,
3919 BdrvChild *src, uint64_t src_offset,
3920 BdrvChild *dst, uint64_t dst_offset,
3921 uint64_t bytes, BdrvRequestFlags read_flags,
3922 BdrvRequestFlags write_flags)
3924 BDRVQcow2State *s = bs->opaque;
3925 int ret;
3926 unsigned int cur_bytes; /* number of bytes in current iteration */
3927 BdrvChild *child = NULL;
3928 BdrvRequestFlags cur_write_flags;
3930 assert(!bs->encrypted);
3931 qemu_co_mutex_lock(&s->lock);
3933 while (bytes != 0) {
3934 uint64_t copy_offset = 0;
3935 /* prepare next request */
3936 cur_bytes = MIN(bytes, INT_MAX);
3937 cur_write_flags = write_flags;
3939 ret = qcow2_get_cluster_offset(bs, src_offset, &cur_bytes, &copy_offset);
3940 if (ret < 0) {
3941 goto out;
3944 switch (ret) {
3945 case QCOW2_CLUSTER_UNALLOCATED:
3946 if (bs->backing && bs->backing->bs) {
3947 int64_t backing_length = bdrv_getlength(bs->backing->bs);
3948 if (src_offset >= backing_length) {
3949 cur_write_flags |= BDRV_REQ_ZERO_WRITE;
3950 } else {
3951 child = bs->backing;
3952 cur_bytes = MIN(cur_bytes, backing_length - src_offset);
3953 copy_offset = src_offset;
3955 } else {
3956 cur_write_flags |= BDRV_REQ_ZERO_WRITE;
3958 break;
3960 case QCOW2_CLUSTER_ZERO_PLAIN:
3961 case QCOW2_CLUSTER_ZERO_ALLOC:
3962 cur_write_flags |= BDRV_REQ_ZERO_WRITE;
3963 break;
3965 case QCOW2_CLUSTER_COMPRESSED:
3966 ret = -ENOTSUP;
3967 goto out;
3969 case QCOW2_CLUSTER_NORMAL:
3970 child = s->data_file;
3971 copy_offset += offset_into_cluster(s, src_offset);
3972 break;
3974 default:
3975 abort();
3977 qemu_co_mutex_unlock(&s->lock);
3978 ret = bdrv_co_copy_range_from(child,
3979 copy_offset,
3980 dst, dst_offset,
3981 cur_bytes, read_flags, cur_write_flags);
3982 qemu_co_mutex_lock(&s->lock);
3983 if (ret < 0) {
3984 goto out;
3987 bytes -= cur_bytes;
3988 src_offset += cur_bytes;
3989 dst_offset += cur_bytes;
3991 ret = 0;
3993 out:
3994 qemu_co_mutex_unlock(&s->lock);
3995 return ret;
3998 static int coroutine_fn
3999 qcow2_co_copy_range_to(BlockDriverState *bs,
4000 BdrvChild *src, uint64_t src_offset,
4001 BdrvChild *dst, uint64_t dst_offset,
4002 uint64_t bytes, BdrvRequestFlags read_flags,
4003 BdrvRequestFlags write_flags)
4005 BDRVQcow2State *s = bs->opaque;
4006 int offset_in_cluster;
4007 int ret;
4008 unsigned int cur_bytes; /* number of sectors in current iteration */
4009 uint64_t cluster_offset;
4010 QCowL2Meta *l2meta = NULL;
4012 assert(!bs->encrypted);
4014 qemu_co_mutex_lock(&s->lock);
4016 while (bytes != 0) {
4018 l2meta = NULL;
4020 offset_in_cluster = offset_into_cluster(s, dst_offset);
4021 cur_bytes = MIN(bytes, INT_MAX);
4023 /* TODO:
4024 * If src->bs == dst->bs, we could simply copy by incrementing
4025 * the refcnt, without copying user data.
4026 * Or if src->bs == dst->bs->backing->bs, we could copy by discarding. */
4027 ret = qcow2_alloc_cluster_offset(bs, dst_offset, &cur_bytes,
4028 &cluster_offset, &l2meta);
4029 if (ret < 0) {
4030 goto fail;
4033 assert(offset_into_cluster(s, cluster_offset) == 0);
4035 ret = qcow2_pre_write_overlap_check(bs, 0,
4036 cluster_offset + offset_in_cluster, cur_bytes, true);
4037 if (ret < 0) {
4038 goto fail;
4041 qemu_co_mutex_unlock(&s->lock);
4042 ret = bdrv_co_copy_range_to(src, src_offset,
4043 s->data_file,
4044 cluster_offset + offset_in_cluster,
4045 cur_bytes, read_flags, write_flags);
4046 qemu_co_mutex_lock(&s->lock);
4047 if (ret < 0) {
4048 goto fail;
4051 ret = qcow2_handle_l2meta(bs, &l2meta, true);
4052 if (ret) {
4053 goto fail;
4056 bytes -= cur_bytes;
4057 src_offset += cur_bytes;
4058 dst_offset += cur_bytes;
4060 ret = 0;
4062 fail:
4063 qcow2_handle_l2meta(bs, &l2meta, false);
4065 qemu_co_mutex_unlock(&s->lock);
4067 trace_qcow2_writev_done_req(qemu_coroutine_self(), ret);
4069 return ret;
4072 static int coroutine_fn qcow2_co_truncate(BlockDriverState *bs, int64_t offset,
4073 bool exact, PreallocMode prealloc,
4074 BdrvRequestFlags flags, Error **errp)
4076 BDRVQcow2State *s = bs->opaque;
4077 uint64_t old_length;
4078 int64_t new_l1_size;
4079 int ret;
4080 QDict *options;
4082 if (prealloc != PREALLOC_MODE_OFF && prealloc != PREALLOC_MODE_METADATA &&
4083 prealloc != PREALLOC_MODE_FALLOC && prealloc != PREALLOC_MODE_FULL)
4085 error_setg(errp, "Unsupported preallocation mode '%s'",
4086 PreallocMode_str(prealloc));
4087 return -ENOTSUP;
4090 if (!QEMU_IS_ALIGNED(offset, BDRV_SECTOR_SIZE)) {
4091 error_setg(errp, "The new size must be a multiple of %u",
4092 (unsigned) BDRV_SECTOR_SIZE);
4093 return -EINVAL;
4096 qemu_co_mutex_lock(&s->lock);
4099 * Even though we store snapshot size for all images, it was not
4100 * required until v3, so it is not safe to proceed for v2.
4102 if (s->nb_snapshots && s->qcow_version < 3) {
4103 error_setg(errp, "Can't resize a v2 image which has snapshots");
4104 ret = -ENOTSUP;
4105 goto fail;
4108 /* See qcow2-bitmap.c for which bitmap scenarios prevent a resize. */
4109 if (qcow2_truncate_bitmaps_check(bs, errp)) {
4110 ret = -ENOTSUP;
4111 goto fail;
4114 old_length = bs->total_sectors * BDRV_SECTOR_SIZE;
4115 new_l1_size = size_to_l1(s, offset);
4117 if (offset < old_length) {
4118 int64_t last_cluster, old_file_size;
4119 if (prealloc != PREALLOC_MODE_OFF) {
4120 error_setg(errp,
4121 "Preallocation can't be used for shrinking an image");
4122 ret = -EINVAL;
4123 goto fail;
4126 ret = qcow2_cluster_discard(bs, ROUND_UP(offset, s->cluster_size),
4127 old_length - ROUND_UP(offset,
4128 s->cluster_size),
4129 QCOW2_DISCARD_ALWAYS, true);
4130 if (ret < 0) {
4131 error_setg_errno(errp, -ret, "Failed to discard cropped clusters");
4132 goto fail;
4135 ret = qcow2_shrink_l1_table(bs, new_l1_size);
4136 if (ret < 0) {
4137 error_setg_errno(errp, -ret,
4138 "Failed to reduce the number of L2 tables");
4139 goto fail;
4142 ret = qcow2_shrink_reftable(bs);
4143 if (ret < 0) {
4144 error_setg_errno(errp, -ret,
4145 "Failed to discard unused refblocks");
4146 goto fail;
4149 old_file_size = bdrv_getlength(bs->file->bs);
4150 if (old_file_size < 0) {
4151 error_setg_errno(errp, -old_file_size,
4152 "Failed to inquire current file length");
4153 ret = old_file_size;
4154 goto fail;
4156 last_cluster = qcow2_get_last_cluster(bs, old_file_size);
4157 if (last_cluster < 0) {
4158 error_setg_errno(errp, -last_cluster,
4159 "Failed to find the last cluster");
4160 ret = last_cluster;
4161 goto fail;
4163 if ((last_cluster + 1) * s->cluster_size < old_file_size) {
4164 Error *local_err = NULL;
4167 * Do not pass @exact here: It will not help the user if
4168 * we get an error here just because they wanted to shrink
4169 * their qcow2 image (on a block device) with qemu-img.
4170 * (And on the qcow2 layer, the @exact requirement is
4171 * always fulfilled, so there is no need to pass it on.)
4173 bdrv_co_truncate(bs->file, (last_cluster + 1) * s->cluster_size,
4174 false, PREALLOC_MODE_OFF, 0, &local_err);
4175 if (local_err) {
4176 warn_reportf_err(local_err,
4177 "Failed to truncate the tail of the image: ");
4180 } else {
4181 ret = qcow2_grow_l1_table(bs, new_l1_size, true);
4182 if (ret < 0) {
4183 error_setg_errno(errp, -ret, "Failed to grow the L1 table");
4184 goto fail;
4188 switch (prealloc) {
4189 case PREALLOC_MODE_OFF:
4190 if (has_data_file(bs)) {
4192 * If the caller wants an exact resize, the external data
4193 * file should be resized to the exact target size, too,
4194 * so we pass @exact here.
4196 ret = bdrv_co_truncate(s->data_file, offset, exact, prealloc, 0,
4197 errp);
4198 if (ret < 0) {
4199 goto fail;
4202 break;
4204 case PREALLOC_MODE_METADATA:
4205 ret = preallocate_co(bs, old_length, offset, prealloc, errp);
4206 if (ret < 0) {
4207 goto fail;
4209 break;
4211 case PREALLOC_MODE_FALLOC:
4212 case PREALLOC_MODE_FULL:
4214 int64_t allocation_start, host_offset, guest_offset;
4215 int64_t clusters_allocated;
4216 int64_t old_file_size, last_cluster, new_file_size;
4217 uint64_t nb_new_data_clusters, nb_new_l2_tables;
4219 /* With a data file, preallocation means just allocating the metadata
4220 * and forwarding the truncate request to the data file */
4221 if (has_data_file(bs)) {
4222 ret = preallocate_co(bs, old_length, offset, prealloc, errp);
4223 if (ret < 0) {
4224 goto fail;
4226 break;
4229 old_file_size = bdrv_getlength(bs->file->bs);
4230 if (old_file_size < 0) {
4231 error_setg_errno(errp, -old_file_size,
4232 "Failed to inquire current file length");
4233 ret = old_file_size;
4234 goto fail;
4237 last_cluster = qcow2_get_last_cluster(bs, old_file_size);
4238 if (last_cluster >= 0) {
4239 old_file_size = (last_cluster + 1) * s->cluster_size;
4240 } else {
4241 old_file_size = ROUND_UP(old_file_size, s->cluster_size);
4244 nb_new_data_clusters = (ROUND_UP(offset, s->cluster_size) -
4245 start_of_cluster(s, old_length)) >> s->cluster_bits;
4247 /* This is an overestimation; we will not actually allocate space for
4248 * these in the file but just make sure the new refcount structures are
4249 * able to cover them so we will not have to allocate new refblocks
4250 * while entering the data blocks in the potentially new L2 tables.
4251 * (We do not actually care where the L2 tables are placed. Maybe they
4252 * are already allocated or they can be placed somewhere before
4253 * @old_file_size. It does not matter because they will be fully
4254 * allocated automatically, so they do not need to be covered by the
4255 * preallocation. All that matters is that we will not have to allocate
4256 * new refcount structures for them.) */
4257 nb_new_l2_tables = DIV_ROUND_UP(nb_new_data_clusters,
4258 s->cluster_size / sizeof(uint64_t));
4259 /* The cluster range may not be aligned to L2 boundaries, so add one L2
4260 * table for a potential head/tail */
4261 nb_new_l2_tables++;
4263 allocation_start = qcow2_refcount_area(bs, old_file_size,
4264 nb_new_data_clusters +
4265 nb_new_l2_tables,
4266 true, 0, 0);
4267 if (allocation_start < 0) {
4268 error_setg_errno(errp, -allocation_start,
4269 "Failed to resize refcount structures");
4270 ret = allocation_start;
4271 goto fail;
4274 clusters_allocated = qcow2_alloc_clusters_at(bs, allocation_start,
4275 nb_new_data_clusters);
4276 if (clusters_allocated < 0) {
4277 error_setg_errno(errp, -clusters_allocated,
4278 "Failed to allocate data clusters");
4279 ret = clusters_allocated;
4280 goto fail;
4283 assert(clusters_allocated == nb_new_data_clusters);
4285 /* Allocate the data area */
4286 new_file_size = allocation_start +
4287 nb_new_data_clusters * s->cluster_size;
4289 * Image file grows, so @exact does not matter.
4291 * If we need to zero out the new area, try first whether the protocol
4292 * driver can already take care of this.
4294 if (flags & BDRV_REQ_ZERO_WRITE) {
4295 ret = bdrv_co_truncate(bs->file, new_file_size, false, prealloc,
4296 BDRV_REQ_ZERO_WRITE, NULL);
4297 if (ret >= 0) {
4298 flags &= ~BDRV_REQ_ZERO_WRITE;
4300 } else {
4301 ret = -1;
4303 if (ret < 0) {
4304 ret = bdrv_co_truncate(bs->file, new_file_size, false, prealloc, 0,
4305 errp);
4307 if (ret < 0) {
4308 error_prepend(errp, "Failed to resize underlying file: ");
4309 qcow2_free_clusters(bs, allocation_start,
4310 nb_new_data_clusters * s->cluster_size,
4311 QCOW2_DISCARD_OTHER);
4312 goto fail;
4315 /* Create the necessary L2 entries */
4316 host_offset = allocation_start;
4317 guest_offset = old_length;
4318 while (nb_new_data_clusters) {
4319 int64_t nb_clusters = MIN(
4320 nb_new_data_clusters,
4321 s->l2_slice_size - offset_to_l2_slice_index(s, guest_offset));
4322 unsigned cow_start_length = offset_into_cluster(s, guest_offset);
4323 QCowL2Meta allocation;
4324 guest_offset = start_of_cluster(s, guest_offset);
4325 allocation = (QCowL2Meta) {
4326 .offset = guest_offset,
4327 .alloc_offset = host_offset,
4328 .nb_clusters = nb_clusters,
4329 .cow_start = {
4330 .offset = 0,
4331 .nb_bytes = cow_start_length,
4333 .cow_end = {
4334 .offset = nb_clusters << s->cluster_bits,
4335 .nb_bytes = 0,
4338 qemu_co_queue_init(&allocation.dependent_requests);
4340 ret = qcow2_alloc_cluster_link_l2(bs, &allocation);
4341 if (ret < 0) {
4342 error_setg_errno(errp, -ret, "Failed to update L2 tables");
4343 qcow2_free_clusters(bs, host_offset,
4344 nb_new_data_clusters * s->cluster_size,
4345 QCOW2_DISCARD_OTHER);
4346 goto fail;
4349 guest_offset += nb_clusters * s->cluster_size;
4350 host_offset += nb_clusters * s->cluster_size;
4351 nb_new_data_clusters -= nb_clusters;
4353 break;
4356 default:
4357 g_assert_not_reached();
4360 if ((flags & BDRV_REQ_ZERO_WRITE) && offset > old_length) {
4361 uint64_t zero_start = QEMU_ALIGN_UP(old_length, s->cluster_size);
4364 * Use zero clusters as much as we can. qcow2_cluster_zeroize()
4365 * requires a cluster-aligned start. The end may be unaligned if it is
4366 * at the end of the image (which it is here).
4368 if (offset > zero_start) {
4369 ret = qcow2_cluster_zeroize(bs, zero_start, offset - zero_start, 0);
4370 if (ret < 0) {
4371 error_setg_errno(errp, -ret, "Failed to zero out new clusters");
4372 goto fail;
4376 /* Write explicit zeros for the unaligned head */
4377 if (zero_start > old_length) {
4378 uint64_t len = MIN(zero_start, offset) - old_length;
4379 uint8_t *buf = qemu_blockalign0(bs, len);
4380 QEMUIOVector qiov;
4381 qemu_iovec_init_buf(&qiov, buf, len);
4383 qemu_co_mutex_unlock(&s->lock);
4384 ret = qcow2_co_pwritev_part(bs, old_length, len, &qiov, 0, 0);
4385 qemu_co_mutex_lock(&s->lock);
4387 qemu_vfree(buf);
4388 if (ret < 0) {
4389 error_setg_errno(errp, -ret, "Failed to zero out the new area");
4390 goto fail;
4395 if (prealloc != PREALLOC_MODE_OFF) {
4396 /* Flush metadata before actually changing the image size */
4397 ret = qcow2_write_caches(bs);
4398 if (ret < 0) {
4399 error_setg_errno(errp, -ret,
4400 "Failed to flush the preallocated area to disk");
4401 goto fail;
4405 bs->total_sectors = offset / BDRV_SECTOR_SIZE;
4407 /* write updated header.size */
4408 offset = cpu_to_be64(offset);
4409 ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, size),
4410 &offset, sizeof(uint64_t));
4411 if (ret < 0) {
4412 error_setg_errno(errp, -ret, "Failed to update the image size");
4413 goto fail;
4416 s->l1_vm_state_index = new_l1_size;
4418 /* Update cache sizes */
4419 options = qdict_clone_shallow(bs->options);
4420 ret = qcow2_update_options(bs, options, s->flags, errp);
4421 qobject_unref(options);
4422 if (ret < 0) {
4423 goto fail;
4425 ret = 0;
4426 fail:
4427 qemu_co_mutex_unlock(&s->lock);
4428 return ret;
4431 static coroutine_fn int
4432 qcow2_co_pwritev_compressed_task(BlockDriverState *bs,
4433 uint64_t offset, uint64_t bytes,
4434 QEMUIOVector *qiov, size_t qiov_offset)
4436 BDRVQcow2State *s = bs->opaque;
4437 int ret;
4438 ssize_t out_len;
4439 uint8_t *buf, *out_buf;
4440 uint64_t cluster_offset;
4442 assert(bytes == s->cluster_size || (bytes < s->cluster_size &&
4443 (offset + bytes == bs->total_sectors << BDRV_SECTOR_BITS)));
4445 buf = qemu_blockalign(bs, s->cluster_size);
4446 if (bytes < s->cluster_size) {
4447 /* Zero-pad last write if image size is not cluster aligned */
4448 memset(buf + bytes, 0, s->cluster_size - bytes);
4450 qemu_iovec_to_buf(qiov, qiov_offset, buf, bytes);
4452 out_buf = g_malloc(s->cluster_size);
4454 out_len = qcow2_co_compress(bs, out_buf, s->cluster_size - 1,
4455 buf, s->cluster_size);
4456 if (out_len == -ENOMEM) {
4457 /* could not compress: write normal cluster */
4458 ret = qcow2_co_pwritev_part(bs, offset, bytes, qiov, qiov_offset, 0);
4459 if (ret < 0) {
4460 goto fail;
4462 goto success;
4463 } else if (out_len < 0) {
4464 ret = -EINVAL;
4465 goto fail;
4468 qemu_co_mutex_lock(&s->lock);
4469 ret = qcow2_alloc_compressed_cluster_offset(bs, offset, out_len,
4470 &cluster_offset);
4471 if (ret < 0) {
4472 qemu_co_mutex_unlock(&s->lock);
4473 goto fail;
4476 ret = qcow2_pre_write_overlap_check(bs, 0, cluster_offset, out_len, true);
4477 qemu_co_mutex_unlock(&s->lock);
4478 if (ret < 0) {
4479 goto fail;
4482 BLKDBG_EVENT(s->data_file, BLKDBG_WRITE_COMPRESSED);
4483 ret = bdrv_co_pwrite(s->data_file, cluster_offset, out_len, out_buf, 0);
4484 if (ret < 0) {
4485 goto fail;
4487 success:
4488 ret = 0;
4489 fail:
4490 qemu_vfree(buf);
4491 g_free(out_buf);
4492 return ret;
4495 static coroutine_fn int qcow2_co_pwritev_compressed_task_entry(AioTask *task)
4497 Qcow2AioTask *t = container_of(task, Qcow2AioTask, task);
4499 assert(!t->cluster_type && !t->l2meta);
4501 return qcow2_co_pwritev_compressed_task(t->bs, t->offset, t->bytes, t->qiov,
4502 t->qiov_offset);
4506 * XXX: put compressed sectors first, then all the cluster aligned
4507 * tables to avoid losing bytes in alignment
4509 static coroutine_fn int
4510 qcow2_co_pwritev_compressed_part(BlockDriverState *bs,
4511 uint64_t offset, uint64_t bytes,
4512 QEMUIOVector *qiov, size_t qiov_offset)
4514 BDRVQcow2State *s = bs->opaque;
4515 AioTaskPool *aio = NULL;
4516 int ret = 0;
4518 if (has_data_file(bs)) {
4519 return -ENOTSUP;
4522 if (bytes == 0) {
4524 * align end of file to a sector boundary to ease reading with
4525 * sector based I/Os
4527 int64_t len = bdrv_getlength(bs->file->bs);
4528 if (len < 0) {
4529 return len;
4531 return bdrv_co_truncate(bs->file, len, false, PREALLOC_MODE_OFF, 0,
4532 NULL);
4535 if (offset_into_cluster(s, offset)) {
4536 return -EINVAL;
4539 if (offset_into_cluster(s, bytes) &&
4540 (offset + bytes) != (bs->total_sectors << BDRV_SECTOR_BITS)) {
4541 return -EINVAL;
4544 while (bytes && aio_task_pool_status(aio) == 0) {
4545 uint64_t chunk_size = MIN(bytes, s->cluster_size);
4547 if (!aio && chunk_size != bytes) {
4548 aio = aio_task_pool_new(QCOW2_MAX_WORKERS);
4551 ret = qcow2_add_task(bs, aio, qcow2_co_pwritev_compressed_task_entry,
4552 0, 0, offset, chunk_size, qiov, qiov_offset, NULL);
4553 if (ret < 0) {
4554 break;
4556 qiov_offset += chunk_size;
4557 offset += chunk_size;
4558 bytes -= chunk_size;
4561 if (aio) {
4562 aio_task_pool_wait_all(aio);
4563 if (ret == 0) {
4564 ret = aio_task_pool_status(aio);
4566 g_free(aio);
4569 return ret;
4572 static int coroutine_fn
4573 qcow2_co_preadv_compressed(BlockDriverState *bs,
4574 uint64_t file_cluster_offset,
4575 uint64_t offset,
4576 uint64_t bytes,
4577 QEMUIOVector *qiov,
4578 size_t qiov_offset)
4580 BDRVQcow2State *s = bs->opaque;
4581 int ret = 0, csize, nb_csectors;
4582 uint64_t coffset;
4583 uint8_t *buf, *out_buf;
4584 int offset_in_cluster = offset_into_cluster(s, offset);
4586 coffset = file_cluster_offset & s->cluster_offset_mask;
4587 nb_csectors = ((file_cluster_offset >> s->csize_shift) & s->csize_mask) + 1;
4588 csize = nb_csectors * QCOW2_COMPRESSED_SECTOR_SIZE -
4589 (coffset & ~QCOW2_COMPRESSED_SECTOR_MASK);
4591 buf = g_try_malloc(csize);
4592 if (!buf) {
4593 return -ENOMEM;
4596 out_buf = qemu_blockalign(bs, s->cluster_size);
4598 BLKDBG_EVENT(bs->file, BLKDBG_READ_COMPRESSED);
4599 ret = bdrv_co_pread(bs->file, coffset, csize, buf, 0);
4600 if (ret < 0) {
4601 goto fail;
4604 if (qcow2_co_decompress(bs, out_buf, s->cluster_size, buf, csize) < 0) {
4605 ret = -EIO;
4606 goto fail;
4609 qemu_iovec_from_buf(qiov, qiov_offset, out_buf + offset_in_cluster, bytes);
4611 fail:
4612 qemu_vfree(out_buf);
4613 g_free(buf);
4615 return ret;
4618 static int make_completely_empty(BlockDriverState *bs)
4620 BDRVQcow2State *s = bs->opaque;
4621 Error *local_err = NULL;
4622 int ret, l1_clusters;
4623 int64_t offset;
4624 uint64_t *new_reftable = NULL;
4625 uint64_t rt_entry, l1_size2;
4626 struct {
4627 uint64_t l1_offset;
4628 uint64_t reftable_offset;
4629 uint32_t reftable_clusters;
4630 } QEMU_PACKED l1_ofs_rt_ofs_cls;
4632 ret = qcow2_cache_empty(bs, s->l2_table_cache);
4633 if (ret < 0) {
4634 goto fail;
4637 ret = qcow2_cache_empty(bs, s->refcount_block_cache);
4638 if (ret < 0) {
4639 goto fail;
4642 /* Refcounts will be broken utterly */
4643 ret = qcow2_mark_dirty(bs);
4644 if (ret < 0) {
4645 goto fail;
4648 BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
4650 l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / sizeof(uint64_t));
4651 l1_size2 = (uint64_t)s->l1_size * sizeof(uint64_t);
4653 /* After this call, neither the in-memory nor the on-disk refcount
4654 * information accurately describe the actual references */
4656 ret = bdrv_pwrite_zeroes(bs->file, s->l1_table_offset,
4657 l1_clusters * s->cluster_size, 0);
4658 if (ret < 0) {
4659 goto fail_broken_refcounts;
4661 memset(s->l1_table, 0, l1_size2);
4663 BLKDBG_EVENT(bs->file, BLKDBG_EMPTY_IMAGE_PREPARE);
4665 /* Overwrite enough clusters at the beginning of the sectors to place
4666 * the refcount table, a refcount block and the L1 table in; this may
4667 * overwrite parts of the existing refcount and L1 table, which is not
4668 * an issue because the dirty flag is set, complete data loss is in fact
4669 * desired and partial data loss is consequently fine as well */
4670 ret = bdrv_pwrite_zeroes(bs->file, s->cluster_size,
4671 (2 + l1_clusters) * s->cluster_size, 0);
4672 /* This call (even if it failed overall) may have overwritten on-disk
4673 * refcount structures; in that case, the in-memory refcount information
4674 * will probably differ from the on-disk information which makes the BDS
4675 * unusable */
4676 if (ret < 0) {
4677 goto fail_broken_refcounts;
4680 BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
4681 BLKDBG_EVENT(bs->file, BLKDBG_REFTABLE_UPDATE);
4683 /* "Create" an empty reftable (one cluster) directly after the image
4684 * header and an empty L1 table three clusters after the image header;
4685 * the cluster between those two will be used as the first refblock */
4686 l1_ofs_rt_ofs_cls.l1_offset = cpu_to_be64(3 * s->cluster_size);
4687 l1_ofs_rt_ofs_cls.reftable_offset = cpu_to_be64(s->cluster_size);
4688 l1_ofs_rt_ofs_cls.reftable_clusters = cpu_to_be32(1);
4689 ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, l1_table_offset),
4690 &l1_ofs_rt_ofs_cls, sizeof(l1_ofs_rt_ofs_cls));
4691 if (ret < 0) {
4692 goto fail_broken_refcounts;
4695 s->l1_table_offset = 3 * s->cluster_size;
4697 new_reftable = g_try_new0(uint64_t, s->cluster_size / sizeof(uint64_t));
4698 if (!new_reftable) {
4699 ret = -ENOMEM;
4700 goto fail_broken_refcounts;
4703 s->refcount_table_offset = s->cluster_size;
4704 s->refcount_table_size = s->cluster_size / sizeof(uint64_t);
4705 s->max_refcount_table_index = 0;
4707 g_free(s->refcount_table);
4708 s->refcount_table = new_reftable;
4709 new_reftable = NULL;
4711 /* Now the in-memory refcount information again corresponds to the on-disk
4712 * information (reftable is empty and no refblocks (the refblock cache is
4713 * empty)); however, this means some clusters (e.g. the image header) are
4714 * referenced, but not refcounted, but the normal qcow2 code assumes that
4715 * the in-memory information is always correct */
4717 BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_ALLOC);
4719 /* Enter the first refblock into the reftable */
4720 rt_entry = cpu_to_be64(2 * s->cluster_size);
4721 ret = bdrv_pwrite_sync(bs->file, s->cluster_size,
4722 &rt_entry, sizeof(rt_entry));
4723 if (ret < 0) {
4724 goto fail_broken_refcounts;
4726 s->refcount_table[0] = 2 * s->cluster_size;
4728 s->free_cluster_index = 0;
4729 assert(3 + l1_clusters <= s->refcount_block_size);
4730 offset = qcow2_alloc_clusters(bs, 3 * s->cluster_size + l1_size2);
4731 if (offset < 0) {
4732 ret = offset;
4733 goto fail_broken_refcounts;
4734 } else if (offset > 0) {
4735 error_report("First cluster in emptied image is in use");
4736 abort();
4739 /* Now finally the in-memory information corresponds to the on-disk
4740 * structures and is correct */
4741 ret = qcow2_mark_clean(bs);
4742 if (ret < 0) {
4743 goto fail;
4746 ret = bdrv_truncate(bs->file, (3 + l1_clusters) * s->cluster_size, false,
4747 PREALLOC_MODE_OFF, 0, &local_err);
4748 if (ret < 0) {
4749 error_report_err(local_err);
4750 goto fail;
4753 return 0;
4755 fail_broken_refcounts:
4756 /* The BDS is unusable at this point. If we wanted to make it usable, we
4757 * would have to call qcow2_refcount_close(), qcow2_refcount_init(),
4758 * qcow2_check_refcounts(), qcow2_refcount_close() and qcow2_refcount_init()
4759 * again. However, because the functions which could have caused this error
4760 * path to be taken are used by those functions as well, it's very likely
4761 * that that sequence will fail as well. Therefore, just eject the BDS. */
4762 bs->drv = NULL;
4764 fail:
4765 g_free(new_reftable);
4766 return ret;
4769 static int qcow2_make_empty(BlockDriverState *bs)
4771 BDRVQcow2State *s = bs->opaque;
4772 uint64_t offset, end_offset;
4773 int step = QEMU_ALIGN_DOWN(INT_MAX, s->cluster_size);
4774 int l1_clusters, ret = 0;
4776 l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / sizeof(uint64_t));
4778 if (s->qcow_version >= 3 && !s->snapshots && !s->nb_bitmaps &&
4779 3 + l1_clusters <= s->refcount_block_size &&
4780 s->crypt_method_header != QCOW_CRYPT_LUKS &&
4781 !has_data_file(bs)) {
4782 /* The following function only works for qcow2 v3 images (it
4783 * requires the dirty flag) and only as long as there are no
4784 * features that reserve extra clusters (such as snapshots,
4785 * LUKS header, or persistent bitmaps), because it completely
4786 * empties the image. Furthermore, the L1 table and three
4787 * additional clusters (image header, refcount table, one
4788 * refcount block) have to fit inside one refcount block. It
4789 * only resets the image file, i.e. does not work with an
4790 * external data file. */
4791 return make_completely_empty(bs);
4794 /* This fallback code simply discards every active cluster; this is slow,
4795 * but works in all cases */
4796 end_offset = bs->total_sectors * BDRV_SECTOR_SIZE;
4797 for (offset = 0; offset < end_offset; offset += step) {
4798 /* As this function is generally used after committing an external
4799 * snapshot, QCOW2_DISCARD_SNAPSHOT seems appropriate. Also, the
4800 * default action for this kind of discard is to pass the discard,
4801 * which will ideally result in an actually smaller image file, as
4802 * is probably desired. */
4803 ret = qcow2_cluster_discard(bs, offset, MIN(step, end_offset - offset),
4804 QCOW2_DISCARD_SNAPSHOT, true);
4805 if (ret < 0) {
4806 break;
4810 return ret;
4813 static coroutine_fn int qcow2_co_flush_to_os(BlockDriverState *bs)
4815 BDRVQcow2State *s = bs->opaque;
4816 int ret;
4818 qemu_co_mutex_lock(&s->lock);
4819 ret = qcow2_write_caches(bs);
4820 qemu_co_mutex_unlock(&s->lock);
4822 return ret;
4825 static BlockMeasureInfo *qcow2_measure(QemuOpts *opts, BlockDriverState *in_bs,
4826 Error **errp)
4828 Error *local_err = NULL;
4829 BlockMeasureInfo *info;
4830 uint64_t required = 0; /* bytes that contribute to required size */
4831 uint64_t virtual_size; /* disk size as seen by guest */
4832 uint64_t refcount_bits;
4833 uint64_t l2_tables;
4834 uint64_t luks_payload_size = 0;
4835 size_t cluster_size;
4836 int version;
4837 char *optstr;
4838 PreallocMode prealloc;
4839 bool has_backing_file;
4840 bool has_luks;
4842 /* Parse image creation options */
4843 cluster_size = qcow2_opt_get_cluster_size_del(opts, &local_err);
4844 if (local_err) {
4845 goto err;
4848 version = qcow2_opt_get_version_del(opts, &local_err);
4849 if (local_err) {
4850 goto err;
4853 refcount_bits = qcow2_opt_get_refcount_bits_del(opts, version, &local_err);
4854 if (local_err) {
4855 goto err;
4858 optstr = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
4859 prealloc = qapi_enum_parse(&PreallocMode_lookup, optstr,
4860 PREALLOC_MODE_OFF, &local_err);
4861 g_free(optstr);
4862 if (local_err) {
4863 goto err;
4866 optstr = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
4867 has_backing_file = !!optstr;
4868 g_free(optstr);
4870 optstr = qemu_opt_get_del(opts, BLOCK_OPT_ENCRYPT_FORMAT);
4871 has_luks = optstr && strcmp(optstr, "luks") == 0;
4872 g_free(optstr);
4874 if (has_luks) {
4875 g_autoptr(QCryptoBlockCreateOptions) create_opts = NULL;
4876 QDict *cryptoopts = qcow2_extract_crypto_opts(opts, "luks", errp);
4877 size_t headerlen;
4879 create_opts = block_crypto_create_opts_init(cryptoopts, errp);
4880 qobject_unref(cryptoopts);
4881 if (!create_opts) {
4882 goto err;
4885 if (!qcrypto_block_calculate_payload_offset(create_opts,
4886 "encrypt.",
4887 &headerlen,
4888 &local_err)) {
4889 goto err;
4892 luks_payload_size = ROUND_UP(headerlen, cluster_size);
4895 virtual_size = qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0);
4896 virtual_size = ROUND_UP(virtual_size, cluster_size);
4898 /* Check that virtual disk size is valid */
4899 l2_tables = DIV_ROUND_UP(virtual_size / cluster_size,
4900 cluster_size / sizeof(uint64_t));
4901 if (l2_tables * sizeof(uint64_t) > QCOW_MAX_L1_SIZE) {
4902 error_setg(&local_err, "The image size is too large "
4903 "(try using a larger cluster size)");
4904 goto err;
4907 /* Account for input image */
4908 if (in_bs) {
4909 int64_t ssize = bdrv_getlength(in_bs);
4910 if (ssize < 0) {
4911 error_setg_errno(&local_err, -ssize,
4912 "Unable to get image virtual_size");
4913 goto err;
4916 virtual_size = ROUND_UP(ssize, cluster_size);
4918 if (has_backing_file) {
4919 /* We don't how much of the backing chain is shared by the input
4920 * image and the new image file. In the worst case the new image's
4921 * backing file has nothing in common with the input image. Be
4922 * conservative and assume all clusters need to be written.
4924 required = virtual_size;
4925 } else {
4926 int64_t offset;
4927 int64_t pnum = 0;
4929 for (offset = 0; offset < ssize; offset += pnum) {
4930 int ret;
4932 ret = bdrv_block_status_above(in_bs, NULL, offset,
4933 ssize - offset, &pnum, NULL,
4934 NULL);
4935 if (ret < 0) {
4936 error_setg_errno(&local_err, -ret,
4937 "Unable to get block status");
4938 goto err;
4941 if (ret & BDRV_BLOCK_ZERO) {
4942 /* Skip zero regions (safe with no backing file) */
4943 } else if ((ret & (BDRV_BLOCK_DATA | BDRV_BLOCK_ALLOCATED)) ==
4944 (BDRV_BLOCK_DATA | BDRV_BLOCK_ALLOCATED)) {
4945 /* Extend pnum to end of cluster for next iteration */
4946 pnum = ROUND_UP(offset + pnum, cluster_size) - offset;
4948 /* Count clusters we've seen */
4949 required += offset % cluster_size + pnum;
4955 /* Take into account preallocation. Nothing special is needed for
4956 * PREALLOC_MODE_METADATA since metadata is always counted.
4958 if (prealloc == PREALLOC_MODE_FULL || prealloc == PREALLOC_MODE_FALLOC) {
4959 required = virtual_size;
4962 info = g_new0(BlockMeasureInfo, 1);
4963 info->fully_allocated =
4964 qcow2_calc_prealloc_size(virtual_size, cluster_size,
4965 ctz32(refcount_bits)) + luks_payload_size;
4968 * Remove data clusters that are not required. This overestimates the
4969 * required size because metadata needed for the fully allocated file is
4970 * still counted. Show bitmaps only if both source and destination
4971 * would support them.
4973 info->required = info->fully_allocated - virtual_size + required;
4974 info->has_bitmaps = version >= 3 && in_bs &&
4975 bdrv_supports_persistent_dirty_bitmap(in_bs);
4976 if (info->has_bitmaps) {
4977 info->bitmaps = qcow2_get_persistent_dirty_bitmap_size(in_bs,
4978 cluster_size);
4980 return info;
4982 err:
4983 error_propagate(errp, local_err);
4984 return NULL;
4987 static int qcow2_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
4989 BDRVQcow2State *s = bs->opaque;
4990 bdi->unallocated_blocks_are_zero = true;
4991 bdi->cluster_size = s->cluster_size;
4992 bdi->vm_state_offset = qcow2_vm_state_offset(s);
4993 return 0;
4996 static ImageInfoSpecific *qcow2_get_specific_info(BlockDriverState *bs,
4997 Error **errp)
4999 BDRVQcow2State *s = bs->opaque;
5000 ImageInfoSpecific *spec_info;
5001 QCryptoBlockInfo *encrypt_info = NULL;
5002 Error *local_err = NULL;
5004 if (s->crypto != NULL) {
5005 encrypt_info = qcrypto_block_get_info(s->crypto, &local_err);
5006 if (local_err) {
5007 error_propagate(errp, local_err);
5008 return NULL;
5012 spec_info = g_new(ImageInfoSpecific, 1);
5013 *spec_info = (ImageInfoSpecific){
5014 .type = IMAGE_INFO_SPECIFIC_KIND_QCOW2,
5015 .u.qcow2.data = g_new0(ImageInfoSpecificQCow2, 1),
5017 if (s->qcow_version == 2) {
5018 *spec_info->u.qcow2.data = (ImageInfoSpecificQCow2){
5019 .compat = g_strdup("0.10"),
5020 .refcount_bits = s->refcount_bits,
5022 } else if (s->qcow_version == 3) {
5023 Qcow2BitmapInfoList *bitmaps;
5024 bitmaps = qcow2_get_bitmap_info_list(bs, &local_err);
5025 if (local_err) {
5026 error_propagate(errp, local_err);
5027 qapi_free_ImageInfoSpecific(spec_info);
5028 qapi_free_QCryptoBlockInfo(encrypt_info);
5029 return NULL;
5031 *spec_info->u.qcow2.data = (ImageInfoSpecificQCow2){
5032 .compat = g_strdup("1.1"),
5033 .lazy_refcounts = s->compatible_features &
5034 QCOW2_COMPAT_LAZY_REFCOUNTS,
5035 .has_lazy_refcounts = true,
5036 .corrupt = s->incompatible_features &
5037 QCOW2_INCOMPAT_CORRUPT,
5038 .has_corrupt = true,
5039 .refcount_bits = s->refcount_bits,
5040 .has_bitmaps = !!bitmaps,
5041 .bitmaps = bitmaps,
5042 .has_data_file = !!s->image_data_file,
5043 .data_file = g_strdup(s->image_data_file),
5044 .has_data_file_raw = has_data_file(bs),
5045 .data_file_raw = data_file_is_raw(bs),
5046 .compression_type = s->compression_type,
5048 } else {
5049 /* if this assertion fails, this probably means a new version was
5050 * added without having it covered here */
5051 assert(false);
5054 if (encrypt_info) {
5055 ImageInfoSpecificQCow2Encryption *qencrypt =
5056 g_new(ImageInfoSpecificQCow2Encryption, 1);
5057 switch (encrypt_info->format) {
5058 case Q_CRYPTO_BLOCK_FORMAT_QCOW:
5059 qencrypt->format = BLOCKDEV_QCOW2_ENCRYPTION_FORMAT_AES;
5060 break;
5061 case Q_CRYPTO_BLOCK_FORMAT_LUKS:
5062 qencrypt->format = BLOCKDEV_QCOW2_ENCRYPTION_FORMAT_LUKS;
5063 qencrypt->u.luks = encrypt_info->u.luks;
5064 break;
5065 default:
5066 abort();
5068 /* Since we did shallow copy above, erase any pointers
5069 * in the original info */
5070 memset(&encrypt_info->u, 0, sizeof(encrypt_info->u));
5071 qapi_free_QCryptoBlockInfo(encrypt_info);
5073 spec_info->u.qcow2.data->has_encrypt = true;
5074 spec_info->u.qcow2.data->encrypt = qencrypt;
5077 return spec_info;
5080 static int qcow2_has_zero_init(BlockDriverState *bs)
5082 BDRVQcow2State *s = bs->opaque;
5083 bool preallocated;
5085 if (qemu_in_coroutine()) {
5086 qemu_co_mutex_lock(&s->lock);
5089 * Check preallocation status: Preallocated images have all L2
5090 * tables allocated, nonpreallocated images have none. It is
5091 * therefore enough to check the first one.
5093 preallocated = s->l1_size > 0 && s->l1_table[0] != 0;
5094 if (qemu_in_coroutine()) {
5095 qemu_co_mutex_unlock(&s->lock);
5098 if (!preallocated) {
5099 return 1;
5100 } else if (bs->encrypted) {
5101 return 0;
5102 } else {
5103 return bdrv_has_zero_init(s->data_file->bs);
5107 static int qcow2_save_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
5108 int64_t pos)
5110 BDRVQcow2State *s = bs->opaque;
5112 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_SAVE);
5113 return bs->drv->bdrv_co_pwritev_part(bs, qcow2_vm_state_offset(s) + pos,
5114 qiov->size, qiov, 0, 0);
5117 static int qcow2_load_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
5118 int64_t pos)
5120 BDRVQcow2State *s = bs->opaque;
5122 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_LOAD);
5123 return bs->drv->bdrv_co_preadv_part(bs, qcow2_vm_state_offset(s) + pos,
5124 qiov->size, qiov, 0, 0);
5128 * Downgrades an image's version. To achieve this, any incompatible features
5129 * have to be removed.
5131 static int qcow2_downgrade(BlockDriverState *bs, int target_version,
5132 BlockDriverAmendStatusCB *status_cb, void *cb_opaque,
5133 Error **errp)
5135 BDRVQcow2State *s = bs->opaque;
5136 int current_version = s->qcow_version;
5137 int ret;
5138 int i;
5140 /* This is qcow2_downgrade(), not qcow2_upgrade() */
5141 assert(target_version < current_version);
5143 /* There are no other versions (now) that you can downgrade to */
5144 assert(target_version == 2);
5146 if (s->refcount_order != 4) {
5147 error_setg(errp, "compat=0.10 requires refcount_bits=16");
5148 return -ENOTSUP;
5151 if (has_data_file(bs)) {
5152 error_setg(errp, "Cannot downgrade an image with a data file");
5153 return -ENOTSUP;
5157 * If any internal snapshot has a different size than the current
5158 * image size, or VM state size that exceeds 32 bits, downgrading
5159 * is unsafe. Even though we would still use v3-compliant output
5160 * to preserve that data, other v2 programs might not realize
5161 * those optional fields are important.
5163 for (i = 0; i < s->nb_snapshots; i++) {
5164 if (s->snapshots[i].vm_state_size > UINT32_MAX ||
5165 s->snapshots[i].disk_size != bs->total_sectors * BDRV_SECTOR_SIZE) {
5166 error_setg(errp, "Internal snapshots prevent downgrade of image");
5167 return -ENOTSUP;
5171 /* clear incompatible features */
5172 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
5173 ret = qcow2_mark_clean(bs);
5174 if (ret < 0) {
5175 error_setg_errno(errp, -ret, "Failed to make the image clean");
5176 return ret;
5180 /* with QCOW2_INCOMPAT_CORRUPT, it is pretty much impossible to get here in
5181 * the first place; if that happens nonetheless, returning -ENOTSUP is the
5182 * best thing to do anyway */
5184 if (s->incompatible_features) {
5185 error_setg(errp, "Cannot downgrade an image with incompatible features "
5186 "%#" PRIx64 " set", s->incompatible_features);
5187 return -ENOTSUP;
5190 /* since we can ignore compatible features, we can set them to 0 as well */
5191 s->compatible_features = 0;
5192 /* if lazy refcounts have been used, they have already been fixed through
5193 * clearing the dirty flag */
5195 /* clearing autoclear features is trivial */
5196 s->autoclear_features = 0;
5198 ret = qcow2_expand_zero_clusters(bs, status_cb, cb_opaque);
5199 if (ret < 0) {
5200 error_setg_errno(errp, -ret, "Failed to turn zero into data clusters");
5201 return ret;
5204 s->qcow_version = target_version;
5205 ret = qcow2_update_header(bs);
5206 if (ret < 0) {
5207 s->qcow_version = current_version;
5208 error_setg_errno(errp, -ret, "Failed to update the image header");
5209 return ret;
5211 return 0;
5215 * Upgrades an image's version. While newer versions encompass all
5216 * features of older versions, some things may have to be presented
5217 * differently.
5219 static int qcow2_upgrade(BlockDriverState *bs, int target_version,
5220 BlockDriverAmendStatusCB *status_cb, void *cb_opaque,
5221 Error **errp)
5223 BDRVQcow2State *s = bs->opaque;
5224 bool need_snapshot_update;
5225 int current_version = s->qcow_version;
5226 int i;
5227 int ret;
5229 /* This is qcow2_upgrade(), not qcow2_downgrade() */
5230 assert(target_version > current_version);
5232 /* There are no other versions (yet) that you can upgrade to */
5233 assert(target_version == 3);
5235 status_cb(bs, 0, 2, cb_opaque);
5238 * In v2, snapshots do not need to have extra data. v3 requires
5239 * the 64-bit VM state size and the virtual disk size to be
5240 * present.
5241 * qcow2_write_snapshots() will always write the list in the
5242 * v3-compliant format.
5244 need_snapshot_update = false;
5245 for (i = 0; i < s->nb_snapshots; i++) {
5246 if (s->snapshots[i].extra_data_size <
5247 sizeof_field(QCowSnapshotExtraData, vm_state_size_large) +
5248 sizeof_field(QCowSnapshotExtraData, disk_size))
5250 need_snapshot_update = true;
5251 break;
5254 if (need_snapshot_update) {
5255 ret = qcow2_write_snapshots(bs);
5256 if (ret < 0) {
5257 error_setg_errno(errp, -ret, "Failed to update the snapshot table");
5258 return ret;
5261 status_cb(bs, 1, 2, cb_opaque);
5263 s->qcow_version = target_version;
5264 ret = qcow2_update_header(bs);
5265 if (ret < 0) {
5266 s->qcow_version = current_version;
5267 error_setg_errno(errp, -ret, "Failed to update the image header");
5268 return ret;
5270 status_cb(bs, 2, 2, cb_opaque);
5272 return 0;
5275 typedef enum Qcow2AmendOperation {
5276 /* This is the value Qcow2AmendHelperCBInfo::last_operation will be
5277 * statically initialized to so that the helper CB can discern the first
5278 * invocation from an operation change */
5279 QCOW2_NO_OPERATION = 0,
5281 QCOW2_UPGRADING,
5282 QCOW2_UPDATING_ENCRYPTION,
5283 QCOW2_CHANGING_REFCOUNT_ORDER,
5284 QCOW2_DOWNGRADING,
5285 } Qcow2AmendOperation;
5287 typedef struct Qcow2AmendHelperCBInfo {
5288 /* The code coordinating the amend operations should only modify
5289 * these four fields; the rest will be managed by the CB */
5290 BlockDriverAmendStatusCB *original_status_cb;
5291 void *original_cb_opaque;
5293 Qcow2AmendOperation current_operation;
5295 /* Total number of operations to perform (only set once) */
5296 int total_operations;
5298 /* The following fields are managed by the CB */
5300 /* Number of operations completed */
5301 int operations_completed;
5303 /* Cumulative offset of all completed operations */
5304 int64_t offset_completed;
5306 Qcow2AmendOperation last_operation;
5307 int64_t last_work_size;
5308 } Qcow2AmendHelperCBInfo;
5310 static void qcow2_amend_helper_cb(BlockDriverState *bs,
5311 int64_t operation_offset,
5312 int64_t operation_work_size, void *opaque)
5314 Qcow2AmendHelperCBInfo *info = opaque;
5315 int64_t current_work_size;
5316 int64_t projected_work_size;
5318 if (info->current_operation != info->last_operation) {
5319 if (info->last_operation != QCOW2_NO_OPERATION) {
5320 info->offset_completed += info->last_work_size;
5321 info->operations_completed++;
5324 info->last_operation = info->current_operation;
5327 assert(info->total_operations > 0);
5328 assert(info->operations_completed < info->total_operations);
5330 info->last_work_size = operation_work_size;
5332 current_work_size = info->offset_completed + operation_work_size;
5334 /* current_work_size is the total work size for (operations_completed + 1)
5335 * operations (which includes this one), so multiply it by the number of
5336 * operations not covered and divide it by the number of operations
5337 * covered to get a projection for the operations not covered */
5338 projected_work_size = current_work_size * (info->total_operations -
5339 info->operations_completed - 1)
5340 / (info->operations_completed + 1);
5342 info->original_status_cb(bs, info->offset_completed + operation_offset,
5343 current_work_size + projected_work_size,
5344 info->original_cb_opaque);
5347 static int qcow2_amend_options(BlockDriverState *bs, QemuOpts *opts,
5348 BlockDriverAmendStatusCB *status_cb,
5349 void *cb_opaque,
5350 bool force,
5351 Error **errp)
5353 BDRVQcow2State *s = bs->opaque;
5354 int old_version = s->qcow_version, new_version = old_version;
5355 uint64_t new_size = 0;
5356 const char *backing_file = NULL, *backing_format = NULL, *data_file = NULL;
5357 bool lazy_refcounts = s->use_lazy_refcounts;
5358 bool data_file_raw = data_file_is_raw(bs);
5359 const char *compat = NULL;
5360 int refcount_bits = s->refcount_bits;
5361 int ret;
5362 QemuOptDesc *desc = opts->list->desc;
5363 Qcow2AmendHelperCBInfo helper_cb_info;
5364 bool encryption_update = false;
5366 while (desc && desc->name) {
5367 if (!qemu_opt_find(opts, desc->name)) {
5368 /* only change explicitly defined options */
5369 desc++;
5370 continue;
5373 if (!strcmp(desc->name, BLOCK_OPT_COMPAT_LEVEL)) {
5374 compat = qemu_opt_get(opts, BLOCK_OPT_COMPAT_LEVEL);
5375 if (!compat) {
5376 /* preserve default */
5377 } else if (!strcmp(compat, "0.10") || !strcmp(compat, "v2")) {
5378 new_version = 2;
5379 } else if (!strcmp(compat, "1.1") || !strcmp(compat, "v3")) {
5380 new_version = 3;
5381 } else {
5382 error_setg(errp, "Unknown compatibility level %s", compat);
5383 return -EINVAL;
5385 } else if (!strcmp(desc->name, BLOCK_OPT_SIZE)) {
5386 new_size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, 0);
5387 } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FILE)) {
5388 backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
5389 } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FMT)) {
5390 backing_format = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
5391 } else if (g_str_has_prefix(desc->name, "encrypt.")) {
5392 if (!s->crypto) {
5393 error_setg(errp,
5394 "Can't amend encryption options - encryption not present");
5395 return -EINVAL;
5397 if (s->crypt_method_header != QCOW_CRYPT_LUKS) {
5398 error_setg(errp,
5399 "Only LUKS encryption options can be amended");
5400 return -ENOTSUP;
5402 encryption_update = true;
5403 } else if (!strcmp(desc->name, BLOCK_OPT_LAZY_REFCOUNTS)) {
5404 lazy_refcounts = qemu_opt_get_bool(opts, BLOCK_OPT_LAZY_REFCOUNTS,
5405 lazy_refcounts);
5406 } else if (!strcmp(desc->name, BLOCK_OPT_REFCOUNT_BITS)) {
5407 refcount_bits = qemu_opt_get_number(opts, BLOCK_OPT_REFCOUNT_BITS,
5408 refcount_bits);
5410 if (refcount_bits <= 0 || refcount_bits > 64 ||
5411 !is_power_of_2(refcount_bits))
5413 error_setg(errp, "Refcount width must be a power of two and "
5414 "may not exceed 64 bits");
5415 return -EINVAL;
5417 } else if (!strcmp(desc->name, BLOCK_OPT_DATA_FILE)) {
5418 data_file = qemu_opt_get(opts, BLOCK_OPT_DATA_FILE);
5419 if (data_file && !has_data_file(bs)) {
5420 error_setg(errp, "data-file can only be set for images that "
5421 "use an external data file");
5422 return -EINVAL;
5424 } else if (!strcmp(desc->name, BLOCK_OPT_DATA_FILE_RAW)) {
5425 data_file_raw = qemu_opt_get_bool(opts, BLOCK_OPT_DATA_FILE_RAW,
5426 data_file_raw);
5427 if (data_file_raw && !data_file_is_raw(bs)) {
5428 error_setg(errp, "data-file-raw cannot be set on existing "
5429 "images");
5430 return -EINVAL;
5432 } else {
5433 /* if this point is reached, this probably means a new option was
5434 * added without having it covered here */
5435 abort();
5438 desc++;
5441 helper_cb_info = (Qcow2AmendHelperCBInfo){
5442 .original_status_cb = status_cb,
5443 .original_cb_opaque = cb_opaque,
5444 .total_operations = (new_version != old_version)
5445 + (s->refcount_bits != refcount_bits) +
5446 (encryption_update == true)
5449 /* Upgrade first (some features may require compat=1.1) */
5450 if (new_version > old_version) {
5451 helper_cb_info.current_operation = QCOW2_UPGRADING;
5452 ret = qcow2_upgrade(bs, new_version, &qcow2_amend_helper_cb,
5453 &helper_cb_info, errp);
5454 if (ret < 0) {
5455 return ret;
5459 if (encryption_update) {
5460 QDict *amend_opts_dict;
5461 QCryptoBlockAmendOptions *amend_opts;
5463 helper_cb_info.current_operation = QCOW2_UPDATING_ENCRYPTION;
5464 amend_opts_dict = qcow2_extract_crypto_opts(opts, "luks", errp);
5465 if (!amend_opts_dict) {
5466 return -EINVAL;
5468 amend_opts = block_crypto_amend_opts_init(amend_opts_dict, errp);
5469 qobject_unref(amend_opts_dict);
5470 if (!amend_opts) {
5471 return -EINVAL;
5473 ret = qcrypto_block_amend_options(s->crypto,
5474 qcow2_crypto_hdr_read_func,
5475 qcow2_crypto_hdr_write_func,
5477 amend_opts,
5478 force,
5479 errp);
5480 qapi_free_QCryptoBlockAmendOptions(amend_opts);
5481 if (ret < 0) {
5482 return ret;
5486 if (s->refcount_bits != refcount_bits) {
5487 int refcount_order = ctz32(refcount_bits);
5489 if (new_version < 3 && refcount_bits != 16) {
5490 error_setg(errp, "Refcount widths other than 16 bits require "
5491 "compatibility level 1.1 or above (use compat=1.1 or "
5492 "greater)");
5493 return -EINVAL;
5496 helper_cb_info.current_operation = QCOW2_CHANGING_REFCOUNT_ORDER;
5497 ret = qcow2_change_refcount_order(bs, refcount_order,
5498 &qcow2_amend_helper_cb,
5499 &helper_cb_info, errp);
5500 if (ret < 0) {
5501 return ret;
5505 /* data-file-raw blocks backing files, so clear it first if requested */
5506 if (data_file_raw) {
5507 s->autoclear_features |= QCOW2_AUTOCLEAR_DATA_FILE_RAW;
5508 } else {
5509 s->autoclear_features &= ~QCOW2_AUTOCLEAR_DATA_FILE_RAW;
5512 if (data_file) {
5513 g_free(s->image_data_file);
5514 s->image_data_file = *data_file ? g_strdup(data_file) : NULL;
5517 ret = qcow2_update_header(bs);
5518 if (ret < 0) {
5519 error_setg_errno(errp, -ret, "Failed to update the image header");
5520 return ret;
5523 if (backing_file || backing_format) {
5524 ret = qcow2_change_backing_file(bs,
5525 backing_file ?: s->image_backing_file,
5526 backing_format ?: s->image_backing_format);
5527 if (ret < 0) {
5528 error_setg_errno(errp, -ret, "Failed to change the backing file");
5529 return ret;
5533 if (s->use_lazy_refcounts != lazy_refcounts) {
5534 if (lazy_refcounts) {
5535 if (new_version < 3) {
5536 error_setg(errp, "Lazy refcounts only supported with "
5537 "compatibility level 1.1 and above (use compat=1.1 "
5538 "or greater)");
5539 return -EINVAL;
5541 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
5542 ret = qcow2_update_header(bs);
5543 if (ret < 0) {
5544 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
5545 error_setg_errno(errp, -ret, "Failed to update the image header");
5546 return ret;
5548 s->use_lazy_refcounts = true;
5549 } else {
5550 /* make image clean first */
5551 ret = qcow2_mark_clean(bs);
5552 if (ret < 0) {
5553 error_setg_errno(errp, -ret, "Failed to make the image clean");
5554 return ret;
5556 /* now disallow lazy refcounts */
5557 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
5558 ret = qcow2_update_header(bs);
5559 if (ret < 0) {
5560 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
5561 error_setg_errno(errp, -ret, "Failed to update the image header");
5562 return ret;
5564 s->use_lazy_refcounts = false;
5568 if (new_size) {
5569 BlockBackend *blk = blk_new_with_bs(bs, BLK_PERM_RESIZE, BLK_PERM_ALL,
5570 errp);
5571 if (!blk) {
5572 return -EPERM;
5576 * Amending image options should ensure that the image has
5577 * exactly the given new values, so pass exact=true here.
5579 ret = blk_truncate(blk, new_size, true, PREALLOC_MODE_OFF, 0, errp);
5580 blk_unref(blk);
5581 if (ret < 0) {
5582 return ret;
5586 /* Downgrade last (so unsupported features can be removed before) */
5587 if (new_version < old_version) {
5588 helper_cb_info.current_operation = QCOW2_DOWNGRADING;
5589 ret = qcow2_downgrade(bs, new_version, &qcow2_amend_helper_cb,
5590 &helper_cb_info, errp);
5591 if (ret < 0) {
5592 return ret;
5596 return 0;
5599 static int coroutine_fn qcow2_co_amend(BlockDriverState *bs,
5600 BlockdevAmendOptions *opts,
5601 bool force,
5602 Error **errp)
5604 BlockdevAmendOptionsQcow2 *qopts = &opts->u.qcow2;
5605 BDRVQcow2State *s = bs->opaque;
5606 int ret = 0;
5608 if (qopts->has_encrypt) {
5609 if (!s->crypto) {
5610 error_setg(errp, "image is not encrypted, can't amend");
5611 return -EOPNOTSUPP;
5614 if (qopts->encrypt->format != Q_CRYPTO_BLOCK_FORMAT_LUKS) {
5615 error_setg(errp,
5616 "Amend can't be used to change the qcow2 encryption format");
5617 return -EOPNOTSUPP;
5620 if (s->crypt_method_header != QCOW_CRYPT_LUKS) {
5621 error_setg(errp,
5622 "Only LUKS encryption options can be amended for qcow2 with blockdev-amend");
5623 return -EOPNOTSUPP;
5626 ret = qcrypto_block_amend_options(s->crypto,
5627 qcow2_crypto_hdr_read_func,
5628 qcow2_crypto_hdr_write_func,
5630 qopts->encrypt,
5631 force,
5632 errp);
5634 return ret;
5638 * If offset or size are negative, respectively, they will not be included in
5639 * the BLOCK_IMAGE_CORRUPTED event emitted.
5640 * fatal will be ignored for read-only BDS; corruptions found there will always
5641 * be considered non-fatal.
5643 void qcow2_signal_corruption(BlockDriverState *bs, bool fatal, int64_t offset,
5644 int64_t size, const char *message_format, ...)
5646 BDRVQcow2State *s = bs->opaque;
5647 const char *node_name;
5648 char *message;
5649 va_list ap;
5651 fatal = fatal && bdrv_is_writable(bs);
5653 if (s->signaled_corruption &&
5654 (!fatal || (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT)))
5656 return;
5659 va_start(ap, message_format);
5660 message = g_strdup_vprintf(message_format, ap);
5661 va_end(ap);
5663 if (fatal) {
5664 fprintf(stderr, "qcow2: Marking image as corrupt: %s; further "
5665 "corruption events will be suppressed\n", message);
5666 } else {
5667 fprintf(stderr, "qcow2: Image is corrupt: %s; further non-fatal "
5668 "corruption events will be suppressed\n", message);
5671 node_name = bdrv_get_node_name(bs);
5672 qapi_event_send_block_image_corrupted(bdrv_get_device_name(bs),
5673 *node_name != '\0', node_name,
5674 message, offset >= 0, offset,
5675 size >= 0, size,
5676 fatal);
5677 g_free(message);
5679 if (fatal) {
5680 qcow2_mark_corrupt(bs);
5681 bs->drv = NULL; /* make BDS unusable */
5684 s->signaled_corruption = true;
5687 #define QCOW_COMMON_OPTIONS \
5689 .name = BLOCK_OPT_SIZE, \
5690 .type = QEMU_OPT_SIZE, \
5691 .help = "Virtual disk size" \
5692 }, \
5694 .name = BLOCK_OPT_COMPAT_LEVEL, \
5695 .type = QEMU_OPT_STRING, \
5696 .help = "Compatibility level (v2 [0.10] or v3 [1.1])" \
5697 }, \
5699 .name = BLOCK_OPT_BACKING_FILE, \
5700 .type = QEMU_OPT_STRING, \
5701 .help = "File name of a base image" \
5702 }, \
5704 .name = BLOCK_OPT_BACKING_FMT, \
5705 .type = QEMU_OPT_STRING, \
5706 .help = "Image format of the base image" \
5707 }, \
5709 .name = BLOCK_OPT_DATA_FILE, \
5710 .type = QEMU_OPT_STRING, \
5711 .help = "File name of an external data file" \
5712 }, \
5714 .name = BLOCK_OPT_DATA_FILE_RAW, \
5715 .type = QEMU_OPT_BOOL, \
5716 .help = "The external data file must stay valid " \
5717 "as a raw image" \
5718 }, \
5720 .name = BLOCK_OPT_LAZY_REFCOUNTS, \
5721 .type = QEMU_OPT_BOOL, \
5722 .help = "Postpone refcount updates", \
5723 .def_value_str = "off" \
5724 }, \
5726 .name = BLOCK_OPT_REFCOUNT_BITS, \
5727 .type = QEMU_OPT_NUMBER, \
5728 .help = "Width of a reference count entry in bits", \
5729 .def_value_str = "16" \
5732 static QemuOptsList qcow2_create_opts = {
5733 .name = "qcow2-create-opts",
5734 .head = QTAILQ_HEAD_INITIALIZER(qcow2_create_opts.head),
5735 .desc = {
5737 .name = BLOCK_OPT_ENCRYPT, \
5738 .type = QEMU_OPT_BOOL, \
5739 .help = "Encrypt the image with format 'aes'. (Deprecated " \
5740 "in favor of " BLOCK_OPT_ENCRYPT_FORMAT "=aes)", \
5741 }, \
5743 .name = BLOCK_OPT_ENCRYPT_FORMAT, \
5744 .type = QEMU_OPT_STRING, \
5745 .help = "Encrypt the image, format choices: 'aes', 'luks'", \
5746 }, \
5747 BLOCK_CRYPTO_OPT_DEF_KEY_SECRET("encrypt.", \
5748 "ID of secret providing qcow AES key or LUKS passphrase"), \
5749 BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_ALG("encrypt."), \
5750 BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_MODE("encrypt."), \
5751 BLOCK_CRYPTO_OPT_DEF_LUKS_IVGEN_ALG("encrypt."), \
5752 BLOCK_CRYPTO_OPT_DEF_LUKS_IVGEN_HASH_ALG("encrypt."), \
5753 BLOCK_CRYPTO_OPT_DEF_LUKS_HASH_ALG("encrypt."), \
5754 BLOCK_CRYPTO_OPT_DEF_LUKS_ITER_TIME("encrypt."), \
5756 .name = BLOCK_OPT_CLUSTER_SIZE, \
5757 .type = QEMU_OPT_SIZE, \
5758 .help = "qcow2 cluster size", \
5759 .def_value_str = stringify(DEFAULT_CLUSTER_SIZE) \
5760 }, \
5762 .name = BLOCK_OPT_PREALLOC, \
5763 .type = QEMU_OPT_STRING, \
5764 .help = "Preallocation mode (allowed values: off, " \
5765 "metadata, falloc, full)" \
5766 }, \
5768 .name = BLOCK_OPT_COMPRESSION_TYPE, \
5769 .type = QEMU_OPT_STRING, \
5770 .help = "Compression method used for image cluster " \
5771 "compression", \
5772 .def_value_str = "zlib" \
5774 QCOW_COMMON_OPTIONS,
5775 { /* end of list */ }
5779 static QemuOptsList qcow2_amend_opts = {
5780 .name = "qcow2-amend-opts",
5781 .head = QTAILQ_HEAD_INITIALIZER(qcow2_amend_opts.head),
5782 .desc = {
5783 BLOCK_CRYPTO_OPT_DEF_LUKS_STATE("encrypt."),
5784 BLOCK_CRYPTO_OPT_DEF_LUKS_KEYSLOT("encrypt."),
5785 BLOCK_CRYPTO_OPT_DEF_LUKS_OLD_SECRET("encrypt."),
5786 BLOCK_CRYPTO_OPT_DEF_LUKS_NEW_SECRET("encrypt."),
5787 BLOCK_CRYPTO_OPT_DEF_LUKS_ITER_TIME("encrypt."),
5788 QCOW_COMMON_OPTIONS,
5789 { /* end of list */ }
5793 static const char *const qcow2_strong_runtime_opts[] = {
5794 "encrypt." BLOCK_CRYPTO_OPT_QCOW_KEY_SECRET,
5796 NULL
5799 BlockDriver bdrv_qcow2 = {
5800 .format_name = "qcow2",
5801 .instance_size = sizeof(BDRVQcow2State),
5802 .bdrv_probe = qcow2_probe,
5803 .bdrv_open = qcow2_open,
5804 .bdrv_close = qcow2_close,
5805 .bdrv_reopen_prepare = qcow2_reopen_prepare,
5806 .bdrv_reopen_commit = qcow2_reopen_commit,
5807 .bdrv_reopen_commit_post = qcow2_reopen_commit_post,
5808 .bdrv_reopen_abort = qcow2_reopen_abort,
5809 .bdrv_join_options = qcow2_join_options,
5810 .bdrv_child_perm = bdrv_default_perms,
5811 .bdrv_co_create_opts = qcow2_co_create_opts,
5812 .bdrv_co_create = qcow2_co_create,
5813 .bdrv_has_zero_init = qcow2_has_zero_init,
5814 .bdrv_co_block_status = qcow2_co_block_status,
5816 .bdrv_co_preadv_part = qcow2_co_preadv_part,
5817 .bdrv_co_pwritev_part = qcow2_co_pwritev_part,
5818 .bdrv_co_flush_to_os = qcow2_co_flush_to_os,
5820 .bdrv_co_pwrite_zeroes = qcow2_co_pwrite_zeroes,
5821 .bdrv_co_pdiscard = qcow2_co_pdiscard,
5822 .bdrv_co_copy_range_from = qcow2_co_copy_range_from,
5823 .bdrv_co_copy_range_to = qcow2_co_copy_range_to,
5824 .bdrv_co_truncate = qcow2_co_truncate,
5825 .bdrv_co_pwritev_compressed_part = qcow2_co_pwritev_compressed_part,
5826 .bdrv_make_empty = qcow2_make_empty,
5828 .bdrv_snapshot_create = qcow2_snapshot_create,
5829 .bdrv_snapshot_goto = qcow2_snapshot_goto,
5830 .bdrv_snapshot_delete = qcow2_snapshot_delete,
5831 .bdrv_snapshot_list = qcow2_snapshot_list,
5832 .bdrv_snapshot_load_tmp = qcow2_snapshot_load_tmp,
5833 .bdrv_measure = qcow2_measure,
5834 .bdrv_get_info = qcow2_get_info,
5835 .bdrv_get_specific_info = qcow2_get_specific_info,
5837 .bdrv_save_vmstate = qcow2_save_vmstate,
5838 .bdrv_load_vmstate = qcow2_load_vmstate,
5840 .is_format = true,
5841 .supports_backing = true,
5842 .bdrv_change_backing_file = qcow2_change_backing_file,
5844 .bdrv_refresh_limits = qcow2_refresh_limits,
5845 .bdrv_co_invalidate_cache = qcow2_co_invalidate_cache,
5846 .bdrv_inactivate = qcow2_inactivate,
5848 .create_opts = &qcow2_create_opts,
5849 .amend_opts = &qcow2_amend_opts,
5850 .strong_runtime_opts = qcow2_strong_runtime_opts,
5851 .mutable_opts = mutable_opts,
5852 .bdrv_co_check = qcow2_co_check,
5853 .bdrv_amend_options = qcow2_amend_options,
5854 .bdrv_co_amend = qcow2_co_amend,
5856 .bdrv_detach_aio_context = qcow2_detach_aio_context,
5857 .bdrv_attach_aio_context = qcow2_attach_aio_context,
5859 .bdrv_supports_persistent_dirty_bitmap =
5860 qcow2_supports_persistent_dirty_bitmap,
5861 .bdrv_co_can_store_new_dirty_bitmap = qcow2_co_can_store_new_dirty_bitmap,
5862 .bdrv_co_remove_persistent_dirty_bitmap =
5863 qcow2_co_remove_persistent_dirty_bitmap,
5866 static void bdrv_qcow2_init(void)
5868 bdrv_register(&bdrv_qcow2);
5871 block_init(bdrv_qcow2_init);