xref: /qemu/block/qcow2.c (revision 4bff28b81a0ddb48a09d279e99ab847e8a292506)
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"
25737e150eSPaolo Bonzini #include "block/block_int.h"
2623588797SKevin Wolf #include "sysemu/block-backend.h"
271de7afc9SPaolo Bonzini #include "qemu/module.h"
28585f8587Sbellard #include <zlib.h>
29f7d0fe02SKevin Wolf #include "block/qcow2.h"
301de7afc9SPaolo Bonzini #include "qemu/error-report.h"
317b1b5d19SPaolo Bonzini #include "qapi/qmp/qerror.h"
32acdfb480SKevin Wolf #include "qapi/qmp/qbool.h"
33ffeaac9bSHu Tao #include "qapi/util.h"
3485186ebdSMax Reitz #include "qapi/qmp/types.h"
3585186ebdSMax Reitz #include "qapi-event.h"
363cce16f4SKevin Wolf #include "trace.h"
371bd0e2d1SChunyan Liu #include "qemu/option_int.h"
38f348b6d1SVeronia Bahaa #include "qemu/cutils.h"
3958369e22SPaolo Bonzini #include "qemu/bswap.h"
40585f8587Sbellard 
41585f8587Sbellard /*
42585f8587Sbellard   Differences with QCOW:
43585f8587Sbellard 
44585f8587Sbellard   - Support for multiple incremental snapshots.
45585f8587Sbellard   - Memory management by reference counts.
46585f8587Sbellard   - Clusters which have a reference count of one have the bit
47585f8587Sbellard     QCOW_OFLAG_COPIED to optimize write performance.
48585f8587Sbellard   - Size of compressed clusters is stored in sectors to reduce bit usage
49585f8587Sbellard     in the cluster offsets.
50585f8587Sbellard   - Support for storing additional data (such as the VM state) in the
51585f8587Sbellard     snapshots.
52585f8587Sbellard   - If a backing store is used, the cluster size is not constrained
53585f8587Sbellard     (could be backported to QCOW).
54585f8587Sbellard   - L2 tables have always a size of one cluster.
55585f8587Sbellard */
56585f8587Sbellard 
579b80ddf3Saliguori 
589b80ddf3Saliguori typedef struct {
599b80ddf3Saliguori     uint32_t magic;
609b80ddf3Saliguori     uint32_t len;
61c4217f64SJeff Cody } QEMU_PACKED QCowExtension;
6221d82ac9SJeff Cody 
637c80ab3fSJes Sorensen #define  QCOW2_EXT_MAGIC_END 0
647c80ab3fSJes Sorensen #define  QCOW2_EXT_MAGIC_BACKING_FORMAT 0xE2792ACA
65cfcc4c62SKevin Wolf #define  QCOW2_EXT_MAGIC_FEATURE_TABLE 0x6803f857
669b80ddf3Saliguori 
677c80ab3fSJes Sorensen static int qcow2_probe(const uint8_t *buf, int buf_size, const char *filename)
68585f8587Sbellard {
69585f8587Sbellard     const QCowHeader *cow_header = (const void *)buf;
70585f8587Sbellard 
71585f8587Sbellard     if (buf_size >= sizeof(QCowHeader) &&
72585f8587Sbellard         be32_to_cpu(cow_header->magic) == QCOW_MAGIC &&
736744cbabSKevin Wolf         be32_to_cpu(cow_header->version) >= 2)
74585f8587Sbellard         return 100;
75585f8587Sbellard     else
76585f8587Sbellard         return 0;
77585f8587Sbellard }
78585f8587Sbellard 
799b80ddf3Saliguori 
809b80ddf3Saliguori /*
819b80ddf3Saliguori  * read qcow2 extension and fill bs
829b80ddf3Saliguori  * start reading from start_offset
839b80ddf3Saliguori  * finish reading upon magic of value 0 or when end_offset reached
849b80ddf3Saliguori  * unknown magic is skipped (future extension this version knows nothing about)
859b80ddf3Saliguori  * return 0 upon success, non-0 otherwise
869b80ddf3Saliguori  */
877c80ab3fSJes Sorensen static int qcow2_read_extensions(BlockDriverState *bs, uint64_t start_offset,
883ef6c40aSMax Reitz                                  uint64_t end_offset, void **p_feature_table,
893ef6c40aSMax Reitz                                  Error **errp)
909b80ddf3Saliguori {
91ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
929b80ddf3Saliguori     QCowExtension ext;
939b80ddf3Saliguori     uint64_t offset;
9475bab85cSKevin Wolf     int ret;
959b80ddf3Saliguori 
969b80ddf3Saliguori #ifdef DEBUG_EXT
977c80ab3fSJes Sorensen     printf("qcow2_read_extensions: start=%ld end=%ld\n", start_offset, end_offset);
989b80ddf3Saliguori #endif
999b80ddf3Saliguori     offset = start_offset;
1009b80ddf3Saliguori     while (offset < end_offset) {
1019b80ddf3Saliguori 
1029b80ddf3Saliguori #ifdef DEBUG_EXT
1039b80ddf3Saliguori         /* Sanity check */
1049b80ddf3Saliguori         if (offset > s->cluster_size)
1057c80ab3fSJes Sorensen             printf("qcow2_read_extension: suspicious offset %lu\n", offset);
1069b80ddf3Saliguori 
1079b2260cbSDong Xu Wang         printf("attempting to read extended header in offset %lu\n", offset);
1089b80ddf3Saliguori #endif
1099b80ddf3Saliguori 
110cf2ab8fcSKevin Wolf         ret = bdrv_pread(bs->file, offset, &ext, sizeof(ext));
1113ef6c40aSMax Reitz         if (ret < 0) {
1123ef6c40aSMax Reitz             error_setg_errno(errp, -ret, "qcow2_read_extension: ERROR: "
1133ef6c40aSMax Reitz                              "pread fail from offset %" PRIu64, offset);
1149b80ddf3Saliguori             return 1;
1159b80ddf3Saliguori         }
1169b80ddf3Saliguori         be32_to_cpus(&ext.magic);
1179b80ddf3Saliguori         be32_to_cpus(&ext.len);
1189b80ddf3Saliguori         offset += sizeof(ext);
1199b80ddf3Saliguori #ifdef DEBUG_EXT
1209b80ddf3Saliguori         printf("ext.magic = 0x%x\n", ext.magic);
1219b80ddf3Saliguori #endif
1222ebafc85SKevin Wolf         if (offset > end_offset || ext.len > end_offset - offset) {
1233ef6c40aSMax Reitz             error_setg(errp, "Header extension too large");
12464ca6aeeSKevin Wolf             return -EINVAL;
12564ca6aeeSKevin Wolf         }
12664ca6aeeSKevin Wolf 
1279b80ddf3Saliguori         switch (ext.magic) {
1287c80ab3fSJes Sorensen         case QCOW2_EXT_MAGIC_END:
1299b80ddf3Saliguori             return 0;
130f965509cSaliguori 
1317c80ab3fSJes Sorensen         case QCOW2_EXT_MAGIC_BACKING_FORMAT:
132f965509cSaliguori             if (ext.len >= sizeof(bs->backing_format)) {
133521b2b5dSMax Reitz                 error_setg(errp, "ERROR: ext_backing_format: len=%" PRIu32
134521b2b5dSMax Reitz                            " too large (>=%zu)", ext.len,
135521b2b5dSMax Reitz                            sizeof(bs->backing_format));
136f965509cSaliguori                 return 2;
137f965509cSaliguori             }
138cf2ab8fcSKevin Wolf             ret = bdrv_pread(bs->file, offset, bs->backing_format, ext.len);
1393ef6c40aSMax Reitz             if (ret < 0) {
1403ef6c40aSMax Reitz                 error_setg_errno(errp, -ret, "ERROR: ext_backing_format: "
1413ef6c40aSMax Reitz                                  "Could not read format name");
142f965509cSaliguori                 return 3;
1433ef6c40aSMax Reitz             }
144f965509cSaliguori             bs->backing_format[ext.len] = '\0';
145e4603fe1SKevin Wolf             s->image_backing_format = g_strdup(bs->backing_format);
146f965509cSaliguori #ifdef DEBUG_EXT
147f965509cSaliguori             printf("Qcow2: Got format extension %s\n", bs->backing_format);
148f965509cSaliguori #endif
149f965509cSaliguori             break;
150f965509cSaliguori 
151cfcc4c62SKevin Wolf         case QCOW2_EXT_MAGIC_FEATURE_TABLE:
152cfcc4c62SKevin Wolf             if (p_feature_table != NULL) {
153cfcc4c62SKevin Wolf                 void* feature_table = g_malloc0(ext.len + 2 * sizeof(Qcow2Feature));
154cf2ab8fcSKevin Wolf                 ret = bdrv_pread(bs->file, offset , feature_table, ext.len);
155cfcc4c62SKevin Wolf                 if (ret < 0) {
1563ef6c40aSMax Reitz                     error_setg_errno(errp, -ret, "ERROR: ext_feature_table: "
1573ef6c40aSMax Reitz                                      "Could not read table");
158cfcc4c62SKevin Wolf                     return ret;
159cfcc4c62SKevin Wolf                 }
160cfcc4c62SKevin Wolf 
161cfcc4c62SKevin Wolf                 *p_feature_table = feature_table;
162cfcc4c62SKevin Wolf             }
163cfcc4c62SKevin Wolf             break;
164cfcc4c62SKevin Wolf 
1659b80ddf3Saliguori         default:
16675bab85cSKevin Wolf             /* unknown magic - save it in case we need to rewrite the header */
16775bab85cSKevin Wolf             {
16875bab85cSKevin Wolf                 Qcow2UnknownHeaderExtension *uext;
16975bab85cSKevin Wolf 
17075bab85cSKevin Wolf                 uext = g_malloc0(sizeof(*uext)  + ext.len);
17175bab85cSKevin Wolf                 uext->magic = ext.magic;
17275bab85cSKevin Wolf                 uext->len = ext.len;
17375bab85cSKevin Wolf                 QLIST_INSERT_HEAD(&s->unknown_header_ext, uext, next);
17475bab85cSKevin Wolf 
175cf2ab8fcSKevin Wolf                 ret = bdrv_pread(bs->file, offset , uext->data, uext->len);
17675bab85cSKevin Wolf                 if (ret < 0) {
1773ef6c40aSMax Reitz                     error_setg_errno(errp, -ret, "ERROR: unknown extension: "
1783ef6c40aSMax Reitz                                      "Could not read data");
17975bab85cSKevin Wolf                     return ret;
18075bab85cSKevin Wolf                 }
18175bab85cSKevin Wolf             }
1829b80ddf3Saliguori             break;
1839b80ddf3Saliguori         }
184fd29b4bbSKevin Wolf 
185fd29b4bbSKevin Wolf         offset += ((ext.len + 7) & ~7);
1869b80ddf3Saliguori     }
1879b80ddf3Saliguori 
1889b80ddf3Saliguori     return 0;
1899b80ddf3Saliguori }
1909b80ddf3Saliguori 
19175bab85cSKevin Wolf static void cleanup_unknown_header_ext(BlockDriverState *bs)
19275bab85cSKevin Wolf {
193ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
19475bab85cSKevin Wolf     Qcow2UnknownHeaderExtension *uext, *next;
19575bab85cSKevin Wolf 
19675bab85cSKevin Wolf     QLIST_FOREACH_SAFE(uext, &s->unknown_header_ext, next, next) {
19775bab85cSKevin Wolf         QLIST_REMOVE(uext, next);
19875bab85cSKevin Wolf         g_free(uext);
19975bab85cSKevin Wolf     }
20075bab85cSKevin Wolf }
2019b80ddf3Saliguori 
202a55448b3SMax Reitz static void report_unsupported_feature(Error **errp, Qcow2Feature *table,
203a55448b3SMax Reitz                                        uint64_t mask)
204cfcc4c62SKevin Wolf {
20512ac6d3dSKevin Wolf     char *features = g_strdup("");
20612ac6d3dSKevin Wolf     char *old;
20712ac6d3dSKevin Wolf 
208cfcc4c62SKevin Wolf     while (table && table->name[0] != '\0') {
209cfcc4c62SKevin Wolf         if (table->type == QCOW2_FEAT_TYPE_INCOMPATIBLE) {
21012ac6d3dSKevin Wolf             if (mask & (1ULL << table->bit)) {
21112ac6d3dSKevin Wolf                 old = features;
21212ac6d3dSKevin Wolf                 features = g_strdup_printf("%s%s%.46s", old, *old ? ", " : "",
21312ac6d3dSKevin Wolf                                            table->name);
21412ac6d3dSKevin Wolf                 g_free(old);
21512ac6d3dSKevin Wolf                 mask &= ~(1ULL << table->bit);
216cfcc4c62SKevin Wolf             }
217cfcc4c62SKevin Wolf         }
218cfcc4c62SKevin Wolf         table++;
219cfcc4c62SKevin Wolf     }
220cfcc4c62SKevin Wolf 
221cfcc4c62SKevin Wolf     if (mask) {
22212ac6d3dSKevin Wolf         old = features;
22312ac6d3dSKevin Wolf         features = g_strdup_printf("%s%sUnknown incompatible feature: %" PRIx64,
22412ac6d3dSKevin Wolf                                    old, *old ? ", " : "", mask);
22512ac6d3dSKevin Wolf         g_free(old);
226cfcc4c62SKevin Wolf     }
22712ac6d3dSKevin Wolf 
228a55448b3SMax Reitz     error_setg(errp, "Unsupported qcow2 feature(s): %s", features);
22912ac6d3dSKevin Wolf     g_free(features);
230cfcc4c62SKevin Wolf }
231cfcc4c62SKevin Wolf 
232c61d0004SStefan Hajnoczi /*
233bfe8043eSStefan Hajnoczi  * Sets the dirty bit and flushes afterwards if necessary.
234bfe8043eSStefan Hajnoczi  *
235bfe8043eSStefan Hajnoczi  * The incompatible_features bit is only set if the image file header was
236bfe8043eSStefan Hajnoczi  * updated successfully.  Therefore it is not required to check the return
237bfe8043eSStefan Hajnoczi  * value of this function.
238bfe8043eSStefan Hajnoczi  */
239280d3735SKevin Wolf int qcow2_mark_dirty(BlockDriverState *bs)
240bfe8043eSStefan Hajnoczi {
241ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
242bfe8043eSStefan Hajnoczi     uint64_t val;
243bfe8043eSStefan Hajnoczi     int ret;
244bfe8043eSStefan Hajnoczi 
245bfe8043eSStefan Hajnoczi     assert(s->qcow_version >= 3);
246bfe8043eSStefan Hajnoczi 
247bfe8043eSStefan Hajnoczi     if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
248bfe8043eSStefan Hajnoczi         return 0; /* already dirty */
249bfe8043eSStefan Hajnoczi     }
250bfe8043eSStefan Hajnoczi 
251bfe8043eSStefan Hajnoczi     val = cpu_to_be64(s->incompatible_features | QCOW2_INCOMPAT_DIRTY);
252d9ca2ea2SKevin Wolf     ret = bdrv_pwrite(bs->file, offsetof(QCowHeader, incompatible_features),
253bfe8043eSStefan Hajnoczi                       &val, sizeof(val));
254bfe8043eSStefan Hajnoczi     if (ret < 0) {
255bfe8043eSStefan Hajnoczi         return ret;
256bfe8043eSStefan Hajnoczi     }
2579a4f4c31SKevin Wolf     ret = bdrv_flush(bs->file->bs);
258bfe8043eSStefan Hajnoczi     if (ret < 0) {
259bfe8043eSStefan Hajnoczi         return ret;
260bfe8043eSStefan Hajnoczi     }
261bfe8043eSStefan Hajnoczi 
262bfe8043eSStefan Hajnoczi     /* Only treat image as dirty if the header was updated successfully */
263bfe8043eSStefan Hajnoczi     s->incompatible_features |= QCOW2_INCOMPAT_DIRTY;
264bfe8043eSStefan Hajnoczi     return 0;
265bfe8043eSStefan Hajnoczi }
266bfe8043eSStefan Hajnoczi 
267bfe8043eSStefan Hajnoczi /*
268c61d0004SStefan Hajnoczi  * Clears the dirty bit and flushes before if necessary.  Only call this
269c61d0004SStefan Hajnoczi  * function when there are no pending requests, it does not guard against
270c61d0004SStefan Hajnoczi  * concurrent requests dirtying the image.
271c61d0004SStefan Hajnoczi  */
272c61d0004SStefan Hajnoczi static int qcow2_mark_clean(BlockDriverState *bs)
273c61d0004SStefan Hajnoczi {
274ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
275c61d0004SStefan Hajnoczi 
276c61d0004SStefan Hajnoczi     if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
2774c2e5f8fSKevin Wolf         int ret;
2784c2e5f8fSKevin Wolf 
2794c2e5f8fSKevin Wolf         s->incompatible_features &= ~QCOW2_INCOMPAT_DIRTY;
2804c2e5f8fSKevin Wolf 
2814c2e5f8fSKevin Wolf         ret = bdrv_flush(bs);
282c61d0004SStefan Hajnoczi         if (ret < 0) {
283c61d0004SStefan Hajnoczi             return ret;
284c61d0004SStefan Hajnoczi         }
285c61d0004SStefan Hajnoczi 
286c61d0004SStefan Hajnoczi         return qcow2_update_header(bs);
287c61d0004SStefan Hajnoczi     }
288c61d0004SStefan Hajnoczi     return 0;
289c61d0004SStefan Hajnoczi }
290c61d0004SStefan Hajnoczi 
29169c98726SMax Reitz /*
29269c98726SMax Reitz  * Marks the image as corrupt.
29369c98726SMax Reitz  */
29469c98726SMax Reitz int qcow2_mark_corrupt(BlockDriverState *bs)
29569c98726SMax Reitz {
296ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
29769c98726SMax Reitz 
29869c98726SMax Reitz     s->incompatible_features |= QCOW2_INCOMPAT_CORRUPT;
29969c98726SMax Reitz     return qcow2_update_header(bs);
30069c98726SMax Reitz }
30169c98726SMax Reitz 
30269c98726SMax Reitz /*
30369c98726SMax Reitz  * Marks the image as consistent, i.e., unsets the corrupt bit, and flushes
30469c98726SMax Reitz  * before if necessary.
30569c98726SMax Reitz  */
30669c98726SMax Reitz int qcow2_mark_consistent(BlockDriverState *bs)
30769c98726SMax Reitz {
308ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
30969c98726SMax Reitz 
31069c98726SMax Reitz     if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
31169c98726SMax Reitz         int ret = bdrv_flush(bs);
31269c98726SMax Reitz         if (ret < 0) {
31369c98726SMax Reitz             return ret;
31469c98726SMax Reitz         }
31569c98726SMax Reitz 
31669c98726SMax Reitz         s->incompatible_features &= ~QCOW2_INCOMPAT_CORRUPT;
31769c98726SMax Reitz         return qcow2_update_header(bs);
31869c98726SMax Reitz     }
31969c98726SMax Reitz     return 0;
32069c98726SMax Reitz }
32169c98726SMax Reitz 
322acbe5982SStefan Hajnoczi static int qcow2_check(BlockDriverState *bs, BdrvCheckResult *result,
323acbe5982SStefan Hajnoczi                        BdrvCheckMode fix)
324acbe5982SStefan Hajnoczi {
325acbe5982SStefan Hajnoczi     int ret = qcow2_check_refcounts(bs, result, fix);
326acbe5982SStefan Hajnoczi     if (ret < 0) {
327acbe5982SStefan Hajnoczi         return ret;
328acbe5982SStefan Hajnoczi     }
329acbe5982SStefan Hajnoczi 
330acbe5982SStefan Hajnoczi     if (fix && result->check_errors == 0 && result->corruptions == 0) {
33124530f3eSMax Reitz         ret = qcow2_mark_clean(bs);
33224530f3eSMax Reitz         if (ret < 0) {
33324530f3eSMax Reitz             return ret;
33424530f3eSMax Reitz         }
33524530f3eSMax Reitz         return qcow2_mark_consistent(bs);
336acbe5982SStefan Hajnoczi     }
337acbe5982SStefan Hajnoczi     return ret;
338acbe5982SStefan Hajnoczi }
339acbe5982SStefan Hajnoczi 
3408c7de283SKevin Wolf static int validate_table_offset(BlockDriverState *bs, uint64_t offset,
3418c7de283SKevin Wolf                                  uint64_t entries, size_t entry_len)
3428c7de283SKevin Wolf {
343ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
3448c7de283SKevin Wolf     uint64_t size;
3458c7de283SKevin Wolf 
3468c7de283SKevin Wolf     /* Use signed INT64_MAX as the maximum even for uint64_t header fields,
3478c7de283SKevin Wolf      * because values will be passed to qemu functions taking int64_t. */
3488c7de283SKevin Wolf     if (entries > INT64_MAX / entry_len) {
3498c7de283SKevin Wolf         return -EINVAL;
3508c7de283SKevin Wolf     }
3518c7de283SKevin Wolf 
3528c7de283SKevin Wolf     size = entries * entry_len;
3538c7de283SKevin Wolf 
3548c7de283SKevin Wolf     if (INT64_MAX - size < offset) {
3558c7de283SKevin Wolf         return -EINVAL;
3568c7de283SKevin Wolf     }
3578c7de283SKevin Wolf 
3588c7de283SKevin Wolf     /* Tables must be cluster aligned */
3598c7de283SKevin Wolf     if (offset & (s->cluster_size - 1)) {
3608c7de283SKevin Wolf         return -EINVAL;
3618c7de283SKevin Wolf     }
3628c7de283SKevin Wolf 
3638c7de283SKevin Wolf     return 0;
3648c7de283SKevin Wolf }
3658c7de283SKevin Wolf 
36674c4510aSKevin Wolf static QemuOptsList qcow2_runtime_opts = {
36774c4510aSKevin Wolf     .name = "qcow2",
36874c4510aSKevin Wolf     .head = QTAILQ_HEAD_INITIALIZER(qcow2_runtime_opts.head),
36974c4510aSKevin Wolf     .desc = {
37074c4510aSKevin Wolf         {
37164aa99d3SKevin Wolf             .name = QCOW2_OPT_LAZY_REFCOUNTS,
37274c4510aSKevin Wolf             .type = QEMU_OPT_BOOL,
37374c4510aSKevin Wolf             .help = "Postpone refcount updates",
37474c4510aSKevin Wolf         },
37567af674eSKevin Wolf         {
37667af674eSKevin Wolf             .name = QCOW2_OPT_DISCARD_REQUEST,
37767af674eSKevin Wolf             .type = QEMU_OPT_BOOL,
37867af674eSKevin Wolf             .help = "Pass guest discard requests to the layer below",
37967af674eSKevin Wolf         },
38067af674eSKevin Wolf         {
38167af674eSKevin Wolf             .name = QCOW2_OPT_DISCARD_SNAPSHOT,
38267af674eSKevin Wolf             .type = QEMU_OPT_BOOL,
38367af674eSKevin Wolf             .help = "Generate discard requests when snapshot related space "
38467af674eSKevin Wolf                     "is freed",
38567af674eSKevin Wolf         },
38667af674eSKevin Wolf         {
38767af674eSKevin Wolf             .name = QCOW2_OPT_DISCARD_OTHER,
38867af674eSKevin Wolf             .type = QEMU_OPT_BOOL,
38967af674eSKevin Wolf             .help = "Generate discard requests when other clusters are freed",
39067af674eSKevin Wolf         },
39105de7e86SMax Reitz         {
39205de7e86SMax Reitz             .name = QCOW2_OPT_OVERLAP,
39305de7e86SMax Reitz             .type = QEMU_OPT_STRING,
39405de7e86SMax Reitz             .help = "Selects which overlap checks to perform from a range of "
39505de7e86SMax Reitz                     "templates (none, constant, cached, all)",
39605de7e86SMax Reitz         },
39705de7e86SMax Reitz         {
398ee42b5ceSMax Reitz             .name = QCOW2_OPT_OVERLAP_TEMPLATE,
399ee42b5ceSMax Reitz             .type = QEMU_OPT_STRING,
400ee42b5ceSMax Reitz             .help = "Selects which overlap checks to perform from a range of "
401ee42b5ceSMax Reitz                     "templates (none, constant, cached, all)",
402ee42b5ceSMax Reitz         },
403ee42b5ceSMax Reitz         {
40405de7e86SMax Reitz             .name = QCOW2_OPT_OVERLAP_MAIN_HEADER,
40505de7e86SMax Reitz             .type = QEMU_OPT_BOOL,
40605de7e86SMax Reitz             .help = "Check for unintended writes into the main qcow2 header",
40705de7e86SMax Reitz         },
40805de7e86SMax Reitz         {
40905de7e86SMax Reitz             .name = QCOW2_OPT_OVERLAP_ACTIVE_L1,
41005de7e86SMax Reitz             .type = QEMU_OPT_BOOL,
41105de7e86SMax Reitz             .help = "Check for unintended writes into the active L1 table",
41205de7e86SMax Reitz         },
41305de7e86SMax Reitz         {
41405de7e86SMax Reitz             .name = QCOW2_OPT_OVERLAP_ACTIVE_L2,
41505de7e86SMax Reitz             .type = QEMU_OPT_BOOL,
41605de7e86SMax Reitz             .help = "Check for unintended writes into an active L2 table",
41705de7e86SMax Reitz         },
41805de7e86SMax Reitz         {
41905de7e86SMax Reitz             .name = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
42005de7e86SMax Reitz             .type = QEMU_OPT_BOOL,
42105de7e86SMax Reitz             .help = "Check for unintended writes into the refcount table",
42205de7e86SMax Reitz         },
42305de7e86SMax Reitz         {
42405de7e86SMax Reitz             .name = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
42505de7e86SMax Reitz             .type = QEMU_OPT_BOOL,
42605de7e86SMax Reitz             .help = "Check for unintended writes into a refcount block",
42705de7e86SMax Reitz         },
42805de7e86SMax Reitz         {
42905de7e86SMax Reitz             .name = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
43005de7e86SMax Reitz             .type = QEMU_OPT_BOOL,
43105de7e86SMax Reitz             .help = "Check for unintended writes into the snapshot table",
43205de7e86SMax Reitz         },
43305de7e86SMax Reitz         {
43405de7e86SMax Reitz             .name = QCOW2_OPT_OVERLAP_INACTIVE_L1,
43505de7e86SMax Reitz             .type = QEMU_OPT_BOOL,
43605de7e86SMax Reitz             .help = "Check for unintended writes into an inactive L1 table",
43705de7e86SMax Reitz         },
43805de7e86SMax Reitz         {
43905de7e86SMax Reitz             .name = QCOW2_OPT_OVERLAP_INACTIVE_L2,
44005de7e86SMax Reitz             .type = QEMU_OPT_BOOL,
44105de7e86SMax Reitz             .help = "Check for unintended writes into an inactive L2 table",
44205de7e86SMax Reitz         },
4436c1c8d5dSMax Reitz         {
4446c1c8d5dSMax Reitz             .name = QCOW2_OPT_CACHE_SIZE,
4456c1c8d5dSMax Reitz             .type = QEMU_OPT_SIZE,
4466c1c8d5dSMax Reitz             .help = "Maximum combined metadata (L2 tables and refcount blocks) "
4476c1c8d5dSMax Reitz                     "cache size",
4486c1c8d5dSMax Reitz         },
4496c1c8d5dSMax Reitz         {
4506c1c8d5dSMax Reitz             .name = QCOW2_OPT_L2_CACHE_SIZE,
4516c1c8d5dSMax Reitz             .type = QEMU_OPT_SIZE,
4526c1c8d5dSMax Reitz             .help = "Maximum L2 table cache size",
4536c1c8d5dSMax Reitz         },
4546c1c8d5dSMax Reitz         {
4556c1c8d5dSMax Reitz             .name = QCOW2_OPT_REFCOUNT_CACHE_SIZE,
4566c1c8d5dSMax Reitz             .type = QEMU_OPT_SIZE,
4576c1c8d5dSMax Reitz             .help = "Maximum refcount block cache size",
4586c1c8d5dSMax Reitz         },
459279621c0SAlberto Garcia         {
460279621c0SAlberto Garcia             .name = QCOW2_OPT_CACHE_CLEAN_INTERVAL,
461279621c0SAlberto Garcia             .type = QEMU_OPT_NUMBER,
462279621c0SAlberto Garcia             .help = "Clean unused cache entries after this time (in seconds)",
463279621c0SAlberto Garcia         },
46474c4510aSKevin Wolf         { /* end of list */ }
46574c4510aSKevin Wolf     },
46674c4510aSKevin Wolf };
46774c4510aSKevin Wolf 
4684092e99dSMax Reitz static const char *overlap_bool_option_names[QCOW2_OL_MAX_BITNR] = {
4694092e99dSMax Reitz     [QCOW2_OL_MAIN_HEADER_BITNR]    = QCOW2_OPT_OVERLAP_MAIN_HEADER,
4704092e99dSMax Reitz     [QCOW2_OL_ACTIVE_L1_BITNR]      = QCOW2_OPT_OVERLAP_ACTIVE_L1,
4714092e99dSMax Reitz     [QCOW2_OL_ACTIVE_L2_BITNR]      = QCOW2_OPT_OVERLAP_ACTIVE_L2,
4724092e99dSMax Reitz     [QCOW2_OL_REFCOUNT_TABLE_BITNR] = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
4734092e99dSMax Reitz     [QCOW2_OL_REFCOUNT_BLOCK_BITNR] = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
4744092e99dSMax Reitz     [QCOW2_OL_SNAPSHOT_TABLE_BITNR] = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
4754092e99dSMax Reitz     [QCOW2_OL_INACTIVE_L1_BITNR]    = QCOW2_OPT_OVERLAP_INACTIVE_L1,
4764092e99dSMax Reitz     [QCOW2_OL_INACTIVE_L2_BITNR]    = QCOW2_OPT_OVERLAP_INACTIVE_L2,
4774092e99dSMax Reitz };
4784092e99dSMax Reitz 
479279621c0SAlberto Garcia static void cache_clean_timer_cb(void *opaque)
480279621c0SAlberto Garcia {
481279621c0SAlberto Garcia     BlockDriverState *bs = opaque;
482ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
483279621c0SAlberto Garcia     qcow2_cache_clean_unused(bs, s->l2_table_cache);
484279621c0SAlberto Garcia     qcow2_cache_clean_unused(bs, s->refcount_block_cache);
485279621c0SAlberto Garcia     timer_mod(s->cache_clean_timer, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) +
486279621c0SAlberto Garcia               (int64_t) s->cache_clean_interval * 1000);
487279621c0SAlberto Garcia }
488279621c0SAlberto Garcia 
489279621c0SAlberto Garcia static void cache_clean_timer_init(BlockDriverState *bs, AioContext *context)
490279621c0SAlberto Garcia {
491ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
492279621c0SAlberto Garcia     if (s->cache_clean_interval > 0) {
493279621c0SAlberto Garcia         s->cache_clean_timer = aio_timer_new(context, QEMU_CLOCK_VIRTUAL,
494279621c0SAlberto Garcia                                              SCALE_MS, cache_clean_timer_cb,
495279621c0SAlberto Garcia                                              bs);
496279621c0SAlberto Garcia         timer_mod(s->cache_clean_timer, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) +
497279621c0SAlberto Garcia                   (int64_t) s->cache_clean_interval * 1000);
498279621c0SAlberto Garcia     }
499279621c0SAlberto Garcia }
500279621c0SAlberto Garcia 
501279621c0SAlberto Garcia static void cache_clean_timer_del(BlockDriverState *bs)
502279621c0SAlberto Garcia {
503ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
504279621c0SAlberto Garcia     if (s->cache_clean_timer) {
505279621c0SAlberto Garcia         timer_del(s->cache_clean_timer);
506279621c0SAlberto Garcia         timer_free(s->cache_clean_timer);
507279621c0SAlberto Garcia         s->cache_clean_timer = NULL;
508279621c0SAlberto Garcia     }
509279621c0SAlberto Garcia }
510279621c0SAlberto Garcia 
511279621c0SAlberto Garcia static void qcow2_detach_aio_context(BlockDriverState *bs)
512279621c0SAlberto Garcia {
513279621c0SAlberto Garcia     cache_clean_timer_del(bs);
514279621c0SAlberto Garcia }
515279621c0SAlberto Garcia 
516279621c0SAlberto Garcia static void qcow2_attach_aio_context(BlockDriverState *bs,
517279621c0SAlberto Garcia                                      AioContext *new_context)
518279621c0SAlberto Garcia {
519279621c0SAlberto Garcia     cache_clean_timer_init(bs, new_context);
520279621c0SAlberto Garcia }
521279621c0SAlberto Garcia 
522bc85ef26SMax Reitz static void read_cache_sizes(BlockDriverState *bs, QemuOpts *opts,
523bc85ef26SMax Reitz                              uint64_t *l2_cache_size,
5246c1c8d5dSMax Reitz                              uint64_t *refcount_cache_size, Error **errp)
5256c1c8d5dSMax Reitz {
526ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
5276c1c8d5dSMax Reitz     uint64_t combined_cache_size;
5286c1c8d5dSMax Reitz     bool l2_cache_size_set, refcount_cache_size_set, combined_cache_size_set;
5296c1c8d5dSMax Reitz 
5306c1c8d5dSMax Reitz     combined_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_CACHE_SIZE);
5316c1c8d5dSMax Reitz     l2_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_L2_CACHE_SIZE);
5326c1c8d5dSMax Reitz     refcount_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
5336c1c8d5dSMax Reitz 
5346c1c8d5dSMax Reitz     combined_cache_size = qemu_opt_get_size(opts, QCOW2_OPT_CACHE_SIZE, 0);
5356c1c8d5dSMax Reitz     *l2_cache_size = qemu_opt_get_size(opts, QCOW2_OPT_L2_CACHE_SIZE, 0);
5366c1c8d5dSMax Reitz     *refcount_cache_size = qemu_opt_get_size(opts,
5376c1c8d5dSMax Reitz                                              QCOW2_OPT_REFCOUNT_CACHE_SIZE, 0);
5386c1c8d5dSMax Reitz 
5396c1c8d5dSMax Reitz     if (combined_cache_size_set) {
5406c1c8d5dSMax Reitz         if (l2_cache_size_set && refcount_cache_size_set) {
5416c1c8d5dSMax Reitz             error_setg(errp, QCOW2_OPT_CACHE_SIZE ", " QCOW2_OPT_L2_CACHE_SIZE
5426c1c8d5dSMax Reitz                        " and " QCOW2_OPT_REFCOUNT_CACHE_SIZE " may not be set "
5436c1c8d5dSMax Reitz                        "the same time");
5446c1c8d5dSMax Reitz             return;
5456c1c8d5dSMax Reitz         } else if (*l2_cache_size > combined_cache_size) {
5466c1c8d5dSMax Reitz             error_setg(errp, QCOW2_OPT_L2_CACHE_SIZE " may not exceed "
5476c1c8d5dSMax Reitz                        QCOW2_OPT_CACHE_SIZE);
5486c1c8d5dSMax Reitz             return;
5496c1c8d5dSMax Reitz         } else if (*refcount_cache_size > combined_cache_size) {
5506c1c8d5dSMax Reitz             error_setg(errp, QCOW2_OPT_REFCOUNT_CACHE_SIZE " may not exceed "
5516c1c8d5dSMax Reitz                        QCOW2_OPT_CACHE_SIZE);
5526c1c8d5dSMax Reitz             return;
5536c1c8d5dSMax Reitz         }
5546c1c8d5dSMax Reitz 
5556c1c8d5dSMax Reitz         if (l2_cache_size_set) {
5566c1c8d5dSMax Reitz             *refcount_cache_size = combined_cache_size - *l2_cache_size;
5576c1c8d5dSMax Reitz         } else if (refcount_cache_size_set) {
5586c1c8d5dSMax Reitz             *l2_cache_size = combined_cache_size - *refcount_cache_size;
5596c1c8d5dSMax Reitz         } else {
5606c1c8d5dSMax Reitz             *refcount_cache_size = combined_cache_size
5616c1c8d5dSMax Reitz                                  / (DEFAULT_L2_REFCOUNT_SIZE_RATIO + 1);
5626c1c8d5dSMax Reitz             *l2_cache_size = combined_cache_size - *refcount_cache_size;
5636c1c8d5dSMax Reitz         }
5646c1c8d5dSMax Reitz     } else {
5656c1c8d5dSMax Reitz         if (!l2_cache_size_set && !refcount_cache_size_set) {
566bc85ef26SMax Reitz             *l2_cache_size = MAX(DEFAULT_L2_CACHE_BYTE_SIZE,
567bc85ef26SMax Reitz                                  (uint64_t)DEFAULT_L2_CACHE_CLUSTERS
568bc85ef26SMax Reitz                                  * s->cluster_size);
5696c1c8d5dSMax Reitz             *refcount_cache_size = *l2_cache_size
5706c1c8d5dSMax Reitz                                  / DEFAULT_L2_REFCOUNT_SIZE_RATIO;
5716c1c8d5dSMax Reitz         } else if (!l2_cache_size_set) {
5726c1c8d5dSMax Reitz             *l2_cache_size = *refcount_cache_size
5736c1c8d5dSMax Reitz                            * DEFAULT_L2_REFCOUNT_SIZE_RATIO;
5746c1c8d5dSMax Reitz         } else if (!refcount_cache_size_set) {
5756c1c8d5dSMax Reitz             *refcount_cache_size = *l2_cache_size
5766c1c8d5dSMax Reitz                                  / DEFAULT_L2_REFCOUNT_SIZE_RATIO;
5776c1c8d5dSMax Reitz         }
5786c1c8d5dSMax Reitz     }
5796c1c8d5dSMax Reitz }
5806c1c8d5dSMax Reitz 
581ee55b173SKevin Wolf typedef struct Qcow2ReopenState {
582ee55b173SKevin Wolf     Qcow2Cache *l2_table_cache;
583ee55b173SKevin Wolf     Qcow2Cache *refcount_block_cache;
584ee55b173SKevin Wolf     bool use_lazy_refcounts;
585ee55b173SKevin Wolf     int overlap_check;
586ee55b173SKevin Wolf     bool discard_passthrough[QCOW2_DISCARD_MAX];
587ee55b173SKevin Wolf     uint64_t cache_clean_interval;
588ee55b173SKevin Wolf } Qcow2ReopenState;
589ee55b173SKevin Wolf 
590ee55b173SKevin Wolf static int qcow2_update_options_prepare(BlockDriverState *bs,
591ee55b173SKevin Wolf                                         Qcow2ReopenState *r,
592ee55b173SKevin Wolf                                         QDict *options, int flags,
593ee55b173SKevin Wolf                                         Error **errp)
5944c75d1a1SKevin Wolf {
5954c75d1a1SKevin Wolf     BDRVQcow2State *s = bs->opaque;
59694edf3fbSKevin Wolf     QemuOpts *opts = NULL;
5974c75d1a1SKevin Wolf     const char *opt_overlap_check, *opt_overlap_check_template;
5984c75d1a1SKevin Wolf     int overlap_check_template = 0;
59994edf3fbSKevin Wolf     uint64_t l2_cache_size, refcount_cache_size;
6004c75d1a1SKevin Wolf     int i;
60194edf3fbSKevin Wolf     Error *local_err = NULL;
6024c75d1a1SKevin Wolf     int ret;
6034c75d1a1SKevin Wolf 
60494edf3fbSKevin Wolf     opts = qemu_opts_create(&qcow2_runtime_opts, NULL, 0, &error_abort);
60594edf3fbSKevin Wolf     qemu_opts_absorb_qdict(opts, options, &local_err);
60694edf3fbSKevin Wolf     if (local_err) {
60794edf3fbSKevin Wolf         error_propagate(errp, local_err);
60894edf3fbSKevin Wolf         ret = -EINVAL;
60994edf3fbSKevin Wolf         goto fail;
61094edf3fbSKevin Wolf     }
61194edf3fbSKevin Wolf 
61294edf3fbSKevin Wolf     /* get L2 table/refcount block cache size from command line options */
61394edf3fbSKevin Wolf     read_cache_sizes(bs, opts, &l2_cache_size, &refcount_cache_size,
61494edf3fbSKevin Wolf                      &local_err);
61594edf3fbSKevin Wolf     if (local_err) {
61694edf3fbSKevin Wolf         error_propagate(errp, local_err);
61794edf3fbSKevin Wolf         ret = -EINVAL;
61894edf3fbSKevin Wolf         goto fail;
61994edf3fbSKevin Wolf     }
62094edf3fbSKevin Wolf 
62194edf3fbSKevin Wolf     l2_cache_size /= s->cluster_size;
62294edf3fbSKevin Wolf     if (l2_cache_size < MIN_L2_CACHE_SIZE) {
62394edf3fbSKevin Wolf         l2_cache_size = MIN_L2_CACHE_SIZE;
62494edf3fbSKevin Wolf     }
62594edf3fbSKevin Wolf     if (l2_cache_size > INT_MAX) {
62694edf3fbSKevin Wolf         error_setg(errp, "L2 cache size too big");
62794edf3fbSKevin Wolf         ret = -EINVAL;
62894edf3fbSKevin Wolf         goto fail;
62994edf3fbSKevin Wolf     }
63094edf3fbSKevin Wolf 
63194edf3fbSKevin Wolf     refcount_cache_size /= s->cluster_size;
63294edf3fbSKevin Wolf     if (refcount_cache_size < MIN_REFCOUNT_CACHE_SIZE) {
63394edf3fbSKevin Wolf         refcount_cache_size = MIN_REFCOUNT_CACHE_SIZE;
63494edf3fbSKevin Wolf     }
63594edf3fbSKevin Wolf     if (refcount_cache_size > INT_MAX) {
63694edf3fbSKevin Wolf         error_setg(errp, "Refcount cache size too big");
63794edf3fbSKevin Wolf         ret = -EINVAL;
63894edf3fbSKevin Wolf         goto fail;
63994edf3fbSKevin Wolf     }
64094edf3fbSKevin Wolf 
6415b0959a7SKevin Wolf     /* alloc new L2 table/refcount block cache, flush old one */
6425b0959a7SKevin Wolf     if (s->l2_table_cache) {
6435b0959a7SKevin Wolf         ret = qcow2_cache_flush(bs, s->l2_table_cache);
6445b0959a7SKevin Wolf         if (ret) {
6455b0959a7SKevin Wolf             error_setg_errno(errp, -ret, "Failed to flush the L2 table cache");
6465b0959a7SKevin Wolf             goto fail;
6475b0959a7SKevin Wolf         }
6485b0959a7SKevin Wolf     }
6495b0959a7SKevin Wolf 
6505b0959a7SKevin Wolf     if (s->refcount_block_cache) {
6515b0959a7SKevin Wolf         ret = qcow2_cache_flush(bs, s->refcount_block_cache);
6525b0959a7SKevin Wolf         if (ret) {
6535b0959a7SKevin Wolf             error_setg_errno(errp, -ret,
6545b0959a7SKevin Wolf                              "Failed to flush the refcount block cache");
6555b0959a7SKevin Wolf             goto fail;
6565b0959a7SKevin Wolf         }
6575b0959a7SKevin Wolf     }
6585b0959a7SKevin Wolf 
659ee55b173SKevin Wolf     r->l2_table_cache = qcow2_cache_create(bs, l2_cache_size);
660ee55b173SKevin Wolf     r->refcount_block_cache = qcow2_cache_create(bs, refcount_cache_size);
661ee55b173SKevin Wolf     if (r->l2_table_cache == NULL || r->refcount_block_cache == NULL) {
66294edf3fbSKevin Wolf         error_setg(errp, "Could not allocate metadata caches");
66394edf3fbSKevin Wolf         ret = -ENOMEM;
66494edf3fbSKevin Wolf         goto fail;
66594edf3fbSKevin Wolf     }
66694edf3fbSKevin Wolf 
66794edf3fbSKevin Wolf     /* New interval for cache cleanup timer */
668ee55b173SKevin Wolf     r->cache_clean_interval =
6695b0959a7SKevin Wolf         qemu_opt_get_number(opts, QCOW2_OPT_CACHE_CLEAN_INTERVAL,
6705b0959a7SKevin Wolf                             s->cache_clean_interval);
67191203f08SAlberto Garcia #ifndef CONFIG_LINUX
67291203f08SAlberto Garcia     if (r->cache_clean_interval != 0) {
67391203f08SAlberto Garcia         error_setg(errp, QCOW2_OPT_CACHE_CLEAN_INTERVAL
67491203f08SAlberto Garcia                    " not supported on this host");
67591203f08SAlberto Garcia         ret = -EINVAL;
67691203f08SAlberto Garcia         goto fail;
67791203f08SAlberto Garcia     }
67891203f08SAlberto Garcia #endif
679ee55b173SKevin Wolf     if (r->cache_clean_interval > UINT_MAX) {
68094edf3fbSKevin Wolf         error_setg(errp, "Cache clean interval too big");
68194edf3fbSKevin Wolf         ret = -EINVAL;
68294edf3fbSKevin Wolf         goto fail;
68394edf3fbSKevin Wolf     }
68494edf3fbSKevin Wolf 
6855b0959a7SKevin Wolf     /* lazy-refcounts; flush if going from enabled to disabled */
686ee55b173SKevin Wolf     r->use_lazy_refcounts = qemu_opt_get_bool(opts, QCOW2_OPT_LAZY_REFCOUNTS,
6874c75d1a1SKevin Wolf         (s->compatible_features & QCOW2_COMPAT_LAZY_REFCOUNTS));
688ee55b173SKevin Wolf     if (r->use_lazy_refcounts && s->qcow_version < 3) {
689007dbc39SKevin Wolf         error_setg(errp, "Lazy refcounts require a qcow2 image with at least "
690007dbc39SKevin Wolf                    "qemu 1.1 compatibility level");
691007dbc39SKevin Wolf         ret = -EINVAL;
692007dbc39SKevin Wolf         goto fail;
693007dbc39SKevin Wolf     }
6944c75d1a1SKevin Wolf 
6955b0959a7SKevin Wolf     if (s->use_lazy_refcounts && !r->use_lazy_refcounts) {
6965b0959a7SKevin Wolf         ret = qcow2_mark_clean(bs);
6975b0959a7SKevin Wolf         if (ret < 0) {
6985b0959a7SKevin Wolf             error_setg_errno(errp, -ret, "Failed to disable lazy refcounts");
6995b0959a7SKevin Wolf             goto fail;
7005b0959a7SKevin Wolf         }
7015b0959a7SKevin Wolf     }
7025b0959a7SKevin Wolf 
703007dbc39SKevin Wolf     /* Overlap check options */
7044c75d1a1SKevin Wolf     opt_overlap_check = qemu_opt_get(opts, QCOW2_OPT_OVERLAP);
7054c75d1a1SKevin Wolf     opt_overlap_check_template = qemu_opt_get(opts, QCOW2_OPT_OVERLAP_TEMPLATE);
7064c75d1a1SKevin Wolf     if (opt_overlap_check_template && opt_overlap_check &&
7074c75d1a1SKevin Wolf         strcmp(opt_overlap_check_template, opt_overlap_check))
7084c75d1a1SKevin Wolf     {
7094c75d1a1SKevin Wolf         error_setg(errp, "Conflicting values for qcow2 options '"
7104c75d1a1SKevin Wolf                    QCOW2_OPT_OVERLAP "' ('%s') and '" QCOW2_OPT_OVERLAP_TEMPLATE
7114c75d1a1SKevin Wolf                    "' ('%s')", opt_overlap_check, opt_overlap_check_template);
7124c75d1a1SKevin Wolf         ret = -EINVAL;
7134c75d1a1SKevin Wolf         goto fail;
7144c75d1a1SKevin Wolf     }
7154c75d1a1SKevin Wolf     if (!opt_overlap_check) {
7164c75d1a1SKevin Wolf         opt_overlap_check = opt_overlap_check_template ?: "cached";
7174c75d1a1SKevin Wolf     }
7184c75d1a1SKevin Wolf 
7194c75d1a1SKevin Wolf     if (!strcmp(opt_overlap_check, "none")) {
7204c75d1a1SKevin Wolf         overlap_check_template = 0;
7214c75d1a1SKevin Wolf     } else if (!strcmp(opt_overlap_check, "constant")) {
7224c75d1a1SKevin Wolf         overlap_check_template = QCOW2_OL_CONSTANT;
7234c75d1a1SKevin Wolf     } else if (!strcmp(opt_overlap_check, "cached")) {
7244c75d1a1SKevin Wolf         overlap_check_template = QCOW2_OL_CACHED;
7254c75d1a1SKevin Wolf     } else if (!strcmp(opt_overlap_check, "all")) {
7264c75d1a1SKevin Wolf         overlap_check_template = QCOW2_OL_ALL;
7274c75d1a1SKevin Wolf     } else {
7284c75d1a1SKevin Wolf         error_setg(errp, "Unsupported value '%s' for qcow2 option "
7294c75d1a1SKevin Wolf                    "'overlap-check'. Allowed are any of the following: "
7304c75d1a1SKevin Wolf                    "none, constant, cached, all", opt_overlap_check);
7314c75d1a1SKevin Wolf         ret = -EINVAL;
7324c75d1a1SKevin Wolf         goto fail;
7334c75d1a1SKevin Wolf     }
7344c75d1a1SKevin Wolf 
735ee55b173SKevin Wolf     r->overlap_check = 0;
7364c75d1a1SKevin Wolf     for (i = 0; i < QCOW2_OL_MAX_BITNR; i++) {
7374c75d1a1SKevin Wolf         /* overlap-check defines a template bitmask, but every flag may be
7384c75d1a1SKevin Wolf          * overwritten through the associated boolean option */
739ee55b173SKevin Wolf         r->overlap_check |=
7404c75d1a1SKevin Wolf             qemu_opt_get_bool(opts, overlap_bool_option_names[i],
7414c75d1a1SKevin Wolf                               overlap_check_template & (1 << i)) << i;
7424c75d1a1SKevin Wolf     }
7434c75d1a1SKevin Wolf 
744ee55b173SKevin Wolf     r->discard_passthrough[QCOW2_DISCARD_NEVER] = false;
745ee55b173SKevin Wolf     r->discard_passthrough[QCOW2_DISCARD_ALWAYS] = true;
746ee55b173SKevin Wolf     r->discard_passthrough[QCOW2_DISCARD_REQUEST] =
747007dbc39SKevin Wolf         qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_REQUEST,
748007dbc39SKevin Wolf                           flags & BDRV_O_UNMAP);
749ee55b173SKevin Wolf     r->discard_passthrough[QCOW2_DISCARD_SNAPSHOT] =
750007dbc39SKevin Wolf         qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_SNAPSHOT, true);
751ee55b173SKevin Wolf     r->discard_passthrough[QCOW2_DISCARD_OTHER] =
752007dbc39SKevin Wolf         qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_OTHER, false);
753007dbc39SKevin Wolf 
7544c75d1a1SKevin Wolf     ret = 0;
7554c75d1a1SKevin Wolf fail:
75694edf3fbSKevin Wolf     qemu_opts_del(opts);
75794edf3fbSKevin Wolf     opts = NULL;
758ee55b173SKevin Wolf     return ret;
759ee55b173SKevin Wolf }
760ee55b173SKevin Wolf 
761ee55b173SKevin Wolf static void qcow2_update_options_commit(BlockDriverState *bs,
762ee55b173SKevin Wolf                                         Qcow2ReopenState *r)
763ee55b173SKevin Wolf {
764ee55b173SKevin Wolf     BDRVQcow2State *s = bs->opaque;
765ee55b173SKevin Wolf     int i;
766ee55b173SKevin Wolf 
7675b0959a7SKevin Wolf     if (s->l2_table_cache) {
7685b0959a7SKevin Wolf         qcow2_cache_destroy(bs, s->l2_table_cache);
7695b0959a7SKevin Wolf     }
7705b0959a7SKevin Wolf     if (s->refcount_block_cache) {
7715b0959a7SKevin Wolf         qcow2_cache_destroy(bs, s->refcount_block_cache);
7725b0959a7SKevin Wolf     }
773ee55b173SKevin Wolf     s->l2_table_cache = r->l2_table_cache;
774ee55b173SKevin Wolf     s->refcount_block_cache = r->refcount_block_cache;
775ee55b173SKevin Wolf 
776ee55b173SKevin Wolf     s->overlap_check = r->overlap_check;
777ee55b173SKevin Wolf     s->use_lazy_refcounts = r->use_lazy_refcounts;
778ee55b173SKevin Wolf 
779ee55b173SKevin Wolf     for (i = 0; i < QCOW2_DISCARD_MAX; i++) {
780ee55b173SKevin Wolf         s->discard_passthrough[i] = r->discard_passthrough[i];
781ee55b173SKevin Wolf     }
782ee55b173SKevin Wolf 
7835b0959a7SKevin Wolf     if (s->cache_clean_interval != r->cache_clean_interval) {
7845b0959a7SKevin Wolf         cache_clean_timer_del(bs);
785ee55b173SKevin Wolf         s->cache_clean_interval = r->cache_clean_interval;
786ee55b173SKevin Wolf         cache_clean_timer_init(bs, bdrv_get_aio_context(bs));
787ee55b173SKevin Wolf     }
7885b0959a7SKevin Wolf }
789ee55b173SKevin Wolf 
790ee55b173SKevin Wolf static void qcow2_update_options_abort(BlockDriverState *bs,
791ee55b173SKevin Wolf                                        Qcow2ReopenState *r)
792ee55b173SKevin Wolf {
793ee55b173SKevin Wolf     if (r->l2_table_cache) {
794ee55b173SKevin Wolf         qcow2_cache_destroy(bs, r->l2_table_cache);
795ee55b173SKevin Wolf     }
796ee55b173SKevin Wolf     if (r->refcount_block_cache) {
797ee55b173SKevin Wolf         qcow2_cache_destroy(bs, r->refcount_block_cache);
798ee55b173SKevin Wolf     }
799ee55b173SKevin Wolf }
800ee55b173SKevin Wolf 
801ee55b173SKevin Wolf static int qcow2_update_options(BlockDriverState *bs, QDict *options,
802ee55b173SKevin Wolf                                 int flags, Error **errp)
803ee55b173SKevin Wolf {
804ee55b173SKevin Wolf     Qcow2ReopenState r = {};
805ee55b173SKevin Wolf     int ret;
806ee55b173SKevin Wolf 
807ee55b173SKevin Wolf     ret = qcow2_update_options_prepare(bs, &r, options, flags, errp);
808ee55b173SKevin Wolf     if (ret >= 0) {
809ee55b173SKevin Wolf         qcow2_update_options_commit(bs, &r);
810ee55b173SKevin Wolf     } else {
811ee55b173SKevin Wolf         qcow2_update_options_abort(bs, &r);
812ee55b173SKevin Wolf     }
81394edf3fbSKevin Wolf 
8144c75d1a1SKevin Wolf     return ret;
8154c75d1a1SKevin Wolf }
8164c75d1a1SKevin Wolf 
8174e4bf5c4SKevin Wolf static int qcow2_do_open(BlockDriverState *bs, QDict *options, int flags,
818015a1036SMax Reitz                          Error **errp)
819585f8587Sbellard {
820ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
8216d33e8e7SKevin Wolf     unsigned int len, i;
8226d33e8e7SKevin Wolf     int ret = 0;
823585f8587Sbellard     QCowHeader header;
82474c4510aSKevin Wolf     Error *local_err = NULL;
8259b80ddf3Saliguori     uint64_t ext_end;
8262cf7cfa1SKevin Wolf     uint64_t l1_vm_state_index;
827585f8587Sbellard 
828cf2ab8fcSKevin Wolf     ret = bdrv_pread(bs->file, 0, &header, sizeof(header));
8296d85a57eSJes Sorensen     if (ret < 0) {
8303ef6c40aSMax Reitz         error_setg_errno(errp, -ret, "Could not read qcow2 header");
831585f8587Sbellard         goto fail;
8326d85a57eSJes Sorensen     }
833585f8587Sbellard     be32_to_cpus(&header.magic);
834585f8587Sbellard     be32_to_cpus(&header.version);
835585f8587Sbellard     be64_to_cpus(&header.backing_file_offset);
836585f8587Sbellard     be32_to_cpus(&header.backing_file_size);
837585f8587Sbellard     be64_to_cpus(&header.size);
838585f8587Sbellard     be32_to_cpus(&header.cluster_bits);
839585f8587Sbellard     be32_to_cpus(&header.crypt_method);
840585f8587Sbellard     be64_to_cpus(&header.l1_table_offset);
841585f8587Sbellard     be32_to_cpus(&header.l1_size);
842585f8587Sbellard     be64_to_cpus(&header.refcount_table_offset);
843585f8587Sbellard     be32_to_cpus(&header.refcount_table_clusters);
844585f8587Sbellard     be64_to_cpus(&header.snapshots_offset);
845585f8587Sbellard     be32_to_cpus(&header.nb_snapshots);
846585f8587Sbellard 
847e8cdcec1SKevin Wolf     if (header.magic != QCOW_MAGIC) {
8483ef6c40aSMax Reitz         error_setg(errp, "Image is not in qcow2 format");
84976abe407SPaolo Bonzini         ret = -EINVAL;
850585f8587Sbellard         goto fail;
8516d85a57eSJes Sorensen     }
8526744cbabSKevin Wolf     if (header.version < 2 || header.version > 3) {
853a55448b3SMax Reitz         error_setg(errp, "Unsupported qcow2 version %" PRIu32, header.version);
854e8cdcec1SKevin Wolf         ret = -ENOTSUP;
855e8cdcec1SKevin Wolf         goto fail;
856e8cdcec1SKevin Wolf     }
8576744cbabSKevin Wolf 
8586744cbabSKevin Wolf     s->qcow_version = header.version;
8596744cbabSKevin Wolf 
86024342f2cSKevin Wolf     /* Initialise cluster size */
86124342f2cSKevin Wolf     if (header.cluster_bits < MIN_CLUSTER_BITS ||
86224342f2cSKevin Wolf         header.cluster_bits > MAX_CLUSTER_BITS) {
863521b2b5dSMax Reitz         error_setg(errp, "Unsupported cluster size: 2^%" PRIu32,
864521b2b5dSMax Reitz                    header.cluster_bits);
86524342f2cSKevin Wolf         ret = -EINVAL;
86624342f2cSKevin Wolf         goto fail;
86724342f2cSKevin Wolf     }
86824342f2cSKevin Wolf 
86924342f2cSKevin Wolf     s->cluster_bits = header.cluster_bits;
87024342f2cSKevin Wolf     s->cluster_size = 1 << s->cluster_bits;
87124342f2cSKevin Wolf     s->cluster_sectors = 1 << (s->cluster_bits - 9);
87224342f2cSKevin Wolf 
8736744cbabSKevin Wolf     /* Initialise version 3 header fields */
8746744cbabSKevin Wolf     if (header.version == 2) {
8756744cbabSKevin Wolf         header.incompatible_features    = 0;
8766744cbabSKevin Wolf         header.compatible_features      = 0;
8776744cbabSKevin Wolf         header.autoclear_features       = 0;
8786744cbabSKevin Wolf         header.refcount_order           = 4;
8796744cbabSKevin Wolf         header.header_length            = 72;
8806744cbabSKevin Wolf     } else {
8816744cbabSKevin Wolf         be64_to_cpus(&header.incompatible_features);
8826744cbabSKevin Wolf         be64_to_cpus(&header.compatible_features);
8836744cbabSKevin Wolf         be64_to_cpus(&header.autoclear_features);
8846744cbabSKevin Wolf         be32_to_cpus(&header.refcount_order);
8856744cbabSKevin Wolf         be32_to_cpus(&header.header_length);
88624342f2cSKevin Wolf 
88724342f2cSKevin Wolf         if (header.header_length < 104) {
88824342f2cSKevin Wolf             error_setg(errp, "qcow2 header too short");
88924342f2cSKevin Wolf             ret = -EINVAL;
89024342f2cSKevin Wolf             goto fail;
89124342f2cSKevin Wolf         }
89224342f2cSKevin Wolf     }
89324342f2cSKevin Wolf 
89424342f2cSKevin Wolf     if (header.header_length > s->cluster_size) {
89524342f2cSKevin Wolf         error_setg(errp, "qcow2 header exceeds cluster size");
89624342f2cSKevin Wolf         ret = -EINVAL;
89724342f2cSKevin Wolf         goto fail;
8986744cbabSKevin Wolf     }
8996744cbabSKevin Wolf 
9006744cbabSKevin Wolf     if (header.header_length > sizeof(header)) {
9016744cbabSKevin Wolf         s->unknown_header_fields_size = header.header_length - sizeof(header);
9026744cbabSKevin Wolf         s->unknown_header_fields = g_malloc(s->unknown_header_fields_size);
903cf2ab8fcSKevin Wolf         ret = bdrv_pread(bs->file, sizeof(header), s->unknown_header_fields,
9046744cbabSKevin Wolf                          s->unknown_header_fields_size);
9056744cbabSKevin Wolf         if (ret < 0) {
9063ef6c40aSMax Reitz             error_setg_errno(errp, -ret, "Could not read unknown qcow2 header "
9073ef6c40aSMax Reitz                              "fields");
9086744cbabSKevin Wolf             goto fail;
9096744cbabSKevin Wolf         }
9106744cbabSKevin Wolf     }
9116744cbabSKevin Wolf 
912a1b3955cSKevin Wolf     if (header.backing_file_offset > s->cluster_size) {
913a1b3955cSKevin Wolf         error_setg(errp, "Invalid backing file offset");
914a1b3955cSKevin Wolf         ret = -EINVAL;
915a1b3955cSKevin Wolf         goto fail;
916a1b3955cSKevin Wolf     }
917a1b3955cSKevin Wolf 
918cfcc4c62SKevin Wolf     if (header.backing_file_offset) {
919cfcc4c62SKevin Wolf         ext_end = header.backing_file_offset;
920cfcc4c62SKevin Wolf     } else {
921cfcc4c62SKevin Wolf         ext_end = 1 << header.cluster_bits;
922cfcc4c62SKevin Wolf     }
923cfcc4c62SKevin Wolf 
9246744cbabSKevin Wolf     /* Handle feature bits */
9256744cbabSKevin Wolf     s->incompatible_features    = header.incompatible_features;
9266744cbabSKevin Wolf     s->compatible_features      = header.compatible_features;
9276744cbabSKevin Wolf     s->autoclear_features       = header.autoclear_features;
9286744cbabSKevin Wolf 
929c61d0004SStefan Hajnoczi     if (s->incompatible_features & ~QCOW2_INCOMPAT_MASK) {
930cfcc4c62SKevin Wolf         void *feature_table = NULL;
931cfcc4c62SKevin Wolf         qcow2_read_extensions(bs, header.header_length, ext_end,
9323ef6c40aSMax Reitz                               &feature_table, NULL);
933a55448b3SMax Reitz         report_unsupported_feature(errp, feature_table,
934c61d0004SStefan Hajnoczi                                    s->incompatible_features &
935c61d0004SStefan Hajnoczi                                    ~QCOW2_INCOMPAT_MASK);
9366744cbabSKevin Wolf         ret = -ENOTSUP;
937c5a33ee9SPrasad Joshi         g_free(feature_table);
9386744cbabSKevin Wolf         goto fail;
9396744cbabSKevin Wolf     }
9406744cbabSKevin Wolf 
94169c98726SMax Reitz     if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
94269c98726SMax Reitz         /* Corrupt images may not be written to unless they are being repaired
94369c98726SMax Reitz          */
94469c98726SMax Reitz         if ((flags & BDRV_O_RDWR) && !(flags & BDRV_O_CHECK)) {
9453ef6c40aSMax Reitz             error_setg(errp, "qcow2: Image is corrupt; cannot be opened "
9463ef6c40aSMax Reitz                        "read/write");
94769c98726SMax Reitz             ret = -EACCES;
94869c98726SMax Reitz             goto fail;
94969c98726SMax Reitz         }
95069c98726SMax Reitz     }
95169c98726SMax Reitz 
9526744cbabSKevin Wolf     /* Check support for various header values */
953b72faf9fSMax Reitz     if (header.refcount_order > 6) {
954b72faf9fSMax Reitz         error_setg(errp, "Reference count entry width too large; may not "
955b72faf9fSMax Reitz                    "exceed 64 bits");
956b72faf9fSMax Reitz         ret = -EINVAL;
9576744cbabSKevin Wolf         goto fail;
9586744cbabSKevin Wolf     }
959b6481f37SMax Reitz     s->refcount_order = header.refcount_order;
960346a53dfSMax Reitz     s->refcount_bits = 1 << s->refcount_order;
961346a53dfSMax Reitz     s->refcount_max = UINT64_C(1) << (s->refcount_bits - 1);
962346a53dfSMax Reitz     s->refcount_max += s->refcount_max - 1;
9636744cbabSKevin Wolf 
9646d85a57eSJes Sorensen     if (header.crypt_method > QCOW_CRYPT_AES) {
965521b2b5dSMax Reitz         error_setg(errp, "Unsupported encryption method: %" PRIu32,
9663ef6c40aSMax Reitz                    header.crypt_method);
9676d85a57eSJes Sorensen         ret = -EINVAL;
968585f8587Sbellard         goto fail;
9696d85a57eSJes Sorensen     }
970f844836dSGonglei     if (!qcrypto_cipher_supports(QCRYPTO_CIPHER_ALG_AES_128,
971f844836dSGonglei                                  QCRYPTO_CIPHER_MODE_CBC)) {
972f6fa64f6SDaniel P. Berrange         error_setg(errp, "AES cipher not available");
973f6fa64f6SDaniel P. Berrange         ret = -EINVAL;
974f6fa64f6SDaniel P. Berrange         goto fail;
975f6fa64f6SDaniel P. Berrange     }
976585f8587Sbellard     s->crypt_method_header = header.crypt_method;
9776d85a57eSJes Sorensen     if (s->crypt_method_header) {
978e6ff69bfSDaniel P. Berrange         if (bdrv_uses_whitelist() &&
979e6ff69bfSDaniel P. Berrange             s->crypt_method_header == QCOW_CRYPT_AES) {
9808c0dcbc4SDaniel P. Berrange             error_setg(errp,
9818c0dcbc4SDaniel P. Berrange                        "Use of AES-CBC encrypted qcow2 images is no longer "
9828c0dcbc4SDaniel P. Berrange                        "supported in system emulators");
9838c0dcbc4SDaniel P. Berrange             error_append_hint(errp,
9848c0dcbc4SDaniel P. Berrange                               "You can use 'qemu-img convert' to convert your "
9858c0dcbc4SDaniel P. Berrange                               "image to an alternative supported format, such "
9868c0dcbc4SDaniel P. Berrange                               "as unencrypted qcow2, or raw with the LUKS "
9878c0dcbc4SDaniel P. Berrange                               "format instead.\n");
9888c0dcbc4SDaniel P. Berrange             ret = -ENOSYS;
9898c0dcbc4SDaniel P. Berrange             goto fail;
990e6ff69bfSDaniel P. Berrange         }
991e6ff69bfSDaniel P. Berrange 
99254115412SEric Blake         bs->encrypted = true;
9936d85a57eSJes Sorensen     }
99424342f2cSKevin Wolf 
995585f8587Sbellard     s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */
996585f8587Sbellard     s->l2_size = 1 << s->l2_bits;
9971d13d654SMax Reitz     /* 2^(s->refcount_order - 3) is the refcount width in bytes */
9981d13d654SMax Reitz     s->refcount_block_bits = s->cluster_bits - (s->refcount_order - 3);
9991d13d654SMax Reitz     s->refcount_block_size = 1 << s->refcount_block_bits;
1000585f8587Sbellard     bs->total_sectors = header.size / 512;
1001585f8587Sbellard     s->csize_shift = (62 - (s->cluster_bits - 8));
1002585f8587Sbellard     s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;
1003585f8587Sbellard     s->cluster_offset_mask = (1LL << s->csize_shift) - 1;
10045dab2fadSKevin Wolf 
1005585f8587Sbellard     s->refcount_table_offset = header.refcount_table_offset;
1006585f8587Sbellard     s->refcount_table_size =
1007585f8587Sbellard         header.refcount_table_clusters << (s->cluster_bits - 3);
1008585f8587Sbellard 
10092b5d5953SKevin Wolf     if (header.refcount_table_clusters > qcow2_max_refcount_clusters(s)) {
10105dab2fadSKevin Wolf         error_setg(errp, "Reference count table too large");
10115dab2fadSKevin Wolf         ret = -EINVAL;
10125dab2fadSKevin Wolf         goto fail;
10135dab2fadSKevin Wolf     }
10145dab2fadSKevin Wolf 
10158c7de283SKevin Wolf     ret = validate_table_offset(bs, s->refcount_table_offset,
10168c7de283SKevin Wolf                                 s->refcount_table_size, sizeof(uint64_t));
10178c7de283SKevin Wolf     if (ret < 0) {
10188c7de283SKevin Wolf         error_setg(errp, "Invalid reference count table offset");
10198c7de283SKevin Wolf         goto fail;
10208c7de283SKevin Wolf     }
10218c7de283SKevin Wolf 
1022ce48f2f4SKevin Wolf     /* Snapshot table offset/length */
1023ce48f2f4SKevin Wolf     if (header.nb_snapshots > QCOW_MAX_SNAPSHOTS) {
1024ce48f2f4SKevin Wolf         error_setg(errp, "Too many snapshots");
1025ce48f2f4SKevin Wolf         ret = -EINVAL;
1026ce48f2f4SKevin Wolf         goto fail;
1027ce48f2f4SKevin Wolf     }
1028ce48f2f4SKevin Wolf 
1029ce48f2f4SKevin Wolf     ret = validate_table_offset(bs, header.snapshots_offset,
1030ce48f2f4SKevin Wolf                                 header.nb_snapshots,
1031ce48f2f4SKevin Wolf                                 sizeof(QCowSnapshotHeader));
1032ce48f2f4SKevin Wolf     if (ret < 0) {
1033ce48f2f4SKevin Wolf         error_setg(errp, "Invalid snapshot table offset");
1034ce48f2f4SKevin Wolf         goto fail;
1035ce48f2f4SKevin Wolf     }
1036ce48f2f4SKevin Wolf 
1037585f8587Sbellard     /* read the level 1 table */
103887b86e7eSWen Congyang     if (header.l1_size > QCOW_MAX_L1_SIZE / sizeof(uint64_t)) {
10392d51c32cSKevin Wolf         error_setg(errp, "Active L1 table too large");
10402d51c32cSKevin Wolf         ret = -EFBIG;
10412d51c32cSKevin Wolf         goto fail;
10422d51c32cSKevin Wolf     }
1043585f8587Sbellard     s->l1_size = header.l1_size;
10442cf7cfa1SKevin Wolf 
10452cf7cfa1SKevin Wolf     l1_vm_state_index = size_to_l1(s, header.size);
10462cf7cfa1SKevin Wolf     if (l1_vm_state_index > INT_MAX) {
10473ef6c40aSMax Reitz         error_setg(errp, "Image is too big");
10482cf7cfa1SKevin Wolf         ret = -EFBIG;
10492cf7cfa1SKevin Wolf         goto fail;
10502cf7cfa1SKevin Wolf     }
10512cf7cfa1SKevin Wolf     s->l1_vm_state_index = l1_vm_state_index;
10522cf7cfa1SKevin Wolf 
1053585f8587Sbellard     /* the L1 table must contain at least enough entries to put
1054585f8587Sbellard        header.size bytes */
10556d85a57eSJes Sorensen     if (s->l1_size < s->l1_vm_state_index) {
10563ef6c40aSMax Reitz         error_setg(errp, "L1 table is too small");
10576d85a57eSJes Sorensen         ret = -EINVAL;
1058585f8587Sbellard         goto fail;
10596d85a57eSJes Sorensen     }
10602d51c32cSKevin Wolf 
10612d51c32cSKevin Wolf     ret = validate_table_offset(bs, header.l1_table_offset,
10622d51c32cSKevin Wolf                                 header.l1_size, sizeof(uint64_t));
10632d51c32cSKevin Wolf     if (ret < 0) {
10642d51c32cSKevin Wolf         error_setg(errp, "Invalid L1 table offset");
10652d51c32cSKevin Wolf         goto fail;
10662d51c32cSKevin Wolf     }
1067585f8587Sbellard     s->l1_table_offset = header.l1_table_offset;
10682d51c32cSKevin Wolf 
10692d51c32cSKevin Wolf 
1070d191d12dSStefan Weil     if (s->l1_size > 0) {
10719a4f4c31SKevin Wolf         s->l1_table = qemu_try_blockalign(bs->file->bs,
10723f6a3ee5SKevin Wolf             align_offset(s->l1_size * sizeof(uint64_t), 512));
1073de82815dSKevin Wolf         if (s->l1_table == NULL) {
1074de82815dSKevin Wolf             error_setg(errp, "Could not allocate L1 table");
1075de82815dSKevin Wolf             ret = -ENOMEM;
1076de82815dSKevin Wolf             goto fail;
1077de82815dSKevin Wolf         }
1078cf2ab8fcSKevin Wolf         ret = bdrv_pread(bs->file, s->l1_table_offset, s->l1_table,
10796d85a57eSJes Sorensen                          s->l1_size * sizeof(uint64_t));
10806d85a57eSJes Sorensen         if (ret < 0) {
10813ef6c40aSMax Reitz             error_setg_errno(errp, -ret, "Could not read L1 table");
1082585f8587Sbellard             goto fail;
10836d85a57eSJes Sorensen         }
1084585f8587Sbellard         for(i = 0;i < s->l1_size; i++) {
1085585f8587Sbellard             be64_to_cpus(&s->l1_table[i]);
1086585f8587Sbellard         }
1087d191d12dSStefan Weil     }
108829c1a730SKevin Wolf 
108994edf3fbSKevin Wolf     /* Parse driver-specific options */
109094edf3fbSKevin Wolf     ret = qcow2_update_options(bs, options, flags, errp);
109190efa0eaSKevin Wolf     if (ret < 0) {
109290efa0eaSKevin Wolf         goto fail;
109390efa0eaSKevin Wolf     }
109490efa0eaSKevin Wolf 
10957267c094SAnthony Liguori     s->cluster_cache = g_malloc(s->cluster_size);
1096585f8587Sbellard     /* one more sector for decompressed data alignment */
10979a4f4c31SKevin Wolf     s->cluster_data = qemu_try_blockalign(bs->file->bs, QCOW_MAX_CRYPT_CLUSTERS
1098de82815dSKevin Wolf                                                     * s->cluster_size + 512);
1099de82815dSKevin Wolf     if (s->cluster_data == NULL) {
1100de82815dSKevin Wolf         error_setg(errp, "Could not allocate temporary cluster buffer");
1101de82815dSKevin Wolf         ret = -ENOMEM;
1102de82815dSKevin Wolf         goto fail;
1103de82815dSKevin Wolf     }
1104de82815dSKevin Wolf 
1105585f8587Sbellard     s->cluster_cache_offset = -1;
110606d9260fSAnthony Liguori     s->flags = flags;
1107585f8587Sbellard 
11086d85a57eSJes Sorensen     ret = qcow2_refcount_init(bs);
11096d85a57eSJes Sorensen     if (ret != 0) {
11103ef6c40aSMax Reitz         error_setg_errno(errp, -ret, "Could not initialize refcount handling");
1111585f8587Sbellard         goto fail;
11126d85a57eSJes Sorensen     }
1113585f8587Sbellard 
111472cf2d4fSBlue Swirl     QLIST_INIT(&s->cluster_allocs);
11150b919faeSKevin Wolf     QTAILQ_INIT(&s->discards);
1116f214978aSKevin Wolf 
11179b80ddf3Saliguori     /* read qcow2 extensions */
11183ef6c40aSMax Reitz     if (qcow2_read_extensions(bs, header.header_length, ext_end, NULL,
11193ef6c40aSMax Reitz         &local_err)) {
11203ef6c40aSMax Reitz         error_propagate(errp, local_err);
11216d85a57eSJes Sorensen         ret = -EINVAL;
11229b80ddf3Saliguori         goto fail;
11236d85a57eSJes Sorensen     }
11249b80ddf3Saliguori 
1125585f8587Sbellard     /* read the backing file name */
1126585f8587Sbellard     if (header.backing_file_offset != 0) {
1127585f8587Sbellard         len = header.backing_file_size;
11289a29e18fSJeff Cody         if (len > MIN(1023, s->cluster_size - header.backing_file_offset) ||
1129e729fa6aSJeff Cody             len >= sizeof(bs->backing_file)) {
11306d33e8e7SKevin Wolf             error_setg(errp, "Backing file name too long");
11316d33e8e7SKevin Wolf             ret = -EINVAL;
11326d33e8e7SKevin Wolf             goto fail;
11336d85a57eSJes Sorensen         }
1134cf2ab8fcSKevin Wolf         ret = bdrv_pread(bs->file, header.backing_file_offset,
11356d85a57eSJes Sorensen                          bs->backing_file, len);
11366d85a57eSJes Sorensen         if (ret < 0) {
11373ef6c40aSMax Reitz             error_setg_errno(errp, -ret, "Could not read backing file name");
1138585f8587Sbellard             goto fail;
11396d85a57eSJes Sorensen         }
1140585f8587Sbellard         bs->backing_file[len] = '\0';
1141e4603fe1SKevin Wolf         s->image_backing_file = g_strdup(bs->backing_file);
1142585f8587Sbellard     }
114342deb29fSKevin Wolf 
114411b128f4SKevin Wolf     /* Internal snapshots */
114511b128f4SKevin Wolf     s->snapshots_offset = header.snapshots_offset;
114611b128f4SKevin Wolf     s->nb_snapshots = header.nb_snapshots;
114711b128f4SKevin Wolf 
114842deb29fSKevin Wolf     ret = qcow2_read_snapshots(bs);
114942deb29fSKevin Wolf     if (ret < 0) {
11503ef6c40aSMax Reitz         error_setg_errno(errp, -ret, "Could not read snapshots");
1151585f8587Sbellard         goto fail;
11526d85a57eSJes Sorensen     }
1153585f8587Sbellard 
1154af7b708dSStefan Hajnoczi     /* Clear unknown autoclear feature bits */
115504c01a5cSKevin Wolf     if (!bs->read_only && !(flags & BDRV_O_INACTIVE) && s->autoclear_features) {
1156af7b708dSStefan Hajnoczi         s->autoclear_features = 0;
1157af7b708dSStefan Hajnoczi         ret = qcow2_update_header(bs);
1158af7b708dSStefan Hajnoczi         if (ret < 0) {
11593ef6c40aSMax Reitz             error_setg_errno(errp, -ret, "Could not update qcow2 header");
1160af7b708dSStefan Hajnoczi             goto fail;
1161af7b708dSStefan Hajnoczi         }
1162af7b708dSStefan Hajnoczi     }
1163af7b708dSStefan Hajnoczi 
116468d100e9SKevin Wolf     /* Initialise locks */
116568d100e9SKevin Wolf     qemu_co_mutex_init(&s->lock);
1166170f4b2eSFam Zheng     bs->supported_zero_flags = BDRV_REQ_MAY_UNMAP;
116768d100e9SKevin Wolf 
1168c61d0004SStefan Hajnoczi     /* Repair image if dirty */
116904c01a5cSKevin Wolf     if (!(flags & (BDRV_O_CHECK | BDRV_O_INACTIVE)) && !bs->read_only &&
1170058f8f16SStefan Hajnoczi         (s->incompatible_features & QCOW2_INCOMPAT_DIRTY)) {
1171c61d0004SStefan Hajnoczi         BdrvCheckResult result = {0};
1172c61d0004SStefan Hajnoczi 
11735b84106bSMax Reitz         ret = qcow2_check(bs, &result, BDRV_FIX_ERRORS | BDRV_FIX_LEAKS);
1174c61d0004SStefan Hajnoczi         if (ret < 0) {
11753ef6c40aSMax Reitz             error_setg_errno(errp, -ret, "Could not repair dirty image");
1176c61d0004SStefan Hajnoczi             goto fail;
1177c61d0004SStefan Hajnoczi         }
1178c61d0004SStefan Hajnoczi     }
1179c61d0004SStefan Hajnoczi 
1180585f8587Sbellard #ifdef DEBUG_ALLOC
11816cbc3031SPhilipp Hahn     {
11826cbc3031SPhilipp Hahn         BdrvCheckResult result = {0};
1183b35278f7SStefan Hajnoczi         qcow2_check_refcounts(bs, &result, 0);
11846cbc3031SPhilipp Hahn     }
1185585f8587Sbellard #endif
11866d85a57eSJes Sorensen     return ret;
1187585f8587Sbellard 
1188585f8587Sbellard  fail:
11896744cbabSKevin Wolf     g_free(s->unknown_header_fields);
119075bab85cSKevin Wolf     cleanup_unknown_header_ext(bs);
1191ed6ccf0fSKevin Wolf     qcow2_free_snapshots(bs);
1192ed6ccf0fSKevin Wolf     qcow2_refcount_close(bs);
1193de82815dSKevin Wolf     qemu_vfree(s->l1_table);
1194cf93980eSMax Reitz     /* else pre-write overlap checks in cache_destroy may crash */
1195cf93980eSMax Reitz     s->l1_table = NULL;
1196279621c0SAlberto Garcia     cache_clean_timer_del(bs);
119729c1a730SKevin Wolf     if (s->l2_table_cache) {
119829c1a730SKevin Wolf         qcow2_cache_destroy(bs, s->l2_table_cache);
119929c1a730SKevin Wolf     }
1200c5a33ee9SPrasad Joshi     if (s->refcount_block_cache) {
1201c5a33ee9SPrasad Joshi         qcow2_cache_destroy(bs, s->refcount_block_cache);
1202c5a33ee9SPrasad Joshi     }
12037267c094SAnthony Liguori     g_free(s->cluster_cache);
1204dea43a65SFrediano Ziglio     qemu_vfree(s->cluster_data);
12056d85a57eSJes Sorensen     return ret;
1206585f8587Sbellard }
1207585f8587Sbellard 
12084e4bf5c4SKevin Wolf static int qcow2_open(BlockDriverState *bs, QDict *options, int flags,
12094e4bf5c4SKevin Wolf                       Error **errp)
12104e4bf5c4SKevin Wolf {
12114e4bf5c4SKevin Wolf     bs->file = bdrv_open_child(NULL, options, "file", bs, &child_file,
12124e4bf5c4SKevin Wolf                                false, errp);
12134e4bf5c4SKevin Wolf     if (!bs->file) {
12144e4bf5c4SKevin Wolf         return -EINVAL;
12154e4bf5c4SKevin Wolf     }
12164e4bf5c4SKevin Wolf 
12174e4bf5c4SKevin Wolf     return qcow2_do_open(bs, options, flags, errp);
12184e4bf5c4SKevin Wolf }
12194e4bf5c4SKevin Wolf 
12203baca891SKevin Wolf static void qcow2_refresh_limits(BlockDriverState *bs, Error **errp)
1221d34682cdSKevin Wolf {
1222ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
1223d34682cdSKevin Wolf 
1224a84178ccSEric Blake     if (bs->encrypted) {
1225a84178ccSEric Blake         /* Encryption works on a sector granularity */
1226a5b8dd2cSEric Blake         bs->bl.request_alignment = BDRV_SECTOR_SIZE;
1227a84178ccSEric Blake     }
1228cf081fcaSEric Blake     bs->bl.pwrite_zeroes_alignment = s->cluster_size;
1229ecdbead6SEric Blake     bs->bl.pdiscard_alignment = s->cluster_size;
1230d34682cdSKevin Wolf }
1231d34682cdSKevin Wolf 
12327c80ab3fSJes Sorensen static int qcow2_set_key(BlockDriverState *bs, const char *key)
1233585f8587Sbellard {
1234ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
1235585f8587Sbellard     uint8_t keybuf[16];
1236585f8587Sbellard     int len, i;
1237f6fa64f6SDaniel P. Berrange     Error *err = NULL;
1238585f8587Sbellard 
1239585f8587Sbellard     memset(keybuf, 0, 16);
1240585f8587Sbellard     len = strlen(key);
1241585f8587Sbellard     if (len > 16)
1242585f8587Sbellard         len = 16;
1243585f8587Sbellard     /* XXX: we could compress the chars to 7 bits to increase
1244585f8587Sbellard        entropy */
1245585f8587Sbellard     for(i = 0;i < len;i++) {
1246585f8587Sbellard         keybuf[i] = key[i];
1247585f8587Sbellard     }
12488336aafaSDaniel P. Berrange     assert(bs->encrypted);
1249585f8587Sbellard 
1250f6fa64f6SDaniel P. Berrange     qcrypto_cipher_free(s->cipher);
1251f6fa64f6SDaniel P. Berrange     s->cipher = qcrypto_cipher_new(
1252f6fa64f6SDaniel P. Berrange         QCRYPTO_CIPHER_ALG_AES_128,
1253f6fa64f6SDaniel P. Berrange         QCRYPTO_CIPHER_MODE_CBC,
1254f6fa64f6SDaniel P. Berrange         keybuf, G_N_ELEMENTS(keybuf),
1255f6fa64f6SDaniel P. Berrange         &err);
1256f6fa64f6SDaniel P. Berrange 
1257f6fa64f6SDaniel P. Berrange     if (!s->cipher) {
1258f6fa64f6SDaniel P. Berrange         /* XXX would be nice if errors in this method could
1259f6fa64f6SDaniel P. Berrange          * be properly propagate to the caller. Would need
1260f6fa64f6SDaniel P. Berrange          * the bdrv_set_key() API signature to be fixed. */
1261f6fa64f6SDaniel P. Berrange         error_free(err);
1262585f8587Sbellard         return -1;
1263585f8587Sbellard     }
1264585f8587Sbellard     return 0;
1265585f8587Sbellard }
1266585f8587Sbellard 
126721d82ac9SJeff Cody static int qcow2_reopen_prepare(BDRVReopenState *state,
126821d82ac9SJeff Cody                                 BlockReopenQueue *queue, Error **errp)
126921d82ac9SJeff Cody {
12705b0959a7SKevin Wolf     Qcow2ReopenState *r;
12714c2e5f8fSKevin Wolf     int ret;
12724c2e5f8fSKevin Wolf 
12735b0959a7SKevin Wolf     r = g_new0(Qcow2ReopenState, 1);
12745b0959a7SKevin Wolf     state->opaque = r;
12755b0959a7SKevin Wolf 
12765b0959a7SKevin Wolf     ret = qcow2_update_options_prepare(state->bs, r, state->options,
12775b0959a7SKevin Wolf                                        state->flags, errp);
12785b0959a7SKevin Wolf     if (ret < 0) {
12795b0959a7SKevin Wolf         goto fail;
12805b0959a7SKevin Wolf     }
12815b0959a7SKevin Wolf 
12825b0959a7SKevin Wolf     /* We need to write out any unwritten data if we reopen read-only. */
12834c2e5f8fSKevin Wolf     if ((state->flags & BDRV_O_RDWR) == 0) {
12844c2e5f8fSKevin Wolf         ret = bdrv_flush(state->bs);
12854c2e5f8fSKevin Wolf         if (ret < 0) {
12865b0959a7SKevin Wolf             goto fail;
12874c2e5f8fSKevin Wolf         }
12884c2e5f8fSKevin Wolf 
12894c2e5f8fSKevin Wolf         ret = qcow2_mark_clean(state->bs);
12904c2e5f8fSKevin Wolf         if (ret < 0) {
12915b0959a7SKevin Wolf             goto fail;
12924c2e5f8fSKevin Wolf         }
12934c2e5f8fSKevin Wolf     }
12944c2e5f8fSKevin Wolf 
129521d82ac9SJeff Cody     return 0;
12965b0959a7SKevin Wolf 
12975b0959a7SKevin Wolf fail:
12985b0959a7SKevin Wolf     qcow2_update_options_abort(state->bs, r);
12995b0959a7SKevin Wolf     g_free(r);
13005b0959a7SKevin Wolf     return ret;
13015b0959a7SKevin Wolf }
13025b0959a7SKevin Wolf 
13035b0959a7SKevin Wolf static void qcow2_reopen_commit(BDRVReopenState *state)
13045b0959a7SKevin Wolf {
13055b0959a7SKevin Wolf     qcow2_update_options_commit(state->bs, state->opaque);
13065b0959a7SKevin Wolf     g_free(state->opaque);
13075b0959a7SKevin Wolf }
13085b0959a7SKevin Wolf 
13095b0959a7SKevin Wolf static void qcow2_reopen_abort(BDRVReopenState *state)
13105b0959a7SKevin Wolf {
13115b0959a7SKevin Wolf     qcow2_update_options_abort(state->bs, state->opaque);
13125b0959a7SKevin Wolf     g_free(state->opaque);
131321d82ac9SJeff Cody }
131421d82ac9SJeff Cody 
13155365f44dSKevin Wolf static void qcow2_join_options(QDict *options, QDict *old_options)
13165365f44dSKevin Wolf {
13175365f44dSKevin Wolf     bool has_new_overlap_template =
13185365f44dSKevin Wolf         qdict_haskey(options, QCOW2_OPT_OVERLAP) ||
13195365f44dSKevin Wolf         qdict_haskey(options, QCOW2_OPT_OVERLAP_TEMPLATE);
13205365f44dSKevin Wolf     bool has_new_total_cache_size =
13215365f44dSKevin Wolf         qdict_haskey(options, QCOW2_OPT_CACHE_SIZE);
13225365f44dSKevin Wolf     bool has_all_cache_options;
13235365f44dSKevin Wolf 
13245365f44dSKevin Wolf     /* New overlap template overrides all old overlap options */
13255365f44dSKevin Wolf     if (has_new_overlap_template) {
13265365f44dSKevin Wolf         qdict_del(old_options, QCOW2_OPT_OVERLAP);
13275365f44dSKevin Wolf         qdict_del(old_options, QCOW2_OPT_OVERLAP_TEMPLATE);
13285365f44dSKevin Wolf         qdict_del(old_options, QCOW2_OPT_OVERLAP_MAIN_HEADER);
13295365f44dSKevin Wolf         qdict_del(old_options, QCOW2_OPT_OVERLAP_ACTIVE_L1);
13305365f44dSKevin Wolf         qdict_del(old_options, QCOW2_OPT_OVERLAP_ACTIVE_L2);
13315365f44dSKevin Wolf         qdict_del(old_options, QCOW2_OPT_OVERLAP_REFCOUNT_TABLE);
13325365f44dSKevin Wolf         qdict_del(old_options, QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK);
13335365f44dSKevin Wolf         qdict_del(old_options, QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE);
13345365f44dSKevin Wolf         qdict_del(old_options, QCOW2_OPT_OVERLAP_INACTIVE_L1);
13355365f44dSKevin Wolf         qdict_del(old_options, QCOW2_OPT_OVERLAP_INACTIVE_L2);
13365365f44dSKevin Wolf     }
13375365f44dSKevin Wolf 
13385365f44dSKevin Wolf     /* New total cache size overrides all old options */
13395365f44dSKevin Wolf     if (qdict_haskey(options, QCOW2_OPT_CACHE_SIZE)) {
13405365f44dSKevin Wolf         qdict_del(old_options, QCOW2_OPT_L2_CACHE_SIZE);
13415365f44dSKevin Wolf         qdict_del(old_options, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
13425365f44dSKevin Wolf     }
13435365f44dSKevin Wolf 
13445365f44dSKevin Wolf     qdict_join(options, old_options, false);
13455365f44dSKevin Wolf 
13465365f44dSKevin Wolf     /*
13475365f44dSKevin Wolf      * If after merging all cache size options are set, an old total size is
13485365f44dSKevin Wolf      * overwritten. Do keep all options, however, if all three are new. The
13495365f44dSKevin Wolf      * resulting error message is what we want to happen.
13505365f44dSKevin Wolf      */
13515365f44dSKevin Wolf     has_all_cache_options =
13525365f44dSKevin Wolf         qdict_haskey(options, QCOW2_OPT_CACHE_SIZE) ||
13535365f44dSKevin Wolf         qdict_haskey(options, QCOW2_OPT_L2_CACHE_SIZE) ||
13545365f44dSKevin Wolf         qdict_haskey(options, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
13555365f44dSKevin Wolf 
13565365f44dSKevin Wolf     if (has_all_cache_options && !has_new_total_cache_size) {
13575365f44dSKevin Wolf         qdict_del(options, QCOW2_OPT_CACHE_SIZE);
13585365f44dSKevin Wolf     }
13595365f44dSKevin Wolf }
13605365f44dSKevin Wolf 
1361b6b8a333SPaolo Bonzini static int64_t coroutine_fn qcow2_co_get_block_status(BlockDriverState *bs,
136267a0fd2aSFam Zheng         int64_t sector_num, int nb_sectors, int *pnum, BlockDriverState **file)
1363585f8587Sbellard {
1364ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
1365585f8587Sbellard     uint64_t cluster_offset;
13664bc74be9SPaolo Bonzini     int index_in_cluster, ret;
1367ecfe1863SKevin Wolf     unsigned int bytes;
13684bc74be9SPaolo Bonzini     int64_t status = 0;
1369585f8587Sbellard 
1370ecfe1863SKevin Wolf     bytes = MIN(INT_MAX, nb_sectors * BDRV_SECTOR_SIZE);
1371f8a2e5e3SStefan Hajnoczi     qemu_co_mutex_lock(&s->lock);
1372ecfe1863SKevin Wolf     ret = qcow2_get_cluster_offset(bs, sector_num << 9, &bytes,
1373ecfe1863SKevin Wolf                                    &cluster_offset);
1374f8a2e5e3SStefan Hajnoczi     qemu_co_mutex_unlock(&s->lock);
13751c46efaaSKevin Wolf     if (ret < 0) {
1376d663640cSPaolo Bonzini         return ret;
13771c46efaaSKevin Wolf     }
1378095a9c58Saliguori 
1379ecfe1863SKevin Wolf     *pnum = bytes >> BDRV_SECTOR_BITS;
1380ecfe1863SKevin Wolf 
13814bc74be9SPaolo Bonzini     if (cluster_offset != 0 && ret != QCOW2_CLUSTER_COMPRESSED &&
1382f6fa64f6SDaniel P. Berrange         !s->cipher) {
13834bc74be9SPaolo Bonzini         index_in_cluster = sector_num & (s->cluster_sectors - 1);
13844bc74be9SPaolo Bonzini         cluster_offset |= (index_in_cluster << BDRV_SECTOR_BITS);
1385178b4db7SFam Zheng         *file = bs->file->bs;
13864bc74be9SPaolo Bonzini         status |= BDRV_BLOCK_OFFSET_VALID | cluster_offset;
13874bc74be9SPaolo Bonzini     }
13884bc74be9SPaolo Bonzini     if (ret == QCOW2_CLUSTER_ZERO) {
13894bc74be9SPaolo Bonzini         status |= BDRV_BLOCK_ZERO;
13904bc74be9SPaolo Bonzini     } else if (ret != QCOW2_CLUSTER_UNALLOCATED) {
13914bc74be9SPaolo Bonzini         status |= BDRV_BLOCK_DATA;
13924bc74be9SPaolo Bonzini     }
13934bc74be9SPaolo Bonzini     return status;
1394585f8587Sbellard }
1395585f8587Sbellard 
1396a9465922Sbellard /* handle reading after the end of the backing file */
1397bd28f835SKevin Wolf int qcow2_backing_read1(BlockDriverState *bs, QEMUIOVector *qiov,
1398ecfe1863SKevin Wolf                         int64_t offset, int bytes)
1399a9465922Sbellard {
1400ecfe1863SKevin Wolf     uint64_t bs_size = bs->total_sectors * BDRV_SECTOR_SIZE;
1401a9465922Sbellard     int n1;
1402bd28f835SKevin Wolf 
1403ecfe1863SKevin Wolf     if ((offset + bytes) <= bs_size) {
1404ecfe1863SKevin Wolf         return bytes;
1405ecfe1863SKevin Wolf     }
1406ecfe1863SKevin Wolf 
1407ecfe1863SKevin Wolf     if (offset >= bs_size) {
1408ecfe1863SKevin Wolf         n1 = 0;
1409ecfe1863SKevin Wolf     } else {
1410ecfe1863SKevin Wolf         n1 = bs_size - offset;
1411ecfe1863SKevin Wolf     }
1412ecfe1863SKevin Wolf 
1413ecfe1863SKevin Wolf     qemu_iovec_memset(qiov, n1, 0, bytes - n1);
1414bd28f835SKevin Wolf 
1415a9465922Sbellard     return n1;
1416a9465922Sbellard }
1417a9465922Sbellard 
1418ecfe1863SKevin Wolf static coroutine_fn int qcow2_co_preadv(BlockDriverState *bs, uint64_t offset,
1419ecfe1863SKevin Wolf                                         uint64_t bytes, QEMUIOVector *qiov,
1420ecfe1863SKevin Wolf                                         int flags)
14211490791fSaliguori {
1422ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
1423ecfe1863SKevin Wolf     int offset_in_cluster, n1;
142468d100e9SKevin Wolf     int ret;
1425ecfe1863SKevin Wolf     unsigned int cur_bytes; /* number of bytes in current iteration */
1426c2bdd990SFrediano Ziglio     uint64_t cluster_offset = 0;
14273fc48d09SFrediano Ziglio     uint64_t bytes_done = 0;
14283fc48d09SFrediano Ziglio     QEMUIOVector hd_qiov;
14293fc48d09SFrediano Ziglio     uint8_t *cluster_data = NULL;
1430585f8587Sbellard 
14313fc48d09SFrediano Ziglio     qemu_iovec_init(&hd_qiov, qiov->niov);
14323fc48d09SFrediano Ziglio 
14333fc48d09SFrediano Ziglio     qemu_co_mutex_lock(&s->lock);
14343fc48d09SFrediano Ziglio 
1435ecfe1863SKevin Wolf     while (bytes != 0) {
1436585f8587Sbellard 
1437faf575c1SFrediano Ziglio         /* prepare next request */
1438ecfe1863SKevin Wolf         cur_bytes = MIN(bytes, INT_MAX);
1439f6fa64f6SDaniel P. Berrange         if (s->cipher) {
1440ecfe1863SKevin Wolf             cur_bytes = MIN(cur_bytes,
1441ecfe1863SKevin Wolf                             QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
1442bd28f835SKevin Wolf         }
1443bd28f835SKevin Wolf 
1444ecfe1863SKevin Wolf         ret = qcow2_get_cluster_offset(bs, offset, &cur_bytes, &cluster_offset);
14451c46efaaSKevin Wolf         if (ret < 0) {
14463fc48d09SFrediano Ziglio             goto fail;
14471c46efaaSKevin Wolf         }
14481c46efaaSKevin Wolf 
1449ecfe1863SKevin Wolf         offset_in_cluster = offset_into_cluster(s, offset);
1450585f8587Sbellard 
14513fc48d09SFrediano Ziglio         qemu_iovec_reset(&hd_qiov);
1452ecfe1863SKevin Wolf         qemu_iovec_concat(&hd_qiov, qiov, bytes_done, cur_bytes);
1453bd28f835SKevin Wolf 
145468d000a3SKevin Wolf         switch (ret) {
145568d000a3SKevin Wolf         case QCOW2_CLUSTER_UNALLOCATED:
1456bd28f835SKevin Wolf 
1457760e0063SKevin Wolf             if (bs->backing) {
1458585f8587Sbellard                 /* read from the base image */
1459760e0063SKevin Wolf                 n1 = qcow2_backing_read1(bs->backing->bs, &hd_qiov,
1460ecfe1863SKevin Wolf                                          offset, cur_bytes);
1461a9465922Sbellard                 if (n1 > 0) {
146244deba5aSKevin Wolf                     QEMUIOVector local_qiov;
146344deba5aSKevin Wolf 
146444deba5aSKevin Wolf                     qemu_iovec_init(&local_qiov, hd_qiov.niov);
1465ecfe1863SKevin Wolf                     qemu_iovec_concat(&local_qiov, &hd_qiov, 0, n1);
146644deba5aSKevin Wolf 
146766f82ceeSKevin Wolf                     BLKDBG_EVENT(bs->file, BLKDBG_READ_BACKING_AIO);
146868d100e9SKevin Wolf                     qemu_co_mutex_unlock(&s->lock);
1469a03ef88fSKevin Wolf                     ret = bdrv_co_preadv(bs->backing, offset, n1,
1470ecfe1863SKevin Wolf                                          &local_qiov, 0);
147168d100e9SKevin Wolf                     qemu_co_mutex_lock(&s->lock);
147244deba5aSKevin Wolf 
147344deba5aSKevin Wolf                     qemu_iovec_destroy(&local_qiov);
147444deba5aSKevin Wolf 
147568d100e9SKevin Wolf                     if (ret < 0) {
14763fc48d09SFrediano Ziglio                         goto fail;
14773ab4c7e9SKevin Wolf                     }
14781490791fSaliguori                 }
1479a9465922Sbellard             } else {
1480585f8587Sbellard                 /* Note: in this case, no need to wait */
1481ecfe1863SKevin Wolf                 qemu_iovec_memset(&hd_qiov, 0, 0, cur_bytes);
14821490791fSaliguori             }
148368d000a3SKevin Wolf             break;
148468d000a3SKevin Wolf 
14856377af48SKevin Wolf         case QCOW2_CLUSTER_ZERO:
1486ecfe1863SKevin Wolf             qemu_iovec_memset(&hd_qiov, 0, 0, cur_bytes);
14876377af48SKevin Wolf             break;
14886377af48SKevin Wolf 
148968d000a3SKevin Wolf         case QCOW2_CLUSTER_COMPRESSED:
1490585f8587Sbellard             /* add AIO support for compressed blocks ? */
1491c2bdd990SFrediano Ziglio             ret = qcow2_decompress_cluster(bs, cluster_offset);
14928af36488SKevin Wolf             if (ret < 0) {
14933fc48d09SFrediano Ziglio                 goto fail;
14948af36488SKevin Wolf             }
1495bd28f835SKevin Wolf 
149603396148SMichael Tokarev             qemu_iovec_from_buf(&hd_qiov, 0,
1497ecfe1863SKevin Wolf                                 s->cluster_cache + offset_in_cluster,
1498ecfe1863SKevin Wolf                                 cur_bytes);
149968d000a3SKevin Wolf             break;
150068d000a3SKevin Wolf 
150168d000a3SKevin Wolf         case QCOW2_CLUSTER_NORMAL:
1502c2bdd990SFrediano Ziglio             if ((cluster_offset & 511) != 0) {
15033fc48d09SFrediano Ziglio                 ret = -EIO;
15043fc48d09SFrediano Ziglio                 goto fail;
1505585f8587Sbellard             }
1506c87c0672Saliguori 
15078336aafaSDaniel P. Berrange             if (bs->encrypted) {
1508f6fa64f6SDaniel P. Berrange                 assert(s->cipher);
15098336aafaSDaniel P. Berrange 
1510bd28f835SKevin Wolf                 /*
1511bd28f835SKevin Wolf                  * For encrypted images, read everything into a temporary
1512bd28f835SKevin Wolf                  * contiguous buffer on which the AES functions can work.
1513bd28f835SKevin Wolf                  */
15143fc48d09SFrediano Ziglio                 if (!cluster_data) {
15153fc48d09SFrediano Ziglio                     cluster_data =
15169a4f4c31SKevin Wolf                         qemu_try_blockalign(bs->file->bs,
15179a4f4c31SKevin Wolf                                             QCOW_MAX_CRYPT_CLUSTERS
1518de82815dSKevin Wolf                                             * s->cluster_size);
1519de82815dSKevin Wolf                     if (cluster_data == NULL) {
1520de82815dSKevin Wolf                         ret = -ENOMEM;
1521de82815dSKevin Wolf                         goto fail;
1522de82815dSKevin Wolf                     }
1523bd28f835SKevin Wolf                 }
1524bd28f835SKevin Wolf 
1525ecfe1863SKevin Wolf                 assert(cur_bytes <= QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
15263fc48d09SFrediano Ziglio                 qemu_iovec_reset(&hd_qiov);
1527ecfe1863SKevin Wolf                 qemu_iovec_add(&hd_qiov, cluster_data, cur_bytes);
1528bd28f835SKevin Wolf             }
1529bd28f835SKevin Wolf 
153066f82ceeSKevin Wolf             BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);
153168d100e9SKevin Wolf             qemu_co_mutex_unlock(&s->lock);
1532a03ef88fSKevin Wolf             ret = bdrv_co_preadv(bs->file,
1533ecfe1863SKevin Wolf                                  cluster_offset + offset_in_cluster,
1534ecfe1863SKevin Wolf                                  cur_bytes, &hd_qiov, 0);
153568d100e9SKevin Wolf             qemu_co_mutex_lock(&s->lock);
153668d100e9SKevin Wolf             if (ret < 0) {
15373fc48d09SFrediano Ziglio                 goto fail;
1538585f8587Sbellard             }
15398336aafaSDaniel P. Berrange             if (bs->encrypted) {
1540f6fa64f6SDaniel P. Berrange                 assert(s->cipher);
1541ecfe1863SKevin Wolf                 assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);
1542ecfe1863SKevin Wolf                 assert((cur_bytes & (BDRV_SECTOR_SIZE - 1)) == 0);
1543f6fa64f6SDaniel P. Berrange                 Error *err = NULL;
1544ecfe1863SKevin Wolf                 if (qcow2_encrypt_sectors(s, offset >> BDRV_SECTOR_BITS,
1545ecfe1863SKevin Wolf                                           cluster_data, cluster_data,
1546ecfe1863SKevin Wolf                                           cur_bytes >> BDRV_SECTOR_BITS,
1547ecfe1863SKevin Wolf                                           false, &err) < 0) {
1548f6fa64f6SDaniel P. Berrange                     error_free(err);
1549f6fa64f6SDaniel P. Berrange                     ret = -EIO;
1550f6fa64f6SDaniel P. Berrange                     goto fail;
1551f6fa64f6SDaniel P. Berrange                 }
1552ecfe1863SKevin Wolf                 qemu_iovec_from_buf(qiov, bytes_done, cluster_data, cur_bytes);
1553171e3d6bSKevin Wolf             }
155468d000a3SKevin Wolf             break;
155568d000a3SKevin Wolf 
155668d000a3SKevin Wolf         default:
155768d000a3SKevin Wolf             g_assert_not_reached();
155868d000a3SKevin Wolf             ret = -EIO;
155968d000a3SKevin Wolf             goto fail;
1560faf575c1SFrediano Ziglio         }
1561faf575c1SFrediano Ziglio 
1562ecfe1863SKevin Wolf         bytes -= cur_bytes;
1563ecfe1863SKevin Wolf         offset += cur_bytes;
1564ecfe1863SKevin Wolf         bytes_done += cur_bytes;
15655ebaa27eSFrediano Ziglio     }
15663fc48d09SFrediano Ziglio     ret = 0;
1567f141eafeSaliguori 
15683fc48d09SFrediano Ziglio fail:
156968d100e9SKevin Wolf     qemu_co_mutex_unlock(&s->lock);
157068d100e9SKevin Wolf 
15713fc48d09SFrediano Ziglio     qemu_iovec_destroy(&hd_qiov);
1572dea43a65SFrediano Ziglio     qemu_vfree(cluster_data);
157368d100e9SKevin Wolf 
157468d100e9SKevin Wolf     return ret;
1575585f8587Sbellard }
1576585f8587Sbellard 
1577d46a0bb2SKevin Wolf static coroutine_fn int qcow2_co_pwritev(BlockDriverState *bs, uint64_t offset,
1578d46a0bb2SKevin Wolf                                          uint64_t bytes, QEMUIOVector *qiov,
1579d46a0bb2SKevin Wolf                                          int flags)
1580585f8587Sbellard {
1581ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
1582d46a0bb2SKevin Wolf     int offset_in_cluster;
158368d100e9SKevin Wolf     int ret;
1584d46a0bb2SKevin Wolf     unsigned int cur_bytes; /* number of sectors in current iteration */
1585c2bdd990SFrediano Ziglio     uint64_t cluster_offset;
15863fc48d09SFrediano Ziglio     QEMUIOVector hd_qiov;
15873fc48d09SFrediano Ziglio     uint64_t bytes_done = 0;
15883fc48d09SFrediano Ziglio     uint8_t *cluster_data = NULL;
15898d2497c3SKevin Wolf     QCowL2Meta *l2meta = NULL;
1590c2271403SFrediano Ziglio 
1591d46a0bb2SKevin Wolf     trace_qcow2_writev_start_req(qemu_coroutine_self(), offset, bytes);
15923cce16f4SKevin Wolf 
15933fc48d09SFrediano Ziglio     qemu_iovec_init(&hd_qiov, qiov->niov);
1594585f8587Sbellard 
15953fc48d09SFrediano Ziglio     s->cluster_cache_offset = -1; /* disable compressed cache */
15963fc48d09SFrediano Ziglio 
15973fc48d09SFrediano Ziglio     qemu_co_mutex_lock(&s->lock);
15983fc48d09SFrediano Ziglio 
1599d46a0bb2SKevin Wolf     while (bytes != 0) {
16003fc48d09SFrediano Ziglio 
1601f50f88b9SKevin Wolf         l2meta = NULL;
1602cf5c1a23SKevin Wolf 
16033cce16f4SKevin Wolf         trace_qcow2_writev_start_part(qemu_coroutine_self());
1604d46a0bb2SKevin Wolf         offset_in_cluster = offset_into_cluster(s, offset);
1605d46a0bb2SKevin Wolf         cur_bytes = MIN(bytes, INT_MAX);
1606d46a0bb2SKevin Wolf         if (bs->encrypted) {
1607d46a0bb2SKevin Wolf             cur_bytes = MIN(cur_bytes,
1608d46a0bb2SKevin Wolf                             QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size
1609d46a0bb2SKevin Wolf                             - offset_in_cluster);
16105ebaa27eSFrediano Ziglio         }
1611095a9c58Saliguori 
1612d46a0bb2SKevin Wolf         ret = qcow2_alloc_cluster_offset(bs, offset, &cur_bytes,
1613d46a0bb2SKevin Wolf                                          &cluster_offset, &l2meta);
1614148da7eaSKevin Wolf         if (ret < 0) {
16153fc48d09SFrediano Ziglio             goto fail;
1616148da7eaSKevin Wolf         }
1617148da7eaSKevin Wolf 
1618c2bdd990SFrediano Ziglio         assert((cluster_offset & 511) == 0);
1619148da7eaSKevin Wolf 
16203fc48d09SFrediano Ziglio         qemu_iovec_reset(&hd_qiov);
1621d46a0bb2SKevin Wolf         qemu_iovec_concat(&hd_qiov, qiov, bytes_done, cur_bytes);
16226f5f060bSKevin Wolf 
16238336aafaSDaniel P. Berrange         if (bs->encrypted) {
1624f6fa64f6SDaniel P. Berrange             Error *err = NULL;
1625f6fa64f6SDaniel P. Berrange             assert(s->cipher);
16263fc48d09SFrediano Ziglio             if (!cluster_data) {
16279a4f4c31SKevin Wolf                 cluster_data = qemu_try_blockalign(bs->file->bs,
1628de82815dSKevin Wolf                                                    QCOW_MAX_CRYPT_CLUSTERS
1629de82815dSKevin Wolf                                                    * s->cluster_size);
1630de82815dSKevin Wolf                 if (cluster_data == NULL) {
1631de82815dSKevin Wolf                     ret = -ENOMEM;
1632de82815dSKevin Wolf                     goto fail;
1633de82815dSKevin Wolf                 }
1634585f8587Sbellard             }
16356f5f060bSKevin Wolf 
16363fc48d09SFrediano Ziglio             assert(hd_qiov.size <=
16375ebaa27eSFrediano Ziglio                    QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
1638d5e6b161SMichael Tokarev             qemu_iovec_to_buf(&hd_qiov, 0, cluster_data, hd_qiov.size);
16396f5f060bSKevin Wolf 
1640d46a0bb2SKevin Wolf             if (qcow2_encrypt_sectors(s, offset >> BDRV_SECTOR_BITS,
1641d46a0bb2SKevin Wolf                                       cluster_data, cluster_data,
1642d46a0bb2SKevin Wolf                                       cur_bytes >>BDRV_SECTOR_BITS,
1643f6fa64f6SDaniel P. Berrange                                       true, &err) < 0) {
1644f6fa64f6SDaniel P. Berrange                 error_free(err);
1645f6fa64f6SDaniel P. Berrange                 ret = -EIO;
1646f6fa64f6SDaniel P. Berrange                 goto fail;
1647f6fa64f6SDaniel P. Berrange             }
16486f5f060bSKevin Wolf 
16493fc48d09SFrediano Ziglio             qemu_iovec_reset(&hd_qiov);
1650d46a0bb2SKevin Wolf             qemu_iovec_add(&hd_qiov, cluster_data, cur_bytes);
1651585f8587Sbellard         }
16526f5f060bSKevin Wolf 
1653231bb267SMax Reitz         ret = qcow2_pre_write_overlap_check(bs, 0,
1654d46a0bb2SKevin Wolf                 cluster_offset + offset_in_cluster, cur_bytes);
1655cf93980eSMax Reitz         if (ret < 0) {
1656cf93980eSMax Reitz             goto fail;
1657cf93980eSMax Reitz         }
1658cf93980eSMax Reitz 
165968d100e9SKevin Wolf         qemu_co_mutex_unlock(&s->lock);
166067a7a0ebSKevin Wolf         BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO);
16613cce16f4SKevin Wolf         trace_qcow2_writev_data(qemu_coroutine_self(),
1662d46a0bb2SKevin Wolf                                 cluster_offset + offset_in_cluster);
1663a03ef88fSKevin Wolf         ret = bdrv_co_pwritev(bs->file,
1664d46a0bb2SKevin Wolf                               cluster_offset + offset_in_cluster,
1665d46a0bb2SKevin Wolf                               cur_bytes, &hd_qiov, 0);
166668d100e9SKevin Wolf         qemu_co_mutex_lock(&s->lock);
166768d100e9SKevin Wolf         if (ret < 0) {
16683fc48d09SFrediano Ziglio             goto fail;
1669171e3d6bSKevin Wolf         }
1670f141eafeSaliguori 
167188c6588cSKevin Wolf         while (l2meta != NULL) {
167288c6588cSKevin Wolf             QCowL2Meta *next;
167388c6588cSKevin Wolf 
1674cf5c1a23SKevin Wolf             ret = qcow2_alloc_cluster_link_l2(bs, l2meta);
1675faf575c1SFrediano Ziglio             if (ret < 0) {
16763fc48d09SFrediano Ziglio                 goto fail;
1677faf575c1SFrediano Ziglio             }
1678faf575c1SFrediano Ziglio 
16794e95314eSKevin Wolf             /* Take the request off the list of running requests */
16804e95314eSKevin Wolf             if (l2meta->nb_clusters != 0) {
16814e95314eSKevin Wolf                 QLIST_REMOVE(l2meta, next_in_flight);
16824e95314eSKevin Wolf             }
16834e95314eSKevin Wolf 
16844e95314eSKevin Wolf             qemu_co_queue_restart_all(&l2meta->dependent_requests);
16854e95314eSKevin Wolf 
168688c6588cSKevin Wolf             next = l2meta->next;
1687cf5c1a23SKevin Wolf             g_free(l2meta);
168888c6588cSKevin Wolf             l2meta = next;
1689f50f88b9SKevin Wolf         }
16900fa9131aSKevin Wolf 
1691d46a0bb2SKevin Wolf         bytes -= cur_bytes;
1692d46a0bb2SKevin Wolf         offset += cur_bytes;
1693d46a0bb2SKevin Wolf         bytes_done += cur_bytes;
1694d46a0bb2SKevin Wolf         trace_qcow2_writev_done_part(qemu_coroutine_self(), cur_bytes);
16955ebaa27eSFrediano Ziglio     }
16963fc48d09SFrediano Ziglio     ret = 0;
1697faf575c1SFrediano Ziglio 
16983fc48d09SFrediano Ziglio fail:
16994e95314eSKevin Wolf     qemu_co_mutex_unlock(&s->lock);
17004e95314eSKevin Wolf 
170188c6588cSKevin Wolf     while (l2meta != NULL) {
170288c6588cSKevin Wolf         QCowL2Meta *next;
170388c6588cSKevin Wolf 
17044e95314eSKevin Wolf         if (l2meta->nb_clusters != 0) {
17054e95314eSKevin Wolf             QLIST_REMOVE(l2meta, next_in_flight);
17064e95314eSKevin Wolf         }
17074e95314eSKevin Wolf         qemu_co_queue_restart_all(&l2meta->dependent_requests);
170888c6588cSKevin Wolf 
170988c6588cSKevin Wolf         next = l2meta->next;
1710cf5c1a23SKevin Wolf         g_free(l2meta);
171188c6588cSKevin Wolf         l2meta = next;
1712cf5c1a23SKevin Wolf     }
17130fa9131aSKevin Wolf 
17143fc48d09SFrediano Ziglio     qemu_iovec_destroy(&hd_qiov);
1715dea43a65SFrediano Ziglio     qemu_vfree(cluster_data);
17163cce16f4SKevin Wolf     trace_qcow2_writev_done_req(qemu_coroutine_self(), ret);
171742496d62SKevin Wolf 
171868d100e9SKevin Wolf     return ret;
1719585f8587Sbellard }
1720585f8587Sbellard 
1721ec6d8912SKevin Wolf static int qcow2_inactivate(BlockDriverState *bs)
1722ec6d8912SKevin Wolf {
1723ec6d8912SKevin Wolf     BDRVQcow2State *s = bs->opaque;
1724ec6d8912SKevin Wolf     int ret, result = 0;
1725ec6d8912SKevin Wolf 
1726ec6d8912SKevin Wolf     ret = qcow2_cache_flush(bs, s->l2_table_cache);
1727ec6d8912SKevin Wolf     if (ret) {
1728ec6d8912SKevin Wolf         result = ret;
1729ec6d8912SKevin Wolf         error_report("Failed to flush the L2 table cache: %s",
1730ec6d8912SKevin Wolf                      strerror(-ret));
1731ec6d8912SKevin Wolf     }
1732ec6d8912SKevin Wolf 
1733ec6d8912SKevin Wolf     ret = qcow2_cache_flush(bs, s->refcount_block_cache);
1734ec6d8912SKevin Wolf     if (ret) {
1735ec6d8912SKevin Wolf         result = ret;
1736ec6d8912SKevin Wolf         error_report("Failed to flush the refcount block cache: %s",
1737ec6d8912SKevin Wolf                      strerror(-ret));
1738ec6d8912SKevin Wolf     }
1739ec6d8912SKevin Wolf 
1740ec6d8912SKevin Wolf     if (result == 0) {
1741ec6d8912SKevin Wolf         qcow2_mark_clean(bs);
1742ec6d8912SKevin Wolf     }
1743ec6d8912SKevin Wolf 
1744ec6d8912SKevin Wolf     return result;
1745ec6d8912SKevin Wolf }
1746ec6d8912SKevin Wolf 
17477c80ab3fSJes Sorensen static void qcow2_close(BlockDriverState *bs)
1748585f8587Sbellard {
1749ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
1750de82815dSKevin Wolf     qemu_vfree(s->l1_table);
1751cf93980eSMax Reitz     /* else pre-write overlap checks in cache_destroy may crash */
1752cf93980eSMax Reitz     s->l1_table = NULL;
175329c1a730SKevin Wolf 
1754140fd5a6SKevin Wolf     if (!(s->flags & BDRV_O_INACTIVE)) {
1755ec6d8912SKevin Wolf         qcow2_inactivate(bs);
17563b5e14c7SMax Reitz     }
1757c61d0004SStefan Hajnoczi 
1758279621c0SAlberto Garcia     cache_clean_timer_del(bs);
175929c1a730SKevin Wolf     qcow2_cache_destroy(bs, s->l2_table_cache);
176029c1a730SKevin Wolf     qcow2_cache_destroy(bs, s->refcount_block_cache);
176129c1a730SKevin Wolf 
1762f6fa64f6SDaniel P. Berrange     qcrypto_cipher_free(s->cipher);
1763f6fa64f6SDaniel P. Berrange     s->cipher = NULL;
1764f6fa64f6SDaniel P. Berrange 
17656744cbabSKevin Wolf     g_free(s->unknown_header_fields);
176675bab85cSKevin Wolf     cleanup_unknown_header_ext(bs);
17676744cbabSKevin Wolf 
1768e4603fe1SKevin Wolf     g_free(s->image_backing_file);
1769e4603fe1SKevin Wolf     g_free(s->image_backing_format);
1770e4603fe1SKevin Wolf 
17717267c094SAnthony Liguori     g_free(s->cluster_cache);
1772dea43a65SFrediano Ziglio     qemu_vfree(s->cluster_data);
1773ed6ccf0fSKevin Wolf     qcow2_refcount_close(bs);
177428c1202bSLi Zhi Hui     qcow2_free_snapshots(bs);
1775585f8587Sbellard }
1776585f8587Sbellard 
17775a8a30dbSKevin Wolf static void qcow2_invalidate_cache(BlockDriverState *bs, Error **errp)
177806d9260fSAnthony Liguori {
1779ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
178006d9260fSAnthony Liguori     int flags = s->flags;
1781f6fa64f6SDaniel P. Berrange     QCryptoCipher *cipher = NULL;
1782acdfb480SKevin Wolf     QDict *options;
17835a8a30dbSKevin Wolf     Error *local_err = NULL;
17845a8a30dbSKevin Wolf     int ret;
178506d9260fSAnthony Liguori 
178606d9260fSAnthony Liguori     /*
178706d9260fSAnthony Liguori      * Backing files are read-only which makes all of their metadata immutable,
178806d9260fSAnthony Liguori      * that means we don't have to worry about reopening them here.
178906d9260fSAnthony Liguori      */
179006d9260fSAnthony Liguori 
1791f6fa64f6SDaniel P. Berrange     cipher = s->cipher;
1792f6fa64f6SDaniel P. Berrange     s->cipher = NULL;
179306d9260fSAnthony Liguori 
179406d9260fSAnthony Liguori     qcow2_close(bs);
179506d9260fSAnthony Liguori 
1796ff99129aSKevin Wolf     memset(s, 0, sizeof(BDRVQcow2State));
1797d475e5acSKevin Wolf     options = qdict_clone_shallow(bs->options);
17985a8a30dbSKevin Wolf 
1799140fd5a6SKevin Wolf     flags &= ~BDRV_O_INACTIVE;
18004e4bf5c4SKevin Wolf     ret = qcow2_do_open(bs, options, flags, &local_err);
1801a1904e48SMarkus Armbruster     QDECREF(options);
18025a8a30dbSKevin Wolf     if (local_err) {
1803e43bfd9cSMarkus Armbruster         error_propagate(errp, local_err);
1804e43bfd9cSMarkus Armbruster         error_prepend(errp, "Could not reopen qcow2 layer: ");
1805191fb11bSKevin Wolf         bs->drv = NULL;
18065a8a30dbSKevin Wolf         return;
18075a8a30dbSKevin Wolf     } else if (ret < 0) {
18085a8a30dbSKevin Wolf         error_setg_errno(errp, -ret, "Could not reopen qcow2 layer");
1809191fb11bSKevin Wolf         bs->drv = NULL;
18105a8a30dbSKevin Wolf         return;
18115a8a30dbSKevin Wolf     }
1812acdfb480SKevin Wolf 
1813f6fa64f6SDaniel P. Berrange     s->cipher = cipher;
181406d9260fSAnthony Liguori }
181506d9260fSAnthony Liguori 
1816e24e49e6SKevin Wolf static size_t header_ext_add(char *buf, uint32_t magic, const void *s,
1817e24e49e6SKevin Wolf     size_t len, size_t buflen)
1818756e6736SKevin Wolf {
1819e24e49e6SKevin Wolf     QCowExtension *ext_backing_fmt = (QCowExtension*) buf;
1820e24e49e6SKevin Wolf     size_t ext_len = sizeof(QCowExtension) + ((len + 7) & ~7);
1821756e6736SKevin Wolf 
1822e24e49e6SKevin Wolf     if (buflen < ext_len) {
1823756e6736SKevin Wolf         return -ENOSPC;
1824756e6736SKevin Wolf     }
1825756e6736SKevin Wolf 
1826e24e49e6SKevin Wolf     *ext_backing_fmt = (QCowExtension) {
1827e24e49e6SKevin Wolf         .magic  = cpu_to_be32(magic),
1828e24e49e6SKevin Wolf         .len    = cpu_to_be32(len),
1829e24e49e6SKevin Wolf     };
18300647d47cSStefan Hajnoczi 
18310647d47cSStefan Hajnoczi     if (len) {
1832e24e49e6SKevin Wolf         memcpy(buf + sizeof(QCowExtension), s, len);
18330647d47cSStefan Hajnoczi     }
1834756e6736SKevin Wolf 
1835e24e49e6SKevin Wolf     return ext_len;
1836756e6736SKevin Wolf }
1837756e6736SKevin Wolf 
1838e24e49e6SKevin Wolf /*
1839e24e49e6SKevin Wolf  * Updates the qcow2 header, including the variable length parts of it, i.e.
1840e24e49e6SKevin Wolf  * the backing file name and all extensions. qcow2 was not designed to allow
1841e24e49e6SKevin Wolf  * such changes, so if we run out of space (we can only use the first cluster)
1842e24e49e6SKevin Wolf  * this function may fail.
1843e24e49e6SKevin Wolf  *
1844e24e49e6SKevin Wolf  * Returns 0 on success, -errno in error cases.
1845e24e49e6SKevin Wolf  */
1846e24e49e6SKevin Wolf int qcow2_update_header(BlockDriverState *bs)
1847e24e49e6SKevin Wolf {
1848ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
1849e24e49e6SKevin Wolf     QCowHeader *header;
1850e24e49e6SKevin Wolf     char *buf;
1851e24e49e6SKevin Wolf     size_t buflen = s->cluster_size;
1852e24e49e6SKevin Wolf     int ret;
1853e24e49e6SKevin Wolf     uint64_t total_size;
1854e24e49e6SKevin Wolf     uint32_t refcount_table_clusters;
18556744cbabSKevin Wolf     size_t header_length;
185675bab85cSKevin Wolf     Qcow2UnknownHeaderExtension *uext;
1857e24e49e6SKevin Wolf 
1858e24e49e6SKevin Wolf     buf = qemu_blockalign(bs, buflen);
1859e24e49e6SKevin Wolf 
1860e24e49e6SKevin Wolf     /* Header structure */
1861e24e49e6SKevin Wolf     header = (QCowHeader*) buf;
1862e24e49e6SKevin Wolf 
1863e24e49e6SKevin Wolf     if (buflen < sizeof(*header)) {
1864e24e49e6SKevin Wolf         ret = -ENOSPC;
1865e24e49e6SKevin Wolf         goto fail;
1866756e6736SKevin Wolf     }
1867756e6736SKevin Wolf 
18686744cbabSKevin Wolf     header_length = sizeof(*header) + s->unknown_header_fields_size;
1869e24e49e6SKevin Wolf     total_size = bs->total_sectors * BDRV_SECTOR_SIZE;
1870e24e49e6SKevin Wolf     refcount_table_clusters = s->refcount_table_size >> (s->cluster_bits - 3);
1871e24e49e6SKevin Wolf 
1872e24e49e6SKevin Wolf     *header = (QCowHeader) {
18736744cbabSKevin Wolf         /* Version 2 fields */
1874e24e49e6SKevin Wolf         .magic                  = cpu_to_be32(QCOW_MAGIC),
18756744cbabSKevin Wolf         .version                = cpu_to_be32(s->qcow_version),
1876e24e49e6SKevin Wolf         .backing_file_offset    = 0,
1877e24e49e6SKevin Wolf         .backing_file_size      = 0,
1878e24e49e6SKevin Wolf         .cluster_bits           = cpu_to_be32(s->cluster_bits),
1879e24e49e6SKevin Wolf         .size                   = cpu_to_be64(total_size),
1880e24e49e6SKevin Wolf         .crypt_method           = cpu_to_be32(s->crypt_method_header),
1881e24e49e6SKevin Wolf         .l1_size                = cpu_to_be32(s->l1_size),
1882e24e49e6SKevin Wolf         .l1_table_offset        = cpu_to_be64(s->l1_table_offset),
1883e24e49e6SKevin Wolf         .refcount_table_offset  = cpu_to_be64(s->refcount_table_offset),
1884e24e49e6SKevin Wolf         .refcount_table_clusters = cpu_to_be32(refcount_table_clusters),
1885e24e49e6SKevin Wolf         .nb_snapshots           = cpu_to_be32(s->nb_snapshots),
1886e24e49e6SKevin Wolf         .snapshots_offset       = cpu_to_be64(s->snapshots_offset),
18876744cbabSKevin Wolf 
18886744cbabSKevin Wolf         /* Version 3 fields */
18896744cbabSKevin Wolf         .incompatible_features  = cpu_to_be64(s->incompatible_features),
18906744cbabSKevin Wolf         .compatible_features    = cpu_to_be64(s->compatible_features),
18916744cbabSKevin Wolf         .autoclear_features     = cpu_to_be64(s->autoclear_features),
1892b6481f37SMax Reitz         .refcount_order         = cpu_to_be32(s->refcount_order),
18936744cbabSKevin Wolf         .header_length          = cpu_to_be32(header_length),
1894e24e49e6SKevin Wolf     };
1895e24e49e6SKevin Wolf 
18966744cbabSKevin Wolf     /* For older versions, write a shorter header */
18976744cbabSKevin Wolf     switch (s->qcow_version) {
18986744cbabSKevin Wolf     case 2:
18996744cbabSKevin Wolf         ret = offsetof(QCowHeader, incompatible_features);
19006744cbabSKevin Wolf         break;
19016744cbabSKevin Wolf     case 3:
19026744cbabSKevin Wolf         ret = sizeof(*header);
19036744cbabSKevin Wolf         break;
19046744cbabSKevin Wolf     default:
1905b6c14762SJim Meyering         ret = -EINVAL;
1906b6c14762SJim Meyering         goto fail;
19076744cbabSKevin Wolf     }
19086744cbabSKevin Wolf 
19096744cbabSKevin Wolf     buf += ret;
19106744cbabSKevin Wolf     buflen -= ret;
19116744cbabSKevin Wolf     memset(buf, 0, buflen);
19126744cbabSKevin Wolf 
19136744cbabSKevin Wolf     /* Preserve any unknown field in the header */
19146744cbabSKevin Wolf     if (s->unknown_header_fields_size) {
19156744cbabSKevin Wolf         if (buflen < s->unknown_header_fields_size) {
19166744cbabSKevin Wolf             ret = -ENOSPC;
19176744cbabSKevin Wolf             goto fail;
19186744cbabSKevin Wolf         }
19196744cbabSKevin Wolf 
19206744cbabSKevin Wolf         memcpy(buf, s->unknown_header_fields, s->unknown_header_fields_size);
19216744cbabSKevin Wolf         buf += s->unknown_header_fields_size;
19226744cbabSKevin Wolf         buflen -= s->unknown_header_fields_size;
19236744cbabSKevin Wolf     }
1924e24e49e6SKevin Wolf 
1925e24e49e6SKevin Wolf     /* Backing file format header extension */
1926e4603fe1SKevin Wolf     if (s->image_backing_format) {
1927e24e49e6SKevin Wolf         ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BACKING_FORMAT,
1928e4603fe1SKevin Wolf                              s->image_backing_format,
1929e4603fe1SKevin Wolf                              strlen(s->image_backing_format),
1930e24e49e6SKevin Wolf                              buflen);
1931756e6736SKevin Wolf         if (ret < 0) {
1932756e6736SKevin Wolf             goto fail;
1933756e6736SKevin Wolf         }
1934756e6736SKevin Wolf 
1935e24e49e6SKevin Wolf         buf += ret;
1936e24e49e6SKevin Wolf         buflen -= ret;
1937e24e49e6SKevin Wolf     }
1938756e6736SKevin Wolf 
1939cfcc4c62SKevin Wolf     /* Feature table */
19401a4828c7SKevin Wolf     if (s->qcow_version >= 3) {
1941cfcc4c62SKevin Wolf         Qcow2Feature features[] = {
1942c61d0004SStefan Hajnoczi             {
1943c61d0004SStefan Hajnoczi                 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
1944c61d0004SStefan Hajnoczi                 .bit  = QCOW2_INCOMPAT_DIRTY_BITNR,
1945c61d0004SStefan Hajnoczi                 .name = "dirty bit",
1946c61d0004SStefan Hajnoczi             },
1947bfe8043eSStefan Hajnoczi             {
194869c98726SMax Reitz                 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
194969c98726SMax Reitz                 .bit  = QCOW2_INCOMPAT_CORRUPT_BITNR,
195069c98726SMax Reitz                 .name = "corrupt bit",
195169c98726SMax Reitz             },
195269c98726SMax Reitz             {
1953bfe8043eSStefan Hajnoczi                 .type = QCOW2_FEAT_TYPE_COMPATIBLE,
1954bfe8043eSStefan Hajnoczi                 .bit  = QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR,
1955bfe8043eSStefan Hajnoczi                 .name = "lazy refcounts",
1956bfe8043eSStefan Hajnoczi             },
1957cfcc4c62SKevin Wolf         };
1958cfcc4c62SKevin Wolf 
1959cfcc4c62SKevin Wolf         ret = header_ext_add(buf, QCOW2_EXT_MAGIC_FEATURE_TABLE,
1960cfcc4c62SKevin Wolf                              features, sizeof(features), buflen);
1961cfcc4c62SKevin Wolf         if (ret < 0) {
1962cfcc4c62SKevin Wolf             goto fail;
1963cfcc4c62SKevin Wolf         }
1964cfcc4c62SKevin Wolf         buf += ret;
1965cfcc4c62SKevin Wolf         buflen -= ret;
19661a4828c7SKevin Wolf     }
1967cfcc4c62SKevin Wolf 
196875bab85cSKevin Wolf     /* Keep unknown header extensions */
196975bab85cSKevin Wolf     QLIST_FOREACH(uext, &s->unknown_header_ext, next) {
197075bab85cSKevin Wolf         ret = header_ext_add(buf, uext->magic, uext->data, uext->len, buflen);
197175bab85cSKevin Wolf         if (ret < 0) {
197275bab85cSKevin Wolf             goto fail;
197375bab85cSKevin Wolf         }
197475bab85cSKevin Wolf 
197575bab85cSKevin Wolf         buf += ret;
197675bab85cSKevin Wolf         buflen -= ret;
197775bab85cSKevin Wolf     }
197875bab85cSKevin Wolf 
1979e24e49e6SKevin Wolf     /* End of header extensions */
1980e24e49e6SKevin Wolf     ret = header_ext_add(buf, QCOW2_EXT_MAGIC_END, NULL, 0, buflen);
1981756e6736SKevin Wolf     if (ret < 0) {
1982756e6736SKevin Wolf         goto fail;
1983756e6736SKevin Wolf     }
1984756e6736SKevin Wolf 
1985e24e49e6SKevin Wolf     buf += ret;
1986e24e49e6SKevin Wolf     buflen -= ret;
1987e24e49e6SKevin Wolf 
1988e24e49e6SKevin Wolf     /* Backing file name */
1989e4603fe1SKevin Wolf     if (s->image_backing_file) {
1990e4603fe1SKevin Wolf         size_t backing_file_len = strlen(s->image_backing_file);
1991e24e49e6SKevin Wolf 
1992e24e49e6SKevin Wolf         if (buflen < backing_file_len) {
1993e24e49e6SKevin Wolf             ret = -ENOSPC;
1994e24e49e6SKevin Wolf             goto fail;
1995e24e49e6SKevin Wolf         }
1996e24e49e6SKevin Wolf 
199700ea1881SJim Meyering         /* Using strncpy is ok here, since buf is not NUL-terminated. */
1998e4603fe1SKevin Wolf         strncpy(buf, s->image_backing_file, buflen);
1999e24e49e6SKevin Wolf 
2000e24e49e6SKevin Wolf         header->backing_file_offset = cpu_to_be64(buf - ((char*) header));
2001e24e49e6SKevin Wolf         header->backing_file_size   = cpu_to_be32(backing_file_len);
2002e24e49e6SKevin Wolf     }
2003e24e49e6SKevin Wolf 
2004e24e49e6SKevin Wolf     /* Write the new header */
2005d9ca2ea2SKevin Wolf     ret = bdrv_pwrite(bs->file, 0, header, s->cluster_size);
2006756e6736SKevin Wolf     if (ret < 0) {
2007756e6736SKevin Wolf         goto fail;
2008756e6736SKevin Wolf     }
2009756e6736SKevin Wolf 
2010756e6736SKevin Wolf     ret = 0;
2011756e6736SKevin Wolf fail:
2012e24e49e6SKevin Wolf     qemu_vfree(header);
2013756e6736SKevin Wolf     return ret;
2014756e6736SKevin Wolf }
2015756e6736SKevin Wolf 
2016756e6736SKevin Wolf static int qcow2_change_backing_file(BlockDriverState *bs,
2017756e6736SKevin Wolf     const char *backing_file, const char *backing_fmt)
2018756e6736SKevin Wolf {
2019ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
2020e4603fe1SKevin Wolf 
20214e876bcfSMax Reitz     if (backing_file && strlen(backing_file) > 1023) {
20224e876bcfSMax Reitz         return -EINVAL;
20234e876bcfSMax Reitz     }
20244e876bcfSMax Reitz 
2025e24e49e6SKevin Wolf     pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
2026e24e49e6SKevin Wolf     pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
2027e24e49e6SKevin Wolf 
2028e4603fe1SKevin Wolf     g_free(s->image_backing_file);
2029e4603fe1SKevin Wolf     g_free(s->image_backing_format);
2030e4603fe1SKevin Wolf 
2031e4603fe1SKevin Wolf     s->image_backing_file = backing_file ? g_strdup(bs->backing_file) : NULL;
2032e4603fe1SKevin Wolf     s->image_backing_format = backing_fmt ? g_strdup(bs->backing_format) : NULL;
2033e4603fe1SKevin Wolf 
2034e24e49e6SKevin Wolf     return qcow2_update_header(bs);
2035756e6736SKevin Wolf }
2036756e6736SKevin Wolf 
2037a35e1c17SKevin Wolf static int preallocate(BlockDriverState *bs)
2038a35e1c17SKevin Wolf {
2039d46a0bb2SKevin Wolf     uint64_t bytes;
2040a35e1c17SKevin Wolf     uint64_t offset;
2041060bee89SKevin Wolf     uint64_t host_offset = 0;
2042d46a0bb2SKevin Wolf     unsigned int cur_bytes;
2043148da7eaSKevin Wolf     int ret;
2044f50f88b9SKevin Wolf     QCowL2Meta *meta;
2045a35e1c17SKevin Wolf 
2046d46a0bb2SKevin Wolf     bytes = bdrv_getlength(bs);
2047a35e1c17SKevin Wolf     offset = 0;
2048a35e1c17SKevin Wolf 
2049d46a0bb2SKevin Wolf     while (bytes) {
2050d46a0bb2SKevin Wolf         cur_bytes = MIN(bytes, INT_MAX);
2051d46a0bb2SKevin Wolf         ret = qcow2_alloc_cluster_offset(bs, offset, &cur_bytes,
2052060bee89SKevin Wolf                                          &host_offset, &meta);
2053148da7eaSKevin Wolf         if (ret < 0) {
205419dbcbf7SKevin Wolf             return ret;
2055a35e1c17SKevin Wolf         }
2056a35e1c17SKevin Wolf 
2057c792707fSStefan Hajnoczi         while (meta) {
2058c792707fSStefan Hajnoczi             QCowL2Meta *next = meta->next;
2059c792707fSStefan Hajnoczi 
2060f50f88b9SKevin Wolf             ret = qcow2_alloc_cluster_link_l2(bs, meta);
206119dbcbf7SKevin Wolf             if (ret < 0) {
20627c2bbf4aSHu Tao                 qcow2_free_any_clusters(bs, meta->alloc_offset,
20637c2bbf4aSHu Tao                                         meta->nb_clusters, QCOW2_DISCARD_NEVER);
206419dbcbf7SKevin Wolf                 return ret;
2065a35e1c17SKevin Wolf             }
2066a35e1c17SKevin Wolf 
20677c2bbf4aSHu Tao             /* There are no dependent requests, but we need to remove our
20687c2bbf4aSHu Tao              * request from the list of in-flight requests */
20694e95314eSKevin Wolf             QLIST_REMOVE(meta, next_in_flight);
2070c792707fSStefan Hajnoczi 
2071c792707fSStefan Hajnoczi             g_free(meta);
2072c792707fSStefan Hajnoczi             meta = next;
2073f50f88b9SKevin Wolf         }
2074f214978aSKevin Wolf 
2075a35e1c17SKevin Wolf         /* TODO Preallocate data if requested */
2076a35e1c17SKevin Wolf 
2077d46a0bb2SKevin Wolf         bytes -= cur_bytes;
2078d46a0bb2SKevin Wolf         offset += cur_bytes;
2079a35e1c17SKevin Wolf     }
2080a35e1c17SKevin Wolf 
2081a35e1c17SKevin Wolf     /*
2082a35e1c17SKevin Wolf      * It is expected that the image file is large enough to actually contain
2083a35e1c17SKevin Wolf      * all of the allocated clusters (otherwise we get failing reads after
2084a35e1c17SKevin Wolf      * EOF). Extend the image to the last allocated sector.
2085a35e1c17SKevin Wolf      */
2086060bee89SKevin Wolf     if (host_offset != 0) {
2087d46a0bb2SKevin Wolf         uint8_t data = 0;
2088d9ca2ea2SKevin Wolf         ret = bdrv_pwrite(bs->file, (host_offset + cur_bytes) - 1,
2089d46a0bb2SKevin Wolf                           &data, 1);
209019dbcbf7SKevin Wolf         if (ret < 0) {
209119dbcbf7SKevin Wolf             return ret;
209219dbcbf7SKevin Wolf         }
2093a35e1c17SKevin Wolf     }
2094a35e1c17SKevin Wolf 
2095a35e1c17SKevin Wolf     return 0;
2096a35e1c17SKevin Wolf }
2097a35e1c17SKevin Wolf 
20987c80ab3fSJes Sorensen static int qcow2_create2(const char *filename, int64_t total_size,
2099a9420734SKevin Wolf                          const char *backing_file, const char *backing_format,
2100ffeaac9bSHu Tao                          int flags, size_t cluster_size, PreallocMode prealloc,
2101bd4b167fSMax Reitz                          QemuOpts *opts, int version, int refcount_order,
21023ef6c40aSMax Reitz                          Error **errp)
2103a9420734SKevin Wolf {
2104a9420734SKevin Wolf     int cluster_bits;
2105e6641719SMax Reitz     QDict *options;
2106e6641719SMax Reitz 
2107e6641719SMax Reitz     /* Calculate cluster_bits */
2108786a4ea8SStefan Hajnoczi     cluster_bits = ctz32(cluster_size);
2109a9420734SKevin Wolf     if (cluster_bits < MIN_CLUSTER_BITS || cluster_bits > MAX_CLUSTER_BITS ||
2110a9420734SKevin Wolf         (1 << cluster_bits) != cluster_size)
2111a9420734SKevin Wolf     {
21123ef6c40aSMax Reitz         error_setg(errp, "Cluster size must be a power of two between %d and "
21133ef6c40aSMax Reitz                    "%dk", 1 << MIN_CLUSTER_BITS, 1 << (MAX_CLUSTER_BITS - 10));
2114a9420734SKevin Wolf         return -EINVAL;
2115a9420734SKevin Wolf     }
2116a9420734SKevin Wolf 
2117a9420734SKevin Wolf     /*
2118a9420734SKevin Wolf      * Open the image file and write a minimal qcow2 header.
2119a9420734SKevin Wolf      *
2120a9420734SKevin Wolf      * We keep things simple and start with a zero-sized image. We also
2121a9420734SKevin Wolf      * do without refcount blocks or a L1 table for now. We'll fix the
2122a9420734SKevin Wolf      * inconsistency later.
2123a9420734SKevin Wolf      *
2124a9420734SKevin Wolf      * We do need a refcount table because growing the refcount table means
2125a9420734SKevin Wolf      * allocating two new refcount blocks - the seconds of which would be at
2126a9420734SKevin Wolf      * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
2127a9420734SKevin Wolf      * size for any qcow2 image.
2128a9420734SKevin Wolf      */
212923588797SKevin Wolf     BlockBackend *blk;
2130f8413b3cSKevin Wolf     QCowHeader *header;
2131b106ad91SKevin Wolf     uint64_t* refcount_table;
21323ef6c40aSMax Reitz     Error *local_err = NULL;
2133a9420734SKevin Wolf     int ret;
2134a9420734SKevin Wolf 
21350e4271b7SHu Tao     if (prealloc == PREALLOC_MODE_FULL || prealloc == PREALLOC_MODE_FALLOC) {
2136bd4b167fSMax Reitz         /* Note: The following calculation does not need to be exact; if it is a
2137bd4b167fSMax Reitz          * bit off, either some bytes will be "leaked" (which is fine) or we
2138bd4b167fSMax Reitz          * will need to increase the file size by some bytes (which is fine,
2139bd4b167fSMax Reitz          * too, as long as the bulk is allocated here). Therefore, using
2140bd4b167fSMax Reitz          * floating point arithmetic is fine. */
21410e4271b7SHu Tao         int64_t meta_size = 0;
21420e4271b7SHu Tao         uint64_t nreftablee, nrefblocke, nl1e, nl2e;
21430e4271b7SHu Tao         int64_t aligned_total_size = align_offset(total_size, cluster_size);
2144bd4b167fSMax Reitz         int refblock_bits, refblock_size;
2145bd4b167fSMax Reitz         /* refcount entry size in bytes */
2146bd4b167fSMax Reitz         double rces = (1 << refcount_order) / 8.;
2147bd4b167fSMax Reitz 
2148bd4b167fSMax Reitz         /* see qcow2_open() */
2149bd4b167fSMax Reitz         refblock_bits = cluster_bits - (refcount_order - 3);
2150bd4b167fSMax Reitz         refblock_size = 1 << refblock_bits;
21510e4271b7SHu Tao 
21520e4271b7SHu Tao         /* header: 1 cluster */
21530e4271b7SHu Tao         meta_size += cluster_size;
21540e4271b7SHu Tao 
21550e4271b7SHu Tao         /* total size of L2 tables */
21560e4271b7SHu Tao         nl2e = aligned_total_size / cluster_size;
21570e4271b7SHu Tao         nl2e = align_offset(nl2e, cluster_size / sizeof(uint64_t));
21580e4271b7SHu Tao         meta_size += nl2e * sizeof(uint64_t);
21590e4271b7SHu Tao 
21600e4271b7SHu Tao         /* total size of L1 tables */
21610e4271b7SHu Tao         nl1e = nl2e * sizeof(uint64_t) / cluster_size;
21620e4271b7SHu Tao         nl1e = align_offset(nl1e, cluster_size / sizeof(uint64_t));
21630e4271b7SHu Tao         meta_size += nl1e * sizeof(uint64_t);
21640e4271b7SHu Tao 
21650e4271b7SHu Tao         /* total size of refcount blocks
21660e4271b7SHu Tao          *
21670e4271b7SHu Tao          * note: every host cluster is reference-counted, including metadata
21680e4271b7SHu Tao          * (even refcount blocks are recursively included).
21690e4271b7SHu Tao          * Let:
21700e4271b7SHu Tao          *   a = total_size (this is the guest disk size)
21710e4271b7SHu Tao          *   m = meta size not including refcount blocks and refcount tables
21720e4271b7SHu Tao          *   c = cluster size
21730e4271b7SHu Tao          *   y1 = number of refcount blocks entries
21740e4271b7SHu Tao          *   y2 = meta size including everything
2175bd4b167fSMax Reitz          *   rces = refcount entry size in bytes
21760e4271b7SHu Tao          * then,
21770e4271b7SHu Tao          *   y1 = (y2 + a)/c
2178bd4b167fSMax Reitz          *   y2 = y1 * rces + y1 * rces * sizeof(u64) / c + m
21790e4271b7SHu Tao          * we can get y1:
2180bd4b167fSMax Reitz          *   y1 = (a + m) / (c - rces - rces * sizeof(u64) / c)
21810e4271b7SHu Tao          */
2182bd4b167fSMax Reitz         nrefblocke = (aligned_total_size + meta_size + cluster_size)
2183bd4b167fSMax Reitz                    / (cluster_size - rces - rces * sizeof(uint64_t)
2184bd4b167fSMax Reitz                                                  / cluster_size);
2185bd4b167fSMax Reitz         meta_size += DIV_ROUND_UP(nrefblocke, refblock_size) * cluster_size;
21860e4271b7SHu Tao 
21870e4271b7SHu Tao         /* total size of refcount tables */
2188bd4b167fSMax Reitz         nreftablee = nrefblocke / refblock_size;
21890e4271b7SHu Tao         nreftablee = align_offset(nreftablee, cluster_size / sizeof(uint64_t));
21900e4271b7SHu Tao         meta_size += nreftablee * sizeof(uint64_t);
21910e4271b7SHu Tao 
21920e4271b7SHu Tao         qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
219339101f25SMarkus Armbruster                             aligned_total_size + meta_size, &error_abort);
2194f43e47dbSMarkus Armbruster         qemu_opt_set(opts, BLOCK_OPT_PREALLOC, PreallocMode_lookup[prealloc],
2195f43e47dbSMarkus Armbruster                      &error_abort);
21960e4271b7SHu Tao     }
21970e4271b7SHu Tao 
2198c282e1fdSChunyan Liu     ret = bdrv_create_file(filename, opts, &local_err);
2199a9420734SKevin Wolf     if (ret < 0) {
22003ef6c40aSMax Reitz         error_propagate(errp, local_err);
2201a9420734SKevin Wolf         return ret;
2202a9420734SKevin Wolf     }
2203a9420734SKevin Wolf 
2204efaa7c4eSMax Reitz     blk = blk_new_open(filename, NULL, NULL,
220555880601SKevin Wolf                        BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_PROTOCOL,
220655880601SKevin Wolf                        &local_err);
220723588797SKevin Wolf     if (blk == NULL) {
22083ef6c40aSMax Reitz         error_propagate(errp, local_err);
220923588797SKevin Wolf         return -EIO;
2210a9420734SKevin Wolf     }
2211a9420734SKevin Wolf 
221223588797SKevin Wolf     blk_set_allow_write_beyond_eof(blk, true);
221323588797SKevin Wolf 
2214a9420734SKevin Wolf     /* Write the header */
2215f8413b3cSKevin Wolf     QEMU_BUILD_BUG_ON((1 << MIN_CLUSTER_BITS) < sizeof(*header));
2216f8413b3cSKevin Wolf     header = g_malloc0(cluster_size);
2217f8413b3cSKevin Wolf     *header = (QCowHeader) {
2218f8413b3cSKevin Wolf         .magic                      = cpu_to_be32(QCOW_MAGIC),
2219f8413b3cSKevin Wolf         .version                    = cpu_to_be32(version),
2220f8413b3cSKevin Wolf         .cluster_bits               = cpu_to_be32(cluster_bits),
2221f8413b3cSKevin Wolf         .size                       = cpu_to_be64(0),
2222f8413b3cSKevin Wolf         .l1_table_offset            = cpu_to_be64(0),
2223f8413b3cSKevin Wolf         .l1_size                    = cpu_to_be32(0),
2224f8413b3cSKevin Wolf         .refcount_table_offset      = cpu_to_be64(cluster_size),
2225f8413b3cSKevin Wolf         .refcount_table_clusters    = cpu_to_be32(1),
2226bd4b167fSMax Reitz         .refcount_order             = cpu_to_be32(refcount_order),
2227f8413b3cSKevin Wolf         .header_length              = cpu_to_be32(sizeof(*header)),
2228f8413b3cSKevin Wolf     };
2229a9420734SKevin Wolf 
2230a9420734SKevin Wolf     if (flags & BLOCK_FLAG_ENCRYPT) {
2231f8413b3cSKevin Wolf         header->crypt_method = cpu_to_be32(QCOW_CRYPT_AES);
2232a9420734SKevin Wolf     } else {
2233f8413b3cSKevin Wolf         header->crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
2234a9420734SKevin Wolf     }
2235a9420734SKevin Wolf 
2236bfe8043eSStefan Hajnoczi     if (flags & BLOCK_FLAG_LAZY_REFCOUNTS) {
2237f8413b3cSKevin Wolf         header->compatible_features |=
2238bfe8043eSStefan Hajnoczi             cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS);
2239bfe8043eSStefan Hajnoczi     }
2240bfe8043eSStefan Hajnoczi 
22418341f00dSEric Blake     ret = blk_pwrite(blk, 0, header, cluster_size, 0);
2242f8413b3cSKevin Wolf     g_free(header);
2243a9420734SKevin Wolf     if (ret < 0) {
22443ef6c40aSMax Reitz         error_setg_errno(errp, -ret, "Could not write qcow2 header");
2245a9420734SKevin Wolf         goto out;
2246a9420734SKevin Wolf     }
2247a9420734SKevin Wolf 
2248b106ad91SKevin Wolf     /* Write a refcount table with one refcount block */
2249b106ad91SKevin Wolf     refcount_table = g_malloc0(2 * cluster_size);
2250b106ad91SKevin Wolf     refcount_table[0] = cpu_to_be64(2 * cluster_size);
22518341f00dSEric Blake     ret = blk_pwrite(blk, cluster_size, refcount_table, 2 * cluster_size, 0);
22527267c094SAnthony Liguori     g_free(refcount_table);
2253a9420734SKevin Wolf 
2254a9420734SKevin Wolf     if (ret < 0) {
22553ef6c40aSMax Reitz         error_setg_errno(errp, -ret, "Could not write refcount table");
2256a9420734SKevin Wolf         goto out;
2257a9420734SKevin Wolf     }
2258a9420734SKevin Wolf 
225923588797SKevin Wolf     blk_unref(blk);
226023588797SKevin Wolf     blk = NULL;
2261a9420734SKevin Wolf 
2262a9420734SKevin Wolf     /*
2263a9420734SKevin Wolf      * And now open the image and make it consistent first (i.e. increase the
2264a9420734SKevin Wolf      * refcount of the cluster that is occupied by the header and the refcount
2265a9420734SKevin Wolf      * table)
2266a9420734SKevin Wolf      */
2267e6641719SMax Reitz     options = qdict_new();
2268e6641719SMax Reitz     qdict_put(options, "driver", qstring_from_str("qcow2"));
2269efaa7c4eSMax Reitz     blk = blk_new_open(filename, NULL, options,
227055880601SKevin Wolf                        BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_NO_FLUSH,
227155880601SKevin Wolf                        &local_err);
227223588797SKevin Wolf     if (blk == NULL) {
22733ef6c40aSMax Reitz         error_propagate(errp, local_err);
227423588797SKevin Wolf         ret = -EIO;
2275a9420734SKevin Wolf         goto out;
2276a9420734SKevin Wolf     }
2277a9420734SKevin Wolf 
227823588797SKevin Wolf     ret = qcow2_alloc_clusters(blk_bs(blk), 3 * cluster_size);
2279a9420734SKevin Wolf     if (ret < 0) {
22803ef6c40aSMax Reitz         error_setg_errno(errp, -ret, "Could not allocate clusters for qcow2 "
22813ef6c40aSMax Reitz                          "header and refcount table");
2282a9420734SKevin Wolf         goto out;
2283a9420734SKevin Wolf 
2284a9420734SKevin Wolf     } else if (ret != 0) {
2285a9420734SKevin Wolf         error_report("Huh, first cluster in empty image is already in use?");
2286a9420734SKevin Wolf         abort();
2287a9420734SKevin Wolf     }
2288a9420734SKevin Wolf 
2289b527c9b3SKevin Wolf     /* Create a full header (including things like feature table) */
229023588797SKevin Wolf     ret = qcow2_update_header(blk_bs(blk));
2291b527c9b3SKevin Wolf     if (ret < 0) {
2292b527c9b3SKevin Wolf         error_setg_errno(errp, -ret, "Could not update qcow2 header");
2293b527c9b3SKevin Wolf         goto out;
2294b527c9b3SKevin Wolf     }
2295b527c9b3SKevin Wolf 
2296a9420734SKevin Wolf     /* Okay, now that we have a valid image, let's give it the right size */
2297ed3d2ec9SMax Reitz     ret = blk_truncate(blk, total_size, errp);
2298a9420734SKevin Wolf     if (ret < 0) {
2299ed3d2ec9SMax Reitz         error_prepend(errp, "Could not resize image: ");
2300a9420734SKevin Wolf         goto out;
2301a9420734SKevin Wolf     }
2302a9420734SKevin Wolf 
2303a9420734SKevin Wolf     /* Want a backing file? There you go.*/
2304a9420734SKevin Wolf     if (backing_file) {
230523588797SKevin Wolf         ret = bdrv_change_backing_file(blk_bs(blk), backing_file, backing_format);
2306a9420734SKevin Wolf         if (ret < 0) {
23073ef6c40aSMax Reitz             error_setg_errno(errp, -ret, "Could not assign backing file '%s' "
23083ef6c40aSMax Reitz                              "with format '%s'", backing_file, backing_format);
2309a9420734SKevin Wolf             goto out;
2310a9420734SKevin Wolf         }
2311a9420734SKevin Wolf     }
2312a9420734SKevin Wolf 
2313a9420734SKevin Wolf     /* And if we're supposed to preallocate metadata, do that now */
23140e4271b7SHu Tao     if (prealloc != PREALLOC_MODE_OFF) {
231523588797SKevin Wolf         BDRVQcow2State *s = blk_bs(blk)->opaque;
231615552c4aSZhi Yong Wu         qemu_co_mutex_lock(&s->lock);
231723588797SKevin Wolf         ret = preallocate(blk_bs(blk));
231815552c4aSZhi Yong Wu         qemu_co_mutex_unlock(&s->lock);
2319a9420734SKevin Wolf         if (ret < 0) {
23203ef6c40aSMax Reitz             error_setg_errno(errp, -ret, "Could not preallocate metadata");
2321a9420734SKevin Wolf             goto out;
2322a9420734SKevin Wolf         }
2323a9420734SKevin Wolf     }
2324a9420734SKevin Wolf 
232523588797SKevin Wolf     blk_unref(blk);
232623588797SKevin Wolf     blk = NULL;
2327ba2ab2f2SMax Reitz 
2328ba2ab2f2SMax Reitz     /* Reopen the image without BDRV_O_NO_FLUSH to flush it before returning */
2329e6641719SMax Reitz     options = qdict_new();
2330e6641719SMax Reitz     qdict_put(options, "driver", qstring_from_str("qcow2"));
2331efaa7c4eSMax Reitz     blk = blk_new_open(filename, NULL, options,
233272e775c7SKevin Wolf                        BDRV_O_RDWR | BDRV_O_NO_BACKING, &local_err);
233323588797SKevin Wolf     if (blk == NULL) {
2334ba2ab2f2SMax Reitz         error_propagate(errp, local_err);
233523588797SKevin Wolf         ret = -EIO;
2336ba2ab2f2SMax Reitz         goto out;
2337ba2ab2f2SMax Reitz     }
2338ba2ab2f2SMax Reitz 
2339a9420734SKevin Wolf     ret = 0;
2340a9420734SKevin Wolf out:
234123588797SKevin Wolf     if (blk) {
234223588797SKevin Wolf         blk_unref(blk);
2343f67503e5SMax Reitz     }
2344a9420734SKevin Wolf     return ret;
2345a9420734SKevin Wolf }
2346de5f3f40SKevin Wolf 
23471bd0e2d1SChunyan Liu static int qcow2_create(const char *filename, QemuOpts *opts, Error **errp)
2348de5f3f40SKevin Wolf {
23491bd0e2d1SChunyan Liu     char *backing_file = NULL;
23501bd0e2d1SChunyan Liu     char *backing_fmt = NULL;
23511bd0e2d1SChunyan Liu     char *buf = NULL;
2352180e9526SHu Tao     uint64_t size = 0;
2353de5f3f40SKevin Wolf     int flags = 0;
235499cce9faSKevin Wolf     size_t cluster_size = DEFAULT_CLUSTER_SIZE;
2355ffeaac9bSHu Tao     PreallocMode prealloc;
23568ad1898cSKevin Wolf     int version = 3;
2357bd4b167fSMax Reitz     uint64_t refcount_bits = 16;
2358bd4b167fSMax Reitz     int refcount_order;
23593ef6c40aSMax Reitz     Error *local_err = NULL;
23603ef6c40aSMax Reitz     int ret;
2361de5f3f40SKevin Wolf 
2362de5f3f40SKevin Wolf     /* Read out options */
2363180e9526SHu Tao     size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
2364c2eb918eSHu Tao                     BDRV_SECTOR_SIZE);
23651bd0e2d1SChunyan Liu     backing_file = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
23661bd0e2d1SChunyan Liu     backing_fmt = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FMT);
23671bd0e2d1SChunyan Liu     if (qemu_opt_get_bool_del(opts, BLOCK_OPT_ENCRYPT, false)) {
23681bd0e2d1SChunyan Liu         flags |= BLOCK_FLAG_ENCRYPT;
2369de5f3f40SKevin Wolf     }
23701bd0e2d1SChunyan Liu     cluster_size = qemu_opt_get_size_del(opts, BLOCK_OPT_CLUSTER_SIZE,
23711bd0e2d1SChunyan Liu                                          DEFAULT_CLUSTER_SIZE);
23721bd0e2d1SChunyan Liu     buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
2373ffeaac9bSHu Tao     prealloc = qapi_enum_parse(PreallocMode_lookup, buf,
23747fb1cf16SEric Blake                                PREALLOC_MODE__MAX, PREALLOC_MODE_OFF,
2375ffeaac9bSHu Tao                                &local_err);
2376ffeaac9bSHu Tao     if (local_err) {
2377ffeaac9bSHu Tao         error_propagate(errp, local_err);
23781bd0e2d1SChunyan Liu         ret = -EINVAL;
23791bd0e2d1SChunyan Liu         goto finish;
2380de5f3f40SKevin Wolf     }
23811bd0e2d1SChunyan Liu     g_free(buf);
23821bd0e2d1SChunyan Liu     buf = qemu_opt_get_del(opts, BLOCK_OPT_COMPAT_LEVEL);
23831bd0e2d1SChunyan Liu     if (!buf) {
23849117b477SKevin Wolf         /* keep the default */
23851bd0e2d1SChunyan Liu     } else if (!strcmp(buf, "0.10")) {
23866744cbabSKevin Wolf         version = 2;
23871bd0e2d1SChunyan Liu     } else if (!strcmp(buf, "1.1")) {
23886744cbabSKevin Wolf         version = 3;
23896744cbabSKevin Wolf     } else {
23901bd0e2d1SChunyan Liu         error_setg(errp, "Invalid compatibility level: '%s'", buf);
23911bd0e2d1SChunyan Liu         ret = -EINVAL;
23921bd0e2d1SChunyan Liu         goto finish;
23936744cbabSKevin Wolf     }
23941bd0e2d1SChunyan Liu 
23951bd0e2d1SChunyan Liu     if (qemu_opt_get_bool_del(opts, BLOCK_OPT_LAZY_REFCOUNTS, false)) {
23961bd0e2d1SChunyan Liu         flags |= BLOCK_FLAG_LAZY_REFCOUNTS;
2397de5f3f40SKevin Wolf     }
2398de5f3f40SKevin Wolf 
2399ffeaac9bSHu Tao     if (backing_file && prealloc != PREALLOC_MODE_OFF) {
24003ef6c40aSMax Reitz         error_setg(errp, "Backing file and preallocation cannot be used at "
24013ef6c40aSMax Reitz                    "the same time");
24021bd0e2d1SChunyan Liu         ret = -EINVAL;
24031bd0e2d1SChunyan Liu         goto finish;
2404de5f3f40SKevin Wolf     }
2405de5f3f40SKevin Wolf 
2406bfe8043eSStefan Hajnoczi     if (version < 3 && (flags & BLOCK_FLAG_LAZY_REFCOUNTS)) {
24073ef6c40aSMax Reitz         error_setg(errp, "Lazy refcounts only supported with compatibility "
24083ef6c40aSMax Reitz                    "level 1.1 and above (use compat=1.1 or greater)");
24091bd0e2d1SChunyan Liu         ret = -EINVAL;
24101bd0e2d1SChunyan Liu         goto finish;
2411bfe8043eSStefan Hajnoczi     }
2412bfe8043eSStefan Hajnoczi 
241306d05fa7SMax Reitz     refcount_bits = qemu_opt_get_number_del(opts, BLOCK_OPT_REFCOUNT_BITS,
241406d05fa7SMax Reitz                                             refcount_bits);
241506d05fa7SMax Reitz     if (refcount_bits > 64 || !is_power_of_2(refcount_bits)) {
241606d05fa7SMax Reitz         error_setg(errp, "Refcount width must be a power of two and may not "
241706d05fa7SMax Reitz                    "exceed 64 bits");
241806d05fa7SMax Reitz         ret = -EINVAL;
241906d05fa7SMax Reitz         goto finish;
242006d05fa7SMax Reitz     }
242106d05fa7SMax Reitz 
2422bd4b167fSMax Reitz     if (version < 3 && refcount_bits != 16) {
2423bd4b167fSMax Reitz         error_setg(errp, "Different refcount widths than 16 bits require "
2424bd4b167fSMax Reitz                    "compatibility level 1.1 or above (use compat=1.1 or "
2425bd4b167fSMax Reitz                    "greater)");
2426bd4b167fSMax Reitz         ret = -EINVAL;
2427bd4b167fSMax Reitz         goto finish;
2428bd4b167fSMax Reitz     }
2429bd4b167fSMax Reitz 
2430786a4ea8SStefan Hajnoczi     refcount_order = ctz32(refcount_bits);
2431bd4b167fSMax Reitz 
2432180e9526SHu Tao     ret = qcow2_create2(filename, size, backing_file, backing_fmt, flags,
2433bd4b167fSMax Reitz                         cluster_size, prealloc, opts, version, refcount_order,
2434bd4b167fSMax Reitz                         &local_err);
24353ef6c40aSMax Reitz     error_propagate(errp, local_err);
24361bd0e2d1SChunyan Liu 
24371bd0e2d1SChunyan Liu finish:
24381bd0e2d1SChunyan Liu     g_free(backing_file);
24391bd0e2d1SChunyan Liu     g_free(backing_fmt);
24401bd0e2d1SChunyan Liu     g_free(buf);
24413ef6c40aSMax Reitz     return ret;
2442de5f3f40SKevin Wolf }
2443de5f3f40SKevin Wolf 
24442928abceSDenis V. Lunev 
2445ebb718a5SEric Blake static bool is_zero_sectors(BlockDriverState *bs, int64_t start,
2446ebb718a5SEric Blake                             uint32_t count)
24472928abceSDenis V. Lunev {
24482928abceSDenis V. Lunev     int nr;
24492928abceSDenis V. Lunev     BlockDriverState *file;
2450ebb718a5SEric Blake     int64_t res;
2451ebb718a5SEric Blake 
2452ebb718a5SEric Blake     if (!count) {
2453ebb718a5SEric Blake         return true;
24542928abceSDenis V. Lunev     }
2455ebb718a5SEric Blake     res = bdrv_get_block_status_above(bs, NULL, start, count,
2456ebb718a5SEric Blake                                       &nr, &file);
2457ebb718a5SEric Blake     return res >= 0 && (res & BDRV_BLOCK_ZERO) && nr == count;
24582928abceSDenis V. Lunev }
24592928abceSDenis V. Lunev 
24605544b59fSEric Blake static coroutine_fn int qcow2_co_pwrite_zeroes(BlockDriverState *bs,
24615544b59fSEric Blake     int64_t offset, int count, BdrvRequestFlags flags)
2462621f0589SKevin Wolf {
2463621f0589SKevin Wolf     int ret;
2464ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
2465621f0589SKevin Wolf 
24665544b59fSEric Blake     uint32_t head = offset % s->cluster_size;
24675544b59fSEric Blake     uint32_t tail = (offset + count) % s->cluster_size;
24682928abceSDenis V. Lunev 
24695544b59fSEric Blake     trace_qcow2_pwrite_zeroes_start_req(qemu_coroutine_self(), offset, count);
24705a64e942SDenis V. Lunev 
2471ebb718a5SEric Blake     if (head || tail) {
24725544b59fSEric Blake         int64_t cl_start = (offset - head) >> BDRV_SECTOR_BITS;
2473ebb718a5SEric Blake         uint64_t off;
2474ecfe1863SKevin Wolf         unsigned int nr;
24752928abceSDenis V. Lunev 
24765544b59fSEric Blake         assert(head + count <= s->cluster_size);
24772928abceSDenis V. Lunev 
2478ebb718a5SEric Blake         /* check whether remainder of cluster already reads as zero */
24795544b59fSEric Blake         if (!(is_zero_sectors(bs, cl_start,
24805544b59fSEric Blake                               DIV_ROUND_UP(head, BDRV_SECTOR_SIZE)) &&
24815544b59fSEric Blake               is_zero_sectors(bs, (offset + count) >> BDRV_SECTOR_BITS,
24825544b59fSEric Blake                               DIV_ROUND_UP(-tail & (s->cluster_size - 1),
24835544b59fSEric Blake                                            BDRV_SECTOR_SIZE)))) {
2484621f0589SKevin Wolf             return -ENOTSUP;
2485621f0589SKevin Wolf         }
2486621f0589SKevin Wolf 
2487621f0589SKevin Wolf         qemu_co_mutex_lock(&s->lock);
24882928abceSDenis V. Lunev         /* We can have new write after previous check */
24895544b59fSEric Blake         offset = cl_start << BDRV_SECTOR_BITS;
24905544b59fSEric Blake         count = s->cluster_size;
2491ecfe1863SKevin Wolf         nr = s->cluster_size;
24925544b59fSEric Blake         ret = qcow2_get_cluster_offset(bs, offset, &nr, &off);
2493ebb718a5SEric Blake         if (ret != QCOW2_CLUSTER_UNALLOCATED && ret != QCOW2_CLUSTER_ZERO) {
24942928abceSDenis V. Lunev             qemu_co_mutex_unlock(&s->lock);
24952928abceSDenis V. Lunev             return -ENOTSUP;
24962928abceSDenis V. Lunev         }
24972928abceSDenis V. Lunev     } else {
24982928abceSDenis V. Lunev         qemu_co_mutex_lock(&s->lock);
24992928abceSDenis V. Lunev     }
25002928abceSDenis V. Lunev 
25015544b59fSEric Blake     trace_qcow2_pwrite_zeroes(qemu_coroutine_self(), offset, count);
25025a64e942SDenis V. Lunev 
25032928abceSDenis V. Lunev     /* Whatever is left can use real zero clusters */
2504170f4b2eSFam Zheng     ret = qcow2_zero_clusters(bs, offset, count >> BDRV_SECTOR_BITS, flags);
2505621f0589SKevin Wolf     qemu_co_mutex_unlock(&s->lock);
2506621f0589SKevin Wolf 
2507621f0589SKevin Wolf     return ret;
2508621f0589SKevin Wolf }
2509621f0589SKevin Wolf 
251082e8a788SEric Blake static coroutine_fn int qcow2_co_pdiscard(BlockDriverState *bs,
251182e8a788SEric Blake                                           int64_t offset, int count)
25125ea929e3SKevin Wolf {
25136db39ae2SPaolo Bonzini     int ret;
2514ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
25156db39ae2SPaolo Bonzini 
251649228d1eSEric Blake     if (!QEMU_IS_ALIGNED(offset | count, s->cluster_size)) {
251749228d1eSEric Blake         assert(count < s->cluster_size);
251849228d1eSEric Blake         return -ENOTSUP;
251949228d1eSEric Blake     }
252049228d1eSEric Blake 
25216db39ae2SPaolo Bonzini     qemu_co_mutex_lock(&s->lock);
252282e8a788SEric Blake     ret = qcow2_discard_clusters(bs, offset, count >> BDRV_SECTOR_BITS,
252382e8a788SEric Blake                                  QCOW2_DISCARD_REQUEST, false);
25246db39ae2SPaolo Bonzini     qemu_co_mutex_unlock(&s->lock);
25256db39ae2SPaolo Bonzini     return ret;
25265ea929e3SKevin Wolf }
25275ea929e3SKevin Wolf 
2528*4bff28b8SMax Reitz static int qcow2_truncate(BlockDriverState *bs, int64_t offset, Error **errp)
2529419b19d9SStefan Hajnoczi {
2530ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
25312cf7cfa1SKevin Wolf     int64_t new_l1_size;
25322cf7cfa1SKevin Wolf     int ret;
2533419b19d9SStefan Hajnoczi 
2534419b19d9SStefan Hajnoczi     if (offset & 511) {
2535*4bff28b8SMax Reitz         error_setg(errp, "The new size must be a multiple of 512");
2536419b19d9SStefan Hajnoczi         return -EINVAL;
2537419b19d9SStefan Hajnoczi     }
2538419b19d9SStefan Hajnoczi 
2539419b19d9SStefan Hajnoczi     /* cannot proceed if image has snapshots */
2540419b19d9SStefan Hajnoczi     if (s->nb_snapshots) {
2541*4bff28b8SMax Reitz         error_setg(errp, "Can't resize an image which has snapshots");
2542419b19d9SStefan Hajnoczi         return -ENOTSUP;
2543419b19d9SStefan Hajnoczi     }
2544419b19d9SStefan Hajnoczi 
2545419b19d9SStefan Hajnoczi     /* shrinking is currently not supported */
2546419b19d9SStefan Hajnoczi     if (offset < bs->total_sectors * 512) {
2547*4bff28b8SMax Reitz         error_setg(errp, "qcow2 doesn't support shrinking images yet");
2548419b19d9SStefan Hajnoczi         return -ENOTSUP;
2549419b19d9SStefan Hajnoczi     }
2550419b19d9SStefan Hajnoczi 
2551419b19d9SStefan Hajnoczi     new_l1_size = size_to_l1(s, offset);
255272893756SStefan Hajnoczi     ret = qcow2_grow_l1_table(bs, new_l1_size, true);
2553419b19d9SStefan Hajnoczi     if (ret < 0) {
2554419b19d9SStefan Hajnoczi         return ret;
2555419b19d9SStefan Hajnoczi     }
2556419b19d9SStefan Hajnoczi 
2557419b19d9SStefan Hajnoczi     /* write updated header.size */
2558419b19d9SStefan Hajnoczi     offset = cpu_to_be64(offset);
2559d9ca2ea2SKevin Wolf     ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, size),
2560419b19d9SStefan Hajnoczi                            &offset, sizeof(uint64_t));
2561419b19d9SStefan Hajnoczi     if (ret < 0) {
2562419b19d9SStefan Hajnoczi         return ret;
2563419b19d9SStefan Hajnoczi     }
2564419b19d9SStefan Hajnoczi 
2565419b19d9SStefan Hajnoczi     s->l1_vm_state_index = new_l1_size;
2566419b19d9SStefan Hajnoczi     return 0;
2567419b19d9SStefan Hajnoczi }
2568419b19d9SStefan Hajnoczi 
256920d97356SBlue Swirl /* XXX: put compressed sectors first, then all the cluster aligned
257020d97356SBlue Swirl    tables to avoid losing bytes in alignment */
2571fcccefc5SPavel Butsykin static coroutine_fn int
2572fcccefc5SPavel Butsykin qcow2_co_pwritev_compressed(BlockDriverState *bs, uint64_t offset,
2573fcccefc5SPavel Butsykin                             uint64_t bytes, QEMUIOVector *qiov)
257420d97356SBlue Swirl {
2575ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
2576fcccefc5SPavel Butsykin     QEMUIOVector hd_qiov;
2577fcccefc5SPavel Butsykin     struct iovec iov;
257820d97356SBlue Swirl     z_stream strm;
257920d97356SBlue Swirl     int ret, out_len;
2580fcccefc5SPavel Butsykin     uint8_t *buf, *out_buf;
258120d97356SBlue Swirl     uint64_t cluster_offset;
258220d97356SBlue Swirl 
2583fcccefc5SPavel Butsykin     if (bytes == 0) {
258420d97356SBlue Swirl         /* align end of file to a sector boundary to ease reading with
258520d97356SBlue Swirl            sector based I/Os */
25869a4f4c31SKevin Wolf         cluster_offset = bdrv_getlength(bs->file->bs);
2587ed3d2ec9SMax Reitz         return bdrv_truncate(bs->file, cluster_offset, NULL);
258820d97356SBlue Swirl     }
258920d97356SBlue Swirl 
2590fcccefc5SPavel Butsykin     buf = qemu_blockalign(bs, s->cluster_size);
2591a2c0ca6fSPavel Butsykin     if (bytes != s->cluster_size) {
2592a2c0ca6fSPavel Butsykin         if (bytes > s->cluster_size ||
2593a2c0ca6fSPavel Butsykin             offset + bytes != bs->total_sectors << BDRV_SECTOR_BITS)
2594a2c0ca6fSPavel Butsykin         {
2595a2c0ca6fSPavel Butsykin             qemu_vfree(buf);
2596a2c0ca6fSPavel Butsykin             return -EINVAL;
2597a2c0ca6fSPavel Butsykin         }
2598a2c0ca6fSPavel Butsykin         /* Zero-pad last write if image size is not cluster aligned */
2599a2c0ca6fSPavel Butsykin         memset(buf + bytes, 0, s->cluster_size - bytes);
2600a2c0ca6fSPavel Butsykin     }
26018b2bd093SPavel Butsykin     qemu_iovec_to_buf(qiov, 0, buf, bytes);
260220d97356SBlue Swirl 
2603ebf7bba0SVladimir Sementsov-Ogievskiy     out_buf = g_malloc(s->cluster_size);
260420d97356SBlue Swirl 
260520d97356SBlue Swirl     /* best compression, small window, no zlib header */
260620d97356SBlue Swirl     memset(&strm, 0, sizeof(strm));
260720d97356SBlue Swirl     ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
260820d97356SBlue Swirl                        Z_DEFLATED, -12,
260920d97356SBlue Swirl                        9, Z_DEFAULT_STRATEGY);
261020d97356SBlue Swirl     if (ret != 0) {
26118f1efd00SKevin Wolf         ret = -EINVAL;
26128f1efd00SKevin Wolf         goto fail;
261320d97356SBlue Swirl     }
261420d97356SBlue Swirl 
261520d97356SBlue Swirl     strm.avail_in = s->cluster_size;
261620d97356SBlue Swirl     strm.next_in = (uint8_t *)buf;
261720d97356SBlue Swirl     strm.avail_out = s->cluster_size;
261820d97356SBlue Swirl     strm.next_out = out_buf;
261920d97356SBlue Swirl 
262020d97356SBlue Swirl     ret = deflate(&strm, Z_FINISH);
262120d97356SBlue Swirl     if (ret != Z_STREAM_END && ret != Z_OK) {
262220d97356SBlue Swirl         deflateEnd(&strm);
26238f1efd00SKevin Wolf         ret = -EINVAL;
26248f1efd00SKevin Wolf         goto fail;
262520d97356SBlue Swirl     }
262620d97356SBlue Swirl     out_len = strm.next_out - out_buf;
262720d97356SBlue Swirl 
262820d97356SBlue Swirl     deflateEnd(&strm);
262920d97356SBlue Swirl 
263020d97356SBlue Swirl     if (ret != Z_STREAM_END || out_len >= s->cluster_size) {
263120d97356SBlue Swirl         /* could not compress: write normal cluster */
2632fcccefc5SPavel Butsykin         ret = qcow2_co_pwritev(bs, offset, bytes, qiov, 0);
26338f1efd00SKevin Wolf         if (ret < 0) {
26348f1efd00SKevin Wolf             goto fail;
26358f1efd00SKevin Wolf         }
2636fcccefc5SPavel Butsykin         goto success;
2637fcccefc5SPavel Butsykin     }
2638fcccefc5SPavel Butsykin 
2639fcccefc5SPavel Butsykin     qemu_co_mutex_lock(&s->lock);
2640fcccefc5SPavel Butsykin     cluster_offset =
2641fcccefc5SPavel Butsykin         qcow2_alloc_compressed_cluster_offset(bs, offset, out_len);
26428f1efd00SKevin Wolf     if (!cluster_offset) {
2643fcccefc5SPavel Butsykin         qemu_co_mutex_unlock(&s->lock);
26448f1efd00SKevin Wolf         ret = -EIO;
26458f1efd00SKevin Wolf         goto fail;
26468f1efd00SKevin Wolf     }
264720d97356SBlue Swirl     cluster_offset &= s->cluster_offset_mask;
2648cf93980eSMax Reitz 
2649231bb267SMax Reitz     ret = qcow2_pre_write_overlap_check(bs, 0, cluster_offset, out_len);
2650fcccefc5SPavel Butsykin     qemu_co_mutex_unlock(&s->lock);
2651cf93980eSMax Reitz     if (ret < 0) {
2652cf93980eSMax Reitz         goto fail;
2653cf93980eSMax Reitz     }
2654cf93980eSMax Reitz 
2655fcccefc5SPavel Butsykin     iov = (struct iovec) {
2656fcccefc5SPavel Butsykin         .iov_base   = out_buf,
2657fcccefc5SPavel Butsykin         .iov_len    = out_len,
2658fcccefc5SPavel Butsykin     };
2659fcccefc5SPavel Butsykin     qemu_iovec_init_external(&hd_qiov, &iov, 1);
2660fcccefc5SPavel Butsykin 
266166f82ceeSKevin Wolf     BLKDBG_EVENT(bs->file, BLKDBG_WRITE_COMPRESSED);
2662fcccefc5SPavel Butsykin     ret = bdrv_co_pwritev(bs->file, cluster_offset, out_len, &hd_qiov, 0);
26638f1efd00SKevin Wolf     if (ret < 0) {
26648f1efd00SKevin Wolf         goto fail;
266520d97356SBlue Swirl     }
2666fcccefc5SPavel Butsykin success:
26678f1efd00SKevin Wolf     ret = 0;
26688f1efd00SKevin Wolf fail:
2669fcccefc5SPavel Butsykin     qemu_vfree(buf);
26707267c094SAnthony Liguori     g_free(out_buf);
26718f1efd00SKevin Wolf     return ret;
267220d97356SBlue Swirl }
267320d97356SBlue Swirl 
267494054183SMax Reitz static int make_completely_empty(BlockDriverState *bs)
267594054183SMax Reitz {
2676ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
2677ed3d2ec9SMax Reitz     Error *local_err = NULL;
267894054183SMax Reitz     int ret, l1_clusters;
267994054183SMax Reitz     int64_t offset;
268094054183SMax Reitz     uint64_t *new_reftable = NULL;
268194054183SMax Reitz     uint64_t rt_entry, l1_size2;
268294054183SMax Reitz     struct {
268394054183SMax Reitz         uint64_t l1_offset;
268494054183SMax Reitz         uint64_t reftable_offset;
268594054183SMax Reitz         uint32_t reftable_clusters;
268694054183SMax Reitz     } QEMU_PACKED l1_ofs_rt_ofs_cls;
268794054183SMax Reitz 
268894054183SMax Reitz     ret = qcow2_cache_empty(bs, s->l2_table_cache);
268994054183SMax Reitz     if (ret < 0) {
269094054183SMax Reitz         goto fail;
269194054183SMax Reitz     }
269294054183SMax Reitz 
269394054183SMax Reitz     ret = qcow2_cache_empty(bs, s->refcount_block_cache);
269494054183SMax Reitz     if (ret < 0) {
269594054183SMax Reitz         goto fail;
269694054183SMax Reitz     }
269794054183SMax Reitz 
269894054183SMax Reitz     /* Refcounts will be broken utterly */
269994054183SMax Reitz     ret = qcow2_mark_dirty(bs);
270094054183SMax Reitz     if (ret < 0) {
270194054183SMax Reitz         goto fail;
270294054183SMax Reitz     }
270394054183SMax Reitz 
270494054183SMax Reitz     BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
270594054183SMax Reitz 
270694054183SMax Reitz     l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / sizeof(uint64_t));
270794054183SMax Reitz     l1_size2 = (uint64_t)s->l1_size * sizeof(uint64_t);
270894054183SMax Reitz 
270994054183SMax Reitz     /* After this call, neither the in-memory nor the on-disk refcount
271094054183SMax Reitz      * information accurately describe the actual references */
271194054183SMax Reitz 
2712720ff280SKevin Wolf     ret = bdrv_pwrite_zeroes(bs->file, s->l1_table_offset,
271374021bc4SEric Blake                              l1_clusters * s->cluster_size, 0);
271494054183SMax Reitz     if (ret < 0) {
271594054183SMax Reitz         goto fail_broken_refcounts;
271694054183SMax Reitz     }
271794054183SMax Reitz     memset(s->l1_table, 0, l1_size2);
271894054183SMax Reitz 
271994054183SMax Reitz     BLKDBG_EVENT(bs->file, BLKDBG_EMPTY_IMAGE_PREPARE);
272094054183SMax Reitz 
272194054183SMax Reitz     /* Overwrite enough clusters at the beginning of the sectors to place
272294054183SMax Reitz      * the refcount table, a refcount block and the L1 table in; this may
272394054183SMax Reitz      * overwrite parts of the existing refcount and L1 table, which is not
272494054183SMax Reitz      * an issue because the dirty flag is set, complete data loss is in fact
272594054183SMax Reitz      * desired and partial data loss is consequently fine as well */
2726720ff280SKevin Wolf     ret = bdrv_pwrite_zeroes(bs->file, s->cluster_size,
272774021bc4SEric Blake                              (2 + l1_clusters) * s->cluster_size, 0);
272894054183SMax Reitz     /* This call (even if it failed overall) may have overwritten on-disk
272994054183SMax Reitz      * refcount structures; in that case, the in-memory refcount information
273094054183SMax Reitz      * will probably differ from the on-disk information which makes the BDS
273194054183SMax Reitz      * unusable */
273294054183SMax Reitz     if (ret < 0) {
273394054183SMax Reitz         goto fail_broken_refcounts;
273494054183SMax Reitz     }
273594054183SMax Reitz 
273694054183SMax Reitz     BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
273794054183SMax Reitz     BLKDBG_EVENT(bs->file, BLKDBG_REFTABLE_UPDATE);
273894054183SMax Reitz 
273994054183SMax Reitz     /* "Create" an empty reftable (one cluster) directly after the image
274094054183SMax Reitz      * header and an empty L1 table three clusters after the image header;
274194054183SMax Reitz      * the cluster between those two will be used as the first refblock */
2742f1f7a1ddSPeter Maydell     l1_ofs_rt_ofs_cls.l1_offset = cpu_to_be64(3 * s->cluster_size);
2743f1f7a1ddSPeter Maydell     l1_ofs_rt_ofs_cls.reftable_offset = cpu_to_be64(s->cluster_size);
2744f1f7a1ddSPeter Maydell     l1_ofs_rt_ofs_cls.reftable_clusters = cpu_to_be32(1);
2745d9ca2ea2SKevin Wolf     ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, l1_table_offset),
274694054183SMax Reitz                            &l1_ofs_rt_ofs_cls, sizeof(l1_ofs_rt_ofs_cls));
274794054183SMax Reitz     if (ret < 0) {
274894054183SMax Reitz         goto fail_broken_refcounts;
274994054183SMax Reitz     }
275094054183SMax Reitz 
275194054183SMax Reitz     s->l1_table_offset = 3 * s->cluster_size;
275294054183SMax Reitz 
275394054183SMax Reitz     new_reftable = g_try_new0(uint64_t, s->cluster_size / sizeof(uint64_t));
275494054183SMax Reitz     if (!new_reftable) {
275594054183SMax Reitz         ret = -ENOMEM;
275694054183SMax Reitz         goto fail_broken_refcounts;
275794054183SMax Reitz     }
275894054183SMax Reitz 
275994054183SMax Reitz     s->refcount_table_offset = s->cluster_size;
276094054183SMax Reitz     s->refcount_table_size   = s->cluster_size / sizeof(uint64_t);
27617061a078SAlberto Garcia     s->max_refcount_table_index = 0;
276294054183SMax Reitz 
276394054183SMax Reitz     g_free(s->refcount_table);
276494054183SMax Reitz     s->refcount_table = new_reftable;
276594054183SMax Reitz     new_reftable = NULL;
276694054183SMax Reitz 
276794054183SMax Reitz     /* Now the in-memory refcount information again corresponds to the on-disk
276894054183SMax Reitz      * information (reftable is empty and no refblocks (the refblock cache is
276994054183SMax Reitz      * empty)); however, this means some clusters (e.g. the image header) are
277094054183SMax Reitz      * referenced, but not refcounted, but the normal qcow2 code assumes that
277194054183SMax Reitz      * the in-memory information is always correct */
277294054183SMax Reitz 
277394054183SMax Reitz     BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_ALLOC);
277494054183SMax Reitz 
277594054183SMax Reitz     /* Enter the first refblock into the reftable */
277694054183SMax Reitz     rt_entry = cpu_to_be64(2 * s->cluster_size);
2777d9ca2ea2SKevin Wolf     ret = bdrv_pwrite_sync(bs->file, s->cluster_size,
277894054183SMax Reitz                            &rt_entry, sizeof(rt_entry));
277994054183SMax Reitz     if (ret < 0) {
278094054183SMax Reitz         goto fail_broken_refcounts;
278194054183SMax Reitz     }
278294054183SMax Reitz     s->refcount_table[0] = 2 * s->cluster_size;
278394054183SMax Reitz 
278494054183SMax Reitz     s->free_cluster_index = 0;
278594054183SMax Reitz     assert(3 + l1_clusters <= s->refcount_block_size);
278694054183SMax Reitz     offset = qcow2_alloc_clusters(bs, 3 * s->cluster_size + l1_size2);
278794054183SMax Reitz     if (offset < 0) {
278894054183SMax Reitz         ret = offset;
278994054183SMax Reitz         goto fail_broken_refcounts;
279094054183SMax Reitz     } else if (offset > 0) {
279194054183SMax Reitz         error_report("First cluster in emptied image is in use");
279294054183SMax Reitz         abort();
279394054183SMax Reitz     }
279494054183SMax Reitz 
279594054183SMax Reitz     /* Now finally the in-memory information corresponds to the on-disk
279694054183SMax Reitz      * structures and is correct */
279794054183SMax Reitz     ret = qcow2_mark_clean(bs);
279894054183SMax Reitz     if (ret < 0) {
279994054183SMax Reitz         goto fail;
280094054183SMax Reitz     }
280194054183SMax Reitz 
2802ed3d2ec9SMax Reitz     ret = bdrv_truncate(bs->file, (3 + l1_clusters) * s->cluster_size,
2803ed3d2ec9SMax Reitz                         &local_err);
280494054183SMax Reitz     if (ret < 0) {
2805ed3d2ec9SMax Reitz         error_report_err(local_err);
280694054183SMax Reitz         goto fail;
280794054183SMax Reitz     }
280894054183SMax Reitz 
280994054183SMax Reitz     return 0;
281094054183SMax Reitz 
281194054183SMax Reitz fail_broken_refcounts:
281294054183SMax Reitz     /* The BDS is unusable at this point. If we wanted to make it usable, we
281394054183SMax Reitz      * would have to call qcow2_refcount_close(), qcow2_refcount_init(),
281494054183SMax Reitz      * qcow2_check_refcounts(), qcow2_refcount_close() and qcow2_refcount_init()
281594054183SMax Reitz      * again. However, because the functions which could have caused this error
281694054183SMax Reitz      * path to be taken are used by those functions as well, it's very likely
281794054183SMax Reitz      * that that sequence will fail as well. Therefore, just eject the BDS. */
281894054183SMax Reitz     bs->drv = NULL;
281994054183SMax Reitz 
282094054183SMax Reitz fail:
282194054183SMax Reitz     g_free(new_reftable);
282294054183SMax Reitz     return ret;
282394054183SMax Reitz }
282494054183SMax Reitz 
2825491d27e2SMax Reitz static int qcow2_make_empty(BlockDriverState *bs)
2826491d27e2SMax Reitz {
2827ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
2828491d27e2SMax Reitz     uint64_t start_sector;
2829a3e1505dSEric Blake     int sector_step = (QEMU_ALIGN_DOWN(INT_MAX, s->cluster_size) /
2830a3e1505dSEric Blake                        BDRV_SECTOR_SIZE);
283194054183SMax Reitz     int l1_clusters, ret = 0;
2832491d27e2SMax Reitz 
283394054183SMax Reitz     l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / sizeof(uint64_t));
283494054183SMax Reitz 
283594054183SMax Reitz     if (s->qcow_version >= 3 && !s->snapshots &&
283694054183SMax Reitz         3 + l1_clusters <= s->refcount_block_size) {
283794054183SMax Reitz         /* The following function only works for qcow2 v3 images (it requires
283894054183SMax Reitz          * the dirty flag) and only as long as there are no snapshots (because
283994054183SMax Reitz          * it completely empties the image). Furthermore, the L1 table and three
284094054183SMax Reitz          * additional clusters (image header, refcount table, one refcount
284194054183SMax Reitz          * block) have to fit inside one refcount block. */
284294054183SMax Reitz         return make_completely_empty(bs);
284394054183SMax Reitz     }
284494054183SMax Reitz 
284594054183SMax Reitz     /* This fallback code simply discards every active cluster; this is slow,
284694054183SMax Reitz      * but works in all cases */
2847491d27e2SMax Reitz     for (start_sector = 0; start_sector < bs->total_sectors;
2848491d27e2SMax Reitz          start_sector += sector_step)
2849491d27e2SMax Reitz     {
2850491d27e2SMax Reitz         /* As this function is generally used after committing an external
2851491d27e2SMax Reitz          * snapshot, QCOW2_DISCARD_SNAPSHOT seems appropriate. Also, the
2852491d27e2SMax Reitz          * default action for this kind of discard is to pass the discard,
2853491d27e2SMax Reitz          * which will ideally result in an actually smaller image file, as
2854491d27e2SMax Reitz          * is probably desired. */
2855491d27e2SMax Reitz         ret = qcow2_discard_clusters(bs, start_sector * BDRV_SECTOR_SIZE,
2856491d27e2SMax Reitz                                      MIN(sector_step,
2857491d27e2SMax Reitz                                          bs->total_sectors - start_sector),
2858491d27e2SMax Reitz                                      QCOW2_DISCARD_SNAPSHOT, true);
2859491d27e2SMax Reitz         if (ret < 0) {
2860491d27e2SMax Reitz             break;
2861491d27e2SMax Reitz         }
2862491d27e2SMax Reitz     }
2863491d27e2SMax Reitz 
2864491d27e2SMax Reitz     return ret;
2865491d27e2SMax Reitz }
2866491d27e2SMax Reitz 
2867a968168cSDong Xu Wang static coroutine_fn int qcow2_co_flush_to_os(BlockDriverState *bs)
286820d97356SBlue Swirl {
2869ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
287029c1a730SKevin Wolf     int ret;
287129c1a730SKevin Wolf 
28728b94ff85SPaolo Bonzini     qemu_co_mutex_lock(&s->lock);
2873f3c3b87dSDenis V. Lunev     ret = qcow2_cache_write(bs, s->l2_table_cache);
287429c1a730SKevin Wolf     if (ret < 0) {
2875c95de7e2SDong Xu Wang         qemu_co_mutex_unlock(&s->lock);
28768b94ff85SPaolo Bonzini         return ret;
287729c1a730SKevin Wolf     }
287829c1a730SKevin Wolf 
2879bfe8043eSStefan Hajnoczi     if (qcow2_need_accurate_refcounts(s)) {
2880f3c3b87dSDenis V. Lunev         ret = qcow2_cache_write(bs, s->refcount_block_cache);
288129c1a730SKevin Wolf         if (ret < 0) {
2882c95de7e2SDong Xu Wang             qemu_co_mutex_unlock(&s->lock);
28838b94ff85SPaolo Bonzini             return ret;
288429c1a730SKevin Wolf         }
2885bfe8043eSStefan Hajnoczi     }
28868b94ff85SPaolo Bonzini     qemu_co_mutex_unlock(&s->lock);
288729c1a730SKevin Wolf 
2888eb489bb1SKevin Wolf     return 0;
2889eb489bb1SKevin Wolf }
2890eb489bb1SKevin Wolf 
28917c80ab3fSJes Sorensen static int qcow2_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
289220d97356SBlue Swirl {
2893ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
289495de6d70SPaolo Bonzini     bdi->unallocated_blocks_are_zero = true;
289595de6d70SPaolo Bonzini     bdi->can_write_zeroes_with_unmap = (s->qcow_version >= 3);
289620d97356SBlue Swirl     bdi->cluster_size = s->cluster_size;
28977c80ab3fSJes Sorensen     bdi->vm_state_offset = qcow2_vm_state_offset(s);
289820d97356SBlue Swirl     return 0;
289920d97356SBlue Swirl }
290020d97356SBlue Swirl 
290137764dfbSMax Reitz static ImageInfoSpecific *qcow2_get_specific_info(BlockDriverState *bs)
290237764dfbSMax Reitz {
2903ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
290437764dfbSMax Reitz     ImageInfoSpecific *spec_info = g_new(ImageInfoSpecific, 1);
290537764dfbSMax Reitz 
290637764dfbSMax Reitz     *spec_info = (ImageInfoSpecific){
29076a8f9661SEric Blake         .type  = IMAGE_INFO_SPECIFIC_KIND_QCOW2,
290832bafa8fSEric Blake         .u.qcow2.data = g_new(ImageInfoSpecificQCow2, 1),
290937764dfbSMax Reitz     };
291037764dfbSMax Reitz     if (s->qcow_version == 2) {
291132bafa8fSEric Blake         *spec_info->u.qcow2.data = (ImageInfoSpecificQCow2){
291237764dfbSMax Reitz             .compat             = g_strdup("0.10"),
29130709c5a1SMax Reitz             .refcount_bits      = s->refcount_bits,
291437764dfbSMax Reitz         };
291537764dfbSMax Reitz     } else if (s->qcow_version == 3) {
291632bafa8fSEric Blake         *spec_info->u.qcow2.data = (ImageInfoSpecificQCow2){
291737764dfbSMax Reitz             .compat             = g_strdup("1.1"),
291837764dfbSMax Reitz             .lazy_refcounts     = s->compatible_features &
291937764dfbSMax Reitz                                   QCOW2_COMPAT_LAZY_REFCOUNTS,
292037764dfbSMax Reitz             .has_lazy_refcounts = true,
29219009b196SMax Reitz             .corrupt            = s->incompatible_features &
29229009b196SMax Reitz                                   QCOW2_INCOMPAT_CORRUPT,
29239009b196SMax Reitz             .has_corrupt        = true,
29240709c5a1SMax Reitz             .refcount_bits      = s->refcount_bits,
292537764dfbSMax Reitz         };
2926b1fc8f93SDenis V. Lunev     } else {
2927b1fc8f93SDenis V. Lunev         /* if this assertion fails, this probably means a new version was
2928b1fc8f93SDenis V. Lunev          * added without having it covered here */
2929b1fc8f93SDenis V. Lunev         assert(false);
293037764dfbSMax Reitz     }
293137764dfbSMax Reitz 
293237764dfbSMax Reitz     return spec_info;
293337764dfbSMax Reitz }
293437764dfbSMax Reitz 
293520d97356SBlue Swirl #if 0
293620d97356SBlue Swirl static void dump_refcounts(BlockDriverState *bs)
293720d97356SBlue Swirl {
2938ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
293920d97356SBlue Swirl     int64_t nb_clusters, k, k1, size;
294020d97356SBlue Swirl     int refcount;
294120d97356SBlue Swirl 
29429a4f4c31SKevin Wolf     size = bdrv_getlength(bs->file->bs);
294320d97356SBlue Swirl     nb_clusters = size_to_clusters(s, size);
294420d97356SBlue Swirl     for(k = 0; k < nb_clusters;) {
294520d97356SBlue Swirl         k1 = k;
294620d97356SBlue Swirl         refcount = get_refcount(bs, k);
294720d97356SBlue Swirl         k++;
294820d97356SBlue Swirl         while (k < nb_clusters && get_refcount(bs, k) == refcount)
294920d97356SBlue Swirl             k++;
29500bfcd599SBlue Swirl         printf("%" PRId64 ": refcount=%d nb=%" PRId64 "\n", k, refcount,
29510bfcd599SBlue Swirl                k - k1);
295220d97356SBlue Swirl     }
295320d97356SBlue Swirl }
295420d97356SBlue Swirl #endif
295520d97356SBlue Swirl 
2956cf8074b3SKevin Wolf static int qcow2_save_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
2957cf8074b3SKevin Wolf                               int64_t pos)
295820d97356SBlue Swirl {
2959ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
296020d97356SBlue Swirl 
296166f82ceeSKevin Wolf     BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_SAVE);
2962734a7758SKevin Wolf     return bs->drv->bdrv_co_pwritev(bs, qcow2_vm_state_offset(s) + pos,
2963734a7758SKevin Wolf                                     qiov->size, qiov, 0);
296420d97356SBlue Swirl }
296520d97356SBlue Swirl 
29665ddda0b8SKevin Wolf static int qcow2_load_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
29675ddda0b8SKevin Wolf                               int64_t pos)
296820d97356SBlue Swirl {
2969ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
297020d97356SBlue Swirl 
297166f82ceeSKevin Wolf     BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_LOAD);
2972734a7758SKevin Wolf     return bs->drv->bdrv_co_preadv(bs, qcow2_vm_state_offset(s) + pos,
2973734a7758SKevin Wolf                                    qiov->size, qiov, 0);
297420d97356SBlue Swirl }
297520d97356SBlue Swirl 
29769296b3edSMax Reitz /*
29779296b3edSMax Reitz  * Downgrades an image's version. To achieve this, any incompatible features
29789296b3edSMax Reitz  * have to be removed.
29799296b3edSMax Reitz  */
29804057a2b2SMax Reitz static int qcow2_downgrade(BlockDriverState *bs, int target_version,
29818b13976dSMax Reitz                            BlockDriverAmendStatusCB *status_cb, void *cb_opaque)
29829296b3edSMax Reitz {
2983ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
29849296b3edSMax Reitz     int current_version = s->qcow_version;
29859296b3edSMax Reitz     int ret;
29869296b3edSMax Reitz 
29879296b3edSMax Reitz     if (target_version == current_version) {
29889296b3edSMax Reitz         return 0;
29899296b3edSMax Reitz     } else if (target_version > current_version) {
29909296b3edSMax Reitz         return -EINVAL;
29919296b3edSMax Reitz     } else if (target_version != 2) {
29929296b3edSMax Reitz         return -EINVAL;
29939296b3edSMax Reitz     }
29949296b3edSMax Reitz 
29959296b3edSMax Reitz     if (s->refcount_order != 4) {
299661ce55fcSMax Reitz         error_report("compat=0.10 requires refcount_bits=16");
29979296b3edSMax Reitz         return -ENOTSUP;
29989296b3edSMax Reitz     }
29999296b3edSMax Reitz 
30009296b3edSMax Reitz     /* clear incompatible features */
30019296b3edSMax Reitz     if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
30029296b3edSMax Reitz         ret = qcow2_mark_clean(bs);
30039296b3edSMax Reitz         if (ret < 0) {
30049296b3edSMax Reitz             return ret;
30059296b3edSMax Reitz         }
30069296b3edSMax Reitz     }
30079296b3edSMax Reitz 
30089296b3edSMax Reitz     /* with QCOW2_INCOMPAT_CORRUPT, it is pretty much impossible to get here in
30099296b3edSMax Reitz      * the first place; if that happens nonetheless, returning -ENOTSUP is the
30109296b3edSMax Reitz      * best thing to do anyway */
30119296b3edSMax Reitz 
30129296b3edSMax Reitz     if (s->incompatible_features) {
30139296b3edSMax Reitz         return -ENOTSUP;
30149296b3edSMax Reitz     }
30159296b3edSMax Reitz 
30169296b3edSMax Reitz     /* since we can ignore compatible features, we can set them to 0 as well */
30179296b3edSMax Reitz     s->compatible_features = 0;
30189296b3edSMax Reitz     /* if lazy refcounts have been used, they have already been fixed through
30199296b3edSMax Reitz      * clearing the dirty flag */
30209296b3edSMax Reitz 
30219296b3edSMax Reitz     /* clearing autoclear features is trivial */
30229296b3edSMax Reitz     s->autoclear_features = 0;
30239296b3edSMax Reitz 
30248b13976dSMax Reitz     ret = qcow2_expand_zero_clusters(bs, status_cb, cb_opaque);
30259296b3edSMax Reitz     if (ret < 0) {
30269296b3edSMax Reitz         return ret;
30279296b3edSMax Reitz     }
30289296b3edSMax Reitz 
30299296b3edSMax Reitz     s->qcow_version = target_version;
30309296b3edSMax Reitz     ret = qcow2_update_header(bs);
30319296b3edSMax Reitz     if (ret < 0) {
30329296b3edSMax Reitz         s->qcow_version = current_version;
30339296b3edSMax Reitz         return ret;
30349296b3edSMax Reitz     }
30359296b3edSMax Reitz     return 0;
30369296b3edSMax Reitz }
30379296b3edSMax Reitz 
3038c293a809SMax Reitz typedef enum Qcow2AmendOperation {
3039c293a809SMax Reitz     /* This is the value Qcow2AmendHelperCBInfo::last_operation will be
3040c293a809SMax Reitz      * statically initialized to so that the helper CB can discern the first
3041c293a809SMax Reitz      * invocation from an operation change */
3042c293a809SMax Reitz     QCOW2_NO_OPERATION = 0,
3043c293a809SMax Reitz 
304461ce55fcSMax Reitz     QCOW2_CHANGING_REFCOUNT_ORDER,
3045c293a809SMax Reitz     QCOW2_DOWNGRADING,
3046c293a809SMax Reitz } Qcow2AmendOperation;
3047c293a809SMax Reitz 
3048c293a809SMax Reitz typedef struct Qcow2AmendHelperCBInfo {
3049c293a809SMax Reitz     /* The code coordinating the amend operations should only modify
3050c293a809SMax Reitz      * these four fields; the rest will be managed by the CB */
3051c293a809SMax Reitz     BlockDriverAmendStatusCB *original_status_cb;
3052c293a809SMax Reitz     void *original_cb_opaque;
3053c293a809SMax Reitz 
3054c293a809SMax Reitz     Qcow2AmendOperation current_operation;
3055c293a809SMax Reitz 
3056c293a809SMax Reitz     /* Total number of operations to perform (only set once) */
3057c293a809SMax Reitz     int total_operations;
3058c293a809SMax Reitz 
3059c293a809SMax Reitz     /* The following fields are managed by the CB */
3060c293a809SMax Reitz 
3061c293a809SMax Reitz     /* Number of operations completed */
3062c293a809SMax Reitz     int operations_completed;
3063c293a809SMax Reitz 
3064c293a809SMax Reitz     /* Cumulative offset of all completed operations */
3065c293a809SMax Reitz     int64_t offset_completed;
3066c293a809SMax Reitz 
3067c293a809SMax Reitz     Qcow2AmendOperation last_operation;
3068c293a809SMax Reitz     int64_t last_work_size;
3069c293a809SMax Reitz } Qcow2AmendHelperCBInfo;
3070c293a809SMax Reitz 
3071c293a809SMax Reitz static void qcow2_amend_helper_cb(BlockDriverState *bs,
3072c293a809SMax Reitz                                   int64_t operation_offset,
3073c293a809SMax Reitz                                   int64_t operation_work_size, void *opaque)
3074c293a809SMax Reitz {
3075c293a809SMax Reitz     Qcow2AmendHelperCBInfo *info = opaque;
3076c293a809SMax Reitz     int64_t current_work_size;
3077c293a809SMax Reitz     int64_t projected_work_size;
3078c293a809SMax Reitz 
3079c293a809SMax Reitz     if (info->current_operation != info->last_operation) {
3080c293a809SMax Reitz         if (info->last_operation != QCOW2_NO_OPERATION) {
3081c293a809SMax Reitz             info->offset_completed += info->last_work_size;
3082c293a809SMax Reitz             info->operations_completed++;
3083c293a809SMax Reitz         }
3084c293a809SMax Reitz 
3085c293a809SMax Reitz         info->last_operation = info->current_operation;
3086c293a809SMax Reitz     }
3087c293a809SMax Reitz 
3088c293a809SMax Reitz     assert(info->total_operations > 0);
3089c293a809SMax Reitz     assert(info->operations_completed < info->total_operations);
3090c293a809SMax Reitz 
3091c293a809SMax Reitz     info->last_work_size = operation_work_size;
3092c293a809SMax Reitz 
3093c293a809SMax Reitz     current_work_size = info->offset_completed + operation_work_size;
3094c293a809SMax Reitz 
3095c293a809SMax Reitz     /* current_work_size is the total work size for (operations_completed + 1)
3096c293a809SMax Reitz      * operations (which includes this one), so multiply it by the number of
3097c293a809SMax Reitz      * operations not covered and divide it by the number of operations
3098c293a809SMax Reitz      * covered to get a projection for the operations not covered */
3099c293a809SMax Reitz     projected_work_size = current_work_size * (info->total_operations -
3100c293a809SMax Reitz                                                info->operations_completed - 1)
3101c293a809SMax Reitz                                             / (info->operations_completed + 1);
3102c293a809SMax Reitz 
3103c293a809SMax Reitz     info->original_status_cb(bs, info->offset_completed + operation_offset,
3104c293a809SMax Reitz                              current_work_size + projected_work_size,
3105c293a809SMax Reitz                              info->original_cb_opaque);
3106c293a809SMax Reitz }
3107c293a809SMax Reitz 
310877485434SMax Reitz static int qcow2_amend_options(BlockDriverState *bs, QemuOpts *opts,
31098b13976dSMax Reitz                                BlockDriverAmendStatusCB *status_cb,
31108b13976dSMax Reitz                                void *cb_opaque)
31119296b3edSMax Reitz {
3112ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
31139296b3edSMax Reitz     int old_version = s->qcow_version, new_version = old_version;
31149296b3edSMax Reitz     uint64_t new_size = 0;
31159296b3edSMax Reitz     const char *backing_file = NULL, *backing_format = NULL;
31169296b3edSMax Reitz     bool lazy_refcounts = s->use_lazy_refcounts;
31171bd0e2d1SChunyan Liu     const char *compat = NULL;
31181bd0e2d1SChunyan Liu     uint64_t cluster_size = s->cluster_size;
31191bd0e2d1SChunyan Liu     bool encrypt;
312061ce55fcSMax Reitz     int refcount_bits = s->refcount_bits;
3121d7086422SKevin Wolf     Error *local_err = NULL;
31229296b3edSMax Reitz     int ret;
31231bd0e2d1SChunyan Liu     QemuOptDesc *desc = opts->list->desc;
3124c293a809SMax Reitz     Qcow2AmendHelperCBInfo helper_cb_info;
31259296b3edSMax Reitz 
31261bd0e2d1SChunyan Liu     while (desc && desc->name) {
31271bd0e2d1SChunyan Liu         if (!qemu_opt_find(opts, desc->name)) {
31289296b3edSMax Reitz             /* only change explicitly defined options */
31291bd0e2d1SChunyan Liu             desc++;
31309296b3edSMax Reitz             continue;
31319296b3edSMax Reitz         }
31329296b3edSMax Reitz 
31338a17b83cSMax Reitz         if (!strcmp(desc->name, BLOCK_OPT_COMPAT_LEVEL)) {
31348a17b83cSMax Reitz             compat = qemu_opt_get(opts, BLOCK_OPT_COMPAT_LEVEL);
31351bd0e2d1SChunyan Liu             if (!compat) {
31369296b3edSMax Reitz                 /* preserve default */
31371bd0e2d1SChunyan Liu             } else if (!strcmp(compat, "0.10")) {
31389296b3edSMax Reitz                 new_version = 2;
31391bd0e2d1SChunyan Liu             } else if (!strcmp(compat, "1.1")) {
31409296b3edSMax Reitz                 new_version = 3;
31419296b3edSMax Reitz             } else {
314229d72431SMax Reitz                 error_report("Unknown compatibility level %s", compat);
31439296b3edSMax Reitz                 return -EINVAL;
31449296b3edSMax Reitz             }
31458a17b83cSMax Reitz         } else if (!strcmp(desc->name, BLOCK_OPT_PREALLOC)) {
314629d72431SMax Reitz             error_report("Cannot change preallocation mode");
31479296b3edSMax Reitz             return -ENOTSUP;
31488a17b83cSMax Reitz         } else if (!strcmp(desc->name, BLOCK_OPT_SIZE)) {
31498a17b83cSMax Reitz             new_size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, 0);
31508a17b83cSMax Reitz         } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FILE)) {
31518a17b83cSMax Reitz             backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
31528a17b83cSMax Reitz         } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FMT)) {
31538a17b83cSMax Reitz             backing_format = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
31548a17b83cSMax Reitz         } else if (!strcmp(desc->name, BLOCK_OPT_ENCRYPT)) {
31558a17b83cSMax Reitz             encrypt = qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT,
3156f6fa64f6SDaniel P. Berrange                                         !!s->cipher);
3157f6fa64f6SDaniel P. Berrange 
3158f6fa64f6SDaniel P. Berrange             if (encrypt != !!s->cipher) {
315929d72431SMax Reitz                 error_report("Changing the encryption flag is not supported");
31609296b3edSMax Reitz                 return -ENOTSUP;
31619296b3edSMax Reitz             }
31628a17b83cSMax Reitz         } else if (!strcmp(desc->name, BLOCK_OPT_CLUSTER_SIZE)) {
31638a17b83cSMax Reitz             cluster_size = qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE,
31641bd0e2d1SChunyan Liu                                              cluster_size);
31651bd0e2d1SChunyan Liu             if (cluster_size != s->cluster_size) {
316629d72431SMax Reitz                 error_report("Changing the cluster size is not supported");
31679296b3edSMax Reitz                 return -ENOTSUP;
31689296b3edSMax Reitz             }
31698a17b83cSMax Reitz         } else if (!strcmp(desc->name, BLOCK_OPT_LAZY_REFCOUNTS)) {
31708a17b83cSMax Reitz             lazy_refcounts = qemu_opt_get_bool(opts, BLOCK_OPT_LAZY_REFCOUNTS,
31711bd0e2d1SChunyan Liu                                                lazy_refcounts);
317206d05fa7SMax Reitz         } else if (!strcmp(desc->name, BLOCK_OPT_REFCOUNT_BITS)) {
317361ce55fcSMax Reitz             refcount_bits = qemu_opt_get_number(opts, BLOCK_OPT_REFCOUNT_BITS,
317461ce55fcSMax Reitz                                                 refcount_bits);
317561ce55fcSMax Reitz 
317661ce55fcSMax Reitz             if (refcount_bits <= 0 || refcount_bits > 64 ||
317761ce55fcSMax Reitz                 !is_power_of_2(refcount_bits))
317861ce55fcSMax Reitz             {
317961ce55fcSMax Reitz                 error_report("Refcount width must be a power of two and may "
318061ce55fcSMax Reitz                              "not exceed 64 bits");
318161ce55fcSMax Reitz                 return -EINVAL;
318261ce55fcSMax Reitz             }
31839296b3edSMax Reitz         } else {
3184164e0f89SMax Reitz             /* if this point is reached, this probably means a new option was
31859296b3edSMax Reitz              * added without having it covered here */
3186164e0f89SMax Reitz             abort();
31879296b3edSMax Reitz         }
31881bd0e2d1SChunyan Liu 
31891bd0e2d1SChunyan Liu         desc++;
31909296b3edSMax Reitz     }
31919296b3edSMax Reitz 
3192c293a809SMax Reitz     helper_cb_info = (Qcow2AmendHelperCBInfo){
3193c293a809SMax Reitz         .original_status_cb = status_cb,
3194c293a809SMax Reitz         .original_cb_opaque = cb_opaque,
3195c293a809SMax Reitz         .total_operations = (new_version < old_version)
319661ce55fcSMax Reitz                           + (s->refcount_bits != refcount_bits)
3197c293a809SMax Reitz     };
3198c293a809SMax Reitz 
31991038bbb8SMax Reitz     /* Upgrade first (some features may require compat=1.1) */
32009296b3edSMax Reitz     if (new_version > old_version) {
32019296b3edSMax Reitz         s->qcow_version = new_version;
32029296b3edSMax Reitz         ret = qcow2_update_header(bs);
32039296b3edSMax Reitz         if (ret < 0) {
32049296b3edSMax Reitz             s->qcow_version = old_version;
32059296b3edSMax Reitz             return ret;
32069296b3edSMax Reitz         }
32079296b3edSMax Reitz     }
32089296b3edSMax Reitz 
320961ce55fcSMax Reitz     if (s->refcount_bits != refcount_bits) {
321061ce55fcSMax Reitz         int refcount_order = ctz32(refcount_bits);
321161ce55fcSMax Reitz         Error *local_error = NULL;
321261ce55fcSMax Reitz 
321361ce55fcSMax Reitz         if (new_version < 3 && refcount_bits != 16) {
321461ce55fcSMax Reitz             error_report("Different refcount widths than 16 bits require "
321561ce55fcSMax Reitz                          "compatibility level 1.1 or above (use compat=1.1 or "
321661ce55fcSMax Reitz                          "greater)");
321761ce55fcSMax Reitz             return -EINVAL;
321861ce55fcSMax Reitz         }
321961ce55fcSMax Reitz 
322061ce55fcSMax Reitz         helper_cb_info.current_operation = QCOW2_CHANGING_REFCOUNT_ORDER;
322161ce55fcSMax Reitz         ret = qcow2_change_refcount_order(bs, refcount_order,
322261ce55fcSMax Reitz                                           &qcow2_amend_helper_cb,
322361ce55fcSMax Reitz                                           &helper_cb_info, &local_error);
322461ce55fcSMax Reitz         if (ret < 0) {
322561ce55fcSMax Reitz             error_report_err(local_error);
322661ce55fcSMax Reitz             return ret;
322761ce55fcSMax Reitz         }
322861ce55fcSMax Reitz     }
322961ce55fcSMax Reitz 
32309296b3edSMax Reitz     if (backing_file || backing_format) {
3231e4603fe1SKevin Wolf         ret = qcow2_change_backing_file(bs,
3232e4603fe1SKevin Wolf                     backing_file ?: s->image_backing_file,
3233e4603fe1SKevin Wolf                     backing_format ?: s->image_backing_format);
32349296b3edSMax Reitz         if (ret < 0) {
32359296b3edSMax Reitz             return ret;
32369296b3edSMax Reitz         }
32379296b3edSMax Reitz     }
32389296b3edSMax Reitz 
32399296b3edSMax Reitz     if (s->use_lazy_refcounts != lazy_refcounts) {
32409296b3edSMax Reitz         if (lazy_refcounts) {
32411038bbb8SMax Reitz             if (new_version < 3) {
324229d72431SMax Reitz                 error_report("Lazy refcounts only supported with compatibility "
324329d72431SMax Reitz                              "level 1.1 and above (use compat=1.1 or greater)");
32449296b3edSMax Reitz                 return -EINVAL;
32459296b3edSMax Reitz             }
32469296b3edSMax Reitz             s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
32479296b3edSMax Reitz             ret = qcow2_update_header(bs);
32489296b3edSMax Reitz             if (ret < 0) {
32499296b3edSMax Reitz                 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
32509296b3edSMax Reitz                 return ret;
32519296b3edSMax Reitz             }
32529296b3edSMax Reitz             s->use_lazy_refcounts = true;
32539296b3edSMax Reitz         } else {
32549296b3edSMax Reitz             /* make image clean first */
32559296b3edSMax Reitz             ret = qcow2_mark_clean(bs);
32569296b3edSMax Reitz             if (ret < 0) {
32579296b3edSMax Reitz                 return ret;
32589296b3edSMax Reitz             }
32599296b3edSMax Reitz             /* now disallow lazy refcounts */
32609296b3edSMax Reitz             s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
32619296b3edSMax Reitz             ret = qcow2_update_header(bs);
32629296b3edSMax Reitz             if (ret < 0) {
32639296b3edSMax Reitz                 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
32649296b3edSMax Reitz                 return ret;
32659296b3edSMax Reitz             }
32669296b3edSMax Reitz             s->use_lazy_refcounts = false;
32679296b3edSMax Reitz         }
32689296b3edSMax Reitz     }
32699296b3edSMax Reitz 
32709296b3edSMax Reitz     if (new_size) {
32716d0eb64dSKevin Wolf         BlockBackend *blk = blk_new(BLK_PERM_RESIZE, BLK_PERM_ALL);
3272d7086422SKevin Wolf         ret = blk_insert_bs(blk, bs, &local_err);
3273d7086422SKevin Wolf         if (ret < 0) {
3274d7086422SKevin Wolf             error_report_err(local_err);
3275d7086422SKevin Wolf             blk_unref(blk);
3276d7086422SKevin Wolf             return ret;
3277d7086422SKevin Wolf         }
3278d7086422SKevin Wolf 
3279ed3d2ec9SMax Reitz         ret = blk_truncate(blk, new_size, &local_err);
328070b27f36SKevin Wolf         blk_unref(blk);
32819296b3edSMax Reitz         if (ret < 0) {
3282ed3d2ec9SMax Reitz             error_report_err(local_err);
32839296b3edSMax Reitz             return ret;
32849296b3edSMax Reitz         }
32859296b3edSMax Reitz     }
32869296b3edSMax Reitz 
32871038bbb8SMax Reitz     /* Downgrade last (so unsupported features can be removed before) */
32881038bbb8SMax Reitz     if (new_version < old_version) {
3289c293a809SMax Reitz         helper_cb_info.current_operation = QCOW2_DOWNGRADING;
3290c293a809SMax Reitz         ret = qcow2_downgrade(bs, new_version, &qcow2_amend_helper_cb,
3291c293a809SMax Reitz                               &helper_cb_info);
32921038bbb8SMax Reitz         if (ret < 0) {
32931038bbb8SMax Reitz             return ret;
32941038bbb8SMax Reitz         }
32951038bbb8SMax Reitz     }
32961038bbb8SMax Reitz 
32979296b3edSMax Reitz     return 0;
32989296b3edSMax Reitz }
32999296b3edSMax Reitz 
330085186ebdSMax Reitz /*
330185186ebdSMax Reitz  * If offset or size are negative, respectively, they will not be included in
330285186ebdSMax Reitz  * the BLOCK_IMAGE_CORRUPTED event emitted.
330385186ebdSMax Reitz  * fatal will be ignored for read-only BDS; corruptions found there will always
330485186ebdSMax Reitz  * be considered non-fatal.
330585186ebdSMax Reitz  */
330685186ebdSMax Reitz void qcow2_signal_corruption(BlockDriverState *bs, bool fatal, int64_t offset,
330785186ebdSMax Reitz                              int64_t size, const char *message_format, ...)
330885186ebdSMax Reitz {
3309ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
3310dc881b44SAlberto Garcia     const char *node_name;
331185186ebdSMax Reitz     char *message;
331285186ebdSMax Reitz     va_list ap;
331385186ebdSMax Reitz 
331485186ebdSMax Reitz     fatal = fatal && !bs->read_only;
331585186ebdSMax Reitz 
331685186ebdSMax Reitz     if (s->signaled_corruption &&
331785186ebdSMax Reitz         (!fatal || (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT)))
331885186ebdSMax Reitz     {
331985186ebdSMax Reitz         return;
332085186ebdSMax Reitz     }
332185186ebdSMax Reitz 
332285186ebdSMax Reitz     va_start(ap, message_format);
332385186ebdSMax Reitz     message = g_strdup_vprintf(message_format, ap);
332485186ebdSMax Reitz     va_end(ap);
332585186ebdSMax Reitz 
332685186ebdSMax Reitz     if (fatal) {
332785186ebdSMax Reitz         fprintf(stderr, "qcow2: Marking image as corrupt: %s; further "
332885186ebdSMax Reitz                 "corruption events will be suppressed\n", message);
332985186ebdSMax Reitz     } else {
333085186ebdSMax Reitz         fprintf(stderr, "qcow2: Image is corrupt: %s; further non-fatal "
333185186ebdSMax Reitz                 "corruption events will be suppressed\n", message);
333285186ebdSMax Reitz     }
333385186ebdSMax Reitz 
3334dc881b44SAlberto Garcia     node_name = bdrv_get_node_name(bs);
3335dc881b44SAlberto Garcia     qapi_event_send_block_image_corrupted(bdrv_get_device_name(bs),
3336dc881b44SAlberto Garcia                                           *node_name != '\0', node_name,
3337dc881b44SAlberto Garcia                                           message, offset >= 0, offset,
3338dc881b44SAlberto Garcia                                           size >= 0, size,
333985186ebdSMax Reitz                                           fatal, &error_abort);
334085186ebdSMax Reitz     g_free(message);
334185186ebdSMax Reitz 
334285186ebdSMax Reitz     if (fatal) {
334385186ebdSMax Reitz         qcow2_mark_corrupt(bs);
334485186ebdSMax Reitz         bs->drv = NULL; /* make BDS unusable */
334585186ebdSMax Reitz     }
334685186ebdSMax Reitz 
334785186ebdSMax Reitz     s->signaled_corruption = true;
334885186ebdSMax Reitz }
334985186ebdSMax Reitz 
33501bd0e2d1SChunyan Liu static QemuOptsList qcow2_create_opts = {
33511bd0e2d1SChunyan Liu     .name = "qcow2-create-opts",
33521bd0e2d1SChunyan Liu     .head = QTAILQ_HEAD_INITIALIZER(qcow2_create_opts.head),
33531bd0e2d1SChunyan Liu     .desc = {
335420d97356SBlue Swirl         {
335520d97356SBlue Swirl             .name = BLOCK_OPT_SIZE,
33561bd0e2d1SChunyan Liu             .type = QEMU_OPT_SIZE,
335720d97356SBlue Swirl             .help = "Virtual disk size"
335820d97356SBlue Swirl         },
335920d97356SBlue Swirl         {
33606744cbabSKevin Wolf             .name = BLOCK_OPT_COMPAT_LEVEL,
33611bd0e2d1SChunyan Liu             .type = QEMU_OPT_STRING,
33626744cbabSKevin Wolf             .help = "Compatibility level (0.10 or 1.1)"
33636744cbabSKevin Wolf         },
33646744cbabSKevin Wolf         {
336520d97356SBlue Swirl             .name = BLOCK_OPT_BACKING_FILE,
33661bd0e2d1SChunyan Liu             .type = QEMU_OPT_STRING,
336720d97356SBlue Swirl             .help = "File name of a base image"
336820d97356SBlue Swirl         },
336920d97356SBlue Swirl         {
337020d97356SBlue Swirl             .name = BLOCK_OPT_BACKING_FMT,
33711bd0e2d1SChunyan Liu             .type = QEMU_OPT_STRING,
337220d97356SBlue Swirl             .help = "Image format of the base image"
337320d97356SBlue Swirl         },
337420d97356SBlue Swirl         {
337520d97356SBlue Swirl             .name = BLOCK_OPT_ENCRYPT,
33761bd0e2d1SChunyan Liu             .type = QEMU_OPT_BOOL,
33771bd0e2d1SChunyan Liu             .help = "Encrypt the image",
33781bd0e2d1SChunyan Liu             .def_value_str = "off"
337920d97356SBlue Swirl         },
338020d97356SBlue Swirl         {
338120d97356SBlue Swirl             .name = BLOCK_OPT_CLUSTER_SIZE,
33821bd0e2d1SChunyan Liu             .type = QEMU_OPT_SIZE,
338399cce9faSKevin Wolf             .help = "qcow2 cluster size",
33841bd0e2d1SChunyan Liu             .def_value_str = stringify(DEFAULT_CLUSTER_SIZE)
338520d97356SBlue Swirl         },
338620d97356SBlue Swirl         {
338720d97356SBlue Swirl             .name = BLOCK_OPT_PREALLOC,
33881bd0e2d1SChunyan Liu             .type = QEMU_OPT_STRING,
33890e4271b7SHu Tao             .help = "Preallocation mode (allowed values: off, metadata, "
33900e4271b7SHu Tao                     "falloc, full)"
339120d97356SBlue Swirl         },
3392bfe8043eSStefan Hajnoczi         {
3393bfe8043eSStefan Hajnoczi             .name = BLOCK_OPT_LAZY_REFCOUNTS,
33941bd0e2d1SChunyan Liu             .type = QEMU_OPT_BOOL,
3395bfe8043eSStefan Hajnoczi             .help = "Postpone refcount updates",
33961bd0e2d1SChunyan Liu             .def_value_str = "off"
3397bfe8043eSStefan Hajnoczi         },
339806d05fa7SMax Reitz         {
339906d05fa7SMax Reitz             .name = BLOCK_OPT_REFCOUNT_BITS,
340006d05fa7SMax Reitz             .type = QEMU_OPT_NUMBER,
340106d05fa7SMax Reitz             .help = "Width of a reference count entry in bits",
340206d05fa7SMax Reitz             .def_value_str = "16"
340306d05fa7SMax Reitz         },
34041bd0e2d1SChunyan Liu         { /* end of list */ }
34051bd0e2d1SChunyan Liu     }
340620d97356SBlue Swirl };
340720d97356SBlue Swirl 
34085f535a94SMax Reitz BlockDriver bdrv_qcow2 = {
340920d97356SBlue Swirl     .format_name        = "qcow2",
3410ff99129aSKevin Wolf     .instance_size      = sizeof(BDRVQcow2State),
34117c80ab3fSJes Sorensen     .bdrv_probe         = qcow2_probe,
34127c80ab3fSJes Sorensen     .bdrv_open          = qcow2_open,
34137c80ab3fSJes Sorensen     .bdrv_close         = qcow2_close,
341421d82ac9SJeff Cody     .bdrv_reopen_prepare  = qcow2_reopen_prepare,
34155b0959a7SKevin Wolf     .bdrv_reopen_commit   = qcow2_reopen_commit,
34165b0959a7SKevin Wolf     .bdrv_reopen_abort    = qcow2_reopen_abort,
34175365f44dSKevin Wolf     .bdrv_join_options    = qcow2_join_options,
3418862f215fSKevin Wolf     .bdrv_child_perm      = bdrv_format_default_perms,
3419c282e1fdSChunyan Liu     .bdrv_create        = qcow2_create,
34203ac21627SPeter Lieven     .bdrv_has_zero_init = bdrv_has_zero_init_1,
3421b6b8a333SPaolo Bonzini     .bdrv_co_get_block_status = qcow2_co_get_block_status,
34227c80ab3fSJes Sorensen     .bdrv_set_key       = qcow2_set_key,
342320d97356SBlue Swirl 
3424ecfe1863SKevin Wolf     .bdrv_co_preadv         = qcow2_co_preadv,
3425d46a0bb2SKevin Wolf     .bdrv_co_pwritev        = qcow2_co_pwritev,
3426eb489bb1SKevin Wolf     .bdrv_co_flush_to_os    = qcow2_co_flush_to_os,
3427419b19d9SStefan Hajnoczi 
34285544b59fSEric Blake     .bdrv_co_pwrite_zeroes  = qcow2_co_pwrite_zeroes,
342982e8a788SEric Blake     .bdrv_co_pdiscard       = qcow2_co_pdiscard,
3430419b19d9SStefan Hajnoczi     .bdrv_truncate          = qcow2_truncate,
3431fcccefc5SPavel Butsykin     .bdrv_co_pwritev_compressed = qcow2_co_pwritev_compressed,
3432491d27e2SMax Reitz     .bdrv_make_empty        = qcow2_make_empty,
343320d97356SBlue Swirl 
343420d97356SBlue Swirl     .bdrv_snapshot_create   = qcow2_snapshot_create,
343520d97356SBlue Swirl     .bdrv_snapshot_goto     = qcow2_snapshot_goto,
343620d97356SBlue Swirl     .bdrv_snapshot_delete   = qcow2_snapshot_delete,
343720d97356SBlue Swirl     .bdrv_snapshot_list     = qcow2_snapshot_list,
343851ef6727Sedison     .bdrv_snapshot_load_tmp = qcow2_snapshot_load_tmp,
34397c80ab3fSJes Sorensen     .bdrv_get_info          = qcow2_get_info,
344037764dfbSMax Reitz     .bdrv_get_specific_info = qcow2_get_specific_info,
344120d97356SBlue Swirl 
34427c80ab3fSJes Sorensen     .bdrv_save_vmstate    = qcow2_save_vmstate,
34437c80ab3fSJes Sorensen     .bdrv_load_vmstate    = qcow2_load_vmstate,
344420d97356SBlue Swirl 
34458ee79e70SKevin Wolf     .supports_backing           = true,
344620d97356SBlue Swirl     .bdrv_change_backing_file   = qcow2_change_backing_file,
344720d97356SBlue Swirl 
3448d34682cdSKevin Wolf     .bdrv_refresh_limits        = qcow2_refresh_limits,
344906d9260fSAnthony Liguori     .bdrv_invalidate_cache      = qcow2_invalidate_cache,
3450ec6d8912SKevin Wolf     .bdrv_inactivate            = qcow2_inactivate,
345106d9260fSAnthony Liguori 
34521bd0e2d1SChunyan Liu     .create_opts         = &qcow2_create_opts,
34537c80ab3fSJes Sorensen     .bdrv_check          = qcow2_check,
3454c282e1fdSChunyan Liu     .bdrv_amend_options  = qcow2_amend_options,
3455279621c0SAlberto Garcia 
3456279621c0SAlberto Garcia     .bdrv_detach_aio_context  = qcow2_detach_aio_context,
3457279621c0SAlberto Garcia     .bdrv_attach_aio_context  = qcow2_attach_aio_context,
345820d97356SBlue Swirl };
345920d97356SBlue Swirl 
34605efa9d5aSAnthony Liguori static void bdrv_qcow2_init(void)
34615efa9d5aSAnthony Liguori {
34625efa9d5aSAnthony Liguori     bdrv_register(&bdrv_qcow2);
34635efa9d5aSAnthony Liguori }
34645efa9d5aSAnthony Liguori 
34655efa9d5aSAnthony Liguori block_init(bdrv_qcow2_init);
3466