]> git.proxmox.com Git - mirror_qemu.git/blame - block/qcow2.c
qemu-img: Add --target-is-zero to convert
[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
88f468e5
VSO
2071 if (qcow2_co_decrypt(bs,
2072 file_cluster_offset + offset_into_cluster(s, offset),
2073 offset, buf, bytes) < 0)
2074 {
2075 ret = -EIO;
2076 goto fail;
2077 }
2078 qemu_iovec_from_buf(qiov, qiov_offset, buf, bytes);
2079
2080fail:
2081 qemu_vfree(buf);
2082
2083 return ret;
2084}
2085
d710cf57
VSO
2086typedef struct Qcow2AioTask {
2087 AioTask task;
2088
2089 BlockDriverState *bs;
2090 QCow2ClusterType cluster_type; /* only for read */
2091 uint64_t file_cluster_offset;
2092 uint64_t offset;
2093 uint64_t bytes;
2094 QEMUIOVector *qiov;
2095 uint64_t qiov_offset;
2096 QCowL2Meta *l2meta; /* only for write */
2097} Qcow2AioTask;
2098
2099static coroutine_fn int qcow2_co_preadv_task_entry(AioTask *task);
2100static coroutine_fn int qcow2_add_task(BlockDriverState *bs,
2101 AioTaskPool *pool,
2102 AioTaskFunc func,
2103 QCow2ClusterType cluster_type,
2104 uint64_t file_cluster_offset,
2105 uint64_t offset,
2106 uint64_t bytes,
2107 QEMUIOVector *qiov,
2108 size_t qiov_offset,
2109 QCowL2Meta *l2meta)
2110{
2111 Qcow2AioTask local_task;
2112 Qcow2AioTask *task = pool ? g_new(Qcow2AioTask, 1) : &local_task;
2113
2114 *task = (Qcow2AioTask) {
2115 .task.func = func,
2116 .bs = bs,
2117 .cluster_type = cluster_type,
2118 .qiov = qiov,
2119 .file_cluster_offset = file_cluster_offset,
2120 .offset = offset,
2121 .bytes = bytes,
2122 .qiov_offset = qiov_offset,
2123 .l2meta = l2meta,
2124 };
2125
2126 trace_qcow2_add_task(qemu_coroutine_self(), bs, pool,
2127 func == qcow2_co_preadv_task_entry ? "read" : "write",
2128 cluster_type, file_cluster_offset, offset, bytes,
2129 qiov, qiov_offset);
2130
2131 if (!pool) {
2132 return func(&task->task);
2133 }
2134
2135 aio_task_pool_start_task(pool, &task->task);
2136
2137 return 0;
2138}
2139
88f468e5
VSO
2140static coroutine_fn int qcow2_co_preadv_task(BlockDriverState *bs,
2141 QCow2ClusterType cluster_type,
2142 uint64_t file_cluster_offset,
2143 uint64_t offset, uint64_t bytes,
2144 QEMUIOVector *qiov,
2145 size_t qiov_offset)
2146{
2147 BDRVQcow2State *s = bs->opaque;
2148 int offset_in_cluster = offset_into_cluster(s, offset);
2149
2150 switch (cluster_type) {
2151 case QCOW2_CLUSTER_ZERO_PLAIN:
2152 case QCOW2_CLUSTER_ZERO_ALLOC:
2153 /* Both zero types are handled in qcow2_co_preadv_part */
2154 g_assert_not_reached();
2155
2156 case QCOW2_CLUSTER_UNALLOCATED:
2157 assert(bs->backing); /* otherwise handled in qcow2_co_preadv_part */
2158
2159 BLKDBG_EVENT(bs->file, BLKDBG_READ_BACKING_AIO);
2160 return bdrv_co_preadv_part(bs->backing, offset, bytes,
2161 qiov, qiov_offset, 0);
2162
2163 case QCOW2_CLUSTER_COMPRESSED:
2164 return qcow2_co_preadv_compressed(bs, file_cluster_offset,
2165 offset, bytes, qiov, qiov_offset);
2166
2167 case QCOW2_CLUSTER_NORMAL:
344ffea9 2168 assert(offset_into_cluster(s, file_cluster_offset) == 0);
88f468e5
VSO
2169 if (bs->encrypted) {
2170 return qcow2_co_preadv_encrypted(bs, file_cluster_offset,
2171 offset, bytes, qiov, qiov_offset);
2172 }
2173
2174 BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);
2175 return bdrv_co_preadv_part(s->data_file,
2176 file_cluster_offset + offset_in_cluster,
2177 bytes, qiov, qiov_offset, 0);
2178
2179 default:
2180 g_assert_not_reached();
2181 }
2182
2183 g_assert_not_reached();
2184}
2185
d710cf57
VSO
2186static coroutine_fn int qcow2_co_preadv_task_entry(AioTask *task)
2187{
2188 Qcow2AioTask *t = container_of(task, Qcow2AioTask, task);
2189
2190 assert(!t->l2meta);
2191
2192 return qcow2_co_preadv_task(t->bs, t->cluster_type, t->file_cluster_offset,
2193 t->offset, t->bytes, t->qiov, t->qiov_offset);
2194}
2195
df893d25
VSO
2196static coroutine_fn int qcow2_co_preadv_part(BlockDriverState *bs,
2197 uint64_t offset, uint64_t bytes,
2198 QEMUIOVector *qiov,
2199 size_t qiov_offset, int flags)
585f8587 2200{
ff99129a 2201 BDRVQcow2State *s = bs->opaque;
d710cf57 2202 int ret = 0;
ecfe1863 2203 unsigned int cur_bytes; /* number of bytes in current iteration */
c2bdd990 2204 uint64_t cluster_offset = 0;
d710cf57 2205 AioTaskPool *aio = NULL;
585f8587 2206
d710cf57 2207 while (bytes != 0 && aio_task_pool_status(aio) == 0) {
5ebaa27e 2208 /* prepare next request */
ecfe1863 2209 cur_bytes = MIN(bytes, INT_MAX);
b25b387f 2210 if (s->crypto) {
ecfe1863
KW
2211 cur_bytes = MIN(cur_bytes,
2212 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
585f8587 2213 }
5ebaa27e 2214
f24196d3 2215 qemu_co_mutex_lock(&s->lock);
ecfe1863 2216 ret = qcow2_get_cluster_offset(bs, offset, &cur_bytes, &cluster_offset);
f24196d3 2217 qemu_co_mutex_unlock(&s->lock);
8af36488 2218 if (ret < 0) {
d710cf57 2219 goto out;
8af36488 2220 }
bd28f835 2221
88f468e5
VSO
2222 if (ret == QCOW2_CLUSTER_ZERO_PLAIN ||
2223 ret == QCOW2_CLUSTER_ZERO_ALLOC ||
2224 (ret == QCOW2_CLUSTER_UNALLOCATED && !bs->backing))
2225 {
df893d25 2226 qemu_iovec_memset(qiov, qiov_offset, 0, cur_bytes);
88f468e5 2227 } else {
d710cf57
VSO
2228 if (!aio && cur_bytes != bytes) {
2229 aio = aio_task_pool_new(QCOW2_MAX_WORKERS);
2230 }
2231 ret = qcow2_add_task(bs, aio, qcow2_co_preadv_task_entry, ret,
2232 cluster_offset, offset, cur_bytes,
2233 qiov, qiov_offset, NULL);
5ebaa27e 2234 if (ret < 0) {
d710cf57 2235 goto out;
5ebaa27e 2236 }
faf575c1 2237 }
f141eafe 2238
ecfe1863
KW
2239 bytes -= cur_bytes;
2240 offset += cur_bytes;
df893d25 2241 qiov_offset += cur_bytes;
5ebaa27e 2242 }
68d100e9 2243
d710cf57
VSO
2244out:
2245 if (aio) {
2246 aio_task_pool_wait_all(aio);
2247 if (ret == 0) {
2248 ret = aio_task_pool_status(aio);
2249 }
2250 g_free(aio);
2251 }
2252
2253 return ret;
585f8587
FB
2254}
2255
ee22a9d8
AG
2256/* Check if it's possible to merge a write request with the writing of
2257 * the data from the COW regions */
2258static bool merge_cow(uint64_t offset, unsigned bytes,
5396234b
VSO
2259 QEMUIOVector *qiov, size_t qiov_offset,
2260 QCowL2Meta *l2meta)
ee22a9d8
AG
2261{
2262 QCowL2Meta *m;
2263
2264 for (m = l2meta; m != NULL; m = m->next) {
2265 /* If both COW regions are empty then there's nothing to merge */
2266 if (m->cow_start.nb_bytes == 0 && m->cow_end.nb_bytes == 0) {
2267 continue;
2268 }
2269
c8bb23cb
AN
2270 /* If COW regions are handled already, skip this too */
2271 if (m->skip_cow) {
2272 continue;
2273 }
2274
ee22a9d8
AG
2275 /* The data (middle) region must be immediately after the
2276 * start region */
2277 if (l2meta_cow_start(m) + m->cow_start.nb_bytes != offset) {
2278 continue;
2279 }
2280
2281 /* The end region must be immediately after the data (middle)
2282 * region */
2283 if (m->offset + m->cow_end.offset != offset + bytes) {
2284 continue;
2285 }
2286
2287 /* Make sure that adding both COW regions to the QEMUIOVector
2288 * does not exceed IOV_MAX */
5396234b 2289 if (qemu_iovec_subvec_niov(qiov, qiov_offset, bytes) > IOV_MAX - 2) {
ee22a9d8
AG
2290 continue;
2291 }
2292
5396234b
VSO
2293 m->data_qiov = qiov;
2294 m->data_qiov_offset = qiov_offset;
ee22a9d8
AG
2295 return true;
2296 }
2297
2298 return false;
2299}
2300
c8bb23cb
AN
2301static bool is_unallocated(BlockDriverState *bs, int64_t offset, int64_t bytes)
2302{
2303 int64_t nr;
2304 return !bytes ||
170d3bd3
AS
2305 (!bdrv_is_allocated_above(bs, NULL, false, offset, bytes, &nr) &&
2306 nr == bytes);
c8bb23cb
AN
2307}
2308
2309static bool is_zero_cow(BlockDriverState *bs, QCowL2Meta *m)
2310{
2311 /*
2312 * This check is designed for optimization shortcut so it must be
2313 * efficient.
2314 * Instead of is_zero(), use is_unallocated() as it is faster (but not
2315 * as accurate and can result in false negatives).
2316 */
2317 return is_unallocated(bs, m->offset + m->cow_start.offset,
2318 m->cow_start.nb_bytes) &&
2319 is_unallocated(bs, m->offset + m->cow_end.offset,
2320 m->cow_end.nb_bytes);
2321}
2322
2323static int handle_alloc_space(BlockDriverState *bs, QCowL2Meta *l2meta)
2324{
2325 BDRVQcow2State *s = bs->opaque;
2326 QCowL2Meta *m;
2327
2328 if (!(s->data_file->bs->supported_zero_flags & BDRV_REQ_NO_FALLBACK)) {
2329 return 0;
2330 }
2331
2332 if (bs->encrypted) {
2333 return 0;
2334 }
2335
2336 for (m = l2meta; m != NULL; m = m->next) {
2337 int ret;
2338
2339 if (!m->cow_start.nb_bytes && !m->cow_end.nb_bytes) {
2340 continue;
2341 }
2342
2343 if (!is_zero_cow(bs, m)) {
2344 continue;
2345 }
2346
2347 /*
2348 * instead of writing zero COW buffers,
2349 * efficiently zero out the whole clusters
2350 */
2351
2352 ret = qcow2_pre_write_overlap_check(bs, 0, m->alloc_offset,
2353 m->nb_clusters * s->cluster_size,
2354 true);
2355 if (ret < 0) {
2356 return ret;
2357 }
2358
2359 BLKDBG_EVENT(bs->file, BLKDBG_CLUSTER_ALLOC_SPACE);
2360 ret = bdrv_co_pwrite_zeroes(s->data_file, m->alloc_offset,
2361 m->nb_clusters * s->cluster_size,
2362 BDRV_REQ_NO_FALLBACK);
2363 if (ret < 0) {
2364 if (ret != -ENOTSUP && ret != -EAGAIN) {
2365 return ret;
2366 }
2367 continue;
2368 }
2369
2370 trace_qcow2_skip_cow(qemu_coroutine_self(), m->offset, m->nb_clusters);
2371 m->skip_cow = true;
2372 }
2373 return 0;
2374}
2375
6aa7a263
VSO
2376/*
2377 * qcow2_co_pwritev_task
2378 * Called with s->lock unlocked
2379 * l2meta - if not NULL, qcow2_co_pwritev_task() will consume it. Caller must
2380 * not use it somehow after qcow2_co_pwritev_task() call
2381 */
2382static coroutine_fn int qcow2_co_pwritev_task(BlockDriverState *bs,
2383 uint64_t file_cluster_offset,
2384 uint64_t offset, uint64_t bytes,
2385 QEMUIOVector *qiov,
2386 uint64_t qiov_offset,
2387 QCowL2Meta *l2meta)
2388{
2389 int ret;
2390 BDRVQcow2State *s = bs->opaque;
2391 void *crypt_buf = NULL;
2392 int offset_in_cluster = offset_into_cluster(s, offset);
2393 QEMUIOVector encrypted_qiov;
2394
2395 if (bs->encrypted) {
2396 assert(s->crypto);
2397 assert(bytes <= QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
2398 crypt_buf = qemu_try_blockalign(bs->file->bs, bytes);
2399 if (crypt_buf == NULL) {
2400 ret = -ENOMEM;
2401 goto out_unlocked;
2402 }
2403 qemu_iovec_to_buf(qiov, qiov_offset, crypt_buf, bytes);
2404
2405 if (qcow2_co_encrypt(bs, file_cluster_offset + offset_in_cluster,
2406 offset, crypt_buf, bytes) < 0)
2407 {
2408 ret = -EIO;
2409 goto out_unlocked;
2410 }
2411
2412 qemu_iovec_init_buf(&encrypted_qiov, crypt_buf, bytes);
2413 qiov = &encrypted_qiov;
2414 qiov_offset = 0;
2415 }
2416
2417 /* Try to efficiently initialize the physical space with zeroes */
2418 ret = handle_alloc_space(bs, l2meta);
2419 if (ret < 0) {
2420 goto out_unlocked;
2421 }
2422
2423 /*
2424 * If we need to do COW, check if it's possible to merge the
2425 * writing of the guest data together with that of the COW regions.
2426 * If it's not possible (or not necessary) then write the
2427 * guest data now.
2428 */
2429 if (!merge_cow(offset, bytes, qiov, qiov_offset, l2meta)) {
2430 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO);
2431 trace_qcow2_writev_data(qemu_coroutine_self(),
2432 file_cluster_offset + offset_in_cluster);
2433 ret = bdrv_co_pwritev_part(s->data_file,
2434 file_cluster_offset + offset_in_cluster,
2435 bytes, qiov, qiov_offset, 0);
2436 if (ret < 0) {
2437 goto out_unlocked;
2438 }
2439 }
2440
2441 qemu_co_mutex_lock(&s->lock);
2442
2443 ret = qcow2_handle_l2meta(bs, &l2meta, true);
2444 goto out_locked;
2445
2446out_unlocked:
2447 qemu_co_mutex_lock(&s->lock);
2448
2449out_locked:
2450 qcow2_handle_l2meta(bs, &l2meta, false);
2451 qemu_co_mutex_unlock(&s->lock);
2452
2453 qemu_vfree(crypt_buf);
2454
2455 return ret;
2456}
2457
d710cf57
VSO
2458static coroutine_fn int qcow2_co_pwritev_task_entry(AioTask *task)
2459{
2460 Qcow2AioTask *t = container_of(task, Qcow2AioTask, task);
2461
2462 assert(!t->cluster_type);
2463
2464 return qcow2_co_pwritev_task(t->bs, t->file_cluster_offset,
2465 t->offset, t->bytes, t->qiov, t->qiov_offset,
2466 t->l2meta);
2467}
2468
5396234b
VSO
2469static coroutine_fn int qcow2_co_pwritev_part(
2470 BlockDriverState *bs, uint64_t offset, uint64_t bytes,
2471 QEMUIOVector *qiov, size_t qiov_offset, int flags)
585f8587 2472{
ff99129a 2473 BDRVQcow2State *s = bs->opaque;
d46a0bb2 2474 int offset_in_cluster;
68d100e9 2475 int ret;
d46a0bb2 2476 unsigned int cur_bytes; /* number of sectors in current iteration */
c2bdd990 2477 uint64_t cluster_offset;
8d2497c3 2478 QCowL2Meta *l2meta = NULL;
d710cf57 2479 AioTaskPool *aio = NULL;
c2271403 2480
d46a0bb2 2481 trace_qcow2_writev_start_req(qemu_coroutine_self(), offset, bytes);
3cce16f4 2482
d710cf57 2483 while (bytes != 0 && aio_task_pool_status(aio) == 0) {
3fc48d09 2484
f50f88b9 2485 l2meta = NULL;
cf5c1a23 2486
3cce16f4 2487 trace_qcow2_writev_start_part(qemu_coroutine_self());
d46a0bb2
KW
2488 offset_in_cluster = offset_into_cluster(s, offset);
2489 cur_bytes = MIN(bytes, INT_MAX);
2490 if (bs->encrypted) {
2491 cur_bytes = MIN(cur_bytes,
2492 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size
2493 - offset_in_cluster);
5ebaa27e 2494 }
095a9c58 2495
6aa7a263
VSO
2496 qemu_co_mutex_lock(&s->lock);
2497
d46a0bb2
KW
2498 ret = qcow2_alloc_cluster_offset(bs, offset, &cur_bytes,
2499 &cluster_offset, &l2meta);
5ebaa27e 2500 if (ret < 0) {
5447c3a0 2501 goto out_locked;
5ebaa27e 2502 }
148da7ea 2503
344ffea9 2504 assert(offset_into_cluster(s, cluster_offset) == 0);
148da7ea 2505
5447c3a0
VSO
2506 ret = qcow2_pre_write_overlap_check(bs, 0,
2507 cluster_offset + offset_in_cluster,
2508 cur_bytes, true);
2509 if (ret < 0) {
2510 goto out_locked;
2511 }
2512
2513 qemu_co_mutex_unlock(&s->lock);
2514
d710cf57
VSO
2515 if (!aio && cur_bytes != bytes) {
2516 aio = aio_task_pool_new(QCOW2_MAX_WORKERS);
2517 }
2518 ret = qcow2_add_task(bs, aio, qcow2_co_pwritev_task_entry, 0,
2519 cluster_offset, offset, cur_bytes,
2520 qiov, qiov_offset, l2meta);
6aa7a263 2521 l2meta = NULL; /* l2meta is consumed by qcow2_co_pwritev_task() */
c8bb23cb 2522 if (ret < 0) {
6aa7a263 2523 goto fail_nometa;
f50f88b9 2524 }
0fa9131a 2525
d46a0bb2
KW
2526 bytes -= cur_bytes;
2527 offset += cur_bytes;
6aa7a263 2528 qiov_offset += cur_bytes;
d46a0bb2 2529 trace_qcow2_writev_done_part(qemu_coroutine_self(), cur_bytes);
5ebaa27e 2530 }
3fc48d09 2531 ret = 0;
faf575c1 2532
5447c3a0
VSO
2533 qemu_co_mutex_lock(&s->lock);
2534
2535out_locked:
fd9fcd37 2536 qcow2_handle_l2meta(bs, &l2meta, false);
0fa9131a 2537
a8c57408
PB
2538 qemu_co_mutex_unlock(&s->lock);
2539
6aa7a263 2540fail_nometa:
d710cf57
VSO
2541 if (aio) {
2542 aio_task_pool_wait_all(aio);
2543 if (ret == 0) {
2544 ret = aio_task_pool_status(aio);
2545 }
2546 g_free(aio);
2547 }
2548
3cce16f4 2549 trace_qcow2_writev_done_req(qemu_coroutine_self(), ret);
42496d62 2550
68d100e9 2551 return ret;
585f8587
FB
2552}
2553
ec6d8912
KW
2554static int qcow2_inactivate(BlockDriverState *bs)
2555{
2556 BDRVQcow2State *s = bs->opaque;
2557 int ret, result = 0;
5f72826e 2558 Error *local_err = NULL;
ec6d8912 2559
644ddbb7 2560 qcow2_store_persistent_dirty_bitmaps(bs, true, &local_err);
83a8c775
PB
2561 if (local_err != NULL) {
2562 result = -EINVAL;
132adb68
VSO
2563 error_reportf_err(local_err, "Lost persistent bitmaps during "
2564 "inactivation of node '%s': ",
2565 bdrv_get_device_or_node_name(bs));
83a8c775
PB
2566 }
2567
ec6d8912
KW
2568 ret = qcow2_cache_flush(bs, s->l2_table_cache);
2569 if (ret) {
2570 result = ret;
2571 error_report("Failed to flush the L2 table cache: %s",
2572 strerror(-ret));
2573 }
2574
2575 ret = qcow2_cache_flush(bs, s->refcount_block_cache);
2576 if (ret) {
2577 result = ret;
2578 error_report("Failed to flush the refcount block cache: %s",
2579 strerror(-ret));
2580 }
2581
2582 if (result == 0) {
2583 qcow2_mark_clean(bs);
2584 }
2585
2586 return result;
2587}
2588
7c80ab3f 2589static void qcow2_close(BlockDriverState *bs)
585f8587 2590{
ff99129a 2591 BDRVQcow2State *s = bs->opaque;
de82815d 2592 qemu_vfree(s->l1_table);
cf93980e
HR
2593 /* else pre-write overlap checks in cache_destroy may crash */
2594 s->l1_table = NULL;
29c1a730 2595
140fd5a6 2596 if (!(s->flags & BDRV_O_INACTIVE)) {
ec6d8912 2597 qcow2_inactivate(bs);
27eb6c09 2598 }
c61d0004 2599
279621c0 2600 cache_clean_timer_del(bs);
e64d4072
AG
2601 qcow2_cache_destroy(s->l2_table_cache);
2602 qcow2_cache_destroy(s->refcount_block_cache);
29c1a730 2603
b25b387f
DB
2604 qcrypto_block_free(s->crypto);
2605 s->crypto = NULL;
f6fa64f6 2606
6744cbab 2607 g_free(s->unknown_header_fields);
75bab85c 2608 cleanup_unknown_header_ext(bs);
6744cbab 2609
9b890bdc 2610 g_free(s->image_data_file);
e4603fe1
KW
2611 g_free(s->image_backing_file);
2612 g_free(s->image_backing_format);
2613
0e8c08be
KW
2614 if (has_data_file(bs)) {
2615 bdrv_unref_child(bs, s->data_file);
2616 }
2617
ed6ccf0f 2618 qcow2_refcount_close(bs);
28c1202b 2619 qcow2_free_snapshots(bs);
585f8587
FB
2620}
2621
2b148f39
PB
2622static void coroutine_fn qcow2_co_invalidate_cache(BlockDriverState *bs,
2623 Error **errp)
06d9260f 2624{
ff99129a 2625 BDRVQcow2State *s = bs->opaque;
06d9260f 2626 int flags = s->flags;
b25b387f 2627 QCryptoBlock *crypto = NULL;
acdfb480 2628 QDict *options;
5a8a30db
KW
2629 Error *local_err = NULL;
2630 int ret;
06d9260f
AL
2631
2632 /*
2633 * Backing files are read-only which makes all of their metadata immutable,
2634 * that means we don't have to worry about reopening them here.
2635 */
2636
b25b387f
DB
2637 crypto = s->crypto;
2638 s->crypto = NULL;
06d9260f
AL
2639
2640 qcow2_close(bs);
2641
ff99129a 2642 memset(s, 0, sizeof(BDRVQcow2State));
d475e5ac 2643 options = qdict_clone_shallow(bs->options);
5a8a30db 2644
140fd5a6 2645 flags &= ~BDRV_O_INACTIVE;
2b148f39 2646 qemu_co_mutex_lock(&s->lock);
4e4bf5c4 2647 ret = qcow2_do_open(bs, options, flags, &local_err);
2b148f39 2648 qemu_co_mutex_unlock(&s->lock);
cb3e7f08 2649 qobject_unref(options);
5a8a30db 2650 if (local_err) {
4b576648
MA
2651 error_propagate_prepend(errp, local_err,
2652 "Could not reopen qcow2 layer: ");
191fb11b 2653 bs->drv = NULL;
5a8a30db
KW
2654 return;
2655 } else if (ret < 0) {
2656 error_setg_errno(errp, -ret, "Could not reopen qcow2 layer");
191fb11b 2657 bs->drv = NULL;
5a8a30db
KW
2658 return;
2659 }
acdfb480 2660
b25b387f 2661 s->crypto = crypto;
06d9260f
AL
2662}
2663
e24e49e6
KW
2664static size_t header_ext_add(char *buf, uint32_t magic, const void *s,
2665 size_t len, size_t buflen)
2666{
2667 QCowExtension *ext_backing_fmt = (QCowExtension*) buf;
2668 size_t ext_len = sizeof(QCowExtension) + ((len + 7) & ~7);
2669
2670 if (buflen < ext_len) {
2671 return -ENOSPC;
2672 }
2673
2674 *ext_backing_fmt = (QCowExtension) {
2675 .magic = cpu_to_be32(magic),
2676 .len = cpu_to_be32(len),
2677 };
0647d47c
SH
2678
2679 if (len) {
2680 memcpy(buf + sizeof(QCowExtension), s, len);
2681 }
e24e49e6
KW
2682
2683 return ext_len;
2684}
2685
756e6736 2686/*
e24e49e6
KW
2687 * Updates the qcow2 header, including the variable length parts of it, i.e.
2688 * the backing file name and all extensions. qcow2 was not designed to allow
2689 * such changes, so if we run out of space (we can only use the first cluster)
2690 * this function may fail.
756e6736
KW
2691 *
2692 * Returns 0 on success, -errno in error cases.
2693 */
e24e49e6 2694int qcow2_update_header(BlockDriverState *bs)
756e6736 2695{
ff99129a 2696 BDRVQcow2State *s = bs->opaque;
e24e49e6
KW
2697 QCowHeader *header;
2698 char *buf;
2699 size_t buflen = s->cluster_size;
756e6736 2700 int ret;
e24e49e6
KW
2701 uint64_t total_size;
2702 uint32_t refcount_table_clusters;
6744cbab 2703 size_t header_length;
75bab85c 2704 Qcow2UnknownHeaderExtension *uext;
756e6736 2705
e24e49e6 2706 buf = qemu_blockalign(bs, buflen);
756e6736 2707
e24e49e6
KW
2708 /* Header structure */
2709 header = (QCowHeader*) buf;
756e6736 2710
e24e49e6
KW
2711 if (buflen < sizeof(*header)) {
2712 ret = -ENOSPC;
2713 goto fail;
756e6736
KW
2714 }
2715
6744cbab 2716 header_length = sizeof(*header) + s->unknown_header_fields_size;
e24e49e6
KW
2717 total_size = bs->total_sectors * BDRV_SECTOR_SIZE;
2718 refcount_table_clusters = s->refcount_table_size >> (s->cluster_bits - 3);
2719
2720 *header = (QCowHeader) {
6744cbab 2721 /* Version 2 fields */
e24e49e6 2722 .magic = cpu_to_be32(QCOW_MAGIC),
6744cbab 2723 .version = cpu_to_be32(s->qcow_version),
e24e49e6
KW
2724 .backing_file_offset = 0,
2725 .backing_file_size = 0,
2726 .cluster_bits = cpu_to_be32(s->cluster_bits),
2727 .size = cpu_to_be64(total_size),
2728 .crypt_method = cpu_to_be32(s->crypt_method_header),
2729 .l1_size = cpu_to_be32(s->l1_size),
2730 .l1_table_offset = cpu_to_be64(s->l1_table_offset),
2731 .refcount_table_offset = cpu_to_be64(s->refcount_table_offset),
2732 .refcount_table_clusters = cpu_to_be32(refcount_table_clusters),
2733 .nb_snapshots = cpu_to_be32(s->nb_snapshots),
2734 .snapshots_offset = cpu_to_be64(s->snapshots_offset),
6744cbab
KW
2735
2736 /* Version 3 fields */
2737 .incompatible_features = cpu_to_be64(s->incompatible_features),
2738 .compatible_features = cpu_to_be64(s->compatible_features),
2739 .autoclear_features = cpu_to_be64(s->autoclear_features),
b6481f37 2740 .refcount_order = cpu_to_be32(s->refcount_order),
6744cbab 2741 .header_length = cpu_to_be32(header_length),
e24e49e6 2742 };
756e6736 2743
6744cbab
KW
2744 /* For older versions, write a shorter header */
2745 switch (s->qcow_version) {
2746 case 2:
2747 ret = offsetof(QCowHeader, incompatible_features);
2748 break;
2749 case 3:
2750 ret = sizeof(*header);
2751 break;
2752 default:
b6c14762
JM
2753 ret = -EINVAL;
2754 goto fail;
6744cbab
KW
2755 }
2756
2757 buf += ret;
2758 buflen -= ret;
2759 memset(buf, 0, buflen);
2760
2761 /* Preserve any unknown field in the header */
2762 if (s->unknown_header_fields_size) {
2763 if (buflen < s->unknown_header_fields_size) {
2764 ret = -ENOSPC;
2765 goto fail;
2766 }
2767
2768 memcpy(buf, s->unknown_header_fields, s->unknown_header_fields_size);
2769 buf += s->unknown_header_fields_size;
2770 buflen -= s->unknown_header_fields_size;
2771 }
756e6736 2772
e24e49e6 2773 /* Backing file format header extension */
e4603fe1 2774 if (s->image_backing_format) {
e24e49e6 2775 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BACKING_FORMAT,
e4603fe1
KW
2776 s->image_backing_format,
2777 strlen(s->image_backing_format),
e24e49e6
KW
2778 buflen);
2779 if (ret < 0) {
2780 goto fail;
756e6736
KW
2781 }
2782
e24e49e6
KW
2783 buf += ret;
2784 buflen -= ret;
756e6736
KW
2785 }
2786
9b890bdc
KW
2787 /* External data file header extension */
2788 if (has_data_file(bs) && s->image_data_file) {
2789 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_DATA_FILE,
2790 s->image_data_file, strlen(s->image_data_file),
2791 buflen);
2792 if (ret < 0) {
2793 goto fail;
2794 }
2795
2796 buf += ret;
2797 buflen -= ret;
2798 }
2799
4652b8f3
DB
2800 /* Full disk encryption header pointer extension */
2801 if (s->crypto_header.offset != 0) {
3b698f52
PM
2802 s->crypto_header.offset = cpu_to_be64(s->crypto_header.offset);
2803 s->crypto_header.length = cpu_to_be64(s->crypto_header.length);
4652b8f3
DB
2804 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_CRYPTO_HEADER,
2805 &s->crypto_header, sizeof(s->crypto_header),
2806 buflen);
3b698f52
PM
2807 s->crypto_header.offset = be64_to_cpu(s->crypto_header.offset);
2808 s->crypto_header.length = be64_to_cpu(s->crypto_header.length);
4652b8f3
DB
2809 if (ret < 0) {
2810 goto fail;
2811 }
2812 buf += ret;
2813 buflen -= ret;
2814 }
2815
cfcc4c62 2816 /* Feature table */
1a4828c7
KW
2817 if (s->qcow_version >= 3) {
2818 Qcow2Feature features[] = {
2819 {
2820 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
2821 .bit = QCOW2_INCOMPAT_DIRTY_BITNR,
2822 .name = "dirty bit",
2823 },
2824 {
2825 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
2826 .bit = QCOW2_INCOMPAT_CORRUPT_BITNR,
2827 .name = "corrupt bit",
2828 },
93c24936
KW
2829 {
2830 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
2831 .bit = QCOW2_INCOMPAT_DATA_FILE_BITNR,
2832 .name = "external data file",
2833 },
1a4828c7
KW
2834 {
2835 .type = QCOW2_FEAT_TYPE_COMPATIBLE,
2836 .bit = QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR,
2837 .name = "lazy refcounts",
2838 },
2839 };
2840
2841 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_FEATURE_TABLE,
2842 features, sizeof(features), buflen);
2843 if (ret < 0) {
2844 goto fail;
2845 }
2846 buf += ret;
2847 buflen -= ret;
cfcc4c62 2848 }
cfcc4c62 2849
88ddffae
VSO
2850 /* Bitmap extension */
2851 if (s->nb_bitmaps > 0) {
2852 Qcow2BitmapHeaderExt bitmaps_header = {
2853 .nb_bitmaps = cpu_to_be32(s->nb_bitmaps),
2854 .bitmap_directory_size =
2855 cpu_to_be64(s->bitmap_directory_size),
2856 .bitmap_directory_offset =
2857 cpu_to_be64(s->bitmap_directory_offset)
2858 };
2859 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BITMAPS,
2860 &bitmaps_header, sizeof(bitmaps_header),
2861 buflen);
2862 if (ret < 0) {
2863 goto fail;
2864 }
2865 buf += ret;
2866 buflen -= ret;
2867 }
2868
75bab85c
KW
2869 /* Keep unknown header extensions */
2870 QLIST_FOREACH(uext, &s->unknown_header_ext, next) {
2871 ret = header_ext_add(buf, uext->magic, uext->data, uext->len, buflen);
2872 if (ret < 0) {
2873 goto fail;
2874 }
2875
2876 buf += ret;
2877 buflen -= ret;
2878 }
2879
e24e49e6
KW
2880 /* End of header extensions */
2881 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_END, NULL, 0, buflen);
756e6736
KW
2882 if (ret < 0) {
2883 goto fail;
2884 }
2885
e24e49e6
KW
2886 buf += ret;
2887 buflen -= ret;
756e6736 2888
e24e49e6 2889 /* Backing file name */
e4603fe1
KW
2890 if (s->image_backing_file) {
2891 size_t backing_file_len = strlen(s->image_backing_file);
e24e49e6
KW
2892
2893 if (buflen < backing_file_len) {
2894 ret = -ENOSPC;
2895 goto fail;
2896 }
2897
00ea1881 2898 /* Using strncpy is ok here, since buf is not NUL-terminated. */
e4603fe1 2899 strncpy(buf, s->image_backing_file, buflen);
e24e49e6
KW
2900
2901 header->backing_file_offset = cpu_to_be64(buf - ((char*) header));
2902 header->backing_file_size = cpu_to_be32(backing_file_len);
756e6736
KW
2903 }
2904
e24e49e6 2905 /* Write the new header */
d9ca2ea2 2906 ret = bdrv_pwrite(bs->file, 0, header, s->cluster_size);
756e6736
KW
2907 if (ret < 0) {
2908 goto fail;
2909 }
2910
2911 ret = 0;
2912fail:
e24e49e6 2913 qemu_vfree(header);
756e6736
KW
2914 return ret;
2915}
2916
2917static int qcow2_change_backing_file(BlockDriverState *bs,
2918 const char *backing_file, const char *backing_fmt)
2919{
ff99129a 2920 BDRVQcow2State *s = bs->opaque;
e4603fe1 2921
6c3944dc
KW
2922 /* Adding a backing file means that the external data file alone won't be
2923 * enough to make sense of the content */
2924 if (backing_file && data_file_is_raw(bs)) {
2925 return -EINVAL;
2926 }
2927
4e876bcf
HR
2928 if (backing_file && strlen(backing_file) > 1023) {
2929 return -EINVAL;
2930 }
2931
998c2019
HR
2932 pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
2933 backing_file ?: "");
e24e49e6
KW
2934 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
2935 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
2936
e4603fe1
KW
2937 g_free(s->image_backing_file);
2938 g_free(s->image_backing_format);
2939
2940 s->image_backing_file = backing_file ? g_strdup(bs->backing_file) : NULL;
2941 s->image_backing_format = backing_fmt ? g_strdup(bs->backing_format) : NULL;
2942
e24e49e6 2943 return qcow2_update_header(bs);
756e6736
KW
2944}
2945
4652b8f3
DB
2946static int qcow2_crypt_method_from_format(const char *encryptfmt)
2947{
2948 if (g_str_equal(encryptfmt, "luks")) {
2949 return QCOW_CRYPT_LUKS;
2950 } else if (g_str_equal(encryptfmt, "aes")) {
2951 return QCOW_CRYPT_AES;
2952 } else {
2953 return -EINVAL;
2954 }
2955}
b25b387f 2956
60900b7b
KW
2957static int qcow2_set_up_encryption(BlockDriverState *bs,
2958 QCryptoBlockCreateOptions *cryptoopts,
2959 Error **errp)
2960{
2961 BDRVQcow2State *s = bs->opaque;
2962 QCryptoBlock *crypto = NULL;
2963 int fmt, ret;
2964
2965 switch (cryptoopts->format) {
2966 case Q_CRYPTO_BLOCK_FORMAT_LUKS:
2967 fmt = QCOW_CRYPT_LUKS;
2968 break;
2969 case Q_CRYPTO_BLOCK_FORMAT_QCOW:
2970 fmt = QCOW_CRYPT_AES;
2971 break;
2972 default:
2973 error_setg(errp, "Crypto format not supported in qcow2");
2974 return -EINVAL;
b25b387f 2975 }
60900b7b 2976
4652b8f3 2977 s->crypt_method_header = fmt;
b25b387f 2978
1cd9a787 2979 crypto = qcrypto_block_create(cryptoopts, "encrypt.",
4652b8f3
DB
2980 qcow2_crypto_hdr_init_func,
2981 qcow2_crypto_hdr_write_func,
b25b387f
DB
2982 bs, errp);
2983 if (!crypto) {
60900b7b 2984 return -EINVAL;
b25b387f
DB
2985 }
2986
2987 ret = qcow2_update_header(bs);
2988 if (ret < 0) {
2989 error_setg_errno(errp, -ret, "Could not write encryption header");
2990 goto out;
2991 }
2992
60900b7b 2993 ret = 0;
b25b387f 2994 out:
b25b387f 2995 qcrypto_block_free(crypto);
b25b387f
DB
2996 return ret;
2997}
2998
7bc45dc1
HR
2999/**
3000 * Preallocates metadata structures for data clusters between @offset (in the
3001 * guest disk) and @new_length (which is thus generally the new guest disk
3002 * size).
3003 *
3004 * Returns: 0 on success, -errno on failure.
3005 */
47e86b86 3006static int coroutine_fn preallocate_co(BlockDriverState *bs, uint64_t offset,
718c0fce
KW
3007 uint64_t new_length, PreallocMode mode,
3008 Error **errp)
a35e1c17 3009{
93e32b3e 3010 BDRVQcow2State *s = bs->opaque;
d46a0bb2 3011 uint64_t bytes;
060bee89 3012 uint64_t host_offset = 0;
718c0fce 3013 int64_t file_length;
d46a0bb2 3014 unsigned int cur_bytes;
148da7ea 3015 int ret;
f50f88b9 3016 QCowL2Meta *meta;
a35e1c17 3017
7bc45dc1
HR
3018 assert(offset <= new_length);
3019 bytes = new_length - offset;
a35e1c17 3020
d46a0bb2 3021 while (bytes) {
f29fbf7c 3022 cur_bytes = MIN(bytes, QEMU_ALIGN_DOWN(INT_MAX, s->cluster_size));
d46a0bb2 3023 ret = qcow2_alloc_cluster_offset(bs, offset, &cur_bytes,
060bee89 3024 &host_offset, &meta);
148da7ea 3025 if (ret < 0) {
360bd074 3026 error_setg_errno(errp, -ret, "Allocating clusters failed");
47e86b86 3027 return ret;
a35e1c17
KW
3028 }
3029
c792707f
SH
3030 while (meta) {
3031 QCowL2Meta *next = meta->next;
3032
7c2bbf4a
HT
3033 ret = qcow2_alloc_cluster_link_l2(bs, meta);
3034 if (ret < 0) {
360bd074 3035 error_setg_errno(errp, -ret, "Mapping clusters failed");
7c2bbf4a
HT
3036 qcow2_free_any_clusters(bs, meta->alloc_offset,
3037 meta->nb_clusters, QCOW2_DISCARD_NEVER);
47e86b86 3038 return ret;
7c2bbf4a
HT
3039 }
3040
3041 /* There are no dependent requests, but we need to remove our
3042 * request from the list of in-flight requests */
4e95314e 3043 QLIST_REMOVE(meta, next_in_flight);
c792707f
SH
3044
3045 g_free(meta);
3046 meta = next;
f50f88b9 3047 }
f214978a 3048
a35e1c17
KW
3049 /* TODO Preallocate data if requested */
3050
d46a0bb2
KW
3051 bytes -= cur_bytes;
3052 offset += cur_bytes;
a35e1c17
KW
3053 }
3054
3055 /*
3056 * It is expected that the image file is large enough to actually contain
3057 * all of the allocated clusters (otherwise we get failing reads after
3058 * EOF). Extend the image to the last allocated sector.
3059 */
718c0fce
KW
3060 file_length = bdrv_getlength(s->data_file->bs);
3061 if (file_length < 0) {
3062 error_setg_errno(errp, -file_length, "Could not get file size");
3063 return file_length;
3064 }
3065
3066 if (host_offset + cur_bytes > file_length) {
3067 if (mode == PREALLOC_MODE_METADATA) {
3068 mode = PREALLOC_MODE_OFF;
3069 }
c80d8b06
HR
3070 ret = bdrv_co_truncate(s->data_file, host_offset + cur_bytes, false,
3071 mode, errp);
19dbcbf7 3072 if (ret < 0) {
47e86b86 3073 return ret;
19dbcbf7 3074 }
a35e1c17
KW
3075 }
3076
47e86b86 3077 return 0;
a35e1c17
KW
3078}
3079
7c5bcc42
SH
3080/* qcow2_refcount_metadata_size:
3081 * @clusters: number of clusters to refcount (including data and L1/L2 tables)
3082 * @cluster_size: size of a cluster, in bytes
3083 * @refcount_order: refcount bits power-of-2 exponent
12cc30a8
HR
3084 * @generous_increase: allow for the refcount table to be 1.5x as large as it
3085 * needs to be
7c5bcc42
SH
3086 *
3087 * Returns: Number of bytes required for refcount blocks and table metadata.
3088 */
12cc30a8
HR
3089int64_t qcow2_refcount_metadata_size(int64_t clusters, size_t cluster_size,
3090 int refcount_order, bool generous_increase,
3091 uint64_t *refblock_count)
7c5bcc42
SH
3092{
3093 /*
3094 * Every host cluster is reference-counted, including metadata (even
3095 * refcount metadata is recursively included).
3096 *
3097 * An accurate formula for the size of refcount metadata size is difficult
3098 * to derive. An easier method of calculation is finding the fixed point
3099 * where no further refcount blocks or table clusters are required to
3100 * reference count every cluster.
3101 */
3102 int64_t blocks_per_table_cluster = cluster_size / sizeof(uint64_t);
3103 int64_t refcounts_per_block = cluster_size * 8 / (1 << refcount_order);
3104 int64_t table = 0; /* number of refcount table clusters */
3105 int64_t blocks = 0; /* number of refcount block clusters */
3106 int64_t last;
3107 int64_t n = 0;
3108
3109 do {
3110 last = n;
3111 blocks = DIV_ROUND_UP(clusters + table + blocks, refcounts_per_block);
3112 table = DIV_ROUND_UP(blocks, blocks_per_table_cluster);
3113 n = clusters + blocks + table;
12cc30a8
HR
3114
3115 if (n == last && generous_increase) {
3116 clusters += DIV_ROUND_UP(table, 2);
3117 n = 0; /* force another loop */
3118 generous_increase = false;
3119 }
7c5bcc42
SH
3120 } while (n != last);
3121
12cc30a8
HR
3122 if (refblock_count) {
3123 *refblock_count = blocks;
3124 }
3125
7c5bcc42
SH
3126 return (blocks + table) * cluster_size;
3127}
3128
95c67e3b
SH
3129/**
3130 * qcow2_calc_prealloc_size:
3131 * @total_size: virtual disk size in bytes
3132 * @cluster_size: cluster size in bytes
3133 * @refcount_order: refcount bits power-of-2 exponent
3134 *
3135 * Returns: Total number of bytes required for the fully allocated image
3136 * (including metadata).
3137 */
3138static int64_t qcow2_calc_prealloc_size(int64_t total_size,
3139 size_t cluster_size,
3140 int refcount_order)
3141{
95c67e3b 3142 int64_t meta_size = 0;
7c5bcc42 3143 uint64_t nl1e, nl2e;
9e029689 3144 int64_t aligned_total_size = ROUND_UP(total_size, cluster_size);
95c67e3b
SH
3145
3146 /* header: 1 cluster */
3147 meta_size += cluster_size;
3148
3149 /* total size of L2 tables */
3150 nl2e = aligned_total_size / cluster_size;
9e029689 3151 nl2e = ROUND_UP(nl2e, cluster_size / sizeof(uint64_t));
95c67e3b
SH
3152 meta_size += nl2e * sizeof(uint64_t);
3153
3154 /* total size of L1 tables */
3155 nl1e = nl2e * sizeof(uint64_t) / cluster_size;
9e029689 3156 nl1e = ROUND_UP(nl1e, cluster_size / sizeof(uint64_t));
95c67e3b
SH
3157 meta_size += nl1e * sizeof(uint64_t);
3158
7c5bcc42
SH
3159 /* total size of refcount table and blocks */
3160 meta_size += qcow2_refcount_metadata_size(
3161 (meta_size + aligned_total_size) / cluster_size,
12cc30a8 3162 cluster_size, refcount_order, false, NULL);
95c67e3b
SH
3163
3164 return meta_size + aligned_total_size;
3165}
3166
29ca9e45 3167static bool validate_cluster_size(size_t cluster_size, Error **errp)
a9420734 3168{
29ca9e45 3169 int cluster_bits = ctz32(cluster_size);
a9420734
KW
3170 if (cluster_bits < MIN_CLUSTER_BITS || cluster_bits > MAX_CLUSTER_BITS ||
3171 (1 << cluster_bits) != cluster_size)
3172 {
3ef6c40a
HR
3173 error_setg(errp, "Cluster size must be a power of two between %d and "
3174 "%dk", 1 << MIN_CLUSTER_BITS, 1 << (MAX_CLUSTER_BITS - 10));
29ca9e45
KW
3175 return false;
3176 }
3177 return true;
3178}
3179
3180static size_t qcow2_opt_get_cluster_size_del(QemuOpts *opts, Error **errp)
3181{
3182 size_t cluster_size;
3183
3184 cluster_size = qemu_opt_get_size_del(opts, BLOCK_OPT_CLUSTER_SIZE,
3185 DEFAULT_CLUSTER_SIZE);
3186 if (!validate_cluster_size(cluster_size, errp)) {
0eb4a8c1
SH
3187 return 0;
3188 }
3189 return cluster_size;
3190}
3191
3192static int qcow2_opt_get_version_del(QemuOpts *opts, Error **errp)
3193{
3194 char *buf;
3195 int ret;
3196
3197 buf = qemu_opt_get_del(opts, BLOCK_OPT_COMPAT_LEVEL);
3198 if (!buf) {
3199 ret = 3; /* default */
3200 } else if (!strcmp(buf, "0.10")) {
3201 ret = 2;
3202 } else if (!strcmp(buf, "1.1")) {
3203 ret = 3;
3204 } else {
3205 error_setg(errp, "Invalid compatibility level: '%s'", buf);
3206 ret = -EINVAL;
3207 }
3208 g_free(buf);
3209 return ret;
3210}
3211
3212static uint64_t qcow2_opt_get_refcount_bits_del(QemuOpts *opts, int version,
3213 Error **errp)
3214{
3215 uint64_t refcount_bits;
3216
3217 refcount_bits = qemu_opt_get_number_del(opts, BLOCK_OPT_REFCOUNT_BITS, 16);
3218 if (refcount_bits > 64 || !is_power_of_2(refcount_bits)) {
3219 error_setg(errp, "Refcount width must be a power of two and may not "
3220 "exceed 64 bits");
3221 return 0;
3222 }
3223
3224 if (version < 3 && refcount_bits != 16) {
3225 error_setg(errp, "Different refcount widths than 16 bits require "
3226 "compatibility level 1.1 or above (use compat=1.1 or "
3227 "greater)");
3228 return 0;
a9420734
KW
3229 }
3230
0eb4a8c1
SH
3231 return refcount_bits;
3232}
3233
c274393a 3234static int coroutine_fn
60900b7b 3235qcow2_co_create(BlockdevCreateOptions *create_options, Error **errp)
0eb4a8c1 3236{
29ca9e45 3237 BlockdevCreateOptionsQcow2 *qcow2_opts;
0eb4a8c1
SH
3238 QDict *options;
3239
a9420734
KW
3240 /*
3241 * Open the image file and write a minimal qcow2 header.
3242 *
3243 * We keep things simple and start with a zero-sized image. We also
3244 * do without refcount blocks or a L1 table for now. We'll fix the
3245 * inconsistency later.
3246 *
3247 * We do need a refcount table because growing the refcount table means
3248 * allocating two new refcount blocks - the seconds of which would be at
3249 * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
3250 * size for any qcow2 image.
3251 */
e1d74bc6
KW
3252 BlockBackend *blk = NULL;
3253 BlockDriverState *bs = NULL;
dcc98687 3254 BlockDriverState *data_bs = NULL;
f8413b3c 3255 QCowHeader *header;
29ca9e45
KW
3256 size_t cluster_size;
3257 int version;
3258 int refcount_order;
b106ad91 3259 uint64_t* refcount_table;
3ef6c40a 3260 Error *local_err = NULL;
a9420734
KW
3261 int ret;
3262
29ca9e45
KW
3263 assert(create_options->driver == BLOCKDEV_DRIVER_QCOW2);
3264 qcow2_opts = &create_options->u.qcow2;
3265
e1d74bc6
KW
3266 bs = bdrv_open_blockdev_ref(qcow2_opts->file, errp);
3267 if (bs == NULL) {
3268 return -EIO;
3269 }
3270
3271 /* Validate options and set default values */
29ca9e45 3272 if (!QEMU_IS_ALIGNED(qcow2_opts->size, BDRV_SECTOR_SIZE)) {
3afea402
AG
3273 error_setg(errp, "Image size must be a multiple of %u bytes",
3274 (unsigned) BDRV_SECTOR_SIZE);
29ca9e45
KW
3275 ret = -EINVAL;
3276 goto out;
3277 }
3278
3279 if (qcow2_opts->has_version) {
3280 switch (qcow2_opts->version) {
3281 case BLOCKDEV_QCOW2_VERSION_V2:
3282 version = 2;
3283 break;
3284 case BLOCKDEV_QCOW2_VERSION_V3:
3285 version = 3;
3286 break;
3287 default:
3288 g_assert_not_reached();
3289 }
3290 } else {
3291 version = 3;
3292 }
3293
3294 if (qcow2_opts->has_cluster_size) {
3295 cluster_size = qcow2_opts->cluster_size;
3296 } else {
3297 cluster_size = DEFAULT_CLUSTER_SIZE;
3298 }
3299
3300 if (!validate_cluster_size(cluster_size, errp)) {
e1d74bc6
KW
3301 ret = -EINVAL;
3302 goto out;
29ca9e45
KW
3303 }
3304
3305 if (!qcow2_opts->has_preallocation) {
3306 qcow2_opts->preallocation = PREALLOC_MODE_OFF;
3307 }
3308 if (qcow2_opts->has_backing_file &&
3309 qcow2_opts->preallocation != PREALLOC_MODE_OFF)
3310 {
3311 error_setg(errp, "Backing file and preallocation cannot be used at "
3312 "the same time");
e1d74bc6
KW
3313 ret = -EINVAL;
3314 goto out;
29ca9e45
KW
3315 }
3316 if (qcow2_opts->has_backing_fmt && !qcow2_opts->has_backing_file) {
3317 error_setg(errp, "Backing format cannot be used without backing file");
e1d74bc6
KW
3318 ret = -EINVAL;
3319 goto out;
29ca9e45
KW
3320 }
3321
3322 if (!qcow2_opts->has_lazy_refcounts) {
3323 qcow2_opts->lazy_refcounts = false;
3324 }
3325 if (version < 3 && qcow2_opts->lazy_refcounts) {
3326 error_setg(errp, "Lazy refcounts only supported with compatibility "
b76b4f60 3327 "level 1.1 and above (use version=v3 or greater)");
e1d74bc6
KW
3328 ret = -EINVAL;
3329 goto out;
29ca9e45
KW
3330 }
3331
3332 if (!qcow2_opts->has_refcount_bits) {
3333 qcow2_opts->refcount_bits = 16;
3334 }
3335 if (qcow2_opts->refcount_bits > 64 ||
3336 !is_power_of_2(qcow2_opts->refcount_bits))
3337 {
3338 error_setg(errp, "Refcount width must be a power of two and may not "
3339 "exceed 64 bits");
e1d74bc6
KW
3340 ret = -EINVAL;
3341 goto out;
29ca9e45
KW
3342 }
3343 if (version < 3 && qcow2_opts->refcount_bits != 16) {
3344 error_setg(errp, "Different refcount widths than 16 bits require "
b76b4f60 3345 "compatibility level 1.1 or above (use version=v3 or "
29ca9e45 3346 "greater)");
e1d74bc6
KW
3347 ret = -EINVAL;
3348 goto out;
29ca9e45
KW
3349 }
3350 refcount_order = ctz32(qcow2_opts->refcount_bits);
3351
6c3944dc
KW
3352 if (qcow2_opts->data_file_raw && !qcow2_opts->data_file) {
3353 error_setg(errp, "data-file-raw requires data-file");
3354 ret = -EINVAL;
3355 goto out;
3356 }
3357 if (qcow2_opts->data_file_raw && qcow2_opts->has_backing_file) {
3358 error_setg(errp, "Backing file and data-file-raw cannot be used at "
3359 "the same time");
3360 ret = -EINVAL;
3361 goto out;
3362 }
3363
dcc98687
KW
3364 if (qcow2_opts->data_file) {
3365 if (version < 3) {
3366 error_setg(errp, "External data files are only supported with "
3367 "compatibility level 1.1 and above (use version=v3 or "
3368 "greater)");
3369 ret = -EINVAL;
3370 goto out;
3371 }
3372 data_bs = bdrv_open_blockdev_ref(qcow2_opts->data_file, errp);
a0cf8363 3373 if (data_bs == NULL) {
dcc98687
KW
3374 ret = -EIO;
3375 goto out;
3376 }
3377 }
29ca9e45
KW
3378
3379 /* Create BlockBackend to write to the image */
d861ab3a
KW
3380 blk = blk_new(bdrv_get_aio_context(bs),
3381 BLK_PERM_WRITE | BLK_PERM_RESIZE, BLK_PERM_ALL);
cbf2b7c4 3382 ret = blk_insert_bs(blk, bs, errp);
a9420734 3383 if (ret < 0) {
cbf2b7c4 3384 goto out;
a9420734 3385 }
23588797
KW
3386 blk_set_allow_write_beyond_eof(blk, true);
3387
a9420734 3388 /* Write the header */
f8413b3c
KW
3389 QEMU_BUILD_BUG_ON((1 << MIN_CLUSTER_BITS) < sizeof(*header));
3390 header = g_malloc0(cluster_size);
3391 *header = (QCowHeader) {
3392 .magic = cpu_to_be32(QCOW_MAGIC),
3393 .version = cpu_to_be32(version),
0eb4a8c1 3394 .cluster_bits = cpu_to_be32(ctz32(cluster_size)),
f8413b3c
KW
3395 .size = cpu_to_be64(0),
3396 .l1_table_offset = cpu_to_be64(0),
3397 .l1_size = cpu_to_be32(0),
3398 .refcount_table_offset = cpu_to_be64(cluster_size),
3399 .refcount_table_clusters = cpu_to_be32(1),
bd4b167f 3400 .refcount_order = cpu_to_be32(refcount_order),
f8413b3c
KW
3401 .header_length = cpu_to_be32(sizeof(*header)),
3402 };
a9420734 3403
b25b387f
DB
3404 /* We'll update this to correct value later */
3405 header->crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
a9420734 3406
29ca9e45 3407 if (qcow2_opts->lazy_refcounts) {
f8413b3c 3408 header->compatible_features |=
bfe8043e
SH
3409 cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS);
3410 }
dcc98687
KW
3411 if (data_bs) {
3412 header->incompatible_features |=
3413 cpu_to_be64(QCOW2_INCOMPAT_DATA_FILE);
3414 }
6c3944dc
KW
3415 if (qcow2_opts->data_file_raw) {
3416 header->autoclear_features |=
3417 cpu_to_be64(QCOW2_AUTOCLEAR_DATA_FILE_RAW);
3418 }
bfe8043e 3419
8341f00d 3420 ret = blk_pwrite(blk, 0, header, cluster_size, 0);
f8413b3c 3421 g_free(header);
a9420734 3422 if (ret < 0) {
3ef6c40a 3423 error_setg_errno(errp, -ret, "Could not write qcow2 header");
a9420734
KW
3424 goto out;
3425 }
3426
b106ad91
KW
3427 /* Write a refcount table with one refcount block */
3428 refcount_table = g_malloc0(2 * cluster_size);
3429 refcount_table[0] = cpu_to_be64(2 * cluster_size);
8341f00d 3430 ret = blk_pwrite(blk, cluster_size, refcount_table, 2 * cluster_size, 0);
7267c094 3431 g_free(refcount_table);
a9420734
KW
3432
3433 if (ret < 0) {
3ef6c40a 3434 error_setg_errno(errp, -ret, "Could not write refcount table");
a9420734
KW
3435 goto out;
3436 }
3437
23588797
KW
3438 blk_unref(blk);
3439 blk = NULL;
a9420734
KW
3440
3441 /*
3442 * And now open the image and make it consistent first (i.e. increase the
3443 * refcount of the cluster that is occupied by the header and the refcount
3444 * table)
3445 */
e6641719 3446 options = qdict_new();
46f5ac20 3447 qdict_put_str(options, "driver", "qcow2");
cbf2b7c4 3448 qdict_put_str(options, "file", bs->node_name);
dcc98687
KW
3449 if (data_bs) {
3450 qdict_put_str(options, "data-file", data_bs->node_name);
3451 }
cbf2b7c4 3452 blk = blk_new_open(NULL, NULL, options,
55880601
KW
3453 BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_NO_FLUSH,
3454 &local_err);
23588797 3455 if (blk == NULL) {
3ef6c40a 3456 error_propagate(errp, local_err);
23588797 3457 ret = -EIO;
a9420734
KW
3458 goto out;
3459 }
3460
23588797 3461 ret = qcow2_alloc_clusters(blk_bs(blk), 3 * cluster_size);
a9420734 3462 if (ret < 0) {
3ef6c40a
HR
3463 error_setg_errno(errp, -ret, "Could not allocate clusters for qcow2 "
3464 "header and refcount table");
a9420734
KW
3465 goto out;
3466
3467 } else if (ret != 0) {
3468 error_report("Huh, first cluster in empty image is already in use?");
3469 abort();
3470 }
3471
9b890bdc
KW
3472 /* Set the external data file if necessary */
3473 if (data_bs) {
3474 BDRVQcow2State *s = blk_bs(blk)->opaque;
3475 s->image_data_file = g_strdup(data_bs->filename);
3476 }
3477
b527c9b3 3478 /* Create a full header (including things like feature table) */
23588797 3479 ret = qcow2_update_header(blk_bs(blk));
b527c9b3
KW
3480 if (ret < 0) {
3481 error_setg_errno(errp, -ret, "Could not update qcow2 header");
3482 goto out;
3483 }
3484
a9420734 3485 /* Okay, now that we have a valid image, let's give it the right size */
c80d8b06
HR
3486 ret = blk_truncate(blk, qcow2_opts->size, false, qcow2_opts->preallocation,
3487 errp);
a9420734 3488 if (ret < 0) {
ed3d2ec9 3489 error_prepend(errp, "Could not resize image: ");
a9420734
KW
3490 goto out;
3491 }
3492
3493 /* Want a backing file? There you go.*/
29ca9e45
KW
3494 if (qcow2_opts->has_backing_file) {
3495 const char *backing_format = NULL;
3496
3497 if (qcow2_opts->has_backing_fmt) {
3498 backing_format = BlockdevDriver_str(qcow2_opts->backing_fmt);
3499 }
3500
3501 ret = bdrv_change_backing_file(blk_bs(blk), qcow2_opts->backing_file,
3502 backing_format);
a9420734 3503 if (ret < 0) {
3ef6c40a 3504 error_setg_errno(errp, -ret, "Could not assign backing file '%s' "
29ca9e45
KW
3505 "with format '%s'", qcow2_opts->backing_file,
3506 backing_format);
a9420734
KW
3507 goto out;
3508 }
3509 }
3510
b25b387f 3511 /* Want encryption? There you go. */
60900b7b
KW
3512 if (qcow2_opts->has_encrypt) {
3513 ret = qcow2_set_up_encryption(blk_bs(blk), qcow2_opts->encrypt, errp);
b25b387f
DB
3514 if (ret < 0) {
3515 goto out;
3516 }
3517 }
3518
23588797
KW
3519 blk_unref(blk);
3520 blk = NULL;
ba2ab2f2 3521
b25b387f
DB
3522 /* Reopen the image without BDRV_O_NO_FLUSH to flush it before returning.
3523 * Using BDRV_O_NO_IO, since encryption is now setup we don't want to
3524 * have to setup decryption context. We're not doing any I/O on the top
3525 * level BlockDriverState, only lower layers, where BDRV_O_NO_IO does
3526 * not have effect.
3527 */
e6641719 3528 options = qdict_new();
46f5ac20 3529 qdict_put_str(options, "driver", "qcow2");
cbf2b7c4 3530 qdict_put_str(options, "file", bs->node_name);
dcc98687
KW
3531 if (data_bs) {
3532 qdict_put_str(options, "data-file", data_bs->node_name);
3533 }
cbf2b7c4 3534 blk = blk_new_open(NULL, NULL, options,
b25b387f
DB
3535 BDRV_O_RDWR | BDRV_O_NO_BACKING | BDRV_O_NO_IO,
3536 &local_err);
23588797 3537 if (blk == NULL) {
ba2ab2f2 3538 error_propagate(errp, local_err);
23588797 3539 ret = -EIO;
ba2ab2f2
HR
3540 goto out;
3541 }
3542
a9420734
KW
3543 ret = 0;
3544out:
e1d74bc6
KW
3545 blk_unref(blk);
3546 bdrv_unref(bs);
dcc98687 3547 bdrv_unref(data_bs);
a9420734
KW
3548 return ret;
3549}
de5f3f40 3550
efc75e2a
SH
3551static int coroutine_fn qcow2_co_create_opts(const char *filename, QemuOpts *opts,
3552 Error **errp)
de5f3f40 3553{
b76b4f60 3554 BlockdevCreateOptions *create_options = NULL;
92adf9db 3555 QDict *qdict;
b76b4f60 3556 Visitor *v;
cbf2b7c4 3557 BlockDriverState *bs = NULL;
9b890bdc 3558 BlockDriverState *data_bs = NULL;
3ef6c40a 3559 Error *local_err = NULL;
b76b4f60 3560 const char *val;
3ef6c40a 3561 int ret;
de5f3f40 3562
b76b4f60
KW
3563 /* Only the keyval visitor supports the dotted syntax needed for
3564 * encryption, so go through a QDict before getting a QAPI type. Ignore
3565 * options meant for the protocol layer so that the visitor doesn't
3566 * complain. */
3567 qdict = qemu_opts_to_qdict_filtered(opts, NULL, bdrv_qcow2.create_opts,
3568 true);
3569
3570 /* Handle encryption options */
3571 val = qdict_get_try_str(qdict, BLOCK_OPT_ENCRYPT);
3572 if (val && !strcmp(val, "on")) {
3573 qdict_put_str(qdict, BLOCK_OPT_ENCRYPT, "qcow");
3574 } else if (val && !strcmp(val, "off")) {
3575 qdict_del(qdict, BLOCK_OPT_ENCRYPT);
3576 }
3577
3578 val = qdict_get_try_str(qdict, BLOCK_OPT_ENCRYPT_FORMAT);
3579 if (val && !strcmp(val, "aes")) {
3580 qdict_put_str(qdict, BLOCK_OPT_ENCRYPT_FORMAT, "qcow");
3581 }
3582
3583 /* Convert compat=0.10/1.1 into compat=v2/v3, to be renamed into
3584 * version=v2/v3 below. */
3585 val = qdict_get_try_str(qdict, BLOCK_OPT_COMPAT_LEVEL);
3586 if (val && !strcmp(val, "0.10")) {
3587 qdict_put_str(qdict, BLOCK_OPT_COMPAT_LEVEL, "v2");
3588 } else if (val && !strcmp(val, "1.1")) {
3589 qdict_put_str(qdict, BLOCK_OPT_COMPAT_LEVEL, "v3");
3590 }
3591
3592 /* Change legacy command line options into QMP ones */
3593 static const QDictRenames opt_renames[] = {
3594 { BLOCK_OPT_BACKING_FILE, "backing-file" },
3595 { BLOCK_OPT_BACKING_FMT, "backing-fmt" },
3596 { BLOCK_OPT_CLUSTER_SIZE, "cluster-size" },
3597 { BLOCK_OPT_LAZY_REFCOUNTS, "lazy-refcounts" },
3598 { BLOCK_OPT_REFCOUNT_BITS, "refcount-bits" },
3599 { BLOCK_OPT_ENCRYPT, BLOCK_OPT_ENCRYPT_FORMAT },
3600 { BLOCK_OPT_COMPAT_LEVEL, "version" },
6c3944dc 3601 { BLOCK_OPT_DATA_FILE_RAW, "data-file-raw" },
b76b4f60
KW
3602 { NULL, NULL },
3603 };
3604
3605 if (!qdict_rename_keys(qdict, opt_renames, errp)) {
29ca9e45
KW
3606 ret = -EINVAL;
3607 goto finish;
3608 }
60900b7b 3609
b76b4f60
KW
3610 /* Create and open the file (protocol layer) */
3611 ret = bdrv_create_file(filename, opts, errp);
3612 if (ret < 0) {
0eb4a8c1
SH
3613 goto finish;
3614 }
b76b4f60
KW
3615
3616 bs = bdrv_open(filename, NULL, NULL,
3617 BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_PROTOCOL, errp);
3618 if (bs == NULL) {
3619 ret = -EIO;
1bd0e2d1
CL
3620 goto finish;
3621 }
0eb4a8c1 3622
9b890bdc
KW
3623 /* Create and open an external data file (protocol layer) */
3624 val = qdict_get_try_str(qdict, BLOCK_OPT_DATA_FILE);
3625 if (val) {
3626 ret = bdrv_create_file(val, opts, errp);
3627 if (ret < 0) {
3628 goto finish;
3629 }
3630
3631 data_bs = bdrv_open(val, NULL, NULL,
3632 BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_PROTOCOL,
3633 errp);
3634 if (data_bs == NULL) {
3635 ret = -EIO;
3636 goto finish;
3637 }
3638
3639 qdict_del(qdict, BLOCK_OPT_DATA_FILE);
3640 qdict_put_str(qdict, "data-file", data_bs->node_name);
3641 }
3642
b76b4f60
KW
3643 /* Set 'driver' and 'node' options */
3644 qdict_put_str(qdict, "driver", "qcow2");
3645 qdict_put_str(qdict, "file", bs->node_name);
3646
3647 /* Now get the QAPI type BlockdevCreateOptions */
af91062e
MA
3648 v = qobject_input_visitor_new_flat_confused(qdict, errp);
3649 if (!v) {
1bd0e2d1
CL
3650 ret = -EINVAL;
3651 goto finish;
3652 }
3653
b76b4f60
KW
3654 visit_type_BlockdevCreateOptions(v, NULL, &create_options, &local_err);
3655 visit_free(v);
de5f3f40 3656
0eb4a8c1
SH
3657 if (local_err) {
3658 error_propagate(errp, local_err);
bd4b167f
HR
3659 ret = -EINVAL;
3660 goto finish;
3661 }
3662
b76b4f60
KW
3663 /* Silently round up size */
3664 create_options->u.qcow2.size = ROUND_UP(create_options->u.qcow2.size,
3665 BDRV_SECTOR_SIZE);
cbf2b7c4
KW
3666
3667 /* Create the qcow2 image (format layer) */
b76b4f60 3668 ret = qcow2_co_create(create_options, errp);
cbf2b7c4
KW
3669 if (ret < 0) {
3670 goto finish;
3671 }
1bd0e2d1 3672
b76b4f60 3673 ret = 0;
1bd0e2d1 3674finish:
cb3e7f08 3675 qobject_unref(qdict);
cbf2b7c4 3676 bdrv_unref(bs);
9b890bdc 3677 bdrv_unref(data_bs);
b76b4f60 3678 qapi_free_BlockdevCreateOptions(create_options);
3ef6c40a 3679 return ret;
de5f3f40
KW
3680}
3681
2928abce 3682
f06f6b66 3683static bool is_zero(BlockDriverState *bs, int64_t offset, int64_t bytes)
2928abce 3684{
31826642
EB
3685 int64_t nr;
3686 int res;
f06f6b66
EB
3687
3688 /* Clamp to image length, before checking status of underlying sectors */
8cbf74b2
EB
3689 if (offset + bytes > bs->total_sectors * BDRV_SECTOR_SIZE) {
3690 bytes = bs->total_sectors * BDRV_SECTOR_SIZE - offset;
fbaa6bb3
EB
3691 }
3692
f06f6b66 3693 if (!bytes) {
ebb718a5
EB
3694 return true;
3695 }
8cbf74b2 3696 res = bdrv_block_status_above(bs, NULL, offset, bytes, &nr, NULL, NULL);
31826642 3697 return res >= 0 && (res & BDRV_BLOCK_ZERO) && nr == bytes;
2928abce
DL
3698}
3699
5544b59f 3700static coroutine_fn int qcow2_co_pwrite_zeroes(BlockDriverState *bs,
f5a5ca79 3701 int64_t offset, int bytes, BdrvRequestFlags flags)
621f0589
KW
3702{
3703 int ret;
ff99129a 3704 BDRVQcow2State *s = bs->opaque;
621f0589 3705
5544b59f 3706 uint32_t head = offset % s->cluster_size;
f5a5ca79 3707 uint32_t tail = (offset + bytes) % s->cluster_size;
2928abce 3708
f5a5ca79
MP
3709 trace_qcow2_pwrite_zeroes_start_req(qemu_coroutine_self(), offset, bytes);
3710 if (offset + bytes == bs->total_sectors * BDRV_SECTOR_SIZE) {
fbaa6bb3
EB
3711 tail = 0;
3712 }
5a64e942 3713
ebb718a5 3714 if (head || tail) {
ebb718a5 3715 uint64_t off;
ecfe1863 3716 unsigned int nr;
2928abce 3717
f5a5ca79 3718 assert(head + bytes <= s->cluster_size);
2928abce 3719
ebb718a5 3720 /* check whether remainder of cluster already reads as zero */
f06f6b66
EB
3721 if (!(is_zero(bs, offset - head, head) &&
3722 is_zero(bs, offset + bytes,
3723 tail ? s->cluster_size - tail : 0))) {
2928abce
DL
3724 return -ENOTSUP;
3725 }
3726
2928abce
DL
3727 qemu_co_mutex_lock(&s->lock);
3728 /* We can have new write after previous check */
f06f6b66 3729 offset = QEMU_ALIGN_DOWN(offset, s->cluster_size);
f5a5ca79 3730 bytes = s->cluster_size;
ecfe1863 3731 nr = s->cluster_size;
5544b59f 3732 ret = qcow2_get_cluster_offset(bs, offset, &nr, &off);
fdfab37d
EB
3733 if (ret != QCOW2_CLUSTER_UNALLOCATED &&
3734 ret != QCOW2_CLUSTER_ZERO_PLAIN &&
3735 ret != QCOW2_CLUSTER_ZERO_ALLOC) {
2928abce
DL
3736 qemu_co_mutex_unlock(&s->lock);
3737 return -ENOTSUP;
3738 }
3739 } else {
3740 qemu_co_mutex_lock(&s->lock);
621f0589
KW
3741 }
3742
f5a5ca79 3743 trace_qcow2_pwrite_zeroes(qemu_coroutine_self(), offset, bytes);
5a64e942 3744
621f0589 3745 /* Whatever is left can use real zero clusters */
f5a5ca79 3746 ret = qcow2_cluster_zeroize(bs, offset, bytes, flags);
621f0589
KW
3747 qemu_co_mutex_unlock(&s->lock);
3748
3749 return ret;
3750}
3751
82e8a788 3752static coroutine_fn int qcow2_co_pdiscard(BlockDriverState *bs,
f5a5ca79 3753 int64_t offset, int bytes)
5ea929e3 3754{
6db39ae2 3755 int ret;
ff99129a 3756 BDRVQcow2State *s = bs->opaque;
6db39ae2 3757
f5a5ca79
MP
3758 if (!QEMU_IS_ALIGNED(offset | bytes, s->cluster_size)) {
3759 assert(bytes < s->cluster_size);
048c5fd1
EB
3760 /* Ignore partial clusters, except for the special case of the
3761 * complete partial cluster at the end of an unaligned file */
3762 if (!QEMU_IS_ALIGNED(offset, s->cluster_size) ||
f5a5ca79 3763 offset + bytes != bs->total_sectors * BDRV_SECTOR_SIZE) {
048c5fd1
EB
3764 return -ENOTSUP;
3765 }
49228d1e
EB
3766 }
3767
6db39ae2 3768 qemu_co_mutex_lock(&s->lock);
f5a5ca79 3769 ret = qcow2_cluster_discard(bs, offset, bytes, QCOW2_DISCARD_REQUEST,
d2cb36af 3770 false);
6db39ae2
PB
3771 qemu_co_mutex_unlock(&s->lock);
3772 return ret;
5ea929e3
KW
3773}
3774
fd9fcd37
FZ
3775static int coroutine_fn
3776qcow2_co_copy_range_from(BlockDriverState *bs,
3777 BdrvChild *src, uint64_t src_offset,
3778 BdrvChild *dst, uint64_t dst_offset,
67b51fb9
VSO
3779 uint64_t bytes, BdrvRequestFlags read_flags,
3780 BdrvRequestFlags write_flags)
fd9fcd37
FZ
3781{
3782 BDRVQcow2State *s = bs->opaque;
3783 int ret;
3784 unsigned int cur_bytes; /* number of bytes in current iteration */
3785 BdrvChild *child = NULL;
67b51fb9 3786 BdrvRequestFlags cur_write_flags;
fd9fcd37
FZ
3787
3788 assert(!bs->encrypted);
3789 qemu_co_mutex_lock(&s->lock);
3790
3791 while (bytes != 0) {
3792 uint64_t copy_offset = 0;
3793 /* prepare next request */
3794 cur_bytes = MIN(bytes, INT_MAX);
67b51fb9 3795 cur_write_flags = write_flags;
fd9fcd37
FZ
3796
3797 ret = qcow2_get_cluster_offset(bs, src_offset, &cur_bytes, &copy_offset);
3798 if (ret < 0) {
3799 goto out;
3800 }
3801
3802 switch (ret) {
3803 case QCOW2_CLUSTER_UNALLOCATED:
3804 if (bs->backing && bs->backing->bs) {
3805 int64_t backing_length = bdrv_getlength(bs->backing->bs);
3806 if (src_offset >= backing_length) {
67b51fb9 3807 cur_write_flags |= BDRV_REQ_ZERO_WRITE;
fd9fcd37
FZ
3808 } else {
3809 child = bs->backing;
3810 cur_bytes = MIN(cur_bytes, backing_length - src_offset);
3811 copy_offset = src_offset;
3812 }
3813 } else {
67b51fb9 3814 cur_write_flags |= BDRV_REQ_ZERO_WRITE;
fd9fcd37
FZ
3815 }
3816 break;
3817
3818 case QCOW2_CLUSTER_ZERO_PLAIN:
3819 case QCOW2_CLUSTER_ZERO_ALLOC:
67b51fb9 3820 cur_write_flags |= BDRV_REQ_ZERO_WRITE;
fd9fcd37
FZ
3821 break;
3822
3823 case QCOW2_CLUSTER_COMPRESSED:
3824 ret = -ENOTSUP;
3825 goto out;
fd9fcd37
FZ
3826
3827 case QCOW2_CLUSTER_NORMAL:
966b000f 3828 child = s->data_file;
fd9fcd37 3829 copy_offset += offset_into_cluster(s, src_offset);
fd9fcd37
FZ
3830 break;
3831
3832 default:
3833 abort();
3834 }
3835 qemu_co_mutex_unlock(&s->lock);
3836 ret = bdrv_co_copy_range_from(child,
3837 copy_offset,
3838 dst, dst_offset,
67b51fb9 3839 cur_bytes, read_flags, cur_write_flags);
fd9fcd37
FZ
3840 qemu_co_mutex_lock(&s->lock);
3841 if (ret < 0) {
3842 goto out;
3843 }
3844
3845 bytes -= cur_bytes;
3846 src_offset += cur_bytes;
3847 dst_offset += cur_bytes;
3848 }
3849 ret = 0;
3850
3851out:
3852 qemu_co_mutex_unlock(&s->lock);
3853 return ret;
3854}
3855
3856static int coroutine_fn
3857qcow2_co_copy_range_to(BlockDriverState *bs,
3858 BdrvChild *src, uint64_t src_offset,
3859 BdrvChild *dst, uint64_t dst_offset,
67b51fb9
VSO
3860 uint64_t bytes, BdrvRequestFlags read_flags,
3861 BdrvRequestFlags write_flags)
fd9fcd37
FZ
3862{
3863 BDRVQcow2State *s = bs->opaque;
3864 int offset_in_cluster;
3865 int ret;
3866 unsigned int cur_bytes; /* number of sectors in current iteration */
3867 uint64_t cluster_offset;
fd9fcd37
FZ
3868 QCowL2Meta *l2meta = NULL;
3869
3870 assert(!bs->encrypted);
fd9fcd37
FZ
3871
3872 qemu_co_mutex_lock(&s->lock);
3873
3874 while (bytes != 0) {
3875
3876 l2meta = NULL;
3877
3878 offset_in_cluster = offset_into_cluster(s, dst_offset);
3879 cur_bytes = MIN(bytes, INT_MAX);
3880
3881 /* TODO:
3882 * If src->bs == dst->bs, we could simply copy by incrementing
3883 * the refcnt, without copying user data.
3884 * Or if src->bs == dst->bs->backing->bs, we could copy by discarding. */
3885 ret = qcow2_alloc_cluster_offset(bs, dst_offset, &cur_bytes,
3886 &cluster_offset, &l2meta);
3887 if (ret < 0) {
3888 goto fail;
3889 }
3890
344ffea9 3891 assert(offset_into_cluster(s, cluster_offset) == 0);
fd9fcd37
FZ
3892
3893 ret = qcow2_pre_write_overlap_check(bs, 0,
966b000f 3894 cluster_offset + offset_in_cluster, cur_bytes, true);
fd9fcd37
FZ
3895 if (ret < 0) {
3896 goto fail;
3897 }
3898
3899 qemu_co_mutex_unlock(&s->lock);
3900 ret = bdrv_co_copy_range_to(src, src_offset,
966b000f 3901 s->data_file,
fd9fcd37 3902 cluster_offset + offset_in_cluster,
67b51fb9 3903 cur_bytes, read_flags, write_flags);
fd9fcd37
FZ
3904 qemu_co_mutex_lock(&s->lock);
3905 if (ret < 0) {
3906 goto fail;
3907 }
3908
3909 ret = qcow2_handle_l2meta(bs, &l2meta, true);
3910 if (ret) {
3911 goto fail;
3912 }
3913
3914 bytes -= cur_bytes;
e06f4639 3915 src_offset += cur_bytes;
fd9fcd37
FZ
3916 dst_offset += cur_bytes;
3917 }
3918 ret = 0;
3919
3920fail:
3921 qcow2_handle_l2meta(bs, &l2meta, false);
3922
3923 qemu_co_mutex_unlock(&s->lock);
3924
fd9fcd37
FZ
3925 trace_qcow2_writev_done_req(qemu_coroutine_self(), ret);
3926
3927 return ret;
3928}
3929
061ca8a3 3930static int coroutine_fn qcow2_co_truncate(BlockDriverState *bs, int64_t offset,
c80d8b06
HR
3931 bool exact, PreallocMode prealloc,
3932 Error **errp)
419b19d9 3933{
ff99129a 3934 BDRVQcow2State *s = bs->opaque;
95b98f34 3935 uint64_t old_length;
2cf7cfa1
KW
3936 int64_t new_l1_size;
3937 int ret;
45b4949c 3938 QDict *options;
419b19d9 3939
772d1f97
HR
3940 if (prealloc != PREALLOC_MODE_OFF && prealloc != PREALLOC_MODE_METADATA &&
3941 prealloc != PREALLOC_MODE_FALLOC && prealloc != PREALLOC_MODE_FULL)
3942 {
8243ccb7 3943 error_setg(errp, "Unsupported preallocation mode '%s'",
977c736f 3944 PreallocMode_str(prealloc));
8243ccb7
HR
3945 return -ENOTSUP;
3946 }
3947
3afea402
AG
3948 if (!QEMU_IS_ALIGNED(offset, BDRV_SECTOR_SIZE)) {
3949 error_setg(errp, "The new size must be a multiple of %u",
3950 (unsigned) BDRV_SECTOR_SIZE);
419b19d9
SH
3951 return -EINVAL;
3952 }
3953
061ca8a3
KW
3954 qemu_co_mutex_lock(&s->lock);
3955
419b19d9
SH
3956 /* cannot proceed if image has snapshots */
3957 if (s->nb_snapshots) {
4bff28b8 3958 error_setg(errp, "Can't resize an image which has snapshots");
061ca8a3
KW
3959 ret = -ENOTSUP;
3960 goto fail;
419b19d9
SH
3961 }
3962
88ddffae 3963 /* cannot proceed if image has bitmaps */
d19c6b36 3964 if (qcow2_truncate_bitmaps_check(bs, errp)) {
061ca8a3
KW
3965 ret = -ENOTSUP;
3966 goto fail;
88ddffae
VSO
3967 }
3968
bd016b91 3969 old_length = bs->total_sectors * BDRV_SECTOR_SIZE;
46b732cd 3970 new_l1_size = size_to_l1(s, offset);
95b98f34 3971
95b98f34 3972 if (offset < old_length) {
163bc39d 3973 int64_t last_cluster, old_file_size;
46b732cd
PB
3974 if (prealloc != PREALLOC_MODE_OFF) {
3975 error_setg(errp,
3976 "Preallocation can't be used for shrinking an image");
061ca8a3
KW
3977 ret = -EINVAL;
3978 goto fail;
46b732cd 3979 }
419b19d9 3980
46b732cd
PB
3981 ret = qcow2_cluster_discard(bs, ROUND_UP(offset, s->cluster_size),
3982 old_length - ROUND_UP(offset,
3983 s->cluster_size),
3984 QCOW2_DISCARD_ALWAYS, true);
3985 if (ret < 0) {
3986 error_setg_errno(errp, -ret, "Failed to discard cropped clusters");
061ca8a3 3987 goto fail;
46b732cd
PB
3988 }
3989
3990 ret = qcow2_shrink_l1_table(bs, new_l1_size);
3991 if (ret < 0) {
3992 error_setg_errno(errp, -ret,
3993 "Failed to reduce the number of L2 tables");
061ca8a3 3994 goto fail;
46b732cd
PB
3995 }
3996
3997 ret = qcow2_shrink_reftable(bs);
3998 if (ret < 0) {
3999 error_setg_errno(errp, -ret,
4000 "Failed to discard unused refblocks");
061ca8a3 4001 goto fail;
46b732cd 4002 }
163bc39d
PB
4003
4004 old_file_size = bdrv_getlength(bs->file->bs);
4005 if (old_file_size < 0) {
4006 error_setg_errno(errp, -old_file_size,
4007 "Failed to inquire current file length");
061ca8a3
KW
4008 ret = old_file_size;
4009 goto fail;
163bc39d
PB
4010 }
4011 last_cluster = qcow2_get_last_cluster(bs, old_file_size);
4012 if (last_cluster < 0) {
4013 error_setg_errno(errp, -last_cluster,
4014 "Failed to find the last cluster");
061ca8a3
KW
4015 ret = last_cluster;
4016 goto fail;
163bc39d
PB
4017 }
4018 if ((last_cluster + 1) * s->cluster_size < old_file_size) {
233521b1
HR
4019 Error *local_err = NULL;
4020
e61a28a9
HR
4021 /*
4022 * Do not pass @exact here: It will not help the user if
4023 * we get an error here just because they wanted to shrink
4024 * their qcow2 image (on a block device) with qemu-img.
4025 * (And on the qcow2 layer, the @exact requirement is
4026 * always fulfilled, so there is no need to pass it on.)
4027 */
061ca8a3 4028 bdrv_co_truncate(bs->file, (last_cluster + 1) * s->cluster_size,
c80d8b06 4029 false, PREALLOC_MODE_OFF, &local_err);
233521b1
HR
4030 if (local_err) {
4031 warn_reportf_err(local_err,
4032 "Failed to truncate the tail of the image: ");
163bc39d
PB
4033 }
4034 }
46b732cd
PB
4035 } else {
4036 ret = qcow2_grow_l1_table(bs, new_l1_size, true);
4037 if (ret < 0) {
4038 error_setg_errno(errp, -ret, "Failed to grow the L1 table");
061ca8a3 4039 goto fail;
46b732cd 4040 }
419b19d9
SH
4041 }
4042
95b98f34
HR
4043 switch (prealloc) {
4044 case PREALLOC_MODE_OFF:
718c0fce 4045 if (has_data_file(bs)) {
e61a28a9
HR
4046 /*
4047 * If the caller wants an exact resize, the external data
4048 * file should be resized to the exact target size, too,
4049 * so we pass @exact here.
4050 */
4051 ret = bdrv_co_truncate(s->data_file, offset, exact, prealloc, errp);
718c0fce
KW
4052 if (ret < 0) {
4053 goto fail;
4054 }
4055 }
95b98f34
HR
4056 break;
4057
4058 case PREALLOC_MODE_METADATA:
718c0fce 4059 ret = preallocate_co(bs, old_length, offset, prealloc, errp);
95b98f34 4060 if (ret < 0) {
061ca8a3 4061 goto fail;
95b98f34
HR
4062 }
4063 break;
4064
772d1f97
HR
4065 case PREALLOC_MODE_FALLOC:
4066 case PREALLOC_MODE_FULL:
4067 {
4068 int64_t allocation_start, host_offset, guest_offset;
4069 int64_t clusters_allocated;
4070 int64_t old_file_size, new_file_size;
4071 uint64_t nb_new_data_clusters, nb_new_l2_tables;
4072
966b000f
KW
4073 /* With a data file, preallocation means just allocating the metadata
4074 * and forwarding the truncate request to the data file */
4075 if (has_data_file(bs)) {
718c0fce 4076 ret = preallocate_co(bs, old_length, offset, prealloc, errp);
966b000f 4077 if (ret < 0) {
966b000f
KW
4078 goto fail;
4079 }
4080 break;
4081 }
4082
772d1f97
HR
4083 old_file_size = bdrv_getlength(bs->file->bs);
4084 if (old_file_size < 0) {
4085 error_setg_errno(errp, -old_file_size,
4086 "Failed to inquire current file length");
061ca8a3
KW
4087 ret = old_file_size;
4088 goto fail;
772d1f97 4089 }
e400ad1e 4090 old_file_size = ROUND_UP(old_file_size, s->cluster_size);
772d1f97
HR
4091
4092 nb_new_data_clusters = DIV_ROUND_UP(offset - old_length,
4093 s->cluster_size);
4094
4095 /* This is an overestimation; we will not actually allocate space for
4096 * these in the file but just make sure the new refcount structures are
4097 * able to cover them so we will not have to allocate new refblocks
4098 * while entering the data blocks in the potentially new L2 tables.
4099 * (We do not actually care where the L2 tables are placed. Maybe they
4100 * are already allocated or they can be placed somewhere before
4101 * @old_file_size. It does not matter because they will be fully
4102 * allocated automatically, so they do not need to be covered by the
4103 * preallocation. All that matters is that we will not have to allocate
4104 * new refcount structures for them.) */
4105 nb_new_l2_tables = DIV_ROUND_UP(nb_new_data_clusters,
4106 s->cluster_size / sizeof(uint64_t));
4107 /* The cluster range may not be aligned to L2 boundaries, so add one L2
4108 * table for a potential head/tail */
4109 nb_new_l2_tables++;
4110
4111 allocation_start = qcow2_refcount_area(bs, old_file_size,
4112 nb_new_data_clusters +
4113 nb_new_l2_tables,
4114 true, 0, 0);
4115 if (allocation_start < 0) {
4116 error_setg_errno(errp, -allocation_start,
4117 "Failed to resize refcount structures");
061ca8a3
KW
4118 ret = allocation_start;
4119 goto fail;
772d1f97
HR
4120 }
4121
4122 clusters_allocated = qcow2_alloc_clusters_at(bs, allocation_start,
4123 nb_new_data_clusters);
4124 if (clusters_allocated < 0) {
4125 error_setg_errno(errp, -clusters_allocated,
4126 "Failed to allocate data clusters");
061ca8a3
KW
4127 ret = clusters_allocated;
4128 goto fail;
772d1f97
HR
4129 }
4130
4131 assert(clusters_allocated == nb_new_data_clusters);
4132
4133 /* Allocate the data area */
4134 new_file_size = allocation_start +
4135 nb_new_data_clusters * s->cluster_size;
e61a28a9 4136 /* Image file grows, so @exact does not matter */
c80d8b06 4137 ret = bdrv_co_truncate(bs->file, new_file_size, false, prealloc, errp);
772d1f97
HR
4138 if (ret < 0) {
4139 error_prepend(errp, "Failed to resize underlying file: ");
4140 qcow2_free_clusters(bs, allocation_start,
4141 nb_new_data_clusters * s->cluster_size,
4142 QCOW2_DISCARD_OTHER);
061ca8a3 4143 goto fail;
772d1f97
HR
4144 }
4145
4146 /* Create the necessary L2 entries */
4147 host_offset = allocation_start;
4148 guest_offset = old_length;
4149 while (nb_new_data_clusters) {
13bec229
AG
4150 int64_t nb_clusters = MIN(
4151 nb_new_data_clusters,
4152 s->l2_slice_size - offset_to_l2_slice_index(s, guest_offset));
772d1f97
HR
4153 QCowL2Meta allocation = {
4154 .offset = guest_offset,
4155 .alloc_offset = host_offset,
4156 .nb_clusters = nb_clusters,
4157 };
4158 qemu_co_queue_init(&allocation.dependent_requests);
4159
4160 ret = qcow2_alloc_cluster_link_l2(bs, &allocation);
4161 if (ret < 0) {
4162 error_setg_errno(errp, -ret, "Failed to update L2 tables");
4163 qcow2_free_clusters(bs, host_offset,
4164 nb_new_data_clusters * s->cluster_size,
4165 QCOW2_DISCARD_OTHER);
061ca8a3 4166 goto fail;
772d1f97
HR
4167 }
4168
4169 guest_offset += nb_clusters * s->cluster_size;
4170 host_offset += nb_clusters * s->cluster_size;
4171 nb_new_data_clusters -= nb_clusters;
4172 }
4173 break;
4174 }
4175
95b98f34
HR
4176 default:
4177 g_assert_not_reached();
4178 }
4179
4180 if (prealloc != PREALLOC_MODE_OFF) {
4181 /* Flush metadata before actually changing the image size */
061ca8a3 4182 ret = qcow2_write_caches(bs);
95b98f34
HR
4183 if (ret < 0) {
4184 error_setg_errno(errp, -ret,
4185 "Failed to flush the preallocated area to disk");
061ca8a3 4186 goto fail;
95b98f34
HR
4187 }
4188 }
4189
45b4949c
LB
4190 bs->total_sectors = offset / BDRV_SECTOR_SIZE;
4191
419b19d9
SH
4192 /* write updated header.size */
4193 offset = cpu_to_be64(offset);
d9ca2ea2 4194 ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, size),
8b3b7206 4195 &offset, sizeof(uint64_t));
419b19d9 4196 if (ret < 0) {
f59adb32 4197 error_setg_errno(errp, -ret, "Failed to update the image size");
061ca8a3 4198 goto fail;
419b19d9
SH
4199 }
4200
4201 s->l1_vm_state_index = new_l1_size;
45b4949c
LB
4202
4203 /* Update cache sizes */
4204 options = qdict_clone_shallow(bs->options);
4205 ret = qcow2_update_options(bs, options, s->flags, errp);
4206 qobject_unref(options);
4207 if (ret < 0) {
4208 goto fail;
4209 }
061ca8a3
KW
4210 ret = 0;
4211fail:
4212 qemu_co_mutex_unlock(&s->lock);
4213 return ret;
419b19d9
SH
4214}
4215
fcccefc5 4216static coroutine_fn int
0d483dce 4217qcow2_co_pwritev_compressed_task(BlockDriverState *bs,
5396234b
VSO
4218 uint64_t offset, uint64_t bytes,
4219 QEMUIOVector *qiov, size_t qiov_offset)
20d97356 4220{
ff99129a 4221 BDRVQcow2State *s = bs->opaque;
2714f13d 4222 int ret;
e1f4a37a 4223 ssize_t out_len;
fcccefc5 4224 uint8_t *buf, *out_buf;
77e023ff 4225 uint64_t cluster_offset;
20d97356 4226
0d483dce
AS
4227 assert(bytes == s->cluster_size || (bytes < s->cluster_size &&
4228 (offset + bytes == bs->total_sectors << BDRV_SECTOR_BITS)));
3e3b838f 4229
a2c0ca6f 4230 buf = qemu_blockalign(bs, s->cluster_size);
0d483dce 4231 if (bytes < s->cluster_size) {
a2c0ca6f
PB
4232 /* Zero-pad last write if image size is not cluster aligned */
4233 memset(buf + bytes, 0, s->cluster_size - bytes);
f4d38bef 4234 }
5396234b 4235 qemu_iovec_to_buf(qiov, qiov_offset, buf, bytes);
20d97356 4236
ebf7bba0 4237 out_buf = g_malloc(s->cluster_size);
20d97356 4238
6994fd78
VSO
4239 out_len = qcow2_co_compress(bs, out_buf, s->cluster_size - 1,
4240 buf, s->cluster_size);
e1f4a37a 4241 if (out_len == -ENOMEM) {
20d97356 4242 /* could not compress: write normal cluster */
5396234b 4243 ret = qcow2_co_pwritev_part(bs, offset, bytes, qiov, qiov_offset, 0);
8f1efd00
KW
4244 if (ret < 0) {
4245 goto fail;
4246 }
fcccefc5 4247 goto success;
e1f4a37a
AG
4248 } else if (out_len < 0) {
4249 ret = -EINVAL;
4250 goto fail;
fcccefc5 4251 }
cf93980e 4252
fcccefc5 4253 qemu_co_mutex_lock(&s->lock);
77e023ff
KW
4254 ret = qcow2_alloc_compressed_cluster_offset(bs, offset, out_len,
4255 &cluster_offset);
4256 if (ret < 0) {
fcccefc5 4257 qemu_co_mutex_unlock(&s->lock);
fcccefc5
PB
4258 goto fail;
4259 }
cf93980e 4260
966b000f 4261 ret = qcow2_pre_write_overlap_check(bs, 0, cluster_offset, out_len, true);
fcccefc5
PB
4262 qemu_co_mutex_unlock(&s->lock);
4263 if (ret < 0) {
4264 goto fail;
20d97356
BS
4265 }
4266
966b000f 4267 BLKDBG_EVENT(s->data_file, BLKDBG_WRITE_COMPRESSED);
b00cb15b 4268 ret = bdrv_co_pwrite(s->data_file, cluster_offset, out_len, out_buf, 0);
fcccefc5
PB
4269 if (ret < 0) {
4270 goto fail;
4271 }
4272success:
8f1efd00
KW
4273 ret = 0;
4274fail:
fcccefc5 4275 qemu_vfree(buf);
7267c094 4276 g_free(out_buf);
8f1efd00 4277 return ret;
20d97356
BS
4278}
4279
0d483dce
AS
4280static coroutine_fn int qcow2_co_pwritev_compressed_task_entry(AioTask *task)
4281{
4282 Qcow2AioTask *t = container_of(task, Qcow2AioTask, task);
4283
4284 assert(!t->cluster_type && !t->l2meta);
4285
4286 return qcow2_co_pwritev_compressed_task(t->bs, t->offset, t->bytes, t->qiov,
4287 t->qiov_offset);
4288}
4289
4290/*
4291 * XXX: put compressed sectors first, then all the cluster aligned
4292 * tables to avoid losing bytes in alignment
4293 */
4294static coroutine_fn int
4295qcow2_co_pwritev_compressed_part(BlockDriverState *bs,
4296 uint64_t offset, uint64_t bytes,
4297 QEMUIOVector *qiov, size_t qiov_offset)
4298{
4299 BDRVQcow2State *s = bs->opaque;
4300 AioTaskPool *aio = NULL;
4301 int ret = 0;
4302
4303 if (has_data_file(bs)) {
4304 return -ENOTSUP;
4305 }
4306
4307 if (bytes == 0) {
4308 /*
4309 * align end of file to a sector boundary to ease reading with
4310 * sector based I/Os
4311 */
4312 int64_t len = bdrv_getlength(bs->file->bs);
4313 if (len < 0) {
4314 return len;
4315 }
4316 return bdrv_co_truncate(bs->file, len, false, PREALLOC_MODE_OFF, NULL);
4317 }
4318
4319 if (offset_into_cluster(s, offset)) {
4320 return -EINVAL;
4321 }
4322
4323 while (bytes && aio_task_pool_status(aio) == 0) {
4324 uint64_t chunk_size = MIN(bytes, s->cluster_size);
4325
4326 if (!aio && chunk_size != bytes) {
4327 aio = aio_task_pool_new(QCOW2_MAX_WORKERS);
4328 }
4329
4330 ret = qcow2_add_task(bs, aio, qcow2_co_pwritev_compressed_task_entry,
4331 0, 0, offset, chunk_size, qiov, qiov_offset, NULL);
4332 if (ret < 0) {
4333 break;
4334 }
4335 qiov_offset += chunk_size;
4336 offset += chunk_size;
4337 bytes -= chunk_size;
4338 }
4339
4340 if (aio) {
4341 aio_task_pool_wait_all(aio);
4342 if (ret == 0) {
4343 ret = aio_task_pool_status(aio);
4344 }
4345 g_free(aio);
4346 }
4347
4348 return ret;
4349}
4350
c3c10f72
VSO
4351static int coroutine_fn
4352qcow2_co_preadv_compressed(BlockDriverState *bs,
4353 uint64_t file_cluster_offset,
4354 uint64_t offset,
4355 uint64_t bytes,
df893d25
VSO
4356 QEMUIOVector *qiov,
4357 size_t qiov_offset)
f4b3e2a9
VSO
4358{
4359 BDRVQcow2State *s = bs->opaque;
c3c10f72 4360 int ret = 0, csize, nb_csectors;
f4b3e2a9 4361 uint64_t coffset;
c3c10f72 4362 uint8_t *buf, *out_buf;
c3c10f72 4363 int offset_in_cluster = offset_into_cluster(s, offset);
f4b3e2a9 4364
c3c10f72
VSO
4365 coffset = file_cluster_offset & s->cluster_offset_mask;
4366 nb_csectors = ((file_cluster_offset >> s->csize_shift) & s->csize_mask) + 1;
b6c24694
AG
4367 csize = nb_csectors * QCOW2_COMPRESSED_SECTOR_SIZE -
4368 (coffset & ~QCOW2_COMPRESSED_SECTOR_MASK);
f4b3e2a9 4369
c3c10f72
VSO
4370 buf = g_try_malloc(csize);
4371 if (!buf) {
4372 return -ENOMEM;
4373 }
f4b3e2a9 4374
c3c10f72 4375 out_buf = qemu_blockalign(bs, s->cluster_size);
c068a1cd 4376
c3c10f72 4377 BLKDBG_EVENT(bs->file, BLKDBG_READ_COMPRESSED);
b00cb15b 4378 ret = bdrv_co_pread(bs->file, coffset, csize, buf, 0);
c3c10f72
VSO
4379 if (ret < 0) {
4380 goto fail;
f4b3e2a9 4381 }
c3c10f72 4382
e23c9d7a 4383 if (qcow2_co_decompress(bs, out_buf, s->cluster_size, buf, csize) < 0) {
c3c10f72
VSO
4384 ret = -EIO;
4385 goto fail;
4386 }
4387
df893d25 4388 qemu_iovec_from_buf(qiov, qiov_offset, out_buf + offset_in_cluster, bytes);
c3c10f72
VSO
4389
4390fail:
4391 qemu_vfree(out_buf);
4392 g_free(buf);
4393
4394 return ret;
f4b3e2a9
VSO
4395}
4396
94054183
HR
4397static int make_completely_empty(BlockDriverState *bs)
4398{
ff99129a 4399 BDRVQcow2State *s = bs->opaque;
ed3d2ec9 4400 Error *local_err = NULL;
94054183
HR
4401 int ret, l1_clusters;
4402 int64_t offset;
4403 uint64_t *new_reftable = NULL;
4404 uint64_t rt_entry, l1_size2;
4405 struct {
4406 uint64_t l1_offset;
4407 uint64_t reftable_offset;
4408 uint32_t reftable_clusters;
4409 } QEMU_PACKED l1_ofs_rt_ofs_cls;
4410
4411 ret = qcow2_cache_empty(bs, s->l2_table_cache);
4412 if (ret < 0) {
4413 goto fail;
4414 }
4415
4416 ret = qcow2_cache_empty(bs, s->refcount_block_cache);
4417 if (ret < 0) {
4418 goto fail;
4419 }
4420
4421 /* Refcounts will be broken utterly */
4422 ret = qcow2_mark_dirty(bs);
4423 if (ret < 0) {
4424 goto fail;
4425 }
4426
4427 BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
4428
4429 l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / sizeof(uint64_t));
4430 l1_size2 = (uint64_t)s->l1_size * sizeof(uint64_t);
4431
4432 /* After this call, neither the in-memory nor the on-disk refcount
4433 * information accurately describe the actual references */
4434
720ff280 4435 ret = bdrv_pwrite_zeroes(bs->file, s->l1_table_offset,
74021bc4 4436 l1_clusters * s->cluster_size, 0);
94054183
HR
4437 if (ret < 0) {
4438 goto fail_broken_refcounts;
4439 }
4440 memset(s->l1_table, 0, l1_size2);
4441
4442 BLKDBG_EVENT(bs->file, BLKDBG_EMPTY_IMAGE_PREPARE);
4443
4444 /* Overwrite enough clusters at the beginning of the sectors to place
4445 * the refcount table, a refcount block and the L1 table in; this may
4446 * overwrite parts of the existing refcount and L1 table, which is not
4447 * an issue because the dirty flag is set, complete data loss is in fact
4448 * desired and partial data loss is consequently fine as well */
720ff280 4449 ret = bdrv_pwrite_zeroes(bs->file, s->cluster_size,
74021bc4 4450 (2 + l1_clusters) * s->cluster_size, 0);
94054183
HR
4451 /* This call (even if it failed overall) may have overwritten on-disk
4452 * refcount structures; in that case, the in-memory refcount information
4453 * will probably differ from the on-disk information which makes the BDS
4454 * unusable */
4455 if (ret < 0) {
4456 goto fail_broken_refcounts;
4457 }
4458
4459 BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
4460 BLKDBG_EVENT(bs->file, BLKDBG_REFTABLE_UPDATE);
4461
4462 /* "Create" an empty reftable (one cluster) directly after the image
4463 * header and an empty L1 table three clusters after the image header;
4464 * the cluster between those two will be used as the first refblock */
f1f7a1dd
PM
4465 l1_ofs_rt_ofs_cls.l1_offset = cpu_to_be64(3 * s->cluster_size);
4466 l1_ofs_rt_ofs_cls.reftable_offset = cpu_to_be64(s->cluster_size);
4467 l1_ofs_rt_ofs_cls.reftable_clusters = cpu_to_be32(1);
d9ca2ea2 4468 ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, l1_table_offset),
94054183
HR
4469 &l1_ofs_rt_ofs_cls, sizeof(l1_ofs_rt_ofs_cls));
4470 if (ret < 0) {
4471 goto fail_broken_refcounts;
4472 }
4473
4474 s->l1_table_offset = 3 * s->cluster_size;
4475
4476 new_reftable = g_try_new0(uint64_t, s->cluster_size / sizeof(uint64_t));
4477 if (!new_reftable) {
4478 ret = -ENOMEM;
4479 goto fail_broken_refcounts;
4480 }
4481
4482 s->refcount_table_offset = s->cluster_size;
4483 s->refcount_table_size = s->cluster_size / sizeof(uint64_t);
7061a078 4484 s->max_refcount_table_index = 0;
94054183
HR
4485
4486 g_free(s->refcount_table);
4487 s->refcount_table = new_reftable;
4488 new_reftable = NULL;
4489
4490 /* Now the in-memory refcount information again corresponds to the on-disk
4491 * information (reftable is empty and no refblocks (the refblock cache is
4492 * empty)); however, this means some clusters (e.g. the image header) are
4493 * referenced, but not refcounted, but the normal qcow2 code assumes that
4494 * the in-memory information is always correct */
4495
4496 BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_ALLOC);
4497
4498 /* Enter the first refblock into the reftable */
4499 rt_entry = cpu_to_be64(2 * s->cluster_size);
d9ca2ea2 4500 ret = bdrv_pwrite_sync(bs->file, s->cluster_size,
94054183
HR
4501 &rt_entry, sizeof(rt_entry));
4502 if (ret < 0) {
4503 goto fail_broken_refcounts;
4504 }
4505 s->refcount_table[0] = 2 * s->cluster_size;
4506
4507 s->free_cluster_index = 0;
4508 assert(3 + l1_clusters <= s->refcount_block_size);
4509 offset = qcow2_alloc_clusters(bs, 3 * s->cluster_size + l1_size2);
4510 if (offset < 0) {
4511 ret = offset;
4512 goto fail_broken_refcounts;
4513 } else if (offset > 0) {
4514 error_report("First cluster in emptied image is in use");
4515 abort();
4516 }
4517
4518 /* Now finally the in-memory information corresponds to the on-disk
4519 * structures and is correct */
4520 ret = qcow2_mark_clean(bs);
4521 if (ret < 0) {
4522 goto fail;
4523 }
4524
c80d8b06 4525 ret = bdrv_truncate(bs->file, (3 + l1_clusters) * s->cluster_size, false,
7ea37c30 4526 PREALLOC_MODE_OFF, &local_err);
94054183 4527 if (ret < 0) {
ed3d2ec9 4528 error_report_err(local_err);
94054183
HR
4529 goto fail;
4530 }
4531
4532 return 0;
4533
4534fail_broken_refcounts:
4535 /* The BDS is unusable at this point. If we wanted to make it usable, we
4536 * would have to call qcow2_refcount_close(), qcow2_refcount_init(),
4537 * qcow2_check_refcounts(), qcow2_refcount_close() and qcow2_refcount_init()
4538 * again. However, because the functions which could have caused this error
4539 * path to be taken are used by those functions as well, it's very likely
4540 * that that sequence will fail as well. Therefore, just eject the BDS. */
4541 bs->drv = NULL;
4542
4543fail:
4544 g_free(new_reftable);
4545 return ret;
4546}
4547
491d27e2
HR
4548static int qcow2_make_empty(BlockDriverState *bs)
4549{
ff99129a 4550 BDRVQcow2State *s = bs->opaque;
d2cb36af
EB
4551 uint64_t offset, end_offset;
4552 int step = QEMU_ALIGN_DOWN(INT_MAX, s->cluster_size);
94054183
HR
4553 int l1_clusters, ret = 0;
4554
4555 l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / sizeof(uint64_t));
4556
4096974e 4557 if (s->qcow_version >= 3 && !s->snapshots && !s->nb_bitmaps &&
f0603329 4558 3 + l1_clusters <= s->refcount_block_size &&
db04524f
KW
4559 s->crypt_method_header != QCOW_CRYPT_LUKS &&
4560 !has_data_file(bs)) {
4096974e
EB
4561 /* The following function only works for qcow2 v3 images (it
4562 * requires the dirty flag) and only as long as there are no
4563 * features that reserve extra clusters (such as snapshots,
4564 * LUKS header, or persistent bitmaps), because it completely
4565 * empties the image. Furthermore, the L1 table and three
4566 * additional clusters (image header, refcount table, one
db04524f
KW
4567 * refcount block) have to fit inside one refcount block. It
4568 * only resets the image file, i.e. does not work with an
4569 * external data file. */
94054183
HR
4570 return make_completely_empty(bs);
4571 }
491d27e2 4572
94054183
HR
4573 /* This fallback code simply discards every active cluster; this is slow,
4574 * but works in all cases */
d2cb36af
EB
4575 end_offset = bs->total_sectors * BDRV_SECTOR_SIZE;
4576 for (offset = 0; offset < end_offset; offset += step) {
491d27e2
HR
4577 /* As this function is generally used after committing an external
4578 * snapshot, QCOW2_DISCARD_SNAPSHOT seems appropriate. Also, the
4579 * default action for this kind of discard is to pass the discard,
4580 * which will ideally result in an actually smaller image file, as
4581 * is probably desired. */
d2cb36af
EB
4582 ret = qcow2_cluster_discard(bs, offset, MIN(step, end_offset - offset),
4583 QCOW2_DISCARD_SNAPSHOT, true);
491d27e2
HR
4584 if (ret < 0) {
4585 break;
4586 }
4587 }
4588
4589 return ret;
4590}
4591
a968168c 4592static coroutine_fn int qcow2_co_flush_to_os(BlockDriverState *bs)
20d97356 4593{
ff99129a 4594 BDRVQcow2State *s = bs->opaque;
29c1a730
KW
4595 int ret;
4596
8b94ff85 4597 qemu_co_mutex_lock(&s->lock);
8b220eb7 4598 ret = qcow2_write_caches(bs);
8b94ff85 4599 qemu_co_mutex_unlock(&s->lock);
29c1a730 4600
8b220eb7 4601 return ret;
eb489bb1
KW
4602}
4603
61914f89
SH
4604static ssize_t qcow2_measure_crypto_hdr_init_func(QCryptoBlock *block,
4605 size_t headerlen, void *opaque, Error **errp)
4606{
4607 size_t *headerlenp = opaque;
4608
4609 /* Stash away the payload size */
4610 *headerlenp = headerlen;
4611 return 0;
4612}
4613
4614static ssize_t qcow2_measure_crypto_hdr_write_func(QCryptoBlock *block,
4615 size_t offset, const uint8_t *buf, size_t buflen,
4616 void *opaque, Error **errp)
4617{
4618 /* Discard the bytes, we're not actually writing to an image */
4619 return buflen;
4620}
4621
4622/* Determine the number of bytes for the LUKS payload */
4623static bool qcow2_measure_luks_headerlen(QemuOpts *opts, size_t *len,
4624 Error **errp)
4625{
4626 QDict *opts_qdict;
4627 QDict *cryptoopts_qdict;
4628 QCryptoBlockCreateOptions *cryptoopts;
4629 QCryptoBlock *crypto;
4630
4631 /* Extract "encrypt." options into a qdict */
4632 opts_qdict = qemu_opts_to_qdict(opts, NULL);
4633 qdict_extract_subqdict(opts_qdict, &cryptoopts_qdict, "encrypt.");
4634 qobject_unref(opts_qdict);
4635
4636 /* Build QCryptoBlockCreateOptions object from qdict */
4637 qdict_put_str(cryptoopts_qdict, "format", "luks");
4638 cryptoopts = block_crypto_create_opts_init(cryptoopts_qdict, errp);
4639 qobject_unref(cryptoopts_qdict);
4640 if (!cryptoopts) {
4641 return false;
4642 }
4643
4644 /* Fake LUKS creation in order to determine the payload size */
4645 crypto = qcrypto_block_create(cryptoopts, "encrypt.",
4646 qcow2_measure_crypto_hdr_init_func,
4647 qcow2_measure_crypto_hdr_write_func,
4648 len, errp);
4649 qapi_free_QCryptoBlockCreateOptions(cryptoopts);
4650 if (!crypto) {
4651 return false;
4652 }
4653
4654 qcrypto_block_free(crypto);
4655 return true;
4656}
4657
c501c352
SH
4658static BlockMeasureInfo *qcow2_measure(QemuOpts *opts, BlockDriverState *in_bs,
4659 Error **errp)
4660{
4661 Error *local_err = NULL;
4662 BlockMeasureInfo *info;
4663 uint64_t required = 0; /* bytes that contribute to required size */
4664 uint64_t virtual_size; /* disk size as seen by guest */
4665 uint64_t refcount_bits;
4666 uint64_t l2_tables;
61914f89 4667 uint64_t luks_payload_size = 0;
c501c352
SH
4668 size_t cluster_size;
4669 int version;
4670 char *optstr;
4671 PreallocMode prealloc;
4672 bool has_backing_file;
61914f89 4673 bool has_luks;
c501c352
SH
4674
4675 /* Parse image creation options */
4676 cluster_size = qcow2_opt_get_cluster_size_del(opts, &local_err);
4677 if (local_err) {
4678 goto err;
4679 }
4680
4681 version = qcow2_opt_get_version_del(opts, &local_err);
4682 if (local_err) {
4683 goto err;
4684 }
4685
4686 refcount_bits = qcow2_opt_get_refcount_bits_del(opts, version, &local_err);
4687 if (local_err) {
4688 goto err;
4689 }
4690
4691 optstr = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
f7abe0ec 4692 prealloc = qapi_enum_parse(&PreallocMode_lookup, optstr,
06c60b6c 4693 PREALLOC_MODE_OFF, &local_err);
c501c352
SH
4694 g_free(optstr);
4695 if (local_err) {
4696 goto err;
4697 }
4698
4699 optstr = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
4700 has_backing_file = !!optstr;
4701 g_free(optstr);
4702
61914f89
SH
4703 optstr = qemu_opt_get_del(opts, BLOCK_OPT_ENCRYPT_FORMAT);
4704 has_luks = optstr && strcmp(optstr, "luks") == 0;
4705 g_free(optstr);
4706
4707 if (has_luks) {
4708 size_t headerlen;
4709
4710 if (!qcow2_measure_luks_headerlen(opts, &headerlen, &local_err)) {
4711 goto err;
4712 }
4713
4714 luks_payload_size = ROUND_UP(headerlen, cluster_size);
4715 }
4716
9e029689
AG
4717 virtual_size = qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0);
4718 virtual_size = ROUND_UP(virtual_size, cluster_size);
c501c352
SH
4719
4720 /* Check that virtual disk size is valid */
4721 l2_tables = DIV_ROUND_UP(virtual_size / cluster_size,
4722 cluster_size / sizeof(uint64_t));
4723 if (l2_tables * sizeof(uint64_t) > QCOW_MAX_L1_SIZE) {
4724 error_setg(&local_err, "The image size is too large "
4725 "(try using a larger cluster size)");
4726 goto err;
4727 }
4728
4729 /* Account for input image */
4730 if (in_bs) {
4731 int64_t ssize = bdrv_getlength(in_bs);
4732 if (ssize < 0) {
4733 error_setg_errno(&local_err, -ssize,
4734 "Unable to get image virtual_size");
4735 goto err;
4736 }
4737
9e029689 4738 virtual_size = ROUND_UP(ssize, cluster_size);
c501c352
SH
4739
4740 if (has_backing_file) {
4741 /* We don't how much of the backing chain is shared by the input
4742 * image and the new image file. In the worst case the new image's
4743 * backing file has nothing in common with the input image. Be
4744 * conservative and assume all clusters need to be written.
4745 */
4746 required = virtual_size;
4747 } else {
b85ee453 4748 int64_t offset;
31826642 4749 int64_t pnum = 0;
c501c352 4750
31826642
EB
4751 for (offset = 0; offset < ssize; offset += pnum) {
4752 int ret;
c501c352 4753
31826642
EB
4754 ret = bdrv_block_status_above(in_bs, NULL, offset,
4755 ssize - offset, &pnum, NULL,
4756 NULL);
c501c352
SH
4757 if (ret < 0) {
4758 error_setg_errno(&local_err, -ret,
4759 "Unable to get block status");
4760 goto err;
4761 }
4762
4763 if (ret & BDRV_BLOCK_ZERO) {
4764 /* Skip zero regions (safe with no backing file) */
4765 } else if ((ret & (BDRV_BLOCK_DATA | BDRV_BLOCK_ALLOCATED)) ==
4766 (BDRV_BLOCK_DATA | BDRV_BLOCK_ALLOCATED)) {
4767 /* Extend pnum to end of cluster for next iteration */
31826642 4768 pnum = ROUND_UP(offset + pnum, cluster_size) - offset;
c501c352
SH
4769
4770 /* Count clusters we've seen */
31826642 4771 required += offset % cluster_size + pnum;
c501c352
SH
4772 }
4773 }
4774 }
4775 }
4776
4777 /* Take into account preallocation. Nothing special is needed for
4778 * PREALLOC_MODE_METADATA since metadata is always counted.
4779 */
4780 if (prealloc == PREALLOC_MODE_FULL || prealloc == PREALLOC_MODE_FALLOC) {
4781 required = virtual_size;
4782 }
4783
4784 info = g_new(BlockMeasureInfo, 1);
4785 info->fully_allocated =
4786 qcow2_calc_prealloc_size(virtual_size, cluster_size,
61914f89 4787 ctz32(refcount_bits)) + luks_payload_size;
c501c352
SH
4788
4789 /* Remove data clusters that are not required. This overestimates the
4790 * required size because metadata needed for the fully allocated file is
4791 * still counted.
4792 */
4793 info->required = info->fully_allocated - virtual_size + required;
4794 return info;
4795
4796err:
4797 error_propagate(errp, local_err);
4798 return NULL;
4799}
4800
7c80ab3f 4801static int qcow2_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
20d97356 4802{
ff99129a 4803 BDRVQcow2State *s = bs->opaque;
95de6d70 4804 bdi->unallocated_blocks_are_zero = true;
20d97356 4805 bdi->cluster_size = s->cluster_size;
7c80ab3f 4806 bdi->vm_state_offset = qcow2_vm_state_offset(s);
20d97356
BS
4807 return 0;
4808}
4809
1bf6e9ca
AS
4810static ImageInfoSpecific *qcow2_get_specific_info(BlockDriverState *bs,
4811 Error **errp)
37764dfb 4812{
ff99129a 4813 BDRVQcow2State *s = bs->opaque;
0a12f6f8
DB
4814 ImageInfoSpecific *spec_info;
4815 QCryptoBlockInfo *encrypt_info = NULL;
1bf6e9ca 4816 Error *local_err = NULL;
37764dfb 4817
0a12f6f8 4818 if (s->crypto != NULL) {
1bf6e9ca
AS
4819 encrypt_info = qcrypto_block_get_info(s->crypto, &local_err);
4820 if (local_err) {
4821 error_propagate(errp, local_err);
4822 return NULL;
4823 }
0a12f6f8
DB
4824 }
4825
4826 spec_info = g_new(ImageInfoSpecific, 1);
37764dfb 4827 *spec_info = (ImageInfoSpecific){
6a8f9661 4828 .type = IMAGE_INFO_SPECIFIC_KIND_QCOW2,
b8968c87 4829 .u.qcow2.data = g_new0(ImageInfoSpecificQCow2, 1),
37764dfb
HR
4830 };
4831 if (s->qcow_version == 2) {
32bafa8f 4832 *spec_info->u.qcow2.data = (ImageInfoSpecificQCow2){
0709c5a1
HR
4833 .compat = g_strdup("0.10"),
4834 .refcount_bits = s->refcount_bits,
37764dfb
HR
4835 };
4836 } else if (s->qcow_version == 3) {
b8968c87
AS
4837 Qcow2BitmapInfoList *bitmaps;
4838 bitmaps = qcow2_get_bitmap_info_list(bs, &local_err);
4839 if (local_err) {
4840 error_propagate(errp, local_err);
4841 qapi_free_ImageInfoSpecific(spec_info);
4842 return NULL;
4843 }
32bafa8f 4844 *spec_info->u.qcow2.data = (ImageInfoSpecificQCow2){
37764dfb
HR
4845 .compat = g_strdup("1.1"),
4846 .lazy_refcounts = s->compatible_features &
4847 QCOW2_COMPAT_LAZY_REFCOUNTS,
4848 .has_lazy_refcounts = true,
9009b196
HR
4849 .corrupt = s->incompatible_features &
4850 QCOW2_INCOMPAT_CORRUPT,
4851 .has_corrupt = true,
0709c5a1 4852 .refcount_bits = s->refcount_bits,
b8968c87
AS
4853 .has_bitmaps = !!bitmaps,
4854 .bitmaps = bitmaps,
9b890bdc
KW
4855 .has_data_file = !!s->image_data_file,
4856 .data_file = g_strdup(s->image_data_file),
6c3944dc
KW
4857 .has_data_file_raw = has_data_file(bs),
4858 .data_file_raw = data_file_is_raw(bs),
37764dfb 4859 };
b1fc8f93
DL
4860 } else {
4861 /* if this assertion fails, this probably means a new version was
4862 * added without having it covered here */
4863 assert(false);
37764dfb
HR
4864 }
4865
0a12f6f8
DB
4866 if (encrypt_info) {
4867 ImageInfoSpecificQCow2Encryption *qencrypt =
4868 g_new(ImageInfoSpecificQCow2Encryption, 1);
4869 switch (encrypt_info->format) {
4870 case Q_CRYPTO_BLOCK_FORMAT_QCOW:
4871 qencrypt->format = BLOCKDEV_QCOW2_ENCRYPTION_FORMAT_AES;
0a12f6f8
DB
4872 break;
4873 case Q_CRYPTO_BLOCK_FORMAT_LUKS:
4874 qencrypt->format = BLOCKDEV_QCOW2_ENCRYPTION_FORMAT_LUKS;
4875 qencrypt->u.luks = encrypt_info->u.luks;
4876 break;
4877 default:
4878 abort();
4879 }
4880 /* Since we did shallow copy above, erase any pointers
4881 * in the original info */
4882 memset(&encrypt_info->u, 0, sizeof(encrypt_info->u));
4883 qapi_free_QCryptoBlockInfo(encrypt_info);
4884
4885 spec_info->u.qcow2.data->has_encrypt = true;
4886 spec_info->u.qcow2.data->encrypt = qencrypt;
4887 }
4888
37764dfb
HR
4889 return spec_info;
4890}
4891
38841dcd
HR
4892static int qcow2_has_zero_init(BlockDriverState *bs)
4893{
4894 BDRVQcow2State *s = bs->opaque;
4895 bool preallocated;
4896
4897 if (qemu_in_coroutine()) {
4898 qemu_co_mutex_lock(&s->lock);
4899 }
4900 /*
4901 * Check preallocation status: Preallocated images have all L2
4902 * tables allocated, nonpreallocated images have none. It is
4903 * therefore enough to check the first one.
4904 */
4905 preallocated = s->l1_size > 0 && s->l1_table[0] != 0;
4906 if (qemu_in_coroutine()) {
4907 qemu_co_mutex_unlock(&s->lock);
4908 }
4909
4910 if (!preallocated) {
4911 return 1;
4912 } else if (bs->encrypted) {
4913 return 0;
4914 } else {
4915 return bdrv_has_zero_init(s->data_file->bs);
4916 }
4917}
4918
cf8074b3
KW
4919static int qcow2_save_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
4920 int64_t pos)
20d97356 4921{
ff99129a 4922 BDRVQcow2State *s = bs->opaque;
20d97356 4923
66f82cee 4924 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_SAVE);
5396234b
VSO
4925 return bs->drv->bdrv_co_pwritev_part(bs, qcow2_vm_state_offset(s) + pos,
4926 qiov->size, qiov, 0, 0);
20d97356
BS
4927}
4928
5ddda0b8
KW
4929static int qcow2_load_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
4930 int64_t pos)
20d97356 4931{
ff99129a 4932 BDRVQcow2State *s = bs->opaque;
20d97356 4933
66f82cee 4934 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_LOAD);
df893d25
VSO
4935 return bs->drv->bdrv_co_preadv_part(bs, qcow2_vm_state_offset(s) + pos,
4936 qiov->size, qiov, 0, 0);
20d97356
BS
4937}
4938
9296b3ed
HR
4939/*
4940 * Downgrades an image's version. To achieve this, any incompatible features
4941 * have to be removed.
4942 */
4057a2b2 4943static int qcow2_downgrade(BlockDriverState *bs, int target_version,
d1402b50
HR
4944 BlockDriverAmendStatusCB *status_cb, void *cb_opaque,
4945 Error **errp)
9296b3ed 4946{
ff99129a 4947 BDRVQcow2State *s = bs->opaque;
9296b3ed
HR
4948 int current_version = s->qcow_version;
4949 int ret;
4950
d1402b50
HR
4951 /* This is qcow2_downgrade(), not qcow2_upgrade() */
4952 assert(target_version < current_version);
4953
4954 /* There are no other versions (now) that you can downgrade to */
4955 assert(target_version == 2);
9296b3ed
HR
4956
4957 if (s->refcount_order != 4) {
d1402b50 4958 error_setg(errp, "compat=0.10 requires refcount_bits=16");
9296b3ed
HR
4959 return -ENOTSUP;
4960 }
4961
966b000f
KW
4962 if (has_data_file(bs)) {
4963 error_setg(errp, "Cannot downgrade an image with a data file");
4964 return -ENOTSUP;
4965 }
4966
9296b3ed
HR
4967 /* clear incompatible features */
4968 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
4969 ret = qcow2_mark_clean(bs);
4970 if (ret < 0) {
d1402b50 4971 error_setg_errno(errp, -ret, "Failed to make the image clean");
9296b3ed
HR
4972 return ret;
4973 }
4974 }
4975
4976 /* with QCOW2_INCOMPAT_CORRUPT, it is pretty much impossible to get here in
4977 * the first place; if that happens nonetheless, returning -ENOTSUP is the
4978 * best thing to do anyway */
4979
4980 if (s->incompatible_features) {
d1402b50
HR
4981 error_setg(errp, "Cannot downgrade an image with incompatible features "
4982 "%#" PRIx64 " set", s->incompatible_features);
9296b3ed
HR
4983 return -ENOTSUP;
4984 }
4985
4986 /* since we can ignore compatible features, we can set them to 0 as well */
4987 s->compatible_features = 0;
4988 /* if lazy refcounts have been used, they have already been fixed through
4989 * clearing the dirty flag */
4990
4991 /* clearing autoclear features is trivial */
4992 s->autoclear_features = 0;
4993
8b13976d 4994 ret = qcow2_expand_zero_clusters(bs, status_cb, cb_opaque);
9296b3ed 4995 if (ret < 0) {
d1402b50 4996 error_setg_errno(errp, -ret, "Failed to turn zero into data clusters");
9296b3ed
HR
4997 return ret;
4998 }
4999
5000 s->qcow_version = target_version;
5001 ret = qcow2_update_header(bs);
5002 if (ret < 0) {
5003 s->qcow_version = current_version;
d1402b50 5004 error_setg_errno(errp, -ret, "Failed to update the image header");
9296b3ed
HR
5005 return ret;
5006 }
5007 return 0;
5008}
5009
722efb0c
HR
5010/*
5011 * Upgrades an image's version. While newer versions encompass all
5012 * features of older versions, some things may have to be presented
5013 * differently.
5014 */
5015static int qcow2_upgrade(BlockDriverState *bs, int target_version,
5016 BlockDriverAmendStatusCB *status_cb, void *cb_opaque,
5017 Error **errp)
5018{
5019 BDRVQcow2State *s = bs->opaque;
0a85af35 5020 bool need_snapshot_update;
722efb0c 5021 int current_version = s->qcow_version;
0a85af35 5022 int i;
722efb0c
HR
5023 int ret;
5024
5025 /* This is qcow2_upgrade(), not qcow2_downgrade() */
5026 assert(target_version > current_version);
5027
5028 /* There are no other versions (yet) that you can upgrade to */
5029 assert(target_version == 3);
5030
0a85af35
HR
5031 status_cb(bs, 0, 2, cb_opaque);
5032
5033 /*
5034 * In v2, snapshots do not need to have extra data. v3 requires
5035 * the 64-bit VM state size and the virtual disk size to be
5036 * present.
5037 * qcow2_write_snapshots() will always write the list in the
5038 * v3-compliant format.
5039 */
5040 need_snapshot_update = false;
5041 for (i = 0; i < s->nb_snapshots; i++) {
5042 if (s->snapshots[i].extra_data_size <
5043 sizeof_field(QCowSnapshotExtraData, vm_state_size_large) +
5044 sizeof_field(QCowSnapshotExtraData, disk_size))
5045 {
5046 need_snapshot_update = true;
5047 break;
5048 }
5049 }
5050 if (need_snapshot_update) {
5051 ret = qcow2_write_snapshots(bs);
5052 if (ret < 0) {
5053 error_setg_errno(errp, -ret, "Failed to update the snapshot table");
5054 return ret;
5055 }
5056 }
5057 status_cb(bs, 1, 2, cb_opaque);
722efb0c
HR
5058
5059 s->qcow_version = target_version;
5060 ret = qcow2_update_header(bs);
5061 if (ret < 0) {
5062 s->qcow_version = current_version;
5063 error_setg_errno(errp, -ret, "Failed to update the image header");
5064 return ret;
5065 }
0a85af35 5066 status_cb(bs, 2, 2, cb_opaque);
722efb0c
HR
5067
5068 return 0;
5069}
5070
c293a809
HR
5071typedef enum Qcow2AmendOperation {
5072 /* This is the value Qcow2AmendHelperCBInfo::last_operation will be
5073 * statically initialized to so that the helper CB can discern the first
5074 * invocation from an operation change */
5075 QCOW2_NO_OPERATION = 0,
5076
722efb0c 5077 QCOW2_UPGRADING,
61ce55fc 5078 QCOW2_CHANGING_REFCOUNT_ORDER,
c293a809
HR
5079 QCOW2_DOWNGRADING,
5080} Qcow2AmendOperation;
5081
5082typedef struct Qcow2AmendHelperCBInfo {
5083 /* The code coordinating the amend operations should only modify
5084 * these four fields; the rest will be managed by the CB */
5085 BlockDriverAmendStatusCB *original_status_cb;
5086 void *original_cb_opaque;
5087
5088 Qcow2AmendOperation current_operation;
5089
5090 /* Total number of operations to perform (only set once) */
5091 int total_operations;
5092
5093 /* The following fields are managed by the CB */
5094
5095 /* Number of operations completed */
5096 int operations_completed;
5097
5098 /* Cumulative offset of all completed operations */
5099 int64_t offset_completed;
5100
5101 Qcow2AmendOperation last_operation;
5102 int64_t last_work_size;
5103} Qcow2AmendHelperCBInfo;
5104
5105static void qcow2_amend_helper_cb(BlockDriverState *bs,
5106 int64_t operation_offset,
5107 int64_t operation_work_size, void *opaque)
5108{
5109 Qcow2AmendHelperCBInfo *info = opaque;
5110 int64_t current_work_size;
5111 int64_t projected_work_size;
5112
5113 if (info->current_operation != info->last_operation) {
5114 if (info->last_operation != QCOW2_NO_OPERATION) {
5115 info->offset_completed += info->last_work_size;
5116 info->operations_completed++;
5117 }
5118
5119 info->last_operation = info->current_operation;
5120 }
5121
5122 assert(info->total_operations > 0);
5123 assert(info->operations_completed < info->total_operations);
5124
5125 info->last_work_size = operation_work_size;
5126
5127 current_work_size = info->offset_completed + operation_work_size;
5128
5129 /* current_work_size is the total work size for (operations_completed + 1)
5130 * operations (which includes this one), so multiply it by the number of
5131 * operations not covered and divide it by the number of operations
5132 * covered to get a projection for the operations not covered */
5133 projected_work_size = current_work_size * (info->total_operations -
5134 info->operations_completed - 1)
5135 / (info->operations_completed + 1);
5136
5137 info->original_status_cb(bs, info->offset_completed + operation_offset,
5138 current_work_size + projected_work_size,
5139 info->original_cb_opaque);
5140}
5141
77485434 5142static int qcow2_amend_options(BlockDriverState *bs, QemuOpts *opts,
8b13976d 5143 BlockDriverAmendStatusCB *status_cb,
d1402b50
HR
5144 void *cb_opaque,
5145 Error **errp)
9296b3ed 5146{
ff99129a 5147 BDRVQcow2State *s = bs->opaque;
9296b3ed
HR
5148 int old_version = s->qcow_version, new_version = old_version;
5149 uint64_t new_size = 0;
9b890bdc 5150 const char *backing_file = NULL, *backing_format = NULL, *data_file = NULL;
9296b3ed 5151 bool lazy_refcounts = s->use_lazy_refcounts;
6c3944dc 5152 bool data_file_raw = data_file_is_raw(bs);
1bd0e2d1
CL
5153 const char *compat = NULL;
5154 uint64_t cluster_size = s->cluster_size;
5155 bool encrypt;
4652b8f3 5156 int encformat;
61ce55fc 5157 int refcount_bits = s->refcount_bits;
9296b3ed 5158 int ret;
1bd0e2d1 5159 QemuOptDesc *desc = opts->list->desc;
c293a809 5160 Qcow2AmendHelperCBInfo helper_cb_info;
9296b3ed 5161
1bd0e2d1
CL
5162 while (desc && desc->name) {
5163 if (!qemu_opt_find(opts, desc->name)) {
9296b3ed 5164 /* only change explicitly defined options */
1bd0e2d1 5165 desc++;
9296b3ed
HR
5166 continue;
5167 }
5168
8a17b83c
HR
5169 if (!strcmp(desc->name, BLOCK_OPT_COMPAT_LEVEL)) {
5170 compat = qemu_opt_get(opts, BLOCK_OPT_COMPAT_LEVEL);
1bd0e2d1 5171 if (!compat) {
9296b3ed 5172 /* preserve default */
f7077c98 5173 } else if (!strcmp(compat, "0.10") || !strcmp(compat, "v2")) {
9296b3ed 5174 new_version = 2;
f7077c98 5175 } else if (!strcmp(compat, "1.1") || !strcmp(compat, "v3")) {
9296b3ed
HR
5176 new_version = 3;
5177 } else {
d1402b50 5178 error_setg(errp, "Unknown compatibility level %s", compat);
9296b3ed
HR
5179 return -EINVAL;
5180 }
8a17b83c 5181 } else if (!strcmp(desc->name, BLOCK_OPT_PREALLOC)) {
d1402b50 5182 error_setg(errp, "Cannot change preallocation mode");
9296b3ed 5183 return -ENOTSUP;
8a17b83c
HR
5184 } else if (!strcmp(desc->name, BLOCK_OPT_SIZE)) {
5185 new_size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, 0);
5186 } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FILE)) {
5187 backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
5188 } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FMT)) {
5189 backing_format = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
5190 } else if (!strcmp(desc->name, BLOCK_OPT_ENCRYPT)) {
5191 encrypt = qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT,
b25b387f 5192 !!s->crypto);
f6fa64f6 5193
b25b387f 5194 if (encrypt != !!s->crypto) {
d1402b50
HR
5195 error_setg(errp,
5196 "Changing the encryption flag is not supported");
9296b3ed
HR
5197 return -ENOTSUP;
5198 }
4652b8f3
DB
5199 } else if (!strcmp(desc->name, BLOCK_OPT_ENCRYPT_FORMAT)) {
5200 encformat = qcow2_crypt_method_from_format(
5201 qemu_opt_get(opts, BLOCK_OPT_ENCRYPT_FORMAT));
5202
5203 if (encformat != s->crypt_method_header) {
d1402b50
HR
5204 error_setg(errp,
5205 "Changing the encryption format is not supported");
4652b8f3
DB
5206 return -ENOTSUP;
5207 }
f66afbe2 5208 } else if (g_str_has_prefix(desc->name, "encrypt.")) {
d1402b50
HR
5209 error_setg(errp,
5210 "Changing the encryption parameters is not supported");
f66afbe2 5211 return -ENOTSUP;
8a17b83c
HR
5212 } else if (!strcmp(desc->name, BLOCK_OPT_CLUSTER_SIZE)) {
5213 cluster_size = qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE,
1bd0e2d1
CL
5214 cluster_size);
5215 if (cluster_size != s->cluster_size) {
d1402b50 5216 error_setg(errp, "Changing the cluster size is not supported");
9296b3ed
HR
5217 return -ENOTSUP;
5218 }
8a17b83c
HR
5219 } else if (!strcmp(desc->name, BLOCK_OPT_LAZY_REFCOUNTS)) {
5220 lazy_refcounts = qemu_opt_get_bool(opts, BLOCK_OPT_LAZY_REFCOUNTS,
1bd0e2d1 5221 lazy_refcounts);
06d05fa7 5222 } else if (!strcmp(desc->name, BLOCK_OPT_REFCOUNT_BITS)) {
61ce55fc
HR
5223 refcount_bits = qemu_opt_get_number(opts, BLOCK_OPT_REFCOUNT_BITS,
5224 refcount_bits);
5225
5226 if (refcount_bits <= 0 || refcount_bits > 64 ||
5227 !is_power_of_2(refcount_bits))
5228 {
d1402b50
HR
5229 error_setg(errp, "Refcount width must be a power of two and "
5230 "may not exceed 64 bits");
61ce55fc
HR
5231 return -EINVAL;
5232 }
9b890bdc
KW
5233 } else if (!strcmp(desc->name, BLOCK_OPT_DATA_FILE)) {
5234 data_file = qemu_opt_get(opts, BLOCK_OPT_DATA_FILE);
5235 if (data_file && !has_data_file(bs)) {
5236 error_setg(errp, "data-file can only be set for images that "
5237 "use an external data file");
5238 return -EINVAL;
5239 }
6c3944dc
KW
5240 } else if (!strcmp(desc->name, BLOCK_OPT_DATA_FILE_RAW)) {
5241 data_file_raw = qemu_opt_get_bool(opts, BLOCK_OPT_DATA_FILE_RAW,
5242 data_file_raw);
5243 if (data_file_raw && !data_file_is_raw(bs)) {
5244 error_setg(errp, "data-file-raw cannot be set on existing "
5245 "images");
5246 return -EINVAL;
5247 }
9296b3ed 5248 } else {
164e0f89 5249 /* if this point is reached, this probably means a new option was
9296b3ed 5250 * added without having it covered here */
164e0f89 5251 abort();
9296b3ed 5252 }
1bd0e2d1
CL
5253
5254 desc++;
9296b3ed
HR
5255 }
5256
c293a809
HR
5257 helper_cb_info = (Qcow2AmendHelperCBInfo){
5258 .original_status_cb = status_cb,
5259 .original_cb_opaque = cb_opaque,
722efb0c 5260 .total_operations = (new_version != old_version)
61ce55fc 5261 + (s->refcount_bits != refcount_bits)
c293a809
HR
5262 };
5263
1038bbb8
HR
5264 /* Upgrade first (some features may require compat=1.1) */
5265 if (new_version > old_version) {
722efb0c
HR
5266 helper_cb_info.current_operation = QCOW2_UPGRADING;
5267 ret = qcow2_upgrade(bs, new_version, &qcow2_amend_helper_cb,
5268 &helper_cb_info, errp);
1038bbb8 5269 if (ret < 0) {
1038bbb8 5270 return ret;
9296b3ed
HR
5271 }
5272 }
5273
61ce55fc
HR
5274 if (s->refcount_bits != refcount_bits) {
5275 int refcount_order = ctz32(refcount_bits);
61ce55fc
HR
5276
5277 if (new_version < 3 && refcount_bits != 16) {
d1402b50
HR
5278 error_setg(errp, "Refcount widths other than 16 bits require "
5279 "compatibility level 1.1 or above (use compat=1.1 or "
5280 "greater)");
61ce55fc
HR
5281 return -EINVAL;
5282 }
5283
5284 helper_cb_info.current_operation = QCOW2_CHANGING_REFCOUNT_ORDER;
5285 ret = qcow2_change_refcount_order(bs, refcount_order,
5286 &qcow2_amend_helper_cb,
d1402b50 5287 &helper_cb_info, errp);
61ce55fc 5288 if (ret < 0) {
61ce55fc
HR
5289 return ret;
5290 }
5291 }
5292
6c3944dc
KW
5293 /* data-file-raw blocks backing files, so clear it first if requested */
5294 if (data_file_raw) {
5295 s->autoclear_features |= QCOW2_AUTOCLEAR_DATA_FILE_RAW;
5296 } else {
5297 s->autoclear_features &= ~QCOW2_AUTOCLEAR_DATA_FILE_RAW;
5298 }
5299
9b890bdc
KW
5300 if (data_file) {
5301 g_free(s->image_data_file);
5302 s->image_data_file = *data_file ? g_strdup(data_file) : NULL;
5303 }
5304
5305 ret = qcow2_update_header(bs);
5306 if (ret < 0) {
5307 error_setg_errno(errp, -ret, "Failed to update the image header");
5308 return ret;
5309 }
5310
9296b3ed 5311 if (backing_file || backing_format) {
e4603fe1
KW
5312 ret = qcow2_change_backing_file(bs,
5313 backing_file ?: s->image_backing_file,
5314 backing_format ?: s->image_backing_format);
9296b3ed 5315 if (ret < 0) {
d1402b50 5316 error_setg_errno(errp, -ret, "Failed to change the backing file");
9296b3ed
HR
5317 return ret;
5318 }
5319 }
5320
5321 if (s->use_lazy_refcounts != lazy_refcounts) {
5322 if (lazy_refcounts) {
1038bbb8 5323 if (new_version < 3) {
d1402b50
HR
5324 error_setg(errp, "Lazy refcounts only supported with "
5325 "compatibility level 1.1 and above (use compat=1.1 "
5326 "or greater)");
9296b3ed
HR
5327 return -EINVAL;
5328 }
5329 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
5330 ret = qcow2_update_header(bs);
5331 if (ret < 0) {
5332 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
d1402b50 5333 error_setg_errno(errp, -ret, "Failed to update the image header");
9296b3ed
HR
5334 return ret;
5335 }
5336 s->use_lazy_refcounts = true;
5337 } else {
5338 /* make image clean first */
5339 ret = qcow2_mark_clean(bs);
5340 if (ret < 0) {
d1402b50 5341 error_setg_errno(errp, -ret, "Failed to make the image clean");
9296b3ed
HR
5342 return ret;
5343 }
5344 /* now disallow lazy refcounts */
5345 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
5346 ret = qcow2_update_header(bs);
5347 if (ret < 0) {
5348 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
d1402b50 5349 error_setg_errno(errp, -ret, "Failed to update the image header");
9296b3ed
HR
5350 return ret;
5351 }
5352 s->use_lazy_refcounts = false;
5353 }
5354 }
5355
5356 if (new_size) {
d861ab3a
KW
5357 BlockBackend *blk = blk_new(bdrv_get_aio_context(bs),
5358 BLK_PERM_RESIZE, BLK_PERM_ALL);
d1402b50 5359 ret = blk_insert_bs(blk, bs, errp);
d7086422 5360 if (ret < 0) {
d7086422
KW
5361 blk_unref(blk);
5362 return ret;
5363 }
5364
e8d04f92
HR
5365 /*
5366 * Amending image options should ensure that the image has
5367 * exactly the given new values, so pass exact=true here.
5368 */
5369 ret = blk_truncate(blk, new_size, true, PREALLOC_MODE_OFF, errp);
70b27f36 5370 blk_unref(blk);
9296b3ed
HR
5371 if (ret < 0) {
5372 return ret;
5373 }
5374 }
5375
1038bbb8
HR
5376 /* Downgrade last (so unsupported features can be removed before) */
5377 if (new_version < old_version) {
c293a809
HR
5378 helper_cb_info.current_operation = QCOW2_DOWNGRADING;
5379 ret = qcow2_downgrade(bs, new_version, &qcow2_amend_helper_cb,
d1402b50 5380 &helper_cb_info, errp);
1038bbb8
HR
5381 if (ret < 0) {
5382 return ret;
5383 }
5384 }
5385
9296b3ed
HR
5386 return 0;
5387}
5388
85186ebd
HR
5389/*
5390 * If offset or size are negative, respectively, they will not be included in
5391 * the BLOCK_IMAGE_CORRUPTED event emitted.
5392 * fatal will be ignored for read-only BDS; corruptions found there will always
5393 * be considered non-fatal.
5394 */
5395void qcow2_signal_corruption(BlockDriverState *bs, bool fatal, int64_t offset,
5396 int64_t size, const char *message_format, ...)
5397{
ff99129a 5398 BDRVQcow2State *s = bs->opaque;
dc881b44 5399 const char *node_name;
85186ebd
HR
5400 char *message;
5401 va_list ap;
5402
ddf3b47e 5403 fatal = fatal && bdrv_is_writable(bs);
85186ebd
HR
5404
5405 if (s->signaled_corruption &&
5406 (!fatal || (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT)))
5407 {
5408 return;
5409 }
5410
5411 va_start(ap, message_format);
5412 message = g_strdup_vprintf(message_format, ap);
5413 va_end(ap);
5414
5415 if (fatal) {
5416 fprintf(stderr, "qcow2: Marking image as corrupt: %s; further "
5417 "corruption events will be suppressed\n", message);
5418 } else {
5419 fprintf(stderr, "qcow2: Image is corrupt: %s; further non-fatal "
5420 "corruption events will be suppressed\n", message);
5421 }
5422
dc881b44
AG
5423 node_name = bdrv_get_node_name(bs);
5424 qapi_event_send_block_image_corrupted(bdrv_get_device_name(bs),
5425 *node_name != '\0', node_name,
5426 message, offset >= 0, offset,
5427 size >= 0, size,
3ab72385 5428 fatal);
85186ebd
HR
5429 g_free(message);
5430
5431 if (fatal) {
5432 qcow2_mark_corrupt(bs);
5433 bs->drv = NULL; /* make BDS unusable */
5434 }
5435
5436 s->signaled_corruption = true;
5437}
5438
1bd0e2d1
CL
5439static QemuOptsList qcow2_create_opts = {
5440 .name = "qcow2-create-opts",
5441 .head = QTAILQ_HEAD_INITIALIZER(qcow2_create_opts.head),
5442 .desc = {
5443 {
5444 .name = BLOCK_OPT_SIZE,
5445 .type = QEMU_OPT_SIZE,
5446 .help = "Virtual disk size"
5447 },
5448 {
5449 .name = BLOCK_OPT_COMPAT_LEVEL,
5450 .type = QEMU_OPT_STRING,
f7077c98 5451 .help = "Compatibility level (v2 [0.10] or v3 [1.1])"
1bd0e2d1
CL
5452 },
5453 {
5454 .name = BLOCK_OPT_BACKING_FILE,
5455 .type = QEMU_OPT_STRING,
5456 .help = "File name of a base image"
5457 },
5458 {
5459 .name = BLOCK_OPT_BACKING_FMT,
5460 .type = QEMU_OPT_STRING,
5461 .help = "Image format of the base image"
5462 },
9b890bdc
KW
5463 {
5464 .name = BLOCK_OPT_DATA_FILE,
5465 .type = QEMU_OPT_STRING,
5466 .help = "File name of an external data file"
5467 },
6c3944dc
KW
5468 {
5469 .name = BLOCK_OPT_DATA_FILE_RAW,
5470 .type = QEMU_OPT_BOOL,
5471 .help = "The external data file must stay valid as a raw image"
5472 },
1bd0e2d1
CL
5473 {
5474 .name = BLOCK_OPT_ENCRYPT,
5475 .type = QEMU_OPT_BOOL,
0cb8d47b
DB
5476 .help = "Encrypt the image with format 'aes'. (Deprecated "
5477 "in favor of " BLOCK_OPT_ENCRYPT_FORMAT "=aes)",
5478 },
5479 {
5480 .name = BLOCK_OPT_ENCRYPT_FORMAT,
5481 .type = QEMU_OPT_STRING,
4652b8f3 5482 .help = "Encrypt the image, format choices: 'aes', 'luks'",
1bd0e2d1 5483 },
4652b8f3
DB
5484 BLOCK_CRYPTO_OPT_DEF_KEY_SECRET("encrypt.",
5485 "ID of secret providing qcow AES key or LUKS passphrase"),
5486 BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_ALG("encrypt."),
5487 BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_MODE("encrypt."),
5488 BLOCK_CRYPTO_OPT_DEF_LUKS_IVGEN_ALG("encrypt."),
5489 BLOCK_CRYPTO_OPT_DEF_LUKS_IVGEN_HASH_ALG("encrypt."),
5490 BLOCK_CRYPTO_OPT_DEF_LUKS_HASH_ALG("encrypt."),
5491 BLOCK_CRYPTO_OPT_DEF_LUKS_ITER_TIME("encrypt."),
1bd0e2d1
CL
5492 {
5493 .name = BLOCK_OPT_CLUSTER_SIZE,
5494 .type = QEMU_OPT_SIZE,
5495 .help = "qcow2 cluster size",
5496 .def_value_str = stringify(DEFAULT_CLUSTER_SIZE)
5497 },
5498 {
5499 .name = BLOCK_OPT_PREALLOC,
5500 .type = QEMU_OPT_STRING,
0e4271b7
HT
5501 .help = "Preallocation mode (allowed values: off, metadata, "
5502 "falloc, full)"
1bd0e2d1
CL
5503 },
5504 {
5505 .name = BLOCK_OPT_LAZY_REFCOUNTS,
5506 .type = QEMU_OPT_BOOL,
5507 .help = "Postpone refcount updates",
5508 .def_value_str = "off"
5509 },
06d05fa7
HR
5510 {
5511 .name = BLOCK_OPT_REFCOUNT_BITS,
5512 .type = QEMU_OPT_NUMBER,
5513 .help = "Width of a reference count entry in bits",
5514 .def_value_str = "16"
5515 },
1bd0e2d1
CL
5516 { /* end of list */ }
5517 }
20d97356
BS
5518};
5519
2654267c
HR
5520static const char *const qcow2_strong_runtime_opts[] = {
5521 "encrypt." BLOCK_CRYPTO_OPT_QCOW_KEY_SECRET,
5522
5523 NULL
5524};
5525
5f535a94 5526BlockDriver bdrv_qcow2 = {
7c80ab3f 5527 .format_name = "qcow2",
ff99129a 5528 .instance_size = sizeof(BDRVQcow2State),
7c80ab3f
JS
5529 .bdrv_probe = qcow2_probe,
5530 .bdrv_open = qcow2_open,
5531 .bdrv_close = qcow2_close,
21d82ac9 5532 .bdrv_reopen_prepare = qcow2_reopen_prepare,
5b0959a7
KW
5533 .bdrv_reopen_commit = qcow2_reopen_commit,
5534 .bdrv_reopen_abort = qcow2_reopen_abort,
5365f44d 5535 .bdrv_join_options = qcow2_join_options,
862f215f 5536 .bdrv_child_perm = bdrv_format_default_perms,
efc75e2a 5537 .bdrv_co_create_opts = qcow2_co_create_opts,
b0292b85 5538 .bdrv_co_create = qcow2_co_create,
38841dcd 5539 .bdrv_has_zero_init = qcow2_has_zero_init,
1dcaf527 5540 .bdrv_has_zero_init_truncate = bdrv_has_zero_init_1,
a320fb04 5541 .bdrv_co_block_status = qcow2_co_block_status,
7c80ab3f 5542
df893d25 5543 .bdrv_co_preadv_part = qcow2_co_preadv_part,
5396234b 5544 .bdrv_co_pwritev_part = qcow2_co_pwritev_part,
eb489bb1 5545 .bdrv_co_flush_to_os = qcow2_co_flush_to_os,
419b19d9 5546
5544b59f 5547 .bdrv_co_pwrite_zeroes = qcow2_co_pwrite_zeroes,
82e8a788 5548 .bdrv_co_pdiscard = qcow2_co_pdiscard,
fd9fcd37
FZ
5549 .bdrv_co_copy_range_from = qcow2_co_copy_range_from,
5550 .bdrv_co_copy_range_to = qcow2_co_copy_range_to,
061ca8a3 5551 .bdrv_co_truncate = qcow2_co_truncate,
5396234b 5552 .bdrv_co_pwritev_compressed_part = qcow2_co_pwritev_compressed_part,
491d27e2 5553 .bdrv_make_empty = qcow2_make_empty,
20d97356
BS
5554
5555 .bdrv_snapshot_create = qcow2_snapshot_create,
5556 .bdrv_snapshot_goto = qcow2_snapshot_goto,
5557 .bdrv_snapshot_delete = qcow2_snapshot_delete,
5558 .bdrv_snapshot_list = qcow2_snapshot_list,
1bd0e2d1 5559 .bdrv_snapshot_load_tmp = qcow2_snapshot_load_tmp,
c501c352 5560 .bdrv_measure = qcow2_measure,
1bd0e2d1 5561 .bdrv_get_info = qcow2_get_info,
37764dfb 5562 .bdrv_get_specific_info = qcow2_get_specific_info,
20d97356 5563
7c80ab3f
JS
5564 .bdrv_save_vmstate = qcow2_save_vmstate,
5565 .bdrv_load_vmstate = qcow2_load_vmstate,
20d97356 5566
8ee79e70 5567 .supports_backing = true,
20d97356
BS
5568 .bdrv_change_backing_file = qcow2_change_backing_file,
5569
d34682cd 5570 .bdrv_refresh_limits = qcow2_refresh_limits,
2b148f39 5571 .bdrv_co_invalidate_cache = qcow2_co_invalidate_cache,
ec6d8912 5572 .bdrv_inactivate = qcow2_inactivate,
06d9260f 5573
1bd0e2d1 5574 .create_opts = &qcow2_create_opts,
2654267c 5575 .strong_runtime_opts = qcow2_strong_runtime_opts,
8a2ce0bc 5576 .mutable_opts = mutable_opts,
2fd61638 5577 .bdrv_co_check = qcow2_co_check,
c282e1fd 5578 .bdrv_amend_options = qcow2_amend_options,
279621c0
AG
5579
5580 .bdrv_detach_aio_context = qcow2_detach_aio_context,
5581 .bdrv_attach_aio_context = qcow2_attach_aio_context,
1b6b0562 5582
d2c3080e
VSO
5583 .bdrv_co_can_store_new_dirty_bitmap = qcow2_co_can_store_new_dirty_bitmap,
5584 .bdrv_co_remove_persistent_dirty_bitmap =
5585 qcow2_co_remove_persistent_dirty_bitmap,
20d97356
BS
5586};
5587
5efa9d5a
AL
5588static void bdrv_qcow2_init(void)
5589{
5590 bdrv_register(&bdrv_qcow2);
5591}
5592
5593block_init(bdrv_qcow2_init);