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