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