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