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