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