xref: /qemu/block/qcow2.c (revision 72e775c7d9de3eaa35a6edaf9d87cedee149d0f5)
1585f8587Sbellard /*
2585f8587Sbellard  * Block driver for the QCOW version 2 format
3585f8587Sbellard  *
4585f8587Sbellard  * Copyright (c) 2004-2006 Fabrice Bellard
5585f8587Sbellard  *
6585f8587Sbellard  * Permission is hereby granted, free of charge, to any person obtaining a copy
7585f8587Sbellard  * of this software and associated documentation files (the "Software"), to deal
8585f8587Sbellard  * in the Software without restriction, including without limitation the rights
9585f8587Sbellard  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10585f8587Sbellard  * copies of the Software, and to permit persons to whom the Software is
11585f8587Sbellard  * furnished to do so, subject to the following conditions:
12585f8587Sbellard  *
13585f8587Sbellard  * The above copyright notice and this permission notice shall be included in
14585f8587Sbellard  * all copies or substantial portions of the Software.
15585f8587Sbellard  *
16585f8587Sbellard  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17585f8587Sbellard  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18585f8587Sbellard  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19585f8587Sbellard  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20585f8587Sbellard  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21585f8587Sbellard  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22585f8587Sbellard  * THE SOFTWARE.
23585f8587Sbellard  */
2480c71a24SPeter Maydell #include "qemu/osdep.h"
25737e150eSPaolo Bonzini #include "block/block_int.h"
2623588797SKevin Wolf #include "sysemu/block-backend.h"
271de7afc9SPaolo Bonzini #include "qemu/module.h"
28585f8587Sbellard #include <zlib.h>
29f7d0fe02SKevin Wolf #include "block/qcow2.h"
301de7afc9SPaolo Bonzini #include "qemu/error-report.h"
317b1b5d19SPaolo Bonzini #include "qapi/qmp/qerror.h"
32acdfb480SKevin Wolf #include "qapi/qmp/qbool.h"
33ffeaac9bSHu Tao #include "qapi/util.h"
3485186ebdSMax Reitz #include "qapi/qmp/types.h"
3585186ebdSMax Reitz #include "qapi-event.h"
363cce16f4SKevin Wolf #include "trace.h"
371bd0e2d1SChunyan Liu #include "qemu/option_int.h"
38f348b6d1SVeronia Bahaa #include "qemu/cutils.h"
39585f8587Sbellard 
40585f8587Sbellard /*
41585f8587Sbellard   Differences with QCOW:
42585f8587Sbellard 
43585f8587Sbellard   - Support for multiple incremental snapshots.
44585f8587Sbellard   - Memory management by reference counts.
45585f8587Sbellard   - Clusters which have a reference count of one have the bit
46585f8587Sbellard     QCOW_OFLAG_COPIED to optimize write performance.
47585f8587Sbellard   - Size of compressed clusters is stored in sectors to reduce bit usage
48585f8587Sbellard     in the cluster offsets.
49585f8587Sbellard   - Support for storing additional data (such as the VM state) in the
50585f8587Sbellard     snapshots.
51585f8587Sbellard   - If a backing store is used, the cluster size is not constrained
52585f8587Sbellard     (could be backported to QCOW).
53585f8587Sbellard   - L2 tables have always a size of one cluster.
54585f8587Sbellard */
55585f8587Sbellard 
569b80ddf3Saliguori 
579b80ddf3Saliguori typedef struct {
589b80ddf3Saliguori     uint32_t magic;
599b80ddf3Saliguori     uint32_t len;
60c4217f64SJeff Cody } QEMU_PACKED QCowExtension;
6121d82ac9SJeff Cody 
627c80ab3fSJes Sorensen #define  QCOW2_EXT_MAGIC_END 0
637c80ab3fSJes Sorensen #define  QCOW2_EXT_MAGIC_BACKING_FORMAT 0xE2792ACA
64cfcc4c62SKevin Wolf #define  QCOW2_EXT_MAGIC_FEATURE_TABLE 0x6803f857
659b80ddf3Saliguori 
667c80ab3fSJes Sorensen static int qcow2_probe(const uint8_t *buf, int buf_size, const char *filename)
67585f8587Sbellard {
68585f8587Sbellard     const QCowHeader *cow_header = (const void *)buf;
69585f8587Sbellard 
70585f8587Sbellard     if (buf_size >= sizeof(QCowHeader) &&
71585f8587Sbellard         be32_to_cpu(cow_header->magic) == QCOW_MAGIC &&
726744cbabSKevin Wolf         be32_to_cpu(cow_header->version) >= 2)
73585f8587Sbellard         return 100;
74585f8587Sbellard     else
75585f8587Sbellard         return 0;
76585f8587Sbellard }
77585f8587Sbellard 
789b80ddf3Saliguori 
799b80ddf3Saliguori /*
809b80ddf3Saliguori  * read qcow2 extension and fill bs
819b80ddf3Saliguori  * start reading from start_offset
829b80ddf3Saliguori  * finish reading upon magic of value 0 or when end_offset reached
839b80ddf3Saliguori  * unknown magic is skipped (future extension this version knows nothing about)
849b80ddf3Saliguori  * return 0 upon success, non-0 otherwise
859b80ddf3Saliguori  */
867c80ab3fSJes Sorensen static int qcow2_read_extensions(BlockDriverState *bs, uint64_t start_offset,
873ef6c40aSMax Reitz                                  uint64_t end_offset, void **p_feature_table,
883ef6c40aSMax Reitz                                  Error **errp)
899b80ddf3Saliguori {
90ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
919b80ddf3Saliguori     QCowExtension ext;
929b80ddf3Saliguori     uint64_t offset;
9375bab85cSKevin Wolf     int ret;
949b80ddf3Saliguori 
959b80ddf3Saliguori #ifdef DEBUG_EXT
967c80ab3fSJes Sorensen     printf("qcow2_read_extensions: start=%ld end=%ld\n", start_offset, end_offset);
979b80ddf3Saliguori #endif
989b80ddf3Saliguori     offset = start_offset;
999b80ddf3Saliguori     while (offset < end_offset) {
1009b80ddf3Saliguori 
1019b80ddf3Saliguori #ifdef DEBUG_EXT
1029b80ddf3Saliguori         /* Sanity check */
1039b80ddf3Saliguori         if (offset > s->cluster_size)
1047c80ab3fSJes Sorensen             printf("qcow2_read_extension: suspicious offset %lu\n", offset);
1059b80ddf3Saliguori 
1069b2260cbSDong Xu Wang         printf("attempting to read extended header in offset %lu\n", offset);
1079b80ddf3Saliguori #endif
1089b80ddf3Saliguori 
1099a4f4c31SKevin Wolf         ret = bdrv_pread(bs->file->bs, offset, &ext, sizeof(ext));
1103ef6c40aSMax Reitz         if (ret < 0) {
1113ef6c40aSMax Reitz             error_setg_errno(errp, -ret, "qcow2_read_extension: ERROR: "
1123ef6c40aSMax Reitz                              "pread fail from offset %" PRIu64, offset);
1139b80ddf3Saliguori             return 1;
1149b80ddf3Saliguori         }
1159b80ddf3Saliguori         be32_to_cpus(&ext.magic);
1169b80ddf3Saliguori         be32_to_cpus(&ext.len);
1179b80ddf3Saliguori         offset += sizeof(ext);
1189b80ddf3Saliguori #ifdef DEBUG_EXT
1199b80ddf3Saliguori         printf("ext.magic = 0x%x\n", ext.magic);
1209b80ddf3Saliguori #endif
1212ebafc85SKevin Wolf         if (offset > end_offset || ext.len > end_offset - offset) {
1223ef6c40aSMax Reitz             error_setg(errp, "Header extension too large");
12364ca6aeeSKevin Wolf             return -EINVAL;
12464ca6aeeSKevin Wolf         }
12564ca6aeeSKevin Wolf 
1269b80ddf3Saliguori         switch (ext.magic) {
1277c80ab3fSJes Sorensen         case QCOW2_EXT_MAGIC_END:
1289b80ddf3Saliguori             return 0;
129f965509cSaliguori 
1307c80ab3fSJes Sorensen         case QCOW2_EXT_MAGIC_BACKING_FORMAT:
131f965509cSaliguori             if (ext.len >= sizeof(bs->backing_format)) {
132521b2b5dSMax Reitz                 error_setg(errp, "ERROR: ext_backing_format: len=%" PRIu32
133521b2b5dSMax Reitz                            " too large (>=%zu)", ext.len,
134521b2b5dSMax Reitz                            sizeof(bs->backing_format));
135f965509cSaliguori                 return 2;
136f965509cSaliguori             }
1379a4f4c31SKevin Wolf             ret = bdrv_pread(bs->file->bs, offset, bs->backing_format, ext.len);
1383ef6c40aSMax Reitz             if (ret < 0) {
1393ef6c40aSMax Reitz                 error_setg_errno(errp, -ret, "ERROR: ext_backing_format: "
1403ef6c40aSMax Reitz                                  "Could not read format name");
141f965509cSaliguori                 return 3;
1423ef6c40aSMax Reitz             }
143f965509cSaliguori             bs->backing_format[ext.len] = '\0';
144e4603fe1SKevin Wolf             s->image_backing_format = g_strdup(bs->backing_format);
145f965509cSaliguori #ifdef DEBUG_EXT
146f965509cSaliguori             printf("Qcow2: Got format extension %s\n", bs->backing_format);
147f965509cSaliguori #endif
148f965509cSaliguori             break;
149f965509cSaliguori 
150cfcc4c62SKevin Wolf         case QCOW2_EXT_MAGIC_FEATURE_TABLE:
151cfcc4c62SKevin Wolf             if (p_feature_table != NULL) {
152cfcc4c62SKevin Wolf                 void* feature_table = g_malloc0(ext.len + 2 * sizeof(Qcow2Feature));
1539a4f4c31SKevin Wolf                 ret = bdrv_pread(bs->file->bs, offset , feature_table, ext.len);
154cfcc4c62SKevin Wolf                 if (ret < 0) {
1553ef6c40aSMax Reitz                     error_setg_errno(errp, -ret, "ERROR: ext_feature_table: "
1563ef6c40aSMax Reitz                                      "Could not read table");
157cfcc4c62SKevin Wolf                     return ret;
158cfcc4c62SKevin Wolf                 }
159cfcc4c62SKevin Wolf 
160cfcc4c62SKevin Wolf                 *p_feature_table = feature_table;
161cfcc4c62SKevin Wolf             }
162cfcc4c62SKevin Wolf             break;
163cfcc4c62SKevin Wolf 
1649b80ddf3Saliguori         default:
16575bab85cSKevin Wolf             /* unknown magic - save it in case we need to rewrite the header */
16675bab85cSKevin Wolf             {
16775bab85cSKevin Wolf                 Qcow2UnknownHeaderExtension *uext;
16875bab85cSKevin Wolf 
16975bab85cSKevin Wolf                 uext = g_malloc0(sizeof(*uext)  + ext.len);
17075bab85cSKevin Wolf                 uext->magic = ext.magic;
17175bab85cSKevin Wolf                 uext->len = ext.len;
17275bab85cSKevin Wolf                 QLIST_INSERT_HEAD(&s->unknown_header_ext, uext, next);
17375bab85cSKevin Wolf 
1749a4f4c31SKevin Wolf                 ret = bdrv_pread(bs->file->bs, offset , uext->data, uext->len);
17575bab85cSKevin Wolf                 if (ret < 0) {
1763ef6c40aSMax Reitz                     error_setg_errno(errp, -ret, "ERROR: unknown extension: "
1773ef6c40aSMax Reitz                                      "Could not read data");
17875bab85cSKevin Wolf                     return ret;
17975bab85cSKevin Wolf                 }
18075bab85cSKevin Wolf             }
1819b80ddf3Saliguori             break;
1829b80ddf3Saliguori         }
183fd29b4bbSKevin Wolf 
184fd29b4bbSKevin Wolf         offset += ((ext.len + 7) & ~7);
1859b80ddf3Saliguori     }
1869b80ddf3Saliguori 
1879b80ddf3Saliguori     return 0;
1889b80ddf3Saliguori }
1899b80ddf3Saliguori 
19075bab85cSKevin Wolf static void cleanup_unknown_header_ext(BlockDriverState *bs)
19175bab85cSKevin Wolf {
192ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
19375bab85cSKevin Wolf     Qcow2UnknownHeaderExtension *uext, *next;
19475bab85cSKevin Wolf 
19575bab85cSKevin Wolf     QLIST_FOREACH_SAFE(uext, &s->unknown_header_ext, next, next) {
19675bab85cSKevin Wolf         QLIST_REMOVE(uext, next);
19775bab85cSKevin Wolf         g_free(uext);
19875bab85cSKevin Wolf     }
19975bab85cSKevin Wolf }
2009b80ddf3Saliguori 
201a55448b3SMax Reitz static void report_unsupported_feature(Error **errp, Qcow2Feature *table,
202a55448b3SMax Reitz                                        uint64_t mask)
203cfcc4c62SKevin Wolf {
20412ac6d3dSKevin Wolf     char *features = g_strdup("");
20512ac6d3dSKevin Wolf     char *old;
20612ac6d3dSKevin Wolf 
207cfcc4c62SKevin Wolf     while (table && table->name[0] != '\0') {
208cfcc4c62SKevin Wolf         if (table->type == QCOW2_FEAT_TYPE_INCOMPATIBLE) {
20912ac6d3dSKevin Wolf             if (mask & (1ULL << table->bit)) {
21012ac6d3dSKevin Wolf                 old = features;
21112ac6d3dSKevin Wolf                 features = g_strdup_printf("%s%s%.46s", old, *old ? ", " : "",
21212ac6d3dSKevin Wolf                                            table->name);
21312ac6d3dSKevin Wolf                 g_free(old);
21412ac6d3dSKevin Wolf                 mask &= ~(1ULL << table->bit);
215cfcc4c62SKevin Wolf             }
216cfcc4c62SKevin Wolf         }
217cfcc4c62SKevin Wolf         table++;
218cfcc4c62SKevin Wolf     }
219cfcc4c62SKevin Wolf 
220cfcc4c62SKevin Wolf     if (mask) {
22112ac6d3dSKevin Wolf         old = features;
22212ac6d3dSKevin Wolf         features = g_strdup_printf("%s%sUnknown incompatible feature: %" PRIx64,
22312ac6d3dSKevin Wolf                                    old, *old ? ", " : "", mask);
22412ac6d3dSKevin Wolf         g_free(old);
225cfcc4c62SKevin Wolf     }
22612ac6d3dSKevin Wolf 
227a55448b3SMax Reitz     error_setg(errp, "Unsupported qcow2 feature(s): %s", features);
22812ac6d3dSKevin Wolf     g_free(features);
229cfcc4c62SKevin Wolf }
230cfcc4c62SKevin Wolf 
231c61d0004SStefan Hajnoczi /*
232bfe8043eSStefan Hajnoczi  * Sets the dirty bit and flushes afterwards if necessary.
233bfe8043eSStefan Hajnoczi  *
234bfe8043eSStefan Hajnoczi  * The incompatible_features bit is only set if the image file header was
235bfe8043eSStefan Hajnoczi  * updated successfully.  Therefore it is not required to check the return
236bfe8043eSStefan Hajnoczi  * value of this function.
237bfe8043eSStefan Hajnoczi  */
238280d3735SKevin Wolf int qcow2_mark_dirty(BlockDriverState *bs)
239bfe8043eSStefan Hajnoczi {
240ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
241bfe8043eSStefan Hajnoczi     uint64_t val;
242bfe8043eSStefan Hajnoczi     int ret;
243bfe8043eSStefan Hajnoczi 
244bfe8043eSStefan Hajnoczi     assert(s->qcow_version >= 3);
245bfe8043eSStefan Hajnoczi 
246bfe8043eSStefan Hajnoczi     if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
247bfe8043eSStefan Hajnoczi         return 0; /* already dirty */
248bfe8043eSStefan Hajnoczi     }
249bfe8043eSStefan Hajnoczi 
250bfe8043eSStefan Hajnoczi     val = cpu_to_be64(s->incompatible_features | QCOW2_INCOMPAT_DIRTY);
2519a4f4c31SKevin Wolf     ret = bdrv_pwrite(bs->file->bs, offsetof(QCowHeader, incompatible_features),
252bfe8043eSStefan Hajnoczi                       &val, sizeof(val));
253bfe8043eSStefan Hajnoczi     if (ret < 0) {
254bfe8043eSStefan Hajnoczi         return ret;
255bfe8043eSStefan Hajnoczi     }
2569a4f4c31SKevin Wolf     ret = bdrv_flush(bs->file->bs);
257bfe8043eSStefan Hajnoczi     if (ret < 0) {
258bfe8043eSStefan Hajnoczi         return ret;
259bfe8043eSStefan Hajnoczi     }
260bfe8043eSStefan Hajnoczi 
261bfe8043eSStefan Hajnoczi     /* Only treat image as dirty if the header was updated successfully */
262bfe8043eSStefan Hajnoczi     s->incompatible_features |= QCOW2_INCOMPAT_DIRTY;
263bfe8043eSStefan Hajnoczi     return 0;
264bfe8043eSStefan Hajnoczi }
265bfe8043eSStefan Hajnoczi 
266bfe8043eSStefan Hajnoczi /*
267c61d0004SStefan Hajnoczi  * Clears the dirty bit and flushes before if necessary.  Only call this
268c61d0004SStefan Hajnoczi  * function when there are no pending requests, it does not guard against
269c61d0004SStefan Hajnoczi  * concurrent requests dirtying the image.
270c61d0004SStefan Hajnoczi  */
271c61d0004SStefan Hajnoczi static int qcow2_mark_clean(BlockDriverState *bs)
272c61d0004SStefan Hajnoczi {
273ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
274c61d0004SStefan Hajnoczi 
275c61d0004SStefan Hajnoczi     if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
2764c2e5f8fSKevin Wolf         int ret;
2774c2e5f8fSKevin Wolf 
2784c2e5f8fSKevin Wolf         s->incompatible_features &= ~QCOW2_INCOMPAT_DIRTY;
2794c2e5f8fSKevin Wolf 
2804c2e5f8fSKevin Wolf         ret = bdrv_flush(bs);
281c61d0004SStefan Hajnoczi         if (ret < 0) {
282c61d0004SStefan Hajnoczi             return ret;
283c61d0004SStefan Hajnoczi         }
284c61d0004SStefan Hajnoczi 
285c61d0004SStefan Hajnoczi         return qcow2_update_header(bs);
286c61d0004SStefan Hajnoczi     }
287c61d0004SStefan Hajnoczi     return 0;
288c61d0004SStefan Hajnoczi }
289c61d0004SStefan Hajnoczi 
29069c98726SMax Reitz /*
29169c98726SMax Reitz  * Marks the image as corrupt.
29269c98726SMax Reitz  */
29369c98726SMax Reitz int qcow2_mark_corrupt(BlockDriverState *bs)
29469c98726SMax Reitz {
295ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
29669c98726SMax Reitz 
29769c98726SMax Reitz     s->incompatible_features |= QCOW2_INCOMPAT_CORRUPT;
29869c98726SMax Reitz     return qcow2_update_header(bs);
29969c98726SMax Reitz }
30069c98726SMax Reitz 
30169c98726SMax Reitz /*
30269c98726SMax Reitz  * Marks the image as consistent, i.e., unsets the corrupt bit, and flushes
30369c98726SMax Reitz  * before if necessary.
30469c98726SMax Reitz  */
30569c98726SMax Reitz int qcow2_mark_consistent(BlockDriverState *bs)
30669c98726SMax Reitz {
307ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
30869c98726SMax Reitz 
30969c98726SMax Reitz     if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
31069c98726SMax Reitz         int ret = bdrv_flush(bs);
31169c98726SMax Reitz         if (ret < 0) {
31269c98726SMax Reitz             return ret;
31369c98726SMax Reitz         }
31469c98726SMax Reitz 
31569c98726SMax Reitz         s->incompatible_features &= ~QCOW2_INCOMPAT_CORRUPT;
31669c98726SMax Reitz         return qcow2_update_header(bs);
31769c98726SMax Reitz     }
31869c98726SMax Reitz     return 0;
31969c98726SMax Reitz }
32069c98726SMax Reitz 
321acbe5982SStefan Hajnoczi static int qcow2_check(BlockDriverState *bs, BdrvCheckResult *result,
322acbe5982SStefan Hajnoczi                        BdrvCheckMode fix)
323acbe5982SStefan Hajnoczi {
324acbe5982SStefan Hajnoczi     int ret = qcow2_check_refcounts(bs, result, fix);
325acbe5982SStefan Hajnoczi     if (ret < 0) {
326acbe5982SStefan Hajnoczi         return ret;
327acbe5982SStefan Hajnoczi     }
328acbe5982SStefan Hajnoczi 
329acbe5982SStefan Hajnoczi     if (fix && result->check_errors == 0 && result->corruptions == 0) {
33024530f3eSMax Reitz         ret = qcow2_mark_clean(bs);
33124530f3eSMax Reitz         if (ret < 0) {
33224530f3eSMax Reitz             return ret;
33324530f3eSMax Reitz         }
33424530f3eSMax Reitz         return qcow2_mark_consistent(bs);
335acbe5982SStefan Hajnoczi     }
336acbe5982SStefan Hajnoczi     return ret;
337acbe5982SStefan Hajnoczi }
338acbe5982SStefan Hajnoczi 
3398c7de283SKevin Wolf static int validate_table_offset(BlockDriverState *bs, uint64_t offset,
3408c7de283SKevin Wolf                                  uint64_t entries, size_t entry_len)
3418c7de283SKevin Wolf {
342ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
3438c7de283SKevin Wolf     uint64_t size;
3448c7de283SKevin Wolf 
3458c7de283SKevin Wolf     /* Use signed INT64_MAX as the maximum even for uint64_t header fields,
3468c7de283SKevin Wolf      * because values will be passed to qemu functions taking int64_t. */
3478c7de283SKevin Wolf     if (entries > INT64_MAX / entry_len) {
3488c7de283SKevin Wolf         return -EINVAL;
3498c7de283SKevin Wolf     }
3508c7de283SKevin Wolf 
3518c7de283SKevin Wolf     size = entries * entry_len;
3528c7de283SKevin Wolf 
3538c7de283SKevin Wolf     if (INT64_MAX - size < offset) {
3548c7de283SKevin Wolf         return -EINVAL;
3558c7de283SKevin Wolf     }
3568c7de283SKevin Wolf 
3578c7de283SKevin Wolf     /* Tables must be cluster aligned */
3588c7de283SKevin Wolf     if (offset & (s->cluster_size - 1)) {
3598c7de283SKevin Wolf         return -EINVAL;
3608c7de283SKevin Wolf     }
3618c7de283SKevin Wolf 
3628c7de283SKevin Wolf     return 0;
3638c7de283SKevin Wolf }
3648c7de283SKevin Wolf 
36574c4510aSKevin Wolf static QemuOptsList qcow2_runtime_opts = {
36674c4510aSKevin Wolf     .name = "qcow2",
36774c4510aSKevin Wolf     .head = QTAILQ_HEAD_INITIALIZER(qcow2_runtime_opts.head),
36874c4510aSKevin Wolf     .desc = {
36974c4510aSKevin Wolf         {
37064aa99d3SKevin Wolf             .name = QCOW2_OPT_LAZY_REFCOUNTS,
37174c4510aSKevin Wolf             .type = QEMU_OPT_BOOL,
37274c4510aSKevin Wolf             .help = "Postpone refcount updates",
37374c4510aSKevin Wolf         },
37467af674eSKevin Wolf         {
37567af674eSKevin Wolf             .name = QCOW2_OPT_DISCARD_REQUEST,
37667af674eSKevin Wolf             .type = QEMU_OPT_BOOL,
37767af674eSKevin Wolf             .help = "Pass guest discard requests to the layer below",
37867af674eSKevin Wolf         },
37967af674eSKevin Wolf         {
38067af674eSKevin Wolf             .name = QCOW2_OPT_DISCARD_SNAPSHOT,
38167af674eSKevin Wolf             .type = QEMU_OPT_BOOL,
38267af674eSKevin Wolf             .help = "Generate discard requests when snapshot related space "
38367af674eSKevin Wolf                     "is freed",
38467af674eSKevin Wolf         },
38567af674eSKevin Wolf         {
38667af674eSKevin Wolf             .name = QCOW2_OPT_DISCARD_OTHER,
38767af674eSKevin Wolf             .type = QEMU_OPT_BOOL,
38867af674eSKevin Wolf             .help = "Generate discard requests when other clusters are freed",
38967af674eSKevin Wolf         },
39005de7e86SMax Reitz         {
39105de7e86SMax Reitz             .name = QCOW2_OPT_OVERLAP,
39205de7e86SMax Reitz             .type = QEMU_OPT_STRING,
39305de7e86SMax Reitz             .help = "Selects which overlap checks to perform from a range of "
39405de7e86SMax Reitz                     "templates (none, constant, cached, all)",
39505de7e86SMax Reitz         },
39605de7e86SMax Reitz         {
397ee42b5ceSMax Reitz             .name = QCOW2_OPT_OVERLAP_TEMPLATE,
398ee42b5ceSMax Reitz             .type = QEMU_OPT_STRING,
399ee42b5ceSMax Reitz             .help = "Selects which overlap checks to perform from a range of "
400ee42b5ceSMax Reitz                     "templates (none, constant, cached, all)",
401ee42b5ceSMax Reitz         },
402ee42b5ceSMax Reitz         {
40305de7e86SMax Reitz             .name = QCOW2_OPT_OVERLAP_MAIN_HEADER,
40405de7e86SMax Reitz             .type = QEMU_OPT_BOOL,
40505de7e86SMax Reitz             .help = "Check for unintended writes into the main qcow2 header",
40605de7e86SMax Reitz         },
40705de7e86SMax Reitz         {
40805de7e86SMax Reitz             .name = QCOW2_OPT_OVERLAP_ACTIVE_L1,
40905de7e86SMax Reitz             .type = QEMU_OPT_BOOL,
41005de7e86SMax Reitz             .help = "Check for unintended writes into the active L1 table",
41105de7e86SMax Reitz         },
41205de7e86SMax Reitz         {
41305de7e86SMax Reitz             .name = QCOW2_OPT_OVERLAP_ACTIVE_L2,
41405de7e86SMax Reitz             .type = QEMU_OPT_BOOL,
41505de7e86SMax Reitz             .help = "Check for unintended writes into an active L2 table",
41605de7e86SMax Reitz         },
41705de7e86SMax Reitz         {
41805de7e86SMax Reitz             .name = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
41905de7e86SMax Reitz             .type = QEMU_OPT_BOOL,
42005de7e86SMax Reitz             .help = "Check for unintended writes into the refcount table",
42105de7e86SMax Reitz         },
42205de7e86SMax Reitz         {
42305de7e86SMax Reitz             .name = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
42405de7e86SMax Reitz             .type = QEMU_OPT_BOOL,
42505de7e86SMax Reitz             .help = "Check for unintended writes into a refcount block",
42605de7e86SMax Reitz         },
42705de7e86SMax Reitz         {
42805de7e86SMax Reitz             .name = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
42905de7e86SMax Reitz             .type = QEMU_OPT_BOOL,
43005de7e86SMax Reitz             .help = "Check for unintended writes into the snapshot table",
43105de7e86SMax Reitz         },
43205de7e86SMax Reitz         {
43305de7e86SMax Reitz             .name = QCOW2_OPT_OVERLAP_INACTIVE_L1,
43405de7e86SMax Reitz             .type = QEMU_OPT_BOOL,
43505de7e86SMax Reitz             .help = "Check for unintended writes into an inactive L1 table",
43605de7e86SMax Reitz         },
43705de7e86SMax Reitz         {
43805de7e86SMax Reitz             .name = QCOW2_OPT_OVERLAP_INACTIVE_L2,
43905de7e86SMax Reitz             .type = QEMU_OPT_BOOL,
44005de7e86SMax Reitz             .help = "Check for unintended writes into an inactive L2 table",
44105de7e86SMax Reitz         },
4426c1c8d5dSMax Reitz         {
4436c1c8d5dSMax Reitz             .name = QCOW2_OPT_CACHE_SIZE,
4446c1c8d5dSMax Reitz             .type = QEMU_OPT_SIZE,
4456c1c8d5dSMax Reitz             .help = "Maximum combined metadata (L2 tables and refcount blocks) "
4466c1c8d5dSMax Reitz                     "cache size",
4476c1c8d5dSMax Reitz         },
4486c1c8d5dSMax Reitz         {
4496c1c8d5dSMax Reitz             .name = QCOW2_OPT_L2_CACHE_SIZE,
4506c1c8d5dSMax Reitz             .type = QEMU_OPT_SIZE,
4516c1c8d5dSMax Reitz             .help = "Maximum L2 table cache size",
4526c1c8d5dSMax Reitz         },
4536c1c8d5dSMax Reitz         {
4546c1c8d5dSMax Reitz             .name = QCOW2_OPT_REFCOUNT_CACHE_SIZE,
4556c1c8d5dSMax Reitz             .type = QEMU_OPT_SIZE,
4566c1c8d5dSMax Reitz             .help = "Maximum refcount block cache size",
4576c1c8d5dSMax Reitz         },
458279621c0SAlberto Garcia         {
459279621c0SAlberto Garcia             .name = QCOW2_OPT_CACHE_CLEAN_INTERVAL,
460279621c0SAlberto Garcia             .type = QEMU_OPT_NUMBER,
461279621c0SAlberto Garcia             .help = "Clean unused cache entries after this time (in seconds)",
462279621c0SAlberto Garcia         },
46374c4510aSKevin Wolf         { /* end of list */ }
46474c4510aSKevin Wolf     },
46574c4510aSKevin Wolf };
46674c4510aSKevin Wolf 
4674092e99dSMax Reitz static const char *overlap_bool_option_names[QCOW2_OL_MAX_BITNR] = {
4684092e99dSMax Reitz     [QCOW2_OL_MAIN_HEADER_BITNR]    = QCOW2_OPT_OVERLAP_MAIN_HEADER,
4694092e99dSMax Reitz     [QCOW2_OL_ACTIVE_L1_BITNR]      = QCOW2_OPT_OVERLAP_ACTIVE_L1,
4704092e99dSMax Reitz     [QCOW2_OL_ACTIVE_L2_BITNR]      = QCOW2_OPT_OVERLAP_ACTIVE_L2,
4714092e99dSMax Reitz     [QCOW2_OL_REFCOUNT_TABLE_BITNR] = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
4724092e99dSMax Reitz     [QCOW2_OL_REFCOUNT_BLOCK_BITNR] = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
4734092e99dSMax Reitz     [QCOW2_OL_SNAPSHOT_TABLE_BITNR] = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
4744092e99dSMax Reitz     [QCOW2_OL_INACTIVE_L1_BITNR]    = QCOW2_OPT_OVERLAP_INACTIVE_L1,
4754092e99dSMax Reitz     [QCOW2_OL_INACTIVE_L2_BITNR]    = QCOW2_OPT_OVERLAP_INACTIVE_L2,
4764092e99dSMax Reitz };
4774092e99dSMax Reitz 
478279621c0SAlberto Garcia static void cache_clean_timer_cb(void *opaque)
479279621c0SAlberto Garcia {
480279621c0SAlberto Garcia     BlockDriverState *bs = opaque;
481ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
482279621c0SAlberto Garcia     qcow2_cache_clean_unused(bs, s->l2_table_cache);
483279621c0SAlberto Garcia     qcow2_cache_clean_unused(bs, s->refcount_block_cache);
484279621c0SAlberto Garcia     timer_mod(s->cache_clean_timer, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) +
485279621c0SAlberto Garcia               (int64_t) s->cache_clean_interval * 1000);
486279621c0SAlberto Garcia }
487279621c0SAlberto Garcia 
488279621c0SAlberto Garcia static void cache_clean_timer_init(BlockDriverState *bs, AioContext *context)
489279621c0SAlberto Garcia {
490ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
491279621c0SAlberto Garcia     if (s->cache_clean_interval > 0) {
492279621c0SAlberto Garcia         s->cache_clean_timer = aio_timer_new(context, QEMU_CLOCK_VIRTUAL,
493279621c0SAlberto Garcia                                              SCALE_MS, cache_clean_timer_cb,
494279621c0SAlberto Garcia                                              bs);
495279621c0SAlberto Garcia         timer_mod(s->cache_clean_timer, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) +
496279621c0SAlberto Garcia                   (int64_t) s->cache_clean_interval * 1000);
497279621c0SAlberto Garcia     }
498279621c0SAlberto Garcia }
499279621c0SAlberto Garcia 
500279621c0SAlberto Garcia static void cache_clean_timer_del(BlockDriverState *bs)
501279621c0SAlberto Garcia {
502ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
503279621c0SAlberto Garcia     if (s->cache_clean_timer) {
504279621c0SAlberto Garcia         timer_del(s->cache_clean_timer);
505279621c0SAlberto Garcia         timer_free(s->cache_clean_timer);
506279621c0SAlberto Garcia         s->cache_clean_timer = NULL;
507279621c0SAlberto Garcia     }
508279621c0SAlberto Garcia }
509279621c0SAlberto Garcia 
510279621c0SAlberto Garcia static void qcow2_detach_aio_context(BlockDriverState *bs)
511279621c0SAlberto Garcia {
512279621c0SAlberto Garcia     cache_clean_timer_del(bs);
513279621c0SAlberto Garcia }
514279621c0SAlberto Garcia 
515279621c0SAlberto Garcia static void qcow2_attach_aio_context(BlockDriverState *bs,
516279621c0SAlberto Garcia                                      AioContext *new_context)
517279621c0SAlberto Garcia {
518279621c0SAlberto Garcia     cache_clean_timer_init(bs, new_context);
519279621c0SAlberto Garcia }
520279621c0SAlberto Garcia 
521bc85ef26SMax Reitz static void read_cache_sizes(BlockDriverState *bs, QemuOpts *opts,
522bc85ef26SMax Reitz                              uint64_t *l2_cache_size,
5236c1c8d5dSMax Reitz                              uint64_t *refcount_cache_size, Error **errp)
5246c1c8d5dSMax Reitz {
525ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
5266c1c8d5dSMax Reitz     uint64_t combined_cache_size;
5276c1c8d5dSMax Reitz     bool l2_cache_size_set, refcount_cache_size_set, combined_cache_size_set;
5286c1c8d5dSMax Reitz 
5296c1c8d5dSMax Reitz     combined_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_CACHE_SIZE);
5306c1c8d5dSMax Reitz     l2_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_L2_CACHE_SIZE);
5316c1c8d5dSMax Reitz     refcount_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
5326c1c8d5dSMax Reitz 
5336c1c8d5dSMax Reitz     combined_cache_size = qemu_opt_get_size(opts, QCOW2_OPT_CACHE_SIZE, 0);
5346c1c8d5dSMax Reitz     *l2_cache_size = qemu_opt_get_size(opts, QCOW2_OPT_L2_CACHE_SIZE, 0);
5356c1c8d5dSMax Reitz     *refcount_cache_size = qemu_opt_get_size(opts,
5366c1c8d5dSMax Reitz                                              QCOW2_OPT_REFCOUNT_CACHE_SIZE, 0);
5376c1c8d5dSMax Reitz 
5386c1c8d5dSMax Reitz     if (combined_cache_size_set) {
5396c1c8d5dSMax Reitz         if (l2_cache_size_set && refcount_cache_size_set) {
5406c1c8d5dSMax Reitz             error_setg(errp, QCOW2_OPT_CACHE_SIZE ", " QCOW2_OPT_L2_CACHE_SIZE
5416c1c8d5dSMax Reitz                        " and " QCOW2_OPT_REFCOUNT_CACHE_SIZE " may not be set "
5426c1c8d5dSMax Reitz                        "the same time");
5436c1c8d5dSMax Reitz             return;
5446c1c8d5dSMax Reitz         } else if (*l2_cache_size > combined_cache_size) {
5456c1c8d5dSMax Reitz             error_setg(errp, QCOW2_OPT_L2_CACHE_SIZE " may not exceed "
5466c1c8d5dSMax Reitz                        QCOW2_OPT_CACHE_SIZE);
5476c1c8d5dSMax Reitz             return;
5486c1c8d5dSMax Reitz         } else if (*refcount_cache_size > combined_cache_size) {
5496c1c8d5dSMax Reitz             error_setg(errp, QCOW2_OPT_REFCOUNT_CACHE_SIZE " may not exceed "
5506c1c8d5dSMax Reitz                        QCOW2_OPT_CACHE_SIZE);
5516c1c8d5dSMax Reitz             return;
5526c1c8d5dSMax Reitz         }
5536c1c8d5dSMax Reitz 
5546c1c8d5dSMax Reitz         if (l2_cache_size_set) {
5556c1c8d5dSMax Reitz             *refcount_cache_size = combined_cache_size - *l2_cache_size;
5566c1c8d5dSMax Reitz         } else if (refcount_cache_size_set) {
5576c1c8d5dSMax Reitz             *l2_cache_size = combined_cache_size - *refcount_cache_size;
5586c1c8d5dSMax Reitz         } else {
5596c1c8d5dSMax Reitz             *refcount_cache_size = combined_cache_size
5606c1c8d5dSMax Reitz                                  / (DEFAULT_L2_REFCOUNT_SIZE_RATIO + 1);
5616c1c8d5dSMax Reitz             *l2_cache_size = combined_cache_size - *refcount_cache_size;
5626c1c8d5dSMax Reitz         }
5636c1c8d5dSMax Reitz     } else {
5646c1c8d5dSMax Reitz         if (!l2_cache_size_set && !refcount_cache_size_set) {
565bc85ef26SMax Reitz             *l2_cache_size = MAX(DEFAULT_L2_CACHE_BYTE_SIZE,
566bc85ef26SMax Reitz                                  (uint64_t)DEFAULT_L2_CACHE_CLUSTERS
567bc85ef26SMax Reitz                                  * s->cluster_size);
5686c1c8d5dSMax Reitz             *refcount_cache_size = *l2_cache_size
5696c1c8d5dSMax Reitz                                  / DEFAULT_L2_REFCOUNT_SIZE_RATIO;
5706c1c8d5dSMax Reitz         } else if (!l2_cache_size_set) {
5716c1c8d5dSMax Reitz             *l2_cache_size = *refcount_cache_size
5726c1c8d5dSMax Reitz                            * DEFAULT_L2_REFCOUNT_SIZE_RATIO;
5736c1c8d5dSMax Reitz         } else if (!refcount_cache_size_set) {
5746c1c8d5dSMax Reitz             *refcount_cache_size = *l2_cache_size
5756c1c8d5dSMax Reitz                                  / DEFAULT_L2_REFCOUNT_SIZE_RATIO;
5766c1c8d5dSMax Reitz         }
5776c1c8d5dSMax Reitz     }
5786c1c8d5dSMax Reitz }
5796c1c8d5dSMax Reitz 
580ee55b173SKevin Wolf typedef struct Qcow2ReopenState {
581ee55b173SKevin Wolf     Qcow2Cache *l2_table_cache;
582ee55b173SKevin Wolf     Qcow2Cache *refcount_block_cache;
583ee55b173SKevin Wolf     bool use_lazy_refcounts;
584ee55b173SKevin Wolf     int overlap_check;
585ee55b173SKevin Wolf     bool discard_passthrough[QCOW2_DISCARD_MAX];
586ee55b173SKevin Wolf     uint64_t cache_clean_interval;
587ee55b173SKevin Wolf } Qcow2ReopenState;
588ee55b173SKevin Wolf 
589ee55b173SKevin Wolf static int qcow2_update_options_prepare(BlockDriverState *bs,
590ee55b173SKevin Wolf                                         Qcow2ReopenState *r,
591ee55b173SKevin Wolf                                         QDict *options, int flags,
592ee55b173SKevin Wolf                                         Error **errp)
5934c75d1a1SKevin Wolf {
5944c75d1a1SKevin Wolf     BDRVQcow2State *s = bs->opaque;
59594edf3fbSKevin Wolf     QemuOpts *opts = NULL;
5964c75d1a1SKevin Wolf     const char *opt_overlap_check, *opt_overlap_check_template;
5974c75d1a1SKevin Wolf     int overlap_check_template = 0;
59894edf3fbSKevin Wolf     uint64_t l2_cache_size, refcount_cache_size;
5994c75d1a1SKevin Wolf     int i;
60094edf3fbSKevin Wolf     Error *local_err = NULL;
6014c75d1a1SKevin Wolf     int ret;
6024c75d1a1SKevin Wolf 
60394edf3fbSKevin Wolf     opts = qemu_opts_create(&qcow2_runtime_opts, NULL, 0, &error_abort);
60494edf3fbSKevin Wolf     qemu_opts_absorb_qdict(opts, options, &local_err);
60594edf3fbSKevin Wolf     if (local_err) {
60694edf3fbSKevin Wolf         error_propagate(errp, local_err);
60794edf3fbSKevin Wolf         ret = -EINVAL;
60894edf3fbSKevin Wolf         goto fail;
60994edf3fbSKevin Wolf     }
61094edf3fbSKevin Wolf 
61194edf3fbSKevin Wolf     /* get L2 table/refcount block cache size from command line options */
61294edf3fbSKevin Wolf     read_cache_sizes(bs, opts, &l2_cache_size, &refcount_cache_size,
61394edf3fbSKevin Wolf                      &local_err);
61494edf3fbSKevin Wolf     if (local_err) {
61594edf3fbSKevin Wolf         error_propagate(errp, local_err);
61694edf3fbSKevin Wolf         ret = -EINVAL;
61794edf3fbSKevin Wolf         goto fail;
61894edf3fbSKevin Wolf     }
61994edf3fbSKevin Wolf 
62094edf3fbSKevin Wolf     l2_cache_size /= s->cluster_size;
62194edf3fbSKevin Wolf     if (l2_cache_size < MIN_L2_CACHE_SIZE) {
62294edf3fbSKevin Wolf         l2_cache_size = MIN_L2_CACHE_SIZE;
62394edf3fbSKevin Wolf     }
62494edf3fbSKevin Wolf     if (l2_cache_size > INT_MAX) {
62594edf3fbSKevin Wolf         error_setg(errp, "L2 cache size too big");
62694edf3fbSKevin Wolf         ret = -EINVAL;
62794edf3fbSKevin Wolf         goto fail;
62894edf3fbSKevin Wolf     }
62994edf3fbSKevin Wolf 
63094edf3fbSKevin Wolf     refcount_cache_size /= s->cluster_size;
63194edf3fbSKevin Wolf     if (refcount_cache_size < MIN_REFCOUNT_CACHE_SIZE) {
63294edf3fbSKevin Wolf         refcount_cache_size = MIN_REFCOUNT_CACHE_SIZE;
63394edf3fbSKevin Wolf     }
63494edf3fbSKevin Wolf     if (refcount_cache_size > INT_MAX) {
63594edf3fbSKevin Wolf         error_setg(errp, "Refcount cache size too big");
63694edf3fbSKevin Wolf         ret = -EINVAL;
63794edf3fbSKevin Wolf         goto fail;
63894edf3fbSKevin Wolf     }
63994edf3fbSKevin Wolf 
6405b0959a7SKevin Wolf     /* alloc new L2 table/refcount block cache, flush old one */
6415b0959a7SKevin Wolf     if (s->l2_table_cache) {
6425b0959a7SKevin Wolf         ret = qcow2_cache_flush(bs, s->l2_table_cache);
6435b0959a7SKevin Wolf         if (ret) {
6445b0959a7SKevin Wolf             error_setg_errno(errp, -ret, "Failed to flush the L2 table cache");
6455b0959a7SKevin Wolf             goto fail;
6465b0959a7SKevin Wolf         }
6475b0959a7SKevin Wolf     }
6485b0959a7SKevin Wolf 
6495b0959a7SKevin Wolf     if (s->refcount_block_cache) {
6505b0959a7SKevin Wolf         ret = qcow2_cache_flush(bs, s->refcount_block_cache);
6515b0959a7SKevin Wolf         if (ret) {
6525b0959a7SKevin Wolf             error_setg_errno(errp, -ret,
6535b0959a7SKevin Wolf                              "Failed to flush the refcount block cache");
6545b0959a7SKevin Wolf             goto fail;
6555b0959a7SKevin Wolf         }
6565b0959a7SKevin Wolf     }
6575b0959a7SKevin Wolf 
658ee55b173SKevin Wolf     r->l2_table_cache = qcow2_cache_create(bs, l2_cache_size);
659ee55b173SKevin Wolf     r->refcount_block_cache = qcow2_cache_create(bs, refcount_cache_size);
660ee55b173SKevin Wolf     if (r->l2_table_cache == NULL || r->refcount_block_cache == NULL) {
66194edf3fbSKevin Wolf         error_setg(errp, "Could not allocate metadata caches");
66294edf3fbSKevin Wolf         ret = -ENOMEM;
66394edf3fbSKevin Wolf         goto fail;
66494edf3fbSKevin Wolf     }
66594edf3fbSKevin Wolf 
66694edf3fbSKevin Wolf     /* New interval for cache cleanup timer */
667ee55b173SKevin Wolf     r->cache_clean_interval =
6685b0959a7SKevin Wolf         qemu_opt_get_number(opts, QCOW2_OPT_CACHE_CLEAN_INTERVAL,
6695b0959a7SKevin Wolf                             s->cache_clean_interval);
670ee55b173SKevin Wolf     if (r->cache_clean_interval > UINT_MAX) {
67194edf3fbSKevin Wolf         error_setg(errp, "Cache clean interval too big");
67294edf3fbSKevin Wolf         ret = -EINVAL;
67394edf3fbSKevin Wolf         goto fail;
67494edf3fbSKevin Wolf     }
67594edf3fbSKevin Wolf 
6765b0959a7SKevin Wolf     /* lazy-refcounts; flush if going from enabled to disabled */
677ee55b173SKevin Wolf     r->use_lazy_refcounts = qemu_opt_get_bool(opts, QCOW2_OPT_LAZY_REFCOUNTS,
6784c75d1a1SKevin Wolf         (s->compatible_features & QCOW2_COMPAT_LAZY_REFCOUNTS));
679ee55b173SKevin Wolf     if (r->use_lazy_refcounts && s->qcow_version < 3) {
680007dbc39SKevin Wolf         error_setg(errp, "Lazy refcounts require a qcow2 image with at least "
681007dbc39SKevin Wolf                    "qemu 1.1 compatibility level");
682007dbc39SKevin Wolf         ret = -EINVAL;
683007dbc39SKevin Wolf         goto fail;
684007dbc39SKevin Wolf     }
6854c75d1a1SKevin Wolf 
6865b0959a7SKevin Wolf     if (s->use_lazy_refcounts && !r->use_lazy_refcounts) {
6875b0959a7SKevin Wolf         ret = qcow2_mark_clean(bs);
6885b0959a7SKevin Wolf         if (ret < 0) {
6895b0959a7SKevin Wolf             error_setg_errno(errp, -ret, "Failed to disable lazy refcounts");
6905b0959a7SKevin Wolf             goto fail;
6915b0959a7SKevin Wolf         }
6925b0959a7SKevin Wolf     }
6935b0959a7SKevin Wolf 
694007dbc39SKevin Wolf     /* Overlap check options */
6954c75d1a1SKevin Wolf     opt_overlap_check = qemu_opt_get(opts, QCOW2_OPT_OVERLAP);
6964c75d1a1SKevin Wolf     opt_overlap_check_template = qemu_opt_get(opts, QCOW2_OPT_OVERLAP_TEMPLATE);
6974c75d1a1SKevin Wolf     if (opt_overlap_check_template && opt_overlap_check &&
6984c75d1a1SKevin Wolf         strcmp(opt_overlap_check_template, opt_overlap_check))
6994c75d1a1SKevin Wolf     {
7004c75d1a1SKevin Wolf         error_setg(errp, "Conflicting values for qcow2 options '"
7014c75d1a1SKevin Wolf                    QCOW2_OPT_OVERLAP "' ('%s') and '" QCOW2_OPT_OVERLAP_TEMPLATE
7024c75d1a1SKevin Wolf                    "' ('%s')", opt_overlap_check, opt_overlap_check_template);
7034c75d1a1SKevin Wolf         ret = -EINVAL;
7044c75d1a1SKevin Wolf         goto fail;
7054c75d1a1SKevin Wolf     }
7064c75d1a1SKevin Wolf     if (!opt_overlap_check) {
7074c75d1a1SKevin Wolf         opt_overlap_check = opt_overlap_check_template ?: "cached";
7084c75d1a1SKevin Wolf     }
7094c75d1a1SKevin Wolf 
7104c75d1a1SKevin Wolf     if (!strcmp(opt_overlap_check, "none")) {
7114c75d1a1SKevin Wolf         overlap_check_template = 0;
7124c75d1a1SKevin Wolf     } else if (!strcmp(opt_overlap_check, "constant")) {
7134c75d1a1SKevin Wolf         overlap_check_template = QCOW2_OL_CONSTANT;
7144c75d1a1SKevin Wolf     } else if (!strcmp(opt_overlap_check, "cached")) {
7154c75d1a1SKevin Wolf         overlap_check_template = QCOW2_OL_CACHED;
7164c75d1a1SKevin Wolf     } else if (!strcmp(opt_overlap_check, "all")) {
7174c75d1a1SKevin Wolf         overlap_check_template = QCOW2_OL_ALL;
7184c75d1a1SKevin Wolf     } else {
7194c75d1a1SKevin Wolf         error_setg(errp, "Unsupported value '%s' for qcow2 option "
7204c75d1a1SKevin Wolf                    "'overlap-check'. Allowed are any of the following: "
7214c75d1a1SKevin Wolf                    "none, constant, cached, all", opt_overlap_check);
7224c75d1a1SKevin Wolf         ret = -EINVAL;
7234c75d1a1SKevin Wolf         goto fail;
7244c75d1a1SKevin Wolf     }
7254c75d1a1SKevin Wolf 
726ee55b173SKevin Wolf     r->overlap_check = 0;
7274c75d1a1SKevin Wolf     for (i = 0; i < QCOW2_OL_MAX_BITNR; i++) {
7284c75d1a1SKevin Wolf         /* overlap-check defines a template bitmask, but every flag may be
7294c75d1a1SKevin Wolf          * overwritten through the associated boolean option */
730ee55b173SKevin Wolf         r->overlap_check |=
7314c75d1a1SKevin Wolf             qemu_opt_get_bool(opts, overlap_bool_option_names[i],
7324c75d1a1SKevin Wolf                               overlap_check_template & (1 << i)) << i;
7334c75d1a1SKevin Wolf     }
7344c75d1a1SKevin Wolf 
735ee55b173SKevin Wolf     r->discard_passthrough[QCOW2_DISCARD_NEVER] = false;
736ee55b173SKevin Wolf     r->discard_passthrough[QCOW2_DISCARD_ALWAYS] = true;
737ee55b173SKevin Wolf     r->discard_passthrough[QCOW2_DISCARD_REQUEST] =
738007dbc39SKevin Wolf         qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_REQUEST,
739007dbc39SKevin Wolf                           flags & BDRV_O_UNMAP);
740ee55b173SKevin Wolf     r->discard_passthrough[QCOW2_DISCARD_SNAPSHOT] =
741007dbc39SKevin Wolf         qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_SNAPSHOT, true);
742ee55b173SKevin Wolf     r->discard_passthrough[QCOW2_DISCARD_OTHER] =
743007dbc39SKevin Wolf         qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_OTHER, false);
744007dbc39SKevin Wolf 
7454c75d1a1SKevin Wolf     ret = 0;
7464c75d1a1SKevin Wolf fail:
74794edf3fbSKevin Wolf     qemu_opts_del(opts);
74894edf3fbSKevin Wolf     opts = NULL;
749ee55b173SKevin Wolf     return ret;
750ee55b173SKevin Wolf }
751ee55b173SKevin Wolf 
752ee55b173SKevin Wolf static void qcow2_update_options_commit(BlockDriverState *bs,
753ee55b173SKevin Wolf                                         Qcow2ReopenState *r)
754ee55b173SKevin Wolf {
755ee55b173SKevin Wolf     BDRVQcow2State *s = bs->opaque;
756ee55b173SKevin Wolf     int i;
757ee55b173SKevin Wolf 
7585b0959a7SKevin Wolf     if (s->l2_table_cache) {
7595b0959a7SKevin Wolf         qcow2_cache_destroy(bs, s->l2_table_cache);
7605b0959a7SKevin Wolf     }
7615b0959a7SKevin Wolf     if (s->refcount_block_cache) {
7625b0959a7SKevin Wolf         qcow2_cache_destroy(bs, s->refcount_block_cache);
7635b0959a7SKevin Wolf     }
764ee55b173SKevin Wolf     s->l2_table_cache = r->l2_table_cache;
765ee55b173SKevin Wolf     s->refcount_block_cache = r->refcount_block_cache;
766ee55b173SKevin Wolf 
767ee55b173SKevin Wolf     s->overlap_check = r->overlap_check;
768ee55b173SKevin Wolf     s->use_lazy_refcounts = r->use_lazy_refcounts;
769ee55b173SKevin Wolf 
770ee55b173SKevin Wolf     for (i = 0; i < QCOW2_DISCARD_MAX; i++) {
771ee55b173SKevin Wolf         s->discard_passthrough[i] = r->discard_passthrough[i];
772ee55b173SKevin Wolf     }
773ee55b173SKevin Wolf 
7745b0959a7SKevin Wolf     if (s->cache_clean_interval != r->cache_clean_interval) {
7755b0959a7SKevin Wolf         cache_clean_timer_del(bs);
776ee55b173SKevin Wolf         s->cache_clean_interval = r->cache_clean_interval;
777ee55b173SKevin Wolf         cache_clean_timer_init(bs, bdrv_get_aio_context(bs));
778ee55b173SKevin Wolf     }
7795b0959a7SKevin Wolf }
780ee55b173SKevin Wolf 
781ee55b173SKevin Wolf static void qcow2_update_options_abort(BlockDriverState *bs,
782ee55b173SKevin Wolf                                        Qcow2ReopenState *r)
783ee55b173SKevin Wolf {
784ee55b173SKevin Wolf     if (r->l2_table_cache) {
785ee55b173SKevin Wolf         qcow2_cache_destroy(bs, r->l2_table_cache);
786ee55b173SKevin Wolf     }
787ee55b173SKevin Wolf     if (r->refcount_block_cache) {
788ee55b173SKevin Wolf         qcow2_cache_destroy(bs, r->refcount_block_cache);
789ee55b173SKevin Wolf     }
790ee55b173SKevin Wolf }
791ee55b173SKevin Wolf 
792ee55b173SKevin Wolf static int qcow2_update_options(BlockDriverState *bs, QDict *options,
793ee55b173SKevin Wolf                                 int flags, Error **errp)
794ee55b173SKevin Wolf {
795ee55b173SKevin Wolf     Qcow2ReopenState r = {};
796ee55b173SKevin Wolf     int ret;
797ee55b173SKevin Wolf 
798ee55b173SKevin Wolf     ret = qcow2_update_options_prepare(bs, &r, options, flags, errp);
799ee55b173SKevin Wolf     if (ret >= 0) {
800ee55b173SKevin Wolf         qcow2_update_options_commit(bs, &r);
801ee55b173SKevin Wolf     } else {
802ee55b173SKevin Wolf         qcow2_update_options_abort(bs, &r);
803ee55b173SKevin Wolf     }
80494edf3fbSKevin Wolf 
8054c75d1a1SKevin Wolf     return ret;
8064c75d1a1SKevin Wolf }
8074c75d1a1SKevin Wolf 
808015a1036SMax Reitz static int qcow2_open(BlockDriverState *bs, QDict *options, int flags,
809015a1036SMax Reitz                       Error **errp)
810585f8587Sbellard {
811ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
8126d33e8e7SKevin Wolf     unsigned int len, i;
8136d33e8e7SKevin Wolf     int ret = 0;
814585f8587Sbellard     QCowHeader header;
81574c4510aSKevin Wolf     Error *local_err = NULL;
8169b80ddf3Saliguori     uint64_t ext_end;
8172cf7cfa1SKevin Wolf     uint64_t l1_vm_state_index;
818585f8587Sbellard 
8199a4f4c31SKevin Wolf     ret = bdrv_pread(bs->file->bs, 0, &header, sizeof(header));
8206d85a57eSJes Sorensen     if (ret < 0) {
8213ef6c40aSMax Reitz         error_setg_errno(errp, -ret, "Could not read qcow2 header");
822585f8587Sbellard         goto fail;
8236d85a57eSJes Sorensen     }
824585f8587Sbellard     be32_to_cpus(&header.magic);
825585f8587Sbellard     be32_to_cpus(&header.version);
826585f8587Sbellard     be64_to_cpus(&header.backing_file_offset);
827585f8587Sbellard     be32_to_cpus(&header.backing_file_size);
828585f8587Sbellard     be64_to_cpus(&header.size);
829585f8587Sbellard     be32_to_cpus(&header.cluster_bits);
830585f8587Sbellard     be32_to_cpus(&header.crypt_method);
831585f8587Sbellard     be64_to_cpus(&header.l1_table_offset);
832585f8587Sbellard     be32_to_cpus(&header.l1_size);
833585f8587Sbellard     be64_to_cpus(&header.refcount_table_offset);
834585f8587Sbellard     be32_to_cpus(&header.refcount_table_clusters);
835585f8587Sbellard     be64_to_cpus(&header.snapshots_offset);
836585f8587Sbellard     be32_to_cpus(&header.nb_snapshots);
837585f8587Sbellard 
838e8cdcec1SKevin Wolf     if (header.magic != QCOW_MAGIC) {
8393ef6c40aSMax Reitz         error_setg(errp, "Image is not in qcow2 format");
84076abe407SPaolo Bonzini         ret = -EINVAL;
841585f8587Sbellard         goto fail;
8426d85a57eSJes Sorensen     }
8436744cbabSKevin Wolf     if (header.version < 2 || header.version > 3) {
844a55448b3SMax Reitz         error_setg(errp, "Unsupported qcow2 version %" PRIu32, header.version);
845e8cdcec1SKevin Wolf         ret = -ENOTSUP;
846e8cdcec1SKevin Wolf         goto fail;
847e8cdcec1SKevin Wolf     }
8486744cbabSKevin Wolf 
8496744cbabSKevin Wolf     s->qcow_version = header.version;
8506744cbabSKevin Wolf 
85124342f2cSKevin Wolf     /* Initialise cluster size */
85224342f2cSKevin Wolf     if (header.cluster_bits < MIN_CLUSTER_BITS ||
85324342f2cSKevin Wolf         header.cluster_bits > MAX_CLUSTER_BITS) {
854521b2b5dSMax Reitz         error_setg(errp, "Unsupported cluster size: 2^%" PRIu32,
855521b2b5dSMax Reitz                    header.cluster_bits);
85624342f2cSKevin Wolf         ret = -EINVAL;
85724342f2cSKevin Wolf         goto fail;
85824342f2cSKevin Wolf     }
85924342f2cSKevin Wolf 
86024342f2cSKevin Wolf     s->cluster_bits = header.cluster_bits;
86124342f2cSKevin Wolf     s->cluster_size = 1 << s->cluster_bits;
86224342f2cSKevin Wolf     s->cluster_sectors = 1 << (s->cluster_bits - 9);
86324342f2cSKevin Wolf 
8646744cbabSKevin Wolf     /* Initialise version 3 header fields */
8656744cbabSKevin Wolf     if (header.version == 2) {
8666744cbabSKevin Wolf         header.incompatible_features    = 0;
8676744cbabSKevin Wolf         header.compatible_features      = 0;
8686744cbabSKevin Wolf         header.autoclear_features       = 0;
8696744cbabSKevin Wolf         header.refcount_order           = 4;
8706744cbabSKevin Wolf         header.header_length            = 72;
8716744cbabSKevin Wolf     } else {
8726744cbabSKevin Wolf         be64_to_cpus(&header.incompatible_features);
8736744cbabSKevin Wolf         be64_to_cpus(&header.compatible_features);
8746744cbabSKevin Wolf         be64_to_cpus(&header.autoclear_features);
8756744cbabSKevin Wolf         be32_to_cpus(&header.refcount_order);
8766744cbabSKevin Wolf         be32_to_cpus(&header.header_length);
87724342f2cSKevin Wolf 
87824342f2cSKevin Wolf         if (header.header_length < 104) {
87924342f2cSKevin Wolf             error_setg(errp, "qcow2 header too short");
88024342f2cSKevin Wolf             ret = -EINVAL;
88124342f2cSKevin Wolf             goto fail;
88224342f2cSKevin Wolf         }
88324342f2cSKevin Wolf     }
88424342f2cSKevin Wolf 
88524342f2cSKevin Wolf     if (header.header_length > s->cluster_size) {
88624342f2cSKevin Wolf         error_setg(errp, "qcow2 header exceeds cluster size");
88724342f2cSKevin Wolf         ret = -EINVAL;
88824342f2cSKevin Wolf         goto fail;
8896744cbabSKevin Wolf     }
8906744cbabSKevin Wolf 
8916744cbabSKevin Wolf     if (header.header_length > sizeof(header)) {
8926744cbabSKevin Wolf         s->unknown_header_fields_size = header.header_length - sizeof(header);
8936744cbabSKevin Wolf         s->unknown_header_fields = g_malloc(s->unknown_header_fields_size);
8949a4f4c31SKevin Wolf         ret = bdrv_pread(bs->file->bs, sizeof(header), s->unknown_header_fields,
8956744cbabSKevin Wolf                          s->unknown_header_fields_size);
8966744cbabSKevin Wolf         if (ret < 0) {
8973ef6c40aSMax Reitz             error_setg_errno(errp, -ret, "Could not read unknown qcow2 header "
8983ef6c40aSMax Reitz                              "fields");
8996744cbabSKevin Wolf             goto fail;
9006744cbabSKevin Wolf         }
9016744cbabSKevin Wolf     }
9026744cbabSKevin Wolf 
903a1b3955cSKevin Wolf     if (header.backing_file_offset > s->cluster_size) {
904a1b3955cSKevin Wolf         error_setg(errp, "Invalid backing file offset");
905a1b3955cSKevin Wolf         ret = -EINVAL;
906a1b3955cSKevin Wolf         goto fail;
907a1b3955cSKevin Wolf     }
908a1b3955cSKevin Wolf 
909cfcc4c62SKevin Wolf     if (header.backing_file_offset) {
910cfcc4c62SKevin Wolf         ext_end = header.backing_file_offset;
911cfcc4c62SKevin Wolf     } else {
912cfcc4c62SKevin Wolf         ext_end = 1 << header.cluster_bits;
913cfcc4c62SKevin Wolf     }
914cfcc4c62SKevin Wolf 
9156744cbabSKevin Wolf     /* Handle feature bits */
9166744cbabSKevin Wolf     s->incompatible_features    = header.incompatible_features;
9176744cbabSKevin Wolf     s->compatible_features      = header.compatible_features;
9186744cbabSKevin Wolf     s->autoclear_features       = header.autoclear_features;
9196744cbabSKevin Wolf 
920c61d0004SStefan Hajnoczi     if (s->incompatible_features & ~QCOW2_INCOMPAT_MASK) {
921cfcc4c62SKevin Wolf         void *feature_table = NULL;
922cfcc4c62SKevin Wolf         qcow2_read_extensions(bs, header.header_length, ext_end,
9233ef6c40aSMax Reitz                               &feature_table, NULL);
924a55448b3SMax Reitz         report_unsupported_feature(errp, feature_table,
925c61d0004SStefan Hajnoczi                                    s->incompatible_features &
926c61d0004SStefan Hajnoczi                                    ~QCOW2_INCOMPAT_MASK);
9276744cbabSKevin Wolf         ret = -ENOTSUP;
928c5a33ee9SPrasad Joshi         g_free(feature_table);
9296744cbabSKevin Wolf         goto fail;
9306744cbabSKevin Wolf     }
9316744cbabSKevin Wolf 
93269c98726SMax Reitz     if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
93369c98726SMax Reitz         /* Corrupt images may not be written to unless they are being repaired
93469c98726SMax Reitz          */
93569c98726SMax Reitz         if ((flags & BDRV_O_RDWR) && !(flags & BDRV_O_CHECK)) {
9363ef6c40aSMax Reitz             error_setg(errp, "qcow2: Image is corrupt; cannot be opened "
9373ef6c40aSMax Reitz                        "read/write");
93869c98726SMax Reitz             ret = -EACCES;
93969c98726SMax Reitz             goto fail;
94069c98726SMax Reitz         }
94169c98726SMax Reitz     }
94269c98726SMax Reitz 
9436744cbabSKevin Wolf     /* Check support for various header values */
944b72faf9fSMax Reitz     if (header.refcount_order > 6) {
945b72faf9fSMax Reitz         error_setg(errp, "Reference count entry width too large; may not "
946b72faf9fSMax Reitz                    "exceed 64 bits");
947b72faf9fSMax Reitz         ret = -EINVAL;
9486744cbabSKevin Wolf         goto fail;
9496744cbabSKevin Wolf     }
950b6481f37SMax Reitz     s->refcount_order = header.refcount_order;
951346a53dfSMax Reitz     s->refcount_bits = 1 << s->refcount_order;
952346a53dfSMax Reitz     s->refcount_max = UINT64_C(1) << (s->refcount_bits - 1);
953346a53dfSMax Reitz     s->refcount_max += s->refcount_max - 1;
9546744cbabSKevin Wolf 
9556d85a57eSJes Sorensen     if (header.crypt_method > QCOW_CRYPT_AES) {
956521b2b5dSMax Reitz         error_setg(errp, "Unsupported encryption method: %" PRIu32,
9573ef6c40aSMax Reitz                    header.crypt_method);
9586d85a57eSJes Sorensen         ret = -EINVAL;
959585f8587Sbellard         goto fail;
9606d85a57eSJes Sorensen     }
961f6fa64f6SDaniel P. Berrange     if (!qcrypto_cipher_supports(QCRYPTO_CIPHER_ALG_AES_128)) {
962f6fa64f6SDaniel P. Berrange         error_setg(errp, "AES cipher not available");
963f6fa64f6SDaniel P. Berrange         ret = -EINVAL;
964f6fa64f6SDaniel P. Berrange         goto fail;
965f6fa64f6SDaniel P. Berrange     }
966585f8587Sbellard     s->crypt_method_header = header.crypt_method;
9676d85a57eSJes Sorensen     if (s->crypt_method_header) {
968e6ff69bfSDaniel P. Berrange         if (bdrv_uses_whitelist() &&
969e6ff69bfSDaniel P. Berrange             s->crypt_method_header == QCOW_CRYPT_AES) {
970e6ff69bfSDaniel P. Berrange             error_report("qcow2 built-in AES encryption is deprecated");
971e6ff69bfSDaniel P. Berrange             error_printf("Support for it will be removed in a future release.\n"
972e6ff69bfSDaniel P. Berrange                          "You can use 'qemu-img convert' to switch to an\n"
973e6ff69bfSDaniel P. Berrange                          "unencrypted qcow2 image, or a LUKS raw image.\n");
974e6ff69bfSDaniel P. Berrange         }
975e6ff69bfSDaniel P. Berrange 
976585f8587Sbellard         bs->encrypted = 1;
9776d85a57eSJes Sorensen     }
97824342f2cSKevin Wolf 
979585f8587Sbellard     s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */
980585f8587Sbellard     s->l2_size = 1 << s->l2_bits;
9811d13d654SMax Reitz     /* 2^(s->refcount_order - 3) is the refcount width in bytes */
9821d13d654SMax Reitz     s->refcount_block_bits = s->cluster_bits - (s->refcount_order - 3);
9831d13d654SMax Reitz     s->refcount_block_size = 1 << s->refcount_block_bits;
984585f8587Sbellard     bs->total_sectors = header.size / 512;
985585f8587Sbellard     s->csize_shift = (62 - (s->cluster_bits - 8));
986585f8587Sbellard     s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;
987585f8587Sbellard     s->cluster_offset_mask = (1LL << s->csize_shift) - 1;
9885dab2fadSKevin Wolf 
989585f8587Sbellard     s->refcount_table_offset = header.refcount_table_offset;
990585f8587Sbellard     s->refcount_table_size =
991585f8587Sbellard         header.refcount_table_clusters << (s->cluster_bits - 3);
992585f8587Sbellard 
9932b5d5953SKevin Wolf     if (header.refcount_table_clusters > qcow2_max_refcount_clusters(s)) {
9945dab2fadSKevin Wolf         error_setg(errp, "Reference count table too large");
9955dab2fadSKevin Wolf         ret = -EINVAL;
9965dab2fadSKevin Wolf         goto fail;
9975dab2fadSKevin Wolf     }
9985dab2fadSKevin Wolf 
9998c7de283SKevin Wolf     ret = validate_table_offset(bs, s->refcount_table_offset,
10008c7de283SKevin Wolf                                 s->refcount_table_size, sizeof(uint64_t));
10018c7de283SKevin Wolf     if (ret < 0) {
10028c7de283SKevin Wolf         error_setg(errp, "Invalid reference count table offset");
10038c7de283SKevin Wolf         goto fail;
10048c7de283SKevin Wolf     }
10058c7de283SKevin Wolf 
1006ce48f2f4SKevin Wolf     /* Snapshot table offset/length */
1007ce48f2f4SKevin Wolf     if (header.nb_snapshots > QCOW_MAX_SNAPSHOTS) {
1008ce48f2f4SKevin Wolf         error_setg(errp, "Too many snapshots");
1009ce48f2f4SKevin Wolf         ret = -EINVAL;
1010ce48f2f4SKevin Wolf         goto fail;
1011ce48f2f4SKevin Wolf     }
1012ce48f2f4SKevin Wolf 
1013ce48f2f4SKevin Wolf     ret = validate_table_offset(bs, header.snapshots_offset,
1014ce48f2f4SKevin Wolf                                 header.nb_snapshots,
1015ce48f2f4SKevin Wolf                                 sizeof(QCowSnapshotHeader));
1016ce48f2f4SKevin Wolf     if (ret < 0) {
1017ce48f2f4SKevin Wolf         error_setg(errp, "Invalid snapshot table offset");
1018ce48f2f4SKevin Wolf         goto fail;
1019ce48f2f4SKevin Wolf     }
1020ce48f2f4SKevin Wolf 
1021585f8587Sbellard     /* read the level 1 table */
102287b86e7eSWen Congyang     if (header.l1_size > QCOW_MAX_L1_SIZE / sizeof(uint64_t)) {
10232d51c32cSKevin Wolf         error_setg(errp, "Active L1 table too large");
10242d51c32cSKevin Wolf         ret = -EFBIG;
10252d51c32cSKevin Wolf         goto fail;
10262d51c32cSKevin Wolf     }
1027585f8587Sbellard     s->l1_size = header.l1_size;
10282cf7cfa1SKevin Wolf 
10292cf7cfa1SKevin Wolf     l1_vm_state_index = size_to_l1(s, header.size);
10302cf7cfa1SKevin Wolf     if (l1_vm_state_index > INT_MAX) {
10313ef6c40aSMax Reitz         error_setg(errp, "Image is too big");
10322cf7cfa1SKevin Wolf         ret = -EFBIG;
10332cf7cfa1SKevin Wolf         goto fail;
10342cf7cfa1SKevin Wolf     }
10352cf7cfa1SKevin Wolf     s->l1_vm_state_index = l1_vm_state_index;
10362cf7cfa1SKevin Wolf 
1037585f8587Sbellard     /* the L1 table must contain at least enough entries to put
1038585f8587Sbellard        header.size bytes */
10396d85a57eSJes Sorensen     if (s->l1_size < s->l1_vm_state_index) {
10403ef6c40aSMax Reitz         error_setg(errp, "L1 table is too small");
10416d85a57eSJes Sorensen         ret = -EINVAL;
1042585f8587Sbellard         goto fail;
10436d85a57eSJes Sorensen     }
10442d51c32cSKevin Wolf 
10452d51c32cSKevin Wolf     ret = validate_table_offset(bs, header.l1_table_offset,
10462d51c32cSKevin Wolf                                 header.l1_size, sizeof(uint64_t));
10472d51c32cSKevin Wolf     if (ret < 0) {
10482d51c32cSKevin Wolf         error_setg(errp, "Invalid L1 table offset");
10492d51c32cSKevin Wolf         goto fail;
10502d51c32cSKevin Wolf     }
1051585f8587Sbellard     s->l1_table_offset = header.l1_table_offset;
10522d51c32cSKevin Wolf 
10532d51c32cSKevin Wolf 
1054d191d12dSStefan Weil     if (s->l1_size > 0) {
10559a4f4c31SKevin Wolf         s->l1_table = qemu_try_blockalign(bs->file->bs,
10563f6a3ee5SKevin Wolf             align_offset(s->l1_size * sizeof(uint64_t), 512));
1057de82815dSKevin Wolf         if (s->l1_table == NULL) {
1058de82815dSKevin Wolf             error_setg(errp, "Could not allocate L1 table");
1059de82815dSKevin Wolf             ret = -ENOMEM;
1060de82815dSKevin Wolf             goto fail;
1061de82815dSKevin Wolf         }
10629a4f4c31SKevin Wolf         ret = bdrv_pread(bs->file->bs, s->l1_table_offset, s->l1_table,
10636d85a57eSJes Sorensen                          s->l1_size * sizeof(uint64_t));
10646d85a57eSJes Sorensen         if (ret < 0) {
10653ef6c40aSMax Reitz             error_setg_errno(errp, -ret, "Could not read L1 table");
1066585f8587Sbellard             goto fail;
10676d85a57eSJes Sorensen         }
1068585f8587Sbellard         for(i = 0;i < s->l1_size; i++) {
1069585f8587Sbellard             be64_to_cpus(&s->l1_table[i]);
1070585f8587Sbellard         }
1071d191d12dSStefan Weil     }
107229c1a730SKevin Wolf 
107394edf3fbSKevin Wolf     /* Parse driver-specific options */
107494edf3fbSKevin Wolf     ret = qcow2_update_options(bs, options, flags, errp);
107590efa0eaSKevin Wolf     if (ret < 0) {
107690efa0eaSKevin Wolf         goto fail;
107790efa0eaSKevin Wolf     }
107890efa0eaSKevin Wolf 
10797267c094SAnthony Liguori     s->cluster_cache = g_malloc(s->cluster_size);
1080585f8587Sbellard     /* one more sector for decompressed data alignment */
10819a4f4c31SKevin Wolf     s->cluster_data = qemu_try_blockalign(bs->file->bs, QCOW_MAX_CRYPT_CLUSTERS
1082de82815dSKevin Wolf                                                     * s->cluster_size + 512);
1083de82815dSKevin Wolf     if (s->cluster_data == NULL) {
1084de82815dSKevin Wolf         error_setg(errp, "Could not allocate temporary cluster buffer");
1085de82815dSKevin Wolf         ret = -ENOMEM;
1086de82815dSKevin Wolf         goto fail;
1087de82815dSKevin Wolf     }
1088de82815dSKevin Wolf 
1089585f8587Sbellard     s->cluster_cache_offset = -1;
109006d9260fSAnthony Liguori     s->flags = flags;
1091585f8587Sbellard 
10926d85a57eSJes Sorensen     ret = qcow2_refcount_init(bs);
10936d85a57eSJes Sorensen     if (ret != 0) {
10943ef6c40aSMax Reitz         error_setg_errno(errp, -ret, "Could not initialize refcount handling");
1095585f8587Sbellard         goto fail;
10966d85a57eSJes Sorensen     }
1097585f8587Sbellard 
109872cf2d4fSBlue Swirl     QLIST_INIT(&s->cluster_allocs);
10990b919faeSKevin Wolf     QTAILQ_INIT(&s->discards);
1100f214978aSKevin Wolf 
11019b80ddf3Saliguori     /* read qcow2 extensions */
11023ef6c40aSMax Reitz     if (qcow2_read_extensions(bs, header.header_length, ext_end, NULL,
11033ef6c40aSMax Reitz         &local_err)) {
11043ef6c40aSMax Reitz         error_propagate(errp, local_err);
11056d85a57eSJes Sorensen         ret = -EINVAL;
11069b80ddf3Saliguori         goto fail;
11076d85a57eSJes Sorensen     }
11089b80ddf3Saliguori 
1109585f8587Sbellard     /* read the backing file name */
1110585f8587Sbellard     if (header.backing_file_offset != 0) {
1111585f8587Sbellard         len = header.backing_file_size;
11129a29e18fSJeff Cody         if (len > MIN(1023, s->cluster_size - header.backing_file_offset) ||
1113e729fa6aSJeff Cody             len >= sizeof(bs->backing_file)) {
11146d33e8e7SKevin Wolf             error_setg(errp, "Backing file name too long");
11156d33e8e7SKevin Wolf             ret = -EINVAL;
11166d33e8e7SKevin Wolf             goto fail;
11176d85a57eSJes Sorensen         }
11189a4f4c31SKevin Wolf         ret = bdrv_pread(bs->file->bs, header.backing_file_offset,
11196d85a57eSJes Sorensen                          bs->backing_file, len);
11206d85a57eSJes Sorensen         if (ret < 0) {
11213ef6c40aSMax Reitz             error_setg_errno(errp, -ret, "Could not read backing file name");
1122585f8587Sbellard             goto fail;
11236d85a57eSJes Sorensen         }
1124585f8587Sbellard         bs->backing_file[len] = '\0';
1125e4603fe1SKevin Wolf         s->image_backing_file = g_strdup(bs->backing_file);
1126585f8587Sbellard     }
112742deb29fSKevin Wolf 
112811b128f4SKevin Wolf     /* Internal snapshots */
112911b128f4SKevin Wolf     s->snapshots_offset = header.snapshots_offset;
113011b128f4SKevin Wolf     s->nb_snapshots = header.nb_snapshots;
113111b128f4SKevin Wolf 
113242deb29fSKevin Wolf     ret = qcow2_read_snapshots(bs);
113342deb29fSKevin Wolf     if (ret < 0) {
11343ef6c40aSMax Reitz         error_setg_errno(errp, -ret, "Could not read snapshots");
1135585f8587Sbellard         goto fail;
11366d85a57eSJes Sorensen     }
1137585f8587Sbellard 
1138af7b708dSStefan Hajnoczi     /* Clear unknown autoclear feature bits */
113904c01a5cSKevin Wolf     if (!bs->read_only && !(flags & BDRV_O_INACTIVE) && s->autoclear_features) {
1140af7b708dSStefan Hajnoczi         s->autoclear_features = 0;
1141af7b708dSStefan Hajnoczi         ret = qcow2_update_header(bs);
1142af7b708dSStefan Hajnoczi         if (ret < 0) {
11433ef6c40aSMax Reitz             error_setg_errno(errp, -ret, "Could not update qcow2 header");
1144af7b708dSStefan Hajnoczi             goto fail;
1145af7b708dSStefan Hajnoczi         }
1146af7b708dSStefan Hajnoczi     }
1147af7b708dSStefan Hajnoczi 
114868d100e9SKevin Wolf     /* Initialise locks */
114968d100e9SKevin Wolf     qemu_co_mutex_init(&s->lock);
115068d100e9SKevin Wolf 
1151c61d0004SStefan Hajnoczi     /* Repair image if dirty */
115204c01a5cSKevin Wolf     if (!(flags & (BDRV_O_CHECK | BDRV_O_INACTIVE)) && !bs->read_only &&
1153058f8f16SStefan Hajnoczi         (s->incompatible_features & QCOW2_INCOMPAT_DIRTY)) {
1154c61d0004SStefan Hajnoczi         BdrvCheckResult result = {0};
1155c61d0004SStefan Hajnoczi 
11565b84106bSMax Reitz         ret = qcow2_check(bs, &result, BDRV_FIX_ERRORS | BDRV_FIX_LEAKS);
1157c61d0004SStefan Hajnoczi         if (ret < 0) {
11583ef6c40aSMax Reitz             error_setg_errno(errp, -ret, "Could not repair dirty image");
1159c61d0004SStefan Hajnoczi             goto fail;
1160c61d0004SStefan Hajnoczi         }
1161c61d0004SStefan Hajnoczi     }
1162c61d0004SStefan Hajnoczi 
1163585f8587Sbellard #ifdef DEBUG_ALLOC
11646cbc3031SPhilipp Hahn     {
11656cbc3031SPhilipp Hahn         BdrvCheckResult result = {0};
1166b35278f7SStefan Hajnoczi         qcow2_check_refcounts(bs, &result, 0);
11676cbc3031SPhilipp Hahn     }
1168585f8587Sbellard #endif
11696d85a57eSJes Sorensen     return ret;
1170585f8587Sbellard 
1171585f8587Sbellard  fail:
11726744cbabSKevin Wolf     g_free(s->unknown_header_fields);
117375bab85cSKevin Wolf     cleanup_unknown_header_ext(bs);
1174ed6ccf0fSKevin Wolf     qcow2_free_snapshots(bs);
1175ed6ccf0fSKevin Wolf     qcow2_refcount_close(bs);
1176de82815dSKevin Wolf     qemu_vfree(s->l1_table);
1177cf93980eSMax Reitz     /* else pre-write overlap checks in cache_destroy may crash */
1178cf93980eSMax Reitz     s->l1_table = NULL;
1179279621c0SAlberto Garcia     cache_clean_timer_del(bs);
118029c1a730SKevin Wolf     if (s->l2_table_cache) {
118129c1a730SKevin Wolf         qcow2_cache_destroy(bs, s->l2_table_cache);
118229c1a730SKevin Wolf     }
1183c5a33ee9SPrasad Joshi     if (s->refcount_block_cache) {
1184c5a33ee9SPrasad Joshi         qcow2_cache_destroy(bs, s->refcount_block_cache);
1185c5a33ee9SPrasad Joshi     }
11867267c094SAnthony Liguori     g_free(s->cluster_cache);
1187dea43a65SFrediano Ziglio     qemu_vfree(s->cluster_data);
11886d85a57eSJes Sorensen     return ret;
1189585f8587Sbellard }
1190585f8587Sbellard 
11913baca891SKevin Wolf static void qcow2_refresh_limits(BlockDriverState *bs, Error **errp)
1192d34682cdSKevin Wolf {
1193ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
1194d34682cdSKevin Wolf 
1195d34682cdSKevin Wolf     bs->bl.write_zeroes_alignment = s->cluster_sectors;
1196d34682cdSKevin Wolf }
1197d34682cdSKevin Wolf 
11987c80ab3fSJes Sorensen static int qcow2_set_key(BlockDriverState *bs, const char *key)
1199585f8587Sbellard {
1200ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
1201585f8587Sbellard     uint8_t keybuf[16];
1202585f8587Sbellard     int len, i;
1203f6fa64f6SDaniel P. Berrange     Error *err = NULL;
1204585f8587Sbellard 
1205585f8587Sbellard     memset(keybuf, 0, 16);
1206585f8587Sbellard     len = strlen(key);
1207585f8587Sbellard     if (len > 16)
1208585f8587Sbellard         len = 16;
1209585f8587Sbellard     /* XXX: we could compress the chars to 7 bits to increase
1210585f8587Sbellard        entropy */
1211585f8587Sbellard     for(i = 0;i < len;i++) {
1212585f8587Sbellard         keybuf[i] = key[i];
1213585f8587Sbellard     }
12148336aafaSDaniel P. Berrange     assert(bs->encrypted);
1215585f8587Sbellard 
1216f6fa64f6SDaniel P. Berrange     qcrypto_cipher_free(s->cipher);
1217f6fa64f6SDaniel P. Berrange     s->cipher = qcrypto_cipher_new(
1218f6fa64f6SDaniel P. Berrange         QCRYPTO_CIPHER_ALG_AES_128,
1219f6fa64f6SDaniel P. Berrange         QCRYPTO_CIPHER_MODE_CBC,
1220f6fa64f6SDaniel P. Berrange         keybuf, G_N_ELEMENTS(keybuf),
1221f6fa64f6SDaniel P. Berrange         &err);
1222f6fa64f6SDaniel P. Berrange 
1223f6fa64f6SDaniel P. Berrange     if (!s->cipher) {
1224f6fa64f6SDaniel P. Berrange         /* XXX would be nice if errors in this method could
1225f6fa64f6SDaniel P. Berrange          * be properly propagate to the caller. Would need
1226f6fa64f6SDaniel P. Berrange          * the bdrv_set_key() API signature to be fixed. */
1227f6fa64f6SDaniel P. Berrange         error_free(err);
1228585f8587Sbellard         return -1;
1229585f8587Sbellard     }
1230585f8587Sbellard     return 0;
1231585f8587Sbellard }
1232585f8587Sbellard 
123321d82ac9SJeff Cody static int qcow2_reopen_prepare(BDRVReopenState *state,
123421d82ac9SJeff Cody                                 BlockReopenQueue *queue, Error **errp)
123521d82ac9SJeff Cody {
12365b0959a7SKevin Wolf     Qcow2ReopenState *r;
12374c2e5f8fSKevin Wolf     int ret;
12384c2e5f8fSKevin Wolf 
12395b0959a7SKevin Wolf     r = g_new0(Qcow2ReopenState, 1);
12405b0959a7SKevin Wolf     state->opaque = r;
12415b0959a7SKevin Wolf 
12425b0959a7SKevin Wolf     ret = qcow2_update_options_prepare(state->bs, r, state->options,
12435b0959a7SKevin Wolf                                        state->flags, errp);
12445b0959a7SKevin Wolf     if (ret < 0) {
12455b0959a7SKevin Wolf         goto fail;
12465b0959a7SKevin Wolf     }
12475b0959a7SKevin Wolf 
12485b0959a7SKevin Wolf     /* We need to write out any unwritten data if we reopen read-only. */
12494c2e5f8fSKevin Wolf     if ((state->flags & BDRV_O_RDWR) == 0) {
12504c2e5f8fSKevin Wolf         ret = bdrv_flush(state->bs);
12514c2e5f8fSKevin Wolf         if (ret < 0) {
12525b0959a7SKevin Wolf             goto fail;
12534c2e5f8fSKevin Wolf         }
12544c2e5f8fSKevin Wolf 
12554c2e5f8fSKevin Wolf         ret = qcow2_mark_clean(state->bs);
12564c2e5f8fSKevin Wolf         if (ret < 0) {
12575b0959a7SKevin Wolf             goto fail;
12584c2e5f8fSKevin Wolf         }
12594c2e5f8fSKevin Wolf     }
12604c2e5f8fSKevin Wolf 
126121d82ac9SJeff Cody     return 0;
12625b0959a7SKevin Wolf 
12635b0959a7SKevin Wolf fail:
12645b0959a7SKevin Wolf     qcow2_update_options_abort(state->bs, r);
12655b0959a7SKevin Wolf     g_free(r);
12665b0959a7SKevin Wolf     return ret;
12675b0959a7SKevin Wolf }
12685b0959a7SKevin Wolf 
12695b0959a7SKevin Wolf static void qcow2_reopen_commit(BDRVReopenState *state)
12705b0959a7SKevin Wolf {
12715b0959a7SKevin Wolf     qcow2_update_options_commit(state->bs, state->opaque);
12725b0959a7SKevin Wolf     g_free(state->opaque);
12735b0959a7SKevin Wolf }
12745b0959a7SKevin Wolf 
12755b0959a7SKevin Wolf static void qcow2_reopen_abort(BDRVReopenState *state)
12765b0959a7SKevin Wolf {
12775b0959a7SKevin Wolf     qcow2_update_options_abort(state->bs, state->opaque);
12785b0959a7SKevin Wolf     g_free(state->opaque);
127921d82ac9SJeff Cody }
128021d82ac9SJeff Cody 
12815365f44dSKevin Wolf static void qcow2_join_options(QDict *options, QDict *old_options)
12825365f44dSKevin Wolf {
12835365f44dSKevin Wolf     bool has_new_overlap_template =
12845365f44dSKevin Wolf         qdict_haskey(options, QCOW2_OPT_OVERLAP) ||
12855365f44dSKevin Wolf         qdict_haskey(options, QCOW2_OPT_OVERLAP_TEMPLATE);
12865365f44dSKevin Wolf     bool has_new_total_cache_size =
12875365f44dSKevin Wolf         qdict_haskey(options, QCOW2_OPT_CACHE_SIZE);
12885365f44dSKevin Wolf     bool has_all_cache_options;
12895365f44dSKevin Wolf 
12905365f44dSKevin Wolf     /* New overlap template overrides all old overlap options */
12915365f44dSKevin Wolf     if (has_new_overlap_template) {
12925365f44dSKevin Wolf         qdict_del(old_options, QCOW2_OPT_OVERLAP);
12935365f44dSKevin Wolf         qdict_del(old_options, QCOW2_OPT_OVERLAP_TEMPLATE);
12945365f44dSKevin Wolf         qdict_del(old_options, QCOW2_OPT_OVERLAP_MAIN_HEADER);
12955365f44dSKevin Wolf         qdict_del(old_options, QCOW2_OPT_OVERLAP_ACTIVE_L1);
12965365f44dSKevin Wolf         qdict_del(old_options, QCOW2_OPT_OVERLAP_ACTIVE_L2);
12975365f44dSKevin Wolf         qdict_del(old_options, QCOW2_OPT_OVERLAP_REFCOUNT_TABLE);
12985365f44dSKevin Wolf         qdict_del(old_options, QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK);
12995365f44dSKevin Wolf         qdict_del(old_options, QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE);
13005365f44dSKevin Wolf         qdict_del(old_options, QCOW2_OPT_OVERLAP_INACTIVE_L1);
13015365f44dSKevin Wolf         qdict_del(old_options, QCOW2_OPT_OVERLAP_INACTIVE_L2);
13025365f44dSKevin Wolf     }
13035365f44dSKevin Wolf 
13045365f44dSKevin Wolf     /* New total cache size overrides all old options */
13055365f44dSKevin Wolf     if (qdict_haskey(options, QCOW2_OPT_CACHE_SIZE)) {
13065365f44dSKevin Wolf         qdict_del(old_options, QCOW2_OPT_L2_CACHE_SIZE);
13075365f44dSKevin Wolf         qdict_del(old_options, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
13085365f44dSKevin Wolf     }
13095365f44dSKevin Wolf 
13105365f44dSKevin Wolf     qdict_join(options, old_options, false);
13115365f44dSKevin Wolf 
13125365f44dSKevin Wolf     /*
13135365f44dSKevin Wolf      * If after merging all cache size options are set, an old total size is
13145365f44dSKevin Wolf      * overwritten. Do keep all options, however, if all three are new. The
13155365f44dSKevin Wolf      * resulting error message is what we want to happen.
13165365f44dSKevin Wolf      */
13175365f44dSKevin Wolf     has_all_cache_options =
13185365f44dSKevin Wolf         qdict_haskey(options, QCOW2_OPT_CACHE_SIZE) ||
13195365f44dSKevin Wolf         qdict_haskey(options, QCOW2_OPT_L2_CACHE_SIZE) ||
13205365f44dSKevin Wolf         qdict_haskey(options, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
13215365f44dSKevin Wolf 
13225365f44dSKevin Wolf     if (has_all_cache_options && !has_new_total_cache_size) {
13235365f44dSKevin Wolf         qdict_del(options, QCOW2_OPT_CACHE_SIZE);
13245365f44dSKevin Wolf     }
13255365f44dSKevin Wolf }
13265365f44dSKevin Wolf 
1327b6b8a333SPaolo Bonzini static int64_t coroutine_fn qcow2_co_get_block_status(BlockDriverState *bs,
132867a0fd2aSFam Zheng         int64_t sector_num, int nb_sectors, int *pnum, BlockDriverState **file)
1329585f8587Sbellard {
1330ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
1331585f8587Sbellard     uint64_t cluster_offset;
13324bc74be9SPaolo Bonzini     int index_in_cluster, ret;
13334bc74be9SPaolo Bonzini     int64_t status = 0;
1334585f8587Sbellard 
1335095a9c58Saliguori     *pnum = nb_sectors;
1336f8a2e5e3SStefan Hajnoczi     qemu_co_mutex_lock(&s->lock);
13371c46efaaSKevin Wolf     ret = qcow2_get_cluster_offset(bs, sector_num << 9, pnum, &cluster_offset);
1338f8a2e5e3SStefan Hajnoczi     qemu_co_mutex_unlock(&s->lock);
13391c46efaaSKevin Wolf     if (ret < 0) {
1340d663640cSPaolo Bonzini         return ret;
13411c46efaaSKevin Wolf     }
1342095a9c58Saliguori 
13434bc74be9SPaolo Bonzini     if (cluster_offset != 0 && ret != QCOW2_CLUSTER_COMPRESSED &&
1344f6fa64f6SDaniel P. Berrange         !s->cipher) {
13454bc74be9SPaolo Bonzini         index_in_cluster = sector_num & (s->cluster_sectors - 1);
13464bc74be9SPaolo Bonzini         cluster_offset |= (index_in_cluster << BDRV_SECTOR_BITS);
1347178b4db7SFam Zheng         *file = bs->file->bs;
13484bc74be9SPaolo Bonzini         status |= BDRV_BLOCK_OFFSET_VALID | cluster_offset;
13494bc74be9SPaolo Bonzini     }
13504bc74be9SPaolo Bonzini     if (ret == QCOW2_CLUSTER_ZERO) {
13514bc74be9SPaolo Bonzini         status |= BDRV_BLOCK_ZERO;
13524bc74be9SPaolo Bonzini     } else if (ret != QCOW2_CLUSTER_UNALLOCATED) {
13534bc74be9SPaolo Bonzini         status |= BDRV_BLOCK_DATA;
13544bc74be9SPaolo Bonzini     }
13554bc74be9SPaolo Bonzini     return status;
1356585f8587Sbellard }
1357585f8587Sbellard 
1358a9465922Sbellard /* handle reading after the end of the backing file */
1359bd28f835SKevin Wolf int qcow2_backing_read1(BlockDriverState *bs, QEMUIOVector *qiov,
1360bd28f835SKevin Wolf                   int64_t sector_num, int nb_sectors)
1361a9465922Sbellard {
1362a9465922Sbellard     int n1;
1363a9465922Sbellard     if ((sector_num + nb_sectors) <= bs->total_sectors)
1364a9465922Sbellard         return nb_sectors;
1365a9465922Sbellard     if (sector_num >= bs->total_sectors)
1366a9465922Sbellard         n1 = 0;
1367a9465922Sbellard     else
1368a9465922Sbellard         n1 = bs->total_sectors - sector_num;
1369bd28f835SKevin Wolf 
13703d9b4925SMichael Tokarev     qemu_iovec_memset(qiov, 512 * n1, 0, 512 * (nb_sectors - n1));
1371bd28f835SKevin Wolf 
1372a9465922Sbellard     return n1;
1373a9465922Sbellard }
1374a9465922Sbellard 
1375a968168cSDong Xu Wang static coroutine_fn int qcow2_co_readv(BlockDriverState *bs, int64_t sector_num,
13763fc48d09SFrediano Ziglio                           int remaining_sectors, QEMUIOVector *qiov)
13771490791fSaliguori {
1378ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
1379a9465922Sbellard     int index_in_cluster, n1;
138068d100e9SKevin Wolf     int ret;
1381faf575c1SFrediano Ziglio     int cur_nr_sectors; /* number of sectors in current iteration */
1382c2bdd990SFrediano Ziglio     uint64_t cluster_offset = 0;
13833fc48d09SFrediano Ziglio     uint64_t bytes_done = 0;
13843fc48d09SFrediano Ziglio     QEMUIOVector hd_qiov;
13853fc48d09SFrediano Ziglio     uint8_t *cluster_data = NULL;
1386585f8587Sbellard 
13873fc48d09SFrediano Ziglio     qemu_iovec_init(&hd_qiov, qiov->niov);
13883fc48d09SFrediano Ziglio 
13893fc48d09SFrediano Ziglio     qemu_co_mutex_lock(&s->lock);
13903fc48d09SFrediano Ziglio 
13913fc48d09SFrediano Ziglio     while (remaining_sectors != 0) {
1392585f8587Sbellard 
1393faf575c1SFrediano Ziglio         /* prepare next request */
13943fc48d09SFrediano Ziglio         cur_nr_sectors = remaining_sectors;
1395f6fa64f6SDaniel P. Berrange         if (s->cipher) {
1396faf575c1SFrediano Ziglio             cur_nr_sectors = MIN(cur_nr_sectors,
1397bd28f835SKevin Wolf                 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors);
1398bd28f835SKevin Wolf         }
1399bd28f835SKevin Wolf 
14003fc48d09SFrediano Ziglio         ret = qcow2_get_cluster_offset(bs, sector_num << 9,
1401c2bdd990SFrediano Ziglio             &cur_nr_sectors, &cluster_offset);
14021c46efaaSKevin Wolf         if (ret < 0) {
14033fc48d09SFrediano Ziglio             goto fail;
14041c46efaaSKevin Wolf         }
14051c46efaaSKevin Wolf 
14063fc48d09SFrediano Ziglio         index_in_cluster = sector_num & (s->cluster_sectors - 1);
1407585f8587Sbellard 
14083fc48d09SFrediano Ziglio         qemu_iovec_reset(&hd_qiov);
14091b093c48SMichael Tokarev         qemu_iovec_concat(&hd_qiov, qiov, bytes_done,
1410faf575c1SFrediano Ziglio             cur_nr_sectors * 512);
1411bd28f835SKevin Wolf 
141268d000a3SKevin Wolf         switch (ret) {
141368d000a3SKevin Wolf         case QCOW2_CLUSTER_UNALLOCATED:
1414bd28f835SKevin Wolf 
1415760e0063SKevin Wolf             if (bs->backing) {
1416585f8587Sbellard                 /* read from the base image */
1417760e0063SKevin Wolf                 n1 = qcow2_backing_read1(bs->backing->bs, &hd_qiov,
14183fc48d09SFrediano Ziglio                     sector_num, cur_nr_sectors);
1419a9465922Sbellard                 if (n1 > 0) {
142044deba5aSKevin Wolf                     QEMUIOVector local_qiov;
142144deba5aSKevin Wolf 
142244deba5aSKevin Wolf                     qemu_iovec_init(&local_qiov, hd_qiov.niov);
142344deba5aSKevin Wolf                     qemu_iovec_concat(&local_qiov, &hd_qiov, 0,
142444deba5aSKevin Wolf                                       n1 * BDRV_SECTOR_SIZE);
142544deba5aSKevin Wolf 
142666f82ceeSKevin Wolf                     BLKDBG_EVENT(bs->file, BLKDBG_READ_BACKING_AIO);
142768d100e9SKevin Wolf                     qemu_co_mutex_unlock(&s->lock);
1428760e0063SKevin Wolf                     ret = bdrv_co_readv(bs->backing->bs, sector_num,
142944deba5aSKevin Wolf                                         n1, &local_qiov);
143068d100e9SKevin Wolf                     qemu_co_mutex_lock(&s->lock);
143144deba5aSKevin Wolf 
143244deba5aSKevin Wolf                     qemu_iovec_destroy(&local_qiov);
143344deba5aSKevin Wolf 
143468d100e9SKevin Wolf                     if (ret < 0) {
14353fc48d09SFrediano Ziglio                         goto fail;
14363ab4c7e9SKevin Wolf                     }
14371490791fSaliguori                 }
1438a9465922Sbellard             } else {
1439585f8587Sbellard                 /* Note: in this case, no need to wait */
14403d9b4925SMichael Tokarev                 qemu_iovec_memset(&hd_qiov, 0, 0, 512 * cur_nr_sectors);
14411490791fSaliguori             }
144268d000a3SKevin Wolf             break;
144368d000a3SKevin Wolf 
14446377af48SKevin Wolf         case QCOW2_CLUSTER_ZERO:
14453d9b4925SMichael Tokarev             qemu_iovec_memset(&hd_qiov, 0, 0, 512 * cur_nr_sectors);
14466377af48SKevin Wolf             break;
14476377af48SKevin Wolf 
144868d000a3SKevin Wolf         case QCOW2_CLUSTER_COMPRESSED:
1449585f8587Sbellard             /* add AIO support for compressed blocks ? */
1450c2bdd990SFrediano Ziglio             ret = qcow2_decompress_cluster(bs, cluster_offset);
14518af36488SKevin Wolf             if (ret < 0) {
14523fc48d09SFrediano Ziglio                 goto fail;
14538af36488SKevin Wolf             }
1454bd28f835SKevin Wolf 
145503396148SMichael Tokarev             qemu_iovec_from_buf(&hd_qiov, 0,
1456bd28f835SKevin Wolf                 s->cluster_cache + index_in_cluster * 512,
1457faf575c1SFrediano Ziglio                 512 * cur_nr_sectors);
145868d000a3SKevin Wolf             break;
145968d000a3SKevin Wolf 
146068d000a3SKevin Wolf         case QCOW2_CLUSTER_NORMAL:
1461c2bdd990SFrediano Ziglio             if ((cluster_offset & 511) != 0) {
14623fc48d09SFrediano Ziglio                 ret = -EIO;
14633fc48d09SFrediano Ziglio                 goto fail;
1464585f8587Sbellard             }
1465c87c0672Saliguori 
14668336aafaSDaniel P. Berrange             if (bs->encrypted) {
1467f6fa64f6SDaniel P. Berrange                 assert(s->cipher);
14688336aafaSDaniel P. Berrange 
1469bd28f835SKevin Wolf                 /*
1470bd28f835SKevin Wolf                  * For encrypted images, read everything into a temporary
1471bd28f835SKevin Wolf                  * contiguous buffer on which the AES functions can work.
1472bd28f835SKevin Wolf                  */
14733fc48d09SFrediano Ziglio                 if (!cluster_data) {
14743fc48d09SFrediano Ziglio                     cluster_data =
14759a4f4c31SKevin Wolf                         qemu_try_blockalign(bs->file->bs,
14769a4f4c31SKevin Wolf                                             QCOW_MAX_CRYPT_CLUSTERS
1477de82815dSKevin Wolf                                             * s->cluster_size);
1478de82815dSKevin Wolf                     if (cluster_data == NULL) {
1479de82815dSKevin Wolf                         ret = -ENOMEM;
1480de82815dSKevin Wolf                         goto fail;
1481de82815dSKevin Wolf                     }
1482bd28f835SKevin Wolf                 }
1483bd28f835SKevin Wolf 
1484faf575c1SFrediano Ziglio                 assert(cur_nr_sectors <=
1485bd28f835SKevin Wolf                     QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors);
14863fc48d09SFrediano Ziglio                 qemu_iovec_reset(&hd_qiov);
14873fc48d09SFrediano Ziglio                 qemu_iovec_add(&hd_qiov, cluster_data,
1488faf575c1SFrediano Ziglio                     512 * cur_nr_sectors);
1489bd28f835SKevin Wolf             }
1490bd28f835SKevin Wolf 
149166f82ceeSKevin Wolf             BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);
149268d100e9SKevin Wolf             qemu_co_mutex_unlock(&s->lock);
14939a4f4c31SKevin Wolf             ret = bdrv_co_readv(bs->file->bs,
1494c2bdd990SFrediano Ziglio                                 (cluster_offset >> 9) + index_in_cluster,
14953fc48d09SFrediano Ziglio                                 cur_nr_sectors, &hd_qiov);
149668d100e9SKevin Wolf             qemu_co_mutex_lock(&s->lock);
149768d100e9SKevin Wolf             if (ret < 0) {
14983fc48d09SFrediano Ziglio                 goto fail;
1499585f8587Sbellard             }
15008336aafaSDaniel P. Berrange             if (bs->encrypted) {
1501f6fa64f6SDaniel P. Berrange                 assert(s->cipher);
1502f6fa64f6SDaniel P. Berrange                 Error *err = NULL;
1503f6fa64f6SDaniel P. Berrange                 if (qcow2_encrypt_sectors(s, sector_num,  cluster_data,
1504f6fa64f6SDaniel P. Berrange                                           cluster_data, cur_nr_sectors, false,
1505f6fa64f6SDaniel P. Berrange                                           &err) < 0) {
1506f6fa64f6SDaniel P. Berrange                     error_free(err);
1507f6fa64f6SDaniel P. Berrange                     ret = -EIO;
1508f6fa64f6SDaniel P. Berrange                     goto fail;
1509f6fa64f6SDaniel P. Berrange                 }
151003396148SMichael Tokarev                 qemu_iovec_from_buf(qiov, bytes_done,
151103396148SMichael Tokarev                     cluster_data, 512 * cur_nr_sectors);
1512171e3d6bSKevin Wolf             }
151368d000a3SKevin Wolf             break;
151468d000a3SKevin Wolf 
151568d000a3SKevin Wolf         default:
151668d000a3SKevin Wolf             g_assert_not_reached();
151768d000a3SKevin Wolf             ret = -EIO;
151868d000a3SKevin Wolf             goto fail;
1519faf575c1SFrediano Ziglio         }
1520faf575c1SFrediano Ziglio 
15213fc48d09SFrediano Ziglio         remaining_sectors -= cur_nr_sectors;
15223fc48d09SFrediano Ziglio         sector_num += cur_nr_sectors;
15233fc48d09SFrediano Ziglio         bytes_done += cur_nr_sectors * 512;
15245ebaa27eSFrediano Ziglio     }
15253fc48d09SFrediano Ziglio     ret = 0;
1526f141eafeSaliguori 
15273fc48d09SFrediano Ziglio fail:
152868d100e9SKevin Wolf     qemu_co_mutex_unlock(&s->lock);
152968d100e9SKevin Wolf 
15303fc48d09SFrediano Ziglio     qemu_iovec_destroy(&hd_qiov);
1531dea43a65SFrediano Ziglio     qemu_vfree(cluster_data);
153268d100e9SKevin Wolf 
153368d100e9SKevin Wolf     return ret;
1534585f8587Sbellard }
1535585f8587Sbellard 
1536a968168cSDong Xu Wang static coroutine_fn int qcow2_co_writev(BlockDriverState *bs,
15373fc48d09SFrediano Ziglio                            int64_t sector_num,
15383fc48d09SFrediano Ziglio                            int remaining_sectors,
15393fc48d09SFrediano Ziglio                            QEMUIOVector *qiov)
1540585f8587Sbellard {
1541ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
1542585f8587Sbellard     int index_in_cluster;
154368d100e9SKevin Wolf     int ret;
1544faf575c1SFrediano Ziglio     int cur_nr_sectors; /* number of sectors in current iteration */
1545c2bdd990SFrediano Ziglio     uint64_t cluster_offset;
15463fc48d09SFrediano Ziglio     QEMUIOVector hd_qiov;
15473fc48d09SFrediano Ziglio     uint64_t bytes_done = 0;
15483fc48d09SFrediano Ziglio     uint8_t *cluster_data = NULL;
15498d2497c3SKevin Wolf     QCowL2Meta *l2meta = NULL;
1550c2271403SFrediano Ziglio 
15513cce16f4SKevin Wolf     trace_qcow2_writev_start_req(qemu_coroutine_self(), sector_num,
15523cce16f4SKevin Wolf                                  remaining_sectors);
15533cce16f4SKevin Wolf 
15543fc48d09SFrediano Ziglio     qemu_iovec_init(&hd_qiov, qiov->niov);
1555585f8587Sbellard 
15563fc48d09SFrediano Ziglio     s->cluster_cache_offset = -1; /* disable compressed cache */
15573fc48d09SFrediano Ziglio 
15583fc48d09SFrediano Ziglio     qemu_co_mutex_lock(&s->lock);
15593fc48d09SFrediano Ziglio 
15603fc48d09SFrediano Ziglio     while (remaining_sectors != 0) {
15613fc48d09SFrediano Ziglio 
1562f50f88b9SKevin Wolf         l2meta = NULL;
1563cf5c1a23SKevin Wolf 
15643cce16f4SKevin Wolf         trace_qcow2_writev_start_part(qemu_coroutine_self());
15653fc48d09SFrediano Ziglio         index_in_cluster = sector_num & (s->cluster_sectors - 1);
156616f0587eSHu Tao         cur_nr_sectors = remaining_sectors;
15678336aafaSDaniel P. Berrange         if (bs->encrypted &&
156816f0587eSHu Tao             cur_nr_sectors >
156916f0587eSHu Tao             QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors - index_in_cluster) {
157016f0587eSHu Tao             cur_nr_sectors =
157116f0587eSHu Tao                 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors - index_in_cluster;
15725ebaa27eSFrediano Ziglio         }
1573095a9c58Saliguori 
15743fc48d09SFrediano Ziglio         ret = qcow2_alloc_cluster_offset(bs, sector_num << 9,
157516f0587eSHu Tao             &cur_nr_sectors, &cluster_offset, &l2meta);
1576148da7eaSKevin Wolf         if (ret < 0) {
15773fc48d09SFrediano Ziglio             goto fail;
1578148da7eaSKevin Wolf         }
1579148da7eaSKevin Wolf 
1580c2bdd990SFrediano Ziglio         assert((cluster_offset & 511) == 0);
1581148da7eaSKevin Wolf 
15823fc48d09SFrediano Ziglio         qemu_iovec_reset(&hd_qiov);
15831b093c48SMichael Tokarev         qemu_iovec_concat(&hd_qiov, qiov, bytes_done,
1584faf575c1SFrediano Ziglio             cur_nr_sectors * 512);
15856f5f060bSKevin Wolf 
15868336aafaSDaniel P. Berrange         if (bs->encrypted) {
1587f6fa64f6SDaniel P. Berrange             Error *err = NULL;
1588f6fa64f6SDaniel P. Berrange             assert(s->cipher);
15893fc48d09SFrediano Ziglio             if (!cluster_data) {
15909a4f4c31SKevin Wolf                 cluster_data = qemu_try_blockalign(bs->file->bs,
1591de82815dSKevin Wolf                                                    QCOW_MAX_CRYPT_CLUSTERS
1592de82815dSKevin Wolf                                                    * s->cluster_size);
1593de82815dSKevin Wolf                 if (cluster_data == NULL) {
1594de82815dSKevin Wolf                     ret = -ENOMEM;
1595de82815dSKevin Wolf                     goto fail;
1596de82815dSKevin Wolf                 }
1597585f8587Sbellard             }
15986f5f060bSKevin Wolf 
15993fc48d09SFrediano Ziglio             assert(hd_qiov.size <=
16005ebaa27eSFrediano Ziglio                    QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
1601d5e6b161SMichael Tokarev             qemu_iovec_to_buf(&hd_qiov, 0, cluster_data, hd_qiov.size);
16026f5f060bSKevin Wolf 
1603f6fa64f6SDaniel P. Berrange             if (qcow2_encrypt_sectors(s, sector_num, cluster_data,
1604f6fa64f6SDaniel P. Berrange                                       cluster_data, cur_nr_sectors,
1605f6fa64f6SDaniel P. Berrange                                       true, &err) < 0) {
1606f6fa64f6SDaniel P. Berrange                 error_free(err);
1607f6fa64f6SDaniel P. Berrange                 ret = -EIO;
1608f6fa64f6SDaniel P. Berrange                 goto fail;
1609f6fa64f6SDaniel P. Berrange             }
16106f5f060bSKevin Wolf 
16113fc48d09SFrediano Ziglio             qemu_iovec_reset(&hd_qiov);
16123fc48d09SFrediano Ziglio             qemu_iovec_add(&hd_qiov, cluster_data,
1613faf575c1SFrediano Ziglio                 cur_nr_sectors * 512);
1614585f8587Sbellard         }
16156f5f060bSKevin Wolf 
1616231bb267SMax Reitz         ret = qcow2_pre_write_overlap_check(bs, 0,
1617cf93980eSMax Reitz                 cluster_offset + index_in_cluster * BDRV_SECTOR_SIZE,
1618cf93980eSMax Reitz                 cur_nr_sectors * BDRV_SECTOR_SIZE);
1619cf93980eSMax Reitz         if (ret < 0) {
1620cf93980eSMax Reitz             goto fail;
1621cf93980eSMax Reitz         }
1622cf93980eSMax Reitz 
162368d100e9SKevin Wolf         qemu_co_mutex_unlock(&s->lock);
162467a7a0ebSKevin Wolf         BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO);
16253cce16f4SKevin Wolf         trace_qcow2_writev_data(qemu_coroutine_self(),
16263cce16f4SKevin Wolf                                 (cluster_offset >> 9) + index_in_cluster);
16279a4f4c31SKevin Wolf         ret = bdrv_co_writev(bs->file->bs,
1628c2bdd990SFrediano Ziglio                              (cluster_offset >> 9) + index_in_cluster,
16293fc48d09SFrediano Ziglio                              cur_nr_sectors, &hd_qiov);
163068d100e9SKevin Wolf         qemu_co_mutex_lock(&s->lock);
163168d100e9SKevin Wolf         if (ret < 0) {
16323fc48d09SFrediano Ziglio             goto fail;
1633171e3d6bSKevin Wolf         }
1634f141eafeSaliguori 
163588c6588cSKevin Wolf         while (l2meta != NULL) {
163688c6588cSKevin Wolf             QCowL2Meta *next;
163788c6588cSKevin Wolf 
1638cf5c1a23SKevin Wolf             ret = qcow2_alloc_cluster_link_l2(bs, l2meta);
1639faf575c1SFrediano Ziglio             if (ret < 0) {
16403fc48d09SFrediano Ziglio                 goto fail;
1641faf575c1SFrediano Ziglio             }
1642faf575c1SFrediano Ziglio 
16434e95314eSKevin Wolf             /* Take the request off the list of running requests */
16444e95314eSKevin Wolf             if (l2meta->nb_clusters != 0) {
16454e95314eSKevin Wolf                 QLIST_REMOVE(l2meta, next_in_flight);
16464e95314eSKevin Wolf             }
16474e95314eSKevin Wolf 
16484e95314eSKevin Wolf             qemu_co_queue_restart_all(&l2meta->dependent_requests);
16494e95314eSKevin Wolf 
165088c6588cSKevin Wolf             next = l2meta->next;
1651cf5c1a23SKevin Wolf             g_free(l2meta);
165288c6588cSKevin Wolf             l2meta = next;
1653f50f88b9SKevin Wolf         }
16540fa9131aSKevin Wolf 
16553fc48d09SFrediano Ziglio         remaining_sectors -= cur_nr_sectors;
16563fc48d09SFrediano Ziglio         sector_num += cur_nr_sectors;
16573fc48d09SFrediano Ziglio         bytes_done += cur_nr_sectors * 512;
16583cce16f4SKevin Wolf         trace_qcow2_writev_done_part(qemu_coroutine_self(), cur_nr_sectors);
16595ebaa27eSFrediano Ziglio     }
16603fc48d09SFrediano Ziglio     ret = 0;
1661faf575c1SFrediano Ziglio 
16623fc48d09SFrediano Ziglio fail:
16634e95314eSKevin Wolf     qemu_co_mutex_unlock(&s->lock);
16644e95314eSKevin Wolf 
166588c6588cSKevin Wolf     while (l2meta != NULL) {
166688c6588cSKevin Wolf         QCowL2Meta *next;
166788c6588cSKevin Wolf 
16684e95314eSKevin Wolf         if (l2meta->nb_clusters != 0) {
16694e95314eSKevin Wolf             QLIST_REMOVE(l2meta, next_in_flight);
16704e95314eSKevin Wolf         }
16714e95314eSKevin Wolf         qemu_co_queue_restart_all(&l2meta->dependent_requests);
167288c6588cSKevin Wolf 
167388c6588cSKevin Wolf         next = l2meta->next;
1674cf5c1a23SKevin Wolf         g_free(l2meta);
167588c6588cSKevin Wolf         l2meta = next;
1676cf5c1a23SKevin Wolf     }
16770fa9131aSKevin Wolf 
16783fc48d09SFrediano Ziglio     qemu_iovec_destroy(&hd_qiov);
1679dea43a65SFrediano Ziglio     qemu_vfree(cluster_data);
16803cce16f4SKevin Wolf     trace_qcow2_writev_done_req(qemu_coroutine_self(), ret);
168142496d62SKevin Wolf 
168268d100e9SKevin Wolf     return ret;
1683585f8587Sbellard }
1684585f8587Sbellard 
1685ec6d8912SKevin Wolf static int qcow2_inactivate(BlockDriverState *bs)
1686ec6d8912SKevin Wolf {
1687ec6d8912SKevin Wolf     BDRVQcow2State *s = bs->opaque;
1688ec6d8912SKevin Wolf     int ret, result = 0;
1689ec6d8912SKevin Wolf 
1690ec6d8912SKevin Wolf     ret = qcow2_cache_flush(bs, s->l2_table_cache);
1691ec6d8912SKevin Wolf     if (ret) {
1692ec6d8912SKevin Wolf         result = ret;
1693ec6d8912SKevin Wolf         error_report("Failed to flush the L2 table cache: %s",
1694ec6d8912SKevin Wolf                      strerror(-ret));
1695ec6d8912SKevin Wolf     }
1696ec6d8912SKevin Wolf 
1697ec6d8912SKevin Wolf     ret = qcow2_cache_flush(bs, s->refcount_block_cache);
1698ec6d8912SKevin Wolf     if (ret) {
1699ec6d8912SKevin Wolf         result = ret;
1700ec6d8912SKevin Wolf         error_report("Failed to flush the refcount block cache: %s",
1701ec6d8912SKevin Wolf                      strerror(-ret));
1702ec6d8912SKevin Wolf     }
1703ec6d8912SKevin Wolf 
1704ec6d8912SKevin Wolf     if (result == 0) {
1705ec6d8912SKevin Wolf         qcow2_mark_clean(bs);
1706ec6d8912SKevin Wolf     }
1707ec6d8912SKevin Wolf 
1708ec6d8912SKevin Wolf     return result;
1709ec6d8912SKevin Wolf }
1710ec6d8912SKevin Wolf 
17117c80ab3fSJes Sorensen static void qcow2_close(BlockDriverState *bs)
1712585f8587Sbellard {
1713ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
1714de82815dSKevin Wolf     qemu_vfree(s->l1_table);
1715cf93980eSMax Reitz     /* else pre-write overlap checks in cache_destroy may crash */
1716cf93980eSMax Reitz     s->l1_table = NULL;
171729c1a730SKevin Wolf 
1718140fd5a6SKevin Wolf     if (!(s->flags & BDRV_O_INACTIVE)) {
1719ec6d8912SKevin Wolf         qcow2_inactivate(bs);
17203b5e14c7SMax Reitz     }
1721c61d0004SStefan Hajnoczi 
1722279621c0SAlberto Garcia     cache_clean_timer_del(bs);
172329c1a730SKevin Wolf     qcow2_cache_destroy(bs, s->l2_table_cache);
172429c1a730SKevin Wolf     qcow2_cache_destroy(bs, s->refcount_block_cache);
172529c1a730SKevin Wolf 
1726f6fa64f6SDaniel P. Berrange     qcrypto_cipher_free(s->cipher);
1727f6fa64f6SDaniel P. Berrange     s->cipher = NULL;
1728f6fa64f6SDaniel P. Berrange 
17296744cbabSKevin Wolf     g_free(s->unknown_header_fields);
173075bab85cSKevin Wolf     cleanup_unknown_header_ext(bs);
17316744cbabSKevin Wolf 
1732e4603fe1SKevin Wolf     g_free(s->image_backing_file);
1733e4603fe1SKevin Wolf     g_free(s->image_backing_format);
1734e4603fe1SKevin Wolf 
17357267c094SAnthony Liguori     g_free(s->cluster_cache);
1736dea43a65SFrediano Ziglio     qemu_vfree(s->cluster_data);
1737ed6ccf0fSKevin Wolf     qcow2_refcount_close(bs);
173828c1202bSLi Zhi Hui     qcow2_free_snapshots(bs);
1739585f8587Sbellard }
1740585f8587Sbellard 
17415a8a30dbSKevin Wolf static void qcow2_invalidate_cache(BlockDriverState *bs, Error **errp)
174206d9260fSAnthony Liguori {
1743ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
174406d9260fSAnthony Liguori     int flags = s->flags;
1745f6fa64f6SDaniel P. Berrange     QCryptoCipher *cipher = NULL;
1746acdfb480SKevin Wolf     QDict *options;
17475a8a30dbSKevin Wolf     Error *local_err = NULL;
17485a8a30dbSKevin Wolf     int ret;
174906d9260fSAnthony Liguori 
175006d9260fSAnthony Liguori     /*
175106d9260fSAnthony Liguori      * Backing files are read-only which makes all of their metadata immutable,
175206d9260fSAnthony Liguori      * that means we don't have to worry about reopening them here.
175306d9260fSAnthony Liguori      */
175406d9260fSAnthony Liguori 
1755f6fa64f6SDaniel P. Berrange     cipher = s->cipher;
1756f6fa64f6SDaniel P. Berrange     s->cipher = NULL;
175706d9260fSAnthony Liguori 
175806d9260fSAnthony Liguori     qcow2_close(bs);
175906d9260fSAnthony Liguori 
17609a4f4c31SKevin Wolf     bdrv_invalidate_cache(bs->file->bs, &local_err);
17615a8a30dbSKevin Wolf     if (local_err) {
17625a8a30dbSKevin Wolf         error_propagate(errp, local_err);
1763191fb11bSKevin Wolf         bs->drv = NULL;
17645a8a30dbSKevin Wolf         return;
17655a8a30dbSKevin Wolf     }
17663456a8d1SKevin Wolf 
1767ff99129aSKevin Wolf     memset(s, 0, sizeof(BDRVQcow2State));
1768d475e5acSKevin Wolf     options = qdict_clone_shallow(bs->options);
17695a8a30dbSKevin Wolf 
1770140fd5a6SKevin Wolf     flags &= ~BDRV_O_INACTIVE;
17715a8a30dbSKevin Wolf     ret = qcow2_open(bs, options, flags, &local_err);
1772a1904e48SMarkus Armbruster     QDECREF(options);
17735a8a30dbSKevin Wolf     if (local_err) {
1774e43bfd9cSMarkus Armbruster         error_propagate(errp, local_err);
1775e43bfd9cSMarkus Armbruster         error_prepend(errp, "Could not reopen qcow2 layer: ");
1776191fb11bSKevin Wolf         bs->drv = NULL;
17775a8a30dbSKevin Wolf         return;
17785a8a30dbSKevin Wolf     } else if (ret < 0) {
17795a8a30dbSKevin Wolf         error_setg_errno(errp, -ret, "Could not reopen qcow2 layer");
1780191fb11bSKevin Wolf         bs->drv = NULL;
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      */
209523588797SKevin Wolf     BlockBackend *blk;
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 
2170efaa7c4eSMax Reitz     blk = blk_new_open(filename, NULL, NULL,
2171*72e775c7SKevin Wolf                        BDRV_O_RDWR | BDRV_O_PROTOCOL, &local_err);
217223588797SKevin Wolf     if (blk == NULL) {
21733ef6c40aSMax Reitz         error_propagate(errp, local_err);
217423588797SKevin Wolf         return -EIO;
2175a9420734SKevin Wolf     }
2176a9420734SKevin Wolf 
217723588797SKevin Wolf     blk_set_allow_write_beyond_eof(blk, true);
217823588797SKevin Wolf 
2179a9420734SKevin Wolf     /* Write the header */
2180f8413b3cSKevin Wolf     QEMU_BUILD_BUG_ON((1 << MIN_CLUSTER_BITS) < sizeof(*header));
2181f8413b3cSKevin Wolf     header = g_malloc0(cluster_size);
2182f8413b3cSKevin Wolf     *header = (QCowHeader) {
2183f8413b3cSKevin Wolf         .magic                      = cpu_to_be32(QCOW_MAGIC),
2184f8413b3cSKevin Wolf         .version                    = cpu_to_be32(version),
2185f8413b3cSKevin Wolf         .cluster_bits               = cpu_to_be32(cluster_bits),
2186f8413b3cSKevin Wolf         .size                       = cpu_to_be64(0),
2187f8413b3cSKevin Wolf         .l1_table_offset            = cpu_to_be64(0),
2188f8413b3cSKevin Wolf         .l1_size                    = cpu_to_be32(0),
2189f8413b3cSKevin Wolf         .refcount_table_offset      = cpu_to_be64(cluster_size),
2190f8413b3cSKevin Wolf         .refcount_table_clusters    = cpu_to_be32(1),
2191bd4b167fSMax Reitz         .refcount_order             = cpu_to_be32(refcount_order),
2192f8413b3cSKevin Wolf         .header_length              = cpu_to_be32(sizeof(*header)),
2193f8413b3cSKevin Wolf     };
2194a9420734SKevin Wolf 
2195a9420734SKevin Wolf     if (flags & BLOCK_FLAG_ENCRYPT) {
2196f8413b3cSKevin Wolf         header->crypt_method = cpu_to_be32(QCOW_CRYPT_AES);
2197a9420734SKevin Wolf     } else {
2198f8413b3cSKevin Wolf         header->crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
2199a9420734SKevin Wolf     }
2200a9420734SKevin Wolf 
2201bfe8043eSStefan Hajnoczi     if (flags & BLOCK_FLAG_LAZY_REFCOUNTS) {
2202f8413b3cSKevin Wolf         header->compatible_features |=
2203bfe8043eSStefan Hajnoczi             cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS);
2204bfe8043eSStefan Hajnoczi     }
2205bfe8043eSStefan Hajnoczi 
220623588797SKevin Wolf     ret = blk_pwrite(blk, 0, header, cluster_size);
2207f8413b3cSKevin Wolf     g_free(header);
2208a9420734SKevin Wolf     if (ret < 0) {
22093ef6c40aSMax Reitz         error_setg_errno(errp, -ret, "Could not write qcow2 header");
2210a9420734SKevin Wolf         goto out;
2211a9420734SKevin Wolf     }
2212a9420734SKevin Wolf 
2213b106ad91SKevin Wolf     /* Write a refcount table with one refcount block */
2214b106ad91SKevin Wolf     refcount_table = g_malloc0(2 * cluster_size);
2215b106ad91SKevin Wolf     refcount_table[0] = cpu_to_be64(2 * cluster_size);
221623588797SKevin Wolf     ret = blk_pwrite(blk, cluster_size, refcount_table, 2 * cluster_size);
22177267c094SAnthony Liguori     g_free(refcount_table);
2218a9420734SKevin Wolf 
2219a9420734SKevin Wolf     if (ret < 0) {
22203ef6c40aSMax Reitz         error_setg_errno(errp, -ret, "Could not write refcount table");
2221a9420734SKevin Wolf         goto out;
2222a9420734SKevin Wolf     }
2223a9420734SKevin Wolf 
222423588797SKevin Wolf     blk_unref(blk);
222523588797SKevin Wolf     blk = NULL;
2226a9420734SKevin Wolf 
2227a9420734SKevin Wolf     /*
2228a9420734SKevin Wolf      * And now open the image and make it consistent first (i.e. increase the
2229a9420734SKevin Wolf      * refcount of the cluster that is occupied by the header and the refcount
2230a9420734SKevin Wolf      * table)
2231a9420734SKevin Wolf      */
2232e6641719SMax Reitz     options = qdict_new();
2233e6641719SMax Reitz     qdict_put(options, "driver", qstring_from_str("qcow2"));
2234efaa7c4eSMax Reitz     blk = blk_new_open(filename, NULL, options,
2235*72e775c7SKevin Wolf                        BDRV_O_RDWR | BDRV_O_NO_FLUSH, &local_err);
223623588797SKevin Wolf     if (blk == NULL) {
22373ef6c40aSMax Reitz         error_propagate(errp, local_err);
223823588797SKevin Wolf         ret = -EIO;
2239a9420734SKevin Wolf         goto out;
2240a9420734SKevin Wolf     }
2241a9420734SKevin Wolf 
224223588797SKevin Wolf     ret = qcow2_alloc_clusters(blk_bs(blk), 3 * cluster_size);
2243a9420734SKevin Wolf     if (ret < 0) {
22443ef6c40aSMax Reitz         error_setg_errno(errp, -ret, "Could not allocate clusters for qcow2 "
22453ef6c40aSMax Reitz                          "header and refcount table");
2246a9420734SKevin Wolf         goto out;
2247a9420734SKevin Wolf 
2248a9420734SKevin Wolf     } else if (ret != 0) {
2249a9420734SKevin Wolf         error_report("Huh, first cluster in empty image is already in use?");
2250a9420734SKevin Wolf         abort();
2251a9420734SKevin Wolf     }
2252a9420734SKevin Wolf 
2253b527c9b3SKevin Wolf     /* Create a full header (including things like feature table) */
225423588797SKevin Wolf     ret = qcow2_update_header(blk_bs(blk));
2255b527c9b3SKevin Wolf     if (ret < 0) {
2256b527c9b3SKevin Wolf         error_setg_errno(errp, -ret, "Could not update qcow2 header");
2257b527c9b3SKevin Wolf         goto out;
2258b527c9b3SKevin Wolf     }
2259b527c9b3SKevin Wolf 
2260a9420734SKevin Wolf     /* Okay, now that we have a valid image, let's give it the right size */
226123588797SKevin Wolf     ret = blk_truncate(blk, total_size);
2262a9420734SKevin Wolf     if (ret < 0) {
22633ef6c40aSMax Reitz         error_setg_errno(errp, -ret, "Could not resize image");
2264a9420734SKevin Wolf         goto out;
2265a9420734SKevin Wolf     }
2266a9420734SKevin Wolf 
2267a9420734SKevin Wolf     /* Want a backing file? There you go.*/
2268a9420734SKevin Wolf     if (backing_file) {
226923588797SKevin Wolf         ret = bdrv_change_backing_file(blk_bs(blk), backing_file, backing_format);
2270a9420734SKevin Wolf         if (ret < 0) {
22713ef6c40aSMax Reitz             error_setg_errno(errp, -ret, "Could not assign backing file '%s' "
22723ef6c40aSMax Reitz                              "with format '%s'", backing_file, backing_format);
2273a9420734SKevin Wolf             goto out;
2274a9420734SKevin Wolf         }
2275a9420734SKevin Wolf     }
2276a9420734SKevin Wolf 
2277a9420734SKevin Wolf     /* And if we're supposed to preallocate metadata, do that now */
22780e4271b7SHu Tao     if (prealloc != PREALLOC_MODE_OFF) {
227923588797SKevin Wolf         BDRVQcow2State *s = blk_bs(blk)->opaque;
228015552c4aSZhi Yong Wu         qemu_co_mutex_lock(&s->lock);
228123588797SKevin Wolf         ret = preallocate(blk_bs(blk));
228215552c4aSZhi Yong Wu         qemu_co_mutex_unlock(&s->lock);
2283a9420734SKevin Wolf         if (ret < 0) {
22843ef6c40aSMax Reitz             error_setg_errno(errp, -ret, "Could not preallocate metadata");
2285a9420734SKevin Wolf             goto out;
2286a9420734SKevin Wolf         }
2287a9420734SKevin Wolf     }
2288a9420734SKevin Wolf 
228923588797SKevin Wolf     blk_unref(blk);
229023588797SKevin Wolf     blk = NULL;
2291ba2ab2f2SMax Reitz 
2292ba2ab2f2SMax Reitz     /* Reopen the image without BDRV_O_NO_FLUSH to flush it before returning */
2293e6641719SMax Reitz     options = qdict_new();
2294e6641719SMax Reitz     qdict_put(options, "driver", qstring_from_str("qcow2"));
2295efaa7c4eSMax Reitz     blk = blk_new_open(filename, NULL, options,
2296*72e775c7SKevin Wolf                        BDRV_O_RDWR | BDRV_O_NO_BACKING, &local_err);
229723588797SKevin Wolf     if (blk == NULL) {
2298ba2ab2f2SMax Reitz         error_propagate(errp, local_err);
229923588797SKevin Wolf         ret = -EIO;
2300ba2ab2f2SMax Reitz         goto out;
2301ba2ab2f2SMax Reitz     }
2302ba2ab2f2SMax Reitz 
2303a9420734SKevin Wolf     ret = 0;
2304a9420734SKevin Wolf out:
230523588797SKevin Wolf     if (blk) {
230623588797SKevin Wolf         blk_unref(blk);
2307f67503e5SMax Reitz     }
2308a9420734SKevin Wolf     return ret;
2309a9420734SKevin Wolf }
2310de5f3f40SKevin Wolf 
23111bd0e2d1SChunyan Liu static int qcow2_create(const char *filename, QemuOpts *opts, Error **errp)
2312de5f3f40SKevin Wolf {
23131bd0e2d1SChunyan Liu     char *backing_file = NULL;
23141bd0e2d1SChunyan Liu     char *backing_fmt = NULL;
23151bd0e2d1SChunyan Liu     char *buf = NULL;
2316180e9526SHu Tao     uint64_t size = 0;
2317de5f3f40SKevin Wolf     int flags = 0;
231899cce9faSKevin Wolf     size_t cluster_size = DEFAULT_CLUSTER_SIZE;
2319ffeaac9bSHu Tao     PreallocMode prealloc;
23208ad1898cSKevin Wolf     int version = 3;
2321bd4b167fSMax Reitz     uint64_t refcount_bits = 16;
2322bd4b167fSMax Reitz     int refcount_order;
23233ef6c40aSMax Reitz     Error *local_err = NULL;
23243ef6c40aSMax Reitz     int ret;
2325de5f3f40SKevin Wolf 
2326de5f3f40SKevin Wolf     /* Read out options */
2327180e9526SHu Tao     size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
2328c2eb918eSHu Tao                     BDRV_SECTOR_SIZE);
23291bd0e2d1SChunyan Liu     backing_file = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
23301bd0e2d1SChunyan Liu     backing_fmt = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FMT);
23311bd0e2d1SChunyan Liu     if (qemu_opt_get_bool_del(opts, BLOCK_OPT_ENCRYPT, false)) {
23321bd0e2d1SChunyan Liu         flags |= BLOCK_FLAG_ENCRYPT;
2333de5f3f40SKevin Wolf     }
23341bd0e2d1SChunyan Liu     cluster_size = qemu_opt_get_size_del(opts, BLOCK_OPT_CLUSTER_SIZE,
23351bd0e2d1SChunyan Liu                                          DEFAULT_CLUSTER_SIZE);
23361bd0e2d1SChunyan Liu     buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
2337ffeaac9bSHu Tao     prealloc = qapi_enum_parse(PreallocMode_lookup, buf,
23387fb1cf16SEric Blake                                PREALLOC_MODE__MAX, PREALLOC_MODE_OFF,
2339ffeaac9bSHu Tao                                &local_err);
2340ffeaac9bSHu Tao     if (local_err) {
2341ffeaac9bSHu Tao         error_propagate(errp, local_err);
23421bd0e2d1SChunyan Liu         ret = -EINVAL;
23431bd0e2d1SChunyan Liu         goto finish;
2344de5f3f40SKevin Wolf     }
23451bd0e2d1SChunyan Liu     g_free(buf);
23461bd0e2d1SChunyan Liu     buf = qemu_opt_get_del(opts, BLOCK_OPT_COMPAT_LEVEL);
23471bd0e2d1SChunyan Liu     if (!buf) {
23489117b477SKevin Wolf         /* keep the default */
23491bd0e2d1SChunyan Liu     } else if (!strcmp(buf, "0.10")) {
23506744cbabSKevin Wolf         version = 2;
23511bd0e2d1SChunyan Liu     } else if (!strcmp(buf, "1.1")) {
23526744cbabSKevin Wolf         version = 3;
23536744cbabSKevin Wolf     } else {
23541bd0e2d1SChunyan Liu         error_setg(errp, "Invalid compatibility level: '%s'", buf);
23551bd0e2d1SChunyan Liu         ret = -EINVAL;
23561bd0e2d1SChunyan Liu         goto finish;
23576744cbabSKevin Wolf     }
23581bd0e2d1SChunyan Liu 
23591bd0e2d1SChunyan Liu     if (qemu_opt_get_bool_del(opts, BLOCK_OPT_LAZY_REFCOUNTS, false)) {
23601bd0e2d1SChunyan Liu         flags |= BLOCK_FLAG_LAZY_REFCOUNTS;
2361de5f3f40SKevin Wolf     }
2362de5f3f40SKevin Wolf 
2363ffeaac9bSHu Tao     if (backing_file && prealloc != PREALLOC_MODE_OFF) {
23643ef6c40aSMax Reitz         error_setg(errp, "Backing file and preallocation cannot be used at "
23653ef6c40aSMax Reitz                    "the same time");
23661bd0e2d1SChunyan Liu         ret = -EINVAL;
23671bd0e2d1SChunyan Liu         goto finish;
2368de5f3f40SKevin Wolf     }
2369de5f3f40SKevin Wolf 
2370bfe8043eSStefan Hajnoczi     if (version < 3 && (flags & BLOCK_FLAG_LAZY_REFCOUNTS)) {
23713ef6c40aSMax Reitz         error_setg(errp, "Lazy refcounts only supported with compatibility "
23723ef6c40aSMax Reitz                    "level 1.1 and above (use compat=1.1 or greater)");
23731bd0e2d1SChunyan Liu         ret = -EINVAL;
23741bd0e2d1SChunyan Liu         goto finish;
2375bfe8043eSStefan Hajnoczi     }
2376bfe8043eSStefan Hajnoczi 
237706d05fa7SMax Reitz     refcount_bits = qemu_opt_get_number_del(opts, BLOCK_OPT_REFCOUNT_BITS,
237806d05fa7SMax Reitz                                             refcount_bits);
237906d05fa7SMax Reitz     if (refcount_bits > 64 || !is_power_of_2(refcount_bits)) {
238006d05fa7SMax Reitz         error_setg(errp, "Refcount width must be a power of two and may not "
238106d05fa7SMax Reitz                    "exceed 64 bits");
238206d05fa7SMax Reitz         ret = -EINVAL;
238306d05fa7SMax Reitz         goto finish;
238406d05fa7SMax Reitz     }
238506d05fa7SMax Reitz 
2386bd4b167fSMax Reitz     if (version < 3 && refcount_bits != 16) {
2387bd4b167fSMax Reitz         error_setg(errp, "Different refcount widths than 16 bits require "
2388bd4b167fSMax Reitz                    "compatibility level 1.1 or above (use compat=1.1 or "
2389bd4b167fSMax Reitz                    "greater)");
2390bd4b167fSMax Reitz         ret = -EINVAL;
2391bd4b167fSMax Reitz         goto finish;
2392bd4b167fSMax Reitz     }
2393bd4b167fSMax Reitz 
2394786a4ea8SStefan Hajnoczi     refcount_order = ctz32(refcount_bits);
2395bd4b167fSMax Reitz 
2396180e9526SHu Tao     ret = qcow2_create2(filename, size, backing_file, backing_fmt, flags,
2397bd4b167fSMax Reitz                         cluster_size, prealloc, opts, version, refcount_order,
2398bd4b167fSMax Reitz                         &local_err);
239984d18f06SMarkus Armbruster     if (local_err) {
24003ef6c40aSMax Reitz         error_propagate(errp, local_err);
24013ef6c40aSMax Reitz     }
24021bd0e2d1SChunyan Liu 
24031bd0e2d1SChunyan Liu finish:
24041bd0e2d1SChunyan Liu     g_free(backing_file);
24051bd0e2d1SChunyan Liu     g_free(backing_fmt);
24061bd0e2d1SChunyan Liu     g_free(buf);
24073ef6c40aSMax Reitz     return ret;
2408de5f3f40SKevin Wolf }
2409de5f3f40SKevin Wolf 
2410621f0589SKevin Wolf static coroutine_fn int qcow2_co_write_zeroes(BlockDriverState *bs,
2411aa7bfbffSPeter Lieven     int64_t sector_num, int nb_sectors, BdrvRequestFlags flags)
2412621f0589SKevin Wolf {
2413621f0589SKevin Wolf     int ret;
2414ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
2415621f0589SKevin Wolf 
2416621f0589SKevin Wolf     /* Emulate misaligned zero writes */
2417621f0589SKevin Wolf     if (sector_num % s->cluster_sectors || nb_sectors % s->cluster_sectors) {
2418621f0589SKevin Wolf         return -ENOTSUP;
2419621f0589SKevin Wolf     }
2420621f0589SKevin Wolf 
2421621f0589SKevin Wolf     /* Whatever is left can use real zero clusters */
2422621f0589SKevin Wolf     qemu_co_mutex_lock(&s->lock);
2423621f0589SKevin Wolf     ret = qcow2_zero_clusters(bs, sector_num << BDRV_SECTOR_BITS,
2424621f0589SKevin Wolf         nb_sectors);
2425621f0589SKevin Wolf     qemu_co_mutex_unlock(&s->lock);
2426621f0589SKevin Wolf 
2427621f0589SKevin Wolf     return ret;
2428621f0589SKevin Wolf }
2429621f0589SKevin Wolf 
24306db39ae2SPaolo Bonzini static coroutine_fn int qcow2_co_discard(BlockDriverState *bs,
24316db39ae2SPaolo Bonzini     int64_t sector_num, int nb_sectors)
24325ea929e3SKevin Wolf {
24336db39ae2SPaolo Bonzini     int ret;
2434ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
24356db39ae2SPaolo Bonzini 
24366db39ae2SPaolo Bonzini     qemu_co_mutex_lock(&s->lock);
24376db39ae2SPaolo Bonzini     ret = qcow2_discard_clusters(bs, sector_num << BDRV_SECTOR_BITS,
2438808c4b6fSMax Reitz         nb_sectors, QCOW2_DISCARD_REQUEST, false);
24396db39ae2SPaolo Bonzini     qemu_co_mutex_unlock(&s->lock);
24406db39ae2SPaolo Bonzini     return ret;
24415ea929e3SKevin Wolf }
24425ea929e3SKevin Wolf 
2443419b19d9SStefan Hajnoczi static int qcow2_truncate(BlockDriverState *bs, int64_t offset)
2444419b19d9SStefan Hajnoczi {
2445ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
24462cf7cfa1SKevin Wolf     int64_t new_l1_size;
24472cf7cfa1SKevin Wolf     int ret;
2448419b19d9SStefan Hajnoczi 
2449419b19d9SStefan Hajnoczi     if (offset & 511) {
2450259b2173SKevin Wolf         error_report("The new size must be a multiple of 512");
2451419b19d9SStefan Hajnoczi         return -EINVAL;
2452419b19d9SStefan Hajnoczi     }
2453419b19d9SStefan Hajnoczi 
2454419b19d9SStefan Hajnoczi     /* cannot proceed if image has snapshots */
2455419b19d9SStefan Hajnoczi     if (s->nb_snapshots) {
2456259b2173SKevin Wolf         error_report("Can't resize an image which has snapshots");
2457419b19d9SStefan Hajnoczi         return -ENOTSUP;
2458419b19d9SStefan Hajnoczi     }
2459419b19d9SStefan Hajnoczi 
2460419b19d9SStefan Hajnoczi     /* shrinking is currently not supported */
2461419b19d9SStefan Hajnoczi     if (offset < bs->total_sectors * 512) {
2462259b2173SKevin Wolf         error_report("qcow2 doesn't support shrinking images yet");
2463419b19d9SStefan Hajnoczi         return -ENOTSUP;
2464419b19d9SStefan Hajnoczi     }
2465419b19d9SStefan Hajnoczi 
2466419b19d9SStefan Hajnoczi     new_l1_size = size_to_l1(s, offset);
246772893756SStefan Hajnoczi     ret = qcow2_grow_l1_table(bs, new_l1_size, true);
2468419b19d9SStefan Hajnoczi     if (ret < 0) {
2469419b19d9SStefan Hajnoczi         return ret;
2470419b19d9SStefan Hajnoczi     }
2471419b19d9SStefan Hajnoczi 
2472419b19d9SStefan Hajnoczi     /* write updated header.size */
2473419b19d9SStefan Hajnoczi     offset = cpu_to_be64(offset);
24749a4f4c31SKevin Wolf     ret = bdrv_pwrite_sync(bs->file->bs, offsetof(QCowHeader, size),
2475419b19d9SStefan Hajnoczi                            &offset, sizeof(uint64_t));
2476419b19d9SStefan Hajnoczi     if (ret < 0) {
2477419b19d9SStefan Hajnoczi         return ret;
2478419b19d9SStefan Hajnoczi     }
2479419b19d9SStefan Hajnoczi 
2480419b19d9SStefan Hajnoczi     s->l1_vm_state_index = new_l1_size;
2481419b19d9SStefan Hajnoczi     return 0;
2482419b19d9SStefan Hajnoczi }
2483419b19d9SStefan Hajnoczi 
248420d97356SBlue Swirl /* XXX: put compressed sectors first, then all the cluster aligned
248520d97356SBlue Swirl    tables to avoid losing bytes in alignment */
24867c80ab3fSJes Sorensen static int qcow2_write_compressed(BlockDriverState *bs, int64_t sector_num,
248720d97356SBlue Swirl                                   const uint8_t *buf, int nb_sectors)
248820d97356SBlue Swirl {
2489ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
249020d97356SBlue Swirl     z_stream strm;
249120d97356SBlue Swirl     int ret, out_len;
249220d97356SBlue Swirl     uint8_t *out_buf;
249320d97356SBlue Swirl     uint64_t cluster_offset;
249420d97356SBlue Swirl 
249520d97356SBlue Swirl     if (nb_sectors == 0) {
249620d97356SBlue Swirl         /* align end of file to a sector boundary to ease reading with
249720d97356SBlue Swirl            sector based I/Os */
24989a4f4c31SKevin Wolf         cluster_offset = bdrv_getlength(bs->file->bs);
24999a4f4c31SKevin Wolf         return bdrv_truncate(bs->file->bs, cluster_offset);
250020d97356SBlue Swirl     }
250120d97356SBlue Swirl 
2502f4d38befSStefan Hajnoczi     if (nb_sectors != s->cluster_sectors) {
2503f4d38befSStefan Hajnoczi         ret = -EINVAL;
2504f4d38befSStefan Hajnoczi 
2505f4d38befSStefan Hajnoczi         /* Zero-pad last write if image size is not cluster aligned */
2506f4d38befSStefan Hajnoczi         if (sector_num + nb_sectors == bs->total_sectors &&
2507f4d38befSStefan Hajnoczi             nb_sectors < s->cluster_sectors) {
2508f4d38befSStefan Hajnoczi             uint8_t *pad_buf = qemu_blockalign(bs, s->cluster_size);
2509f4d38befSStefan Hajnoczi             memset(pad_buf, 0, s->cluster_size);
2510f4d38befSStefan Hajnoczi             memcpy(pad_buf, buf, nb_sectors * BDRV_SECTOR_SIZE);
2511f4d38befSStefan Hajnoczi             ret = qcow2_write_compressed(bs, sector_num,
2512f4d38befSStefan Hajnoczi                                          pad_buf, s->cluster_sectors);
2513f4d38befSStefan Hajnoczi             qemu_vfree(pad_buf);
2514f4d38befSStefan Hajnoczi         }
2515f4d38befSStefan Hajnoczi         return ret;
2516f4d38befSStefan Hajnoczi     }
251720d97356SBlue Swirl 
25187267c094SAnthony Liguori     out_buf = g_malloc(s->cluster_size + (s->cluster_size / 1000) + 128);
251920d97356SBlue Swirl 
252020d97356SBlue Swirl     /* best compression, small window, no zlib header */
252120d97356SBlue Swirl     memset(&strm, 0, sizeof(strm));
252220d97356SBlue Swirl     ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
252320d97356SBlue Swirl                        Z_DEFLATED, -12,
252420d97356SBlue Swirl                        9, Z_DEFAULT_STRATEGY);
252520d97356SBlue Swirl     if (ret != 0) {
25268f1efd00SKevin Wolf         ret = -EINVAL;
25278f1efd00SKevin Wolf         goto fail;
252820d97356SBlue Swirl     }
252920d97356SBlue Swirl 
253020d97356SBlue Swirl     strm.avail_in = s->cluster_size;
253120d97356SBlue Swirl     strm.next_in = (uint8_t *)buf;
253220d97356SBlue Swirl     strm.avail_out = s->cluster_size;
253320d97356SBlue Swirl     strm.next_out = out_buf;
253420d97356SBlue Swirl 
253520d97356SBlue Swirl     ret = deflate(&strm, Z_FINISH);
253620d97356SBlue Swirl     if (ret != Z_STREAM_END && ret != Z_OK) {
253720d97356SBlue Swirl         deflateEnd(&strm);
25388f1efd00SKevin Wolf         ret = -EINVAL;
25398f1efd00SKevin Wolf         goto fail;
254020d97356SBlue Swirl     }
254120d97356SBlue Swirl     out_len = strm.next_out - out_buf;
254220d97356SBlue Swirl 
254320d97356SBlue Swirl     deflateEnd(&strm);
254420d97356SBlue Swirl 
254520d97356SBlue Swirl     if (ret != Z_STREAM_END || out_len >= s->cluster_size) {
254620d97356SBlue Swirl         /* could not compress: write normal cluster */
25478f1efd00SKevin Wolf         ret = bdrv_write(bs, sector_num, buf, s->cluster_sectors);
25488f1efd00SKevin Wolf         if (ret < 0) {
25498f1efd00SKevin Wolf             goto fail;
25508f1efd00SKevin Wolf         }
255120d97356SBlue Swirl     } else {
255220d97356SBlue Swirl         cluster_offset = qcow2_alloc_compressed_cluster_offset(bs,
255320d97356SBlue Swirl             sector_num << 9, out_len);
25548f1efd00SKevin Wolf         if (!cluster_offset) {
25558f1efd00SKevin Wolf             ret = -EIO;
25568f1efd00SKevin Wolf             goto fail;
25578f1efd00SKevin Wolf         }
255820d97356SBlue Swirl         cluster_offset &= s->cluster_offset_mask;
2559cf93980eSMax Reitz 
2560231bb267SMax Reitz         ret = qcow2_pre_write_overlap_check(bs, 0, cluster_offset, out_len);
2561cf93980eSMax Reitz         if (ret < 0) {
2562cf93980eSMax Reitz             goto fail;
2563cf93980eSMax Reitz         }
2564cf93980eSMax Reitz 
256566f82ceeSKevin Wolf         BLKDBG_EVENT(bs->file, BLKDBG_WRITE_COMPRESSED);
25669a4f4c31SKevin Wolf         ret = bdrv_pwrite(bs->file->bs, cluster_offset, out_buf, out_len);
25678f1efd00SKevin Wolf         if (ret < 0) {
25688f1efd00SKevin Wolf             goto fail;
256920d97356SBlue Swirl         }
257020d97356SBlue Swirl     }
257120d97356SBlue Swirl 
25728f1efd00SKevin Wolf     ret = 0;
25738f1efd00SKevin Wolf fail:
25747267c094SAnthony Liguori     g_free(out_buf);
25758f1efd00SKevin Wolf     return ret;
257620d97356SBlue Swirl }
257720d97356SBlue Swirl 
257894054183SMax Reitz static int make_completely_empty(BlockDriverState *bs)
257994054183SMax Reitz {
2580ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
258194054183SMax Reitz     int ret, l1_clusters;
258294054183SMax Reitz     int64_t offset;
258394054183SMax Reitz     uint64_t *new_reftable = NULL;
258494054183SMax Reitz     uint64_t rt_entry, l1_size2;
258594054183SMax Reitz     struct {
258694054183SMax Reitz         uint64_t l1_offset;
258794054183SMax Reitz         uint64_t reftable_offset;
258894054183SMax Reitz         uint32_t reftable_clusters;
258994054183SMax Reitz     } QEMU_PACKED l1_ofs_rt_ofs_cls;
259094054183SMax Reitz 
259194054183SMax Reitz     ret = qcow2_cache_empty(bs, s->l2_table_cache);
259294054183SMax Reitz     if (ret < 0) {
259394054183SMax Reitz         goto fail;
259494054183SMax Reitz     }
259594054183SMax Reitz 
259694054183SMax Reitz     ret = qcow2_cache_empty(bs, s->refcount_block_cache);
259794054183SMax Reitz     if (ret < 0) {
259894054183SMax Reitz         goto fail;
259994054183SMax Reitz     }
260094054183SMax Reitz 
260194054183SMax Reitz     /* Refcounts will be broken utterly */
260294054183SMax Reitz     ret = qcow2_mark_dirty(bs);
260394054183SMax Reitz     if (ret < 0) {
260494054183SMax Reitz         goto fail;
260594054183SMax Reitz     }
260694054183SMax Reitz 
260794054183SMax Reitz     BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
260894054183SMax Reitz 
260994054183SMax Reitz     l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / sizeof(uint64_t));
261094054183SMax Reitz     l1_size2 = (uint64_t)s->l1_size * sizeof(uint64_t);
261194054183SMax Reitz 
261294054183SMax Reitz     /* After this call, neither the in-memory nor the on-disk refcount
261394054183SMax Reitz      * information accurately describe the actual references */
261494054183SMax Reitz 
26159a4f4c31SKevin Wolf     ret = bdrv_write_zeroes(bs->file->bs, s->l1_table_offset / BDRV_SECTOR_SIZE,
261694054183SMax Reitz                             l1_clusters * s->cluster_sectors, 0);
261794054183SMax Reitz     if (ret < 0) {
261894054183SMax Reitz         goto fail_broken_refcounts;
261994054183SMax Reitz     }
262094054183SMax Reitz     memset(s->l1_table, 0, l1_size2);
262194054183SMax Reitz 
262294054183SMax Reitz     BLKDBG_EVENT(bs->file, BLKDBG_EMPTY_IMAGE_PREPARE);
262394054183SMax Reitz 
262494054183SMax Reitz     /* Overwrite enough clusters at the beginning of the sectors to place
262594054183SMax Reitz      * the refcount table, a refcount block and the L1 table in; this may
262694054183SMax Reitz      * overwrite parts of the existing refcount and L1 table, which is not
262794054183SMax Reitz      * an issue because the dirty flag is set, complete data loss is in fact
262894054183SMax Reitz      * desired and partial data loss is consequently fine as well */
26299a4f4c31SKevin Wolf     ret = bdrv_write_zeroes(bs->file->bs, s->cluster_size / BDRV_SECTOR_SIZE,
263094054183SMax Reitz                             (2 + l1_clusters) * s->cluster_size /
263194054183SMax Reitz                             BDRV_SECTOR_SIZE, 0);
263294054183SMax Reitz     /* This call (even if it failed overall) may have overwritten on-disk
263394054183SMax Reitz      * refcount structures; in that case, the in-memory refcount information
263494054183SMax Reitz      * will probably differ from the on-disk information which makes the BDS
263594054183SMax Reitz      * unusable */
263694054183SMax Reitz     if (ret < 0) {
263794054183SMax Reitz         goto fail_broken_refcounts;
263894054183SMax Reitz     }
263994054183SMax Reitz 
264094054183SMax Reitz     BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
264194054183SMax Reitz     BLKDBG_EVENT(bs->file, BLKDBG_REFTABLE_UPDATE);
264294054183SMax Reitz 
264394054183SMax Reitz     /* "Create" an empty reftable (one cluster) directly after the image
264494054183SMax Reitz      * header and an empty L1 table three clusters after the image header;
264594054183SMax Reitz      * the cluster between those two will be used as the first refblock */
264694054183SMax Reitz     cpu_to_be64w(&l1_ofs_rt_ofs_cls.l1_offset, 3 * s->cluster_size);
264794054183SMax Reitz     cpu_to_be64w(&l1_ofs_rt_ofs_cls.reftable_offset, s->cluster_size);
264894054183SMax Reitz     cpu_to_be32w(&l1_ofs_rt_ofs_cls.reftable_clusters, 1);
26499a4f4c31SKevin Wolf     ret = bdrv_pwrite_sync(bs->file->bs, offsetof(QCowHeader, l1_table_offset),
265094054183SMax Reitz                            &l1_ofs_rt_ofs_cls, sizeof(l1_ofs_rt_ofs_cls));
265194054183SMax Reitz     if (ret < 0) {
265294054183SMax Reitz         goto fail_broken_refcounts;
265394054183SMax Reitz     }
265494054183SMax Reitz 
265594054183SMax Reitz     s->l1_table_offset = 3 * s->cluster_size;
265694054183SMax Reitz 
265794054183SMax Reitz     new_reftable = g_try_new0(uint64_t, s->cluster_size / sizeof(uint64_t));
265894054183SMax Reitz     if (!new_reftable) {
265994054183SMax Reitz         ret = -ENOMEM;
266094054183SMax Reitz         goto fail_broken_refcounts;
266194054183SMax Reitz     }
266294054183SMax Reitz 
266394054183SMax Reitz     s->refcount_table_offset = s->cluster_size;
266494054183SMax Reitz     s->refcount_table_size   = s->cluster_size / sizeof(uint64_t);
266594054183SMax Reitz 
266694054183SMax Reitz     g_free(s->refcount_table);
266794054183SMax Reitz     s->refcount_table = new_reftable;
266894054183SMax Reitz     new_reftable = NULL;
266994054183SMax Reitz 
267094054183SMax Reitz     /* Now the in-memory refcount information again corresponds to the on-disk
267194054183SMax Reitz      * information (reftable is empty and no refblocks (the refblock cache is
267294054183SMax Reitz      * empty)); however, this means some clusters (e.g. the image header) are
267394054183SMax Reitz      * referenced, but not refcounted, but the normal qcow2 code assumes that
267494054183SMax Reitz      * the in-memory information is always correct */
267594054183SMax Reitz 
267694054183SMax Reitz     BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_ALLOC);
267794054183SMax Reitz 
267894054183SMax Reitz     /* Enter the first refblock into the reftable */
267994054183SMax Reitz     rt_entry = cpu_to_be64(2 * s->cluster_size);
26809a4f4c31SKevin Wolf     ret = bdrv_pwrite_sync(bs->file->bs, s->cluster_size,
268194054183SMax Reitz                            &rt_entry, sizeof(rt_entry));
268294054183SMax Reitz     if (ret < 0) {
268394054183SMax Reitz         goto fail_broken_refcounts;
268494054183SMax Reitz     }
268594054183SMax Reitz     s->refcount_table[0] = 2 * s->cluster_size;
268694054183SMax Reitz 
268794054183SMax Reitz     s->free_cluster_index = 0;
268894054183SMax Reitz     assert(3 + l1_clusters <= s->refcount_block_size);
268994054183SMax Reitz     offset = qcow2_alloc_clusters(bs, 3 * s->cluster_size + l1_size2);
269094054183SMax Reitz     if (offset < 0) {
269194054183SMax Reitz         ret = offset;
269294054183SMax Reitz         goto fail_broken_refcounts;
269394054183SMax Reitz     } else if (offset > 0) {
269494054183SMax Reitz         error_report("First cluster in emptied image is in use");
269594054183SMax Reitz         abort();
269694054183SMax Reitz     }
269794054183SMax Reitz 
269894054183SMax Reitz     /* Now finally the in-memory information corresponds to the on-disk
269994054183SMax Reitz      * structures and is correct */
270094054183SMax Reitz     ret = qcow2_mark_clean(bs);
270194054183SMax Reitz     if (ret < 0) {
270294054183SMax Reitz         goto fail;
270394054183SMax Reitz     }
270494054183SMax Reitz 
27059a4f4c31SKevin Wolf     ret = bdrv_truncate(bs->file->bs, (3 + l1_clusters) * s->cluster_size);
270694054183SMax Reitz     if (ret < 0) {
270794054183SMax Reitz         goto fail;
270894054183SMax Reitz     }
270994054183SMax Reitz 
271094054183SMax Reitz     return 0;
271194054183SMax Reitz 
271294054183SMax Reitz fail_broken_refcounts:
271394054183SMax Reitz     /* The BDS is unusable at this point. If we wanted to make it usable, we
271494054183SMax Reitz      * would have to call qcow2_refcount_close(), qcow2_refcount_init(),
271594054183SMax Reitz      * qcow2_check_refcounts(), qcow2_refcount_close() and qcow2_refcount_init()
271694054183SMax Reitz      * again. However, because the functions which could have caused this error
271794054183SMax Reitz      * path to be taken are used by those functions as well, it's very likely
271894054183SMax Reitz      * that that sequence will fail as well. Therefore, just eject the BDS. */
271994054183SMax Reitz     bs->drv = NULL;
272094054183SMax Reitz 
272194054183SMax Reitz fail:
272294054183SMax Reitz     g_free(new_reftable);
272394054183SMax Reitz     return ret;
272494054183SMax Reitz }
272594054183SMax Reitz 
2726491d27e2SMax Reitz static int qcow2_make_empty(BlockDriverState *bs)
2727491d27e2SMax Reitz {
2728ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
2729491d27e2SMax Reitz     uint64_t start_sector;
2730491d27e2SMax Reitz     int sector_step = INT_MAX / BDRV_SECTOR_SIZE;
273194054183SMax Reitz     int l1_clusters, ret = 0;
2732491d27e2SMax Reitz 
273394054183SMax Reitz     l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / sizeof(uint64_t));
273494054183SMax Reitz 
273594054183SMax Reitz     if (s->qcow_version >= 3 && !s->snapshots &&
273694054183SMax Reitz         3 + l1_clusters <= s->refcount_block_size) {
273794054183SMax Reitz         /* The following function only works for qcow2 v3 images (it requires
273894054183SMax Reitz          * the dirty flag) and only as long as there are no snapshots (because
273994054183SMax Reitz          * it completely empties the image). Furthermore, the L1 table and three
274094054183SMax Reitz          * additional clusters (image header, refcount table, one refcount
274194054183SMax Reitz          * block) have to fit inside one refcount block. */
274294054183SMax Reitz         return make_completely_empty(bs);
274394054183SMax Reitz     }
274494054183SMax Reitz 
274594054183SMax Reitz     /* This fallback code simply discards every active cluster; this is slow,
274694054183SMax Reitz      * but works in all cases */
2747491d27e2SMax Reitz     for (start_sector = 0; start_sector < bs->total_sectors;
2748491d27e2SMax Reitz          start_sector += sector_step)
2749491d27e2SMax Reitz     {
2750491d27e2SMax Reitz         /* As this function is generally used after committing an external
2751491d27e2SMax Reitz          * snapshot, QCOW2_DISCARD_SNAPSHOT seems appropriate. Also, the
2752491d27e2SMax Reitz          * default action for this kind of discard is to pass the discard,
2753491d27e2SMax Reitz          * which will ideally result in an actually smaller image file, as
2754491d27e2SMax Reitz          * is probably desired. */
2755491d27e2SMax Reitz         ret = qcow2_discard_clusters(bs, start_sector * BDRV_SECTOR_SIZE,
2756491d27e2SMax Reitz                                      MIN(sector_step,
2757491d27e2SMax Reitz                                          bs->total_sectors - start_sector),
2758491d27e2SMax Reitz                                      QCOW2_DISCARD_SNAPSHOT, true);
2759491d27e2SMax Reitz         if (ret < 0) {
2760491d27e2SMax Reitz             break;
2761491d27e2SMax Reitz         }
2762491d27e2SMax Reitz     }
2763491d27e2SMax Reitz 
2764491d27e2SMax Reitz     return ret;
2765491d27e2SMax Reitz }
2766491d27e2SMax Reitz 
2767a968168cSDong Xu Wang static coroutine_fn int qcow2_co_flush_to_os(BlockDriverState *bs)
276820d97356SBlue Swirl {
2769ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
277029c1a730SKevin Wolf     int ret;
277129c1a730SKevin Wolf 
27728b94ff85SPaolo Bonzini     qemu_co_mutex_lock(&s->lock);
277329c1a730SKevin Wolf     ret = qcow2_cache_flush(bs, s->l2_table_cache);
277429c1a730SKevin Wolf     if (ret < 0) {
2775c95de7e2SDong Xu Wang         qemu_co_mutex_unlock(&s->lock);
27768b94ff85SPaolo Bonzini         return ret;
277729c1a730SKevin Wolf     }
277829c1a730SKevin Wolf 
2779bfe8043eSStefan Hajnoczi     if (qcow2_need_accurate_refcounts(s)) {
278029c1a730SKevin Wolf         ret = qcow2_cache_flush(bs, s->refcount_block_cache);
278129c1a730SKevin Wolf         if (ret < 0) {
2782c95de7e2SDong Xu Wang             qemu_co_mutex_unlock(&s->lock);
27838b94ff85SPaolo Bonzini             return ret;
278429c1a730SKevin Wolf         }
2785bfe8043eSStefan Hajnoczi     }
27868b94ff85SPaolo Bonzini     qemu_co_mutex_unlock(&s->lock);
278729c1a730SKevin Wolf 
2788eb489bb1SKevin Wolf     return 0;
2789eb489bb1SKevin Wolf }
2790eb489bb1SKevin Wolf 
27917c80ab3fSJes Sorensen static int qcow2_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
279220d97356SBlue Swirl {
2793ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
279495de6d70SPaolo Bonzini     bdi->unallocated_blocks_are_zero = true;
279595de6d70SPaolo Bonzini     bdi->can_write_zeroes_with_unmap = (s->qcow_version >= 3);
279620d97356SBlue Swirl     bdi->cluster_size = s->cluster_size;
27977c80ab3fSJes Sorensen     bdi->vm_state_offset = qcow2_vm_state_offset(s);
279820d97356SBlue Swirl     return 0;
279920d97356SBlue Swirl }
280020d97356SBlue Swirl 
280137764dfbSMax Reitz static ImageInfoSpecific *qcow2_get_specific_info(BlockDriverState *bs)
280237764dfbSMax Reitz {
2803ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
280437764dfbSMax Reitz     ImageInfoSpecific *spec_info = g_new(ImageInfoSpecific, 1);
280537764dfbSMax Reitz 
280637764dfbSMax Reitz     *spec_info = (ImageInfoSpecific){
28076a8f9661SEric Blake         .type  = IMAGE_INFO_SPECIFIC_KIND_QCOW2,
280832bafa8fSEric Blake         .u.qcow2.data = g_new(ImageInfoSpecificQCow2, 1),
280937764dfbSMax Reitz     };
281037764dfbSMax Reitz     if (s->qcow_version == 2) {
281132bafa8fSEric Blake         *spec_info->u.qcow2.data = (ImageInfoSpecificQCow2){
281237764dfbSMax Reitz             .compat             = g_strdup("0.10"),
28130709c5a1SMax Reitz             .refcount_bits      = s->refcount_bits,
281437764dfbSMax Reitz         };
281537764dfbSMax Reitz     } else if (s->qcow_version == 3) {
281632bafa8fSEric Blake         *spec_info->u.qcow2.data = (ImageInfoSpecificQCow2){
281737764dfbSMax Reitz             .compat             = g_strdup("1.1"),
281837764dfbSMax Reitz             .lazy_refcounts     = s->compatible_features &
281937764dfbSMax Reitz                                   QCOW2_COMPAT_LAZY_REFCOUNTS,
282037764dfbSMax Reitz             .has_lazy_refcounts = true,
28219009b196SMax Reitz             .corrupt            = s->incompatible_features &
28229009b196SMax Reitz                                   QCOW2_INCOMPAT_CORRUPT,
28239009b196SMax Reitz             .has_corrupt        = true,
28240709c5a1SMax Reitz             .refcount_bits      = s->refcount_bits,
282537764dfbSMax Reitz         };
2826b1fc8f93SDenis V. Lunev     } else {
2827b1fc8f93SDenis V. Lunev         /* if this assertion fails, this probably means a new version was
2828b1fc8f93SDenis V. Lunev          * added without having it covered here */
2829b1fc8f93SDenis V. Lunev         assert(false);
283037764dfbSMax Reitz     }
283137764dfbSMax Reitz 
283237764dfbSMax Reitz     return spec_info;
283337764dfbSMax Reitz }
283437764dfbSMax Reitz 
283520d97356SBlue Swirl #if 0
283620d97356SBlue Swirl static void dump_refcounts(BlockDriverState *bs)
283720d97356SBlue Swirl {
2838ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
283920d97356SBlue Swirl     int64_t nb_clusters, k, k1, size;
284020d97356SBlue Swirl     int refcount;
284120d97356SBlue Swirl 
28429a4f4c31SKevin Wolf     size = bdrv_getlength(bs->file->bs);
284320d97356SBlue Swirl     nb_clusters = size_to_clusters(s, size);
284420d97356SBlue Swirl     for(k = 0; k < nb_clusters;) {
284520d97356SBlue Swirl         k1 = k;
284620d97356SBlue Swirl         refcount = get_refcount(bs, k);
284720d97356SBlue Swirl         k++;
284820d97356SBlue Swirl         while (k < nb_clusters && get_refcount(bs, k) == refcount)
284920d97356SBlue Swirl             k++;
28500bfcd599SBlue Swirl         printf("%" PRId64 ": refcount=%d nb=%" PRId64 "\n", k, refcount,
28510bfcd599SBlue Swirl                k - k1);
285220d97356SBlue Swirl     }
285320d97356SBlue Swirl }
285420d97356SBlue Swirl #endif
285520d97356SBlue Swirl 
2856cf8074b3SKevin Wolf static int qcow2_save_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
2857cf8074b3SKevin Wolf                               int64_t pos)
285820d97356SBlue Swirl {
2859ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
2860eedff66fSMax Reitz     int64_t total_sectors = bs->total_sectors;
28616e13610aSMax Reitz     bool zero_beyond_eof = bs->zero_beyond_eof;
286220d97356SBlue Swirl     int ret;
286320d97356SBlue Swirl 
286466f82ceeSKevin Wolf     BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_SAVE);
28656e13610aSMax Reitz     bs->zero_beyond_eof = false;
28668d3b1a2dSKevin Wolf     ret = bdrv_pwritev(bs, qcow2_vm_state_offset(s) + pos, qiov);
28676e13610aSMax Reitz     bs->zero_beyond_eof = zero_beyond_eof;
286820d97356SBlue Swirl 
2869eedff66fSMax Reitz     /* bdrv_co_do_writev will have increased the total_sectors value to include
2870eedff66fSMax Reitz      * the VM state - the VM state is however not an actual part of the block
2871eedff66fSMax Reitz      * device, therefore, we need to restore the old value. */
2872eedff66fSMax Reitz     bs->total_sectors = total_sectors;
2873eedff66fSMax Reitz 
287420d97356SBlue Swirl     return ret;
287520d97356SBlue Swirl }
287620d97356SBlue Swirl 
28777c80ab3fSJes Sorensen static int qcow2_load_vmstate(BlockDriverState *bs, uint8_t *buf,
287820d97356SBlue Swirl                               int64_t pos, int size)
287920d97356SBlue Swirl {
2880ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
28810d51b4deSAsias He     bool zero_beyond_eof = bs->zero_beyond_eof;
288220d97356SBlue Swirl     int ret;
288320d97356SBlue Swirl 
288466f82ceeSKevin Wolf     BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_LOAD);
28850d51b4deSAsias He     bs->zero_beyond_eof = false;
28867c80ab3fSJes Sorensen     ret = bdrv_pread(bs, qcow2_vm_state_offset(s) + pos, buf, size);
28870d51b4deSAsias He     bs->zero_beyond_eof = zero_beyond_eof;
288820d97356SBlue Swirl 
288920d97356SBlue Swirl     return ret;
289020d97356SBlue Swirl }
289120d97356SBlue Swirl 
28929296b3edSMax Reitz /*
28939296b3edSMax Reitz  * Downgrades an image's version. To achieve this, any incompatible features
28949296b3edSMax Reitz  * have to be removed.
28959296b3edSMax Reitz  */
28964057a2b2SMax Reitz static int qcow2_downgrade(BlockDriverState *bs, int target_version,
28978b13976dSMax Reitz                            BlockDriverAmendStatusCB *status_cb, void *cb_opaque)
28989296b3edSMax Reitz {
2899ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
29009296b3edSMax Reitz     int current_version = s->qcow_version;
29019296b3edSMax Reitz     int ret;
29029296b3edSMax Reitz 
29039296b3edSMax Reitz     if (target_version == current_version) {
29049296b3edSMax Reitz         return 0;
29059296b3edSMax Reitz     } else if (target_version > current_version) {
29069296b3edSMax Reitz         return -EINVAL;
29079296b3edSMax Reitz     } else if (target_version != 2) {
29089296b3edSMax Reitz         return -EINVAL;
29099296b3edSMax Reitz     }
29109296b3edSMax Reitz 
29119296b3edSMax Reitz     if (s->refcount_order != 4) {
291261ce55fcSMax Reitz         error_report("compat=0.10 requires refcount_bits=16");
29139296b3edSMax Reitz         return -ENOTSUP;
29149296b3edSMax Reitz     }
29159296b3edSMax Reitz 
29169296b3edSMax Reitz     /* clear incompatible features */
29179296b3edSMax Reitz     if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
29189296b3edSMax Reitz         ret = qcow2_mark_clean(bs);
29199296b3edSMax Reitz         if (ret < 0) {
29209296b3edSMax Reitz             return ret;
29219296b3edSMax Reitz         }
29229296b3edSMax Reitz     }
29239296b3edSMax Reitz 
29249296b3edSMax Reitz     /* with QCOW2_INCOMPAT_CORRUPT, it is pretty much impossible to get here in
29259296b3edSMax Reitz      * the first place; if that happens nonetheless, returning -ENOTSUP is the
29269296b3edSMax Reitz      * best thing to do anyway */
29279296b3edSMax Reitz 
29289296b3edSMax Reitz     if (s->incompatible_features) {
29299296b3edSMax Reitz         return -ENOTSUP;
29309296b3edSMax Reitz     }
29319296b3edSMax Reitz 
29329296b3edSMax Reitz     /* since we can ignore compatible features, we can set them to 0 as well */
29339296b3edSMax Reitz     s->compatible_features = 0;
29349296b3edSMax Reitz     /* if lazy refcounts have been used, they have already been fixed through
29359296b3edSMax Reitz      * clearing the dirty flag */
29369296b3edSMax Reitz 
29379296b3edSMax Reitz     /* clearing autoclear features is trivial */
29389296b3edSMax Reitz     s->autoclear_features = 0;
29399296b3edSMax Reitz 
29408b13976dSMax Reitz     ret = qcow2_expand_zero_clusters(bs, status_cb, cb_opaque);
29419296b3edSMax Reitz     if (ret < 0) {
29429296b3edSMax Reitz         return ret;
29439296b3edSMax Reitz     }
29449296b3edSMax Reitz 
29459296b3edSMax Reitz     s->qcow_version = target_version;
29469296b3edSMax Reitz     ret = qcow2_update_header(bs);
29479296b3edSMax Reitz     if (ret < 0) {
29489296b3edSMax Reitz         s->qcow_version = current_version;
29499296b3edSMax Reitz         return ret;
29509296b3edSMax Reitz     }
29519296b3edSMax Reitz     return 0;
29529296b3edSMax Reitz }
29539296b3edSMax Reitz 
2954c293a809SMax Reitz typedef enum Qcow2AmendOperation {
2955c293a809SMax Reitz     /* This is the value Qcow2AmendHelperCBInfo::last_operation will be
2956c293a809SMax Reitz      * statically initialized to so that the helper CB can discern the first
2957c293a809SMax Reitz      * invocation from an operation change */
2958c293a809SMax Reitz     QCOW2_NO_OPERATION = 0,
2959c293a809SMax Reitz 
296061ce55fcSMax Reitz     QCOW2_CHANGING_REFCOUNT_ORDER,
2961c293a809SMax Reitz     QCOW2_DOWNGRADING,
2962c293a809SMax Reitz } Qcow2AmendOperation;
2963c293a809SMax Reitz 
2964c293a809SMax Reitz typedef struct Qcow2AmendHelperCBInfo {
2965c293a809SMax Reitz     /* The code coordinating the amend operations should only modify
2966c293a809SMax Reitz      * these four fields; the rest will be managed by the CB */
2967c293a809SMax Reitz     BlockDriverAmendStatusCB *original_status_cb;
2968c293a809SMax Reitz     void *original_cb_opaque;
2969c293a809SMax Reitz 
2970c293a809SMax Reitz     Qcow2AmendOperation current_operation;
2971c293a809SMax Reitz 
2972c293a809SMax Reitz     /* Total number of operations to perform (only set once) */
2973c293a809SMax Reitz     int total_operations;
2974c293a809SMax Reitz 
2975c293a809SMax Reitz     /* The following fields are managed by the CB */
2976c293a809SMax Reitz 
2977c293a809SMax Reitz     /* Number of operations completed */
2978c293a809SMax Reitz     int operations_completed;
2979c293a809SMax Reitz 
2980c293a809SMax Reitz     /* Cumulative offset of all completed operations */
2981c293a809SMax Reitz     int64_t offset_completed;
2982c293a809SMax Reitz 
2983c293a809SMax Reitz     Qcow2AmendOperation last_operation;
2984c293a809SMax Reitz     int64_t last_work_size;
2985c293a809SMax Reitz } Qcow2AmendHelperCBInfo;
2986c293a809SMax Reitz 
2987c293a809SMax Reitz static void qcow2_amend_helper_cb(BlockDriverState *bs,
2988c293a809SMax Reitz                                   int64_t operation_offset,
2989c293a809SMax Reitz                                   int64_t operation_work_size, void *opaque)
2990c293a809SMax Reitz {
2991c293a809SMax Reitz     Qcow2AmendHelperCBInfo *info = opaque;
2992c293a809SMax Reitz     int64_t current_work_size;
2993c293a809SMax Reitz     int64_t projected_work_size;
2994c293a809SMax Reitz 
2995c293a809SMax Reitz     if (info->current_operation != info->last_operation) {
2996c293a809SMax Reitz         if (info->last_operation != QCOW2_NO_OPERATION) {
2997c293a809SMax Reitz             info->offset_completed += info->last_work_size;
2998c293a809SMax Reitz             info->operations_completed++;
2999c293a809SMax Reitz         }
3000c293a809SMax Reitz 
3001c293a809SMax Reitz         info->last_operation = info->current_operation;
3002c293a809SMax Reitz     }
3003c293a809SMax Reitz 
3004c293a809SMax Reitz     assert(info->total_operations > 0);
3005c293a809SMax Reitz     assert(info->operations_completed < info->total_operations);
3006c293a809SMax Reitz 
3007c293a809SMax Reitz     info->last_work_size = operation_work_size;
3008c293a809SMax Reitz 
3009c293a809SMax Reitz     current_work_size = info->offset_completed + operation_work_size;
3010c293a809SMax Reitz 
3011c293a809SMax Reitz     /* current_work_size is the total work size for (operations_completed + 1)
3012c293a809SMax Reitz      * operations (which includes this one), so multiply it by the number of
3013c293a809SMax Reitz      * operations not covered and divide it by the number of operations
3014c293a809SMax Reitz      * covered to get a projection for the operations not covered */
3015c293a809SMax Reitz     projected_work_size = current_work_size * (info->total_operations -
3016c293a809SMax Reitz                                                info->operations_completed - 1)
3017c293a809SMax Reitz                                             / (info->operations_completed + 1);
3018c293a809SMax Reitz 
3019c293a809SMax Reitz     info->original_status_cb(bs, info->offset_completed + operation_offset,
3020c293a809SMax Reitz                              current_work_size + projected_work_size,
3021c293a809SMax Reitz                              info->original_cb_opaque);
3022c293a809SMax Reitz }
3023c293a809SMax Reitz 
302477485434SMax Reitz static int qcow2_amend_options(BlockDriverState *bs, QemuOpts *opts,
30258b13976dSMax Reitz                                BlockDriverAmendStatusCB *status_cb,
30268b13976dSMax Reitz                                void *cb_opaque)
30279296b3edSMax Reitz {
3028ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
30299296b3edSMax Reitz     int old_version = s->qcow_version, new_version = old_version;
30309296b3edSMax Reitz     uint64_t new_size = 0;
30319296b3edSMax Reitz     const char *backing_file = NULL, *backing_format = NULL;
30329296b3edSMax Reitz     bool lazy_refcounts = s->use_lazy_refcounts;
30331bd0e2d1SChunyan Liu     const char *compat = NULL;
30341bd0e2d1SChunyan Liu     uint64_t cluster_size = s->cluster_size;
30351bd0e2d1SChunyan Liu     bool encrypt;
303661ce55fcSMax Reitz     int refcount_bits = s->refcount_bits;
30379296b3edSMax Reitz     int ret;
30381bd0e2d1SChunyan Liu     QemuOptDesc *desc = opts->list->desc;
3039c293a809SMax Reitz     Qcow2AmendHelperCBInfo helper_cb_info;
30409296b3edSMax Reitz 
30411bd0e2d1SChunyan Liu     while (desc && desc->name) {
30421bd0e2d1SChunyan Liu         if (!qemu_opt_find(opts, desc->name)) {
30439296b3edSMax Reitz             /* only change explicitly defined options */
30441bd0e2d1SChunyan Liu             desc++;
30459296b3edSMax Reitz             continue;
30469296b3edSMax Reitz         }
30479296b3edSMax Reitz 
30488a17b83cSMax Reitz         if (!strcmp(desc->name, BLOCK_OPT_COMPAT_LEVEL)) {
30498a17b83cSMax Reitz             compat = qemu_opt_get(opts, BLOCK_OPT_COMPAT_LEVEL);
30501bd0e2d1SChunyan Liu             if (!compat) {
30519296b3edSMax Reitz                 /* preserve default */
30521bd0e2d1SChunyan Liu             } else if (!strcmp(compat, "0.10")) {
30539296b3edSMax Reitz                 new_version = 2;
30541bd0e2d1SChunyan Liu             } else if (!strcmp(compat, "1.1")) {
30559296b3edSMax Reitz                 new_version = 3;
30569296b3edSMax Reitz             } else {
305729d72431SMax Reitz                 error_report("Unknown compatibility level %s", compat);
30589296b3edSMax Reitz                 return -EINVAL;
30599296b3edSMax Reitz             }
30608a17b83cSMax Reitz         } else if (!strcmp(desc->name, BLOCK_OPT_PREALLOC)) {
306129d72431SMax Reitz             error_report("Cannot change preallocation mode");
30629296b3edSMax Reitz             return -ENOTSUP;
30638a17b83cSMax Reitz         } else if (!strcmp(desc->name, BLOCK_OPT_SIZE)) {
30648a17b83cSMax Reitz             new_size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, 0);
30658a17b83cSMax Reitz         } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FILE)) {
30668a17b83cSMax Reitz             backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
30678a17b83cSMax Reitz         } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FMT)) {
30688a17b83cSMax Reitz             backing_format = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
30698a17b83cSMax Reitz         } else if (!strcmp(desc->name, BLOCK_OPT_ENCRYPT)) {
30708a17b83cSMax Reitz             encrypt = qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT,
3071f6fa64f6SDaniel P. Berrange                                         !!s->cipher);
3072f6fa64f6SDaniel P. Berrange 
3073f6fa64f6SDaniel P. Berrange             if (encrypt != !!s->cipher) {
307429d72431SMax Reitz                 error_report("Changing the encryption flag is not supported");
30759296b3edSMax Reitz                 return -ENOTSUP;
30769296b3edSMax Reitz             }
30778a17b83cSMax Reitz         } else if (!strcmp(desc->name, BLOCK_OPT_CLUSTER_SIZE)) {
30788a17b83cSMax Reitz             cluster_size = qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE,
30791bd0e2d1SChunyan Liu                                              cluster_size);
30801bd0e2d1SChunyan Liu             if (cluster_size != s->cluster_size) {
308129d72431SMax Reitz                 error_report("Changing the cluster size is not supported");
30829296b3edSMax Reitz                 return -ENOTSUP;
30839296b3edSMax Reitz             }
30848a17b83cSMax Reitz         } else if (!strcmp(desc->name, BLOCK_OPT_LAZY_REFCOUNTS)) {
30858a17b83cSMax Reitz             lazy_refcounts = qemu_opt_get_bool(opts, BLOCK_OPT_LAZY_REFCOUNTS,
30861bd0e2d1SChunyan Liu                                                lazy_refcounts);
308706d05fa7SMax Reitz         } else if (!strcmp(desc->name, BLOCK_OPT_REFCOUNT_BITS)) {
308861ce55fcSMax Reitz             refcount_bits = qemu_opt_get_number(opts, BLOCK_OPT_REFCOUNT_BITS,
308961ce55fcSMax Reitz                                                 refcount_bits);
309061ce55fcSMax Reitz 
309161ce55fcSMax Reitz             if (refcount_bits <= 0 || refcount_bits > 64 ||
309261ce55fcSMax Reitz                 !is_power_of_2(refcount_bits))
309361ce55fcSMax Reitz             {
309461ce55fcSMax Reitz                 error_report("Refcount width must be a power of two and may "
309561ce55fcSMax Reitz                              "not exceed 64 bits");
309661ce55fcSMax Reitz                 return -EINVAL;
309761ce55fcSMax Reitz             }
30989296b3edSMax Reitz         } else {
3099164e0f89SMax Reitz             /* if this point is reached, this probably means a new option was
31009296b3edSMax Reitz              * added without having it covered here */
3101164e0f89SMax Reitz             abort();
31029296b3edSMax Reitz         }
31031bd0e2d1SChunyan Liu 
31041bd0e2d1SChunyan Liu         desc++;
31059296b3edSMax Reitz     }
31069296b3edSMax Reitz 
3107c293a809SMax Reitz     helper_cb_info = (Qcow2AmendHelperCBInfo){
3108c293a809SMax Reitz         .original_status_cb = status_cb,
3109c293a809SMax Reitz         .original_cb_opaque = cb_opaque,
3110c293a809SMax Reitz         .total_operations = (new_version < old_version)
311161ce55fcSMax Reitz                           + (s->refcount_bits != refcount_bits)
3112c293a809SMax Reitz     };
3113c293a809SMax Reitz 
31141038bbb8SMax Reitz     /* Upgrade first (some features may require compat=1.1) */
31159296b3edSMax Reitz     if (new_version > old_version) {
31169296b3edSMax Reitz         s->qcow_version = new_version;
31179296b3edSMax Reitz         ret = qcow2_update_header(bs);
31189296b3edSMax Reitz         if (ret < 0) {
31199296b3edSMax Reitz             s->qcow_version = old_version;
31209296b3edSMax Reitz             return ret;
31219296b3edSMax Reitz         }
31229296b3edSMax Reitz     }
31239296b3edSMax Reitz 
312461ce55fcSMax Reitz     if (s->refcount_bits != refcount_bits) {
312561ce55fcSMax Reitz         int refcount_order = ctz32(refcount_bits);
312661ce55fcSMax Reitz         Error *local_error = NULL;
312761ce55fcSMax Reitz 
312861ce55fcSMax Reitz         if (new_version < 3 && refcount_bits != 16) {
312961ce55fcSMax Reitz             error_report("Different refcount widths than 16 bits require "
313061ce55fcSMax Reitz                          "compatibility level 1.1 or above (use compat=1.1 or "
313161ce55fcSMax Reitz                          "greater)");
313261ce55fcSMax Reitz             return -EINVAL;
313361ce55fcSMax Reitz         }
313461ce55fcSMax Reitz 
313561ce55fcSMax Reitz         helper_cb_info.current_operation = QCOW2_CHANGING_REFCOUNT_ORDER;
313661ce55fcSMax Reitz         ret = qcow2_change_refcount_order(bs, refcount_order,
313761ce55fcSMax Reitz                                           &qcow2_amend_helper_cb,
313861ce55fcSMax Reitz                                           &helper_cb_info, &local_error);
313961ce55fcSMax Reitz         if (ret < 0) {
314061ce55fcSMax Reitz             error_report_err(local_error);
314161ce55fcSMax Reitz             return ret;
314261ce55fcSMax Reitz         }
314361ce55fcSMax Reitz     }
314461ce55fcSMax Reitz 
31459296b3edSMax Reitz     if (backing_file || backing_format) {
3146e4603fe1SKevin Wolf         ret = qcow2_change_backing_file(bs,
3147e4603fe1SKevin Wolf                     backing_file ?: s->image_backing_file,
3148e4603fe1SKevin Wolf                     backing_format ?: s->image_backing_format);
31499296b3edSMax Reitz         if (ret < 0) {
31509296b3edSMax Reitz             return ret;
31519296b3edSMax Reitz         }
31529296b3edSMax Reitz     }
31539296b3edSMax Reitz 
31549296b3edSMax Reitz     if (s->use_lazy_refcounts != lazy_refcounts) {
31559296b3edSMax Reitz         if (lazy_refcounts) {
31561038bbb8SMax Reitz             if (new_version < 3) {
315729d72431SMax Reitz                 error_report("Lazy refcounts only supported with compatibility "
315829d72431SMax Reitz                              "level 1.1 and above (use compat=1.1 or greater)");
31599296b3edSMax Reitz                 return -EINVAL;
31609296b3edSMax Reitz             }
31619296b3edSMax Reitz             s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
31629296b3edSMax Reitz             ret = qcow2_update_header(bs);
31639296b3edSMax Reitz             if (ret < 0) {
31649296b3edSMax Reitz                 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
31659296b3edSMax Reitz                 return ret;
31669296b3edSMax Reitz             }
31679296b3edSMax Reitz             s->use_lazy_refcounts = true;
31689296b3edSMax Reitz         } else {
31699296b3edSMax Reitz             /* make image clean first */
31709296b3edSMax Reitz             ret = qcow2_mark_clean(bs);
31719296b3edSMax Reitz             if (ret < 0) {
31729296b3edSMax Reitz                 return ret;
31739296b3edSMax Reitz             }
31749296b3edSMax Reitz             /* now disallow lazy refcounts */
31759296b3edSMax Reitz             s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
31769296b3edSMax Reitz             ret = qcow2_update_header(bs);
31779296b3edSMax Reitz             if (ret < 0) {
31789296b3edSMax Reitz                 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
31799296b3edSMax Reitz                 return ret;
31809296b3edSMax Reitz             }
31819296b3edSMax Reitz             s->use_lazy_refcounts = false;
31829296b3edSMax Reitz         }
31839296b3edSMax Reitz     }
31849296b3edSMax Reitz 
31859296b3edSMax Reitz     if (new_size) {
31869296b3edSMax Reitz         ret = bdrv_truncate(bs, new_size);
31879296b3edSMax Reitz         if (ret < 0) {
31889296b3edSMax Reitz             return ret;
31899296b3edSMax Reitz         }
31909296b3edSMax Reitz     }
31919296b3edSMax Reitz 
31921038bbb8SMax Reitz     /* Downgrade last (so unsupported features can be removed before) */
31931038bbb8SMax Reitz     if (new_version < old_version) {
3194c293a809SMax Reitz         helper_cb_info.current_operation = QCOW2_DOWNGRADING;
3195c293a809SMax Reitz         ret = qcow2_downgrade(bs, new_version, &qcow2_amend_helper_cb,
3196c293a809SMax Reitz                               &helper_cb_info);
31971038bbb8SMax Reitz         if (ret < 0) {
31981038bbb8SMax Reitz             return ret;
31991038bbb8SMax Reitz         }
32001038bbb8SMax Reitz     }
32011038bbb8SMax Reitz 
32029296b3edSMax Reitz     return 0;
32039296b3edSMax Reitz }
32049296b3edSMax Reitz 
320585186ebdSMax Reitz /*
320685186ebdSMax Reitz  * If offset or size are negative, respectively, they will not be included in
320785186ebdSMax Reitz  * the BLOCK_IMAGE_CORRUPTED event emitted.
320885186ebdSMax Reitz  * fatal will be ignored for read-only BDS; corruptions found there will always
320985186ebdSMax Reitz  * be considered non-fatal.
321085186ebdSMax Reitz  */
321185186ebdSMax Reitz void qcow2_signal_corruption(BlockDriverState *bs, bool fatal, int64_t offset,
321285186ebdSMax Reitz                              int64_t size, const char *message_format, ...)
321385186ebdSMax Reitz {
3214ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
3215dc881b44SAlberto Garcia     const char *node_name;
321685186ebdSMax Reitz     char *message;
321785186ebdSMax Reitz     va_list ap;
321885186ebdSMax Reitz 
321985186ebdSMax Reitz     fatal = fatal && !bs->read_only;
322085186ebdSMax Reitz 
322185186ebdSMax Reitz     if (s->signaled_corruption &&
322285186ebdSMax Reitz         (!fatal || (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT)))
322385186ebdSMax Reitz     {
322485186ebdSMax Reitz         return;
322585186ebdSMax Reitz     }
322685186ebdSMax Reitz 
322785186ebdSMax Reitz     va_start(ap, message_format);
322885186ebdSMax Reitz     message = g_strdup_vprintf(message_format, ap);
322985186ebdSMax Reitz     va_end(ap);
323085186ebdSMax Reitz 
323185186ebdSMax Reitz     if (fatal) {
323285186ebdSMax Reitz         fprintf(stderr, "qcow2: Marking image as corrupt: %s; further "
323385186ebdSMax Reitz                 "corruption events will be suppressed\n", message);
323485186ebdSMax Reitz     } else {
323585186ebdSMax Reitz         fprintf(stderr, "qcow2: Image is corrupt: %s; further non-fatal "
323685186ebdSMax Reitz                 "corruption events will be suppressed\n", message);
323785186ebdSMax Reitz     }
323885186ebdSMax Reitz 
3239dc881b44SAlberto Garcia     node_name = bdrv_get_node_name(bs);
3240dc881b44SAlberto Garcia     qapi_event_send_block_image_corrupted(bdrv_get_device_name(bs),
3241dc881b44SAlberto Garcia                                           *node_name != '\0', node_name,
3242dc881b44SAlberto Garcia                                           message, offset >= 0, offset,
3243dc881b44SAlberto Garcia                                           size >= 0, size,
324485186ebdSMax Reitz                                           fatal, &error_abort);
324585186ebdSMax Reitz     g_free(message);
324685186ebdSMax Reitz 
324785186ebdSMax Reitz     if (fatal) {
324885186ebdSMax Reitz         qcow2_mark_corrupt(bs);
324985186ebdSMax Reitz         bs->drv = NULL; /* make BDS unusable */
325085186ebdSMax Reitz     }
325185186ebdSMax Reitz 
325285186ebdSMax Reitz     s->signaled_corruption = true;
325385186ebdSMax Reitz }
325485186ebdSMax Reitz 
32551bd0e2d1SChunyan Liu static QemuOptsList qcow2_create_opts = {
32561bd0e2d1SChunyan Liu     .name = "qcow2-create-opts",
32571bd0e2d1SChunyan Liu     .head = QTAILQ_HEAD_INITIALIZER(qcow2_create_opts.head),
32581bd0e2d1SChunyan Liu     .desc = {
325920d97356SBlue Swirl         {
326020d97356SBlue Swirl             .name = BLOCK_OPT_SIZE,
32611bd0e2d1SChunyan Liu             .type = QEMU_OPT_SIZE,
326220d97356SBlue Swirl             .help = "Virtual disk size"
326320d97356SBlue Swirl         },
326420d97356SBlue Swirl         {
32656744cbabSKevin Wolf             .name = BLOCK_OPT_COMPAT_LEVEL,
32661bd0e2d1SChunyan Liu             .type = QEMU_OPT_STRING,
32676744cbabSKevin Wolf             .help = "Compatibility level (0.10 or 1.1)"
32686744cbabSKevin Wolf         },
32696744cbabSKevin Wolf         {
327020d97356SBlue Swirl             .name = BLOCK_OPT_BACKING_FILE,
32711bd0e2d1SChunyan Liu             .type = QEMU_OPT_STRING,
327220d97356SBlue Swirl             .help = "File name of a base image"
327320d97356SBlue Swirl         },
327420d97356SBlue Swirl         {
327520d97356SBlue Swirl             .name = BLOCK_OPT_BACKING_FMT,
32761bd0e2d1SChunyan Liu             .type = QEMU_OPT_STRING,
327720d97356SBlue Swirl             .help = "Image format of the base image"
327820d97356SBlue Swirl         },
327920d97356SBlue Swirl         {
328020d97356SBlue Swirl             .name = BLOCK_OPT_ENCRYPT,
32811bd0e2d1SChunyan Liu             .type = QEMU_OPT_BOOL,
32821bd0e2d1SChunyan Liu             .help = "Encrypt the image",
32831bd0e2d1SChunyan Liu             .def_value_str = "off"
328420d97356SBlue Swirl         },
328520d97356SBlue Swirl         {
328620d97356SBlue Swirl             .name = BLOCK_OPT_CLUSTER_SIZE,
32871bd0e2d1SChunyan Liu             .type = QEMU_OPT_SIZE,
328899cce9faSKevin Wolf             .help = "qcow2 cluster size",
32891bd0e2d1SChunyan Liu             .def_value_str = stringify(DEFAULT_CLUSTER_SIZE)
329020d97356SBlue Swirl         },
329120d97356SBlue Swirl         {
329220d97356SBlue Swirl             .name = BLOCK_OPT_PREALLOC,
32931bd0e2d1SChunyan Liu             .type = QEMU_OPT_STRING,
32940e4271b7SHu Tao             .help = "Preallocation mode (allowed values: off, metadata, "
32950e4271b7SHu Tao                     "falloc, full)"
329620d97356SBlue Swirl         },
3297bfe8043eSStefan Hajnoczi         {
3298bfe8043eSStefan Hajnoczi             .name = BLOCK_OPT_LAZY_REFCOUNTS,
32991bd0e2d1SChunyan Liu             .type = QEMU_OPT_BOOL,
3300bfe8043eSStefan Hajnoczi             .help = "Postpone refcount updates",
33011bd0e2d1SChunyan Liu             .def_value_str = "off"
3302bfe8043eSStefan Hajnoczi         },
330306d05fa7SMax Reitz         {
330406d05fa7SMax Reitz             .name = BLOCK_OPT_REFCOUNT_BITS,
330506d05fa7SMax Reitz             .type = QEMU_OPT_NUMBER,
330606d05fa7SMax Reitz             .help = "Width of a reference count entry in bits",
330706d05fa7SMax Reitz             .def_value_str = "16"
330806d05fa7SMax Reitz         },
33091bd0e2d1SChunyan Liu         { /* end of list */ }
33101bd0e2d1SChunyan Liu     }
331120d97356SBlue Swirl };
331220d97356SBlue Swirl 
33135f535a94SMax Reitz BlockDriver bdrv_qcow2 = {
331420d97356SBlue Swirl     .format_name        = "qcow2",
3315ff99129aSKevin Wolf     .instance_size      = sizeof(BDRVQcow2State),
33167c80ab3fSJes Sorensen     .bdrv_probe         = qcow2_probe,
33177c80ab3fSJes Sorensen     .bdrv_open          = qcow2_open,
33187c80ab3fSJes Sorensen     .bdrv_close         = qcow2_close,
331921d82ac9SJeff Cody     .bdrv_reopen_prepare  = qcow2_reopen_prepare,
33205b0959a7SKevin Wolf     .bdrv_reopen_commit   = qcow2_reopen_commit,
33215b0959a7SKevin Wolf     .bdrv_reopen_abort    = qcow2_reopen_abort,
33225365f44dSKevin Wolf     .bdrv_join_options    = qcow2_join_options,
3323c282e1fdSChunyan Liu     .bdrv_create        = qcow2_create,
33243ac21627SPeter Lieven     .bdrv_has_zero_init = bdrv_has_zero_init_1,
3325b6b8a333SPaolo Bonzini     .bdrv_co_get_block_status = qcow2_co_get_block_status,
33267c80ab3fSJes Sorensen     .bdrv_set_key       = qcow2_set_key,
332720d97356SBlue Swirl 
332868d100e9SKevin Wolf     .bdrv_co_readv          = qcow2_co_readv,
332968d100e9SKevin Wolf     .bdrv_co_writev         = qcow2_co_writev,
3330eb489bb1SKevin Wolf     .bdrv_co_flush_to_os    = qcow2_co_flush_to_os,
3331419b19d9SStefan Hajnoczi 
3332621f0589SKevin Wolf     .bdrv_co_write_zeroes   = qcow2_co_write_zeroes,
33336db39ae2SPaolo Bonzini     .bdrv_co_discard        = qcow2_co_discard,
3334419b19d9SStefan Hajnoczi     .bdrv_truncate          = qcow2_truncate,
33357c80ab3fSJes Sorensen     .bdrv_write_compressed  = qcow2_write_compressed,
3336491d27e2SMax Reitz     .bdrv_make_empty        = qcow2_make_empty,
333720d97356SBlue Swirl 
333820d97356SBlue Swirl     .bdrv_snapshot_create   = qcow2_snapshot_create,
333920d97356SBlue Swirl     .bdrv_snapshot_goto     = qcow2_snapshot_goto,
334020d97356SBlue Swirl     .bdrv_snapshot_delete   = qcow2_snapshot_delete,
334120d97356SBlue Swirl     .bdrv_snapshot_list     = qcow2_snapshot_list,
334251ef6727Sedison     .bdrv_snapshot_load_tmp = qcow2_snapshot_load_tmp,
33437c80ab3fSJes Sorensen     .bdrv_get_info          = qcow2_get_info,
334437764dfbSMax Reitz     .bdrv_get_specific_info = qcow2_get_specific_info,
334520d97356SBlue Swirl 
33467c80ab3fSJes Sorensen     .bdrv_save_vmstate    = qcow2_save_vmstate,
33477c80ab3fSJes Sorensen     .bdrv_load_vmstate    = qcow2_load_vmstate,
334820d97356SBlue Swirl 
33498ee79e70SKevin Wolf     .supports_backing           = true,
335020d97356SBlue Swirl     .bdrv_change_backing_file   = qcow2_change_backing_file,
335120d97356SBlue Swirl 
3352d34682cdSKevin Wolf     .bdrv_refresh_limits        = qcow2_refresh_limits,
335306d9260fSAnthony Liguori     .bdrv_invalidate_cache      = qcow2_invalidate_cache,
3354ec6d8912SKevin Wolf     .bdrv_inactivate            = qcow2_inactivate,
335506d9260fSAnthony Liguori 
33561bd0e2d1SChunyan Liu     .create_opts         = &qcow2_create_opts,
33577c80ab3fSJes Sorensen     .bdrv_check          = qcow2_check,
3358c282e1fdSChunyan Liu     .bdrv_amend_options  = qcow2_amend_options,
3359279621c0SAlberto Garcia 
3360279621c0SAlberto Garcia     .bdrv_detach_aio_context  = qcow2_detach_aio_context,
3361279621c0SAlberto Garcia     .bdrv_attach_aio_context  = qcow2_attach_aio_context,
336220d97356SBlue Swirl };
336320d97356SBlue Swirl 
33645efa9d5aSAnthony Liguori static void bdrv_qcow2_init(void)
33655efa9d5aSAnthony Liguori {
33665efa9d5aSAnthony Liguori     bdrv_register(&bdrv_qcow2);
33675efa9d5aSAnthony Liguori }
33685efa9d5aSAnthony Liguori 
33695efa9d5aSAnthony Liguori block_init(bdrv_qcow2_init);
3370