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