xref: /qemu/block/qcow2.c (revision ec6d891224f708b2cda2a1edf68ffc0ff1316fca)
1585f8587Sbellard /*
2585f8587Sbellard  * Block driver for the QCOW version 2 format
3585f8587Sbellard  *
4585f8587Sbellard  * Copyright (c) 2004-2006 Fabrice Bellard
5585f8587Sbellard  *
6585f8587Sbellard  * Permission is hereby granted, free of charge, to any person obtaining a copy
7585f8587Sbellard  * of this software and associated documentation files (the "Software"), to deal
8585f8587Sbellard  * in the Software without restriction, including without limitation the rights
9585f8587Sbellard  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10585f8587Sbellard  * copies of the Software, and to permit persons to whom the Software is
11585f8587Sbellard  * furnished to do so, subject to the following conditions:
12585f8587Sbellard  *
13585f8587Sbellard  * The above copyright notice and this permission notice shall be included in
14585f8587Sbellard  * all copies or substantial portions of the Software.
15585f8587Sbellard  *
16585f8587Sbellard  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17585f8587Sbellard  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18585f8587Sbellard  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19585f8587Sbellard  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20585f8587Sbellard  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21585f8587Sbellard  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22585f8587Sbellard  * THE SOFTWARE.
23585f8587Sbellard  */
2480c71a24SPeter Maydell #include "qemu/osdep.h"
25faf07963Spbrook #include "qemu-common.h"
26737e150eSPaolo Bonzini #include "block/block_int.h"
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"
38585f8587Sbellard 
39585f8587Sbellard /*
40585f8587Sbellard   Differences with QCOW:
41585f8587Sbellard 
42585f8587Sbellard   - Support for multiple incremental snapshots.
43585f8587Sbellard   - Memory management by reference counts.
44585f8587Sbellard   - Clusters which have a reference count of one have the bit
45585f8587Sbellard     QCOW_OFLAG_COPIED to optimize write performance.
46585f8587Sbellard   - Size of compressed clusters is stored in sectors to reduce bit usage
47585f8587Sbellard     in the cluster offsets.
48585f8587Sbellard   - Support for storing additional data (such as the VM state) in the
49585f8587Sbellard     snapshots.
50585f8587Sbellard   - If a backing store is used, the cluster size is not constrained
51585f8587Sbellard     (could be backported to QCOW).
52585f8587Sbellard   - L2 tables have always a size of one cluster.
53585f8587Sbellard */
54585f8587Sbellard 
559b80ddf3Saliguori 
569b80ddf3Saliguori typedef struct {
579b80ddf3Saliguori     uint32_t magic;
589b80ddf3Saliguori     uint32_t len;
59c4217f64SJeff Cody } QEMU_PACKED QCowExtension;
6021d82ac9SJeff Cody 
617c80ab3fSJes Sorensen #define  QCOW2_EXT_MAGIC_END 0
627c80ab3fSJes Sorensen #define  QCOW2_EXT_MAGIC_BACKING_FORMAT 0xE2792ACA
63cfcc4c62SKevin Wolf #define  QCOW2_EXT_MAGIC_FEATURE_TABLE 0x6803f857
649b80ddf3Saliguori 
657c80ab3fSJes Sorensen static int qcow2_probe(const uint8_t *buf, int buf_size, const char *filename)
66585f8587Sbellard {
67585f8587Sbellard     const QCowHeader *cow_header = (const void *)buf;
68585f8587Sbellard 
69585f8587Sbellard     if (buf_size >= sizeof(QCowHeader) &&
70585f8587Sbellard         be32_to_cpu(cow_header->magic) == QCOW_MAGIC &&
716744cbabSKevin Wolf         be32_to_cpu(cow_header->version) >= 2)
72585f8587Sbellard         return 100;
73585f8587Sbellard     else
74585f8587Sbellard         return 0;
75585f8587Sbellard }
76585f8587Sbellard 
779b80ddf3Saliguori 
789b80ddf3Saliguori /*
799b80ddf3Saliguori  * read qcow2 extension and fill bs
809b80ddf3Saliguori  * start reading from start_offset
819b80ddf3Saliguori  * finish reading upon magic of value 0 or when end_offset reached
829b80ddf3Saliguori  * unknown magic is skipped (future extension this version knows nothing about)
839b80ddf3Saliguori  * return 0 upon success, non-0 otherwise
849b80ddf3Saliguori  */
857c80ab3fSJes Sorensen static int qcow2_read_extensions(BlockDriverState *bs, uint64_t start_offset,
863ef6c40aSMax Reitz                                  uint64_t end_offset, void **p_feature_table,
873ef6c40aSMax Reitz                                  Error **errp)
889b80ddf3Saliguori {
89ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
909b80ddf3Saliguori     QCowExtension ext;
919b80ddf3Saliguori     uint64_t offset;
9275bab85cSKevin Wolf     int ret;
939b80ddf3Saliguori 
949b80ddf3Saliguori #ifdef DEBUG_EXT
957c80ab3fSJes Sorensen     printf("qcow2_read_extensions: start=%ld end=%ld\n", start_offset, end_offset);
969b80ddf3Saliguori #endif
979b80ddf3Saliguori     offset = start_offset;
989b80ddf3Saliguori     while (offset < end_offset) {
999b80ddf3Saliguori 
1009b80ddf3Saliguori #ifdef DEBUG_EXT
1019b80ddf3Saliguori         /* Sanity check */
1029b80ddf3Saliguori         if (offset > s->cluster_size)
1037c80ab3fSJes Sorensen             printf("qcow2_read_extension: suspicious offset %lu\n", offset);
1049b80ddf3Saliguori 
1059b2260cbSDong Xu Wang         printf("attempting to read extended header in offset %lu\n", offset);
1069b80ddf3Saliguori #endif
1079b80ddf3Saliguori 
1089a4f4c31SKevin Wolf         ret = bdrv_pread(bs->file->bs, offset, &ext, sizeof(ext));
1093ef6c40aSMax Reitz         if (ret < 0) {
1103ef6c40aSMax Reitz             error_setg_errno(errp, -ret, "qcow2_read_extension: ERROR: "
1113ef6c40aSMax Reitz                              "pread fail from offset %" PRIu64, offset);
1129b80ddf3Saliguori             return 1;
1139b80ddf3Saliguori         }
1149b80ddf3Saliguori         be32_to_cpus(&ext.magic);
1159b80ddf3Saliguori         be32_to_cpus(&ext.len);
1169b80ddf3Saliguori         offset += sizeof(ext);
1179b80ddf3Saliguori #ifdef DEBUG_EXT
1189b80ddf3Saliguori         printf("ext.magic = 0x%x\n", ext.magic);
1199b80ddf3Saliguori #endif
1202ebafc85SKevin Wolf         if (offset > end_offset || ext.len > end_offset - offset) {
1213ef6c40aSMax Reitz             error_setg(errp, "Header extension too large");
12264ca6aeeSKevin Wolf             return -EINVAL;
12364ca6aeeSKevin Wolf         }
12464ca6aeeSKevin Wolf 
1259b80ddf3Saliguori         switch (ext.magic) {
1267c80ab3fSJes Sorensen         case QCOW2_EXT_MAGIC_END:
1279b80ddf3Saliguori             return 0;
128f965509cSaliguori 
1297c80ab3fSJes Sorensen         case QCOW2_EXT_MAGIC_BACKING_FORMAT:
130f965509cSaliguori             if (ext.len >= sizeof(bs->backing_format)) {
131521b2b5dSMax Reitz                 error_setg(errp, "ERROR: ext_backing_format: len=%" PRIu32
132521b2b5dSMax Reitz                            " too large (>=%zu)", ext.len,
133521b2b5dSMax Reitz                            sizeof(bs->backing_format));
134f965509cSaliguori                 return 2;
135f965509cSaliguori             }
1369a4f4c31SKevin Wolf             ret = bdrv_pread(bs->file->bs, offset, bs->backing_format, ext.len);
1373ef6c40aSMax Reitz             if (ret < 0) {
1383ef6c40aSMax Reitz                 error_setg_errno(errp, -ret, "ERROR: ext_backing_format: "
1393ef6c40aSMax Reitz                                  "Could not read format name");
140f965509cSaliguori                 return 3;
1413ef6c40aSMax Reitz             }
142f965509cSaliguori             bs->backing_format[ext.len] = '\0';
143e4603fe1SKevin Wolf             s->image_backing_format = g_strdup(bs->backing_format);
144f965509cSaliguori #ifdef DEBUG_EXT
145f965509cSaliguori             printf("Qcow2: Got format extension %s\n", bs->backing_format);
146f965509cSaliguori #endif
147f965509cSaliguori             break;
148f965509cSaliguori 
149cfcc4c62SKevin Wolf         case QCOW2_EXT_MAGIC_FEATURE_TABLE:
150cfcc4c62SKevin Wolf             if (p_feature_table != NULL) {
151cfcc4c62SKevin Wolf                 void* feature_table = g_malloc0(ext.len + 2 * sizeof(Qcow2Feature));
1529a4f4c31SKevin Wolf                 ret = bdrv_pread(bs->file->bs, offset , feature_table, ext.len);
153cfcc4c62SKevin Wolf                 if (ret < 0) {
1543ef6c40aSMax Reitz                     error_setg_errno(errp, -ret, "ERROR: ext_feature_table: "
1553ef6c40aSMax Reitz                                      "Could not read table");
156cfcc4c62SKevin Wolf                     return ret;
157cfcc4c62SKevin Wolf                 }
158cfcc4c62SKevin Wolf 
159cfcc4c62SKevin Wolf                 *p_feature_table = feature_table;
160cfcc4c62SKevin Wolf             }
161cfcc4c62SKevin Wolf             break;
162cfcc4c62SKevin Wolf 
1639b80ddf3Saliguori         default:
16475bab85cSKevin Wolf             /* unknown magic - save it in case we need to rewrite the header */
16575bab85cSKevin Wolf             {
16675bab85cSKevin Wolf                 Qcow2UnknownHeaderExtension *uext;
16775bab85cSKevin Wolf 
16875bab85cSKevin Wolf                 uext = g_malloc0(sizeof(*uext)  + ext.len);
16975bab85cSKevin Wolf                 uext->magic = ext.magic;
17075bab85cSKevin Wolf                 uext->len = ext.len;
17175bab85cSKevin Wolf                 QLIST_INSERT_HEAD(&s->unknown_header_ext, uext, next);
17275bab85cSKevin Wolf 
1739a4f4c31SKevin Wolf                 ret = bdrv_pread(bs->file->bs, offset , uext->data, uext->len);
17475bab85cSKevin Wolf                 if (ret < 0) {
1753ef6c40aSMax Reitz                     error_setg_errno(errp, -ret, "ERROR: unknown extension: "
1763ef6c40aSMax Reitz                                      "Could not read data");
17775bab85cSKevin Wolf                     return ret;
17875bab85cSKevin Wolf                 }
17975bab85cSKevin Wolf             }
1809b80ddf3Saliguori             break;
1819b80ddf3Saliguori         }
182fd29b4bbSKevin Wolf 
183fd29b4bbSKevin Wolf         offset += ((ext.len + 7) & ~7);
1849b80ddf3Saliguori     }
1859b80ddf3Saliguori 
1869b80ddf3Saliguori     return 0;
1879b80ddf3Saliguori }
1889b80ddf3Saliguori 
18975bab85cSKevin Wolf static void cleanup_unknown_header_ext(BlockDriverState *bs)
19075bab85cSKevin Wolf {
191ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
19275bab85cSKevin Wolf     Qcow2UnknownHeaderExtension *uext, *next;
19375bab85cSKevin Wolf 
19475bab85cSKevin Wolf     QLIST_FOREACH_SAFE(uext, &s->unknown_header_ext, next, next) {
19575bab85cSKevin Wolf         QLIST_REMOVE(uext, next);
19675bab85cSKevin Wolf         g_free(uext);
19775bab85cSKevin Wolf     }
19875bab85cSKevin Wolf }
1999b80ddf3Saliguori 
2003ef6c40aSMax Reitz static void GCC_FMT_ATTR(3, 4) report_unsupported(BlockDriverState *bs,
2013ef6c40aSMax Reitz     Error **errp, const char *fmt, ...)
2026744cbabSKevin Wolf {
2036744cbabSKevin Wolf     char msg[64];
2046744cbabSKevin Wolf     va_list ap;
2056744cbabSKevin Wolf 
2066744cbabSKevin Wolf     va_start(ap, fmt);
2076744cbabSKevin Wolf     vsnprintf(msg, sizeof(msg), fmt, ap);
2086744cbabSKevin Wolf     va_end(ap);
2096744cbabSKevin Wolf 
210c6bd8c70SMarkus Armbruster     error_setg(errp, QERR_UNKNOWN_BLOCK_FORMAT_FEATURE,
21181e5f78aSAlberto Garcia                bdrv_get_device_or_node_name(bs), "qcow2", msg);
2126744cbabSKevin Wolf }
2136744cbabSKevin Wolf 
214cfcc4c62SKevin Wolf static void report_unsupported_feature(BlockDriverState *bs,
2153ef6c40aSMax Reitz     Error **errp, Qcow2Feature *table, uint64_t mask)
216cfcc4c62SKevin Wolf {
21712ac6d3dSKevin Wolf     char *features = g_strdup("");
21812ac6d3dSKevin Wolf     char *old;
21912ac6d3dSKevin Wolf 
220cfcc4c62SKevin Wolf     while (table && table->name[0] != '\0') {
221cfcc4c62SKevin Wolf         if (table->type == QCOW2_FEAT_TYPE_INCOMPATIBLE) {
22212ac6d3dSKevin Wolf             if (mask & (1ULL << table->bit)) {
22312ac6d3dSKevin Wolf                 old = features;
22412ac6d3dSKevin Wolf                 features = g_strdup_printf("%s%s%.46s", old, *old ? ", " : "",
22512ac6d3dSKevin Wolf                                            table->name);
22612ac6d3dSKevin Wolf                 g_free(old);
22712ac6d3dSKevin Wolf                 mask &= ~(1ULL << table->bit);
228cfcc4c62SKevin Wolf             }
229cfcc4c62SKevin Wolf         }
230cfcc4c62SKevin Wolf         table++;
231cfcc4c62SKevin Wolf     }
232cfcc4c62SKevin Wolf 
233cfcc4c62SKevin Wolf     if (mask) {
23412ac6d3dSKevin Wolf         old = features;
23512ac6d3dSKevin Wolf         features = g_strdup_printf("%s%sUnknown incompatible feature: %" PRIx64,
23612ac6d3dSKevin Wolf                                    old, *old ? ", " : "", mask);
23712ac6d3dSKevin Wolf         g_free(old);
238cfcc4c62SKevin Wolf     }
23912ac6d3dSKevin Wolf 
24012ac6d3dSKevin Wolf     report_unsupported(bs, errp, "%s", features);
24112ac6d3dSKevin Wolf     g_free(features);
242cfcc4c62SKevin Wolf }
243cfcc4c62SKevin Wolf 
244c61d0004SStefan Hajnoczi /*
245bfe8043eSStefan Hajnoczi  * Sets the dirty bit and flushes afterwards if necessary.
246bfe8043eSStefan Hajnoczi  *
247bfe8043eSStefan Hajnoczi  * The incompatible_features bit is only set if the image file header was
248bfe8043eSStefan Hajnoczi  * updated successfully.  Therefore it is not required to check the return
249bfe8043eSStefan Hajnoczi  * value of this function.
250bfe8043eSStefan Hajnoczi  */
251280d3735SKevin Wolf int qcow2_mark_dirty(BlockDriverState *bs)
252bfe8043eSStefan Hajnoczi {
253ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
254bfe8043eSStefan Hajnoczi     uint64_t val;
255bfe8043eSStefan Hajnoczi     int ret;
256bfe8043eSStefan Hajnoczi 
257bfe8043eSStefan Hajnoczi     assert(s->qcow_version >= 3);
258bfe8043eSStefan Hajnoczi 
259bfe8043eSStefan Hajnoczi     if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
260bfe8043eSStefan Hajnoczi         return 0; /* already dirty */
261bfe8043eSStefan Hajnoczi     }
262bfe8043eSStefan Hajnoczi 
263bfe8043eSStefan Hajnoczi     val = cpu_to_be64(s->incompatible_features | QCOW2_INCOMPAT_DIRTY);
2649a4f4c31SKevin Wolf     ret = bdrv_pwrite(bs->file->bs, offsetof(QCowHeader, incompatible_features),
265bfe8043eSStefan Hajnoczi                       &val, sizeof(val));
266bfe8043eSStefan Hajnoczi     if (ret < 0) {
267bfe8043eSStefan Hajnoczi         return ret;
268bfe8043eSStefan Hajnoczi     }
2699a4f4c31SKevin Wolf     ret = bdrv_flush(bs->file->bs);
270bfe8043eSStefan Hajnoczi     if (ret < 0) {
271bfe8043eSStefan Hajnoczi         return ret;
272bfe8043eSStefan Hajnoczi     }
273bfe8043eSStefan Hajnoczi 
274bfe8043eSStefan Hajnoczi     /* Only treat image as dirty if the header was updated successfully */
275bfe8043eSStefan Hajnoczi     s->incompatible_features |= QCOW2_INCOMPAT_DIRTY;
276bfe8043eSStefan Hajnoczi     return 0;
277bfe8043eSStefan Hajnoczi }
278bfe8043eSStefan Hajnoczi 
279bfe8043eSStefan Hajnoczi /*
280c61d0004SStefan Hajnoczi  * Clears the dirty bit and flushes before if necessary.  Only call this
281c61d0004SStefan Hajnoczi  * function when there are no pending requests, it does not guard against
282c61d0004SStefan Hajnoczi  * concurrent requests dirtying the image.
283c61d0004SStefan Hajnoczi  */
284c61d0004SStefan Hajnoczi static int qcow2_mark_clean(BlockDriverState *bs)
285c61d0004SStefan Hajnoczi {
286ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
287c61d0004SStefan Hajnoczi 
288c61d0004SStefan Hajnoczi     if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
2894c2e5f8fSKevin Wolf         int ret;
2904c2e5f8fSKevin Wolf 
2914c2e5f8fSKevin Wolf         s->incompatible_features &= ~QCOW2_INCOMPAT_DIRTY;
2924c2e5f8fSKevin Wolf 
2934c2e5f8fSKevin Wolf         ret = bdrv_flush(bs);
294c61d0004SStefan Hajnoczi         if (ret < 0) {
295c61d0004SStefan Hajnoczi             return ret;
296c61d0004SStefan Hajnoczi         }
297c61d0004SStefan Hajnoczi 
298c61d0004SStefan Hajnoczi         return qcow2_update_header(bs);
299c61d0004SStefan Hajnoczi     }
300c61d0004SStefan Hajnoczi     return 0;
301c61d0004SStefan Hajnoczi }
302c61d0004SStefan Hajnoczi 
30369c98726SMax Reitz /*
30469c98726SMax Reitz  * Marks the image as corrupt.
30569c98726SMax Reitz  */
30669c98726SMax Reitz int qcow2_mark_corrupt(BlockDriverState *bs)
30769c98726SMax Reitz {
308ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
30969c98726SMax Reitz 
31069c98726SMax Reitz     s->incompatible_features |= QCOW2_INCOMPAT_CORRUPT;
31169c98726SMax Reitz     return qcow2_update_header(bs);
31269c98726SMax Reitz }
31369c98726SMax Reitz 
31469c98726SMax Reitz /*
31569c98726SMax Reitz  * Marks the image as consistent, i.e., unsets the corrupt bit, and flushes
31669c98726SMax Reitz  * before if necessary.
31769c98726SMax Reitz  */
31869c98726SMax Reitz int qcow2_mark_consistent(BlockDriverState *bs)
31969c98726SMax Reitz {
320ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
32169c98726SMax Reitz 
32269c98726SMax Reitz     if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
32369c98726SMax Reitz         int ret = bdrv_flush(bs);
32469c98726SMax Reitz         if (ret < 0) {
32569c98726SMax Reitz             return ret;
32669c98726SMax Reitz         }
32769c98726SMax Reitz 
32869c98726SMax Reitz         s->incompatible_features &= ~QCOW2_INCOMPAT_CORRUPT;
32969c98726SMax Reitz         return qcow2_update_header(bs);
33069c98726SMax Reitz     }
33169c98726SMax Reitz     return 0;
33269c98726SMax Reitz }
33369c98726SMax Reitz 
334acbe5982SStefan Hajnoczi static int qcow2_check(BlockDriverState *bs, BdrvCheckResult *result,
335acbe5982SStefan Hajnoczi                        BdrvCheckMode fix)
336acbe5982SStefan Hajnoczi {
337acbe5982SStefan Hajnoczi     int ret = qcow2_check_refcounts(bs, result, fix);
338acbe5982SStefan Hajnoczi     if (ret < 0) {
339acbe5982SStefan Hajnoczi         return ret;
340acbe5982SStefan Hajnoczi     }
341acbe5982SStefan Hajnoczi 
342acbe5982SStefan Hajnoczi     if (fix && result->check_errors == 0 && result->corruptions == 0) {
34324530f3eSMax Reitz         ret = qcow2_mark_clean(bs);
34424530f3eSMax Reitz         if (ret < 0) {
34524530f3eSMax Reitz             return ret;
34624530f3eSMax Reitz         }
34724530f3eSMax Reitz         return qcow2_mark_consistent(bs);
348acbe5982SStefan Hajnoczi     }
349acbe5982SStefan Hajnoczi     return ret;
350acbe5982SStefan Hajnoczi }
351acbe5982SStefan Hajnoczi 
3528c7de283SKevin Wolf static int validate_table_offset(BlockDriverState *bs, uint64_t offset,
3538c7de283SKevin Wolf                                  uint64_t entries, size_t entry_len)
3548c7de283SKevin Wolf {
355ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
3568c7de283SKevin Wolf     uint64_t size;
3578c7de283SKevin Wolf 
3588c7de283SKevin Wolf     /* Use signed INT64_MAX as the maximum even for uint64_t header fields,
3598c7de283SKevin Wolf      * because values will be passed to qemu functions taking int64_t. */
3608c7de283SKevin Wolf     if (entries > INT64_MAX / entry_len) {
3618c7de283SKevin Wolf         return -EINVAL;
3628c7de283SKevin Wolf     }
3638c7de283SKevin Wolf 
3648c7de283SKevin Wolf     size = entries * entry_len;
3658c7de283SKevin Wolf 
3668c7de283SKevin Wolf     if (INT64_MAX - size < offset) {
3678c7de283SKevin Wolf         return -EINVAL;
3688c7de283SKevin Wolf     }
3698c7de283SKevin Wolf 
3708c7de283SKevin Wolf     /* Tables must be cluster aligned */
3718c7de283SKevin Wolf     if (offset & (s->cluster_size - 1)) {
3728c7de283SKevin Wolf         return -EINVAL;
3738c7de283SKevin Wolf     }
3748c7de283SKevin Wolf 
3758c7de283SKevin Wolf     return 0;
3768c7de283SKevin Wolf }
3778c7de283SKevin Wolf 
37874c4510aSKevin Wolf static QemuOptsList qcow2_runtime_opts = {
37974c4510aSKevin Wolf     .name = "qcow2",
38074c4510aSKevin Wolf     .head = QTAILQ_HEAD_INITIALIZER(qcow2_runtime_opts.head),
38174c4510aSKevin Wolf     .desc = {
38274c4510aSKevin Wolf         {
38364aa99d3SKevin Wolf             .name = QCOW2_OPT_LAZY_REFCOUNTS,
38474c4510aSKevin Wolf             .type = QEMU_OPT_BOOL,
38574c4510aSKevin Wolf             .help = "Postpone refcount updates",
38674c4510aSKevin Wolf         },
38767af674eSKevin Wolf         {
38867af674eSKevin Wolf             .name = QCOW2_OPT_DISCARD_REQUEST,
38967af674eSKevin Wolf             .type = QEMU_OPT_BOOL,
39067af674eSKevin Wolf             .help = "Pass guest discard requests to the layer below",
39167af674eSKevin Wolf         },
39267af674eSKevin Wolf         {
39367af674eSKevin Wolf             .name = QCOW2_OPT_DISCARD_SNAPSHOT,
39467af674eSKevin Wolf             .type = QEMU_OPT_BOOL,
39567af674eSKevin Wolf             .help = "Generate discard requests when snapshot related space "
39667af674eSKevin Wolf                     "is freed",
39767af674eSKevin Wolf         },
39867af674eSKevin Wolf         {
39967af674eSKevin Wolf             .name = QCOW2_OPT_DISCARD_OTHER,
40067af674eSKevin Wolf             .type = QEMU_OPT_BOOL,
40167af674eSKevin Wolf             .help = "Generate discard requests when other clusters are freed",
40267af674eSKevin Wolf         },
40305de7e86SMax Reitz         {
40405de7e86SMax Reitz             .name = QCOW2_OPT_OVERLAP,
40505de7e86SMax Reitz             .type = QEMU_OPT_STRING,
40605de7e86SMax Reitz             .help = "Selects which overlap checks to perform from a range of "
40705de7e86SMax Reitz                     "templates (none, constant, cached, all)",
40805de7e86SMax Reitz         },
40905de7e86SMax Reitz         {
410ee42b5ceSMax Reitz             .name = QCOW2_OPT_OVERLAP_TEMPLATE,
411ee42b5ceSMax Reitz             .type = QEMU_OPT_STRING,
412ee42b5ceSMax Reitz             .help = "Selects which overlap checks to perform from a range of "
413ee42b5ceSMax Reitz                     "templates (none, constant, cached, all)",
414ee42b5ceSMax Reitz         },
415ee42b5ceSMax Reitz         {
41605de7e86SMax Reitz             .name = QCOW2_OPT_OVERLAP_MAIN_HEADER,
41705de7e86SMax Reitz             .type = QEMU_OPT_BOOL,
41805de7e86SMax Reitz             .help = "Check for unintended writes into the main qcow2 header",
41905de7e86SMax Reitz         },
42005de7e86SMax Reitz         {
42105de7e86SMax Reitz             .name = QCOW2_OPT_OVERLAP_ACTIVE_L1,
42205de7e86SMax Reitz             .type = QEMU_OPT_BOOL,
42305de7e86SMax Reitz             .help = "Check for unintended writes into the active L1 table",
42405de7e86SMax Reitz         },
42505de7e86SMax Reitz         {
42605de7e86SMax Reitz             .name = QCOW2_OPT_OVERLAP_ACTIVE_L2,
42705de7e86SMax Reitz             .type = QEMU_OPT_BOOL,
42805de7e86SMax Reitz             .help = "Check for unintended writes into an active L2 table",
42905de7e86SMax Reitz         },
43005de7e86SMax Reitz         {
43105de7e86SMax Reitz             .name = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
43205de7e86SMax Reitz             .type = QEMU_OPT_BOOL,
43305de7e86SMax Reitz             .help = "Check for unintended writes into the refcount table",
43405de7e86SMax Reitz         },
43505de7e86SMax Reitz         {
43605de7e86SMax Reitz             .name = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
43705de7e86SMax Reitz             .type = QEMU_OPT_BOOL,
43805de7e86SMax Reitz             .help = "Check for unintended writes into a refcount block",
43905de7e86SMax Reitz         },
44005de7e86SMax Reitz         {
44105de7e86SMax Reitz             .name = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
44205de7e86SMax Reitz             .type = QEMU_OPT_BOOL,
44305de7e86SMax Reitz             .help = "Check for unintended writes into the snapshot table",
44405de7e86SMax Reitz         },
44505de7e86SMax Reitz         {
44605de7e86SMax Reitz             .name = QCOW2_OPT_OVERLAP_INACTIVE_L1,
44705de7e86SMax Reitz             .type = QEMU_OPT_BOOL,
44805de7e86SMax Reitz             .help = "Check for unintended writes into an inactive L1 table",
44905de7e86SMax Reitz         },
45005de7e86SMax Reitz         {
45105de7e86SMax Reitz             .name = QCOW2_OPT_OVERLAP_INACTIVE_L2,
45205de7e86SMax Reitz             .type = QEMU_OPT_BOOL,
45305de7e86SMax Reitz             .help = "Check for unintended writes into an inactive L2 table",
45405de7e86SMax Reitz         },
4556c1c8d5dSMax Reitz         {
4566c1c8d5dSMax Reitz             .name = QCOW2_OPT_CACHE_SIZE,
4576c1c8d5dSMax Reitz             .type = QEMU_OPT_SIZE,
4586c1c8d5dSMax Reitz             .help = "Maximum combined metadata (L2 tables and refcount blocks) "
4596c1c8d5dSMax Reitz                     "cache size",
4606c1c8d5dSMax Reitz         },
4616c1c8d5dSMax Reitz         {
4626c1c8d5dSMax Reitz             .name = QCOW2_OPT_L2_CACHE_SIZE,
4636c1c8d5dSMax Reitz             .type = QEMU_OPT_SIZE,
4646c1c8d5dSMax Reitz             .help = "Maximum L2 table cache size",
4656c1c8d5dSMax Reitz         },
4666c1c8d5dSMax Reitz         {
4676c1c8d5dSMax Reitz             .name = QCOW2_OPT_REFCOUNT_CACHE_SIZE,
4686c1c8d5dSMax Reitz             .type = QEMU_OPT_SIZE,
4696c1c8d5dSMax Reitz             .help = "Maximum refcount block cache size",
4706c1c8d5dSMax Reitz         },
471279621c0SAlberto Garcia         {
472279621c0SAlberto Garcia             .name = QCOW2_OPT_CACHE_CLEAN_INTERVAL,
473279621c0SAlberto Garcia             .type = QEMU_OPT_NUMBER,
474279621c0SAlberto Garcia             .help = "Clean unused cache entries after this time (in seconds)",
475279621c0SAlberto Garcia         },
47674c4510aSKevin Wolf         { /* end of list */ }
47774c4510aSKevin Wolf     },
47874c4510aSKevin Wolf };
47974c4510aSKevin Wolf 
4804092e99dSMax Reitz static const char *overlap_bool_option_names[QCOW2_OL_MAX_BITNR] = {
4814092e99dSMax Reitz     [QCOW2_OL_MAIN_HEADER_BITNR]    = QCOW2_OPT_OVERLAP_MAIN_HEADER,
4824092e99dSMax Reitz     [QCOW2_OL_ACTIVE_L1_BITNR]      = QCOW2_OPT_OVERLAP_ACTIVE_L1,
4834092e99dSMax Reitz     [QCOW2_OL_ACTIVE_L2_BITNR]      = QCOW2_OPT_OVERLAP_ACTIVE_L2,
4844092e99dSMax Reitz     [QCOW2_OL_REFCOUNT_TABLE_BITNR] = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
4854092e99dSMax Reitz     [QCOW2_OL_REFCOUNT_BLOCK_BITNR] = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
4864092e99dSMax Reitz     [QCOW2_OL_SNAPSHOT_TABLE_BITNR] = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
4874092e99dSMax Reitz     [QCOW2_OL_INACTIVE_L1_BITNR]    = QCOW2_OPT_OVERLAP_INACTIVE_L1,
4884092e99dSMax Reitz     [QCOW2_OL_INACTIVE_L2_BITNR]    = QCOW2_OPT_OVERLAP_INACTIVE_L2,
4894092e99dSMax Reitz };
4904092e99dSMax Reitz 
491279621c0SAlberto Garcia static void cache_clean_timer_cb(void *opaque)
492279621c0SAlberto Garcia {
493279621c0SAlberto Garcia     BlockDriverState *bs = opaque;
494ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
495279621c0SAlberto Garcia     qcow2_cache_clean_unused(bs, s->l2_table_cache);
496279621c0SAlberto Garcia     qcow2_cache_clean_unused(bs, s->refcount_block_cache);
497279621c0SAlberto Garcia     timer_mod(s->cache_clean_timer, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) +
498279621c0SAlberto Garcia               (int64_t) s->cache_clean_interval * 1000);
499279621c0SAlberto Garcia }
500279621c0SAlberto Garcia 
501279621c0SAlberto Garcia static void cache_clean_timer_init(BlockDriverState *bs, AioContext *context)
502279621c0SAlberto Garcia {
503ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
504279621c0SAlberto Garcia     if (s->cache_clean_interval > 0) {
505279621c0SAlberto Garcia         s->cache_clean_timer = aio_timer_new(context, QEMU_CLOCK_VIRTUAL,
506279621c0SAlberto Garcia                                              SCALE_MS, cache_clean_timer_cb,
507279621c0SAlberto Garcia                                              bs);
508279621c0SAlberto Garcia         timer_mod(s->cache_clean_timer, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) +
509279621c0SAlberto Garcia                   (int64_t) s->cache_clean_interval * 1000);
510279621c0SAlberto Garcia     }
511279621c0SAlberto Garcia }
512279621c0SAlberto Garcia 
513279621c0SAlberto Garcia static void cache_clean_timer_del(BlockDriverState *bs)
514279621c0SAlberto Garcia {
515ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
516279621c0SAlberto Garcia     if (s->cache_clean_timer) {
517279621c0SAlberto Garcia         timer_del(s->cache_clean_timer);
518279621c0SAlberto Garcia         timer_free(s->cache_clean_timer);
519279621c0SAlberto Garcia         s->cache_clean_timer = NULL;
520279621c0SAlberto Garcia     }
521279621c0SAlberto Garcia }
522279621c0SAlberto Garcia 
523279621c0SAlberto Garcia static void qcow2_detach_aio_context(BlockDriverState *bs)
524279621c0SAlberto Garcia {
525279621c0SAlberto Garcia     cache_clean_timer_del(bs);
526279621c0SAlberto Garcia }
527279621c0SAlberto Garcia 
528279621c0SAlberto Garcia static void qcow2_attach_aio_context(BlockDriverState *bs,
529279621c0SAlberto Garcia                                      AioContext *new_context)
530279621c0SAlberto Garcia {
531279621c0SAlberto Garcia     cache_clean_timer_init(bs, new_context);
532279621c0SAlberto Garcia }
533279621c0SAlberto Garcia 
534bc85ef26SMax Reitz static void read_cache_sizes(BlockDriverState *bs, QemuOpts *opts,
535bc85ef26SMax Reitz                              uint64_t *l2_cache_size,
5366c1c8d5dSMax Reitz                              uint64_t *refcount_cache_size, Error **errp)
5376c1c8d5dSMax Reitz {
538ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
5396c1c8d5dSMax Reitz     uint64_t combined_cache_size;
5406c1c8d5dSMax Reitz     bool l2_cache_size_set, refcount_cache_size_set, combined_cache_size_set;
5416c1c8d5dSMax Reitz 
5426c1c8d5dSMax Reitz     combined_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_CACHE_SIZE);
5436c1c8d5dSMax Reitz     l2_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_L2_CACHE_SIZE);
5446c1c8d5dSMax Reitz     refcount_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
5456c1c8d5dSMax Reitz 
5466c1c8d5dSMax Reitz     combined_cache_size = qemu_opt_get_size(opts, QCOW2_OPT_CACHE_SIZE, 0);
5476c1c8d5dSMax Reitz     *l2_cache_size = qemu_opt_get_size(opts, QCOW2_OPT_L2_CACHE_SIZE, 0);
5486c1c8d5dSMax Reitz     *refcount_cache_size = qemu_opt_get_size(opts,
5496c1c8d5dSMax Reitz                                              QCOW2_OPT_REFCOUNT_CACHE_SIZE, 0);
5506c1c8d5dSMax Reitz 
5516c1c8d5dSMax Reitz     if (combined_cache_size_set) {
5526c1c8d5dSMax Reitz         if (l2_cache_size_set && refcount_cache_size_set) {
5536c1c8d5dSMax Reitz             error_setg(errp, QCOW2_OPT_CACHE_SIZE ", " QCOW2_OPT_L2_CACHE_SIZE
5546c1c8d5dSMax Reitz                        " and " QCOW2_OPT_REFCOUNT_CACHE_SIZE " may not be set "
5556c1c8d5dSMax Reitz                        "the same time");
5566c1c8d5dSMax Reitz             return;
5576c1c8d5dSMax Reitz         } else if (*l2_cache_size > combined_cache_size) {
5586c1c8d5dSMax Reitz             error_setg(errp, QCOW2_OPT_L2_CACHE_SIZE " may not exceed "
5596c1c8d5dSMax Reitz                        QCOW2_OPT_CACHE_SIZE);
5606c1c8d5dSMax Reitz             return;
5616c1c8d5dSMax Reitz         } else if (*refcount_cache_size > combined_cache_size) {
5626c1c8d5dSMax Reitz             error_setg(errp, QCOW2_OPT_REFCOUNT_CACHE_SIZE " may not exceed "
5636c1c8d5dSMax Reitz                        QCOW2_OPT_CACHE_SIZE);
5646c1c8d5dSMax Reitz             return;
5656c1c8d5dSMax Reitz         }
5666c1c8d5dSMax Reitz 
5676c1c8d5dSMax Reitz         if (l2_cache_size_set) {
5686c1c8d5dSMax Reitz             *refcount_cache_size = combined_cache_size - *l2_cache_size;
5696c1c8d5dSMax Reitz         } else if (refcount_cache_size_set) {
5706c1c8d5dSMax Reitz             *l2_cache_size = combined_cache_size - *refcount_cache_size;
5716c1c8d5dSMax Reitz         } else {
5726c1c8d5dSMax Reitz             *refcount_cache_size = combined_cache_size
5736c1c8d5dSMax Reitz                                  / (DEFAULT_L2_REFCOUNT_SIZE_RATIO + 1);
5746c1c8d5dSMax Reitz             *l2_cache_size = combined_cache_size - *refcount_cache_size;
5756c1c8d5dSMax Reitz         }
5766c1c8d5dSMax Reitz     } else {
5776c1c8d5dSMax Reitz         if (!l2_cache_size_set && !refcount_cache_size_set) {
578bc85ef26SMax Reitz             *l2_cache_size = MAX(DEFAULT_L2_CACHE_BYTE_SIZE,
579bc85ef26SMax Reitz                                  (uint64_t)DEFAULT_L2_CACHE_CLUSTERS
580bc85ef26SMax Reitz                                  * s->cluster_size);
5816c1c8d5dSMax Reitz             *refcount_cache_size = *l2_cache_size
5826c1c8d5dSMax Reitz                                  / DEFAULT_L2_REFCOUNT_SIZE_RATIO;
5836c1c8d5dSMax Reitz         } else if (!l2_cache_size_set) {
5846c1c8d5dSMax Reitz             *l2_cache_size = *refcount_cache_size
5856c1c8d5dSMax Reitz                            * DEFAULT_L2_REFCOUNT_SIZE_RATIO;
5866c1c8d5dSMax Reitz         } else if (!refcount_cache_size_set) {
5876c1c8d5dSMax Reitz             *refcount_cache_size = *l2_cache_size
5886c1c8d5dSMax Reitz                                  / DEFAULT_L2_REFCOUNT_SIZE_RATIO;
5896c1c8d5dSMax Reitz         }
5906c1c8d5dSMax Reitz     }
5916c1c8d5dSMax Reitz }
5926c1c8d5dSMax Reitz 
593ee55b173SKevin Wolf typedef struct Qcow2ReopenState {
594ee55b173SKevin Wolf     Qcow2Cache *l2_table_cache;
595ee55b173SKevin Wolf     Qcow2Cache *refcount_block_cache;
596ee55b173SKevin Wolf     bool use_lazy_refcounts;
597ee55b173SKevin Wolf     int overlap_check;
598ee55b173SKevin Wolf     bool discard_passthrough[QCOW2_DISCARD_MAX];
599ee55b173SKevin Wolf     uint64_t cache_clean_interval;
600ee55b173SKevin Wolf } Qcow2ReopenState;
601ee55b173SKevin Wolf 
602ee55b173SKevin Wolf static int qcow2_update_options_prepare(BlockDriverState *bs,
603ee55b173SKevin Wolf                                         Qcow2ReopenState *r,
604ee55b173SKevin Wolf                                         QDict *options, int flags,
605ee55b173SKevin Wolf                                         Error **errp)
6064c75d1a1SKevin Wolf {
6074c75d1a1SKevin Wolf     BDRVQcow2State *s = bs->opaque;
60894edf3fbSKevin Wolf     QemuOpts *opts = NULL;
6094c75d1a1SKevin Wolf     const char *opt_overlap_check, *opt_overlap_check_template;
6104c75d1a1SKevin Wolf     int overlap_check_template = 0;
61194edf3fbSKevin Wolf     uint64_t l2_cache_size, refcount_cache_size;
6124c75d1a1SKevin Wolf     int i;
61394edf3fbSKevin Wolf     Error *local_err = NULL;
6144c75d1a1SKevin Wolf     int ret;
6154c75d1a1SKevin Wolf 
61694edf3fbSKevin Wolf     opts = qemu_opts_create(&qcow2_runtime_opts, NULL, 0, &error_abort);
61794edf3fbSKevin Wolf     qemu_opts_absorb_qdict(opts, options, &local_err);
61894edf3fbSKevin Wolf     if (local_err) {
61994edf3fbSKevin Wolf         error_propagate(errp, local_err);
62094edf3fbSKevin Wolf         ret = -EINVAL;
62194edf3fbSKevin Wolf         goto fail;
62294edf3fbSKevin Wolf     }
62394edf3fbSKevin Wolf 
62494edf3fbSKevin Wolf     /* get L2 table/refcount block cache size from command line options */
62594edf3fbSKevin Wolf     read_cache_sizes(bs, opts, &l2_cache_size, &refcount_cache_size,
62694edf3fbSKevin Wolf                      &local_err);
62794edf3fbSKevin Wolf     if (local_err) {
62894edf3fbSKevin Wolf         error_propagate(errp, local_err);
62994edf3fbSKevin Wolf         ret = -EINVAL;
63094edf3fbSKevin Wolf         goto fail;
63194edf3fbSKevin Wolf     }
63294edf3fbSKevin Wolf 
63394edf3fbSKevin Wolf     l2_cache_size /= s->cluster_size;
63494edf3fbSKevin Wolf     if (l2_cache_size < MIN_L2_CACHE_SIZE) {
63594edf3fbSKevin Wolf         l2_cache_size = MIN_L2_CACHE_SIZE;
63694edf3fbSKevin Wolf     }
63794edf3fbSKevin Wolf     if (l2_cache_size > INT_MAX) {
63894edf3fbSKevin Wolf         error_setg(errp, "L2 cache size too big");
63994edf3fbSKevin Wolf         ret = -EINVAL;
64094edf3fbSKevin Wolf         goto fail;
64194edf3fbSKevin Wolf     }
64294edf3fbSKevin Wolf 
64394edf3fbSKevin Wolf     refcount_cache_size /= s->cluster_size;
64494edf3fbSKevin Wolf     if (refcount_cache_size < MIN_REFCOUNT_CACHE_SIZE) {
64594edf3fbSKevin Wolf         refcount_cache_size = MIN_REFCOUNT_CACHE_SIZE;
64694edf3fbSKevin Wolf     }
64794edf3fbSKevin Wolf     if (refcount_cache_size > INT_MAX) {
64894edf3fbSKevin Wolf         error_setg(errp, "Refcount cache size too big");
64994edf3fbSKevin Wolf         ret = -EINVAL;
65094edf3fbSKevin Wolf         goto fail;
65194edf3fbSKevin Wolf     }
65294edf3fbSKevin Wolf 
6535b0959a7SKevin Wolf     /* alloc new L2 table/refcount block cache, flush old one */
6545b0959a7SKevin Wolf     if (s->l2_table_cache) {
6555b0959a7SKevin Wolf         ret = qcow2_cache_flush(bs, s->l2_table_cache);
6565b0959a7SKevin Wolf         if (ret) {
6575b0959a7SKevin Wolf             error_setg_errno(errp, -ret, "Failed to flush the L2 table cache");
6585b0959a7SKevin Wolf             goto fail;
6595b0959a7SKevin Wolf         }
6605b0959a7SKevin Wolf     }
6615b0959a7SKevin Wolf 
6625b0959a7SKevin Wolf     if (s->refcount_block_cache) {
6635b0959a7SKevin Wolf         ret = qcow2_cache_flush(bs, s->refcount_block_cache);
6645b0959a7SKevin Wolf         if (ret) {
6655b0959a7SKevin Wolf             error_setg_errno(errp, -ret,
6665b0959a7SKevin Wolf                              "Failed to flush the refcount block cache");
6675b0959a7SKevin Wolf             goto fail;
6685b0959a7SKevin Wolf         }
6695b0959a7SKevin Wolf     }
6705b0959a7SKevin Wolf 
671ee55b173SKevin Wolf     r->l2_table_cache = qcow2_cache_create(bs, l2_cache_size);
672ee55b173SKevin Wolf     r->refcount_block_cache = qcow2_cache_create(bs, refcount_cache_size);
673ee55b173SKevin Wolf     if (r->l2_table_cache == NULL || r->refcount_block_cache == NULL) {
67494edf3fbSKevin Wolf         error_setg(errp, "Could not allocate metadata caches");
67594edf3fbSKevin Wolf         ret = -ENOMEM;
67694edf3fbSKevin Wolf         goto fail;
67794edf3fbSKevin Wolf     }
67894edf3fbSKevin Wolf 
67994edf3fbSKevin Wolf     /* New interval for cache cleanup timer */
680ee55b173SKevin Wolf     r->cache_clean_interval =
6815b0959a7SKevin Wolf         qemu_opt_get_number(opts, QCOW2_OPT_CACHE_CLEAN_INTERVAL,
6825b0959a7SKevin Wolf                             s->cache_clean_interval);
683ee55b173SKevin Wolf     if (r->cache_clean_interval > UINT_MAX) {
68494edf3fbSKevin Wolf         error_setg(errp, "Cache clean interval too big");
68594edf3fbSKevin Wolf         ret = -EINVAL;
68694edf3fbSKevin Wolf         goto fail;
68794edf3fbSKevin Wolf     }
68894edf3fbSKevin Wolf 
6895b0959a7SKevin Wolf     /* lazy-refcounts; flush if going from enabled to disabled */
690ee55b173SKevin Wolf     r->use_lazy_refcounts = qemu_opt_get_bool(opts, QCOW2_OPT_LAZY_REFCOUNTS,
6914c75d1a1SKevin Wolf         (s->compatible_features & QCOW2_COMPAT_LAZY_REFCOUNTS));
692ee55b173SKevin Wolf     if (r->use_lazy_refcounts && s->qcow_version < 3) {
693007dbc39SKevin Wolf         error_setg(errp, "Lazy refcounts require a qcow2 image with at least "
694007dbc39SKevin Wolf                    "qemu 1.1 compatibility level");
695007dbc39SKevin Wolf         ret = -EINVAL;
696007dbc39SKevin Wolf         goto fail;
697007dbc39SKevin Wolf     }
6984c75d1a1SKevin Wolf 
6995b0959a7SKevin Wolf     if (s->use_lazy_refcounts && !r->use_lazy_refcounts) {
7005b0959a7SKevin Wolf         ret = qcow2_mark_clean(bs);
7015b0959a7SKevin Wolf         if (ret < 0) {
7025b0959a7SKevin Wolf             error_setg_errno(errp, -ret, "Failed to disable lazy refcounts");
7035b0959a7SKevin Wolf             goto fail;
7045b0959a7SKevin Wolf         }
7055b0959a7SKevin Wolf     }
7065b0959a7SKevin Wolf 
707007dbc39SKevin Wolf     /* Overlap check options */
7084c75d1a1SKevin Wolf     opt_overlap_check = qemu_opt_get(opts, QCOW2_OPT_OVERLAP);
7094c75d1a1SKevin Wolf     opt_overlap_check_template = qemu_opt_get(opts, QCOW2_OPT_OVERLAP_TEMPLATE);
7104c75d1a1SKevin Wolf     if (opt_overlap_check_template && opt_overlap_check &&
7114c75d1a1SKevin Wolf         strcmp(opt_overlap_check_template, opt_overlap_check))
7124c75d1a1SKevin Wolf     {
7134c75d1a1SKevin Wolf         error_setg(errp, "Conflicting values for qcow2 options '"
7144c75d1a1SKevin Wolf                    QCOW2_OPT_OVERLAP "' ('%s') and '" QCOW2_OPT_OVERLAP_TEMPLATE
7154c75d1a1SKevin Wolf                    "' ('%s')", opt_overlap_check, opt_overlap_check_template);
7164c75d1a1SKevin Wolf         ret = -EINVAL;
7174c75d1a1SKevin Wolf         goto fail;
7184c75d1a1SKevin Wolf     }
7194c75d1a1SKevin Wolf     if (!opt_overlap_check) {
7204c75d1a1SKevin Wolf         opt_overlap_check = opt_overlap_check_template ?: "cached";
7214c75d1a1SKevin Wolf     }
7224c75d1a1SKevin Wolf 
7234c75d1a1SKevin Wolf     if (!strcmp(opt_overlap_check, "none")) {
7244c75d1a1SKevin Wolf         overlap_check_template = 0;
7254c75d1a1SKevin Wolf     } else if (!strcmp(opt_overlap_check, "constant")) {
7264c75d1a1SKevin Wolf         overlap_check_template = QCOW2_OL_CONSTANT;
7274c75d1a1SKevin Wolf     } else if (!strcmp(opt_overlap_check, "cached")) {
7284c75d1a1SKevin Wolf         overlap_check_template = QCOW2_OL_CACHED;
7294c75d1a1SKevin Wolf     } else if (!strcmp(opt_overlap_check, "all")) {
7304c75d1a1SKevin Wolf         overlap_check_template = QCOW2_OL_ALL;
7314c75d1a1SKevin Wolf     } else {
7324c75d1a1SKevin Wolf         error_setg(errp, "Unsupported value '%s' for qcow2 option "
7334c75d1a1SKevin Wolf                    "'overlap-check'. Allowed are any of the following: "
7344c75d1a1SKevin Wolf                    "none, constant, cached, all", opt_overlap_check);
7354c75d1a1SKevin Wolf         ret = -EINVAL;
7364c75d1a1SKevin Wolf         goto fail;
7374c75d1a1SKevin Wolf     }
7384c75d1a1SKevin Wolf 
739ee55b173SKevin Wolf     r->overlap_check = 0;
7404c75d1a1SKevin Wolf     for (i = 0; i < QCOW2_OL_MAX_BITNR; i++) {
7414c75d1a1SKevin Wolf         /* overlap-check defines a template bitmask, but every flag may be
7424c75d1a1SKevin Wolf          * overwritten through the associated boolean option */
743ee55b173SKevin Wolf         r->overlap_check |=
7444c75d1a1SKevin Wolf             qemu_opt_get_bool(opts, overlap_bool_option_names[i],
7454c75d1a1SKevin Wolf                               overlap_check_template & (1 << i)) << i;
7464c75d1a1SKevin Wolf     }
7474c75d1a1SKevin Wolf 
748ee55b173SKevin Wolf     r->discard_passthrough[QCOW2_DISCARD_NEVER] = false;
749ee55b173SKevin Wolf     r->discard_passthrough[QCOW2_DISCARD_ALWAYS] = true;
750ee55b173SKevin Wolf     r->discard_passthrough[QCOW2_DISCARD_REQUEST] =
751007dbc39SKevin Wolf         qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_REQUEST,
752007dbc39SKevin Wolf                           flags & BDRV_O_UNMAP);
753ee55b173SKevin Wolf     r->discard_passthrough[QCOW2_DISCARD_SNAPSHOT] =
754007dbc39SKevin Wolf         qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_SNAPSHOT, true);
755ee55b173SKevin Wolf     r->discard_passthrough[QCOW2_DISCARD_OTHER] =
756007dbc39SKevin Wolf         qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_OTHER, false);
757007dbc39SKevin Wolf 
7584c75d1a1SKevin Wolf     ret = 0;
7594c75d1a1SKevin Wolf fail:
76094edf3fbSKevin Wolf     qemu_opts_del(opts);
76194edf3fbSKevin Wolf     opts = NULL;
762ee55b173SKevin Wolf     return ret;
763ee55b173SKevin Wolf }
764ee55b173SKevin Wolf 
765ee55b173SKevin Wolf static void qcow2_update_options_commit(BlockDriverState *bs,
766ee55b173SKevin Wolf                                         Qcow2ReopenState *r)
767ee55b173SKevin Wolf {
768ee55b173SKevin Wolf     BDRVQcow2State *s = bs->opaque;
769ee55b173SKevin Wolf     int i;
770ee55b173SKevin Wolf 
7715b0959a7SKevin Wolf     if (s->l2_table_cache) {
7725b0959a7SKevin Wolf         qcow2_cache_destroy(bs, s->l2_table_cache);
7735b0959a7SKevin Wolf     }
7745b0959a7SKevin Wolf     if (s->refcount_block_cache) {
7755b0959a7SKevin Wolf         qcow2_cache_destroy(bs, s->refcount_block_cache);
7765b0959a7SKevin Wolf     }
777ee55b173SKevin Wolf     s->l2_table_cache = r->l2_table_cache;
778ee55b173SKevin Wolf     s->refcount_block_cache = r->refcount_block_cache;
779ee55b173SKevin Wolf 
780ee55b173SKevin Wolf     s->overlap_check = r->overlap_check;
781ee55b173SKevin Wolf     s->use_lazy_refcounts = r->use_lazy_refcounts;
782ee55b173SKevin Wolf 
783ee55b173SKevin Wolf     for (i = 0; i < QCOW2_DISCARD_MAX; i++) {
784ee55b173SKevin Wolf         s->discard_passthrough[i] = r->discard_passthrough[i];
785ee55b173SKevin Wolf     }
786ee55b173SKevin Wolf 
7875b0959a7SKevin Wolf     if (s->cache_clean_interval != r->cache_clean_interval) {
7885b0959a7SKevin Wolf         cache_clean_timer_del(bs);
789ee55b173SKevin Wolf         s->cache_clean_interval = r->cache_clean_interval;
790ee55b173SKevin Wolf         cache_clean_timer_init(bs, bdrv_get_aio_context(bs));
791ee55b173SKevin Wolf     }
7925b0959a7SKevin Wolf }
793ee55b173SKevin Wolf 
794ee55b173SKevin Wolf static void qcow2_update_options_abort(BlockDriverState *bs,
795ee55b173SKevin Wolf                                        Qcow2ReopenState *r)
796ee55b173SKevin Wolf {
797ee55b173SKevin Wolf     if (r->l2_table_cache) {
798ee55b173SKevin Wolf         qcow2_cache_destroy(bs, r->l2_table_cache);
799ee55b173SKevin Wolf     }
800ee55b173SKevin Wolf     if (r->refcount_block_cache) {
801ee55b173SKevin Wolf         qcow2_cache_destroy(bs, r->refcount_block_cache);
802ee55b173SKevin Wolf     }
803ee55b173SKevin Wolf }
804ee55b173SKevin Wolf 
805ee55b173SKevin Wolf static int qcow2_update_options(BlockDriverState *bs, QDict *options,
806ee55b173SKevin Wolf                                 int flags, Error **errp)
807ee55b173SKevin Wolf {
808ee55b173SKevin Wolf     Qcow2ReopenState r = {};
809ee55b173SKevin Wolf     int ret;
810ee55b173SKevin Wolf 
811ee55b173SKevin Wolf     ret = qcow2_update_options_prepare(bs, &r, options, flags, errp);
812ee55b173SKevin Wolf     if (ret >= 0) {
813ee55b173SKevin Wolf         qcow2_update_options_commit(bs, &r);
814ee55b173SKevin Wolf     } else {
815ee55b173SKevin Wolf         qcow2_update_options_abort(bs, &r);
816ee55b173SKevin Wolf     }
81794edf3fbSKevin Wolf 
8184c75d1a1SKevin Wolf     return ret;
8194c75d1a1SKevin Wolf }
8204c75d1a1SKevin Wolf 
821015a1036SMax Reitz static int qcow2_open(BlockDriverState *bs, QDict *options, int flags,
822015a1036SMax Reitz                       Error **errp)
823585f8587Sbellard {
824ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
8256d33e8e7SKevin Wolf     unsigned int len, i;
8266d33e8e7SKevin Wolf     int ret = 0;
827585f8587Sbellard     QCowHeader header;
82874c4510aSKevin Wolf     Error *local_err = NULL;
8299b80ddf3Saliguori     uint64_t ext_end;
8302cf7cfa1SKevin Wolf     uint64_t l1_vm_state_index;
831585f8587Sbellard 
8329a4f4c31SKevin Wolf     ret = bdrv_pread(bs->file->bs, 0, &header, sizeof(header));
8336d85a57eSJes Sorensen     if (ret < 0) {
8343ef6c40aSMax Reitz         error_setg_errno(errp, -ret, "Could not read qcow2 header");
835585f8587Sbellard         goto fail;
8366d85a57eSJes Sorensen     }
837585f8587Sbellard     be32_to_cpus(&header.magic);
838585f8587Sbellard     be32_to_cpus(&header.version);
839585f8587Sbellard     be64_to_cpus(&header.backing_file_offset);
840585f8587Sbellard     be32_to_cpus(&header.backing_file_size);
841585f8587Sbellard     be64_to_cpus(&header.size);
842585f8587Sbellard     be32_to_cpus(&header.cluster_bits);
843585f8587Sbellard     be32_to_cpus(&header.crypt_method);
844585f8587Sbellard     be64_to_cpus(&header.l1_table_offset);
845585f8587Sbellard     be32_to_cpus(&header.l1_size);
846585f8587Sbellard     be64_to_cpus(&header.refcount_table_offset);
847585f8587Sbellard     be32_to_cpus(&header.refcount_table_clusters);
848585f8587Sbellard     be64_to_cpus(&header.snapshots_offset);
849585f8587Sbellard     be32_to_cpus(&header.nb_snapshots);
850585f8587Sbellard 
851e8cdcec1SKevin Wolf     if (header.magic != QCOW_MAGIC) {
8523ef6c40aSMax Reitz         error_setg(errp, "Image is not in qcow2 format");
85376abe407SPaolo Bonzini         ret = -EINVAL;
854585f8587Sbellard         goto fail;
8556d85a57eSJes Sorensen     }
8566744cbabSKevin Wolf     if (header.version < 2 || header.version > 3) {
857521b2b5dSMax Reitz         report_unsupported(bs, errp, "QCOW version %" PRIu32, header.version);
858e8cdcec1SKevin Wolf         ret = -ENOTSUP;
859e8cdcec1SKevin Wolf         goto fail;
860e8cdcec1SKevin Wolf     }
8616744cbabSKevin Wolf 
8626744cbabSKevin Wolf     s->qcow_version = header.version;
8636744cbabSKevin Wolf 
86424342f2cSKevin Wolf     /* Initialise cluster size */
86524342f2cSKevin Wolf     if (header.cluster_bits < MIN_CLUSTER_BITS ||
86624342f2cSKevin Wolf         header.cluster_bits > MAX_CLUSTER_BITS) {
867521b2b5dSMax Reitz         error_setg(errp, "Unsupported cluster size: 2^%" PRIu32,
868521b2b5dSMax Reitz                    header.cluster_bits);
86924342f2cSKevin Wolf         ret = -EINVAL;
87024342f2cSKevin Wolf         goto fail;
87124342f2cSKevin Wolf     }
87224342f2cSKevin Wolf 
87324342f2cSKevin Wolf     s->cluster_bits = header.cluster_bits;
87424342f2cSKevin Wolf     s->cluster_size = 1 << s->cluster_bits;
87524342f2cSKevin Wolf     s->cluster_sectors = 1 << (s->cluster_bits - 9);
87624342f2cSKevin Wolf 
8776744cbabSKevin Wolf     /* Initialise version 3 header fields */
8786744cbabSKevin Wolf     if (header.version == 2) {
8796744cbabSKevin Wolf         header.incompatible_features    = 0;
8806744cbabSKevin Wolf         header.compatible_features      = 0;
8816744cbabSKevin Wolf         header.autoclear_features       = 0;
8826744cbabSKevin Wolf         header.refcount_order           = 4;
8836744cbabSKevin Wolf         header.header_length            = 72;
8846744cbabSKevin Wolf     } else {
8856744cbabSKevin Wolf         be64_to_cpus(&header.incompatible_features);
8866744cbabSKevin Wolf         be64_to_cpus(&header.compatible_features);
8876744cbabSKevin Wolf         be64_to_cpus(&header.autoclear_features);
8886744cbabSKevin Wolf         be32_to_cpus(&header.refcount_order);
8896744cbabSKevin Wolf         be32_to_cpus(&header.header_length);
89024342f2cSKevin Wolf 
89124342f2cSKevin Wolf         if (header.header_length < 104) {
89224342f2cSKevin Wolf             error_setg(errp, "qcow2 header too short");
89324342f2cSKevin Wolf             ret = -EINVAL;
89424342f2cSKevin Wolf             goto fail;
89524342f2cSKevin Wolf         }
89624342f2cSKevin Wolf     }
89724342f2cSKevin Wolf 
89824342f2cSKevin Wolf     if (header.header_length > s->cluster_size) {
89924342f2cSKevin Wolf         error_setg(errp, "qcow2 header exceeds cluster size");
90024342f2cSKevin Wolf         ret = -EINVAL;
90124342f2cSKevin Wolf         goto fail;
9026744cbabSKevin Wolf     }
9036744cbabSKevin Wolf 
9046744cbabSKevin Wolf     if (header.header_length > sizeof(header)) {
9056744cbabSKevin Wolf         s->unknown_header_fields_size = header.header_length - sizeof(header);
9066744cbabSKevin Wolf         s->unknown_header_fields = g_malloc(s->unknown_header_fields_size);
9079a4f4c31SKevin Wolf         ret = bdrv_pread(bs->file->bs, sizeof(header), s->unknown_header_fields,
9086744cbabSKevin Wolf                          s->unknown_header_fields_size);
9096744cbabSKevin Wolf         if (ret < 0) {
9103ef6c40aSMax Reitz             error_setg_errno(errp, -ret, "Could not read unknown qcow2 header "
9113ef6c40aSMax Reitz                              "fields");
9126744cbabSKevin Wolf             goto fail;
9136744cbabSKevin Wolf         }
9146744cbabSKevin Wolf     }
9156744cbabSKevin Wolf 
916a1b3955cSKevin Wolf     if (header.backing_file_offset > s->cluster_size) {
917a1b3955cSKevin Wolf         error_setg(errp, "Invalid backing file offset");
918a1b3955cSKevin Wolf         ret = -EINVAL;
919a1b3955cSKevin Wolf         goto fail;
920a1b3955cSKevin Wolf     }
921a1b3955cSKevin Wolf 
922cfcc4c62SKevin Wolf     if (header.backing_file_offset) {
923cfcc4c62SKevin Wolf         ext_end = header.backing_file_offset;
924cfcc4c62SKevin Wolf     } else {
925cfcc4c62SKevin Wolf         ext_end = 1 << header.cluster_bits;
926cfcc4c62SKevin Wolf     }
927cfcc4c62SKevin Wolf 
9286744cbabSKevin Wolf     /* Handle feature bits */
9296744cbabSKevin Wolf     s->incompatible_features    = header.incompatible_features;
9306744cbabSKevin Wolf     s->compatible_features      = header.compatible_features;
9316744cbabSKevin Wolf     s->autoclear_features       = header.autoclear_features;
9326744cbabSKevin Wolf 
933c61d0004SStefan Hajnoczi     if (s->incompatible_features & ~QCOW2_INCOMPAT_MASK) {
934cfcc4c62SKevin Wolf         void *feature_table = NULL;
935cfcc4c62SKevin Wolf         qcow2_read_extensions(bs, header.header_length, ext_end,
9363ef6c40aSMax Reitz                               &feature_table, NULL);
9373ef6c40aSMax Reitz         report_unsupported_feature(bs, errp, feature_table,
938c61d0004SStefan Hajnoczi                                    s->incompatible_features &
939c61d0004SStefan Hajnoczi                                    ~QCOW2_INCOMPAT_MASK);
9406744cbabSKevin Wolf         ret = -ENOTSUP;
941c5a33ee9SPrasad Joshi         g_free(feature_table);
9426744cbabSKevin Wolf         goto fail;
9436744cbabSKevin Wolf     }
9446744cbabSKevin Wolf 
94569c98726SMax Reitz     if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
94669c98726SMax Reitz         /* Corrupt images may not be written to unless they are being repaired
94769c98726SMax Reitz          */
94869c98726SMax Reitz         if ((flags & BDRV_O_RDWR) && !(flags & BDRV_O_CHECK)) {
9493ef6c40aSMax Reitz             error_setg(errp, "qcow2: Image is corrupt; cannot be opened "
9503ef6c40aSMax Reitz                        "read/write");
95169c98726SMax Reitz             ret = -EACCES;
95269c98726SMax Reitz             goto fail;
95369c98726SMax Reitz         }
95469c98726SMax Reitz     }
95569c98726SMax Reitz 
9566744cbabSKevin Wolf     /* Check support for various header values */
957b72faf9fSMax Reitz     if (header.refcount_order > 6) {
958b72faf9fSMax Reitz         error_setg(errp, "Reference count entry width too large; may not "
959b72faf9fSMax Reitz                    "exceed 64 bits");
960b72faf9fSMax Reitz         ret = -EINVAL;
9616744cbabSKevin Wolf         goto fail;
9626744cbabSKevin Wolf     }
963b6481f37SMax Reitz     s->refcount_order = header.refcount_order;
964346a53dfSMax Reitz     s->refcount_bits = 1 << s->refcount_order;
965346a53dfSMax Reitz     s->refcount_max = UINT64_C(1) << (s->refcount_bits - 1);
966346a53dfSMax Reitz     s->refcount_max += s->refcount_max - 1;
9676744cbabSKevin Wolf 
9686d85a57eSJes Sorensen     if (header.crypt_method > QCOW_CRYPT_AES) {
969521b2b5dSMax Reitz         error_setg(errp, "Unsupported encryption method: %" PRIu32,
9703ef6c40aSMax Reitz                    header.crypt_method);
9716d85a57eSJes Sorensen         ret = -EINVAL;
972585f8587Sbellard         goto fail;
9736d85a57eSJes Sorensen     }
974f6fa64f6SDaniel P. Berrange     if (!qcrypto_cipher_supports(QCRYPTO_CIPHER_ALG_AES_128)) {
975f6fa64f6SDaniel P. Berrange         error_setg(errp, "AES cipher not available");
976f6fa64f6SDaniel P. Berrange         ret = -EINVAL;
977f6fa64f6SDaniel P. Berrange         goto fail;
978f6fa64f6SDaniel P. Berrange     }
979585f8587Sbellard     s->crypt_method_header = header.crypt_method;
9806d85a57eSJes Sorensen     if (s->crypt_method_header) {
981585f8587Sbellard         bs->encrypted = 1;
9826d85a57eSJes Sorensen     }
98324342f2cSKevin Wolf 
984585f8587Sbellard     s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */
985585f8587Sbellard     s->l2_size = 1 << s->l2_bits;
9861d13d654SMax Reitz     /* 2^(s->refcount_order - 3) is the refcount width in bytes */
9871d13d654SMax Reitz     s->refcount_block_bits = s->cluster_bits - (s->refcount_order - 3);
9881d13d654SMax Reitz     s->refcount_block_size = 1 << s->refcount_block_bits;
989585f8587Sbellard     bs->total_sectors = header.size / 512;
990585f8587Sbellard     s->csize_shift = (62 - (s->cluster_bits - 8));
991585f8587Sbellard     s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;
992585f8587Sbellard     s->cluster_offset_mask = (1LL << s->csize_shift) - 1;
9935dab2fadSKevin Wolf 
994585f8587Sbellard     s->refcount_table_offset = header.refcount_table_offset;
995585f8587Sbellard     s->refcount_table_size =
996585f8587Sbellard         header.refcount_table_clusters << (s->cluster_bits - 3);
997585f8587Sbellard 
9982b5d5953SKevin Wolf     if (header.refcount_table_clusters > qcow2_max_refcount_clusters(s)) {
9995dab2fadSKevin Wolf         error_setg(errp, "Reference count table too large");
10005dab2fadSKevin Wolf         ret = -EINVAL;
10015dab2fadSKevin Wolf         goto fail;
10025dab2fadSKevin Wolf     }
10035dab2fadSKevin Wolf 
10048c7de283SKevin Wolf     ret = validate_table_offset(bs, s->refcount_table_offset,
10058c7de283SKevin Wolf                                 s->refcount_table_size, sizeof(uint64_t));
10068c7de283SKevin Wolf     if (ret < 0) {
10078c7de283SKevin Wolf         error_setg(errp, "Invalid reference count table offset");
10088c7de283SKevin Wolf         goto fail;
10098c7de283SKevin Wolf     }
10108c7de283SKevin Wolf 
1011ce48f2f4SKevin Wolf     /* Snapshot table offset/length */
1012ce48f2f4SKevin Wolf     if (header.nb_snapshots > QCOW_MAX_SNAPSHOTS) {
1013ce48f2f4SKevin Wolf         error_setg(errp, "Too many snapshots");
1014ce48f2f4SKevin Wolf         ret = -EINVAL;
1015ce48f2f4SKevin Wolf         goto fail;
1016ce48f2f4SKevin Wolf     }
1017ce48f2f4SKevin Wolf 
1018ce48f2f4SKevin Wolf     ret = validate_table_offset(bs, header.snapshots_offset,
1019ce48f2f4SKevin Wolf                                 header.nb_snapshots,
1020ce48f2f4SKevin Wolf                                 sizeof(QCowSnapshotHeader));
1021ce48f2f4SKevin Wolf     if (ret < 0) {
1022ce48f2f4SKevin Wolf         error_setg(errp, "Invalid snapshot table offset");
1023ce48f2f4SKevin Wolf         goto fail;
1024ce48f2f4SKevin Wolf     }
1025ce48f2f4SKevin Wolf 
1026585f8587Sbellard     /* read the level 1 table */
102787b86e7eSWen Congyang     if (header.l1_size > QCOW_MAX_L1_SIZE / sizeof(uint64_t)) {
10282d51c32cSKevin Wolf         error_setg(errp, "Active L1 table too large");
10292d51c32cSKevin Wolf         ret = -EFBIG;
10302d51c32cSKevin Wolf         goto fail;
10312d51c32cSKevin Wolf     }
1032585f8587Sbellard     s->l1_size = header.l1_size;
10332cf7cfa1SKevin Wolf 
10342cf7cfa1SKevin Wolf     l1_vm_state_index = size_to_l1(s, header.size);
10352cf7cfa1SKevin Wolf     if (l1_vm_state_index > INT_MAX) {
10363ef6c40aSMax Reitz         error_setg(errp, "Image is too big");
10372cf7cfa1SKevin Wolf         ret = -EFBIG;
10382cf7cfa1SKevin Wolf         goto fail;
10392cf7cfa1SKevin Wolf     }
10402cf7cfa1SKevin Wolf     s->l1_vm_state_index = l1_vm_state_index;
10412cf7cfa1SKevin Wolf 
1042585f8587Sbellard     /* the L1 table must contain at least enough entries to put
1043585f8587Sbellard        header.size bytes */
10446d85a57eSJes Sorensen     if (s->l1_size < s->l1_vm_state_index) {
10453ef6c40aSMax Reitz         error_setg(errp, "L1 table is too small");
10466d85a57eSJes Sorensen         ret = -EINVAL;
1047585f8587Sbellard         goto fail;
10486d85a57eSJes Sorensen     }
10492d51c32cSKevin Wolf 
10502d51c32cSKevin Wolf     ret = validate_table_offset(bs, header.l1_table_offset,
10512d51c32cSKevin Wolf                                 header.l1_size, sizeof(uint64_t));
10522d51c32cSKevin Wolf     if (ret < 0) {
10532d51c32cSKevin Wolf         error_setg(errp, "Invalid L1 table offset");
10542d51c32cSKevin Wolf         goto fail;
10552d51c32cSKevin Wolf     }
1056585f8587Sbellard     s->l1_table_offset = header.l1_table_offset;
10572d51c32cSKevin Wolf 
10582d51c32cSKevin Wolf 
1059d191d12dSStefan Weil     if (s->l1_size > 0) {
10609a4f4c31SKevin Wolf         s->l1_table = qemu_try_blockalign(bs->file->bs,
10613f6a3ee5SKevin Wolf             align_offset(s->l1_size * sizeof(uint64_t), 512));
1062de82815dSKevin Wolf         if (s->l1_table == NULL) {
1063de82815dSKevin Wolf             error_setg(errp, "Could not allocate L1 table");
1064de82815dSKevin Wolf             ret = -ENOMEM;
1065de82815dSKevin Wolf             goto fail;
1066de82815dSKevin Wolf         }
10679a4f4c31SKevin Wolf         ret = bdrv_pread(bs->file->bs, s->l1_table_offset, s->l1_table,
10686d85a57eSJes Sorensen                          s->l1_size * sizeof(uint64_t));
10696d85a57eSJes Sorensen         if (ret < 0) {
10703ef6c40aSMax Reitz             error_setg_errno(errp, -ret, "Could not read L1 table");
1071585f8587Sbellard             goto fail;
10726d85a57eSJes Sorensen         }
1073585f8587Sbellard         for(i = 0;i < s->l1_size; i++) {
1074585f8587Sbellard             be64_to_cpus(&s->l1_table[i]);
1075585f8587Sbellard         }
1076d191d12dSStefan Weil     }
107729c1a730SKevin Wolf 
107894edf3fbSKevin Wolf     /* Parse driver-specific options */
107994edf3fbSKevin Wolf     ret = qcow2_update_options(bs, options, flags, errp);
108090efa0eaSKevin Wolf     if (ret < 0) {
108190efa0eaSKevin Wolf         goto fail;
108290efa0eaSKevin Wolf     }
108390efa0eaSKevin Wolf 
10847267c094SAnthony Liguori     s->cluster_cache = g_malloc(s->cluster_size);
1085585f8587Sbellard     /* one more sector for decompressed data alignment */
10869a4f4c31SKevin Wolf     s->cluster_data = qemu_try_blockalign(bs->file->bs, QCOW_MAX_CRYPT_CLUSTERS
1087de82815dSKevin Wolf                                                     * s->cluster_size + 512);
1088de82815dSKevin Wolf     if (s->cluster_data == NULL) {
1089de82815dSKevin Wolf         error_setg(errp, "Could not allocate temporary cluster buffer");
1090de82815dSKevin Wolf         ret = -ENOMEM;
1091de82815dSKevin Wolf         goto fail;
1092de82815dSKevin Wolf     }
1093de82815dSKevin Wolf 
1094585f8587Sbellard     s->cluster_cache_offset = -1;
109506d9260fSAnthony Liguori     s->flags = flags;
1096585f8587Sbellard 
10976d85a57eSJes Sorensen     ret = qcow2_refcount_init(bs);
10986d85a57eSJes Sorensen     if (ret != 0) {
10993ef6c40aSMax Reitz         error_setg_errno(errp, -ret, "Could not initialize refcount handling");
1100585f8587Sbellard         goto fail;
11016d85a57eSJes Sorensen     }
1102585f8587Sbellard 
110372cf2d4fSBlue Swirl     QLIST_INIT(&s->cluster_allocs);
11040b919faeSKevin Wolf     QTAILQ_INIT(&s->discards);
1105f214978aSKevin Wolf 
11069b80ddf3Saliguori     /* read qcow2 extensions */
11073ef6c40aSMax Reitz     if (qcow2_read_extensions(bs, header.header_length, ext_end, NULL,
11083ef6c40aSMax Reitz         &local_err)) {
11093ef6c40aSMax Reitz         error_propagate(errp, local_err);
11106d85a57eSJes Sorensen         ret = -EINVAL;
11119b80ddf3Saliguori         goto fail;
11126d85a57eSJes Sorensen     }
11139b80ddf3Saliguori 
1114585f8587Sbellard     /* read the backing file name */
1115585f8587Sbellard     if (header.backing_file_offset != 0) {
1116585f8587Sbellard         len = header.backing_file_size;
11179a29e18fSJeff Cody         if (len > MIN(1023, s->cluster_size - header.backing_file_offset) ||
1118e729fa6aSJeff Cody             len >= sizeof(bs->backing_file)) {
11196d33e8e7SKevin Wolf             error_setg(errp, "Backing file name too long");
11206d33e8e7SKevin Wolf             ret = -EINVAL;
11216d33e8e7SKevin Wolf             goto fail;
11226d85a57eSJes Sorensen         }
11239a4f4c31SKevin Wolf         ret = bdrv_pread(bs->file->bs, header.backing_file_offset,
11246d85a57eSJes Sorensen                          bs->backing_file, len);
11256d85a57eSJes Sorensen         if (ret < 0) {
11263ef6c40aSMax Reitz             error_setg_errno(errp, -ret, "Could not read backing file name");
1127585f8587Sbellard             goto fail;
11286d85a57eSJes Sorensen         }
1129585f8587Sbellard         bs->backing_file[len] = '\0';
1130e4603fe1SKevin Wolf         s->image_backing_file = g_strdup(bs->backing_file);
1131585f8587Sbellard     }
113242deb29fSKevin Wolf 
113311b128f4SKevin Wolf     /* Internal snapshots */
113411b128f4SKevin Wolf     s->snapshots_offset = header.snapshots_offset;
113511b128f4SKevin Wolf     s->nb_snapshots = header.nb_snapshots;
113611b128f4SKevin Wolf 
113742deb29fSKevin Wolf     ret = qcow2_read_snapshots(bs);
113842deb29fSKevin Wolf     if (ret < 0) {
11393ef6c40aSMax Reitz         error_setg_errno(errp, -ret, "Could not read snapshots");
1140585f8587Sbellard         goto fail;
11416d85a57eSJes Sorensen     }
1142585f8587Sbellard 
1143af7b708dSStefan Hajnoczi     /* Clear unknown autoclear feature bits */
114404c01a5cSKevin Wolf     if (!bs->read_only && !(flags & BDRV_O_INACTIVE) && s->autoclear_features) {
1145af7b708dSStefan Hajnoczi         s->autoclear_features = 0;
1146af7b708dSStefan Hajnoczi         ret = qcow2_update_header(bs);
1147af7b708dSStefan Hajnoczi         if (ret < 0) {
11483ef6c40aSMax Reitz             error_setg_errno(errp, -ret, "Could not update qcow2 header");
1149af7b708dSStefan Hajnoczi             goto fail;
1150af7b708dSStefan Hajnoczi         }
1151af7b708dSStefan Hajnoczi     }
1152af7b708dSStefan Hajnoczi 
115368d100e9SKevin Wolf     /* Initialise locks */
115468d100e9SKevin Wolf     qemu_co_mutex_init(&s->lock);
115568d100e9SKevin Wolf 
1156c61d0004SStefan Hajnoczi     /* Repair image if dirty */
115704c01a5cSKevin Wolf     if (!(flags & (BDRV_O_CHECK | BDRV_O_INACTIVE)) && !bs->read_only &&
1158058f8f16SStefan Hajnoczi         (s->incompatible_features & QCOW2_INCOMPAT_DIRTY)) {
1159c61d0004SStefan Hajnoczi         BdrvCheckResult result = {0};
1160c61d0004SStefan Hajnoczi 
11615b84106bSMax Reitz         ret = qcow2_check(bs, &result, BDRV_FIX_ERRORS | BDRV_FIX_LEAKS);
1162c61d0004SStefan Hajnoczi         if (ret < 0) {
11633ef6c40aSMax Reitz             error_setg_errno(errp, -ret, "Could not repair dirty image");
1164c61d0004SStefan Hajnoczi             goto fail;
1165c61d0004SStefan Hajnoczi         }
1166c61d0004SStefan Hajnoczi     }
1167c61d0004SStefan Hajnoczi 
1168585f8587Sbellard #ifdef DEBUG_ALLOC
11696cbc3031SPhilipp Hahn     {
11706cbc3031SPhilipp Hahn         BdrvCheckResult result = {0};
1171b35278f7SStefan Hajnoczi         qcow2_check_refcounts(bs, &result, 0);
11726cbc3031SPhilipp Hahn     }
1173585f8587Sbellard #endif
11746d85a57eSJes Sorensen     return ret;
1175585f8587Sbellard 
1176585f8587Sbellard  fail:
11776744cbabSKevin Wolf     g_free(s->unknown_header_fields);
117875bab85cSKevin Wolf     cleanup_unknown_header_ext(bs);
1179ed6ccf0fSKevin Wolf     qcow2_free_snapshots(bs);
1180ed6ccf0fSKevin Wolf     qcow2_refcount_close(bs);
1181de82815dSKevin Wolf     qemu_vfree(s->l1_table);
1182cf93980eSMax Reitz     /* else pre-write overlap checks in cache_destroy may crash */
1183cf93980eSMax Reitz     s->l1_table = NULL;
1184279621c0SAlberto Garcia     cache_clean_timer_del(bs);
118529c1a730SKevin Wolf     if (s->l2_table_cache) {
118629c1a730SKevin Wolf         qcow2_cache_destroy(bs, s->l2_table_cache);
118729c1a730SKevin Wolf     }
1188c5a33ee9SPrasad Joshi     if (s->refcount_block_cache) {
1189c5a33ee9SPrasad Joshi         qcow2_cache_destroy(bs, s->refcount_block_cache);
1190c5a33ee9SPrasad Joshi     }
11917267c094SAnthony Liguori     g_free(s->cluster_cache);
1192dea43a65SFrediano Ziglio     qemu_vfree(s->cluster_data);
11936d85a57eSJes Sorensen     return ret;
1194585f8587Sbellard }
1195585f8587Sbellard 
11963baca891SKevin Wolf static void qcow2_refresh_limits(BlockDriverState *bs, Error **errp)
1197d34682cdSKevin Wolf {
1198ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
1199d34682cdSKevin Wolf 
1200d34682cdSKevin Wolf     bs->bl.write_zeroes_alignment = s->cluster_sectors;
1201d34682cdSKevin Wolf }
1202d34682cdSKevin Wolf 
12037c80ab3fSJes Sorensen static int qcow2_set_key(BlockDriverState *bs, const char *key)
1204585f8587Sbellard {
1205ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
1206585f8587Sbellard     uint8_t keybuf[16];
1207585f8587Sbellard     int len, i;
1208f6fa64f6SDaniel P. Berrange     Error *err = NULL;
1209585f8587Sbellard 
1210585f8587Sbellard     memset(keybuf, 0, 16);
1211585f8587Sbellard     len = strlen(key);
1212585f8587Sbellard     if (len > 16)
1213585f8587Sbellard         len = 16;
1214585f8587Sbellard     /* XXX: we could compress the chars to 7 bits to increase
1215585f8587Sbellard        entropy */
1216585f8587Sbellard     for(i = 0;i < len;i++) {
1217585f8587Sbellard         keybuf[i] = key[i];
1218585f8587Sbellard     }
12198336aafaSDaniel P. Berrange     assert(bs->encrypted);
1220585f8587Sbellard 
1221f6fa64f6SDaniel P. Berrange     qcrypto_cipher_free(s->cipher);
1222f6fa64f6SDaniel P. Berrange     s->cipher = qcrypto_cipher_new(
1223f6fa64f6SDaniel P. Berrange         QCRYPTO_CIPHER_ALG_AES_128,
1224f6fa64f6SDaniel P. Berrange         QCRYPTO_CIPHER_MODE_CBC,
1225f6fa64f6SDaniel P. Berrange         keybuf, G_N_ELEMENTS(keybuf),
1226f6fa64f6SDaniel P. Berrange         &err);
1227f6fa64f6SDaniel P. Berrange 
1228f6fa64f6SDaniel P. Berrange     if (!s->cipher) {
1229f6fa64f6SDaniel P. Berrange         /* XXX would be nice if errors in this method could
1230f6fa64f6SDaniel P. Berrange          * be properly propagate to the caller. Would need
1231f6fa64f6SDaniel P. Berrange          * the bdrv_set_key() API signature to be fixed. */
1232f6fa64f6SDaniel P. Berrange         error_free(err);
1233585f8587Sbellard         return -1;
1234585f8587Sbellard     }
1235585f8587Sbellard     return 0;
1236585f8587Sbellard }
1237585f8587Sbellard 
123821d82ac9SJeff Cody static int qcow2_reopen_prepare(BDRVReopenState *state,
123921d82ac9SJeff Cody                                 BlockReopenQueue *queue, Error **errp)
124021d82ac9SJeff Cody {
12415b0959a7SKevin Wolf     Qcow2ReopenState *r;
12424c2e5f8fSKevin Wolf     int ret;
12434c2e5f8fSKevin Wolf 
12445b0959a7SKevin Wolf     r = g_new0(Qcow2ReopenState, 1);
12455b0959a7SKevin Wolf     state->opaque = r;
12465b0959a7SKevin Wolf 
12475b0959a7SKevin Wolf     ret = qcow2_update_options_prepare(state->bs, r, state->options,
12485b0959a7SKevin Wolf                                        state->flags, errp);
12495b0959a7SKevin Wolf     if (ret < 0) {
12505b0959a7SKevin Wolf         goto fail;
12515b0959a7SKevin Wolf     }
12525b0959a7SKevin Wolf 
12535b0959a7SKevin Wolf     /* We need to write out any unwritten data if we reopen read-only. */
12544c2e5f8fSKevin Wolf     if ((state->flags & BDRV_O_RDWR) == 0) {
12554c2e5f8fSKevin Wolf         ret = bdrv_flush(state->bs);
12564c2e5f8fSKevin Wolf         if (ret < 0) {
12575b0959a7SKevin Wolf             goto fail;
12584c2e5f8fSKevin Wolf         }
12594c2e5f8fSKevin Wolf 
12604c2e5f8fSKevin Wolf         ret = qcow2_mark_clean(state->bs);
12614c2e5f8fSKevin Wolf         if (ret < 0) {
12625b0959a7SKevin Wolf             goto fail;
12634c2e5f8fSKevin Wolf         }
12644c2e5f8fSKevin Wolf     }
12654c2e5f8fSKevin Wolf 
126621d82ac9SJeff Cody     return 0;
12675b0959a7SKevin Wolf 
12685b0959a7SKevin Wolf fail:
12695b0959a7SKevin Wolf     qcow2_update_options_abort(state->bs, r);
12705b0959a7SKevin Wolf     g_free(r);
12715b0959a7SKevin Wolf     return ret;
12725b0959a7SKevin Wolf }
12735b0959a7SKevin Wolf 
12745b0959a7SKevin Wolf static void qcow2_reopen_commit(BDRVReopenState *state)
12755b0959a7SKevin Wolf {
12765b0959a7SKevin Wolf     qcow2_update_options_commit(state->bs, state->opaque);
12775b0959a7SKevin Wolf     g_free(state->opaque);
12785b0959a7SKevin Wolf }
12795b0959a7SKevin Wolf 
12805b0959a7SKevin Wolf static void qcow2_reopen_abort(BDRVReopenState *state)
12815b0959a7SKevin Wolf {
12825b0959a7SKevin Wolf     qcow2_update_options_abort(state->bs, state->opaque);
12835b0959a7SKevin Wolf     g_free(state->opaque);
128421d82ac9SJeff Cody }
128521d82ac9SJeff Cody 
12865365f44dSKevin Wolf static void qcow2_join_options(QDict *options, QDict *old_options)
12875365f44dSKevin Wolf {
12885365f44dSKevin Wolf     bool has_new_overlap_template =
12895365f44dSKevin Wolf         qdict_haskey(options, QCOW2_OPT_OVERLAP) ||
12905365f44dSKevin Wolf         qdict_haskey(options, QCOW2_OPT_OVERLAP_TEMPLATE);
12915365f44dSKevin Wolf     bool has_new_total_cache_size =
12925365f44dSKevin Wolf         qdict_haskey(options, QCOW2_OPT_CACHE_SIZE);
12935365f44dSKevin Wolf     bool has_all_cache_options;
12945365f44dSKevin Wolf 
12955365f44dSKevin Wolf     /* New overlap template overrides all old overlap options */
12965365f44dSKevin Wolf     if (has_new_overlap_template) {
12975365f44dSKevin Wolf         qdict_del(old_options, QCOW2_OPT_OVERLAP);
12985365f44dSKevin Wolf         qdict_del(old_options, QCOW2_OPT_OVERLAP_TEMPLATE);
12995365f44dSKevin Wolf         qdict_del(old_options, QCOW2_OPT_OVERLAP_MAIN_HEADER);
13005365f44dSKevin Wolf         qdict_del(old_options, QCOW2_OPT_OVERLAP_ACTIVE_L1);
13015365f44dSKevin Wolf         qdict_del(old_options, QCOW2_OPT_OVERLAP_ACTIVE_L2);
13025365f44dSKevin Wolf         qdict_del(old_options, QCOW2_OPT_OVERLAP_REFCOUNT_TABLE);
13035365f44dSKevin Wolf         qdict_del(old_options, QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK);
13045365f44dSKevin Wolf         qdict_del(old_options, QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE);
13055365f44dSKevin Wolf         qdict_del(old_options, QCOW2_OPT_OVERLAP_INACTIVE_L1);
13065365f44dSKevin Wolf         qdict_del(old_options, QCOW2_OPT_OVERLAP_INACTIVE_L2);
13075365f44dSKevin Wolf     }
13085365f44dSKevin Wolf 
13095365f44dSKevin Wolf     /* New total cache size overrides all old options */
13105365f44dSKevin Wolf     if (qdict_haskey(options, QCOW2_OPT_CACHE_SIZE)) {
13115365f44dSKevin Wolf         qdict_del(old_options, QCOW2_OPT_L2_CACHE_SIZE);
13125365f44dSKevin Wolf         qdict_del(old_options, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
13135365f44dSKevin Wolf     }
13145365f44dSKevin Wolf 
13155365f44dSKevin Wolf     qdict_join(options, old_options, false);
13165365f44dSKevin Wolf 
13175365f44dSKevin Wolf     /*
13185365f44dSKevin Wolf      * If after merging all cache size options are set, an old total size is
13195365f44dSKevin Wolf      * overwritten. Do keep all options, however, if all three are new. The
13205365f44dSKevin Wolf      * resulting error message is what we want to happen.
13215365f44dSKevin Wolf      */
13225365f44dSKevin Wolf     has_all_cache_options =
13235365f44dSKevin Wolf         qdict_haskey(options, QCOW2_OPT_CACHE_SIZE) ||
13245365f44dSKevin Wolf         qdict_haskey(options, QCOW2_OPT_L2_CACHE_SIZE) ||
13255365f44dSKevin Wolf         qdict_haskey(options, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
13265365f44dSKevin Wolf 
13275365f44dSKevin Wolf     if (has_all_cache_options && !has_new_total_cache_size) {
13285365f44dSKevin Wolf         qdict_del(options, QCOW2_OPT_CACHE_SIZE);
13295365f44dSKevin Wolf     }
13305365f44dSKevin Wolf }
13315365f44dSKevin Wolf 
1332b6b8a333SPaolo Bonzini static int64_t coroutine_fn qcow2_co_get_block_status(BlockDriverState *bs,
1333f8a2e5e3SStefan Hajnoczi         int64_t sector_num, int nb_sectors, int *pnum)
1334585f8587Sbellard {
1335ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
1336585f8587Sbellard     uint64_t cluster_offset;
13374bc74be9SPaolo Bonzini     int index_in_cluster, ret;
13384bc74be9SPaolo Bonzini     int64_t status = 0;
1339585f8587Sbellard 
1340095a9c58Saliguori     *pnum = nb_sectors;
1341f8a2e5e3SStefan Hajnoczi     qemu_co_mutex_lock(&s->lock);
13421c46efaaSKevin Wolf     ret = qcow2_get_cluster_offset(bs, sector_num << 9, pnum, &cluster_offset);
1343f8a2e5e3SStefan Hajnoczi     qemu_co_mutex_unlock(&s->lock);
13441c46efaaSKevin Wolf     if (ret < 0) {
1345d663640cSPaolo Bonzini         return ret;
13461c46efaaSKevin Wolf     }
1347095a9c58Saliguori 
13484bc74be9SPaolo Bonzini     if (cluster_offset != 0 && ret != QCOW2_CLUSTER_COMPRESSED &&
1349f6fa64f6SDaniel P. Berrange         !s->cipher) {
13504bc74be9SPaolo Bonzini         index_in_cluster = sector_num & (s->cluster_sectors - 1);
13514bc74be9SPaolo Bonzini         cluster_offset |= (index_in_cluster << BDRV_SECTOR_BITS);
13524bc74be9SPaolo Bonzini         status |= BDRV_BLOCK_OFFSET_VALID | cluster_offset;
13534bc74be9SPaolo Bonzini     }
13544bc74be9SPaolo Bonzini     if (ret == QCOW2_CLUSTER_ZERO) {
13554bc74be9SPaolo Bonzini         status |= BDRV_BLOCK_ZERO;
13564bc74be9SPaolo Bonzini     } else if (ret != QCOW2_CLUSTER_UNALLOCATED) {
13574bc74be9SPaolo Bonzini         status |= BDRV_BLOCK_DATA;
13584bc74be9SPaolo Bonzini     }
13594bc74be9SPaolo Bonzini     return status;
1360585f8587Sbellard }
1361585f8587Sbellard 
1362a9465922Sbellard /* handle reading after the end of the backing file */
1363bd28f835SKevin Wolf int qcow2_backing_read1(BlockDriverState *bs, QEMUIOVector *qiov,
1364bd28f835SKevin Wolf                   int64_t sector_num, int nb_sectors)
1365a9465922Sbellard {
1366a9465922Sbellard     int n1;
1367a9465922Sbellard     if ((sector_num + nb_sectors) <= bs->total_sectors)
1368a9465922Sbellard         return nb_sectors;
1369a9465922Sbellard     if (sector_num >= bs->total_sectors)
1370a9465922Sbellard         n1 = 0;
1371a9465922Sbellard     else
1372a9465922Sbellard         n1 = bs->total_sectors - sector_num;
1373bd28f835SKevin Wolf 
13743d9b4925SMichael Tokarev     qemu_iovec_memset(qiov, 512 * n1, 0, 512 * (nb_sectors - n1));
1375bd28f835SKevin Wolf 
1376a9465922Sbellard     return n1;
1377a9465922Sbellard }
1378a9465922Sbellard 
1379a968168cSDong Xu Wang static coroutine_fn int qcow2_co_readv(BlockDriverState *bs, int64_t sector_num,
13803fc48d09SFrediano Ziglio                           int remaining_sectors, QEMUIOVector *qiov)
13811490791fSaliguori {
1382ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
1383a9465922Sbellard     int index_in_cluster, n1;
138468d100e9SKevin Wolf     int ret;
1385faf575c1SFrediano Ziglio     int cur_nr_sectors; /* number of sectors in current iteration */
1386c2bdd990SFrediano Ziglio     uint64_t cluster_offset = 0;
13873fc48d09SFrediano Ziglio     uint64_t bytes_done = 0;
13883fc48d09SFrediano Ziglio     QEMUIOVector hd_qiov;
13893fc48d09SFrediano Ziglio     uint8_t *cluster_data = NULL;
1390585f8587Sbellard 
13913fc48d09SFrediano Ziglio     qemu_iovec_init(&hd_qiov, qiov->niov);
13923fc48d09SFrediano Ziglio 
13933fc48d09SFrediano Ziglio     qemu_co_mutex_lock(&s->lock);
13943fc48d09SFrediano Ziglio 
13953fc48d09SFrediano Ziglio     while (remaining_sectors != 0) {
1396585f8587Sbellard 
1397faf575c1SFrediano Ziglio         /* prepare next request */
13983fc48d09SFrediano Ziglio         cur_nr_sectors = remaining_sectors;
1399f6fa64f6SDaniel P. Berrange         if (s->cipher) {
1400faf575c1SFrediano Ziglio             cur_nr_sectors = MIN(cur_nr_sectors,
1401bd28f835SKevin Wolf                 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors);
1402bd28f835SKevin Wolf         }
1403bd28f835SKevin Wolf 
14043fc48d09SFrediano Ziglio         ret = qcow2_get_cluster_offset(bs, sector_num << 9,
1405c2bdd990SFrediano Ziglio             &cur_nr_sectors, &cluster_offset);
14061c46efaaSKevin Wolf         if (ret < 0) {
14073fc48d09SFrediano Ziglio             goto fail;
14081c46efaaSKevin Wolf         }
14091c46efaaSKevin Wolf 
14103fc48d09SFrediano Ziglio         index_in_cluster = sector_num & (s->cluster_sectors - 1);
1411585f8587Sbellard 
14123fc48d09SFrediano Ziglio         qemu_iovec_reset(&hd_qiov);
14131b093c48SMichael Tokarev         qemu_iovec_concat(&hd_qiov, qiov, bytes_done,
1414faf575c1SFrediano Ziglio             cur_nr_sectors * 512);
1415bd28f835SKevin Wolf 
141668d000a3SKevin Wolf         switch (ret) {
141768d000a3SKevin Wolf         case QCOW2_CLUSTER_UNALLOCATED:
1418bd28f835SKevin Wolf 
1419760e0063SKevin Wolf             if (bs->backing) {
1420585f8587Sbellard                 /* read from the base image */
1421760e0063SKevin Wolf                 n1 = qcow2_backing_read1(bs->backing->bs, &hd_qiov,
14223fc48d09SFrediano Ziglio                     sector_num, cur_nr_sectors);
1423a9465922Sbellard                 if (n1 > 0) {
142444deba5aSKevin Wolf                     QEMUIOVector local_qiov;
142544deba5aSKevin Wolf 
142644deba5aSKevin Wolf                     qemu_iovec_init(&local_qiov, hd_qiov.niov);
142744deba5aSKevin Wolf                     qemu_iovec_concat(&local_qiov, &hd_qiov, 0,
142844deba5aSKevin Wolf                                       n1 * BDRV_SECTOR_SIZE);
142944deba5aSKevin Wolf 
143066f82ceeSKevin Wolf                     BLKDBG_EVENT(bs->file, BLKDBG_READ_BACKING_AIO);
143168d100e9SKevin Wolf                     qemu_co_mutex_unlock(&s->lock);
1432760e0063SKevin Wolf                     ret = bdrv_co_readv(bs->backing->bs, sector_num,
143344deba5aSKevin Wolf                                         n1, &local_qiov);
143468d100e9SKevin Wolf                     qemu_co_mutex_lock(&s->lock);
143544deba5aSKevin Wolf 
143644deba5aSKevin Wolf                     qemu_iovec_destroy(&local_qiov);
143744deba5aSKevin Wolf 
143868d100e9SKevin Wolf                     if (ret < 0) {
14393fc48d09SFrediano Ziglio                         goto fail;
14403ab4c7e9SKevin Wolf                     }
14411490791fSaliguori                 }
1442a9465922Sbellard             } else {
1443585f8587Sbellard                 /* Note: in this case, no need to wait */
14443d9b4925SMichael Tokarev                 qemu_iovec_memset(&hd_qiov, 0, 0, 512 * cur_nr_sectors);
14451490791fSaliguori             }
144668d000a3SKevin Wolf             break;
144768d000a3SKevin Wolf 
14486377af48SKevin Wolf         case QCOW2_CLUSTER_ZERO:
14493d9b4925SMichael Tokarev             qemu_iovec_memset(&hd_qiov, 0, 0, 512 * cur_nr_sectors);
14506377af48SKevin Wolf             break;
14516377af48SKevin Wolf 
145268d000a3SKevin Wolf         case QCOW2_CLUSTER_COMPRESSED:
1453585f8587Sbellard             /* add AIO support for compressed blocks ? */
1454c2bdd990SFrediano Ziglio             ret = qcow2_decompress_cluster(bs, cluster_offset);
14558af36488SKevin Wolf             if (ret < 0) {
14563fc48d09SFrediano Ziglio                 goto fail;
14578af36488SKevin Wolf             }
1458bd28f835SKevin Wolf 
145903396148SMichael Tokarev             qemu_iovec_from_buf(&hd_qiov, 0,
1460bd28f835SKevin Wolf                 s->cluster_cache + index_in_cluster * 512,
1461faf575c1SFrediano Ziglio                 512 * cur_nr_sectors);
146268d000a3SKevin Wolf             break;
146368d000a3SKevin Wolf 
146468d000a3SKevin Wolf         case QCOW2_CLUSTER_NORMAL:
1465c2bdd990SFrediano Ziglio             if ((cluster_offset & 511) != 0) {
14663fc48d09SFrediano Ziglio                 ret = -EIO;
14673fc48d09SFrediano Ziglio                 goto fail;
1468585f8587Sbellard             }
1469c87c0672Saliguori 
14708336aafaSDaniel P. Berrange             if (bs->encrypted) {
1471f6fa64f6SDaniel P. Berrange                 assert(s->cipher);
14728336aafaSDaniel P. Berrange 
1473bd28f835SKevin Wolf                 /*
1474bd28f835SKevin Wolf                  * For encrypted images, read everything into a temporary
1475bd28f835SKevin Wolf                  * contiguous buffer on which the AES functions can work.
1476bd28f835SKevin Wolf                  */
14773fc48d09SFrediano Ziglio                 if (!cluster_data) {
14783fc48d09SFrediano Ziglio                     cluster_data =
14799a4f4c31SKevin Wolf                         qemu_try_blockalign(bs->file->bs,
14809a4f4c31SKevin Wolf                                             QCOW_MAX_CRYPT_CLUSTERS
1481de82815dSKevin Wolf                                             * s->cluster_size);
1482de82815dSKevin Wolf                     if (cluster_data == NULL) {
1483de82815dSKevin Wolf                         ret = -ENOMEM;
1484de82815dSKevin Wolf                         goto fail;
1485de82815dSKevin Wolf                     }
1486bd28f835SKevin Wolf                 }
1487bd28f835SKevin Wolf 
1488faf575c1SFrediano Ziglio                 assert(cur_nr_sectors <=
1489bd28f835SKevin Wolf                     QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors);
14903fc48d09SFrediano Ziglio                 qemu_iovec_reset(&hd_qiov);
14913fc48d09SFrediano Ziglio                 qemu_iovec_add(&hd_qiov, cluster_data,
1492faf575c1SFrediano Ziglio                     512 * cur_nr_sectors);
1493bd28f835SKevin Wolf             }
1494bd28f835SKevin Wolf 
149566f82ceeSKevin Wolf             BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);
149668d100e9SKevin Wolf             qemu_co_mutex_unlock(&s->lock);
14979a4f4c31SKevin Wolf             ret = bdrv_co_readv(bs->file->bs,
1498c2bdd990SFrediano Ziglio                                 (cluster_offset >> 9) + index_in_cluster,
14993fc48d09SFrediano Ziglio                                 cur_nr_sectors, &hd_qiov);
150068d100e9SKevin Wolf             qemu_co_mutex_lock(&s->lock);
150168d100e9SKevin Wolf             if (ret < 0) {
15023fc48d09SFrediano Ziglio                 goto fail;
1503585f8587Sbellard             }
15048336aafaSDaniel P. Berrange             if (bs->encrypted) {
1505f6fa64f6SDaniel P. Berrange                 assert(s->cipher);
1506f6fa64f6SDaniel P. Berrange                 Error *err = NULL;
1507f6fa64f6SDaniel P. Berrange                 if (qcow2_encrypt_sectors(s, sector_num,  cluster_data,
1508f6fa64f6SDaniel P. Berrange                                           cluster_data, cur_nr_sectors, false,
1509f6fa64f6SDaniel P. Berrange                                           &err) < 0) {
1510f6fa64f6SDaniel P. Berrange                     error_free(err);
1511f6fa64f6SDaniel P. Berrange                     ret = -EIO;
1512f6fa64f6SDaniel P. Berrange                     goto fail;
1513f6fa64f6SDaniel P. Berrange                 }
151403396148SMichael Tokarev                 qemu_iovec_from_buf(qiov, bytes_done,
151503396148SMichael Tokarev                     cluster_data, 512 * cur_nr_sectors);
1516171e3d6bSKevin Wolf             }
151768d000a3SKevin Wolf             break;
151868d000a3SKevin Wolf 
151968d000a3SKevin Wolf         default:
152068d000a3SKevin Wolf             g_assert_not_reached();
152168d000a3SKevin Wolf             ret = -EIO;
152268d000a3SKevin Wolf             goto fail;
1523faf575c1SFrediano Ziglio         }
1524faf575c1SFrediano Ziglio 
15253fc48d09SFrediano Ziglio         remaining_sectors -= cur_nr_sectors;
15263fc48d09SFrediano Ziglio         sector_num += cur_nr_sectors;
15273fc48d09SFrediano Ziglio         bytes_done += cur_nr_sectors * 512;
15285ebaa27eSFrediano Ziglio     }
15293fc48d09SFrediano Ziglio     ret = 0;
1530f141eafeSaliguori 
15313fc48d09SFrediano Ziglio fail:
153268d100e9SKevin Wolf     qemu_co_mutex_unlock(&s->lock);
153368d100e9SKevin Wolf 
15343fc48d09SFrediano Ziglio     qemu_iovec_destroy(&hd_qiov);
1535dea43a65SFrediano Ziglio     qemu_vfree(cluster_data);
153668d100e9SKevin Wolf 
153768d100e9SKevin Wolf     return ret;
1538585f8587Sbellard }
1539585f8587Sbellard 
1540a968168cSDong Xu Wang static coroutine_fn int qcow2_co_writev(BlockDriverState *bs,
15413fc48d09SFrediano Ziglio                            int64_t sector_num,
15423fc48d09SFrediano Ziglio                            int remaining_sectors,
15433fc48d09SFrediano Ziglio                            QEMUIOVector *qiov)
1544585f8587Sbellard {
1545ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
1546585f8587Sbellard     int index_in_cluster;
154768d100e9SKevin Wolf     int ret;
1548faf575c1SFrediano Ziglio     int cur_nr_sectors; /* number of sectors in current iteration */
1549c2bdd990SFrediano Ziglio     uint64_t cluster_offset;
15503fc48d09SFrediano Ziglio     QEMUIOVector hd_qiov;
15513fc48d09SFrediano Ziglio     uint64_t bytes_done = 0;
15523fc48d09SFrediano Ziglio     uint8_t *cluster_data = NULL;
15538d2497c3SKevin Wolf     QCowL2Meta *l2meta = NULL;
1554c2271403SFrediano Ziglio 
15553cce16f4SKevin Wolf     trace_qcow2_writev_start_req(qemu_coroutine_self(), sector_num,
15563cce16f4SKevin Wolf                                  remaining_sectors);
15573cce16f4SKevin Wolf 
15583fc48d09SFrediano Ziglio     qemu_iovec_init(&hd_qiov, qiov->niov);
1559585f8587Sbellard 
15603fc48d09SFrediano Ziglio     s->cluster_cache_offset = -1; /* disable compressed cache */
15613fc48d09SFrediano Ziglio 
15623fc48d09SFrediano Ziglio     qemu_co_mutex_lock(&s->lock);
15633fc48d09SFrediano Ziglio 
15643fc48d09SFrediano Ziglio     while (remaining_sectors != 0) {
15653fc48d09SFrediano Ziglio 
1566f50f88b9SKevin Wolf         l2meta = NULL;
1567cf5c1a23SKevin Wolf 
15683cce16f4SKevin Wolf         trace_qcow2_writev_start_part(qemu_coroutine_self());
15693fc48d09SFrediano Ziglio         index_in_cluster = sector_num & (s->cluster_sectors - 1);
157016f0587eSHu Tao         cur_nr_sectors = remaining_sectors;
15718336aafaSDaniel P. Berrange         if (bs->encrypted &&
157216f0587eSHu Tao             cur_nr_sectors >
157316f0587eSHu Tao             QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors - index_in_cluster) {
157416f0587eSHu Tao             cur_nr_sectors =
157516f0587eSHu Tao                 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors - index_in_cluster;
15765ebaa27eSFrediano Ziglio         }
1577095a9c58Saliguori 
15783fc48d09SFrediano Ziglio         ret = qcow2_alloc_cluster_offset(bs, sector_num << 9,
157916f0587eSHu Tao             &cur_nr_sectors, &cluster_offset, &l2meta);
1580148da7eaSKevin Wolf         if (ret < 0) {
15813fc48d09SFrediano Ziglio             goto fail;
1582148da7eaSKevin Wolf         }
1583148da7eaSKevin Wolf 
1584c2bdd990SFrediano Ziglio         assert((cluster_offset & 511) == 0);
1585148da7eaSKevin Wolf 
15863fc48d09SFrediano Ziglio         qemu_iovec_reset(&hd_qiov);
15871b093c48SMichael Tokarev         qemu_iovec_concat(&hd_qiov, qiov, bytes_done,
1588faf575c1SFrediano Ziglio             cur_nr_sectors * 512);
15896f5f060bSKevin Wolf 
15908336aafaSDaniel P. Berrange         if (bs->encrypted) {
1591f6fa64f6SDaniel P. Berrange             Error *err = NULL;
1592f6fa64f6SDaniel P. Berrange             assert(s->cipher);
15933fc48d09SFrediano Ziglio             if (!cluster_data) {
15949a4f4c31SKevin Wolf                 cluster_data = qemu_try_blockalign(bs->file->bs,
1595de82815dSKevin Wolf                                                    QCOW_MAX_CRYPT_CLUSTERS
1596de82815dSKevin Wolf                                                    * s->cluster_size);
1597de82815dSKevin Wolf                 if (cluster_data == NULL) {
1598de82815dSKevin Wolf                     ret = -ENOMEM;
1599de82815dSKevin Wolf                     goto fail;
1600de82815dSKevin Wolf                 }
1601585f8587Sbellard             }
16026f5f060bSKevin Wolf 
16033fc48d09SFrediano Ziglio             assert(hd_qiov.size <=
16045ebaa27eSFrediano Ziglio                    QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
1605d5e6b161SMichael Tokarev             qemu_iovec_to_buf(&hd_qiov, 0, cluster_data, hd_qiov.size);
16066f5f060bSKevin Wolf 
1607f6fa64f6SDaniel P. Berrange             if (qcow2_encrypt_sectors(s, sector_num, cluster_data,
1608f6fa64f6SDaniel P. Berrange                                       cluster_data, cur_nr_sectors,
1609f6fa64f6SDaniel P. Berrange                                       true, &err) < 0) {
1610f6fa64f6SDaniel P. Berrange                 error_free(err);
1611f6fa64f6SDaniel P. Berrange                 ret = -EIO;
1612f6fa64f6SDaniel P. Berrange                 goto fail;
1613f6fa64f6SDaniel P. Berrange             }
16146f5f060bSKevin Wolf 
16153fc48d09SFrediano Ziglio             qemu_iovec_reset(&hd_qiov);
16163fc48d09SFrediano Ziglio             qemu_iovec_add(&hd_qiov, cluster_data,
1617faf575c1SFrediano Ziglio                 cur_nr_sectors * 512);
1618585f8587Sbellard         }
16196f5f060bSKevin Wolf 
1620231bb267SMax Reitz         ret = qcow2_pre_write_overlap_check(bs, 0,
1621cf93980eSMax Reitz                 cluster_offset + index_in_cluster * BDRV_SECTOR_SIZE,
1622cf93980eSMax Reitz                 cur_nr_sectors * BDRV_SECTOR_SIZE);
1623cf93980eSMax Reitz         if (ret < 0) {
1624cf93980eSMax Reitz             goto fail;
1625cf93980eSMax Reitz         }
1626cf93980eSMax Reitz 
162768d100e9SKevin Wolf         qemu_co_mutex_unlock(&s->lock);
162867a7a0ebSKevin Wolf         BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO);
16293cce16f4SKevin Wolf         trace_qcow2_writev_data(qemu_coroutine_self(),
16303cce16f4SKevin Wolf                                 (cluster_offset >> 9) + index_in_cluster);
16319a4f4c31SKevin Wolf         ret = bdrv_co_writev(bs->file->bs,
1632c2bdd990SFrediano Ziglio                              (cluster_offset >> 9) + index_in_cluster,
16333fc48d09SFrediano Ziglio                              cur_nr_sectors, &hd_qiov);
163468d100e9SKevin Wolf         qemu_co_mutex_lock(&s->lock);
163568d100e9SKevin Wolf         if (ret < 0) {
16363fc48d09SFrediano Ziglio             goto fail;
1637171e3d6bSKevin Wolf         }
1638f141eafeSaliguori 
163988c6588cSKevin Wolf         while (l2meta != NULL) {
164088c6588cSKevin Wolf             QCowL2Meta *next;
164188c6588cSKevin Wolf 
1642cf5c1a23SKevin Wolf             ret = qcow2_alloc_cluster_link_l2(bs, l2meta);
1643faf575c1SFrediano Ziglio             if (ret < 0) {
16443fc48d09SFrediano Ziglio                 goto fail;
1645faf575c1SFrediano Ziglio             }
1646faf575c1SFrediano Ziglio 
16474e95314eSKevin Wolf             /* Take the request off the list of running requests */
16484e95314eSKevin Wolf             if (l2meta->nb_clusters != 0) {
16494e95314eSKevin Wolf                 QLIST_REMOVE(l2meta, next_in_flight);
16504e95314eSKevin Wolf             }
16514e95314eSKevin Wolf 
16524e95314eSKevin Wolf             qemu_co_queue_restart_all(&l2meta->dependent_requests);
16534e95314eSKevin Wolf 
165488c6588cSKevin Wolf             next = l2meta->next;
1655cf5c1a23SKevin Wolf             g_free(l2meta);
165688c6588cSKevin Wolf             l2meta = next;
1657f50f88b9SKevin Wolf         }
16580fa9131aSKevin Wolf 
16593fc48d09SFrediano Ziglio         remaining_sectors -= cur_nr_sectors;
16603fc48d09SFrediano Ziglio         sector_num += cur_nr_sectors;
16613fc48d09SFrediano Ziglio         bytes_done += cur_nr_sectors * 512;
16623cce16f4SKevin Wolf         trace_qcow2_writev_done_part(qemu_coroutine_self(), cur_nr_sectors);
16635ebaa27eSFrediano Ziglio     }
16643fc48d09SFrediano Ziglio     ret = 0;
1665faf575c1SFrediano Ziglio 
16663fc48d09SFrediano Ziglio fail:
16674e95314eSKevin Wolf     qemu_co_mutex_unlock(&s->lock);
16684e95314eSKevin Wolf 
166988c6588cSKevin Wolf     while (l2meta != NULL) {
167088c6588cSKevin Wolf         QCowL2Meta *next;
167188c6588cSKevin Wolf 
16724e95314eSKevin Wolf         if (l2meta->nb_clusters != 0) {
16734e95314eSKevin Wolf             QLIST_REMOVE(l2meta, next_in_flight);
16744e95314eSKevin Wolf         }
16754e95314eSKevin Wolf         qemu_co_queue_restart_all(&l2meta->dependent_requests);
167688c6588cSKevin Wolf 
167788c6588cSKevin Wolf         next = l2meta->next;
1678cf5c1a23SKevin Wolf         g_free(l2meta);
167988c6588cSKevin Wolf         l2meta = next;
1680cf5c1a23SKevin Wolf     }
16810fa9131aSKevin Wolf 
16823fc48d09SFrediano Ziglio     qemu_iovec_destroy(&hd_qiov);
1683dea43a65SFrediano Ziglio     qemu_vfree(cluster_data);
16843cce16f4SKevin Wolf     trace_qcow2_writev_done_req(qemu_coroutine_self(), ret);
168542496d62SKevin Wolf 
168668d100e9SKevin Wolf     return ret;
1687585f8587Sbellard }
1688585f8587Sbellard 
1689*ec6d8912SKevin Wolf static int qcow2_inactivate(BlockDriverState *bs)
1690*ec6d8912SKevin Wolf {
1691*ec6d8912SKevin Wolf     BDRVQcow2State *s = bs->opaque;
1692*ec6d8912SKevin Wolf     int ret, result = 0;
1693*ec6d8912SKevin Wolf 
1694*ec6d8912SKevin Wolf     ret = qcow2_cache_flush(bs, s->l2_table_cache);
1695*ec6d8912SKevin Wolf     if (ret) {
1696*ec6d8912SKevin Wolf         result = ret;
1697*ec6d8912SKevin Wolf         error_report("Failed to flush the L2 table cache: %s",
1698*ec6d8912SKevin Wolf                      strerror(-ret));
1699*ec6d8912SKevin Wolf     }
1700*ec6d8912SKevin Wolf 
1701*ec6d8912SKevin Wolf     ret = qcow2_cache_flush(bs, s->refcount_block_cache);
1702*ec6d8912SKevin Wolf     if (ret) {
1703*ec6d8912SKevin Wolf         result = ret;
1704*ec6d8912SKevin Wolf         error_report("Failed to flush the refcount block cache: %s",
1705*ec6d8912SKevin Wolf                      strerror(-ret));
1706*ec6d8912SKevin Wolf     }
1707*ec6d8912SKevin Wolf 
1708*ec6d8912SKevin Wolf     if (result == 0) {
1709*ec6d8912SKevin Wolf         qcow2_mark_clean(bs);
1710*ec6d8912SKevin Wolf     }
1711*ec6d8912SKevin Wolf 
1712*ec6d8912SKevin Wolf     return result;
1713*ec6d8912SKevin Wolf }
1714*ec6d8912SKevin Wolf 
17157c80ab3fSJes Sorensen static void qcow2_close(BlockDriverState *bs)
1716585f8587Sbellard {
1717ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
1718de82815dSKevin Wolf     qemu_vfree(s->l1_table);
1719cf93980eSMax Reitz     /* else pre-write overlap checks in cache_destroy may crash */
1720cf93980eSMax Reitz     s->l1_table = NULL;
172129c1a730SKevin Wolf 
172204c01a5cSKevin Wolf     if (!(bs->open_flags & BDRV_O_INACTIVE)) {
1723*ec6d8912SKevin Wolf         qcow2_inactivate(bs);
17243b5e14c7SMax Reitz     }
1725c61d0004SStefan Hajnoczi 
1726279621c0SAlberto Garcia     cache_clean_timer_del(bs);
172729c1a730SKevin Wolf     qcow2_cache_destroy(bs, s->l2_table_cache);
172829c1a730SKevin Wolf     qcow2_cache_destroy(bs, s->refcount_block_cache);
172929c1a730SKevin Wolf 
1730f6fa64f6SDaniel P. Berrange     qcrypto_cipher_free(s->cipher);
1731f6fa64f6SDaniel P. Berrange     s->cipher = NULL;
1732f6fa64f6SDaniel P. Berrange 
17336744cbabSKevin Wolf     g_free(s->unknown_header_fields);
173475bab85cSKevin Wolf     cleanup_unknown_header_ext(bs);
17356744cbabSKevin Wolf 
1736e4603fe1SKevin Wolf     g_free(s->image_backing_file);
1737e4603fe1SKevin Wolf     g_free(s->image_backing_format);
1738e4603fe1SKevin Wolf 
17397267c094SAnthony Liguori     g_free(s->cluster_cache);
1740dea43a65SFrediano Ziglio     qemu_vfree(s->cluster_data);
1741ed6ccf0fSKevin Wolf     qcow2_refcount_close(bs);
174228c1202bSLi Zhi Hui     qcow2_free_snapshots(bs);
1743585f8587Sbellard }
1744585f8587Sbellard 
17455a8a30dbSKevin Wolf static void qcow2_invalidate_cache(BlockDriverState *bs, Error **errp)
174606d9260fSAnthony Liguori {
1747ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
174806d9260fSAnthony Liguori     int flags = s->flags;
1749f6fa64f6SDaniel P. Berrange     QCryptoCipher *cipher = NULL;
1750acdfb480SKevin Wolf     QDict *options;
17515a8a30dbSKevin Wolf     Error *local_err = NULL;
17525a8a30dbSKevin Wolf     int ret;
175306d9260fSAnthony Liguori 
175406d9260fSAnthony Liguori     /*
175506d9260fSAnthony Liguori      * Backing files are read-only which makes all of their metadata immutable,
175606d9260fSAnthony Liguori      * that means we don't have to worry about reopening them here.
175706d9260fSAnthony Liguori      */
175806d9260fSAnthony Liguori 
1759f6fa64f6SDaniel P. Berrange     cipher = s->cipher;
1760f6fa64f6SDaniel P. Berrange     s->cipher = NULL;
176106d9260fSAnthony Liguori 
176206d9260fSAnthony Liguori     qcow2_close(bs);
176306d9260fSAnthony Liguori 
17649a4f4c31SKevin Wolf     bdrv_invalidate_cache(bs->file->bs, &local_err);
17655a8a30dbSKevin Wolf     if (local_err) {
17665a8a30dbSKevin Wolf         error_propagate(errp, local_err);
17675a8a30dbSKevin Wolf         return;
17685a8a30dbSKevin Wolf     }
17693456a8d1SKevin Wolf 
1770ff99129aSKevin Wolf     memset(s, 0, sizeof(BDRVQcow2State));
1771d475e5acSKevin Wolf     options = qdict_clone_shallow(bs->options);
17725a8a30dbSKevin Wolf 
17735a8a30dbSKevin Wolf     ret = qcow2_open(bs, options, flags, &local_err);
1774a1904e48SMarkus Armbruster     QDECREF(options);
17755a8a30dbSKevin Wolf     if (local_err) {
1776e43bfd9cSMarkus Armbruster         error_propagate(errp, local_err);
1777e43bfd9cSMarkus Armbruster         error_prepend(errp, "Could not reopen qcow2 layer: ");
17785a8a30dbSKevin Wolf         return;
17795a8a30dbSKevin Wolf     } else if (ret < 0) {
17805a8a30dbSKevin Wolf         error_setg_errno(errp, -ret, "Could not reopen qcow2 layer");
17815a8a30dbSKevin Wolf         return;
17825a8a30dbSKevin Wolf     }
1783acdfb480SKevin Wolf 
1784f6fa64f6SDaniel P. Berrange     s->cipher = cipher;
178506d9260fSAnthony Liguori }
178606d9260fSAnthony Liguori 
1787e24e49e6SKevin Wolf static size_t header_ext_add(char *buf, uint32_t magic, const void *s,
1788e24e49e6SKevin Wolf     size_t len, size_t buflen)
1789756e6736SKevin Wolf {
1790e24e49e6SKevin Wolf     QCowExtension *ext_backing_fmt = (QCowExtension*) buf;
1791e24e49e6SKevin Wolf     size_t ext_len = sizeof(QCowExtension) + ((len + 7) & ~7);
1792756e6736SKevin Wolf 
1793e24e49e6SKevin Wolf     if (buflen < ext_len) {
1794756e6736SKevin Wolf         return -ENOSPC;
1795756e6736SKevin Wolf     }
1796756e6736SKevin Wolf 
1797e24e49e6SKevin Wolf     *ext_backing_fmt = (QCowExtension) {
1798e24e49e6SKevin Wolf         .magic  = cpu_to_be32(magic),
1799e24e49e6SKevin Wolf         .len    = cpu_to_be32(len),
1800e24e49e6SKevin Wolf     };
1801e24e49e6SKevin Wolf     memcpy(buf + sizeof(QCowExtension), s, len);
1802756e6736SKevin Wolf 
1803e24e49e6SKevin Wolf     return ext_len;
1804756e6736SKevin Wolf }
1805756e6736SKevin Wolf 
1806e24e49e6SKevin Wolf /*
1807e24e49e6SKevin Wolf  * Updates the qcow2 header, including the variable length parts of it, i.e.
1808e24e49e6SKevin Wolf  * the backing file name and all extensions. qcow2 was not designed to allow
1809e24e49e6SKevin Wolf  * such changes, so if we run out of space (we can only use the first cluster)
1810e24e49e6SKevin Wolf  * this function may fail.
1811e24e49e6SKevin Wolf  *
1812e24e49e6SKevin Wolf  * Returns 0 on success, -errno in error cases.
1813e24e49e6SKevin Wolf  */
1814e24e49e6SKevin Wolf int qcow2_update_header(BlockDriverState *bs)
1815e24e49e6SKevin Wolf {
1816ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
1817e24e49e6SKevin Wolf     QCowHeader *header;
1818e24e49e6SKevin Wolf     char *buf;
1819e24e49e6SKevin Wolf     size_t buflen = s->cluster_size;
1820e24e49e6SKevin Wolf     int ret;
1821e24e49e6SKevin Wolf     uint64_t total_size;
1822e24e49e6SKevin Wolf     uint32_t refcount_table_clusters;
18236744cbabSKevin Wolf     size_t header_length;
182475bab85cSKevin Wolf     Qcow2UnknownHeaderExtension *uext;
1825e24e49e6SKevin Wolf 
1826e24e49e6SKevin Wolf     buf = qemu_blockalign(bs, buflen);
1827e24e49e6SKevin Wolf 
1828e24e49e6SKevin Wolf     /* Header structure */
1829e24e49e6SKevin Wolf     header = (QCowHeader*) buf;
1830e24e49e6SKevin Wolf 
1831e24e49e6SKevin Wolf     if (buflen < sizeof(*header)) {
1832e24e49e6SKevin Wolf         ret = -ENOSPC;
1833e24e49e6SKevin Wolf         goto fail;
1834756e6736SKevin Wolf     }
1835756e6736SKevin Wolf 
18366744cbabSKevin Wolf     header_length = sizeof(*header) + s->unknown_header_fields_size;
1837e24e49e6SKevin Wolf     total_size = bs->total_sectors * BDRV_SECTOR_SIZE;
1838e24e49e6SKevin Wolf     refcount_table_clusters = s->refcount_table_size >> (s->cluster_bits - 3);
1839e24e49e6SKevin Wolf 
1840e24e49e6SKevin Wolf     *header = (QCowHeader) {
18416744cbabSKevin Wolf         /* Version 2 fields */
1842e24e49e6SKevin Wolf         .magic                  = cpu_to_be32(QCOW_MAGIC),
18436744cbabSKevin Wolf         .version                = cpu_to_be32(s->qcow_version),
1844e24e49e6SKevin Wolf         .backing_file_offset    = 0,
1845e24e49e6SKevin Wolf         .backing_file_size      = 0,
1846e24e49e6SKevin Wolf         .cluster_bits           = cpu_to_be32(s->cluster_bits),
1847e24e49e6SKevin Wolf         .size                   = cpu_to_be64(total_size),
1848e24e49e6SKevin Wolf         .crypt_method           = cpu_to_be32(s->crypt_method_header),
1849e24e49e6SKevin Wolf         .l1_size                = cpu_to_be32(s->l1_size),
1850e24e49e6SKevin Wolf         .l1_table_offset        = cpu_to_be64(s->l1_table_offset),
1851e24e49e6SKevin Wolf         .refcount_table_offset  = cpu_to_be64(s->refcount_table_offset),
1852e24e49e6SKevin Wolf         .refcount_table_clusters = cpu_to_be32(refcount_table_clusters),
1853e24e49e6SKevin Wolf         .nb_snapshots           = cpu_to_be32(s->nb_snapshots),
1854e24e49e6SKevin Wolf         .snapshots_offset       = cpu_to_be64(s->snapshots_offset),
18556744cbabSKevin Wolf 
18566744cbabSKevin Wolf         /* Version 3 fields */
18576744cbabSKevin Wolf         .incompatible_features  = cpu_to_be64(s->incompatible_features),
18586744cbabSKevin Wolf         .compatible_features    = cpu_to_be64(s->compatible_features),
18596744cbabSKevin Wolf         .autoclear_features     = cpu_to_be64(s->autoclear_features),
1860b6481f37SMax Reitz         .refcount_order         = cpu_to_be32(s->refcount_order),
18616744cbabSKevin Wolf         .header_length          = cpu_to_be32(header_length),
1862e24e49e6SKevin Wolf     };
1863e24e49e6SKevin Wolf 
18646744cbabSKevin Wolf     /* For older versions, write a shorter header */
18656744cbabSKevin Wolf     switch (s->qcow_version) {
18666744cbabSKevin Wolf     case 2:
18676744cbabSKevin Wolf         ret = offsetof(QCowHeader, incompatible_features);
18686744cbabSKevin Wolf         break;
18696744cbabSKevin Wolf     case 3:
18706744cbabSKevin Wolf         ret = sizeof(*header);
18716744cbabSKevin Wolf         break;
18726744cbabSKevin Wolf     default:
1873b6c14762SJim Meyering         ret = -EINVAL;
1874b6c14762SJim Meyering         goto fail;
18756744cbabSKevin Wolf     }
18766744cbabSKevin Wolf 
18776744cbabSKevin Wolf     buf += ret;
18786744cbabSKevin Wolf     buflen -= ret;
18796744cbabSKevin Wolf     memset(buf, 0, buflen);
18806744cbabSKevin Wolf 
18816744cbabSKevin Wolf     /* Preserve any unknown field in the header */
18826744cbabSKevin Wolf     if (s->unknown_header_fields_size) {
18836744cbabSKevin Wolf         if (buflen < s->unknown_header_fields_size) {
18846744cbabSKevin Wolf             ret = -ENOSPC;
18856744cbabSKevin Wolf             goto fail;
18866744cbabSKevin Wolf         }
18876744cbabSKevin Wolf 
18886744cbabSKevin Wolf         memcpy(buf, s->unknown_header_fields, s->unknown_header_fields_size);
18896744cbabSKevin Wolf         buf += s->unknown_header_fields_size;
18906744cbabSKevin Wolf         buflen -= s->unknown_header_fields_size;
18916744cbabSKevin Wolf     }
1892e24e49e6SKevin Wolf 
1893e24e49e6SKevin Wolf     /* Backing file format header extension */
1894e4603fe1SKevin Wolf     if (s->image_backing_format) {
1895e24e49e6SKevin Wolf         ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BACKING_FORMAT,
1896e4603fe1SKevin Wolf                              s->image_backing_format,
1897e4603fe1SKevin Wolf                              strlen(s->image_backing_format),
1898e24e49e6SKevin Wolf                              buflen);
1899756e6736SKevin Wolf         if (ret < 0) {
1900756e6736SKevin Wolf             goto fail;
1901756e6736SKevin Wolf         }
1902756e6736SKevin Wolf 
1903e24e49e6SKevin Wolf         buf += ret;
1904e24e49e6SKevin Wolf         buflen -= ret;
1905e24e49e6SKevin Wolf     }
1906756e6736SKevin Wolf 
1907cfcc4c62SKevin Wolf     /* Feature table */
19081a4828c7SKevin Wolf     if (s->qcow_version >= 3) {
1909cfcc4c62SKevin Wolf         Qcow2Feature features[] = {
1910c61d0004SStefan Hajnoczi             {
1911c61d0004SStefan Hajnoczi                 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
1912c61d0004SStefan Hajnoczi                 .bit  = QCOW2_INCOMPAT_DIRTY_BITNR,
1913c61d0004SStefan Hajnoczi                 .name = "dirty bit",
1914c61d0004SStefan Hajnoczi             },
1915bfe8043eSStefan Hajnoczi             {
191669c98726SMax Reitz                 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
191769c98726SMax Reitz                 .bit  = QCOW2_INCOMPAT_CORRUPT_BITNR,
191869c98726SMax Reitz                 .name = "corrupt bit",
191969c98726SMax Reitz             },
192069c98726SMax Reitz             {
1921bfe8043eSStefan Hajnoczi                 .type = QCOW2_FEAT_TYPE_COMPATIBLE,
1922bfe8043eSStefan Hajnoczi                 .bit  = QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR,
1923bfe8043eSStefan Hajnoczi                 .name = "lazy refcounts",
1924bfe8043eSStefan Hajnoczi             },
1925cfcc4c62SKevin Wolf         };
1926cfcc4c62SKevin Wolf 
1927cfcc4c62SKevin Wolf         ret = header_ext_add(buf, QCOW2_EXT_MAGIC_FEATURE_TABLE,
1928cfcc4c62SKevin Wolf                              features, sizeof(features), buflen);
1929cfcc4c62SKevin Wolf         if (ret < 0) {
1930cfcc4c62SKevin Wolf             goto fail;
1931cfcc4c62SKevin Wolf         }
1932cfcc4c62SKevin Wolf         buf += ret;
1933cfcc4c62SKevin Wolf         buflen -= ret;
19341a4828c7SKevin Wolf     }
1935cfcc4c62SKevin Wolf 
193675bab85cSKevin Wolf     /* Keep unknown header extensions */
193775bab85cSKevin Wolf     QLIST_FOREACH(uext, &s->unknown_header_ext, next) {
193875bab85cSKevin Wolf         ret = header_ext_add(buf, uext->magic, uext->data, uext->len, buflen);
193975bab85cSKevin Wolf         if (ret < 0) {
194075bab85cSKevin Wolf             goto fail;
194175bab85cSKevin Wolf         }
194275bab85cSKevin Wolf 
194375bab85cSKevin Wolf         buf += ret;
194475bab85cSKevin Wolf         buflen -= ret;
194575bab85cSKevin Wolf     }
194675bab85cSKevin Wolf 
1947e24e49e6SKevin Wolf     /* End of header extensions */
1948e24e49e6SKevin Wolf     ret = header_ext_add(buf, QCOW2_EXT_MAGIC_END, NULL, 0, buflen);
1949756e6736SKevin Wolf     if (ret < 0) {
1950756e6736SKevin Wolf         goto fail;
1951756e6736SKevin Wolf     }
1952756e6736SKevin Wolf 
1953e24e49e6SKevin Wolf     buf += ret;
1954e24e49e6SKevin Wolf     buflen -= ret;
1955e24e49e6SKevin Wolf 
1956e24e49e6SKevin Wolf     /* Backing file name */
1957e4603fe1SKevin Wolf     if (s->image_backing_file) {
1958e4603fe1SKevin Wolf         size_t backing_file_len = strlen(s->image_backing_file);
1959e24e49e6SKevin Wolf 
1960e24e49e6SKevin Wolf         if (buflen < backing_file_len) {
1961e24e49e6SKevin Wolf             ret = -ENOSPC;
1962e24e49e6SKevin Wolf             goto fail;
1963e24e49e6SKevin Wolf         }
1964e24e49e6SKevin Wolf 
196500ea1881SJim Meyering         /* Using strncpy is ok here, since buf is not NUL-terminated. */
1966e4603fe1SKevin Wolf         strncpy(buf, s->image_backing_file, buflen);
1967e24e49e6SKevin Wolf 
1968e24e49e6SKevin Wolf         header->backing_file_offset = cpu_to_be64(buf - ((char*) header));
1969e24e49e6SKevin Wolf         header->backing_file_size   = cpu_to_be32(backing_file_len);
1970e24e49e6SKevin Wolf     }
1971e24e49e6SKevin Wolf 
1972e24e49e6SKevin Wolf     /* Write the new header */
19739a4f4c31SKevin Wolf     ret = bdrv_pwrite(bs->file->bs, 0, header, s->cluster_size);
1974756e6736SKevin Wolf     if (ret < 0) {
1975756e6736SKevin Wolf         goto fail;
1976756e6736SKevin Wolf     }
1977756e6736SKevin Wolf 
1978756e6736SKevin Wolf     ret = 0;
1979756e6736SKevin Wolf fail:
1980e24e49e6SKevin Wolf     qemu_vfree(header);
1981756e6736SKevin Wolf     return ret;
1982756e6736SKevin Wolf }
1983756e6736SKevin Wolf 
1984756e6736SKevin Wolf static int qcow2_change_backing_file(BlockDriverState *bs,
1985756e6736SKevin Wolf     const char *backing_file, const char *backing_fmt)
1986756e6736SKevin Wolf {
1987ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
1988e4603fe1SKevin Wolf 
1989e24e49e6SKevin Wolf     pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
1990e24e49e6SKevin Wolf     pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
1991e24e49e6SKevin Wolf 
1992e4603fe1SKevin Wolf     g_free(s->image_backing_file);
1993e4603fe1SKevin Wolf     g_free(s->image_backing_format);
1994e4603fe1SKevin Wolf 
1995e4603fe1SKevin Wolf     s->image_backing_file = backing_file ? g_strdup(bs->backing_file) : NULL;
1996e4603fe1SKevin Wolf     s->image_backing_format = backing_fmt ? g_strdup(bs->backing_format) : NULL;
1997e4603fe1SKevin Wolf 
1998e24e49e6SKevin Wolf     return qcow2_update_header(bs);
1999756e6736SKevin Wolf }
2000756e6736SKevin Wolf 
2001a35e1c17SKevin Wolf static int preallocate(BlockDriverState *bs)
2002a35e1c17SKevin Wolf {
2003a35e1c17SKevin Wolf     uint64_t nb_sectors;
2004a35e1c17SKevin Wolf     uint64_t offset;
2005060bee89SKevin Wolf     uint64_t host_offset = 0;
2006a35e1c17SKevin Wolf     int num;
2007148da7eaSKevin Wolf     int ret;
2008f50f88b9SKevin Wolf     QCowL2Meta *meta;
2009a35e1c17SKevin Wolf 
201057322b78SMarkus Armbruster     nb_sectors = bdrv_nb_sectors(bs);
2011a35e1c17SKevin Wolf     offset = 0;
2012a35e1c17SKevin Wolf 
2013a35e1c17SKevin Wolf     while (nb_sectors) {
20147c2bbf4aSHu Tao         num = MIN(nb_sectors, INT_MAX >> BDRV_SECTOR_BITS);
201516f0587eSHu Tao         ret = qcow2_alloc_cluster_offset(bs, offset, &num,
2016060bee89SKevin Wolf                                          &host_offset, &meta);
2017148da7eaSKevin Wolf         if (ret < 0) {
201819dbcbf7SKevin Wolf             return ret;
2019a35e1c17SKevin Wolf         }
2020a35e1c17SKevin Wolf 
2021c792707fSStefan Hajnoczi         while (meta) {
2022c792707fSStefan Hajnoczi             QCowL2Meta *next = meta->next;
2023c792707fSStefan Hajnoczi 
2024f50f88b9SKevin Wolf             ret = qcow2_alloc_cluster_link_l2(bs, meta);
202519dbcbf7SKevin Wolf             if (ret < 0) {
20267c2bbf4aSHu Tao                 qcow2_free_any_clusters(bs, meta->alloc_offset,
20277c2bbf4aSHu Tao                                         meta->nb_clusters, QCOW2_DISCARD_NEVER);
202819dbcbf7SKevin Wolf                 return ret;
2029a35e1c17SKevin Wolf             }
2030a35e1c17SKevin Wolf 
20317c2bbf4aSHu Tao             /* There are no dependent requests, but we need to remove our
20327c2bbf4aSHu Tao              * request from the list of in-flight requests */
20334e95314eSKevin Wolf             QLIST_REMOVE(meta, next_in_flight);
2034c792707fSStefan Hajnoczi 
2035c792707fSStefan Hajnoczi             g_free(meta);
2036c792707fSStefan Hajnoczi             meta = next;
2037f50f88b9SKevin Wolf         }
2038f214978aSKevin Wolf 
2039a35e1c17SKevin Wolf         /* TODO Preallocate data if requested */
2040a35e1c17SKevin Wolf 
2041a35e1c17SKevin Wolf         nb_sectors -= num;
20427c2bbf4aSHu Tao         offset += num << BDRV_SECTOR_BITS;
2043a35e1c17SKevin Wolf     }
2044a35e1c17SKevin Wolf 
2045a35e1c17SKevin Wolf     /*
2046a35e1c17SKevin Wolf      * It is expected that the image file is large enough to actually contain
2047a35e1c17SKevin Wolf      * all of the allocated clusters (otherwise we get failing reads after
2048a35e1c17SKevin Wolf      * EOF). Extend the image to the last allocated sector.
2049a35e1c17SKevin Wolf      */
2050060bee89SKevin Wolf     if (host_offset != 0) {
20517c2bbf4aSHu Tao         uint8_t buf[BDRV_SECTOR_SIZE];
20527c2bbf4aSHu Tao         memset(buf, 0, BDRV_SECTOR_SIZE);
20539a4f4c31SKevin Wolf         ret = bdrv_write(bs->file->bs,
20549a4f4c31SKevin Wolf                          (host_offset >> BDRV_SECTOR_BITS) + num - 1,
20557c2bbf4aSHu Tao                          buf, 1);
205619dbcbf7SKevin Wolf         if (ret < 0) {
205719dbcbf7SKevin Wolf             return ret;
205819dbcbf7SKevin Wolf         }
2059a35e1c17SKevin Wolf     }
2060a35e1c17SKevin Wolf 
2061a35e1c17SKevin Wolf     return 0;
2062a35e1c17SKevin Wolf }
2063a35e1c17SKevin Wolf 
20647c80ab3fSJes Sorensen static int qcow2_create2(const char *filename, int64_t total_size,
2065a9420734SKevin Wolf                          const char *backing_file, const char *backing_format,
2066ffeaac9bSHu Tao                          int flags, size_t cluster_size, PreallocMode prealloc,
2067bd4b167fSMax Reitz                          QemuOpts *opts, int version, int refcount_order,
20683ef6c40aSMax Reitz                          Error **errp)
2069a9420734SKevin Wolf {
2070a9420734SKevin Wolf     int cluster_bits;
2071e6641719SMax Reitz     QDict *options;
2072e6641719SMax Reitz 
2073e6641719SMax Reitz     /* Calculate cluster_bits */
2074786a4ea8SStefan Hajnoczi     cluster_bits = ctz32(cluster_size);
2075a9420734SKevin Wolf     if (cluster_bits < MIN_CLUSTER_BITS || cluster_bits > MAX_CLUSTER_BITS ||
2076a9420734SKevin Wolf         (1 << cluster_bits) != cluster_size)
2077a9420734SKevin Wolf     {
20783ef6c40aSMax Reitz         error_setg(errp, "Cluster size must be a power of two between %d and "
20793ef6c40aSMax Reitz                    "%dk", 1 << MIN_CLUSTER_BITS, 1 << (MAX_CLUSTER_BITS - 10));
2080a9420734SKevin Wolf         return -EINVAL;
2081a9420734SKevin Wolf     }
2082a9420734SKevin Wolf 
2083a9420734SKevin Wolf     /*
2084a9420734SKevin Wolf      * Open the image file and write a minimal qcow2 header.
2085a9420734SKevin Wolf      *
2086a9420734SKevin Wolf      * We keep things simple and start with a zero-sized image. We also
2087a9420734SKevin Wolf      * do without refcount blocks or a L1 table for now. We'll fix the
2088a9420734SKevin Wolf      * inconsistency later.
2089a9420734SKevin Wolf      *
2090a9420734SKevin Wolf      * We do need a refcount table because growing the refcount table means
2091a9420734SKevin Wolf      * allocating two new refcount blocks - the seconds of which would be at
2092a9420734SKevin Wolf      * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
2093a9420734SKevin Wolf      * size for any qcow2 image.
2094a9420734SKevin Wolf      */
2095a9420734SKevin Wolf     BlockDriverState* bs;
2096f8413b3cSKevin Wolf     QCowHeader *header;
2097b106ad91SKevin Wolf     uint64_t* refcount_table;
20983ef6c40aSMax Reitz     Error *local_err = NULL;
2099a9420734SKevin Wolf     int ret;
2100a9420734SKevin Wolf 
21010e4271b7SHu Tao     if (prealloc == PREALLOC_MODE_FULL || prealloc == PREALLOC_MODE_FALLOC) {
2102bd4b167fSMax Reitz         /* Note: The following calculation does not need to be exact; if it is a
2103bd4b167fSMax Reitz          * bit off, either some bytes will be "leaked" (which is fine) or we
2104bd4b167fSMax Reitz          * will need to increase the file size by some bytes (which is fine,
2105bd4b167fSMax Reitz          * too, as long as the bulk is allocated here). Therefore, using
2106bd4b167fSMax Reitz          * floating point arithmetic is fine. */
21070e4271b7SHu Tao         int64_t meta_size = 0;
21080e4271b7SHu Tao         uint64_t nreftablee, nrefblocke, nl1e, nl2e;
21090e4271b7SHu Tao         int64_t aligned_total_size = align_offset(total_size, cluster_size);
2110bd4b167fSMax Reitz         int refblock_bits, refblock_size;
2111bd4b167fSMax Reitz         /* refcount entry size in bytes */
2112bd4b167fSMax Reitz         double rces = (1 << refcount_order) / 8.;
2113bd4b167fSMax Reitz 
2114bd4b167fSMax Reitz         /* see qcow2_open() */
2115bd4b167fSMax Reitz         refblock_bits = cluster_bits - (refcount_order - 3);
2116bd4b167fSMax Reitz         refblock_size = 1 << refblock_bits;
21170e4271b7SHu Tao 
21180e4271b7SHu Tao         /* header: 1 cluster */
21190e4271b7SHu Tao         meta_size += cluster_size;
21200e4271b7SHu Tao 
21210e4271b7SHu Tao         /* total size of L2 tables */
21220e4271b7SHu Tao         nl2e = aligned_total_size / cluster_size;
21230e4271b7SHu Tao         nl2e = align_offset(nl2e, cluster_size / sizeof(uint64_t));
21240e4271b7SHu Tao         meta_size += nl2e * sizeof(uint64_t);
21250e4271b7SHu Tao 
21260e4271b7SHu Tao         /* total size of L1 tables */
21270e4271b7SHu Tao         nl1e = nl2e * sizeof(uint64_t) / cluster_size;
21280e4271b7SHu Tao         nl1e = align_offset(nl1e, cluster_size / sizeof(uint64_t));
21290e4271b7SHu Tao         meta_size += nl1e * sizeof(uint64_t);
21300e4271b7SHu Tao 
21310e4271b7SHu Tao         /* total size of refcount blocks
21320e4271b7SHu Tao          *
21330e4271b7SHu Tao          * note: every host cluster is reference-counted, including metadata
21340e4271b7SHu Tao          * (even refcount blocks are recursively included).
21350e4271b7SHu Tao          * Let:
21360e4271b7SHu Tao          *   a = total_size (this is the guest disk size)
21370e4271b7SHu Tao          *   m = meta size not including refcount blocks and refcount tables
21380e4271b7SHu Tao          *   c = cluster size
21390e4271b7SHu Tao          *   y1 = number of refcount blocks entries
21400e4271b7SHu Tao          *   y2 = meta size including everything
2141bd4b167fSMax Reitz          *   rces = refcount entry size in bytes
21420e4271b7SHu Tao          * then,
21430e4271b7SHu Tao          *   y1 = (y2 + a)/c
2144bd4b167fSMax Reitz          *   y2 = y1 * rces + y1 * rces * sizeof(u64) / c + m
21450e4271b7SHu Tao          * we can get y1:
2146bd4b167fSMax Reitz          *   y1 = (a + m) / (c - rces - rces * sizeof(u64) / c)
21470e4271b7SHu Tao          */
2148bd4b167fSMax Reitz         nrefblocke = (aligned_total_size + meta_size + cluster_size)
2149bd4b167fSMax Reitz                    / (cluster_size - rces - rces * sizeof(uint64_t)
2150bd4b167fSMax Reitz                                                  / cluster_size);
2151bd4b167fSMax Reitz         meta_size += DIV_ROUND_UP(nrefblocke, refblock_size) * cluster_size;
21520e4271b7SHu Tao 
21530e4271b7SHu Tao         /* total size of refcount tables */
2154bd4b167fSMax Reitz         nreftablee = nrefblocke / refblock_size;
21550e4271b7SHu Tao         nreftablee = align_offset(nreftablee, cluster_size / sizeof(uint64_t));
21560e4271b7SHu Tao         meta_size += nreftablee * sizeof(uint64_t);
21570e4271b7SHu Tao 
21580e4271b7SHu Tao         qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
215939101f25SMarkus Armbruster                             aligned_total_size + meta_size, &error_abort);
2160f43e47dbSMarkus Armbruster         qemu_opt_set(opts, BLOCK_OPT_PREALLOC, PreallocMode_lookup[prealloc],
2161f43e47dbSMarkus Armbruster                      &error_abort);
21620e4271b7SHu Tao     }
21630e4271b7SHu Tao 
2164c282e1fdSChunyan Liu     ret = bdrv_create_file(filename, opts, &local_err);
2165a9420734SKevin Wolf     if (ret < 0) {
21663ef6c40aSMax Reitz         error_propagate(errp, local_err);
2167a9420734SKevin Wolf         return ret;
2168a9420734SKevin Wolf     }
2169a9420734SKevin Wolf 
21702e40134bSMax Reitz     bs = NULL;
21712e40134bSMax Reitz     ret = bdrv_open(&bs, filename, NULL, NULL, BDRV_O_RDWR | BDRV_O_PROTOCOL,
21726ebf9aa2SMax Reitz                     &local_err);
2173a9420734SKevin Wolf     if (ret < 0) {
21743ef6c40aSMax Reitz         error_propagate(errp, local_err);
2175a9420734SKevin Wolf         return ret;
2176a9420734SKevin Wolf     }
2177a9420734SKevin Wolf 
2178a9420734SKevin Wolf     /* Write the header */
2179f8413b3cSKevin Wolf     QEMU_BUILD_BUG_ON((1 << MIN_CLUSTER_BITS) < sizeof(*header));
2180f8413b3cSKevin Wolf     header = g_malloc0(cluster_size);
2181f8413b3cSKevin Wolf     *header = (QCowHeader) {
2182f8413b3cSKevin Wolf         .magic                      = cpu_to_be32(QCOW_MAGIC),
2183f8413b3cSKevin Wolf         .version                    = cpu_to_be32(version),
2184f8413b3cSKevin Wolf         .cluster_bits               = cpu_to_be32(cluster_bits),
2185f8413b3cSKevin Wolf         .size                       = cpu_to_be64(0),
2186f8413b3cSKevin Wolf         .l1_table_offset            = cpu_to_be64(0),
2187f8413b3cSKevin Wolf         .l1_size                    = cpu_to_be32(0),
2188f8413b3cSKevin Wolf         .refcount_table_offset      = cpu_to_be64(cluster_size),
2189f8413b3cSKevin Wolf         .refcount_table_clusters    = cpu_to_be32(1),
2190bd4b167fSMax Reitz         .refcount_order             = cpu_to_be32(refcount_order),
2191f8413b3cSKevin Wolf         .header_length              = cpu_to_be32(sizeof(*header)),
2192f8413b3cSKevin Wolf     };
2193a9420734SKevin Wolf 
2194a9420734SKevin Wolf     if (flags & BLOCK_FLAG_ENCRYPT) {
2195f8413b3cSKevin Wolf         header->crypt_method = cpu_to_be32(QCOW_CRYPT_AES);
2196a9420734SKevin Wolf     } else {
2197f8413b3cSKevin Wolf         header->crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
2198a9420734SKevin Wolf     }
2199a9420734SKevin Wolf 
2200bfe8043eSStefan Hajnoczi     if (flags & BLOCK_FLAG_LAZY_REFCOUNTS) {
2201f8413b3cSKevin Wolf         header->compatible_features |=
2202bfe8043eSStefan Hajnoczi             cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS);
2203bfe8043eSStefan Hajnoczi     }
2204bfe8043eSStefan Hajnoczi 
2205f8413b3cSKevin Wolf     ret = bdrv_pwrite(bs, 0, header, cluster_size);
2206f8413b3cSKevin Wolf     g_free(header);
2207a9420734SKevin Wolf     if (ret < 0) {
22083ef6c40aSMax Reitz         error_setg_errno(errp, -ret, "Could not write qcow2 header");
2209a9420734SKevin Wolf         goto out;
2210a9420734SKevin Wolf     }
2211a9420734SKevin Wolf 
2212b106ad91SKevin Wolf     /* Write a refcount table with one refcount block */
2213b106ad91SKevin Wolf     refcount_table = g_malloc0(2 * cluster_size);
2214b106ad91SKevin Wolf     refcount_table[0] = cpu_to_be64(2 * cluster_size);
2215b106ad91SKevin Wolf     ret = bdrv_pwrite(bs, cluster_size, refcount_table, 2 * cluster_size);
22167267c094SAnthony Liguori     g_free(refcount_table);
2217a9420734SKevin Wolf 
2218a9420734SKevin Wolf     if (ret < 0) {
22193ef6c40aSMax Reitz         error_setg_errno(errp, -ret, "Could not write refcount table");
2220a9420734SKevin Wolf         goto out;
2221a9420734SKevin Wolf     }
2222a9420734SKevin Wolf 
2223f67503e5SMax Reitz     bdrv_unref(bs);
2224f67503e5SMax Reitz     bs = NULL;
2225a9420734SKevin Wolf 
2226a9420734SKevin Wolf     /*
2227a9420734SKevin Wolf      * And now open the image and make it consistent first (i.e. increase the
2228a9420734SKevin Wolf      * refcount of the cluster that is occupied by the header and the refcount
2229a9420734SKevin Wolf      * table)
2230a9420734SKevin Wolf      */
2231e6641719SMax Reitz     options = qdict_new();
2232e6641719SMax Reitz     qdict_put(options, "driver", qstring_from_str("qcow2"));
2233e6641719SMax Reitz     ret = bdrv_open(&bs, filename, NULL, options,
2234ef810437SMax Reitz                     BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_NO_FLUSH,
22356ebf9aa2SMax Reitz                     &local_err);
2236a9420734SKevin Wolf     if (ret < 0) {
22373ef6c40aSMax Reitz         error_propagate(errp, local_err);
2238a9420734SKevin Wolf         goto out;
2239a9420734SKevin Wolf     }
2240a9420734SKevin Wolf 
2241b106ad91SKevin Wolf     ret = qcow2_alloc_clusters(bs, 3 * cluster_size);
2242a9420734SKevin Wolf     if (ret < 0) {
22433ef6c40aSMax Reitz         error_setg_errno(errp, -ret, "Could not allocate clusters for qcow2 "
22443ef6c40aSMax Reitz                          "header and refcount table");
2245a9420734SKevin Wolf         goto out;
2246a9420734SKevin Wolf 
2247a9420734SKevin Wolf     } else if (ret != 0) {
2248a9420734SKevin Wolf         error_report("Huh, first cluster in empty image is already in use?");
2249a9420734SKevin Wolf         abort();
2250a9420734SKevin Wolf     }
2251a9420734SKevin Wolf 
2252b527c9b3SKevin Wolf     /* Create a full header (including things like feature table) */
2253b527c9b3SKevin Wolf     ret = qcow2_update_header(bs);
2254b527c9b3SKevin Wolf     if (ret < 0) {
2255b527c9b3SKevin Wolf         error_setg_errno(errp, -ret, "Could not update qcow2 header");
2256b527c9b3SKevin Wolf         goto out;
2257b527c9b3SKevin Wolf     }
2258b527c9b3SKevin Wolf 
2259a9420734SKevin Wolf     /* Okay, now that we have a valid image, let's give it the right size */
2260180e9526SHu Tao     ret = bdrv_truncate(bs, total_size);
2261a9420734SKevin Wolf     if (ret < 0) {
22623ef6c40aSMax Reitz         error_setg_errno(errp, -ret, "Could not resize image");
2263a9420734SKevin Wolf         goto out;
2264a9420734SKevin Wolf     }
2265a9420734SKevin Wolf 
2266a9420734SKevin Wolf     /* Want a backing file? There you go.*/
2267a9420734SKevin Wolf     if (backing_file) {
2268a9420734SKevin Wolf         ret = bdrv_change_backing_file(bs, backing_file, backing_format);
2269a9420734SKevin Wolf         if (ret < 0) {
22703ef6c40aSMax Reitz             error_setg_errno(errp, -ret, "Could not assign backing file '%s' "
22713ef6c40aSMax Reitz                              "with format '%s'", backing_file, backing_format);
2272a9420734SKevin Wolf             goto out;
2273a9420734SKevin Wolf         }
2274a9420734SKevin Wolf     }
2275a9420734SKevin Wolf 
2276a9420734SKevin Wolf     /* And if we're supposed to preallocate metadata, do that now */
22770e4271b7SHu Tao     if (prealloc != PREALLOC_MODE_OFF) {
2278ff99129aSKevin Wolf         BDRVQcow2State *s = bs->opaque;
227915552c4aSZhi Yong Wu         qemu_co_mutex_lock(&s->lock);
2280a9420734SKevin Wolf         ret = preallocate(bs);
228115552c4aSZhi Yong Wu         qemu_co_mutex_unlock(&s->lock);
2282a9420734SKevin Wolf         if (ret < 0) {
22833ef6c40aSMax Reitz             error_setg_errno(errp, -ret, "Could not preallocate metadata");
2284a9420734SKevin Wolf             goto out;
2285a9420734SKevin Wolf         }
2286a9420734SKevin Wolf     }
2287a9420734SKevin Wolf 
2288f67503e5SMax Reitz     bdrv_unref(bs);
2289f67503e5SMax Reitz     bs = NULL;
2290ba2ab2f2SMax Reitz 
2291ba2ab2f2SMax Reitz     /* Reopen the image without BDRV_O_NO_FLUSH to flush it before returning */
2292e6641719SMax Reitz     options = qdict_new();
2293e6641719SMax Reitz     qdict_put(options, "driver", qstring_from_str("qcow2"));
2294e6641719SMax Reitz     ret = bdrv_open(&bs, filename, NULL, options,
2295c9fbb99dSKevin Wolf                     BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_NO_BACKING,
22966ebf9aa2SMax Reitz                     &local_err);
229784d18f06SMarkus Armbruster     if (local_err) {
2298ba2ab2f2SMax Reitz         error_propagate(errp, local_err);
2299ba2ab2f2SMax Reitz         goto out;
2300ba2ab2f2SMax Reitz     }
2301ba2ab2f2SMax Reitz 
2302a9420734SKevin Wolf     ret = 0;
2303a9420734SKevin Wolf out:
2304f67503e5SMax Reitz     if (bs) {
23054f6fd349SFam Zheng         bdrv_unref(bs);
2306f67503e5SMax Reitz     }
2307a9420734SKevin Wolf     return ret;
2308a9420734SKevin Wolf }
2309de5f3f40SKevin Wolf 
23101bd0e2d1SChunyan Liu static int qcow2_create(const char *filename, QemuOpts *opts, Error **errp)
2311de5f3f40SKevin Wolf {
23121bd0e2d1SChunyan Liu     char *backing_file = NULL;
23131bd0e2d1SChunyan Liu     char *backing_fmt = NULL;
23141bd0e2d1SChunyan Liu     char *buf = NULL;
2315180e9526SHu Tao     uint64_t size = 0;
2316de5f3f40SKevin Wolf     int flags = 0;
231799cce9faSKevin Wolf     size_t cluster_size = DEFAULT_CLUSTER_SIZE;
2318ffeaac9bSHu Tao     PreallocMode prealloc;
23198ad1898cSKevin Wolf     int version = 3;
2320bd4b167fSMax Reitz     uint64_t refcount_bits = 16;
2321bd4b167fSMax Reitz     int refcount_order;
23223ef6c40aSMax Reitz     Error *local_err = NULL;
23233ef6c40aSMax Reitz     int ret;
2324de5f3f40SKevin Wolf 
2325de5f3f40SKevin Wolf     /* Read out options */
2326180e9526SHu Tao     size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
2327c2eb918eSHu Tao                     BDRV_SECTOR_SIZE);
23281bd0e2d1SChunyan Liu     backing_file = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
23291bd0e2d1SChunyan Liu     backing_fmt = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FMT);
23301bd0e2d1SChunyan Liu     if (qemu_opt_get_bool_del(opts, BLOCK_OPT_ENCRYPT, false)) {
23311bd0e2d1SChunyan Liu         flags |= BLOCK_FLAG_ENCRYPT;
2332de5f3f40SKevin Wolf     }
23331bd0e2d1SChunyan Liu     cluster_size = qemu_opt_get_size_del(opts, BLOCK_OPT_CLUSTER_SIZE,
23341bd0e2d1SChunyan Liu                                          DEFAULT_CLUSTER_SIZE);
23351bd0e2d1SChunyan Liu     buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
2336ffeaac9bSHu Tao     prealloc = qapi_enum_parse(PreallocMode_lookup, buf,
23377fb1cf16SEric Blake                                PREALLOC_MODE__MAX, PREALLOC_MODE_OFF,
2338ffeaac9bSHu Tao                                &local_err);
2339ffeaac9bSHu Tao     if (local_err) {
2340ffeaac9bSHu Tao         error_propagate(errp, local_err);
23411bd0e2d1SChunyan Liu         ret = -EINVAL;
23421bd0e2d1SChunyan Liu         goto finish;
2343de5f3f40SKevin Wolf     }
23441bd0e2d1SChunyan Liu     g_free(buf);
23451bd0e2d1SChunyan Liu     buf = qemu_opt_get_del(opts, BLOCK_OPT_COMPAT_LEVEL);
23461bd0e2d1SChunyan Liu     if (!buf) {
23479117b477SKevin Wolf         /* keep the default */
23481bd0e2d1SChunyan Liu     } else if (!strcmp(buf, "0.10")) {
23496744cbabSKevin Wolf         version = 2;
23501bd0e2d1SChunyan Liu     } else if (!strcmp(buf, "1.1")) {
23516744cbabSKevin Wolf         version = 3;
23526744cbabSKevin Wolf     } else {
23531bd0e2d1SChunyan Liu         error_setg(errp, "Invalid compatibility level: '%s'", buf);
23541bd0e2d1SChunyan Liu         ret = -EINVAL;
23551bd0e2d1SChunyan Liu         goto finish;
23566744cbabSKevin Wolf     }
23571bd0e2d1SChunyan Liu 
23581bd0e2d1SChunyan Liu     if (qemu_opt_get_bool_del(opts, BLOCK_OPT_LAZY_REFCOUNTS, false)) {
23591bd0e2d1SChunyan Liu         flags |= BLOCK_FLAG_LAZY_REFCOUNTS;
2360de5f3f40SKevin Wolf     }
2361de5f3f40SKevin Wolf 
2362ffeaac9bSHu Tao     if (backing_file && prealloc != PREALLOC_MODE_OFF) {
23633ef6c40aSMax Reitz         error_setg(errp, "Backing file and preallocation cannot be used at "
23643ef6c40aSMax Reitz                    "the same time");
23651bd0e2d1SChunyan Liu         ret = -EINVAL;
23661bd0e2d1SChunyan Liu         goto finish;
2367de5f3f40SKevin Wolf     }
2368de5f3f40SKevin Wolf 
2369bfe8043eSStefan Hajnoczi     if (version < 3 && (flags & BLOCK_FLAG_LAZY_REFCOUNTS)) {
23703ef6c40aSMax Reitz         error_setg(errp, "Lazy refcounts only supported with compatibility "
23713ef6c40aSMax Reitz                    "level 1.1 and above (use compat=1.1 or greater)");
23721bd0e2d1SChunyan Liu         ret = -EINVAL;
23731bd0e2d1SChunyan Liu         goto finish;
2374bfe8043eSStefan Hajnoczi     }
2375bfe8043eSStefan Hajnoczi 
237606d05fa7SMax Reitz     refcount_bits = qemu_opt_get_number_del(opts, BLOCK_OPT_REFCOUNT_BITS,
237706d05fa7SMax Reitz                                             refcount_bits);
237806d05fa7SMax Reitz     if (refcount_bits > 64 || !is_power_of_2(refcount_bits)) {
237906d05fa7SMax Reitz         error_setg(errp, "Refcount width must be a power of two and may not "
238006d05fa7SMax Reitz                    "exceed 64 bits");
238106d05fa7SMax Reitz         ret = -EINVAL;
238206d05fa7SMax Reitz         goto finish;
238306d05fa7SMax Reitz     }
238406d05fa7SMax Reitz 
2385bd4b167fSMax Reitz     if (version < 3 && refcount_bits != 16) {
2386bd4b167fSMax Reitz         error_setg(errp, "Different refcount widths than 16 bits require "
2387bd4b167fSMax Reitz                    "compatibility level 1.1 or above (use compat=1.1 or "
2388bd4b167fSMax Reitz                    "greater)");
2389bd4b167fSMax Reitz         ret = -EINVAL;
2390bd4b167fSMax Reitz         goto finish;
2391bd4b167fSMax Reitz     }
2392bd4b167fSMax Reitz 
2393786a4ea8SStefan Hajnoczi     refcount_order = ctz32(refcount_bits);
2394bd4b167fSMax Reitz 
2395180e9526SHu Tao     ret = qcow2_create2(filename, size, backing_file, backing_fmt, flags,
2396bd4b167fSMax Reitz                         cluster_size, prealloc, opts, version, refcount_order,
2397bd4b167fSMax Reitz                         &local_err);
239884d18f06SMarkus Armbruster     if (local_err) {
23993ef6c40aSMax Reitz         error_propagate(errp, local_err);
24003ef6c40aSMax Reitz     }
24011bd0e2d1SChunyan Liu 
24021bd0e2d1SChunyan Liu finish:
24031bd0e2d1SChunyan Liu     g_free(backing_file);
24041bd0e2d1SChunyan Liu     g_free(backing_fmt);
24051bd0e2d1SChunyan Liu     g_free(buf);
24063ef6c40aSMax Reitz     return ret;
2407de5f3f40SKevin Wolf }
2408de5f3f40SKevin Wolf 
2409621f0589SKevin Wolf static coroutine_fn int qcow2_co_write_zeroes(BlockDriverState *bs,
2410aa7bfbffSPeter Lieven     int64_t sector_num, int nb_sectors, BdrvRequestFlags flags)
2411621f0589SKevin Wolf {
2412621f0589SKevin Wolf     int ret;
2413ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
2414621f0589SKevin Wolf 
2415621f0589SKevin Wolf     /* Emulate misaligned zero writes */
2416621f0589SKevin Wolf     if (sector_num % s->cluster_sectors || nb_sectors % s->cluster_sectors) {
2417621f0589SKevin Wolf         return -ENOTSUP;
2418621f0589SKevin Wolf     }
2419621f0589SKevin Wolf 
2420621f0589SKevin Wolf     /* Whatever is left can use real zero clusters */
2421621f0589SKevin Wolf     qemu_co_mutex_lock(&s->lock);
2422621f0589SKevin Wolf     ret = qcow2_zero_clusters(bs, sector_num << BDRV_SECTOR_BITS,
2423621f0589SKevin Wolf         nb_sectors);
2424621f0589SKevin Wolf     qemu_co_mutex_unlock(&s->lock);
2425621f0589SKevin Wolf 
2426621f0589SKevin Wolf     return ret;
2427621f0589SKevin Wolf }
2428621f0589SKevin Wolf 
24296db39ae2SPaolo Bonzini static coroutine_fn int qcow2_co_discard(BlockDriverState *bs,
24306db39ae2SPaolo Bonzini     int64_t sector_num, int nb_sectors)
24315ea929e3SKevin Wolf {
24326db39ae2SPaolo Bonzini     int ret;
2433ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
24346db39ae2SPaolo Bonzini 
24356db39ae2SPaolo Bonzini     qemu_co_mutex_lock(&s->lock);
24366db39ae2SPaolo Bonzini     ret = qcow2_discard_clusters(bs, sector_num << BDRV_SECTOR_BITS,
2437808c4b6fSMax Reitz         nb_sectors, QCOW2_DISCARD_REQUEST, false);
24386db39ae2SPaolo Bonzini     qemu_co_mutex_unlock(&s->lock);
24396db39ae2SPaolo Bonzini     return ret;
24405ea929e3SKevin Wolf }
24415ea929e3SKevin Wolf 
2442419b19d9SStefan Hajnoczi static int qcow2_truncate(BlockDriverState *bs, int64_t offset)
2443419b19d9SStefan Hajnoczi {
2444ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
24452cf7cfa1SKevin Wolf     int64_t new_l1_size;
24462cf7cfa1SKevin Wolf     int ret;
2447419b19d9SStefan Hajnoczi 
2448419b19d9SStefan Hajnoczi     if (offset & 511) {
2449259b2173SKevin Wolf         error_report("The new size must be a multiple of 512");
2450419b19d9SStefan Hajnoczi         return -EINVAL;
2451419b19d9SStefan Hajnoczi     }
2452419b19d9SStefan Hajnoczi 
2453419b19d9SStefan Hajnoczi     /* cannot proceed if image has snapshots */
2454419b19d9SStefan Hajnoczi     if (s->nb_snapshots) {
2455259b2173SKevin Wolf         error_report("Can't resize an image which has snapshots");
2456419b19d9SStefan Hajnoczi         return -ENOTSUP;
2457419b19d9SStefan Hajnoczi     }
2458419b19d9SStefan Hajnoczi 
2459419b19d9SStefan Hajnoczi     /* shrinking is currently not supported */
2460419b19d9SStefan Hajnoczi     if (offset < bs->total_sectors * 512) {
2461259b2173SKevin Wolf         error_report("qcow2 doesn't support shrinking images yet");
2462419b19d9SStefan Hajnoczi         return -ENOTSUP;
2463419b19d9SStefan Hajnoczi     }
2464419b19d9SStefan Hajnoczi 
2465419b19d9SStefan Hajnoczi     new_l1_size = size_to_l1(s, offset);
246672893756SStefan Hajnoczi     ret = qcow2_grow_l1_table(bs, new_l1_size, true);
2467419b19d9SStefan Hajnoczi     if (ret < 0) {
2468419b19d9SStefan Hajnoczi         return ret;
2469419b19d9SStefan Hajnoczi     }
2470419b19d9SStefan Hajnoczi 
2471419b19d9SStefan Hajnoczi     /* write updated header.size */
2472419b19d9SStefan Hajnoczi     offset = cpu_to_be64(offset);
24739a4f4c31SKevin Wolf     ret = bdrv_pwrite_sync(bs->file->bs, offsetof(QCowHeader, size),
2474419b19d9SStefan Hajnoczi                            &offset, sizeof(uint64_t));
2475419b19d9SStefan Hajnoczi     if (ret < 0) {
2476419b19d9SStefan Hajnoczi         return ret;
2477419b19d9SStefan Hajnoczi     }
2478419b19d9SStefan Hajnoczi 
2479419b19d9SStefan Hajnoczi     s->l1_vm_state_index = new_l1_size;
2480419b19d9SStefan Hajnoczi     return 0;
2481419b19d9SStefan Hajnoczi }
2482419b19d9SStefan Hajnoczi 
248320d97356SBlue Swirl /* XXX: put compressed sectors first, then all the cluster aligned
248420d97356SBlue Swirl    tables to avoid losing bytes in alignment */
24857c80ab3fSJes Sorensen static int qcow2_write_compressed(BlockDriverState *bs, int64_t sector_num,
248620d97356SBlue Swirl                                   const uint8_t *buf, int nb_sectors)
248720d97356SBlue Swirl {
2488ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
248920d97356SBlue Swirl     z_stream strm;
249020d97356SBlue Swirl     int ret, out_len;
249120d97356SBlue Swirl     uint8_t *out_buf;
249220d97356SBlue Swirl     uint64_t cluster_offset;
249320d97356SBlue Swirl 
249420d97356SBlue Swirl     if (nb_sectors == 0) {
249520d97356SBlue Swirl         /* align end of file to a sector boundary to ease reading with
249620d97356SBlue Swirl            sector based I/Os */
24979a4f4c31SKevin Wolf         cluster_offset = bdrv_getlength(bs->file->bs);
24989a4f4c31SKevin Wolf         return bdrv_truncate(bs->file->bs, cluster_offset);
249920d97356SBlue Swirl     }
250020d97356SBlue Swirl 
2501f4d38befSStefan Hajnoczi     if (nb_sectors != s->cluster_sectors) {
2502f4d38befSStefan Hajnoczi         ret = -EINVAL;
2503f4d38befSStefan Hajnoczi 
2504f4d38befSStefan Hajnoczi         /* Zero-pad last write if image size is not cluster aligned */
2505f4d38befSStefan Hajnoczi         if (sector_num + nb_sectors == bs->total_sectors &&
2506f4d38befSStefan Hajnoczi             nb_sectors < s->cluster_sectors) {
2507f4d38befSStefan Hajnoczi             uint8_t *pad_buf = qemu_blockalign(bs, s->cluster_size);
2508f4d38befSStefan Hajnoczi             memset(pad_buf, 0, s->cluster_size);
2509f4d38befSStefan Hajnoczi             memcpy(pad_buf, buf, nb_sectors * BDRV_SECTOR_SIZE);
2510f4d38befSStefan Hajnoczi             ret = qcow2_write_compressed(bs, sector_num,
2511f4d38befSStefan Hajnoczi                                          pad_buf, s->cluster_sectors);
2512f4d38befSStefan Hajnoczi             qemu_vfree(pad_buf);
2513f4d38befSStefan Hajnoczi         }
2514f4d38befSStefan Hajnoczi         return ret;
2515f4d38befSStefan Hajnoczi     }
251620d97356SBlue Swirl 
25177267c094SAnthony Liguori     out_buf = g_malloc(s->cluster_size + (s->cluster_size / 1000) + 128);
251820d97356SBlue Swirl 
251920d97356SBlue Swirl     /* best compression, small window, no zlib header */
252020d97356SBlue Swirl     memset(&strm, 0, sizeof(strm));
252120d97356SBlue Swirl     ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
252220d97356SBlue Swirl                        Z_DEFLATED, -12,
252320d97356SBlue Swirl                        9, Z_DEFAULT_STRATEGY);
252420d97356SBlue Swirl     if (ret != 0) {
25258f1efd00SKevin Wolf         ret = -EINVAL;
25268f1efd00SKevin Wolf         goto fail;
252720d97356SBlue Swirl     }
252820d97356SBlue Swirl 
252920d97356SBlue Swirl     strm.avail_in = s->cluster_size;
253020d97356SBlue Swirl     strm.next_in = (uint8_t *)buf;
253120d97356SBlue Swirl     strm.avail_out = s->cluster_size;
253220d97356SBlue Swirl     strm.next_out = out_buf;
253320d97356SBlue Swirl 
253420d97356SBlue Swirl     ret = deflate(&strm, Z_FINISH);
253520d97356SBlue Swirl     if (ret != Z_STREAM_END && ret != Z_OK) {
253620d97356SBlue Swirl         deflateEnd(&strm);
25378f1efd00SKevin Wolf         ret = -EINVAL;
25388f1efd00SKevin Wolf         goto fail;
253920d97356SBlue Swirl     }
254020d97356SBlue Swirl     out_len = strm.next_out - out_buf;
254120d97356SBlue Swirl 
254220d97356SBlue Swirl     deflateEnd(&strm);
254320d97356SBlue Swirl 
254420d97356SBlue Swirl     if (ret != Z_STREAM_END || out_len >= s->cluster_size) {
254520d97356SBlue Swirl         /* could not compress: write normal cluster */
25468f1efd00SKevin Wolf         ret = bdrv_write(bs, sector_num, buf, s->cluster_sectors);
25478f1efd00SKevin Wolf         if (ret < 0) {
25488f1efd00SKevin Wolf             goto fail;
25498f1efd00SKevin Wolf         }
255020d97356SBlue Swirl     } else {
255120d97356SBlue Swirl         cluster_offset = qcow2_alloc_compressed_cluster_offset(bs,
255220d97356SBlue Swirl             sector_num << 9, out_len);
25538f1efd00SKevin Wolf         if (!cluster_offset) {
25548f1efd00SKevin Wolf             ret = -EIO;
25558f1efd00SKevin Wolf             goto fail;
25568f1efd00SKevin Wolf         }
255720d97356SBlue Swirl         cluster_offset &= s->cluster_offset_mask;
2558cf93980eSMax Reitz 
2559231bb267SMax Reitz         ret = qcow2_pre_write_overlap_check(bs, 0, cluster_offset, out_len);
2560cf93980eSMax Reitz         if (ret < 0) {
2561cf93980eSMax Reitz             goto fail;
2562cf93980eSMax Reitz         }
2563cf93980eSMax Reitz 
256466f82ceeSKevin Wolf         BLKDBG_EVENT(bs->file, BLKDBG_WRITE_COMPRESSED);
25659a4f4c31SKevin Wolf         ret = bdrv_pwrite(bs->file->bs, cluster_offset, out_buf, out_len);
25668f1efd00SKevin Wolf         if (ret < 0) {
25678f1efd00SKevin Wolf             goto fail;
256820d97356SBlue Swirl         }
256920d97356SBlue Swirl     }
257020d97356SBlue Swirl 
25718f1efd00SKevin Wolf     ret = 0;
25728f1efd00SKevin Wolf fail:
25737267c094SAnthony Liguori     g_free(out_buf);
25748f1efd00SKevin Wolf     return ret;
257520d97356SBlue Swirl }
257620d97356SBlue Swirl 
257794054183SMax Reitz static int make_completely_empty(BlockDriverState *bs)
257894054183SMax Reitz {
2579ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
258094054183SMax Reitz     int ret, l1_clusters;
258194054183SMax Reitz     int64_t offset;
258294054183SMax Reitz     uint64_t *new_reftable = NULL;
258394054183SMax Reitz     uint64_t rt_entry, l1_size2;
258494054183SMax Reitz     struct {
258594054183SMax Reitz         uint64_t l1_offset;
258694054183SMax Reitz         uint64_t reftable_offset;
258794054183SMax Reitz         uint32_t reftable_clusters;
258894054183SMax Reitz     } QEMU_PACKED l1_ofs_rt_ofs_cls;
258994054183SMax Reitz 
259094054183SMax Reitz     ret = qcow2_cache_empty(bs, s->l2_table_cache);
259194054183SMax Reitz     if (ret < 0) {
259294054183SMax Reitz         goto fail;
259394054183SMax Reitz     }
259494054183SMax Reitz 
259594054183SMax Reitz     ret = qcow2_cache_empty(bs, s->refcount_block_cache);
259694054183SMax Reitz     if (ret < 0) {
259794054183SMax Reitz         goto fail;
259894054183SMax Reitz     }
259994054183SMax Reitz 
260094054183SMax Reitz     /* Refcounts will be broken utterly */
260194054183SMax Reitz     ret = qcow2_mark_dirty(bs);
260294054183SMax Reitz     if (ret < 0) {
260394054183SMax Reitz         goto fail;
260494054183SMax Reitz     }
260594054183SMax Reitz 
260694054183SMax Reitz     BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
260794054183SMax Reitz 
260894054183SMax Reitz     l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / sizeof(uint64_t));
260994054183SMax Reitz     l1_size2 = (uint64_t)s->l1_size * sizeof(uint64_t);
261094054183SMax Reitz 
261194054183SMax Reitz     /* After this call, neither the in-memory nor the on-disk refcount
261294054183SMax Reitz      * information accurately describe the actual references */
261394054183SMax Reitz 
26149a4f4c31SKevin Wolf     ret = bdrv_write_zeroes(bs->file->bs, s->l1_table_offset / BDRV_SECTOR_SIZE,
261594054183SMax Reitz                             l1_clusters * s->cluster_sectors, 0);
261694054183SMax Reitz     if (ret < 0) {
261794054183SMax Reitz         goto fail_broken_refcounts;
261894054183SMax Reitz     }
261994054183SMax Reitz     memset(s->l1_table, 0, l1_size2);
262094054183SMax Reitz 
262194054183SMax Reitz     BLKDBG_EVENT(bs->file, BLKDBG_EMPTY_IMAGE_PREPARE);
262294054183SMax Reitz 
262394054183SMax Reitz     /* Overwrite enough clusters at the beginning of the sectors to place
262494054183SMax Reitz      * the refcount table, a refcount block and the L1 table in; this may
262594054183SMax Reitz      * overwrite parts of the existing refcount and L1 table, which is not
262694054183SMax Reitz      * an issue because the dirty flag is set, complete data loss is in fact
262794054183SMax Reitz      * desired and partial data loss is consequently fine as well */
26289a4f4c31SKevin Wolf     ret = bdrv_write_zeroes(bs->file->bs, s->cluster_size / BDRV_SECTOR_SIZE,
262994054183SMax Reitz                             (2 + l1_clusters) * s->cluster_size /
263094054183SMax Reitz                             BDRV_SECTOR_SIZE, 0);
263194054183SMax Reitz     /* This call (even if it failed overall) may have overwritten on-disk
263294054183SMax Reitz      * refcount structures; in that case, the in-memory refcount information
263394054183SMax Reitz      * will probably differ from the on-disk information which makes the BDS
263494054183SMax Reitz      * unusable */
263594054183SMax Reitz     if (ret < 0) {
263694054183SMax Reitz         goto fail_broken_refcounts;
263794054183SMax Reitz     }
263894054183SMax Reitz 
263994054183SMax Reitz     BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
264094054183SMax Reitz     BLKDBG_EVENT(bs->file, BLKDBG_REFTABLE_UPDATE);
264194054183SMax Reitz 
264294054183SMax Reitz     /* "Create" an empty reftable (one cluster) directly after the image
264394054183SMax Reitz      * header and an empty L1 table three clusters after the image header;
264494054183SMax Reitz      * the cluster between those two will be used as the first refblock */
264594054183SMax Reitz     cpu_to_be64w(&l1_ofs_rt_ofs_cls.l1_offset, 3 * s->cluster_size);
264694054183SMax Reitz     cpu_to_be64w(&l1_ofs_rt_ofs_cls.reftable_offset, s->cluster_size);
264794054183SMax Reitz     cpu_to_be32w(&l1_ofs_rt_ofs_cls.reftable_clusters, 1);
26489a4f4c31SKevin Wolf     ret = bdrv_pwrite_sync(bs->file->bs, offsetof(QCowHeader, l1_table_offset),
264994054183SMax Reitz                            &l1_ofs_rt_ofs_cls, sizeof(l1_ofs_rt_ofs_cls));
265094054183SMax Reitz     if (ret < 0) {
265194054183SMax Reitz         goto fail_broken_refcounts;
265294054183SMax Reitz     }
265394054183SMax Reitz 
265494054183SMax Reitz     s->l1_table_offset = 3 * s->cluster_size;
265594054183SMax Reitz 
265694054183SMax Reitz     new_reftable = g_try_new0(uint64_t, s->cluster_size / sizeof(uint64_t));
265794054183SMax Reitz     if (!new_reftable) {
265894054183SMax Reitz         ret = -ENOMEM;
265994054183SMax Reitz         goto fail_broken_refcounts;
266094054183SMax Reitz     }
266194054183SMax Reitz 
266294054183SMax Reitz     s->refcount_table_offset = s->cluster_size;
266394054183SMax Reitz     s->refcount_table_size   = s->cluster_size / sizeof(uint64_t);
266494054183SMax Reitz 
266594054183SMax Reitz     g_free(s->refcount_table);
266694054183SMax Reitz     s->refcount_table = new_reftable;
266794054183SMax Reitz     new_reftable = NULL;
266894054183SMax Reitz 
266994054183SMax Reitz     /* Now the in-memory refcount information again corresponds to the on-disk
267094054183SMax Reitz      * information (reftable is empty and no refblocks (the refblock cache is
267194054183SMax Reitz      * empty)); however, this means some clusters (e.g. the image header) are
267294054183SMax Reitz      * referenced, but not refcounted, but the normal qcow2 code assumes that
267394054183SMax Reitz      * the in-memory information is always correct */
267494054183SMax Reitz 
267594054183SMax Reitz     BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_ALLOC);
267694054183SMax Reitz 
267794054183SMax Reitz     /* Enter the first refblock into the reftable */
267894054183SMax Reitz     rt_entry = cpu_to_be64(2 * s->cluster_size);
26799a4f4c31SKevin Wolf     ret = bdrv_pwrite_sync(bs->file->bs, s->cluster_size,
268094054183SMax Reitz                            &rt_entry, sizeof(rt_entry));
268194054183SMax Reitz     if (ret < 0) {
268294054183SMax Reitz         goto fail_broken_refcounts;
268394054183SMax Reitz     }
268494054183SMax Reitz     s->refcount_table[0] = 2 * s->cluster_size;
268594054183SMax Reitz 
268694054183SMax Reitz     s->free_cluster_index = 0;
268794054183SMax Reitz     assert(3 + l1_clusters <= s->refcount_block_size);
268894054183SMax Reitz     offset = qcow2_alloc_clusters(bs, 3 * s->cluster_size + l1_size2);
268994054183SMax Reitz     if (offset < 0) {
269094054183SMax Reitz         ret = offset;
269194054183SMax Reitz         goto fail_broken_refcounts;
269294054183SMax Reitz     } else if (offset > 0) {
269394054183SMax Reitz         error_report("First cluster in emptied image is in use");
269494054183SMax Reitz         abort();
269594054183SMax Reitz     }
269694054183SMax Reitz 
269794054183SMax Reitz     /* Now finally the in-memory information corresponds to the on-disk
269894054183SMax Reitz      * structures and is correct */
269994054183SMax Reitz     ret = qcow2_mark_clean(bs);
270094054183SMax Reitz     if (ret < 0) {
270194054183SMax Reitz         goto fail;
270294054183SMax Reitz     }
270394054183SMax Reitz 
27049a4f4c31SKevin Wolf     ret = bdrv_truncate(bs->file->bs, (3 + l1_clusters) * s->cluster_size);
270594054183SMax Reitz     if (ret < 0) {
270694054183SMax Reitz         goto fail;
270794054183SMax Reitz     }
270894054183SMax Reitz 
270994054183SMax Reitz     return 0;
271094054183SMax Reitz 
271194054183SMax Reitz fail_broken_refcounts:
271294054183SMax Reitz     /* The BDS is unusable at this point. If we wanted to make it usable, we
271394054183SMax Reitz      * would have to call qcow2_refcount_close(), qcow2_refcount_init(),
271494054183SMax Reitz      * qcow2_check_refcounts(), qcow2_refcount_close() and qcow2_refcount_init()
271594054183SMax Reitz      * again. However, because the functions which could have caused this error
271694054183SMax Reitz      * path to be taken are used by those functions as well, it's very likely
271794054183SMax Reitz      * that that sequence will fail as well. Therefore, just eject the BDS. */
271894054183SMax Reitz     bs->drv = NULL;
271994054183SMax Reitz 
272094054183SMax Reitz fail:
272194054183SMax Reitz     g_free(new_reftable);
272294054183SMax Reitz     return ret;
272394054183SMax Reitz }
272494054183SMax Reitz 
2725491d27e2SMax Reitz static int qcow2_make_empty(BlockDriverState *bs)
2726491d27e2SMax Reitz {
2727ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
2728491d27e2SMax Reitz     uint64_t start_sector;
2729491d27e2SMax Reitz     int sector_step = INT_MAX / BDRV_SECTOR_SIZE;
273094054183SMax Reitz     int l1_clusters, ret = 0;
2731491d27e2SMax Reitz 
273294054183SMax Reitz     l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / sizeof(uint64_t));
273394054183SMax Reitz 
273494054183SMax Reitz     if (s->qcow_version >= 3 && !s->snapshots &&
273594054183SMax Reitz         3 + l1_clusters <= s->refcount_block_size) {
273694054183SMax Reitz         /* The following function only works for qcow2 v3 images (it requires
273794054183SMax Reitz          * the dirty flag) and only as long as there are no snapshots (because
273894054183SMax Reitz          * it completely empties the image). Furthermore, the L1 table and three
273994054183SMax Reitz          * additional clusters (image header, refcount table, one refcount
274094054183SMax Reitz          * block) have to fit inside one refcount block. */
274194054183SMax Reitz         return make_completely_empty(bs);
274294054183SMax Reitz     }
274394054183SMax Reitz 
274494054183SMax Reitz     /* This fallback code simply discards every active cluster; this is slow,
274594054183SMax Reitz      * but works in all cases */
2746491d27e2SMax Reitz     for (start_sector = 0; start_sector < bs->total_sectors;
2747491d27e2SMax Reitz          start_sector += sector_step)
2748491d27e2SMax Reitz     {
2749491d27e2SMax Reitz         /* As this function is generally used after committing an external
2750491d27e2SMax Reitz          * snapshot, QCOW2_DISCARD_SNAPSHOT seems appropriate. Also, the
2751491d27e2SMax Reitz          * default action for this kind of discard is to pass the discard,
2752491d27e2SMax Reitz          * which will ideally result in an actually smaller image file, as
2753491d27e2SMax Reitz          * is probably desired. */
2754491d27e2SMax Reitz         ret = qcow2_discard_clusters(bs, start_sector * BDRV_SECTOR_SIZE,
2755491d27e2SMax Reitz                                      MIN(sector_step,
2756491d27e2SMax Reitz                                          bs->total_sectors - start_sector),
2757491d27e2SMax Reitz                                      QCOW2_DISCARD_SNAPSHOT, true);
2758491d27e2SMax Reitz         if (ret < 0) {
2759491d27e2SMax Reitz             break;
2760491d27e2SMax Reitz         }
2761491d27e2SMax Reitz     }
2762491d27e2SMax Reitz 
2763491d27e2SMax Reitz     return ret;
2764491d27e2SMax Reitz }
2765491d27e2SMax Reitz 
2766a968168cSDong Xu Wang static coroutine_fn int qcow2_co_flush_to_os(BlockDriverState *bs)
276720d97356SBlue Swirl {
2768ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
276929c1a730SKevin Wolf     int ret;
277029c1a730SKevin Wolf 
27718b94ff85SPaolo Bonzini     qemu_co_mutex_lock(&s->lock);
277229c1a730SKevin Wolf     ret = qcow2_cache_flush(bs, s->l2_table_cache);
277329c1a730SKevin Wolf     if (ret < 0) {
2774c95de7e2SDong Xu Wang         qemu_co_mutex_unlock(&s->lock);
27758b94ff85SPaolo Bonzini         return ret;
277629c1a730SKevin Wolf     }
277729c1a730SKevin Wolf 
2778bfe8043eSStefan Hajnoczi     if (qcow2_need_accurate_refcounts(s)) {
277929c1a730SKevin Wolf         ret = qcow2_cache_flush(bs, s->refcount_block_cache);
278029c1a730SKevin Wolf         if (ret < 0) {
2781c95de7e2SDong Xu Wang             qemu_co_mutex_unlock(&s->lock);
27828b94ff85SPaolo Bonzini             return ret;
278329c1a730SKevin Wolf         }
2784bfe8043eSStefan Hajnoczi     }
27858b94ff85SPaolo Bonzini     qemu_co_mutex_unlock(&s->lock);
278629c1a730SKevin Wolf 
2787eb489bb1SKevin Wolf     return 0;
2788eb489bb1SKevin Wolf }
2789eb489bb1SKevin Wolf 
27907c80ab3fSJes Sorensen static int qcow2_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
279120d97356SBlue Swirl {
2792ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
279395de6d70SPaolo Bonzini     bdi->unallocated_blocks_are_zero = true;
279495de6d70SPaolo Bonzini     bdi->can_write_zeroes_with_unmap = (s->qcow_version >= 3);
279520d97356SBlue Swirl     bdi->cluster_size = s->cluster_size;
27967c80ab3fSJes Sorensen     bdi->vm_state_offset = qcow2_vm_state_offset(s);
279720d97356SBlue Swirl     return 0;
279820d97356SBlue Swirl }
279920d97356SBlue Swirl 
280037764dfbSMax Reitz static ImageInfoSpecific *qcow2_get_specific_info(BlockDriverState *bs)
280137764dfbSMax Reitz {
2802ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
280337764dfbSMax Reitz     ImageInfoSpecific *spec_info = g_new(ImageInfoSpecific, 1);
280437764dfbSMax Reitz 
280537764dfbSMax Reitz     *spec_info = (ImageInfoSpecific){
28066a8f9661SEric Blake         .type  = IMAGE_INFO_SPECIFIC_KIND_QCOW2,
28076a8f9661SEric Blake         .u.qcow2 = g_new(ImageInfoSpecificQCow2, 1),
280837764dfbSMax Reitz     };
280937764dfbSMax Reitz     if (s->qcow_version == 2) {
28106a8f9661SEric Blake         *spec_info->u.qcow2 = (ImageInfoSpecificQCow2){
281137764dfbSMax Reitz             .compat             = g_strdup("0.10"),
28120709c5a1SMax Reitz             .refcount_bits      = s->refcount_bits,
281337764dfbSMax Reitz         };
281437764dfbSMax Reitz     } else if (s->qcow_version == 3) {
28156a8f9661SEric Blake         *spec_info->u.qcow2 = (ImageInfoSpecificQCow2){
281637764dfbSMax Reitz             .compat             = g_strdup("1.1"),
281737764dfbSMax Reitz             .lazy_refcounts     = s->compatible_features &
281837764dfbSMax Reitz                                   QCOW2_COMPAT_LAZY_REFCOUNTS,
281937764dfbSMax Reitz             .has_lazy_refcounts = true,
28209009b196SMax Reitz             .corrupt            = s->incompatible_features &
28219009b196SMax Reitz                                   QCOW2_INCOMPAT_CORRUPT,
28229009b196SMax Reitz             .has_corrupt        = true,
28230709c5a1SMax Reitz             .refcount_bits      = s->refcount_bits,
282437764dfbSMax Reitz         };
2825b1fc8f93SDenis V. Lunev     } else {
2826b1fc8f93SDenis V. Lunev         /* if this assertion fails, this probably means a new version was
2827b1fc8f93SDenis V. Lunev          * added without having it covered here */
2828b1fc8f93SDenis V. Lunev         assert(false);
282937764dfbSMax Reitz     }
283037764dfbSMax Reitz 
283137764dfbSMax Reitz     return spec_info;
283237764dfbSMax Reitz }
283337764dfbSMax Reitz 
283420d97356SBlue Swirl #if 0
283520d97356SBlue Swirl static void dump_refcounts(BlockDriverState *bs)
283620d97356SBlue Swirl {
2837ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
283820d97356SBlue Swirl     int64_t nb_clusters, k, k1, size;
283920d97356SBlue Swirl     int refcount;
284020d97356SBlue Swirl 
28419a4f4c31SKevin Wolf     size = bdrv_getlength(bs->file->bs);
284220d97356SBlue Swirl     nb_clusters = size_to_clusters(s, size);
284320d97356SBlue Swirl     for(k = 0; k < nb_clusters;) {
284420d97356SBlue Swirl         k1 = k;
284520d97356SBlue Swirl         refcount = get_refcount(bs, k);
284620d97356SBlue Swirl         k++;
284720d97356SBlue Swirl         while (k < nb_clusters && get_refcount(bs, k) == refcount)
284820d97356SBlue Swirl             k++;
28490bfcd599SBlue Swirl         printf("%" PRId64 ": refcount=%d nb=%" PRId64 "\n", k, refcount,
28500bfcd599SBlue Swirl                k - k1);
285120d97356SBlue Swirl     }
285220d97356SBlue Swirl }
285320d97356SBlue Swirl #endif
285420d97356SBlue Swirl 
2855cf8074b3SKevin Wolf static int qcow2_save_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
2856cf8074b3SKevin Wolf                               int64_t pos)
285720d97356SBlue Swirl {
2858ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
2859eedff66fSMax Reitz     int64_t total_sectors = bs->total_sectors;
28606e13610aSMax Reitz     bool zero_beyond_eof = bs->zero_beyond_eof;
286120d97356SBlue Swirl     int ret;
286220d97356SBlue Swirl 
286366f82ceeSKevin Wolf     BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_SAVE);
28646e13610aSMax Reitz     bs->zero_beyond_eof = false;
28658d3b1a2dSKevin Wolf     ret = bdrv_pwritev(bs, qcow2_vm_state_offset(s) + pos, qiov);
28666e13610aSMax Reitz     bs->zero_beyond_eof = zero_beyond_eof;
286720d97356SBlue Swirl 
2868eedff66fSMax Reitz     /* bdrv_co_do_writev will have increased the total_sectors value to include
2869eedff66fSMax Reitz      * the VM state - the VM state is however not an actual part of the block
2870eedff66fSMax Reitz      * device, therefore, we need to restore the old value. */
2871eedff66fSMax Reitz     bs->total_sectors = total_sectors;
2872eedff66fSMax Reitz 
287320d97356SBlue Swirl     return ret;
287420d97356SBlue Swirl }
287520d97356SBlue Swirl 
28767c80ab3fSJes Sorensen static int qcow2_load_vmstate(BlockDriverState *bs, uint8_t *buf,
287720d97356SBlue Swirl                               int64_t pos, int size)
287820d97356SBlue Swirl {
2879ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
28800d51b4deSAsias He     bool zero_beyond_eof = bs->zero_beyond_eof;
288120d97356SBlue Swirl     int ret;
288220d97356SBlue Swirl 
288366f82ceeSKevin Wolf     BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_LOAD);
28840d51b4deSAsias He     bs->zero_beyond_eof = false;
28857c80ab3fSJes Sorensen     ret = bdrv_pread(bs, qcow2_vm_state_offset(s) + pos, buf, size);
28860d51b4deSAsias He     bs->zero_beyond_eof = zero_beyond_eof;
288720d97356SBlue Swirl 
288820d97356SBlue Swirl     return ret;
288920d97356SBlue Swirl }
289020d97356SBlue Swirl 
28919296b3edSMax Reitz /*
28929296b3edSMax Reitz  * Downgrades an image's version. To achieve this, any incompatible features
28939296b3edSMax Reitz  * have to be removed.
28949296b3edSMax Reitz  */
28954057a2b2SMax Reitz static int qcow2_downgrade(BlockDriverState *bs, int target_version,
28968b13976dSMax Reitz                            BlockDriverAmendStatusCB *status_cb, void *cb_opaque)
28979296b3edSMax Reitz {
2898ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
28999296b3edSMax Reitz     int current_version = s->qcow_version;
29009296b3edSMax Reitz     int ret;
29019296b3edSMax Reitz 
29029296b3edSMax Reitz     if (target_version == current_version) {
29039296b3edSMax Reitz         return 0;
29049296b3edSMax Reitz     } else if (target_version > current_version) {
29059296b3edSMax Reitz         return -EINVAL;
29069296b3edSMax Reitz     } else if (target_version != 2) {
29079296b3edSMax Reitz         return -EINVAL;
29089296b3edSMax Reitz     }
29099296b3edSMax Reitz 
29109296b3edSMax Reitz     if (s->refcount_order != 4) {
291161ce55fcSMax Reitz         error_report("compat=0.10 requires refcount_bits=16");
29129296b3edSMax Reitz         return -ENOTSUP;
29139296b3edSMax Reitz     }
29149296b3edSMax Reitz 
29159296b3edSMax Reitz     /* clear incompatible features */
29169296b3edSMax Reitz     if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
29179296b3edSMax Reitz         ret = qcow2_mark_clean(bs);
29189296b3edSMax Reitz         if (ret < 0) {
29199296b3edSMax Reitz             return ret;
29209296b3edSMax Reitz         }
29219296b3edSMax Reitz     }
29229296b3edSMax Reitz 
29239296b3edSMax Reitz     /* with QCOW2_INCOMPAT_CORRUPT, it is pretty much impossible to get here in
29249296b3edSMax Reitz      * the first place; if that happens nonetheless, returning -ENOTSUP is the
29259296b3edSMax Reitz      * best thing to do anyway */
29269296b3edSMax Reitz 
29279296b3edSMax Reitz     if (s->incompatible_features) {
29289296b3edSMax Reitz         return -ENOTSUP;
29299296b3edSMax Reitz     }
29309296b3edSMax Reitz 
29319296b3edSMax Reitz     /* since we can ignore compatible features, we can set them to 0 as well */
29329296b3edSMax Reitz     s->compatible_features = 0;
29339296b3edSMax Reitz     /* if lazy refcounts have been used, they have already been fixed through
29349296b3edSMax Reitz      * clearing the dirty flag */
29359296b3edSMax Reitz 
29369296b3edSMax Reitz     /* clearing autoclear features is trivial */
29379296b3edSMax Reitz     s->autoclear_features = 0;
29389296b3edSMax Reitz 
29398b13976dSMax Reitz     ret = qcow2_expand_zero_clusters(bs, status_cb, cb_opaque);
29409296b3edSMax Reitz     if (ret < 0) {
29419296b3edSMax Reitz         return ret;
29429296b3edSMax Reitz     }
29439296b3edSMax Reitz 
29449296b3edSMax Reitz     s->qcow_version = target_version;
29459296b3edSMax Reitz     ret = qcow2_update_header(bs);
29469296b3edSMax Reitz     if (ret < 0) {
29479296b3edSMax Reitz         s->qcow_version = current_version;
29489296b3edSMax Reitz         return ret;
29499296b3edSMax Reitz     }
29509296b3edSMax Reitz     return 0;
29519296b3edSMax Reitz }
29529296b3edSMax Reitz 
2953c293a809SMax Reitz typedef enum Qcow2AmendOperation {
2954c293a809SMax Reitz     /* This is the value Qcow2AmendHelperCBInfo::last_operation will be
2955c293a809SMax Reitz      * statically initialized to so that the helper CB can discern the first
2956c293a809SMax Reitz      * invocation from an operation change */
2957c293a809SMax Reitz     QCOW2_NO_OPERATION = 0,
2958c293a809SMax Reitz 
295961ce55fcSMax Reitz     QCOW2_CHANGING_REFCOUNT_ORDER,
2960c293a809SMax Reitz     QCOW2_DOWNGRADING,
2961c293a809SMax Reitz } Qcow2AmendOperation;
2962c293a809SMax Reitz 
2963c293a809SMax Reitz typedef struct Qcow2AmendHelperCBInfo {
2964c293a809SMax Reitz     /* The code coordinating the amend operations should only modify
2965c293a809SMax Reitz      * these four fields; the rest will be managed by the CB */
2966c293a809SMax Reitz     BlockDriverAmendStatusCB *original_status_cb;
2967c293a809SMax Reitz     void *original_cb_opaque;
2968c293a809SMax Reitz 
2969c293a809SMax Reitz     Qcow2AmendOperation current_operation;
2970c293a809SMax Reitz 
2971c293a809SMax Reitz     /* Total number of operations to perform (only set once) */
2972c293a809SMax Reitz     int total_operations;
2973c293a809SMax Reitz 
2974c293a809SMax Reitz     /* The following fields are managed by the CB */
2975c293a809SMax Reitz 
2976c293a809SMax Reitz     /* Number of operations completed */
2977c293a809SMax Reitz     int operations_completed;
2978c293a809SMax Reitz 
2979c293a809SMax Reitz     /* Cumulative offset of all completed operations */
2980c293a809SMax Reitz     int64_t offset_completed;
2981c293a809SMax Reitz 
2982c293a809SMax Reitz     Qcow2AmendOperation last_operation;
2983c293a809SMax Reitz     int64_t last_work_size;
2984c293a809SMax Reitz } Qcow2AmendHelperCBInfo;
2985c293a809SMax Reitz 
2986c293a809SMax Reitz static void qcow2_amend_helper_cb(BlockDriverState *bs,
2987c293a809SMax Reitz                                   int64_t operation_offset,
2988c293a809SMax Reitz                                   int64_t operation_work_size, void *opaque)
2989c293a809SMax Reitz {
2990c293a809SMax Reitz     Qcow2AmendHelperCBInfo *info = opaque;
2991c293a809SMax Reitz     int64_t current_work_size;
2992c293a809SMax Reitz     int64_t projected_work_size;
2993c293a809SMax Reitz 
2994c293a809SMax Reitz     if (info->current_operation != info->last_operation) {
2995c293a809SMax Reitz         if (info->last_operation != QCOW2_NO_OPERATION) {
2996c293a809SMax Reitz             info->offset_completed += info->last_work_size;
2997c293a809SMax Reitz             info->operations_completed++;
2998c293a809SMax Reitz         }
2999c293a809SMax Reitz 
3000c293a809SMax Reitz         info->last_operation = info->current_operation;
3001c293a809SMax Reitz     }
3002c293a809SMax Reitz 
3003c293a809SMax Reitz     assert(info->total_operations > 0);
3004c293a809SMax Reitz     assert(info->operations_completed < info->total_operations);
3005c293a809SMax Reitz 
3006c293a809SMax Reitz     info->last_work_size = operation_work_size;
3007c293a809SMax Reitz 
3008c293a809SMax Reitz     current_work_size = info->offset_completed + operation_work_size;
3009c293a809SMax Reitz 
3010c293a809SMax Reitz     /* current_work_size is the total work size for (operations_completed + 1)
3011c293a809SMax Reitz      * operations (which includes this one), so multiply it by the number of
3012c293a809SMax Reitz      * operations not covered and divide it by the number of operations
3013c293a809SMax Reitz      * covered to get a projection for the operations not covered */
3014c293a809SMax Reitz     projected_work_size = current_work_size * (info->total_operations -
3015c293a809SMax Reitz                                                info->operations_completed - 1)
3016c293a809SMax Reitz                                             / (info->operations_completed + 1);
3017c293a809SMax Reitz 
3018c293a809SMax Reitz     info->original_status_cb(bs, info->offset_completed + operation_offset,
3019c293a809SMax Reitz                              current_work_size + projected_work_size,
3020c293a809SMax Reitz                              info->original_cb_opaque);
3021c293a809SMax Reitz }
3022c293a809SMax Reitz 
302377485434SMax Reitz static int qcow2_amend_options(BlockDriverState *bs, QemuOpts *opts,
30248b13976dSMax Reitz                                BlockDriverAmendStatusCB *status_cb,
30258b13976dSMax Reitz                                void *cb_opaque)
30269296b3edSMax Reitz {
3027ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
30289296b3edSMax Reitz     int old_version = s->qcow_version, new_version = old_version;
30299296b3edSMax Reitz     uint64_t new_size = 0;
30309296b3edSMax Reitz     const char *backing_file = NULL, *backing_format = NULL;
30319296b3edSMax Reitz     bool lazy_refcounts = s->use_lazy_refcounts;
30321bd0e2d1SChunyan Liu     const char *compat = NULL;
30331bd0e2d1SChunyan Liu     uint64_t cluster_size = s->cluster_size;
30341bd0e2d1SChunyan Liu     bool encrypt;
303561ce55fcSMax Reitz     int refcount_bits = s->refcount_bits;
30369296b3edSMax Reitz     int ret;
30371bd0e2d1SChunyan Liu     QemuOptDesc *desc = opts->list->desc;
3038c293a809SMax Reitz     Qcow2AmendHelperCBInfo helper_cb_info;
30399296b3edSMax Reitz 
30401bd0e2d1SChunyan Liu     while (desc && desc->name) {
30411bd0e2d1SChunyan Liu         if (!qemu_opt_find(opts, desc->name)) {
30429296b3edSMax Reitz             /* only change explicitly defined options */
30431bd0e2d1SChunyan Liu             desc++;
30449296b3edSMax Reitz             continue;
30459296b3edSMax Reitz         }
30469296b3edSMax Reitz 
30478a17b83cSMax Reitz         if (!strcmp(desc->name, BLOCK_OPT_COMPAT_LEVEL)) {
30488a17b83cSMax Reitz             compat = qemu_opt_get(opts, BLOCK_OPT_COMPAT_LEVEL);
30491bd0e2d1SChunyan Liu             if (!compat) {
30509296b3edSMax Reitz                 /* preserve default */
30511bd0e2d1SChunyan Liu             } else if (!strcmp(compat, "0.10")) {
30529296b3edSMax Reitz                 new_version = 2;
30531bd0e2d1SChunyan Liu             } else if (!strcmp(compat, "1.1")) {
30549296b3edSMax Reitz                 new_version = 3;
30559296b3edSMax Reitz             } else {
305629d72431SMax Reitz                 error_report("Unknown compatibility level %s", compat);
30579296b3edSMax Reitz                 return -EINVAL;
30589296b3edSMax Reitz             }
30598a17b83cSMax Reitz         } else if (!strcmp(desc->name, BLOCK_OPT_PREALLOC)) {
306029d72431SMax Reitz             error_report("Cannot change preallocation mode");
30619296b3edSMax Reitz             return -ENOTSUP;
30628a17b83cSMax Reitz         } else if (!strcmp(desc->name, BLOCK_OPT_SIZE)) {
30638a17b83cSMax Reitz             new_size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, 0);
30648a17b83cSMax Reitz         } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FILE)) {
30658a17b83cSMax Reitz             backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
30668a17b83cSMax Reitz         } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FMT)) {
30678a17b83cSMax Reitz             backing_format = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
30688a17b83cSMax Reitz         } else if (!strcmp(desc->name, BLOCK_OPT_ENCRYPT)) {
30698a17b83cSMax Reitz             encrypt = qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT,
3070f6fa64f6SDaniel P. Berrange                                         !!s->cipher);
3071f6fa64f6SDaniel P. Berrange 
3072f6fa64f6SDaniel P. Berrange             if (encrypt != !!s->cipher) {
307329d72431SMax Reitz                 error_report("Changing the encryption flag is not supported");
30749296b3edSMax Reitz                 return -ENOTSUP;
30759296b3edSMax Reitz             }
30768a17b83cSMax Reitz         } else if (!strcmp(desc->name, BLOCK_OPT_CLUSTER_SIZE)) {
30778a17b83cSMax Reitz             cluster_size = qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE,
30781bd0e2d1SChunyan Liu                                              cluster_size);
30791bd0e2d1SChunyan Liu             if (cluster_size != s->cluster_size) {
308029d72431SMax Reitz                 error_report("Changing the cluster size is not supported");
30819296b3edSMax Reitz                 return -ENOTSUP;
30829296b3edSMax Reitz             }
30838a17b83cSMax Reitz         } else if (!strcmp(desc->name, BLOCK_OPT_LAZY_REFCOUNTS)) {
30848a17b83cSMax Reitz             lazy_refcounts = qemu_opt_get_bool(opts, BLOCK_OPT_LAZY_REFCOUNTS,
30851bd0e2d1SChunyan Liu                                                lazy_refcounts);
308606d05fa7SMax Reitz         } else if (!strcmp(desc->name, BLOCK_OPT_REFCOUNT_BITS)) {
308761ce55fcSMax Reitz             refcount_bits = qemu_opt_get_number(opts, BLOCK_OPT_REFCOUNT_BITS,
308861ce55fcSMax Reitz                                                 refcount_bits);
308961ce55fcSMax Reitz 
309061ce55fcSMax Reitz             if (refcount_bits <= 0 || refcount_bits > 64 ||
309161ce55fcSMax Reitz                 !is_power_of_2(refcount_bits))
309261ce55fcSMax Reitz             {
309361ce55fcSMax Reitz                 error_report("Refcount width must be a power of two and may "
309461ce55fcSMax Reitz                              "not exceed 64 bits");
309561ce55fcSMax Reitz                 return -EINVAL;
309661ce55fcSMax Reitz             }
30979296b3edSMax Reitz         } else {
3098164e0f89SMax Reitz             /* if this point is reached, this probably means a new option was
30999296b3edSMax Reitz              * added without having it covered here */
3100164e0f89SMax Reitz             abort();
31019296b3edSMax Reitz         }
31021bd0e2d1SChunyan Liu 
31031bd0e2d1SChunyan Liu         desc++;
31049296b3edSMax Reitz     }
31059296b3edSMax Reitz 
3106c293a809SMax Reitz     helper_cb_info = (Qcow2AmendHelperCBInfo){
3107c293a809SMax Reitz         .original_status_cb = status_cb,
3108c293a809SMax Reitz         .original_cb_opaque = cb_opaque,
3109c293a809SMax Reitz         .total_operations = (new_version < old_version)
311061ce55fcSMax Reitz                           + (s->refcount_bits != refcount_bits)
3111c293a809SMax Reitz     };
3112c293a809SMax Reitz 
31131038bbb8SMax Reitz     /* Upgrade first (some features may require compat=1.1) */
31149296b3edSMax Reitz     if (new_version > old_version) {
31159296b3edSMax Reitz         s->qcow_version = new_version;
31169296b3edSMax Reitz         ret = qcow2_update_header(bs);
31179296b3edSMax Reitz         if (ret < 0) {
31189296b3edSMax Reitz             s->qcow_version = old_version;
31199296b3edSMax Reitz             return ret;
31209296b3edSMax Reitz         }
31219296b3edSMax Reitz     }
31229296b3edSMax Reitz 
312361ce55fcSMax Reitz     if (s->refcount_bits != refcount_bits) {
312461ce55fcSMax Reitz         int refcount_order = ctz32(refcount_bits);
312561ce55fcSMax Reitz         Error *local_error = NULL;
312661ce55fcSMax Reitz 
312761ce55fcSMax Reitz         if (new_version < 3 && refcount_bits != 16) {
312861ce55fcSMax Reitz             error_report("Different refcount widths than 16 bits require "
312961ce55fcSMax Reitz                          "compatibility level 1.1 or above (use compat=1.1 or "
313061ce55fcSMax Reitz                          "greater)");
313161ce55fcSMax Reitz             return -EINVAL;
313261ce55fcSMax Reitz         }
313361ce55fcSMax Reitz 
313461ce55fcSMax Reitz         helper_cb_info.current_operation = QCOW2_CHANGING_REFCOUNT_ORDER;
313561ce55fcSMax Reitz         ret = qcow2_change_refcount_order(bs, refcount_order,
313661ce55fcSMax Reitz                                           &qcow2_amend_helper_cb,
313761ce55fcSMax Reitz                                           &helper_cb_info, &local_error);
313861ce55fcSMax Reitz         if (ret < 0) {
313961ce55fcSMax Reitz             error_report_err(local_error);
314061ce55fcSMax Reitz             return ret;
314161ce55fcSMax Reitz         }
314261ce55fcSMax Reitz     }
314361ce55fcSMax Reitz 
31449296b3edSMax Reitz     if (backing_file || backing_format) {
3145e4603fe1SKevin Wolf         ret = qcow2_change_backing_file(bs,
3146e4603fe1SKevin Wolf                     backing_file ?: s->image_backing_file,
3147e4603fe1SKevin Wolf                     backing_format ?: s->image_backing_format);
31489296b3edSMax Reitz         if (ret < 0) {
31499296b3edSMax Reitz             return ret;
31509296b3edSMax Reitz         }
31519296b3edSMax Reitz     }
31529296b3edSMax Reitz 
31539296b3edSMax Reitz     if (s->use_lazy_refcounts != lazy_refcounts) {
31549296b3edSMax Reitz         if (lazy_refcounts) {
31551038bbb8SMax Reitz             if (new_version < 3) {
315629d72431SMax Reitz                 error_report("Lazy refcounts only supported with compatibility "
315729d72431SMax Reitz                              "level 1.1 and above (use compat=1.1 or greater)");
31589296b3edSMax Reitz                 return -EINVAL;
31599296b3edSMax Reitz             }
31609296b3edSMax Reitz             s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
31619296b3edSMax Reitz             ret = qcow2_update_header(bs);
31629296b3edSMax Reitz             if (ret < 0) {
31639296b3edSMax Reitz                 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
31649296b3edSMax Reitz                 return ret;
31659296b3edSMax Reitz             }
31669296b3edSMax Reitz             s->use_lazy_refcounts = true;
31679296b3edSMax Reitz         } else {
31689296b3edSMax Reitz             /* make image clean first */
31699296b3edSMax Reitz             ret = qcow2_mark_clean(bs);
31709296b3edSMax Reitz             if (ret < 0) {
31719296b3edSMax Reitz                 return ret;
31729296b3edSMax Reitz             }
31739296b3edSMax Reitz             /* now disallow lazy refcounts */
31749296b3edSMax Reitz             s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
31759296b3edSMax Reitz             ret = qcow2_update_header(bs);
31769296b3edSMax Reitz             if (ret < 0) {
31779296b3edSMax Reitz                 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
31789296b3edSMax Reitz                 return ret;
31799296b3edSMax Reitz             }
31809296b3edSMax Reitz             s->use_lazy_refcounts = false;
31819296b3edSMax Reitz         }
31829296b3edSMax Reitz     }
31839296b3edSMax Reitz 
31849296b3edSMax Reitz     if (new_size) {
31859296b3edSMax Reitz         ret = bdrv_truncate(bs, new_size);
31869296b3edSMax Reitz         if (ret < 0) {
31879296b3edSMax Reitz             return ret;
31889296b3edSMax Reitz         }
31899296b3edSMax Reitz     }
31909296b3edSMax Reitz 
31911038bbb8SMax Reitz     /* Downgrade last (so unsupported features can be removed before) */
31921038bbb8SMax Reitz     if (new_version < old_version) {
3193c293a809SMax Reitz         helper_cb_info.current_operation = QCOW2_DOWNGRADING;
3194c293a809SMax Reitz         ret = qcow2_downgrade(bs, new_version, &qcow2_amend_helper_cb,
3195c293a809SMax Reitz                               &helper_cb_info);
31961038bbb8SMax Reitz         if (ret < 0) {
31971038bbb8SMax Reitz             return ret;
31981038bbb8SMax Reitz         }
31991038bbb8SMax Reitz     }
32001038bbb8SMax Reitz 
32019296b3edSMax Reitz     return 0;
32029296b3edSMax Reitz }
32039296b3edSMax Reitz 
320485186ebdSMax Reitz /*
320585186ebdSMax Reitz  * If offset or size are negative, respectively, they will not be included in
320685186ebdSMax Reitz  * the BLOCK_IMAGE_CORRUPTED event emitted.
320785186ebdSMax Reitz  * fatal will be ignored for read-only BDS; corruptions found there will always
320885186ebdSMax Reitz  * be considered non-fatal.
320985186ebdSMax Reitz  */
321085186ebdSMax Reitz void qcow2_signal_corruption(BlockDriverState *bs, bool fatal, int64_t offset,
321185186ebdSMax Reitz                              int64_t size, const char *message_format, ...)
321285186ebdSMax Reitz {
3213ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
3214dc881b44SAlberto Garcia     const char *node_name;
321585186ebdSMax Reitz     char *message;
321685186ebdSMax Reitz     va_list ap;
321785186ebdSMax Reitz 
321885186ebdSMax Reitz     fatal = fatal && !bs->read_only;
321985186ebdSMax Reitz 
322085186ebdSMax Reitz     if (s->signaled_corruption &&
322185186ebdSMax Reitz         (!fatal || (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT)))
322285186ebdSMax Reitz     {
322385186ebdSMax Reitz         return;
322485186ebdSMax Reitz     }
322585186ebdSMax Reitz 
322685186ebdSMax Reitz     va_start(ap, message_format);
322785186ebdSMax Reitz     message = g_strdup_vprintf(message_format, ap);
322885186ebdSMax Reitz     va_end(ap);
322985186ebdSMax Reitz 
323085186ebdSMax Reitz     if (fatal) {
323185186ebdSMax Reitz         fprintf(stderr, "qcow2: Marking image as corrupt: %s; further "
323285186ebdSMax Reitz                 "corruption events will be suppressed\n", message);
323385186ebdSMax Reitz     } else {
323485186ebdSMax Reitz         fprintf(stderr, "qcow2: Image is corrupt: %s; further non-fatal "
323585186ebdSMax Reitz                 "corruption events will be suppressed\n", message);
323685186ebdSMax Reitz     }
323785186ebdSMax Reitz 
3238dc881b44SAlberto Garcia     node_name = bdrv_get_node_name(bs);
3239dc881b44SAlberto Garcia     qapi_event_send_block_image_corrupted(bdrv_get_device_name(bs),
3240dc881b44SAlberto Garcia                                           *node_name != '\0', node_name,
3241dc881b44SAlberto Garcia                                           message, offset >= 0, offset,
3242dc881b44SAlberto Garcia                                           size >= 0, size,
324385186ebdSMax Reitz                                           fatal, &error_abort);
324485186ebdSMax Reitz     g_free(message);
324585186ebdSMax Reitz 
324685186ebdSMax Reitz     if (fatal) {
324785186ebdSMax Reitz         qcow2_mark_corrupt(bs);
324885186ebdSMax Reitz         bs->drv = NULL; /* make BDS unusable */
324985186ebdSMax Reitz     }
325085186ebdSMax Reitz 
325185186ebdSMax Reitz     s->signaled_corruption = true;
325285186ebdSMax Reitz }
325385186ebdSMax Reitz 
32541bd0e2d1SChunyan Liu static QemuOptsList qcow2_create_opts = {
32551bd0e2d1SChunyan Liu     .name = "qcow2-create-opts",
32561bd0e2d1SChunyan Liu     .head = QTAILQ_HEAD_INITIALIZER(qcow2_create_opts.head),
32571bd0e2d1SChunyan Liu     .desc = {
325820d97356SBlue Swirl         {
325920d97356SBlue Swirl             .name = BLOCK_OPT_SIZE,
32601bd0e2d1SChunyan Liu             .type = QEMU_OPT_SIZE,
326120d97356SBlue Swirl             .help = "Virtual disk size"
326220d97356SBlue Swirl         },
326320d97356SBlue Swirl         {
32646744cbabSKevin Wolf             .name = BLOCK_OPT_COMPAT_LEVEL,
32651bd0e2d1SChunyan Liu             .type = QEMU_OPT_STRING,
32666744cbabSKevin Wolf             .help = "Compatibility level (0.10 or 1.1)"
32676744cbabSKevin Wolf         },
32686744cbabSKevin Wolf         {
326920d97356SBlue Swirl             .name = BLOCK_OPT_BACKING_FILE,
32701bd0e2d1SChunyan Liu             .type = QEMU_OPT_STRING,
327120d97356SBlue Swirl             .help = "File name of a base image"
327220d97356SBlue Swirl         },
327320d97356SBlue Swirl         {
327420d97356SBlue Swirl             .name = BLOCK_OPT_BACKING_FMT,
32751bd0e2d1SChunyan Liu             .type = QEMU_OPT_STRING,
327620d97356SBlue Swirl             .help = "Image format of the base image"
327720d97356SBlue Swirl         },
327820d97356SBlue Swirl         {
327920d97356SBlue Swirl             .name = BLOCK_OPT_ENCRYPT,
32801bd0e2d1SChunyan Liu             .type = QEMU_OPT_BOOL,
32811bd0e2d1SChunyan Liu             .help = "Encrypt the image",
32821bd0e2d1SChunyan Liu             .def_value_str = "off"
328320d97356SBlue Swirl         },
328420d97356SBlue Swirl         {
328520d97356SBlue Swirl             .name = BLOCK_OPT_CLUSTER_SIZE,
32861bd0e2d1SChunyan Liu             .type = QEMU_OPT_SIZE,
328799cce9faSKevin Wolf             .help = "qcow2 cluster size",
32881bd0e2d1SChunyan Liu             .def_value_str = stringify(DEFAULT_CLUSTER_SIZE)
328920d97356SBlue Swirl         },
329020d97356SBlue Swirl         {
329120d97356SBlue Swirl             .name = BLOCK_OPT_PREALLOC,
32921bd0e2d1SChunyan Liu             .type = QEMU_OPT_STRING,
32930e4271b7SHu Tao             .help = "Preallocation mode (allowed values: off, metadata, "
32940e4271b7SHu Tao                     "falloc, full)"
329520d97356SBlue Swirl         },
3296bfe8043eSStefan Hajnoczi         {
3297bfe8043eSStefan Hajnoczi             .name = BLOCK_OPT_LAZY_REFCOUNTS,
32981bd0e2d1SChunyan Liu             .type = QEMU_OPT_BOOL,
3299bfe8043eSStefan Hajnoczi             .help = "Postpone refcount updates",
33001bd0e2d1SChunyan Liu             .def_value_str = "off"
3301bfe8043eSStefan Hajnoczi         },
330206d05fa7SMax Reitz         {
330306d05fa7SMax Reitz             .name = BLOCK_OPT_REFCOUNT_BITS,
330406d05fa7SMax Reitz             .type = QEMU_OPT_NUMBER,
330506d05fa7SMax Reitz             .help = "Width of a reference count entry in bits",
330606d05fa7SMax Reitz             .def_value_str = "16"
330706d05fa7SMax Reitz         },
33081bd0e2d1SChunyan Liu         { /* end of list */ }
33091bd0e2d1SChunyan Liu     }
331020d97356SBlue Swirl };
331120d97356SBlue Swirl 
33125f535a94SMax Reitz BlockDriver bdrv_qcow2 = {
331320d97356SBlue Swirl     .format_name        = "qcow2",
3314ff99129aSKevin Wolf     .instance_size      = sizeof(BDRVQcow2State),
33157c80ab3fSJes Sorensen     .bdrv_probe         = qcow2_probe,
33167c80ab3fSJes Sorensen     .bdrv_open          = qcow2_open,
33177c80ab3fSJes Sorensen     .bdrv_close         = qcow2_close,
331821d82ac9SJeff Cody     .bdrv_reopen_prepare  = qcow2_reopen_prepare,
33195b0959a7SKevin Wolf     .bdrv_reopen_commit   = qcow2_reopen_commit,
33205b0959a7SKevin Wolf     .bdrv_reopen_abort    = qcow2_reopen_abort,
33215365f44dSKevin Wolf     .bdrv_join_options    = qcow2_join_options,
3322c282e1fdSChunyan Liu     .bdrv_create        = qcow2_create,
33233ac21627SPeter Lieven     .bdrv_has_zero_init = bdrv_has_zero_init_1,
3324b6b8a333SPaolo Bonzini     .bdrv_co_get_block_status = qcow2_co_get_block_status,
33257c80ab3fSJes Sorensen     .bdrv_set_key       = qcow2_set_key,
332620d97356SBlue Swirl 
332768d100e9SKevin Wolf     .bdrv_co_readv          = qcow2_co_readv,
332868d100e9SKevin Wolf     .bdrv_co_writev         = qcow2_co_writev,
3329eb489bb1SKevin Wolf     .bdrv_co_flush_to_os    = qcow2_co_flush_to_os,
3330419b19d9SStefan Hajnoczi 
3331621f0589SKevin Wolf     .bdrv_co_write_zeroes   = qcow2_co_write_zeroes,
33326db39ae2SPaolo Bonzini     .bdrv_co_discard        = qcow2_co_discard,
3333419b19d9SStefan Hajnoczi     .bdrv_truncate          = qcow2_truncate,
33347c80ab3fSJes Sorensen     .bdrv_write_compressed  = qcow2_write_compressed,
3335491d27e2SMax Reitz     .bdrv_make_empty        = qcow2_make_empty,
333620d97356SBlue Swirl 
333720d97356SBlue Swirl     .bdrv_snapshot_create   = qcow2_snapshot_create,
333820d97356SBlue Swirl     .bdrv_snapshot_goto     = qcow2_snapshot_goto,
333920d97356SBlue Swirl     .bdrv_snapshot_delete   = qcow2_snapshot_delete,
334020d97356SBlue Swirl     .bdrv_snapshot_list     = qcow2_snapshot_list,
334151ef6727Sedison     .bdrv_snapshot_load_tmp = qcow2_snapshot_load_tmp,
33427c80ab3fSJes Sorensen     .bdrv_get_info          = qcow2_get_info,
334337764dfbSMax Reitz     .bdrv_get_specific_info = qcow2_get_specific_info,
334420d97356SBlue Swirl 
33457c80ab3fSJes Sorensen     .bdrv_save_vmstate    = qcow2_save_vmstate,
33467c80ab3fSJes Sorensen     .bdrv_load_vmstate    = qcow2_load_vmstate,
334720d97356SBlue Swirl 
33488ee79e70SKevin Wolf     .supports_backing           = true,
334920d97356SBlue Swirl     .bdrv_change_backing_file   = qcow2_change_backing_file,
335020d97356SBlue Swirl 
3351d34682cdSKevin Wolf     .bdrv_refresh_limits        = qcow2_refresh_limits,
335206d9260fSAnthony Liguori     .bdrv_invalidate_cache      = qcow2_invalidate_cache,
3353*ec6d8912SKevin Wolf     .bdrv_inactivate            = qcow2_inactivate,
335406d9260fSAnthony Liguori 
33551bd0e2d1SChunyan Liu     .create_opts         = &qcow2_create_opts,
33567c80ab3fSJes Sorensen     .bdrv_check          = qcow2_check,
3357c282e1fdSChunyan Liu     .bdrv_amend_options  = qcow2_amend_options,
3358279621c0SAlberto Garcia 
3359279621c0SAlberto Garcia     .bdrv_detach_aio_context  = qcow2_detach_aio_context,
3360279621c0SAlberto Garcia     .bdrv_attach_aio_context  = qcow2_attach_aio_context,
336120d97356SBlue Swirl };
336220d97356SBlue Swirl 
33635efa9d5aSAnthony Liguori static void bdrv_qcow2_init(void)
33645efa9d5aSAnthony Liguori {
33655efa9d5aSAnthony Liguori     bdrv_register(&bdrv_qcow2);
33665efa9d5aSAnthony Liguori }
33675efa9d5aSAnthony Liguori 
33685efa9d5aSAnthony Liguori block_init(bdrv_qcow2_init);
3369