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