xref: /qemu/block/qcow2.c (revision 6d33e8e7dc9d40ea105feed4b39caa3e641569e8)
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;
448*6d33e8e7SKevin Wolf     unsigned int len, i;
449*6d33e8e7SKevin Wolf     int ret = 0;
450585f8587Sbellard     QCowHeader header;
45174c4510aSKevin Wolf     QemuOpts *opts;
45274c4510aSKevin Wolf     Error *local_err = NULL;
4539b80ddf3Saliguori     uint64_t ext_end;
4542cf7cfa1SKevin Wolf     uint64_t l1_vm_state_index;
4551fa5cc83SMax Reitz     const char *opt_overlap_check;
4561fa5cc83SMax Reitz     int overlap_check_template = 0;
457585f8587Sbellard 
4586d85a57eSJes Sorensen     ret = bdrv_pread(bs->file, 0, &header, sizeof(header));
4596d85a57eSJes Sorensen     if (ret < 0) {
4603ef6c40aSMax Reitz         error_setg_errno(errp, -ret, "Could not read qcow2 header");
461585f8587Sbellard         goto fail;
4626d85a57eSJes Sorensen     }
463585f8587Sbellard     be32_to_cpus(&header.magic);
464585f8587Sbellard     be32_to_cpus(&header.version);
465585f8587Sbellard     be64_to_cpus(&header.backing_file_offset);
466585f8587Sbellard     be32_to_cpus(&header.backing_file_size);
467585f8587Sbellard     be64_to_cpus(&header.size);
468585f8587Sbellard     be32_to_cpus(&header.cluster_bits);
469585f8587Sbellard     be32_to_cpus(&header.crypt_method);
470585f8587Sbellard     be64_to_cpus(&header.l1_table_offset);
471585f8587Sbellard     be32_to_cpus(&header.l1_size);
472585f8587Sbellard     be64_to_cpus(&header.refcount_table_offset);
473585f8587Sbellard     be32_to_cpus(&header.refcount_table_clusters);
474585f8587Sbellard     be64_to_cpus(&header.snapshots_offset);
475585f8587Sbellard     be32_to_cpus(&header.nb_snapshots);
476585f8587Sbellard 
477e8cdcec1SKevin Wolf     if (header.magic != QCOW_MAGIC) {
4783ef6c40aSMax Reitz         error_setg(errp, "Image is not in qcow2 format");
47976abe407SPaolo Bonzini         ret = -EINVAL;
480585f8587Sbellard         goto fail;
4816d85a57eSJes Sorensen     }
4826744cbabSKevin Wolf     if (header.version < 2 || header.version > 3) {
4833ef6c40aSMax Reitz         report_unsupported(bs, errp, "QCOW version %d", header.version);
484e8cdcec1SKevin Wolf         ret = -ENOTSUP;
485e8cdcec1SKevin Wolf         goto fail;
486e8cdcec1SKevin Wolf     }
4876744cbabSKevin Wolf 
4886744cbabSKevin Wolf     s->qcow_version = header.version;
4896744cbabSKevin Wolf 
49024342f2cSKevin Wolf     /* Initialise cluster size */
49124342f2cSKevin Wolf     if (header.cluster_bits < MIN_CLUSTER_BITS ||
49224342f2cSKevin Wolf         header.cluster_bits > MAX_CLUSTER_BITS) {
49324342f2cSKevin Wolf         error_setg(errp, "Unsupported cluster size: 2^%i", header.cluster_bits);
49424342f2cSKevin Wolf         ret = -EINVAL;
49524342f2cSKevin Wolf         goto fail;
49624342f2cSKevin Wolf     }
49724342f2cSKevin Wolf 
49824342f2cSKevin Wolf     s->cluster_bits = header.cluster_bits;
49924342f2cSKevin Wolf     s->cluster_size = 1 << s->cluster_bits;
50024342f2cSKevin Wolf     s->cluster_sectors = 1 << (s->cluster_bits - 9);
50124342f2cSKevin Wolf 
5026744cbabSKevin Wolf     /* Initialise version 3 header fields */
5036744cbabSKevin Wolf     if (header.version == 2) {
5046744cbabSKevin Wolf         header.incompatible_features    = 0;
5056744cbabSKevin Wolf         header.compatible_features      = 0;
5066744cbabSKevin Wolf         header.autoclear_features       = 0;
5076744cbabSKevin Wolf         header.refcount_order           = 4;
5086744cbabSKevin Wolf         header.header_length            = 72;
5096744cbabSKevin Wolf     } else {
5106744cbabSKevin Wolf         be64_to_cpus(&header.incompatible_features);
5116744cbabSKevin Wolf         be64_to_cpus(&header.compatible_features);
5126744cbabSKevin Wolf         be64_to_cpus(&header.autoclear_features);
5136744cbabSKevin Wolf         be32_to_cpus(&header.refcount_order);
5146744cbabSKevin Wolf         be32_to_cpus(&header.header_length);
51524342f2cSKevin Wolf 
51624342f2cSKevin Wolf         if (header.header_length < 104) {
51724342f2cSKevin Wolf             error_setg(errp, "qcow2 header too short");
51824342f2cSKevin Wolf             ret = -EINVAL;
51924342f2cSKevin Wolf             goto fail;
52024342f2cSKevin Wolf         }
52124342f2cSKevin Wolf     }
52224342f2cSKevin Wolf 
52324342f2cSKevin Wolf     if (header.header_length > s->cluster_size) {
52424342f2cSKevin Wolf         error_setg(errp, "qcow2 header exceeds cluster size");
52524342f2cSKevin Wolf         ret = -EINVAL;
52624342f2cSKevin Wolf         goto fail;
5276744cbabSKevin Wolf     }
5286744cbabSKevin Wolf 
5296744cbabSKevin Wolf     if (header.header_length > sizeof(header)) {
5306744cbabSKevin Wolf         s->unknown_header_fields_size = header.header_length - sizeof(header);
5316744cbabSKevin Wolf         s->unknown_header_fields = g_malloc(s->unknown_header_fields_size);
5326744cbabSKevin Wolf         ret = bdrv_pread(bs->file, sizeof(header), s->unknown_header_fields,
5336744cbabSKevin Wolf                          s->unknown_header_fields_size);
5346744cbabSKevin Wolf         if (ret < 0) {
5353ef6c40aSMax Reitz             error_setg_errno(errp, -ret, "Could not read unknown qcow2 header "
5363ef6c40aSMax Reitz                              "fields");
5376744cbabSKevin Wolf             goto fail;
5386744cbabSKevin Wolf         }
5396744cbabSKevin Wolf     }
5406744cbabSKevin Wolf 
541a1b3955cSKevin Wolf     if (header.backing_file_offset > s->cluster_size) {
542a1b3955cSKevin Wolf         error_setg(errp, "Invalid backing file offset");
543a1b3955cSKevin Wolf         ret = -EINVAL;
544a1b3955cSKevin Wolf         goto fail;
545a1b3955cSKevin Wolf     }
546a1b3955cSKevin Wolf 
547cfcc4c62SKevin Wolf     if (header.backing_file_offset) {
548cfcc4c62SKevin Wolf         ext_end = header.backing_file_offset;
549cfcc4c62SKevin Wolf     } else {
550cfcc4c62SKevin Wolf         ext_end = 1 << header.cluster_bits;
551cfcc4c62SKevin Wolf     }
552cfcc4c62SKevin Wolf 
5536744cbabSKevin Wolf     /* Handle feature bits */
5546744cbabSKevin Wolf     s->incompatible_features    = header.incompatible_features;
5556744cbabSKevin Wolf     s->compatible_features      = header.compatible_features;
5566744cbabSKevin Wolf     s->autoclear_features       = header.autoclear_features;
5576744cbabSKevin Wolf 
558c61d0004SStefan Hajnoczi     if (s->incompatible_features & ~QCOW2_INCOMPAT_MASK) {
559cfcc4c62SKevin Wolf         void *feature_table = NULL;
560cfcc4c62SKevin Wolf         qcow2_read_extensions(bs, header.header_length, ext_end,
5613ef6c40aSMax Reitz                               &feature_table, NULL);
5623ef6c40aSMax Reitz         report_unsupported_feature(bs, errp, feature_table,
563c61d0004SStefan Hajnoczi                                    s->incompatible_features &
564c61d0004SStefan Hajnoczi                                    ~QCOW2_INCOMPAT_MASK);
5656744cbabSKevin Wolf         ret = -ENOTSUP;
566c5a33ee9SPrasad Joshi         g_free(feature_table);
5676744cbabSKevin Wolf         goto fail;
5686744cbabSKevin Wolf     }
5696744cbabSKevin Wolf 
57069c98726SMax Reitz     if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
57169c98726SMax Reitz         /* Corrupt images may not be written to unless they are being repaired
57269c98726SMax Reitz          */
57369c98726SMax Reitz         if ((flags & BDRV_O_RDWR) && !(flags & BDRV_O_CHECK)) {
5743ef6c40aSMax Reitz             error_setg(errp, "qcow2: Image is corrupt; cannot be opened "
5753ef6c40aSMax Reitz                        "read/write");
57669c98726SMax Reitz             ret = -EACCES;
57769c98726SMax Reitz             goto fail;
57869c98726SMax Reitz         }
57969c98726SMax Reitz     }
58069c98726SMax Reitz 
5816744cbabSKevin Wolf     /* Check support for various header values */
5826744cbabSKevin Wolf     if (header.refcount_order != 4) {
5833ef6c40aSMax Reitz         report_unsupported(bs, errp, "%d bit reference counts",
5846744cbabSKevin Wolf                            1 << header.refcount_order);
5856744cbabSKevin Wolf         ret = -ENOTSUP;
5866744cbabSKevin Wolf         goto fail;
5876744cbabSKevin Wolf     }
588b6481f37SMax Reitz     s->refcount_order = header.refcount_order;
5896744cbabSKevin Wolf 
5906d85a57eSJes Sorensen     if (header.crypt_method > QCOW_CRYPT_AES) {
5913ef6c40aSMax Reitz         error_setg(errp, "Unsupported encryption method: %i",
5923ef6c40aSMax Reitz                    header.crypt_method);
5936d85a57eSJes Sorensen         ret = -EINVAL;
594585f8587Sbellard         goto fail;
5956d85a57eSJes Sorensen     }
596585f8587Sbellard     s->crypt_method_header = header.crypt_method;
5976d85a57eSJes Sorensen     if (s->crypt_method_header) {
598585f8587Sbellard         bs->encrypted = 1;
5996d85a57eSJes Sorensen     }
60024342f2cSKevin Wolf 
601585f8587Sbellard     s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */
602585f8587Sbellard     s->l2_size = 1 << s->l2_bits;
603585f8587Sbellard     bs->total_sectors = header.size / 512;
604585f8587Sbellard     s->csize_shift = (62 - (s->cluster_bits - 8));
605585f8587Sbellard     s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;
606585f8587Sbellard     s->cluster_offset_mask = (1LL << s->csize_shift) - 1;
6075dab2fadSKevin Wolf 
608585f8587Sbellard     s->refcount_table_offset = header.refcount_table_offset;
609585f8587Sbellard     s->refcount_table_size =
610585f8587Sbellard         header.refcount_table_clusters << (s->cluster_bits - 3);
611585f8587Sbellard 
6125dab2fadSKevin Wolf     if (header.refcount_table_clusters > (0x800000 >> s->cluster_bits)) {
6135dab2fadSKevin Wolf         /* 8 MB refcount table is enough for 2 PB images at 64k cluster size
6145dab2fadSKevin Wolf          * (128 GB for 512 byte clusters, 2 EB for 2 MB clusters) */
6155dab2fadSKevin Wolf         error_setg(errp, "Reference count table too large");
6165dab2fadSKevin Wolf         ret = -EINVAL;
6175dab2fadSKevin Wolf         goto fail;
6185dab2fadSKevin Wolf     }
6195dab2fadSKevin Wolf 
6208c7de283SKevin Wolf     ret = validate_table_offset(bs, s->refcount_table_offset,
6218c7de283SKevin Wolf                                 s->refcount_table_size, sizeof(uint64_t));
6228c7de283SKevin Wolf     if (ret < 0) {
6238c7de283SKevin Wolf         error_setg(errp, "Invalid reference count table offset");
6248c7de283SKevin Wolf         goto fail;
6258c7de283SKevin Wolf     }
6268c7de283SKevin Wolf 
627ce48f2f4SKevin Wolf     /* Snapshot table offset/length */
628ce48f2f4SKevin Wolf     if (header.nb_snapshots > QCOW_MAX_SNAPSHOTS) {
629ce48f2f4SKevin Wolf         error_setg(errp, "Too many snapshots");
630ce48f2f4SKevin Wolf         ret = -EINVAL;
631ce48f2f4SKevin Wolf         goto fail;
632ce48f2f4SKevin Wolf     }
633ce48f2f4SKevin Wolf 
634ce48f2f4SKevin Wolf     ret = validate_table_offset(bs, header.snapshots_offset,
635ce48f2f4SKevin Wolf                                 header.nb_snapshots,
636ce48f2f4SKevin Wolf                                 sizeof(QCowSnapshotHeader));
637ce48f2f4SKevin Wolf     if (ret < 0) {
638ce48f2f4SKevin Wolf         error_setg(errp, "Invalid snapshot table offset");
639ce48f2f4SKevin Wolf         goto fail;
640ce48f2f4SKevin Wolf     }
641ce48f2f4SKevin Wolf 
642585f8587Sbellard     s->snapshots_offset = header.snapshots_offset;
643585f8587Sbellard     s->nb_snapshots = header.nb_snapshots;
644585f8587Sbellard 
645585f8587Sbellard     /* read the level 1 table */
6462d51c32cSKevin Wolf     if (header.l1_size > 0x2000000) {
6472d51c32cSKevin Wolf         /* 32 MB L1 table is enough for 2 PB images at 64k cluster size
6482d51c32cSKevin Wolf          * (128 GB for 512 byte clusters, 2 EB for 2 MB clusters) */
6492d51c32cSKevin Wolf         error_setg(errp, "Active L1 table too large");
6502d51c32cSKevin Wolf         ret = -EFBIG;
6512d51c32cSKevin Wolf         goto fail;
6522d51c32cSKevin Wolf     }
653585f8587Sbellard     s->l1_size = header.l1_size;
6542cf7cfa1SKevin Wolf 
6552cf7cfa1SKevin Wolf     l1_vm_state_index = size_to_l1(s, header.size);
6562cf7cfa1SKevin Wolf     if (l1_vm_state_index > INT_MAX) {
6573ef6c40aSMax Reitz         error_setg(errp, "Image is too big");
6582cf7cfa1SKevin Wolf         ret = -EFBIG;
6592cf7cfa1SKevin Wolf         goto fail;
6602cf7cfa1SKevin Wolf     }
6612cf7cfa1SKevin Wolf     s->l1_vm_state_index = l1_vm_state_index;
6622cf7cfa1SKevin Wolf 
663585f8587Sbellard     /* the L1 table must contain at least enough entries to put
664585f8587Sbellard        header.size bytes */
6656d85a57eSJes Sorensen     if (s->l1_size < s->l1_vm_state_index) {
6663ef6c40aSMax Reitz         error_setg(errp, "L1 table is too small");
6676d85a57eSJes Sorensen         ret = -EINVAL;
668585f8587Sbellard         goto fail;
6696d85a57eSJes Sorensen     }
6702d51c32cSKevin Wolf 
6712d51c32cSKevin Wolf     ret = validate_table_offset(bs, header.l1_table_offset,
6722d51c32cSKevin Wolf                                 header.l1_size, sizeof(uint64_t));
6732d51c32cSKevin Wolf     if (ret < 0) {
6742d51c32cSKevin Wolf         error_setg(errp, "Invalid L1 table offset");
6752d51c32cSKevin Wolf         goto fail;
6762d51c32cSKevin Wolf     }
677585f8587Sbellard     s->l1_table_offset = header.l1_table_offset;
6782d51c32cSKevin Wolf 
6792d51c32cSKevin Wolf 
680d191d12dSStefan Weil     if (s->l1_size > 0) {
6817267c094SAnthony Liguori         s->l1_table = g_malloc0(
6823f6a3ee5SKevin Wolf             align_offset(s->l1_size * sizeof(uint64_t), 512));
6836d85a57eSJes Sorensen         ret = bdrv_pread(bs->file, s->l1_table_offset, s->l1_table,
6846d85a57eSJes Sorensen                          s->l1_size * sizeof(uint64_t));
6856d85a57eSJes Sorensen         if (ret < 0) {
6863ef6c40aSMax Reitz             error_setg_errno(errp, -ret, "Could not read L1 table");
687585f8587Sbellard             goto fail;
6886d85a57eSJes Sorensen         }
689585f8587Sbellard         for(i = 0;i < s->l1_size; i++) {
690585f8587Sbellard             be64_to_cpus(&s->l1_table[i]);
691585f8587Sbellard         }
692d191d12dSStefan Weil     }
69329c1a730SKevin Wolf 
69429c1a730SKevin Wolf     /* alloc L2 table/refcount block cache */
6956af4e9eaSPaolo Bonzini     s->l2_table_cache = qcow2_cache_create(bs, L2_CACHE_SIZE);
6966af4e9eaSPaolo Bonzini     s->refcount_block_cache = qcow2_cache_create(bs, REFCOUNT_CACHE_SIZE);
69729c1a730SKevin Wolf 
6987267c094SAnthony Liguori     s->cluster_cache = g_malloc(s->cluster_size);
699585f8587Sbellard     /* one more sector for decompressed data alignment */
700dea43a65SFrediano Ziglio     s->cluster_data = qemu_blockalign(bs, QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size
701095a9c58Saliguori                                   + 512);
702585f8587Sbellard     s->cluster_cache_offset = -1;
70306d9260fSAnthony Liguori     s->flags = flags;
704585f8587Sbellard 
7056d85a57eSJes Sorensen     ret = qcow2_refcount_init(bs);
7066d85a57eSJes Sorensen     if (ret != 0) {
7073ef6c40aSMax Reitz         error_setg_errno(errp, -ret, "Could not initialize refcount handling");
708585f8587Sbellard         goto fail;
7096d85a57eSJes Sorensen     }
710585f8587Sbellard 
71172cf2d4fSBlue Swirl     QLIST_INIT(&s->cluster_allocs);
7120b919faeSKevin Wolf     QTAILQ_INIT(&s->discards);
713f214978aSKevin Wolf 
7149b80ddf3Saliguori     /* read qcow2 extensions */
7153ef6c40aSMax Reitz     if (qcow2_read_extensions(bs, header.header_length, ext_end, NULL,
7163ef6c40aSMax Reitz         &local_err)) {
7173ef6c40aSMax Reitz         error_propagate(errp, local_err);
7186d85a57eSJes Sorensen         ret = -EINVAL;
7199b80ddf3Saliguori         goto fail;
7206d85a57eSJes Sorensen     }
7219b80ddf3Saliguori 
722585f8587Sbellard     /* read the backing file name */
723585f8587Sbellard     if (header.backing_file_offset != 0) {
724585f8587Sbellard         len = header.backing_file_size;
725*6d33e8e7SKevin Wolf         if (len > MIN(1023, s->cluster_size - header.backing_file_offset)) {
726*6d33e8e7SKevin Wolf             error_setg(errp, "Backing file name too long");
727*6d33e8e7SKevin Wolf             ret = -EINVAL;
728*6d33e8e7SKevin Wolf             goto fail;
7296d85a57eSJes Sorensen         }
7306d85a57eSJes Sorensen         ret = bdrv_pread(bs->file, header.backing_file_offset,
7316d85a57eSJes Sorensen                          bs->backing_file, len);
7326d85a57eSJes Sorensen         if (ret < 0) {
7333ef6c40aSMax Reitz             error_setg_errno(errp, -ret, "Could not read backing file name");
734585f8587Sbellard             goto fail;
7356d85a57eSJes Sorensen         }
736585f8587Sbellard         bs->backing_file[len] = '\0';
737585f8587Sbellard     }
73842deb29fSKevin Wolf 
73942deb29fSKevin Wolf     ret = qcow2_read_snapshots(bs);
74042deb29fSKevin Wolf     if (ret < 0) {
7413ef6c40aSMax Reitz         error_setg_errno(errp, -ret, "Could not read snapshots");
742585f8587Sbellard         goto fail;
7436d85a57eSJes Sorensen     }
744585f8587Sbellard 
745af7b708dSStefan Hajnoczi     /* Clear unknown autoclear feature bits */
74627eb6c09SKevin Wolf     if (!bs->read_only && !(flags & BDRV_O_INCOMING) && s->autoclear_features) {
747af7b708dSStefan Hajnoczi         s->autoclear_features = 0;
748af7b708dSStefan Hajnoczi         ret = qcow2_update_header(bs);
749af7b708dSStefan Hajnoczi         if (ret < 0) {
7503ef6c40aSMax Reitz             error_setg_errno(errp, -ret, "Could not update qcow2 header");
751af7b708dSStefan Hajnoczi             goto fail;
752af7b708dSStefan Hajnoczi         }
753af7b708dSStefan Hajnoczi     }
754af7b708dSStefan Hajnoczi 
75568d100e9SKevin Wolf     /* Initialise locks */
75668d100e9SKevin Wolf     qemu_co_mutex_init(&s->lock);
75768d100e9SKevin Wolf 
758c61d0004SStefan Hajnoczi     /* Repair image if dirty */
75927eb6c09SKevin Wolf     if (!(flags & (BDRV_O_CHECK | BDRV_O_INCOMING)) && !bs->read_only &&
760058f8f16SStefan Hajnoczi         (s->incompatible_features & QCOW2_INCOMPAT_DIRTY)) {
761c61d0004SStefan Hajnoczi         BdrvCheckResult result = {0};
762c61d0004SStefan Hajnoczi 
763acbe5982SStefan Hajnoczi         ret = qcow2_check(bs, &result, BDRV_FIX_ERRORS);
764c61d0004SStefan Hajnoczi         if (ret < 0) {
7653ef6c40aSMax Reitz             error_setg_errno(errp, -ret, "Could not repair dirty image");
766c61d0004SStefan Hajnoczi             goto fail;
767c61d0004SStefan Hajnoczi         }
768c61d0004SStefan Hajnoczi     }
769c61d0004SStefan Hajnoczi 
77074c4510aSKevin Wolf     /* Enable lazy_refcounts according to image and command line options */
77187ea75d5SPeter Crosthwaite     opts = qemu_opts_create(&qcow2_runtime_opts, NULL, 0, &error_abort);
77274c4510aSKevin Wolf     qemu_opts_absorb_qdict(opts, options, &local_err);
77384d18f06SMarkus Armbruster     if (local_err) {
7743ef6c40aSMax Reitz         error_propagate(errp, local_err);
77574c4510aSKevin Wolf         ret = -EINVAL;
77674c4510aSKevin Wolf         goto fail;
77774c4510aSKevin Wolf     }
77874c4510aSKevin Wolf 
779acdfb480SKevin Wolf     s->use_lazy_refcounts = qemu_opt_get_bool(opts, QCOW2_OPT_LAZY_REFCOUNTS,
78074c4510aSKevin Wolf         (s->compatible_features & QCOW2_COMPAT_LAZY_REFCOUNTS));
78174c4510aSKevin Wolf 
78267af674eSKevin Wolf     s->discard_passthrough[QCOW2_DISCARD_NEVER] = false;
78367af674eSKevin Wolf     s->discard_passthrough[QCOW2_DISCARD_ALWAYS] = true;
78467af674eSKevin Wolf     s->discard_passthrough[QCOW2_DISCARD_REQUEST] =
78567af674eSKevin Wolf         qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_REQUEST,
78667af674eSKevin Wolf                           flags & BDRV_O_UNMAP);
78767af674eSKevin Wolf     s->discard_passthrough[QCOW2_DISCARD_SNAPSHOT] =
78867af674eSKevin Wolf         qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_SNAPSHOT, true);
78967af674eSKevin Wolf     s->discard_passthrough[QCOW2_DISCARD_OTHER] =
79067af674eSKevin Wolf         qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_OTHER, false);
79167af674eSKevin Wolf 
7921fa5cc83SMax Reitz     opt_overlap_check = qemu_opt_get(opts, "overlap-check") ?: "cached";
7931fa5cc83SMax Reitz     if (!strcmp(opt_overlap_check, "none")) {
7941fa5cc83SMax Reitz         overlap_check_template = 0;
7951fa5cc83SMax Reitz     } else if (!strcmp(opt_overlap_check, "constant")) {
7961fa5cc83SMax Reitz         overlap_check_template = QCOW2_OL_CONSTANT;
7971fa5cc83SMax Reitz     } else if (!strcmp(opt_overlap_check, "cached")) {
7981fa5cc83SMax Reitz         overlap_check_template = QCOW2_OL_CACHED;
7991fa5cc83SMax Reitz     } else if (!strcmp(opt_overlap_check, "all")) {
8001fa5cc83SMax Reitz         overlap_check_template = QCOW2_OL_ALL;
8011fa5cc83SMax Reitz     } else {
8021fa5cc83SMax Reitz         error_setg(errp, "Unsupported value '%s' for qcow2 option "
8031fa5cc83SMax Reitz                    "'overlap-check'. Allowed are either of the following: "
8041fa5cc83SMax Reitz                    "none, constant, cached, all", opt_overlap_check);
8051fa5cc83SMax Reitz         qemu_opts_del(opts);
8061fa5cc83SMax Reitz         ret = -EINVAL;
8071fa5cc83SMax Reitz         goto fail;
8081fa5cc83SMax Reitz     }
8091fa5cc83SMax Reitz 
8101fa5cc83SMax Reitz     s->overlap_check = 0;
8111fa5cc83SMax Reitz     for (i = 0; i < QCOW2_OL_MAX_BITNR; i++) {
8121fa5cc83SMax Reitz         /* overlap-check defines a template bitmask, but every flag may be
8131fa5cc83SMax Reitz          * overwritten through the associated boolean option */
8141fa5cc83SMax Reitz         s->overlap_check |=
8151fa5cc83SMax Reitz             qemu_opt_get_bool(opts, overlap_bool_option_names[i],
8161fa5cc83SMax Reitz                               overlap_check_template & (1 << i)) << i;
8171fa5cc83SMax Reitz     }
8183e355390SMax Reitz 
81974c4510aSKevin Wolf     qemu_opts_del(opts);
82074c4510aSKevin Wolf 
82174c4510aSKevin Wolf     if (s->use_lazy_refcounts && s->qcow_version < 3) {
8223ef6c40aSMax Reitz         error_setg(errp, "Lazy refcounts require a qcow2 image with at least "
8233ef6c40aSMax Reitz                    "qemu 1.1 compatibility level");
82474c4510aSKevin Wolf         ret = -EINVAL;
82574c4510aSKevin Wolf         goto fail;
82674c4510aSKevin Wolf     }
82774c4510aSKevin Wolf 
828585f8587Sbellard #ifdef DEBUG_ALLOC
8296cbc3031SPhilipp Hahn     {
8306cbc3031SPhilipp Hahn         BdrvCheckResult result = {0};
831b35278f7SStefan Hajnoczi         qcow2_check_refcounts(bs, &result, 0);
8326cbc3031SPhilipp Hahn     }
833585f8587Sbellard #endif
8346d85a57eSJes Sorensen     return ret;
835585f8587Sbellard 
836585f8587Sbellard  fail:
8376744cbabSKevin Wolf     g_free(s->unknown_header_fields);
83875bab85cSKevin Wolf     cleanup_unknown_header_ext(bs);
839ed6ccf0fSKevin Wolf     qcow2_free_snapshots(bs);
840ed6ccf0fSKevin Wolf     qcow2_refcount_close(bs);
8417267c094SAnthony Liguori     g_free(s->l1_table);
842cf93980eSMax Reitz     /* else pre-write overlap checks in cache_destroy may crash */
843cf93980eSMax Reitz     s->l1_table = NULL;
84429c1a730SKevin Wolf     if (s->l2_table_cache) {
84529c1a730SKevin Wolf         qcow2_cache_destroy(bs, s->l2_table_cache);
84629c1a730SKevin Wolf     }
847c5a33ee9SPrasad Joshi     if (s->refcount_block_cache) {
848c5a33ee9SPrasad Joshi         qcow2_cache_destroy(bs, s->refcount_block_cache);
849c5a33ee9SPrasad Joshi     }
8507267c094SAnthony Liguori     g_free(s->cluster_cache);
851dea43a65SFrediano Ziglio     qemu_vfree(s->cluster_data);
8526d85a57eSJes Sorensen     return ret;
853585f8587Sbellard }
854585f8587Sbellard 
855d34682cdSKevin Wolf static int qcow2_refresh_limits(BlockDriverState *bs)
856d34682cdSKevin Wolf {
857d34682cdSKevin Wolf     BDRVQcowState *s = bs->opaque;
858d34682cdSKevin Wolf 
859d34682cdSKevin Wolf     bs->bl.write_zeroes_alignment = s->cluster_sectors;
860d34682cdSKevin Wolf 
861d34682cdSKevin Wolf     return 0;
862d34682cdSKevin Wolf }
863d34682cdSKevin Wolf 
8647c80ab3fSJes Sorensen static int qcow2_set_key(BlockDriverState *bs, const char *key)
865585f8587Sbellard {
866585f8587Sbellard     BDRVQcowState *s = bs->opaque;
867585f8587Sbellard     uint8_t keybuf[16];
868585f8587Sbellard     int len, i;
869585f8587Sbellard 
870585f8587Sbellard     memset(keybuf, 0, 16);
871585f8587Sbellard     len = strlen(key);
872585f8587Sbellard     if (len > 16)
873585f8587Sbellard         len = 16;
874585f8587Sbellard     /* XXX: we could compress the chars to 7 bits to increase
875585f8587Sbellard        entropy */
876585f8587Sbellard     for(i = 0;i < len;i++) {
877585f8587Sbellard         keybuf[i] = key[i];
878585f8587Sbellard     }
879585f8587Sbellard     s->crypt_method = s->crypt_method_header;
880585f8587Sbellard 
881585f8587Sbellard     if (AES_set_encrypt_key(keybuf, 128, &s->aes_encrypt_key) != 0)
882585f8587Sbellard         return -1;
883585f8587Sbellard     if (AES_set_decrypt_key(keybuf, 128, &s->aes_decrypt_key) != 0)
884585f8587Sbellard         return -1;
885585f8587Sbellard #if 0
886585f8587Sbellard     /* test */
887585f8587Sbellard     {
888585f8587Sbellard         uint8_t in[16];
889585f8587Sbellard         uint8_t out[16];
890585f8587Sbellard         uint8_t tmp[16];
891585f8587Sbellard         for(i=0;i<16;i++)
892585f8587Sbellard             in[i] = i;
893585f8587Sbellard         AES_encrypt(in, tmp, &s->aes_encrypt_key);
894585f8587Sbellard         AES_decrypt(tmp, out, &s->aes_decrypt_key);
895585f8587Sbellard         for(i = 0; i < 16; i++)
896585f8587Sbellard             printf(" %02x", tmp[i]);
897585f8587Sbellard         printf("\n");
898585f8587Sbellard         for(i = 0; i < 16; i++)
899585f8587Sbellard             printf(" %02x", out[i]);
900585f8587Sbellard         printf("\n");
901585f8587Sbellard     }
902585f8587Sbellard #endif
903585f8587Sbellard     return 0;
904585f8587Sbellard }
905585f8587Sbellard 
90621d82ac9SJeff Cody /* We have nothing to do for QCOW2 reopen, stubs just return
90721d82ac9SJeff Cody  * success */
90821d82ac9SJeff Cody static int qcow2_reopen_prepare(BDRVReopenState *state,
90921d82ac9SJeff Cody                                 BlockReopenQueue *queue, Error **errp)
91021d82ac9SJeff Cody {
91121d82ac9SJeff Cody     return 0;
91221d82ac9SJeff Cody }
91321d82ac9SJeff Cody 
914b6b8a333SPaolo Bonzini static int64_t coroutine_fn qcow2_co_get_block_status(BlockDriverState *bs,
915f8a2e5e3SStefan Hajnoczi         int64_t sector_num, int nb_sectors, int *pnum)
916585f8587Sbellard {
917f8a2e5e3SStefan Hajnoczi     BDRVQcowState *s = bs->opaque;
918585f8587Sbellard     uint64_t cluster_offset;
9194bc74be9SPaolo Bonzini     int index_in_cluster, ret;
9204bc74be9SPaolo Bonzini     int64_t status = 0;
921585f8587Sbellard 
922095a9c58Saliguori     *pnum = nb_sectors;
923f8a2e5e3SStefan Hajnoczi     qemu_co_mutex_lock(&s->lock);
9241c46efaaSKevin Wolf     ret = qcow2_get_cluster_offset(bs, sector_num << 9, pnum, &cluster_offset);
925f8a2e5e3SStefan Hajnoczi     qemu_co_mutex_unlock(&s->lock);
9261c46efaaSKevin Wolf     if (ret < 0) {
927d663640cSPaolo Bonzini         return ret;
9281c46efaaSKevin Wolf     }
929095a9c58Saliguori 
9304bc74be9SPaolo Bonzini     if (cluster_offset != 0 && ret != QCOW2_CLUSTER_COMPRESSED &&
9314bc74be9SPaolo Bonzini         !s->crypt_method) {
9324bc74be9SPaolo Bonzini         index_in_cluster = sector_num & (s->cluster_sectors - 1);
9334bc74be9SPaolo Bonzini         cluster_offset |= (index_in_cluster << BDRV_SECTOR_BITS);
9344bc74be9SPaolo Bonzini         status |= BDRV_BLOCK_OFFSET_VALID | cluster_offset;
9354bc74be9SPaolo Bonzini     }
9364bc74be9SPaolo Bonzini     if (ret == QCOW2_CLUSTER_ZERO) {
9374bc74be9SPaolo Bonzini         status |= BDRV_BLOCK_ZERO;
9384bc74be9SPaolo Bonzini     } else if (ret != QCOW2_CLUSTER_UNALLOCATED) {
9394bc74be9SPaolo Bonzini         status |= BDRV_BLOCK_DATA;
9404bc74be9SPaolo Bonzini     }
9414bc74be9SPaolo Bonzini     return status;
942585f8587Sbellard }
943585f8587Sbellard 
944a9465922Sbellard /* handle reading after the end of the backing file */
945bd28f835SKevin Wolf int qcow2_backing_read1(BlockDriverState *bs, QEMUIOVector *qiov,
946bd28f835SKevin Wolf                   int64_t sector_num, int nb_sectors)
947a9465922Sbellard {
948a9465922Sbellard     int n1;
949a9465922Sbellard     if ((sector_num + nb_sectors) <= bs->total_sectors)
950a9465922Sbellard         return nb_sectors;
951a9465922Sbellard     if (sector_num >= bs->total_sectors)
952a9465922Sbellard         n1 = 0;
953a9465922Sbellard     else
954a9465922Sbellard         n1 = bs->total_sectors - sector_num;
955bd28f835SKevin Wolf 
9563d9b4925SMichael Tokarev     qemu_iovec_memset(qiov, 512 * n1, 0, 512 * (nb_sectors - n1));
957bd28f835SKevin Wolf 
958a9465922Sbellard     return n1;
959a9465922Sbellard }
960a9465922Sbellard 
961a968168cSDong Xu Wang static coroutine_fn int qcow2_co_readv(BlockDriverState *bs, int64_t sector_num,
9623fc48d09SFrediano Ziglio                           int remaining_sectors, QEMUIOVector *qiov)
9631490791fSaliguori {
964585f8587Sbellard     BDRVQcowState *s = bs->opaque;
965a9465922Sbellard     int index_in_cluster, n1;
96668d100e9SKevin Wolf     int ret;
967faf575c1SFrediano Ziglio     int cur_nr_sectors; /* number of sectors in current iteration */
968c2bdd990SFrediano Ziglio     uint64_t cluster_offset = 0;
9693fc48d09SFrediano Ziglio     uint64_t bytes_done = 0;
9703fc48d09SFrediano Ziglio     QEMUIOVector hd_qiov;
9713fc48d09SFrediano Ziglio     uint8_t *cluster_data = NULL;
972585f8587Sbellard 
9733fc48d09SFrediano Ziglio     qemu_iovec_init(&hd_qiov, qiov->niov);
9743fc48d09SFrediano Ziglio 
9753fc48d09SFrediano Ziglio     qemu_co_mutex_lock(&s->lock);
9763fc48d09SFrediano Ziglio 
9773fc48d09SFrediano Ziglio     while (remaining_sectors != 0) {
978585f8587Sbellard 
979faf575c1SFrediano Ziglio         /* prepare next request */
9803fc48d09SFrediano Ziglio         cur_nr_sectors = remaining_sectors;
981bd28f835SKevin Wolf         if (s->crypt_method) {
982faf575c1SFrediano Ziglio             cur_nr_sectors = MIN(cur_nr_sectors,
983bd28f835SKevin Wolf                 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors);
984bd28f835SKevin Wolf         }
985bd28f835SKevin Wolf 
9863fc48d09SFrediano Ziglio         ret = qcow2_get_cluster_offset(bs, sector_num << 9,
987c2bdd990SFrediano Ziglio             &cur_nr_sectors, &cluster_offset);
9881c46efaaSKevin Wolf         if (ret < 0) {
9893fc48d09SFrediano Ziglio             goto fail;
9901c46efaaSKevin Wolf         }
9911c46efaaSKevin Wolf 
9923fc48d09SFrediano Ziglio         index_in_cluster = sector_num & (s->cluster_sectors - 1);
993585f8587Sbellard 
9943fc48d09SFrediano Ziglio         qemu_iovec_reset(&hd_qiov);
9951b093c48SMichael Tokarev         qemu_iovec_concat(&hd_qiov, qiov, bytes_done,
996faf575c1SFrediano Ziglio             cur_nr_sectors * 512);
997bd28f835SKevin Wolf 
99868d000a3SKevin Wolf         switch (ret) {
99968d000a3SKevin Wolf         case QCOW2_CLUSTER_UNALLOCATED:
1000bd28f835SKevin Wolf 
1001585f8587Sbellard             if (bs->backing_hd) {
1002585f8587Sbellard                 /* read from the base image */
10033fc48d09SFrediano Ziglio                 n1 = qcow2_backing_read1(bs->backing_hd, &hd_qiov,
10043fc48d09SFrediano Ziglio                     sector_num, cur_nr_sectors);
1005a9465922Sbellard                 if (n1 > 0) {
100666f82ceeSKevin Wolf                     BLKDBG_EVENT(bs->file, BLKDBG_READ_BACKING_AIO);
100768d100e9SKevin Wolf                     qemu_co_mutex_unlock(&s->lock);
10083fc48d09SFrediano Ziglio                     ret = bdrv_co_readv(bs->backing_hd, sector_num,
10093fc48d09SFrediano Ziglio                                         n1, &hd_qiov);
101068d100e9SKevin Wolf                     qemu_co_mutex_lock(&s->lock);
101168d100e9SKevin Wolf                     if (ret < 0) {
10123fc48d09SFrediano Ziglio                         goto fail;
10133ab4c7e9SKevin Wolf                     }
10141490791fSaliguori                 }
1015a9465922Sbellard             } else {
1016585f8587Sbellard                 /* Note: in this case, no need to wait */
10173d9b4925SMichael Tokarev                 qemu_iovec_memset(&hd_qiov, 0, 0, 512 * cur_nr_sectors);
10181490791fSaliguori             }
101968d000a3SKevin Wolf             break;
102068d000a3SKevin Wolf 
10216377af48SKevin Wolf         case QCOW2_CLUSTER_ZERO:
10223d9b4925SMichael Tokarev             qemu_iovec_memset(&hd_qiov, 0, 0, 512 * cur_nr_sectors);
10236377af48SKevin Wolf             break;
10246377af48SKevin Wolf 
102568d000a3SKevin Wolf         case QCOW2_CLUSTER_COMPRESSED:
1026585f8587Sbellard             /* add AIO support for compressed blocks ? */
1027c2bdd990SFrediano Ziglio             ret = qcow2_decompress_cluster(bs, cluster_offset);
10288af36488SKevin Wolf             if (ret < 0) {
10293fc48d09SFrediano Ziglio                 goto fail;
10308af36488SKevin Wolf             }
1031bd28f835SKevin Wolf 
103203396148SMichael Tokarev             qemu_iovec_from_buf(&hd_qiov, 0,
1033bd28f835SKevin Wolf                 s->cluster_cache + index_in_cluster * 512,
1034faf575c1SFrediano Ziglio                 512 * cur_nr_sectors);
103568d000a3SKevin Wolf             break;
103668d000a3SKevin Wolf 
103768d000a3SKevin Wolf         case QCOW2_CLUSTER_NORMAL:
1038c2bdd990SFrediano Ziglio             if ((cluster_offset & 511) != 0) {
10393fc48d09SFrediano Ziglio                 ret = -EIO;
10403fc48d09SFrediano Ziglio                 goto fail;
1041585f8587Sbellard             }
1042c87c0672Saliguori 
1043bd28f835SKevin Wolf             if (s->crypt_method) {
1044bd28f835SKevin Wolf                 /*
1045bd28f835SKevin Wolf                  * For encrypted images, read everything into a temporary
1046bd28f835SKevin Wolf                  * contiguous buffer on which the AES functions can work.
1047bd28f835SKevin Wolf                  */
10483fc48d09SFrediano Ziglio                 if (!cluster_data) {
10493fc48d09SFrediano Ziglio                     cluster_data =
1050dea43a65SFrediano Ziglio                         qemu_blockalign(bs, QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
1051bd28f835SKevin Wolf                 }
1052bd28f835SKevin Wolf 
1053faf575c1SFrediano Ziglio                 assert(cur_nr_sectors <=
1054bd28f835SKevin Wolf                     QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors);
10553fc48d09SFrediano Ziglio                 qemu_iovec_reset(&hd_qiov);
10563fc48d09SFrediano Ziglio                 qemu_iovec_add(&hd_qiov, cluster_data,
1057faf575c1SFrediano Ziglio                     512 * cur_nr_sectors);
1058bd28f835SKevin Wolf             }
1059bd28f835SKevin Wolf 
106066f82ceeSKevin Wolf             BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);
106168d100e9SKevin Wolf             qemu_co_mutex_unlock(&s->lock);
106268d100e9SKevin Wolf             ret = bdrv_co_readv(bs->file,
1063c2bdd990SFrediano Ziglio                                 (cluster_offset >> 9) + index_in_cluster,
10643fc48d09SFrediano Ziglio                                 cur_nr_sectors, &hd_qiov);
106568d100e9SKevin Wolf             qemu_co_mutex_lock(&s->lock);
106668d100e9SKevin Wolf             if (ret < 0) {
10673fc48d09SFrediano Ziglio                 goto fail;
1068585f8587Sbellard             }
1069faf575c1SFrediano Ziglio             if (s->crypt_method) {
10703fc48d09SFrediano Ziglio                 qcow2_encrypt_sectors(s, sector_num,  cluster_data,
10713fc48d09SFrediano Ziglio                     cluster_data, cur_nr_sectors, 0, &s->aes_decrypt_key);
107203396148SMichael Tokarev                 qemu_iovec_from_buf(qiov, bytes_done,
107303396148SMichael Tokarev                     cluster_data, 512 * cur_nr_sectors);
1074171e3d6bSKevin Wolf             }
107568d000a3SKevin Wolf             break;
107668d000a3SKevin Wolf 
107768d000a3SKevin Wolf         default:
107868d000a3SKevin Wolf             g_assert_not_reached();
107968d000a3SKevin Wolf             ret = -EIO;
108068d000a3SKevin Wolf             goto fail;
1081faf575c1SFrediano Ziglio         }
1082faf575c1SFrediano Ziglio 
10833fc48d09SFrediano Ziglio         remaining_sectors -= cur_nr_sectors;
10843fc48d09SFrediano Ziglio         sector_num += cur_nr_sectors;
10853fc48d09SFrediano Ziglio         bytes_done += cur_nr_sectors * 512;
10865ebaa27eSFrediano Ziglio     }
10873fc48d09SFrediano Ziglio     ret = 0;
1088f141eafeSaliguori 
10893fc48d09SFrediano Ziglio fail:
109068d100e9SKevin Wolf     qemu_co_mutex_unlock(&s->lock);
109168d100e9SKevin Wolf 
10923fc48d09SFrediano Ziglio     qemu_iovec_destroy(&hd_qiov);
1093dea43a65SFrediano Ziglio     qemu_vfree(cluster_data);
109468d100e9SKevin Wolf 
109568d100e9SKevin Wolf     return ret;
1096585f8587Sbellard }
1097585f8587Sbellard 
1098a968168cSDong Xu Wang static coroutine_fn int qcow2_co_writev(BlockDriverState *bs,
10993fc48d09SFrediano Ziglio                            int64_t sector_num,
11003fc48d09SFrediano Ziglio                            int remaining_sectors,
11013fc48d09SFrediano Ziglio                            QEMUIOVector *qiov)
1102585f8587Sbellard {
1103585f8587Sbellard     BDRVQcowState *s = bs->opaque;
1104585f8587Sbellard     int index_in_cluster;
110568d100e9SKevin Wolf     int ret;
1106faf575c1SFrediano Ziglio     int cur_nr_sectors; /* number of sectors in current iteration */
1107c2bdd990SFrediano Ziglio     uint64_t cluster_offset;
11083fc48d09SFrediano Ziglio     QEMUIOVector hd_qiov;
11093fc48d09SFrediano Ziglio     uint64_t bytes_done = 0;
11103fc48d09SFrediano Ziglio     uint8_t *cluster_data = NULL;
11118d2497c3SKevin Wolf     QCowL2Meta *l2meta = NULL;
1112c2271403SFrediano Ziglio 
11133cce16f4SKevin Wolf     trace_qcow2_writev_start_req(qemu_coroutine_self(), sector_num,
11143cce16f4SKevin Wolf                                  remaining_sectors);
11153cce16f4SKevin Wolf 
11163fc48d09SFrediano Ziglio     qemu_iovec_init(&hd_qiov, qiov->niov);
1117585f8587Sbellard 
11183fc48d09SFrediano Ziglio     s->cluster_cache_offset = -1; /* disable compressed cache */
11193fc48d09SFrediano Ziglio 
11203fc48d09SFrediano Ziglio     qemu_co_mutex_lock(&s->lock);
11213fc48d09SFrediano Ziglio 
11223fc48d09SFrediano Ziglio     while (remaining_sectors != 0) {
11233fc48d09SFrediano Ziglio 
1124f50f88b9SKevin Wolf         l2meta = NULL;
1125cf5c1a23SKevin Wolf 
11263cce16f4SKevin Wolf         trace_qcow2_writev_start_part(qemu_coroutine_self());
11273fc48d09SFrediano Ziglio         index_in_cluster = sector_num & (s->cluster_sectors - 1);
112816f0587eSHu Tao         cur_nr_sectors = remaining_sectors;
1129095a9c58Saliguori         if (s->crypt_method &&
113016f0587eSHu Tao             cur_nr_sectors >
113116f0587eSHu Tao             QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors - index_in_cluster) {
113216f0587eSHu Tao             cur_nr_sectors =
113316f0587eSHu Tao                 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors - index_in_cluster;
11345ebaa27eSFrediano Ziglio         }
1135095a9c58Saliguori 
11363fc48d09SFrediano Ziglio         ret = qcow2_alloc_cluster_offset(bs, sector_num << 9,
113716f0587eSHu Tao             &cur_nr_sectors, &cluster_offset, &l2meta);
1138148da7eaSKevin Wolf         if (ret < 0) {
11393fc48d09SFrediano Ziglio             goto fail;
1140148da7eaSKevin Wolf         }
1141148da7eaSKevin Wolf 
1142c2bdd990SFrediano Ziglio         assert((cluster_offset & 511) == 0);
1143148da7eaSKevin Wolf 
11443fc48d09SFrediano Ziglio         qemu_iovec_reset(&hd_qiov);
11451b093c48SMichael Tokarev         qemu_iovec_concat(&hd_qiov, qiov, bytes_done,
1146faf575c1SFrediano Ziglio             cur_nr_sectors * 512);
11476f5f060bSKevin Wolf 
1148585f8587Sbellard         if (s->crypt_method) {
11493fc48d09SFrediano Ziglio             if (!cluster_data) {
1150dea43a65SFrediano Ziglio                 cluster_data = qemu_blockalign(bs, QCOW_MAX_CRYPT_CLUSTERS *
1151095a9c58Saliguori                                                  s->cluster_size);
1152585f8587Sbellard             }
11536f5f060bSKevin Wolf 
11543fc48d09SFrediano Ziglio             assert(hd_qiov.size <=
11555ebaa27eSFrediano Ziglio                    QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
1156d5e6b161SMichael Tokarev             qemu_iovec_to_buf(&hd_qiov, 0, cluster_data, hd_qiov.size);
11576f5f060bSKevin Wolf 
11583fc48d09SFrediano Ziglio             qcow2_encrypt_sectors(s, sector_num, cluster_data,
11593fc48d09SFrediano Ziglio                 cluster_data, cur_nr_sectors, 1, &s->aes_encrypt_key);
11606f5f060bSKevin Wolf 
11613fc48d09SFrediano Ziglio             qemu_iovec_reset(&hd_qiov);
11623fc48d09SFrediano Ziglio             qemu_iovec_add(&hd_qiov, cluster_data,
1163faf575c1SFrediano Ziglio                 cur_nr_sectors * 512);
1164585f8587Sbellard         }
11656f5f060bSKevin Wolf 
1166231bb267SMax Reitz         ret = qcow2_pre_write_overlap_check(bs, 0,
1167cf93980eSMax Reitz                 cluster_offset + index_in_cluster * BDRV_SECTOR_SIZE,
1168cf93980eSMax Reitz                 cur_nr_sectors * BDRV_SECTOR_SIZE);
1169cf93980eSMax Reitz         if (ret < 0) {
1170cf93980eSMax Reitz             goto fail;
1171cf93980eSMax Reitz         }
1172cf93980eSMax Reitz 
117368d100e9SKevin Wolf         qemu_co_mutex_unlock(&s->lock);
117467a7a0ebSKevin Wolf         BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO);
11753cce16f4SKevin Wolf         trace_qcow2_writev_data(qemu_coroutine_self(),
11763cce16f4SKevin Wolf                                 (cluster_offset >> 9) + index_in_cluster);
117768d100e9SKevin Wolf         ret = bdrv_co_writev(bs->file,
1178c2bdd990SFrediano Ziglio                              (cluster_offset >> 9) + index_in_cluster,
11793fc48d09SFrediano Ziglio                              cur_nr_sectors, &hd_qiov);
118068d100e9SKevin Wolf         qemu_co_mutex_lock(&s->lock);
118168d100e9SKevin Wolf         if (ret < 0) {
11823fc48d09SFrediano Ziglio             goto fail;
1183171e3d6bSKevin Wolf         }
1184f141eafeSaliguori 
118588c6588cSKevin Wolf         while (l2meta != NULL) {
118688c6588cSKevin Wolf             QCowL2Meta *next;
118788c6588cSKevin Wolf 
1188cf5c1a23SKevin Wolf             ret = qcow2_alloc_cluster_link_l2(bs, l2meta);
1189faf575c1SFrediano Ziglio             if (ret < 0) {
11903fc48d09SFrediano Ziglio                 goto fail;
1191faf575c1SFrediano Ziglio             }
1192faf575c1SFrediano Ziglio 
11934e95314eSKevin Wolf             /* Take the request off the list of running requests */
11944e95314eSKevin Wolf             if (l2meta->nb_clusters != 0) {
11954e95314eSKevin Wolf                 QLIST_REMOVE(l2meta, next_in_flight);
11964e95314eSKevin Wolf             }
11974e95314eSKevin Wolf 
11984e95314eSKevin Wolf             qemu_co_queue_restart_all(&l2meta->dependent_requests);
11994e95314eSKevin Wolf 
120088c6588cSKevin Wolf             next = l2meta->next;
1201cf5c1a23SKevin Wolf             g_free(l2meta);
120288c6588cSKevin Wolf             l2meta = next;
1203f50f88b9SKevin Wolf         }
12040fa9131aSKevin Wolf 
12053fc48d09SFrediano Ziglio         remaining_sectors -= cur_nr_sectors;
12063fc48d09SFrediano Ziglio         sector_num += cur_nr_sectors;
12073fc48d09SFrediano Ziglio         bytes_done += cur_nr_sectors * 512;
12083cce16f4SKevin Wolf         trace_qcow2_writev_done_part(qemu_coroutine_self(), cur_nr_sectors);
12095ebaa27eSFrediano Ziglio     }
12103fc48d09SFrediano Ziglio     ret = 0;
1211faf575c1SFrediano Ziglio 
12123fc48d09SFrediano Ziglio fail:
12134e95314eSKevin Wolf     qemu_co_mutex_unlock(&s->lock);
12144e95314eSKevin Wolf 
121588c6588cSKevin Wolf     while (l2meta != NULL) {
121688c6588cSKevin Wolf         QCowL2Meta *next;
121788c6588cSKevin Wolf 
12184e95314eSKevin Wolf         if (l2meta->nb_clusters != 0) {
12194e95314eSKevin Wolf             QLIST_REMOVE(l2meta, next_in_flight);
12204e95314eSKevin Wolf         }
12214e95314eSKevin Wolf         qemu_co_queue_restart_all(&l2meta->dependent_requests);
122288c6588cSKevin Wolf 
122388c6588cSKevin Wolf         next = l2meta->next;
1224cf5c1a23SKevin Wolf         g_free(l2meta);
122588c6588cSKevin Wolf         l2meta = next;
1226cf5c1a23SKevin Wolf     }
12270fa9131aSKevin Wolf 
12283fc48d09SFrediano Ziglio     qemu_iovec_destroy(&hd_qiov);
1229dea43a65SFrediano Ziglio     qemu_vfree(cluster_data);
12303cce16f4SKevin Wolf     trace_qcow2_writev_done_req(qemu_coroutine_self(), ret);
123142496d62SKevin Wolf 
123268d100e9SKevin Wolf     return ret;
1233585f8587Sbellard }
1234585f8587Sbellard 
12357c80ab3fSJes Sorensen static void qcow2_close(BlockDriverState *bs)
1236585f8587Sbellard {
1237585f8587Sbellard     BDRVQcowState *s = bs->opaque;
12387267c094SAnthony Liguori     g_free(s->l1_table);
1239cf93980eSMax Reitz     /* else pre-write overlap checks in cache_destroy may crash */
1240cf93980eSMax Reitz     s->l1_table = NULL;
124129c1a730SKevin Wolf 
124227eb6c09SKevin Wolf     if (!(bs->open_flags & BDRV_O_INCOMING)) {
124329c1a730SKevin Wolf         qcow2_cache_flush(bs, s->l2_table_cache);
124429c1a730SKevin Wolf         qcow2_cache_flush(bs, s->refcount_block_cache);
124529c1a730SKevin Wolf 
1246c61d0004SStefan Hajnoczi         qcow2_mark_clean(bs);
124727eb6c09SKevin Wolf     }
1248c61d0004SStefan Hajnoczi 
124929c1a730SKevin Wolf     qcow2_cache_destroy(bs, s->l2_table_cache);
125029c1a730SKevin Wolf     qcow2_cache_destroy(bs, s->refcount_block_cache);
125129c1a730SKevin Wolf 
12526744cbabSKevin Wolf     g_free(s->unknown_header_fields);
125375bab85cSKevin Wolf     cleanup_unknown_header_ext(bs);
12546744cbabSKevin Wolf 
12557267c094SAnthony Liguori     g_free(s->cluster_cache);
1256dea43a65SFrediano Ziglio     qemu_vfree(s->cluster_data);
1257ed6ccf0fSKevin Wolf     qcow2_refcount_close(bs);
125828c1202bSLi Zhi Hui     qcow2_free_snapshots(bs);
1259585f8587Sbellard }
1260585f8587Sbellard 
12615a8a30dbSKevin Wolf static void qcow2_invalidate_cache(BlockDriverState *bs, Error **errp)
126206d9260fSAnthony Liguori {
126306d9260fSAnthony Liguori     BDRVQcowState *s = bs->opaque;
126406d9260fSAnthony Liguori     int flags = s->flags;
126506d9260fSAnthony Liguori     AES_KEY aes_encrypt_key;
126606d9260fSAnthony Liguori     AES_KEY aes_decrypt_key;
126706d9260fSAnthony Liguori     uint32_t crypt_method = 0;
1268acdfb480SKevin Wolf     QDict *options;
12695a8a30dbSKevin Wolf     Error *local_err = NULL;
12705a8a30dbSKevin Wolf     int ret;
127106d9260fSAnthony Liguori 
127206d9260fSAnthony Liguori     /*
127306d9260fSAnthony Liguori      * Backing files are read-only which makes all of their metadata immutable,
127406d9260fSAnthony Liguori      * that means we don't have to worry about reopening them here.
127506d9260fSAnthony Liguori      */
127606d9260fSAnthony Liguori 
127706d9260fSAnthony Liguori     if (s->crypt_method) {
127806d9260fSAnthony Liguori         crypt_method = s->crypt_method;
127906d9260fSAnthony Liguori         memcpy(&aes_encrypt_key, &s->aes_encrypt_key, sizeof(aes_encrypt_key));
128006d9260fSAnthony Liguori         memcpy(&aes_decrypt_key, &s->aes_decrypt_key, sizeof(aes_decrypt_key));
128106d9260fSAnthony Liguori     }
128206d9260fSAnthony Liguori 
128306d9260fSAnthony Liguori     qcow2_close(bs);
128406d9260fSAnthony Liguori 
12855a8a30dbSKevin Wolf     bdrv_invalidate_cache(bs->file, &local_err);
12865a8a30dbSKevin Wolf     if (local_err) {
12875a8a30dbSKevin Wolf         error_propagate(errp, local_err);
12885a8a30dbSKevin Wolf         return;
12895a8a30dbSKevin Wolf     }
12903456a8d1SKevin Wolf 
129106d9260fSAnthony Liguori     memset(s, 0, sizeof(BDRVQcowState));
1292d475e5acSKevin Wolf     options = qdict_clone_shallow(bs->options);
12935a8a30dbSKevin Wolf 
12945a8a30dbSKevin Wolf     ret = qcow2_open(bs, options, flags, &local_err);
12955a8a30dbSKevin Wolf     if (local_err) {
12965a8a30dbSKevin Wolf         error_setg(errp, "Could not reopen qcow2 layer: %s",
12975a8a30dbSKevin Wolf                    error_get_pretty(local_err));
12985a8a30dbSKevin Wolf         error_free(local_err);
12995a8a30dbSKevin Wolf         return;
13005a8a30dbSKevin Wolf     } else if (ret < 0) {
13015a8a30dbSKevin Wolf         error_setg_errno(errp, -ret, "Could not reopen qcow2 layer");
13025a8a30dbSKevin Wolf         return;
13035a8a30dbSKevin Wolf     }
1304acdfb480SKevin Wolf 
1305acdfb480SKevin Wolf     QDECREF(options);
130606d9260fSAnthony Liguori 
130706d9260fSAnthony Liguori     if (crypt_method) {
130806d9260fSAnthony Liguori         s->crypt_method = crypt_method;
130906d9260fSAnthony Liguori         memcpy(&s->aes_encrypt_key, &aes_encrypt_key, sizeof(aes_encrypt_key));
131006d9260fSAnthony Liguori         memcpy(&s->aes_decrypt_key, &aes_decrypt_key, sizeof(aes_decrypt_key));
131106d9260fSAnthony Liguori     }
131206d9260fSAnthony Liguori }
131306d9260fSAnthony Liguori 
1314e24e49e6SKevin Wolf static size_t header_ext_add(char *buf, uint32_t magic, const void *s,
1315e24e49e6SKevin Wolf     size_t len, size_t buflen)
1316756e6736SKevin Wolf {
1317e24e49e6SKevin Wolf     QCowExtension *ext_backing_fmt = (QCowExtension*) buf;
1318e24e49e6SKevin Wolf     size_t ext_len = sizeof(QCowExtension) + ((len + 7) & ~7);
1319756e6736SKevin Wolf 
1320e24e49e6SKevin Wolf     if (buflen < ext_len) {
1321756e6736SKevin Wolf         return -ENOSPC;
1322756e6736SKevin Wolf     }
1323756e6736SKevin Wolf 
1324e24e49e6SKevin Wolf     *ext_backing_fmt = (QCowExtension) {
1325e24e49e6SKevin Wolf         .magic  = cpu_to_be32(magic),
1326e24e49e6SKevin Wolf         .len    = cpu_to_be32(len),
1327e24e49e6SKevin Wolf     };
1328e24e49e6SKevin Wolf     memcpy(buf + sizeof(QCowExtension), s, len);
1329756e6736SKevin Wolf 
1330e24e49e6SKevin Wolf     return ext_len;
1331756e6736SKevin Wolf }
1332756e6736SKevin Wolf 
1333e24e49e6SKevin Wolf /*
1334e24e49e6SKevin Wolf  * Updates the qcow2 header, including the variable length parts of it, i.e.
1335e24e49e6SKevin Wolf  * the backing file name and all extensions. qcow2 was not designed to allow
1336e24e49e6SKevin Wolf  * such changes, so if we run out of space (we can only use the first cluster)
1337e24e49e6SKevin Wolf  * this function may fail.
1338e24e49e6SKevin Wolf  *
1339e24e49e6SKevin Wolf  * Returns 0 on success, -errno in error cases.
1340e24e49e6SKevin Wolf  */
1341e24e49e6SKevin Wolf int qcow2_update_header(BlockDriverState *bs)
1342e24e49e6SKevin Wolf {
1343e24e49e6SKevin Wolf     BDRVQcowState *s = bs->opaque;
1344e24e49e6SKevin Wolf     QCowHeader *header;
1345e24e49e6SKevin Wolf     char *buf;
1346e24e49e6SKevin Wolf     size_t buflen = s->cluster_size;
1347e24e49e6SKevin Wolf     int ret;
1348e24e49e6SKevin Wolf     uint64_t total_size;
1349e24e49e6SKevin Wolf     uint32_t refcount_table_clusters;
13506744cbabSKevin Wolf     size_t header_length;
135175bab85cSKevin Wolf     Qcow2UnknownHeaderExtension *uext;
1352e24e49e6SKevin Wolf 
1353e24e49e6SKevin Wolf     buf = qemu_blockalign(bs, buflen);
1354e24e49e6SKevin Wolf 
1355e24e49e6SKevin Wolf     /* Header structure */
1356e24e49e6SKevin Wolf     header = (QCowHeader*) buf;
1357e24e49e6SKevin Wolf 
1358e24e49e6SKevin Wolf     if (buflen < sizeof(*header)) {
1359e24e49e6SKevin Wolf         ret = -ENOSPC;
1360e24e49e6SKevin Wolf         goto fail;
1361756e6736SKevin Wolf     }
1362756e6736SKevin Wolf 
13636744cbabSKevin Wolf     header_length = sizeof(*header) + s->unknown_header_fields_size;
1364e24e49e6SKevin Wolf     total_size = bs->total_sectors * BDRV_SECTOR_SIZE;
1365e24e49e6SKevin Wolf     refcount_table_clusters = s->refcount_table_size >> (s->cluster_bits - 3);
1366e24e49e6SKevin Wolf 
1367e24e49e6SKevin Wolf     *header = (QCowHeader) {
13686744cbabSKevin Wolf         /* Version 2 fields */
1369e24e49e6SKevin Wolf         .magic                  = cpu_to_be32(QCOW_MAGIC),
13706744cbabSKevin Wolf         .version                = cpu_to_be32(s->qcow_version),
1371e24e49e6SKevin Wolf         .backing_file_offset    = 0,
1372e24e49e6SKevin Wolf         .backing_file_size      = 0,
1373e24e49e6SKevin Wolf         .cluster_bits           = cpu_to_be32(s->cluster_bits),
1374e24e49e6SKevin Wolf         .size                   = cpu_to_be64(total_size),
1375e24e49e6SKevin Wolf         .crypt_method           = cpu_to_be32(s->crypt_method_header),
1376e24e49e6SKevin Wolf         .l1_size                = cpu_to_be32(s->l1_size),
1377e24e49e6SKevin Wolf         .l1_table_offset        = cpu_to_be64(s->l1_table_offset),
1378e24e49e6SKevin Wolf         .refcount_table_offset  = cpu_to_be64(s->refcount_table_offset),
1379e24e49e6SKevin Wolf         .refcount_table_clusters = cpu_to_be32(refcount_table_clusters),
1380e24e49e6SKevin Wolf         .nb_snapshots           = cpu_to_be32(s->nb_snapshots),
1381e24e49e6SKevin Wolf         .snapshots_offset       = cpu_to_be64(s->snapshots_offset),
13826744cbabSKevin Wolf 
13836744cbabSKevin Wolf         /* Version 3 fields */
13846744cbabSKevin Wolf         .incompatible_features  = cpu_to_be64(s->incompatible_features),
13856744cbabSKevin Wolf         .compatible_features    = cpu_to_be64(s->compatible_features),
13866744cbabSKevin Wolf         .autoclear_features     = cpu_to_be64(s->autoclear_features),
1387b6481f37SMax Reitz         .refcount_order         = cpu_to_be32(s->refcount_order),
13886744cbabSKevin Wolf         .header_length          = cpu_to_be32(header_length),
1389e24e49e6SKevin Wolf     };
1390e24e49e6SKevin Wolf 
13916744cbabSKevin Wolf     /* For older versions, write a shorter header */
13926744cbabSKevin Wolf     switch (s->qcow_version) {
13936744cbabSKevin Wolf     case 2:
13946744cbabSKevin Wolf         ret = offsetof(QCowHeader, incompatible_features);
13956744cbabSKevin Wolf         break;
13966744cbabSKevin Wolf     case 3:
13976744cbabSKevin Wolf         ret = sizeof(*header);
13986744cbabSKevin Wolf         break;
13996744cbabSKevin Wolf     default:
1400b6c14762SJim Meyering         ret = -EINVAL;
1401b6c14762SJim Meyering         goto fail;
14026744cbabSKevin Wolf     }
14036744cbabSKevin Wolf 
14046744cbabSKevin Wolf     buf += ret;
14056744cbabSKevin Wolf     buflen -= ret;
14066744cbabSKevin Wolf     memset(buf, 0, buflen);
14076744cbabSKevin Wolf 
14086744cbabSKevin Wolf     /* Preserve any unknown field in the header */
14096744cbabSKevin Wolf     if (s->unknown_header_fields_size) {
14106744cbabSKevin Wolf         if (buflen < s->unknown_header_fields_size) {
14116744cbabSKevin Wolf             ret = -ENOSPC;
14126744cbabSKevin Wolf             goto fail;
14136744cbabSKevin Wolf         }
14146744cbabSKevin Wolf 
14156744cbabSKevin Wolf         memcpy(buf, s->unknown_header_fields, s->unknown_header_fields_size);
14166744cbabSKevin Wolf         buf += s->unknown_header_fields_size;
14176744cbabSKevin Wolf         buflen -= s->unknown_header_fields_size;
14186744cbabSKevin Wolf     }
1419e24e49e6SKevin Wolf 
1420e24e49e6SKevin Wolf     /* Backing file format header extension */
1421e24e49e6SKevin Wolf     if (*bs->backing_format) {
1422e24e49e6SKevin Wolf         ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BACKING_FORMAT,
1423e24e49e6SKevin Wolf                              bs->backing_format, strlen(bs->backing_format),
1424e24e49e6SKevin Wolf                              buflen);
1425756e6736SKevin Wolf         if (ret < 0) {
1426756e6736SKevin Wolf             goto fail;
1427756e6736SKevin Wolf         }
1428756e6736SKevin Wolf 
1429e24e49e6SKevin Wolf         buf += ret;
1430e24e49e6SKevin Wolf         buflen -= ret;
1431e24e49e6SKevin Wolf     }
1432756e6736SKevin Wolf 
1433cfcc4c62SKevin Wolf     /* Feature table */
1434cfcc4c62SKevin Wolf     Qcow2Feature features[] = {
1435c61d0004SStefan Hajnoczi         {
1436c61d0004SStefan Hajnoczi             .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
1437c61d0004SStefan Hajnoczi             .bit  = QCOW2_INCOMPAT_DIRTY_BITNR,
1438c61d0004SStefan Hajnoczi             .name = "dirty bit",
1439c61d0004SStefan Hajnoczi         },
1440bfe8043eSStefan Hajnoczi         {
144169c98726SMax Reitz             .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
144269c98726SMax Reitz             .bit  = QCOW2_INCOMPAT_CORRUPT_BITNR,
144369c98726SMax Reitz             .name = "corrupt bit",
144469c98726SMax Reitz         },
144569c98726SMax Reitz         {
1446bfe8043eSStefan Hajnoczi             .type = QCOW2_FEAT_TYPE_COMPATIBLE,
1447bfe8043eSStefan Hajnoczi             .bit  = QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR,
1448bfe8043eSStefan Hajnoczi             .name = "lazy refcounts",
1449bfe8043eSStefan Hajnoczi         },
1450cfcc4c62SKevin Wolf     };
1451cfcc4c62SKevin Wolf 
1452cfcc4c62SKevin Wolf     ret = header_ext_add(buf, QCOW2_EXT_MAGIC_FEATURE_TABLE,
1453cfcc4c62SKevin Wolf                          features, sizeof(features), buflen);
1454cfcc4c62SKevin Wolf     if (ret < 0) {
1455cfcc4c62SKevin Wolf         goto fail;
1456cfcc4c62SKevin Wolf     }
1457cfcc4c62SKevin Wolf     buf += ret;
1458cfcc4c62SKevin Wolf     buflen -= ret;
1459cfcc4c62SKevin Wolf 
146075bab85cSKevin Wolf     /* Keep unknown header extensions */
146175bab85cSKevin Wolf     QLIST_FOREACH(uext, &s->unknown_header_ext, next) {
146275bab85cSKevin Wolf         ret = header_ext_add(buf, uext->magic, uext->data, uext->len, buflen);
146375bab85cSKevin Wolf         if (ret < 0) {
146475bab85cSKevin Wolf             goto fail;
146575bab85cSKevin Wolf         }
146675bab85cSKevin Wolf 
146775bab85cSKevin Wolf         buf += ret;
146875bab85cSKevin Wolf         buflen -= ret;
146975bab85cSKevin Wolf     }
147075bab85cSKevin Wolf 
1471e24e49e6SKevin Wolf     /* End of header extensions */
1472e24e49e6SKevin Wolf     ret = header_ext_add(buf, QCOW2_EXT_MAGIC_END, NULL, 0, buflen);
1473756e6736SKevin Wolf     if (ret < 0) {
1474756e6736SKevin Wolf         goto fail;
1475756e6736SKevin Wolf     }
1476756e6736SKevin Wolf 
1477e24e49e6SKevin Wolf     buf += ret;
1478e24e49e6SKevin Wolf     buflen -= ret;
1479e24e49e6SKevin Wolf 
1480e24e49e6SKevin Wolf     /* Backing file name */
1481e24e49e6SKevin Wolf     if (*bs->backing_file) {
1482e24e49e6SKevin Wolf         size_t backing_file_len = strlen(bs->backing_file);
1483e24e49e6SKevin Wolf 
1484e24e49e6SKevin Wolf         if (buflen < backing_file_len) {
1485e24e49e6SKevin Wolf             ret = -ENOSPC;
1486e24e49e6SKevin Wolf             goto fail;
1487e24e49e6SKevin Wolf         }
1488e24e49e6SKevin Wolf 
148900ea1881SJim Meyering         /* Using strncpy is ok here, since buf is not NUL-terminated. */
1490e24e49e6SKevin Wolf         strncpy(buf, bs->backing_file, buflen);
1491e24e49e6SKevin Wolf 
1492e24e49e6SKevin Wolf         header->backing_file_offset = cpu_to_be64(buf - ((char*) header));
1493e24e49e6SKevin Wolf         header->backing_file_size   = cpu_to_be32(backing_file_len);
1494e24e49e6SKevin Wolf     }
1495e24e49e6SKevin Wolf 
1496e24e49e6SKevin Wolf     /* Write the new header */
1497e24e49e6SKevin Wolf     ret = bdrv_pwrite(bs->file, 0, header, s->cluster_size);
1498756e6736SKevin Wolf     if (ret < 0) {
1499756e6736SKevin Wolf         goto fail;
1500756e6736SKevin Wolf     }
1501756e6736SKevin Wolf 
1502756e6736SKevin Wolf     ret = 0;
1503756e6736SKevin Wolf fail:
1504e24e49e6SKevin Wolf     qemu_vfree(header);
1505756e6736SKevin Wolf     return ret;
1506756e6736SKevin Wolf }
1507756e6736SKevin Wolf 
1508756e6736SKevin Wolf static int qcow2_change_backing_file(BlockDriverState *bs,
1509756e6736SKevin Wolf     const char *backing_file, const char *backing_fmt)
1510756e6736SKevin Wolf {
1511e24e49e6SKevin Wolf     pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
1512e24e49e6SKevin Wolf     pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
1513e24e49e6SKevin Wolf 
1514e24e49e6SKevin Wolf     return qcow2_update_header(bs);
1515756e6736SKevin Wolf }
1516756e6736SKevin Wolf 
1517a35e1c17SKevin Wolf static int preallocate(BlockDriverState *bs)
1518a35e1c17SKevin Wolf {
1519a35e1c17SKevin Wolf     uint64_t nb_sectors;
1520a35e1c17SKevin Wolf     uint64_t offset;
1521060bee89SKevin Wolf     uint64_t host_offset = 0;
1522a35e1c17SKevin Wolf     int num;
1523148da7eaSKevin Wolf     int ret;
1524f50f88b9SKevin Wolf     QCowL2Meta *meta;
1525a35e1c17SKevin Wolf 
15267c2bbf4aSHu Tao     nb_sectors = bdrv_getlength(bs) >> BDRV_SECTOR_BITS;
1527a35e1c17SKevin Wolf     offset = 0;
1528a35e1c17SKevin Wolf 
1529a35e1c17SKevin Wolf     while (nb_sectors) {
15307c2bbf4aSHu Tao         num = MIN(nb_sectors, INT_MAX >> BDRV_SECTOR_BITS);
153116f0587eSHu Tao         ret = qcow2_alloc_cluster_offset(bs, offset, &num,
1532060bee89SKevin Wolf                                          &host_offset, &meta);
1533148da7eaSKevin Wolf         if (ret < 0) {
153419dbcbf7SKevin Wolf             return ret;
1535a35e1c17SKevin Wolf         }
1536a35e1c17SKevin Wolf 
15377c2bbf4aSHu Tao         if (meta != NULL) {
1538f50f88b9SKevin Wolf             ret = qcow2_alloc_cluster_link_l2(bs, meta);
153919dbcbf7SKevin Wolf             if (ret < 0) {
15407c2bbf4aSHu Tao                 qcow2_free_any_clusters(bs, meta->alloc_offset,
15417c2bbf4aSHu Tao                                         meta->nb_clusters, QCOW2_DISCARD_NEVER);
154219dbcbf7SKevin Wolf                 return ret;
1543a35e1c17SKevin Wolf             }
1544a35e1c17SKevin Wolf 
15457c2bbf4aSHu Tao             /* There are no dependent requests, but we need to remove our
15467c2bbf4aSHu Tao              * request from the list of in-flight requests */
15474e95314eSKevin Wolf             QLIST_REMOVE(meta, next_in_flight);
1548f50f88b9SKevin Wolf         }
1549f214978aSKevin Wolf 
1550a35e1c17SKevin Wolf         /* TODO Preallocate data if requested */
1551a35e1c17SKevin Wolf 
1552a35e1c17SKevin Wolf         nb_sectors -= num;
15537c2bbf4aSHu Tao         offset += num << BDRV_SECTOR_BITS;
1554a35e1c17SKevin Wolf     }
1555a35e1c17SKevin Wolf 
1556a35e1c17SKevin Wolf     /*
1557a35e1c17SKevin Wolf      * It is expected that the image file is large enough to actually contain
1558a35e1c17SKevin Wolf      * all of the allocated clusters (otherwise we get failing reads after
1559a35e1c17SKevin Wolf      * EOF). Extend the image to the last allocated sector.
1560a35e1c17SKevin Wolf      */
1561060bee89SKevin Wolf     if (host_offset != 0) {
15627c2bbf4aSHu Tao         uint8_t buf[BDRV_SECTOR_SIZE];
15637c2bbf4aSHu Tao         memset(buf, 0, BDRV_SECTOR_SIZE);
15647c2bbf4aSHu Tao         ret = bdrv_write(bs->file, (host_offset >> BDRV_SECTOR_BITS) + num - 1,
15657c2bbf4aSHu Tao                          buf, 1);
156619dbcbf7SKevin Wolf         if (ret < 0) {
156719dbcbf7SKevin Wolf             return ret;
156819dbcbf7SKevin Wolf         }
1569a35e1c17SKevin Wolf     }
1570a35e1c17SKevin Wolf 
1571a35e1c17SKevin Wolf     return 0;
1572a35e1c17SKevin Wolf }
1573a35e1c17SKevin Wolf 
15747c80ab3fSJes Sorensen static int qcow2_create2(const char *filename, int64_t total_size,
1575a9420734SKevin Wolf                          const char *backing_file, const char *backing_format,
1576a9420734SKevin Wolf                          int flags, size_t cluster_size, int prealloc,
15773ef6c40aSMax Reitz                          QEMUOptionParameter *options, int version,
15783ef6c40aSMax Reitz                          Error **errp)
1579a9420734SKevin Wolf {
15809b2260cbSDong Xu Wang     /* Calculate cluster_bits */
1581a9420734SKevin Wolf     int cluster_bits;
1582a9420734SKevin Wolf     cluster_bits = ffs(cluster_size) - 1;
1583a9420734SKevin Wolf     if (cluster_bits < MIN_CLUSTER_BITS || cluster_bits > MAX_CLUSTER_BITS ||
1584a9420734SKevin Wolf         (1 << cluster_bits) != cluster_size)
1585a9420734SKevin Wolf     {
15863ef6c40aSMax Reitz         error_setg(errp, "Cluster size must be a power of two between %d and "
15873ef6c40aSMax Reitz                    "%dk", 1 << MIN_CLUSTER_BITS, 1 << (MAX_CLUSTER_BITS - 10));
1588a9420734SKevin Wolf         return -EINVAL;
1589a9420734SKevin Wolf     }
1590a9420734SKevin Wolf 
1591a9420734SKevin Wolf     /*
1592a9420734SKevin Wolf      * Open the image file and write a minimal qcow2 header.
1593a9420734SKevin Wolf      *
1594a9420734SKevin Wolf      * We keep things simple and start with a zero-sized image. We also
1595a9420734SKevin Wolf      * do without refcount blocks or a L1 table for now. We'll fix the
1596a9420734SKevin Wolf      * inconsistency later.
1597a9420734SKevin Wolf      *
1598a9420734SKevin Wolf      * We do need a refcount table because growing the refcount table means
1599a9420734SKevin Wolf      * allocating two new refcount blocks - the seconds of which would be at
1600a9420734SKevin Wolf      * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
1601a9420734SKevin Wolf      * size for any qcow2 image.
1602a9420734SKevin Wolf      */
1603a9420734SKevin Wolf     BlockDriverState* bs;
1604f8413b3cSKevin Wolf     QCowHeader *header;
1605a9420734SKevin Wolf     uint8_t* refcount_table;
16063ef6c40aSMax Reitz     Error *local_err = NULL;
1607a9420734SKevin Wolf     int ret;
1608a9420734SKevin Wolf 
16093ef6c40aSMax Reitz     ret = bdrv_create_file(filename, options, &local_err);
1610a9420734SKevin Wolf     if (ret < 0) {
16113ef6c40aSMax Reitz         error_propagate(errp, local_err);
1612a9420734SKevin Wolf         return ret;
1613a9420734SKevin Wolf     }
1614a9420734SKevin Wolf 
16152e40134bSMax Reitz     bs = NULL;
16162e40134bSMax Reitz     ret = bdrv_open(&bs, filename, NULL, NULL, BDRV_O_RDWR | BDRV_O_PROTOCOL,
16172e40134bSMax Reitz                     NULL, &local_err);
1618a9420734SKevin Wolf     if (ret < 0) {
16193ef6c40aSMax Reitz         error_propagate(errp, local_err);
1620a9420734SKevin Wolf         return ret;
1621a9420734SKevin Wolf     }
1622a9420734SKevin Wolf 
1623a9420734SKevin Wolf     /* Write the header */
1624f8413b3cSKevin Wolf     QEMU_BUILD_BUG_ON((1 << MIN_CLUSTER_BITS) < sizeof(*header));
1625f8413b3cSKevin Wolf     header = g_malloc0(cluster_size);
1626f8413b3cSKevin Wolf     *header = (QCowHeader) {
1627f8413b3cSKevin Wolf         .magic                      = cpu_to_be32(QCOW_MAGIC),
1628f8413b3cSKevin Wolf         .version                    = cpu_to_be32(version),
1629f8413b3cSKevin Wolf         .cluster_bits               = cpu_to_be32(cluster_bits),
1630f8413b3cSKevin Wolf         .size                       = cpu_to_be64(0),
1631f8413b3cSKevin Wolf         .l1_table_offset            = cpu_to_be64(0),
1632f8413b3cSKevin Wolf         .l1_size                    = cpu_to_be32(0),
1633f8413b3cSKevin Wolf         .refcount_table_offset      = cpu_to_be64(cluster_size),
1634f8413b3cSKevin Wolf         .refcount_table_clusters    = cpu_to_be32(1),
1635f8413b3cSKevin Wolf         .refcount_order             = cpu_to_be32(3 + REFCOUNT_SHIFT),
1636f8413b3cSKevin Wolf         .header_length              = cpu_to_be32(sizeof(*header)),
1637f8413b3cSKevin Wolf     };
1638a9420734SKevin Wolf 
1639a9420734SKevin Wolf     if (flags & BLOCK_FLAG_ENCRYPT) {
1640f8413b3cSKevin Wolf         header->crypt_method = cpu_to_be32(QCOW_CRYPT_AES);
1641a9420734SKevin Wolf     } else {
1642f8413b3cSKevin Wolf         header->crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
1643a9420734SKevin Wolf     }
1644a9420734SKevin Wolf 
1645bfe8043eSStefan Hajnoczi     if (flags & BLOCK_FLAG_LAZY_REFCOUNTS) {
1646f8413b3cSKevin Wolf         header->compatible_features |=
1647bfe8043eSStefan Hajnoczi             cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS);
1648bfe8043eSStefan Hajnoczi     }
1649bfe8043eSStefan Hajnoczi 
1650f8413b3cSKevin Wolf     ret = bdrv_pwrite(bs, 0, header, cluster_size);
1651f8413b3cSKevin Wolf     g_free(header);
1652a9420734SKevin Wolf     if (ret < 0) {
16533ef6c40aSMax Reitz         error_setg_errno(errp, -ret, "Could not write qcow2 header");
1654a9420734SKevin Wolf         goto out;
1655a9420734SKevin Wolf     }
1656a9420734SKevin Wolf 
1657a9420734SKevin Wolf     /* Write an empty refcount table */
16587267c094SAnthony Liguori     refcount_table = g_malloc0(cluster_size);
1659a9420734SKevin Wolf     ret = bdrv_pwrite(bs, cluster_size, refcount_table, cluster_size);
16607267c094SAnthony Liguori     g_free(refcount_table);
1661a9420734SKevin Wolf 
1662a9420734SKevin Wolf     if (ret < 0) {
16633ef6c40aSMax Reitz         error_setg_errno(errp, -ret, "Could not write refcount table");
1664a9420734SKevin Wolf         goto out;
1665a9420734SKevin Wolf     }
1666a9420734SKevin Wolf 
1667f67503e5SMax Reitz     bdrv_unref(bs);
1668f67503e5SMax Reitz     bs = NULL;
1669a9420734SKevin Wolf 
1670a9420734SKevin Wolf     /*
1671a9420734SKevin Wolf      * And now open the image and make it consistent first (i.e. increase the
1672a9420734SKevin Wolf      * refcount of the cluster that is occupied by the header and the refcount
1673a9420734SKevin Wolf      * table)
1674a9420734SKevin Wolf      */
1675a9420734SKevin Wolf     BlockDriver* drv = bdrv_find_format("qcow2");
1676a9420734SKevin Wolf     assert(drv != NULL);
1677ddf5636dSMax Reitz     ret = bdrv_open(&bs, filename, NULL, NULL,
16783ef6c40aSMax Reitz         BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_NO_FLUSH, drv, &local_err);
1679a9420734SKevin Wolf     if (ret < 0) {
16803ef6c40aSMax Reitz         error_propagate(errp, local_err);
1681a9420734SKevin Wolf         goto out;
1682a9420734SKevin Wolf     }
1683a9420734SKevin Wolf 
1684a9420734SKevin Wolf     ret = qcow2_alloc_clusters(bs, 2 * cluster_size);
1685a9420734SKevin Wolf     if (ret < 0) {
16863ef6c40aSMax Reitz         error_setg_errno(errp, -ret, "Could not allocate clusters for qcow2 "
16873ef6c40aSMax Reitz                          "header and refcount table");
1688a9420734SKevin Wolf         goto out;
1689a9420734SKevin Wolf 
1690a9420734SKevin Wolf     } else if (ret != 0) {
1691a9420734SKevin Wolf         error_report("Huh, first cluster in empty image is already in use?");
1692a9420734SKevin Wolf         abort();
1693a9420734SKevin Wolf     }
1694a9420734SKevin Wolf 
1695a9420734SKevin Wolf     /* Okay, now that we have a valid image, let's give it the right size */
1696a9420734SKevin Wolf     ret = bdrv_truncate(bs, total_size * BDRV_SECTOR_SIZE);
1697a9420734SKevin Wolf     if (ret < 0) {
16983ef6c40aSMax Reitz         error_setg_errno(errp, -ret, "Could not resize image");
1699a9420734SKevin Wolf         goto out;
1700a9420734SKevin Wolf     }
1701a9420734SKevin Wolf 
1702a9420734SKevin Wolf     /* Want a backing file? There you go.*/
1703a9420734SKevin Wolf     if (backing_file) {
1704a9420734SKevin Wolf         ret = bdrv_change_backing_file(bs, backing_file, backing_format);
1705a9420734SKevin Wolf         if (ret < 0) {
17063ef6c40aSMax Reitz             error_setg_errno(errp, -ret, "Could not assign backing file '%s' "
17073ef6c40aSMax Reitz                              "with format '%s'", backing_file, backing_format);
1708a9420734SKevin Wolf             goto out;
1709a9420734SKevin Wolf         }
1710a9420734SKevin Wolf     }
1711a9420734SKevin Wolf 
1712a9420734SKevin Wolf     /* And if we're supposed to preallocate metadata, do that now */
1713a9420734SKevin Wolf     if (prealloc) {
171415552c4aSZhi Yong Wu         BDRVQcowState *s = bs->opaque;
171515552c4aSZhi Yong Wu         qemu_co_mutex_lock(&s->lock);
1716a9420734SKevin Wolf         ret = preallocate(bs);
171715552c4aSZhi Yong Wu         qemu_co_mutex_unlock(&s->lock);
1718a9420734SKevin Wolf         if (ret < 0) {
17193ef6c40aSMax Reitz             error_setg_errno(errp, -ret, "Could not preallocate metadata");
1720a9420734SKevin Wolf             goto out;
1721a9420734SKevin Wolf         }
1722a9420734SKevin Wolf     }
1723a9420734SKevin Wolf 
1724f67503e5SMax Reitz     bdrv_unref(bs);
1725f67503e5SMax Reitz     bs = NULL;
1726ba2ab2f2SMax Reitz 
1727ba2ab2f2SMax Reitz     /* Reopen the image without BDRV_O_NO_FLUSH to flush it before returning */
1728ddf5636dSMax Reitz     ret = bdrv_open(&bs, filename, NULL, NULL,
1729c9fbb99dSKevin Wolf                     BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_NO_BACKING,
1730c9fbb99dSKevin Wolf                     drv, &local_err);
173184d18f06SMarkus Armbruster     if (local_err) {
1732ba2ab2f2SMax Reitz         error_propagate(errp, local_err);
1733ba2ab2f2SMax Reitz         goto out;
1734ba2ab2f2SMax Reitz     }
1735ba2ab2f2SMax Reitz 
1736a9420734SKevin Wolf     ret = 0;
1737a9420734SKevin Wolf out:
1738f67503e5SMax Reitz     if (bs) {
17394f6fd349SFam Zheng         bdrv_unref(bs);
1740f67503e5SMax Reitz     }
1741a9420734SKevin Wolf     return ret;
1742a9420734SKevin Wolf }
1743de5f3f40SKevin Wolf 
1744d5124c00SMax Reitz static int qcow2_create(const char *filename, QEMUOptionParameter *options,
1745d5124c00SMax Reitz                         Error **errp)
1746de5f3f40SKevin Wolf {
1747de5f3f40SKevin Wolf     const char *backing_file = NULL;
1748de5f3f40SKevin Wolf     const char *backing_fmt = NULL;
1749de5f3f40SKevin Wolf     uint64_t sectors = 0;
1750de5f3f40SKevin Wolf     int flags = 0;
175199cce9faSKevin Wolf     size_t cluster_size = DEFAULT_CLUSTER_SIZE;
1752de5f3f40SKevin Wolf     int prealloc = 0;
17538ad1898cSKevin Wolf     int version = 3;
17543ef6c40aSMax Reitz     Error *local_err = NULL;
17553ef6c40aSMax Reitz     int ret;
1756de5f3f40SKevin Wolf 
1757de5f3f40SKevin Wolf     /* Read out options */
1758de5f3f40SKevin Wolf     while (options && options->name) {
1759de5f3f40SKevin Wolf         if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
1760de5f3f40SKevin Wolf             sectors = options->value.n / 512;
1761de5f3f40SKevin Wolf         } else if (!strcmp(options->name, BLOCK_OPT_BACKING_FILE)) {
1762de5f3f40SKevin Wolf             backing_file = options->value.s;
1763de5f3f40SKevin Wolf         } else if (!strcmp(options->name, BLOCK_OPT_BACKING_FMT)) {
1764de5f3f40SKevin Wolf             backing_fmt = options->value.s;
1765de5f3f40SKevin Wolf         } else if (!strcmp(options->name, BLOCK_OPT_ENCRYPT)) {
1766de5f3f40SKevin Wolf             flags |= options->value.n ? BLOCK_FLAG_ENCRYPT : 0;
1767de5f3f40SKevin Wolf         } else if (!strcmp(options->name, BLOCK_OPT_CLUSTER_SIZE)) {
1768de5f3f40SKevin Wolf             if (options->value.n) {
1769de5f3f40SKevin Wolf                 cluster_size = options->value.n;
1770de5f3f40SKevin Wolf             }
1771de5f3f40SKevin Wolf         } else if (!strcmp(options->name, BLOCK_OPT_PREALLOC)) {
1772de5f3f40SKevin Wolf             if (!options->value.s || !strcmp(options->value.s, "off")) {
1773de5f3f40SKevin Wolf                 prealloc = 0;
1774de5f3f40SKevin Wolf             } else if (!strcmp(options->value.s, "metadata")) {
1775de5f3f40SKevin Wolf                 prealloc = 1;
1776de5f3f40SKevin Wolf             } else {
17773ef6c40aSMax Reitz                 error_setg(errp, "Invalid preallocation mode: '%s'",
1778de5f3f40SKevin Wolf                            options->value.s);
1779de5f3f40SKevin Wolf                 return -EINVAL;
1780de5f3f40SKevin Wolf             }
17816744cbabSKevin Wolf         } else if (!strcmp(options->name, BLOCK_OPT_COMPAT_LEVEL)) {
17829117b477SKevin Wolf             if (!options->value.s) {
17839117b477SKevin Wolf                 /* keep the default */
17849117b477SKevin Wolf             } else if (!strcmp(options->value.s, "0.10")) {
17856744cbabSKevin Wolf                 version = 2;
17866744cbabSKevin Wolf             } else if (!strcmp(options->value.s, "1.1")) {
17876744cbabSKevin Wolf                 version = 3;
17886744cbabSKevin Wolf             } else {
17893ef6c40aSMax Reitz                 error_setg(errp, "Invalid compatibility level: '%s'",
17906744cbabSKevin Wolf                            options->value.s);
17916744cbabSKevin Wolf                 return -EINVAL;
17926744cbabSKevin Wolf             }
1793bfe8043eSStefan Hajnoczi         } else if (!strcmp(options->name, BLOCK_OPT_LAZY_REFCOUNTS)) {
1794bfe8043eSStefan Hajnoczi             flags |= options->value.n ? BLOCK_FLAG_LAZY_REFCOUNTS : 0;
1795de5f3f40SKevin Wolf         }
1796de5f3f40SKevin Wolf         options++;
1797de5f3f40SKevin Wolf     }
1798de5f3f40SKevin Wolf 
1799de5f3f40SKevin Wolf     if (backing_file && prealloc) {
18003ef6c40aSMax Reitz         error_setg(errp, "Backing file and preallocation cannot be used at "
18013ef6c40aSMax Reitz                    "the same time");
1802de5f3f40SKevin Wolf         return -EINVAL;
1803de5f3f40SKevin Wolf     }
1804de5f3f40SKevin Wolf 
1805bfe8043eSStefan Hajnoczi     if (version < 3 && (flags & BLOCK_FLAG_LAZY_REFCOUNTS)) {
18063ef6c40aSMax Reitz         error_setg(errp, "Lazy refcounts only supported with compatibility "
18073ef6c40aSMax Reitz                    "level 1.1 and above (use compat=1.1 or greater)");
1808bfe8043eSStefan Hajnoczi         return -EINVAL;
1809bfe8043eSStefan Hajnoczi     }
1810bfe8043eSStefan Hajnoczi 
18113ef6c40aSMax Reitz     ret = qcow2_create2(filename, sectors, backing_file, backing_fmt, flags,
18123ef6c40aSMax Reitz                         cluster_size, prealloc, options, version, &local_err);
181384d18f06SMarkus Armbruster     if (local_err) {
18143ef6c40aSMax Reitz         error_propagate(errp, local_err);
18153ef6c40aSMax Reitz     }
18163ef6c40aSMax Reitz     return ret;
1817de5f3f40SKevin Wolf }
1818de5f3f40SKevin Wolf 
1819621f0589SKevin Wolf static coroutine_fn int qcow2_co_write_zeroes(BlockDriverState *bs,
1820aa7bfbffSPeter Lieven     int64_t sector_num, int nb_sectors, BdrvRequestFlags flags)
1821621f0589SKevin Wolf {
1822621f0589SKevin Wolf     int ret;
1823621f0589SKevin Wolf     BDRVQcowState *s = bs->opaque;
1824621f0589SKevin Wolf 
1825621f0589SKevin Wolf     /* Emulate misaligned zero writes */
1826621f0589SKevin Wolf     if (sector_num % s->cluster_sectors || nb_sectors % s->cluster_sectors) {
1827621f0589SKevin Wolf         return -ENOTSUP;
1828621f0589SKevin Wolf     }
1829621f0589SKevin Wolf 
1830621f0589SKevin Wolf     /* Whatever is left can use real zero clusters */
1831621f0589SKevin Wolf     qemu_co_mutex_lock(&s->lock);
1832621f0589SKevin Wolf     ret = qcow2_zero_clusters(bs, sector_num << BDRV_SECTOR_BITS,
1833621f0589SKevin Wolf         nb_sectors);
1834621f0589SKevin Wolf     qemu_co_mutex_unlock(&s->lock);
1835621f0589SKevin Wolf 
1836621f0589SKevin Wolf     return ret;
1837621f0589SKevin Wolf }
1838621f0589SKevin Wolf 
18396db39ae2SPaolo Bonzini static coroutine_fn int qcow2_co_discard(BlockDriverState *bs,
18406db39ae2SPaolo Bonzini     int64_t sector_num, int nb_sectors)
18415ea929e3SKevin Wolf {
18426db39ae2SPaolo Bonzini     int ret;
18436db39ae2SPaolo Bonzini     BDRVQcowState *s = bs->opaque;
18446db39ae2SPaolo Bonzini 
18456db39ae2SPaolo Bonzini     qemu_co_mutex_lock(&s->lock);
18466db39ae2SPaolo Bonzini     ret = qcow2_discard_clusters(bs, sector_num << BDRV_SECTOR_BITS,
1847670df5e3SKevin Wolf         nb_sectors, QCOW2_DISCARD_REQUEST);
18486db39ae2SPaolo Bonzini     qemu_co_mutex_unlock(&s->lock);
18496db39ae2SPaolo Bonzini     return ret;
18505ea929e3SKevin Wolf }
18515ea929e3SKevin Wolf 
1852419b19d9SStefan Hajnoczi static int qcow2_truncate(BlockDriverState *bs, int64_t offset)
1853419b19d9SStefan Hajnoczi {
1854419b19d9SStefan Hajnoczi     BDRVQcowState *s = bs->opaque;
18552cf7cfa1SKevin Wolf     int64_t new_l1_size;
18562cf7cfa1SKevin Wolf     int ret;
1857419b19d9SStefan Hajnoczi 
1858419b19d9SStefan Hajnoczi     if (offset & 511) {
1859259b2173SKevin Wolf         error_report("The new size must be a multiple of 512");
1860419b19d9SStefan Hajnoczi         return -EINVAL;
1861419b19d9SStefan Hajnoczi     }
1862419b19d9SStefan Hajnoczi 
1863419b19d9SStefan Hajnoczi     /* cannot proceed if image has snapshots */
1864419b19d9SStefan Hajnoczi     if (s->nb_snapshots) {
1865259b2173SKevin Wolf         error_report("Can't resize an image which has snapshots");
1866419b19d9SStefan Hajnoczi         return -ENOTSUP;
1867419b19d9SStefan Hajnoczi     }
1868419b19d9SStefan Hajnoczi 
1869419b19d9SStefan Hajnoczi     /* shrinking is currently not supported */
1870419b19d9SStefan Hajnoczi     if (offset < bs->total_sectors * 512) {
1871259b2173SKevin Wolf         error_report("qcow2 doesn't support shrinking images yet");
1872419b19d9SStefan Hajnoczi         return -ENOTSUP;
1873419b19d9SStefan Hajnoczi     }
1874419b19d9SStefan Hajnoczi 
1875419b19d9SStefan Hajnoczi     new_l1_size = size_to_l1(s, offset);
187672893756SStefan Hajnoczi     ret = qcow2_grow_l1_table(bs, new_l1_size, true);
1877419b19d9SStefan Hajnoczi     if (ret < 0) {
1878419b19d9SStefan Hajnoczi         return ret;
1879419b19d9SStefan Hajnoczi     }
1880419b19d9SStefan Hajnoczi 
1881419b19d9SStefan Hajnoczi     /* write updated header.size */
1882419b19d9SStefan Hajnoczi     offset = cpu_to_be64(offset);
18838b3b7206SKevin Wolf     ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, size),
1884419b19d9SStefan Hajnoczi                            &offset, sizeof(uint64_t));
1885419b19d9SStefan Hajnoczi     if (ret < 0) {
1886419b19d9SStefan Hajnoczi         return ret;
1887419b19d9SStefan Hajnoczi     }
1888419b19d9SStefan Hajnoczi 
1889419b19d9SStefan Hajnoczi     s->l1_vm_state_index = new_l1_size;
1890419b19d9SStefan Hajnoczi     return 0;
1891419b19d9SStefan Hajnoczi }
1892419b19d9SStefan Hajnoczi 
189320d97356SBlue Swirl /* XXX: put compressed sectors first, then all the cluster aligned
189420d97356SBlue Swirl    tables to avoid losing bytes in alignment */
18957c80ab3fSJes Sorensen static int qcow2_write_compressed(BlockDriverState *bs, int64_t sector_num,
189620d97356SBlue Swirl                                   const uint8_t *buf, int nb_sectors)
189720d97356SBlue Swirl {
189820d97356SBlue Swirl     BDRVQcowState *s = bs->opaque;
189920d97356SBlue Swirl     z_stream strm;
190020d97356SBlue Swirl     int ret, out_len;
190120d97356SBlue Swirl     uint8_t *out_buf;
190220d97356SBlue Swirl     uint64_t cluster_offset;
190320d97356SBlue Swirl 
190420d97356SBlue Swirl     if (nb_sectors == 0) {
190520d97356SBlue Swirl         /* align end of file to a sector boundary to ease reading with
190620d97356SBlue Swirl            sector based I/Os */
190766f82ceeSKevin Wolf         cluster_offset = bdrv_getlength(bs->file);
190820d97356SBlue Swirl         cluster_offset = (cluster_offset + 511) & ~511;
190966f82ceeSKevin Wolf         bdrv_truncate(bs->file, cluster_offset);
191020d97356SBlue Swirl         return 0;
191120d97356SBlue Swirl     }
191220d97356SBlue Swirl 
1913f4d38befSStefan Hajnoczi     if (nb_sectors != s->cluster_sectors) {
1914f4d38befSStefan Hajnoczi         ret = -EINVAL;
1915f4d38befSStefan Hajnoczi 
1916f4d38befSStefan Hajnoczi         /* Zero-pad last write if image size is not cluster aligned */
1917f4d38befSStefan Hajnoczi         if (sector_num + nb_sectors == bs->total_sectors &&
1918f4d38befSStefan Hajnoczi             nb_sectors < s->cluster_sectors) {
1919f4d38befSStefan Hajnoczi             uint8_t *pad_buf = qemu_blockalign(bs, s->cluster_size);
1920f4d38befSStefan Hajnoczi             memset(pad_buf, 0, s->cluster_size);
1921f4d38befSStefan Hajnoczi             memcpy(pad_buf, buf, nb_sectors * BDRV_SECTOR_SIZE);
1922f4d38befSStefan Hajnoczi             ret = qcow2_write_compressed(bs, sector_num,
1923f4d38befSStefan Hajnoczi                                          pad_buf, s->cluster_sectors);
1924f4d38befSStefan Hajnoczi             qemu_vfree(pad_buf);
1925f4d38befSStefan Hajnoczi         }
1926f4d38befSStefan Hajnoczi         return ret;
1927f4d38befSStefan Hajnoczi     }
192820d97356SBlue Swirl 
19297267c094SAnthony Liguori     out_buf = g_malloc(s->cluster_size + (s->cluster_size / 1000) + 128);
193020d97356SBlue Swirl 
193120d97356SBlue Swirl     /* best compression, small window, no zlib header */
193220d97356SBlue Swirl     memset(&strm, 0, sizeof(strm));
193320d97356SBlue Swirl     ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
193420d97356SBlue Swirl                        Z_DEFLATED, -12,
193520d97356SBlue Swirl                        9, Z_DEFAULT_STRATEGY);
193620d97356SBlue Swirl     if (ret != 0) {
19378f1efd00SKevin Wolf         ret = -EINVAL;
19388f1efd00SKevin Wolf         goto fail;
193920d97356SBlue Swirl     }
194020d97356SBlue Swirl 
194120d97356SBlue Swirl     strm.avail_in = s->cluster_size;
194220d97356SBlue Swirl     strm.next_in = (uint8_t *)buf;
194320d97356SBlue Swirl     strm.avail_out = s->cluster_size;
194420d97356SBlue Swirl     strm.next_out = out_buf;
194520d97356SBlue Swirl 
194620d97356SBlue Swirl     ret = deflate(&strm, Z_FINISH);
194720d97356SBlue Swirl     if (ret != Z_STREAM_END && ret != Z_OK) {
194820d97356SBlue Swirl         deflateEnd(&strm);
19498f1efd00SKevin Wolf         ret = -EINVAL;
19508f1efd00SKevin Wolf         goto fail;
195120d97356SBlue Swirl     }
195220d97356SBlue Swirl     out_len = strm.next_out - out_buf;
195320d97356SBlue Swirl 
195420d97356SBlue Swirl     deflateEnd(&strm);
195520d97356SBlue Swirl 
195620d97356SBlue Swirl     if (ret != Z_STREAM_END || out_len >= s->cluster_size) {
195720d97356SBlue Swirl         /* could not compress: write normal cluster */
19588f1efd00SKevin Wolf         ret = bdrv_write(bs, sector_num, buf, s->cluster_sectors);
19598f1efd00SKevin Wolf         if (ret < 0) {
19608f1efd00SKevin Wolf             goto fail;
19618f1efd00SKevin Wolf         }
196220d97356SBlue Swirl     } else {
196320d97356SBlue Swirl         cluster_offset = qcow2_alloc_compressed_cluster_offset(bs,
196420d97356SBlue Swirl             sector_num << 9, out_len);
19658f1efd00SKevin Wolf         if (!cluster_offset) {
19668f1efd00SKevin Wolf             ret = -EIO;
19678f1efd00SKevin Wolf             goto fail;
19688f1efd00SKevin Wolf         }
196920d97356SBlue Swirl         cluster_offset &= s->cluster_offset_mask;
1970cf93980eSMax Reitz 
1971231bb267SMax Reitz         ret = qcow2_pre_write_overlap_check(bs, 0, cluster_offset, out_len);
1972cf93980eSMax Reitz         if (ret < 0) {
1973cf93980eSMax Reitz             goto fail;
1974cf93980eSMax Reitz         }
1975cf93980eSMax Reitz 
197666f82ceeSKevin Wolf         BLKDBG_EVENT(bs->file, BLKDBG_WRITE_COMPRESSED);
19778f1efd00SKevin Wolf         ret = bdrv_pwrite(bs->file, cluster_offset, out_buf, out_len);
19788f1efd00SKevin Wolf         if (ret < 0) {
19798f1efd00SKevin Wolf             goto fail;
198020d97356SBlue Swirl         }
198120d97356SBlue Swirl     }
198220d97356SBlue Swirl 
19838f1efd00SKevin Wolf     ret = 0;
19848f1efd00SKevin Wolf fail:
19857267c094SAnthony Liguori     g_free(out_buf);
19868f1efd00SKevin Wolf     return ret;
198720d97356SBlue Swirl }
198820d97356SBlue Swirl 
1989a968168cSDong Xu Wang static coroutine_fn int qcow2_co_flush_to_os(BlockDriverState *bs)
199020d97356SBlue Swirl {
199129c1a730SKevin Wolf     BDRVQcowState *s = bs->opaque;
199229c1a730SKevin Wolf     int ret;
199329c1a730SKevin Wolf 
19948b94ff85SPaolo Bonzini     qemu_co_mutex_lock(&s->lock);
199529c1a730SKevin Wolf     ret = qcow2_cache_flush(bs, s->l2_table_cache);
199629c1a730SKevin Wolf     if (ret < 0) {
1997c95de7e2SDong Xu Wang         qemu_co_mutex_unlock(&s->lock);
19988b94ff85SPaolo Bonzini         return ret;
199929c1a730SKevin Wolf     }
200029c1a730SKevin Wolf 
2001bfe8043eSStefan Hajnoczi     if (qcow2_need_accurate_refcounts(s)) {
200229c1a730SKevin Wolf         ret = qcow2_cache_flush(bs, s->refcount_block_cache);
200329c1a730SKevin Wolf         if (ret < 0) {
2004c95de7e2SDong Xu Wang             qemu_co_mutex_unlock(&s->lock);
20058b94ff85SPaolo Bonzini             return ret;
200629c1a730SKevin Wolf         }
2007bfe8043eSStefan Hajnoczi     }
20088b94ff85SPaolo Bonzini     qemu_co_mutex_unlock(&s->lock);
200929c1a730SKevin Wolf 
2010eb489bb1SKevin Wolf     return 0;
2011eb489bb1SKevin Wolf }
2012eb489bb1SKevin Wolf 
20137c80ab3fSJes Sorensen static int qcow2_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
201420d97356SBlue Swirl {
201520d97356SBlue Swirl     BDRVQcowState *s = bs->opaque;
201695de6d70SPaolo Bonzini     bdi->unallocated_blocks_are_zero = true;
201795de6d70SPaolo Bonzini     bdi->can_write_zeroes_with_unmap = (s->qcow_version >= 3);
201820d97356SBlue Swirl     bdi->cluster_size = s->cluster_size;
20197c80ab3fSJes Sorensen     bdi->vm_state_offset = qcow2_vm_state_offset(s);
202020d97356SBlue Swirl     return 0;
202120d97356SBlue Swirl }
202220d97356SBlue Swirl 
202337764dfbSMax Reitz static ImageInfoSpecific *qcow2_get_specific_info(BlockDriverState *bs)
202437764dfbSMax Reitz {
202537764dfbSMax Reitz     BDRVQcowState *s = bs->opaque;
202637764dfbSMax Reitz     ImageInfoSpecific *spec_info = g_new(ImageInfoSpecific, 1);
202737764dfbSMax Reitz 
202837764dfbSMax Reitz     *spec_info = (ImageInfoSpecific){
202937764dfbSMax Reitz         .kind  = IMAGE_INFO_SPECIFIC_KIND_QCOW2,
203037764dfbSMax Reitz         {
203137764dfbSMax Reitz             .qcow2 = g_new(ImageInfoSpecificQCow2, 1),
203237764dfbSMax Reitz         },
203337764dfbSMax Reitz     };
203437764dfbSMax Reitz     if (s->qcow_version == 2) {
203537764dfbSMax Reitz         *spec_info->qcow2 = (ImageInfoSpecificQCow2){
203637764dfbSMax Reitz             .compat = g_strdup("0.10"),
203737764dfbSMax Reitz         };
203837764dfbSMax Reitz     } else if (s->qcow_version == 3) {
203937764dfbSMax Reitz         *spec_info->qcow2 = (ImageInfoSpecificQCow2){
204037764dfbSMax Reitz             .compat             = g_strdup("1.1"),
204137764dfbSMax Reitz             .lazy_refcounts     = s->compatible_features &
204237764dfbSMax Reitz                                   QCOW2_COMPAT_LAZY_REFCOUNTS,
204337764dfbSMax Reitz             .has_lazy_refcounts = true,
204437764dfbSMax Reitz         };
204537764dfbSMax Reitz     }
204637764dfbSMax Reitz 
204737764dfbSMax Reitz     return spec_info;
204837764dfbSMax Reitz }
204937764dfbSMax Reitz 
205020d97356SBlue Swirl #if 0
205120d97356SBlue Swirl static void dump_refcounts(BlockDriverState *bs)
205220d97356SBlue Swirl {
205320d97356SBlue Swirl     BDRVQcowState *s = bs->opaque;
205420d97356SBlue Swirl     int64_t nb_clusters, k, k1, size;
205520d97356SBlue Swirl     int refcount;
205620d97356SBlue Swirl 
205766f82ceeSKevin Wolf     size = bdrv_getlength(bs->file);
205820d97356SBlue Swirl     nb_clusters = size_to_clusters(s, size);
205920d97356SBlue Swirl     for(k = 0; k < nb_clusters;) {
206020d97356SBlue Swirl         k1 = k;
206120d97356SBlue Swirl         refcount = get_refcount(bs, k);
206220d97356SBlue Swirl         k++;
206320d97356SBlue Swirl         while (k < nb_clusters && get_refcount(bs, k) == refcount)
206420d97356SBlue Swirl             k++;
20650bfcd599SBlue Swirl         printf("%" PRId64 ": refcount=%d nb=%" PRId64 "\n", k, refcount,
20660bfcd599SBlue Swirl                k - k1);
206720d97356SBlue Swirl     }
206820d97356SBlue Swirl }
206920d97356SBlue Swirl #endif
207020d97356SBlue Swirl 
2071cf8074b3SKevin Wolf static int qcow2_save_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
2072cf8074b3SKevin Wolf                               int64_t pos)
207320d97356SBlue Swirl {
207420d97356SBlue Swirl     BDRVQcowState *s = bs->opaque;
2075eedff66fSMax Reitz     int64_t total_sectors = bs->total_sectors;
207620d97356SBlue Swirl     int growable = bs->growable;
20776e13610aSMax Reitz     bool zero_beyond_eof = bs->zero_beyond_eof;
207820d97356SBlue Swirl     int ret;
207920d97356SBlue Swirl 
208066f82ceeSKevin Wolf     BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_SAVE);
208120d97356SBlue Swirl     bs->growable = 1;
20826e13610aSMax Reitz     bs->zero_beyond_eof = false;
20838d3b1a2dSKevin Wolf     ret = bdrv_pwritev(bs, qcow2_vm_state_offset(s) + pos, qiov);
208420d97356SBlue Swirl     bs->growable = growable;
20856e13610aSMax Reitz     bs->zero_beyond_eof = zero_beyond_eof;
208620d97356SBlue Swirl 
2087eedff66fSMax Reitz     /* bdrv_co_do_writev will have increased the total_sectors value to include
2088eedff66fSMax Reitz      * the VM state - the VM state is however not an actual part of the block
2089eedff66fSMax Reitz      * device, therefore, we need to restore the old value. */
2090eedff66fSMax Reitz     bs->total_sectors = total_sectors;
2091eedff66fSMax Reitz 
209220d97356SBlue Swirl     return ret;
209320d97356SBlue Swirl }
209420d97356SBlue Swirl 
20957c80ab3fSJes Sorensen static int qcow2_load_vmstate(BlockDriverState *bs, uint8_t *buf,
209620d97356SBlue Swirl                               int64_t pos, int size)
209720d97356SBlue Swirl {
209820d97356SBlue Swirl     BDRVQcowState *s = bs->opaque;
209920d97356SBlue Swirl     int growable = bs->growable;
21000d51b4deSAsias He     bool zero_beyond_eof = bs->zero_beyond_eof;
210120d97356SBlue Swirl     int ret;
210220d97356SBlue Swirl 
210366f82ceeSKevin Wolf     BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_LOAD);
210420d97356SBlue Swirl     bs->growable = 1;
21050d51b4deSAsias He     bs->zero_beyond_eof = false;
21067c80ab3fSJes Sorensen     ret = bdrv_pread(bs, qcow2_vm_state_offset(s) + pos, buf, size);
210720d97356SBlue Swirl     bs->growable = growable;
21080d51b4deSAsias He     bs->zero_beyond_eof = zero_beyond_eof;
210920d97356SBlue Swirl 
211020d97356SBlue Swirl     return ret;
211120d97356SBlue Swirl }
211220d97356SBlue Swirl 
21139296b3edSMax Reitz /*
21149296b3edSMax Reitz  * Downgrades an image's version. To achieve this, any incompatible features
21159296b3edSMax Reitz  * have to be removed.
21169296b3edSMax Reitz  */
21179296b3edSMax Reitz static int qcow2_downgrade(BlockDriverState *bs, int target_version)
21189296b3edSMax Reitz {
21199296b3edSMax Reitz     BDRVQcowState *s = bs->opaque;
21209296b3edSMax Reitz     int current_version = s->qcow_version;
21219296b3edSMax Reitz     int ret;
21229296b3edSMax Reitz 
21239296b3edSMax Reitz     if (target_version == current_version) {
21249296b3edSMax Reitz         return 0;
21259296b3edSMax Reitz     } else if (target_version > current_version) {
21269296b3edSMax Reitz         return -EINVAL;
21279296b3edSMax Reitz     } else if (target_version != 2) {
21289296b3edSMax Reitz         return -EINVAL;
21299296b3edSMax Reitz     }
21309296b3edSMax Reitz 
21319296b3edSMax Reitz     if (s->refcount_order != 4) {
21329296b3edSMax Reitz         /* we would have to convert the image to a refcount_order == 4 image
21339296b3edSMax Reitz          * here; however, since qemu (at the time of writing this) does not
21349296b3edSMax Reitz          * support anything different than 4 anyway, there is no point in doing
21359296b3edSMax Reitz          * so right now; however, we should error out (if qemu supports this in
21369296b3edSMax Reitz          * the future and this code has not been adapted) */
21379296b3edSMax Reitz         error_report("qcow2_downgrade: Image refcount orders other than 4 are "
21389296b3edSMax Reitz                      "currently not supported.");
21399296b3edSMax Reitz         return -ENOTSUP;
21409296b3edSMax Reitz     }
21419296b3edSMax Reitz 
21429296b3edSMax Reitz     /* clear incompatible features */
21439296b3edSMax Reitz     if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
21449296b3edSMax Reitz         ret = qcow2_mark_clean(bs);
21459296b3edSMax Reitz         if (ret < 0) {
21469296b3edSMax Reitz             return ret;
21479296b3edSMax Reitz         }
21489296b3edSMax Reitz     }
21499296b3edSMax Reitz 
21509296b3edSMax Reitz     /* with QCOW2_INCOMPAT_CORRUPT, it is pretty much impossible to get here in
21519296b3edSMax Reitz      * the first place; if that happens nonetheless, returning -ENOTSUP is the
21529296b3edSMax Reitz      * best thing to do anyway */
21539296b3edSMax Reitz 
21549296b3edSMax Reitz     if (s->incompatible_features) {
21559296b3edSMax Reitz         return -ENOTSUP;
21569296b3edSMax Reitz     }
21579296b3edSMax Reitz 
21589296b3edSMax Reitz     /* since we can ignore compatible features, we can set them to 0 as well */
21599296b3edSMax Reitz     s->compatible_features = 0;
21609296b3edSMax Reitz     /* if lazy refcounts have been used, they have already been fixed through
21619296b3edSMax Reitz      * clearing the dirty flag */
21629296b3edSMax Reitz 
21639296b3edSMax Reitz     /* clearing autoclear features is trivial */
21649296b3edSMax Reitz     s->autoclear_features = 0;
21659296b3edSMax Reitz 
21669296b3edSMax Reitz     ret = qcow2_expand_zero_clusters(bs);
21679296b3edSMax Reitz     if (ret < 0) {
21689296b3edSMax Reitz         return ret;
21699296b3edSMax Reitz     }
21709296b3edSMax Reitz 
21719296b3edSMax Reitz     s->qcow_version = target_version;
21729296b3edSMax Reitz     ret = qcow2_update_header(bs);
21739296b3edSMax Reitz     if (ret < 0) {
21749296b3edSMax Reitz         s->qcow_version = current_version;
21759296b3edSMax Reitz         return ret;
21769296b3edSMax Reitz     }
21779296b3edSMax Reitz     return 0;
21789296b3edSMax Reitz }
21799296b3edSMax Reitz 
21809296b3edSMax Reitz static int qcow2_amend_options(BlockDriverState *bs,
21819296b3edSMax Reitz                                QEMUOptionParameter *options)
21829296b3edSMax Reitz {
21839296b3edSMax Reitz     BDRVQcowState *s = bs->opaque;
21849296b3edSMax Reitz     int old_version = s->qcow_version, new_version = old_version;
21859296b3edSMax Reitz     uint64_t new_size = 0;
21869296b3edSMax Reitz     const char *backing_file = NULL, *backing_format = NULL;
21879296b3edSMax Reitz     bool lazy_refcounts = s->use_lazy_refcounts;
21889296b3edSMax Reitz     int ret;
21899296b3edSMax Reitz     int i;
21909296b3edSMax Reitz 
21919296b3edSMax Reitz     for (i = 0; options[i].name; i++)
21929296b3edSMax Reitz     {
21939296b3edSMax Reitz         if (!options[i].assigned) {
21949296b3edSMax Reitz             /* only change explicitly defined options */
21959296b3edSMax Reitz             continue;
21969296b3edSMax Reitz         }
21979296b3edSMax Reitz 
21989296b3edSMax Reitz         if (!strcmp(options[i].name, "compat")) {
21999296b3edSMax Reitz             if (!options[i].value.s) {
22009296b3edSMax Reitz                 /* preserve default */
22019296b3edSMax Reitz             } else if (!strcmp(options[i].value.s, "0.10")) {
22029296b3edSMax Reitz                 new_version = 2;
22039296b3edSMax Reitz             } else if (!strcmp(options[i].value.s, "1.1")) {
22049296b3edSMax Reitz                 new_version = 3;
22059296b3edSMax Reitz             } else {
22069296b3edSMax Reitz                 fprintf(stderr, "Unknown compatibility level %s.\n",
22079296b3edSMax Reitz                         options[i].value.s);
22089296b3edSMax Reitz                 return -EINVAL;
22099296b3edSMax Reitz             }
22109296b3edSMax Reitz         } else if (!strcmp(options[i].name, "preallocation")) {
22119296b3edSMax Reitz             fprintf(stderr, "Cannot change preallocation mode.\n");
22129296b3edSMax Reitz             return -ENOTSUP;
22139296b3edSMax Reitz         } else if (!strcmp(options[i].name, "size")) {
22149296b3edSMax Reitz             new_size = options[i].value.n;
22159296b3edSMax Reitz         } else if (!strcmp(options[i].name, "backing_file")) {
22169296b3edSMax Reitz             backing_file = options[i].value.s;
22179296b3edSMax Reitz         } else if (!strcmp(options[i].name, "backing_fmt")) {
22189296b3edSMax Reitz             backing_format = options[i].value.s;
22199296b3edSMax Reitz         } else if (!strcmp(options[i].name, "encryption")) {
22209296b3edSMax Reitz             if ((options[i].value.n != !!s->crypt_method)) {
22219296b3edSMax Reitz                 fprintf(stderr, "Changing the encryption flag is not "
22229296b3edSMax Reitz                         "supported.\n");
22239296b3edSMax Reitz                 return -ENOTSUP;
22249296b3edSMax Reitz             }
22259296b3edSMax Reitz         } else if (!strcmp(options[i].name, "cluster_size")) {
22269296b3edSMax Reitz             if (options[i].value.n != s->cluster_size) {
22279296b3edSMax Reitz                 fprintf(stderr, "Changing the cluster size is not "
22289296b3edSMax Reitz                         "supported.\n");
22299296b3edSMax Reitz                 return -ENOTSUP;
22309296b3edSMax Reitz             }
22319296b3edSMax Reitz         } else if (!strcmp(options[i].name, "lazy_refcounts")) {
22329296b3edSMax Reitz             lazy_refcounts = options[i].value.n;
22339296b3edSMax Reitz         } else {
22349296b3edSMax Reitz             /* if this assertion fails, this probably means a new option was
22359296b3edSMax Reitz              * added without having it covered here */
22369296b3edSMax Reitz             assert(false);
22379296b3edSMax Reitz         }
22389296b3edSMax Reitz     }
22399296b3edSMax Reitz 
22409296b3edSMax Reitz     if (new_version != old_version) {
22419296b3edSMax Reitz         if (new_version > old_version) {
22429296b3edSMax Reitz             /* Upgrade */
22439296b3edSMax Reitz             s->qcow_version = new_version;
22449296b3edSMax Reitz             ret = qcow2_update_header(bs);
22459296b3edSMax Reitz             if (ret < 0) {
22469296b3edSMax Reitz                 s->qcow_version = old_version;
22479296b3edSMax Reitz                 return ret;
22489296b3edSMax Reitz             }
22499296b3edSMax Reitz         } else {
22509296b3edSMax Reitz             ret = qcow2_downgrade(bs, new_version);
22519296b3edSMax Reitz             if (ret < 0) {
22529296b3edSMax Reitz                 return ret;
22539296b3edSMax Reitz             }
22549296b3edSMax Reitz         }
22559296b3edSMax Reitz     }
22569296b3edSMax Reitz 
22579296b3edSMax Reitz     if (backing_file || backing_format) {
22589296b3edSMax Reitz         ret = qcow2_change_backing_file(bs, backing_file ?: bs->backing_file,
22599296b3edSMax Reitz                                         backing_format ?: bs->backing_format);
22609296b3edSMax Reitz         if (ret < 0) {
22619296b3edSMax Reitz             return ret;
22629296b3edSMax Reitz         }
22639296b3edSMax Reitz     }
22649296b3edSMax Reitz 
22659296b3edSMax Reitz     if (s->use_lazy_refcounts != lazy_refcounts) {
22669296b3edSMax Reitz         if (lazy_refcounts) {
22679296b3edSMax Reitz             if (s->qcow_version < 3) {
22689296b3edSMax Reitz                 fprintf(stderr, "Lazy refcounts only supported with compatibility "
22699296b3edSMax Reitz                         "level 1.1 and above (use compat=1.1 or greater)\n");
22709296b3edSMax Reitz                 return -EINVAL;
22719296b3edSMax Reitz             }
22729296b3edSMax Reitz             s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
22739296b3edSMax Reitz             ret = qcow2_update_header(bs);
22749296b3edSMax Reitz             if (ret < 0) {
22759296b3edSMax Reitz                 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
22769296b3edSMax Reitz                 return ret;
22779296b3edSMax Reitz             }
22789296b3edSMax Reitz             s->use_lazy_refcounts = true;
22799296b3edSMax Reitz         } else {
22809296b3edSMax Reitz             /* make image clean first */
22819296b3edSMax Reitz             ret = qcow2_mark_clean(bs);
22829296b3edSMax Reitz             if (ret < 0) {
22839296b3edSMax Reitz                 return ret;
22849296b3edSMax Reitz             }
22859296b3edSMax Reitz             /* now disallow lazy refcounts */
22869296b3edSMax Reitz             s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
22879296b3edSMax Reitz             ret = qcow2_update_header(bs);
22889296b3edSMax Reitz             if (ret < 0) {
22899296b3edSMax Reitz                 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
22909296b3edSMax Reitz                 return ret;
22919296b3edSMax Reitz             }
22929296b3edSMax Reitz             s->use_lazy_refcounts = false;
22939296b3edSMax Reitz         }
22949296b3edSMax Reitz     }
22959296b3edSMax Reitz 
22969296b3edSMax Reitz     if (new_size) {
22979296b3edSMax Reitz         ret = bdrv_truncate(bs, new_size);
22989296b3edSMax Reitz         if (ret < 0) {
22999296b3edSMax Reitz             return ret;
23009296b3edSMax Reitz         }
23019296b3edSMax Reitz     }
23029296b3edSMax Reitz 
23039296b3edSMax Reitz     return 0;
23049296b3edSMax Reitz }
23059296b3edSMax Reitz 
23067c80ab3fSJes Sorensen static QEMUOptionParameter qcow2_create_options[] = {
230720d97356SBlue Swirl     {
230820d97356SBlue Swirl         .name = BLOCK_OPT_SIZE,
230920d97356SBlue Swirl         .type = OPT_SIZE,
231020d97356SBlue Swirl         .help = "Virtual disk size"
231120d97356SBlue Swirl     },
231220d97356SBlue Swirl     {
23136744cbabSKevin Wolf         .name = BLOCK_OPT_COMPAT_LEVEL,
23146744cbabSKevin Wolf         .type = OPT_STRING,
23156744cbabSKevin Wolf         .help = "Compatibility level (0.10 or 1.1)"
23166744cbabSKevin Wolf     },
23176744cbabSKevin Wolf     {
231820d97356SBlue Swirl         .name = BLOCK_OPT_BACKING_FILE,
231920d97356SBlue Swirl         .type = OPT_STRING,
232020d97356SBlue Swirl         .help = "File name of a base image"
232120d97356SBlue Swirl     },
232220d97356SBlue Swirl     {
232320d97356SBlue Swirl         .name = BLOCK_OPT_BACKING_FMT,
232420d97356SBlue Swirl         .type = OPT_STRING,
232520d97356SBlue Swirl         .help = "Image format of the base image"
232620d97356SBlue Swirl     },
232720d97356SBlue Swirl     {
232820d97356SBlue Swirl         .name = BLOCK_OPT_ENCRYPT,
232920d97356SBlue Swirl         .type = OPT_FLAG,
233020d97356SBlue Swirl         .help = "Encrypt the image"
233120d97356SBlue Swirl     },
233220d97356SBlue Swirl     {
233320d97356SBlue Swirl         .name = BLOCK_OPT_CLUSTER_SIZE,
233420d97356SBlue Swirl         .type = OPT_SIZE,
233599cce9faSKevin Wolf         .help = "qcow2 cluster size",
233699cce9faSKevin Wolf         .value = { .n = DEFAULT_CLUSTER_SIZE },
233720d97356SBlue Swirl     },
233820d97356SBlue Swirl     {
233920d97356SBlue Swirl         .name = BLOCK_OPT_PREALLOC,
234020d97356SBlue Swirl         .type = OPT_STRING,
234120d97356SBlue Swirl         .help = "Preallocation mode (allowed values: off, metadata)"
234220d97356SBlue Swirl     },
2343bfe8043eSStefan Hajnoczi     {
2344bfe8043eSStefan Hajnoczi         .name = BLOCK_OPT_LAZY_REFCOUNTS,
2345bfe8043eSStefan Hajnoczi         .type = OPT_FLAG,
2346bfe8043eSStefan Hajnoczi         .help = "Postpone refcount updates",
2347bfe8043eSStefan Hajnoczi     },
234820d97356SBlue Swirl     { NULL }
234920d97356SBlue Swirl };
235020d97356SBlue Swirl 
235120d97356SBlue Swirl static BlockDriver bdrv_qcow2 = {
235220d97356SBlue Swirl     .format_name        = "qcow2",
235320d97356SBlue Swirl     .instance_size      = sizeof(BDRVQcowState),
23547c80ab3fSJes Sorensen     .bdrv_probe         = qcow2_probe,
23557c80ab3fSJes Sorensen     .bdrv_open          = qcow2_open,
23567c80ab3fSJes Sorensen     .bdrv_close         = qcow2_close,
235721d82ac9SJeff Cody     .bdrv_reopen_prepare  = qcow2_reopen_prepare,
23587c80ab3fSJes Sorensen     .bdrv_create        = qcow2_create,
23593ac21627SPeter Lieven     .bdrv_has_zero_init = bdrv_has_zero_init_1,
2360b6b8a333SPaolo Bonzini     .bdrv_co_get_block_status = qcow2_co_get_block_status,
23617c80ab3fSJes Sorensen     .bdrv_set_key       = qcow2_set_key,
236220d97356SBlue Swirl 
236368d100e9SKevin Wolf     .bdrv_co_readv          = qcow2_co_readv,
236468d100e9SKevin Wolf     .bdrv_co_writev         = qcow2_co_writev,
2365eb489bb1SKevin Wolf     .bdrv_co_flush_to_os    = qcow2_co_flush_to_os,
2366419b19d9SStefan Hajnoczi 
2367621f0589SKevin Wolf     .bdrv_co_write_zeroes   = qcow2_co_write_zeroes,
23686db39ae2SPaolo Bonzini     .bdrv_co_discard        = qcow2_co_discard,
2369419b19d9SStefan Hajnoczi     .bdrv_truncate          = qcow2_truncate,
23707c80ab3fSJes Sorensen     .bdrv_write_compressed  = qcow2_write_compressed,
237120d97356SBlue Swirl 
237220d97356SBlue Swirl     .bdrv_snapshot_create   = qcow2_snapshot_create,
237320d97356SBlue Swirl     .bdrv_snapshot_goto     = qcow2_snapshot_goto,
237420d97356SBlue Swirl     .bdrv_snapshot_delete   = qcow2_snapshot_delete,
237520d97356SBlue Swirl     .bdrv_snapshot_list     = qcow2_snapshot_list,
237651ef6727Sedison     .bdrv_snapshot_load_tmp     = qcow2_snapshot_load_tmp,
23777c80ab3fSJes Sorensen     .bdrv_get_info      = qcow2_get_info,
237837764dfbSMax Reitz     .bdrv_get_specific_info = qcow2_get_specific_info,
237920d97356SBlue Swirl 
23807c80ab3fSJes Sorensen     .bdrv_save_vmstate    = qcow2_save_vmstate,
23817c80ab3fSJes Sorensen     .bdrv_load_vmstate    = qcow2_load_vmstate,
238220d97356SBlue Swirl 
238320d97356SBlue Swirl     .bdrv_change_backing_file   = qcow2_change_backing_file,
238420d97356SBlue Swirl 
2385d34682cdSKevin Wolf     .bdrv_refresh_limits        = qcow2_refresh_limits,
238606d9260fSAnthony Liguori     .bdrv_invalidate_cache      = qcow2_invalidate_cache,
238706d9260fSAnthony Liguori 
23887c80ab3fSJes Sorensen     .create_options = qcow2_create_options,
23897c80ab3fSJes Sorensen     .bdrv_check = qcow2_check,
23909296b3edSMax Reitz     .bdrv_amend_options = qcow2_amend_options,
239120d97356SBlue Swirl };
239220d97356SBlue Swirl 
23935efa9d5aSAnthony Liguori static void bdrv_qcow2_init(void)
23945efa9d5aSAnthony Liguori {
23955efa9d5aSAnthony Liguori     bdrv_register(&bdrv_qcow2);
23965efa9d5aSAnthony Liguori }
23975efa9d5aSAnthony Liguori 
23985efa9d5aSAnthony Liguori block_init(bdrv_qcow2_init);
2399