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