xref: /openbmc/qemu/block/qcow2.c (revision afd76ffba966a072a7bbd0048bdf3b2ab69d3d4a)
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 "block/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 "block/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_co_preadv(BlockDriverState *bs, uint64_t offset,
1765                                         uint64_t bytes, QEMUIOVector *qiov,
1766                                         int flags)
1767 {
1768     BDRVQcow2State *s = bs->opaque;
1769     int offset_in_cluster;
1770     int ret;
1771     unsigned int cur_bytes; /* number of bytes in current iteration */
1772     uint64_t cluster_offset = 0;
1773     uint64_t bytes_done = 0;
1774     QEMUIOVector hd_qiov;
1775     uint8_t *cluster_data = NULL;
1776 
1777     qemu_iovec_init(&hd_qiov, qiov->niov);
1778 
1779     qemu_co_mutex_lock(&s->lock);
1780 
1781     while (bytes != 0) {
1782 
1783         /* prepare next request */
1784         cur_bytes = MIN(bytes, INT_MAX);
1785         if (s->crypto) {
1786             cur_bytes = MIN(cur_bytes,
1787                             QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
1788         }
1789 
1790         ret = qcow2_get_cluster_offset(bs, offset, &cur_bytes, &cluster_offset);
1791         if (ret < 0) {
1792             goto fail;
1793         }
1794 
1795         offset_in_cluster = offset_into_cluster(s, offset);
1796 
1797         qemu_iovec_reset(&hd_qiov);
1798         qemu_iovec_concat(&hd_qiov, qiov, bytes_done, cur_bytes);
1799 
1800         switch (ret) {
1801         case QCOW2_CLUSTER_UNALLOCATED:
1802 
1803             if (bs->backing) {
1804                 BLKDBG_EVENT(bs->file, BLKDBG_READ_BACKING_AIO);
1805                 qemu_co_mutex_unlock(&s->lock);
1806                 ret = bdrv_co_preadv(bs->backing, offset, cur_bytes,
1807                                      &hd_qiov, 0);
1808                 qemu_co_mutex_lock(&s->lock);
1809                 if (ret < 0) {
1810                     goto fail;
1811                 }
1812             } else {
1813                 /* Note: in this case, no need to wait */
1814                 qemu_iovec_memset(&hd_qiov, 0, 0, cur_bytes);
1815             }
1816             break;
1817 
1818         case QCOW2_CLUSTER_ZERO_PLAIN:
1819         case QCOW2_CLUSTER_ZERO_ALLOC:
1820             qemu_iovec_memset(&hd_qiov, 0, 0, cur_bytes);
1821             break;
1822 
1823         case QCOW2_CLUSTER_COMPRESSED:
1824             /* add AIO support for compressed blocks ? */
1825             ret = qcow2_decompress_cluster(bs, cluster_offset);
1826             if (ret < 0) {
1827                 goto fail;
1828             }
1829 
1830             qemu_iovec_from_buf(&hd_qiov, 0,
1831                                 s->cluster_cache + offset_in_cluster,
1832                                 cur_bytes);
1833             break;
1834 
1835         case QCOW2_CLUSTER_NORMAL:
1836             if ((cluster_offset & 511) != 0) {
1837                 ret = -EIO;
1838                 goto fail;
1839             }
1840 
1841             if (bs->encrypted) {
1842                 assert(s->crypto);
1843 
1844                 /*
1845                  * For encrypted images, read everything into a temporary
1846                  * contiguous buffer on which the AES functions can work.
1847                  */
1848                 if (!cluster_data) {
1849                     cluster_data =
1850                         qemu_try_blockalign(bs->file->bs,
1851                                             QCOW_MAX_CRYPT_CLUSTERS
1852                                             * s->cluster_size);
1853                     if (cluster_data == NULL) {
1854                         ret = -ENOMEM;
1855                         goto fail;
1856                     }
1857                 }
1858 
1859                 assert(cur_bytes <= QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
1860                 qemu_iovec_reset(&hd_qiov);
1861                 qemu_iovec_add(&hd_qiov, cluster_data, cur_bytes);
1862             }
1863 
1864             BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);
1865             qemu_co_mutex_unlock(&s->lock);
1866             ret = bdrv_co_preadv(bs->file,
1867                                  cluster_offset + offset_in_cluster,
1868                                  cur_bytes, &hd_qiov, 0);
1869             qemu_co_mutex_lock(&s->lock);
1870             if (ret < 0) {
1871                 goto fail;
1872             }
1873             if (bs->encrypted) {
1874                 assert(s->crypto);
1875                 assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);
1876                 assert((cur_bytes & (BDRV_SECTOR_SIZE - 1)) == 0);
1877                 if (qcrypto_block_decrypt(s->crypto,
1878                                           (s->crypt_physical_offset ?
1879                                            cluster_offset + offset_in_cluster :
1880                                            offset),
1881                                           cluster_data,
1882                                           cur_bytes,
1883                                           NULL) < 0) {
1884                     ret = -EIO;
1885                     goto fail;
1886                 }
1887                 qemu_iovec_from_buf(qiov, bytes_done, cluster_data, cur_bytes);
1888             }
1889             break;
1890 
1891         default:
1892             g_assert_not_reached();
1893             ret = -EIO;
1894             goto fail;
1895         }
1896 
1897         bytes -= cur_bytes;
1898         offset += cur_bytes;
1899         bytes_done += cur_bytes;
1900     }
1901     ret = 0;
1902 
1903 fail:
1904     qemu_co_mutex_unlock(&s->lock);
1905 
1906     qemu_iovec_destroy(&hd_qiov);
1907     qemu_vfree(cluster_data);
1908 
1909     return ret;
1910 }
1911 
1912 /* Check if it's possible to merge a write request with the writing of
1913  * the data from the COW regions */
1914 static bool merge_cow(uint64_t offset, unsigned bytes,
1915                       QEMUIOVector *hd_qiov, QCowL2Meta *l2meta)
1916 {
1917     QCowL2Meta *m;
1918 
1919     for (m = l2meta; m != NULL; m = m->next) {
1920         /* If both COW regions are empty then there's nothing to merge */
1921         if (m->cow_start.nb_bytes == 0 && m->cow_end.nb_bytes == 0) {
1922             continue;
1923         }
1924 
1925         /* The data (middle) region must be immediately after the
1926          * start region */
1927         if (l2meta_cow_start(m) + m->cow_start.nb_bytes != offset) {
1928             continue;
1929         }
1930 
1931         /* The end region must be immediately after the data (middle)
1932          * region */
1933         if (m->offset + m->cow_end.offset != offset + bytes) {
1934             continue;
1935         }
1936 
1937         /* Make sure that adding both COW regions to the QEMUIOVector
1938          * does not exceed IOV_MAX */
1939         if (hd_qiov->niov > IOV_MAX - 2) {
1940             continue;
1941         }
1942 
1943         m->data_qiov = hd_qiov;
1944         return true;
1945     }
1946 
1947     return false;
1948 }
1949 
1950 static coroutine_fn int qcow2_co_pwritev(BlockDriverState *bs, uint64_t offset,
1951                                          uint64_t bytes, QEMUIOVector *qiov,
1952                                          int flags)
1953 {
1954     BDRVQcow2State *s = bs->opaque;
1955     int offset_in_cluster;
1956     int ret;
1957     unsigned int cur_bytes; /* number of sectors in current iteration */
1958     uint64_t cluster_offset;
1959     QEMUIOVector hd_qiov;
1960     uint64_t bytes_done = 0;
1961     uint8_t *cluster_data = NULL;
1962     QCowL2Meta *l2meta = NULL;
1963 
1964     trace_qcow2_writev_start_req(qemu_coroutine_self(), offset, bytes);
1965 
1966     qemu_iovec_init(&hd_qiov, qiov->niov);
1967 
1968     s->cluster_cache_offset = -1; /* disable compressed cache */
1969 
1970     qemu_co_mutex_lock(&s->lock);
1971 
1972     while (bytes != 0) {
1973 
1974         l2meta = NULL;
1975 
1976         trace_qcow2_writev_start_part(qemu_coroutine_self());
1977         offset_in_cluster = offset_into_cluster(s, offset);
1978         cur_bytes = MIN(bytes, INT_MAX);
1979         if (bs->encrypted) {
1980             cur_bytes = MIN(cur_bytes,
1981                             QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size
1982                             - offset_in_cluster);
1983         }
1984 
1985         ret = qcow2_alloc_cluster_offset(bs, offset, &cur_bytes,
1986                                          &cluster_offset, &l2meta);
1987         if (ret < 0) {
1988             goto fail;
1989         }
1990 
1991         assert((cluster_offset & 511) == 0);
1992 
1993         qemu_iovec_reset(&hd_qiov);
1994         qemu_iovec_concat(&hd_qiov, qiov, bytes_done, cur_bytes);
1995 
1996         if (bs->encrypted) {
1997             assert(s->crypto);
1998             if (!cluster_data) {
1999                 cluster_data = qemu_try_blockalign(bs->file->bs,
2000                                                    QCOW_MAX_CRYPT_CLUSTERS
2001                                                    * s->cluster_size);
2002                 if (cluster_data == NULL) {
2003                     ret = -ENOMEM;
2004                     goto fail;
2005                 }
2006             }
2007 
2008             assert(hd_qiov.size <=
2009                    QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
2010             qemu_iovec_to_buf(&hd_qiov, 0, cluster_data, hd_qiov.size);
2011 
2012             if (qcrypto_block_encrypt(s->crypto,
2013                                       (s->crypt_physical_offset ?
2014                                        cluster_offset + offset_in_cluster :
2015                                        offset),
2016                                       cluster_data,
2017                                       cur_bytes, NULL) < 0) {
2018                 ret = -EIO;
2019                 goto fail;
2020             }
2021 
2022             qemu_iovec_reset(&hd_qiov);
2023             qemu_iovec_add(&hd_qiov, cluster_data, cur_bytes);
2024         }
2025 
2026         ret = qcow2_pre_write_overlap_check(bs, 0,
2027                 cluster_offset + offset_in_cluster, cur_bytes);
2028         if (ret < 0) {
2029             goto fail;
2030         }
2031 
2032         /* If we need to do COW, check if it's possible to merge the
2033          * writing of the guest data together with that of the COW regions.
2034          * If it's not possible (or not necessary) then write the
2035          * guest data now. */
2036         if (!merge_cow(offset, cur_bytes, &hd_qiov, l2meta)) {
2037             qemu_co_mutex_unlock(&s->lock);
2038             BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO);
2039             trace_qcow2_writev_data(qemu_coroutine_self(),
2040                                     cluster_offset + offset_in_cluster);
2041             ret = bdrv_co_pwritev(bs->file,
2042                                   cluster_offset + offset_in_cluster,
2043                                   cur_bytes, &hd_qiov, 0);
2044             qemu_co_mutex_lock(&s->lock);
2045             if (ret < 0) {
2046                 goto fail;
2047             }
2048         }
2049 
2050         while (l2meta != NULL) {
2051             QCowL2Meta *next;
2052 
2053             ret = qcow2_alloc_cluster_link_l2(bs, l2meta);
2054             if (ret < 0) {
2055                 goto fail;
2056             }
2057 
2058             /* Take the request off the list of running requests */
2059             if (l2meta->nb_clusters != 0) {
2060                 QLIST_REMOVE(l2meta, next_in_flight);
2061             }
2062 
2063             qemu_co_queue_restart_all(&l2meta->dependent_requests);
2064 
2065             next = l2meta->next;
2066             g_free(l2meta);
2067             l2meta = next;
2068         }
2069 
2070         bytes -= cur_bytes;
2071         offset += cur_bytes;
2072         bytes_done += cur_bytes;
2073         trace_qcow2_writev_done_part(qemu_coroutine_self(), cur_bytes);
2074     }
2075     ret = 0;
2076 
2077 fail:
2078     while (l2meta != NULL) {
2079         QCowL2Meta *next;
2080 
2081         if (l2meta->nb_clusters != 0) {
2082             QLIST_REMOVE(l2meta, next_in_flight);
2083         }
2084         qemu_co_queue_restart_all(&l2meta->dependent_requests);
2085 
2086         next = l2meta->next;
2087         g_free(l2meta);
2088         l2meta = next;
2089     }
2090 
2091     qemu_co_mutex_unlock(&s->lock);
2092 
2093     qemu_iovec_destroy(&hd_qiov);
2094     qemu_vfree(cluster_data);
2095     trace_qcow2_writev_done_req(qemu_coroutine_self(), ret);
2096 
2097     return ret;
2098 }
2099 
2100 static int qcow2_inactivate(BlockDriverState *bs)
2101 {
2102     BDRVQcow2State *s = bs->opaque;
2103     int ret, result = 0;
2104     Error *local_err = NULL;
2105 
2106     qcow2_store_persistent_dirty_bitmaps(bs, &local_err);
2107     if (local_err != NULL) {
2108         result = -EINVAL;
2109         error_report_err(local_err);
2110         error_report("Persistent bitmaps are lost for node '%s'",
2111                      bdrv_get_device_or_node_name(bs));
2112     }
2113 
2114     ret = qcow2_cache_flush(bs, s->l2_table_cache);
2115     if (ret) {
2116         result = ret;
2117         error_report("Failed to flush the L2 table cache: %s",
2118                      strerror(-ret));
2119     }
2120 
2121     ret = qcow2_cache_flush(bs, s->refcount_block_cache);
2122     if (ret) {
2123         result = ret;
2124         error_report("Failed to flush the refcount block cache: %s",
2125                      strerror(-ret));
2126     }
2127 
2128     if (result == 0) {
2129         qcow2_mark_clean(bs);
2130     }
2131 
2132     return result;
2133 }
2134 
2135 static void qcow2_close(BlockDriverState *bs)
2136 {
2137     BDRVQcow2State *s = bs->opaque;
2138     qemu_vfree(s->l1_table);
2139     /* else pre-write overlap checks in cache_destroy may crash */
2140     s->l1_table = NULL;
2141 
2142     if (!(s->flags & BDRV_O_INACTIVE)) {
2143         qcow2_inactivate(bs);
2144     }
2145 
2146     cache_clean_timer_del(bs);
2147     qcow2_cache_destroy(s->l2_table_cache);
2148     qcow2_cache_destroy(s->refcount_block_cache);
2149 
2150     qcrypto_block_free(s->crypto);
2151     s->crypto = NULL;
2152 
2153     g_free(s->unknown_header_fields);
2154     cleanup_unknown_header_ext(bs);
2155 
2156     g_free(s->image_backing_file);
2157     g_free(s->image_backing_format);
2158 
2159     g_free(s->cluster_cache);
2160     qemu_vfree(s->cluster_data);
2161     qcow2_refcount_close(bs);
2162     qcow2_free_snapshots(bs);
2163 }
2164 
2165 static void coroutine_fn qcow2_co_invalidate_cache(BlockDriverState *bs,
2166                                                    Error **errp)
2167 {
2168     BDRVQcow2State *s = bs->opaque;
2169     int flags = s->flags;
2170     QCryptoBlock *crypto = NULL;
2171     QDict *options;
2172     Error *local_err = NULL;
2173     int ret;
2174 
2175     /*
2176      * Backing files are read-only which makes all of their metadata immutable,
2177      * that means we don't have to worry about reopening them here.
2178      */
2179 
2180     crypto = s->crypto;
2181     s->crypto = NULL;
2182 
2183     qcow2_close(bs);
2184 
2185     memset(s, 0, sizeof(BDRVQcow2State));
2186     options = qdict_clone_shallow(bs->options);
2187 
2188     flags &= ~BDRV_O_INACTIVE;
2189     qemu_co_mutex_lock(&s->lock);
2190     ret = qcow2_do_open(bs, options, flags, &local_err);
2191     qemu_co_mutex_unlock(&s->lock);
2192     qobject_unref(options);
2193     if (local_err) {
2194         error_propagate(errp, local_err);
2195         error_prepend(errp, "Could not reopen qcow2 layer: ");
2196         bs->drv = NULL;
2197         return;
2198     } else if (ret < 0) {
2199         error_setg_errno(errp, -ret, "Could not reopen qcow2 layer");
2200         bs->drv = NULL;
2201         return;
2202     }
2203 
2204     s->crypto = crypto;
2205 }
2206 
2207 static size_t header_ext_add(char *buf, uint32_t magic, const void *s,
2208     size_t len, size_t buflen)
2209 {
2210     QCowExtension *ext_backing_fmt = (QCowExtension*) buf;
2211     size_t ext_len = sizeof(QCowExtension) + ((len + 7) & ~7);
2212 
2213     if (buflen < ext_len) {
2214         return -ENOSPC;
2215     }
2216 
2217     *ext_backing_fmt = (QCowExtension) {
2218         .magic  = cpu_to_be32(magic),
2219         .len    = cpu_to_be32(len),
2220     };
2221 
2222     if (len) {
2223         memcpy(buf + sizeof(QCowExtension), s, len);
2224     }
2225 
2226     return ext_len;
2227 }
2228 
2229 /*
2230  * Updates the qcow2 header, including the variable length parts of it, i.e.
2231  * the backing file name and all extensions. qcow2 was not designed to allow
2232  * such changes, so if we run out of space (we can only use the first cluster)
2233  * this function may fail.
2234  *
2235  * Returns 0 on success, -errno in error cases.
2236  */
2237 int qcow2_update_header(BlockDriverState *bs)
2238 {
2239     BDRVQcow2State *s = bs->opaque;
2240     QCowHeader *header;
2241     char *buf;
2242     size_t buflen = s->cluster_size;
2243     int ret;
2244     uint64_t total_size;
2245     uint32_t refcount_table_clusters;
2246     size_t header_length;
2247     Qcow2UnknownHeaderExtension *uext;
2248 
2249     buf = qemu_blockalign(bs, buflen);
2250 
2251     /* Header structure */
2252     header = (QCowHeader*) buf;
2253 
2254     if (buflen < sizeof(*header)) {
2255         ret = -ENOSPC;
2256         goto fail;
2257     }
2258 
2259     header_length = sizeof(*header) + s->unknown_header_fields_size;
2260     total_size = bs->total_sectors * BDRV_SECTOR_SIZE;
2261     refcount_table_clusters = s->refcount_table_size >> (s->cluster_bits - 3);
2262 
2263     *header = (QCowHeader) {
2264         /* Version 2 fields */
2265         .magic                  = cpu_to_be32(QCOW_MAGIC),
2266         .version                = cpu_to_be32(s->qcow_version),
2267         .backing_file_offset    = 0,
2268         .backing_file_size      = 0,
2269         .cluster_bits           = cpu_to_be32(s->cluster_bits),
2270         .size                   = cpu_to_be64(total_size),
2271         .crypt_method           = cpu_to_be32(s->crypt_method_header),
2272         .l1_size                = cpu_to_be32(s->l1_size),
2273         .l1_table_offset        = cpu_to_be64(s->l1_table_offset),
2274         .refcount_table_offset  = cpu_to_be64(s->refcount_table_offset),
2275         .refcount_table_clusters = cpu_to_be32(refcount_table_clusters),
2276         .nb_snapshots           = cpu_to_be32(s->nb_snapshots),
2277         .snapshots_offset       = cpu_to_be64(s->snapshots_offset),
2278 
2279         /* Version 3 fields */
2280         .incompatible_features  = cpu_to_be64(s->incompatible_features),
2281         .compatible_features    = cpu_to_be64(s->compatible_features),
2282         .autoclear_features     = cpu_to_be64(s->autoclear_features),
2283         .refcount_order         = cpu_to_be32(s->refcount_order),
2284         .header_length          = cpu_to_be32(header_length),
2285     };
2286 
2287     /* For older versions, write a shorter header */
2288     switch (s->qcow_version) {
2289     case 2:
2290         ret = offsetof(QCowHeader, incompatible_features);
2291         break;
2292     case 3:
2293         ret = sizeof(*header);
2294         break;
2295     default:
2296         ret = -EINVAL;
2297         goto fail;
2298     }
2299 
2300     buf += ret;
2301     buflen -= ret;
2302     memset(buf, 0, buflen);
2303 
2304     /* Preserve any unknown field in the header */
2305     if (s->unknown_header_fields_size) {
2306         if (buflen < s->unknown_header_fields_size) {
2307             ret = -ENOSPC;
2308             goto fail;
2309         }
2310 
2311         memcpy(buf, s->unknown_header_fields, s->unknown_header_fields_size);
2312         buf += s->unknown_header_fields_size;
2313         buflen -= s->unknown_header_fields_size;
2314     }
2315 
2316     /* Backing file format header extension */
2317     if (s->image_backing_format) {
2318         ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BACKING_FORMAT,
2319                              s->image_backing_format,
2320                              strlen(s->image_backing_format),
2321                              buflen);
2322         if (ret < 0) {
2323             goto fail;
2324         }
2325 
2326         buf += ret;
2327         buflen -= ret;
2328     }
2329 
2330     /* Full disk encryption header pointer extension */
2331     if (s->crypto_header.offset != 0) {
2332         cpu_to_be64s(&s->crypto_header.offset);
2333         cpu_to_be64s(&s->crypto_header.length);
2334         ret = header_ext_add(buf, QCOW2_EXT_MAGIC_CRYPTO_HEADER,
2335                              &s->crypto_header, sizeof(s->crypto_header),
2336                              buflen);
2337         be64_to_cpus(&s->crypto_header.offset);
2338         be64_to_cpus(&s->crypto_header.length);
2339         if (ret < 0) {
2340             goto fail;
2341         }
2342         buf += ret;
2343         buflen -= ret;
2344     }
2345 
2346     /* Feature table */
2347     if (s->qcow_version >= 3) {
2348         Qcow2Feature features[] = {
2349             {
2350                 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
2351                 .bit  = QCOW2_INCOMPAT_DIRTY_BITNR,
2352                 .name = "dirty bit",
2353             },
2354             {
2355                 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
2356                 .bit  = QCOW2_INCOMPAT_CORRUPT_BITNR,
2357                 .name = "corrupt bit",
2358             },
2359             {
2360                 .type = QCOW2_FEAT_TYPE_COMPATIBLE,
2361                 .bit  = QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR,
2362                 .name = "lazy refcounts",
2363             },
2364         };
2365 
2366         ret = header_ext_add(buf, QCOW2_EXT_MAGIC_FEATURE_TABLE,
2367                              features, sizeof(features), buflen);
2368         if (ret < 0) {
2369             goto fail;
2370         }
2371         buf += ret;
2372         buflen -= ret;
2373     }
2374 
2375     /* Bitmap extension */
2376     if (s->nb_bitmaps > 0) {
2377         Qcow2BitmapHeaderExt bitmaps_header = {
2378             .nb_bitmaps = cpu_to_be32(s->nb_bitmaps),
2379             .bitmap_directory_size =
2380                     cpu_to_be64(s->bitmap_directory_size),
2381             .bitmap_directory_offset =
2382                     cpu_to_be64(s->bitmap_directory_offset)
2383         };
2384         ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BITMAPS,
2385                              &bitmaps_header, sizeof(bitmaps_header),
2386                              buflen);
2387         if (ret < 0) {
2388             goto fail;
2389         }
2390         buf += ret;
2391         buflen -= ret;
2392     }
2393 
2394     /* Keep unknown header extensions */
2395     QLIST_FOREACH(uext, &s->unknown_header_ext, next) {
2396         ret = header_ext_add(buf, uext->magic, uext->data, uext->len, buflen);
2397         if (ret < 0) {
2398             goto fail;
2399         }
2400 
2401         buf += ret;
2402         buflen -= ret;
2403     }
2404 
2405     /* End of header extensions */
2406     ret = header_ext_add(buf, QCOW2_EXT_MAGIC_END, NULL, 0, buflen);
2407     if (ret < 0) {
2408         goto fail;
2409     }
2410 
2411     buf += ret;
2412     buflen -= ret;
2413 
2414     /* Backing file name */
2415     if (s->image_backing_file) {
2416         size_t backing_file_len = strlen(s->image_backing_file);
2417 
2418         if (buflen < backing_file_len) {
2419             ret = -ENOSPC;
2420             goto fail;
2421         }
2422 
2423         /* Using strncpy is ok here, since buf is not NUL-terminated. */
2424         strncpy(buf, s->image_backing_file, buflen);
2425 
2426         header->backing_file_offset = cpu_to_be64(buf - ((char*) header));
2427         header->backing_file_size   = cpu_to_be32(backing_file_len);
2428     }
2429 
2430     /* Write the new header */
2431     ret = bdrv_pwrite(bs->file, 0, header, s->cluster_size);
2432     if (ret < 0) {
2433         goto fail;
2434     }
2435 
2436     ret = 0;
2437 fail:
2438     qemu_vfree(header);
2439     return ret;
2440 }
2441 
2442 static int qcow2_change_backing_file(BlockDriverState *bs,
2443     const char *backing_file, const char *backing_fmt)
2444 {
2445     BDRVQcow2State *s = bs->opaque;
2446 
2447     if (backing_file && strlen(backing_file) > 1023) {
2448         return -EINVAL;
2449     }
2450 
2451     pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
2452     pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
2453 
2454     g_free(s->image_backing_file);
2455     g_free(s->image_backing_format);
2456 
2457     s->image_backing_file = backing_file ? g_strdup(bs->backing_file) : NULL;
2458     s->image_backing_format = backing_fmt ? g_strdup(bs->backing_format) : NULL;
2459 
2460     return qcow2_update_header(bs);
2461 }
2462 
2463 static int qcow2_crypt_method_from_format(const char *encryptfmt)
2464 {
2465     if (g_str_equal(encryptfmt, "luks")) {
2466         return QCOW_CRYPT_LUKS;
2467     } else if (g_str_equal(encryptfmt, "aes")) {
2468         return QCOW_CRYPT_AES;
2469     } else {
2470         return -EINVAL;
2471     }
2472 }
2473 
2474 static int qcow2_set_up_encryption(BlockDriverState *bs,
2475                                    QCryptoBlockCreateOptions *cryptoopts,
2476                                    Error **errp)
2477 {
2478     BDRVQcow2State *s = bs->opaque;
2479     QCryptoBlock *crypto = NULL;
2480     int fmt, ret;
2481 
2482     switch (cryptoopts->format) {
2483     case Q_CRYPTO_BLOCK_FORMAT_LUKS:
2484         fmt = QCOW_CRYPT_LUKS;
2485         break;
2486     case Q_CRYPTO_BLOCK_FORMAT_QCOW:
2487         fmt = QCOW_CRYPT_AES;
2488         break;
2489     default:
2490         error_setg(errp, "Crypto format not supported in qcow2");
2491         return -EINVAL;
2492     }
2493 
2494     s->crypt_method_header = fmt;
2495 
2496     crypto = qcrypto_block_create(cryptoopts, "encrypt.",
2497                                   qcow2_crypto_hdr_init_func,
2498                                   qcow2_crypto_hdr_write_func,
2499                                   bs, errp);
2500     if (!crypto) {
2501         return -EINVAL;
2502     }
2503 
2504     ret = qcow2_update_header(bs);
2505     if (ret < 0) {
2506         error_setg_errno(errp, -ret, "Could not write encryption header");
2507         goto out;
2508     }
2509 
2510     ret = 0;
2511  out:
2512     qcrypto_block_free(crypto);
2513     return ret;
2514 }
2515 
2516 
2517 typedef struct PreallocCo {
2518     BlockDriverState *bs;
2519     uint64_t offset;
2520     uint64_t new_length;
2521 
2522     int ret;
2523 } PreallocCo;
2524 
2525 /**
2526  * Preallocates metadata structures for data clusters between @offset (in the
2527  * guest disk) and @new_length (which is thus generally the new guest disk
2528  * size).
2529  *
2530  * Returns: 0 on success, -errno on failure.
2531  */
2532 static void coroutine_fn preallocate_co(void *opaque)
2533 {
2534     PreallocCo *params = opaque;
2535     BlockDriverState *bs = params->bs;
2536     uint64_t offset = params->offset;
2537     uint64_t new_length = params->new_length;
2538     BDRVQcow2State *s = bs->opaque;
2539     uint64_t bytes;
2540     uint64_t host_offset = 0;
2541     unsigned int cur_bytes;
2542     int ret;
2543     QCowL2Meta *meta;
2544 
2545     qemu_co_mutex_lock(&s->lock);
2546 
2547     assert(offset <= new_length);
2548     bytes = new_length - offset;
2549 
2550     while (bytes) {
2551         cur_bytes = MIN(bytes, INT_MAX);
2552         ret = qcow2_alloc_cluster_offset(bs, offset, &cur_bytes,
2553                                          &host_offset, &meta);
2554         if (ret < 0) {
2555             goto done;
2556         }
2557 
2558         while (meta) {
2559             QCowL2Meta *next = meta->next;
2560 
2561             ret = qcow2_alloc_cluster_link_l2(bs, meta);
2562             if (ret < 0) {
2563                 qcow2_free_any_clusters(bs, meta->alloc_offset,
2564                                         meta->nb_clusters, QCOW2_DISCARD_NEVER);
2565                 goto done;
2566             }
2567 
2568             /* There are no dependent requests, but we need to remove our
2569              * request from the list of in-flight requests */
2570             QLIST_REMOVE(meta, next_in_flight);
2571 
2572             g_free(meta);
2573             meta = next;
2574         }
2575 
2576         /* TODO Preallocate data if requested */
2577 
2578         bytes -= cur_bytes;
2579         offset += cur_bytes;
2580     }
2581 
2582     /*
2583      * It is expected that the image file is large enough to actually contain
2584      * all of the allocated clusters (otherwise we get failing reads after
2585      * EOF). Extend the image to the last allocated sector.
2586      */
2587     if (host_offset != 0) {
2588         uint8_t data = 0;
2589         ret = bdrv_pwrite(bs->file, (host_offset + cur_bytes) - 1,
2590                           &data, 1);
2591         if (ret < 0) {
2592             goto done;
2593         }
2594     }
2595 
2596     ret = 0;
2597 
2598 done:
2599     qemu_co_mutex_unlock(&s->lock);
2600     params->ret = ret;
2601 }
2602 
2603 static int preallocate(BlockDriverState *bs,
2604                        uint64_t offset, uint64_t new_length)
2605 {
2606     PreallocCo params = {
2607         .bs         = bs,
2608         .offset     = offset,
2609         .new_length = new_length,
2610         .ret        = -EINPROGRESS,
2611     };
2612 
2613     if (qemu_in_coroutine()) {
2614         preallocate_co(&params);
2615     } else {
2616         Coroutine *co = qemu_coroutine_create(preallocate_co, &params);
2617         bdrv_coroutine_enter(bs, co);
2618         BDRV_POLL_WHILE(bs, params.ret == -EINPROGRESS);
2619     }
2620     return params.ret;
2621 }
2622 
2623 /* qcow2_refcount_metadata_size:
2624  * @clusters: number of clusters to refcount (including data and L1/L2 tables)
2625  * @cluster_size: size of a cluster, in bytes
2626  * @refcount_order: refcount bits power-of-2 exponent
2627  * @generous_increase: allow for the refcount table to be 1.5x as large as it
2628  *                     needs to be
2629  *
2630  * Returns: Number of bytes required for refcount blocks and table metadata.
2631  */
2632 int64_t qcow2_refcount_metadata_size(int64_t clusters, size_t cluster_size,
2633                                      int refcount_order, bool generous_increase,
2634                                      uint64_t *refblock_count)
2635 {
2636     /*
2637      * Every host cluster is reference-counted, including metadata (even
2638      * refcount metadata is recursively included).
2639      *
2640      * An accurate formula for the size of refcount metadata size is difficult
2641      * to derive.  An easier method of calculation is finding the fixed point
2642      * where no further refcount blocks or table clusters are required to
2643      * reference count every cluster.
2644      */
2645     int64_t blocks_per_table_cluster = cluster_size / sizeof(uint64_t);
2646     int64_t refcounts_per_block = cluster_size * 8 / (1 << refcount_order);
2647     int64_t table = 0;  /* number of refcount table clusters */
2648     int64_t blocks = 0; /* number of refcount block clusters */
2649     int64_t last;
2650     int64_t n = 0;
2651 
2652     do {
2653         last = n;
2654         blocks = DIV_ROUND_UP(clusters + table + blocks, refcounts_per_block);
2655         table = DIV_ROUND_UP(blocks, blocks_per_table_cluster);
2656         n = clusters + blocks + table;
2657 
2658         if (n == last && generous_increase) {
2659             clusters += DIV_ROUND_UP(table, 2);
2660             n = 0; /* force another loop */
2661             generous_increase = false;
2662         }
2663     } while (n != last);
2664 
2665     if (refblock_count) {
2666         *refblock_count = blocks;
2667     }
2668 
2669     return (blocks + table) * cluster_size;
2670 }
2671 
2672 /**
2673  * qcow2_calc_prealloc_size:
2674  * @total_size: virtual disk size in bytes
2675  * @cluster_size: cluster size in bytes
2676  * @refcount_order: refcount bits power-of-2 exponent
2677  *
2678  * Returns: Total number of bytes required for the fully allocated image
2679  * (including metadata).
2680  */
2681 static int64_t qcow2_calc_prealloc_size(int64_t total_size,
2682                                         size_t cluster_size,
2683                                         int refcount_order)
2684 {
2685     int64_t meta_size = 0;
2686     uint64_t nl1e, nl2e;
2687     int64_t aligned_total_size = ROUND_UP(total_size, cluster_size);
2688 
2689     /* header: 1 cluster */
2690     meta_size += cluster_size;
2691 
2692     /* total size of L2 tables */
2693     nl2e = aligned_total_size / cluster_size;
2694     nl2e = ROUND_UP(nl2e, cluster_size / sizeof(uint64_t));
2695     meta_size += nl2e * sizeof(uint64_t);
2696 
2697     /* total size of L1 tables */
2698     nl1e = nl2e * sizeof(uint64_t) / cluster_size;
2699     nl1e = ROUND_UP(nl1e, cluster_size / sizeof(uint64_t));
2700     meta_size += nl1e * sizeof(uint64_t);
2701 
2702     /* total size of refcount table and blocks */
2703     meta_size += qcow2_refcount_metadata_size(
2704             (meta_size + aligned_total_size) / cluster_size,
2705             cluster_size, refcount_order, false, NULL);
2706 
2707     return meta_size + aligned_total_size;
2708 }
2709 
2710 static bool validate_cluster_size(size_t cluster_size, Error **errp)
2711 {
2712     int cluster_bits = ctz32(cluster_size);
2713     if (cluster_bits < MIN_CLUSTER_BITS || cluster_bits > MAX_CLUSTER_BITS ||
2714         (1 << cluster_bits) != cluster_size)
2715     {
2716         error_setg(errp, "Cluster size must be a power of two between %d and "
2717                    "%dk", 1 << MIN_CLUSTER_BITS, 1 << (MAX_CLUSTER_BITS - 10));
2718         return false;
2719     }
2720     return true;
2721 }
2722 
2723 static size_t qcow2_opt_get_cluster_size_del(QemuOpts *opts, Error **errp)
2724 {
2725     size_t cluster_size;
2726 
2727     cluster_size = qemu_opt_get_size_del(opts, BLOCK_OPT_CLUSTER_SIZE,
2728                                          DEFAULT_CLUSTER_SIZE);
2729     if (!validate_cluster_size(cluster_size, errp)) {
2730         return 0;
2731     }
2732     return cluster_size;
2733 }
2734 
2735 static int qcow2_opt_get_version_del(QemuOpts *opts, Error **errp)
2736 {
2737     char *buf;
2738     int ret;
2739 
2740     buf = qemu_opt_get_del(opts, BLOCK_OPT_COMPAT_LEVEL);
2741     if (!buf) {
2742         ret = 3; /* default */
2743     } else if (!strcmp(buf, "0.10")) {
2744         ret = 2;
2745     } else if (!strcmp(buf, "1.1")) {
2746         ret = 3;
2747     } else {
2748         error_setg(errp, "Invalid compatibility level: '%s'", buf);
2749         ret = -EINVAL;
2750     }
2751     g_free(buf);
2752     return ret;
2753 }
2754 
2755 static uint64_t qcow2_opt_get_refcount_bits_del(QemuOpts *opts, int version,
2756                                                 Error **errp)
2757 {
2758     uint64_t refcount_bits;
2759 
2760     refcount_bits = qemu_opt_get_number_del(opts, BLOCK_OPT_REFCOUNT_BITS, 16);
2761     if (refcount_bits > 64 || !is_power_of_2(refcount_bits)) {
2762         error_setg(errp, "Refcount width must be a power of two and may not "
2763                    "exceed 64 bits");
2764         return 0;
2765     }
2766 
2767     if (version < 3 && refcount_bits != 16) {
2768         error_setg(errp, "Different refcount widths than 16 bits require "
2769                    "compatibility level 1.1 or above (use compat=1.1 or "
2770                    "greater)");
2771         return 0;
2772     }
2773 
2774     return refcount_bits;
2775 }
2776 
2777 static int coroutine_fn
2778 qcow2_co_create(BlockdevCreateOptions *create_options, Error **errp)
2779 {
2780     BlockdevCreateOptionsQcow2 *qcow2_opts;
2781     QDict *options;
2782 
2783     /*
2784      * Open the image file and write a minimal qcow2 header.
2785      *
2786      * We keep things simple and start with a zero-sized image. We also
2787      * do without refcount blocks or a L1 table for now. We'll fix the
2788      * inconsistency later.
2789      *
2790      * We do need a refcount table because growing the refcount table means
2791      * allocating two new refcount blocks - the seconds of which would be at
2792      * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
2793      * size for any qcow2 image.
2794      */
2795     BlockBackend *blk = NULL;
2796     BlockDriverState *bs = NULL;
2797     QCowHeader *header;
2798     size_t cluster_size;
2799     int version;
2800     int refcount_order;
2801     uint64_t* refcount_table;
2802     Error *local_err = NULL;
2803     int ret;
2804 
2805     assert(create_options->driver == BLOCKDEV_DRIVER_QCOW2);
2806     qcow2_opts = &create_options->u.qcow2;
2807 
2808     bs = bdrv_open_blockdev_ref(qcow2_opts->file, errp);
2809     if (bs == NULL) {
2810         return -EIO;
2811     }
2812 
2813     /* Validate options and set default values */
2814     if (!QEMU_IS_ALIGNED(qcow2_opts->size, BDRV_SECTOR_SIZE)) {
2815         error_setg(errp, "Image size must be a multiple of 512 bytes");
2816         ret = -EINVAL;
2817         goto out;
2818     }
2819 
2820     if (qcow2_opts->has_version) {
2821         switch (qcow2_opts->version) {
2822         case BLOCKDEV_QCOW2_VERSION_V2:
2823             version = 2;
2824             break;
2825         case BLOCKDEV_QCOW2_VERSION_V3:
2826             version = 3;
2827             break;
2828         default:
2829             g_assert_not_reached();
2830         }
2831     } else {
2832         version = 3;
2833     }
2834 
2835     if (qcow2_opts->has_cluster_size) {
2836         cluster_size = qcow2_opts->cluster_size;
2837     } else {
2838         cluster_size = DEFAULT_CLUSTER_SIZE;
2839     }
2840 
2841     if (!validate_cluster_size(cluster_size, errp)) {
2842         ret = -EINVAL;
2843         goto out;
2844     }
2845 
2846     if (!qcow2_opts->has_preallocation) {
2847         qcow2_opts->preallocation = PREALLOC_MODE_OFF;
2848     }
2849     if (qcow2_opts->has_backing_file &&
2850         qcow2_opts->preallocation != PREALLOC_MODE_OFF)
2851     {
2852         error_setg(errp, "Backing file and preallocation cannot be used at "
2853                    "the same time");
2854         ret = -EINVAL;
2855         goto out;
2856     }
2857     if (qcow2_opts->has_backing_fmt && !qcow2_opts->has_backing_file) {
2858         error_setg(errp, "Backing format cannot be used without backing file");
2859         ret = -EINVAL;
2860         goto out;
2861     }
2862 
2863     if (!qcow2_opts->has_lazy_refcounts) {
2864         qcow2_opts->lazy_refcounts = false;
2865     }
2866     if (version < 3 && qcow2_opts->lazy_refcounts) {
2867         error_setg(errp, "Lazy refcounts only supported with compatibility "
2868                    "level 1.1 and above (use version=v3 or greater)");
2869         ret = -EINVAL;
2870         goto out;
2871     }
2872 
2873     if (!qcow2_opts->has_refcount_bits) {
2874         qcow2_opts->refcount_bits = 16;
2875     }
2876     if (qcow2_opts->refcount_bits > 64 ||
2877         !is_power_of_2(qcow2_opts->refcount_bits))
2878     {
2879         error_setg(errp, "Refcount width must be a power of two and may not "
2880                    "exceed 64 bits");
2881         ret = -EINVAL;
2882         goto out;
2883     }
2884     if (version < 3 && qcow2_opts->refcount_bits != 16) {
2885         error_setg(errp, "Different refcount widths than 16 bits require "
2886                    "compatibility level 1.1 or above (use version=v3 or "
2887                    "greater)");
2888         ret = -EINVAL;
2889         goto out;
2890     }
2891     refcount_order = ctz32(qcow2_opts->refcount_bits);
2892 
2893 
2894     /* Create BlockBackend to write to the image */
2895     blk = blk_new(BLK_PERM_WRITE | BLK_PERM_RESIZE, BLK_PERM_ALL);
2896     ret = blk_insert_bs(blk, bs, errp);
2897     if (ret < 0) {
2898         goto out;
2899     }
2900     blk_set_allow_write_beyond_eof(blk, true);
2901 
2902     /* Clear the protocol layer and preallocate it if necessary */
2903     ret = blk_truncate(blk, 0, PREALLOC_MODE_OFF, errp);
2904     if (ret < 0) {
2905         goto out;
2906     }
2907 
2908     if (qcow2_opts->preallocation == PREALLOC_MODE_FULL ||
2909         qcow2_opts->preallocation == PREALLOC_MODE_FALLOC)
2910     {
2911         int64_t prealloc_size =
2912             qcow2_calc_prealloc_size(qcow2_opts->size, cluster_size,
2913                                      refcount_order);
2914 
2915         ret = blk_truncate(blk, prealloc_size, qcow2_opts->preallocation, errp);
2916         if (ret < 0) {
2917             goto out;
2918         }
2919     }
2920 
2921     /* Write the header */
2922     QEMU_BUILD_BUG_ON((1 << MIN_CLUSTER_BITS) < sizeof(*header));
2923     header = g_malloc0(cluster_size);
2924     *header = (QCowHeader) {
2925         .magic                      = cpu_to_be32(QCOW_MAGIC),
2926         .version                    = cpu_to_be32(version),
2927         .cluster_bits               = cpu_to_be32(ctz32(cluster_size)),
2928         .size                       = cpu_to_be64(0),
2929         .l1_table_offset            = cpu_to_be64(0),
2930         .l1_size                    = cpu_to_be32(0),
2931         .refcount_table_offset      = cpu_to_be64(cluster_size),
2932         .refcount_table_clusters    = cpu_to_be32(1),
2933         .refcount_order             = cpu_to_be32(refcount_order),
2934         .header_length              = cpu_to_be32(sizeof(*header)),
2935     };
2936 
2937     /* We'll update this to correct value later */
2938     header->crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
2939 
2940     if (qcow2_opts->lazy_refcounts) {
2941         header->compatible_features |=
2942             cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS);
2943     }
2944 
2945     ret = blk_pwrite(blk, 0, header, cluster_size, 0);
2946     g_free(header);
2947     if (ret < 0) {
2948         error_setg_errno(errp, -ret, "Could not write qcow2 header");
2949         goto out;
2950     }
2951 
2952     /* Write a refcount table with one refcount block */
2953     refcount_table = g_malloc0(2 * cluster_size);
2954     refcount_table[0] = cpu_to_be64(2 * cluster_size);
2955     ret = blk_pwrite(blk, cluster_size, refcount_table, 2 * cluster_size, 0);
2956     g_free(refcount_table);
2957 
2958     if (ret < 0) {
2959         error_setg_errno(errp, -ret, "Could not write refcount table");
2960         goto out;
2961     }
2962 
2963     blk_unref(blk);
2964     blk = NULL;
2965 
2966     /*
2967      * And now open the image and make it consistent first (i.e. increase the
2968      * refcount of the cluster that is occupied by the header and the refcount
2969      * table)
2970      */
2971     options = qdict_new();
2972     qdict_put_str(options, "driver", "qcow2");
2973     qdict_put_str(options, "file", bs->node_name);
2974     blk = blk_new_open(NULL, NULL, options,
2975                        BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_NO_FLUSH,
2976                        &local_err);
2977     if (blk == NULL) {
2978         error_propagate(errp, local_err);
2979         ret = -EIO;
2980         goto out;
2981     }
2982 
2983     ret = qcow2_alloc_clusters(blk_bs(blk), 3 * cluster_size);
2984     if (ret < 0) {
2985         error_setg_errno(errp, -ret, "Could not allocate clusters for qcow2 "
2986                          "header and refcount table");
2987         goto out;
2988 
2989     } else if (ret != 0) {
2990         error_report("Huh, first cluster in empty image is already in use?");
2991         abort();
2992     }
2993 
2994     /* Create a full header (including things like feature table) */
2995     ret = qcow2_update_header(blk_bs(blk));
2996     if (ret < 0) {
2997         error_setg_errno(errp, -ret, "Could not update qcow2 header");
2998         goto out;
2999     }
3000 
3001     /* Okay, now that we have a valid image, let's give it the right size */
3002     ret = blk_truncate(blk, qcow2_opts->size, PREALLOC_MODE_OFF, errp);
3003     if (ret < 0) {
3004         error_prepend(errp, "Could not resize image: ");
3005         goto out;
3006     }
3007 
3008     /* Want a backing file? There you go.*/
3009     if (qcow2_opts->has_backing_file) {
3010         const char *backing_format = NULL;
3011 
3012         if (qcow2_opts->has_backing_fmt) {
3013             backing_format = BlockdevDriver_str(qcow2_opts->backing_fmt);
3014         }
3015 
3016         ret = bdrv_change_backing_file(blk_bs(blk), qcow2_opts->backing_file,
3017                                        backing_format);
3018         if (ret < 0) {
3019             error_setg_errno(errp, -ret, "Could not assign backing file '%s' "
3020                              "with format '%s'", qcow2_opts->backing_file,
3021                              backing_format);
3022             goto out;
3023         }
3024     }
3025 
3026     /* Want encryption? There you go. */
3027     if (qcow2_opts->has_encrypt) {
3028         ret = qcow2_set_up_encryption(blk_bs(blk), qcow2_opts->encrypt, errp);
3029         if (ret < 0) {
3030             goto out;
3031         }
3032     }
3033 
3034     /* And if we're supposed to preallocate metadata, do that now */
3035     if (qcow2_opts->preallocation != PREALLOC_MODE_OFF) {
3036         ret = preallocate(blk_bs(blk), 0, qcow2_opts->size);
3037         if (ret < 0) {
3038             error_setg_errno(errp, -ret, "Could not preallocate metadata");
3039             goto out;
3040         }
3041     }
3042 
3043     blk_unref(blk);
3044     blk = NULL;
3045 
3046     /* Reopen the image without BDRV_O_NO_FLUSH to flush it before returning.
3047      * Using BDRV_O_NO_IO, since encryption is now setup we don't want to
3048      * have to setup decryption context. We're not doing any I/O on the top
3049      * level BlockDriverState, only lower layers, where BDRV_O_NO_IO does
3050      * not have effect.
3051      */
3052     options = qdict_new();
3053     qdict_put_str(options, "driver", "qcow2");
3054     qdict_put_str(options, "file", bs->node_name);
3055     blk = blk_new_open(NULL, NULL, options,
3056                        BDRV_O_RDWR | BDRV_O_NO_BACKING | BDRV_O_NO_IO,
3057                        &local_err);
3058     if (blk == NULL) {
3059         error_propagate(errp, local_err);
3060         ret = -EIO;
3061         goto out;
3062     }
3063 
3064     ret = 0;
3065 out:
3066     blk_unref(blk);
3067     bdrv_unref(bs);
3068     return ret;
3069 }
3070 
3071 static int coroutine_fn qcow2_co_create_opts(const char *filename, QemuOpts *opts,
3072                                              Error **errp)
3073 {
3074     BlockdevCreateOptions *create_options = NULL;
3075     QDict *qdict = NULL;
3076     QObject *qobj;
3077     Visitor *v;
3078     BlockDriverState *bs = NULL;
3079     Error *local_err = NULL;
3080     const char *val;
3081     int ret;
3082 
3083     /* Only the keyval visitor supports the dotted syntax needed for
3084      * encryption, so go through a QDict before getting a QAPI type. Ignore
3085      * options meant for the protocol layer so that the visitor doesn't
3086      * complain. */
3087     qdict = qemu_opts_to_qdict_filtered(opts, NULL, bdrv_qcow2.create_opts,
3088                                         true);
3089 
3090     /* Handle encryption options */
3091     val = qdict_get_try_str(qdict, BLOCK_OPT_ENCRYPT);
3092     if (val && !strcmp(val, "on")) {
3093         qdict_put_str(qdict, BLOCK_OPT_ENCRYPT, "qcow");
3094     } else if (val && !strcmp(val, "off")) {
3095         qdict_del(qdict, BLOCK_OPT_ENCRYPT);
3096     }
3097 
3098     val = qdict_get_try_str(qdict, BLOCK_OPT_ENCRYPT_FORMAT);
3099     if (val && !strcmp(val, "aes")) {
3100         qdict_put_str(qdict, BLOCK_OPT_ENCRYPT_FORMAT, "qcow");
3101     }
3102 
3103     /* Convert compat=0.10/1.1 into compat=v2/v3, to be renamed into
3104      * version=v2/v3 below. */
3105     val = qdict_get_try_str(qdict, BLOCK_OPT_COMPAT_LEVEL);
3106     if (val && !strcmp(val, "0.10")) {
3107         qdict_put_str(qdict, BLOCK_OPT_COMPAT_LEVEL, "v2");
3108     } else if (val && !strcmp(val, "1.1")) {
3109         qdict_put_str(qdict, BLOCK_OPT_COMPAT_LEVEL, "v3");
3110     }
3111 
3112     /* Change legacy command line options into QMP ones */
3113     static const QDictRenames opt_renames[] = {
3114         { BLOCK_OPT_BACKING_FILE,       "backing-file" },
3115         { BLOCK_OPT_BACKING_FMT,        "backing-fmt" },
3116         { BLOCK_OPT_CLUSTER_SIZE,       "cluster-size" },
3117         { BLOCK_OPT_LAZY_REFCOUNTS,     "lazy-refcounts" },
3118         { BLOCK_OPT_REFCOUNT_BITS,      "refcount-bits" },
3119         { BLOCK_OPT_ENCRYPT,            BLOCK_OPT_ENCRYPT_FORMAT },
3120         { BLOCK_OPT_COMPAT_LEVEL,       "version" },
3121         { NULL, NULL },
3122     };
3123 
3124     if (!qdict_rename_keys(qdict, opt_renames, errp)) {
3125         ret = -EINVAL;
3126         goto finish;
3127     }
3128 
3129     /* Create and open the file (protocol layer) */
3130     ret = bdrv_create_file(filename, opts, errp);
3131     if (ret < 0) {
3132         goto finish;
3133     }
3134 
3135     bs = bdrv_open(filename, NULL, NULL,
3136                    BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_PROTOCOL, errp);
3137     if (bs == NULL) {
3138         ret = -EIO;
3139         goto finish;
3140     }
3141 
3142     /* Set 'driver' and 'node' options */
3143     qdict_put_str(qdict, "driver", "qcow2");
3144     qdict_put_str(qdict, "file", bs->node_name);
3145 
3146     /* Now get the QAPI type BlockdevCreateOptions */
3147     qobj = qdict_crumple(qdict, errp);
3148     qobject_unref(qdict);
3149     qdict = qobject_to(QDict, qobj);
3150     if (qdict == NULL) {
3151         ret = -EINVAL;
3152         goto finish;
3153     }
3154 
3155     v = qobject_input_visitor_new_keyval(QOBJECT(qdict));
3156     visit_type_BlockdevCreateOptions(v, NULL, &create_options, &local_err);
3157     visit_free(v);
3158 
3159     if (local_err) {
3160         error_propagate(errp, local_err);
3161         ret = -EINVAL;
3162         goto finish;
3163     }
3164 
3165     /* Silently round up size */
3166     create_options->u.qcow2.size = ROUND_UP(create_options->u.qcow2.size,
3167                                             BDRV_SECTOR_SIZE);
3168 
3169     /* Create the qcow2 image (format layer) */
3170     ret = qcow2_co_create(create_options, errp);
3171     if (ret < 0) {
3172         goto finish;
3173     }
3174 
3175     ret = 0;
3176 finish:
3177     qobject_unref(qdict);
3178     bdrv_unref(bs);
3179     qapi_free_BlockdevCreateOptions(create_options);
3180     return ret;
3181 }
3182 
3183 
3184 static bool is_zero(BlockDriverState *bs, int64_t offset, int64_t bytes)
3185 {
3186     int64_t nr;
3187     int res;
3188 
3189     /* Clamp to image length, before checking status of underlying sectors */
3190     if (offset + bytes > bs->total_sectors * BDRV_SECTOR_SIZE) {
3191         bytes = bs->total_sectors * BDRV_SECTOR_SIZE - offset;
3192     }
3193 
3194     if (!bytes) {
3195         return true;
3196     }
3197     res = bdrv_block_status_above(bs, NULL, offset, bytes, &nr, NULL, NULL);
3198     return res >= 0 && (res & BDRV_BLOCK_ZERO) && nr == bytes;
3199 }
3200 
3201 static coroutine_fn int qcow2_co_pwrite_zeroes(BlockDriverState *bs,
3202     int64_t offset, int bytes, BdrvRequestFlags flags)
3203 {
3204     int ret;
3205     BDRVQcow2State *s = bs->opaque;
3206 
3207     uint32_t head = offset % s->cluster_size;
3208     uint32_t tail = (offset + bytes) % s->cluster_size;
3209 
3210     trace_qcow2_pwrite_zeroes_start_req(qemu_coroutine_self(), offset, bytes);
3211     if (offset + bytes == bs->total_sectors * BDRV_SECTOR_SIZE) {
3212         tail = 0;
3213     }
3214 
3215     if (head || tail) {
3216         uint64_t off;
3217         unsigned int nr;
3218 
3219         assert(head + bytes <= s->cluster_size);
3220 
3221         /* check whether remainder of cluster already reads as zero */
3222         if (!(is_zero(bs, offset - head, head) &&
3223               is_zero(bs, offset + bytes,
3224                       tail ? s->cluster_size - tail : 0))) {
3225             return -ENOTSUP;
3226         }
3227 
3228         qemu_co_mutex_lock(&s->lock);
3229         /* We can have new write after previous check */
3230         offset = QEMU_ALIGN_DOWN(offset, s->cluster_size);
3231         bytes = s->cluster_size;
3232         nr = s->cluster_size;
3233         ret = qcow2_get_cluster_offset(bs, offset, &nr, &off);
3234         if (ret != QCOW2_CLUSTER_UNALLOCATED &&
3235             ret != QCOW2_CLUSTER_ZERO_PLAIN &&
3236             ret != QCOW2_CLUSTER_ZERO_ALLOC) {
3237             qemu_co_mutex_unlock(&s->lock);
3238             return -ENOTSUP;
3239         }
3240     } else {
3241         qemu_co_mutex_lock(&s->lock);
3242     }
3243 
3244     trace_qcow2_pwrite_zeroes(qemu_coroutine_self(), offset, bytes);
3245 
3246     /* Whatever is left can use real zero clusters */
3247     ret = qcow2_cluster_zeroize(bs, offset, bytes, flags);
3248     qemu_co_mutex_unlock(&s->lock);
3249 
3250     return ret;
3251 }
3252 
3253 static coroutine_fn int qcow2_co_pdiscard(BlockDriverState *bs,
3254                                           int64_t offset, int bytes)
3255 {
3256     int ret;
3257     BDRVQcow2State *s = bs->opaque;
3258 
3259     if (!QEMU_IS_ALIGNED(offset | bytes, s->cluster_size)) {
3260         assert(bytes < s->cluster_size);
3261         /* Ignore partial clusters, except for the special case of the
3262          * complete partial cluster at the end of an unaligned file */
3263         if (!QEMU_IS_ALIGNED(offset, s->cluster_size) ||
3264             offset + bytes != bs->total_sectors * BDRV_SECTOR_SIZE) {
3265             return -ENOTSUP;
3266         }
3267     }
3268 
3269     qemu_co_mutex_lock(&s->lock);
3270     ret = qcow2_cluster_discard(bs, offset, bytes, QCOW2_DISCARD_REQUEST,
3271                                 false);
3272     qemu_co_mutex_unlock(&s->lock);
3273     return ret;
3274 }
3275 
3276 static int qcow2_truncate(BlockDriverState *bs, int64_t offset,
3277                           PreallocMode prealloc, Error **errp)
3278 {
3279     BDRVQcow2State *s = bs->opaque;
3280     uint64_t old_length;
3281     int64_t new_l1_size;
3282     int ret;
3283 
3284     if (prealloc != PREALLOC_MODE_OFF && prealloc != PREALLOC_MODE_METADATA &&
3285         prealloc != PREALLOC_MODE_FALLOC && prealloc != PREALLOC_MODE_FULL)
3286     {
3287         error_setg(errp, "Unsupported preallocation mode '%s'",
3288                    PreallocMode_str(prealloc));
3289         return -ENOTSUP;
3290     }
3291 
3292     if (offset & 511) {
3293         error_setg(errp, "The new size must be a multiple of 512");
3294         return -EINVAL;
3295     }
3296 
3297     /* cannot proceed if image has snapshots */
3298     if (s->nb_snapshots) {
3299         error_setg(errp, "Can't resize an image which has snapshots");
3300         return -ENOTSUP;
3301     }
3302 
3303     /* cannot proceed if image has bitmaps */
3304     if (s->nb_bitmaps) {
3305         /* TODO: resize bitmaps in the image */
3306         error_setg(errp, "Can't resize an image which has bitmaps");
3307         return -ENOTSUP;
3308     }
3309 
3310     old_length = bs->total_sectors * 512;
3311     new_l1_size = size_to_l1(s, offset);
3312 
3313     if (offset < old_length) {
3314         int64_t last_cluster, old_file_size;
3315         if (prealloc != PREALLOC_MODE_OFF) {
3316             error_setg(errp,
3317                        "Preallocation can't be used for shrinking an image");
3318             return -EINVAL;
3319         }
3320 
3321         ret = qcow2_cluster_discard(bs, ROUND_UP(offset, s->cluster_size),
3322                                     old_length - ROUND_UP(offset,
3323                                                           s->cluster_size),
3324                                     QCOW2_DISCARD_ALWAYS, true);
3325         if (ret < 0) {
3326             error_setg_errno(errp, -ret, "Failed to discard cropped clusters");
3327             return ret;
3328         }
3329 
3330         ret = qcow2_shrink_l1_table(bs, new_l1_size);
3331         if (ret < 0) {
3332             error_setg_errno(errp, -ret,
3333                              "Failed to reduce the number of L2 tables");
3334             return ret;
3335         }
3336 
3337         ret = qcow2_shrink_reftable(bs);
3338         if (ret < 0) {
3339             error_setg_errno(errp, -ret,
3340                              "Failed to discard unused refblocks");
3341             return ret;
3342         }
3343 
3344         old_file_size = bdrv_getlength(bs->file->bs);
3345         if (old_file_size < 0) {
3346             error_setg_errno(errp, -old_file_size,
3347                              "Failed to inquire current file length");
3348             return old_file_size;
3349         }
3350         last_cluster = qcow2_get_last_cluster(bs, old_file_size);
3351         if (last_cluster < 0) {
3352             error_setg_errno(errp, -last_cluster,
3353                              "Failed to find the last cluster");
3354             return last_cluster;
3355         }
3356         if ((last_cluster + 1) * s->cluster_size < old_file_size) {
3357             Error *local_err = NULL;
3358 
3359             bdrv_truncate(bs->file, (last_cluster + 1) * s->cluster_size,
3360                           PREALLOC_MODE_OFF, &local_err);
3361             if (local_err) {
3362                 warn_reportf_err(local_err,
3363                                  "Failed to truncate the tail of the image: ");
3364             }
3365         }
3366     } else {
3367         ret = qcow2_grow_l1_table(bs, new_l1_size, true);
3368         if (ret < 0) {
3369             error_setg_errno(errp, -ret, "Failed to grow the L1 table");
3370             return ret;
3371         }
3372     }
3373 
3374     switch (prealloc) {
3375     case PREALLOC_MODE_OFF:
3376         break;
3377 
3378     case PREALLOC_MODE_METADATA:
3379         ret = preallocate(bs, old_length, offset);
3380         if (ret < 0) {
3381             error_setg_errno(errp, -ret, "Preallocation failed");
3382             return ret;
3383         }
3384         break;
3385 
3386     case PREALLOC_MODE_FALLOC:
3387     case PREALLOC_MODE_FULL:
3388     {
3389         int64_t allocation_start, host_offset, guest_offset;
3390         int64_t clusters_allocated;
3391         int64_t old_file_size, new_file_size;
3392         uint64_t nb_new_data_clusters, nb_new_l2_tables;
3393 
3394         old_file_size = bdrv_getlength(bs->file->bs);
3395         if (old_file_size < 0) {
3396             error_setg_errno(errp, -old_file_size,
3397                              "Failed to inquire current file length");
3398             return old_file_size;
3399         }
3400         old_file_size = ROUND_UP(old_file_size, s->cluster_size);
3401 
3402         nb_new_data_clusters = DIV_ROUND_UP(offset - old_length,
3403                                             s->cluster_size);
3404 
3405         /* This is an overestimation; we will not actually allocate space for
3406          * these in the file but just make sure the new refcount structures are
3407          * able to cover them so we will not have to allocate new refblocks
3408          * while entering the data blocks in the potentially new L2 tables.
3409          * (We do not actually care where the L2 tables are placed. Maybe they
3410          *  are already allocated or they can be placed somewhere before
3411          *  @old_file_size. It does not matter because they will be fully
3412          *  allocated automatically, so they do not need to be covered by the
3413          *  preallocation. All that matters is that we will not have to allocate
3414          *  new refcount structures for them.) */
3415         nb_new_l2_tables = DIV_ROUND_UP(nb_new_data_clusters,
3416                                         s->cluster_size / sizeof(uint64_t));
3417         /* The cluster range may not be aligned to L2 boundaries, so add one L2
3418          * table for a potential head/tail */
3419         nb_new_l2_tables++;
3420 
3421         allocation_start = qcow2_refcount_area(bs, old_file_size,
3422                                                nb_new_data_clusters +
3423                                                nb_new_l2_tables,
3424                                                true, 0, 0);
3425         if (allocation_start < 0) {
3426             error_setg_errno(errp, -allocation_start,
3427                              "Failed to resize refcount structures");
3428             return allocation_start;
3429         }
3430 
3431         clusters_allocated = qcow2_alloc_clusters_at(bs, allocation_start,
3432                                                      nb_new_data_clusters);
3433         if (clusters_allocated < 0) {
3434             error_setg_errno(errp, -clusters_allocated,
3435                              "Failed to allocate data clusters");
3436             return -clusters_allocated;
3437         }
3438 
3439         assert(clusters_allocated == nb_new_data_clusters);
3440 
3441         /* Allocate the data area */
3442         new_file_size = allocation_start +
3443                         nb_new_data_clusters * s->cluster_size;
3444         ret = bdrv_truncate(bs->file, new_file_size, prealloc, errp);
3445         if (ret < 0) {
3446             error_prepend(errp, "Failed to resize underlying file: ");
3447             qcow2_free_clusters(bs, allocation_start,
3448                                 nb_new_data_clusters * s->cluster_size,
3449                                 QCOW2_DISCARD_OTHER);
3450             return ret;
3451         }
3452 
3453         /* Create the necessary L2 entries */
3454         host_offset = allocation_start;
3455         guest_offset = old_length;
3456         while (nb_new_data_clusters) {
3457             int64_t nb_clusters = MIN(
3458                 nb_new_data_clusters,
3459                 s->l2_slice_size - offset_to_l2_slice_index(s, guest_offset));
3460             QCowL2Meta allocation = {
3461                 .offset       = guest_offset,
3462                 .alloc_offset = host_offset,
3463                 .nb_clusters  = nb_clusters,
3464             };
3465             qemu_co_queue_init(&allocation.dependent_requests);
3466 
3467             ret = qcow2_alloc_cluster_link_l2(bs, &allocation);
3468             if (ret < 0) {
3469                 error_setg_errno(errp, -ret, "Failed to update L2 tables");
3470                 qcow2_free_clusters(bs, host_offset,
3471                                     nb_new_data_clusters * s->cluster_size,
3472                                     QCOW2_DISCARD_OTHER);
3473                 return ret;
3474             }
3475 
3476             guest_offset += nb_clusters * s->cluster_size;
3477             host_offset += nb_clusters * s->cluster_size;
3478             nb_new_data_clusters -= nb_clusters;
3479         }
3480         break;
3481     }
3482 
3483     default:
3484         g_assert_not_reached();
3485     }
3486 
3487     if (prealloc != PREALLOC_MODE_OFF) {
3488         /* Flush metadata before actually changing the image size */
3489         ret = bdrv_flush(bs);
3490         if (ret < 0) {
3491             error_setg_errno(errp, -ret,
3492                              "Failed to flush the preallocated area to disk");
3493             return ret;
3494         }
3495     }
3496 
3497     /* write updated header.size */
3498     offset = cpu_to_be64(offset);
3499     ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, size),
3500                            &offset, sizeof(uint64_t));
3501     if (ret < 0) {
3502         error_setg_errno(errp, -ret, "Failed to update the image size");
3503         return ret;
3504     }
3505 
3506     s->l1_vm_state_index = new_l1_size;
3507     return 0;
3508 }
3509 
3510 /* XXX: put compressed sectors first, then all the cluster aligned
3511    tables to avoid losing bytes in alignment */
3512 static coroutine_fn int
3513 qcow2_co_pwritev_compressed(BlockDriverState *bs, uint64_t offset,
3514                             uint64_t bytes, QEMUIOVector *qiov)
3515 {
3516     BDRVQcow2State *s = bs->opaque;
3517     QEMUIOVector hd_qiov;
3518     struct iovec iov;
3519     z_stream strm;
3520     int ret, out_len;
3521     uint8_t *buf, *out_buf;
3522     int64_t cluster_offset;
3523 
3524     if (bytes == 0) {
3525         /* align end of file to a sector boundary to ease reading with
3526            sector based I/Os */
3527         cluster_offset = bdrv_getlength(bs->file->bs);
3528         if (cluster_offset < 0) {
3529             return cluster_offset;
3530         }
3531         return bdrv_truncate(bs->file, cluster_offset, PREALLOC_MODE_OFF, NULL);
3532     }
3533 
3534     if (offset_into_cluster(s, offset)) {
3535         return -EINVAL;
3536     }
3537 
3538     buf = qemu_blockalign(bs, s->cluster_size);
3539     if (bytes != s->cluster_size) {
3540         if (bytes > s->cluster_size ||
3541             offset + bytes != bs->total_sectors << BDRV_SECTOR_BITS)
3542         {
3543             qemu_vfree(buf);
3544             return -EINVAL;
3545         }
3546         /* Zero-pad last write if image size is not cluster aligned */
3547         memset(buf + bytes, 0, s->cluster_size - bytes);
3548     }
3549     qemu_iovec_to_buf(qiov, 0, buf, bytes);
3550 
3551     out_buf = g_malloc(s->cluster_size);
3552 
3553     /* best compression, small window, no zlib header */
3554     memset(&strm, 0, sizeof(strm));
3555     ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
3556                        Z_DEFLATED, -12,
3557                        9, Z_DEFAULT_STRATEGY);
3558     if (ret != 0) {
3559         ret = -EINVAL;
3560         goto fail;
3561     }
3562 
3563     strm.avail_in = s->cluster_size;
3564     strm.next_in = (uint8_t *)buf;
3565     strm.avail_out = s->cluster_size;
3566     strm.next_out = out_buf;
3567 
3568     ret = deflate(&strm, Z_FINISH);
3569     if (ret != Z_STREAM_END && ret != Z_OK) {
3570         deflateEnd(&strm);
3571         ret = -EINVAL;
3572         goto fail;
3573     }
3574     out_len = strm.next_out - out_buf;
3575 
3576     deflateEnd(&strm);
3577 
3578     if (ret != Z_STREAM_END || out_len >= s->cluster_size) {
3579         /* could not compress: write normal cluster */
3580         ret = qcow2_co_pwritev(bs, offset, bytes, qiov, 0);
3581         if (ret < 0) {
3582             goto fail;
3583         }
3584         goto success;
3585     }
3586 
3587     qemu_co_mutex_lock(&s->lock);
3588     cluster_offset =
3589         qcow2_alloc_compressed_cluster_offset(bs, offset, out_len);
3590     if (!cluster_offset) {
3591         qemu_co_mutex_unlock(&s->lock);
3592         ret = -EIO;
3593         goto fail;
3594     }
3595     cluster_offset &= s->cluster_offset_mask;
3596 
3597     ret = qcow2_pre_write_overlap_check(bs, 0, cluster_offset, out_len);
3598     qemu_co_mutex_unlock(&s->lock);
3599     if (ret < 0) {
3600         goto fail;
3601     }
3602 
3603     iov = (struct iovec) {
3604         .iov_base   = out_buf,
3605         .iov_len    = out_len,
3606     };
3607     qemu_iovec_init_external(&hd_qiov, &iov, 1);
3608 
3609     BLKDBG_EVENT(bs->file, BLKDBG_WRITE_COMPRESSED);
3610     ret = bdrv_co_pwritev(bs->file, cluster_offset, out_len, &hd_qiov, 0);
3611     if (ret < 0) {
3612         goto fail;
3613     }
3614 success:
3615     ret = 0;
3616 fail:
3617     qemu_vfree(buf);
3618     g_free(out_buf);
3619     return ret;
3620 }
3621 
3622 static int make_completely_empty(BlockDriverState *bs)
3623 {
3624     BDRVQcow2State *s = bs->opaque;
3625     Error *local_err = NULL;
3626     int ret, l1_clusters;
3627     int64_t offset;
3628     uint64_t *new_reftable = NULL;
3629     uint64_t rt_entry, l1_size2;
3630     struct {
3631         uint64_t l1_offset;
3632         uint64_t reftable_offset;
3633         uint32_t reftable_clusters;
3634     } QEMU_PACKED l1_ofs_rt_ofs_cls;
3635 
3636     ret = qcow2_cache_empty(bs, s->l2_table_cache);
3637     if (ret < 0) {
3638         goto fail;
3639     }
3640 
3641     ret = qcow2_cache_empty(bs, s->refcount_block_cache);
3642     if (ret < 0) {
3643         goto fail;
3644     }
3645 
3646     /* Refcounts will be broken utterly */
3647     ret = qcow2_mark_dirty(bs);
3648     if (ret < 0) {
3649         goto fail;
3650     }
3651 
3652     BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
3653 
3654     l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / sizeof(uint64_t));
3655     l1_size2 = (uint64_t)s->l1_size * sizeof(uint64_t);
3656 
3657     /* After this call, neither the in-memory nor the on-disk refcount
3658      * information accurately describe the actual references */
3659 
3660     ret = bdrv_pwrite_zeroes(bs->file, s->l1_table_offset,
3661                              l1_clusters * s->cluster_size, 0);
3662     if (ret < 0) {
3663         goto fail_broken_refcounts;
3664     }
3665     memset(s->l1_table, 0, l1_size2);
3666 
3667     BLKDBG_EVENT(bs->file, BLKDBG_EMPTY_IMAGE_PREPARE);
3668 
3669     /* Overwrite enough clusters at the beginning of the sectors to place
3670      * the refcount table, a refcount block and the L1 table in; this may
3671      * overwrite parts of the existing refcount and L1 table, which is not
3672      * an issue because the dirty flag is set, complete data loss is in fact
3673      * desired and partial data loss is consequently fine as well */
3674     ret = bdrv_pwrite_zeroes(bs->file, s->cluster_size,
3675                              (2 + l1_clusters) * s->cluster_size, 0);
3676     /* This call (even if it failed overall) may have overwritten on-disk
3677      * refcount structures; in that case, the in-memory refcount information
3678      * will probably differ from the on-disk information which makes the BDS
3679      * unusable */
3680     if (ret < 0) {
3681         goto fail_broken_refcounts;
3682     }
3683 
3684     BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
3685     BLKDBG_EVENT(bs->file, BLKDBG_REFTABLE_UPDATE);
3686 
3687     /* "Create" an empty reftable (one cluster) directly after the image
3688      * header and an empty L1 table three clusters after the image header;
3689      * the cluster between those two will be used as the first refblock */
3690     l1_ofs_rt_ofs_cls.l1_offset = cpu_to_be64(3 * s->cluster_size);
3691     l1_ofs_rt_ofs_cls.reftable_offset = cpu_to_be64(s->cluster_size);
3692     l1_ofs_rt_ofs_cls.reftable_clusters = cpu_to_be32(1);
3693     ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, l1_table_offset),
3694                            &l1_ofs_rt_ofs_cls, sizeof(l1_ofs_rt_ofs_cls));
3695     if (ret < 0) {
3696         goto fail_broken_refcounts;
3697     }
3698 
3699     s->l1_table_offset = 3 * s->cluster_size;
3700 
3701     new_reftable = g_try_new0(uint64_t, s->cluster_size / sizeof(uint64_t));
3702     if (!new_reftable) {
3703         ret = -ENOMEM;
3704         goto fail_broken_refcounts;
3705     }
3706 
3707     s->refcount_table_offset = s->cluster_size;
3708     s->refcount_table_size   = s->cluster_size / sizeof(uint64_t);
3709     s->max_refcount_table_index = 0;
3710 
3711     g_free(s->refcount_table);
3712     s->refcount_table = new_reftable;
3713     new_reftable = NULL;
3714 
3715     /* Now the in-memory refcount information again corresponds to the on-disk
3716      * information (reftable is empty and no refblocks (the refblock cache is
3717      * empty)); however, this means some clusters (e.g. the image header) are
3718      * referenced, but not refcounted, but the normal qcow2 code assumes that
3719      * the in-memory information is always correct */
3720 
3721     BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_ALLOC);
3722 
3723     /* Enter the first refblock into the reftable */
3724     rt_entry = cpu_to_be64(2 * s->cluster_size);
3725     ret = bdrv_pwrite_sync(bs->file, s->cluster_size,
3726                            &rt_entry, sizeof(rt_entry));
3727     if (ret < 0) {
3728         goto fail_broken_refcounts;
3729     }
3730     s->refcount_table[0] = 2 * s->cluster_size;
3731 
3732     s->free_cluster_index = 0;
3733     assert(3 + l1_clusters <= s->refcount_block_size);
3734     offset = qcow2_alloc_clusters(bs, 3 * s->cluster_size + l1_size2);
3735     if (offset < 0) {
3736         ret = offset;
3737         goto fail_broken_refcounts;
3738     } else if (offset > 0) {
3739         error_report("First cluster in emptied image is in use");
3740         abort();
3741     }
3742 
3743     /* Now finally the in-memory information corresponds to the on-disk
3744      * structures and is correct */
3745     ret = qcow2_mark_clean(bs);
3746     if (ret < 0) {
3747         goto fail;
3748     }
3749 
3750     ret = bdrv_truncate(bs->file, (3 + l1_clusters) * s->cluster_size,
3751                         PREALLOC_MODE_OFF, &local_err);
3752     if (ret < 0) {
3753         error_report_err(local_err);
3754         goto fail;
3755     }
3756 
3757     return 0;
3758 
3759 fail_broken_refcounts:
3760     /* The BDS is unusable at this point. If we wanted to make it usable, we
3761      * would have to call qcow2_refcount_close(), qcow2_refcount_init(),
3762      * qcow2_check_refcounts(), qcow2_refcount_close() and qcow2_refcount_init()
3763      * again. However, because the functions which could have caused this error
3764      * path to be taken are used by those functions as well, it's very likely
3765      * that that sequence will fail as well. Therefore, just eject the BDS. */
3766     bs->drv = NULL;
3767 
3768 fail:
3769     g_free(new_reftable);
3770     return ret;
3771 }
3772 
3773 static int qcow2_make_empty(BlockDriverState *bs)
3774 {
3775     BDRVQcow2State *s = bs->opaque;
3776     uint64_t offset, end_offset;
3777     int step = QEMU_ALIGN_DOWN(INT_MAX, s->cluster_size);
3778     int l1_clusters, ret = 0;
3779 
3780     l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / sizeof(uint64_t));
3781 
3782     if (s->qcow_version >= 3 && !s->snapshots && !s->nb_bitmaps &&
3783         3 + l1_clusters <= s->refcount_block_size &&
3784         s->crypt_method_header != QCOW_CRYPT_LUKS) {
3785         /* The following function only works for qcow2 v3 images (it
3786          * requires the dirty flag) and only as long as there are no
3787          * features that reserve extra clusters (such as snapshots,
3788          * LUKS header, or persistent bitmaps), because it completely
3789          * empties the image.  Furthermore, the L1 table and three
3790          * additional clusters (image header, refcount table, one
3791          * refcount block) have to fit inside one refcount block. */
3792         return make_completely_empty(bs);
3793     }
3794 
3795     /* This fallback code simply discards every active cluster; this is slow,
3796      * but works in all cases */
3797     end_offset = bs->total_sectors * BDRV_SECTOR_SIZE;
3798     for (offset = 0; offset < end_offset; offset += step) {
3799         /* As this function is generally used after committing an external
3800          * snapshot, QCOW2_DISCARD_SNAPSHOT seems appropriate. Also, the
3801          * default action for this kind of discard is to pass the discard,
3802          * which will ideally result in an actually smaller image file, as
3803          * is probably desired. */
3804         ret = qcow2_cluster_discard(bs, offset, MIN(step, end_offset - offset),
3805                                     QCOW2_DISCARD_SNAPSHOT, true);
3806         if (ret < 0) {
3807             break;
3808         }
3809     }
3810 
3811     return ret;
3812 }
3813 
3814 static coroutine_fn int qcow2_co_flush_to_os(BlockDriverState *bs)
3815 {
3816     BDRVQcow2State *s = bs->opaque;
3817     int ret;
3818 
3819     qemu_co_mutex_lock(&s->lock);
3820     ret = qcow2_write_caches(bs);
3821     qemu_co_mutex_unlock(&s->lock);
3822 
3823     return ret;
3824 }
3825 
3826 static BlockMeasureInfo *qcow2_measure(QemuOpts *opts, BlockDriverState *in_bs,
3827                                        Error **errp)
3828 {
3829     Error *local_err = NULL;
3830     BlockMeasureInfo *info;
3831     uint64_t required = 0; /* bytes that contribute to required size */
3832     uint64_t virtual_size; /* disk size as seen by guest */
3833     uint64_t refcount_bits;
3834     uint64_t l2_tables;
3835     size_t cluster_size;
3836     int version;
3837     char *optstr;
3838     PreallocMode prealloc;
3839     bool has_backing_file;
3840 
3841     /* Parse image creation options */
3842     cluster_size = qcow2_opt_get_cluster_size_del(opts, &local_err);
3843     if (local_err) {
3844         goto err;
3845     }
3846 
3847     version = qcow2_opt_get_version_del(opts, &local_err);
3848     if (local_err) {
3849         goto err;
3850     }
3851 
3852     refcount_bits = qcow2_opt_get_refcount_bits_del(opts, version, &local_err);
3853     if (local_err) {
3854         goto err;
3855     }
3856 
3857     optstr = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
3858     prealloc = qapi_enum_parse(&PreallocMode_lookup, optstr,
3859                                PREALLOC_MODE_OFF, &local_err);
3860     g_free(optstr);
3861     if (local_err) {
3862         goto err;
3863     }
3864 
3865     optstr = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
3866     has_backing_file = !!optstr;
3867     g_free(optstr);
3868 
3869     virtual_size = qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0);
3870     virtual_size = ROUND_UP(virtual_size, cluster_size);
3871 
3872     /* Check that virtual disk size is valid */
3873     l2_tables = DIV_ROUND_UP(virtual_size / cluster_size,
3874                              cluster_size / sizeof(uint64_t));
3875     if (l2_tables * sizeof(uint64_t) > QCOW_MAX_L1_SIZE) {
3876         error_setg(&local_err, "The image size is too large "
3877                                "(try using a larger cluster size)");
3878         goto err;
3879     }
3880 
3881     /* Account for input image */
3882     if (in_bs) {
3883         int64_t ssize = bdrv_getlength(in_bs);
3884         if (ssize < 0) {
3885             error_setg_errno(&local_err, -ssize,
3886                              "Unable to get image virtual_size");
3887             goto err;
3888         }
3889 
3890         virtual_size = ROUND_UP(ssize, cluster_size);
3891 
3892         if (has_backing_file) {
3893             /* We don't how much of the backing chain is shared by the input
3894              * image and the new image file.  In the worst case the new image's
3895              * backing file has nothing in common with the input image.  Be
3896              * conservative and assume all clusters need to be written.
3897              */
3898             required = virtual_size;
3899         } else {
3900             int64_t offset;
3901             int64_t pnum = 0;
3902 
3903             for (offset = 0; offset < ssize; offset += pnum) {
3904                 int ret;
3905 
3906                 ret = bdrv_block_status_above(in_bs, NULL, offset,
3907                                               ssize - offset, &pnum, NULL,
3908                                               NULL);
3909                 if (ret < 0) {
3910                     error_setg_errno(&local_err, -ret,
3911                                      "Unable to get block status");
3912                     goto err;
3913                 }
3914 
3915                 if (ret & BDRV_BLOCK_ZERO) {
3916                     /* Skip zero regions (safe with no backing file) */
3917                 } else if ((ret & (BDRV_BLOCK_DATA | BDRV_BLOCK_ALLOCATED)) ==
3918                            (BDRV_BLOCK_DATA | BDRV_BLOCK_ALLOCATED)) {
3919                     /* Extend pnum to end of cluster for next iteration */
3920                     pnum = ROUND_UP(offset + pnum, cluster_size) - offset;
3921 
3922                     /* Count clusters we've seen */
3923                     required += offset % cluster_size + pnum;
3924                 }
3925             }
3926         }
3927     }
3928 
3929     /* Take into account preallocation.  Nothing special is needed for
3930      * PREALLOC_MODE_METADATA since metadata is always counted.
3931      */
3932     if (prealloc == PREALLOC_MODE_FULL || prealloc == PREALLOC_MODE_FALLOC) {
3933         required = virtual_size;
3934     }
3935 
3936     info = g_new(BlockMeasureInfo, 1);
3937     info->fully_allocated =
3938         qcow2_calc_prealloc_size(virtual_size, cluster_size,
3939                                  ctz32(refcount_bits));
3940 
3941     /* Remove data clusters that are not required.  This overestimates the
3942      * required size because metadata needed for the fully allocated file is
3943      * still counted.
3944      */
3945     info->required = info->fully_allocated - virtual_size + required;
3946     return info;
3947 
3948 err:
3949     error_propagate(errp, local_err);
3950     return NULL;
3951 }
3952 
3953 static int qcow2_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
3954 {
3955     BDRVQcow2State *s = bs->opaque;
3956     bdi->unallocated_blocks_are_zero = true;
3957     bdi->cluster_size = s->cluster_size;
3958     bdi->vm_state_offset = qcow2_vm_state_offset(s);
3959     return 0;
3960 }
3961 
3962 static ImageInfoSpecific *qcow2_get_specific_info(BlockDriverState *bs)
3963 {
3964     BDRVQcow2State *s = bs->opaque;
3965     ImageInfoSpecific *spec_info;
3966     QCryptoBlockInfo *encrypt_info = NULL;
3967 
3968     if (s->crypto != NULL) {
3969         encrypt_info = qcrypto_block_get_info(s->crypto, &error_abort);
3970     }
3971 
3972     spec_info = g_new(ImageInfoSpecific, 1);
3973     *spec_info = (ImageInfoSpecific){
3974         .type  = IMAGE_INFO_SPECIFIC_KIND_QCOW2,
3975         .u.qcow2.data = g_new(ImageInfoSpecificQCow2, 1),
3976     };
3977     if (s->qcow_version == 2) {
3978         *spec_info->u.qcow2.data = (ImageInfoSpecificQCow2){
3979             .compat             = g_strdup("0.10"),
3980             .refcount_bits      = s->refcount_bits,
3981         };
3982     } else if (s->qcow_version == 3) {
3983         *spec_info->u.qcow2.data = (ImageInfoSpecificQCow2){
3984             .compat             = g_strdup("1.1"),
3985             .lazy_refcounts     = s->compatible_features &
3986                                   QCOW2_COMPAT_LAZY_REFCOUNTS,
3987             .has_lazy_refcounts = true,
3988             .corrupt            = s->incompatible_features &
3989                                   QCOW2_INCOMPAT_CORRUPT,
3990             .has_corrupt        = true,
3991             .refcount_bits      = s->refcount_bits,
3992         };
3993     } else {
3994         /* if this assertion fails, this probably means a new version was
3995          * added without having it covered here */
3996         assert(false);
3997     }
3998 
3999     if (encrypt_info) {
4000         ImageInfoSpecificQCow2Encryption *qencrypt =
4001             g_new(ImageInfoSpecificQCow2Encryption, 1);
4002         switch (encrypt_info->format) {
4003         case Q_CRYPTO_BLOCK_FORMAT_QCOW:
4004             qencrypt->format = BLOCKDEV_QCOW2_ENCRYPTION_FORMAT_AES;
4005             qencrypt->u.aes = encrypt_info->u.qcow;
4006             break;
4007         case Q_CRYPTO_BLOCK_FORMAT_LUKS:
4008             qencrypt->format = BLOCKDEV_QCOW2_ENCRYPTION_FORMAT_LUKS;
4009             qencrypt->u.luks = encrypt_info->u.luks;
4010             break;
4011         default:
4012             abort();
4013         }
4014         /* Since we did shallow copy above, erase any pointers
4015          * in the original info */
4016         memset(&encrypt_info->u, 0, sizeof(encrypt_info->u));
4017         qapi_free_QCryptoBlockInfo(encrypt_info);
4018 
4019         spec_info->u.qcow2.data->has_encrypt = true;
4020         spec_info->u.qcow2.data->encrypt = qencrypt;
4021     }
4022 
4023     return spec_info;
4024 }
4025 
4026 static int qcow2_save_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
4027                               int64_t pos)
4028 {
4029     BDRVQcow2State *s = bs->opaque;
4030 
4031     BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_SAVE);
4032     return bs->drv->bdrv_co_pwritev(bs, qcow2_vm_state_offset(s) + pos,
4033                                     qiov->size, qiov, 0);
4034 }
4035 
4036 static int qcow2_load_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
4037                               int64_t pos)
4038 {
4039     BDRVQcow2State *s = bs->opaque;
4040 
4041     BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_LOAD);
4042     return bs->drv->bdrv_co_preadv(bs, qcow2_vm_state_offset(s) + pos,
4043                                    qiov->size, qiov, 0);
4044 }
4045 
4046 /*
4047  * Downgrades an image's version. To achieve this, any incompatible features
4048  * have to be removed.
4049  */
4050 static int qcow2_downgrade(BlockDriverState *bs, int target_version,
4051                            BlockDriverAmendStatusCB *status_cb, void *cb_opaque)
4052 {
4053     BDRVQcow2State *s = bs->opaque;
4054     int current_version = s->qcow_version;
4055     int ret;
4056 
4057     if (target_version == current_version) {
4058         return 0;
4059     } else if (target_version > current_version) {
4060         return -EINVAL;
4061     } else if (target_version != 2) {
4062         return -EINVAL;
4063     }
4064 
4065     if (s->refcount_order != 4) {
4066         error_report("compat=0.10 requires refcount_bits=16");
4067         return -ENOTSUP;
4068     }
4069 
4070     /* clear incompatible features */
4071     if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
4072         ret = qcow2_mark_clean(bs);
4073         if (ret < 0) {
4074             return ret;
4075         }
4076     }
4077 
4078     /* with QCOW2_INCOMPAT_CORRUPT, it is pretty much impossible to get here in
4079      * the first place; if that happens nonetheless, returning -ENOTSUP is the
4080      * best thing to do anyway */
4081 
4082     if (s->incompatible_features) {
4083         return -ENOTSUP;
4084     }
4085 
4086     /* since we can ignore compatible features, we can set them to 0 as well */
4087     s->compatible_features = 0;
4088     /* if lazy refcounts have been used, they have already been fixed through
4089      * clearing the dirty flag */
4090 
4091     /* clearing autoclear features is trivial */
4092     s->autoclear_features = 0;
4093 
4094     ret = qcow2_expand_zero_clusters(bs, status_cb, cb_opaque);
4095     if (ret < 0) {
4096         return ret;
4097     }
4098 
4099     s->qcow_version = target_version;
4100     ret = qcow2_update_header(bs);
4101     if (ret < 0) {
4102         s->qcow_version = current_version;
4103         return ret;
4104     }
4105     return 0;
4106 }
4107 
4108 typedef enum Qcow2AmendOperation {
4109     /* This is the value Qcow2AmendHelperCBInfo::last_operation will be
4110      * statically initialized to so that the helper CB can discern the first
4111      * invocation from an operation change */
4112     QCOW2_NO_OPERATION = 0,
4113 
4114     QCOW2_CHANGING_REFCOUNT_ORDER,
4115     QCOW2_DOWNGRADING,
4116 } Qcow2AmendOperation;
4117 
4118 typedef struct Qcow2AmendHelperCBInfo {
4119     /* The code coordinating the amend operations should only modify
4120      * these four fields; the rest will be managed by the CB */
4121     BlockDriverAmendStatusCB *original_status_cb;
4122     void *original_cb_opaque;
4123 
4124     Qcow2AmendOperation current_operation;
4125 
4126     /* Total number of operations to perform (only set once) */
4127     int total_operations;
4128 
4129     /* The following fields are managed by the CB */
4130 
4131     /* Number of operations completed */
4132     int operations_completed;
4133 
4134     /* Cumulative offset of all completed operations */
4135     int64_t offset_completed;
4136 
4137     Qcow2AmendOperation last_operation;
4138     int64_t last_work_size;
4139 } Qcow2AmendHelperCBInfo;
4140 
4141 static void qcow2_amend_helper_cb(BlockDriverState *bs,
4142                                   int64_t operation_offset,
4143                                   int64_t operation_work_size, void *opaque)
4144 {
4145     Qcow2AmendHelperCBInfo *info = opaque;
4146     int64_t current_work_size;
4147     int64_t projected_work_size;
4148 
4149     if (info->current_operation != info->last_operation) {
4150         if (info->last_operation != QCOW2_NO_OPERATION) {
4151             info->offset_completed += info->last_work_size;
4152             info->operations_completed++;
4153         }
4154 
4155         info->last_operation = info->current_operation;
4156     }
4157 
4158     assert(info->total_operations > 0);
4159     assert(info->operations_completed < info->total_operations);
4160 
4161     info->last_work_size = operation_work_size;
4162 
4163     current_work_size = info->offset_completed + operation_work_size;
4164 
4165     /* current_work_size is the total work size for (operations_completed + 1)
4166      * operations (which includes this one), so multiply it by the number of
4167      * operations not covered and divide it by the number of operations
4168      * covered to get a projection for the operations not covered */
4169     projected_work_size = current_work_size * (info->total_operations -
4170                                                info->operations_completed - 1)
4171                                             / (info->operations_completed + 1);
4172 
4173     info->original_status_cb(bs, info->offset_completed + operation_offset,
4174                              current_work_size + projected_work_size,
4175                              info->original_cb_opaque);
4176 }
4177 
4178 static int qcow2_amend_options(BlockDriverState *bs, QemuOpts *opts,
4179                                BlockDriverAmendStatusCB *status_cb,
4180                                void *cb_opaque)
4181 {
4182     BDRVQcow2State *s = bs->opaque;
4183     int old_version = s->qcow_version, new_version = old_version;
4184     uint64_t new_size = 0;
4185     const char *backing_file = NULL, *backing_format = NULL;
4186     bool lazy_refcounts = s->use_lazy_refcounts;
4187     const char *compat = NULL;
4188     uint64_t cluster_size = s->cluster_size;
4189     bool encrypt;
4190     int encformat;
4191     int refcount_bits = s->refcount_bits;
4192     Error *local_err = NULL;
4193     int ret;
4194     QemuOptDesc *desc = opts->list->desc;
4195     Qcow2AmendHelperCBInfo helper_cb_info;
4196 
4197     while (desc && desc->name) {
4198         if (!qemu_opt_find(opts, desc->name)) {
4199             /* only change explicitly defined options */
4200             desc++;
4201             continue;
4202         }
4203 
4204         if (!strcmp(desc->name, BLOCK_OPT_COMPAT_LEVEL)) {
4205             compat = qemu_opt_get(opts, BLOCK_OPT_COMPAT_LEVEL);
4206             if (!compat) {
4207                 /* preserve default */
4208             } else if (!strcmp(compat, "0.10")) {
4209                 new_version = 2;
4210             } else if (!strcmp(compat, "1.1")) {
4211                 new_version = 3;
4212             } else {
4213                 error_report("Unknown compatibility level %s", compat);
4214                 return -EINVAL;
4215             }
4216         } else if (!strcmp(desc->name, BLOCK_OPT_PREALLOC)) {
4217             error_report("Cannot change preallocation mode");
4218             return -ENOTSUP;
4219         } else if (!strcmp(desc->name, BLOCK_OPT_SIZE)) {
4220             new_size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, 0);
4221         } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FILE)) {
4222             backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
4223         } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FMT)) {
4224             backing_format = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
4225         } else if (!strcmp(desc->name, BLOCK_OPT_ENCRYPT)) {
4226             encrypt = qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT,
4227                                         !!s->crypto);
4228 
4229             if (encrypt != !!s->crypto) {
4230                 error_report("Changing the encryption flag is not supported");
4231                 return -ENOTSUP;
4232             }
4233         } else if (!strcmp(desc->name, BLOCK_OPT_ENCRYPT_FORMAT)) {
4234             encformat = qcow2_crypt_method_from_format(
4235                 qemu_opt_get(opts, BLOCK_OPT_ENCRYPT_FORMAT));
4236 
4237             if (encformat != s->crypt_method_header) {
4238                 error_report("Changing the encryption format is not supported");
4239                 return -ENOTSUP;
4240             }
4241         } else if (g_str_has_prefix(desc->name, "encrypt.")) {
4242             error_report("Changing the encryption parameters is not supported");
4243             return -ENOTSUP;
4244         } else if (!strcmp(desc->name, BLOCK_OPT_CLUSTER_SIZE)) {
4245             cluster_size = qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE,
4246                                              cluster_size);
4247             if (cluster_size != s->cluster_size) {
4248                 error_report("Changing the cluster size is not supported");
4249                 return -ENOTSUP;
4250             }
4251         } else if (!strcmp(desc->name, BLOCK_OPT_LAZY_REFCOUNTS)) {
4252             lazy_refcounts = qemu_opt_get_bool(opts, BLOCK_OPT_LAZY_REFCOUNTS,
4253                                                lazy_refcounts);
4254         } else if (!strcmp(desc->name, BLOCK_OPT_REFCOUNT_BITS)) {
4255             refcount_bits = qemu_opt_get_number(opts, BLOCK_OPT_REFCOUNT_BITS,
4256                                                 refcount_bits);
4257 
4258             if (refcount_bits <= 0 || refcount_bits > 64 ||
4259                 !is_power_of_2(refcount_bits))
4260             {
4261                 error_report("Refcount width must be a power of two and may "
4262                              "not exceed 64 bits");
4263                 return -EINVAL;
4264             }
4265         } else {
4266             /* if this point is reached, this probably means a new option was
4267              * added without having it covered here */
4268             abort();
4269         }
4270 
4271         desc++;
4272     }
4273 
4274     helper_cb_info = (Qcow2AmendHelperCBInfo){
4275         .original_status_cb = status_cb,
4276         .original_cb_opaque = cb_opaque,
4277         .total_operations = (new_version < old_version)
4278                           + (s->refcount_bits != refcount_bits)
4279     };
4280 
4281     /* Upgrade first (some features may require compat=1.1) */
4282     if (new_version > old_version) {
4283         s->qcow_version = new_version;
4284         ret = qcow2_update_header(bs);
4285         if (ret < 0) {
4286             s->qcow_version = old_version;
4287             return ret;
4288         }
4289     }
4290 
4291     if (s->refcount_bits != refcount_bits) {
4292         int refcount_order = ctz32(refcount_bits);
4293 
4294         if (new_version < 3 && refcount_bits != 16) {
4295             error_report("Different refcount widths than 16 bits require "
4296                          "compatibility level 1.1 or above (use compat=1.1 or "
4297                          "greater)");
4298             return -EINVAL;
4299         }
4300 
4301         helper_cb_info.current_operation = QCOW2_CHANGING_REFCOUNT_ORDER;
4302         ret = qcow2_change_refcount_order(bs, refcount_order,
4303                                           &qcow2_amend_helper_cb,
4304                                           &helper_cb_info, &local_err);
4305         if (ret < 0) {
4306             error_report_err(local_err);
4307             return ret;
4308         }
4309     }
4310 
4311     if (backing_file || backing_format) {
4312         ret = qcow2_change_backing_file(bs,
4313                     backing_file ?: s->image_backing_file,
4314                     backing_format ?: s->image_backing_format);
4315         if (ret < 0) {
4316             return ret;
4317         }
4318     }
4319 
4320     if (s->use_lazy_refcounts != lazy_refcounts) {
4321         if (lazy_refcounts) {
4322             if (new_version < 3) {
4323                 error_report("Lazy refcounts only supported with compatibility "
4324                              "level 1.1 and above (use compat=1.1 or greater)");
4325                 return -EINVAL;
4326             }
4327             s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
4328             ret = qcow2_update_header(bs);
4329             if (ret < 0) {
4330                 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
4331                 return ret;
4332             }
4333             s->use_lazy_refcounts = true;
4334         } else {
4335             /* make image clean first */
4336             ret = qcow2_mark_clean(bs);
4337             if (ret < 0) {
4338                 return ret;
4339             }
4340             /* now disallow lazy refcounts */
4341             s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
4342             ret = qcow2_update_header(bs);
4343             if (ret < 0) {
4344                 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
4345                 return ret;
4346             }
4347             s->use_lazy_refcounts = false;
4348         }
4349     }
4350 
4351     if (new_size) {
4352         BlockBackend *blk = blk_new(BLK_PERM_RESIZE, BLK_PERM_ALL);
4353         ret = blk_insert_bs(blk, bs, &local_err);
4354         if (ret < 0) {
4355             error_report_err(local_err);
4356             blk_unref(blk);
4357             return ret;
4358         }
4359 
4360         ret = blk_truncate(blk, new_size, PREALLOC_MODE_OFF, &local_err);
4361         blk_unref(blk);
4362         if (ret < 0) {
4363             error_report_err(local_err);
4364             return ret;
4365         }
4366     }
4367 
4368     /* Downgrade last (so unsupported features can be removed before) */
4369     if (new_version < old_version) {
4370         helper_cb_info.current_operation = QCOW2_DOWNGRADING;
4371         ret = qcow2_downgrade(bs, new_version, &qcow2_amend_helper_cb,
4372                               &helper_cb_info);
4373         if (ret < 0) {
4374             return ret;
4375         }
4376     }
4377 
4378     return 0;
4379 }
4380 
4381 /*
4382  * If offset or size are negative, respectively, they will not be included in
4383  * the BLOCK_IMAGE_CORRUPTED event emitted.
4384  * fatal will be ignored for read-only BDS; corruptions found there will always
4385  * be considered non-fatal.
4386  */
4387 void qcow2_signal_corruption(BlockDriverState *bs, bool fatal, int64_t offset,
4388                              int64_t size, const char *message_format, ...)
4389 {
4390     BDRVQcow2State *s = bs->opaque;
4391     const char *node_name;
4392     char *message;
4393     va_list ap;
4394 
4395     fatal = fatal && !bs->read_only;
4396 
4397     if (s->signaled_corruption &&
4398         (!fatal || (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT)))
4399     {
4400         return;
4401     }
4402 
4403     va_start(ap, message_format);
4404     message = g_strdup_vprintf(message_format, ap);
4405     va_end(ap);
4406 
4407     if (fatal) {
4408         fprintf(stderr, "qcow2: Marking image as corrupt: %s; further "
4409                 "corruption events will be suppressed\n", message);
4410     } else {
4411         fprintf(stderr, "qcow2: Image is corrupt: %s; further non-fatal "
4412                 "corruption events will be suppressed\n", message);
4413     }
4414 
4415     node_name = bdrv_get_node_name(bs);
4416     qapi_event_send_block_image_corrupted(bdrv_get_device_name(bs),
4417                                           *node_name != '\0', node_name,
4418                                           message, offset >= 0, offset,
4419                                           size >= 0, size,
4420                                           fatal, &error_abort);
4421     g_free(message);
4422 
4423     if (fatal) {
4424         qcow2_mark_corrupt(bs);
4425         bs->drv = NULL; /* make BDS unusable */
4426     }
4427 
4428     s->signaled_corruption = true;
4429 }
4430 
4431 static QemuOptsList qcow2_create_opts = {
4432     .name = "qcow2-create-opts",
4433     .head = QTAILQ_HEAD_INITIALIZER(qcow2_create_opts.head),
4434     .desc = {
4435         {
4436             .name = BLOCK_OPT_SIZE,
4437             .type = QEMU_OPT_SIZE,
4438             .help = "Virtual disk size"
4439         },
4440         {
4441             .name = BLOCK_OPT_COMPAT_LEVEL,
4442             .type = QEMU_OPT_STRING,
4443             .help = "Compatibility level (0.10 or 1.1)"
4444         },
4445         {
4446             .name = BLOCK_OPT_BACKING_FILE,
4447             .type = QEMU_OPT_STRING,
4448             .help = "File name of a base image"
4449         },
4450         {
4451             .name = BLOCK_OPT_BACKING_FMT,
4452             .type = QEMU_OPT_STRING,
4453             .help = "Image format of the base image"
4454         },
4455         {
4456             .name = BLOCK_OPT_ENCRYPT,
4457             .type = QEMU_OPT_BOOL,
4458             .help = "Encrypt the image with format 'aes'. (Deprecated "
4459                     "in favor of " BLOCK_OPT_ENCRYPT_FORMAT "=aes)",
4460         },
4461         {
4462             .name = BLOCK_OPT_ENCRYPT_FORMAT,
4463             .type = QEMU_OPT_STRING,
4464             .help = "Encrypt the image, format choices: 'aes', 'luks'",
4465         },
4466         BLOCK_CRYPTO_OPT_DEF_KEY_SECRET("encrypt.",
4467             "ID of secret providing qcow AES key or LUKS passphrase"),
4468         BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_ALG("encrypt."),
4469         BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_MODE("encrypt."),
4470         BLOCK_CRYPTO_OPT_DEF_LUKS_IVGEN_ALG("encrypt."),
4471         BLOCK_CRYPTO_OPT_DEF_LUKS_IVGEN_HASH_ALG("encrypt."),
4472         BLOCK_CRYPTO_OPT_DEF_LUKS_HASH_ALG("encrypt."),
4473         BLOCK_CRYPTO_OPT_DEF_LUKS_ITER_TIME("encrypt."),
4474         {
4475             .name = BLOCK_OPT_CLUSTER_SIZE,
4476             .type = QEMU_OPT_SIZE,
4477             .help = "qcow2 cluster size",
4478             .def_value_str = stringify(DEFAULT_CLUSTER_SIZE)
4479         },
4480         {
4481             .name = BLOCK_OPT_PREALLOC,
4482             .type = QEMU_OPT_STRING,
4483             .help = "Preallocation mode (allowed values: off, metadata, "
4484                     "falloc, full)"
4485         },
4486         {
4487             .name = BLOCK_OPT_LAZY_REFCOUNTS,
4488             .type = QEMU_OPT_BOOL,
4489             .help = "Postpone refcount updates",
4490             .def_value_str = "off"
4491         },
4492         {
4493             .name = BLOCK_OPT_REFCOUNT_BITS,
4494             .type = QEMU_OPT_NUMBER,
4495             .help = "Width of a reference count entry in bits",
4496             .def_value_str = "16"
4497         },
4498         { /* end of list */ }
4499     }
4500 };
4501 
4502 BlockDriver bdrv_qcow2 = {
4503     .format_name        = "qcow2",
4504     .instance_size      = sizeof(BDRVQcow2State),
4505     .bdrv_probe         = qcow2_probe,
4506     .bdrv_open          = qcow2_open,
4507     .bdrv_close         = qcow2_close,
4508     .bdrv_reopen_prepare  = qcow2_reopen_prepare,
4509     .bdrv_reopen_commit   = qcow2_reopen_commit,
4510     .bdrv_reopen_abort    = qcow2_reopen_abort,
4511     .bdrv_join_options    = qcow2_join_options,
4512     .bdrv_child_perm      = bdrv_format_default_perms,
4513     .bdrv_co_create_opts  = qcow2_co_create_opts,
4514     .bdrv_co_create       = qcow2_co_create,
4515     .bdrv_has_zero_init = bdrv_has_zero_init_1,
4516     .bdrv_co_block_status = qcow2_co_block_status,
4517 
4518     .bdrv_co_preadv         = qcow2_co_preadv,
4519     .bdrv_co_pwritev        = qcow2_co_pwritev,
4520     .bdrv_co_flush_to_os    = qcow2_co_flush_to_os,
4521 
4522     .bdrv_co_pwrite_zeroes  = qcow2_co_pwrite_zeroes,
4523     .bdrv_co_pdiscard       = qcow2_co_pdiscard,
4524     .bdrv_truncate          = qcow2_truncate,
4525     .bdrv_co_pwritev_compressed = qcow2_co_pwritev_compressed,
4526     .bdrv_make_empty        = qcow2_make_empty,
4527 
4528     .bdrv_snapshot_create   = qcow2_snapshot_create,
4529     .bdrv_snapshot_goto     = qcow2_snapshot_goto,
4530     .bdrv_snapshot_delete   = qcow2_snapshot_delete,
4531     .bdrv_snapshot_list     = qcow2_snapshot_list,
4532     .bdrv_snapshot_load_tmp = qcow2_snapshot_load_tmp,
4533     .bdrv_measure           = qcow2_measure,
4534     .bdrv_get_info          = qcow2_get_info,
4535     .bdrv_get_specific_info = qcow2_get_specific_info,
4536 
4537     .bdrv_save_vmstate    = qcow2_save_vmstate,
4538     .bdrv_load_vmstate    = qcow2_load_vmstate,
4539 
4540     .supports_backing           = true,
4541     .bdrv_change_backing_file   = qcow2_change_backing_file,
4542 
4543     .bdrv_refresh_limits        = qcow2_refresh_limits,
4544     .bdrv_co_invalidate_cache   = qcow2_co_invalidate_cache,
4545     .bdrv_inactivate            = qcow2_inactivate,
4546 
4547     .create_opts         = &qcow2_create_opts,
4548     .bdrv_co_check       = qcow2_co_check,
4549     .bdrv_amend_options  = qcow2_amend_options,
4550 
4551     .bdrv_detach_aio_context  = qcow2_detach_aio_context,
4552     .bdrv_attach_aio_context  = qcow2_attach_aio_context,
4553 
4554     .bdrv_reopen_bitmaps_rw = qcow2_reopen_bitmaps_rw,
4555     .bdrv_can_store_new_dirty_bitmap = qcow2_can_store_new_dirty_bitmap,
4556     .bdrv_remove_persistent_dirty_bitmap = qcow2_remove_persistent_dirty_bitmap,
4557 };
4558 
4559 static void bdrv_qcow2_init(void)
4560 {
4561     bdrv_register(&bdrv_qcow2);
4562 }
4563 
4564 block_init(bdrv_qcow2_init);
4565