xref: /qemu/block/qcow2.c (revision 180e95265e87edcb457a9f92f844e4b08bcc60a0)
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"
341bd0e2d1SChunyan Liu #include "qemu/option_int.h"
35585f8587Sbellard 
36585f8587Sbellard /*
37585f8587Sbellard   Differences with QCOW:
38585f8587Sbellard 
39585f8587Sbellard   - Support for multiple incremental snapshots.
40585f8587Sbellard   - Memory management by reference counts.
41585f8587Sbellard   - Clusters which have a reference count of one have the bit
42585f8587Sbellard     QCOW_OFLAG_COPIED to optimize write performance.
43585f8587Sbellard   - Size of compressed clusters is stored in sectors to reduce bit usage
44585f8587Sbellard     in the cluster offsets.
45585f8587Sbellard   - Support for storing additional data (such as the VM state) in the
46585f8587Sbellard     snapshots.
47585f8587Sbellard   - If a backing store is used, the cluster size is not constrained
48585f8587Sbellard     (could be backported to QCOW).
49585f8587Sbellard   - L2 tables have always a size of one cluster.
50585f8587Sbellard */
51585f8587Sbellard 
529b80ddf3Saliguori 
539b80ddf3Saliguori typedef struct {
549b80ddf3Saliguori     uint32_t magic;
559b80ddf3Saliguori     uint32_t len;
56c4217f64SJeff Cody } QEMU_PACKED QCowExtension;
5721d82ac9SJeff Cody 
587c80ab3fSJes Sorensen #define  QCOW2_EXT_MAGIC_END 0
597c80ab3fSJes Sorensen #define  QCOW2_EXT_MAGIC_BACKING_FORMAT 0xE2792ACA
60cfcc4c62SKevin Wolf #define  QCOW2_EXT_MAGIC_FEATURE_TABLE 0x6803f857
619b80ddf3Saliguori 
627c80ab3fSJes Sorensen static int qcow2_probe(const uint8_t *buf, int buf_size, const char *filename)
63585f8587Sbellard {
64585f8587Sbellard     const QCowHeader *cow_header = (const void *)buf;
65585f8587Sbellard 
66585f8587Sbellard     if (buf_size >= sizeof(QCowHeader) &&
67585f8587Sbellard         be32_to_cpu(cow_header->magic) == QCOW_MAGIC &&
686744cbabSKevin Wolf         be32_to_cpu(cow_header->version) >= 2)
69585f8587Sbellard         return 100;
70585f8587Sbellard     else
71585f8587Sbellard         return 0;
72585f8587Sbellard }
73585f8587Sbellard 
749b80ddf3Saliguori 
759b80ddf3Saliguori /*
769b80ddf3Saliguori  * read qcow2 extension and fill bs
779b80ddf3Saliguori  * start reading from start_offset
789b80ddf3Saliguori  * finish reading upon magic of value 0 or when end_offset reached
799b80ddf3Saliguori  * unknown magic is skipped (future extension this version knows nothing about)
809b80ddf3Saliguori  * return 0 upon success, non-0 otherwise
819b80ddf3Saliguori  */
827c80ab3fSJes Sorensen static int qcow2_read_extensions(BlockDriverState *bs, uint64_t start_offset,
833ef6c40aSMax Reitz                                  uint64_t end_offset, void **p_feature_table,
843ef6c40aSMax Reitz                                  Error **errp)
859b80ddf3Saliguori {
8675bab85cSKevin Wolf     BDRVQcowState *s = bs->opaque;
879b80ddf3Saliguori     QCowExtension ext;
889b80ddf3Saliguori     uint64_t offset;
8975bab85cSKevin Wolf     int ret;
909b80ddf3Saliguori 
919b80ddf3Saliguori #ifdef DEBUG_EXT
927c80ab3fSJes Sorensen     printf("qcow2_read_extensions: start=%ld end=%ld\n", start_offset, end_offset);
939b80ddf3Saliguori #endif
949b80ddf3Saliguori     offset = start_offset;
959b80ddf3Saliguori     while (offset < end_offset) {
969b80ddf3Saliguori 
979b80ddf3Saliguori #ifdef DEBUG_EXT
989b80ddf3Saliguori         /* Sanity check */
999b80ddf3Saliguori         if (offset > s->cluster_size)
1007c80ab3fSJes Sorensen             printf("qcow2_read_extension: suspicious offset %lu\n", offset);
1019b80ddf3Saliguori 
1029b2260cbSDong Xu Wang         printf("attempting to read extended header in offset %lu\n", offset);
1039b80ddf3Saliguori #endif
1049b80ddf3Saliguori 
1053ef6c40aSMax Reitz         ret = bdrv_pread(bs->file, offset, &ext, sizeof(ext));
1063ef6c40aSMax Reitz         if (ret < 0) {
1073ef6c40aSMax Reitz             error_setg_errno(errp, -ret, "qcow2_read_extension: ERROR: "
1083ef6c40aSMax Reitz                              "pread fail from offset %" PRIu64, offset);
1099b80ddf3Saliguori             return 1;
1109b80ddf3Saliguori         }
1119b80ddf3Saliguori         be32_to_cpus(&ext.magic);
1129b80ddf3Saliguori         be32_to_cpus(&ext.len);
1139b80ddf3Saliguori         offset += sizeof(ext);
1149b80ddf3Saliguori #ifdef DEBUG_EXT
1159b80ddf3Saliguori         printf("ext.magic = 0x%x\n", ext.magic);
1169b80ddf3Saliguori #endif
11764ca6aeeSKevin Wolf         if (ext.len > end_offset - offset) {
1183ef6c40aSMax Reitz             error_setg(errp, "Header extension too large");
11964ca6aeeSKevin Wolf             return -EINVAL;
12064ca6aeeSKevin Wolf         }
12164ca6aeeSKevin Wolf 
1229b80ddf3Saliguori         switch (ext.magic) {
1237c80ab3fSJes Sorensen         case QCOW2_EXT_MAGIC_END:
1249b80ddf3Saliguori             return 0;
125f965509cSaliguori 
1267c80ab3fSJes Sorensen         case QCOW2_EXT_MAGIC_BACKING_FORMAT:
127f965509cSaliguori             if (ext.len >= sizeof(bs->backing_format)) {
128521b2b5dSMax Reitz                 error_setg(errp, "ERROR: ext_backing_format: len=%" PRIu32
129521b2b5dSMax Reitz                            " too large (>=%zu)", ext.len,
130521b2b5dSMax Reitz                            sizeof(bs->backing_format));
131f965509cSaliguori                 return 2;
132f965509cSaliguori             }
1333ef6c40aSMax Reitz             ret = bdrv_pread(bs->file, offset, bs->backing_format, ext.len);
1343ef6c40aSMax Reitz             if (ret < 0) {
1353ef6c40aSMax Reitz                 error_setg_errno(errp, -ret, "ERROR: ext_backing_format: "
1363ef6c40aSMax Reitz                                  "Could not read format name");
137f965509cSaliguori                 return 3;
1383ef6c40aSMax Reitz             }
139f965509cSaliguori             bs->backing_format[ext.len] = '\0';
140f965509cSaliguori #ifdef DEBUG_EXT
141f965509cSaliguori             printf("Qcow2: Got format extension %s\n", bs->backing_format);
142f965509cSaliguori #endif
143f965509cSaliguori             break;
144f965509cSaliguori 
145cfcc4c62SKevin Wolf         case QCOW2_EXT_MAGIC_FEATURE_TABLE:
146cfcc4c62SKevin Wolf             if (p_feature_table != NULL) {
147cfcc4c62SKevin Wolf                 void* feature_table = g_malloc0(ext.len + 2 * sizeof(Qcow2Feature));
148cfcc4c62SKevin Wolf                 ret = bdrv_pread(bs->file, offset , feature_table, ext.len);
149cfcc4c62SKevin Wolf                 if (ret < 0) {
1503ef6c40aSMax Reitz                     error_setg_errno(errp, -ret, "ERROR: ext_feature_table: "
1513ef6c40aSMax Reitz                                      "Could not read table");
152cfcc4c62SKevin Wolf                     return ret;
153cfcc4c62SKevin Wolf                 }
154cfcc4c62SKevin Wolf 
155cfcc4c62SKevin Wolf                 *p_feature_table = feature_table;
156cfcc4c62SKevin Wolf             }
157cfcc4c62SKevin Wolf             break;
158cfcc4c62SKevin Wolf 
1599b80ddf3Saliguori         default:
16075bab85cSKevin Wolf             /* unknown magic - save it in case we need to rewrite the header */
16175bab85cSKevin Wolf             {
16275bab85cSKevin Wolf                 Qcow2UnknownHeaderExtension *uext;
16375bab85cSKevin Wolf 
16475bab85cSKevin Wolf                 uext = g_malloc0(sizeof(*uext)  + ext.len);
16575bab85cSKevin Wolf                 uext->magic = ext.magic;
16675bab85cSKevin Wolf                 uext->len = ext.len;
16775bab85cSKevin Wolf                 QLIST_INSERT_HEAD(&s->unknown_header_ext, uext, next);
16875bab85cSKevin Wolf 
16975bab85cSKevin Wolf                 ret = bdrv_pread(bs->file, offset , uext->data, uext->len);
17075bab85cSKevin Wolf                 if (ret < 0) {
1713ef6c40aSMax Reitz                     error_setg_errno(errp, -ret, "ERROR: unknown extension: "
1723ef6c40aSMax Reitz                                      "Could not read data");
17375bab85cSKevin Wolf                     return ret;
17475bab85cSKevin Wolf                 }
17575bab85cSKevin Wolf             }
1769b80ddf3Saliguori             break;
1779b80ddf3Saliguori         }
178fd29b4bbSKevin Wolf 
179fd29b4bbSKevin Wolf         offset += ((ext.len + 7) & ~7);
1809b80ddf3Saliguori     }
1819b80ddf3Saliguori 
1829b80ddf3Saliguori     return 0;
1839b80ddf3Saliguori }
1849b80ddf3Saliguori 
18575bab85cSKevin Wolf static void cleanup_unknown_header_ext(BlockDriverState *bs)
18675bab85cSKevin Wolf {
18775bab85cSKevin Wolf     BDRVQcowState *s = bs->opaque;
18875bab85cSKevin Wolf     Qcow2UnknownHeaderExtension *uext, *next;
18975bab85cSKevin Wolf 
19075bab85cSKevin Wolf     QLIST_FOREACH_SAFE(uext, &s->unknown_header_ext, next, next) {
19175bab85cSKevin Wolf         QLIST_REMOVE(uext, next);
19275bab85cSKevin Wolf         g_free(uext);
19375bab85cSKevin Wolf     }
19475bab85cSKevin Wolf }
1959b80ddf3Saliguori 
1963ef6c40aSMax Reitz static void GCC_FMT_ATTR(3, 4) report_unsupported(BlockDriverState *bs,
1973ef6c40aSMax Reitz     Error **errp, const char *fmt, ...)
1986744cbabSKevin Wolf {
1996744cbabSKevin Wolf     char msg[64];
2006744cbabSKevin Wolf     va_list ap;
2016744cbabSKevin Wolf 
2026744cbabSKevin Wolf     va_start(ap, fmt);
2036744cbabSKevin Wolf     vsnprintf(msg, sizeof(msg), fmt, ap);
2046744cbabSKevin Wolf     va_end(ap);
2056744cbabSKevin Wolf 
2063ef6c40aSMax Reitz     error_set(errp, QERR_UNKNOWN_BLOCK_FORMAT_FEATURE, bs->device_name, "qcow2",
2073ef6c40aSMax Reitz               msg);
2086744cbabSKevin Wolf }
2096744cbabSKevin Wolf 
210cfcc4c62SKevin Wolf static void report_unsupported_feature(BlockDriverState *bs,
2113ef6c40aSMax Reitz     Error **errp, Qcow2Feature *table, uint64_t mask)
212cfcc4c62SKevin Wolf {
21312ac6d3dSKevin Wolf     char *features = g_strdup("");
21412ac6d3dSKevin Wolf     char *old;
21512ac6d3dSKevin Wolf 
216cfcc4c62SKevin Wolf     while (table && table->name[0] != '\0') {
217cfcc4c62SKevin Wolf         if (table->type == QCOW2_FEAT_TYPE_INCOMPATIBLE) {
21812ac6d3dSKevin Wolf             if (mask & (1ULL << table->bit)) {
21912ac6d3dSKevin Wolf                 old = features;
22012ac6d3dSKevin Wolf                 features = g_strdup_printf("%s%s%.46s", old, *old ? ", " : "",
22112ac6d3dSKevin Wolf                                            table->name);
22212ac6d3dSKevin Wolf                 g_free(old);
22312ac6d3dSKevin Wolf                 mask &= ~(1ULL << table->bit);
224cfcc4c62SKevin Wolf             }
225cfcc4c62SKevin Wolf         }
226cfcc4c62SKevin Wolf         table++;
227cfcc4c62SKevin Wolf     }
228cfcc4c62SKevin Wolf 
229cfcc4c62SKevin Wolf     if (mask) {
23012ac6d3dSKevin Wolf         old = features;
23112ac6d3dSKevin Wolf         features = g_strdup_printf("%s%sUnknown incompatible feature: %" PRIx64,
23212ac6d3dSKevin Wolf                                    old, *old ? ", " : "", mask);
23312ac6d3dSKevin Wolf         g_free(old);
234cfcc4c62SKevin Wolf     }
23512ac6d3dSKevin Wolf 
23612ac6d3dSKevin Wolf     report_unsupported(bs, errp, "%s", features);
23712ac6d3dSKevin Wolf     g_free(features);
238cfcc4c62SKevin Wolf }
239cfcc4c62SKevin Wolf 
240c61d0004SStefan Hajnoczi /*
241bfe8043eSStefan Hajnoczi  * Sets the dirty bit and flushes afterwards if necessary.
242bfe8043eSStefan Hajnoczi  *
243bfe8043eSStefan Hajnoczi  * The incompatible_features bit is only set if the image file header was
244bfe8043eSStefan Hajnoczi  * updated successfully.  Therefore it is not required to check the return
245bfe8043eSStefan Hajnoczi  * value of this function.
246bfe8043eSStefan Hajnoczi  */
247280d3735SKevin Wolf int qcow2_mark_dirty(BlockDriverState *bs)
248bfe8043eSStefan Hajnoczi {
249bfe8043eSStefan Hajnoczi     BDRVQcowState *s = bs->opaque;
250bfe8043eSStefan Hajnoczi     uint64_t val;
251bfe8043eSStefan Hajnoczi     int ret;
252bfe8043eSStefan Hajnoczi 
253bfe8043eSStefan Hajnoczi     assert(s->qcow_version >= 3);
254bfe8043eSStefan Hajnoczi 
255bfe8043eSStefan Hajnoczi     if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
256bfe8043eSStefan Hajnoczi         return 0; /* already dirty */
257bfe8043eSStefan Hajnoczi     }
258bfe8043eSStefan Hajnoczi 
259bfe8043eSStefan Hajnoczi     val = cpu_to_be64(s->incompatible_features | QCOW2_INCOMPAT_DIRTY);
260bfe8043eSStefan Hajnoczi     ret = bdrv_pwrite(bs->file, offsetof(QCowHeader, incompatible_features),
261bfe8043eSStefan Hajnoczi                       &val, sizeof(val));
262bfe8043eSStefan Hajnoczi     if (ret < 0) {
263bfe8043eSStefan Hajnoczi         return ret;
264bfe8043eSStefan Hajnoczi     }
265bfe8043eSStefan Hajnoczi     ret = bdrv_flush(bs->file);
266bfe8043eSStefan Hajnoczi     if (ret < 0) {
267bfe8043eSStefan Hajnoczi         return ret;
268bfe8043eSStefan Hajnoczi     }
269bfe8043eSStefan Hajnoczi 
270bfe8043eSStefan Hajnoczi     /* Only treat image as dirty if the header was updated successfully */
271bfe8043eSStefan Hajnoczi     s->incompatible_features |= QCOW2_INCOMPAT_DIRTY;
272bfe8043eSStefan Hajnoczi     return 0;
273bfe8043eSStefan Hajnoczi }
274bfe8043eSStefan Hajnoczi 
275bfe8043eSStefan Hajnoczi /*
276c61d0004SStefan Hajnoczi  * Clears the dirty bit and flushes before if necessary.  Only call this
277c61d0004SStefan Hajnoczi  * function when there are no pending requests, it does not guard against
278c61d0004SStefan Hajnoczi  * concurrent requests dirtying the image.
279c61d0004SStefan Hajnoczi  */
280c61d0004SStefan Hajnoczi static int qcow2_mark_clean(BlockDriverState *bs)
281c61d0004SStefan Hajnoczi {
282c61d0004SStefan Hajnoczi     BDRVQcowState *s = bs->opaque;
283c61d0004SStefan Hajnoczi 
284c61d0004SStefan Hajnoczi     if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
2854c2e5f8fSKevin Wolf         int ret;
2864c2e5f8fSKevin Wolf 
2874c2e5f8fSKevin Wolf         s->incompatible_features &= ~QCOW2_INCOMPAT_DIRTY;
2884c2e5f8fSKevin Wolf 
2894c2e5f8fSKevin Wolf         ret = bdrv_flush(bs);
290c61d0004SStefan Hajnoczi         if (ret < 0) {
291c61d0004SStefan Hajnoczi             return ret;
292c61d0004SStefan Hajnoczi         }
293c61d0004SStefan Hajnoczi 
294c61d0004SStefan Hajnoczi         return qcow2_update_header(bs);
295c61d0004SStefan Hajnoczi     }
296c61d0004SStefan Hajnoczi     return 0;
297c61d0004SStefan Hajnoczi }
298c61d0004SStefan Hajnoczi 
29969c98726SMax Reitz /*
30069c98726SMax Reitz  * Marks the image as corrupt.
30169c98726SMax Reitz  */
30269c98726SMax Reitz int qcow2_mark_corrupt(BlockDriverState *bs)
30369c98726SMax Reitz {
30469c98726SMax Reitz     BDRVQcowState *s = bs->opaque;
30569c98726SMax Reitz 
30669c98726SMax Reitz     s->incompatible_features |= QCOW2_INCOMPAT_CORRUPT;
30769c98726SMax Reitz     return qcow2_update_header(bs);
30869c98726SMax Reitz }
30969c98726SMax Reitz 
31069c98726SMax Reitz /*
31169c98726SMax Reitz  * Marks the image as consistent, i.e., unsets the corrupt bit, and flushes
31269c98726SMax Reitz  * before if necessary.
31369c98726SMax Reitz  */
31469c98726SMax Reitz int qcow2_mark_consistent(BlockDriverState *bs)
31569c98726SMax Reitz {
31669c98726SMax Reitz     BDRVQcowState *s = bs->opaque;
31769c98726SMax Reitz 
31869c98726SMax Reitz     if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
31969c98726SMax Reitz         int ret = bdrv_flush(bs);
32069c98726SMax Reitz         if (ret < 0) {
32169c98726SMax Reitz             return ret;
32269c98726SMax Reitz         }
32369c98726SMax Reitz 
32469c98726SMax Reitz         s->incompatible_features &= ~QCOW2_INCOMPAT_CORRUPT;
32569c98726SMax Reitz         return qcow2_update_header(bs);
32669c98726SMax Reitz     }
32769c98726SMax Reitz     return 0;
32869c98726SMax Reitz }
32969c98726SMax Reitz 
330acbe5982SStefan Hajnoczi static int qcow2_check(BlockDriverState *bs, BdrvCheckResult *result,
331acbe5982SStefan Hajnoczi                        BdrvCheckMode fix)
332acbe5982SStefan Hajnoczi {
333acbe5982SStefan Hajnoczi     int ret = qcow2_check_refcounts(bs, result, fix);
334acbe5982SStefan Hajnoczi     if (ret < 0) {
335acbe5982SStefan Hajnoczi         return ret;
336acbe5982SStefan Hajnoczi     }
337acbe5982SStefan Hajnoczi 
338acbe5982SStefan Hajnoczi     if (fix && result->check_errors == 0 && result->corruptions == 0) {
33924530f3eSMax Reitz         ret = qcow2_mark_clean(bs);
34024530f3eSMax Reitz         if (ret < 0) {
34124530f3eSMax Reitz             return ret;
34224530f3eSMax Reitz         }
34324530f3eSMax Reitz         return qcow2_mark_consistent(bs);
344acbe5982SStefan Hajnoczi     }
345acbe5982SStefan Hajnoczi     return ret;
346acbe5982SStefan Hajnoczi }
347acbe5982SStefan Hajnoczi 
3488c7de283SKevin Wolf static int validate_table_offset(BlockDriverState *bs, uint64_t offset,
3498c7de283SKevin Wolf                                  uint64_t entries, size_t entry_len)
3508c7de283SKevin Wolf {
3518c7de283SKevin Wolf     BDRVQcowState *s = bs->opaque;
3528c7de283SKevin Wolf     uint64_t size;
3538c7de283SKevin Wolf 
3548c7de283SKevin Wolf     /* Use signed INT64_MAX as the maximum even for uint64_t header fields,
3558c7de283SKevin Wolf      * because values will be passed to qemu functions taking int64_t. */
3568c7de283SKevin Wolf     if (entries > INT64_MAX / entry_len) {
3578c7de283SKevin Wolf         return -EINVAL;
3588c7de283SKevin Wolf     }
3598c7de283SKevin Wolf 
3608c7de283SKevin Wolf     size = entries * entry_len;
3618c7de283SKevin Wolf 
3628c7de283SKevin Wolf     if (INT64_MAX - size < offset) {
3638c7de283SKevin Wolf         return -EINVAL;
3648c7de283SKevin Wolf     }
3658c7de283SKevin Wolf 
3668c7de283SKevin Wolf     /* Tables must be cluster aligned */
3678c7de283SKevin Wolf     if (offset & (s->cluster_size - 1)) {
3688c7de283SKevin Wolf         return -EINVAL;
3698c7de283SKevin Wolf     }
3708c7de283SKevin Wolf 
3718c7de283SKevin Wolf     return 0;
3728c7de283SKevin Wolf }
3738c7de283SKevin Wolf 
37474c4510aSKevin Wolf static QemuOptsList qcow2_runtime_opts = {
37574c4510aSKevin Wolf     .name = "qcow2",
37674c4510aSKevin Wolf     .head = QTAILQ_HEAD_INITIALIZER(qcow2_runtime_opts.head),
37774c4510aSKevin Wolf     .desc = {
37874c4510aSKevin Wolf         {
37964aa99d3SKevin Wolf             .name = QCOW2_OPT_LAZY_REFCOUNTS,
38074c4510aSKevin Wolf             .type = QEMU_OPT_BOOL,
38174c4510aSKevin Wolf             .help = "Postpone refcount updates",
38274c4510aSKevin Wolf         },
38367af674eSKevin Wolf         {
38467af674eSKevin Wolf             .name = QCOW2_OPT_DISCARD_REQUEST,
38567af674eSKevin Wolf             .type = QEMU_OPT_BOOL,
38667af674eSKevin Wolf             .help = "Pass guest discard requests to the layer below",
38767af674eSKevin Wolf         },
38867af674eSKevin Wolf         {
38967af674eSKevin Wolf             .name = QCOW2_OPT_DISCARD_SNAPSHOT,
39067af674eSKevin Wolf             .type = QEMU_OPT_BOOL,
39167af674eSKevin Wolf             .help = "Generate discard requests when snapshot related space "
39267af674eSKevin Wolf                     "is freed",
39367af674eSKevin Wolf         },
39467af674eSKevin Wolf         {
39567af674eSKevin Wolf             .name = QCOW2_OPT_DISCARD_OTHER,
39667af674eSKevin Wolf             .type = QEMU_OPT_BOOL,
39767af674eSKevin Wolf             .help = "Generate discard requests when other clusters are freed",
39867af674eSKevin Wolf         },
39905de7e86SMax Reitz         {
40005de7e86SMax Reitz             .name = QCOW2_OPT_OVERLAP,
40105de7e86SMax Reitz             .type = QEMU_OPT_STRING,
40205de7e86SMax Reitz             .help = "Selects which overlap checks to perform from a range of "
40305de7e86SMax Reitz                     "templates (none, constant, cached, all)",
40405de7e86SMax Reitz         },
40505de7e86SMax Reitz         {
40605de7e86SMax Reitz             .name = QCOW2_OPT_OVERLAP_MAIN_HEADER,
40705de7e86SMax Reitz             .type = QEMU_OPT_BOOL,
40805de7e86SMax Reitz             .help = "Check for unintended writes into the main qcow2 header",
40905de7e86SMax Reitz         },
41005de7e86SMax Reitz         {
41105de7e86SMax Reitz             .name = QCOW2_OPT_OVERLAP_ACTIVE_L1,
41205de7e86SMax Reitz             .type = QEMU_OPT_BOOL,
41305de7e86SMax Reitz             .help = "Check for unintended writes into the active L1 table",
41405de7e86SMax Reitz         },
41505de7e86SMax Reitz         {
41605de7e86SMax Reitz             .name = QCOW2_OPT_OVERLAP_ACTIVE_L2,
41705de7e86SMax Reitz             .type = QEMU_OPT_BOOL,
41805de7e86SMax Reitz             .help = "Check for unintended writes into an active L2 table",
41905de7e86SMax Reitz         },
42005de7e86SMax Reitz         {
42105de7e86SMax Reitz             .name = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
42205de7e86SMax Reitz             .type = QEMU_OPT_BOOL,
42305de7e86SMax Reitz             .help = "Check for unintended writes into the refcount table",
42405de7e86SMax Reitz         },
42505de7e86SMax Reitz         {
42605de7e86SMax Reitz             .name = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
42705de7e86SMax Reitz             .type = QEMU_OPT_BOOL,
42805de7e86SMax Reitz             .help = "Check for unintended writes into a refcount block",
42905de7e86SMax Reitz         },
43005de7e86SMax Reitz         {
43105de7e86SMax Reitz             .name = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
43205de7e86SMax Reitz             .type = QEMU_OPT_BOOL,
43305de7e86SMax Reitz             .help = "Check for unintended writes into the snapshot table",
43405de7e86SMax Reitz         },
43505de7e86SMax Reitz         {
43605de7e86SMax Reitz             .name = QCOW2_OPT_OVERLAP_INACTIVE_L1,
43705de7e86SMax Reitz             .type = QEMU_OPT_BOOL,
43805de7e86SMax Reitz             .help = "Check for unintended writes into an inactive L1 table",
43905de7e86SMax Reitz         },
44005de7e86SMax Reitz         {
44105de7e86SMax Reitz             .name = QCOW2_OPT_OVERLAP_INACTIVE_L2,
44205de7e86SMax Reitz             .type = QEMU_OPT_BOOL,
44305de7e86SMax Reitz             .help = "Check for unintended writes into an inactive L2 table",
44405de7e86SMax Reitz         },
4456c1c8d5dSMax Reitz         {
4466c1c8d5dSMax Reitz             .name = QCOW2_OPT_CACHE_SIZE,
4476c1c8d5dSMax Reitz             .type = QEMU_OPT_SIZE,
4486c1c8d5dSMax Reitz             .help = "Maximum combined metadata (L2 tables and refcount blocks) "
4496c1c8d5dSMax Reitz                     "cache size",
4506c1c8d5dSMax Reitz         },
4516c1c8d5dSMax Reitz         {
4526c1c8d5dSMax Reitz             .name = QCOW2_OPT_L2_CACHE_SIZE,
4536c1c8d5dSMax Reitz             .type = QEMU_OPT_SIZE,
4546c1c8d5dSMax Reitz             .help = "Maximum L2 table cache size",
4556c1c8d5dSMax Reitz         },
4566c1c8d5dSMax Reitz         {
4576c1c8d5dSMax Reitz             .name = QCOW2_OPT_REFCOUNT_CACHE_SIZE,
4586c1c8d5dSMax Reitz             .type = QEMU_OPT_SIZE,
4596c1c8d5dSMax Reitz             .help = "Maximum refcount block cache size",
4606c1c8d5dSMax Reitz         },
46174c4510aSKevin Wolf         { /* end of list */ }
46274c4510aSKevin Wolf     },
46374c4510aSKevin Wolf };
46474c4510aSKevin Wolf 
4654092e99dSMax Reitz static const char *overlap_bool_option_names[QCOW2_OL_MAX_BITNR] = {
4664092e99dSMax Reitz     [QCOW2_OL_MAIN_HEADER_BITNR]    = QCOW2_OPT_OVERLAP_MAIN_HEADER,
4674092e99dSMax Reitz     [QCOW2_OL_ACTIVE_L1_BITNR]      = QCOW2_OPT_OVERLAP_ACTIVE_L1,
4684092e99dSMax Reitz     [QCOW2_OL_ACTIVE_L2_BITNR]      = QCOW2_OPT_OVERLAP_ACTIVE_L2,
4694092e99dSMax Reitz     [QCOW2_OL_REFCOUNT_TABLE_BITNR] = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
4704092e99dSMax Reitz     [QCOW2_OL_REFCOUNT_BLOCK_BITNR] = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
4714092e99dSMax Reitz     [QCOW2_OL_SNAPSHOT_TABLE_BITNR] = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
4724092e99dSMax Reitz     [QCOW2_OL_INACTIVE_L1_BITNR]    = QCOW2_OPT_OVERLAP_INACTIVE_L1,
4734092e99dSMax Reitz     [QCOW2_OL_INACTIVE_L2_BITNR]    = QCOW2_OPT_OVERLAP_INACTIVE_L2,
4744092e99dSMax Reitz };
4754092e99dSMax Reitz 
4766c1c8d5dSMax Reitz static void read_cache_sizes(QemuOpts *opts, uint64_t *l2_cache_size,
4776c1c8d5dSMax Reitz                              uint64_t *refcount_cache_size, Error **errp)
4786c1c8d5dSMax Reitz {
4796c1c8d5dSMax Reitz     uint64_t combined_cache_size;
4806c1c8d5dSMax Reitz     bool l2_cache_size_set, refcount_cache_size_set, combined_cache_size_set;
4816c1c8d5dSMax Reitz 
4826c1c8d5dSMax Reitz     combined_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_CACHE_SIZE);
4836c1c8d5dSMax Reitz     l2_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_L2_CACHE_SIZE);
4846c1c8d5dSMax Reitz     refcount_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
4856c1c8d5dSMax Reitz 
4866c1c8d5dSMax Reitz     combined_cache_size = qemu_opt_get_size(opts, QCOW2_OPT_CACHE_SIZE, 0);
4876c1c8d5dSMax Reitz     *l2_cache_size = qemu_opt_get_size(opts, QCOW2_OPT_L2_CACHE_SIZE, 0);
4886c1c8d5dSMax Reitz     *refcount_cache_size = qemu_opt_get_size(opts,
4896c1c8d5dSMax Reitz                                              QCOW2_OPT_REFCOUNT_CACHE_SIZE, 0);
4906c1c8d5dSMax Reitz 
4916c1c8d5dSMax Reitz     if (combined_cache_size_set) {
4926c1c8d5dSMax Reitz         if (l2_cache_size_set && refcount_cache_size_set) {
4936c1c8d5dSMax Reitz             error_setg(errp, QCOW2_OPT_CACHE_SIZE ", " QCOW2_OPT_L2_CACHE_SIZE
4946c1c8d5dSMax Reitz                        " and " QCOW2_OPT_REFCOUNT_CACHE_SIZE " may not be set "
4956c1c8d5dSMax Reitz                        "the same time");
4966c1c8d5dSMax Reitz             return;
4976c1c8d5dSMax Reitz         } else if (*l2_cache_size > combined_cache_size) {
4986c1c8d5dSMax Reitz             error_setg(errp, QCOW2_OPT_L2_CACHE_SIZE " may not exceed "
4996c1c8d5dSMax Reitz                        QCOW2_OPT_CACHE_SIZE);
5006c1c8d5dSMax Reitz             return;
5016c1c8d5dSMax Reitz         } else if (*refcount_cache_size > combined_cache_size) {
5026c1c8d5dSMax Reitz             error_setg(errp, QCOW2_OPT_REFCOUNT_CACHE_SIZE " may not exceed "
5036c1c8d5dSMax Reitz                        QCOW2_OPT_CACHE_SIZE);
5046c1c8d5dSMax Reitz             return;
5056c1c8d5dSMax Reitz         }
5066c1c8d5dSMax Reitz 
5076c1c8d5dSMax Reitz         if (l2_cache_size_set) {
5086c1c8d5dSMax Reitz             *refcount_cache_size = combined_cache_size - *l2_cache_size;
5096c1c8d5dSMax Reitz         } else if (refcount_cache_size_set) {
5106c1c8d5dSMax Reitz             *l2_cache_size = combined_cache_size - *refcount_cache_size;
5116c1c8d5dSMax Reitz         } else {
5126c1c8d5dSMax Reitz             *refcount_cache_size = combined_cache_size
5136c1c8d5dSMax Reitz                                  / (DEFAULT_L2_REFCOUNT_SIZE_RATIO + 1);
5146c1c8d5dSMax Reitz             *l2_cache_size = combined_cache_size - *refcount_cache_size;
5156c1c8d5dSMax Reitz         }
5166c1c8d5dSMax Reitz     } else {
5176c1c8d5dSMax Reitz         if (!l2_cache_size_set && !refcount_cache_size_set) {
5186c1c8d5dSMax Reitz             *l2_cache_size = DEFAULT_L2_CACHE_BYTE_SIZE;
5196c1c8d5dSMax Reitz             *refcount_cache_size = *l2_cache_size
5206c1c8d5dSMax Reitz                                  / DEFAULT_L2_REFCOUNT_SIZE_RATIO;
5216c1c8d5dSMax Reitz         } else if (!l2_cache_size_set) {
5226c1c8d5dSMax Reitz             *l2_cache_size = *refcount_cache_size
5236c1c8d5dSMax Reitz                            * DEFAULT_L2_REFCOUNT_SIZE_RATIO;
5246c1c8d5dSMax Reitz         } else if (!refcount_cache_size_set) {
5256c1c8d5dSMax Reitz             *refcount_cache_size = *l2_cache_size
5266c1c8d5dSMax Reitz                                  / DEFAULT_L2_REFCOUNT_SIZE_RATIO;
5276c1c8d5dSMax Reitz         }
5286c1c8d5dSMax Reitz     }
5296c1c8d5dSMax Reitz }
5306c1c8d5dSMax Reitz 
531015a1036SMax Reitz static int qcow2_open(BlockDriverState *bs, QDict *options, int flags,
532015a1036SMax Reitz                       Error **errp)
533585f8587Sbellard {
534585f8587Sbellard     BDRVQcowState *s = bs->opaque;
5356d33e8e7SKevin Wolf     unsigned int len, i;
5366d33e8e7SKevin Wolf     int ret = 0;
537585f8587Sbellard     QCowHeader header;
53874c4510aSKevin Wolf     QemuOpts *opts;
53974c4510aSKevin Wolf     Error *local_err = NULL;
5409b80ddf3Saliguori     uint64_t ext_end;
5412cf7cfa1SKevin Wolf     uint64_t l1_vm_state_index;
5421fa5cc83SMax Reitz     const char *opt_overlap_check;
5431fa5cc83SMax Reitz     int overlap_check_template = 0;
544440ba08aSMax Reitz     uint64_t l2_cache_size, refcount_cache_size;
545585f8587Sbellard 
5466d85a57eSJes Sorensen     ret = bdrv_pread(bs->file, 0, &header, sizeof(header));
5476d85a57eSJes Sorensen     if (ret < 0) {
5483ef6c40aSMax Reitz         error_setg_errno(errp, -ret, "Could not read qcow2 header");
549585f8587Sbellard         goto fail;
5506d85a57eSJes Sorensen     }
551585f8587Sbellard     be32_to_cpus(&header.magic);
552585f8587Sbellard     be32_to_cpus(&header.version);
553585f8587Sbellard     be64_to_cpus(&header.backing_file_offset);
554585f8587Sbellard     be32_to_cpus(&header.backing_file_size);
555585f8587Sbellard     be64_to_cpus(&header.size);
556585f8587Sbellard     be32_to_cpus(&header.cluster_bits);
557585f8587Sbellard     be32_to_cpus(&header.crypt_method);
558585f8587Sbellard     be64_to_cpus(&header.l1_table_offset);
559585f8587Sbellard     be32_to_cpus(&header.l1_size);
560585f8587Sbellard     be64_to_cpus(&header.refcount_table_offset);
561585f8587Sbellard     be32_to_cpus(&header.refcount_table_clusters);
562585f8587Sbellard     be64_to_cpus(&header.snapshots_offset);
563585f8587Sbellard     be32_to_cpus(&header.nb_snapshots);
564585f8587Sbellard 
565e8cdcec1SKevin Wolf     if (header.magic != QCOW_MAGIC) {
5663ef6c40aSMax Reitz         error_setg(errp, "Image is not in qcow2 format");
56776abe407SPaolo Bonzini         ret = -EINVAL;
568585f8587Sbellard         goto fail;
5696d85a57eSJes Sorensen     }
5706744cbabSKevin Wolf     if (header.version < 2 || header.version > 3) {
571521b2b5dSMax Reitz         report_unsupported(bs, errp, "QCOW version %" PRIu32, header.version);
572e8cdcec1SKevin Wolf         ret = -ENOTSUP;
573e8cdcec1SKevin Wolf         goto fail;
574e8cdcec1SKevin Wolf     }
5756744cbabSKevin Wolf 
5766744cbabSKevin Wolf     s->qcow_version = header.version;
5776744cbabSKevin Wolf 
57824342f2cSKevin Wolf     /* Initialise cluster size */
57924342f2cSKevin Wolf     if (header.cluster_bits < MIN_CLUSTER_BITS ||
58024342f2cSKevin Wolf         header.cluster_bits > MAX_CLUSTER_BITS) {
581521b2b5dSMax Reitz         error_setg(errp, "Unsupported cluster size: 2^%" PRIu32,
582521b2b5dSMax Reitz                    header.cluster_bits);
58324342f2cSKevin Wolf         ret = -EINVAL;
58424342f2cSKevin Wolf         goto fail;
58524342f2cSKevin Wolf     }
58624342f2cSKevin Wolf 
58724342f2cSKevin Wolf     s->cluster_bits = header.cluster_bits;
58824342f2cSKevin Wolf     s->cluster_size = 1 << s->cluster_bits;
58924342f2cSKevin Wolf     s->cluster_sectors = 1 << (s->cluster_bits - 9);
59024342f2cSKevin Wolf 
5916744cbabSKevin Wolf     /* Initialise version 3 header fields */
5926744cbabSKevin Wolf     if (header.version == 2) {
5936744cbabSKevin Wolf         header.incompatible_features    = 0;
5946744cbabSKevin Wolf         header.compatible_features      = 0;
5956744cbabSKevin Wolf         header.autoclear_features       = 0;
5966744cbabSKevin Wolf         header.refcount_order           = 4;
5976744cbabSKevin Wolf         header.header_length            = 72;
5986744cbabSKevin Wolf     } else {
5996744cbabSKevin Wolf         be64_to_cpus(&header.incompatible_features);
6006744cbabSKevin Wolf         be64_to_cpus(&header.compatible_features);
6016744cbabSKevin Wolf         be64_to_cpus(&header.autoclear_features);
6026744cbabSKevin Wolf         be32_to_cpus(&header.refcount_order);
6036744cbabSKevin Wolf         be32_to_cpus(&header.header_length);
60424342f2cSKevin Wolf 
60524342f2cSKevin Wolf         if (header.header_length < 104) {
60624342f2cSKevin Wolf             error_setg(errp, "qcow2 header too short");
60724342f2cSKevin Wolf             ret = -EINVAL;
60824342f2cSKevin Wolf             goto fail;
60924342f2cSKevin Wolf         }
61024342f2cSKevin Wolf     }
61124342f2cSKevin Wolf 
61224342f2cSKevin Wolf     if (header.header_length > s->cluster_size) {
61324342f2cSKevin Wolf         error_setg(errp, "qcow2 header exceeds cluster size");
61424342f2cSKevin Wolf         ret = -EINVAL;
61524342f2cSKevin Wolf         goto fail;
6166744cbabSKevin Wolf     }
6176744cbabSKevin Wolf 
6186744cbabSKevin Wolf     if (header.header_length > sizeof(header)) {
6196744cbabSKevin Wolf         s->unknown_header_fields_size = header.header_length - sizeof(header);
6206744cbabSKevin Wolf         s->unknown_header_fields = g_malloc(s->unknown_header_fields_size);
6216744cbabSKevin Wolf         ret = bdrv_pread(bs->file, sizeof(header), s->unknown_header_fields,
6226744cbabSKevin Wolf                          s->unknown_header_fields_size);
6236744cbabSKevin Wolf         if (ret < 0) {
6243ef6c40aSMax Reitz             error_setg_errno(errp, -ret, "Could not read unknown qcow2 header "
6253ef6c40aSMax Reitz                              "fields");
6266744cbabSKevin Wolf             goto fail;
6276744cbabSKevin Wolf         }
6286744cbabSKevin Wolf     }
6296744cbabSKevin Wolf 
630a1b3955cSKevin Wolf     if (header.backing_file_offset > s->cluster_size) {
631a1b3955cSKevin Wolf         error_setg(errp, "Invalid backing file offset");
632a1b3955cSKevin Wolf         ret = -EINVAL;
633a1b3955cSKevin Wolf         goto fail;
634a1b3955cSKevin Wolf     }
635a1b3955cSKevin Wolf 
636cfcc4c62SKevin Wolf     if (header.backing_file_offset) {
637cfcc4c62SKevin Wolf         ext_end = header.backing_file_offset;
638cfcc4c62SKevin Wolf     } else {
639cfcc4c62SKevin Wolf         ext_end = 1 << header.cluster_bits;
640cfcc4c62SKevin Wolf     }
641cfcc4c62SKevin Wolf 
6426744cbabSKevin Wolf     /* Handle feature bits */
6436744cbabSKevin Wolf     s->incompatible_features    = header.incompatible_features;
6446744cbabSKevin Wolf     s->compatible_features      = header.compatible_features;
6456744cbabSKevin Wolf     s->autoclear_features       = header.autoclear_features;
6466744cbabSKevin Wolf 
647c61d0004SStefan Hajnoczi     if (s->incompatible_features & ~QCOW2_INCOMPAT_MASK) {
648cfcc4c62SKevin Wolf         void *feature_table = NULL;
649cfcc4c62SKevin Wolf         qcow2_read_extensions(bs, header.header_length, ext_end,
6503ef6c40aSMax Reitz                               &feature_table, NULL);
6513ef6c40aSMax Reitz         report_unsupported_feature(bs, errp, feature_table,
652c61d0004SStefan Hajnoczi                                    s->incompatible_features &
653c61d0004SStefan Hajnoczi                                    ~QCOW2_INCOMPAT_MASK);
6546744cbabSKevin Wolf         ret = -ENOTSUP;
655c5a33ee9SPrasad Joshi         g_free(feature_table);
6566744cbabSKevin Wolf         goto fail;
6576744cbabSKevin Wolf     }
6586744cbabSKevin Wolf 
65969c98726SMax Reitz     if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
66069c98726SMax Reitz         /* Corrupt images may not be written to unless they are being repaired
66169c98726SMax Reitz          */
66269c98726SMax Reitz         if ((flags & BDRV_O_RDWR) && !(flags & BDRV_O_CHECK)) {
6633ef6c40aSMax Reitz             error_setg(errp, "qcow2: Image is corrupt; cannot be opened "
6643ef6c40aSMax Reitz                        "read/write");
66569c98726SMax Reitz             ret = -EACCES;
66669c98726SMax Reitz             goto fail;
66769c98726SMax Reitz         }
66869c98726SMax Reitz     }
66969c98726SMax Reitz 
6706744cbabSKevin Wolf     /* Check support for various header values */
6716744cbabSKevin Wolf     if (header.refcount_order != 4) {
6723ef6c40aSMax Reitz         report_unsupported(bs, errp, "%d bit reference counts",
6736744cbabSKevin Wolf                            1 << header.refcount_order);
6746744cbabSKevin Wolf         ret = -ENOTSUP;
6756744cbabSKevin Wolf         goto fail;
6766744cbabSKevin Wolf     }
677b6481f37SMax Reitz     s->refcount_order = header.refcount_order;
6786744cbabSKevin Wolf 
6796d85a57eSJes Sorensen     if (header.crypt_method > QCOW_CRYPT_AES) {
680521b2b5dSMax Reitz         error_setg(errp, "Unsupported encryption method: %" PRIu32,
6813ef6c40aSMax Reitz                    header.crypt_method);
6826d85a57eSJes Sorensen         ret = -EINVAL;
683585f8587Sbellard         goto fail;
6846d85a57eSJes Sorensen     }
685585f8587Sbellard     s->crypt_method_header = header.crypt_method;
6866d85a57eSJes Sorensen     if (s->crypt_method_header) {
687585f8587Sbellard         bs->encrypted = 1;
6886d85a57eSJes Sorensen     }
68924342f2cSKevin Wolf 
690585f8587Sbellard     s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */
691585f8587Sbellard     s->l2_size = 1 << s->l2_bits;
692585f8587Sbellard     bs->total_sectors = header.size / 512;
693585f8587Sbellard     s->csize_shift = (62 - (s->cluster_bits - 8));
694585f8587Sbellard     s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;
695585f8587Sbellard     s->cluster_offset_mask = (1LL << s->csize_shift) - 1;
6965dab2fadSKevin Wolf 
697585f8587Sbellard     s->refcount_table_offset = header.refcount_table_offset;
698585f8587Sbellard     s->refcount_table_size =
699585f8587Sbellard         header.refcount_table_clusters << (s->cluster_bits - 3);
700585f8587Sbellard 
7012b5d5953SKevin Wolf     if (header.refcount_table_clusters > qcow2_max_refcount_clusters(s)) {
7025dab2fadSKevin Wolf         error_setg(errp, "Reference count table too large");
7035dab2fadSKevin Wolf         ret = -EINVAL;
7045dab2fadSKevin Wolf         goto fail;
7055dab2fadSKevin Wolf     }
7065dab2fadSKevin Wolf 
7078c7de283SKevin Wolf     ret = validate_table_offset(bs, s->refcount_table_offset,
7088c7de283SKevin Wolf                                 s->refcount_table_size, sizeof(uint64_t));
7098c7de283SKevin Wolf     if (ret < 0) {
7108c7de283SKevin Wolf         error_setg(errp, "Invalid reference count table offset");
7118c7de283SKevin Wolf         goto fail;
7128c7de283SKevin Wolf     }
7138c7de283SKevin Wolf 
714ce48f2f4SKevin Wolf     /* Snapshot table offset/length */
715ce48f2f4SKevin Wolf     if (header.nb_snapshots > QCOW_MAX_SNAPSHOTS) {
716ce48f2f4SKevin Wolf         error_setg(errp, "Too many snapshots");
717ce48f2f4SKevin Wolf         ret = -EINVAL;
718ce48f2f4SKevin Wolf         goto fail;
719ce48f2f4SKevin Wolf     }
720ce48f2f4SKevin Wolf 
721ce48f2f4SKevin Wolf     ret = validate_table_offset(bs, header.snapshots_offset,
722ce48f2f4SKevin Wolf                                 header.nb_snapshots,
723ce48f2f4SKevin Wolf                                 sizeof(QCowSnapshotHeader));
724ce48f2f4SKevin Wolf     if (ret < 0) {
725ce48f2f4SKevin Wolf         error_setg(errp, "Invalid snapshot table offset");
726ce48f2f4SKevin Wolf         goto fail;
727ce48f2f4SKevin Wolf     }
728ce48f2f4SKevin Wolf 
729585f8587Sbellard     /* read the level 1 table */
7306a83f8b5SKevin Wolf     if (header.l1_size > QCOW_MAX_L1_SIZE) {
7312d51c32cSKevin Wolf         error_setg(errp, "Active L1 table too large");
7322d51c32cSKevin Wolf         ret = -EFBIG;
7332d51c32cSKevin Wolf         goto fail;
7342d51c32cSKevin Wolf     }
735585f8587Sbellard     s->l1_size = header.l1_size;
7362cf7cfa1SKevin Wolf 
7372cf7cfa1SKevin Wolf     l1_vm_state_index = size_to_l1(s, header.size);
7382cf7cfa1SKevin Wolf     if (l1_vm_state_index > INT_MAX) {
7393ef6c40aSMax Reitz         error_setg(errp, "Image is too big");
7402cf7cfa1SKevin Wolf         ret = -EFBIG;
7412cf7cfa1SKevin Wolf         goto fail;
7422cf7cfa1SKevin Wolf     }
7432cf7cfa1SKevin Wolf     s->l1_vm_state_index = l1_vm_state_index;
7442cf7cfa1SKevin Wolf 
745585f8587Sbellard     /* the L1 table must contain at least enough entries to put
746585f8587Sbellard        header.size bytes */
7476d85a57eSJes Sorensen     if (s->l1_size < s->l1_vm_state_index) {
7483ef6c40aSMax Reitz         error_setg(errp, "L1 table is too small");
7496d85a57eSJes Sorensen         ret = -EINVAL;
750585f8587Sbellard         goto fail;
7516d85a57eSJes Sorensen     }
7522d51c32cSKevin Wolf 
7532d51c32cSKevin Wolf     ret = validate_table_offset(bs, header.l1_table_offset,
7542d51c32cSKevin Wolf                                 header.l1_size, sizeof(uint64_t));
7552d51c32cSKevin Wolf     if (ret < 0) {
7562d51c32cSKevin Wolf         error_setg(errp, "Invalid L1 table offset");
7572d51c32cSKevin Wolf         goto fail;
7582d51c32cSKevin Wolf     }
759585f8587Sbellard     s->l1_table_offset = header.l1_table_offset;
7602d51c32cSKevin Wolf 
7612d51c32cSKevin Wolf 
762d191d12dSStefan Weil     if (s->l1_size > 0) {
763de82815dSKevin Wolf         s->l1_table = qemu_try_blockalign(bs->file,
7643f6a3ee5SKevin Wolf             align_offset(s->l1_size * sizeof(uint64_t), 512));
765de82815dSKevin Wolf         if (s->l1_table == NULL) {
766de82815dSKevin Wolf             error_setg(errp, "Could not allocate L1 table");
767de82815dSKevin Wolf             ret = -ENOMEM;
768de82815dSKevin Wolf             goto fail;
769de82815dSKevin Wolf         }
7706d85a57eSJes Sorensen         ret = bdrv_pread(bs->file, s->l1_table_offset, s->l1_table,
7716d85a57eSJes Sorensen                          s->l1_size * sizeof(uint64_t));
7726d85a57eSJes Sorensen         if (ret < 0) {
7733ef6c40aSMax Reitz             error_setg_errno(errp, -ret, "Could not read L1 table");
774585f8587Sbellard             goto fail;
7756d85a57eSJes Sorensen         }
776585f8587Sbellard         for(i = 0;i < s->l1_size; i++) {
777585f8587Sbellard             be64_to_cpus(&s->l1_table[i]);
778585f8587Sbellard         }
779d191d12dSStefan Weil     }
78029c1a730SKevin Wolf 
7816c1c8d5dSMax Reitz     /* get L2 table/refcount block cache size from command line options */
7826c1c8d5dSMax Reitz     opts = qemu_opts_create(&qcow2_runtime_opts, NULL, 0, &error_abort);
7836c1c8d5dSMax Reitz     qemu_opts_absorb_qdict(opts, options, &local_err);
7846c1c8d5dSMax Reitz     if (local_err) {
7856c1c8d5dSMax Reitz         error_propagate(errp, local_err);
7866c1c8d5dSMax Reitz         ret = -EINVAL;
7876c1c8d5dSMax Reitz         goto fail;
7886c1c8d5dSMax Reitz     }
7896c1c8d5dSMax Reitz 
7906c1c8d5dSMax Reitz     read_cache_sizes(opts, &l2_cache_size, &refcount_cache_size, &local_err);
7916c1c8d5dSMax Reitz     if (local_err) {
7926c1c8d5dSMax Reitz         error_propagate(errp, local_err);
7936c1c8d5dSMax Reitz         ret = -EINVAL;
7946c1c8d5dSMax Reitz         goto fail;
7956c1c8d5dSMax Reitz     }
7966c1c8d5dSMax Reitz 
7976c1c8d5dSMax Reitz     l2_cache_size /= s->cluster_size;
798440ba08aSMax Reitz     if (l2_cache_size < MIN_L2_CACHE_SIZE) {
799440ba08aSMax Reitz         l2_cache_size = MIN_L2_CACHE_SIZE;
800440ba08aSMax Reitz     }
8016c1c8d5dSMax Reitz     if (l2_cache_size > INT_MAX) {
8026c1c8d5dSMax Reitz         error_setg(errp, "L2 cache size too big");
8036c1c8d5dSMax Reitz         ret = -EINVAL;
8046c1c8d5dSMax Reitz         goto fail;
8056c1c8d5dSMax Reitz     }
806440ba08aSMax Reitz 
8076c1c8d5dSMax Reitz     refcount_cache_size /= s->cluster_size;
808440ba08aSMax Reitz     if (refcount_cache_size < MIN_REFCOUNT_CACHE_SIZE) {
809440ba08aSMax Reitz         refcount_cache_size = MIN_REFCOUNT_CACHE_SIZE;
810440ba08aSMax Reitz     }
8116c1c8d5dSMax Reitz     if (refcount_cache_size > INT_MAX) {
8126c1c8d5dSMax Reitz         error_setg(errp, "Refcount cache size too big");
8136c1c8d5dSMax Reitz         ret = -EINVAL;
8146c1c8d5dSMax Reitz         goto fail;
8156c1c8d5dSMax Reitz     }
816440ba08aSMax Reitz 
8176c1c8d5dSMax Reitz     /* alloc L2 table/refcount block cache */
818440ba08aSMax Reitz     s->l2_table_cache = qcow2_cache_create(bs, l2_cache_size);
819440ba08aSMax Reitz     s->refcount_block_cache = qcow2_cache_create(bs, refcount_cache_size);
820de82815dSKevin Wolf     if (s->l2_table_cache == NULL || s->refcount_block_cache == NULL) {
821de82815dSKevin Wolf         error_setg(errp, "Could not allocate metadata caches");
822de82815dSKevin Wolf         ret = -ENOMEM;
823de82815dSKevin Wolf         goto fail;
824de82815dSKevin Wolf     }
82529c1a730SKevin Wolf 
8267267c094SAnthony Liguori     s->cluster_cache = g_malloc(s->cluster_size);
827585f8587Sbellard     /* one more sector for decompressed data alignment */
828de82815dSKevin Wolf     s->cluster_data = qemu_try_blockalign(bs->file, QCOW_MAX_CRYPT_CLUSTERS
829de82815dSKevin Wolf                                                     * s->cluster_size + 512);
830de82815dSKevin Wolf     if (s->cluster_data == NULL) {
831de82815dSKevin Wolf         error_setg(errp, "Could not allocate temporary cluster buffer");
832de82815dSKevin Wolf         ret = -ENOMEM;
833de82815dSKevin Wolf         goto fail;
834de82815dSKevin Wolf     }
835de82815dSKevin Wolf 
836585f8587Sbellard     s->cluster_cache_offset = -1;
83706d9260fSAnthony Liguori     s->flags = flags;
838585f8587Sbellard 
8396d85a57eSJes Sorensen     ret = qcow2_refcount_init(bs);
8406d85a57eSJes Sorensen     if (ret != 0) {
8413ef6c40aSMax Reitz         error_setg_errno(errp, -ret, "Could not initialize refcount handling");
842585f8587Sbellard         goto fail;
8436d85a57eSJes Sorensen     }
844585f8587Sbellard 
84572cf2d4fSBlue Swirl     QLIST_INIT(&s->cluster_allocs);
8460b919faeSKevin Wolf     QTAILQ_INIT(&s->discards);
847f214978aSKevin Wolf 
8489b80ddf3Saliguori     /* read qcow2 extensions */
8493ef6c40aSMax Reitz     if (qcow2_read_extensions(bs, header.header_length, ext_end, NULL,
8503ef6c40aSMax Reitz         &local_err)) {
8513ef6c40aSMax Reitz         error_propagate(errp, local_err);
8526d85a57eSJes Sorensen         ret = -EINVAL;
8539b80ddf3Saliguori         goto fail;
8546d85a57eSJes Sorensen     }
8559b80ddf3Saliguori 
856585f8587Sbellard     /* read the backing file name */
857585f8587Sbellard     if (header.backing_file_offset != 0) {
858585f8587Sbellard         len = header.backing_file_size;
8596d33e8e7SKevin Wolf         if (len > MIN(1023, s->cluster_size - header.backing_file_offset)) {
8606d33e8e7SKevin Wolf             error_setg(errp, "Backing file name too long");
8616d33e8e7SKevin Wolf             ret = -EINVAL;
8626d33e8e7SKevin Wolf             goto fail;
8636d85a57eSJes Sorensen         }
8646d85a57eSJes Sorensen         ret = bdrv_pread(bs->file, header.backing_file_offset,
8656d85a57eSJes Sorensen                          bs->backing_file, len);
8666d85a57eSJes Sorensen         if (ret < 0) {
8673ef6c40aSMax Reitz             error_setg_errno(errp, -ret, "Could not read backing file name");
868585f8587Sbellard             goto fail;
8696d85a57eSJes Sorensen         }
870585f8587Sbellard         bs->backing_file[len] = '\0';
871585f8587Sbellard     }
87242deb29fSKevin Wolf 
87311b128f4SKevin Wolf     /* Internal snapshots */
87411b128f4SKevin Wolf     s->snapshots_offset = header.snapshots_offset;
87511b128f4SKevin Wolf     s->nb_snapshots = header.nb_snapshots;
87611b128f4SKevin Wolf 
87742deb29fSKevin Wolf     ret = qcow2_read_snapshots(bs);
87842deb29fSKevin Wolf     if (ret < 0) {
8793ef6c40aSMax Reitz         error_setg_errno(errp, -ret, "Could not read snapshots");
880585f8587Sbellard         goto fail;
8816d85a57eSJes Sorensen     }
882585f8587Sbellard 
883af7b708dSStefan Hajnoczi     /* Clear unknown autoclear feature bits */
88427eb6c09SKevin Wolf     if (!bs->read_only && !(flags & BDRV_O_INCOMING) && s->autoclear_features) {
885af7b708dSStefan Hajnoczi         s->autoclear_features = 0;
886af7b708dSStefan Hajnoczi         ret = qcow2_update_header(bs);
887af7b708dSStefan Hajnoczi         if (ret < 0) {
8883ef6c40aSMax Reitz             error_setg_errno(errp, -ret, "Could not update qcow2 header");
889af7b708dSStefan Hajnoczi             goto fail;
890af7b708dSStefan Hajnoczi         }
891af7b708dSStefan Hajnoczi     }
892af7b708dSStefan Hajnoczi 
89368d100e9SKevin Wolf     /* Initialise locks */
89468d100e9SKevin Wolf     qemu_co_mutex_init(&s->lock);
89568d100e9SKevin Wolf 
896c61d0004SStefan Hajnoczi     /* Repair image if dirty */
89727eb6c09SKevin Wolf     if (!(flags & (BDRV_O_CHECK | BDRV_O_INCOMING)) && !bs->read_only &&
898058f8f16SStefan Hajnoczi         (s->incompatible_features & QCOW2_INCOMPAT_DIRTY)) {
899c61d0004SStefan Hajnoczi         BdrvCheckResult result = {0};
900c61d0004SStefan Hajnoczi 
901acbe5982SStefan Hajnoczi         ret = qcow2_check(bs, &result, BDRV_FIX_ERRORS);
902c61d0004SStefan Hajnoczi         if (ret < 0) {
9033ef6c40aSMax Reitz             error_setg_errno(errp, -ret, "Could not repair dirty image");
904c61d0004SStefan Hajnoczi             goto fail;
905c61d0004SStefan Hajnoczi         }
906c61d0004SStefan Hajnoczi     }
907c61d0004SStefan Hajnoczi 
90874c4510aSKevin Wolf     /* Enable lazy_refcounts according to image and command line options */
909acdfb480SKevin Wolf     s->use_lazy_refcounts = qemu_opt_get_bool(opts, QCOW2_OPT_LAZY_REFCOUNTS,
91074c4510aSKevin Wolf         (s->compatible_features & QCOW2_COMPAT_LAZY_REFCOUNTS));
91174c4510aSKevin Wolf 
91267af674eSKevin Wolf     s->discard_passthrough[QCOW2_DISCARD_NEVER] = false;
91367af674eSKevin Wolf     s->discard_passthrough[QCOW2_DISCARD_ALWAYS] = true;
91467af674eSKevin Wolf     s->discard_passthrough[QCOW2_DISCARD_REQUEST] =
91567af674eSKevin Wolf         qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_REQUEST,
91667af674eSKevin Wolf                           flags & BDRV_O_UNMAP);
91767af674eSKevin Wolf     s->discard_passthrough[QCOW2_DISCARD_SNAPSHOT] =
91867af674eSKevin Wolf         qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_SNAPSHOT, true);
91967af674eSKevin Wolf     s->discard_passthrough[QCOW2_DISCARD_OTHER] =
92067af674eSKevin Wolf         qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_OTHER, false);
92167af674eSKevin Wolf 
9221fa5cc83SMax Reitz     opt_overlap_check = qemu_opt_get(opts, "overlap-check") ?: "cached";
9231fa5cc83SMax Reitz     if (!strcmp(opt_overlap_check, "none")) {
9241fa5cc83SMax Reitz         overlap_check_template = 0;
9251fa5cc83SMax Reitz     } else if (!strcmp(opt_overlap_check, "constant")) {
9261fa5cc83SMax Reitz         overlap_check_template = QCOW2_OL_CONSTANT;
9271fa5cc83SMax Reitz     } else if (!strcmp(opt_overlap_check, "cached")) {
9281fa5cc83SMax Reitz         overlap_check_template = QCOW2_OL_CACHED;
9291fa5cc83SMax Reitz     } else if (!strcmp(opt_overlap_check, "all")) {
9301fa5cc83SMax Reitz         overlap_check_template = QCOW2_OL_ALL;
9311fa5cc83SMax Reitz     } else {
9321fa5cc83SMax Reitz         error_setg(errp, "Unsupported value '%s' for qcow2 option "
9331fa5cc83SMax Reitz                    "'overlap-check'. Allowed are either of the following: "
9341fa5cc83SMax Reitz                    "none, constant, cached, all", opt_overlap_check);
9351fa5cc83SMax Reitz         qemu_opts_del(opts);
9361fa5cc83SMax Reitz         ret = -EINVAL;
9371fa5cc83SMax Reitz         goto fail;
9381fa5cc83SMax Reitz     }
9391fa5cc83SMax Reitz 
9401fa5cc83SMax Reitz     s->overlap_check = 0;
9411fa5cc83SMax Reitz     for (i = 0; i < QCOW2_OL_MAX_BITNR; i++) {
9421fa5cc83SMax Reitz         /* overlap-check defines a template bitmask, but every flag may be
9431fa5cc83SMax Reitz          * overwritten through the associated boolean option */
9441fa5cc83SMax Reitz         s->overlap_check |=
9451fa5cc83SMax Reitz             qemu_opt_get_bool(opts, overlap_bool_option_names[i],
9461fa5cc83SMax Reitz                               overlap_check_template & (1 << i)) << i;
9471fa5cc83SMax Reitz     }
9483e355390SMax Reitz 
94974c4510aSKevin Wolf     qemu_opts_del(opts);
95074c4510aSKevin Wolf 
95174c4510aSKevin Wolf     if (s->use_lazy_refcounts && s->qcow_version < 3) {
9523ef6c40aSMax Reitz         error_setg(errp, "Lazy refcounts require a qcow2 image with at least "
9533ef6c40aSMax Reitz                    "qemu 1.1 compatibility level");
95474c4510aSKevin Wolf         ret = -EINVAL;
95574c4510aSKevin Wolf         goto fail;
95674c4510aSKevin Wolf     }
95774c4510aSKevin Wolf 
958585f8587Sbellard #ifdef DEBUG_ALLOC
9596cbc3031SPhilipp Hahn     {
9606cbc3031SPhilipp Hahn         BdrvCheckResult result = {0};
961b35278f7SStefan Hajnoczi         qcow2_check_refcounts(bs, &result, 0);
9626cbc3031SPhilipp Hahn     }
963585f8587Sbellard #endif
9646d85a57eSJes Sorensen     return ret;
965585f8587Sbellard 
966585f8587Sbellard  fail:
9676744cbabSKevin Wolf     g_free(s->unknown_header_fields);
96875bab85cSKevin Wolf     cleanup_unknown_header_ext(bs);
969ed6ccf0fSKevin Wolf     qcow2_free_snapshots(bs);
970ed6ccf0fSKevin Wolf     qcow2_refcount_close(bs);
971de82815dSKevin Wolf     qemu_vfree(s->l1_table);
972cf93980eSMax Reitz     /* else pre-write overlap checks in cache_destroy may crash */
973cf93980eSMax Reitz     s->l1_table = NULL;
97429c1a730SKevin Wolf     if (s->l2_table_cache) {
97529c1a730SKevin Wolf         qcow2_cache_destroy(bs, s->l2_table_cache);
97629c1a730SKevin Wolf     }
977c5a33ee9SPrasad Joshi     if (s->refcount_block_cache) {
978c5a33ee9SPrasad Joshi         qcow2_cache_destroy(bs, s->refcount_block_cache);
979c5a33ee9SPrasad Joshi     }
9807267c094SAnthony Liguori     g_free(s->cluster_cache);
981dea43a65SFrediano Ziglio     qemu_vfree(s->cluster_data);
9826d85a57eSJes Sorensen     return ret;
983585f8587Sbellard }
984585f8587Sbellard 
9853baca891SKevin Wolf static void qcow2_refresh_limits(BlockDriverState *bs, Error **errp)
986d34682cdSKevin Wolf {
987d34682cdSKevin Wolf     BDRVQcowState *s = bs->opaque;
988d34682cdSKevin Wolf 
989d34682cdSKevin Wolf     bs->bl.write_zeroes_alignment = s->cluster_sectors;
990d34682cdSKevin Wolf }
991d34682cdSKevin Wolf 
9927c80ab3fSJes Sorensen static int qcow2_set_key(BlockDriverState *bs, const char *key)
993585f8587Sbellard {
994585f8587Sbellard     BDRVQcowState *s = bs->opaque;
995585f8587Sbellard     uint8_t keybuf[16];
996585f8587Sbellard     int len, i;
997585f8587Sbellard 
998585f8587Sbellard     memset(keybuf, 0, 16);
999585f8587Sbellard     len = strlen(key);
1000585f8587Sbellard     if (len > 16)
1001585f8587Sbellard         len = 16;
1002585f8587Sbellard     /* XXX: we could compress the chars to 7 bits to increase
1003585f8587Sbellard        entropy */
1004585f8587Sbellard     for(i = 0;i < len;i++) {
1005585f8587Sbellard         keybuf[i] = key[i];
1006585f8587Sbellard     }
1007585f8587Sbellard     s->crypt_method = s->crypt_method_header;
1008585f8587Sbellard 
1009585f8587Sbellard     if (AES_set_encrypt_key(keybuf, 128, &s->aes_encrypt_key) != 0)
1010585f8587Sbellard         return -1;
1011585f8587Sbellard     if (AES_set_decrypt_key(keybuf, 128, &s->aes_decrypt_key) != 0)
1012585f8587Sbellard         return -1;
1013585f8587Sbellard #if 0
1014585f8587Sbellard     /* test */
1015585f8587Sbellard     {
1016585f8587Sbellard         uint8_t in[16];
1017585f8587Sbellard         uint8_t out[16];
1018585f8587Sbellard         uint8_t tmp[16];
1019585f8587Sbellard         for(i=0;i<16;i++)
1020585f8587Sbellard             in[i] = i;
1021585f8587Sbellard         AES_encrypt(in, tmp, &s->aes_encrypt_key);
1022585f8587Sbellard         AES_decrypt(tmp, out, &s->aes_decrypt_key);
1023585f8587Sbellard         for(i = 0; i < 16; i++)
1024585f8587Sbellard             printf(" %02x", tmp[i]);
1025585f8587Sbellard         printf("\n");
1026585f8587Sbellard         for(i = 0; i < 16; i++)
1027585f8587Sbellard             printf(" %02x", out[i]);
1028585f8587Sbellard         printf("\n");
1029585f8587Sbellard     }
1030585f8587Sbellard #endif
1031585f8587Sbellard     return 0;
1032585f8587Sbellard }
1033585f8587Sbellard 
10344c2e5f8fSKevin Wolf /* We have no actual commit/abort logic for qcow2, but we need to write out any
10354c2e5f8fSKevin Wolf  * unwritten data if we reopen read-only. */
103621d82ac9SJeff Cody static int qcow2_reopen_prepare(BDRVReopenState *state,
103721d82ac9SJeff Cody                                 BlockReopenQueue *queue, Error **errp)
103821d82ac9SJeff Cody {
10394c2e5f8fSKevin Wolf     int ret;
10404c2e5f8fSKevin Wolf 
10414c2e5f8fSKevin Wolf     if ((state->flags & BDRV_O_RDWR) == 0) {
10424c2e5f8fSKevin Wolf         ret = bdrv_flush(state->bs);
10434c2e5f8fSKevin Wolf         if (ret < 0) {
10444c2e5f8fSKevin Wolf             return ret;
10454c2e5f8fSKevin Wolf         }
10464c2e5f8fSKevin Wolf 
10474c2e5f8fSKevin Wolf         ret = qcow2_mark_clean(state->bs);
10484c2e5f8fSKevin Wolf         if (ret < 0) {
10494c2e5f8fSKevin Wolf             return ret;
10504c2e5f8fSKevin Wolf         }
10514c2e5f8fSKevin Wolf     }
10524c2e5f8fSKevin Wolf 
105321d82ac9SJeff Cody     return 0;
105421d82ac9SJeff Cody }
105521d82ac9SJeff Cody 
1056b6b8a333SPaolo Bonzini static int64_t coroutine_fn qcow2_co_get_block_status(BlockDriverState *bs,
1057f8a2e5e3SStefan Hajnoczi         int64_t sector_num, int nb_sectors, int *pnum)
1058585f8587Sbellard {
1059f8a2e5e3SStefan Hajnoczi     BDRVQcowState *s = bs->opaque;
1060585f8587Sbellard     uint64_t cluster_offset;
10614bc74be9SPaolo Bonzini     int index_in_cluster, ret;
10624bc74be9SPaolo Bonzini     int64_t status = 0;
1063585f8587Sbellard 
1064095a9c58Saliguori     *pnum = nb_sectors;
1065f8a2e5e3SStefan Hajnoczi     qemu_co_mutex_lock(&s->lock);
10661c46efaaSKevin Wolf     ret = qcow2_get_cluster_offset(bs, sector_num << 9, pnum, &cluster_offset);
1067f8a2e5e3SStefan Hajnoczi     qemu_co_mutex_unlock(&s->lock);
10681c46efaaSKevin Wolf     if (ret < 0) {
1069d663640cSPaolo Bonzini         return ret;
10701c46efaaSKevin Wolf     }
1071095a9c58Saliguori 
10724bc74be9SPaolo Bonzini     if (cluster_offset != 0 && ret != QCOW2_CLUSTER_COMPRESSED &&
10734bc74be9SPaolo Bonzini         !s->crypt_method) {
10744bc74be9SPaolo Bonzini         index_in_cluster = sector_num & (s->cluster_sectors - 1);
10754bc74be9SPaolo Bonzini         cluster_offset |= (index_in_cluster << BDRV_SECTOR_BITS);
10764bc74be9SPaolo Bonzini         status |= BDRV_BLOCK_OFFSET_VALID | cluster_offset;
10774bc74be9SPaolo Bonzini     }
10784bc74be9SPaolo Bonzini     if (ret == QCOW2_CLUSTER_ZERO) {
10794bc74be9SPaolo Bonzini         status |= BDRV_BLOCK_ZERO;
10804bc74be9SPaolo Bonzini     } else if (ret != QCOW2_CLUSTER_UNALLOCATED) {
10814bc74be9SPaolo Bonzini         status |= BDRV_BLOCK_DATA;
10824bc74be9SPaolo Bonzini     }
10834bc74be9SPaolo Bonzini     return status;
1084585f8587Sbellard }
1085585f8587Sbellard 
1086a9465922Sbellard /* handle reading after the end of the backing file */
1087bd28f835SKevin Wolf int qcow2_backing_read1(BlockDriverState *bs, QEMUIOVector *qiov,
1088bd28f835SKevin Wolf                   int64_t sector_num, int nb_sectors)
1089a9465922Sbellard {
1090a9465922Sbellard     int n1;
1091a9465922Sbellard     if ((sector_num + nb_sectors) <= bs->total_sectors)
1092a9465922Sbellard         return nb_sectors;
1093a9465922Sbellard     if (sector_num >= bs->total_sectors)
1094a9465922Sbellard         n1 = 0;
1095a9465922Sbellard     else
1096a9465922Sbellard         n1 = bs->total_sectors - sector_num;
1097bd28f835SKevin Wolf 
10983d9b4925SMichael Tokarev     qemu_iovec_memset(qiov, 512 * n1, 0, 512 * (nb_sectors - n1));
1099bd28f835SKevin Wolf 
1100a9465922Sbellard     return n1;
1101a9465922Sbellard }
1102a9465922Sbellard 
1103a968168cSDong Xu Wang static coroutine_fn int qcow2_co_readv(BlockDriverState *bs, int64_t sector_num,
11043fc48d09SFrediano Ziglio                           int remaining_sectors, QEMUIOVector *qiov)
11051490791fSaliguori {
1106585f8587Sbellard     BDRVQcowState *s = bs->opaque;
1107a9465922Sbellard     int index_in_cluster, n1;
110868d100e9SKevin Wolf     int ret;
1109faf575c1SFrediano Ziglio     int cur_nr_sectors; /* number of sectors in current iteration */
1110c2bdd990SFrediano Ziglio     uint64_t cluster_offset = 0;
11113fc48d09SFrediano Ziglio     uint64_t bytes_done = 0;
11123fc48d09SFrediano Ziglio     QEMUIOVector hd_qiov;
11133fc48d09SFrediano Ziglio     uint8_t *cluster_data = NULL;
1114585f8587Sbellard 
11153fc48d09SFrediano Ziglio     qemu_iovec_init(&hd_qiov, qiov->niov);
11163fc48d09SFrediano Ziglio 
11173fc48d09SFrediano Ziglio     qemu_co_mutex_lock(&s->lock);
11183fc48d09SFrediano Ziglio 
11193fc48d09SFrediano Ziglio     while (remaining_sectors != 0) {
1120585f8587Sbellard 
1121faf575c1SFrediano Ziglio         /* prepare next request */
11223fc48d09SFrediano Ziglio         cur_nr_sectors = remaining_sectors;
1123bd28f835SKevin Wolf         if (s->crypt_method) {
1124faf575c1SFrediano Ziglio             cur_nr_sectors = MIN(cur_nr_sectors,
1125bd28f835SKevin Wolf                 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors);
1126bd28f835SKevin Wolf         }
1127bd28f835SKevin Wolf 
11283fc48d09SFrediano Ziglio         ret = qcow2_get_cluster_offset(bs, sector_num << 9,
1129c2bdd990SFrediano Ziglio             &cur_nr_sectors, &cluster_offset);
11301c46efaaSKevin Wolf         if (ret < 0) {
11313fc48d09SFrediano Ziglio             goto fail;
11321c46efaaSKevin Wolf         }
11331c46efaaSKevin Wolf 
11343fc48d09SFrediano Ziglio         index_in_cluster = sector_num & (s->cluster_sectors - 1);
1135585f8587Sbellard 
11363fc48d09SFrediano Ziglio         qemu_iovec_reset(&hd_qiov);
11371b093c48SMichael Tokarev         qemu_iovec_concat(&hd_qiov, qiov, bytes_done,
1138faf575c1SFrediano Ziglio             cur_nr_sectors * 512);
1139bd28f835SKevin Wolf 
114068d000a3SKevin Wolf         switch (ret) {
114168d000a3SKevin Wolf         case QCOW2_CLUSTER_UNALLOCATED:
1142bd28f835SKevin Wolf 
1143585f8587Sbellard             if (bs->backing_hd) {
1144585f8587Sbellard                 /* read from the base image */
11453fc48d09SFrediano Ziglio                 n1 = qcow2_backing_read1(bs->backing_hd, &hd_qiov,
11463fc48d09SFrediano Ziglio                     sector_num, cur_nr_sectors);
1147a9465922Sbellard                 if (n1 > 0) {
114844deba5aSKevin Wolf                     QEMUIOVector local_qiov;
114944deba5aSKevin Wolf 
115044deba5aSKevin Wolf                     qemu_iovec_init(&local_qiov, hd_qiov.niov);
115144deba5aSKevin Wolf                     qemu_iovec_concat(&local_qiov, &hd_qiov, 0,
115244deba5aSKevin Wolf                                       n1 * BDRV_SECTOR_SIZE);
115344deba5aSKevin Wolf 
115466f82ceeSKevin Wolf                     BLKDBG_EVENT(bs->file, BLKDBG_READ_BACKING_AIO);
115568d100e9SKevin Wolf                     qemu_co_mutex_unlock(&s->lock);
11563fc48d09SFrediano Ziglio                     ret = bdrv_co_readv(bs->backing_hd, sector_num,
115744deba5aSKevin Wolf                                         n1, &local_qiov);
115868d100e9SKevin Wolf                     qemu_co_mutex_lock(&s->lock);
115944deba5aSKevin Wolf 
116044deba5aSKevin Wolf                     qemu_iovec_destroy(&local_qiov);
116144deba5aSKevin Wolf 
116268d100e9SKevin Wolf                     if (ret < 0) {
11633fc48d09SFrediano Ziglio                         goto fail;
11643ab4c7e9SKevin Wolf                     }
11651490791fSaliguori                 }
1166a9465922Sbellard             } else {
1167585f8587Sbellard                 /* Note: in this case, no need to wait */
11683d9b4925SMichael Tokarev                 qemu_iovec_memset(&hd_qiov, 0, 0, 512 * cur_nr_sectors);
11691490791fSaliguori             }
117068d000a3SKevin Wolf             break;
117168d000a3SKevin Wolf 
11726377af48SKevin Wolf         case QCOW2_CLUSTER_ZERO:
11733d9b4925SMichael Tokarev             qemu_iovec_memset(&hd_qiov, 0, 0, 512 * cur_nr_sectors);
11746377af48SKevin Wolf             break;
11756377af48SKevin Wolf 
117668d000a3SKevin Wolf         case QCOW2_CLUSTER_COMPRESSED:
1177585f8587Sbellard             /* add AIO support for compressed blocks ? */
1178c2bdd990SFrediano Ziglio             ret = qcow2_decompress_cluster(bs, cluster_offset);
11798af36488SKevin Wolf             if (ret < 0) {
11803fc48d09SFrediano Ziglio                 goto fail;
11818af36488SKevin Wolf             }
1182bd28f835SKevin Wolf 
118303396148SMichael Tokarev             qemu_iovec_from_buf(&hd_qiov, 0,
1184bd28f835SKevin Wolf                 s->cluster_cache + index_in_cluster * 512,
1185faf575c1SFrediano Ziglio                 512 * cur_nr_sectors);
118668d000a3SKevin Wolf             break;
118768d000a3SKevin Wolf 
118868d000a3SKevin Wolf         case QCOW2_CLUSTER_NORMAL:
1189c2bdd990SFrediano Ziglio             if ((cluster_offset & 511) != 0) {
11903fc48d09SFrediano Ziglio                 ret = -EIO;
11913fc48d09SFrediano Ziglio                 goto fail;
1192585f8587Sbellard             }
1193c87c0672Saliguori 
1194bd28f835SKevin Wolf             if (s->crypt_method) {
1195bd28f835SKevin Wolf                 /*
1196bd28f835SKevin Wolf                  * For encrypted images, read everything into a temporary
1197bd28f835SKevin Wolf                  * contiguous buffer on which the AES functions can work.
1198bd28f835SKevin Wolf                  */
11993fc48d09SFrediano Ziglio                 if (!cluster_data) {
12003fc48d09SFrediano Ziglio                     cluster_data =
1201de82815dSKevin Wolf                         qemu_try_blockalign(bs->file, QCOW_MAX_CRYPT_CLUSTERS
1202de82815dSKevin Wolf                                                       * s->cluster_size);
1203de82815dSKevin Wolf                     if (cluster_data == NULL) {
1204de82815dSKevin Wolf                         ret = -ENOMEM;
1205de82815dSKevin Wolf                         goto fail;
1206de82815dSKevin Wolf                     }
1207bd28f835SKevin Wolf                 }
1208bd28f835SKevin Wolf 
1209faf575c1SFrediano Ziglio                 assert(cur_nr_sectors <=
1210bd28f835SKevin Wolf                     QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors);
12113fc48d09SFrediano Ziglio                 qemu_iovec_reset(&hd_qiov);
12123fc48d09SFrediano Ziglio                 qemu_iovec_add(&hd_qiov, cluster_data,
1213faf575c1SFrediano Ziglio                     512 * cur_nr_sectors);
1214bd28f835SKevin Wolf             }
1215bd28f835SKevin Wolf 
121666f82ceeSKevin Wolf             BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);
121768d100e9SKevin Wolf             qemu_co_mutex_unlock(&s->lock);
121868d100e9SKevin Wolf             ret = bdrv_co_readv(bs->file,
1219c2bdd990SFrediano Ziglio                                 (cluster_offset >> 9) + index_in_cluster,
12203fc48d09SFrediano Ziglio                                 cur_nr_sectors, &hd_qiov);
122168d100e9SKevin Wolf             qemu_co_mutex_lock(&s->lock);
122268d100e9SKevin Wolf             if (ret < 0) {
12233fc48d09SFrediano Ziglio                 goto fail;
1224585f8587Sbellard             }
1225faf575c1SFrediano Ziglio             if (s->crypt_method) {
12263fc48d09SFrediano Ziglio                 qcow2_encrypt_sectors(s, sector_num,  cluster_data,
12273fc48d09SFrediano Ziglio                     cluster_data, cur_nr_sectors, 0, &s->aes_decrypt_key);
122803396148SMichael Tokarev                 qemu_iovec_from_buf(qiov, bytes_done,
122903396148SMichael Tokarev                     cluster_data, 512 * cur_nr_sectors);
1230171e3d6bSKevin Wolf             }
123168d000a3SKevin Wolf             break;
123268d000a3SKevin Wolf 
123368d000a3SKevin Wolf         default:
123468d000a3SKevin Wolf             g_assert_not_reached();
123568d000a3SKevin Wolf             ret = -EIO;
123668d000a3SKevin Wolf             goto fail;
1237faf575c1SFrediano Ziglio         }
1238faf575c1SFrediano Ziglio 
12393fc48d09SFrediano Ziglio         remaining_sectors -= cur_nr_sectors;
12403fc48d09SFrediano Ziglio         sector_num += cur_nr_sectors;
12413fc48d09SFrediano Ziglio         bytes_done += cur_nr_sectors * 512;
12425ebaa27eSFrediano Ziglio     }
12433fc48d09SFrediano Ziglio     ret = 0;
1244f141eafeSaliguori 
12453fc48d09SFrediano Ziglio fail:
124668d100e9SKevin Wolf     qemu_co_mutex_unlock(&s->lock);
124768d100e9SKevin Wolf 
12483fc48d09SFrediano Ziglio     qemu_iovec_destroy(&hd_qiov);
1249dea43a65SFrediano Ziglio     qemu_vfree(cluster_data);
125068d100e9SKevin Wolf 
125168d100e9SKevin Wolf     return ret;
1252585f8587Sbellard }
1253585f8587Sbellard 
1254a968168cSDong Xu Wang static coroutine_fn int qcow2_co_writev(BlockDriverState *bs,
12553fc48d09SFrediano Ziglio                            int64_t sector_num,
12563fc48d09SFrediano Ziglio                            int remaining_sectors,
12573fc48d09SFrediano Ziglio                            QEMUIOVector *qiov)
1258585f8587Sbellard {
1259585f8587Sbellard     BDRVQcowState *s = bs->opaque;
1260585f8587Sbellard     int index_in_cluster;
126168d100e9SKevin Wolf     int ret;
1262faf575c1SFrediano Ziglio     int cur_nr_sectors; /* number of sectors in current iteration */
1263c2bdd990SFrediano Ziglio     uint64_t cluster_offset;
12643fc48d09SFrediano Ziglio     QEMUIOVector hd_qiov;
12653fc48d09SFrediano Ziglio     uint64_t bytes_done = 0;
12663fc48d09SFrediano Ziglio     uint8_t *cluster_data = NULL;
12678d2497c3SKevin Wolf     QCowL2Meta *l2meta = NULL;
1268c2271403SFrediano Ziglio 
12693cce16f4SKevin Wolf     trace_qcow2_writev_start_req(qemu_coroutine_self(), sector_num,
12703cce16f4SKevin Wolf                                  remaining_sectors);
12713cce16f4SKevin Wolf 
12723fc48d09SFrediano Ziglio     qemu_iovec_init(&hd_qiov, qiov->niov);
1273585f8587Sbellard 
12743fc48d09SFrediano Ziglio     s->cluster_cache_offset = -1; /* disable compressed cache */
12753fc48d09SFrediano Ziglio 
12763fc48d09SFrediano Ziglio     qemu_co_mutex_lock(&s->lock);
12773fc48d09SFrediano Ziglio 
12783fc48d09SFrediano Ziglio     while (remaining_sectors != 0) {
12793fc48d09SFrediano Ziglio 
1280f50f88b9SKevin Wolf         l2meta = NULL;
1281cf5c1a23SKevin Wolf 
12823cce16f4SKevin Wolf         trace_qcow2_writev_start_part(qemu_coroutine_self());
12833fc48d09SFrediano Ziglio         index_in_cluster = sector_num & (s->cluster_sectors - 1);
128416f0587eSHu Tao         cur_nr_sectors = remaining_sectors;
1285095a9c58Saliguori         if (s->crypt_method &&
128616f0587eSHu Tao             cur_nr_sectors >
128716f0587eSHu Tao             QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors - index_in_cluster) {
128816f0587eSHu Tao             cur_nr_sectors =
128916f0587eSHu Tao                 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors - index_in_cluster;
12905ebaa27eSFrediano Ziglio         }
1291095a9c58Saliguori 
12923fc48d09SFrediano Ziglio         ret = qcow2_alloc_cluster_offset(bs, sector_num << 9,
129316f0587eSHu Tao             &cur_nr_sectors, &cluster_offset, &l2meta);
1294148da7eaSKevin Wolf         if (ret < 0) {
12953fc48d09SFrediano Ziglio             goto fail;
1296148da7eaSKevin Wolf         }
1297148da7eaSKevin Wolf 
1298c2bdd990SFrediano Ziglio         assert((cluster_offset & 511) == 0);
1299148da7eaSKevin Wolf 
13003fc48d09SFrediano Ziglio         qemu_iovec_reset(&hd_qiov);
13011b093c48SMichael Tokarev         qemu_iovec_concat(&hd_qiov, qiov, bytes_done,
1302faf575c1SFrediano Ziglio             cur_nr_sectors * 512);
13036f5f060bSKevin Wolf 
1304585f8587Sbellard         if (s->crypt_method) {
13053fc48d09SFrediano Ziglio             if (!cluster_data) {
1306de82815dSKevin Wolf                 cluster_data = qemu_try_blockalign(bs->file,
1307de82815dSKevin Wolf                                                    QCOW_MAX_CRYPT_CLUSTERS
1308de82815dSKevin Wolf                                                    * s->cluster_size);
1309de82815dSKevin Wolf                 if (cluster_data == NULL) {
1310de82815dSKevin Wolf                     ret = -ENOMEM;
1311de82815dSKevin Wolf                     goto fail;
1312de82815dSKevin Wolf                 }
1313585f8587Sbellard             }
13146f5f060bSKevin Wolf 
13153fc48d09SFrediano Ziglio             assert(hd_qiov.size <=
13165ebaa27eSFrediano Ziglio                    QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
1317d5e6b161SMichael Tokarev             qemu_iovec_to_buf(&hd_qiov, 0, cluster_data, hd_qiov.size);
13186f5f060bSKevin Wolf 
13193fc48d09SFrediano Ziglio             qcow2_encrypt_sectors(s, sector_num, cluster_data,
13203fc48d09SFrediano Ziglio                 cluster_data, cur_nr_sectors, 1, &s->aes_encrypt_key);
13216f5f060bSKevin Wolf 
13223fc48d09SFrediano Ziglio             qemu_iovec_reset(&hd_qiov);
13233fc48d09SFrediano Ziglio             qemu_iovec_add(&hd_qiov, cluster_data,
1324faf575c1SFrediano Ziglio                 cur_nr_sectors * 512);
1325585f8587Sbellard         }
13266f5f060bSKevin Wolf 
1327231bb267SMax Reitz         ret = qcow2_pre_write_overlap_check(bs, 0,
1328cf93980eSMax Reitz                 cluster_offset + index_in_cluster * BDRV_SECTOR_SIZE,
1329cf93980eSMax Reitz                 cur_nr_sectors * BDRV_SECTOR_SIZE);
1330cf93980eSMax Reitz         if (ret < 0) {
1331cf93980eSMax Reitz             goto fail;
1332cf93980eSMax Reitz         }
1333cf93980eSMax Reitz 
133468d100e9SKevin Wolf         qemu_co_mutex_unlock(&s->lock);
133567a7a0ebSKevin Wolf         BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO);
13363cce16f4SKevin Wolf         trace_qcow2_writev_data(qemu_coroutine_self(),
13373cce16f4SKevin Wolf                                 (cluster_offset >> 9) + index_in_cluster);
133868d100e9SKevin Wolf         ret = bdrv_co_writev(bs->file,
1339c2bdd990SFrediano Ziglio                              (cluster_offset >> 9) + index_in_cluster,
13403fc48d09SFrediano Ziglio                              cur_nr_sectors, &hd_qiov);
134168d100e9SKevin Wolf         qemu_co_mutex_lock(&s->lock);
134268d100e9SKevin Wolf         if (ret < 0) {
13433fc48d09SFrediano Ziglio             goto fail;
1344171e3d6bSKevin Wolf         }
1345f141eafeSaliguori 
134688c6588cSKevin Wolf         while (l2meta != NULL) {
134788c6588cSKevin Wolf             QCowL2Meta *next;
134888c6588cSKevin Wolf 
1349cf5c1a23SKevin Wolf             ret = qcow2_alloc_cluster_link_l2(bs, l2meta);
1350faf575c1SFrediano Ziglio             if (ret < 0) {
13513fc48d09SFrediano Ziglio                 goto fail;
1352faf575c1SFrediano Ziglio             }
1353faf575c1SFrediano Ziglio 
13544e95314eSKevin Wolf             /* Take the request off the list of running requests */
13554e95314eSKevin Wolf             if (l2meta->nb_clusters != 0) {
13564e95314eSKevin Wolf                 QLIST_REMOVE(l2meta, next_in_flight);
13574e95314eSKevin Wolf             }
13584e95314eSKevin Wolf 
13594e95314eSKevin Wolf             qemu_co_queue_restart_all(&l2meta->dependent_requests);
13604e95314eSKevin Wolf 
136188c6588cSKevin Wolf             next = l2meta->next;
1362cf5c1a23SKevin Wolf             g_free(l2meta);
136388c6588cSKevin Wolf             l2meta = next;
1364f50f88b9SKevin Wolf         }
13650fa9131aSKevin Wolf 
13663fc48d09SFrediano Ziglio         remaining_sectors -= cur_nr_sectors;
13673fc48d09SFrediano Ziglio         sector_num += cur_nr_sectors;
13683fc48d09SFrediano Ziglio         bytes_done += cur_nr_sectors * 512;
13693cce16f4SKevin Wolf         trace_qcow2_writev_done_part(qemu_coroutine_self(), cur_nr_sectors);
13705ebaa27eSFrediano Ziglio     }
13713fc48d09SFrediano Ziglio     ret = 0;
1372faf575c1SFrediano Ziglio 
13733fc48d09SFrediano Ziglio fail:
13744e95314eSKevin Wolf     qemu_co_mutex_unlock(&s->lock);
13754e95314eSKevin Wolf 
137688c6588cSKevin Wolf     while (l2meta != NULL) {
137788c6588cSKevin Wolf         QCowL2Meta *next;
137888c6588cSKevin Wolf 
13794e95314eSKevin Wolf         if (l2meta->nb_clusters != 0) {
13804e95314eSKevin Wolf             QLIST_REMOVE(l2meta, next_in_flight);
13814e95314eSKevin Wolf         }
13824e95314eSKevin Wolf         qemu_co_queue_restart_all(&l2meta->dependent_requests);
138388c6588cSKevin Wolf 
138488c6588cSKevin Wolf         next = l2meta->next;
1385cf5c1a23SKevin Wolf         g_free(l2meta);
138688c6588cSKevin Wolf         l2meta = next;
1387cf5c1a23SKevin Wolf     }
13880fa9131aSKevin Wolf 
13893fc48d09SFrediano Ziglio     qemu_iovec_destroy(&hd_qiov);
1390dea43a65SFrediano Ziglio     qemu_vfree(cluster_data);
13913cce16f4SKevin Wolf     trace_qcow2_writev_done_req(qemu_coroutine_self(), ret);
139242496d62SKevin Wolf 
139368d100e9SKevin Wolf     return ret;
1394585f8587Sbellard }
1395585f8587Sbellard 
13967c80ab3fSJes Sorensen static void qcow2_close(BlockDriverState *bs)
1397585f8587Sbellard {
1398585f8587Sbellard     BDRVQcowState *s = bs->opaque;
1399de82815dSKevin Wolf     qemu_vfree(s->l1_table);
1400cf93980eSMax Reitz     /* else pre-write overlap checks in cache_destroy may crash */
1401cf93980eSMax Reitz     s->l1_table = NULL;
140229c1a730SKevin Wolf 
140327eb6c09SKevin Wolf     if (!(bs->open_flags & BDRV_O_INCOMING)) {
140429c1a730SKevin Wolf         qcow2_cache_flush(bs, s->l2_table_cache);
140529c1a730SKevin Wolf         qcow2_cache_flush(bs, s->refcount_block_cache);
140629c1a730SKevin Wolf 
1407c61d0004SStefan Hajnoczi         qcow2_mark_clean(bs);
140827eb6c09SKevin Wolf     }
1409c61d0004SStefan Hajnoczi 
141029c1a730SKevin Wolf     qcow2_cache_destroy(bs, s->l2_table_cache);
141129c1a730SKevin Wolf     qcow2_cache_destroy(bs, s->refcount_block_cache);
141229c1a730SKevin Wolf 
14136744cbabSKevin Wolf     g_free(s->unknown_header_fields);
141475bab85cSKevin Wolf     cleanup_unknown_header_ext(bs);
14156744cbabSKevin Wolf 
14167267c094SAnthony Liguori     g_free(s->cluster_cache);
1417dea43a65SFrediano Ziglio     qemu_vfree(s->cluster_data);
1418ed6ccf0fSKevin Wolf     qcow2_refcount_close(bs);
141928c1202bSLi Zhi Hui     qcow2_free_snapshots(bs);
1420585f8587Sbellard }
1421585f8587Sbellard 
14225a8a30dbSKevin Wolf static void qcow2_invalidate_cache(BlockDriverState *bs, Error **errp)
142306d9260fSAnthony Liguori {
142406d9260fSAnthony Liguori     BDRVQcowState *s = bs->opaque;
142506d9260fSAnthony Liguori     int flags = s->flags;
142606d9260fSAnthony Liguori     AES_KEY aes_encrypt_key;
142706d9260fSAnthony Liguori     AES_KEY aes_decrypt_key;
142806d9260fSAnthony Liguori     uint32_t crypt_method = 0;
1429acdfb480SKevin Wolf     QDict *options;
14305a8a30dbSKevin Wolf     Error *local_err = NULL;
14315a8a30dbSKevin Wolf     int ret;
143206d9260fSAnthony Liguori 
143306d9260fSAnthony Liguori     /*
143406d9260fSAnthony Liguori      * Backing files are read-only which makes all of their metadata immutable,
143506d9260fSAnthony Liguori      * that means we don't have to worry about reopening them here.
143606d9260fSAnthony Liguori      */
143706d9260fSAnthony Liguori 
143806d9260fSAnthony Liguori     if (s->crypt_method) {
143906d9260fSAnthony Liguori         crypt_method = s->crypt_method;
144006d9260fSAnthony Liguori         memcpy(&aes_encrypt_key, &s->aes_encrypt_key, sizeof(aes_encrypt_key));
144106d9260fSAnthony Liguori         memcpy(&aes_decrypt_key, &s->aes_decrypt_key, sizeof(aes_decrypt_key));
144206d9260fSAnthony Liguori     }
144306d9260fSAnthony Liguori 
144406d9260fSAnthony Liguori     qcow2_close(bs);
144506d9260fSAnthony Liguori 
14465a8a30dbSKevin Wolf     bdrv_invalidate_cache(bs->file, &local_err);
14475a8a30dbSKevin Wolf     if (local_err) {
14485a8a30dbSKevin Wolf         error_propagate(errp, local_err);
14495a8a30dbSKevin Wolf         return;
14505a8a30dbSKevin Wolf     }
14513456a8d1SKevin Wolf 
145206d9260fSAnthony Liguori     memset(s, 0, sizeof(BDRVQcowState));
1453d475e5acSKevin Wolf     options = qdict_clone_shallow(bs->options);
14545a8a30dbSKevin Wolf 
14555a8a30dbSKevin Wolf     ret = qcow2_open(bs, options, flags, &local_err);
1456a1904e48SMarkus Armbruster     QDECREF(options);
14575a8a30dbSKevin Wolf     if (local_err) {
14585a8a30dbSKevin Wolf         error_setg(errp, "Could not reopen qcow2 layer: %s",
14595a8a30dbSKevin Wolf                    error_get_pretty(local_err));
14605a8a30dbSKevin Wolf         error_free(local_err);
14615a8a30dbSKevin Wolf         return;
14625a8a30dbSKevin Wolf     } else if (ret < 0) {
14635a8a30dbSKevin Wolf         error_setg_errno(errp, -ret, "Could not reopen qcow2 layer");
14645a8a30dbSKevin Wolf         return;
14655a8a30dbSKevin Wolf     }
1466acdfb480SKevin Wolf 
146706d9260fSAnthony Liguori     if (crypt_method) {
146806d9260fSAnthony Liguori         s->crypt_method = crypt_method;
146906d9260fSAnthony Liguori         memcpy(&s->aes_encrypt_key, &aes_encrypt_key, sizeof(aes_encrypt_key));
147006d9260fSAnthony Liguori         memcpy(&s->aes_decrypt_key, &aes_decrypt_key, sizeof(aes_decrypt_key));
147106d9260fSAnthony Liguori     }
147206d9260fSAnthony Liguori }
147306d9260fSAnthony Liguori 
1474e24e49e6SKevin Wolf static size_t header_ext_add(char *buf, uint32_t magic, const void *s,
1475e24e49e6SKevin Wolf     size_t len, size_t buflen)
1476756e6736SKevin Wolf {
1477e24e49e6SKevin Wolf     QCowExtension *ext_backing_fmt = (QCowExtension*) buf;
1478e24e49e6SKevin Wolf     size_t ext_len = sizeof(QCowExtension) + ((len + 7) & ~7);
1479756e6736SKevin Wolf 
1480e24e49e6SKevin Wolf     if (buflen < ext_len) {
1481756e6736SKevin Wolf         return -ENOSPC;
1482756e6736SKevin Wolf     }
1483756e6736SKevin Wolf 
1484e24e49e6SKevin Wolf     *ext_backing_fmt = (QCowExtension) {
1485e24e49e6SKevin Wolf         .magic  = cpu_to_be32(magic),
1486e24e49e6SKevin Wolf         .len    = cpu_to_be32(len),
1487e24e49e6SKevin Wolf     };
1488e24e49e6SKevin Wolf     memcpy(buf + sizeof(QCowExtension), s, len);
1489756e6736SKevin Wolf 
1490e24e49e6SKevin Wolf     return ext_len;
1491756e6736SKevin Wolf }
1492756e6736SKevin Wolf 
1493e24e49e6SKevin Wolf /*
1494e24e49e6SKevin Wolf  * Updates the qcow2 header, including the variable length parts of it, i.e.
1495e24e49e6SKevin Wolf  * the backing file name and all extensions. qcow2 was not designed to allow
1496e24e49e6SKevin Wolf  * such changes, so if we run out of space (we can only use the first cluster)
1497e24e49e6SKevin Wolf  * this function may fail.
1498e24e49e6SKevin Wolf  *
1499e24e49e6SKevin Wolf  * Returns 0 on success, -errno in error cases.
1500e24e49e6SKevin Wolf  */
1501e24e49e6SKevin Wolf int qcow2_update_header(BlockDriverState *bs)
1502e24e49e6SKevin Wolf {
1503e24e49e6SKevin Wolf     BDRVQcowState *s = bs->opaque;
1504e24e49e6SKevin Wolf     QCowHeader *header;
1505e24e49e6SKevin Wolf     char *buf;
1506e24e49e6SKevin Wolf     size_t buflen = s->cluster_size;
1507e24e49e6SKevin Wolf     int ret;
1508e24e49e6SKevin Wolf     uint64_t total_size;
1509e24e49e6SKevin Wolf     uint32_t refcount_table_clusters;
15106744cbabSKevin Wolf     size_t header_length;
151175bab85cSKevin Wolf     Qcow2UnknownHeaderExtension *uext;
1512e24e49e6SKevin Wolf 
1513e24e49e6SKevin Wolf     buf = qemu_blockalign(bs, buflen);
1514e24e49e6SKevin Wolf 
1515e24e49e6SKevin Wolf     /* Header structure */
1516e24e49e6SKevin Wolf     header = (QCowHeader*) buf;
1517e24e49e6SKevin Wolf 
1518e24e49e6SKevin Wolf     if (buflen < sizeof(*header)) {
1519e24e49e6SKevin Wolf         ret = -ENOSPC;
1520e24e49e6SKevin Wolf         goto fail;
1521756e6736SKevin Wolf     }
1522756e6736SKevin Wolf 
15236744cbabSKevin Wolf     header_length = sizeof(*header) + s->unknown_header_fields_size;
1524e24e49e6SKevin Wolf     total_size = bs->total_sectors * BDRV_SECTOR_SIZE;
1525e24e49e6SKevin Wolf     refcount_table_clusters = s->refcount_table_size >> (s->cluster_bits - 3);
1526e24e49e6SKevin Wolf 
1527e24e49e6SKevin Wolf     *header = (QCowHeader) {
15286744cbabSKevin Wolf         /* Version 2 fields */
1529e24e49e6SKevin Wolf         .magic                  = cpu_to_be32(QCOW_MAGIC),
15306744cbabSKevin Wolf         .version                = cpu_to_be32(s->qcow_version),
1531e24e49e6SKevin Wolf         .backing_file_offset    = 0,
1532e24e49e6SKevin Wolf         .backing_file_size      = 0,
1533e24e49e6SKevin Wolf         .cluster_bits           = cpu_to_be32(s->cluster_bits),
1534e24e49e6SKevin Wolf         .size                   = cpu_to_be64(total_size),
1535e24e49e6SKevin Wolf         .crypt_method           = cpu_to_be32(s->crypt_method_header),
1536e24e49e6SKevin Wolf         .l1_size                = cpu_to_be32(s->l1_size),
1537e24e49e6SKevin Wolf         .l1_table_offset        = cpu_to_be64(s->l1_table_offset),
1538e24e49e6SKevin Wolf         .refcount_table_offset  = cpu_to_be64(s->refcount_table_offset),
1539e24e49e6SKevin Wolf         .refcount_table_clusters = cpu_to_be32(refcount_table_clusters),
1540e24e49e6SKevin Wolf         .nb_snapshots           = cpu_to_be32(s->nb_snapshots),
1541e24e49e6SKevin Wolf         .snapshots_offset       = cpu_to_be64(s->snapshots_offset),
15426744cbabSKevin Wolf 
15436744cbabSKevin Wolf         /* Version 3 fields */
15446744cbabSKevin Wolf         .incompatible_features  = cpu_to_be64(s->incompatible_features),
15456744cbabSKevin Wolf         .compatible_features    = cpu_to_be64(s->compatible_features),
15466744cbabSKevin Wolf         .autoclear_features     = cpu_to_be64(s->autoclear_features),
1547b6481f37SMax Reitz         .refcount_order         = cpu_to_be32(s->refcount_order),
15486744cbabSKevin Wolf         .header_length          = cpu_to_be32(header_length),
1549e24e49e6SKevin Wolf     };
1550e24e49e6SKevin Wolf 
15516744cbabSKevin Wolf     /* For older versions, write a shorter header */
15526744cbabSKevin Wolf     switch (s->qcow_version) {
15536744cbabSKevin Wolf     case 2:
15546744cbabSKevin Wolf         ret = offsetof(QCowHeader, incompatible_features);
15556744cbabSKevin Wolf         break;
15566744cbabSKevin Wolf     case 3:
15576744cbabSKevin Wolf         ret = sizeof(*header);
15586744cbabSKevin Wolf         break;
15596744cbabSKevin Wolf     default:
1560b6c14762SJim Meyering         ret = -EINVAL;
1561b6c14762SJim Meyering         goto fail;
15626744cbabSKevin Wolf     }
15636744cbabSKevin Wolf 
15646744cbabSKevin Wolf     buf += ret;
15656744cbabSKevin Wolf     buflen -= ret;
15666744cbabSKevin Wolf     memset(buf, 0, buflen);
15676744cbabSKevin Wolf 
15686744cbabSKevin Wolf     /* Preserve any unknown field in the header */
15696744cbabSKevin Wolf     if (s->unknown_header_fields_size) {
15706744cbabSKevin Wolf         if (buflen < s->unknown_header_fields_size) {
15716744cbabSKevin Wolf             ret = -ENOSPC;
15726744cbabSKevin Wolf             goto fail;
15736744cbabSKevin Wolf         }
15746744cbabSKevin Wolf 
15756744cbabSKevin Wolf         memcpy(buf, s->unknown_header_fields, s->unknown_header_fields_size);
15766744cbabSKevin Wolf         buf += s->unknown_header_fields_size;
15776744cbabSKevin Wolf         buflen -= s->unknown_header_fields_size;
15786744cbabSKevin Wolf     }
1579e24e49e6SKevin Wolf 
1580e24e49e6SKevin Wolf     /* Backing file format header extension */
1581e24e49e6SKevin Wolf     if (*bs->backing_format) {
1582e24e49e6SKevin Wolf         ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BACKING_FORMAT,
1583e24e49e6SKevin Wolf                              bs->backing_format, strlen(bs->backing_format),
1584e24e49e6SKevin Wolf                              buflen);
1585756e6736SKevin Wolf         if (ret < 0) {
1586756e6736SKevin Wolf             goto fail;
1587756e6736SKevin Wolf         }
1588756e6736SKevin Wolf 
1589e24e49e6SKevin Wolf         buf += ret;
1590e24e49e6SKevin Wolf         buflen -= ret;
1591e24e49e6SKevin Wolf     }
1592756e6736SKevin Wolf 
1593cfcc4c62SKevin Wolf     /* Feature table */
1594cfcc4c62SKevin Wolf     Qcow2Feature features[] = {
1595c61d0004SStefan Hajnoczi         {
1596c61d0004SStefan Hajnoczi             .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
1597c61d0004SStefan Hajnoczi             .bit  = QCOW2_INCOMPAT_DIRTY_BITNR,
1598c61d0004SStefan Hajnoczi             .name = "dirty bit",
1599c61d0004SStefan Hajnoczi         },
1600bfe8043eSStefan Hajnoczi         {
160169c98726SMax Reitz             .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
160269c98726SMax Reitz             .bit  = QCOW2_INCOMPAT_CORRUPT_BITNR,
160369c98726SMax Reitz             .name = "corrupt bit",
160469c98726SMax Reitz         },
160569c98726SMax Reitz         {
1606bfe8043eSStefan Hajnoczi             .type = QCOW2_FEAT_TYPE_COMPATIBLE,
1607bfe8043eSStefan Hajnoczi             .bit  = QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR,
1608bfe8043eSStefan Hajnoczi             .name = "lazy refcounts",
1609bfe8043eSStefan Hajnoczi         },
1610cfcc4c62SKevin Wolf     };
1611cfcc4c62SKevin Wolf 
1612cfcc4c62SKevin Wolf     ret = header_ext_add(buf, QCOW2_EXT_MAGIC_FEATURE_TABLE,
1613cfcc4c62SKevin Wolf                          features, sizeof(features), buflen);
1614cfcc4c62SKevin Wolf     if (ret < 0) {
1615cfcc4c62SKevin Wolf         goto fail;
1616cfcc4c62SKevin Wolf     }
1617cfcc4c62SKevin Wolf     buf += ret;
1618cfcc4c62SKevin Wolf     buflen -= ret;
1619cfcc4c62SKevin Wolf 
162075bab85cSKevin Wolf     /* Keep unknown header extensions */
162175bab85cSKevin Wolf     QLIST_FOREACH(uext, &s->unknown_header_ext, next) {
162275bab85cSKevin Wolf         ret = header_ext_add(buf, uext->magic, uext->data, uext->len, buflen);
162375bab85cSKevin Wolf         if (ret < 0) {
162475bab85cSKevin Wolf             goto fail;
162575bab85cSKevin Wolf         }
162675bab85cSKevin Wolf 
162775bab85cSKevin Wolf         buf += ret;
162875bab85cSKevin Wolf         buflen -= ret;
162975bab85cSKevin Wolf     }
163075bab85cSKevin Wolf 
1631e24e49e6SKevin Wolf     /* End of header extensions */
1632e24e49e6SKevin Wolf     ret = header_ext_add(buf, QCOW2_EXT_MAGIC_END, NULL, 0, buflen);
1633756e6736SKevin Wolf     if (ret < 0) {
1634756e6736SKevin Wolf         goto fail;
1635756e6736SKevin Wolf     }
1636756e6736SKevin Wolf 
1637e24e49e6SKevin Wolf     buf += ret;
1638e24e49e6SKevin Wolf     buflen -= ret;
1639e24e49e6SKevin Wolf 
1640e24e49e6SKevin Wolf     /* Backing file name */
1641e24e49e6SKevin Wolf     if (*bs->backing_file) {
1642e24e49e6SKevin Wolf         size_t backing_file_len = strlen(bs->backing_file);
1643e24e49e6SKevin Wolf 
1644e24e49e6SKevin Wolf         if (buflen < backing_file_len) {
1645e24e49e6SKevin Wolf             ret = -ENOSPC;
1646e24e49e6SKevin Wolf             goto fail;
1647e24e49e6SKevin Wolf         }
1648e24e49e6SKevin Wolf 
164900ea1881SJim Meyering         /* Using strncpy is ok here, since buf is not NUL-terminated. */
1650e24e49e6SKevin Wolf         strncpy(buf, bs->backing_file, buflen);
1651e24e49e6SKevin Wolf 
1652e24e49e6SKevin Wolf         header->backing_file_offset = cpu_to_be64(buf - ((char*) header));
1653e24e49e6SKevin Wolf         header->backing_file_size   = cpu_to_be32(backing_file_len);
1654e24e49e6SKevin Wolf     }
1655e24e49e6SKevin Wolf 
1656e24e49e6SKevin Wolf     /* Write the new header */
1657e24e49e6SKevin Wolf     ret = bdrv_pwrite(bs->file, 0, header, s->cluster_size);
1658756e6736SKevin Wolf     if (ret < 0) {
1659756e6736SKevin Wolf         goto fail;
1660756e6736SKevin Wolf     }
1661756e6736SKevin Wolf 
1662756e6736SKevin Wolf     ret = 0;
1663756e6736SKevin Wolf fail:
1664e24e49e6SKevin Wolf     qemu_vfree(header);
1665756e6736SKevin Wolf     return ret;
1666756e6736SKevin Wolf }
1667756e6736SKevin Wolf 
1668756e6736SKevin Wolf static int qcow2_change_backing_file(BlockDriverState *bs,
1669756e6736SKevin Wolf     const char *backing_file, const char *backing_fmt)
1670756e6736SKevin Wolf {
1671e24e49e6SKevin Wolf     pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
1672e24e49e6SKevin Wolf     pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
1673e24e49e6SKevin Wolf 
1674e24e49e6SKevin Wolf     return qcow2_update_header(bs);
1675756e6736SKevin Wolf }
1676756e6736SKevin Wolf 
1677a35e1c17SKevin Wolf static int preallocate(BlockDriverState *bs)
1678a35e1c17SKevin Wolf {
1679a35e1c17SKevin Wolf     uint64_t nb_sectors;
1680a35e1c17SKevin Wolf     uint64_t offset;
1681060bee89SKevin Wolf     uint64_t host_offset = 0;
1682a35e1c17SKevin Wolf     int num;
1683148da7eaSKevin Wolf     int ret;
1684f50f88b9SKevin Wolf     QCowL2Meta *meta;
1685a35e1c17SKevin Wolf 
168657322b78SMarkus Armbruster     nb_sectors = bdrv_nb_sectors(bs);
1687a35e1c17SKevin Wolf     offset = 0;
1688a35e1c17SKevin Wolf 
1689a35e1c17SKevin Wolf     while (nb_sectors) {
16907c2bbf4aSHu Tao         num = MIN(nb_sectors, INT_MAX >> BDRV_SECTOR_BITS);
169116f0587eSHu Tao         ret = qcow2_alloc_cluster_offset(bs, offset, &num,
1692060bee89SKevin Wolf                                          &host_offset, &meta);
1693148da7eaSKevin Wolf         if (ret < 0) {
169419dbcbf7SKevin Wolf             return ret;
1695a35e1c17SKevin Wolf         }
1696a35e1c17SKevin Wolf 
1697c792707fSStefan Hajnoczi         while (meta) {
1698c792707fSStefan Hajnoczi             QCowL2Meta *next = meta->next;
1699c792707fSStefan Hajnoczi 
1700f50f88b9SKevin Wolf             ret = qcow2_alloc_cluster_link_l2(bs, meta);
170119dbcbf7SKevin Wolf             if (ret < 0) {
17027c2bbf4aSHu Tao                 qcow2_free_any_clusters(bs, meta->alloc_offset,
17037c2bbf4aSHu Tao                                         meta->nb_clusters, QCOW2_DISCARD_NEVER);
170419dbcbf7SKevin Wolf                 return ret;
1705a35e1c17SKevin Wolf             }
1706a35e1c17SKevin Wolf 
17077c2bbf4aSHu Tao             /* There are no dependent requests, but we need to remove our
17087c2bbf4aSHu Tao              * request from the list of in-flight requests */
17094e95314eSKevin Wolf             QLIST_REMOVE(meta, next_in_flight);
1710c792707fSStefan Hajnoczi 
1711c792707fSStefan Hajnoczi             g_free(meta);
1712c792707fSStefan Hajnoczi             meta = next;
1713f50f88b9SKevin Wolf         }
1714f214978aSKevin Wolf 
1715a35e1c17SKevin Wolf         /* TODO Preallocate data if requested */
1716a35e1c17SKevin Wolf 
1717a35e1c17SKevin Wolf         nb_sectors -= num;
17187c2bbf4aSHu Tao         offset += num << BDRV_SECTOR_BITS;
1719a35e1c17SKevin Wolf     }
1720a35e1c17SKevin Wolf 
1721a35e1c17SKevin Wolf     /*
1722a35e1c17SKevin Wolf      * It is expected that the image file is large enough to actually contain
1723a35e1c17SKevin Wolf      * all of the allocated clusters (otherwise we get failing reads after
1724a35e1c17SKevin Wolf      * EOF). Extend the image to the last allocated sector.
1725a35e1c17SKevin Wolf      */
1726060bee89SKevin Wolf     if (host_offset != 0) {
17277c2bbf4aSHu Tao         uint8_t buf[BDRV_SECTOR_SIZE];
17287c2bbf4aSHu Tao         memset(buf, 0, BDRV_SECTOR_SIZE);
17297c2bbf4aSHu Tao         ret = bdrv_write(bs->file, (host_offset >> BDRV_SECTOR_BITS) + num - 1,
17307c2bbf4aSHu Tao                          buf, 1);
173119dbcbf7SKevin Wolf         if (ret < 0) {
173219dbcbf7SKevin Wolf             return ret;
173319dbcbf7SKevin Wolf         }
1734a35e1c17SKevin Wolf     }
1735a35e1c17SKevin Wolf 
1736a35e1c17SKevin Wolf     return 0;
1737a35e1c17SKevin Wolf }
1738a35e1c17SKevin Wolf 
17397c80ab3fSJes Sorensen static int qcow2_create2(const char *filename, int64_t total_size,
1740a9420734SKevin Wolf                          const char *backing_file, const char *backing_format,
1741a9420734SKevin Wolf                          int flags, size_t cluster_size, int prealloc,
17421bd0e2d1SChunyan Liu                          QemuOpts *opts, int version,
17433ef6c40aSMax Reitz                          Error **errp)
1744a9420734SKevin Wolf {
17459b2260cbSDong Xu Wang     /* Calculate cluster_bits */
1746a9420734SKevin Wolf     int cluster_bits;
1747a9420734SKevin Wolf     cluster_bits = ffs(cluster_size) - 1;
1748a9420734SKevin Wolf     if (cluster_bits < MIN_CLUSTER_BITS || cluster_bits > MAX_CLUSTER_BITS ||
1749a9420734SKevin Wolf         (1 << cluster_bits) != cluster_size)
1750a9420734SKevin Wolf     {
17513ef6c40aSMax Reitz         error_setg(errp, "Cluster size must be a power of two between %d and "
17523ef6c40aSMax Reitz                    "%dk", 1 << MIN_CLUSTER_BITS, 1 << (MAX_CLUSTER_BITS - 10));
1753a9420734SKevin Wolf         return -EINVAL;
1754a9420734SKevin Wolf     }
1755a9420734SKevin Wolf 
1756a9420734SKevin Wolf     /*
1757a9420734SKevin Wolf      * Open the image file and write a minimal qcow2 header.
1758a9420734SKevin Wolf      *
1759a9420734SKevin Wolf      * We keep things simple and start with a zero-sized image. We also
1760a9420734SKevin Wolf      * do without refcount blocks or a L1 table for now. We'll fix the
1761a9420734SKevin Wolf      * inconsistency later.
1762a9420734SKevin Wolf      *
1763a9420734SKevin Wolf      * We do need a refcount table because growing the refcount table means
1764a9420734SKevin Wolf      * allocating two new refcount blocks - the seconds of which would be at
1765a9420734SKevin Wolf      * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
1766a9420734SKevin Wolf      * size for any qcow2 image.
1767a9420734SKevin Wolf      */
1768a9420734SKevin Wolf     BlockDriverState* bs;
1769f8413b3cSKevin Wolf     QCowHeader *header;
1770b106ad91SKevin Wolf     uint64_t* refcount_table;
17713ef6c40aSMax Reitz     Error *local_err = NULL;
1772a9420734SKevin Wolf     int ret;
1773a9420734SKevin Wolf 
1774c282e1fdSChunyan Liu     ret = bdrv_create_file(filename, opts, &local_err);
1775a9420734SKevin Wolf     if (ret < 0) {
17763ef6c40aSMax Reitz         error_propagate(errp, local_err);
1777a9420734SKevin Wolf         return ret;
1778a9420734SKevin Wolf     }
1779a9420734SKevin Wolf 
17802e40134bSMax Reitz     bs = NULL;
17812e40134bSMax Reitz     ret = bdrv_open(&bs, filename, NULL, NULL, BDRV_O_RDWR | BDRV_O_PROTOCOL,
17822e40134bSMax Reitz                     NULL, &local_err);
1783a9420734SKevin Wolf     if (ret < 0) {
17843ef6c40aSMax Reitz         error_propagate(errp, local_err);
1785a9420734SKevin Wolf         return ret;
1786a9420734SKevin Wolf     }
1787a9420734SKevin Wolf 
1788a9420734SKevin Wolf     /* Write the header */
1789f8413b3cSKevin Wolf     QEMU_BUILD_BUG_ON((1 << MIN_CLUSTER_BITS) < sizeof(*header));
1790f8413b3cSKevin Wolf     header = g_malloc0(cluster_size);
1791f8413b3cSKevin Wolf     *header = (QCowHeader) {
1792f8413b3cSKevin Wolf         .magic                      = cpu_to_be32(QCOW_MAGIC),
1793f8413b3cSKevin Wolf         .version                    = cpu_to_be32(version),
1794f8413b3cSKevin Wolf         .cluster_bits               = cpu_to_be32(cluster_bits),
1795f8413b3cSKevin Wolf         .size                       = cpu_to_be64(0),
1796f8413b3cSKevin Wolf         .l1_table_offset            = cpu_to_be64(0),
1797f8413b3cSKevin Wolf         .l1_size                    = cpu_to_be32(0),
1798f8413b3cSKevin Wolf         .refcount_table_offset      = cpu_to_be64(cluster_size),
1799f8413b3cSKevin Wolf         .refcount_table_clusters    = cpu_to_be32(1),
1800f8413b3cSKevin Wolf         .refcount_order             = cpu_to_be32(3 + REFCOUNT_SHIFT),
1801f8413b3cSKevin Wolf         .header_length              = cpu_to_be32(sizeof(*header)),
1802f8413b3cSKevin Wolf     };
1803a9420734SKevin Wolf 
1804a9420734SKevin Wolf     if (flags & BLOCK_FLAG_ENCRYPT) {
1805f8413b3cSKevin Wolf         header->crypt_method = cpu_to_be32(QCOW_CRYPT_AES);
1806a9420734SKevin Wolf     } else {
1807f8413b3cSKevin Wolf         header->crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
1808a9420734SKevin Wolf     }
1809a9420734SKevin Wolf 
1810bfe8043eSStefan Hajnoczi     if (flags & BLOCK_FLAG_LAZY_REFCOUNTS) {
1811f8413b3cSKevin Wolf         header->compatible_features |=
1812bfe8043eSStefan Hajnoczi             cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS);
1813bfe8043eSStefan Hajnoczi     }
1814bfe8043eSStefan Hajnoczi 
1815f8413b3cSKevin Wolf     ret = bdrv_pwrite(bs, 0, header, cluster_size);
1816f8413b3cSKevin Wolf     g_free(header);
1817a9420734SKevin Wolf     if (ret < 0) {
18183ef6c40aSMax Reitz         error_setg_errno(errp, -ret, "Could not write qcow2 header");
1819a9420734SKevin Wolf         goto out;
1820a9420734SKevin Wolf     }
1821a9420734SKevin Wolf 
1822b106ad91SKevin Wolf     /* Write a refcount table with one refcount block */
1823b106ad91SKevin Wolf     refcount_table = g_malloc0(2 * cluster_size);
1824b106ad91SKevin Wolf     refcount_table[0] = cpu_to_be64(2 * cluster_size);
1825b106ad91SKevin Wolf     ret = bdrv_pwrite(bs, cluster_size, refcount_table, 2 * cluster_size);
18267267c094SAnthony Liguori     g_free(refcount_table);
1827a9420734SKevin Wolf 
1828a9420734SKevin Wolf     if (ret < 0) {
18293ef6c40aSMax Reitz         error_setg_errno(errp, -ret, "Could not write refcount table");
1830a9420734SKevin Wolf         goto out;
1831a9420734SKevin Wolf     }
1832a9420734SKevin Wolf 
1833f67503e5SMax Reitz     bdrv_unref(bs);
1834f67503e5SMax Reitz     bs = NULL;
1835a9420734SKevin Wolf 
1836a9420734SKevin Wolf     /*
1837a9420734SKevin Wolf      * And now open the image and make it consistent first (i.e. increase the
1838a9420734SKevin Wolf      * refcount of the cluster that is occupied by the header and the refcount
1839a9420734SKevin Wolf      * table)
1840a9420734SKevin Wolf      */
1841a9420734SKevin Wolf     BlockDriver* drv = bdrv_find_format("qcow2");
1842a9420734SKevin Wolf     assert(drv != NULL);
1843ddf5636dSMax Reitz     ret = bdrv_open(&bs, filename, NULL, NULL,
18443ef6c40aSMax Reitz         BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_NO_FLUSH, drv, &local_err);
1845a9420734SKevin Wolf     if (ret < 0) {
18463ef6c40aSMax Reitz         error_propagate(errp, local_err);
1847a9420734SKevin Wolf         goto out;
1848a9420734SKevin Wolf     }
1849a9420734SKevin Wolf 
1850b106ad91SKevin Wolf     ret = qcow2_alloc_clusters(bs, 3 * cluster_size);
1851a9420734SKevin Wolf     if (ret < 0) {
18523ef6c40aSMax Reitz         error_setg_errno(errp, -ret, "Could not allocate clusters for qcow2 "
18533ef6c40aSMax Reitz                          "header and refcount table");
1854a9420734SKevin Wolf         goto out;
1855a9420734SKevin Wolf 
1856a9420734SKevin Wolf     } else if (ret != 0) {
1857a9420734SKevin Wolf         error_report("Huh, first cluster in empty image is already in use?");
1858a9420734SKevin Wolf         abort();
1859a9420734SKevin Wolf     }
1860a9420734SKevin Wolf 
1861a9420734SKevin Wolf     /* Okay, now that we have a valid image, let's give it the right size */
1862*180e9526SHu Tao     ret = bdrv_truncate(bs, total_size);
1863a9420734SKevin Wolf     if (ret < 0) {
18643ef6c40aSMax Reitz         error_setg_errno(errp, -ret, "Could not resize image");
1865a9420734SKevin Wolf         goto out;
1866a9420734SKevin Wolf     }
1867a9420734SKevin Wolf 
1868a9420734SKevin Wolf     /* Want a backing file? There you go.*/
1869a9420734SKevin Wolf     if (backing_file) {
1870a9420734SKevin Wolf         ret = bdrv_change_backing_file(bs, backing_file, backing_format);
1871a9420734SKevin Wolf         if (ret < 0) {
18723ef6c40aSMax Reitz             error_setg_errno(errp, -ret, "Could not assign backing file '%s' "
18733ef6c40aSMax Reitz                              "with format '%s'", backing_file, backing_format);
1874a9420734SKevin Wolf             goto out;
1875a9420734SKevin Wolf         }
1876a9420734SKevin Wolf     }
1877a9420734SKevin Wolf 
1878a9420734SKevin Wolf     /* And if we're supposed to preallocate metadata, do that now */
1879a9420734SKevin Wolf     if (prealloc) {
188015552c4aSZhi Yong Wu         BDRVQcowState *s = bs->opaque;
188115552c4aSZhi Yong Wu         qemu_co_mutex_lock(&s->lock);
1882a9420734SKevin Wolf         ret = preallocate(bs);
188315552c4aSZhi Yong Wu         qemu_co_mutex_unlock(&s->lock);
1884a9420734SKevin Wolf         if (ret < 0) {
18853ef6c40aSMax Reitz             error_setg_errno(errp, -ret, "Could not preallocate metadata");
1886a9420734SKevin Wolf             goto out;
1887a9420734SKevin Wolf         }
1888a9420734SKevin Wolf     }
1889a9420734SKevin Wolf 
1890f67503e5SMax Reitz     bdrv_unref(bs);
1891f67503e5SMax Reitz     bs = NULL;
1892ba2ab2f2SMax Reitz 
1893ba2ab2f2SMax Reitz     /* Reopen the image without BDRV_O_NO_FLUSH to flush it before returning */
1894ddf5636dSMax Reitz     ret = bdrv_open(&bs, filename, NULL, NULL,
1895c9fbb99dSKevin Wolf                     BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_NO_BACKING,
1896c9fbb99dSKevin Wolf                     drv, &local_err);
189784d18f06SMarkus Armbruster     if (local_err) {
1898ba2ab2f2SMax Reitz         error_propagate(errp, local_err);
1899ba2ab2f2SMax Reitz         goto out;
1900ba2ab2f2SMax Reitz     }
1901ba2ab2f2SMax Reitz 
1902a9420734SKevin Wolf     ret = 0;
1903a9420734SKevin Wolf out:
1904f67503e5SMax Reitz     if (bs) {
19054f6fd349SFam Zheng         bdrv_unref(bs);
1906f67503e5SMax Reitz     }
1907a9420734SKevin Wolf     return ret;
1908a9420734SKevin Wolf }
1909de5f3f40SKevin Wolf 
19101bd0e2d1SChunyan Liu static int qcow2_create(const char *filename, QemuOpts *opts, Error **errp)
1911de5f3f40SKevin Wolf {
19121bd0e2d1SChunyan Liu     char *backing_file = NULL;
19131bd0e2d1SChunyan Liu     char *backing_fmt = NULL;
19141bd0e2d1SChunyan Liu     char *buf = NULL;
1915*180e9526SHu Tao     uint64_t size = 0;
1916de5f3f40SKevin Wolf     int flags = 0;
191799cce9faSKevin Wolf     size_t cluster_size = DEFAULT_CLUSTER_SIZE;
1918de5f3f40SKevin Wolf     int prealloc = 0;
19198ad1898cSKevin Wolf     int version = 3;
19203ef6c40aSMax Reitz     Error *local_err = NULL;
19213ef6c40aSMax Reitz     int ret;
1922de5f3f40SKevin Wolf 
1923de5f3f40SKevin Wolf     /* Read out options */
1924*180e9526SHu Tao     size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
1925c2eb918eSHu Tao                     BDRV_SECTOR_SIZE);
19261bd0e2d1SChunyan Liu     backing_file = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
19271bd0e2d1SChunyan Liu     backing_fmt = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FMT);
19281bd0e2d1SChunyan Liu     if (qemu_opt_get_bool_del(opts, BLOCK_OPT_ENCRYPT, false)) {
19291bd0e2d1SChunyan Liu         flags |= BLOCK_FLAG_ENCRYPT;
1930de5f3f40SKevin Wolf     }
19311bd0e2d1SChunyan Liu     cluster_size = qemu_opt_get_size_del(opts, BLOCK_OPT_CLUSTER_SIZE,
19321bd0e2d1SChunyan Liu                                          DEFAULT_CLUSTER_SIZE);
19331bd0e2d1SChunyan Liu     buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
19341bd0e2d1SChunyan Liu     if (!buf || !strcmp(buf, "off")) {
1935de5f3f40SKevin Wolf         prealloc = 0;
19361bd0e2d1SChunyan Liu     } else if (!strcmp(buf, "metadata")) {
1937de5f3f40SKevin Wolf         prealloc = 1;
1938de5f3f40SKevin Wolf     } else {
19391bd0e2d1SChunyan Liu         error_setg(errp, "Invalid preallocation mode: '%s'", buf);
19401bd0e2d1SChunyan Liu         ret = -EINVAL;
19411bd0e2d1SChunyan Liu         goto finish;
1942de5f3f40SKevin Wolf     }
19431bd0e2d1SChunyan Liu     g_free(buf);
19441bd0e2d1SChunyan Liu     buf = qemu_opt_get_del(opts, BLOCK_OPT_COMPAT_LEVEL);
19451bd0e2d1SChunyan Liu     if (!buf) {
19469117b477SKevin Wolf         /* keep the default */
19471bd0e2d1SChunyan Liu     } else if (!strcmp(buf, "0.10")) {
19486744cbabSKevin Wolf         version = 2;
19491bd0e2d1SChunyan Liu     } else if (!strcmp(buf, "1.1")) {
19506744cbabSKevin Wolf         version = 3;
19516744cbabSKevin Wolf     } else {
19521bd0e2d1SChunyan Liu         error_setg(errp, "Invalid compatibility level: '%s'", buf);
19531bd0e2d1SChunyan Liu         ret = -EINVAL;
19541bd0e2d1SChunyan Liu         goto finish;
19556744cbabSKevin Wolf     }
19561bd0e2d1SChunyan Liu 
19571bd0e2d1SChunyan Liu     if (qemu_opt_get_bool_del(opts, BLOCK_OPT_LAZY_REFCOUNTS, false)) {
19581bd0e2d1SChunyan Liu         flags |= BLOCK_FLAG_LAZY_REFCOUNTS;
1959de5f3f40SKevin Wolf     }
1960de5f3f40SKevin Wolf 
1961de5f3f40SKevin Wolf     if (backing_file && prealloc) {
19623ef6c40aSMax Reitz         error_setg(errp, "Backing file and preallocation cannot be used at "
19633ef6c40aSMax Reitz                    "the same time");
19641bd0e2d1SChunyan Liu         ret = -EINVAL;
19651bd0e2d1SChunyan Liu         goto finish;
1966de5f3f40SKevin Wolf     }
1967de5f3f40SKevin Wolf 
1968bfe8043eSStefan Hajnoczi     if (version < 3 && (flags & BLOCK_FLAG_LAZY_REFCOUNTS)) {
19693ef6c40aSMax Reitz         error_setg(errp, "Lazy refcounts only supported with compatibility "
19703ef6c40aSMax Reitz                    "level 1.1 and above (use compat=1.1 or greater)");
19711bd0e2d1SChunyan Liu         ret = -EINVAL;
19721bd0e2d1SChunyan Liu         goto finish;
1973bfe8043eSStefan Hajnoczi     }
1974bfe8043eSStefan Hajnoczi 
1975*180e9526SHu Tao     ret = qcow2_create2(filename, size, backing_file, backing_fmt, flags,
19761bd0e2d1SChunyan Liu                         cluster_size, prealloc, opts, version, &local_err);
197784d18f06SMarkus Armbruster     if (local_err) {
19783ef6c40aSMax Reitz         error_propagate(errp, local_err);
19793ef6c40aSMax Reitz     }
19801bd0e2d1SChunyan Liu 
19811bd0e2d1SChunyan Liu finish:
19821bd0e2d1SChunyan Liu     g_free(backing_file);
19831bd0e2d1SChunyan Liu     g_free(backing_fmt);
19841bd0e2d1SChunyan Liu     g_free(buf);
19853ef6c40aSMax Reitz     return ret;
1986de5f3f40SKevin Wolf }
1987de5f3f40SKevin Wolf 
1988621f0589SKevin Wolf static coroutine_fn int qcow2_co_write_zeroes(BlockDriverState *bs,
1989aa7bfbffSPeter Lieven     int64_t sector_num, int nb_sectors, BdrvRequestFlags flags)
1990621f0589SKevin Wolf {
1991621f0589SKevin Wolf     int ret;
1992621f0589SKevin Wolf     BDRVQcowState *s = bs->opaque;
1993621f0589SKevin Wolf 
1994621f0589SKevin Wolf     /* Emulate misaligned zero writes */
1995621f0589SKevin Wolf     if (sector_num % s->cluster_sectors || nb_sectors % s->cluster_sectors) {
1996621f0589SKevin Wolf         return -ENOTSUP;
1997621f0589SKevin Wolf     }
1998621f0589SKevin Wolf 
1999621f0589SKevin Wolf     /* Whatever is left can use real zero clusters */
2000621f0589SKevin Wolf     qemu_co_mutex_lock(&s->lock);
2001621f0589SKevin Wolf     ret = qcow2_zero_clusters(bs, sector_num << BDRV_SECTOR_BITS,
2002621f0589SKevin Wolf         nb_sectors);
2003621f0589SKevin Wolf     qemu_co_mutex_unlock(&s->lock);
2004621f0589SKevin Wolf 
2005621f0589SKevin Wolf     return ret;
2006621f0589SKevin Wolf }
2007621f0589SKevin Wolf 
20086db39ae2SPaolo Bonzini static coroutine_fn int qcow2_co_discard(BlockDriverState *bs,
20096db39ae2SPaolo Bonzini     int64_t sector_num, int nb_sectors)
20105ea929e3SKevin Wolf {
20116db39ae2SPaolo Bonzini     int ret;
20126db39ae2SPaolo Bonzini     BDRVQcowState *s = bs->opaque;
20136db39ae2SPaolo Bonzini 
20146db39ae2SPaolo Bonzini     qemu_co_mutex_lock(&s->lock);
20156db39ae2SPaolo Bonzini     ret = qcow2_discard_clusters(bs, sector_num << BDRV_SECTOR_BITS,
2016670df5e3SKevin Wolf         nb_sectors, QCOW2_DISCARD_REQUEST);
20176db39ae2SPaolo Bonzini     qemu_co_mutex_unlock(&s->lock);
20186db39ae2SPaolo Bonzini     return ret;
20195ea929e3SKevin Wolf }
20205ea929e3SKevin Wolf 
2021419b19d9SStefan Hajnoczi static int qcow2_truncate(BlockDriverState *bs, int64_t offset)
2022419b19d9SStefan Hajnoczi {
2023419b19d9SStefan Hajnoczi     BDRVQcowState *s = bs->opaque;
20242cf7cfa1SKevin Wolf     int64_t new_l1_size;
20252cf7cfa1SKevin Wolf     int ret;
2026419b19d9SStefan Hajnoczi 
2027419b19d9SStefan Hajnoczi     if (offset & 511) {
2028259b2173SKevin Wolf         error_report("The new size must be a multiple of 512");
2029419b19d9SStefan Hajnoczi         return -EINVAL;
2030419b19d9SStefan Hajnoczi     }
2031419b19d9SStefan Hajnoczi 
2032419b19d9SStefan Hajnoczi     /* cannot proceed if image has snapshots */
2033419b19d9SStefan Hajnoczi     if (s->nb_snapshots) {
2034259b2173SKevin Wolf         error_report("Can't resize an image which has snapshots");
2035419b19d9SStefan Hajnoczi         return -ENOTSUP;
2036419b19d9SStefan Hajnoczi     }
2037419b19d9SStefan Hajnoczi 
2038419b19d9SStefan Hajnoczi     /* shrinking is currently not supported */
2039419b19d9SStefan Hajnoczi     if (offset < bs->total_sectors * 512) {
2040259b2173SKevin Wolf         error_report("qcow2 doesn't support shrinking images yet");
2041419b19d9SStefan Hajnoczi         return -ENOTSUP;
2042419b19d9SStefan Hajnoczi     }
2043419b19d9SStefan Hajnoczi 
2044419b19d9SStefan Hajnoczi     new_l1_size = size_to_l1(s, offset);
204572893756SStefan Hajnoczi     ret = qcow2_grow_l1_table(bs, new_l1_size, true);
2046419b19d9SStefan Hajnoczi     if (ret < 0) {
2047419b19d9SStefan Hajnoczi         return ret;
2048419b19d9SStefan Hajnoczi     }
2049419b19d9SStefan Hajnoczi 
2050419b19d9SStefan Hajnoczi     /* write updated header.size */
2051419b19d9SStefan Hajnoczi     offset = cpu_to_be64(offset);
20528b3b7206SKevin Wolf     ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, size),
2053419b19d9SStefan Hajnoczi                            &offset, sizeof(uint64_t));
2054419b19d9SStefan Hajnoczi     if (ret < 0) {
2055419b19d9SStefan Hajnoczi         return ret;
2056419b19d9SStefan Hajnoczi     }
2057419b19d9SStefan Hajnoczi 
2058419b19d9SStefan Hajnoczi     s->l1_vm_state_index = new_l1_size;
2059419b19d9SStefan Hajnoczi     return 0;
2060419b19d9SStefan Hajnoczi }
2061419b19d9SStefan Hajnoczi 
206220d97356SBlue Swirl /* XXX: put compressed sectors first, then all the cluster aligned
206320d97356SBlue Swirl    tables to avoid losing bytes in alignment */
20647c80ab3fSJes Sorensen static int qcow2_write_compressed(BlockDriverState *bs, int64_t sector_num,
206520d97356SBlue Swirl                                   const uint8_t *buf, int nb_sectors)
206620d97356SBlue Swirl {
206720d97356SBlue Swirl     BDRVQcowState *s = bs->opaque;
206820d97356SBlue Swirl     z_stream strm;
206920d97356SBlue Swirl     int ret, out_len;
207020d97356SBlue Swirl     uint8_t *out_buf;
207120d97356SBlue Swirl     uint64_t cluster_offset;
207220d97356SBlue Swirl 
207320d97356SBlue Swirl     if (nb_sectors == 0) {
207420d97356SBlue Swirl         /* align end of file to a sector boundary to ease reading with
207520d97356SBlue Swirl            sector based I/Os */
207666f82ceeSKevin Wolf         cluster_offset = bdrv_getlength(bs->file);
207766f82ceeSKevin Wolf         bdrv_truncate(bs->file, cluster_offset);
207820d97356SBlue Swirl         return 0;
207920d97356SBlue Swirl     }
208020d97356SBlue Swirl 
2081f4d38befSStefan Hajnoczi     if (nb_sectors != s->cluster_sectors) {
2082f4d38befSStefan Hajnoczi         ret = -EINVAL;
2083f4d38befSStefan Hajnoczi 
2084f4d38befSStefan Hajnoczi         /* Zero-pad last write if image size is not cluster aligned */
2085f4d38befSStefan Hajnoczi         if (sector_num + nb_sectors == bs->total_sectors &&
2086f4d38befSStefan Hajnoczi             nb_sectors < s->cluster_sectors) {
2087f4d38befSStefan Hajnoczi             uint8_t *pad_buf = qemu_blockalign(bs, s->cluster_size);
2088f4d38befSStefan Hajnoczi             memset(pad_buf, 0, s->cluster_size);
2089f4d38befSStefan Hajnoczi             memcpy(pad_buf, buf, nb_sectors * BDRV_SECTOR_SIZE);
2090f4d38befSStefan Hajnoczi             ret = qcow2_write_compressed(bs, sector_num,
2091f4d38befSStefan Hajnoczi                                          pad_buf, s->cluster_sectors);
2092f4d38befSStefan Hajnoczi             qemu_vfree(pad_buf);
2093f4d38befSStefan Hajnoczi         }
2094f4d38befSStefan Hajnoczi         return ret;
2095f4d38befSStefan Hajnoczi     }
209620d97356SBlue Swirl 
20977267c094SAnthony Liguori     out_buf = g_malloc(s->cluster_size + (s->cluster_size / 1000) + 128);
209820d97356SBlue Swirl 
209920d97356SBlue Swirl     /* best compression, small window, no zlib header */
210020d97356SBlue Swirl     memset(&strm, 0, sizeof(strm));
210120d97356SBlue Swirl     ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
210220d97356SBlue Swirl                        Z_DEFLATED, -12,
210320d97356SBlue Swirl                        9, Z_DEFAULT_STRATEGY);
210420d97356SBlue Swirl     if (ret != 0) {
21058f1efd00SKevin Wolf         ret = -EINVAL;
21068f1efd00SKevin Wolf         goto fail;
210720d97356SBlue Swirl     }
210820d97356SBlue Swirl 
210920d97356SBlue Swirl     strm.avail_in = s->cluster_size;
211020d97356SBlue Swirl     strm.next_in = (uint8_t *)buf;
211120d97356SBlue Swirl     strm.avail_out = s->cluster_size;
211220d97356SBlue Swirl     strm.next_out = out_buf;
211320d97356SBlue Swirl 
211420d97356SBlue Swirl     ret = deflate(&strm, Z_FINISH);
211520d97356SBlue Swirl     if (ret != Z_STREAM_END && ret != Z_OK) {
211620d97356SBlue Swirl         deflateEnd(&strm);
21178f1efd00SKevin Wolf         ret = -EINVAL;
21188f1efd00SKevin Wolf         goto fail;
211920d97356SBlue Swirl     }
212020d97356SBlue Swirl     out_len = strm.next_out - out_buf;
212120d97356SBlue Swirl 
212220d97356SBlue Swirl     deflateEnd(&strm);
212320d97356SBlue Swirl 
212420d97356SBlue Swirl     if (ret != Z_STREAM_END || out_len >= s->cluster_size) {
212520d97356SBlue Swirl         /* could not compress: write normal cluster */
21268f1efd00SKevin Wolf         ret = bdrv_write(bs, sector_num, buf, s->cluster_sectors);
21278f1efd00SKevin Wolf         if (ret < 0) {
21288f1efd00SKevin Wolf             goto fail;
21298f1efd00SKevin Wolf         }
213020d97356SBlue Swirl     } else {
213120d97356SBlue Swirl         cluster_offset = qcow2_alloc_compressed_cluster_offset(bs,
213220d97356SBlue Swirl             sector_num << 9, out_len);
21338f1efd00SKevin Wolf         if (!cluster_offset) {
21348f1efd00SKevin Wolf             ret = -EIO;
21358f1efd00SKevin Wolf             goto fail;
21368f1efd00SKevin Wolf         }
213720d97356SBlue Swirl         cluster_offset &= s->cluster_offset_mask;
2138cf93980eSMax Reitz 
2139231bb267SMax Reitz         ret = qcow2_pre_write_overlap_check(bs, 0, cluster_offset, out_len);
2140cf93980eSMax Reitz         if (ret < 0) {
2141cf93980eSMax Reitz             goto fail;
2142cf93980eSMax Reitz         }
2143cf93980eSMax Reitz 
214466f82ceeSKevin Wolf         BLKDBG_EVENT(bs->file, BLKDBG_WRITE_COMPRESSED);
21458f1efd00SKevin Wolf         ret = bdrv_pwrite(bs->file, cluster_offset, out_buf, out_len);
21468f1efd00SKevin Wolf         if (ret < 0) {
21478f1efd00SKevin Wolf             goto fail;
214820d97356SBlue Swirl         }
214920d97356SBlue Swirl     }
215020d97356SBlue Swirl 
21518f1efd00SKevin Wolf     ret = 0;
21528f1efd00SKevin Wolf fail:
21537267c094SAnthony Liguori     g_free(out_buf);
21548f1efd00SKevin Wolf     return ret;
215520d97356SBlue Swirl }
215620d97356SBlue Swirl 
2157a968168cSDong Xu Wang static coroutine_fn int qcow2_co_flush_to_os(BlockDriverState *bs)
215820d97356SBlue Swirl {
215929c1a730SKevin Wolf     BDRVQcowState *s = bs->opaque;
216029c1a730SKevin Wolf     int ret;
216129c1a730SKevin Wolf 
21628b94ff85SPaolo Bonzini     qemu_co_mutex_lock(&s->lock);
216329c1a730SKevin Wolf     ret = qcow2_cache_flush(bs, s->l2_table_cache);
216429c1a730SKevin Wolf     if (ret < 0) {
2165c95de7e2SDong Xu Wang         qemu_co_mutex_unlock(&s->lock);
21668b94ff85SPaolo Bonzini         return ret;
216729c1a730SKevin Wolf     }
216829c1a730SKevin Wolf 
2169bfe8043eSStefan Hajnoczi     if (qcow2_need_accurate_refcounts(s)) {
217029c1a730SKevin Wolf         ret = qcow2_cache_flush(bs, s->refcount_block_cache);
217129c1a730SKevin Wolf         if (ret < 0) {
2172c95de7e2SDong Xu Wang             qemu_co_mutex_unlock(&s->lock);
21738b94ff85SPaolo Bonzini             return ret;
217429c1a730SKevin Wolf         }
2175bfe8043eSStefan Hajnoczi     }
21768b94ff85SPaolo Bonzini     qemu_co_mutex_unlock(&s->lock);
217729c1a730SKevin Wolf 
2178eb489bb1SKevin Wolf     return 0;
2179eb489bb1SKevin Wolf }
2180eb489bb1SKevin Wolf 
21817c80ab3fSJes Sorensen static int qcow2_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
218220d97356SBlue Swirl {
218320d97356SBlue Swirl     BDRVQcowState *s = bs->opaque;
218495de6d70SPaolo Bonzini     bdi->unallocated_blocks_are_zero = true;
218595de6d70SPaolo Bonzini     bdi->can_write_zeroes_with_unmap = (s->qcow_version >= 3);
218620d97356SBlue Swirl     bdi->cluster_size = s->cluster_size;
21877c80ab3fSJes Sorensen     bdi->vm_state_offset = qcow2_vm_state_offset(s);
218820d97356SBlue Swirl     return 0;
218920d97356SBlue Swirl }
219020d97356SBlue Swirl 
219137764dfbSMax Reitz static ImageInfoSpecific *qcow2_get_specific_info(BlockDriverState *bs)
219237764dfbSMax Reitz {
219337764dfbSMax Reitz     BDRVQcowState *s = bs->opaque;
219437764dfbSMax Reitz     ImageInfoSpecific *spec_info = g_new(ImageInfoSpecific, 1);
219537764dfbSMax Reitz 
219637764dfbSMax Reitz     *spec_info = (ImageInfoSpecific){
219737764dfbSMax Reitz         .kind  = IMAGE_INFO_SPECIFIC_KIND_QCOW2,
219837764dfbSMax Reitz         {
219937764dfbSMax Reitz             .qcow2 = g_new(ImageInfoSpecificQCow2, 1),
220037764dfbSMax Reitz         },
220137764dfbSMax Reitz     };
220237764dfbSMax Reitz     if (s->qcow_version == 2) {
220337764dfbSMax Reitz         *spec_info->qcow2 = (ImageInfoSpecificQCow2){
220437764dfbSMax Reitz             .compat = g_strdup("0.10"),
220537764dfbSMax Reitz         };
220637764dfbSMax Reitz     } else if (s->qcow_version == 3) {
220737764dfbSMax Reitz         *spec_info->qcow2 = (ImageInfoSpecificQCow2){
220837764dfbSMax Reitz             .compat             = g_strdup("1.1"),
220937764dfbSMax Reitz             .lazy_refcounts     = s->compatible_features &
221037764dfbSMax Reitz                                   QCOW2_COMPAT_LAZY_REFCOUNTS,
221137764dfbSMax Reitz             .has_lazy_refcounts = true,
221237764dfbSMax Reitz         };
221337764dfbSMax Reitz     }
221437764dfbSMax Reitz 
221537764dfbSMax Reitz     return spec_info;
221637764dfbSMax Reitz }
221737764dfbSMax Reitz 
221820d97356SBlue Swirl #if 0
221920d97356SBlue Swirl static void dump_refcounts(BlockDriverState *bs)
222020d97356SBlue Swirl {
222120d97356SBlue Swirl     BDRVQcowState *s = bs->opaque;
222220d97356SBlue Swirl     int64_t nb_clusters, k, k1, size;
222320d97356SBlue Swirl     int refcount;
222420d97356SBlue Swirl 
222566f82ceeSKevin Wolf     size = bdrv_getlength(bs->file);
222620d97356SBlue Swirl     nb_clusters = size_to_clusters(s, size);
222720d97356SBlue Swirl     for(k = 0; k < nb_clusters;) {
222820d97356SBlue Swirl         k1 = k;
222920d97356SBlue Swirl         refcount = get_refcount(bs, k);
223020d97356SBlue Swirl         k++;
223120d97356SBlue Swirl         while (k < nb_clusters && get_refcount(bs, k) == refcount)
223220d97356SBlue Swirl             k++;
22330bfcd599SBlue Swirl         printf("%" PRId64 ": refcount=%d nb=%" PRId64 "\n", k, refcount,
22340bfcd599SBlue Swirl                k - k1);
223520d97356SBlue Swirl     }
223620d97356SBlue Swirl }
223720d97356SBlue Swirl #endif
223820d97356SBlue Swirl 
2239cf8074b3SKevin Wolf static int qcow2_save_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
2240cf8074b3SKevin Wolf                               int64_t pos)
224120d97356SBlue Swirl {
224220d97356SBlue Swirl     BDRVQcowState *s = bs->opaque;
2243eedff66fSMax Reitz     int64_t total_sectors = bs->total_sectors;
224420d97356SBlue Swirl     int growable = bs->growable;
22456e13610aSMax Reitz     bool zero_beyond_eof = bs->zero_beyond_eof;
224620d97356SBlue Swirl     int ret;
224720d97356SBlue Swirl 
224866f82ceeSKevin Wolf     BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_SAVE);
224920d97356SBlue Swirl     bs->growable = 1;
22506e13610aSMax Reitz     bs->zero_beyond_eof = false;
22518d3b1a2dSKevin Wolf     ret = bdrv_pwritev(bs, qcow2_vm_state_offset(s) + pos, qiov);
225220d97356SBlue Swirl     bs->growable = growable;
22536e13610aSMax Reitz     bs->zero_beyond_eof = zero_beyond_eof;
225420d97356SBlue Swirl 
2255eedff66fSMax Reitz     /* bdrv_co_do_writev will have increased the total_sectors value to include
2256eedff66fSMax Reitz      * the VM state - the VM state is however not an actual part of the block
2257eedff66fSMax Reitz      * device, therefore, we need to restore the old value. */
2258eedff66fSMax Reitz     bs->total_sectors = total_sectors;
2259eedff66fSMax Reitz 
226020d97356SBlue Swirl     return ret;
226120d97356SBlue Swirl }
226220d97356SBlue Swirl 
22637c80ab3fSJes Sorensen static int qcow2_load_vmstate(BlockDriverState *bs, uint8_t *buf,
226420d97356SBlue Swirl                               int64_t pos, int size)
226520d97356SBlue Swirl {
226620d97356SBlue Swirl     BDRVQcowState *s = bs->opaque;
226720d97356SBlue Swirl     int growable = bs->growable;
22680d51b4deSAsias He     bool zero_beyond_eof = bs->zero_beyond_eof;
226920d97356SBlue Swirl     int ret;
227020d97356SBlue Swirl 
227166f82ceeSKevin Wolf     BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_LOAD);
227220d97356SBlue Swirl     bs->growable = 1;
22730d51b4deSAsias He     bs->zero_beyond_eof = false;
22747c80ab3fSJes Sorensen     ret = bdrv_pread(bs, qcow2_vm_state_offset(s) + pos, buf, size);
227520d97356SBlue Swirl     bs->growable = growable;
22760d51b4deSAsias He     bs->zero_beyond_eof = zero_beyond_eof;
227720d97356SBlue Swirl 
227820d97356SBlue Swirl     return ret;
227920d97356SBlue Swirl }
228020d97356SBlue Swirl 
22819296b3edSMax Reitz /*
22829296b3edSMax Reitz  * Downgrades an image's version. To achieve this, any incompatible features
22839296b3edSMax Reitz  * have to be removed.
22849296b3edSMax Reitz  */
22859296b3edSMax Reitz static int qcow2_downgrade(BlockDriverState *bs, int target_version)
22869296b3edSMax Reitz {
22879296b3edSMax Reitz     BDRVQcowState *s = bs->opaque;
22889296b3edSMax Reitz     int current_version = s->qcow_version;
22899296b3edSMax Reitz     int ret;
22909296b3edSMax Reitz 
22919296b3edSMax Reitz     if (target_version == current_version) {
22929296b3edSMax Reitz         return 0;
22939296b3edSMax Reitz     } else if (target_version > current_version) {
22949296b3edSMax Reitz         return -EINVAL;
22959296b3edSMax Reitz     } else if (target_version != 2) {
22969296b3edSMax Reitz         return -EINVAL;
22979296b3edSMax Reitz     }
22989296b3edSMax Reitz 
22999296b3edSMax Reitz     if (s->refcount_order != 4) {
23009296b3edSMax Reitz         /* we would have to convert the image to a refcount_order == 4 image
23019296b3edSMax Reitz          * here; however, since qemu (at the time of writing this) does not
23029296b3edSMax Reitz          * support anything different than 4 anyway, there is no point in doing
23039296b3edSMax Reitz          * so right now; however, we should error out (if qemu supports this in
23049296b3edSMax Reitz          * the future and this code has not been adapted) */
23059296b3edSMax Reitz         error_report("qcow2_downgrade: Image refcount orders other than 4 are "
23069296b3edSMax Reitz                      "currently not supported.");
23079296b3edSMax Reitz         return -ENOTSUP;
23089296b3edSMax Reitz     }
23099296b3edSMax Reitz 
23109296b3edSMax Reitz     /* clear incompatible features */
23119296b3edSMax Reitz     if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
23129296b3edSMax Reitz         ret = qcow2_mark_clean(bs);
23139296b3edSMax Reitz         if (ret < 0) {
23149296b3edSMax Reitz             return ret;
23159296b3edSMax Reitz         }
23169296b3edSMax Reitz     }
23179296b3edSMax Reitz 
23189296b3edSMax Reitz     /* with QCOW2_INCOMPAT_CORRUPT, it is pretty much impossible to get here in
23199296b3edSMax Reitz      * the first place; if that happens nonetheless, returning -ENOTSUP is the
23209296b3edSMax Reitz      * best thing to do anyway */
23219296b3edSMax Reitz 
23229296b3edSMax Reitz     if (s->incompatible_features) {
23239296b3edSMax Reitz         return -ENOTSUP;
23249296b3edSMax Reitz     }
23259296b3edSMax Reitz 
23269296b3edSMax Reitz     /* since we can ignore compatible features, we can set them to 0 as well */
23279296b3edSMax Reitz     s->compatible_features = 0;
23289296b3edSMax Reitz     /* if lazy refcounts have been used, they have already been fixed through
23299296b3edSMax Reitz      * clearing the dirty flag */
23309296b3edSMax Reitz 
23319296b3edSMax Reitz     /* clearing autoclear features is trivial */
23329296b3edSMax Reitz     s->autoclear_features = 0;
23339296b3edSMax Reitz 
23349296b3edSMax Reitz     ret = qcow2_expand_zero_clusters(bs);
23359296b3edSMax Reitz     if (ret < 0) {
23369296b3edSMax Reitz         return ret;
23379296b3edSMax Reitz     }
23389296b3edSMax Reitz 
23399296b3edSMax Reitz     s->qcow_version = target_version;
23409296b3edSMax Reitz     ret = qcow2_update_header(bs);
23419296b3edSMax Reitz     if (ret < 0) {
23429296b3edSMax Reitz         s->qcow_version = current_version;
23439296b3edSMax Reitz         return ret;
23449296b3edSMax Reitz     }
23459296b3edSMax Reitz     return 0;
23469296b3edSMax Reitz }
23479296b3edSMax Reitz 
23481bd0e2d1SChunyan Liu static int qcow2_amend_options(BlockDriverState *bs, QemuOpts *opts)
23499296b3edSMax Reitz {
23509296b3edSMax Reitz     BDRVQcowState *s = bs->opaque;
23519296b3edSMax Reitz     int old_version = s->qcow_version, new_version = old_version;
23529296b3edSMax Reitz     uint64_t new_size = 0;
23539296b3edSMax Reitz     const char *backing_file = NULL, *backing_format = NULL;
23549296b3edSMax Reitz     bool lazy_refcounts = s->use_lazy_refcounts;
23551bd0e2d1SChunyan Liu     const char *compat = NULL;
23561bd0e2d1SChunyan Liu     uint64_t cluster_size = s->cluster_size;
23571bd0e2d1SChunyan Liu     bool encrypt;
23589296b3edSMax Reitz     int ret;
23591bd0e2d1SChunyan Liu     QemuOptDesc *desc = opts->list->desc;
23609296b3edSMax Reitz 
23611bd0e2d1SChunyan Liu     while (desc && desc->name) {
23621bd0e2d1SChunyan Liu         if (!qemu_opt_find(opts, desc->name)) {
23639296b3edSMax Reitz             /* only change explicitly defined options */
23641bd0e2d1SChunyan Liu             desc++;
23659296b3edSMax Reitz             continue;
23669296b3edSMax Reitz         }
23679296b3edSMax Reitz 
23681bd0e2d1SChunyan Liu         if (!strcmp(desc->name, "compat")) {
23691bd0e2d1SChunyan Liu             compat = qemu_opt_get(opts, "compat");
23701bd0e2d1SChunyan Liu             if (!compat) {
23719296b3edSMax Reitz                 /* preserve default */
23721bd0e2d1SChunyan Liu             } else if (!strcmp(compat, "0.10")) {
23739296b3edSMax Reitz                 new_version = 2;
23741bd0e2d1SChunyan Liu             } else if (!strcmp(compat, "1.1")) {
23759296b3edSMax Reitz                 new_version = 3;
23769296b3edSMax Reitz             } else {
23771bd0e2d1SChunyan Liu                 fprintf(stderr, "Unknown compatibility level %s.\n", compat);
23789296b3edSMax Reitz                 return -EINVAL;
23799296b3edSMax Reitz             }
23801bd0e2d1SChunyan Liu         } else if (!strcmp(desc->name, "preallocation")) {
23819296b3edSMax Reitz             fprintf(stderr, "Cannot change preallocation mode.\n");
23829296b3edSMax Reitz             return -ENOTSUP;
23831bd0e2d1SChunyan Liu         } else if (!strcmp(desc->name, "size")) {
23841bd0e2d1SChunyan Liu             new_size = qemu_opt_get_size(opts, "size", 0);
23851bd0e2d1SChunyan Liu         } else if (!strcmp(desc->name, "backing_file")) {
23861bd0e2d1SChunyan Liu             backing_file = qemu_opt_get(opts, "backing_file");
23871bd0e2d1SChunyan Liu         } else if (!strcmp(desc->name, "backing_fmt")) {
23881bd0e2d1SChunyan Liu             backing_format = qemu_opt_get(opts, "backing_fmt");
23891bd0e2d1SChunyan Liu         } else if (!strcmp(desc->name, "encryption")) {
23901bd0e2d1SChunyan Liu             encrypt = qemu_opt_get_bool(opts, "encryption", s->crypt_method);
23911bd0e2d1SChunyan Liu             if (encrypt != !!s->crypt_method) {
23929296b3edSMax Reitz                 fprintf(stderr, "Changing the encryption flag is not "
23939296b3edSMax Reitz                         "supported.\n");
23949296b3edSMax Reitz                 return -ENOTSUP;
23959296b3edSMax Reitz             }
23961bd0e2d1SChunyan Liu         } else if (!strcmp(desc->name, "cluster_size")) {
23971bd0e2d1SChunyan Liu             cluster_size = qemu_opt_get_size(opts, "cluster_size",
23981bd0e2d1SChunyan Liu                                              cluster_size);
23991bd0e2d1SChunyan Liu             if (cluster_size != s->cluster_size) {
24009296b3edSMax Reitz                 fprintf(stderr, "Changing the cluster size is not "
24019296b3edSMax Reitz                         "supported.\n");
24029296b3edSMax Reitz                 return -ENOTSUP;
24039296b3edSMax Reitz             }
24041bd0e2d1SChunyan Liu         } else if (!strcmp(desc->name, "lazy_refcounts")) {
24051bd0e2d1SChunyan Liu             lazy_refcounts = qemu_opt_get_bool(opts, "lazy_refcounts",
24061bd0e2d1SChunyan Liu                                                lazy_refcounts);
24079296b3edSMax Reitz         } else {
24089296b3edSMax Reitz             /* if this assertion fails, this probably means a new option was
24099296b3edSMax Reitz              * added without having it covered here */
24109296b3edSMax Reitz             assert(false);
24119296b3edSMax Reitz         }
24121bd0e2d1SChunyan Liu 
24131bd0e2d1SChunyan Liu         desc++;
24149296b3edSMax Reitz     }
24159296b3edSMax Reitz 
24169296b3edSMax Reitz     if (new_version != old_version) {
24179296b3edSMax Reitz         if (new_version > old_version) {
24189296b3edSMax Reitz             /* Upgrade */
24199296b3edSMax Reitz             s->qcow_version = new_version;
24209296b3edSMax Reitz             ret = qcow2_update_header(bs);
24219296b3edSMax Reitz             if (ret < 0) {
24229296b3edSMax Reitz                 s->qcow_version = old_version;
24239296b3edSMax Reitz                 return ret;
24249296b3edSMax Reitz             }
24259296b3edSMax Reitz         } else {
24269296b3edSMax Reitz             ret = qcow2_downgrade(bs, new_version);
24279296b3edSMax Reitz             if (ret < 0) {
24289296b3edSMax Reitz                 return ret;
24299296b3edSMax Reitz             }
24309296b3edSMax Reitz         }
24319296b3edSMax Reitz     }
24329296b3edSMax Reitz 
24339296b3edSMax Reitz     if (backing_file || backing_format) {
24349296b3edSMax Reitz         ret = qcow2_change_backing_file(bs, backing_file ?: bs->backing_file,
24359296b3edSMax Reitz                                         backing_format ?: bs->backing_format);
24369296b3edSMax Reitz         if (ret < 0) {
24379296b3edSMax Reitz             return ret;
24389296b3edSMax Reitz         }
24399296b3edSMax Reitz     }
24409296b3edSMax Reitz 
24419296b3edSMax Reitz     if (s->use_lazy_refcounts != lazy_refcounts) {
24429296b3edSMax Reitz         if (lazy_refcounts) {
24439296b3edSMax Reitz             if (s->qcow_version < 3) {
24449296b3edSMax Reitz                 fprintf(stderr, "Lazy refcounts only supported with compatibility "
24459296b3edSMax Reitz                         "level 1.1 and above (use compat=1.1 or greater)\n");
24469296b3edSMax Reitz                 return -EINVAL;
24479296b3edSMax Reitz             }
24489296b3edSMax Reitz             s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
24499296b3edSMax Reitz             ret = qcow2_update_header(bs);
24509296b3edSMax Reitz             if (ret < 0) {
24519296b3edSMax Reitz                 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
24529296b3edSMax Reitz                 return ret;
24539296b3edSMax Reitz             }
24549296b3edSMax Reitz             s->use_lazy_refcounts = true;
24559296b3edSMax Reitz         } else {
24569296b3edSMax Reitz             /* make image clean first */
24579296b3edSMax Reitz             ret = qcow2_mark_clean(bs);
24589296b3edSMax Reitz             if (ret < 0) {
24599296b3edSMax Reitz                 return ret;
24609296b3edSMax Reitz             }
24619296b3edSMax Reitz             /* now disallow lazy refcounts */
24629296b3edSMax Reitz             s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
24639296b3edSMax Reitz             ret = qcow2_update_header(bs);
24649296b3edSMax Reitz             if (ret < 0) {
24659296b3edSMax Reitz                 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
24669296b3edSMax Reitz                 return ret;
24679296b3edSMax Reitz             }
24689296b3edSMax Reitz             s->use_lazy_refcounts = false;
24699296b3edSMax Reitz         }
24709296b3edSMax Reitz     }
24719296b3edSMax Reitz 
24729296b3edSMax Reitz     if (new_size) {
24739296b3edSMax Reitz         ret = bdrv_truncate(bs, new_size);
24749296b3edSMax Reitz         if (ret < 0) {
24759296b3edSMax Reitz             return ret;
24769296b3edSMax Reitz         }
24779296b3edSMax Reitz     }
24789296b3edSMax Reitz 
24799296b3edSMax Reitz     return 0;
24809296b3edSMax Reitz }
24819296b3edSMax Reitz 
24821bd0e2d1SChunyan Liu static QemuOptsList qcow2_create_opts = {
24831bd0e2d1SChunyan Liu     .name = "qcow2-create-opts",
24841bd0e2d1SChunyan Liu     .head = QTAILQ_HEAD_INITIALIZER(qcow2_create_opts.head),
24851bd0e2d1SChunyan Liu     .desc = {
248620d97356SBlue Swirl         {
248720d97356SBlue Swirl             .name = BLOCK_OPT_SIZE,
24881bd0e2d1SChunyan Liu             .type = QEMU_OPT_SIZE,
248920d97356SBlue Swirl             .help = "Virtual disk size"
249020d97356SBlue Swirl         },
249120d97356SBlue Swirl         {
24926744cbabSKevin Wolf             .name = BLOCK_OPT_COMPAT_LEVEL,
24931bd0e2d1SChunyan Liu             .type = QEMU_OPT_STRING,
24946744cbabSKevin Wolf             .help = "Compatibility level (0.10 or 1.1)"
24956744cbabSKevin Wolf         },
24966744cbabSKevin Wolf         {
249720d97356SBlue Swirl             .name = BLOCK_OPT_BACKING_FILE,
24981bd0e2d1SChunyan Liu             .type = QEMU_OPT_STRING,
249920d97356SBlue Swirl             .help = "File name of a base image"
250020d97356SBlue Swirl         },
250120d97356SBlue Swirl         {
250220d97356SBlue Swirl             .name = BLOCK_OPT_BACKING_FMT,
25031bd0e2d1SChunyan Liu             .type = QEMU_OPT_STRING,
250420d97356SBlue Swirl             .help = "Image format of the base image"
250520d97356SBlue Swirl         },
250620d97356SBlue Swirl         {
250720d97356SBlue Swirl             .name = BLOCK_OPT_ENCRYPT,
25081bd0e2d1SChunyan Liu             .type = QEMU_OPT_BOOL,
25091bd0e2d1SChunyan Liu             .help = "Encrypt the image",
25101bd0e2d1SChunyan Liu             .def_value_str = "off"
251120d97356SBlue Swirl         },
251220d97356SBlue Swirl         {
251320d97356SBlue Swirl             .name = BLOCK_OPT_CLUSTER_SIZE,
25141bd0e2d1SChunyan Liu             .type = QEMU_OPT_SIZE,
251599cce9faSKevin Wolf             .help = "qcow2 cluster size",
25161bd0e2d1SChunyan Liu             .def_value_str = stringify(DEFAULT_CLUSTER_SIZE)
251720d97356SBlue Swirl         },
251820d97356SBlue Swirl         {
251920d97356SBlue Swirl             .name = BLOCK_OPT_PREALLOC,
25201bd0e2d1SChunyan Liu             .type = QEMU_OPT_STRING,
252120d97356SBlue Swirl             .help = "Preallocation mode (allowed values: off, metadata)"
252220d97356SBlue Swirl         },
2523bfe8043eSStefan Hajnoczi         {
2524bfe8043eSStefan Hajnoczi             .name = BLOCK_OPT_LAZY_REFCOUNTS,
25251bd0e2d1SChunyan Liu             .type = QEMU_OPT_BOOL,
2526bfe8043eSStefan Hajnoczi             .help = "Postpone refcount updates",
25271bd0e2d1SChunyan Liu             .def_value_str = "off"
2528bfe8043eSStefan Hajnoczi         },
25291bd0e2d1SChunyan Liu         { /* end of list */ }
25301bd0e2d1SChunyan Liu     }
253120d97356SBlue Swirl };
253220d97356SBlue Swirl 
253320d97356SBlue Swirl static BlockDriver bdrv_qcow2 = {
253420d97356SBlue Swirl     .format_name        = "qcow2",
253520d97356SBlue Swirl     .instance_size      = sizeof(BDRVQcowState),
25367c80ab3fSJes Sorensen     .bdrv_probe         = qcow2_probe,
25377c80ab3fSJes Sorensen     .bdrv_open          = qcow2_open,
25387c80ab3fSJes Sorensen     .bdrv_close         = qcow2_close,
253921d82ac9SJeff Cody     .bdrv_reopen_prepare  = qcow2_reopen_prepare,
2540c282e1fdSChunyan Liu     .bdrv_create        = qcow2_create,
25413ac21627SPeter Lieven     .bdrv_has_zero_init = bdrv_has_zero_init_1,
2542b6b8a333SPaolo Bonzini     .bdrv_co_get_block_status = qcow2_co_get_block_status,
25437c80ab3fSJes Sorensen     .bdrv_set_key       = qcow2_set_key,
254420d97356SBlue Swirl 
254568d100e9SKevin Wolf     .bdrv_co_readv          = qcow2_co_readv,
254668d100e9SKevin Wolf     .bdrv_co_writev         = qcow2_co_writev,
2547eb489bb1SKevin Wolf     .bdrv_co_flush_to_os    = qcow2_co_flush_to_os,
2548419b19d9SStefan Hajnoczi 
2549621f0589SKevin Wolf     .bdrv_co_write_zeroes   = qcow2_co_write_zeroes,
25506db39ae2SPaolo Bonzini     .bdrv_co_discard        = qcow2_co_discard,
2551419b19d9SStefan Hajnoczi     .bdrv_truncate          = qcow2_truncate,
25527c80ab3fSJes Sorensen     .bdrv_write_compressed  = qcow2_write_compressed,
255320d97356SBlue Swirl 
255420d97356SBlue Swirl     .bdrv_snapshot_create   = qcow2_snapshot_create,
255520d97356SBlue Swirl     .bdrv_snapshot_goto     = qcow2_snapshot_goto,
255620d97356SBlue Swirl     .bdrv_snapshot_delete   = qcow2_snapshot_delete,
255720d97356SBlue Swirl     .bdrv_snapshot_list     = qcow2_snapshot_list,
255851ef6727Sedison     .bdrv_snapshot_load_tmp = qcow2_snapshot_load_tmp,
25597c80ab3fSJes Sorensen     .bdrv_get_info          = qcow2_get_info,
256037764dfbSMax Reitz     .bdrv_get_specific_info = qcow2_get_specific_info,
256120d97356SBlue Swirl 
25627c80ab3fSJes Sorensen     .bdrv_save_vmstate    = qcow2_save_vmstate,
25637c80ab3fSJes Sorensen     .bdrv_load_vmstate    = qcow2_load_vmstate,
256420d97356SBlue Swirl 
25658ee79e70SKevin Wolf     .supports_backing           = true,
256620d97356SBlue Swirl     .bdrv_change_backing_file   = qcow2_change_backing_file,
256720d97356SBlue Swirl 
2568d34682cdSKevin Wolf     .bdrv_refresh_limits        = qcow2_refresh_limits,
256906d9260fSAnthony Liguori     .bdrv_invalidate_cache      = qcow2_invalidate_cache,
257006d9260fSAnthony Liguori 
25711bd0e2d1SChunyan Liu     .create_opts         = &qcow2_create_opts,
25727c80ab3fSJes Sorensen     .bdrv_check          = qcow2_check,
2573c282e1fdSChunyan Liu     .bdrv_amend_options  = qcow2_amend_options,
257420d97356SBlue Swirl };
257520d97356SBlue Swirl 
25765efa9d5aSAnthony Liguori static void bdrv_qcow2_init(void)
25775efa9d5aSAnthony Liguori {
25785efa9d5aSAnthony Liguori     bdrv_register(&bdrv_qcow2);
25795efa9d5aSAnthony Liguori }
25805efa9d5aSAnthony Liguori 
25815efa9d5aSAnthony Liguori block_init(bdrv_qcow2_init);
2582