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