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