]> git.proxmox.com Git - mirror_qemu.git/blame - block/qcow2.c
block: Do not truncate file node when formatting
[mirror_qemu.git] / block / qcow2.c
CommitLineData
585f8587
FB
1/*
2 * Block driver for the QCOW version 2 format
5fafdf24 3 *
585f8587 4 * Copyright (c) 2004-2006 Fabrice Bellard
5fafdf24 5 *
585f8587
FB
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
23 */
e688df6b 24
80c71a24 25#include "qemu/osdep.h"
2714f13d 26
609f45ea 27#include "block/qdict.h"
23588797 28#include "sysemu/block-backend.h"
db725815 29#include "qemu/main-loop.h"
1de7afc9 30#include "qemu/module.h"
0d8c41da 31#include "qcow2.h"
1de7afc9 32#include "qemu/error-report.h"
e688df6b 33#include "qapi/error.h"
9af23989 34#include "qapi/qapi-events-block-core.h"
6b673957
MA
35#include "qapi/qmp/qdict.h"
36#include "qapi/qmp/qstring.h"
3cce16f4 37#include "trace.h"
1bd0e2d1 38#include "qemu/option_int.h"
f348b6d1 39#include "qemu/cutils.h"
58369e22 40#include "qemu/bswap.h"
b76b4f60
KW
41#include "qapi/qobject-input-visitor.h"
42#include "qapi/qapi-visit-block-core.h"
0d8c41da 43#include "crypto.h"
d710cf57 44#include "block/aio_task.h"
585f8587
FB
45
46/*
47 Differences with QCOW:
48
49 - Support for multiple incremental snapshots.
50 - Memory management by reference counts.
51 - Clusters which have a reference count of one have the bit
52 QCOW_OFLAG_COPIED to optimize write performance.
5fafdf24 53 - Size of compressed clusters is stored in sectors to reduce bit usage
585f8587
FB
54 in the cluster offsets.
55 - Support for storing additional data (such as the VM state) in the
3b46e624 56 snapshots.
585f8587
FB
57 - If a backing store is used, the cluster size is not constrained
58 (could be backported to QCOW).
59 - L2 tables have always a size of one cluster.
60*/
61
9b80ddf3
AL
62
63typedef struct {
64 uint32_t magic;
65 uint32_t len;
c4217f64 66} QEMU_PACKED QCowExtension;
21d82ac9 67
7c80ab3f
JS
68#define QCOW2_EXT_MAGIC_END 0
69#define QCOW2_EXT_MAGIC_BACKING_FORMAT 0xE2792ACA
cfcc4c62 70#define QCOW2_EXT_MAGIC_FEATURE_TABLE 0x6803f857
4652b8f3 71#define QCOW2_EXT_MAGIC_CRYPTO_HEADER 0x0537be77
88ddffae 72#define QCOW2_EXT_MAGIC_BITMAPS 0x23852875
93c24936 73#define QCOW2_EXT_MAGIC_DATA_FILE 0x44415441
9b80ddf3 74
c3c10f72
VSO
75static int coroutine_fn
76qcow2_co_preadv_compressed(BlockDriverState *bs,
77 uint64_t file_cluster_offset,
78 uint64_t offset,
79 uint64_t bytes,
df893d25
VSO
80 QEMUIOVector *qiov,
81 size_t qiov_offset);
c3c10f72 82
7c80ab3f 83static int qcow2_probe(const uint8_t *buf, int buf_size, const char *filename)
585f8587
FB
84{
85 const QCowHeader *cow_header = (const void *)buf;
3b46e624 86
585f8587
FB
87 if (buf_size >= sizeof(QCowHeader) &&
88 be32_to_cpu(cow_header->magic) == QCOW_MAGIC &&
6744cbab 89 be32_to_cpu(cow_header->version) >= 2)
585f8587
FB
90 return 100;
91 else
92 return 0;
93}
94
9b80ddf3 95
4652b8f3
DB
96static ssize_t qcow2_crypto_hdr_read_func(QCryptoBlock *block, size_t offset,
97 uint8_t *buf, size_t buflen,
98 void *opaque, Error **errp)
99{
100 BlockDriverState *bs = opaque;
101 BDRVQcow2State *s = bs->opaque;
102 ssize_t ret;
103
104 if ((offset + buflen) > s->crypto_header.length) {
105 error_setg(errp, "Request for data outside of extension header");
106 return -1;
107 }
108
109 ret = bdrv_pread(bs->file,
110 s->crypto_header.offset + offset, buf, buflen);
111 if (ret < 0) {
112 error_setg_errno(errp, -ret, "Could not read encryption header");
113 return -1;
114 }
115 return ret;
116}
117
118
119static ssize_t qcow2_crypto_hdr_init_func(QCryptoBlock *block, size_t headerlen,
120 void *opaque, Error **errp)
121{
122 BlockDriverState *bs = opaque;
123 BDRVQcow2State *s = bs->opaque;
124 int64_t ret;
125 int64_t clusterlen;
126
127 ret = qcow2_alloc_clusters(bs, headerlen);
128 if (ret < 0) {
129 error_setg_errno(errp, -ret,
130 "Cannot allocate cluster for LUKS header size %zu",
131 headerlen);
132 return -1;
133 }
134
135 s->crypto_header.length = headerlen;
136 s->crypto_header.offset = ret;
137
138 /* Zero fill remaining space in cluster so it has predictable
139 * content in case of future spec changes */
140 clusterlen = size_to_clusters(s, headerlen) * s->cluster_size;
966b000f 141 assert(qcow2_pre_write_overlap_check(bs, 0, ret, clusterlen, false) == 0);
4652b8f3
DB
142 ret = bdrv_pwrite_zeroes(bs->file,
143 ret + headerlen,
144 clusterlen - headerlen, 0);
145 if (ret < 0) {
146 error_setg_errno(errp, -ret, "Could not zero fill encryption header");
147 return -1;
148 }
149
150 return ret;
151}
152
153
154static ssize_t qcow2_crypto_hdr_write_func(QCryptoBlock *block, size_t offset,
155 const uint8_t *buf, size_t buflen,
156 void *opaque, Error **errp)
157{
158 BlockDriverState *bs = opaque;
159 BDRVQcow2State *s = bs->opaque;
160 ssize_t ret;
161
162 if ((offset + buflen) > s->crypto_header.length) {
163 error_setg(errp, "Request for data outside of extension header");
164 return -1;
165 }
166
167 ret = bdrv_pwrite(bs->file,
168 s->crypto_header.offset + offset, buf, buflen);
169 if (ret < 0) {
170 error_setg_errno(errp, -ret, "Could not read encryption header");
171 return -1;
172 }
173 return ret;
174}
175
176
9b80ddf3
AL
177/*
178 * read qcow2 extension and fill bs
179 * start reading from start_offset
180 * finish reading upon magic of value 0 or when end_offset reached
181 * unknown magic is skipped (future extension this version knows nothing about)
182 * return 0 upon success, non-0 otherwise
183 */
7c80ab3f 184static int qcow2_read_extensions(BlockDriverState *bs, uint64_t start_offset,
3ef6c40a 185 uint64_t end_offset, void **p_feature_table,
88ddffae
VSO
186 int flags, bool *need_update_header,
187 Error **errp)
9b80ddf3 188{
ff99129a 189 BDRVQcow2State *s = bs->opaque;
9b80ddf3
AL
190 QCowExtension ext;
191 uint64_t offset;
75bab85c 192 int ret;
88ddffae
VSO
193 Qcow2BitmapHeaderExt bitmaps_ext;
194
195 if (need_update_header != NULL) {
196 *need_update_header = false;
197 }
9b80ddf3
AL
198
199#ifdef DEBUG_EXT
7c80ab3f 200 printf("qcow2_read_extensions: start=%ld end=%ld\n", start_offset, end_offset);
9b80ddf3
AL
201#endif
202 offset = start_offset;
203 while (offset < end_offset) {
204
205#ifdef DEBUG_EXT
206 /* Sanity check */
207 if (offset > s->cluster_size)
7c80ab3f 208 printf("qcow2_read_extension: suspicious offset %lu\n", offset);
9b80ddf3 209
9b2260cb 210 printf("attempting to read extended header in offset %lu\n", offset);
9b80ddf3
AL
211#endif
212
cf2ab8fc 213 ret = bdrv_pread(bs->file, offset, &ext, sizeof(ext));
3ef6c40a
HR
214 if (ret < 0) {
215 error_setg_errno(errp, -ret, "qcow2_read_extension: ERROR: "
216 "pread fail from offset %" PRIu64, offset);
9b80ddf3
AL
217 return 1;
218 }
3b698f52
PM
219 ext.magic = be32_to_cpu(ext.magic);
220 ext.len = be32_to_cpu(ext.len);
9b80ddf3
AL
221 offset += sizeof(ext);
222#ifdef DEBUG_EXT
223 printf("ext.magic = 0x%x\n", ext.magic);
224#endif
2ebafc85 225 if (offset > end_offset || ext.len > end_offset - offset) {
3ef6c40a 226 error_setg(errp, "Header extension too large");
64ca6aee
KW
227 return -EINVAL;
228 }
229
9b80ddf3 230 switch (ext.magic) {
7c80ab3f 231 case QCOW2_EXT_MAGIC_END:
9b80ddf3 232 return 0;
f965509c 233
7c80ab3f 234 case QCOW2_EXT_MAGIC_BACKING_FORMAT:
f965509c 235 if (ext.len >= sizeof(bs->backing_format)) {
521b2b5d
HR
236 error_setg(errp, "ERROR: ext_backing_format: len=%" PRIu32
237 " too large (>=%zu)", ext.len,
238 sizeof(bs->backing_format));
f965509c
AL
239 return 2;
240 }
cf2ab8fc 241 ret = bdrv_pread(bs->file, offset, bs->backing_format, ext.len);
3ef6c40a
HR
242 if (ret < 0) {
243 error_setg_errno(errp, -ret, "ERROR: ext_backing_format: "
244 "Could not read format name");
f965509c 245 return 3;
3ef6c40a 246 }
f965509c 247 bs->backing_format[ext.len] = '\0';
e4603fe1 248 s->image_backing_format = g_strdup(bs->backing_format);
f965509c
AL
249#ifdef DEBUG_EXT
250 printf("Qcow2: Got format extension %s\n", bs->backing_format);
251#endif
f965509c
AL
252 break;
253
cfcc4c62
KW
254 case QCOW2_EXT_MAGIC_FEATURE_TABLE:
255 if (p_feature_table != NULL) {
256 void* feature_table = g_malloc0(ext.len + 2 * sizeof(Qcow2Feature));
cf2ab8fc 257 ret = bdrv_pread(bs->file, offset , feature_table, ext.len);
cfcc4c62 258 if (ret < 0) {
3ef6c40a
HR
259 error_setg_errno(errp, -ret, "ERROR: ext_feature_table: "
260 "Could not read table");
cfcc4c62
KW
261 return ret;
262 }
263
264 *p_feature_table = feature_table;
265 }
266 break;
267
4652b8f3
DB
268 case QCOW2_EXT_MAGIC_CRYPTO_HEADER: {
269 unsigned int cflags = 0;
270 if (s->crypt_method_header != QCOW_CRYPT_LUKS) {
271 error_setg(errp, "CRYPTO header extension only "
272 "expected with LUKS encryption method");
273 return -EINVAL;
274 }
275 if (ext.len != sizeof(Qcow2CryptoHeaderExtension)) {
276 error_setg(errp, "CRYPTO header extension size %u, "
277 "but expected size %zu", ext.len,
278 sizeof(Qcow2CryptoHeaderExtension));
279 return -EINVAL;
280 }
281
282 ret = bdrv_pread(bs->file, offset, &s->crypto_header, ext.len);
283 if (ret < 0) {
284 error_setg_errno(errp, -ret,
285 "Unable to read CRYPTO header extension");
286 return ret;
287 }
3b698f52
PM
288 s->crypto_header.offset = be64_to_cpu(s->crypto_header.offset);
289 s->crypto_header.length = be64_to_cpu(s->crypto_header.length);
4652b8f3
DB
290
291 if ((s->crypto_header.offset % s->cluster_size) != 0) {
292 error_setg(errp, "Encryption header offset '%" PRIu64 "' is "
293 "not a multiple of cluster size '%u'",
294 s->crypto_header.offset, s->cluster_size);
295 return -EINVAL;
296 }
297
298 if (flags & BDRV_O_NO_IO) {
299 cflags |= QCRYPTO_BLOCK_OPEN_NO_IO;
300 }
1cd9a787 301 s->crypto = qcrypto_block_open(s->crypto_opts, "encrypt.",
4652b8f3 302 qcow2_crypto_hdr_read_func,
8ac0f15f 303 bs, cflags, QCOW2_MAX_THREADS, errp);
4652b8f3
DB
304 if (!s->crypto) {
305 return -EINVAL;
306 }
307 } break;
308
88ddffae
VSO
309 case QCOW2_EXT_MAGIC_BITMAPS:
310 if (ext.len != sizeof(bitmaps_ext)) {
311 error_setg_errno(errp, -ret, "bitmaps_ext: "
312 "Invalid extension length");
313 return -EINVAL;
314 }
315
316 if (!(s->autoclear_features & QCOW2_AUTOCLEAR_BITMAPS)) {
c9ceb3ec
HR
317 if (s->qcow_version < 3) {
318 /* Let's be a bit more specific */
319 warn_report("This qcow2 v2 image contains bitmaps, but "
320 "they may have been modified by a program "
321 "without persistent bitmap support; so now "
322 "they must all be considered inconsistent");
323 } else {
324 warn_report("a program lacking bitmap support "
325 "modified this file, so all bitmaps are now "
326 "considered inconsistent");
327 }
55d527a9
AF
328 error_printf("Some clusters may be leaked, "
329 "run 'qemu-img check -r' on the image "
88ddffae
VSO
330 "file to fix.");
331 if (need_update_header != NULL) {
332 /* Updating is needed to drop invalid bitmap extension. */
333 *need_update_header = true;
334 }
335 break;
336 }
337
338 ret = bdrv_pread(bs->file, offset, &bitmaps_ext, ext.len);
339 if (ret < 0) {
340 error_setg_errno(errp, -ret, "bitmaps_ext: "
341 "Could not read ext header");
342 return ret;
343 }
344
345 if (bitmaps_ext.reserved32 != 0) {
346 error_setg_errno(errp, -ret, "bitmaps_ext: "
347 "Reserved field is not zero");
348 return -EINVAL;
349 }
350
3b698f52
PM
351 bitmaps_ext.nb_bitmaps = be32_to_cpu(bitmaps_ext.nb_bitmaps);
352 bitmaps_ext.bitmap_directory_size =
353 be64_to_cpu(bitmaps_ext.bitmap_directory_size);
354 bitmaps_ext.bitmap_directory_offset =
355 be64_to_cpu(bitmaps_ext.bitmap_directory_offset);
88ddffae
VSO
356
357 if (bitmaps_ext.nb_bitmaps > QCOW2_MAX_BITMAPS) {
358 error_setg(errp,
359 "bitmaps_ext: Image has %" PRIu32 " bitmaps, "
360 "exceeding the QEMU supported maximum of %d",
361 bitmaps_ext.nb_bitmaps, QCOW2_MAX_BITMAPS);
362 return -EINVAL;
363 }
364
365 if (bitmaps_ext.nb_bitmaps == 0) {
366 error_setg(errp, "found bitmaps extension with zero bitmaps");
367 return -EINVAL;
368 }
369
370 if (bitmaps_ext.bitmap_directory_offset & (s->cluster_size - 1)) {
371 error_setg(errp, "bitmaps_ext: "
372 "invalid bitmap directory offset");
373 return -EINVAL;
374 }
375
376 if (bitmaps_ext.bitmap_directory_size >
377 QCOW2_MAX_BITMAP_DIRECTORY_SIZE) {
378 error_setg(errp, "bitmaps_ext: "
379 "bitmap directory size (%" PRIu64 ") exceeds "
380 "the maximum supported size (%d)",
381 bitmaps_ext.bitmap_directory_size,
382 QCOW2_MAX_BITMAP_DIRECTORY_SIZE);
383 return -EINVAL;
384 }
385
386 s->nb_bitmaps = bitmaps_ext.nb_bitmaps;
387 s->bitmap_directory_offset =
388 bitmaps_ext.bitmap_directory_offset;
389 s->bitmap_directory_size =
390 bitmaps_ext.bitmap_directory_size;
391
392#ifdef DEBUG_EXT
393 printf("Qcow2: Got bitmaps extension: "
394 "offset=%" PRIu64 " nb_bitmaps=%" PRIu32 "\n",
395 s->bitmap_directory_offset, s->nb_bitmaps);
396#endif
397 break;
398
9b890bdc
KW
399 case QCOW2_EXT_MAGIC_DATA_FILE:
400 {
401 s->image_data_file = g_malloc0(ext.len + 1);
402 ret = bdrv_pread(bs->file, offset, s->image_data_file, ext.len);
403 if (ret < 0) {
404 error_setg_errno(errp, -ret,
405 "ERROR: Could not read data file name");
406 return ret;
407 }
408#ifdef DEBUG_EXT
409 printf("Qcow2: Got external data file %s\n", s->image_data_file);
410#endif
411 break;
412 }
413
9b80ddf3 414 default:
75bab85c 415 /* unknown magic - save it in case we need to rewrite the header */
4096974e
EB
416 /* If you add a new feature, make sure to also update the fast
417 * path of qcow2_make_empty() to deal with it. */
75bab85c
KW
418 {
419 Qcow2UnknownHeaderExtension *uext;
420
421 uext = g_malloc0(sizeof(*uext) + ext.len);
422 uext->magic = ext.magic;
423 uext->len = ext.len;
424 QLIST_INSERT_HEAD(&s->unknown_header_ext, uext, next);
425
cf2ab8fc 426 ret = bdrv_pread(bs->file, offset , uext->data, uext->len);
75bab85c 427 if (ret < 0) {
3ef6c40a
HR
428 error_setg_errno(errp, -ret, "ERROR: unknown extension: "
429 "Could not read data");
75bab85c
KW
430 return ret;
431 }
75bab85c 432 }
9b80ddf3
AL
433 break;
434 }
fd29b4bb
KW
435
436 offset += ((ext.len + 7) & ~7);
9b80ddf3
AL
437 }
438
439 return 0;
440}
441
75bab85c
KW
442static void cleanup_unknown_header_ext(BlockDriverState *bs)
443{
ff99129a 444 BDRVQcow2State *s = bs->opaque;
75bab85c
KW
445 Qcow2UnknownHeaderExtension *uext, *next;
446
447 QLIST_FOREACH_SAFE(uext, &s->unknown_header_ext, next, next) {
448 QLIST_REMOVE(uext, next);
449 g_free(uext);
450 }
451}
9b80ddf3 452
a55448b3
HR
453static void report_unsupported_feature(Error **errp, Qcow2Feature *table,
454 uint64_t mask)
cfcc4c62 455{
12ac6d3d
KW
456 char *features = g_strdup("");
457 char *old;
458
cfcc4c62
KW
459 while (table && table->name[0] != '\0') {
460 if (table->type == QCOW2_FEAT_TYPE_INCOMPATIBLE) {
12ac6d3d
KW
461 if (mask & (1ULL << table->bit)) {
462 old = features;
463 features = g_strdup_printf("%s%s%.46s", old, *old ? ", " : "",
464 table->name);
465 g_free(old);
466 mask &= ~(1ULL << table->bit);
cfcc4c62
KW
467 }
468 }
469 table++;
470 }
471
472 if (mask) {
12ac6d3d
KW
473 old = features;
474 features = g_strdup_printf("%s%sUnknown incompatible feature: %" PRIx64,
475 old, *old ? ", " : "", mask);
476 g_free(old);
cfcc4c62 477 }
12ac6d3d 478
a55448b3 479 error_setg(errp, "Unsupported qcow2 feature(s): %s", features);
12ac6d3d 480 g_free(features);
cfcc4c62
KW
481}
482
bfe8043e
SH
483/*
484 * Sets the dirty bit and flushes afterwards if necessary.
485 *
486 * The incompatible_features bit is only set if the image file header was
487 * updated successfully. Therefore it is not required to check the return
488 * value of this function.
489 */
280d3735 490int qcow2_mark_dirty(BlockDriverState *bs)
bfe8043e 491{
ff99129a 492 BDRVQcow2State *s = bs->opaque;
bfe8043e
SH
493 uint64_t val;
494 int ret;
495
496 assert(s->qcow_version >= 3);
497
498 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
499 return 0; /* already dirty */
500 }
501
502 val = cpu_to_be64(s->incompatible_features | QCOW2_INCOMPAT_DIRTY);
d9ca2ea2 503 ret = bdrv_pwrite(bs->file, offsetof(QCowHeader, incompatible_features),
bfe8043e
SH
504 &val, sizeof(val));
505 if (ret < 0) {
506 return ret;
507 }
9a4f4c31 508 ret = bdrv_flush(bs->file->bs);
bfe8043e
SH
509 if (ret < 0) {
510 return ret;
511 }
512
513 /* Only treat image as dirty if the header was updated successfully */
514 s->incompatible_features |= QCOW2_INCOMPAT_DIRTY;
515 return 0;
516}
517
c61d0004
SH
518/*
519 * Clears the dirty bit and flushes before if necessary. Only call this
520 * function when there are no pending requests, it does not guard against
521 * concurrent requests dirtying the image.
522 */
523static int qcow2_mark_clean(BlockDriverState *bs)
524{
ff99129a 525 BDRVQcow2State *s = bs->opaque;
c61d0004
SH
526
527 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
4c2e5f8f
KW
528 int ret;
529
530 s->incompatible_features &= ~QCOW2_INCOMPAT_DIRTY;
531
8b220eb7 532 ret = qcow2_flush_caches(bs);
c61d0004
SH
533 if (ret < 0) {
534 return ret;
535 }
536
c61d0004
SH
537 return qcow2_update_header(bs);
538 }
539 return 0;
540}
541
69c98726
HR
542/*
543 * Marks the image as corrupt.
544 */
545int qcow2_mark_corrupt(BlockDriverState *bs)
546{
ff99129a 547 BDRVQcow2State *s = bs->opaque;
69c98726
HR
548
549 s->incompatible_features |= QCOW2_INCOMPAT_CORRUPT;
550 return qcow2_update_header(bs);
551}
552
553/*
554 * Marks the image as consistent, i.e., unsets the corrupt bit, and flushes
555 * before if necessary.
556 */
557int qcow2_mark_consistent(BlockDriverState *bs)
558{
ff99129a 559 BDRVQcow2State *s = bs->opaque;
69c98726
HR
560
561 if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
8b220eb7 562 int ret = qcow2_flush_caches(bs);
69c98726
HR
563 if (ret < 0) {
564 return ret;
565 }
566
567 s->incompatible_features &= ~QCOW2_INCOMPAT_CORRUPT;
568 return qcow2_update_header(bs);
569 }
570 return 0;
571}
572
8bc584fe
HR
573static void qcow2_add_check_result(BdrvCheckResult *out,
574 const BdrvCheckResult *src,
575 bool set_allocation_info)
576{
577 out->corruptions += src->corruptions;
578 out->leaks += src->leaks;
579 out->check_errors += src->check_errors;
580 out->corruptions_fixed += src->corruptions_fixed;
581 out->leaks_fixed += src->leaks_fixed;
582
583 if (set_allocation_info) {
584 out->image_end_offset = src->image_end_offset;
585 out->bfi = src->bfi;
586 }
587}
588
2fd61638
PB
589static int coroutine_fn qcow2_co_check_locked(BlockDriverState *bs,
590 BdrvCheckResult *result,
591 BdrvCheckMode fix)
acbe5982 592{
8bc584fe
HR
593 BdrvCheckResult snapshot_res = {};
594 BdrvCheckResult refcount_res = {};
595 int ret;
596
597 memset(result, 0, sizeof(*result));
598
599 ret = qcow2_check_read_snapshot_table(bs, &snapshot_res, fix);
8bc584fe 600 if (ret < 0) {
fe446b5d 601 qcow2_add_check_result(result, &snapshot_res, false);
8bc584fe
HR
602 return ret;
603 }
604
605 ret = qcow2_check_refcounts(bs, &refcount_res, fix);
606 qcow2_add_check_result(result, &refcount_res, true);
fe446b5d
HR
607 if (ret < 0) {
608 qcow2_add_check_result(result, &snapshot_res, false);
609 return ret;
610 }
611
612 ret = qcow2_check_fix_snapshot_table(bs, &snapshot_res, fix);
613 qcow2_add_check_result(result, &snapshot_res, false);
acbe5982
SH
614 if (ret < 0) {
615 return ret;
616 }
617
618 if (fix && result->check_errors == 0 && result->corruptions == 0) {
24530f3e
HR
619 ret = qcow2_mark_clean(bs);
620 if (ret < 0) {
621 return ret;
622 }
623 return qcow2_mark_consistent(bs);
acbe5982
SH
624 }
625 return ret;
626}
627
2fd61638
PB
628static int coroutine_fn qcow2_co_check(BlockDriverState *bs,
629 BdrvCheckResult *result,
630 BdrvCheckMode fix)
631{
632 BDRVQcow2State *s = bs->opaque;
633 int ret;
634
635 qemu_co_mutex_lock(&s->lock);
636 ret = qcow2_co_check_locked(bs, result, fix);
637 qemu_co_mutex_unlock(&s->lock);
638 return ret;
639}
640
0cf0e598
AG
641int qcow2_validate_table(BlockDriverState *bs, uint64_t offset,
642 uint64_t entries, size_t entry_len,
643 int64_t max_size_bytes, const char *table_name,
644 Error **errp)
8c7de283 645{
ff99129a 646 BDRVQcow2State *s = bs->opaque;
8c7de283 647
0cf0e598
AG
648 if (entries > max_size_bytes / entry_len) {
649 error_setg(errp, "%s too large", table_name);
650 return -EFBIG;
8c7de283
KW
651 }
652
0cf0e598
AG
653 /* Use signed INT64_MAX as the maximum even for uint64_t header fields,
654 * because values will be passed to qemu functions taking int64_t. */
655 if ((INT64_MAX - entries * entry_len < offset) ||
656 (offset_into_cluster(s, offset) != 0)) {
657 error_setg(errp, "%s offset invalid", table_name);
8c7de283
KW
658 return -EINVAL;
659 }
660
661 return 0;
662}
663
8a2ce0bc
AG
664static const char *const mutable_opts[] = {
665 QCOW2_OPT_LAZY_REFCOUNTS,
666 QCOW2_OPT_DISCARD_REQUEST,
667 QCOW2_OPT_DISCARD_SNAPSHOT,
668 QCOW2_OPT_DISCARD_OTHER,
669 QCOW2_OPT_OVERLAP,
670 QCOW2_OPT_OVERLAP_TEMPLATE,
671 QCOW2_OPT_OVERLAP_MAIN_HEADER,
672 QCOW2_OPT_OVERLAP_ACTIVE_L1,
673 QCOW2_OPT_OVERLAP_ACTIVE_L2,
674 QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
675 QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
676 QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
677 QCOW2_OPT_OVERLAP_INACTIVE_L1,
678 QCOW2_OPT_OVERLAP_INACTIVE_L2,
679 QCOW2_OPT_OVERLAP_BITMAP_DIRECTORY,
680 QCOW2_OPT_CACHE_SIZE,
681 QCOW2_OPT_L2_CACHE_SIZE,
682 QCOW2_OPT_L2_CACHE_ENTRY_SIZE,
683 QCOW2_OPT_REFCOUNT_CACHE_SIZE,
684 QCOW2_OPT_CACHE_CLEAN_INTERVAL,
685 NULL
686};
687
74c4510a
KW
688static QemuOptsList qcow2_runtime_opts = {
689 .name = "qcow2",
690 .head = QTAILQ_HEAD_INITIALIZER(qcow2_runtime_opts.head),
691 .desc = {
692 {
64aa99d3 693 .name = QCOW2_OPT_LAZY_REFCOUNTS,
74c4510a
KW
694 .type = QEMU_OPT_BOOL,
695 .help = "Postpone refcount updates",
696 },
67af674e
KW
697 {
698 .name = QCOW2_OPT_DISCARD_REQUEST,
699 .type = QEMU_OPT_BOOL,
700 .help = "Pass guest discard requests to the layer below",
701 },
702 {
703 .name = QCOW2_OPT_DISCARD_SNAPSHOT,
704 .type = QEMU_OPT_BOOL,
705 .help = "Generate discard requests when snapshot related space "
706 "is freed",
707 },
708 {
709 .name = QCOW2_OPT_DISCARD_OTHER,
710 .type = QEMU_OPT_BOOL,
711 .help = "Generate discard requests when other clusters are freed",
712 },
05de7e86
HR
713 {
714 .name = QCOW2_OPT_OVERLAP,
715 .type = QEMU_OPT_STRING,
716 .help = "Selects which overlap checks to perform from a range of "
717 "templates (none, constant, cached, all)",
718 },
ee42b5ce
HR
719 {
720 .name = QCOW2_OPT_OVERLAP_TEMPLATE,
721 .type = QEMU_OPT_STRING,
722 .help = "Selects which overlap checks to perform from a range of "
723 "templates (none, constant, cached, all)",
724 },
05de7e86
HR
725 {
726 .name = QCOW2_OPT_OVERLAP_MAIN_HEADER,
727 .type = QEMU_OPT_BOOL,
728 .help = "Check for unintended writes into the main qcow2 header",
729 },
730 {
731 .name = QCOW2_OPT_OVERLAP_ACTIVE_L1,
732 .type = QEMU_OPT_BOOL,
733 .help = "Check for unintended writes into the active L1 table",
734 },
735 {
736 .name = QCOW2_OPT_OVERLAP_ACTIVE_L2,
737 .type = QEMU_OPT_BOOL,
738 .help = "Check for unintended writes into an active L2 table",
739 },
740 {
741 .name = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
742 .type = QEMU_OPT_BOOL,
743 .help = "Check for unintended writes into the refcount table",
744 },
745 {
746 .name = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
747 .type = QEMU_OPT_BOOL,
748 .help = "Check for unintended writes into a refcount block",
749 },
750 {
751 .name = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
752 .type = QEMU_OPT_BOOL,
753 .help = "Check for unintended writes into the snapshot table",
754 },
755 {
756 .name = QCOW2_OPT_OVERLAP_INACTIVE_L1,
757 .type = QEMU_OPT_BOOL,
758 .help = "Check for unintended writes into an inactive L1 table",
759 },
760 {
761 .name = QCOW2_OPT_OVERLAP_INACTIVE_L2,
762 .type = QEMU_OPT_BOOL,
763 .help = "Check for unintended writes into an inactive L2 table",
764 },
0e4e4318
VSO
765 {
766 .name = QCOW2_OPT_OVERLAP_BITMAP_DIRECTORY,
767 .type = QEMU_OPT_BOOL,
768 .help = "Check for unintended writes into the bitmap directory",
769 },
6c1c8d5d
HR
770 {
771 .name = QCOW2_OPT_CACHE_SIZE,
772 .type = QEMU_OPT_SIZE,
773 .help = "Maximum combined metadata (L2 tables and refcount blocks) "
774 "cache size",
775 },
776 {
777 .name = QCOW2_OPT_L2_CACHE_SIZE,
778 .type = QEMU_OPT_SIZE,
779 .help = "Maximum L2 table cache size",
780 },
1221fe6f
AG
781 {
782 .name = QCOW2_OPT_L2_CACHE_ENTRY_SIZE,
783 .type = QEMU_OPT_SIZE,
784 .help = "Size of each entry in the L2 cache",
785 },
6c1c8d5d
HR
786 {
787 .name = QCOW2_OPT_REFCOUNT_CACHE_SIZE,
788 .type = QEMU_OPT_SIZE,
789 .help = "Maximum refcount block cache size",
790 },
279621c0
AG
791 {
792 .name = QCOW2_OPT_CACHE_CLEAN_INTERVAL,
793 .type = QEMU_OPT_NUMBER,
794 .help = "Clean unused cache entries after this time (in seconds)",
795 },
4652b8f3
DB
796 BLOCK_CRYPTO_OPT_DEF_KEY_SECRET("encrypt.",
797 "ID of secret providing qcow2 AES key or LUKS passphrase"),
74c4510a
KW
798 { /* end of list */ }
799 },
800};
801
4092e99d 802static const char *overlap_bool_option_names[QCOW2_OL_MAX_BITNR] = {
0e4e4318
VSO
803 [QCOW2_OL_MAIN_HEADER_BITNR] = QCOW2_OPT_OVERLAP_MAIN_HEADER,
804 [QCOW2_OL_ACTIVE_L1_BITNR] = QCOW2_OPT_OVERLAP_ACTIVE_L1,
805 [QCOW2_OL_ACTIVE_L2_BITNR] = QCOW2_OPT_OVERLAP_ACTIVE_L2,
806 [QCOW2_OL_REFCOUNT_TABLE_BITNR] = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
807 [QCOW2_OL_REFCOUNT_BLOCK_BITNR] = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
808 [QCOW2_OL_SNAPSHOT_TABLE_BITNR] = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
809 [QCOW2_OL_INACTIVE_L1_BITNR] = QCOW2_OPT_OVERLAP_INACTIVE_L1,
810 [QCOW2_OL_INACTIVE_L2_BITNR] = QCOW2_OPT_OVERLAP_INACTIVE_L2,
811 [QCOW2_OL_BITMAP_DIRECTORY_BITNR] = QCOW2_OPT_OVERLAP_BITMAP_DIRECTORY,
4092e99d
HR
812};
813
279621c0
AG
814static void cache_clean_timer_cb(void *opaque)
815{
816 BlockDriverState *bs = opaque;
ff99129a 817 BDRVQcow2State *s = bs->opaque;
b2f68bff
AG
818 qcow2_cache_clean_unused(s->l2_table_cache);
819 qcow2_cache_clean_unused(s->refcount_block_cache);
279621c0
AG
820 timer_mod(s->cache_clean_timer, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) +
821 (int64_t) s->cache_clean_interval * 1000);
822}
823
824static void cache_clean_timer_init(BlockDriverState *bs, AioContext *context)
825{
ff99129a 826 BDRVQcow2State *s = bs->opaque;
279621c0
AG
827 if (s->cache_clean_interval > 0) {
828 s->cache_clean_timer = aio_timer_new(context, QEMU_CLOCK_VIRTUAL,
829 SCALE_MS, cache_clean_timer_cb,
830 bs);
831 timer_mod(s->cache_clean_timer, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) +
832 (int64_t) s->cache_clean_interval * 1000);
833 }
834}
835
836static void cache_clean_timer_del(BlockDriverState *bs)
837{
ff99129a 838 BDRVQcow2State *s = bs->opaque;
279621c0
AG
839 if (s->cache_clean_timer) {
840 timer_del(s->cache_clean_timer);
841 timer_free(s->cache_clean_timer);
842 s->cache_clean_timer = NULL;
843 }
844}
845
846static void qcow2_detach_aio_context(BlockDriverState *bs)
847{
848 cache_clean_timer_del(bs);
849}
850
851static void qcow2_attach_aio_context(BlockDriverState *bs,
852 AioContext *new_context)
853{
854 cache_clean_timer_init(bs, new_context);
855}
856
bc85ef26
HR
857static void read_cache_sizes(BlockDriverState *bs, QemuOpts *opts,
858 uint64_t *l2_cache_size,
1221fe6f 859 uint64_t *l2_cache_entry_size,
6c1c8d5d
HR
860 uint64_t *refcount_cache_size, Error **errp)
861{
ff99129a 862 BDRVQcow2State *s = bs->opaque;
b749562d 863 uint64_t combined_cache_size, l2_cache_max_setting;
6c1c8d5d 864 bool l2_cache_size_set, refcount_cache_size_set, combined_cache_size_set;
af39bd0d 865 bool l2_cache_entry_size_set;
7af5eea9 866 int min_refcount_cache = MIN_REFCOUNT_CACHE_SIZE * s->cluster_size;
b749562d 867 uint64_t virtual_disk_size = bs->total_sectors * BDRV_SECTOR_SIZE;
b70d0820
AG
868 uint64_t max_l2_entries = DIV_ROUND_UP(virtual_disk_size, s->cluster_size);
869 /* An L2 table is always one cluster in size so the max cache size
870 * should be a multiple of the cluster size. */
871 uint64_t max_l2_cache = ROUND_UP(max_l2_entries * sizeof(uint64_t),
872 s->cluster_size);
6c1c8d5d
HR
873
874 combined_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_CACHE_SIZE);
875 l2_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_L2_CACHE_SIZE);
876 refcount_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
af39bd0d 877 l2_cache_entry_size_set = qemu_opt_get(opts, QCOW2_OPT_L2_CACHE_ENTRY_SIZE);
6c1c8d5d
HR
878
879 combined_cache_size = qemu_opt_get_size(opts, QCOW2_OPT_CACHE_SIZE, 0);
b749562d
LB
880 l2_cache_max_setting = qemu_opt_get_size(opts, QCOW2_OPT_L2_CACHE_SIZE,
881 DEFAULT_L2_CACHE_MAX_SIZE);
6c1c8d5d
HR
882 *refcount_cache_size = qemu_opt_get_size(opts,
883 QCOW2_OPT_REFCOUNT_CACHE_SIZE, 0);
884
1221fe6f
AG
885 *l2_cache_entry_size = qemu_opt_get_size(
886 opts, QCOW2_OPT_L2_CACHE_ENTRY_SIZE, s->cluster_size);
887
b749562d
LB
888 *l2_cache_size = MIN(max_l2_cache, l2_cache_max_setting);
889
6c1c8d5d
HR
890 if (combined_cache_size_set) {
891 if (l2_cache_size_set && refcount_cache_size_set) {
892 error_setg(errp, QCOW2_OPT_CACHE_SIZE ", " QCOW2_OPT_L2_CACHE_SIZE
893 " and " QCOW2_OPT_REFCOUNT_CACHE_SIZE " may not be set "
308999e9 894 "at the same time");
6c1c8d5d 895 return;
b749562d
LB
896 } else if (l2_cache_size_set &&
897 (l2_cache_max_setting > combined_cache_size)) {
6c1c8d5d
HR
898 error_setg(errp, QCOW2_OPT_L2_CACHE_SIZE " may not exceed "
899 QCOW2_OPT_CACHE_SIZE);
900 return;
901 } else if (*refcount_cache_size > combined_cache_size) {
902 error_setg(errp, QCOW2_OPT_REFCOUNT_CACHE_SIZE " may not exceed "
903 QCOW2_OPT_CACHE_SIZE);
904 return;
905 }
906
907 if (l2_cache_size_set) {
908 *refcount_cache_size = combined_cache_size - *l2_cache_size;
909 } else if (refcount_cache_size_set) {
910 *l2_cache_size = combined_cache_size - *refcount_cache_size;
911 } else {
52253998
AG
912 /* Assign as much memory as possible to the L2 cache, and
913 * use the remainder for the refcount cache */
914 if (combined_cache_size >= max_l2_cache + min_refcount_cache) {
915 *l2_cache_size = max_l2_cache;
916 *refcount_cache_size = combined_cache_size - *l2_cache_size;
917 } else {
918 *refcount_cache_size =
919 MIN(combined_cache_size, min_refcount_cache);
920 *l2_cache_size = combined_cache_size - *refcount_cache_size;
921 }
6c1c8d5d 922 }
6c1c8d5d 923 }
af39bd0d
AG
924
925 /*
926 * If the L2 cache is not enough to cover the whole disk then
927 * default to 4KB entries. Smaller entries reduce the cost of
928 * loads and evictions and increase I/O performance.
929 */
930 if (*l2_cache_size < max_l2_cache && !l2_cache_entry_size_set) {
931 *l2_cache_entry_size = MIN(s->cluster_size, 4096);
932 }
933
657ada52
LB
934 /* l2_cache_size and refcount_cache_size are ensured to have at least
935 * their minimum values in qcow2_update_options_prepare() */
1221fe6f
AG
936
937 if (*l2_cache_entry_size < (1 << MIN_CLUSTER_BITS) ||
938 *l2_cache_entry_size > s->cluster_size ||
939 !is_power_of_2(*l2_cache_entry_size)) {
940 error_setg(errp, "L2 cache entry size must be a power of two "
941 "between %d and the cluster size (%d)",
942 1 << MIN_CLUSTER_BITS, s->cluster_size);
943 return;
944 }
6c1c8d5d
HR
945}
946
ee55b173
KW
947typedef struct Qcow2ReopenState {
948 Qcow2Cache *l2_table_cache;
949 Qcow2Cache *refcount_block_cache;
3c2e511a 950 int l2_slice_size; /* Number of entries in a slice of the L2 table */
ee55b173
KW
951 bool use_lazy_refcounts;
952 int overlap_check;
953 bool discard_passthrough[QCOW2_DISCARD_MAX];
954 uint64_t cache_clean_interval;
b25b387f 955 QCryptoBlockOpenOptions *crypto_opts; /* Disk encryption runtime options */
ee55b173
KW
956} Qcow2ReopenState;
957
958static int qcow2_update_options_prepare(BlockDriverState *bs,
959 Qcow2ReopenState *r,
960 QDict *options, int flags,
961 Error **errp)
4c75d1a1
KW
962{
963 BDRVQcow2State *s = bs->opaque;
94edf3fb 964 QemuOpts *opts = NULL;
4c75d1a1
KW
965 const char *opt_overlap_check, *opt_overlap_check_template;
966 int overlap_check_template = 0;
1221fe6f 967 uint64_t l2_cache_size, l2_cache_entry_size, refcount_cache_size;
4c75d1a1 968 int i;
b25b387f
DB
969 const char *encryptfmt;
970 QDict *encryptopts = NULL;
94edf3fb 971 Error *local_err = NULL;
4c75d1a1
KW
972 int ret;
973
b25b387f
DB
974 qdict_extract_subqdict(options, &encryptopts, "encrypt.");
975 encryptfmt = qdict_get_try_str(encryptopts, "format");
976
94edf3fb
KW
977 opts = qemu_opts_create(&qcow2_runtime_opts, NULL, 0, &error_abort);
978 qemu_opts_absorb_qdict(opts, options, &local_err);
979 if (local_err) {
980 error_propagate(errp, local_err);
981 ret = -EINVAL;
982 goto fail;
983 }
984
985 /* get L2 table/refcount block cache size from command line options */
1221fe6f
AG
986 read_cache_sizes(bs, opts, &l2_cache_size, &l2_cache_entry_size,
987 &refcount_cache_size, &local_err);
94edf3fb
KW
988 if (local_err) {
989 error_propagate(errp, local_err);
990 ret = -EINVAL;
991 goto fail;
992 }
993
1221fe6f 994 l2_cache_size /= l2_cache_entry_size;
94edf3fb
KW
995 if (l2_cache_size < MIN_L2_CACHE_SIZE) {
996 l2_cache_size = MIN_L2_CACHE_SIZE;
997 }
998 if (l2_cache_size > INT_MAX) {
999 error_setg(errp, "L2 cache size too big");
1000 ret = -EINVAL;
1001 goto fail;
1002 }
1003
1004 refcount_cache_size /= s->cluster_size;
1005 if (refcount_cache_size < MIN_REFCOUNT_CACHE_SIZE) {
1006 refcount_cache_size = MIN_REFCOUNT_CACHE_SIZE;
1007 }
1008 if (refcount_cache_size > INT_MAX) {
1009 error_setg(errp, "Refcount cache size too big");
1010 ret = -EINVAL;
1011 goto fail;
1012 }
1013
5b0959a7
KW
1014 /* alloc new L2 table/refcount block cache, flush old one */
1015 if (s->l2_table_cache) {
1016 ret = qcow2_cache_flush(bs, s->l2_table_cache);
1017 if (ret) {
1018 error_setg_errno(errp, -ret, "Failed to flush the L2 table cache");
1019 goto fail;
1020 }
1021 }
1022
1023 if (s->refcount_block_cache) {
1024 ret = qcow2_cache_flush(bs, s->refcount_block_cache);
1025 if (ret) {
1026 error_setg_errno(errp, -ret,
1027 "Failed to flush the refcount block cache");
1028 goto fail;
1029 }
1030 }
1031
1221fe6f
AG
1032 r->l2_slice_size = l2_cache_entry_size / sizeof(uint64_t);
1033 r->l2_table_cache = qcow2_cache_create(bs, l2_cache_size,
1034 l2_cache_entry_size);
1035 r->refcount_block_cache = qcow2_cache_create(bs, refcount_cache_size,
1036 s->cluster_size);
ee55b173 1037 if (r->l2_table_cache == NULL || r->refcount_block_cache == NULL) {
94edf3fb
KW
1038 error_setg(errp, "Could not allocate metadata caches");
1039 ret = -ENOMEM;
1040 goto fail;
1041 }
1042
1043 /* New interval for cache cleanup timer */
ee55b173 1044 r->cache_clean_interval =
5b0959a7 1045 qemu_opt_get_number(opts, QCOW2_OPT_CACHE_CLEAN_INTERVAL,
e957b50b 1046 DEFAULT_CACHE_CLEAN_INTERVAL);
91203f08
AG
1047#ifndef CONFIG_LINUX
1048 if (r->cache_clean_interval != 0) {
1049 error_setg(errp, QCOW2_OPT_CACHE_CLEAN_INTERVAL
1050 " not supported on this host");
1051 ret = -EINVAL;
1052 goto fail;
1053 }
1054#endif
ee55b173 1055 if (r->cache_clean_interval > UINT_MAX) {
94edf3fb
KW
1056 error_setg(errp, "Cache clean interval too big");
1057 ret = -EINVAL;
1058 goto fail;
1059 }
94edf3fb 1060
5b0959a7 1061 /* lazy-refcounts; flush if going from enabled to disabled */
ee55b173 1062 r->use_lazy_refcounts = qemu_opt_get_bool(opts, QCOW2_OPT_LAZY_REFCOUNTS,
4c75d1a1 1063 (s->compatible_features & QCOW2_COMPAT_LAZY_REFCOUNTS));
ee55b173 1064 if (r->use_lazy_refcounts && s->qcow_version < 3) {
007dbc39
KW
1065 error_setg(errp, "Lazy refcounts require a qcow2 image with at least "
1066 "qemu 1.1 compatibility level");
1067 ret = -EINVAL;
1068 goto fail;
1069 }
4c75d1a1 1070
5b0959a7
KW
1071 if (s->use_lazy_refcounts && !r->use_lazy_refcounts) {
1072 ret = qcow2_mark_clean(bs);
1073 if (ret < 0) {
1074 error_setg_errno(errp, -ret, "Failed to disable lazy refcounts");
1075 goto fail;
1076 }
1077 }
1078
007dbc39 1079 /* Overlap check options */
4c75d1a1
KW
1080 opt_overlap_check = qemu_opt_get(opts, QCOW2_OPT_OVERLAP);
1081 opt_overlap_check_template = qemu_opt_get(opts, QCOW2_OPT_OVERLAP_TEMPLATE);
1082 if (opt_overlap_check_template && opt_overlap_check &&
1083 strcmp(opt_overlap_check_template, opt_overlap_check))
1084 {
1085 error_setg(errp, "Conflicting values for qcow2 options '"
1086 QCOW2_OPT_OVERLAP "' ('%s') and '" QCOW2_OPT_OVERLAP_TEMPLATE
1087 "' ('%s')", opt_overlap_check, opt_overlap_check_template);
1088 ret = -EINVAL;
1089 goto fail;
1090 }
1091 if (!opt_overlap_check) {
1092 opt_overlap_check = opt_overlap_check_template ?: "cached";
1093 }
1094
1095 if (!strcmp(opt_overlap_check, "none")) {
1096 overlap_check_template = 0;
1097 } else if (!strcmp(opt_overlap_check, "constant")) {
1098 overlap_check_template = QCOW2_OL_CONSTANT;
1099 } else if (!strcmp(opt_overlap_check, "cached")) {
1100 overlap_check_template = QCOW2_OL_CACHED;
1101 } else if (!strcmp(opt_overlap_check, "all")) {
1102 overlap_check_template = QCOW2_OL_ALL;
1103 } else {
1104 error_setg(errp, "Unsupported value '%s' for qcow2 option "
1105 "'overlap-check'. Allowed are any of the following: "
1106 "none, constant, cached, all", opt_overlap_check);
1107 ret = -EINVAL;
1108 goto fail;
1109 }
1110
ee55b173 1111 r->overlap_check = 0;
4c75d1a1
KW
1112 for (i = 0; i < QCOW2_OL_MAX_BITNR; i++) {
1113 /* overlap-check defines a template bitmask, but every flag may be
1114 * overwritten through the associated boolean option */
ee55b173 1115 r->overlap_check |=
4c75d1a1
KW
1116 qemu_opt_get_bool(opts, overlap_bool_option_names[i],
1117 overlap_check_template & (1 << i)) << i;
1118 }
1119
ee55b173
KW
1120 r->discard_passthrough[QCOW2_DISCARD_NEVER] = false;
1121 r->discard_passthrough[QCOW2_DISCARD_ALWAYS] = true;
1122 r->discard_passthrough[QCOW2_DISCARD_REQUEST] =
007dbc39
KW
1123 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_REQUEST,
1124 flags & BDRV_O_UNMAP);
ee55b173 1125 r->discard_passthrough[QCOW2_DISCARD_SNAPSHOT] =
007dbc39 1126 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_SNAPSHOT, true);
ee55b173 1127 r->discard_passthrough[QCOW2_DISCARD_OTHER] =
007dbc39
KW
1128 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_OTHER, false);
1129
b25b387f
DB
1130 switch (s->crypt_method_header) {
1131 case QCOW_CRYPT_NONE:
1132 if (encryptfmt) {
1133 error_setg(errp, "No encryption in image header, but options "
1134 "specified format '%s'", encryptfmt);
1135 ret = -EINVAL;
1136 goto fail;
1137 }
1138 break;
1139
1140 case QCOW_CRYPT_AES:
1141 if (encryptfmt && !g_str_equal(encryptfmt, "aes")) {
1142 error_setg(errp,
1143 "Header reported 'aes' encryption format but "
1144 "options specify '%s'", encryptfmt);
1145 ret = -EINVAL;
1146 goto fail;
1147 }
796d3239
MA
1148 qdict_put_str(encryptopts, "format", "qcow");
1149 r->crypto_opts = block_crypto_open_opts_init(encryptopts, errp);
b25b387f
DB
1150 break;
1151
4652b8f3
DB
1152 case QCOW_CRYPT_LUKS:
1153 if (encryptfmt && !g_str_equal(encryptfmt, "luks")) {
1154 error_setg(errp,
1155 "Header reported 'luks' encryption format but "
1156 "options specify '%s'", encryptfmt);
1157 ret = -EINVAL;
1158 goto fail;
1159 }
796d3239
MA
1160 qdict_put_str(encryptopts, "format", "luks");
1161 r->crypto_opts = block_crypto_open_opts_init(encryptopts, errp);
4652b8f3
DB
1162 break;
1163
b25b387f
DB
1164 default:
1165 error_setg(errp, "Unsupported encryption method %d",
1166 s->crypt_method_header);
1167 break;
1168 }
1169 if (s->crypt_method_header != QCOW_CRYPT_NONE && !r->crypto_opts) {
1170 ret = -EINVAL;
1171 goto fail;
1172 }
1173
4c75d1a1
KW
1174 ret = 0;
1175fail:
cb3e7f08 1176 qobject_unref(encryptopts);
94edf3fb
KW
1177 qemu_opts_del(opts);
1178 opts = NULL;
ee55b173
KW
1179 return ret;
1180}
1181
1182static void qcow2_update_options_commit(BlockDriverState *bs,
1183 Qcow2ReopenState *r)
1184{
1185 BDRVQcow2State *s = bs->opaque;
1186 int i;
1187
5b0959a7 1188 if (s->l2_table_cache) {
e64d4072 1189 qcow2_cache_destroy(s->l2_table_cache);
5b0959a7
KW
1190 }
1191 if (s->refcount_block_cache) {
e64d4072 1192 qcow2_cache_destroy(s->refcount_block_cache);
5b0959a7 1193 }
ee55b173
KW
1194 s->l2_table_cache = r->l2_table_cache;
1195 s->refcount_block_cache = r->refcount_block_cache;
3c2e511a 1196 s->l2_slice_size = r->l2_slice_size;
ee55b173
KW
1197
1198 s->overlap_check = r->overlap_check;
1199 s->use_lazy_refcounts = r->use_lazy_refcounts;
1200
1201 for (i = 0; i < QCOW2_DISCARD_MAX; i++) {
1202 s->discard_passthrough[i] = r->discard_passthrough[i];
1203 }
1204
5b0959a7
KW
1205 if (s->cache_clean_interval != r->cache_clean_interval) {
1206 cache_clean_timer_del(bs);
1207 s->cache_clean_interval = r->cache_clean_interval;
1208 cache_clean_timer_init(bs, bdrv_get_aio_context(bs));
1209 }
b25b387f
DB
1210
1211 qapi_free_QCryptoBlockOpenOptions(s->crypto_opts);
1212 s->crypto_opts = r->crypto_opts;
ee55b173
KW
1213}
1214
1215static void qcow2_update_options_abort(BlockDriverState *bs,
1216 Qcow2ReopenState *r)
1217{
1218 if (r->l2_table_cache) {
e64d4072 1219 qcow2_cache_destroy(r->l2_table_cache);
ee55b173
KW
1220 }
1221 if (r->refcount_block_cache) {
e64d4072 1222 qcow2_cache_destroy(r->refcount_block_cache);
ee55b173 1223 }
b25b387f 1224 qapi_free_QCryptoBlockOpenOptions(r->crypto_opts);
ee55b173
KW
1225}
1226
1227static int qcow2_update_options(BlockDriverState *bs, QDict *options,
1228 int flags, Error **errp)
1229{
1230 Qcow2ReopenState r = {};
1231 int ret;
1232
1233 ret = qcow2_update_options_prepare(bs, &r, options, flags, errp);
1234 if (ret >= 0) {
1235 qcow2_update_options_commit(bs, &r);
1236 } else {
1237 qcow2_update_options_abort(bs, &r);
1238 }
94edf3fb 1239
4c75d1a1
KW
1240 return ret;
1241}
1242
1fafcd93
PB
1243/* Called with s->lock held. */
1244static int coroutine_fn qcow2_do_open(BlockDriverState *bs, QDict *options,
1245 int flags, Error **errp)
585f8587 1246{
ff99129a 1247 BDRVQcow2State *s = bs->opaque;
6d33e8e7
KW
1248 unsigned int len, i;
1249 int ret = 0;
585f8587 1250 QCowHeader header;
74c4510a 1251 Error *local_err = NULL;
9b80ddf3 1252 uint64_t ext_end;
2cf7cfa1 1253 uint64_t l1_vm_state_index;
88ddffae 1254 bool update_header = false;
585f8587 1255
cf2ab8fc 1256 ret = bdrv_pread(bs->file, 0, &header, sizeof(header));
6d85a57e 1257 if (ret < 0) {
3ef6c40a 1258 error_setg_errno(errp, -ret, "Could not read qcow2 header");
585f8587 1259 goto fail;
6d85a57e 1260 }
3b698f52
PM
1261 header.magic = be32_to_cpu(header.magic);
1262 header.version = be32_to_cpu(header.version);
1263 header.backing_file_offset = be64_to_cpu(header.backing_file_offset);
1264 header.backing_file_size = be32_to_cpu(header.backing_file_size);
1265 header.size = be64_to_cpu(header.size);
1266 header.cluster_bits = be32_to_cpu(header.cluster_bits);
1267 header.crypt_method = be32_to_cpu(header.crypt_method);
1268 header.l1_table_offset = be64_to_cpu(header.l1_table_offset);
1269 header.l1_size = be32_to_cpu(header.l1_size);
1270 header.refcount_table_offset = be64_to_cpu(header.refcount_table_offset);
1271 header.refcount_table_clusters =
1272 be32_to_cpu(header.refcount_table_clusters);
1273 header.snapshots_offset = be64_to_cpu(header.snapshots_offset);
1274 header.nb_snapshots = be32_to_cpu(header.nb_snapshots);
3b46e624 1275
e8cdcec1 1276 if (header.magic != QCOW_MAGIC) {
3ef6c40a 1277 error_setg(errp, "Image is not in qcow2 format");
76abe407 1278 ret = -EINVAL;
585f8587 1279 goto fail;
6d85a57e 1280 }
6744cbab 1281 if (header.version < 2 || header.version > 3) {
a55448b3 1282 error_setg(errp, "Unsupported qcow2 version %" PRIu32, header.version);
6744cbab
KW
1283 ret = -ENOTSUP;
1284 goto fail;
1285 }
1286
1287 s->qcow_version = header.version;
1288
24342f2c
KW
1289 /* Initialise cluster size */
1290 if (header.cluster_bits < MIN_CLUSTER_BITS ||
1291 header.cluster_bits > MAX_CLUSTER_BITS) {
521b2b5d
HR
1292 error_setg(errp, "Unsupported cluster size: 2^%" PRIu32,
1293 header.cluster_bits);
24342f2c
KW
1294 ret = -EINVAL;
1295 goto fail;
1296 }
1297
1298 s->cluster_bits = header.cluster_bits;
1299 s->cluster_size = 1 << s->cluster_bits;
24342f2c 1300
6744cbab
KW
1301 /* Initialise version 3 header fields */
1302 if (header.version == 2) {
1303 header.incompatible_features = 0;
1304 header.compatible_features = 0;
1305 header.autoclear_features = 0;
1306 header.refcount_order = 4;
1307 header.header_length = 72;
1308 } else {
3b698f52
PM
1309 header.incompatible_features =
1310 be64_to_cpu(header.incompatible_features);
1311 header.compatible_features = be64_to_cpu(header.compatible_features);
1312 header.autoclear_features = be64_to_cpu(header.autoclear_features);
1313 header.refcount_order = be32_to_cpu(header.refcount_order);
1314 header.header_length = be32_to_cpu(header.header_length);
24342f2c
KW
1315
1316 if (header.header_length < 104) {
1317 error_setg(errp, "qcow2 header too short");
1318 ret = -EINVAL;
1319 goto fail;
1320 }
1321 }
1322
1323 if (header.header_length > s->cluster_size) {
1324 error_setg(errp, "qcow2 header exceeds cluster size");
1325 ret = -EINVAL;
1326 goto fail;
6744cbab
KW
1327 }
1328
1329 if (header.header_length > sizeof(header)) {
1330 s->unknown_header_fields_size = header.header_length - sizeof(header);
1331 s->unknown_header_fields = g_malloc(s->unknown_header_fields_size);
cf2ab8fc 1332 ret = bdrv_pread(bs->file, sizeof(header), s->unknown_header_fields,
6744cbab
KW
1333 s->unknown_header_fields_size);
1334 if (ret < 0) {
3ef6c40a
HR
1335 error_setg_errno(errp, -ret, "Could not read unknown qcow2 header "
1336 "fields");
6744cbab
KW
1337 goto fail;
1338 }
1339 }
1340
a1b3955c
KW
1341 if (header.backing_file_offset > s->cluster_size) {
1342 error_setg(errp, "Invalid backing file offset");
1343 ret = -EINVAL;
1344 goto fail;
1345 }
1346
cfcc4c62
KW
1347 if (header.backing_file_offset) {
1348 ext_end = header.backing_file_offset;
1349 } else {
1350 ext_end = 1 << header.cluster_bits;
1351 }
1352
6744cbab
KW
1353 /* Handle feature bits */
1354 s->incompatible_features = header.incompatible_features;
1355 s->compatible_features = header.compatible_features;
1356 s->autoclear_features = header.autoclear_features;
1357
c61d0004 1358 if (s->incompatible_features & ~QCOW2_INCOMPAT_MASK) {
cfcc4c62
KW
1359 void *feature_table = NULL;
1360 qcow2_read_extensions(bs, header.header_length, ext_end,
88ddffae 1361 &feature_table, flags, NULL, NULL);
a55448b3 1362 report_unsupported_feature(errp, feature_table,
c61d0004
SH
1363 s->incompatible_features &
1364 ~QCOW2_INCOMPAT_MASK);
6744cbab 1365 ret = -ENOTSUP;
c5a33ee9 1366 g_free(feature_table);
6744cbab
KW
1367 goto fail;
1368 }
1369
69c98726
HR
1370 if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
1371 /* Corrupt images may not be written to unless they are being repaired
1372 */
1373 if ((flags & BDRV_O_RDWR) && !(flags & BDRV_O_CHECK)) {
3ef6c40a
HR
1374 error_setg(errp, "qcow2: Image is corrupt; cannot be opened "
1375 "read/write");
69c98726
HR
1376 ret = -EACCES;
1377 goto fail;
1378 }
1379 }
1380
6744cbab 1381 /* Check support for various header values */
b72faf9f
HR
1382 if (header.refcount_order > 6) {
1383 error_setg(errp, "Reference count entry width too large; may not "
1384 "exceed 64 bits");
1385 ret = -EINVAL;
e8cdcec1
KW
1386 goto fail;
1387 }
b6481f37 1388 s->refcount_order = header.refcount_order;
346a53df
HR
1389 s->refcount_bits = 1 << s->refcount_order;
1390 s->refcount_max = UINT64_C(1) << (s->refcount_bits - 1);
1391 s->refcount_max += s->refcount_max - 1;
6744cbab 1392
585f8587 1393 s->crypt_method_header = header.crypt_method;
6d85a57e 1394 if (s->crypt_method_header) {
e6ff69bf
DB
1395 if (bdrv_uses_whitelist() &&
1396 s->crypt_method_header == QCOW_CRYPT_AES) {
8c0dcbc4
DB
1397 error_setg(errp,
1398 "Use of AES-CBC encrypted qcow2 images is no longer "
1399 "supported in system emulators");
1400 error_append_hint(errp,
1401 "You can use 'qemu-img convert' to convert your "
1402 "image to an alternative supported format, such "
1403 "as unencrypted qcow2, or raw with the LUKS "
1404 "format instead.\n");
1405 ret = -ENOSYS;
1406 goto fail;
e6ff69bf
DB
1407 }
1408
4652b8f3
DB
1409 if (s->crypt_method_header == QCOW_CRYPT_AES) {
1410 s->crypt_physical_offset = false;
1411 } else {
1412 /* Assuming LUKS and any future crypt methods we
1413 * add will all use physical offsets, due to the
1414 * fact that the alternative is insecure... */
1415 s->crypt_physical_offset = true;
1416 }
1417
54115412 1418 bs->encrypted = true;
6d85a57e 1419 }
24342f2c 1420
585f8587
FB
1421 s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */
1422 s->l2_size = 1 << s->l2_bits;
1d13d654
HR
1423 /* 2^(s->refcount_order - 3) is the refcount width in bytes */
1424 s->refcount_block_bits = s->cluster_bits - (s->refcount_order - 3);
1425 s->refcount_block_size = 1 << s->refcount_block_bits;
bd016b91 1426 bs->total_sectors = header.size / BDRV_SECTOR_SIZE;
585f8587
FB
1427 s->csize_shift = (62 - (s->cluster_bits - 8));
1428 s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;
1429 s->cluster_offset_mask = (1LL << s->csize_shift) - 1;
5dab2fad 1430
585f8587 1431 s->refcount_table_offset = header.refcount_table_offset;
5fafdf24 1432 s->refcount_table_size =
585f8587
FB
1433 header.refcount_table_clusters << (s->cluster_bits - 3);
1434
951053a9
AG
1435 if (header.refcount_table_clusters == 0 && !(flags & BDRV_O_CHECK)) {
1436 error_setg(errp, "Image does not contain a reference count table");
1437 ret = -EINVAL;
1438 goto fail;
1439 }
1440
0cf0e598
AG
1441 ret = qcow2_validate_table(bs, s->refcount_table_offset,
1442 header.refcount_table_clusters,
1443 s->cluster_size, QCOW_MAX_REFTABLE_SIZE,
1444 "Reference count table", errp);
8c7de283 1445 if (ret < 0) {
8c7de283
KW
1446 goto fail;
1447 }
1448
8bc584fe
HR
1449 if (!(flags & BDRV_O_CHECK)) {
1450 /*
1451 * The total size in bytes of the snapshot table is checked in
1452 * qcow2_read_snapshots() because the size of each snapshot is
1453 * variable and we don't know it yet.
1454 * Here we only check the offset and number of snapshots.
1455 */
1456 ret = qcow2_validate_table(bs, header.snapshots_offset,
1457 header.nb_snapshots,
1458 sizeof(QCowSnapshotHeader),
1459 sizeof(QCowSnapshotHeader) *
1460 QCOW_MAX_SNAPSHOTS,
1461 "Snapshot table", errp);
1462 if (ret < 0) {
1463 goto fail;
1464 }
ce48f2f4
KW
1465 }
1466
585f8587 1467 /* read the level 1 table */
0cf0e598
AG
1468 ret = qcow2_validate_table(bs, header.l1_table_offset,
1469 header.l1_size, sizeof(uint64_t),
1470 QCOW_MAX_L1_SIZE, "Active L1 table", errp);
1471 if (ret < 0) {
2d51c32c
KW
1472 goto fail;
1473 }
585f8587 1474 s->l1_size = header.l1_size;
0cf0e598 1475 s->l1_table_offset = header.l1_table_offset;
2cf7cfa1
KW
1476
1477 l1_vm_state_index = size_to_l1(s, header.size);
1478 if (l1_vm_state_index > INT_MAX) {
3ef6c40a 1479 error_setg(errp, "Image is too big");
2cf7cfa1
KW
1480 ret = -EFBIG;
1481 goto fail;
1482 }
1483 s->l1_vm_state_index = l1_vm_state_index;
1484
585f8587
FB
1485 /* the L1 table must contain at least enough entries to put
1486 header.size bytes */
6d85a57e 1487 if (s->l1_size < s->l1_vm_state_index) {
3ef6c40a 1488 error_setg(errp, "L1 table is too small");
6d85a57e 1489 ret = -EINVAL;
585f8587 1490 goto fail;
6d85a57e 1491 }
2d51c32c 1492
d191d12d 1493 if (s->l1_size > 0) {
9a4f4c31 1494 s->l1_table = qemu_try_blockalign(bs->file->bs,
9e029689 1495 ROUND_UP(s->l1_size * sizeof(uint64_t), 512));
de82815d
KW
1496 if (s->l1_table == NULL) {
1497 error_setg(errp, "Could not allocate L1 table");
1498 ret = -ENOMEM;
1499 goto fail;
1500 }
cf2ab8fc 1501 ret = bdrv_pread(bs->file, s->l1_table_offset, s->l1_table,
6d85a57e
JS
1502 s->l1_size * sizeof(uint64_t));
1503 if (ret < 0) {
3ef6c40a 1504 error_setg_errno(errp, -ret, "Could not read L1 table");
d191d12d 1505 goto fail;
6d85a57e 1506 }
d191d12d 1507 for(i = 0;i < s->l1_size; i++) {
3b698f52 1508 s->l1_table[i] = be64_to_cpu(s->l1_table[i]);
d191d12d 1509 }
585f8587 1510 }
29c1a730 1511
94edf3fb
KW
1512 /* Parse driver-specific options */
1513 ret = qcow2_update_options(bs, options, flags, errp);
90efa0ea
KW
1514 if (ret < 0) {
1515 goto fail;
1516 }
1517
06d9260f 1518 s->flags = flags;
3b46e624 1519
6d85a57e
JS
1520 ret = qcow2_refcount_init(bs);
1521 if (ret != 0) {
3ef6c40a 1522 error_setg_errno(errp, -ret, "Could not initialize refcount handling");
585f8587 1523 goto fail;
6d85a57e 1524 }
585f8587 1525
72cf2d4f 1526 QLIST_INIT(&s->cluster_allocs);
0b919fae 1527 QTAILQ_INIT(&s->discards);
f214978a 1528
9b80ddf3 1529 /* read qcow2 extensions */
3ef6c40a 1530 if (qcow2_read_extensions(bs, header.header_length, ext_end, NULL,
88ddffae 1531 flags, &update_header, &local_err)) {
3ef6c40a 1532 error_propagate(errp, local_err);
6d85a57e 1533 ret = -EINVAL;
9b80ddf3 1534 goto fail;
6d85a57e 1535 }
9b80ddf3 1536
0e8c08be
KW
1537 /* Open external data file */
1538 s->data_file = bdrv_open_child(NULL, options, "data-file", bs, &child_file,
1539 true, &local_err);
1540 if (local_err) {
1541 error_propagate(errp, local_err);
1542 ret = -EINVAL;
1543 goto fail;
1544 }
1545
1546 if (s->incompatible_features & QCOW2_INCOMPAT_DATA_FILE) {
9b890bdc
KW
1547 if (!s->data_file && s->image_data_file) {
1548 s->data_file = bdrv_open_child(s->image_data_file, options,
1549 "data-file", bs, &child_file,
1550 false, errp);
1551 if (!s->data_file) {
1552 ret = -EINVAL;
1553 goto fail;
1554 }
1555 }
0e8c08be
KW
1556 if (!s->data_file) {
1557 error_setg(errp, "'data-file' is required for this image");
1558 ret = -EINVAL;
1559 goto fail;
1560 }
1561 } else {
1562 if (s->data_file) {
1563 error_setg(errp, "'data-file' can only be set for images with an "
1564 "external data file");
1565 ret = -EINVAL;
1566 goto fail;
6c3944dc
KW
1567 }
1568
1569 s->data_file = bs->file;
1570
1571 if (data_file_is_raw(bs)) {
1572 error_setg(errp, "data-file-raw requires a data file");
1573 ret = -EINVAL;
1574 goto fail;
0e8c08be
KW
1575 }
1576 }
93c24936 1577
4652b8f3
DB
1578 /* qcow2_read_extension may have set up the crypto context
1579 * if the crypt method needs a header region, some methods
1580 * don't need header extensions, so must check here
1581 */
1582 if (s->crypt_method_header && !s->crypto) {
1583 if (s->crypt_method_header == QCOW_CRYPT_AES) {
1584 unsigned int cflags = 0;
1585 if (flags & BDRV_O_NO_IO) {
1586 cflags |= QCRYPTO_BLOCK_OPEN_NO_IO;
1587 }
1cd9a787 1588 s->crypto = qcrypto_block_open(s->crypto_opts, "encrypt.",
8ac0f15f
VSO
1589 NULL, NULL, cflags,
1590 QCOW2_MAX_THREADS, errp);
4652b8f3
DB
1591 if (!s->crypto) {
1592 ret = -EINVAL;
1593 goto fail;
1594 }
1595 } else if (!(flags & BDRV_O_NO_IO)) {
1596 error_setg(errp, "Missing CRYPTO header for crypt method %d",
1597 s->crypt_method_header);
b25b387f
DB
1598 ret = -EINVAL;
1599 goto fail;
1600 }
1601 }
1602
585f8587
FB
1603 /* read the backing file name */
1604 if (header.backing_file_offset != 0) {
1605 len = header.backing_file_size;
9a29e18f 1606 if (len > MIN(1023, s->cluster_size - header.backing_file_offset) ||
e729fa6a 1607 len >= sizeof(bs->backing_file)) {
6d33e8e7
KW
1608 error_setg(errp, "Backing file name too long");
1609 ret = -EINVAL;
1610 goto fail;
6d85a57e 1611 }
cf2ab8fc 1612 ret = bdrv_pread(bs->file, header.backing_file_offset,
998c2019 1613 bs->auto_backing_file, len);
6d85a57e 1614 if (ret < 0) {
3ef6c40a 1615 error_setg_errno(errp, -ret, "Could not read backing file name");
585f8587 1616 goto fail;
6d85a57e 1617 }
998c2019
HR
1618 bs->auto_backing_file[len] = '\0';
1619 pstrcpy(bs->backing_file, sizeof(bs->backing_file),
1620 bs->auto_backing_file);
1621 s->image_backing_file = g_strdup(bs->auto_backing_file);
585f8587 1622 }
42deb29f 1623
8bc584fe
HR
1624 /*
1625 * Internal snapshots; skip reading them in check mode, because
1626 * we do not need them then, and we do not want to abort because
1627 * of a broken table.
1628 */
1629 if (!(flags & BDRV_O_CHECK)) {
1630 s->snapshots_offset = header.snapshots_offset;
1631 s->nb_snapshots = header.nb_snapshots;
11b128f4 1632
8bc584fe
HR
1633 ret = qcow2_read_snapshots(bs, errp);
1634 if (ret < 0) {
1635 goto fail;
1636 }
6d85a57e 1637 }
585f8587 1638
af7b708d 1639 /* Clear unknown autoclear feature bits */
88ddffae 1640 update_header |= s->autoclear_features & ~QCOW2_AUTOCLEAR_MASK;
d1258dd0
VSO
1641 update_header =
1642 update_header && !bs->read_only && !(flags & BDRV_O_INACTIVE);
1643 if (update_header) {
88ddffae 1644 s->autoclear_features &= QCOW2_AUTOCLEAR_MASK;
d1258dd0
VSO
1645 }
1646
9c98f145
VSO
1647 /* == Handle persistent dirty bitmaps ==
1648 *
1649 * We want load dirty bitmaps in three cases:
1650 *
1651 * 1. Normal open of the disk in active mode, not related to invalidation
1652 * after migration.
1653 *
1654 * 2. Invalidation of the target vm after pre-copy phase of migration, if
1655 * bitmaps are _not_ migrating through migration channel, i.e.
1656 * 'dirty-bitmaps' capability is disabled.
1657 *
1658 * 3. Invalidation of source vm after failed or canceled migration.
1659 * This is a very interesting case. There are two possible types of
1660 * bitmaps:
1661 *
1662 * A. Stored on inactivation and removed. They should be loaded from the
1663 * image.
1664 *
1665 * B. Not stored: not-persistent bitmaps and bitmaps, migrated through
1666 * the migration channel (with dirty-bitmaps capability).
1667 *
1668 * On the other hand, there are two possible sub-cases:
1669 *
1670 * 3.1 disk was changed by somebody else while were inactive. In this
1671 * case all in-RAM dirty bitmaps (both persistent and not) are
1672 * definitely invalid. And we don't have any method to determine
1673 * this.
1674 *
1675 * Simple and safe thing is to just drop all the bitmaps of type B on
1676 * inactivation. But in this case we lose bitmaps in valid 4.2 case.
1677 *
1678 * On the other hand, resuming source vm, if disk was already changed
1679 * is a bad thing anyway: not only bitmaps, the whole vm state is
1680 * out of sync with disk.
1681 *
1682 * This means, that user or management tool, who for some reason
1683 * decided to resume source vm, after disk was already changed by
1684 * target vm, should at least drop all dirty bitmaps by hand.
1685 *
1686 * So, we can ignore this case for now, but TODO: "generation"
1687 * extension for qcow2, to determine, that image was changed after
1688 * last inactivation. And if it is changed, we will drop (or at least
1689 * mark as 'invalid' all the bitmaps of type B, both persistent
1690 * and not).
1691 *
1692 * 3.2 disk was _not_ changed while were inactive. Bitmaps may be saved
1693 * to disk ('dirty-bitmaps' capability disabled), or not saved
1694 * ('dirty-bitmaps' capability enabled), but we don't need to care
1695 * of: let's load bitmaps as always: stored bitmaps will be loaded,
1696 * and not stored has flag IN_USE=1 in the image and will be skipped
1697 * on loading.
1698 *
1699 * One remaining possible case when we don't want load bitmaps:
1700 *
1701 * 4. Open disk in inactive mode in target vm (bitmaps are migrating or
1702 * will be loaded on invalidation, no needs try loading them before)
1703 */
1704
1705 if (!(bdrv_get_flags(bs) & BDRV_O_INACTIVE)) {
1706 /* It's case 1, 2 or 3.2. Or 3.1 which is BUG in management layer. */
1707 bool header_updated = qcow2_load_dirty_bitmaps(bs, &local_err);
1708
1709 update_header = update_header && !header_updated;
d1258dd0
VSO
1710 }
1711 if (local_err != NULL) {
1712 error_propagate(errp, local_err);
1713 ret = -EINVAL;
1714 goto fail;
1715 }
1716
1717 if (update_header) {
af7b708d
SH
1718 ret = qcow2_update_header(bs);
1719 if (ret < 0) {
3ef6c40a 1720 error_setg_errno(errp, -ret, "Could not update qcow2 header");
af7b708d
SH
1721 goto fail;
1722 }
1723 }
1724
e24d813b 1725 bs->supported_zero_flags = header.version >= 3 ? BDRV_REQ_MAY_UNMAP : 0;
68d100e9 1726
c61d0004 1727 /* Repair image if dirty */
04c01a5c 1728 if (!(flags & (BDRV_O_CHECK | BDRV_O_INACTIVE)) && !bs->read_only &&
058f8f16 1729 (s->incompatible_features & QCOW2_INCOMPAT_DIRTY)) {
c61d0004
SH
1730 BdrvCheckResult result = {0};
1731
2fd61638
PB
1732 ret = qcow2_co_check_locked(bs, &result,
1733 BDRV_FIX_ERRORS | BDRV_FIX_LEAKS);
791fff50
HR
1734 if (ret < 0 || result.check_errors) {
1735 if (ret >= 0) {
1736 ret = -EIO;
1737 }
3ef6c40a 1738 error_setg_errno(errp, -ret, "Could not repair dirty image");
c61d0004
SH
1739 goto fail;
1740 }
1741 }
1742
585f8587 1743#ifdef DEBUG_ALLOC
6cbc3031
PH
1744 {
1745 BdrvCheckResult result = {0};
b35278f7 1746 qcow2_check_refcounts(bs, &result, 0);
6cbc3031 1747 }
585f8587 1748#endif
ceb029cd 1749
6f13a316 1750 qemu_co_queue_init(&s->thread_task_queue);
ceb029cd 1751
6d85a57e 1752 return ret;
585f8587
FB
1753
1754 fail:
9b890bdc 1755 g_free(s->image_data_file);
0e8c08be
KW
1756 if (has_data_file(bs)) {
1757 bdrv_unref_child(bs, s->data_file);
1758 }
6744cbab 1759 g_free(s->unknown_header_fields);
75bab85c 1760 cleanup_unknown_header_ext(bs);
ed6ccf0f
KW
1761 qcow2_free_snapshots(bs);
1762 qcow2_refcount_close(bs);
de82815d 1763 qemu_vfree(s->l1_table);
cf93980e
HR
1764 /* else pre-write overlap checks in cache_destroy may crash */
1765 s->l1_table = NULL;
279621c0 1766 cache_clean_timer_del(bs);
29c1a730 1767 if (s->l2_table_cache) {
e64d4072 1768 qcow2_cache_destroy(s->l2_table_cache);
29c1a730 1769 }
c5a33ee9 1770 if (s->refcount_block_cache) {
e64d4072 1771 qcow2_cache_destroy(s->refcount_block_cache);
c5a33ee9 1772 }
b25b387f
DB
1773 qcrypto_block_free(s->crypto);
1774 qapi_free_QCryptoBlockOpenOptions(s->crypto_opts);
6d85a57e 1775 return ret;
585f8587
FB
1776}
1777
1fafcd93
PB
1778typedef struct QCow2OpenCo {
1779 BlockDriverState *bs;
1780 QDict *options;
1781 int flags;
1782 Error **errp;
1783 int ret;
1784} QCow2OpenCo;
1785
1786static void coroutine_fn qcow2_open_entry(void *opaque)
1787{
1788 QCow2OpenCo *qoc = opaque;
1789 BDRVQcow2State *s = qoc->bs->opaque;
1790
1791 qemu_co_mutex_lock(&s->lock);
1792 qoc->ret = qcow2_do_open(qoc->bs, qoc->options, qoc->flags, qoc->errp);
1793 qemu_co_mutex_unlock(&s->lock);
1794}
1795
4e4bf5c4
KW
1796static int qcow2_open(BlockDriverState *bs, QDict *options, int flags,
1797 Error **errp)
1798{
1fafcd93
PB
1799 BDRVQcow2State *s = bs->opaque;
1800 QCow2OpenCo qoc = {
1801 .bs = bs,
1802 .options = options,
1803 .flags = flags,
1804 .errp = errp,
1805 .ret = -EINPROGRESS
1806 };
1807
4e4bf5c4
KW
1808 bs->file = bdrv_open_child(NULL, options, "file", bs, &child_file,
1809 false, errp);
1810 if (!bs->file) {
1811 return -EINVAL;
1812 }
1813
1fafcd93
PB
1814 /* Initialise locks */
1815 qemu_co_mutex_init(&s->lock);
1816
1817 if (qemu_in_coroutine()) {
1818 /* From bdrv_co_create. */
1819 qcow2_open_entry(&qoc);
1820 } else {
4720cbee 1821 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
1fafcd93
PB
1822 qemu_coroutine_enter(qemu_coroutine_create(qcow2_open_entry, &qoc));
1823 BDRV_POLL_WHILE(bs, qoc.ret == -EINPROGRESS);
1824 }
1825 return qoc.ret;
4e4bf5c4
KW
1826}
1827
3baca891 1828static void qcow2_refresh_limits(BlockDriverState *bs, Error **errp)
d34682cd 1829{
ff99129a 1830 BDRVQcow2State *s = bs->opaque;
d34682cd 1831
a84178cc
EB
1832 if (bs->encrypted) {
1833 /* Encryption works on a sector granularity */
6f8f015c 1834 bs->bl.request_alignment = qcrypto_block_get_sector_size(s->crypto);
a84178cc 1835 }
cf081fca 1836 bs->bl.pwrite_zeroes_alignment = s->cluster_size;
ecdbead6 1837 bs->bl.pdiscard_alignment = s->cluster_size;
d34682cd
KW
1838}
1839
21d82ac9
JC
1840static int qcow2_reopen_prepare(BDRVReopenState *state,
1841 BlockReopenQueue *queue, Error **errp)
1842{
5b0959a7 1843 Qcow2ReopenState *r;
4c2e5f8f
KW
1844 int ret;
1845
5b0959a7
KW
1846 r = g_new0(Qcow2ReopenState, 1);
1847 state->opaque = r;
1848
1849 ret = qcow2_update_options_prepare(state->bs, r, state->options,
1850 state->flags, errp);
1851 if (ret < 0) {
1852 goto fail;
1853 }
1854
1855 /* We need to write out any unwritten data if we reopen read-only. */
4c2e5f8f 1856 if ((state->flags & BDRV_O_RDWR) == 0) {
169b8793
VSO
1857 ret = qcow2_reopen_bitmaps_ro(state->bs, errp);
1858 if (ret < 0) {
1859 goto fail;
1860 }
1861
4c2e5f8f
KW
1862 ret = bdrv_flush(state->bs);
1863 if (ret < 0) {
5b0959a7 1864 goto fail;
4c2e5f8f
KW
1865 }
1866
1867 ret = qcow2_mark_clean(state->bs);
1868 if (ret < 0) {
5b0959a7 1869 goto fail;
4c2e5f8f
KW
1870 }
1871 }
1872
21d82ac9 1873 return 0;
5b0959a7
KW
1874
1875fail:
1876 qcow2_update_options_abort(state->bs, r);
1877 g_free(r);
1878 return ret;
1879}
1880
1881static void qcow2_reopen_commit(BDRVReopenState *state)
1882{
1883 qcow2_update_options_commit(state->bs, state->opaque);
4dd09f62
VSO
1884 if (state->flags & BDRV_O_RDWR) {
1885 Error *local_err = NULL;
1886
1887 if (qcow2_reopen_bitmaps_rw(state->bs, &local_err) < 0) {
1888 /*
1889 * This is not fatal, bitmaps just left read-only, so all following
1890 * writes will fail. User can remove read-only bitmaps to unblock
1891 * writes or retry reopen.
1892 */
1893 error_reportf_err(local_err,
1894 "%s: Failed to make dirty bitmaps writable: ",
1895 bdrv_get_node_name(state->bs));
1896 }
1897 }
5b0959a7
KW
1898 g_free(state->opaque);
1899}
1900
1901static void qcow2_reopen_abort(BDRVReopenState *state)
1902{
1903 qcow2_update_options_abort(state->bs, state->opaque);
1904 g_free(state->opaque);
21d82ac9
JC
1905}
1906
5365f44d
KW
1907static void qcow2_join_options(QDict *options, QDict *old_options)
1908{
1909 bool has_new_overlap_template =
1910 qdict_haskey(options, QCOW2_OPT_OVERLAP) ||
1911 qdict_haskey(options, QCOW2_OPT_OVERLAP_TEMPLATE);
1912 bool has_new_total_cache_size =
1913 qdict_haskey(options, QCOW2_OPT_CACHE_SIZE);
1914 bool has_all_cache_options;
1915
1916 /* New overlap template overrides all old overlap options */
1917 if (has_new_overlap_template) {
1918 qdict_del(old_options, QCOW2_OPT_OVERLAP);
1919 qdict_del(old_options, QCOW2_OPT_OVERLAP_TEMPLATE);
1920 qdict_del(old_options, QCOW2_OPT_OVERLAP_MAIN_HEADER);
1921 qdict_del(old_options, QCOW2_OPT_OVERLAP_ACTIVE_L1);
1922 qdict_del(old_options, QCOW2_OPT_OVERLAP_ACTIVE_L2);
1923 qdict_del(old_options, QCOW2_OPT_OVERLAP_REFCOUNT_TABLE);
1924 qdict_del(old_options, QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK);
1925 qdict_del(old_options, QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE);
1926 qdict_del(old_options, QCOW2_OPT_OVERLAP_INACTIVE_L1);
1927 qdict_del(old_options, QCOW2_OPT_OVERLAP_INACTIVE_L2);
1928 }
1929
1930 /* New total cache size overrides all old options */
1931 if (qdict_haskey(options, QCOW2_OPT_CACHE_SIZE)) {
1932 qdict_del(old_options, QCOW2_OPT_L2_CACHE_SIZE);
1933 qdict_del(old_options, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
1934 }
1935
1936 qdict_join(options, old_options, false);
1937
1938 /*
1939 * If after merging all cache size options are set, an old total size is
1940 * overwritten. Do keep all options, however, if all three are new. The
1941 * resulting error message is what we want to happen.
1942 */
1943 has_all_cache_options =
1944 qdict_haskey(options, QCOW2_OPT_CACHE_SIZE) ||
1945 qdict_haskey(options, QCOW2_OPT_L2_CACHE_SIZE) ||
1946 qdict_haskey(options, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
1947
1948 if (has_all_cache_options && !has_new_total_cache_size) {
1949 qdict_del(options, QCOW2_OPT_CACHE_SIZE);
1950 }
1951}
1952
a320fb04
EB
1953static int coroutine_fn qcow2_co_block_status(BlockDriverState *bs,
1954 bool want_zero,
1955 int64_t offset, int64_t count,
1956 int64_t *pnum, int64_t *map,
1957 BlockDriverState **file)
585f8587 1958{
ff99129a 1959 BDRVQcow2State *s = bs->opaque;
585f8587 1960 uint64_t cluster_offset;
4bc74be9 1961 int index_in_cluster, ret;
ecfe1863 1962 unsigned int bytes;
a320fb04 1963 int status = 0;
585f8587 1964
5e978550
KW
1965 qemu_co_mutex_lock(&s->lock);
1966
69f47505
VSO
1967 if (!s->metadata_preallocation_checked) {
1968 ret = qcow2_detect_metadata_preallocation(bs);
1969 s->metadata_preallocation = (ret == 1);
1970 s->metadata_preallocation_checked = true;
1971 }
1972
a320fb04 1973 bytes = MIN(INT_MAX, count);
a320fb04 1974 ret = qcow2_get_cluster_offset(bs, offset, &bytes, &cluster_offset);
f8a2e5e3 1975 qemu_co_mutex_unlock(&s->lock);
1c46efaa 1976 if (ret < 0) {
d663640c 1977 return ret;
1c46efaa 1978 }
095a9c58 1979
a320fb04 1980 *pnum = bytes;
ecfe1863 1981
37be1403 1982 if ((ret == QCOW2_CLUSTER_NORMAL || ret == QCOW2_CLUSTER_ZERO_ALLOC) &&
b25b387f 1983 !s->crypto) {
a320fb04
EB
1984 index_in_cluster = offset & (s->cluster_size - 1);
1985 *map = cluster_offset | index_in_cluster;
37be1403 1986 *file = s->data_file->bs;
a320fb04 1987 status |= BDRV_BLOCK_OFFSET_VALID;
4bc74be9 1988 }
fdfab37d 1989 if (ret == QCOW2_CLUSTER_ZERO_PLAIN || ret == QCOW2_CLUSTER_ZERO_ALLOC) {
4bc74be9
PB
1990 status |= BDRV_BLOCK_ZERO;
1991 } else if (ret != QCOW2_CLUSTER_UNALLOCATED) {
1992 status |= BDRV_BLOCK_DATA;
1993 }
69f47505
VSO
1994 if (s->metadata_preallocation && (status & BDRV_BLOCK_DATA) &&
1995 (status & BDRV_BLOCK_OFFSET_VALID))
1996 {
1997 status |= BDRV_BLOCK_RECURSE;
1998 }
4bc74be9 1999 return status;
585f8587
FB
2000}
2001
fd9fcd37
FZ
2002static coroutine_fn int qcow2_handle_l2meta(BlockDriverState *bs,
2003 QCowL2Meta **pl2meta,
2004 bool link_l2)
2005{
2006 int ret = 0;
2007 QCowL2Meta *l2meta = *pl2meta;
2008
2009 while (l2meta != NULL) {
2010 QCowL2Meta *next;
2011
354d930d 2012 if (link_l2) {
fd9fcd37
FZ
2013 ret = qcow2_alloc_cluster_link_l2(bs, l2meta);
2014 if (ret) {
2015 goto out;
2016 }
8b24cd14
KW
2017 } else {
2018 qcow2_alloc_cluster_abort(bs, l2meta);
fd9fcd37
FZ
2019 }
2020
2021 /* Take the request off the list of running requests */
2022 if (l2meta->nb_clusters != 0) {
2023 QLIST_REMOVE(l2meta, next_in_flight);
2024 }
2025
2026 qemu_co_queue_restart_all(&l2meta->dependent_requests);
2027
2028 next = l2meta->next;
2029 g_free(l2meta);
2030 l2meta = next;
2031 }
2032out:
2033 *pl2meta = l2meta;
2034 return ret;
2035}
2036
88f468e5
VSO
2037static coroutine_fn int
2038qcow2_co_preadv_encrypted(BlockDriverState *bs,
2039 uint64_t file_cluster_offset,
2040 uint64_t offset,
2041 uint64_t bytes,
2042 QEMUIOVector *qiov,
2043 uint64_t qiov_offset)
2044{
2045 int ret;
2046 BDRVQcow2State *s = bs->opaque;
2047 uint8_t *buf;
2048
2049 assert(bs->encrypted && s->crypto);
2050 assert(bytes <= QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
2051
2052 /*
2053 * For encrypted images, read everything into a temporary
2054 * contiguous buffer on which the AES functions can work.
2055 * Also, decryption in a separate buffer is better as it
2056 * prevents the guest from learning information about the
2057 * encrypted nature of the virtual disk.
2058 */
2059
2060 buf = qemu_try_blockalign(s->data_file->bs, bytes);
2061 if (buf == NULL) {
2062 return -ENOMEM;
2063 }
2064
2065 BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);
2066 ret = bdrv_co_pread(s->data_file,
2067 file_cluster_offset + offset_into_cluster(s, offset),
2068 bytes, buf, 0);
2069 if (ret < 0) {
2070 goto fail;
2071 }
2072
2073 assert(QEMU_IS_ALIGNED(offset, BDRV_SECTOR_SIZE));
2074 assert(QEMU_IS_ALIGNED(bytes, BDRV_SECTOR_SIZE));
2075 if (qcow2_co_decrypt(bs,
2076 file_cluster_offset + offset_into_cluster(s, offset),
2077 offset, buf, bytes) < 0)
2078 {
2079 ret = -EIO;
2080 goto fail;
2081 }
2082 qemu_iovec_from_buf(qiov, qiov_offset, buf, bytes);
2083
2084fail:
2085 qemu_vfree(buf);
2086
2087 return ret;
2088}
2089
d710cf57
VSO
2090typedef struct Qcow2AioTask {
2091 AioTask task;
2092
2093 BlockDriverState *bs;
2094 QCow2ClusterType cluster_type; /* only for read */
2095 uint64_t file_cluster_offset;
2096 uint64_t offset;
2097 uint64_t bytes;
2098 QEMUIOVector *qiov;
2099 uint64_t qiov_offset;
2100 QCowL2Meta *l2meta; /* only for write */
2101} Qcow2AioTask;
2102
2103static coroutine_fn int qcow2_co_preadv_task_entry(AioTask *task);
2104static coroutine_fn int qcow2_add_task(BlockDriverState *bs,
2105 AioTaskPool *pool,
2106 AioTaskFunc func,
2107 QCow2ClusterType cluster_type,
2108 uint64_t file_cluster_offset,
2109 uint64_t offset,
2110 uint64_t bytes,
2111 QEMUIOVector *qiov,
2112 size_t qiov_offset,
2113 QCowL2Meta *l2meta)
2114{
2115 Qcow2AioTask local_task;
2116 Qcow2AioTask *task = pool ? g_new(Qcow2AioTask, 1) : &local_task;
2117
2118 *task = (Qcow2AioTask) {
2119 .task.func = func,
2120 .bs = bs,
2121 .cluster_type = cluster_type,
2122 .qiov = qiov,
2123 .file_cluster_offset = file_cluster_offset,
2124 .offset = offset,
2125 .bytes = bytes,
2126 .qiov_offset = qiov_offset,
2127 .l2meta = l2meta,
2128 };
2129
2130 trace_qcow2_add_task(qemu_coroutine_self(), bs, pool,
2131 func == qcow2_co_preadv_task_entry ? "read" : "write",
2132 cluster_type, file_cluster_offset, offset, bytes,
2133 qiov, qiov_offset);
2134
2135 if (!pool) {
2136 return func(&task->task);
2137 }
2138
2139 aio_task_pool_start_task(pool, &task->task);
2140
2141 return 0;
2142}
2143
88f468e5
VSO
2144static coroutine_fn int qcow2_co_preadv_task(BlockDriverState *bs,
2145 QCow2ClusterType cluster_type,
2146 uint64_t file_cluster_offset,
2147 uint64_t offset, uint64_t bytes,
2148 QEMUIOVector *qiov,
2149 size_t qiov_offset)
2150{
2151 BDRVQcow2State *s = bs->opaque;
2152 int offset_in_cluster = offset_into_cluster(s, offset);
2153
2154 switch (cluster_type) {
2155 case QCOW2_CLUSTER_ZERO_PLAIN:
2156 case QCOW2_CLUSTER_ZERO_ALLOC:
2157 /* Both zero types are handled in qcow2_co_preadv_part */
2158 g_assert_not_reached();
2159
2160 case QCOW2_CLUSTER_UNALLOCATED:
2161 assert(bs->backing); /* otherwise handled in qcow2_co_preadv_part */
2162
2163 BLKDBG_EVENT(bs->file, BLKDBG_READ_BACKING_AIO);
2164 return bdrv_co_preadv_part(bs->backing, offset, bytes,
2165 qiov, qiov_offset, 0);
2166
2167 case QCOW2_CLUSTER_COMPRESSED:
2168 return qcow2_co_preadv_compressed(bs, file_cluster_offset,
2169 offset, bytes, qiov, qiov_offset);
2170
2171 case QCOW2_CLUSTER_NORMAL:
2172 if ((file_cluster_offset & 511) != 0) {
2173 return -EIO;
2174 }
2175
2176 if (bs->encrypted) {
2177 return qcow2_co_preadv_encrypted(bs, file_cluster_offset,
2178 offset, bytes, qiov, qiov_offset);
2179 }
2180
2181 BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);
2182 return bdrv_co_preadv_part(s->data_file,
2183 file_cluster_offset + offset_in_cluster,
2184 bytes, qiov, qiov_offset, 0);
2185
2186 default:
2187 g_assert_not_reached();
2188 }
2189
2190 g_assert_not_reached();
2191}
2192
d710cf57
VSO
2193static coroutine_fn int qcow2_co_preadv_task_entry(AioTask *task)
2194{
2195 Qcow2AioTask *t = container_of(task, Qcow2AioTask, task);
2196
2197 assert(!t->l2meta);
2198
2199 return qcow2_co_preadv_task(t->bs, t->cluster_type, t->file_cluster_offset,
2200 t->offset, t->bytes, t->qiov, t->qiov_offset);
2201}
2202
df893d25
VSO
2203static coroutine_fn int qcow2_co_preadv_part(BlockDriverState *bs,
2204 uint64_t offset, uint64_t bytes,
2205 QEMUIOVector *qiov,
2206 size_t qiov_offset, int flags)
585f8587 2207{
ff99129a 2208 BDRVQcow2State *s = bs->opaque;
d710cf57 2209 int ret = 0;
ecfe1863 2210 unsigned int cur_bytes; /* number of bytes in current iteration */
c2bdd990 2211 uint64_t cluster_offset = 0;
d710cf57 2212 AioTaskPool *aio = NULL;
585f8587 2213
d710cf57 2214 while (bytes != 0 && aio_task_pool_status(aio) == 0) {
5ebaa27e 2215 /* prepare next request */
ecfe1863 2216 cur_bytes = MIN(bytes, INT_MAX);
b25b387f 2217 if (s->crypto) {
ecfe1863
KW
2218 cur_bytes = MIN(cur_bytes,
2219 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
585f8587 2220 }
5ebaa27e 2221
f24196d3 2222 qemu_co_mutex_lock(&s->lock);
ecfe1863 2223 ret = qcow2_get_cluster_offset(bs, offset, &cur_bytes, &cluster_offset);
f24196d3 2224 qemu_co_mutex_unlock(&s->lock);
8af36488 2225 if (ret < 0) {
d710cf57 2226 goto out;
8af36488 2227 }
bd28f835 2228
88f468e5
VSO
2229 if (ret == QCOW2_CLUSTER_ZERO_PLAIN ||
2230 ret == QCOW2_CLUSTER_ZERO_ALLOC ||
2231 (ret == QCOW2_CLUSTER_UNALLOCATED && !bs->backing))
2232 {
df893d25 2233 qemu_iovec_memset(qiov, qiov_offset, 0, cur_bytes);
88f468e5 2234 } else {
d710cf57
VSO
2235 if (!aio && cur_bytes != bytes) {
2236 aio = aio_task_pool_new(QCOW2_MAX_WORKERS);
2237 }
2238 ret = qcow2_add_task(bs, aio, qcow2_co_preadv_task_entry, ret,
2239 cluster_offset, offset, cur_bytes,
2240 qiov, qiov_offset, NULL);
5ebaa27e 2241 if (ret < 0) {
d710cf57 2242 goto out;
5ebaa27e 2243 }
faf575c1 2244 }
f141eafe 2245
ecfe1863
KW
2246 bytes -= cur_bytes;
2247 offset += cur_bytes;
df893d25 2248 qiov_offset += cur_bytes;
5ebaa27e 2249 }
68d100e9 2250
d710cf57
VSO
2251out:
2252 if (aio) {
2253 aio_task_pool_wait_all(aio);
2254 if (ret == 0) {
2255 ret = aio_task_pool_status(aio);
2256 }
2257 g_free(aio);
2258 }
2259
2260 return ret;
585f8587
FB
2261}
2262
ee22a9d8
AG
2263/* Check if it's possible to merge a write request with the writing of
2264 * the data from the COW regions */
2265static bool merge_cow(uint64_t offset, unsigned bytes,
5396234b
VSO
2266 QEMUIOVector *qiov, size_t qiov_offset,
2267 QCowL2Meta *l2meta)
ee22a9d8
AG
2268{
2269 QCowL2Meta *m;
2270
2271 for (m = l2meta; m != NULL; m = m->next) {
2272 /* If both COW regions are empty then there's nothing to merge */
2273 if (m->cow_start.nb_bytes == 0 && m->cow_end.nb_bytes == 0) {
2274 continue;
2275 }
2276
c8bb23cb
AN
2277 /* If COW regions are handled already, skip this too */
2278 if (m->skip_cow) {
2279 continue;
2280 }
2281
ee22a9d8
AG
2282 /* The data (middle) region must be immediately after the
2283 * start region */
2284 if (l2meta_cow_start(m) + m->cow_start.nb_bytes != offset) {
2285 continue;
2286 }
2287
2288 /* The end region must be immediately after the data (middle)
2289 * region */
2290 if (m->offset + m->cow_end.offset != offset + bytes) {
2291 continue;
2292 }
2293
2294 /* Make sure that adding both COW regions to the QEMUIOVector
2295 * does not exceed IOV_MAX */
5396234b 2296 if (qemu_iovec_subvec_niov(qiov, qiov_offset, bytes) > IOV_MAX - 2) {
ee22a9d8
AG
2297 continue;
2298 }
2299
5396234b
VSO
2300 m->data_qiov = qiov;
2301 m->data_qiov_offset = qiov_offset;
ee22a9d8
AG
2302 return true;
2303 }
2304
2305 return false;
2306}
2307
c8bb23cb
AN
2308static bool is_unallocated(BlockDriverState *bs, int64_t offset, int64_t bytes)
2309{
2310 int64_t nr;
2311 return !bytes ||
170d3bd3
AS
2312 (!bdrv_is_allocated_above(bs, NULL, false, offset, bytes, &nr) &&
2313 nr == bytes);
c8bb23cb
AN
2314}
2315
2316static bool is_zero_cow(BlockDriverState *bs, QCowL2Meta *m)
2317{
2318 /*
2319 * This check is designed for optimization shortcut so it must be
2320 * efficient.
2321 * Instead of is_zero(), use is_unallocated() as it is faster (but not
2322 * as accurate and can result in false negatives).
2323 */
2324 return is_unallocated(bs, m->offset + m->cow_start.offset,
2325 m->cow_start.nb_bytes) &&
2326 is_unallocated(bs, m->offset + m->cow_end.offset,
2327 m->cow_end.nb_bytes);
2328}
2329
2330static int handle_alloc_space(BlockDriverState *bs, QCowL2Meta *l2meta)
2331{
2332 BDRVQcow2State *s = bs->opaque;
2333 QCowL2Meta *m;
2334
2335 if (!(s->data_file->bs->supported_zero_flags & BDRV_REQ_NO_FALLBACK)) {
2336 return 0;
2337 }
2338
2339 if (bs->encrypted) {
2340 return 0;
2341 }
2342
2343 for (m = l2meta; m != NULL; m = m->next) {
2344 int ret;
2345
2346 if (!m->cow_start.nb_bytes && !m->cow_end.nb_bytes) {
2347 continue;
2348 }
2349
2350 if (!is_zero_cow(bs, m)) {
2351 continue;
2352 }
2353
2354 /*
2355 * instead of writing zero COW buffers,
2356 * efficiently zero out the whole clusters
2357 */
2358
2359 ret = qcow2_pre_write_overlap_check(bs, 0, m->alloc_offset,
2360 m->nb_clusters * s->cluster_size,
2361 true);
2362 if (ret < 0) {
2363 return ret;
2364 }
2365
2366 BLKDBG_EVENT(bs->file, BLKDBG_CLUSTER_ALLOC_SPACE);
2367 ret = bdrv_co_pwrite_zeroes(s->data_file, m->alloc_offset,
2368 m->nb_clusters * s->cluster_size,
2369 BDRV_REQ_NO_FALLBACK);
2370 if (ret < 0) {
2371 if (ret != -ENOTSUP && ret != -EAGAIN) {
2372 return ret;
2373 }
2374 continue;
2375 }
2376
2377 trace_qcow2_skip_cow(qemu_coroutine_self(), m->offset, m->nb_clusters);
2378 m->skip_cow = true;
2379 }
2380 return 0;
2381}
2382
6aa7a263
VSO
2383/*
2384 * qcow2_co_pwritev_task
2385 * Called with s->lock unlocked
2386 * l2meta - if not NULL, qcow2_co_pwritev_task() will consume it. Caller must
2387 * not use it somehow after qcow2_co_pwritev_task() call
2388 */
2389static coroutine_fn int qcow2_co_pwritev_task(BlockDriverState *bs,
2390 uint64_t file_cluster_offset,
2391 uint64_t offset, uint64_t bytes,
2392 QEMUIOVector *qiov,
2393 uint64_t qiov_offset,
2394 QCowL2Meta *l2meta)
2395{
2396 int ret;
2397 BDRVQcow2State *s = bs->opaque;
2398 void *crypt_buf = NULL;
2399 int offset_in_cluster = offset_into_cluster(s, offset);
2400 QEMUIOVector encrypted_qiov;
2401
2402 if (bs->encrypted) {
2403 assert(s->crypto);
2404 assert(bytes <= QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
2405 crypt_buf = qemu_try_blockalign(bs->file->bs, bytes);
2406 if (crypt_buf == NULL) {
2407 ret = -ENOMEM;
2408 goto out_unlocked;
2409 }
2410 qemu_iovec_to_buf(qiov, qiov_offset, crypt_buf, bytes);
2411
2412 if (qcow2_co_encrypt(bs, file_cluster_offset + offset_in_cluster,
2413 offset, crypt_buf, bytes) < 0)
2414 {
2415 ret = -EIO;
2416 goto out_unlocked;
2417 }
2418
2419 qemu_iovec_init_buf(&encrypted_qiov, crypt_buf, bytes);
2420 qiov = &encrypted_qiov;
2421 qiov_offset = 0;
2422 }
2423
2424 /* Try to efficiently initialize the physical space with zeroes */
2425 ret = handle_alloc_space(bs, l2meta);
2426 if (ret < 0) {
2427 goto out_unlocked;
2428 }
2429
2430 /*
2431 * If we need to do COW, check if it's possible to merge the
2432 * writing of the guest data together with that of the COW regions.
2433 * If it's not possible (or not necessary) then write the
2434 * guest data now.
2435 */
2436 if (!merge_cow(offset, bytes, qiov, qiov_offset, l2meta)) {
2437 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO);
2438 trace_qcow2_writev_data(qemu_coroutine_self(),
2439 file_cluster_offset + offset_in_cluster);
2440 ret = bdrv_co_pwritev_part(s->data_file,
2441 file_cluster_offset + offset_in_cluster,
2442 bytes, qiov, qiov_offset, 0);
2443 if (ret < 0) {
2444 goto out_unlocked;
2445 }
2446 }
2447
2448 qemu_co_mutex_lock(&s->lock);
2449
2450 ret = qcow2_handle_l2meta(bs, &l2meta, true);
2451 goto out_locked;
2452
2453out_unlocked:
2454 qemu_co_mutex_lock(&s->lock);
2455
2456out_locked:
2457 qcow2_handle_l2meta(bs, &l2meta, false);
2458 qemu_co_mutex_unlock(&s->lock);
2459
2460 qemu_vfree(crypt_buf);
2461
2462 return ret;
2463}
2464
d710cf57
VSO
2465static coroutine_fn int qcow2_co_pwritev_task_entry(AioTask *task)
2466{
2467 Qcow2AioTask *t = container_of(task, Qcow2AioTask, task);
2468
2469 assert(!t->cluster_type);
2470
2471 return qcow2_co_pwritev_task(t->bs, t->file_cluster_offset,
2472 t->offset, t->bytes, t->qiov, t->qiov_offset,
2473 t->l2meta);
2474}
2475
5396234b
VSO
2476static coroutine_fn int qcow2_co_pwritev_part(
2477 BlockDriverState *bs, uint64_t offset, uint64_t bytes,
2478 QEMUIOVector *qiov, size_t qiov_offset, int flags)
585f8587 2479{
ff99129a 2480 BDRVQcow2State *s = bs->opaque;
d46a0bb2 2481 int offset_in_cluster;
68d100e9 2482 int ret;
d46a0bb2 2483 unsigned int cur_bytes; /* number of sectors in current iteration */
c2bdd990 2484 uint64_t cluster_offset;
8d2497c3 2485 QCowL2Meta *l2meta = NULL;
d710cf57 2486 AioTaskPool *aio = NULL;
c2271403 2487
d46a0bb2 2488 trace_qcow2_writev_start_req(qemu_coroutine_self(), offset, bytes);
3cce16f4 2489
d710cf57 2490 while (bytes != 0 && aio_task_pool_status(aio) == 0) {
3fc48d09 2491
f50f88b9 2492 l2meta = NULL;
cf5c1a23 2493
3cce16f4 2494 trace_qcow2_writev_start_part(qemu_coroutine_self());
d46a0bb2
KW
2495 offset_in_cluster = offset_into_cluster(s, offset);
2496 cur_bytes = MIN(bytes, INT_MAX);
2497 if (bs->encrypted) {
2498 cur_bytes = MIN(cur_bytes,
2499 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size
2500 - offset_in_cluster);
5ebaa27e 2501 }
095a9c58 2502
6aa7a263
VSO
2503 qemu_co_mutex_lock(&s->lock);
2504
d46a0bb2
KW
2505 ret = qcow2_alloc_cluster_offset(bs, offset, &cur_bytes,
2506 &cluster_offset, &l2meta);
5ebaa27e 2507 if (ret < 0) {
5447c3a0 2508 goto out_locked;
5ebaa27e 2509 }
148da7ea 2510
5ebaa27e 2511 assert((cluster_offset & 511) == 0);
148da7ea 2512
5447c3a0
VSO
2513 ret = qcow2_pre_write_overlap_check(bs, 0,
2514 cluster_offset + offset_in_cluster,
2515 cur_bytes, true);
2516 if (ret < 0) {
2517 goto out_locked;
2518 }
2519
2520 qemu_co_mutex_unlock(&s->lock);
2521
d710cf57
VSO
2522 if (!aio && cur_bytes != bytes) {
2523 aio = aio_task_pool_new(QCOW2_MAX_WORKERS);
2524 }
2525 ret = qcow2_add_task(bs, aio, qcow2_co_pwritev_task_entry, 0,
2526 cluster_offset, offset, cur_bytes,
2527 qiov, qiov_offset, l2meta);
6aa7a263 2528 l2meta = NULL; /* l2meta is consumed by qcow2_co_pwritev_task() */
c8bb23cb 2529 if (ret < 0) {
6aa7a263 2530 goto fail_nometa;
f50f88b9 2531 }
0fa9131a 2532
d46a0bb2
KW
2533 bytes -= cur_bytes;
2534 offset += cur_bytes;
6aa7a263 2535 qiov_offset += cur_bytes;
d46a0bb2 2536 trace_qcow2_writev_done_part(qemu_coroutine_self(), cur_bytes);
5ebaa27e 2537 }
3fc48d09 2538 ret = 0;
faf575c1 2539
5447c3a0
VSO
2540 qemu_co_mutex_lock(&s->lock);
2541
2542out_locked:
fd9fcd37 2543 qcow2_handle_l2meta(bs, &l2meta, false);
0fa9131a 2544
a8c57408
PB
2545 qemu_co_mutex_unlock(&s->lock);
2546
6aa7a263 2547fail_nometa:
d710cf57
VSO
2548 if (aio) {
2549 aio_task_pool_wait_all(aio);
2550 if (ret == 0) {
2551 ret = aio_task_pool_status(aio);
2552 }
2553 g_free(aio);
2554 }
2555
3cce16f4 2556 trace_qcow2_writev_done_req(qemu_coroutine_self(), ret);
42496d62 2557
68d100e9 2558 return ret;
585f8587
FB
2559}
2560
ec6d8912
KW
2561static int qcow2_inactivate(BlockDriverState *bs)
2562{
2563 BDRVQcow2State *s = bs->opaque;
2564 int ret, result = 0;
5f72826e 2565 Error *local_err = NULL;
ec6d8912 2566
644ddbb7 2567 qcow2_store_persistent_dirty_bitmaps(bs, true, &local_err);
83a8c775
PB
2568 if (local_err != NULL) {
2569 result = -EINVAL;
132adb68
VSO
2570 error_reportf_err(local_err, "Lost persistent bitmaps during "
2571 "inactivation of node '%s': ",
2572 bdrv_get_device_or_node_name(bs));
83a8c775
PB
2573 }
2574
ec6d8912
KW
2575 ret = qcow2_cache_flush(bs, s->l2_table_cache);
2576 if (ret) {
2577 result = ret;
2578 error_report("Failed to flush the L2 table cache: %s",
2579 strerror(-ret));
2580 }
2581
2582 ret = qcow2_cache_flush(bs, s->refcount_block_cache);
2583 if (ret) {
2584 result = ret;
2585 error_report("Failed to flush the refcount block cache: %s",
2586 strerror(-ret));
2587 }
2588
2589 if (result == 0) {
2590 qcow2_mark_clean(bs);
2591 }
2592
2593 return result;
2594}
2595
7c80ab3f 2596static void qcow2_close(BlockDriverState *bs)
585f8587 2597{
ff99129a 2598 BDRVQcow2State *s = bs->opaque;
de82815d 2599 qemu_vfree(s->l1_table);
cf93980e
HR
2600 /* else pre-write overlap checks in cache_destroy may crash */
2601 s->l1_table = NULL;
29c1a730 2602
140fd5a6 2603 if (!(s->flags & BDRV_O_INACTIVE)) {
ec6d8912 2604 qcow2_inactivate(bs);
27eb6c09 2605 }
c61d0004 2606
279621c0 2607 cache_clean_timer_del(bs);
e64d4072
AG
2608 qcow2_cache_destroy(s->l2_table_cache);
2609 qcow2_cache_destroy(s->refcount_block_cache);
29c1a730 2610
b25b387f
DB
2611 qcrypto_block_free(s->crypto);
2612 s->crypto = NULL;
f6fa64f6 2613
6744cbab 2614 g_free(s->unknown_header_fields);
75bab85c 2615 cleanup_unknown_header_ext(bs);
6744cbab 2616
9b890bdc 2617 g_free(s->image_data_file);
e4603fe1
KW
2618 g_free(s->image_backing_file);
2619 g_free(s->image_backing_format);
2620
0e8c08be
KW
2621 if (has_data_file(bs)) {
2622 bdrv_unref_child(bs, s->data_file);
2623 }
2624
ed6ccf0f 2625 qcow2_refcount_close(bs);
28c1202b 2626 qcow2_free_snapshots(bs);
585f8587
FB
2627}
2628
2b148f39
PB
2629static void coroutine_fn qcow2_co_invalidate_cache(BlockDriverState *bs,
2630 Error **errp)
06d9260f 2631{
ff99129a 2632 BDRVQcow2State *s = bs->opaque;
06d9260f 2633 int flags = s->flags;
b25b387f 2634 QCryptoBlock *crypto = NULL;
acdfb480 2635 QDict *options;
5a8a30db
KW
2636 Error *local_err = NULL;
2637 int ret;
06d9260f
AL
2638
2639 /*
2640 * Backing files are read-only which makes all of their metadata immutable,
2641 * that means we don't have to worry about reopening them here.
2642 */
2643
b25b387f
DB
2644 crypto = s->crypto;
2645 s->crypto = NULL;
06d9260f
AL
2646
2647 qcow2_close(bs);
2648
ff99129a 2649 memset(s, 0, sizeof(BDRVQcow2State));
d475e5ac 2650 options = qdict_clone_shallow(bs->options);
5a8a30db 2651
140fd5a6 2652 flags &= ~BDRV_O_INACTIVE;
2b148f39 2653 qemu_co_mutex_lock(&s->lock);
4e4bf5c4 2654 ret = qcow2_do_open(bs, options, flags, &local_err);
2b148f39 2655 qemu_co_mutex_unlock(&s->lock);
cb3e7f08 2656 qobject_unref(options);
5a8a30db 2657 if (local_err) {
4b576648
MA
2658 error_propagate_prepend(errp, local_err,
2659 "Could not reopen qcow2 layer: ");
191fb11b 2660 bs->drv = NULL;
5a8a30db
KW
2661 return;
2662 } else if (ret < 0) {
2663 error_setg_errno(errp, -ret, "Could not reopen qcow2 layer");
191fb11b 2664 bs->drv = NULL;
5a8a30db
KW
2665 return;
2666 }
acdfb480 2667
b25b387f 2668 s->crypto = crypto;
06d9260f
AL
2669}
2670
e24e49e6
KW
2671static size_t header_ext_add(char *buf, uint32_t magic, const void *s,
2672 size_t len, size_t buflen)
2673{
2674 QCowExtension *ext_backing_fmt = (QCowExtension*) buf;
2675 size_t ext_len = sizeof(QCowExtension) + ((len + 7) & ~7);
2676
2677 if (buflen < ext_len) {
2678 return -ENOSPC;
2679 }
2680
2681 *ext_backing_fmt = (QCowExtension) {
2682 .magic = cpu_to_be32(magic),
2683 .len = cpu_to_be32(len),
2684 };
0647d47c
SH
2685
2686 if (len) {
2687 memcpy(buf + sizeof(QCowExtension), s, len);
2688 }
e24e49e6
KW
2689
2690 return ext_len;
2691}
2692
756e6736 2693/*
e24e49e6
KW
2694 * Updates the qcow2 header, including the variable length parts of it, i.e.
2695 * the backing file name and all extensions. qcow2 was not designed to allow
2696 * such changes, so if we run out of space (we can only use the first cluster)
2697 * this function may fail.
756e6736
KW
2698 *
2699 * Returns 0 on success, -errno in error cases.
2700 */
e24e49e6 2701int qcow2_update_header(BlockDriverState *bs)
756e6736 2702{
ff99129a 2703 BDRVQcow2State *s = bs->opaque;
e24e49e6
KW
2704 QCowHeader *header;
2705 char *buf;
2706 size_t buflen = s->cluster_size;
756e6736 2707 int ret;
e24e49e6
KW
2708 uint64_t total_size;
2709 uint32_t refcount_table_clusters;
6744cbab 2710 size_t header_length;
75bab85c 2711 Qcow2UnknownHeaderExtension *uext;
756e6736 2712
e24e49e6 2713 buf = qemu_blockalign(bs, buflen);
756e6736 2714
e24e49e6
KW
2715 /* Header structure */
2716 header = (QCowHeader*) buf;
756e6736 2717
e24e49e6
KW
2718 if (buflen < sizeof(*header)) {
2719 ret = -ENOSPC;
2720 goto fail;
756e6736
KW
2721 }
2722
6744cbab 2723 header_length = sizeof(*header) + s->unknown_header_fields_size;
e24e49e6
KW
2724 total_size = bs->total_sectors * BDRV_SECTOR_SIZE;
2725 refcount_table_clusters = s->refcount_table_size >> (s->cluster_bits - 3);
2726
2727 *header = (QCowHeader) {
6744cbab 2728 /* Version 2 fields */
e24e49e6 2729 .magic = cpu_to_be32(QCOW_MAGIC),
6744cbab 2730 .version = cpu_to_be32(s->qcow_version),
e24e49e6
KW
2731 .backing_file_offset = 0,
2732 .backing_file_size = 0,
2733 .cluster_bits = cpu_to_be32(s->cluster_bits),
2734 .size = cpu_to_be64(total_size),
2735 .crypt_method = cpu_to_be32(s->crypt_method_header),
2736 .l1_size = cpu_to_be32(s->l1_size),
2737 .l1_table_offset = cpu_to_be64(s->l1_table_offset),
2738 .refcount_table_offset = cpu_to_be64(s->refcount_table_offset),
2739 .refcount_table_clusters = cpu_to_be32(refcount_table_clusters),
2740 .nb_snapshots = cpu_to_be32(s->nb_snapshots),
2741 .snapshots_offset = cpu_to_be64(s->snapshots_offset),
6744cbab
KW
2742
2743 /* Version 3 fields */
2744 .incompatible_features = cpu_to_be64(s->incompatible_features),
2745 .compatible_features = cpu_to_be64(s->compatible_features),
2746 .autoclear_features = cpu_to_be64(s->autoclear_features),
b6481f37 2747 .refcount_order = cpu_to_be32(s->refcount_order),
6744cbab 2748 .header_length = cpu_to_be32(header_length),
e24e49e6 2749 };
756e6736 2750
6744cbab
KW
2751 /* For older versions, write a shorter header */
2752 switch (s->qcow_version) {
2753 case 2:
2754 ret = offsetof(QCowHeader, incompatible_features);
2755 break;
2756 case 3:
2757 ret = sizeof(*header);
2758 break;
2759 default:
b6c14762
JM
2760 ret = -EINVAL;
2761 goto fail;
6744cbab
KW
2762 }
2763
2764 buf += ret;
2765 buflen -= ret;
2766 memset(buf, 0, buflen);
2767
2768 /* Preserve any unknown field in the header */
2769 if (s->unknown_header_fields_size) {
2770 if (buflen < s->unknown_header_fields_size) {
2771 ret = -ENOSPC;
2772 goto fail;
2773 }
2774
2775 memcpy(buf, s->unknown_header_fields, s->unknown_header_fields_size);
2776 buf += s->unknown_header_fields_size;
2777 buflen -= s->unknown_header_fields_size;
2778 }
756e6736 2779
e24e49e6 2780 /* Backing file format header extension */
e4603fe1 2781 if (s->image_backing_format) {
e24e49e6 2782 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BACKING_FORMAT,
e4603fe1
KW
2783 s->image_backing_format,
2784 strlen(s->image_backing_format),
e24e49e6
KW
2785 buflen);
2786 if (ret < 0) {
2787 goto fail;
756e6736
KW
2788 }
2789
e24e49e6
KW
2790 buf += ret;
2791 buflen -= ret;
756e6736
KW
2792 }
2793
9b890bdc
KW
2794 /* External data file header extension */
2795 if (has_data_file(bs) && s->image_data_file) {
2796 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_DATA_FILE,
2797 s->image_data_file, strlen(s->image_data_file),
2798 buflen);
2799 if (ret < 0) {
2800 goto fail;
2801 }
2802
2803 buf += ret;
2804 buflen -= ret;
2805 }
2806
4652b8f3
DB
2807 /* Full disk encryption header pointer extension */
2808 if (s->crypto_header.offset != 0) {
3b698f52
PM
2809 s->crypto_header.offset = cpu_to_be64(s->crypto_header.offset);
2810 s->crypto_header.length = cpu_to_be64(s->crypto_header.length);
4652b8f3
DB
2811 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_CRYPTO_HEADER,
2812 &s->crypto_header, sizeof(s->crypto_header),
2813 buflen);
3b698f52
PM
2814 s->crypto_header.offset = be64_to_cpu(s->crypto_header.offset);
2815 s->crypto_header.length = be64_to_cpu(s->crypto_header.length);
4652b8f3
DB
2816 if (ret < 0) {
2817 goto fail;
2818 }
2819 buf += ret;
2820 buflen -= ret;
2821 }
2822
cfcc4c62 2823 /* Feature table */
1a4828c7
KW
2824 if (s->qcow_version >= 3) {
2825 Qcow2Feature features[] = {
2826 {
2827 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
2828 .bit = QCOW2_INCOMPAT_DIRTY_BITNR,
2829 .name = "dirty bit",
2830 },
2831 {
2832 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
2833 .bit = QCOW2_INCOMPAT_CORRUPT_BITNR,
2834 .name = "corrupt bit",
2835 },
93c24936
KW
2836 {
2837 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
2838 .bit = QCOW2_INCOMPAT_DATA_FILE_BITNR,
2839 .name = "external data file",
2840 },
1a4828c7
KW
2841 {
2842 .type = QCOW2_FEAT_TYPE_COMPATIBLE,
2843 .bit = QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR,
2844 .name = "lazy refcounts",
2845 },
2846 };
2847
2848 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_FEATURE_TABLE,
2849 features, sizeof(features), buflen);
2850 if (ret < 0) {
2851 goto fail;
2852 }
2853 buf += ret;
2854 buflen -= ret;
cfcc4c62 2855 }
cfcc4c62 2856
88ddffae
VSO
2857 /* Bitmap extension */
2858 if (s->nb_bitmaps > 0) {
2859 Qcow2BitmapHeaderExt bitmaps_header = {
2860 .nb_bitmaps = cpu_to_be32(s->nb_bitmaps),
2861 .bitmap_directory_size =
2862 cpu_to_be64(s->bitmap_directory_size),
2863 .bitmap_directory_offset =
2864 cpu_to_be64(s->bitmap_directory_offset)
2865 };
2866 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BITMAPS,
2867 &bitmaps_header, sizeof(bitmaps_header),
2868 buflen);
2869 if (ret < 0) {
2870 goto fail;
2871 }
2872 buf += ret;
2873 buflen -= ret;
2874 }
2875
75bab85c
KW
2876 /* Keep unknown header extensions */
2877 QLIST_FOREACH(uext, &s->unknown_header_ext, next) {
2878 ret = header_ext_add(buf, uext->magic, uext->data, uext->len, buflen);
2879 if (ret < 0) {
2880 goto fail;
2881 }
2882
2883 buf += ret;
2884 buflen -= ret;
2885 }
2886
e24e49e6
KW
2887 /* End of header extensions */
2888 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_END, NULL, 0, buflen);
756e6736
KW
2889 if (ret < 0) {
2890 goto fail;
2891 }
2892
e24e49e6
KW
2893 buf += ret;
2894 buflen -= ret;
756e6736 2895
e24e49e6 2896 /* Backing file name */
e4603fe1
KW
2897 if (s->image_backing_file) {
2898 size_t backing_file_len = strlen(s->image_backing_file);
e24e49e6
KW
2899
2900 if (buflen < backing_file_len) {
2901 ret = -ENOSPC;
2902 goto fail;
2903 }
2904
00ea1881 2905 /* Using strncpy is ok here, since buf is not NUL-terminated. */
e4603fe1 2906 strncpy(buf, s->image_backing_file, buflen);
e24e49e6
KW
2907
2908 header->backing_file_offset = cpu_to_be64(buf - ((char*) header));
2909 header->backing_file_size = cpu_to_be32(backing_file_len);
756e6736
KW
2910 }
2911
e24e49e6 2912 /* Write the new header */
d9ca2ea2 2913 ret = bdrv_pwrite(bs->file, 0, header, s->cluster_size);
756e6736
KW
2914 if (ret < 0) {
2915 goto fail;
2916 }
2917
2918 ret = 0;
2919fail:
e24e49e6 2920 qemu_vfree(header);
756e6736
KW
2921 return ret;
2922}
2923
2924static int qcow2_change_backing_file(BlockDriverState *bs,
2925 const char *backing_file, const char *backing_fmt)
2926{
ff99129a 2927 BDRVQcow2State *s = bs->opaque;
e4603fe1 2928
6c3944dc
KW
2929 /* Adding a backing file means that the external data file alone won't be
2930 * enough to make sense of the content */
2931 if (backing_file && data_file_is_raw(bs)) {
2932 return -EINVAL;
2933 }
2934
4e876bcf
HR
2935 if (backing_file && strlen(backing_file) > 1023) {
2936 return -EINVAL;
2937 }
2938
998c2019
HR
2939 pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
2940 backing_file ?: "");
e24e49e6
KW
2941 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
2942 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
2943
e4603fe1
KW
2944 g_free(s->image_backing_file);
2945 g_free(s->image_backing_format);
2946
2947 s->image_backing_file = backing_file ? g_strdup(bs->backing_file) : NULL;
2948 s->image_backing_format = backing_fmt ? g_strdup(bs->backing_format) : NULL;
2949
e24e49e6 2950 return qcow2_update_header(bs);
756e6736
KW
2951}
2952
4652b8f3
DB
2953static int qcow2_crypt_method_from_format(const char *encryptfmt)
2954{
2955 if (g_str_equal(encryptfmt, "luks")) {
2956 return QCOW_CRYPT_LUKS;
2957 } else if (g_str_equal(encryptfmt, "aes")) {
2958 return QCOW_CRYPT_AES;
2959 } else {
2960 return -EINVAL;
2961 }
2962}
b25b387f 2963
60900b7b
KW
2964static int qcow2_set_up_encryption(BlockDriverState *bs,
2965 QCryptoBlockCreateOptions *cryptoopts,
2966 Error **errp)
2967{
2968 BDRVQcow2State *s = bs->opaque;
2969 QCryptoBlock *crypto = NULL;
2970 int fmt, ret;
2971
2972 switch (cryptoopts->format) {
2973 case Q_CRYPTO_BLOCK_FORMAT_LUKS:
2974 fmt = QCOW_CRYPT_LUKS;
2975 break;
2976 case Q_CRYPTO_BLOCK_FORMAT_QCOW:
2977 fmt = QCOW_CRYPT_AES;
2978 break;
2979 default:
2980 error_setg(errp, "Crypto format not supported in qcow2");
2981 return -EINVAL;
b25b387f 2982 }
60900b7b 2983
4652b8f3 2984 s->crypt_method_header = fmt;
b25b387f 2985
1cd9a787 2986 crypto = qcrypto_block_create(cryptoopts, "encrypt.",
4652b8f3
DB
2987 qcow2_crypto_hdr_init_func,
2988 qcow2_crypto_hdr_write_func,
b25b387f
DB
2989 bs, errp);
2990 if (!crypto) {
60900b7b 2991 return -EINVAL;
b25b387f
DB
2992 }
2993
2994 ret = qcow2_update_header(bs);
2995 if (ret < 0) {
2996 error_setg_errno(errp, -ret, "Could not write encryption header");
2997 goto out;
2998 }
2999
60900b7b 3000 ret = 0;
b25b387f 3001 out:
b25b387f 3002 qcrypto_block_free(crypto);
b25b387f
DB
3003 return ret;
3004}
3005
7bc45dc1
HR
3006/**
3007 * Preallocates metadata structures for data clusters between @offset (in the
3008 * guest disk) and @new_length (which is thus generally the new guest disk
3009 * size).
3010 *
3011 * Returns: 0 on success, -errno on failure.
3012 */
47e86b86 3013static int coroutine_fn preallocate_co(BlockDriverState *bs, uint64_t offset,
718c0fce
KW
3014 uint64_t new_length, PreallocMode mode,
3015 Error **errp)
a35e1c17 3016{
93e32b3e 3017 BDRVQcow2State *s = bs->opaque;
d46a0bb2 3018 uint64_t bytes;
060bee89 3019 uint64_t host_offset = 0;
718c0fce 3020 int64_t file_length;
d46a0bb2 3021 unsigned int cur_bytes;
148da7ea 3022 int ret;
f50f88b9 3023 QCowL2Meta *meta;
a35e1c17 3024
7bc45dc1
HR
3025 assert(offset <= new_length);
3026 bytes = new_length - offset;
a35e1c17 3027
d46a0bb2 3028 while (bytes) {
f29fbf7c 3029 cur_bytes = MIN(bytes, QEMU_ALIGN_DOWN(INT_MAX, s->cluster_size));
d46a0bb2 3030 ret = qcow2_alloc_cluster_offset(bs, offset, &cur_bytes,
060bee89 3031 &host_offset, &meta);
148da7ea 3032 if (ret < 0) {
360bd074 3033 error_setg_errno(errp, -ret, "Allocating clusters failed");
47e86b86 3034 return ret;
a35e1c17
KW
3035 }
3036
c792707f
SH
3037 while (meta) {
3038 QCowL2Meta *next = meta->next;
3039
7c2bbf4a
HT
3040 ret = qcow2_alloc_cluster_link_l2(bs, meta);
3041 if (ret < 0) {
360bd074 3042 error_setg_errno(errp, -ret, "Mapping clusters failed");
7c2bbf4a
HT
3043 qcow2_free_any_clusters(bs, meta->alloc_offset,
3044 meta->nb_clusters, QCOW2_DISCARD_NEVER);
47e86b86 3045 return ret;
7c2bbf4a
HT
3046 }
3047
3048 /* There are no dependent requests, but we need to remove our
3049 * request from the list of in-flight requests */
4e95314e 3050 QLIST_REMOVE(meta, next_in_flight);
c792707f
SH
3051
3052 g_free(meta);
3053 meta = next;
f50f88b9 3054 }
f214978a 3055
a35e1c17
KW
3056 /* TODO Preallocate data if requested */
3057
d46a0bb2
KW
3058 bytes -= cur_bytes;
3059 offset += cur_bytes;
a35e1c17
KW
3060 }
3061
3062 /*
3063 * It is expected that the image file is large enough to actually contain
3064 * all of the allocated clusters (otherwise we get failing reads after
3065 * EOF). Extend the image to the last allocated sector.
3066 */
718c0fce
KW
3067 file_length = bdrv_getlength(s->data_file->bs);
3068 if (file_length < 0) {
3069 error_setg_errno(errp, -file_length, "Could not get file size");
3070 return file_length;
3071 }
3072
3073 if (host_offset + cur_bytes > file_length) {
3074 if (mode == PREALLOC_MODE_METADATA) {
3075 mode = PREALLOC_MODE_OFF;
3076 }
3077 ret = bdrv_co_truncate(s->data_file, host_offset + cur_bytes, mode,
3078 errp);
19dbcbf7 3079 if (ret < 0) {
47e86b86 3080 return ret;
19dbcbf7 3081 }
a35e1c17
KW
3082 }
3083
47e86b86 3084 return 0;
a35e1c17
KW
3085}
3086
7c5bcc42
SH
3087/* qcow2_refcount_metadata_size:
3088 * @clusters: number of clusters to refcount (including data and L1/L2 tables)
3089 * @cluster_size: size of a cluster, in bytes
3090 * @refcount_order: refcount bits power-of-2 exponent
12cc30a8
HR
3091 * @generous_increase: allow for the refcount table to be 1.5x as large as it
3092 * needs to be
7c5bcc42
SH
3093 *
3094 * Returns: Number of bytes required for refcount blocks and table metadata.
3095 */
12cc30a8
HR
3096int64_t qcow2_refcount_metadata_size(int64_t clusters, size_t cluster_size,
3097 int refcount_order, bool generous_increase,
3098 uint64_t *refblock_count)
7c5bcc42
SH
3099{
3100 /*
3101 * Every host cluster is reference-counted, including metadata (even
3102 * refcount metadata is recursively included).
3103 *
3104 * An accurate formula for the size of refcount metadata size is difficult
3105 * to derive. An easier method of calculation is finding the fixed point
3106 * where no further refcount blocks or table clusters are required to
3107 * reference count every cluster.
3108 */
3109 int64_t blocks_per_table_cluster = cluster_size / sizeof(uint64_t);
3110 int64_t refcounts_per_block = cluster_size * 8 / (1 << refcount_order);
3111 int64_t table = 0; /* number of refcount table clusters */
3112 int64_t blocks = 0; /* number of refcount block clusters */
3113 int64_t last;
3114 int64_t n = 0;
3115
3116 do {
3117 last = n;
3118 blocks = DIV_ROUND_UP(clusters + table + blocks, refcounts_per_block);
3119 table = DIV_ROUND_UP(blocks, blocks_per_table_cluster);
3120 n = clusters + blocks + table;
12cc30a8
HR
3121
3122 if (n == last && generous_increase) {
3123 clusters += DIV_ROUND_UP(table, 2);
3124 n = 0; /* force another loop */
3125 generous_increase = false;
3126 }
7c5bcc42
SH
3127 } while (n != last);
3128
12cc30a8
HR
3129 if (refblock_count) {
3130 *refblock_count = blocks;
3131 }
3132
7c5bcc42
SH
3133 return (blocks + table) * cluster_size;
3134}
3135
95c67e3b
SH
3136/**
3137 * qcow2_calc_prealloc_size:
3138 * @total_size: virtual disk size in bytes
3139 * @cluster_size: cluster size in bytes
3140 * @refcount_order: refcount bits power-of-2 exponent
3141 *
3142 * Returns: Total number of bytes required for the fully allocated image
3143 * (including metadata).
3144 */
3145static int64_t qcow2_calc_prealloc_size(int64_t total_size,
3146 size_t cluster_size,
3147 int refcount_order)
3148{
95c67e3b 3149 int64_t meta_size = 0;
7c5bcc42 3150 uint64_t nl1e, nl2e;
9e029689 3151 int64_t aligned_total_size = ROUND_UP(total_size, cluster_size);
95c67e3b
SH
3152
3153 /* header: 1 cluster */
3154 meta_size += cluster_size;
3155
3156 /* total size of L2 tables */
3157 nl2e = aligned_total_size / cluster_size;
9e029689 3158 nl2e = ROUND_UP(nl2e, cluster_size / sizeof(uint64_t));
95c67e3b
SH
3159 meta_size += nl2e * sizeof(uint64_t);
3160
3161 /* total size of L1 tables */
3162 nl1e = nl2e * sizeof(uint64_t) / cluster_size;
9e029689 3163 nl1e = ROUND_UP(nl1e, cluster_size / sizeof(uint64_t));
95c67e3b
SH
3164 meta_size += nl1e * sizeof(uint64_t);
3165
7c5bcc42
SH
3166 /* total size of refcount table and blocks */
3167 meta_size += qcow2_refcount_metadata_size(
3168 (meta_size + aligned_total_size) / cluster_size,
12cc30a8 3169 cluster_size, refcount_order, false, NULL);
95c67e3b
SH
3170
3171 return meta_size + aligned_total_size;
3172}
3173
29ca9e45 3174static bool validate_cluster_size(size_t cluster_size, Error **errp)
a9420734 3175{
29ca9e45 3176 int cluster_bits = ctz32(cluster_size);
a9420734
KW
3177 if (cluster_bits < MIN_CLUSTER_BITS || cluster_bits > MAX_CLUSTER_BITS ||
3178 (1 << cluster_bits) != cluster_size)
3179 {
3ef6c40a
HR
3180 error_setg(errp, "Cluster size must be a power of two between %d and "
3181 "%dk", 1 << MIN_CLUSTER_BITS, 1 << (MAX_CLUSTER_BITS - 10));
29ca9e45
KW
3182 return false;
3183 }
3184 return true;
3185}
3186
3187static size_t qcow2_opt_get_cluster_size_del(QemuOpts *opts, Error **errp)
3188{
3189 size_t cluster_size;
3190
3191 cluster_size = qemu_opt_get_size_del(opts, BLOCK_OPT_CLUSTER_SIZE,
3192 DEFAULT_CLUSTER_SIZE);
3193 if (!validate_cluster_size(cluster_size, errp)) {
0eb4a8c1
SH
3194 return 0;
3195 }
3196 return cluster_size;
3197}
3198
3199static int qcow2_opt_get_version_del(QemuOpts *opts, Error **errp)
3200{
3201 char *buf;
3202 int ret;
3203
3204 buf = qemu_opt_get_del(opts, BLOCK_OPT_COMPAT_LEVEL);
3205 if (!buf) {
3206 ret = 3; /* default */
3207 } else if (!strcmp(buf, "0.10")) {
3208 ret = 2;
3209 } else if (!strcmp(buf, "1.1")) {
3210 ret = 3;
3211 } else {
3212 error_setg(errp, "Invalid compatibility level: '%s'", buf);
3213 ret = -EINVAL;
3214 }
3215 g_free(buf);
3216 return ret;
3217}
3218
3219static uint64_t qcow2_opt_get_refcount_bits_del(QemuOpts *opts, int version,
3220 Error **errp)
3221{
3222 uint64_t refcount_bits;
3223
3224 refcount_bits = qemu_opt_get_number_del(opts, BLOCK_OPT_REFCOUNT_BITS, 16);
3225 if (refcount_bits > 64 || !is_power_of_2(refcount_bits)) {
3226 error_setg(errp, "Refcount width must be a power of two and may not "
3227 "exceed 64 bits");
3228 return 0;
3229 }
3230
3231 if (version < 3 && refcount_bits != 16) {
3232 error_setg(errp, "Different refcount widths than 16 bits require "
3233 "compatibility level 1.1 or above (use compat=1.1 or "
3234 "greater)");
3235 return 0;
a9420734
KW
3236 }
3237
0eb4a8c1
SH
3238 return refcount_bits;
3239}
3240
c274393a 3241static int coroutine_fn
60900b7b 3242qcow2_co_create(BlockdevCreateOptions *create_options, Error **errp)
0eb4a8c1 3243{
29ca9e45 3244 BlockdevCreateOptionsQcow2 *qcow2_opts;
0eb4a8c1
SH
3245 QDict *options;
3246
a9420734
KW
3247 /*
3248 * Open the image file and write a minimal qcow2 header.
3249 *
3250 * We keep things simple and start with a zero-sized image. We also
3251 * do without refcount blocks or a L1 table for now. We'll fix the
3252 * inconsistency later.
3253 *
3254 * We do need a refcount table because growing the refcount table means
3255 * allocating two new refcount blocks - the seconds of which would be at
3256 * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
3257 * size for any qcow2 image.
3258 */
e1d74bc6
KW
3259 BlockBackend *blk = NULL;
3260 BlockDriverState *bs = NULL;
dcc98687 3261 BlockDriverState *data_bs = NULL;
f8413b3c 3262 QCowHeader *header;
29ca9e45
KW
3263 size_t cluster_size;
3264 int version;
3265 int refcount_order;
b106ad91 3266 uint64_t* refcount_table;
3ef6c40a 3267 Error *local_err = NULL;
a9420734
KW
3268 int ret;
3269
29ca9e45
KW
3270 assert(create_options->driver == BLOCKDEV_DRIVER_QCOW2);
3271 qcow2_opts = &create_options->u.qcow2;
3272
e1d74bc6
KW
3273 bs = bdrv_open_blockdev_ref(qcow2_opts->file, errp);
3274 if (bs == NULL) {
3275 return -EIO;
3276 }
3277
3278 /* Validate options and set default values */
29ca9e45
KW
3279 if (!QEMU_IS_ALIGNED(qcow2_opts->size, BDRV_SECTOR_SIZE)) {
3280 error_setg(errp, "Image size must be a multiple of 512 bytes");
3281 ret = -EINVAL;
3282 goto out;
3283 }
3284
3285 if (qcow2_opts->has_version) {
3286 switch (qcow2_opts->version) {
3287 case BLOCKDEV_QCOW2_VERSION_V2:
3288 version = 2;
3289 break;
3290 case BLOCKDEV_QCOW2_VERSION_V3:
3291 version = 3;
3292 break;
3293 default:
3294 g_assert_not_reached();
3295 }
3296 } else {
3297 version = 3;
3298 }
3299
3300 if (qcow2_opts->has_cluster_size) {
3301 cluster_size = qcow2_opts->cluster_size;
3302 } else {
3303 cluster_size = DEFAULT_CLUSTER_SIZE;
3304 }
3305
3306 if (!validate_cluster_size(cluster_size, errp)) {
e1d74bc6
KW
3307 ret = -EINVAL;
3308 goto out;
29ca9e45
KW
3309 }
3310
3311 if (!qcow2_opts->has_preallocation) {
3312 qcow2_opts->preallocation = PREALLOC_MODE_OFF;
3313 }
3314 if (qcow2_opts->has_backing_file &&
3315 qcow2_opts->preallocation != PREALLOC_MODE_OFF)
3316 {
3317 error_setg(errp, "Backing file and preallocation cannot be used at "
3318 "the same time");
e1d74bc6
KW
3319 ret = -EINVAL;
3320 goto out;
29ca9e45
KW
3321 }
3322 if (qcow2_opts->has_backing_fmt && !qcow2_opts->has_backing_file) {
3323 error_setg(errp, "Backing format cannot be used without backing file");
e1d74bc6
KW
3324 ret = -EINVAL;
3325 goto out;
29ca9e45
KW
3326 }
3327
3328 if (!qcow2_opts->has_lazy_refcounts) {
3329 qcow2_opts->lazy_refcounts = false;
3330 }
3331 if (version < 3 && qcow2_opts->lazy_refcounts) {
3332 error_setg(errp, "Lazy refcounts only supported with compatibility "
b76b4f60 3333 "level 1.1 and above (use version=v3 or greater)");
e1d74bc6
KW
3334 ret = -EINVAL;
3335 goto out;
29ca9e45
KW
3336 }
3337
3338 if (!qcow2_opts->has_refcount_bits) {
3339 qcow2_opts->refcount_bits = 16;
3340 }
3341 if (qcow2_opts->refcount_bits > 64 ||
3342 !is_power_of_2(qcow2_opts->refcount_bits))
3343 {
3344 error_setg(errp, "Refcount width must be a power of two and may not "
3345 "exceed 64 bits");
e1d74bc6
KW
3346 ret = -EINVAL;
3347 goto out;
29ca9e45
KW
3348 }
3349 if (version < 3 && qcow2_opts->refcount_bits != 16) {
3350 error_setg(errp, "Different refcount widths than 16 bits require "
b76b4f60 3351 "compatibility level 1.1 or above (use version=v3 or "
29ca9e45 3352 "greater)");
e1d74bc6
KW
3353 ret = -EINVAL;
3354 goto out;
29ca9e45
KW
3355 }
3356 refcount_order = ctz32(qcow2_opts->refcount_bits);
3357
6c3944dc
KW
3358 if (qcow2_opts->data_file_raw && !qcow2_opts->data_file) {
3359 error_setg(errp, "data-file-raw requires data-file");
3360 ret = -EINVAL;
3361 goto out;
3362 }
3363 if (qcow2_opts->data_file_raw && qcow2_opts->has_backing_file) {
3364 error_setg(errp, "Backing file and data-file-raw cannot be used at "
3365 "the same time");
3366 ret = -EINVAL;
3367 goto out;
3368 }
3369
dcc98687
KW
3370 if (qcow2_opts->data_file) {
3371 if (version < 3) {
3372 error_setg(errp, "External data files are only supported with "
3373 "compatibility level 1.1 and above (use version=v3 or "
3374 "greater)");
3375 ret = -EINVAL;
3376 goto out;
3377 }
3378 data_bs = bdrv_open_blockdev_ref(qcow2_opts->data_file, errp);
a0cf8363 3379 if (data_bs == NULL) {
dcc98687
KW
3380 ret = -EIO;
3381 goto out;
3382 }
3383 }
29ca9e45
KW
3384
3385 /* Create BlockBackend to write to the image */
d861ab3a
KW
3386 blk = blk_new(bdrv_get_aio_context(bs),
3387 BLK_PERM_WRITE | BLK_PERM_RESIZE, BLK_PERM_ALL);
cbf2b7c4 3388 ret = blk_insert_bs(blk, bs, errp);
a9420734 3389 if (ret < 0) {
cbf2b7c4 3390 goto out;
a9420734 3391 }
23588797
KW
3392 blk_set_allow_write_beyond_eof(blk, true);
3393
a9420734 3394 /* Write the header */
f8413b3c
KW
3395 QEMU_BUILD_BUG_ON((1 << MIN_CLUSTER_BITS) < sizeof(*header));
3396 header = g_malloc0(cluster_size);
3397 *header = (QCowHeader) {
3398 .magic = cpu_to_be32(QCOW_MAGIC),
3399 .version = cpu_to_be32(version),
0eb4a8c1 3400 .cluster_bits = cpu_to_be32(ctz32(cluster_size)),
f8413b3c
KW
3401 .size = cpu_to_be64(0),
3402 .l1_table_offset = cpu_to_be64(0),
3403 .l1_size = cpu_to_be32(0),
3404 .refcount_table_offset = cpu_to_be64(cluster_size),
3405 .refcount_table_clusters = cpu_to_be32(1),
bd4b167f 3406 .refcount_order = cpu_to_be32(refcount_order),
f8413b3c
KW
3407 .header_length = cpu_to_be32(sizeof(*header)),
3408 };
a9420734 3409
b25b387f
DB
3410 /* We'll update this to correct value later */
3411 header->crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
a9420734 3412
29ca9e45 3413 if (qcow2_opts->lazy_refcounts) {
f8413b3c 3414 header->compatible_features |=
bfe8043e
SH
3415 cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS);
3416 }
dcc98687
KW
3417 if (data_bs) {
3418 header->incompatible_features |=
3419 cpu_to_be64(QCOW2_INCOMPAT_DATA_FILE);
3420 }
6c3944dc
KW
3421 if (qcow2_opts->data_file_raw) {
3422 header->autoclear_features |=
3423 cpu_to_be64(QCOW2_AUTOCLEAR_DATA_FILE_RAW);
3424 }
bfe8043e 3425
8341f00d 3426 ret = blk_pwrite(blk, 0, header, cluster_size, 0);
f8413b3c 3427 g_free(header);
a9420734 3428 if (ret < 0) {
3ef6c40a 3429 error_setg_errno(errp, -ret, "Could not write qcow2 header");
a9420734
KW
3430 goto out;
3431 }
3432
b106ad91
KW
3433 /* Write a refcount table with one refcount block */
3434 refcount_table = g_malloc0(2 * cluster_size);
3435 refcount_table[0] = cpu_to_be64(2 * cluster_size);
8341f00d 3436 ret = blk_pwrite(blk, cluster_size, refcount_table, 2 * cluster_size, 0);
7267c094 3437 g_free(refcount_table);
a9420734
KW
3438
3439 if (ret < 0) {
3ef6c40a 3440 error_setg_errno(errp, -ret, "Could not write refcount table");
a9420734
KW
3441 goto out;
3442 }
3443
23588797
KW
3444 blk_unref(blk);
3445 blk = NULL;
a9420734
KW
3446
3447 /*
3448 * And now open the image and make it consistent first (i.e. increase the
3449 * refcount of the cluster that is occupied by the header and the refcount
3450 * table)
3451 */
e6641719 3452 options = qdict_new();
46f5ac20 3453 qdict_put_str(options, "driver", "qcow2");
cbf2b7c4 3454 qdict_put_str(options, "file", bs->node_name);
dcc98687
KW
3455 if (data_bs) {
3456 qdict_put_str(options, "data-file", data_bs->node_name);
3457 }
cbf2b7c4 3458 blk = blk_new_open(NULL, NULL, options,
55880601
KW
3459 BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_NO_FLUSH,
3460 &local_err);
23588797 3461 if (blk == NULL) {
3ef6c40a 3462 error_propagate(errp, local_err);
23588797 3463 ret = -EIO;
a9420734
KW
3464 goto out;
3465 }
3466
23588797 3467 ret = qcow2_alloc_clusters(blk_bs(blk), 3 * cluster_size);
a9420734 3468 if (ret < 0) {
3ef6c40a
HR
3469 error_setg_errno(errp, -ret, "Could not allocate clusters for qcow2 "
3470 "header and refcount table");
a9420734
KW
3471 goto out;
3472
3473 } else if (ret != 0) {
3474 error_report("Huh, first cluster in empty image is already in use?");
3475 abort();
3476 }
3477
9b890bdc
KW
3478 /* Set the external data file if necessary */
3479 if (data_bs) {
3480 BDRVQcow2State *s = blk_bs(blk)->opaque;
3481 s->image_data_file = g_strdup(data_bs->filename);
3482 }
3483
b527c9b3 3484 /* Create a full header (including things like feature table) */
23588797 3485 ret = qcow2_update_header(blk_bs(blk));
b527c9b3
KW
3486 if (ret < 0) {
3487 error_setg_errno(errp, -ret, "Could not update qcow2 header");
3488 goto out;
3489 }
3490
a9420734 3491 /* Okay, now that we have a valid image, let's give it the right size */
c5e86ebc 3492 ret = blk_truncate(blk, qcow2_opts->size, qcow2_opts->preallocation, errp);
a9420734 3493 if (ret < 0) {
ed3d2ec9 3494 error_prepend(errp, "Could not resize image: ");
a9420734
KW
3495 goto out;
3496 }
3497
3498 /* Want a backing file? There you go.*/
29ca9e45
KW
3499 if (qcow2_opts->has_backing_file) {
3500 const char *backing_format = NULL;
3501
3502 if (qcow2_opts->has_backing_fmt) {
3503 backing_format = BlockdevDriver_str(qcow2_opts->backing_fmt);
3504 }
3505
3506 ret = bdrv_change_backing_file(blk_bs(blk), qcow2_opts->backing_file,
3507 backing_format);
a9420734 3508 if (ret < 0) {
3ef6c40a 3509 error_setg_errno(errp, -ret, "Could not assign backing file '%s' "
29ca9e45
KW
3510 "with format '%s'", qcow2_opts->backing_file,
3511 backing_format);
a9420734
KW
3512 goto out;
3513 }
3514 }
3515
b25b387f 3516 /* Want encryption? There you go. */
60900b7b
KW
3517 if (qcow2_opts->has_encrypt) {
3518 ret = qcow2_set_up_encryption(blk_bs(blk), qcow2_opts->encrypt, errp);
b25b387f
DB
3519 if (ret < 0) {
3520 goto out;
3521 }
3522 }
3523
23588797
KW
3524 blk_unref(blk);
3525 blk = NULL;
ba2ab2f2 3526
b25b387f
DB
3527 /* Reopen the image without BDRV_O_NO_FLUSH to flush it before returning.
3528 * Using BDRV_O_NO_IO, since encryption is now setup we don't want to
3529 * have to setup decryption context. We're not doing any I/O on the top
3530 * level BlockDriverState, only lower layers, where BDRV_O_NO_IO does
3531 * not have effect.
3532 */
e6641719 3533 options = qdict_new();
46f5ac20 3534 qdict_put_str(options, "driver", "qcow2");
cbf2b7c4 3535 qdict_put_str(options, "file", bs->node_name);
dcc98687
KW
3536 if (data_bs) {
3537 qdict_put_str(options, "data-file", data_bs->node_name);
3538 }
cbf2b7c4 3539 blk = blk_new_open(NULL, NULL, options,
b25b387f
DB
3540 BDRV_O_RDWR | BDRV_O_NO_BACKING | BDRV_O_NO_IO,
3541 &local_err);
23588797 3542 if (blk == NULL) {
ba2ab2f2 3543 error_propagate(errp, local_err);
23588797 3544 ret = -EIO;
ba2ab2f2
HR
3545 goto out;
3546 }
3547
a9420734
KW
3548 ret = 0;
3549out:
e1d74bc6
KW
3550 blk_unref(blk);
3551 bdrv_unref(bs);
dcc98687 3552 bdrv_unref(data_bs);
a9420734
KW
3553 return ret;
3554}
de5f3f40 3555
efc75e2a
SH
3556static int coroutine_fn qcow2_co_create_opts(const char *filename, QemuOpts *opts,
3557 Error **errp)
de5f3f40 3558{
b76b4f60 3559 BlockdevCreateOptions *create_options = NULL;
92adf9db 3560 QDict *qdict;
b76b4f60 3561 Visitor *v;
cbf2b7c4 3562 BlockDriverState *bs = NULL;
9b890bdc 3563 BlockDriverState *data_bs = NULL;
3ef6c40a 3564 Error *local_err = NULL;
b76b4f60 3565 const char *val;
3ef6c40a 3566 int ret;
de5f3f40 3567
b76b4f60
KW
3568 /* Only the keyval visitor supports the dotted syntax needed for
3569 * encryption, so go through a QDict before getting a QAPI type. Ignore
3570 * options meant for the protocol layer so that the visitor doesn't
3571 * complain. */
3572 qdict = qemu_opts_to_qdict_filtered(opts, NULL, bdrv_qcow2.create_opts,
3573 true);
3574
3575 /* Handle encryption options */
3576 val = qdict_get_try_str(qdict, BLOCK_OPT_ENCRYPT);
3577 if (val && !strcmp(val, "on")) {
3578 qdict_put_str(qdict, BLOCK_OPT_ENCRYPT, "qcow");
3579 } else if (val && !strcmp(val, "off")) {
3580 qdict_del(qdict, BLOCK_OPT_ENCRYPT);
3581 }
3582
3583 val = qdict_get_try_str(qdict, BLOCK_OPT_ENCRYPT_FORMAT);
3584 if (val && !strcmp(val, "aes")) {
3585 qdict_put_str(qdict, BLOCK_OPT_ENCRYPT_FORMAT, "qcow");
3586 }
3587
3588 /* Convert compat=0.10/1.1 into compat=v2/v3, to be renamed into
3589 * version=v2/v3 below. */
3590 val = qdict_get_try_str(qdict, BLOCK_OPT_COMPAT_LEVEL);
3591 if (val && !strcmp(val, "0.10")) {
3592 qdict_put_str(qdict, BLOCK_OPT_COMPAT_LEVEL, "v2");
3593 } else if (val && !strcmp(val, "1.1")) {
3594 qdict_put_str(qdict, BLOCK_OPT_COMPAT_LEVEL, "v3");
3595 }
3596
3597 /* Change legacy command line options into QMP ones */
3598 static const QDictRenames opt_renames[] = {
3599 { BLOCK_OPT_BACKING_FILE, "backing-file" },
3600 { BLOCK_OPT_BACKING_FMT, "backing-fmt" },
3601 { BLOCK_OPT_CLUSTER_SIZE, "cluster-size" },
3602 { BLOCK_OPT_LAZY_REFCOUNTS, "lazy-refcounts" },
3603 { BLOCK_OPT_REFCOUNT_BITS, "refcount-bits" },
3604 { BLOCK_OPT_ENCRYPT, BLOCK_OPT_ENCRYPT_FORMAT },
3605 { BLOCK_OPT_COMPAT_LEVEL, "version" },
6c3944dc 3606 { BLOCK_OPT_DATA_FILE_RAW, "data-file-raw" },
b76b4f60
KW
3607 { NULL, NULL },
3608 };
3609
3610 if (!qdict_rename_keys(qdict, opt_renames, errp)) {
29ca9e45
KW
3611 ret = -EINVAL;
3612 goto finish;
3613 }
60900b7b 3614
b76b4f60
KW
3615 /* Create and open the file (protocol layer) */
3616 ret = bdrv_create_file(filename, opts, errp);
3617 if (ret < 0) {
0eb4a8c1
SH
3618 goto finish;
3619 }
b76b4f60
KW
3620
3621 bs = bdrv_open(filename, NULL, NULL,
3622 BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_PROTOCOL, errp);
3623 if (bs == NULL) {
3624 ret = -EIO;
1bd0e2d1
CL
3625 goto finish;
3626 }
0eb4a8c1 3627
9b890bdc
KW
3628 /* Create and open an external data file (protocol layer) */
3629 val = qdict_get_try_str(qdict, BLOCK_OPT_DATA_FILE);
3630 if (val) {
3631 ret = bdrv_create_file(val, opts, errp);
3632 if (ret < 0) {
3633 goto finish;
3634 }
3635
3636 data_bs = bdrv_open(val, NULL, NULL,
3637 BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_PROTOCOL,
3638 errp);
3639 if (data_bs == NULL) {
3640 ret = -EIO;
3641 goto finish;
3642 }
3643
3644 qdict_del(qdict, BLOCK_OPT_DATA_FILE);
3645 qdict_put_str(qdict, "data-file", data_bs->node_name);
3646 }
3647
b76b4f60
KW
3648 /* Set 'driver' and 'node' options */
3649 qdict_put_str(qdict, "driver", "qcow2");
3650 qdict_put_str(qdict, "file", bs->node_name);
3651
3652 /* Now get the QAPI type BlockdevCreateOptions */
af91062e
MA
3653 v = qobject_input_visitor_new_flat_confused(qdict, errp);
3654 if (!v) {
1bd0e2d1
CL
3655 ret = -EINVAL;
3656 goto finish;
3657 }
3658
b76b4f60
KW
3659 visit_type_BlockdevCreateOptions(v, NULL, &create_options, &local_err);
3660 visit_free(v);
de5f3f40 3661
0eb4a8c1
SH
3662 if (local_err) {
3663 error_propagate(errp, local_err);
bd4b167f
HR
3664 ret = -EINVAL;
3665 goto finish;
3666 }
3667
b76b4f60
KW
3668 /* Silently round up size */
3669 create_options->u.qcow2.size = ROUND_UP(create_options->u.qcow2.size,
3670 BDRV_SECTOR_SIZE);
cbf2b7c4
KW
3671
3672 /* Create the qcow2 image (format layer) */
b76b4f60 3673 ret = qcow2_co_create(create_options, errp);
cbf2b7c4
KW
3674 if (ret < 0) {
3675 goto finish;
3676 }
1bd0e2d1 3677
b76b4f60 3678 ret = 0;
1bd0e2d1 3679finish:
cb3e7f08 3680 qobject_unref(qdict);
cbf2b7c4 3681 bdrv_unref(bs);
9b890bdc 3682 bdrv_unref(data_bs);
b76b4f60 3683 qapi_free_BlockdevCreateOptions(create_options);
3ef6c40a 3684 return ret;
de5f3f40
KW
3685}
3686
2928abce 3687
f06f6b66 3688static bool is_zero(BlockDriverState *bs, int64_t offset, int64_t bytes)
2928abce 3689{
31826642
EB
3690 int64_t nr;
3691 int res;
f06f6b66
EB
3692
3693 /* Clamp to image length, before checking status of underlying sectors */
8cbf74b2
EB
3694 if (offset + bytes > bs->total_sectors * BDRV_SECTOR_SIZE) {
3695 bytes = bs->total_sectors * BDRV_SECTOR_SIZE - offset;
fbaa6bb3
EB
3696 }
3697
f06f6b66 3698 if (!bytes) {
ebb718a5
EB
3699 return true;
3700 }
8cbf74b2 3701 res = bdrv_block_status_above(bs, NULL, offset, bytes, &nr, NULL, NULL);
31826642 3702 return res >= 0 && (res & BDRV_BLOCK_ZERO) && nr == bytes;
2928abce
DL
3703}
3704
5544b59f 3705static coroutine_fn int qcow2_co_pwrite_zeroes(BlockDriverState *bs,
f5a5ca79 3706 int64_t offset, int bytes, BdrvRequestFlags flags)
621f0589
KW
3707{
3708 int ret;
ff99129a 3709 BDRVQcow2State *s = bs->opaque;
621f0589 3710
5544b59f 3711 uint32_t head = offset % s->cluster_size;
f5a5ca79 3712 uint32_t tail = (offset + bytes) % s->cluster_size;
2928abce 3713
f5a5ca79
MP
3714 trace_qcow2_pwrite_zeroes_start_req(qemu_coroutine_self(), offset, bytes);
3715 if (offset + bytes == bs->total_sectors * BDRV_SECTOR_SIZE) {
fbaa6bb3
EB
3716 tail = 0;
3717 }
5a64e942 3718
ebb718a5 3719 if (head || tail) {
ebb718a5 3720 uint64_t off;
ecfe1863 3721 unsigned int nr;
2928abce 3722
f5a5ca79 3723 assert(head + bytes <= s->cluster_size);
2928abce 3724
ebb718a5 3725 /* check whether remainder of cluster already reads as zero */
f06f6b66
EB
3726 if (!(is_zero(bs, offset - head, head) &&
3727 is_zero(bs, offset + bytes,
3728 tail ? s->cluster_size - tail : 0))) {
2928abce
DL
3729 return -ENOTSUP;
3730 }
3731
2928abce
DL
3732 qemu_co_mutex_lock(&s->lock);
3733 /* We can have new write after previous check */
f06f6b66 3734 offset = QEMU_ALIGN_DOWN(offset, s->cluster_size);
f5a5ca79 3735 bytes = s->cluster_size;
ecfe1863 3736 nr = s->cluster_size;
5544b59f 3737 ret = qcow2_get_cluster_offset(bs, offset, &nr, &off);
fdfab37d
EB
3738 if (ret != QCOW2_CLUSTER_UNALLOCATED &&
3739 ret != QCOW2_CLUSTER_ZERO_PLAIN &&
3740 ret != QCOW2_CLUSTER_ZERO_ALLOC) {
2928abce
DL
3741 qemu_co_mutex_unlock(&s->lock);
3742 return -ENOTSUP;
3743 }
3744 } else {
3745 qemu_co_mutex_lock(&s->lock);
621f0589
KW
3746 }
3747
f5a5ca79 3748 trace_qcow2_pwrite_zeroes(qemu_coroutine_self(), offset, bytes);
5a64e942 3749
621f0589 3750 /* Whatever is left can use real zero clusters */
f5a5ca79 3751 ret = qcow2_cluster_zeroize(bs, offset, bytes, flags);
621f0589
KW
3752 qemu_co_mutex_unlock(&s->lock);
3753
3754 return ret;
3755}
3756
82e8a788 3757static coroutine_fn int qcow2_co_pdiscard(BlockDriverState *bs,
f5a5ca79 3758 int64_t offset, int bytes)
5ea929e3 3759{
6db39ae2 3760 int ret;
ff99129a 3761 BDRVQcow2State *s = bs->opaque;
6db39ae2 3762
f5a5ca79
MP
3763 if (!QEMU_IS_ALIGNED(offset | bytes, s->cluster_size)) {
3764 assert(bytes < s->cluster_size);
048c5fd1
EB
3765 /* Ignore partial clusters, except for the special case of the
3766 * complete partial cluster at the end of an unaligned file */
3767 if (!QEMU_IS_ALIGNED(offset, s->cluster_size) ||
f5a5ca79 3768 offset + bytes != bs->total_sectors * BDRV_SECTOR_SIZE) {
048c5fd1
EB
3769 return -ENOTSUP;
3770 }
49228d1e
EB
3771 }
3772
6db39ae2 3773 qemu_co_mutex_lock(&s->lock);
f5a5ca79 3774 ret = qcow2_cluster_discard(bs, offset, bytes, QCOW2_DISCARD_REQUEST,
d2cb36af 3775 false);
6db39ae2
PB
3776 qemu_co_mutex_unlock(&s->lock);
3777 return ret;
5ea929e3
KW
3778}
3779
fd9fcd37
FZ
3780static int coroutine_fn
3781qcow2_co_copy_range_from(BlockDriverState *bs,
3782 BdrvChild *src, uint64_t src_offset,
3783 BdrvChild *dst, uint64_t dst_offset,
67b51fb9
VSO
3784 uint64_t bytes, BdrvRequestFlags read_flags,
3785 BdrvRequestFlags write_flags)
fd9fcd37
FZ
3786{
3787 BDRVQcow2State *s = bs->opaque;
3788 int ret;
3789 unsigned int cur_bytes; /* number of bytes in current iteration */
3790 BdrvChild *child = NULL;
67b51fb9 3791 BdrvRequestFlags cur_write_flags;
fd9fcd37
FZ
3792
3793 assert(!bs->encrypted);
3794 qemu_co_mutex_lock(&s->lock);
3795
3796 while (bytes != 0) {
3797 uint64_t copy_offset = 0;
3798 /* prepare next request */
3799 cur_bytes = MIN(bytes, INT_MAX);
67b51fb9 3800 cur_write_flags = write_flags;
fd9fcd37
FZ
3801
3802 ret = qcow2_get_cluster_offset(bs, src_offset, &cur_bytes, &copy_offset);
3803 if (ret < 0) {
3804 goto out;
3805 }
3806
3807 switch (ret) {
3808 case QCOW2_CLUSTER_UNALLOCATED:
3809 if (bs->backing && bs->backing->bs) {
3810 int64_t backing_length = bdrv_getlength(bs->backing->bs);
3811 if (src_offset >= backing_length) {
67b51fb9 3812 cur_write_flags |= BDRV_REQ_ZERO_WRITE;
fd9fcd37
FZ
3813 } else {
3814 child = bs->backing;
3815 cur_bytes = MIN(cur_bytes, backing_length - src_offset);
3816 copy_offset = src_offset;
3817 }
3818 } else {
67b51fb9 3819 cur_write_flags |= BDRV_REQ_ZERO_WRITE;
fd9fcd37
FZ
3820 }
3821 break;
3822
3823 case QCOW2_CLUSTER_ZERO_PLAIN:
3824 case QCOW2_CLUSTER_ZERO_ALLOC:
67b51fb9 3825 cur_write_flags |= BDRV_REQ_ZERO_WRITE;
fd9fcd37
FZ
3826 break;
3827
3828 case QCOW2_CLUSTER_COMPRESSED:
3829 ret = -ENOTSUP;
3830 goto out;
fd9fcd37
FZ
3831
3832 case QCOW2_CLUSTER_NORMAL:
966b000f 3833 child = s->data_file;
fd9fcd37
FZ
3834 copy_offset += offset_into_cluster(s, src_offset);
3835 if ((copy_offset & 511) != 0) {
3836 ret = -EIO;
3837 goto out;
3838 }
3839 break;
3840
3841 default:
3842 abort();
3843 }
3844 qemu_co_mutex_unlock(&s->lock);
3845 ret = bdrv_co_copy_range_from(child,
3846 copy_offset,
3847 dst, dst_offset,
67b51fb9 3848 cur_bytes, read_flags, cur_write_flags);
fd9fcd37
FZ
3849 qemu_co_mutex_lock(&s->lock);
3850 if (ret < 0) {
3851 goto out;
3852 }
3853
3854 bytes -= cur_bytes;
3855 src_offset += cur_bytes;
3856 dst_offset += cur_bytes;
3857 }
3858 ret = 0;
3859
3860out:
3861 qemu_co_mutex_unlock(&s->lock);
3862 return ret;
3863}
3864
3865static int coroutine_fn
3866qcow2_co_copy_range_to(BlockDriverState *bs,
3867 BdrvChild *src, uint64_t src_offset,
3868 BdrvChild *dst, uint64_t dst_offset,
67b51fb9
VSO
3869 uint64_t bytes, BdrvRequestFlags read_flags,
3870 BdrvRequestFlags write_flags)
fd9fcd37
FZ
3871{
3872 BDRVQcow2State *s = bs->opaque;
3873 int offset_in_cluster;
3874 int ret;
3875 unsigned int cur_bytes; /* number of sectors in current iteration */
3876 uint64_t cluster_offset;
fd9fcd37
FZ
3877 QCowL2Meta *l2meta = NULL;
3878
3879 assert(!bs->encrypted);
fd9fcd37
FZ
3880
3881 qemu_co_mutex_lock(&s->lock);
3882
3883 while (bytes != 0) {
3884
3885 l2meta = NULL;
3886
3887 offset_in_cluster = offset_into_cluster(s, dst_offset);
3888 cur_bytes = MIN(bytes, INT_MAX);
3889
3890 /* TODO:
3891 * If src->bs == dst->bs, we could simply copy by incrementing
3892 * the refcnt, without copying user data.
3893 * Or if src->bs == dst->bs->backing->bs, we could copy by discarding. */
3894 ret = qcow2_alloc_cluster_offset(bs, dst_offset, &cur_bytes,
3895 &cluster_offset, &l2meta);
3896 if (ret < 0) {
3897 goto fail;
3898 }
3899
3900 assert((cluster_offset & 511) == 0);
3901
3902 ret = qcow2_pre_write_overlap_check(bs, 0,
966b000f 3903 cluster_offset + offset_in_cluster, cur_bytes, true);
fd9fcd37
FZ
3904 if (ret < 0) {
3905 goto fail;
3906 }
3907
3908 qemu_co_mutex_unlock(&s->lock);
3909 ret = bdrv_co_copy_range_to(src, src_offset,
966b000f 3910 s->data_file,
fd9fcd37 3911 cluster_offset + offset_in_cluster,
67b51fb9 3912 cur_bytes, read_flags, write_flags);
fd9fcd37
FZ
3913 qemu_co_mutex_lock(&s->lock);
3914 if (ret < 0) {
3915 goto fail;
3916 }
3917
3918 ret = qcow2_handle_l2meta(bs, &l2meta, true);
3919 if (ret) {
3920 goto fail;
3921 }
3922
3923 bytes -= cur_bytes;
e06f4639 3924 src_offset += cur_bytes;
fd9fcd37
FZ
3925 dst_offset += cur_bytes;
3926 }
3927 ret = 0;
3928
3929fail:
3930 qcow2_handle_l2meta(bs, &l2meta, false);
3931
3932 qemu_co_mutex_unlock(&s->lock);
3933
fd9fcd37
FZ
3934 trace_qcow2_writev_done_req(qemu_coroutine_self(), ret);
3935
3936 return ret;
3937}
3938
061ca8a3
KW
3939static int coroutine_fn qcow2_co_truncate(BlockDriverState *bs, int64_t offset,
3940 PreallocMode prealloc, Error **errp)
419b19d9 3941{
ff99129a 3942 BDRVQcow2State *s = bs->opaque;
95b98f34 3943 uint64_t old_length;
2cf7cfa1
KW
3944 int64_t new_l1_size;
3945 int ret;
45b4949c 3946 QDict *options;
419b19d9 3947
772d1f97
HR
3948 if (prealloc != PREALLOC_MODE_OFF && prealloc != PREALLOC_MODE_METADATA &&
3949 prealloc != PREALLOC_MODE_FALLOC && prealloc != PREALLOC_MODE_FULL)
3950 {
8243ccb7 3951 error_setg(errp, "Unsupported preallocation mode '%s'",
977c736f 3952 PreallocMode_str(prealloc));
8243ccb7
HR
3953 return -ENOTSUP;
3954 }
3955
419b19d9 3956 if (offset & 511) {
4bff28b8 3957 error_setg(errp, "The new size must be a multiple of 512");
419b19d9
SH
3958 return -EINVAL;
3959 }
3960
061ca8a3
KW
3961 qemu_co_mutex_lock(&s->lock);
3962
419b19d9
SH
3963 /* cannot proceed if image has snapshots */
3964 if (s->nb_snapshots) {
4bff28b8 3965 error_setg(errp, "Can't resize an image which has snapshots");
061ca8a3
KW
3966 ret = -ENOTSUP;
3967 goto fail;
419b19d9
SH
3968 }
3969
88ddffae 3970 /* cannot proceed if image has bitmaps */
d19c6b36 3971 if (qcow2_truncate_bitmaps_check(bs, errp)) {
061ca8a3
KW
3972 ret = -ENOTSUP;
3973 goto fail;
88ddffae
VSO
3974 }
3975
bd016b91 3976 old_length = bs->total_sectors * BDRV_SECTOR_SIZE;
46b732cd 3977 new_l1_size = size_to_l1(s, offset);
95b98f34 3978
95b98f34 3979 if (offset < old_length) {
163bc39d 3980 int64_t last_cluster, old_file_size;
46b732cd
PB
3981 if (prealloc != PREALLOC_MODE_OFF) {
3982 error_setg(errp,
3983 "Preallocation can't be used for shrinking an image");
061ca8a3
KW
3984 ret = -EINVAL;
3985 goto fail;
46b732cd 3986 }
419b19d9 3987
46b732cd
PB
3988 ret = qcow2_cluster_discard(bs, ROUND_UP(offset, s->cluster_size),
3989 old_length - ROUND_UP(offset,
3990 s->cluster_size),
3991 QCOW2_DISCARD_ALWAYS, true);
3992 if (ret < 0) {
3993 error_setg_errno(errp, -ret, "Failed to discard cropped clusters");
061ca8a3 3994 goto fail;
46b732cd
PB
3995 }
3996
3997 ret = qcow2_shrink_l1_table(bs, new_l1_size);
3998 if (ret < 0) {
3999 error_setg_errno(errp, -ret,
4000 "Failed to reduce the number of L2 tables");
061ca8a3 4001 goto fail;
46b732cd
PB
4002 }
4003
4004 ret = qcow2_shrink_reftable(bs);
4005 if (ret < 0) {
4006 error_setg_errno(errp, -ret,
4007 "Failed to discard unused refblocks");
061ca8a3 4008 goto fail;
46b732cd 4009 }
163bc39d
PB
4010
4011 old_file_size = bdrv_getlength(bs->file->bs);
4012 if (old_file_size < 0) {
4013 error_setg_errno(errp, -old_file_size,
4014 "Failed to inquire current file length");
061ca8a3
KW
4015 ret = old_file_size;
4016 goto fail;
163bc39d
PB
4017 }
4018 last_cluster = qcow2_get_last_cluster(bs, old_file_size);
4019 if (last_cluster < 0) {
4020 error_setg_errno(errp, -last_cluster,
4021 "Failed to find the last cluster");
061ca8a3
KW
4022 ret = last_cluster;
4023 goto fail;
163bc39d
PB
4024 }
4025 if ((last_cluster + 1) * s->cluster_size < old_file_size) {
233521b1
HR
4026 Error *local_err = NULL;
4027
061ca8a3
KW
4028 bdrv_co_truncate(bs->file, (last_cluster + 1) * s->cluster_size,
4029 PREALLOC_MODE_OFF, &local_err);
233521b1
HR
4030 if (local_err) {
4031 warn_reportf_err(local_err,
4032 "Failed to truncate the tail of the image: ");
163bc39d
PB
4033 }
4034 }
46b732cd
PB
4035 } else {
4036 ret = qcow2_grow_l1_table(bs, new_l1_size, true);
4037 if (ret < 0) {
4038 error_setg_errno(errp, -ret, "Failed to grow the L1 table");
061ca8a3 4039 goto fail;
46b732cd 4040 }
419b19d9
SH
4041 }
4042
95b98f34
HR
4043 switch (prealloc) {
4044 case PREALLOC_MODE_OFF:
718c0fce
KW
4045 if (has_data_file(bs)) {
4046 ret = bdrv_co_truncate(s->data_file, offset, prealloc, errp);
4047 if (ret < 0) {
4048 goto fail;
4049 }
4050 }
95b98f34
HR
4051 break;
4052
4053 case PREALLOC_MODE_METADATA:
718c0fce 4054 ret = preallocate_co(bs, old_length, offset, prealloc, errp);
95b98f34 4055 if (ret < 0) {
061ca8a3 4056 goto fail;
95b98f34
HR
4057 }
4058 break;
4059
772d1f97
HR
4060 case PREALLOC_MODE_FALLOC:
4061 case PREALLOC_MODE_FULL:
4062 {
4063 int64_t allocation_start, host_offset, guest_offset;
4064 int64_t clusters_allocated;
4065 int64_t old_file_size, new_file_size;
4066 uint64_t nb_new_data_clusters, nb_new_l2_tables;
4067
966b000f
KW
4068 /* With a data file, preallocation means just allocating the metadata
4069 * and forwarding the truncate request to the data file */
4070 if (has_data_file(bs)) {
718c0fce 4071 ret = preallocate_co(bs, old_length, offset, prealloc, errp);
966b000f 4072 if (ret < 0) {
966b000f
KW
4073 goto fail;
4074 }
4075 break;
4076 }
4077
772d1f97
HR
4078 old_file_size = bdrv_getlength(bs->file->bs);
4079 if (old_file_size < 0) {
4080 error_setg_errno(errp, -old_file_size,
4081 "Failed to inquire current file length");
061ca8a3
KW
4082 ret = old_file_size;
4083 goto fail;
772d1f97 4084 }
e400ad1e 4085 old_file_size = ROUND_UP(old_file_size, s->cluster_size);
772d1f97
HR
4086
4087 nb_new_data_clusters = DIV_ROUND_UP(offset - old_length,
4088 s->cluster_size);
4089
4090 /* This is an overestimation; we will not actually allocate space for
4091 * these in the file but just make sure the new refcount structures are
4092 * able to cover them so we will not have to allocate new refblocks
4093 * while entering the data blocks in the potentially new L2 tables.
4094 * (We do not actually care where the L2 tables are placed. Maybe they
4095 * are already allocated or they can be placed somewhere before
4096 * @old_file_size. It does not matter because they will be fully
4097 * allocated automatically, so they do not need to be covered by the
4098 * preallocation. All that matters is that we will not have to allocate
4099 * new refcount structures for them.) */
4100 nb_new_l2_tables = DIV_ROUND_UP(nb_new_data_clusters,
4101 s->cluster_size / sizeof(uint64_t));
4102 /* The cluster range may not be aligned to L2 boundaries, so add one L2
4103 * table for a potential head/tail */
4104 nb_new_l2_tables++;
4105
4106 allocation_start = qcow2_refcount_area(bs, old_file_size,
4107 nb_new_data_clusters +
4108 nb_new_l2_tables,
4109 true, 0, 0);
4110 if (allocation_start < 0) {
4111 error_setg_errno(errp, -allocation_start,
4112 "Failed to resize refcount structures");
061ca8a3
KW
4113 ret = allocation_start;
4114 goto fail;
772d1f97
HR
4115 }
4116
4117 clusters_allocated = qcow2_alloc_clusters_at(bs, allocation_start,
4118 nb_new_data_clusters);
4119 if (clusters_allocated < 0) {
4120 error_setg_errno(errp, -clusters_allocated,
4121 "Failed to allocate data clusters");
061ca8a3
KW
4122 ret = clusters_allocated;
4123 goto fail;
772d1f97
HR
4124 }
4125
4126 assert(clusters_allocated == nb_new_data_clusters);
4127
4128 /* Allocate the data area */
4129 new_file_size = allocation_start +
4130 nb_new_data_clusters * s->cluster_size;
061ca8a3 4131 ret = bdrv_co_truncate(bs->file, new_file_size, prealloc, errp);
772d1f97
HR
4132 if (ret < 0) {
4133 error_prepend(errp, "Failed to resize underlying file: ");
4134 qcow2_free_clusters(bs, allocation_start,
4135 nb_new_data_clusters * s->cluster_size,
4136 QCOW2_DISCARD_OTHER);
061ca8a3 4137 goto fail;
772d1f97
HR
4138 }
4139
4140 /* Create the necessary L2 entries */
4141 host_offset = allocation_start;
4142 guest_offset = old_length;
4143 while (nb_new_data_clusters) {
13bec229
AG
4144 int64_t nb_clusters = MIN(
4145 nb_new_data_clusters,
4146 s->l2_slice_size - offset_to_l2_slice_index(s, guest_offset));
772d1f97
HR
4147 QCowL2Meta allocation = {
4148 .offset = guest_offset,
4149 .alloc_offset = host_offset,
4150 .nb_clusters = nb_clusters,
4151 };
4152 qemu_co_queue_init(&allocation.dependent_requests);
4153
4154 ret = qcow2_alloc_cluster_link_l2(bs, &allocation);
4155 if (ret < 0) {
4156 error_setg_errno(errp, -ret, "Failed to update L2 tables");
4157 qcow2_free_clusters(bs, host_offset,
4158 nb_new_data_clusters * s->cluster_size,
4159 QCOW2_DISCARD_OTHER);
061ca8a3 4160 goto fail;
772d1f97
HR
4161 }
4162
4163 guest_offset += nb_clusters * s->cluster_size;
4164 host_offset += nb_clusters * s->cluster_size;
4165 nb_new_data_clusters -= nb_clusters;
4166 }
4167 break;
4168 }
4169
95b98f34
HR
4170 default:
4171 g_assert_not_reached();
4172 }
4173
4174 if (prealloc != PREALLOC_MODE_OFF) {
4175 /* Flush metadata before actually changing the image size */
061ca8a3 4176 ret = qcow2_write_caches(bs);
95b98f34
HR
4177 if (ret < 0) {
4178 error_setg_errno(errp, -ret,
4179 "Failed to flush the preallocated area to disk");
061ca8a3 4180 goto fail;
95b98f34
HR
4181 }
4182 }
4183
45b4949c
LB
4184 bs->total_sectors = offset / BDRV_SECTOR_SIZE;
4185
419b19d9
SH
4186 /* write updated header.size */
4187 offset = cpu_to_be64(offset);
d9ca2ea2 4188 ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, size),
8b3b7206 4189 &offset, sizeof(uint64_t));
419b19d9 4190 if (ret < 0) {
f59adb32 4191 error_setg_errno(errp, -ret, "Failed to update the image size");
061ca8a3 4192 goto fail;
419b19d9
SH
4193 }
4194
4195 s->l1_vm_state_index = new_l1_size;
45b4949c
LB
4196
4197 /* Update cache sizes */
4198 options = qdict_clone_shallow(bs->options);
4199 ret = qcow2_update_options(bs, options, s->flags, errp);
4200 qobject_unref(options);
4201 if (ret < 0) {
4202 goto fail;
4203 }
061ca8a3
KW
4204 ret = 0;
4205fail:
4206 qemu_co_mutex_unlock(&s->lock);
4207 return ret;
419b19d9
SH
4208}
4209
20d97356
BS
4210/* XXX: put compressed sectors first, then all the cluster aligned
4211 tables to avoid losing bytes in alignment */
fcccefc5 4212static coroutine_fn int
5396234b
VSO
4213qcow2_co_pwritev_compressed_part(BlockDriverState *bs,
4214 uint64_t offset, uint64_t bytes,
4215 QEMUIOVector *qiov, size_t qiov_offset)
20d97356 4216{
ff99129a 4217 BDRVQcow2State *s = bs->opaque;
2714f13d 4218 int ret;
e1f4a37a 4219 ssize_t out_len;
fcccefc5 4220 uint8_t *buf, *out_buf;
77e023ff 4221 uint64_t cluster_offset;
20d97356 4222
966b000f
KW
4223 if (has_data_file(bs)) {
4224 return -ENOTSUP;
4225 }
4226
fcccefc5 4227 if (bytes == 0) {
20d97356
BS
4228 /* align end of file to a sector boundary to ease reading with
4229 sector based I/Os */
77e023ff
KW
4230 int64_t len = bdrv_getlength(bs->file->bs);
4231 if (len < 0) {
4232 return len;
d0d5d0e3 4233 }
77e023ff 4234 return bdrv_co_truncate(bs->file, len, PREALLOC_MODE_OFF, NULL);
20d97356
BS
4235 }
4236
3e3b838f
AN
4237 if (offset_into_cluster(s, offset)) {
4238 return -EINVAL;
4239 }
4240
a2c0ca6f 4241 buf = qemu_blockalign(bs, s->cluster_size);
fcccefc5 4242 if (bytes != s->cluster_size) {
a2c0ca6f
PB
4243 if (bytes > s->cluster_size ||
4244 offset + bytes != bs->total_sectors << BDRV_SECTOR_BITS)
fcccefc5 4245 {
a2c0ca6f
PB
4246 qemu_vfree(buf);
4247 return -EINVAL;
f4d38bef 4248 }
a2c0ca6f
PB
4249 /* Zero-pad last write if image size is not cluster aligned */
4250 memset(buf + bytes, 0, s->cluster_size - bytes);
f4d38bef 4251 }
5396234b 4252 qemu_iovec_to_buf(qiov, qiov_offset, buf, bytes);
20d97356 4253
ebf7bba0 4254 out_buf = g_malloc(s->cluster_size);
20d97356 4255
6994fd78
VSO
4256 out_len = qcow2_co_compress(bs, out_buf, s->cluster_size - 1,
4257 buf, s->cluster_size);
e1f4a37a 4258 if (out_len == -ENOMEM) {
20d97356 4259 /* could not compress: write normal cluster */
5396234b 4260 ret = qcow2_co_pwritev_part(bs, offset, bytes, qiov, qiov_offset, 0);
8f1efd00
KW
4261 if (ret < 0) {
4262 goto fail;
4263 }
fcccefc5 4264 goto success;
e1f4a37a
AG
4265 } else if (out_len < 0) {
4266 ret = -EINVAL;
4267 goto fail;
fcccefc5 4268 }
cf93980e 4269
fcccefc5 4270 qemu_co_mutex_lock(&s->lock);
77e023ff
KW
4271 ret = qcow2_alloc_compressed_cluster_offset(bs, offset, out_len,
4272 &cluster_offset);
4273 if (ret < 0) {
fcccefc5 4274 qemu_co_mutex_unlock(&s->lock);
fcccefc5
PB
4275 goto fail;
4276 }
cf93980e 4277
966b000f 4278 ret = qcow2_pre_write_overlap_check(bs, 0, cluster_offset, out_len, true);
fcccefc5
PB
4279 qemu_co_mutex_unlock(&s->lock);
4280 if (ret < 0) {
4281 goto fail;
20d97356
BS
4282 }
4283
966b000f 4284 BLKDBG_EVENT(s->data_file, BLKDBG_WRITE_COMPRESSED);
b00cb15b 4285 ret = bdrv_co_pwrite(s->data_file, cluster_offset, out_len, out_buf, 0);
fcccefc5
PB
4286 if (ret < 0) {
4287 goto fail;
4288 }
4289success:
8f1efd00
KW
4290 ret = 0;
4291fail:
fcccefc5 4292 qemu_vfree(buf);
7267c094 4293 g_free(out_buf);
8f1efd00 4294 return ret;
20d97356
BS
4295}
4296
c3c10f72
VSO
4297static int coroutine_fn
4298qcow2_co_preadv_compressed(BlockDriverState *bs,
4299 uint64_t file_cluster_offset,
4300 uint64_t offset,
4301 uint64_t bytes,
df893d25
VSO
4302 QEMUIOVector *qiov,
4303 size_t qiov_offset)
f4b3e2a9
VSO
4304{
4305 BDRVQcow2State *s = bs->opaque;
c3c10f72 4306 int ret = 0, csize, nb_csectors;
f4b3e2a9 4307 uint64_t coffset;
c3c10f72 4308 uint8_t *buf, *out_buf;
c3c10f72 4309 int offset_in_cluster = offset_into_cluster(s, offset);
f4b3e2a9 4310
c3c10f72
VSO
4311 coffset = file_cluster_offset & s->cluster_offset_mask;
4312 nb_csectors = ((file_cluster_offset >> s->csize_shift) & s->csize_mask) + 1;
b6c24694
AG
4313 csize = nb_csectors * QCOW2_COMPRESSED_SECTOR_SIZE -
4314 (coffset & ~QCOW2_COMPRESSED_SECTOR_MASK);
f4b3e2a9 4315
c3c10f72
VSO
4316 buf = g_try_malloc(csize);
4317 if (!buf) {
4318 return -ENOMEM;
4319 }
f4b3e2a9 4320
c3c10f72 4321 out_buf = qemu_blockalign(bs, s->cluster_size);
c068a1cd 4322
c3c10f72 4323 BLKDBG_EVENT(bs->file, BLKDBG_READ_COMPRESSED);
b00cb15b 4324 ret = bdrv_co_pread(bs->file, coffset, csize, buf, 0);
c3c10f72
VSO
4325 if (ret < 0) {
4326 goto fail;
f4b3e2a9 4327 }
c3c10f72 4328
e23c9d7a 4329 if (qcow2_co_decompress(bs, out_buf, s->cluster_size, buf, csize) < 0) {
c3c10f72
VSO
4330 ret = -EIO;
4331 goto fail;
4332 }
4333
df893d25 4334 qemu_iovec_from_buf(qiov, qiov_offset, out_buf + offset_in_cluster, bytes);
c3c10f72
VSO
4335
4336fail:
4337 qemu_vfree(out_buf);
4338 g_free(buf);
4339
4340 return ret;
f4b3e2a9
VSO
4341}
4342
94054183
HR
4343static int make_completely_empty(BlockDriverState *bs)
4344{
ff99129a 4345 BDRVQcow2State *s = bs->opaque;
ed3d2ec9 4346 Error *local_err = NULL;
94054183
HR
4347 int ret, l1_clusters;
4348 int64_t offset;
4349 uint64_t *new_reftable = NULL;
4350 uint64_t rt_entry, l1_size2;
4351 struct {
4352 uint64_t l1_offset;
4353 uint64_t reftable_offset;
4354 uint32_t reftable_clusters;
4355 } QEMU_PACKED l1_ofs_rt_ofs_cls;
4356
4357 ret = qcow2_cache_empty(bs, s->l2_table_cache);
4358 if (ret < 0) {
4359 goto fail;
4360 }
4361
4362 ret = qcow2_cache_empty(bs, s->refcount_block_cache);
4363 if (ret < 0) {
4364 goto fail;
4365 }
4366
4367 /* Refcounts will be broken utterly */
4368 ret = qcow2_mark_dirty(bs);
4369 if (ret < 0) {
4370 goto fail;
4371 }
4372
4373 BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
4374
4375 l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / sizeof(uint64_t));
4376 l1_size2 = (uint64_t)s->l1_size * sizeof(uint64_t);
4377
4378 /* After this call, neither the in-memory nor the on-disk refcount
4379 * information accurately describe the actual references */
4380
720ff280 4381 ret = bdrv_pwrite_zeroes(bs->file, s->l1_table_offset,
74021bc4 4382 l1_clusters * s->cluster_size, 0);
94054183
HR
4383 if (ret < 0) {
4384 goto fail_broken_refcounts;
4385 }
4386 memset(s->l1_table, 0, l1_size2);
4387
4388 BLKDBG_EVENT(bs->file, BLKDBG_EMPTY_IMAGE_PREPARE);
4389
4390 /* Overwrite enough clusters at the beginning of the sectors to place
4391 * the refcount table, a refcount block and the L1 table in; this may
4392 * overwrite parts of the existing refcount and L1 table, which is not
4393 * an issue because the dirty flag is set, complete data loss is in fact
4394 * desired and partial data loss is consequently fine as well */
720ff280 4395 ret = bdrv_pwrite_zeroes(bs->file, s->cluster_size,
74021bc4 4396 (2 + l1_clusters) * s->cluster_size, 0);
94054183
HR
4397 /* This call (even if it failed overall) may have overwritten on-disk
4398 * refcount structures; in that case, the in-memory refcount information
4399 * will probably differ from the on-disk information which makes the BDS
4400 * unusable */
4401 if (ret < 0) {
4402 goto fail_broken_refcounts;
4403 }
4404
4405 BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
4406 BLKDBG_EVENT(bs->file, BLKDBG_REFTABLE_UPDATE);
4407
4408 /* "Create" an empty reftable (one cluster) directly after the image
4409 * header and an empty L1 table three clusters after the image header;
4410 * the cluster between those two will be used as the first refblock */
f1f7a1dd
PM
4411 l1_ofs_rt_ofs_cls.l1_offset = cpu_to_be64(3 * s->cluster_size);
4412 l1_ofs_rt_ofs_cls.reftable_offset = cpu_to_be64(s->cluster_size);
4413 l1_ofs_rt_ofs_cls.reftable_clusters = cpu_to_be32(1);
d9ca2ea2 4414 ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, l1_table_offset),
94054183
HR
4415 &l1_ofs_rt_ofs_cls, sizeof(l1_ofs_rt_ofs_cls));
4416 if (ret < 0) {
4417 goto fail_broken_refcounts;
4418 }
4419
4420 s->l1_table_offset = 3 * s->cluster_size;
4421
4422 new_reftable = g_try_new0(uint64_t, s->cluster_size / sizeof(uint64_t));
4423 if (!new_reftable) {
4424 ret = -ENOMEM;
4425 goto fail_broken_refcounts;
4426 }
4427
4428 s->refcount_table_offset = s->cluster_size;
4429 s->refcount_table_size = s->cluster_size / sizeof(uint64_t);
7061a078 4430 s->max_refcount_table_index = 0;
94054183
HR
4431
4432 g_free(s->refcount_table);
4433 s->refcount_table = new_reftable;
4434 new_reftable = NULL;
4435
4436 /* Now the in-memory refcount information again corresponds to the on-disk
4437 * information (reftable is empty and no refblocks (the refblock cache is
4438 * empty)); however, this means some clusters (e.g. the image header) are
4439 * referenced, but not refcounted, but the normal qcow2 code assumes that
4440 * the in-memory information is always correct */
4441
4442 BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_ALLOC);
4443
4444 /* Enter the first refblock into the reftable */
4445 rt_entry = cpu_to_be64(2 * s->cluster_size);
d9ca2ea2 4446 ret = bdrv_pwrite_sync(bs->file, s->cluster_size,
94054183
HR
4447 &rt_entry, sizeof(rt_entry));
4448 if (ret < 0) {
4449 goto fail_broken_refcounts;
4450 }
4451 s->refcount_table[0] = 2 * s->cluster_size;
4452
4453 s->free_cluster_index = 0;
4454 assert(3 + l1_clusters <= s->refcount_block_size);
4455 offset = qcow2_alloc_clusters(bs, 3 * s->cluster_size + l1_size2);
4456 if (offset < 0) {
4457 ret = offset;
4458 goto fail_broken_refcounts;
4459 } else if (offset > 0) {
4460 error_report("First cluster in emptied image is in use");
4461 abort();
4462 }
4463
4464 /* Now finally the in-memory information corresponds to the on-disk
4465 * structures and is correct */
4466 ret = qcow2_mark_clean(bs);
4467 if (ret < 0) {
4468 goto fail;
4469 }
4470
ed3d2ec9 4471 ret = bdrv_truncate(bs->file, (3 + l1_clusters) * s->cluster_size,
7ea37c30 4472 PREALLOC_MODE_OFF, &local_err);
94054183 4473 if (ret < 0) {
ed3d2ec9 4474 error_report_err(local_err);
94054183
HR
4475 goto fail;
4476 }
4477
4478 return 0;
4479
4480fail_broken_refcounts:
4481 /* The BDS is unusable at this point. If we wanted to make it usable, we
4482 * would have to call qcow2_refcount_close(), qcow2_refcount_init(),
4483 * qcow2_check_refcounts(), qcow2_refcount_close() and qcow2_refcount_init()
4484 * again. However, because the functions which could have caused this error
4485 * path to be taken are used by those functions as well, it's very likely
4486 * that that sequence will fail as well. Therefore, just eject the BDS. */
4487 bs->drv = NULL;
4488
4489fail:
4490 g_free(new_reftable);
4491 return ret;
4492}
4493
491d27e2
HR
4494static int qcow2_make_empty(BlockDriverState *bs)
4495{
ff99129a 4496 BDRVQcow2State *s = bs->opaque;
d2cb36af
EB
4497 uint64_t offset, end_offset;
4498 int step = QEMU_ALIGN_DOWN(INT_MAX, s->cluster_size);
94054183
HR
4499 int l1_clusters, ret = 0;
4500
4501 l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / sizeof(uint64_t));
4502
4096974e 4503 if (s->qcow_version >= 3 && !s->snapshots && !s->nb_bitmaps &&
f0603329 4504 3 + l1_clusters <= s->refcount_block_size &&
db04524f
KW
4505 s->crypt_method_header != QCOW_CRYPT_LUKS &&
4506 !has_data_file(bs)) {
4096974e
EB
4507 /* The following function only works for qcow2 v3 images (it
4508 * requires the dirty flag) and only as long as there are no
4509 * features that reserve extra clusters (such as snapshots,
4510 * LUKS header, or persistent bitmaps), because it completely
4511 * empties the image. Furthermore, the L1 table and three
4512 * additional clusters (image header, refcount table, one
db04524f
KW
4513 * refcount block) have to fit inside one refcount block. It
4514 * only resets the image file, i.e. does not work with an
4515 * external data file. */
94054183
HR
4516 return make_completely_empty(bs);
4517 }
491d27e2 4518
94054183
HR
4519 /* This fallback code simply discards every active cluster; this is slow,
4520 * but works in all cases */
d2cb36af
EB
4521 end_offset = bs->total_sectors * BDRV_SECTOR_SIZE;
4522 for (offset = 0; offset < end_offset; offset += step) {
491d27e2
HR
4523 /* As this function is generally used after committing an external
4524 * snapshot, QCOW2_DISCARD_SNAPSHOT seems appropriate. Also, the
4525 * default action for this kind of discard is to pass the discard,
4526 * which will ideally result in an actually smaller image file, as
4527 * is probably desired. */
d2cb36af
EB
4528 ret = qcow2_cluster_discard(bs, offset, MIN(step, end_offset - offset),
4529 QCOW2_DISCARD_SNAPSHOT, true);
491d27e2
HR
4530 if (ret < 0) {
4531 break;
4532 }
4533 }
4534
4535 return ret;
4536}
4537
a968168c 4538static coroutine_fn int qcow2_co_flush_to_os(BlockDriverState *bs)
20d97356 4539{
ff99129a 4540 BDRVQcow2State *s = bs->opaque;
29c1a730
KW
4541 int ret;
4542
8b94ff85 4543 qemu_co_mutex_lock(&s->lock);
8b220eb7 4544 ret = qcow2_write_caches(bs);
8b94ff85 4545 qemu_co_mutex_unlock(&s->lock);
29c1a730 4546
8b220eb7 4547 return ret;
eb489bb1
KW
4548}
4549
61914f89
SH
4550static ssize_t qcow2_measure_crypto_hdr_init_func(QCryptoBlock *block,
4551 size_t headerlen, void *opaque, Error **errp)
4552{
4553 size_t *headerlenp = opaque;
4554
4555 /* Stash away the payload size */
4556 *headerlenp = headerlen;
4557 return 0;
4558}
4559
4560static ssize_t qcow2_measure_crypto_hdr_write_func(QCryptoBlock *block,
4561 size_t offset, const uint8_t *buf, size_t buflen,
4562 void *opaque, Error **errp)
4563{
4564 /* Discard the bytes, we're not actually writing to an image */
4565 return buflen;
4566}
4567
4568/* Determine the number of bytes for the LUKS payload */
4569static bool qcow2_measure_luks_headerlen(QemuOpts *opts, size_t *len,
4570 Error **errp)
4571{
4572 QDict *opts_qdict;
4573 QDict *cryptoopts_qdict;
4574 QCryptoBlockCreateOptions *cryptoopts;
4575 QCryptoBlock *crypto;
4576
4577 /* Extract "encrypt." options into a qdict */
4578 opts_qdict = qemu_opts_to_qdict(opts, NULL);
4579 qdict_extract_subqdict(opts_qdict, &cryptoopts_qdict, "encrypt.");
4580 qobject_unref(opts_qdict);
4581
4582 /* Build QCryptoBlockCreateOptions object from qdict */
4583 qdict_put_str(cryptoopts_qdict, "format", "luks");
4584 cryptoopts = block_crypto_create_opts_init(cryptoopts_qdict, errp);
4585 qobject_unref(cryptoopts_qdict);
4586 if (!cryptoopts) {
4587 return false;
4588 }
4589
4590 /* Fake LUKS creation in order to determine the payload size */
4591 crypto = qcrypto_block_create(cryptoopts, "encrypt.",
4592 qcow2_measure_crypto_hdr_init_func,
4593 qcow2_measure_crypto_hdr_write_func,
4594 len, errp);
4595 qapi_free_QCryptoBlockCreateOptions(cryptoopts);
4596 if (!crypto) {
4597 return false;
4598 }
4599
4600 qcrypto_block_free(crypto);
4601 return true;
4602}
4603
c501c352
SH
4604static BlockMeasureInfo *qcow2_measure(QemuOpts *opts, BlockDriverState *in_bs,
4605 Error **errp)
4606{
4607 Error *local_err = NULL;
4608 BlockMeasureInfo *info;
4609 uint64_t required = 0; /* bytes that contribute to required size */
4610 uint64_t virtual_size; /* disk size as seen by guest */
4611 uint64_t refcount_bits;
4612 uint64_t l2_tables;
61914f89 4613 uint64_t luks_payload_size = 0;
c501c352
SH
4614 size_t cluster_size;
4615 int version;
4616 char *optstr;
4617 PreallocMode prealloc;
4618 bool has_backing_file;
61914f89 4619 bool has_luks;
c501c352
SH
4620
4621 /* Parse image creation options */
4622 cluster_size = qcow2_opt_get_cluster_size_del(opts, &local_err);
4623 if (local_err) {
4624 goto err;
4625 }
4626
4627 version = qcow2_opt_get_version_del(opts, &local_err);
4628 if (local_err) {
4629 goto err;
4630 }
4631
4632 refcount_bits = qcow2_opt_get_refcount_bits_del(opts, version, &local_err);
4633 if (local_err) {
4634 goto err;
4635 }
4636
4637 optstr = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
f7abe0ec 4638 prealloc = qapi_enum_parse(&PreallocMode_lookup, optstr,
06c60b6c 4639 PREALLOC_MODE_OFF, &local_err);
c501c352
SH
4640 g_free(optstr);
4641 if (local_err) {
4642 goto err;
4643 }
4644
4645 optstr = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
4646 has_backing_file = !!optstr;
4647 g_free(optstr);
4648
61914f89
SH
4649 optstr = qemu_opt_get_del(opts, BLOCK_OPT_ENCRYPT_FORMAT);
4650 has_luks = optstr && strcmp(optstr, "luks") == 0;
4651 g_free(optstr);
4652
4653 if (has_luks) {
4654 size_t headerlen;
4655
4656 if (!qcow2_measure_luks_headerlen(opts, &headerlen, &local_err)) {
4657 goto err;
4658 }
4659
4660 luks_payload_size = ROUND_UP(headerlen, cluster_size);
4661 }
4662
9e029689
AG
4663 virtual_size = qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0);
4664 virtual_size = ROUND_UP(virtual_size, cluster_size);
c501c352
SH
4665
4666 /* Check that virtual disk size is valid */
4667 l2_tables = DIV_ROUND_UP(virtual_size / cluster_size,
4668 cluster_size / sizeof(uint64_t));
4669 if (l2_tables * sizeof(uint64_t) > QCOW_MAX_L1_SIZE) {
4670 error_setg(&local_err, "The image size is too large "
4671 "(try using a larger cluster size)");
4672 goto err;
4673 }
4674
4675 /* Account for input image */
4676 if (in_bs) {
4677 int64_t ssize = bdrv_getlength(in_bs);
4678 if (ssize < 0) {
4679 error_setg_errno(&local_err, -ssize,
4680 "Unable to get image virtual_size");
4681 goto err;
4682 }
4683
9e029689 4684 virtual_size = ROUND_UP(ssize, cluster_size);
c501c352
SH
4685
4686 if (has_backing_file) {
4687 /* We don't how much of the backing chain is shared by the input
4688 * image and the new image file. In the worst case the new image's
4689 * backing file has nothing in common with the input image. Be
4690 * conservative and assume all clusters need to be written.
4691 */
4692 required = virtual_size;
4693 } else {
b85ee453 4694 int64_t offset;
31826642 4695 int64_t pnum = 0;
c501c352 4696
31826642
EB
4697 for (offset = 0; offset < ssize; offset += pnum) {
4698 int ret;
c501c352 4699
31826642
EB
4700 ret = bdrv_block_status_above(in_bs, NULL, offset,
4701 ssize - offset, &pnum, NULL,
4702 NULL);
c501c352
SH
4703 if (ret < 0) {
4704 error_setg_errno(&local_err, -ret,
4705 "Unable to get block status");
4706 goto err;
4707 }
4708
4709 if (ret & BDRV_BLOCK_ZERO) {
4710 /* Skip zero regions (safe with no backing file) */
4711 } else if ((ret & (BDRV_BLOCK_DATA | BDRV_BLOCK_ALLOCATED)) ==
4712 (BDRV_BLOCK_DATA | BDRV_BLOCK_ALLOCATED)) {
4713 /* Extend pnum to end of cluster for next iteration */
31826642 4714 pnum = ROUND_UP(offset + pnum, cluster_size) - offset;
c501c352
SH
4715
4716 /* Count clusters we've seen */
31826642 4717 required += offset % cluster_size + pnum;
c501c352
SH
4718 }
4719 }
4720 }
4721 }
4722
4723 /* Take into account preallocation. Nothing special is needed for
4724 * PREALLOC_MODE_METADATA since metadata is always counted.
4725 */
4726 if (prealloc == PREALLOC_MODE_FULL || prealloc == PREALLOC_MODE_FALLOC) {
4727 required = virtual_size;
4728 }
4729
4730 info = g_new(BlockMeasureInfo, 1);
4731 info->fully_allocated =
4732 qcow2_calc_prealloc_size(virtual_size, cluster_size,
61914f89 4733 ctz32(refcount_bits)) + luks_payload_size;
c501c352
SH
4734
4735 /* Remove data clusters that are not required. This overestimates the
4736 * required size because metadata needed for the fully allocated file is
4737 * still counted.
4738 */
4739 info->required = info->fully_allocated - virtual_size + required;
4740 return info;
4741
4742err:
4743 error_propagate(errp, local_err);
4744 return NULL;
4745}
4746
7c80ab3f 4747static int qcow2_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
20d97356 4748{
ff99129a 4749 BDRVQcow2State *s = bs->opaque;
95de6d70 4750 bdi->unallocated_blocks_are_zero = true;
20d97356 4751 bdi->cluster_size = s->cluster_size;
7c80ab3f 4752 bdi->vm_state_offset = qcow2_vm_state_offset(s);
20d97356
BS
4753 return 0;
4754}
4755
1bf6e9ca
AS
4756static ImageInfoSpecific *qcow2_get_specific_info(BlockDriverState *bs,
4757 Error **errp)
37764dfb 4758{
ff99129a 4759 BDRVQcow2State *s = bs->opaque;
0a12f6f8
DB
4760 ImageInfoSpecific *spec_info;
4761 QCryptoBlockInfo *encrypt_info = NULL;
1bf6e9ca 4762 Error *local_err = NULL;
37764dfb 4763
0a12f6f8 4764 if (s->crypto != NULL) {
1bf6e9ca
AS
4765 encrypt_info = qcrypto_block_get_info(s->crypto, &local_err);
4766 if (local_err) {
4767 error_propagate(errp, local_err);
4768 return NULL;
4769 }
0a12f6f8
DB
4770 }
4771
4772 spec_info = g_new(ImageInfoSpecific, 1);
37764dfb 4773 *spec_info = (ImageInfoSpecific){
6a8f9661 4774 .type = IMAGE_INFO_SPECIFIC_KIND_QCOW2,
b8968c87 4775 .u.qcow2.data = g_new0(ImageInfoSpecificQCow2, 1),
37764dfb
HR
4776 };
4777 if (s->qcow_version == 2) {
32bafa8f 4778 *spec_info->u.qcow2.data = (ImageInfoSpecificQCow2){
0709c5a1
HR
4779 .compat = g_strdup("0.10"),
4780 .refcount_bits = s->refcount_bits,
37764dfb
HR
4781 };
4782 } else if (s->qcow_version == 3) {
b8968c87
AS
4783 Qcow2BitmapInfoList *bitmaps;
4784 bitmaps = qcow2_get_bitmap_info_list(bs, &local_err);
4785 if (local_err) {
4786 error_propagate(errp, local_err);
4787 qapi_free_ImageInfoSpecific(spec_info);
4788 return NULL;
4789 }
32bafa8f 4790 *spec_info->u.qcow2.data = (ImageInfoSpecificQCow2){
37764dfb
HR
4791 .compat = g_strdup("1.1"),
4792 .lazy_refcounts = s->compatible_features &
4793 QCOW2_COMPAT_LAZY_REFCOUNTS,
4794 .has_lazy_refcounts = true,
9009b196
HR
4795 .corrupt = s->incompatible_features &
4796 QCOW2_INCOMPAT_CORRUPT,
4797 .has_corrupt = true,
0709c5a1 4798 .refcount_bits = s->refcount_bits,
b8968c87
AS
4799 .has_bitmaps = !!bitmaps,
4800 .bitmaps = bitmaps,
9b890bdc
KW
4801 .has_data_file = !!s->image_data_file,
4802 .data_file = g_strdup(s->image_data_file),
6c3944dc
KW
4803 .has_data_file_raw = has_data_file(bs),
4804 .data_file_raw = data_file_is_raw(bs),
37764dfb 4805 };
b1fc8f93
DL
4806 } else {
4807 /* if this assertion fails, this probably means a new version was
4808 * added without having it covered here */
4809 assert(false);
37764dfb
HR
4810 }
4811
0a12f6f8
DB
4812 if (encrypt_info) {
4813 ImageInfoSpecificQCow2Encryption *qencrypt =
4814 g_new(ImageInfoSpecificQCow2Encryption, 1);
4815 switch (encrypt_info->format) {
4816 case Q_CRYPTO_BLOCK_FORMAT_QCOW:
4817 qencrypt->format = BLOCKDEV_QCOW2_ENCRYPTION_FORMAT_AES;
0a12f6f8
DB
4818 break;
4819 case Q_CRYPTO_BLOCK_FORMAT_LUKS:
4820 qencrypt->format = BLOCKDEV_QCOW2_ENCRYPTION_FORMAT_LUKS;
4821 qencrypt->u.luks = encrypt_info->u.luks;
4822 break;
4823 default:
4824 abort();
4825 }
4826 /* Since we did shallow copy above, erase any pointers
4827 * in the original info */
4828 memset(&encrypt_info->u, 0, sizeof(encrypt_info->u));
4829 qapi_free_QCryptoBlockInfo(encrypt_info);
4830
4831 spec_info->u.qcow2.data->has_encrypt = true;
4832 spec_info->u.qcow2.data->encrypt = qencrypt;
4833 }
4834
37764dfb
HR
4835 return spec_info;
4836}
4837
38841dcd
HR
4838static int qcow2_has_zero_init(BlockDriverState *bs)
4839{
4840 BDRVQcow2State *s = bs->opaque;
4841 bool preallocated;
4842
4843 if (qemu_in_coroutine()) {
4844 qemu_co_mutex_lock(&s->lock);
4845 }
4846 /*
4847 * Check preallocation status: Preallocated images have all L2
4848 * tables allocated, nonpreallocated images have none. It is
4849 * therefore enough to check the first one.
4850 */
4851 preallocated = s->l1_size > 0 && s->l1_table[0] != 0;
4852 if (qemu_in_coroutine()) {
4853 qemu_co_mutex_unlock(&s->lock);
4854 }
4855
4856 if (!preallocated) {
4857 return 1;
4858 } else if (bs->encrypted) {
4859 return 0;
4860 } else {
4861 return bdrv_has_zero_init(s->data_file->bs);
4862 }
4863}
4864
cf8074b3
KW
4865static int qcow2_save_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
4866 int64_t pos)
20d97356 4867{
ff99129a 4868 BDRVQcow2State *s = bs->opaque;
20d97356 4869
66f82cee 4870 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_SAVE);
5396234b
VSO
4871 return bs->drv->bdrv_co_pwritev_part(bs, qcow2_vm_state_offset(s) + pos,
4872 qiov->size, qiov, 0, 0);
20d97356
BS
4873}
4874
5ddda0b8
KW
4875static int qcow2_load_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
4876 int64_t pos)
20d97356 4877{
ff99129a 4878 BDRVQcow2State *s = bs->opaque;
20d97356 4879
66f82cee 4880 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_LOAD);
df893d25
VSO
4881 return bs->drv->bdrv_co_preadv_part(bs, qcow2_vm_state_offset(s) + pos,
4882 qiov->size, qiov, 0, 0);
20d97356
BS
4883}
4884
9296b3ed
HR
4885/*
4886 * Downgrades an image's version. To achieve this, any incompatible features
4887 * have to be removed.
4888 */
4057a2b2 4889static int qcow2_downgrade(BlockDriverState *bs, int target_version,
d1402b50
HR
4890 BlockDriverAmendStatusCB *status_cb, void *cb_opaque,
4891 Error **errp)
9296b3ed 4892{
ff99129a 4893 BDRVQcow2State *s = bs->opaque;
9296b3ed
HR
4894 int current_version = s->qcow_version;
4895 int ret;
4896
d1402b50
HR
4897 /* This is qcow2_downgrade(), not qcow2_upgrade() */
4898 assert(target_version < current_version);
4899
4900 /* There are no other versions (now) that you can downgrade to */
4901 assert(target_version == 2);
9296b3ed
HR
4902
4903 if (s->refcount_order != 4) {
d1402b50 4904 error_setg(errp, "compat=0.10 requires refcount_bits=16");
9296b3ed
HR
4905 return -ENOTSUP;
4906 }
4907
966b000f
KW
4908 if (has_data_file(bs)) {
4909 error_setg(errp, "Cannot downgrade an image with a data file");
4910 return -ENOTSUP;
4911 }
4912
9296b3ed
HR
4913 /* clear incompatible features */
4914 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
4915 ret = qcow2_mark_clean(bs);
4916 if (ret < 0) {
d1402b50 4917 error_setg_errno(errp, -ret, "Failed to make the image clean");
9296b3ed
HR
4918 return ret;
4919 }
4920 }
4921
4922 /* with QCOW2_INCOMPAT_CORRUPT, it is pretty much impossible to get here in
4923 * the first place; if that happens nonetheless, returning -ENOTSUP is the
4924 * best thing to do anyway */
4925
4926 if (s->incompatible_features) {
d1402b50
HR
4927 error_setg(errp, "Cannot downgrade an image with incompatible features "
4928 "%#" PRIx64 " set", s->incompatible_features);
9296b3ed
HR
4929 return -ENOTSUP;
4930 }
4931
4932 /* since we can ignore compatible features, we can set them to 0 as well */
4933 s->compatible_features = 0;
4934 /* if lazy refcounts have been used, they have already been fixed through
4935 * clearing the dirty flag */
4936
4937 /* clearing autoclear features is trivial */
4938 s->autoclear_features = 0;
4939
8b13976d 4940 ret = qcow2_expand_zero_clusters(bs, status_cb, cb_opaque);
9296b3ed 4941 if (ret < 0) {
d1402b50 4942 error_setg_errno(errp, -ret, "Failed to turn zero into data clusters");
9296b3ed
HR
4943 return ret;
4944 }
4945
4946 s->qcow_version = target_version;
4947 ret = qcow2_update_header(bs);
4948 if (ret < 0) {
4949 s->qcow_version = current_version;
d1402b50 4950 error_setg_errno(errp, -ret, "Failed to update the image header");
9296b3ed
HR
4951 return ret;
4952 }
4953 return 0;
4954}
4955
722efb0c
HR
4956/*
4957 * Upgrades an image's version. While newer versions encompass all
4958 * features of older versions, some things may have to be presented
4959 * differently.
4960 */
4961static int qcow2_upgrade(BlockDriverState *bs, int target_version,
4962 BlockDriverAmendStatusCB *status_cb, void *cb_opaque,
4963 Error **errp)
4964{
4965 BDRVQcow2State *s = bs->opaque;
0a85af35 4966 bool need_snapshot_update;
722efb0c 4967 int current_version = s->qcow_version;
0a85af35 4968 int i;
722efb0c
HR
4969 int ret;
4970
4971 /* This is qcow2_upgrade(), not qcow2_downgrade() */
4972 assert(target_version > current_version);
4973
4974 /* There are no other versions (yet) that you can upgrade to */
4975 assert(target_version == 3);
4976
0a85af35
HR
4977 status_cb(bs, 0, 2, cb_opaque);
4978
4979 /*
4980 * In v2, snapshots do not need to have extra data. v3 requires
4981 * the 64-bit VM state size and the virtual disk size to be
4982 * present.
4983 * qcow2_write_snapshots() will always write the list in the
4984 * v3-compliant format.
4985 */
4986 need_snapshot_update = false;
4987 for (i = 0; i < s->nb_snapshots; i++) {
4988 if (s->snapshots[i].extra_data_size <
4989 sizeof_field(QCowSnapshotExtraData, vm_state_size_large) +
4990 sizeof_field(QCowSnapshotExtraData, disk_size))
4991 {
4992 need_snapshot_update = true;
4993 break;
4994 }
4995 }
4996 if (need_snapshot_update) {
4997 ret = qcow2_write_snapshots(bs);
4998 if (ret < 0) {
4999 error_setg_errno(errp, -ret, "Failed to update the snapshot table");
5000 return ret;
5001 }
5002 }
5003 status_cb(bs, 1, 2, cb_opaque);
722efb0c
HR
5004
5005 s->qcow_version = target_version;
5006 ret = qcow2_update_header(bs);
5007 if (ret < 0) {
5008 s->qcow_version = current_version;
5009 error_setg_errno(errp, -ret, "Failed to update the image header");
5010 return ret;
5011 }
0a85af35 5012 status_cb(bs, 2, 2, cb_opaque);
722efb0c
HR
5013
5014 return 0;
5015}
5016
c293a809
HR
5017typedef enum Qcow2AmendOperation {
5018 /* This is the value Qcow2AmendHelperCBInfo::last_operation will be
5019 * statically initialized to so that the helper CB can discern the first
5020 * invocation from an operation change */
5021 QCOW2_NO_OPERATION = 0,
5022
722efb0c 5023 QCOW2_UPGRADING,
61ce55fc 5024 QCOW2_CHANGING_REFCOUNT_ORDER,
c293a809
HR
5025 QCOW2_DOWNGRADING,
5026} Qcow2AmendOperation;
5027
5028typedef struct Qcow2AmendHelperCBInfo {
5029 /* The code coordinating the amend operations should only modify
5030 * these four fields; the rest will be managed by the CB */
5031 BlockDriverAmendStatusCB *original_status_cb;
5032 void *original_cb_opaque;
5033
5034 Qcow2AmendOperation current_operation;
5035
5036 /* Total number of operations to perform (only set once) */
5037 int total_operations;
5038
5039 /* The following fields are managed by the CB */
5040
5041 /* Number of operations completed */
5042 int operations_completed;
5043
5044 /* Cumulative offset of all completed operations */
5045 int64_t offset_completed;
5046
5047 Qcow2AmendOperation last_operation;
5048 int64_t last_work_size;
5049} Qcow2AmendHelperCBInfo;
5050
5051static void qcow2_amend_helper_cb(BlockDriverState *bs,
5052 int64_t operation_offset,
5053 int64_t operation_work_size, void *opaque)
5054{
5055 Qcow2AmendHelperCBInfo *info = opaque;
5056 int64_t current_work_size;
5057 int64_t projected_work_size;
5058
5059 if (info->current_operation != info->last_operation) {
5060 if (info->last_operation != QCOW2_NO_OPERATION) {
5061 info->offset_completed += info->last_work_size;
5062 info->operations_completed++;
5063 }
5064
5065 info->last_operation = info->current_operation;
5066 }
5067
5068 assert(info->total_operations > 0);
5069 assert(info->operations_completed < info->total_operations);
5070
5071 info->last_work_size = operation_work_size;
5072
5073 current_work_size = info->offset_completed + operation_work_size;
5074
5075 /* current_work_size is the total work size for (operations_completed + 1)
5076 * operations (which includes this one), so multiply it by the number of
5077 * operations not covered and divide it by the number of operations
5078 * covered to get a projection for the operations not covered */
5079 projected_work_size = current_work_size * (info->total_operations -
5080 info->operations_completed - 1)
5081 / (info->operations_completed + 1);
5082
5083 info->original_status_cb(bs, info->offset_completed + operation_offset,
5084 current_work_size + projected_work_size,
5085 info->original_cb_opaque);
5086}
5087
77485434 5088static int qcow2_amend_options(BlockDriverState *bs, QemuOpts *opts,
8b13976d 5089 BlockDriverAmendStatusCB *status_cb,
d1402b50
HR
5090 void *cb_opaque,
5091 Error **errp)
9296b3ed 5092{
ff99129a 5093 BDRVQcow2State *s = bs->opaque;
9296b3ed
HR
5094 int old_version = s->qcow_version, new_version = old_version;
5095 uint64_t new_size = 0;
9b890bdc 5096 const char *backing_file = NULL, *backing_format = NULL, *data_file = NULL;
9296b3ed 5097 bool lazy_refcounts = s->use_lazy_refcounts;
6c3944dc 5098 bool data_file_raw = data_file_is_raw(bs);
1bd0e2d1
CL
5099 const char *compat = NULL;
5100 uint64_t cluster_size = s->cluster_size;
5101 bool encrypt;
4652b8f3 5102 int encformat;
61ce55fc 5103 int refcount_bits = s->refcount_bits;
9296b3ed 5104 int ret;
1bd0e2d1 5105 QemuOptDesc *desc = opts->list->desc;
c293a809 5106 Qcow2AmendHelperCBInfo helper_cb_info;
9296b3ed 5107
1bd0e2d1
CL
5108 while (desc && desc->name) {
5109 if (!qemu_opt_find(opts, desc->name)) {
9296b3ed 5110 /* only change explicitly defined options */
1bd0e2d1 5111 desc++;
9296b3ed
HR
5112 continue;
5113 }
5114
8a17b83c
HR
5115 if (!strcmp(desc->name, BLOCK_OPT_COMPAT_LEVEL)) {
5116 compat = qemu_opt_get(opts, BLOCK_OPT_COMPAT_LEVEL);
1bd0e2d1 5117 if (!compat) {
9296b3ed 5118 /* preserve default */
f7077c98 5119 } else if (!strcmp(compat, "0.10") || !strcmp(compat, "v2")) {
9296b3ed 5120 new_version = 2;
f7077c98 5121 } else if (!strcmp(compat, "1.1") || !strcmp(compat, "v3")) {
9296b3ed
HR
5122 new_version = 3;
5123 } else {
d1402b50 5124 error_setg(errp, "Unknown compatibility level %s", compat);
9296b3ed
HR
5125 return -EINVAL;
5126 }
8a17b83c 5127 } else if (!strcmp(desc->name, BLOCK_OPT_PREALLOC)) {
d1402b50 5128 error_setg(errp, "Cannot change preallocation mode");
9296b3ed 5129 return -ENOTSUP;
8a17b83c
HR
5130 } else if (!strcmp(desc->name, BLOCK_OPT_SIZE)) {
5131 new_size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, 0);
5132 } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FILE)) {
5133 backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
5134 } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FMT)) {
5135 backing_format = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
5136 } else if (!strcmp(desc->name, BLOCK_OPT_ENCRYPT)) {
5137 encrypt = qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT,
b25b387f 5138 !!s->crypto);
f6fa64f6 5139
b25b387f 5140 if (encrypt != !!s->crypto) {
d1402b50
HR
5141 error_setg(errp,
5142 "Changing the encryption flag is not supported");
9296b3ed
HR
5143 return -ENOTSUP;
5144 }
4652b8f3
DB
5145 } else if (!strcmp(desc->name, BLOCK_OPT_ENCRYPT_FORMAT)) {
5146 encformat = qcow2_crypt_method_from_format(
5147 qemu_opt_get(opts, BLOCK_OPT_ENCRYPT_FORMAT));
5148
5149 if (encformat != s->crypt_method_header) {
d1402b50
HR
5150 error_setg(errp,
5151 "Changing the encryption format is not supported");
4652b8f3
DB
5152 return -ENOTSUP;
5153 }
f66afbe2 5154 } else if (g_str_has_prefix(desc->name, "encrypt.")) {
d1402b50
HR
5155 error_setg(errp,
5156 "Changing the encryption parameters is not supported");
f66afbe2 5157 return -ENOTSUP;
8a17b83c
HR
5158 } else if (!strcmp(desc->name, BLOCK_OPT_CLUSTER_SIZE)) {
5159 cluster_size = qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE,
1bd0e2d1
CL
5160 cluster_size);
5161 if (cluster_size != s->cluster_size) {
d1402b50 5162 error_setg(errp, "Changing the cluster size is not supported");
9296b3ed
HR
5163 return -ENOTSUP;
5164 }
8a17b83c
HR
5165 } else if (!strcmp(desc->name, BLOCK_OPT_LAZY_REFCOUNTS)) {
5166 lazy_refcounts = qemu_opt_get_bool(opts, BLOCK_OPT_LAZY_REFCOUNTS,
1bd0e2d1 5167 lazy_refcounts);
06d05fa7 5168 } else if (!strcmp(desc->name, BLOCK_OPT_REFCOUNT_BITS)) {
61ce55fc
HR
5169 refcount_bits = qemu_opt_get_number(opts, BLOCK_OPT_REFCOUNT_BITS,
5170 refcount_bits);
5171
5172 if (refcount_bits <= 0 || refcount_bits > 64 ||
5173 !is_power_of_2(refcount_bits))
5174 {
d1402b50
HR
5175 error_setg(errp, "Refcount width must be a power of two and "
5176 "may not exceed 64 bits");
61ce55fc
HR
5177 return -EINVAL;
5178 }
9b890bdc
KW
5179 } else if (!strcmp(desc->name, BLOCK_OPT_DATA_FILE)) {
5180 data_file = qemu_opt_get(opts, BLOCK_OPT_DATA_FILE);
5181 if (data_file && !has_data_file(bs)) {
5182 error_setg(errp, "data-file can only be set for images that "
5183 "use an external data file");
5184 return -EINVAL;
5185 }
6c3944dc
KW
5186 } else if (!strcmp(desc->name, BLOCK_OPT_DATA_FILE_RAW)) {
5187 data_file_raw = qemu_opt_get_bool(opts, BLOCK_OPT_DATA_FILE_RAW,
5188 data_file_raw);
5189 if (data_file_raw && !data_file_is_raw(bs)) {
5190 error_setg(errp, "data-file-raw cannot be set on existing "
5191 "images");
5192 return -EINVAL;
5193 }
9296b3ed 5194 } else {
164e0f89 5195 /* if this point is reached, this probably means a new option was
9296b3ed 5196 * added without having it covered here */
164e0f89 5197 abort();
9296b3ed 5198 }
1bd0e2d1
CL
5199
5200 desc++;
9296b3ed
HR
5201 }
5202
c293a809
HR
5203 helper_cb_info = (Qcow2AmendHelperCBInfo){
5204 .original_status_cb = status_cb,
5205 .original_cb_opaque = cb_opaque,
722efb0c 5206 .total_operations = (new_version != old_version)
61ce55fc 5207 + (s->refcount_bits != refcount_bits)
c293a809
HR
5208 };
5209
1038bbb8
HR
5210 /* Upgrade first (some features may require compat=1.1) */
5211 if (new_version > old_version) {
722efb0c
HR
5212 helper_cb_info.current_operation = QCOW2_UPGRADING;
5213 ret = qcow2_upgrade(bs, new_version, &qcow2_amend_helper_cb,
5214 &helper_cb_info, errp);
1038bbb8 5215 if (ret < 0) {
1038bbb8 5216 return ret;
9296b3ed
HR
5217 }
5218 }
5219
61ce55fc
HR
5220 if (s->refcount_bits != refcount_bits) {
5221 int refcount_order = ctz32(refcount_bits);
61ce55fc
HR
5222
5223 if (new_version < 3 && refcount_bits != 16) {
d1402b50
HR
5224 error_setg(errp, "Refcount widths other than 16 bits require "
5225 "compatibility level 1.1 or above (use compat=1.1 or "
5226 "greater)");
61ce55fc
HR
5227 return -EINVAL;
5228 }
5229
5230 helper_cb_info.current_operation = QCOW2_CHANGING_REFCOUNT_ORDER;
5231 ret = qcow2_change_refcount_order(bs, refcount_order,
5232 &qcow2_amend_helper_cb,
d1402b50 5233 &helper_cb_info, errp);
61ce55fc 5234 if (ret < 0) {
61ce55fc
HR
5235 return ret;
5236 }
5237 }
5238
6c3944dc
KW
5239 /* data-file-raw blocks backing files, so clear it first if requested */
5240 if (data_file_raw) {
5241 s->autoclear_features |= QCOW2_AUTOCLEAR_DATA_FILE_RAW;
5242 } else {
5243 s->autoclear_features &= ~QCOW2_AUTOCLEAR_DATA_FILE_RAW;
5244 }
5245
9b890bdc
KW
5246 if (data_file) {
5247 g_free(s->image_data_file);
5248 s->image_data_file = *data_file ? g_strdup(data_file) : NULL;
5249 }
5250
5251 ret = qcow2_update_header(bs);
5252 if (ret < 0) {
5253 error_setg_errno(errp, -ret, "Failed to update the image header");
5254 return ret;
5255 }
5256
9296b3ed 5257 if (backing_file || backing_format) {
e4603fe1
KW
5258 ret = qcow2_change_backing_file(bs,
5259 backing_file ?: s->image_backing_file,
5260 backing_format ?: s->image_backing_format);
9296b3ed 5261 if (ret < 0) {
d1402b50 5262 error_setg_errno(errp, -ret, "Failed to change the backing file");
9296b3ed
HR
5263 return ret;
5264 }
5265 }
5266
5267 if (s->use_lazy_refcounts != lazy_refcounts) {
5268 if (lazy_refcounts) {
1038bbb8 5269 if (new_version < 3) {
d1402b50
HR
5270 error_setg(errp, "Lazy refcounts only supported with "
5271 "compatibility level 1.1 and above (use compat=1.1 "
5272 "or greater)");
9296b3ed
HR
5273 return -EINVAL;
5274 }
5275 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
5276 ret = qcow2_update_header(bs);
5277 if (ret < 0) {
5278 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
d1402b50 5279 error_setg_errno(errp, -ret, "Failed to update the image header");
9296b3ed
HR
5280 return ret;
5281 }
5282 s->use_lazy_refcounts = true;
5283 } else {
5284 /* make image clean first */
5285 ret = qcow2_mark_clean(bs);
5286 if (ret < 0) {
d1402b50 5287 error_setg_errno(errp, -ret, "Failed to make the image clean");
9296b3ed
HR
5288 return ret;
5289 }
5290 /* now disallow lazy refcounts */
5291 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
5292 ret = qcow2_update_header(bs);
5293 if (ret < 0) {
5294 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
d1402b50 5295 error_setg_errno(errp, -ret, "Failed to update the image header");
9296b3ed
HR
5296 return ret;
5297 }
5298 s->use_lazy_refcounts = false;
5299 }
5300 }
5301
5302 if (new_size) {
d861ab3a
KW
5303 BlockBackend *blk = blk_new(bdrv_get_aio_context(bs),
5304 BLK_PERM_RESIZE, BLK_PERM_ALL);
d1402b50 5305 ret = blk_insert_bs(blk, bs, errp);
d7086422 5306 if (ret < 0) {
d7086422
KW
5307 blk_unref(blk);
5308 return ret;
5309 }
5310
d1402b50 5311 ret = blk_truncate(blk, new_size, PREALLOC_MODE_OFF, errp);
70b27f36 5312 blk_unref(blk);
9296b3ed
HR
5313 if (ret < 0) {
5314 return ret;
5315 }
5316 }
5317
1038bbb8
HR
5318 /* Downgrade last (so unsupported features can be removed before) */
5319 if (new_version < old_version) {
c293a809
HR
5320 helper_cb_info.current_operation = QCOW2_DOWNGRADING;
5321 ret = qcow2_downgrade(bs, new_version, &qcow2_amend_helper_cb,
d1402b50 5322 &helper_cb_info, errp);
1038bbb8
HR
5323 if (ret < 0) {
5324 return ret;
5325 }
5326 }
5327
9296b3ed
HR
5328 return 0;
5329}
5330
85186ebd
HR
5331/*
5332 * If offset or size are negative, respectively, they will not be included in
5333 * the BLOCK_IMAGE_CORRUPTED event emitted.
5334 * fatal will be ignored for read-only BDS; corruptions found there will always
5335 * be considered non-fatal.
5336 */
5337void qcow2_signal_corruption(BlockDriverState *bs, bool fatal, int64_t offset,
5338 int64_t size, const char *message_format, ...)
5339{
ff99129a 5340 BDRVQcow2State *s = bs->opaque;
dc881b44 5341 const char *node_name;
85186ebd
HR
5342 char *message;
5343 va_list ap;
5344
ddf3b47e 5345 fatal = fatal && bdrv_is_writable(bs);
85186ebd
HR
5346
5347 if (s->signaled_corruption &&
5348 (!fatal || (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT)))
5349 {
5350 return;
5351 }
5352
5353 va_start(ap, message_format);
5354 message = g_strdup_vprintf(message_format, ap);
5355 va_end(ap);
5356
5357 if (fatal) {
5358 fprintf(stderr, "qcow2: Marking image as corrupt: %s; further "
5359 "corruption events will be suppressed\n", message);
5360 } else {
5361 fprintf(stderr, "qcow2: Image is corrupt: %s; further non-fatal "
5362 "corruption events will be suppressed\n", message);
5363 }
5364
dc881b44
AG
5365 node_name = bdrv_get_node_name(bs);
5366 qapi_event_send_block_image_corrupted(bdrv_get_device_name(bs),
5367 *node_name != '\0', node_name,
5368 message, offset >= 0, offset,
5369 size >= 0, size,
3ab72385 5370 fatal);
85186ebd
HR
5371 g_free(message);
5372
5373 if (fatal) {
5374 qcow2_mark_corrupt(bs);
5375 bs->drv = NULL; /* make BDS unusable */
5376 }
5377
5378 s->signaled_corruption = true;
5379}
5380
1bd0e2d1
CL
5381static QemuOptsList qcow2_create_opts = {
5382 .name = "qcow2-create-opts",
5383 .head = QTAILQ_HEAD_INITIALIZER(qcow2_create_opts.head),
5384 .desc = {
5385 {
5386 .name = BLOCK_OPT_SIZE,
5387 .type = QEMU_OPT_SIZE,
5388 .help = "Virtual disk size"
5389 },
5390 {
5391 .name = BLOCK_OPT_COMPAT_LEVEL,
5392 .type = QEMU_OPT_STRING,
f7077c98 5393 .help = "Compatibility level (v2 [0.10] or v3 [1.1])"
1bd0e2d1
CL
5394 },
5395 {
5396 .name = BLOCK_OPT_BACKING_FILE,
5397 .type = QEMU_OPT_STRING,
5398 .help = "File name of a base image"
5399 },
5400 {
5401 .name = BLOCK_OPT_BACKING_FMT,
5402 .type = QEMU_OPT_STRING,
5403 .help = "Image format of the base image"
5404 },
9b890bdc
KW
5405 {
5406 .name = BLOCK_OPT_DATA_FILE,
5407 .type = QEMU_OPT_STRING,
5408 .help = "File name of an external data file"
5409 },
6c3944dc
KW
5410 {
5411 .name = BLOCK_OPT_DATA_FILE_RAW,
5412 .type = QEMU_OPT_BOOL,
5413 .help = "The external data file must stay valid as a raw image"
5414 },
1bd0e2d1
CL
5415 {
5416 .name = BLOCK_OPT_ENCRYPT,
5417 .type = QEMU_OPT_BOOL,
0cb8d47b
DB
5418 .help = "Encrypt the image with format 'aes'. (Deprecated "
5419 "in favor of " BLOCK_OPT_ENCRYPT_FORMAT "=aes)",
5420 },
5421 {
5422 .name = BLOCK_OPT_ENCRYPT_FORMAT,
5423 .type = QEMU_OPT_STRING,
4652b8f3 5424 .help = "Encrypt the image, format choices: 'aes', 'luks'",
1bd0e2d1 5425 },
4652b8f3
DB
5426 BLOCK_CRYPTO_OPT_DEF_KEY_SECRET("encrypt.",
5427 "ID of secret providing qcow AES key or LUKS passphrase"),
5428 BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_ALG("encrypt."),
5429 BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_MODE("encrypt."),
5430 BLOCK_CRYPTO_OPT_DEF_LUKS_IVGEN_ALG("encrypt."),
5431 BLOCK_CRYPTO_OPT_DEF_LUKS_IVGEN_HASH_ALG("encrypt."),
5432 BLOCK_CRYPTO_OPT_DEF_LUKS_HASH_ALG("encrypt."),
5433 BLOCK_CRYPTO_OPT_DEF_LUKS_ITER_TIME("encrypt."),
1bd0e2d1
CL
5434 {
5435 .name = BLOCK_OPT_CLUSTER_SIZE,
5436 .type = QEMU_OPT_SIZE,
5437 .help = "qcow2 cluster size",
5438 .def_value_str = stringify(DEFAULT_CLUSTER_SIZE)
5439 },
5440 {
5441 .name = BLOCK_OPT_PREALLOC,
5442 .type = QEMU_OPT_STRING,
0e4271b7
HT
5443 .help = "Preallocation mode (allowed values: off, metadata, "
5444 "falloc, full)"
1bd0e2d1
CL
5445 },
5446 {
5447 .name = BLOCK_OPT_LAZY_REFCOUNTS,
5448 .type = QEMU_OPT_BOOL,
5449 .help = "Postpone refcount updates",
5450 .def_value_str = "off"
5451 },
06d05fa7
HR
5452 {
5453 .name = BLOCK_OPT_REFCOUNT_BITS,
5454 .type = QEMU_OPT_NUMBER,
5455 .help = "Width of a reference count entry in bits",
5456 .def_value_str = "16"
5457 },
1bd0e2d1
CL
5458 { /* end of list */ }
5459 }
20d97356
BS
5460};
5461
2654267c
HR
5462static const char *const qcow2_strong_runtime_opts[] = {
5463 "encrypt." BLOCK_CRYPTO_OPT_QCOW_KEY_SECRET,
5464
5465 NULL
5466};
5467
5f535a94 5468BlockDriver bdrv_qcow2 = {
7c80ab3f 5469 .format_name = "qcow2",
ff99129a 5470 .instance_size = sizeof(BDRVQcow2State),
7c80ab3f
JS
5471 .bdrv_probe = qcow2_probe,
5472 .bdrv_open = qcow2_open,
5473 .bdrv_close = qcow2_close,
21d82ac9 5474 .bdrv_reopen_prepare = qcow2_reopen_prepare,
5b0959a7
KW
5475 .bdrv_reopen_commit = qcow2_reopen_commit,
5476 .bdrv_reopen_abort = qcow2_reopen_abort,
5365f44d 5477 .bdrv_join_options = qcow2_join_options,
862f215f 5478 .bdrv_child_perm = bdrv_format_default_perms,
efc75e2a 5479 .bdrv_co_create_opts = qcow2_co_create_opts,
b0292b85 5480 .bdrv_co_create = qcow2_co_create,
38841dcd 5481 .bdrv_has_zero_init = qcow2_has_zero_init,
1dcaf527 5482 .bdrv_has_zero_init_truncate = bdrv_has_zero_init_1,
a320fb04 5483 .bdrv_co_block_status = qcow2_co_block_status,
7c80ab3f 5484
df893d25 5485 .bdrv_co_preadv_part = qcow2_co_preadv_part,
5396234b 5486 .bdrv_co_pwritev_part = qcow2_co_pwritev_part,
eb489bb1 5487 .bdrv_co_flush_to_os = qcow2_co_flush_to_os,
419b19d9 5488
5544b59f 5489 .bdrv_co_pwrite_zeroes = qcow2_co_pwrite_zeroes,
82e8a788 5490 .bdrv_co_pdiscard = qcow2_co_pdiscard,
fd9fcd37
FZ
5491 .bdrv_co_copy_range_from = qcow2_co_copy_range_from,
5492 .bdrv_co_copy_range_to = qcow2_co_copy_range_to,
061ca8a3 5493 .bdrv_co_truncate = qcow2_co_truncate,
5396234b 5494 .bdrv_co_pwritev_compressed_part = qcow2_co_pwritev_compressed_part,
491d27e2 5495 .bdrv_make_empty = qcow2_make_empty,
20d97356
BS
5496
5497 .bdrv_snapshot_create = qcow2_snapshot_create,
5498 .bdrv_snapshot_goto = qcow2_snapshot_goto,
5499 .bdrv_snapshot_delete = qcow2_snapshot_delete,
5500 .bdrv_snapshot_list = qcow2_snapshot_list,
1bd0e2d1 5501 .bdrv_snapshot_load_tmp = qcow2_snapshot_load_tmp,
c501c352 5502 .bdrv_measure = qcow2_measure,
1bd0e2d1 5503 .bdrv_get_info = qcow2_get_info,
37764dfb 5504 .bdrv_get_specific_info = qcow2_get_specific_info,
20d97356 5505
7c80ab3f
JS
5506 .bdrv_save_vmstate = qcow2_save_vmstate,
5507 .bdrv_load_vmstate = qcow2_load_vmstate,
20d97356 5508
8ee79e70 5509 .supports_backing = true,
20d97356
BS
5510 .bdrv_change_backing_file = qcow2_change_backing_file,
5511
d34682cd 5512 .bdrv_refresh_limits = qcow2_refresh_limits,
2b148f39 5513 .bdrv_co_invalidate_cache = qcow2_co_invalidate_cache,
ec6d8912 5514 .bdrv_inactivate = qcow2_inactivate,
06d9260f 5515
1bd0e2d1 5516 .create_opts = &qcow2_create_opts,
2654267c 5517 .strong_runtime_opts = qcow2_strong_runtime_opts,
8a2ce0bc 5518 .mutable_opts = mutable_opts,
2fd61638 5519 .bdrv_co_check = qcow2_co_check,
c282e1fd 5520 .bdrv_amend_options = qcow2_amend_options,
279621c0
AG
5521
5522 .bdrv_detach_aio_context = qcow2_detach_aio_context,
5523 .bdrv_attach_aio_context = qcow2_attach_aio_context,
1b6b0562 5524
d2c3080e
VSO
5525 .bdrv_co_can_store_new_dirty_bitmap = qcow2_co_can_store_new_dirty_bitmap,
5526 .bdrv_co_remove_persistent_dirty_bitmap =
5527 qcow2_co_remove_persistent_dirty_bitmap,
20d97356
BS
5528};
5529
5efa9d5a
AL
5530static void bdrv_qcow2_init(void)
5531{
5532 bdrv_register(&bdrv_qcow2);
5533}
5534
5535block_init(bdrv_qcow2_init);