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