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