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