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