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