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