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