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