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