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