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