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