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