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