xref: /qemu/block/qcow2.c (revision efaa7c4eeb7490c6f37f34fbc77e91f29363eebd)
1585f8587Sbellard /*
2585f8587Sbellard  * Block driver for the QCOW version 2 format
3585f8587Sbellard  *
4585f8587Sbellard  * Copyright (c) 2004-2006 Fabrice Bellard
5585f8587Sbellard  *
6585f8587Sbellard  * Permission is hereby granted, free of charge, to any person obtaining a copy
7585f8587Sbellard  * of this software and associated documentation files (the "Software"), to deal
8585f8587Sbellard  * in the Software without restriction, including without limitation the rights
9585f8587Sbellard  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10585f8587Sbellard  * copies of the Software, and to permit persons to whom the Software is
11585f8587Sbellard  * furnished to do so, subject to the following conditions:
12585f8587Sbellard  *
13585f8587Sbellard  * The above copyright notice and this permission notice shall be included in
14585f8587Sbellard  * all copies or substantial portions of the Software.
15585f8587Sbellard  *
16585f8587Sbellard  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17585f8587Sbellard  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18585f8587Sbellard  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19585f8587Sbellard  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20585f8587Sbellard  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21585f8587Sbellard  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22585f8587Sbellard  * THE SOFTWARE.
23585f8587Sbellard  */
2480c71a24SPeter Maydell #include "qemu/osdep.h"
25faf07963Spbrook #include "qemu-common.h"
26737e150eSPaolo Bonzini #include "block/block_int.h"
2723588797SKevin Wolf #include "sysemu/block-backend.h"
281de7afc9SPaolo Bonzini #include "qemu/module.h"
29585f8587Sbellard #include <zlib.h>
30f7d0fe02SKevin Wolf #include "block/qcow2.h"
311de7afc9SPaolo Bonzini #include "qemu/error-report.h"
327b1b5d19SPaolo Bonzini #include "qapi/qmp/qerror.h"
33acdfb480SKevin Wolf #include "qapi/qmp/qbool.h"
34ffeaac9bSHu Tao #include "qapi/util.h"
3585186ebdSMax Reitz #include "qapi/qmp/types.h"
3685186ebdSMax Reitz #include "qapi-event.h"
373cce16f4SKevin Wolf #include "trace.h"
381bd0e2d1SChunyan Liu #include "qemu/option_int.h"
39585f8587Sbellard 
40585f8587Sbellard /*
41585f8587Sbellard   Differences with QCOW:
42585f8587Sbellard 
43585f8587Sbellard   - Support for multiple incremental snapshots.
44585f8587Sbellard   - Memory management by reference counts.
45585f8587Sbellard   - Clusters which have a reference count of one have the bit
46585f8587Sbellard     QCOW_OFLAG_COPIED to optimize write performance.
47585f8587Sbellard   - Size of compressed clusters is stored in sectors to reduce bit usage
48585f8587Sbellard     in the cluster offsets.
49585f8587Sbellard   - Support for storing additional data (such as the VM state) in the
50585f8587Sbellard     snapshots.
51585f8587Sbellard   - If a backing store is used, the cluster size is not constrained
52585f8587Sbellard     (could be backported to QCOW).
53585f8587Sbellard   - L2 tables have always a size of one cluster.
54585f8587Sbellard */
55585f8587Sbellard 
569b80ddf3Saliguori 
579b80ddf3Saliguori typedef struct {
589b80ddf3Saliguori     uint32_t magic;
599b80ddf3Saliguori     uint32_t len;
60c4217f64SJeff Cody } QEMU_PACKED QCowExtension;
6121d82ac9SJeff Cody 
627c80ab3fSJes Sorensen #define  QCOW2_EXT_MAGIC_END 0
637c80ab3fSJes Sorensen #define  QCOW2_EXT_MAGIC_BACKING_FORMAT 0xE2792ACA
64cfcc4c62SKevin Wolf #define  QCOW2_EXT_MAGIC_FEATURE_TABLE 0x6803f857
659b80ddf3Saliguori 
667c80ab3fSJes Sorensen static int qcow2_probe(const uint8_t *buf, int buf_size, const char *filename)
67585f8587Sbellard {
68585f8587Sbellard     const QCowHeader *cow_header = (const void *)buf;
69585f8587Sbellard 
70585f8587Sbellard     if (buf_size >= sizeof(QCowHeader) &&
71585f8587Sbellard         be32_to_cpu(cow_header->magic) == QCOW_MAGIC &&
726744cbabSKevin Wolf         be32_to_cpu(cow_header->version) >= 2)
73585f8587Sbellard         return 100;
74585f8587Sbellard     else
75585f8587Sbellard         return 0;
76585f8587Sbellard }
77585f8587Sbellard 
789b80ddf3Saliguori 
799b80ddf3Saliguori /*
809b80ddf3Saliguori  * read qcow2 extension and fill bs
819b80ddf3Saliguori  * start reading from start_offset
829b80ddf3Saliguori  * finish reading upon magic of value 0 or when end_offset reached
839b80ddf3Saliguori  * unknown magic is skipped (future extension this version knows nothing about)
849b80ddf3Saliguori  * return 0 upon success, non-0 otherwise
859b80ddf3Saliguori  */
867c80ab3fSJes Sorensen static int qcow2_read_extensions(BlockDriverState *bs, uint64_t start_offset,
873ef6c40aSMax Reitz                                  uint64_t end_offset, void **p_feature_table,
883ef6c40aSMax Reitz                                  Error **errp)
899b80ddf3Saliguori {
90ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
919b80ddf3Saliguori     QCowExtension ext;
929b80ddf3Saliguori     uint64_t offset;
9375bab85cSKevin Wolf     int ret;
949b80ddf3Saliguori 
959b80ddf3Saliguori #ifdef DEBUG_EXT
967c80ab3fSJes Sorensen     printf("qcow2_read_extensions: start=%ld end=%ld\n", start_offset, end_offset);
979b80ddf3Saliguori #endif
989b80ddf3Saliguori     offset = start_offset;
999b80ddf3Saliguori     while (offset < end_offset) {
1009b80ddf3Saliguori 
1019b80ddf3Saliguori #ifdef DEBUG_EXT
1029b80ddf3Saliguori         /* Sanity check */
1039b80ddf3Saliguori         if (offset > s->cluster_size)
1047c80ab3fSJes Sorensen             printf("qcow2_read_extension: suspicious offset %lu\n", offset);
1059b80ddf3Saliguori 
1069b2260cbSDong Xu Wang         printf("attempting to read extended header in offset %lu\n", offset);
1079b80ddf3Saliguori #endif
1089b80ddf3Saliguori 
1099a4f4c31SKevin Wolf         ret = bdrv_pread(bs->file->bs, offset, &ext, sizeof(ext));
1103ef6c40aSMax Reitz         if (ret < 0) {
1113ef6c40aSMax Reitz             error_setg_errno(errp, -ret, "qcow2_read_extension: ERROR: "
1123ef6c40aSMax Reitz                              "pread fail from offset %" PRIu64, offset);
1139b80ddf3Saliguori             return 1;
1149b80ddf3Saliguori         }
1159b80ddf3Saliguori         be32_to_cpus(&ext.magic);
1169b80ddf3Saliguori         be32_to_cpus(&ext.len);
1179b80ddf3Saliguori         offset += sizeof(ext);
1189b80ddf3Saliguori #ifdef DEBUG_EXT
1199b80ddf3Saliguori         printf("ext.magic = 0x%x\n", ext.magic);
1209b80ddf3Saliguori #endif
1212ebafc85SKevin Wolf         if (offset > end_offset || ext.len > end_offset - offset) {
1223ef6c40aSMax Reitz             error_setg(errp, "Header extension too large");
12364ca6aeeSKevin Wolf             return -EINVAL;
12464ca6aeeSKevin Wolf         }
12564ca6aeeSKevin Wolf 
1269b80ddf3Saliguori         switch (ext.magic) {
1277c80ab3fSJes Sorensen         case QCOW2_EXT_MAGIC_END:
1289b80ddf3Saliguori             return 0;
129f965509cSaliguori 
1307c80ab3fSJes Sorensen         case QCOW2_EXT_MAGIC_BACKING_FORMAT:
131f965509cSaliguori             if (ext.len >= sizeof(bs->backing_format)) {
132521b2b5dSMax Reitz                 error_setg(errp, "ERROR: ext_backing_format: len=%" PRIu32
133521b2b5dSMax Reitz                            " too large (>=%zu)", ext.len,
134521b2b5dSMax Reitz                            sizeof(bs->backing_format));
135f965509cSaliguori                 return 2;
136f965509cSaliguori             }
1379a4f4c31SKevin Wolf             ret = bdrv_pread(bs->file->bs, offset, bs->backing_format, ext.len);
1383ef6c40aSMax Reitz             if (ret < 0) {
1393ef6c40aSMax Reitz                 error_setg_errno(errp, -ret, "ERROR: ext_backing_format: "
1403ef6c40aSMax Reitz                                  "Could not read format name");
141f965509cSaliguori                 return 3;
1423ef6c40aSMax Reitz             }
143f965509cSaliguori             bs->backing_format[ext.len] = '\0';
144e4603fe1SKevin Wolf             s->image_backing_format = g_strdup(bs->backing_format);
145f965509cSaliguori #ifdef DEBUG_EXT
146f965509cSaliguori             printf("Qcow2: Got format extension %s\n", bs->backing_format);
147f965509cSaliguori #endif
148f965509cSaliguori             break;
149f965509cSaliguori 
150cfcc4c62SKevin Wolf         case QCOW2_EXT_MAGIC_FEATURE_TABLE:
151cfcc4c62SKevin Wolf             if (p_feature_table != NULL) {
152cfcc4c62SKevin Wolf                 void* feature_table = g_malloc0(ext.len + 2 * sizeof(Qcow2Feature));
1539a4f4c31SKevin Wolf                 ret = bdrv_pread(bs->file->bs, offset , feature_table, ext.len);
154cfcc4c62SKevin Wolf                 if (ret < 0) {
1553ef6c40aSMax Reitz                     error_setg_errno(errp, -ret, "ERROR: ext_feature_table: "
1563ef6c40aSMax Reitz                                      "Could not read table");
157cfcc4c62SKevin Wolf                     return ret;
158cfcc4c62SKevin Wolf                 }
159cfcc4c62SKevin Wolf 
160cfcc4c62SKevin Wolf                 *p_feature_table = feature_table;
161cfcc4c62SKevin Wolf             }
162cfcc4c62SKevin Wolf             break;
163cfcc4c62SKevin Wolf 
1649b80ddf3Saliguori         default:
16575bab85cSKevin Wolf             /* unknown magic - save it in case we need to rewrite the header */
16675bab85cSKevin Wolf             {
16775bab85cSKevin Wolf                 Qcow2UnknownHeaderExtension *uext;
16875bab85cSKevin Wolf 
16975bab85cSKevin Wolf                 uext = g_malloc0(sizeof(*uext)  + ext.len);
17075bab85cSKevin Wolf                 uext->magic = ext.magic;
17175bab85cSKevin Wolf                 uext->len = ext.len;
17275bab85cSKevin Wolf                 QLIST_INSERT_HEAD(&s->unknown_header_ext, uext, next);
17375bab85cSKevin Wolf 
1749a4f4c31SKevin Wolf                 ret = bdrv_pread(bs->file->bs, offset , uext->data, uext->len);
17575bab85cSKevin Wolf                 if (ret < 0) {
1763ef6c40aSMax Reitz                     error_setg_errno(errp, -ret, "ERROR: unknown extension: "
1773ef6c40aSMax Reitz                                      "Could not read data");
17875bab85cSKevin Wolf                     return ret;
17975bab85cSKevin Wolf                 }
18075bab85cSKevin Wolf             }
1819b80ddf3Saliguori             break;
1829b80ddf3Saliguori         }
183fd29b4bbSKevin Wolf 
184fd29b4bbSKevin Wolf         offset += ((ext.len + 7) & ~7);
1859b80ddf3Saliguori     }
1869b80ddf3Saliguori 
1879b80ddf3Saliguori     return 0;
1889b80ddf3Saliguori }
1899b80ddf3Saliguori 
19075bab85cSKevin Wolf static void cleanup_unknown_header_ext(BlockDriverState *bs)
19175bab85cSKevin Wolf {
192ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
19375bab85cSKevin Wolf     Qcow2UnknownHeaderExtension *uext, *next;
19475bab85cSKevin Wolf 
19575bab85cSKevin Wolf     QLIST_FOREACH_SAFE(uext, &s->unknown_header_ext, next, next) {
19675bab85cSKevin Wolf         QLIST_REMOVE(uext, next);
19775bab85cSKevin Wolf         g_free(uext);
19875bab85cSKevin Wolf     }
19975bab85cSKevin Wolf }
2009b80ddf3Saliguori 
201a55448b3SMax Reitz static void report_unsupported_feature(Error **errp, Qcow2Feature *table,
202a55448b3SMax Reitz                                        uint64_t mask)
203cfcc4c62SKevin Wolf {
20412ac6d3dSKevin Wolf     char *features = g_strdup("");
20512ac6d3dSKevin Wolf     char *old;
20612ac6d3dSKevin Wolf 
207cfcc4c62SKevin Wolf     while (table && table->name[0] != '\0') {
208cfcc4c62SKevin Wolf         if (table->type == QCOW2_FEAT_TYPE_INCOMPATIBLE) {
20912ac6d3dSKevin Wolf             if (mask & (1ULL << table->bit)) {
21012ac6d3dSKevin Wolf                 old = features;
21112ac6d3dSKevin Wolf                 features = g_strdup_printf("%s%s%.46s", old, *old ? ", " : "",
21212ac6d3dSKevin Wolf                                            table->name);
21312ac6d3dSKevin Wolf                 g_free(old);
21412ac6d3dSKevin Wolf                 mask &= ~(1ULL << table->bit);
215cfcc4c62SKevin Wolf             }
216cfcc4c62SKevin Wolf         }
217cfcc4c62SKevin Wolf         table++;
218cfcc4c62SKevin Wolf     }
219cfcc4c62SKevin Wolf 
220cfcc4c62SKevin Wolf     if (mask) {
22112ac6d3dSKevin Wolf         old = features;
22212ac6d3dSKevin Wolf         features = g_strdup_printf("%s%sUnknown incompatible feature: %" PRIx64,
22312ac6d3dSKevin Wolf                                    old, *old ? ", " : "", mask);
22412ac6d3dSKevin Wolf         g_free(old);
225cfcc4c62SKevin Wolf     }
22612ac6d3dSKevin Wolf 
227a55448b3SMax Reitz     error_setg(errp, "Unsupported qcow2 feature(s): %s", features);
22812ac6d3dSKevin Wolf     g_free(features);
229cfcc4c62SKevin Wolf }
230cfcc4c62SKevin Wolf 
231c61d0004SStefan Hajnoczi /*
232bfe8043eSStefan Hajnoczi  * Sets the dirty bit and flushes afterwards if necessary.
233bfe8043eSStefan Hajnoczi  *
234bfe8043eSStefan Hajnoczi  * The incompatible_features bit is only set if the image file header was
235bfe8043eSStefan Hajnoczi  * updated successfully.  Therefore it is not required to check the return
236bfe8043eSStefan Hajnoczi  * value of this function.
237bfe8043eSStefan Hajnoczi  */
238280d3735SKevin Wolf int qcow2_mark_dirty(BlockDriverState *bs)
239bfe8043eSStefan Hajnoczi {
240ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
241bfe8043eSStefan Hajnoczi     uint64_t val;
242bfe8043eSStefan Hajnoczi     int ret;
243bfe8043eSStefan Hajnoczi 
244bfe8043eSStefan Hajnoczi     assert(s->qcow_version >= 3);
245bfe8043eSStefan Hajnoczi 
246bfe8043eSStefan Hajnoczi     if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
247bfe8043eSStefan Hajnoczi         return 0; /* already dirty */
248bfe8043eSStefan Hajnoczi     }
249bfe8043eSStefan Hajnoczi 
250bfe8043eSStefan Hajnoczi     val = cpu_to_be64(s->incompatible_features | QCOW2_INCOMPAT_DIRTY);
2519a4f4c31SKevin Wolf     ret = bdrv_pwrite(bs->file->bs, offsetof(QCowHeader, incompatible_features),
252bfe8043eSStefan Hajnoczi                       &val, sizeof(val));
253bfe8043eSStefan Hajnoczi     if (ret < 0) {
254bfe8043eSStefan Hajnoczi         return ret;
255bfe8043eSStefan Hajnoczi     }
2569a4f4c31SKevin Wolf     ret = bdrv_flush(bs->file->bs);
257bfe8043eSStefan Hajnoczi     if (ret < 0) {
258bfe8043eSStefan Hajnoczi         return ret;
259bfe8043eSStefan Hajnoczi     }
260bfe8043eSStefan Hajnoczi 
261bfe8043eSStefan Hajnoczi     /* Only treat image as dirty if the header was updated successfully */
262bfe8043eSStefan Hajnoczi     s->incompatible_features |= QCOW2_INCOMPAT_DIRTY;
263bfe8043eSStefan Hajnoczi     return 0;
264bfe8043eSStefan Hajnoczi }
265bfe8043eSStefan Hajnoczi 
266bfe8043eSStefan Hajnoczi /*
267c61d0004SStefan Hajnoczi  * Clears the dirty bit and flushes before if necessary.  Only call this
268c61d0004SStefan Hajnoczi  * function when there are no pending requests, it does not guard against
269c61d0004SStefan Hajnoczi  * concurrent requests dirtying the image.
270c61d0004SStefan Hajnoczi  */
271c61d0004SStefan Hajnoczi static int qcow2_mark_clean(BlockDriverState *bs)
272c61d0004SStefan Hajnoczi {
273ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
274c61d0004SStefan Hajnoczi 
275c61d0004SStefan Hajnoczi     if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
2764c2e5f8fSKevin Wolf         int ret;
2774c2e5f8fSKevin Wolf 
2784c2e5f8fSKevin Wolf         s->incompatible_features &= ~QCOW2_INCOMPAT_DIRTY;
2794c2e5f8fSKevin Wolf 
2804c2e5f8fSKevin Wolf         ret = bdrv_flush(bs);
281c61d0004SStefan Hajnoczi         if (ret < 0) {
282c61d0004SStefan Hajnoczi             return ret;
283c61d0004SStefan Hajnoczi         }
284c61d0004SStefan Hajnoczi 
285c61d0004SStefan Hajnoczi         return qcow2_update_header(bs);
286c61d0004SStefan Hajnoczi     }
287c61d0004SStefan Hajnoczi     return 0;
288c61d0004SStefan Hajnoczi }
289c61d0004SStefan Hajnoczi 
29069c98726SMax Reitz /*
29169c98726SMax Reitz  * Marks the image as corrupt.
29269c98726SMax Reitz  */
29369c98726SMax Reitz int qcow2_mark_corrupt(BlockDriverState *bs)
29469c98726SMax Reitz {
295ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
29669c98726SMax Reitz 
29769c98726SMax Reitz     s->incompatible_features |= QCOW2_INCOMPAT_CORRUPT;
29869c98726SMax Reitz     return qcow2_update_header(bs);
29969c98726SMax Reitz }
30069c98726SMax Reitz 
30169c98726SMax Reitz /*
30269c98726SMax Reitz  * Marks the image as consistent, i.e., unsets the corrupt bit, and flushes
30369c98726SMax Reitz  * before if necessary.
30469c98726SMax Reitz  */
30569c98726SMax Reitz int qcow2_mark_consistent(BlockDriverState *bs)
30669c98726SMax Reitz {
307ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
30869c98726SMax Reitz 
30969c98726SMax Reitz     if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
31069c98726SMax Reitz         int ret = bdrv_flush(bs);
31169c98726SMax Reitz         if (ret < 0) {
31269c98726SMax Reitz             return ret;
31369c98726SMax Reitz         }
31469c98726SMax Reitz 
31569c98726SMax Reitz         s->incompatible_features &= ~QCOW2_INCOMPAT_CORRUPT;
31669c98726SMax Reitz         return qcow2_update_header(bs);
31769c98726SMax Reitz     }
31869c98726SMax Reitz     return 0;
31969c98726SMax Reitz }
32069c98726SMax Reitz 
321acbe5982SStefan Hajnoczi static int qcow2_check(BlockDriverState *bs, BdrvCheckResult *result,
322acbe5982SStefan Hajnoczi                        BdrvCheckMode fix)
323acbe5982SStefan Hajnoczi {
324acbe5982SStefan Hajnoczi     int ret = qcow2_check_refcounts(bs, result, fix);
325acbe5982SStefan Hajnoczi     if (ret < 0) {
326acbe5982SStefan Hajnoczi         return ret;
327acbe5982SStefan Hajnoczi     }
328acbe5982SStefan Hajnoczi 
329acbe5982SStefan Hajnoczi     if (fix && result->check_errors == 0 && result->corruptions == 0) {
33024530f3eSMax Reitz         ret = qcow2_mark_clean(bs);
33124530f3eSMax Reitz         if (ret < 0) {
33224530f3eSMax Reitz             return ret;
33324530f3eSMax Reitz         }
33424530f3eSMax Reitz         return qcow2_mark_consistent(bs);
335acbe5982SStefan Hajnoczi     }
336acbe5982SStefan Hajnoczi     return ret;
337acbe5982SStefan Hajnoczi }
338acbe5982SStefan Hajnoczi 
3398c7de283SKevin Wolf static int validate_table_offset(BlockDriverState *bs, uint64_t offset,
3408c7de283SKevin Wolf                                  uint64_t entries, size_t entry_len)
3418c7de283SKevin Wolf {
342ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
3438c7de283SKevin Wolf     uint64_t size;
3448c7de283SKevin Wolf 
3458c7de283SKevin Wolf     /* Use signed INT64_MAX as the maximum even for uint64_t header fields,
3468c7de283SKevin Wolf      * because values will be passed to qemu functions taking int64_t. */
3478c7de283SKevin Wolf     if (entries > INT64_MAX / entry_len) {
3488c7de283SKevin Wolf         return -EINVAL;
3498c7de283SKevin Wolf     }
3508c7de283SKevin Wolf 
3518c7de283SKevin Wolf     size = entries * entry_len;
3528c7de283SKevin Wolf 
3538c7de283SKevin Wolf     if (INT64_MAX - size < offset) {
3548c7de283SKevin Wolf         return -EINVAL;
3558c7de283SKevin Wolf     }
3568c7de283SKevin Wolf 
3578c7de283SKevin Wolf     /* Tables must be cluster aligned */
3588c7de283SKevin Wolf     if (offset & (s->cluster_size - 1)) {
3598c7de283SKevin Wolf         return -EINVAL;
3608c7de283SKevin Wolf     }
3618c7de283SKevin Wolf 
3628c7de283SKevin Wolf     return 0;
3638c7de283SKevin Wolf }
3648c7de283SKevin Wolf 
36574c4510aSKevin Wolf static QemuOptsList qcow2_runtime_opts = {
36674c4510aSKevin Wolf     .name = "qcow2",
36774c4510aSKevin Wolf     .head = QTAILQ_HEAD_INITIALIZER(qcow2_runtime_opts.head),
36874c4510aSKevin Wolf     .desc = {
36974c4510aSKevin Wolf         {
37064aa99d3SKevin Wolf             .name = QCOW2_OPT_LAZY_REFCOUNTS,
37174c4510aSKevin Wolf             .type = QEMU_OPT_BOOL,
37274c4510aSKevin Wolf             .help = "Postpone refcount updates",
37374c4510aSKevin Wolf         },
37467af674eSKevin Wolf         {
37567af674eSKevin Wolf             .name = QCOW2_OPT_DISCARD_REQUEST,
37667af674eSKevin Wolf             .type = QEMU_OPT_BOOL,
37767af674eSKevin Wolf             .help = "Pass guest discard requests to the layer below",
37867af674eSKevin Wolf         },
37967af674eSKevin Wolf         {
38067af674eSKevin Wolf             .name = QCOW2_OPT_DISCARD_SNAPSHOT,
38167af674eSKevin Wolf             .type = QEMU_OPT_BOOL,
38267af674eSKevin Wolf             .help = "Generate discard requests when snapshot related space "
38367af674eSKevin Wolf                     "is freed",
38467af674eSKevin Wolf         },
38567af674eSKevin Wolf         {
38667af674eSKevin Wolf             .name = QCOW2_OPT_DISCARD_OTHER,
38767af674eSKevin Wolf             .type = QEMU_OPT_BOOL,
38867af674eSKevin Wolf             .help = "Generate discard requests when other clusters are freed",
38967af674eSKevin Wolf         },
39005de7e86SMax Reitz         {
39105de7e86SMax Reitz             .name = QCOW2_OPT_OVERLAP,
39205de7e86SMax Reitz             .type = QEMU_OPT_STRING,
39305de7e86SMax Reitz             .help = "Selects which overlap checks to perform from a range of "
39405de7e86SMax Reitz                     "templates (none, constant, cached, all)",
39505de7e86SMax Reitz         },
39605de7e86SMax Reitz         {
397ee42b5ceSMax Reitz             .name = QCOW2_OPT_OVERLAP_TEMPLATE,
398ee42b5ceSMax Reitz             .type = QEMU_OPT_STRING,
399ee42b5ceSMax Reitz             .help = "Selects which overlap checks to perform from a range of "
400ee42b5ceSMax Reitz                     "templates (none, constant, cached, all)",
401ee42b5ceSMax Reitz         },
402ee42b5ceSMax Reitz         {
40305de7e86SMax Reitz             .name = QCOW2_OPT_OVERLAP_MAIN_HEADER,
40405de7e86SMax Reitz             .type = QEMU_OPT_BOOL,
40505de7e86SMax Reitz             .help = "Check for unintended writes into the main qcow2 header",
40605de7e86SMax Reitz         },
40705de7e86SMax Reitz         {
40805de7e86SMax Reitz             .name = QCOW2_OPT_OVERLAP_ACTIVE_L1,
40905de7e86SMax Reitz             .type = QEMU_OPT_BOOL,
41005de7e86SMax Reitz             .help = "Check for unintended writes into the active L1 table",
41105de7e86SMax Reitz         },
41205de7e86SMax Reitz         {
41305de7e86SMax Reitz             .name = QCOW2_OPT_OVERLAP_ACTIVE_L2,
41405de7e86SMax Reitz             .type = QEMU_OPT_BOOL,
41505de7e86SMax Reitz             .help = "Check for unintended writes into an active L2 table",
41605de7e86SMax Reitz         },
41705de7e86SMax Reitz         {
41805de7e86SMax Reitz             .name = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
41905de7e86SMax Reitz             .type = QEMU_OPT_BOOL,
42005de7e86SMax Reitz             .help = "Check for unintended writes into the refcount table",
42105de7e86SMax Reitz         },
42205de7e86SMax Reitz         {
42305de7e86SMax Reitz             .name = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
42405de7e86SMax Reitz             .type = QEMU_OPT_BOOL,
42505de7e86SMax Reitz             .help = "Check for unintended writes into a refcount block",
42605de7e86SMax Reitz         },
42705de7e86SMax Reitz         {
42805de7e86SMax Reitz             .name = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
42905de7e86SMax Reitz             .type = QEMU_OPT_BOOL,
43005de7e86SMax Reitz             .help = "Check for unintended writes into the snapshot table",
43105de7e86SMax Reitz         },
43205de7e86SMax Reitz         {
43305de7e86SMax Reitz             .name = QCOW2_OPT_OVERLAP_INACTIVE_L1,
43405de7e86SMax Reitz             .type = QEMU_OPT_BOOL,
43505de7e86SMax Reitz             .help = "Check for unintended writes into an inactive L1 table",
43605de7e86SMax Reitz         },
43705de7e86SMax Reitz         {
43805de7e86SMax Reitz             .name = QCOW2_OPT_OVERLAP_INACTIVE_L2,
43905de7e86SMax Reitz             .type = QEMU_OPT_BOOL,
44005de7e86SMax Reitz             .help = "Check for unintended writes into an inactive L2 table",
44105de7e86SMax Reitz         },
4426c1c8d5dSMax Reitz         {
4436c1c8d5dSMax Reitz             .name = QCOW2_OPT_CACHE_SIZE,
4446c1c8d5dSMax Reitz             .type = QEMU_OPT_SIZE,
4456c1c8d5dSMax Reitz             .help = "Maximum combined metadata (L2 tables and refcount blocks) "
4466c1c8d5dSMax Reitz                     "cache size",
4476c1c8d5dSMax Reitz         },
4486c1c8d5dSMax Reitz         {
4496c1c8d5dSMax Reitz             .name = QCOW2_OPT_L2_CACHE_SIZE,
4506c1c8d5dSMax Reitz             .type = QEMU_OPT_SIZE,
4516c1c8d5dSMax Reitz             .help = "Maximum L2 table cache size",
4526c1c8d5dSMax Reitz         },
4536c1c8d5dSMax Reitz         {
4546c1c8d5dSMax Reitz             .name = QCOW2_OPT_REFCOUNT_CACHE_SIZE,
4556c1c8d5dSMax Reitz             .type = QEMU_OPT_SIZE,
4566c1c8d5dSMax Reitz             .help = "Maximum refcount block cache size",
4576c1c8d5dSMax Reitz         },
458279621c0SAlberto Garcia         {
459279621c0SAlberto Garcia             .name = QCOW2_OPT_CACHE_CLEAN_INTERVAL,
460279621c0SAlberto Garcia             .type = QEMU_OPT_NUMBER,
461279621c0SAlberto Garcia             .help = "Clean unused cache entries after this time (in seconds)",
462279621c0SAlberto Garcia         },
46374c4510aSKevin Wolf         { /* end of list */ }
46474c4510aSKevin Wolf     },
46574c4510aSKevin Wolf };
46674c4510aSKevin Wolf 
4674092e99dSMax Reitz static const char *overlap_bool_option_names[QCOW2_OL_MAX_BITNR] = {
4684092e99dSMax Reitz     [QCOW2_OL_MAIN_HEADER_BITNR]    = QCOW2_OPT_OVERLAP_MAIN_HEADER,
4694092e99dSMax Reitz     [QCOW2_OL_ACTIVE_L1_BITNR]      = QCOW2_OPT_OVERLAP_ACTIVE_L1,
4704092e99dSMax Reitz     [QCOW2_OL_ACTIVE_L2_BITNR]      = QCOW2_OPT_OVERLAP_ACTIVE_L2,
4714092e99dSMax Reitz     [QCOW2_OL_REFCOUNT_TABLE_BITNR] = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
4724092e99dSMax Reitz     [QCOW2_OL_REFCOUNT_BLOCK_BITNR] = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
4734092e99dSMax Reitz     [QCOW2_OL_SNAPSHOT_TABLE_BITNR] = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
4744092e99dSMax Reitz     [QCOW2_OL_INACTIVE_L1_BITNR]    = QCOW2_OPT_OVERLAP_INACTIVE_L1,
4754092e99dSMax Reitz     [QCOW2_OL_INACTIVE_L2_BITNR]    = QCOW2_OPT_OVERLAP_INACTIVE_L2,
4764092e99dSMax Reitz };
4774092e99dSMax Reitz 
478279621c0SAlberto Garcia static void cache_clean_timer_cb(void *opaque)
479279621c0SAlberto Garcia {
480279621c0SAlberto Garcia     BlockDriverState *bs = opaque;
481ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
482279621c0SAlberto Garcia     qcow2_cache_clean_unused(bs, s->l2_table_cache);
483279621c0SAlberto Garcia     qcow2_cache_clean_unused(bs, s->refcount_block_cache);
484279621c0SAlberto Garcia     timer_mod(s->cache_clean_timer, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) +
485279621c0SAlberto Garcia               (int64_t) s->cache_clean_interval * 1000);
486279621c0SAlberto Garcia }
487279621c0SAlberto Garcia 
488279621c0SAlberto Garcia static void cache_clean_timer_init(BlockDriverState *bs, AioContext *context)
489279621c0SAlberto Garcia {
490ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
491279621c0SAlberto Garcia     if (s->cache_clean_interval > 0) {
492279621c0SAlberto Garcia         s->cache_clean_timer = aio_timer_new(context, QEMU_CLOCK_VIRTUAL,
493279621c0SAlberto Garcia                                              SCALE_MS, cache_clean_timer_cb,
494279621c0SAlberto Garcia                                              bs);
495279621c0SAlberto Garcia         timer_mod(s->cache_clean_timer, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) +
496279621c0SAlberto Garcia                   (int64_t) s->cache_clean_interval * 1000);
497279621c0SAlberto Garcia     }
498279621c0SAlberto Garcia }
499279621c0SAlberto Garcia 
500279621c0SAlberto Garcia static void cache_clean_timer_del(BlockDriverState *bs)
501279621c0SAlberto Garcia {
502ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
503279621c0SAlberto Garcia     if (s->cache_clean_timer) {
504279621c0SAlberto Garcia         timer_del(s->cache_clean_timer);
505279621c0SAlberto Garcia         timer_free(s->cache_clean_timer);
506279621c0SAlberto Garcia         s->cache_clean_timer = NULL;
507279621c0SAlberto Garcia     }
508279621c0SAlberto Garcia }
509279621c0SAlberto Garcia 
510279621c0SAlberto Garcia static void qcow2_detach_aio_context(BlockDriverState *bs)
511279621c0SAlberto Garcia {
512279621c0SAlberto Garcia     cache_clean_timer_del(bs);
513279621c0SAlberto Garcia }
514279621c0SAlberto Garcia 
515279621c0SAlberto Garcia static void qcow2_attach_aio_context(BlockDriverState *bs,
516279621c0SAlberto Garcia                                      AioContext *new_context)
517279621c0SAlberto Garcia {
518279621c0SAlberto Garcia     cache_clean_timer_init(bs, new_context);
519279621c0SAlberto Garcia }
520279621c0SAlberto Garcia 
521bc85ef26SMax Reitz static void read_cache_sizes(BlockDriverState *bs, QemuOpts *opts,
522bc85ef26SMax Reitz                              uint64_t *l2_cache_size,
5236c1c8d5dSMax Reitz                              uint64_t *refcount_cache_size, Error **errp)
5246c1c8d5dSMax Reitz {
525ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
5266c1c8d5dSMax Reitz     uint64_t combined_cache_size;
5276c1c8d5dSMax Reitz     bool l2_cache_size_set, refcount_cache_size_set, combined_cache_size_set;
5286c1c8d5dSMax Reitz 
5296c1c8d5dSMax Reitz     combined_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_CACHE_SIZE);
5306c1c8d5dSMax Reitz     l2_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_L2_CACHE_SIZE);
5316c1c8d5dSMax Reitz     refcount_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
5326c1c8d5dSMax Reitz 
5336c1c8d5dSMax Reitz     combined_cache_size = qemu_opt_get_size(opts, QCOW2_OPT_CACHE_SIZE, 0);
5346c1c8d5dSMax Reitz     *l2_cache_size = qemu_opt_get_size(opts, QCOW2_OPT_L2_CACHE_SIZE, 0);
5356c1c8d5dSMax Reitz     *refcount_cache_size = qemu_opt_get_size(opts,
5366c1c8d5dSMax Reitz                                              QCOW2_OPT_REFCOUNT_CACHE_SIZE, 0);
5376c1c8d5dSMax Reitz 
5386c1c8d5dSMax Reitz     if (combined_cache_size_set) {
5396c1c8d5dSMax Reitz         if (l2_cache_size_set && refcount_cache_size_set) {
5406c1c8d5dSMax Reitz             error_setg(errp, QCOW2_OPT_CACHE_SIZE ", " QCOW2_OPT_L2_CACHE_SIZE
5416c1c8d5dSMax Reitz                        " and " QCOW2_OPT_REFCOUNT_CACHE_SIZE " may not be set "
5426c1c8d5dSMax Reitz                        "the same time");
5436c1c8d5dSMax Reitz             return;
5446c1c8d5dSMax Reitz         } else if (*l2_cache_size > combined_cache_size) {
5456c1c8d5dSMax Reitz             error_setg(errp, QCOW2_OPT_L2_CACHE_SIZE " may not exceed "
5466c1c8d5dSMax Reitz                        QCOW2_OPT_CACHE_SIZE);
5476c1c8d5dSMax Reitz             return;
5486c1c8d5dSMax Reitz         } else if (*refcount_cache_size > combined_cache_size) {
5496c1c8d5dSMax Reitz             error_setg(errp, QCOW2_OPT_REFCOUNT_CACHE_SIZE " may not exceed "
5506c1c8d5dSMax Reitz                        QCOW2_OPT_CACHE_SIZE);
5516c1c8d5dSMax Reitz             return;
5526c1c8d5dSMax Reitz         }
5536c1c8d5dSMax Reitz 
5546c1c8d5dSMax Reitz         if (l2_cache_size_set) {
5556c1c8d5dSMax Reitz             *refcount_cache_size = combined_cache_size - *l2_cache_size;
5566c1c8d5dSMax Reitz         } else if (refcount_cache_size_set) {
5576c1c8d5dSMax Reitz             *l2_cache_size = combined_cache_size - *refcount_cache_size;
5586c1c8d5dSMax Reitz         } else {
5596c1c8d5dSMax Reitz             *refcount_cache_size = combined_cache_size
5606c1c8d5dSMax Reitz                                  / (DEFAULT_L2_REFCOUNT_SIZE_RATIO + 1);
5616c1c8d5dSMax Reitz             *l2_cache_size = combined_cache_size - *refcount_cache_size;
5626c1c8d5dSMax Reitz         }
5636c1c8d5dSMax Reitz     } else {
5646c1c8d5dSMax Reitz         if (!l2_cache_size_set && !refcount_cache_size_set) {
565bc85ef26SMax Reitz             *l2_cache_size = MAX(DEFAULT_L2_CACHE_BYTE_SIZE,
566bc85ef26SMax Reitz                                  (uint64_t)DEFAULT_L2_CACHE_CLUSTERS
567bc85ef26SMax Reitz                                  * s->cluster_size);
5686c1c8d5dSMax Reitz             *refcount_cache_size = *l2_cache_size
5696c1c8d5dSMax Reitz                                  / DEFAULT_L2_REFCOUNT_SIZE_RATIO;
5706c1c8d5dSMax Reitz         } else if (!l2_cache_size_set) {
5716c1c8d5dSMax Reitz             *l2_cache_size = *refcount_cache_size
5726c1c8d5dSMax Reitz                            * DEFAULT_L2_REFCOUNT_SIZE_RATIO;
5736c1c8d5dSMax Reitz         } else if (!refcount_cache_size_set) {
5746c1c8d5dSMax Reitz             *refcount_cache_size = *l2_cache_size
5756c1c8d5dSMax Reitz                                  / DEFAULT_L2_REFCOUNT_SIZE_RATIO;
5766c1c8d5dSMax Reitz         }
5776c1c8d5dSMax Reitz     }
5786c1c8d5dSMax Reitz }
5796c1c8d5dSMax Reitz 
580ee55b173SKevin Wolf typedef struct Qcow2ReopenState {
581ee55b173SKevin Wolf     Qcow2Cache *l2_table_cache;
582ee55b173SKevin Wolf     Qcow2Cache *refcount_block_cache;
583ee55b173SKevin Wolf     bool use_lazy_refcounts;
584ee55b173SKevin Wolf     int overlap_check;
585ee55b173SKevin Wolf     bool discard_passthrough[QCOW2_DISCARD_MAX];
586ee55b173SKevin Wolf     uint64_t cache_clean_interval;
587ee55b173SKevin Wolf } Qcow2ReopenState;
588ee55b173SKevin Wolf 
589ee55b173SKevin Wolf static int qcow2_update_options_prepare(BlockDriverState *bs,
590ee55b173SKevin Wolf                                         Qcow2ReopenState *r,
591ee55b173SKevin Wolf                                         QDict *options, int flags,
592ee55b173SKevin Wolf                                         Error **errp)
5934c75d1a1SKevin Wolf {
5944c75d1a1SKevin Wolf     BDRVQcow2State *s = bs->opaque;
59594edf3fbSKevin Wolf     QemuOpts *opts = NULL;
5964c75d1a1SKevin Wolf     const char *opt_overlap_check, *opt_overlap_check_template;
5974c75d1a1SKevin Wolf     int overlap_check_template = 0;
59894edf3fbSKevin Wolf     uint64_t l2_cache_size, refcount_cache_size;
5994c75d1a1SKevin Wolf     int i;
60094edf3fbSKevin Wolf     Error *local_err = NULL;
6014c75d1a1SKevin Wolf     int ret;
6024c75d1a1SKevin Wolf 
60394edf3fbSKevin Wolf     opts = qemu_opts_create(&qcow2_runtime_opts, NULL, 0, &error_abort);
60494edf3fbSKevin Wolf     qemu_opts_absorb_qdict(opts, options, &local_err);
60594edf3fbSKevin Wolf     if (local_err) {
60694edf3fbSKevin Wolf         error_propagate(errp, local_err);
60794edf3fbSKevin Wolf         ret = -EINVAL;
60894edf3fbSKevin Wolf         goto fail;
60994edf3fbSKevin Wolf     }
61094edf3fbSKevin Wolf 
61194edf3fbSKevin Wolf     /* get L2 table/refcount block cache size from command line options */
61294edf3fbSKevin Wolf     read_cache_sizes(bs, opts, &l2_cache_size, &refcount_cache_size,
61394edf3fbSKevin Wolf                      &local_err);
61494edf3fbSKevin Wolf     if (local_err) {
61594edf3fbSKevin Wolf         error_propagate(errp, local_err);
61694edf3fbSKevin Wolf         ret = -EINVAL;
61794edf3fbSKevin Wolf         goto fail;
61894edf3fbSKevin Wolf     }
61994edf3fbSKevin Wolf 
62094edf3fbSKevin Wolf     l2_cache_size /= s->cluster_size;
62194edf3fbSKevin Wolf     if (l2_cache_size < MIN_L2_CACHE_SIZE) {
62294edf3fbSKevin Wolf         l2_cache_size = MIN_L2_CACHE_SIZE;
62394edf3fbSKevin Wolf     }
62494edf3fbSKevin Wolf     if (l2_cache_size > INT_MAX) {
62594edf3fbSKevin Wolf         error_setg(errp, "L2 cache size too big");
62694edf3fbSKevin Wolf         ret = -EINVAL;
62794edf3fbSKevin Wolf         goto fail;
62894edf3fbSKevin Wolf     }
62994edf3fbSKevin Wolf 
63094edf3fbSKevin Wolf     refcount_cache_size /= s->cluster_size;
63194edf3fbSKevin Wolf     if (refcount_cache_size < MIN_REFCOUNT_CACHE_SIZE) {
63294edf3fbSKevin Wolf         refcount_cache_size = MIN_REFCOUNT_CACHE_SIZE;
63394edf3fbSKevin Wolf     }
63494edf3fbSKevin Wolf     if (refcount_cache_size > INT_MAX) {
63594edf3fbSKevin Wolf         error_setg(errp, "Refcount cache size too big");
63694edf3fbSKevin Wolf         ret = -EINVAL;
63794edf3fbSKevin Wolf         goto fail;
63894edf3fbSKevin Wolf     }
63994edf3fbSKevin Wolf 
6405b0959a7SKevin Wolf     /* alloc new L2 table/refcount block cache, flush old one */
6415b0959a7SKevin Wolf     if (s->l2_table_cache) {
6425b0959a7SKevin Wolf         ret = qcow2_cache_flush(bs, s->l2_table_cache);
6435b0959a7SKevin Wolf         if (ret) {
6445b0959a7SKevin Wolf             error_setg_errno(errp, -ret, "Failed to flush the L2 table cache");
6455b0959a7SKevin Wolf             goto fail;
6465b0959a7SKevin Wolf         }
6475b0959a7SKevin Wolf     }
6485b0959a7SKevin Wolf 
6495b0959a7SKevin Wolf     if (s->refcount_block_cache) {
6505b0959a7SKevin Wolf         ret = qcow2_cache_flush(bs, s->refcount_block_cache);
6515b0959a7SKevin Wolf         if (ret) {
6525b0959a7SKevin Wolf             error_setg_errno(errp, -ret,
6535b0959a7SKevin Wolf                              "Failed to flush the refcount block cache");
6545b0959a7SKevin Wolf             goto fail;
6555b0959a7SKevin Wolf         }
6565b0959a7SKevin Wolf     }
6575b0959a7SKevin Wolf 
658ee55b173SKevin Wolf     r->l2_table_cache = qcow2_cache_create(bs, l2_cache_size);
659ee55b173SKevin Wolf     r->refcount_block_cache = qcow2_cache_create(bs, refcount_cache_size);
660ee55b173SKevin Wolf     if (r->l2_table_cache == NULL || r->refcount_block_cache == NULL) {
66194edf3fbSKevin Wolf         error_setg(errp, "Could not allocate metadata caches");
66294edf3fbSKevin Wolf         ret = -ENOMEM;
66394edf3fbSKevin Wolf         goto fail;
66494edf3fbSKevin Wolf     }
66594edf3fbSKevin Wolf 
66694edf3fbSKevin Wolf     /* New interval for cache cleanup timer */
667ee55b173SKevin Wolf     r->cache_clean_interval =
6685b0959a7SKevin Wolf         qemu_opt_get_number(opts, QCOW2_OPT_CACHE_CLEAN_INTERVAL,
6695b0959a7SKevin Wolf                             s->cache_clean_interval);
670ee55b173SKevin Wolf     if (r->cache_clean_interval > UINT_MAX) {
67194edf3fbSKevin Wolf         error_setg(errp, "Cache clean interval too big");
67294edf3fbSKevin Wolf         ret = -EINVAL;
67394edf3fbSKevin Wolf         goto fail;
67494edf3fbSKevin Wolf     }
67594edf3fbSKevin Wolf 
6765b0959a7SKevin Wolf     /* lazy-refcounts; flush if going from enabled to disabled */
677ee55b173SKevin Wolf     r->use_lazy_refcounts = qemu_opt_get_bool(opts, QCOW2_OPT_LAZY_REFCOUNTS,
6784c75d1a1SKevin Wolf         (s->compatible_features & QCOW2_COMPAT_LAZY_REFCOUNTS));
679ee55b173SKevin Wolf     if (r->use_lazy_refcounts && s->qcow_version < 3) {
680007dbc39SKevin Wolf         error_setg(errp, "Lazy refcounts require a qcow2 image with at least "
681007dbc39SKevin Wolf                    "qemu 1.1 compatibility level");
682007dbc39SKevin Wolf         ret = -EINVAL;
683007dbc39SKevin Wolf         goto fail;
684007dbc39SKevin Wolf     }
6854c75d1a1SKevin Wolf 
6865b0959a7SKevin Wolf     if (s->use_lazy_refcounts && !r->use_lazy_refcounts) {
6875b0959a7SKevin Wolf         ret = qcow2_mark_clean(bs);
6885b0959a7SKevin Wolf         if (ret < 0) {
6895b0959a7SKevin Wolf             error_setg_errno(errp, -ret, "Failed to disable lazy refcounts");
6905b0959a7SKevin Wolf             goto fail;
6915b0959a7SKevin Wolf         }
6925b0959a7SKevin Wolf     }
6935b0959a7SKevin Wolf 
694007dbc39SKevin Wolf     /* Overlap check options */
6954c75d1a1SKevin Wolf     opt_overlap_check = qemu_opt_get(opts, QCOW2_OPT_OVERLAP);
6964c75d1a1SKevin Wolf     opt_overlap_check_template = qemu_opt_get(opts, QCOW2_OPT_OVERLAP_TEMPLATE);
6974c75d1a1SKevin Wolf     if (opt_overlap_check_template && opt_overlap_check &&
6984c75d1a1SKevin Wolf         strcmp(opt_overlap_check_template, opt_overlap_check))
6994c75d1a1SKevin Wolf     {
7004c75d1a1SKevin Wolf         error_setg(errp, "Conflicting values for qcow2 options '"
7014c75d1a1SKevin Wolf                    QCOW2_OPT_OVERLAP "' ('%s') and '" QCOW2_OPT_OVERLAP_TEMPLATE
7024c75d1a1SKevin Wolf                    "' ('%s')", opt_overlap_check, opt_overlap_check_template);
7034c75d1a1SKevin Wolf         ret = -EINVAL;
7044c75d1a1SKevin Wolf         goto fail;
7054c75d1a1SKevin Wolf     }
7064c75d1a1SKevin Wolf     if (!opt_overlap_check) {
7074c75d1a1SKevin Wolf         opt_overlap_check = opt_overlap_check_template ?: "cached";
7084c75d1a1SKevin Wolf     }
7094c75d1a1SKevin Wolf 
7104c75d1a1SKevin Wolf     if (!strcmp(opt_overlap_check, "none")) {
7114c75d1a1SKevin Wolf         overlap_check_template = 0;
7124c75d1a1SKevin Wolf     } else if (!strcmp(opt_overlap_check, "constant")) {
7134c75d1a1SKevin Wolf         overlap_check_template = QCOW2_OL_CONSTANT;
7144c75d1a1SKevin Wolf     } else if (!strcmp(opt_overlap_check, "cached")) {
7154c75d1a1SKevin Wolf         overlap_check_template = QCOW2_OL_CACHED;
7164c75d1a1SKevin Wolf     } else if (!strcmp(opt_overlap_check, "all")) {
7174c75d1a1SKevin Wolf         overlap_check_template = QCOW2_OL_ALL;
7184c75d1a1SKevin Wolf     } else {
7194c75d1a1SKevin Wolf         error_setg(errp, "Unsupported value '%s' for qcow2 option "
7204c75d1a1SKevin Wolf                    "'overlap-check'. Allowed are any of the following: "
7214c75d1a1SKevin Wolf                    "none, constant, cached, all", opt_overlap_check);
7224c75d1a1SKevin Wolf         ret = -EINVAL;
7234c75d1a1SKevin Wolf         goto fail;
7244c75d1a1SKevin Wolf     }
7254c75d1a1SKevin Wolf 
726ee55b173SKevin Wolf     r->overlap_check = 0;
7274c75d1a1SKevin Wolf     for (i = 0; i < QCOW2_OL_MAX_BITNR; i++) {
7284c75d1a1SKevin Wolf         /* overlap-check defines a template bitmask, but every flag may be
7294c75d1a1SKevin Wolf          * overwritten through the associated boolean option */
730ee55b173SKevin Wolf         r->overlap_check |=
7314c75d1a1SKevin Wolf             qemu_opt_get_bool(opts, overlap_bool_option_names[i],
7324c75d1a1SKevin Wolf                               overlap_check_template & (1 << i)) << i;
7334c75d1a1SKevin Wolf     }
7344c75d1a1SKevin Wolf 
735ee55b173SKevin Wolf     r->discard_passthrough[QCOW2_DISCARD_NEVER] = false;
736ee55b173SKevin Wolf     r->discard_passthrough[QCOW2_DISCARD_ALWAYS] = true;
737ee55b173SKevin Wolf     r->discard_passthrough[QCOW2_DISCARD_REQUEST] =
738007dbc39SKevin Wolf         qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_REQUEST,
739007dbc39SKevin Wolf                           flags & BDRV_O_UNMAP);
740ee55b173SKevin Wolf     r->discard_passthrough[QCOW2_DISCARD_SNAPSHOT] =
741007dbc39SKevin Wolf         qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_SNAPSHOT, true);
742ee55b173SKevin Wolf     r->discard_passthrough[QCOW2_DISCARD_OTHER] =
743007dbc39SKevin Wolf         qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_OTHER, false);
744007dbc39SKevin Wolf 
7454c75d1a1SKevin Wolf     ret = 0;
7464c75d1a1SKevin Wolf fail:
74794edf3fbSKevin Wolf     qemu_opts_del(opts);
74894edf3fbSKevin Wolf     opts = NULL;
749ee55b173SKevin Wolf     return ret;
750ee55b173SKevin Wolf }
751ee55b173SKevin Wolf 
752ee55b173SKevin Wolf static void qcow2_update_options_commit(BlockDriverState *bs,
753ee55b173SKevin Wolf                                         Qcow2ReopenState *r)
754ee55b173SKevin Wolf {
755ee55b173SKevin Wolf     BDRVQcow2State *s = bs->opaque;
756ee55b173SKevin Wolf     int i;
757ee55b173SKevin Wolf 
7585b0959a7SKevin Wolf     if (s->l2_table_cache) {
7595b0959a7SKevin Wolf         qcow2_cache_destroy(bs, s->l2_table_cache);
7605b0959a7SKevin Wolf     }
7615b0959a7SKevin Wolf     if (s->refcount_block_cache) {
7625b0959a7SKevin Wolf         qcow2_cache_destroy(bs, s->refcount_block_cache);
7635b0959a7SKevin Wolf     }
764ee55b173SKevin Wolf     s->l2_table_cache = r->l2_table_cache;
765ee55b173SKevin Wolf     s->refcount_block_cache = r->refcount_block_cache;
766ee55b173SKevin Wolf 
767ee55b173SKevin Wolf     s->overlap_check = r->overlap_check;
768ee55b173SKevin Wolf     s->use_lazy_refcounts = r->use_lazy_refcounts;
769ee55b173SKevin Wolf 
770ee55b173SKevin Wolf     for (i = 0; i < QCOW2_DISCARD_MAX; i++) {
771ee55b173SKevin Wolf         s->discard_passthrough[i] = r->discard_passthrough[i];
772ee55b173SKevin Wolf     }
773ee55b173SKevin Wolf 
7745b0959a7SKevin Wolf     if (s->cache_clean_interval != r->cache_clean_interval) {
7755b0959a7SKevin Wolf         cache_clean_timer_del(bs);
776ee55b173SKevin Wolf         s->cache_clean_interval = r->cache_clean_interval;
777ee55b173SKevin Wolf         cache_clean_timer_init(bs, bdrv_get_aio_context(bs));
778ee55b173SKevin Wolf     }
7795b0959a7SKevin Wolf }
780ee55b173SKevin Wolf 
781ee55b173SKevin Wolf static void qcow2_update_options_abort(BlockDriverState *bs,
782ee55b173SKevin Wolf                                        Qcow2ReopenState *r)
783ee55b173SKevin Wolf {
784ee55b173SKevin Wolf     if (r->l2_table_cache) {
785ee55b173SKevin Wolf         qcow2_cache_destroy(bs, r->l2_table_cache);
786ee55b173SKevin Wolf     }
787ee55b173SKevin Wolf     if (r->refcount_block_cache) {
788ee55b173SKevin Wolf         qcow2_cache_destroy(bs, r->refcount_block_cache);
789ee55b173SKevin Wolf     }
790ee55b173SKevin Wolf }
791ee55b173SKevin Wolf 
792ee55b173SKevin Wolf static int qcow2_update_options(BlockDriverState *bs, QDict *options,
793ee55b173SKevin Wolf                                 int flags, Error **errp)
794ee55b173SKevin Wolf {
795ee55b173SKevin Wolf     Qcow2ReopenState r = {};
796ee55b173SKevin Wolf     int ret;
797ee55b173SKevin Wolf 
798ee55b173SKevin Wolf     ret = qcow2_update_options_prepare(bs, &r, options, flags, errp);
799ee55b173SKevin Wolf     if (ret >= 0) {
800ee55b173SKevin Wolf         qcow2_update_options_commit(bs, &r);
801ee55b173SKevin Wolf     } else {
802ee55b173SKevin Wolf         qcow2_update_options_abort(bs, &r);
803ee55b173SKevin Wolf     }
80494edf3fbSKevin Wolf 
8054c75d1a1SKevin Wolf     return ret;
8064c75d1a1SKevin Wolf }
8074c75d1a1SKevin Wolf 
808015a1036SMax Reitz static int qcow2_open(BlockDriverState *bs, QDict *options, int flags,
809015a1036SMax Reitz                       Error **errp)
810585f8587Sbellard {
811ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
8126d33e8e7SKevin Wolf     unsigned int len, i;
8136d33e8e7SKevin Wolf     int ret = 0;
814585f8587Sbellard     QCowHeader header;
81574c4510aSKevin Wolf     Error *local_err = NULL;
8169b80ddf3Saliguori     uint64_t ext_end;
8172cf7cfa1SKevin Wolf     uint64_t l1_vm_state_index;
818585f8587Sbellard 
8199a4f4c31SKevin Wolf     ret = bdrv_pread(bs->file->bs, 0, &header, sizeof(header));
8206d85a57eSJes Sorensen     if (ret < 0) {
8213ef6c40aSMax Reitz         error_setg_errno(errp, -ret, "Could not read qcow2 header");
822585f8587Sbellard         goto fail;
8236d85a57eSJes Sorensen     }
824585f8587Sbellard     be32_to_cpus(&header.magic);
825585f8587Sbellard     be32_to_cpus(&header.version);
826585f8587Sbellard     be64_to_cpus(&header.backing_file_offset);
827585f8587Sbellard     be32_to_cpus(&header.backing_file_size);
828585f8587Sbellard     be64_to_cpus(&header.size);
829585f8587Sbellard     be32_to_cpus(&header.cluster_bits);
830585f8587Sbellard     be32_to_cpus(&header.crypt_method);
831585f8587Sbellard     be64_to_cpus(&header.l1_table_offset);
832585f8587Sbellard     be32_to_cpus(&header.l1_size);
833585f8587Sbellard     be64_to_cpus(&header.refcount_table_offset);
834585f8587Sbellard     be32_to_cpus(&header.refcount_table_clusters);
835585f8587Sbellard     be64_to_cpus(&header.snapshots_offset);
836585f8587Sbellard     be32_to_cpus(&header.nb_snapshots);
837585f8587Sbellard 
838e8cdcec1SKevin Wolf     if (header.magic != QCOW_MAGIC) {
8393ef6c40aSMax Reitz         error_setg(errp, "Image is not in qcow2 format");
84076abe407SPaolo Bonzini         ret = -EINVAL;
841585f8587Sbellard         goto fail;
8426d85a57eSJes Sorensen     }
8436744cbabSKevin Wolf     if (header.version < 2 || header.version > 3) {
844a55448b3SMax Reitz         error_setg(errp, "Unsupported qcow2 version %" PRIu32, header.version);
845e8cdcec1SKevin Wolf         ret = -ENOTSUP;
846e8cdcec1SKevin Wolf         goto fail;
847e8cdcec1SKevin Wolf     }
8486744cbabSKevin Wolf 
8496744cbabSKevin Wolf     s->qcow_version = header.version;
8506744cbabSKevin Wolf 
85124342f2cSKevin Wolf     /* Initialise cluster size */
85224342f2cSKevin Wolf     if (header.cluster_bits < MIN_CLUSTER_BITS ||
85324342f2cSKevin Wolf         header.cluster_bits > MAX_CLUSTER_BITS) {
854521b2b5dSMax Reitz         error_setg(errp, "Unsupported cluster size: 2^%" PRIu32,
855521b2b5dSMax Reitz                    header.cluster_bits);
85624342f2cSKevin Wolf         ret = -EINVAL;
85724342f2cSKevin Wolf         goto fail;
85824342f2cSKevin Wolf     }
85924342f2cSKevin Wolf 
86024342f2cSKevin Wolf     s->cluster_bits = header.cluster_bits;
86124342f2cSKevin Wolf     s->cluster_size = 1 << s->cluster_bits;
86224342f2cSKevin Wolf     s->cluster_sectors = 1 << (s->cluster_bits - 9);
86324342f2cSKevin Wolf 
8646744cbabSKevin Wolf     /* Initialise version 3 header fields */
8656744cbabSKevin Wolf     if (header.version == 2) {
8666744cbabSKevin Wolf         header.incompatible_features    = 0;
8676744cbabSKevin Wolf         header.compatible_features      = 0;
8686744cbabSKevin Wolf         header.autoclear_features       = 0;
8696744cbabSKevin Wolf         header.refcount_order           = 4;
8706744cbabSKevin Wolf         header.header_length            = 72;
8716744cbabSKevin Wolf     } else {
8726744cbabSKevin Wolf         be64_to_cpus(&header.incompatible_features);
8736744cbabSKevin Wolf         be64_to_cpus(&header.compatible_features);
8746744cbabSKevin Wolf         be64_to_cpus(&header.autoclear_features);
8756744cbabSKevin Wolf         be32_to_cpus(&header.refcount_order);
8766744cbabSKevin Wolf         be32_to_cpus(&header.header_length);
87724342f2cSKevin Wolf 
87824342f2cSKevin Wolf         if (header.header_length < 104) {
87924342f2cSKevin Wolf             error_setg(errp, "qcow2 header too short");
88024342f2cSKevin Wolf             ret = -EINVAL;
88124342f2cSKevin Wolf             goto fail;
88224342f2cSKevin Wolf         }
88324342f2cSKevin Wolf     }
88424342f2cSKevin Wolf 
88524342f2cSKevin Wolf     if (header.header_length > s->cluster_size) {
88624342f2cSKevin Wolf         error_setg(errp, "qcow2 header exceeds cluster size");
88724342f2cSKevin Wolf         ret = -EINVAL;
88824342f2cSKevin Wolf         goto fail;
8896744cbabSKevin Wolf     }
8906744cbabSKevin Wolf 
8916744cbabSKevin Wolf     if (header.header_length > sizeof(header)) {
8926744cbabSKevin Wolf         s->unknown_header_fields_size = header.header_length - sizeof(header);
8936744cbabSKevin Wolf         s->unknown_header_fields = g_malloc(s->unknown_header_fields_size);
8949a4f4c31SKevin Wolf         ret = bdrv_pread(bs->file->bs, sizeof(header), s->unknown_header_fields,
8956744cbabSKevin Wolf                          s->unknown_header_fields_size);
8966744cbabSKevin Wolf         if (ret < 0) {
8973ef6c40aSMax Reitz             error_setg_errno(errp, -ret, "Could not read unknown qcow2 header "
8983ef6c40aSMax Reitz                              "fields");
8996744cbabSKevin Wolf             goto fail;
9006744cbabSKevin Wolf         }
9016744cbabSKevin Wolf     }
9026744cbabSKevin Wolf 
903a1b3955cSKevin Wolf     if (header.backing_file_offset > s->cluster_size) {
904a1b3955cSKevin Wolf         error_setg(errp, "Invalid backing file offset");
905a1b3955cSKevin Wolf         ret = -EINVAL;
906a1b3955cSKevin Wolf         goto fail;
907a1b3955cSKevin Wolf     }
908a1b3955cSKevin Wolf 
909cfcc4c62SKevin Wolf     if (header.backing_file_offset) {
910cfcc4c62SKevin Wolf         ext_end = header.backing_file_offset;
911cfcc4c62SKevin Wolf     } else {
912cfcc4c62SKevin Wolf         ext_end = 1 << header.cluster_bits;
913cfcc4c62SKevin Wolf     }
914cfcc4c62SKevin Wolf 
9156744cbabSKevin Wolf     /* Handle feature bits */
9166744cbabSKevin Wolf     s->incompatible_features    = header.incompatible_features;
9176744cbabSKevin Wolf     s->compatible_features      = header.compatible_features;
9186744cbabSKevin Wolf     s->autoclear_features       = header.autoclear_features;
9196744cbabSKevin Wolf 
920c61d0004SStefan Hajnoczi     if (s->incompatible_features & ~QCOW2_INCOMPAT_MASK) {
921cfcc4c62SKevin Wolf         void *feature_table = NULL;
922cfcc4c62SKevin Wolf         qcow2_read_extensions(bs, header.header_length, ext_end,
9233ef6c40aSMax Reitz                               &feature_table, NULL);
924a55448b3SMax Reitz         report_unsupported_feature(errp, feature_table,
925c61d0004SStefan Hajnoczi                                    s->incompatible_features &
926c61d0004SStefan Hajnoczi                                    ~QCOW2_INCOMPAT_MASK);
9276744cbabSKevin Wolf         ret = -ENOTSUP;
928c5a33ee9SPrasad Joshi         g_free(feature_table);
9296744cbabSKevin Wolf         goto fail;
9306744cbabSKevin Wolf     }
9316744cbabSKevin Wolf 
93269c98726SMax Reitz     if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
93369c98726SMax Reitz         /* Corrupt images may not be written to unless they are being repaired
93469c98726SMax Reitz          */
93569c98726SMax Reitz         if ((flags & BDRV_O_RDWR) && !(flags & BDRV_O_CHECK)) {
9363ef6c40aSMax Reitz             error_setg(errp, "qcow2: Image is corrupt; cannot be opened "
9373ef6c40aSMax Reitz                        "read/write");
93869c98726SMax Reitz             ret = -EACCES;
93969c98726SMax Reitz             goto fail;
94069c98726SMax Reitz         }
94169c98726SMax Reitz     }
94269c98726SMax Reitz 
9436744cbabSKevin Wolf     /* Check support for various header values */
944b72faf9fSMax Reitz     if (header.refcount_order > 6) {
945b72faf9fSMax Reitz         error_setg(errp, "Reference count entry width too large; may not "
946b72faf9fSMax Reitz                    "exceed 64 bits");
947b72faf9fSMax Reitz         ret = -EINVAL;
9486744cbabSKevin Wolf         goto fail;
9496744cbabSKevin Wolf     }
950b6481f37SMax Reitz     s->refcount_order = header.refcount_order;
951346a53dfSMax Reitz     s->refcount_bits = 1 << s->refcount_order;
952346a53dfSMax Reitz     s->refcount_max = UINT64_C(1) << (s->refcount_bits - 1);
953346a53dfSMax Reitz     s->refcount_max += s->refcount_max - 1;
9546744cbabSKevin Wolf 
9556d85a57eSJes Sorensen     if (header.crypt_method > QCOW_CRYPT_AES) {
956521b2b5dSMax Reitz         error_setg(errp, "Unsupported encryption method: %" PRIu32,
9573ef6c40aSMax Reitz                    header.crypt_method);
9586d85a57eSJes Sorensen         ret = -EINVAL;
959585f8587Sbellard         goto fail;
9606d85a57eSJes Sorensen     }
961f6fa64f6SDaniel P. Berrange     if (!qcrypto_cipher_supports(QCRYPTO_CIPHER_ALG_AES_128)) {
962f6fa64f6SDaniel P. Berrange         error_setg(errp, "AES cipher not available");
963f6fa64f6SDaniel P. Berrange         ret = -EINVAL;
964f6fa64f6SDaniel P. Berrange         goto fail;
965f6fa64f6SDaniel P. Berrange     }
966585f8587Sbellard     s->crypt_method_header = header.crypt_method;
9676d85a57eSJes Sorensen     if (s->crypt_method_header) {
968585f8587Sbellard         bs->encrypted = 1;
9696d85a57eSJes Sorensen     }
97024342f2cSKevin Wolf 
971585f8587Sbellard     s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */
972585f8587Sbellard     s->l2_size = 1 << s->l2_bits;
9731d13d654SMax Reitz     /* 2^(s->refcount_order - 3) is the refcount width in bytes */
9741d13d654SMax Reitz     s->refcount_block_bits = s->cluster_bits - (s->refcount_order - 3);
9751d13d654SMax Reitz     s->refcount_block_size = 1 << s->refcount_block_bits;
976585f8587Sbellard     bs->total_sectors = header.size / 512;
977585f8587Sbellard     s->csize_shift = (62 - (s->cluster_bits - 8));
978585f8587Sbellard     s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;
979585f8587Sbellard     s->cluster_offset_mask = (1LL << s->csize_shift) - 1;
9805dab2fadSKevin Wolf 
981585f8587Sbellard     s->refcount_table_offset = header.refcount_table_offset;
982585f8587Sbellard     s->refcount_table_size =
983585f8587Sbellard         header.refcount_table_clusters << (s->cluster_bits - 3);
984585f8587Sbellard 
9852b5d5953SKevin Wolf     if (header.refcount_table_clusters > qcow2_max_refcount_clusters(s)) {
9865dab2fadSKevin Wolf         error_setg(errp, "Reference count table too large");
9875dab2fadSKevin Wolf         ret = -EINVAL;
9885dab2fadSKevin Wolf         goto fail;
9895dab2fadSKevin Wolf     }
9905dab2fadSKevin Wolf 
9918c7de283SKevin Wolf     ret = validate_table_offset(bs, s->refcount_table_offset,
9928c7de283SKevin Wolf                                 s->refcount_table_size, sizeof(uint64_t));
9938c7de283SKevin Wolf     if (ret < 0) {
9948c7de283SKevin Wolf         error_setg(errp, "Invalid reference count table offset");
9958c7de283SKevin Wolf         goto fail;
9968c7de283SKevin Wolf     }
9978c7de283SKevin Wolf 
998ce48f2f4SKevin Wolf     /* Snapshot table offset/length */
999ce48f2f4SKevin Wolf     if (header.nb_snapshots > QCOW_MAX_SNAPSHOTS) {
1000ce48f2f4SKevin Wolf         error_setg(errp, "Too many snapshots");
1001ce48f2f4SKevin Wolf         ret = -EINVAL;
1002ce48f2f4SKevin Wolf         goto fail;
1003ce48f2f4SKevin Wolf     }
1004ce48f2f4SKevin Wolf 
1005ce48f2f4SKevin Wolf     ret = validate_table_offset(bs, header.snapshots_offset,
1006ce48f2f4SKevin Wolf                                 header.nb_snapshots,
1007ce48f2f4SKevin Wolf                                 sizeof(QCowSnapshotHeader));
1008ce48f2f4SKevin Wolf     if (ret < 0) {
1009ce48f2f4SKevin Wolf         error_setg(errp, "Invalid snapshot table offset");
1010ce48f2f4SKevin Wolf         goto fail;
1011ce48f2f4SKevin Wolf     }
1012ce48f2f4SKevin Wolf 
1013585f8587Sbellard     /* read the level 1 table */
101487b86e7eSWen Congyang     if (header.l1_size > QCOW_MAX_L1_SIZE / sizeof(uint64_t)) {
10152d51c32cSKevin Wolf         error_setg(errp, "Active L1 table too large");
10162d51c32cSKevin Wolf         ret = -EFBIG;
10172d51c32cSKevin Wolf         goto fail;
10182d51c32cSKevin Wolf     }
1019585f8587Sbellard     s->l1_size = header.l1_size;
10202cf7cfa1SKevin Wolf 
10212cf7cfa1SKevin Wolf     l1_vm_state_index = size_to_l1(s, header.size);
10222cf7cfa1SKevin Wolf     if (l1_vm_state_index > INT_MAX) {
10233ef6c40aSMax Reitz         error_setg(errp, "Image is too big");
10242cf7cfa1SKevin Wolf         ret = -EFBIG;
10252cf7cfa1SKevin Wolf         goto fail;
10262cf7cfa1SKevin Wolf     }
10272cf7cfa1SKevin Wolf     s->l1_vm_state_index = l1_vm_state_index;
10282cf7cfa1SKevin Wolf 
1029585f8587Sbellard     /* the L1 table must contain at least enough entries to put
1030585f8587Sbellard        header.size bytes */
10316d85a57eSJes Sorensen     if (s->l1_size < s->l1_vm_state_index) {
10323ef6c40aSMax Reitz         error_setg(errp, "L1 table is too small");
10336d85a57eSJes Sorensen         ret = -EINVAL;
1034585f8587Sbellard         goto fail;
10356d85a57eSJes Sorensen     }
10362d51c32cSKevin Wolf 
10372d51c32cSKevin Wolf     ret = validate_table_offset(bs, header.l1_table_offset,
10382d51c32cSKevin Wolf                                 header.l1_size, sizeof(uint64_t));
10392d51c32cSKevin Wolf     if (ret < 0) {
10402d51c32cSKevin Wolf         error_setg(errp, "Invalid L1 table offset");
10412d51c32cSKevin Wolf         goto fail;
10422d51c32cSKevin Wolf     }
1043585f8587Sbellard     s->l1_table_offset = header.l1_table_offset;
10442d51c32cSKevin Wolf 
10452d51c32cSKevin Wolf 
1046d191d12dSStefan Weil     if (s->l1_size > 0) {
10479a4f4c31SKevin Wolf         s->l1_table = qemu_try_blockalign(bs->file->bs,
10483f6a3ee5SKevin Wolf             align_offset(s->l1_size * sizeof(uint64_t), 512));
1049de82815dSKevin Wolf         if (s->l1_table == NULL) {
1050de82815dSKevin Wolf             error_setg(errp, "Could not allocate L1 table");
1051de82815dSKevin Wolf             ret = -ENOMEM;
1052de82815dSKevin Wolf             goto fail;
1053de82815dSKevin Wolf         }
10549a4f4c31SKevin Wolf         ret = bdrv_pread(bs->file->bs, s->l1_table_offset, s->l1_table,
10556d85a57eSJes Sorensen                          s->l1_size * sizeof(uint64_t));
10566d85a57eSJes Sorensen         if (ret < 0) {
10573ef6c40aSMax Reitz             error_setg_errno(errp, -ret, "Could not read L1 table");
1058585f8587Sbellard             goto fail;
10596d85a57eSJes Sorensen         }
1060585f8587Sbellard         for(i = 0;i < s->l1_size; i++) {
1061585f8587Sbellard             be64_to_cpus(&s->l1_table[i]);
1062585f8587Sbellard         }
1063d191d12dSStefan Weil     }
106429c1a730SKevin Wolf 
106594edf3fbSKevin Wolf     /* Parse driver-specific options */
106694edf3fbSKevin Wolf     ret = qcow2_update_options(bs, options, flags, errp);
106790efa0eaSKevin Wolf     if (ret < 0) {
106890efa0eaSKevin Wolf         goto fail;
106990efa0eaSKevin Wolf     }
107090efa0eaSKevin Wolf 
10717267c094SAnthony Liguori     s->cluster_cache = g_malloc(s->cluster_size);
1072585f8587Sbellard     /* one more sector for decompressed data alignment */
10739a4f4c31SKevin Wolf     s->cluster_data = qemu_try_blockalign(bs->file->bs, QCOW_MAX_CRYPT_CLUSTERS
1074de82815dSKevin Wolf                                                     * s->cluster_size + 512);
1075de82815dSKevin Wolf     if (s->cluster_data == NULL) {
1076de82815dSKevin Wolf         error_setg(errp, "Could not allocate temporary cluster buffer");
1077de82815dSKevin Wolf         ret = -ENOMEM;
1078de82815dSKevin Wolf         goto fail;
1079de82815dSKevin Wolf     }
1080de82815dSKevin Wolf 
1081585f8587Sbellard     s->cluster_cache_offset = -1;
108206d9260fSAnthony Liguori     s->flags = flags;
1083585f8587Sbellard 
10846d85a57eSJes Sorensen     ret = qcow2_refcount_init(bs);
10856d85a57eSJes Sorensen     if (ret != 0) {
10863ef6c40aSMax Reitz         error_setg_errno(errp, -ret, "Could not initialize refcount handling");
1087585f8587Sbellard         goto fail;
10886d85a57eSJes Sorensen     }
1089585f8587Sbellard 
109072cf2d4fSBlue Swirl     QLIST_INIT(&s->cluster_allocs);
10910b919faeSKevin Wolf     QTAILQ_INIT(&s->discards);
1092f214978aSKevin Wolf 
10939b80ddf3Saliguori     /* read qcow2 extensions */
10943ef6c40aSMax Reitz     if (qcow2_read_extensions(bs, header.header_length, ext_end, NULL,
10953ef6c40aSMax Reitz         &local_err)) {
10963ef6c40aSMax Reitz         error_propagate(errp, local_err);
10976d85a57eSJes Sorensen         ret = -EINVAL;
10989b80ddf3Saliguori         goto fail;
10996d85a57eSJes Sorensen     }
11009b80ddf3Saliguori 
1101585f8587Sbellard     /* read the backing file name */
1102585f8587Sbellard     if (header.backing_file_offset != 0) {
1103585f8587Sbellard         len = header.backing_file_size;
11049a29e18fSJeff Cody         if (len > MIN(1023, s->cluster_size - header.backing_file_offset) ||
1105e729fa6aSJeff Cody             len >= sizeof(bs->backing_file)) {
11066d33e8e7SKevin Wolf             error_setg(errp, "Backing file name too long");
11076d33e8e7SKevin Wolf             ret = -EINVAL;
11086d33e8e7SKevin Wolf             goto fail;
11096d85a57eSJes Sorensen         }
11109a4f4c31SKevin Wolf         ret = bdrv_pread(bs->file->bs, header.backing_file_offset,
11116d85a57eSJes Sorensen                          bs->backing_file, len);
11126d85a57eSJes Sorensen         if (ret < 0) {
11133ef6c40aSMax Reitz             error_setg_errno(errp, -ret, "Could not read backing file name");
1114585f8587Sbellard             goto fail;
11156d85a57eSJes Sorensen         }
1116585f8587Sbellard         bs->backing_file[len] = '\0';
1117e4603fe1SKevin Wolf         s->image_backing_file = g_strdup(bs->backing_file);
1118585f8587Sbellard     }
111942deb29fSKevin Wolf 
112011b128f4SKevin Wolf     /* Internal snapshots */
112111b128f4SKevin Wolf     s->snapshots_offset = header.snapshots_offset;
112211b128f4SKevin Wolf     s->nb_snapshots = header.nb_snapshots;
112311b128f4SKevin Wolf 
112442deb29fSKevin Wolf     ret = qcow2_read_snapshots(bs);
112542deb29fSKevin Wolf     if (ret < 0) {
11263ef6c40aSMax Reitz         error_setg_errno(errp, -ret, "Could not read snapshots");
1127585f8587Sbellard         goto fail;
11286d85a57eSJes Sorensen     }
1129585f8587Sbellard 
1130af7b708dSStefan Hajnoczi     /* Clear unknown autoclear feature bits */
113104c01a5cSKevin Wolf     if (!bs->read_only && !(flags & BDRV_O_INACTIVE) && s->autoclear_features) {
1132af7b708dSStefan Hajnoczi         s->autoclear_features = 0;
1133af7b708dSStefan Hajnoczi         ret = qcow2_update_header(bs);
1134af7b708dSStefan Hajnoczi         if (ret < 0) {
11353ef6c40aSMax Reitz             error_setg_errno(errp, -ret, "Could not update qcow2 header");
1136af7b708dSStefan Hajnoczi             goto fail;
1137af7b708dSStefan Hajnoczi         }
1138af7b708dSStefan Hajnoczi     }
1139af7b708dSStefan Hajnoczi 
114068d100e9SKevin Wolf     /* Initialise locks */
114168d100e9SKevin Wolf     qemu_co_mutex_init(&s->lock);
114268d100e9SKevin Wolf 
1143c61d0004SStefan Hajnoczi     /* Repair image if dirty */
114404c01a5cSKevin Wolf     if (!(flags & (BDRV_O_CHECK | BDRV_O_INACTIVE)) && !bs->read_only &&
1145058f8f16SStefan Hajnoczi         (s->incompatible_features & QCOW2_INCOMPAT_DIRTY)) {
1146c61d0004SStefan Hajnoczi         BdrvCheckResult result = {0};
1147c61d0004SStefan Hajnoczi 
11485b84106bSMax Reitz         ret = qcow2_check(bs, &result, BDRV_FIX_ERRORS | BDRV_FIX_LEAKS);
1149c61d0004SStefan Hajnoczi         if (ret < 0) {
11503ef6c40aSMax Reitz             error_setg_errno(errp, -ret, "Could not repair dirty image");
1151c61d0004SStefan Hajnoczi             goto fail;
1152c61d0004SStefan Hajnoczi         }
1153c61d0004SStefan Hajnoczi     }
1154c61d0004SStefan Hajnoczi 
1155585f8587Sbellard #ifdef DEBUG_ALLOC
11566cbc3031SPhilipp Hahn     {
11576cbc3031SPhilipp Hahn         BdrvCheckResult result = {0};
1158b35278f7SStefan Hajnoczi         qcow2_check_refcounts(bs, &result, 0);
11596cbc3031SPhilipp Hahn     }
1160585f8587Sbellard #endif
11616d85a57eSJes Sorensen     return ret;
1162585f8587Sbellard 
1163585f8587Sbellard  fail:
11646744cbabSKevin Wolf     g_free(s->unknown_header_fields);
116575bab85cSKevin Wolf     cleanup_unknown_header_ext(bs);
1166ed6ccf0fSKevin Wolf     qcow2_free_snapshots(bs);
1167ed6ccf0fSKevin Wolf     qcow2_refcount_close(bs);
1168de82815dSKevin Wolf     qemu_vfree(s->l1_table);
1169cf93980eSMax Reitz     /* else pre-write overlap checks in cache_destroy may crash */
1170cf93980eSMax Reitz     s->l1_table = NULL;
1171279621c0SAlberto Garcia     cache_clean_timer_del(bs);
117229c1a730SKevin Wolf     if (s->l2_table_cache) {
117329c1a730SKevin Wolf         qcow2_cache_destroy(bs, s->l2_table_cache);
117429c1a730SKevin Wolf     }
1175c5a33ee9SPrasad Joshi     if (s->refcount_block_cache) {
1176c5a33ee9SPrasad Joshi         qcow2_cache_destroy(bs, s->refcount_block_cache);
1177c5a33ee9SPrasad Joshi     }
11787267c094SAnthony Liguori     g_free(s->cluster_cache);
1179dea43a65SFrediano Ziglio     qemu_vfree(s->cluster_data);
11806d85a57eSJes Sorensen     return ret;
1181585f8587Sbellard }
1182585f8587Sbellard 
11833baca891SKevin Wolf static void qcow2_refresh_limits(BlockDriverState *bs, Error **errp)
1184d34682cdSKevin Wolf {
1185ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
1186d34682cdSKevin Wolf 
1187d34682cdSKevin Wolf     bs->bl.write_zeroes_alignment = s->cluster_sectors;
1188d34682cdSKevin Wolf }
1189d34682cdSKevin Wolf 
11907c80ab3fSJes Sorensen static int qcow2_set_key(BlockDriverState *bs, const char *key)
1191585f8587Sbellard {
1192ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
1193585f8587Sbellard     uint8_t keybuf[16];
1194585f8587Sbellard     int len, i;
1195f6fa64f6SDaniel P. Berrange     Error *err = NULL;
1196585f8587Sbellard 
1197585f8587Sbellard     memset(keybuf, 0, 16);
1198585f8587Sbellard     len = strlen(key);
1199585f8587Sbellard     if (len > 16)
1200585f8587Sbellard         len = 16;
1201585f8587Sbellard     /* XXX: we could compress the chars to 7 bits to increase
1202585f8587Sbellard        entropy */
1203585f8587Sbellard     for(i = 0;i < len;i++) {
1204585f8587Sbellard         keybuf[i] = key[i];
1205585f8587Sbellard     }
12068336aafaSDaniel P. Berrange     assert(bs->encrypted);
1207585f8587Sbellard 
1208f6fa64f6SDaniel P. Berrange     qcrypto_cipher_free(s->cipher);
1209f6fa64f6SDaniel P. Berrange     s->cipher = qcrypto_cipher_new(
1210f6fa64f6SDaniel P. Berrange         QCRYPTO_CIPHER_ALG_AES_128,
1211f6fa64f6SDaniel P. Berrange         QCRYPTO_CIPHER_MODE_CBC,
1212f6fa64f6SDaniel P. Berrange         keybuf, G_N_ELEMENTS(keybuf),
1213f6fa64f6SDaniel P. Berrange         &err);
1214f6fa64f6SDaniel P. Berrange 
1215f6fa64f6SDaniel P. Berrange     if (!s->cipher) {
1216f6fa64f6SDaniel P. Berrange         /* XXX would be nice if errors in this method could
1217f6fa64f6SDaniel P. Berrange          * be properly propagate to the caller. Would need
1218f6fa64f6SDaniel P. Berrange          * the bdrv_set_key() API signature to be fixed. */
1219f6fa64f6SDaniel P. Berrange         error_free(err);
1220585f8587Sbellard         return -1;
1221585f8587Sbellard     }
1222585f8587Sbellard     return 0;
1223585f8587Sbellard }
1224585f8587Sbellard 
122521d82ac9SJeff Cody static int qcow2_reopen_prepare(BDRVReopenState *state,
122621d82ac9SJeff Cody                                 BlockReopenQueue *queue, Error **errp)
122721d82ac9SJeff Cody {
12285b0959a7SKevin Wolf     Qcow2ReopenState *r;
12294c2e5f8fSKevin Wolf     int ret;
12304c2e5f8fSKevin Wolf 
12315b0959a7SKevin Wolf     r = g_new0(Qcow2ReopenState, 1);
12325b0959a7SKevin Wolf     state->opaque = r;
12335b0959a7SKevin Wolf 
12345b0959a7SKevin Wolf     ret = qcow2_update_options_prepare(state->bs, r, state->options,
12355b0959a7SKevin Wolf                                        state->flags, errp);
12365b0959a7SKevin Wolf     if (ret < 0) {
12375b0959a7SKevin Wolf         goto fail;
12385b0959a7SKevin Wolf     }
12395b0959a7SKevin Wolf 
12405b0959a7SKevin Wolf     /* We need to write out any unwritten data if we reopen read-only. */
12414c2e5f8fSKevin Wolf     if ((state->flags & BDRV_O_RDWR) == 0) {
12424c2e5f8fSKevin Wolf         ret = bdrv_flush(state->bs);
12434c2e5f8fSKevin Wolf         if (ret < 0) {
12445b0959a7SKevin Wolf             goto fail;
12454c2e5f8fSKevin Wolf         }
12464c2e5f8fSKevin Wolf 
12474c2e5f8fSKevin Wolf         ret = qcow2_mark_clean(state->bs);
12484c2e5f8fSKevin Wolf         if (ret < 0) {
12495b0959a7SKevin Wolf             goto fail;
12504c2e5f8fSKevin Wolf         }
12514c2e5f8fSKevin Wolf     }
12524c2e5f8fSKevin Wolf 
125321d82ac9SJeff Cody     return 0;
12545b0959a7SKevin Wolf 
12555b0959a7SKevin Wolf fail:
12565b0959a7SKevin Wolf     qcow2_update_options_abort(state->bs, r);
12575b0959a7SKevin Wolf     g_free(r);
12585b0959a7SKevin Wolf     return ret;
12595b0959a7SKevin Wolf }
12605b0959a7SKevin Wolf 
12615b0959a7SKevin Wolf static void qcow2_reopen_commit(BDRVReopenState *state)
12625b0959a7SKevin Wolf {
12635b0959a7SKevin Wolf     qcow2_update_options_commit(state->bs, state->opaque);
12645b0959a7SKevin Wolf     g_free(state->opaque);
12655b0959a7SKevin Wolf }
12665b0959a7SKevin Wolf 
12675b0959a7SKevin Wolf static void qcow2_reopen_abort(BDRVReopenState *state)
12685b0959a7SKevin Wolf {
12695b0959a7SKevin Wolf     qcow2_update_options_abort(state->bs, state->opaque);
12705b0959a7SKevin Wolf     g_free(state->opaque);
127121d82ac9SJeff Cody }
127221d82ac9SJeff Cody 
12735365f44dSKevin Wolf static void qcow2_join_options(QDict *options, QDict *old_options)
12745365f44dSKevin Wolf {
12755365f44dSKevin Wolf     bool has_new_overlap_template =
12765365f44dSKevin Wolf         qdict_haskey(options, QCOW2_OPT_OVERLAP) ||
12775365f44dSKevin Wolf         qdict_haskey(options, QCOW2_OPT_OVERLAP_TEMPLATE);
12785365f44dSKevin Wolf     bool has_new_total_cache_size =
12795365f44dSKevin Wolf         qdict_haskey(options, QCOW2_OPT_CACHE_SIZE);
12805365f44dSKevin Wolf     bool has_all_cache_options;
12815365f44dSKevin Wolf 
12825365f44dSKevin Wolf     /* New overlap template overrides all old overlap options */
12835365f44dSKevin Wolf     if (has_new_overlap_template) {
12845365f44dSKevin Wolf         qdict_del(old_options, QCOW2_OPT_OVERLAP);
12855365f44dSKevin Wolf         qdict_del(old_options, QCOW2_OPT_OVERLAP_TEMPLATE);
12865365f44dSKevin Wolf         qdict_del(old_options, QCOW2_OPT_OVERLAP_MAIN_HEADER);
12875365f44dSKevin Wolf         qdict_del(old_options, QCOW2_OPT_OVERLAP_ACTIVE_L1);
12885365f44dSKevin Wolf         qdict_del(old_options, QCOW2_OPT_OVERLAP_ACTIVE_L2);
12895365f44dSKevin Wolf         qdict_del(old_options, QCOW2_OPT_OVERLAP_REFCOUNT_TABLE);
12905365f44dSKevin Wolf         qdict_del(old_options, QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK);
12915365f44dSKevin Wolf         qdict_del(old_options, QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE);
12925365f44dSKevin Wolf         qdict_del(old_options, QCOW2_OPT_OVERLAP_INACTIVE_L1);
12935365f44dSKevin Wolf         qdict_del(old_options, QCOW2_OPT_OVERLAP_INACTIVE_L2);
12945365f44dSKevin Wolf     }
12955365f44dSKevin Wolf 
12965365f44dSKevin Wolf     /* New total cache size overrides all old options */
12975365f44dSKevin Wolf     if (qdict_haskey(options, QCOW2_OPT_CACHE_SIZE)) {
12985365f44dSKevin Wolf         qdict_del(old_options, QCOW2_OPT_L2_CACHE_SIZE);
12995365f44dSKevin Wolf         qdict_del(old_options, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
13005365f44dSKevin Wolf     }
13015365f44dSKevin Wolf 
13025365f44dSKevin Wolf     qdict_join(options, old_options, false);
13035365f44dSKevin Wolf 
13045365f44dSKevin Wolf     /*
13055365f44dSKevin Wolf      * If after merging all cache size options are set, an old total size is
13065365f44dSKevin Wolf      * overwritten. Do keep all options, however, if all three are new. The
13075365f44dSKevin Wolf      * resulting error message is what we want to happen.
13085365f44dSKevin Wolf      */
13095365f44dSKevin Wolf     has_all_cache_options =
13105365f44dSKevin Wolf         qdict_haskey(options, QCOW2_OPT_CACHE_SIZE) ||
13115365f44dSKevin Wolf         qdict_haskey(options, QCOW2_OPT_L2_CACHE_SIZE) ||
13125365f44dSKevin Wolf         qdict_haskey(options, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
13135365f44dSKevin Wolf 
13145365f44dSKevin Wolf     if (has_all_cache_options && !has_new_total_cache_size) {
13155365f44dSKevin Wolf         qdict_del(options, QCOW2_OPT_CACHE_SIZE);
13165365f44dSKevin Wolf     }
13175365f44dSKevin Wolf }
13185365f44dSKevin Wolf 
1319b6b8a333SPaolo Bonzini static int64_t coroutine_fn qcow2_co_get_block_status(BlockDriverState *bs,
132067a0fd2aSFam Zheng         int64_t sector_num, int nb_sectors, int *pnum, BlockDriverState **file)
1321585f8587Sbellard {
1322ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
1323585f8587Sbellard     uint64_t cluster_offset;
13244bc74be9SPaolo Bonzini     int index_in_cluster, ret;
13254bc74be9SPaolo Bonzini     int64_t status = 0;
1326585f8587Sbellard 
1327095a9c58Saliguori     *pnum = nb_sectors;
1328f8a2e5e3SStefan Hajnoczi     qemu_co_mutex_lock(&s->lock);
13291c46efaaSKevin Wolf     ret = qcow2_get_cluster_offset(bs, sector_num << 9, pnum, &cluster_offset);
1330f8a2e5e3SStefan Hajnoczi     qemu_co_mutex_unlock(&s->lock);
13311c46efaaSKevin Wolf     if (ret < 0) {
1332d663640cSPaolo Bonzini         return ret;
13331c46efaaSKevin Wolf     }
1334095a9c58Saliguori 
13354bc74be9SPaolo Bonzini     if (cluster_offset != 0 && ret != QCOW2_CLUSTER_COMPRESSED &&
1336f6fa64f6SDaniel P. Berrange         !s->cipher) {
13374bc74be9SPaolo Bonzini         index_in_cluster = sector_num & (s->cluster_sectors - 1);
13384bc74be9SPaolo Bonzini         cluster_offset |= (index_in_cluster << BDRV_SECTOR_BITS);
1339178b4db7SFam Zheng         *file = bs->file->bs;
13404bc74be9SPaolo Bonzini         status |= BDRV_BLOCK_OFFSET_VALID | cluster_offset;
13414bc74be9SPaolo Bonzini     }
13424bc74be9SPaolo Bonzini     if (ret == QCOW2_CLUSTER_ZERO) {
13434bc74be9SPaolo Bonzini         status |= BDRV_BLOCK_ZERO;
13444bc74be9SPaolo Bonzini     } else if (ret != QCOW2_CLUSTER_UNALLOCATED) {
13454bc74be9SPaolo Bonzini         status |= BDRV_BLOCK_DATA;
13464bc74be9SPaolo Bonzini     }
13474bc74be9SPaolo Bonzini     return status;
1348585f8587Sbellard }
1349585f8587Sbellard 
1350a9465922Sbellard /* handle reading after the end of the backing file */
1351bd28f835SKevin Wolf int qcow2_backing_read1(BlockDriverState *bs, QEMUIOVector *qiov,
1352bd28f835SKevin Wolf                   int64_t sector_num, int nb_sectors)
1353a9465922Sbellard {
1354a9465922Sbellard     int n1;
1355a9465922Sbellard     if ((sector_num + nb_sectors) <= bs->total_sectors)
1356a9465922Sbellard         return nb_sectors;
1357a9465922Sbellard     if (sector_num >= bs->total_sectors)
1358a9465922Sbellard         n1 = 0;
1359a9465922Sbellard     else
1360a9465922Sbellard         n1 = bs->total_sectors - sector_num;
1361bd28f835SKevin Wolf 
13623d9b4925SMichael Tokarev     qemu_iovec_memset(qiov, 512 * n1, 0, 512 * (nb_sectors - n1));
1363bd28f835SKevin Wolf 
1364a9465922Sbellard     return n1;
1365a9465922Sbellard }
1366a9465922Sbellard 
1367a968168cSDong Xu Wang static coroutine_fn int qcow2_co_readv(BlockDriverState *bs, int64_t sector_num,
13683fc48d09SFrediano Ziglio                           int remaining_sectors, QEMUIOVector *qiov)
13691490791fSaliguori {
1370ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
1371a9465922Sbellard     int index_in_cluster, n1;
137268d100e9SKevin Wolf     int ret;
1373faf575c1SFrediano Ziglio     int cur_nr_sectors; /* number of sectors in current iteration */
1374c2bdd990SFrediano Ziglio     uint64_t cluster_offset = 0;
13753fc48d09SFrediano Ziglio     uint64_t bytes_done = 0;
13763fc48d09SFrediano Ziglio     QEMUIOVector hd_qiov;
13773fc48d09SFrediano Ziglio     uint8_t *cluster_data = NULL;
1378585f8587Sbellard 
13793fc48d09SFrediano Ziglio     qemu_iovec_init(&hd_qiov, qiov->niov);
13803fc48d09SFrediano Ziglio 
13813fc48d09SFrediano Ziglio     qemu_co_mutex_lock(&s->lock);
13823fc48d09SFrediano Ziglio 
13833fc48d09SFrediano Ziglio     while (remaining_sectors != 0) {
1384585f8587Sbellard 
1385faf575c1SFrediano Ziglio         /* prepare next request */
13863fc48d09SFrediano Ziglio         cur_nr_sectors = remaining_sectors;
1387f6fa64f6SDaniel P. Berrange         if (s->cipher) {
1388faf575c1SFrediano Ziglio             cur_nr_sectors = MIN(cur_nr_sectors,
1389bd28f835SKevin Wolf                 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors);
1390bd28f835SKevin Wolf         }
1391bd28f835SKevin Wolf 
13923fc48d09SFrediano Ziglio         ret = qcow2_get_cluster_offset(bs, sector_num << 9,
1393c2bdd990SFrediano Ziglio             &cur_nr_sectors, &cluster_offset);
13941c46efaaSKevin Wolf         if (ret < 0) {
13953fc48d09SFrediano Ziglio             goto fail;
13961c46efaaSKevin Wolf         }
13971c46efaaSKevin Wolf 
13983fc48d09SFrediano Ziglio         index_in_cluster = sector_num & (s->cluster_sectors - 1);
1399585f8587Sbellard 
14003fc48d09SFrediano Ziglio         qemu_iovec_reset(&hd_qiov);
14011b093c48SMichael Tokarev         qemu_iovec_concat(&hd_qiov, qiov, bytes_done,
1402faf575c1SFrediano Ziglio             cur_nr_sectors * 512);
1403bd28f835SKevin Wolf 
140468d000a3SKevin Wolf         switch (ret) {
140568d000a3SKevin Wolf         case QCOW2_CLUSTER_UNALLOCATED:
1406bd28f835SKevin Wolf 
1407760e0063SKevin Wolf             if (bs->backing) {
1408585f8587Sbellard                 /* read from the base image */
1409760e0063SKevin Wolf                 n1 = qcow2_backing_read1(bs->backing->bs, &hd_qiov,
14103fc48d09SFrediano Ziglio                     sector_num, cur_nr_sectors);
1411a9465922Sbellard                 if (n1 > 0) {
141244deba5aSKevin Wolf                     QEMUIOVector local_qiov;
141344deba5aSKevin Wolf 
141444deba5aSKevin Wolf                     qemu_iovec_init(&local_qiov, hd_qiov.niov);
141544deba5aSKevin Wolf                     qemu_iovec_concat(&local_qiov, &hd_qiov, 0,
141644deba5aSKevin Wolf                                       n1 * BDRV_SECTOR_SIZE);
141744deba5aSKevin Wolf 
141866f82ceeSKevin Wolf                     BLKDBG_EVENT(bs->file, BLKDBG_READ_BACKING_AIO);
141968d100e9SKevin Wolf                     qemu_co_mutex_unlock(&s->lock);
1420760e0063SKevin Wolf                     ret = bdrv_co_readv(bs->backing->bs, sector_num,
142144deba5aSKevin Wolf                                         n1, &local_qiov);
142268d100e9SKevin Wolf                     qemu_co_mutex_lock(&s->lock);
142344deba5aSKevin Wolf 
142444deba5aSKevin Wolf                     qemu_iovec_destroy(&local_qiov);
142544deba5aSKevin Wolf 
142668d100e9SKevin Wolf                     if (ret < 0) {
14273fc48d09SFrediano Ziglio                         goto fail;
14283ab4c7e9SKevin Wolf                     }
14291490791fSaliguori                 }
1430a9465922Sbellard             } else {
1431585f8587Sbellard                 /* Note: in this case, no need to wait */
14323d9b4925SMichael Tokarev                 qemu_iovec_memset(&hd_qiov, 0, 0, 512 * cur_nr_sectors);
14331490791fSaliguori             }
143468d000a3SKevin Wolf             break;
143568d000a3SKevin Wolf 
14366377af48SKevin Wolf         case QCOW2_CLUSTER_ZERO:
14373d9b4925SMichael Tokarev             qemu_iovec_memset(&hd_qiov, 0, 0, 512 * cur_nr_sectors);
14386377af48SKevin Wolf             break;
14396377af48SKevin Wolf 
144068d000a3SKevin Wolf         case QCOW2_CLUSTER_COMPRESSED:
1441585f8587Sbellard             /* add AIO support for compressed blocks ? */
1442c2bdd990SFrediano Ziglio             ret = qcow2_decompress_cluster(bs, cluster_offset);
14438af36488SKevin Wolf             if (ret < 0) {
14443fc48d09SFrediano Ziglio                 goto fail;
14458af36488SKevin Wolf             }
1446bd28f835SKevin Wolf 
144703396148SMichael Tokarev             qemu_iovec_from_buf(&hd_qiov, 0,
1448bd28f835SKevin Wolf                 s->cluster_cache + index_in_cluster * 512,
1449faf575c1SFrediano Ziglio                 512 * cur_nr_sectors);
145068d000a3SKevin Wolf             break;
145168d000a3SKevin Wolf 
145268d000a3SKevin Wolf         case QCOW2_CLUSTER_NORMAL:
1453c2bdd990SFrediano Ziglio             if ((cluster_offset & 511) != 0) {
14543fc48d09SFrediano Ziglio                 ret = -EIO;
14553fc48d09SFrediano Ziglio                 goto fail;
1456585f8587Sbellard             }
1457c87c0672Saliguori 
14588336aafaSDaniel P. Berrange             if (bs->encrypted) {
1459f6fa64f6SDaniel P. Berrange                 assert(s->cipher);
14608336aafaSDaniel P. Berrange 
1461bd28f835SKevin Wolf                 /*
1462bd28f835SKevin Wolf                  * For encrypted images, read everything into a temporary
1463bd28f835SKevin Wolf                  * contiguous buffer on which the AES functions can work.
1464bd28f835SKevin Wolf                  */
14653fc48d09SFrediano Ziglio                 if (!cluster_data) {
14663fc48d09SFrediano Ziglio                     cluster_data =
14679a4f4c31SKevin Wolf                         qemu_try_blockalign(bs->file->bs,
14689a4f4c31SKevin Wolf                                             QCOW_MAX_CRYPT_CLUSTERS
1469de82815dSKevin Wolf                                             * s->cluster_size);
1470de82815dSKevin Wolf                     if (cluster_data == NULL) {
1471de82815dSKevin Wolf                         ret = -ENOMEM;
1472de82815dSKevin Wolf                         goto fail;
1473de82815dSKevin Wolf                     }
1474bd28f835SKevin Wolf                 }
1475bd28f835SKevin Wolf 
1476faf575c1SFrediano Ziglio                 assert(cur_nr_sectors <=
1477bd28f835SKevin Wolf                     QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors);
14783fc48d09SFrediano Ziglio                 qemu_iovec_reset(&hd_qiov);
14793fc48d09SFrediano Ziglio                 qemu_iovec_add(&hd_qiov, cluster_data,
1480faf575c1SFrediano Ziglio                     512 * cur_nr_sectors);
1481bd28f835SKevin Wolf             }
1482bd28f835SKevin Wolf 
148366f82ceeSKevin Wolf             BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);
148468d100e9SKevin Wolf             qemu_co_mutex_unlock(&s->lock);
14859a4f4c31SKevin Wolf             ret = bdrv_co_readv(bs->file->bs,
1486c2bdd990SFrediano Ziglio                                 (cluster_offset >> 9) + index_in_cluster,
14873fc48d09SFrediano Ziglio                                 cur_nr_sectors, &hd_qiov);
148868d100e9SKevin Wolf             qemu_co_mutex_lock(&s->lock);
148968d100e9SKevin Wolf             if (ret < 0) {
14903fc48d09SFrediano Ziglio                 goto fail;
1491585f8587Sbellard             }
14928336aafaSDaniel P. Berrange             if (bs->encrypted) {
1493f6fa64f6SDaniel P. Berrange                 assert(s->cipher);
1494f6fa64f6SDaniel P. Berrange                 Error *err = NULL;
1495f6fa64f6SDaniel P. Berrange                 if (qcow2_encrypt_sectors(s, sector_num,  cluster_data,
1496f6fa64f6SDaniel P. Berrange                                           cluster_data, cur_nr_sectors, false,
1497f6fa64f6SDaniel P. Berrange                                           &err) < 0) {
1498f6fa64f6SDaniel P. Berrange                     error_free(err);
1499f6fa64f6SDaniel P. Berrange                     ret = -EIO;
1500f6fa64f6SDaniel P. Berrange                     goto fail;
1501f6fa64f6SDaniel P. Berrange                 }
150203396148SMichael Tokarev                 qemu_iovec_from_buf(qiov, bytes_done,
150303396148SMichael Tokarev                     cluster_data, 512 * cur_nr_sectors);
1504171e3d6bSKevin Wolf             }
150568d000a3SKevin Wolf             break;
150668d000a3SKevin Wolf 
150768d000a3SKevin Wolf         default:
150868d000a3SKevin Wolf             g_assert_not_reached();
150968d000a3SKevin Wolf             ret = -EIO;
151068d000a3SKevin Wolf             goto fail;
1511faf575c1SFrediano Ziglio         }
1512faf575c1SFrediano Ziglio 
15133fc48d09SFrediano Ziglio         remaining_sectors -= cur_nr_sectors;
15143fc48d09SFrediano Ziglio         sector_num += cur_nr_sectors;
15153fc48d09SFrediano Ziglio         bytes_done += cur_nr_sectors * 512;
15165ebaa27eSFrediano Ziglio     }
15173fc48d09SFrediano Ziglio     ret = 0;
1518f141eafeSaliguori 
15193fc48d09SFrediano Ziglio fail:
152068d100e9SKevin Wolf     qemu_co_mutex_unlock(&s->lock);
152168d100e9SKevin Wolf 
15223fc48d09SFrediano Ziglio     qemu_iovec_destroy(&hd_qiov);
1523dea43a65SFrediano Ziglio     qemu_vfree(cluster_data);
152468d100e9SKevin Wolf 
152568d100e9SKevin Wolf     return ret;
1526585f8587Sbellard }
1527585f8587Sbellard 
1528a968168cSDong Xu Wang static coroutine_fn int qcow2_co_writev(BlockDriverState *bs,
15293fc48d09SFrediano Ziglio                            int64_t sector_num,
15303fc48d09SFrediano Ziglio                            int remaining_sectors,
15313fc48d09SFrediano Ziglio                            QEMUIOVector *qiov)
1532585f8587Sbellard {
1533ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
1534585f8587Sbellard     int index_in_cluster;
153568d100e9SKevin Wolf     int ret;
1536faf575c1SFrediano Ziglio     int cur_nr_sectors; /* number of sectors in current iteration */
1537c2bdd990SFrediano Ziglio     uint64_t cluster_offset;
15383fc48d09SFrediano Ziglio     QEMUIOVector hd_qiov;
15393fc48d09SFrediano Ziglio     uint64_t bytes_done = 0;
15403fc48d09SFrediano Ziglio     uint8_t *cluster_data = NULL;
15418d2497c3SKevin Wolf     QCowL2Meta *l2meta = NULL;
1542c2271403SFrediano Ziglio 
15433cce16f4SKevin Wolf     trace_qcow2_writev_start_req(qemu_coroutine_self(), sector_num,
15443cce16f4SKevin Wolf                                  remaining_sectors);
15453cce16f4SKevin Wolf 
15463fc48d09SFrediano Ziglio     qemu_iovec_init(&hd_qiov, qiov->niov);
1547585f8587Sbellard 
15483fc48d09SFrediano Ziglio     s->cluster_cache_offset = -1; /* disable compressed cache */
15493fc48d09SFrediano Ziglio 
15503fc48d09SFrediano Ziglio     qemu_co_mutex_lock(&s->lock);
15513fc48d09SFrediano Ziglio 
15523fc48d09SFrediano Ziglio     while (remaining_sectors != 0) {
15533fc48d09SFrediano Ziglio 
1554f50f88b9SKevin Wolf         l2meta = NULL;
1555cf5c1a23SKevin Wolf 
15563cce16f4SKevin Wolf         trace_qcow2_writev_start_part(qemu_coroutine_self());
15573fc48d09SFrediano Ziglio         index_in_cluster = sector_num & (s->cluster_sectors - 1);
155816f0587eSHu Tao         cur_nr_sectors = remaining_sectors;
15598336aafaSDaniel P. Berrange         if (bs->encrypted &&
156016f0587eSHu Tao             cur_nr_sectors >
156116f0587eSHu Tao             QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors - index_in_cluster) {
156216f0587eSHu Tao             cur_nr_sectors =
156316f0587eSHu Tao                 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors - index_in_cluster;
15645ebaa27eSFrediano Ziglio         }
1565095a9c58Saliguori 
15663fc48d09SFrediano Ziglio         ret = qcow2_alloc_cluster_offset(bs, sector_num << 9,
156716f0587eSHu Tao             &cur_nr_sectors, &cluster_offset, &l2meta);
1568148da7eaSKevin Wolf         if (ret < 0) {
15693fc48d09SFrediano Ziglio             goto fail;
1570148da7eaSKevin Wolf         }
1571148da7eaSKevin Wolf 
1572c2bdd990SFrediano Ziglio         assert((cluster_offset & 511) == 0);
1573148da7eaSKevin Wolf 
15743fc48d09SFrediano Ziglio         qemu_iovec_reset(&hd_qiov);
15751b093c48SMichael Tokarev         qemu_iovec_concat(&hd_qiov, qiov, bytes_done,
1576faf575c1SFrediano Ziglio             cur_nr_sectors * 512);
15776f5f060bSKevin Wolf 
15788336aafaSDaniel P. Berrange         if (bs->encrypted) {
1579f6fa64f6SDaniel P. Berrange             Error *err = NULL;
1580f6fa64f6SDaniel P. Berrange             assert(s->cipher);
15813fc48d09SFrediano Ziglio             if (!cluster_data) {
15829a4f4c31SKevin Wolf                 cluster_data = qemu_try_blockalign(bs->file->bs,
1583de82815dSKevin Wolf                                                    QCOW_MAX_CRYPT_CLUSTERS
1584de82815dSKevin Wolf                                                    * s->cluster_size);
1585de82815dSKevin Wolf                 if (cluster_data == NULL) {
1586de82815dSKevin Wolf                     ret = -ENOMEM;
1587de82815dSKevin Wolf                     goto fail;
1588de82815dSKevin Wolf                 }
1589585f8587Sbellard             }
15906f5f060bSKevin Wolf 
15913fc48d09SFrediano Ziglio             assert(hd_qiov.size <=
15925ebaa27eSFrediano Ziglio                    QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
1593d5e6b161SMichael Tokarev             qemu_iovec_to_buf(&hd_qiov, 0, cluster_data, hd_qiov.size);
15946f5f060bSKevin Wolf 
1595f6fa64f6SDaniel P. Berrange             if (qcow2_encrypt_sectors(s, sector_num, cluster_data,
1596f6fa64f6SDaniel P. Berrange                                       cluster_data, cur_nr_sectors,
1597f6fa64f6SDaniel P. Berrange                                       true, &err) < 0) {
1598f6fa64f6SDaniel P. Berrange                 error_free(err);
1599f6fa64f6SDaniel P. Berrange                 ret = -EIO;
1600f6fa64f6SDaniel P. Berrange                 goto fail;
1601f6fa64f6SDaniel P. Berrange             }
16026f5f060bSKevin Wolf 
16033fc48d09SFrediano Ziglio             qemu_iovec_reset(&hd_qiov);
16043fc48d09SFrediano Ziglio             qemu_iovec_add(&hd_qiov, cluster_data,
1605faf575c1SFrediano Ziglio                 cur_nr_sectors * 512);
1606585f8587Sbellard         }
16076f5f060bSKevin Wolf 
1608231bb267SMax Reitz         ret = qcow2_pre_write_overlap_check(bs, 0,
1609cf93980eSMax Reitz                 cluster_offset + index_in_cluster * BDRV_SECTOR_SIZE,
1610cf93980eSMax Reitz                 cur_nr_sectors * BDRV_SECTOR_SIZE);
1611cf93980eSMax Reitz         if (ret < 0) {
1612cf93980eSMax Reitz             goto fail;
1613cf93980eSMax Reitz         }
1614cf93980eSMax Reitz 
161568d100e9SKevin Wolf         qemu_co_mutex_unlock(&s->lock);
161667a7a0ebSKevin Wolf         BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO);
16173cce16f4SKevin Wolf         trace_qcow2_writev_data(qemu_coroutine_self(),
16183cce16f4SKevin Wolf                                 (cluster_offset >> 9) + index_in_cluster);
16199a4f4c31SKevin Wolf         ret = bdrv_co_writev(bs->file->bs,
1620c2bdd990SFrediano Ziglio                              (cluster_offset >> 9) + index_in_cluster,
16213fc48d09SFrediano Ziglio                              cur_nr_sectors, &hd_qiov);
162268d100e9SKevin Wolf         qemu_co_mutex_lock(&s->lock);
162368d100e9SKevin Wolf         if (ret < 0) {
16243fc48d09SFrediano Ziglio             goto fail;
1625171e3d6bSKevin Wolf         }
1626f141eafeSaliguori 
162788c6588cSKevin Wolf         while (l2meta != NULL) {
162888c6588cSKevin Wolf             QCowL2Meta *next;
162988c6588cSKevin Wolf 
1630cf5c1a23SKevin Wolf             ret = qcow2_alloc_cluster_link_l2(bs, l2meta);
1631faf575c1SFrediano Ziglio             if (ret < 0) {
16323fc48d09SFrediano Ziglio                 goto fail;
1633faf575c1SFrediano Ziglio             }
1634faf575c1SFrediano Ziglio 
16354e95314eSKevin Wolf             /* Take the request off the list of running requests */
16364e95314eSKevin Wolf             if (l2meta->nb_clusters != 0) {
16374e95314eSKevin Wolf                 QLIST_REMOVE(l2meta, next_in_flight);
16384e95314eSKevin Wolf             }
16394e95314eSKevin Wolf 
16404e95314eSKevin Wolf             qemu_co_queue_restart_all(&l2meta->dependent_requests);
16414e95314eSKevin Wolf 
164288c6588cSKevin Wolf             next = l2meta->next;
1643cf5c1a23SKevin Wolf             g_free(l2meta);
164488c6588cSKevin Wolf             l2meta = next;
1645f50f88b9SKevin Wolf         }
16460fa9131aSKevin Wolf 
16473fc48d09SFrediano Ziglio         remaining_sectors -= cur_nr_sectors;
16483fc48d09SFrediano Ziglio         sector_num += cur_nr_sectors;
16493fc48d09SFrediano Ziglio         bytes_done += cur_nr_sectors * 512;
16503cce16f4SKevin Wolf         trace_qcow2_writev_done_part(qemu_coroutine_self(), cur_nr_sectors);
16515ebaa27eSFrediano Ziglio     }
16523fc48d09SFrediano Ziglio     ret = 0;
1653faf575c1SFrediano Ziglio 
16543fc48d09SFrediano Ziglio fail:
16554e95314eSKevin Wolf     qemu_co_mutex_unlock(&s->lock);
16564e95314eSKevin Wolf 
165788c6588cSKevin Wolf     while (l2meta != NULL) {
165888c6588cSKevin Wolf         QCowL2Meta *next;
165988c6588cSKevin Wolf 
16604e95314eSKevin Wolf         if (l2meta->nb_clusters != 0) {
16614e95314eSKevin Wolf             QLIST_REMOVE(l2meta, next_in_flight);
16624e95314eSKevin Wolf         }
16634e95314eSKevin Wolf         qemu_co_queue_restart_all(&l2meta->dependent_requests);
166488c6588cSKevin Wolf 
166588c6588cSKevin Wolf         next = l2meta->next;
1666cf5c1a23SKevin Wolf         g_free(l2meta);
166788c6588cSKevin Wolf         l2meta = next;
1668cf5c1a23SKevin Wolf     }
16690fa9131aSKevin Wolf 
16703fc48d09SFrediano Ziglio     qemu_iovec_destroy(&hd_qiov);
1671dea43a65SFrediano Ziglio     qemu_vfree(cluster_data);
16723cce16f4SKevin Wolf     trace_qcow2_writev_done_req(qemu_coroutine_self(), ret);
167342496d62SKevin Wolf 
167468d100e9SKevin Wolf     return ret;
1675585f8587Sbellard }
1676585f8587Sbellard 
1677ec6d8912SKevin Wolf static int qcow2_inactivate(BlockDriverState *bs)
1678ec6d8912SKevin Wolf {
1679ec6d8912SKevin Wolf     BDRVQcow2State *s = bs->opaque;
1680ec6d8912SKevin Wolf     int ret, result = 0;
1681ec6d8912SKevin Wolf 
1682ec6d8912SKevin Wolf     ret = qcow2_cache_flush(bs, s->l2_table_cache);
1683ec6d8912SKevin Wolf     if (ret) {
1684ec6d8912SKevin Wolf         result = ret;
1685ec6d8912SKevin Wolf         error_report("Failed to flush the L2 table cache: %s",
1686ec6d8912SKevin Wolf                      strerror(-ret));
1687ec6d8912SKevin Wolf     }
1688ec6d8912SKevin Wolf 
1689ec6d8912SKevin Wolf     ret = qcow2_cache_flush(bs, s->refcount_block_cache);
1690ec6d8912SKevin Wolf     if (ret) {
1691ec6d8912SKevin Wolf         result = ret;
1692ec6d8912SKevin Wolf         error_report("Failed to flush the refcount block cache: %s",
1693ec6d8912SKevin Wolf                      strerror(-ret));
1694ec6d8912SKevin Wolf     }
1695ec6d8912SKevin Wolf 
1696ec6d8912SKevin Wolf     if (result == 0) {
1697ec6d8912SKevin Wolf         qcow2_mark_clean(bs);
1698ec6d8912SKevin Wolf     }
1699ec6d8912SKevin Wolf 
1700ec6d8912SKevin Wolf     return result;
1701ec6d8912SKevin Wolf }
1702ec6d8912SKevin Wolf 
17037c80ab3fSJes Sorensen static void qcow2_close(BlockDriverState *bs)
1704585f8587Sbellard {
1705ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
1706de82815dSKevin Wolf     qemu_vfree(s->l1_table);
1707cf93980eSMax Reitz     /* else pre-write overlap checks in cache_destroy may crash */
1708cf93980eSMax Reitz     s->l1_table = NULL;
170929c1a730SKevin Wolf 
1710140fd5a6SKevin Wolf     if (!(s->flags & BDRV_O_INACTIVE)) {
1711ec6d8912SKevin Wolf         qcow2_inactivate(bs);
17123b5e14c7SMax Reitz     }
1713c61d0004SStefan Hajnoczi 
1714279621c0SAlberto Garcia     cache_clean_timer_del(bs);
171529c1a730SKevin Wolf     qcow2_cache_destroy(bs, s->l2_table_cache);
171629c1a730SKevin Wolf     qcow2_cache_destroy(bs, s->refcount_block_cache);
171729c1a730SKevin Wolf 
1718f6fa64f6SDaniel P. Berrange     qcrypto_cipher_free(s->cipher);
1719f6fa64f6SDaniel P. Berrange     s->cipher = NULL;
1720f6fa64f6SDaniel P. Berrange 
17216744cbabSKevin Wolf     g_free(s->unknown_header_fields);
172275bab85cSKevin Wolf     cleanup_unknown_header_ext(bs);
17236744cbabSKevin Wolf 
1724e4603fe1SKevin Wolf     g_free(s->image_backing_file);
1725e4603fe1SKevin Wolf     g_free(s->image_backing_format);
1726e4603fe1SKevin Wolf 
17277267c094SAnthony Liguori     g_free(s->cluster_cache);
1728dea43a65SFrediano Ziglio     qemu_vfree(s->cluster_data);
1729ed6ccf0fSKevin Wolf     qcow2_refcount_close(bs);
173028c1202bSLi Zhi Hui     qcow2_free_snapshots(bs);
1731585f8587Sbellard }
1732585f8587Sbellard 
17335a8a30dbSKevin Wolf static void qcow2_invalidate_cache(BlockDriverState *bs, Error **errp)
173406d9260fSAnthony Liguori {
1735ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
173606d9260fSAnthony Liguori     int flags = s->flags;
1737f6fa64f6SDaniel P. Berrange     QCryptoCipher *cipher = NULL;
1738acdfb480SKevin Wolf     QDict *options;
17395a8a30dbSKevin Wolf     Error *local_err = NULL;
17405a8a30dbSKevin Wolf     int ret;
174106d9260fSAnthony Liguori 
174206d9260fSAnthony Liguori     /*
174306d9260fSAnthony Liguori      * Backing files are read-only which makes all of their metadata immutable,
174406d9260fSAnthony Liguori      * that means we don't have to worry about reopening them here.
174506d9260fSAnthony Liguori      */
174606d9260fSAnthony Liguori 
1747f6fa64f6SDaniel P. Berrange     cipher = s->cipher;
1748f6fa64f6SDaniel P. Berrange     s->cipher = NULL;
174906d9260fSAnthony Liguori 
175006d9260fSAnthony Liguori     qcow2_close(bs);
175106d9260fSAnthony Liguori 
17529a4f4c31SKevin Wolf     bdrv_invalidate_cache(bs->file->bs, &local_err);
17535a8a30dbSKevin Wolf     if (local_err) {
17545a8a30dbSKevin Wolf         error_propagate(errp, local_err);
1755191fb11bSKevin Wolf         bs->drv = NULL;
17565a8a30dbSKevin Wolf         return;
17575a8a30dbSKevin Wolf     }
17583456a8d1SKevin Wolf 
1759ff99129aSKevin Wolf     memset(s, 0, sizeof(BDRVQcow2State));
1760d475e5acSKevin Wolf     options = qdict_clone_shallow(bs->options);
17615a8a30dbSKevin Wolf 
1762140fd5a6SKevin Wolf     flags &= ~BDRV_O_INACTIVE;
17635a8a30dbSKevin Wolf     ret = qcow2_open(bs, options, flags, &local_err);
1764a1904e48SMarkus Armbruster     QDECREF(options);
17655a8a30dbSKevin Wolf     if (local_err) {
1766e43bfd9cSMarkus Armbruster         error_propagate(errp, local_err);
1767e43bfd9cSMarkus Armbruster         error_prepend(errp, "Could not reopen qcow2 layer: ");
1768191fb11bSKevin Wolf         bs->drv = NULL;
17695a8a30dbSKevin Wolf         return;
17705a8a30dbSKevin Wolf     } else if (ret < 0) {
17715a8a30dbSKevin Wolf         error_setg_errno(errp, -ret, "Could not reopen qcow2 layer");
1772191fb11bSKevin Wolf         bs->drv = NULL;
17735a8a30dbSKevin Wolf         return;
17745a8a30dbSKevin Wolf     }
1775acdfb480SKevin Wolf 
1776f6fa64f6SDaniel P. Berrange     s->cipher = cipher;
177706d9260fSAnthony Liguori }
177806d9260fSAnthony Liguori 
1779e24e49e6SKevin Wolf static size_t header_ext_add(char *buf, uint32_t magic, const void *s,
1780e24e49e6SKevin Wolf     size_t len, size_t buflen)
1781756e6736SKevin Wolf {
1782e24e49e6SKevin Wolf     QCowExtension *ext_backing_fmt = (QCowExtension*) buf;
1783e24e49e6SKevin Wolf     size_t ext_len = sizeof(QCowExtension) + ((len + 7) & ~7);
1784756e6736SKevin Wolf 
1785e24e49e6SKevin Wolf     if (buflen < ext_len) {
1786756e6736SKevin Wolf         return -ENOSPC;
1787756e6736SKevin Wolf     }
1788756e6736SKevin Wolf 
1789e24e49e6SKevin Wolf     *ext_backing_fmt = (QCowExtension) {
1790e24e49e6SKevin Wolf         .magic  = cpu_to_be32(magic),
1791e24e49e6SKevin Wolf         .len    = cpu_to_be32(len),
1792e24e49e6SKevin Wolf     };
1793e24e49e6SKevin Wolf     memcpy(buf + sizeof(QCowExtension), s, len);
1794756e6736SKevin Wolf 
1795e24e49e6SKevin Wolf     return ext_len;
1796756e6736SKevin Wolf }
1797756e6736SKevin Wolf 
1798e24e49e6SKevin Wolf /*
1799e24e49e6SKevin Wolf  * Updates the qcow2 header, including the variable length parts of it, i.e.
1800e24e49e6SKevin Wolf  * the backing file name and all extensions. qcow2 was not designed to allow
1801e24e49e6SKevin Wolf  * such changes, so if we run out of space (we can only use the first cluster)
1802e24e49e6SKevin Wolf  * this function may fail.
1803e24e49e6SKevin Wolf  *
1804e24e49e6SKevin Wolf  * Returns 0 on success, -errno in error cases.
1805e24e49e6SKevin Wolf  */
1806e24e49e6SKevin Wolf int qcow2_update_header(BlockDriverState *bs)
1807e24e49e6SKevin Wolf {
1808ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
1809e24e49e6SKevin Wolf     QCowHeader *header;
1810e24e49e6SKevin Wolf     char *buf;
1811e24e49e6SKevin Wolf     size_t buflen = s->cluster_size;
1812e24e49e6SKevin Wolf     int ret;
1813e24e49e6SKevin Wolf     uint64_t total_size;
1814e24e49e6SKevin Wolf     uint32_t refcount_table_clusters;
18156744cbabSKevin Wolf     size_t header_length;
181675bab85cSKevin Wolf     Qcow2UnknownHeaderExtension *uext;
1817e24e49e6SKevin Wolf 
1818e24e49e6SKevin Wolf     buf = qemu_blockalign(bs, buflen);
1819e24e49e6SKevin Wolf 
1820e24e49e6SKevin Wolf     /* Header structure */
1821e24e49e6SKevin Wolf     header = (QCowHeader*) buf;
1822e24e49e6SKevin Wolf 
1823e24e49e6SKevin Wolf     if (buflen < sizeof(*header)) {
1824e24e49e6SKevin Wolf         ret = -ENOSPC;
1825e24e49e6SKevin Wolf         goto fail;
1826756e6736SKevin Wolf     }
1827756e6736SKevin Wolf 
18286744cbabSKevin Wolf     header_length = sizeof(*header) + s->unknown_header_fields_size;
1829e24e49e6SKevin Wolf     total_size = bs->total_sectors * BDRV_SECTOR_SIZE;
1830e24e49e6SKevin Wolf     refcount_table_clusters = s->refcount_table_size >> (s->cluster_bits - 3);
1831e24e49e6SKevin Wolf 
1832e24e49e6SKevin Wolf     *header = (QCowHeader) {
18336744cbabSKevin Wolf         /* Version 2 fields */
1834e24e49e6SKevin Wolf         .magic                  = cpu_to_be32(QCOW_MAGIC),
18356744cbabSKevin Wolf         .version                = cpu_to_be32(s->qcow_version),
1836e24e49e6SKevin Wolf         .backing_file_offset    = 0,
1837e24e49e6SKevin Wolf         .backing_file_size      = 0,
1838e24e49e6SKevin Wolf         .cluster_bits           = cpu_to_be32(s->cluster_bits),
1839e24e49e6SKevin Wolf         .size                   = cpu_to_be64(total_size),
1840e24e49e6SKevin Wolf         .crypt_method           = cpu_to_be32(s->crypt_method_header),
1841e24e49e6SKevin Wolf         .l1_size                = cpu_to_be32(s->l1_size),
1842e24e49e6SKevin Wolf         .l1_table_offset        = cpu_to_be64(s->l1_table_offset),
1843e24e49e6SKevin Wolf         .refcount_table_offset  = cpu_to_be64(s->refcount_table_offset),
1844e24e49e6SKevin Wolf         .refcount_table_clusters = cpu_to_be32(refcount_table_clusters),
1845e24e49e6SKevin Wolf         .nb_snapshots           = cpu_to_be32(s->nb_snapshots),
1846e24e49e6SKevin Wolf         .snapshots_offset       = cpu_to_be64(s->snapshots_offset),
18476744cbabSKevin Wolf 
18486744cbabSKevin Wolf         /* Version 3 fields */
18496744cbabSKevin Wolf         .incompatible_features  = cpu_to_be64(s->incompatible_features),
18506744cbabSKevin Wolf         .compatible_features    = cpu_to_be64(s->compatible_features),
18516744cbabSKevin Wolf         .autoclear_features     = cpu_to_be64(s->autoclear_features),
1852b6481f37SMax Reitz         .refcount_order         = cpu_to_be32(s->refcount_order),
18536744cbabSKevin Wolf         .header_length          = cpu_to_be32(header_length),
1854e24e49e6SKevin Wolf     };
1855e24e49e6SKevin Wolf 
18566744cbabSKevin Wolf     /* For older versions, write a shorter header */
18576744cbabSKevin Wolf     switch (s->qcow_version) {
18586744cbabSKevin Wolf     case 2:
18596744cbabSKevin Wolf         ret = offsetof(QCowHeader, incompatible_features);
18606744cbabSKevin Wolf         break;
18616744cbabSKevin Wolf     case 3:
18626744cbabSKevin Wolf         ret = sizeof(*header);
18636744cbabSKevin Wolf         break;
18646744cbabSKevin Wolf     default:
1865b6c14762SJim Meyering         ret = -EINVAL;
1866b6c14762SJim Meyering         goto fail;
18676744cbabSKevin Wolf     }
18686744cbabSKevin Wolf 
18696744cbabSKevin Wolf     buf += ret;
18706744cbabSKevin Wolf     buflen -= ret;
18716744cbabSKevin Wolf     memset(buf, 0, buflen);
18726744cbabSKevin Wolf 
18736744cbabSKevin Wolf     /* Preserve any unknown field in the header */
18746744cbabSKevin Wolf     if (s->unknown_header_fields_size) {
18756744cbabSKevin Wolf         if (buflen < s->unknown_header_fields_size) {
18766744cbabSKevin Wolf             ret = -ENOSPC;
18776744cbabSKevin Wolf             goto fail;
18786744cbabSKevin Wolf         }
18796744cbabSKevin Wolf 
18806744cbabSKevin Wolf         memcpy(buf, s->unknown_header_fields, s->unknown_header_fields_size);
18816744cbabSKevin Wolf         buf += s->unknown_header_fields_size;
18826744cbabSKevin Wolf         buflen -= s->unknown_header_fields_size;
18836744cbabSKevin Wolf     }
1884e24e49e6SKevin Wolf 
1885e24e49e6SKevin Wolf     /* Backing file format header extension */
1886e4603fe1SKevin Wolf     if (s->image_backing_format) {
1887e24e49e6SKevin Wolf         ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BACKING_FORMAT,
1888e4603fe1SKevin Wolf                              s->image_backing_format,
1889e4603fe1SKevin Wolf                              strlen(s->image_backing_format),
1890e24e49e6SKevin Wolf                              buflen);
1891756e6736SKevin Wolf         if (ret < 0) {
1892756e6736SKevin Wolf             goto fail;
1893756e6736SKevin Wolf         }
1894756e6736SKevin Wolf 
1895e24e49e6SKevin Wolf         buf += ret;
1896e24e49e6SKevin Wolf         buflen -= ret;
1897e24e49e6SKevin Wolf     }
1898756e6736SKevin Wolf 
1899cfcc4c62SKevin Wolf     /* Feature table */
19001a4828c7SKevin Wolf     if (s->qcow_version >= 3) {
1901cfcc4c62SKevin Wolf         Qcow2Feature features[] = {
1902c61d0004SStefan Hajnoczi             {
1903c61d0004SStefan Hajnoczi                 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
1904c61d0004SStefan Hajnoczi                 .bit  = QCOW2_INCOMPAT_DIRTY_BITNR,
1905c61d0004SStefan Hajnoczi                 .name = "dirty bit",
1906c61d0004SStefan Hajnoczi             },
1907bfe8043eSStefan Hajnoczi             {
190869c98726SMax Reitz                 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
190969c98726SMax Reitz                 .bit  = QCOW2_INCOMPAT_CORRUPT_BITNR,
191069c98726SMax Reitz                 .name = "corrupt bit",
191169c98726SMax Reitz             },
191269c98726SMax Reitz             {
1913bfe8043eSStefan Hajnoczi                 .type = QCOW2_FEAT_TYPE_COMPATIBLE,
1914bfe8043eSStefan Hajnoczi                 .bit  = QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR,
1915bfe8043eSStefan Hajnoczi                 .name = "lazy refcounts",
1916bfe8043eSStefan Hajnoczi             },
1917cfcc4c62SKevin Wolf         };
1918cfcc4c62SKevin Wolf 
1919cfcc4c62SKevin Wolf         ret = header_ext_add(buf, QCOW2_EXT_MAGIC_FEATURE_TABLE,
1920cfcc4c62SKevin Wolf                              features, sizeof(features), buflen);
1921cfcc4c62SKevin Wolf         if (ret < 0) {
1922cfcc4c62SKevin Wolf             goto fail;
1923cfcc4c62SKevin Wolf         }
1924cfcc4c62SKevin Wolf         buf += ret;
1925cfcc4c62SKevin Wolf         buflen -= ret;
19261a4828c7SKevin Wolf     }
1927cfcc4c62SKevin Wolf 
192875bab85cSKevin Wolf     /* Keep unknown header extensions */
192975bab85cSKevin Wolf     QLIST_FOREACH(uext, &s->unknown_header_ext, next) {
193075bab85cSKevin Wolf         ret = header_ext_add(buf, uext->magic, uext->data, uext->len, buflen);
193175bab85cSKevin Wolf         if (ret < 0) {
193275bab85cSKevin Wolf             goto fail;
193375bab85cSKevin Wolf         }
193475bab85cSKevin Wolf 
193575bab85cSKevin Wolf         buf += ret;
193675bab85cSKevin Wolf         buflen -= ret;
193775bab85cSKevin Wolf     }
193875bab85cSKevin Wolf 
1939e24e49e6SKevin Wolf     /* End of header extensions */
1940e24e49e6SKevin Wolf     ret = header_ext_add(buf, QCOW2_EXT_MAGIC_END, NULL, 0, buflen);
1941756e6736SKevin Wolf     if (ret < 0) {
1942756e6736SKevin Wolf         goto fail;
1943756e6736SKevin Wolf     }
1944756e6736SKevin Wolf 
1945e24e49e6SKevin Wolf     buf += ret;
1946e24e49e6SKevin Wolf     buflen -= ret;
1947e24e49e6SKevin Wolf 
1948e24e49e6SKevin Wolf     /* Backing file name */
1949e4603fe1SKevin Wolf     if (s->image_backing_file) {
1950e4603fe1SKevin Wolf         size_t backing_file_len = strlen(s->image_backing_file);
1951e24e49e6SKevin Wolf 
1952e24e49e6SKevin Wolf         if (buflen < backing_file_len) {
1953e24e49e6SKevin Wolf             ret = -ENOSPC;
1954e24e49e6SKevin Wolf             goto fail;
1955e24e49e6SKevin Wolf         }
1956e24e49e6SKevin Wolf 
195700ea1881SJim Meyering         /* Using strncpy is ok here, since buf is not NUL-terminated. */
1958e4603fe1SKevin Wolf         strncpy(buf, s->image_backing_file, buflen);
1959e24e49e6SKevin Wolf 
1960e24e49e6SKevin Wolf         header->backing_file_offset = cpu_to_be64(buf - ((char*) header));
1961e24e49e6SKevin Wolf         header->backing_file_size   = cpu_to_be32(backing_file_len);
1962e24e49e6SKevin Wolf     }
1963e24e49e6SKevin Wolf 
1964e24e49e6SKevin Wolf     /* Write the new header */
19659a4f4c31SKevin Wolf     ret = bdrv_pwrite(bs->file->bs, 0, header, s->cluster_size);
1966756e6736SKevin Wolf     if (ret < 0) {
1967756e6736SKevin Wolf         goto fail;
1968756e6736SKevin Wolf     }
1969756e6736SKevin Wolf 
1970756e6736SKevin Wolf     ret = 0;
1971756e6736SKevin Wolf fail:
1972e24e49e6SKevin Wolf     qemu_vfree(header);
1973756e6736SKevin Wolf     return ret;
1974756e6736SKevin Wolf }
1975756e6736SKevin Wolf 
1976756e6736SKevin Wolf static int qcow2_change_backing_file(BlockDriverState *bs,
1977756e6736SKevin Wolf     const char *backing_file, const char *backing_fmt)
1978756e6736SKevin Wolf {
1979ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
1980e4603fe1SKevin Wolf 
1981e24e49e6SKevin Wolf     pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
1982e24e49e6SKevin Wolf     pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
1983e24e49e6SKevin Wolf 
1984e4603fe1SKevin Wolf     g_free(s->image_backing_file);
1985e4603fe1SKevin Wolf     g_free(s->image_backing_format);
1986e4603fe1SKevin Wolf 
1987e4603fe1SKevin Wolf     s->image_backing_file = backing_file ? g_strdup(bs->backing_file) : NULL;
1988e4603fe1SKevin Wolf     s->image_backing_format = backing_fmt ? g_strdup(bs->backing_format) : NULL;
1989e4603fe1SKevin Wolf 
1990e24e49e6SKevin Wolf     return qcow2_update_header(bs);
1991756e6736SKevin Wolf }
1992756e6736SKevin Wolf 
1993a35e1c17SKevin Wolf static int preallocate(BlockDriverState *bs)
1994a35e1c17SKevin Wolf {
1995a35e1c17SKevin Wolf     uint64_t nb_sectors;
1996a35e1c17SKevin Wolf     uint64_t offset;
1997060bee89SKevin Wolf     uint64_t host_offset = 0;
1998a35e1c17SKevin Wolf     int num;
1999148da7eaSKevin Wolf     int ret;
2000f50f88b9SKevin Wolf     QCowL2Meta *meta;
2001a35e1c17SKevin Wolf 
200257322b78SMarkus Armbruster     nb_sectors = bdrv_nb_sectors(bs);
2003a35e1c17SKevin Wolf     offset = 0;
2004a35e1c17SKevin Wolf 
2005a35e1c17SKevin Wolf     while (nb_sectors) {
20067c2bbf4aSHu Tao         num = MIN(nb_sectors, INT_MAX >> BDRV_SECTOR_BITS);
200716f0587eSHu Tao         ret = qcow2_alloc_cluster_offset(bs, offset, &num,
2008060bee89SKevin Wolf                                          &host_offset, &meta);
2009148da7eaSKevin Wolf         if (ret < 0) {
201019dbcbf7SKevin Wolf             return ret;
2011a35e1c17SKevin Wolf         }
2012a35e1c17SKevin Wolf 
2013c792707fSStefan Hajnoczi         while (meta) {
2014c792707fSStefan Hajnoczi             QCowL2Meta *next = meta->next;
2015c792707fSStefan Hajnoczi 
2016f50f88b9SKevin Wolf             ret = qcow2_alloc_cluster_link_l2(bs, meta);
201719dbcbf7SKevin Wolf             if (ret < 0) {
20187c2bbf4aSHu Tao                 qcow2_free_any_clusters(bs, meta->alloc_offset,
20197c2bbf4aSHu Tao                                         meta->nb_clusters, QCOW2_DISCARD_NEVER);
202019dbcbf7SKevin Wolf                 return ret;
2021a35e1c17SKevin Wolf             }
2022a35e1c17SKevin Wolf 
20237c2bbf4aSHu Tao             /* There are no dependent requests, but we need to remove our
20247c2bbf4aSHu Tao              * request from the list of in-flight requests */
20254e95314eSKevin Wolf             QLIST_REMOVE(meta, next_in_flight);
2026c792707fSStefan Hajnoczi 
2027c792707fSStefan Hajnoczi             g_free(meta);
2028c792707fSStefan Hajnoczi             meta = next;
2029f50f88b9SKevin Wolf         }
2030f214978aSKevin Wolf 
2031a35e1c17SKevin Wolf         /* TODO Preallocate data if requested */
2032a35e1c17SKevin Wolf 
2033a35e1c17SKevin Wolf         nb_sectors -= num;
20347c2bbf4aSHu Tao         offset += num << BDRV_SECTOR_BITS;
2035a35e1c17SKevin Wolf     }
2036a35e1c17SKevin Wolf 
2037a35e1c17SKevin Wolf     /*
2038a35e1c17SKevin Wolf      * It is expected that the image file is large enough to actually contain
2039a35e1c17SKevin Wolf      * all of the allocated clusters (otherwise we get failing reads after
2040a35e1c17SKevin Wolf      * EOF). Extend the image to the last allocated sector.
2041a35e1c17SKevin Wolf      */
2042060bee89SKevin Wolf     if (host_offset != 0) {
20437c2bbf4aSHu Tao         uint8_t buf[BDRV_SECTOR_SIZE];
20447c2bbf4aSHu Tao         memset(buf, 0, BDRV_SECTOR_SIZE);
20459a4f4c31SKevin Wolf         ret = bdrv_write(bs->file->bs,
20469a4f4c31SKevin Wolf                          (host_offset >> BDRV_SECTOR_BITS) + num - 1,
20477c2bbf4aSHu Tao                          buf, 1);
204819dbcbf7SKevin Wolf         if (ret < 0) {
204919dbcbf7SKevin Wolf             return ret;
205019dbcbf7SKevin Wolf         }
2051a35e1c17SKevin Wolf     }
2052a35e1c17SKevin Wolf 
2053a35e1c17SKevin Wolf     return 0;
2054a35e1c17SKevin Wolf }
2055a35e1c17SKevin Wolf 
20567c80ab3fSJes Sorensen static int qcow2_create2(const char *filename, int64_t total_size,
2057a9420734SKevin Wolf                          const char *backing_file, const char *backing_format,
2058ffeaac9bSHu Tao                          int flags, size_t cluster_size, PreallocMode prealloc,
2059bd4b167fSMax Reitz                          QemuOpts *opts, int version, int refcount_order,
20603ef6c40aSMax Reitz                          Error **errp)
2061a9420734SKevin Wolf {
2062a9420734SKevin Wolf     int cluster_bits;
2063e6641719SMax Reitz     QDict *options;
2064e6641719SMax Reitz 
2065e6641719SMax Reitz     /* Calculate cluster_bits */
2066786a4ea8SStefan Hajnoczi     cluster_bits = ctz32(cluster_size);
2067a9420734SKevin Wolf     if (cluster_bits < MIN_CLUSTER_BITS || cluster_bits > MAX_CLUSTER_BITS ||
2068a9420734SKevin Wolf         (1 << cluster_bits) != cluster_size)
2069a9420734SKevin Wolf     {
20703ef6c40aSMax Reitz         error_setg(errp, "Cluster size must be a power of two between %d and "
20713ef6c40aSMax Reitz                    "%dk", 1 << MIN_CLUSTER_BITS, 1 << (MAX_CLUSTER_BITS - 10));
2072a9420734SKevin Wolf         return -EINVAL;
2073a9420734SKevin Wolf     }
2074a9420734SKevin Wolf 
2075a9420734SKevin Wolf     /*
2076a9420734SKevin Wolf      * Open the image file and write a minimal qcow2 header.
2077a9420734SKevin Wolf      *
2078a9420734SKevin Wolf      * We keep things simple and start with a zero-sized image. We also
2079a9420734SKevin Wolf      * do without refcount blocks or a L1 table for now. We'll fix the
2080a9420734SKevin Wolf      * inconsistency later.
2081a9420734SKevin Wolf      *
2082a9420734SKevin Wolf      * We do need a refcount table because growing the refcount table means
2083a9420734SKevin Wolf      * allocating two new refcount blocks - the seconds of which would be at
2084a9420734SKevin Wolf      * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
2085a9420734SKevin Wolf      * size for any qcow2 image.
2086a9420734SKevin Wolf      */
208723588797SKevin Wolf     BlockBackend *blk;
2088f8413b3cSKevin Wolf     QCowHeader *header;
2089b106ad91SKevin Wolf     uint64_t* refcount_table;
20903ef6c40aSMax Reitz     Error *local_err = NULL;
2091a9420734SKevin Wolf     int ret;
2092a9420734SKevin Wolf 
20930e4271b7SHu Tao     if (prealloc == PREALLOC_MODE_FULL || prealloc == PREALLOC_MODE_FALLOC) {
2094bd4b167fSMax Reitz         /* Note: The following calculation does not need to be exact; if it is a
2095bd4b167fSMax Reitz          * bit off, either some bytes will be "leaked" (which is fine) or we
2096bd4b167fSMax Reitz          * will need to increase the file size by some bytes (which is fine,
2097bd4b167fSMax Reitz          * too, as long as the bulk is allocated here). Therefore, using
2098bd4b167fSMax Reitz          * floating point arithmetic is fine. */
20990e4271b7SHu Tao         int64_t meta_size = 0;
21000e4271b7SHu Tao         uint64_t nreftablee, nrefblocke, nl1e, nl2e;
21010e4271b7SHu Tao         int64_t aligned_total_size = align_offset(total_size, cluster_size);
2102bd4b167fSMax Reitz         int refblock_bits, refblock_size;
2103bd4b167fSMax Reitz         /* refcount entry size in bytes */
2104bd4b167fSMax Reitz         double rces = (1 << refcount_order) / 8.;
2105bd4b167fSMax Reitz 
2106bd4b167fSMax Reitz         /* see qcow2_open() */
2107bd4b167fSMax Reitz         refblock_bits = cluster_bits - (refcount_order - 3);
2108bd4b167fSMax Reitz         refblock_size = 1 << refblock_bits;
21090e4271b7SHu Tao 
21100e4271b7SHu Tao         /* header: 1 cluster */
21110e4271b7SHu Tao         meta_size += cluster_size;
21120e4271b7SHu Tao 
21130e4271b7SHu Tao         /* total size of L2 tables */
21140e4271b7SHu Tao         nl2e = aligned_total_size / cluster_size;
21150e4271b7SHu Tao         nl2e = align_offset(nl2e, cluster_size / sizeof(uint64_t));
21160e4271b7SHu Tao         meta_size += nl2e * sizeof(uint64_t);
21170e4271b7SHu Tao 
21180e4271b7SHu Tao         /* total size of L1 tables */
21190e4271b7SHu Tao         nl1e = nl2e * sizeof(uint64_t) / cluster_size;
21200e4271b7SHu Tao         nl1e = align_offset(nl1e, cluster_size / sizeof(uint64_t));
21210e4271b7SHu Tao         meta_size += nl1e * sizeof(uint64_t);
21220e4271b7SHu Tao 
21230e4271b7SHu Tao         /* total size of refcount blocks
21240e4271b7SHu Tao          *
21250e4271b7SHu Tao          * note: every host cluster is reference-counted, including metadata
21260e4271b7SHu Tao          * (even refcount blocks are recursively included).
21270e4271b7SHu Tao          * Let:
21280e4271b7SHu Tao          *   a = total_size (this is the guest disk size)
21290e4271b7SHu Tao          *   m = meta size not including refcount blocks and refcount tables
21300e4271b7SHu Tao          *   c = cluster size
21310e4271b7SHu Tao          *   y1 = number of refcount blocks entries
21320e4271b7SHu Tao          *   y2 = meta size including everything
2133bd4b167fSMax Reitz          *   rces = refcount entry size in bytes
21340e4271b7SHu Tao          * then,
21350e4271b7SHu Tao          *   y1 = (y2 + a)/c
2136bd4b167fSMax Reitz          *   y2 = y1 * rces + y1 * rces * sizeof(u64) / c + m
21370e4271b7SHu Tao          * we can get y1:
2138bd4b167fSMax Reitz          *   y1 = (a + m) / (c - rces - rces * sizeof(u64) / c)
21390e4271b7SHu Tao          */
2140bd4b167fSMax Reitz         nrefblocke = (aligned_total_size + meta_size + cluster_size)
2141bd4b167fSMax Reitz                    / (cluster_size - rces - rces * sizeof(uint64_t)
2142bd4b167fSMax Reitz                                                  / cluster_size);
2143bd4b167fSMax Reitz         meta_size += DIV_ROUND_UP(nrefblocke, refblock_size) * cluster_size;
21440e4271b7SHu Tao 
21450e4271b7SHu Tao         /* total size of refcount tables */
2146bd4b167fSMax Reitz         nreftablee = nrefblocke / refblock_size;
21470e4271b7SHu Tao         nreftablee = align_offset(nreftablee, cluster_size / sizeof(uint64_t));
21480e4271b7SHu Tao         meta_size += nreftablee * sizeof(uint64_t);
21490e4271b7SHu Tao 
21500e4271b7SHu Tao         qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
215139101f25SMarkus Armbruster                             aligned_total_size + meta_size, &error_abort);
2152f43e47dbSMarkus Armbruster         qemu_opt_set(opts, BLOCK_OPT_PREALLOC, PreallocMode_lookup[prealloc],
2153f43e47dbSMarkus Armbruster                      &error_abort);
21540e4271b7SHu Tao     }
21550e4271b7SHu Tao 
2156c282e1fdSChunyan Liu     ret = bdrv_create_file(filename, opts, &local_err);
2157a9420734SKevin Wolf     if (ret < 0) {
21583ef6c40aSMax Reitz         error_propagate(errp, local_err);
2159a9420734SKevin Wolf         return ret;
2160a9420734SKevin Wolf     }
2161a9420734SKevin Wolf 
2162*efaa7c4eSMax Reitz     blk = blk_new_open(filename, NULL, NULL,
21636340472cSKevin Wolf                        BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_PROTOCOL,
21646ebf9aa2SMax Reitz                        &local_err);
216523588797SKevin Wolf     if (blk == NULL) {
21663ef6c40aSMax Reitz         error_propagate(errp, local_err);
216723588797SKevin Wolf         return -EIO;
2168a9420734SKevin Wolf     }
2169a9420734SKevin Wolf 
217023588797SKevin Wolf     blk_set_allow_write_beyond_eof(blk, true);
217123588797SKevin Wolf 
2172a9420734SKevin Wolf     /* Write the header */
2173f8413b3cSKevin Wolf     QEMU_BUILD_BUG_ON((1 << MIN_CLUSTER_BITS) < sizeof(*header));
2174f8413b3cSKevin Wolf     header = g_malloc0(cluster_size);
2175f8413b3cSKevin Wolf     *header = (QCowHeader) {
2176f8413b3cSKevin Wolf         .magic                      = cpu_to_be32(QCOW_MAGIC),
2177f8413b3cSKevin Wolf         .version                    = cpu_to_be32(version),
2178f8413b3cSKevin Wolf         .cluster_bits               = cpu_to_be32(cluster_bits),
2179f8413b3cSKevin Wolf         .size                       = cpu_to_be64(0),
2180f8413b3cSKevin Wolf         .l1_table_offset            = cpu_to_be64(0),
2181f8413b3cSKevin Wolf         .l1_size                    = cpu_to_be32(0),
2182f8413b3cSKevin Wolf         .refcount_table_offset      = cpu_to_be64(cluster_size),
2183f8413b3cSKevin Wolf         .refcount_table_clusters    = cpu_to_be32(1),
2184bd4b167fSMax Reitz         .refcount_order             = cpu_to_be32(refcount_order),
2185f8413b3cSKevin Wolf         .header_length              = cpu_to_be32(sizeof(*header)),
2186f8413b3cSKevin Wolf     };
2187a9420734SKevin Wolf 
2188a9420734SKevin Wolf     if (flags & BLOCK_FLAG_ENCRYPT) {
2189f8413b3cSKevin Wolf         header->crypt_method = cpu_to_be32(QCOW_CRYPT_AES);
2190a9420734SKevin Wolf     } else {
2191f8413b3cSKevin Wolf         header->crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
2192a9420734SKevin Wolf     }
2193a9420734SKevin Wolf 
2194bfe8043eSStefan Hajnoczi     if (flags & BLOCK_FLAG_LAZY_REFCOUNTS) {
2195f8413b3cSKevin Wolf         header->compatible_features |=
2196bfe8043eSStefan Hajnoczi             cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS);
2197bfe8043eSStefan Hajnoczi     }
2198bfe8043eSStefan Hajnoczi 
219923588797SKevin Wolf     ret = blk_pwrite(blk, 0, header, cluster_size);
2200f8413b3cSKevin Wolf     g_free(header);
2201a9420734SKevin Wolf     if (ret < 0) {
22023ef6c40aSMax Reitz         error_setg_errno(errp, -ret, "Could not write qcow2 header");
2203a9420734SKevin Wolf         goto out;
2204a9420734SKevin Wolf     }
2205a9420734SKevin Wolf 
2206b106ad91SKevin Wolf     /* Write a refcount table with one refcount block */
2207b106ad91SKevin Wolf     refcount_table = g_malloc0(2 * cluster_size);
2208b106ad91SKevin Wolf     refcount_table[0] = cpu_to_be64(2 * cluster_size);
220923588797SKevin Wolf     ret = blk_pwrite(blk, cluster_size, refcount_table, 2 * cluster_size);
22107267c094SAnthony Liguori     g_free(refcount_table);
2211a9420734SKevin Wolf 
2212a9420734SKevin Wolf     if (ret < 0) {
22133ef6c40aSMax Reitz         error_setg_errno(errp, -ret, "Could not write refcount table");
2214a9420734SKevin Wolf         goto out;
2215a9420734SKevin Wolf     }
2216a9420734SKevin Wolf 
221723588797SKevin Wolf     blk_unref(blk);
221823588797SKevin Wolf     blk = NULL;
2219a9420734SKevin Wolf 
2220a9420734SKevin Wolf     /*
2221a9420734SKevin Wolf      * And now open the image and make it consistent first (i.e. increase the
2222a9420734SKevin Wolf      * refcount of the cluster that is occupied by the header and the refcount
2223a9420734SKevin Wolf      * table)
2224a9420734SKevin Wolf      */
2225e6641719SMax Reitz     options = qdict_new();
2226e6641719SMax Reitz     qdict_put(options, "driver", qstring_from_str("qcow2"));
2227*efaa7c4eSMax Reitz     blk = blk_new_open(filename, NULL, options,
2228ef810437SMax Reitz                        BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_NO_FLUSH,
22296ebf9aa2SMax Reitz                        &local_err);
223023588797SKevin Wolf     if (blk == NULL) {
22313ef6c40aSMax Reitz         error_propagate(errp, local_err);
223223588797SKevin Wolf         ret = -EIO;
2233a9420734SKevin Wolf         goto out;
2234a9420734SKevin Wolf     }
2235a9420734SKevin Wolf 
223623588797SKevin Wolf     ret = qcow2_alloc_clusters(blk_bs(blk), 3 * cluster_size);
2237a9420734SKevin Wolf     if (ret < 0) {
22383ef6c40aSMax Reitz         error_setg_errno(errp, -ret, "Could not allocate clusters for qcow2 "
22393ef6c40aSMax Reitz                          "header and refcount table");
2240a9420734SKevin Wolf         goto out;
2241a9420734SKevin Wolf 
2242a9420734SKevin Wolf     } else if (ret != 0) {
2243a9420734SKevin Wolf         error_report("Huh, first cluster in empty image is already in use?");
2244a9420734SKevin Wolf         abort();
2245a9420734SKevin Wolf     }
2246a9420734SKevin Wolf 
2247b527c9b3SKevin Wolf     /* Create a full header (including things like feature table) */
224823588797SKevin Wolf     ret = qcow2_update_header(blk_bs(blk));
2249b527c9b3SKevin Wolf     if (ret < 0) {
2250b527c9b3SKevin Wolf         error_setg_errno(errp, -ret, "Could not update qcow2 header");
2251b527c9b3SKevin Wolf         goto out;
2252b527c9b3SKevin Wolf     }
2253b527c9b3SKevin Wolf 
2254a9420734SKevin Wolf     /* Okay, now that we have a valid image, let's give it the right size */
225523588797SKevin Wolf     ret = blk_truncate(blk, total_size);
2256a9420734SKevin Wolf     if (ret < 0) {
22573ef6c40aSMax Reitz         error_setg_errno(errp, -ret, "Could not resize image");
2258a9420734SKevin Wolf         goto out;
2259a9420734SKevin Wolf     }
2260a9420734SKevin Wolf 
2261a9420734SKevin Wolf     /* Want a backing file? There you go.*/
2262a9420734SKevin Wolf     if (backing_file) {
226323588797SKevin Wolf         ret = bdrv_change_backing_file(blk_bs(blk), backing_file, backing_format);
2264a9420734SKevin Wolf         if (ret < 0) {
22653ef6c40aSMax Reitz             error_setg_errno(errp, -ret, "Could not assign backing file '%s' "
22663ef6c40aSMax Reitz                              "with format '%s'", backing_file, backing_format);
2267a9420734SKevin Wolf             goto out;
2268a9420734SKevin Wolf         }
2269a9420734SKevin Wolf     }
2270a9420734SKevin Wolf 
2271a9420734SKevin Wolf     /* And if we're supposed to preallocate metadata, do that now */
22720e4271b7SHu Tao     if (prealloc != PREALLOC_MODE_OFF) {
227323588797SKevin Wolf         BDRVQcow2State *s = blk_bs(blk)->opaque;
227415552c4aSZhi Yong Wu         qemu_co_mutex_lock(&s->lock);
227523588797SKevin Wolf         ret = preallocate(blk_bs(blk));
227615552c4aSZhi Yong Wu         qemu_co_mutex_unlock(&s->lock);
2277a9420734SKevin Wolf         if (ret < 0) {
22783ef6c40aSMax Reitz             error_setg_errno(errp, -ret, "Could not preallocate metadata");
2279a9420734SKevin Wolf             goto out;
2280a9420734SKevin Wolf         }
2281a9420734SKevin Wolf     }
2282a9420734SKevin Wolf 
228323588797SKevin Wolf     blk_unref(blk);
228423588797SKevin Wolf     blk = NULL;
2285ba2ab2f2SMax Reitz 
2286ba2ab2f2SMax Reitz     /* Reopen the image without BDRV_O_NO_FLUSH to flush it before returning */
2287e6641719SMax Reitz     options = qdict_new();
2288e6641719SMax Reitz     qdict_put(options, "driver", qstring_from_str("qcow2"));
2289*efaa7c4eSMax Reitz     blk = blk_new_open(filename, NULL, options,
2290c9fbb99dSKevin Wolf                        BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_NO_BACKING,
22916ebf9aa2SMax Reitz                        &local_err);
229223588797SKevin Wolf     if (blk == NULL) {
2293ba2ab2f2SMax Reitz         error_propagate(errp, local_err);
229423588797SKevin Wolf         ret = -EIO;
2295ba2ab2f2SMax Reitz         goto out;
2296ba2ab2f2SMax Reitz     }
2297ba2ab2f2SMax Reitz 
2298a9420734SKevin Wolf     ret = 0;
2299a9420734SKevin Wolf out:
230023588797SKevin Wolf     if (blk) {
230123588797SKevin Wolf         blk_unref(blk);
2302f67503e5SMax Reitz     }
2303a9420734SKevin Wolf     return ret;
2304a9420734SKevin Wolf }
2305de5f3f40SKevin Wolf 
23061bd0e2d1SChunyan Liu static int qcow2_create(const char *filename, QemuOpts *opts, Error **errp)
2307de5f3f40SKevin Wolf {
23081bd0e2d1SChunyan Liu     char *backing_file = NULL;
23091bd0e2d1SChunyan Liu     char *backing_fmt = NULL;
23101bd0e2d1SChunyan Liu     char *buf = NULL;
2311180e9526SHu Tao     uint64_t size = 0;
2312de5f3f40SKevin Wolf     int flags = 0;
231399cce9faSKevin Wolf     size_t cluster_size = DEFAULT_CLUSTER_SIZE;
2314ffeaac9bSHu Tao     PreallocMode prealloc;
23158ad1898cSKevin Wolf     int version = 3;
2316bd4b167fSMax Reitz     uint64_t refcount_bits = 16;
2317bd4b167fSMax Reitz     int refcount_order;
23183ef6c40aSMax Reitz     Error *local_err = NULL;
23193ef6c40aSMax Reitz     int ret;
2320de5f3f40SKevin Wolf 
2321de5f3f40SKevin Wolf     /* Read out options */
2322180e9526SHu Tao     size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
2323c2eb918eSHu Tao                     BDRV_SECTOR_SIZE);
23241bd0e2d1SChunyan Liu     backing_file = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
23251bd0e2d1SChunyan Liu     backing_fmt = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FMT);
23261bd0e2d1SChunyan Liu     if (qemu_opt_get_bool_del(opts, BLOCK_OPT_ENCRYPT, false)) {
23271bd0e2d1SChunyan Liu         flags |= BLOCK_FLAG_ENCRYPT;
2328de5f3f40SKevin Wolf     }
23291bd0e2d1SChunyan Liu     cluster_size = qemu_opt_get_size_del(opts, BLOCK_OPT_CLUSTER_SIZE,
23301bd0e2d1SChunyan Liu                                          DEFAULT_CLUSTER_SIZE);
23311bd0e2d1SChunyan Liu     buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
2332ffeaac9bSHu Tao     prealloc = qapi_enum_parse(PreallocMode_lookup, buf,
23337fb1cf16SEric Blake                                PREALLOC_MODE__MAX, PREALLOC_MODE_OFF,
2334ffeaac9bSHu Tao                                &local_err);
2335ffeaac9bSHu Tao     if (local_err) {
2336ffeaac9bSHu Tao         error_propagate(errp, local_err);
23371bd0e2d1SChunyan Liu         ret = -EINVAL;
23381bd0e2d1SChunyan Liu         goto finish;
2339de5f3f40SKevin Wolf     }
23401bd0e2d1SChunyan Liu     g_free(buf);
23411bd0e2d1SChunyan Liu     buf = qemu_opt_get_del(opts, BLOCK_OPT_COMPAT_LEVEL);
23421bd0e2d1SChunyan Liu     if (!buf) {
23439117b477SKevin Wolf         /* keep the default */
23441bd0e2d1SChunyan Liu     } else if (!strcmp(buf, "0.10")) {
23456744cbabSKevin Wolf         version = 2;
23461bd0e2d1SChunyan Liu     } else if (!strcmp(buf, "1.1")) {
23476744cbabSKevin Wolf         version = 3;
23486744cbabSKevin Wolf     } else {
23491bd0e2d1SChunyan Liu         error_setg(errp, "Invalid compatibility level: '%s'", buf);
23501bd0e2d1SChunyan Liu         ret = -EINVAL;
23511bd0e2d1SChunyan Liu         goto finish;
23526744cbabSKevin Wolf     }
23531bd0e2d1SChunyan Liu 
23541bd0e2d1SChunyan Liu     if (qemu_opt_get_bool_del(opts, BLOCK_OPT_LAZY_REFCOUNTS, false)) {
23551bd0e2d1SChunyan Liu         flags |= BLOCK_FLAG_LAZY_REFCOUNTS;
2356de5f3f40SKevin Wolf     }
2357de5f3f40SKevin Wolf 
2358ffeaac9bSHu Tao     if (backing_file && prealloc != PREALLOC_MODE_OFF) {
23593ef6c40aSMax Reitz         error_setg(errp, "Backing file and preallocation cannot be used at "
23603ef6c40aSMax Reitz                    "the same time");
23611bd0e2d1SChunyan Liu         ret = -EINVAL;
23621bd0e2d1SChunyan Liu         goto finish;
2363de5f3f40SKevin Wolf     }
2364de5f3f40SKevin Wolf 
2365bfe8043eSStefan Hajnoczi     if (version < 3 && (flags & BLOCK_FLAG_LAZY_REFCOUNTS)) {
23663ef6c40aSMax Reitz         error_setg(errp, "Lazy refcounts only supported with compatibility "
23673ef6c40aSMax Reitz                    "level 1.1 and above (use compat=1.1 or greater)");
23681bd0e2d1SChunyan Liu         ret = -EINVAL;
23691bd0e2d1SChunyan Liu         goto finish;
2370bfe8043eSStefan Hajnoczi     }
2371bfe8043eSStefan Hajnoczi 
237206d05fa7SMax Reitz     refcount_bits = qemu_opt_get_number_del(opts, BLOCK_OPT_REFCOUNT_BITS,
237306d05fa7SMax Reitz                                             refcount_bits);
237406d05fa7SMax Reitz     if (refcount_bits > 64 || !is_power_of_2(refcount_bits)) {
237506d05fa7SMax Reitz         error_setg(errp, "Refcount width must be a power of two and may not "
237606d05fa7SMax Reitz                    "exceed 64 bits");
237706d05fa7SMax Reitz         ret = -EINVAL;
237806d05fa7SMax Reitz         goto finish;
237906d05fa7SMax Reitz     }
238006d05fa7SMax Reitz 
2381bd4b167fSMax Reitz     if (version < 3 && refcount_bits != 16) {
2382bd4b167fSMax Reitz         error_setg(errp, "Different refcount widths than 16 bits require "
2383bd4b167fSMax Reitz                    "compatibility level 1.1 or above (use compat=1.1 or "
2384bd4b167fSMax Reitz                    "greater)");
2385bd4b167fSMax Reitz         ret = -EINVAL;
2386bd4b167fSMax Reitz         goto finish;
2387bd4b167fSMax Reitz     }
2388bd4b167fSMax Reitz 
2389786a4ea8SStefan Hajnoczi     refcount_order = ctz32(refcount_bits);
2390bd4b167fSMax Reitz 
2391180e9526SHu Tao     ret = qcow2_create2(filename, size, backing_file, backing_fmt, flags,
2392bd4b167fSMax Reitz                         cluster_size, prealloc, opts, version, refcount_order,
2393bd4b167fSMax Reitz                         &local_err);
239484d18f06SMarkus Armbruster     if (local_err) {
23953ef6c40aSMax Reitz         error_propagate(errp, local_err);
23963ef6c40aSMax Reitz     }
23971bd0e2d1SChunyan Liu 
23981bd0e2d1SChunyan Liu finish:
23991bd0e2d1SChunyan Liu     g_free(backing_file);
24001bd0e2d1SChunyan Liu     g_free(backing_fmt);
24011bd0e2d1SChunyan Liu     g_free(buf);
24023ef6c40aSMax Reitz     return ret;
2403de5f3f40SKevin Wolf }
2404de5f3f40SKevin Wolf 
2405621f0589SKevin Wolf static coroutine_fn int qcow2_co_write_zeroes(BlockDriverState *bs,
2406aa7bfbffSPeter Lieven     int64_t sector_num, int nb_sectors, BdrvRequestFlags flags)
2407621f0589SKevin Wolf {
2408621f0589SKevin Wolf     int ret;
2409ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
2410621f0589SKevin Wolf 
2411621f0589SKevin Wolf     /* Emulate misaligned zero writes */
2412621f0589SKevin Wolf     if (sector_num % s->cluster_sectors || nb_sectors % s->cluster_sectors) {
2413621f0589SKevin Wolf         return -ENOTSUP;
2414621f0589SKevin Wolf     }
2415621f0589SKevin Wolf 
2416621f0589SKevin Wolf     /* Whatever is left can use real zero clusters */
2417621f0589SKevin Wolf     qemu_co_mutex_lock(&s->lock);
2418621f0589SKevin Wolf     ret = qcow2_zero_clusters(bs, sector_num << BDRV_SECTOR_BITS,
2419621f0589SKevin Wolf         nb_sectors);
2420621f0589SKevin Wolf     qemu_co_mutex_unlock(&s->lock);
2421621f0589SKevin Wolf 
2422621f0589SKevin Wolf     return ret;
2423621f0589SKevin Wolf }
2424621f0589SKevin Wolf 
24256db39ae2SPaolo Bonzini static coroutine_fn int qcow2_co_discard(BlockDriverState *bs,
24266db39ae2SPaolo Bonzini     int64_t sector_num, int nb_sectors)
24275ea929e3SKevin Wolf {
24286db39ae2SPaolo Bonzini     int ret;
2429ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
24306db39ae2SPaolo Bonzini 
24316db39ae2SPaolo Bonzini     qemu_co_mutex_lock(&s->lock);
24326db39ae2SPaolo Bonzini     ret = qcow2_discard_clusters(bs, sector_num << BDRV_SECTOR_BITS,
2433808c4b6fSMax Reitz         nb_sectors, QCOW2_DISCARD_REQUEST, false);
24346db39ae2SPaolo Bonzini     qemu_co_mutex_unlock(&s->lock);
24356db39ae2SPaolo Bonzini     return ret;
24365ea929e3SKevin Wolf }
24375ea929e3SKevin Wolf 
2438419b19d9SStefan Hajnoczi static int qcow2_truncate(BlockDriverState *bs, int64_t offset)
2439419b19d9SStefan Hajnoczi {
2440ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
24412cf7cfa1SKevin Wolf     int64_t new_l1_size;
24422cf7cfa1SKevin Wolf     int ret;
2443419b19d9SStefan Hajnoczi 
2444419b19d9SStefan Hajnoczi     if (offset & 511) {
2445259b2173SKevin Wolf         error_report("The new size must be a multiple of 512");
2446419b19d9SStefan Hajnoczi         return -EINVAL;
2447419b19d9SStefan Hajnoczi     }
2448419b19d9SStefan Hajnoczi 
2449419b19d9SStefan Hajnoczi     /* cannot proceed if image has snapshots */
2450419b19d9SStefan Hajnoczi     if (s->nb_snapshots) {
2451259b2173SKevin Wolf         error_report("Can't resize an image which has snapshots");
2452419b19d9SStefan Hajnoczi         return -ENOTSUP;
2453419b19d9SStefan Hajnoczi     }
2454419b19d9SStefan Hajnoczi 
2455419b19d9SStefan Hajnoczi     /* shrinking is currently not supported */
2456419b19d9SStefan Hajnoczi     if (offset < bs->total_sectors * 512) {
2457259b2173SKevin Wolf         error_report("qcow2 doesn't support shrinking images yet");
2458419b19d9SStefan Hajnoczi         return -ENOTSUP;
2459419b19d9SStefan Hajnoczi     }
2460419b19d9SStefan Hajnoczi 
2461419b19d9SStefan Hajnoczi     new_l1_size = size_to_l1(s, offset);
246272893756SStefan Hajnoczi     ret = qcow2_grow_l1_table(bs, new_l1_size, true);
2463419b19d9SStefan Hajnoczi     if (ret < 0) {
2464419b19d9SStefan Hajnoczi         return ret;
2465419b19d9SStefan Hajnoczi     }
2466419b19d9SStefan Hajnoczi 
2467419b19d9SStefan Hajnoczi     /* write updated header.size */
2468419b19d9SStefan Hajnoczi     offset = cpu_to_be64(offset);
24699a4f4c31SKevin Wolf     ret = bdrv_pwrite_sync(bs->file->bs, offsetof(QCowHeader, size),
2470419b19d9SStefan Hajnoczi                            &offset, sizeof(uint64_t));
2471419b19d9SStefan Hajnoczi     if (ret < 0) {
2472419b19d9SStefan Hajnoczi         return ret;
2473419b19d9SStefan Hajnoczi     }
2474419b19d9SStefan Hajnoczi 
2475419b19d9SStefan Hajnoczi     s->l1_vm_state_index = new_l1_size;
2476419b19d9SStefan Hajnoczi     return 0;
2477419b19d9SStefan Hajnoczi }
2478419b19d9SStefan Hajnoczi 
247920d97356SBlue Swirl /* XXX: put compressed sectors first, then all the cluster aligned
248020d97356SBlue Swirl    tables to avoid losing bytes in alignment */
24817c80ab3fSJes Sorensen static int qcow2_write_compressed(BlockDriverState *bs, int64_t sector_num,
248220d97356SBlue Swirl                                   const uint8_t *buf, int nb_sectors)
248320d97356SBlue Swirl {
2484ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
248520d97356SBlue Swirl     z_stream strm;
248620d97356SBlue Swirl     int ret, out_len;
248720d97356SBlue Swirl     uint8_t *out_buf;
248820d97356SBlue Swirl     uint64_t cluster_offset;
248920d97356SBlue Swirl 
249020d97356SBlue Swirl     if (nb_sectors == 0) {
249120d97356SBlue Swirl         /* align end of file to a sector boundary to ease reading with
249220d97356SBlue Swirl            sector based I/Os */
24939a4f4c31SKevin Wolf         cluster_offset = bdrv_getlength(bs->file->bs);
24949a4f4c31SKevin Wolf         return bdrv_truncate(bs->file->bs, cluster_offset);
249520d97356SBlue Swirl     }
249620d97356SBlue Swirl 
2497f4d38befSStefan Hajnoczi     if (nb_sectors != s->cluster_sectors) {
2498f4d38befSStefan Hajnoczi         ret = -EINVAL;
2499f4d38befSStefan Hajnoczi 
2500f4d38befSStefan Hajnoczi         /* Zero-pad last write if image size is not cluster aligned */
2501f4d38befSStefan Hajnoczi         if (sector_num + nb_sectors == bs->total_sectors &&
2502f4d38befSStefan Hajnoczi             nb_sectors < s->cluster_sectors) {
2503f4d38befSStefan Hajnoczi             uint8_t *pad_buf = qemu_blockalign(bs, s->cluster_size);
2504f4d38befSStefan Hajnoczi             memset(pad_buf, 0, s->cluster_size);
2505f4d38befSStefan Hajnoczi             memcpy(pad_buf, buf, nb_sectors * BDRV_SECTOR_SIZE);
2506f4d38befSStefan Hajnoczi             ret = qcow2_write_compressed(bs, sector_num,
2507f4d38befSStefan Hajnoczi                                          pad_buf, s->cluster_sectors);
2508f4d38befSStefan Hajnoczi             qemu_vfree(pad_buf);
2509f4d38befSStefan Hajnoczi         }
2510f4d38befSStefan Hajnoczi         return ret;
2511f4d38befSStefan Hajnoczi     }
251220d97356SBlue Swirl 
25137267c094SAnthony Liguori     out_buf = g_malloc(s->cluster_size + (s->cluster_size / 1000) + 128);
251420d97356SBlue Swirl 
251520d97356SBlue Swirl     /* best compression, small window, no zlib header */
251620d97356SBlue Swirl     memset(&strm, 0, sizeof(strm));
251720d97356SBlue Swirl     ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
251820d97356SBlue Swirl                        Z_DEFLATED, -12,
251920d97356SBlue Swirl                        9, Z_DEFAULT_STRATEGY);
252020d97356SBlue Swirl     if (ret != 0) {
25218f1efd00SKevin Wolf         ret = -EINVAL;
25228f1efd00SKevin Wolf         goto fail;
252320d97356SBlue Swirl     }
252420d97356SBlue Swirl 
252520d97356SBlue Swirl     strm.avail_in = s->cluster_size;
252620d97356SBlue Swirl     strm.next_in = (uint8_t *)buf;
252720d97356SBlue Swirl     strm.avail_out = s->cluster_size;
252820d97356SBlue Swirl     strm.next_out = out_buf;
252920d97356SBlue Swirl 
253020d97356SBlue Swirl     ret = deflate(&strm, Z_FINISH);
253120d97356SBlue Swirl     if (ret != Z_STREAM_END && ret != Z_OK) {
253220d97356SBlue Swirl         deflateEnd(&strm);
25338f1efd00SKevin Wolf         ret = -EINVAL;
25348f1efd00SKevin Wolf         goto fail;
253520d97356SBlue Swirl     }
253620d97356SBlue Swirl     out_len = strm.next_out - out_buf;
253720d97356SBlue Swirl 
253820d97356SBlue Swirl     deflateEnd(&strm);
253920d97356SBlue Swirl 
254020d97356SBlue Swirl     if (ret != Z_STREAM_END || out_len >= s->cluster_size) {
254120d97356SBlue Swirl         /* could not compress: write normal cluster */
25428f1efd00SKevin Wolf         ret = bdrv_write(bs, sector_num, buf, s->cluster_sectors);
25438f1efd00SKevin Wolf         if (ret < 0) {
25448f1efd00SKevin Wolf             goto fail;
25458f1efd00SKevin Wolf         }
254620d97356SBlue Swirl     } else {
254720d97356SBlue Swirl         cluster_offset = qcow2_alloc_compressed_cluster_offset(bs,
254820d97356SBlue Swirl             sector_num << 9, out_len);
25498f1efd00SKevin Wolf         if (!cluster_offset) {
25508f1efd00SKevin Wolf             ret = -EIO;
25518f1efd00SKevin Wolf             goto fail;
25528f1efd00SKevin Wolf         }
255320d97356SBlue Swirl         cluster_offset &= s->cluster_offset_mask;
2554cf93980eSMax Reitz 
2555231bb267SMax Reitz         ret = qcow2_pre_write_overlap_check(bs, 0, cluster_offset, out_len);
2556cf93980eSMax Reitz         if (ret < 0) {
2557cf93980eSMax Reitz             goto fail;
2558cf93980eSMax Reitz         }
2559cf93980eSMax Reitz 
256066f82ceeSKevin Wolf         BLKDBG_EVENT(bs->file, BLKDBG_WRITE_COMPRESSED);
25619a4f4c31SKevin Wolf         ret = bdrv_pwrite(bs->file->bs, cluster_offset, out_buf, out_len);
25628f1efd00SKevin Wolf         if (ret < 0) {
25638f1efd00SKevin Wolf             goto fail;
256420d97356SBlue Swirl         }
256520d97356SBlue Swirl     }
256620d97356SBlue Swirl 
25678f1efd00SKevin Wolf     ret = 0;
25688f1efd00SKevin Wolf fail:
25697267c094SAnthony Liguori     g_free(out_buf);
25708f1efd00SKevin Wolf     return ret;
257120d97356SBlue Swirl }
257220d97356SBlue Swirl 
257394054183SMax Reitz static int make_completely_empty(BlockDriverState *bs)
257494054183SMax Reitz {
2575ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
257694054183SMax Reitz     int ret, l1_clusters;
257794054183SMax Reitz     int64_t offset;
257894054183SMax Reitz     uint64_t *new_reftable = NULL;
257994054183SMax Reitz     uint64_t rt_entry, l1_size2;
258094054183SMax Reitz     struct {
258194054183SMax Reitz         uint64_t l1_offset;
258294054183SMax Reitz         uint64_t reftable_offset;
258394054183SMax Reitz         uint32_t reftable_clusters;
258494054183SMax Reitz     } QEMU_PACKED l1_ofs_rt_ofs_cls;
258594054183SMax Reitz 
258694054183SMax Reitz     ret = qcow2_cache_empty(bs, s->l2_table_cache);
258794054183SMax Reitz     if (ret < 0) {
258894054183SMax Reitz         goto fail;
258994054183SMax Reitz     }
259094054183SMax Reitz 
259194054183SMax Reitz     ret = qcow2_cache_empty(bs, s->refcount_block_cache);
259294054183SMax Reitz     if (ret < 0) {
259394054183SMax Reitz         goto fail;
259494054183SMax Reitz     }
259594054183SMax Reitz 
259694054183SMax Reitz     /* Refcounts will be broken utterly */
259794054183SMax Reitz     ret = qcow2_mark_dirty(bs);
259894054183SMax Reitz     if (ret < 0) {
259994054183SMax Reitz         goto fail;
260094054183SMax Reitz     }
260194054183SMax Reitz 
260294054183SMax Reitz     BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
260394054183SMax Reitz 
260494054183SMax Reitz     l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / sizeof(uint64_t));
260594054183SMax Reitz     l1_size2 = (uint64_t)s->l1_size * sizeof(uint64_t);
260694054183SMax Reitz 
260794054183SMax Reitz     /* After this call, neither the in-memory nor the on-disk refcount
260894054183SMax Reitz      * information accurately describe the actual references */
260994054183SMax Reitz 
26109a4f4c31SKevin Wolf     ret = bdrv_write_zeroes(bs->file->bs, s->l1_table_offset / BDRV_SECTOR_SIZE,
261194054183SMax Reitz                             l1_clusters * s->cluster_sectors, 0);
261294054183SMax Reitz     if (ret < 0) {
261394054183SMax Reitz         goto fail_broken_refcounts;
261494054183SMax Reitz     }
261594054183SMax Reitz     memset(s->l1_table, 0, l1_size2);
261694054183SMax Reitz 
261794054183SMax Reitz     BLKDBG_EVENT(bs->file, BLKDBG_EMPTY_IMAGE_PREPARE);
261894054183SMax Reitz 
261994054183SMax Reitz     /* Overwrite enough clusters at the beginning of the sectors to place
262094054183SMax Reitz      * the refcount table, a refcount block and the L1 table in; this may
262194054183SMax Reitz      * overwrite parts of the existing refcount and L1 table, which is not
262294054183SMax Reitz      * an issue because the dirty flag is set, complete data loss is in fact
262394054183SMax Reitz      * desired and partial data loss is consequently fine as well */
26249a4f4c31SKevin Wolf     ret = bdrv_write_zeroes(bs->file->bs, s->cluster_size / BDRV_SECTOR_SIZE,
262594054183SMax Reitz                             (2 + l1_clusters) * s->cluster_size /
262694054183SMax Reitz                             BDRV_SECTOR_SIZE, 0);
262794054183SMax Reitz     /* This call (even if it failed overall) may have overwritten on-disk
262894054183SMax Reitz      * refcount structures; in that case, the in-memory refcount information
262994054183SMax Reitz      * will probably differ from the on-disk information which makes the BDS
263094054183SMax Reitz      * unusable */
263194054183SMax Reitz     if (ret < 0) {
263294054183SMax Reitz         goto fail_broken_refcounts;
263394054183SMax Reitz     }
263494054183SMax Reitz 
263594054183SMax Reitz     BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
263694054183SMax Reitz     BLKDBG_EVENT(bs->file, BLKDBG_REFTABLE_UPDATE);
263794054183SMax Reitz 
263894054183SMax Reitz     /* "Create" an empty reftable (one cluster) directly after the image
263994054183SMax Reitz      * header and an empty L1 table three clusters after the image header;
264094054183SMax Reitz      * the cluster between those two will be used as the first refblock */
264194054183SMax Reitz     cpu_to_be64w(&l1_ofs_rt_ofs_cls.l1_offset, 3 * s->cluster_size);
264294054183SMax Reitz     cpu_to_be64w(&l1_ofs_rt_ofs_cls.reftable_offset, s->cluster_size);
264394054183SMax Reitz     cpu_to_be32w(&l1_ofs_rt_ofs_cls.reftable_clusters, 1);
26449a4f4c31SKevin Wolf     ret = bdrv_pwrite_sync(bs->file->bs, offsetof(QCowHeader, l1_table_offset),
264594054183SMax Reitz                            &l1_ofs_rt_ofs_cls, sizeof(l1_ofs_rt_ofs_cls));
264694054183SMax Reitz     if (ret < 0) {
264794054183SMax Reitz         goto fail_broken_refcounts;
264894054183SMax Reitz     }
264994054183SMax Reitz 
265094054183SMax Reitz     s->l1_table_offset = 3 * s->cluster_size;
265194054183SMax Reitz 
265294054183SMax Reitz     new_reftable = g_try_new0(uint64_t, s->cluster_size / sizeof(uint64_t));
265394054183SMax Reitz     if (!new_reftable) {
265494054183SMax Reitz         ret = -ENOMEM;
265594054183SMax Reitz         goto fail_broken_refcounts;
265694054183SMax Reitz     }
265794054183SMax Reitz 
265894054183SMax Reitz     s->refcount_table_offset = s->cluster_size;
265994054183SMax Reitz     s->refcount_table_size   = s->cluster_size / sizeof(uint64_t);
266094054183SMax Reitz 
266194054183SMax Reitz     g_free(s->refcount_table);
266294054183SMax Reitz     s->refcount_table = new_reftable;
266394054183SMax Reitz     new_reftable = NULL;
266494054183SMax Reitz 
266594054183SMax Reitz     /* Now the in-memory refcount information again corresponds to the on-disk
266694054183SMax Reitz      * information (reftable is empty and no refblocks (the refblock cache is
266794054183SMax Reitz      * empty)); however, this means some clusters (e.g. the image header) are
266894054183SMax Reitz      * referenced, but not refcounted, but the normal qcow2 code assumes that
266994054183SMax Reitz      * the in-memory information is always correct */
267094054183SMax Reitz 
267194054183SMax Reitz     BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_ALLOC);
267294054183SMax Reitz 
267394054183SMax Reitz     /* Enter the first refblock into the reftable */
267494054183SMax Reitz     rt_entry = cpu_to_be64(2 * s->cluster_size);
26759a4f4c31SKevin Wolf     ret = bdrv_pwrite_sync(bs->file->bs, s->cluster_size,
267694054183SMax Reitz                            &rt_entry, sizeof(rt_entry));
267794054183SMax Reitz     if (ret < 0) {
267894054183SMax Reitz         goto fail_broken_refcounts;
267994054183SMax Reitz     }
268094054183SMax Reitz     s->refcount_table[0] = 2 * s->cluster_size;
268194054183SMax Reitz 
268294054183SMax Reitz     s->free_cluster_index = 0;
268394054183SMax Reitz     assert(3 + l1_clusters <= s->refcount_block_size);
268494054183SMax Reitz     offset = qcow2_alloc_clusters(bs, 3 * s->cluster_size + l1_size2);
268594054183SMax Reitz     if (offset < 0) {
268694054183SMax Reitz         ret = offset;
268794054183SMax Reitz         goto fail_broken_refcounts;
268894054183SMax Reitz     } else if (offset > 0) {
268994054183SMax Reitz         error_report("First cluster in emptied image is in use");
269094054183SMax Reitz         abort();
269194054183SMax Reitz     }
269294054183SMax Reitz 
269394054183SMax Reitz     /* Now finally the in-memory information corresponds to the on-disk
269494054183SMax Reitz      * structures and is correct */
269594054183SMax Reitz     ret = qcow2_mark_clean(bs);
269694054183SMax Reitz     if (ret < 0) {
269794054183SMax Reitz         goto fail;
269894054183SMax Reitz     }
269994054183SMax Reitz 
27009a4f4c31SKevin Wolf     ret = bdrv_truncate(bs->file->bs, (3 + l1_clusters) * s->cluster_size);
270194054183SMax Reitz     if (ret < 0) {
270294054183SMax Reitz         goto fail;
270394054183SMax Reitz     }
270494054183SMax Reitz 
270594054183SMax Reitz     return 0;
270694054183SMax Reitz 
270794054183SMax Reitz fail_broken_refcounts:
270894054183SMax Reitz     /* The BDS is unusable at this point. If we wanted to make it usable, we
270994054183SMax Reitz      * would have to call qcow2_refcount_close(), qcow2_refcount_init(),
271094054183SMax Reitz      * qcow2_check_refcounts(), qcow2_refcount_close() and qcow2_refcount_init()
271194054183SMax Reitz      * again. However, because the functions which could have caused this error
271294054183SMax Reitz      * path to be taken are used by those functions as well, it's very likely
271394054183SMax Reitz      * that that sequence will fail as well. Therefore, just eject the BDS. */
271494054183SMax Reitz     bs->drv = NULL;
271594054183SMax Reitz 
271694054183SMax Reitz fail:
271794054183SMax Reitz     g_free(new_reftable);
271894054183SMax Reitz     return ret;
271994054183SMax Reitz }
272094054183SMax Reitz 
2721491d27e2SMax Reitz static int qcow2_make_empty(BlockDriverState *bs)
2722491d27e2SMax Reitz {
2723ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
2724491d27e2SMax Reitz     uint64_t start_sector;
2725491d27e2SMax Reitz     int sector_step = INT_MAX / BDRV_SECTOR_SIZE;
272694054183SMax Reitz     int l1_clusters, ret = 0;
2727491d27e2SMax Reitz 
272894054183SMax Reitz     l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / sizeof(uint64_t));
272994054183SMax Reitz 
273094054183SMax Reitz     if (s->qcow_version >= 3 && !s->snapshots &&
273194054183SMax Reitz         3 + l1_clusters <= s->refcount_block_size) {
273294054183SMax Reitz         /* The following function only works for qcow2 v3 images (it requires
273394054183SMax Reitz          * the dirty flag) and only as long as there are no snapshots (because
273494054183SMax Reitz          * it completely empties the image). Furthermore, the L1 table and three
273594054183SMax Reitz          * additional clusters (image header, refcount table, one refcount
273694054183SMax Reitz          * block) have to fit inside one refcount block. */
273794054183SMax Reitz         return make_completely_empty(bs);
273894054183SMax Reitz     }
273994054183SMax Reitz 
274094054183SMax Reitz     /* This fallback code simply discards every active cluster; this is slow,
274194054183SMax Reitz      * but works in all cases */
2742491d27e2SMax Reitz     for (start_sector = 0; start_sector < bs->total_sectors;
2743491d27e2SMax Reitz          start_sector += sector_step)
2744491d27e2SMax Reitz     {
2745491d27e2SMax Reitz         /* As this function is generally used after committing an external
2746491d27e2SMax Reitz          * snapshot, QCOW2_DISCARD_SNAPSHOT seems appropriate. Also, the
2747491d27e2SMax Reitz          * default action for this kind of discard is to pass the discard,
2748491d27e2SMax Reitz          * which will ideally result in an actually smaller image file, as
2749491d27e2SMax Reitz          * is probably desired. */
2750491d27e2SMax Reitz         ret = qcow2_discard_clusters(bs, start_sector * BDRV_SECTOR_SIZE,
2751491d27e2SMax Reitz                                      MIN(sector_step,
2752491d27e2SMax Reitz                                          bs->total_sectors - start_sector),
2753491d27e2SMax Reitz                                      QCOW2_DISCARD_SNAPSHOT, true);
2754491d27e2SMax Reitz         if (ret < 0) {
2755491d27e2SMax Reitz             break;
2756491d27e2SMax Reitz         }
2757491d27e2SMax Reitz     }
2758491d27e2SMax Reitz 
2759491d27e2SMax Reitz     return ret;
2760491d27e2SMax Reitz }
2761491d27e2SMax Reitz 
2762a968168cSDong Xu Wang static coroutine_fn int qcow2_co_flush_to_os(BlockDriverState *bs)
276320d97356SBlue Swirl {
2764ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
276529c1a730SKevin Wolf     int ret;
276629c1a730SKevin Wolf 
27678b94ff85SPaolo Bonzini     qemu_co_mutex_lock(&s->lock);
276829c1a730SKevin Wolf     ret = qcow2_cache_flush(bs, s->l2_table_cache);
276929c1a730SKevin Wolf     if (ret < 0) {
2770c95de7e2SDong Xu Wang         qemu_co_mutex_unlock(&s->lock);
27718b94ff85SPaolo Bonzini         return ret;
277229c1a730SKevin Wolf     }
277329c1a730SKevin Wolf 
2774bfe8043eSStefan Hajnoczi     if (qcow2_need_accurate_refcounts(s)) {
277529c1a730SKevin Wolf         ret = qcow2_cache_flush(bs, s->refcount_block_cache);
277629c1a730SKevin Wolf         if (ret < 0) {
2777c95de7e2SDong Xu Wang             qemu_co_mutex_unlock(&s->lock);
27788b94ff85SPaolo Bonzini             return ret;
277929c1a730SKevin Wolf         }
2780bfe8043eSStefan Hajnoczi     }
27818b94ff85SPaolo Bonzini     qemu_co_mutex_unlock(&s->lock);
278229c1a730SKevin Wolf 
2783eb489bb1SKevin Wolf     return 0;
2784eb489bb1SKevin Wolf }
2785eb489bb1SKevin Wolf 
27867c80ab3fSJes Sorensen static int qcow2_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
278720d97356SBlue Swirl {
2788ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
278995de6d70SPaolo Bonzini     bdi->unallocated_blocks_are_zero = true;
279095de6d70SPaolo Bonzini     bdi->can_write_zeroes_with_unmap = (s->qcow_version >= 3);
279120d97356SBlue Swirl     bdi->cluster_size = s->cluster_size;
27927c80ab3fSJes Sorensen     bdi->vm_state_offset = qcow2_vm_state_offset(s);
279320d97356SBlue Swirl     return 0;
279420d97356SBlue Swirl }
279520d97356SBlue Swirl 
279637764dfbSMax Reitz static ImageInfoSpecific *qcow2_get_specific_info(BlockDriverState *bs)
279737764dfbSMax Reitz {
2798ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
279937764dfbSMax Reitz     ImageInfoSpecific *spec_info = g_new(ImageInfoSpecific, 1);
280037764dfbSMax Reitz 
280137764dfbSMax Reitz     *spec_info = (ImageInfoSpecific){
28026a8f9661SEric Blake         .type  = IMAGE_INFO_SPECIFIC_KIND_QCOW2,
28036a8f9661SEric Blake         .u.qcow2 = g_new(ImageInfoSpecificQCow2, 1),
280437764dfbSMax Reitz     };
280537764dfbSMax Reitz     if (s->qcow_version == 2) {
28066a8f9661SEric Blake         *spec_info->u.qcow2 = (ImageInfoSpecificQCow2){
280737764dfbSMax Reitz             .compat             = g_strdup("0.10"),
28080709c5a1SMax Reitz             .refcount_bits      = s->refcount_bits,
280937764dfbSMax Reitz         };
281037764dfbSMax Reitz     } else if (s->qcow_version == 3) {
28116a8f9661SEric Blake         *spec_info->u.qcow2 = (ImageInfoSpecificQCow2){
281237764dfbSMax Reitz             .compat             = g_strdup("1.1"),
281337764dfbSMax Reitz             .lazy_refcounts     = s->compatible_features &
281437764dfbSMax Reitz                                   QCOW2_COMPAT_LAZY_REFCOUNTS,
281537764dfbSMax Reitz             .has_lazy_refcounts = true,
28169009b196SMax Reitz             .corrupt            = s->incompatible_features &
28179009b196SMax Reitz                                   QCOW2_INCOMPAT_CORRUPT,
28189009b196SMax Reitz             .has_corrupt        = true,
28190709c5a1SMax Reitz             .refcount_bits      = s->refcount_bits,
282037764dfbSMax Reitz         };
2821b1fc8f93SDenis V. Lunev     } else {
2822b1fc8f93SDenis V. Lunev         /* if this assertion fails, this probably means a new version was
2823b1fc8f93SDenis V. Lunev          * added without having it covered here */
2824b1fc8f93SDenis V. Lunev         assert(false);
282537764dfbSMax Reitz     }
282637764dfbSMax Reitz 
282737764dfbSMax Reitz     return spec_info;
282837764dfbSMax Reitz }
282937764dfbSMax Reitz 
283020d97356SBlue Swirl #if 0
283120d97356SBlue Swirl static void dump_refcounts(BlockDriverState *bs)
283220d97356SBlue Swirl {
2833ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
283420d97356SBlue Swirl     int64_t nb_clusters, k, k1, size;
283520d97356SBlue Swirl     int refcount;
283620d97356SBlue Swirl 
28379a4f4c31SKevin Wolf     size = bdrv_getlength(bs->file->bs);
283820d97356SBlue Swirl     nb_clusters = size_to_clusters(s, size);
283920d97356SBlue Swirl     for(k = 0; k < nb_clusters;) {
284020d97356SBlue Swirl         k1 = k;
284120d97356SBlue Swirl         refcount = get_refcount(bs, k);
284220d97356SBlue Swirl         k++;
284320d97356SBlue Swirl         while (k < nb_clusters && get_refcount(bs, k) == refcount)
284420d97356SBlue Swirl             k++;
28450bfcd599SBlue Swirl         printf("%" PRId64 ": refcount=%d nb=%" PRId64 "\n", k, refcount,
28460bfcd599SBlue Swirl                k - k1);
284720d97356SBlue Swirl     }
284820d97356SBlue Swirl }
284920d97356SBlue Swirl #endif
285020d97356SBlue Swirl 
2851cf8074b3SKevin Wolf static int qcow2_save_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
2852cf8074b3SKevin Wolf                               int64_t pos)
285320d97356SBlue Swirl {
2854ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
2855eedff66fSMax Reitz     int64_t total_sectors = bs->total_sectors;
28566e13610aSMax Reitz     bool zero_beyond_eof = bs->zero_beyond_eof;
285720d97356SBlue Swirl     int ret;
285820d97356SBlue Swirl 
285966f82ceeSKevin Wolf     BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_SAVE);
28606e13610aSMax Reitz     bs->zero_beyond_eof = false;
28618d3b1a2dSKevin Wolf     ret = bdrv_pwritev(bs, qcow2_vm_state_offset(s) + pos, qiov);
28626e13610aSMax Reitz     bs->zero_beyond_eof = zero_beyond_eof;
286320d97356SBlue Swirl 
2864eedff66fSMax Reitz     /* bdrv_co_do_writev will have increased the total_sectors value to include
2865eedff66fSMax Reitz      * the VM state - the VM state is however not an actual part of the block
2866eedff66fSMax Reitz      * device, therefore, we need to restore the old value. */
2867eedff66fSMax Reitz     bs->total_sectors = total_sectors;
2868eedff66fSMax Reitz 
286920d97356SBlue Swirl     return ret;
287020d97356SBlue Swirl }
287120d97356SBlue Swirl 
28727c80ab3fSJes Sorensen static int qcow2_load_vmstate(BlockDriverState *bs, uint8_t *buf,
287320d97356SBlue Swirl                               int64_t pos, int size)
287420d97356SBlue Swirl {
2875ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
28760d51b4deSAsias He     bool zero_beyond_eof = bs->zero_beyond_eof;
287720d97356SBlue Swirl     int ret;
287820d97356SBlue Swirl 
287966f82ceeSKevin Wolf     BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_LOAD);
28800d51b4deSAsias He     bs->zero_beyond_eof = false;
28817c80ab3fSJes Sorensen     ret = bdrv_pread(bs, qcow2_vm_state_offset(s) + pos, buf, size);
28820d51b4deSAsias He     bs->zero_beyond_eof = zero_beyond_eof;
288320d97356SBlue Swirl 
288420d97356SBlue Swirl     return ret;
288520d97356SBlue Swirl }
288620d97356SBlue Swirl 
28879296b3edSMax Reitz /*
28889296b3edSMax Reitz  * Downgrades an image's version. To achieve this, any incompatible features
28899296b3edSMax Reitz  * have to be removed.
28909296b3edSMax Reitz  */
28914057a2b2SMax Reitz static int qcow2_downgrade(BlockDriverState *bs, int target_version,
28928b13976dSMax Reitz                            BlockDriverAmendStatusCB *status_cb, void *cb_opaque)
28939296b3edSMax Reitz {
2894ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
28959296b3edSMax Reitz     int current_version = s->qcow_version;
28969296b3edSMax Reitz     int ret;
28979296b3edSMax Reitz 
28989296b3edSMax Reitz     if (target_version == current_version) {
28999296b3edSMax Reitz         return 0;
29009296b3edSMax Reitz     } else if (target_version > current_version) {
29019296b3edSMax Reitz         return -EINVAL;
29029296b3edSMax Reitz     } else if (target_version != 2) {
29039296b3edSMax Reitz         return -EINVAL;
29049296b3edSMax Reitz     }
29059296b3edSMax Reitz 
29069296b3edSMax Reitz     if (s->refcount_order != 4) {
290761ce55fcSMax Reitz         error_report("compat=0.10 requires refcount_bits=16");
29089296b3edSMax Reitz         return -ENOTSUP;
29099296b3edSMax Reitz     }
29109296b3edSMax Reitz 
29119296b3edSMax Reitz     /* clear incompatible features */
29129296b3edSMax Reitz     if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
29139296b3edSMax Reitz         ret = qcow2_mark_clean(bs);
29149296b3edSMax Reitz         if (ret < 0) {
29159296b3edSMax Reitz             return ret;
29169296b3edSMax Reitz         }
29179296b3edSMax Reitz     }
29189296b3edSMax Reitz 
29199296b3edSMax Reitz     /* with QCOW2_INCOMPAT_CORRUPT, it is pretty much impossible to get here in
29209296b3edSMax Reitz      * the first place; if that happens nonetheless, returning -ENOTSUP is the
29219296b3edSMax Reitz      * best thing to do anyway */
29229296b3edSMax Reitz 
29239296b3edSMax Reitz     if (s->incompatible_features) {
29249296b3edSMax Reitz         return -ENOTSUP;
29259296b3edSMax Reitz     }
29269296b3edSMax Reitz 
29279296b3edSMax Reitz     /* since we can ignore compatible features, we can set them to 0 as well */
29289296b3edSMax Reitz     s->compatible_features = 0;
29299296b3edSMax Reitz     /* if lazy refcounts have been used, they have already been fixed through
29309296b3edSMax Reitz      * clearing the dirty flag */
29319296b3edSMax Reitz 
29329296b3edSMax Reitz     /* clearing autoclear features is trivial */
29339296b3edSMax Reitz     s->autoclear_features = 0;
29349296b3edSMax Reitz 
29358b13976dSMax Reitz     ret = qcow2_expand_zero_clusters(bs, status_cb, cb_opaque);
29369296b3edSMax Reitz     if (ret < 0) {
29379296b3edSMax Reitz         return ret;
29389296b3edSMax Reitz     }
29399296b3edSMax Reitz 
29409296b3edSMax Reitz     s->qcow_version = target_version;
29419296b3edSMax Reitz     ret = qcow2_update_header(bs);
29429296b3edSMax Reitz     if (ret < 0) {
29439296b3edSMax Reitz         s->qcow_version = current_version;
29449296b3edSMax Reitz         return ret;
29459296b3edSMax Reitz     }
29469296b3edSMax Reitz     return 0;
29479296b3edSMax Reitz }
29489296b3edSMax Reitz 
2949c293a809SMax Reitz typedef enum Qcow2AmendOperation {
2950c293a809SMax Reitz     /* This is the value Qcow2AmendHelperCBInfo::last_operation will be
2951c293a809SMax Reitz      * statically initialized to so that the helper CB can discern the first
2952c293a809SMax Reitz      * invocation from an operation change */
2953c293a809SMax Reitz     QCOW2_NO_OPERATION = 0,
2954c293a809SMax Reitz 
295561ce55fcSMax Reitz     QCOW2_CHANGING_REFCOUNT_ORDER,
2956c293a809SMax Reitz     QCOW2_DOWNGRADING,
2957c293a809SMax Reitz } Qcow2AmendOperation;
2958c293a809SMax Reitz 
2959c293a809SMax Reitz typedef struct Qcow2AmendHelperCBInfo {
2960c293a809SMax Reitz     /* The code coordinating the amend operations should only modify
2961c293a809SMax Reitz      * these four fields; the rest will be managed by the CB */
2962c293a809SMax Reitz     BlockDriverAmendStatusCB *original_status_cb;
2963c293a809SMax Reitz     void *original_cb_opaque;
2964c293a809SMax Reitz 
2965c293a809SMax Reitz     Qcow2AmendOperation current_operation;
2966c293a809SMax Reitz 
2967c293a809SMax Reitz     /* Total number of operations to perform (only set once) */
2968c293a809SMax Reitz     int total_operations;
2969c293a809SMax Reitz 
2970c293a809SMax Reitz     /* The following fields are managed by the CB */
2971c293a809SMax Reitz 
2972c293a809SMax Reitz     /* Number of operations completed */
2973c293a809SMax Reitz     int operations_completed;
2974c293a809SMax Reitz 
2975c293a809SMax Reitz     /* Cumulative offset of all completed operations */
2976c293a809SMax Reitz     int64_t offset_completed;
2977c293a809SMax Reitz 
2978c293a809SMax Reitz     Qcow2AmendOperation last_operation;
2979c293a809SMax Reitz     int64_t last_work_size;
2980c293a809SMax Reitz } Qcow2AmendHelperCBInfo;
2981c293a809SMax Reitz 
2982c293a809SMax Reitz static void qcow2_amend_helper_cb(BlockDriverState *bs,
2983c293a809SMax Reitz                                   int64_t operation_offset,
2984c293a809SMax Reitz                                   int64_t operation_work_size, void *opaque)
2985c293a809SMax Reitz {
2986c293a809SMax Reitz     Qcow2AmendHelperCBInfo *info = opaque;
2987c293a809SMax Reitz     int64_t current_work_size;
2988c293a809SMax Reitz     int64_t projected_work_size;
2989c293a809SMax Reitz 
2990c293a809SMax Reitz     if (info->current_operation != info->last_operation) {
2991c293a809SMax Reitz         if (info->last_operation != QCOW2_NO_OPERATION) {
2992c293a809SMax Reitz             info->offset_completed += info->last_work_size;
2993c293a809SMax Reitz             info->operations_completed++;
2994c293a809SMax Reitz         }
2995c293a809SMax Reitz 
2996c293a809SMax Reitz         info->last_operation = info->current_operation;
2997c293a809SMax Reitz     }
2998c293a809SMax Reitz 
2999c293a809SMax Reitz     assert(info->total_operations > 0);
3000c293a809SMax Reitz     assert(info->operations_completed < info->total_operations);
3001c293a809SMax Reitz 
3002c293a809SMax Reitz     info->last_work_size = operation_work_size;
3003c293a809SMax Reitz 
3004c293a809SMax Reitz     current_work_size = info->offset_completed + operation_work_size;
3005c293a809SMax Reitz 
3006c293a809SMax Reitz     /* current_work_size is the total work size for (operations_completed + 1)
3007c293a809SMax Reitz      * operations (which includes this one), so multiply it by the number of
3008c293a809SMax Reitz      * operations not covered and divide it by the number of operations
3009c293a809SMax Reitz      * covered to get a projection for the operations not covered */
3010c293a809SMax Reitz     projected_work_size = current_work_size * (info->total_operations -
3011c293a809SMax Reitz                                                info->operations_completed - 1)
3012c293a809SMax Reitz                                             / (info->operations_completed + 1);
3013c293a809SMax Reitz 
3014c293a809SMax Reitz     info->original_status_cb(bs, info->offset_completed + operation_offset,
3015c293a809SMax Reitz                              current_work_size + projected_work_size,
3016c293a809SMax Reitz                              info->original_cb_opaque);
3017c293a809SMax Reitz }
3018c293a809SMax Reitz 
301977485434SMax Reitz static int qcow2_amend_options(BlockDriverState *bs, QemuOpts *opts,
30208b13976dSMax Reitz                                BlockDriverAmendStatusCB *status_cb,
30218b13976dSMax Reitz                                void *cb_opaque)
30229296b3edSMax Reitz {
3023ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
30249296b3edSMax Reitz     int old_version = s->qcow_version, new_version = old_version;
30259296b3edSMax Reitz     uint64_t new_size = 0;
30269296b3edSMax Reitz     const char *backing_file = NULL, *backing_format = NULL;
30279296b3edSMax Reitz     bool lazy_refcounts = s->use_lazy_refcounts;
30281bd0e2d1SChunyan Liu     const char *compat = NULL;
30291bd0e2d1SChunyan Liu     uint64_t cluster_size = s->cluster_size;
30301bd0e2d1SChunyan Liu     bool encrypt;
303161ce55fcSMax Reitz     int refcount_bits = s->refcount_bits;
30329296b3edSMax Reitz     int ret;
30331bd0e2d1SChunyan Liu     QemuOptDesc *desc = opts->list->desc;
3034c293a809SMax Reitz     Qcow2AmendHelperCBInfo helper_cb_info;
30359296b3edSMax Reitz 
30361bd0e2d1SChunyan Liu     while (desc && desc->name) {
30371bd0e2d1SChunyan Liu         if (!qemu_opt_find(opts, desc->name)) {
30389296b3edSMax Reitz             /* only change explicitly defined options */
30391bd0e2d1SChunyan Liu             desc++;
30409296b3edSMax Reitz             continue;
30419296b3edSMax Reitz         }
30429296b3edSMax Reitz 
30438a17b83cSMax Reitz         if (!strcmp(desc->name, BLOCK_OPT_COMPAT_LEVEL)) {
30448a17b83cSMax Reitz             compat = qemu_opt_get(opts, BLOCK_OPT_COMPAT_LEVEL);
30451bd0e2d1SChunyan Liu             if (!compat) {
30469296b3edSMax Reitz                 /* preserve default */
30471bd0e2d1SChunyan Liu             } else if (!strcmp(compat, "0.10")) {
30489296b3edSMax Reitz                 new_version = 2;
30491bd0e2d1SChunyan Liu             } else if (!strcmp(compat, "1.1")) {
30509296b3edSMax Reitz                 new_version = 3;
30519296b3edSMax Reitz             } else {
305229d72431SMax Reitz                 error_report("Unknown compatibility level %s", compat);
30539296b3edSMax Reitz                 return -EINVAL;
30549296b3edSMax Reitz             }
30558a17b83cSMax Reitz         } else if (!strcmp(desc->name, BLOCK_OPT_PREALLOC)) {
305629d72431SMax Reitz             error_report("Cannot change preallocation mode");
30579296b3edSMax Reitz             return -ENOTSUP;
30588a17b83cSMax Reitz         } else if (!strcmp(desc->name, BLOCK_OPT_SIZE)) {
30598a17b83cSMax Reitz             new_size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, 0);
30608a17b83cSMax Reitz         } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FILE)) {
30618a17b83cSMax Reitz             backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
30628a17b83cSMax Reitz         } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FMT)) {
30638a17b83cSMax Reitz             backing_format = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
30648a17b83cSMax Reitz         } else if (!strcmp(desc->name, BLOCK_OPT_ENCRYPT)) {
30658a17b83cSMax Reitz             encrypt = qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT,
3066f6fa64f6SDaniel P. Berrange                                         !!s->cipher);
3067f6fa64f6SDaniel P. Berrange 
3068f6fa64f6SDaniel P. Berrange             if (encrypt != !!s->cipher) {
306929d72431SMax Reitz                 error_report("Changing the encryption flag is not supported");
30709296b3edSMax Reitz                 return -ENOTSUP;
30719296b3edSMax Reitz             }
30728a17b83cSMax Reitz         } else if (!strcmp(desc->name, BLOCK_OPT_CLUSTER_SIZE)) {
30738a17b83cSMax Reitz             cluster_size = qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE,
30741bd0e2d1SChunyan Liu                                              cluster_size);
30751bd0e2d1SChunyan Liu             if (cluster_size != s->cluster_size) {
307629d72431SMax Reitz                 error_report("Changing the cluster size is not supported");
30779296b3edSMax Reitz                 return -ENOTSUP;
30789296b3edSMax Reitz             }
30798a17b83cSMax Reitz         } else if (!strcmp(desc->name, BLOCK_OPT_LAZY_REFCOUNTS)) {
30808a17b83cSMax Reitz             lazy_refcounts = qemu_opt_get_bool(opts, BLOCK_OPT_LAZY_REFCOUNTS,
30811bd0e2d1SChunyan Liu                                                lazy_refcounts);
308206d05fa7SMax Reitz         } else if (!strcmp(desc->name, BLOCK_OPT_REFCOUNT_BITS)) {
308361ce55fcSMax Reitz             refcount_bits = qemu_opt_get_number(opts, BLOCK_OPT_REFCOUNT_BITS,
308461ce55fcSMax Reitz                                                 refcount_bits);
308561ce55fcSMax Reitz 
308661ce55fcSMax Reitz             if (refcount_bits <= 0 || refcount_bits > 64 ||
308761ce55fcSMax Reitz                 !is_power_of_2(refcount_bits))
308861ce55fcSMax Reitz             {
308961ce55fcSMax Reitz                 error_report("Refcount width must be a power of two and may "
309061ce55fcSMax Reitz                              "not exceed 64 bits");
309161ce55fcSMax Reitz                 return -EINVAL;
309261ce55fcSMax Reitz             }
30939296b3edSMax Reitz         } else {
3094164e0f89SMax Reitz             /* if this point is reached, this probably means a new option was
30959296b3edSMax Reitz              * added without having it covered here */
3096164e0f89SMax Reitz             abort();
30979296b3edSMax Reitz         }
30981bd0e2d1SChunyan Liu 
30991bd0e2d1SChunyan Liu         desc++;
31009296b3edSMax Reitz     }
31019296b3edSMax Reitz 
3102c293a809SMax Reitz     helper_cb_info = (Qcow2AmendHelperCBInfo){
3103c293a809SMax Reitz         .original_status_cb = status_cb,
3104c293a809SMax Reitz         .original_cb_opaque = cb_opaque,
3105c293a809SMax Reitz         .total_operations = (new_version < old_version)
310661ce55fcSMax Reitz                           + (s->refcount_bits != refcount_bits)
3107c293a809SMax Reitz     };
3108c293a809SMax Reitz 
31091038bbb8SMax Reitz     /* Upgrade first (some features may require compat=1.1) */
31109296b3edSMax Reitz     if (new_version > old_version) {
31119296b3edSMax Reitz         s->qcow_version = new_version;
31129296b3edSMax Reitz         ret = qcow2_update_header(bs);
31139296b3edSMax Reitz         if (ret < 0) {
31149296b3edSMax Reitz             s->qcow_version = old_version;
31159296b3edSMax Reitz             return ret;
31169296b3edSMax Reitz         }
31179296b3edSMax Reitz     }
31189296b3edSMax Reitz 
311961ce55fcSMax Reitz     if (s->refcount_bits != refcount_bits) {
312061ce55fcSMax Reitz         int refcount_order = ctz32(refcount_bits);
312161ce55fcSMax Reitz         Error *local_error = NULL;
312261ce55fcSMax Reitz 
312361ce55fcSMax Reitz         if (new_version < 3 && refcount_bits != 16) {
312461ce55fcSMax Reitz             error_report("Different refcount widths than 16 bits require "
312561ce55fcSMax Reitz                          "compatibility level 1.1 or above (use compat=1.1 or "
312661ce55fcSMax Reitz                          "greater)");
312761ce55fcSMax Reitz             return -EINVAL;
312861ce55fcSMax Reitz         }
312961ce55fcSMax Reitz 
313061ce55fcSMax Reitz         helper_cb_info.current_operation = QCOW2_CHANGING_REFCOUNT_ORDER;
313161ce55fcSMax Reitz         ret = qcow2_change_refcount_order(bs, refcount_order,
313261ce55fcSMax Reitz                                           &qcow2_amend_helper_cb,
313361ce55fcSMax Reitz                                           &helper_cb_info, &local_error);
313461ce55fcSMax Reitz         if (ret < 0) {
313561ce55fcSMax Reitz             error_report_err(local_error);
313661ce55fcSMax Reitz             return ret;
313761ce55fcSMax Reitz         }
313861ce55fcSMax Reitz     }
313961ce55fcSMax Reitz 
31409296b3edSMax Reitz     if (backing_file || backing_format) {
3141e4603fe1SKevin Wolf         ret = qcow2_change_backing_file(bs,
3142e4603fe1SKevin Wolf                     backing_file ?: s->image_backing_file,
3143e4603fe1SKevin Wolf                     backing_format ?: s->image_backing_format);
31449296b3edSMax Reitz         if (ret < 0) {
31459296b3edSMax Reitz             return ret;
31469296b3edSMax Reitz         }
31479296b3edSMax Reitz     }
31489296b3edSMax Reitz 
31499296b3edSMax Reitz     if (s->use_lazy_refcounts != lazy_refcounts) {
31509296b3edSMax Reitz         if (lazy_refcounts) {
31511038bbb8SMax Reitz             if (new_version < 3) {
315229d72431SMax Reitz                 error_report("Lazy refcounts only supported with compatibility "
315329d72431SMax Reitz                              "level 1.1 and above (use compat=1.1 or greater)");
31549296b3edSMax Reitz                 return -EINVAL;
31559296b3edSMax Reitz             }
31569296b3edSMax Reitz             s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
31579296b3edSMax Reitz             ret = qcow2_update_header(bs);
31589296b3edSMax Reitz             if (ret < 0) {
31599296b3edSMax Reitz                 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
31609296b3edSMax Reitz                 return ret;
31619296b3edSMax Reitz             }
31629296b3edSMax Reitz             s->use_lazy_refcounts = true;
31639296b3edSMax Reitz         } else {
31649296b3edSMax Reitz             /* make image clean first */
31659296b3edSMax Reitz             ret = qcow2_mark_clean(bs);
31669296b3edSMax Reitz             if (ret < 0) {
31679296b3edSMax Reitz                 return ret;
31689296b3edSMax Reitz             }
31699296b3edSMax Reitz             /* now disallow lazy refcounts */
31709296b3edSMax Reitz             s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
31719296b3edSMax Reitz             ret = qcow2_update_header(bs);
31729296b3edSMax Reitz             if (ret < 0) {
31739296b3edSMax Reitz                 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
31749296b3edSMax Reitz                 return ret;
31759296b3edSMax Reitz             }
31769296b3edSMax Reitz             s->use_lazy_refcounts = false;
31779296b3edSMax Reitz         }
31789296b3edSMax Reitz     }
31799296b3edSMax Reitz 
31809296b3edSMax Reitz     if (new_size) {
31819296b3edSMax Reitz         ret = bdrv_truncate(bs, new_size);
31829296b3edSMax Reitz         if (ret < 0) {
31839296b3edSMax Reitz             return ret;
31849296b3edSMax Reitz         }
31859296b3edSMax Reitz     }
31869296b3edSMax Reitz 
31871038bbb8SMax Reitz     /* Downgrade last (so unsupported features can be removed before) */
31881038bbb8SMax Reitz     if (new_version < old_version) {
3189c293a809SMax Reitz         helper_cb_info.current_operation = QCOW2_DOWNGRADING;
3190c293a809SMax Reitz         ret = qcow2_downgrade(bs, new_version, &qcow2_amend_helper_cb,
3191c293a809SMax Reitz                               &helper_cb_info);
31921038bbb8SMax Reitz         if (ret < 0) {
31931038bbb8SMax Reitz             return ret;
31941038bbb8SMax Reitz         }
31951038bbb8SMax Reitz     }
31961038bbb8SMax Reitz 
31979296b3edSMax Reitz     return 0;
31989296b3edSMax Reitz }
31999296b3edSMax Reitz 
320085186ebdSMax Reitz /*
320185186ebdSMax Reitz  * If offset or size are negative, respectively, they will not be included in
320285186ebdSMax Reitz  * the BLOCK_IMAGE_CORRUPTED event emitted.
320385186ebdSMax Reitz  * fatal will be ignored for read-only BDS; corruptions found there will always
320485186ebdSMax Reitz  * be considered non-fatal.
320585186ebdSMax Reitz  */
320685186ebdSMax Reitz void qcow2_signal_corruption(BlockDriverState *bs, bool fatal, int64_t offset,
320785186ebdSMax Reitz                              int64_t size, const char *message_format, ...)
320885186ebdSMax Reitz {
3209ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
3210dc881b44SAlberto Garcia     const char *node_name;
321185186ebdSMax Reitz     char *message;
321285186ebdSMax Reitz     va_list ap;
321385186ebdSMax Reitz 
321485186ebdSMax Reitz     fatal = fatal && !bs->read_only;
321585186ebdSMax Reitz 
321685186ebdSMax Reitz     if (s->signaled_corruption &&
321785186ebdSMax Reitz         (!fatal || (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT)))
321885186ebdSMax Reitz     {
321985186ebdSMax Reitz         return;
322085186ebdSMax Reitz     }
322185186ebdSMax Reitz 
322285186ebdSMax Reitz     va_start(ap, message_format);
322385186ebdSMax Reitz     message = g_strdup_vprintf(message_format, ap);
322485186ebdSMax Reitz     va_end(ap);
322585186ebdSMax Reitz 
322685186ebdSMax Reitz     if (fatal) {
322785186ebdSMax Reitz         fprintf(stderr, "qcow2: Marking image as corrupt: %s; further "
322885186ebdSMax Reitz                 "corruption events will be suppressed\n", message);
322985186ebdSMax Reitz     } else {
323085186ebdSMax Reitz         fprintf(stderr, "qcow2: Image is corrupt: %s; further non-fatal "
323185186ebdSMax Reitz                 "corruption events will be suppressed\n", message);
323285186ebdSMax Reitz     }
323385186ebdSMax Reitz 
3234dc881b44SAlberto Garcia     node_name = bdrv_get_node_name(bs);
3235dc881b44SAlberto Garcia     qapi_event_send_block_image_corrupted(bdrv_get_device_name(bs),
3236dc881b44SAlberto Garcia                                           *node_name != '\0', node_name,
3237dc881b44SAlberto Garcia                                           message, offset >= 0, offset,
3238dc881b44SAlberto Garcia                                           size >= 0, size,
323985186ebdSMax Reitz                                           fatal, &error_abort);
324085186ebdSMax Reitz     g_free(message);
324185186ebdSMax Reitz 
324285186ebdSMax Reitz     if (fatal) {
324385186ebdSMax Reitz         qcow2_mark_corrupt(bs);
324485186ebdSMax Reitz         bs->drv = NULL; /* make BDS unusable */
324585186ebdSMax Reitz     }
324685186ebdSMax Reitz 
324785186ebdSMax Reitz     s->signaled_corruption = true;
324885186ebdSMax Reitz }
324985186ebdSMax Reitz 
32501bd0e2d1SChunyan Liu static QemuOptsList qcow2_create_opts = {
32511bd0e2d1SChunyan Liu     .name = "qcow2-create-opts",
32521bd0e2d1SChunyan Liu     .head = QTAILQ_HEAD_INITIALIZER(qcow2_create_opts.head),
32531bd0e2d1SChunyan Liu     .desc = {
325420d97356SBlue Swirl         {
325520d97356SBlue Swirl             .name = BLOCK_OPT_SIZE,
32561bd0e2d1SChunyan Liu             .type = QEMU_OPT_SIZE,
325720d97356SBlue Swirl             .help = "Virtual disk size"
325820d97356SBlue Swirl         },
325920d97356SBlue Swirl         {
32606744cbabSKevin Wolf             .name = BLOCK_OPT_COMPAT_LEVEL,
32611bd0e2d1SChunyan Liu             .type = QEMU_OPT_STRING,
32626744cbabSKevin Wolf             .help = "Compatibility level (0.10 or 1.1)"
32636744cbabSKevin Wolf         },
32646744cbabSKevin Wolf         {
326520d97356SBlue Swirl             .name = BLOCK_OPT_BACKING_FILE,
32661bd0e2d1SChunyan Liu             .type = QEMU_OPT_STRING,
326720d97356SBlue Swirl             .help = "File name of a base image"
326820d97356SBlue Swirl         },
326920d97356SBlue Swirl         {
327020d97356SBlue Swirl             .name = BLOCK_OPT_BACKING_FMT,
32711bd0e2d1SChunyan Liu             .type = QEMU_OPT_STRING,
327220d97356SBlue Swirl             .help = "Image format of the base image"
327320d97356SBlue Swirl         },
327420d97356SBlue Swirl         {
327520d97356SBlue Swirl             .name = BLOCK_OPT_ENCRYPT,
32761bd0e2d1SChunyan Liu             .type = QEMU_OPT_BOOL,
32771bd0e2d1SChunyan Liu             .help = "Encrypt the image",
32781bd0e2d1SChunyan Liu             .def_value_str = "off"
327920d97356SBlue Swirl         },
328020d97356SBlue Swirl         {
328120d97356SBlue Swirl             .name = BLOCK_OPT_CLUSTER_SIZE,
32821bd0e2d1SChunyan Liu             .type = QEMU_OPT_SIZE,
328399cce9faSKevin Wolf             .help = "qcow2 cluster size",
32841bd0e2d1SChunyan Liu             .def_value_str = stringify(DEFAULT_CLUSTER_SIZE)
328520d97356SBlue Swirl         },
328620d97356SBlue Swirl         {
328720d97356SBlue Swirl             .name = BLOCK_OPT_PREALLOC,
32881bd0e2d1SChunyan Liu             .type = QEMU_OPT_STRING,
32890e4271b7SHu Tao             .help = "Preallocation mode (allowed values: off, metadata, "
32900e4271b7SHu Tao                     "falloc, full)"
329120d97356SBlue Swirl         },
3292bfe8043eSStefan Hajnoczi         {
3293bfe8043eSStefan Hajnoczi             .name = BLOCK_OPT_LAZY_REFCOUNTS,
32941bd0e2d1SChunyan Liu             .type = QEMU_OPT_BOOL,
3295bfe8043eSStefan Hajnoczi             .help = "Postpone refcount updates",
32961bd0e2d1SChunyan Liu             .def_value_str = "off"
3297bfe8043eSStefan Hajnoczi         },
329806d05fa7SMax Reitz         {
329906d05fa7SMax Reitz             .name = BLOCK_OPT_REFCOUNT_BITS,
330006d05fa7SMax Reitz             .type = QEMU_OPT_NUMBER,
330106d05fa7SMax Reitz             .help = "Width of a reference count entry in bits",
330206d05fa7SMax Reitz             .def_value_str = "16"
330306d05fa7SMax Reitz         },
33041bd0e2d1SChunyan Liu         { /* end of list */ }
33051bd0e2d1SChunyan Liu     }
330620d97356SBlue Swirl };
330720d97356SBlue Swirl 
33085f535a94SMax Reitz BlockDriver bdrv_qcow2 = {
330920d97356SBlue Swirl     .format_name        = "qcow2",
3310ff99129aSKevin Wolf     .instance_size      = sizeof(BDRVQcow2State),
33117c80ab3fSJes Sorensen     .bdrv_probe         = qcow2_probe,
33127c80ab3fSJes Sorensen     .bdrv_open          = qcow2_open,
33137c80ab3fSJes Sorensen     .bdrv_close         = qcow2_close,
331421d82ac9SJeff Cody     .bdrv_reopen_prepare  = qcow2_reopen_prepare,
33155b0959a7SKevin Wolf     .bdrv_reopen_commit   = qcow2_reopen_commit,
33165b0959a7SKevin Wolf     .bdrv_reopen_abort    = qcow2_reopen_abort,
33175365f44dSKevin Wolf     .bdrv_join_options    = qcow2_join_options,
3318c282e1fdSChunyan Liu     .bdrv_create        = qcow2_create,
33193ac21627SPeter Lieven     .bdrv_has_zero_init = bdrv_has_zero_init_1,
3320b6b8a333SPaolo Bonzini     .bdrv_co_get_block_status = qcow2_co_get_block_status,
33217c80ab3fSJes Sorensen     .bdrv_set_key       = qcow2_set_key,
332220d97356SBlue Swirl 
332368d100e9SKevin Wolf     .bdrv_co_readv          = qcow2_co_readv,
332468d100e9SKevin Wolf     .bdrv_co_writev         = qcow2_co_writev,
3325eb489bb1SKevin Wolf     .bdrv_co_flush_to_os    = qcow2_co_flush_to_os,
3326419b19d9SStefan Hajnoczi 
3327621f0589SKevin Wolf     .bdrv_co_write_zeroes   = qcow2_co_write_zeroes,
33286db39ae2SPaolo Bonzini     .bdrv_co_discard        = qcow2_co_discard,
3329419b19d9SStefan Hajnoczi     .bdrv_truncate          = qcow2_truncate,
33307c80ab3fSJes Sorensen     .bdrv_write_compressed  = qcow2_write_compressed,
3331491d27e2SMax Reitz     .bdrv_make_empty        = qcow2_make_empty,
333220d97356SBlue Swirl 
333320d97356SBlue Swirl     .bdrv_snapshot_create   = qcow2_snapshot_create,
333420d97356SBlue Swirl     .bdrv_snapshot_goto     = qcow2_snapshot_goto,
333520d97356SBlue Swirl     .bdrv_snapshot_delete   = qcow2_snapshot_delete,
333620d97356SBlue Swirl     .bdrv_snapshot_list     = qcow2_snapshot_list,
333751ef6727Sedison     .bdrv_snapshot_load_tmp = qcow2_snapshot_load_tmp,
33387c80ab3fSJes Sorensen     .bdrv_get_info          = qcow2_get_info,
333937764dfbSMax Reitz     .bdrv_get_specific_info = qcow2_get_specific_info,
334020d97356SBlue Swirl 
33417c80ab3fSJes Sorensen     .bdrv_save_vmstate    = qcow2_save_vmstate,
33427c80ab3fSJes Sorensen     .bdrv_load_vmstate    = qcow2_load_vmstate,
334320d97356SBlue Swirl 
33448ee79e70SKevin Wolf     .supports_backing           = true,
334520d97356SBlue Swirl     .bdrv_change_backing_file   = qcow2_change_backing_file,
334620d97356SBlue Swirl 
3347d34682cdSKevin Wolf     .bdrv_refresh_limits        = qcow2_refresh_limits,
334806d9260fSAnthony Liguori     .bdrv_invalidate_cache      = qcow2_invalidate_cache,
3349ec6d8912SKevin Wolf     .bdrv_inactivate            = qcow2_inactivate,
335006d9260fSAnthony Liguori 
33511bd0e2d1SChunyan Liu     .create_opts         = &qcow2_create_opts,
33527c80ab3fSJes Sorensen     .bdrv_check          = qcow2_check,
3353c282e1fdSChunyan Liu     .bdrv_amend_options  = qcow2_amend_options,
3354279621c0SAlberto Garcia 
3355279621c0SAlberto Garcia     .bdrv_detach_aio_context  = qcow2_detach_aio_context,
3356279621c0SAlberto Garcia     .bdrv_attach_aio_context  = qcow2_attach_aio_context,
335720d97356SBlue Swirl };
335820d97356SBlue Swirl 
33595efa9d5aSAnthony Liguori static void bdrv_qcow2_init(void)
33605efa9d5aSAnthony Liguori {
33615efa9d5aSAnthony Liguori     bdrv_register(&bdrv_qcow2);
33625efa9d5aSAnthony Liguori }
33635efa9d5aSAnthony Liguori 
33645efa9d5aSAnthony Liguori block_init(bdrv_qcow2_init);
3365