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