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