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