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