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