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