xref: /qemu/block/qcow2.c (revision d46a0bb24d6061c1eadcf1136fa73dc7c4ac267d)
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 
1109a4f4c31SKevin Wolf         ret = bdrv_pread(bs->file->bs, 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             }
1389a4f4c31SKevin Wolf             ret = bdrv_pread(bs->file->bs, 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));
1549a4f4c31SKevin Wolf                 ret = bdrv_pread(bs->file->bs, 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 
1759a4f4c31SKevin Wolf                 ret = bdrv_pread(bs->file->bs, 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);
2529a4f4c31SKevin Wolf     ret = bdrv_pwrite(bs->file->bs, 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);
671ee55b173SKevin Wolf     if (r->cache_clean_interval > UINT_MAX) {
67294edf3fbSKevin Wolf         error_setg(errp, "Cache clean interval too big");
67394edf3fbSKevin Wolf         ret = -EINVAL;
67494edf3fbSKevin Wolf         goto fail;
67594edf3fbSKevin Wolf     }
67694edf3fbSKevin Wolf 
6775b0959a7SKevin Wolf     /* lazy-refcounts; flush if going from enabled to disabled */
678ee55b173SKevin Wolf     r->use_lazy_refcounts = qemu_opt_get_bool(opts, QCOW2_OPT_LAZY_REFCOUNTS,
6794c75d1a1SKevin Wolf         (s->compatible_features & QCOW2_COMPAT_LAZY_REFCOUNTS));
680ee55b173SKevin Wolf     if (r->use_lazy_refcounts && s->qcow_version < 3) {
681007dbc39SKevin Wolf         error_setg(errp, "Lazy refcounts require a qcow2 image with at least "
682007dbc39SKevin Wolf                    "qemu 1.1 compatibility level");
683007dbc39SKevin Wolf         ret = -EINVAL;
684007dbc39SKevin Wolf         goto fail;
685007dbc39SKevin Wolf     }
6864c75d1a1SKevin Wolf 
6875b0959a7SKevin Wolf     if (s->use_lazy_refcounts && !r->use_lazy_refcounts) {
6885b0959a7SKevin Wolf         ret = qcow2_mark_clean(bs);
6895b0959a7SKevin Wolf         if (ret < 0) {
6905b0959a7SKevin Wolf             error_setg_errno(errp, -ret, "Failed to disable lazy refcounts");
6915b0959a7SKevin Wolf             goto fail;
6925b0959a7SKevin Wolf         }
6935b0959a7SKevin Wolf     }
6945b0959a7SKevin Wolf 
695007dbc39SKevin Wolf     /* Overlap check options */
6964c75d1a1SKevin Wolf     opt_overlap_check = qemu_opt_get(opts, QCOW2_OPT_OVERLAP);
6974c75d1a1SKevin Wolf     opt_overlap_check_template = qemu_opt_get(opts, QCOW2_OPT_OVERLAP_TEMPLATE);
6984c75d1a1SKevin Wolf     if (opt_overlap_check_template && opt_overlap_check &&
6994c75d1a1SKevin Wolf         strcmp(opt_overlap_check_template, opt_overlap_check))
7004c75d1a1SKevin Wolf     {
7014c75d1a1SKevin Wolf         error_setg(errp, "Conflicting values for qcow2 options '"
7024c75d1a1SKevin Wolf                    QCOW2_OPT_OVERLAP "' ('%s') and '" QCOW2_OPT_OVERLAP_TEMPLATE
7034c75d1a1SKevin Wolf                    "' ('%s')", opt_overlap_check, opt_overlap_check_template);
7044c75d1a1SKevin Wolf         ret = -EINVAL;
7054c75d1a1SKevin Wolf         goto fail;
7064c75d1a1SKevin Wolf     }
7074c75d1a1SKevin Wolf     if (!opt_overlap_check) {
7084c75d1a1SKevin Wolf         opt_overlap_check = opt_overlap_check_template ?: "cached";
7094c75d1a1SKevin Wolf     }
7104c75d1a1SKevin Wolf 
7114c75d1a1SKevin Wolf     if (!strcmp(opt_overlap_check, "none")) {
7124c75d1a1SKevin Wolf         overlap_check_template = 0;
7134c75d1a1SKevin Wolf     } else if (!strcmp(opt_overlap_check, "constant")) {
7144c75d1a1SKevin Wolf         overlap_check_template = QCOW2_OL_CONSTANT;
7154c75d1a1SKevin Wolf     } else if (!strcmp(opt_overlap_check, "cached")) {
7164c75d1a1SKevin Wolf         overlap_check_template = QCOW2_OL_CACHED;
7174c75d1a1SKevin Wolf     } else if (!strcmp(opt_overlap_check, "all")) {
7184c75d1a1SKevin Wolf         overlap_check_template = QCOW2_OL_ALL;
7194c75d1a1SKevin Wolf     } else {
7204c75d1a1SKevin Wolf         error_setg(errp, "Unsupported value '%s' for qcow2 option "
7214c75d1a1SKevin Wolf                    "'overlap-check'. Allowed are any of the following: "
7224c75d1a1SKevin Wolf                    "none, constant, cached, all", opt_overlap_check);
7234c75d1a1SKevin Wolf         ret = -EINVAL;
7244c75d1a1SKevin Wolf         goto fail;
7254c75d1a1SKevin Wolf     }
7264c75d1a1SKevin Wolf 
727ee55b173SKevin Wolf     r->overlap_check = 0;
7284c75d1a1SKevin Wolf     for (i = 0; i < QCOW2_OL_MAX_BITNR; i++) {
7294c75d1a1SKevin Wolf         /* overlap-check defines a template bitmask, but every flag may be
7304c75d1a1SKevin Wolf          * overwritten through the associated boolean option */
731ee55b173SKevin Wolf         r->overlap_check |=
7324c75d1a1SKevin Wolf             qemu_opt_get_bool(opts, overlap_bool_option_names[i],
7334c75d1a1SKevin Wolf                               overlap_check_template & (1 << i)) << i;
7344c75d1a1SKevin Wolf     }
7354c75d1a1SKevin Wolf 
736ee55b173SKevin Wolf     r->discard_passthrough[QCOW2_DISCARD_NEVER] = false;
737ee55b173SKevin Wolf     r->discard_passthrough[QCOW2_DISCARD_ALWAYS] = true;
738ee55b173SKevin Wolf     r->discard_passthrough[QCOW2_DISCARD_REQUEST] =
739007dbc39SKevin Wolf         qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_REQUEST,
740007dbc39SKevin Wolf                           flags & BDRV_O_UNMAP);
741ee55b173SKevin Wolf     r->discard_passthrough[QCOW2_DISCARD_SNAPSHOT] =
742007dbc39SKevin Wolf         qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_SNAPSHOT, true);
743ee55b173SKevin Wolf     r->discard_passthrough[QCOW2_DISCARD_OTHER] =
744007dbc39SKevin Wolf         qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_OTHER, false);
745007dbc39SKevin Wolf 
7464c75d1a1SKevin Wolf     ret = 0;
7474c75d1a1SKevin Wolf fail:
74894edf3fbSKevin Wolf     qemu_opts_del(opts);
74994edf3fbSKevin Wolf     opts = NULL;
750ee55b173SKevin Wolf     return ret;
751ee55b173SKevin Wolf }
752ee55b173SKevin Wolf 
753ee55b173SKevin Wolf static void qcow2_update_options_commit(BlockDriverState *bs,
754ee55b173SKevin Wolf                                         Qcow2ReopenState *r)
755ee55b173SKevin Wolf {
756ee55b173SKevin Wolf     BDRVQcow2State *s = bs->opaque;
757ee55b173SKevin Wolf     int i;
758ee55b173SKevin Wolf 
7595b0959a7SKevin Wolf     if (s->l2_table_cache) {
7605b0959a7SKevin Wolf         qcow2_cache_destroy(bs, s->l2_table_cache);
7615b0959a7SKevin Wolf     }
7625b0959a7SKevin Wolf     if (s->refcount_block_cache) {
7635b0959a7SKevin Wolf         qcow2_cache_destroy(bs, s->refcount_block_cache);
7645b0959a7SKevin Wolf     }
765ee55b173SKevin Wolf     s->l2_table_cache = r->l2_table_cache;
766ee55b173SKevin Wolf     s->refcount_block_cache = r->refcount_block_cache;
767ee55b173SKevin Wolf 
768ee55b173SKevin Wolf     s->overlap_check = r->overlap_check;
769ee55b173SKevin Wolf     s->use_lazy_refcounts = r->use_lazy_refcounts;
770ee55b173SKevin Wolf 
771ee55b173SKevin Wolf     for (i = 0; i < QCOW2_DISCARD_MAX; i++) {
772ee55b173SKevin Wolf         s->discard_passthrough[i] = r->discard_passthrough[i];
773ee55b173SKevin Wolf     }
774ee55b173SKevin Wolf 
7755b0959a7SKevin Wolf     if (s->cache_clean_interval != r->cache_clean_interval) {
7765b0959a7SKevin Wolf         cache_clean_timer_del(bs);
777ee55b173SKevin Wolf         s->cache_clean_interval = r->cache_clean_interval;
778ee55b173SKevin Wolf         cache_clean_timer_init(bs, bdrv_get_aio_context(bs));
779ee55b173SKevin Wolf     }
7805b0959a7SKevin Wolf }
781ee55b173SKevin Wolf 
782ee55b173SKevin Wolf static void qcow2_update_options_abort(BlockDriverState *bs,
783ee55b173SKevin Wolf                                        Qcow2ReopenState *r)
784ee55b173SKevin Wolf {
785ee55b173SKevin Wolf     if (r->l2_table_cache) {
786ee55b173SKevin Wolf         qcow2_cache_destroy(bs, r->l2_table_cache);
787ee55b173SKevin Wolf     }
788ee55b173SKevin Wolf     if (r->refcount_block_cache) {
789ee55b173SKevin Wolf         qcow2_cache_destroy(bs, r->refcount_block_cache);
790ee55b173SKevin Wolf     }
791ee55b173SKevin Wolf }
792ee55b173SKevin Wolf 
793ee55b173SKevin Wolf static int qcow2_update_options(BlockDriverState *bs, QDict *options,
794ee55b173SKevin Wolf                                 int flags, Error **errp)
795ee55b173SKevin Wolf {
796ee55b173SKevin Wolf     Qcow2ReopenState r = {};
797ee55b173SKevin Wolf     int ret;
798ee55b173SKevin Wolf 
799ee55b173SKevin Wolf     ret = qcow2_update_options_prepare(bs, &r, options, flags, errp);
800ee55b173SKevin Wolf     if (ret >= 0) {
801ee55b173SKevin Wolf         qcow2_update_options_commit(bs, &r);
802ee55b173SKevin Wolf     } else {
803ee55b173SKevin Wolf         qcow2_update_options_abort(bs, &r);
804ee55b173SKevin Wolf     }
80594edf3fbSKevin Wolf 
8064c75d1a1SKevin Wolf     return ret;
8074c75d1a1SKevin Wolf }
8084c75d1a1SKevin Wolf 
809015a1036SMax Reitz static int qcow2_open(BlockDriverState *bs, QDict *options, int flags,
810015a1036SMax Reitz                       Error **errp)
811585f8587Sbellard {
812ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
8136d33e8e7SKevin Wolf     unsigned int len, i;
8146d33e8e7SKevin Wolf     int ret = 0;
815585f8587Sbellard     QCowHeader header;
81674c4510aSKevin Wolf     Error *local_err = NULL;
8179b80ddf3Saliguori     uint64_t ext_end;
8182cf7cfa1SKevin Wolf     uint64_t l1_vm_state_index;
819585f8587Sbellard 
8209a4f4c31SKevin Wolf     ret = bdrv_pread(bs->file->bs, 0, &header, sizeof(header));
8216d85a57eSJes Sorensen     if (ret < 0) {
8223ef6c40aSMax Reitz         error_setg_errno(errp, -ret, "Could not read qcow2 header");
823585f8587Sbellard         goto fail;
8246d85a57eSJes Sorensen     }
825585f8587Sbellard     be32_to_cpus(&header.magic);
826585f8587Sbellard     be32_to_cpus(&header.version);
827585f8587Sbellard     be64_to_cpus(&header.backing_file_offset);
828585f8587Sbellard     be32_to_cpus(&header.backing_file_size);
829585f8587Sbellard     be64_to_cpus(&header.size);
830585f8587Sbellard     be32_to_cpus(&header.cluster_bits);
831585f8587Sbellard     be32_to_cpus(&header.crypt_method);
832585f8587Sbellard     be64_to_cpus(&header.l1_table_offset);
833585f8587Sbellard     be32_to_cpus(&header.l1_size);
834585f8587Sbellard     be64_to_cpus(&header.refcount_table_offset);
835585f8587Sbellard     be32_to_cpus(&header.refcount_table_clusters);
836585f8587Sbellard     be64_to_cpus(&header.snapshots_offset);
837585f8587Sbellard     be32_to_cpus(&header.nb_snapshots);
838585f8587Sbellard 
839e8cdcec1SKevin Wolf     if (header.magic != QCOW_MAGIC) {
8403ef6c40aSMax Reitz         error_setg(errp, "Image is not in qcow2 format");
84176abe407SPaolo Bonzini         ret = -EINVAL;
842585f8587Sbellard         goto fail;
8436d85a57eSJes Sorensen     }
8446744cbabSKevin Wolf     if (header.version < 2 || header.version > 3) {
845a55448b3SMax Reitz         error_setg(errp, "Unsupported qcow2 version %" PRIu32, header.version);
846e8cdcec1SKevin Wolf         ret = -ENOTSUP;
847e8cdcec1SKevin Wolf         goto fail;
848e8cdcec1SKevin Wolf     }
8496744cbabSKevin Wolf 
8506744cbabSKevin Wolf     s->qcow_version = header.version;
8516744cbabSKevin Wolf 
85224342f2cSKevin Wolf     /* Initialise cluster size */
85324342f2cSKevin Wolf     if (header.cluster_bits < MIN_CLUSTER_BITS ||
85424342f2cSKevin Wolf         header.cluster_bits > MAX_CLUSTER_BITS) {
855521b2b5dSMax Reitz         error_setg(errp, "Unsupported cluster size: 2^%" PRIu32,
856521b2b5dSMax Reitz                    header.cluster_bits);
85724342f2cSKevin Wolf         ret = -EINVAL;
85824342f2cSKevin Wolf         goto fail;
85924342f2cSKevin Wolf     }
86024342f2cSKevin Wolf 
86124342f2cSKevin Wolf     s->cluster_bits = header.cluster_bits;
86224342f2cSKevin Wolf     s->cluster_size = 1 << s->cluster_bits;
86324342f2cSKevin Wolf     s->cluster_sectors = 1 << (s->cluster_bits - 9);
86424342f2cSKevin Wolf 
8656744cbabSKevin Wolf     /* Initialise version 3 header fields */
8666744cbabSKevin Wolf     if (header.version == 2) {
8676744cbabSKevin Wolf         header.incompatible_features    = 0;
8686744cbabSKevin Wolf         header.compatible_features      = 0;
8696744cbabSKevin Wolf         header.autoclear_features       = 0;
8706744cbabSKevin Wolf         header.refcount_order           = 4;
8716744cbabSKevin Wolf         header.header_length            = 72;
8726744cbabSKevin Wolf     } else {
8736744cbabSKevin Wolf         be64_to_cpus(&header.incompatible_features);
8746744cbabSKevin Wolf         be64_to_cpus(&header.compatible_features);
8756744cbabSKevin Wolf         be64_to_cpus(&header.autoclear_features);
8766744cbabSKevin Wolf         be32_to_cpus(&header.refcount_order);
8776744cbabSKevin Wolf         be32_to_cpus(&header.header_length);
87824342f2cSKevin Wolf 
87924342f2cSKevin Wolf         if (header.header_length < 104) {
88024342f2cSKevin Wolf             error_setg(errp, "qcow2 header too short");
88124342f2cSKevin Wolf             ret = -EINVAL;
88224342f2cSKevin Wolf             goto fail;
88324342f2cSKevin Wolf         }
88424342f2cSKevin Wolf     }
88524342f2cSKevin Wolf 
88624342f2cSKevin Wolf     if (header.header_length > s->cluster_size) {
88724342f2cSKevin Wolf         error_setg(errp, "qcow2 header exceeds cluster size");
88824342f2cSKevin Wolf         ret = -EINVAL;
88924342f2cSKevin Wolf         goto fail;
8906744cbabSKevin Wolf     }
8916744cbabSKevin Wolf 
8926744cbabSKevin Wolf     if (header.header_length > sizeof(header)) {
8936744cbabSKevin Wolf         s->unknown_header_fields_size = header.header_length - sizeof(header);
8946744cbabSKevin Wolf         s->unknown_header_fields = g_malloc(s->unknown_header_fields_size);
8959a4f4c31SKevin Wolf         ret = bdrv_pread(bs->file->bs, sizeof(header), s->unknown_header_fields,
8966744cbabSKevin Wolf                          s->unknown_header_fields_size);
8976744cbabSKevin Wolf         if (ret < 0) {
8983ef6c40aSMax Reitz             error_setg_errno(errp, -ret, "Could not read unknown qcow2 header "
8993ef6c40aSMax Reitz                              "fields");
9006744cbabSKevin Wolf             goto fail;
9016744cbabSKevin Wolf         }
9026744cbabSKevin Wolf     }
9036744cbabSKevin Wolf 
904a1b3955cSKevin Wolf     if (header.backing_file_offset > s->cluster_size) {
905a1b3955cSKevin Wolf         error_setg(errp, "Invalid backing file offset");
906a1b3955cSKevin Wolf         ret = -EINVAL;
907a1b3955cSKevin Wolf         goto fail;
908a1b3955cSKevin Wolf     }
909a1b3955cSKevin Wolf 
910cfcc4c62SKevin Wolf     if (header.backing_file_offset) {
911cfcc4c62SKevin Wolf         ext_end = header.backing_file_offset;
912cfcc4c62SKevin Wolf     } else {
913cfcc4c62SKevin Wolf         ext_end = 1 << header.cluster_bits;
914cfcc4c62SKevin Wolf     }
915cfcc4c62SKevin Wolf 
9166744cbabSKevin Wolf     /* Handle feature bits */
9176744cbabSKevin Wolf     s->incompatible_features    = header.incompatible_features;
9186744cbabSKevin Wolf     s->compatible_features      = header.compatible_features;
9196744cbabSKevin Wolf     s->autoclear_features       = header.autoclear_features;
9206744cbabSKevin Wolf 
921c61d0004SStefan Hajnoczi     if (s->incompatible_features & ~QCOW2_INCOMPAT_MASK) {
922cfcc4c62SKevin Wolf         void *feature_table = NULL;
923cfcc4c62SKevin Wolf         qcow2_read_extensions(bs, header.header_length, ext_end,
9243ef6c40aSMax Reitz                               &feature_table, NULL);
925a55448b3SMax Reitz         report_unsupported_feature(errp, feature_table,
926c61d0004SStefan Hajnoczi                                    s->incompatible_features &
927c61d0004SStefan Hajnoczi                                    ~QCOW2_INCOMPAT_MASK);
9286744cbabSKevin Wolf         ret = -ENOTSUP;
929c5a33ee9SPrasad Joshi         g_free(feature_table);
9306744cbabSKevin Wolf         goto fail;
9316744cbabSKevin Wolf     }
9326744cbabSKevin Wolf 
93369c98726SMax Reitz     if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
93469c98726SMax Reitz         /* Corrupt images may not be written to unless they are being repaired
93569c98726SMax Reitz          */
93669c98726SMax Reitz         if ((flags & BDRV_O_RDWR) && !(flags & BDRV_O_CHECK)) {
9373ef6c40aSMax Reitz             error_setg(errp, "qcow2: Image is corrupt; cannot be opened "
9383ef6c40aSMax Reitz                        "read/write");
93969c98726SMax Reitz             ret = -EACCES;
94069c98726SMax Reitz             goto fail;
94169c98726SMax Reitz         }
94269c98726SMax Reitz     }
94369c98726SMax Reitz 
9446744cbabSKevin Wolf     /* Check support for various header values */
945b72faf9fSMax Reitz     if (header.refcount_order > 6) {
946b72faf9fSMax Reitz         error_setg(errp, "Reference count entry width too large; may not "
947b72faf9fSMax Reitz                    "exceed 64 bits");
948b72faf9fSMax Reitz         ret = -EINVAL;
9496744cbabSKevin Wolf         goto fail;
9506744cbabSKevin Wolf     }
951b6481f37SMax Reitz     s->refcount_order = header.refcount_order;
952346a53dfSMax Reitz     s->refcount_bits = 1 << s->refcount_order;
953346a53dfSMax Reitz     s->refcount_max = UINT64_C(1) << (s->refcount_bits - 1);
954346a53dfSMax Reitz     s->refcount_max += s->refcount_max - 1;
9556744cbabSKevin Wolf 
9566d85a57eSJes Sorensen     if (header.crypt_method > QCOW_CRYPT_AES) {
957521b2b5dSMax Reitz         error_setg(errp, "Unsupported encryption method: %" PRIu32,
9583ef6c40aSMax Reitz                    header.crypt_method);
9596d85a57eSJes Sorensen         ret = -EINVAL;
960585f8587Sbellard         goto fail;
9616d85a57eSJes Sorensen     }
962f6fa64f6SDaniel P. Berrange     if (!qcrypto_cipher_supports(QCRYPTO_CIPHER_ALG_AES_128)) {
963f6fa64f6SDaniel P. Berrange         error_setg(errp, "AES cipher not available");
964f6fa64f6SDaniel P. Berrange         ret = -EINVAL;
965f6fa64f6SDaniel P. Berrange         goto fail;
966f6fa64f6SDaniel P. Berrange     }
967585f8587Sbellard     s->crypt_method_header = header.crypt_method;
9686d85a57eSJes Sorensen     if (s->crypt_method_header) {
969e6ff69bfSDaniel P. Berrange         if (bdrv_uses_whitelist() &&
970e6ff69bfSDaniel P. Berrange             s->crypt_method_header == QCOW_CRYPT_AES) {
971e6ff69bfSDaniel P. Berrange             error_report("qcow2 built-in AES encryption is deprecated");
972e6ff69bfSDaniel P. Berrange             error_printf("Support for it will be removed in a future release.\n"
973e6ff69bfSDaniel P. Berrange                          "You can use 'qemu-img convert' to switch to an\n"
974e6ff69bfSDaniel P. Berrange                          "unencrypted qcow2 image, or a LUKS raw image.\n");
975e6ff69bfSDaniel P. Berrange         }
976e6ff69bfSDaniel P. Berrange 
977585f8587Sbellard         bs->encrypted = 1;
978ecfe1863SKevin Wolf 
979ecfe1863SKevin Wolf         /* Encryption works on a sector granularity */
980ecfe1863SKevin Wolf         bs->request_alignment = BDRV_SECTOR_SIZE;
9816d85a57eSJes Sorensen     }
98224342f2cSKevin Wolf 
983585f8587Sbellard     s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */
984585f8587Sbellard     s->l2_size = 1 << s->l2_bits;
9851d13d654SMax Reitz     /* 2^(s->refcount_order - 3) is the refcount width in bytes */
9861d13d654SMax Reitz     s->refcount_block_bits = s->cluster_bits - (s->refcount_order - 3);
9871d13d654SMax Reitz     s->refcount_block_size = 1 << s->refcount_block_bits;
988585f8587Sbellard     bs->total_sectors = header.size / 512;
989585f8587Sbellard     s->csize_shift = (62 - (s->cluster_bits - 8));
990585f8587Sbellard     s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;
991585f8587Sbellard     s->cluster_offset_mask = (1LL << s->csize_shift) - 1;
9925dab2fadSKevin Wolf 
993585f8587Sbellard     s->refcount_table_offset = header.refcount_table_offset;
994585f8587Sbellard     s->refcount_table_size =
995585f8587Sbellard         header.refcount_table_clusters << (s->cluster_bits - 3);
996585f8587Sbellard 
9972b5d5953SKevin Wolf     if (header.refcount_table_clusters > qcow2_max_refcount_clusters(s)) {
9985dab2fadSKevin Wolf         error_setg(errp, "Reference count table too large");
9995dab2fadSKevin Wolf         ret = -EINVAL;
10005dab2fadSKevin Wolf         goto fail;
10015dab2fadSKevin Wolf     }
10025dab2fadSKevin Wolf 
10038c7de283SKevin Wolf     ret = validate_table_offset(bs, s->refcount_table_offset,
10048c7de283SKevin Wolf                                 s->refcount_table_size, sizeof(uint64_t));
10058c7de283SKevin Wolf     if (ret < 0) {
10068c7de283SKevin Wolf         error_setg(errp, "Invalid reference count table offset");
10078c7de283SKevin Wolf         goto fail;
10088c7de283SKevin Wolf     }
10098c7de283SKevin Wolf 
1010ce48f2f4SKevin Wolf     /* Snapshot table offset/length */
1011ce48f2f4SKevin Wolf     if (header.nb_snapshots > QCOW_MAX_SNAPSHOTS) {
1012ce48f2f4SKevin Wolf         error_setg(errp, "Too many snapshots");
1013ce48f2f4SKevin Wolf         ret = -EINVAL;
1014ce48f2f4SKevin Wolf         goto fail;
1015ce48f2f4SKevin Wolf     }
1016ce48f2f4SKevin Wolf 
1017ce48f2f4SKevin Wolf     ret = validate_table_offset(bs, header.snapshots_offset,
1018ce48f2f4SKevin Wolf                                 header.nb_snapshots,
1019ce48f2f4SKevin Wolf                                 sizeof(QCowSnapshotHeader));
1020ce48f2f4SKevin Wolf     if (ret < 0) {
1021ce48f2f4SKevin Wolf         error_setg(errp, "Invalid snapshot table offset");
1022ce48f2f4SKevin Wolf         goto fail;
1023ce48f2f4SKevin Wolf     }
1024ce48f2f4SKevin Wolf 
1025585f8587Sbellard     /* read the level 1 table */
102687b86e7eSWen Congyang     if (header.l1_size > QCOW_MAX_L1_SIZE / sizeof(uint64_t)) {
10272d51c32cSKevin Wolf         error_setg(errp, "Active L1 table too large");
10282d51c32cSKevin Wolf         ret = -EFBIG;
10292d51c32cSKevin Wolf         goto fail;
10302d51c32cSKevin Wolf     }
1031585f8587Sbellard     s->l1_size = header.l1_size;
10322cf7cfa1SKevin Wolf 
10332cf7cfa1SKevin Wolf     l1_vm_state_index = size_to_l1(s, header.size);
10342cf7cfa1SKevin Wolf     if (l1_vm_state_index > INT_MAX) {
10353ef6c40aSMax Reitz         error_setg(errp, "Image is too big");
10362cf7cfa1SKevin Wolf         ret = -EFBIG;
10372cf7cfa1SKevin Wolf         goto fail;
10382cf7cfa1SKevin Wolf     }
10392cf7cfa1SKevin Wolf     s->l1_vm_state_index = l1_vm_state_index;
10402cf7cfa1SKevin Wolf 
1041585f8587Sbellard     /* the L1 table must contain at least enough entries to put
1042585f8587Sbellard        header.size bytes */
10436d85a57eSJes Sorensen     if (s->l1_size < s->l1_vm_state_index) {
10443ef6c40aSMax Reitz         error_setg(errp, "L1 table is too small");
10456d85a57eSJes Sorensen         ret = -EINVAL;
1046585f8587Sbellard         goto fail;
10476d85a57eSJes Sorensen     }
10482d51c32cSKevin Wolf 
10492d51c32cSKevin Wolf     ret = validate_table_offset(bs, header.l1_table_offset,
10502d51c32cSKevin Wolf                                 header.l1_size, sizeof(uint64_t));
10512d51c32cSKevin Wolf     if (ret < 0) {
10522d51c32cSKevin Wolf         error_setg(errp, "Invalid L1 table offset");
10532d51c32cSKevin Wolf         goto fail;
10542d51c32cSKevin Wolf     }
1055585f8587Sbellard     s->l1_table_offset = header.l1_table_offset;
10562d51c32cSKevin Wolf 
10572d51c32cSKevin Wolf 
1058d191d12dSStefan Weil     if (s->l1_size > 0) {
10599a4f4c31SKevin Wolf         s->l1_table = qemu_try_blockalign(bs->file->bs,
10603f6a3ee5SKevin Wolf             align_offset(s->l1_size * sizeof(uint64_t), 512));
1061de82815dSKevin Wolf         if (s->l1_table == NULL) {
1062de82815dSKevin Wolf             error_setg(errp, "Could not allocate L1 table");
1063de82815dSKevin Wolf             ret = -ENOMEM;
1064de82815dSKevin Wolf             goto fail;
1065de82815dSKevin Wolf         }
10669a4f4c31SKevin Wolf         ret = bdrv_pread(bs->file->bs, s->l1_table_offset, s->l1_table,
10676d85a57eSJes Sorensen                          s->l1_size * sizeof(uint64_t));
10686d85a57eSJes Sorensen         if (ret < 0) {
10693ef6c40aSMax Reitz             error_setg_errno(errp, -ret, "Could not read L1 table");
1070585f8587Sbellard             goto fail;
10716d85a57eSJes Sorensen         }
1072585f8587Sbellard         for(i = 0;i < s->l1_size; i++) {
1073585f8587Sbellard             be64_to_cpus(&s->l1_table[i]);
1074585f8587Sbellard         }
1075d191d12dSStefan Weil     }
107629c1a730SKevin Wolf 
107794edf3fbSKevin Wolf     /* Parse driver-specific options */
107894edf3fbSKevin Wolf     ret = qcow2_update_options(bs, options, flags, errp);
107990efa0eaSKevin Wolf     if (ret < 0) {
108090efa0eaSKevin Wolf         goto fail;
108190efa0eaSKevin Wolf     }
108290efa0eaSKevin Wolf 
10837267c094SAnthony Liguori     s->cluster_cache = g_malloc(s->cluster_size);
1084585f8587Sbellard     /* one more sector for decompressed data alignment */
10859a4f4c31SKevin Wolf     s->cluster_data = qemu_try_blockalign(bs->file->bs, QCOW_MAX_CRYPT_CLUSTERS
1086de82815dSKevin Wolf                                                     * s->cluster_size + 512);
1087de82815dSKevin Wolf     if (s->cluster_data == NULL) {
1088de82815dSKevin Wolf         error_setg(errp, "Could not allocate temporary cluster buffer");
1089de82815dSKevin Wolf         ret = -ENOMEM;
1090de82815dSKevin Wolf         goto fail;
1091de82815dSKevin Wolf     }
1092de82815dSKevin Wolf 
1093585f8587Sbellard     s->cluster_cache_offset = -1;
109406d9260fSAnthony Liguori     s->flags = flags;
1095585f8587Sbellard 
10966d85a57eSJes Sorensen     ret = qcow2_refcount_init(bs);
10976d85a57eSJes Sorensen     if (ret != 0) {
10983ef6c40aSMax Reitz         error_setg_errno(errp, -ret, "Could not initialize refcount handling");
1099585f8587Sbellard         goto fail;
11006d85a57eSJes Sorensen     }
1101585f8587Sbellard 
110272cf2d4fSBlue Swirl     QLIST_INIT(&s->cluster_allocs);
11030b919faeSKevin Wolf     QTAILQ_INIT(&s->discards);
1104f214978aSKevin Wolf 
11059b80ddf3Saliguori     /* read qcow2 extensions */
11063ef6c40aSMax Reitz     if (qcow2_read_extensions(bs, header.header_length, ext_end, NULL,
11073ef6c40aSMax Reitz         &local_err)) {
11083ef6c40aSMax Reitz         error_propagate(errp, local_err);
11096d85a57eSJes Sorensen         ret = -EINVAL;
11109b80ddf3Saliguori         goto fail;
11116d85a57eSJes Sorensen     }
11129b80ddf3Saliguori 
1113585f8587Sbellard     /* read the backing file name */
1114585f8587Sbellard     if (header.backing_file_offset != 0) {
1115585f8587Sbellard         len = header.backing_file_size;
11169a29e18fSJeff Cody         if (len > MIN(1023, s->cluster_size - header.backing_file_offset) ||
1117e729fa6aSJeff Cody             len >= sizeof(bs->backing_file)) {
11186d33e8e7SKevin Wolf             error_setg(errp, "Backing file name too long");
11196d33e8e7SKevin Wolf             ret = -EINVAL;
11206d33e8e7SKevin Wolf             goto fail;
11216d85a57eSJes Sorensen         }
11229a4f4c31SKevin Wolf         ret = bdrv_pread(bs->file->bs, header.backing_file_offset,
11236d85a57eSJes Sorensen                          bs->backing_file, len);
11246d85a57eSJes Sorensen         if (ret < 0) {
11253ef6c40aSMax Reitz             error_setg_errno(errp, -ret, "Could not read backing file name");
1126585f8587Sbellard             goto fail;
11276d85a57eSJes Sorensen         }
1128585f8587Sbellard         bs->backing_file[len] = '\0';
1129e4603fe1SKevin Wolf         s->image_backing_file = g_strdup(bs->backing_file);
1130585f8587Sbellard     }
113142deb29fSKevin Wolf 
113211b128f4SKevin Wolf     /* Internal snapshots */
113311b128f4SKevin Wolf     s->snapshots_offset = header.snapshots_offset;
113411b128f4SKevin Wolf     s->nb_snapshots = header.nb_snapshots;
113511b128f4SKevin Wolf 
113642deb29fSKevin Wolf     ret = qcow2_read_snapshots(bs);
113742deb29fSKevin Wolf     if (ret < 0) {
11383ef6c40aSMax Reitz         error_setg_errno(errp, -ret, "Could not read snapshots");
1139585f8587Sbellard         goto fail;
11406d85a57eSJes Sorensen     }
1141585f8587Sbellard 
1142af7b708dSStefan Hajnoczi     /* Clear unknown autoclear feature bits */
114304c01a5cSKevin Wolf     if (!bs->read_only && !(flags & BDRV_O_INACTIVE) && s->autoclear_features) {
1144af7b708dSStefan Hajnoczi         s->autoclear_features = 0;
1145af7b708dSStefan Hajnoczi         ret = qcow2_update_header(bs);
1146af7b708dSStefan Hajnoczi         if (ret < 0) {
11473ef6c40aSMax Reitz             error_setg_errno(errp, -ret, "Could not update qcow2 header");
1148af7b708dSStefan Hajnoczi             goto fail;
1149af7b708dSStefan Hajnoczi         }
1150af7b708dSStefan Hajnoczi     }
1151af7b708dSStefan Hajnoczi 
115268d100e9SKevin Wolf     /* Initialise locks */
115368d100e9SKevin Wolf     qemu_co_mutex_init(&s->lock);
115468d100e9SKevin Wolf 
1155c61d0004SStefan Hajnoczi     /* Repair image if dirty */
115604c01a5cSKevin Wolf     if (!(flags & (BDRV_O_CHECK | BDRV_O_INACTIVE)) && !bs->read_only &&
1157058f8f16SStefan Hajnoczi         (s->incompatible_features & QCOW2_INCOMPAT_DIRTY)) {
1158c61d0004SStefan Hajnoczi         BdrvCheckResult result = {0};
1159c61d0004SStefan Hajnoczi 
11605b84106bSMax Reitz         ret = qcow2_check(bs, &result, BDRV_FIX_ERRORS | BDRV_FIX_LEAKS);
1161c61d0004SStefan Hajnoczi         if (ret < 0) {
11623ef6c40aSMax Reitz             error_setg_errno(errp, -ret, "Could not repair dirty image");
1163c61d0004SStefan Hajnoczi             goto fail;
1164c61d0004SStefan Hajnoczi         }
1165c61d0004SStefan Hajnoczi     }
1166c61d0004SStefan Hajnoczi 
1167585f8587Sbellard #ifdef DEBUG_ALLOC
11686cbc3031SPhilipp Hahn     {
11696cbc3031SPhilipp Hahn         BdrvCheckResult result = {0};
1170b35278f7SStefan Hajnoczi         qcow2_check_refcounts(bs, &result, 0);
11716cbc3031SPhilipp Hahn     }
1172585f8587Sbellard #endif
11736d85a57eSJes Sorensen     return ret;
1174585f8587Sbellard 
1175585f8587Sbellard  fail:
11766744cbabSKevin Wolf     g_free(s->unknown_header_fields);
117775bab85cSKevin Wolf     cleanup_unknown_header_ext(bs);
1178ed6ccf0fSKevin Wolf     qcow2_free_snapshots(bs);
1179ed6ccf0fSKevin Wolf     qcow2_refcount_close(bs);
1180de82815dSKevin Wolf     qemu_vfree(s->l1_table);
1181cf93980eSMax Reitz     /* else pre-write overlap checks in cache_destroy may crash */
1182cf93980eSMax Reitz     s->l1_table = NULL;
1183279621c0SAlberto Garcia     cache_clean_timer_del(bs);
118429c1a730SKevin Wolf     if (s->l2_table_cache) {
118529c1a730SKevin Wolf         qcow2_cache_destroy(bs, s->l2_table_cache);
118629c1a730SKevin Wolf     }
1187c5a33ee9SPrasad Joshi     if (s->refcount_block_cache) {
1188c5a33ee9SPrasad Joshi         qcow2_cache_destroy(bs, s->refcount_block_cache);
1189c5a33ee9SPrasad Joshi     }
11907267c094SAnthony Liguori     g_free(s->cluster_cache);
1191dea43a65SFrediano Ziglio     qemu_vfree(s->cluster_data);
11926d85a57eSJes Sorensen     return ret;
1193585f8587Sbellard }
1194585f8587Sbellard 
11953baca891SKevin Wolf static void qcow2_refresh_limits(BlockDriverState *bs, Error **errp)
1196d34682cdSKevin Wolf {
1197ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
1198d34682cdSKevin Wolf 
1199cf081fcaSEric Blake     bs->bl.pwrite_zeroes_alignment = s->cluster_size;
1200d34682cdSKevin Wolf }
1201d34682cdSKevin Wolf 
12027c80ab3fSJes Sorensen static int qcow2_set_key(BlockDriverState *bs, const char *key)
1203585f8587Sbellard {
1204ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
1205585f8587Sbellard     uint8_t keybuf[16];
1206585f8587Sbellard     int len, i;
1207f6fa64f6SDaniel P. Berrange     Error *err = NULL;
1208585f8587Sbellard 
1209585f8587Sbellard     memset(keybuf, 0, 16);
1210585f8587Sbellard     len = strlen(key);
1211585f8587Sbellard     if (len > 16)
1212585f8587Sbellard         len = 16;
1213585f8587Sbellard     /* XXX: we could compress the chars to 7 bits to increase
1214585f8587Sbellard        entropy */
1215585f8587Sbellard     for(i = 0;i < len;i++) {
1216585f8587Sbellard         keybuf[i] = key[i];
1217585f8587Sbellard     }
12188336aafaSDaniel P. Berrange     assert(bs->encrypted);
1219585f8587Sbellard 
1220f6fa64f6SDaniel P. Berrange     qcrypto_cipher_free(s->cipher);
1221f6fa64f6SDaniel P. Berrange     s->cipher = qcrypto_cipher_new(
1222f6fa64f6SDaniel P. Berrange         QCRYPTO_CIPHER_ALG_AES_128,
1223f6fa64f6SDaniel P. Berrange         QCRYPTO_CIPHER_MODE_CBC,
1224f6fa64f6SDaniel P. Berrange         keybuf, G_N_ELEMENTS(keybuf),
1225f6fa64f6SDaniel P. Berrange         &err);
1226f6fa64f6SDaniel P. Berrange 
1227f6fa64f6SDaniel P. Berrange     if (!s->cipher) {
1228f6fa64f6SDaniel P. Berrange         /* XXX would be nice if errors in this method could
1229f6fa64f6SDaniel P. Berrange          * be properly propagate to the caller. Would need
1230f6fa64f6SDaniel P. Berrange          * the bdrv_set_key() API signature to be fixed. */
1231f6fa64f6SDaniel P. Berrange         error_free(err);
1232585f8587Sbellard         return -1;
1233585f8587Sbellard     }
1234585f8587Sbellard     return 0;
1235585f8587Sbellard }
1236585f8587Sbellard 
123721d82ac9SJeff Cody static int qcow2_reopen_prepare(BDRVReopenState *state,
123821d82ac9SJeff Cody                                 BlockReopenQueue *queue, Error **errp)
123921d82ac9SJeff Cody {
12405b0959a7SKevin Wolf     Qcow2ReopenState *r;
12414c2e5f8fSKevin Wolf     int ret;
12424c2e5f8fSKevin Wolf 
12435b0959a7SKevin Wolf     r = g_new0(Qcow2ReopenState, 1);
12445b0959a7SKevin Wolf     state->opaque = r;
12455b0959a7SKevin Wolf 
12465b0959a7SKevin Wolf     ret = qcow2_update_options_prepare(state->bs, r, state->options,
12475b0959a7SKevin Wolf                                        state->flags, errp);
12485b0959a7SKevin Wolf     if (ret < 0) {
12495b0959a7SKevin Wolf         goto fail;
12505b0959a7SKevin Wolf     }
12515b0959a7SKevin Wolf 
12525b0959a7SKevin Wolf     /* We need to write out any unwritten data if we reopen read-only. */
12534c2e5f8fSKevin Wolf     if ((state->flags & BDRV_O_RDWR) == 0) {
12544c2e5f8fSKevin Wolf         ret = bdrv_flush(state->bs);
12554c2e5f8fSKevin Wolf         if (ret < 0) {
12565b0959a7SKevin Wolf             goto fail;
12574c2e5f8fSKevin Wolf         }
12584c2e5f8fSKevin Wolf 
12594c2e5f8fSKevin Wolf         ret = qcow2_mark_clean(state->bs);
12604c2e5f8fSKevin Wolf         if (ret < 0) {
12615b0959a7SKevin Wolf             goto fail;
12624c2e5f8fSKevin Wolf         }
12634c2e5f8fSKevin Wolf     }
12644c2e5f8fSKevin Wolf 
126521d82ac9SJeff Cody     return 0;
12665b0959a7SKevin Wolf 
12675b0959a7SKevin Wolf fail:
12685b0959a7SKevin Wolf     qcow2_update_options_abort(state->bs, r);
12695b0959a7SKevin Wolf     g_free(r);
12705b0959a7SKevin Wolf     return ret;
12715b0959a7SKevin Wolf }
12725b0959a7SKevin Wolf 
12735b0959a7SKevin Wolf static void qcow2_reopen_commit(BDRVReopenState *state)
12745b0959a7SKevin Wolf {
12755b0959a7SKevin Wolf     qcow2_update_options_commit(state->bs, state->opaque);
12765b0959a7SKevin Wolf     g_free(state->opaque);
12775b0959a7SKevin Wolf }
12785b0959a7SKevin Wolf 
12795b0959a7SKevin Wolf static void qcow2_reopen_abort(BDRVReopenState *state)
12805b0959a7SKevin Wolf {
12815b0959a7SKevin Wolf     qcow2_update_options_abort(state->bs, state->opaque);
12825b0959a7SKevin Wolf     g_free(state->opaque);
128321d82ac9SJeff Cody }
128421d82ac9SJeff Cody 
12855365f44dSKevin Wolf static void qcow2_join_options(QDict *options, QDict *old_options)
12865365f44dSKevin Wolf {
12875365f44dSKevin Wolf     bool has_new_overlap_template =
12885365f44dSKevin Wolf         qdict_haskey(options, QCOW2_OPT_OVERLAP) ||
12895365f44dSKevin Wolf         qdict_haskey(options, QCOW2_OPT_OVERLAP_TEMPLATE);
12905365f44dSKevin Wolf     bool has_new_total_cache_size =
12915365f44dSKevin Wolf         qdict_haskey(options, QCOW2_OPT_CACHE_SIZE);
12925365f44dSKevin Wolf     bool has_all_cache_options;
12935365f44dSKevin Wolf 
12945365f44dSKevin Wolf     /* New overlap template overrides all old overlap options */
12955365f44dSKevin Wolf     if (has_new_overlap_template) {
12965365f44dSKevin Wolf         qdict_del(old_options, QCOW2_OPT_OVERLAP);
12975365f44dSKevin Wolf         qdict_del(old_options, QCOW2_OPT_OVERLAP_TEMPLATE);
12985365f44dSKevin Wolf         qdict_del(old_options, QCOW2_OPT_OVERLAP_MAIN_HEADER);
12995365f44dSKevin Wolf         qdict_del(old_options, QCOW2_OPT_OVERLAP_ACTIVE_L1);
13005365f44dSKevin Wolf         qdict_del(old_options, QCOW2_OPT_OVERLAP_ACTIVE_L2);
13015365f44dSKevin Wolf         qdict_del(old_options, QCOW2_OPT_OVERLAP_REFCOUNT_TABLE);
13025365f44dSKevin Wolf         qdict_del(old_options, QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK);
13035365f44dSKevin Wolf         qdict_del(old_options, QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE);
13045365f44dSKevin Wolf         qdict_del(old_options, QCOW2_OPT_OVERLAP_INACTIVE_L1);
13055365f44dSKevin Wolf         qdict_del(old_options, QCOW2_OPT_OVERLAP_INACTIVE_L2);
13065365f44dSKevin Wolf     }
13075365f44dSKevin Wolf 
13085365f44dSKevin Wolf     /* New total cache size overrides all old options */
13095365f44dSKevin Wolf     if (qdict_haskey(options, QCOW2_OPT_CACHE_SIZE)) {
13105365f44dSKevin Wolf         qdict_del(old_options, QCOW2_OPT_L2_CACHE_SIZE);
13115365f44dSKevin Wolf         qdict_del(old_options, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
13125365f44dSKevin Wolf     }
13135365f44dSKevin Wolf 
13145365f44dSKevin Wolf     qdict_join(options, old_options, false);
13155365f44dSKevin Wolf 
13165365f44dSKevin Wolf     /*
13175365f44dSKevin Wolf      * If after merging all cache size options are set, an old total size is
13185365f44dSKevin Wolf      * overwritten. Do keep all options, however, if all three are new. The
13195365f44dSKevin Wolf      * resulting error message is what we want to happen.
13205365f44dSKevin Wolf      */
13215365f44dSKevin Wolf     has_all_cache_options =
13225365f44dSKevin Wolf         qdict_haskey(options, QCOW2_OPT_CACHE_SIZE) ||
13235365f44dSKevin Wolf         qdict_haskey(options, QCOW2_OPT_L2_CACHE_SIZE) ||
13245365f44dSKevin Wolf         qdict_haskey(options, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
13255365f44dSKevin Wolf 
13265365f44dSKevin Wolf     if (has_all_cache_options && !has_new_total_cache_size) {
13275365f44dSKevin Wolf         qdict_del(options, QCOW2_OPT_CACHE_SIZE);
13285365f44dSKevin Wolf     }
13295365f44dSKevin Wolf }
13305365f44dSKevin Wolf 
1331b6b8a333SPaolo Bonzini static int64_t coroutine_fn qcow2_co_get_block_status(BlockDriverState *bs,
133267a0fd2aSFam Zheng         int64_t sector_num, int nb_sectors, int *pnum, BlockDriverState **file)
1333585f8587Sbellard {
1334ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
1335585f8587Sbellard     uint64_t cluster_offset;
13364bc74be9SPaolo Bonzini     int index_in_cluster, ret;
1337ecfe1863SKevin Wolf     unsigned int bytes;
13384bc74be9SPaolo Bonzini     int64_t status = 0;
1339585f8587Sbellard 
1340ecfe1863SKevin Wolf     bytes = MIN(INT_MAX, nb_sectors * BDRV_SECTOR_SIZE);
1341f8a2e5e3SStefan Hajnoczi     qemu_co_mutex_lock(&s->lock);
1342ecfe1863SKevin Wolf     ret = qcow2_get_cluster_offset(bs, sector_num << 9, &bytes,
1343ecfe1863SKevin Wolf                                    &cluster_offset);
1344f8a2e5e3SStefan Hajnoczi     qemu_co_mutex_unlock(&s->lock);
13451c46efaaSKevin Wolf     if (ret < 0) {
1346d663640cSPaolo Bonzini         return ret;
13471c46efaaSKevin Wolf     }
1348095a9c58Saliguori 
1349ecfe1863SKevin Wolf     *pnum = bytes >> BDRV_SECTOR_BITS;
1350ecfe1863SKevin Wolf 
13514bc74be9SPaolo Bonzini     if (cluster_offset != 0 && ret != QCOW2_CLUSTER_COMPRESSED &&
1352f6fa64f6SDaniel P. Berrange         !s->cipher) {
13534bc74be9SPaolo Bonzini         index_in_cluster = sector_num & (s->cluster_sectors - 1);
13544bc74be9SPaolo Bonzini         cluster_offset |= (index_in_cluster << BDRV_SECTOR_BITS);
1355178b4db7SFam Zheng         *file = bs->file->bs;
13564bc74be9SPaolo Bonzini         status |= BDRV_BLOCK_OFFSET_VALID | cluster_offset;
13574bc74be9SPaolo Bonzini     }
13584bc74be9SPaolo Bonzini     if (ret == QCOW2_CLUSTER_ZERO) {
13594bc74be9SPaolo Bonzini         status |= BDRV_BLOCK_ZERO;
13604bc74be9SPaolo Bonzini     } else if (ret != QCOW2_CLUSTER_UNALLOCATED) {
13614bc74be9SPaolo Bonzini         status |= BDRV_BLOCK_DATA;
13624bc74be9SPaolo Bonzini     }
13634bc74be9SPaolo Bonzini     return status;
1364585f8587Sbellard }
1365585f8587Sbellard 
1366a9465922Sbellard /* handle reading after the end of the backing file */
1367bd28f835SKevin Wolf int qcow2_backing_read1(BlockDriverState *bs, QEMUIOVector *qiov,
1368ecfe1863SKevin Wolf                         int64_t offset, int bytes)
1369a9465922Sbellard {
1370ecfe1863SKevin Wolf     uint64_t bs_size = bs->total_sectors * BDRV_SECTOR_SIZE;
1371a9465922Sbellard     int n1;
1372bd28f835SKevin Wolf 
1373ecfe1863SKevin Wolf     if ((offset + bytes) <= bs_size) {
1374ecfe1863SKevin Wolf         return bytes;
1375ecfe1863SKevin Wolf     }
1376ecfe1863SKevin Wolf 
1377ecfe1863SKevin Wolf     if (offset >= bs_size) {
1378ecfe1863SKevin Wolf         n1 = 0;
1379ecfe1863SKevin Wolf     } else {
1380ecfe1863SKevin Wolf         n1 = bs_size - offset;
1381ecfe1863SKevin Wolf     }
1382ecfe1863SKevin Wolf 
1383ecfe1863SKevin Wolf     qemu_iovec_memset(qiov, n1, 0, bytes - n1);
1384bd28f835SKevin Wolf 
1385a9465922Sbellard     return n1;
1386a9465922Sbellard }
1387a9465922Sbellard 
1388ecfe1863SKevin Wolf static coroutine_fn int qcow2_co_preadv(BlockDriverState *bs, uint64_t offset,
1389ecfe1863SKevin Wolf                                         uint64_t bytes, QEMUIOVector *qiov,
1390ecfe1863SKevin Wolf                                         int flags)
13911490791fSaliguori {
1392ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
1393ecfe1863SKevin Wolf     int offset_in_cluster, n1;
139468d100e9SKevin Wolf     int ret;
1395ecfe1863SKevin Wolf     unsigned int cur_bytes; /* number of bytes in current iteration */
1396c2bdd990SFrediano Ziglio     uint64_t cluster_offset = 0;
13973fc48d09SFrediano Ziglio     uint64_t bytes_done = 0;
13983fc48d09SFrediano Ziglio     QEMUIOVector hd_qiov;
13993fc48d09SFrediano Ziglio     uint8_t *cluster_data = NULL;
1400585f8587Sbellard 
14013fc48d09SFrediano Ziglio     qemu_iovec_init(&hd_qiov, qiov->niov);
14023fc48d09SFrediano Ziglio 
14033fc48d09SFrediano Ziglio     qemu_co_mutex_lock(&s->lock);
14043fc48d09SFrediano Ziglio 
1405ecfe1863SKevin Wolf     while (bytes != 0) {
1406585f8587Sbellard 
1407faf575c1SFrediano Ziglio         /* prepare next request */
1408ecfe1863SKevin Wolf         cur_bytes = MIN(bytes, INT_MAX);
1409f6fa64f6SDaniel P. Berrange         if (s->cipher) {
1410ecfe1863SKevin Wolf             cur_bytes = MIN(cur_bytes,
1411ecfe1863SKevin Wolf                             QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
1412bd28f835SKevin Wolf         }
1413bd28f835SKevin Wolf 
1414ecfe1863SKevin Wolf         ret = qcow2_get_cluster_offset(bs, offset, &cur_bytes, &cluster_offset);
14151c46efaaSKevin Wolf         if (ret < 0) {
14163fc48d09SFrediano Ziglio             goto fail;
14171c46efaaSKevin Wolf         }
14181c46efaaSKevin Wolf 
1419ecfe1863SKevin Wolf         offset_in_cluster = offset_into_cluster(s, offset);
1420585f8587Sbellard 
14213fc48d09SFrediano Ziglio         qemu_iovec_reset(&hd_qiov);
1422ecfe1863SKevin Wolf         qemu_iovec_concat(&hd_qiov, qiov, bytes_done, cur_bytes);
1423bd28f835SKevin Wolf 
142468d000a3SKevin Wolf         switch (ret) {
142568d000a3SKevin Wolf         case QCOW2_CLUSTER_UNALLOCATED:
1426bd28f835SKevin Wolf 
1427760e0063SKevin Wolf             if (bs->backing) {
1428585f8587Sbellard                 /* read from the base image */
1429760e0063SKevin Wolf                 n1 = qcow2_backing_read1(bs->backing->bs, &hd_qiov,
1430ecfe1863SKevin Wolf                                          offset, cur_bytes);
1431a9465922Sbellard                 if (n1 > 0) {
143244deba5aSKevin Wolf                     QEMUIOVector local_qiov;
143344deba5aSKevin Wolf 
143444deba5aSKevin Wolf                     qemu_iovec_init(&local_qiov, hd_qiov.niov);
1435ecfe1863SKevin Wolf                     qemu_iovec_concat(&local_qiov, &hd_qiov, 0, n1);
143644deba5aSKevin Wolf 
143766f82ceeSKevin Wolf                     BLKDBG_EVENT(bs->file, BLKDBG_READ_BACKING_AIO);
143868d100e9SKevin Wolf                     qemu_co_mutex_unlock(&s->lock);
1439ecfe1863SKevin Wolf                     ret = bdrv_co_preadv(bs->backing->bs, offset, n1,
1440ecfe1863SKevin Wolf                                          &local_qiov, 0);
144168d100e9SKevin Wolf                     qemu_co_mutex_lock(&s->lock);
144244deba5aSKevin Wolf 
144344deba5aSKevin Wolf                     qemu_iovec_destroy(&local_qiov);
144444deba5aSKevin Wolf 
144568d100e9SKevin Wolf                     if (ret < 0) {
14463fc48d09SFrediano Ziglio                         goto fail;
14473ab4c7e9SKevin Wolf                     }
14481490791fSaliguori                 }
1449a9465922Sbellard             } else {
1450585f8587Sbellard                 /* Note: in this case, no need to wait */
1451ecfe1863SKevin Wolf                 qemu_iovec_memset(&hd_qiov, 0, 0, cur_bytes);
14521490791fSaliguori             }
145368d000a3SKevin Wolf             break;
145468d000a3SKevin Wolf 
14556377af48SKevin Wolf         case QCOW2_CLUSTER_ZERO:
1456ecfe1863SKevin Wolf             qemu_iovec_memset(&hd_qiov, 0, 0, cur_bytes);
14576377af48SKevin Wolf             break;
14586377af48SKevin Wolf 
145968d000a3SKevin Wolf         case QCOW2_CLUSTER_COMPRESSED:
1460585f8587Sbellard             /* add AIO support for compressed blocks ? */
1461c2bdd990SFrediano Ziglio             ret = qcow2_decompress_cluster(bs, cluster_offset);
14628af36488SKevin Wolf             if (ret < 0) {
14633fc48d09SFrediano Ziglio                 goto fail;
14648af36488SKevin Wolf             }
1465bd28f835SKevin Wolf 
146603396148SMichael Tokarev             qemu_iovec_from_buf(&hd_qiov, 0,
1467ecfe1863SKevin Wolf                                 s->cluster_cache + offset_in_cluster,
1468ecfe1863SKevin Wolf                                 cur_bytes);
146968d000a3SKevin Wolf             break;
147068d000a3SKevin Wolf 
147168d000a3SKevin Wolf         case QCOW2_CLUSTER_NORMAL:
1472c2bdd990SFrediano Ziglio             if ((cluster_offset & 511) != 0) {
14733fc48d09SFrediano Ziglio                 ret = -EIO;
14743fc48d09SFrediano Ziglio                 goto fail;
1475585f8587Sbellard             }
1476c87c0672Saliguori 
14778336aafaSDaniel P. Berrange             if (bs->encrypted) {
1478f6fa64f6SDaniel P. Berrange                 assert(s->cipher);
14798336aafaSDaniel P. Berrange 
1480bd28f835SKevin Wolf                 /*
1481bd28f835SKevin Wolf                  * For encrypted images, read everything into a temporary
1482bd28f835SKevin Wolf                  * contiguous buffer on which the AES functions can work.
1483bd28f835SKevin Wolf                  */
14843fc48d09SFrediano Ziglio                 if (!cluster_data) {
14853fc48d09SFrediano Ziglio                     cluster_data =
14869a4f4c31SKevin Wolf                         qemu_try_blockalign(bs->file->bs,
14879a4f4c31SKevin Wolf                                             QCOW_MAX_CRYPT_CLUSTERS
1488de82815dSKevin Wolf                                             * s->cluster_size);
1489de82815dSKevin Wolf                     if (cluster_data == NULL) {
1490de82815dSKevin Wolf                         ret = -ENOMEM;
1491de82815dSKevin Wolf                         goto fail;
1492de82815dSKevin Wolf                     }
1493bd28f835SKevin Wolf                 }
1494bd28f835SKevin Wolf 
1495ecfe1863SKevin Wolf                 assert(cur_bytes <= QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
14963fc48d09SFrediano Ziglio                 qemu_iovec_reset(&hd_qiov);
1497ecfe1863SKevin Wolf                 qemu_iovec_add(&hd_qiov, cluster_data, cur_bytes);
1498bd28f835SKevin Wolf             }
1499bd28f835SKevin Wolf 
150066f82ceeSKevin Wolf             BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);
150168d100e9SKevin Wolf             qemu_co_mutex_unlock(&s->lock);
1502ecfe1863SKevin Wolf             ret = bdrv_co_preadv(bs->file->bs,
1503ecfe1863SKevin Wolf                                  cluster_offset + offset_in_cluster,
1504ecfe1863SKevin Wolf                                  cur_bytes, &hd_qiov, 0);
150568d100e9SKevin Wolf             qemu_co_mutex_lock(&s->lock);
150668d100e9SKevin Wolf             if (ret < 0) {
15073fc48d09SFrediano Ziglio                 goto fail;
1508585f8587Sbellard             }
15098336aafaSDaniel P. Berrange             if (bs->encrypted) {
1510f6fa64f6SDaniel P. Berrange                 assert(s->cipher);
1511ecfe1863SKevin Wolf                 assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);
1512ecfe1863SKevin Wolf                 assert((cur_bytes & (BDRV_SECTOR_SIZE - 1)) == 0);
1513f6fa64f6SDaniel P. Berrange                 Error *err = NULL;
1514ecfe1863SKevin Wolf                 if (qcow2_encrypt_sectors(s, offset >> BDRV_SECTOR_BITS,
1515ecfe1863SKevin Wolf                                           cluster_data, cluster_data,
1516ecfe1863SKevin Wolf                                           cur_bytes >> BDRV_SECTOR_BITS,
1517ecfe1863SKevin Wolf                                           false, &err) < 0) {
1518f6fa64f6SDaniel P. Berrange                     error_free(err);
1519f6fa64f6SDaniel P. Berrange                     ret = -EIO;
1520f6fa64f6SDaniel P. Berrange                     goto fail;
1521f6fa64f6SDaniel P. Berrange                 }
1522ecfe1863SKevin Wolf                 qemu_iovec_from_buf(qiov, bytes_done, cluster_data, cur_bytes);
1523171e3d6bSKevin Wolf             }
152468d000a3SKevin Wolf             break;
152568d000a3SKevin Wolf 
152668d000a3SKevin Wolf         default:
152768d000a3SKevin Wolf             g_assert_not_reached();
152868d000a3SKevin Wolf             ret = -EIO;
152968d000a3SKevin Wolf             goto fail;
1530faf575c1SFrediano Ziglio         }
1531faf575c1SFrediano Ziglio 
1532ecfe1863SKevin Wolf         bytes -= cur_bytes;
1533ecfe1863SKevin Wolf         offset += cur_bytes;
1534ecfe1863SKevin Wolf         bytes_done += cur_bytes;
15355ebaa27eSFrediano Ziglio     }
15363fc48d09SFrediano Ziglio     ret = 0;
1537f141eafeSaliguori 
15383fc48d09SFrediano Ziglio fail:
153968d100e9SKevin Wolf     qemu_co_mutex_unlock(&s->lock);
154068d100e9SKevin Wolf 
15413fc48d09SFrediano Ziglio     qemu_iovec_destroy(&hd_qiov);
1542dea43a65SFrediano Ziglio     qemu_vfree(cluster_data);
154368d100e9SKevin Wolf 
154468d100e9SKevin Wolf     return ret;
1545585f8587Sbellard }
1546585f8587Sbellard 
1547*d46a0bb2SKevin Wolf static coroutine_fn int qcow2_co_pwritev(BlockDriverState *bs, uint64_t offset,
1548*d46a0bb2SKevin Wolf                                          uint64_t bytes, QEMUIOVector *qiov,
1549*d46a0bb2SKevin Wolf                                          int flags)
1550585f8587Sbellard {
1551ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
1552*d46a0bb2SKevin Wolf     int offset_in_cluster;
155368d100e9SKevin Wolf     int ret;
1554*d46a0bb2SKevin Wolf     unsigned int cur_bytes; /* number of sectors in current iteration */
1555c2bdd990SFrediano Ziglio     uint64_t cluster_offset;
15563fc48d09SFrediano Ziglio     QEMUIOVector hd_qiov;
15573fc48d09SFrediano Ziglio     uint64_t bytes_done = 0;
15583fc48d09SFrediano Ziglio     uint8_t *cluster_data = NULL;
15598d2497c3SKevin Wolf     QCowL2Meta *l2meta = NULL;
1560c2271403SFrediano Ziglio 
1561*d46a0bb2SKevin Wolf     trace_qcow2_writev_start_req(qemu_coroutine_self(), offset, bytes);
15623cce16f4SKevin Wolf 
15633fc48d09SFrediano Ziglio     qemu_iovec_init(&hd_qiov, qiov->niov);
1564585f8587Sbellard 
15653fc48d09SFrediano Ziglio     s->cluster_cache_offset = -1; /* disable compressed cache */
15663fc48d09SFrediano Ziglio 
15673fc48d09SFrediano Ziglio     qemu_co_mutex_lock(&s->lock);
15683fc48d09SFrediano Ziglio 
1569*d46a0bb2SKevin Wolf     while (bytes != 0) {
15703fc48d09SFrediano Ziglio 
1571f50f88b9SKevin Wolf         l2meta = NULL;
1572cf5c1a23SKevin Wolf 
15733cce16f4SKevin Wolf         trace_qcow2_writev_start_part(qemu_coroutine_self());
1574*d46a0bb2SKevin Wolf         offset_in_cluster = offset_into_cluster(s, offset);
1575*d46a0bb2SKevin Wolf         cur_bytes = MIN(bytes, INT_MAX);
1576*d46a0bb2SKevin Wolf         if (bs->encrypted) {
1577*d46a0bb2SKevin Wolf             cur_bytes = MIN(cur_bytes,
1578*d46a0bb2SKevin Wolf                             QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size
1579*d46a0bb2SKevin Wolf                             - offset_in_cluster);
15805ebaa27eSFrediano Ziglio         }
1581095a9c58Saliguori 
1582*d46a0bb2SKevin Wolf         ret = qcow2_alloc_cluster_offset(bs, offset, &cur_bytes,
1583*d46a0bb2SKevin Wolf                                          &cluster_offset, &l2meta);
1584148da7eaSKevin Wolf         if (ret < 0) {
15853fc48d09SFrediano Ziglio             goto fail;
1586148da7eaSKevin Wolf         }
1587148da7eaSKevin Wolf 
1588c2bdd990SFrediano Ziglio         assert((cluster_offset & 511) == 0);
1589148da7eaSKevin Wolf 
15903fc48d09SFrediano Ziglio         qemu_iovec_reset(&hd_qiov);
1591*d46a0bb2SKevin Wolf         qemu_iovec_concat(&hd_qiov, qiov, bytes_done, cur_bytes);
15926f5f060bSKevin Wolf 
15938336aafaSDaniel P. Berrange         if (bs->encrypted) {
1594f6fa64f6SDaniel P. Berrange             Error *err = NULL;
1595f6fa64f6SDaniel P. Berrange             assert(s->cipher);
15963fc48d09SFrediano Ziglio             if (!cluster_data) {
15979a4f4c31SKevin Wolf                 cluster_data = qemu_try_blockalign(bs->file->bs,
1598de82815dSKevin Wolf                                                    QCOW_MAX_CRYPT_CLUSTERS
1599de82815dSKevin Wolf                                                    * s->cluster_size);
1600de82815dSKevin Wolf                 if (cluster_data == NULL) {
1601de82815dSKevin Wolf                     ret = -ENOMEM;
1602de82815dSKevin Wolf                     goto fail;
1603de82815dSKevin Wolf                 }
1604585f8587Sbellard             }
16056f5f060bSKevin Wolf 
16063fc48d09SFrediano Ziglio             assert(hd_qiov.size <=
16075ebaa27eSFrediano Ziglio                    QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
1608d5e6b161SMichael Tokarev             qemu_iovec_to_buf(&hd_qiov, 0, cluster_data, hd_qiov.size);
16096f5f060bSKevin Wolf 
1610*d46a0bb2SKevin Wolf             if (qcow2_encrypt_sectors(s, offset >> BDRV_SECTOR_BITS,
1611*d46a0bb2SKevin Wolf                                       cluster_data, cluster_data,
1612*d46a0bb2SKevin Wolf                                       cur_bytes >>BDRV_SECTOR_BITS,
1613f6fa64f6SDaniel P. Berrange                                       true, &err) < 0) {
1614f6fa64f6SDaniel P. Berrange                 error_free(err);
1615f6fa64f6SDaniel P. Berrange                 ret = -EIO;
1616f6fa64f6SDaniel P. Berrange                 goto fail;
1617f6fa64f6SDaniel P. Berrange             }
16186f5f060bSKevin Wolf 
16193fc48d09SFrediano Ziglio             qemu_iovec_reset(&hd_qiov);
1620*d46a0bb2SKevin Wolf             qemu_iovec_add(&hd_qiov, cluster_data, cur_bytes);
1621585f8587Sbellard         }
16226f5f060bSKevin Wolf 
1623231bb267SMax Reitz         ret = qcow2_pre_write_overlap_check(bs, 0,
1624*d46a0bb2SKevin Wolf                 cluster_offset + offset_in_cluster, cur_bytes);
1625cf93980eSMax Reitz         if (ret < 0) {
1626cf93980eSMax Reitz             goto fail;
1627cf93980eSMax Reitz         }
1628cf93980eSMax Reitz 
162968d100e9SKevin Wolf         qemu_co_mutex_unlock(&s->lock);
163067a7a0ebSKevin Wolf         BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO);
16313cce16f4SKevin Wolf         trace_qcow2_writev_data(qemu_coroutine_self(),
1632*d46a0bb2SKevin Wolf                                 cluster_offset + offset_in_cluster);
1633*d46a0bb2SKevin Wolf         ret = bdrv_co_pwritev(bs->file->bs,
1634*d46a0bb2SKevin Wolf                               cluster_offset + offset_in_cluster,
1635*d46a0bb2SKevin Wolf                               cur_bytes, &hd_qiov, 0);
163668d100e9SKevin Wolf         qemu_co_mutex_lock(&s->lock);
163768d100e9SKevin Wolf         if (ret < 0) {
16383fc48d09SFrediano Ziglio             goto fail;
1639171e3d6bSKevin Wolf         }
1640f141eafeSaliguori 
164188c6588cSKevin Wolf         while (l2meta != NULL) {
164288c6588cSKevin Wolf             QCowL2Meta *next;
164388c6588cSKevin Wolf 
1644cf5c1a23SKevin Wolf             ret = qcow2_alloc_cluster_link_l2(bs, l2meta);
1645faf575c1SFrediano Ziglio             if (ret < 0) {
16463fc48d09SFrediano Ziglio                 goto fail;
1647faf575c1SFrediano Ziglio             }
1648faf575c1SFrediano Ziglio 
16494e95314eSKevin Wolf             /* Take the request off the list of running requests */
16504e95314eSKevin Wolf             if (l2meta->nb_clusters != 0) {
16514e95314eSKevin Wolf                 QLIST_REMOVE(l2meta, next_in_flight);
16524e95314eSKevin Wolf             }
16534e95314eSKevin Wolf 
16544e95314eSKevin Wolf             qemu_co_queue_restart_all(&l2meta->dependent_requests);
16554e95314eSKevin Wolf 
165688c6588cSKevin Wolf             next = l2meta->next;
1657cf5c1a23SKevin Wolf             g_free(l2meta);
165888c6588cSKevin Wolf             l2meta = next;
1659f50f88b9SKevin Wolf         }
16600fa9131aSKevin Wolf 
1661*d46a0bb2SKevin Wolf         bytes -= cur_bytes;
1662*d46a0bb2SKevin Wolf         offset += cur_bytes;
1663*d46a0bb2SKevin Wolf         bytes_done += cur_bytes;
1664*d46a0bb2SKevin Wolf         trace_qcow2_writev_done_part(qemu_coroutine_self(), cur_bytes);
16655ebaa27eSFrediano Ziglio     }
16663fc48d09SFrediano Ziglio     ret = 0;
1667faf575c1SFrediano Ziglio 
16683fc48d09SFrediano Ziglio fail:
16694e95314eSKevin Wolf     qemu_co_mutex_unlock(&s->lock);
16704e95314eSKevin Wolf 
167188c6588cSKevin Wolf     while (l2meta != NULL) {
167288c6588cSKevin Wolf         QCowL2Meta *next;
167388c6588cSKevin Wolf 
16744e95314eSKevin Wolf         if (l2meta->nb_clusters != 0) {
16754e95314eSKevin Wolf             QLIST_REMOVE(l2meta, next_in_flight);
16764e95314eSKevin Wolf         }
16774e95314eSKevin Wolf         qemu_co_queue_restart_all(&l2meta->dependent_requests);
167888c6588cSKevin Wolf 
167988c6588cSKevin Wolf         next = l2meta->next;
1680cf5c1a23SKevin Wolf         g_free(l2meta);
168188c6588cSKevin Wolf         l2meta = next;
1682cf5c1a23SKevin Wolf     }
16830fa9131aSKevin Wolf 
16843fc48d09SFrediano Ziglio     qemu_iovec_destroy(&hd_qiov);
1685dea43a65SFrediano Ziglio     qemu_vfree(cluster_data);
16863cce16f4SKevin Wolf     trace_qcow2_writev_done_req(qemu_coroutine_self(), ret);
168742496d62SKevin Wolf 
168868d100e9SKevin Wolf     return ret;
1689585f8587Sbellard }
1690585f8587Sbellard 
1691ec6d8912SKevin Wolf static int qcow2_inactivate(BlockDriverState *bs)
1692ec6d8912SKevin Wolf {
1693ec6d8912SKevin Wolf     BDRVQcow2State *s = bs->opaque;
1694ec6d8912SKevin Wolf     int ret, result = 0;
1695ec6d8912SKevin Wolf 
1696ec6d8912SKevin Wolf     ret = qcow2_cache_flush(bs, s->l2_table_cache);
1697ec6d8912SKevin Wolf     if (ret) {
1698ec6d8912SKevin Wolf         result = ret;
1699ec6d8912SKevin Wolf         error_report("Failed to flush the L2 table cache: %s",
1700ec6d8912SKevin Wolf                      strerror(-ret));
1701ec6d8912SKevin Wolf     }
1702ec6d8912SKevin Wolf 
1703ec6d8912SKevin Wolf     ret = qcow2_cache_flush(bs, s->refcount_block_cache);
1704ec6d8912SKevin Wolf     if (ret) {
1705ec6d8912SKevin Wolf         result = ret;
1706ec6d8912SKevin Wolf         error_report("Failed to flush the refcount block cache: %s",
1707ec6d8912SKevin Wolf                      strerror(-ret));
1708ec6d8912SKevin Wolf     }
1709ec6d8912SKevin Wolf 
1710ec6d8912SKevin Wolf     if (result == 0) {
1711ec6d8912SKevin Wolf         qcow2_mark_clean(bs);
1712ec6d8912SKevin Wolf     }
1713ec6d8912SKevin Wolf 
1714ec6d8912SKevin Wolf     return result;
1715ec6d8912SKevin Wolf }
1716ec6d8912SKevin Wolf 
17177c80ab3fSJes Sorensen static void qcow2_close(BlockDriverState *bs)
1718585f8587Sbellard {
1719ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
1720de82815dSKevin Wolf     qemu_vfree(s->l1_table);
1721cf93980eSMax Reitz     /* else pre-write overlap checks in cache_destroy may crash */
1722cf93980eSMax Reitz     s->l1_table = NULL;
172329c1a730SKevin Wolf 
1724140fd5a6SKevin Wolf     if (!(s->flags & BDRV_O_INACTIVE)) {
1725ec6d8912SKevin Wolf         qcow2_inactivate(bs);
17263b5e14c7SMax Reitz     }
1727c61d0004SStefan Hajnoczi 
1728279621c0SAlberto Garcia     cache_clean_timer_del(bs);
172929c1a730SKevin Wolf     qcow2_cache_destroy(bs, s->l2_table_cache);
173029c1a730SKevin Wolf     qcow2_cache_destroy(bs, s->refcount_block_cache);
173129c1a730SKevin Wolf 
1732f6fa64f6SDaniel P. Berrange     qcrypto_cipher_free(s->cipher);
1733f6fa64f6SDaniel P. Berrange     s->cipher = NULL;
1734f6fa64f6SDaniel P. Berrange 
17356744cbabSKevin Wolf     g_free(s->unknown_header_fields);
173675bab85cSKevin Wolf     cleanup_unknown_header_ext(bs);
17376744cbabSKevin Wolf 
1738e4603fe1SKevin Wolf     g_free(s->image_backing_file);
1739e4603fe1SKevin Wolf     g_free(s->image_backing_format);
1740e4603fe1SKevin Wolf 
17417267c094SAnthony Liguori     g_free(s->cluster_cache);
1742dea43a65SFrediano Ziglio     qemu_vfree(s->cluster_data);
1743ed6ccf0fSKevin Wolf     qcow2_refcount_close(bs);
174428c1202bSLi Zhi Hui     qcow2_free_snapshots(bs);
1745585f8587Sbellard }
1746585f8587Sbellard 
17475a8a30dbSKevin Wolf static void qcow2_invalidate_cache(BlockDriverState *bs, Error **errp)
174806d9260fSAnthony Liguori {
1749ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
175006d9260fSAnthony Liguori     int flags = s->flags;
1751f6fa64f6SDaniel P. Berrange     QCryptoCipher *cipher = NULL;
1752acdfb480SKevin Wolf     QDict *options;
17535a8a30dbSKevin Wolf     Error *local_err = NULL;
17545a8a30dbSKevin Wolf     int ret;
175506d9260fSAnthony Liguori 
175606d9260fSAnthony Liguori     /*
175706d9260fSAnthony Liguori      * Backing files are read-only which makes all of their metadata immutable,
175806d9260fSAnthony Liguori      * that means we don't have to worry about reopening them here.
175906d9260fSAnthony Liguori      */
176006d9260fSAnthony Liguori 
1761f6fa64f6SDaniel P. Berrange     cipher = s->cipher;
1762f6fa64f6SDaniel P. Berrange     s->cipher = NULL;
176306d9260fSAnthony Liguori 
176406d9260fSAnthony Liguori     qcow2_close(bs);
176506d9260fSAnthony Liguori 
1766ff99129aSKevin Wolf     memset(s, 0, sizeof(BDRVQcow2State));
1767d475e5acSKevin Wolf     options = qdict_clone_shallow(bs->options);
17685a8a30dbSKevin Wolf 
1769140fd5a6SKevin Wolf     flags &= ~BDRV_O_INACTIVE;
17705a8a30dbSKevin Wolf     ret = qcow2_open(bs, options, flags, &local_err);
1771a1904e48SMarkus Armbruster     QDECREF(options);
17725a8a30dbSKevin Wolf     if (local_err) {
1773e43bfd9cSMarkus Armbruster         error_propagate(errp, local_err);
1774e43bfd9cSMarkus Armbruster         error_prepend(errp, "Could not reopen qcow2 layer: ");
1775191fb11bSKevin Wolf         bs->drv = NULL;
17765a8a30dbSKevin Wolf         return;
17775a8a30dbSKevin Wolf     } else if (ret < 0) {
17785a8a30dbSKevin Wolf         error_setg_errno(errp, -ret, "Could not reopen qcow2 layer");
1779191fb11bSKevin Wolf         bs->drv = NULL;
17805a8a30dbSKevin Wolf         return;
17815a8a30dbSKevin Wolf     }
1782acdfb480SKevin Wolf 
1783f6fa64f6SDaniel P. Berrange     s->cipher = cipher;
178406d9260fSAnthony Liguori }
178506d9260fSAnthony Liguori 
1786e24e49e6SKevin Wolf static size_t header_ext_add(char *buf, uint32_t magic, const void *s,
1787e24e49e6SKevin Wolf     size_t len, size_t buflen)
1788756e6736SKevin Wolf {
1789e24e49e6SKevin Wolf     QCowExtension *ext_backing_fmt = (QCowExtension*) buf;
1790e24e49e6SKevin Wolf     size_t ext_len = sizeof(QCowExtension) + ((len + 7) & ~7);
1791756e6736SKevin Wolf 
1792e24e49e6SKevin Wolf     if (buflen < ext_len) {
1793756e6736SKevin Wolf         return -ENOSPC;
1794756e6736SKevin Wolf     }
1795756e6736SKevin Wolf 
1796e24e49e6SKevin Wolf     *ext_backing_fmt = (QCowExtension) {
1797e24e49e6SKevin Wolf         .magic  = cpu_to_be32(magic),
1798e24e49e6SKevin Wolf         .len    = cpu_to_be32(len),
1799e24e49e6SKevin Wolf     };
1800e24e49e6SKevin Wolf     memcpy(buf + sizeof(QCowExtension), s, len);
1801756e6736SKevin Wolf 
1802e24e49e6SKevin Wolf     return ext_len;
1803756e6736SKevin Wolf }
1804756e6736SKevin Wolf 
1805e24e49e6SKevin Wolf /*
1806e24e49e6SKevin Wolf  * Updates the qcow2 header, including the variable length parts of it, i.e.
1807e24e49e6SKevin Wolf  * the backing file name and all extensions. qcow2 was not designed to allow
1808e24e49e6SKevin Wolf  * such changes, so if we run out of space (we can only use the first cluster)
1809e24e49e6SKevin Wolf  * this function may fail.
1810e24e49e6SKevin Wolf  *
1811e24e49e6SKevin Wolf  * Returns 0 on success, -errno in error cases.
1812e24e49e6SKevin Wolf  */
1813e24e49e6SKevin Wolf int qcow2_update_header(BlockDriverState *bs)
1814e24e49e6SKevin Wolf {
1815ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
1816e24e49e6SKevin Wolf     QCowHeader *header;
1817e24e49e6SKevin Wolf     char *buf;
1818e24e49e6SKevin Wolf     size_t buflen = s->cluster_size;
1819e24e49e6SKevin Wolf     int ret;
1820e24e49e6SKevin Wolf     uint64_t total_size;
1821e24e49e6SKevin Wolf     uint32_t refcount_table_clusters;
18226744cbabSKevin Wolf     size_t header_length;
182375bab85cSKevin Wolf     Qcow2UnknownHeaderExtension *uext;
1824e24e49e6SKevin Wolf 
1825e24e49e6SKevin Wolf     buf = qemu_blockalign(bs, buflen);
1826e24e49e6SKevin Wolf 
1827e24e49e6SKevin Wolf     /* Header structure */
1828e24e49e6SKevin Wolf     header = (QCowHeader*) buf;
1829e24e49e6SKevin Wolf 
1830e24e49e6SKevin Wolf     if (buflen < sizeof(*header)) {
1831e24e49e6SKevin Wolf         ret = -ENOSPC;
1832e24e49e6SKevin Wolf         goto fail;
1833756e6736SKevin Wolf     }
1834756e6736SKevin Wolf 
18356744cbabSKevin Wolf     header_length = sizeof(*header) + s->unknown_header_fields_size;
1836e24e49e6SKevin Wolf     total_size = bs->total_sectors * BDRV_SECTOR_SIZE;
1837e24e49e6SKevin Wolf     refcount_table_clusters = s->refcount_table_size >> (s->cluster_bits - 3);
1838e24e49e6SKevin Wolf 
1839e24e49e6SKevin Wolf     *header = (QCowHeader) {
18406744cbabSKevin Wolf         /* Version 2 fields */
1841e24e49e6SKevin Wolf         .magic                  = cpu_to_be32(QCOW_MAGIC),
18426744cbabSKevin Wolf         .version                = cpu_to_be32(s->qcow_version),
1843e24e49e6SKevin Wolf         .backing_file_offset    = 0,
1844e24e49e6SKevin Wolf         .backing_file_size      = 0,
1845e24e49e6SKevin Wolf         .cluster_bits           = cpu_to_be32(s->cluster_bits),
1846e24e49e6SKevin Wolf         .size                   = cpu_to_be64(total_size),
1847e24e49e6SKevin Wolf         .crypt_method           = cpu_to_be32(s->crypt_method_header),
1848e24e49e6SKevin Wolf         .l1_size                = cpu_to_be32(s->l1_size),
1849e24e49e6SKevin Wolf         .l1_table_offset        = cpu_to_be64(s->l1_table_offset),
1850e24e49e6SKevin Wolf         .refcount_table_offset  = cpu_to_be64(s->refcount_table_offset),
1851e24e49e6SKevin Wolf         .refcount_table_clusters = cpu_to_be32(refcount_table_clusters),
1852e24e49e6SKevin Wolf         .nb_snapshots           = cpu_to_be32(s->nb_snapshots),
1853e24e49e6SKevin Wolf         .snapshots_offset       = cpu_to_be64(s->snapshots_offset),
18546744cbabSKevin Wolf 
18556744cbabSKevin Wolf         /* Version 3 fields */
18566744cbabSKevin Wolf         .incompatible_features  = cpu_to_be64(s->incompatible_features),
18576744cbabSKevin Wolf         .compatible_features    = cpu_to_be64(s->compatible_features),
18586744cbabSKevin Wolf         .autoclear_features     = cpu_to_be64(s->autoclear_features),
1859b6481f37SMax Reitz         .refcount_order         = cpu_to_be32(s->refcount_order),
18606744cbabSKevin Wolf         .header_length          = cpu_to_be32(header_length),
1861e24e49e6SKevin Wolf     };
1862e24e49e6SKevin Wolf 
18636744cbabSKevin Wolf     /* For older versions, write a shorter header */
18646744cbabSKevin Wolf     switch (s->qcow_version) {
18656744cbabSKevin Wolf     case 2:
18666744cbabSKevin Wolf         ret = offsetof(QCowHeader, incompatible_features);
18676744cbabSKevin Wolf         break;
18686744cbabSKevin Wolf     case 3:
18696744cbabSKevin Wolf         ret = sizeof(*header);
18706744cbabSKevin Wolf         break;
18716744cbabSKevin Wolf     default:
1872b6c14762SJim Meyering         ret = -EINVAL;
1873b6c14762SJim Meyering         goto fail;
18746744cbabSKevin Wolf     }
18756744cbabSKevin Wolf 
18766744cbabSKevin Wolf     buf += ret;
18776744cbabSKevin Wolf     buflen -= ret;
18786744cbabSKevin Wolf     memset(buf, 0, buflen);
18796744cbabSKevin Wolf 
18806744cbabSKevin Wolf     /* Preserve any unknown field in the header */
18816744cbabSKevin Wolf     if (s->unknown_header_fields_size) {
18826744cbabSKevin Wolf         if (buflen < s->unknown_header_fields_size) {
18836744cbabSKevin Wolf             ret = -ENOSPC;
18846744cbabSKevin Wolf             goto fail;
18856744cbabSKevin Wolf         }
18866744cbabSKevin Wolf 
18876744cbabSKevin Wolf         memcpy(buf, s->unknown_header_fields, s->unknown_header_fields_size);
18886744cbabSKevin Wolf         buf += s->unknown_header_fields_size;
18896744cbabSKevin Wolf         buflen -= s->unknown_header_fields_size;
18906744cbabSKevin Wolf     }
1891e24e49e6SKevin Wolf 
1892e24e49e6SKevin Wolf     /* Backing file format header extension */
1893e4603fe1SKevin Wolf     if (s->image_backing_format) {
1894e24e49e6SKevin Wolf         ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BACKING_FORMAT,
1895e4603fe1SKevin Wolf                              s->image_backing_format,
1896e4603fe1SKevin Wolf                              strlen(s->image_backing_format),
1897e24e49e6SKevin Wolf                              buflen);
1898756e6736SKevin Wolf         if (ret < 0) {
1899756e6736SKevin Wolf             goto fail;
1900756e6736SKevin Wolf         }
1901756e6736SKevin Wolf 
1902e24e49e6SKevin Wolf         buf += ret;
1903e24e49e6SKevin Wolf         buflen -= ret;
1904e24e49e6SKevin Wolf     }
1905756e6736SKevin Wolf 
1906cfcc4c62SKevin Wolf     /* Feature table */
19071a4828c7SKevin Wolf     if (s->qcow_version >= 3) {
1908cfcc4c62SKevin Wolf         Qcow2Feature features[] = {
1909c61d0004SStefan Hajnoczi             {
1910c61d0004SStefan Hajnoczi                 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
1911c61d0004SStefan Hajnoczi                 .bit  = QCOW2_INCOMPAT_DIRTY_BITNR,
1912c61d0004SStefan Hajnoczi                 .name = "dirty bit",
1913c61d0004SStefan Hajnoczi             },
1914bfe8043eSStefan Hajnoczi             {
191569c98726SMax Reitz                 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
191669c98726SMax Reitz                 .bit  = QCOW2_INCOMPAT_CORRUPT_BITNR,
191769c98726SMax Reitz                 .name = "corrupt bit",
191869c98726SMax Reitz             },
191969c98726SMax Reitz             {
1920bfe8043eSStefan Hajnoczi                 .type = QCOW2_FEAT_TYPE_COMPATIBLE,
1921bfe8043eSStefan Hajnoczi                 .bit  = QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR,
1922bfe8043eSStefan Hajnoczi                 .name = "lazy refcounts",
1923bfe8043eSStefan Hajnoczi             },
1924cfcc4c62SKevin Wolf         };
1925cfcc4c62SKevin Wolf 
1926cfcc4c62SKevin Wolf         ret = header_ext_add(buf, QCOW2_EXT_MAGIC_FEATURE_TABLE,
1927cfcc4c62SKevin Wolf                              features, sizeof(features), buflen);
1928cfcc4c62SKevin Wolf         if (ret < 0) {
1929cfcc4c62SKevin Wolf             goto fail;
1930cfcc4c62SKevin Wolf         }
1931cfcc4c62SKevin Wolf         buf += ret;
1932cfcc4c62SKevin Wolf         buflen -= ret;
19331a4828c7SKevin Wolf     }
1934cfcc4c62SKevin Wolf 
193575bab85cSKevin Wolf     /* Keep unknown header extensions */
193675bab85cSKevin Wolf     QLIST_FOREACH(uext, &s->unknown_header_ext, next) {
193775bab85cSKevin Wolf         ret = header_ext_add(buf, uext->magic, uext->data, uext->len, buflen);
193875bab85cSKevin Wolf         if (ret < 0) {
193975bab85cSKevin Wolf             goto fail;
194075bab85cSKevin Wolf         }
194175bab85cSKevin Wolf 
194275bab85cSKevin Wolf         buf += ret;
194375bab85cSKevin Wolf         buflen -= ret;
194475bab85cSKevin Wolf     }
194575bab85cSKevin Wolf 
1946e24e49e6SKevin Wolf     /* End of header extensions */
1947e24e49e6SKevin Wolf     ret = header_ext_add(buf, QCOW2_EXT_MAGIC_END, NULL, 0, buflen);
1948756e6736SKevin Wolf     if (ret < 0) {
1949756e6736SKevin Wolf         goto fail;
1950756e6736SKevin Wolf     }
1951756e6736SKevin Wolf 
1952e24e49e6SKevin Wolf     buf += ret;
1953e24e49e6SKevin Wolf     buflen -= ret;
1954e24e49e6SKevin Wolf 
1955e24e49e6SKevin Wolf     /* Backing file name */
1956e4603fe1SKevin Wolf     if (s->image_backing_file) {
1957e4603fe1SKevin Wolf         size_t backing_file_len = strlen(s->image_backing_file);
1958e24e49e6SKevin Wolf 
1959e24e49e6SKevin Wolf         if (buflen < backing_file_len) {
1960e24e49e6SKevin Wolf             ret = -ENOSPC;
1961e24e49e6SKevin Wolf             goto fail;
1962e24e49e6SKevin Wolf         }
1963e24e49e6SKevin Wolf 
196400ea1881SJim Meyering         /* Using strncpy is ok here, since buf is not NUL-terminated. */
1965e4603fe1SKevin Wolf         strncpy(buf, s->image_backing_file, buflen);
1966e24e49e6SKevin Wolf 
1967e24e49e6SKevin Wolf         header->backing_file_offset = cpu_to_be64(buf - ((char*) header));
1968e24e49e6SKevin Wolf         header->backing_file_size   = cpu_to_be32(backing_file_len);
1969e24e49e6SKevin Wolf     }
1970e24e49e6SKevin Wolf 
1971e24e49e6SKevin Wolf     /* Write the new header */
19729a4f4c31SKevin Wolf     ret = bdrv_pwrite(bs->file->bs, 0, header, s->cluster_size);
1973756e6736SKevin Wolf     if (ret < 0) {
1974756e6736SKevin Wolf         goto fail;
1975756e6736SKevin Wolf     }
1976756e6736SKevin Wolf 
1977756e6736SKevin Wolf     ret = 0;
1978756e6736SKevin Wolf fail:
1979e24e49e6SKevin Wolf     qemu_vfree(header);
1980756e6736SKevin Wolf     return ret;
1981756e6736SKevin Wolf }
1982756e6736SKevin Wolf 
1983756e6736SKevin Wolf static int qcow2_change_backing_file(BlockDriverState *bs,
1984756e6736SKevin Wolf     const char *backing_file, const char *backing_fmt)
1985756e6736SKevin Wolf {
1986ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
1987e4603fe1SKevin Wolf 
19884e876bcfSMax Reitz     if (backing_file && strlen(backing_file) > 1023) {
19894e876bcfSMax Reitz         return -EINVAL;
19904e876bcfSMax Reitz     }
19914e876bcfSMax Reitz 
1992e24e49e6SKevin Wolf     pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
1993e24e49e6SKevin Wolf     pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
1994e24e49e6SKevin Wolf 
1995e4603fe1SKevin Wolf     g_free(s->image_backing_file);
1996e4603fe1SKevin Wolf     g_free(s->image_backing_format);
1997e4603fe1SKevin Wolf 
1998e4603fe1SKevin Wolf     s->image_backing_file = backing_file ? g_strdup(bs->backing_file) : NULL;
1999e4603fe1SKevin Wolf     s->image_backing_format = backing_fmt ? g_strdup(bs->backing_format) : NULL;
2000e4603fe1SKevin Wolf 
2001e24e49e6SKevin Wolf     return qcow2_update_header(bs);
2002756e6736SKevin Wolf }
2003756e6736SKevin Wolf 
2004a35e1c17SKevin Wolf static int preallocate(BlockDriverState *bs)
2005a35e1c17SKevin Wolf {
2006*d46a0bb2SKevin Wolf     uint64_t bytes;
2007a35e1c17SKevin Wolf     uint64_t offset;
2008060bee89SKevin Wolf     uint64_t host_offset = 0;
2009*d46a0bb2SKevin Wolf     unsigned int cur_bytes;
2010148da7eaSKevin Wolf     int ret;
2011f50f88b9SKevin Wolf     QCowL2Meta *meta;
2012a35e1c17SKevin Wolf 
2013*d46a0bb2SKevin Wolf     bytes = bdrv_getlength(bs);
2014a35e1c17SKevin Wolf     offset = 0;
2015a35e1c17SKevin Wolf 
2016*d46a0bb2SKevin Wolf     while (bytes) {
2017*d46a0bb2SKevin Wolf         cur_bytes = MIN(bytes, INT_MAX);
2018*d46a0bb2SKevin Wolf         ret = qcow2_alloc_cluster_offset(bs, offset, &cur_bytes,
2019060bee89SKevin Wolf                                          &host_offset, &meta);
2020148da7eaSKevin Wolf         if (ret < 0) {
202119dbcbf7SKevin Wolf             return ret;
2022a35e1c17SKevin Wolf         }
2023a35e1c17SKevin Wolf 
2024c792707fSStefan Hajnoczi         while (meta) {
2025c792707fSStefan Hajnoczi             QCowL2Meta *next = meta->next;
2026c792707fSStefan Hajnoczi 
2027f50f88b9SKevin Wolf             ret = qcow2_alloc_cluster_link_l2(bs, meta);
202819dbcbf7SKevin Wolf             if (ret < 0) {
20297c2bbf4aSHu Tao                 qcow2_free_any_clusters(bs, meta->alloc_offset,
20307c2bbf4aSHu Tao                                         meta->nb_clusters, QCOW2_DISCARD_NEVER);
203119dbcbf7SKevin Wolf                 return ret;
2032a35e1c17SKevin Wolf             }
2033a35e1c17SKevin Wolf 
20347c2bbf4aSHu Tao             /* There are no dependent requests, but we need to remove our
20357c2bbf4aSHu Tao              * request from the list of in-flight requests */
20364e95314eSKevin Wolf             QLIST_REMOVE(meta, next_in_flight);
2037c792707fSStefan Hajnoczi 
2038c792707fSStefan Hajnoczi             g_free(meta);
2039c792707fSStefan Hajnoczi             meta = next;
2040f50f88b9SKevin Wolf         }
2041f214978aSKevin Wolf 
2042a35e1c17SKevin Wolf         /* TODO Preallocate data if requested */
2043a35e1c17SKevin Wolf 
2044*d46a0bb2SKevin Wolf         bytes -= cur_bytes;
2045*d46a0bb2SKevin Wolf         offset += cur_bytes;
2046a35e1c17SKevin Wolf     }
2047a35e1c17SKevin Wolf 
2048a35e1c17SKevin Wolf     /*
2049a35e1c17SKevin Wolf      * It is expected that the image file is large enough to actually contain
2050a35e1c17SKevin Wolf      * all of the allocated clusters (otherwise we get failing reads after
2051a35e1c17SKevin Wolf      * EOF). Extend the image to the last allocated sector.
2052a35e1c17SKevin Wolf      */
2053060bee89SKevin Wolf     if (host_offset != 0) {
2054*d46a0bb2SKevin Wolf         uint8_t data = 0;
2055*d46a0bb2SKevin Wolf         ret = bdrv_pwrite(bs->file->bs, (host_offset + cur_bytes) - 1,
2056*d46a0bb2SKevin Wolf                           &data, 1);
205719dbcbf7SKevin Wolf         if (ret < 0) {
205819dbcbf7SKevin Wolf             return ret;
205919dbcbf7SKevin Wolf         }
2060a35e1c17SKevin Wolf     }
2061a35e1c17SKevin Wolf 
2062a35e1c17SKevin Wolf     return 0;
2063a35e1c17SKevin Wolf }
2064a35e1c17SKevin Wolf 
20657c80ab3fSJes Sorensen static int qcow2_create2(const char *filename, int64_t total_size,
2066a9420734SKevin Wolf                          const char *backing_file, const char *backing_format,
2067ffeaac9bSHu Tao                          int flags, size_t cluster_size, PreallocMode prealloc,
2068bd4b167fSMax Reitz                          QemuOpts *opts, int version, int refcount_order,
20693ef6c40aSMax Reitz                          Error **errp)
2070a9420734SKevin Wolf {
2071a9420734SKevin Wolf     int cluster_bits;
2072e6641719SMax Reitz     QDict *options;
2073e6641719SMax Reitz 
2074e6641719SMax Reitz     /* Calculate cluster_bits */
2075786a4ea8SStefan Hajnoczi     cluster_bits = ctz32(cluster_size);
2076a9420734SKevin Wolf     if (cluster_bits < MIN_CLUSTER_BITS || cluster_bits > MAX_CLUSTER_BITS ||
2077a9420734SKevin Wolf         (1 << cluster_bits) != cluster_size)
2078a9420734SKevin Wolf     {
20793ef6c40aSMax Reitz         error_setg(errp, "Cluster size must be a power of two between %d and "
20803ef6c40aSMax Reitz                    "%dk", 1 << MIN_CLUSTER_BITS, 1 << (MAX_CLUSTER_BITS - 10));
2081a9420734SKevin Wolf         return -EINVAL;
2082a9420734SKevin Wolf     }
2083a9420734SKevin Wolf 
2084a9420734SKevin Wolf     /*
2085a9420734SKevin Wolf      * Open the image file and write a minimal qcow2 header.
2086a9420734SKevin Wolf      *
2087a9420734SKevin Wolf      * We keep things simple and start with a zero-sized image. We also
2088a9420734SKevin Wolf      * do without refcount blocks or a L1 table for now. We'll fix the
2089a9420734SKevin Wolf      * inconsistency later.
2090a9420734SKevin Wolf      *
2091a9420734SKevin Wolf      * We do need a refcount table because growing the refcount table means
2092a9420734SKevin Wolf      * allocating two new refcount blocks - the seconds of which would be at
2093a9420734SKevin Wolf      * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
2094a9420734SKevin Wolf      * size for any qcow2 image.
2095a9420734SKevin Wolf      */
209623588797SKevin Wolf     BlockBackend *blk;
2097f8413b3cSKevin Wolf     QCowHeader *header;
2098b106ad91SKevin Wolf     uint64_t* refcount_table;
20993ef6c40aSMax Reitz     Error *local_err = NULL;
2100a9420734SKevin Wolf     int ret;
2101a9420734SKevin Wolf 
21020e4271b7SHu Tao     if (prealloc == PREALLOC_MODE_FULL || prealloc == PREALLOC_MODE_FALLOC) {
2103bd4b167fSMax Reitz         /* Note: The following calculation does not need to be exact; if it is a
2104bd4b167fSMax Reitz          * bit off, either some bytes will be "leaked" (which is fine) or we
2105bd4b167fSMax Reitz          * will need to increase the file size by some bytes (which is fine,
2106bd4b167fSMax Reitz          * too, as long as the bulk is allocated here). Therefore, using
2107bd4b167fSMax Reitz          * floating point arithmetic is fine. */
21080e4271b7SHu Tao         int64_t meta_size = 0;
21090e4271b7SHu Tao         uint64_t nreftablee, nrefblocke, nl1e, nl2e;
21100e4271b7SHu Tao         int64_t aligned_total_size = align_offset(total_size, cluster_size);
2111bd4b167fSMax Reitz         int refblock_bits, refblock_size;
2112bd4b167fSMax Reitz         /* refcount entry size in bytes */
2113bd4b167fSMax Reitz         double rces = (1 << refcount_order) / 8.;
2114bd4b167fSMax Reitz 
2115bd4b167fSMax Reitz         /* see qcow2_open() */
2116bd4b167fSMax Reitz         refblock_bits = cluster_bits - (refcount_order - 3);
2117bd4b167fSMax Reitz         refblock_size = 1 << refblock_bits;
21180e4271b7SHu Tao 
21190e4271b7SHu Tao         /* header: 1 cluster */
21200e4271b7SHu Tao         meta_size += cluster_size;
21210e4271b7SHu Tao 
21220e4271b7SHu Tao         /* total size of L2 tables */
21230e4271b7SHu Tao         nl2e = aligned_total_size / cluster_size;
21240e4271b7SHu Tao         nl2e = align_offset(nl2e, cluster_size / sizeof(uint64_t));
21250e4271b7SHu Tao         meta_size += nl2e * sizeof(uint64_t);
21260e4271b7SHu Tao 
21270e4271b7SHu Tao         /* total size of L1 tables */
21280e4271b7SHu Tao         nl1e = nl2e * sizeof(uint64_t) / cluster_size;
21290e4271b7SHu Tao         nl1e = align_offset(nl1e, cluster_size / sizeof(uint64_t));
21300e4271b7SHu Tao         meta_size += nl1e * sizeof(uint64_t);
21310e4271b7SHu Tao 
21320e4271b7SHu Tao         /* total size of refcount blocks
21330e4271b7SHu Tao          *
21340e4271b7SHu Tao          * note: every host cluster is reference-counted, including metadata
21350e4271b7SHu Tao          * (even refcount blocks are recursively included).
21360e4271b7SHu Tao          * Let:
21370e4271b7SHu Tao          *   a = total_size (this is the guest disk size)
21380e4271b7SHu Tao          *   m = meta size not including refcount blocks and refcount tables
21390e4271b7SHu Tao          *   c = cluster size
21400e4271b7SHu Tao          *   y1 = number of refcount blocks entries
21410e4271b7SHu Tao          *   y2 = meta size including everything
2142bd4b167fSMax Reitz          *   rces = refcount entry size in bytes
21430e4271b7SHu Tao          * then,
21440e4271b7SHu Tao          *   y1 = (y2 + a)/c
2145bd4b167fSMax Reitz          *   y2 = y1 * rces + y1 * rces * sizeof(u64) / c + m
21460e4271b7SHu Tao          * we can get y1:
2147bd4b167fSMax Reitz          *   y1 = (a + m) / (c - rces - rces * sizeof(u64) / c)
21480e4271b7SHu Tao          */
2149bd4b167fSMax Reitz         nrefblocke = (aligned_total_size + meta_size + cluster_size)
2150bd4b167fSMax Reitz                    / (cluster_size - rces - rces * sizeof(uint64_t)
2151bd4b167fSMax Reitz                                                  / cluster_size);
2152bd4b167fSMax Reitz         meta_size += DIV_ROUND_UP(nrefblocke, refblock_size) * cluster_size;
21530e4271b7SHu Tao 
21540e4271b7SHu Tao         /* total size of refcount tables */
2155bd4b167fSMax Reitz         nreftablee = nrefblocke / refblock_size;
21560e4271b7SHu Tao         nreftablee = align_offset(nreftablee, cluster_size / sizeof(uint64_t));
21570e4271b7SHu Tao         meta_size += nreftablee * sizeof(uint64_t);
21580e4271b7SHu Tao 
21590e4271b7SHu Tao         qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
216039101f25SMarkus Armbruster                             aligned_total_size + meta_size, &error_abort);
2161f43e47dbSMarkus Armbruster         qemu_opt_set(opts, BLOCK_OPT_PREALLOC, PreallocMode_lookup[prealloc],
2162f43e47dbSMarkus Armbruster                      &error_abort);
21630e4271b7SHu Tao     }
21640e4271b7SHu Tao 
2165c282e1fdSChunyan Liu     ret = bdrv_create_file(filename, opts, &local_err);
2166a9420734SKevin Wolf     if (ret < 0) {
21673ef6c40aSMax Reitz         error_propagate(errp, local_err);
2168a9420734SKevin Wolf         return ret;
2169a9420734SKevin Wolf     }
2170a9420734SKevin Wolf 
2171efaa7c4eSMax Reitz     blk = blk_new_open(filename, NULL, NULL,
217272e775c7SKevin Wolf                        BDRV_O_RDWR | BDRV_O_PROTOCOL, &local_err);
217323588797SKevin Wolf     if (blk == NULL) {
21743ef6c40aSMax Reitz         error_propagate(errp, local_err);
217523588797SKevin Wolf         return -EIO;
2176a9420734SKevin Wolf     }
2177a9420734SKevin Wolf 
217823588797SKevin Wolf     blk_set_allow_write_beyond_eof(blk, true);
217923588797SKevin Wolf 
2180a9420734SKevin Wolf     /* Write the header */
2181f8413b3cSKevin Wolf     QEMU_BUILD_BUG_ON((1 << MIN_CLUSTER_BITS) < sizeof(*header));
2182f8413b3cSKevin Wolf     header = g_malloc0(cluster_size);
2183f8413b3cSKevin Wolf     *header = (QCowHeader) {
2184f8413b3cSKevin Wolf         .magic                      = cpu_to_be32(QCOW_MAGIC),
2185f8413b3cSKevin Wolf         .version                    = cpu_to_be32(version),
2186f8413b3cSKevin Wolf         .cluster_bits               = cpu_to_be32(cluster_bits),
2187f8413b3cSKevin Wolf         .size                       = cpu_to_be64(0),
2188f8413b3cSKevin Wolf         .l1_table_offset            = cpu_to_be64(0),
2189f8413b3cSKevin Wolf         .l1_size                    = cpu_to_be32(0),
2190f8413b3cSKevin Wolf         .refcount_table_offset      = cpu_to_be64(cluster_size),
2191f8413b3cSKevin Wolf         .refcount_table_clusters    = cpu_to_be32(1),
2192bd4b167fSMax Reitz         .refcount_order             = cpu_to_be32(refcount_order),
2193f8413b3cSKevin Wolf         .header_length              = cpu_to_be32(sizeof(*header)),
2194f8413b3cSKevin Wolf     };
2195a9420734SKevin Wolf 
2196a9420734SKevin Wolf     if (flags & BLOCK_FLAG_ENCRYPT) {
2197f8413b3cSKevin Wolf         header->crypt_method = cpu_to_be32(QCOW_CRYPT_AES);
2198a9420734SKevin Wolf     } else {
2199f8413b3cSKevin Wolf         header->crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
2200a9420734SKevin Wolf     }
2201a9420734SKevin Wolf 
2202bfe8043eSStefan Hajnoczi     if (flags & BLOCK_FLAG_LAZY_REFCOUNTS) {
2203f8413b3cSKevin Wolf         header->compatible_features |=
2204bfe8043eSStefan Hajnoczi             cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS);
2205bfe8043eSStefan Hajnoczi     }
2206bfe8043eSStefan Hajnoczi 
22078341f00dSEric Blake     ret = blk_pwrite(blk, 0, header, cluster_size, 0);
2208f8413b3cSKevin Wolf     g_free(header);
2209a9420734SKevin Wolf     if (ret < 0) {
22103ef6c40aSMax Reitz         error_setg_errno(errp, -ret, "Could not write qcow2 header");
2211a9420734SKevin Wolf         goto out;
2212a9420734SKevin Wolf     }
2213a9420734SKevin Wolf 
2214b106ad91SKevin Wolf     /* Write a refcount table with one refcount block */
2215b106ad91SKevin Wolf     refcount_table = g_malloc0(2 * cluster_size);
2216b106ad91SKevin Wolf     refcount_table[0] = cpu_to_be64(2 * cluster_size);
22178341f00dSEric Blake     ret = blk_pwrite(blk, cluster_size, refcount_table, 2 * cluster_size, 0);
22187267c094SAnthony Liguori     g_free(refcount_table);
2219a9420734SKevin Wolf 
2220a9420734SKevin Wolf     if (ret < 0) {
22213ef6c40aSMax Reitz         error_setg_errno(errp, -ret, "Could not write refcount table");
2222a9420734SKevin Wolf         goto out;
2223a9420734SKevin Wolf     }
2224a9420734SKevin Wolf 
222523588797SKevin Wolf     blk_unref(blk);
222623588797SKevin Wolf     blk = NULL;
2227a9420734SKevin Wolf 
2228a9420734SKevin Wolf     /*
2229a9420734SKevin Wolf      * And now open the image and make it consistent first (i.e. increase the
2230a9420734SKevin Wolf      * refcount of the cluster that is occupied by the header and the refcount
2231a9420734SKevin Wolf      * table)
2232a9420734SKevin Wolf      */
2233e6641719SMax Reitz     options = qdict_new();
2234e6641719SMax Reitz     qdict_put(options, "driver", qstring_from_str("qcow2"));
2235efaa7c4eSMax Reitz     blk = blk_new_open(filename, NULL, options,
223672e775c7SKevin Wolf                        BDRV_O_RDWR | BDRV_O_NO_FLUSH, &local_err);
223723588797SKevin Wolf     if (blk == NULL) {
22383ef6c40aSMax Reitz         error_propagate(errp, local_err);
223923588797SKevin Wolf         ret = -EIO;
2240a9420734SKevin Wolf         goto out;
2241a9420734SKevin Wolf     }
2242a9420734SKevin Wolf 
224323588797SKevin Wolf     ret = qcow2_alloc_clusters(blk_bs(blk), 3 * cluster_size);
2244a9420734SKevin Wolf     if (ret < 0) {
22453ef6c40aSMax Reitz         error_setg_errno(errp, -ret, "Could not allocate clusters for qcow2 "
22463ef6c40aSMax Reitz                          "header and refcount table");
2247a9420734SKevin Wolf         goto out;
2248a9420734SKevin Wolf 
2249a9420734SKevin Wolf     } else if (ret != 0) {
2250a9420734SKevin Wolf         error_report("Huh, first cluster in empty image is already in use?");
2251a9420734SKevin Wolf         abort();
2252a9420734SKevin Wolf     }
2253a9420734SKevin Wolf 
2254b527c9b3SKevin Wolf     /* Create a full header (including things like feature table) */
225523588797SKevin Wolf     ret = qcow2_update_header(blk_bs(blk));
2256b527c9b3SKevin Wolf     if (ret < 0) {
2257b527c9b3SKevin Wolf         error_setg_errno(errp, -ret, "Could not update qcow2 header");
2258b527c9b3SKevin Wolf         goto out;
2259b527c9b3SKevin Wolf     }
2260b527c9b3SKevin Wolf 
2261a9420734SKevin Wolf     /* Okay, now that we have a valid image, let's give it the right size */
226223588797SKevin Wolf     ret = blk_truncate(blk, total_size);
2263a9420734SKevin Wolf     if (ret < 0) {
22643ef6c40aSMax Reitz         error_setg_errno(errp, -ret, "Could not resize image");
2265a9420734SKevin Wolf         goto out;
2266a9420734SKevin Wolf     }
2267a9420734SKevin Wolf 
2268a9420734SKevin Wolf     /* Want a backing file? There you go.*/
2269a9420734SKevin Wolf     if (backing_file) {
227023588797SKevin Wolf         ret = bdrv_change_backing_file(blk_bs(blk), backing_file, backing_format);
2271a9420734SKevin Wolf         if (ret < 0) {
22723ef6c40aSMax Reitz             error_setg_errno(errp, -ret, "Could not assign backing file '%s' "
22733ef6c40aSMax Reitz                              "with format '%s'", backing_file, backing_format);
2274a9420734SKevin Wolf             goto out;
2275a9420734SKevin Wolf         }
2276a9420734SKevin Wolf     }
2277a9420734SKevin Wolf 
2278a9420734SKevin Wolf     /* And if we're supposed to preallocate metadata, do that now */
22790e4271b7SHu Tao     if (prealloc != PREALLOC_MODE_OFF) {
228023588797SKevin Wolf         BDRVQcow2State *s = blk_bs(blk)->opaque;
228115552c4aSZhi Yong Wu         qemu_co_mutex_lock(&s->lock);
228223588797SKevin Wolf         ret = preallocate(blk_bs(blk));
228315552c4aSZhi Yong Wu         qemu_co_mutex_unlock(&s->lock);
2284a9420734SKevin Wolf         if (ret < 0) {
22853ef6c40aSMax Reitz             error_setg_errno(errp, -ret, "Could not preallocate metadata");
2286a9420734SKevin Wolf             goto out;
2287a9420734SKevin Wolf         }
2288a9420734SKevin Wolf     }
2289a9420734SKevin Wolf 
229023588797SKevin Wolf     blk_unref(blk);
229123588797SKevin Wolf     blk = NULL;
2292ba2ab2f2SMax Reitz 
2293ba2ab2f2SMax Reitz     /* Reopen the image without BDRV_O_NO_FLUSH to flush it before returning */
2294e6641719SMax Reitz     options = qdict_new();
2295e6641719SMax Reitz     qdict_put(options, "driver", qstring_from_str("qcow2"));
2296efaa7c4eSMax Reitz     blk = blk_new_open(filename, NULL, options,
229772e775c7SKevin Wolf                        BDRV_O_RDWR | BDRV_O_NO_BACKING, &local_err);
229823588797SKevin Wolf     if (blk == NULL) {
2299ba2ab2f2SMax Reitz         error_propagate(errp, local_err);
230023588797SKevin Wolf         ret = -EIO;
2301ba2ab2f2SMax Reitz         goto out;
2302ba2ab2f2SMax Reitz     }
2303ba2ab2f2SMax Reitz 
2304a9420734SKevin Wolf     ret = 0;
2305a9420734SKevin Wolf out:
230623588797SKevin Wolf     if (blk) {
230723588797SKevin Wolf         blk_unref(blk);
2308f67503e5SMax Reitz     }
2309a9420734SKevin Wolf     return ret;
2310a9420734SKevin Wolf }
2311de5f3f40SKevin Wolf 
23121bd0e2d1SChunyan Liu static int qcow2_create(const char *filename, QemuOpts *opts, Error **errp)
2313de5f3f40SKevin Wolf {
23141bd0e2d1SChunyan Liu     char *backing_file = NULL;
23151bd0e2d1SChunyan Liu     char *backing_fmt = NULL;
23161bd0e2d1SChunyan Liu     char *buf = NULL;
2317180e9526SHu Tao     uint64_t size = 0;
2318de5f3f40SKevin Wolf     int flags = 0;
231999cce9faSKevin Wolf     size_t cluster_size = DEFAULT_CLUSTER_SIZE;
2320ffeaac9bSHu Tao     PreallocMode prealloc;
23218ad1898cSKevin Wolf     int version = 3;
2322bd4b167fSMax Reitz     uint64_t refcount_bits = 16;
2323bd4b167fSMax Reitz     int refcount_order;
23243ef6c40aSMax Reitz     Error *local_err = NULL;
23253ef6c40aSMax Reitz     int ret;
2326de5f3f40SKevin Wolf 
2327de5f3f40SKevin Wolf     /* Read out options */
2328180e9526SHu Tao     size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
2329c2eb918eSHu Tao                     BDRV_SECTOR_SIZE);
23301bd0e2d1SChunyan Liu     backing_file = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
23311bd0e2d1SChunyan Liu     backing_fmt = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FMT);
23321bd0e2d1SChunyan Liu     if (qemu_opt_get_bool_del(opts, BLOCK_OPT_ENCRYPT, false)) {
23331bd0e2d1SChunyan Liu         flags |= BLOCK_FLAG_ENCRYPT;
2334de5f3f40SKevin Wolf     }
23351bd0e2d1SChunyan Liu     cluster_size = qemu_opt_get_size_del(opts, BLOCK_OPT_CLUSTER_SIZE,
23361bd0e2d1SChunyan Liu                                          DEFAULT_CLUSTER_SIZE);
23371bd0e2d1SChunyan Liu     buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
2338ffeaac9bSHu Tao     prealloc = qapi_enum_parse(PreallocMode_lookup, buf,
23397fb1cf16SEric Blake                                PREALLOC_MODE__MAX, PREALLOC_MODE_OFF,
2340ffeaac9bSHu Tao                                &local_err);
2341ffeaac9bSHu Tao     if (local_err) {
2342ffeaac9bSHu Tao         error_propagate(errp, local_err);
23431bd0e2d1SChunyan Liu         ret = -EINVAL;
23441bd0e2d1SChunyan Liu         goto finish;
2345de5f3f40SKevin Wolf     }
23461bd0e2d1SChunyan Liu     g_free(buf);
23471bd0e2d1SChunyan Liu     buf = qemu_opt_get_del(opts, BLOCK_OPT_COMPAT_LEVEL);
23481bd0e2d1SChunyan Liu     if (!buf) {
23499117b477SKevin Wolf         /* keep the default */
23501bd0e2d1SChunyan Liu     } else if (!strcmp(buf, "0.10")) {
23516744cbabSKevin Wolf         version = 2;
23521bd0e2d1SChunyan Liu     } else if (!strcmp(buf, "1.1")) {
23536744cbabSKevin Wolf         version = 3;
23546744cbabSKevin Wolf     } else {
23551bd0e2d1SChunyan Liu         error_setg(errp, "Invalid compatibility level: '%s'", buf);
23561bd0e2d1SChunyan Liu         ret = -EINVAL;
23571bd0e2d1SChunyan Liu         goto finish;
23586744cbabSKevin Wolf     }
23591bd0e2d1SChunyan Liu 
23601bd0e2d1SChunyan Liu     if (qemu_opt_get_bool_del(opts, BLOCK_OPT_LAZY_REFCOUNTS, false)) {
23611bd0e2d1SChunyan Liu         flags |= BLOCK_FLAG_LAZY_REFCOUNTS;
2362de5f3f40SKevin Wolf     }
2363de5f3f40SKevin Wolf 
2364ffeaac9bSHu Tao     if (backing_file && prealloc != PREALLOC_MODE_OFF) {
23653ef6c40aSMax Reitz         error_setg(errp, "Backing file and preallocation cannot be used at "
23663ef6c40aSMax Reitz                    "the same time");
23671bd0e2d1SChunyan Liu         ret = -EINVAL;
23681bd0e2d1SChunyan Liu         goto finish;
2369de5f3f40SKevin Wolf     }
2370de5f3f40SKevin Wolf 
2371bfe8043eSStefan Hajnoczi     if (version < 3 && (flags & BLOCK_FLAG_LAZY_REFCOUNTS)) {
23723ef6c40aSMax Reitz         error_setg(errp, "Lazy refcounts only supported with compatibility "
23733ef6c40aSMax Reitz                    "level 1.1 and above (use compat=1.1 or greater)");
23741bd0e2d1SChunyan Liu         ret = -EINVAL;
23751bd0e2d1SChunyan Liu         goto finish;
2376bfe8043eSStefan Hajnoczi     }
2377bfe8043eSStefan Hajnoczi 
237806d05fa7SMax Reitz     refcount_bits = qemu_opt_get_number_del(opts, BLOCK_OPT_REFCOUNT_BITS,
237906d05fa7SMax Reitz                                             refcount_bits);
238006d05fa7SMax Reitz     if (refcount_bits > 64 || !is_power_of_2(refcount_bits)) {
238106d05fa7SMax Reitz         error_setg(errp, "Refcount width must be a power of two and may not "
238206d05fa7SMax Reitz                    "exceed 64 bits");
238306d05fa7SMax Reitz         ret = -EINVAL;
238406d05fa7SMax Reitz         goto finish;
238506d05fa7SMax Reitz     }
238606d05fa7SMax Reitz 
2387bd4b167fSMax Reitz     if (version < 3 && refcount_bits != 16) {
2388bd4b167fSMax Reitz         error_setg(errp, "Different refcount widths than 16 bits require "
2389bd4b167fSMax Reitz                    "compatibility level 1.1 or above (use compat=1.1 or "
2390bd4b167fSMax Reitz                    "greater)");
2391bd4b167fSMax Reitz         ret = -EINVAL;
2392bd4b167fSMax Reitz         goto finish;
2393bd4b167fSMax Reitz     }
2394bd4b167fSMax Reitz 
2395786a4ea8SStefan Hajnoczi     refcount_order = ctz32(refcount_bits);
2396bd4b167fSMax Reitz 
2397180e9526SHu Tao     ret = qcow2_create2(filename, size, backing_file, backing_fmt, flags,
2398bd4b167fSMax Reitz                         cluster_size, prealloc, opts, version, refcount_order,
2399bd4b167fSMax Reitz                         &local_err);
240084d18f06SMarkus Armbruster     if (local_err) {
24013ef6c40aSMax Reitz         error_propagate(errp, local_err);
24023ef6c40aSMax Reitz     }
24031bd0e2d1SChunyan Liu 
24041bd0e2d1SChunyan Liu finish:
24051bd0e2d1SChunyan Liu     g_free(backing_file);
24061bd0e2d1SChunyan Liu     g_free(backing_fmt);
24071bd0e2d1SChunyan Liu     g_free(buf);
24083ef6c40aSMax Reitz     return ret;
2409de5f3f40SKevin Wolf }
2410de5f3f40SKevin Wolf 
24112928abceSDenis V. Lunev 
2412ebb718a5SEric Blake static bool is_zero_sectors(BlockDriverState *bs, int64_t start,
2413ebb718a5SEric Blake                             uint32_t count)
24142928abceSDenis V. Lunev {
24152928abceSDenis V. Lunev     int nr;
24162928abceSDenis V. Lunev     BlockDriverState *file;
2417ebb718a5SEric Blake     int64_t res;
2418ebb718a5SEric Blake 
2419ebb718a5SEric Blake     if (!count) {
2420ebb718a5SEric Blake         return true;
24212928abceSDenis V. Lunev     }
2422ebb718a5SEric Blake     res = bdrv_get_block_status_above(bs, NULL, start, count,
2423ebb718a5SEric Blake                                       &nr, &file);
2424ebb718a5SEric Blake     return res >= 0 && (res & BDRV_BLOCK_ZERO) && nr == count;
24252928abceSDenis V. Lunev }
24262928abceSDenis V. Lunev 
24275544b59fSEric Blake static coroutine_fn int qcow2_co_pwrite_zeroes(BlockDriverState *bs,
24285544b59fSEric Blake     int64_t offset, int count, BdrvRequestFlags flags)
2429621f0589SKevin Wolf {
2430621f0589SKevin Wolf     int ret;
2431ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
2432621f0589SKevin Wolf 
24335544b59fSEric Blake     uint32_t head = offset % s->cluster_size;
24345544b59fSEric Blake     uint32_t tail = (offset + count) % s->cluster_size;
24352928abceSDenis V. Lunev 
24365544b59fSEric Blake     trace_qcow2_pwrite_zeroes_start_req(qemu_coroutine_self(), offset, count);
24375a64e942SDenis V. Lunev 
2438ebb718a5SEric Blake     if (head || tail) {
24395544b59fSEric Blake         int64_t cl_start = (offset - head) >> BDRV_SECTOR_BITS;
2440ebb718a5SEric Blake         uint64_t off;
2441ecfe1863SKevin Wolf         unsigned int nr;
24422928abceSDenis V. Lunev 
24435544b59fSEric Blake         assert(head + count <= s->cluster_size);
24442928abceSDenis V. Lunev 
2445ebb718a5SEric Blake         /* check whether remainder of cluster already reads as zero */
24465544b59fSEric Blake         if (!(is_zero_sectors(bs, cl_start,
24475544b59fSEric Blake                               DIV_ROUND_UP(head, BDRV_SECTOR_SIZE)) &&
24485544b59fSEric Blake               is_zero_sectors(bs, (offset + count) >> BDRV_SECTOR_BITS,
24495544b59fSEric Blake                               DIV_ROUND_UP(-tail & (s->cluster_size - 1),
24505544b59fSEric Blake                                            BDRV_SECTOR_SIZE)))) {
2451621f0589SKevin Wolf             return -ENOTSUP;
2452621f0589SKevin Wolf         }
2453621f0589SKevin Wolf 
2454621f0589SKevin Wolf         qemu_co_mutex_lock(&s->lock);
24552928abceSDenis V. Lunev         /* We can have new write after previous check */
24565544b59fSEric Blake         offset = cl_start << BDRV_SECTOR_BITS;
24575544b59fSEric Blake         count = s->cluster_size;
2458ecfe1863SKevin Wolf         nr = s->cluster_size;
24595544b59fSEric Blake         ret = qcow2_get_cluster_offset(bs, offset, &nr, &off);
2460ebb718a5SEric Blake         if (ret != QCOW2_CLUSTER_UNALLOCATED && ret != QCOW2_CLUSTER_ZERO) {
24612928abceSDenis V. Lunev             qemu_co_mutex_unlock(&s->lock);
24622928abceSDenis V. Lunev             return -ENOTSUP;
24632928abceSDenis V. Lunev         }
24642928abceSDenis V. Lunev     } else {
24652928abceSDenis V. Lunev         qemu_co_mutex_lock(&s->lock);
24662928abceSDenis V. Lunev     }
24672928abceSDenis V. Lunev 
24685544b59fSEric Blake     trace_qcow2_pwrite_zeroes(qemu_coroutine_self(), offset, count);
24695a64e942SDenis V. Lunev 
24702928abceSDenis V. Lunev     /* Whatever is left can use real zero clusters */
24715544b59fSEric Blake     ret = qcow2_zero_clusters(bs, offset, count >> BDRV_SECTOR_BITS);
2472621f0589SKevin Wolf     qemu_co_mutex_unlock(&s->lock);
2473621f0589SKevin Wolf 
2474621f0589SKevin Wolf     return ret;
2475621f0589SKevin Wolf }
2476621f0589SKevin Wolf 
24776db39ae2SPaolo Bonzini static coroutine_fn int qcow2_co_discard(BlockDriverState *bs,
24786db39ae2SPaolo Bonzini     int64_t sector_num, int nb_sectors)
24795ea929e3SKevin Wolf {
24806db39ae2SPaolo Bonzini     int ret;
2481ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
24826db39ae2SPaolo Bonzini 
24836db39ae2SPaolo Bonzini     qemu_co_mutex_lock(&s->lock);
24846db39ae2SPaolo Bonzini     ret = qcow2_discard_clusters(bs, sector_num << BDRV_SECTOR_BITS,
2485808c4b6fSMax Reitz         nb_sectors, QCOW2_DISCARD_REQUEST, false);
24866db39ae2SPaolo Bonzini     qemu_co_mutex_unlock(&s->lock);
24876db39ae2SPaolo Bonzini     return ret;
24885ea929e3SKevin Wolf }
24895ea929e3SKevin Wolf 
2490419b19d9SStefan Hajnoczi static int qcow2_truncate(BlockDriverState *bs, int64_t offset)
2491419b19d9SStefan Hajnoczi {
2492ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
24932cf7cfa1SKevin Wolf     int64_t new_l1_size;
24942cf7cfa1SKevin Wolf     int ret;
2495419b19d9SStefan Hajnoczi 
2496419b19d9SStefan Hajnoczi     if (offset & 511) {
2497259b2173SKevin Wolf         error_report("The new size must be a multiple of 512");
2498419b19d9SStefan Hajnoczi         return -EINVAL;
2499419b19d9SStefan Hajnoczi     }
2500419b19d9SStefan Hajnoczi 
2501419b19d9SStefan Hajnoczi     /* cannot proceed if image has snapshots */
2502419b19d9SStefan Hajnoczi     if (s->nb_snapshots) {
2503259b2173SKevin Wolf         error_report("Can't resize an image which has snapshots");
2504419b19d9SStefan Hajnoczi         return -ENOTSUP;
2505419b19d9SStefan Hajnoczi     }
2506419b19d9SStefan Hajnoczi 
2507419b19d9SStefan Hajnoczi     /* shrinking is currently not supported */
2508419b19d9SStefan Hajnoczi     if (offset < bs->total_sectors * 512) {
2509259b2173SKevin Wolf         error_report("qcow2 doesn't support shrinking images yet");
2510419b19d9SStefan Hajnoczi         return -ENOTSUP;
2511419b19d9SStefan Hajnoczi     }
2512419b19d9SStefan Hajnoczi 
2513419b19d9SStefan Hajnoczi     new_l1_size = size_to_l1(s, offset);
251472893756SStefan Hajnoczi     ret = qcow2_grow_l1_table(bs, new_l1_size, true);
2515419b19d9SStefan Hajnoczi     if (ret < 0) {
2516419b19d9SStefan Hajnoczi         return ret;
2517419b19d9SStefan Hajnoczi     }
2518419b19d9SStefan Hajnoczi 
2519419b19d9SStefan Hajnoczi     /* write updated header.size */
2520419b19d9SStefan Hajnoczi     offset = cpu_to_be64(offset);
25219a4f4c31SKevin Wolf     ret = bdrv_pwrite_sync(bs->file->bs, offsetof(QCowHeader, size),
2522419b19d9SStefan Hajnoczi                            &offset, sizeof(uint64_t));
2523419b19d9SStefan Hajnoczi     if (ret < 0) {
2524419b19d9SStefan Hajnoczi         return ret;
2525419b19d9SStefan Hajnoczi     }
2526419b19d9SStefan Hajnoczi 
2527419b19d9SStefan Hajnoczi     s->l1_vm_state_index = new_l1_size;
2528419b19d9SStefan Hajnoczi     return 0;
2529419b19d9SStefan Hajnoczi }
2530419b19d9SStefan Hajnoczi 
253120d97356SBlue Swirl /* XXX: put compressed sectors first, then all the cluster aligned
253220d97356SBlue Swirl    tables to avoid losing bytes in alignment */
25337c80ab3fSJes Sorensen static int qcow2_write_compressed(BlockDriverState *bs, int64_t sector_num,
253420d97356SBlue Swirl                                   const uint8_t *buf, int nb_sectors)
253520d97356SBlue Swirl {
2536ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
253720d97356SBlue Swirl     z_stream strm;
253820d97356SBlue Swirl     int ret, out_len;
253920d97356SBlue Swirl     uint8_t *out_buf;
254020d97356SBlue Swirl     uint64_t cluster_offset;
254120d97356SBlue Swirl 
254220d97356SBlue Swirl     if (nb_sectors == 0) {
254320d97356SBlue Swirl         /* align end of file to a sector boundary to ease reading with
254420d97356SBlue Swirl            sector based I/Os */
25459a4f4c31SKevin Wolf         cluster_offset = bdrv_getlength(bs->file->bs);
25469a4f4c31SKevin Wolf         return bdrv_truncate(bs->file->bs, cluster_offset);
254720d97356SBlue Swirl     }
254820d97356SBlue Swirl 
2549f4d38befSStefan Hajnoczi     if (nb_sectors != s->cluster_sectors) {
2550f4d38befSStefan Hajnoczi         ret = -EINVAL;
2551f4d38befSStefan Hajnoczi 
2552f4d38befSStefan Hajnoczi         /* Zero-pad last write if image size is not cluster aligned */
2553f4d38befSStefan Hajnoczi         if (sector_num + nb_sectors == bs->total_sectors &&
2554f4d38befSStefan Hajnoczi             nb_sectors < s->cluster_sectors) {
2555f4d38befSStefan Hajnoczi             uint8_t *pad_buf = qemu_blockalign(bs, s->cluster_size);
2556f4d38befSStefan Hajnoczi             memset(pad_buf, 0, s->cluster_size);
2557f4d38befSStefan Hajnoczi             memcpy(pad_buf, buf, nb_sectors * BDRV_SECTOR_SIZE);
2558f4d38befSStefan Hajnoczi             ret = qcow2_write_compressed(bs, sector_num,
2559f4d38befSStefan Hajnoczi                                          pad_buf, s->cluster_sectors);
2560f4d38befSStefan Hajnoczi             qemu_vfree(pad_buf);
2561f4d38befSStefan Hajnoczi         }
2562f4d38befSStefan Hajnoczi         return ret;
2563f4d38befSStefan Hajnoczi     }
256420d97356SBlue Swirl 
25657267c094SAnthony Liguori     out_buf = g_malloc(s->cluster_size + (s->cluster_size / 1000) + 128);
256620d97356SBlue Swirl 
256720d97356SBlue Swirl     /* best compression, small window, no zlib header */
256820d97356SBlue Swirl     memset(&strm, 0, sizeof(strm));
256920d97356SBlue Swirl     ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
257020d97356SBlue Swirl                        Z_DEFLATED, -12,
257120d97356SBlue Swirl                        9, Z_DEFAULT_STRATEGY);
257220d97356SBlue Swirl     if (ret != 0) {
25738f1efd00SKevin Wolf         ret = -EINVAL;
25748f1efd00SKevin Wolf         goto fail;
257520d97356SBlue Swirl     }
257620d97356SBlue Swirl 
257720d97356SBlue Swirl     strm.avail_in = s->cluster_size;
257820d97356SBlue Swirl     strm.next_in = (uint8_t *)buf;
257920d97356SBlue Swirl     strm.avail_out = s->cluster_size;
258020d97356SBlue Swirl     strm.next_out = out_buf;
258120d97356SBlue Swirl 
258220d97356SBlue Swirl     ret = deflate(&strm, Z_FINISH);
258320d97356SBlue Swirl     if (ret != Z_STREAM_END && ret != Z_OK) {
258420d97356SBlue Swirl         deflateEnd(&strm);
25858f1efd00SKevin Wolf         ret = -EINVAL;
25868f1efd00SKevin Wolf         goto fail;
258720d97356SBlue Swirl     }
258820d97356SBlue Swirl     out_len = strm.next_out - out_buf;
258920d97356SBlue Swirl 
259020d97356SBlue Swirl     deflateEnd(&strm);
259120d97356SBlue Swirl 
259220d97356SBlue Swirl     if (ret != Z_STREAM_END || out_len >= s->cluster_size) {
259320d97356SBlue Swirl         /* could not compress: write normal cluster */
25948f1efd00SKevin Wolf         ret = bdrv_write(bs, sector_num, buf, s->cluster_sectors);
25958f1efd00SKevin Wolf         if (ret < 0) {
25968f1efd00SKevin Wolf             goto fail;
25978f1efd00SKevin Wolf         }
259820d97356SBlue Swirl     } else {
259920d97356SBlue Swirl         cluster_offset = qcow2_alloc_compressed_cluster_offset(bs,
260020d97356SBlue Swirl             sector_num << 9, out_len);
26018f1efd00SKevin Wolf         if (!cluster_offset) {
26028f1efd00SKevin Wolf             ret = -EIO;
26038f1efd00SKevin Wolf             goto fail;
26048f1efd00SKevin Wolf         }
260520d97356SBlue Swirl         cluster_offset &= s->cluster_offset_mask;
2606cf93980eSMax Reitz 
2607231bb267SMax Reitz         ret = qcow2_pre_write_overlap_check(bs, 0, cluster_offset, out_len);
2608cf93980eSMax Reitz         if (ret < 0) {
2609cf93980eSMax Reitz             goto fail;
2610cf93980eSMax Reitz         }
2611cf93980eSMax Reitz 
261266f82ceeSKevin Wolf         BLKDBG_EVENT(bs->file, BLKDBG_WRITE_COMPRESSED);
26139a4f4c31SKevin Wolf         ret = bdrv_pwrite(bs->file->bs, cluster_offset, out_buf, out_len);
26148f1efd00SKevin Wolf         if (ret < 0) {
26158f1efd00SKevin Wolf             goto fail;
261620d97356SBlue Swirl         }
261720d97356SBlue Swirl     }
261820d97356SBlue Swirl 
26198f1efd00SKevin Wolf     ret = 0;
26208f1efd00SKevin Wolf fail:
26217267c094SAnthony Liguori     g_free(out_buf);
26228f1efd00SKevin Wolf     return ret;
262320d97356SBlue Swirl }
262420d97356SBlue Swirl 
262594054183SMax Reitz static int make_completely_empty(BlockDriverState *bs)
262694054183SMax Reitz {
2627ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
262894054183SMax Reitz     int ret, l1_clusters;
262994054183SMax Reitz     int64_t offset;
263094054183SMax Reitz     uint64_t *new_reftable = NULL;
263194054183SMax Reitz     uint64_t rt_entry, l1_size2;
263294054183SMax Reitz     struct {
263394054183SMax Reitz         uint64_t l1_offset;
263494054183SMax Reitz         uint64_t reftable_offset;
263594054183SMax Reitz         uint32_t reftable_clusters;
263694054183SMax Reitz     } QEMU_PACKED l1_ofs_rt_ofs_cls;
263794054183SMax Reitz 
263894054183SMax Reitz     ret = qcow2_cache_empty(bs, s->l2_table_cache);
263994054183SMax Reitz     if (ret < 0) {
264094054183SMax Reitz         goto fail;
264194054183SMax Reitz     }
264294054183SMax Reitz 
264394054183SMax Reitz     ret = qcow2_cache_empty(bs, s->refcount_block_cache);
264494054183SMax Reitz     if (ret < 0) {
264594054183SMax Reitz         goto fail;
264694054183SMax Reitz     }
264794054183SMax Reitz 
264894054183SMax Reitz     /* Refcounts will be broken utterly */
264994054183SMax Reitz     ret = qcow2_mark_dirty(bs);
265094054183SMax Reitz     if (ret < 0) {
265194054183SMax Reitz         goto fail;
265294054183SMax Reitz     }
265394054183SMax Reitz 
265494054183SMax Reitz     BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
265594054183SMax Reitz 
265694054183SMax Reitz     l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / sizeof(uint64_t));
265794054183SMax Reitz     l1_size2 = (uint64_t)s->l1_size * sizeof(uint64_t);
265894054183SMax Reitz 
265994054183SMax Reitz     /* After this call, neither the in-memory nor the on-disk refcount
266094054183SMax Reitz      * information accurately describe the actual references */
266194054183SMax Reitz 
266274021bc4SEric Blake     ret = bdrv_pwrite_zeroes(bs->file->bs, s->l1_table_offset,
266374021bc4SEric Blake                              l1_clusters * s->cluster_size, 0);
266494054183SMax Reitz     if (ret < 0) {
266594054183SMax Reitz         goto fail_broken_refcounts;
266694054183SMax Reitz     }
266794054183SMax Reitz     memset(s->l1_table, 0, l1_size2);
266894054183SMax Reitz 
266994054183SMax Reitz     BLKDBG_EVENT(bs->file, BLKDBG_EMPTY_IMAGE_PREPARE);
267094054183SMax Reitz 
267194054183SMax Reitz     /* Overwrite enough clusters at the beginning of the sectors to place
267294054183SMax Reitz      * the refcount table, a refcount block and the L1 table in; this may
267394054183SMax Reitz      * overwrite parts of the existing refcount and L1 table, which is not
267494054183SMax Reitz      * an issue because the dirty flag is set, complete data loss is in fact
267594054183SMax Reitz      * desired and partial data loss is consequently fine as well */
267674021bc4SEric Blake     ret = bdrv_pwrite_zeroes(bs->file->bs, s->cluster_size,
267774021bc4SEric Blake                              (2 + l1_clusters) * s->cluster_size, 0);
267894054183SMax Reitz     /* This call (even if it failed overall) may have overwritten on-disk
267994054183SMax Reitz      * refcount structures; in that case, the in-memory refcount information
268094054183SMax Reitz      * will probably differ from the on-disk information which makes the BDS
268194054183SMax Reitz      * unusable */
268294054183SMax Reitz     if (ret < 0) {
268394054183SMax Reitz         goto fail_broken_refcounts;
268494054183SMax Reitz     }
268594054183SMax Reitz 
268694054183SMax Reitz     BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
268794054183SMax Reitz     BLKDBG_EVENT(bs->file, BLKDBG_REFTABLE_UPDATE);
268894054183SMax Reitz 
268994054183SMax Reitz     /* "Create" an empty reftable (one cluster) directly after the image
269094054183SMax Reitz      * header and an empty L1 table three clusters after the image header;
269194054183SMax Reitz      * the cluster between those two will be used as the first refblock */
269294054183SMax Reitz     cpu_to_be64w(&l1_ofs_rt_ofs_cls.l1_offset, 3 * s->cluster_size);
269394054183SMax Reitz     cpu_to_be64w(&l1_ofs_rt_ofs_cls.reftable_offset, s->cluster_size);
269494054183SMax Reitz     cpu_to_be32w(&l1_ofs_rt_ofs_cls.reftable_clusters, 1);
26959a4f4c31SKevin Wolf     ret = bdrv_pwrite_sync(bs->file->bs, offsetof(QCowHeader, l1_table_offset),
269694054183SMax Reitz                            &l1_ofs_rt_ofs_cls, sizeof(l1_ofs_rt_ofs_cls));
269794054183SMax Reitz     if (ret < 0) {
269894054183SMax Reitz         goto fail_broken_refcounts;
269994054183SMax Reitz     }
270094054183SMax Reitz 
270194054183SMax Reitz     s->l1_table_offset = 3 * s->cluster_size;
270294054183SMax Reitz 
270394054183SMax Reitz     new_reftable = g_try_new0(uint64_t, s->cluster_size / sizeof(uint64_t));
270494054183SMax Reitz     if (!new_reftable) {
270594054183SMax Reitz         ret = -ENOMEM;
270694054183SMax Reitz         goto fail_broken_refcounts;
270794054183SMax Reitz     }
270894054183SMax Reitz 
270994054183SMax Reitz     s->refcount_table_offset = s->cluster_size;
271094054183SMax Reitz     s->refcount_table_size   = s->cluster_size / sizeof(uint64_t);
271194054183SMax Reitz 
271294054183SMax Reitz     g_free(s->refcount_table);
271394054183SMax Reitz     s->refcount_table = new_reftable;
271494054183SMax Reitz     new_reftable = NULL;
271594054183SMax Reitz 
271694054183SMax Reitz     /* Now the in-memory refcount information again corresponds to the on-disk
271794054183SMax Reitz      * information (reftable is empty and no refblocks (the refblock cache is
271894054183SMax Reitz      * empty)); however, this means some clusters (e.g. the image header) are
271994054183SMax Reitz      * referenced, but not refcounted, but the normal qcow2 code assumes that
272094054183SMax Reitz      * the in-memory information is always correct */
272194054183SMax Reitz 
272294054183SMax Reitz     BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_ALLOC);
272394054183SMax Reitz 
272494054183SMax Reitz     /* Enter the first refblock into the reftable */
272594054183SMax Reitz     rt_entry = cpu_to_be64(2 * s->cluster_size);
27269a4f4c31SKevin Wolf     ret = bdrv_pwrite_sync(bs->file->bs, s->cluster_size,
272794054183SMax Reitz                            &rt_entry, sizeof(rt_entry));
272894054183SMax Reitz     if (ret < 0) {
272994054183SMax Reitz         goto fail_broken_refcounts;
273094054183SMax Reitz     }
273194054183SMax Reitz     s->refcount_table[0] = 2 * s->cluster_size;
273294054183SMax Reitz 
273394054183SMax Reitz     s->free_cluster_index = 0;
273494054183SMax Reitz     assert(3 + l1_clusters <= s->refcount_block_size);
273594054183SMax Reitz     offset = qcow2_alloc_clusters(bs, 3 * s->cluster_size + l1_size2);
273694054183SMax Reitz     if (offset < 0) {
273794054183SMax Reitz         ret = offset;
273894054183SMax Reitz         goto fail_broken_refcounts;
273994054183SMax Reitz     } else if (offset > 0) {
274094054183SMax Reitz         error_report("First cluster in emptied image is in use");
274194054183SMax Reitz         abort();
274294054183SMax Reitz     }
274394054183SMax Reitz 
274494054183SMax Reitz     /* Now finally the in-memory information corresponds to the on-disk
274594054183SMax Reitz      * structures and is correct */
274694054183SMax Reitz     ret = qcow2_mark_clean(bs);
274794054183SMax Reitz     if (ret < 0) {
274894054183SMax Reitz         goto fail;
274994054183SMax Reitz     }
275094054183SMax Reitz 
27519a4f4c31SKevin Wolf     ret = bdrv_truncate(bs->file->bs, (3 + l1_clusters) * s->cluster_size);
275294054183SMax Reitz     if (ret < 0) {
275394054183SMax Reitz         goto fail;
275494054183SMax Reitz     }
275594054183SMax Reitz 
275694054183SMax Reitz     return 0;
275794054183SMax Reitz 
275894054183SMax Reitz fail_broken_refcounts:
275994054183SMax Reitz     /* The BDS is unusable at this point. If we wanted to make it usable, we
276094054183SMax Reitz      * would have to call qcow2_refcount_close(), qcow2_refcount_init(),
276194054183SMax Reitz      * qcow2_check_refcounts(), qcow2_refcount_close() and qcow2_refcount_init()
276294054183SMax Reitz      * again. However, because the functions which could have caused this error
276394054183SMax Reitz      * path to be taken are used by those functions as well, it's very likely
276494054183SMax Reitz      * that that sequence will fail as well. Therefore, just eject the BDS. */
276594054183SMax Reitz     bs->drv = NULL;
276694054183SMax Reitz 
276794054183SMax Reitz fail:
276894054183SMax Reitz     g_free(new_reftable);
276994054183SMax Reitz     return ret;
277094054183SMax Reitz }
277194054183SMax Reitz 
2772491d27e2SMax Reitz static int qcow2_make_empty(BlockDriverState *bs)
2773491d27e2SMax Reitz {
2774ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
2775491d27e2SMax Reitz     uint64_t start_sector;
2776491d27e2SMax Reitz     int sector_step = INT_MAX / BDRV_SECTOR_SIZE;
277794054183SMax Reitz     int l1_clusters, ret = 0;
2778491d27e2SMax Reitz 
277994054183SMax Reitz     l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / sizeof(uint64_t));
278094054183SMax Reitz 
278194054183SMax Reitz     if (s->qcow_version >= 3 && !s->snapshots &&
278294054183SMax Reitz         3 + l1_clusters <= s->refcount_block_size) {
278394054183SMax Reitz         /* The following function only works for qcow2 v3 images (it requires
278494054183SMax Reitz          * the dirty flag) and only as long as there are no snapshots (because
278594054183SMax Reitz          * it completely empties the image). Furthermore, the L1 table and three
278694054183SMax Reitz          * additional clusters (image header, refcount table, one refcount
278794054183SMax Reitz          * block) have to fit inside one refcount block. */
278894054183SMax Reitz         return make_completely_empty(bs);
278994054183SMax Reitz     }
279094054183SMax Reitz 
279194054183SMax Reitz     /* This fallback code simply discards every active cluster; this is slow,
279294054183SMax Reitz      * but works in all cases */
2793491d27e2SMax Reitz     for (start_sector = 0; start_sector < bs->total_sectors;
2794491d27e2SMax Reitz          start_sector += sector_step)
2795491d27e2SMax Reitz     {
2796491d27e2SMax Reitz         /* As this function is generally used after committing an external
2797491d27e2SMax Reitz          * snapshot, QCOW2_DISCARD_SNAPSHOT seems appropriate. Also, the
2798491d27e2SMax Reitz          * default action for this kind of discard is to pass the discard,
2799491d27e2SMax Reitz          * which will ideally result in an actually smaller image file, as
2800491d27e2SMax Reitz          * is probably desired. */
2801491d27e2SMax Reitz         ret = qcow2_discard_clusters(bs, start_sector * BDRV_SECTOR_SIZE,
2802491d27e2SMax Reitz                                      MIN(sector_step,
2803491d27e2SMax Reitz                                          bs->total_sectors - start_sector),
2804491d27e2SMax Reitz                                      QCOW2_DISCARD_SNAPSHOT, true);
2805491d27e2SMax Reitz         if (ret < 0) {
2806491d27e2SMax Reitz             break;
2807491d27e2SMax Reitz         }
2808491d27e2SMax Reitz     }
2809491d27e2SMax Reitz 
2810491d27e2SMax Reitz     return ret;
2811491d27e2SMax Reitz }
2812491d27e2SMax Reitz 
2813a968168cSDong Xu Wang static coroutine_fn int qcow2_co_flush_to_os(BlockDriverState *bs)
281420d97356SBlue Swirl {
2815ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
281629c1a730SKevin Wolf     int ret;
281729c1a730SKevin Wolf 
28188b94ff85SPaolo Bonzini     qemu_co_mutex_lock(&s->lock);
2819f3c3b87dSDenis V. Lunev     ret = qcow2_cache_write(bs, s->l2_table_cache);
282029c1a730SKevin Wolf     if (ret < 0) {
2821c95de7e2SDong Xu Wang         qemu_co_mutex_unlock(&s->lock);
28228b94ff85SPaolo Bonzini         return ret;
282329c1a730SKevin Wolf     }
282429c1a730SKevin Wolf 
2825bfe8043eSStefan Hajnoczi     if (qcow2_need_accurate_refcounts(s)) {
2826f3c3b87dSDenis V. Lunev         ret = qcow2_cache_write(bs, s->refcount_block_cache);
282729c1a730SKevin Wolf         if (ret < 0) {
2828c95de7e2SDong Xu Wang             qemu_co_mutex_unlock(&s->lock);
28298b94ff85SPaolo Bonzini             return ret;
283029c1a730SKevin Wolf         }
2831bfe8043eSStefan Hajnoczi     }
28328b94ff85SPaolo Bonzini     qemu_co_mutex_unlock(&s->lock);
283329c1a730SKevin Wolf 
2834eb489bb1SKevin Wolf     return 0;
2835eb489bb1SKevin Wolf }
2836eb489bb1SKevin Wolf 
28377c80ab3fSJes Sorensen static int qcow2_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
283820d97356SBlue Swirl {
2839ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
284095de6d70SPaolo Bonzini     bdi->unallocated_blocks_are_zero = true;
284195de6d70SPaolo Bonzini     bdi->can_write_zeroes_with_unmap = (s->qcow_version >= 3);
284220d97356SBlue Swirl     bdi->cluster_size = s->cluster_size;
28437c80ab3fSJes Sorensen     bdi->vm_state_offset = qcow2_vm_state_offset(s);
284420d97356SBlue Swirl     return 0;
284520d97356SBlue Swirl }
284620d97356SBlue Swirl 
284737764dfbSMax Reitz static ImageInfoSpecific *qcow2_get_specific_info(BlockDriverState *bs)
284837764dfbSMax Reitz {
2849ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
285037764dfbSMax Reitz     ImageInfoSpecific *spec_info = g_new(ImageInfoSpecific, 1);
285137764dfbSMax Reitz 
285237764dfbSMax Reitz     *spec_info = (ImageInfoSpecific){
28536a8f9661SEric Blake         .type  = IMAGE_INFO_SPECIFIC_KIND_QCOW2,
285432bafa8fSEric Blake         .u.qcow2.data = g_new(ImageInfoSpecificQCow2, 1),
285537764dfbSMax Reitz     };
285637764dfbSMax Reitz     if (s->qcow_version == 2) {
285732bafa8fSEric Blake         *spec_info->u.qcow2.data = (ImageInfoSpecificQCow2){
285837764dfbSMax Reitz             .compat             = g_strdup("0.10"),
28590709c5a1SMax Reitz             .refcount_bits      = s->refcount_bits,
286037764dfbSMax Reitz         };
286137764dfbSMax Reitz     } else if (s->qcow_version == 3) {
286232bafa8fSEric Blake         *spec_info->u.qcow2.data = (ImageInfoSpecificQCow2){
286337764dfbSMax Reitz             .compat             = g_strdup("1.1"),
286437764dfbSMax Reitz             .lazy_refcounts     = s->compatible_features &
286537764dfbSMax Reitz                                   QCOW2_COMPAT_LAZY_REFCOUNTS,
286637764dfbSMax Reitz             .has_lazy_refcounts = true,
28679009b196SMax Reitz             .corrupt            = s->incompatible_features &
28689009b196SMax Reitz                                   QCOW2_INCOMPAT_CORRUPT,
28699009b196SMax Reitz             .has_corrupt        = true,
28700709c5a1SMax Reitz             .refcount_bits      = s->refcount_bits,
287137764dfbSMax Reitz         };
2872b1fc8f93SDenis V. Lunev     } else {
2873b1fc8f93SDenis V. Lunev         /* if this assertion fails, this probably means a new version was
2874b1fc8f93SDenis V. Lunev          * added without having it covered here */
2875b1fc8f93SDenis V. Lunev         assert(false);
287637764dfbSMax Reitz     }
287737764dfbSMax Reitz 
287837764dfbSMax Reitz     return spec_info;
287937764dfbSMax Reitz }
288037764dfbSMax Reitz 
288120d97356SBlue Swirl #if 0
288220d97356SBlue Swirl static void dump_refcounts(BlockDriverState *bs)
288320d97356SBlue Swirl {
2884ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
288520d97356SBlue Swirl     int64_t nb_clusters, k, k1, size;
288620d97356SBlue Swirl     int refcount;
288720d97356SBlue Swirl 
28889a4f4c31SKevin Wolf     size = bdrv_getlength(bs->file->bs);
288920d97356SBlue Swirl     nb_clusters = size_to_clusters(s, size);
289020d97356SBlue Swirl     for(k = 0; k < nb_clusters;) {
289120d97356SBlue Swirl         k1 = k;
289220d97356SBlue Swirl         refcount = get_refcount(bs, k);
289320d97356SBlue Swirl         k++;
289420d97356SBlue Swirl         while (k < nb_clusters && get_refcount(bs, k) == refcount)
289520d97356SBlue Swirl             k++;
28960bfcd599SBlue Swirl         printf("%" PRId64 ": refcount=%d nb=%" PRId64 "\n", k, refcount,
28970bfcd599SBlue Swirl                k - k1);
289820d97356SBlue Swirl     }
289920d97356SBlue Swirl }
290020d97356SBlue Swirl #endif
290120d97356SBlue Swirl 
2902cf8074b3SKevin Wolf static int qcow2_save_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
2903cf8074b3SKevin Wolf                               int64_t pos)
290420d97356SBlue Swirl {
2905ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
2906eedff66fSMax Reitz     int64_t total_sectors = bs->total_sectors;
29076e13610aSMax Reitz     bool zero_beyond_eof = bs->zero_beyond_eof;
290820d97356SBlue Swirl     int ret;
290920d97356SBlue Swirl 
291066f82ceeSKevin Wolf     BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_SAVE);
29116e13610aSMax Reitz     bs->zero_beyond_eof = false;
29128d3b1a2dSKevin Wolf     ret = bdrv_pwritev(bs, qcow2_vm_state_offset(s) + pos, qiov);
29136e13610aSMax Reitz     bs->zero_beyond_eof = zero_beyond_eof;
291420d97356SBlue Swirl 
2915eedff66fSMax Reitz     /* bdrv_co_do_writev will have increased the total_sectors value to include
2916eedff66fSMax Reitz      * the VM state - the VM state is however not an actual part of the block
2917eedff66fSMax Reitz      * device, therefore, we need to restore the old value. */
2918eedff66fSMax Reitz     bs->total_sectors = total_sectors;
2919eedff66fSMax Reitz 
292020d97356SBlue Swirl     return ret;
292120d97356SBlue Swirl }
292220d97356SBlue Swirl 
29237c80ab3fSJes Sorensen static int qcow2_load_vmstate(BlockDriverState *bs, uint8_t *buf,
292420d97356SBlue Swirl                               int64_t pos, int size)
292520d97356SBlue Swirl {
2926ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
29270d51b4deSAsias He     bool zero_beyond_eof = bs->zero_beyond_eof;
292820d97356SBlue Swirl     int ret;
292920d97356SBlue Swirl 
293066f82ceeSKevin Wolf     BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_LOAD);
29310d51b4deSAsias He     bs->zero_beyond_eof = false;
29327c80ab3fSJes Sorensen     ret = bdrv_pread(bs, qcow2_vm_state_offset(s) + pos, buf, size);
29330d51b4deSAsias He     bs->zero_beyond_eof = zero_beyond_eof;
293420d97356SBlue Swirl 
293520d97356SBlue Swirl     return ret;
293620d97356SBlue Swirl }
293720d97356SBlue Swirl 
29389296b3edSMax Reitz /*
29399296b3edSMax Reitz  * Downgrades an image's version. To achieve this, any incompatible features
29409296b3edSMax Reitz  * have to be removed.
29419296b3edSMax Reitz  */
29424057a2b2SMax Reitz static int qcow2_downgrade(BlockDriverState *bs, int target_version,
29438b13976dSMax Reitz                            BlockDriverAmendStatusCB *status_cb, void *cb_opaque)
29449296b3edSMax Reitz {
2945ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
29469296b3edSMax Reitz     int current_version = s->qcow_version;
29479296b3edSMax Reitz     int ret;
29489296b3edSMax Reitz 
29499296b3edSMax Reitz     if (target_version == current_version) {
29509296b3edSMax Reitz         return 0;
29519296b3edSMax Reitz     } else if (target_version > current_version) {
29529296b3edSMax Reitz         return -EINVAL;
29539296b3edSMax Reitz     } else if (target_version != 2) {
29549296b3edSMax Reitz         return -EINVAL;
29559296b3edSMax Reitz     }
29569296b3edSMax Reitz 
29579296b3edSMax Reitz     if (s->refcount_order != 4) {
295861ce55fcSMax Reitz         error_report("compat=0.10 requires refcount_bits=16");
29599296b3edSMax Reitz         return -ENOTSUP;
29609296b3edSMax Reitz     }
29619296b3edSMax Reitz 
29629296b3edSMax Reitz     /* clear incompatible features */
29639296b3edSMax Reitz     if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
29649296b3edSMax Reitz         ret = qcow2_mark_clean(bs);
29659296b3edSMax Reitz         if (ret < 0) {
29669296b3edSMax Reitz             return ret;
29679296b3edSMax Reitz         }
29689296b3edSMax Reitz     }
29699296b3edSMax Reitz 
29709296b3edSMax Reitz     /* with QCOW2_INCOMPAT_CORRUPT, it is pretty much impossible to get here in
29719296b3edSMax Reitz      * the first place; if that happens nonetheless, returning -ENOTSUP is the
29729296b3edSMax Reitz      * best thing to do anyway */
29739296b3edSMax Reitz 
29749296b3edSMax Reitz     if (s->incompatible_features) {
29759296b3edSMax Reitz         return -ENOTSUP;
29769296b3edSMax Reitz     }
29779296b3edSMax Reitz 
29789296b3edSMax Reitz     /* since we can ignore compatible features, we can set them to 0 as well */
29799296b3edSMax Reitz     s->compatible_features = 0;
29809296b3edSMax Reitz     /* if lazy refcounts have been used, they have already been fixed through
29819296b3edSMax Reitz      * clearing the dirty flag */
29829296b3edSMax Reitz 
29839296b3edSMax Reitz     /* clearing autoclear features is trivial */
29849296b3edSMax Reitz     s->autoclear_features = 0;
29859296b3edSMax Reitz 
29868b13976dSMax Reitz     ret = qcow2_expand_zero_clusters(bs, status_cb, cb_opaque);
29879296b3edSMax Reitz     if (ret < 0) {
29889296b3edSMax Reitz         return ret;
29899296b3edSMax Reitz     }
29909296b3edSMax Reitz 
29919296b3edSMax Reitz     s->qcow_version = target_version;
29929296b3edSMax Reitz     ret = qcow2_update_header(bs);
29939296b3edSMax Reitz     if (ret < 0) {
29949296b3edSMax Reitz         s->qcow_version = current_version;
29959296b3edSMax Reitz         return ret;
29969296b3edSMax Reitz     }
29979296b3edSMax Reitz     return 0;
29989296b3edSMax Reitz }
29999296b3edSMax Reitz 
3000c293a809SMax Reitz typedef enum Qcow2AmendOperation {
3001c293a809SMax Reitz     /* This is the value Qcow2AmendHelperCBInfo::last_operation will be
3002c293a809SMax Reitz      * statically initialized to so that the helper CB can discern the first
3003c293a809SMax Reitz      * invocation from an operation change */
3004c293a809SMax Reitz     QCOW2_NO_OPERATION = 0,
3005c293a809SMax Reitz 
300661ce55fcSMax Reitz     QCOW2_CHANGING_REFCOUNT_ORDER,
3007c293a809SMax Reitz     QCOW2_DOWNGRADING,
3008c293a809SMax Reitz } Qcow2AmendOperation;
3009c293a809SMax Reitz 
3010c293a809SMax Reitz typedef struct Qcow2AmendHelperCBInfo {
3011c293a809SMax Reitz     /* The code coordinating the amend operations should only modify
3012c293a809SMax Reitz      * these four fields; the rest will be managed by the CB */
3013c293a809SMax Reitz     BlockDriverAmendStatusCB *original_status_cb;
3014c293a809SMax Reitz     void *original_cb_opaque;
3015c293a809SMax Reitz 
3016c293a809SMax Reitz     Qcow2AmendOperation current_operation;
3017c293a809SMax Reitz 
3018c293a809SMax Reitz     /* Total number of operations to perform (only set once) */
3019c293a809SMax Reitz     int total_operations;
3020c293a809SMax Reitz 
3021c293a809SMax Reitz     /* The following fields are managed by the CB */
3022c293a809SMax Reitz 
3023c293a809SMax Reitz     /* Number of operations completed */
3024c293a809SMax Reitz     int operations_completed;
3025c293a809SMax Reitz 
3026c293a809SMax Reitz     /* Cumulative offset of all completed operations */
3027c293a809SMax Reitz     int64_t offset_completed;
3028c293a809SMax Reitz 
3029c293a809SMax Reitz     Qcow2AmendOperation last_operation;
3030c293a809SMax Reitz     int64_t last_work_size;
3031c293a809SMax Reitz } Qcow2AmendHelperCBInfo;
3032c293a809SMax Reitz 
3033c293a809SMax Reitz static void qcow2_amend_helper_cb(BlockDriverState *bs,
3034c293a809SMax Reitz                                   int64_t operation_offset,
3035c293a809SMax Reitz                                   int64_t operation_work_size, void *opaque)
3036c293a809SMax Reitz {
3037c293a809SMax Reitz     Qcow2AmendHelperCBInfo *info = opaque;
3038c293a809SMax Reitz     int64_t current_work_size;
3039c293a809SMax Reitz     int64_t projected_work_size;
3040c293a809SMax Reitz 
3041c293a809SMax Reitz     if (info->current_operation != info->last_operation) {
3042c293a809SMax Reitz         if (info->last_operation != QCOW2_NO_OPERATION) {
3043c293a809SMax Reitz             info->offset_completed += info->last_work_size;
3044c293a809SMax Reitz             info->operations_completed++;
3045c293a809SMax Reitz         }
3046c293a809SMax Reitz 
3047c293a809SMax Reitz         info->last_operation = info->current_operation;
3048c293a809SMax Reitz     }
3049c293a809SMax Reitz 
3050c293a809SMax Reitz     assert(info->total_operations > 0);
3051c293a809SMax Reitz     assert(info->operations_completed < info->total_operations);
3052c293a809SMax Reitz 
3053c293a809SMax Reitz     info->last_work_size = operation_work_size;
3054c293a809SMax Reitz 
3055c293a809SMax Reitz     current_work_size = info->offset_completed + operation_work_size;
3056c293a809SMax Reitz 
3057c293a809SMax Reitz     /* current_work_size is the total work size for (operations_completed + 1)
3058c293a809SMax Reitz      * operations (which includes this one), so multiply it by the number of
3059c293a809SMax Reitz      * operations not covered and divide it by the number of operations
3060c293a809SMax Reitz      * covered to get a projection for the operations not covered */
3061c293a809SMax Reitz     projected_work_size = current_work_size * (info->total_operations -
3062c293a809SMax Reitz                                                info->operations_completed - 1)
3063c293a809SMax Reitz                                             / (info->operations_completed + 1);
3064c293a809SMax Reitz 
3065c293a809SMax Reitz     info->original_status_cb(bs, info->offset_completed + operation_offset,
3066c293a809SMax Reitz                              current_work_size + projected_work_size,
3067c293a809SMax Reitz                              info->original_cb_opaque);
3068c293a809SMax Reitz }
3069c293a809SMax Reitz 
307077485434SMax Reitz static int qcow2_amend_options(BlockDriverState *bs, QemuOpts *opts,
30718b13976dSMax Reitz                                BlockDriverAmendStatusCB *status_cb,
30728b13976dSMax Reitz                                void *cb_opaque)
30739296b3edSMax Reitz {
3074ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
30759296b3edSMax Reitz     int old_version = s->qcow_version, new_version = old_version;
30769296b3edSMax Reitz     uint64_t new_size = 0;
30779296b3edSMax Reitz     const char *backing_file = NULL, *backing_format = NULL;
30789296b3edSMax Reitz     bool lazy_refcounts = s->use_lazy_refcounts;
30791bd0e2d1SChunyan Liu     const char *compat = NULL;
30801bd0e2d1SChunyan Liu     uint64_t cluster_size = s->cluster_size;
30811bd0e2d1SChunyan Liu     bool encrypt;
308261ce55fcSMax Reitz     int refcount_bits = s->refcount_bits;
30839296b3edSMax Reitz     int ret;
30841bd0e2d1SChunyan Liu     QemuOptDesc *desc = opts->list->desc;
3085c293a809SMax Reitz     Qcow2AmendHelperCBInfo helper_cb_info;
30869296b3edSMax Reitz 
30871bd0e2d1SChunyan Liu     while (desc && desc->name) {
30881bd0e2d1SChunyan Liu         if (!qemu_opt_find(opts, desc->name)) {
30899296b3edSMax Reitz             /* only change explicitly defined options */
30901bd0e2d1SChunyan Liu             desc++;
30919296b3edSMax Reitz             continue;
30929296b3edSMax Reitz         }
30939296b3edSMax Reitz 
30948a17b83cSMax Reitz         if (!strcmp(desc->name, BLOCK_OPT_COMPAT_LEVEL)) {
30958a17b83cSMax Reitz             compat = qemu_opt_get(opts, BLOCK_OPT_COMPAT_LEVEL);
30961bd0e2d1SChunyan Liu             if (!compat) {
30979296b3edSMax Reitz                 /* preserve default */
30981bd0e2d1SChunyan Liu             } else if (!strcmp(compat, "0.10")) {
30999296b3edSMax Reitz                 new_version = 2;
31001bd0e2d1SChunyan Liu             } else if (!strcmp(compat, "1.1")) {
31019296b3edSMax Reitz                 new_version = 3;
31029296b3edSMax Reitz             } else {
310329d72431SMax Reitz                 error_report("Unknown compatibility level %s", compat);
31049296b3edSMax Reitz                 return -EINVAL;
31059296b3edSMax Reitz             }
31068a17b83cSMax Reitz         } else if (!strcmp(desc->name, BLOCK_OPT_PREALLOC)) {
310729d72431SMax Reitz             error_report("Cannot change preallocation mode");
31089296b3edSMax Reitz             return -ENOTSUP;
31098a17b83cSMax Reitz         } else if (!strcmp(desc->name, BLOCK_OPT_SIZE)) {
31108a17b83cSMax Reitz             new_size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, 0);
31118a17b83cSMax Reitz         } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FILE)) {
31128a17b83cSMax Reitz             backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
31138a17b83cSMax Reitz         } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FMT)) {
31148a17b83cSMax Reitz             backing_format = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
31158a17b83cSMax Reitz         } else if (!strcmp(desc->name, BLOCK_OPT_ENCRYPT)) {
31168a17b83cSMax Reitz             encrypt = qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT,
3117f6fa64f6SDaniel P. Berrange                                         !!s->cipher);
3118f6fa64f6SDaniel P. Berrange 
3119f6fa64f6SDaniel P. Berrange             if (encrypt != !!s->cipher) {
312029d72431SMax Reitz                 error_report("Changing the encryption flag is not supported");
31219296b3edSMax Reitz                 return -ENOTSUP;
31229296b3edSMax Reitz             }
31238a17b83cSMax Reitz         } else if (!strcmp(desc->name, BLOCK_OPT_CLUSTER_SIZE)) {
31248a17b83cSMax Reitz             cluster_size = qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE,
31251bd0e2d1SChunyan Liu                                              cluster_size);
31261bd0e2d1SChunyan Liu             if (cluster_size != s->cluster_size) {
312729d72431SMax Reitz                 error_report("Changing the cluster size is not supported");
31289296b3edSMax Reitz                 return -ENOTSUP;
31299296b3edSMax Reitz             }
31308a17b83cSMax Reitz         } else if (!strcmp(desc->name, BLOCK_OPT_LAZY_REFCOUNTS)) {
31318a17b83cSMax Reitz             lazy_refcounts = qemu_opt_get_bool(opts, BLOCK_OPT_LAZY_REFCOUNTS,
31321bd0e2d1SChunyan Liu                                                lazy_refcounts);
313306d05fa7SMax Reitz         } else if (!strcmp(desc->name, BLOCK_OPT_REFCOUNT_BITS)) {
313461ce55fcSMax Reitz             refcount_bits = qemu_opt_get_number(opts, BLOCK_OPT_REFCOUNT_BITS,
313561ce55fcSMax Reitz                                                 refcount_bits);
313661ce55fcSMax Reitz 
313761ce55fcSMax Reitz             if (refcount_bits <= 0 || refcount_bits > 64 ||
313861ce55fcSMax Reitz                 !is_power_of_2(refcount_bits))
313961ce55fcSMax Reitz             {
314061ce55fcSMax Reitz                 error_report("Refcount width must be a power of two and may "
314161ce55fcSMax Reitz                              "not exceed 64 bits");
314261ce55fcSMax Reitz                 return -EINVAL;
314361ce55fcSMax Reitz             }
31449296b3edSMax Reitz         } else {
3145164e0f89SMax Reitz             /* if this point is reached, this probably means a new option was
31469296b3edSMax Reitz              * added without having it covered here */
3147164e0f89SMax Reitz             abort();
31489296b3edSMax Reitz         }
31491bd0e2d1SChunyan Liu 
31501bd0e2d1SChunyan Liu         desc++;
31519296b3edSMax Reitz     }
31529296b3edSMax Reitz 
3153c293a809SMax Reitz     helper_cb_info = (Qcow2AmendHelperCBInfo){
3154c293a809SMax Reitz         .original_status_cb = status_cb,
3155c293a809SMax Reitz         .original_cb_opaque = cb_opaque,
3156c293a809SMax Reitz         .total_operations = (new_version < old_version)
315761ce55fcSMax Reitz                           + (s->refcount_bits != refcount_bits)
3158c293a809SMax Reitz     };
3159c293a809SMax Reitz 
31601038bbb8SMax Reitz     /* Upgrade first (some features may require compat=1.1) */
31619296b3edSMax Reitz     if (new_version > old_version) {
31629296b3edSMax Reitz         s->qcow_version = new_version;
31639296b3edSMax Reitz         ret = qcow2_update_header(bs);
31649296b3edSMax Reitz         if (ret < 0) {
31659296b3edSMax Reitz             s->qcow_version = old_version;
31669296b3edSMax Reitz             return ret;
31679296b3edSMax Reitz         }
31689296b3edSMax Reitz     }
31699296b3edSMax Reitz 
317061ce55fcSMax Reitz     if (s->refcount_bits != refcount_bits) {
317161ce55fcSMax Reitz         int refcount_order = ctz32(refcount_bits);
317261ce55fcSMax Reitz         Error *local_error = NULL;
317361ce55fcSMax Reitz 
317461ce55fcSMax Reitz         if (new_version < 3 && refcount_bits != 16) {
317561ce55fcSMax Reitz             error_report("Different refcount widths than 16 bits require "
317661ce55fcSMax Reitz                          "compatibility level 1.1 or above (use compat=1.1 or "
317761ce55fcSMax Reitz                          "greater)");
317861ce55fcSMax Reitz             return -EINVAL;
317961ce55fcSMax Reitz         }
318061ce55fcSMax Reitz 
318161ce55fcSMax Reitz         helper_cb_info.current_operation = QCOW2_CHANGING_REFCOUNT_ORDER;
318261ce55fcSMax Reitz         ret = qcow2_change_refcount_order(bs, refcount_order,
318361ce55fcSMax Reitz                                           &qcow2_amend_helper_cb,
318461ce55fcSMax Reitz                                           &helper_cb_info, &local_error);
318561ce55fcSMax Reitz         if (ret < 0) {
318661ce55fcSMax Reitz             error_report_err(local_error);
318761ce55fcSMax Reitz             return ret;
318861ce55fcSMax Reitz         }
318961ce55fcSMax Reitz     }
319061ce55fcSMax Reitz 
31919296b3edSMax Reitz     if (backing_file || backing_format) {
3192e4603fe1SKevin Wolf         ret = qcow2_change_backing_file(bs,
3193e4603fe1SKevin Wolf                     backing_file ?: s->image_backing_file,
3194e4603fe1SKevin Wolf                     backing_format ?: s->image_backing_format);
31959296b3edSMax Reitz         if (ret < 0) {
31969296b3edSMax Reitz             return ret;
31979296b3edSMax Reitz         }
31989296b3edSMax Reitz     }
31999296b3edSMax Reitz 
32009296b3edSMax Reitz     if (s->use_lazy_refcounts != lazy_refcounts) {
32019296b3edSMax Reitz         if (lazy_refcounts) {
32021038bbb8SMax Reitz             if (new_version < 3) {
320329d72431SMax Reitz                 error_report("Lazy refcounts only supported with compatibility "
320429d72431SMax Reitz                              "level 1.1 and above (use compat=1.1 or greater)");
32059296b3edSMax Reitz                 return -EINVAL;
32069296b3edSMax Reitz             }
32079296b3edSMax Reitz             s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
32089296b3edSMax Reitz             ret = qcow2_update_header(bs);
32099296b3edSMax Reitz             if (ret < 0) {
32109296b3edSMax Reitz                 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
32119296b3edSMax Reitz                 return ret;
32129296b3edSMax Reitz             }
32139296b3edSMax Reitz             s->use_lazy_refcounts = true;
32149296b3edSMax Reitz         } else {
32159296b3edSMax Reitz             /* make image clean first */
32169296b3edSMax Reitz             ret = qcow2_mark_clean(bs);
32179296b3edSMax Reitz             if (ret < 0) {
32189296b3edSMax Reitz                 return ret;
32199296b3edSMax Reitz             }
32209296b3edSMax Reitz             /* now disallow lazy refcounts */
32219296b3edSMax Reitz             s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
32229296b3edSMax Reitz             ret = qcow2_update_header(bs);
32239296b3edSMax Reitz             if (ret < 0) {
32249296b3edSMax Reitz                 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
32259296b3edSMax Reitz                 return ret;
32269296b3edSMax Reitz             }
32279296b3edSMax Reitz             s->use_lazy_refcounts = false;
32289296b3edSMax Reitz         }
32299296b3edSMax Reitz     }
32309296b3edSMax Reitz 
32319296b3edSMax Reitz     if (new_size) {
32329296b3edSMax Reitz         ret = bdrv_truncate(bs, new_size);
32339296b3edSMax Reitz         if (ret < 0) {
32349296b3edSMax Reitz             return ret;
32359296b3edSMax Reitz         }
32369296b3edSMax Reitz     }
32379296b3edSMax Reitz 
32381038bbb8SMax Reitz     /* Downgrade last (so unsupported features can be removed before) */
32391038bbb8SMax Reitz     if (new_version < old_version) {
3240c293a809SMax Reitz         helper_cb_info.current_operation = QCOW2_DOWNGRADING;
3241c293a809SMax Reitz         ret = qcow2_downgrade(bs, new_version, &qcow2_amend_helper_cb,
3242c293a809SMax Reitz                               &helper_cb_info);
32431038bbb8SMax Reitz         if (ret < 0) {
32441038bbb8SMax Reitz             return ret;
32451038bbb8SMax Reitz         }
32461038bbb8SMax Reitz     }
32471038bbb8SMax Reitz 
32489296b3edSMax Reitz     return 0;
32499296b3edSMax Reitz }
32509296b3edSMax Reitz 
325185186ebdSMax Reitz /*
325285186ebdSMax Reitz  * If offset or size are negative, respectively, they will not be included in
325385186ebdSMax Reitz  * the BLOCK_IMAGE_CORRUPTED event emitted.
325485186ebdSMax Reitz  * fatal will be ignored for read-only BDS; corruptions found there will always
325585186ebdSMax Reitz  * be considered non-fatal.
325685186ebdSMax Reitz  */
325785186ebdSMax Reitz void qcow2_signal_corruption(BlockDriverState *bs, bool fatal, int64_t offset,
325885186ebdSMax Reitz                              int64_t size, const char *message_format, ...)
325985186ebdSMax Reitz {
3260ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
3261dc881b44SAlberto Garcia     const char *node_name;
326285186ebdSMax Reitz     char *message;
326385186ebdSMax Reitz     va_list ap;
326485186ebdSMax Reitz 
326585186ebdSMax Reitz     fatal = fatal && !bs->read_only;
326685186ebdSMax Reitz 
326785186ebdSMax Reitz     if (s->signaled_corruption &&
326885186ebdSMax Reitz         (!fatal || (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT)))
326985186ebdSMax Reitz     {
327085186ebdSMax Reitz         return;
327185186ebdSMax Reitz     }
327285186ebdSMax Reitz 
327385186ebdSMax Reitz     va_start(ap, message_format);
327485186ebdSMax Reitz     message = g_strdup_vprintf(message_format, ap);
327585186ebdSMax Reitz     va_end(ap);
327685186ebdSMax Reitz 
327785186ebdSMax Reitz     if (fatal) {
327885186ebdSMax Reitz         fprintf(stderr, "qcow2: Marking image as corrupt: %s; further "
327985186ebdSMax Reitz                 "corruption events will be suppressed\n", message);
328085186ebdSMax Reitz     } else {
328185186ebdSMax Reitz         fprintf(stderr, "qcow2: Image is corrupt: %s; further non-fatal "
328285186ebdSMax Reitz                 "corruption events will be suppressed\n", message);
328385186ebdSMax Reitz     }
328485186ebdSMax Reitz 
3285dc881b44SAlberto Garcia     node_name = bdrv_get_node_name(bs);
3286dc881b44SAlberto Garcia     qapi_event_send_block_image_corrupted(bdrv_get_device_name(bs),
3287dc881b44SAlberto Garcia                                           *node_name != '\0', node_name,
3288dc881b44SAlberto Garcia                                           message, offset >= 0, offset,
3289dc881b44SAlberto Garcia                                           size >= 0, size,
329085186ebdSMax Reitz                                           fatal, &error_abort);
329185186ebdSMax Reitz     g_free(message);
329285186ebdSMax Reitz 
329385186ebdSMax Reitz     if (fatal) {
329485186ebdSMax Reitz         qcow2_mark_corrupt(bs);
329585186ebdSMax Reitz         bs->drv = NULL; /* make BDS unusable */
329685186ebdSMax Reitz     }
329785186ebdSMax Reitz 
329885186ebdSMax Reitz     s->signaled_corruption = true;
329985186ebdSMax Reitz }
330085186ebdSMax Reitz 
33011bd0e2d1SChunyan Liu static QemuOptsList qcow2_create_opts = {
33021bd0e2d1SChunyan Liu     .name = "qcow2-create-opts",
33031bd0e2d1SChunyan Liu     .head = QTAILQ_HEAD_INITIALIZER(qcow2_create_opts.head),
33041bd0e2d1SChunyan Liu     .desc = {
330520d97356SBlue Swirl         {
330620d97356SBlue Swirl             .name = BLOCK_OPT_SIZE,
33071bd0e2d1SChunyan Liu             .type = QEMU_OPT_SIZE,
330820d97356SBlue Swirl             .help = "Virtual disk size"
330920d97356SBlue Swirl         },
331020d97356SBlue Swirl         {
33116744cbabSKevin Wolf             .name = BLOCK_OPT_COMPAT_LEVEL,
33121bd0e2d1SChunyan Liu             .type = QEMU_OPT_STRING,
33136744cbabSKevin Wolf             .help = "Compatibility level (0.10 or 1.1)"
33146744cbabSKevin Wolf         },
33156744cbabSKevin Wolf         {
331620d97356SBlue Swirl             .name = BLOCK_OPT_BACKING_FILE,
33171bd0e2d1SChunyan Liu             .type = QEMU_OPT_STRING,
331820d97356SBlue Swirl             .help = "File name of a base image"
331920d97356SBlue Swirl         },
332020d97356SBlue Swirl         {
332120d97356SBlue Swirl             .name = BLOCK_OPT_BACKING_FMT,
33221bd0e2d1SChunyan Liu             .type = QEMU_OPT_STRING,
332320d97356SBlue Swirl             .help = "Image format of the base image"
332420d97356SBlue Swirl         },
332520d97356SBlue Swirl         {
332620d97356SBlue Swirl             .name = BLOCK_OPT_ENCRYPT,
33271bd0e2d1SChunyan Liu             .type = QEMU_OPT_BOOL,
33281bd0e2d1SChunyan Liu             .help = "Encrypt the image",
33291bd0e2d1SChunyan Liu             .def_value_str = "off"
333020d97356SBlue Swirl         },
333120d97356SBlue Swirl         {
333220d97356SBlue Swirl             .name = BLOCK_OPT_CLUSTER_SIZE,
33331bd0e2d1SChunyan Liu             .type = QEMU_OPT_SIZE,
333499cce9faSKevin Wolf             .help = "qcow2 cluster size",
33351bd0e2d1SChunyan Liu             .def_value_str = stringify(DEFAULT_CLUSTER_SIZE)
333620d97356SBlue Swirl         },
333720d97356SBlue Swirl         {
333820d97356SBlue Swirl             .name = BLOCK_OPT_PREALLOC,
33391bd0e2d1SChunyan Liu             .type = QEMU_OPT_STRING,
33400e4271b7SHu Tao             .help = "Preallocation mode (allowed values: off, metadata, "
33410e4271b7SHu Tao                     "falloc, full)"
334220d97356SBlue Swirl         },
3343bfe8043eSStefan Hajnoczi         {
3344bfe8043eSStefan Hajnoczi             .name = BLOCK_OPT_LAZY_REFCOUNTS,
33451bd0e2d1SChunyan Liu             .type = QEMU_OPT_BOOL,
3346bfe8043eSStefan Hajnoczi             .help = "Postpone refcount updates",
33471bd0e2d1SChunyan Liu             .def_value_str = "off"
3348bfe8043eSStefan Hajnoczi         },
334906d05fa7SMax Reitz         {
335006d05fa7SMax Reitz             .name = BLOCK_OPT_REFCOUNT_BITS,
335106d05fa7SMax Reitz             .type = QEMU_OPT_NUMBER,
335206d05fa7SMax Reitz             .help = "Width of a reference count entry in bits",
335306d05fa7SMax Reitz             .def_value_str = "16"
335406d05fa7SMax Reitz         },
33551bd0e2d1SChunyan Liu         { /* end of list */ }
33561bd0e2d1SChunyan Liu     }
335720d97356SBlue Swirl };
335820d97356SBlue Swirl 
33595f535a94SMax Reitz BlockDriver bdrv_qcow2 = {
336020d97356SBlue Swirl     .format_name        = "qcow2",
3361ff99129aSKevin Wolf     .instance_size      = sizeof(BDRVQcow2State),
33627c80ab3fSJes Sorensen     .bdrv_probe         = qcow2_probe,
33637c80ab3fSJes Sorensen     .bdrv_open          = qcow2_open,
33647c80ab3fSJes Sorensen     .bdrv_close         = qcow2_close,
336521d82ac9SJeff Cody     .bdrv_reopen_prepare  = qcow2_reopen_prepare,
33665b0959a7SKevin Wolf     .bdrv_reopen_commit   = qcow2_reopen_commit,
33675b0959a7SKevin Wolf     .bdrv_reopen_abort    = qcow2_reopen_abort,
33685365f44dSKevin Wolf     .bdrv_join_options    = qcow2_join_options,
3369c282e1fdSChunyan Liu     .bdrv_create        = qcow2_create,
33703ac21627SPeter Lieven     .bdrv_has_zero_init = bdrv_has_zero_init_1,
3371b6b8a333SPaolo Bonzini     .bdrv_co_get_block_status = qcow2_co_get_block_status,
33727c80ab3fSJes Sorensen     .bdrv_set_key       = qcow2_set_key,
337320d97356SBlue Swirl 
3374ecfe1863SKevin Wolf     .bdrv_co_preadv         = qcow2_co_preadv,
3375*d46a0bb2SKevin Wolf     .bdrv_co_pwritev        = qcow2_co_pwritev,
3376eb489bb1SKevin Wolf     .bdrv_co_flush_to_os    = qcow2_co_flush_to_os,
3377419b19d9SStefan Hajnoczi 
33785544b59fSEric Blake     .bdrv_co_pwrite_zeroes  = qcow2_co_pwrite_zeroes,
33796db39ae2SPaolo Bonzini     .bdrv_co_discard        = qcow2_co_discard,
3380419b19d9SStefan Hajnoczi     .bdrv_truncate          = qcow2_truncate,
33817c80ab3fSJes Sorensen     .bdrv_write_compressed  = qcow2_write_compressed,
3382491d27e2SMax Reitz     .bdrv_make_empty        = qcow2_make_empty,
338320d97356SBlue Swirl 
338420d97356SBlue Swirl     .bdrv_snapshot_create   = qcow2_snapshot_create,
338520d97356SBlue Swirl     .bdrv_snapshot_goto     = qcow2_snapshot_goto,
338620d97356SBlue Swirl     .bdrv_snapshot_delete   = qcow2_snapshot_delete,
338720d97356SBlue Swirl     .bdrv_snapshot_list     = qcow2_snapshot_list,
338851ef6727Sedison     .bdrv_snapshot_load_tmp = qcow2_snapshot_load_tmp,
33897c80ab3fSJes Sorensen     .bdrv_get_info          = qcow2_get_info,
339037764dfbSMax Reitz     .bdrv_get_specific_info = qcow2_get_specific_info,
339120d97356SBlue Swirl 
33927c80ab3fSJes Sorensen     .bdrv_save_vmstate    = qcow2_save_vmstate,
33937c80ab3fSJes Sorensen     .bdrv_load_vmstate    = qcow2_load_vmstate,
339420d97356SBlue Swirl 
33958ee79e70SKevin Wolf     .supports_backing           = true,
339620d97356SBlue Swirl     .bdrv_change_backing_file   = qcow2_change_backing_file,
339720d97356SBlue Swirl 
3398d34682cdSKevin Wolf     .bdrv_refresh_limits        = qcow2_refresh_limits,
339906d9260fSAnthony Liguori     .bdrv_invalidate_cache      = qcow2_invalidate_cache,
3400ec6d8912SKevin Wolf     .bdrv_inactivate            = qcow2_inactivate,
340106d9260fSAnthony Liguori 
34021bd0e2d1SChunyan Liu     .create_opts         = &qcow2_create_opts,
34037c80ab3fSJes Sorensen     .bdrv_check          = qcow2_check,
3404c282e1fdSChunyan Liu     .bdrv_amend_options  = qcow2_amend_options,
3405279621c0SAlberto Garcia 
3406279621c0SAlberto Garcia     .bdrv_detach_aio_context  = qcow2_detach_aio_context,
3407279621c0SAlberto Garcia     .bdrv_attach_aio_context  = qcow2_attach_aio_context,
340820d97356SBlue Swirl };
340920d97356SBlue Swirl 
34105efa9d5aSAnthony Liguori static void bdrv_qcow2_init(void)
34115efa9d5aSAnthony Liguori {
34125efa9d5aSAnthony Liguori     bdrv_register(&bdrv_qcow2);
34135efa9d5aSAnthony Liguori }
34145efa9d5aSAnthony Liguori 
34155efa9d5aSAnthony Liguori block_init(bdrv_qcow2_init);
3416