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