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