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