xref: /qemu/block/qcow2.c (revision 2d51c32c4b511db8bb9e58208f1e2c25e4c06c85)
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  */
24faf07963Spbrook #include "qemu-common.h"
25737e150eSPaolo Bonzini #include "block/block_int.h"
261de7afc9SPaolo Bonzini #include "qemu/module.h"
27585f8587Sbellard #include <zlib.h>
28753d9b82SAurelien Jarno #include "qemu/aes.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"
333cce16f4SKevin Wolf #include "trace.h"
34585f8587Sbellard 
35585f8587Sbellard /*
36585f8587Sbellard   Differences with QCOW:
37585f8587Sbellard 
38585f8587Sbellard   - Support for multiple incremental snapshots.
39585f8587Sbellard   - Memory management by reference counts.
40585f8587Sbellard   - Clusters which have a reference count of one have the bit
41585f8587Sbellard     QCOW_OFLAG_COPIED to optimize write performance.
42585f8587Sbellard   - Size of compressed clusters is stored in sectors to reduce bit usage
43585f8587Sbellard     in the cluster offsets.
44585f8587Sbellard   - Support for storing additional data (such as the VM state) in the
45585f8587Sbellard     snapshots.
46585f8587Sbellard   - If a backing store is used, the cluster size is not constrained
47585f8587Sbellard     (could be backported to QCOW).
48585f8587Sbellard   - L2 tables have always a size of one cluster.
49585f8587Sbellard */
50585f8587Sbellard 
519b80ddf3Saliguori 
529b80ddf3Saliguori typedef struct {
539b80ddf3Saliguori     uint32_t magic;
549b80ddf3Saliguori     uint32_t len;
55c4217f64SJeff Cody } QEMU_PACKED QCowExtension;
5621d82ac9SJeff Cody 
577c80ab3fSJes Sorensen #define  QCOW2_EXT_MAGIC_END 0
587c80ab3fSJes Sorensen #define  QCOW2_EXT_MAGIC_BACKING_FORMAT 0xE2792ACA
59cfcc4c62SKevin Wolf #define  QCOW2_EXT_MAGIC_FEATURE_TABLE 0x6803f857
609b80ddf3Saliguori 
617c80ab3fSJes Sorensen static int qcow2_probe(const uint8_t *buf, int buf_size, const char *filename)
62585f8587Sbellard {
63585f8587Sbellard     const QCowHeader *cow_header = (const void *)buf;
64585f8587Sbellard 
65585f8587Sbellard     if (buf_size >= sizeof(QCowHeader) &&
66585f8587Sbellard         be32_to_cpu(cow_header->magic) == QCOW_MAGIC &&
676744cbabSKevin Wolf         be32_to_cpu(cow_header->version) >= 2)
68585f8587Sbellard         return 100;
69585f8587Sbellard     else
70585f8587Sbellard         return 0;
71585f8587Sbellard }
72585f8587Sbellard 
739b80ddf3Saliguori 
749b80ddf3Saliguori /*
759b80ddf3Saliguori  * read qcow2 extension and fill bs
769b80ddf3Saliguori  * start reading from start_offset
779b80ddf3Saliguori  * finish reading upon magic of value 0 or when end_offset reached
789b80ddf3Saliguori  * unknown magic is skipped (future extension this version knows nothing about)
799b80ddf3Saliguori  * return 0 upon success, non-0 otherwise
809b80ddf3Saliguori  */
817c80ab3fSJes Sorensen static int qcow2_read_extensions(BlockDriverState *bs, uint64_t start_offset,
823ef6c40aSMax Reitz                                  uint64_t end_offset, void **p_feature_table,
833ef6c40aSMax Reitz                                  Error **errp)
849b80ddf3Saliguori {
8575bab85cSKevin Wolf     BDRVQcowState *s = bs->opaque;
869b80ddf3Saliguori     QCowExtension ext;
879b80ddf3Saliguori     uint64_t offset;
8875bab85cSKevin Wolf     int ret;
899b80ddf3Saliguori 
909b80ddf3Saliguori #ifdef DEBUG_EXT
917c80ab3fSJes Sorensen     printf("qcow2_read_extensions: start=%ld end=%ld\n", start_offset, end_offset);
929b80ddf3Saliguori #endif
939b80ddf3Saliguori     offset = start_offset;
949b80ddf3Saliguori     while (offset < end_offset) {
959b80ddf3Saliguori 
969b80ddf3Saliguori #ifdef DEBUG_EXT
979b80ddf3Saliguori         /* Sanity check */
989b80ddf3Saliguori         if (offset > s->cluster_size)
997c80ab3fSJes Sorensen             printf("qcow2_read_extension: suspicious offset %lu\n", offset);
1009b80ddf3Saliguori 
1019b2260cbSDong Xu Wang         printf("attempting to read extended header in offset %lu\n", offset);
1029b80ddf3Saliguori #endif
1039b80ddf3Saliguori 
1043ef6c40aSMax Reitz         ret = bdrv_pread(bs->file, offset, &ext, sizeof(ext));
1053ef6c40aSMax Reitz         if (ret < 0) {
1063ef6c40aSMax Reitz             error_setg_errno(errp, -ret, "qcow2_read_extension: ERROR: "
1073ef6c40aSMax Reitz                              "pread fail from offset %" PRIu64, offset);
1089b80ddf3Saliguori             return 1;
1099b80ddf3Saliguori         }
1109b80ddf3Saliguori         be32_to_cpus(&ext.magic);
1119b80ddf3Saliguori         be32_to_cpus(&ext.len);
1129b80ddf3Saliguori         offset += sizeof(ext);
1139b80ddf3Saliguori #ifdef DEBUG_EXT
1149b80ddf3Saliguori         printf("ext.magic = 0x%x\n", ext.magic);
1159b80ddf3Saliguori #endif
11664ca6aeeSKevin Wolf         if (ext.len > end_offset - offset) {
1173ef6c40aSMax Reitz             error_setg(errp, "Header extension too large");
11864ca6aeeSKevin Wolf             return -EINVAL;
11964ca6aeeSKevin Wolf         }
12064ca6aeeSKevin Wolf 
1219b80ddf3Saliguori         switch (ext.magic) {
1227c80ab3fSJes Sorensen         case QCOW2_EXT_MAGIC_END:
1239b80ddf3Saliguori             return 0;
124f965509cSaliguori 
1257c80ab3fSJes Sorensen         case QCOW2_EXT_MAGIC_BACKING_FORMAT:
126f965509cSaliguori             if (ext.len >= sizeof(bs->backing_format)) {
1273ef6c40aSMax Reitz                 error_setg(errp, "ERROR: ext_backing_format: len=%u too large"
1283ef6c40aSMax Reitz                            " (>=%zu)", ext.len, sizeof(bs->backing_format));
129f965509cSaliguori                 return 2;
130f965509cSaliguori             }
1313ef6c40aSMax Reitz             ret = bdrv_pread(bs->file, offset, bs->backing_format, ext.len);
1323ef6c40aSMax Reitz             if (ret < 0) {
1333ef6c40aSMax Reitz                 error_setg_errno(errp, -ret, "ERROR: ext_backing_format: "
1343ef6c40aSMax Reitz                                  "Could not read format name");
135f965509cSaliguori                 return 3;
1363ef6c40aSMax Reitz             }
137f965509cSaliguori             bs->backing_format[ext.len] = '\0';
138f965509cSaliguori #ifdef DEBUG_EXT
139f965509cSaliguori             printf("Qcow2: Got format extension %s\n", bs->backing_format);
140f965509cSaliguori #endif
141f965509cSaliguori             break;
142f965509cSaliguori 
143cfcc4c62SKevin Wolf         case QCOW2_EXT_MAGIC_FEATURE_TABLE:
144cfcc4c62SKevin Wolf             if (p_feature_table != NULL) {
145cfcc4c62SKevin Wolf                 void* feature_table = g_malloc0(ext.len + 2 * sizeof(Qcow2Feature));
146cfcc4c62SKevin Wolf                 ret = bdrv_pread(bs->file, offset , feature_table, ext.len);
147cfcc4c62SKevin Wolf                 if (ret < 0) {
1483ef6c40aSMax Reitz                     error_setg_errno(errp, -ret, "ERROR: ext_feature_table: "
1493ef6c40aSMax Reitz                                      "Could not read table");
150cfcc4c62SKevin Wolf                     return ret;
151cfcc4c62SKevin Wolf                 }
152cfcc4c62SKevin Wolf 
153cfcc4c62SKevin Wolf                 *p_feature_table = feature_table;
154cfcc4c62SKevin Wolf             }
155cfcc4c62SKevin Wolf             break;
156cfcc4c62SKevin Wolf 
1579b80ddf3Saliguori         default:
15875bab85cSKevin Wolf             /* unknown magic - save it in case we need to rewrite the header */
15975bab85cSKevin Wolf             {
16075bab85cSKevin Wolf                 Qcow2UnknownHeaderExtension *uext;
16175bab85cSKevin Wolf 
16275bab85cSKevin Wolf                 uext = g_malloc0(sizeof(*uext)  + ext.len);
16375bab85cSKevin Wolf                 uext->magic = ext.magic;
16475bab85cSKevin Wolf                 uext->len = ext.len;
16575bab85cSKevin Wolf                 QLIST_INSERT_HEAD(&s->unknown_header_ext, uext, next);
16675bab85cSKevin Wolf 
16775bab85cSKevin Wolf                 ret = bdrv_pread(bs->file, offset , uext->data, uext->len);
16875bab85cSKevin Wolf                 if (ret < 0) {
1693ef6c40aSMax Reitz                     error_setg_errno(errp, -ret, "ERROR: unknown extension: "
1703ef6c40aSMax Reitz                                      "Could not read data");
17175bab85cSKevin Wolf                     return ret;
17275bab85cSKevin Wolf                 }
17375bab85cSKevin Wolf             }
1749b80ddf3Saliguori             break;
1759b80ddf3Saliguori         }
176fd29b4bbSKevin Wolf 
177fd29b4bbSKevin Wolf         offset += ((ext.len + 7) & ~7);
1789b80ddf3Saliguori     }
1799b80ddf3Saliguori 
1809b80ddf3Saliguori     return 0;
1819b80ddf3Saliguori }
1829b80ddf3Saliguori 
18375bab85cSKevin Wolf static void cleanup_unknown_header_ext(BlockDriverState *bs)
18475bab85cSKevin Wolf {
18575bab85cSKevin Wolf     BDRVQcowState *s = bs->opaque;
18675bab85cSKevin Wolf     Qcow2UnknownHeaderExtension *uext, *next;
18775bab85cSKevin Wolf 
18875bab85cSKevin Wolf     QLIST_FOREACH_SAFE(uext, &s->unknown_header_ext, next, next) {
18975bab85cSKevin Wolf         QLIST_REMOVE(uext, next);
19075bab85cSKevin Wolf         g_free(uext);
19175bab85cSKevin Wolf     }
19275bab85cSKevin Wolf }
1939b80ddf3Saliguori 
1943ef6c40aSMax Reitz static void GCC_FMT_ATTR(3, 4) report_unsupported(BlockDriverState *bs,
1953ef6c40aSMax Reitz     Error **errp, const char *fmt, ...)
1966744cbabSKevin Wolf {
1976744cbabSKevin Wolf     char msg[64];
1986744cbabSKevin Wolf     va_list ap;
1996744cbabSKevin Wolf 
2006744cbabSKevin Wolf     va_start(ap, fmt);
2016744cbabSKevin Wolf     vsnprintf(msg, sizeof(msg), fmt, ap);
2026744cbabSKevin Wolf     va_end(ap);
2036744cbabSKevin Wolf 
2043ef6c40aSMax Reitz     error_set(errp, QERR_UNKNOWN_BLOCK_FORMAT_FEATURE, bs->device_name, "qcow2",
2053ef6c40aSMax Reitz               msg);
2066744cbabSKevin Wolf }
2076744cbabSKevin Wolf 
208cfcc4c62SKevin Wolf static void report_unsupported_feature(BlockDriverState *bs,
2093ef6c40aSMax Reitz     Error **errp, Qcow2Feature *table, uint64_t mask)
210cfcc4c62SKevin Wolf {
211cfcc4c62SKevin Wolf     while (table && table->name[0] != '\0') {
212cfcc4c62SKevin Wolf         if (table->type == QCOW2_FEAT_TYPE_INCOMPATIBLE) {
213cfcc4c62SKevin Wolf             if (mask & (1 << table->bit)) {
2143ef6c40aSMax Reitz                 report_unsupported(bs, errp, "%.46s", table->name);
215cfcc4c62SKevin Wolf                 mask &= ~(1 << table->bit);
216cfcc4c62SKevin Wolf             }
217cfcc4c62SKevin Wolf         }
218cfcc4c62SKevin Wolf         table++;
219cfcc4c62SKevin Wolf     }
220cfcc4c62SKevin Wolf 
221cfcc4c62SKevin Wolf     if (mask) {
2223ef6c40aSMax Reitz         report_unsupported(bs, errp, "Unknown incompatible feature: %" PRIx64,
2233ef6c40aSMax Reitz                            mask);
224cfcc4c62SKevin Wolf     }
225cfcc4c62SKevin Wolf }
226cfcc4c62SKevin Wolf 
227c61d0004SStefan Hajnoczi /*
228bfe8043eSStefan Hajnoczi  * Sets the dirty bit and flushes afterwards if necessary.
229bfe8043eSStefan Hajnoczi  *
230bfe8043eSStefan Hajnoczi  * The incompatible_features bit is only set if the image file header was
231bfe8043eSStefan Hajnoczi  * updated successfully.  Therefore it is not required to check the return
232bfe8043eSStefan Hajnoczi  * value of this function.
233bfe8043eSStefan Hajnoczi  */
234280d3735SKevin Wolf int qcow2_mark_dirty(BlockDriverState *bs)
235bfe8043eSStefan Hajnoczi {
236bfe8043eSStefan Hajnoczi     BDRVQcowState *s = bs->opaque;
237bfe8043eSStefan Hajnoczi     uint64_t val;
238bfe8043eSStefan Hajnoczi     int ret;
239bfe8043eSStefan Hajnoczi 
240bfe8043eSStefan Hajnoczi     assert(s->qcow_version >= 3);
241bfe8043eSStefan Hajnoczi 
242bfe8043eSStefan Hajnoczi     if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
243bfe8043eSStefan Hajnoczi         return 0; /* already dirty */
244bfe8043eSStefan Hajnoczi     }
245bfe8043eSStefan Hajnoczi 
246bfe8043eSStefan Hajnoczi     val = cpu_to_be64(s->incompatible_features | QCOW2_INCOMPAT_DIRTY);
247bfe8043eSStefan Hajnoczi     ret = bdrv_pwrite(bs->file, offsetof(QCowHeader, incompatible_features),
248bfe8043eSStefan Hajnoczi                       &val, sizeof(val));
249bfe8043eSStefan Hajnoczi     if (ret < 0) {
250bfe8043eSStefan Hajnoczi         return ret;
251bfe8043eSStefan Hajnoczi     }
252bfe8043eSStefan Hajnoczi     ret = bdrv_flush(bs->file);
253bfe8043eSStefan Hajnoczi     if (ret < 0) {
254bfe8043eSStefan Hajnoczi         return ret;
255bfe8043eSStefan Hajnoczi     }
256bfe8043eSStefan Hajnoczi 
257bfe8043eSStefan Hajnoczi     /* Only treat image as dirty if the header was updated successfully */
258bfe8043eSStefan Hajnoczi     s->incompatible_features |= QCOW2_INCOMPAT_DIRTY;
259bfe8043eSStefan Hajnoczi     return 0;
260bfe8043eSStefan Hajnoczi }
261bfe8043eSStefan Hajnoczi 
262bfe8043eSStefan Hajnoczi /*
263c61d0004SStefan Hajnoczi  * Clears the dirty bit and flushes before if necessary.  Only call this
264c61d0004SStefan Hajnoczi  * function when there are no pending requests, it does not guard against
265c61d0004SStefan Hajnoczi  * concurrent requests dirtying the image.
266c61d0004SStefan Hajnoczi  */
267c61d0004SStefan Hajnoczi static int qcow2_mark_clean(BlockDriverState *bs)
268c61d0004SStefan Hajnoczi {
269c61d0004SStefan Hajnoczi     BDRVQcowState *s = bs->opaque;
270c61d0004SStefan Hajnoczi 
271c61d0004SStefan Hajnoczi     if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
272c61d0004SStefan Hajnoczi         int ret = bdrv_flush(bs);
273c61d0004SStefan Hajnoczi         if (ret < 0) {
274c61d0004SStefan Hajnoczi             return ret;
275c61d0004SStefan Hajnoczi         }
276c61d0004SStefan Hajnoczi 
277c61d0004SStefan Hajnoczi         s->incompatible_features &= ~QCOW2_INCOMPAT_DIRTY;
278c61d0004SStefan Hajnoczi         return qcow2_update_header(bs);
279c61d0004SStefan Hajnoczi     }
280c61d0004SStefan Hajnoczi     return 0;
281c61d0004SStefan Hajnoczi }
282c61d0004SStefan Hajnoczi 
28369c98726SMax Reitz /*
28469c98726SMax Reitz  * Marks the image as corrupt.
28569c98726SMax Reitz  */
28669c98726SMax Reitz int qcow2_mark_corrupt(BlockDriverState *bs)
28769c98726SMax Reitz {
28869c98726SMax Reitz     BDRVQcowState *s = bs->opaque;
28969c98726SMax Reitz 
29069c98726SMax Reitz     s->incompatible_features |= QCOW2_INCOMPAT_CORRUPT;
29169c98726SMax Reitz     return qcow2_update_header(bs);
29269c98726SMax Reitz }
29369c98726SMax Reitz 
29469c98726SMax Reitz /*
29569c98726SMax Reitz  * Marks the image as consistent, i.e., unsets the corrupt bit, and flushes
29669c98726SMax Reitz  * before if necessary.
29769c98726SMax Reitz  */
29869c98726SMax Reitz int qcow2_mark_consistent(BlockDriverState *bs)
29969c98726SMax Reitz {
30069c98726SMax Reitz     BDRVQcowState *s = bs->opaque;
30169c98726SMax Reitz 
30269c98726SMax Reitz     if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
30369c98726SMax Reitz         int ret = bdrv_flush(bs);
30469c98726SMax Reitz         if (ret < 0) {
30569c98726SMax Reitz             return ret;
30669c98726SMax Reitz         }
30769c98726SMax Reitz 
30869c98726SMax Reitz         s->incompatible_features &= ~QCOW2_INCOMPAT_CORRUPT;
30969c98726SMax Reitz         return qcow2_update_header(bs);
31069c98726SMax Reitz     }
31169c98726SMax Reitz     return 0;
31269c98726SMax Reitz }
31369c98726SMax Reitz 
314acbe5982SStefan Hajnoczi static int qcow2_check(BlockDriverState *bs, BdrvCheckResult *result,
315acbe5982SStefan Hajnoczi                        BdrvCheckMode fix)
316acbe5982SStefan Hajnoczi {
317acbe5982SStefan Hajnoczi     int ret = qcow2_check_refcounts(bs, result, fix);
318acbe5982SStefan Hajnoczi     if (ret < 0) {
319acbe5982SStefan Hajnoczi         return ret;
320acbe5982SStefan Hajnoczi     }
321acbe5982SStefan Hajnoczi 
322acbe5982SStefan Hajnoczi     if (fix && result->check_errors == 0 && result->corruptions == 0) {
32324530f3eSMax Reitz         ret = qcow2_mark_clean(bs);
32424530f3eSMax Reitz         if (ret < 0) {
32524530f3eSMax Reitz             return ret;
32624530f3eSMax Reitz         }
32724530f3eSMax Reitz         return qcow2_mark_consistent(bs);
328acbe5982SStefan Hajnoczi     }
329acbe5982SStefan Hajnoczi     return ret;
330acbe5982SStefan Hajnoczi }
331acbe5982SStefan Hajnoczi 
3328c7de283SKevin Wolf static int validate_table_offset(BlockDriverState *bs, uint64_t offset,
3338c7de283SKevin Wolf                                  uint64_t entries, size_t entry_len)
3348c7de283SKevin Wolf {
3358c7de283SKevin Wolf     BDRVQcowState *s = bs->opaque;
3368c7de283SKevin Wolf     uint64_t size;
3378c7de283SKevin Wolf 
3388c7de283SKevin Wolf     /* Use signed INT64_MAX as the maximum even for uint64_t header fields,
3398c7de283SKevin Wolf      * because values will be passed to qemu functions taking int64_t. */
3408c7de283SKevin Wolf     if (entries > INT64_MAX / entry_len) {
3418c7de283SKevin Wolf         return -EINVAL;
3428c7de283SKevin Wolf     }
3438c7de283SKevin Wolf 
3448c7de283SKevin Wolf     size = entries * entry_len;
3458c7de283SKevin Wolf 
3468c7de283SKevin Wolf     if (INT64_MAX - size < offset) {
3478c7de283SKevin Wolf         return -EINVAL;
3488c7de283SKevin Wolf     }
3498c7de283SKevin Wolf 
3508c7de283SKevin Wolf     /* Tables must be cluster aligned */
3518c7de283SKevin Wolf     if (offset & (s->cluster_size - 1)) {
3528c7de283SKevin Wolf         return -EINVAL;
3538c7de283SKevin Wolf     }
3548c7de283SKevin Wolf 
3558c7de283SKevin Wolf     return 0;
3568c7de283SKevin Wolf }
3578c7de283SKevin Wolf 
35874c4510aSKevin Wolf static QemuOptsList qcow2_runtime_opts = {
35974c4510aSKevin Wolf     .name = "qcow2",
36074c4510aSKevin Wolf     .head = QTAILQ_HEAD_INITIALIZER(qcow2_runtime_opts.head),
36174c4510aSKevin Wolf     .desc = {
36274c4510aSKevin Wolf         {
36364aa99d3SKevin Wolf             .name = QCOW2_OPT_LAZY_REFCOUNTS,
36474c4510aSKevin Wolf             .type = QEMU_OPT_BOOL,
36574c4510aSKevin Wolf             .help = "Postpone refcount updates",
36674c4510aSKevin Wolf         },
36767af674eSKevin Wolf         {
36867af674eSKevin Wolf             .name = QCOW2_OPT_DISCARD_REQUEST,
36967af674eSKevin Wolf             .type = QEMU_OPT_BOOL,
37067af674eSKevin Wolf             .help = "Pass guest discard requests to the layer below",
37167af674eSKevin Wolf         },
37267af674eSKevin Wolf         {
37367af674eSKevin Wolf             .name = QCOW2_OPT_DISCARD_SNAPSHOT,
37467af674eSKevin Wolf             .type = QEMU_OPT_BOOL,
37567af674eSKevin Wolf             .help = "Generate discard requests when snapshot related space "
37667af674eSKevin Wolf                     "is freed",
37767af674eSKevin Wolf         },
37867af674eSKevin Wolf         {
37967af674eSKevin Wolf             .name = QCOW2_OPT_DISCARD_OTHER,
38067af674eSKevin Wolf             .type = QEMU_OPT_BOOL,
38167af674eSKevin Wolf             .help = "Generate discard requests when other clusters are freed",
38267af674eSKevin Wolf         },
38305de7e86SMax Reitz         {
38405de7e86SMax Reitz             .name = QCOW2_OPT_OVERLAP,
38505de7e86SMax Reitz             .type = QEMU_OPT_STRING,
38605de7e86SMax Reitz             .help = "Selects which overlap checks to perform from a range of "
38705de7e86SMax Reitz                     "templates (none, constant, cached, all)",
38805de7e86SMax Reitz         },
38905de7e86SMax Reitz         {
39005de7e86SMax Reitz             .name = QCOW2_OPT_OVERLAP_MAIN_HEADER,
39105de7e86SMax Reitz             .type = QEMU_OPT_BOOL,
39205de7e86SMax Reitz             .help = "Check for unintended writes into the main qcow2 header",
39305de7e86SMax Reitz         },
39405de7e86SMax Reitz         {
39505de7e86SMax Reitz             .name = QCOW2_OPT_OVERLAP_ACTIVE_L1,
39605de7e86SMax Reitz             .type = QEMU_OPT_BOOL,
39705de7e86SMax Reitz             .help = "Check for unintended writes into the active L1 table",
39805de7e86SMax Reitz         },
39905de7e86SMax Reitz         {
40005de7e86SMax Reitz             .name = QCOW2_OPT_OVERLAP_ACTIVE_L2,
40105de7e86SMax Reitz             .type = QEMU_OPT_BOOL,
40205de7e86SMax Reitz             .help = "Check for unintended writes into an active L2 table",
40305de7e86SMax Reitz         },
40405de7e86SMax Reitz         {
40505de7e86SMax Reitz             .name = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
40605de7e86SMax Reitz             .type = QEMU_OPT_BOOL,
40705de7e86SMax Reitz             .help = "Check for unintended writes into the refcount table",
40805de7e86SMax Reitz         },
40905de7e86SMax Reitz         {
41005de7e86SMax Reitz             .name = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
41105de7e86SMax Reitz             .type = QEMU_OPT_BOOL,
41205de7e86SMax Reitz             .help = "Check for unintended writes into a refcount block",
41305de7e86SMax Reitz         },
41405de7e86SMax Reitz         {
41505de7e86SMax Reitz             .name = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
41605de7e86SMax Reitz             .type = QEMU_OPT_BOOL,
41705de7e86SMax Reitz             .help = "Check for unintended writes into the snapshot table",
41805de7e86SMax Reitz         },
41905de7e86SMax Reitz         {
42005de7e86SMax Reitz             .name = QCOW2_OPT_OVERLAP_INACTIVE_L1,
42105de7e86SMax Reitz             .type = QEMU_OPT_BOOL,
42205de7e86SMax Reitz             .help = "Check for unintended writes into an inactive L1 table",
42305de7e86SMax Reitz         },
42405de7e86SMax Reitz         {
42505de7e86SMax Reitz             .name = QCOW2_OPT_OVERLAP_INACTIVE_L2,
42605de7e86SMax Reitz             .type = QEMU_OPT_BOOL,
42705de7e86SMax Reitz             .help = "Check for unintended writes into an inactive L2 table",
42805de7e86SMax Reitz         },
42974c4510aSKevin Wolf         { /* end of list */ }
43074c4510aSKevin Wolf     },
43174c4510aSKevin Wolf };
43274c4510aSKevin Wolf 
4334092e99dSMax Reitz static const char *overlap_bool_option_names[QCOW2_OL_MAX_BITNR] = {
4344092e99dSMax Reitz     [QCOW2_OL_MAIN_HEADER_BITNR]    = QCOW2_OPT_OVERLAP_MAIN_HEADER,
4354092e99dSMax Reitz     [QCOW2_OL_ACTIVE_L1_BITNR]      = QCOW2_OPT_OVERLAP_ACTIVE_L1,
4364092e99dSMax Reitz     [QCOW2_OL_ACTIVE_L2_BITNR]      = QCOW2_OPT_OVERLAP_ACTIVE_L2,
4374092e99dSMax Reitz     [QCOW2_OL_REFCOUNT_TABLE_BITNR] = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
4384092e99dSMax Reitz     [QCOW2_OL_REFCOUNT_BLOCK_BITNR] = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
4394092e99dSMax Reitz     [QCOW2_OL_SNAPSHOT_TABLE_BITNR] = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
4404092e99dSMax Reitz     [QCOW2_OL_INACTIVE_L1_BITNR]    = QCOW2_OPT_OVERLAP_INACTIVE_L1,
4414092e99dSMax Reitz     [QCOW2_OL_INACTIVE_L2_BITNR]    = QCOW2_OPT_OVERLAP_INACTIVE_L2,
4424092e99dSMax Reitz };
4434092e99dSMax Reitz 
444015a1036SMax Reitz static int qcow2_open(BlockDriverState *bs, QDict *options, int flags,
445015a1036SMax Reitz                       Error **errp)
446585f8587Sbellard {
447585f8587Sbellard     BDRVQcowState *s = bs->opaque;
4486d85a57eSJes Sorensen     int len, i, ret = 0;
449585f8587Sbellard     QCowHeader header;
45074c4510aSKevin Wolf     QemuOpts *opts;
45174c4510aSKevin Wolf     Error *local_err = NULL;
4529b80ddf3Saliguori     uint64_t ext_end;
4532cf7cfa1SKevin Wolf     uint64_t l1_vm_state_index;
4541fa5cc83SMax Reitz     const char *opt_overlap_check;
4551fa5cc83SMax Reitz     int overlap_check_template = 0;
456585f8587Sbellard 
4576d85a57eSJes Sorensen     ret = bdrv_pread(bs->file, 0, &header, sizeof(header));
4586d85a57eSJes Sorensen     if (ret < 0) {
4593ef6c40aSMax Reitz         error_setg_errno(errp, -ret, "Could not read qcow2 header");
460585f8587Sbellard         goto fail;
4616d85a57eSJes Sorensen     }
462585f8587Sbellard     be32_to_cpus(&header.magic);
463585f8587Sbellard     be32_to_cpus(&header.version);
464585f8587Sbellard     be64_to_cpus(&header.backing_file_offset);
465585f8587Sbellard     be32_to_cpus(&header.backing_file_size);
466585f8587Sbellard     be64_to_cpus(&header.size);
467585f8587Sbellard     be32_to_cpus(&header.cluster_bits);
468585f8587Sbellard     be32_to_cpus(&header.crypt_method);
469585f8587Sbellard     be64_to_cpus(&header.l1_table_offset);
470585f8587Sbellard     be32_to_cpus(&header.l1_size);
471585f8587Sbellard     be64_to_cpus(&header.refcount_table_offset);
472585f8587Sbellard     be32_to_cpus(&header.refcount_table_clusters);
473585f8587Sbellard     be64_to_cpus(&header.snapshots_offset);
474585f8587Sbellard     be32_to_cpus(&header.nb_snapshots);
475585f8587Sbellard 
476e8cdcec1SKevin Wolf     if (header.magic != QCOW_MAGIC) {
4773ef6c40aSMax Reitz         error_setg(errp, "Image is not in qcow2 format");
47876abe407SPaolo Bonzini         ret = -EINVAL;
479585f8587Sbellard         goto fail;
4806d85a57eSJes Sorensen     }
4816744cbabSKevin Wolf     if (header.version < 2 || header.version > 3) {
4823ef6c40aSMax Reitz         report_unsupported(bs, errp, "QCOW version %d", header.version);
483e8cdcec1SKevin Wolf         ret = -ENOTSUP;
484e8cdcec1SKevin Wolf         goto fail;
485e8cdcec1SKevin Wolf     }
4866744cbabSKevin Wolf 
4876744cbabSKevin Wolf     s->qcow_version = header.version;
4886744cbabSKevin Wolf 
48924342f2cSKevin Wolf     /* Initialise cluster size */
49024342f2cSKevin Wolf     if (header.cluster_bits < MIN_CLUSTER_BITS ||
49124342f2cSKevin Wolf         header.cluster_bits > MAX_CLUSTER_BITS) {
49224342f2cSKevin Wolf         error_setg(errp, "Unsupported cluster size: 2^%i", header.cluster_bits);
49324342f2cSKevin Wolf         ret = -EINVAL;
49424342f2cSKevin Wolf         goto fail;
49524342f2cSKevin Wolf     }
49624342f2cSKevin Wolf 
49724342f2cSKevin Wolf     s->cluster_bits = header.cluster_bits;
49824342f2cSKevin Wolf     s->cluster_size = 1 << s->cluster_bits;
49924342f2cSKevin Wolf     s->cluster_sectors = 1 << (s->cluster_bits - 9);
50024342f2cSKevin Wolf 
5016744cbabSKevin Wolf     /* Initialise version 3 header fields */
5026744cbabSKevin Wolf     if (header.version == 2) {
5036744cbabSKevin Wolf         header.incompatible_features    = 0;
5046744cbabSKevin Wolf         header.compatible_features      = 0;
5056744cbabSKevin Wolf         header.autoclear_features       = 0;
5066744cbabSKevin Wolf         header.refcount_order           = 4;
5076744cbabSKevin Wolf         header.header_length            = 72;
5086744cbabSKevin Wolf     } else {
5096744cbabSKevin Wolf         be64_to_cpus(&header.incompatible_features);
5106744cbabSKevin Wolf         be64_to_cpus(&header.compatible_features);
5116744cbabSKevin Wolf         be64_to_cpus(&header.autoclear_features);
5126744cbabSKevin Wolf         be32_to_cpus(&header.refcount_order);
5136744cbabSKevin Wolf         be32_to_cpus(&header.header_length);
51424342f2cSKevin Wolf 
51524342f2cSKevin Wolf         if (header.header_length < 104) {
51624342f2cSKevin Wolf             error_setg(errp, "qcow2 header too short");
51724342f2cSKevin Wolf             ret = -EINVAL;
51824342f2cSKevin Wolf             goto fail;
51924342f2cSKevin Wolf         }
52024342f2cSKevin Wolf     }
52124342f2cSKevin Wolf 
52224342f2cSKevin Wolf     if (header.header_length > s->cluster_size) {
52324342f2cSKevin Wolf         error_setg(errp, "qcow2 header exceeds cluster size");
52424342f2cSKevin Wolf         ret = -EINVAL;
52524342f2cSKevin Wolf         goto fail;
5266744cbabSKevin Wolf     }
5276744cbabSKevin Wolf 
5286744cbabSKevin Wolf     if (header.header_length > sizeof(header)) {
5296744cbabSKevin Wolf         s->unknown_header_fields_size = header.header_length - sizeof(header);
5306744cbabSKevin Wolf         s->unknown_header_fields = g_malloc(s->unknown_header_fields_size);
5316744cbabSKevin Wolf         ret = bdrv_pread(bs->file, sizeof(header), s->unknown_header_fields,
5326744cbabSKevin Wolf                          s->unknown_header_fields_size);
5336744cbabSKevin Wolf         if (ret < 0) {
5343ef6c40aSMax Reitz             error_setg_errno(errp, -ret, "Could not read unknown qcow2 header "
5353ef6c40aSMax Reitz                              "fields");
5366744cbabSKevin Wolf             goto fail;
5376744cbabSKevin Wolf         }
5386744cbabSKevin Wolf     }
5396744cbabSKevin Wolf 
540a1b3955cSKevin Wolf     if (header.backing_file_offset > s->cluster_size) {
541a1b3955cSKevin Wolf         error_setg(errp, "Invalid backing file offset");
542a1b3955cSKevin Wolf         ret = -EINVAL;
543a1b3955cSKevin Wolf         goto fail;
544a1b3955cSKevin Wolf     }
545a1b3955cSKevin Wolf 
546cfcc4c62SKevin Wolf     if (header.backing_file_offset) {
547cfcc4c62SKevin Wolf         ext_end = header.backing_file_offset;
548cfcc4c62SKevin Wolf     } else {
549cfcc4c62SKevin Wolf         ext_end = 1 << header.cluster_bits;
550cfcc4c62SKevin Wolf     }
551cfcc4c62SKevin Wolf 
5526744cbabSKevin Wolf     /* Handle feature bits */
5536744cbabSKevin Wolf     s->incompatible_features    = header.incompatible_features;
5546744cbabSKevin Wolf     s->compatible_features      = header.compatible_features;
5556744cbabSKevin Wolf     s->autoclear_features       = header.autoclear_features;
5566744cbabSKevin Wolf 
557c61d0004SStefan Hajnoczi     if (s->incompatible_features & ~QCOW2_INCOMPAT_MASK) {
558cfcc4c62SKevin Wolf         void *feature_table = NULL;
559cfcc4c62SKevin Wolf         qcow2_read_extensions(bs, header.header_length, ext_end,
5603ef6c40aSMax Reitz                               &feature_table, NULL);
5613ef6c40aSMax Reitz         report_unsupported_feature(bs, errp, feature_table,
562c61d0004SStefan Hajnoczi                                    s->incompatible_features &
563c61d0004SStefan Hajnoczi                                    ~QCOW2_INCOMPAT_MASK);
5646744cbabSKevin Wolf         ret = -ENOTSUP;
565c5a33ee9SPrasad Joshi         g_free(feature_table);
5666744cbabSKevin Wolf         goto fail;
5676744cbabSKevin Wolf     }
5686744cbabSKevin Wolf 
56969c98726SMax Reitz     if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
57069c98726SMax Reitz         /* Corrupt images may not be written to unless they are being repaired
57169c98726SMax Reitz          */
57269c98726SMax Reitz         if ((flags & BDRV_O_RDWR) && !(flags & BDRV_O_CHECK)) {
5733ef6c40aSMax Reitz             error_setg(errp, "qcow2: Image is corrupt; cannot be opened "
5743ef6c40aSMax Reitz                        "read/write");
57569c98726SMax Reitz             ret = -EACCES;
57669c98726SMax Reitz             goto fail;
57769c98726SMax Reitz         }
57869c98726SMax Reitz     }
57969c98726SMax Reitz 
5806744cbabSKevin Wolf     /* Check support for various header values */
5816744cbabSKevin Wolf     if (header.refcount_order != 4) {
5823ef6c40aSMax Reitz         report_unsupported(bs, errp, "%d bit reference counts",
5836744cbabSKevin Wolf                            1 << header.refcount_order);
5846744cbabSKevin Wolf         ret = -ENOTSUP;
5856744cbabSKevin Wolf         goto fail;
5866744cbabSKevin Wolf     }
587b6481f37SMax Reitz     s->refcount_order = header.refcount_order;
5886744cbabSKevin Wolf 
5896d85a57eSJes Sorensen     if (header.crypt_method > QCOW_CRYPT_AES) {
5903ef6c40aSMax Reitz         error_setg(errp, "Unsupported encryption method: %i",
5913ef6c40aSMax Reitz                    header.crypt_method);
5926d85a57eSJes Sorensen         ret = -EINVAL;
593585f8587Sbellard         goto fail;
5946d85a57eSJes Sorensen     }
595585f8587Sbellard     s->crypt_method_header = header.crypt_method;
5966d85a57eSJes Sorensen     if (s->crypt_method_header) {
597585f8587Sbellard         bs->encrypted = 1;
5986d85a57eSJes Sorensen     }
59924342f2cSKevin Wolf 
600585f8587Sbellard     s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */
601585f8587Sbellard     s->l2_size = 1 << s->l2_bits;
602585f8587Sbellard     bs->total_sectors = header.size / 512;
603585f8587Sbellard     s->csize_shift = (62 - (s->cluster_bits - 8));
604585f8587Sbellard     s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;
605585f8587Sbellard     s->cluster_offset_mask = (1LL << s->csize_shift) - 1;
6065dab2fadSKevin Wolf 
607585f8587Sbellard     s->refcount_table_offset = header.refcount_table_offset;
608585f8587Sbellard     s->refcount_table_size =
609585f8587Sbellard         header.refcount_table_clusters << (s->cluster_bits - 3);
610585f8587Sbellard 
6115dab2fadSKevin Wolf     if (header.refcount_table_clusters > (0x800000 >> s->cluster_bits)) {
6125dab2fadSKevin Wolf         /* 8 MB refcount table is enough for 2 PB images at 64k cluster size
6135dab2fadSKevin Wolf          * (128 GB for 512 byte clusters, 2 EB for 2 MB clusters) */
6145dab2fadSKevin Wolf         error_setg(errp, "Reference count table too large");
6155dab2fadSKevin Wolf         ret = -EINVAL;
6165dab2fadSKevin Wolf         goto fail;
6175dab2fadSKevin Wolf     }
6185dab2fadSKevin Wolf 
6198c7de283SKevin Wolf     ret = validate_table_offset(bs, s->refcount_table_offset,
6208c7de283SKevin Wolf                                 s->refcount_table_size, sizeof(uint64_t));
6218c7de283SKevin Wolf     if (ret < 0) {
6228c7de283SKevin Wolf         error_setg(errp, "Invalid reference count table offset");
6238c7de283SKevin Wolf         goto fail;
6248c7de283SKevin Wolf     }
6258c7de283SKevin Wolf 
626ce48f2f4SKevin Wolf     /* Snapshot table offset/length */
627ce48f2f4SKevin Wolf     if (header.nb_snapshots > QCOW_MAX_SNAPSHOTS) {
628ce48f2f4SKevin Wolf         error_setg(errp, "Too many snapshots");
629ce48f2f4SKevin Wolf         ret = -EINVAL;
630ce48f2f4SKevin Wolf         goto fail;
631ce48f2f4SKevin Wolf     }
632ce48f2f4SKevin Wolf 
633ce48f2f4SKevin Wolf     ret = validate_table_offset(bs, header.snapshots_offset,
634ce48f2f4SKevin Wolf                                 header.nb_snapshots,
635ce48f2f4SKevin Wolf                                 sizeof(QCowSnapshotHeader));
636ce48f2f4SKevin Wolf     if (ret < 0) {
637ce48f2f4SKevin Wolf         error_setg(errp, "Invalid snapshot table offset");
638ce48f2f4SKevin Wolf         goto fail;
639ce48f2f4SKevin Wolf     }
640ce48f2f4SKevin Wolf 
641585f8587Sbellard     s->snapshots_offset = header.snapshots_offset;
642585f8587Sbellard     s->nb_snapshots = header.nb_snapshots;
643585f8587Sbellard 
644585f8587Sbellard     /* read the level 1 table */
645*2d51c32cSKevin Wolf     if (header.l1_size > 0x2000000) {
646*2d51c32cSKevin Wolf         /* 32 MB L1 table is enough for 2 PB images at 64k cluster size
647*2d51c32cSKevin Wolf          * (128 GB for 512 byte clusters, 2 EB for 2 MB clusters) */
648*2d51c32cSKevin Wolf         error_setg(errp, "Active L1 table too large");
649*2d51c32cSKevin Wolf         ret = -EFBIG;
650*2d51c32cSKevin Wolf         goto fail;
651*2d51c32cSKevin Wolf     }
652585f8587Sbellard     s->l1_size = header.l1_size;
6532cf7cfa1SKevin Wolf 
6542cf7cfa1SKevin Wolf     l1_vm_state_index = size_to_l1(s, header.size);
6552cf7cfa1SKevin Wolf     if (l1_vm_state_index > INT_MAX) {
6563ef6c40aSMax Reitz         error_setg(errp, "Image is too big");
6572cf7cfa1SKevin Wolf         ret = -EFBIG;
6582cf7cfa1SKevin Wolf         goto fail;
6592cf7cfa1SKevin Wolf     }
6602cf7cfa1SKevin Wolf     s->l1_vm_state_index = l1_vm_state_index;
6612cf7cfa1SKevin Wolf 
662585f8587Sbellard     /* the L1 table must contain at least enough entries to put
663585f8587Sbellard        header.size bytes */
6646d85a57eSJes Sorensen     if (s->l1_size < s->l1_vm_state_index) {
6653ef6c40aSMax Reitz         error_setg(errp, "L1 table is too small");
6666d85a57eSJes Sorensen         ret = -EINVAL;
667585f8587Sbellard         goto fail;
6686d85a57eSJes Sorensen     }
669*2d51c32cSKevin Wolf 
670*2d51c32cSKevin Wolf     ret = validate_table_offset(bs, header.l1_table_offset,
671*2d51c32cSKevin Wolf                                 header.l1_size, sizeof(uint64_t));
672*2d51c32cSKevin Wolf     if (ret < 0) {
673*2d51c32cSKevin Wolf         error_setg(errp, "Invalid L1 table offset");
674*2d51c32cSKevin Wolf         goto fail;
675*2d51c32cSKevin Wolf     }
676585f8587Sbellard     s->l1_table_offset = header.l1_table_offset;
677*2d51c32cSKevin Wolf 
678*2d51c32cSKevin Wolf 
679d191d12dSStefan Weil     if (s->l1_size > 0) {
6807267c094SAnthony Liguori         s->l1_table = g_malloc0(
6813f6a3ee5SKevin Wolf             align_offset(s->l1_size * sizeof(uint64_t), 512));
6826d85a57eSJes Sorensen         ret = bdrv_pread(bs->file, s->l1_table_offset, s->l1_table,
6836d85a57eSJes Sorensen                          s->l1_size * sizeof(uint64_t));
6846d85a57eSJes Sorensen         if (ret < 0) {
6853ef6c40aSMax Reitz             error_setg_errno(errp, -ret, "Could not read L1 table");
686585f8587Sbellard             goto fail;
6876d85a57eSJes Sorensen         }
688585f8587Sbellard         for(i = 0;i < s->l1_size; i++) {
689585f8587Sbellard             be64_to_cpus(&s->l1_table[i]);
690585f8587Sbellard         }
691d191d12dSStefan Weil     }
69229c1a730SKevin Wolf 
69329c1a730SKevin Wolf     /* alloc L2 table/refcount block cache */
6946af4e9eaSPaolo Bonzini     s->l2_table_cache = qcow2_cache_create(bs, L2_CACHE_SIZE);
6956af4e9eaSPaolo Bonzini     s->refcount_block_cache = qcow2_cache_create(bs, REFCOUNT_CACHE_SIZE);
69629c1a730SKevin Wolf 
6977267c094SAnthony Liguori     s->cluster_cache = g_malloc(s->cluster_size);
698585f8587Sbellard     /* one more sector for decompressed data alignment */
699dea43a65SFrediano Ziglio     s->cluster_data = qemu_blockalign(bs, QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size
700095a9c58Saliguori                                   + 512);
701585f8587Sbellard     s->cluster_cache_offset = -1;
70206d9260fSAnthony Liguori     s->flags = flags;
703585f8587Sbellard 
7046d85a57eSJes Sorensen     ret = qcow2_refcount_init(bs);
7056d85a57eSJes Sorensen     if (ret != 0) {
7063ef6c40aSMax Reitz         error_setg_errno(errp, -ret, "Could not initialize refcount handling");
707585f8587Sbellard         goto fail;
7086d85a57eSJes Sorensen     }
709585f8587Sbellard 
71072cf2d4fSBlue Swirl     QLIST_INIT(&s->cluster_allocs);
7110b919faeSKevin Wolf     QTAILQ_INIT(&s->discards);
712f214978aSKevin Wolf 
7139b80ddf3Saliguori     /* read qcow2 extensions */
7143ef6c40aSMax Reitz     if (qcow2_read_extensions(bs, header.header_length, ext_end, NULL,
7153ef6c40aSMax Reitz         &local_err)) {
7163ef6c40aSMax Reitz         error_propagate(errp, local_err);
7176d85a57eSJes Sorensen         ret = -EINVAL;
7189b80ddf3Saliguori         goto fail;
7196d85a57eSJes Sorensen     }
7209b80ddf3Saliguori 
721585f8587Sbellard     /* read the backing file name */
722585f8587Sbellard     if (header.backing_file_offset != 0) {
723585f8587Sbellard         len = header.backing_file_size;
7246d85a57eSJes Sorensen         if (len > 1023) {
725585f8587Sbellard             len = 1023;
7266d85a57eSJes Sorensen         }
7276d85a57eSJes Sorensen         ret = bdrv_pread(bs->file, header.backing_file_offset,
7286d85a57eSJes Sorensen                          bs->backing_file, len);
7296d85a57eSJes Sorensen         if (ret < 0) {
7303ef6c40aSMax Reitz             error_setg_errno(errp, -ret, "Could not read backing file name");
731585f8587Sbellard             goto fail;
7326d85a57eSJes Sorensen         }
733585f8587Sbellard         bs->backing_file[len] = '\0';
734585f8587Sbellard     }
73542deb29fSKevin Wolf 
73642deb29fSKevin Wolf     ret = qcow2_read_snapshots(bs);
73742deb29fSKevin Wolf     if (ret < 0) {
7383ef6c40aSMax Reitz         error_setg_errno(errp, -ret, "Could not read snapshots");
739585f8587Sbellard         goto fail;
7406d85a57eSJes Sorensen     }
741585f8587Sbellard 
742af7b708dSStefan Hajnoczi     /* Clear unknown autoclear feature bits */
74327eb6c09SKevin Wolf     if (!bs->read_only && !(flags & BDRV_O_INCOMING) && s->autoclear_features) {
744af7b708dSStefan Hajnoczi         s->autoclear_features = 0;
745af7b708dSStefan Hajnoczi         ret = qcow2_update_header(bs);
746af7b708dSStefan Hajnoczi         if (ret < 0) {
7473ef6c40aSMax Reitz             error_setg_errno(errp, -ret, "Could not update qcow2 header");
748af7b708dSStefan Hajnoczi             goto fail;
749af7b708dSStefan Hajnoczi         }
750af7b708dSStefan Hajnoczi     }
751af7b708dSStefan Hajnoczi 
75268d100e9SKevin Wolf     /* Initialise locks */
75368d100e9SKevin Wolf     qemu_co_mutex_init(&s->lock);
75468d100e9SKevin Wolf 
755c61d0004SStefan Hajnoczi     /* Repair image if dirty */
75627eb6c09SKevin Wolf     if (!(flags & (BDRV_O_CHECK | BDRV_O_INCOMING)) && !bs->read_only &&
757058f8f16SStefan Hajnoczi         (s->incompatible_features & QCOW2_INCOMPAT_DIRTY)) {
758c61d0004SStefan Hajnoczi         BdrvCheckResult result = {0};
759c61d0004SStefan Hajnoczi 
760acbe5982SStefan Hajnoczi         ret = qcow2_check(bs, &result, BDRV_FIX_ERRORS);
761c61d0004SStefan Hajnoczi         if (ret < 0) {
7623ef6c40aSMax Reitz             error_setg_errno(errp, -ret, "Could not repair dirty image");
763c61d0004SStefan Hajnoczi             goto fail;
764c61d0004SStefan Hajnoczi         }
765c61d0004SStefan Hajnoczi     }
766c61d0004SStefan Hajnoczi 
76774c4510aSKevin Wolf     /* Enable lazy_refcounts according to image and command line options */
76887ea75d5SPeter Crosthwaite     opts = qemu_opts_create(&qcow2_runtime_opts, NULL, 0, &error_abort);
76974c4510aSKevin Wolf     qemu_opts_absorb_qdict(opts, options, &local_err);
77084d18f06SMarkus Armbruster     if (local_err) {
7713ef6c40aSMax Reitz         error_propagate(errp, local_err);
77274c4510aSKevin Wolf         ret = -EINVAL;
77374c4510aSKevin Wolf         goto fail;
77474c4510aSKevin Wolf     }
77574c4510aSKevin Wolf 
776acdfb480SKevin Wolf     s->use_lazy_refcounts = qemu_opt_get_bool(opts, QCOW2_OPT_LAZY_REFCOUNTS,
77774c4510aSKevin Wolf         (s->compatible_features & QCOW2_COMPAT_LAZY_REFCOUNTS));
77874c4510aSKevin Wolf 
77967af674eSKevin Wolf     s->discard_passthrough[QCOW2_DISCARD_NEVER] = false;
78067af674eSKevin Wolf     s->discard_passthrough[QCOW2_DISCARD_ALWAYS] = true;
78167af674eSKevin Wolf     s->discard_passthrough[QCOW2_DISCARD_REQUEST] =
78267af674eSKevin Wolf         qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_REQUEST,
78367af674eSKevin Wolf                           flags & BDRV_O_UNMAP);
78467af674eSKevin Wolf     s->discard_passthrough[QCOW2_DISCARD_SNAPSHOT] =
78567af674eSKevin Wolf         qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_SNAPSHOT, true);
78667af674eSKevin Wolf     s->discard_passthrough[QCOW2_DISCARD_OTHER] =
78767af674eSKevin Wolf         qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_OTHER, false);
78867af674eSKevin Wolf 
7891fa5cc83SMax Reitz     opt_overlap_check = qemu_opt_get(opts, "overlap-check") ?: "cached";
7901fa5cc83SMax Reitz     if (!strcmp(opt_overlap_check, "none")) {
7911fa5cc83SMax Reitz         overlap_check_template = 0;
7921fa5cc83SMax Reitz     } else if (!strcmp(opt_overlap_check, "constant")) {
7931fa5cc83SMax Reitz         overlap_check_template = QCOW2_OL_CONSTANT;
7941fa5cc83SMax Reitz     } else if (!strcmp(opt_overlap_check, "cached")) {
7951fa5cc83SMax Reitz         overlap_check_template = QCOW2_OL_CACHED;
7961fa5cc83SMax Reitz     } else if (!strcmp(opt_overlap_check, "all")) {
7971fa5cc83SMax Reitz         overlap_check_template = QCOW2_OL_ALL;
7981fa5cc83SMax Reitz     } else {
7991fa5cc83SMax Reitz         error_setg(errp, "Unsupported value '%s' for qcow2 option "
8001fa5cc83SMax Reitz                    "'overlap-check'. Allowed are either of the following: "
8011fa5cc83SMax Reitz                    "none, constant, cached, all", opt_overlap_check);
8021fa5cc83SMax Reitz         qemu_opts_del(opts);
8031fa5cc83SMax Reitz         ret = -EINVAL;
8041fa5cc83SMax Reitz         goto fail;
8051fa5cc83SMax Reitz     }
8061fa5cc83SMax Reitz 
8071fa5cc83SMax Reitz     s->overlap_check = 0;
8081fa5cc83SMax Reitz     for (i = 0; i < QCOW2_OL_MAX_BITNR; i++) {
8091fa5cc83SMax Reitz         /* overlap-check defines a template bitmask, but every flag may be
8101fa5cc83SMax Reitz          * overwritten through the associated boolean option */
8111fa5cc83SMax Reitz         s->overlap_check |=
8121fa5cc83SMax Reitz             qemu_opt_get_bool(opts, overlap_bool_option_names[i],
8131fa5cc83SMax Reitz                               overlap_check_template & (1 << i)) << i;
8141fa5cc83SMax Reitz     }
8153e355390SMax Reitz 
81674c4510aSKevin Wolf     qemu_opts_del(opts);
81774c4510aSKevin Wolf 
81874c4510aSKevin Wolf     if (s->use_lazy_refcounts && s->qcow_version < 3) {
8193ef6c40aSMax Reitz         error_setg(errp, "Lazy refcounts require a qcow2 image with at least "
8203ef6c40aSMax Reitz                    "qemu 1.1 compatibility level");
82174c4510aSKevin Wolf         ret = -EINVAL;
82274c4510aSKevin Wolf         goto fail;
82374c4510aSKevin Wolf     }
82474c4510aSKevin Wolf 
825585f8587Sbellard #ifdef DEBUG_ALLOC
8266cbc3031SPhilipp Hahn     {
8276cbc3031SPhilipp Hahn         BdrvCheckResult result = {0};
828b35278f7SStefan Hajnoczi         qcow2_check_refcounts(bs, &result, 0);
8296cbc3031SPhilipp Hahn     }
830585f8587Sbellard #endif
8316d85a57eSJes Sorensen     return ret;
832585f8587Sbellard 
833585f8587Sbellard  fail:
8346744cbabSKevin Wolf     g_free(s->unknown_header_fields);
83575bab85cSKevin Wolf     cleanup_unknown_header_ext(bs);
836ed6ccf0fSKevin Wolf     qcow2_free_snapshots(bs);
837ed6ccf0fSKevin Wolf     qcow2_refcount_close(bs);
8387267c094SAnthony Liguori     g_free(s->l1_table);
839cf93980eSMax Reitz     /* else pre-write overlap checks in cache_destroy may crash */
840cf93980eSMax Reitz     s->l1_table = NULL;
84129c1a730SKevin Wolf     if (s->l2_table_cache) {
84229c1a730SKevin Wolf         qcow2_cache_destroy(bs, s->l2_table_cache);
84329c1a730SKevin Wolf     }
844c5a33ee9SPrasad Joshi     if (s->refcount_block_cache) {
845c5a33ee9SPrasad Joshi         qcow2_cache_destroy(bs, s->refcount_block_cache);
846c5a33ee9SPrasad Joshi     }
8477267c094SAnthony Liguori     g_free(s->cluster_cache);
848dea43a65SFrediano Ziglio     qemu_vfree(s->cluster_data);
8496d85a57eSJes Sorensen     return ret;
850585f8587Sbellard }
851585f8587Sbellard 
852d34682cdSKevin Wolf static int qcow2_refresh_limits(BlockDriverState *bs)
853d34682cdSKevin Wolf {
854d34682cdSKevin Wolf     BDRVQcowState *s = bs->opaque;
855d34682cdSKevin Wolf 
856d34682cdSKevin Wolf     bs->bl.write_zeroes_alignment = s->cluster_sectors;
857d34682cdSKevin Wolf 
858d34682cdSKevin Wolf     return 0;
859d34682cdSKevin Wolf }
860d34682cdSKevin Wolf 
8617c80ab3fSJes Sorensen static int qcow2_set_key(BlockDriverState *bs, const char *key)
862585f8587Sbellard {
863585f8587Sbellard     BDRVQcowState *s = bs->opaque;
864585f8587Sbellard     uint8_t keybuf[16];
865585f8587Sbellard     int len, i;
866585f8587Sbellard 
867585f8587Sbellard     memset(keybuf, 0, 16);
868585f8587Sbellard     len = strlen(key);
869585f8587Sbellard     if (len > 16)
870585f8587Sbellard         len = 16;
871585f8587Sbellard     /* XXX: we could compress the chars to 7 bits to increase
872585f8587Sbellard        entropy */
873585f8587Sbellard     for(i = 0;i < len;i++) {
874585f8587Sbellard         keybuf[i] = key[i];
875585f8587Sbellard     }
876585f8587Sbellard     s->crypt_method = s->crypt_method_header;
877585f8587Sbellard 
878585f8587Sbellard     if (AES_set_encrypt_key(keybuf, 128, &s->aes_encrypt_key) != 0)
879585f8587Sbellard         return -1;
880585f8587Sbellard     if (AES_set_decrypt_key(keybuf, 128, &s->aes_decrypt_key) != 0)
881585f8587Sbellard         return -1;
882585f8587Sbellard #if 0
883585f8587Sbellard     /* test */
884585f8587Sbellard     {
885585f8587Sbellard         uint8_t in[16];
886585f8587Sbellard         uint8_t out[16];
887585f8587Sbellard         uint8_t tmp[16];
888585f8587Sbellard         for(i=0;i<16;i++)
889585f8587Sbellard             in[i] = i;
890585f8587Sbellard         AES_encrypt(in, tmp, &s->aes_encrypt_key);
891585f8587Sbellard         AES_decrypt(tmp, out, &s->aes_decrypt_key);
892585f8587Sbellard         for(i = 0; i < 16; i++)
893585f8587Sbellard             printf(" %02x", tmp[i]);
894585f8587Sbellard         printf("\n");
895585f8587Sbellard         for(i = 0; i < 16; i++)
896585f8587Sbellard             printf(" %02x", out[i]);
897585f8587Sbellard         printf("\n");
898585f8587Sbellard     }
899585f8587Sbellard #endif
900585f8587Sbellard     return 0;
901585f8587Sbellard }
902585f8587Sbellard 
90321d82ac9SJeff Cody /* We have nothing to do for QCOW2 reopen, stubs just return
90421d82ac9SJeff Cody  * success */
90521d82ac9SJeff Cody static int qcow2_reopen_prepare(BDRVReopenState *state,
90621d82ac9SJeff Cody                                 BlockReopenQueue *queue, Error **errp)
90721d82ac9SJeff Cody {
90821d82ac9SJeff Cody     return 0;
90921d82ac9SJeff Cody }
91021d82ac9SJeff Cody 
911b6b8a333SPaolo Bonzini static int64_t coroutine_fn qcow2_co_get_block_status(BlockDriverState *bs,
912f8a2e5e3SStefan Hajnoczi         int64_t sector_num, int nb_sectors, int *pnum)
913585f8587Sbellard {
914f8a2e5e3SStefan Hajnoczi     BDRVQcowState *s = bs->opaque;
915585f8587Sbellard     uint64_t cluster_offset;
9164bc74be9SPaolo Bonzini     int index_in_cluster, ret;
9174bc74be9SPaolo Bonzini     int64_t status = 0;
918585f8587Sbellard 
919095a9c58Saliguori     *pnum = nb_sectors;
920f8a2e5e3SStefan Hajnoczi     qemu_co_mutex_lock(&s->lock);
9211c46efaaSKevin Wolf     ret = qcow2_get_cluster_offset(bs, sector_num << 9, pnum, &cluster_offset);
922f8a2e5e3SStefan Hajnoczi     qemu_co_mutex_unlock(&s->lock);
9231c46efaaSKevin Wolf     if (ret < 0) {
924d663640cSPaolo Bonzini         return ret;
9251c46efaaSKevin Wolf     }
926095a9c58Saliguori 
9274bc74be9SPaolo Bonzini     if (cluster_offset != 0 && ret != QCOW2_CLUSTER_COMPRESSED &&
9284bc74be9SPaolo Bonzini         !s->crypt_method) {
9294bc74be9SPaolo Bonzini         index_in_cluster = sector_num & (s->cluster_sectors - 1);
9304bc74be9SPaolo Bonzini         cluster_offset |= (index_in_cluster << BDRV_SECTOR_BITS);
9314bc74be9SPaolo Bonzini         status |= BDRV_BLOCK_OFFSET_VALID | cluster_offset;
9324bc74be9SPaolo Bonzini     }
9334bc74be9SPaolo Bonzini     if (ret == QCOW2_CLUSTER_ZERO) {
9344bc74be9SPaolo Bonzini         status |= BDRV_BLOCK_ZERO;
9354bc74be9SPaolo Bonzini     } else if (ret != QCOW2_CLUSTER_UNALLOCATED) {
9364bc74be9SPaolo Bonzini         status |= BDRV_BLOCK_DATA;
9374bc74be9SPaolo Bonzini     }
9384bc74be9SPaolo Bonzini     return status;
939585f8587Sbellard }
940585f8587Sbellard 
941a9465922Sbellard /* handle reading after the end of the backing file */
942bd28f835SKevin Wolf int qcow2_backing_read1(BlockDriverState *bs, QEMUIOVector *qiov,
943bd28f835SKevin Wolf                   int64_t sector_num, int nb_sectors)
944a9465922Sbellard {
945a9465922Sbellard     int n1;
946a9465922Sbellard     if ((sector_num + nb_sectors) <= bs->total_sectors)
947a9465922Sbellard         return nb_sectors;
948a9465922Sbellard     if (sector_num >= bs->total_sectors)
949a9465922Sbellard         n1 = 0;
950a9465922Sbellard     else
951a9465922Sbellard         n1 = bs->total_sectors - sector_num;
952bd28f835SKevin Wolf 
9533d9b4925SMichael Tokarev     qemu_iovec_memset(qiov, 512 * n1, 0, 512 * (nb_sectors - n1));
954bd28f835SKevin Wolf 
955a9465922Sbellard     return n1;
956a9465922Sbellard }
957a9465922Sbellard 
958a968168cSDong Xu Wang static coroutine_fn int qcow2_co_readv(BlockDriverState *bs, int64_t sector_num,
9593fc48d09SFrediano Ziglio                           int remaining_sectors, QEMUIOVector *qiov)
9601490791fSaliguori {
961585f8587Sbellard     BDRVQcowState *s = bs->opaque;
962a9465922Sbellard     int index_in_cluster, n1;
96368d100e9SKevin Wolf     int ret;
964faf575c1SFrediano Ziglio     int cur_nr_sectors; /* number of sectors in current iteration */
965c2bdd990SFrediano Ziglio     uint64_t cluster_offset = 0;
9663fc48d09SFrediano Ziglio     uint64_t bytes_done = 0;
9673fc48d09SFrediano Ziglio     QEMUIOVector hd_qiov;
9683fc48d09SFrediano Ziglio     uint8_t *cluster_data = NULL;
969585f8587Sbellard 
9703fc48d09SFrediano Ziglio     qemu_iovec_init(&hd_qiov, qiov->niov);
9713fc48d09SFrediano Ziglio 
9723fc48d09SFrediano Ziglio     qemu_co_mutex_lock(&s->lock);
9733fc48d09SFrediano Ziglio 
9743fc48d09SFrediano Ziglio     while (remaining_sectors != 0) {
975585f8587Sbellard 
976faf575c1SFrediano Ziglio         /* prepare next request */
9773fc48d09SFrediano Ziglio         cur_nr_sectors = remaining_sectors;
978bd28f835SKevin Wolf         if (s->crypt_method) {
979faf575c1SFrediano Ziglio             cur_nr_sectors = MIN(cur_nr_sectors,
980bd28f835SKevin Wolf                 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors);
981bd28f835SKevin Wolf         }
982bd28f835SKevin Wolf 
9833fc48d09SFrediano Ziglio         ret = qcow2_get_cluster_offset(bs, sector_num << 9,
984c2bdd990SFrediano Ziglio             &cur_nr_sectors, &cluster_offset);
9851c46efaaSKevin Wolf         if (ret < 0) {
9863fc48d09SFrediano Ziglio             goto fail;
9871c46efaaSKevin Wolf         }
9881c46efaaSKevin Wolf 
9893fc48d09SFrediano Ziglio         index_in_cluster = sector_num & (s->cluster_sectors - 1);
990585f8587Sbellard 
9913fc48d09SFrediano Ziglio         qemu_iovec_reset(&hd_qiov);
9921b093c48SMichael Tokarev         qemu_iovec_concat(&hd_qiov, qiov, bytes_done,
993faf575c1SFrediano Ziglio             cur_nr_sectors * 512);
994bd28f835SKevin Wolf 
99568d000a3SKevin Wolf         switch (ret) {
99668d000a3SKevin Wolf         case QCOW2_CLUSTER_UNALLOCATED:
997bd28f835SKevin Wolf 
998585f8587Sbellard             if (bs->backing_hd) {
999585f8587Sbellard                 /* read from the base image */
10003fc48d09SFrediano Ziglio                 n1 = qcow2_backing_read1(bs->backing_hd, &hd_qiov,
10013fc48d09SFrediano Ziglio                     sector_num, cur_nr_sectors);
1002a9465922Sbellard                 if (n1 > 0) {
100366f82ceeSKevin Wolf                     BLKDBG_EVENT(bs->file, BLKDBG_READ_BACKING_AIO);
100468d100e9SKevin Wolf                     qemu_co_mutex_unlock(&s->lock);
10053fc48d09SFrediano Ziglio                     ret = bdrv_co_readv(bs->backing_hd, sector_num,
10063fc48d09SFrediano Ziglio                                         n1, &hd_qiov);
100768d100e9SKevin Wolf                     qemu_co_mutex_lock(&s->lock);
100868d100e9SKevin Wolf                     if (ret < 0) {
10093fc48d09SFrediano Ziglio                         goto fail;
10103ab4c7e9SKevin Wolf                     }
10111490791fSaliguori                 }
1012a9465922Sbellard             } else {
1013585f8587Sbellard                 /* Note: in this case, no need to wait */
10143d9b4925SMichael Tokarev                 qemu_iovec_memset(&hd_qiov, 0, 0, 512 * cur_nr_sectors);
10151490791fSaliguori             }
101668d000a3SKevin Wolf             break;
101768d000a3SKevin Wolf 
10186377af48SKevin Wolf         case QCOW2_CLUSTER_ZERO:
10193d9b4925SMichael Tokarev             qemu_iovec_memset(&hd_qiov, 0, 0, 512 * cur_nr_sectors);
10206377af48SKevin Wolf             break;
10216377af48SKevin Wolf 
102268d000a3SKevin Wolf         case QCOW2_CLUSTER_COMPRESSED:
1023585f8587Sbellard             /* add AIO support for compressed blocks ? */
1024c2bdd990SFrediano Ziglio             ret = qcow2_decompress_cluster(bs, cluster_offset);
10258af36488SKevin Wolf             if (ret < 0) {
10263fc48d09SFrediano Ziglio                 goto fail;
10278af36488SKevin Wolf             }
1028bd28f835SKevin Wolf 
102903396148SMichael Tokarev             qemu_iovec_from_buf(&hd_qiov, 0,
1030bd28f835SKevin Wolf                 s->cluster_cache + index_in_cluster * 512,
1031faf575c1SFrediano Ziglio                 512 * cur_nr_sectors);
103268d000a3SKevin Wolf             break;
103368d000a3SKevin Wolf 
103468d000a3SKevin Wolf         case QCOW2_CLUSTER_NORMAL:
1035c2bdd990SFrediano Ziglio             if ((cluster_offset & 511) != 0) {
10363fc48d09SFrediano Ziglio                 ret = -EIO;
10373fc48d09SFrediano Ziglio                 goto fail;
1038585f8587Sbellard             }
1039c87c0672Saliguori 
1040bd28f835SKevin Wolf             if (s->crypt_method) {
1041bd28f835SKevin Wolf                 /*
1042bd28f835SKevin Wolf                  * For encrypted images, read everything into a temporary
1043bd28f835SKevin Wolf                  * contiguous buffer on which the AES functions can work.
1044bd28f835SKevin Wolf                  */
10453fc48d09SFrediano Ziglio                 if (!cluster_data) {
10463fc48d09SFrediano Ziglio                     cluster_data =
1047dea43a65SFrediano Ziglio                         qemu_blockalign(bs, QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
1048bd28f835SKevin Wolf                 }
1049bd28f835SKevin Wolf 
1050faf575c1SFrediano Ziglio                 assert(cur_nr_sectors <=
1051bd28f835SKevin Wolf                     QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors);
10523fc48d09SFrediano Ziglio                 qemu_iovec_reset(&hd_qiov);
10533fc48d09SFrediano Ziglio                 qemu_iovec_add(&hd_qiov, cluster_data,
1054faf575c1SFrediano Ziglio                     512 * cur_nr_sectors);
1055bd28f835SKevin Wolf             }
1056bd28f835SKevin Wolf 
105766f82ceeSKevin Wolf             BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);
105868d100e9SKevin Wolf             qemu_co_mutex_unlock(&s->lock);
105968d100e9SKevin Wolf             ret = bdrv_co_readv(bs->file,
1060c2bdd990SFrediano Ziglio                                 (cluster_offset >> 9) + index_in_cluster,
10613fc48d09SFrediano Ziglio                                 cur_nr_sectors, &hd_qiov);
106268d100e9SKevin Wolf             qemu_co_mutex_lock(&s->lock);
106368d100e9SKevin Wolf             if (ret < 0) {
10643fc48d09SFrediano Ziglio                 goto fail;
1065585f8587Sbellard             }
1066faf575c1SFrediano Ziglio             if (s->crypt_method) {
10673fc48d09SFrediano Ziglio                 qcow2_encrypt_sectors(s, sector_num,  cluster_data,
10683fc48d09SFrediano Ziglio                     cluster_data, cur_nr_sectors, 0, &s->aes_decrypt_key);
106903396148SMichael Tokarev                 qemu_iovec_from_buf(qiov, bytes_done,
107003396148SMichael Tokarev                     cluster_data, 512 * cur_nr_sectors);
1071171e3d6bSKevin Wolf             }
107268d000a3SKevin Wolf             break;
107368d000a3SKevin Wolf 
107468d000a3SKevin Wolf         default:
107568d000a3SKevin Wolf             g_assert_not_reached();
107668d000a3SKevin Wolf             ret = -EIO;
107768d000a3SKevin Wolf             goto fail;
1078faf575c1SFrediano Ziglio         }
1079faf575c1SFrediano Ziglio 
10803fc48d09SFrediano Ziglio         remaining_sectors -= cur_nr_sectors;
10813fc48d09SFrediano Ziglio         sector_num += cur_nr_sectors;
10823fc48d09SFrediano Ziglio         bytes_done += cur_nr_sectors * 512;
10835ebaa27eSFrediano Ziglio     }
10843fc48d09SFrediano Ziglio     ret = 0;
1085f141eafeSaliguori 
10863fc48d09SFrediano Ziglio fail:
108768d100e9SKevin Wolf     qemu_co_mutex_unlock(&s->lock);
108868d100e9SKevin Wolf 
10893fc48d09SFrediano Ziglio     qemu_iovec_destroy(&hd_qiov);
1090dea43a65SFrediano Ziglio     qemu_vfree(cluster_data);
109168d100e9SKevin Wolf 
109268d100e9SKevin Wolf     return ret;
1093585f8587Sbellard }
1094585f8587Sbellard 
1095a968168cSDong Xu Wang static coroutine_fn int qcow2_co_writev(BlockDriverState *bs,
10963fc48d09SFrediano Ziglio                            int64_t sector_num,
10973fc48d09SFrediano Ziglio                            int remaining_sectors,
10983fc48d09SFrediano Ziglio                            QEMUIOVector *qiov)
1099585f8587Sbellard {
1100585f8587Sbellard     BDRVQcowState *s = bs->opaque;
1101585f8587Sbellard     int index_in_cluster;
110268d100e9SKevin Wolf     int ret;
1103faf575c1SFrediano Ziglio     int cur_nr_sectors; /* number of sectors in current iteration */
1104c2bdd990SFrediano Ziglio     uint64_t cluster_offset;
11053fc48d09SFrediano Ziglio     QEMUIOVector hd_qiov;
11063fc48d09SFrediano Ziglio     uint64_t bytes_done = 0;
11073fc48d09SFrediano Ziglio     uint8_t *cluster_data = NULL;
11088d2497c3SKevin Wolf     QCowL2Meta *l2meta = NULL;
1109c2271403SFrediano Ziglio 
11103cce16f4SKevin Wolf     trace_qcow2_writev_start_req(qemu_coroutine_self(), sector_num,
11113cce16f4SKevin Wolf                                  remaining_sectors);
11123cce16f4SKevin Wolf 
11133fc48d09SFrediano Ziglio     qemu_iovec_init(&hd_qiov, qiov->niov);
1114585f8587Sbellard 
11153fc48d09SFrediano Ziglio     s->cluster_cache_offset = -1; /* disable compressed cache */
11163fc48d09SFrediano Ziglio 
11173fc48d09SFrediano Ziglio     qemu_co_mutex_lock(&s->lock);
11183fc48d09SFrediano Ziglio 
11193fc48d09SFrediano Ziglio     while (remaining_sectors != 0) {
11203fc48d09SFrediano Ziglio 
1121f50f88b9SKevin Wolf         l2meta = NULL;
1122cf5c1a23SKevin Wolf 
11233cce16f4SKevin Wolf         trace_qcow2_writev_start_part(qemu_coroutine_self());
11243fc48d09SFrediano Ziglio         index_in_cluster = sector_num & (s->cluster_sectors - 1);
112516f0587eSHu Tao         cur_nr_sectors = remaining_sectors;
1126095a9c58Saliguori         if (s->crypt_method &&
112716f0587eSHu Tao             cur_nr_sectors >
112816f0587eSHu Tao             QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors - index_in_cluster) {
112916f0587eSHu Tao             cur_nr_sectors =
113016f0587eSHu Tao                 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors - index_in_cluster;
11315ebaa27eSFrediano Ziglio         }
1132095a9c58Saliguori 
11333fc48d09SFrediano Ziglio         ret = qcow2_alloc_cluster_offset(bs, sector_num << 9,
113416f0587eSHu Tao             &cur_nr_sectors, &cluster_offset, &l2meta);
1135148da7eaSKevin Wolf         if (ret < 0) {
11363fc48d09SFrediano Ziglio             goto fail;
1137148da7eaSKevin Wolf         }
1138148da7eaSKevin Wolf 
1139c2bdd990SFrediano Ziglio         assert((cluster_offset & 511) == 0);
1140148da7eaSKevin Wolf 
11413fc48d09SFrediano Ziglio         qemu_iovec_reset(&hd_qiov);
11421b093c48SMichael Tokarev         qemu_iovec_concat(&hd_qiov, qiov, bytes_done,
1143faf575c1SFrediano Ziglio             cur_nr_sectors * 512);
11446f5f060bSKevin Wolf 
1145585f8587Sbellard         if (s->crypt_method) {
11463fc48d09SFrediano Ziglio             if (!cluster_data) {
1147dea43a65SFrediano Ziglio                 cluster_data = qemu_blockalign(bs, QCOW_MAX_CRYPT_CLUSTERS *
1148095a9c58Saliguori                                                  s->cluster_size);
1149585f8587Sbellard             }
11506f5f060bSKevin Wolf 
11513fc48d09SFrediano Ziglio             assert(hd_qiov.size <=
11525ebaa27eSFrediano Ziglio                    QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
1153d5e6b161SMichael Tokarev             qemu_iovec_to_buf(&hd_qiov, 0, cluster_data, hd_qiov.size);
11546f5f060bSKevin Wolf 
11553fc48d09SFrediano Ziglio             qcow2_encrypt_sectors(s, sector_num, cluster_data,
11563fc48d09SFrediano Ziglio                 cluster_data, cur_nr_sectors, 1, &s->aes_encrypt_key);
11576f5f060bSKevin Wolf 
11583fc48d09SFrediano Ziglio             qemu_iovec_reset(&hd_qiov);
11593fc48d09SFrediano Ziglio             qemu_iovec_add(&hd_qiov, cluster_data,
1160faf575c1SFrediano Ziglio                 cur_nr_sectors * 512);
1161585f8587Sbellard         }
11626f5f060bSKevin Wolf 
1163231bb267SMax Reitz         ret = qcow2_pre_write_overlap_check(bs, 0,
1164cf93980eSMax Reitz                 cluster_offset + index_in_cluster * BDRV_SECTOR_SIZE,
1165cf93980eSMax Reitz                 cur_nr_sectors * BDRV_SECTOR_SIZE);
1166cf93980eSMax Reitz         if (ret < 0) {
1167cf93980eSMax Reitz             goto fail;
1168cf93980eSMax Reitz         }
1169cf93980eSMax Reitz 
117068d100e9SKevin Wolf         qemu_co_mutex_unlock(&s->lock);
117167a7a0ebSKevin Wolf         BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO);
11723cce16f4SKevin Wolf         trace_qcow2_writev_data(qemu_coroutine_self(),
11733cce16f4SKevin Wolf                                 (cluster_offset >> 9) + index_in_cluster);
117468d100e9SKevin Wolf         ret = bdrv_co_writev(bs->file,
1175c2bdd990SFrediano Ziglio                              (cluster_offset >> 9) + index_in_cluster,
11763fc48d09SFrediano Ziglio                              cur_nr_sectors, &hd_qiov);
117768d100e9SKevin Wolf         qemu_co_mutex_lock(&s->lock);
117868d100e9SKevin Wolf         if (ret < 0) {
11793fc48d09SFrediano Ziglio             goto fail;
1180171e3d6bSKevin Wolf         }
1181f141eafeSaliguori 
118288c6588cSKevin Wolf         while (l2meta != NULL) {
118388c6588cSKevin Wolf             QCowL2Meta *next;
118488c6588cSKevin Wolf 
1185cf5c1a23SKevin Wolf             ret = qcow2_alloc_cluster_link_l2(bs, l2meta);
1186faf575c1SFrediano Ziglio             if (ret < 0) {
11873fc48d09SFrediano Ziglio                 goto fail;
1188faf575c1SFrediano Ziglio             }
1189faf575c1SFrediano Ziglio 
11904e95314eSKevin Wolf             /* Take the request off the list of running requests */
11914e95314eSKevin Wolf             if (l2meta->nb_clusters != 0) {
11924e95314eSKevin Wolf                 QLIST_REMOVE(l2meta, next_in_flight);
11934e95314eSKevin Wolf             }
11944e95314eSKevin Wolf 
11954e95314eSKevin Wolf             qemu_co_queue_restart_all(&l2meta->dependent_requests);
11964e95314eSKevin Wolf 
119788c6588cSKevin Wolf             next = l2meta->next;
1198cf5c1a23SKevin Wolf             g_free(l2meta);
119988c6588cSKevin Wolf             l2meta = next;
1200f50f88b9SKevin Wolf         }
12010fa9131aSKevin Wolf 
12023fc48d09SFrediano Ziglio         remaining_sectors -= cur_nr_sectors;
12033fc48d09SFrediano Ziglio         sector_num += cur_nr_sectors;
12043fc48d09SFrediano Ziglio         bytes_done += cur_nr_sectors * 512;
12053cce16f4SKevin Wolf         trace_qcow2_writev_done_part(qemu_coroutine_self(), cur_nr_sectors);
12065ebaa27eSFrediano Ziglio     }
12073fc48d09SFrediano Ziglio     ret = 0;
1208faf575c1SFrediano Ziglio 
12093fc48d09SFrediano Ziglio fail:
12104e95314eSKevin Wolf     qemu_co_mutex_unlock(&s->lock);
12114e95314eSKevin Wolf 
121288c6588cSKevin Wolf     while (l2meta != NULL) {
121388c6588cSKevin Wolf         QCowL2Meta *next;
121488c6588cSKevin Wolf 
12154e95314eSKevin Wolf         if (l2meta->nb_clusters != 0) {
12164e95314eSKevin Wolf             QLIST_REMOVE(l2meta, next_in_flight);
12174e95314eSKevin Wolf         }
12184e95314eSKevin Wolf         qemu_co_queue_restart_all(&l2meta->dependent_requests);
121988c6588cSKevin Wolf 
122088c6588cSKevin Wolf         next = l2meta->next;
1221cf5c1a23SKevin Wolf         g_free(l2meta);
122288c6588cSKevin Wolf         l2meta = next;
1223cf5c1a23SKevin Wolf     }
12240fa9131aSKevin Wolf 
12253fc48d09SFrediano Ziglio     qemu_iovec_destroy(&hd_qiov);
1226dea43a65SFrediano Ziglio     qemu_vfree(cluster_data);
12273cce16f4SKevin Wolf     trace_qcow2_writev_done_req(qemu_coroutine_self(), ret);
122842496d62SKevin Wolf 
122968d100e9SKevin Wolf     return ret;
1230585f8587Sbellard }
1231585f8587Sbellard 
12327c80ab3fSJes Sorensen static void qcow2_close(BlockDriverState *bs)
1233585f8587Sbellard {
1234585f8587Sbellard     BDRVQcowState *s = bs->opaque;
12357267c094SAnthony Liguori     g_free(s->l1_table);
1236cf93980eSMax Reitz     /* else pre-write overlap checks in cache_destroy may crash */
1237cf93980eSMax Reitz     s->l1_table = NULL;
123829c1a730SKevin Wolf 
123927eb6c09SKevin Wolf     if (!(bs->open_flags & BDRV_O_INCOMING)) {
124029c1a730SKevin Wolf         qcow2_cache_flush(bs, s->l2_table_cache);
124129c1a730SKevin Wolf         qcow2_cache_flush(bs, s->refcount_block_cache);
124229c1a730SKevin Wolf 
1243c61d0004SStefan Hajnoczi         qcow2_mark_clean(bs);
124427eb6c09SKevin Wolf     }
1245c61d0004SStefan Hajnoczi 
124629c1a730SKevin Wolf     qcow2_cache_destroy(bs, s->l2_table_cache);
124729c1a730SKevin Wolf     qcow2_cache_destroy(bs, s->refcount_block_cache);
124829c1a730SKevin Wolf 
12496744cbabSKevin Wolf     g_free(s->unknown_header_fields);
125075bab85cSKevin Wolf     cleanup_unknown_header_ext(bs);
12516744cbabSKevin Wolf 
12527267c094SAnthony Liguori     g_free(s->cluster_cache);
1253dea43a65SFrediano Ziglio     qemu_vfree(s->cluster_data);
1254ed6ccf0fSKevin Wolf     qcow2_refcount_close(bs);
125528c1202bSLi Zhi Hui     qcow2_free_snapshots(bs);
1256585f8587Sbellard }
1257585f8587Sbellard 
12585a8a30dbSKevin Wolf static void qcow2_invalidate_cache(BlockDriverState *bs, Error **errp)
125906d9260fSAnthony Liguori {
126006d9260fSAnthony Liguori     BDRVQcowState *s = bs->opaque;
126106d9260fSAnthony Liguori     int flags = s->flags;
126206d9260fSAnthony Liguori     AES_KEY aes_encrypt_key;
126306d9260fSAnthony Liguori     AES_KEY aes_decrypt_key;
126406d9260fSAnthony Liguori     uint32_t crypt_method = 0;
1265acdfb480SKevin Wolf     QDict *options;
12665a8a30dbSKevin Wolf     Error *local_err = NULL;
12675a8a30dbSKevin Wolf     int ret;
126806d9260fSAnthony Liguori 
126906d9260fSAnthony Liguori     /*
127006d9260fSAnthony Liguori      * Backing files are read-only which makes all of their metadata immutable,
127106d9260fSAnthony Liguori      * that means we don't have to worry about reopening them here.
127206d9260fSAnthony Liguori      */
127306d9260fSAnthony Liguori 
127406d9260fSAnthony Liguori     if (s->crypt_method) {
127506d9260fSAnthony Liguori         crypt_method = s->crypt_method;
127606d9260fSAnthony Liguori         memcpy(&aes_encrypt_key, &s->aes_encrypt_key, sizeof(aes_encrypt_key));
127706d9260fSAnthony Liguori         memcpy(&aes_decrypt_key, &s->aes_decrypt_key, sizeof(aes_decrypt_key));
127806d9260fSAnthony Liguori     }
127906d9260fSAnthony Liguori 
128006d9260fSAnthony Liguori     qcow2_close(bs);
128106d9260fSAnthony Liguori 
12825a8a30dbSKevin Wolf     bdrv_invalidate_cache(bs->file, &local_err);
12835a8a30dbSKevin Wolf     if (local_err) {
12845a8a30dbSKevin Wolf         error_propagate(errp, local_err);
12855a8a30dbSKevin Wolf         return;
12865a8a30dbSKevin Wolf     }
12873456a8d1SKevin Wolf 
128806d9260fSAnthony Liguori     memset(s, 0, sizeof(BDRVQcowState));
1289d475e5acSKevin Wolf     options = qdict_clone_shallow(bs->options);
12905a8a30dbSKevin Wolf 
12915a8a30dbSKevin Wolf     ret = qcow2_open(bs, options, flags, &local_err);
12925a8a30dbSKevin Wolf     if (local_err) {
12935a8a30dbSKevin Wolf         error_setg(errp, "Could not reopen qcow2 layer: %s",
12945a8a30dbSKevin Wolf                    error_get_pretty(local_err));
12955a8a30dbSKevin Wolf         error_free(local_err);
12965a8a30dbSKevin Wolf         return;
12975a8a30dbSKevin Wolf     } else if (ret < 0) {
12985a8a30dbSKevin Wolf         error_setg_errno(errp, -ret, "Could not reopen qcow2 layer");
12995a8a30dbSKevin Wolf         return;
13005a8a30dbSKevin Wolf     }
1301acdfb480SKevin Wolf 
1302acdfb480SKevin Wolf     QDECREF(options);
130306d9260fSAnthony Liguori 
130406d9260fSAnthony Liguori     if (crypt_method) {
130506d9260fSAnthony Liguori         s->crypt_method = crypt_method;
130606d9260fSAnthony Liguori         memcpy(&s->aes_encrypt_key, &aes_encrypt_key, sizeof(aes_encrypt_key));
130706d9260fSAnthony Liguori         memcpy(&s->aes_decrypt_key, &aes_decrypt_key, sizeof(aes_decrypt_key));
130806d9260fSAnthony Liguori     }
130906d9260fSAnthony Liguori }
131006d9260fSAnthony Liguori 
1311e24e49e6SKevin Wolf static size_t header_ext_add(char *buf, uint32_t magic, const void *s,
1312e24e49e6SKevin Wolf     size_t len, size_t buflen)
1313756e6736SKevin Wolf {
1314e24e49e6SKevin Wolf     QCowExtension *ext_backing_fmt = (QCowExtension*) buf;
1315e24e49e6SKevin Wolf     size_t ext_len = sizeof(QCowExtension) + ((len + 7) & ~7);
1316756e6736SKevin Wolf 
1317e24e49e6SKevin Wolf     if (buflen < ext_len) {
1318756e6736SKevin Wolf         return -ENOSPC;
1319756e6736SKevin Wolf     }
1320756e6736SKevin Wolf 
1321e24e49e6SKevin Wolf     *ext_backing_fmt = (QCowExtension) {
1322e24e49e6SKevin Wolf         .magic  = cpu_to_be32(magic),
1323e24e49e6SKevin Wolf         .len    = cpu_to_be32(len),
1324e24e49e6SKevin Wolf     };
1325e24e49e6SKevin Wolf     memcpy(buf + sizeof(QCowExtension), s, len);
1326756e6736SKevin Wolf 
1327e24e49e6SKevin Wolf     return ext_len;
1328756e6736SKevin Wolf }
1329756e6736SKevin Wolf 
1330e24e49e6SKevin Wolf /*
1331e24e49e6SKevin Wolf  * Updates the qcow2 header, including the variable length parts of it, i.e.
1332e24e49e6SKevin Wolf  * the backing file name and all extensions. qcow2 was not designed to allow
1333e24e49e6SKevin Wolf  * such changes, so if we run out of space (we can only use the first cluster)
1334e24e49e6SKevin Wolf  * this function may fail.
1335e24e49e6SKevin Wolf  *
1336e24e49e6SKevin Wolf  * Returns 0 on success, -errno in error cases.
1337e24e49e6SKevin Wolf  */
1338e24e49e6SKevin Wolf int qcow2_update_header(BlockDriverState *bs)
1339e24e49e6SKevin Wolf {
1340e24e49e6SKevin Wolf     BDRVQcowState *s = bs->opaque;
1341e24e49e6SKevin Wolf     QCowHeader *header;
1342e24e49e6SKevin Wolf     char *buf;
1343e24e49e6SKevin Wolf     size_t buflen = s->cluster_size;
1344e24e49e6SKevin Wolf     int ret;
1345e24e49e6SKevin Wolf     uint64_t total_size;
1346e24e49e6SKevin Wolf     uint32_t refcount_table_clusters;
13476744cbabSKevin Wolf     size_t header_length;
134875bab85cSKevin Wolf     Qcow2UnknownHeaderExtension *uext;
1349e24e49e6SKevin Wolf 
1350e24e49e6SKevin Wolf     buf = qemu_blockalign(bs, buflen);
1351e24e49e6SKevin Wolf 
1352e24e49e6SKevin Wolf     /* Header structure */
1353e24e49e6SKevin Wolf     header = (QCowHeader*) buf;
1354e24e49e6SKevin Wolf 
1355e24e49e6SKevin Wolf     if (buflen < sizeof(*header)) {
1356e24e49e6SKevin Wolf         ret = -ENOSPC;
1357e24e49e6SKevin Wolf         goto fail;
1358756e6736SKevin Wolf     }
1359756e6736SKevin Wolf 
13606744cbabSKevin Wolf     header_length = sizeof(*header) + s->unknown_header_fields_size;
1361e24e49e6SKevin Wolf     total_size = bs->total_sectors * BDRV_SECTOR_SIZE;
1362e24e49e6SKevin Wolf     refcount_table_clusters = s->refcount_table_size >> (s->cluster_bits - 3);
1363e24e49e6SKevin Wolf 
1364e24e49e6SKevin Wolf     *header = (QCowHeader) {
13656744cbabSKevin Wolf         /* Version 2 fields */
1366e24e49e6SKevin Wolf         .magic                  = cpu_to_be32(QCOW_MAGIC),
13676744cbabSKevin Wolf         .version                = cpu_to_be32(s->qcow_version),
1368e24e49e6SKevin Wolf         .backing_file_offset    = 0,
1369e24e49e6SKevin Wolf         .backing_file_size      = 0,
1370e24e49e6SKevin Wolf         .cluster_bits           = cpu_to_be32(s->cluster_bits),
1371e24e49e6SKevin Wolf         .size                   = cpu_to_be64(total_size),
1372e24e49e6SKevin Wolf         .crypt_method           = cpu_to_be32(s->crypt_method_header),
1373e24e49e6SKevin Wolf         .l1_size                = cpu_to_be32(s->l1_size),
1374e24e49e6SKevin Wolf         .l1_table_offset        = cpu_to_be64(s->l1_table_offset),
1375e24e49e6SKevin Wolf         .refcount_table_offset  = cpu_to_be64(s->refcount_table_offset),
1376e24e49e6SKevin Wolf         .refcount_table_clusters = cpu_to_be32(refcount_table_clusters),
1377e24e49e6SKevin Wolf         .nb_snapshots           = cpu_to_be32(s->nb_snapshots),
1378e24e49e6SKevin Wolf         .snapshots_offset       = cpu_to_be64(s->snapshots_offset),
13796744cbabSKevin Wolf 
13806744cbabSKevin Wolf         /* Version 3 fields */
13816744cbabSKevin Wolf         .incompatible_features  = cpu_to_be64(s->incompatible_features),
13826744cbabSKevin Wolf         .compatible_features    = cpu_to_be64(s->compatible_features),
13836744cbabSKevin Wolf         .autoclear_features     = cpu_to_be64(s->autoclear_features),
1384b6481f37SMax Reitz         .refcount_order         = cpu_to_be32(s->refcount_order),
13856744cbabSKevin Wolf         .header_length          = cpu_to_be32(header_length),
1386e24e49e6SKevin Wolf     };
1387e24e49e6SKevin Wolf 
13886744cbabSKevin Wolf     /* For older versions, write a shorter header */
13896744cbabSKevin Wolf     switch (s->qcow_version) {
13906744cbabSKevin Wolf     case 2:
13916744cbabSKevin Wolf         ret = offsetof(QCowHeader, incompatible_features);
13926744cbabSKevin Wolf         break;
13936744cbabSKevin Wolf     case 3:
13946744cbabSKevin Wolf         ret = sizeof(*header);
13956744cbabSKevin Wolf         break;
13966744cbabSKevin Wolf     default:
1397b6c14762SJim Meyering         ret = -EINVAL;
1398b6c14762SJim Meyering         goto fail;
13996744cbabSKevin Wolf     }
14006744cbabSKevin Wolf 
14016744cbabSKevin Wolf     buf += ret;
14026744cbabSKevin Wolf     buflen -= ret;
14036744cbabSKevin Wolf     memset(buf, 0, buflen);
14046744cbabSKevin Wolf 
14056744cbabSKevin Wolf     /* Preserve any unknown field in the header */
14066744cbabSKevin Wolf     if (s->unknown_header_fields_size) {
14076744cbabSKevin Wolf         if (buflen < s->unknown_header_fields_size) {
14086744cbabSKevin Wolf             ret = -ENOSPC;
14096744cbabSKevin Wolf             goto fail;
14106744cbabSKevin Wolf         }
14116744cbabSKevin Wolf 
14126744cbabSKevin Wolf         memcpy(buf, s->unknown_header_fields, s->unknown_header_fields_size);
14136744cbabSKevin Wolf         buf += s->unknown_header_fields_size;
14146744cbabSKevin Wolf         buflen -= s->unknown_header_fields_size;
14156744cbabSKevin Wolf     }
1416e24e49e6SKevin Wolf 
1417e24e49e6SKevin Wolf     /* Backing file format header extension */
1418e24e49e6SKevin Wolf     if (*bs->backing_format) {
1419e24e49e6SKevin Wolf         ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BACKING_FORMAT,
1420e24e49e6SKevin Wolf                              bs->backing_format, strlen(bs->backing_format),
1421e24e49e6SKevin Wolf                              buflen);
1422756e6736SKevin Wolf         if (ret < 0) {
1423756e6736SKevin Wolf             goto fail;
1424756e6736SKevin Wolf         }
1425756e6736SKevin Wolf 
1426e24e49e6SKevin Wolf         buf += ret;
1427e24e49e6SKevin Wolf         buflen -= ret;
1428e24e49e6SKevin Wolf     }
1429756e6736SKevin Wolf 
1430cfcc4c62SKevin Wolf     /* Feature table */
1431cfcc4c62SKevin Wolf     Qcow2Feature features[] = {
1432c61d0004SStefan Hajnoczi         {
1433c61d0004SStefan Hajnoczi             .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
1434c61d0004SStefan Hajnoczi             .bit  = QCOW2_INCOMPAT_DIRTY_BITNR,
1435c61d0004SStefan Hajnoczi             .name = "dirty bit",
1436c61d0004SStefan Hajnoczi         },
1437bfe8043eSStefan Hajnoczi         {
143869c98726SMax Reitz             .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
143969c98726SMax Reitz             .bit  = QCOW2_INCOMPAT_CORRUPT_BITNR,
144069c98726SMax Reitz             .name = "corrupt bit",
144169c98726SMax Reitz         },
144269c98726SMax Reitz         {
1443bfe8043eSStefan Hajnoczi             .type = QCOW2_FEAT_TYPE_COMPATIBLE,
1444bfe8043eSStefan Hajnoczi             .bit  = QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR,
1445bfe8043eSStefan Hajnoczi             .name = "lazy refcounts",
1446bfe8043eSStefan Hajnoczi         },
1447cfcc4c62SKevin Wolf     };
1448cfcc4c62SKevin Wolf 
1449cfcc4c62SKevin Wolf     ret = header_ext_add(buf, QCOW2_EXT_MAGIC_FEATURE_TABLE,
1450cfcc4c62SKevin Wolf                          features, sizeof(features), buflen);
1451cfcc4c62SKevin Wolf     if (ret < 0) {
1452cfcc4c62SKevin Wolf         goto fail;
1453cfcc4c62SKevin Wolf     }
1454cfcc4c62SKevin Wolf     buf += ret;
1455cfcc4c62SKevin Wolf     buflen -= ret;
1456cfcc4c62SKevin Wolf 
145775bab85cSKevin Wolf     /* Keep unknown header extensions */
145875bab85cSKevin Wolf     QLIST_FOREACH(uext, &s->unknown_header_ext, next) {
145975bab85cSKevin Wolf         ret = header_ext_add(buf, uext->magic, uext->data, uext->len, buflen);
146075bab85cSKevin Wolf         if (ret < 0) {
146175bab85cSKevin Wolf             goto fail;
146275bab85cSKevin Wolf         }
146375bab85cSKevin Wolf 
146475bab85cSKevin Wolf         buf += ret;
146575bab85cSKevin Wolf         buflen -= ret;
146675bab85cSKevin Wolf     }
146775bab85cSKevin Wolf 
1468e24e49e6SKevin Wolf     /* End of header extensions */
1469e24e49e6SKevin Wolf     ret = header_ext_add(buf, QCOW2_EXT_MAGIC_END, NULL, 0, buflen);
1470756e6736SKevin Wolf     if (ret < 0) {
1471756e6736SKevin Wolf         goto fail;
1472756e6736SKevin Wolf     }
1473756e6736SKevin Wolf 
1474e24e49e6SKevin Wolf     buf += ret;
1475e24e49e6SKevin Wolf     buflen -= ret;
1476e24e49e6SKevin Wolf 
1477e24e49e6SKevin Wolf     /* Backing file name */
1478e24e49e6SKevin Wolf     if (*bs->backing_file) {
1479e24e49e6SKevin Wolf         size_t backing_file_len = strlen(bs->backing_file);
1480e24e49e6SKevin Wolf 
1481e24e49e6SKevin Wolf         if (buflen < backing_file_len) {
1482e24e49e6SKevin Wolf             ret = -ENOSPC;
1483e24e49e6SKevin Wolf             goto fail;
1484e24e49e6SKevin Wolf         }
1485e24e49e6SKevin Wolf 
148600ea1881SJim Meyering         /* Using strncpy is ok here, since buf is not NUL-terminated. */
1487e24e49e6SKevin Wolf         strncpy(buf, bs->backing_file, buflen);
1488e24e49e6SKevin Wolf 
1489e24e49e6SKevin Wolf         header->backing_file_offset = cpu_to_be64(buf - ((char*) header));
1490e24e49e6SKevin Wolf         header->backing_file_size   = cpu_to_be32(backing_file_len);
1491e24e49e6SKevin Wolf     }
1492e24e49e6SKevin Wolf 
1493e24e49e6SKevin Wolf     /* Write the new header */
1494e24e49e6SKevin Wolf     ret = bdrv_pwrite(bs->file, 0, header, s->cluster_size);
1495756e6736SKevin Wolf     if (ret < 0) {
1496756e6736SKevin Wolf         goto fail;
1497756e6736SKevin Wolf     }
1498756e6736SKevin Wolf 
1499756e6736SKevin Wolf     ret = 0;
1500756e6736SKevin Wolf fail:
1501e24e49e6SKevin Wolf     qemu_vfree(header);
1502756e6736SKevin Wolf     return ret;
1503756e6736SKevin Wolf }
1504756e6736SKevin Wolf 
1505756e6736SKevin Wolf static int qcow2_change_backing_file(BlockDriverState *bs,
1506756e6736SKevin Wolf     const char *backing_file, const char *backing_fmt)
1507756e6736SKevin Wolf {
1508e24e49e6SKevin Wolf     pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
1509e24e49e6SKevin Wolf     pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
1510e24e49e6SKevin Wolf 
1511e24e49e6SKevin Wolf     return qcow2_update_header(bs);
1512756e6736SKevin Wolf }
1513756e6736SKevin Wolf 
1514a35e1c17SKevin Wolf static int preallocate(BlockDriverState *bs)
1515a35e1c17SKevin Wolf {
1516a35e1c17SKevin Wolf     uint64_t nb_sectors;
1517a35e1c17SKevin Wolf     uint64_t offset;
1518060bee89SKevin Wolf     uint64_t host_offset = 0;
1519a35e1c17SKevin Wolf     int num;
1520148da7eaSKevin Wolf     int ret;
1521f50f88b9SKevin Wolf     QCowL2Meta *meta;
1522a35e1c17SKevin Wolf 
15237c2bbf4aSHu Tao     nb_sectors = bdrv_getlength(bs) >> BDRV_SECTOR_BITS;
1524a35e1c17SKevin Wolf     offset = 0;
1525a35e1c17SKevin Wolf 
1526a35e1c17SKevin Wolf     while (nb_sectors) {
15277c2bbf4aSHu Tao         num = MIN(nb_sectors, INT_MAX >> BDRV_SECTOR_BITS);
152816f0587eSHu Tao         ret = qcow2_alloc_cluster_offset(bs, offset, &num,
1529060bee89SKevin Wolf                                          &host_offset, &meta);
1530148da7eaSKevin Wolf         if (ret < 0) {
153119dbcbf7SKevin Wolf             return ret;
1532a35e1c17SKevin Wolf         }
1533a35e1c17SKevin Wolf 
15347c2bbf4aSHu Tao         if (meta != NULL) {
1535f50f88b9SKevin Wolf             ret = qcow2_alloc_cluster_link_l2(bs, meta);
153619dbcbf7SKevin Wolf             if (ret < 0) {
15377c2bbf4aSHu Tao                 qcow2_free_any_clusters(bs, meta->alloc_offset,
15387c2bbf4aSHu Tao                                         meta->nb_clusters, QCOW2_DISCARD_NEVER);
153919dbcbf7SKevin Wolf                 return ret;
1540a35e1c17SKevin Wolf             }
1541a35e1c17SKevin Wolf 
15427c2bbf4aSHu Tao             /* There are no dependent requests, but we need to remove our
15437c2bbf4aSHu Tao              * request from the list of in-flight requests */
15444e95314eSKevin Wolf             QLIST_REMOVE(meta, next_in_flight);
1545f50f88b9SKevin Wolf         }
1546f214978aSKevin Wolf 
1547a35e1c17SKevin Wolf         /* TODO Preallocate data if requested */
1548a35e1c17SKevin Wolf 
1549a35e1c17SKevin Wolf         nb_sectors -= num;
15507c2bbf4aSHu Tao         offset += num << BDRV_SECTOR_BITS;
1551a35e1c17SKevin Wolf     }
1552a35e1c17SKevin Wolf 
1553a35e1c17SKevin Wolf     /*
1554a35e1c17SKevin Wolf      * It is expected that the image file is large enough to actually contain
1555a35e1c17SKevin Wolf      * all of the allocated clusters (otherwise we get failing reads after
1556a35e1c17SKevin Wolf      * EOF). Extend the image to the last allocated sector.
1557a35e1c17SKevin Wolf      */
1558060bee89SKevin Wolf     if (host_offset != 0) {
15597c2bbf4aSHu Tao         uint8_t buf[BDRV_SECTOR_SIZE];
15607c2bbf4aSHu Tao         memset(buf, 0, BDRV_SECTOR_SIZE);
15617c2bbf4aSHu Tao         ret = bdrv_write(bs->file, (host_offset >> BDRV_SECTOR_BITS) + num - 1,
15627c2bbf4aSHu Tao                          buf, 1);
156319dbcbf7SKevin Wolf         if (ret < 0) {
156419dbcbf7SKevin Wolf             return ret;
156519dbcbf7SKevin Wolf         }
1566a35e1c17SKevin Wolf     }
1567a35e1c17SKevin Wolf 
1568a35e1c17SKevin Wolf     return 0;
1569a35e1c17SKevin Wolf }
1570a35e1c17SKevin Wolf 
15717c80ab3fSJes Sorensen static int qcow2_create2(const char *filename, int64_t total_size,
1572a9420734SKevin Wolf                          const char *backing_file, const char *backing_format,
1573a9420734SKevin Wolf                          int flags, size_t cluster_size, int prealloc,
15743ef6c40aSMax Reitz                          QEMUOptionParameter *options, int version,
15753ef6c40aSMax Reitz                          Error **errp)
1576a9420734SKevin Wolf {
15779b2260cbSDong Xu Wang     /* Calculate cluster_bits */
1578a9420734SKevin Wolf     int cluster_bits;
1579a9420734SKevin Wolf     cluster_bits = ffs(cluster_size) - 1;
1580a9420734SKevin Wolf     if (cluster_bits < MIN_CLUSTER_BITS || cluster_bits > MAX_CLUSTER_BITS ||
1581a9420734SKevin Wolf         (1 << cluster_bits) != cluster_size)
1582a9420734SKevin Wolf     {
15833ef6c40aSMax Reitz         error_setg(errp, "Cluster size must be a power of two between %d and "
15843ef6c40aSMax Reitz                    "%dk", 1 << MIN_CLUSTER_BITS, 1 << (MAX_CLUSTER_BITS - 10));
1585a9420734SKevin Wolf         return -EINVAL;
1586a9420734SKevin Wolf     }
1587a9420734SKevin Wolf 
1588a9420734SKevin Wolf     /*
1589a9420734SKevin Wolf      * Open the image file and write a minimal qcow2 header.
1590a9420734SKevin Wolf      *
1591a9420734SKevin Wolf      * We keep things simple and start with a zero-sized image. We also
1592a9420734SKevin Wolf      * do without refcount blocks or a L1 table for now. We'll fix the
1593a9420734SKevin Wolf      * inconsistency later.
1594a9420734SKevin Wolf      *
1595a9420734SKevin Wolf      * We do need a refcount table because growing the refcount table means
1596a9420734SKevin Wolf      * allocating two new refcount blocks - the seconds of which would be at
1597a9420734SKevin Wolf      * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
1598a9420734SKevin Wolf      * size for any qcow2 image.
1599a9420734SKevin Wolf      */
1600a9420734SKevin Wolf     BlockDriverState* bs;
1601f8413b3cSKevin Wolf     QCowHeader *header;
1602a9420734SKevin Wolf     uint8_t* refcount_table;
16033ef6c40aSMax Reitz     Error *local_err = NULL;
1604a9420734SKevin Wolf     int ret;
1605a9420734SKevin Wolf 
16063ef6c40aSMax Reitz     ret = bdrv_create_file(filename, options, &local_err);
1607a9420734SKevin Wolf     if (ret < 0) {
16083ef6c40aSMax Reitz         error_propagate(errp, local_err);
1609a9420734SKevin Wolf         return ret;
1610a9420734SKevin Wolf     }
1611a9420734SKevin Wolf 
16122e40134bSMax Reitz     bs = NULL;
16132e40134bSMax Reitz     ret = bdrv_open(&bs, filename, NULL, NULL, BDRV_O_RDWR | BDRV_O_PROTOCOL,
16142e40134bSMax Reitz                     NULL, &local_err);
1615a9420734SKevin Wolf     if (ret < 0) {
16163ef6c40aSMax Reitz         error_propagate(errp, local_err);
1617a9420734SKevin Wolf         return ret;
1618a9420734SKevin Wolf     }
1619a9420734SKevin Wolf 
1620a9420734SKevin Wolf     /* Write the header */
1621f8413b3cSKevin Wolf     QEMU_BUILD_BUG_ON((1 << MIN_CLUSTER_BITS) < sizeof(*header));
1622f8413b3cSKevin Wolf     header = g_malloc0(cluster_size);
1623f8413b3cSKevin Wolf     *header = (QCowHeader) {
1624f8413b3cSKevin Wolf         .magic                      = cpu_to_be32(QCOW_MAGIC),
1625f8413b3cSKevin Wolf         .version                    = cpu_to_be32(version),
1626f8413b3cSKevin Wolf         .cluster_bits               = cpu_to_be32(cluster_bits),
1627f8413b3cSKevin Wolf         .size                       = cpu_to_be64(0),
1628f8413b3cSKevin Wolf         .l1_table_offset            = cpu_to_be64(0),
1629f8413b3cSKevin Wolf         .l1_size                    = cpu_to_be32(0),
1630f8413b3cSKevin Wolf         .refcount_table_offset      = cpu_to_be64(cluster_size),
1631f8413b3cSKevin Wolf         .refcount_table_clusters    = cpu_to_be32(1),
1632f8413b3cSKevin Wolf         .refcount_order             = cpu_to_be32(3 + REFCOUNT_SHIFT),
1633f8413b3cSKevin Wolf         .header_length              = cpu_to_be32(sizeof(*header)),
1634f8413b3cSKevin Wolf     };
1635a9420734SKevin Wolf 
1636a9420734SKevin Wolf     if (flags & BLOCK_FLAG_ENCRYPT) {
1637f8413b3cSKevin Wolf         header->crypt_method = cpu_to_be32(QCOW_CRYPT_AES);
1638a9420734SKevin Wolf     } else {
1639f8413b3cSKevin Wolf         header->crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
1640a9420734SKevin Wolf     }
1641a9420734SKevin Wolf 
1642bfe8043eSStefan Hajnoczi     if (flags & BLOCK_FLAG_LAZY_REFCOUNTS) {
1643f8413b3cSKevin Wolf         header->compatible_features |=
1644bfe8043eSStefan Hajnoczi             cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS);
1645bfe8043eSStefan Hajnoczi     }
1646bfe8043eSStefan Hajnoczi 
1647f8413b3cSKevin Wolf     ret = bdrv_pwrite(bs, 0, header, cluster_size);
1648f8413b3cSKevin Wolf     g_free(header);
1649a9420734SKevin Wolf     if (ret < 0) {
16503ef6c40aSMax Reitz         error_setg_errno(errp, -ret, "Could not write qcow2 header");
1651a9420734SKevin Wolf         goto out;
1652a9420734SKevin Wolf     }
1653a9420734SKevin Wolf 
1654a9420734SKevin Wolf     /* Write an empty refcount table */
16557267c094SAnthony Liguori     refcount_table = g_malloc0(cluster_size);
1656a9420734SKevin Wolf     ret = bdrv_pwrite(bs, cluster_size, refcount_table, cluster_size);
16577267c094SAnthony Liguori     g_free(refcount_table);
1658a9420734SKevin Wolf 
1659a9420734SKevin Wolf     if (ret < 0) {
16603ef6c40aSMax Reitz         error_setg_errno(errp, -ret, "Could not write refcount table");
1661a9420734SKevin Wolf         goto out;
1662a9420734SKevin Wolf     }
1663a9420734SKevin Wolf 
1664f67503e5SMax Reitz     bdrv_unref(bs);
1665f67503e5SMax Reitz     bs = NULL;
1666a9420734SKevin Wolf 
1667a9420734SKevin Wolf     /*
1668a9420734SKevin Wolf      * And now open the image and make it consistent first (i.e. increase the
1669a9420734SKevin Wolf      * refcount of the cluster that is occupied by the header and the refcount
1670a9420734SKevin Wolf      * table)
1671a9420734SKevin Wolf      */
1672a9420734SKevin Wolf     BlockDriver* drv = bdrv_find_format("qcow2");
1673a9420734SKevin Wolf     assert(drv != NULL);
1674ddf5636dSMax Reitz     ret = bdrv_open(&bs, filename, NULL, NULL,
16753ef6c40aSMax Reitz         BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_NO_FLUSH, drv, &local_err);
1676a9420734SKevin Wolf     if (ret < 0) {
16773ef6c40aSMax Reitz         error_propagate(errp, local_err);
1678a9420734SKevin Wolf         goto out;
1679a9420734SKevin Wolf     }
1680a9420734SKevin Wolf 
1681a9420734SKevin Wolf     ret = qcow2_alloc_clusters(bs, 2 * cluster_size);
1682a9420734SKevin Wolf     if (ret < 0) {
16833ef6c40aSMax Reitz         error_setg_errno(errp, -ret, "Could not allocate clusters for qcow2 "
16843ef6c40aSMax Reitz                          "header and refcount table");
1685a9420734SKevin Wolf         goto out;
1686a9420734SKevin Wolf 
1687a9420734SKevin Wolf     } else if (ret != 0) {
1688a9420734SKevin Wolf         error_report("Huh, first cluster in empty image is already in use?");
1689a9420734SKevin Wolf         abort();
1690a9420734SKevin Wolf     }
1691a9420734SKevin Wolf 
1692a9420734SKevin Wolf     /* Okay, now that we have a valid image, let's give it the right size */
1693a9420734SKevin Wolf     ret = bdrv_truncate(bs, total_size * BDRV_SECTOR_SIZE);
1694a9420734SKevin Wolf     if (ret < 0) {
16953ef6c40aSMax Reitz         error_setg_errno(errp, -ret, "Could not resize image");
1696a9420734SKevin Wolf         goto out;
1697a9420734SKevin Wolf     }
1698a9420734SKevin Wolf 
1699a9420734SKevin Wolf     /* Want a backing file? There you go.*/
1700a9420734SKevin Wolf     if (backing_file) {
1701a9420734SKevin Wolf         ret = bdrv_change_backing_file(bs, backing_file, backing_format);
1702a9420734SKevin Wolf         if (ret < 0) {
17033ef6c40aSMax Reitz             error_setg_errno(errp, -ret, "Could not assign backing file '%s' "
17043ef6c40aSMax Reitz                              "with format '%s'", backing_file, backing_format);
1705a9420734SKevin Wolf             goto out;
1706a9420734SKevin Wolf         }
1707a9420734SKevin Wolf     }
1708a9420734SKevin Wolf 
1709a9420734SKevin Wolf     /* And if we're supposed to preallocate metadata, do that now */
1710a9420734SKevin Wolf     if (prealloc) {
171115552c4aSZhi Yong Wu         BDRVQcowState *s = bs->opaque;
171215552c4aSZhi Yong Wu         qemu_co_mutex_lock(&s->lock);
1713a9420734SKevin Wolf         ret = preallocate(bs);
171415552c4aSZhi Yong Wu         qemu_co_mutex_unlock(&s->lock);
1715a9420734SKevin Wolf         if (ret < 0) {
17163ef6c40aSMax Reitz             error_setg_errno(errp, -ret, "Could not preallocate metadata");
1717a9420734SKevin Wolf             goto out;
1718a9420734SKevin Wolf         }
1719a9420734SKevin Wolf     }
1720a9420734SKevin Wolf 
1721f67503e5SMax Reitz     bdrv_unref(bs);
1722f67503e5SMax Reitz     bs = NULL;
1723ba2ab2f2SMax Reitz 
1724ba2ab2f2SMax Reitz     /* Reopen the image without BDRV_O_NO_FLUSH to flush it before returning */
1725ddf5636dSMax Reitz     ret = bdrv_open(&bs, filename, NULL, NULL,
1726c9fbb99dSKevin Wolf                     BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_NO_BACKING,
1727c9fbb99dSKevin Wolf                     drv, &local_err);
172884d18f06SMarkus Armbruster     if (local_err) {
1729ba2ab2f2SMax Reitz         error_propagate(errp, local_err);
1730ba2ab2f2SMax Reitz         goto out;
1731ba2ab2f2SMax Reitz     }
1732ba2ab2f2SMax Reitz 
1733a9420734SKevin Wolf     ret = 0;
1734a9420734SKevin Wolf out:
1735f67503e5SMax Reitz     if (bs) {
17364f6fd349SFam Zheng         bdrv_unref(bs);
1737f67503e5SMax Reitz     }
1738a9420734SKevin Wolf     return ret;
1739a9420734SKevin Wolf }
1740de5f3f40SKevin Wolf 
1741d5124c00SMax Reitz static int qcow2_create(const char *filename, QEMUOptionParameter *options,
1742d5124c00SMax Reitz                         Error **errp)
1743de5f3f40SKevin Wolf {
1744de5f3f40SKevin Wolf     const char *backing_file = NULL;
1745de5f3f40SKevin Wolf     const char *backing_fmt = NULL;
1746de5f3f40SKevin Wolf     uint64_t sectors = 0;
1747de5f3f40SKevin Wolf     int flags = 0;
174899cce9faSKevin Wolf     size_t cluster_size = DEFAULT_CLUSTER_SIZE;
1749de5f3f40SKevin Wolf     int prealloc = 0;
17508ad1898cSKevin Wolf     int version = 3;
17513ef6c40aSMax Reitz     Error *local_err = NULL;
17523ef6c40aSMax Reitz     int ret;
1753de5f3f40SKevin Wolf 
1754de5f3f40SKevin Wolf     /* Read out options */
1755de5f3f40SKevin Wolf     while (options && options->name) {
1756de5f3f40SKevin Wolf         if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
1757de5f3f40SKevin Wolf             sectors = options->value.n / 512;
1758de5f3f40SKevin Wolf         } else if (!strcmp(options->name, BLOCK_OPT_BACKING_FILE)) {
1759de5f3f40SKevin Wolf             backing_file = options->value.s;
1760de5f3f40SKevin Wolf         } else if (!strcmp(options->name, BLOCK_OPT_BACKING_FMT)) {
1761de5f3f40SKevin Wolf             backing_fmt = options->value.s;
1762de5f3f40SKevin Wolf         } else if (!strcmp(options->name, BLOCK_OPT_ENCRYPT)) {
1763de5f3f40SKevin Wolf             flags |= options->value.n ? BLOCK_FLAG_ENCRYPT : 0;
1764de5f3f40SKevin Wolf         } else if (!strcmp(options->name, BLOCK_OPT_CLUSTER_SIZE)) {
1765de5f3f40SKevin Wolf             if (options->value.n) {
1766de5f3f40SKevin Wolf                 cluster_size = options->value.n;
1767de5f3f40SKevin Wolf             }
1768de5f3f40SKevin Wolf         } else if (!strcmp(options->name, BLOCK_OPT_PREALLOC)) {
1769de5f3f40SKevin Wolf             if (!options->value.s || !strcmp(options->value.s, "off")) {
1770de5f3f40SKevin Wolf                 prealloc = 0;
1771de5f3f40SKevin Wolf             } else if (!strcmp(options->value.s, "metadata")) {
1772de5f3f40SKevin Wolf                 prealloc = 1;
1773de5f3f40SKevin Wolf             } else {
17743ef6c40aSMax Reitz                 error_setg(errp, "Invalid preallocation mode: '%s'",
1775de5f3f40SKevin Wolf                            options->value.s);
1776de5f3f40SKevin Wolf                 return -EINVAL;
1777de5f3f40SKevin Wolf             }
17786744cbabSKevin Wolf         } else if (!strcmp(options->name, BLOCK_OPT_COMPAT_LEVEL)) {
17799117b477SKevin Wolf             if (!options->value.s) {
17809117b477SKevin Wolf                 /* keep the default */
17819117b477SKevin Wolf             } else if (!strcmp(options->value.s, "0.10")) {
17826744cbabSKevin Wolf                 version = 2;
17836744cbabSKevin Wolf             } else if (!strcmp(options->value.s, "1.1")) {
17846744cbabSKevin Wolf                 version = 3;
17856744cbabSKevin Wolf             } else {
17863ef6c40aSMax Reitz                 error_setg(errp, "Invalid compatibility level: '%s'",
17876744cbabSKevin Wolf                            options->value.s);
17886744cbabSKevin Wolf                 return -EINVAL;
17896744cbabSKevin Wolf             }
1790bfe8043eSStefan Hajnoczi         } else if (!strcmp(options->name, BLOCK_OPT_LAZY_REFCOUNTS)) {
1791bfe8043eSStefan Hajnoczi             flags |= options->value.n ? BLOCK_FLAG_LAZY_REFCOUNTS : 0;
1792de5f3f40SKevin Wolf         }
1793de5f3f40SKevin Wolf         options++;
1794de5f3f40SKevin Wolf     }
1795de5f3f40SKevin Wolf 
1796de5f3f40SKevin Wolf     if (backing_file && prealloc) {
17973ef6c40aSMax Reitz         error_setg(errp, "Backing file and preallocation cannot be used at "
17983ef6c40aSMax Reitz                    "the same time");
1799de5f3f40SKevin Wolf         return -EINVAL;
1800de5f3f40SKevin Wolf     }
1801de5f3f40SKevin Wolf 
1802bfe8043eSStefan Hajnoczi     if (version < 3 && (flags & BLOCK_FLAG_LAZY_REFCOUNTS)) {
18033ef6c40aSMax Reitz         error_setg(errp, "Lazy refcounts only supported with compatibility "
18043ef6c40aSMax Reitz                    "level 1.1 and above (use compat=1.1 or greater)");
1805bfe8043eSStefan Hajnoczi         return -EINVAL;
1806bfe8043eSStefan Hajnoczi     }
1807bfe8043eSStefan Hajnoczi 
18083ef6c40aSMax Reitz     ret = qcow2_create2(filename, sectors, backing_file, backing_fmt, flags,
18093ef6c40aSMax Reitz                         cluster_size, prealloc, options, version, &local_err);
181084d18f06SMarkus Armbruster     if (local_err) {
18113ef6c40aSMax Reitz         error_propagate(errp, local_err);
18123ef6c40aSMax Reitz     }
18133ef6c40aSMax Reitz     return ret;
1814de5f3f40SKevin Wolf }
1815de5f3f40SKevin Wolf 
1816621f0589SKevin Wolf static coroutine_fn int qcow2_co_write_zeroes(BlockDriverState *bs,
1817aa7bfbffSPeter Lieven     int64_t sector_num, int nb_sectors, BdrvRequestFlags flags)
1818621f0589SKevin Wolf {
1819621f0589SKevin Wolf     int ret;
1820621f0589SKevin Wolf     BDRVQcowState *s = bs->opaque;
1821621f0589SKevin Wolf 
1822621f0589SKevin Wolf     /* Emulate misaligned zero writes */
1823621f0589SKevin Wolf     if (sector_num % s->cluster_sectors || nb_sectors % s->cluster_sectors) {
1824621f0589SKevin Wolf         return -ENOTSUP;
1825621f0589SKevin Wolf     }
1826621f0589SKevin Wolf 
1827621f0589SKevin Wolf     /* Whatever is left can use real zero clusters */
1828621f0589SKevin Wolf     qemu_co_mutex_lock(&s->lock);
1829621f0589SKevin Wolf     ret = qcow2_zero_clusters(bs, sector_num << BDRV_SECTOR_BITS,
1830621f0589SKevin Wolf         nb_sectors);
1831621f0589SKevin Wolf     qemu_co_mutex_unlock(&s->lock);
1832621f0589SKevin Wolf 
1833621f0589SKevin Wolf     return ret;
1834621f0589SKevin Wolf }
1835621f0589SKevin Wolf 
18366db39ae2SPaolo Bonzini static coroutine_fn int qcow2_co_discard(BlockDriverState *bs,
18376db39ae2SPaolo Bonzini     int64_t sector_num, int nb_sectors)
18385ea929e3SKevin Wolf {
18396db39ae2SPaolo Bonzini     int ret;
18406db39ae2SPaolo Bonzini     BDRVQcowState *s = bs->opaque;
18416db39ae2SPaolo Bonzini 
18426db39ae2SPaolo Bonzini     qemu_co_mutex_lock(&s->lock);
18436db39ae2SPaolo Bonzini     ret = qcow2_discard_clusters(bs, sector_num << BDRV_SECTOR_BITS,
1844670df5e3SKevin Wolf         nb_sectors, QCOW2_DISCARD_REQUEST);
18456db39ae2SPaolo Bonzini     qemu_co_mutex_unlock(&s->lock);
18466db39ae2SPaolo Bonzini     return ret;
18475ea929e3SKevin Wolf }
18485ea929e3SKevin Wolf 
1849419b19d9SStefan Hajnoczi static int qcow2_truncate(BlockDriverState *bs, int64_t offset)
1850419b19d9SStefan Hajnoczi {
1851419b19d9SStefan Hajnoczi     BDRVQcowState *s = bs->opaque;
18522cf7cfa1SKevin Wolf     int64_t new_l1_size;
18532cf7cfa1SKevin Wolf     int ret;
1854419b19d9SStefan Hajnoczi 
1855419b19d9SStefan Hajnoczi     if (offset & 511) {
1856259b2173SKevin Wolf         error_report("The new size must be a multiple of 512");
1857419b19d9SStefan Hajnoczi         return -EINVAL;
1858419b19d9SStefan Hajnoczi     }
1859419b19d9SStefan Hajnoczi 
1860419b19d9SStefan Hajnoczi     /* cannot proceed if image has snapshots */
1861419b19d9SStefan Hajnoczi     if (s->nb_snapshots) {
1862259b2173SKevin Wolf         error_report("Can't resize an image which has snapshots");
1863419b19d9SStefan Hajnoczi         return -ENOTSUP;
1864419b19d9SStefan Hajnoczi     }
1865419b19d9SStefan Hajnoczi 
1866419b19d9SStefan Hajnoczi     /* shrinking is currently not supported */
1867419b19d9SStefan Hajnoczi     if (offset < bs->total_sectors * 512) {
1868259b2173SKevin Wolf         error_report("qcow2 doesn't support shrinking images yet");
1869419b19d9SStefan Hajnoczi         return -ENOTSUP;
1870419b19d9SStefan Hajnoczi     }
1871419b19d9SStefan Hajnoczi 
1872419b19d9SStefan Hajnoczi     new_l1_size = size_to_l1(s, offset);
187372893756SStefan Hajnoczi     ret = qcow2_grow_l1_table(bs, new_l1_size, true);
1874419b19d9SStefan Hajnoczi     if (ret < 0) {
1875419b19d9SStefan Hajnoczi         return ret;
1876419b19d9SStefan Hajnoczi     }
1877419b19d9SStefan Hajnoczi 
1878419b19d9SStefan Hajnoczi     /* write updated header.size */
1879419b19d9SStefan Hajnoczi     offset = cpu_to_be64(offset);
18808b3b7206SKevin Wolf     ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, size),
1881419b19d9SStefan Hajnoczi                            &offset, sizeof(uint64_t));
1882419b19d9SStefan Hajnoczi     if (ret < 0) {
1883419b19d9SStefan Hajnoczi         return ret;
1884419b19d9SStefan Hajnoczi     }
1885419b19d9SStefan Hajnoczi 
1886419b19d9SStefan Hajnoczi     s->l1_vm_state_index = new_l1_size;
1887419b19d9SStefan Hajnoczi     return 0;
1888419b19d9SStefan Hajnoczi }
1889419b19d9SStefan Hajnoczi 
189020d97356SBlue Swirl /* XXX: put compressed sectors first, then all the cluster aligned
189120d97356SBlue Swirl    tables to avoid losing bytes in alignment */
18927c80ab3fSJes Sorensen static int qcow2_write_compressed(BlockDriverState *bs, int64_t sector_num,
189320d97356SBlue Swirl                                   const uint8_t *buf, int nb_sectors)
189420d97356SBlue Swirl {
189520d97356SBlue Swirl     BDRVQcowState *s = bs->opaque;
189620d97356SBlue Swirl     z_stream strm;
189720d97356SBlue Swirl     int ret, out_len;
189820d97356SBlue Swirl     uint8_t *out_buf;
189920d97356SBlue Swirl     uint64_t cluster_offset;
190020d97356SBlue Swirl 
190120d97356SBlue Swirl     if (nb_sectors == 0) {
190220d97356SBlue Swirl         /* align end of file to a sector boundary to ease reading with
190320d97356SBlue Swirl            sector based I/Os */
190466f82ceeSKevin Wolf         cluster_offset = bdrv_getlength(bs->file);
190520d97356SBlue Swirl         cluster_offset = (cluster_offset + 511) & ~511;
190666f82ceeSKevin Wolf         bdrv_truncate(bs->file, cluster_offset);
190720d97356SBlue Swirl         return 0;
190820d97356SBlue Swirl     }
190920d97356SBlue Swirl 
1910f4d38befSStefan Hajnoczi     if (nb_sectors != s->cluster_sectors) {
1911f4d38befSStefan Hajnoczi         ret = -EINVAL;
1912f4d38befSStefan Hajnoczi 
1913f4d38befSStefan Hajnoczi         /* Zero-pad last write if image size is not cluster aligned */
1914f4d38befSStefan Hajnoczi         if (sector_num + nb_sectors == bs->total_sectors &&
1915f4d38befSStefan Hajnoczi             nb_sectors < s->cluster_sectors) {
1916f4d38befSStefan Hajnoczi             uint8_t *pad_buf = qemu_blockalign(bs, s->cluster_size);
1917f4d38befSStefan Hajnoczi             memset(pad_buf, 0, s->cluster_size);
1918f4d38befSStefan Hajnoczi             memcpy(pad_buf, buf, nb_sectors * BDRV_SECTOR_SIZE);
1919f4d38befSStefan Hajnoczi             ret = qcow2_write_compressed(bs, sector_num,
1920f4d38befSStefan Hajnoczi                                          pad_buf, s->cluster_sectors);
1921f4d38befSStefan Hajnoczi             qemu_vfree(pad_buf);
1922f4d38befSStefan Hajnoczi         }
1923f4d38befSStefan Hajnoczi         return ret;
1924f4d38befSStefan Hajnoczi     }
192520d97356SBlue Swirl 
19267267c094SAnthony Liguori     out_buf = g_malloc(s->cluster_size + (s->cluster_size / 1000) + 128);
192720d97356SBlue Swirl 
192820d97356SBlue Swirl     /* best compression, small window, no zlib header */
192920d97356SBlue Swirl     memset(&strm, 0, sizeof(strm));
193020d97356SBlue Swirl     ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
193120d97356SBlue Swirl                        Z_DEFLATED, -12,
193220d97356SBlue Swirl                        9, Z_DEFAULT_STRATEGY);
193320d97356SBlue Swirl     if (ret != 0) {
19348f1efd00SKevin Wolf         ret = -EINVAL;
19358f1efd00SKevin Wolf         goto fail;
193620d97356SBlue Swirl     }
193720d97356SBlue Swirl 
193820d97356SBlue Swirl     strm.avail_in = s->cluster_size;
193920d97356SBlue Swirl     strm.next_in = (uint8_t *)buf;
194020d97356SBlue Swirl     strm.avail_out = s->cluster_size;
194120d97356SBlue Swirl     strm.next_out = out_buf;
194220d97356SBlue Swirl 
194320d97356SBlue Swirl     ret = deflate(&strm, Z_FINISH);
194420d97356SBlue Swirl     if (ret != Z_STREAM_END && ret != Z_OK) {
194520d97356SBlue Swirl         deflateEnd(&strm);
19468f1efd00SKevin Wolf         ret = -EINVAL;
19478f1efd00SKevin Wolf         goto fail;
194820d97356SBlue Swirl     }
194920d97356SBlue Swirl     out_len = strm.next_out - out_buf;
195020d97356SBlue Swirl 
195120d97356SBlue Swirl     deflateEnd(&strm);
195220d97356SBlue Swirl 
195320d97356SBlue Swirl     if (ret != Z_STREAM_END || out_len >= s->cluster_size) {
195420d97356SBlue Swirl         /* could not compress: write normal cluster */
19558f1efd00SKevin Wolf         ret = bdrv_write(bs, sector_num, buf, s->cluster_sectors);
19568f1efd00SKevin Wolf         if (ret < 0) {
19578f1efd00SKevin Wolf             goto fail;
19588f1efd00SKevin Wolf         }
195920d97356SBlue Swirl     } else {
196020d97356SBlue Swirl         cluster_offset = qcow2_alloc_compressed_cluster_offset(bs,
196120d97356SBlue Swirl             sector_num << 9, out_len);
19628f1efd00SKevin Wolf         if (!cluster_offset) {
19638f1efd00SKevin Wolf             ret = -EIO;
19648f1efd00SKevin Wolf             goto fail;
19658f1efd00SKevin Wolf         }
196620d97356SBlue Swirl         cluster_offset &= s->cluster_offset_mask;
1967cf93980eSMax Reitz 
1968231bb267SMax Reitz         ret = qcow2_pre_write_overlap_check(bs, 0, cluster_offset, out_len);
1969cf93980eSMax Reitz         if (ret < 0) {
1970cf93980eSMax Reitz             goto fail;
1971cf93980eSMax Reitz         }
1972cf93980eSMax Reitz 
197366f82ceeSKevin Wolf         BLKDBG_EVENT(bs->file, BLKDBG_WRITE_COMPRESSED);
19748f1efd00SKevin Wolf         ret = bdrv_pwrite(bs->file, cluster_offset, out_buf, out_len);
19758f1efd00SKevin Wolf         if (ret < 0) {
19768f1efd00SKevin Wolf             goto fail;
197720d97356SBlue Swirl         }
197820d97356SBlue Swirl     }
197920d97356SBlue Swirl 
19808f1efd00SKevin Wolf     ret = 0;
19818f1efd00SKevin Wolf fail:
19827267c094SAnthony Liguori     g_free(out_buf);
19838f1efd00SKevin Wolf     return ret;
198420d97356SBlue Swirl }
198520d97356SBlue Swirl 
1986a968168cSDong Xu Wang static coroutine_fn int qcow2_co_flush_to_os(BlockDriverState *bs)
198720d97356SBlue Swirl {
198829c1a730SKevin Wolf     BDRVQcowState *s = bs->opaque;
198929c1a730SKevin Wolf     int ret;
199029c1a730SKevin Wolf 
19918b94ff85SPaolo Bonzini     qemu_co_mutex_lock(&s->lock);
199229c1a730SKevin Wolf     ret = qcow2_cache_flush(bs, s->l2_table_cache);
199329c1a730SKevin Wolf     if (ret < 0) {
1994c95de7e2SDong Xu Wang         qemu_co_mutex_unlock(&s->lock);
19958b94ff85SPaolo Bonzini         return ret;
199629c1a730SKevin Wolf     }
199729c1a730SKevin Wolf 
1998bfe8043eSStefan Hajnoczi     if (qcow2_need_accurate_refcounts(s)) {
199929c1a730SKevin Wolf         ret = qcow2_cache_flush(bs, s->refcount_block_cache);
200029c1a730SKevin Wolf         if (ret < 0) {
2001c95de7e2SDong Xu Wang             qemu_co_mutex_unlock(&s->lock);
20028b94ff85SPaolo Bonzini             return ret;
200329c1a730SKevin Wolf         }
2004bfe8043eSStefan Hajnoczi     }
20058b94ff85SPaolo Bonzini     qemu_co_mutex_unlock(&s->lock);
200629c1a730SKevin Wolf 
2007eb489bb1SKevin Wolf     return 0;
2008eb489bb1SKevin Wolf }
2009eb489bb1SKevin Wolf 
20107c80ab3fSJes Sorensen static int qcow2_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
201120d97356SBlue Swirl {
201220d97356SBlue Swirl     BDRVQcowState *s = bs->opaque;
201395de6d70SPaolo Bonzini     bdi->unallocated_blocks_are_zero = true;
201495de6d70SPaolo Bonzini     bdi->can_write_zeroes_with_unmap = (s->qcow_version >= 3);
201520d97356SBlue Swirl     bdi->cluster_size = s->cluster_size;
20167c80ab3fSJes Sorensen     bdi->vm_state_offset = qcow2_vm_state_offset(s);
201720d97356SBlue Swirl     return 0;
201820d97356SBlue Swirl }
201920d97356SBlue Swirl 
202037764dfbSMax Reitz static ImageInfoSpecific *qcow2_get_specific_info(BlockDriverState *bs)
202137764dfbSMax Reitz {
202237764dfbSMax Reitz     BDRVQcowState *s = bs->opaque;
202337764dfbSMax Reitz     ImageInfoSpecific *spec_info = g_new(ImageInfoSpecific, 1);
202437764dfbSMax Reitz 
202537764dfbSMax Reitz     *spec_info = (ImageInfoSpecific){
202637764dfbSMax Reitz         .kind  = IMAGE_INFO_SPECIFIC_KIND_QCOW2,
202737764dfbSMax Reitz         {
202837764dfbSMax Reitz             .qcow2 = g_new(ImageInfoSpecificQCow2, 1),
202937764dfbSMax Reitz         },
203037764dfbSMax Reitz     };
203137764dfbSMax Reitz     if (s->qcow_version == 2) {
203237764dfbSMax Reitz         *spec_info->qcow2 = (ImageInfoSpecificQCow2){
203337764dfbSMax Reitz             .compat = g_strdup("0.10"),
203437764dfbSMax Reitz         };
203537764dfbSMax Reitz     } else if (s->qcow_version == 3) {
203637764dfbSMax Reitz         *spec_info->qcow2 = (ImageInfoSpecificQCow2){
203737764dfbSMax Reitz             .compat             = g_strdup("1.1"),
203837764dfbSMax Reitz             .lazy_refcounts     = s->compatible_features &
203937764dfbSMax Reitz                                   QCOW2_COMPAT_LAZY_REFCOUNTS,
204037764dfbSMax Reitz             .has_lazy_refcounts = true,
204137764dfbSMax Reitz         };
204237764dfbSMax Reitz     }
204337764dfbSMax Reitz 
204437764dfbSMax Reitz     return spec_info;
204537764dfbSMax Reitz }
204637764dfbSMax Reitz 
204720d97356SBlue Swirl #if 0
204820d97356SBlue Swirl static void dump_refcounts(BlockDriverState *bs)
204920d97356SBlue Swirl {
205020d97356SBlue Swirl     BDRVQcowState *s = bs->opaque;
205120d97356SBlue Swirl     int64_t nb_clusters, k, k1, size;
205220d97356SBlue Swirl     int refcount;
205320d97356SBlue Swirl 
205466f82ceeSKevin Wolf     size = bdrv_getlength(bs->file);
205520d97356SBlue Swirl     nb_clusters = size_to_clusters(s, size);
205620d97356SBlue Swirl     for(k = 0; k < nb_clusters;) {
205720d97356SBlue Swirl         k1 = k;
205820d97356SBlue Swirl         refcount = get_refcount(bs, k);
205920d97356SBlue Swirl         k++;
206020d97356SBlue Swirl         while (k < nb_clusters && get_refcount(bs, k) == refcount)
206120d97356SBlue Swirl             k++;
20620bfcd599SBlue Swirl         printf("%" PRId64 ": refcount=%d nb=%" PRId64 "\n", k, refcount,
20630bfcd599SBlue Swirl                k - k1);
206420d97356SBlue Swirl     }
206520d97356SBlue Swirl }
206620d97356SBlue Swirl #endif
206720d97356SBlue Swirl 
2068cf8074b3SKevin Wolf static int qcow2_save_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
2069cf8074b3SKevin Wolf                               int64_t pos)
207020d97356SBlue Swirl {
207120d97356SBlue Swirl     BDRVQcowState *s = bs->opaque;
2072eedff66fSMax Reitz     int64_t total_sectors = bs->total_sectors;
207320d97356SBlue Swirl     int growable = bs->growable;
20746e13610aSMax Reitz     bool zero_beyond_eof = bs->zero_beyond_eof;
207520d97356SBlue Swirl     int ret;
207620d97356SBlue Swirl 
207766f82ceeSKevin Wolf     BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_SAVE);
207820d97356SBlue Swirl     bs->growable = 1;
20796e13610aSMax Reitz     bs->zero_beyond_eof = false;
20808d3b1a2dSKevin Wolf     ret = bdrv_pwritev(bs, qcow2_vm_state_offset(s) + pos, qiov);
208120d97356SBlue Swirl     bs->growable = growable;
20826e13610aSMax Reitz     bs->zero_beyond_eof = zero_beyond_eof;
208320d97356SBlue Swirl 
2084eedff66fSMax Reitz     /* bdrv_co_do_writev will have increased the total_sectors value to include
2085eedff66fSMax Reitz      * the VM state - the VM state is however not an actual part of the block
2086eedff66fSMax Reitz      * device, therefore, we need to restore the old value. */
2087eedff66fSMax Reitz     bs->total_sectors = total_sectors;
2088eedff66fSMax Reitz 
208920d97356SBlue Swirl     return ret;
209020d97356SBlue Swirl }
209120d97356SBlue Swirl 
20927c80ab3fSJes Sorensen static int qcow2_load_vmstate(BlockDriverState *bs, uint8_t *buf,
209320d97356SBlue Swirl                               int64_t pos, int size)
209420d97356SBlue Swirl {
209520d97356SBlue Swirl     BDRVQcowState *s = bs->opaque;
209620d97356SBlue Swirl     int growable = bs->growable;
20970d51b4deSAsias He     bool zero_beyond_eof = bs->zero_beyond_eof;
209820d97356SBlue Swirl     int ret;
209920d97356SBlue Swirl 
210066f82ceeSKevin Wolf     BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_LOAD);
210120d97356SBlue Swirl     bs->growable = 1;
21020d51b4deSAsias He     bs->zero_beyond_eof = false;
21037c80ab3fSJes Sorensen     ret = bdrv_pread(bs, qcow2_vm_state_offset(s) + pos, buf, size);
210420d97356SBlue Swirl     bs->growable = growable;
21050d51b4deSAsias He     bs->zero_beyond_eof = zero_beyond_eof;
210620d97356SBlue Swirl 
210720d97356SBlue Swirl     return ret;
210820d97356SBlue Swirl }
210920d97356SBlue Swirl 
21109296b3edSMax Reitz /*
21119296b3edSMax Reitz  * Downgrades an image's version. To achieve this, any incompatible features
21129296b3edSMax Reitz  * have to be removed.
21139296b3edSMax Reitz  */
21149296b3edSMax Reitz static int qcow2_downgrade(BlockDriverState *bs, int target_version)
21159296b3edSMax Reitz {
21169296b3edSMax Reitz     BDRVQcowState *s = bs->opaque;
21179296b3edSMax Reitz     int current_version = s->qcow_version;
21189296b3edSMax Reitz     int ret;
21199296b3edSMax Reitz 
21209296b3edSMax Reitz     if (target_version == current_version) {
21219296b3edSMax Reitz         return 0;
21229296b3edSMax Reitz     } else if (target_version > current_version) {
21239296b3edSMax Reitz         return -EINVAL;
21249296b3edSMax Reitz     } else if (target_version != 2) {
21259296b3edSMax Reitz         return -EINVAL;
21269296b3edSMax Reitz     }
21279296b3edSMax Reitz 
21289296b3edSMax Reitz     if (s->refcount_order != 4) {
21299296b3edSMax Reitz         /* we would have to convert the image to a refcount_order == 4 image
21309296b3edSMax Reitz          * here; however, since qemu (at the time of writing this) does not
21319296b3edSMax Reitz          * support anything different than 4 anyway, there is no point in doing
21329296b3edSMax Reitz          * so right now; however, we should error out (if qemu supports this in
21339296b3edSMax Reitz          * the future and this code has not been adapted) */
21349296b3edSMax Reitz         error_report("qcow2_downgrade: Image refcount orders other than 4 are "
21359296b3edSMax Reitz                      "currently not supported.");
21369296b3edSMax Reitz         return -ENOTSUP;
21379296b3edSMax Reitz     }
21389296b3edSMax Reitz 
21399296b3edSMax Reitz     /* clear incompatible features */
21409296b3edSMax Reitz     if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
21419296b3edSMax Reitz         ret = qcow2_mark_clean(bs);
21429296b3edSMax Reitz         if (ret < 0) {
21439296b3edSMax Reitz             return ret;
21449296b3edSMax Reitz         }
21459296b3edSMax Reitz     }
21469296b3edSMax Reitz 
21479296b3edSMax Reitz     /* with QCOW2_INCOMPAT_CORRUPT, it is pretty much impossible to get here in
21489296b3edSMax Reitz      * the first place; if that happens nonetheless, returning -ENOTSUP is the
21499296b3edSMax Reitz      * best thing to do anyway */
21509296b3edSMax Reitz 
21519296b3edSMax Reitz     if (s->incompatible_features) {
21529296b3edSMax Reitz         return -ENOTSUP;
21539296b3edSMax Reitz     }
21549296b3edSMax Reitz 
21559296b3edSMax Reitz     /* since we can ignore compatible features, we can set them to 0 as well */
21569296b3edSMax Reitz     s->compatible_features = 0;
21579296b3edSMax Reitz     /* if lazy refcounts have been used, they have already been fixed through
21589296b3edSMax Reitz      * clearing the dirty flag */
21599296b3edSMax Reitz 
21609296b3edSMax Reitz     /* clearing autoclear features is trivial */
21619296b3edSMax Reitz     s->autoclear_features = 0;
21629296b3edSMax Reitz 
21639296b3edSMax Reitz     ret = qcow2_expand_zero_clusters(bs);
21649296b3edSMax Reitz     if (ret < 0) {
21659296b3edSMax Reitz         return ret;
21669296b3edSMax Reitz     }
21679296b3edSMax Reitz 
21689296b3edSMax Reitz     s->qcow_version = target_version;
21699296b3edSMax Reitz     ret = qcow2_update_header(bs);
21709296b3edSMax Reitz     if (ret < 0) {
21719296b3edSMax Reitz         s->qcow_version = current_version;
21729296b3edSMax Reitz         return ret;
21739296b3edSMax Reitz     }
21749296b3edSMax Reitz     return 0;
21759296b3edSMax Reitz }
21769296b3edSMax Reitz 
21779296b3edSMax Reitz static int qcow2_amend_options(BlockDriverState *bs,
21789296b3edSMax Reitz                                QEMUOptionParameter *options)
21799296b3edSMax Reitz {
21809296b3edSMax Reitz     BDRVQcowState *s = bs->opaque;
21819296b3edSMax Reitz     int old_version = s->qcow_version, new_version = old_version;
21829296b3edSMax Reitz     uint64_t new_size = 0;
21839296b3edSMax Reitz     const char *backing_file = NULL, *backing_format = NULL;
21849296b3edSMax Reitz     bool lazy_refcounts = s->use_lazy_refcounts;
21859296b3edSMax Reitz     int ret;
21869296b3edSMax Reitz     int i;
21879296b3edSMax Reitz 
21889296b3edSMax Reitz     for (i = 0; options[i].name; i++)
21899296b3edSMax Reitz     {
21909296b3edSMax Reitz         if (!options[i].assigned) {
21919296b3edSMax Reitz             /* only change explicitly defined options */
21929296b3edSMax Reitz             continue;
21939296b3edSMax Reitz         }
21949296b3edSMax Reitz 
21959296b3edSMax Reitz         if (!strcmp(options[i].name, "compat")) {
21969296b3edSMax Reitz             if (!options[i].value.s) {
21979296b3edSMax Reitz                 /* preserve default */
21989296b3edSMax Reitz             } else if (!strcmp(options[i].value.s, "0.10")) {
21999296b3edSMax Reitz                 new_version = 2;
22009296b3edSMax Reitz             } else if (!strcmp(options[i].value.s, "1.1")) {
22019296b3edSMax Reitz                 new_version = 3;
22029296b3edSMax Reitz             } else {
22039296b3edSMax Reitz                 fprintf(stderr, "Unknown compatibility level %s.\n",
22049296b3edSMax Reitz                         options[i].value.s);
22059296b3edSMax Reitz                 return -EINVAL;
22069296b3edSMax Reitz             }
22079296b3edSMax Reitz         } else if (!strcmp(options[i].name, "preallocation")) {
22089296b3edSMax Reitz             fprintf(stderr, "Cannot change preallocation mode.\n");
22099296b3edSMax Reitz             return -ENOTSUP;
22109296b3edSMax Reitz         } else if (!strcmp(options[i].name, "size")) {
22119296b3edSMax Reitz             new_size = options[i].value.n;
22129296b3edSMax Reitz         } else if (!strcmp(options[i].name, "backing_file")) {
22139296b3edSMax Reitz             backing_file = options[i].value.s;
22149296b3edSMax Reitz         } else if (!strcmp(options[i].name, "backing_fmt")) {
22159296b3edSMax Reitz             backing_format = options[i].value.s;
22169296b3edSMax Reitz         } else if (!strcmp(options[i].name, "encryption")) {
22179296b3edSMax Reitz             if ((options[i].value.n != !!s->crypt_method)) {
22189296b3edSMax Reitz                 fprintf(stderr, "Changing the encryption flag is not "
22199296b3edSMax Reitz                         "supported.\n");
22209296b3edSMax Reitz                 return -ENOTSUP;
22219296b3edSMax Reitz             }
22229296b3edSMax Reitz         } else if (!strcmp(options[i].name, "cluster_size")) {
22239296b3edSMax Reitz             if (options[i].value.n != s->cluster_size) {
22249296b3edSMax Reitz                 fprintf(stderr, "Changing the cluster size is not "
22259296b3edSMax Reitz                         "supported.\n");
22269296b3edSMax Reitz                 return -ENOTSUP;
22279296b3edSMax Reitz             }
22289296b3edSMax Reitz         } else if (!strcmp(options[i].name, "lazy_refcounts")) {
22299296b3edSMax Reitz             lazy_refcounts = options[i].value.n;
22309296b3edSMax Reitz         } else {
22319296b3edSMax Reitz             /* if this assertion fails, this probably means a new option was
22329296b3edSMax Reitz              * added without having it covered here */
22339296b3edSMax Reitz             assert(false);
22349296b3edSMax Reitz         }
22359296b3edSMax Reitz     }
22369296b3edSMax Reitz 
22379296b3edSMax Reitz     if (new_version != old_version) {
22389296b3edSMax Reitz         if (new_version > old_version) {
22399296b3edSMax Reitz             /* Upgrade */
22409296b3edSMax Reitz             s->qcow_version = new_version;
22419296b3edSMax Reitz             ret = qcow2_update_header(bs);
22429296b3edSMax Reitz             if (ret < 0) {
22439296b3edSMax Reitz                 s->qcow_version = old_version;
22449296b3edSMax Reitz                 return ret;
22459296b3edSMax Reitz             }
22469296b3edSMax Reitz         } else {
22479296b3edSMax Reitz             ret = qcow2_downgrade(bs, new_version);
22489296b3edSMax Reitz             if (ret < 0) {
22499296b3edSMax Reitz                 return ret;
22509296b3edSMax Reitz             }
22519296b3edSMax Reitz         }
22529296b3edSMax Reitz     }
22539296b3edSMax Reitz 
22549296b3edSMax Reitz     if (backing_file || backing_format) {
22559296b3edSMax Reitz         ret = qcow2_change_backing_file(bs, backing_file ?: bs->backing_file,
22569296b3edSMax Reitz                                         backing_format ?: bs->backing_format);
22579296b3edSMax Reitz         if (ret < 0) {
22589296b3edSMax Reitz             return ret;
22599296b3edSMax Reitz         }
22609296b3edSMax Reitz     }
22619296b3edSMax Reitz 
22629296b3edSMax Reitz     if (s->use_lazy_refcounts != lazy_refcounts) {
22639296b3edSMax Reitz         if (lazy_refcounts) {
22649296b3edSMax Reitz             if (s->qcow_version < 3) {
22659296b3edSMax Reitz                 fprintf(stderr, "Lazy refcounts only supported with compatibility "
22669296b3edSMax Reitz                         "level 1.1 and above (use compat=1.1 or greater)\n");
22679296b3edSMax Reitz                 return -EINVAL;
22689296b3edSMax Reitz             }
22699296b3edSMax Reitz             s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
22709296b3edSMax Reitz             ret = qcow2_update_header(bs);
22719296b3edSMax Reitz             if (ret < 0) {
22729296b3edSMax Reitz                 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
22739296b3edSMax Reitz                 return ret;
22749296b3edSMax Reitz             }
22759296b3edSMax Reitz             s->use_lazy_refcounts = true;
22769296b3edSMax Reitz         } else {
22779296b3edSMax Reitz             /* make image clean first */
22789296b3edSMax Reitz             ret = qcow2_mark_clean(bs);
22799296b3edSMax Reitz             if (ret < 0) {
22809296b3edSMax Reitz                 return ret;
22819296b3edSMax Reitz             }
22829296b3edSMax Reitz             /* now disallow lazy refcounts */
22839296b3edSMax Reitz             s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
22849296b3edSMax Reitz             ret = qcow2_update_header(bs);
22859296b3edSMax Reitz             if (ret < 0) {
22869296b3edSMax Reitz                 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
22879296b3edSMax Reitz                 return ret;
22889296b3edSMax Reitz             }
22899296b3edSMax Reitz             s->use_lazy_refcounts = false;
22909296b3edSMax Reitz         }
22919296b3edSMax Reitz     }
22929296b3edSMax Reitz 
22939296b3edSMax Reitz     if (new_size) {
22949296b3edSMax Reitz         ret = bdrv_truncate(bs, new_size);
22959296b3edSMax Reitz         if (ret < 0) {
22969296b3edSMax Reitz             return ret;
22979296b3edSMax Reitz         }
22989296b3edSMax Reitz     }
22999296b3edSMax Reitz 
23009296b3edSMax Reitz     return 0;
23019296b3edSMax Reitz }
23029296b3edSMax Reitz 
23037c80ab3fSJes Sorensen static QEMUOptionParameter qcow2_create_options[] = {
230420d97356SBlue Swirl     {
230520d97356SBlue Swirl         .name = BLOCK_OPT_SIZE,
230620d97356SBlue Swirl         .type = OPT_SIZE,
230720d97356SBlue Swirl         .help = "Virtual disk size"
230820d97356SBlue Swirl     },
230920d97356SBlue Swirl     {
23106744cbabSKevin Wolf         .name = BLOCK_OPT_COMPAT_LEVEL,
23116744cbabSKevin Wolf         .type = OPT_STRING,
23126744cbabSKevin Wolf         .help = "Compatibility level (0.10 or 1.1)"
23136744cbabSKevin Wolf     },
23146744cbabSKevin Wolf     {
231520d97356SBlue Swirl         .name = BLOCK_OPT_BACKING_FILE,
231620d97356SBlue Swirl         .type = OPT_STRING,
231720d97356SBlue Swirl         .help = "File name of a base image"
231820d97356SBlue Swirl     },
231920d97356SBlue Swirl     {
232020d97356SBlue Swirl         .name = BLOCK_OPT_BACKING_FMT,
232120d97356SBlue Swirl         .type = OPT_STRING,
232220d97356SBlue Swirl         .help = "Image format of the base image"
232320d97356SBlue Swirl     },
232420d97356SBlue Swirl     {
232520d97356SBlue Swirl         .name = BLOCK_OPT_ENCRYPT,
232620d97356SBlue Swirl         .type = OPT_FLAG,
232720d97356SBlue Swirl         .help = "Encrypt the image"
232820d97356SBlue Swirl     },
232920d97356SBlue Swirl     {
233020d97356SBlue Swirl         .name = BLOCK_OPT_CLUSTER_SIZE,
233120d97356SBlue Swirl         .type = OPT_SIZE,
233299cce9faSKevin Wolf         .help = "qcow2 cluster size",
233399cce9faSKevin Wolf         .value = { .n = DEFAULT_CLUSTER_SIZE },
233420d97356SBlue Swirl     },
233520d97356SBlue Swirl     {
233620d97356SBlue Swirl         .name = BLOCK_OPT_PREALLOC,
233720d97356SBlue Swirl         .type = OPT_STRING,
233820d97356SBlue Swirl         .help = "Preallocation mode (allowed values: off, metadata)"
233920d97356SBlue Swirl     },
2340bfe8043eSStefan Hajnoczi     {
2341bfe8043eSStefan Hajnoczi         .name = BLOCK_OPT_LAZY_REFCOUNTS,
2342bfe8043eSStefan Hajnoczi         .type = OPT_FLAG,
2343bfe8043eSStefan Hajnoczi         .help = "Postpone refcount updates",
2344bfe8043eSStefan Hajnoczi     },
234520d97356SBlue Swirl     { NULL }
234620d97356SBlue Swirl };
234720d97356SBlue Swirl 
234820d97356SBlue Swirl static BlockDriver bdrv_qcow2 = {
234920d97356SBlue Swirl     .format_name        = "qcow2",
235020d97356SBlue Swirl     .instance_size      = sizeof(BDRVQcowState),
23517c80ab3fSJes Sorensen     .bdrv_probe         = qcow2_probe,
23527c80ab3fSJes Sorensen     .bdrv_open          = qcow2_open,
23537c80ab3fSJes Sorensen     .bdrv_close         = qcow2_close,
235421d82ac9SJeff Cody     .bdrv_reopen_prepare  = qcow2_reopen_prepare,
23557c80ab3fSJes Sorensen     .bdrv_create        = qcow2_create,
23563ac21627SPeter Lieven     .bdrv_has_zero_init = bdrv_has_zero_init_1,
2357b6b8a333SPaolo Bonzini     .bdrv_co_get_block_status = qcow2_co_get_block_status,
23587c80ab3fSJes Sorensen     .bdrv_set_key       = qcow2_set_key,
235920d97356SBlue Swirl 
236068d100e9SKevin Wolf     .bdrv_co_readv          = qcow2_co_readv,
236168d100e9SKevin Wolf     .bdrv_co_writev         = qcow2_co_writev,
2362eb489bb1SKevin Wolf     .bdrv_co_flush_to_os    = qcow2_co_flush_to_os,
2363419b19d9SStefan Hajnoczi 
2364621f0589SKevin Wolf     .bdrv_co_write_zeroes   = qcow2_co_write_zeroes,
23656db39ae2SPaolo Bonzini     .bdrv_co_discard        = qcow2_co_discard,
2366419b19d9SStefan Hajnoczi     .bdrv_truncate          = qcow2_truncate,
23677c80ab3fSJes Sorensen     .bdrv_write_compressed  = qcow2_write_compressed,
236820d97356SBlue Swirl 
236920d97356SBlue Swirl     .bdrv_snapshot_create   = qcow2_snapshot_create,
237020d97356SBlue Swirl     .bdrv_snapshot_goto     = qcow2_snapshot_goto,
237120d97356SBlue Swirl     .bdrv_snapshot_delete   = qcow2_snapshot_delete,
237220d97356SBlue Swirl     .bdrv_snapshot_list     = qcow2_snapshot_list,
237351ef6727Sedison     .bdrv_snapshot_load_tmp     = qcow2_snapshot_load_tmp,
23747c80ab3fSJes Sorensen     .bdrv_get_info      = qcow2_get_info,
237537764dfbSMax Reitz     .bdrv_get_specific_info = qcow2_get_specific_info,
237620d97356SBlue Swirl 
23777c80ab3fSJes Sorensen     .bdrv_save_vmstate    = qcow2_save_vmstate,
23787c80ab3fSJes Sorensen     .bdrv_load_vmstate    = qcow2_load_vmstate,
237920d97356SBlue Swirl 
238020d97356SBlue Swirl     .bdrv_change_backing_file   = qcow2_change_backing_file,
238120d97356SBlue Swirl 
2382d34682cdSKevin Wolf     .bdrv_refresh_limits        = qcow2_refresh_limits,
238306d9260fSAnthony Liguori     .bdrv_invalidate_cache      = qcow2_invalidate_cache,
238406d9260fSAnthony Liguori 
23857c80ab3fSJes Sorensen     .create_options = qcow2_create_options,
23867c80ab3fSJes Sorensen     .bdrv_check = qcow2_check,
23879296b3edSMax Reitz     .bdrv_amend_options = qcow2_amend_options,
238820d97356SBlue Swirl };
238920d97356SBlue Swirl 
23905efa9d5aSAnthony Liguori static void bdrv_qcow2_init(void)
23915efa9d5aSAnthony Liguori {
23925efa9d5aSAnthony Liguori     bdrv_register(&bdrv_qcow2);
23935efa9d5aSAnthony Liguori }
23945efa9d5aSAnthony Liguori 
23955efa9d5aSAnthony Liguori block_init(bdrv_qcow2_init);
2396