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