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