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