]> git.proxmox.com Git - mirror_qemu.git/blame - block/qcow2.c
block/backup: centralize copy_bitmap initialization
[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);
3fc48d09 2062 qemu_iovec_reset(&hd_qiov);
ecfe1863 2063 qemu_iovec_add(&hd_qiov, cluster_data, cur_bytes);
5ebaa27e
FZ
2064 }
2065
2066 BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);
966b000f 2067 ret = bdrv_co_preadv(s->data_file,
ecfe1863
KW
2068 cluster_offset + offset_in_cluster,
2069 cur_bytes, &hd_qiov, 0);
5ebaa27e 2070 if (ret < 0) {
3fc48d09 2071 goto fail;
5ebaa27e 2072 }
8336aafa 2073 if (bs->encrypted) {
b25b387f 2074 assert(s->crypto);
ecfe1863
KW
2075 assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);
2076 assert((cur_bytes & (BDRV_SECTOR_SIZE - 1)) == 0);
8ac0f15f
VSO
2077 if (qcow2_co_decrypt(bs, cluster_offset, offset,
2078 cluster_data, cur_bytes) < 0) {
f6fa64f6
DB
2079 ret = -EIO;
2080 goto fail;
2081 }
ecfe1863 2082 qemu_iovec_from_buf(qiov, bytes_done, cluster_data, cur_bytes);
5ebaa27e 2083 }
68d000a3
KW
2084 break;
2085
2086 default:
2087 g_assert_not_reached();
2088 ret = -EIO;
2089 goto fail;
faf575c1 2090 }
f141eafe 2091
ecfe1863
KW
2092 bytes -= cur_bytes;
2093 offset += cur_bytes;
2094 bytes_done += cur_bytes;
5ebaa27e 2095 }
3fc48d09 2096 ret = 0;
faf575c1 2097
3fc48d09 2098fail:
3fc48d09 2099 qemu_iovec_destroy(&hd_qiov);
dea43a65 2100 qemu_vfree(cluster_data);
68d100e9
KW
2101
2102 return ret;
585f8587
FB
2103}
2104
ee22a9d8
AG
2105/* Check if it's possible to merge a write request with the writing of
2106 * the data from the COW regions */
2107static bool merge_cow(uint64_t offset, unsigned bytes,
2108 QEMUIOVector *hd_qiov, QCowL2Meta *l2meta)
2109{
2110 QCowL2Meta *m;
2111
2112 for (m = l2meta; m != NULL; m = m->next) {
2113 /* If both COW regions are empty then there's nothing to merge */
2114 if (m->cow_start.nb_bytes == 0 && m->cow_end.nb_bytes == 0) {
2115 continue;
2116 }
2117
c8bb23cb
AN
2118 /* If COW regions are handled already, skip this too */
2119 if (m->skip_cow) {
2120 continue;
2121 }
2122
ee22a9d8
AG
2123 /* The data (middle) region must be immediately after the
2124 * start region */
2125 if (l2meta_cow_start(m) + m->cow_start.nb_bytes != offset) {
2126 continue;
2127 }
2128
2129 /* The end region must be immediately after the data (middle)
2130 * region */
2131 if (m->offset + m->cow_end.offset != offset + bytes) {
2132 continue;
2133 }
2134
2135 /* Make sure that adding both COW regions to the QEMUIOVector
2136 * does not exceed IOV_MAX */
2137 if (hd_qiov->niov > IOV_MAX - 2) {
2138 continue;
2139 }
2140
2141 m->data_qiov = hd_qiov;
2142 return true;
2143 }
2144
2145 return false;
2146}
2147
c8bb23cb
AN
2148static bool is_unallocated(BlockDriverState *bs, int64_t offset, int64_t bytes)
2149{
2150 int64_t nr;
2151 return !bytes ||
170d3bd3
AS
2152 (!bdrv_is_allocated_above(bs, NULL, false, offset, bytes, &nr) &&
2153 nr == bytes);
c8bb23cb
AN
2154}
2155
2156static bool is_zero_cow(BlockDriverState *bs, QCowL2Meta *m)
2157{
2158 /*
2159 * This check is designed for optimization shortcut so it must be
2160 * efficient.
2161 * Instead of is_zero(), use is_unallocated() as it is faster (but not
2162 * as accurate and can result in false negatives).
2163 */
2164 return is_unallocated(bs, m->offset + m->cow_start.offset,
2165 m->cow_start.nb_bytes) &&
2166 is_unallocated(bs, m->offset + m->cow_end.offset,
2167 m->cow_end.nb_bytes);
2168}
2169
2170static int handle_alloc_space(BlockDriverState *bs, QCowL2Meta *l2meta)
2171{
2172 BDRVQcow2State *s = bs->opaque;
2173 QCowL2Meta *m;
2174
2175 if (!(s->data_file->bs->supported_zero_flags & BDRV_REQ_NO_FALLBACK)) {
2176 return 0;
2177 }
2178
2179 if (bs->encrypted) {
2180 return 0;
2181 }
2182
2183 for (m = l2meta; m != NULL; m = m->next) {
2184 int ret;
2185
2186 if (!m->cow_start.nb_bytes && !m->cow_end.nb_bytes) {
2187 continue;
2188 }
2189
2190 if (!is_zero_cow(bs, m)) {
2191 continue;
2192 }
2193
2194 /*
2195 * instead of writing zero COW buffers,
2196 * efficiently zero out the whole clusters
2197 */
2198
2199 ret = qcow2_pre_write_overlap_check(bs, 0, m->alloc_offset,
2200 m->nb_clusters * s->cluster_size,
2201 true);
2202 if (ret < 0) {
2203 return ret;
2204 }
2205
2206 BLKDBG_EVENT(bs->file, BLKDBG_CLUSTER_ALLOC_SPACE);
2207 ret = bdrv_co_pwrite_zeroes(s->data_file, m->alloc_offset,
2208 m->nb_clusters * s->cluster_size,
2209 BDRV_REQ_NO_FALLBACK);
2210 if (ret < 0) {
2211 if (ret != -ENOTSUP && ret != -EAGAIN) {
2212 return ret;
2213 }
2214 continue;
2215 }
2216
2217 trace_qcow2_skip_cow(qemu_coroutine_self(), m->offset, m->nb_clusters);
2218 m->skip_cow = true;
2219 }
2220 return 0;
2221}
2222
d46a0bb2
KW
2223static coroutine_fn int qcow2_co_pwritev(BlockDriverState *bs, uint64_t offset,
2224 uint64_t bytes, QEMUIOVector *qiov,
2225 int flags)
585f8587 2226{
ff99129a 2227 BDRVQcow2State *s = bs->opaque;
d46a0bb2 2228 int offset_in_cluster;
68d100e9 2229 int ret;
d46a0bb2 2230 unsigned int cur_bytes; /* number of sectors in current iteration */
c2bdd990 2231 uint64_t cluster_offset;
3fc48d09
FZ
2232 QEMUIOVector hd_qiov;
2233 uint64_t bytes_done = 0;
2234 uint8_t *cluster_data = NULL;
8d2497c3 2235 QCowL2Meta *l2meta = NULL;
c2271403 2236
d46a0bb2 2237 trace_qcow2_writev_start_req(qemu_coroutine_self(), offset, bytes);
3cce16f4 2238
3fc48d09
FZ
2239 qemu_iovec_init(&hd_qiov, qiov->niov);
2240
3fc48d09
FZ
2241 qemu_co_mutex_lock(&s->lock);
2242
d46a0bb2 2243 while (bytes != 0) {
3fc48d09 2244
f50f88b9 2245 l2meta = NULL;
cf5c1a23 2246
3cce16f4 2247 trace_qcow2_writev_start_part(qemu_coroutine_self());
d46a0bb2
KW
2248 offset_in_cluster = offset_into_cluster(s, offset);
2249 cur_bytes = MIN(bytes, INT_MAX);
2250 if (bs->encrypted) {
2251 cur_bytes = MIN(cur_bytes,
2252 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size
2253 - offset_in_cluster);
5ebaa27e 2254 }
095a9c58 2255
d46a0bb2
KW
2256 ret = qcow2_alloc_cluster_offset(bs, offset, &cur_bytes,
2257 &cluster_offset, &l2meta);
5ebaa27e 2258 if (ret < 0) {
5447c3a0 2259 goto out_locked;
5ebaa27e 2260 }
148da7ea 2261
5ebaa27e 2262 assert((cluster_offset & 511) == 0);
148da7ea 2263
5447c3a0
VSO
2264 ret = qcow2_pre_write_overlap_check(bs, 0,
2265 cluster_offset + offset_in_cluster,
2266 cur_bytes, true);
2267 if (ret < 0) {
2268 goto out_locked;
2269 }
2270
2271 qemu_co_mutex_unlock(&s->lock);
2272
3fc48d09 2273 qemu_iovec_reset(&hd_qiov);
d46a0bb2 2274 qemu_iovec_concat(&hd_qiov, qiov, bytes_done, cur_bytes);
6f5f060b 2275
8336aafa 2276 if (bs->encrypted) {
b25b387f 2277 assert(s->crypto);
3fc48d09 2278 if (!cluster_data) {
9a4f4c31 2279 cluster_data = qemu_try_blockalign(bs->file->bs,
de82815d
KW
2280 QCOW_MAX_CRYPT_CLUSTERS
2281 * s->cluster_size);
2282 if (cluster_data == NULL) {
2283 ret = -ENOMEM;
5447c3a0 2284 goto out_unlocked;
de82815d 2285 }
5ebaa27e 2286 }
6f5f060b 2287
3fc48d09 2288 assert(hd_qiov.size <=
5ebaa27e 2289 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
d5e6b161 2290 qemu_iovec_to_buf(&hd_qiov, 0, cluster_data, hd_qiov.size);
6f5f060b 2291
8ac0f15f
VSO
2292 if (qcow2_co_encrypt(bs, cluster_offset, offset,
2293 cluster_data, cur_bytes) < 0) {
f6fa64f6 2294 ret = -EIO;
5447c3a0 2295 goto out_unlocked;
f6fa64f6 2296 }
6f5f060b 2297
3fc48d09 2298 qemu_iovec_reset(&hd_qiov);
d46a0bb2 2299 qemu_iovec_add(&hd_qiov, cluster_data, cur_bytes);
5ebaa27e 2300 }
6f5f060b 2301
c8bb23cb
AN
2302 /* Try to efficiently initialize the physical space with zeroes */
2303 ret = handle_alloc_space(bs, l2meta);
2304 if (ret < 0) {
2305 goto out_unlocked;
2306 }
2307
ee22a9d8
AG
2308 /* If we need to do COW, check if it's possible to merge the
2309 * writing of the guest data together with that of the COW regions.
2310 * If it's not possible (or not necessary) then write the
2311 * guest data now. */
2312 if (!merge_cow(offset, cur_bytes, &hd_qiov, l2meta)) {
ee22a9d8
AG
2313 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO);
2314 trace_qcow2_writev_data(qemu_coroutine_self(),
2315 cluster_offset + offset_in_cluster);
966b000f 2316 ret = bdrv_co_pwritev(s->data_file,
ee22a9d8
AG
2317 cluster_offset + offset_in_cluster,
2318 cur_bytes, &hd_qiov, 0);
ee22a9d8 2319 if (ret < 0) {
5447c3a0 2320 goto out_unlocked;
ee22a9d8 2321 }
5ebaa27e 2322 }
f141eafe 2323
5447c3a0
VSO
2324 qemu_co_mutex_lock(&s->lock);
2325
fd9fcd37
FZ
2326 ret = qcow2_handle_l2meta(bs, &l2meta, true);
2327 if (ret) {
5447c3a0 2328 goto out_locked;
f50f88b9 2329 }
0fa9131a 2330
d46a0bb2
KW
2331 bytes -= cur_bytes;
2332 offset += cur_bytes;
2333 bytes_done += cur_bytes;
2334 trace_qcow2_writev_done_part(qemu_coroutine_self(), cur_bytes);
5ebaa27e 2335 }
3fc48d09 2336 ret = 0;
5447c3a0 2337 goto out_locked;
faf575c1 2338
5447c3a0
VSO
2339out_unlocked:
2340 qemu_co_mutex_lock(&s->lock);
2341
2342out_locked:
fd9fcd37 2343 qcow2_handle_l2meta(bs, &l2meta, false);
0fa9131a 2344
a8c57408
PB
2345 qemu_co_mutex_unlock(&s->lock);
2346
3fc48d09 2347 qemu_iovec_destroy(&hd_qiov);
dea43a65 2348 qemu_vfree(cluster_data);
3cce16f4 2349 trace_qcow2_writev_done_req(qemu_coroutine_self(), ret);
42496d62 2350
68d100e9 2351 return ret;
585f8587
FB
2352}
2353
ec6d8912
KW
2354static int qcow2_inactivate(BlockDriverState *bs)
2355{
2356 BDRVQcow2State *s = bs->opaque;
2357 int ret, result = 0;
5f72826e 2358 Error *local_err = NULL;
ec6d8912 2359
83a8c775
PB
2360 qcow2_store_persistent_dirty_bitmaps(bs, &local_err);
2361 if (local_err != NULL) {
2362 result = -EINVAL;
132adb68
VSO
2363 error_reportf_err(local_err, "Lost persistent bitmaps during "
2364 "inactivation of node '%s': ",
2365 bdrv_get_device_or_node_name(bs));
83a8c775
PB
2366 }
2367
ec6d8912
KW
2368 ret = qcow2_cache_flush(bs, s->l2_table_cache);
2369 if (ret) {
2370 result = ret;
2371 error_report("Failed to flush the L2 table cache: %s",
2372 strerror(-ret));
2373 }
2374
2375 ret = qcow2_cache_flush(bs, s->refcount_block_cache);
2376 if (ret) {
2377 result = ret;
2378 error_report("Failed to flush the refcount block cache: %s",
2379 strerror(-ret));
2380 }
2381
2382 if (result == 0) {
2383 qcow2_mark_clean(bs);
2384 }
2385
2386 return result;
2387}
2388
7c80ab3f 2389static void qcow2_close(BlockDriverState *bs)
585f8587 2390{
ff99129a 2391 BDRVQcow2State *s = bs->opaque;
de82815d 2392 qemu_vfree(s->l1_table);
cf93980e
HR
2393 /* else pre-write overlap checks in cache_destroy may crash */
2394 s->l1_table = NULL;
29c1a730 2395
140fd5a6 2396 if (!(s->flags & BDRV_O_INACTIVE)) {
ec6d8912 2397 qcow2_inactivate(bs);
27eb6c09 2398 }
c61d0004 2399
279621c0 2400 cache_clean_timer_del(bs);
e64d4072
AG
2401 qcow2_cache_destroy(s->l2_table_cache);
2402 qcow2_cache_destroy(s->refcount_block_cache);
29c1a730 2403
b25b387f
DB
2404 qcrypto_block_free(s->crypto);
2405 s->crypto = NULL;
f6fa64f6 2406
6744cbab 2407 g_free(s->unknown_header_fields);
75bab85c 2408 cleanup_unknown_header_ext(bs);
6744cbab 2409
9b890bdc 2410 g_free(s->image_data_file);
e4603fe1
KW
2411 g_free(s->image_backing_file);
2412 g_free(s->image_backing_format);
2413
0e8c08be
KW
2414 if (has_data_file(bs)) {
2415 bdrv_unref_child(bs, s->data_file);
2416 }
2417
ed6ccf0f 2418 qcow2_refcount_close(bs);
28c1202b 2419 qcow2_free_snapshots(bs);
585f8587
FB
2420}
2421
2b148f39
PB
2422static void coroutine_fn qcow2_co_invalidate_cache(BlockDriverState *bs,
2423 Error **errp)
06d9260f 2424{
ff99129a 2425 BDRVQcow2State *s = bs->opaque;
06d9260f 2426 int flags = s->flags;
b25b387f 2427 QCryptoBlock *crypto = NULL;
acdfb480 2428 QDict *options;
5a8a30db
KW
2429 Error *local_err = NULL;
2430 int ret;
06d9260f
AL
2431
2432 /*
2433 * Backing files are read-only which makes all of their metadata immutable,
2434 * that means we don't have to worry about reopening them here.
2435 */
2436
b25b387f
DB
2437 crypto = s->crypto;
2438 s->crypto = NULL;
06d9260f
AL
2439
2440 qcow2_close(bs);
2441
ff99129a 2442 memset(s, 0, sizeof(BDRVQcow2State));
d475e5ac 2443 options = qdict_clone_shallow(bs->options);
5a8a30db 2444
140fd5a6 2445 flags &= ~BDRV_O_INACTIVE;
2b148f39 2446 qemu_co_mutex_lock(&s->lock);
4e4bf5c4 2447 ret = qcow2_do_open(bs, options, flags, &local_err);
2b148f39 2448 qemu_co_mutex_unlock(&s->lock);
cb3e7f08 2449 qobject_unref(options);
5a8a30db 2450 if (local_err) {
4b576648
MA
2451 error_propagate_prepend(errp, local_err,
2452 "Could not reopen qcow2 layer: ");
191fb11b 2453 bs->drv = NULL;
5a8a30db
KW
2454 return;
2455 } else if (ret < 0) {
2456 error_setg_errno(errp, -ret, "Could not reopen qcow2 layer");
191fb11b 2457 bs->drv = NULL;
5a8a30db
KW
2458 return;
2459 }
acdfb480 2460
b25b387f 2461 s->crypto = crypto;
06d9260f
AL
2462}
2463
e24e49e6
KW
2464static size_t header_ext_add(char *buf, uint32_t magic, const void *s,
2465 size_t len, size_t buflen)
2466{
2467 QCowExtension *ext_backing_fmt = (QCowExtension*) buf;
2468 size_t ext_len = sizeof(QCowExtension) + ((len + 7) & ~7);
2469
2470 if (buflen < ext_len) {
2471 return -ENOSPC;
2472 }
2473
2474 *ext_backing_fmt = (QCowExtension) {
2475 .magic = cpu_to_be32(magic),
2476 .len = cpu_to_be32(len),
2477 };
0647d47c
SH
2478
2479 if (len) {
2480 memcpy(buf + sizeof(QCowExtension), s, len);
2481 }
e24e49e6
KW
2482
2483 return ext_len;
2484}
2485
756e6736 2486/*
e24e49e6
KW
2487 * Updates the qcow2 header, including the variable length parts of it, i.e.
2488 * the backing file name and all extensions. qcow2 was not designed to allow
2489 * such changes, so if we run out of space (we can only use the first cluster)
2490 * this function may fail.
756e6736
KW
2491 *
2492 * Returns 0 on success, -errno in error cases.
2493 */
e24e49e6 2494int qcow2_update_header(BlockDriverState *bs)
756e6736 2495{
ff99129a 2496 BDRVQcow2State *s = bs->opaque;
e24e49e6
KW
2497 QCowHeader *header;
2498 char *buf;
2499 size_t buflen = s->cluster_size;
756e6736 2500 int ret;
e24e49e6
KW
2501 uint64_t total_size;
2502 uint32_t refcount_table_clusters;
6744cbab 2503 size_t header_length;
75bab85c 2504 Qcow2UnknownHeaderExtension *uext;
756e6736 2505
e24e49e6 2506 buf = qemu_blockalign(bs, buflen);
756e6736 2507
e24e49e6
KW
2508 /* Header structure */
2509 header = (QCowHeader*) buf;
756e6736 2510
e24e49e6
KW
2511 if (buflen < sizeof(*header)) {
2512 ret = -ENOSPC;
2513 goto fail;
756e6736
KW
2514 }
2515
6744cbab 2516 header_length = sizeof(*header) + s->unknown_header_fields_size;
e24e49e6
KW
2517 total_size = bs->total_sectors * BDRV_SECTOR_SIZE;
2518 refcount_table_clusters = s->refcount_table_size >> (s->cluster_bits - 3);
2519
2520 *header = (QCowHeader) {
6744cbab 2521 /* Version 2 fields */
e24e49e6 2522 .magic = cpu_to_be32(QCOW_MAGIC),
6744cbab 2523 .version = cpu_to_be32(s->qcow_version),
e24e49e6
KW
2524 .backing_file_offset = 0,
2525 .backing_file_size = 0,
2526 .cluster_bits = cpu_to_be32(s->cluster_bits),
2527 .size = cpu_to_be64(total_size),
2528 .crypt_method = cpu_to_be32(s->crypt_method_header),
2529 .l1_size = cpu_to_be32(s->l1_size),
2530 .l1_table_offset = cpu_to_be64(s->l1_table_offset),
2531 .refcount_table_offset = cpu_to_be64(s->refcount_table_offset),
2532 .refcount_table_clusters = cpu_to_be32(refcount_table_clusters),
2533 .nb_snapshots = cpu_to_be32(s->nb_snapshots),
2534 .snapshots_offset = cpu_to_be64(s->snapshots_offset),
6744cbab
KW
2535
2536 /* Version 3 fields */
2537 .incompatible_features = cpu_to_be64(s->incompatible_features),
2538 .compatible_features = cpu_to_be64(s->compatible_features),
2539 .autoclear_features = cpu_to_be64(s->autoclear_features),
b6481f37 2540 .refcount_order = cpu_to_be32(s->refcount_order),
6744cbab 2541 .header_length = cpu_to_be32(header_length),
e24e49e6 2542 };
756e6736 2543
6744cbab
KW
2544 /* For older versions, write a shorter header */
2545 switch (s->qcow_version) {
2546 case 2:
2547 ret = offsetof(QCowHeader, incompatible_features);
2548 break;
2549 case 3:
2550 ret = sizeof(*header);
2551 break;
2552 default:
b6c14762
JM
2553 ret = -EINVAL;
2554 goto fail;
6744cbab
KW
2555 }
2556
2557 buf += ret;
2558 buflen -= ret;
2559 memset(buf, 0, buflen);
2560
2561 /* Preserve any unknown field in the header */
2562 if (s->unknown_header_fields_size) {
2563 if (buflen < s->unknown_header_fields_size) {
2564 ret = -ENOSPC;
2565 goto fail;
2566 }
2567
2568 memcpy(buf, s->unknown_header_fields, s->unknown_header_fields_size);
2569 buf += s->unknown_header_fields_size;
2570 buflen -= s->unknown_header_fields_size;
2571 }
756e6736 2572
e24e49e6 2573 /* Backing file format header extension */
e4603fe1 2574 if (s->image_backing_format) {
e24e49e6 2575 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BACKING_FORMAT,
e4603fe1
KW
2576 s->image_backing_format,
2577 strlen(s->image_backing_format),
e24e49e6
KW
2578 buflen);
2579 if (ret < 0) {
2580 goto fail;
756e6736
KW
2581 }
2582
e24e49e6
KW
2583 buf += ret;
2584 buflen -= ret;
756e6736
KW
2585 }
2586
9b890bdc
KW
2587 /* External data file header extension */
2588 if (has_data_file(bs) && s->image_data_file) {
2589 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_DATA_FILE,
2590 s->image_data_file, strlen(s->image_data_file),
2591 buflen);
2592 if (ret < 0) {
2593 goto fail;
2594 }
2595
2596 buf += ret;
2597 buflen -= ret;
2598 }
2599
4652b8f3
DB
2600 /* Full disk encryption header pointer extension */
2601 if (s->crypto_header.offset != 0) {
3b698f52
PM
2602 s->crypto_header.offset = cpu_to_be64(s->crypto_header.offset);
2603 s->crypto_header.length = cpu_to_be64(s->crypto_header.length);
4652b8f3
DB
2604 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_CRYPTO_HEADER,
2605 &s->crypto_header, sizeof(s->crypto_header),
2606 buflen);
3b698f52
PM
2607 s->crypto_header.offset = be64_to_cpu(s->crypto_header.offset);
2608 s->crypto_header.length = be64_to_cpu(s->crypto_header.length);
4652b8f3
DB
2609 if (ret < 0) {
2610 goto fail;
2611 }
2612 buf += ret;
2613 buflen -= ret;
2614 }
2615
cfcc4c62 2616 /* Feature table */
1a4828c7
KW
2617 if (s->qcow_version >= 3) {
2618 Qcow2Feature features[] = {
2619 {
2620 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
2621 .bit = QCOW2_INCOMPAT_DIRTY_BITNR,
2622 .name = "dirty bit",
2623 },
2624 {
2625 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
2626 .bit = QCOW2_INCOMPAT_CORRUPT_BITNR,
2627 .name = "corrupt bit",
2628 },
93c24936
KW
2629 {
2630 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
2631 .bit = QCOW2_INCOMPAT_DATA_FILE_BITNR,
2632 .name = "external data file",
2633 },
1a4828c7
KW
2634 {
2635 .type = QCOW2_FEAT_TYPE_COMPATIBLE,
2636 .bit = QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR,
2637 .name = "lazy refcounts",
2638 },
2639 };
2640
2641 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_FEATURE_TABLE,
2642 features, sizeof(features), buflen);
2643 if (ret < 0) {
2644 goto fail;
2645 }
2646 buf += ret;
2647 buflen -= ret;
cfcc4c62 2648 }
cfcc4c62 2649
88ddffae
VSO
2650 /* Bitmap extension */
2651 if (s->nb_bitmaps > 0) {
2652 Qcow2BitmapHeaderExt bitmaps_header = {
2653 .nb_bitmaps = cpu_to_be32(s->nb_bitmaps),
2654 .bitmap_directory_size =
2655 cpu_to_be64(s->bitmap_directory_size),
2656 .bitmap_directory_offset =
2657 cpu_to_be64(s->bitmap_directory_offset)
2658 };
2659 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BITMAPS,
2660 &bitmaps_header, sizeof(bitmaps_header),
2661 buflen);
2662 if (ret < 0) {
2663 goto fail;
2664 }
2665 buf += ret;
2666 buflen -= ret;
2667 }
2668
75bab85c
KW
2669 /* Keep unknown header extensions */
2670 QLIST_FOREACH(uext, &s->unknown_header_ext, next) {
2671 ret = header_ext_add(buf, uext->magic, uext->data, uext->len, buflen);
2672 if (ret < 0) {
2673 goto fail;
2674 }
2675
2676 buf += ret;
2677 buflen -= ret;
2678 }
2679
e24e49e6
KW
2680 /* End of header extensions */
2681 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_END, NULL, 0, buflen);
756e6736
KW
2682 if (ret < 0) {
2683 goto fail;
2684 }
2685
e24e49e6
KW
2686 buf += ret;
2687 buflen -= ret;
756e6736 2688
e24e49e6 2689 /* Backing file name */
e4603fe1
KW
2690 if (s->image_backing_file) {
2691 size_t backing_file_len = strlen(s->image_backing_file);
e24e49e6
KW
2692
2693 if (buflen < backing_file_len) {
2694 ret = -ENOSPC;
2695 goto fail;
2696 }
2697
00ea1881 2698 /* Using strncpy is ok here, since buf is not NUL-terminated. */
e4603fe1 2699 strncpy(buf, s->image_backing_file, buflen);
e24e49e6
KW
2700
2701 header->backing_file_offset = cpu_to_be64(buf - ((char*) header));
2702 header->backing_file_size = cpu_to_be32(backing_file_len);
756e6736
KW
2703 }
2704
e24e49e6 2705 /* Write the new header */
d9ca2ea2 2706 ret = bdrv_pwrite(bs->file, 0, header, s->cluster_size);
756e6736
KW
2707 if (ret < 0) {
2708 goto fail;
2709 }
2710
2711 ret = 0;
2712fail:
e24e49e6 2713 qemu_vfree(header);
756e6736
KW
2714 return ret;
2715}
2716
2717static int qcow2_change_backing_file(BlockDriverState *bs,
2718 const char *backing_file, const char *backing_fmt)
2719{
ff99129a 2720 BDRVQcow2State *s = bs->opaque;
e4603fe1 2721
6c3944dc
KW
2722 /* Adding a backing file means that the external data file alone won't be
2723 * enough to make sense of the content */
2724 if (backing_file && data_file_is_raw(bs)) {
2725 return -EINVAL;
2726 }
2727
4e876bcf
HR
2728 if (backing_file && strlen(backing_file) > 1023) {
2729 return -EINVAL;
2730 }
2731
998c2019
HR
2732 pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
2733 backing_file ?: "");
e24e49e6
KW
2734 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
2735 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
2736
e4603fe1
KW
2737 g_free(s->image_backing_file);
2738 g_free(s->image_backing_format);
2739
2740 s->image_backing_file = backing_file ? g_strdup(bs->backing_file) : NULL;
2741 s->image_backing_format = backing_fmt ? g_strdup(bs->backing_format) : NULL;
2742
e24e49e6 2743 return qcow2_update_header(bs);
756e6736
KW
2744}
2745
4652b8f3
DB
2746static int qcow2_crypt_method_from_format(const char *encryptfmt)
2747{
2748 if (g_str_equal(encryptfmt, "luks")) {
2749 return QCOW_CRYPT_LUKS;
2750 } else if (g_str_equal(encryptfmt, "aes")) {
2751 return QCOW_CRYPT_AES;
2752 } else {
2753 return -EINVAL;
2754 }
2755}
b25b387f 2756
60900b7b
KW
2757static int qcow2_set_up_encryption(BlockDriverState *bs,
2758 QCryptoBlockCreateOptions *cryptoopts,
2759 Error **errp)
2760{
2761 BDRVQcow2State *s = bs->opaque;
2762 QCryptoBlock *crypto = NULL;
2763 int fmt, ret;
2764
2765 switch (cryptoopts->format) {
2766 case Q_CRYPTO_BLOCK_FORMAT_LUKS:
2767 fmt = QCOW_CRYPT_LUKS;
2768 break;
2769 case Q_CRYPTO_BLOCK_FORMAT_QCOW:
2770 fmt = QCOW_CRYPT_AES;
2771 break;
2772 default:
2773 error_setg(errp, "Crypto format not supported in qcow2");
2774 return -EINVAL;
b25b387f 2775 }
60900b7b 2776
4652b8f3 2777 s->crypt_method_header = fmt;
b25b387f 2778
1cd9a787 2779 crypto = qcrypto_block_create(cryptoopts, "encrypt.",
4652b8f3
DB
2780 qcow2_crypto_hdr_init_func,
2781 qcow2_crypto_hdr_write_func,
b25b387f
DB
2782 bs, errp);
2783 if (!crypto) {
60900b7b 2784 return -EINVAL;
b25b387f
DB
2785 }
2786
2787 ret = qcow2_update_header(bs);
2788 if (ret < 0) {
2789 error_setg_errno(errp, -ret, "Could not write encryption header");
2790 goto out;
2791 }
2792
60900b7b 2793 ret = 0;
b25b387f 2794 out:
b25b387f 2795 qcrypto_block_free(crypto);
b25b387f
DB
2796 return ret;
2797}
2798
7bc45dc1
HR
2799/**
2800 * Preallocates metadata structures for data clusters between @offset (in the
2801 * guest disk) and @new_length (which is thus generally the new guest disk
2802 * size).
2803 *
2804 * Returns: 0 on success, -errno on failure.
2805 */
47e86b86 2806static int coroutine_fn preallocate_co(BlockDriverState *bs, uint64_t offset,
718c0fce
KW
2807 uint64_t new_length, PreallocMode mode,
2808 Error **errp)
a35e1c17 2809{
93e32b3e 2810 BDRVQcow2State *s = bs->opaque;
d46a0bb2 2811 uint64_t bytes;
060bee89 2812 uint64_t host_offset = 0;
718c0fce 2813 int64_t file_length;
d46a0bb2 2814 unsigned int cur_bytes;
148da7ea 2815 int ret;
f50f88b9 2816 QCowL2Meta *meta;
a35e1c17 2817
7bc45dc1
HR
2818 assert(offset <= new_length);
2819 bytes = new_length - offset;
a35e1c17 2820
d46a0bb2 2821 while (bytes) {
f29fbf7c 2822 cur_bytes = MIN(bytes, QEMU_ALIGN_DOWN(INT_MAX, s->cluster_size));
d46a0bb2 2823 ret = qcow2_alloc_cluster_offset(bs, offset, &cur_bytes,
060bee89 2824 &host_offset, &meta);
148da7ea 2825 if (ret < 0) {
360bd074 2826 error_setg_errno(errp, -ret, "Allocating clusters failed");
47e86b86 2827 return ret;
a35e1c17
KW
2828 }
2829
c792707f
SH
2830 while (meta) {
2831 QCowL2Meta *next = meta->next;
2832
7c2bbf4a
HT
2833 ret = qcow2_alloc_cluster_link_l2(bs, meta);
2834 if (ret < 0) {
360bd074 2835 error_setg_errno(errp, -ret, "Mapping clusters failed");
7c2bbf4a
HT
2836 qcow2_free_any_clusters(bs, meta->alloc_offset,
2837 meta->nb_clusters, QCOW2_DISCARD_NEVER);
47e86b86 2838 return ret;
7c2bbf4a
HT
2839 }
2840
2841 /* There are no dependent requests, but we need to remove our
2842 * request from the list of in-flight requests */
4e95314e 2843 QLIST_REMOVE(meta, next_in_flight);
c792707f
SH
2844
2845 g_free(meta);
2846 meta = next;
f50f88b9 2847 }
f214978a 2848
a35e1c17
KW
2849 /* TODO Preallocate data if requested */
2850
d46a0bb2
KW
2851 bytes -= cur_bytes;
2852 offset += cur_bytes;
a35e1c17
KW
2853 }
2854
2855 /*
2856 * It is expected that the image file is large enough to actually contain
2857 * all of the allocated clusters (otherwise we get failing reads after
2858 * EOF). Extend the image to the last allocated sector.
2859 */
718c0fce
KW
2860 file_length = bdrv_getlength(s->data_file->bs);
2861 if (file_length < 0) {
2862 error_setg_errno(errp, -file_length, "Could not get file size");
2863 return file_length;
2864 }
2865
2866 if (host_offset + cur_bytes > file_length) {
2867 if (mode == PREALLOC_MODE_METADATA) {
2868 mode = PREALLOC_MODE_OFF;
2869 }
2870 ret = bdrv_co_truncate(s->data_file, host_offset + cur_bytes, mode,
2871 errp);
19dbcbf7 2872 if (ret < 0) {
47e86b86 2873 return ret;
19dbcbf7 2874 }
a35e1c17
KW
2875 }
2876
47e86b86 2877 return 0;
a35e1c17
KW
2878}
2879
7c5bcc42
SH
2880/* qcow2_refcount_metadata_size:
2881 * @clusters: number of clusters to refcount (including data and L1/L2 tables)
2882 * @cluster_size: size of a cluster, in bytes
2883 * @refcount_order: refcount bits power-of-2 exponent
12cc30a8
HR
2884 * @generous_increase: allow for the refcount table to be 1.5x as large as it
2885 * needs to be
7c5bcc42
SH
2886 *
2887 * Returns: Number of bytes required for refcount blocks and table metadata.
2888 */
12cc30a8
HR
2889int64_t qcow2_refcount_metadata_size(int64_t clusters, size_t cluster_size,
2890 int refcount_order, bool generous_increase,
2891 uint64_t *refblock_count)
7c5bcc42
SH
2892{
2893 /*
2894 * Every host cluster is reference-counted, including metadata (even
2895 * refcount metadata is recursively included).
2896 *
2897 * An accurate formula for the size of refcount metadata size is difficult
2898 * to derive. An easier method of calculation is finding the fixed point
2899 * where no further refcount blocks or table clusters are required to
2900 * reference count every cluster.
2901 */
2902 int64_t blocks_per_table_cluster = cluster_size / sizeof(uint64_t);
2903 int64_t refcounts_per_block = cluster_size * 8 / (1 << refcount_order);
2904 int64_t table = 0; /* number of refcount table clusters */
2905 int64_t blocks = 0; /* number of refcount block clusters */
2906 int64_t last;
2907 int64_t n = 0;
2908
2909 do {
2910 last = n;
2911 blocks = DIV_ROUND_UP(clusters + table + blocks, refcounts_per_block);
2912 table = DIV_ROUND_UP(blocks, blocks_per_table_cluster);
2913 n = clusters + blocks + table;
12cc30a8
HR
2914
2915 if (n == last && generous_increase) {
2916 clusters += DIV_ROUND_UP(table, 2);
2917 n = 0; /* force another loop */
2918 generous_increase = false;
2919 }
7c5bcc42
SH
2920 } while (n != last);
2921
12cc30a8
HR
2922 if (refblock_count) {
2923 *refblock_count = blocks;
2924 }
2925
7c5bcc42
SH
2926 return (blocks + table) * cluster_size;
2927}
2928
95c67e3b
SH
2929/**
2930 * qcow2_calc_prealloc_size:
2931 * @total_size: virtual disk size in bytes
2932 * @cluster_size: cluster size in bytes
2933 * @refcount_order: refcount bits power-of-2 exponent
2934 *
2935 * Returns: Total number of bytes required for the fully allocated image
2936 * (including metadata).
2937 */
2938static int64_t qcow2_calc_prealloc_size(int64_t total_size,
2939 size_t cluster_size,
2940 int refcount_order)
2941{
95c67e3b 2942 int64_t meta_size = 0;
7c5bcc42 2943 uint64_t nl1e, nl2e;
9e029689 2944 int64_t aligned_total_size = ROUND_UP(total_size, cluster_size);
95c67e3b
SH
2945
2946 /* header: 1 cluster */
2947 meta_size += cluster_size;
2948
2949 /* total size of L2 tables */
2950 nl2e = aligned_total_size / cluster_size;
9e029689 2951 nl2e = ROUND_UP(nl2e, cluster_size / sizeof(uint64_t));
95c67e3b
SH
2952 meta_size += nl2e * sizeof(uint64_t);
2953
2954 /* total size of L1 tables */
2955 nl1e = nl2e * sizeof(uint64_t) / cluster_size;
9e029689 2956 nl1e = ROUND_UP(nl1e, cluster_size / sizeof(uint64_t));
95c67e3b
SH
2957 meta_size += nl1e * sizeof(uint64_t);
2958
7c5bcc42
SH
2959 /* total size of refcount table and blocks */
2960 meta_size += qcow2_refcount_metadata_size(
2961 (meta_size + aligned_total_size) / cluster_size,
12cc30a8 2962 cluster_size, refcount_order, false, NULL);
95c67e3b
SH
2963
2964 return meta_size + aligned_total_size;
2965}
2966
29ca9e45 2967static bool validate_cluster_size(size_t cluster_size, Error **errp)
a9420734 2968{
29ca9e45 2969 int cluster_bits = ctz32(cluster_size);
a9420734
KW
2970 if (cluster_bits < MIN_CLUSTER_BITS || cluster_bits > MAX_CLUSTER_BITS ||
2971 (1 << cluster_bits) != cluster_size)
2972 {
3ef6c40a
HR
2973 error_setg(errp, "Cluster size must be a power of two between %d and "
2974 "%dk", 1 << MIN_CLUSTER_BITS, 1 << (MAX_CLUSTER_BITS - 10));
29ca9e45
KW
2975 return false;
2976 }
2977 return true;
2978}
2979
2980static size_t qcow2_opt_get_cluster_size_del(QemuOpts *opts, Error **errp)
2981{
2982 size_t cluster_size;
2983
2984 cluster_size = qemu_opt_get_size_del(opts, BLOCK_OPT_CLUSTER_SIZE,
2985 DEFAULT_CLUSTER_SIZE);
2986 if (!validate_cluster_size(cluster_size, errp)) {
0eb4a8c1
SH
2987 return 0;
2988 }
2989 return cluster_size;
2990}
2991
2992static int qcow2_opt_get_version_del(QemuOpts *opts, Error **errp)
2993{
2994 char *buf;
2995 int ret;
2996
2997 buf = qemu_opt_get_del(opts, BLOCK_OPT_COMPAT_LEVEL);
2998 if (!buf) {
2999 ret = 3; /* default */
3000 } else if (!strcmp(buf, "0.10")) {
3001 ret = 2;
3002 } else if (!strcmp(buf, "1.1")) {
3003 ret = 3;
3004 } else {
3005 error_setg(errp, "Invalid compatibility level: '%s'", buf);
3006 ret = -EINVAL;
3007 }
3008 g_free(buf);
3009 return ret;
3010}
3011
3012static uint64_t qcow2_opt_get_refcount_bits_del(QemuOpts *opts, int version,
3013 Error **errp)
3014{
3015 uint64_t refcount_bits;
3016
3017 refcount_bits = qemu_opt_get_number_del(opts, BLOCK_OPT_REFCOUNT_BITS, 16);
3018 if (refcount_bits > 64 || !is_power_of_2(refcount_bits)) {
3019 error_setg(errp, "Refcount width must be a power of two and may not "
3020 "exceed 64 bits");
3021 return 0;
3022 }
3023
3024 if (version < 3 && refcount_bits != 16) {
3025 error_setg(errp, "Different refcount widths than 16 bits require "
3026 "compatibility level 1.1 or above (use compat=1.1 or "
3027 "greater)");
3028 return 0;
a9420734
KW
3029 }
3030
0eb4a8c1
SH
3031 return refcount_bits;
3032}
3033
c274393a 3034static int coroutine_fn
60900b7b 3035qcow2_co_create(BlockdevCreateOptions *create_options, Error **errp)
0eb4a8c1 3036{
29ca9e45 3037 BlockdevCreateOptionsQcow2 *qcow2_opts;
0eb4a8c1
SH
3038 QDict *options;
3039
a9420734
KW
3040 /*
3041 * Open the image file and write a minimal qcow2 header.
3042 *
3043 * We keep things simple and start with a zero-sized image. We also
3044 * do without refcount blocks or a L1 table for now. We'll fix the
3045 * inconsistency later.
3046 *
3047 * We do need a refcount table because growing the refcount table means
3048 * allocating two new refcount blocks - the seconds of which would be at
3049 * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
3050 * size for any qcow2 image.
3051 */
e1d74bc6
KW
3052 BlockBackend *blk = NULL;
3053 BlockDriverState *bs = NULL;
dcc98687 3054 BlockDriverState *data_bs = NULL;
f8413b3c 3055 QCowHeader *header;
29ca9e45
KW
3056 size_t cluster_size;
3057 int version;
3058 int refcount_order;
b106ad91 3059 uint64_t* refcount_table;
3ef6c40a 3060 Error *local_err = NULL;
a9420734
KW
3061 int ret;
3062
29ca9e45
KW
3063 assert(create_options->driver == BLOCKDEV_DRIVER_QCOW2);
3064 qcow2_opts = &create_options->u.qcow2;
3065
e1d74bc6
KW
3066 bs = bdrv_open_blockdev_ref(qcow2_opts->file, errp);
3067 if (bs == NULL) {
3068 return -EIO;
3069 }
3070
3071 /* Validate options and set default values */
29ca9e45
KW
3072 if (!QEMU_IS_ALIGNED(qcow2_opts->size, BDRV_SECTOR_SIZE)) {
3073 error_setg(errp, "Image size must be a multiple of 512 bytes");
3074 ret = -EINVAL;
3075 goto out;
3076 }
3077
3078 if (qcow2_opts->has_version) {
3079 switch (qcow2_opts->version) {
3080 case BLOCKDEV_QCOW2_VERSION_V2:
3081 version = 2;
3082 break;
3083 case BLOCKDEV_QCOW2_VERSION_V3:
3084 version = 3;
3085 break;
3086 default:
3087 g_assert_not_reached();
3088 }
3089 } else {
3090 version = 3;
3091 }
3092
3093 if (qcow2_opts->has_cluster_size) {
3094 cluster_size = qcow2_opts->cluster_size;
3095 } else {
3096 cluster_size = DEFAULT_CLUSTER_SIZE;
3097 }
3098
3099 if (!validate_cluster_size(cluster_size, errp)) {
e1d74bc6
KW
3100 ret = -EINVAL;
3101 goto out;
29ca9e45
KW
3102 }
3103
3104 if (!qcow2_opts->has_preallocation) {
3105 qcow2_opts->preallocation = PREALLOC_MODE_OFF;
3106 }
3107 if (qcow2_opts->has_backing_file &&
3108 qcow2_opts->preallocation != PREALLOC_MODE_OFF)
3109 {
3110 error_setg(errp, "Backing file and preallocation cannot be used at "
3111 "the same time");
e1d74bc6
KW
3112 ret = -EINVAL;
3113 goto out;
29ca9e45
KW
3114 }
3115 if (qcow2_opts->has_backing_fmt && !qcow2_opts->has_backing_file) {
3116 error_setg(errp, "Backing format cannot be used without backing file");
e1d74bc6
KW
3117 ret = -EINVAL;
3118 goto out;
29ca9e45
KW
3119 }
3120
3121 if (!qcow2_opts->has_lazy_refcounts) {
3122 qcow2_opts->lazy_refcounts = false;
3123 }
3124 if (version < 3 && qcow2_opts->lazy_refcounts) {
3125 error_setg(errp, "Lazy refcounts only supported with compatibility "
b76b4f60 3126 "level 1.1 and above (use version=v3 or greater)");
e1d74bc6
KW
3127 ret = -EINVAL;
3128 goto out;
29ca9e45
KW
3129 }
3130
3131 if (!qcow2_opts->has_refcount_bits) {
3132 qcow2_opts->refcount_bits = 16;
3133 }
3134 if (qcow2_opts->refcount_bits > 64 ||
3135 !is_power_of_2(qcow2_opts->refcount_bits))
3136 {
3137 error_setg(errp, "Refcount width must be a power of two and may not "
3138 "exceed 64 bits");
e1d74bc6
KW
3139 ret = -EINVAL;
3140 goto out;
29ca9e45
KW
3141 }
3142 if (version < 3 && qcow2_opts->refcount_bits != 16) {
3143 error_setg(errp, "Different refcount widths than 16 bits require "
b76b4f60 3144 "compatibility level 1.1 or above (use version=v3 or "
29ca9e45 3145 "greater)");
e1d74bc6
KW
3146 ret = -EINVAL;
3147 goto out;
29ca9e45
KW
3148 }
3149 refcount_order = ctz32(qcow2_opts->refcount_bits);
3150
6c3944dc
KW
3151 if (qcow2_opts->data_file_raw && !qcow2_opts->data_file) {
3152 error_setg(errp, "data-file-raw requires data-file");
3153 ret = -EINVAL;
3154 goto out;
3155 }
3156 if (qcow2_opts->data_file_raw && qcow2_opts->has_backing_file) {
3157 error_setg(errp, "Backing file and data-file-raw cannot be used at "
3158 "the same time");
3159 ret = -EINVAL;
3160 goto out;
3161 }
3162
dcc98687
KW
3163 if (qcow2_opts->data_file) {
3164 if (version < 3) {
3165 error_setg(errp, "External data files are only supported with "
3166 "compatibility level 1.1 and above (use version=v3 or "
3167 "greater)");
3168 ret = -EINVAL;
3169 goto out;
3170 }
3171 data_bs = bdrv_open_blockdev_ref(qcow2_opts->data_file, errp);
a0cf8363 3172 if (data_bs == NULL) {
dcc98687
KW
3173 ret = -EIO;
3174 goto out;
3175 }
3176 }
29ca9e45
KW
3177
3178 /* Create BlockBackend to write to the image */
d861ab3a
KW
3179 blk = blk_new(bdrv_get_aio_context(bs),
3180 BLK_PERM_WRITE | BLK_PERM_RESIZE, BLK_PERM_ALL);
cbf2b7c4 3181 ret = blk_insert_bs(blk, bs, errp);
a9420734 3182 if (ret < 0) {
cbf2b7c4 3183 goto out;
a9420734 3184 }
23588797
KW
3185 blk_set_allow_write_beyond_eof(blk, true);
3186
e4b5dad8
KW
3187 /* Clear the protocol layer and preallocate it if necessary */
3188 ret = blk_truncate(blk, 0, PREALLOC_MODE_OFF, errp);
3189 if (ret < 0) {
3190 goto out;
3191 }
3192
a9420734 3193 /* Write the header */
f8413b3c
KW
3194 QEMU_BUILD_BUG_ON((1 << MIN_CLUSTER_BITS) < sizeof(*header));
3195 header = g_malloc0(cluster_size);
3196 *header = (QCowHeader) {
3197 .magic = cpu_to_be32(QCOW_MAGIC),
3198 .version = cpu_to_be32(version),
0eb4a8c1 3199 .cluster_bits = cpu_to_be32(ctz32(cluster_size)),
f8413b3c
KW
3200 .size = cpu_to_be64(0),
3201 .l1_table_offset = cpu_to_be64(0),
3202 .l1_size = cpu_to_be32(0),
3203 .refcount_table_offset = cpu_to_be64(cluster_size),
3204 .refcount_table_clusters = cpu_to_be32(1),
bd4b167f 3205 .refcount_order = cpu_to_be32(refcount_order),
f8413b3c
KW
3206 .header_length = cpu_to_be32(sizeof(*header)),
3207 };
a9420734 3208
b25b387f
DB
3209 /* We'll update this to correct value later */
3210 header->crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
a9420734 3211
29ca9e45 3212 if (qcow2_opts->lazy_refcounts) {
f8413b3c 3213 header->compatible_features |=
bfe8043e
SH
3214 cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS);
3215 }
dcc98687
KW
3216 if (data_bs) {
3217 header->incompatible_features |=
3218 cpu_to_be64(QCOW2_INCOMPAT_DATA_FILE);
3219 }
6c3944dc
KW
3220 if (qcow2_opts->data_file_raw) {
3221 header->autoclear_features |=
3222 cpu_to_be64(QCOW2_AUTOCLEAR_DATA_FILE_RAW);
3223 }
bfe8043e 3224
8341f00d 3225 ret = blk_pwrite(blk, 0, header, cluster_size, 0);
f8413b3c 3226 g_free(header);
a9420734 3227 if (ret < 0) {
3ef6c40a 3228 error_setg_errno(errp, -ret, "Could not write qcow2 header");
a9420734
KW
3229 goto out;
3230 }
3231
b106ad91
KW
3232 /* Write a refcount table with one refcount block */
3233 refcount_table = g_malloc0(2 * cluster_size);
3234 refcount_table[0] = cpu_to_be64(2 * cluster_size);
8341f00d 3235 ret = blk_pwrite(blk, cluster_size, refcount_table, 2 * cluster_size, 0);
7267c094 3236 g_free(refcount_table);
a9420734
KW
3237
3238 if (ret < 0) {
3ef6c40a 3239 error_setg_errno(errp, -ret, "Could not write refcount table");
a9420734
KW
3240 goto out;
3241 }
3242
23588797
KW
3243 blk_unref(blk);
3244 blk = NULL;
a9420734
KW
3245
3246 /*
3247 * And now open the image and make it consistent first (i.e. increase the
3248 * refcount of the cluster that is occupied by the header and the refcount
3249 * table)
3250 */
e6641719 3251 options = qdict_new();
46f5ac20 3252 qdict_put_str(options, "driver", "qcow2");
cbf2b7c4 3253 qdict_put_str(options, "file", bs->node_name);
dcc98687
KW
3254 if (data_bs) {
3255 qdict_put_str(options, "data-file", data_bs->node_name);
3256 }
cbf2b7c4 3257 blk = blk_new_open(NULL, NULL, options,
55880601
KW
3258 BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_NO_FLUSH,
3259 &local_err);
23588797 3260 if (blk == NULL) {
3ef6c40a 3261 error_propagate(errp, local_err);
23588797 3262 ret = -EIO;
a9420734
KW
3263 goto out;
3264 }
3265
23588797 3266 ret = qcow2_alloc_clusters(blk_bs(blk), 3 * cluster_size);
a9420734 3267 if (ret < 0) {
3ef6c40a
HR
3268 error_setg_errno(errp, -ret, "Could not allocate clusters for qcow2 "
3269 "header and refcount table");
a9420734
KW
3270 goto out;
3271
3272 } else if (ret != 0) {
3273 error_report("Huh, first cluster in empty image is already in use?");
3274 abort();
3275 }
3276
9b890bdc
KW
3277 /* Set the external data file if necessary */
3278 if (data_bs) {
3279 BDRVQcow2State *s = blk_bs(blk)->opaque;
3280 s->image_data_file = g_strdup(data_bs->filename);
3281 }
3282
b527c9b3 3283 /* Create a full header (including things like feature table) */
23588797 3284 ret = qcow2_update_header(blk_bs(blk));
b527c9b3
KW
3285 if (ret < 0) {
3286 error_setg_errno(errp, -ret, "Could not update qcow2 header");
3287 goto out;
3288 }
3289
a9420734 3290 /* Okay, now that we have a valid image, let's give it the right size */
c5e86ebc 3291 ret = blk_truncate(blk, qcow2_opts->size, qcow2_opts->preallocation, errp);
a9420734 3292 if (ret < 0) {
ed3d2ec9 3293 error_prepend(errp, "Could not resize image: ");
a9420734
KW
3294 goto out;
3295 }
3296
3297 /* Want a backing file? There you go.*/
29ca9e45
KW
3298 if (qcow2_opts->has_backing_file) {
3299 const char *backing_format = NULL;
3300
3301 if (qcow2_opts->has_backing_fmt) {
3302 backing_format = BlockdevDriver_str(qcow2_opts->backing_fmt);
3303 }
3304
3305 ret = bdrv_change_backing_file(blk_bs(blk), qcow2_opts->backing_file,
3306 backing_format);
a9420734 3307 if (ret < 0) {
3ef6c40a 3308 error_setg_errno(errp, -ret, "Could not assign backing file '%s' "
29ca9e45
KW
3309 "with format '%s'", qcow2_opts->backing_file,
3310 backing_format);
a9420734
KW
3311 goto out;
3312 }
3313 }
3314
b25b387f 3315 /* Want encryption? There you go. */
60900b7b
KW
3316 if (qcow2_opts->has_encrypt) {
3317 ret = qcow2_set_up_encryption(blk_bs(blk), qcow2_opts->encrypt, errp);
b25b387f
DB
3318 if (ret < 0) {
3319 goto out;
3320 }
3321 }
3322
23588797
KW
3323 blk_unref(blk);
3324 blk = NULL;
ba2ab2f2 3325
b25b387f
DB
3326 /* Reopen the image without BDRV_O_NO_FLUSH to flush it before returning.
3327 * Using BDRV_O_NO_IO, since encryption is now setup we don't want to
3328 * have to setup decryption context. We're not doing any I/O on the top
3329 * level BlockDriverState, only lower layers, where BDRV_O_NO_IO does
3330 * not have effect.
3331 */
e6641719 3332 options = qdict_new();
46f5ac20 3333 qdict_put_str(options, "driver", "qcow2");
cbf2b7c4 3334 qdict_put_str(options, "file", bs->node_name);
dcc98687
KW
3335 if (data_bs) {
3336 qdict_put_str(options, "data-file", data_bs->node_name);
3337 }
cbf2b7c4 3338 blk = blk_new_open(NULL, NULL, options,
b25b387f
DB
3339 BDRV_O_RDWR | BDRV_O_NO_BACKING | BDRV_O_NO_IO,
3340 &local_err);
23588797 3341 if (blk == NULL) {
ba2ab2f2 3342 error_propagate(errp, local_err);
23588797 3343 ret = -EIO;
ba2ab2f2
HR
3344 goto out;
3345 }
3346
a9420734
KW
3347 ret = 0;
3348out:
e1d74bc6
KW
3349 blk_unref(blk);
3350 bdrv_unref(bs);
dcc98687 3351 bdrv_unref(data_bs);
a9420734
KW
3352 return ret;
3353}
de5f3f40 3354
efc75e2a
SH
3355static int coroutine_fn qcow2_co_create_opts(const char *filename, QemuOpts *opts,
3356 Error **errp)
de5f3f40 3357{
b76b4f60 3358 BlockdevCreateOptions *create_options = NULL;
92adf9db 3359 QDict *qdict;
b76b4f60 3360 Visitor *v;
cbf2b7c4 3361 BlockDriverState *bs = NULL;
9b890bdc 3362 BlockDriverState *data_bs = NULL;
3ef6c40a 3363 Error *local_err = NULL;
b76b4f60 3364 const char *val;
3ef6c40a 3365 int ret;
de5f3f40 3366
b76b4f60
KW
3367 /* Only the keyval visitor supports the dotted syntax needed for
3368 * encryption, so go through a QDict before getting a QAPI type. Ignore
3369 * options meant for the protocol layer so that the visitor doesn't
3370 * complain. */
3371 qdict = qemu_opts_to_qdict_filtered(opts, NULL, bdrv_qcow2.create_opts,
3372 true);
3373
3374 /* Handle encryption options */
3375 val = qdict_get_try_str(qdict, BLOCK_OPT_ENCRYPT);
3376 if (val && !strcmp(val, "on")) {
3377 qdict_put_str(qdict, BLOCK_OPT_ENCRYPT, "qcow");
3378 } else if (val && !strcmp(val, "off")) {
3379 qdict_del(qdict, BLOCK_OPT_ENCRYPT);
3380 }
3381
3382 val = qdict_get_try_str(qdict, BLOCK_OPT_ENCRYPT_FORMAT);
3383 if (val && !strcmp(val, "aes")) {
3384 qdict_put_str(qdict, BLOCK_OPT_ENCRYPT_FORMAT, "qcow");
3385 }
3386
3387 /* Convert compat=0.10/1.1 into compat=v2/v3, to be renamed into
3388 * version=v2/v3 below. */
3389 val = qdict_get_try_str(qdict, BLOCK_OPT_COMPAT_LEVEL);
3390 if (val && !strcmp(val, "0.10")) {
3391 qdict_put_str(qdict, BLOCK_OPT_COMPAT_LEVEL, "v2");
3392 } else if (val && !strcmp(val, "1.1")) {
3393 qdict_put_str(qdict, BLOCK_OPT_COMPAT_LEVEL, "v3");
3394 }
3395
3396 /* Change legacy command line options into QMP ones */
3397 static const QDictRenames opt_renames[] = {
3398 { BLOCK_OPT_BACKING_FILE, "backing-file" },
3399 { BLOCK_OPT_BACKING_FMT, "backing-fmt" },
3400 { BLOCK_OPT_CLUSTER_SIZE, "cluster-size" },
3401 { BLOCK_OPT_LAZY_REFCOUNTS, "lazy-refcounts" },
3402 { BLOCK_OPT_REFCOUNT_BITS, "refcount-bits" },
3403 { BLOCK_OPT_ENCRYPT, BLOCK_OPT_ENCRYPT_FORMAT },
3404 { BLOCK_OPT_COMPAT_LEVEL, "version" },
6c3944dc 3405 { BLOCK_OPT_DATA_FILE_RAW, "data-file-raw" },
b76b4f60
KW
3406 { NULL, NULL },
3407 };
3408
3409 if (!qdict_rename_keys(qdict, opt_renames, errp)) {
29ca9e45
KW
3410 ret = -EINVAL;
3411 goto finish;
3412 }
60900b7b 3413
b76b4f60
KW
3414 /* Create and open the file (protocol layer) */
3415 ret = bdrv_create_file(filename, opts, errp);
3416 if (ret < 0) {
0eb4a8c1
SH
3417 goto finish;
3418 }
b76b4f60
KW
3419
3420 bs = bdrv_open(filename, NULL, NULL,
3421 BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_PROTOCOL, errp);
3422 if (bs == NULL) {
3423 ret = -EIO;
1bd0e2d1
CL
3424 goto finish;
3425 }
0eb4a8c1 3426
9b890bdc
KW
3427 /* Create and open an external data file (protocol layer) */
3428 val = qdict_get_try_str(qdict, BLOCK_OPT_DATA_FILE);
3429 if (val) {
3430 ret = bdrv_create_file(val, opts, errp);
3431 if (ret < 0) {
3432 goto finish;
3433 }
3434
3435 data_bs = bdrv_open(val, NULL, NULL,
3436 BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_PROTOCOL,
3437 errp);
3438 if (data_bs == NULL) {
3439 ret = -EIO;
3440 goto finish;
3441 }
3442
3443 qdict_del(qdict, BLOCK_OPT_DATA_FILE);
3444 qdict_put_str(qdict, "data-file", data_bs->node_name);
3445 }
3446
b76b4f60
KW
3447 /* Set 'driver' and 'node' options */
3448 qdict_put_str(qdict, "driver", "qcow2");
3449 qdict_put_str(qdict, "file", bs->node_name);
3450
3451 /* Now get the QAPI type BlockdevCreateOptions */
af91062e
MA
3452 v = qobject_input_visitor_new_flat_confused(qdict, errp);
3453 if (!v) {
1bd0e2d1
CL
3454 ret = -EINVAL;
3455 goto finish;
3456 }
3457
b76b4f60
KW
3458 visit_type_BlockdevCreateOptions(v, NULL, &create_options, &local_err);
3459 visit_free(v);
de5f3f40 3460
0eb4a8c1
SH
3461 if (local_err) {
3462 error_propagate(errp, local_err);
bd4b167f
HR
3463 ret = -EINVAL;
3464 goto finish;
3465 }
3466
b76b4f60
KW
3467 /* Silently round up size */
3468 create_options->u.qcow2.size = ROUND_UP(create_options->u.qcow2.size,
3469 BDRV_SECTOR_SIZE);
cbf2b7c4
KW
3470
3471 /* Create the qcow2 image (format layer) */
b76b4f60 3472 ret = qcow2_co_create(create_options, errp);
cbf2b7c4
KW
3473 if (ret < 0) {
3474 goto finish;
3475 }
1bd0e2d1 3476
b76b4f60 3477 ret = 0;
1bd0e2d1 3478finish:
cb3e7f08 3479 qobject_unref(qdict);
cbf2b7c4 3480 bdrv_unref(bs);
9b890bdc 3481 bdrv_unref(data_bs);
b76b4f60 3482 qapi_free_BlockdevCreateOptions(create_options);
3ef6c40a 3483 return ret;
de5f3f40
KW
3484}
3485
2928abce 3486
f06f6b66 3487static bool is_zero(BlockDriverState *bs, int64_t offset, int64_t bytes)
2928abce 3488{
31826642
EB
3489 int64_t nr;
3490 int res;
f06f6b66
EB
3491
3492 /* Clamp to image length, before checking status of underlying sectors */
8cbf74b2
EB
3493 if (offset + bytes > bs->total_sectors * BDRV_SECTOR_SIZE) {
3494 bytes = bs->total_sectors * BDRV_SECTOR_SIZE - offset;
fbaa6bb3
EB
3495 }
3496
f06f6b66 3497 if (!bytes) {
ebb718a5
EB
3498 return true;
3499 }
8cbf74b2 3500 res = bdrv_block_status_above(bs, NULL, offset, bytes, &nr, NULL, NULL);
31826642 3501 return res >= 0 && (res & BDRV_BLOCK_ZERO) && nr == bytes;
2928abce
DL
3502}
3503
5544b59f 3504static coroutine_fn int qcow2_co_pwrite_zeroes(BlockDriverState *bs,
f5a5ca79 3505 int64_t offset, int bytes, BdrvRequestFlags flags)
621f0589
KW
3506{
3507 int ret;
ff99129a 3508 BDRVQcow2State *s = bs->opaque;
621f0589 3509
5544b59f 3510 uint32_t head = offset % s->cluster_size;
f5a5ca79 3511 uint32_t tail = (offset + bytes) % s->cluster_size;
2928abce 3512
f5a5ca79
MP
3513 trace_qcow2_pwrite_zeroes_start_req(qemu_coroutine_self(), offset, bytes);
3514 if (offset + bytes == bs->total_sectors * BDRV_SECTOR_SIZE) {
fbaa6bb3
EB
3515 tail = 0;
3516 }
5a64e942 3517
ebb718a5 3518 if (head || tail) {
ebb718a5 3519 uint64_t off;
ecfe1863 3520 unsigned int nr;
2928abce 3521
f5a5ca79 3522 assert(head + bytes <= s->cluster_size);
2928abce 3523
ebb718a5 3524 /* check whether remainder of cluster already reads as zero */
f06f6b66
EB
3525 if (!(is_zero(bs, offset - head, head) &&
3526 is_zero(bs, offset + bytes,
3527 tail ? s->cluster_size - tail : 0))) {
2928abce
DL
3528 return -ENOTSUP;
3529 }
3530
2928abce
DL
3531 qemu_co_mutex_lock(&s->lock);
3532 /* We can have new write after previous check */
f06f6b66 3533 offset = QEMU_ALIGN_DOWN(offset, s->cluster_size);
f5a5ca79 3534 bytes = s->cluster_size;
ecfe1863 3535 nr = s->cluster_size;
5544b59f 3536 ret = qcow2_get_cluster_offset(bs, offset, &nr, &off);
fdfab37d
EB
3537 if (ret != QCOW2_CLUSTER_UNALLOCATED &&
3538 ret != QCOW2_CLUSTER_ZERO_PLAIN &&
3539 ret != QCOW2_CLUSTER_ZERO_ALLOC) {
2928abce
DL
3540 qemu_co_mutex_unlock(&s->lock);
3541 return -ENOTSUP;
3542 }
3543 } else {
3544 qemu_co_mutex_lock(&s->lock);
621f0589
KW
3545 }
3546
f5a5ca79 3547 trace_qcow2_pwrite_zeroes(qemu_coroutine_self(), offset, bytes);
5a64e942 3548
621f0589 3549 /* Whatever is left can use real zero clusters */
f5a5ca79 3550 ret = qcow2_cluster_zeroize(bs, offset, bytes, flags);
621f0589
KW
3551 qemu_co_mutex_unlock(&s->lock);
3552
3553 return ret;
3554}
3555
82e8a788 3556static coroutine_fn int qcow2_co_pdiscard(BlockDriverState *bs,
f5a5ca79 3557 int64_t offset, int bytes)
5ea929e3 3558{
6db39ae2 3559 int ret;
ff99129a 3560 BDRVQcow2State *s = bs->opaque;
6db39ae2 3561
f5a5ca79
MP
3562 if (!QEMU_IS_ALIGNED(offset | bytes, s->cluster_size)) {
3563 assert(bytes < s->cluster_size);
048c5fd1
EB
3564 /* Ignore partial clusters, except for the special case of the
3565 * complete partial cluster at the end of an unaligned file */
3566 if (!QEMU_IS_ALIGNED(offset, s->cluster_size) ||
f5a5ca79 3567 offset + bytes != bs->total_sectors * BDRV_SECTOR_SIZE) {
048c5fd1
EB
3568 return -ENOTSUP;
3569 }
49228d1e
EB
3570 }
3571
6db39ae2 3572 qemu_co_mutex_lock(&s->lock);
f5a5ca79 3573 ret = qcow2_cluster_discard(bs, offset, bytes, QCOW2_DISCARD_REQUEST,
d2cb36af 3574 false);
6db39ae2
PB
3575 qemu_co_mutex_unlock(&s->lock);
3576 return ret;
5ea929e3
KW
3577}
3578
fd9fcd37
FZ
3579static int coroutine_fn
3580qcow2_co_copy_range_from(BlockDriverState *bs,
3581 BdrvChild *src, uint64_t src_offset,
3582 BdrvChild *dst, uint64_t dst_offset,
67b51fb9
VSO
3583 uint64_t bytes, BdrvRequestFlags read_flags,
3584 BdrvRequestFlags write_flags)
fd9fcd37
FZ
3585{
3586 BDRVQcow2State *s = bs->opaque;
3587 int ret;
3588 unsigned int cur_bytes; /* number of bytes in current iteration */
3589 BdrvChild *child = NULL;
67b51fb9 3590 BdrvRequestFlags cur_write_flags;
fd9fcd37
FZ
3591
3592 assert(!bs->encrypted);
3593 qemu_co_mutex_lock(&s->lock);
3594
3595 while (bytes != 0) {
3596 uint64_t copy_offset = 0;
3597 /* prepare next request */
3598 cur_bytes = MIN(bytes, INT_MAX);
67b51fb9 3599 cur_write_flags = write_flags;
fd9fcd37
FZ
3600
3601 ret = qcow2_get_cluster_offset(bs, src_offset, &cur_bytes, &copy_offset);
3602 if (ret < 0) {
3603 goto out;
3604 }
3605
3606 switch (ret) {
3607 case QCOW2_CLUSTER_UNALLOCATED:
3608 if (bs->backing && bs->backing->bs) {
3609 int64_t backing_length = bdrv_getlength(bs->backing->bs);
3610 if (src_offset >= backing_length) {
67b51fb9 3611 cur_write_flags |= BDRV_REQ_ZERO_WRITE;
fd9fcd37
FZ
3612 } else {
3613 child = bs->backing;
3614 cur_bytes = MIN(cur_bytes, backing_length - src_offset);
3615 copy_offset = src_offset;
3616 }
3617 } else {
67b51fb9 3618 cur_write_flags |= BDRV_REQ_ZERO_WRITE;
fd9fcd37
FZ
3619 }
3620 break;
3621
3622 case QCOW2_CLUSTER_ZERO_PLAIN:
3623 case QCOW2_CLUSTER_ZERO_ALLOC:
67b51fb9 3624 cur_write_flags |= BDRV_REQ_ZERO_WRITE;
fd9fcd37
FZ
3625 break;
3626
3627 case QCOW2_CLUSTER_COMPRESSED:
3628 ret = -ENOTSUP;
3629 goto out;
fd9fcd37
FZ
3630
3631 case QCOW2_CLUSTER_NORMAL:
966b000f 3632 child = s->data_file;
fd9fcd37
FZ
3633 copy_offset += offset_into_cluster(s, src_offset);
3634 if ((copy_offset & 511) != 0) {
3635 ret = -EIO;
3636 goto out;
3637 }
3638 break;
3639
3640 default:
3641 abort();
3642 }
3643 qemu_co_mutex_unlock(&s->lock);
3644 ret = bdrv_co_copy_range_from(child,
3645 copy_offset,
3646 dst, dst_offset,
67b51fb9 3647 cur_bytes, read_flags, cur_write_flags);
fd9fcd37
FZ
3648 qemu_co_mutex_lock(&s->lock);
3649 if (ret < 0) {
3650 goto out;
3651 }
3652
3653 bytes -= cur_bytes;
3654 src_offset += cur_bytes;
3655 dst_offset += cur_bytes;
3656 }
3657 ret = 0;
3658
3659out:
3660 qemu_co_mutex_unlock(&s->lock);
3661 return ret;
3662}
3663
3664static int coroutine_fn
3665qcow2_co_copy_range_to(BlockDriverState *bs,
3666 BdrvChild *src, uint64_t src_offset,
3667 BdrvChild *dst, uint64_t dst_offset,
67b51fb9
VSO
3668 uint64_t bytes, BdrvRequestFlags read_flags,
3669 BdrvRequestFlags write_flags)
fd9fcd37
FZ
3670{
3671 BDRVQcow2State *s = bs->opaque;
3672 int offset_in_cluster;
3673 int ret;
3674 unsigned int cur_bytes; /* number of sectors in current iteration */
3675 uint64_t cluster_offset;
fd9fcd37
FZ
3676 QCowL2Meta *l2meta = NULL;
3677
3678 assert(!bs->encrypted);
fd9fcd37
FZ
3679
3680 qemu_co_mutex_lock(&s->lock);
3681
3682 while (bytes != 0) {
3683
3684 l2meta = NULL;
3685
3686 offset_in_cluster = offset_into_cluster(s, dst_offset);
3687 cur_bytes = MIN(bytes, INT_MAX);
3688
3689 /* TODO:
3690 * If src->bs == dst->bs, we could simply copy by incrementing
3691 * the refcnt, without copying user data.
3692 * Or if src->bs == dst->bs->backing->bs, we could copy by discarding. */
3693 ret = qcow2_alloc_cluster_offset(bs, dst_offset, &cur_bytes,
3694 &cluster_offset, &l2meta);
3695 if (ret < 0) {
3696 goto fail;
3697 }
3698
3699 assert((cluster_offset & 511) == 0);
3700
3701 ret = qcow2_pre_write_overlap_check(bs, 0,
966b000f 3702 cluster_offset + offset_in_cluster, cur_bytes, true);
fd9fcd37
FZ
3703 if (ret < 0) {
3704 goto fail;
3705 }
3706
3707 qemu_co_mutex_unlock(&s->lock);
3708 ret = bdrv_co_copy_range_to(src, src_offset,
966b000f 3709 s->data_file,
fd9fcd37 3710 cluster_offset + offset_in_cluster,
67b51fb9 3711 cur_bytes, read_flags, write_flags);
fd9fcd37
FZ
3712 qemu_co_mutex_lock(&s->lock);
3713 if (ret < 0) {
3714 goto fail;
3715 }
3716
3717 ret = qcow2_handle_l2meta(bs, &l2meta, true);
3718 if (ret) {
3719 goto fail;
3720 }
3721
3722 bytes -= cur_bytes;
e06f4639 3723 src_offset += cur_bytes;
fd9fcd37
FZ
3724 dst_offset += cur_bytes;
3725 }
3726 ret = 0;
3727
3728fail:
3729 qcow2_handle_l2meta(bs, &l2meta, false);
3730
3731 qemu_co_mutex_unlock(&s->lock);
3732
fd9fcd37
FZ
3733 trace_qcow2_writev_done_req(qemu_coroutine_self(), ret);
3734
3735 return ret;
3736}
3737
061ca8a3
KW
3738static int coroutine_fn qcow2_co_truncate(BlockDriverState *bs, int64_t offset,
3739 PreallocMode prealloc, Error **errp)
419b19d9 3740{
ff99129a 3741 BDRVQcow2State *s = bs->opaque;
95b98f34 3742 uint64_t old_length;
2cf7cfa1
KW
3743 int64_t new_l1_size;
3744 int ret;
45b4949c 3745 QDict *options;
419b19d9 3746
772d1f97
HR
3747 if (prealloc != PREALLOC_MODE_OFF && prealloc != PREALLOC_MODE_METADATA &&
3748 prealloc != PREALLOC_MODE_FALLOC && prealloc != PREALLOC_MODE_FULL)
3749 {
8243ccb7 3750 error_setg(errp, "Unsupported preallocation mode '%s'",
977c736f 3751 PreallocMode_str(prealloc));
8243ccb7
HR
3752 return -ENOTSUP;
3753 }
3754
419b19d9 3755 if (offset & 511) {
4bff28b8 3756 error_setg(errp, "The new size must be a multiple of 512");
419b19d9
SH
3757 return -EINVAL;
3758 }
3759
061ca8a3
KW
3760 qemu_co_mutex_lock(&s->lock);
3761
419b19d9
SH
3762 /* cannot proceed if image has snapshots */
3763 if (s->nb_snapshots) {
4bff28b8 3764 error_setg(errp, "Can't resize an image which has snapshots");
061ca8a3
KW
3765 ret = -ENOTSUP;
3766 goto fail;
419b19d9
SH
3767 }
3768
88ddffae 3769 /* cannot proceed if image has bitmaps */
d19c6b36 3770 if (qcow2_truncate_bitmaps_check(bs, errp)) {
061ca8a3
KW
3771 ret = -ENOTSUP;
3772 goto fail;
88ddffae
VSO
3773 }
3774
bd016b91 3775 old_length = bs->total_sectors * BDRV_SECTOR_SIZE;
46b732cd 3776 new_l1_size = size_to_l1(s, offset);
95b98f34 3777
95b98f34 3778 if (offset < old_length) {
163bc39d 3779 int64_t last_cluster, old_file_size;
46b732cd
PB
3780 if (prealloc != PREALLOC_MODE_OFF) {
3781 error_setg(errp,
3782 "Preallocation can't be used for shrinking an image");
061ca8a3
KW
3783 ret = -EINVAL;
3784 goto fail;
46b732cd 3785 }
419b19d9 3786
46b732cd
PB
3787 ret = qcow2_cluster_discard(bs, ROUND_UP(offset, s->cluster_size),
3788 old_length - ROUND_UP(offset,
3789 s->cluster_size),
3790 QCOW2_DISCARD_ALWAYS, true);
3791 if (ret < 0) {
3792 error_setg_errno(errp, -ret, "Failed to discard cropped clusters");
061ca8a3 3793 goto fail;
46b732cd
PB
3794 }
3795
3796 ret = qcow2_shrink_l1_table(bs, new_l1_size);
3797 if (ret < 0) {
3798 error_setg_errno(errp, -ret,
3799 "Failed to reduce the number of L2 tables");
061ca8a3 3800 goto fail;
46b732cd
PB
3801 }
3802
3803 ret = qcow2_shrink_reftable(bs);
3804 if (ret < 0) {
3805 error_setg_errno(errp, -ret,
3806 "Failed to discard unused refblocks");
061ca8a3 3807 goto fail;
46b732cd 3808 }
163bc39d
PB
3809
3810 old_file_size = bdrv_getlength(bs->file->bs);
3811 if (old_file_size < 0) {
3812 error_setg_errno(errp, -old_file_size,
3813 "Failed to inquire current file length");
061ca8a3
KW
3814 ret = old_file_size;
3815 goto fail;
163bc39d
PB
3816 }
3817 last_cluster = qcow2_get_last_cluster(bs, old_file_size);
3818 if (last_cluster < 0) {
3819 error_setg_errno(errp, -last_cluster,
3820 "Failed to find the last cluster");
061ca8a3
KW
3821 ret = last_cluster;
3822 goto fail;
163bc39d
PB
3823 }
3824 if ((last_cluster + 1) * s->cluster_size < old_file_size) {
233521b1
HR
3825 Error *local_err = NULL;
3826
061ca8a3
KW
3827 bdrv_co_truncate(bs->file, (last_cluster + 1) * s->cluster_size,
3828 PREALLOC_MODE_OFF, &local_err);
233521b1
HR
3829 if (local_err) {
3830 warn_reportf_err(local_err,
3831 "Failed to truncate the tail of the image: ");
163bc39d
PB
3832 }
3833 }
46b732cd
PB
3834 } else {
3835 ret = qcow2_grow_l1_table(bs, new_l1_size, true);
3836 if (ret < 0) {
3837 error_setg_errno(errp, -ret, "Failed to grow the L1 table");
061ca8a3 3838 goto fail;
46b732cd 3839 }
419b19d9
SH
3840 }
3841
95b98f34
HR
3842 switch (prealloc) {
3843 case PREALLOC_MODE_OFF:
718c0fce
KW
3844 if (has_data_file(bs)) {
3845 ret = bdrv_co_truncate(s->data_file, offset, prealloc, errp);
3846 if (ret < 0) {
3847 goto fail;
3848 }
3849 }
95b98f34
HR
3850 break;
3851
3852 case PREALLOC_MODE_METADATA:
718c0fce 3853 ret = preallocate_co(bs, old_length, offset, prealloc, errp);
95b98f34 3854 if (ret < 0) {
061ca8a3 3855 goto fail;
95b98f34
HR
3856 }
3857 break;
3858
772d1f97
HR
3859 case PREALLOC_MODE_FALLOC:
3860 case PREALLOC_MODE_FULL:
3861 {
3862 int64_t allocation_start, host_offset, guest_offset;
3863 int64_t clusters_allocated;
3864 int64_t old_file_size, new_file_size;
3865 uint64_t nb_new_data_clusters, nb_new_l2_tables;
3866
966b000f
KW
3867 /* With a data file, preallocation means just allocating the metadata
3868 * and forwarding the truncate request to the data file */
3869 if (has_data_file(bs)) {
718c0fce 3870 ret = preallocate_co(bs, old_length, offset, prealloc, errp);
966b000f 3871 if (ret < 0) {
966b000f
KW
3872 goto fail;
3873 }
3874 break;
3875 }
3876
772d1f97
HR
3877 old_file_size = bdrv_getlength(bs->file->bs);
3878 if (old_file_size < 0) {
3879 error_setg_errno(errp, -old_file_size,
3880 "Failed to inquire current file length");
061ca8a3
KW
3881 ret = old_file_size;
3882 goto fail;
772d1f97 3883 }
e400ad1e 3884 old_file_size = ROUND_UP(old_file_size, s->cluster_size);
772d1f97
HR
3885
3886 nb_new_data_clusters = DIV_ROUND_UP(offset - old_length,
3887 s->cluster_size);
3888
3889 /* This is an overestimation; we will not actually allocate space for
3890 * these in the file but just make sure the new refcount structures are
3891 * able to cover them so we will not have to allocate new refblocks
3892 * while entering the data blocks in the potentially new L2 tables.
3893 * (We do not actually care where the L2 tables are placed. Maybe they
3894 * are already allocated or they can be placed somewhere before
3895 * @old_file_size. It does not matter because they will be fully
3896 * allocated automatically, so they do not need to be covered by the
3897 * preallocation. All that matters is that we will not have to allocate
3898 * new refcount structures for them.) */
3899 nb_new_l2_tables = DIV_ROUND_UP(nb_new_data_clusters,
3900 s->cluster_size / sizeof(uint64_t));
3901 /* The cluster range may not be aligned to L2 boundaries, so add one L2
3902 * table for a potential head/tail */
3903 nb_new_l2_tables++;
3904
3905 allocation_start = qcow2_refcount_area(bs, old_file_size,
3906 nb_new_data_clusters +
3907 nb_new_l2_tables,
3908 true, 0, 0);
3909 if (allocation_start < 0) {
3910 error_setg_errno(errp, -allocation_start,
3911 "Failed to resize refcount structures");
061ca8a3
KW
3912 ret = allocation_start;
3913 goto fail;
772d1f97
HR
3914 }
3915
3916 clusters_allocated = qcow2_alloc_clusters_at(bs, allocation_start,
3917 nb_new_data_clusters);
3918 if (clusters_allocated < 0) {
3919 error_setg_errno(errp, -clusters_allocated,
3920 "Failed to allocate data clusters");
061ca8a3
KW
3921 ret = clusters_allocated;
3922 goto fail;
772d1f97
HR
3923 }
3924
3925 assert(clusters_allocated == nb_new_data_clusters);
3926
3927 /* Allocate the data area */
3928 new_file_size = allocation_start +
3929 nb_new_data_clusters * s->cluster_size;
061ca8a3 3930 ret = bdrv_co_truncate(bs->file, new_file_size, prealloc, errp);
772d1f97
HR
3931 if (ret < 0) {
3932 error_prepend(errp, "Failed to resize underlying file: ");
3933 qcow2_free_clusters(bs, allocation_start,
3934 nb_new_data_clusters * s->cluster_size,
3935 QCOW2_DISCARD_OTHER);
061ca8a3 3936 goto fail;
772d1f97
HR
3937 }
3938
3939 /* Create the necessary L2 entries */
3940 host_offset = allocation_start;
3941 guest_offset = old_length;
3942 while (nb_new_data_clusters) {
13bec229
AG
3943 int64_t nb_clusters = MIN(
3944 nb_new_data_clusters,
3945 s->l2_slice_size - offset_to_l2_slice_index(s, guest_offset));
772d1f97
HR
3946 QCowL2Meta allocation = {
3947 .offset = guest_offset,
3948 .alloc_offset = host_offset,
3949 .nb_clusters = nb_clusters,
3950 };
3951 qemu_co_queue_init(&allocation.dependent_requests);
3952
3953 ret = qcow2_alloc_cluster_link_l2(bs, &allocation);
3954 if (ret < 0) {
3955 error_setg_errno(errp, -ret, "Failed to update L2 tables");
3956 qcow2_free_clusters(bs, host_offset,
3957 nb_new_data_clusters * s->cluster_size,
3958 QCOW2_DISCARD_OTHER);
061ca8a3 3959 goto fail;
772d1f97
HR
3960 }
3961
3962 guest_offset += nb_clusters * s->cluster_size;
3963 host_offset += nb_clusters * s->cluster_size;
3964 nb_new_data_clusters -= nb_clusters;
3965 }
3966 break;
3967 }
3968
95b98f34
HR
3969 default:
3970 g_assert_not_reached();
3971 }
3972
3973 if (prealloc != PREALLOC_MODE_OFF) {
3974 /* Flush metadata before actually changing the image size */
061ca8a3 3975 ret = qcow2_write_caches(bs);
95b98f34
HR
3976 if (ret < 0) {
3977 error_setg_errno(errp, -ret,
3978 "Failed to flush the preallocated area to disk");
061ca8a3 3979 goto fail;
95b98f34
HR
3980 }
3981 }
3982
45b4949c
LB
3983 bs->total_sectors = offset / BDRV_SECTOR_SIZE;
3984
419b19d9
SH
3985 /* write updated header.size */
3986 offset = cpu_to_be64(offset);
d9ca2ea2 3987 ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, size),
8b3b7206 3988 &offset, sizeof(uint64_t));
419b19d9 3989 if (ret < 0) {
f59adb32 3990 error_setg_errno(errp, -ret, "Failed to update the image size");
061ca8a3 3991 goto fail;
419b19d9
SH
3992 }
3993
3994 s->l1_vm_state_index = new_l1_size;
45b4949c
LB
3995
3996 /* Update cache sizes */
3997 options = qdict_clone_shallow(bs->options);
3998 ret = qcow2_update_options(bs, options, s->flags, errp);
3999 qobject_unref(options);
4000 if (ret < 0) {
4001 goto fail;
4002 }
061ca8a3
KW
4003 ret = 0;
4004fail:
4005 qemu_co_mutex_unlock(&s->lock);
4006 return ret;
419b19d9
SH
4007}
4008
20d97356
BS
4009/* XXX: put compressed sectors first, then all the cluster aligned
4010 tables to avoid losing bytes in alignment */
fcccefc5
PB
4011static coroutine_fn int
4012qcow2_co_pwritev_compressed(BlockDriverState *bs, uint64_t offset,
4013 uint64_t bytes, QEMUIOVector *qiov)
20d97356 4014{
ff99129a 4015 BDRVQcow2State *s = bs->opaque;
2714f13d 4016 int ret;
e1f4a37a 4017 ssize_t out_len;
fcccefc5 4018 uint8_t *buf, *out_buf;
77e023ff 4019 uint64_t cluster_offset;
20d97356 4020
966b000f
KW
4021 if (has_data_file(bs)) {
4022 return -ENOTSUP;
4023 }
4024
fcccefc5 4025 if (bytes == 0) {
20d97356
BS
4026 /* align end of file to a sector boundary to ease reading with
4027 sector based I/Os */
77e023ff
KW
4028 int64_t len = bdrv_getlength(bs->file->bs);
4029 if (len < 0) {
4030 return len;
d0d5d0e3 4031 }
77e023ff 4032 return bdrv_co_truncate(bs->file, len, PREALLOC_MODE_OFF, NULL);
20d97356
BS
4033 }
4034
3e3b838f
AN
4035 if (offset_into_cluster(s, offset)) {
4036 return -EINVAL;
4037 }
4038
a2c0ca6f 4039 buf = qemu_blockalign(bs, s->cluster_size);
fcccefc5 4040 if (bytes != s->cluster_size) {
a2c0ca6f
PB
4041 if (bytes > s->cluster_size ||
4042 offset + bytes != bs->total_sectors << BDRV_SECTOR_BITS)
fcccefc5 4043 {
a2c0ca6f
PB
4044 qemu_vfree(buf);
4045 return -EINVAL;
f4d38bef 4046 }
a2c0ca6f
PB
4047 /* Zero-pad last write if image size is not cluster aligned */
4048 memset(buf + bytes, 0, s->cluster_size - bytes);
f4d38bef 4049 }
8b2bd093 4050 qemu_iovec_to_buf(qiov, 0, buf, bytes);
20d97356 4051
ebf7bba0 4052 out_buf = g_malloc(s->cluster_size);
20d97356 4053
6994fd78
VSO
4054 out_len = qcow2_co_compress(bs, out_buf, s->cluster_size - 1,
4055 buf, s->cluster_size);
e1f4a37a 4056 if (out_len == -ENOMEM) {
20d97356 4057 /* could not compress: write normal cluster */
fcccefc5 4058 ret = qcow2_co_pwritev(bs, offset, bytes, qiov, 0);
8f1efd00
KW
4059 if (ret < 0) {
4060 goto fail;
4061 }
fcccefc5 4062 goto success;
e1f4a37a
AG
4063 } else if (out_len < 0) {
4064 ret = -EINVAL;
4065 goto fail;
fcccefc5 4066 }
cf93980e 4067
fcccefc5 4068 qemu_co_mutex_lock(&s->lock);
77e023ff
KW
4069 ret = qcow2_alloc_compressed_cluster_offset(bs, offset, out_len,
4070 &cluster_offset);
4071 if (ret < 0) {
fcccefc5 4072 qemu_co_mutex_unlock(&s->lock);
fcccefc5
PB
4073 goto fail;
4074 }
cf93980e 4075
966b000f 4076 ret = qcow2_pre_write_overlap_check(bs, 0, cluster_offset, out_len, true);
fcccefc5
PB
4077 qemu_co_mutex_unlock(&s->lock);
4078 if (ret < 0) {
4079 goto fail;
20d97356
BS
4080 }
4081
966b000f 4082 BLKDBG_EVENT(s->data_file, BLKDBG_WRITE_COMPRESSED);
b00cb15b 4083 ret = bdrv_co_pwrite(s->data_file, cluster_offset, out_len, out_buf, 0);
fcccefc5
PB
4084 if (ret < 0) {
4085 goto fail;
4086 }
4087success:
8f1efd00
KW
4088 ret = 0;
4089fail:
fcccefc5 4090 qemu_vfree(buf);
7267c094 4091 g_free(out_buf);
8f1efd00 4092 return ret;
20d97356
BS
4093}
4094
c3c10f72
VSO
4095static int coroutine_fn
4096qcow2_co_preadv_compressed(BlockDriverState *bs,
4097 uint64_t file_cluster_offset,
4098 uint64_t offset,
4099 uint64_t bytes,
4100 QEMUIOVector *qiov)
f4b3e2a9
VSO
4101{
4102 BDRVQcow2State *s = bs->opaque;
c3c10f72 4103 int ret = 0, csize, nb_csectors;
f4b3e2a9 4104 uint64_t coffset;
c3c10f72 4105 uint8_t *buf, *out_buf;
c3c10f72 4106 int offset_in_cluster = offset_into_cluster(s, offset);
f4b3e2a9 4107
c3c10f72
VSO
4108 coffset = file_cluster_offset & s->cluster_offset_mask;
4109 nb_csectors = ((file_cluster_offset >> s->csize_shift) & s->csize_mask) + 1;
b6c24694
AG
4110 csize = nb_csectors * QCOW2_COMPRESSED_SECTOR_SIZE -
4111 (coffset & ~QCOW2_COMPRESSED_SECTOR_MASK);
f4b3e2a9 4112
c3c10f72
VSO
4113 buf = g_try_malloc(csize);
4114 if (!buf) {
4115 return -ENOMEM;
4116 }
f4b3e2a9 4117
c3c10f72 4118 out_buf = qemu_blockalign(bs, s->cluster_size);
c068a1cd 4119
c3c10f72 4120 BLKDBG_EVENT(bs->file, BLKDBG_READ_COMPRESSED);
b00cb15b 4121 ret = bdrv_co_pread(bs->file, coffset, csize, buf, 0);
c3c10f72
VSO
4122 if (ret < 0) {
4123 goto fail;
f4b3e2a9 4124 }
c3c10f72 4125
e23c9d7a 4126 if (qcow2_co_decompress(bs, out_buf, s->cluster_size, buf, csize) < 0) {
c3c10f72
VSO
4127 ret = -EIO;
4128 goto fail;
4129 }
4130
4131 qemu_iovec_from_buf(qiov, 0, out_buf + offset_in_cluster, bytes);
4132
4133fail:
4134 qemu_vfree(out_buf);
4135 g_free(buf);
4136
4137 return ret;
f4b3e2a9
VSO
4138}
4139
94054183
HR
4140static int make_completely_empty(BlockDriverState *bs)
4141{
ff99129a 4142 BDRVQcow2State *s = bs->opaque;
ed3d2ec9 4143 Error *local_err = NULL;
94054183
HR
4144 int ret, l1_clusters;
4145 int64_t offset;
4146 uint64_t *new_reftable = NULL;
4147 uint64_t rt_entry, l1_size2;
4148 struct {
4149 uint64_t l1_offset;
4150 uint64_t reftable_offset;
4151 uint32_t reftable_clusters;
4152 } QEMU_PACKED l1_ofs_rt_ofs_cls;
4153
4154 ret = qcow2_cache_empty(bs, s->l2_table_cache);
4155 if (ret < 0) {
4156 goto fail;
4157 }
4158
4159 ret = qcow2_cache_empty(bs, s->refcount_block_cache);
4160 if (ret < 0) {
4161 goto fail;
4162 }
4163
4164 /* Refcounts will be broken utterly */
4165 ret = qcow2_mark_dirty(bs);
4166 if (ret < 0) {
4167 goto fail;
4168 }
4169
4170 BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
4171
4172 l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / sizeof(uint64_t));
4173 l1_size2 = (uint64_t)s->l1_size * sizeof(uint64_t);
4174
4175 /* After this call, neither the in-memory nor the on-disk refcount
4176 * information accurately describe the actual references */
4177
720ff280 4178 ret = bdrv_pwrite_zeroes(bs->file, s->l1_table_offset,
74021bc4 4179 l1_clusters * s->cluster_size, 0);
94054183
HR
4180 if (ret < 0) {
4181 goto fail_broken_refcounts;
4182 }
4183 memset(s->l1_table, 0, l1_size2);
4184
4185 BLKDBG_EVENT(bs->file, BLKDBG_EMPTY_IMAGE_PREPARE);
4186
4187 /* Overwrite enough clusters at the beginning of the sectors to place
4188 * the refcount table, a refcount block and the L1 table in; this may
4189 * overwrite parts of the existing refcount and L1 table, which is not
4190 * an issue because the dirty flag is set, complete data loss is in fact
4191 * desired and partial data loss is consequently fine as well */
720ff280 4192 ret = bdrv_pwrite_zeroes(bs->file, s->cluster_size,
74021bc4 4193 (2 + l1_clusters) * s->cluster_size, 0);
94054183
HR
4194 /* This call (even if it failed overall) may have overwritten on-disk
4195 * refcount structures; in that case, the in-memory refcount information
4196 * will probably differ from the on-disk information which makes the BDS
4197 * unusable */
4198 if (ret < 0) {
4199 goto fail_broken_refcounts;
4200 }
4201
4202 BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
4203 BLKDBG_EVENT(bs->file, BLKDBG_REFTABLE_UPDATE);
4204
4205 /* "Create" an empty reftable (one cluster) directly after the image
4206 * header and an empty L1 table three clusters after the image header;
4207 * the cluster between those two will be used as the first refblock */
f1f7a1dd
PM
4208 l1_ofs_rt_ofs_cls.l1_offset = cpu_to_be64(3 * s->cluster_size);
4209 l1_ofs_rt_ofs_cls.reftable_offset = cpu_to_be64(s->cluster_size);
4210 l1_ofs_rt_ofs_cls.reftable_clusters = cpu_to_be32(1);
d9ca2ea2 4211 ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, l1_table_offset),
94054183
HR
4212 &l1_ofs_rt_ofs_cls, sizeof(l1_ofs_rt_ofs_cls));
4213 if (ret < 0) {
4214 goto fail_broken_refcounts;
4215 }
4216
4217 s->l1_table_offset = 3 * s->cluster_size;
4218
4219 new_reftable = g_try_new0(uint64_t, s->cluster_size / sizeof(uint64_t));
4220 if (!new_reftable) {
4221 ret = -ENOMEM;
4222 goto fail_broken_refcounts;
4223 }
4224
4225 s->refcount_table_offset = s->cluster_size;
4226 s->refcount_table_size = s->cluster_size / sizeof(uint64_t);
7061a078 4227 s->max_refcount_table_index = 0;
94054183
HR
4228
4229 g_free(s->refcount_table);
4230 s->refcount_table = new_reftable;
4231 new_reftable = NULL;
4232
4233 /* Now the in-memory refcount information again corresponds to the on-disk
4234 * information (reftable is empty and no refblocks (the refblock cache is
4235 * empty)); however, this means some clusters (e.g. the image header) are
4236 * referenced, but not refcounted, but the normal qcow2 code assumes that
4237 * the in-memory information is always correct */
4238
4239 BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_ALLOC);
4240
4241 /* Enter the first refblock into the reftable */
4242 rt_entry = cpu_to_be64(2 * s->cluster_size);
d9ca2ea2 4243 ret = bdrv_pwrite_sync(bs->file, s->cluster_size,
94054183
HR
4244 &rt_entry, sizeof(rt_entry));
4245 if (ret < 0) {
4246 goto fail_broken_refcounts;
4247 }
4248 s->refcount_table[0] = 2 * s->cluster_size;
4249
4250 s->free_cluster_index = 0;
4251 assert(3 + l1_clusters <= s->refcount_block_size);
4252 offset = qcow2_alloc_clusters(bs, 3 * s->cluster_size + l1_size2);
4253 if (offset < 0) {
4254 ret = offset;
4255 goto fail_broken_refcounts;
4256 } else if (offset > 0) {
4257 error_report("First cluster in emptied image is in use");
4258 abort();
4259 }
4260
4261 /* Now finally the in-memory information corresponds to the on-disk
4262 * structures and is correct */
4263 ret = qcow2_mark_clean(bs);
4264 if (ret < 0) {
4265 goto fail;
4266 }
4267
ed3d2ec9 4268 ret = bdrv_truncate(bs->file, (3 + l1_clusters) * s->cluster_size,
7ea37c30 4269 PREALLOC_MODE_OFF, &local_err);
94054183 4270 if (ret < 0) {
ed3d2ec9 4271 error_report_err(local_err);
94054183
HR
4272 goto fail;
4273 }
4274
4275 return 0;
4276
4277fail_broken_refcounts:
4278 /* The BDS is unusable at this point. If we wanted to make it usable, we
4279 * would have to call qcow2_refcount_close(), qcow2_refcount_init(),
4280 * qcow2_check_refcounts(), qcow2_refcount_close() and qcow2_refcount_init()
4281 * again. However, because the functions which could have caused this error
4282 * path to be taken are used by those functions as well, it's very likely
4283 * that that sequence will fail as well. Therefore, just eject the BDS. */
4284 bs->drv = NULL;
4285
4286fail:
4287 g_free(new_reftable);
4288 return ret;
4289}
4290
491d27e2
HR
4291static int qcow2_make_empty(BlockDriverState *bs)
4292{
ff99129a 4293 BDRVQcow2State *s = bs->opaque;
d2cb36af
EB
4294 uint64_t offset, end_offset;
4295 int step = QEMU_ALIGN_DOWN(INT_MAX, s->cluster_size);
94054183
HR
4296 int l1_clusters, ret = 0;
4297
4298 l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / sizeof(uint64_t));
4299
4096974e 4300 if (s->qcow_version >= 3 && !s->snapshots && !s->nb_bitmaps &&
f0603329 4301 3 + l1_clusters <= s->refcount_block_size &&
db04524f
KW
4302 s->crypt_method_header != QCOW_CRYPT_LUKS &&
4303 !has_data_file(bs)) {
4096974e
EB
4304 /* The following function only works for qcow2 v3 images (it
4305 * requires the dirty flag) and only as long as there are no
4306 * features that reserve extra clusters (such as snapshots,
4307 * LUKS header, or persistent bitmaps), because it completely
4308 * empties the image. Furthermore, the L1 table and three
4309 * additional clusters (image header, refcount table, one
db04524f
KW
4310 * refcount block) have to fit inside one refcount block. It
4311 * only resets the image file, i.e. does not work with an
4312 * external data file. */
94054183
HR
4313 return make_completely_empty(bs);
4314 }
491d27e2 4315
94054183
HR
4316 /* This fallback code simply discards every active cluster; this is slow,
4317 * but works in all cases */
d2cb36af
EB
4318 end_offset = bs->total_sectors * BDRV_SECTOR_SIZE;
4319 for (offset = 0; offset < end_offset; offset += step) {
491d27e2
HR
4320 /* As this function is generally used after committing an external
4321 * snapshot, QCOW2_DISCARD_SNAPSHOT seems appropriate. Also, the
4322 * default action for this kind of discard is to pass the discard,
4323 * which will ideally result in an actually smaller image file, as
4324 * is probably desired. */
d2cb36af
EB
4325 ret = qcow2_cluster_discard(bs, offset, MIN(step, end_offset - offset),
4326 QCOW2_DISCARD_SNAPSHOT, true);
491d27e2
HR
4327 if (ret < 0) {
4328 break;
4329 }
4330 }
4331
4332 return ret;
4333}
4334
a968168c 4335static coroutine_fn int qcow2_co_flush_to_os(BlockDriverState *bs)
20d97356 4336{
ff99129a 4337 BDRVQcow2State *s = bs->opaque;
29c1a730
KW
4338 int ret;
4339
8b94ff85 4340 qemu_co_mutex_lock(&s->lock);
8b220eb7 4341 ret = qcow2_write_caches(bs);
8b94ff85 4342 qemu_co_mutex_unlock(&s->lock);
29c1a730 4343
8b220eb7 4344 return ret;
eb489bb1
KW
4345}
4346
61914f89
SH
4347static ssize_t qcow2_measure_crypto_hdr_init_func(QCryptoBlock *block,
4348 size_t headerlen, void *opaque, Error **errp)
4349{
4350 size_t *headerlenp = opaque;
4351
4352 /* Stash away the payload size */
4353 *headerlenp = headerlen;
4354 return 0;
4355}
4356
4357static ssize_t qcow2_measure_crypto_hdr_write_func(QCryptoBlock *block,
4358 size_t offset, const uint8_t *buf, size_t buflen,
4359 void *opaque, Error **errp)
4360{
4361 /* Discard the bytes, we're not actually writing to an image */
4362 return buflen;
4363}
4364
4365/* Determine the number of bytes for the LUKS payload */
4366static bool qcow2_measure_luks_headerlen(QemuOpts *opts, size_t *len,
4367 Error **errp)
4368{
4369 QDict *opts_qdict;
4370 QDict *cryptoopts_qdict;
4371 QCryptoBlockCreateOptions *cryptoopts;
4372 QCryptoBlock *crypto;
4373
4374 /* Extract "encrypt." options into a qdict */
4375 opts_qdict = qemu_opts_to_qdict(opts, NULL);
4376 qdict_extract_subqdict(opts_qdict, &cryptoopts_qdict, "encrypt.");
4377 qobject_unref(opts_qdict);
4378
4379 /* Build QCryptoBlockCreateOptions object from qdict */
4380 qdict_put_str(cryptoopts_qdict, "format", "luks");
4381 cryptoopts = block_crypto_create_opts_init(cryptoopts_qdict, errp);
4382 qobject_unref(cryptoopts_qdict);
4383 if (!cryptoopts) {
4384 return false;
4385 }
4386
4387 /* Fake LUKS creation in order to determine the payload size */
4388 crypto = qcrypto_block_create(cryptoopts, "encrypt.",
4389 qcow2_measure_crypto_hdr_init_func,
4390 qcow2_measure_crypto_hdr_write_func,
4391 len, errp);
4392 qapi_free_QCryptoBlockCreateOptions(cryptoopts);
4393 if (!crypto) {
4394 return false;
4395 }
4396
4397 qcrypto_block_free(crypto);
4398 return true;
4399}
4400
c501c352
SH
4401static BlockMeasureInfo *qcow2_measure(QemuOpts *opts, BlockDriverState *in_bs,
4402 Error **errp)
4403{
4404 Error *local_err = NULL;
4405 BlockMeasureInfo *info;
4406 uint64_t required = 0; /* bytes that contribute to required size */
4407 uint64_t virtual_size; /* disk size as seen by guest */
4408 uint64_t refcount_bits;
4409 uint64_t l2_tables;
61914f89 4410 uint64_t luks_payload_size = 0;
c501c352
SH
4411 size_t cluster_size;
4412 int version;
4413 char *optstr;
4414 PreallocMode prealloc;
4415 bool has_backing_file;
61914f89 4416 bool has_luks;
c501c352
SH
4417
4418 /* Parse image creation options */
4419 cluster_size = qcow2_opt_get_cluster_size_del(opts, &local_err);
4420 if (local_err) {
4421 goto err;
4422 }
4423
4424 version = qcow2_opt_get_version_del(opts, &local_err);
4425 if (local_err) {
4426 goto err;
4427 }
4428
4429 refcount_bits = qcow2_opt_get_refcount_bits_del(opts, version, &local_err);
4430 if (local_err) {
4431 goto err;
4432 }
4433
4434 optstr = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
f7abe0ec 4435 prealloc = qapi_enum_parse(&PreallocMode_lookup, optstr,
06c60b6c 4436 PREALLOC_MODE_OFF, &local_err);
c501c352
SH
4437 g_free(optstr);
4438 if (local_err) {
4439 goto err;
4440 }
4441
4442 optstr = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
4443 has_backing_file = !!optstr;
4444 g_free(optstr);
4445
61914f89
SH
4446 optstr = qemu_opt_get_del(opts, BLOCK_OPT_ENCRYPT_FORMAT);
4447 has_luks = optstr && strcmp(optstr, "luks") == 0;
4448 g_free(optstr);
4449
4450 if (has_luks) {
4451 size_t headerlen;
4452
4453 if (!qcow2_measure_luks_headerlen(opts, &headerlen, &local_err)) {
4454 goto err;
4455 }
4456
4457 luks_payload_size = ROUND_UP(headerlen, cluster_size);
4458 }
4459
9e029689
AG
4460 virtual_size = qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0);
4461 virtual_size = ROUND_UP(virtual_size, cluster_size);
c501c352
SH
4462
4463 /* Check that virtual disk size is valid */
4464 l2_tables = DIV_ROUND_UP(virtual_size / cluster_size,
4465 cluster_size / sizeof(uint64_t));
4466 if (l2_tables * sizeof(uint64_t) > QCOW_MAX_L1_SIZE) {
4467 error_setg(&local_err, "The image size is too large "
4468 "(try using a larger cluster size)");
4469 goto err;
4470 }
4471
4472 /* Account for input image */
4473 if (in_bs) {
4474 int64_t ssize = bdrv_getlength(in_bs);
4475 if (ssize < 0) {
4476 error_setg_errno(&local_err, -ssize,
4477 "Unable to get image virtual_size");
4478 goto err;
4479 }
4480
9e029689 4481 virtual_size = ROUND_UP(ssize, cluster_size);
c501c352
SH
4482
4483 if (has_backing_file) {
4484 /* We don't how much of the backing chain is shared by the input
4485 * image and the new image file. In the worst case the new image's
4486 * backing file has nothing in common with the input image. Be
4487 * conservative and assume all clusters need to be written.
4488 */
4489 required = virtual_size;
4490 } else {
b85ee453 4491 int64_t offset;
31826642 4492 int64_t pnum = 0;
c501c352 4493
31826642
EB
4494 for (offset = 0; offset < ssize; offset += pnum) {
4495 int ret;
c501c352 4496
31826642
EB
4497 ret = bdrv_block_status_above(in_bs, NULL, offset,
4498 ssize - offset, &pnum, NULL,
4499 NULL);
c501c352
SH
4500 if (ret < 0) {
4501 error_setg_errno(&local_err, -ret,
4502 "Unable to get block status");
4503 goto err;
4504 }
4505
4506 if (ret & BDRV_BLOCK_ZERO) {
4507 /* Skip zero regions (safe with no backing file) */
4508 } else if ((ret & (BDRV_BLOCK_DATA | BDRV_BLOCK_ALLOCATED)) ==
4509 (BDRV_BLOCK_DATA | BDRV_BLOCK_ALLOCATED)) {
4510 /* Extend pnum to end of cluster for next iteration */
31826642 4511 pnum = ROUND_UP(offset + pnum, cluster_size) - offset;
c501c352
SH
4512
4513 /* Count clusters we've seen */
31826642 4514 required += offset % cluster_size + pnum;
c501c352
SH
4515 }
4516 }
4517 }
4518 }
4519
4520 /* Take into account preallocation. Nothing special is needed for
4521 * PREALLOC_MODE_METADATA since metadata is always counted.
4522 */
4523 if (prealloc == PREALLOC_MODE_FULL || prealloc == PREALLOC_MODE_FALLOC) {
4524 required = virtual_size;
4525 }
4526
4527 info = g_new(BlockMeasureInfo, 1);
4528 info->fully_allocated =
4529 qcow2_calc_prealloc_size(virtual_size, cluster_size,
61914f89 4530 ctz32(refcount_bits)) + luks_payload_size;
c501c352
SH
4531
4532 /* Remove data clusters that are not required. This overestimates the
4533 * required size because metadata needed for the fully allocated file is
4534 * still counted.
4535 */
4536 info->required = info->fully_allocated - virtual_size + required;
4537 return info;
4538
4539err:
4540 error_propagate(errp, local_err);
4541 return NULL;
4542}
4543
7c80ab3f 4544static int qcow2_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
20d97356 4545{
ff99129a 4546 BDRVQcow2State *s = bs->opaque;
95de6d70 4547 bdi->unallocated_blocks_are_zero = true;
20d97356 4548 bdi->cluster_size = s->cluster_size;
7c80ab3f 4549 bdi->vm_state_offset = qcow2_vm_state_offset(s);
20d97356
BS
4550 return 0;
4551}
4552
1bf6e9ca
AS
4553static ImageInfoSpecific *qcow2_get_specific_info(BlockDriverState *bs,
4554 Error **errp)
37764dfb 4555{
ff99129a 4556 BDRVQcow2State *s = bs->opaque;
0a12f6f8
DB
4557 ImageInfoSpecific *spec_info;
4558 QCryptoBlockInfo *encrypt_info = NULL;
1bf6e9ca 4559 Error *local_err = NULL;
37764dfb 4560
0a12f6f8 4561 if (s->crypto != NULL) {
1bf6e9ca
AS
4562 encrypt_info = qcrypto_block_get_info(s->crypto, &local_err);
4563 if (local_err) {
4564 error_propagate(errp, local_err);
4565 return NULL;
4566 }
0a12f6f8
DB
4567 }
4568
4569 spec_info = g_new(ImageInfoSpecific, 1);
37764dfb 4570 *spec_info = (ImageInfoSpecific){
6a8f9661 4571 .type = IMAGE_INFO_SPECIFIC_KIND_QCOW2,
b8968c87 4572 .u.qcow2.data = g_new0(ImageInfoSpecificQCow2, 1),
37764dfb
HR
4573 };
4574 if (s->qcow_version == 2) {
32bafa8f 4575 *spec_info->u.qcow2.data = (ImageInfoSpecificQCow2){
0709c5a1
HR
4576 .compat = g_strdup("0.10"),
4577 .refcount_bits = s->refcount_bits,
37764dfb
HR
4578 };
4579 } else if (s->qcow_version == 3) {
b8968c87
AS
4580 Qcow2BitmapInfoList *bitmaps;
4581 bitmaps = qcow2_get_bitmap_info_list(bs, &local_err);
4582 if (local_err) {
4583 error_propagate(errp, local_err);
4584 qapi_free_ImageInfoSpecific(spec_info);
4585 return NULL;
4586 }
32bafa8f 4587 *spec_info->u.qcow2.data = (ImageInfoSpecificQCow2){
37764dfb
HR
4588 .compat = g_strdup("1.1"),
4589 .lazy_refcounts = s->compatible_features &
4590 QCOW2_COMPAT_LAZY_REFCOUNTS,
4591 .has_lazy_refcounts = true,
9009b196
HR
4592 .corrupt = s->incompatible_features &
4593 QCOW2_INCOMPAT_CORRUPT,
4594 .has_corrupt = true,
0709c5a1 4595 .refcount_bits = s->refcount_bits,
b8968c87
AS
4596 .has_bitmaps = !!bitmaps,
4597 .bitmaps = bitmaps,
9b890bdc
KW
4598 .has_data_file = !!s->image_data_file,
4599 .data_file = g_strdup(s->image_data_file),
6c3944dc
KW
4600 .has_data_file_raw = has_data_file(bs),
4601 .data_file_raw = data_file_is_raw(bs),
37764dfb 4602 };
b1fc8f93
DL
4603 } else {
4604 /* if this assertion fails, this probably means a new version was
4605 * added without having it covered here */
4606 assert(false);
37764dfb
HR
4607 }
4608
0a12f6f8
DB
4609 if (encrypt_info) {
4610 ImageInfoSpecificQCow2Encryption *qencrypt =
4611 g_new(ImageInfoSpecificQCow2Encryption, 1);
4612 switch (encrypt_info->format) {
4613 case Q_CRYPTO_BLOCK_FORMAT_QCOW:
4614 qencrypt->format = BLOCKDEV_QCOW2_ENCRYPTION_FORMAT_AES;
0a12f6f8
DB
4615 break;
4616 case Q_CRYPTO_BLOCK_FORMAT_LUKS:
4617 qencrypt->format = BLOCKDEV_QCOW2_ENCRYPTION_FORMAT_LUKS;
4618 qencrypt->u.luks = encrypt_info->u.luks;
4619 break;
4620 default:
4621 abort();
4622 }
4623 /* Since we did shallow copy above, erase any pointers
4624 * in the original info */
4625 memset(&encrypt_info->u, 0, sizeof(encrypt_info->u));
4626 qapi_free_QCryptoBlockInfo(encrypt_info);
4627
4628 spec_info->u.qcow2.data->has_encrypt = true;
4629 spec_info->u.qcow2.data->encrypt = qencrypt;
4630 }
4631
37764dfb
HR
4632 return spec_info;
4633}
4634
cf8074b3
KW
4635static int qcow2_save_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
4636 int64_t pos)
20d97356 4637{
ff99129a 4638 BDRVQcow2State *s = bs->opaque;
20d97356 4639
66f82cee 4640 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_SAVE);
734a7758
KW
4641 return bs->drv->bdrv_co_pwritev(bs, qcow2_vm_state_offset(s) + pos,
4642 qiov->size, qiov, 0);
20d97356
BS
4643}
4644
5ddda0b8
KW
4645static int qcow2_load_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
4646 int64_t pos)
20d97356 4647{
ff99129a 4648 BDRVQcow2State *s = bs->opaque;
20d97356 4649
66f82cee 4650 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_LOAD);
734a7758
KW
4651 return bs->drv->bdrv_co_preadv(bs, qcow2_vm_state_offset(s) + pos,
4652 qiov->size, qiov, 0);
20d97356
BS
4653}
4654
9296b3ed
HR
4655/*
4656 * Downgrades an image's version. To achieve this, any incompatible features
4657 * have to be removed.
4658 */
4057a2b2 4659static int qcow2_downgrade(BlockDriverState *bs, int target_version,
d1402b50
HR
4660 BlockDriverAmendStatusCB *status_cb, void *cb_opaque,
4661 Error **errp)
9296b3ed 4662{
ff99129a 4663 BDRVQcow2State *s = bs->opaque;
9296b3ed
HR
4664 int current_version = s->qcow_version;
4665 int ret;
4666
d1402b50
HR
4667 /* This is qcow2_downgrade(), not qcow2_upgrade() */
4668 assert(target_version < current_version);
4669
4670 /* There are no other versions (now) that you can downgrade to */
4671 assert(target_version == 2);
9296b3ed
HR
4672
4673 if (s->refcount_order != 4) {
d1402b50 4674 error_setg(errp, "compat=0.10 requires refcount_bits=16");
9296b3ed
HR
4675 return -ENOTSUP;
4676 }
4677
966b000f
KW
4678 if (has_data_file(bs)) {
4679 error_setg(errp, "Cannot downgrade an image with a data file");
4680 return -ENOTSUP;
4681 }
4682
9296b3ed
HR
4683 /* clear incompatible features */
4684 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
4685 ret = qcow2_mark_clean(bs);
4686 if (ret < 0) {
d1402b50 4687 error_setg_errno(errp, -ret, "Failed to make the image clean");
9296b3ed
HR
4688 return ret;
4689 }
4690 }
4691
4692 /* with QCOW2_INCOMPAT_CORRUPT, it is pretty much impossible to get here in
4693 * the first place; if that happens nonetheless, returning -ENOTSUP is the
4694 * best thing to do anyway */
4695
4696 if (s->incompatible_features) {
d1402b50
HR
4697 error_setg(errp, "Cannot downgrade an image with incompatible features "
4698 "%#" PRIx64 " set", s->incompatible_features);
9296b3ed
HR
4699 return -ENOTSUP;
4700 }
4701
4702 /* since we can ignore compatible features, we can set them to 0 as well */
4703 s->compatible_features = 0;
4704 /* if lazy refcounts have been used, they have already been fixed through
4705 * clearing the dirty flag */
4706
4707 /* clearing autoclear features is trivial */
4708 s->autoclear_features = 0;
4709
8b13976d 4710 ret = qcow2_expand_zero_clusters(bs, status_cb, cb_opaque);
9296b3ed 4711 if (ret < 0) {
d1402b50 4712 error_setg_errno(errp, -ret, "Failed to turn zero into data clusters");
9296b3ed
HR
4713 return ret;
4714 }
4715
4716 s->qcow_version = target_version;
4717 ret = qcow2_update_header(bs);
4718 if (ret < 0) {
4719 s->qcow_version = current_version;
d1402b50 4720 error_setg_errno(errp, -ret, "Failed to update the image header");
9296b3ed
HR
4721 return ret;
4722 }
4723 return 0;
4724}
4725
c293a809
HR
4726typedef enum Qcow2AmendOperation {
4727 /* This is the value Qcow2AmendHelperCBInfo::last_operation will be
4728 * statically initialized to so that the helper CB can discern the first
4729 * invocation from an operation change */
4730 QCOW2_NO_OPERATION = 0,
4731
61ce55fc 4732 QCOW2_CHANGING_REFCOUNT_ORDER,
c293a809
HR
4733 QCOW2_DOWNGRADING,
4734} Qcow2AmendOperation;
4735
4736typedef struct Qcow2AmendHelperCBInfo {
4737 /* The code coordinating the amend operations should only modify
4738 * these four fields; the rest will be managed by the CB */
4739 BlockDriverAmendStatusCB *original_status_cb;
4740 void *original_cb_opaque;
4741
4742 Qcow2AmendOperation current_operation;
4743
4744 /* Total number of operations to perform (only set once) */
4745 int total_operations;
4746
4747 /* The following fields are managed by the CB */
4748
4749 /* Number of operations completed */
4750 int operations_completed;
4751
4752 /* Cumulative offset of all completed operations */
4753 int64_t offset_completed;
4754
4755 Qcow2AmendOperation last_operation;
4756 int64_t last_work_size;
4757} Qcow2AmendHelperCBInfo;
4758
4759static void qcow2_amend_helper_cb(BlockDriverState *bs,
4760 int64_t operation_offset,
4761 int64_t operation_work_size, void *opaque)
4762{
4763 Qcow2AmendHelperCBInfo *info = opaque;
4764 int64_t current_work_size;
4765 int64_t projected_work_size;
4766
4767 if (info->current_operation != info->last_operation) {
4768 if (info->last_operation != QCOW2_NO_OPERATION) {
4769 info->offset_completed += info->last_work_size;
4770 info->operations_completed++;
4771 }
4772
4773 info->last_operation = info->current_operation;
4774 }
4775
4776 assert(info->total_operations > 0);
4777 assert(info->operations_completed < info->total_operations);
4778
4779 info->last_work_size = operation_work_size;
4780
4781 current_work_size = info->offset_completed + operation_work_size;
4782
4783 /* current_work_size is the total work size for (operations_completed + 1)
4784 * operations (which includes this one), so multiply it by the number of
4785 * operations not covered and divide it by the number of operations
4786 * covered to get a projection for the operations not covered */
4787 projected_work_size = current_work_size * (info->total_operations -
4788 info->operations_completed - 1)
4789 / (info->operations_completed + 1);
4790
4791 info->original_status_cb(bs, info->offset_completed + operation_offset,
4792 current_work_size + projected_work_size,
4793 info->original_cb_opaque);
4794}
4795
77485434 4796static int qcow2_amend_options(BlockDriverState *bs, QemuOpts *opts,
8b13976d 4797 BlockDriverAmendStatusCB *status_cb,
d1402b50
HR
4798 void *cb_opaque,
4799 Error **errp)
9296b3ed 4800{
ff99129a 4801 BDRVQcow2State *s = bs->opaque;
9296b3ed
HR
4802 int old_version = s->qcow_version, new_version = old_version;
4803 uint64_t new_size = 0;
9b890bdc 4804 const char *backing_file = NULL, *backing_format = NULL, *data_file = NULL;
9296b3ed 4805 bool lazy_refcounts = s->use_lazy_refcounts;
6c3944dc 4806 bool data_file_raw = data_file_is_raw(bs);
1bd0e2d1
CL
4807 const char *compat = NULL;
4808 uint64_t cluster_size = s->cluster_size;
4809 bool encrypt;
4652b8f3 4810 int encformat;
61ce55fc 4811 int refcount_bits = s->refcount_bits;
9296b3ed 4812 int ret;
1bd0e2d1 4813 QemuOptDesc *desc = opts->list->desc;
c293a809 4814 Qcow2AmendHelperCBInfo helper_cb_info;
9296b3ed 4815
1bd0e2d1
CL
4816 while (desc && desc->name) {
4817 if (!qemu_opt_find(opts, desc->name)) {
9296b3ed 4818 /* only change explicitly defined options */
1bd0e2d1 4819 desc++;
9296b3ed
HR
4820 continue;
4821 }
4822
8a17b83c
HR
4823 if (!strcmp(desc->name, BLOCK_OPT_COMPAT_LEVEL)) {
4824 compat = qemu_opt_get(opts, BLOCK_OPT_COMPAT_LEVEL);
1bd0e2d1 4825 if (!compat) {
9296b3ed 4826 /* preserve default */
f7077c98 4827 } else if (!strcmp(compat, "0.10") || !strcmp(compat, "v2")) {
9296b3ed 4828 new_version = 2;
f7077c98 4829 } else if (!strcmp(compat, "1.1") || !strcmp(compat, "v3")) {
9296b3ed
HR
4830 new_version = 3;
4831 } else {
d1402b50 4832 error_setg(errp, "Unknown compatibility level %s", compat);
9296b3ed
HR
4833 return -EINVAL;
4834 }
8a17b83c 4835 } else if (!strcmp(desc->name, BLOCK_OPT_PREALLOC)) {
d1402b50 4836 error_setg(errp, "Cannot change preallocation mode");
9296b3ed 4837 return -ENOTSUP;
8a17b83c
HR
4838 } else if (!strcmp(desc->name, BLOCK_OPT_SIZE)) {
4839 new_size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, 0);
4840 } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FILE)) {
4841 backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
4842 } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FMT)) {
4843 backing_format = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
4844 } else if (!strcmp(desc->name, BLOCK_OPT_ENCRYPT)) {
4845 encrypt = qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT,
b25b387f 4846 !!s->crypto);
f6fa64f6 4847
b25b387f 4848 if (encrypt != !!s->crypto) {
d1402b50
HR
4849 error_setg(errp,
4850 "Changing the encryption flag is not supported");
9296b3ed
HR
4851 return -ENOTSUP;
4852 }
4652b8f3
DB
4853 } else if (!strcmp(desc->name, BLOCK_OPT_ENCRYPT_FORMAT)) {
4854 encformat = qcow2_crypt_method_from_format(
4855 qemu_opt_get(opts, BLOCK_OPT_ENCRYPT_FORMAT));
4856
4857 if (encformat != s->crypt_method_header) {
d1402b50
HR
4858 error_setg(errp,
4859 "Changing the encryption format is not supported");
4652b8f3
DB
4860 return -ENOTSUP;
4861 }
f66afbe2 4862 } else if (g_str_has_prefix(desc->name, "encrypt.")) {
d1402b50
HR
4863 error_setg(errp,
4864 "Changing the encryption parameters is not supported");
f66afbe2 4865 return -ENOTSUP;
8a17b83c
HR
4866 } else if (!strcmp(desc->name, BLOCK_OPT_CLUSTER_SIZE)) {
4867 cluster_size = qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE,
1bd0e2d1
CL
4868 cluster_size);
4869 if (cluster_size != s->cluster_size) {
d1402b50 4870 error_setg(errp, "Changing the cluster size is not supported");
9296b3ed
HR
4871 return -ENOTSUP;
4872 }
8a17b83c
HR
4873 } else if (!strcmp(desc->name, BLOCK_OPT_LAZY_REFCOUNTS)) {
4874 lazy_refcounts = qemu_opt_get_bool(opts, BLOCK_OPT_LAZY_REFCOUNTS,
1bd0e2d1 4875 lazy_refcounts);
06d05fa7 4876 } else if (!strcmp(desc->name, BLOCK_OPT_REFCOUNT_BITS)) {
61ce55fc
HR
4877 refcount_bits = qemu_opt_get_number(opts, BLOCK_OPT_REFCOUNT_BITS,
4878 refcount_bits);
4879
4880 if (refcount_bits <= 0 || refcount_bits > 64 ||
4881 !is_power_of_2(refcount_bits))
4882 {
d1402b50
HR
4883 error_setg(errp, "Refcount width must be a power of two and "
4884 "may not exceed 64 bits");
61ce55fc
HR
4885 return -EINVAL;
4886 }
9b890bdc
KW
4887 } else if (!strcmp(desc->name, BLOCK_OPT_DATA_FILE)) {
4888 data_file = qemu_opt_get(opts, BLOCK_OPT_DATA_FILE);
4889 if (data_file && !has_data_file(bs)) {
4890 error_setg(errp, "data-file can only be set for images that "
4891 "use an external data file");
4892 return -EINVAL;
4893 }
6c3944dc
KW
4894 } else if (!strcmp(desc->name, BLOCK_OPT_DATA_FILE_RAW)) {
4895 data_file_raw = qemu_opt_get_bool(opts, BLOCK_OPT_DATA_FILE_RAW,
4896 data_file_raw);
4897 if (data_file_raw && !data_file_is_raw(bs)) {
4898 error_setg(errp, "data-file-raw cannot be set on existing "
4899 "images");
4900 return -EINVAL;
4901 }
9296b3ed 4902 } else {
164e0f89 4903 /* if this point is reached, this probably means a new option was
9296b3ed 4904 * added without having it covered here */
164e0f89 4905 abort();
9296b3ed 4906 }
1bd0e2d1
CL
4907
4908 desc++;
9296b3ed
HR
4909 }
4910
c293a809
HR
4911 helper_cb_info = (Qcow2AmendHelperCBInfo){
4912 .original_status_cb = status_cb,
4913 .original_cb_opaque = cb_opaque,
4914 .total_operations = (new_version < old_version)
61ce55fc 4915 + (s->refcount_bits != refcount_bits)
c293a809
HR
4916 };
4917
1038bbb8
HR
4918 /* Upgrade first (some features may require compat=1.1) */
4919 if (new_version > old_version) {
4920 s->qcow_version = new_version;
4921 ret = qcow2_update_header(bs);
4922 if (ret < 0) {
4923 s->qcow_version = old_version;
d1402b50 4924 error_setg_errno(errp, -ret, "Failed to update the image header");
1038bbb8 4925 return ret;
9296b3ed
HR
4926 }
4927 }
4928
61ce55fc
HR
4929 if (s->refcount_bits != refcount_bits) {
4930 int refcount_order = ctz32(refcount_bits);
61ce55fc
HR
4931
4932 if (new_version < 3 && refcount_bits != 16) {
d1402b50
HR
4933 error_setg(errp, "Refcount widths other than 16 bits require "
4934 "compatibility level 1.1 or above (use compat=1.1 or "
4935 "greater)");
61ce55fc
HR
4936 return -EINVAL;
4937 }
4938
4939 helper_cb_info.current_operation = QCOW2_CHANGING_REFCOUNT_ORDER;
4940 ret = qcow2_change_refcount_order(bs, refcount_order,
4941 &qcow2_amend_helper_cb,
d1402b50 4942 &helper_cb_info, errp);
61ce55fc 4943 if (ret < 0) {
61ce55fc
HR
4944 return ret;
4945 }
4946 }
4947
6c3944dc
KW
4948 /* data-file-raw blocks backing files, so clear it first if requested */
4949 if (data_file_raw) {
4950 s->autoclear_features |= QCOW2_AUTOCLEAR_DATA_FILE_RAW;
4951 } else {
4952 s->autoclear_features &= ~QCOW2_AUTOCLEAR_DATA_FILE_RAW;
4953 }
4954
9b890bdc
KW
4955 if (data_file) {
4956 g_free(s->image_data_file);
4957 s->image_data_file = *data_file ? g_strdup(data_file) : NULL;
4958 }
4959
4960 ret = qcow2_update_header(bs);
4961 if (ret < 0) {
4962 error_setg_errno(errp, -ret, "Failed to update the image header");
4963 return ret;
4964 }
4965
9296b3ed 4966 if (backing_file || backing_format) {
e4603fe1
KW
4967 ret = qcow2_change_backing_file(bs,
4968 backing_file ?: s->image_backing_file,
4969 backing_format ?: s->image_backing_format);
9296b3ed 4970 if (ret < 0) {
d1402b50 4971 error_setg_errno(errp, -ret, "Failed to change the backing file");
9296b3ed
HR
4972 return ret;
4973 }
4974 }
4975
4976 if (s->use_lazy_refcounts != lazy_refcounts) {
4977 if (lazy_refcounts) {
1038bbb8 4978 if (new_version < 3) {
d1402b50
HR
4979 error_setg(errp, "Lazy refcounts only supported with "
4980 "compatibility level 1.1 and above (use compat=1.1 "
4981 "or greater)");
9296b3ed
HR
4982 return -EINVAL;
4983 }
4984 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
4985 ret = qcow2_update_header(bs);
4986 if (ret < 0) {
4987 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
d1402b50 4988 error_setg_errno(errp, -ret, "Failed to update the image header");
9296b3ed
HR
4989 return ret;
4990 }
4991 s->use_lazy_refcounts = true;
4992 } else {
4993 /* make image clean first */
4994 ret = qcow2_mark_clean(bs);
4995 if (ret < 0) {
d1402b50 4996 error_setg_errno(errp, -ret, "Failed to make the image clean");
9296b3ed
HR
4997 return ret;
4998 }
4999 /* now disallow lazy refcounts */
5000 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
5001 ret = qcow2_update_header(bs);
5002 if (ret < 0) {
5003 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
d1402b50 5004 error_setg_errno(errp, -ret, "Failed to update the image header");
9296b3ed
HR
5005 return ret;
5006 }
5007 s->use_lazy_refcounts = false;
5008 }
5009 }
5010
5011 if (new_size) {
d861ab3a
KW
5012 BlockBackend *blk = blk_new(bdrv_get_aio_context(bs),
5013 BLK_PERM_RESIZE, BLK_PERM_ALL);
d1402b50 5014 ret = blk_insert_bs(blk, bs, errp);
d7086422 5015 if (ret < 0) {
d7086422
KW
5016 blk_unref(blk);
5017 return ret;
5018 }
5019
d1402b50 5020 ret = blk_truncate(blk, new_size, PREALLOC_MODE_OFF, errp);
70b27f36 5021 blk_unref(blk);
9296b3ed
HR
5022 if (ret < 0) {
5023 return ret;
5024 }
5025 }
5026
1038bbb8
HR
5027 /* Downgrade last (so unsupported features can be removed before) */
5028 if (new_version < old_version) {
c293a809
HR
5029 helper_cb_info.current_operation = QCOW2_DOWNGRADING;
5030 ret = qcow2_downgrade(bs, new_version, &qcow2_amend_helper_cb,
d1402b50 5031 &helper_cb_info, errp);
1038bbb8
HR
5032 if (ret < 0) {
5033 return ret;
5034 }
5035 }
5036
9296b3ed
HR
5037 return 0;
5038}
5039
85186ebd
HR
5040/*
5041 * If offset or size are negative, respectively, they will not be included in
5042 * the BLOCK_IMAGE_CORRUPTED event emitted.
5043 * fatal will be ignored for read-only BDS; corruptions found there will always
5044 * be considered non-fatal.
5045 */
5046void qcow2_signal_corruption(BlockDriverState *bs, bool fatal, int64_t offset,
5047 int64_t size, const char *message_format, ...)
5048{
ff99129a 5049 BDRVQcow2State *s = bs->opaque;
dc881b44 5050 const char *node_name;
85186ebd
HR
5051 char *message;
5052 va_list ap;
5053
ddf3b47e 5054 fatal = fatal && bdrv_is_writable(bs);
85186ebd
HR
5055
5056 if (s->signaled_corruption &&
5057 (!fatal || (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT)))
5058 {
5059 return;
5060 }
5061
5062 va_start(ap, message_format);
5063 message = g_strdup_vprintf(message_format, ap);
5064 va_end(ap);
5065
5066 if (fatal) {
5067 fprintf(stderr, "qcow2: Marking image as corrupt: %s; further "
5068 "corruption events will be suppressed\n", message);
5069 } else {
5070 fprintf(stderr, "qcow2: Image is corrupt: %s; further non-fatal "
5071 "corruption events will be suppressed\n", message);
5072 }
5073
dc881b44
AG
5074 node_name = bdrv_get_node_name(bs);
5075 qapi_event_send_block_image_corrupted(bdrv_get_device_name(bs),
5076 *node_name != '\0', node_name,
5077 message, offset >= 0, offset,
5078 size >= 0, size,
3ab72385 5079 fatal);
85186ebd
HR
5080 g_free(message);
5081
5082 if (fatal) {
5083 qcow2_mark_corrupt(bs);
5084 bs->drv = NULL; /* make BDS unusable */
5085 }
5086
5087 s->signaled_corruption = true;
5088}
5089
1bd0e2d1
CL
5090static QemuOptsList qcow2_create_opts = {
5091 .name = "qcow2-create-opts",
5092 .head = QTAILQ_HEAD_INITIALIZER(qcow2_create_opts.head),
5093 .desc = {
5094 {
5095 .name = BLOCK_OPT_SIZE,
5096 .type = QEMU_OPT_SIZE,
5097 .help = "Virtual disk size"
5098 },
5099 {
5100 .name = BLOCK_OPT_COMPAT_LEVEL,
5101 .type = QEMU_OPT_STRING,
f7077c98 5102 .help = "Compatibility level (v2 [0.10] or v3 [1.1])"
1bd0e2d1
CL
5103 },
5104 {
5105 .name = BLOCK_OPT_BACKING_FILE,
5106 .type = QEMU_OPT_STRING,
5107 .help = "File name of a base image"
5108 },
5109 {
5110 .name = BLOCK_OPT_BACKING_FMT,
5111 .type = QEMU_OPT_STRING,
5112 .help = "Image format of the base image"
5113 },
9b890bdc
KW
5114 {
5115 .name = BLOCK_OPT_DATA_FILE,
5116 .type = QEMU_OPT_STRING,
5117 .help = "File name of an external data file"
5118 },
6c3944dc
KW
5119 {
5120 .name = BLOCK_OPT_DATA_FILE_RAW,
5121 .type = QEMU_OPT_BOOL,
5122 .help = "The external data file must stay valid as a raw image"
5123 },
1bd0e2d1
CL
5124 {
5125 .name = BLOCK_OPT_ENCRYPT,
5126 .type = QEMU_OPT_BOOL,
0cb8d47b
DB
5127 .help = "Encrypt the image with format 'aes'. (Deprecated "
5128 "in favor of " BLOCK_OPT_ENCRYPT_FORMAT "=aes)",
5129 },
5130 {
5131 .name = BLOCK_OPT_ENCRYPT_FORMAT,
5132 .type = QEMU_OPT_STRING,
4652b8f3 5133 .help = "Encrypt the image, format choices: 'aes', 'luks'",
1bd0e2d1 5134 },
4652b8f3
DB
5135 BLOCK_CRYPTO_OPT_DEF_KEY_SECRET("encrypt.",
5136 "ID of secret providing qcow AES key or LUKS passphrase"),
5137 BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_ALG("encrypt."),
5138 BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_MODE("encrypt."),
5139 BLOCK_CRYPTO_OPT_DEF_LUKS_IVGEN_ALG("encrypt."),
5140 BLOCK_CRYPTO_OPT_DEF_LUKS_IVGEN_HASH_ALG("encrypt."),
5141 BLOCK_CRYPTO_OPT_DEF_LUKS_HASH_ALG("encrypt."),
5142 BLOCK_CRYPTO_OPT_DEF_LUKS_ITER_TIME("encrypt."),
1bd0e2d1
CL
5143 {
5144 .name = BLOCK_OPT_CLUSTER_SIZE,
5145 .type = QEMU_OPT_SIZE,
5146 .help = "qcow2 cluster size",
5147 .def_value_str = stringify(DEFAULT_CLUSTER_SIZE)
5148 },
5149 {
5150 .name = BLOCK_OPT_PREALLOC,
5151 .type = QEMU_OPT_STRING,
0e4271b7
HT
5152 .help = "Preallocation mode (allowed values: off, metadata, "
5153 "falloc, full)"
1bd0e2d1
CL
5154 },
5155 {
5156 .name = BLOCK_OPT_LAZY_REFCOUNTS,
5157 .type = QEMU_OPT_BOOL,
5158 .help = "Postpone refcount updates",
5159 .def_value_str = "off"
5160 },
06d05fa7
HR
5161 {
5162 .name = BLOCK_OPT_REFCOUNT_BITS,
5163 .type = QEMU_OPT_NUMBER,
5164 .help = "Width of a reference count entry in bits",
5165 .def_value_str = "16"
5166 },
1bd0e2d1
CL
5167 { /* end of list */ }
5168 }
20d97356
BS
5169};
5170
2654267c
HR
5171static const char *const qcow2_strong_runtime_opts[] = {
5172 "encrypt." BLOCK_CRYPTO_OPT_QCOW_KEY_SECRET,
5173
5174 NULL
5175};
5176
5f535a94 5177BlockDriver bdrv_qcow2 = {
7c80ab3f 5178 .format_name = "qcow2",
ff99129a 5179 .instance_size = sizeof(BDRVQcow2State),
7c80ab3f
JS
5180 .bdrv_probe = qcow2_probe,
5181 .bdrv_open = qcow2_open,
5182 .bdrv_close = qcow2_close,
21d82ac9 5183 .bdrv_reopen_prepare = qcow2_reopen_prepare,
5b0959a7
KW
5184 .bdrv_reopen_commit = qcow2_reopen_commit,
5185 .bdrv_reopen_abort = qcow2_reopen_abort,
5365f44d 5186 .bdrv_join_options = qcow2_join_options,
862f215f 5187 .bdrv_child_perm = bdrv_format_default_perms,
efc75e2a 5188 .bdrv_co_create_opts = qcow2_co_create_opts,
b0292b85 5189 .bdrv_co_create = qcow2_co_create,
3ac21627 5190 .bdrv_has_zero_init = bdrv_has_zero_init_1,
a320fb04 5191 .bdrv_co_block_status = qcow2_co_block_status,
7c80ab3f 5192
ecfe1863 5193 .bdrv_co_preadv = qcow2_co_preadv,
d46a0bb2 5194 .bdrv_co_pwritev = qcow2_co_pwritev,
eb489bb1 5195 .bdrv_co_flush_to_os = qcow2_co_flush_to_os,
419b19d9 5196
5544b59f 5197 .bdrv_co_pwrite_zeroes = qcow2_co_pwrite_zeroes,
82e8a788 5198 .bdrv_co_pdiscard = qcow2_co_pdiscard,
fd9fcd37
FZ
5199 .bdrv_co_copy_range_from = qcow2_co_copy_range_from,
5200 .bdrv_co_copy_range_to = qcow2_co_copy_range_to,
061ca8a3 5201 .bdrv_co_truncate = qcow2_co_truncate,
fcccefc5 5202 .bdrv_co_pwritev_compressed = qcow2_co_pwritev_compressed,
491d27e2 5203 .bdrv_make_empty = qcow2_make_empty,
20d97356
BS
5204
5205 .bdrv_snapshot_create = qcow2_snapshot_create,
5206 .bdrv_snapshot_goto = qcow2_snapshot_goto,
5207 .bdrv_snapshot_delete = qcow2_snapshot_delete,
5208 .bdrv_snapshot_list = qcow2_snapshot_list,
1bd0e2d1 5209 .bdrv_snapshot_load_tmp = qcow2_snapshot_load_tmp,
c501c352 5210 .bdrv_measure = qcow2_measure,
1bd0e2d1 5211 .bdrv_get_info = qcow2_get_info,
37764dfb 5212 .bdrv_get_specific_info = qcow2_get_specific_info,
20d97356 5213
7c80ab3f
JS
5214 .bdrv_save_vmstate = qcow2_save_vmstate,
5215 .bdrv_load_vmstate = qcow2_load_vmstate,
20d97356 5216
8ee79e70 5217 .supports_backing = true,
20d97356
BS
5218 .bdrv_change_backing_file = qcow2_change_backing_file,
5219
d34682cd 5220 .bdrv_refresh_limits = qcow2_refresh_limits,
2b148f39 5221 .bdrv_co_invalidate_cache = qcow2_co_invalidate_cache,
ec6d8912 5222 .bdrv_inactivate = qcow2_inactivate,
06d9260f 5223
1bd0e2d1 5224 .create_opts = &qcow2_create_opts,
2654267c 5225 .strong_runtime_opts = qcow2_strong_runtime_opts,
8a2ce0bc 5226 .mutable_opts = mutable_opts,
2fd61638 5227 .bdrv_co_check = qcow2_co_check,
c282e1fd 5228 .bdrv_amend_options = qcow2_amend_options,
279621c0
AG
5229
5230 .bdrv_detach_aio_context = qcow2_detach_aio_context,
5231 .bdrv_attach_aio_context = qcow2_attach_aio_context,
1b6b0562
VSO
5232
5233 .bdrv_reopen_bitmaps_rw = qcow2_reopen_bitmaps_rw,
da0eb242 5234 .bdrv_can_store_new_dirty_bitmap = qcow2_can_store_new_dirty_bitmap,
469c71ed 5235 .bdrv_remove_persistent_dirty_bitmap = qcow2_remove_persistent_dirty_bitmap,
20d97356
BS
5236};
5237
5efa9d5a
AL
5238static void bdrv_qcow2_init(void)
5239{
5240 bdrv_register(&bdrv_qcow2);
5241}
5242
5243block_init(bdrv_qcow2_init);