xref: /openbmc/qemu/block/qcow2.c (revision b2580720)
1 /*
2  * Block driver for the QCOW version 2 format
3  *
4  * Copyright (c) 2004-2006 Fabrice Bellard
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to deal
8  * in the Software without restriction, including without limitation the rights
9  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10  * copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22  * THE SOFTWARE.
23  */
24 
25 #include "qemu/osdep.h"
26 
27 #include "block/qdict.h"
28 #include "sysemu/block-backend.h"
29 #include "qemu/main-loop.h"
30 #include "qemu/module.h"
31 #include "qcow2.h"
32 #include "qemu/error-report.h"
33 #include "qapi/error.h"
34 #include "qapi/qapi-events-block-core.h"
35 #include "qapi/qmp/qdict.h"
36 #include "qapi/qmp/qstring.h"
37 #include "trace.h"
38 #include "qemu/option_int.h"
39 #include "qemu/cutils.h"
40 #include "qemu/bswap.h"
41 #include "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 cache_clean_timer_cb(void *opaque)
839 {
840     BlockDriverState *bs = opaque;
841     BDRVQcow2State *s = bs->opaque;
842     qcow2_cache_clean_unused(s->l2_table_cache);
843     qcow2_cache_clean_unused(s->refcount_block_cache);
844     timer_mod(s->cache_clean_timer, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) +
845               (int64_t) s->cache_clean_interval * 1000);
846 }
847 
848 static void cache_clean_timer_init(BlockDriverState *bs, AioContext *context)
849 {
850     BDRVQcow2State *s = bs->opaque;
851     if (s->cache_clean_interval > 0) {
852         s->cache_clean_timer =
853             aio_timer_new_with_attrs(context, QEMU_CLOCK_VIRTUAL,
854                                      SCALE_MS, QEMU_TIMER_ATTR_EXTERNAL,
855                                      cache_clean_timer_cb, bs);
856         timer_mod(s->cache_clean_timer, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) +
857                   (int64_t) s->cache_clean_interval * 1000);
858     }
859 }
860 
861 static void cache_clean_timer_del(BlockDriverState *bs)
862 {
863     BDRVQcow2State *s = bs->opaque;
864     if (s->cache_clean_timer) {
865         timer_free(s->cache_clean_timer);
866         s->cache_clean_timer = NULL;
867     }
868 }
869 
870 static void qcow2_detach_aio_context(BlockDriverState *bs)
871 {
872     cache_clean_timer_del(bs);
873 }
874 
875 static void qcow2_attach_aio_context(BlockDriverState *bs,
876                                      AioContext *new_context)
877 {
878     cache_clean_timer_init(bs, new_context);
879 }
880 
881 static bool read_cache_sizes(BlockDriverState *bs, QemuOpts *opts,
882                              uint64_t *l2_cache_size,
883                              uint64_t *l2_cache_entry_size,
884                              uint64_t *refcount_cache_size, Error **errp)
885 {
886     BDRVQcow2State *s = bs->opaque;
887     uint64_t combined_cache_size, l2_cache_max_setting;
888     bool l2_cache_size_set, refcount_cache_size_set, combined_cache_size_set;
889     bool l2_cache_entry_size_set;
890     int min_refcount_cache = MIN_REFCOUNT_CACHE_SIZE * s->cluster_size;
891     uint64_t virtual_disk_size = bs->total_sectors * BDRV_SECTOR_SIZE;
892     uint64_t max_l2_entries = DIV_ROUND_UP(virtual_disk_size, s->cluster_size);
893     /* An L2 table is always one cluster in size so the max cache size
894      * should be a multiple of the cluster size. */
895     uint64_t max_l2_cache = ROUND_UP(max_l2_entries * l2_entry_size(s),
896                                      s->cluster_size);
897 
898     combined_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_CACHE_SIZE);
899     l2_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_L2_CACHE_SIZE);
900     refcount_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
901     l2_cache_entry_size_set = qemu_opt_get(opts, QCOW2_OPT_L2_CACHE_ENTRY_SIZE);
902 
903     combined_cache_size = qemu_opt_get_size(opts, QCOW2_OPT_CACHE_SIZE, 0);
904     l2_cache_max_setting = qemu_opt_get_size(opts, QCOW2_OPT_L2_CACHE_SIZE,
905                                              DEFAULT_L2_CACHE_MAX_SIZE);
906     *refcount_cache_size = qemu_opt_get_size(opts,
907                                              QCOW2_OPT_REFCOUNT_CACHE_SIZE, 0);
908 
909     *l2_cache_entry_size = qemu_opt_get_size(
910         opts, QCOW2_OPT_L2_CACHE_ENTRY_SIZE, s->cluster_size);
911 
912     *l2_cache_size = MIN(max_l2_cache, l2_cache_max_setting);
913 
914     if (combined_cache_size_set) {
915         if (l2_cache_size_set && refcount_cache_size_set) {
916             error_setg(errp, QCOW2_OPT_CACHE_SIZE ", " QCOW2_OPT_L2_CACHE_SIZE
917                        " and " QCOW2_OPT_REFCOUNT_CACHE_SIZE " may not be set "
918                        "at the same time");
919             return false;
920         } else if (l2_cache_size_set &&
921                    (l2_cache_max_setting > combined_cache_size)) {
922             error_setg(errp, QCOW2_OPT_L2_CACHE_SIZE " may not exceed "
923                        QCOW2_OPT_CACHE_SIZE);
924             return false;
925         } else if (*refcount_cache_size > combined_cache_size) {
926             error_setg(errp, QCOW2_OPT_REFCOUNT_CACHE_SIZE " may not exceed "
927                        QCOW2_OPT_CACHE_SIZE);
928             return false;
929         }
930 
931         if (l2_cache_size_set) {
932             *refcount_cache_size = combined_cache_size - *l2_cache_size;
933         } else if (refcount_cache_size_set) {
934             *l2_cache_size = combined_cache_size - *refcount_cache_size;
935         } else {
936             /* Assign as much memory as possible to the L2 cache, and
937              * use the remainder for the refcount cache */
938             if (combined_cache_size >= max_l2_cache + min_refcount_cache) {
939                 *l2_cache_size = max_l2_cache;
940                 *refcount_cache_size = combined_cache_size - *l2_cache_size;
941             } else {
942                 *refcount_cache_size =
943                     MIN(combined_cache_size, min_refcount_cache);
944                 *l2_cache_size = combined_cache_size - *refcount_cache_size;
945             }
946         }
947     }
948 
949     /*
950      * If the L2 cache is not enough to cover the whole disk then
951      * default to 4KB entries. Smaller entries reduce the cost of
952      * loads and evictions and increase I/O performance.
953      */
954     if (*l2_cache_size < max_l2_cache && !l2_cache_entry_size_set) {
955         *l2_cache_entry_size = MIN(s->cluster_size, 4096);
956     }
957 
958     /* l2_cache_size and refcount_cache_size are ensured to have at least
959      * their minimum values in qcow2_update_options_prepare() */
960 
961     if (*l2_cache_entry_size < (1 << MIN_CLUSTER_BITS) ||
962         *l2_cache_entry_size > s->cluster_size ||
963         !is_power_of_2(*l2_cache_entry_size)) {
964         error_setg(errp, "L2 cache entry size must be a power of two "
965                    "between %d and the cluster size (%d)",
966                    1 << MIN_CLUSTER_BITS, s->cluster_size);
967         return false;
968     }
969 
970     return true;
971 }
972 
973 typedef struct Qcow2ReopenState {
974     Qcow2Cache *l2_table_cache;
975     Qcow2Cache *refcount_block_cache;
976     int l2_slice_size; /* Number of entries in a slice of the L2 table */
977     bool use_lazy_refcounts;
978     int overlap_check;
979     bool discard_passthrough[QCOW2_DISCARD_MAX];
980     bool discard_no_unref;
981     uint64_t cache_clean_interval;
982     QCryptoBlockOpenOptions *crypto_opts; /* Disk encryption runtime options */
983 } Qcow2ReopenState;
984 
985 static int GRAPH_RDLOCK
986 qcow2_update_options_prepare(BlockDriverState *bs, Qcow2ReopenState *r,
987                              QDict *options, int flags, Error **errp)
988 {
989     BDRVQcow2State *s = bs->opaque;
990     QemuOpts *opts = NULL;
991     const char *opt_overlap_check, *opt_overlap_check_template;
992     int overlap_check_template = 0;
993     uint64_t l2_cache_size, l2_cache_entry_size, refcount_cache_size;
994     int i;
995     const char *encryptfmt;
996     QDict *encryptopts = NULL;
997     int ret;
998 
999     qdict_extract_subqdict(options, &encryptopts, "encrypt.");
1000     encryptfmt = qdict_get_try_str(encryptopts, "format");
1001 
1002     opts = qemu_opts_create(&qcow2_runtime_opts, NULL, 0, &error_abort);
1003     if (!qemu_opts_absorb_qdict(opts, options, errp)) {
1004         ret = -EINVAL;
1005         goto fail;
1006     }
1007 
1008     /* get L2 table/refcount block cache size from command line options */
1009     if (!read_cache_sizes(bs, opts, &l2_cache_size, &l2_cache_entry_size,
1010                           &refcount_cache_size, errp)) {
1011         ret = -EINVAL;
1012         goto fail;
1013     }
1014 
1015     l2_cache_size /= l2_cache_entry_size;
1016     if (l2_cache_size < MIN_L2_CACHE_SIZE) {
1017         l2_cache_size = MIN_L2_CACHE_SIZE;
1018     }
1019     if (l2_cache_size > INT_MAX) {
1020         error_setg(errp, "L2 cache size too big");
1021         ret = -EINVAL;
1022         goto fail;
1023     }
1024 
1025     refcount_cache_size /= s->cluster_size;
1026     if (refcount_cache_size < MIN_REFCOUNT_CACHE_SIZE) {
1027         refcount_cache_size = MIN_REFCOUNT_CACHE_SIZE;
1028     }
1029     if (refcount_cache_size > INT_MAX) {
1030         error_setg(errp, "Refcount cache size too big");
1031         ret = -EINVAL;
1032         goto fail;
1033     }
1034 
1035     /* alloc new L2 table/refcount block cache, flush old one */
1036     if (s->l2_table_cache) {
1037         ret = qcow2_cache_flush(bs, s->l2_table_cache);
1038         if (ret) {
1039             error_setg_errno(errp, -ret, "Failed to flush the L2 table cache");
1040             goto fail;
1041         }
1042     }
1043 
1044     if (s->refcount_block_cache) {
1045         ret = qcow2_cache_flush(bs, s->refcount_block_cache);
1046         if (ret) {
1047             error_setg_errno(errp, -ret,
1048                              "Failed to flush the refcount block cache");
1049             goto fail;
1050         }
1051     }
1052 
1053     r->l2_slice_size = l2_cache_entry_size / l2_entry_size(s);
1054     r->l2_table_cache = qcow2_cache_create(bs, l2_cache_size,
1055                                            l2_cache_entry_size);
1056     r->refcount_block_cache = qcow2_cache_create(bs, refcount_cache_size,
1057                                                  s->cluster_size);
1058     if (r->l2_table_cache == NULL || r->refcount_block_cache == NULL) {
1059         error_setg(errp, "Could not allocate metadata caches");
1060         ret = -ENOMEM;
1061         goto fail;
1062     }
1063 
1064     /* New interval for cache cleanup timer */
1065     r->cache_clean_interval =
1066         qemu_opt_get_number(opts, QCOW2_OPT_CACHE_CLEAN_INTERVAL,
1067                             DEFAULT_CACHE_CLEAN_INTERVAL);
1068 #ifndef CONFIG_LINUX
1069     if (r->cache_clean_interval != 0) {
1070         error_setg(errp, QCOW2_OPT_CACHE_CLEAN_INTERVAL
1071                    " not supported on this host");
1072         ret = -EINVAL;
1073         goto fail;
1074     }
1075 #endif
1076     if (r->cache_clean_interval > UINT_MAX) {
1077         error_setg(errp, "Cache clean interval too big");
1078         ret = -EINVAL;
1079         goto fail;
1080     }
1081 
1082     /* lazy-refcounts; flush if going from enabled to disabled */
1083     r->use_lazy_refcounts = qemu_opt_get_bool(opts, QCOW2_OPT_LAZY_REFCOUNTS,
1084         (s->compatible_features & QCOW2_COMPAT_LAZY_REFCOUNTS));
1085     if (r->use_lazy_refcounts && s->qcow_version < 3) {
1086         error_setg(errp, "Lazy refcounts require a qcow2 image with at least "
1087                    "qemu 1.1 compatibility level");
1088         ret = -EINVAL;
1089         goto fail;
1090     }
1091 
1092     if (s->use_lazy_refcounts && !r->use_lazy_refcounts) {
1093         ret = qcow2_mark_clean(bs);
1094         if (ret < 0) {
1095             error_setg_errno(errp, -ret, "Failed to disable lazy refcounts");
1096             goto fail;
1097         }
1098     }
1099 
1100     /* Overlap check options */
1101     opt_overlap_check = qemu_opt_get(opts, QCOW2_OPT_OVERLAP);
1102     opt_overlap_check_template = qemu_opt_get(opts, QCOW2_OPT_OVERLAP_TEMPLATE);
1103     if (opt_overlap_check_template && opt_overlap_check &&
1104         strcmp(opt_overlap_check_template, opt_overlap_check))
1105     {
1106         error_setg(errp, "Conflicting values for qcow2 options '"
1107                    QCOW2_OPT_OVERLAP "' ('%s') and '" QCOW2_OPT_OVERLAP_TEMPLATE
1108                    "' ('%s')", opt_overlap_check, opt_overlap_check_template);
1109         ret = -EINVAL;
1110         goto fail;
1111     }
1112     if (!opt_overlap_check) {
1113         opt_overlap_check = opt_overlap_check_template ?: "cached";
1114     }
1115 
1116     if (!strcmp(opt_overlap_check, "none")) {
1117         overlap_check_template = 0;
1118     } else if (!strcmp(opt_overlap_check, "constant")) {
1119         overlap_check_template = QCOW2_OL_CONSTANT;
1120     } else if (!strcmp(opt_overlap_check, "cached")) {
1121         overlap_check_template = QCOW2_OL_CACHED;
1122     } else if (!strcmp(opt_overlap_check, "all")) {
1123         overlap_check_template = QCOW2_OL_ALL;
1124     } else {
1125         error_setg(errp, "Unsupported value '%s' for qcow2 option "
1126                    "'overlap-check'. Allowed are any of the following: "
1127                    "none, constant, cached, all", opt_overlap_check);
1128         ret = -EINVAL;
1129         goto fail;
1130     }
1131 
1132     r->overlap_check = 0;
1133     for (i = 0; i < QCOW2_OL_MAX_BITNR; i++) {
1134         /* overlap-check defines a template bitmask, but every flag may be
1135          * overwritten through the associated boolean option */
1136         r->overlap_check |=
1137             qemu_opt_get_bool(opts, overlap_bool_option_names[i],
1138                               overlap_check_template & (1 << i)) << i;
1139     }
1140 
1141     r->discard_passthrough[QCOW2_DISCARD_NEVER] = false;
1142     r->discard_passthrough[QCOW2_DISCARD_ALWAYS] = true;
1143     r->discard_passthrough[QCOW2_DISCARD_REQUEST] =
1144         qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_REQUEST,
1145                           flags & BDRV_O_UNMAP);
1146     r->discard_passthrough[QCOW2_DISCARD_SNAPSHOT] =
1147         qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_SNAPSHOT, true);
1148     r->discard_passthrough[QCOW2_DISCARD_OTHER] =
1149         qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_OTHER, false);
1150 
1151     r->discard_no_unref = qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_NO_UNREF,
1152                                             false);
1153     if (r->discard_no_unref && s->qcow_version < 3) {
1154         error_setg(errp,
1155                    "discard-no-unref is only supported since qcow2 version 3");
1156         ret = -EINVAL;
1157         goto fail;
1158     }
1159 
1160     switch (s->crypt_method_header) {
1161     case QCOW_CRYPT_NONE:
1162         if (encryptfmt) {
1163             error_setg(errp, "No encryption in image header, but options "
1164                        "specified format '%s'", encryptfmt);
1165             ret = -EINVAL;
1166             goto fail;
1167         }
1168         break;
1169 
1170     case QCOW_CRYPT_AES:
1171         if (encryptfmt && !g_str_equal(encryptfmt, "aes")) {
1172             error_setg(errp,
1173                        "Header reported 'aes' encryption format but "
1174                        "options specify '%s'", encryptfmt);
1175             ret = -EINVAL;
1176             goto fail;
1177         }
1178         qdict_put_str(encryptopts, "format", "qcow");
1179         r->crypto_opts = block_crypto_open_opts_init(encryptopts, errp);
1180         if (!r->crypto_opts) {
1181             ret = -EINVAL;
1182             goto fail;
1183         }
1184         break;
1185 
1186     case QCOW_CRYPT_LUKS:
1187         if (encryptfmt && !g_str_equal(encryptfmt, "luks")) {
1188             error_setg(errp,
1189                        "Header reported 'luks' encryption format but "
1190                        "options specify '%s'", encryptfmt);
1191             ret = -EINVAL;
1192             goto fail;
1193         }
1194         qdict_put_str(encryptopts, "format", "luks");
1195         r->crypto_opts = block_crypto_open_opts_init(encryptopts, errp);
1196         if (!r->crypto_opts) {
1197             ret = -EINVAL;
1198             goto fail;
1199         }
1200         break;
1201 
1202     default:
1203         error_setg(errp, "Unsupported encryption method %d",
1204                    s->crypt_method_header);
1205         ret = -EINVAL;
1206         goto fail;
1207     }
1208 
1209     ret = 0;
1210 fail:
1211     qobject_unref(encryptopts);
1212     qemu_opts_del(opts);
1213     opts = NULL;
1214     return ret;
1215 }
1216 
1217 static void qcow2_update_options_commit(BlockDriverState *bs,
1218                                         Qcow2ReopenState *r)
1219 {
1220     BDRVQcow2State *s = bs->opaque;
1221     int i;
1222 
1223     if (s->l2_table_cache) {
1224         qcow2_cache_destroy(s->l2_table_cache);
1225     }
1226     if (s->refcount_block_cache) {
1227         qcow2_cache_destroy(s->refcount_block_cache);
1228     }
1229     s->l2_table_cache = r->l2_table_cache;
1230     s->refcount_block_cache = r->refcount_block_cache;
1231     s->l2_slice_size = r->l2_slice_size;
1232 
1233     s->overlap_check = r->overlap_check;
1234     s->use_lazy_refcounts = r->use_lazy_refcounts;
1235 
1236     for (i = 0; i < QCOW2_DISCARD_MAX; i++) {
1237         s->discard_passthrough[i] = r->discard_passthrough[i];
1238     }
1239 
1240     s->discard_no_unref = r->discard_no_unref;
1241 
1242     if (s->cache_clean_interval != r->cache_clean_interval) {
1243         cache_clean_timer_del(bs);
1244         s->cache_clean_interval = r->cache_clean_interval;
1245         cache_clean_timer_init(bs, bdrv_get_aio_context(bs));
1246     }
1247 
1248     qapi_free_QCryptoBlockOpenOptions(s->crypto_opts);
1249     s->crypto_opts = r->crypto_opts;
1250 }
1251 
1252 static void qcow2_update_options_abort(BlockDriverState *bs,
1253                                        Qcow2ReopenState *r)
1254 {
1255     if (r->l2_table_cache) {
1256         qcow2_cache_destroy(r->l2_table_cache);
1257     }
1258     if (r->refcount_block_cache) {
1259         qcow2_cache_destroy(r->refcount_block_cache);
1260     }
1261     qapi_free_QCryptoBlockOpenOptions(r->crypto_opts);
1262 }
1263 
1264 static int coroutine_fn GRAPH_RDLOCK
1265 qcow2_update_options(BlockDriverState *bs, QDict *options, int flags,
1266                      Error **errp)
1267 {
1268     Qcow2ReopenState r = {};
1269     int ret;
1270 
1271     ret = qcow2_update_options_prepare(bs, &r, options, flags, errp);
1272     if (ret >= 0) {
1273         qcow2_update_options_commit(bs, &r);
1274     } else {
1275         qcow2_update_options_abort(bs, &r);
1276     }
1277 
1278     return ret;
1279 }
1280 
1281 static int validate_compression_type(BDRVQcow2State *s, Error **errp)
1282 {
1283     switch (s->compression_type) {
1284     case QCOW2_COMPRESSION_TYPE_ZLIB:
1285 #ifdef CONFIG_ZSTD
1286     case QCOW2_COMPRESSION_TYPE_ZSTD:
1287 #endif
1288         break;
1289 
1290     default:
1291         error_setg(errp, "qcow2: unknown compression type: %u",
1292                    s->compression_type);
1293         return -ENOTSUP;
1294     }
1295 
1296     /*
1297      * if the compression type differs from QCOW2_COMPRESSION_TYPE_ZLIB
1298      * the incompatible feature flag must be set
1299      */
1300     if (s->compression_type == QCOW2_COMPRESSION_TYPE_ZLIB) {
1301         if (s->incompatible_features & QCOW2_INCOMPAT_COMPRESSION) {
1302             error_setg(errp, "qcow2: Compression type incompatible feature "
1303                              "bit must not be set");
1304             return -EINVAL;
1305         }
1306     } else {
1307         if (!(s->incompatible_features & QCOW2_INCOMPAT_COMPRESSION)) {
1308             error_setg(errp, "qcow2: Compression type incompatible feature "
1309                              "bit must be set");
1310             return -EINVAL;
1311         }
1312     }
1313 
1314     return 0;
1315 }
1316 
1317 /* Called with s->lock held.  */
1318 static int coroutine_fn GRAPH_RDLOCK
1319 qcow2_do_open(BlockDriverState *bs, QDict *options, int flags,
1320               bool open_data_file, Error **errp)
1321 {
1322     ERRP_GUARD();
1323     BDRVQcow2State *s = bs->opaque;
1324     unsigned int len, i;
1325     int ret = 0;
1326     QCowHeader header;
1327     uint64_t ext_end;
1328     uint64_t l1_vm_state_index;
1329     bool update_header = false;
1330 
1331     ret = bdrv_co_pread(bs->file, 0, sizeof(header), &header, 0);
1332     if (ret < 0) {
1333         error_setg_errno(errp, -ret, "Could not read qcow2 header");
1334         goto fail;
1335     }
1336     header.magic = be32_to_cpu(header.magic);
1337     header.version = be32_to_cpu(header.version);
1338     header.backing_file_offset = be64_to_cpu(header.backing_file_offset);
1339     header.backing_file_size = be32_to_cpu(header.backing_file_size);
1340     header.size = be64_to_cpu(header.size);
1341     header.cluster_bits = be32_to_cpu(header.cluster_bits);
1342     header.crypt_method = be32_to_cpu(header.crypt_method);
1343     header.l1_table_offset = be64_to_cpu(header.l1_table_offset);
1344     header.l1_size = be32_to_cpu(header.l1_size);
1345     header.refcount_table_offset = be64_to_cpu(header.refcount_table_offset);
1346     header.refcount_table_clusters =
1347         be32_to_cpu(header.refcount_table_clusters);
1348     header.snapshots_offset = be64_to_cpu(header.snapshots_offset);
1349     header.nb_snapshots = be32_to_cpu(header.nb_snapshots);
1350 
1351     if (header.magic != QCOW_MAGIC) {
1352         error_setg(errp, "Image is not in qcow2 format");
1353         ret = -EINVAL;
1354         goto fail;
1355     }
1356     if (header.version < 2 || header.version > 3) {
1357         error_setg(errp, "Unsupported qcow2 version %" PRIu32, header.version);
1358         ret = -ENOTSUP;
1359         goto fail;
1360     }
1361 
1362     s->qcow_version = header.version;
1363 
1364     /* Initialise cluster size */
1365     if (header.cluster_bits < MIN_CLUSTER_BITS ||
1366         header.cluster_bits > MAX_CLUSTER_BITS) {
1367         error_setg(errp, "Unsupported cluster size: 2^%" PRIu32,
1368                    header.cluster_bits);
1369         ret = -EINVAL;
1370         goto fail;
1371     }
1372 
1373     s->cluster_bits = header.cluster_bits;
1374     s->cluster_size = 1 << s->cluster_bits;
1375 
1376     /* Initialise version 3 header fields */
1377     if (header.version == 2) {
1378         header.incompatible_features    = 0;
1379         header.compatible_features      = 0;
1380         header.autoclear_features       = 0;
1381         header.refcount_order           = 4;
1382         header.header_length            = 72;
1383     } else {
1384         header.incompatible_features =
1385             be64_to_cpu(header.incompatible_features);
1386         header.compatible_features = be64_to_cpu(header.compatible_features);
1387         header.autoclear_features = be64_to_cpu(header.autoclear_features);
1388         header.refcount_order = be32_to_cpu(header.refcount_order);
1389         header.header_length = be32_to_cpu(header.header_length);
1390 
1391         if (header.header_length < 104) {
1392             error_setg(errp, "qcow2 header too short");
1393             ret = -EINVAL;
1394             goto fail;
1395         }
1396     }
1397 
1398     if (header.header_length > s->cluster_size) {
1399         error_setg(errp, "qcow2 header exceeds cluster size");
1400         ret = -EINVAL;
1401         goto fail;
1402     }
1403 
1404     if (header.header_length > sizeof(header)) {
1405         s->unknown_header_fields_size = header.header_length - sizeof(header);
1406         s->unknown_header_fields = g_malloc(s->unknown_header_fields_size);
1407         ret = bdrv_co_pread(bs->file, sizeof(header),
1408                             s->unknown_header_fields_size,
1409                             s->unknown_header_fields, 0);
1410         if (ret < 0) {
1411             error_setg_errno(errp, -ret, "Could not read unknown qcow2 header "
1412                              "fields");
1413             goto fail;
1414         }
1415     }
1416 
1417     if (header.backing_file_offset > s->cluster_size) {
1418         error_setg(errp, "Invalid backing file offset");
1419         ret = -EINVAL;
1420         goto fail;
1421     }
1422 
1423     if (header.backing_file_offset) {
1424         ext_end = header.backing_file_offset;
1425     } else {
1426         ext_end = 1 << header.cluster_bits;
1427     }
1428 
1429     /* Handle feature bits */
1430     s->incompatible_features    = header.incompatible_features;
1431     s->compatible_features      = header.compatible_features;
1432     s->autoclear_features       = header.autoclear_features;
1433 
1434     /*
1435      * Handle compression type
1436      * Older qcow2 images don't contain the compression type header.
1437      * Distinguish them by the header length and use
1438      * the only valid (default) compression type in that case
1439      */
1440     if (header.header_length > offsetof(QCowHeader, compression_type)) {
1441         s->compression_type = header.compression_type;
1442     } else {
1443         s->compression_type = QCOW2_COMPRESSION_TYPE_ZLIB;
1444     }
1445 
1446     ret = validate_compression_type(s, errp);
1447     if (ret) {
1448         goto fail;
1449     }
1450 
1451     if (s->incompatible_features & ~QCOW2_INCOMPAT_MASK) {
1452         void *feature_table = NULL;
1453         qcow2_read_extensions(bs, header.header_length, ext_end,
1454                               &feature_table, flags, NULL, NULL);
1455         report_unsupported_feature(errp, feature_table,
1456                                    s->incompatible_features &
1457                                    ~QCOW2_INCOMPAT_MASK);
1458         ret = -ENOTSUP;
1459         g_free(feature_table);
1460         goto fail;
1461     }
1462 
1463     if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
1464         /* Corrupt images may not be written to unless they are being repaired
1465          */
1466         if ((flags & BDRV_O_RDWR) && !(flags & BDRV_O_CHECK)) {
1467             error_setg(errp, "qcow2: Image is corrupt; cannot be opened "
1468                        "read/write");
1469             ret = -EACCES;
1470             goto fail;
1471         }
1472     }
1473 
1474     s->subclusters_per_cluster =
1475         has_subclusters(s) ? QCOW_EXTL2_SUBCLUSTERS_PER_CLUSTER : 1;
1476     s->subcluster_size = s->cluster_size / s->subclusters_per_cluster;
1477     s->subcluster_bits = ctz32(s->subcluster_size);
1478 
1479     if (s->subcluster_size < (1 << MIN_CLUSTER_BITS)) {
1480         error_setg(errp, "Unsupported subcluster size: %d", s->subcluster_size);
1481         ret = -EINVAL;
1482         goto fail;
1483     }
1484 
1485     /* Check support for various header values */
1486     if (header.refcount_order > 6) {
1487         error_setg(errp, "Reference count entry width too large; may not "
1488                    "exceed 64 bits");
1489         ret = -EINVAL;
1490         goto fail;
1491     }
1492     s->refcount_order = header.refcount_order;
1493     s->refcount_bits = 1 << s->refcount_order;
1494     s->refcount_max = UINT64_C(1) << (s->refcount_bits - 1);
1495     s->refcount_max += s->refcount_max - 1;
1496 
1497     s->crypt_method_header = header.crypt_method;
1498     if (s->crypt_method_header) {
1499         if (bdrv_uses_whitelist() &&
1500             s->crypt_method_header == QCOW_CRYPT_AES) {
1501             error_setg(errp,
1502                        "Use of AES-CBC encrypted qcow2 images is no longer "
1503                        "supported in system emulators");
1504             error_append_hint(errp,
1505                               "You can use 'qemu-img convert' to convert your "
1506                               "image to an alternative supported format, such "
1507                               "as unencrypted qcow2, or raw with the LUKS "
1508                               "format instead.\n");
1509             ret = -ENOSYS;
1510             goto fail;
1511         }
1512 
1513         if (s->crypt_method_header == QCOW_CRYPT_AES) {
1514             s->crypt_physical_offset = false;
1515         } else {
1516             /* Assuming LUKS and any future crypt methods we
1517              * add will all use physical offsets, due to the
1518              * fact that the alternative is insecure...  */
1519             s->crypt_physical_offset = true;
1520         }
1521 
1522         bs->encrypted = true;
1523     }
1524 
1525     s->l2_bits = s->cluster_bits - ctz32(l2_entry_size(s));
1526     s->l2_size = 1 << s->l2_bits;
1527     /* 2^(s->refcount_order - 3) is the refcount width in bytes */
1528     s->refcount_block_bits = s->cluster_bits - (s->refcount_order - 3);
1529     s->refcount_block_size = 1 << s->refcount_block_bits;
1530     bs->total_sectors = header.size / BDRV_SECTOR_SIZE;
1531     s->csize_shift = (62 - (s->cluster_bits - 8));
1532     s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;
1533     s->cluster_offset_mask = (1LL << s->csize_shift) - 1;
1534 
1535     s->refcount_table_offset = header.refcount_table_offset;
1536     s->refcount_table_size =
1537         header.refcount_table_clusters << (s->cluster_bits - 3);
1538 
1539     if (header.refcount_table_clusters == 0 && !(flags & BDRV_O_CHECK)) {
1540         error_setg(errp, "Image does not contain a reference count table");
1541         ret = -EINVAL;
1542         goto fail;
1543     }
1544 
1545     ret = qcow2_validate_table(bs, s->refcount_table_offset,
1546                                header.refcount_table_clusters,
1547                                s->cluster_size, QCOW_MAX_REFTABLE_SIZE,
1548                                "Reference count table", errp);
1549     if (ret < 0) {
1550         goto fail;
1551     }
1552 
1553     if (!(flags & BDRV_O_CHECK)) {
1554         /*
1555          * The total size in bytes of the snapshot table is checked in
1556          * qcow2_read_snapshots() because the size of each snapshot is
1557          * variable and we don't know it yet.
1558          * Here we only check the offset and number of snapshots.
1559          */
1560         ret = qcow2_validate_table(bs, header.snapshots_offset,
1561                                    header.nb_snapshots,
1562                                    sizeof(QCowSnapshotHeader),
1563                                    sizeof(QCowSnapshotHeader) *
1564                                        QCOW_MAX_SNAPSHOTS,
1565                                    "Snapshot table", errp);
1566         if (ret < 0) {
1567             goto fail;
1568         }
1569     }
1570 
1571     /* read the level 1 table */
1572     ret = qcow2_validate_table(bs, header.l1_table_offset,
1573                                header.l1_size, L1E_SIZE,
1574                                QCOW_MAX_L1_SIZE, "Active L1 table", errp);
1575     if (ret < 0) {
1576         goto fail;
1577     }
1578     s->l1_size = header.l1_size;
1579     s->l1_table_offset = header.l1_table_offset;
1580 
1581     l1_vm_state_index = size_to_l1(s, header.size);
1582     if (l1_vm_state_index > INT_MAX) {
1583         error_setg(errp, "Image is too big");
1584         ret = -EFBIG;
1585         goto fail;
1586     }
1587     s->l1_vm_state_index = l1_vm_state_index;
1588 
1589     /* the L1 table must contain at least enough entries to put
1590        header.size bytes */
1591     if (s->l1_size < s->l1_vm_state_index) {
1592         error_setg(errp, "L1 table is too small");
1593         ret = -EINVAL;
1594         goto fail;
1595     }
1596 
1597     if (s->l1_size > 0) {
1598         s->l1_table = qemu_try_blockalign(bs->file->bs, s->l1_size * L1E_SIZE);
1599         if (s->l1_table == NULL) {
1600             error_setg(errp, "Could not allocate L1 table");
1601             ret = -ENOMEM;
1602             goto fail;
1603         }
1604         ret = bdrv_co_pread(bs->file, s->l1_table_offset, s->l1_size * L1E_SIZE,
1605                             s->l1_table, 0);
1606         if (ret < 0) {
1607             error_setg_errno(errp, -ret, "Could not read L1 table");
1608             goto fail;
1609         }
1610         for(i = 0;i < s->l1_size; i++) {
1611             s->l1_table[i] = be64_to_cpu(s->l1_table[i]);
1612         }
1613     }
1614 
1615     /* Parse driver-specific options */
1616     ret = qcow2_update_options(bs, options, flags, errp);
1617     if (ret < 0) {
1618         goto fail;
1619     }
1620 
1621     s->flags = flags;
1622 
1623     ret = qcow2_refcount_init(bs);
1624     if (ret != 0) {
1625         error_setg_errno(errp, -ret, "Could not initialize refcount handling");
1626         goto fail;
1627     }
1628 
1629     QLIST_INIT(&s->cluster_allocs);
1630     QTAILQ_INIT(&s->discards);
1631 
1632     /* read qcow2 extensions */
1633     if (qcow2_read_extensions(bs, header.header_length, ext_end, NULL,
1634                               flags, &update_header, errp)) {
1635         ret = -EINVAL;
1636         goto fail;
1637     }
1638 
1639     if (open_data_file) {
1640         /* Open external data file */
1641         bdrv_graph_co_rdunlock();
1642         s->data_file = bdrv_co_open_child(NULL, options, "data-file", bs,
1643                                           &child_of_bds, BDRV_CHILD_DATA,
1644                                           true, errp);
1645         bdrv_graph_co_rdlock();
1646         if (*errp) {
1647             ret = -EINVAL;
1648             goto fail;
1649         }
1650 
1651         if (s->incompatible_features & QCOW2_INCOMPAT_DATA_FILE) {
1652             if (!s->data_file && s->image_data_file) {
1653                 bdrv_graph_co_rdunlock();
1654                 s->data_file = bdrv_co_open_child(s->image_data_file, options,
1655                                                   "data-file", bs,
1656                                                   &child_of_bds,
1657                                                   BDRV_CHILD_DATA, false, errp);
1658                 bdrv_graph_co_rdlock();
1659                 if (!s->data_file) {
1660                     ret = -EINVAL;
1661                     goto fail;
1662                 }
1663             }
1664             if (!s->data_file) {
1665                 error_setg(errp, "'data-file' is required for this image");
1666                 ret = -EINVAL;
1667                 goto fail;
1668             }
1669 
1670             /* No data here */
1671             bs->file->role &= ~BDRV_CHILD_DATA;
1672 
1673             /* Must succeed because we have given up permissions if anything */
1674             bdrv_child_refresh_perms(bs, bs->file, &error_abort);
1675         } else {
1676             if (s->data_file) {
1677                 error_setg(errp, "'data-file' can only be set for images with "
1678                                  "an external data file");
1679                 ret = -EINVAL;
1680                 goto fail;
1681             }
1682 
1683             s->data_file = bs->file;
1684 
1685             if (data_file_is_raw(bs)) {
1686                 error_setg(errp, "data-file-raw requires a data file");
1687                 ret = -EINVAL;
1688                 goto fail;
1689             }
1690         }
1691     }
1692 
1693     /* qcow2_read_extension may have set up the crypto context
1694      * if the crypt method needs a header region, some methods
1695      * don't need header extensions, so must check here
1696      */
1697     if (s->crypt_method_header && !s->crypto) {
1698         if (s->crypt_method_header == QCOW_CRYPT_AES) {
1699             unsigned int cflags = 0;
1700             if (flags & BDRV_O_NO_IO) {
1701                 cflags |= QCRYPTO_BLOCK_OPEN_NO_IO;
1702             }
1703             s->crypto = qcrypto_block_open(s->crypto_opts, "encrypt.",
1704                                            NULL, NULL, cflags, errp);
1705             if (!s->crypto) {
1706                 ret = -EINVAL;
1707                 goto fail;
1708             }
1709         } else if (!(flags & BDRV_O_NO_IO)) {
1710             error_setg(errp, "Missing CRYPTO header for crypt method %d",
1711                        s->crypt_method_header);
1712             ret = -EINVAL;
1713             goto fail;
1714         }
1715     }
1716 
1717     /* read the backing file name */
1718     if (header.backing_file_offset != 0) {
1719         len = header.backing_file_size;
1720         if (len > MIN(1023, s->cluster_size - header.backing_file_offset) ||
1721             len >= sizeof(bs->backing_file)) {
1722             error_setg(errp, "Backing file name too long");
1723             ret = -EINVAL;
1724             goto fail;
1725         }
1726 
1727         s->image_backing_file = g_malloc(len + 1);
1728         ret = bdrv_co_pread(bs->file, header.backing_file_offset, len,
1729                             s->image_backing_file, 0);
1730         if (ret < 0) {
1731             error_setg_errno(errp, -ret, "Could not read backing file name");
1732             goto fail;
1733         }
1734         s->image_backing_file[len] = '\0';
1735 
1736         /*
1737          * Update only when something has changed.  This function is called by
1738          * qcow2_co_invalidate_cache(), and we do not want to reset
1739          * auto_backing_file unless necessary.
1740          */
1741         if (!g_str_equal(s->image_backing_file, bs->backing_file)) {
1742             pstrcpy(bs->backing_file, sizeof(bs->backing_file),
1743                     s->image_backing_file);
1744             pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
1745                     s->image_backing_file);
1746         }
1747     }
1748 
1749     /*
1750      * Internal snapshots; skip reading them in check mode, because
1751      * we do not need them then, and we do not want to abort because
1752      * of a broken table.
1753      */
1754     if (!(flags & BDRV_O_CHECK)) {
1755         s->snapshots_offset = header.snapshots_offset;
1756         s->nb_snapshots = header.nb_snapshots;
1757 
1758         ret = qcow2_read_snapshots(bs, errp);
1759         if (ret < 0) {
1760             goto fail;
1761         }
1762     }
1763 
1764     /* Clear unknown autoclear feature bits */
1765     update_header |= s->autoclear_features & ~QCOW2_AUTOCLEAR_MASK;
1766     update_header = update_header && bdrv_is_writable(bs);
1767     if (update_header) {
1768         s->autoclear_features &= QCOW2_AUTOCLEAR_MASK;
1769     }
1770 
1771     /* == Handle persistent dirty bitmaps ==
1772      *
1773      * We want load dirty bitmaps in three cases:
1774      *
1775      * 1. Normal open of the disk in active mode, not related to invalidation
1776      *    after migration.
1777      *
1778      * 2. Invalidation of the target vm after pre-copy phase of migration, if
1779      *    bitmaps are _not_ migrating through migration channel, i.e.
1780      *    'dirty-bitmaps' capability is disabled.
1781      *
1782      * 3. Invalidation of source vm after failed or canceled migration.
1783      *    This is a very interesting case. There are two possible types of
1784      *    bitmaps:
1785      *
1786      *    A. Stored on inactivation and removed. They should be loaded from the
1787      *       image.
1788      *
1789      *    B. Not stored: not-persistent bitmaps and bitmaps, migrated through
1790      *       the migration channel (with dirty-bitmaps capability).
1791      *
1792      *    On the other hand, there are two possible sub-cases:
1793      *
1794      *    3.1 disk was changed by somebody else while were inactive. In this
1795      *        case all in-RAM dirty bitmaps (both persistent and not) are
1796      *        definitely invalid. And we don't have any method to determine
1797      *        this.
1798      *
1799      *        Simple and safe thing is to just drop all the bitmaps of type B on
1800      *        inactivation. But in this case we lose bitmaps in valid 4.2 case.
1801      *
1802      *        On the other hand, resuming source vm, if disk was already changed
1803      *        is a bad thing anyway: not only bitmaps, the whole vm state is
1804      *        out of sync with disk.
1805      *
1806      *        This means, that user or management tool, who for some reason
1807      *        decided to resume source vm, after disk was already changed by
1808      *        target vm, should at least drop all dirty bitmaps by hand.
1809      *
1810      *        So, we can ignore this case for now, but TODO: "generation"
1811      *        extension for qcow2, to determine, that image was changed after
1812      *        last inactivation. And if it is changed, we will drop (or at least
1813      *        mark as 'invalid' all the bitmaps of type B, both persistent
1814      *        and not).
1815      *
1816      *    3.2 disk was _not_ changed while were inactive. Bitmaps may be saved
1817      *        to disk ('dirty-bitmaps' capability disabled), or not saved
1818      *        ('dirty-bitmaps' capability enabled), but we don't need to care
1819      *        of: let's load bitmaps as always: stored bitmaps will be loaded,
1820      *        and not stored has flag IN_USE=1 in the image and will be skipped
1821      *        on loading.
1822      *
1823      * One remaining possible case when we don't want load bitmaps:
1824      *
1825      * 4. Open disk in inactive mode in target vm (bitmaps are migrating or
1826      *    will be loaded on invalidation, no needs try loading them before)
1827      */
1828 
1829     if (!(bdrv_get_flags(bs) & BDRV_O_INACTIVE)) {
1830         /* It's case 1, 2 or 3.2. Or 3.1 which is BUG in management layer. */
1831         bool header_updated;
1832         if (!qcow2_load_dirty_bitmaps(bs, &header_updated, errp)) {
1833             ret = -EINVAL;
1834             goto fail;
1835         }
1836 
1837         update_header = update_header && !header_updated;
1838     }
1839 
1840     if (update_header) {
1841         ret = qcow2_update_header(bs);
1842         if (ret < 0) {
1843             error_setg_errno(errp, -ret, "Could not update qcow2 header");
1844             goto fail;
1845         }
1846     }
1847 
1848     bs->supported_zero_flags = header.version >= 3 ?
1849                                BDRV_REQ_MAY_UNMAP | BDRV_REQ_NO_FALLBACK : 0;
1850     bs->supported_truncate_flags = BDRV_REQ_ZERO_WRITE;
1851 
1852     /* Repair image if dirty */
1853     if (!(flags & BDRV_O_CHECK) && bdrv_is_writable(bs) &&
1854         (s->incompatible_features & QCOW2_INCOMPAT_DIRTY)) {
1855         BdrvCheckResult result = {0};
1856 
1857         ret = qcow2_co_check_locked(bs, &result,
1858                                     BDRV_FIX_ERRORS | BDRV_FIX_LEAKS);
1859         if (ret < 0 || result.check_errors) {
1860             if (ret >= 0) {
1861                 ret = -EIO;
1862             }
1863             error_setg_errno(errp, -ret, "Could not repair dirty image");
1864             goto fail;
1865         }
1866     }
1867 
1868 #ifdef DEBUG_ALLOC
1869     {
1870         BdrvCheckResult result = {0};
1871         qcow2_check_refcounts(bs, &result, 0);
1872     }
1873 #endif
1874 
1875     qemu_co_queue_init(&s->thread_task_queue);
1876 
1877     return ret;
1878 
1879  fail:
1880     g_free(s->image_data_file);
1881     if (open_data_file && has_data_file(bs)) {
1882         bdrv_graph_co_rdunlock();
1883         bdrv_co_unref_child(bs, s->data_file);
1884         bdrv_graph_co_rdlock();
1885         s->data_file = NULL;
1886     }
1887     g_free(s->unknown_header_fields);
1888     cleanup_unknown_header_ext(bs);
1889     qcow2_free_snapshots(bs);
1890     qcow2_refcount_close(bs);
1891     qemu_vfree(s->l1_table);
1892     /* else pre-write overlap checks in cache_destroy may crash */
1893     s->l1_table = NULL;
1894     cache_clean_timer_del(bs);
1895     if (s->l2_table_cache) {
1896         qcow2_cache_destroy(s->l2_table_cache);
1897     }
1898     if (s->refcount_block_cache) {
1899         qcow2_cache_destroy(s->refcount_block_cache);
1900     }
1901     qcrypto_block_free(s->crypto);
1902     qapi_free_QCryptoBlockOpenOptions(s->crypto_opts);
1903     return ret;
1904 }
1905 
1906 typedef struct QCow2OpenCo {
1907     BlockDriverState *bs;
1908     QDict *options;
1909     int flags;
1910     Error **errp;
1911     int ret;
1912 } QCow2OpenCo;
1913 
1914 static void coroutine_fn qcow2_open_entry(void *opaque)
1915 {
1916     QCow2OpenCo *qoc = opaque;
1917     BDRVQcow2State *s = qoc->bs->opaque;
1918 
1919     GRAPH_RDLOCK_GUARD();
1920 
1921     qemu_co_mutex_lock(&s->lock);
1922     qoc->ret = qcow2_do_open(qoc->bs, qoc->options, qoc->flags, true,
1923                              qoc->errp);
1924     qemu_co_mutex_unlock(&s->lock);
1925 
1926     aio_wait_kick();
1927 }
1928 
1929 static int qcow2_open(BlockDriverState *bs, QDict *options, int flags,
1930                       Error **errp)
1931 {
1932     BDRVQcow2State *s = bs->opaque;
1933     QCow2OpenCo qoc = {
1934         .bs = bs,
1935         .options = options,
1936         .flags = flags,
1937         .errp = errp,
1938         .ret = -EINPROGRESS
1939     };
1940     int ret;
1941 
1942     ret = bdrv_open_file_child(NULL, options, "file", bs, errp);
1943     if (ret < 0) {
1944         return ret;
1945     }
1946 
1947     /* Initialise locks */
1948     qemu_co_mutex_init(&s->lock);
1949 
1950     assert(!qemu_in_coroutine());
1951     assert(qemu_get_current_aio_context() == qemu_get_aio_context());
1952 
1953     aio_co_enter(bdrv_get_aio_context(bs),
1954                  qemu_coroutine_create(qcow2_open_entry, &qoc));
1955     AIO_WAIT_WHILE_UNLOCKED(NULL, qoc.ret == -EINPROGRESS);
1956 
1957     return qoc.ret;
1958 }
1959 
1960 static void qcow2_refresh_limits(BlockDriverState *bs, Error **errp)
1961 {
1962     BDRVQcow2State *s = bs->opaque;
1963 
1964     if (bs->encrypted) {
1965         /* Encryption works on a sector granularity */
1966         bs->bl.request_alignment = qcrypto_block_get_sector_size(s->crypto);
1967     }
1968     bs->bl.pwrite_zeroes_alignment = s->subcluster_size;
1969     bs->bl.pdiscard_alignment = s->cluster_size;
1970 }
1971 
1972 static int GRAPH_UNLOCKED
1973 qcow2_reopen_prepare(BDRVReopenState *state,BlockReopenQueue *queue,
1974                      Error **errp)
1975 {
1976     BDRVQcow2State *s = state->bs->opaque;
1977     Qcow2ReopenState *r;
1978     int ret;
1979 
1980     GLOBAL_STATE_CODE();
1981     GRAPH_RDLOCK_GUARD_MAINLOOP();
1982 
1983     r = g_new0(Qcow2ReopenState, 1);
1984     state->opaque = r;
1985 
1986     ret = qcow2_update_options_prepare(state->bs, r, state->options,
1987                                        state->flags, errp);
1988     if (ret < 0) {
1989         goto fail;
1990     }
1991 
1992     /* We need to write out any unwritten data if we reopen read-only. */
1993     if ((state->flags & BDRV_O_RDWR) == 0) {
1994         ret = qcow2_reopen_bitmaps_ro(state->bs, errp);
1995         if (ret < 0) {
1996             goto fail;
1997         }
1998 
1999         ret = bdrv_flush(state->bs);
2000         if (ret < 0) {
2001             goto fail;
2002         }
2003 
2004         ret = qcow2_mark_clean(state->bs);
2005         if (ret < 0) {
2006             goto fail;
2007         }
2008     }
2009 
2010     /*
2011      * Without an external data file, s->data_file points to the same BdrvChild
2012      * as bs->file. It needs to be resynced after reopen because bs->file may
2013      * be changed. We can't use it in the meantime.
2014      */
2015     if (!has_data_file(state->bs)) {
2016         assert(s->data_file == state->bs->file);
2017         s->data_file = NULL;
2018     }
2019 
2020     return 0;
2021 
2022 fail:
2023     qcow2_update_options_abort(state->bs, r);
2024     g_free(r);
2025     return ret;
2026 }
2027 
2028 static void qcow2_reopen_commit(BDRVReopenState *state)
2029 {
2030     BDRVQcow2State *s = state->bs->opaque;
2031 
2032     GRAPH_RDLOCK_GUARD_MAINLOOP();
2033 
2034     qcow2_update_options_commit(state->bs, state->opaque);
2035     if (!s->data_file) {
2036         /*
2037          * If we don't have an external data file, s->data_file was cleared by
2038          * qcow2_reopen_prepare() and needs to be updated.
2039          */
2040         s->data_file = state->bs->file;
2041     }
2042     g_free(state->opaque);
2043 }
2044 
2045 static void qcow2_reopen_commit_post(BDRVReopenState *state)
2046 {
2047     GRAPH_RDLOCK_GUARD_MAINLOOP();
2048 
2049     if (state->flags & BDRV_O_RDWR) {
2050         Error *local_err = NULL;
2051 
2052         if (qcow2_reopen_bitmaps_rw(state->bs, &local_err) < 0) {
2053             /*
2054              * This is not fatal, bitmaps just left read-only, so all following
2055              * writes will fail. User can remove read-only bitmaps to unblock
2056              * writes or retry reopen.
2057              */
2058             error_reportf_err(local_err,
2059                               "%s: Failed to make dirty bitmaps writable: ",
2060                               bdrv_get_node_name(state->bs));
2061         }
2062     }
2063 }
2064 
2065 static void qcow2_reopen_abort(BDRVReopenState *state)
2066 {
2067     BDRVQcow2State *s = state->bs->opaque;
2068 
2069     GRAPH_RDLOCK_GUARD_MAINLOOP();
2070 
2071     if (!s->data_file) {
2072         /*
2073          * If we don't have an external data file, s->data_file was cleared by
2074          * qcow2_reopen_prepare() and needs to be restored.
2075          */
2076         s->data_file = state->bs->file;
2077     }
2078     qcow2_update_options_abort(state->bs, state->opaque);
2079     g_free(state->opaque);
2080 }
2081 
2082 static void qcow2_join_options(QDict *options, QDict *old_options)
2083 {
2084     bool has_new_overlap_template =
2085         qdict_haskey(options, QCOW2_OPT_OVERLAP) ||
2086         qdict_haskey(options, QCOW2_OPT_OVERLAP_TEMPLATE);
2087     bool has_new_total_cache_size =
2088         qdict_haskey(options, QCOW2_OPT_CACHE_SIZE);
2089     bool has_all_cache_options;
2090 
2091     /* New overlap template overrides all old overlap options */
2092     if (has_new_overlap_template) {
2093         qdict_del(old_options, QCOW2_OPT_OVERLAP);
2094         qdict_del(old_options, QCOW2_OPT_OVERLAP_TEMPLATE);
2095         qdict_del(old_options, QCOW2_OPT_OVERLAP_MAIN_HEADER);
2096         qdict_del(old_options, QCOW2_OPT_OVERLAP_ACTIVE_L1);
2097         qdict_del(old_options, QCOW2_OPT_OVERLAP_ACTIVE_L2);
2098         qdict_del(old_options, QCOW2_OPT_OVERLAP_REFCOUNT_TABLE);
2099         qdict_del(old_options, QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK);
2100         qdict_del(old_options, QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE);
2101         qdict_del(old_options, QCOW2_OPT_OVERLAP_INACTIVE_L1);
2102         qdict_del(old_options, QCOW2_OPT_OVERLAP_INACTIVE_L2);
2103     }
2104 
2105     /* New total cache size overrides all old options */
2106     if (qdict_haskey(options, QCOW2_OPT_CACHE_SIZE)) {
2107         qdict_del(old_options, QCOW2_OPT_L2_CACHE_SIZE);
2108         qdict_del(old_options, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
2109     }
2110 
2111     qdict_join(options, old_options, false);
2112 
2113     /*
2114      * If after merging all cache size options are set, an old total size is
2115      * overwritten. Do keep all options, however, if all three are new. The
2116      * resulting error message is what we want to happen.
2117      */
2118     has_all_cache_options =
2119         qdict_haskey(options, QCOW2_OPT_CACHE_SIZE) ||
2120         qdict_haskey(options, QCOW2_OPT_L2_CACHE_SIZE) ||
2121         qdict_haskey(options, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
2122 
2123     if (has_all_cache_options && !has_new_total_cache_size) {
2124         qdict_del(options, QCOW2_OPT_CACHE_SIZE);
2125     }
2126 }
2127 
2128 static int coroutine_fn GRAPH_RDLOCK
2129 qcow2_co_block_status(BlockDriverState *bs, bool want_zero, int64_t offset,
2130                       int64_t count, int64_t *pnum, int64_t *map,
2131                       BlockDriverState **file)
2132 {
2133     BDRVQcow2State *s = bs->opaque;
2134     uint64_t host_offset;
2135     unsigned int bytes;
2136     QCow2SubclusterType type;
2137     int ret, status = 0;
2138 
2139     qemu_co_mutex_lock(&s->lock);
2140 
2141     if (!s->metadata_preallocation_checked) {
2142         ret = qcow2_detect_metadata_preallocation(bs);
2143         s->metadata_preallocation = (ret == 1);
2144         s->metadata_preallocation_checked = true;
2145     }
2146 
2147     bytes = MIN(INT_MAX, count);
2148     ret = qcow2_get_host_offset(bs, offset, &bytes, &host_offset, &type);
2149     qemu_co_mutex_unlock(&s->lock);
2150     if (ret < 0) {
2151         return ret;
2152     }
2153 
2154     *pnum = bytes;
2155 
2156     if ((type == QCOW2_SUBCLUSTER_NORMAL ||
2157          type == QCOW2_SUBCLUSTER_ZERO_ALLOC ||
2158          type == QCOW2_SUBCLUSTER_UNALLOCATED_ALLOC) && !s->crypto) {
2159         *map = host_offset;
2160         *file = s->data_file->bs;
2161         status |= BDRV_BLOCK_OFFSET_VALID;
2162     }
2163     if (type == QCOW2_SUBCLUSTER_ZERO_PLAIN ||
2164         type == QCOW2_SUBCLUSTER_ZERO_ALLOC) {
2165         status |= BDRV_BLOCK_ZERO;
2166     } else if (type != QCOW2_SUBCLUSTER_UNALLOCATED_PLAIN &&
2167                type != QCOW2_SUBCLUSTER_UNALLOCATED_ALLOC) {
2168         status |= BDRV_BLOCK_DATA;
2169     }
2170     if (s->metadata_preallocation && (status & BDRV_BLOCK_DATA) &&
2171         (status & BDRV_BLOCK_OFFSET_VALID))
2172     {
2173         status |= BDRV_BLOCK_RECURSE;
2174     }
2175     if (type == QCOW2_SUBCLUSTER_COMPRESSED) {
2176         status |= BDRV_BLOCK_COMPRESSED;
2177     }
2178     return status;
2179 }
2180 
2181 static int coroutine_fn GRAPH_RDLOCK
2182 qcow2_handle_l2meta(BlockDriverState *bs, QCowL2Meta **pl2meta, bool link_l2)
2183 {
2184     int ret = 0;
2185     QCowL2Meta *l2meta = *pl2meta;
2186 
2187     while (l2meta != NULL) {
2188         QCowL2Meta *next;
2189 
2190         if (link_l2) {
2191             ret = qcow2_alloc_cluster_link_l2(bs, l2meta);
2192             if (ret) {
2193                 goto out;
2194             }
2195         } else {
2196             qcow2_alloc_cluster_abort(bs, l2meta);
2197         }
2198 
2199         /* Take the request off the list of running requests */
2200         QLIST_REMOVE(l2meta, next_in_flight);
2201 
2202         qemu_co_queue_restart_all(&l2meta->dependent_requests);
2203 
2204         next = l2meta->next;
2205         g_free(l2meta);
2206         l2meta = next;
2207     }
2208 out:
2209     *pl2meta = l2meta;
2210     return ret;
2211 }
2212 
2213 static int coroutine_fn GRAPH_RDLOCK
2214 qcow2_co_preadv_encrypted(BlockDriverState *bs,
2215                            uint64_t host_offset,
2216                            uint64_t offset,
2217                            uint64_t bytes,
2218                            QEMUIOVector *qiov,
2219                            uint64_t qiov_offset)
2220 {
2221     int ret;
2222     BDRVQcow2State *s = bs->opaque;
2223     uint8_t *buf;
2224 
2225     assert(bs->encrypted && s->crypto);
2226     assert(bytes <= QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
2227 
2228     /*
2229      * For encrypted images, read everything into a temporary
2230      * contiguous buffer on which the AES functions can work.
2231      * Also, decryption in a separate buffer is better as it
2232      * prevents the guest from learning information about the
2233      * encrypted nature of the virtual disk.
2234      */
2235 
2236     buf = qemu_try_blockalign(s->data_file->bs, bytes);
2237     if (buf == NULL) {
2238         return -ENOMEM;
2239     }
2240 
2241     BLKDBG_CO_EVENT(bs->file, BLKDBG_READ_AIO);
2242     ret = bdrv_co_pread(s->data_file, host_offset, bytes, buf, 0);
2243     if (ret < 0) {
2244         goto fail;
2245     }
2246 
2247     if (qcow2_co_decrypt(bs, host_offset, offset, buf, bytes) < 0)
2248     {
2249         ret = -EIO;
2250         goto fail;
2251     }
2252     qemu_iovec_from_buf(qiov, qiov_offset, buf, bytes);
2253 
2254 fail:
2255     qemu_vfree(buf);
2256 
2257     return ret;
2258 }
2259 
2260 typedef struct Qcow2AioTask {
2261     AioTask task;
2262 
2263     BlockDriverState *bs;
2264     QCow2SubclusterType subcluster_type; /* only for read */
2265     uint64_t host_offset; /* or l2_entry for compressed read */
2266     uint64_t offset;
2267     uint64_t bytes;
2268     QEMUIOVector *qiov;
2269     uint64_t qiov_offset;
2270     QCowL2Meta *l2meta; /* only for write */
2271 } Qcow2AioTask;
2272 
2273 static coroutine_fn int qcow2_co_preadv_task_entry(AioTask *task);
2274 static coroutine_fn int qcow2_add_task(BlockDriverState *bs,
2275                                        AioTaskPool *pool,
2276                                        AioTaskFunc func,
2277                                        QCow2SubclusterType subcluster_type,
2278                                        uint64_t host_offset,
2279                                        uint64_t offset,
2280                                        uint64_t bytes,
2281                                        QEMUIOVector *qiov,
2282                                        size_t qiov_offset,
2283                                        QCowL2Meta *l2meta)
2284 {
2285     Qcow2AioTask local_task;
2286     Qcow2AioTask *task = pool ? g_new(Qcow2AioTask, 1) : &local_task;
2287 
2288     *task = (Qcow2AioTask) {
2289         .task.func = func,
2290         .bs = bs,
2291         .subcluster_type = subcluster_type,
2292         .qiov = qiov,
2293         .host_offset = host_offset,
2294         .offset = offset,
2295         .bytes = bytes,
2296         .qiov_offset = qiov_offset,
2297         .l2meta = l2meta,
2298     };
2299 
2300     trace_qcow2_add_task(qemu_coroutine_self(), bs, pool,
2301                          func == qcow2_co_preadv_task_entry ? "read" : "write",
2302                          subcluster_type, host_offset, offset, bytes,
2303                          qiov, qiov_offset);
2304 
2305     if (!pool) {
2306         return func(&task->task);
2307     }
2308 
2309     aio_task_pool_start_task(pool, &task->task);
2310 
2311     return 0;
2312 }
2313 
2314 static int coroutine_fn GRAPH_RDLOCK
2315 qcow2_co_preadv_task(BlockDriverState *bs, QCow2SubclusterType subc_type,
2316                      uint64_t host_offset, uint64_t offset, uint64_t bytes,
2317                      QEMUIOVector *qiov, size_t qiov_offset)
2318 {
2319     BDRVQcow2State *s = bs->opaque;
2320 
2321     switch (subc_type) {
2322     case QCOW2_SUBCLUSTER_ZERO_PLAIN:
2323     case QCOW2_SUBCLUSTER_ZERO_ALLOC:
2324         /* Both zero types are handled in qcow2_co_preadv_part */
2325         g_assert_not_reached();
2326 
2327     case QCOW2_SUBCLUSTER_UNALLOCATED_PLAIN:
2328     case QCOW2_SUBCLUSTER_UNALLOCATED_ALLOC:
2329         assert(bs->backing); /* otherwise handled in qcow2_co_preadv_part */
2330 
2331         BLKDBG_CO_EVENT(bs->file, BLKDBG_READ_BACKING_AIO);
2332         return bdrv_co_preadv_part(bs->backing, offset, bytes,
2333                                    qiov, qiov_offset, 0);
2334 
2335     case QCOW2_SUBCLUSTER_COMPRESSED:
2336         return qcow2_co_preadv_compressed(bs, host_offset,
2337                                           offset, bytes, qiov, qiov_offset);
2338 
2339     case QCOW2_SUBCLUSTER_NORMAL:
2340         if (bs->encrypted) {
2341             return qcow2_co_preadv_encrypted(bs, host_offset,
2342                                              offset, bytes, qiov, qiov_offset);
2343         }
2344 
2345         BLKDBG_CO_EVENT(bs->file, BLKDBG_READ_AIO);
2346         return bdrv_co_preadv_part(s->data_file, host_offset,
2347                                    bytes, qiov, qiov_offset, 0);
2348 
2349     default:
2350         g_assert_not_reached();
2351     }
2352 
2353     g_assert_not_reached();
2354 }
2355 
2356 /*
2357  * This function can count as GRAPH_RDLOCK because qcow2_co_preadv_part() holds
2358  * the graph lock and keeps it until this coroutine has terminated.
2359  */
2360 static int coroutine_fn GRAPH_RDLOCK qcow2_co_preadv_task_entry(AioTask *task)
2361 {
2362     Qcow2AioTask *t = container_of(task, Qcow2AioTask, task);
2363 
2364     assert(!t->l2meta);
2365 
2366     return qcow2_co_preadv_task(t->bs, t->subcluster_type,
2367                                 t->host_offset, t->offset, t->bytes,
2368                                 t->qiov, t->qiov_offset);
2369 }
2370 
2371 static int coroutine_fn GRAPH_RDLOCK
2372 qcow2_co_preadv_part(BlockDriverState *bs, int64_t offset, int64_t bytes,
2373                      QEMUIOVector *qiov, size_t qiov_offset,
2374                      BdrvRequestFlags flags)
2375 {
2376     BDRVQcow2State *s = bs->opaque;
2377     int ret = 0;
2378     unsigned int cur_bytes; /* number of bytes in current iteration */
2379     uint64_t host_offset = 0;
2380     QCow2SubclusterType type;
2381     AioTaskPool *aio = NULL;
2382 
2383     while (bytes != 0 && aio_task_pool_status(aio) == 0) {
2384         /* prepare next request */
2385         cur_bytes = MIN(bytes, INT_MAX);
2386         if (s->crypto) {
2387             cur_bytes = MIN(cur_bytes,
2388                             QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
2389         }
2390 
2391         qemu_co_mutex_lock(&s->lock);
2392         ret = qcow2_get_host_offset(bs, offset, &cur_bytes,
2393                                     &host_offset, &type);
2394         qemu_co_mutex_unlock(&s->lock);
2395         if (ret < 0) {
2396             goto out;
2397         }
2398 
2399         if (type == QCOW2_SUBCLUSTER_ZERO_PLAIN ||
2400             type == QCOW2_SUBCLUSTER_ZERO_ALLOC ||
2401             (type == QCOW2_SUBCLUSTER_UNALLOCATED_PLAIN && !bs->backing) ||
2402             (type == QCOW2_SUBCLUSTER_UNALLOCATED_ALLOC && !bs->backing))
2403         {
2404             qemu_iovec_memset(qiov, qiov_offset, 0, cur_bytes);
2405         } else {
2406             if (!aio && cur_bytes != bytes) {
2407                 aio = aio_task_pool_new(QCOW2_MAX_WORKERS);
2408             }
2409             ret = qcow2_add_task(bs, aio, qcow2_co_preadv_task_entry, type,
2410                                  host_offset, offset, cur_bytes,
2411                                  qiov, qiov_offset, NULL);
2412             if (ret < 0) {
2413                 goto out;
2414             }
2415         }
2416 
2417         bytes -= cur_bytes;
2418         offset += cur_bytes;
2419         qiov_offset += cur_bytes;
2420     }
2421 
2422 out:
2423     if (aio) {
2424         aio_task_pool_wait_all(aio);
2425         if (ret == 0) {
2426             ret = aio_task_pool_status(aio);
2427         }
2428         g_free(aio);
2429     }
2430 
2431     return ret;
2432 }
2433 
2434 /* Check if it's possible to merge a write request with the writing of
2435  * the data from the COW regions */
2436 static bool merge_cow(uint64_t offset, unsigned bytes,
2437                       QEMUIOVector *qiov, size_t qiov_offset,
2438                       QCowL2Meta *l2meta)
2439 {
2440     QCowL2Meta *m;
2441 
2442     for (m = l2meta; m != NULL; m = m->next) {
2443         /* If both COW regions are empty then there's nothing to merge */
2444         if (m->cow_start.nb_bytes == 0 && m->cow_end.nb_bytes == 0) {
2445             continue;
2446         }
2447 
2448         /* If COW regions are handled already, skip this too */
2449         if (m->skip_cow) {
2450             continue;
2451         }
2452 
2453         /*
2454          * The write request should start immediately after the first
2455          * COW region. This does not always happen because the area
2456          * touched by the request can be larger than the one defined
2457          * by @m (a single request can span an area consisting of a
2458          * mix of previously unallocated and allocated clusters, that
2459          * is why @l2meta is a list).
2460          */
2461         if (l2meta_cow_start(m) + m->cow_start.nb_bytes != offset) {
2462             /* In this case the request starts before this region */
2463             assert(offset < l2meta_cow_start(m));
2464             assert(m->cow_start.nb_bytes == 0);
2465             continue;
2466         }
2467 
2468         /* The write request should end immediately before the second
2469          * COW region (see above for why it does not always happen) */
2470         if (m->offset + m->cow_end.offset != offset + bytes) {
2471             assert(offset + bytes > m->offset + m->cow_end.offset);
2472             assert(m->cow_end.nb_bytes == 0);
2473             continue;
2474         }
2475 
2476         /* Make sure that adding both COW regions to the QEMUIOVector
2477          * does not exceed IOV_MAX */
2478         if (qemu_iovec_subvec_niov(qiov, qiov_offset, bytes) > IOV_MAX - 2) {
2479             continue;
2480         }
2481 
2482         m->data_qiov = qiov;
2483         m->data_qiov_offset = qiov_offset;
2484         return true;
2485     }
2486 
2487     return false;
2488 }
2489 
2490 /*
2491  * Return 1 if the COW regions read as zeroes, 0 if not, < 0 on error.
2492  * Note that returning 0 does not guarantee non-zero data.
2493  */
2494 static int coroutine_fn GRAPH_RDLOCK
2495 is_zero_cow(BlockDriverState *bs, QCowL2Meta *m)
2496 {
2497     /*
2498      * This check is designed for optimization shortcut so it must be
2499      * efficient.
2500      * Instead of is_zero(), use bdrv_co_is_zero_fast() as it is
2501      * faster (but not as accurate and can result in false negatives).
2502      */
2503     int ret = bdrv_co_is_zero_fast(bs, m->offset + m->cow_start.offset,
2504                                    m->cow_start.nb_bytes);
2505     if (ret <= 0) {
2506         return ret;
2507     }
2508 
2509     return bdrv_co_is_zero_fast(bs, m->offset + m->cow_end.offset,
2510                                 m->cow_end.nb_bytes);
2511 }
2512 
2513 static int coroutine_fn GRAPH_RDLOCK
2514 handle_alloc_space(BlockDriverState *bs, QCowL2Meta *l2meta)
2515 {
2516     BDRVQcow2State *s = bs->opaque;
2517     QCowL2Meta *m;
2518 
2519     if (!(s->data_file->bs->supported_zero_flags & BDRV_REQ_NO_FALLBACK)) {
2520         return 0;
2521     }
2522 
2523     if (bs->encrypted) {
2524         return 0;
2525     }
2526 
2527     for (m = l2meta; m != NULL; m = m->next) {
2528         int ret;
2529         uint64_t start_offset = m->alloc_offset + m->cow_start.offset;
2530         unsigned nb_bytes = m->cow_end.offset + m->cow_end.nb_bytes -
2531             m->cow_start.offset;
2532 
2533         if (!m->cow_start.nb_bytes && !m->cow_end.nb_bytes) {
2534             continue;
2535         }
2536 
2537         ret = is_zero_cow(bs, m);
2538         if (ret < 0) {
2539             return ret;
2540         } else if (ret == 0) {
2541             continue;
2542         }
2543 
2544         /*
2545          * instead of writing zero COW buffers,
2546          * efficiently zero out the whole clusters
2547          */
2548 
2549         ret = qcow2_pre_write_overlap_check(bs, 0, start_offset, nb_bytes,
2550                                             true);
2551         if (ret < 0) {
2552             return ret;
2553         }
2554 
2555         BLKDBG_CO_EVENT(bs->file, BLKDBG_CLUSTER_ALLOC_SPACE);
2556         ret = bdrv_co_pwrite_zeroes(s->data_file, start_offset, nb_bytes,
2557                                     BDRV_REQ_NO_FALLBACK);
2558         if (ret < 0) {
2559             if (ret != -ENOTSUP && ret != -EAGAIN) {
2560                 return ret;
2561             }
2562             continue;
2563         }
2564 
2565         trace_qcow2_skip_cow(qemu_coroutine_self(), m->offset, m->nb_clusters);
2566         m->skip_cow = true;
2567     }
2568     return 0;
2569 }
2570 
2571 /*
2572  * qcow2_co_pwritev_task
2573  * Called with s->lock unlocked
2574  * l2meta  - if not NULL, qcow2_co_pwritev_task() will consume it. Caller must
2575  *           not use it somehow after qcow2_co_pwritev_task() call
2576  */
2577 static coroutine_fn GRAPH_RDLOCK
2578 int qcow2_co_pwritev_task(BlockDriverState *bs, uint64_t host_offset,
2579                           uint64_t offset, uint64_t bytes, QEMUIOVector *qiov,
2580                           uint64_t qiov_offset, QCowL2Meta *l2meta)
2581 {
2582     int ret;
2583     BDRVQcow2State *s = bs->opaque;
2584     void *crypt_buf = NULL;
2585     QEMUIOVector encrypted_qiov;
2586 
2587     if (bs->encrypted) {
2588         assert(s->crypto);
2589         assert(bytes <= QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
2590         crypt_buf = qemu_try_blockalign(bs->file->bs, bytes);
2591         if (crypt_buf == NULL) {
2592             ret = -ENOMEM;
2593             goto out_unlocked;
2594         }
2595         qemu_iovec_to_buf(qiov, qiov_offset, crypt_buf, bytes);
2596 
2597         if (qcow2_co_encrypt(bs, host_offset, offset, crypt_buf, bytes) < 0) {
2598             ret = -EIO;
2599             goto out_unlocked;
2600         }
2601 
2602         qemu_iovec_init_buf(&encrypted_qiov, crypt_buf, bytes);
2603         qiov = &encrypted_qiov;
2604         qiov_offset = 0;
2605     }
2606 
2607     /* Try to efficiently initialize the physical space with zeroes */
2608     ret = handle_alloc_space(bs, l2meta);
2609     if (ret < 0) {
2610         goto out_unlocked;
2611     }
2612 
2613     /*
2614      * If we need to do COW, check if it's possible to merge the
2615      * writing of the guest data together with that of the COW regions.
2616      * If it's not possible (or not necessary) then write the
2617      * guest data now.
2618      */
2619     if (!merge_cow(offset, bytes, qiov, qiov_offset, l2meta)) {
2620         BLKDBG_CO_EVENT(bs->file, BLKDBG_WRITE_AIO);
2621         trace_qcow2_writev_data(qemu_coroutine_self(), host_offset);
2622         ret = bdrv_co_pwritev_part(s->data_file, host_offset,
2623                                    bytes, qiov, qiov_offset, 0);
2624         if (ret < 0) {
2625             goto out_unlocked;
2626         }
2627     }
2628 
2629     qemu_co_mutex_lock(&s->lock);
2630 
2631     ret = qcow2_handle_l2meta(bs, &l2meta, true);
2632     goto out_locked;
2633 
2634 out_unlocked:
2635     qemu_co_mutex_lock(&s->lock);
2636 
2637 out_locked:
2638     qcow2_handle_l2meta(bs, &l2meta, false);
2639     qemu_co_mutex_unlock(&s->lock);
2640 
2641     qemu_vfree(crypt_buf);
2642 
2643     return ret;
2644 }
2645 
2646 /*
2647  * This function can count as GRAPH_RDLOCK because qcow2_co_pwritev_part() holds
2648  * the graph lock and keeps it until this coroutine has terminated.
2649  */
2650 static coroutine_fn GRAPH_RDLOCK int qcow2_co_pwritev_task_entry(AioTask *task)
2651 {
2652     Qcow2AioTask *t = container_of(task, Qcow2AioTask, task);
2653 
2654     assert(!t->subcluster_type);
2655 
2656     return qcow2_co_pwritev_task(t->bs, t->host_offset,
2657                                  t->offset, t->bytes, t->qiov, t->qiov_offset,
2658                                  t->l2meta);
2659 }
2660 
2661 static int coroutine_fn GRAPH_RDLOCK
2662 qcow2_co_pwritev_part(BlockDriverState *bs, int64_t offset, int64_t bytes,
2663                       QEMUIOVector *qiov, size_t qiov_offset,
2664                       BdrvRequestFlags flags)
2665 {
2666     BDRVQcow2State *s = bs->opaque;
2667     int offset_in_cluster;
2668     int ret;
2669     unsigned int cur_bytes; /* number of sectors in current iteration */
2670     uint64_t host_offset;
2671     QCowL2Meta *l2meta = NULL;
2672     AioTaskPool *aio = NULL;
2673 
2674     trace_qcow2_writev_start_req(qemu_coroutine_self(), offset, bytes);
2675 
2676     while (bytes != 0 && aio_task_pool_status(aio) == 0) {
2677 
2678         l2meta = NULL;
2679 
2680         trace_qcow2_writev_start_part(qemu_coroutine_self());
2681         offset_in_cluster = offset_into_cluster(s, offset);
2682         cur_bytes = MIN(bytes, INT_MAX);
2683         if (bs->encrypted) {
2684             cur_bytes = MIN(cur_bytes,
2685                             QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size
2686                             - offset_in_cluster);
2687         }
2688 
2689         qemu_co_mutex_lock(&s->lock);
2690 
2691         ret = qcow2_alloc_host_offset(bs, offset, &cur_bytes,
2692                                       &host_offset, &l2meta);
2693         if (ret < 0) {
2694             goto out_locked;
2695         }
2696 
2697         ret = qcow2_pre_write_overlap_check(bs, 0, host_offset,
2698                                             cur_bytes, true);
2699         if (ret < 0) {
2700             goto out_locked;
2701         }
2702 
2703         qemu_co_mutex_unlock(&s->lock);
2704 
2705         if (!aio && cur_bytes != bytes) {
2706             aio = aio_task_pool_new(QCOW2_MAX_WORKERS);
2707         }
2708         ret = qcow2_add_task(bs, aio, qcow2_co_pwritev_task_entry, 0,
2709                              host_offset, offset,
2710                              cur_bytes, qiov, qiov_offset, l2meta);
2711         l2meta = NULL; /* l2meta is consumed by qcow2_co_pwritev_task() */
2712         if (ret < 0) {
2713             goto fail_nometa;
2714         }
2715 
2716         bytes -= cur_bytes;
2717         offset += cur_bytes;
2718         qiov_offset += cur_bytes;
2719         trace_qcow2_writev_done_part(qemu_coroutine_self(), cur_bytes);
2720     }
2721     ret = 0;
2722 
2723     qemu_co_mutex_lock(&s->lock);
2724 
2725 out_locked:
2726     qcow2_handle_l2meta(bs, &l2meta, false);
2727 
2728     qemu_co_mutex_unlock(&s->lock);
2729 
2730 fail_nometa:
2731     if (aio) {
2732         aio_task_pool_wait_all(aio);
2733         if (ret == 0) {
2734             ret = aio_task_pool_status(aio);
2735         }
2736         g_free(aio);
2737     }
2738 
2739     trace_qcow2_writev_done_req(qemu_coroutine_self(), ret);
2740 
2741     return ret;
2742 }
2743 
2744 static int GRAPH_RDLOCK qcow2_inactivate(BlockDriverState *bs)
2745 {
2746     BDRVQcow2State *s = bs->opaque;
2747     int ret, result = 0;
2748     Error *local_err = NULL;
2749 
2750     qcow2_store_persistent_dirty_bitmaps(bs, true, &local_err);
2751     if (local_err != NULL) {
2752         result = -EINVAL;
2753         error_reportf_err(local_err, "Lost persistent bitmaps during "
2754                           "inactivation of node '%s': ",
2755                           bdrv_get_device_or_node_name(bs));
2756     }
2757 
2758     ret = qcow2_cache_flush(bs, s->l2_table_cache);
2759     if (ret) {
2760         result = ret;
2761         error_report("Failed to flush the L2 table cache: %s",
2762                      strerror(-ret));
2763     }
2764 
2765     ret = qcow2_cache_flush(bs, s->refcount_block_cache);
2766     if (ret) {
2767         result = ret;
2768         error_report("Failed to flush the refcount block cache: %s",
2769                      strerror(-ret));
2770     }
2771 
2772     if (result == 0) {
2773         qcow2_mark_clean(bs);
2774     }
2775 
2776     return result;
2777 }
2778 
2779 static void coroutine_mixed_fn GRAPH_RDLOCK
2780 qcow2_do_close(BlockDriverState *bs, bool close_data_file)
2781 {
2782     BDRVQcow2State *s = bs->opaque;
2783     qemu_vfree(s->l1_table);
2784     /* else pre-write overlap checks in cache_destroy may crash */
2785     s->l1_table = NULL;
2786 
2787     if (!(s->flags & BDRV_O_INACTIVE)) {
2788         qcow2_inactivate(bs);
2789     }
2790 
2791     cache_clean_timer_del(bs);
2792     qcow2_cache_destroy(s->l2_table_cache);
2793     qcow2_cache_destroy(s->refcount_block_cache);
2794 
2795     qcrypto_block_free(s->crypto);
2796     s->crypto = NULL;
2797     qapi_free_QCryptoBlockOpenOptions(s->crypto_opts);
2798 
2799     g_free(s->unknown_header_fields);
2800     cleanup_unknown_header_ext(bs);
2801 
2802     g_free(s->image_data_file);
2803     g_free(s->image_backing_file);
2804     g_free(s->image_backing_format);
2805 
2806     if (close_data_file && has_data_file(bs)) {
2807         GLOBAL_STATE_CODE();
2808         bdrv_graph_rdunlock_main_loop();
2809         bdrv_graph_wrlock();
2810         bdrv_unref_child(bs, s->data_file);
2811         bdrv_graph_wrunlock();
2812         s->data_file = NULL;
2813         bdrv_graph_rdlock_main_loop();
2814     }
2815 
2816     qcow2_refcount_close(bs);
2817     qcow2_free_snapshots(bs);
2818 }
2819 
2820 static void GRAPH_UNLOCKED qcow2_close(BlockDriverState *bs)
2821 {
2822     GLOBAL_STATE_CODE();
2823     GRAPH_RDLOCK_GUARD_MAINLOOP();
2824 
2825     qcow2_do_close(bs, true);
2826 }
2827 
2828 static void coroutine_fn GRAPH_RDLOCK
2829 qcow2_co_invalidate_cache(BlockDriverState *bs, Error **errp)
2830 {
2831     ERRP_GUARD();
2832     BDRVQcow2State *s = bs->opaque;
2833     BdrvChild *data_file;
2834     int flags = s->flags;
2835     QCryptoBlock *crypto = NULL;
2836     QDict *options;
2837     int ret;
2838 
2839     /*
2840      * Backing files are read-only which makes all of their metadata immutable,
2841      * that means we don't have to worry about reopening them here.
2842      */
2843 
2844     crypto = s->crypto;
2845     s->crypto = NULL;
2846 
2847     /*
2848      * Do not reopen s->data_file (i.e., have qcow2_do_close() not close it,
2849      * and then prevent qcow2_do_open() from opening it), because this function
2850      * runs in the I/O path and as such we must not invoke global-state
2851      * functions like bdrv_unref_child() and bdrv_open_child().
2852      */
2853 
2854     qcow2_do_close(bs, false);
2855 
2856     data_file = s->data_file;
2857     memset(s, 0, sizeof(BDRVQcow2State));
2858     s->data_file = data_file;
2859 
2860     options = qdict_clone_shallow(bs->options);
2861 
2862     flags &= ~BDRV_O_INACTIVE;
2863     qemu_co_mutex_lock(&s->lock);
2864     ret = qcow2_do_open(bs, options, flags, false, errp);
2865     qemu_co_mutex_unlock(&s->lock);
2866     qobject_unref(options);
2867     if (ret < 0) {
2868         error_prepend(errp, "Could not reopen qcow2 layer: ");
2869         bs->drv = NULL;
2870         return;
2871     }
2872 
2873     s->crypto = crypto;
2874 }
2875 
2876 static size_t header_ext_add(char *buf, uint32_t magic, const void *s,
2877     size_t len, size_t buflen)
2878 {
2879     QCowExtension *ext_backing_fmt = (QCowExtension*) buf;
2880     size_t ext_len = sizeof(QCowExtension) + ((len + 7) & ~7);
2881 
2882     if (buflen < ext_len) {
2883         return -ENOSPC;
2884     }
2885 
2886     *ext_backing_fmt = (QCowExtension) {
2887         .magic  = cpu_to_be32(magic),
2888         .len    = cpu_to_be32(len),
2889     };
2890 
2891     if (len) {
2892         memcpy(buf + sizeof(QCowExtension), s, len);
2893     }
2894 
2895     return ext_len;
2896 }
2897 
2898 /*
2899  * Updates the qcow2 header, including the variable length parts of it, i.e.
2900  * the backing file name and all extensions. qcow2 was not designed to allow
2901  * such changes, so if we run out of space (we can only use the first cluster)
2902  * this function may fail.
2903  *
2904  * Returns 0 on success, -errno in error cases.
2905  */
2906 int qcow2_update_header(BlockDriverState *bs)
2907 {
2908     BDRVQcow2State *s = bs->opaque;
2909     QCowHeader *header;
2910     char *buf;
2911     size_t buflen = s->cluster_size;
2912     int ret;
2913     uint64_t total_size;
2914     uint32_t refcount_table_clusters;
2915     size_t header_length;
2916     Qcow2UnknownHeaderExtension *uext;
2917 
2918     buf = qemu_blockalign(bs, buflen);
2919 
2920     /* Header structure */
2921     header = (QCowHeader*) buf;
2922 
2923     if (buflen < sizeof(*header)) {
2924         ret = -ENOSPC;
2925         goto fail;
2926     }
2927 
2928     header_length = sizeof(*header) + s->unknown_header_fields_size;
2929     total_size = bs->total_sectors * BDRV_SECTOR_SIZE;
2930     refcount_table_clusters = s->refcount_table_size >> (s->cluster_bits - 3);
2931 
2932     ret = validate_compression_type(s, NULL);
2933     if (ret) {
2934         goto fail;
2935     }
2936 
2937     *header = (QCowHeader) {
2938         /* Version 2 fields */
2939         .magic                  = cpu_to_be32(QCOW_MAGIC),
2940         .version                = cpu_to_be32(s->qcow_version),
2941         .backing_file_offset    = 0,
2942         .backing_file_size      = 0,
2943         .cluster_bits           = cpu_to_be32(s->cluster_bits),
2944         .size                   = cpu_to_be64(total_size),
2945         .crypt_method           = cpu_to_be32(s->crypt_method_header),
2946         .l1_size                = cpu_to_be32(s->l1_size),
2947         .l1_table_offset        = cpu_to_be64(s->l1_table_offset),
2948         .refcount_table_offset  = cpu_to_be64(s->refcount_table_offset),
2949         .refcount_table_clusters = cpu_to_be32(refcount_table_clusters),
2950         .nb_snapshots           = cpu_to_be32(s->nb_snapshots),
2951         .snapshots_offset       = cpu_to_be64(s->snapshots_offset),
2952 
2953         /* Version 3 fields */
2954         .incompatible_features  = cpu_to_be64(s->incompatible_features),
2955         .compatible_features    = cpu_to_be64(s->compatible_features),
2956         .autoclear_features     = cpu_to_be64(s->autoclear_features),
2957         .refcount_order         = cpu_to_be32(s->refcount_order),
2958         .header_length          = cpu_to_be32(header_length),
2959         .compression_type       = s->compression_type,
2960     };
2961 
2962     /* For older versions, write a shorter header */
2963     switch (s->qcow_version) {
2964     case 2:
2965         ret = offsetof(QCowHeader, incompatible_features);
2966         break;
2967     case 3:
2968         ret = sizeof(*header);
2969         break;
2970     default:
2971         ret = -EINVAL;
2972         goto fail;
2973     }
2974 
2975     buf += ret;
2976     buflen -= ret;
2977     memset(buf, 0, buflen);
2978 
2979     /* Preserve any unknown field in the header */
2980     if (s->unknown_header_fields_size) {
2981         if (buflen < s->unknown_header_fields_size) {
2982             ret = -ENOSPC;
2983             goto fail;
2984         }
2985 
2986         memcpy(buf, s->unknown_header_fields, s->unknown_header_fields_size);
2987         buf += s->unknown_header_fields_size;
2988         buflen -= s->unknown_header_fields_size;
2989     }
2990 
2991     /* Backing file format header extension */
2992     if (s->image_backing_format) {
2993         ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BACKING_FORMAT,
2994                              s->image_backing_format,
2995                              strlen(s->image_backing_format),
2996                              buflen);
2997         if (ret < 0) {
2998             goto fail;
2999         }
3000 
3001         buf += ret;
3002         buflen -= ret;
3003     }
3004 
3005     /* External data file header extension */
3006     if (has_data_file(bs) && s->image_data_file) {
3007         ret = header_ext_add(buf, QCOW2_EXT_MAGIC_DATA_FILE,
3008                              s->image_data_file, strlen(s->image_data_file),
3009                              buflen);
3010         if (ret < 0) {
3011             goto fail;
3012         }
3013 
3014         buf += ret;
3015         buflen -= ret;
3016     }
3017 
3018     /* Full disk encryption header pointer extension */
3019     if (s->crypto_header.offset != 0) {
3020         s->crypto_header.offset = cpu_to_be64(s->crypto_header.offset);
3021         s->crypto_header.length = cpu_to_be64(s->crypto_header.length);
3022         ret = header_ext_add(buf, QCOW2_EXT_MAGIC_CRYPTO_HEADER,
3023                              &s->crypto_header, sizeof(s->crypto_header),
3024                              buflen);
3025         s->crypto_header.offset = be64_to_cpu(s->crypto_header.offset);
3026         s->crypto_header.length = be64_to_cpu(s->crypto_header.length);
3027         if (ret < 0) {
3028             goto fail;
3029         }
3030         buf += ret;
3031         buflen -= ret;
3032     }
3033 
3034     /*
3035      * Feature table.  A mere 8 feature names occupies 392 bytes, and
3036      * when coupled with the v3 minimum header of 104 bytes plus the
3037      * 8-byte end-of-extension marker, that would leave only 8 bytes
3038      * for a backing file name in an image with 512-byte clusters.
3039      * Thus, we choose to omit this header for cluster sizes 4k and
3040      * smaller.
3041      */
3042     if (s->qcow_version >= 3 && s->cluster_size > 4096) {
3043         static const Qcow2Feature features[] = {
3044             {
3045                 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
3046                 .bit  = QCOW2_INCOMPAT_DIRTY_BITNR,
3047                 .name = "dirty bit",
3048             },
3049             {
3050                 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
3051                 .bit  = QCOW2_INCOMPAT_CORRUPT_BITNR,
3052                 .name = "corrupt bit",
3053             },
3054             {
3055                 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
3056                 .bit  = QCOW2_INCOMPAT_DATA_FILE_BITNR,
3057                 .name = "external data file",
3058             },
3059             {
3060                 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
3061                 .bit  = QCOW2_INCOMPAT_COMPRESSION_BITNR,
3062                 .name = "compression type",
3063             },
3064             {
3065                 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
3066                 .bit  = QCOW2_INCOMPAT_EXTL2_BITNR,
3067                 .name = "extended L2 entries",
3068             },
3069             {
3070                 .type = QCOW2_FEAT_TYPE_COMPATIBLE,
3071                 .bit  = QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR,
3072                 .name = "lazy refcounts",
3073             },
3074             {
3075                 .type = QCOW2_FEAT_TYPE_AUTOCLEAR,
3076                 .bit  = QCOW2_AUTOCLEAR_BITMAPS_BITNR,
3077                 .name = "bitmaps",
3078             },
3079             {
3080                 .type = QCOW2_FEAT_TYPE_AUTOCLEAR,
3081                 .bit  = QCOW2_AUTOCLEAR_DATA_FILE_RAW_BITNR,
3082                 .name = "raw external data",
3083             },
3084         };
3085 
3086         ret = header_ext_add(buf, QCOW2_EXT_MAGIC_FEATURE_TABLE,
3087                              features, sizeof(features), buflen);
3088         if (ret < 0) {
3089             goto fail;
3090         }
3091         buf += ret;
3092         buflen -= ret;
3093     }
3094 
3095     /* Bitmap extension */
3096     if (s->nb_bitmaps > 0) {
3097         Qcow2BitmapHeaderExt bitmaps_header = {
3098             .nb_bitmaps = cpu_to_be32(s->nb_bitmaps),
3099             .bitmap_directory_size =
3100                     cpu_to_be64(s->bitmap_directory_size),
3101             .bitmap_directory_offset =
3102                     cpu_to_be64(s->bitmap_directory_offset)
3103         };
3104         ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BITMAPS,
3105                              &bitmaps_header, sizeof(bitmaps_header),
3106                              buflen);
3107         if (ret < 0) {
3108             goto fail;
3109         }
3110         buf += ret;
3111         buflen -= ret;
3112     }
3113 
3114     /* Keep unknown header extensions */
3115     QLIST_FOREACH(uext, &s->unknown_header_ext, next) {
3116         ret = header_ext_add(buf, uext->magic, uext->data, uext->len, buflen);
3117         if (ret < 0) {
3118             goto fail;
3119         }
3120 
3121         buf += ret;
3122         buflen -= ret;
3123     }
3124 
3125     /* End of header extensions */
3126     ret = header_ext_add(buf, QCOW2_EXT_MAGIC_END, NULL, 0, buflen);
3127     if (ret < 0) {
3128         goto fail;
3129     }
3130 
3131     buf += ret;
3132     buflen -= ret;
3133 
3134     /* Backing file name */
3135     if (s->image_backing_file) {
3136         size_t backing_file_len = strlen(s->image_backing_file);
3137 
3138         if (buflen < backing_file_len) {
3139             ret = -ENOSPC;
3140             goto fail;
3141         }
3142 
3143         /* Using strncpy is ok here, since buf is not NUL-terminated. */
3144         strncpy(buf, s->image_backing_file, buflen);
3145 
3146         header->backing_file_offset = cpu_to_be64(buf - ((char*) header));
3147         header->backing_file_size   = cpu_to_be32(backing_file_len);
3148     }
3149 
3150     /* Write the new header */
3151     ret = bdrv_pwrite(bs->file, 0, s->cluster_size, header, 0);
3152     if (ret < 0) {
3153         goto fail;
3154     }
3155 
3156     ret = 0;
3157 fail:
3158     qemu_vfree(header);
3159     return ret;
3160 }
3161 
3162 static int coroutine_fn GRAPH_RDLOCK
3163 qcow2_co_change_backing_file(BlockDriverState *bs, const char *backing_file,
3164                              const char *backing_fmt)
3165 {
3166     BDRVQcow2State *s = bs->opaque;
3167 
3168     /* Adding a backing file means that the external data file alone won't be
3169      * enough to make sense of the content */
3170     if (backing_file && data_file_is_raw(bs)) {
3171         return -EINVAL;
3172     }
3173 
3174     if (backing_file && strlen(backing_file) > 1023) {
3175         return -EINVAL;
3176     }
3177 
3178     pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
3179             backing_file ?: "");
3180     pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
3181     pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
3182 
3183     g_free(s->image_backing_file);
3184     g_free(s->image_backing_format);
3185 
3186     s->image_backing_file = backing_file ? g_strdup(bs->backing_file) : NULL;
3187     s->image_backing_format = backing_fmt ? g_strdup(bs->backing_format) : NULL;
3188 
3189     return qcow2_update_header(bs);
3190 }
3191 
3192 static int coroutine_fn GRAPH_RDLOCK
3193 qcow2_set_up_encryption(BlockDriverState *bs,
3194                         QCryptoBlockCreateOptions *cryptoopts,
3195                         Error **errp)
3196 {
3197     BDRVQcow2State *s = bs->opaque;
3198     QCryptoBlock *crypto = NULL;
3199     int fmt, ret;
3200 
3201     switch (cryptoopts->format) {
3202     case Q_CRYPTO_BLOCK_FORMAT_LUKS:
3203         fmt = QCOW_CRYPT_LUKS;
3204         break;
3205     case Q_CRYPTO_BLOCK_FORMAT_QCOW:
3206         fmt = QCOW_CRYPT_AES;
3207         break;
3208     default:
3209         error_setg(errp, "Crypto format not supported in qcow2");
3210         return -EINVAL;
3211     }
3212 
3213     s->crypt_method_header = fmt;
3214 
3215     crypto = qcrypto_block_create(cryptoopts, "encrypt.",
3216                                   qcow2_crypto_hdr_init_func,
3217                                   qcow2_crypto_hdr_write_func,
3218                                   bs, 0, errp);
3219     if (!crypto) {
3220         return -EINVAL;
3221     }
3222 
3223     ret = qcow2_update_header(bs);
3224     if (ret < 0) {
3225         error_setg_errno(errp, -ret, "Could not write encryption header");
3226         goto out;
3227     }
3228 
3229     ret = 0;
3230  out:
3231     qcrypto_block_free(crypto);
3232     return ret;
3233 }
3234 
3235 /**
3236  * Preallocates metadata structures for data clusters between @offset (in the
3237  * guest disk) and @new_length (which is thus generally the new guest disk
3238  * size).
3239  *
3240  * Returns: 0 on success, -errno on failure.
3241  */
3242 static int coroutine_fn GRAPH_RDLOCK
3243 preallocate_co(BlockDriverState *bs, uint64_t offset, uint64_t new_length,
3244                PreallocMode mode, Error **errp)
3245 {
3246     BDRVQcow2State *s = bs->opaque;
3247     uint64_t bytes;
3248     uint64_t host_offset = 0;
3249     int64_t file_length;
3250     unsigned int cur_bytes;
3251     int ret;
3252     QCowL2Meta *meta = NULL, *m;
3253 
3254     assert(offset <= new_length);
3255     bytes = new_length - offset;
3256 
3257     while (bytes) {
3258         cur_bytes = MIN(bytes, QEMU_ALIGN_DOWN(INT_MAX, s->cluster_size));
3259         ret = qcow2_alloc_host_offset(bs, offset, &cur_bytes,
3260                                       &host_offset, &meta);
3261         if (ret < 0) {
3262             error_setg_errno(errp, -ret, "Allocating clusters failed");
3263             goto out;
3264         }
3265 
3266         for (m = meta; m != NULL; m = m->next) {
3267             m->prealloc = true;
3268         }
3269 
3270         ret = qcow2_handle_l2meta(bs, &meta, true);
3271         if (ret < 0) {
3272             error_setg_errno(errp, -ret, "Mapping clusters failed");
3273             goto out;
3274         }
3275 
3276         /* TODO Preallocate data if requested */
3277 
3278         bytes -= cur_bytes;
3279         offset += cur_bytes;
3280     }
3281 
3282     /*
3283      * It is expected that the image file is large enough to actually contain
3284      * all of the allocated clusters (otherwise we get failing reads after
3285      * EOF). Extend the image to the last allocated sector.
3286      */
3287     file_length = bdrv_co_getlength(s->data_file->bs);
3288     if (file_length < 0) {
3289         error_setg_errno(errp, -file_length, "Could not get file size");
3290         ret = file_length;
3291         goto out;
3292     }
3293 
3294     if (host_offset + cur_bytes > file_length) {
3295         if (mode == PREALLOC_MODE_METADATA) {
3296             mode = PREALLOC_MODE_OFF;
3297         }
3298         ret = bdrv_co_truncate(s->data_file, host_offset + cur_bytes, false,
3299                                mode, 0, errp);
3300         if (ret < 0) {
3301             goto out;
3302         }
3303     }
3304 
3305     ret = 0;
3306 
3307 out:
3308     qcow2_handle_l2meta(bs, &meta, false);
3309     return ret;
3310 }
3311 
3312 /* qcow2_refcount_metadata_size:
3313  * @clusters: number of clusters to refcount (including data and L1/L2 tables)
3314  * @cluster_size: size of a cluster, in bytes
3315  * @refcount_order: refcount bits power-of-2 exponent
3316  * @generous_increase: allow for the refcount table to be 1.5x as large as it
3317  *                     needs to be
3318  *
3319  * Returns: Number of bytes required for refcount blocks and table metadata.
3320  */
3321 int64_t qcow2_refcount_metadata_size(int64_t clusters, size_t cluster_size,
3322                                      int refcount_order, bool generous_increase,
3323                                      uint64_t *refblock_count)
3324 {
3325     /*
3326      * Every host cluster is reference-counted, including metadata (even
3327      * refcount metadata is recursively included).
3328      *
3329      * An accurate formula for the size of refcount metadata size is difficult
3330      * to derive.  An easier method of calculation is finding the fixed point
3331      * where no further refcount blocks or table clusters are required to
3332      * reference count every cluster.
3333      */
3334     int64_t blocks_per_table_cluster = cluster_size / REFTABLE_ENTRY_SIZE;
3335     int64_t refcounts_per_block = cluster_size * 8 / (1 << refcount_order);
3336     int64_t table = 0;  /* number of refcount table clusters */
3337     int64_t blocks = 0; /* number of refcount block clusters */
3338     int64_t last;
3339     int64_t n = 0;
3340 
3341     do {
3342         last = n;
3343         blocks = DIV_ROUND_UP(clusters + table + blocks, refcounts_per_block);
3344         table = DIV_ROUND_UP(blocks, blocks_per_table_cluster);
3345         n = clusters + blocks + table;
3346 
3347         if (n == last && generous_increase) {
3348             clusters += DIV_ROUND_UP(table, 2);
3349             n = 0; /* force another loop */
3350             generous_increase = false;
3351         }
3352     } while (n != last);
3353 
3354     if (refblock_count) {
3355         *refblock_count = blocks;
3356     }
3357 
3358     return (blocks + table) * cluster_size;
3359 }
3360 
3361 /**
3362  * qcow2_calc_prealloc_size:
3363  * @total_size: virtual disk size in bytes
3364  * @cluster_size: cluster size in bytes
3365  * @refcount_order: refcount bits power-of-2 exponent
3366  * @extended_l2: true if the image has extended L2 entries
3367  *
3368  * Returns: Total number of bytes required for the fully allocated image
3369  * (including metadata).
3370  */
3371 static int64_t qcow2_calc_prealloc_size(int64_t total_size,
3372                                         size_t cluster_size,
3373                                         int refcount_order,
3374                                         bool extended_l2)
3375 {
3376     int64_t meta_size = 0;
3377     uint64_t nl1e, nl2e;
3378     int64_t aligned_total_size = ROUND_UP(total_size, cluster_size);
3379     size_t l2e_size = extended_l2 ? L2E_SIZE_EXTENDED : L2E_SIZE_NORMAL;
3380 
3381     /* header: 1 cluster */
3382     meta_size += cluster_size;
3383 
3384     /* total size of L2 tables */
3385     nl2e = aligned_total_size / cluster_size;
3386     nl2e = ROUND_UP(nl2e, cluster_size / l2e_size);
3387     meta_size += nl2e * l2e_size;
3388 
3389     /* total size of L1 tables */
3390     nl1e = nl2e * l2e_size / cluster_size;
3391     nl1e = ROUND_UP(nl1e, cluster_size / L1E_SIZE);
3392     meta_size += nl1e * L1E_SIZE;
3393 
3394     /* total size of refcount table and blocks */
3395     meta_size += qcow2_refcount_metadata_size(
3396             (meta_size + aligned_total_size) / cluster_size,
3397             cluster_size, refcount_order, false, NULL);
3398 
3399     return meta_size + aligned_total_size;
3400 }
3401 
3402 static bool validate_cluster_size(size_t cluster_size, bool extended_l2,
3403                                   Error **errp)
3404 {
3405     int cluster_bits = ctz32(cluster_size);
3406     if (cluster_bits < MIN_CLUSTER_BITS || cluster_bits > MAX_CLUSTER_BITS ||
3407         (1 << cluster_bits) != cluster_size)
3408     {
3409         error_setg(errp, "Cluster size must be a power of two between %d and "
3410                    "%dk", 1 << MIN_CLUSTER_BITS, 1 << (MAX_CLUSTER_BITS - 10));
3411         return false;
3412     }
3413 
3414     if (extended_l2) {
3415         unsigned min_cluster_size =
3416             (1 << MIN_CLUSTER_BITS) * QCOW_EXTL2_SUBCLUSTERS_PER_CLUSTER;
3417         if (cluster_size < min_cluster_size) {
3418             error_setg(errp, "Extended L2 entries are only supported with "
3419                        "cluster sizes of at least %u bytes", min_cluster_size);
3420             return false;
3421         }
3422     }
3423 
3424     return true;
3425 }
3426 
3427 static size_t qcow2_opt_get_cluster_size_del(QemuOpts *opts, bool extended_l2,
3428                                              Error **errp)
3429 {
3430     size_t cluster_size;
3431 
3432     cluster_size = qemu_opt_get_size_del(opts, BLOCK_OPT_CLUSTER_SIZE,
3433                                          DEFAULT_CLUSTER_SIZE);
3434     if (!validate_cluster_size(cluster_size, extended_l2, errp)) {
3435         return 0;
3436     }
3437     return cluster_size;
3438 }
3439 
3440 static int qcow2_opt_get_version_del(QemuOpts *opts, Error **errp)
3441 {
3442     char *buf;
3443     int ret;
3444 
3445     buf = qemu_opt_get_del(opts, BLOCK_OPT_COMPAT_LEVEL);
3446     if (!buf) {
3447         ret = 3; /* default */
3448     } else if (!strcmp(buf, "0.10")) {
3449         ret = 2;
3450     } else if (!strcmp(buf, "1.1")) {
3451         ret = 3;
3452     } else {
3453         error_setg(errp, "Invalid compatibility level: '%s'", buf);
3454         ret = -EINVAL;
3455     }
3456     g_free(buf);
3457     return ret;
3458 }
3459 
3460 static uint64_t qcow2_opt_get_refcount_bits_del(QemuOpts *opts, int version,
3461                                                 Error **errp)
3462 {
3463     uint64_t refcount_bits;
3464 
3465     refcount_bits = qemu_opt_get_number_del(opts, BLOCK_OPT_REFCOUNT_BITS, 16);
3466     if (refcount_bits > 64 || !is_power_of_2(refcount_bits)) {
3467         error_setg(errp, "Refcount width must be a power of two and may not "
3468                    "exceed 64 bits");
3469         return 0;
3470     }
3471 
3472     if (version < 3 && refcount_bits != 16) {
3473         error_setg(errp, "Different refcount widths than 16 bits require "
3474                    "compatibility level 1.1 or above (use compat=1.1 or "
3475                    "greater)");
3476         return 0;
3477     }
3478 
3479     return refcount_bits;
3480 }
3481 
3482 static int coroutine_fn GRAPH_UNLOCKED
3483 qcow2_co_create(BlockdevCreateOptions *create_options, Error **errp)
3484 {
3485     ERRP_GUARD();
3486     BlockdevCreateOptionsQcow2 *qcow2_opts;
3487     QDict *options;
3488 
3489     /*
3490      * Open the image file and write a minimal qcow2 header.
3491      *
3492      * We keep things simple and start with a zero-sized image. We also
3493      * do without refcount blocks or a L1 table for now. We'll fix the
3494      * inconsistency later.
3495      *
3496      * We do need a refcount table because growing the refcount table means
3497      * allocating two new refcount blocks - the second of which would be at
3498      * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
3499      * size for any qcow2 image.
3500      */
3501     BlockBackend *blk = NULL;
3502     BlockDriverState *bs = NULL;
3503     BlockDriverState *data_bs = NULL;
3504     QCowHeader *header;
3505     size_t cluster_size;
3506     int version;
3507     int refcount_order;
3508     uint64_t *refcount_table;
3509     int ret;
3510     uint8_t compression_type = QCOW2_COMPRESSION_TYPE_ZLIB;
3511 
3512     assert(create_options->driver == BLOCKDEV_DRIVER_QCOW2);
3513     qcow2_opts = &create_options->u.qcow2;
3514 
3515     bs = bdrv_co_open_blockdev_ref(qcow2_opts->file, errp);
3516     if (bs == NULL) {
3517         return -EIO;
3518     }
3519 
3520     /* Validate options and set default values */
3521     if (!QEMU_IS_ALIGNED(qcow2_opts->size, BDRV_SECTOR_SIZE)) {
3522         error_setg(errp, "Image size must be a multiple of %u bytes",
3523                    (unsigned) BDRV_SECTOR_SIZE);
3524         ret = -EINVAL;
3525         goto out;
3526     }
3527 
3528     if (qcow2_opts->has_version) {
3529         switch (qcow2_opts->version) {
3530         case BLOCKDEV_QCOW2_VERSION_V2:
3531             version = 2;
3532             break;
3533         case BLOCKDEV_QCOW2_VERSION_V3:
3534             version = 3;
3535             break;
3536         default:
3537             g_assert_not_reached();
3538         }
3539     } else {
3540         version = 3;
3541     }
3542 
3543     if (qcow2_opts->has_cluster_size) {
3544         cluster_size = qcow2_opts->cluster_size;
3545     } else {
3546         cluster_size = DEFAULT_CLUSTER_SIZE;
3547     }
3548 
3549     if (!qcow2_opts->has_extended_l2) {
3550         qcow2_opts->extended_l2 = false;
3551     }
3552     if (qcow2_opts->extended_l2) {
3553         if (version < 3) {
3554             error_setg(errp, "Extended L2 entries are only supported with "
3555                        "compatibility level 1.1 and above (use version=v3 or "
3556                        "greater)");
3557             ret = -EINVAL;
3558             goto out;
3559         }
3560     }
3561 
3562     if (!validate_cluster_size(cluster_size, qcow2_opts->extended_l2, errp)) {
3563         ret = -EINVAL;
3564         goto out;
3565     }
3566 
3567     if (!qcow2_opts->has_preallocation) {
3568         qcow2_opts->preallocation = PREALLOC_MODE_OFF;
3569     }
3570     if (qcow2_opts->backing_file &&
3571         qcow2_opts->preallocation != PREALLOC_MODE_OFF &&
3572         !qcow2_opts->extended_l2)
3573     {
3574         error_setg(errp, "Backing file and preallocation can only be used at "
3575                    "the same time if extended_l2 is on");
3576         ret = -EINVAL;
3577         goto out;
3578     }
3579     if (qcow2_opts->has_backing_fmt && !qcow2_opts->backing_file) {
3580         error_setg(errp, "Backing format cannot be used without backing file");
3581         ret = -EINVAL;
3582         goto out;
3583     }
3584 
3585     if (!qcow2_opts->has_lazy_refcounts) {
3586         qcow2_opts->lazy_refcounts = false;
3587     }
3588     if (version < 3 && qcow2_opts->lazy_refcounts) {
3589         error_setg(errp, "Lazy refcounts only supported with compatibility "
3590                    "level 1.1 and above (use version=v3 or greater)");
3591         ret = -EINVAL;
3592         goto out;
3593     }
3594 
3595     if (!qcow2_opts->has_refcount_bits) {
3596         qcow2_opts->refcount_bits = 16;
3597     }
3598     if (qcow2_opts->refcount_bits > 64 ||
3599         !is_power_of_2(qcow2_opts->refcount_bits))
3600     {
3601         error_setg(errp, "Refcount width must be a power of two and may not "
3602                    "exceed 64 bits");
3603         ret = -EINVAL;
3604         goto out;
3605     }
3606     if (version < 3 && qcow2_opts->refcount_bits != 16) {
3607         error_setg(errp, "Different refcount widths than 16 bits require "
3608                    "compatibility level 1.1 or above (use version=v3 or "
3609                    "greater)");
3610         ret = -EINVAL;
3611         goto out;
3612     }
3613     refcount_order = ctz32(qcow2_opts->refcount_bits);
3614 
3615     if (qcow2_opts->data_file_raw && !qcow2_opts->data_file) {
3616         error_setg(errp, "data-file-raw requires data-file");
3617         ret = -EINVAL;
3618         goto out;
3619     }
3620     if (qcow2_opts->data_file_raw && qcow2_opts->backing_file) {
3621         error_setg(errp, "Backing file and data-file-raw cannot be used at "
3622                    "the same time");
3623         ret = -EINVAL;
3624         goto out;
3625     }
3626     if (qcow2_opts->data_file_raw &&
3627         qcow2_opts->preallocation == PREALLOC_MODE_OFF)
3628     {
3629         /*
3630          * data-file-raw means that "the external data file can be
3631          * read as a consistent standalone raw image without looking
3632          * at the qcow2 metadata."  It does not say that the metadata
3633          * must be ignored, though (and the qcow2 driver in fact does
3634          * not ignore it), so the L1/L2 tables must be present and
3635          * give a 1:1 mapping, so you get the same result regardless
3636          * of whether you look at the metadata or whether you ignore
3637          * it.
3638          */
3639         qcow2_opts->preallocation = PREALLOC_MODE_METADATA;
3640 
3641         /*
3642          * Cannot use preallocation with backing files, but giving a
3643          * backing file when specifying data_file_raw is an error
3644          * anyway.
3645          */
3646         assert(!qcow2_opts->backing_file);
3647     }
3648 
3649     if (qcow2_opts->data_file) {
3650         if (version < 3) {
3651             error_setg(errp, "External data files are only supported with "
3652                        "compatibility level 1.1 and above (use version=v3 or "
3653                        "greater)");
3654             ret = -EINVAL;
3655             goto out;
3656         }
3657         data_bs = bdrv_co_open_blockdev_ref(qcow2_opts->data_file, errp);
3658         if (data_bs == NULL) {
3659             ret = -EIO;
3660             goto out;
3661         }
3662     }
3663 
3664     if (qcow2_opts->has_compression_type &&
3665         qcow2_opts->compression_type != QCOW2_COMPRESSION_TYPE_ZLIB) {
3666 
3667         ret = -EINVAL;
3668 
3669         if (version < 3) {
3670             error_setg(errp, "Non-zlib compression type is only supported with "
3671                        "compatibility level 1.1 and above (use version=v3 or "
3672                        "greater)");
3673             goto out;
3674         }
3675 
3676         switch (qcow2_opts->compression_type) {
3677 #ifdef CONFIG_ZSTD
3678         case QCOW2_COMPRESSION_TYPE_ZSTD:
3679             break;
3680 #endif
3681         default:
3682             error_setg(errp, "Unknown compression type");
3683             goto out;
3684         }
3685 
3686         compression_type = qcow2_opts->compression_type;
3687     }
3688 
3689     /* Create BlockBackend to write to the image */
3690     blk = blk_co_new_with_bs(bs, BLK_PERM_WRITE | BLK_PERM_RESIZE, BLK_PERM_ALL,
3691                              errp);
3692     if (!blk) {
3693         ret = -EPERM;
3694         goto out;
3695     }
3696     blk_set_allow_write_beyond_eof(blk, true);
3697 
3698     /* Write the header */
3699     QEMU_BUILD_BUG_ON((1 << MIN_CLUSTER_BITS) < sizeof(*header));
3700     header = g_malloc0(cluster_size);
3701     *header = (QCowHeader) {
3702         .magic                      = cpu_to_be32(QCOW_MAGIC),
3703         .version                    = cpu_to_be32(version),
3704         .cluster_bits               = cpu_to_be32(ctz32(cluster_size)),
3705         .size                       = cpu_to_be64(0),
3706         .l1_table_offset            = cpu_to_be64(0),
3707         .l1_size                    = cpu_to_be32(0),
3708         .refcount_table_offset      = cpu_to_be64(cluster_size),
3709         .refcount_table_clusters    = cpu_to_be32(1),
3710         .refcount_order             = cpu_to_be32(refcount_order),
3711         /* don't deal with endianness since compression_type is 1 byte long */
3712         .compression_type           = compression_type,
3713         .header_length              = cpu_to_be32(sizeof(*header)),
3714     };
3715 
3716     /* We'll update this to correct value later */
3717     header->crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
3718 
3719     if (qcow2_opts->lazy_refcounts) {
3720         header->compatible_features |=
3721             cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS);
3722     }
3723     if (data_bs) {
3724         header->incompatible_features |=
3725             cpu_to_be64(QCOW2_INCOMPAT_DATA_FILE);
3726     }
3727     if (qcow2_opts->data_file_raw) {
3728         header->autoclear_features |=
3729             cpu_to_be64(QCOW2_AUTOCLEAR_DATA_FILE_RAW);
3730     }
3731     if (compression_type != QCOW2_COMPRESSION_TYPE_ZLIB) {
3732         header->incompatible_features |=
3733             cpu_to_be64(QCOW2_INCOMPAT_COMPRESSION);
3734     }
3735 
3736     if (qcow2_opts->extended_l2) {
3737         header->incompatible_features |=
3738             cpu_to_be64(QCOW2_INCOMPAT_EXTL2);
3739     }
3740 
3741     ret = blk_co_pwrite(blk, 0, cluster_size, header, 0);
3742     g_free(header);
3743     if (ret < 0) {
3744         error_setg_errno(errp, -ret, "Could not write qcow2 header");
3745         goto out;
3746     }
3747 
3748     /* Write a refcount table with one refcount block */
3749     refcount_table = g_malloc0(2 * cluster_size);
3750     refcount_table[0] = cpu_to_be64(2 * cluster_size);
3751     ret = blk_co_pwrite(blk, cluster_size, 2 * cluster_size, refcount_table, 0);
3752     g_free(refcount_table);
3753 
3754     if (ret < 0) {
3755         error_setg_errno(errp, -ret, "Could not write refcount table");
3756         goto out;
3757     }
3758 
3759     blk_co_unref(blk);
3760     blk = NULL;
3761 
3762     /*
3763      * And now open the image and make it consistent first (i.e. increase the
3764      * refcount of the cluster that is occupied by the header and the refcount
3765      * table)
3766      */
3767     options = qdict_new();
3768     qdict_put_str(options, "driver", "qcow2");
3769     qdict_put_str(options, "file", bs->node_name);
3770     if (data_bs) {
3771         qdict_put_str(options, "data-file", data_bs->node_name);
3772     }
3773     blk = blk_co_new_open(NULL, NULL, options,
3774                           BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_NO_FLUSH,
3775                           errp);
3776     if (blk == NULL) {
3777         ret = -EIO;
3778         goto out;
3779     }
3780 
3781     bdrv_graph_co_rdlock();
3782     ret = qcow2_alloc_clusters(blk_bs(blk), 3 * cluster_size);
3783     if (ret < 0) {
3784         bdrv_graph_co_rdunlock();
3785         error_setg_errno(errp, -ret, "Could not allocate clusters for qcow2 "
3786                          "header and refcount table");
3787         goto out;
3788 
3789     } else if (ret != 0) {
3790         error_report("Huh, first cluster in empty image is already in use?");
3791         abort();
3792     }
3793 
3794     /* Set the external data file if necessary */
3795     if (data_bs) {
3796         BDRVQcow2State *s = blk_bs(blk)->opaque;
3797         s->image_data_file = g_strdup(data_bs->filename);
3798     }
3799 
3800     /* Create a full header (including things like feature table) */
3801     ret = qcow2_update_header(blk_bs(blk));
3802     bdrv_graph_co_rdunlock();
3803 
3804     if (ret < 0) {
3805         error_setg_errno(errp, -ret, "Could not update qcow2 header");
3806         goto out;
3807     }
3808 
3809     /* Okay, now that we have a valid image, let's give it the right size */
3810     ret = blk_co_truncate(blk, qcow2_opts->size, false,
3811                           qcow2_opts->preallocation, 0, errp);
3812     if (ret < 0) {
3813         error_prepend(errp, "Could not resize image: ");
3814         goto out;
3815     }
3816 
3817     /* Want a backing file? There you go. */
3818     if (qcow2_opts->backing_file) {
3819         const char *backing_format = NULL;
3820 
3821         if (qcow2_opts->has_backing_fmt) {
3822             backing_format = BlockdevDriver_str(qcow2_opts->backing_fmt);
3823         }
3824 
3825         bdrv_graph_co_rdlock();
3826         ret = bdrv_co_change_backing_file(blk_bs(blk), qcow2_opts->backing_file,
3827                                           backing_format, false);
3828         bdrv_graph_co_rdunlock();
3829 
3830         if (ret < 0) {
3831             error_setg_errno(errp, -ret, "Could not assign backing file '%s' "
3832                              "with format '%s'", qcow2_opts->backing_file,
3833                              backing_format);
3834             goto out;
3835         }
3836     }
3837 
3838     /* Want encryption? There you go. */
3839     if (qcow2_opts->encrypt) {
3840         bdrv_graph_co_rdlock();
3841         ret = qcow2_set_up_encryption(blk_bs(blk), qcow2_opts->encrypt, errp);
3842         bdrv_graph_co_rdunlock();
3843 
3844         if (ret < 0) {
3845             goto out;
3846         }
3847     }
3848 
3849     blk_co_unref(blk);
3850     blk = NULL;
3851 
3852     /* Reopen the image without BDRV_O_NO_FLUSH to flush it before returning.
3853      * Using BDRV_O_NO_IO, since encryption is now setup we don't want to
3854      * have to setup decryption context. We're not doing any I/O on the top
3855      * level BlockDriverState, only lower layers, where BDRV_O_NO_IO does
3856      * not have effect.
3857      */
3858     options = qdict_new();
3859     qdict_put_str(options, "driver", "qcow2");
3860     qdict_put_str(options, "file", bs->node_name);
3861     if (data_bs) {
3862         qdict_put_str(options, "data-file", data_bs->node_name);
3863     }
3864     blk = blk_co_new_open(NULL, NULL, options,
3865                           BDRV_O_RDWR | BDRV_O_NO_BACKING | BDRV_O_NO_IO,
3866                           errp);
3867     if (blk == NULL) {
3868         ret = -EIO;
3869         goto out;
3870     }
3871 
3872     ret = 0;
3873 out:
3874     blk_co_unref(blk);
3875     bdrv_co_unref(bs);
3876     bdrv_co_unref(data_bs);
3877     return ret;
3878 }
3879 
3880 static int coroutine_fn GRAPH_UNLOCKED
3881 qcow2_co_create_opts(BlockDriver *drv, const char *filename, QemuOpts *opts,
3882                      Error **errp)
3883 {
3884     BlockdevCreateOptions *create_options = NULL;
3885     QDict *qdict;
3886     Visitor *v;
3887     BlockDriverState *bs = NULL;
3888     BlockDriverState *data_bs = NULL;
3889     const char *val;
3890     int ret;
3891 
3892     /* Only the keyval visitor supports the dotted syntax needed for
3893      * encryption, so go through a QDict before getting a QAPI type. Ignore
3894      * options meant for the protocol layer so that the visitor doesn't
3895      * complain. */
3896     qdict = qemu_opts_to_qdict_filtered(opts, NULL, bdrv_qcow2.create_opts,
3897                                         true);
3898 
3899     /* Handle encryption options */
3900     val = qdict_get_try_str(qdict, BLOCK_OPT_ENCRYPT);
3901     if (val && !strcmp(val, "on")) {
3902         qdict_put_str(qdict, BLOCK_OPT_ENCRYPT, "qcow");
3903     } else if (val && !strcmp(val, "off")) {
3904         qdict_del(qdict, BLOCK_OPT_ENCRYPT);
3905     }
3906 
3907     val = qdict_get_try_str(qdict, BLOCK_OPT_ENCRYPT_FORMAT);
3908     if (val && !strcmp(val, "aes")) {
3909         qdict_put_str(qdict, BLOCK_OPT_ENCRYPT_FORMAT, "qcow");
3910     }
3911 
3912     /* Convert compat=0.10/1.1 into compat=v2/v3, to be renamed into
3913      * version=v2/v3 below. */
3914     val = qdict_get_try_str(qdict, BLOCK_OPT_COMPAT_LEVEL);
3915     if (val && !strcmp(val, "0.10")) {
3916         qdict_put_str(qdict, BLOCK_OPT_COMPAT_LEVEL, "v2");
3917     } else if (val && !strcmp(val, "1.1")) {
3918         qdict_put_str(qdict, BLOCK_OPT_COMPAT_LEVEL, "v3");
3919     }
3920 
3921     /* Change legacy command line options into QMP ones */
3922     static const QDictRenames opt_renames[] = {
3923         { BLOCK_OPT_BACKING_FILE,       "backing-file" },
3924         { BLOCK_OPT_BACKING_FMT,        "backing-fmt" },
3925         { BLOCK_OPT_CLUSTER_SIZE,       "cluster-size" },
3926         { BLOCK_OPT_LAZY_REFCOUNTS,     "lazy-refcounts" },
3927         { BLOCK_OPT_EXTL2,              "extended-l2" },
3928         { BLOCK_OPT_REFCOUNT_BITS,      "refcount-bits" },
3929         { BLOCK_OPT_ENCRYPT,            BLOCK_OPT_ENCRYPT_FORMAT },
3930         { BLOCK_OPT_COMPAT_LEVEL,       "version" },
3931         { BLOCK_OPT_DATA_FILE_RAW,      "data-file-raw" },
3932         { BLOCK_OPT_COMPRESSION_TYPE,   "compression-type" },
3933         { NULL, NULL },
3934     };
3935 
3936     if (!qdict_rename_keys(qdict, opt_renames, errp)) {
3937         ret = -EINVAL;
3938         goto finish;
3939     }
3940 
3941     /* Create and open the file (protocol layer) */
3942     ret = bdrv_co_create_file(filename, opts, errp);
3943     if (ret < 0) {
3944         goto finish;
3945     }
3946 
3947     bs = bdrv_co_open(filename, NULL, NULL,
3948                       BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_PROTOCOL, errp);
3949     if (bs == NULL) {
3950         ret = -EIO;
3951         goto finish;
3952     }
3953 
3954     /* Create and open an external data file (protocol layer) */
3955     val = qdict_get_try_str(qdict, BLOCK_OPT_DATA_FILE);
3956     if (val) {
3957         ret = bdrv_co_create_file(val, opts, errp);
3958         if (ret < 0) {
3959             goto finish;
3960         }
3961 
3962         data_bs = bdrv_co_open(val, NULL, NULL,
3963                                BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_PROTOCOL,
3964                                errp);
3965         if (data_bs == NULL) {
3966             ret = -EIO;
3967             goto finish;
3968         }
3969 
3970         qdict_del(qdict, BLOCK_OPT_DATA_FILE);
3971         qdict_put_str(qdict, "data-file", data_bs->node_name);
3972     }
3973 
3974     /* Set 'driver' and 'node' options */
3975     qdict_put_str(qdict, "driver", "qcow2");
3976     qdict_put_str(qdict, "file", bs->node_name);
3977 
3978     /* Now get the QAPI type BlockdevCreateOptions */
3979     v = qobject_input_visitor_new_flat_confused(qdict, errp);
3980     if (!v) {
3981         ret = -EINVAL;
3982         goto finish;
3983     }
3984 
3985     visit_type_BlockdevCreateOptions(v, NULL, &create_options, errp);
3986     visit_free(v);
3987     if (!create_options) {
3988         ret = -EINVAL;
3989         goto finish;
3990     }
3991 
3992     /* Silently round up size */
3993     create_options->u.qcow2.size = ROUND_UP(create_options->u.qcow2.size,
3994                                             BDRV_SECTOR_SIZE);
3995 
3996     /* Create the qcow2 image (format layer) */
3997     ret = qcow2_co_create(create_options, errp);
3998 finish:
3999     if (ret < 0) {
4000         bdrv_graph_co_rdlock();
4001         bdrv_co_delete_file_noerr(bs);
4002         bdrv_co_delete_file_noerr(data_bs);
4003         bdrv_graph_co_rdunlock();
4004     } else {
4005         ret = 0;
4006     }
4007 
4008     qobject_unref(qdict);
4009     bdrv_co_unref(bs);
4010     bdrv_co_unref(data_bs);
4011     qapi_free_BlockdevCreateOptions(create_options);
4012     return ret;
4013 }
4014 
4015 
4016 static bool coroutine_fn GRAPH_RDLOCK
4017 is_zero(BlockDriverState *bs, int64_t offset, int64_t bytes)
4018 {
4019     int64_t nr;
4020     int res;
4021 
4022     /* Clamp to image length, before checking status of underlying sectors */
4023     if (offset + bytes > bs->total_sectors * BDRV_SECTOR_SIZE) {
4024         bytes = bs->total_sectors * BDRV_SECTOR_SIZE - offset;
4025     }
4026 
4027     if (!bytes) {
4028         return true;
4029     }
4030 
4031     /*
4032      * bdrv_block_status_above doesn't merge different types of zeros, for
4033      * example, zeros which come from the region which is unallocated in
4034      * the whole backing chain, and zeros which come because of a short
4035      * backing file. So, we need a loop.
4036      */
4037     do {
4038         res = bdrv_co_block_status_above(bs, NULL, offset, bytes, &nr, NULL, NULL);
4039         offset += nr;
4040         bytes -= nr;
4041     } while (res >= 0 && (res & BDRV_BLOCK_ZERO) && nr && bytes);
4042 
4043     return res >= 0 && (res & BDRV_BLOCK_ZERO) && bytes == 0;
4044 }
4045 
4046 static int coroutine_fn GRAPH_RDLOCK
4047 qcow2_co_pwrite_zeroes(BlockDriverState *bs, int64_t offset, int64_t bytes,
4048                        BdrvRequestFlags flags)
4049 {
4050     int ret;
4051     BDRVQcow2State *s = bs->opaque;
4052 
4053     uint32_t head = offset_into_subcluster(s, offset);
4054     uint32_t tail = ROUND_UP(offset + bytes, s->subcluster_size) -
4055         (offset + bytes);
4056 
4057     trace_qcow2_pwrite_zeroes_start_req(qemu_coroutine_self(), offset, bytes);
4058     if (offset + bytes == bs->total_sectors * BDRV_SECTOR_SIZE) {
4059         tail = 0;
4060     }
4061 
4062     if (head || tail) {
4063         uint64_t off;
4064         unsigned int nr;
4065         QCow2SubclusterType type;
4066 
4067         assert(head + bytes + tail <= s->subcluster_size);
4068 
4069         /* check whether remainder of cluster already reads as zero */
4070         if (!(is_zero(bs, offset - head, head) &&
4071               is_zero(bs, offset + bytes, tail))) {
4072             return -ENOTSUP;
4073         }
4074 
4075         qemu_co_mutex_lock(&s->lock);
4076         /* We can have new write after previous check */
4077         offset -= head;
4078         bytes = s->subcluster_size;
4079         nr = s->subcluster_size;
4080         ret = qcow2_get_host_offset(bs, offset, &nr, &off, &type);
4081         if (ret < 0 ||
4082             (type != QCOW2_SUBCLUSTER_UNALLOCATED_PLAIN &&
4083              type != QCOW2_SUBCLUSTER_UNALLOCATED_ALLOC &&
4084              type != QCOW2_SUBCLUSTER_ZERO_PLAIN &&
4085              type != QCOW2_SUBCLUSTER_ZERO_ALLOC)) {
4086             qemu_co_mutex_unlock(&s->lock);
4087             return ret < 0 ? ret : -ENOTSUP;
4088         }
4089     } else {
4090         qemu_co_mutex_lock(&s->lock);
4091     }
4092 
4093     trace_qcow2_pwrite_zeroes(qemu_coroutine_self(), offset, bytes);
4094 
4095     /* Whatever is left can use real zero subclusters */
4096     ret = qcow2_subcluster_zeroize(bs, offset, bytes, flags);
4097     qemu_co_mutex_unlock(&s->lock);
4098 
4099     return ret;
4100 }
4101 
4102 static int coroutine_fn GRAPH_RDLOCK
4103 qcow2_co_pdiscard(BlockDriverState *bs, int64_t offset, int64_t bytes)
4104 {
4105     int ret;
4106     BDRVQcow2State *s = bs->opaque;
4107 
4108     /* If the image does not support QCOW_OFLAG_ZERO then discarding
4109      * clusters could expose stale data from the backing file. */
4110     if (s->qcow_version < 3 && bs->backing) {
4111         return -ENOTSUP;
4112     }
4113 
4114     if (!QEMU_IS_ALIGNED(offset | bytes, s->cluster_size)) {
4115         assert(bytes < s->cluster_size);
4116         /* Ignore partial clusters, except for the special case of the
4117          * complete partial cluster at the end of an unaligned file */
4118         if (!QEMU_IS_ALIGNED(offset, s->cluster_size) ||
4119             offset + bytes != bs->total_sectors * BDRV_SECTOR_SIZE) {
4120             return -ENOTSUP;
4121         }
4122     }
4123 
4124     qemu_co_mutex_lock(&s->lock);
4125     ret = qcow2_cluster_discard(bs, offset, bytes, QCOW2_DISCARD_REQUEST,
4126                                 false);
4127     qemu_co_mutex_unlock(&s->lock);
4128     return ret;
4129 }
4130 
4131 static int coroutine_fn GRAPH_RDLOCK
4132 qcow2_co_copy_range_from(BlockDriverState *bs,
4133                          BdrvChild *src, int64_t src_offset,
4134                          BdrvChild *dst, int64_t dst_offset,
4135                          int64_t bytes, BdrvRequestFlags read_flags,
4136                          BdrvRequestFlags write_flags)
4137 {
4138     BDRVQcow2State *s = bs->opaque;
4139     int ret;
4140     unsigned int cur_bytes; /* number of bytes in current iteration */
4141     BdrvChild *child = NULL;
4142     BdrvRequestFlags cur_write_flags;
4143 
4144     assert(!bs->encrypted);
4145     qemu_co_mutex_lock(&s->lock);
4146 
4147     while (bytes != 0) {
4148         uint64_t copy_offset = 0;
4149         QCow2SubclusterType type;
4150         /* prepare next request */
4151         cur_bytes = MIN(bytes, INT_MAX);
4152         cur_write_flags = write_flags;
4153 
4154         ret = qcow2_get_host_offset(bs, src_offset, &cur_bytes,
4155                                     &copy_offset, &type);
4156         if (ret < 0) {
4157             goto out;
4158         }
4159 
4160         switch (type) {
4161         case QCOW2_SUBCLUSTER_UNALLOCATED_PLAIN:
4162         case QCOW2_SUBCLUSTER_UNALLOCATED_ALLOC:
4163             if (bs->backing && bs->backing->bs) {
4164                 int64_t backing_length = bdrv_co_getlength(bs->backing->bs);
4165                 if (src_offset >= backing_length) {
4166                     cur_write_flags |= BDRV_REQ_ZERO_WRITE;
4167                 } else {
4168                     child = bs->backing;
4169                     cur_bytes = MIN(cur_bytes, backing_length - src_offset);
4170                     copy_offset = src_offset;
4171                 }
4172             } else {
4173                 cur_write_flags |= BDRV_REQ_ZERO_WRITE;
4174             }
4175             break;
4176 
4177         case QCOW2_SUBCLUSTER_ZERO_PLAIN:
4178         case QCOW2_SUBCLUSTER_ZERO_ALLOC:
4179             cur_write_flags |= BDRV_REQ_ZERO_WRITE;
4180             break;
4181 
4182         case QCOW2_SUBCLUSTER_COMPRESSED:
4183             ret = -ENOTSUP;
4184             goto out;
4185 
4186         case QCOW2_SUBCLUSTER_NORMAL:
4187             child = s->data_file;
4188             break;
4189 
4190         default:
4191             abort();
4192         }
4193         qemu_co_mutex_unlock(&s->lock);
4194         ret = bdrv_co_copy_range_from(child,
4195                                       copy_offset,
4196                                       dst, dst_offset,
4197                                       cur_bytes, read_flags, cur_write_flags);
4198         qemu_co_mutex_lock(&s->lock);
4199         if (ret < 0) {
4200             goto out;
4201         }
4202 
4203         bytes -= cur_bytes;
4204         src_offset += cur_bytes;
4205         dst_offset += cur_bytes;
4206     }
4207     ret = 0;
4208 
4209 out:
4210     qemu_co_mutex_unlock(&s->lock);
4211     return ret;
4212 }
4213 
4214 static int coroutine_fn GRAPH_RDLOCK
4215 qcow2_co_copy_range_to(BlockDriverState *bs,
4216                        BdrvChild *src, int64_t src_offset,
4217                        BdrvChild *dst, int64_t dst_offset,
4218                        int64_t bytes, BdrvRequestFlags read_flags,
4219                        BdrvRequestFlags write_flags)
4220 {
4221     BDRVQcow2State *s = bs->opaque;
4222     int ret;
4223     unsigned int cur_bytes; /* number of sectors in current iteration */
4224     uint64_t host_offset;
4225     QCowL2Meta *l2meta = NULL;
4226 
4227     assert(!bs->encrypted);
4228 
4229     qemu_co_mutex_lock(&s->lock);
4230 
4231     while (bytes != 0) {
4232 
4233         l2meta = NULL;
4234 
4235         cur_bytes = MIN(bytes, INT_MAX);
4236 
4237         /* TODO:
4238          * If src->bs == dst->bs, we could simply copy by incrementing
4239          * the refcnt, without copying user data.
4240          * Or if src->bs == dst->bs->backing->bs, we could copy by discarding. */
4241         ret = qcow2_alloc_host_offset(bs, dst_offset, &cur_bytes,
4242                                       &host_offset, &l2meta);
4243         if (ret < 0) {
4244             goto fail;
4245         }
4246 
4247         ret = qcow2_pre_write_overlap_check(bs, 0, host_offset, cur_bytes,
4248                                             true);
4249         if (ret < 0) {
4250             goto fail;
4251         }
4252 
4253         qemu_co_mutex_unlock(&s->lock);
4254         ret = bdrv_co_copy_range_to(src, src_offset, s->data_file, host_offset,
4255                                     cur_bytes, read_flags, write_flags);
4256         qemu_co_mutex_lock(&s->lock);
4257         if (ret < 0) {
4258             goto fail;
4259         }
4260 
4261         ret = qcow2_handle_l2meta(bs, &l2meta, true);
4262         if (ret) {
4263             goto fail;
4264         }
4265 
4266         bytes -= cur_bytes;
4267         src_offset += cur_bytes;
4268         dst_offset += cur_bytes;
4269     }
4270     ret = 0;
4271 
4272 fail:
4273     qcow2_handle_l2meta(bs, &l2meta, false);
4274 
4275     qemu_co_mutex_unlock(&s->lock);
4276 
4277     trace_qcow2_writev_done_req(qemu_coroutine_self(), ret);
4278 
4279     return ret;
4280 }
4281 
4282 static int coroutine_fn GRAPH_RDLOCK
4283 qcow2_co_truncate(BlockDriverState *bs, int64_t offset, bool exact,
4284                   PreallocMode prealloc, BdrvRequestFlags flags, Error **errp)
4285 {
4286     ERRP_GUARD();
4287     BDRVQcow2State *s = bs->opaque;
4288     uint64_t old_length;
4289     int64_t new_l1_size;
4290     int ret;
4291     QDict *options;
4292 
4293     if (prealloc != PREALLOC_MODE_OFF && prealloc != PREALLOC_MODE_METADATA &&
4294         prealloc != PREALLOC_MODE_FALLOC && prealloc != PREALLOC_MODE_FULL)
4295     {
4296         error_setg(errp, "Unsupported preallocation mode '%s'",
4297                    PreallocMode_str(prealloc));
4298         return -ENOTSUP;
4299     }
4300 
4301     if (!QEMU_IS_ALIGNED(offset, BDRV_SECTOR_SIZE)) {
4302         error_setg(errp, "The new size must be a multiple of %u",
4303                    (unsigned) BDRV_SECTOR_SIZE);
4304         return -EINVAL;
4305     }
4306 
4307     qemu_co_mutex_lock(&s->lock);
4308 
4309     /*
4310      * Even though we store snapshot size for all images, it was not
4311      * required until v3, so it is not safe to proceed for v2.
4312      */
4313     if (s->nb_snapshots && s->qcow_version < 3) {
4314         error_setg(errp, "Can't resize a v2 image which has snapshots");
4315         ret = -ENOTSUP;
4316         goto fail;
4317     }
4318 
4319     /* See qcow2-bitmap.c for which bitmap scenarios prevent a resize. */
4320     if (qcow2_truncate_bitmaps_check(bs, errp)) {
4321         ret = -ENOTSUP;
4322         goto fail;
4323     }
4324 
4325     old_length = bs->total_sectors * BDRV_SECTOR_SIZE;
4326     new_l1_size = size_to_l1(s, offset);
4327 
4328     if (offset < old_length) {
4329         int64_t last_cluster, old_file_size;
4330         if (prealloc != PREALLOC_MODE_OFF) {
4331             error_setg(errp,
4332                        "Preallocation can't be used for shrinking an image");
4333             ret = -EINVAL;
4334             goto fail;
4335         }
4336 
4337         ret = qcow2_cluster_discard(bs, ROUND_UP(offset, s->cluster_size),
4338                                     old_length - ROUND_UP(offset,
4339                                                           s->cluster_size),
4340                                     QCOW2_DISCARD_ALWAYS, true);
4341         if (ret < 0) {
4342             error_setg_errno(errp, -ret, "Failed to discard cropped clusters");
4343             goto fail;
4344         }
4345 
4346         ret = qcow2_shrink_l1_table(bs, new_l1_size);
4347         if (ret < 0) {
4348             error_setg_errno(errp, -ret,
4349                              "Failed to reduce the number of L2 tables");
4350             goto fail;
4351         }
4352 
4353         ret = qcow2_shrink_reftable(bs);
4354         if (ret < 0) {
4355             error_setg_errno(errp, -ret,
4356                              "Failed to discard unused refblocks");
4357             goto fail;
4358         }
4359 
4360         old_file_size = bdrv_co_getlength(bs->file->bs);
4361         if (old_file_size < 0) {
4362             error_setg_errno(errp, -old_file_size,
4363                              "Failed to inquire current file length");
4364             ret = old_file_size;
4365             goto fail;
4366         }
4367         last_cluster = qcow2_get_last_cluster(bs, old_file_size);
4368         if (last_cluster < 0) {
4369             error_setg_errno(errp, -last_cluster,
4370                              "Failed to find the last cluster");
4371             ret = last_cluster;
4372             goto fail;
4373         }
4374         if ((last_cluster + 1) * s->cluster_size < old_file_size) {
4375             Error *local_err = NULL;
4376 
4377             /*
4378              * Do not pass @exact here: It will not help the user if
4379              * we get an error here just because they wanted to shrink
4380              * their qcow2 image (on a block device) with qemu-img.
4381              * (And on the qcow2 layer, the @exact requirement is
4382              * always fulfilled, so there is no need to pass it on.)
4383              */
4384             bdrv_co_truncate(bs->file, (last_cluster + 1) * s->cluster_size,
4385                              false, PREALLOC_MODE_OFF, 0, &local_err);
4386             if (local_err) {
4387                 warn_reportf_err(local_err,
4388                                  "Failed to truncate the tail of the image: ");
4389             }
4390         }
4391     } else {
4392         ret = qcow2_grow_l1_table(bs, new_l1_size, true);
4393         if (ret < 0) {
4394             error_setg_errno(errp, -ret, "Failed to grow the L1 table");
4395             goto fail;
4396         }
4397 
4398         if (data_file_is_raw(bs) && prealloc == PREALLOC_MODE_OFF) {
4399             /*
4400              * When creating a qcow2 image with data-file-raw, we enforce
4401              * at least prealloc=metadata, so that the L1/L2 tables are
4402              * fully allocated and reading from the data file will return
4403              * the same data as reading from the qcow2 image.  When the
4404              * image is grown, we must consequently preallocate the
4405              * metadata structures to cover the added area.
4406              */
4407             prealloc = PREALLOC_MODE_METADATA;
4408         }
4409     }
4410 
4411     switch (prealloc) {
4412     case PREALLOC_MODE_OFF:
4413         if (has_data_file(bs)) {
4414             /*
4415              * If the caller wants an exact resize, the external data
4416              * file should be resized to the exact target size, too,
4417              * so we pass @exact here.
4418              */
4419             ret = bdrv_co_truncate(s->data_file, offset, exact, prealloc, 0,
4420                                    errp);
4421             if (ret < 0) {
4422                 goto fail;
4423             }
4424         }
4425         break;
4426 
4427     case PREALLOC_MODE_METADATA:
4428         ret = preallocate_co(bs, old_length, offset, prealloc, errp);
4429         if (ret < 0) {
4430             goto fail;
4431         }
4432         break;
4433 
4434     case PREALLOC_MODE_FALLOC:
4435     case PREALLOC_MODE_FULL:
4436     {
4437         int64_t allocation_start, host_offset, guest_offset;
4438         int64_t clusters_allocated;
4439         int64_t old_file_size, last_cluster, new_file_size;
4440         uint64_t nb_new_data_clusters, nb_new_l2_tables;
4441         bool subclusters_need_allocation = false;
4442 
4443         /* With a data file, preallocation means just allocating the metadata
4444          * and forwarding the truncate request to the data file */
4445         if (has_data_file(bs)) {
4446             ret = preallocate_co(bs, old_length, offset, prealloc, errp);
4447             if (ret < 0) {
4448                 goto fail;
4449             }
4450             break;
4451         }
4452 
4453         old_file_size = bdrv_co_getlength(bs->file->bs);
4454         if (old_file_size < 0) {
4455             error_setg_errno(errp, -old_file_size,
4456                              "Failed to inquire current file length");
4457             ret = old_file_size;
4458             goto fail;
4459         }
4460 
4461         last_cluster = qcow2_get_last_cluster(bs, old_file_size);
4462         if (last_cluster >= 0) {
4463             old_file_size = (last_cluster + 1) * s->cluster_size;
4464         } else {
4465             old_file_size = ROUND_UP(old_file_size, s->cluster_size);
4466         }
4467 
4468         nb_new_data_clusters = (ROUND_UP(offset, s->cluster_size) -
4469             start_of_cluster(s, old_length)) >> s->cluster_bits;
4470 
4471         /* This is an overestimation; we will not actually allocate space for
4472          * these in the file but just make sure the new refcount structures are
4473          * able to cover them so we will not have to allocate new refblocks
4474          * while entering the data blocks in the potentially new L2 tables.
4475          * (We do not actually care where the L2 tables are placed. Maybe they
4476          *  are already allocated or they can be placed somewhere before
4477          *  @old_file_size. It does not matter because they will be fully
4478          *  allocated automatically, so they do not need to be covered by the
4479          *  preallocation. All that matters is that we will not have to allocate
4480          *  new refcount structures for them.) */
4481         nb_new_l2_tables = DIV_ROUND_UP(nb_new_data_clusters,
4482                                         s->cluster_size / l2_entry_size(s));
4483         /* The cluster range may not be aligned to L2 boundaries, so add one L2
4484          * table for a potential head/tail */
4485         nb_new_l2_tables++;
4486 
4487         allocation_start = qcow2_refcount_area(bs, old_file_size,
4488                                                nb_new_data_clusters +
4489                                                nb_new_l2_tables,
4490                                                true, 0, 0);
4491         if (allocation_start < 0) {
4492             error_setg_errno(errp, -allocation_start,
4493                              "Failed to resize refcount structures");
4494             ret = allocation_start;
4495             goto fail;
4496         }
4497 
4498         clusters_allocated = qcow2_alloc_clusters_at(bs, allocation_start,
4499                                                      nb_new_data_clusters);
4500         if (clusters_allocated < 0) {
4501             error_setg_errno(errp, -clusters_allocated,
4502                              "Failed to allocate data clusters");
4503             ret = clusters_allocated;
4504             goto fail;
4505         }
4506 
4507         assert(clusters_allocated == nb_new_data_clusters);
4508 
4509         /* Allocate the data area */
4510         new_file_size = allocation_start +
4511                         nb_new_data_clusters * s->cluster_size;
4512         /*
4513          * Image file grows, so @exact does not matter.
4514          *
4515          * If we need to zero out the new area, try first whether the protocol
4516          * driver can already take care of this.
4517          */
4518         if (flags & BDRV_REQ_ZERO_WRITE) {
4519             ret = bdrv_co_truncate(bs->file, new_file_size, false, prealloc,
4520                                    BDRV_REQ_ZERO_WRITE, NULL);
4521             if (ret >= 0) {
4522                 flags &= ~BDRV_REQ_ZERO_WRITE;
4523                 /* Ensure that we read zeroes and not backing file data */
4524                 subclusters_need_allocation = true;
4525             }
4526         } else {
4527             ret = -1;
4528         }
4529         if (ret < 0) {
4530             ret = bdrv_co_truncate(bs->file, new_file_size, false, prealloc, 0,
4531                                    errp);
4532         }
4533         if (ret < 0) {
4534             error_prepend(errp, "Failed to resize underlying file: ");
4535             qcow2_free_clusters(bs, allocation_start,
4536                                 nb_new_data_clusters * s->cluster_size,
4537                                 QCOW2_DISCARD_OTHER);
4538             goto fail;
4539         }
4540 
4541         /* Create the necessary L2 entries */
4542         host_offset = allocation_start;
4543         guest_offset = old_length;
4544         while (nb_new_data_clusters) {
4545             int64_t nb_clusters = MIN(
4546                 nb_new_data_clusters,
4547                 s->l2_slice_size - offset_to_l2_slice_index(s, guest_offset));
4548             unsigned cow_start_length = offset_into_cluster(s, guest_offset);
4549             QCowL2Meta allocation;
4550             guest_offset = start_of_cluster(s, guest_offset);
4551             allocation = (QCowL2Meta) {
4552                 .offset       = guest_offset,
4553                 .alloc_offset = host_offset,
4554                 .nb_clusters  = nb_clusters,
4555                 .cow_start    = {
4556                     .offset       = 0,
4557                     .nb_bytes     = cow_start_length,
4558                 },
4559                 .cow_end      = {
4560                     .offset       = nb_clusters << s->cluster_bits,
4561                     .nb_bytes     = 0,
4562                 },
4563                 .prealloc     = !subclusters_need_allocation,
4564             };
4565             qemu_co_queue_init(&allocation.dependent_requests);
4566 
4567             ret = qcow2_alloc_cluster_link_l2(bs, &allocation);
4568             if (ret < 0) {
4569                 error_setg_errno(errp, -ret, "Failed to update L2 tables");
4570                 qcow2_free_clusters(bs, host_offset,
4571                                     nb_new_data_clusters * s->cluster_size,
4572                                     QCOW2_DISCARD_OTHER);
4573                 goto fail;
4574             }
4575 
4576             guest_offset += nb_clusters * s->cluster_size;
4577             host_offset += nb_clusters * s->cluster_size;
4578             nb_new_data_clusters -= nb_clusters;
4579         }
4580         break;
4581     }
4582 
4583     default:
4584         g_assert_not_reached();
4585     }
4586 
4587     if ((flags & BDRV_REQ_ZERO_WRITE) && offset > old_length) {
4588         uint64_t zero_start = QEMU_ALIGN_UP(old_length, s->subcluster_size);
4589 
4590         /*
4591          * Use zero clusters as much as we can. qcow2_subcluster_zeroize()
4592          * requires a subcluster-aligned start. The end may be unaligned if
4593          * it is at the end of the image (which it is here).
4594          */
4595         if (offset > zero_start) {
4596             ret = qcow2_subcluster_zeroize(bs, zero_start, offset - zero_start,
4597                                            0);
4598             if (ret < 0) {
4599                 error_setg_errno(errp, -ret, "Failed to zero out new clusters");
4600                 goto fail;
4601             }
4602         }
4603 
4604         /* Write explicit zeros for the unaligned head */
4605         if (zero_start > old_length) {
4606             uint64_t len = MIN(zero_start, offset) - old_length;
4607             uint8_t *buf = qemu_blockalign0(bs, len);
4608             QEMUIOVector qiov;
4609             qemu_iovec_init_buf(&qiov, buf, len);
4610 
4611             qemu_co_mutex_unlock(&s->lock);
4612             ret = qcow2_co_pwritev_part(bs, old_length, len, &qiov, 0, 0);
4613             qemu_co_mutex_lock(&s->lock);
4614 
4615             qemu_vfree(buf);
4616             if (ret < 0) {
4617                 error_setg_errno(errp, -ret, "Failed to zero out the new area");
4618                 goto fail;
4619             }
4620         }
4621     }
4622 
4623     if (prealloc != PREALLOC_MODE_OFF) {
4624         /* Flush metadata before actually changing the image size */
4625         ret = qcow2_write_caches(bs);
4626         if (ret < 0) {
4627             error_setg_errno(errp, -ret,
4628                              "Failed to flush the preallocated area to disk");
4629             goto fail;
4630         }
4631     }
4632 
4633     bs->total_sectors = offset / BDRV_SECTOR_SIZE;
4634 
4635     /* write updated header.size */
4636     offset = cpu_to_be64(offset);
4637     ret = bdrv_co_pwrite_sync(bs->file, offsetof(QCowHeader, size),
4638                               sizeof(offset), &offset, 0);
4639     if (ret < 0) {
4640         error_setg_errno(errp, -ret, "Failed to update the image size");
4641         goto fail;
4642     }
4643 
4644     s->l1_vm_state_index = new_l1_size;
4645 
4646     /* Update cache sizes */
4647     options = qdict_clone_shallow(bs->options);
4648     ret = qcow2_update_options(bs, options, s->flags, errp);
4649     qobject_unref(options);
4650     if (ret < 0) {
4651         goto fail;
4652     }
4653     ret = 0;
4654 fail:
4655     qemu_co_mutex_unlock(&s->lock);
4656     return ret;
4657 }
4658 
4659 static int coroutine_fn GRAPH_RDLOCK
4660 qcow2_co_pwritev_compressed_task(BlockDriverState *bs,
4661                                  uint64_t offset, uint64_t bytes,
4662                                  QEMUIOVector *qiov, size_t qiov_offset)
4663 {
4664     BDRVQcow2State *s = bs->opaque;
4665     int ret;
4666     ssize_t out_len;
4667     uint8_t *buf, *out_buf;
4668     uint64_t cluster_offset;
4669 
4670     assert(bytes == s->cluster_size || (bytes < s->cluster_size &&
4671            (offset + bytes == bs->total_sectors << BDRV_SECTOR_BITS)));
4672 
4673     buf = qemu_blockalign(bs, s->cluster_size);
4674     if (bytes < s->cluster_size) {
4675         /* Zero-pad last write if image size is not cluster aligned */
4676         memset(buf + bytes, 0, s->cluster_size - bytes);
4677     }
4678     qemu_iovec_to_buf(qiov, qiov_offset, buf, bytes);
4679 
4680     out_buf = g_malloc(s->cluster_size);
4681 
4682     out_len = qcow2_co_compress(bs, out_buf, s->cluster_size - 1,
4683                                 buf, s->cluster_size);
4684     if (out_len == -ENOMEM) {
4685         /* could not compress: write normal cluster */
4686         ret = qcow2_co_pwritev_part(bs, offset, bytes, qiov, qiov_offset, 0);
4687         if (ret < 0) {
4688             goto fail;
4689         }
4690         goto success;
4691     } else if (out_len < 0) {
4692         ret = -EINVAL;
4693         goto fail;
4694     }
4695 
4696     qemu_co_mutex_lock(&s->lock);
4697     ret = qcow2_alloc_compressed_cluster_offset(bs, offset, out_len,
4698                                                 &cluster_offset);
4699     if (ret < 0) {
4700         qemu_co_mutex_unlock(&s->lock);
4701         goto fail;
4702     }
4703 
4704     ret = qcow2_pre_write_overlap_check(bs, 0, cluster_offset, out_len, true);
4705     qemu_co_mutex_unlock(&s->lock);
4706     if (ret < 0) {
4707         goto fail;
4708     }
4709 
4710     BLKDBG_CO_EVENT(s->data_file, BLKDBG_WRITE_COMPRESSED);
4711     ret = bdrv_co_pwrite(s->data_file, cluster_offset, out_len, out_buf, 0);
4712     if (ret < 0) {
4713         goto fail;
4714     }
4715 success:
4716     ret = 0;
4717 fail:
4718     qemu_vfree(buf);
4719     g_free(out_buf);
4720     return ret;
4721 }
4722 
4723 /*
4724  * This function can count as GRAPH_RDLOCK because
4725  * qcow2_co_pwritev_compressed_part() holds the graph lock and keeps it until
4726  * this coroutine has terminated.
4727  */
4728 static int coroutine_fn GRAPH_RDLOCK
4729 qcow2_co_pwritev_compressed_task_entry(AioTask *task)
4730 {
4731     Qcow2AioTask *t = container_of(task, Qcow2AioTask, task);
4732 
4733     assert(!t->subcluster_type && !t->l2meta);
4734 
4735     return qcow2_co_pwritev_compressed_task(t->bs, t->offset, t->bytes, t->qiov,
4736                                             t->qiov_offset);
4737 }
4738 
4739 /*
4740  * XXX: put compressed sectors first, then all the cluster aligned
4741  * tables to avoid losing bytes in alignment
4742  */
4743 static int coroutine_fn GRAPH_RDLOCK
4744 qcow2_co_pwritev_compressed_part(BlockDriverState *bs,
4745                                  int64_t offset, int64_t bytes,
4746                                  QEMUIOVector *qiov, size_t qiov_offset)
4747 {
4748     BDRVQcow2State *s = bs->opaque;
4749     AioTaskPool *aio = NULL;
4750     int ret = 0;
4751 
4752     if (has_data_file(bs)) {
4753         return -ENOTSUP;
4754     }
4755 
4756     if (bytes == 0) {
4757         /*
4758          * align end of file to a sector boundary to ease reading with
4759          * sector based I/Os
4760          */
4761         int64_t len = bdrv_co_getlength(bs->file->bs);
4762         if (len < 0) {
4763             return len;
4764         }
4765         return bdrv_co_truncate(bs->file, len, false, PREALLOC_MODE_OFF, 0,
4766                                 NULL);
4767     }
4768 
4769     if (offset_into_cluster(s, offset)) {
4770         return -EINVAL;
4771     }
4772 
4773     if (offset_into_cluster(s, bytes) &&
4774         (offset + bytes) != (bs->total_sectors << BDRV_SECTOR_BITS)) {
4775         return -EINVAL;
4776     }
4777 
4778     while (bytes && aio_task_pool_status(aio) == 0) {
4779         uint64_t chunk_size = MIN(bytes, s->cluster_size);
4780 
4781         if (!aio && chunk_size != bytes) {
4782             aio = aio_task_pool_new(QCOW2_MAX_WORKERS);
4783         }
4784 
4785         ret = qcow2_add_task(bs, aio, qcow2_co_pwritev_compressed_task_entry,
4786                              0, 0, offset, chunk_size, qiov, qiov_offset, NULL);
4787         if (ret < 0) {
4788             break;
4789         }
4790         qiov_offset += chunk_size;
4791         offset += chunk_size;
4792         bytes -= chunk_size;
4793     }
4794 
4795     if (aio) {
4796         aio_task_pool_wait_all(aio);
4797         if (ret == 0) {
4798             ret = aio_task_pool_status(aio);
4799         }
4800         g_free(aio);
4801     }
4802 
4803     return ret;
4804 }
4805 
4806 static int coroutine_fn GRAPH_RDLOCK
4807 qcow2_co_preadv_compressed(BlockDriverState *bs,
4808                            uint64_t l2_entry,
4809                            uint64_t offset,
4810                            uint64_t bytes,
4811                            QEMUIOVector *qiov,
4812                            size_t qiov_offset)
4813 {
4814     BDRVQcow2State *s = bs->opaque;
4815     int ret = 0, csize;
4816     uint64_t coffset;
4817     uint8_t *buf, *out_buf;
4818     int offset_in_cluster = offset_into_cluster(s, offset);
4819 
4820     qcow2_parse_compressed_l2_entry(bs, l2_entry, &coffset, &csize);
4821 
4822     buf = g_try_malloc(csize);
4823     if (!buf) {
4824         return -ENOMEM;
4825     }
4826 
4827     out_buf = qemu_blockalign(bs, s->cluster_size);
4828 
4829     BLKDBG_CO_EVENT(bs->file, BLKDBG_READ_COMPRESSED);
4830     ret = bdrv_co_pread(bs->file, coffset, csize, buf, 0);
4831     if (ret < 0) {
4832         goto fail;
4833     }
4834 
4835     if (qcow2_co_decompress(bs, out_buf, s->cluster_size, buf, csize) < 0) {
4836         ret = -EIO;
4837         goto fail;
4838     }
4839 
4840     qemu_iovec_from_buf(qiov, qiov_offset, out_buf + offset_in_cluster, bytes);
4841 
4842 fail:
4843     qemu_vfree(out_buf);
4844     g_free(buf);
4845 
4846     return ret;
4847 }
4848 
4849 static int GRAPH_RDLOCK make_completely_empty(BlockDriverState *bs)
4850 {
4851     BDRVQcow2State *s = bs->opaque;
4852     Error *local_err = NULL;
4853     int ret, l1_clusters;
4854     int64_t offset;
4855     uint64_t *new_reftable = NULL;
4856     uint64_t rt_entry, l1_size2;
4857     struct {
4858         uint64_t l1_offset;
4859         uint64_t reftable_offset;
4860         uint32_t reftable_clusters;
4861     } QEMU_PACKED l1_ofs_rt_ofs_cls;
4862 
4863     ret = qcow2_cache_empty(bs, s->l2_table_cache);
4864     if (ret < 0) {
4865         goto fail;
4866     }
4867 
4868     ret = qcow2_cache_empty(bs, s->refcount_block_cache);
4869     if (ret < 0) {
4870         goto fail;
4871     }
4872 
4873     /* Refcounts will be broken utterly */
4874     ret = qcow2_mark_dirty(bs);
4875     if (ret < 0) {
4876         goto fail;
4877     }
4878 
4879     BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
4880 
4881     l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / L1E_SIZE);
4882     l1_size2 = (uint64_t)s->l1_size * L1E_SIZE;
4883 
4884     /* After this call, neither the in-memory nor the on-disk refcount
4885      * information accurately describe the actual references */
4886 
4887     ret = bdrv_pwrite_zeroes(bs->file, s->l1_table_offset,
4888                              l1_clusters * s->cluster_size, 0);
4889     if (ret < 0) {
4890         goto fail_broken_refcounts;
4891     }
4892     memset(s->l1_table, 0, l1_size2);
4893 
4894     BLKDBG_EVENT(bs->file, BLKDBG_EMPTY_IMAGE_PREPARE);
4895 
4896     /* Overwrite enough clusters at the beginning of the sectors to place
4897      * the refcount table, a refcount block and the L1 table in; this may
4898      * overwrite parts of the existing refcount and L1 table, which is not
4899      * an issue because the dirty flag is set, complete data loss is in fact
4900      * desired and partial data loss is consequently fine as well */
4901     ret = bdrv_pwrite_zeroes(bs->file, s->cluster_size,
4902                              (2 + l1_clusters) * s->cluster_size, 0);
4903     /* This call (even if it failed overall) may have overwritten on-disk
4904      * refcount structures; in that case, the in-memory refcount information
4905      * will probably differ from the on-disk information which makes the BDS
4906      * unusable */
4907     if (ret < 0) {
4908         goto fail_broken_refcounts;
4909     }
4910 
4911     BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
4912     BLKDBG_EVENT(bs->file, BLKDBG_REFTABLE_UPDATE);
4913 
4914     /* "Create" an empty reftable (one cluster) directly after the image
4915      * header and an empty L1 table three clusters after the image header;
4916      * the cluster between those two will be used as the first refblock */
4917     l1_ofs_rt_ofs_cls.l1_offset = cpu_to_be64(3 * s->cluster_size);
4918     l1_ofs_rt_ofs_cls.reftable_offset = cpu_to_be64(s->cluster_size);
4919     l1_ofs_rt_ofs_cls.reftable_clusters = cpu_to_be32(1);
4920     ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, l1_table_offset),
4921                            sizeof(l1_ofs_rt_ofs_cls), &l1_ofs_rt_ofs_cls, 0);
4922     if (ret < 0) {
4923         goto fail_broken_refcounts;
4924     }
4925 
4926     s->l1_table_offset = 3 * s->cluster_size;
4927 
4928     new_reftable = g_try_new0(uint64_t, s->cluster_size / REFTABLE_ENTRY_SIZE);
4929     if (!new_reftable) {
4930         ret = -ENOMEM;
4931         goto fail_broken_refcounts;
4932     }
4933 
4934     s->refcount_table_offset = s->cluster_size;
4935     s->refcount_table_size   = s->cluster_size / REFTABLE_ENTRY_SIZE;
4936     s->max_refcount_table_index = 0;
4937 
4938     g_free(s->refcount_table);
4939     s->refcount_table = new_reftable;
4940     new_reftable = NULL;
4941 
4942     /* Now the in-memory refcount information again corresponds to the on-disk
4943      * information (reftable is empty and no refblocks (the refblock cache is
4944      * empty)); however, this means some clusters (e.g. the image header) are
4945      * referenced, but not refcounted, but the normal qcow2 code assumes that
4946      * the in-memory information is always correct */
4947 
4948     BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_ALLOC);
4949 
4950     /* Enter the first refblock into the reftable */
4951     rt_entry = cpu_to_be64(2 * s->cluster_size);
4952     ret = bdrv_pwrite_sync(bs->file, s->cluster_size, sizeof(rt_entry),
4953                            &rt_entry, 0);
4954     if (ret < 0) {
4955         goto fail_broken_refcounts;
4956     }
4957     s->refcount_table[0] = 2 * s->cluster_size;
4958 
4959     s->free_cluster_index = 0;
4960     assert(3 + l1_clusters <= s->refcount_block_size);
4961     offset = qcow2_alloc_clusters(bs, 3 * s->cluster_size + l1_size2);
4962     if (offset < 0) {
4963         ret = offset;
4964         goto fail_broken_refcounts;
4965     } else if (offset > 0) {
4966         error_report("First cluster in emptied image is in use");
4967         abort();
4968     }
4969 
4970     /* Now finally the in-memory information corresponds to the on-disk
4971      * structures and is correct */
4972     ret = qcow2_mark_clean(bs);
4973     if (ret < 0) {
4974         goto fail;
4975     }
4976 
4977     ret = bdrv_truncate(bs->file, (3 + l1_clusters) * s->cluster_size, false,
4978                         PREALLOC_MODE_OFF, 0, &local_err);
4979     if (ret < 0) {
4980         error_report_err(local_err);
4981         goto fail;
4982     }
4983 
4984     return 0;
4985 
4986 fail_broken_refcounts:
4987     /* The BDS is unusable at this point. If we wanted to make it usable, we
4988      * would have to call qcow2_refcount_close(), qcow2_refcount_init(),
4989      * qcow2_check_refcounts(), qcow2_refcount_close() and qcow2_refcount_init()
4990      * again. However, because the functions which could have caused this error
4991      * path to be taken are used by those functions as well, it's very likely
4992      * that that sequence will fail as well. Therefore, just eject the BDS. */
4993     bs->drv = NULL;
4994 
4995 fail:
4996     g_free(new_reftable);
4997     return ret;
4998 }
4999 
5000 static int GRAPH_RDLOCK qcow2_make_empty(BlockDriverState *bs)
5001 {
5002     BDRVQcow2State *s = bs->opaque;
5003     uint64_t offset, end_offset;
5004     int step = QEMU_ALIGN_DOWN(INT_MAX, s->cluster_size);
5005     int l1_clusters, ret = 0;
5006 
5007     l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / L1E_SIZE);
5008 
5009     if (s->qcow_version >= 3 && !s->snapshots && !s->nb_bitmaps &&
5010         3 + l1_clusters <= s->refcount_block_size &&
5011         s->crypt_method_header != QCOW_CRYPT_LUKS &&
5012         !has_data_file(bs)) {
5013         /* The following function only works for qcow2 v3 images (it
5014          * requires the dirty flag) and only as long as there are no
5015          * features that reserve extra clusters (such as snapshots,
5016          * LUKS header, or persistent bitmaps), because it completely
5017          * empties the image.  Furthermore, the L1 table and three
5018          * additional clusters (image header, refcount table, one
5019          * refcount block) have to fit inside one refcount block. It
5020          * only resets the image file, i.e. does not work with an
5021          * external data file. */
5022         return make_completely_empty(bs);
5023     }
5024 
5025     /* This fallback code simply discards every active cluster; this is slow,
5026      * but works in all cases */
5027     end_offset = bs->total_sectors * BDRV_SECTOR_SIZE;
5028     for (offset = 0; offset < end_offset; offset += step) {
5029         /* As this function is generally used after committing an external
5030          * snapshot, QCOW2_DISCARD_SNAPSHOT seems appropriate. Also, the
5031          * default action for this kind of discard is to pass the discard,
5032          * which will ideally result in an actually smaller image file, as
5033          * is probably desired. */
5034         ret = qcow2_cluster_discard(bs, offset, MIN(step, end_offset - offset),
5035                                     QCOW2_DISCARD_SNAPSHOT, true);
5036         if (ret < 0) {
5037             break;
5038         }
5039     }
5040 
5041     return ret;
5042 }
5043 
5044 static coroutine_fn GRAPH_RDLOCK int qcow2_co_flush_to_os(BlockDriverState *bs)
5045 {
5046     BDRVQcow2State *s = bs->opaque;
5047     int ret;
5048 
5049     qemu_co_mutex_lock(&s->lock);
5050     ret = qcow2_write_caches(bs);
5051     qemu_co_mutex_unlock(&s->lock);
5052 
5053     return ret;
5054 }
5055 
5056 static BlockMeasureInfo *qcow2_measure(QemuOpts *opts, BlockDriverState *in_bs,
5057                                        Error **errp)
5058 {
5059     Error *local_err = NULL;
5060     BlockMeasureInfo *info;
5061     uint64_t required = 0; /* bytes that contribute to required size */
5062     uint64_t virtual_size; /* disk size as seen by guest */
5063     uint64_t refcount_bits;
5064     uint64_t l2_tables;
5065     uint64_t luks_payload_size = 0;
5066     size_t cluster_size;
5067     int version;
5068     char *optstr;
5069     PreallocMode prealloc;
5070     bool has_backing_file;
5071     bool has_luks;
5072     bool extended_l2;
5073     size_t l2e_size;
5074 
5075     /* Parse image creation options */
5076     extended_l2 = qemu_opt_get_bool_del(opts, BLOCK_OPT_EXTL2, false);
5077 
5078     cluster_size = qcow2_opt_get_cluster_size_del(opts, extended_l2,
5079                                                   &local_err);
5080     if (local_err) {
5081         goto err;
5082     }
5083 
5084     version = qcow2_opt_get_version_del(opts, &local_err);
5085     if (local_err) {
5086         goto err;
5087     }
5088 
5089     refcount_bits = qcow2_opt_get_refcount_bits_del(opts, version, &local_err);
5090     if (local_err) {
5091         goto err;
5092     }
5093 
5094     optstr = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
5095     prealloc = qapi_enum_parse(&PreallocMode_lookup, optstr,
5096                                PREALLOC_MODE_OFF, &local_err);
5097     g_free(optstr);
5098     if (local_err) {
5099         goto err;
5100     }
5101 
5102     optstr = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
5103     has_backing_file = !!optstr;
5104     g_free(optstr);
5105 
5106     optstr = qemu_opt_get_del(opts, BLOCK_OPT_ENCRYPT_FORMAT);
5107     has_luks = optstr && strcmp(optstr, "luks") == 0;
5108     g_free(optstr);
5109 
5110     if (has_luks) {
5111         g_autoptr(QCryptoBlockCreateOptions) create_opts = NULL;
5112         QDict *cryptoopts = qcow2_extract_crypto_opts(opts, "luks", errp);
5113         size_t headerlen;
5114 
5115         create_opts = block_crypto_create_opts_init(cryptoopts, errp);
5116         qobject_unref(cryptoopts);
5117         if (!create_opts) {
5118             goto err;
5119         }
5120 
5121         if (!qcrypto_block_calculate_payload_offset(create_opts,
5122                                                     "encrypt.",
5123                                                     &headerlen,
5124                                                     &local_err)) {
5125             goto err;
5126         }
5127 
5128         luks_payload_size = ROUND_UP(headerlen, cluster_size);
5129     }
5130 
5131     virtual_size = qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0);
5132     virtual_size = ROUND_UP(virtual_size, cluster_size);
5133 
5134     /* Check that virtual disk size is valid */
5135     l2e_size = extended_l2 ? L2E_SIZE_EXTENDED : L2E_SIZE_NORMAL;
5136     l2_tables = DIV_ROUND_UP(virtual_size / cluster_size,
5137                              cluster_size / l2e_size);
5138     if (l2_tables * L1E_SIZE > QCOW_MAX_L1_SIZE) {
5139         error_setg(&local_err, "The image size is too large "
5140                                "(try using a larger cluster size)");
5141         goto err;
5142     }
5143 
5144     /* Account for input image */
5145     if (in_bs) {
5146         int64_t ssize = bdrv_getlength(in_bs);
5147         if (ssize < 0) {
5148             error_setg_errno(&local_err, -ssize,
5149                              "Unable to get image virtual_size");
5150             goto err;
5151         }
5152 
5153         virtual_size = ROUND_UP(ssize, cluster_size);
5154 
5155         if (has_backing_file) {
5156             /* We don't how much of the backing chain is shared by the input
5157              * image and the new image file.  In the worst case the new image's
5158              * backing file has nothing in common with the input image.  Be
5159              * conservative and assume all clusters need to be written.
5160              */
5161             required = virtual_size;
5162         } else {
5163             int64_t offset;
5164             int64_t pnum = 0;
5165 
5166             for (offset = 0; offset < ssize; offset += pnum) {
5167                 int ret;
5168 
5169                 ret = bdrv_block_status_above(in_bs, NULL, offset,
5170                                               ssize - offset, &pnum, NULL,
5171                                               NULL);
5172                 if (ret < 0) {
5173                     error_setg_errno(&local_err, -ret,
5174                                      "Unable to get block status");
5175                     goto err;
5176                 }
5177 
5178                 if (ret & BDRV_BLOCK_ZERO) {
5179                     /* Skip zero regions (safe with no backing file) */
5180                 } else if ((ret & (BDRV_BLOCK_DATA | BDRV_BLOCK_ALLOCATED)) ==
5181                            (BDRV_BLOCK_DATA | BDRV_BLOCK_ALLOCATED)) {
5182                     /* Extend pnum to end of cluster for next iteration */
5183                     pnum = ROUND_UP(offset + pnum, cluster_size) - offset;
5184 
5185                     /* Count clusters we've seen */
5186                     required += offset % cluster_size + pnum;
5187                 }
5188             }
5189         }
5190     }
5191 
5192     /* Take into account preallocation.  Nothing special is needed for
5193      * PREALLOC_MODE_METADATA since metadata is always counted.
5194      */
5195     if (prealloc == PREALLOC_MODE_FULL || prealloc == PREALLOC_MODE_FALLOC) {
5196         required = virtual_size;
5197     }
5198 
5199     info = g_new0(BlockMeasureInfo, 1);
5200     info->fully_allocated = luks_payload_size +
5201         qcow2_calc_prealloc_size(virtual_size, cluster_size,
5202                                  ctz32(refcount_bits), extended_l2);
5203 
5204     /*
5205      * Remove data clusters that are not required.  This overestimates the
5206      * required size because metadata needed for the fully allocated file is
5207      * still counted.  Show bitmaps only if both source and destination
5208      * would support them.
5209      */
5210     info->required = info->fully_allocated - virtual_size + required;
5211     info->has_bitmaps = version >= 3 && in_bs &&
5212         bdrv_supports_persistent_dirty_bitmap(in_bs);
5213     if (info->has_bitmaps) {
5214         info->bitmaps = qcow2_get_persistent_dirty_bitmap_size(in_bs,
5215                                                                cluster_size);
5216     }
5217     return info;
5218 
5219 err:
5220     error_propagate(errp, local_err);
5221     return NULL;
5222 }
5223 
5224 static int coroutine_fn
5225 qcow2_co_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
5226 {
5227     BDRVQcow2State *s = bs->opaque;
5228     bdi->cluster_size = s->cluster_size;
5229     bdi->subcluster_size = s->subcluster_size;
5230     bdi->vm_state_offset = qcow2_vm_state_offset(s);
5231     bdi->is_dirty = s->incompatible_features & QCOW2_INCOMPAT_DIRTY;
5232     return 0;
5233 }
5234 
5235 static ImageInfoSpecific * GRAPH_RDLOCK
5236 qcow2_get_specific_info(BlockDriverState *bs, Error **errp)
5237 {
5238     BDRVQcow2State *s = bs->opaque;
5239     ImageInfoSpecific *spec_info;
5240     QCryptoBlockInfo *encrypt_info = NULL;
5241 
5242     if (s->crypto != NULL) {
5243         encrypt_info = qcrypto_block_get_info(s->crypto, errp);
5244         if (!encrypt_info) {
5245             return NULL;
5246         }
5247     }
5248 
5249     spec_info = g_new(ImageInfoSpecific, 1);
5250     *spec_info = (ImageInfoSpecific){
5251         .type  = IMAGE_INFO_SPECIFIC_KIND_QCOW2,
5252         .u.qcow2.data = g_new0(ImageInfoSpecificQCow2, 1),
5253     };
5254     if (s->qcow_version == 2) {
5255         *spec_info->u.qcow2.data = (ImageInfoSpecificQCow2){
5256             .compat             = g_strdup("0.10"),
5257             .refcount_bits      = s->refcount_bits,
5258         };
5259     } else if (s->qcow_version == 3) {
5260         Qcow2BitmapInfoList *bitmaps;
5261         if (!qcow2_get_bitmap_info_list(bs, &bitmaps, errp)) {
5262             qapi_free_ImageInfoSpecific(spec_info);
5263             qapi_free_QCryptoBlockInfo(encrypt_info);
5264             return NULL;
5265         }
5266         *spec_info->u.qcow2.data = (ImageInfoSpecificQCow2){
5267             .compat             = g_strdup("1.1"),
5268             .lazy_refcounts     = s->compatible_features &
5269                                   QCOW2_COMPAT_LAZY_REFCOUNTS,
5270             .has_lazy_refcounts = true,
5271             .corrupt            = s->incompatible_features &
5272                                   QCOW2_INCOMPAT_CORRUPT,
5273             .has_corrupt        = true,
5274             .has_extended_l2    = true,
5275             .extended_l2        = has_subclusters(s),
5276             .refcount_bits      = s->refcount_bits,
5277             .has_bitmaps        = !!bitmaps,
5278             .bitmaps            = bitmaps,
5279             .data_file          = g_strdup(s->image_data_file),
5280             .has_data_file_raw  = has_data_file(bs),
5281             .data_file_raw      = data_file_is_raw(bs),
5282             .compression_type   = s->compression_type,
5283         };
5284     } else {
5285         /* if this assertion fails, this probably means a new version was
5286          * added without having it covered here */
5287         assert(false);
5288     }
5289 
5290     if (encrypt_info) {
5291         ImageInfoSpecificQCow2Encryption *qencrypt =
5292             g_new(ImageInfoSpecificQCow2Encryption, 1);
5293         switch (encrypt_info->format) {
5294         case Q_CRYPTO_BLOCK_FORMAT_QCOW:
5295             qencrypt->format = BLOCKDEV_QCOW2_ENCRYPTION_FORMAT_AES;
5296             break;
5297         case Q_CRYPTO_BLOCK_FORMAT_LUKS:
5298             qencrypt->format = BLOCKDEV_QCOW2_ENCRYPTION_FORMAT_LUKS;
5299             qencrypt->u.luks = encrypt_info->u.luks;
5300             break;
5301         default:
5302             abort();
5303         }
5304         /* Since we did shallow copy above, erase any pointers
5305          * in the original info */
5306         memset(&encrypt_info->u, 0, sizeof(encrypt_info->u));
5307         qapi_free_QCryptoBlockInfo(encrypt_info);
5308 
5309         spec_info->u.qcow2.data->encrypt = qencrypt;
5310     }
5311 
5312     return spec_info;
5313 }
5314 
5315 static int coroutine_mixed_fn GRAPH_RDLOCK
5316 qcow2_has_zero_init(BlockDriverState *bs)
5317 {
5318     BDRVQcow2State *s = bs->opaque;
5319     bool preallocated;
5320 
5321     if (qemu_in_coroutine()) {
5322         qemu_co_mutex_lock(&s->lock);
5323     }
5324     /*
5325      * Check preallocation status: Preallocated images have all L2
5326      * tables allocated, nonpreallocated images have none.  It is
5327      * therefore enough to check the first one.
5328      */
5329     preallocated = s->l1_size > 0 && s->l1_table[0] != 0;
5330     if (qemu_in_coroutine()) {
5331         qemu_co_mutex_unlock(&s->lock);
5332     }
5333 
5334     if (!preallocated) {
5335         return 1;
5336     } else if (bs->encrypted) {
5337         return 0;
5338     } else {
5339         return bdrv_has_zero_init(s->data_file->bs);
5340     }
5341 }
5342 
5343 /*
5344  * Check the request to vmstate. On success return
5345  *      qcow2_vm_state_offset(bs) + @pos
5346  */
5347 static int64_t qcow2_check_vmstate_request(BlockDriverState *bs,
5348                                            QEMUIOVector *qiov, int64_t pos)
5349 {
5350     BDRVQcow2State *s = bs->opaque;
5351     int64_t vmstate_offset = qcow2_vm_state_offset(s);
5352     int ret;
5353 
5354     /* Incoming requests must be OK */
5355     bdrv_check_qiov_request(pos, qiov->size, qiov, 0, &error_abort);
5356 
5357     if (INT64_MAX - pos < vmstate_offset) {
5358         return -EIO;
5359     }
5360 
5361     pos += vmstate_offset;
5362     ret = bdrv_check_qiov_request(pos, qiov->size, qiov, 0, NULL);
5363     if (ret < 0) {
5364         return ret;
5365     }
5366 
5367     return pos;
5368 }
5369 
5370 static int coroutine_fn GRAPH_RDLOCK
5371 qcow2_co_save_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos)
5372 {
5373     int64_t offset = qcow2_check_vmstate_request(bs, qiov, pos);
5374     if (offset < 0) {
5375         return offset;
5376     }
5377 
5378     BLKDBG_CO_EVENT(bs->file, BLKDBG_VMSTATE_SAVE);
5379     return bs->drv->bdrv_co_pwritev_part(bs, offset, qiov->size, qiov, 0, 0);
5380 }
5381 
5382 static int coroutine_fn GRAPH_RDLOCK
5383 qcow2_co_load_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos)
5384 {
5385     int64_t offset = qcow2_check_vmstate_request(bs, qiov, pos);
5386     if (offset < 0) {
5387         return offset;
5388     }
5389 
5390     BLKDBG_CO_EVENT(bs->file, BLKDBG_VMSTATE_LOAD);
5391     return bs->drv->bdrv_co_preadv_part(bs, offset, qiov->size, qiov, 0, 0);
5392 }
5393 
5394 static int GRAPH_RDLOCK qcow2_has_compressed_clusters(BlockDriverState *bs)
5395 {
5396     int64_t offset = 0;
5397     int64_t bytes = bdrv_getlength(bs);
5398 
5399     if (bytes < 0) {
5400         return bytes;
5401     }
5402 
5403     while (bytes != 0) {
5404         int ret;
5405         QCow2SubclusterType type;
5406         unsigned int cur_bytes = MIN(INT_MAX, bytes);
5407         uint64_t host_offset;
5408 
5409         ret = qcow2_get_host_offset(bs, offset, &cur_bytes, &host_offset,
5410                                     &type);
5411         if (ret < 0) {
5412             return ret;
5413         }
5414 
5415         if (type == QCOW2_SUBCLUSTER_COMPRESSED) {
5416             return 1;
5417         }
5418 
5419         offset += cur_bytes;
5420         bytes -= cur_bytes;
5421     }
5422 
5423     return 0;
5424 }
5425 
5426 /*
5427  * Downgrades an image's version. To achieve this, any incompatible features
5428  * have to be removed.
5429  */
5430 static int GRAPH_RDLOCK
5431 qcow2_downgrade(BlockDriverState *bs, int target_version,
5432                 BlockDriverAmendStatusCB *status_cb, void *cb_opaque,
5433                 Error **errp)
5434 {
5435     BDRVQcow2State *s = bs->opaque;
5436     int current_version = s->qcow_version;
5437     int ret;
5438     int i;
5439 
5440     /* This is qcow2_downgrade(), not qcow2_upgrade() */
5441     assert(target_version < current_version);
5442 
5443     /* There are no other versions (now) that you can downgrade to */
5444     assert(target_version == 2);
5445 
5446     if (s->refcount_order != 4) {
5447         error_setg(errp, "compat=0.10 requires refcount_bits=16");
5448         return -ENOTSUP;
5449     }
5450 
5451     if (has_data_file(bs)) {
5452         error_setg(errp, "Cannot downgrade an image with a data file");
5453         return -ENOTSUP;
5454     }
5455 
5456     /*
5457      * If any internal snapshot has a different size than the current
5458      * image size, or VM state size that exceeds 32 bits, downgrading
5459      * is unsafe.  Even though we would still use v3-compliant output
5460      * to preserve that data, other v2 programs might not realize
5461      * those optional fields are important.
5462      */
5463     for (i = 0; i < s->nb_snapshots; i++) {
5464         if (s->snapshots[i].vm_state_size > UINT32_MAX ||
5465             s->snapshots[i].disk_size != bs->total_sectors * BDRV_SECTOR_SIZE) {
5466             error_setg(errp, "Internal snapshots prevent downgrade of image");
5467             return -ENOTSUP;
5468         }
5469     }
5470 
5471     /* clear incompatible features */
5472     if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
5473         ret = qcow2_mark_clean(bs);
5474         if (ret < 0) {
5475             error_setg_errno(errp, -ret, "Failed to make the image clean");
5476             return ret;
5477         }
5478     }
5479 
5480     /* with QCOW2_INCOMPAT_CORRUPT, it is pretty much impossible to get here in
5481      * the first place; if that happens nonetheless, returning -ENOTSUP is the
5482      * best thing to do anyway */
5483 
5484     if (s->incompatible_features & ~QCOW2_INCOMPAT_COMPRESSION) {
5485         error_setg(errp, "Cannot downgrade an image with incompatible features "
5486                    "0x%" PRIx64 " set",
5487                    s->incompatible_features & ~QCOW2_INCOMPAT_COMPRESSION);
5488         return -ENOTSUP;
5489     }
5490 
5491     /* since we can ignore compatible features, we can set them to 0 as well */
5492     s->compatible_features = 0;
5493     /* if lazy refcounts have been used, they have already been fixed through
5494      * clearing the dirty flag */
5495 
5496     /* clearing autoclear features is trivial */
5497     s->autoclear_features = 0;
5498 
5499     ret = qcow2_expand_zero_clusters(bs, status_cb, cb_opaque);
5500     if (ret < 0) {
5501         error_setg_errno(errp, -ret, "Failed to turn zero into data clusters");
5502         return ret;
5503     }
5504 
5505     if (s->incompatible_features & QCOW2_INCOMPAT_COMPRESSION) {
5506         ret = qcow2_has_compressed_clusters(bs);
5507         if (ret < 0) {
5508             error_setg(errp, "Failed to check block status");
5509             return -EINVAL;
5510         }
5511         if (ret) {
5512             error_setg(errp, "Cannot downgrade an image with zstd compression "
5513                        "type and existing compressed clusters");
5514             return -ENOTSUP;
5515         }
5516         /*
5517          * No compressed clusters for now, so just chose default zlib
5518          * compression.
5519          */
5520         s->incompatible_features &= ~QCOW2_INCOMPAT_COMPRESSION;
5521         s->compression_type = QCOW2_COMPRESSION_TYPE_ZLIB;
5522     }
5523 
5524     assert(s->incompatible_features == 0);
5525 
5526     s->qcow_version = target_version;
5527     ret = qcow2_update_header(bs);
5528     if (ret < 0) {
5529         s->qcow_version = current_version;
5530         error_setg_errno(errp, -ret, "Failed to update the image header");
5531         return ret;
5532     }
5533     return 0;
5534 }
5535 
5536 /*
5537  * Upgrades an image's version.  While newer versions encompass all
5538  * features of older versions, some things may have to be presented
5539  * differently.
5540  */
5541 static int GRAPH_RDLOCK
5542 qcow2_upgrade(BlockDriverState *bs, int target_version,
5543               BlockDriverAmendStatusCB *status_cb, void *cb_opaque,
5544               Error **errp)
5545 {
5546     BDRVQcow2State *s = bs->opaque;
5547     bool need_snapshot_update;
5548     int current_version = s->qcow_version;
5549     int i;
5550     int ret;
5551 
5552     /* This is qcow2_upgrade(), not qcow2_downgrade() */
5553     assert(target_version > current_version);
5554 
5555     /* There are no other versions (yet) that you can upgrade to */
5556     assert(target_version == 3);
5557 
5558     status_cb(bs, 0, 2, cb_opaque);
5559 
5560     /*
5561      * In v2, snapshots do not need to have extra data.  v3 requires
5562      * the 64-bit VM state size and the virtual disk size to be
5563      * present.
5564      * qcow2_write_snapshots() will always write the list in the
5565      * v3-compliant format.
5566      */
5567     need_snapshot_update = false;
5568     for (i = 0; i < s->nb_snapshots; i++) {
5569         if (s->snapshots[i].extra_data_size <
5570             sizeof_field(QCowSnapshotExtraData, vm_state_size_large) +
5571             sizeof_field(QCowSnapshotExtraData, disk_size))
5572         {
5573             need_snapshot_update = true;
5574             break;
5575         }
5576     }
5577     if (need_snapshot_update) {
5578         ret = qcow2_write_snapshots(bs);
5579         if (ret < 0) {
5580             error_setg_errno(errp, -ret, "Failed to update the snapshot table");
5581             return ret;
5582         }
5583     }
5584     status_cb(bs, 1, 2, cb_opaque);
5585 
5586     s->qcow_version = target_version;
5587     ret = qcow2_update_header(bs);
5588     if (ret < 0) {
5589         s->qcow_version = current_version;
5590         error_setg_errno(errp, -ret, "Failed to update the image header");
5591         return ret;
5592     }
5593     status_cb(bs, 2, 2, cb_opaque);
5594 
5595     return 0;
5596 }
5597 
5598 typedef enum Qcow2AmendOperation {
5599     /* This is the value Qcow2AmendHelperCBInfo::last_operation will be
5600      * statically initialized to so that the helper CB can discern the first
5601      * invocation from an operation change */
5602     QCOW2_NO_OPERATION = 0,
5603 
5604     QCOW2_UPGRADING,
5605     QCOW2_UPDATING_ENCRYPTION,
5606     QCOW2_CHANGING_REFCOUNT_ORDER,
5607     QCOW2_DOWNGRADING,
5608 } Qcow2AmendOperation;
5609 
5610 typedef struct Qcow2AmendHelperCBInfo {
5611     /* The code coordinating the amend operations should only modify
5612      * these four fields; the rest will be managed by the CB */
5613     BlockDriverAmendStatusCB *original_status_cb;
5614     void *original_cb_opaque;
5615 
5616     Qcow2AmendOperation current_operation;
5617 
5618     /* Total number of operations to perform (only set once) */
5619     int total_operations;
5620 
5621     /* The following fields are managed by the CB */
5622 
5623     /* Number of operations completed */
5624     int operations_completed;
5625 
5626     /* Cumulative offset of all completed operations */
5627     int64_t offset_completed;
5628 
5629     Qcow2AmendOperation last_operation;
5630     int64_t last_work_size;
5631 } Qcow2AmendHelperCBInfo;
5632 
5633 static void qcow2_amend_helper_cb(BlockDriverState *bs,
5634                                   int64_t operation_offset,
5635                                   int64_t operation_work_size, void *opaque)
5636 {
5637     Qcow2AmendHelperCBInfo *info = opaque;
5638     int64_t current_work_size;
5639     int64_t projected_work_size;
5640 
5641     if (info->current_operation != info->last_operation) {
5642         if (info->last_operation != QCOW2_NO_OPERATION) {
5643             info->offset_completed += info->last_work_size;
5644             info->operations_completed++;
5645         }
5646 
5647         info->last_operation = info->current_operation;
5648     }
5649 
5650     assert(info->total_operations > 0);
5651     assert(info->operations_completed < info->total_operations);
5652 
5653     info->last_work_size = operation_work_size;
5654 
5655     current_work_size = info->offset_completed + operation_work_size;
5656 
5657     /* current_work_size is the total work size for (operations_completed + 1)
5658      * operations (which includes this one), so multiply it by the number of
5659      * operations not covered and divide it by the number of operations
5660      * covered to get a projection for the operations not covered */
5661     projected_work_size = current_work_size * (info->total_operations -
5662                                                info->operations_completed - 1)
5663                                             / (info->operations_completed + 1);
5664 
5665     info->original_status_cb(bs, info->offset_completed + operation_offset,
5666                              current_work_size + projected_work_size,
5667                              info->original_cb_opaque);
5668 }
5669 
5670 static int GRAPH_RDLOCK
5671 qcow2_amend_options(BlockDriverState *bs, QemuOpts *opts,
5672                     BlockDriverAmendStatusCB *status_cb, void *cb_opaque,
5673                     bool force, Error **errp)
5674 {
5675     BDRVQcow2State *s = bs->opaque;
5676     int old_version = s->qcow_version, new_version = old_version;
5677     uint64_t new_size = 0;
5678     const char *backing_file = NULL, *backing_format = NULL, *data_file = NULL;
5679     bool lazy_refcounts = s->use_lazy_refcounts;
5680     bool data_file_raw = data_file_is_raw(bs);
5681     const char *compat = NULL;
5682     int refcount_bits = s->refcount_bits;
5683     int ret;
5684     QemuOptDesc *desc = opts->list->desc;
5685     Qcow2AmendHelperCBInfo helper_cb_info;
5686     bool encryption_update = false;
5687 
5688     while (desc && desc->name) {
5689         if (!qemu_opt_find(opts, desc->name)) {
5690             /* only change explicitly defined options */
5691             desc++;
5692             continue;
5693         }
5694 
5695         if (!strcmp(desc->name, BLOCK_OPT_COMPAT_LEVEL)) {
5696             compat = qemu_opt_get(opts, BLOCK_OPT_COMPAT_LEVEL);
5697             if (!compat) {
5698                 /* preserve default */
5699             } else if (!strcmp(compat, "0.10") || !strcmp(compat, "v2")) {
5700                 new_version = 2;
5701             } else if (!strcmp(compat, "1.1") || !strcmp(compat, "v3")) {
5702                 new_version = 3;
5703             } else {
5704                 error_setg(errp, "Unknown compatibility level %s", compat);
5705                 return -EINVAL;
5706             }
5707         } else if (!strcmp(desc->name, BLOCK_OPT_SIZE)) {
5708             new_size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, 0);
5709         } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FILE)) {
5710             backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
5711         } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FMT)) {
5712             backing_format = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
5713         } else if (g_str_has_prefix(desc->name, "encrypt.")) {
5714             if (!s->crypto) {
5715                 error_setg(errp,
5716                            "Can't amend encryption options - encryption not present");
5717                 return -EINVAL;
5718             }
5719             if (s->crypt_method_header != QCOW_CRYPT_LUKS) {
5720                 error_setg(errp,
5721                            "Only LUKS encryption options can be amended");
5722                 return -ENOTSUP;
5723             }
5724             encryption_update = true;
5725         } else if (!strcmp(desc->name, BLOCK_OPT_LAZY_REFCOUNTS)) {
5726             lazy_refcounts = qemu_opt_get_bool(opts, BLOCK_OPT_LAZY_REFCOUNTS,
5727                                                lazy_refcounts);
5728         } else if (!strcmp(desc->name, BLOCK_OPT_REFCOUNT_BITS)) {
5729             refcount_bits = qemu_opt_get_number(opts, BLOCK_OPT_REFCOUNT_BITS,
5730                                                 refcount_bits);
5731 
5732             if (refcount_bits <= 0 || refcount_bits > 64 ||
5733                 !is_power_of_2(refcount_bits))
5734             {
5735                 error_setg(errp, "Refcount width must be a power of two and "
5736                            "may not exceed 64 bits");
5737                 return -EINVAL;
5738             }
5739         } else if (!strcmp(desc->name, BLOCK_OPT_DATA_FILE)) {
5740             data_file = qemu_opt_get(opts, BLOCK_OPT_DATA_FILE);
5741             if (data_file && !has_data_file(bs)) {
5742                 error_setg(errp, "data-file can only be set for images that "
5743                                  "use an external data file");
5744                 return -EINVAL;
5745             }
5746         } else if (!strcmp(desc->name, BLOCK_OPT_DATA_FILE_RAW)) {
5747             data_file_raw = qemu_opt_get_bool(opts, BLOCK_OPT_DATA_FILE_RAW,
5748                                               data_file_raw);
5749             if (data_file_raw && !data_file_is_raw(bs)) {
5750                 error_setg(errp, "data-file-raw cannot be set on existing "
5751                                  "images");
5752                 return -EINVAL;
5753             }
5754         } else {
5755             /* if this point is reached, this probably means a new option was
5756              * added without having it covered here */
5757             abort();
5758         }
5759 
5760         desc++;
5761     }
5762 
5763     helper_cb_info = (Qcow2AmendHelperCBInfo){
5764         .original_status_cb = status_cb,
5765         .original_cb_opaque = cb_opaque,
5766         .total_operations = (new_version != old_version)
5767                           + (s->refcount_bits != refcount_bits) +
5768                             (encryption_update == true)
5769     };
5770 
5771     /* Upgrade first (some features may require compat=1.1) */
5772     if (new_version > old_version) {
5773         helper_cb_info.current_operation = QCOW2_UPGRADING;
5774         ret = qcow2_upgrade(bs, new_version, &qcow2_amend_helper_cb,
5775                             &helper_cb_info, errp);
5776         if (ret < 0) {
5777             return ret;
5778         }
5779     }
5780 
5781     if (encryption_update) {
5782         QDict *amend_opts_dict;
5783         QCryptoBlockAmendOptions *amend_opts;
5784 
5785         helper_cb_info.current_operation = QCOW2_UPDATING_ENCRYPTION;
5786         amend_opts_dict = qcow2_extract_crypto_opts(opts, "luks", errp);
5787         if (!amend_opts_dict) {
5788             return -EINVAL;
5789         }
5790         amend_opts = block_crypto_amend_opts_init(amend_opts_dict, errp);
5791         qobject_unref(amend_opts_dict);
5792         if (!amend_opts) {
5793             return -EINVAL;
5794         }
5795         ret = qcrypto_block_amend_options(s->crypto,
5796                                           qcow2_crypto_hdr_read_func,
5797                                           qcow2_crypto_hdr_write_func,
5798                                           bs,
5799                                           amend_opts,
5800                                           force,
5801                                           errp);
5802         qapi_free_QCryptoBlockAmendOptions(amend_opts);
5803         if (ret < 0) {
5804             return ret;
5805         }
5806     }
5807 
5808     if (s->refcount_bits != refcount_bits) {
5809         int refcount_order = ctz32(refcount_bits);
5810 
5811         if (new_version < 3 && refcount_bits != 16) {
5812             error_setg(errp, "Refcount widths other than 16 bits require "
5813                        "compatibility level 1.1 or above (use compat=1.1 or "
5814                        "greater)");
5815             return -EINVAL;
5816         }
5817 
5818         helper_cb_info.current_operation = QCOW2_CHANGING_REFCOUNT_ORDER;
5819         ret = qcow2_change_refcount_order(bs, refcount_order,
5820                                           &qcow2_amend_helper_cb,
5821                                           &helper_cb_info, errp);
5822         if (ret < 0) {
5823             return ret;
5824         }
5825     }
5826 
5827     /* data-file-raw blocks backing files, so clear it first if requested */
5828     if (data_file_raw) {
5829         s->autoclear_features |= QCOW2_AUTOCLEAR_DATA_FILE_RAW;
5830     } else {
5831         s->autoclear_features &= ~QCOW2_AUTOCLEAR_DATA_FILE_RAW;
5832     }
5833 
5834     if (data_file) {
5835         g_free(s->image_data_file);
5836         s->image_data_file = *data_file ? g_strdup(data_file) : NULL;
5837     }
5838 
5839     ret = qcow2_update_header(bs);
5840     if (ret < 0) {
5841         error_setg_errno(errp, -ret, "Failed to update the image header");
5842         return ret;
5843     }
5844 
5845     if (backing_file || backing_format) {
5846         if (g_strcmp0(backing_file, s->image_backing_file) ||
5847             g_strcmp0(backing_format, s->image_backing_format)) {
5848             error_setg(errp, "Cannot amend the backing file");
5849             error_append_hint(errp,
5850                               "You can use 'qemu-img rebase' instead.\n");
5851             return -EINVAL;
5852         }
5853     }
5854 
5855     if (s->use_lazy_refcounts != lazy_refcounts) {
5856         if (lazy_refcounts) {
5857             if (new_version < 3) {
5858                 error_setg(errp, "Lazy refcounts only supported with "
5859                            "compatibility level 1.1 and above (use compat=1.1 "
5860                            "or greater)");
5861                 return -EINVAL;
5862             }
5863             s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
5864             ret = qcow2_update_header(bs);
5865             if (ret < 0) {
5866                 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
5867                 error_setg_errno(errp, -ret, "Failed to update the image header");
5868                 return ret;
5869             }
5870             s->use_lazy_refcounts = true;
5871         } else {
5872             /* make image clean first */
5873             ret = qcow2_mark_clean(bs);
5874             if (ret < 0) {
5875                 error_setg_errno(errp, -ret, "Failed to make the image clean");
5876                 return ret;
5877             }
5878             /* now disallow lazy refcounts */
5879             s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
5880             ret = qcow2_update_header(bs);
5881             if (ret < 0) {
5882                 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
5883                 error_setg_errno(errp, -ret, "Failed to update the image header");
5884                 return ret;
5885             }
5886             s->use_lazy_refcounts = false;
5887         }
5888     }
5889 
5890     if (new_size) {
5891         BlockBackend *blk = blk_new_with_bs(bs, BLK_PERM_RESIZE, BLK_PERM_ALL,
5892                                             errp);
5893         if (!blk) {
5894             return -EPERM;
5895         }
5896 
5897         /*
5898          * Amending image options should ensure that the image has
5899          * exactly the given new values, so pass exact=true here.
5900          */
5901         ret = blk_truncate(blk, new_size, true, PREALLOC_MODE_OFF, 0, errp);
5902         blk_unref(blk);
5903         if (ret < 0) {
5904             return ret;
5905         }
5906     }
5907 
5908     /* Downgrade last (so unsupported features can be removed before) */
5909     if (new_version < old_version) {
5910         helper_cb_info.current_operation = QCOW2_DOWNGRADING;
5911         ret = qcow2_downgrade(bs, new_version, &qcow2_amend_helper_cb,
5912                               &helper_cb_info, errp);
5913         if (ret < 0) {
5914             return ret;
5915         }
5916     }
5917 
5918     return 0;
5919 }
5920 
5921 static int coroutine_fn qcow2_co_amend(BlockDriverState *bs,
5922                                        BlockdevAmendOptions *opts,
5923                                        bool force,
5924                                        Error **errp)
5925 {
5926     BlockdevAmendOptionsQcow2 *qopts = &opts->u.qcow2;
5927     BDRVQcow2State *s = bs->opaque;
5928     int ret = 0;
5929 
5930     if (qopts->encrypt) {
5931         if (!s->crypto) {
5932             error_setg(errp, "image is not encrypted, can't amend");
5933             return -EOPNOTSUPP;
5934         }
5935 
5936         if (qopts->encrypt->format != Q_CRYPTO_BLOCK_FORMAT_LUKS) {
5937             error_setg(errp,
5938                        "Amend can't be used to change the qcow2 encryption format");
5939             return -EOPNOTSUPP;
5940         }
5941 
5942         if (s->crypt_method_header != QCOW_CRYPT_LUKS) {
5943             error_setg(errp,
5944                        "Only LUKS encryption options can be amended for qcow2 with blockdev-amend");
5945             return -EOPNOTSUPP;
5946         }
5947 
5948         ret = qcrypto_block_amend_options(s->crypto,
5949                                           qcow2_crypto_hdr_read_func,
5950                                           qcow2_crypto_hdr_write_func,
5951                                           bs,
5952                                           qopts->encrypt,
5953                                           force,
5954                                           errp);
5955     }
5956     return ret;
5957 }
5958 
5959 /*
5960  * If offset or size are negative, respectively, they will not be included in
5961  * the BLOCK_IMAGE_CORRUPTED event emitted.
5962  * fatal will be ignored for read-only BDS; corruptions found there will always
5963  * be considered non-fatal.
5964  */
5965 void qcow2_signal_corruption(BlockDriverState *bs, bool fatal, int64_t offset,
5966                              int64_t size, const char *message_format, ...)
5967 {
5968     BDRVQcow2State *s = bs->opaque;
5969     const char *node_name;
5970     char *message;
5971     va_list ap;
5972 
5973     fatal = fatal && bdrv_is_writable(bs);
5974 
5975     if (s->signaled_corruption &&
5976         (!fatal || (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT)))
5977     {
5978         return;
5979     }
5980 
5981     va_start(ap, message_format);
5982     message = g_strdup_vprintf(message_format, ap);
5983     va_end(ap);
5984 
5985     if (fatal) {
5986         fprintf(stderr, "qcow2: Marking image as corrupt: %s; further "
5987                 "corruption events will be suppressed\n", message);
5988     } else {
5989         fprintf(stderr, "qcow2: Image is corrupt: %s; further non-fatal "
5990                 "corruption events will be suppressed\n", message);
5991     }
5992 
5993     node_name = bdrv_get_node_name(bs);
5994     qapi_event_send_block_image_corrupted(bdrv_get_device_name(bs),
5995                                           *node_name ? node_name : NULL,
5996                                           message, offset >= 0, offset,
5997                                           size >= 0, size,
5998                                           fatal);
5999     g_free(message);
6000 
6001     if (fatal) {
6002         qcow2_mark_corrupt(bs);
6003         bs->drv = NULL; /* make BDS unusable */
6004     }
6005 
6006     s->signaled_corruption = true;
6007 }
6008 
6009 #define QCOW_COMMON_OPTIONS                                         \
6010     {                                                               \
6011         .name = BLOCK_OPT_SIZE,                                     \
6012         .type = QEMU_OPT_SIZE,                                      \
6013         .help = "Virtual disk size"                                 \
6014     },                                                              \
6015     {                                                               \
6016         .name = BLOCK_OPT_COMPAT_LEVEL,                             \
6017         .type = QEMU_OPT_STRING,                                    \
6018         .help = "Compatibility level (v2 [0.10] or v3 [1.1])"       \
6019     },                                                              \
6020     {                                                               \
6021         .name = BLOCK_OPT_BACKING_FILE,                             \
6022         .type = QEMU_OPT_STRING,                                    \
6023         .help = "File name of a base image"                         \
6024     },                                                              \
6025     {                                                               \
6026         .name = BLOCK_OPT_BACKING_FMT,                              \
6027         .type = QEMU_OPT_STRING,                                    \
6028         .help = "Image format of the base image"                    \
6029     },                                                              \
6030     {                                                               \
6031         .name = BLOCK_OPT_DATA_FILE,                                \
6032         .type = QEMU_OPT_STRING,                                    \
6033         .help = "File name of an external data file"                \
6034     },                                                              \
6035     {                                                               \
6036         .name = BLOCK_OPT_DATA_FILE_RAW,                            \
6037         .type = QEMU_OPT_BOOL,                                      \
6038         .help = "The external data file must stay valid "           \
6039                 "as a raw image"                                    \
6040     },                                                              \
6041     {                                                               \
6042         .name = BLOCK_OPT_LAZY_REFCOUNTS,                           \
6043         .type = QEMU_OPT_BOOL,                                      \
6044         .help = "Postpone refcount updates",                        \
6045         .def_value_str = "off"                                      \
6046     },                                                              \
6047     {                                                               \
6048         .name = BLOCK_OPT_REFCOUNT_BITS,                            \
6049         .type = QEMU_OPT_NUMBER,                                    \
6050         .help = "Width of a reference count entry in bits",         \
6051         .def_value_str = "16"                                       \
6052     }
6053 
6054 static QemuOptsList qcow2_create_opts = {
6055     .name = "qcow2-create-opts",
6056     .head = QTAILQ_HEAD_INITIALIZER(qcow2_create_opts.head),
6057     .desc = {
6058         {                                                               \
6059             .name = BLOCK_OPT_ENCRYPT,                                  \
6060             .type = QEMU_OPT_BOOL,                                      \
6061             .help = "Encrypt the image with format 'aes'. (Deprecated " \
6062                     "in favor of " BLOCK_OPT_ENCRYPT_FORMAT "=aes)",    \
6063         },                                                              \
6064         {                                                               \
6065             .name = BLOCK_OPT_ENCRYPT_FORMAT,                           \
6066             .type = QEMU_OPT_STRING,                                    \
6067             .help = "Encrypt the image, format choices: 'aes', 'luks'", \
6068         },                                                              \
6069         BLOCK_CRYPTO_OPT_DEF_KEY_SECRET("encrypt.",                     \
6070             "ID of secret providing qcow AES key or LUKS passphrase"),  \
6071         BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_ALG("encrypt."),               \
6072         BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_MODE("encrypt."),              \
6073         BLOCK_CRYPTO_OPT_DEF_LUKS_IVGEN_ALG("encrypt."),                \
6074         BLOCK_CRYPTO_OPT_DEF_LUKS_IVGEN_HASH_ALG("encrypt."),           \
6075         BLOCK_CRYPTO_OPT_DEF_LUKS_HASH_ALG("encrypt."),                 \
6076         BLOCK_CRYPTO_OPT_DEF_LUKS_ITER_TIME("encrypt."),                \
6077         {                                                               \
6078             .name = BLOCK_OPT_CLUSTER_SIZE,                             \
6079             .type = QEMU_OPT_SIZE,                                      \
6080             .help = "qcow2 cluster size",                               \
6081             .def_value_str = stringify(DEFAULT_CLUSTER_SIZE)            \
6082         },                                                              \
6083         {                                                               \
6084             .name = BLOCK_OPT_EXTL2,                                    \
6085             .type = QEMU_OPT_BOOL,                                      \
6086             .help = "Extended L2 tables",                               \
6087             .def_value_str = "off"                                      \
6088         },                                                              \
6089         {                                                               \
6090             .name = BLOCK_OPT_PREALLOC,                                 \
6091             .type = QEMU_OPT_STRING,                                    \
6092             .help = "Preallocation mode (allowed values: off, "         \
6093                     "metadata, falloc, full)"                           \
6094         },                                                              \
6095         {                                                               \
6096             .name = BLOCK_OPT_COMPRESSION_TYPE,                         \
6097             .type = QEMU_OPT_STRING,                                    \
6098             .help = "Compression method used for image cluster "        \
6099                     "compression",                                      \
6100             .def_value_str = "zlib"                                     \
6101         },
6102         QCOW_COMMON_OPTIONS,
6103         { /* end of list */ }
6104     }
6105 };
6106 
6107 static QemuOptsList qcow2_amend_opts = {
6108     .name = "qcow2-amend-opts",
6109     .head = QTAILQ_HEAD_INITIALIZER(qcow2_amend_opts.head),
6110     .desc = {
6111         BLOCK_CRYPTO_OPT_DEF_LUKS_STATE("encrypt."),
6112         BLOCK_CRYPTO_OPT_DEF_LUKS_KEYSLOT("encrypt."),
6113         BLOCK_CRYPTO_OPT_DEF_LUKS_OLD_SECRET("encrypt."),
6114         BLOCK_CRYPTO_OPT_DEF_LUKS_NEW_SECRET("encrypt."),
6115         BLOCK_CRYPTO_OPT_DEF_LUKS_ITER_TIME("encrypt."),
6116         QCOW_COMMON_OPTIONS,
6117         { /* end of list */ }
6118     }
6119 };
6120 
6121 static const char *const qcow2_strong_runtime_opts[] = {
6122     "encrypt." BLOCK_CRYPTO_OPT_QCOW_KEY_SECRET,
6123 
6124     NULL
6125 };
6126 
6127 BlockDriver bdrv_qcow2 = {
6128     .format_name                        = "qcow2",
6129     .instance_size                      = sizeof(BDRVQcow2State),
6130     .bdrv_probe                         = qcow2_probe,
6131     .bdrv_open                          = qcow2_open,
6132     .bdrv_close                         = qcow2_close,
6133     .bdrv_reopen_prepare                = qcow2_reopen_prepare,
6134     .bdrv_reopen_commit                 = qcow2_reopen_commit,
6135     .bdrv_reopen_commit_post            = qcow2_reopen_commit_post,
6136     .bdrv_reopen_abort                  = qcow2_reopen_abort,
6137     .bdrv_join_options                  = qcow2_join_options,
6138     .bdrv_child_perm                    = bdrv_default_perms,
6139     .bdrv_co_create_opts                = qcow2_co_create_opts,
6140     .bdrv_co_create                     = qcow2_co_create,
6141     .bdrv_has_zero_init                 = qcow2_has_zero_init,
6142     .bdrv_co_block_status               = qcow2_co_block_status,
6143 
6144     .bdrv_co_preadv_part                = qcow2_co_preadv_part,
6145     .bdrv_co_pwritev_part               = qcow2_co_pwritev_part,
6146     .bdrv_co_flush_to_os                = qcow2_co_flush_to_os,
6147 
6148     .bdrv_co_pwrite_zeroes              = qcow2_co_pwrite_zeroes,
6149     .bdrv_co_pdiscard                   = qcow2_co_pdiscard,
6150     .bdrv_co_copy_range_from            = qcow2_co_copy_range_from,
6151     .bdrv_co_copy_range_to              = qcow2_co_copy_range_to,
6152     .bdrv_co_truncate                   = qcow2_co_truncate,
6153     .bdrv_co_pwritev_compressed_part    = qcow2_co_pwritev_compressed_part,
6154     .bdrv_make_empty                    = qcow2_make_empty,
6155 
6156     .bdrv_snapshot_create               = qcow2_snapshot_create,
6157     .bdrv_snapshot_goto                 = qcow2_snapshot_goto,
6158     .bdrv_snapshot_delete               = qcow2_snapshot_delete,
6159     .bdrv_snapshot_list                 = qcow2_snapshot_list,
6160     .bdrv_snapshot_load_tmp             = qcow2_snapshot_load_tmp,
6161     .bdrv_measure                       = qcow2_measure,
6162     .bdrv_co_get_info                   = qcow2_co_get_info,
6163     .bdrv_get_specific_info             = qcow2_get_specific_info,
6164 
6165     .bdrv_co_save_vmstate               = qcow2_co_save_vmstate,
6166     .bdrv_co_load_vmstate               = qcow2_co_load_vmstate,
6167 
6168     .is_format                          = true,
6169     .supports_backing                   = true,
6170     .bdrv_co_change_backing_file        = qcow2_co_change_backing_file,
6171 
6172     .bdrv_refresh_limits                = qcow2_refresh_limits,
6173     .bdrv_co_invalidate_cache           = qcow2_co_invalidate_cache,
6174     .bdrv_inactivate                    = qcow2_inactivate,
6175 
6176     .create_opts                        = &qcow2_create_opts,
6177     .amend_opts                         = &qcow2_amend_opts,
6178     .strong_runtime_opts                = qcow2_strong_runtime_opts,
6179     .mutable_opts                       = mutable_opts,
6180     .bdrv_co_check                      = qcow2_co_check,
6181     .bdrv_amend_options                 = qcow2_amend_options,
6182     .bdrv_co_amend                      = qcow2_co_amend,
6183 
6184     .bdrv_detach_aio_context            = qcow2_detach_aio_context,
6185     .bdrv_attach_aio_context            = qcow2_attach_aio_context,
6186 
6187     .bdrv_supports_persistent_dirty_bitmap =
6188             qcow2_supports_persistent_dirty_bitmap,
6189     .bdrv_co_can_store_new_dirty_bitmap = qcow2_co_can_store_new_dirty_bitmap,
6190     .bdrv_co_remove_persistent_dirty_bitmap =
6191             qcow2_co_remove_persistent_dirty_bitmap,
6192 };
6193 
6194 static void bdrv_qcow2_init(void)
6195 {
6196     bdrv_register(&bdrv_qcow2);
6197 }
6198 
6199 block_init(bdrv_qcow2_init);
6200