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