]> git.proxmox.com Git - mirror_qemu.git/blob - block/qcow2.c
block: convert bdrv_invalidate_cache callback to coroutine_fn
[mirror_qemu.git] / block / qcow2.c
1 /*
2 * Block driver for the QCOW version 2 format
3 *
4 * Copyright (c) 2004-2006 Fabrice Bellard
5 *
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:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
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.
23 */
24
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/qapi-events-block-core.h"
34 #include "qapi/qmp/qdict.h"
35 #include "qapi/qmp/qstring.h"
36 #include "trace.h"
37 #include "qemu/option_int.h"
38 #include "qemu/cutils.h"
39 #include "qemu/bswap.h"
40 #include "qapi/opts-visitor.h"
41 #include "block/crypto.h"
42
43 /*
44 Differences with QCOW:
45
46 - Support for multiple incremental snapshots.
47 - Memory management by reference counts.
48 - Clusters which have a reference count of one have the bit
49 QCOW_OFLAG_COPIED to optimize write performance.
50 - Size of compressed clusters is stored in sectors to reduce bit usage
51 in the cluster offsets.
52 - Support for storing additional data (such as the VM state) in the
53 snapshots.
54 - If a backing store is used, the cluster size is not constrained
55 (could be backported to QCOW).
56 - L2 tables have always a size of one cluster.
57 */
58
59
60 typedef struct {
61 uint32_t magic;
62 uint32_t len;
63 } QEMU_PACKED QCowExtension;
64
65 #define QCOW2_EXT_MAGIC_END 0
66 #define QCOW2_EXT_MAGIC_BACKING_FORMAT 0xE2792ACA
67 #define QCOW2_EXT_MAGIC_FEATURE_TABLE 0x6803f857
68 #define QCOW2_EXT_MAGIC_CRYPTO_HEADER 0x0537be77
69 #define QCOW2_EXT_MAGIC_BITMAPS 0x23852875
70
71 static int qcow2_probe(const uint8_t *buf, int buf_size, const char *filename)
72 {
73 const QCowHeader *cow_header = (const void *)buf;
74
75 if (buf_size >= sizeof(QCowHeader) &&
76 be32_to_cpu(cow_header->magic) == QCOW_MAGIC &&
77 be32_to_cpu(cow_header->version) >= 2)
78 return 100;
79 else
80 return 0;
81 }
82
83
84 static ssize_t qcow2_crypto_hdr_read_func(QCryptoBlock *block, size_t offset,
85 uint8_t *buf, size_t buflen,
86 void *opaque, Error **errp)
87 {
88 BlockDriverState *bs = opaque;
89 BDRVQcow2State *s = bs->opaque;
90 ssize_t ret;
91
92 if ((offset + buflen) > s->crypto_header.length) {
93 error_setg(errp, "Request for data outside of extension header");
94 return -1;
95 }
96
97 ret = bdrv_pread(bs->file,
98 s->crypto_header.offset + offset, buf, buflen);
99 if (ret < 0) {
100 error_setg_errno(errp, -ret, "Could not read encryption header");
101 return -1;
102 }
103 return ret;
104 }
105
106
107 static ssize_t qcow2_crypto_hdr_init_func(QCryptoBlock *block, size_t headerlen,
108 void *opaque, Error **errp)
109 {
110 BlockDriverState *bs = opaque;
111 BDRVQcow2State *s = bs->opaque;
112 int64_t ret;
113 int64_t clusterlen;
114
115 ret = qcow2_alloc_clusters(bs, headerlen);
116 if (ret < 0) {
117 error_setg_errno(errp, -ret,
118 "Cannot allocate cluster for LUKS header size %zu",
119 headerlen);
120 return -1;
121 }
122
123 s->crypto_header.length = headerlen;
124 s->crypto_header.offset = ret;
125
126 /* Zero fill remaining space in cluster so it has predictable
127 * content in case of future spec changes */
128 clusterlen = size_to_clusters(s, headerlen) * s->cluster_size;
129 assert(qcow2_pre_write_overlap_check(bs, 0, ret, clusterlen) == 0);
130 ret = bdrv_pwrite_zeroes(bs->file,
131 ret + headerlen,
132 clusterlen - headerlen, 0);
133 if (ret < 0) {
134 error_setg_errno(errp, -ret, "Could not zero fill encryption header");
135 return -1;
136 }
137
138 return ret;
139 }
140
141
142 static ssize_t qcow2_crypto_hdr_write_func(QCryptoBlock *block, size_t offset,
143 const uint8_t *buf, size_t buflen,
144 void *opaque, Error **errp)
145 {
146 BlockDriverState *bs = opaque;
147 BDRVQcow2State *s = bs->opaque;
148 ssize_t ret;
149
150 if ((offset + buflen) > s->crypto_header.length) {
151 error_setg(errp, "Request for data outside of extension header");
152 return -1;
153 }
154
155 ret = bdrv_pwrite(bs->file,
156 s->crypto_header.offset + offset, buf, buflen);
157 if (ret < 0) {
158 error_setg_errno(errp, -ret, "Could not read encryption header");
159 return -1;
160 }
161 return ret;
162 }
163
164
165 /*
166 * read qcow2 extension and fill bs
167 * start reading from start_offset
168 * finish reading upon magic of value 0 or when end_offset reached
169 * unknown magic is skipped (future extension this version knows nothing about)
170 * return 0 upon success, non-0 otherwise
171 */
172 static int qcow2_read_extensions(BlockDriverState *bs, uint64_t start_offset,
173 uint64_t end_offset, void **p_feature_table,
174 int flags, bool *need_update_header,
175 Error **errp)
176 {
177 BDRVQcow2State *s = bs->opaque;
178 QCowExtension ext;
179 uint64_t offset;
180 int ret;
181 Qcow2BitmapHeaderExt bitmaps_ext;
182
183 if (need_update_header != NULL) {
184 *need_update_header = false;
185 }
186
187 #ifdef DEBUG_EXT
188 printf("qcow2_read_extensions: start=%ld end=%ld\n", start_offset, end_offset);
189 #endif
190 offset = start_offset;
191 while (offset < end_offset) {
192
193 #ifdef DEBUG_EXT
194 /* Sanity check */
195 if (offset > s->cluster_size)
196 printf("qcow2_read_extension: suspicious offset %lu\n", offset);
197
198 printf("attempting to read extended header in offset %lu\n", offset);
199 #endif
200
201 ret = bdrv_pread(bs->file, offset, &ext, sizeof(ext));
202 if (ret < 0) {
203 error_setg_errno(errp, -ret, "qcow2_read_extension: ERROR: "
204 "pread fail from offset %" PRIu64, offset);
205 return 1;
206 }
207 be32_to_cpus(&ext.magic);
208 be32_to_cpus(&ext.len);
209 offset += sizeof(ext);
210 #ifdef DEBUG_EXT
211 printf("ext.magic = 0x%x\n", ext.magic);
212 #endif
213 if (offset > end_offset || ext.len > end_offset - offset) {
214 error_setg(errp, "Header extension too large");
215 return -EINVAL;
216 }
217
218 switch (ext.magic) {
219 case QCOW2_EXT_MAGIC_END:
220 return 0;
221
222 case QCOW2_EXT_MAGIC_BACKING_FORMAT:
223 if (ext.len >= sizeof(bs->backing_format)) {
224 error_setg(errp, "ERROR: ext_backing_format: len=%" PRIu32
225 " too large (>=%zu)", ext.len,
226 sizeof(bs->backing_format));
227 return 2;
228 }
229 ret = bdrv_pread(bs->file, offset, bs->backing_format, ext.len);
230 if (ret < 0) {
231 error_setg_errno(errp, -ret, "ERROR: ext_backing_format: "
232 "Could not read format name");
233 return 3;
234 }
235 bs->backing_format[ext.len] = '\0';
236 s->image_backing_format = g_strdup(bs->backing_format);
237 #ifdef DEBUG_EXT
238 printf("Qcow2: Got format extension %s\n", bs->backing_format);
239 #endif
240 break;
241
242 case QCOW2_EXT_MAGIC_FEATURE_TABLE:
243 if (p_feature_table != NULL) {
244 void* feature_table = g_malloc0(ext.len + 2 * sizeof(Qcow2Feature));
245 ret = bdrv_pread(bs->file, offset , feature_table, ext.len);
246 if (ret < 0) {
247 error_setg_errno(errp, -ret, "ERROR: ext_feature_table: "
248 "Could not read table");
249 return ret;
250 }
251
252 *p_feature_table = feature_table;
253 }
254 break;
255
256 case QCOW2_EXT_MAGIC_CRYPTO_HEADER: {
257 unsigned int cflags = 0;
258 if (s->crypt_method_header != QCOW_CRYPT_LUKS) {
259 error_setg(errp, "CRYPTO header extension only "
260 "expected with LUKS encryption method");
261 return -EINVAL;
262 }
263 if (ext.len != sizeof(Qcow2CryptoHeaderExtension)) {
264 error_setg(errp, "CRYPTO header extension size %u, "
265 "but expected size %zu", ext.len,
266 sizeof(Qcow2CryptoHeaderExtension));
267 return -EINVAL;
268 }
269
270 ret = bdrv_pread(bs->file, offset, &s->crypto_header, ext.len);
271 if (ret < 0) {
272 error_setg_errno(errp, -ret,
273 "Unable to read CRYPTO header extension");
274 return ret;
275 }
276 be64_to_cpus(&s->crypto_header.offset);
277 be64_to_cpus(&s->crypto_header.length);
278
279 if ((s->crypto_header.offset % s->cluster_size) != 0) {
280 error_setg(errp, "Encryption header offset '%" PRIu64 "' is "
281 "not a multiple of cluster size '%u'",
282 s->crypto_header.offset, s->cluster_size);
283 return -EINVAL;
284 }
285
286 if (flags & BDRV_O_NO_IO) {
287 cflags |= QCRYPTO_BLOCK_OPEN_NO_IO;
288 }
289 s->crypto = qcrypto_block_open(s->crypto_opts, "encrypt.",
290 qcow2_crypto_hdr_read_func,
291 bs, cflags, errp);
292 if (!s->crypto) {
293 return -EINVAL;
294 }
295 } break;
296
297 case QCOW2_EXT_MAGIC_BITMAPS:
298 if (ext.len != sizeof(bitmaps_ext)) {
299 error_setg_errno(errp, -ret, "bitmaps_ext: "
300 "Invalid extension length");
301 return -EINVAL;
302 }
303
304 if (!(s->autoclear_features & QCOW2_AUTOCLEAR_BITMAPS)) {
305 if (s->qcow_version < 3) {
306 /* Let's be a bit more specific */
307 warn_report("This qcow2 v2 image contains bitmaps, but "
308 "they may have been modified by a program "
309 "without persistent bitmap support; so now "
310 "they must all be considered inconsistent");
311 } else {
312 warn_report("a program lacking bitmap support "
313 "modified this file, so all bitmaps are now "
314 "considered inconsistent");
315 }
316 error_printf("Some clusters may be leaked, "
317 "run 'qemu-img check -r' on the image "
318 "file to fix.");
319 if (need_update_header != NULL) {
320 /* Updating is needed to drop invalid bitmap extension. */
321 *need_update_header = true;
322 }
323 break;
324 }
325
326 ret = bdrv_pread(bs->file, offset, &bitmaps_ext, ext.len);
327 if (ret < 0) {
328 error_setg_errno(errp, -ret, "bitmaps_ext: "
329 "Could not read ext header");
330 return ret;
331 }
332
333 if (bitmaps_ext.reserved32 != 0) {
334 error_setg_errno(errp, -ret, "bitmaps_ext: "
335 "Reserved field is not zero");
336 return -EINVAL;
337 }
338
339 be32_to_cpus(&bitmaps_ext.nb_bitmaps);
340 be64_to_cpus(&bitmaps_ext.bitmap_directory_size);
341 be64_to_cpus(&bitmaps_ext.bitmap_directory_offset);
342
343 if (bitmaps_ext.nb_bitmaps > QCOW2_MAX_BITMAPS) {
344 error_setg(errp,
345 "bitmaps_ext: Image has %" PRIu32 " bitmaps, "
346 "exceeding the QEMU supported maximum of %d",
347 bitmaps_ext.nb_bitmaps, QCOW2_MAX_BITMAPS);
348 return -EINVAL;
349 }
350
351 if (bitmaps_ext.nb_bitmaps == 0) {
352 error_setg(errp, "found bitmaps extension with zero bitmaps");
353 return -EINVAL;
354 }
355
356 if (bitmaps_ext.bitmap_directory_offset & (s->cluster_size - 1)) {
357 error_setg(errp, "bitmaps_ext: "
358 "invalid bitmap directory offset");
359 return -EINVAL;
360 }
361
362 if (bitmaps_ext.bitmap_directory_size >
363 QCOW2_MAX_BITMAP_DIRECTORY_SIZE) {
364 error_setg(errp, "bitmaps_ext: "
365 "bitmap directory size (%" PRIu64 ") exceeds "
366 "the maximum supported size (%d)",
367 bitmaps_ext.bitmap_directory_size,
368 QCOW2_MAX_BITMAP_DIRECTORY_SIZE);
369 return -EINVAL;
370 }
371
372 s->nb_bitmaps = bitmaps_ext.nb_bitmaps;
373 s->bitmap_directory_offset =
374 bitmaps_ext.bitmap_directory_offset;
375 s->bitmap_directory_size =
376 bitmaps_ext.bitmap_directory_size;
377
378 #ifdef DEBUG_EXT
379 printf("Qcow2: Got bitmaps extension: "
380 "offset=%" PRIu64 " nb_bitmaps=%" PRIu32 "\n",
381 s->bitmap_directory_offset, s->nb_bitmaps);
382 #endif
383 break;
384
385 default:
386 /* unknown magic - save it in case we need to rewrite the header */
387 /* If you add a new feature, make sure to also update the fast
388 * path of qcow2_make_empty() to deal with it. */
389 {
390 Qcow2UnknownHeaderExtension *uext;
391
392 uext = g_malloc0(sizeof(*uext) + ext.len);
393 uext->magic = ext.magic;
394 uext->len = ext.len;
395 QLIST_INSERT_HEAD(&s->unknown_header_ext, uext, next);
396
397 ret = bdrv_pread(bs->file, offset , uext->data, uext->len);
398 if (ret < 0) {
399 error_setg_errno(errp, -ret, "ERROR: unknown extension: "
400 "Could not read data");
401 return ret;
402 }
403 }
404 break;
405 }
406
407 offset += ((ext.len + 7) & ~7);
408 }
409
410 return 0;
411 }
412
413 static void cleanup_unknown_header_ext(BlockDriverState *bs)
414 {
415 BDRVQcow2State *s = bs->opaque;
416 Qcow2UnknownHeaderExtension *uext, *next;
417
418 QLIST_FOREACH_SAFE(uext, &s->unknown_header_ext, next, next) {
419 QLIST_REMOVE(uext, next);
420 g_free(uext);
421 }
422 }
423
424 static void report_unsupported_feature(Error **errp, Qcow2Feature *table,
425 uint64_t mask)
426 {
427 char *features = g_strdup("");
428 char *old;
429
430 while (table && table->name[0] != '\0') {
431 if (table->type == QCOW2_FEAT_TYPE_INCOMPATIBLE) {
432 if (mask & (1ULL << table->bit)) {
433 old = features;
434 features = g_strdup_printf("%s%s%.46s", old, *old ? ", " : "",
435 table->name);
436 g_free(old);
437 mask &= ~(1ULL << table->bit);
438 }
439 }
440 table++;
441 }
442
443 if (mask) {
444 old = features;
445 features = g_strdup_printf("%s%sUnknown incompatible feature: %" PRIx64,
446 old, *old ? ", " : "", mask);
447 g_free(old);
448 }
449
450 error_setg(errp, "Unsupported qcow2 feature(s): %s", features);
451 g_free(features);
452 }
453
454 /*
455 * Sets the dirty bit and flushes afterwards if necessary.
456 *
457 * The incompatible_features bit is only set if the image file header was
458 * updated successfully. Therefore it is not required to check the return
459 * value of this function.
460 */
461 int qcow2_mark_dirty(BlockDriverState *bs)
462 {
463 BDRVQcow2State *s = bs->opaque;
464 uint64_t val;
465 int ret;
466
467 assert(s->qcow_version >= 3);
468
469 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
470 return 0; /* already dirty */
471 }
472
473 val = cpu_to_be64(s->incompatible_features | QCOW2_INCOMPAT_DIRTY);
474 ret = bdrv_pwrite(bs->file, offsetof(QCowHeader, incompatible_features),
475 &val, sizeof(val));
476 if (ret < 0) {
477 return ret;
478 }
479 ret = bdrv_flush(bs->file->bs);
480 if (ret < 0) {
481 return ret;
482 }
483
484 /* Only treat image as dirty if the header was updated successfully */
485 s->incompatible_features |= QCOW2_INCOMPAT_DIRTY;
486 return 0;
487 }
488
489 /*
490 * Clears the dirty bit and flushes before if necessary. Only call this
491 * function when there are no pending requests, it does not guard against
492 * concurrent requests dirtying the image.
493 */
494 static int qcow2_mark_clean(BlockDriverState *bs)
495 {
496 BDRVQcow2State *s = bs->opaque;
497
498 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
499 int ret;
500
501 s->incompatible_features &= ~QCOW2_INCOMPAT_DIRTY;
502
503 ret = qcow2_flush_caches(bs);
504 if (ret < 0) {
505 return ret;
506 }
507
508 return qcow2_update_header(bs);
509 }
510 return 0;
511 }
512
513 /*
514 * Marks the image as corrupt.
515 */
516 int qcow2_mark_corrupt(BlockDriverState *bs)
517 {
518 BDRVQcow2State *s = bs->opaque;
519
520 s->incompatible_features |= QCOW2_INCOMPAT_CORRUPT;
521 return qcow2_update_header(bs);
522 }
523
524 /*
525 * Marks the image as consistent, i.e., unsets the corrupt bit, and flushes
526 * before if necessary.
527 */
528 int qcow2_mark_consistent(BlockDriverState *bs)
529 {
530 BDRVQcow2State *s = bs->opaque;
531
532 if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
533 int ret = qcow2_flush_caches(bs);
534 if (ret < 0) {
535 return ret;
536 }
537
538 s->incompatible_features &= ~QCOW2_INCOMPAT_CORRUPT;
539 return qcow2_update_header(bs);
540 }
541 return 0;
542 }
543
544 static int qcow2_check(BlockDriverState *bs, BdrvCheckResult *result,
545 BdrvCheckMode fix)
546 {
547 int ret = qcow2_check_refcounts(bs, result, fix);
548 if (ret < 0) {
549 return ret;
550 }
551
552 if (fix && result->check_errors == 0 && result->corruptions == 0) {
553 ret = qcow2_mark_clean(bs);
554 if (ret < 0) {
555 return ret;
556 }
557 return qcow2_mark_consistent(bs);
558 }
559 return ret;
560 }
561
562 static int validate_table_offset(BlockDriverState *bs, uint64_t offset,
563 uint64_t entries, size_t entry_len)
564 {
565 BDRVQcow2State *s = bs->opaque;
566 uint64_t size;
567
568 /* Use signed INT64_MAX as the maximum even for uint64_t header fields,
569 * because values will be passed to qemu functions taking int64_t. */
570 if (entries > INT64_MAX / entry_len) {
571 return -EINVAL;
572 }
573
574 size = entries * entry_len;
575
576 if (INT64_MAX - size < offset) {
577 return -EINVAL;
578 }
579
580 /* Tables must be cluster aligned */
581 if (offset_into_cluster(s, offset) != 0) {
582 return -EINVAL;
583 }
584
585 return 0;
586 }
587
588 static QemuOptsList qcow2_runtime_opts = {
589 .name = "qcow2",
590 .head = QTAILQ_HEAD_INITIALIZER(qcow2_runtime_opts.head),
591 .desc = {
592 {
593 .name = QCOW2_OPT_LAZY_REFCOUNTS,
594 .type = QEMU_OPT_BOOL,
595 .help = "Postpone refcount updates",
596 },
597 {
598 .name = QCOW2_OPT_DISCARD_REQUEST,
599 .type = QEMU_OPT_BOOL,
600 .help = "Pass guest discard requests to the layer below",
601 },
602 {
603 .name = QCOW2_OPT_DISCARD_SNAPSHOT,
604 .type = QEMU_OPT_BOOL,
605 .help = "Generate discard requests when snapshot related space "
606 "is freed",
607 },
608 {
609 .name = QCOW2_OPT_DISCARD_OTHER,
610 .type = QEMU_OPT_BOOL,
611 .help = "Generate discard requests when other clusters are freed",
612 },
613 {
614 .name = QCOW2_OPT_OVERLAP,
615 .type = QEMU_OPT_STRING,
616 .help = "Selects which overlap checks to perform from a range of "
617 "templates (none, constant, cached, all)",
618 },
619 {
620 .name = QCOW2_OPT_OVERLAP_TEMPLATE,
621 .type = QEMU_OPT_STRING,
622 .help = "Selects which overlap checks to perform from a range of "
623 "templates (none, constant, cached, all)",
624 },
625 {
626 .name = QCOW2_OPT_OVERLAP_MAIN_HEADER,
627 .type = QEMU_OPT_BOOL,
628 .help = "Check for unintended writes into the main qcow2 header",
629 },
630 {
631 .name = QCOW2_OPT_OVERLAP_ACTIVE_L1,
632 .type = QEMU_OPT_BOOL,
633 .help = "Check for unintended writes into the active L1 table",
634 },
635 {
636 .name = QCOW2_OPT_OVERLAP_ACTIVE_L2,
637 .type = QEMU_OPT_BOOL,
638 .help = "Check for unintended writes into an active L2 table",
639 },
640 {
641 .name = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
642 .type = QEMU_OPT_BOOL,
643 .help = "Check for unintended writes into the refcount table",
644 },
645 {
646 .name = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
647 .type = QEMU_OPT_BOOL,
648 .help = "Check for unintended writes into a refcount block",
649 },
650 {
651 .name = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
652 .type = QEMU_OPT_BOOL,
653 .help = "Check for unintended writes into the snapshot table",
654 },
655 {
656 .name = QCOW2_OPT_OVERLAP_INACTIVE_L1,
657 .type = QEMU_OPT_BOOL,
658 .help = "Check for unintended writes into an inactive L1 table",
659 },
660 {
661 .name = QCOW2_OPT_OVERLAP_INACTIVE_L2,
662 .type = QEMU_OPT_BOOL,
663 .help = "Check for unintended writes into an inactive L2 table",
664 },
665 {
666 .name = QCOW2_OPT_CACHE_SIZE,
667 .type = QEMU_OPT_SIZE,
668 .help = "Maximum combined metadata (L2 tables and refcount blocks) "
669 "cache size",
670 },
671 {
672 .name = QCOW2_OPT_L2_CACHE_SIZE,
673 .type = QEMU_OPT_SIZE,
674 .help = "Maximum L2 table cache size",
675 },
676 {
677 .name = QCOW2_OPT_L2_CACHE_ENTRY_SIZE,
678 .type = QEMU_OPT_SIZE,
679 .help = "Size of each entry in the L2 cache",
680 },
681 {
682 .name = QCOW2_OPT_REFCOUNT_CACHE_SIZE,
683 .type = QEMU_OPT_SIZE,
684 .help = "Maximum refcount block cache size",
685 },
686 {
687 .name = QCOW2_OPT_CACHE_CLEAN_INTERVAL,
688 .type = QEMU_OPT_NUMBER,
689 .help = "Clean unused cache entries after this time (in seconds)",
690 },
691 BLOCK_CRYPTO_OPT_DEF_KEY_SECRET("encrypt.",
692 "ID of secret providing qcow2 AES key or LUKS passphrase"),
693 { /* end of list */ }
694 },
695 };
696
697 static const char *overlap_bool_option_names[QCOW2_OL_MAX_BITNR] = {
698 [QCOW2_OL_MAIN_HEADER_BITNR] = QCOW2_OPT_OVERLAP_MAIN_HEADER,
699 [QCOW2_OL_ACTIVE_L1_BITNR] = QCOW2_OPT_OVERLAP_ACTIVE_L1,
700 [QCOW2_OL_ACTIVE_L2_BITNR] = QCOW2_OPT_OVERLAP_ACTIVE_L2,
701 [QCOW2_OL_REFCOUNT_TABLE_BITNR] = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
702 [QCOW2_OL_REFCOUNT_BLOCK_BITNR] = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
703 [QCOW2_OL_SNAPSHOT_TABLE_BITNR] = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
704 [QCOW2_OL_INACTIVE_L1_BITNR] = QCOW2_OPT_OVERLAP_INACTIVE_L1,
705 [QCOW2_OL_INACTIVE_L2_BITNR] = QCOW2_OPT_OVERLAP_INACTIVE_L2,
706 };
707
708 static void cache_clean_timer_cb(void *opaque)
709 {
710 BlockDriverState *bs = opaque;
711 BDRVQcow2State *s = bs->opaque;
712 qcow2_cache_clean_unused(s->l2_table_cache);
713 qcow2_cache_clean_unused(s->refcount_block_cache);
714 timer_mod(s->cache_clean_timer, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) +
715 (int64_t) s->cache_clean_interval * 1000);
716 }
717
718 static void cache_clean_timer_init(BlockDriverState *bs, AioContext *context)
719 {
720 BDRVQcow2State *s = bs->opaque;
721 if (s->cache_clean_interval > 0) {
722 s->cache_clean_timer = aio_timer_new(context, QEMU_CLOCK_VIRTUAL,
723 SCALE_MS, cache_clean_timer_cb,
724 bs);
725 timer_mod(s->cache_clean_timer, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) +
726 (int64_t) s->cache_clean_interval * 1000);
727 }
728 }
729
730 static void cache_clean_timer_del(BlockDriverState *bs)
731 {
732 BDRVQcow2State *s = bs->opaque;
733 if (s->cache_clean_timer) {
734 timer_del(s->cache_clean_timer);
735 timer_free(s->cache_clean_timer);
736 s->cache_clean_timer = NULL;
737 }
738 }
739
740 static void qcow2_detach_aio_context(BlockDriverState *bs)
741 {
742 cache_clean_timer_del(bs);
743 }
744
745 static void qcow2_attach_aio_context(BlockDriverState *bs,
746 AioContext *new_context)
747 {
748 cache_clean_timer_init(bs, new_context);
749 }
750
751 static void read_cache_sizes(BlockDriverState *bs, QemuOpts *opts,
752 uint64_t *l2_cache_size,
753 uint64_t *l2_cache_entry_size,
754 uint64_t *refcount_cache_size, Error **errp)
755 {
756 BDRVQcow2State *s = bs->opaque;
757 uint64_t combined_cache_size;
758 bool l2_cache_size_set, refcount_cache_size_set, combined_cache_size_set;
759
760 combined_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_CACHE_SIZE);
761 l2_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_L2_CACHE_SIZE);
762 refcount_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
763
764 combined_cache_size = qemu_opt_get_size(opts, QCOW2_OPT_CACHE_SIZE, 0);
765 *l2_cache_size = qemu_opt_get_size(opts, QCOW2_OPT_L2_CACHE_SIZE, 0);
766 *refcount_cache_size = qemu_opt_get_size(opts,
767 QCOW2_OPT_REFCOUNT_CACHE_SIZE, 0);
768
769 *l2_cache_entry_size = qemu_opt_get_size(
770 opts, QCOW2_OPT_L2_CACHE_ENTRY_SIZE, s->cluster_size);
771
772 if (combined_cache_size_set) {
773 if (l2_cache_size_set && refcount_cache_size_set) {
774 error_setg(errp, QCOW2_OPT_CACHE_SIZE ", " QCOW2_OPT_L2_CACHE_SIZE
775 " and " QCOW2_OPT_REFCOUNT_CACHE_SIZE " may not be set "
776 "the same time");
777 return;
778 } else if (*l2_cache_size > combined_cache_size) {
779 error_setg(errp, QCOW2_OPT_L2_CACHE_SIZE " may not exceed "
780 QCOW2_OPT_CACHE_SIZE);
781 return;
782 } else if (*refcount_cache_size > combined_cache_size) {
783 error_setg(errp, QCOW2_OPT_REFCOUNT_CACHE_SIZE " may not exceed "
784 QCOW2_OPT_CACHE_SIZE);
785 return;
786 }
787
788 if (l2_cache_size_set) {
789 *refcount_cache_size = combined_cache_size - *l2_cache_size;
790 } else if (refcount_cache_size_set) {
791 *l2_cache_size = combined_cache_size - *refcount_cache_size;
792 } else {
793 *refcount_cache_size = combined_cache_size
794 / (DEFAULT_L2_REFCOUNT_SIZE_RATIO + 1);
795 *l2_cache_size = combined_cache_size - *refcount_cache_size;
796 }
797 } else {
798 if (!l2_cache_size_set && !refcount_cache_size_set) {
799 *l2_cache_size = MAX(DEFAULT_L2_CACHE_BYTE_SIZE,
800 (uint64_t)DEFAULT_L2_CACHE_CLUSTERS
801 * s->cluster_size);
802 *refcount_cache_size = *l2_cache_size
803 / DEFAULT_L2_REFCOUNT_SIZE_RATIO;
804 } else if (!l2_cache_size_set) {
805 *l2_cache_size = *refcount_cache_size
806 * DEFAULT_L2_REFCOUNT_SIZE_RATIO;
807 } else if (!refcount_cache_size_set) {
808 *refcount_cache_size = *l2_cache_size
809 / DEFAULT_L2_REFCOUNT_SIZE_RATIO;
810 }
811 }
812
813 if (*l2_cache_entry_size < (1 << MIN_CLUSTER_BITS) ||
814 *l2_cache_entry_size > s->cluster_size ||
815 !is_power_of_2(*l2_cache_entry_size)) {
816 error_setg(errp, "L2 cache entry size must be a power of two "
817 "between %d and the cluster size (%d)",
818 1 << MIN_CLUSTER_BITS, s->cluster_size);
819 return;
820 }
821 }
822
823 typedef struct Qcow2ReopenState {
824 Qcow2Cache *l2_table_cache;
825 Qcow2Cache *refcount_block_cache;
826 int l2_slice_size; /* Number of entries in a slice of the L2 table */
827 bool use_lazy_refcounts;
828 int overlap_check;
829 bool discard_passthrough[QCOW2_DISCARD_MAX];
830 uint64_t cache_clean_interval;
831 QCryptoBlockOpenOptions *crypto_opts; /* Disk encryption runtime options */
832 } Qcow2ReopenState;
833
834 static int qcow2_update_options_prepare(BlockDriverState *bs,
835 Qcow2ReopenState *r,
836 QDict *options, int flags,
837 Error **errp)
838 {
839 BDRVQcow2State *s = bs->opaque;
840 QemuOpts *opts = NULL;
841 const char *opt_overlap_check, *opt_overlap_check_template;
842 int overlap_check_template = 0;
843 uint64_t l2_cache_size, l2_cache_entry_size, refcount_cache_size;
844 int i;
845 const char *encryptfmt;
846 QDict *encryptopts = NULL;
847 Error *local_err = NULL;
848 int ret;
849
850 qdict_extract_subqdict(options, &encryptopts, "encrypt.");
851 encryptfmt = qdict_get_try_str(encryptopts, "format");
852
853 opts = qemu_opts_create(&qcow2_runtime_opts, NULL, 0, &error_abort);
854 qemu_opts_absorb_qdict(opts, options, &local_err);
855 if (local_err) {
856 error_propagate(errp, local_err);
857 ret = -EINVAL;
858 goto fail;
859 }
860
861 /* get L2 table/refcount block cache size from command line options */
862 read_cache_sizes(bs, opts, &l2_cache_size, &l2_cache_entry_size,
863 &refcount_cache_size, &local_err);
864 if (local_err) {
865 error_propagate(errp, local_err);
866 ret = -EINVAL;
867 goto fail;
868 }
869
870 l2_cache_size /= l2_cache_entry_size;
871 if (l2_cache_size < MIN_L2_CACHE_SIZE) {
872 l2_cache_size = MIN_L2_CACHE_SIZE;
873 }
874 if (l2_cache_size > INT_MAX) {
875 error_setg(errp, "L2 cache size too big");
876 ret = -EINVAL;
877 goto fail;
878 }
879
880 refcount_cache_size /= s->cluster_size;
881 if (refcount_cache_size < MIN_REFCOUNT_CACHE_SIZE) {
882 refcount_cache_size = MIN_REFCOUNT_CACHE_SIZE;
883 }
884 if (refcount_cache_size > INT_MAX) {
885 error_setg(errp, "Refcount cache size too big");
886 ret = -EINVAL;
887 goto fail;
888 }
889
890 /* alloc new L2 table/refcount block cache, flush old one */
891 if (s->l2_table_cache) {
892 ret = qcow2_cache_flush(bs, s->l2_table_cache);
893 if (ret) {
894 error_setg_errno(errp, -ret, "Failed to flush the L2 table cache");
895 goto fail;
896 }
897 }
898
899 if (s->refcount_block_cache) {
900 ret = qcow2_cache_flush(bs, s->refcount_block_cache);
901 if (ret) {
902 error_setg_errno(errp, -ret,
903 "Failed to flush the refcount block cache");
904 goto fail;
905 }
906 }
907
908 r->l2_slice_size = l2_cache_entry_size / sizeof(uint64_t);
909 r->l2_table_cache = qcow2_cache_create(bs, l2_cache_size,
910 l2_cache_entry_size);
911 r->refcount_block_cache = qcow2_cache_create(bs, refcount_cache_size,
912 s->cluster_size);
913 if (r->l2_table_cache == NULL || r->refcount_block_cache == NULL) {
914 error_setg(errp, "Could not allocate metadata caches");
915 ret = -ENOMEM;
916 goto fail;
917 }
918
919 /* New interval for cache cleanup timer */
920 r->cache_clean_interval =
921 qemu_opt_get_number(opts, QCOW2_OPT_CACHE_CLEAN_INTERVAL,
922 s->cache_clean_interval);
923 #ifndef CONFIG_LINUX
924 if (r->cache_clean_interval != 0) {
925 error_setg(errp, QCOW2_OPT_CACHE_CLEAN_INTERVAL
926 " not supported on this host");
927 ret = -EINVAL;
928 goto fail;
929 }
930 #endif
931 if (r->cache_clean_interval > UINT_MAX) {
932 error_setg(errp, "Cache clean interval too big");
933 ret = -EINVAL;
934 goto fail;
935 }
936
937 /* lazy-refcounts; flush if going from enabled to disabled */
938 r->use_lazy_refcounts = qemu_opt_get_bool(opts, QCOW2_OPT_LAZY_REFCOUNTS,
939 (s->compatible_features & QCOW2_COMPAT_LAZY_REFCOUNTS));
940 if (r->use_lazy_refcounts && s->qcow_version < 3) {
941 error_setg(errp, "Lazy refcounts require a qcow2 image with at least "
942 "qemu 1.1 compatibility level");
943 ret = -EINVAL;
944 goto fail;
945 }
946
947 if (s->use_lazy_refcounts && !r->use_lazy_refcounts) {
948 ret = qcow2_mark_clean(bs);
949 if (ret < 0) {
950 error_setg_errno(errp, -ret, "Failed to disable lazy refcounts");
951 goto fail;
952 }
953 }
954
955 /* Overlap check options */
956 opt_overlap_check = qemu_opt_get(opts, QCOW2_OPT_OVERLAP);
957 opt_overlap_check_template = qemu_opt_get(opts, QCOW2_OPT_OVERLAP_TEMPLATE);
958 if (opt_overlap_check_template && opt_overlap_check &&
959 strcmp(opt_overlap_check_template, opt_overlap_check))
960 {
961 error_setg(errp, "Conflicting values for qcow2 options '"
962 QCOW2_OPT_OVERLAP "' ('%s') and '" QCOW2_OPT_OVERLAP_TEMPLATE
963 "' ('%s')", opt_overlap_check, opt_overlap_check_template);
964 ret = -EINVAL;
965 goto fail;
966 }
967 if (!opt_overlap_check) {
968 opt_overlap_check = opt_overlap_check_template ?: "cached";
969 }
970
971 if (!strcmp(opt_overlap_check, "none")) {
972 overlap_check_template = 0;
973 } else if (!strcmp(opt_overlap_check, "constant")) {
974 overlap_check_template = QCOW2_OL_CONSTANT;
975 } else if (!strcmp(opt_overlap_check, "cached")) {
976 overlap_check_template = QCOW2_OL_CACHED;
977 } else if (!strcmp(opt_overlap_check, "all")) {
978 overlap_check_template = QCOW2_OL_ALL;
979 } else {
980 error_setg(errp, "Unsupported value '%s' for qcow2 option "
981 "'overlap-check'. Allowed are any of the following: "
982 "none, constant, cached, all", opt_overlap_check);
983 ret = -EINVAL;
984 goto fail;
985 }
986
987 r->overlap_check = 0;
988 for (i = 0; i < QCOW2_OL_MAX_BITNR; i++) {
989 /* overlap-check defines a template bitmask, but every flag may be
990 * overwritten through the associated boolean option */
991 r->overlap_check |=
992 qemu_opt_get_bool(opts, overlap_bool_option_names[i],
993 overlap_check_template & (1 << i)) << i;
994 }
995
996 r->discard_passthrough[QCOW2_DISCARD_NEVER] = false;
997 r->discard_passthrough[QCOW2_DISCARD_ALWAYS] = true;
998 r->discard_passthrough[QCOW2_DISCARD_REQUEST] =
999 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_REQUEST,
1000 flags & BDRV_O_UNMAP);
1001 r->discard_passthrough[QCOW2_DISCARD_SNAPSHOT] =
1002 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_SNAPSHOT, true);
1003 r->discard_passthrough[QCOW2_DISCARD_OTHER] =
1004 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_OTHER, false);
1005
1006 switch (s->crypt_method_header) {
1007 case QCOW_CRYPT_NONE:
1008 if (encryptfmt) {
1009 error_setg(errp, "No encryption in image header, but options "
1010 "specified format '%s'", encryptfmt);
1011 ret = -EINVAL;
1012 goto fail;
1013 }
1014 break;
1015
1016 case QCOW_CRYPT_AES:
1017 if (encryptfmt && !g_str_equal(encryptfmt, "aes")) {
1018 error_setg(errp,
1019 "Header reported 'aes' encryption format but "
1020 "options specify '%s'", encryptfmt);
1021 ret = -EINVAL;
1022 goto fail;
1023 }
1024 qdict_del(encryptopts, "format");
1025 r->crypto_opts = block_crypto_open_opts_init(
1026 Q_CRYPTO_BLOCK_FORMAT_QCOW, encryptopts, errp);
1027 break;
1028
1029 case QCOW_CRYPT_LUKS:
1030 if (encryptfmt && !g_str_equal(encryptfmt, "luks")) {
1031 error_setg(errp,
1032 "Header reported 'luks' encryption format but "
1033 "options specify '%s'", encryptfmt);
1034 ret = -EINVAL;
1035 goto fail;
1036 }
1037 qdict_del(encryptopts, "format");
1038 r->crypto_opts = block_crypto_open_opts_init(
1039 Q_CRYPTO_BLOCK_FORMAT_LUKS, encryptopts, errp);
1040 break;
1041
1042 default:
1043 error_setg(errp, "Unsupported encryption method %d",
1044 s->crypt_method_header);
1045 break;
1046 }
1047 if (s->crypt_method_header != QCOW_CRYPT_NONE && !r->crypto_opts) {
1048 ret = -EINVAL;
1049 goto fail;
1050 }
1051
1052 ret = 0;
1053 fail:
1054 QDECREF(encryptopts);
1055 qemu_opts_del(opts);
1056 opts = NULL;
1057 return ret;
1058 }
1059
1060 static void qcow2_update_options_commit(BlockDriverState *bs,
1061 Qcow2ReopenState *r)
1062 {
1063 BDRVQcow2State *s = bs->opaque;
1064 int i;
1065
1066 if (s->l2_table_cache) {
1067 qcow2_cache_destroy(s->l2_table_cache);
1068 }
1069 if (s->refcount_block_cache) {
1070 qcow2_cache_destroy(s->refcount_block_cache);
1071 }
1072 s->l2_table_cache = r->l2_table_cache;
1073 s->refcount_block_cache = r->refcount_block_cache;
1074 s->l2_slice_size = r->l2_slice_size;
1075
1076 s->overlap_check = r->overlap_check;
1077 s->use_lazy_refcounts = r->use_lazy_refcounts;
1078
1079 for (i = 0; i < QCOW2_DISCARD_MAX; i++) {
1080 s->discard_passthrough[i] = r->discard_passthrough[i];
1081 }
1082
1083 if (s->cache_clean_interval != r->cache_clean_interval) {
1084 cache_clean_timer_del(bs);
1085 s->cache_clean_interval = r->cache_clean_interval;
1086 cache_clean_timer_init(bs, bdrv_get_aio_context(bs));
1087 }
1088
1089 qapi_free_QCryptoBlockOpenOptions(s->crypto_opts);
1090 s->crypto_opts = r->crypto_opts;
1091 }
1092
1093 static void qcow2_update_options_abort(BlockDriverState *bs,
1094 Qcow2ReopenState *r)
1095 {
1096 if (r->l2_table_cache) {
1097 qcow2_cache_destroy(r->l2_table_cache);
1098 }
1099 if (r->refcount_block_cache) {
1100 qcow2_cache_destroy(r->refcount_block_cache);
1101 }
1102 qapi_free_QCryptoBlockOpenOptions(r->crypto_opts);
1103 }
1104
1105 static int qcow2_update_options(BlockDriverState *bs, QDict *options,
1106 int flags, Error **errp)
1107 {
1108 Qcow2ReopenState r = {};
1109 int ret;
1110
1111 ret = qcow2_update_options_prepare(bs, &r, options, flags, errp);
1112 if (ret >= 0) {
1113 qcow2_update_options_commit(bs, &r);
1114 } else {
1115 qcow2_update_options_abort(bs, &r);
1116 }
1117
1118 return ret;
1119 }
1120
1121 /* Called with s->lock held. */
1122 static int coroutine_fn qcow2_do_open(BlockDriverState *bs, QDict *options,
1123 int flags, Error **errp)
1124 {
1125 BDRVQcow2State *s = bs->opaque;
1126 unsigned int len, i;
1127 int ret = 0;
1128 QCowHeader header;
1129 Error *local_err = NULL;
1130 uint64_t ext_end;
1131 uint64_t l1_vm_state_index;
1132 bool update_header = false;
1133
1134 ret = bdrv_pread(bs->file, 0, &header, sizeof(header));
1135 if (ret < 0) {
1136 error_setg_errno(errp, -ret, "Could not read qcow2 header");
1137 goto fail;
1138 }
1139 be32_to_cpus(&header.magic);
1140 be32_to_cpus(&header.version);
1141 be64_to_cpus(&header.backing_file_offset);
1142 be32_to_cpus(&header.backing_file_size);
1143 be64_to_cpus(&header.size);
1144 be32_to_cpus(&header.cluster_bits);
1145 be32_to_cpus(&header.crypt_method);
1146 be64_to_cpus(&header.l1_table_offset);
1147 be32_to_cpus(&header.l1_size);
1148 be64_to_cpus(&header.refcount_table_offset);
1149 be32_to_cpus(&header.refcount_table_clusters);
1150 be64_to_cpus(&header.snapshots_offset);
1151 be32_to_cpus(&header.nb_snapshots);
1152
1153 if (header.magic != QCOW_MAGIC) {
1154 error_setg(errp, "Image is not in qcow2 format");
1155 ret = -EINVAL;
1156 goto fail;
1157 }
1158 if (header.version < 2 || header.version > 3) {
1159 error_setg(errp, "Unsupported qcow2 version %" PRIu32, header.version);
1160 ret = -ENOTSUP;
1161 goto fail;
1162 }
1163
1164 s->qcow_version = header.version;
1165
1166 /* Initialise cluster size */
1167 if (header.cluster_bits < MIN_CLUSTER_BITS ||
1168 header.cluster_bits > MAX_CLUSTER_BITS) {
1169 error_setg(errp, "Unsupported cluster size: 2^%" PRIu32,
1170 header.cluster_bits);
1171 ret = -EINVAL;
1172 goto fail;
1173 }
1174
1175 s->cluster_bits = header.cluster_bits;
1176 s->cluster_size = 1 << s->cluster_bits;
1177 s->cluster_sectors = 1 << (s->cluster_bits - BDRV_SECTOR_BITS);
1178
1179 /* Initialise version 3 header fields */
1180 if (header.version == 2) {
1181 header.incompatible_features = 0;
1182 header.compatible_features = 0;
1183 header.autoclear_features = 0;
1184 header.refcount_order = 4;
1185 header.header_length = 72;
1186 } else {
1187 be64_to_cpus(&header.incompatible_features);
1188 be64_to_cpus(&header.compatible_features);
1189 be64_to_cpus(&header.autoclear_features);
1190 be32_to_cpus(&header.refcount_order);
1191 be32_to_cpus(&header.header_length);
1192
1193 if (header.header_length < 104) {
1194 error_setg(errp, "qcow2 header too short");
1195 ret = -EINVAL;
1196 goto fail;
1197 }
1198 }
1199
1200 if (header.header_length > s->cluster_size) {
1201 error_setg(errp, "qcow2 header exceeds cluster size");
1202 ret = -EINVAL;
1203 goto fail;
1204 }
1205
1206 if (header.header_length > sizeof(header)) {
1207 s->unknown_header_fields_size = header.header_length - sizeof(header);
1208 s->unknown_header_fields = g_malloc(s->unknown_header_fields_size);
1209 ret = bdrv_pread(bs->file, sizeof(header), s->unknown_header_fields,
1210 s->unknown_header_fields_size);
1211 if (ret < 0) {
1212 error_setg_errno(errp, -ret, "Could not read unknown qcow2 header "
1213 "fields");
1214 goto fail;
1215 }
1216 }
1217
1218 if (header.backing_file_offset > s->cluster_size) {
1219 error_setg(errp, "Invalid backing file offset");
1220 ret = -EINVAL;
1221 goto fail;
1222 }
1223
1224 if (header.backing_file_offset) {
1225 ext_end = header.backing_file_offset;
1226 } else {
1227 ext_end = 1 << header.cluster_bits;
1228 }
1229
1230 /* Handle feature bits */
1231 s->incompatible_features = header.incompatible_features;
1232 s->compatible_features = header.compatible_features;
1233 s->autoclear_features = header.autoclear_features;
1234
1235 if (s->incompatible_features & ~QCOW2_INCOMPAT_MASK) {
1236 void *feature_table = NULL;
1237 qcow2_read_extensions(bs, header.header_length, ext_end,
1238 &feature_table, flags, NULL, NULL);
1239 report_unsupported_feature(errp, feature_table,
1240 s->incompatible_features &
1241 ~QCOW2_INCOMPAT_MASK);
1242 ret = -ENOTSUP;
1243 g_free(feature_table);
1244 goto fail;
1245 }
1246
1247 if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
1248 /* Corrupt images may not be written to unless they are being repaired
1249 */
1250 if ((flags & BDRV_O_RDWR) && !(flags & BDRV_O_CHECK)) {
1251 error_setg(errp, "qcow2: Image is corrupt; cannot be opened "
1252 "read/write");
1253 ret = -EACCES;
1254 goto fail;
1255 }
1256 }
1257
1258 /* Check support for various header values */
1259 if (header.refcount_order > 6) {
1260 error_setg(errp, "Reference count entry width too large; may not "
1261 "exceed 64 bits");
1262 ret = -EINVAL;
1263 goto fail;
1264 }
1265 s->refcount_order = header.refcount_order;
1266 s->refcount_bits = 1 << s->refcount_order;
1267 s->refcount_max = UINT64_C(1) << (s->refcount_bits - 1);
1268 s->refcount_max += s->refcount_max - 1;
1269
1270 s->crypt_method_header = header.crypt_method;
1271 if (s->crypt_method_header) {
1272 if (bdrv_uses_whitelist() &&
1273 s->crypt_method_header == QCOW_CRYPT_AES) {
1274 error_setg(errp,
1275 "Use of AES-CBC encrypted qcow2 images is no longer "
1276 "supported in system emulators");
1277 error_append_hint(errp,
1278 "You can use 'qemu-img convert' to convert your "
1279 "image to an alternative supported format, such "
1280 "as unencrypted qcow2, or raw with the LUKS "
1281 "format instead.\n");
1282 ret = -ENOSYS;
1283 goto fail;
1284 }
1285
1286 if (s->crypt_method_header == QCOW_CRYPT_AES) {
1287 s->crypt_physical_offset = false;
1288 } else {
1289 /* Assuming LUKS and any future crypt methods we
1290 * add will all use physical offsets, due to the
1291 * fact that the alternative is insecure... */
1292 s->crypt_physical_offset = true;
1293 }
1294
1295 bs->encrypted = true;
1296 }
1297
1298 s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */
1299 s->l2_size = 1 << s->l2_bits;
1300 /* 2^(s->refcount_order - 3) is the refcount width in bytes */
1301 s->refcount_block_bits = s->cluster_bits - (s->refcount_order - 3);
1302 s->refcount_block_size = 1 << s->refcount_block_bits;
1303 bs->total_sectors = header.size / 512;
1304 s->csize_shift = (62 - (s->cluster_bits - 8));
1305 s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;
1306 s->cluster_offset_mask = (1LL << s->csize_shift) - 1;
1307
1308 s->refcount_table_offset = header.refcount_table_offset;
1309 s->refcount_table_size =
1310 header.refcount_table_clusters << (s->cluster_bits - 3);
1311
1312 if (header.refcount_table_clusters > qcow2_max_refcount_clusters(s)) {
1313 error_setg(errp, "Reference count table too large");
1314 ret = -EINVAL;
1315 goto fail;
1316 }
1317
1318 if (header.refcount_table_clusters == 0 && !(flags & BDRV_O_CHECK)) {
1319 error_setg(errp, "Image does not contain a reference count table");
1320 ret = -EINVAL;
1321 goto fail;
1322 }
1323
1324 ret = validate_table_offset(bs, s->refcount_table_offset,
1325 s->refcount_table_size, sizeof(uint64_t));
1326 if (ret < 0) {
1327 error_setg(errp, "Invalid reference count table offset");
1328 goto fail;
1329 }
1330
1331 /* Snapshot table offset/length */
1332 if (header.nb_snapshots > QCOW_MAX_SNAPSHOTS) {
1333 error_setg(errp, "Too many snapshots");
1334 ret = -EINVAL;
1335 goto fail;
1336 }
1337
1338 ret = validate_table_offset(bs, header.snapshots_offset,
1339 header.nb_snapshots,
1340 sizeof(QCowSnapshotHeader));
1341 if (ret < 0) {
1342 error_setg(errp, "Invalid snapshot table offset");
1343 goto fail;
1344 }
1345
1346 /* read the level 1 table */
1347 if (header.l1_size > QCOW_MAX_L1_SIZE / sizeof(uint64_t)) {
1348 error_setg(errp, "Active L1 table too large");
1349 ret = -EFBIG;
1350 goto fail;
1351 }
1352 s->l1_size = header.l1_size;
1353
1354 l1_vm_state_index = size_to_l1(s, header.size);
1355 if (l1_vm_state_index > INT_MAX) {
1356 error_setg(errp, "Image is too big");
1357 ret = -EFBIG;
1358 goto fail;
1359 }
1360 s->l1_vm_state_index = l1_vm_state_index;
1361
1362 /* the L1 table must contain at least enough entries to put
1363 header.size bytes */
1364 if (s->l1_size < s->l1_vm_state_index) {
1365 error_setg(errp, "L1 table is too small");
1366 ret = -EINVAL;
1367 goto fail;
1368 }
1369
1370 ret = validate_table_offset(bs, header.l1_table_offset,
1371 header.l1_size, sizeof(uint64_t));
1372 if (ret < 0) {
1373 error_setg(errp, "Invalid L1 table offset");
1374 goto fail;
1375 }
1376 s->l1_table_offset = header.l1_table_offset;
1377
1378
1379 if (s->l1_size > 0) {
1380 s->l1_table = qemu_try_blockalign(bs->file->bs,
1381 ROUND_UP(s->l1_size * sizeof(uint64_t), 512));
1382 if (s->l1_table == NULL) {
1383 error_setg(errp, "Could not allocate L1 table");
1384 ret = -ENOMEM;
1385 goto fail;
1386 }
1387 ret = bdrv_pread(bs->file, s->l1_table_offset, s->l1_table,
1388 s->l1_size * sizeof(uint64_t));
1389 if (ret < 0) {
1390 error_setg_errno(errp, -ret, "Could not read L1 table");
1391 goto fail;
1392 }
1393 for(i = 0;i < s->l1_size; i++) {
1394 be64_to_cpus(&s->l1_table[i]);
1395 }
1396 }
1397
1398 /* Parse driver-specific options */
1399 ret = qcow2_update_options(bs, options, flags, errp);
1400 if (ret < 0) {
1401 goto fail;
1402 }
1403
1404 s->cluster_cache_offset = -1;
1405 s->flags = flags;
1406
1407 ret = qcow2_refcount_init(bs);
1408 if (ret != 0) {
1409 error_setg_errno(errp, -ret, "Could not initialize refcount handling");
1410 goto fail;
1411 }
1412
1413 QLIST_INIT(&s->cluster_allocs);
1414 QTAILQ_INIT(&s->discards);
1415
1416 /* read qcow2 extensions */
1417 if (qcow2_read_extensions(bs, header.header_length, ext_end, NULL,
1418 flags, &update_header, &local_err)) {
1419 error_propagate(errp, local_err);
1420 ret = -EINVAL;
1421 goto fail;
1422 }
1423
1424 /* qcow2_read_extension may have set up the crypto context
1425 * if the crypt method needs a header region, some methods
1426 * don't need header extensions, so must check here
1427 */
1428 if (s->crypt_method_header && !s->crypto) {
1429 if (s->crypt_method_header == QCOW_CRYPT_AES) {
1430 unsigned int cflags = 0;
1431 if (flags & BDRV_O_NO_IO) {
1432 cflags |= QCRYPTO_BLOCK_OPEN_NO_IO;
1433 }
1434 s->crypto = qcrypto_block_open(s->crypto_opts, "encrypt.",
1435 NULL, NULL, cflags, errp);
1436 if (!s->crypto) {
1437 ret = -EINVAL;
1438 goto fail;
1439 }
1440 } else if (!(flags & BDRV_O_NO_IO)) {
1441 error_setg(errp, "Missing CRYPTO header for crypt method %d",
1442 s->crypt_method_header);
1443 ret = -EINVAL;
1444 goto fail;
1445 }
1446 }
1447
1448 /* read the backing file name */
1449 if (header.backing_file_offset != 0) {
1450 len = header.backing_file_size;
1451 if (len > MIN(1023, s->cluster_size - header.backing_file_offset) ||
1452 len >= sizeof(bs->backing_file)) {
1453 error_setg(errp, "Backing file name too long");
1454 ret = -EINVAL;
1455 goto fail;
1456 }
1457 ret = bdrv_pread(bs->file, header.backing_file_offset,
1458 bs->backing_file, len);
1459 if (ret < 0) {
1460 error_setg_errno(errp, -ret, "Could not read backing file name");
1461 goto fail;
1462 }
1463 bs->backing_file[len] = '\0';
1464 s->image_backing_file = g_strdup(bs->backing_file);
1465 }
1466
1467 /* Internal snapshots */
1468 s->snapshots_offset = header.snapshots_offset;
1469 s->nb_snapshots = header.nb_snapshots;
1470
1471 ret = qcow2_read_snapshots(bs);
1472 if (ret < 0) {
1473 error_setg_errno(errp, -ret, "Could not read snapshots");
1474 goto fail;
1475 }
1476
1477 /* Clear unknown autoclear feature bits */
1478 update_header |= s->autoclear_features & ~QCOW2_AUTOCLEAR_MASK;
1479 update_header =
1480 update_header && !bs->read_only && !(flags & BDRV_O_INACTIVE);
1481 if (update_header) {
1482 s->autoclear_features &= QCOW2_AUTOCLEAR_MASK;
1483 }
1484
1485 if (qcow2_load_dirty_bitmaps(bs, &local_err)) {
1486 update_header = false;
1487 }
1488 if (local_err != NULL) {
1489 error_propagate(errp, local_err);
1490 ret = -EINVAL;
1491 goto fail;
1492 }
1493
1494 if (update_header) {
1495 ret = qcow2_update_header(bs);
1496 if (ret < 0) {
1497 error_setg_errno(errp, -ret, "Could not update qcow2 header");
1498 goto fail;
1499 }
1500 }
1501
1502 bs->supported_zero_flags = header.version >= 3 ? BDRV_REQ_MAY_UNMAP : 0;
1503
1504 /* Repair image if dirty */
1505 if (!(flags & (BDRV_O_CHECK | BDRV_O_INACTIVE)) && !bs->read_only &&
1506 (s->incompatible_features & QCOW2_INCOMPAT_DIRTY)) {
1507 BdrvCheckResult result = {0};
1508
1509 ret = qcow2_check(bs, &result, BDRV_FIX_ERRORS | BDRV_FIX_LEAKS);
1510 if (ret < 0 || result.check_errors) {
1511 if (ret >= 0) {
1512 ret = -EIO;
1513 }
1514 error_setg_errno(errp, -ret, "Could not repair dirty image");
1515 goto fail;
1516 }
1517 }
1518
1519 #ifdef DEBUG_ALLOC
1520 {
1521 BdrvCheckResult result = {0};
1522 qcow2_check_refcounts(bs, &result, 0);
1523 }
1524 #endif
1525 return ret;
1526
1527 fail:
1528 g_free(s->unknown_header_fields);
1529 cleanup_unknown_header_ext(bs);
1530 qcow2_free_snapshots(bs);
1531 qcow2_refcount_close(bs);
1532 qemu_vfree(s->l1_table);
1533 /* else pre-write overlap checks in cache_destroy may crash */
1534 s->l1_table = NULL;
1535 cache_clean_timer_del(bs);
1536 if (s->l2_table_cache) {
1537 qcow2_cache_destroy(s->l2_table_cache);
1538 }
1539 if (s->refcount_block_cache) {
1540 qcow2_cache_destroy(s->refcount_block_cache);
1541 }
1542 qcrypto_block_free(s->crypto);
1543 qapi_free_QCryptoBlockOpenOptions(s->crypto_opts);
1544 return ret;
1545 }
1546
1547 typedef struct QCow2OpenCo {
1548 BlockDriverState *bs;
1549 QDict *options;
1550 int flags;
1551 Error **errp;
1552 int ret;
1553 } QCow2OpenCo;
1554
1555 static void coroutine_fn qcow2_open_entry(void *opaque)
1556 {
1557 QCow2OpenCo *qoc = opaque;
1558 BDRVQcow2State *s = qoc->bs->opaque;
1559
1560 qemu_co_mutex_lock(&s->lock);
1561 qoc->ret = qcow2_do_open(qoc->bs, qoc->options, qoc->flags, qoc->errp);
1562 qemu_co_mutex_unlock(&s->lock);
1563 }
1564
1565 static int qcow2_open(BlockDriverState *bs, QDict *options, int flags,
1566 Error **errp)
1567 {
1568 BDRVQcow2State *s = bs->opaque;
1569 QCow2OpenCo qoc = {
1570 .bs = bs,
1571 .options = options,
1572 .flags = flags,
1573 .errp = errp,
1574 .ret = -EINPROGRESS
1575 };
1576
1577 bs->file = bdrv_open_child(NULL, options, "file", bs, &child_file,
1578 false, errp);
1579 if (!bs->file) {
1580 return -EINVAL;
1581 }
1582
1583 /* Initialise locks */
1584 qemu_co_mutex_init(&s->lock);
1585
1586 if (qemu_in_coroutine()) {
1587 /* From bdrv_co_create. */
1588 qcow2_open_entry(&qoc);
1589 } else {
1590 qemu_coroutine_enter(qemu_coroutine_create(qcow2_open_entry, &qoc));
1591 BDRV_POLL_WHILE(bs, qoc.ret == -EINPROGRESS);
1592 }
1593 return qoc.ret;
1594 }
1595
1596 static void qcow2_refresh_limits(BlockDriverState *bs, Error **errp)
1597 {
1598 BDRVQcow2State *s = bs->opaque;
1599
1600 if (bs->encrypted) {
1601 /* Encryption works on a sector granularity */
1602 bs->bl.request_alignment = BDRV_SECTOR_SIZE;
1603 }
1604 bs->bl.pwrite_zeroes_alignment = s->cluster_size;
1605 bs->bl.pdiscard_alignment = s->cluster_size;
1606 }
1607
1608 static int qcow2_reopen_prepare(BDRVReopenState *state,
1609 BlockReopenQueue *queue, Error **errp)
1610 {
1611 Qcow2ReopenState *r;
1612 int ret;
1613
1614 r = g_new0(Qcow2ReopenState, 1);
1615 state->opaque = r;
1616
1617 ret = qcow2_update_options_prepare(state->bs, r, state->options,
1618 state->flags, errp);
1619 if (ret < 0) {
1620 goto fail;
1621 }
1622
1623 /* We need to write out any unwritten data if we reopen read-only. */
1624 if ((state->flags & BDRV_O_RDWR) == 0) {
1625 ret = qcow2_reopen_bitmaps_ro(state->bs, errp);
1626 if (ret < 0) {
1627 goto fail;
1628 }
1629
1630 ret = bdrv_flush(state->bs);
1631 if (ret < 0) {
1632 goto fail;
1633 }
1634
1635 ret = qcow2_mark_clean(state->bs);
1636 if (ret < 0) {
1637 goto fail;
1638 }
1639 }
1640
1641 return 0;
1642
1643 fail:
1644 qcow2_update_options_abort(state->bs, r);
1645 g_free(r);
1646 return ret;
1647 }
1648
1649 static void qcow2_reopen_commit(BDRVReopenState *state)
1650 {
1651 qcow2_update_options_commit(state->bs, state->opaque);
1652 g_free(state->opaque);
1653 }
1654
1655 static void qcow2_reopen_abort(BDRVReopenState *state)
1656 {
1657 qcow2_update_options_abort(state->bs, state->opaque);
1658 g_free(state->opaque);
1659 }
1660
1661 static void qcow2_join_options(QDict *options, QDict *old_options)
1662 {
1663 bool has_new_overlap_template =
1664 qdict_haskey(options, QCOW2_OPT_OVERLAP) ||
1665 qdict_haskey(options, QCOW2_OPT_OVERLAP_TEMPLATE);
1666 bool has_new_total_cache_size =
1667 qdict_haskey(options, QCOW2_OPT_CACHE_SIZE);
1668 bool has_all_cache_options;
1669
1670 /* New overlap template overrides all old overlap options */
1671 if (has_new_overlap_template) {
1672 qdict_del(old_options, QCOW2_OPT_OVERLAP);
1673 qdict_del(old_options, QCOW2_OPT_OVERLAP_TEMPLATE);
1674 qdict_del(old_options, QCOW2_OPT_OVERLAP_MAIN_HEADER);
1675 qdict_del(old_options, QCOW2_OPT_OVERLAP_ACTIVE_L1);
1676 qdict_del(old_options, QCOW2_OPT_OVERLAP_ACTIVE_L2);
1677 qdict_del(old_options, QCOW2_OPT_OVERLAP_REFCOUNT_TABLE);
1678 qdict_del(old_options, QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK);
1679 qdict_del(old_options, QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE);
1680 qdict_del(old_options, QCOW2_OPT_OVERLAP_INACTIVE_L1);
1681 qdict_del(old_options, QCOW2_OPT_OVERLAP_INACTIVE_L2);
1682 }
1683
1684 /* New total cache size overrides all old options */
1685 if (qdict_haskey(options, QCOW2_OPT_CACHE_SIZE)) {
1686 qdict_del(old_options, QCOW2_OPT_L2_CACHE_SIZE);
1687 qdict_del(old_options, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
1688 }
1689
1690 qdict_join(options, old_options, false);
1691
1692 /*
1693 * If after merging all cache size options are set, an old total size is
1694 * overwritten. Do keep all options, however, if all three are new. The
1695 * resulting error message is what we want to happen.
1696 */
1697 has_all_cache_options =
1698 qdict_haskey(options, QCOW2_OPT_CACHE_SIZE) ||
1699 qdict_haskey(options, QCOW2_OPT_L2_CACHE_SIZE) ||
1700 qdict_haskey(options, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
1701
1702 if (has_all_cache_options && !has_new_total_cache_size) {
1703 qdict_del(options, QCOW2_OPT_CACHE_SIZE);
1704 }
1705 }
1706
1707 static int coroutine_fn qcow2_co_block_status(BlockDriverState *bs,
1708 bool want_zero,
1709 int64_t offset, int64_t count,
1710 int64_t *pnum, int64_t *map,
1711 BlockDriverState **file)
1712 {
1713 BDRVQcow2State *s = bs->opaque;
1714 uint64_t cluster_offset;
1715 int index_in_cluster, ret;
1716 unsigned int bytes;
1717 int status = 0;
1718
1719 bytes = MIN(INT_MAX, count);
1720 qemu_co_mutex_lock(&s->lock);
1721 ret = qcow2_get_cluster_offset(bs, offset, &bytes, &cluster_offset);
1722 qemu_co_mutex_unlock(&s->lock);
1723 if (ret < 0) {
1724 return ret;
1725 }
1726
1727 *pnum = bytes;
1728
1729 if (cluster_offset != 0 && ret != QCOW2_CLUSTER_COMPRESSED &&
1730 !s->crypto) {
1731 index_in_cluster = offset & (s->cluster_size - 1);
1732 *map = cluster_offset | index_in_cluster;
1733 *file = bs->file->bs;
1734 status |= BDRV_BLOCK_OFFSET_VALID;
1735 }
1736 if (ret == QCOW2_CLUSTER_ZERO_PLAIN || ret == QCOW2_CLUSTER_ZERO_ALLOC) {
1737 status |= BDRV_BLOCK_ZERO;
1738 } else if (ret != QCOW2_CLUSTER_UNALLOCATED) {
1739 status |= BDRV_BLOCK_DATA;
1740 }
1741 return status;
1742 }
1743
1744 static coroutine_fn int qcow2_co_preadv(BlockDriverState *bs, uint64_t offset,
1745 uint64_t bytes, QEMUIOVector *qiov,
1746 int flags)
1747 {
1748 BDRVQcow2State *s = bs->opaque;
1749 int offset_in_cluster;
1750 int ret;
1751 unsigned int cur_bytes; /* number of bytes in current iteration */
1752 uint64_t cluster_offset = 0;
1753 uint64_t bytes_done = 0;
1754 QEMUIOVector hd_qiov;
1755 uint8_t *cluster_data = NULL;
1756
1757 qemu_iovec_init(&hd_qiov, qiov->niov);
1758
1759 qemu_co_mutex_lock(&s->lock);
1760
1761 while (bytes != 0) {
1762
1763 /* prepare next request */
1764 cur_bytes = MIN(bytes, INT_MAX);
1765 if (s->crypto) {
1766 cur_bytes = MIN(cur_bytes,
1767 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
1768 }
1769
1770 ret = qcow2_get_cluster_offset(bs, offset, &cur_bytes, &cluster_offset);
1771 if (ret < 0) {
1772 goto fail;
1773 }
1774
1775 offset_in_cluster = offset_into_cluster(s, offset);
1776
1777 qemu_iovec_reset(&hd_qiov);
1778 qemu_iovec_concat(&hd_qiov, qiov, bytes_done, cur_bytes);
1779
1780 switch (ret) {
1781 case QCOW2_CLUSTER_UNALLOCATED:
1782
1783 if (bs->backing) {
1784 BLKDBG_EVENT(bs->file, BLKDBG_READ_BACKING_AIO);
1785 qemu_co_mutex_unlock(&s->lock);
1786 ret = bdrv_co_preadv(bs->backing, offset, cur_bytes,
1787 &hd_qiov, 0);
1788 qemu_co_mutex_lock(&s->lock);
1789 if (ret < 0) {
1790 goto fail;
1791 }
1792 } else {
1793 /* Note: in this case, no need to wait */
1794 qemu_iovec_memset(&hd_qiov, 0, 0, cur_bytes);
1795 }
1796 break;
1797
1798 case QCOW2_CLUSTER_ZERO_PLAIN:
1799 case QCOW2_CLUSTER_ZERO_ALLOC:
1800 qemu_iovec_memset(&hd_qiov, 0, 0, cur_bytes);
1801 break;
1802
1803 case QCOW2_CLUSTER_COMPRESSED:
1804 /* add AIO support for compressed blocks ? */
1805 ret = qcow2_decompress_cluster(bs, cluster_offset);
1806 if (ret < 0) {
1807 goto fail;
1808 }
1809
1810 qemu_iovec_from_buf(&hd_qiov, 0,
1811 s->cluster_cache + offset_in_cluster,
1812 cur_bytes);
1813 break;
1814
1815 case QCOW2_CLUSTER_NORMAL:
1816 if ((cluster_offset & 511) != 0) {
1817 ret = -EIO;
1818 goto fail;
1819 }
1820
1821 if (bs->encrypted) {
1822 assert(s->crypto);
1823
1824 /*
1825 * For encrypted images, read everything into a temporary
1826 * contiguous buffer on which the AES functions can work.
1827 */
1828 if (!cluster_data) {
1829 cluster_data =
1830 qemu_try_blockalign(bs->file->bs,
1831 QCOW_MAX_CRYPT_CLUSTERS
1832 * s->cluster_size);
1833 if (cluster_data == NULL) {
1834 ret = -ENOMEM;
1835 goto fail;
1836 }
1837 }
1838
1839 assert(cur_bytes <= QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
1840 qemu_iovec_reset(&hd_qiov);
1841 qemu_iovec_add(&hd_qiov, cluster_data, cur_bytes);
1842 }
1843
1844 BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);
1845 qemu_co_mutex_unlock(&s->lock);
1846 ret = bdrv_co_preadv(bs->file,
1847 cluster_offset + offset_in_cluster,
1848 cur_bytes, &hd_qiov, 0);
1849 qemu_co_mutex_lock(&s->lock);
1850 if (ret < 0) {
1851 goto fail;
1852 }
1853 if (bs->encrypted) {
1854 assert(s->crypto);
1855 assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);
1856 assert((cur_bytes & (BDRV_SECTOR_SIZE - 1)) == 0);
1857 if (qcrypto_block_decrypt(s->crypto,
1858 (s->crypt_physical_offset ?
1859 cluster_offset + offset_in_cluster :
1860 offset),
1861 cluster_data,
1862 cur_bytes,
1863 NULL) < 0) {
1864 ret = -EIO;
1865 goto fail;
1866 }
1867 qemu_iovec_from_buf(qiov, bytes_done, cluster_data, cur_bytes);
1868 }
1869 break;
1870
1871 default:
1872 g_assert_not_reached();
1873 ret = -EIO;
1874 goto fail;
1875 }
1876
1877 bytes -= cur_bytes;
1878 offset += cur_bytes;
1879 bytes_done += cur_bytes;
1880 }
1881 ret = 0;
1882
1883 fail:
1884 qemu_co_mutex_unlock(&s->lock);
1885
1886 qemu_iovec_destroy(&hd_qiov);
1887 qemu_vfree(cluster_data);
1888
1889 return ret;
1890 }
1891
1892 /* Check if it's possible to merge a write request with the writing of
1893 * the data from the COW regions */
1894 static bool merge_cow(uint64_t offset, unsigned bytes,
1895 QEMUIOVector *hd_qiov, QCowL2Meta *l2meta)
1896 {
1897 QCowL2Meta *m;
1898
1899 for (m = l2meta; m != NULL; m = m->next) {
1900 /* If both COW regions are empty then there's nothing to merge */
1901 if (m->cow_start.nb_bytes == 0 && m->cow_end.nb_bytes == 0) {
1902 continue;
1903 }
1904
1905 /* The data (middle) region must be immediately after the
1906 * start region */
1907 if (l2meta_cow_start(m) + m->cow_start.nb_bytes != offset) {
1908 continue;
1909 }
1910
1911 /* The end region must be immediately after the data (middle)
1912 * region */
1913 if (m->offset + m->cow_end.offset != offset + bytes) {
1914 continue;
1915 }
1916
1917 /* Make sure that adding both COW regions to the QEMUIOVector
1918 * does not exceed IOV_MAX */
1919 if (hd_qiov->niov > IOV_MAX - 2) {
1920 continue;
1921 }
1922
1923 m->data_qiov = hd_qiov;
1924 return true;
1925 }
1926
1927 return false;
1928 }
1929
1930 static coroutine_fn int qcow2_co_pwritev(BlockDriverState *bs, uint64_t offset,
1931 uint64_t bytes, QEMUIOVector *qiov,
1932 int flags)
1933 {
1934 BDRVQcow2State *s = bs->opaque;
1935 int offset_in_cluster;
1936 int ret;
1937 unsigned int cur_bytes; /* number of sectors in current iteration */
1938 uint64_t cluster_offset;
1939 QEMUIOVector hd_qiov;
1940 uint64_t bytes_done = 0;
1941 uint8_t *cluster_data = NULL;
1942 QCowL2Meta *l2meta = NULL;
1943
1944 trace_qcow2_writev_start_req(qemu_coroutine_self(), offset, bytes);
1945
1946 qemu_iovec_init(&hd_qiov, qiov->niov);
1947
1948 s->cluster_cache_offset = -1; /* disable compressed cache */
1949
1950 qemu_co_mutex_lock(&s->lock);
1951
1952 while (bytes != 0) {
1953
1954 l2meta = NULL;
1955
1956 trace_qcow2_writev_start_part(qemu_coroutine_self());
1957 offset_in_cluster = offset_into_cluster(s, offset);
1958 cur_bytes = MIN(bytes, INT_MAX);
1959 if (bs->encrypted) {
1960 cur_bytes = MIN(cur_bytes,
1961 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size
1962 - offset_in_cluster);
1963 }
1964
1965 ret = qcow2_alloc_cluster_offset(bs, offset, &cur_bytes,
1966 &cluster_offset, &l2meta);
1967 if (ret < 0) {
1968 goto fail;
1969 }
1970
1971 assert((cluster_offset & 511) == 0);
1972
1973 qemu_iovec_reset(&hd_qiov);
1974 qemu_iovec_concat(&hd_qiov, qiov, bytes_done, cur_bytes);
1975
1976 if (bs->encrypted) {
1977 assert(s->crypto);
1978 if (!cluster_data) {
1979 cluster_data = qemu_try_blockalign(bs->file->bs,
1980 QCOW_MAX_CRYPT_CLUSTERS
1981 * s->cluster_size);
1982 if (cluster_data == NULL) {
1983 ret = -ENOMEM;
1984 goto fail;
1985 }
1986 }
1987
1988 assert(hd_qiov.size <=
1989 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
1990 qemu_iovec_to_buf(&hd_qiov, 0, cluster_data, hd_qiov.size);
1991
1992 if (qcrypto_block_encrypt(s->crypto,
1993 (s->crypt_physical_offset ?
1994 cluster_offset + offset_in_cluster :
1995 offset),
1996 cluster_data,
1997 cur_bytes, NULL) < 0) {
1998 ret = -EIO;
1999 goto fail;
2000 }
2001
2002 qemu_iovec_reset(&hd_qiov);
2003 qemu_iovec_add(&hd_qiov, cluster_data, cur_bytes);
2004 }
2005
2006 ret = qcow2_pre_write_overlap_check(bs, 0,
2007 cluster_offset + offset_in_cluster, cur_bytes);
2008 if (ret < 0) {
2009 goto fail;
2010 }
2011
2012 /* If we need to do COW, check if it's possible to merge the
2013 * writing of the guest data together with that of the COW regions.
2014 * If it's not possible (or not necessary) then write the
2015 * guest data now. */
2016 if (!merge_cow(offset, cur_bytes, &hd_qiov, l2meta)) {
2017 qemu_co_mutex_unlock(&s->lock);
2018 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO);
2019 trace_qcow2_writev_data(qemu_coroutine_self(),
2020 cluster_offset + offset_in_cluster);
2021 ret = bdrv_co_pwritev(bs->file,
2022 cluster_offset + offset_in_cluster,
2023 cur_bytes, &hd_qiov, 0);
2024 qemu_co_mutex_lock(&s->lock);
2025 if (ret < 0) {
2026 goto fail;
2027 }
2028 }
2029
2030 while (l2meta != NULL) {
2031 QCowL2Meta *next;
2032
2033 ret = qcow2_alloc_cluster_link_l2(bs, l2meta);
2034 if (ret < 0) {
2035 goto fail;
2036 }
2037
2038 /* Take the request off the list of running requests */
2039 if (l2meta->nb_clusters != 0) {
2040 QLIST_REMOVE(l2meta, next_in_flight);
2041 }
2042
2043 qemu_co_queue_restart_all(&l2meta->dependent_requests);
2044
2045 next = l2meta->next;
2046 g_free(l2meta);
2047 l2meta = next;
2048 }
2049
2050 bytes -= cur_bytes;
2051 offset += cur_bytes;
2052 bytes_done += cur_bytes;
2053 trace_qcow2_writev_done_part(qemu_coroutine_self(), cur_bytes);
2054 }
2055 ret = 0;
2056
2057 fail:
2058 while (l2meta != NULL) {
2059 QCowL2Meta *next;
2060
2061 if (l2meta->nb_clusters != 0) {
2062 QLIST_REMOVE(l2meta, next_in_flight);
2063 }
2064 qemu_co_queue_restart_all(&l2meta->dependent_requests);
2065
2066 next = l2meta->next;
2067 g_free(l2meta);
2068 l2meta = next;
2069 }
2070
2071 qemu_co_mutex_unlock(&s->lock);
2072
2073 qemu_iovec_destroy(&hd_qiov);
2074 qemu_vfree(cluster_data);
2075 trace_qcow2_writev_done_req(qemu_coroutine_self(), ret);
2076
2077 return ret;
2078 }
2079
2080 static int qcow2_inactivate(BlockDriverState *bs)
2081 {
2082 BDRVQcow2State *s = bs->opaque;
2083 int ret, result = 0;
2084 Error *local_err = NULL;
2085
2086 qcow2_store_persistent_dirty_bitmaps(bs, &local_err);
2087 if (local_err != NULL) {
2088 result = -EINVAL;
2089 error_report_err(local_err);
2090 error_report("Persistent bitmaps are lost for node '%s'",
2091 bdrv_get_device_or_node_name(bs));
2092 }
2093
2094 ret = qcow2_cache_flush(bs, s->l2_table_cache);
2095 if (ret) {
2096 result = ret;
2097 error_report("Failed to flush the L2 table cache: %s",
2098 strerror(-ret));
2099 }
2100
2101 ret = qcow2_cache_flush(bs, s->refcount_block_cache);
2102 if (ret) {
2103 result = ret;
2104 error_report("Failed to flush the refcount block cache: %s",
2105 strerror(-ret));
2106 }
2107
2108 if (result == 0) {
2109 qcow2_mark_clean(bs);
2110 }
2111
2112 return result;
2113 }
2114
2115 static void qcow2_close(BlockDriverState *bs)
2116 {
2117 BDRVQcow2State *s = bs->opaque;
2118 qemu_vfree(s->l1_table);
2119 /* else pre-write overlap checks in cache_destroy may crash */
2120 s->l1_table = NULL;
2121
2122 if (!(s->flags & BDRV_O_INACTIVE)) {
2123 qcow2_inactivate(bs);
2124 }
2125
2126 cache_clean_timer_del(bs);
2127 qcow2_cache_destroy(s->l2_table_cache);
2128 qcow2_cache_destroy(s->refcount_block_cache);
2129
2130 qcrypto_block_free(s->crypto);
2131 s->crypto = NULL;
2132
2133 g_free(s->unknown_header_fields);
2134 cleanup_unknown_header_ext(bs);
2135
2136 g_free(s->image_backing_file);
2137 g_free(s->image_backing_format);
2138
2139 g_free(s->cluster_cache);
2140 qemu_vfree(s->cluster_data);
2141 qcow2_refcount_close(bs);
2142 qcow2_free_snapshots(bs);
2143 }
2144
2145 static void coroutine_fn qcow2_co_invalidate_cache(BlockDriverState *bs,
2146 Error **errp)
2147 {
2148 BDRVQcow2State *s = bs->opaque;
2149 int flags = s->flags;
2150 QCryptoBlock *crypto = NULL;
2151 QDict *options;
2152 Error *local_err = NULL;
2153 int ret;
2154
2155 /*
2156 * Backing files are read-only which makes all of their metadata immutable,
2157 * that means we don't have to worry about reopening them here.
2158 */
2159
2160 crypto = s->crypto;
2161 s->crypto = NULL;
2162
2163 qcow2_close(bs);
2164
2165 memset(s, 0, sizeof(BDRVQcow2State));
2166 options = qdict_clone_shallow(bs->options);
2167
2168 flags &= ~BDRV_O_INACTIVE;
2169 qemu_co_mutex_lock(&s->lock);
2170 ret = qcow2_do_open(bs, options, flags, &local_err);
2171 qemu_co_mutex_unlock(&s->lock);
2172 QDECREF(options);
2173 if (local_err) {
2174 error_propagate(errp, local_err);
2175 error_prepend(errp, "Could not reopen qcow2 layer: ");
2176 bs->drv = NULL;
2177 return;
2178 } else if (ret < 0) {
2179 error_setg_errno(errp, -ret, "Could not reopen qcow2 layer");
2180 bs->drv = NULL;
2181 return;
2182 }
2183
2184 s->crypto = crypto;
2185 }
2186
2187 static size_t header_ext_add(char *buf, uint32_t magic, const void *s,
2188 size_t len, size_t buflen)
2189 {
2190 QCowExtension *ext_backing_fmt = (QCowExtension*) buf;
2191 size_t ext_len = sizeof(QCowExtension) + ((len + 7) & ~7);
2192
2193 if (buflen < ext_len) {
2194 return -ENOSPC;
2195 }
2196
2197 *ext_backing_fmt = (QCowExtension) {
2198 .magic = cpu_to_be32(magic),
2199 .len = cpu_to_be32(len),
2200 };
2201
2202 if (len) {
2203 memcpy(buf + sizeof(QCowExtension), s, len);
2204 }
2205
2206 return ext_len;
2207 }
2208
2209 /*
2210 * Updates the qcow2 header, including the variable length parts of it, i.e.
2211 * the backing file name and all extensions. qcow2 was not designed to allow
2212 * such changes, so if we run out of space (we can only use the first cluster)
2213 * this function may fail.
2214 *
2215 * Returns 0 on success, -errno in error cases.
2216 */
2217 int qcow2_update_header(BlockDriverState *bs)
2218 {
2219 BDRVQcow2State *s = bs->opaque;
2220 QCowHeader *header;
2221 char *buf;
2222 size_t buflen = s->cluster_size;
2223 int ret;
2224 uint64_t total_size;
2225 uint32_t refcount_table_clusters;
2226 size_t header_length;
2227 Qcow2UnknownHeaderExtension *uext;
2228
2229 buf = qemu_blockalign(bs, buflen);
2230
2231 /* Header structure */
2232 header = (QCowHeader*) buf;
2233
2234 if (buflen < sizeof(*header)) {
2235 ret = -ENOSPC;
2236 goto fail;
2237 }
2238
2239 header_length = sizeof(*header) + s->unknown_header_fields_size;
2240 total_size = bs->total_sectors * BDRV_SECTOR_SIZE;
2241 refcount_table_clusters = s->refcount_table_size >> (s->cluster_bits - 3);
2242
2243 *header = (QCowHeader) {
2244 /* Version 2 fields */
2245 .magic = cpu_to_be32(QCOW_MAGIC),
2246 .version = cpu_to_be32(s->qcow_version),
2247 .backing_file_offset = 0,
2248 .backing_file_size = 0,
2249 .cluster_bits = cpu_to_be32(s->cluster_bits),
2250 .size = cpu_to_be64(total_size),
2251 .crypt_method = cpu_to_be32(s->crypt_method_header),
2252 .l1_size = cpu_to_be32(s->l1_size),
2253 .l1_table_offset = cpu_to_be64(s->l1_table_offset),
2254 .refcount_table_offset = cpu_to_be64(s->refcount_table_offset),
2255 .refcount_table_clusters = cpu_to_be32(refcount_table_clusters),
2256 .nb_snapshots = cpu_to_be32(s->nb_snapshots),
2257 .snapshots_offset = cpu_to_be64(s->snapshots_offset),
2258
2259 /* Version 3 fields */
2260 .incompatible_features = cpu_to_be64(s->incompatible_features),
2261 .compatible_features = cpu_to_be64(s->compatible_features),
2262 .autoclear_features = cpu_to_be64(s->autoclear_features),
2263 .refcount_order = cpu_to_be32(s->refcount_order),
2264 .header_length = cpu_to_be32(header_length),
2265 };
2266
2267 /* For older versions, write a shorter header */
2268 switch (s->qcow_version) {
2269 case 2:
2270 ret = offsetof(QCowHeader, incompatible_features);
2271 break;
2272 case 3:
2273 ret = sizeof(*header);
2274 break;
2275 default:
2276 ret = -EINVAL;
2277 goto fail;
2278 }
2279
2280 buf += ret;
2281 buflen -= ret;
2282 memset(buf, 0, buflen);
2283
2284 /* Preserve any unknown field in the header */
2285 if (s->unknown_header_fields_size) {
2286 if (buflen < s->unknown_header_fields_size) {
2287 ret = -ENOSPC;
2288 goto fail;
2289 }
2290
2291 memcpy(buf, s->unknown_header_fields, s->unknown_header_fields_size);
2292 buf += s->unknown_header_fields_size;
2293 buflen -= s->unknown_header_fields_size;
2294 }
2295
2296 /* Backing file format header extension */
2297 if (s->image_backing_format) {
2298 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BACKING_FORMAT,
2299 s->image_backing_format,
2300 strlen(s->image_backing_format),
2301 buflen);
2302 if (ret < 0) {
2303 goto fail;
2304 }
2305
2306 buf += ret;
2307 buflen -= ret;
2308 }
2309
2310 /* Full disk encryption header pointer extension */
2311 if (s->crypto_header.offset != 0) {
2312 cpu_to_be64s(&s->crypto_header.offset);
2313 cpu_to_be64s(&s->crypto_header.length);
2314 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_CRYPTO_HEADER,
2315 &s->crypto_header, sizeof(s->crypto_header),
2316 buflen);
2317 be64_to_cpus(&s->crypto_header.offset);
2318 be64_to_cpus(&s->crypto_header.length);
2319 if (ret < 0) {
2320 goto fail;
2321 }
2322 buf += ret;
2323 buflen -= ret;
2324 }
2325
2326 /* Feature table */
2327 if (s->qcow_version >= 3) {
2328 Qcow2Feature features[] = {
2329 {
2330 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
2331 .bit = QCOW2_INCOMPAT_DIRTY_BITNR,
2332 .name = "dirty bit",
2333 },
2334 {
2335 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
2336 .bit = QCOW2_INCOMPAT_CORRUPT_BITNR,
2337 .name = "corrupt bit",
2338 },
2339 {
2340 .type = QCOW2_FEAT_TYPE_COMPATIBLE,
2341 .bit = QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR,
2342 .name = "lazy refcounts",
2343 },
2344 };
2345
2346 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_FEATURE_TABLE,
2347 features, sizeof(features), buflen);
2348 if (ret < 0) {
2349 goto fail;
2350 }
2351 buf += ret;
2352 buflen -= ret;
2353 }
2354
2355 /* Bitmap extension */
2356 if (s->nb_bitmaps > 0) {
2357 Qcow2BitmapHeaderExt bitmaps_header = {
2358 .nb_bitmaps = cpu_to_be32(s->nb_bitmaps),
2359 .bitmap_directory_size =
2360 cpu_to_be64(s->bitmap_directory_size),
2361 .bitmap_directory_offset =
2362 cpu_to_be64(s->bitmap_directory_offset)
2363 };
2364 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BITMAPS,
2365 &bitmaps_header, sizeof(bitmaps_header),
2366 buflen);
2367 if (ret < 0) {
2368 goto fail;
2369 }
2370 buf += ret;
2371 buflen -= ret;
2372 }
2373
2374 /* Keep unknown header extensions */
2375 QLIST_FOREACH(uext, &s->unknown_header_ext, next) {
2376 ret = header_ext_add(buf, uext->magic, uext->data, uext->len, buflen);
2377 if (ret < 0) {
2378 goto fail;
2379 }
2380
2381 buf += ret;
2382 buflen -= ret;
2383 }
2384
2385 /* End of header extensions */
2386 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_END, NULL, 0, buflen);
2387 if (ret < 0) {
2388 goto fail;
2389 }
2390
2391 buf += ret;
2392 buflen -= ret;
2393
2394 /* Backing file name */
2395 if (s->image_backing_file) {
2396 size_t backing_file_len = strlen(s->image_backing_file);
2397
2398 if (buflen < backing_file_len) {
2399 ret = -ENOSPC;
2400 goto fail;
2401 }
2402
2403 /* Using strncpy is ok here, since buf is not NUL-terminated. */
2404 strncpy(buf, s->image_backing_file, buflen);
2405
2406 header->backing_file_offset = cpu_to_be64(buf - ((char*) header));
2407 header->backing_file_size = cpu_to_be32(backing_file_len);
2408 }
2409
2410 /* Write the new header */
2411 ret = bdrv_pwrite(bs->file, 0, header, s->cluster_size);
2412 if (ret < 0) {
2413 goto fail;
2414 }
2415
2416 ret = 0;
2417 fail:
2418 qemu_vfree(header);
2419 return ret;
2420 }
2421
2422 static int qcow2_change_backing_file(BlockDriverState *bs,
2423 const char *backing_file, const char *backing_fmt)
2424 {
2425 BDRVQcow2State *s = bs->opaque;
2426
2427 if (backing_file && strlen(backing_file) > 1023) {
2428 return -EINVAL;
2429 }
2430
2431 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
2432 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
2433
2434 g_free(s->image_backing_file);
2435 g_free(s->image_backing_format);
2436
2437 s->image_backing_file = backing_file ? g_strdup(bs->backing_file) : NULL;
2438 s->image_backing_format = backing_fmt ? g_strdup(bs->backing_format) : NULL;
2439
2440 return qcow2_update_header(bs);
2441 }
2442
2443 static int qcow2_crypt_method_from_format(const char *encryptfmt)
2444 {
2445 if (g_str_equal(encryptfmt, "luks")) {
2446 return QCOW_CRYPT_LUKS;
2447 } else if (g_str_equal(encryptfmt, "aes")) {
2448 return QCOW_CRYPT_AES;
2449 } else {
2450 return -EINVAL;
2451 }
2452 }
2453
2454 static int qcow2_set_up_encryption(BlockDriverState *bs, const char *encryptfmt,
2455 QemuOpts *opts, Error **errp)
2456 {
2457 BDRVQcow2State *s = bs->opaque;
2458 QCryptoBlockCreateOptions *cryptoopts = NULL;
2459 QCryptoBlock *crypto = NULL;
2460 int ret = -EINVAL;
2461 QDict *options, *encryptopts;
2462 int fmt;
2463
2464 options = qemu_opts_to_qdict(opts, NULL);
2465 qdict_extract_subqdict(options, &encryptopts, "encrypt.");
2466 QDECREF(options);
2467
2468 fmt = qcow2_crypt_method_from_format(encryptfmt);
2469
2470 switch (fmt) {
2471 case QCOW_CRYPT_LUKS:
2472 cryptoopts = block_crypto_create_opts_init(
2473 Q_CRYPTO_BLOCK_FORMAT_LUKS, encryptopts, errp);
2474 break;
2475 case QCOW_CRYPT_AES:
2476 cryptoopts = block_crypto_create_opts_init(
2477 Q_CRYPTO_BLOCK_FORMAT_QCOW, encryptopts, errp);
2478 break;
2479 default:
2480 error_setg(errp, "Unknown encryption format '%s'", encryptfmt);
2481 break;
2482 }
2483 if (!cryptoopts) {
2484 ret = -EINVAL;
2485 goto out;
2486 }
2487 s->crypt_method_header = fmt;
2488
2489 crypto = qcrypto_block_create(cryptoopts, "encrypt.",
2490 qcow2_crypto_hdr_init_func,
2491 qcow2_crypto_hdr_write_func,
2492 bs, errp);
2493 if (!crypto) {
2494 ret = -EINVAL;
2495 goto out;
2496 }
2497
2498 ret = qcow2_update_header(bs);
2499 if (ret < 0) {
2500 error_setg_errno(errp, -ret, "Could not write encryption header");
2501 goto out;
2502 }
2503
2504 out:
2505 QDECREF(encryptopts);
2506 qcrypto_block_free(crypto);
2507 qapi_free_QCryptoBlockCreateOptions(cryptoopts);
2508 return ret;
2509 }
2510
2511
2512 typedef struct PreallocCo {
2513 BlockDriverState *bs;
2514 uint64_t offset;
2515 uint64_t new_length;
2516
2517 int ret;
2518 } PreallocCo;
2519
2520 /**
2521 * Preallocates metadata structures for data clusters between @offset (in the
2522 * guest disk) and @new_length (which is thus generally the new guest disk
2523 * size).
2524 *
2525 * Returns: 0 on success, -errno on failure.
2526 */
2527 static void coroutine_fn preallocate_co(void *opaque)
2528 {
2529 PreallocCo *params = opaque;
2530 BlockDriverState *bs = params->bs;
2531 uint64_t offset = params->offset;
2532 uint64_t new_length = params->new_length;
2533 BDRVQcow2State *s = bs->opaque;
2534 uint64_t bytes;
2535 uint64_t host_offset = 0;
2536 unsigned int cur_bytes;
2537 int ret;
2538 QCowL2Meta *meta;
2539
2540 qemu_co_mutex_lock(&s->lock);
2541
2542 assert(offset <= new_length);
2543 bytes = new_length - offset;
2544
2545 while (bytes) {
2546 cur_bytes = MIN(bytes, INT_MAX);
2547 ret = qcow2_alloc_cluster_offset(bs, offset, &cur_bytes,
2548 &host_offset, &meta);
2549 if (ret < 0) {
2550 goto done;
2551 }
2552
2553 while (meta) {
2554 QCowL2Meta *next = meta->next;
2555
2556 ret = qcow2_alloc_cluster_link_l2(bs, meta);
2557 if (ret < 0) {
2558 qcow2_free_any_clusters(bs, meta->alloc_offset,
2559 meta->nb_clusters, QCOW2_DISCARD_NEVER);
2560 goto done;
2561 }
2562
2563 /* There are no dependent requests, but we need to remove our
2564 * request from the list of in-flight requests */
2565 QLIST_REMOVE(meta, next_in_flight);
2566
2567 g_free(meta);
2568 meta = next;
2569 }
2570
2571 /* TODO Preallocate data if requested */
2572
2573 bytes -= cur_bytes;
2574 offset += cur_bytes;
2575 }
2576
2577 /*
2578 * It is expected that the image file is large enough to actually contain
2579 * all of the allocated clusters (otherwise we get failing reads after
2580 * EOF). Extend the image to the last allocated sector.
2581 */
2582 if (host_offset != 0) {
2583 uint8_t data = 0;
2584 ret = bdrv_pwrite(bs->file, (host_offset + cur_bytes) - 1,
2585 &data, 1);
2586 if (ret < 0) {
2587 goto done;
2588 }
2589 }
2590
2591 ret = 0;
2592
2593 done:
2594 qemu_co_mutex_unlock(&s->lock);
2595 params->ret = ret;
2596 }
2597
2598 static int preallocate(BlockDriverState *bs,
2599 uint64_t offset, uint64_t new_length)
2600 {
2601 PreallocCo params = {
2602 .bs = bs,
2603 .offset = offset,
2604 .new_length = new_length,
2605 .ret = -EINPROGRESS,
2606 };
2607
2608 if (qemu_in_coroutine()) {
2609 preallocate_co(&params);
2610 } else {
2611 Coroutine *co = qemu_coroutine_create(preallocate_co, &params);
2612 bdrv_coroutine_enter(bs, co);
2613 BDRV_POLL_WHILE(bs, params.ret == -EINPROGRESS);
2614 }
2615 return params.ret;
2616 }
2617
2618 /* qcow2_refcount_metadata_size:
2619 * @clusters: number of clusters to refcount (including data and L1/L2 tables)
2620 * @cluster_size: size of a cluster, in bytes
2621 * @refcount_order: refcount bits power-of-2 exponent
2622 * @generous_increase: allow for the refcount table to be 1.5x as large as it
2623 * needs to be
2624 *
2625 * Returns: Number of bytes required for refcount blocks and table metadata.
2626 */
2627 int64_t qcow2_refcount_metadata_size(int64_t clusters, size_t cluster_size,
2628 int refcount_order, bool generous_increase,
2629 uint64_t *refblock_count)
2630 {
2631 /*
2632 * Every host cluster is reference-counted, including metadata (even
2633 * refcount metadata is recursively included).
2634 *
2635 * An accurate formula for the size of refcount metadata size is difficult
2636 * to derive. An easier method of calculation is finding the fixed point
2637 * where no further refcount blocks or table clusters are required to
2638 * reference count every cluster.
2639 */
2640 int64_t blocks_per_table_cluster = cluster_size / sizeof(uint64_t);
2641 int64_t refcounts_per_block = cluster_size * 8 / (1 << refcount_order);
2642 int64_t table = 0; /* number of refcount table clusters */
2643 int64_t blocks = 0; /* number of refcount block clusters */
2644 int64_t last;
2645 int64_t n = 0;
2646
2647 do {
2648 last = n;
2649 blocks = DIV_ROUND_UP(clusters + table + blocks, refcounts_per_block);
2650 table = DIV_ROUND_UP(blocks, blocks_per_table_cluster);
2651 n = clusters + blocks + table;
2652
2653 if (n == last && generous_increase) {
2654 clusters += DIV_ROUND_UP(table, 2);
2655 n = 0; /* force another loop */
2656 generous_increase = false;
2657 }
2658 } while (n != last);
2659
2660 if (refblock_count) {
2661 *refblock_count = blocks;
2662 }
2663
2664 return (blocks + table) * cluster_size;
2665 }
2666
2667 /**
2668 * qcow2_calc_prealloc_size:
2669 * @total_size: virtual disk size in bytes
2670 * @cluster_size: cluster size in bytes
2671 * @refcount_order: refcount bits power-of-2 exponent
2672 *
2673 * Returns: Total number of bytes required for the fully allocated image
2674 * (including metadata).
2675 */
2676 static int64_t qcow2_calc_prealloc_size(int64_t total_size,
2677 size_t cluster_size,
2678 int refcount_order)
2679 {
2680 int64_t meta_size = 0;
2681 uint64_t nl1e, nl2e;
2682 int64_t aligned_total_size = ROUND_UP(total_size, cluster_size);
2683
2684 /* header: 1 cluster */
2685 meta_size += cluster_size;
2686
2687 /* total size of L2 tables */
2688 nl2e = aligned_total_size / cluster_size;
2689 nl2e = ROUND_UP(nl2e, cluster_size / sizeof(uint64_t));
2690 meta_size += nl2e * sizeof(uint64_t);
2691
2692 /* total size of L1 tables */
2693 nl1e = nl2e * sizeof(uint64_t) / cluster_size;
2694 nl1e = ROUND_UP(nl1e, cluster_size / sizeof(uint64_t));
2695 meta_size += nl1e * sizeof(uint64_t);
2696
2697 /* total size of refcount table and blocks */
2698 meta_size += qcow2_refcount_metadata_size(
2699 (meta_size + aligned_total_size) / cluster_size,
2700 cluster_size, refcount_order, false, NULL);
2701
2702 return meta_size + aligned_total_size;
2703 }
2704
2705 static size_t qcow2_opt_get_cluster_size_del(QemuOpts *opts, Error **errp)
2706 {
2707 size_t cluster_size;
2708 int cluster_bits;
2709
2710 cluster_size = qemu_opt_get_size_del(opts, BLOCK_OPT_CLUSTER_SIZE,
2711 DEFAULT_CLUSTER_SIZE);
2712 cluster_bits = ctz32(cluster_size);
2713 if (cluster_bits < MIN_CLUSTER_BITS || cluster_bits > MAX_CLUSTER_BITS ||
2714 (1 << cluster_bits) != cluster_size)
2715 {
2716 error_setg(errp, "Cluster size must be a power of two between %d and "
2717 "%dk", 1 << MIN_CLUSTER_BITS, 1 << (MAX_CLUSTER_BITS - 10));
2718 return 0;
2719 }
2720 return cluster_size;
2721 }
2722
2723 static int qcow2_opt_get_version_del(QemuOpts *opts, Error **errp)
2724 {
2725 char *buf;
2726 int ret;
2727
2728 buf = qemu_opt_get_del(opts, BLOCK_OPT_COMPAT_LEVEL);
2729 if (!buf) {
2730 ret = 3; /* default */
2731 } else if (!strcmp(buf, "0.10")) {
2732 ret = 2;
2733 } else if (!strcmp(buf, "1.1")) {
2734 ret = 3;
2735 } else {
2736 error_setg(errp, "Invalid compatibility level: '%s'", buf);
2737 ret = -EINVAL;
2738 }
2739 g_free(buf);
2740 return ret;
2741 }
2742
2743 static uint64_t qcow2_opt_get_refcount_bits_del(QemuOpts *opts, int version,
2744 Error **errp)
2745 {
2746 uint64_t refcount_bits;
2747
2748 refcount_bits = qemu_opt_get_number_del(opts, BLOCK_OPT_REFCOUNT_BITS, 16);
2749 if (refcount_bits > 64 || !is_power_of_2(refcount_bits)) {
2750 error_setg(errp, "Refcount width must be a power of two and may not "
2751 "exceed 64 bits");
2752 return 0;
2753 }
2754
2755 if (version < 3 && refcount_bits != 16) {
2756 error_setg(errp, "Different refcount widths than 16 bits require "
2757 "compatibility level 1.1 or above (use compat=1.1 or "
2758 "greater)");
2759 return 0;
2760 }
2761
2762 return refcount_bits;
2763 }
2764
2765 static int coroutine_fn
2766 qcow2_co_create2(const char *filename, int64_t total_size,
2767 const char *backing_file, const char *backing_format,
2768 int flags, size_t cluster_size, PreallocMode prealloc,
2769 QemuOpts *opts, int version, int refcount_order,
2770 const char *encryptfmt, Error **errp)
2771 {
2772 QDict *options;
2773
2774 /*
2775 * Open the image file and write a minimal qcow2 header.
2776 *
2777 * We keep things simple and start with a zero-sized image. We also
2778 * do without refcount blocks or a L1 table for now. We'll fix the
2779 * inconsistency later.
2780 *
2781 * We do need a refcount table because growing the refcount table means
2782 * allocating two new refcount blocks - the seconds of which would be at
2783 * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
2784 * size for any qcow2 image.
2785 */
2786 BlockBackend *blk;
2787 QCowHeader *header;
2788 uint64_t* refcount_table;
2789 Error *local_err = NULL;
2790 int ret;
2791
2792 if (prealloc == PREALLOC_MODE_FULL || prealloc == PREALLOC_MODE_FALLOC) {
2793 int64_t prealloc_size =
2794 qcow2_calc_prealloc_size(total_size, cluster_size, refcount_order);
2795 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, prealloc_size, &error_abort);
2796 qemu_opt_set(opts, BLOCK_OPT_PREALLOC, PreallocMode_str(prealloc),
2797 &error_abort);
2798 }
2799
2800 ret = bdrv_create_file(filename, opts, &local_err);
2801 if (ret < 0) {
2802 error_propagate(errp, local_err);
2803 return ret;
2804 }
2805
2806 blk = blk_new_open(filename, NULL, NULL,
2807 BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_PROTOCOL,
2808 &local_err);
2809 if (blk == NULL) {
2810 error_propagate(errp, local_err);
2811 return -EIO;
2812 }
2813
2814 blk_set_allow_write_beyond_eof(blk, true);
2815
2816 /* Write the header */
2817 QEMU_BUILD_BUG_ON((1 << MIN_CLUSTER_BITS) < sizeof(*header));
2818 header = g_malloc0(cluster_size);
2819 *header = (QCowHeader) {
2820 .magic = cpu_to_be32(QCOW_MAGIC),
2821 .version = cpu_to_be32(version),
2822 .cluster_bits = cpu_to_be32(ctz32(cluster_size)),
2823 .size = cpu_to_be64(0),
2824 .l1_table_offset = cpu_to_be64(0),
2825 .l1_size = cpu_to_be32(0),
2826 .refcount_table_offset = cpu_to_be64(cluster_size),
2827 .refcount_table_clusters = cpu_to_be32(1),
2828 .refcount_order = cpu_to_be32(refcount_order),
2829 .header_length = cpu_to_be32(sizeof(*header)),
2830 };
2831
2832 /* We'll update this to correct value later */
2833 header->crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
2834
2835 if (flags & BLOCK_FLAG_LAZY_REFCOUNTS) {
2836 header->compatible_features |=
2837 cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS);
2838 }
2839
2840 ret = blk_pwrite(blk, 0, header, cluster_size, 0);
2841 g_free(header);
2842 if (ret < 0) {
2843 error_setg_errno(errp, -ret, "Could not write qcow2 header");
2844 goto out;
2845 }
2846
2847 /* Write a refcount table with one refcount block */
2848 refcount_table = g_malloc0(2 * cluster_size);
2849 refcount_table[0] = cpu_to_be64(2 * cluster_size);
2850 ret = blk_pwrite(blk, cluster_size, refcount_table, 2 * cluster_size, 0);
2851 g_free(refcount_table);
2852
2853 if (ret < 0) {
2854 error_setg_errno(errp, -ret, "Could not write refcount table");
2855 goto out;
2856 }
2857
2858 blk_unref(blk);
2859 blk = NULL;
2860
2861 /*
2862 * And now open the image and make it consistent first (i.e. increase the
2863 * refcount of the cluster that is occupied by the header and the refcount
2864 * table)
2865 */
2866 options = qdict_new();
2867 qdict_put_str(options, "driver", "qcow2");
2868 blk = blk_new_open(filename, NULL, options,
2869 BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_NO_FLUSH,
2870 &local_err);
2871 if (blk == NULL) {
2872 error_propagate(errp, local_err);
2873 ret = -EIO;
2874 goto out;
2875 }
2876
2877 ret = qcow2_alloc_clusters(blk_bs(blk), 3 * cluster_size);
2878 if (ret < 0) {
2879 error_setg_errno(errp, -ret, "Could not allocate clusters for qcow2 "
2880 "header and refcount table");
2881 goto out;
2882
2883 } else if (ret != 0) {
2884 error_report("Huh, first cluster in empty image is already in use?");
2885 abort();
2886 }
2887
2888 /* Create a full header (including things like feature table) */
2889 ret = qcow2_update_header(blk_bs(blk));
2890 if (ret < 0) {
2891 error_setg_errno(errp, -ret, "Could not update qcow2 header");
2892 goto out;
2893 }
2894
2895 /* Okay, now that we have a valid image, let's give it the right size */
2896 ret = blk_truncate(blk, total_size, PREALLOC_MODE_OFF, errp);
2897 if (ret < 0) {
2898 error_prepend(errp, "Could not resize image: ");
2899 goto out;
2900 }
2901
2902 /* Want a backing file? There you go.*/
2903 if (backing_file) {
2904 ret = bdrv_change_backing_file(blk_bs(blk), backing_file, backing_format);
2905 if (ret < 0) {
2906 error_setg_errno(errp, -ret, "Could not assign backing file '%s' "
2907 "with format '%s'", backing_file, backing_format);
2908 goto out;
2909 }
2910 }
2911
2912 /* Want encryption? There you go. */
2913 if (encryptfmt) {
2914 ret = qcow2_set_up_encryption(blk_bs(blk), encryptfmt, opts, errp);
2915 if (ret < 0) {
2916 goto out;
2917 }
2918 }
2919
2920 /* And if we're supposed to preallocate metadata, do that now */
2921 if (prealloc != PREALLOC_MODE_OFF) {
2922 ret = preallocate(blk_bs(blk), 0, total_size);
2923 if (ret < 0) {
2924 error_setg_errno(errp, -ret, "Could not preallocate metadata");
2925 goto out;
2926 }
2927 }
2928
2929 blk_unref(blk);
2930 blk = NULL;
2931
2932 /* Reopen the image without BDRV_O_NO_FLUSH to flush it before returning.
2933 * Using BDRV_O_NO_IO, since encryption is now setup we don't want to
2934 * have to setup decryption context. We're not doing any I/O on the top
2935 * level BlockDriverState, only lower layers, where BDRV_O_NO_IO does
2936 * not have effect.
2937 */
2938 options = qdict_new();
2939 qdict_put_str(options, "driver", "qcow2");
2940 blk = blk_new_open(filename, NULL, options,
2941 BDRV_O_RDWR | BDRV_O_NO_BACKING | BDRV_O_NO_IO,
2942 &local_err);
2943 if (blk == NULL) {
2944 error_propagate(errp, local_err);
2945 ret = -EIO;
2946 goto out;
2947 }
2948
2949 ret = 0;
2950 out:
2951 if (blk) {
2952 blk_unref(blk);
2953 }
2954 return ret;
2955 }
2956
2957 static int coroutine_fn qcow2_co_create_opts(const char *filename, QemuOpts *opts,
2958 Error **errp)
2959 {
2960 char *backing_file = NULL;
2961 char *backing_fmt = NULL;
2962 char *buf = NULL;
2963 uint64_t size = 0;
2964 int flags = 0;
2965 size_t cluster_size = DEFAULT_CLUSTER_SIZE;
2966 PreallocMode prealloc;
2967 int version;
2968 uint64_t refcount_bits;
2969 int refcount_order;
2970 char *encryptfmt = NULL;
2971 Error *local_err = NULL;
2972 int ret;
2973
2974 /* Read out options */
2975 size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
2976 BDRV_SECTOR_SIZE);
2977 backing_file = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
2978 backing_fmt = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FMT);
2979 encryptfmt = qemu_opt_get_del(opts, BLOCK_OPT_ENCRYPT_FORMAT);
2980 if (encryptfmt) {
2981 if (qemu_opt_get(opts, BLOCK_OPT_ENCRYPT)) {
2982 error_setg(errp, "Options " BLOCK_OPT_ENCRYPT " and "
2983 BLOCK_OPT_ENCRYPT_FORMAT " are mutually exclusive");
2984 ret = -EINVAL;
2985 goto finish;
2986 }
2987 } else if (qemu_opt_get_bool_del(opts, BLOCK_OPT_ENCRYPT, false)) {
2988 encryptfmt = g_strdup("aes");
2989 }
2990 cluster_size = qcow2_opt_get_cluster_size_del(opts, &local_err);
2991 if (local_err) {
2992 error_propagate(errp, local_err);
2993 ret = -EINVAL;
2994 goto finish;
2995 }
2996 buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
2997 prealloc = qapi_enum_parse(&PreallocMode_lookup, buf,
2998 PREALLOC_MODE_OFF, &local_err);
2999 if (local_err) {
3000 error_propagate(errp, local_err);
3001 ret = -EINVAL;
3002 goto finish;
3003 }
3004
3005 version = qcow2_opt_get_version_del(opts, &local_err);
3006 if (local_err) {
3007 error_propagate(errp, local_err);
3008 ret = -EINVAL;
3009 goto finish;
3010 }
3011
3012 if (qemu_opt_get_bool_del(opts, BLOCK_OPT_LAZY_REFCOUNTS, false)) {
3013 flags |= BLOCK_FLAG_LAZY_REFCOUNTS;
3014 }
3015
3016 if (backing_file && prealloc != PREALLOC_MODE_OFF) {
3017 error_setg(errp, "Backing file and preallocation cannot be used at "
3018 "the same time");
3019 ret = -EINVAL;
3020 goto finish;
3021 }
3022
3023 if (version < 3 && (flags & BLOCK_FLAG_LAZY_REFCOUNTS)) {
3024 error_setg(errp, "Lazy refcounts only supported with compatibility "
3025 "level 1.1 and above (use compat=1.1 or greater)");
3026 ret = -EINVAL;
3027 goto finish;
3028 }
3029
3030 refcount_bits = qcow2_opt_get_refcount_bits_del(opts, version, &local_err);
3031 if (local_err) {
3032 error_propagate(errp, local_err);
3033 ret = -EINVAL;
3034 goto finish;
3035 }
3036
3037 refcount_order = ctz32(refcount_bits);
3038
3039 ret = qcow2_co_create2(filename, size, backing_file, backing_fmt, flags,
3040 cluster_size, prealloc, opts, version, refcount_order,
3041 encryptfmt, &local_err);
3042 error_propagate(errp, local_err);
3043
3044 finish:
3045 g_free(backing_file);
3046 g_free(backing_fmt);
3047 g_free(encryptfmt);
3048 g_free(buf);
3049 return ret;
3050 }
3051
3052
3053 static bool is_zero(BlockDriverState *bs, int64_t offset, int64_t bytes)
3054 {
3055 int64_t nr;
3056 int res;
3057
3058 /* Clamp to image length, before checking status of underlying sectors */
3059 if (offset + bytes > bs->total_sectors * BDRV_SECTOR_SIZE) {
3060 bytes = bs->total_sectors * BDRV_SECTOR_SIZE - offset;
3061 }
3062
3063 if (!bytes) {
3064 return true;
3065 }
3066 res = bdrv_block_status_above(bs, NULL, offset, bytes, &nr, NULL, NULL);
3067 return res >= 0 && (res & BDRV_BLOCK_ZERO) && nr == bytes;
3068 }
3069
3070 static coroutine_fn int qcow2_co_pwrite_zeroes(BlockDriverState *bs,
3071 int64_t offset, int bytes, BdrvRequestFlags flags)
3072 {
3073 int ret;
3074 BDRVQcow2State *s = bs->opaque;
3075
3076 uint32_t head = offset % s->cluster_size;
3077 uint32_t tail = (offset + bytes) % s->cluster_size;
3078
3079 trace_qcow2_pwrite_zeroes_start_req(qemu_coroutine_self(), offset, bytes);
3080 if (offset + bytes == bs->total_sectors * BDRV_SECTOR_SIZE) {
3081 tail = 0;
3082 }
3083
3084 if (head || tail) {
3085 uint64_t off;
3086 unsigned int nr;
3087
3088 assert(head + bytes <= s->cluster_size);
3089
3090 /* check whether remainder of cluster already reads as zero */
3091 if (!(is_zero(bs, offset - head, head) &&
3092 is_zero(bs, offset + bytes,
3093 tail ? s->cluster_size - tail : 0))) {
3094 return -ENOTSUP;
3095 }
3096
3097 qemu_co_mutex_lock(&s->lock);
3098 /* We can have new write after previous check */
3099 offset = QEMU_ALIGN_DOWN(offset, s->cluster_size);
3100 bytes = s->cluster_size;
3101 nr = s->cluster_size;
3102 ret = qcow2_get_cluster_offset(bs, offset, &nr, &off);
3103 if (ret != QCOW2_CLUSTER_UNALLOCATED &&
3104 ret != QCOW2_CLUSTER_ZERO_PLAIN &&
3105 ret != QCOW2_CLUSTER_ZERO_ALLOC) {
3106 qemu_co_mutex_unlock(&s->lock);
3107 return -ENOTSUP;
3108 }
3109 } else {
3110 qemu_co_mutex_lock(&s->lock);
3111 }
3112
3113 trace_qcow2_pwrite_zeroes(qemu_coroutine_self(), offset, bytes);
3114
3115 /* Whatever is left can use real zero clusters */
3116 ret = qcow2_cluster_zeroize(bs, offset, bytes, flags);
3117 qemu_co_mutex_unlock(&s->lock);
3118
3119 return ret;
3120 }
3121
3122 static coroutine_fn int qcow2_co_pdiscard(BlockDriverState *bs,
3123 int64_t offset, int bytes)
3124 {
3125 int ret;
3126 BDRVQcow2State *s = bs->opaque;
3127
3128 if (!QEMU_IS_ALIGNED(offset | bytes, s->cluster_size)) {
3129 assert(bytes < s->cluster_size);
3130 /* Ignore partial clusters, except for the special case of the
3131 * complete partial cluster at the end of an unaligned file */
3132 if (!QEMU_IS_ALIGNED(offset, s->cluster_size) ||
3133 offset + bytes != bs->total_sectors * BDRV_SECTOR_SIZE) {
3134 return -ENOTSUP;
3135 }
3136 }
3137
3138 qemu_co_mutex_lock(&s->lock);
3139 ret = qcow2_cluster_discard(bs, offset, bytes, QCOW2_DISCARD_REQUEST,
3140 false);
3141 qemu_co_mutex_unlock(&s->lock);
3142 return ret;
3143 }
3144
3145 static int qcow2_truncate(BlockDriverState *bs, int64_t offset,
3146 PreallocMode prealloc, Error **errp)
3147 {
3148 BDRVQcow2State *s = bs->opaque;
3149 uint64_t old_length;
3150 int64_t new_l1_size;
3151 int ret;
3152
3153 if (prealloc != PREALLOC_MODE_OFF && prealloc != PREALLOC_MODE_METADATA &&
3154 prealloc != PREALLOC_MODE_FALLOC && prealloc != PREALLOC_MODE_FULL)
3155 {
3156 error_setg(errp, "Unsupported preallocation mode '%s'",
3157 PreallocMode_str(prealloc));
3158 return -ENOTSUP;
3159 }
3160
3161 if (offset & 511) {
3162 error_setg(errp, "The new size must be a multiple of 512");
3163 return -EINVAL;
3164 }
3165
3166 /* cannot proceed if image has snapshots */
3167 if (s->nb_snapshots) {
3168 error_setg(errp, "Can't resize an image which has snapshots");
3169 return -ENOTSUP;
3170 }
3171
3172 /* cannot proceed if image has bitmaps */
3173 if (s->nb_bitmaps) {
3174 /* TODO: resize bitmaps in the image */
3175 error_setg(errp, "Can't resize an image which has bitmaps");
3176 return -ENOTSUP;
3177 }
3178
3179 old_length = bs->total_sectors * 512;
3180 new_l1_size = size_to_l1(s, offset);
3181
3182 if (offset < old_length) {
3183 int64_t last_cluster, old_file_size;
3184 if (prealloc != PREALLOC_MODE_OFF) {
3185 error_setg(errp,
3186 "Preallocation can't be used for shrinking an image");
3187 return -EINVAL;
3188 }
3189
3190 ret = qcow2_cluster_discard(bs, ROUND_UP(offset, s->cluster_size),
3191 old_length - ROUND_UP(offset,
3192 s->cluster_size),
3193 QCOW2_DISCARD_ALWAYS, true);
3194 if (ret < 0) {
3195 error_setg_errno(errp, -ret, "Failed to discard cropped clusters");
3196 return ret;
3197 }
3198
3199 ret = qcow2_shrink_l1_table(bs, new_l1_size);
3200 if (ret < 0) {
3201 error_setg_errno(errp, -ret,
3202 "Failed to reduce the number of L2 tables");
3203 return ret;
3204 }
3205
3206 ret = qcow2_shrink_reftable(bs);
3207 if (ret < 0) {
3208 error_setg_errno(errp, -ret,
3209 "Failed to discard unused refblocks");
3210 return ret;
3211 }
3212
3213 old_file_size = bdrv_getlength(bs->file->bs);
3214 if (old_file_size < 0) {
3215 error_setg_errno(errp, -old_file_size,
3216 "Failed to inquire current file length");
3217 return old_file_size;
3218 }
3219 last_cluster = qcow2_get_last_cluster(bs, old_file_size);
3220 if (last_cluster < 0) {
3221 error_setg_errno(errp, -last_cluster,
3222 "Failed to find the last cluster");
3223 return last_cluster;
3224 }
3225 if ((last_cluster + 1) * s->cluster_size < old_file_size) {
3226 Error *local_err = NULL;
3227
3228 bdrv_truncate(bs->file, (last_cluster + 1) * s->cluster_size,
3229 PREALLOC_MODE_OFF, &local_err);
3230 if (local_err) {
3231 warn_reportf_err(local_err,
3232 "Failed to truncate the tail of the image: ");
3233 }
3234 }
3235 } else {
3236 ret = qcow2_grow_l1_table(bs, new_l1_size, true);
3237 if (ret < 0) {
3238 error_setg_errno(errp, -ret, "Failed to grow the L1 table");
3239 return ret;
3240 }
3241 }
3242
3243 switch (prealloc) {
3244 case PREALLOC_MODE_OFF:
3245 break;
3246
3247 case PREALLOC_MODE_METADATA:
3248 ret = preallocate(bs, old_length, offset);
3249 if (ret < 0) {
3250 error_setg_errno(errp, -ret, "Preallocation failed");
3251 return ret;
3252 }
3253 break;
3254
3255 case PREALLOC_MODE_FALLOC:
3256 case PREALLOC_MODE_FULL:
3257 {
3258 int64_t allocation_start, host_offset, guest_offset;
3259 int64_t clusters_allocated;
3260 int64_t old_file_size, new_file_size;
3261 uint64_t nb_new_data_clusters, nb_new_l2_tables;
3262
3263 old_file_size = bdrv_getlength(bs->file->bs);
3264 if (old_file_size < 0) {
3265 error_setg_errno(errp, -old_file_size,
3266 "Failed to inquire current file length");
3267 return old_file_size;
3268 }
3269 old_file_size = ROUND_UP(old_file_size, s->cluster_size);
3270
3271 nb_new_data_clusters = DIV_ROUND_UP(offset - old_length,
3272 s->cluster_size);
3273
3274 /* This is an overestimation; we will not actually allocate space for
3275 * these in the file but just make sure the new refcount structures are
3276 * able to cover them so we will not have to allocate new refblocks
3277 * while entering the data blocks in the potentially new L2 tables.
3278 * (We do not actually care where the L2 tables are placed. Maybe they
3279 * are already allocated or they can be placed somewhere before
3280 * @old_file_size. It does not matter because they will be fully
3281 * allocated automatically, so they do not need to be covered by the
3282 * preallocation. All that matters is that we will not have to allocate
3283 * new refcount structures for them.) */
3284 nb_new_l2_tables = DIV_ROUND_UP(nb_new_data_clusters,
3285 s->cluster_size / sizeof(uint64_t));
3286 /* The cluster range may not be aligned to L2 boundaries, so add one L2
3287 * table for a potential head/tail */
3288 nb_new_l2_tables++;
3289
3290 allocation_start = qcow2_refcount_area(bs, old_file_size,
3291 nb_new_data_clusters +
3292 nb_new_l2_tables,
3293 true, 0, 0);
3294 if (allocation_start < 0) {
3295 error_setg_errno(errp, -allocation_start,
3296 "Failed to resize refcount structures");
3297 return allocation_start;
3298 }
3299
3300 clusters_allocated = qcow2_alloc_clusters_at(bs, allocation_start,
3301 nb_new_data_clusters);
3302 if (clusters_allocated < 0) {
3303 error_setg_errno(errp, -clusters_allocated,
3304 "Failed to allocate data clusters");
3305 return -clusters_allocated;
3306 }
3307
3308 assert(clusters_allocated == nb_new_data_clusters);
3309
3310 /* Allocate the data area */
3311 new_file_size = allocation_start +
3312 nb_new_data_clusters * s->cluster_size;
3313 ret = bdrv_truncate(bs->file, new_file_size, prealloc, errp);
3314 if (ret < 0) {
3315 error_prepend(errp, "Failed to resize underlying file: ");
3316 qcow2_free_clusters(bs, allocation_start,
3317 nb_new_data_clusters * s->cluster_size,
3318 QCOW2_DISCARD_OTHER);
3319 return ret;
3320 }
3321
3322 /* Create the necessary L2 entries */
3323 host_offset = allocation_start;
3324 guest_offset = old_length;
3325 while (nb_new_data_clusters) {
3326 int64_t nb_clusters = MIN(
3327 nb_new_data_clusters,
3328 s->l2_slice_size - offset_to_l2_slice_index(s, guest_offset));
3329 QCowL2Meta allocation = {
3330 .offset = guest_offset,
3331 .alloc_offset = host_offset,
3332 .nb_clusters = nb_clusters,
3333 };
3334 qemu_co_queue_init(&allocation.dependent_requests);
3335
3336 ret = qcow2_alloc_cluster_link_l2(bs, &allocation);
3337 if (ret < 0) {
3338 error_setg_errno(errp, -ret, "Failed to update L2 tables");
3339 qcow2_free_clusters(bs, host_offset,
3340 nb_new_data_clusters * s->cluster_size,
3341 QCOW2_DISCARD_OTHER);
3342 return ret;
3343 }
3344
3345 guest_offset += nb_clusters * s->cluster_size;
3346 host_offset += nb_clusters * s->cluster_size;
3347 nb_new_data_clusters -= nb_clusters;
3348 }
3349 break;
3350 }
3351
3352 default:
3353 g_assert_not_reached();
3354 }
3355
3356 if (prealloc != PREALLOC_MODE_OFF) {
3357 /* Flush metadata before actually changing the image size */
3358 ret = bdrv_flush(bs);
3359 if (ret < 0) {
3360 error_setg_errno(errp, -ret,
3361 "Failed to flush the preallocated area to disk");
3362 return ret;
3363 }
3364 }
3365
3366 /* write updated header.size */
3367 offset = cpu_to_be64(offset);
3368 ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, size),
3369 &offset, sizeof(uint64_t));
3370 if (ret < 0) {
3371 error_setg_errno(errp, -ret, "Failed to update the image size");
3372 return ret;
3373 }
3374
3375 s->l1_vm_state_index = new_l1_size;
3376 return 0;
3377 }
3378
3379 /* XXX: put compressed sectors first, then all the cluster aligned
3380 tables to avoid losing bytes in alignment */
3381 static coroutine_fn int
3382 qcow2_co_pwritev_compressed(BlockDriverState *bs, uint64_t offset,
3383 uint64_t bytes, QEMUIOVector *qiov)
3384 {
3385 BDRVQcow2State *s = bs->opaque;
3386 QEMUIOVector hd_qiov;
3387 struct iovec iov;
3388 z_stream strm;
3389 int ret, out_len;
3390 uint8_t *buf, *out_buf;
3391 int64_t cluster_offset;
3392
3393 if (bytes == 0) {
3394 /* align end of file to a sector boundary to ease reading with
3395 sector based I/Os */
3396 cluster_offset = bdrv_getlength(bs->file->bs);
3397 if (cluster_offset < 0) {
3398 return cluster_offset;
3399 }
3400 return bdrv_truncate(bs->file, cluster_offset, PREALLOC_MODE_OFF, NULL);
3401 }
3402
3403 if (offset_into_cluster(s, offset)) {
3404 return -EINVAL;
3405 }
3406
3407 buf = qemu_blockalign(bs, s->cluster_size);
3408 if (bytes != s->cluster_size) {
3409 if (bytes > s->cluster_size ||
3410 offset + bytes != bs->total_sectors << BDRV_SECTOR_BITS)
3411 {
3412 qemu_vfree(buf);
3413 return -EINVAL;
3414 }
3415 /* Zero-pad last write if image size is not cluster aligned */
3416 memset(buf + bytes, 0, s->cluster_size - bytes);
3417 }
3418 qemu_iovec_to_buf(qiov, 0, buf, bytes);
3419
3420 out_buf = g_malloc(s->cluster_size);
3421
3422 /* best compression, small window, no zlib header */
3423 memset(&strm, 0, sizeof(strm));
3424 ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
3425 Z_DEFLATED, -12,
3426 9, Z_DEFAULT_STRATEGY);
3427 if (ret != 0) {
3428 ret = -EINVAL;
3429 goto fail;
3430 }
3431
3432 strm.avail_in = s->cluster_size;
3433 strm.next_in = (uint8_t *)buf;
3434 strm.avail_out = s->cluster_size;
3435 strm.next_out = out_buf;
3436
3437 ret = deflate(&strm, Z_FINISH);
3438 if (ret != Z_STREAM_END && ret != Z_OK) {
3439 deflateEnd(&strm);
3440 ret = -EINVAL;
3441 goto fail;
3442 }
3443 out_len = strm.next_out - out_buf;
3444
3445 deflateEnd(&strm);
3446
3447 if (ret != Z_STREAM_END || out_len >= s->cluster_size) {
3448 /* could not compress: write normal cluster */
3449 ret = qcow2_co_pwritev(bs, offset, bytes, qiov, 0);
3450 if (ret < 0) {
3451 goto fail;
3452 }
3453 goto success;
3454 }
3455
3456 qemu_co_mutex_lock(&s->lock);
3457 cluster_offset =
3458 qcow2_alloc_compressed_cluster_offset(bs, offset, out_len);
3459 if (!cluster_offset) {
3460 qemu_co_mutex_unlock(&s->lock);
3461 ret = -EIO;
3462 goto fail;
3463 }
3464 cluster_offset &= s->cluster_offset_mask;
3465
3466 ret = qcow2_pre_write_overlap_check(bs, 0, cluster_offset, out_len);
3467 qemu_co_mutex_unlock(&s->lock);
3468 if (ret < 0) {
3469 goto fail;
3470 }
3471
3472 iov = (struct iovec) {
3473 .iov_base = out_buf,
3474 .iov_len = out_len,
3475 };
3476 qemu_iovec_init_external(&hd_qiov, &iov, 1);
3477
3478 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_COMPRESSED);
3479 ret = bdrv_co_pwritev(bs->file, cluster_offset, out_len, &hd_qiov, 0);
3480 if (ret < 0) {
3481 goto fail;
3482 }
3483 success:
3484 ret = 0;
3485 fail:
3486 qemu_vfree(buf);
3487 g_free(out_buf);
3488 return ret;
3489 }
3490
3491 static int make_completely_empty(BlockDriverState *bs)
3492 {
3493 BDRVQcow2State *s = bs->opaque;
3494 Error *local_err = NULL;
3495 int ret, l1_clusters;
3496 int64_t offset;
3497 uint64_t *new_reftable = NULL;
3498 uint64_t rt_entry, l1_size2;
3499 struct {
3500 uint64_t l1_offset;
3501 uint64_t reftable_offset;
3502 uint32_t reftable_clusters;
3503 } QEMU_PACKED l1_ofs_rt_ofs_cls;
3504
3505 ret = qcow2_cache_empty(bs, s->l2_table_cache);
3506 if (ret < 0) {
3507 goto fail;
3508 }
3509
3510 ret = qcow2_cache_empty(bs, s->refcount_block_cache);
3511 if (ret < 0) {
3512 goto fail;
3513 }
3514
3515 /* Refcounts will be broken utterly */
3516 ret = qcow2_mark_dirty(bs);
3517 if (ret < 0) {
3518 goto fail;
3519 }
3520
3521 BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
3522
3523 l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / sizeof(uint64_t));
3524 l1_size2 = (uint64_t)s->l1_size * sizeof(uint64_t);
3525
3526 /* After this call, neither the in-memory nor the on-disk refcount
3527 * information accurately describe the actual references */
3528
3529 ret = bdrv_pwrite_zeroes(bs->file, s->l1_table_offset,
3530 l1_clusters * s->cluster_size, 0);
3531 if (ret < 0) {
3532 goto fail_broken_refcounts;
3533 }
3534 memset(s->l1_table, 0, l1_size2);
3535
3536 BLKDBG_EVENT(bs->file, BLKDBG_EMPTY_IMAGE_PREPARE);
3537
3538 /* Overwrite enough clusters at the beginning of the sectors to place
3539 * the refcount table, a refcount block and the L1 table in; this may
3540 * overwrite parts of the existing refcount and L1 table, which is not
3541 * an issue because the dirty flag is set, complete data loss is in fact
3542 * desired and partial data loss is consequently fine as well */
3543 ret = bdrv_pwrite_zeroes(bs->file, s->cluster_size,
3544 (2 + l1_clusters) * s->cluster_size, 0);
3545 /* This call (even if it failed overall) may have overwritten on-disk
3546 * refcount structures; in that case, the in-memory refcount information
3547 * will probably differ from the on-disk information which makes the BDS
3548 * unusable */
3549 if (ret < 0) {
3550 goto fail_broken_refcounts;
3551 }
3552
3553 BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
3554 BLKDBG_EVENT(bs->file, BLKDBG_REFTABLE_UPDATE);
3555
3556 /* "Create" an empty reftable (one cluster) directly after the image
3557 * header and an empty L1 table three clusters after the image header;
3558 * the cluster between those two will be used as the first refblock */
3559 l1_ofs_rt_ofs_cls.l1_offset = cpu_to_be64(3 * s->cluster_size);
3560 l1_ofs_rt_ofs_cls.reftable_offset = cpu_to_be64(s->cluster_size);
3561 l1_ofs_rt_ofs_cls.reftable_clusters = cpu_to_be32(1);
3562 ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, l1_table_offset),
3563 &l1_ofs_rt_ofs_cls, sizeof(l1_ofs_rt_ofs_cls));
3564 if (ret < 0) {
3565 goto fail_broken_refcounts;
3566 }
3567
3568 s->l1_table_offset = 3 * s->cluster_size;
3569
3570 new_reftable = g_try_new0(uint64_t, s->cluster_size / sizeof(uint64_t));
3571 if (!new_reftable) {
3572 ret = -ENOMEM;
3573 goto fail_broken_refcounts;
3574 }
3575
3576 s->refcount_table_offset = s->cluster_size;
3577 s->refcount_table_size = s->cluster_size / sizeof(uint64_t);
3578 s->max_refcount_table_index = 0;
3579
3580 g_free(s->refcount_table);
3581 s->refcount_table = new_reftable;
3582 new_reftable = NULL;
3583
3584 /* Now the in-memory refcount information again corresponds to the on-disk
3585 * information (reftable is empty and no refblocks (the refblock cache is
3586 * empty)); however, this means some clusters (e.g. the image header) are
3587 * referenced, but not refcounted, but the normal qcow2 code assumes that
3588 * the in-memory information is always correct */
3589
3590 BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_ALLOC);
3591
3592 /* Enter the first refblock into the reftable */
3593 rt_entry = cpu_to_be64(2 * s->cluster_size);
3594 ret = bdrv_pwrite_sync(bs->file, s->cluster_size,
3595 &rt_entry, sizeof(rt_entry));
3596 if (ret < 0) {
3597 goto fail_broken_refcounts;
3598 }
3599 s->refcount_table[0] = 2 * s->cluster_size;
3600
3601 s->free_cluster_index = 0;
3602 assert(3 + l1_clusters <= s->refcount_block_size);
3603 offset = qcow2_alloc_clusters(bs, 3 * s->cluster_size + l1_size2);
3604 if (offset < 0) {
3605 ret = offset;
3606 goto fail_broken_refcounts;
3607 } else if (offset > 0) {
3608 error_report("First cluster in emptied image is in use");
3609 abort();
3610 }
3611
3612 /* Now finally the in-memory information corresponds to the on-disk
3613 * structures and is correct */
3614 ret = qcow2_mark_clean(bs);
3615 if (ret < 0) {
3616 goto fail;
3617 }
3618
3619 ret = bdrv_truncate(bs->file, (3 + l1_clusters) * s->cluster_size,
3620 PREALLOC_MODE_OFF, &local_err);
3621 if (ret < 0) {
3622 error_report_err(local_err);
3623 goto fail;
3624 }
3625
3626 return 0;
3627
3628 fail_broken_refcounts:
3629 /* The BDS is unusable at this point. If we wanted to make it usable, we
3630 * would have to call qcow2_refcount_close(), qcow2_refcount_init(),
3631 * qcow2_check_refcounts(), qcow2_refcount_close() and qcow2_refcount_init()
3632 * again. However, because the functions which could have caused this error
3633 * path to be taken are used by those functions as well, it's very likely
3634 * that that sequence will fail as well. Therefore, just eject the BDS. */
3635 bs->drv = NULL;
3636
3637 fail:
3638 g_free(new_reftable);
3639 return ret;
3640 }
3641
3642 static int qcow2_make_empty(BlockDriverState *bs)
3643 {
3644 BDRVQcow2State *s = bs->opaque;
3645 uint64_t offset, end_offset;
3646 int step = QEMU_ALIGN_DOWN(INT_MAX, s->cluster_size);
3647 int l1_clusters, ret = 0;
3648
3649 l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / sizeof(uint64_t));
3650
3651 if (s->qcow_version >= 3 && !s->snapshots && !s->nb_bitmaps &&
3652 3 + l1_clusters <= s->refcount_block_size &&
3653 s->crypt_method_header != QCOW_CRYPT_LUKS) {
3654 /* The following function only works for qcow2 v3 images (it
3655 * requires the dirty flag) and only as long as there are no
3656 * features that reserve extra clusters (such as snapshots,
3657 * LUKS header, or persistent bitmaps), because it completely
3658 * empties the image. Furthermore, the L1 table and three
3659 * additional clusters (image header, refcount table, one
3660 * refcount block) have to fit inside one refcount block. */
3661 return make_completely_empty(bs);
3662 }
3663
3664 /* This fallback code simply discards every active cluster; this is slow,
3665 * but works in all cases */
3666 end_offset = bs->total_sectors * BDRV_SECTOR_SIZE;
3667 for (offset = 0; offset < end_offset; offset += step) {
3668 /* As this function is generally used after committing an external
3669 * snapshot, QCOW2_DISCARD_SNAPSHOT seems appropriate. Also, the
3670 * default action for this kind of discard is to pass the discard,
3671 * which will ideally result in an actually smaller image file, as
3672 * is probably desired. */
3673 ret = qcow2_cluster_discard(bs, offset, MIN(step, end_offset - offset),
3674 QCOW2_DISCARD_SNAPSHOT, true);
3675 if (ret < 0) {
3676 break;
3677 }
3678 }
3679
3680 return ret;
3681 }
3682
3683 static coroutine_fn int qcow2_co_flush_to_os(BlockDriverState *bs)
3684 {
3685 BDRVQcow2State *s = bs->opaque;
3686 int ret;
3687
3688 qemu_co_mutex_lock(&s->lock);
3689 ret = qcow2_write_caches(bs);
3690 qemu_co_mutex_unlock(&s->lock);
3691
3692 return ret;
3693 }
3694
3695 static BlockMeasureInfo *qcow2_measure(QemuOpts *opts, BlockDriverState *in_bs,
3696 Error **errp)
3697 {
3698 Error *local_err = NULL;
3699 BlockMeasureInfo *info;
3700 uint64_t required = 0; /* bytes that contribute to required size */
3701 uint64_t virtual_size; /* disk size as seen by guest */
3702 uint64_t refcount_bits;
3703 uint64_t l2_tables;
3704 size_t cluster_size;
3705 int version;
3706 char *optstr;
3707 PreallocMode prealloc;
3708 bool has_backing_file;
3709
3710 /* Parse image creation options */
3711 cluster_size = qcow2_opt_get_cluster_size_del(opts, &local_err);
3712 if (local_err) {
3713 goto err;
3714 }
3715
3716 version = qcow2_opt_get_version_del(opts, &local_err);
3717 if (local_err) {
3718 goto err;
3719 }
3720
3721 refcount_bits = qcow2_opt_get_refcount_bits_del(opts, version, &local_err);
3722 if (local_err) {
3723 goto err;
3724 }
3725
3726 optstr = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
3727 prealloc = qapi_enum_parse(&PreallocMode_lookup, optstr,
3728 PREALLOC_MODE_OFF, &local_err);
3729 g_free(optstr);
3730 if (local_err) {
3731 goto err;
3732 }
3733
3734 optstr = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
3735 has_backing_file = !!optstr;
3736 g_free(optstr);
3737
3738 virtual_size = qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0);
3739 virtual_size = ROUND_UP(virtual_size, cluster_size);
3740
3741 /* Check that virtual disk size is valid */
3742 l2_tables = DIV_ROUND_UP(virtual_size / cluster_size,
3743 cluster_size / sizeof(uint64_t));
3744 if (l2_tables * sizeof(uint64_t) > QCOW_MAX_L1_SIZE) {
3745 error_setg(&local_err, "The image size is too large "
3746 "(try using a larger cluster size)");
3747 goto err;
3748 }
3749
3750 /* Account for input image */
3751 if (in_bs) {
3752 int64_t ssize = bdrv_getlength(in_bs);
3753 if (ssize < 0) {
3754 error_setg_errno(&local_err, -ssize,
3755 "Unable to get image virtual_size");
3756 goto err;
3757 }
3758
3759 virtual_size = ROUND_UP(ssize, cluster_size);
3760
3761 if (has_backing_file) {
3762 /* We don't how much of the backing chain is shared by the input
3763 * image and the new image file. In the worst case the new image's
3764 * backing file has nothing in common with the input image. Be
3765 * conservative and assume all clusters need to be written.
3766 */
3767 required = virtual_size;
3768 } else {
3769 int64_t offset;
3770 int64_t pnum = 0;
3771
3772 for (offset = 0; offset < ssize; offset += pnum) {
3773 int ret;
3774
3775 ret = bdrv_block_status_above(in_bs, NULL, offset,
3776 ssize - offset, &pnum, NULL,
3777 NULL);
3778 if (ret < 0) {
3779 error_setg_errno(&local_err, -ret,
3780 "Unable to get block status");
3781 goto err;
3782 }
3783
3784 if (ret & BDRV_BLOCK_ZERO) {
3785 /* Skip zero regions (safe with no backing file) */
3786 } else if ((ret & (BDRV_BLOCK_DATA | BDRV_BLOCK_ALLOCATED)) ==
3787 (BDRV_BLOCK_DATA | BDRV_BLOCK_ALLOCATED)) {
3788 /* Extend pnum to end of cluster for next iteration */
3789 pnum = ROUND_UP(offset + pnum, cluster_size) - offset;
3790
3791 /* Count clusters we've seen */
3792 required += offset % cluster_size + pnum;
3793 }
3794 }
3795 }
3796 }
3797
3798 /* Take into account preallocation. Nothing special is needed for
3799 * PREALLOC_MODE_METADATA since metadata is always counted.
3800 */
3801 if (prealloc == PREALLOC_MODE_FULL || prealloc == PREALLOC_MODE_FALLOC) {
3802 required = virtual_size;
3803 }
3804
3805 info = g_new(BlockMeasureInfo, 1);
3806 info->fully_allocated =
3807 qcow2_calc_prealloc_size(virtual_size, cluster_size,
3808 ctz32(refcount_bits));
3809
3810 /* Remove data clusters that are not required. This overestimates the
3811 * required size because metadata needed for the fully allocated file is
3812 * still counted.
3813 */
3814 info->required = info->fully_allocated - virtual_size + required;
3815 return info;
3816
3817 err:
3818 error_propagate(errp, local_err);
3819 return NULL;
3820 }
3821
3822 static int qcow2_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
3823 {
3824 BDRVQcow2State *s = bs->opaque;
3825 bdi->unallocated_blocks_are_zero = true;
3826 bdi->cluster_size = s->cluster_size;
3827 bdi->vm_state_offset = qcow2_vm_state_offset(s);
3828 return 0;
3829 }
3830
3831 static ImageInfoSpecific *qcow2_get_specific_info(BlockDriverState *bs)
3832 {
3833 BDRVQcow2State *s = bs->opaque;
3834 ImageInfoSpecific *spec_info;
3835 QCryptoBlockInfo *encrypt_info = NULL;
3836
3837 if (s->crypto != NULL) {
3838 encrypt_info = qcrypto_block_get_info(s->crypto, &error_abort);
3839 }
3840
3841 spec_info = g_new(ImageInfoSpecific, 1);
3842 *spec_info = (ImageInfoSpecific){
3843 .type = IMAGE_INFO_SPECIFIC_KIND_QCOW2,
3844 .u.qcow2.data = g_new(ImageInfoSpecificQCow2, 1),
3845 };
3846 if (s->qcow_version == 2) {
3847 *spec_info->u.qcow2.data = (ImageInfoSpecificQCow2){
3848 .compat = g_strdup("0.10"),
3849 .refcount_bits = s->refcount_bits,
3850 };
3851 } else if (s->qcow_version == 3) {
3852 *spec_info->u.qcow2.data = (ImageInfoSpecificQCow2){
3853 .compat = g_strdup("1.1"),
3854 .lazy_refcounts = s->compatible_features &
3855 QCOW2_COMPAT_LAZY_REFCOUNTS,
3856 .has_lazy_refcounts = true,
3857 .corrupt = s->incompatible_features &
3858 QCOW2_INCOMPAT_CORRUPT,
3859 .has_corrupt = true,
3860 .refcount_bits = s->refcount_bits,
3861 };
3862 } else {
3863 /* if this assertion fails, this probably means a new version was
3864 * added without having it covered here */
3865 assert(false);
3866 }
3867
3868 if (encrypt_info) {
3869 ImageInfoSpecificQCow2Encryption *qencrypt =
3870 g_new(ImageInfoSpecificQCow2Encryption, 1);
3871 switch (encrypt_info->format) {
3872 case Q_CRYPTO_BLOCK_FORMAT_QCOW:
3873 qencrypt->format = BLOCKDEV_QCOW2_ENCRYPTION_FORMAT_AES;
3874 qencrypt->u.aes = encrypt_info->u.qcow;
3875 break;
3876 case Q_CRYPTO_BLOCK_FORMAT_LUKS:
3877 qencrypt->format = BLOCKDEV_QCOW2_ENCRYPTION_FORMAT_LUKS;
3878 qencrypt->u.luks = encrypt_info->u.luks;
3879 break;
3880 default:
3881 abort();
3882 }
3883 /* Since we did shallow copy above, erase any pointers
3884 * in the original info */
3885 memset(&encrypt_info->u, 0, sizeof(encrypt_info->u));
3886 qapi_free_QCryptoBlockInfo(encrypt_info);
3887
3888 spec_info->u.qcow2.data->has_encrypt = true;
3889 spec_info->u.qcow2.data->encrypt = qencrypt;
3890 }
3891
3892 return spec_info;
3893 }
3894
3895 static int qcow2_save_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
3896 int64_t pos)
3897 {
3898 BDRVQcow2State *s = bs->opaque;
3899
3900 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_SAVE);
3901 return bs->drv->bdrv_co_pwritev(bs, qcow2_vm_state_offset(s) + pos,
3902 qiov->size, qiov, 0);
3903 }
3904
3905 static int qcow2_load_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
3906 int64_t pos)
3907 {
3908 BDRVQcow2State *s = bs->opaque;
3909
3910 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_LOAD);
3911 return bs->drv->bdrv_co_preadv(bs, qcow2_vm_state_offset(s) + pos,
3912 qiov->size, qiov, 0);
3913 }
3914
3915 /*
3916 * Downgrades an image's version. To achieve this, any incompatible features
3917 * have to be removed.
3918 */
3919 static int qcow2_downgrade(BlockDriverState *bs, int target_version,
3920 BlockDriverAmendStatusCB *status_cb, void *cb_opaque)
3921 {
3922 BDRVQcow2State *s = bs->opaque;
3923 int current_version = s->qcow_version;
3924 int ret;
3925
3926 if (target_version == current_version) {
3927 return 0;
3928 } else if (target_version > current_version) {
3929 return -EINVAL;
3930 } else if (target_version != 2) {
3931 return -EINVAL;
3932 }
3933
3934 if (s->refcount_order != 4) {
3935 error_report("compat=0.10 requires refcount_bits=16");
3936 return -ENOTSUP;
3937 }
3938
3939 /* clear incompatible features */
3940 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
3941 ret = qcow2_mark_clean(bs);
3942 if (ret < 0) {
3943 return ret;
3944 }
3945 }
3946
3947 /* with QCOW2_INCOMPAT_CORRUPT, it is pretty much impossible to get here in
3948 * the first place; if that happens nonetheless, returning -ENOTSUP is the
3949 * best thing to do anyway */
3950
3951 if (s->incompatible_features) {
3952 return -ENOTSUP;
3953 }
3954
3955 /* since we can ignore compatible features, we can set them to 0 as well */
3956 s->compatible_features = 0;
3957 /* if lazy refcounts have been used, they have already been fixed through
3958 * clearing the dirty flag */
3959
3960 /* clearing autoclear features is trivial */
3961 s->autoclear_features = 0;
3962
3963 ret = qcow2_expand_zero_clusters(bs, status_cb, cb_opaque);
3964 if (ret < 0) {
3965 return ret;
3966 }
3967
3968 s->qcow_version = target_version;
3969 ret = qcow2_update_header(bs);
3970 if (ret < 0) {
3971 s->qcow_version = current_version;
3972 return ret;
3973 }
3974 return 0;
3975 }
3976
3977 typedef enum Qcow2AmendOperation {
3978 /* This is the value Qcow2AmendHelperCBInfo::last_operation will be
3979 * statically initialized to so that the helper CB can discern the first
3980 * invocation from an operation change */
3981 QCOW2_NO_OPERATION = 0,
3982
3983 QCOW2_CHANGING_REFCOUNT_ORDER,
3984 QCOW2_DOWNGRADING,
3985 } Qcow2AmendOperation;
3986
3987 typedef struct Qcow2AmendHelperCBInfo {
3988 /* The code coordinating the amend operations should only modify
3989 * these four fields; the rest will be managed by the CB */
3990 BlockDriverAmendStatusCB *original_status_cb;
3991 void *original_cb_opaque;
3992
3993 Qcow2AmendOperation current_operation;
3994
3995 /* Total number of operations to perform (only set once) */
3996 int total_operations;
3997
3998 /* The following fields are managed by the CB */
3999
4000 /* Number of operations completed */
4001 int operations_completed;
4002
4003 /* Cumulative offset of all completed operations */
4004 int64_t offset_completed;
4005
4006 Qcow2AmendOperation last_operation;
4007 int64_t last_work_size;
4008 } Qcow2AmendHelperCBInfo;
4009
4010 static void qcow2_amend_helper_cb(BlockDriverState *bs,
4011 int64_t operation_offset,
4012 int64_t operation_work_size, void *opaque)
4013 {
4014 Qcow2AmendHelperCBInfo *info = opaque;
4015 int64_t current_work_size;
4016 int64_t projected_work_size;
4017
4018 if (info->current_operation != info->last_operation) {
4019 if (info->last_operation != QCOW2_NO_OPERATION) {
4020 info->offset_completed += info->last_work_size;
4021 info->operations_completed++;
4022 }
4023
4024 info->last_operation = info->current_operation;
4025 }
4026
4027 assert(info->total_operations > 0);
4028 assert(info->operations_completed < info->total_operations);
4029
4030 info->last_work_size = operation_work_size;
4031
4032 current_work_size = info->offset_completed + operation_work_size;
4033
4034 /* current_work_size is the total work size for (operations_completed + 1)
4035 * operations (which includes this one), so multiply it by the number of
4036 * operations not covered and divide it by the number of operations
4037 * covered to get a projection for the operations not covered */
4038 projected_work_size = current_work_size * (info->total_operations -
4039 info->operations_completed - 1)
4040 / (info->operations_completed + 1);
4041
4042 info->original_status_cb(bs, info->offset_completed + operation_offset,
4043 current_work_size + projected_work_size,
4044 info->original_cb_opaque);
4045 }
4046
4047 static int qcow2_amend_options(BlockDriverState *bs, QemuOpts *opts,
4048 BlockDriverAmendStatusCB *status_cb,
4049 void *cb_opaque)
4050 {
4051 BDRVQcow2State *s = bs->opaque;
4052 int old_version = s->qcow_version, new_version = old_version;
4053 uint64_t new_size = 0;
4054 const char *backing_file = NULL, *backing_format = NULL;
4055 bool lazy_refcounts = s->use_lazy_refcounts;
4056 const char *compat = NULL;
4057 uint64_t cluster_size = s->cluster_size;
4058 bool encrypt;
4059 int encformat;
4060 int refcount_bits = s->refcount_bits;
4061 Error *local_err = NULL;
4062 int ret;
4063 QemuOptDesc *desc = opts->list->desc;
4064 Qcow2AmendHelperCBInfo helper_cb_info;
4065
4066 while (desc && desc->name) {
4067 if (!qemu_opt_find(opts, desc->name)) {
4068 /* only change explicitly defined options */
4069 desc++;
4070 continue;
4071 }
4072
4073 if (!strcmp(desc->name, BLOCK_OPT_COMPAT_LEVEL)) {
4074 compat = qemu_opt_get(opts, BLOCK_OPT_COMPAT_LEVEL);
4075 if (!compat) {
4076 /* preserve default */
4077 } else if (!strcmp(compat, "0.10")) {
4078 new_version = 2;
4079 } else if (!strcmp(compat, "1.1")) {
4080 new_version = 3;
4081 } else {
4082 error_report("Unknown compatibility level %s", compat);
4083 return -EINVAL;
4084 }
4085 } else if (!strcmp(desc->name, BLOCK_OPT_PREALLOC)) {
4086 error_report("Cannot change preallocation mode");
4087 return -ENOTSUP;
4088 } else if (!strcmp(desc->name, BLOCK_OPT_SIZE)) {
4089 new_size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, 0);
4090 } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FILE)) {
4091 backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
4092 } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FMT)) {
4093 backing_format = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
4094 } else if (!strcmp(desc->name, BLOCK_OPT_ENCRYPT)) {
4095 encrypt = qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT,
4096 !!s->crypto);
4097
4098 if (encrypt != !!s->crypto) {
4099 error_report("Changing the encryption flag is not supported");
4100 return -ENOTSUP;
4101 }
4102 } else if (!strcmp(desc->name, BLOCK_OPT_ENCRYPT_FORMAT)) {
4103 encformat = qcow2_crypt_method_from_format(
4104 qemu_opt_get(opts, BLOCK_OPT_ENCRYPT_FORMAT));
4105
4106 if (encformat != s->crypt_method_header) {
4107 error_report("Changing the encryption format is not supported");
4108 return -ENOTSUP;
4109 }
4110 } else if (g_str_has_prefix(desc->name, "encrypt.")) {
4111 error_report("Changing the encryption parameters is not supported");
4112 return -ENOTSUP;
4113 } else if (!strcmp(desc->name, BLOCK_OPT_CLUSTER_SIZE)) {
4114 cluster_size = qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE,
4115 cluster_size);
4116 if (cluster_size != s->cluster_size) {
4117 error_report("Changing the cluster size is not supported");
4118 return -ENOTSUP;
4119 }
4120 } else if (!strcmp(desc->name, BLOCK_OPT_LAZY_REFCOUNTS)) {
4121 lazy_refcounts = qemu_opt_get_bool(opts, BLOCK_OPT_LAZY_REFCOUNTS,
4122 lazy_refcounts);
4123 } else if (!strcmp(desc->name, BLOCK_OPT_REFCOUNT_BITS)) {
4124 refcount_bits = qemu_opt_get_number(opts, BLOCK_OPT_REFCOUNT_BITS,
4125 refcount_bits);
4126
4127 if (refcount_bits <= 0 || refcount_bits > 64 ||
4128 !is_power_of_2(refcount_bits))
4129 {
4130 error_report("Refcount width must be a power of two and may "
4131 "not exceed 64 bits");
4132 return -EINVAL;
4133 }
4134 } else {
4135 /* if this point is reached, this probably means a new option was
4136 * added without having it covered here */
4137 abort();
4138 }
4139
4140 desc++;
4141 }
4142
4143 helper_cb_info = (Qcow2AmendHelperCBInfo){
4144 .original_status_cb = status_cb,
4145 .original_cb_opaque = cb_opaque,
4146 .total_operations = (new_version < old_version)
4147 + (s->refcount_bits != refcount_bits)
4148 };
4149
4150 /* Upgrade first (some features may require compat=1.1) */
4151 if (new_version > old_version) {
4152 s->qcow_version = new_version;
4153 ret = qcow2_update_header(bs);
4154 if (ret < 0) {
4155 s->qcow_version = old_version;
4156 return ret;
4157 }
4158 }
4159
4160 if (s->refcount_bits != refcount_bits) {
4161 int refcount_order = ctz32(refcount_bits);
4162
4163 if (new_version < 3 && refcount_bits != 16) {
4164 error_report("Different refcount widths than 16 bits require "
4165 "compatibility level 1.1 or above (use compat=1.1 or "
4166 "greater)");
4167 return -EINVAL;
4168 }
4169
4170 helper_cb_info.current_operation = QCOW2_CHANGING_REFCOUNT_ORDER;
4171 ret = qcow2_change_refcount_order(bs, refcount_order,
4172 &qcow2_amend_helper_cb,
4173 &helper_cb_info, &local_err);
4174 if (ret < 0) {
4175 error_report_err(local_err);
4176 return ret;
4177 }
4178 }
4179
4180 if (backing_file || backing_format) {
4181 ret = qcow2_change_backing_file(bs,
4182 backing_file ?: s->image_backing_file,
4183 backing_format ?: s->image_backing_format);
4184 if (ret < 0) {
4185 return ret;
4186 }
4187 }
4188
4189 if (s->use_lazy_refcounts != lazy_refcounts) {
4190 if (lazy_refcounts) {
4191 if (new_version < 3) {
4192 error_report("Lazy refcounts only supported with compatibility "
4193 "level 1.1 and above (use compat=1.1 or greater)");
4194 return -EINVAL;
4195 }
4196 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
4197 ret = qcow2_update_header(bs);
4198 if (ret < 0) {
4199 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
4200 return ret;
4201 }
4202 s->use_lazy_refcounts = true;
4203 } else {
4204 /* make image clean first */
4205 ret = qcow2_mark_clean(bs);
4206 if (ret < 0) {
4207 return ret;
4208 }
4209 /* now disallow lazy refcounts */
4210 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
4211 ret = qcow2_update_header(bs);
4212 if (ret < 0) {
4213 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
4214 return ret;
4215 }
4216 s->use_lazy_refcounts = false;
4217 }
4218 }
4219
4220 if (new_size) {
4221 BlockBackend *blk = blk_new(BLK_PERM_RESIZE, BLK_PERM_ALL);
4222 ret = blk_insert_bs(blk, bs, &local_err);
4223 if (ret < 0) {
4224 error_report_err(local_err);
4225 blk_unref(blk);
4226 return ret;
4227 }
4228
4229 ret = blk_truncate(blk, new_size, PREALLOC_MODE_OFF, &local_err);
4230 blk_unref(blk);
4231 if (ret < 0) {
4232 error_report_err(local_err);
4233 return ret;
4234 }
4235 }
4236
4237 /* Downgrade last (so unsupported features can be removed before) */
4238 if (new_version < old_version) {
4239 helper_cb_info.current_operation = QCOW2_DOWNGRADING;
4240 ret = qcow2_downgrade(bs, new_version, &qcow2_amend_helper_cb,
4241 &helper_cb_info);
4242 if (ret < 0) {
4243 return ret;
4244 }
4245 }
4246
4247 return 0;
4248 }
4249
4250 /*
4251 * If offset or size are negative, respectively, they will not be included in
4252 * the BLOCK_IMAGE_CORRUPTED event emitted.
4253 * fatal will be ignored for read-only BDS; corruptions found there will always
4254 * be considered non-fatal.
4255 */
4256 void qcow2_signal_corruption(BlockDriverState *bs, bool fatal, int64_t offset,
4257 int64_t size, const char *message_format, ...)
4258 {
4259 BDRVQcow2State *s = bs->opaque;
4260 const char *node_name;
4261 char *message;
4262 va_list ap;
4263
4264 fatal = fatal && !bs->read_only;
4265
4266 if (s->signaled_corruption &&
4267 (!fatal || (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT)))
4268 {
4269 return;
4270 }
4271
4272 va_start(ap, message_format);
4273 message = g_strdup_vprintf(message_format, ap);
4274 va_end(ap);
4275
4276 if (fatal) {
4277 fprintf(stderr, "qcow2: Marking image as corrupt: %s; further "
4278 "corruption events will be suppressed\n", message);
4279 } else {
4280 fprintf(stderr, "qcow2: Image is corrupt: %s; further non-fatal "
4281 "corruption events will be suppressed\n", message);
4282 }
4283
4284 node_name = bdrv_get_node_name(bs);
4285 qapi_event_send_block_image_corrupted(bdrv_get_device_name(bs),
4286 *node_name != '\0', node_name,
4287 message, offset >= 0, offset,
4288 size >= 0, size,
4289 fatal, &error_abort);
4290 g_free(message);
4291
4292 if (fatal) {
4293 qcow2_mark_corrupt(bs);
4294 bs->drv = NULL; /* make BDS unusable */
4295 }
4296
4297 s->signaled_corruption = true;
4298 }
4299
4300 static QemuOptsList qcow2_create_opts = {
4301 .name = "qcow2-create-opts",
4302 .head = QTAILQ_HEAD_INITIALIZER(qcow2_create_opts.head),
4303 .desc = {
4304 {
4305 .name = BLOCK_OPT_SIZE,
4306 .type = QEMU_OPT_SIZE,
4307 .help = "Virtual disk size"
4308 },
4309 {
4310 .name = BLOCK_OPT_COMPAT_LEVEL,
4311 .type = QEMU_OPT_STRING,
4312 .help = "Compatibility level (0.10 or 1.1)"
4313 },
4314 {
4315 .name = BLOCK_OPT_BACKING_FILE,
4316 .type = QEMU_OPT_STRING,
4317 .help = "File name of a base image"
4318 },
4319 {
4320 .name = BLOCK_OPT_BACKING_FMT,
4321 .type = QEMU_OPT_STRING,
4322 .help = "Image format of the base image"
4323 },
4324 {
4325 .name = BLOCK_OPT_ENCRYPT,
4326 .type = QEMU_OPT_BOOL,
4327 .help = "Encrypt the image with format 'aes'. (Deprecated "
4328 "in favor of " BLOCK_OPT_ENCRYPT_FORMAT "=aes)",
4329 },
4330 {
4331 .name = BLOCK_OPT_ENCRYPT_FORMAT,
4332 .type = QEMU_OPT_STRING,
4333 .help = "Encrypt the image, format choices: 'aes', 'luks'",
4334 },
4335 BLOCK_CRYPTO_OPT_DEF_KEY_SECRET("encrypt.",
4336 "ID of secret providing qcow AES key or LUKS passphrase"),
4337 BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_ALG("encrypt."),
4338 BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_MODE("encrypt."),
4339 BLOCK_CRYPTO_OPT_DEF_LUKS_IVGEN_ALG("encrypt."),
4340 BLOCK_CRYPTO_OPT_DEF_LUKS_IVGEN_HASH_ALG("encrypt."),
4341 BLOCK_CRYPTO_OPT_DEF_LUKS_HASH_ALG("encrypt."),
4342 BLOCK_CRYPTO_OPT_DEF_LUKS_ITER_TIME("encrypt."),
4343 {
4344 .name = BLOCK_OPT_CLUSTER_SIZE,
4345 .type = QEMU_OPT_SIZE,
4346 .help = "qcow2 cluster size",
4347 .def_value_str = stringify(DEFAULT_CLUSTER_SIZE)
4348 },
4349 {
4350 .name = BLOCK_OPT_PREALLOC,
4351 .type = QEMU_OPT_STRING,
4352 .help = "Preallocation mode (allowed values: off, metadata, "
4353 "falloc, full)"
4354 },
4355 {
4356 .name = BLOCK_OPT_LAZY_REFCOUNTS,
4357 .type = QEMU_OPT_BOOL,
4358 .help = "Postpone refcount updates",
4359 .def_value_str = "off"
4360 },
4361 {
4362 .name = BLOCK_OPT_REFCOUNT_BITS,
4363 .type = QEMU_OPT_NUMBER,
4364 .help = "Width of a reference count entry in bits",
4365 .def_value_str = "16"
4366 },
4367 { /* end of list */ }
4368 }
4369 };
4370
4371 BlockDriver bdrv_qcow2 = {
4372 .format_name = "qcow2",
4373 .instance_size = sizeof(BDRVQcow2State),
4374 .bdrv_probe = qcow2_probe,
4375 .bdrv_open = qcow2_open,
4376 .bdrv_close = qcow2_close,
4377 .bdrv_reopen_prepare = qcow2_reopen_prepare,
4378 .bdrv_reopen_commit = qcow2_reopen_commit,
4379 .bdrv_reopen_abort = qcow2_reopen_abort,
4380 .bdrv_join_options = qcow2_join_options,
4381 .bdrv_child_perm = bdrv_format_default_perms,
4382 .bdrv_co_create_opts = qcow2_co_create_opts,
4383 .bdrv_has_zero_init = bdrv_has_zero_init_1,
4384 .bdrv_co_block_status = qcow2_co_block_status,
4385
4386 .bdrv_co_preadv = qcow2_co_preadv,
4387 .bdrv_co_pwritev = qcow2_co_pwritev,
4388 .bdrv_co_flush_to_os = qcow2_co_flush_to_os,
4389
4390 .bdrv_co_pwrite_zeroes = qcow2_co_pwrite_zeroes,
4391 .bdrv_co_pdiscard = qcow2_co_pdiscard,
4392 .bdrv_truncate = qcow2_truncate,
4393 .bdrv_co_pwritev_compressed = qcow2_co_pwritev_compressed,
4394 .bdrv_make_empty = qcow2_make_empty,
4395
4396 .bdrv_snapshot_create = qcow2_snapshot_create,
4397 .bdrv_snapshot_goto = qcow2_snapshot_goto,
4398 .bdrv_snapshot_delete = qcow2_snapshot_delete,
4399 .bdrv_snapshot_list = qcow2_snapshot_list,
4400 .bdrv_snapshot_load_tmp = qcow2_snapshot_load_tmp,
4401 .bdrv_measure = qcow2_measure,
4402 .bdrv_get_info = qcow2_get_info,
4403 .bdrv_get_specific_info = qcow2_get_specific_info,
4404
4405 .bdrv_save_vmstate = qcow2_save_vmstate,
4406 .bdrv_load_vmstate = qcow2_load_vmstate,
4407
4408 .supports_backing = true,
4409 .bdrv_change_backing_file = qcow2_change_backing_file,
4410
4411 .bdrv_refresh_limits = qcow2_refresh_limits,
4412 .bdrv_co_invalidate_cache = qcow2_co_invalidate_cache,
4413 .bdrv_inactivate = qcow2_inactivate,
4414
4415 .create_opts = &qcow2_create_opts,
4416 .bdrv_check = qcow2_check,
4417 .bdrv_amend_options = qcow2_amend_options,
4418
4419 .bdrv_detach_aio_context = qcow2_detach_aio_context,
4420 .bdrv_attach_aio_context = qcow2_attach_aio_context,
4421
4422 .bdrv_reopen_bitmaps_rw = qcow2_reopen_bitmaps_rw,
4423 .bdrv_can_store_new_dirty_bitmap = qcow2_can_store_new_dirty_bitmap,
4424 .bdrv_remove_persistent_dirty_bitmap = qcow2_remove_persistent_dirty_bitmap,
4425 };
4426
4427 static void bdrv_qcow2_init(void)
4428 {
4429 bdrv_register(&bdrv_qcow2);
4430 }
4431
4432 block_init(bdrv_qcow2_init);