qcow2: Update expand_zero_clusters_in_l1() to support L2 slices
[qemu/kevin.git] / block / qcow2.c
blobba8d71c72d55c1449584960bbdbbe38feea98786
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"
26 #include "block/block_int.h"
27 #include "sysemu/block-backend.h"
28 #include "qemu/module.h"
29 #include <zlib.h>
30 #include "block/qcow2.h"
31 #include "qemu/error-report.h"
32 #include "qapi/error.h"
33 #include "qapi/qmp/qerror.h"
34 #include "qapi/qmp/qdict.h"
35 #include "qapi/qmp/qstring.h"
36 #include "qapi-event.h"
37 #include "trace.h"
38 #include "qemu/option_int.h"
39 #include "qemu/cutils.h"
40 #include "qemu/bswap.h"
41 #include "qapi/opts-visitor.h"
42 #include "qapi-visit.h"
43 #include "block/crypto.h"
46 Differences with QCOW:
48 - Support for multiple incremental snapshots.
49 - Memory management by reference counts.
50 - Clusters which have a reference count of one have the bit
51 QCOW_OFLAG_COPIED to optimize write performance.
52 - Size of compressed clusters is stored in sectors to reduce bit usage
53 in the cluster offsets.
54 - Support for storing additional data (such as the VM state) in the
55 snapshots.
56 - If a backing store is used, the cluster size is not constrained
57 (could be backported to QCOW).
58 - L2 tables have always a size of one cluster.
62 typedef struct {
63 uint32_t magic;
64 uint32_t len;
65 } QEMU_PACKED QCowExtension;
67 #define QCOW2_EXT_MAGIC_END 0
68 #define QCOW2_EXT_MAGIC_BACKING_FORMAT 0xE2792ACA
69 #define QCOW2_EXT_MAGIC_FEATURE_TABLE 0x6803f857
70 #define QCOW2_EXT_MAGIC_CRYPTO_HEADER 0x0537be77
71 #define QCOW2_EXT_MAGIC_BITMAPS 0x23852875
73 static int qcow2_probe(const uint8_t *buf, int buf_size, const char *filename)
75 const QCowHeader *cow_header = (const void *)buf;
77 if (buf_size >= sizeof(QCowHeader) &&
78 be32_to_cpu(cow_header->magic) == QCOW_MAGIC &&
79 be32_to_cpu(cow_header->version) >= 2)
80 return 100;
81 else
82 return 0;
86 static ssize_t qcow2_crypto_hdr_read_func(QCryptoBlock *block, size_t offset,
87 uint8_t *buf, size_t buflen,
88 void *opaque, Error **errp)
90 BlockDriverState *bs = opaque;
91 BDRVQcow2State *s = bs->opaque;
92 ssize_t ret;
94 if ((offset + buflen) > s->crypto_header.length) {
95 error_setg(errp, "Request for data outside of extension header");
96 return -1;
99 ret = bdrv_pread(bs->file,
100 s->crypto_header.offset + offset, buf, buflen);
101 if (ret < 0) {
102 error_setg_errno(errp, -ret, "Could not read encryption header");
103 return -1;
105 return ret;
109 static ssize_t qcow2_crypto_hdr_init_func(QCryptoBlock *block, size_t headerlen,
110 void *opaque, Error **errp)
112 BlockDriverState *bs = opaque;
113 BDRVQcow2State *s = bs->opaque;
114 int64_t ret;
115 int64_t clusterlen;
117 ret = qcow2_alloc_clusters(bs, headerlen);
118 if (ret < 0) {
119 error_setg_errno(errp, -ret,
120 "Cannot allocate cluster for LUKS header size %zu",
121 headerlen);
122 return -1;
125 s->crypto_header.length = headerlen;
126 s->crypto_header.offset = ret;
128 /* Zero fill remaining space in cluster so it has predictable
129 * content in case of future spec changes */
130 clusterlen = size_to_clusters(s, headerlen) * s->cluster_size;
131 assert(qcow2_pre_write_overlap_check(bs, 0, ret, clusterlen) == 0);
132 ret = bdrv_pwrite_zeroes(bs->file,
133 ret + headerlen,
134 clusterlen - headerlen, 0);
135 if (ret < 0) {
136 error_setg_errno(errp, -ret, "Could not zero fill encryption header");
137 return -1;
140 return ret;
144 static ssize_t qcow2_crypto_hdr_write_func(QCryptoBlock *block, size_t offset,
145 const uint8_t *buf, size_t buflen,
146 void *opaque, Error **errp)
148 BlockDriverState *bs = opaque;
149 BDRVQcow2State *s = bs->opaque;
150 ssize_t ret;
152 if ((offset + buflen) > s->crypto_header.length) {
153 error_setg(errp, "Request for data outside of extension header");
154 return -1;
157 ret = bdrv_pwrite(bs->file,
158 s->crypto_header.offset + offset, buf, buflen);
159 if (ret < 0) {
160 error_setg_errno(errp, -ret, "Could not read encryption header");
161 return -1;
163 return ret;
168 * read qcow2 extension and fill bs
169 * start reading from start_offset
170 * finish reading upon magic of value 0 or when end_offset reached
171 * unknown magic is skipped (future extension this version knows nothing about)
172 * return 0 upon success, non-0 otherwise
174 static int qcow2_read_extensions(BlockDriverState *bs, uint64_t start_offset,
175 uint64_t end_offset, void **p_feature_table,
176 int flags, bool *need_update_header,
177 Error **errp)
179 BDRVQcow2State *s = bs->opaque;
180 QCowExtension ext;
181 uint64_t offset;
182 int ret;
183 Qcow2BitmapHeaderExt bitmaps_ext;
185 if (need_update_header != NULL) {
186 *need_update_header = false;
189 #ifdef DEBUG_EXT
190 printf("qcow2_read_extensions: start=%ld end=%ld\n", start_offset, end_offset);
191 #endif
192 offset = start_offset;
193 while (offset < end_offset) {
195 #ifdef DEBUG_EXT
196 /* Sanity check */
197 if (offset > s->cluster_size)
198 printf("qcow2_read_extension: suspicious offset %lu\n", offset);
200 printf("attempting to read extended header in offset %lu\n", offset);
201 #endif
203 ret = bdrv_pread(bs->file, offset, &ext, sizeof(ext));
204 if (ret < 0) {
205 error_setg_errno(errp, -ret, "qcow2_read_extension: ERROR: "
206 "pread fail from offset %" PRIu64, offset);
207 return 1;
209 be32_to_cpus(&ext.magic);
210 be32_to_cpus(&ext.len);
211 offset += sizeof(ext);
212 #ifdef DEBUG_EXT
213 printf("ext.magic = 0x%x\n", ext.magic);
214 #endif
215 if (offset > end_offset || ext.len > end_offset - offset) {
216 error_setg(errp, "Header extension too large");
217 return -EINVAL;
220 switch (ext.magic) {
221 case QCOW2_EXT_MAGIC_END:
222 return 0;
224 case QCOW2_EXT_MAGIC_BACKING_FORMAT:
225 if (ext.len >= sizeof(bs->backing_format)) {
226 error_setg(errp, "ERROR: ext_backing_format: len=%" PRIu32
227 " too large (>=%zu)", ext.len,
228 sizeof(bs->backing_format));
229 return 2;
231 ret = bdrv_pread(bs->file, offset, bs->backing_format, ext.len);
232 if (ret < 0) {
233 error_setg_errno(errp, -ret, "ERROR: ext_backing_format: "
234 "Could not read format name");
235 return 3;
237 bs->backing_format[ext.len] = '\0';
238 s->image_backing_format = g_strdup(bs->backing_format);
239 #ifdef DEBUG_EXT
240 printf("Qcow2: Got format extension %s\n", bs->backing_format);
241 #endif
242 break;
244 case QCOW2_EXT_MAGIC_FEATURE_TABLE:
245 if (p_feature_table != NULL) {
246 void* feature_table = g_malloc0(ext.len + 2 * sizeof(Qcow2Feature));
247 ret = bdrv_pread(bs->file, offset , feature_table, ext.len);
248 if (ret < 0) {
249 error_setg_errno(errp, -ret, "ERROR: ext_feature_table: "
250 "Could not read table");
251 return ret;
254 *p_feature_table = feature_table;
256 break;
258 case QCOW2_EXT_MAGIC_CRYPTO_HEADER: {
259 unsigned int cflags = 0;
260 if (s->crypt_method_header != QCOW_CRYPT_LUKS) {
261 error_setg(errp, "CRYPTO header extension only "
262 "expected with LUKS encryption method");
263 return -EINVAL;
265 if (ext.len != sizeof(Qcow2CryptoHeaderExtension)) {
266 error_setg(errp, "CRYPTO header extension size %u, "
267 "but expected size %zu", ext.len,
268 sizeof(Qcow2CryptoHeaderExtension));
269 return -EINVAL;
272 ret = bdrv_pread(bs->file, offset, &s->crypto_header, ext.len);
273 if (ret < 0) {
274 error_setg_errno(errp, -ret,
275 "Unable to read CRYPTO header extension");
276 return ret;
278 be64_to_cpus(&s->crypto_header.offset);
279 be64_to_cpus(&s->crypto_header.length);
281 if ((s->crypto_header.offset % s->cluster_size) != 0) {
282 error_setg(errp, "Encryption header offset '%" PRIu64 "' is "
283 "not a multiple of cluster size '%u'",
284 s->crypto_header.offset, s->cluster_size);
285 return -EINVAL;
288 if (flags & BDRV_O_NO_IO) {
289 cflags |= QCRYPTO_BLOCK_OPEN_NO_IO;
291 s->crypto = qcrypto_block_open(s->crypto_opts, "encrypt.",
292 qcow2_crypto_hdr_read_func,
293 bs, cflags, errp);
294 if (!s->crypto) {
295 return -EINVAL;
297 } break;
299 case QCOW2_EXT_MAGIC_BITMAPS:
300 if (ext.len != sizeof(bitmaps_ext)) {
301 error_setg_errno(errp, -ret, "bitmaps_ext: "
302 "Invalid extension length");
303 return -EINVAL;
306 if (!(s->autoclear_features & QCOW2_AUTOCLEAR_BITMAPS)) {
307 if (s->qcow_version < 3) {
308 /* Let's be a bit more specific */
309 warn_report("This qcow2 v2 image contains bitmaps, but "
310 "they may have been modified by a program "
311 "without persistent bitmap support; so now "
312 "they must all be considered inconsistent");
313 } else {
314 warn_report("a program lacking bitmap support "
315 "modified this file, so all bitmaps are now "
316 "considered inconsistent");
318 error_printf("Some clusters may be leaked, "
319 "run 'qemu-img check -r' on the image "
320 "file to fix.");
321 if (need_update_header != NULL) {
322 /* Updating is needed to drop invalid bitmap extension. */
323 *need_update_header = true;
325 break;
328 ret = bdrv_pread(bs->file, offset, &bitmaps_ext, ext.len);
329 if (ret < 0) {
330 error_setg_errno(errp, -ret, "bitmaps_ext: "
331 "Could not read ext header");
332 return ret;
335 if (bitmaps_ext.reserved32 != 0) {
336 error_setg_errno(errp, -ret, "bitmaps_ext: "
337 "Reserved field is not zero");
338 return -EINVAL;
341 be32_to_cpus(&bitmaps_ext.nb_bitmaps);
342 be64_to_cpus(&bitmaps_ext.bitmap_directory_size);
343 be64_to_cpus(&bitmaps_ext.bitmap_directory_offset);
345 if (bitmaps_ext.nb_bitmaps > QCOW2_MAX_BITMAPS) {
346 error_setg(errp,
347 "bitmaps_ext: Image has %" PRIu32 " bitmaps, "
348 "exceeding the QEMU supported maximum of %d",
349 bitmaps_ext.nb_bitmaps, QCOW2_MAX_BITMAPS);
350 return -EINVAL;
353 if (bitmaps_ext.nb_bitmaps == 0) {
354 error_setg(errp, "found bitmaps extension with zero bitmaps");
355 return -EINVAL;
358 if (bitmaps_ext.bitmap_directory_offset & (s->cluster_size - 1)) {
359 error_setg(errp, "bitmaps_ext: "
360 "invalid bitmap directory offset");
361 return -EINVAL;
364 if (bitmaps_ext.bitmap_directory_size >
365 QCOW2_MAX_BITMAP_DIRECTORY_SIZE) {
366 error_setg(errp, "bitmaps_ext: "
367 "bitmap directory size (%" PRIu64 ") exceeds "
368 "the maximum supported size (%d)",
369 bitmaps_ext.bitmap_directory_size,
370 QCOW2_MAX_BITMAP_DIRECTORY_SIZE);
371 return -EINVAL;
374 s->nb_bitmaps = bitmaps_ext.nb_bitmaps;
375 s->bitmap_directory_offset =
376 bitmaps_ext.bitmap_directory_offset;
377 s->bitmap_directory_size =
378 bitmaps_ext.bitmap_directory_size;
380 #ifdef DEBUG_EXT
381 printf("Qcow2: Got bitmaps extension: "
382 "offset=%" PRIu64 " nb_bitmaps=%" PRIu32 "\n",
383 s->bitmap_directory_offset, s->nb_bitmaps);
384 #endif
385 break;
387 default:
388 /* unknown magic - save it in case we need to rewrite the header */
389 /* If you add a new feature, make sure to also update the fast
390 * path of qcow2_make_empty() to deal with it. */
392 Qcow2UnknownHeaderExtension *uext;
394 uext = g_malloc0(sizeof(*uext) + ext.len);
395 uext->magic = ext.magic;
396 uext->len = ext.len;
397 QLIST_INSERT_HEAD(&s->unknown_header_ext, uext, next);
399 ret = bdrv_pread(bs->file, offset , uext->data, uext->len);
400 if (ret < 0) {
401 error_setg_errno(errp, -ret, "ERROR: unknown extension: "
402 "Could not read data");
403 return ret;
406 break;
409 offset += ((ext.len + 7) & ~7);
412 return 0;
415 static void cleanup_unknown_header_ext(BlockDriverState *bs)
417 BDRVQcow2State *s = bs->opaque;
418 Qcow2UnknownHeaderExtension *uext, *next;
420 QLIST_FOREACH_SAFE(uext, &s->unknown_header_ext, next, next) {
421 QLIST_REMOVE(uext, next);
422 g_free(uext);
426 static void report_unsupported_feature(Error **errp, Qcow2Feature *table,
427 uint64_t mask)
429 char *features = g_strdup("");
430 char *old;
432 while (table && table->name[0] != '\0') {
433 if (table->type == QCOW2_FEAT_TYPE_INCOMPATIBLE) {
434 if (mask & (1ULL << table->bit)) {
435 old = features;
436 features = g_strdup_printf("%s%s%.46s", old, *old ? ", " : "",
437 table->name);
438 g_free(old);
439 mask &= ~(1ULL << table->bit);
442 table++;
445 if (mask) {
446 old = features;
447 features = g_strdup_printf("%s%sUnknown incompatible feature: %" PRIx64,
448 old, *old ? ", " : "", mask);
449 g_free(old);
452 error_setg(errp, "Unsupported qcow2 feature(s): %s", features);
453 g_free(features);
457 * Sets the dirty bit and flushes afterwards if necessary.
459 * The incompatible_features bit is only set if the image file header was
460 * updated successfully. Therefore it is not required to check the return
461 * value of this function.
463 int qcow2_mark_dirty(BlockDriverState *bs)
465 BDRVQcow2State *s = bs->opaque;
466 uint64_t val;
467 int ret;
469 assert(s->qcow_version >= 3);
471 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
472 return 0; /* already dirty */
475 val = cpu_to_be64(s->incompatible_features | QCOW2_INCOMPAT_DIRTY);
476 ret = bdrv_pwrite(bs->file, offsetof(QCowHeader, incompatible_features),
477 &val, sizeof(val));
478 if (ret < 0) {
479 return ret;
481 ret = bdrv_flush(bs->file->bs);
482 if (ret < 0) {
483 return ret;
486 /* Only treat image as dirty if the header was updated successfully */
487 s->incompatible_features |= QCOW2_INCOMPAT_DIRTY;
488 return 0;
492 * Clears the dirty bit and flushes before if necessary. Only call this
493 * function when there are no pending requests, it does not guard against
494 * concurrent requests dirtying the image.
496 static int qcow2_mark_clean(BlockDriverState *bs)
498 BDRVQcow2State *s = bs->opaque;
500 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
501 int ret;
503 s->incompatible_features &= ~QCOW2_INCOMPAT_DIRTY;
505 ret = bdrv_flush(bs);
506 if (ret < 0) {
507 return ret;
510 return qcow2_update_header(bs);
512 return 0;
516 * Marks the image as corrupt.
518 int qcow2_mark_corrupt(BlockDriverState *bs)
520 BDRVQcow2State *s = bs->opaque;
522 s->incompatible_features |= QCOW2_INCOMPAT_CORRUPT;
523 return qcow2_update_header(bs);
527 * Marks the image as consistent, i.e., unsets the corrupt bit, and flushes
528 * before if necessary.
530 int qcow2_mark_consistent(BlockDriverState *bs)
532 BDRVQcow2State *s = bs->opaque;
534 if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
535 int ret = bdrv_flush(bs);
536 if (ret < 0) {
537 return ret;
540 s->incompatible_features &= ~QCOW2_INCOMPAT_CORRUPT;
541 return qcow2_update_header(bs);
543 return 0;
546 static int qcow2_check(BlockDriverState *bs, BdrvCheckResult *result,
547 BdrvCheckMode fix)
549 int ret = qcow2_check_refcounts(bs, result, fix);
550 if (ret < 0) {
551 return ret;
554 if (fix && result->check_errors == 0 && result->corruptions == 0) {
555 ret = qcow2_mark_clean(bs);
556 if (ret < 0) {
557 return ret;
559 return qcow2_mark_consistent(bs);
561 return ret;
564 static int validate_table_offset(BlockDriverState *bs, uint64_t offset,
565 uint64_t entries, size_t entry_len)
567 BDRVQcow2State *s = bs->opaque;
568 uint64_t size;
570 /* Use signed INT64_MAX as the maximum even for uint64_t header fields,
571 * because values will be passed to qemu functions taking int64_t. */
572 if (entries > INT64_MAX / entry_len) {
573 return -EINVAL;
576 size = entries * entry_len;
578 if (INT64_MAX - size < offset) {
579 return -EINVAL;
582 /* Tables must be cluster aligned */
583 if (offset_into_cluster(s, offset) != 0) {
584 return -EINVAL;
587 return 0;
590 static QemuOptsList qcow2_runtime_opts = {
591 .name = "qcow2",
592 .head = QTAILQ_HEAD_INITIALIZER(qcow2_runtime_opts.head),
593 .desc = {
595 .name = QCOW2_OPT_LAZY_REFCOUNTS,
596 .type = QEMU_OPT_BOOL,
597 .help = "Postpone refcount updates",
600 .name = QCOW2_OPT_DISCARD_REQUEST,
601 .type = QEMU_OPT_BOOL,
602 .help = "Pass guest discard requests to the layer below",
605 .name = QCOW2_OPT_DISCARD_SNAPSHOT,
606 .type = QEMU_OPT_BOOL,
607 .help = "Generate discard requests when snapshot related space "
608 "is freed",
611 .name = QCOW2_OPT_DISCARD_OTHER,
612 .type = QEMU_OPT_BOOL,
613 .help = "Generate discard requests when other clusters are freed",
616 .name = QCOW2_OPT_OVERLAP,
617 .type = QEMU_OPT_STRING,
618 .help = "Selects which overlap checks to perform from a range of "
619 "templates (none, constant, cached, all)",
622 .name = QCOW2_OPT_OVERLAP_TEMPLATE,
623 .type = QEMU_OPT_STRING,
624 .help = "Selects which overlap checks to perform from a range of "
625 "templates (none, constant, cached, all)",
628 .name = QCOW2_OPT_OVERLAP_MAIN_HEADER,
629 .type = QEMU_OPT_BOOL,
630 .help = "Check for unintended writes into the main qcow2 header",
633 .name = QCOW2_OPT_OVERLAP_ACTIVE_L1,
634 .type = QEMU_OPT_BOOL,
635 .help = "Check for unintended writes into the active L1 table",
638 .name = QCOW2_OPT_OVERLAP_ACTIVE_L2,
639 .type = QEMU_OPT_BOOL,
640 .help = "Check for unintended writes into an active L2 table",
643 .name = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
644 .type = QEMU_OPT_BOOL,
645 .help = "Check for unintended writes into the refcount table",
648 .name = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
649 .type = QEMU_OPT_BOOL,
650 .help = "Check for unintended writes into a refcount block",
653 .name = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
654 .type = QEMU_OPT_BOOL,
655 .help = "Check for unintended writes into the snapshot table",
658 .name = QCOW2_OPT_OVERLAP_INACTIVE_L1,
659 .type = QEMU_OPT_BOOL,
660 .help = "Check for unintended writes into an inactive L1 table",
663 .name = QCOW2_OPT_OVERLAP_INACTIVE_L2,
664 .type = QEMU_OPT_BOOL,
665 .help = "Check for unintended writes into an inactive L2 table",
668 .name = QCOW2_OPT_CACHE_SIZE,
669 .type = QEMU_OPT_SIZE,
670 .help = "Maximum combined metadata (L2 tables and refcount blocks) "
671 "cache size",
674 .name = QCOW2_OPT_L2_CACHE_SIZE,
675 .type = QEMU_OPT_SIZE,
676 .help = "Maximum L2 table cache size",
679 .name = QCOW2_OPT_REFCOUNT_CACHE_SIZE,
680 .type = QEMU_OPT_SIZE,
681 .help = "Maximum refcount block cache size",
684 .name = QCOW2_OPT_CACHE_CLEAN_INTERVAL,
685 .type = QEMU_OPT_NUMBER,
686 .help = "Clean unused cache entries after this time (in seconds)",
688 BLOCK_CRYPTO_OPT_DEF_KEY_SECRET("encrypt.",
689 "ID of secret providing qcow2 AES key or LUKS passphrase"),
690 { /* end of list */ }
694 static const char *overlap_bool_option_names[QCOW2_OL_MAX_BITNR] = {
695 [QCOW2_OL_MAIN_HEADER_BITNR] = QCOW2_OPT_OVERLAP_MAIN_HEADER,
696 [QCOW2_OL_ACTIVE_L1_BITNR] = QCOW2_OPT_OVERLAP_ACTIVE_L1,
697 [QCOW2_OL_ACTIVE_L2_BITNR] = QCOW2_OPT_OVERLAP_ACTIVE_L2,
698 [QCOW2_OL_REFCOUNT_TABLE_BITNR] = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
699 [QCOW2_OL_REFCOUNT_BLOCK_BITNR] = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
700 [QCOW2_OL_SNAPSHOT_TABLE_BITNR] = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
701 [QCOW2_OL_INACTIVE_L1_BITNR] = QCOW2_OPT_OVERLAP_INACTIVE_L1,
702 [QCOW2_OL_INACTIVE_L2_BITNR] = QCOW2_OPT_OVERLAP_INACTIVE_L2,
705 static void cache_clean_timer_cb(void *opaque)
707 BlockDriverState *bs = opaque;
708 BDRVQcow2State *s = bs->opaque;
709 qcow2_cache_clean_unused(s->l2_table_cache);
710 qcow2_cache_clean_unused(s->refcount_block_cache);
711 timer_mod(s->cache_clean_timer, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) +
712 (int64_t) s->cache_clean_interval * 1000);
715 static void cache_clean_timer_init(BlockDriverState *bs, AioContext *context)
717 BDRVQcow2State *s = bs->opaque;
718 if (s->cache_clean_interval > 0) {
719 s->cache_clean_timer = aio_timer_new(context, QEMU_CLOCK_VIRTUAL,
720 SCALE_MS, cache_clean_timer_cb,
721 bs);
722 timer_mod(s->cache_clean_timer, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) +
723 (int64_t) s->cache_clean_interval * 1000);
727 static void cache_clean_timer_del(BlockDriverState *bs)
729 BDRVQcow2State *s = bs->opaque;
730 if (s->cache_clean_timer) {
731 timer_del(s->cache_clean_timer);
732 timer_free(s->cache_clean_timer);
733 s->cache_clean_timer = NULL;
737 static void qcow2_detach_aio_context(BlockDriverState *bs)
739 cache_clean_timer_del(bs);
742 static void qcow2_attach_aio_context(BlockDriverState *bs,
743 AioContext *new_context)
745 cache_clean_timer_init(bs, new_context);
748 static void read_cache_sizes(BlockDriverState *bs, QemuOpts *opts,
749 uint64_t *l2_cache_size,
750 uint64_t *refcount_cache_size, Error **errp)
752 BDRVQcow2State *s = bs->opaque;
753 uint64_t combined_cache_size;
754 bool l2_cache_size_set, refcount_cache_size_set, combined_cache_size_set;
756 combined_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_CACHE_SIZE);
757 l2_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_L2_CACHE_SIZE);
758 refcount_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
760 combined_cache_size = qemu_opt_get_size(opts, QCOW2_OPT_CACHE_SIZE, 0);
761 *l2_cache_size = qemu_opt_get_size(opts, QCOW2_OPT_L2_CACHE_SIZE, 0);
762 *refcount_cache_size = qemu_opt_get_size(opts,
763 QCOW2_OPT_REFCOUNT_CACHE_SIZE, 0);
765 if (combined_cache_size_set) {
766 if (l2_cache_size_set && refcount_cache_size_set) {
767 error_setg(errp, QCOW2_OPT_CACHE_SIZE ", " QCOW2_OPT_L2_CACHE_SIZE
768 " and " QCOW2_OPT_REFCOUNT_CACHE_SIZE " may not be set "
769 "the same time");
770 return;
771 } else if (*l2_cache_size > combined_cache_size) {
772 error_setg(errp, QCOW2_OPT_L2_CACHE_SIZE " may not exceed "
773 QCOW2_OPT_CACHE_SIZE);
774 return;
775 } else if (*refcount_cache_size > combined_cache_size) {
776 error_setg(errp, QCOW2_OPT_REFCOUNT_CACHE_SIZE " may not exceed "
777 QCOW2_OPT_CACHE_SIZE);
778 return;
781 if (l2_cache_size_set) {
782 *refcount_cache_size = combined_cache_size - *l2_cache_size;
783 } else if (refcount_cache_size_set) {
784 *l2_cache_size = combined_cache_size - *refcount_cache_size;
785 } else {
786 *refcount_cache_size = combined_cache_size
787 / (DEFAULT_L2_REFCOUNT_SIZE_RATIO + 1);
788 *l2_cache_size = combined_cache_size - *refcount_cache_size;
790 } else {
791 if (!l2_cache_size_set && !refcount_cache_size_set) {
792 *l2_cache_size = MAX(DEFAULT_L2_CACHE_BYTE_SIZE,
793 (uint64_t)DEFAULT_L2_CACHE_CLUSTERS
794 * s->cluster_size);
795 *refcount_cache_size = *l2_cache_size
796 / DEFAULT_L2_REFCOUNT_SIZE_RATIO;
797 } else if (!l2_cache_size_set) {
798 *l2_cache_size = *refcount_cache_size
799 * DEFAULT_L2_REFCOUNT_SIZE_RATIO;
800 } else if (!refcount_cache_size_set) {
801 *refcount_cache_size = *l2_cache_size
802 / DEFAULT_L2_REFCOUNT_SIZE_RATIO;
807 typedef struct Qcow2ReopenState {
808 Qcow2Cache *l2_table_cache;
809 Qcow2Cache *refcount_block_cache;
810 int l2_slice_size; /* Number of entries in a slice of the L2 table */
811 bool use_lazy_refcounts;
812 int overlap_check;
813 bool discard_passthrough[QCOW2_DISCARD_MAX];
814 uint64_t cache_clean_interval;
815 QCryptoBlockOpenOptions *crypto_opts; /* Disk encryption runtime options */
816 } Qcow2ReopenState;
818 static int qcow2_update_options_prepare(BlockDriverState *bs,
819 Qcow2ReopenState *r,
820 QDict *options, int flags,
821 Error **errp)
823 BDRVQcow2State *s = bs->opaque;
824 QemuOpts *opts = NULL;
825 const char *opt_overlap_check, *opt_overlap_check_template;
826 int overlap_check_template = 0;
827 uint64_t l2_cache_size, refcount_cache_size;
828 int i;
829 const char *encryptfmt;
830 QDict *encryptopts = NULL;
831 Error *local_err = NULL;
832 int ret;
834 qdict_extract_subqdict(options, &encryptopts, "encrypt.");
835 encryptfmt = qdict_get_try_str(encryptopts, "format");
837 opts = qemu_opts_create(&qcow2_runtime_opts, NULL, 0, &error_abort);
838 qemu_opts_absorb_qdict(opts, options, &local_err);
839 if (local_err) {
840 error_propagate(errp, local_err);
841 ret = -EINVAL;
842 goto fail;
845 /* get L2 table/refcount block cache size from command line options */
846 read_cache_sizes(bs, opts, &l2_cache_size, &refcount_cache_size,
847 &local_err);
848 if (local_err) {
849 error_propagate(errp, local_err);
850 ret = -EINVAL;
851 goto fail;
854 l2_cache_size /= s->cluster_size;
855 if (l2_cache_size < MIN_L2_CACHE_SIZE) {
856 l2_cache_size = MIN_L2_CACHE_SIZE;
858 if (l2_cache_size > INT_MAX) {
859 error_setg(errp, "L2 cache size too big");
860 ret = -EINVAL;
861 goto fail;
864 refcount_cache_size /= s->cluster_size;
865 if (refcount_cache_size < MIN_REFCOUNT_CACHE_SIZE) {
866 refcount_cache_size = MIN_REFCOUNT_CACHE_SIZE;
868 if (refcount_cache_size > INT_MAX) {
869 error_setg(errp, "Refcount cache size too big");
870 ret = -EINVAL;
871 goto fail;
874 /* alloc new L2 table/refcount block cache, flush old one */
875 if (s->l2_table_cache) {
876 ret = qcow2_cache_flush(bs, s->l2_table_cache);
877 if (ret) {
878 error_setg_errno(errp, -ret, "Failed to flush the L2 table cache");
879 goto fail;
883 if (s->refcount_block_cache) {
884 ret = qcow2_cache_flush(bs, s->refcount_block_cache);
885 if (ret) {
886 error_setg_errno(errp, -ret,
887 "Failed to flush the refcount block cache");
888 goto fail;
892 r->l2_slice_size = s->cluster_size / sizeof(uint64_t);
893 r->l2_table_cache = qcow2_cache_create(bs, l2_cache_size);
894 r->refcount_block_cache = qcow2_cache_create(bs, refcount_cache_size);
895 if (r->l2_table_cache == NULL || r->refcount_block_cache == NULL) {
896 error_setg(errp, "Could not allocate metadata caches");
897 ret = -ENOMEM;
898 goto fail;
901 /* New interval for cache cleanup timer */
902 r->cache_clean_interval =
903 qemu_opt_get_number(opts, QCOW2_OPT_CACHE_CLEAN_INTERVAL,
904 s->cache_clean_interval);
905 #ifndef CONFIG_LINUX
906 if (r->cache_clean_interval != 0) {
907 error_setg(errp, QCOW2_OPT_CACHE_CLEAN_INTERVAL
908 " not supported on this host");
909 ret = -EINVAL;
910 goto fail;
912 #endif
913 if (r->cache_clean_interval > UINT_MAX) {
914 error_setg(errp, "Cache clean interval too big");
915 ret = -EINVAL;
916 goto fail;
919 /* lazy-refcounts; flush if going from enabled to disabled */
920 r->use_lazy_refcounts = qemu_opt_get_bool(opts, QCOW2_OPT_LAZY_REFCOUNTS,
921 (s->compatible_features & QCOW2_COMPAT_LAZY_REFCOUNTS));
922 if (r->use_lazy_refcounts && s->qcow_version < 3) {
923 error_setg(errp, "Lazy refcounts require a qcow2 image with at least "
924 "qemu 1.1 compatibility level");
925 ret = -EINVAL;
926 goto fail;
929 if (s->use_lazy_refcounts && !r->use_lazy_refcounts) {
930 ret = qcow2_mark_clean(bs);
931 if (ret < 0) {
932 error_setg_errno(errp, -ret, "Failed to disable lazy refcounts");
933 goto fail;
937 /* Overlap check options */
938 opt_overlap_check = qemu_opt_get(opts, QCOW2_OPT_OVERLAP);
939 opt_overlap_check_template = qemu_opt_get(opts, QCOW2_OPT_OVERLAP_TEMPLATE);
940 if (opt_overlap_check_template && opt_overlap_check &&
941 strcmp(opt_overlap_check_template, opt_overlap_check))
943 error_setg(errp, "Conflicting values for qcow2 options '"
944 QCOW2_OPT_OVERLAP "' ('%s') and '" QCOW2_OPT_OVERLAP_TEMPLATE
945 "' ('%s')", opt_overlap_check, opt_overlap_check_template);
946 ret = -EINVAL;
947 goto fail;
949 if (!opt_overlap_check) {
950 opt_overlap_check = opt_overlap_check_template ?: "cached";
953 if (!strcmp(opt_overlap_check, "none")) {
954 overlap_check_template = 0;
955 } else if (!strcmp(opt_overlap_check, "constant")) {
956 overlap_check_template = QCOW2_OL_CONSTANT;
957 } else if (!strcmp(opt_overlap_check, "cached")) {
958 overlap_check_template = QCOW2_OL_CACHED;
959 } else if (!strcmp(opt_overlap_check, "all")) {
960 overlap_check_template = QCOW2_OL_ALL;
961 } else {
962 error_setg(errp, "Unsupported value '%s' for qcow2 option "
963 "'overlap-check'. Allowed are any of the following: "
964 "none, constant, cached, all", opt_overlap_check);
965 ret = -EINVAL;
966 goto fail;
969 r->overlap_check = 0;
970 for (i = 0; i < QCOW2_OL_MAX_BITNR; i++) {
971 /* overlap-check defines a template bitmask, but every flag may be
972 * overwritten through the associated boolean option */
973 r->overlap_check |=
974 qemu_opt_get_bool(opts, overlap_bool_option_names[i],
975 overlap_check_template & (1 << i)) << i;
978 r->discard_passthrough[QCOW2_DISCARD_NEVER] = false;
979 r->discard_passthrough[QCOW2_DISCARD_ALWAYS] = true;
980 r->discard_passthrough[QCOW2_DISCARD_REQUEST] =
981 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_REQUEST,
982 flags & BDRV_O_UNMAP);
983 r->discard_passthrough[QCOW2_DISCARD_SNAPSHOT] =
984 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_SNAPSHOT, true);
985 r->discard_passthrough[QCOW2_DISCARD_OTHER] =
986 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_OTHER, false);
988 switch (s->crypt_method_header) {
989 case QCOW_CRYPT_NONE:
990 if (encryptfmt) {
991 error_setg(errp, "No encryption in image header, but options "
992 "specified format '%s'", encryptfmt);
993 ret = -EINVAL;
994 goto fail;
996 break;
998 case QCOW_CRYPT_AES:
999 if (encryptfmt && !g_str_equal(encryptfmt, "aes")) {
1000 error_setg(errp,
1001 "Header reported 'aes' encryption format but "
1002 "options specify '%s'", encryptfmt);
1003 ret = -EINVAL;
1004 goto fail;
1006 qdict_del(encryptopts, "format");
1007 r->crypto_opts = block_crypto_open_opts_init(
1008 Q_CRYPTO_BLOCK_FORMAT_QCOW, encryptopts, errp);
1009 break;
1011 case QCOW_CRYPT_LUKS:
1012 if (encryptfmt && !g_str_equal(encryptfmt, "luks")) {
1013 error_setg(errp,
1014 "Header reported 'luks' encryption format but "
1015 "options specify '%s'", encryptfmt);
1016 ret = -EINVAL;
1017 goto fail;
1019 qdict_del(encryptopts, "format");
1020 r->crypto_opts = block_crypto_open_opts_init(
1021 Q_CRYPTO_BLOCK_FORMAT_LUKS, encryptopts, errp);
1022 break;
1024 default:
1025 error_setg(errp, "Unsupported encryption method %d",
1026 s->crypt_method_header);
1027 break;
1029 if (s->crypt_method_header != QCOW_CRYPT_NONE && !r->crypto_opts) {
1030 ret = -EINVAL;
1031 goto fail;
1034 ret = 0;
1035 fail:
1036 QDECREF(encryptopts);
1037 qemu_opts_del(opts);
1038 opts = NULL;
1039 return ret;
1042 static void qcow2_update_options_commit(BlockDriverState *bs,
1043 Qcow2ReopenState *r)
1045 BDRVQcow2State *s = bs->opaque;
1046 int i;
1048 if (s->l2_table_cache) {
1049 qcow2_cache_destroy(s->l2_table_cache);
1051 if (s->refcount_block_cache) {
1052 qcow2_cache_destroy(s->refcount_block_cache);
1054 s->l2_table_cache = r->l2_table_cache;
1055 s->refcount_block_cache = r->refcount_block_cache;
1056 s->l2_slice_size = r->l2_slice_size;
1058 s->overlap_check = r->overlap_check;
1059 s->use_lazy_refcounts = r->use_lazy_refcounts;
1061 for (i = 0; i < QCOW2_DISCARD_MAX; i++) {
1062 s->discard_passthrough[i] = r->discard_passthrough[i];
1065 if (s->cache_clean_interval != r->cache_clean_interval) {
1066 cache_clean_timer_del(bs);
1067 s->cache_clean_interval = r->cache_clean_interval;
1068 cache_clean_timer_init(bs, bdrv_get_aio_context(bs));
1071 qapi_free_QCryptoBlockOpenOptions(s->crypto_opts);
1072 s->crypto_opts = r->crypto_opts;
1075 static void qcow2_update_options_abort(BlockDriverState *bs,
1076 Qcow2ReopenState *r)
1078 if (r->l2_table_cache) {
1079 qcow2_cache_destroy(r->l2_table_cache);
1081 if (r->refcount_block_cache) {
1082 qcow2_cache_destroy(r->refcount_block_cache);
1084 qapi_free_QCryptoBlockOpenOptions(r->crypto_opts);
1087 static int qcow2_update_options(BlockDriverState *bs, QDict *options,
1088 int flags, Error **errp)
1090 Qcow2ReopenState r = {};
1091 int ret;
1093 ret = qcow2_update_options_prepare(bs, &r, options, flags, errp);
1094 if (ret >= 0) {
1095 qcow2_update_options_commit(bs, &r);
1096 } else {
1097 qcow2_update_options_abort(bs, &r);
1100 return ret;
1103 static int qcow2_do_open(BlockDriverState *bs, QDict *options, int flags,
1104 Error **errp)
1106 BDRVQcow2State *s = bs->opaque;
1107 unsigned int len, i;
1108 int ret = 0;
1109 QCowHeader header;
1110 Error *local_err = NULL;
1111 uint64_t ext_end;
1112 uint64_t l1_vm_state_index;
1113 bool update_header = false;
1115 ret = bdrv_pread(bs->file, 0, &header, sizeof(header));
1116 if (ret < 0) {
1117 error_setg_errno(errp, -ret, "Could not read qcow2 header");
1118 goto fail;
1120 be32_to_cpus(&header.magic);
1121 be32_to_cpus(&header.version);
1122 be64_to_cpus(&header.backing_file_offset);
1123 be32_to_cpus(&header.backing_file_size);
1124 be64_to_cpus(&header.size);
1125 be32_to_cpus(&header.cluster_bits);
1126 be32_to_cpus(&header.crypt_method);
1127 be64_to_cpus(&header.l1_table_offset);
1128 be32_to_cpus(&header.l1_size);
1129 be64_to_cpus(&header.refcount_table_offset);
1130 be32_to_cpus(&header.refcount_table_clusters);
1131 be64_to_cpus(&header.snapshots_offset);
1132 be32_to_cpus(&header.nb_snapshots);
1134 if (header.magic != QCOW_MAGIC) {
1135 error_setg(errp, "Image is not in qcow2 format");
1136 ret = -EINVAL;
1137 goto fail;
1139 if (header.version < 2 || header.version > 3) {
1140 error_setg(errp, "Unsupported qcow2 version %" PRIu32, header.version);
1141 ret = -ENOTSUP;
1142 goto fail;
1145 s->qcow_version = header.version;
1147 /* Initialise cluster size */
1148 if (header.cluster_bits < MIN_CLUSTER_BITS ||
1149 header.cluster_bits > MAX_CLUSTER_BITS) {
1150 error_setg(errp, "Unsupported cluster size: 2^%" PRIu32,
1151 header.cluster_bits);
1152 ret = -EINVAL;
1153 goto fail;
1156 s->cluster_bits = header.cluster_bits;
1157 s->cluster_size = 1 << s->cluster_bits;
1158 s->cluster_sectors = 1 << (s->cluster_bits - BDRV_SECTOR_BITS);
1160 /* Initialise version 3 header fields */
1161 if (header.version == 2) {
1162 header.incompatible_features = 0;
1163 header.compatible_features = 0;
1164 header.autoclear_features = 0;
1165 header.refcount_order = 4;
1166 header.header_length = 72;
1167 } else {
1168 be64_to_cpus(&header.incompatible_features);
1169 be64_to_cpus(&header.compatible_features);
1170 be64_to_cpus(&header.autoclear_features);
1171 be32_to_cpus(&header.refcount_order);
1172 be32_to_cpus(&header.header_length);
1174 if (header.header_length < 104) {
1175 error_setg(errp, "qcow2 header too short");
1176 ret = -EINVAL;
1177 goto fail;
1181 if (header.header_length > s->cluster_size) {
1182 error_setg(errp, "qcow2 header exceeds cluster size");
1183 ret = -EINVAL;
1184 goto fail;
1187 if (header.header_length > sizeof(header)) {
1188 s->unknown_header_fields_size = header.header_length - sizeof(header);
1189 s->unknown_header_fields = g_malloc(s->unknown_header_fields_size);
1190 ret = bdrv_pread(bs->file, sizeof(header), s->unknown_header_fields,
1191 s->unknown_header_fields_size);
1192 if (ret < 0) {
1193 error_setg_errno(errp, -ret, "Could not read unknown qcow2 header "
1194 "fields");
1195 goto fail;
1199 if (header.backing_file_offset > s->cluster_size) {
1200 error_setg(errp, "Invalid backing file offset");
1201 ret = -EINVAL;
1202 goto fail;
1205 if (header.backing_file_offset) {
1206 ext_end = header.backing_file_offset;
1207 } else {
1208 ext_end = 1 << header.cluster_bits;
1211 /* Handle feature bits */
1212 s->incompatible_features = header.incompatible_features;
1213 s->compatible_features = header.compatible_features;
1214 s->autoclear_features = header.autoclear_features;
1216 if (s->incompatible_features & ~QCOW2_INCOMPAT_MASK) {
1217 void *feature_table = NULL;
1218 qcow2_read_extensions(bs, header.header_length, ext_end,
1219 &feature_table, flags, NULL, NULL);
1220 report_unsupported_feature(errp, feature_table,
1221 s->incompatible_features &
1222 ~QCOW2_INCOMPAT_MASK);
1223 ret = -ENOTSUP;
1224 g_free(feature_table);
1225 goto fail;
1228 if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
1229 /* Corrupt images may not be written to unless they are being repaired
1231 if ((flags & BDRV_O_RDWR) && !(flags & BDRV_O_CHECK)) {
1232 error_setg(errp, "qcow2: Image is corrupt; cannot be opened "
1233 "read/write");
1234 ret = -EACCES;
1235 goto fail;
1239 /* Check support for various header values */
1240 if (header.refcount_order > 6) {
1241 error_setg(errp, "Reference count entry width too large; may not "
1242 "exceed 64 bits");
1243 ret = -EINVAL;
1244 goto fail;
1246 s->refcount_order = header.refcount_order;
1247 s->refcount_bits = 1 << s->refcount_order;
1248 s->refcount_max = UINT64_C(1) << (s->refcount_bits - 1);
1249 s->refcount_max += s->refcount_max - 1;
1251 s->crypt_method_header = header.crypt_method;
1252 if (s->crypt_method_header) {
1253 if (bdrv_uses_whitelist() &&
1254 s->crypt_method_header == QCOW_CRYPT_AES) {
1255 error_setg(errp,
1256 "Use of AES-CBC encrypted qcow2 images is no longer "
1257 "supported in system emulators");
1258 error_append_hint(errp,
1259 "You can use 'qemu-img convert' to convert your "
1260 "image to an alternative supported format, such "
1261 "as unencrypted qcow2, or raw with the LUKS "
1262 "format instead.\n");
1263 ret = -ENOSYS;
1264 goto fail;
1267 if (s->crypt_method_header == QCOW_CRYPT_AES) {
1268 s->crypt_physical_offset = false;
1269 } else {
1270 /* Assuming LUKS and any future crypt methods we
1271 * add will all use physical offsets, due to the
1272 * fact that the alternative is insecure... */
1273 s->crypt_physical_offset = true;
1276 bs->encrypted = true;
1279 s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */
1280 s->l2_size = 1 << s->l2_bits;
1281 /* 2^(s->refcount_order - 3) is the refcount width in bytes */
1282 s->refcount_block_bits = s->cluster_bits - (s->refcount_order - 3);
1283 s->refcount_block_size = 1 << s->refcount_block_bits;
1284 bs->total_sectors = header.size / 512;
1285 s->csize_shift = (62 - (s->cluster_bits - 8));
1286 s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;
1287 s->cluster_offset_mask = (1LL << s->csize_shift) - 1;
1289 s->refcount_table_offset = header.refcount_table_offset;
1290 s->refcount_table_size =
1291 header.refcount_table_clusters << (s->cluster_bits - 3);
1293 if (header.refcount_table_clusters > qcow2_max_refcount_clusters(s)) {
1294 error_setg(errp, "Reference count table too large");
1295 ret = -EINVAL;
1296 goto fail;
1299 if (header.refcount_table_clusters == 0 && !(flags & BDRV_O_CHECK)) {
1300 error_setg(errp, "Image does not contain a reference count table");
1301 ret = -EINVAL;
1302 goto fail;
1305 ret = validate_table_offset(bs, s->refcount_table_offset,
1306 s->refcount_table_size, sizeof(uint64_t));
1307 if (ret < 0) {
1308 error_setg(errp, "Invalid reference count table offset");
1309 goto fail;
1312 /* Snapshot table offset/length */
1313 if (header.nb_snapshots > QCOW_MAX_SNAPSHOTS) {
1314 error_setg(errp, "Too many snapshots");
1315 ret = -EINVAL;
1316 goto fail;
1319 ret = validate_table_offset(bs, header.snapshots_offset,
1320 header.nb_snapshots,
1321 sizeof(QCowSnapshotHeader));
1322 if (ret < 0) {
1323 error_setg(errp, "Invalid snapshot table offset");
1324 goto fail;
1327 /* read the level 1 table */
1328 if (header.l1_size > QCOW_MAX_L1_SIZE / sizeof(uint64_t)) {
1329 error_setg(errp, "Active L1 table too large");
1330 ret = -EFBIG;
1331 goto fail;
1333 s->l1_size = header.l1_size;
1335 l1_vm_state_index = size_to_l1(s, header.size);
1336 if (l1_vm_state_index > INT_MAX) {
1337 error_setg(errp, "Image is too big");
1338 ret = -EFBIG;
1339 goto fail;
1341 s->l1_vm_state_index = l1_vm_state_index;
1343 /* the L1 table must contain at least enough entries to put
1344 header.size bytes */
1345 if (s->l1_size < s->l1_vm_state_index) {
1346 error_setg(errp, "L1 table is too small");
1347 ret = -EINVAL;
1348 goto fail;
1351 ret = validate_table_offset(bs, header.l1_table_offset,
1352 header.l1_size, sizeof(uint64_t));
1353 if (ret < 0) {
1354 error_setg(errp, "Invalid L1 table offset");
1355 goto fail;
1357 s->l1_table_offset = header.l1_table_offset;
1360 if (s->l1_size > 0) {
1361 s->l1_table = qemu_try_blockalign(bs->file->bs,
1362 align_offset(s->l1_size * sizeof(uint64_t), 512));
1363 if (s->l1_table == NULL) {
1364 error_setg(errp, "Could not allocate L1 table");
1365 ret = -ENOMEM;
1366 goto fail;
1368 ret = bdrv_pread(bs->file, s->l1_table_offset, s->l1_table,
1369 s->l1_size * sizeof(uint64_t));
1370 if (ret < 0) {
1371 error_setg_errno(errp, -ret, "Could not read L1 table");
1372 goto fail;
1374 for(i = 0;i < s->l1_size; i++) {
1375 be64_to_cpus(&s->l1_table[i]);
1379 /* Parse driver-specific options */
1380 ret = qcow2_update_options(bs, options, flags, errp);
1381 if (ret < 0) {
1382 goto fail;
1385 s->cluster_cache_offset = -1;
1386 s->flags = flags;
1388 ret = qcow2_refcount_init(bs);
1389 if (ret != 0) {
1390 error_setg_errno(errp, -ret, "Could not initialize refcount handling");
1391 goto fail;
1394 QLIST_INIT(&s->cluster_allocs);
1395 QTAILQ_INIT(&s->discards);
1397 /* read qcow2 extensions */
1398 if (qcow2_read_extensions(bs, header.header_length, ext_end, NULL,
1399 flags, &update_header, &local_err)) {
1400 error_propagate(errp, local_err);
1401 ret = -EINVAL;
1402 goto fail;
1405 /* qcow2_read_extension may have set up the crypto context
1406 * if the crypt method needs a header region, some methods
1407 * don't need header extensions, so must check here
1409 if (s->crypt_method_header && !s->crypto) {
1410 if (s->crypt_method_header == QCOW_CRYPT_AES) {
1411 unsigned int cflags = 0;
1412 if (flags & BDRV_O_NO_IO) {
1413 cflags |= QCRYPTO_BLOCK_OPEN_NO_IO;
1415 s->crypto = qcrypto_block_open(s->crypto_opts, "encrypt.",
1416 NULL, NULL, cflags, errp);
1417 if (!s->crypto) {
1418 ret = -EINVAL;
1419 goto fail;
1421 } else if (!(flags & BDRV_O_NO_IO)) {
1422 error_setg(errp, "Missing CRYPTO header for crypt method %d",
1423 s->crypt_method_header);
1424 ret = -EINVAL;
1425 goto fail;
1429 /* read the backing file name */
1430 if (header.backing_file_offset != 0) {
1431 len = header.backing_file_size;
1432 if (len > MIN(1023, s->cluster_size - header.backing_file_offset) ||
1433 len >= sizeof(bs->backing_file)) {
1434 error_setg(errp, "Backing file name too long");
1435 ret = -EINVAL;
1436 goto fail;
1438 ret = bdrv_pread(bs->file, header.backing_file_offset,
1439 bs->backing_file, len);
1440 if (ret < 0) {
1441 error_setg_errno(errp, -ret, "Could not read backing file name");
1442 goto fail;
1444 bs->backing_file[len] = '\0';
1445 s->image_backing_file = g_strdup(bs->backing_file);
1448 /* Internal snapshots */
1449 s->snapshots_offset = header.snapshots_offset;
1450 s->nb_snapshots = header.nb_snapshots;
1452 ret = qcow2_read_snapshots(bs);
1453 if (ret < 0) {
1454 error_setg_errno(errp, -ret, "Could not read snapshots");
1455 goto fail;
1458 /* Clear unknown autoclear feature bits */
1459 update_header |= s->autoclear_features & ~QCOW2_AUTOCLEAR_MASK;
1460 update_header =
1461 update_header && !bs->read_only && !(flags & BDRV_O_INACTIVE);
1462 if (update_header) {
1463 s->autoclear_features &= QCOW2_AUTOCLEAR_MASK;
1466 if (qcow2_load_dirty_bitmaps(bs, &local_err)) {
1467 update_header = false;
1469 if (local_err != NULL) {
1470 error_propagate(errp, local_err);
1471 ret = -EINVAL;
1472 goto fail;
1475 if (update_header) {
1476 ret = qcow2_update_header(bs);
1477 if (ret < 0) {
1478 error_setg_errno(errp, -ret, "Could not update qcow2 header");
1479 goto fail;
1483 /* Initialise locks */
1484 qemu_co_mutex_init(&s->lock);
1485 bs->supported_zero_flags = header.version >= 3 ? BDRV_REQ_MAY_UNMAP : 0;
1487 /* Repair image if dirty */
1488 if (!(flags & (BDRV_O_CHECK | BDRV_O_INACTIVE)) && !bs->read_only &&
1489 (s->incompatible_features & QCOW2_INCOMPAT_DIRTY)) {
1490 BdrvCheckResult result = {0};
1492 ret = qcow2_check(bs, &result, BDRV_FIX_ERRORS | BDRV_FIX_LEAKS);
1493 if (ret < 0 || result.check_errors) {
1494 if (ret >= 0) {
1495 ret = -EIO;
1497 error_setg_errno(errp, -ret, "Could not repair dirty image");
1498 goto fail;
1502 #ifdef DEBUG_ALLOC
1504 BdrvCheckResult result = {0};
1505 qcow2_check_refcounts(bs, &result, 0);
1507 #endif
1508 return ret;
1510 fail:
1511 g_free(s->unknown_header_fields);
1512 cleanup_unknown_header_ext(bs);
1513 qcow2_free_snapshots(bs);
1514 qcow2_refcount_close(bs);
1515 qemu_vfree(s->l1_table);
1516 /* else pre-write overlap checks in cache_destroy may crash */
1517 s->l1_table = NULL;
1518 cache_clean_timer_del(bs);
1519 if (s->l2_table_cache) {
1520 qcow2_cache_destroy(s->l2_table_cache);
1522 if (s->refcount_block_cache) {
1523 qcow2_cache_destroy(s->refcount_block_cache);
1525 qcrypto_block_free(s->crypto);
1526 qapi_free_QCryptoBlockOpenOptions(s->crypto_opts);
1527 return ret;
1530 static int qcow2_open(BlockDriverState *bs, QDict *options, int flags,
1531 Error **errp)
1533 bs->file = bdrv_open_child(NULL, options, "file", bs, &child_file,
1534 false, errp);
1535 if (!bs->file) {
1536 return -EINVAL;
1539 return qcow2_do_open(bs, options, flags, errp);
1542 static void qcow2_refresh_limits(BlockDriverState *bs, Error **errp)
1544 BDRVQcow2State *s = bs->opaque;
1546 if (bs->encrypted) {
1547 /* Encryption works on a sector granularity */
1548 bs->bl.request_alignment = BDRV_SECTOR_SIZE;
1550 bs->bl.pwrite_zeroes_alignment = s->cluster_size;
1551 bs->bl.pdiscard_alignment = s->cluster_size;
1554 static int qcow2_reopen_prepare(BDRVReopenState *state,
1555 BlockReopenQueue *queue, Error **errp)
1557 Qcow2ReopenState *r;
1558 int ret;
1560 r = g_new0(Qcow2ReopenState, 1);
1561 state->opaque = r;
1563 ret = qcow2_update_options_prepare(state->bs, r, state->options,
1564 state->flags, errp);
1565 if (ret < 0) {
1566 goto fail;
1569 /* We need to write out any unwritten data if we reopen read-only. */
1570 if ((state->flags & BDRV_O_RDWR) == 0) {
1571 ret = qcow2_reopen_bitmaps_ro(state->bs, errp);
1572 if (ret < 0) {
1573 goto fail;
1576 ret = bdrv_flush(state->bs);
1577 if (ret < 0) {
1578 goto fail;
1581 ret = qcow2_mark_clean(state->bs);
1582 if (ret < 0) {
1583 goto fail;
1587 return 0;
1589 fail:
1590 qcow2_update_options_abort(state->bs, r);
1591 g_free(r);
1592 return ret;
1595 static void qcow2_reopen_commit(BDRVReopenState *state)
1597 qcow2_update_options_commit(state->bs, state->opaque);
1598 g_free(state->opaque);
1601 static void qcow2_reopen_abort(BDRVReopenState *state)
1603 qcow2_update_options_abort(state->bs, state->opaque);
1604 g_free(state->opaque);
1607 static void qcow2_join_options(QDict *options, QDict *old_options)
1609 bool has_new_overlap_template =
1610 qdict_haskey(options, QCOW2_OPT_OVERLAP) ||
1611 qdict_haskey(options, QCOW2_OPT_OVERLAP_TEMPLATE);
1612 bool has_new_total_cache_size =
1613 qdict_haskey(options, QCOW2_OPT_CACHE_SIZE);
1614 bool has_all_cache_options;
1616 /* New overlap template overrides all old overlap options */
1617 if (has_new_overlap_template) {
1618 qdict_del(old_options, QCOW2_OPT_OVERLAP);
1619 qdict_del(old_options, QCOW2_OPT_OVERLAP_TEMPLATE);
1620 qdict_del(old_options, QCOW2_OPT_OVERLAP_MAIN_HEADER);
1621 qdict_del(old_options, QCOW2_OPT_OVERLAP_ACTIVE_L1);
1622 qdict_del(old_options, QCOW2_OPT_OVERLAP_ACTIVE_L2);
1623 qdict_del(old_options, QCOW2_OPT_OVERLAP_REFCOUNT_TABLE);
1624 qdict_del(old_options, QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK);
1625 qdict_del(old_options, QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE);
1626 qdict_del(old_options, QCOW2_OPT_OVERLAP_INACTIVE_L1);
1627 qdict_del(old_options, QCOW2_OPT_OVERLAP_INACTIVE_L2);
1630 /* New total cache size overrides all old options */
1631 if (qdict_haskey(options, QCOW2_OPT_CACHE_SIZE)) {
1632 qdict_del(old_options, QCOW2_OPT_L2_CACHE_SIZE);
1633 qdict_del(old_options, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
1636 qdict_join(options, old_options, false);
1639 * If after merging all cache size options are set, an old total size is
1640 * overwritten. Do keep all options, however, if all three are new. The
1641 * resulting error message is what we want to happen.
1643 has_all_cache_options =
1644 qdict_haskey(options, QCOW2_OPT_CACHE_SIZE) ||
1645 qdict_haskey(options, QCOW2_OPT_L2_CACHE_SIZE) ||
1646 qdict_haskey(options, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
1648 if (has_all_cache_options && !has_new_total_cache_size) {
1649 qdict_del(options, QCOW2_OPT_CACHE_SIZE);
1653 static int64_t coroutine_fn qcow2_co_get_block_status(BlockDriverState *bs,
1654 int64_t sector_num, int nb_sectors, int *pnum, BlockDriverState **file)
1656 BDRVQcow2State *s = bs->opaque;
1657 uint64_t cluster_offset;
1658 int index_in_cluster, ret;
1659 unsigned int bytes;
1660 int64_t status = 0;
1662 bytes = MIN(INT_MAX, nb_sectors * BDRV_SECTOR_SIZE);
1663 qemu_co_mutex_lock(&s->lock);
1664 ret = qcow2_get_cluster_offset(bs, sector_num << BDRV_SECTOR_BITS, &bytes,
1665 &cluster_offset);
1666 qemu_co_mutex_unlock(&s->lock);
1667 if (ret < 0) {
1668 return ret;
1671 *pnum = bytes >> BDRV_SECTOR_BITS;
1673 if (cluster_offset != 0 && ret != QCOW2_CLUSTER_COMPRESSED &&
1674 !s->crypto) {
1675 index_in_cluster = sector_num & (s->cluster_sectors - 1);
1676 cluster_offset |= (index_in_cluster << BDRV_SECTOR_BITS);
1677 *file = bs->file->bs;
1678 status |= BDRV_BLOCK_OFFSET_VALID | cluster_offset;
1680 if (ret == QCOW2_CLUSTER_ZERO_PLAIN || ret == QCOW2_CLUSTER_ZERO_ALLOC) {
1681 status |= BDRV_BLOCK_ZERO;
1682 } else if (ret != QCOW2_CLUSTER_UNALLOCATED) {
1683 status |= BDRV_BLOCK_DATA;
1685 return status;
1688 static coroutine_fn int qcow2_co_preadv(BlockDriverState *bs, uint64_t offset,
1689 uint64_t bytes, QEMUIOVector *qiov,
1690 int flags)
1692 BDRVQcow2State *s = bs->opaque;
1693 int offset_in_cluster;
1694 int ret;
1695 unsigned int cur_bytes; /* number of bytes in current iteration */
1696 uint64_t cluster_offset = 0;
1697 uint64_t bytes_done = 0;
1698 QEMUIOVector hd_qiov;
1699 uint8_t *cluster_data = NULL;
1701 qemu_iovec_init(&hd_qiov, qiov->niov);
1703 qemu_co_mutex_lock(&s->lock);
1705 while (bytes != 0) {
1707 /* prepare next request */
1708 cur_bytes = MIN(bytes, INT_MAX);
1709 if (s->crypto) {
1710 cur_bytes = MIN(cur_bytes,
1711 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
1714 ret = qcow2_get_cluster_offset(bs, offset, &cur_bytes, &cluster_offset);
1715 if (ret < 0) {
1716 goto fail;
1719 offset_in_cluster = offset_into_cluster(s, offset);
1721 qemu_iovec_reset(&hd_qiov);
1722 qemu_iovec_concat(&hd_qiov, qiov, bytes_done, cur_bytes);
1724 switch (ret) {
1725 case QCOW2_CLUSTER_UNALLOCATED:
1727 if (bs->backing) {
1728 BLKDBG_EVENT(bs->file, BLKDBG_READ_BACKING_AIO);
1729 qemu_co_mutex_unlock(&s->lock);
1730 ret = bdrv_co_preadv(bs->backing, offset, cur_bytes,
1731 &hd_qiov, 0);
1732 qemu_co_mutex_lock(&s->lock);
1733 if (ret < 0) {
1734 goto fail;
1736 } else {
1737 /* Note: in this case, no need to wait */
1738 qemu_iovec_memset(&hd_qiov, 0, 0, cur_bytes);
1740 break;
1742 case QCOW2_CLUSTER_ZERO_PLAIN:
1743 case QCOW2_CLUSTER_ZERO_ALLOC:
1744 qemu_iovec_memset(&hd_qiov, 0, 0, cur_bytes);
1745 break;
1747 case QCOW2_CLUSTER_COMPRESSED:
1748 /* add AIO support for compressed blocks ? */
1749 ret = qcow2_decompress_cluster(bs, cluster_offset);
1750 if (ret < 0) {
1751 goto fail;
1754 qemu_iovec_from_buf(&hd_qiov, 0,
1755 s->cluster_cache + offset_in_cluster,
1756 cur_bytes);
1757 break;
1759 case QCOW2_CLUSTER_NORMAL:
1760 if ((cluster_offset & 511) != 0) {
1761 ret = -EIO;
1762 goto fail;
1765 if (bs->encrypted) {
1766 assert(s->crypto);
1769 * For encrypted images, read everything into a temporary
1770 * contiguous buffer on which the AES functions can work.
1772 if (!cluster_data) {
1773 cluster_data =
1774 qemu_try_blockalign(bs->file->bs,
1775 QCOW_MAX_CRYPT_CLUSTERS
1776 * s->cluster_size);
1777 if (cluster_data == NULL) {
1778 ret = -ENOMEM;
1779 goto fail;
1783 assert(cur_bytes <= QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
1784 qemu_iovec_reset(&hd_qiov);
1785 qemu_iovec_add(&hd_qiov, cluster_data, cur_bytes);
1788 BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);
1789 qemu_co_mutex_unlock(&s->lock);
1790 ret = bdrv_co_preadv(bs->file,
1791 cluster_offset + offset_in_cluster,
1792 cur_bytes, &hd_qiov, 0);
1793 qemu_co_mutex_lock(&s->lock);
1794 if (ret < 0) {
1795 goto fail;
1797 if (bs->encrypted) {
1798 assert(s->crypto);
1799 assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);
1800 assert((cur_bytes & (BDRV_SECTOR_SIZE - 1)) == 0);
1801 if (qcrypto_block_decrypt(s->crypto,
1802 (s->crypt_physical_offset ?
1803 cluster_offset + offset_in_cluster :
1804 offset),
1805 cluster_data,
1806 cur_bytes,
1807 NULL) < 0) {
1808 ret = -EIO;
1809 goto fail;
1811 qemu_iovec_from_buf(qiov, bytes_done, cluster_data, cur_bytes);
1813 break;
1815 default:
1816 g_assert_not_reached();
1817 ret = -EIO;
1818 goto fail;
1821 bytes -= cur_bytes;
1822 offset += cur_bytes;
1823 bytes_done += cur_bytes;
1825 ret = 0;
1827 fail:
1828 qemu_co_mutex_unlock(&s->lock);
1830 qemu_iovec_destroy(&hd_qiov);
1831 qemu_vfree(cluster_data);
1833 return ret;
1836 /* Check if it's possible to merge a write request with the writing of
1837 * the data from the COW regions */
1838 static bool merge_cow(uint64_t offset, unsigned bytes,
1839 QEMUIOVector *hd_qiov, QCowL2Meta *l2meta)
1841 QCowL2Meta *m;
1843 for (m = l2meta; m != NULL; m = m->next) {
1844 /* If both COW regions are empty then there's nothing to merge */
1845 if (m->cow_start.nb_bytes == 0 && m->cow_end.nb_bytes == 0) {
1846 continue;
1849 /* The data (middle) region must be immediately after the
1850 * start region */
1851 if (l2meta_cow_start(m) + m->cow_start.nb_bytes != offset) {
1852 continue;
1855 /* The end region must be immediately after the data (middle)
1856 * region */
1857 if (m->offset + m->cow_end.offset != offset + bytes) {
1858 continue;
1861 /* Make sure that adding both COW regions to the QEMUIOVector
1862 * does not exceed IOV_MAX */
1863 if (hd_qiov->niov > IOV_MAX - 2) {
1864 continue;
1867 m->data_qiov = hd_qiov;
1868 return true;
1871 return false;
1874 static coroutine_fn int qcow2_co_pwritev(BlockDriverState *bs, uint64_t offset,
1875 uint64_t bytes, QEMUIOVector *qiov,
1876 int flags)
1878 BDRVQcow2State *s = bs->opaque;
1879 int offset_in_cluster;
1880 int ret;
1881 unsigned int cur_bytes; /* number of sectors in current iteration */
1882 uint64_t cluster_offset;
1883 QEMUIOVector hd_qiov;
1884 uint64_t bytes_done = 0;
1885 uint8_t *cluster_data = NULL;
1886 QCowL2Meta *l2meta = NULL;
1888 trace_qcow2_writev_start_req(qemu_coroutine_self(), offset, bytes);
1890 qemu_iovec_init(&hd_qiov, qiov->niov);
1892 s->cluster_cache_offset = -1; /* disable compressed cache */
1894 qemu_co_mutex_lock(&s->lock);
1896 while (bytes != 0) {
1898 l2meta = NULL;
1900 trace_qcow2_writev_start_part(qemu_coroutine_self());
1901 offset_in_cluster = offset_into_cluster(s, offset);
1902 cur_bytes = MIN(bytes, INT_MAX);
1903 if (bs->encrypted) {
1904 cur_bytes = MIN(cur_bytes,
1905 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size
1906 - offset_in_cluster);
1909 ret = qcow2_alloc_cluster_offset(bs, offset, &cur_bytes,
1910 &cluster_offset, &l2meta);
1911 if (ret < 0) {
1912 goto fail;
1915 assert((cluster_offset & 511) == 0);
1917 qemu_iovec_reset(&hd_qiov);
1918 qemu_iovec_concat(&hd_qiov, qiov, bytes_done, cur_bytes);
1920 if (bs->encrypted) {
1921 assert(s->crypto);
1922 if (!cluster_data) {
1923 cluster_data = qemu_try_blockalign(bs->file->bs,
1924 QCOW_MAX_CRYPT_CLUSTERS
1925 * s->cluster_size);
1926 if (cluster_data == NULL) {
1927 ret = -ENOMEM;
1928 goto fail;
1932 assert(hd_qiov.size <=
1933 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
1934 qemu_iovec_to_buf(&hd_qiov, 0, cluster_data, hd_qiov.size);
1936 if (qcrypto_block_encrypt(s->crypto,
1937 (s->crypt_physical_offset ?
1938 cluster_offset + offset_in_cluster :
1939 offset),
1940 cluster_data,
1941 cur_bytes, NULL) < 0) {
1942 ret = -EIO;
1943 goto fail;
1946 qemu_iovec_reset(&hd_qiov);
1947 qemu_iovec_add(&hd_qiov, cluster_data, cur_bytes);
1950 ret = qcow2_pre_write_overlap_check(bs, 0,
1951 cluster_offset + offset_in_cluster, cur_bytes);
1952 if (ret < 0) {
1953 goto fail;
1956 /* If we need to do COW, check if it's possible to merge the
1957 * writing of the guest data together with that of the COW regions.
1958 * If it's not possible (or not necessary) then write the
1959 * guest data now. */
1960 if (!merge_cow(offset, cur_bytes, &hd_qiov, l2meta)) {
1961 qemu_co_mutex_unlock(&s->lock);
1962 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO);
1963 trace_qcow2_writev_data(qemu_coroutine_self(),
1964 cluster_offset + offset_in_cluster);
1965 ret = bdrv_co_pwritev(bs->file,
1966 cluster_offset + offset_in_cluster,
1967 cur_bytes, &hd_qiov, 0);
1968 qemu_co_mutex_lock(&s->lock);
1969 if (ret < 0) {
1970 goto fail;
1974 while (l2meta != NULL) {
1975 QCowL2Meta *next;
1977 ret = qcow2_alloc_cluster_link_l2(bs, l2meta);
1978 if (ret < 0) {
1979 goto fail;
1982 /* Take the request off the list of running requests */
1983 if (l2meta->nb_clusters != 0) {
1984 QLIST_REMOVE(l2meta, next_in_flight);
1987 qemu_co_queue_restart_all(&l2meta->dependent_requests);
1989 next = l2meta->next;
1990 g_free(l2meta);
1991 l2meta = next;
1994 bytes -= cur_bytes;
1995 offset += cur_bytes;
1996 bytes_done += cur_bytes;
1997 trace_qcow2_writev_done_part(qemu_coroutine_self(), cur_bytes);
1999 ret = 0;
2001 fail:
2002 while (l2meta != NULL) {
2003 QCowL2Meta *next;
2005 if (l2meta->nb_clusters != 0) {
2006 QLIST_REMOVE(l2meta, next_in_flight);
2008 qemu_co_queue_restart_all(&l2meta->dependent_requests);
2010 next = l2meta->next;
2011 g_free(l2meta);
2012 l2meta = next;
2015 qemu_co_mutex_unlock(&s->lock);
2017 qemu_iovec_destroy(&hd_qiov);
2018 qemu_vfree(cluster_data);
2019 trace_qcow2_writev_done_req(qemu_coroutine_self(), ret);
2021 return ret;
2024 static int qcow2_inactivate(BlockDriverState *bs)
2026 BDRVQcow2State *s = bs->opaque;
2027 int ret, result = 0;
2028 Error *local_err = NULL;
2030 qcow2_store_persistent_dirty_bitmaps(bs, &local_err);
2031 if (local_err != NULL) {
2032 result = -EINVAL;
2033 error_report_err(local_err);
2034 error_report("Persistent bitmaps are lost for node '%s'",
2035 bdrv_get_device_or_node_name(bs));
2038 ret = qcow2_cache_flush(bs, s->l2_table_cache);
2039 if (ret) {
2040 result = ret;
2041 error_report("Failed to flush the L2 table cache: %s",
2042 strerror(-ret));
2045 ret = qcow2_cache_flush(bs, s->refcount_block_cache);
2046 if (ret) {
2047 result = ret;
2048 error_report("Failed to flush the refcount block cache: %s",
2049 strerror(-ret));
2052 if (result == 0) {
2053 qcow2_mark_clean(bs);
2056 return result;
2059 static void qcow2_close(BlockDriverState *bs)
2061 BDRVQcow2State *s = bs->opaque;
2062 qemu_vfree(s->l1_table);
2063 /* else pre-write overlap checks in cache_destroy may crash */
2064 s->l1_table = NULL;
2066 if (!(s->flags & BDRV_O_INACTIVE)) {
2067 qcow2_inactivate(bs);
2070 cache_clean_timer_del(bs);
2071 qcow2_cache_destroy(s->l2_table_cache);
2072 qcow2_cache_destroy(s->refcount_block_cache);
2074 qcrypto_block_free(s->crypto);
2075 s->crypto = NULL;
2077 g_free(s->unknown_header_fields);
2078 cleanup_unknown_header_ext(bs);
2080 g_free(s->image_backing_file);
2081 g_free(s->image_backing_format);
2083 g_free(s->cluster_cache);
2084 qemu_vfree(s->cluster_data);
2085 qcow2_refcount_close(bs);
2086 qcow2_free_snapshots(bs);
2089 static void qcow2_invalidate_cache(BlockDriverState *bs, Error **errp)
2091 BDRVQcow2State *s = bs->opaque;
2092 int flags = s->flags;
2093 QCryptoBlock *crypto = NULL;
2094 QDict *options;
2095 Error *local_err = NULL;
2096 int ret;
2099 * Backing files are read-only which makes all of their metadata immutable,
2100 * that means we don't have to worry about reopening them here.
2103 crypto = s->crypto;
2104 s->crypto = NULL;
2106 qcow2_close(bs);
2108 memset(s, 0, sizeof(BDRVQcow2State));
2109 options = qdict_clone_shallow(bs->options);
2111 flags &= ~BDRV_O_INACTIVE;
2112 ret = qcow2_do_open(bs, options, flags, &local_err);
2113 QDECREF(options);
2114 if (local_err) {
2115 error_propagate(errp, local_err);
2116 error_prepend(errp, "Could not reopen qcow2 layer: ");
2117 bs->drv = NULL;
2118 return;
2119 } else if (ret < 0) {
2120 error_setg_errno(errp, -ret, "Could not reopen qcow2 layer");
2121 bs->drv = NULL;
2122 return;
2125 s->crypto = crypto;
2128 static size_t header_ext_add(char *buf, uint32_t magic, const void *s,
2129 size_t len, size_t buflen)
2131 QCowExtension *ext_backing_fmt = (QCowExtension*) buf;
2132 size_t ext_len = sizeof(QCowExtension) + ((len + 7) & ~7);
2134 if (buflen < ext_len) {
2135 return -ENOSPC;
2138 *ext_backing_fmt = (QCowExtension) {
2139 .magic = cpu_to_be32(magic),
2140 .len = cpu_to_be32(len),
2143 if (len) {
2144 memcpy(buf + sizeof(QCowExtension), s, len);
2147 return ext_len;
2151 * Updates the qcow2 header, including the variable length parts of it, i.e.
2152 * the backing file name and all extensions. qcow2 was not designed to allow
2153 * such changes, so if we run out of space (we can only use the first cluster)
2154 * this function may fail.
2156 * Returns 0 on success, -errno in error cases.
2158 int qcow2_update_header(BlockDriverState *bs)
2160 BDRVQcow2State *s = bs->opaque;
2161 QCowHeader *header;
2162 char *buf;
2163 size_t buflen = s->cluster_size;
2164 int ret;
2165 uint64_t total_size;
2166 uint32_t refcount_table_clusters;
2167 size_t header_length;
2168 Qcow2UnknownHeaderExtension *uext;
2170 buf = qemu_blockalign(bs, buflen);
2172 /* Header structure */
2173 header = (QCowHeader*) buf;
2175 if (buflen < sizeof(*header)) {
2176 ret = -ENOSPC;
2177 goto fail;
2180 header_length = sizeof(*header) + s->unknown_header_fields_size;
2181 total_size = bs->total_sectors * BDRV_SECTOR_SIZE;
2182 refcount_table_clusters = s->refcount_table_size >> (s->cluster_bits - 3);
2184 *header = (QCowHeader) {
2185 /* Version 2 fields */
2186 .magic = cpu_to_be32(QCOW_MAGIC),
2187 .version = cpu_to_be32(s->qcow_version),
2188 .backing_file_offset = 0,
2189 .backing_file_size = 0,
2190 .cluster_bits = cpu_to_be32(s->cluster_bits),
2191 .size = cpu_to_be64(total_size),
2192 .crypt_method = cpu_to_be32(s->crypt_method_header),
2193 .l1_size = cpu_to_be32(s->l1_size),
2194 .l1_table_offset = cpu_to_be64(s->l1_table_offset),
2195 .refcount_table_offset = cpu_to_be64(s->refcount_table_offset),
2196 .refcount_table_clusters = cpu_to_be32(refcount_table_clusters),
2197 .nb_snapshots = cpu_to_be32(s->nb_snapshots),
2198 .snapshots_offset = cpu_to_be64(s->snapshots_offset),
2200 /* Version 3 fields */
2201 .incompatible_features = cpu_to_be64(s->incompatible_features),
2202 .compatible_features = cpu_to_be64(s->compatible_features),
2203 .autoclear_features = cpu_to_be64(s->autoclear_features),
2204 .refcount_order = cpu_to_be32(s->refcount_order),
2205 .header_length = cpu_to_be32(header_length),
2208 /* For older versions, write a shorter header */
2209 switch (s->qcow_version) {
2210 case 2:
2211 ret = offsetof(QCowHeader, incompatible_features);
2212 break;
2213 case 3:
2214 ret = sizeof(*header);
2215 break;
2216 default:
2217 ret = -EINVAL;
2218 goto fail;
2221 buf += ret;
2222 buflen -= ret;
2223 memset(buf, 0, buflen);
2225 /* Preserve any unknown field in the header */
2226 if (s->unknown_header_fields_size) {
2227 if (buflen < s->unknown_header_fields_size) {
2228 ret = -ENOSPC;
2229 goto fail;
2232 memcpy(buf, s->unknown_header_fields, s->unknown_header_fields_size);
2233 buf += s->unknown_header_fields_size;
2234 buflen -= s->unknown_header_fields_size;
2237 /* Backing file format header extension */
2238 if (s->image_backing_format) {
2239 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BACKING_FORMAT,
2240 s->image_backing_format,
2241 strlen(s->image_backing_format),
2242 buflen);
2243 if (ret < 0) {
2244 goto fail;
2247 buf += ret;
2248 buflen -= ret;
2251 /* Full disk encryption header pointer extension */
2252 if (s->crypto_header.offset != 0) {
2253 cpu_to_be64s(&s->crypto_header.offset);
2254 cpu_to_be64s(&s->crypto_header.length);
2255 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_CRYPTO_HEADER,
2256 &s->crypto_header, sizeof(s->crypto_header),
2257 buflen);
2258 be64_to_cpus(&s->crypto_header.offset);
2259 be64_to_cpus(&s->crypto_header.length);
2260 if (ret < 0) {
2261 goto fail;
2263 buf += ret;
2264 buflen -= ret;
2267 /* Feature table */
2268 if (s->qcow_version >= 3) {
2269 Qcow2Feature features[] = {
2271 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
2272 .bit = QCOW2_INCOMPAT_DIRTY_BITNR,
2273 .name = "dirty bit",
2276 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
2277 .bit = QCOW2_INCOMPAT_CORRUPT_BITNR,
2278 .name = "corrupt bit",
2281 .type = QCOW2_FEAT_TYPE_COMPATIBLE,
2282 .bit = QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR,
2283 .name = "lazy refcounts",
2287 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_FEATURE_TABLE,
2288 features, sizeof(features), buflen);
2289 if (ret < 0) {
2290 goto fail;
2292 buf += ret;
2293 buflen -= ret;
2296 /* Bitmap extension */
2297 if (s->nb_bitmaps > 0) {
2298 Qcow2BitmapHeaderExt bitmaps_header = {
2299 .nb_bitmaps = cpu_to_be32(s->nb_bitmaps),
2300 .bitmap_directory_size =
2301 cpu_to_be64(s->bitmap_directory_size),
2302 .bitmap_directory_offset =
2303 cpu_to_be64(s->bitmap_directory_offset)
2305 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BITMAPS,
2306 &bitmaps_header, sizeof(bitmaps_header),
2307 buflen);
2308 if (ret < 0) {
2309 goto fail;
2311 buf += ret;
2312 buflen -= ret;
2315 /* Keep unknown header extensions */
2316 QLIST_FOREACH(uext, &s->unknown_header_ext, next) {
2317 ret = header_ext_add(buf, uext->magic, uext->data, uext->len, buflen);
2318 if (ret < 0) {
2319 goto fail;
2322 buf += ret;
2323 buflen -= ret;
2326 /* End of header extensions */
2327 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_END, NULL, 0, buflen);
2328 if (ret < 0) {
2329 goto fail;
2332 buf += ret;
2333 buflen -= ret;
2335 /* Backing file name */
2336 if (s->image_backing_file) {
2337 size_t backing_file_len = strlen(s->image_backing_file);
2339 if (buflen < backing_file_len) {
2340 ret = -ENOSPC;
2341 goto fail;
2344 /* Using strncpy is ok here, since buf is not NUL-terminated. */
2345 strncpy(buf, s->image_backing_file, buflen);
2347 header->backing_file_offset = cpu_to_be64(buf - ((char*) header));
2348 header->backing_file_size = cpu_to_be32(backing_file_len);
2351 /* Write the new header */
2352 ret = bdrv_pwrite(bs->file, 0, header, s->cluster_size);
2353 if (ret < 0) {
2354 goto fail;
2357 ret = 0;
2358 fail:
2359 qemu_vfree(header);
2360 return ret;
2363 static int qcow2_change_backing_file(BlockDriverState *bs,
2364 const char *backing_file, const char *backing_fmt)
2366 BDRVQcow2State *s = bs->opaque;
2368 if (backing_file && strlen(backing_file) > 1023) {
2369 return -EINVAL;
2372 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
2373 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
2375 g_free(s->image_backing_file);
2376 g_free(s->image_backing_format);
2378 s->image_backing_file = backing_file ? g_strdup(bs->backing_file) : NULL;
2379 s->image_backing_format = backing_fmt ? g_strdup(bs->backing_format) : NULL;
2381 return qcow2_update_header(bs);
2384 static int qcow2_crypt_method_from_format(const char *encryptfmt)
2386 if (g_str_equal(encryptfmt, "luks")) {
2387 return QCOW_CRYPT_LUKS;
2388 } else if (g_str_equal(encryptfmt, "aes")) {
2389 return QCOW_CRYPT_AES;
2390 } else {
2391 return -EINVAL;
2395 static int qcow2_set_up_encryption(BlockDriverState *bs, const char *encryptfmt,
2396 QemuOpts *opts, Error **errp)
2398 BDRVQcow2State *s = bs->opaque;
2399 QCryptoBlockCreateOptions *cryptoopts = NULL;
2400 QCryptoBlock *crypto = NULL;
2401 int ret = -EINVAL;
2402 QDict *options, *encryptopts;
2403 int fmt;
2405 options = qemu_opts_to_qdict(opts, NULL);
2406 qdict_extract_subqdict(options, &encryptopts, "encrypt.");
2407 QDECREF(options);
2409 fmt = qcow2_crypt_method_from_format(encryptfmt);
2411 switch (fmt) {
2412 case QCOW_CRYPT_LUKS:
2413 cryptoopts = block_crypto_create_opts_init(
2414 Q_CRYPTO_BLOCK_FORMAT_LUKS, encryptopts, errp);
2415 break;
2416 case QCOW_CRYPT_AES:
2417 cryptoopts = block_crypto_create_opts_init(
2418 Q_CRYPTO_BLOCK_FORMAT_QCOW, encryptopts, errp);
2419 break;
2420 default:
2421 error_setg(errp, "Unknown encryption format '%s'", encryptfmt);
2422 break;
2424 if (!cryptoopts) {
2425 ret = -EINVAL;
2426 goto out;
2428 s->crypt_method_header = fmt;
2430 crypto = qcrypto_block_create(cryptoopts, "encrypt.",
2431 qcow2_crypto_hdr_init_func,
2432 qcow2_crypto_hdr_write_func,
2433 bs, errp);
2434 if (!crypto) {
2435 ret = -EINVAL;
2436 goto out;
2439 ret = qcow2_update_header(bs);
2440 if (ret < 0) {
2441 error_setg_errno(errp, -ret, "Could not write encryption header");
2442 goto out;
2445 out:
2446 QDECREF(encryptopts);
2447 qcrypto_block_free(crypto);
2448 qapi_free_QCryptoBlockCreateOptions(cryptoopts);
2449 return ret;
2453 typedef struct PreallocCo {
2454 BlockDriverState *bs;
2455 uint64_t offset;
2456 uint64_t new_length;
2458 int ret;
2459 } PreallocCo;
2462 * Preallocates metadata structures for data clusters between @offset (in the
2463 * guest disk) and @new_length (which is thus generally the new guest disk
2464 * size).
2466 * Returns: 0 on success, -errno on failure.
2468 static void coroutine_fn preallocate_co(void *opaque)
2470 PreallocCo *params = opaque;
2471 BlockDriverState *bs = params->bs;
2472 uint64_t offset = params->offset;
2473 uint64_t new_length = params->new_length;
2474 BDRVQcow2State *s = bs->opaque;
2475 uint64_t bytes;
2476 uint64_t host_offset = 0;
2477 unsigned int cur_bytes;
2478 int ret;
2479 QCowL2Meta *meta;
2481 qemu_co_mutex_lock(&s->lock);
2483 assert(offset <= new_length);
2484 bytes = new_length - offset;
2486 while (bytes) {
2487 cur_bytes = MIN(bytes, INT_MAX);
2488 ret = qcow2_alloc_cluster_offset(bs, offset, &cur_bytes,
2489 &host_offset, &meta);
2490 if (ret < 0) {
2491 goto done;
2494 while (meta) {
2495 QCowL2Meta *next = meta->next;
2497 ret = qcow2_alloc_cluster_link_l2(bs, meta);
2498 if (ret < 0) {
2499 qcow2_free_any_clusters(bs, meta->alloc_offset,
2500 meta->nb_clusters, QCOW2_DISCARD_NEVER);
2501 goto done;
2504 /* There are no dependent requests, but we need to remove our
2505 * request from the list of in-flight requests */
2506 QLIST_REMOVE(meta, next_in_flight);
2508 g_free(meta);
2509 meta = next;
2512 /* TODO Preallocate data if requested */
2514 bytes -= cur_bytes;
2515 offset += cur_bytes;
2519 * It is expected that the image file is large enough to actually contain
2520 * all of the allocated clusters (otherwise we get failing reads after
2521 * EOF). Extend the image to the last allocated sector.
2523 if (host_offset != 0) {
2524 uint8_t data = 0;
2525 ret = bdrv_pwrite(bs->file, (host_offset + cur_bytes) - 1,
2526 &data, 1);
2527 if (ret < 0) {
2528 goto done;
2532 ret = 0;
2534 done:
2535 qemu_co_mutex_unlock(&s->lock);
2536 params->ret = ret;
2539 static int preallocate(BlockDriverState *bs,
2540 uint64_t offset, uint64_t new_length)
2542 PreallocCo params = {
2543 .bs = bs,
2544 .offset = offset,
2545 .new_length = new_length,
2546 .ret = -EINPROGRESS,
2549 if (qemu_in_coroutine()) {
2550 preallocate_co(&params);
2551 } else {
2552 Coroutine *co = qemu_coroutine_create(preallocate_co, &params);
2553 bdrv_coroutine_enter(bs, co);
2554 BDRV_POLL_WHILE(bs, params.ret == -EINPROGRESS);
2556 return params.ret;
2559 /* qcow2_refcount_metadata_size:
2560 * @clusters: number of clusters to refcount (including data and L1/L2 tables)
2561 * @cluster_size: size of a cluster, in bytes
2562 * @refcount_order: refcount bits power-of-2 exponent
2563 * @generous_increase: allow for the refcount table to be 1.5x as large as it
2564 * needs to be
2566 * Returns: Number of bytes required for refcount blocks and table metadata.
2568 int64_t qcow2_refcount_metadata_size(int64_t clusters, size_t cluster_size,
2569 int refcount_order, bool generous_increase,
2570 uint64_t *refblock_count)
2573 * Every host cluster is reference-counted, including metadata (even
2574 * refcount metadata is recursively included).
2576 * An accurate formula for the size of refcount metadata size is difficult
2577 * to derive. An easier method of calculation is finding the fixed point
2578 * where no further refcount blocks or table clusters are required to
2579 * reference count every cluster.
2581 int64_t blocks_per_table_cluster = cluster_size / sizeof(uint64_t);
2582 int64_t refcounts_per_block = cluster_size * 8 / (1 << refcount_order);
2583 int64_t table = 0; /* number of refcount table clusters */
2584 int64_t blocks = 0; /* number of refcount block clusters */
2585 int64_t last;
2586 int64_t n = 0;
2588 do {
2589 last = n;
2590 blocks = DIV_ROUND_UP(clusters + table + blocks, refcounts_per_block);
2591 table = DIV_ROUND_UP(blocks, blocks_per_table_cluster);
2592 n = clusters + blocks + table;
2594 if (n == last && generous_increase) {
2595 clusters += DIV_ROUND_UP(table, 2);
2596 n = 0; /* force another loop */
2597 generous_increase = false;
2599 } while (n != last);
2601 if (refblock_count) {
2602 *refblock_count = blocks;
2605 return (blocks + table) * cluster_size;
2609 * qcow2_calc_prealloc_size:
2610 * @total_size: virtual disk size in bytes
2611 * @cluster_size: cluster size in bytes
2612 * @refcount_order: refcount bits power-of-2 exponent
2614 * Returns: Total number of bytes required for the fully allocated image
2615 * (including metadata).
2617 static int64_t qcow2_calc_prealloc_size(int64_t total_size,
2618 size_t cluster_size,
2619 int refcount_order)
2621 int64_t meta_size = 0;
2622 uint64_t nl1e, nl2e;
2623 int64_t aligned_total_size = align_offset(total_size, cluster_size);
2625 /* header: 1 cluster */
2626 meta_size += cluster_size;
2628 /* total size of L2 tables */
2629 nl2e = aligned_total_size / cluster_size;
2630 nl2e = align_offset(nl2e, cluster_size / sizeof(uint64_t));
2631 meta_size += nl2e * sizeof(uint64_t);
2633 /* total size of L1 tables */
2634 nl1e = nl2e * sizeof(uint64_t) / cluster_size;
2635 nl1e = align_offset(nl1e, cluster_size / sizeof(uint64_t));
2636 meta_size += nl1e * sizeof(uint64_t);
2638 /* total size of refcount table and blocks */
2639 meta_size += qcow2_refcount_metadata_size(
2640 (meta_size + aligned_total_size) / cluster_size,
2641 cluster_size, refcount_order, false, NULL);
2643 return meta_size + aligned_total_size;
2646 static size_t qcow2_opt_get_cluster_size_del(QemuOpts *opts, Error **errp)
2648 size_t cluster_size;
2649 int cluster_bits;
2651 cluster_size = qemu_opt_get_size_del(opts, BLOCK_OPT_CLUSTER_SIZE,
2652 DEFAULT_CLUSTER_SIZE);
2653 cluster_bits = ctz32(cluster_size);
2654 if (cluster_bits < MIN_CLUSTER_BITS || cluster_bits > MAX_CLUSTER_BITS ||
2655 (1 << cluster_bits) != cluster_size)
2657 error_setg(errp, "Cluster size must be a power of two between %d and "
2658 "%dk", 1 << MIN_CLUSTER_BITS, 1 << (MAX_CLUSTER_BITS - 10));
2659 return 0;
2661 return cluster_size;
2664 static int qcow2_opt_get_version_del(QemuOpts *opts, Error **errp)
2666 char *buf;
2667 int ret;
2669 buf = qemu_opt_get_del(opts, BLOCK_OPT_COMPAT_LEVEL);
2670 if (!buf) {
2671 ret = 3; /* default */
2672 } else if (!strcmp(buf, "0.10")) {
2673 ret = 2;
2674 } else if (!strcmp(buf, "1.1")) {
2675 ret = 3;
2676 } else {
2677 error_setg(errp, "Invalid compatibility level: '%s'", buf);
2678 ret = -EINVAL;
2680 g_free(buf);
2681 return ret;
2684 static uint64_t qcow2_opt_get_refcount_bits_del(QemuOpts *opts, int version,
2685 Error **errp)
2687 uint64_t refcount_bits;
2689 refcount_bits = qemu_opt_get_number_del(opts, BLOCK_OPT_REFCOUNT_BITS, 16);
2690 if (refcount_bits > 64 || !is_power_of_2(refcount_bits)) {
2691 error_setg(errp, "Refcount width must be a power of two and may not "
2692 "exceed 64 bits");
2693 return 0;
2696 if (version < 3 && refcount_bits != 16) {
2697 error_setg(errp, "Different refcount widths than 16 bits require "
2698 "compatibility level 1.1 or above (use compat=1.1 or "
2699 "greater)");
2700 return 0;
2703 return refcount_bits;
2706 static int qcow2_create2(const char *filename, int64_t total_size,
2707 const char *backing_file, const char *backing_format,
2708 int flags, size_t cluster_size, PreallocMode prealloc,
2709 QemuOpts *opts, int version, int refcount_order,
2710 const char *encryptfmt, Error **errp)
2712 QDict *options;
2715 * Open the image file and write a minimal qcow2 header.
2717 * We keep things simple and start with a zero-sized image. We also
2718 * do without refcount blocks or a L1 table for now. We'll fix the
2719 * inconsistency later.
2721 * We do need a refcount table because growing the refcount table means
2722 * allocating two new refcount blocks - the seconds of which would be at
2723 * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
2724 * size for any qcow2 image.
2726 BlockBackend *blk;
2727 QCowHeader *header;
2728 uint64_t* refcount_table;
2729 Error *local_err = NULL;
2730 int ret;
2732 if (prealloc == PREALLOC_MODE_FULL || prealloc == PREALLOC_MODE_FALLOC) {
2733 int64_t prealloc_size =
2734 qcow2_calc_prealloc_size(total_size, cluster_size, refcount_order);
2735 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, prealloc_size, &error_abort);
2736 qemu_opt_set(opts, BLOCK_OPT_PREALLOC, PreallocMode_str(prealloc),
2737 &error_abort);
2740 ret = bdrv_create_file(filename, opts, &local_err);
2741 if (ret < 0) {
2742 error_propagate(errp, local_err);
2743 return ret;
2746 blk = blk_new_open(filename, NULL, NULL,
2747 BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_PROTOCOL,
2748 &local_err);
2749 if (blk == NULL) {
2750 error_propagate(errp, local_err);
2751 return -EIO;
2754 blk_set_allow_write_beyond_eof(blk, true);
2756 /* Write the header */
2757 QEMU_BUILD_BUG_ON((1 << MIN_CLUSTER_BITS) < sizeof(*header));
2758 header = g_malloc0(cluster_size);
2759 *header = (QCowHeader) {
2760 .magic = cpu_to_be32(QCOW_MAGIC),
2761 .version = cpu_to_be32(version),
2762 .cluster_bits = cpu_to_be32(ctz32(cluster_size)),
2763 .size = cpu_to_be64(0),
2764 .l1_table_offset = cpu_to_be64(0),
2765 .l1_size = cpu_to_be32(0),
2766 .refcount_table_offset = cpu_to_be64(cluster_size),
2767 .refcount_table_clusters = cpu_to_be32(1),
2768 .refcount_order = cpu_to_be32(refcount_order),
2769 .header_length = cpu_to_be32(sizeof(*header)),
2772 /* We'll update this to correct value later */
2773 header->crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
2775 if (flags & BLOCK_FLAG_LAZY_REFCOUNTS) {
2776 header->compatible_features |=
2777 cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS);
2780 ret = blk_pwrite(blk, 0, header, cluster_size, 0);
2781 g_free(header);
2782 if (ret < 0) {
2783 error_setg_errno(errp, -ret, "Could not write qcow2 header");
2784 goto out;
2787 /* Write a refcount table with one refcount block */
2788 refcount_table = g_malloc0(2 * cluster_size);
2789 refcount_table[0] = cpu_to_be64(2 * cluster_size);
2790 ret = blk_pwrite(blk, cluster_size, refcount_table, 2 * cluster_size, 0);
2791 g_free(refcount_table);
2793 if (ret < 0) {
2794 error_setg_errno(errp, -ret, "Could not write refcount table");
2795 goto out;
2798 blk_unref(blk);
2799 blk = NULL;
2802 * And now open the image and make it consistent first (i.e. increase the
2803 * refcount of the cluster that is occupied by the header and the refcount
2804 * table)
2806 options = qdict_new();
2807 qdict_put_str(options, "driver", "qcow2");
2808 blk = blk_new_open(filename, NULL, options,
2809 BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_NO_FLUSH,
2810 &local_err);
2811 if (blk == NULL) {
2812 error_propagate(errp, local_err);
2813 ret = -EIO;
2814 goto out;
2817 ret = qcow2_alloc_clusters(blk_bs(blk), 3 * cluster_size);
2818 if (ret < 0) {
2819 error_setg_errno(errp, -ret, "Could not allocate clusters for qcow2 "
2820 "header and refcount table");
2821 goto out;
2823 } else if (ret != 0) {
2824 error_report("Huh, first cluster in empty image is already in use?");
2825 abort();
2828 /* Create a full header (including things like feature table) */
2829 ret = qcow2_update_header(blk_bs(blk));
2830 if (ret < 0) {
2831 error_setg_errno(errp, -ret, "Could not update qcow2 header");
2832 goto out;
2835 /* Okay, now that we have a valid image, let's give it the right size */
2836 ret = blk_truncate(blk, total_size, PREALLOC_MODE_OFF, errp);
2837 if (ret < 0) {
2838 error_prepend(errp, "Could not resize image: ");
2839 goto out;
2842 /* Want a backing file? There you go.*/
2843 if (backing_file) {
2844 ret = bdrv_change_backing_file(blk_bs(blk), backing_file, backing_format);
2845 if (ret < 0) {
2846 error_setg_errno(errp, -ret, "Could not assign backing file '%s' "
2847 "with format '%s'", backing_file, backing_format);
2848 goto out;
2852 /* Want encryption? There you go. */
2853 if (encryptfmt) {
2854 ret = qcow2_set_up_encryption(blk_bs(blk), encryptfmt, opts, errp);
2855 if (ret < 0) {
2856 goto out;
2860 /* And if we're supposed to preallocate metadata, do that now */
2861 if (prealloc != PREALLOC_MODE_OFF) {
2862 ret = preallocate(blk_bs(blk), 0, total_size);
2863 if (ret < 0) {
2864 error_setg_errno(errp, -ret, "Could not preallocate metadata");
2865 goto out;
2869 blk_unref(blk);
2870 blk = NULL;
2872 /* Reopen the image without BDRV_O_NO_FLUSH to flush it before returning.
2873 * Using BDRV_O_NO_IO, since encryption is now setup we don't want to
2874 * have to setup decryption context. We're not doing any I/O on the top
2875 * level BlockDriverState, only lower layers, where BDRV_O_NO_IO does
2876 * not have effect.
2878 options = qdict_new();
2879 qdict_put_str(options, "driver", "qcow2");
2880 blk = blk_new_open(filename, NULL, options,
2881 BDRV_O_RDWR | BDRV_O_NO_BACKING | BDRV_O_NO_IO,
2882 &local_err);
2883 if (blk == NULL) {
2884 error_propagate(errp, local_err);
2885 ret = -EIO;
2886 goto out;
2889 ret = 0;
2890 out:
2891 if (blk) {
2892 blk_unref(blk);
2894 return ret;
2897 static int qcow2_create(const char *filename, QemuOpts *opts, Error **errp)
2899 char *backing_file = NULL;
2900 char *backing_fmt = NULL;
2901 char *buf = NULL;
2902 uint64_t size = 0;
2903 int flags = 0;
2904 size_t cluster_size = DEFAULT_CLUSTER_SIZE;
2905 PreallocMode prealloc;
2906 int version;
2907 uint64_t refcount_bits;
2908 int refcount_order;
2909 char *encryptfmt = NULL;
2910 Error *local_err = NULL;
2911 int ret;
2913 /* Read out options */
2914 size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
2915 BDRV_SECTOR_SIZE);
2916 backing_file = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
2917 backing_fmt = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FMT);
2918 encryptfmt = qemu_opt_get_del(opts, BLOCK_OPT_ENCRYPT_FORMAT);
2919 if (encryptfmt) {
2920 if (qemu_opt_get(opts, BLOCK_OPT_ENCRYPT)) {
2921 error_setg(errp, "Options " BLOCK_OPT_ENCRYPT " and "
2922 BLOCK_OPT_ENCRYPT_FORMAT " are mutually exclusive");
2923 ret = -EINVAL;
2924 goto finish;
2926 } else if (qemu_opt_get_bool_del(opts, BLOCK_OPT_ENCRYPT, false)) {
2927 encryptfmt = g_strdup("aes");
2929 cluster_size = qcow2_opt_get_cluster_size_del(opts, &local_err);
2930 if (local_err) {
2931 error_propagate(errp, local_err);
2932 ret = -EINVAL;
2933 goto finish;
2935 buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
2936 prealloc = qapi_enum_parse(&PreallocMode_lookup, buf,
2937 PREALLOC_MODE_OFF, &local_err);
2938 if (local_err) {
2939 error_propagate(errp, local_err);
2940 ret = -EINVAL;
2941 goto finish;
2944 version = qcow2_opt_get_version_del(opts, &local_err);
2945 if (local_err) {
2946 error_propagate(errp, local_err);
2947 ret = -EINVAL;
2948 goto finish;
2951 if (qemu_opt_get_bool_del(opts, BLOCK_OPT_LAZY_REFCOUNTS, false)) {
2952 flags |= BLOCK_FLAG_LAZY_REFCOUNTS;
2955 if (backing_file && prealloc != PREALLOC_MODE_OFF) {
2956 error_setg(errp, "Backing file and preallocation cannot be used at "
2957 "the same time");
2958 ret = -EINVAL;
2959 goto finish;
2962 if (version < 3 && (flags & BLOCK_FLAG_LAZY_REFCOUNTS)) {
2963 error_setg(errp, "Lazy refcounts only supported with compatibility "
2964 "level 1.1 and above (use compat=1.1 or greater)");
2965 ret = -EINVAL;
2966 goto finish;
2969 refcount_bits = qcow2_opt_get_refcount_bits_del(opts, version, &local_err);
2970 if (local_err) {
2971 error_propagate(errp, local_err);
2972 ret = -EINVAL;
2973 goto finish;
2976 refcount_order = ctz32(refcount_bits);
2978 ret = qcow2_create2(filename, size, backing_file, backing_fmt, flags,
2979 cluster_size, prealloc, opts, version, refcount_order,
2980 encryptfmt, &local_err);
2981 error_propagate(errp, local_err);
2983 finish:
2984 g_free(backing_file);
2985 g_free(backing_fmt);
2986 g_free(encryptfmt);
2987 g_free(buf);
2988 return ret;
2992 static bool is_zero(BlockDriverState *bs, int64_t offset, int64_t bytes)
2994 int64_t nr;
2995 int res;
2997 /* Clamp to image length, before checking status of underlying sectors */
2998 if (offset + bytes > bs->total_sectors * BDRV_SECTOR_SIZE) {
2999 bytes = bs->total_sectors * BDRV_SECTOR_SIZE - offset;
3002 if (!bytes) {
3003 return true;
3005 res = bdrv_block_status_above(bs, NULL, offset, bytes, &nr, NULL, NULL);
3006 return res >= 0 && (res & BDRV_BLOCK_ZERO) && nr == bytes;
3009 static coroutine_fn int qcow2_co_pwrite_zeroes(BlockDriverState *bs,
3010 int64_t offset, int bytes, BdrvRequestFlags flags)
3012 int ret;
3013 BDRVQcow2State *s = bs->opaque;
3015 uint32_t head = offset % s->cluster_size;
3016 uint32_t tail = (offset + bytes) % s->cluster_size;
3018 trace_qcow2_pwrite_zeroes_start_req(qemu_coroutine_self(), offset, bytes);
3019 if (offset + bytes == bs->total_sectors * BDRV_SECTOR_SIZE) {
3020 tail = 0;
3023 if (head || tail) {
3024 uint64_t off;
3025 unsigned int nr;
3027 assert(head + bytes <= s->cluster_size);
3029 /* check whether remainder of cluster already reads as zero */
3030 if (!(is_zero(bs, offset - head, head) &&
3031 is_zero(bs, offset + bytes,
3032 tail ? s->cluster_size - tail : 0))) {
3033 return -ENOTSUP;
3036 qemu_co_mutex_lock(&s->lock);
3037 /* We can have new write after previous check */
3038 offset = QEMU_ALIGN_DOWN(offset, s->cluster_size);
3039 bytes = s->cluster_size;
3040 nr = s->cluster_size;
3041 ret = qcow2_get_cluster_offset(bs, offset, &nr, &off);
3042 if (ret != QCOW2_CLUSTER_UNALLOCATED &&
3043 ret != QCOW2_CLUSTER_ZERO_PLAIN &&
3044 ret != QCOW2_CLUSTER_ZERO_ALLOC) {
3045 qemu_co_mutex_unlock(&s->lock);
3046 return -ENOTSUP;
3048 } else {
3049 qemu_co_mutex_lock(&s->lock);
3052 trace_qcow2_pwrite_zeroes(qemu_coroutine_self(), offset, bytes);
3054 /* Whatever is left can use real zero clusters */
3055 ret = qcow2_cluster_zeroize(bs, offset, bytes, flags);
3056 qemu_co_mutex_unlock(&s->lock);
3058 return ret;
3061 static coroutine_fn int qcow2_co_pdiscard(BlockDriverState *bs,
3062 int64_t offset, int bytes)
3064 int ret;
3065 BDRVQcow2State *s = bs->opaque;
3067 if (!QEMU_IS_ALIGNED(offset | bytes, s->cluster_size)) {
3068 assert(bytes < s->cluster_size);
3069 /* Ignore partial clusters, except for the special case of the
3070 * complete partial cluster at the end of an unaligned file */
3071 if (!QEMU_IS_ALIGNED(offset, s->cluster_size) ||
3072 offset + bytes != bs->total_sectors * BDRV_SECTOR_SIZE) {
3073 return -ENOTSUP;
3077 qemu_co_mutex_lock(&s->lock);
3078 ret = qcow2_cluster_discard(bs, offset, bytes, QCOW2_DISCARD_REQUEST,
3079 false);
3080 qemu_co_mutex_unlock(&s->lock);
3081 return ret;
3084 static int qcow2_truncate(BlockDriverState *bs, int64_t offset,
3085 PreallocMode prealloc, Error **errp)
3087 BDRVQcow2State *s = bs->opaque;
3088 uint64_t old_length;
3089 int64_t new_l1_size;
3090 int ret;
3092 if (prealloc != PREALLOC_MODE_OFF && prealloc != PREALLOC_MODE_METADATA &&
3093 prealloc != PREALLOC_MODE_FALLOC && prealloc != PREALLOC_MODE_FULL)
3095 error_setg(errp, "Unsupported preallocation mode '%s'",
3096 PreallocMode_str(prealloc));
3097 return -ENOTSUP;
3100 if (offset & 511) {
3101 error_setg(errp, "The new size must be a multiple of 512");
3102 return -EINVAL;
3105 /* cannot proceed if image has snapshots */
3106 if (s->nb_snapshots) {
3107 error_setg(errp, "Can't resize an image which has snapshots");
3108 return -ENOTSUP;
3111 /* cannot proceed if image has bitmaps */
3112 if (s->nb_bitmaps) {
3113 /* TODO: resize bitmaps in the image */
3114 error_setg(errp, "Can't resize an image which has bitmaps");
3115 return -ENOTSUP;
3118 old_length = bs->total_sectors * 512;
3119 new_l1_size = size_to_l1(s, offset);
3121 if (offset < old_length) {
3122 int64_t last_cluster, old_file_size;
3123 if (prealloc != PREALLOC_MODE_OFF) {
3124 error_setg(errp,
3125 "Preallocation can't be used for shrinking an image");
3126 return -EINVAL;
3129 ret = qcow2_cluster_discard(bs, ROUND_UP(offset, s->cluster_size),
3130 old_length - ROUND_UP(offset,
3131 s->cluster_size),
3132 QCOW2_DISCARD_ALWAYS, true);
3133 if (ret < 0) {
3134 error_setg_errno(errp, -ret, "Failed to discard cropped clusters");
3135 return ret;
3138 ret = qcow2_shrink_l1_table(bs, new_l1_size);
3139 if (ret < 0) {
3140 error_setg_errno(errp, -ret,
3141 "Failed to reduce the number of L2 tables");
3142 return ret;
3145 ret = qcow2_shrink_reftable(bs);
3146 if (ret < 0) {
3147 error_setg_errno(errp, -ret,
3148 "Failed to discard unused refblocks");
3149 return ret;
3152 old_file_size = bdrv_getlength(bs->file->bs);
3153 if (old_file_size < 0) {
3154 error_setg_errno(errp, -old_file_size,
3155 "Failed to inquire current file length");
3156 return old_file_size;
3158 last_cluster = qcow2_get_last_cluster(bs, old_file_size);
3159 if (last_cluster < 0) {
3160 error_setg_errno(errp, -last_cluster,
3161 "Failed to find the last cluster");
3162 return last_cluster;
3164 if ((last_cluster + 1) * s->cluster_size < old_file_size) {
3165 Error *local_err = NULL;
3167 bdrv_truncate(bs->file, (last_cluster + 1) * s->cluster_size,
3168 PREALLOC_MODE_OFF, &local_err);
3169 if (local_err) {
3170 warn_reportf_err(local_err,
3171 "Failed to truncate the tail of the image: ");
3174 } else {
3175 ret = qcow2_grow_l1_table(bs, new_l1_size, true);
3176 if (ret < 0) {
3177 error_setg_errno(errp, -ret, "Failed to grow the L1 table");
3178 return ret;
3182 switch (prealloc) {
3183 case PREALLOC_MODE_OFF:
3184 break;
3186 case PREALLOC_MODE_METADATA:
3187 ret = preallocate(bs, old_length, offset);
3188 if (ret < 0) {
3189 error_setg_errno(errp, -ret, "Preallocation failed");
3190 return ret;
3192 break;
3194 case PREALLOC_MODE_FALLOC:
3195 case PREALLOC_MODE_FULL:
3197 int64_t allocation_start, host_offset, guest_offset;
3198 int64_t clusters_allocated;
3199 int64_t old_file_size, new_file_size;
3200 uint64_t nb_new_data_clusters, nb_new_l2_tables;
3202 old_file_size = bdrv_getlength(bs->file->bs);
3203 if (old_file_size < 0) {
3204 error_setg_errno(errp, -old_file_size,
3205 "Failed to inquire current file length");
3206 return old_file_size;
3208 old_file_size = ROUND_UP(old_file_size, s->cluster_size);
3210 nb_new_data_clusters = DIV_ROUND_UP(offset - old_length,
3211 s->cluster_size);
3213 /* This is an overestimation; we will not actually allocate space for
3214 * these in the file but just make sure the new refcount structures are
3215 * able to cover them so we will not have to allocate new refblocks
3216 * while entering the data blocks in the potentially new L2 tables.
3217 * (We do not actually care where the L2 tables are placed. Maybe they
3218 * are already allocated or they can be placed somewhere before
3219 * @old_file_size. It does not matter because they will be fully
3220 * allocated automatically, so they do not need to be covered by the
3221 * preallocation. All that matters is that we will not have to allocate
3222 * new refcount structures for them.) */
3223 nb_new_l2_tables = DIV_ROUND_UP(nb_new_data_clusters,
3224 s->cluster_size / sizeof(uint64_t));
3225 /* The cluster range may not be aligned to L2 boundaries, so add one L2
3226 * table for a potential head/tail */
3227 nb_new_l2_tables++;
3229 allocation_start = qcow2_refcount_area(bs, old_file_size,
3230 nb_new_data_clusters +
3231 nb_new_l2_tables,
3232 true, 0, 0);
3233 if (allocation_start < 0) {
3234 error_setg_errno(errp, -allocation_start,
3235 "Failed to resize refcount structures");
3236 return allocation_start;
3239 clusters_allocated = qcow2_alloc_clusters_at(bs, allocation_start,
3240 nb_new_data_clusters);
3241 if (clusters_allocated < 0) {
3242 error_setg_errno(errp, -clusters_allocated,
3243 "Failed to allocate data clusters");
3244 return -clusters_allocated;
3247 assert(clusters_allocated == nb_new_data_clusters);
3249 /* Allocate the data area */
3250 new_file_size = allocation_start +
3251 nb_new_data_clusters * s->cluster_size;
3252 ret = bdrv_truncate(bs->file, new_file_size, prealloc, errp);
3253 if (ret < 0) {
3254 error_prepend(errp, "Failed to resize underlying file: ");
3255 qcow2_free_clusters(bs, allocation_start,
3256 nb_new_data_clusters * s->cluster_size,
3257 QCOW2_DISCARD_OTHER);
3258 return ret;
3261 /* Create the necessary L2 entries */
3262 host_offset = allocation_start;
3263 guest_offset = old_length;
3264 while (nb_new_data_clusters) {
3265 int64_t guest_cluster = guest_offset >> s->cluster_bits;
3266 int64_t nb_clusters = MIN(nb_new_data_clusters,
3267 s->l2_size - guest_cluster % s->l2_size);
3268 QCowL2Meta allocation = {
3269 .offset = guest_offset,
3270 .alloc_offset = host_offset,
3271 .nb_clusters = nb_clusters,
3273 qemu_co_queue_init(&allocation.dependent_requests);
3275 ret = qcow2_alloc_cluster_link_l2(bs, &allocation);
3276 if (ret < 0) {
3277 error_setg_errno(errp, -ret, "Failed to update L2 tables");
3278 qcow2_free_clusters(bs, host_offset,
3279 nb_new_data_clusters * s->cluster_size,
3280 QCOW2_DISCARD_OTHER);
3281 return ret;
3284 guest_offset += nb_clusters * s->cluster_size;
3285 host_offset += nb_clusters * s->cluster_size;
3286 nb_new_data_clusters -= nb_clusters;
3288 break;
3291 default:
3292 g_assert_not_reached();
3295 if (prealloc != PREALLOC_MODE_OFF) {
3296 /* Flush metadata before actually changing the image size */
3297 ret = bdrv_flush(bs);
3298 if (ret < 0) {
3299 error_setg_errno(errp, -ret,
3300 "Failed to flush the preallocated area to disk");
3301 return ret;
3305 /* write updated header.size */
3306 offset = cpu_to_be64(offset);
3307 ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, size),
3308 &offset, sizeof(uint64_t));
3309 if (ret < 0) {
3310 error_setg_errno(errp, -ret, "Failed to update the image size");
3311 return ret;
3314 s->l1_vm_state_index = new_l1_size;
3315 return 0;
3318 /* XXX: put compressed sectors first, then all the cluster aligned
3319 tables to avoid losing bytes in alignment */
3320 static coroutine_fn int
3321 qcow2_co_pwritev_compressed(BlockDriverState *bs, uint64_t offset,
3322 uint64_t bytes, QEMUIOVector *qiov)
3324 BDRVQcow2State *s = bs->opaque;
3325 QEMUIOVector hd_qiov;
3326 struct iovec iov;
3327 z_stream strm;
3328 int ret, out_len;
3329 uint8_t *buf, *out_buf;
3330 int64_t cluster_offset;
3332 if (bytes == 0) {
3333 /* align end of file to a sector boundary to ease reading with
3334 sector based I/Os */
3335 cluster_offset = bdrv_getlength(bs->file->bs);
3336 if (cluster_offset < 0) {
3337 return cluster_offset;
3339 return bdrv_truncate(bs->file, cluster_offset, PREALLOC_MODE_OFF, NULL);
3342 if (offset_into_cluster(s, offset)) {
3343 return -EINVAL;
3346 buf = qemu_blockalign(bs, s->cluster_size);
3347 if (bytes != s->cluster_size) {
3348 if (bytes > s->cluster_size ||
3349 offset + bytes != bs->total_sectors << BDRV_SECTOR_BITS)
3351 qemu_vfree(buf);
3352 return -EINVAL;
3354 /* Zero-pad last write if image size is not cluster aligned */
3355 memset(buf + bytes, 0, s->cluster_size - bytes);
3357 qemu_iovec_to_buf(qiov, 0, buf, bytes);
3359 out_buf = g_malloc(s->cluster_size);
3361 /* best compression, small window, no zlib header */
3362 memset(&strm, 0, sizeof(strm));
3363 ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
3364 Z_DEFLATED, -12,
3365 9, Z_DEFAULT_STRATEGY);
3366 if (ret != 0) {
3367 ret = -EINVAL;
3368 goto fail;
3371 strm.avail_in = s->cluster_size;
3372 strm.next_in = (uint8_t *)buf;
3373 strm.avail_out = s->cluster_size;
3374 strm.next_out = out_buf;
3376 ret = deflate(&strm, Z_FINISH);
3377 if (ret != Z_STREAM_END && ret != Z_OK) {
3378 deflateEnd(&strm);
3379 ret = -EINVAL;
3380 goto fail;
3382 out_len = strm.next_out - out_buf;
3384 deflateEnd(&strm);
3386 if (ret != Z_STREAM_END || out_len >= s->cluster_size) {
3387 /* could not compress: write normal cluster */
3388 ret = qcow2_co_pwritev(bs, offset, bytes, qiov, 0);
3389 if (ret < 0) {
3390 goto fail;
3392 goto success;
3395 qemu_co_mutex_lock(&s->lock);
3396 cluster_offset =
3397 qcow2_alloc_compressed_cluster_offset(bs, offset, out_len);
3398 if (!cluster_offset) {
3399 qemu_co_mutex_unlock(&s->lock);
3400 ret = -EIO;
3401 goto fail;
3403 cluster_offset &= s->cluster_offset_mask;
3405 ret = qcow2_pre_write_overlap_check(bs, 0, cluster_offset, out_len);
3406 qemu_co_mutex_unlock(&s->lock);
3407 if (ret < 0) {
3408 goto fail;
3411 iov = (struct iovec) {
3412 .iov_base = out_buf,
3413 .iov_len = out_len,
3415 qemu_iovec_init_external(&hd_qiov, &iov, 1);
3417 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_COMPRESSED);
3418 ret = bdrv_co_pwritev(bs->file, cluster_offset, out_len, &hd_qiov, 0);
3419 if (ret < 0) {
3420 goto fail;
3422 success:
3423 ret = 0;
3424 fail:
3425 qemu_vfree(buf);
3426 g_free(out_buf);
3427 return ret;
3430 static int make_completely_empty(BlockDriverState *bs)
3432 BDRVQcow2State *s = bs->opaque;
3433 Error *local_err = NULL;
3434 int ret, l1_clusters;
3435 int64_t offset;
3436 uint64_t *new_reftable = NULL;
3437 uint64_t rt_entry, l1_size2;
3438 struct {
3439 uint64_t l1_offset;
3440 uint64_t reftable_offset;
3441 uint32_t reftable_clusters;
3442 } QEMU_PACKED l1_ofs_rt_ofs_cls;
3444 ret = qcow2_cache_empty(bs, s->l2_table_cache);
3445 if (ret < 0) {
3446 goto fail;
3449 ret = qcow2_cache_empty(bs, s->refcount_block_cache);
3450 if (ret < 0) {
3451 goto fail;
3454 /* Refcounts will be broken utterly */
3455 ret = qcow2_mark_dirty(bs);
3456 if (ret < 0) {
3457 goto fail;
3460 BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
3462 l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / sizeof(uint64_t));
3463 l1_size2 = (uint64_t)s->l1_size * sizeof(uint64_t);
3465 /* After this call, neither the in-memory nor the on-disk refcount
3466 * information accurately describe the actual references */
3468 ret = bdrv_pwrite_zeroes(bs->file, s->l1_table_offset,
3469 l1_clusters * s->cluster_size, 0);
3470 if (ret < 0) {
3471 goto fail_broken_refcounts;
3473 memset(s->l1_table, 0, l1_size2);
3475 BLKDBG_EVENT(bs->file, BLKDBG_EMPTY_IMAGE_PREPARE);
3477 /* Overwrite enough clusters at the beginning of the sectors to place
3478 * the refcount table, a refcount block and the L1 table in; this may
3479 * overwrite parts of the existing refcount and L1 table, which is not
3480 * an issue because the dirty flag is set, complete data loss is in fact
3481 * desired and partial data loss is consequently fine as well */
3482 ret = bdrv_pwrite_zeroes(bs->file, s->cluster_size,
3483 (2 + l1_clusters) * s->cluster_size, 0);
3484 /* This call (even if it failed overall) may have overwritten on-disk
3485 * refcount structures; in that case, the in-memory refcount information
3486 * will probably differ from the on-disk information which makes the BDS
3487 * unusable */
3488 if (ret < 0) {
3489 goto fail_broken_refcounts;
3492 BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
3493 BLKDBG_EVENT(bs->file, BLKDBG_REFTABLE_UPDATE);
3495 /* "Create" an empty reftable (one cluster) directly after the image
3496 * header and an empty L1 table three clusters after the image header;
3497 * the cluster between those two will be used as the first refblock */
3498 l1_ofs_rt_ofs_cls.l1_offset = cpu_to_be64(3 * s->cluster_size);
3499 l1_ofs_rt_ofs_cls.reftable_offset = cpu_to_be64(s->cluster_size);
3500 l1_ofs_rt_ofs_cls.reftable_clusters = cpu_to_be32(1);
3501 ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, l1_table_offset),
3502 &l1_ofs_rt_ofs_cls, sizeof(l1_ofs_rt_ofs_cls));
3503 if (ret < 0) {
3504 goto fail_broken_refcounts;
3507 s->l1_table_offset = 3 * s->cluster_size;
3509 new_reftable = g_try_new0(uint64_t, s->cluster_size / sizeof(uint64_t));
3510 if (!new_reftable) {
3511 ret = -ENOMEM;
3512 goto fail_broken_refcounts;
3515 s->refcount_table_offset = s->cluster_size;
3516 s->refcount_table_size = s->cluster_size / sizeof(uint64_t);
3517 s->max_refcount_table_index = 0;
3519 g_free(s->refcount_table);
3520 s->refcount_table = new_reftable;
3521 new_reftable = NULL;
3523 /* Now the in-memory refcount information again corresponds to the on-disk
3524 * information (reftable is empty and no refblocks (the refblock cache is
3525 * empty)); however, this means some clusters (e.g. the image header) are
3526 * referenced, but not refcounted, but the normal qcow2 code assumes that
3527 * the in-memory information is always correct */
3529 BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_ALLOC);
3531 /* Enter the first refblock into the reftable */
3532 rt_entry = cpu_to_be64(2 * s->cluster_size);
3533 ret = bdrv_pwrite_sync(bs->file, s->cluster_size,
3534 &rt_entry, sizeof(rt_entry));
3535 if (ret < 0) {
3536 goto fail_broken_refcounts;
3538 s->refcount_table[0] = 2 * s->cluster_size;
3540 s->free_cluster_index = 0;
3541 assert(3 + l1_clusters <= s->refcount_block_size);
3542 offset = qcow2_alloc_clusters(bs, 3 * s->cluster_size + l1_size2);
3543 if (offset < 0) {
3544 ret = offset;
3545 goto fail_broken_refcounts;
3546 } else if (offset > 0) {
3547 error_report("First cluster in emptied image is in use");
3548 abort();
3551 /* Now finally the in-memory information corresponds to the on-disk
3552 * structures and is correct */
3553 ret = qcow2_mark_clean(bs);
3554 if (ret < 0) {
3555 goto fail;
3558 ret = bdrv_truncate(bs->file, (3 + l1_clusters) * s->cluster_size,
3559 PREALLOC_MODE_OFF, &local_err);
3560 if (ret < 0) {
3561 error_report_err(local_err);
3562 goto fail;
3565 return 0;
3567 fail_broken_refcounts:
3568 /* The BDS is unusable at this point. If we wanted to make it usable, we
3569 * would have to call qcow2_refcount_close(), qcow2_refcount_init(),
3570 * qcow2_check_refcounts(), qcow2_refcount_close() and qcow2_refcount_init()
3571 * again. However, because the functions which could have caused this error
3572 * path to be taken are used by those functions as well, it's very likely
3573 * that that sequence will fail as well. Therefore, just eject the BDS. */
3574 bs->drv = NULL;
3576 fail:
3577 g_free(new_reftable);
3578 return ret;
3581 static int qcow2_make_empty(BlockDriverState *bs)
3583 BDRVQcow2State *s = bs->opaque;
3584 uint64_t offset, end_offset;
3585 int step = QEMU_ALIGN_DOWN(INT_MAX, s->cluster_size);
3586 int l1_clusters, ret = 0;
3588 l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / sizeof(uint64_t));
3590 if (s->qcow_version >= 3 && !s->snapshots && !s->nb_bitmaps &&
3591 3 + l1_clusters <= s->refcount_block_size &&
3592 s->crypt_method_header != QCOW_CRYPT_LUKS) {
3593 /* The following function only works for qcow2 v3 images (it
3594 * requires the dirty flag) and only as long as there are no
3595 * features that reserve extra clusters (such as snapshots,
3596 * LUKS header, or persistent bitmaps), because it completely
3597 * empties the image. Furthermore, the L1 table and three
3598 * additional clusters (image header, refcount table, one
3599 * refcount block) have to fit inside one refcount block. */
3600 return make_completely_empty(bs);
3603 /* This fallback code simply discards every active cluster; this is slow,
3604 * but works in all cases */
3605 end_offset = bs->total_sectors * BDRV_SECTOR_SIZE;
3606 for (offset = 0; offset < end_offset; offset += step) {
3607 /* As this function is generally used after committing an external
3608 * snapshot, QCOW2_DISCARD_SNAPSHOT seems appropriate. Also, the
3609 * default action for this kind of discard is to pass the discard,
3610 * which will ideally result in an actually smaller image file, as
3611 * is probably desired. */
3612 ret = qcow2_cluster_discard(bs, offset, MIN(step, end_offset - offset),
3613 QCOW2_DISCARD_SNAPSHOT, true);
3614 if (ret < 0) {
3615 break;
3619 return ret;
3622 static coroutine_fn int qcow2_co_flush_to_os(BlockDriverState *bs)
3624 BDRVQcow2State *s = bs->opaque;
3625 int ret;
3627 qemu_co_mutex_lock(&s->lock);
3628 ret = qcow2_cache_write(bs, s->l2_table_cache);
3629 if (ret < 0) {
3630 qemu_co_mutex_unlock(&s->lock);
3631 return ret;
3634 if (qcow2_need_accurate_refcounts(s)) {
3635 ret = qcow2_cache_write(bs, s->refcount_block_cache);
3636 if (ret < 0) {
3637 qemu_co_mutex_unlock(&s->lock);
3638 return ret;
3641 qemu_co_mutex_unlock(&s->lock);
3643 return 0;
3646 static BlockMeasureInfo *qcow2_measure(QemuOpts *opts, BlockDriverState *in_bs,
3647 Error **errp)
3649 Error *local_err = NULL;
3650 BlockMeasureInfo *info;
3651 uint64_t required = 0; /* bytes that contribute to required size */
3652 uint64_t virtual_size; /* disk size as seen by guest */
3653 uint64_t refcount_bits;
3654 uint64_t l2_tables;
3655 size_t cluster_size;
3656 int version;
3657 char *optstr;
3658 PreallocMode prealloc;
3659 bool has_backing_file;
3661 /* Parse image creation options */
3662 cluster_size = qcow2_opt_get_cluster_size_del(opts, &local_err);
3663 if (local_err) {
3664 goto err;
3667 version = qcow2_opt_get_version_del(opts, &local_err);
3668 if (local_err) {
3669 goto err;
3672 refcount_bits = qcow2_opt_get_refcount_bits_del(opts, version, &local_err);
3673 if (local_err) {
3674 goto err;
3677 optstr = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
3678 prealloc = qapi_enum_parse(&PreallocMode_lookup, optstr,
3679 PREALLOC_MODE_OFF, &local_err);
3680 g_free(optstr);
3681 if (local_err) {
3682 goto err;
3685 optstr = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
3686 has_backing_file = !!optstr;
3687 g_free(optstr);
3689 virtual_size = align_offset(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
3690 cluster_size);
3692 /* Check that virtual disk size is valid */
3693 l2_tables = DIV_ROUND_UP(virtual_size / cluster_size,
3694 cluster_size / sizeof(uint64_t));
3695 if (l2_tables * sizeof(uint64_t) > QCOW_MAX_L1_SIZE) {
3696 error_setg(&local_err, "The image size is too large "
3697 "(try using a larger cluster size)");
3698 goto err;
3701 /* Account for input image */
3702 if (in_bs) {
3703 int64_t ssize = bdrv_getlength(in_bs);
3704 if (ssize < 0) {
3705 error_setg_errno(&local_err, -ssize,
3706 "Unable to get image virtual_size");
3707 goto err;
3710 virtual_size = align_offset(ssize, cluster_size);
3712 if (has_backing_file) {
3713 /* We don't how much of the backing chain is shared by the input
3714 * image and the new image file. In the worst case the new image's
3715 * backing file has nothing in common with the input image. Be
3716 * conservative and assume all clusters need to be written.
3718 required = virtual_size;
3719 } else {
3720 int64_t offset;
3721 int64_t pnum = 0;
3723 for (offset = 0; offset < ssize; offset += pnum) {
3724 int ret;
3726 ret = bdrv_block_status_above(in_bs, NULL, offset,
3727 ssize - offset, &pnum, NULL,
3728 NULL);
3729 if (ret < 0) {
3730 error_setg_errno(&local_err, -ret,
3731 "Unable to get block status");
3732 goto err;
3735 if (ret & BDRV_BLOCK_ZERO) {
3736 /* Skip zero regions (safe with no backing file) */
3737 } else if ((ret & (BDRV_BLOCK_DATA | BDRV_BLOCK_ALLOCATED)) ==
3738 (BDRV_BLOCK_DATA | BDRV_BLOCK_ALLOCATED)) {
3739 /* Extend pnum to end of cluster for next iteration */
3740 pnum = ROUND_UP(offset + pnum, cluster_size) - offset;
3742 /* Count clusters we've seen */
3743 required += offset % cluster_size + pnum;
3749 /* Take into account preallocation. Nothing special is needed for
3750 * PREALLOC_MODE_METADATA since metadata is always counted.
3752 if (prealloc == PREALLOC_MODE_FULL || prealloc == PREALLOC_MODE_FALLOC) {
3753 required = virtual_size;
3756 info = g_new(BlockMeasureInfo, 1);
3757 info->fully_allocated =
3758 qcow2_calc_prealloc_size(virtual_size, cluster_size,
3759 ctz32(refcount_bits));
3761 /* Remove data clusters that are not required. This overestimates the
3762 * required size because metadata needed for the fully allocated file is
3763 * still counted.
3765 info->required = info->fully_allocated - virtual_size + required;
3766 return info;
3768 err:
3769 error_propagate(errp, local_err);
3770 return NULL;
3773 static int qcow2_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
3775 BDRVQcow2State *s = bs->opaque;
3776 bdi->unallocated_blocks_are_zero = true;
3777 bdi->cluster_size = s->cluster_size;
3778 bdi->vm_state_offset = qcow2_vm_state_offset(s);
3779 return 0;
3782 static ImageInfoSpecific *qcow2_get_specific_info(BlockDriverState *bs)
3784 BDRVQcow2State *s = bs->opaque;
3785 ImageInfoSpecific *spec_info;
3786 QCryptoBlockInfo *encrypt_info = NULL;
3788 if (s->crypto != NULL) {
3789 encrypt_info = qcrypto_block_get_info(s->crypto, &error_abort);
3792 spec_info = g_new(ImageInfoSpecific, 1);
3793 *spec_info = (ImageInfoSpecific){
3794 .type = IMAGE_INFO_SPECIFIC_KIND_QCOW2,
3795 .u.qcow2.data = g_new(ImageInfoSpecificQCow2, 1),
3797 if (s->qcow_version == 2) {
3798 *spec_info->u.qcow2.data = (ImageInfoSpecificQCow2){
3799 .compat = g_strdup("0.10"),
3800 .refcount_bits = s->refcount_bits,
3802 } else if (s->qcow_version == 3) {
3803 *spec_info->u.qcow2.data = (ImageInfoSpecificQCow2){
3804 .compat = g_strdup("1.1"),
3805 .lazy_refcounts = s->compatible_features &
3806 QCOW2_COMPAT_LAZY_REFCOUNTS,
3807 .has_lazy_refcounts = true,
3808 .corrupt = s->incompatible_features &
3809 QCOW2_INCOMPAT_CORRUPT,
3810 .has_corrupt = true,
3811 .refcount_bits = s->refcount_bits,
3813 } else {
3814 /* if this assertion fails, this probably means a new version was
3815 * added without having it covered here */
3816 assert(false);
3819 if (encrypt_info) {
3820 ImageInfoSpecificQCow2Encryption *qencrypt =
3821 g_new(ImageInfoSpecificQCow2Encryption, 1);
3822 switch (encrypt_info->format) {
3823 case Q_CRYPTO_BLOCK_FORMAT_QCOW:
3824 qencrypt->format = BLOCKDEV_QCOW2_ENCRYPTION_FORMAT_AES;
3825 qencrypt->u.aes = encrypt_info->u.qcow;
3826 break;
3827 case Q_CRYPTO_BLOCK_FORMAT_LUKS:
3828 qencrypt->format = BLOCKDEV_QCOW2_ENCRYPTION_FORMAT_LUKS;
3829 qencrypt->u.luks = encrypt_info->u.luks;
3830 break;
3831 default:
3832 abort();
3834 /* Since we did shallow copy above, erase any pointers
3835 * in the original info */
3836 memset(&encrypt_info->u, 0, sizeof(encrypt_info->u));
3837 qapi_free_QCryptoBlockInfo(encrypt_info);
3839 spec_info->u.qcow2.data->has_encrypt = true;
3840 spec_info->u.qcow2.data->encrypt = qencrypt;
3843 return spec_info;
3846 static int qcow2_save_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
3847 int64_t pos)
3849 BDRVQcow2State *s = bs->opaque;
3851 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_SAVE);
3852 return bs->drv->bdrv_co_pwritev(bs, qcow2_vm_state_offset(s) + pos,
3853 qiov->size, qiov, 0);
3856 static int qcow2_load_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
3857 int64_t pos)
3859 BDRVQcow2State *s = bs->opaque;
3861 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_LOAD);
3862 return bs->drv->bdrv_co_preadv(bs, qcow2_vm_state_offset(s) + pos,
3863 qiov->size, qiov, 0);
3867 * Downgrades an image's version. To achieve this, any incompatible features
3868 * have to be removed.
3870 static int qcow2_downgrade(BlockDriverState *bs, int target_version,
3871 BlockDriverAmendStatusCB *status_cb, void *cb_opaque)
3873 BDRVQcow2State *s = bs->opaque;
3874 int current_version = s->qcow_version;
3875 int ret;
3877 if (target_version == current_version) {
3878 return 0;
3879 } else if (target_version > current_version) {
3880 return -EINVAL;
3881 } else if (target_version != 2) {
3882 return -EINVAL;
3885 if (s->refcount_order != 4) {
3886 error_report("compat=0.10 requires refcount_bits=16");
3887 return -ENOTSUP;
3890 /* clear incompatible features */
3891 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
3892 ret = qcow2_mark_clean(bs);
3893 if (ret < 0) {
3894 return ret;
3898 /* with QCOW2_INCOMPAT_CORRUPT, it is pretty much impossible to get here in
3899 * the first place; if that happens nonetheless, returning -ENOTSUP is the
3900 * best thing to do anyway */
3902 if (s->incompatible_features) {
3903 return -ENOTSUP;
3906 /* since we can ignore compatible features, we can set them to 0 as well */
3907 s->compatible_features = 0;
3908 /* if lazy refcounts have been used, they have already been fixed through
3909 * clearing the dirty flag */
3911 /* clearing autoclear features is trivial */
3912 s->autoclear_features = 0;
3914 ret = qcow2_expand_zero_clusters(bs, status_cb, cb_opaque);
3915 if (ret < 0) {
3916 return ret;
3919 s->qcow_version = target_version;
3920 ret = qcow2_update_header(bs);
3921 if (ret < 0) {
3922 s->qcow_version = current_version;
3923 return ret;
3925 return 0;
3928 typedef enum Qcow2AmendOperation {
3929 /* This is the value Qcow2AmendHelperCBInfo::last_operation will be
3930 * statically initialized to so that the helper CB can discern the first
3931 * invocation from an operation change */
3932 QCOW2_NO_OPERATION = 0,
3934 QCOW2_CHANGING_REFCOUNT_ORDER,
3935 QCOW2_DOWNGRADING,
3936 } Qcow2AmendOperation;
3938 typedef struct Qcow2AmendHelperCBInfo {
3939 /* The code coordinating the amend operations should only modify
3940 * these four fields; the rest will be managed by the CB */
3941 BlockDriverAmendStatusCB *original_status_cb;
3942 void *original_cb_opaque;
3944 Qcow2AmendOperation current_operation;
3946 /* Total number of operations to perform (only set once) */
3947 int total_operations;
3949 /* The following fields are managed by the CB */
3951 /* Number of operations completed */
3952 int operations_completed;
3954 /* Cumulative offset of all completed operations */
3955 int64_t offset_completed;
3957 Qcow2AmendOperation last_operation;
3958 int64_t last_work_size;
3959 } Qcow2AmendHelperCBInfo;
3961 static void qcow2_amend_helper_cb(BlockDriverState *bs,
3962 int64_t operation_offset,
3963 int64_t operation_work_size, void *opaque)
3965 Qcow2AmendHelperCBInfo *info = opaque;
3966 int64_t current_work_size;
3967 int64_t projected_work_size;
3969 if (info->current_operation != info->last_operation) {
3970 if (info->last_operation != QCOW2_NO_OPERATION) {
3971 info->offset_completed += info->last_work_size;
3972 info->operations_completed++;
3975 info->last_operation = info->current_operation;
3978 assert(info->total_operations > 0);
3979 assert(info->operations_completed < info->total_operations);
3981 info->last_work_size = operation_work_size;
3983 current_work_size = info->offset_completed + operation_work_size;
3985 /* current_work_size is the total work size for (operations_completed + 1)
3986 * operations (which includes this one), so multiply it by the number of
3987 * operations not covered and divide it by the number of operations
3988 * covered to get a projection for the operations not covered */
3989 projected_work_size = current_work_size * (info->total_operations -
3990 info->operations_completed - 1)
3991 / (info->operations_completed + 1);
3993 info->original_status_cb(bs, info->offset_completed + operation_offset,
3994 current_work_size + projected_work_size,
3995 info->original_cb_opaque);
3998 static int qcow2_amend_options(BlockDriverState *bs, QemuOpts *opts,
3999 BlockDriverAmendStatusCB *status_cb,
4000 void *cb_opaque)
4002 BDRVQcow2State *s = bs->opaque;
4003 int old_version = s->qcow_version, new_version = old_version;
4004 uint64_t new_size = 0;
4005 const char *backing_file = NULL, *backing_format = NULL;
4006 bool lazy_refcounts = s->use_lazy_refcounts;
4007 const char *compat = NULL;
4008 uint64_t cluster_size = s->cluster_size;
4009 bool encrypt;
4010 int encformat;
4011 int refcount_bits = s->refcount_bits;
4012 Error *local_err = NULL;
4013 int ret;
4014 QemuOptDesc *desc = opts->list->desc;
4015 Qcow2AmendHelperCBInfo helper_cb_info;
4017 while (desc && desc->name) {
4018 if (!qemu_opt_find(opts, desc->name)) {
4019 /* only change explicitly defined options */
4020 desc++;
4021 continue;
4024 if (!strcmp(desc->name, BLOCK_OPT_COMPAT_LEVEL)) {
4025 compat = qemu_opt_get(opts, BLOCK_OPT_COMPAT_LEVEL);
4026 if (!compat) {
4027 /* preserve default */
4028 } else if (!strcmp(compat, "0.10")) {
4029 new_version = 2;
4030 } else if (!strcmp(compat, "1.1")) {
4031 new_version = 3;
4032 } else {
4033 error_report("Unknown compatibility level %s", compat);
4034 return -EINVAL;
4036 } else if (!strcmp(desc->name, BLOCK_OPT_PREALLOC)) {
4037 error_report("Cannot change preallocation mode");
4038 return -ENOTSUP;
4039 } else if (!strcmp(desc->name, BLOCK_OPT_SIZE)) {
4040 new_size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, 0);
4041 } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FILE)) {
4042 backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
4043 } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FMT)) {
4044 backing_format = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
4045 } else if (!strcmp(desc->name, BLOCK_OPT_ENCRYPT)) {
4046 encrypt = qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT,
4047 !!s->crypto);
4049 if (encrypt != !!s->crypto) {
4050 error_report("Changing the encryption flag is not supported");
4051 return -ENOTSUP;
4053 } else if (!strcmp(desc->name, BLOCK_OPT_ENCRYPT_FORMAT)) {
4054 encformat = qcow2_crypt_method_from_format(
4055 qemu_opt_get(opts, BLOCK_OPT_ENCRYPT_FORMAT));
4057 if (encformat != s->crypt_method_header) {
4058 error_report("Changing the encryption format is not supported");
4059 return -ENOTSUP;
4061 } else if (g_str_has_prefix(desc->name, "encrypt.")) {
4062 error_report("Changing the encryption parameters is not supported");
4063 return -ENOTSUP;
4064 } else if (!strcmp(desc->name, BLOCK_OPT_CLUSTER_SIZE)) {
4065 cluster_size = qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE,
4066 cluster_size);
4067 if (cluster_size != s->cluster_size) {
4068 error_report("Changing the cluster size is not supported");
4069 return -ENOTSUP;
4071 } else if (!strcmp(desc->name, BLOCK_OPT_LAZY_REFCOUNTS)) {
4072 lazy_refcounts = qemu_opt_get_bool(opts, BLOCK_OPT_LAZY_REFCOUNTS,
4073 lazy_refcounts);
4074 } else if (!strcmp(desc->name, BLOCK_OPT_REFCOUNT_BITS)) {
4075 refcount_bits = qemu_opt_get_number(opts, BLOCK_OPT_REFCOUNT_BITS,
4076 refcount_bits);
4078 if (refcount_bits <= 0 || refcount_bits > 64 ||
4079 !is_power_of_2(refcount_bits))
4081 error_report("Refcount width must be a power of two and may "
4082 "not exceed 64 bits");
4083 return -EINVAL;
4085 } else {
4086 /* if this point is reached, this probably means a new option was
4087 * added without having it covered here */
4088 abort();
4091 desc++;
4094 helper_cb_info = (Qcow2AmendHelperCBInfo){
4095 .original_status_cb = status_cb,
4096 .original_cb_opaque = cb_opaque,
4097 .total_operations = (new_version < old_version)
4098 + (s->refcount_bits != refcount_bits)
4101 /* Upgrade first (some features may require compat=1.1) */
4102 if (new_version > old_version) {
4103 s->qcow_version = new_version;
4104 ret = qcow2_update_header(bs);
4105 if (ret < 0) {
4106 s->qcow_version = old_version;
4107 return ret;
4111 if (s->refcount_bits != refcount_bits) {
4112 int refcount_order = ctz32(refcount_bits);
4114 if (new_version < 3 && refcount_bits != 16) {
4115 error_report("Different refcount widths than 16 bits require "
4116 "compatibility level 1.1 or above (use compat=1.1 or "
4117 "greater)");
4118 return -EINVAL;
4121 helper_cb_info.current_operation = QCOW2_CHANGING_REFCOUNT_ORDER;
4122 ret = qcow2_change_refcount_order(bs, refcount_order,
4123 &qcow2_amend_helper_cb,
4124 &helper_cb_info, &local_err);
4125 if (ret < 0) {
4126 error_report_err(local_err);
4127 return ret;
4131 if (backing_file || backing_format) {
4132 ret = qcow2_change_backing_file(bs,
4133 backing_file ?: s->image_backing_file,
4134 backing_format ?: s->image_backing_format);
4135 if (ret < 0) {
4136 return ret;
4140 if (s->use_lazy_refcounts != lazy_refcounts) {
4141 if (lazy_refcounts) {
4142 if (new_version < 3) {
4143 error_report("Lazy refcounts only supported with compatibility "
4144 "level 1.1 and above (use compat=1.1 or greater)");
4145 return -EINVAL;
4147 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
4148 ret = qcow2_update_header(bs);
4149 if (ret < 0) {
4150 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
4151 return ret;
4153 s->use_lazy_refcounts = true;
4154 } else {
4155 /* make image clean first */
4156 ret = qcow2_mark_clean(bs);
4157 if (ret < 0) {
4158 return ret;
4160 /* now disallow lazy refcounts */
4161 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
4162 ret = qcow2_update_header(bs);
4163 if (ret < 0) {
4164 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
4165 return ret;
4167 s->use_lazy_refcounts = false;
4171 if (new_size) {
4172 BlockBackend *blk = blk_new(BLK_PERM_RESIZE, BLK_PERM_ALL);
4173 ret = blk_insert_bs(blk, bs, &local_err);
4174 if (ret < 0) {
4175 error_report_err(local_err);
4176 blk_unref(blk);
4177 return ret;
4180 ret = blk_truncate(blk, new_size, PREALLOC_MODE_OFF, &local_err);
4181 blk_unref(blk);
4182 if (ret < 0) {
4183 error_report_err(local_err);
4184 return ret;
4188 /* Downgrade last (so unsupported features can be removed before) */
4189 if (new_version < old_version) {
4190 helper_cb_info.current_operation = QCOW2_DOWNGRADING;
4191 ret = qcow2_downgrade(bs, new_version, &qcow2_amend_helper_cb,
4192 &helper_cb_info);
4193 if (ret < 0) {
4194 return ret;
4198 return 0;
4202 * If offset or size are negative, respectively, they will not be included in
4203 * the BLOCK_IMAGE_CORRUPTED event emitted.
4204 * fatal will be ignored for read-only BDS; corruptions found there will always
4205 * be considered non-fatal.
4207 void qcow2_signal_corruption(BlockDriverState *bs, bool fatal, int64_t offset,
4208 int64_t size, const char *message_format, ...)
4210 BDRVQcow2State *s = bs->opaque;
4211 const char *node_name;
4212 char *message;
4213 va_list ap;
4215 fatal = fatal && !bs->read_only;
4217 if (s->signaled_corruption &&
4218 (!fatal || (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT)))
4220 return;
4223 va_start(ap, message_format);
4224 message = g_strdup_vprintf(message_format, ap);
4225 va_end(ap);
4227 if (fatal) {
4228 fprintf(stderr, "qcow2: Marking image as corrupt: %s; further "
4229 "corruption events will be suppressed\n", message);
4230 } else {
4231 fprintf(stderr, "qcow2: Image is corrupt: %s; further non-fatal "
4232 "corruption events will be suppressed\n", message);
4235 node_name = bdrv_get_node_name(bs);
4236 qapi_event_send_block_image_corrupted(bdrv_get_device_name(bs),
4237 *node_name != '\0', node_name,
4238 message, offset >= 0, offset,
4239 size >= 0, size,
4240 fatal, &error_abort);
4241 g_free(message);
4243 if (fatal) {
4244 qcow2_mark_corrupt(bs);
4245 bs->drv = NULL; /* make BDS unusable */
4248 s->signaled_corruption = true;
4251 static QemuOptsList qcow2_create_opts = {
4252 .name = "qcow2-create-opts",
4253 .head = QTAILQ_HEAD_INITIALIZER(qcow2_create_opts.head),
4254 .desc = {
4256 .name = BLOCK_OPT_SIZE,
4257 .type = QEMU_OPT_SIZE,
4258 .help = "Virtual disk size"
4261 .name = BLOCK_OPT_COMPAT_LEVEL,
4262 .type = QEMU_OPT_STRING,
4263 .help = "Compatibility level (0.10 or 1.1)"
4266 .name = BLOCK_OPT_BACKING_FILE,
4267 .type = QEMU_OPT_STRING,
4268 .help = "File name of a base image"
4271 .name = BLOCK_OPT_BACKING_FMT,
4272 .type = QEMU_OPT_STRING,
4273 .help = "Image format of the base image"
4276 .name = BLOCK_OPT_ENCRYPT,
4277 .type = QEMU_OPT_BOOL,
4278 .help = "Encrypt the image with format 'aes'. (Deprecated "
4279 "in favor of " BLOCK_OPT_ENCRYPT_FORMAT "=aes)",
4282 .name = BLOCK_OPT_ENCRYPT_FORMAT,
4283 .type = QEMU_OPT_STRING,
4284 .help = "Encrypt the image, format choices: 'aes', 'luks'",
4286 BLOCK_CRYPTO_OPT_DEF_KEY_SECRET("encrypt.",
4287 "ID of secret providing qcow AES key or LUKS passphrase"),
4288 BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_ALG("encrypt."),
4289 BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_MODE("encrypt."),
4290 BLOCK_CRYPTO_OPT_DEF_LUKS_IVGEN_ALG("encrypt."),
4291 BLOCK_CRYPTO_OPT_DEF_LUKS_IVGEN_HASH_ALG("encrypt."),
4292 BLOCK_CRYPTO_OPT_DEF_LUKS_HASH_ALG("encrypt."),
4293 BLOCK_CRYPTO_OPT_DEF_LUKS_ITER_TIME("encrypt."),
4295 .name = BLOCK_OPT_CLUSTER_SIZE,
4296 .type = QEMU_OPT_SIZE,
4297 .help = "qcow2 cluster size",
4298 .def_value_str = stringify(DEFAULT_CLUSTER_SIZE)
4301 .name = BLOCK_OPT_PREALLOC,
4302 .type = QEMU_OPT_STRING,
4303 .help = "Preallocation mode (allowed values: off, metadata, "
4304 "falloc, full)"
4307 .name = BLOCK_OPT_LAZY_REFCOUNTS,
4308 .type = QEMU_OPT_BOOL,
4309 .help = "Postpone refcount updates",
4310 .def_value_str = "off"
4313 .name = BLOCK_OPT_REFCOUNT_BITS,
4314 .type = QEMU_OPT_NUMBER,
4315 .help = "Width of a reference count entry in bits",
4316 .def_value_str = "16"
4318 { /* end of list */ }
4322 BlockDriver bdrv_qcow2 = {
4323 .format_name = "qcow2",
4324 .instance_size = sizeof(BDRVQcow2State),
4325 .bdrv_probe = qcow2_probe,
4326 .bdrv_open = qcow2_open,
4327 .bdrv_close = qcow2_close,
4328 .bdrv_reopen_prepare = qcow2_reopen_prepare,
4329 .bdrv_reopen_commit = qcow2_reopen_commit,
4330 .bdrv_reopen_abort = qcow2_reopen_abort,
4331 .bdrv_join_options = qcow2_join_options,
4332 .bdrv_child_perm = bdrv_format_default_perms,
4333 .bdrv_create = qcow2_create,
4334 .bdrv_has_zero_init = bdrv_has_zero_init_1,
4335 .bdrv_co_get_block_status = qcow2_co_get_block_status,
4337 .bdrv_co_preadv = qcow2_co_preadv,
4338 .bdrv_co_pwritev = qcow2_co_pwritev,
4339 .bdrv_co_flush_to_os = qcow2_co_flush_to_os,
4341 .bdrv_co_pwrite_zeroes = qcow2_co_pwrite_zeroes,
4342 .bdrv_co_pdiscard = qcow2_co_pdiscard,
4343 .bdrv_truncate = qcow2_truncate,
4344 .bdrv_co_pwritev_compressed = qcow2_co_pwritev_compressed,
4345 .bdrv_make_empty = qcow2_make_empty,
4347 .bdrv_snapshot_create = qcow2_snapshot_create,
4348 .bdrv_snapshot_goto = qcow2_snapshot_goto,
4349 .bdrv_snapshot_delete = qcow2_snapshot_delete,
4350 .bdrv_snapshot_list = qcow2_snapshot_list,
4351 .bdrv_snapshot_load_tmp = qcow2_snapshot_load_tmp,
4352 .bdrv_measure = qcow2_measure,
4353 .bdrv_get_info = qcow2_get_info,
4354 .bdrv_get_specific_info = qcow2_get_specific_info,
4356 .bdrv_save_vmstate = qcow2_save_vmstate,
4357 .bdrv_load_vmstate = qcow2_load_vmstate,
4359 .supports_backing = true,
4360 .bdrv_change_backing_file = qcow2_change_backing_file,
4362 .bdrv_refresh_limits = qcow2_refresh_limits,
4363 .bdrv_invalidate_cache = qcow2_invalidate_cache,
4364 .bdrv_inactivate = qcow2_inactivate,
4366 .create_opts = &qcow2_create_opts,
4367 .bdrv_check = qcow2_check,
4368 .bdrv_amend_options = qcow2_amend_options,
4370 .bdrv_detach_aio_context = qcow2_detach_aio_context,
4371 .bdrv_attach_aio_context = qcow2_attach_aio_context,
4373 .bdrv_reopen_bitmaps_rw = qcow2_reopen_bitmaps_rw,
4374 .bdrv_can_store_new_dirty_bitmap = qcow2_can_store_new_dirty_bitmap,
4375 .bdrv_remove_persistent_dirty_bitmap = qcow2_remove_persistent_dirty_bitmap,
4378 static void bdrv_qcow2_init(void)
4380 bdrv_register(&bdrv_qcow2);
4383 block_init(bdrv_qcow2_init);