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