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