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 */
24e688df6bSMarkus Armbruster
2580c71a24SPeter Maydell #include "qemu/osdep.h"
262714f13dSVladimir Sementsov-Ogievskiy
27609f45eaSMax Reitz #include "block/qdict.h"
2832cad1ffSPhilippe Mathieu-Daudé #include "system/block-backend.h"
29db725815SMarkus Armbruster #include "qemu/main-loop.h"
301de7afc9SPaolo Bonzini #include "qemu/module.h"
310d8c41daSMichael S. Tsirkin #include "qcow2.h"
321de7afc9SPaolo Bonzini #include "qemu/error-report.h"
33e688df6bSMarkus Armbruster #include "qapi/error.h"
349af23989SMarkus Armbruster #include "qapi/qapi-events-block-core.h"
35407bc4bfSDaniel P. Berrangé #include "qobject/qdict.h"
36407bc4bfSDaniel P. Berrangé #include "qobject/qstring.h"
373cce16f4SKevin Wolf #include "trace.h"
381bd0e2d1SChunyan Liu #include "qemu/option_int.h"
39f348b6d1SVeronia Bahaa #include "qemu/cutils.h"
4058369e22SPaolo Bonzini #include "qemu/bswap.h"
415df022cfSPeter Maydell #include "qemu/memalign.h"
42b76b4f60SKevin Wolf #include "qapi/qobject-input-visitor.h"
43b76b4f60SKevin Wolf #include "qapi/qapi-visit-block-core.h"
440d8c41daSMichael S. Tsirkin #include "crypto.h"
45d710cf57SVladimir Sementsov-Ogievskiy #include "block/aio_task.h"
46e2c1c34fSMarkus Armbruster #include "block/dirty-bitmap.h"
47585f8587Sbellard
48585f8587Sbellard /*
49585f8587Sbellard Differences with QCOW:
50585f8587Sbellard
51585f8587Sbellard - Support for multiple incremental snapshots.
52585f8587Sbellard - Memory management by reference counts.
53585f8587Sbellard - Clusters which have a reference count of one have the bit
54585f8587Sbellard QCOW_OFLAG_COPIED to optimize write performance.
55585f8587Sbellard - Size of compressed clusters is stored in sectors to reduce bit usage
56585f8587Sbellard in the cluster offsets.
57585f8587Sbellard - Support for storing additional data (such as the VM state) in the
58585f8587Sbellard snapshots.
59585f8587Sbellard - If a backing store is used, the cluster size is not constrained
60585f8587Sbellard (could be backported to QCOW).
61585f8587Sbellard - L2 tables have always a size of one cluster.
62585f8587Sbellard */
63585f8587Sbellard
649b80ddf3Saliguori
659b80ddf3Saliguori typedef struct {
669b80ddf3Saliguori uint32_t magic;
679b80ddf3Saliguori uint32_t len;
68c4217f64SJeff Cody } QEMU_PACKED QCowExtension;
6921d82ac9SJeff Cody
707c80ab3fSJes Sorensen #define QCOW2_EXT_MAGIC_END 0
718098969cSAndrey Shinkevich #define QCOW2_EXT_MAGIC_BACKING_FORMAT 0xe2792aca
72cfcc4c62SKevin Wolf #define QCOW2_EXT_MAGIC_FEATURE_TABLE 0x6803f857
734652b8f3SDaniel P. Berrange #define QCOW2_EXT_MAGIC_CRYPTO_HEADER 0x0537be77
7488ddffaeSVladimir Sementsov-Ogievskiy #define QCOW2_EXT_MAGIC_BITMAPS 0x23852875
7593c24936SKevin Wolf #define QCOW2_EXT_MAGIC_DATA_FILE 0x44415441
769b80ddf3Saliguori
77c3c10f72SVladimir Sementsov-Ogievskiy static int coroutine_fn
78c3c10f72SVladimir Sementsov-Ogievskiy qcow2_co_preadv_compressed(BlockDriverState *bs,
799a3978a4SVladimir Sementsov-Ogievskiy uint64_t l2_entry,
80c3c10f72SVladimir Sementsov-Ogievskiy uint64_t offset,
81c3c10f72SVladimir Sementsov-Ogievskiy uint64_t bytes,
82df893d25SVladimir Sementsov-Ogievskiy QEMUIOVector *qiov,
83df893d25SVladimir Sementsov-Ogievskiy size_t qiov_offset);
84c3c10f72SVladimir Sementsov-Ogievskiy
qcow2_probe(const uint8_t * buf,int buf_size,const char * filename)857c80ab3fSJes Sorensen static int qcow2_probe(const uint8_t *buf, int buf_size, const char *filename)
86585f8587Sbellard {
87585f8587Sbellard const QCowHeader *cow_header = (const void *)buf;
88585f8587Sbellard
89585f8587Sbellard if (buf_size >= sizeof(QCowHeader) &&
90585f8587Sbellard be32_to_cpu(cow_header->magic) == QCOW_MAGIC &&
916744cbabSKevin Wolf be32_to_cpu(cow_header->version) >= 2)
92585f8587Sbellard return 100;
93585f8587Sbellard else
94585f8587Sbellard return 0;
95585f8587Sbellard }
96585f8587Sbellard
979b80ddf3Saliguori
988f897341SKevin Wolf static int GRAPH_RDLOCK
qcow2_crypto_hdr_read_func(QCryptoBlock * block,size_t offset,uint8_t * buf,size_t buflen,void * opaque,Error ** errp)998f897341SKevin Wolf qcow2_crypto_hdr_read_func(QCryptoBlock *block, size_t offset,
1004652b8f3SDaniel P. Berrange uint8_t *buf, size_t buflen,
1014652b8f3SDaniel P. Berrange void *opaque, Error **errp)
1024652b8f3SDaniel P. Berrange {
1034652b8f3SDaniel P. Berrange BlockDriverState *bs = opaque;
1044652b8f3SDaniel P. Berrange BDRVQcow2State *s = bs->opaque;
1054652b8f3SDaniel P. Berrange ssize_t ret;
1064652b8f3SDaniel P. Berrange
1074652b8f3SDaniel P. Berrange if ((offset + buflen) > s->crypto_header.length) {
1084652b8f3SDaniel P. Berrange error_setg(errp, "Request for data outside of extension header");
1094652b8f3SDaniel P. Berrange return -1;
1104652b8f3SDaniel P. Berrange }
1114652b8f3SDaniel P. Berrange
11232cc71deSAlberto Faria ret = bdrv_pread(bs->file, s->crypto_header.offset + offset, buflen, buf,
11353fb7844SAlberto Faria 0);
1144652b8f3SDaniel P. Berrange if (ret < 0) {
1154652b8f3SDaniel P. Berrange error_setg_errno(errp, -ret, "Could not read encryption header");
1164652b8f3SDaniel P. Berrange return -1;
1174652b8f3SDaniel P. Berrange }
118757dda54SAlberto Faria return 0;
1194652b8f3SDaniel P. Berrange }
1204652b8f3SDaniel P. Berrange
1214652b8f3SDaniel P. Berrange
1224db7ba3bSKevin Wolf static int coroutine_fn GRAPH_RDLOCK
qcow2_crypto_hdr_init_func(QCryptoBlock * block,size_t headerlen,void * opaque,Error ** errp)1234db7ba3bSKevin Wolf qcow2_crypto_hdr_init_func(QCryptoBlock *block, size_t headerlen, void *opaque,
1244db7ba3bSKevin Wolf Error **errp)
1254652b8f3SDaniel P. Berrange {
1264652b8f3SDaniel P. Berrange BlockDriverState *bs = opaque;
1274652b8f3SDaniel P. Berrange BDRVQcow2State *s = bs->opaque;
1284652b8f3SDaniel P. Berrange int64_t ret;
1294652b8f3SDaniel P. Berrange int64_t clusterlen;
1304652b8f3SDaniel P. Berrange
1314652b8f3SDaniel P. Berrange ret = qcow2_alloc_clusters(bs, headerlen);
1324652b8f3SDaniel P. Berrange if (ret < 0) {
1334652b8f3SDaniel P. Berrange error_setg_errno(errp, -ret,
1344652b8f3SDaniel P. Berrange "Cannot allocate cluster for LUKS header size %zu",
1354652b8f3SDaniel P. Berrange headerlen);
1364652b8f3SDaniel P. Berrange return -1;
1374652b8f3SDaniel P. Berrange }
1384652b8f3SDaniel P. Berrange
1394652b8f3SDaniel P. Berrange s->crypto_header.length = headerlen;
1404652b8f3SDaniel P. Berrange s->crypto_header.offset = ret;
1414652b8f3SDaniel P. Berrange
142087ab8e7SDaniel P. Berrangé /*
143087ab8e7SDaniel P. Berrangé * Zero fill all space in cluster so it has predictable
144087ab8e7SDaniel P. Berrangé * content, as we may not initialize some regions of the
145087ab8e7SDaniel P. Berrangé * header (eg only 1 out of 8 key slots will be initialized)
146087ab8e7SDaniel P. Berrangé */
1474652b8f3SDaniel P. Berrange clusterlen = size_to_clusters(s, headerlen) * s->cluster_size;
148966b000fSKevin Wolf assert(qcow2_pre_write_overlap_check(bs, 0, ret, clusterlen, false) == 0);
1494db7ba3bSKevin Wolf ret = bdrv_co_pwrite_zeroes(bs->file, ret, clusterlen, 0);
1504652b8f3SDaniel P. Berrange if (ret < 0) {
1514652b8f3SDaniel P. Berrange error_setg_errno(errp, -ret, "Could not zero fill encryption header");
1524652b8f3SDaniel P. Berrange return -1;
1534652b8f3SDaniel P. Berrange }
1544652b8f3SDaniel P. Berrange
155757dda54SAlberto Faria return 0;
1564652b8f3SDaniel P. Berrange }
1574652b8f3SDaniel P. Berrange
1584652b8f3SDaniel P. Berrange
1594db7ba3bSKevin Wolf /* The graph lock must be held when called in coroutine context */
1608f897341SKevin Wolf static int coroutine_mixed_fn GRAPH_RDLOCK
qcow2_crypto_hdr_write_func(QCryptoBlock * block,size_t offset,const uint8_t * buf,size_t buflen,void * opaque,Error ** errp)1614db7ba3bSKevin Wolf qcow2_crypto_hdr_write_func(QCryptoBlock *block, size_t offset,
1624652b8f3SDaniel P. Berrange const uint8_t *buf, size_t buflen,
1634652b8f3SDaniel P. Berrange void *opaque, Error **errp)
1644652b8f3SDaniel P. Berrange {
1654652b8f3SDaniel P. Berrange BlockDriverState *bs = opaque;
1664652b8f3SDaniel P. Berrange BDRVQcow2State *s = bs->opaque;
1674652b8f3SDaniel P. Berrange ssize_t ret;
1684652b8f3SDaniel P. Berrange
1694652b8f3SDaniel P. Berrange if ((offset + buflen) > s->crypto_header.length) {
1704652b8f3SDaniel P. Berrange error_setg(errp, "Request for data outside of extension header");
1714652b8f3SDaniel P. Berrange return -1;
1724652b8f3SDaniel P. Berrange }
1734652b8f3SDaniel P. Berrange
17432cc71deSAlberto Faria ret = bdrv_pwrite(bs->file, s->crypto_header.offset + offset, buflen, buf,
17553fb7844SAlberto Faria 0);
1764652b8f3SDaniel P. Berrange if (ret < 0) {
1774652b8f3SDaniel P. Berrange error_setg_errno(errp, -ret, "Could not read encryption header");
1784652b8f3SDaniel P. Berrange return -1;
1794652b8f3SDaniel P. Berrange }
180757dda54SAlberto Faria return 0;
1814652b8f3SDaniel P. Berrange }
1824652b8f3SDaniel P. Berrange
18390766d9dSMaxim Levitsky static QDict*
qcow2_extract_crypto_opts(QemuOpts * opts,const char * fmt,Error ** errp)18490766d9dSMaxim Levitsky qcow2_extract_crypto_opts(QemuOpts *opts, const char *fmt, Error **errp)
18590766d9dSMaxim Levitsky {
18690766d9dSMaxim Levitsky QDict *cryptoopts_qdict;
18790766d9dSMaxim Levitsky QDict *opts_qdict;
18890766d9dSMaxim Levitsky
18990766d9dSMaxim Levitsky /* Extract "encrypt." options into a qdict */
19090766d9dSMaxim Levitsky opts_qdict = qemu_opts_to_qdict(opts, NULL);
19190766d9dSMaxim Levitsky qdict_extract_subqdict(opts_qdict, &cryptoopts_qdict, "encrypt.");
19290766d9dSMaxim Levitsky qobject_unref(opts_qdict);
19390766d9dSMaxim Levitsky qdict_put_str(cryptoopts_qdict, "format", fmt);
19490766d9dSMaxim Levitsky return cryptoopts_qdict;
19590766d9dSMaxim Levitsky }
1964652b8f3SDaniel P. Berrange
1979b80ddf3Saliguori /*
1989b80ddf3Saliguori * read qcow2 extension and fill bs
1999b80ddf3Saliguori * start reading from start_offset
2009b80ddf3Saliguori * finish reading upon magic of value 0 or when end_offset reached
2019b80ddf3Saliguori * unknown magic is skipped (future extension this version knows nothing about)
2029b80ddf3Saliguori * return 0 upon success, non-0 otherwise
2039b80ddf3Saliguori */
204a39bae4eSPaolo Bonzini static int coroutine_fn GRAPH_RDLOCK
qcow2_read_extensions(BlockDriverState * bs,uint64_t start_offset,uint64_t end_offset,void ** p_feature_table,int flags,bool * need_update_header,Error ** errp)205a39bae4eSPaolo Bonzini qcow2_read_extensions(BlockDriverState *bs, uint64_t start_offset,
2063ef6c40aSMax Reitz uint64_t end_offset, void **p_feature_table,
207a39bae4eSPaolo Bonzini int flags, bool *need_update_header, Error **errp)
2089b80ddf3Saliguori {
209ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque;
2109b80ddf3Saliguori QCowExtension ext;
2119b80ddf3Saliguori uint64_t offset;
21275bab85cSKevin Wolf int ret;
21388ddffaeSVladimir Sementsov-Ogievskiy Qcow2BitmapHeaderExt bitmaps_ext;
21488ddffaeSVladimir Sementsov-Ogievskiy
21588ddffaeSVladimir Sementsov-Ogievskiy if (need_update_header != NULL) {
21688ddffaeSVladimir Sementsov-Ogievskiy *need_update_header = false;
21788ddffaeSVladimir Sementsov-Ogievskiy }
2189b80ddf3Saliguori
2199b80ddf3Saliguori #ifdef DEBUG_EXT
2207c80ab3fSJes Sorensen printf("qcow2_read_extensions: start=%ld end=%ld\n", start_offset, end_offset);
2219b80ddf3Saliguori #endif
2229b80ddf3Saliguori offset = start_offset;
2239b80ddf3Saliguori while (offset < end_offset) {
2249b80ddf3Saliguori
2259b80ddf3Saliguori #ifdef DEBUG_EXT
2269b80ddf3Saliguori /* Sanity check */
2279b80ddf3Saliguori if (offset > s->cluster_size)
2287c80ab3fSJes Sorensen printf("qcow2_read_extension: suspicious offset %lu\n", offset);
2299b80ddf3Saliguori
2309b2260cbSDong Xu Wang printf("attempting to read extended header in offset %lu\n", offset);
2319b80ddf3Saliguori #endif
2329b80ddf3Saliguori
233a39bae4eSPaolo Bonzini ret = bdrv_co_pread(bs->file, offset, sizeof(ext), &ext, 0);
2343ef6c40aSMax Reitz if (ret < 0) {
2353ef6c40aSMax Reitz error_setg_errno(errp, -ret, "qcow2_read_extension: ERROR: "
2363ef6c40aSMax Reitz "pread fail from offset %" PRIu64, offset);
2379b80ddf3Saliguori return 1;
2389b80ddf3Saliguori }
2393b698f52SPeter Maydell ext.magic = be32_to_cpu(ext.magic);
2403b698f52SPeter Maydell ext.len = be32_to_cpu(ext.len);
2419b80ddf3Saliguori offset += sizeof(ext);
2429b80ddf3Saliguori #ifdef DEBUG_EXT
2439b80ddf3Saliguori printf("ext.magic = 0x%x\n", ext.magic);
2449b80ddf3Saliguori #endif
2452ebafc85SKevin Wolf if (offset > end_offset || ext.len > end_offset - offset) {
2463ef6c40aSMax Reitz error_setg(errp, "Header extension too large");
24764ca6aeeSKevin Wolf return -EINVAL;
24864ca6aeeSKevin Wolf }
24964ca6aeeSKevin Wolf
2509b80ddf3Saliguori switch (ext.magic) {
2517c80ab3fSJes Sorensen case QCOW2_EXT_MAGIC_END:
2529b80ddf3Saliguori return 0;
253f965509cSaliguori
2547c80ab3fSJes Sorensen case QCOW2_EXT_MAGIC_BACKING_FORMAT:
255f965509cSaliguori if (ext.len >= sizeof(bs->backing_format)) {
256521b2b5dSMax Reitz error_setg(errp, "ERROR: ext_backing_format: len=%" PRIu32
257521b2b5dSMax Reitz " too large (>=%zu)", ext.len,
258521b2b5dSMax Reitz sizeof(bs->backing_format));
259f965509cSaliguori return 2;
260f965509cSaliguori }
261a39bae4eSPaolo Bonzini ret = bdrv_co_pread(bs->file, offset, ext.len, bs->backing_format, 0);
2623ef6c40aSMax Reitz if (ret < 0) {
2633ef6c40aSMax Reitz error_setg_errno(errp, -ret, "ERROR: ext_backing_format: "
2643ef6c40aSMax Reitz "Could not read format name");
265f965509cSaliguori return 3;
2663ef6c40aSMax Reitz }
267f965509cSaliguori bs->backing_format[ext.len] = '\0';
268e4603fe1SKevin Wolf s->image_backing_format = g_strdup(bs->backing_format);
269f965509cSaliguori #ifdef DEBUG_EXT
270f965509cSaliguori printf("Qcow2: Got format extension %s\n", bs->backing_format);
271f965509cSaliguori #endif
272f965509cSaliguori break;
273f965509cSaliguori
274cfcc4c62SKevin Wolf case QCOW2_EXT_MAGIC_FEATURE_TABLE:
275cfcc4c62SKevin Wolf if (p_feature_table != NULL) {
276cfcc4c62SKevin Wolf void *feature_table = g_malloc0(ext.len + 2 * sizeof(Qcow2Feature));
277a39bae4eSPaolo Bonzini ret = bdrv_co_pread(bs->file, offset, ext.len, feature_table, 0);
278cfcc4c62SKevin Wolf if (ret < 0) {
2793ef6c40aSMax Reitz error_setg_errno(errp, -ret, "ERROR: ext_feature_table: "
2803ef6c40aSMax Reitz "Could not read table");
28138f034e7Slu zhipeng g_free(feature_table);
282cfcc4c62SKevin Wolf return ret;
283cfcc4c62SKevin Wolf }
284cfcc4c62SKevin Wolf
285cfcc4c62SKevin Wolf *p_feature_table = feature_table;
286cfcc4c62SKevin Wolf }
287cfcc4c62SKevin Wolf break;
288cfcc4c62SKevin Wolf
2894652b8f3SDaniel P. Berrange case QCOW2_EXT_MAGIC_CRYPTO_HEADER: {
2904652b8f3SDaniel P. Berrange unsigned int cflags = 0;
2914652b8f3SDaniel P. Berrange if (s->crypt_method_header != QCOW_CRYPT_LUKS) {
2924652b8f3SDaniel P. Berrange error_setg(errp, "CRYPTO header extension only "
2934652b8f3SDaniel P. Berrange "expected with LUKS encryption method");
2944652b8f3SDaniel P. Berrange return -EINVAL;
2954652b8f3SDaniel P. Berrange }
2964652b8f3SDaniel P. Berrange if (ext.len != sizeof(Qcow2CryptoHeaderExtension)) {
2974652b8f3SDaniel P. Berrange error_setg(errp, "CRYPTO header extension size %u, "
2984652b8f3SDaniel P. Berrange "but expected size %zu", ext.len,
2994652b8f3SDaniel P. Berrange sizeof(Qcow2CryptoHeaderExtension));
3004652b8f3SDaniel P. Berrange return -EINVAL;
3014652b8f3SDaniel P. Berrange }
3024652b8f3SDaniel P. Berrange
303a39bae4eSPaolo Bonzini ret = bdrv_co_pread(bs->file, offset, ext.len, &s->crypto_header, 0);
3044652b8f3SDaniel P. Berrange if (ret < 0) {
3054652b8f3SDaniel P. Berrange error_setg_errno(errp, -ret,
3064652b8f3SDaniel P. Berrange "Unable to read CRYPTO header extension");
3074652b8f3SDaniel P. Berrange return ret;
3084652b8f3SDaniel P. Berrange }
3093b698f52SPeter Maydell s->crypto_header.offset = be64_to_cpu(s->crypto_header.offset);
3103b698f52SPeter Maydell s->crypto_header.length = be64_to_cpu(s->crypto_header.length);
3114652b8f3SDaniel P. Berrange
3124652b8f3SDaniel P. Berrange if ((s->crypto_header.offset % s->cluster_size) != 0) {
3134652b8f3SDaniel P. Berrange error_setg(errp, "Encryption header offset '%" PRIu64 "' is "
3144652b8f3SDaniel P. Berrange "not a multiple of cluster size '%u'",
3154652b8f3SDaniel P. Berrange s->crypto_header.offset, s->cluster_size);
3164652b8f3SDaniel P. Berrange return -EINVAL;
3174652b8f3SDaniel P. Berrange }
3184652b8f3SDaniel P. Berrange
3194652b8f3SDaniel P. Berrange if (flags & BDRV_O_NO_IO) {
3204652b8f3SDaniel P. Berrange cflags |= QCRYPTO_BLOCK_OPEN_NO_IO;
3214652b8f3SDaniel P. Berrange }
3221cd9a787SDaniel P. Berrange s->crypto = qcrypto_block_open(s->crypto_opts, "encrypt.",
3234652b8f3SDaniel P. Berrange qcow2_crypto_hdr_read_func,
3243ab0f063SStefan Hajnoczi bs, cflags, errp);
3254652b8f3SDaniel P. Berrange if (!s->crypto) {
3264652b8f3SDaniel P. Berrange return -EINVAL;
3274652b8f3SDaniel P. Berrange }
3284652b8f3SDaniel P. Berrange } break;
3294652b8f3SDaniel P. Berrange
33088ddffaeSVladimir Sementsov-Ogievskiy case QCOW2_EXT_MAGIC_BITMAPS:
33188ddffaeSVladimir Sementsov-Ogievskiy if (ext.len != sizeof(bitmaps_ext)) {
33288ddffaeSVladimir Sementsov-Ogievskiy error_setg_errno(errp, -ret, "bitmaps_ext: "
33388ddffaeSVladimir Sementsov-Ogievskiy "Invalid extension length");
33488ddffaeSVladimir Sementsov-Ogievskiy return -EINVAL;
33588ddffaeSVladimir Sementsov-Ogievskiy }
33688ddffaeSVladimir Sementsov-Ogievskiy
33788ddffaeSVladimir Sementsov-Ogievskiy if (!(s->autoclear_features & QCOW2_AUTOCLEAR_BITMAPS)) {
338c9ceb3ecSMax Reitz if (s->qcow_version < 3) {
339c9ceb3ecSMax Reitz /* Let's be a bit more specific */
340c9ceb3ecSMax Reitz warn_report("This qcow2 v2 image contains bitmaps, but "
341c9ceb3ecSMax Reitz "they may have been modified by a program "
342c9ceb3ecSMax Reitz "without persistent bitmap support; so now "
343c9ceb3ecSMax Reitz "they must all be considered inconsistent");
344c9ceb3ecSMax Reitz } else {
34555d527a9SAlistair Francis warn_report("a program lacking bitmap support "
34688ddffaeSVladimir Sementsov-Ogievskiy "modified this file, so all bitmaps are now "
34755d527a9SAlistair Francis "considered inconsistent");
348c9ceb3ecSMax Reitz }
34955d527a9SAlistair Francis error_printf("Some clusters may be leaked, "
35055d527a9SAlistair Francis "run 'qemu-img check -r' on the image "
35188ddffaeSVladimir Sementsov-Ogievskiy "file to fix.");
35288ddffaeSVladimir Sementsov-Ogievskiy if (need_update_header != NULL) {
35388ddffaeSVladimir Sementsov-Ogievskiy /* Updating is needed to drop invalid bitmap extension. */
35488ddffaeSVladimir Sementsov-Ogievskiy *need_update_header = true;
35588ddffaeSVladimir Sementsov-Ogievskiy }
35688ddffaeSVladimir Sementsov-Ogievskiy break;
35788ddffaeSVladimir Sementsov-Ogievskiy }
35888ddffaeSVladimir Sementsov-Ogievskiy
359a39bae4eSPaolo Bonzini ret = bdrv_co_pread(bs->file, offset, ext.len, &bitmaps_ext, 0);
36088ddffaeSVladimir Sementsov-Ogievskiy if (ret < 0) {
36188ddffaeSVladimir Sementsov-Ogievskiy error_setg_errno(errp, -ret, "bitmaps_ext: "
36288ddffaeSVladimir Sementsov-Ogievskiy "Could not read ext header");
36388ddffaeSVladimir Sementsov-Ogievskiy return ret;
36488ddffaeSVladimir Sementsov-Ogievskiy }
36588ddffaeSVladimir Sementsov-Ogievskiy
36688ddffaeSVladimir Sementsov-Ogievskiy if (bitmaps_ext.reserved32 != 0) {
36788ddffaeSVladimir Sementsov-Ogievskiy error_setg_errno(errp, -ret, "bitmaps_ext: "
36888ddffaeSVladimir Sementsov-Ogievskiy "Reserved field is not zero");
36988ddffaeSVladimir Sementsov-Ogievskiy return -EINVAL;
37088ddffaeSVladimir Sementsov-Ogievskiy }
37188ddffaeSVladimir Sementsov-Ogievskiy
3723b698f52SPeter Maydell bitmaps_ext.nb_bitmaps = be32_to_cpu(bitmaps_ext.nb_bitmaps);
3733b698f52SPeter Maydell bitmaps_ext.bitmap_directory_size =
3743b698f52SPeter Maydell be64_to_cpu(bitmaps_ext.bitmap_directory_size);
3753b698f52SPeter Maydell bitmaps_ext.bitmap_directory_offset =
3763b698f52SPeter Maydell be64_to_cpu(bitmaps_ext.bitmap_directory_offset);
37788ddffaeSVladimir Sementsov-Ogievskiy
37888ddffaeSVladimir Sementsov-Ogievskiy if (bitmaps_ext.nb_bitmaps > QCOW2_MAX_BITMAPS) {
37988ddffaeSVladimir Sementsov-Ogievskiy error_setg(errp,
38088ddffaeSVladimir Sementsov-Ogievskiy "bitmaps_ext: Image has %" PRIu32 " bitmaps, "
38188ddffaeSVladimir Sementsov-Ogievskiy "exceeding the QEMU supported maximum of %d",
38288ddffaeSVladimir Sementsov-Ogievskiy bitmaps_ext.nb_bitmaps, QCOW2_MAX_BITMAPS);
38388ddffaeSVladimir Sementsov-Ogievskiy return -EINVAL;
38488ddffaeSVladimir Sementsov-Ogievskiy }
38588ddffaeSVladimir Sementsov-Ogievskiy
38688ddffaeSVladimir Sementsov-Ogievskiy if (bitmaps_ext.nb_bitmaps == 0) {
38788ddffaeSVladimir Sementsov-Ogievskiy error_setg(errp, "found bitmaps extension with zero bitmaps");
38888ddffaeSVladimir Sementsov-Ogievskiy return -EINVAL;
38988ddffaeSVladimir Sementsov-Ogievskiy }
39088ddffaeSVladimir Sementsov-Ogievskiy
39174e60fb5SAlberto Garcia if (offset_into_cluster(s, bitmaps_ext.bitmap_directory_offset)) {
39288ddffaeSVladimir Sementsov-Ogievskiy error_setg(errp, "bitmaps_ext: "
39388ddffaeSVladimir Sementsov-Ogievskiy "invalid bitmap directory offset");
39488ddffaeSVladimir Sementsov-Ogievskiy return -EINVAL;
39588ddffaeSVladimir Sementsov-Ogievskiy }
39688ddffaeSVladimir Sementsov-Ogievskiy
39788ddffaeSVladimir Sementsov-Ogievskiy if (bitmaps_ext.bitmap_directory_size >
39888ddffaeSVladimir Sementsov-Ogievskiy QCOW2_MAX_BITMAP_DIRECTORY_SIZE) {
39988ddffaeSVladimir Sementsov-Ogievskiy error_setg(errp, "bitmaps_ext: "
40088ddffaeSVladimir Sementsov-Ogievskiy "bitmap directory size (%" PRIu64 ") exceeds "
40188ddffaeSVladimir Sementsov-Ogievskiy "the maximum supported size (%d)",
40288ddffaeSVladimir Sementsov-Ogievskiy bitmaps_ext.bitmap_directory_size,
40388ddffaeSVladimir Sementsov-Ogievskiy QCOW2_MAX_BITMAP_DIRECTORY_SIZE);
40488ddffaeSVladimir Sementsov-Ogievskiy return -EINVAL;
40588ddffaeSVladimir Sementsov-Ogievskiy }
40688ddffaeSVladimir Sementsov-Ogievskiy
40788ddffaeSVladimir Sementsov-Ogievskiy s->nb_bitmaps = bitmaps_ext.nb_bitmaps;
40888ddffaeSVladimir Sementsov-Ogievskiy s->bitmap_directory_offset =
40988ddffaeSVladimir Sementsov-Ogievskiy bitmaps_ext.bitmap_directory_offset;
41088ddffaeSVladimir Sementsov-Ogievskiy s->bitmap_directory_size =
41188ddffaeSVladimir Sementsov-Ogievskiy bitmaps_ext.bitmap_directory_size;
41288ddffaeSVladimir Sementsov-Ogievskiy
41388ddffaeSVladimir Sementsov-Ogievskiy #ifdef DEBUG_EXT
41488ddffaeSVladimir Sementsov-Ogievskiy printf("Qcow2: Got bitmaps extension: "
41588ddffaeSVladimir Sementsov-Ogievskiy "offset=%" PRIu64 " nb_bitmaps=%" PRIu32 "\n",
41688ddffaeSVladimir Sementsov-Ogievskiy s->bitmap_directory_offset, s->nb_bitmaps);
41788ddffaeSVladimir Sementsov-Ogievskiy #endif
41888ddffaeSVladimir Sementsov-Ogievskiy break;
41988ddffaeSVladimir Sementsov-Ogievskiy
4209b890bdcSKevin Wolf case QCOW2_EXT_MAGIC_DATA_FILE:
4219b890bdcSKevin Wolf {
4229b890bdcSKevin Wolf s->image_data_file = g_malloc0(ext.len + 1);
423a39bae4eSPaolo Bonzini ret = bdrv_co_pread(bs->file, offset, ext.len, s->image_data_file, 0);
4249b890bdcSKevin Wolf if (ret < 0) {
4259b890bdcSKevin Wolf error_setg_errno(errp, -ret,
4269b890bdcSKevin Wolf "ERROR: Could not read data file name");
4279b890bdcSKevin Wolf return ret;
4289b890bdcSKevin Wolf }
4299b890bdcSKevin Wolf #ifdef DEBUG_EXT
4309b890bdcSKevin Wolf printf("Qcow2: Got external data file %s\n", s->image_data_file);
4319b890bdcSKevin Wolf #endif
4329b890bdcSKevin Wolf break;
4339b890bdcSKevin Wolf }
4349b890bdcSKevin Wolf
4359b80ddf3Saliguori default:
43675bab85cSKevin Wolf /* unknown magic - save it in case we need to rewrite the header */
4374096974eSEric Blake /* If you add a new feature, make sure to also update the fast
4384096974eSEric Blake * path of qcow2_make_empty() to deal with it. */
43975bab85cSKevin Wolf {
44075bab85cSKevin Wolf Qcow2UnknownHeaderExtension *uext;
44175bab85cSKevin Wolf
44275bab85cSKevin Wolf uext = g_malloc0(sizeof(*uext) + ext.len);
44375bab85cSKevin Wolf uext->magic = ext.magic;
44475bab85cSKevin Wolf uext->len = ext.len;
44575bab85cSKevin Wolf QLIST_INSERT_HEAD(&s->unknown_header_ext, uext, next);
44675bab85cSKevin Wolf
447a39bae4eSPaolo Bonzini ret = bdrv_co_pread(bs->file, offset, uext->len, uext->data, 0);
44875bab85cSKevin Wolf if (ret < 0) {
4493ef6c40aSMax Reitz error_setg_errno(errp, -ret, "ERROR: unknown extension: "
4503ef6c40aSMax Reitz "Could not read data");
45175bab85cSKevin Wolf return ret;
45275bab85cSKevin Wolf }
45375bab85cSKevin Wolf }
4549b80ddf3Saliguori break;
4559b80ddf3Saliguori }
456fd29b4bbSKevin Wolf
457fd29b4bbSKevin Wolf offset += ((ext.len + 7) & ~7);
4589b80ddf3Saliguori }
4599b80ddf3Saliguori
4609b80ddf3Saliguori return 0;
4619b80ddf3Saliguori }
4629b80ddf3Saliguori
cleanup_unknown_header_ext(BlockDriverState * bs)46375bab85cSKevin Wolf static void cleanup_unknown_header_ext(BlockDriverState *bs)
46475bab85cSKevin Wolf {
465ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque;
46675bab85cSKevin Wolf Qcow2UnknownHeaderExtension *uext, *next;
46775bab85cSKevin Wolf
46875bab85cSKevin Wolf QLIST_FOREACH_SAFE(uext, &s->unknown_header_ext, next, next) {
46975bab85cSKevin Wolf QLIST_REMOVE(uext, next);
47075bab85cSKevin Wolf g_free(uext);
47175bab85cSKevin Wolf }
47275bab85cSKevin Wolf }
4739b80ddf3Saliguori
report_unsupported_feature(Error ** errp,Qcow2Feature * table,uint64_t mask)474a55448b3SMax Reitz static void report_unsupported_feature(Error **errp, Qcow2Feature *table,
475a55448b3SMax Reitz uint64_t mask)
476cfcc4c62SKevin Wolf {
4777cdca2e2SAlberto Garcia g_autoptr(GString) features = g_string_sized_new(60);
47812ac6d3dSKevin Wolf
479cfcc4c62SKevin Wolf while (table && table->name[0] != '\0') {
480cfcc4c62SKevin Wolf if (table->type == QCOW2_FEAT_TYPE_INCOMPATIBLE) {
48112ac6d3dSKevin Wolf if (mask & (1ULL << table->bit)) {
4827cdca2e2SAlberto Garcia if (features->len > 0) {
4837cdca2e2SAlberto Garcia g_string_append(features, ", ");
4847cdca2e2SAlberto Garcia }
4857cdca2e2SAlberto Garcia g_string_append_printf(features, "%.46s", table->name);
48612ac6d3dSKevin Wolf mask &= ~(1ULL << table->bit);
487cfcc4c62SKevin Wolf }
488cfcc4c62SKevin Wolf }
489cfcc4c62SKevin Wolf table++;
490cfcc4c62SKevin Wolf }
491cfcc4c62SKevin Wolf
492cfcc4c62SKevin Wolf if (mask) {
4937cdca2e2SAlberto Garcia if (features->len > 0) {
4947cdca2e2SAlberto Garcia g_string_append(features, ", ");
4957cdca2e2SAlberto Garcia }
4967cdca2e2SAlberto Garcia g_string_append_printf(features,
4977cdca2e2SAlberto Garcia "Unknown incompatible feature: %" PRIx64, mask);
498cfcc4c62SKevin Wolf }
49912ac6d3dSKevin Wolf
5007cdca2e2SAlberto Garcia error_setg(errp, "Unsupported qcow2 feature(s): %s", features->str);
501cfcc4c62SKevin Wolf }
502cfcc4c62SKevin Wolf
503c61d0004SStefan Hajnoczi /*
504bfe8043eSStefan Hajnoczi * Sets the dirty bit and flushes afterwards if necessary.
505bfe8043eSStefan Hajnoczi *
506bfe8043eSStefan Hajnoczi * The incompatible_features bit is only set if the image file header was
507bfe8043eSStefan Hajnoczi * updated successfully. Therefore it is not required to check the return
508bfe8043eSStefan Hajnoczi * value of this function.
509bfe8043eSStefan Hajnoczi */
qcow2_mark_dirty(BlockDriverState * bs)510280d3735SKevin Wolf int qcow2_mark_dirty(BlockDriverState *bs)
511bfe8043eSStefan Hajnoczi {
512ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque;
513bfe8043eSStefan Hajnoczi uint64_t val;
514bfe8043eSStefan Hajnoczi int ret;
515bfe8043eSStefan Hajnoczi
516bfe8043eSStefan Hajnoczi assert(s->qcow_version >= 3);
517bfe8043eSStefan Hajnoczi
518bfe8043eSStefan Hajnoczi if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
519bfe8043eSStefan Hajnoczi return 0; /* already dirty */
520bfe8043eSStefan Hajnoczi }
521bfe8043eSStefan Hajnoczi
522bfe8043eSStefan Hajnoczi val = cpu_to_be64(s->incompatible_features | QCOW2_INCOMPAT_DIRTY);
52386da4322SAlberto Faria ret = bdrv_pwrite_sync(bs->file,
52486da4322SAlberto Faria offsetof(QCowHeader, incompatible_features),
52532cc71deSAlberto Faria sizeof(val), &val, 0);
526bfe8043eSStefan Hajnoczi if (ret < 0) {
527bfe8043eSStefan Hajnoczi return ret;
528bfe8043eSStefan Hajnoczi }
529bfe8043eSStefan Hajnoczi
530bfe8043eSStefan Hajnoczi /* Only treat image as dirty if the header was updated successfully */
531bfe8043eSStefan Hajnoczi s->incompatible_features |= QCOW2_INCOMPAT_DIRTY;
532bfe8043eSStefan Hajnoczi return 0;
533bfe8043eSStefan Hajnoczi }
534bfe8043eSStefan Hajnoczi
535bfe8043eSStefan Hajnoczi /*
536c61d0004SStefan Hajnoczi * Clears the dirty bit and flushes before if necessary. Only call this
537c61d0004SStefan Hajnoczi * function when there are no pending requests, it does not guard against
538c61d0004SStefan Hajnoczi * concurrent requests dirtying the image.
539c61d0004SStefan Hajnoczi */
qcow2_mark_clean(BlockDriverState * bs)5400bb79c97SKevin Wolf static int GRAPH_RDLOCK qcow2_mark_clean(BlockDriverState *bs)
541c61d0004SStefan Hajnoczi {
542ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque;
543c61d0004SStefan Hajnoczi
544c61d0004SStefan Hajnoczi if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
5454c2e5f8fSKevin Wolf int ret;
5464c2e5f8fSKevin Wolf
5474c2e5f8fSKevin Wolf s->incompatible_features &= ~QCOW2_INCOMPAT_DIRTY;
5484c2e5f8fSKevin Wolf
5498b220eb7SPaolo Bonzini ret = qcow2_flush_caches(bs);
550c61d0004SStefan Hajnoczi if (ret < 0) {
551c61d0004SStefan Hajnoczi return ret;
552c61d0004SStefan Hajnoczi }
553c61d0004SStefan Hajnoczi
554c61d0004SStefan Hajnoczi return qcow2_update_header(bs);
555c61d0004SStefan Hajnoczi }
556c61d0004SStefan Hajnoczi return 0;
557c61d0004SStefan Hajnoczi }
558c61d0004SStefan Hajnoczi
55969c98726SMax Reitz /*
56069c98726SMax Reitz * Marks the image as corrupt.
56169c98726SMax Reitz */
qcow2_mark_corrupt(BlockDriverState * bs)56269c98726SMax Reitz int qcow2_mark_corrupt(BlockDriverState *bs)
56369c98726SMax Reitz {
564ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque;
56569c98726SMax Reitz
56669c98726SMax Reitz s->incompatible_features |= QCOW2_INCOMPAT_CORRUPT;
56769c98726SMax Reitz return qcow2_update_header(bs);
56869c98726SMax Reitz }
56969c98726SMax Reitz
57069c98726SMax Reitz /*
57169c98726SMax Reitz * Marks the image as consistent, i.e., unsets the corrupt bit, and flushes
57269c98726SMax Reitz * before if necessary.
57369c98726SMax Reitz */
5740bb79c97SKevin Wolf static int coroutine_fn GRAPH_RDLOCK
qcow2_mark_consistent(BlockDriverState * bs)5750bb79c97SKevin Wolf qcow2_mark_consistent(BlockDriverState *bs)
57669c98726SMax Reitz {
577ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque;
57869c98726SMax Reitz
57969c98726SMax Reitz if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
5808b220eb7SPaolo Bonzini int ret = qcow2_flush_caches(bs);
58169c98726SMax Reitz if (ret < 0) {
58269c98726SMax Reitz return ret;
58369c98726SMax Reitz }
58469c98726SMax Reitz
58569c98726SMax Reitz s->incompatible_features &= ~QCOW2_INCOMPAT_CORRUPT;
58669c98726SMax Reitz return qcow2_update_header(bs);
58769c98726SMax Reitz }
58869c98726SMax Reitz return 0;
58969c98726SMax Reitz }
59069c98726SMax Reitz
qcow2_add_check_result(BdrvCheckResult * out,const BdrvCheckResult * src,bool set_allocation_info)5918bc584feSMax Reitz static void qcow2_add_check_result(BdrvCheckResult *out,
5928bc584feSMax Reitz const BdrvCheckResult *src,
5938bc584feSMax Reitz bool set_allocation_info)
5948bc584feSMax Reitz {
5958bc584feSMax Reitz out->corruptions += src->corruptions;
5968bc584feSMax Reitz out->leaks += src->leaks;
5978bc584feSMax Reitz out->check_errors += src->check_errors;
5988bc584feSMax Reitz out->corruptions_fixed += src->corruptions_fixed;
5998bc584feSMax Reitz out->leaks_fixed += src->leaks_fixed;
6008bc584feSMax Reitz
6018bc584feSMax Reitz if (set_allocation_info) {
6028bc584feSMax Reitz out->image_end_offset = src->image_end_offset;
6038bc584feSMax Reitz out->bfi = src->bfi;
6048bc584feSMax Reitz }
6058bc584feSMax Reitz }
6068bc584feSMax Reitz
607b9b10c35SKevin Wolf static int coroutine_fn GRAPH_RDLOCK
qcow2_co_check_locked(BlockDriverState * bs,BdrvCheckResult * result,BdrvCheckMode fix)608b9b10c35SKevin Wolf qcow2_co_check_locked(BlockDriverState *bs, BdrvCheckResult *result,
609acbe5982SStefan Hajnoczi BdrvCheckMode fix)
610acbe5982SStefan Hajnoczi {
6118bc584feSMax Reitz BdrvCheckResult snapshot_res = {};
6128bc584feSMax Reitz BdrvCheckResult refcount_res = {};
6138bc584feSMax Reitz int ret;
6148bc584feSMax Reitz
6158bc584feSMax Reitz memset(result, 0, sizeof(*result));
6168bc584feSMax Reitz
6178bc584feSMax Reitz ret = qcow2_check_read_snapshot_table(bs, &snapshot_res, fix);
6188bc584feSMax Reitz if (ret < 0) {
619fe446b5dSMax Reitz qcow2_add_check_result(result, &snapshot_res, false);
6208bc584feSMax Reitz return ret;
6218bc584feSMax Reitz }
6228bc584feSMax Reitz
6238bc584feSMax Reitz ret = qcow2_check_refcounts(bs, &refcount_res, fix);
6248bc584feSMax Reitz qcow2_add_check_result(result, &refcount_res, true);
625acbe5982SStefan Hajnoczi if (ret < 0) {
626fe446b5dSMax Reitz qcow2_add_check_result(result, &snapshot_res, false);
627fe446b5dSMax Reitz return ret;
628fe446b5dSMax Reitz }
629fe446b5dSMax Reitz
630fe446b5dSMax Reitz ret = qcow2_check_fix_snapshot_table(bs, &snapshot_res, fix);
631fe446b5dSMax Reitz qcow2_add_check_result(result, &snapshot_res, false);
632fe446b5dSMax Reitz if (ret < 0) {
633acbe5982SStefan Hajnoczi return ret;
634acbe5982SStefan Hajnoczi }
635acbe5982SStefan Hajnoczi
636acbe5982SStefan Hajnoczi if (fix && result->check_errors == 0 && result->corruptions == 0) {
63724530f3eSMax Reitz ret = qcow2_mark_clean(bs);
63824530f3eSMax Reitz if (ret < 0) {
63924530f3eSMax Reitz return ret;
64024530f3eSMax Reitz }
64124530f3eSMax Reitz return qcow2_mark_consistent(bs);
642acbe5982SStefan Hajnoczi }
643acbe5982SStefan Hajnoczi return ret;
644acbe5982SStefan Hajnoczi }
645acbe5982SStefan Hajnoczi
646b9b10c35SKevin Wolf static int coroutine_fn GRAPH_RDLOCK
qcow2_co_check(BlockDriverState * bs,BdrvCheckResult * result,BdrvCheckMode fix)647b9b10c35SKevin Wolf qcow2_co_check(BlockDriverState *bs, BdrvCheckResult *result,
6482fd61638SPaolo Bonzini BdrvCheckMode fix)
6492fd61638SPaolo Bonzini {
6502fd61638SPaolo Bonzini BDRVQcow2State *s = bs->opaque;
6512fd61638SPaolo Bonzini int ret;
6522fd61638SPaolo Bonzini
6532fd61638SPaolo Bonzini qemu_co_mutex_lock(&s->lock);
6542fd61638SPaolo Bonzini ret = qcow2_co_check_locked(bs, result, fix);
6552fd61638SPaolo Bonzini qemu_co_mutex_unlock(&s->lock);
6562fd61638SPaolo Bonzini return ret;
6572fd61638SPaolo Bonzini }
6582fd61638SPaolo Bonzini
qcow2_validate_table(BlockDriverState * bs,uint64_t offset,uint64_t entries,size_t entry_len,int64_t max_size_bytes,const char * table_name,Error ** errp)6590cf0e598SAlberto Garcia int qcow2_validate_table(BlockDriverState *bs, uint64_t offset,
6600cf0e598SAlberto Garcia uint64_t entries, size_t entry_len,
6610cf0e598SAlberto Garcia int64_t max_size_bytes, const char *table_name,
6620cf0e598SAlberto Garcia Error **errp)
6638c7de283SKevin Wolf {
664ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque;
6650cf0e598SAlberto Garcia
6660cf0e598SAlberto Garcia if (entries > max_size_bytes / entry_len) {
6670cf0e598SAlberto Garcia error_setg(errp, "%s too large", table_name);
6680cf0e598SAlberto Garcia return -EFBIG;
6690cf0e598SAlberto Garcia }
6708c7de283SKevin Wolf
6718c7de283SKevin Wolf /* Use signed INT64_MAX as the maximum even for uint64_t header fields,
6728c7de283SKevin Wolf * because values will be passed to qemu functions taking int64_t. */
6730cf0e598SAlberto Garcia if ((INT64_MAX - entries * entry_len < offset) ||
6740cf0e598SAlberto Garcia (offset_into_cluster(s, offset) != 0)) {
6750cf0e598SAlberto Garcia error_setg(errp, "%s offset invalid", table_name);
6768c7de283SKevin Wolf return -EINVAL;
6778c7de283SKevin Wolf }
6788c7de283SKevin Wolf
6798c7de283SKevin Wolf return 0;
6808c7de283SKevin Wolf }
6818c7de283SKevin Wolf
6828a2ce0bcSAlberto Garcia static const char *const mutable_opts[] = {
6838a2ce0bcSAlberto Garcia QCOW2_OPT_LAZY_REFCOUNTS,
6848a2ce0bcSAlberto Garcia QCOW2_OPT_DISCARD_REQUEST,
6858a2ce0bcSAlberto Garcia QCOW2_OPT_DISCARD_SNAPSHOT,
6868a2ce0bcSAlberto Garcia QCOW2_OPT_DISCARD_OTHER,
68742a2890aSJean-Louis Dupond QCOW2_OPT_DISCARD_NO_UNREF,
6888a2ce0bcSAlberto Garcia QCOW2_OPT_OVERLAP,
6898a2ce0bcSAlberto Garcia QCOW2_OPT_OVERLAP_TEMPLATE,
6908a2ce0bcSAlberto Garcia QCOW2_OPT_OVERLAP_MAIN_HEADER,
6918a2ce0bcSAlberto Garcia QCOW2_OPT_OVERLAP_ACTIVE_L1,
6928a2ce0bcSAlberto Garcia QCOW2_OPT_OVERLAP_ACTIVE_L2,
6938a2ce0bcSAlberto Garcia QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
6948a2ce0bcSAlberto Garcia QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
6958a2ce0bcSAlberto Garcia QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
6968a2ce0bcSAlberto Garcia QCOW2_OPT_OVERLAP_INACTIVE_L1,
6978a2ce0bcSAlberto Garcia QCOW2_OPT_OVERLAP_INACTIVE_L2,
6988a2ce0bcSAlberto Garcia QCOW2_OPT_OVERLAP_BITMAP_DIRECTORY,
6998a2ce0bcSAlberto Garcia QCOW2_OPT_CACHE_SIZE,
7008a2ce0bcSAlberto Garcia QCOW2_OPT_L2_CACHE_SIZE,
7018a2ce0bcSAlberto Garcia QCOW2_OPT_L2_CACHE_ENTRY_SIZE,
7028a2ce0bcSAlberto Garcia QCOW2_OPT_REFCOUNT_CACHE_SIZE,
7038a2ce0bcSAlberto Garcia QCOW2_OPT_CACHE_CLEAN_INTERVAL,
7048a2ce0bcSAlberto Garcia NULL
7058a2ce0bcSAlberto Garcia };
7068a2ce0bcSAlberto Garcia
70774c4510aSKevin Wolf static QemuOptsList qcow2_runtime_opts = {
70874c4510aSKevin Wolf .name = "qcow2",
70974c4510aSKevin Wolf .head = QTAILQ_HEAD_INITIALIZER(qcow2_runtime_opts.head),
71074c4510aSKevin Wolf .desc = {
71174c4510aSKevin Wolf {
71264aa99d3SKevin Wolf .name = QCOW2_OPT_LAZY_REFCOUNTS,
71374c4510aSKevin Wolf .type = QEMU_OPT_BOOL,
71474c4510aSKevin Wolf .help = "Postpone refcount updates",
71574c4510aSKevin Wolf },
71667af674eSKevin Wolf {
71767af674eSKevin Wolf .name = QCOW2_OPT_DISCARD_REQUEST,
71867af674eSKevin Wolf .type = QEMU_OPT_BOOL,
71967af674eSKevin Wolf .help = "Pass guest discard requests to the layer below",
72067af674eSKevin Wolf },
72167af674eSKevin Wolf {
72267af674eSKevin Wolf .name = QCOW2_OPT_DISCARD_SNAPSHOT,
72367af674eSKevin Wolf .type = QEMU_OPT_BOOL,
72467af674eSKevin Wolf .help = "Generate discard requests when snapshot related space "
72567af674eSKevin Wolf "is freed",
72667af674eSKevin Wolf },
72767af674eSKevin Wolf {
72867af674eSKevin Wolf .name = QCOW2_OPT_DISCARD_OTHER,
72967af674eSKevin Wolf .type = QEMU_OPT_BOOL,
73067af674eSKevin Wolf .help = "Generate discard requests when other clusters are freed",
73167af674eSKevin Wolf },
73205de7e86SMax Reitz {
73342a2890aSJean-Louis Dupond .name = QCOW2_OPT_DISCARD_NO_UNREF,
73442a2890aSJean-Louis Dupond .type = QEMU_OPT_BOOL,
73542a2890aSJean-Louis Dupond .help = "Do not unreference discarded clusters",
73642a2890aSJean-Louis Dupond },
73742a2890aSJean-Louis Dupond {
73805de7e86SMax Reitz .name = QCOW2_OPT_OVERLAP,
73905de7e86SMax Reitz .type = QEMU_OPT_STRING,
74005de7e86SMax Reitz .help = "Selects which overlap checks to perform from a range of "
74105de7e86SMax Reitz "templates (none, constant, cached, all)",
74205de7e86SMax Reitz },
74305de7e86SMax Reitz {
744ee42b5ceSMax Reitz .name = QCOW2_OPT_OVERLAP_TEMPLATE,
745ee42b5ceSMax Reitz .type = QEMU_OPT_STRING,
746ee42b5ceSMax Reitz .help = "Selects which overlap checks to perform from a range of "
747ee42b5ceSMax Reitz "templates (none, constant, cached, all)",
748ee42b5ceSMax Reitz },
749ee42b5ceSMax Reitz {
75005de7e86SMax Reitz .name = QCOW2_OPT_OVERLAP_MAIN_HEADER,
75105de7e86SMax Reitz .type = QEMU_OPT_BOOL,
75205de7e86SMax Reitz .help = "Check for unintended writes into the main qcow2 header",
75305de7e86SMax Reitz },
75405de7e86SMax Reitz {
75505de7e86SMax Reitz .name = QCOW2_OPT_OVERLAP_ACTIVE_L1,
75605de7e86SMax Reitz .type = QEMU_OPT_BOOL,
75705de7e86SMax Reitz .help = "Check for unintended writes into the active L1 table",
75805de7e86SMax Reitz },
75905de7e86SMax Reitz {
76005de7e86SMax Reitz .name = QCOW2_OPT_OVERLAP_ACTIVE_L2,
76105de7e86SMax Reitz .type = QEMU_OPT_BOOL,
76205de7e86SMax Reitz .help = "Check for unintended writes into an active L2 table",
76305de7e86SMax Reitz },
76405de7e86SMax Reitz {
76505de7e86SMax Reitz .name = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
76605de7e86SMax Reitz .type = QEMU_OPT_BOOL,
76705de7e86SMax Reitz .help = "Check for unintended writes into the refcount table",
76805de7e86SMax Reitz },
76905de7e86SMax Reitz {
77005de7e86SMax Reitz .name = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
77105de7e86SMax Reitz .type = QEMU_OPT_BOOL,
77205de7e86SMax Reitz .help = "Check for unintended writes into a refcount block",
77305de7e86SMax Reitz },
77405de7e86SMax Reitz {
77505de7e86SMax Reitz .name = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
77605de7e86SMax Reitz .type = QEMU_OPT_BOOL,
77705de7e86SMax Reitz .help = "Check for unintended writes into the snapshot table",
77805de7e86SMax Reitz },
77905de7e86SMax Reitz {
78005de7e86SMax Reitz .name = QCOW2_OPT_OVERLAP_INACTIVE_L1,
78105de7e86SMax Reitz .type = QEMU_OPT_BOOL,
78205de7e86SMax Reitz .help = "Check for unintended writes into an inactive L1 table",
78305de7e86SMax Reitz },
78405de7e86SMax Reitz {
78505de7e86SMax Reitz .name = QCOW2_OPT_OVERLAP_INACTIVE_L2,
78605de7e86SMax Reitz .type = QEMU_OPT_BOOL,
78705de7e86SMax Reitz .help = "Check for unintended writes into an inactive L2 table",
78805de7e86SMax Reitz },
7896c1c8d5dSMax Reitz {
7900e4e4318SVladimir Sementsov-Ogievskiy .name = QCOW2_OPT_OVERLAP_BITMAP_DIRECTORY,
7910e4e4318SVladimir Sementsov-Ogievskiy .type = QEMU_OPT_BOOL,
7920e4e4318SVladimir Sementsov-Ogievskiy .help = "Check for unintended writes into the bitmap directory",
7930e4e4318SVladimir Sementsov-Ogievskiy },
7940e4e4318SVladimir Sementsov-Ogievskiy {
7956c1c8d5dSMax Reitz .name = QCOW2_OPT_CACHE_SIZE,
7966c1c8d5dSMax Reitz .type = QEMU_OPT_SIZE,
7976c1c8d5dSMax Reitz .help = "Maximum combined metadata (L2 tables and refcount blocks) "
7986c1c8d5dSMax Reitz "cache size",
7996c1c8d5dSMax Reitz },
8006c1c8d5dSMax Reitz {
8016c1c8d5dSMax Reitz .name = QCOW2_OPT_L2_CACHE_SIZE,
8026c1c8d5dSMax Reitz .type = QEMU_OPT_SIZE,
8036c1c8d5dSMax Reitz .help = "Maximum L2 table cache size",
8046c1c8d5dSMax Reitz },
8056c1c8d5dSMax Reitz {
8061221fe6fSAlberto Garcia .name = QCOW2_OPT_L2_CACHE_ENTRY_SIZE,
8071221fe6fSAlberto Garcia .type = QEMU_OPT_SIZE,
8081221fe6fSAlberto Garcia .help = "Size of each entry in the L2 cache",
8091221fe6fSAlberto Garcia },
8101221fe6fSAlberto Garcia {
8116c1c8d5dSMax Reitz .name = QCOW2_OPT_REFCOUNT_CACHE_SIZE,
8126c1c8d5dSMax Reitz .type = QEMU_OPT_SIZE,
8136c1c8d5dSMax Reitz .help = "Maximum refcount block cache size",
8146c1c8d5dSMax Reitz },
815279621c0SAlberto Garcia {
816279621c0SAlberto Garcia .name = QCOW2_OPT_CACHE_CLEAN_INTERVAL,
817279621c0SAlberto Garcia .type = QEMU_OPT_NUMBER,
818279621c0SAlberto Garcia .help = "Clean unused cache entries after this time (in seconds)",
819279621c0SAlberto Garcia },
8204652b8f3SDaniel P. Berrange BLOCK_CRYPTO_OPT_DEF_KEY_SECRET("encrypt.",
8214652b8f3SDaniel P. Berrange "ID of secret providing qcow2 AES key or LUKS passphrase"),
82274c4510aSKevin Wolf { /* end of list */ }
82374c4510aSKevin Wolf },
82474c4510aSKevin Wolf };
82574c4510aSKevin Wolf
8264092e99dSMax Reitz static const char *overlap_bool_option_names[QCOW2_OL_MAX_BITNR] = {
8274092e99dSMax Reitz [QCOW2_OL_MAIN_HEADER_BITNR] = QCOW2_OPT_OVERLAP_MAIN_HEADER,
8284092e99dSMax Reitz [QCOW2_OL_ACTIVE_L1_BITNR] = QCOW2_OPT_OVERLAP_ACTIVE_L1,
8294092e99dSMax Reitz [QCOW2_OL_ACTIVE_L2_BITNR] = QCOW2_OPT_OVERLAP_ACTIVE_L2,
8304092e99dSMax Reitz [QCOW2_OL_REFCOUNT_TABLE_BITNR] = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
8314092e99dSMax Reitz [QCOW2_OL_REFCOUNT_BLOCK_BITNR] = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
8324092e99dSMax Reitz [QCOW2_OL_SNAPSHOT_TABLE_BITNR] = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
8334092e99dSMax Reitz [QCOW2_OL_INACTIVE_L1_BITNR] = QCOW2_OPT_OVERLAP_INACTIVE_L1,
8344092e99dSMax Reitz [QCOW2_OL_INACTIVE_L2_BITNR] = QCOW2_OPT_OVERLAP_INACTIVE_L2,
8350e4e4318SVladimir Sementsov-Ogievskiy [QCOW2_OL_BITMAP_DIRECTORY_BITNR] = QCOW2_OPT_OVERLAP_BITMAP_DIRECTORY,
8364092e99dSMax Reitz };
8374092e99dSMax Reitz
cache_clean_timer_cb(void * opaque)838279621c0SAlberto Garcia static void cache_clean_timer_cb(void *opaque)
839279621c0SAlberto Garcia {
840279621c0SAlberto Garcia BlockDriverState *bs = opaque;
841ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque;
842b2f68bffSAlberto Garcia qcow2_cache_clean_unused(s->l2_table_cache);
843b2f68bffSAlberto Garcia qcow2_cache_clean_unused(s->refcount_block_cache);
844279621c0SAlberto Garcia timer_mod(s->cache_clean_timer, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) +
845279621c0SAlberto Garcia (int64_t) s->cache_clean_interval * 1000);
846279621c0SAlberto Garcia }
847279621c0SAlberto Garcia
cache_clean_timer_init(BlockDriverState * bs,AioContext * context)848279621c0SAlberto Garcia static void cache_clean_timer_init(BlockDriverState *bs, AioContext *context)
849279621c0SAlberto Garcia {
850ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque;
851279621c0SAlberto Garcia if (s->cache_clean_interval > 0) {
852ad0ce642SPavel Dovgalyuk s->cache_clean_timer =
853ad0ce642SPavel Dovgalyuk aio_timer_new_with_attrs(context, QEMU_CLOCK_VIRTUAL,
854ad0ce642SPavel Dovgalyuk SCALE_MS, QEMU_TIMER_ATTR_EXTERNAL,
855ad0ce642SPavel Dovgalyuk cache_clean_timer_cb, bs);
856279621c0SAlberto Garcia timer_mod(s->cache_clean_timer, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) +
857279621c0SAlberto Garcia (int64_t) s->cache_clean_interval * 1000);
858279621c0SAlberto Garcia }
859279621c0SAlberto Garcia }
860279621c0SAlberto Garcia
cache_clean_timer_del(BlockDriverState * bs)861279621c0SAlberto Garcia static void cache_clean_timer_del(BlockDriverState *bs)
862279621c0SAlberto Garcia {
863ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque;
864279621c0SAlberto Garcia if (s->cache_clean_timer) {
865279621c0SAlberto Garcia timer_free(s->cache_clean_timer);
866279621c0SAlberto Garcia s->cache_clean_timer = NULL;
867279621c0SAlberto Garcia }
868279621c0SAlberto Garcia }
869279621c0SAlberto Garcia
qcow2_detach_aio_context(BlockDriverState * bs)870279621c0SAlberto Garcia static void qcow2_detach_aio_context(BlockDriverState *bs)
871279621c0SAlberto Garcia {
872279621c0SAlberto Garcia cache_clean_timer_del(bs);
873279621c0SAlberto Garcia }
874279621c0SAlberto Garcia
qcow2_attach_aio_context(BlockDriverState * bs,AioContext * new_context)875279621c0SAlberto Garcia static void qcow2_attach_aio_context(BlockDriverState *bs,
876279621c0SAlberto Garcia AioContext *new_context)
877279621c0SAlberto Garcia {
878279621c0SAlberto Garcia cache_clean_timer_init(bs, new_context);
879279621c0SAlberto Garcia }
880279621c0SAlberto Garcia
read_cache_sizes(BlockDriverState * bs,QemuOpts * opts,uint64_t * l2_cache_size,uint64_t * l2_cache_entry_size,uint64_t * refcount_cache_size,Error ** errp)881772c4cadSVladimir Sementsov-Ogievskiy static bool read_cache_sizes(BlockDriverState *bs, QemuOpts *opts,
882bc85ef26SMax Reitz uint64_t *l2_cache_size,
8831221fe6fSAlberto Garcia uint64_t *l2_cache_entry_size,
8846c1c8d5dSMax Reitz uint64_t *refcount_cache_size, Error **errp)
8856c1c8d5dSMax Reitz {
886ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque;
887b749562dSLeonid Bloch uint64_t combined_cache_size, l2_cache_max_setting;
8886c1c8d5dSMax Reitz bool l2_cache_size_set, refcount_cache_size_set, combined_cache_size_set;
889af39bd0dSAlberto Garcia bool l2_cache_entry_size_set;
8907af5eea9SAlberto Garcia int min_refcount_cache = MIN_REFCOUNT_CACHE_SIZE * s->cluster_size;
891b749562dSLeonid Bloch uint64_t virtual_disk_size = bs->total_sectors * BDRV_SECTOR_SIZE;
892b70d0820SAlberto Garcia uint64_t max_l2_entries = DIV_ROUND_UP(virtual_disk_size, s->cluster_size);
893b70d0820SAlberto Garcia /* An L2 table is always one cluster in size so the max cache size
894b70d0820SAlberto Garcia * should be a multiple of the cluster size. */
895c8fd8554SAlberto Garcia uint64_t max_l2_cache = ROUND_UP(max_l2_entries * l2_entry_size(s),
896b70d0820SAlberto Garcia s->cluster_size);
8976c1c8d5dSMax Reitz
8986c1c8d5dSMax Reitz combined_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_CACHE_SIZE);
8996c1c8d5dSMax Reitz l2_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_L2_CACHE_SIZE);
9006c1c8d5dSMax Reitz refcount_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
901af39bd0dSAlberto Garcia l2_cache_entry_size_set = qemu_opt_get(opts, QCOW2_OPT_L2_CACHE_ENTRY_SIZE);
9026c1c8d5dSMax Reitz
9036c1c8d5dSMax Reitz combined_cache_size = qemu_opt_get_size(opts, QCOW2_OPT_CACHE_SIZE, 0);
904b749562dSLeonid Bloch l2_cache_max_setting = qemu_opt_get_size(opts, QCOW2_OPT_L2_CACHE_SIZE,
905b749562dSLeonid Bloch DEFAULT_L2_CACHE_MAX_SIZE);
9066c1c8d5dSMax Reitz *refcount_cache_size = qemu_opt_get_size(opts,
9076c1c8d5dSMax Reitz QCOW2_OPT_REFCOUNT_CACHE_SIZE, 0);
9086c1c8d5dSMax Reitz
9091221fe6fSAlberto Garcia *l2_cache_entry_size = qemu_opt_get_size(
9101221fe6fSAlberto Garcia opts, QCOW2_OPT_L2_CACHE_ENTRY_SIZE, s->cluster_size);
9111221fe6fSAlberto Garcia
912b749562dSLeonid Bloch *l2_cache_size = MIN(max_l2_cache, l2_cache_max_setting);
913b749562dSLeonid Bloch
9146c1c8d5dSMax Reitz if (combined_cache_size_set) {
9156c1c8d5dSMax Reitz if (l2_cache_size_set && refcount_cache_size_set) {
9166c1c8d5dSMax Reitz error_setg(errp, QCOW2_OPT_CACHE_SIZE ", " QCOW2_OPT_L2_CACHE_SIZE
9176c1c8d5dSMax Reitz " and " QCOW2_OPT_REFCOUNT_CACHE_SIZE " may not be set "
918308999e9SLeonid Bloch "at the same time");
919772c4cadSVladimir Sementsov-Ogievskiy return false;
920b749562dSLeonid Bloch } else if (l2_cache_size_set &&
921b749562dSLeonid Bloch (l2_cache_max_setting > combined_cache_size)) {
9226c1c8d5dSMax Reitz error_setg(errp, QCOW2_OPT_L2_CACHE_SIZE " may not exceed "
9236c1c8d5dSMax Reitz QCOW2_OPT_CACHE_SIZE);
924772c4cadSVladimir Sementsov-Ogievskiy return false;
9256c1c8d5dSMax Reitz } else if (*refcount_cache_size > combined_cache_size) {
9266c1c8d5dSMax Reitz error_setg(errp, QCOW2_OPT_REFCOUNT_CACHE_SIZE " may not exceed "
9276c1c8d5dSMax Reitz QCOW2_OPT_CACHE_SIZE);
928772c4cadSVladimir Sementsov-Ogievskiy return false;
9296c1c8d5dSMax Reitz }
9306c1c8d5dSMax Reitz
9316c1c8d5dSMax Reitz if (l2_cache_size_set) {
9326c1c8d5dSMax Reitz *refcount_cache_size = combined_cache_size - *l2_cache_size;
9336c1c8d5dSMax Reitz } else if (refcount_cache_size_set) {
9346c1c8d5dSMax Reitz *l2_cache_size = combined_cache_size - *refcount_cache_size;
9356c1c8d5dSMax Reitz } else {
93652253998SAlberto Garcia /* Assign as much memory as possible to the L2 cache, and
93752253998SAlberto Garcia * use the remainder for the refcount cache */
93852253998SAlberto Garcia if (combined_cache_size >= max_l2_cache + min_refcount_cache) {
93952253998SAlberto Garcia *l2_cache_size = max_l2_cache;
94052253998SAlberto Garcia *refcount_cache_size = combined_cache_size - *l2_cache_size;
94152253998SAlberto Garcia } else {
94252253998SAlberto Garcia *refcount_cache_size =
94352253998SAlberto Garcia MIN(combined_cache_size, min_refcount_cache);
9446c1c8d5dSMax Reitz *l2_cache_size = combined_cache_size - *refcount_cache_size;
9456c1c8d5dSMax Reitz }
94652253998SAlberto Garcia }
9476c1c8d5dSMax Reitz }
948af39bd0dSAlberto Garcia
949af39bd0dSAlberto Garcia /*
950af39bd0dSAlberto Garcia * If the L2 cache is not enough to cover the whole disk then
951af39bd0dSAlberto Garcia * default to 4KB entries. Smaller entries reduce the cost of
952af39bd0dSAlberto Garcia * loads and evictions and increase I/O performance.
953af39bd0dSAlberto Garcia */
954af39bd0dSAlberto Garcia if (*l2_cache_size < max_l2_cache && !l2_cache_entry_size_set) {
955af39bd0dSAlberto Garcia *l2_cache_entry_size = MIN(s->cluster_size, 4096);
956af39bd0dSAlberto Garcia }
957af39bd0dSAlberto Garcia
958657ada52SLeonid Bloch /* l2_cache_size and refcount_cache_size are ensured to have at least
959657ada52SLeonid Bloch * their minimum values in qcow2_update_options_prepare() */
9601221fe6fSAlberto Garcia
9611221fe6fSAlberto Garcia if (*l2_cache_entry_size < (1 << MIN_CLUSTER_BITS) ||
9621221fe6fSAlberto Garcia *l2_cache_entry_size > s->cluster_size ||
9631221fe6fSAlberto Garcia !is_power_of_2(*l2_cache_entry_size)) {
9641221fe6fSAlberto Garcia error_setg(errp, "L2 cache entry size must be a power of two "
9651221fe6fSAlberto Garcia "between %d and the cluster size (%d)",
9661221fe6fSAlberto Garcia 1 << MIN_CLUSTER_BITS, s->cluster_size);
967772c4cadSVladimir Sementsov-Ogievskiy return false;
9681221fe6fSAlberto Garcia }
969772c4cadSVladimir Sementsov-Ogievskiy
970772c4cadSVladimir Sementsov-Ogievskiy return true;
9716c1c8d5dSMax Reitz }
9726c1c8d5dSMax Reitz
973ee55b173SKevin Wolf typedef struct Qcow2ReopenState {
974ee55b173SKevin Wolf Qcow2Cache *l2_table_cache;
975ee55b173SKevin Wolf Qcow2Cache *refcount_block_cache;
9763c2e511aSAlberto Garcia int l2_slice_size; /* Number of entries in a slice of the L2 table */
977ee55b173SKevin Wolf bool use_lazy_refcounts;
978ee55b173SKevin Wolf int overlap_check;
979ee55b173SKevin Wolf bool discard_passthrough[QCOW2_DISCARD_MAX];
98042a2890aSJean-Louis Dupond bool discard_no_unref;
981ee55b173SKevin Wolf uint64_t cache_clean_interval;
982b25b387fSDaniel P. Berrange QCryptoBlockOpenOptions *crypto_opts; /* Disk encryption runtime options */
983ee55b173SKevin Wolf } Qcow2ReopenState;
984ee55b173SKevin Wolf
9850bb79c97SKevin Wolf static int GRAPH_RDLOCK
qcow2_update_options_prepare(BlockDriverState * bs,Qcow2ReopenState * r,QDict * options,int flags,Error ** errp)9860bb79c97SKevin Wolf qcow2_update_options_prepare(BlockDriverState *bs, Qcow2ReopenState *r,
9870bb79c97SKevin Wolf QDict *options, int flags, Error **errp)
9884c75d1a1SKevin Wolf {
9894c75d1a1SKevin Wolf BDRVQcow2State *s = bs->opaque;
99094edf3fbSKevin Wolf QemuOpts *opts = NULL;
9914c75d1a1SKevin Wolf const char *opt_overlap_check, *opt_overlap_check_template;
9924c75d1a1SKevin Wolf int overlap_check_template = 0;
9931221fe6fSAlberto Garcia uint64_t l2_cache_size, l2_cache_entry_size, refcount_cache_size;
9944c75d1a1SKevin Wolf int i;
995b25b387fSDaniel P. Berrange const char *encryptfmt;
996b25b387fSDaniel P. Berrange QDict *encryptopts = NULL;
9974c75d1a1SKevin Wolf int ret;
9984c75d1a1SKevin Wolf
999b25b387fSDaniel P. Berrange qdict_extract_subqdict(options, &encryptopts, "encrypt.");
1000b25b387fSDaniel P. Berrange encryptfmt = qdict_get_try_str(encryptopts, "format");
1001b25b387fSDaniel P. Berrange
100294edf3fbSKevin Wolf opts = qemu_opts_create(&qcow2_runtime_opts, NULL, 0, &error_abort);
1003af175e85SMarkus Armbruster if (!qemu_opts_absorb_qdict(opts, options, errp)) {
100494edf3fbSKevin Wolf ret = -EINVAL;
100594edf3fbSKevin Wolf goto fail;
100694edf3fbSKevin Wolf }
100794edf3fbSKevin Wolf
100894edf3fbSKevin Wolf /* get L2 table/refcount block cache size from command line options */
1009772c4cadSVladimir Sementsov-Ogievskiy if (!read_cache_sizes(bs, opts, &l2_cache_size, &l2_cache_entry_size,
1010772c4cadSVladimir Sementsov-Ogievskiy &refcount_cache_size, errp)) {
101194edf3fbSKevin Wolf ret = -EINVAL;
101294edf3fbSKevin Wolf goto fail;
101394edf3fbSKevin Wolf }
101494edf3fbSKevin Wolf
10151221fe6fSAlberto Garcia l2_cache_size /= l2_cache_entry_size;
101694edf3fbSKevin Wolf if (l2_cache_size < MIN_L2_CACHE_SIZE) {
101794edf3fbSKevin Wolf l2_cache_size = MIN_L2_CACHE_SIZE;
101894edf3fbSKevin Wolf }
101994edf3fbSKevin Wolf if (l2_cache_size > INT_MAX) {
102094edf3fbSKevin Wolf error_setg(errp, "L2 cache size too big");
102194edf3fbSKevin Wolf ret = -EINVAL;
102294edf3fbSKevin Wolf goto fail;
102394edf3fbSKevin Wolf }
102494edf3fbSKevin Wolf
102594edf3fbSKevin Wolf refcount_cache_size /= s->cluster_size;
102694edf3fbSKevin Wolf if (refcount_cache_size < MIN_REFCOUNT_CACHE_SIZE) {
102794edf3fbSKevin Wolf refcount_cache_size = MIN_REFCOUNT_CACHE_SIZE;
102894edf3fbSKevin Wolf }
102994edf3fbSKevin Wolf if (refcount_cache_size > INT_MAX) {
103094edf3fbSKevin Wolf error_setg(errp, "Refcount cache size too big");
103194edf3fbSKevin Wolf ret = -EINVAL;
103294edf3fbSKevin Wolf goto fail;
103394edf3fbSKevin Wolf }
103494edf3fbSKevin Wolf
10355b0959a7SKevin Wolf /* alloc new L2 table/refcount block cache, flush old one */
10365b0959a7SKevin Wolf if (s->l2_table_cache) {
10375b0959a7SKevin Wolf ret = qcow2_cache_flush(bs, s->l2_table_cache);
10385b0959a7SKevin Wolf if (ret) {
10395b0959a7SKevin Wolf error_setg_errno(errp, -ret, "Failed to flush the L2 table cache");
10405b0959a7SKevin Wolf goto fail;
10415b0959a7SKevin Wolf }
10425b0959a7SKevin Wolf }
10435b0959a7SKevin Wolf
10445b0959a7SKevin Wolf if (s->refcount_block_cache) {
10455b0959a7SKevin Wolf ret = qcow2_cache_flush(bs, s->refcount_block_cache);
10465b0959a7SKevin Wolf if (ret) {
10475b0959a7SKevin Wolf error_setg_errno(errp, -ret,
10485b0959a7SKevin Wolf "Failed to flush the refcount block cache");
10495b0959a7SKevin Wolf goto fail;
10505b0959a7SKevin Wolf }
10515b0959a7SKevin Wolf }
10525b0959a7SKevin Wolf
1053c8fd8554SAlberto Garcia r->l2_slice_size = l2_cache_entry_size / l2_entry_size(s);
10541221fe6fSAlberto Garcia r->l2_table_cache = qcow2_cache_create(bs, l2_cache_size,
10551221fe6fSAlberto Garcia l2_cache_entry_size);
10561221fe6fSAlberto Garcia r->refcount_block_cache = qcow2_cache_create(bs, refcount_cache_size,
10571221fe6fSAlberto Garcia s->cluster_size);
1058ee55b173SKevin Wolf if (r->l2_table_cache == NULL || r->refcount_block_cache == NULL) {
105994edf3fbSKevin Wolf error_setg(errp, "Could not allocate metadata caches");
106094edf3fbSKevin Wolf ret = -ENOMEM;
106194edf3fbSKevin Wolf goto fail;
106294edf3fbSKevin Wolf }
106394edf3fbSKevin Wolf
106494edf3fbSKevin Wolf /* New interval for cache cleanup timer */
1065ee55b173SKevin Wolf r->cache_clean_interval =
10665b0959a7SKevin Wolf qemu_opt_get_number(opts, QCOW2_OPT_CACHE_CLEAN_INTERVAL,
1067e957b50bSLeonid Bloch DEFAULT_CACHE_CLEAN_INTERVAL);
106891203f08SAlberto Garcia #ifndef CONFIG_LINUX
106991203f08SAlberto Garcia if (r->cache_clean_interval != 0) {
107091203f08SAlberto Garcia error_setg(errp, QCOW2_OPT_CACHE_CLEAN_INTERVAL
107191203f08SAlberto Garcia " not supported on this host");
107291203f08SAlberto Garcia ret = -EINVAL;
107391203f08SAlberto Garcia goto fail;
107491203f08SAlberto Garcia }
107591203f08SAlberto Garcia #endif
1076ee55b173SKevin Wolf if (r->cache_clean_interval > UINT_MAX) {
107794edf3fbSKevin Wolf error_setg(errp, "Cache clean interval too big");
107894edf3fbSKevin Wolf ret = -EINVAL;
107994edf3fbSKevin Wolf goto fail;
108094edf3fbSKevin Wolf }
108194edf3fbSKevin Wolf
10825b0959a7SKevin Wolf /* lazy-refcounts; flush if going from enabled to disabled */
1083ee55b173SKevin Wolf r->use_lazy_refcounts = qemu_opt_get_bool(opts, QCOW2_OPT_LAZY_REFCOUNTS,
10844c75d1a1SKevin Wolf (s->compatible_features & QCOW2_COMPAT_LAZY_REFCOUNTS));
1085ee55b173SKevin Wolf if (r->use_lazy_refcounts && s->qcow_version < 3) {
1086007dbc39SKevin Wolf error_setg(errp, "Lazy refcounts require a qcow2 image with at least "
1087007dbc39SKevin Wolf "qemu 1.1 compatibility level");
1088007dbc39SKevin Wolf ret = -EINVAL;
1089007dbc39SKevin Wolf goto fail;
1090007dbc39SKevin Wolf }
10914c75d1a1SKevin Wolf
10925b0959a7SKevin Wolf if (s->use_lazy_refcounts && !r->use_lazy_refcounts) {
10935b0959a7SKevin Wolf ret = qcow2_mark_clean(bs);
10945b0959a7SKevin Wolf if (ret < 0) {
10955b0959a7SKevin Wolf error_setg_errno(errp, -ret, "Failed to disable lazy refcounts");
10965b0959a7SKevin Wolf goto fail;
10975b0959a7SKevin Wolf }
10985b0959a7SKevin Wolf }
10995b0959a7SKevin Wolf
1100007dbc39SKevin Wolf /* Overlap check options */
11014c75d1a1SKevin Wolf opt_overlap_check = qemu_opt_get(opts, QCOW2_OPT_OVERLAP);
11024c75d1a1SKevin Wolf opt_overlap_check_template = qemu_opt_get(opts, QCOW2_OPT_OVERLAP_TEMPLATE);
11034c75d1a1SKevin Wolf if (opt_overlap_check_template && opt_overlap_check &&
11044c75d1a1SKevin Wolf strcmp(opt_overlap_check_template, opt_overlap_check))
11054c75d1a1SKevin Wolf {
11064c75d1a1SKevin Wolf error_setg(errp, "Conflicting values for qcow2 options '"
11074c75d1a1SKevin Wolf QCOW2_OPT_OVERLAP "' ('%s') and '" QCOW2_OPT_OVERLAP_TEMPLATE
11084c75d1a1SKevin Wolf "' ('%s')", opt_overlap_check, opt_overlap_check_template);
11094c75d1a1SKevin Wolf ret = -EINVAL;
11104c75d1a1SKevin Wolf goto fail;
11114c75d1a1SKevin Wolf }
11124c75d1a1SKevin Wolf if (!opt_overlap_check) {
11134c75d1a1SKevin Wolf opt_overlap_check = opt_overlap_check_template ?: "cached";
11144c75d1a1SKevin Wolf }
11154c75d1a1SKevin Wolf
11164c75d1a1SKevin Wolf if (!strcmp(opt_overlap_check, "none")) {
11174c75d1a1SKevin Wolf overlap_check_template = 0;
11184c75d1a1SKevin Wolf } else if (!strcmp(opt_overlap_check, "constant")) {
11194c75d1a1SKevin Wolf overlap_check_template = QCOW2_OL_CONSTANT;
11204c75d1a1SKevin Wolf } else if (!strcmp(opt_overlap_check, "cached")) {
11214c75d1a1SKevin Wolf overlap_check_template = QCOW2_OL_CACHED;
11224c75d1a1SKevin Wolf } else if (!strcmp(opt_overlap_check, "all")) {
11234c75d1a1SKevin Wolf overlap_check_template = QCOW2_OL_ALL;
11244c75d1a1SKevin Wolf } else {
11254c75d1a1SKevin Wolf error_setg(errp, "Unsupported value '%s' for qcow2 option "
11264c75d1a1SKevin Wolf "'overlap-check'. Allowed are any of the following: "
11274c75d1a1SKevin Wolf "none, constant, cached, all", opt_overlap_check);
11284c75d1a1SKevin Wolf ret = -EINVAL;
11294c75d1a1SKevin Wolf goto fail;
11304c75d1a1SKevin Wolf }
11314c75d1a1SKevin Wolf
1132ee55b173SKevin Wolf r->overlap_check = 0;
11334c75d1a1SKevin Wolf for (i = 0; i < QCOW2_OL_MAX_BITNR; i++) {
11344c75d1a1SKevin Wolf /* overlap-check defines a template bitmask, but every flag may be
11354c75d1a1SKevin Wolf * overwritten through the associated boolean option */
1136ee55b173SKevin Wolf r->overlap_check |=
11374c75d1a1SKevin Wolf qemu_opt_get_bool(opts, overlap_bool_option_names[i],
11384c75d1a1SKevin Wolf overlap_check_template & (1 << i)) << i;
11394c75d1a1SKevin Wolf }
11404c75d1a1SKevin Wolf
1141ee55b173SKevin Wolf r->discard_passthrough[QCOW2_DISCARD_NEVER] = false;
1142ee55b173SKevin Wolf r->discard_passthrough[QCOW2_DISCARD_ALWAYS] = true;
1143ee55b173SKevin Wolf r->discard_passthrough[QCOW2_DISCARD_REQUEST] =
1144007dbc39SKevin Wolf qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_REQUEST,
1145007dbc39SKevin Wolf flags & BDRV_O_UNMAP);
1146ee55b173SKevin Wolf r->discard_passthrough[QCOW2_DISCARD_SNAPSHOT] =
1147007dbc39SKevin Wolf qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_SNAPSHOT, true);
1148ee55b173SKevin Wolf r->discard_passthrough[QCOW2_DISCARD_OTHER] =
1149007dbc39SKevin Wolf qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_OTHER, false);
1150007dbc39SKevin Wolf
115142a2890aSJean-Louis Dupond r->discard_no_unref = qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_NO_UNREF,
115242a2890aSJean-Louis Dupond false);
115342a2890aSJean-Louis Dupond if (r->discard_no_unref && s->qcow_version < 3) {
115442a2890aSJean-Louis Dupond error_setg(errp,
115542a2890aSJean-Louis Dupond "discard-no-unref is only supported since qcow2 version 3");
115642a2890aSJean-Louis Dupond ret = -EINVAL;
115742a2890aSJean-Louis Dupond goto fail;
115842a2890aSJean-Louis Dupond }
115942a2890aSJean-Louis Dupond
1160b25b387fSDaniel P. Berrange switch (s->crypt_method_header) {
1161b25b387fSDaniel P. Berrange case QCOW_CRYPT_NONE:
1162b25b387fSDaniel P. Berrange if (encryptfmt) {
1163b25b387fSDaniel P. Berrange error_setg(errp, "No encryption in image header, but options "
1164b25b387fSDaniel P. Berrange "specified format '%s'", encryptfmt);
1165b25b387fSDaniel P. Berrange ret = -EINVAL;
1166b25b387fSDaniel P. Berrange goto fail;
1167b25b387fSDaniel P. Berrange }
1168b25b387fSDaniel P. Berrange break;
1169b25b387fSDaniel P. Berrange
1170b25b387fSDaniel P. Berrange case QCOW_CRYPT_AES:
1171b25b387fSDaniel P. Berrange if (encryptfmt && !g_str_equal(encryptfmt, "aes")) {
1172b25b387fSDaniel P. Berrange error_setg(errp,
1173b25b387fSDaniel P. Berrange "Header reported 'aes' encryption format but "
1174b25b387fSDaniel P. Berrange "options specify '%s'", encryptfmt);
1175b25b387fSDaniel P. Berrange ret = -EINVAL;
1176b25b387fSDaniel P. Berrange goto fail;
1177b25b387fSDaniel P. Berrange }
1178796d3239SMarkus Armbruster qdict_put_str(encryptopts, "format", "qcow");
1179796d3239SMarkus Armbruster r->crypto_opts = block_crypto_open_opts_init(encryptopts, errp);
11801184b411SVladimir Sementsov-Ogievskiy if (!r->crypto_opts) {
11811184b411SVladimir Sementsov-Ogievskiy ret = -EINVAL;
11821184b411SVladimir Sementsov-Ogievskiy goto fail;
11831184b411SVladimir Sementsov-Ogievskiy }
1184b25b387fSDaniel P. Berrange break;
1185b25b387fSDaniel P. Berrange
11864652b8f3SDaniel P. Berrange case QCOW_CRYPT_LUKS:
11874652b8f3SDaniel P. Berrange if (encryptfmt && !g_str_equal(encryptfmt, "luks")) {
11884652b8f3SDaniel P. Berrange error_setg(errp,
11894652b8f3SDaniel P. Berrange "Header reported 'luks' encryption format but "
11904652b8f3SDaniel P. Berrange "options specify '%s'", encryptfmt);
11914652b8f3SDaniel P. Berrange ret = -EINVAL;
11924652b8f3SDaniel P. Berrange goto fail;
11934652b8f3SDaniel P. Berrange }
1194796d3239SMarkus Armbruster qdict_put_str(encryptopts, "format", "luks");
1195796d3239SMarkus Armbruster r->crypto_opts = block_crypto_open_opts_init(encryptopts, errp);
11961184b411SVladimir Sementsov-Ogievskiy if (!r->crypto_opts) {
11971184b411SVladimir Sementsov-Ogievskiy ret = -EINVAL;
11981184b411SVladimir Sementsov-Ogievskiy goto fail;
11991184b411SVladimir Sementsov-Ogievskiy }
12004652b8f3SDaniel P. Berrange break;
12014652b8f3SDaniel P. Berrange
1202b25b387fSDaniel P. Berrange default:
1203b25b387fSDaniel P. Berrange error_setg(errp, "Unsupported encryption method %d",
1204b25b387fSDaniel P. Berrange s->crypt_method_header);
1205b25b387fSDaniel P. Berrange ret = -EINVAL;
1206b25b387fSDaniel P. Berrange goto fail;
1207b25b387fSDaniel P. Berrange }
1208b25b387fSDaniel P. Berrange
12094c75d1a1SKevin Wolf ret = 0;
12104c75d1a1SKevin Wolf fail:
1211cb3e7f08SMarc-André Lureau qobject_unref(encryptopts);
121294edf3fbSKevin Wolf qemu_opts_del(opts);
121394edf3fbSKevin Wolf opts = NULL;
1214ee55b173SKevin Wolf return ret;
1215ee55b173SKevin Wolf }
1216ee55b173SKevin Wolf
qcow2_update_options_commit(BlockDriverState * bs,Qcow2ReopenState * r)1217ee55b173SKevin Wolf static void qcow2_update_options_commit(BlockDriverState *bs,
1218ee55b173SKevin Wolf Qcow2ReopenState *r)
1219ee55b173SKevin Wolf {
1220ee55b173SKevin Wolf BDRVQcow2State *s = bs->opaque;
1221ee55b173SKevin Wolf int i;
1222ee55b173SKevin Wolf
12235b0959a7SKevin Wolf if (s->l2_table_cache) {
1224e64d4072SAlberto Garcia qcow2_cache_destroy(s->l2_table_cache);
12255b0959a7SKevin Wolf }
12265b0959a7SKevin Wolf if (s->refcount_block_cache) {
1227e64d4072SAlberto Garcia qcow2_cache_destroy(s->refcount_block_cache);
12285b0959a7SKevin Wolf }
1229ee55b173SKevin Wolf s->l2_table_cache = r->l2_table_cache;
1230ee55b173SKevin Wolf s->refcount_block_cache = r->refcount_block_cache;
12313c2e511aSAlberto Garcia s->l2_slice_size = r->l2_slice_size;
1232ee55b173SKevin Wolf
1233ee55b173SKevin Wolf s->overlap_check = r->overlap_check;
1234ee55b173SKevin Wolf s->use_lazy_refcounts = r->use_lazy_refcounts;
1235ee55b173SKevin Wolf
1236ee55b173SKevin Wolf for (i = 0; i < QCOW2_DISCARD_MAX; i++) {
1237ee55b173SKevin Wolf s->discard_passthrough[i] = r->discard_passthrough[i];
1238ee55b173SKevin Wolf }
1239ee55b173SKevin Wolf
124042a2890aSJean-Louis Dupond s->discard_no_unref = r->discard_no_unref;
124142a2890aSJean-Louis Dupond
12425b0959a7SKevin Wolf if (s->cache_clean_interval != r->cache_clean_interval) {
12435b0959a7SKevin Wolf cache_clean_timer_del(bs);
1244ee55b173SKevin Wolf s->cache_clean_interval = r->cache_clean_interval;
1245ee55b173SKevin Wolf cache_clean_timer_init(bs, bdrv_get_aio_context(bs));
1246ee55b173SKevin Wolf }
1247b25b387fSDaniel P. Berrange
1248b25b387fSDaniel P. Berrange qapi_free_QCryptoBlockOpenOptions(s->crypto_opts);
1249b25b387fSDaniel P. Berrange s->crypto_opts = r->crypto_opts;
12505b0959a7SKevin Wolf }
1251ee55b173SKevin Wolf
qcow2_update_options_abort(BlockDriverState * bs,Qcow2ReopenState * r)1252ee55b173SKevin Wolf static void qcow2_update_options_abort(BlockDriverState *bs,
1253ee55b173SKevin Wolf Qcow2ReopenState *r)
1254ee55b173SKevin Wolf {
1255ee55b173SKevin Wolf if (r->l2_table_cache) {
1256e64d4072SAlberto Garcia qcow2_cache_destroy(r->l2_table_cache);
1257ee55b173SKevin Wolf }
1258ee55b173SKevin Wolf if (r->refcount_block_cache) {
1259e64d4072SAlberto Garcia qcow2_cache_destroy(r->refcount_block_cache);
1260ee55b173SKevin Wolf }
1261b25b387fSDaniel P. Berrange qapi_free_QCryptoBlockOpenOptions(r->crypto_opts);
1262ee55b173SKevin Wolf }
1263ee55b173SKevin Wolf
12640bb79c97SKevin Wolf static int coroutine_fn GRAPH_RDLOCK
qcow2_update_options(BlockDriverState * bs,QDict * options,int flags,Error ** errp)1265a39bae4eSPaolo Bonzini qcow2_update_options(BlockDriverState *bs, QDict *options, int flags,
1266a39bae4eSPaolo Bonzini Error **errp)
1267ee55b173SKevin Wolf {
1268ee55b173SKevin Wolf Qcow2ReopenState r = {};
1269ee55b173SKevin Wolf int ret;
1270ee55b173SKevin Wolf
1271ee55b173SKevin Wolf ret = qcow2_update_options_prepare(bs, &r, options, flags, errp);
1272ee55b173SKevin Wolf if (ret >= 0) {
1273ee55b173SKevin Wolf qcow2_update_options_commit(bs, &r);
1274ee55b173SKevin Wolf } else {
1275ee55b173SKevin Wolf qcow2_update_options_abort(bs, &r);
1276ee55b173SKevin Wolf }
127794edf3fbSKevin Wolf
12784c75d1a1SKevin Wolf return ret;
12794c75d1a1SKevin Wolf }
12804c75d1a1SKevin Wolf
validate_compression_type(BDRVQcow2State * s,Error ** errp)1281572ad978SDenis Plotnikov static int validate_compression_type(BDRVQcow2State *s, Error **errp)
1282572ad978SDenis Plotnikov {
1283572ad978SDenis Plotnikov switch (s->compression_type) {
1284572ad978SDenis Plotnikov case QCOW2_COMPRESSION_TYPE_ZLIB:
1285d298ac10SDenis Plotnikov #ifdef CONFIG_ZSTD
1286d298ac10SDenis Plotnikov case QCOW2_COMPRESSION_TYPE_ZSTD:
1287d298ac10SDenis Plotnikov #endif
1288572ad978SDenis Plotnikov break;
1289572ad978SDenis Plotnikov
1290572ad978SDenis Plotnikov default:
1291572ad978SDenis Plotnikov error_setg(errp, "qcow2: unknown compression type: %u",
1292572ad978SDenis Plotnikov s->compression_type);
1293572ad978SDenis Plotnikov return -ENOTSUP;
1294572ad978SDenis Plotnikov }
1295572ad978SDenis Plotnikov
1296572ad978SDenis Plotnikov /*
1297572ad978SDenis Plotnikov * if the compression type differs from QCOW2_COMPRESSION_TYPE_ZLIB
1298572ad978SDenis Plotnikov * the incompatible feature flag must be set
1299572ad978SDenis Plotnikov */
1300572ad978SDenis Plotnikov if (s->compression_type == QCOW2_COMPRESSION_TYPE_ZLIB) {
1301572ad978SDenis Plotnikov if (s->incompatible_features & QCOW2_INCOMPAT_COMPRESSION) {
1302572ad978SDenis Plotnikov error_setg(errp, "qcow2: Compression type incompatible feature "
1303572ad978SDenis Plotnikov "bit must not be set");
1304572ad978SDenis Plotnikov return -EINVAL;
1305572ad978SDenis Plotnikov }
1306572ad978SDenis Plotnikov } else {
1307572ad978SDenis Plotnikov if (!(s->incompatible_features & QCOW2_INCOMPAT_COMPRESSION)) {
1308572ad978SDenis Plotnikov error_setg(errp, "qcow2: Compression type incompatible feature "
1309572ad978SDenis Plotnikov "bit must be set");
1310572ad978SDenis Plotnikov return -EINVAL;
1311572ad978SDenis Plotnikov }
1312572ad978SDenis Plotnikov }
1313572ad978SDenis Plotnikov
1314572ad978SDenis Plotnikov return 0;
1315572ad978SDenis Plotnikov }
1316572ad978SDenis Plotnikov
13171fafcd93SPaolo Bonzini /* Called with s->lock held. */
1318b9b10c35SKevin Wolf static int coroutine_fn GRAPH_RDLOCK
qcow2_do_open(BlockDriverState * bs,QDict * options,int flags,bool open_data_file,Error ** errp)1319b9b10c35SKevin Wolf qcow2_do_open(BlockDriverState *bs, QDict *options, int flags,
1320b9b10c35SKevin Wolf bool open_data_file, Error **errp)
1321585f8587Sbellard {
1322bc520249SVladimir Sementsov-Ogievskiy ERRP_GUARD();
1323ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque;
13246d33e8e7SKevin Wolf unsigned int len, i;
13256d33e8e7SKevin Wolf int ret = 0;
1326585f8587Sbellard QCowHeader header;
13279b80ddf3Saliguori uint64_t ext_end;
13282cf7cfa1SKevin Wolf uint64_t l1_vm_state_index;
132988ddffaeSVladimir Sementsov-Ogievskiy bool update_header = false;
1330585f8587Sbellard
133138505e2aSAlberto Faria ret = bdrv_co_pread(bs->file, 0, sizeof(header), &header, 0);
13326d85a57eSJes Sorensen if (ret < 0) {
13333ef6c40aSMax Reitz error_setg_errno(errp, -ret, "Could not read qcow2 header");
1334585f8587Sbellard goto fail;
13356d85a57eSJes Sorensen }
13363b698f52SPeter Maydell header.magic = be32_to_cpu(header.magic);
13373b698f52SPeter Maydell header.version = be32_to_cpu(header.version);
13383b698f52SPeter Maydell header.backing_file_offset = be64_to_cpu(header.backing_file_offset);
13393b698f52SPeter Maydell header.backing_file_size = be32_to_cpu(header.backing_file_size);
13403b698f52SPeter Maydell header.size = be64_to_cpu(header.size);
13413b698f52SPeter Maydell header.cluster_bits = be32_to_cpu(header.cluster_bits);
13423b698f52SPeter Maydell header.crypt_method = be32_to_cpu(header.crypt_method);
13433b698f52SPeter Maydell header.l1_table_offset = be64_to_cpu(header.l1_table_offset);
13443b698f52SPeter Maydell header.l1_size = be32_to_cpu(header.l1_size);
13453b698f52SPeter Maydell header.refcount_table_offset = be64_to_cpu(header.refcount_table_offset);
13463b698f52SPeter Maydell header.refcount_table_clusters =
13473b698f52SPeter Maydell be32_to_cpu(header.refcount_table_clusters);
13483b698f52SPeter Maydell header.snapshots_offset = be64_to_cpu(header.snapshots_offset);
13493b698f52SPeter Maydell header.nb_snapshots = be32_to_cpu(header.nb_snapshots);
1350585f8587Sbellard
1351e8cdcec1SKevin Wolf if (header.magic != QCOW_MAGIC) {
13523ef6c40aSMax Reitz error_setg(errp, "Image is not in qcow2 format");
135376abe407SPaolo Bonzini ret = -EINVAL;
1354585f8587Sbellard goto fail;
13556d85a57eSJes Sorensen }
13566744cbabSKevin Wolf if (header.version < 2 || header.version > 3) {
1357a55448b3SMax Reitz error_setg(errp, "Unsupported qcow2 version %" PRIu32, header.version);
1358e8cdcec1SKevin Wolf ret = -ENOTSUP;
1359e8cdcec1SKevin Wolf goto fail;
1360e8cdcec1SKevin Wolf }
13616744cbabSKevin Wolf
13626744cbabSKevin Wolf s->qcow_version = header.version;
13636744cbabSKevin Wolf
136424342f2cSKevin Wolf /* Initialise cluster size */
136524342f2cSKevin Wolf if (header.cluster_bits < MIN_CLUSTER_BITS ||
136624342f2cSKevin Wolf header.cluster_bits > MAX_CLUSTER_BITS) {
1367521b2b5dSMax Reitz error_setg(errp, "Unsupported cluster size: 2^%" PRIu32,
1368521b2b5dSMax Reitz header.cluster_bits);
136924342f2cSKevin Wolf ret = -EINVAL;
137024342f2cSKevin Wolf goto fail;
137124342f2cSKevin Wolf }
137224342f2cSKevin Wolf
137324342f2cSKevin Wolf s->cluster_bits = header.cluster_bits;
137424342f2cSKevin Wolf s->cluster_size = 1 << s->cluster_bits;
137524342f2cSKevin Wolf
13766744cbabSKevin Wolf /* Initialise version 3 header fields */
13776744cbabSKevin Wolf if (header.version == 2) {
13786744cbabSKevin Wolf header.incompatible_features = 0;
13796744cbabSKevin Wolf header.compatible_features = 0;
13806744cbabSKevin Wolf header.autoclear_features = 0;
13816744cbabSKevin Wolf header.refcount_order = 4;
13826744cbabSKevin Wolf header.header_length = 72;
13836744cbabSKevin Wolf } else {
13843b698f52SPeter Maydell header.incompatible_features =
13853b698f52SPeter Maydell be64_to_cpu(header.incompatible_features);
13863b698f52SPeter Maydell header.compatible_features = be64_to_cpu(header.compatible_features);
13873b698f52SPeter Maydell header.autoclear_features = be64_to_cpu(header.autoclear_features);
13883b698f52SPeter Maydell header.refcount_order = be32_to_cpu(header.refcount_order);
13893b698f52SPeter Maydell header.header_length = be32_to_cpu(header.header_length);
139024342f2cSKevin Wolf
139124342f2cSKevin Wolf if (header.header_length < 104) {
139224342f2cSKevin Wolf error_setg(errp, "qcow2 header too short");
139324342f2cSKevin Wolf ret = -EINVAL;
139424342f2cSKevin Wolf goto fail;
139524342f2cSKevin Wolf }
139624342f2cSKevin Wolf }
139724342f2cSKevin Wolf
139824342f2cSKevin Wolf if (header.header_length > s->cluster_size) {
139924342f2cSKevin Wolf error_setg(errp, "qcow2 header exceeds cluster size");
140024342f2cSKevin Wolf ret = -EINVAL;
140124342f2cSKevin Wolf goto fail;
14026744cbabSKevin Wolf }
14036744cbabSKevin Wolf
14046744cbabSKevin Wolf if (header.header_length > sizeof(header)) {
14056744cbabSKevin Wolf s->unknown_header_fields_size = header.header_length - sizeof(header);
14066744cbabSKevin Wolf s->unknown_header_fields = g_malloc(s->unknown_header_fields_size);
140738505e2aSAlberto Faria ret = bdrv_co_pread(bs->file, sizeof(header),
140832cc71deSAlberto Faria s->unknown_header_fields_size,
140932cc71deSAlberto Faria s->unknown_header_fields, 0);
14106744cbabSKevin Wolf if (ret < 0) {
14113ef6c40aSMax Reitz error_setg_errno(errp, -ret, "Could not read unknown qcow2 header "
14123ef6c40aSMax Reitz "fields");
14136744cbabSKevin Wolf goto fail;
14146744cbabSKevin Wolf }
14156744cbabSKevin Wolf }
14166744cbabSKevin Wolf
1417a1b3955cSKevin Wolf if (header.backing_file_offset > s->cluster_size) {
1418a1b3955cSKevin Wolf error_setg(errp, "Invalid backing file offset");
1419a1b3955cSKevin Wolf ret = -EINVAL;
1420a1b3955cSKevin Wolf goto fail;
1421a1b3955cSKevin Wolf }
1422a1b3955cSKevin Wolf
1423cfcc4c62SKevin Wolf if (header.backing_file_offset) {
1424cfcc4c62SKevin Wolf ext_end = header.backing_file_offset;
1425cfcc4c62SKevin Wolf } else {
1426cfcc4c62SKevin Wolf ext_end = 1 << header.cluster_bits;
1427cfcc4c62SKevin Wolf }
1428cfcc4c62SKevin Wolf
14296744cbabSKevin Wolf /* Handle feature bits */
14306744cbabSKevin Wolf s->incompatible_features = header.incompatible_features;
14316744cbabSKevin Wolf s->compatible_features = header.compatible_features;
14326744cbabSKevin Wolf s->autoclear_features = header.autoclear_features;
14336744cbabSKevin Wolf
1434572ad978SDenis Plotnikov /*
1435572ad978SDenis Plotnikov * Handle compression type
1436572ad978SDenis Plotnikov * Older qcow2 images don't contain the compression type header.
1437572ad978SDenis Plotnikov * Distinguish them by the header length and use
1438572ad978SDenis Plotnikov * the only valid (default) compression type in that case
1439572ad978SDenis Plotnikov */
1440572ad978SDenis Plotnikov if (header.header_length > offsetof(QCowHeader, compression_type)) {
1441572ad978SDenis Plotnikov s->compression_type = header.compression_type;
1442572ad978SDenis Plotnikov } else {
1443572ad978SDenis Plotnikov s->compression_type = QCOW2_COMPRESSION_TYPE_ZLIB;
1444572ad978SDenis Plotnikov }
1445572ad978SDenis Plotnikov
1446572ad978SDenis Plotnikov ret = validate_compression_type(s, errp);
1447572ad978SDenis Plotnikov if (ret) {
1448572ad978SDenis Plotnikov goto fail;
1449572ad978SDenis Plotnikov }
1450572ad978SDenis Plotnikov
1451c61d0004SStefan Hajnoczi if (s->incompatible_features & ~QCOW2_INCOMPAT_MASK) {
1452cfcc4c62SKevin Wolf void *feature_table = NULL;
1453cfcc4c62SKevin Wolf qcow2_read_extensions(bs, header.header_length, ext_end,
145488ddffaeSVladimir Sementsov-Ogievskiy &feature_table, flags, NULL, NULL);
1455a55448b3SMax Reitz report_unsupported_feature(errp, feature_table,
1456c61d0004SStefan Hajnoczi s->incompatible_features &
1457c61d0004SStefan Hajnoczi ~QCOW2_INCOMPAT_MASK);
14586744cbabSKevin Wolf ret = -ENOTSUP;
1459c5a33ee9SPrasad Joshi g_free(feature_table);
14606744cbabSKevin Wolf goto fail;
14616744cbabSKevin Wolf }
14626744cbabSKevin Wolf
146369c98726SMax Reitz if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
146469c98726SMax Reitz /* Corrupt images may not be written to unless they are being repaired
146569c98726SMax Reitz */
146669c98726SMax Reitz if ((flags & BDRV_O_RDWR) && !(flags & BDRV_O_CHECK)) {
14673ef6c40aSMax Reitz error_setg(errp, "qcow2: Image is corrupt; cannot be opened "
14683ef6c40aSMax Reitz "read/write");
146969c98726SMax Reitz ret = -EACCES;
147069c98726SMax Reitz goto fail;
147169c98726SMax Reitz }
147269c98726SMax Reitz }
147369c98726SMax Reitz
1474d0346b55SAlberto Garcia s->subclusters_per_cluster =
1475d0346b55SAlberto Garcia has_subclusters(s) ? QCOW_EXTL2_SUBCLUSTERS_PER_CLUSTER : 1;
1476d0346b55SAlberto Garcia s->subcluster_size = s->cluster_size / s->subclusters_per_cluster;
1477d0346b55SAlberto Garcia s->subcluster_bits = ctz32(s->subcluster_size);
1478d0346b55SAlberto Garcia
14797be20252SAlberto Garcia if (s->subcluster_size < (1 << MIN_CLUSTER_BITS)) {
14807be20252SAlberto Garcia error_setg(errp, "Unsupported subcluster size: %d", s->subcluster_size);
14817be20252SAlberto Garcia ret = -EINVAL;
14827be20252SAlberto Garcia goto fail;
14837be20252SAlberto Garcia }
14847be20252SAlberto Garcia
14856744cbabSKevin Wolf /* Check support for various header values */
1486b72faf9fSMax Reitz if (header.refcount_order > 6) {
1487b72faf9fSMax Reitz error_setg(errp, "Reference count entry width too large; may not "
1488b72faf9fSMax Reitz "exceed 64 bits");
1489b72faf9fSMax Reitz ret = -EINVAL;
14906744cbabSKevin Wolf goto fail;
14916744cbabSKevin Wolf }
1492b6481f37SMax Reitz s->refcount_order = header.refcount_order;
1493346a53dfSMax Reitz s->refcount_bits = 1 << s->refcount_order;
1494346a53dfSMax Reitz s->refcount_max = UINT64_C(1) << (s->refcount_bits - 1);
1495346a53dfSMax Reitz s->refcount_max += s->refcount_max - 1;
14966744cbabSKevin Wolf
1497585f8587Sbellard s->crypt_method_header = header.crypt_method;
14986d85a57eSJes Sorensen if (s->crypt_method_header) {
1499e6ff69bfSDaniel P. Berrange if (bdrv_uses_whitelist() &&
1500e6ff69bfSDaniel P. Berrange s->crypt_method_header == QCOW_CRYPT_AES) {
15018c0dcbc4SDaniel P. Berrange error_setg(errp,
15028c0dcbc4SDaniel P. Berrange "Use of AES-CBC encrypted qcow2 images is no longer "
15038c0dcbc4SDaniel P. Berrange "supported in system emulators");
15048c0dcbc4SDaniel P. Berrange error_append_hint(errp,
15058c0dcbc4SDaniel P. Berrange "You can use 'qemu-img convert' to convert your "
15068c0dcbc4SDaniel P. Berrange "image to an alternative supported format, such "
15078c0dcbc4SDaniel P. Berrange "as unencrypted qcow2, or raw with the LUKS "
15088c0dcbc4SDaniel P. Berrange "format instead.\n");
15098c0dcbc4SDaniel P. Berrange ret = -ENOSYS;
15108c0dcbc4SDaniel P. Berrange goto fail;
1511e6ff69bfSDaniel P. Berrange }
1512e6ff69bfSDaniel P. Berrange
15134652b8f3SDaniel P. Berrange if (s->crypt_method_header == QCOW_CRYPT_AES) {
15144652b8f3SDaniel P. Berrange s->crypt_physical_offset = false;
15154652b8f3SDaniel P. Berrange } else {
15164652b8f3SDaniel P. Berrange /* Assuming LUKS and any future crypt methods we
15174652b8f3SDaniel P. Berrange * add will all use physical offsets, due to the
15184652b8f3SDaniel P. Berrange * fact that the alternative is insecure... */
15194652b8f3SDaniel P. Berrange s->crypt_physical_offset = true;
15204652b8f3SDaniel P. Berrange }
15214652b8f3SDaniel P. Berrange
152254115412SEric Blake bs->encrypted = true;
15236d85a57eSJes Sorensen }
152424342f2cSKevin Wolf
1525c8fd8554SAlberto Garcia s->l2_bits = s->cluster_bits - ctz32(l2_entry_size(s));
1526585f8587Sbellard s->l2_size = 1 << s->l2_bits;
15271d13d654SMax Reitz /* 2^(s->refcount_order - 3) is the refcount width in bytes */
15281d13d654SMax Reitz s->refcount_block_bits = s->cluster_bits - (s->refcount_order - 3);
15291d13d654SMax Reitz s->refcount_block_size = 1 << s->refcount_block_bits;
1530bd016b91SLeonid Bloch bs->total_sectors = header.size / BDRV_SECTOR_SIZE;
1531585f8587Sbellard s->csize_shift = (62 - (s->cluster_bits - 8));
1532585f8587Sbellard s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;
1533585f8587Sbellard s->cluster_offset_mask = (1LL << s->csize_shift) - 1;
15345dab2fadSKevin Wolf
1535585f8587Sbellard s->refcount_table_offset = header.refcount_table_offset;
1536585f8587Sbellard s->refcount_table_size =
1537585f8587Sbellard header.refcount_table_clusters << (s->cluster_bits - 3);
1538585f8587Sbellard
1539951053a9SAlberto Garcia if (header.refcount_table_clusters == 0 && !(flags & BDRV_O_CHECK)) {
1540951053a9SAlberto Garcia error_setg(errp, "Image does not contain a reference count table");
1541951053a9SAlberto Garcia ret = -EINVAL;
1542951053a9SAlberto Garcia goto fail;
1543951053a9SAlberto Garcia }
1544951053a9SAlberto Garcia
15450cf0e598SAlberto Garcia ret = qcow2_validate_table(bs, s->refcount_table_offset,
15460cf0e598SAlberto Garcia header.refcount_table_clusters,
15470cf0e598SAlberto Garcia s->cluster_size, QCOW_MAX_REFTABLE_SIZE,
15480cf0e598SAlberto Garcia "Reference count table", errp);
15498c7de283SKevin Wolf if (ret < 0) {
15508c7de283SKevin Wolf goto fail;
15518c7de283SKevin Wolf }
15528c7de283SKevin Wolf
15538bc584feSMax Reitz if (!(flags & BDRV_O_CHECK)) {
15548bc584feSMax Reitz /*
15558bc584feSMax Reitz * The total size in bytes of the snapshot table is checked in
15560cf0e598SAlberto Garcia * qcow2_read_snapshots() because the size of each snapshot is
15570cf0e598SAlberto Garcia * variable and we don't know it yet.
15588bc584feSMax Reitz * Here we only check the offset and number of snapshots.
15598bc584feSMax Reitz */
15600cf0e598SAlberto Garcia ret = qcow2_validate_table(bs, header.snapshots_offset,
1561ce48f2f4SKevin Wolf header.nb_snapshots,
15620cf0e598SAlberto Garcia sizeof(QCowSnapshotHeader),
15638bc584feSMax Reitz sizeof(QCowSnapshotHeader) *
15648bc584feSMax Reitz QCOW_MAX_SNAPSHOTS,
15650cf0e598SAlberto Garcia "Snapshot table", errp);
1566ce48f2f4SKevin Wolf if (ret < 0) {
1567ce48f2f4SKevin Wolf goto fail;
1568ce48f2f4SKevin Wolf }
15698bc584feSMax Reitz }
1570ce48f2f4SKevin Wolf
1571585f8587Sbellard /* read the level 1 table */
15720cf0e598SAlberto Garcia ret = qcow2_validate_table(bs, header.l1_table_offset,
157302b1ecfaSAlberto Garcia header.l1_size, L1E_SIZE,
15740cf0e598SAlberto Garcia QCOW_MAX_L1_SIZE, "Active L1 table", errp);
15750cf0e598SAlberto Garcia if (ret < 0) {
15762d51c32cSKevin Wolf goto fail;
15772d51c32cSKevin Wolf }
1578585f8587Sbellard s->l1_size = header.l1_size;
15790cf0e598SAlberto Garcia s->l1_table_offset = header.l1_table_offset;
15802cf7cfa1SKevin Wolf
15812cf7cfa1SKevin Wolf l1_vm_state_index = size_to_l1(s, header.size);
15822cf7cfa1SKevin Wolf if (l1_vm_state_index > INT_MAX) {
15833ef6c40aSMax Reitz error_setg(errp, "Image is too big");
15842cf7cfa1SKevin Wolf ret = -EFBIG;
15852cf7cfa1SKevin Wolf goto fail;
15862cf7cfa1SKevin Wolf }
15872cf7cfa1SKevin Wolf s->l1_vm_state_index = l1_vm_state_index;
15882cf7cfa1SKevin Wolf
1589585f8587Sbellard /* the L1 table must contain at least enough entries to put
1590585f8587Sbellard header.size bytes */
15916d85a57eSJes Sorensen if (s->l1_size < s->l1_vm_state_index) {
15923ef6c40aSMax Reitz error_setg(errp, "L1 table is too small");
15936d85a57eSJes Sorensen ret = -EINVAL;
1594585f8587Sbellard goto fail;
15956d85a57eSJes Sorensen }
15962d51c32cSKevin Wolf
1597d191d12dSStefan Weil if (s->l1_size > 0) {
159802b1ecfaSAlberto Garcia s->l1_table = qemu_try_blockalign(bs->file->bs, s->l1_size * L1E_SIZE);
1599de82815dSKevin Wolf if (s->l1_table == NULL) {
1600de82815dSKevin Wolf error_setg(errp, "Could not allocate L1 table");
1601de82815dSKevin Wolf ret = -ENOMEM;
1602de82815dSKevin Wolf goto fail;
1603de82815dSKevin Wolf }
160438505e2aSAlberto Faria ret = bdrv_co_pread(bs->file, s->l1_table_offset, s->l1_size * L1E_SIZE,
160532cc71deSAlberto Faria s->l1_table, 0);
16066d85a57eSJes Sorensen if (ret < 0) {
16073ef6c40aSMax Reitz error_setg_errno(errp, -ret, "Could not read L1 table");
1608585f8587Sbellard goto fail;
16096d85a57eSJes Sorensen }
1610585f8587Sbellard for(i = 0;i < s->l1_size; i++) {
16113b698f52SPeter Maydell s->l1_table[i] = be64_to_cpu(s->l1_table[i]);
1612585f8587Sbellard }
1613d191d12dSStefan Weil }
161429c1a730SKevin Wolf
161594edf3fbSKevin Wolf /* Parse driver-specific options */
161694edf3fbSKevin Wolf ret = qcow2_update_options(bs, options, flags, errp);
161790efa0eaSKevin Wolf if (ret < 0) {
161890efa0eaSKevin Wolf goto fail;
161990efa0eaSKevin Wolf }
162090efa0eaSKevin Wolf
162106d9260fSAnthony Liguori s->flags = flags;
1622585f8587Sbellard
16236d85a57eSJes Sorensen ret = qcow2_refcount_init(bs);
16246d85a57eSJes Sorensen if (ret != 0) {
16253ef6c40aSMax Reitz error_setg_errno(errp, -ret, "Could not initialize refcount handling");
1626585f8587Sbellard goto fail;
16276d85a57eSJes Sorensen }
1628585f8587Sbellard
162972cf2d4fSBlue Swirl QLIST_INIT(&s->cluster_allocs);
16300b919faeSKevin Wolf QTAILQ_INIT(&s->discards);
1631f214978aSKevin Wolf
16329b80ddf3Saliguori /* read qcow2 extensions */
16333ef6c40aSMax Reitz if (qcow2_read_extensions(bs, header.header_length, ext_end, NULL,
1634af175e85SMarkus Armbruster flags, &update_header, errp)) {
16356d85a57eSJes Sorensen ret = -EINVAL;
16369b80ddf3Saliguori goto fail;
16376d85a57eSJes Sorensen }
16389b80ddf3Saliguori
1639bd385a52SKevin Wolf if (open_data_file && (flags & BDRV_O_NO_IO)) {
1640bd385a52SKevin Wolf /*
1641bd385a52SKevin Wolf * Don't open the data file for 'qemu-img info' so that it can be used
1642bd385a52SKevin Wolf * to verify that an untrusted qcow2 image doesn't refer to external
1643bd385a52SKevin Wolf * files.
1644bd385a52SKevin Wolf *
1645bd385a52SKevin Wolf * Note: This still makes has_data_file() return true.
1646bd385a52SKevin Wolf */
1647bd385a52SKevin Wolf if (s->incompatible_features & QCOW2_INCOMPAT_DATA_FILE) {
1648bd385a52SKevin Wolf s->data_file = NULL;
1649bd385a52SKevin Wolf } else {
1650bd385a52SKevin Wolf s->data_file = bs->file;
1651bd385a52SKevin Wolf }
1652bd385a52SKevin Wolf qdict_extract_subqdict(options, NULL, "data-file.");
1653bd385a52SKevin Wolf qdict_del(options, "data-file");
1654bd385a52SKevin Wolf } else if (open_data_file) {
16550e8c08beSKevin Wolf /* Open external data file */
1656e3e31dc8SKevin Wolf bdrv_graph_co_rdunlock();
1657ecbc57caSKevin Wolf s->data_file = bdrv_co_open_child(NULL, options, "data-file", bs,
16588b1869daSMax Reitz &child_of_bds, BDRV_CHILD_DATA,
1659bc520249SVladimir Sementsov-Ogievskiy true, errp);
1660e3e31dc8SKevin Wolf bdrv_graph_co_rdlock();
1661bc520249SVladimir Sementsov-Ogievskiy if (*errp) {
16620e8c08beSKevin Wolf ret = -EINVAL;
16630e8c08beSKevin Wolf goto fail;
16640e8c08beSKevin Wolf }
16650e8c08beSKevin Wolf
16660e8c08beSKevin Wolf if (s->incompatible_features & QCOW2_INCOMPAT_DATA_FILE) {
16679b890bdcSKevin Wolf if (!s->data_file && s->image_data_file) {
1668e3e31dc8SKevin Wolf bdrv_graph_co_rdunlock();
1669ecbc57caSKevin Wolf s->data_file = bdrv_co_open_child(s->image_data_file, options,
1670ecbc57caSKevin Wolf "data-file", bs,
1671ecbc57caSKevin Wolf &child_of_bds,
16728b1869daSMax Reitz BDRV_CHILD_DATA, false, errp);
1673e3e31dc8SKevin Wolf bdrv_graph_co_rdlock();
16749b890bdcSKevin Wolf if (!s->data_file) {
16759b890bdcSKevin Wolf ret = -EINVAL;
16769b890bdcSKevin Wolf goto fail;
16779b890bdcSKevin Wolf }
16789b890bdcSKevin Wolf }
16790e8c08beSKevin Wolf if (!s->data_file) {
16800e8c08beSKevin Wolf error_setg(errp, "'data-file' is required for this image");
16810e8c08beSKevin Wolf ret = -EINVAL;
16820e8c08beSKevin Wolf goto fail;
16830e8c08beSKevin Wolf }
16848b1869daSMax Reitz
16858b1869daSMax Reitz /* No data here */
16868b1869daSMax Reitz bs->file->role &= ~BDRV_CHILD_DATA;
16878b1869daSMax Reitz
16888b1869daSMax Reitz /* Must succeed because we have given up permissions if anything */
16898b1869daSMax Reitz bdrv_child_refresh_perms(bs, bs->file, &error_abort);
16900e8c08beSKevin Wolf } else {
16910e8c08beSKevin Wolf if (s->data_file) {
169206e9cd19SHanna Reitz error_setg(errp, "'data-file' can only be set for images with "
169306e9cd19SHanna Reitz "an external data file");
16940e8c08beSKevin Wolf ret = -EINVAL;
16950e8c08beSKevin Wolf goto fail;
16966c3944dcSKevin Wolf }
16976c3944dcSKevin Wolf
169893c24936SKevin Wolf s->data_file = bs->file;
16996c3944dcSKevin Wolf
17006c3944dcSKevin Wolf if (data_file_is_raw(bs)) {
17016c3944dcSKevin Wolf error_setg(errp, "data-file-raw requires a data file");
17026c3944dcSKevin Wolf ret = -EINVAL;
17036c3944dcSKevin Wolf goto fail;
17040e8c08beSKevin Wolf }
17050e8c08beSKevin Wolf }
170606e9cd19SHanna Reitz }
170793c24936SKevin Wolf
17084652b8f3SDaniel P. Berrange /* qcow2_read_extension may have set up the crypto context
17094652b8f3SDaniel P. Berrange * if the crypt method needs a header region, some methods
17104652b8f3SDaniel P. Berrange * don't need header extensions, so must check here
17114652b8f3SDaniel P. Berrange */
17124652b8f3SDaniel P. Berrange if (s->crypt_method_header && !s->crypto) {
1713b25b387fSDaniel P. Berrange if (s->crypt_method_header == QCOW_CRYPT_AES) {
1714b25b387fSDaniel P. Berrange unsigned int cflags = 0;
1715b25b387fSDaniel P. Berrange if (flags & BDRV_O_NO_IO) {
1716b25b387fSDaniel P. Berrange cflags |= QCRYPTO_BLOCK_OPEN_NO_IO;
1717b25b387fSDaniel P. Berrange }
17181cd9a787SDaniel P. Berrange s->crypto = qcrypto_block_open(s->crypto_opts, "encrypt.",
17193ab0f063SStefan Hajnoczi NULL, NULL, cflags, errp);
1720b25b387fSDaniel P. Berrange if (!s->crypto) {
1721b25b387fSDaniel P. Berrange ret = -EINVAL;
1722b25b387fSDaniel P. Berrange goto fail;
1723b25b387fSDaniel P. Berrange }
17248e4ffb4eSKevin Wolf } else {
17254652b8f3SDaniel P. Berrange error_setg(errp, "Missing CRYPTO header for crypt method %d",
17264652b8f3SDaniel P. Berrange s->crypt_method_header);
17274652b8f3SDaniel P. Berrange ret = -EINVAL;
17284652b8f3SDaniel P. Berrange goto fail;
17294652b8f3SDaniel P. Berrange }
1730b25b387fSDaniel P. Berrange }
1731b25b387fSDaniel P. Berrange
1732585f8587Sbellard /* read the backing file name */
1733585f8587Sbellard if (header.backing_file_offset != 0) {
1734585f8587Sbellard len = header.backing_file_size;
17359a29e18fSJeff Cody if (len > MIN(1023, s->cluster_size - header.backing_file_offset) ||
1736e729fa6aSJeff Cody len >= sizeof(bs->backing_file)) {
17376d33e8e7SKevin Wolf error_setg(errp, "Backing file name too long");
17386d33e8e7SKevin Wolf ret = -EINVAL;
17396d33e8e7SKevin Wolf goto fail;
17406d85a57eSJes Sorensen }
1741ec64b1caSHanna Reitz
1742ec64b1caSHanna Reitz s->image_backing_file = g_malloc(len + 1);
174338505e2aSAlberto Faria ret = bdrv_co_pread(bs->file, header.backing_file_offset, len,
1744ec64b1caSHanna Reitz s->image_backing_file, 0);
17456d85a57eSJes Sorensen if (ret < 0) {
17463ef6c40aSMax Reitz error_setg_errno(errp, -ret, "Could not read backing file name");
1747585f8587Sbellard goto fail;
17486d85a57eSJes Sorensen }
1749ec64b1caSHanna Reitz s->image_backing_file[len] = '\0';
1750ec64b1caSHanna Reitz
1751ec64b1caSHanna Reitz /*
1752ec64b1caSHanna Reitz * Update only when something has changed. This function is called by
1753ec64b1caSHanna Reitz * qcow2_co_invalidate_cache(), and we do not want to reset
1754ec64b1caSHanna Reitz * auto_backing_file unless necessary.
1755ec64b1caSHanna Reitz */
1756ec64b1caSHanna Reitz if (!g_str_equal(s->image_backing_file, bs->backing_file)) {
1757998c2019SMax Reitz pstrcpy(bs->backing_file, sizeof(bs->backing_file),
1758ec64b1caSHanna Reitz s->image_backing_file);
1759ec64b1caSHanna Reitz pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
1760ec64b1caSHanna Reitz s->image_backing_file);
1761ec64b1caSHanna Reitz }
1762585f8587Sbellard }
176342deb29fSKevin Wolf
17648bc584feSMax Reitz /*
17658bc584feSMax Reitz * Internal snapshots; skip reading them in check mode, because
17668bc584feSMax Reitz * we do not need them then, and we do not want to abort because
17678bc584feSMax Reitz * of a broken table.
17688bc584feSMax Reitz */
17698bc584feSMax Reitz if (!(flags & BDRV_O_CHECK)) {
177011b128f4SKevin Wolf s->snapshots_offset = header.snapshots_offset;
177111b128f4SKevin Wolf s->nb_snapshots = header.nb_snapshots;
177211b128f4SKevin Wolf
1773ecf6c7c0SMax Reitz ret = qcow2_read_snapshots(bs, errp);
177442deb29fSKevin Wolf if (ret < 0) {
1775585f8587Sbellard goto fail;
17766d85a57eSJes Sorensen }
17778bc584feSMax Reitz }
1778585f8587Sbellard
1779af7b708dSStefan Hajnoczi /* Clear unknown autoclear feature bits */
178088ddffaeSVladimir Sementsov-Ogievskiy update_header |= s->autoclear_features & ~QCOW2_AUTOCLEAR_MASK;
1781307261b2SVladimir Sementsov-Ogievskiy update_header = update_header && bdrv_is_writable(bs);
1782d1258dd0SVladimir Sementsov-Ogievskiy if (update_header) {
178388ddffaeSVladimir Sementsov-Ogievskiy s->autoclear_features &= QCOW2_AUTOCLEAR_MASK;
1784d1258dd0SVladimir Sementsov-Ogievskiy }
1785d1258dd0SVladimir Sementsov-Ogievskiy
17869c98f145SVladimir Sementsov-Ogievskiy /* == Handle persistent dirty bitmaps ==
17879c98f145SVladimir Sementsov-Ogievskiy *
17889c98f145SVladimir Sementsov-Ogievskiy * We want load dirty bitmaps in three cases:
17899c98f145SVladimir Sementsov-Ogievskiy *
17909c98f145SVladimir Sementsov-Ogievskiy * 1. Normal open of the disk in active mode, not related to invalidation
17919c98f145SVladimir Sementsov-Ogievskiy * after migration.
17929c98f145SVladimir Sementsov-Ogievskiy *
17939c98f145SVladimir Sementsov-Ogievskiy * 2. Invalidation of the target vm after pre-copy phase of migration, if
17949c98f145SVladimir Sementsov-Ogievskiy * bitmaps are _not_ migrating through migration channel, i.e.
17959c98f145SVladimir Sementsov-Ogievskiy * 'dirty-bitmaps' capability is disabled.
17969c98f145SVladimir Sementsov-Ogievskiy *
17979c98f145SVladimir Sementsov-Ogievskiy * 3. Invalidation of source vm after failed or canceled migration.
17989c98f145SVladimir Sementsov-Ogievskiy * This is a very interesting case. There are two possible types of
17999c98f145SVladimir Sementsov-Ogievskiy * bitmaps:
18009c98f145SVladimir Sementsov-Ogievskiy *
18019c98f145SVladimir Sementsov-Ogievskiy * A. Stored on inactivation and removed. They should be loaded from the
18029c98f145SVladimir Sementsov-Ogievskiy * image.
18039c98f145SVladimir Sementsov-Ogievskiy *
18049c98f145SVladimir Sementsov-Ogievskiy * B. Not stored: not-persistent bitmaps and bitmaps, migrated through
18059c98f145SVladimir Sementsov-Ogievskiy * the migration channel (with dirty-bitmaps capability).
18069c98f145SVladimir Sementsov-Ogievskiy *
18079c98f145SVladimir Sementsov-Ogievskiy * On the other hand, there are two possible sub-cases:
18089c98f145SVladimir Sementsov-Ogievskiy *
18099c98f145SVladimir Sementsov-Ogievskiy * 3.1 disk was changed by somebody else while were inactive. In this
18109c98f145SVladimir Sementsov-Ogievskiy * case all in-RAM dirty bitmaps (both persistent and not) are
18119c98f145SVladimir Sementsov-Ogievskiy * definitely invalid. And we don't have any method to determine
18129c98f145SVladimir Sementsov-Ogievskiy * this.
18139c98f145SVladimir Sementsov-Ogievskiy *
18149c98f145SVladimir Sementsov-Ogievskiy * Simple and safe thing is to just drop all the bitmaps of type B on
18159c98f145SVladimir Sementsov-Ogievskiy * inactivation. But in this case we lose bitmaps in valid 4.2 case.
18169c98f145SVladimir Sementsov-Ogievskiy *
18179c98f145SVladimir Sementsov-Ogievskiy * On the other hand, resuming source vm, if disk was already changed
18189c98f145SVladimir Sementsov-Ogievskiy * is a bad thing anyway: not only bitmaps, the whole vm state is
18199c98f145SVladimir Sementsov-Ogievskiy * out of sync with disk.
18209c98f145SVladimir Sementsov-Ogievskiy *
18219c98f145SVladimir Sementsov-Ogievskiy * This means, that user or management tool, who for some reason
18229c98f145SVladimir Sementsov-Ogievskiy * decided to resume source vm, after disk was already changed by
18239c98f145SVladimir Sementsov-Ogievskiy * target vm, should at least drop all dirty bitmaps by hand.
18249c98f145SVladimir Sementsov-Ogievskiy *
18259c98f145SVladimir Sementsov-Ogievskiy * So, we can ignore this case for now, but TODO: "generation"
18269c98f145SVladimir Sementsov-Ogievskiy * extension for qcow2, to determine, that image was changed after
18279c98f145SVladimir Sementsov-Ogievskiy * last inactivation. And if it is changed, we will drop (or at least
18289c98f145SVladimir Sementsov-Ogievskiy * mark as 'invalid' all the bitmaps of type B, both persistent
18299c98f145SVladimir Sementsov-Ogievskiy * and not).
18309c98f145SVladimir Sementsov-Ogievskiy *
18319c98f145SVladimir Sementsov-Ogievskiy * 3.2 disk was _not_ changed while were inactive. Bitmaps may be saved
18329c98f145SVladimir Sementsov-Ogievskiy * to disk ('dirty-bitmaps' capability disabled), or not saved
18339c98f145SVladimir Sementsov-Ogievskiy * ('dirty-bitmaps' capability enabled), but we don't need to care
18349c98f145SVladimir Sementsov-Ogievskiy * of: let's load bitmaps as always: stored bitmaps will be loaded,
18359c98f145SVladimir Sementsov-Ogievskiy * and not stored has flag IN_USE=1 in the image and will be skipped
18369c98f145SVladimir Sementsov-Ogievskiy * on loading.
18379c98f145SVladimir Sementsov-Ogievskiy *
18389c98f145SVladimir Sementsov-Ogievskiy * One remaining possible case when we don't want load bitmaps:
18399c98f145SVladimir Sementsov-Ogievskiy *
18409c98f145SVladimir Sementsov-Ogievskiy * 4. Open disk in inactive mode in target vm (bitmaps are migrating or
18419c98f145SVladimir Sementsov-Ogievskiy * will be loaded on invalidation, no needs try loading them before)
18429c98f145SVladimir Sementsov-Ogievskiy */
18439c98f145SVladimir Sementsov-Ogievskiy
18449c98f145SVladimir Sementsov-Ogievskiy if (!(bdrv_get_flags(bs) & BDRV_O_INACTIVE)) {
18459c98f145SVladimir Sementsov-Ogievskiy /* It's case 1, 2 or 3.2. Or 3.1 which is BUG in management layer. */
18460c1e9d2aSVladimir Sementsov-Ogievskiy bool header_updated;
18470c1e9d2aSVladimir Sementsov-Ogievskiy if (!qcow2_load_dirty_bitmaps(bs, &header_updated, errp)) {
1848d1258dd0SVladimir Sementsov-Ogievskiy ret = -EINVAL;
1849d1258dd0SVladimir Sementsov-Ogievskiy goto fail;
1850d1258dd0SVladimir Sementsov-Ogievskiy }
1851d1258dd0SVladimir Sementsov-Ogievskiy
185266be5c3eSTuguoyi update_header = update_header && !header_updated;
185366be5c3eSTuguoyi }
185466be5c3eSTuguoyi
1855d1258dd0SVladimir Sementsov-Ogievskiy if (update_header) {
1856af7b708dSStefan Hajnoczi ret = qcow2_update_header(bs);
1857af7b708dSStefan Hajnoczi if (ret < 0) {
18583ef6c40aSMax Reitz error_setg_errno(errp, -ret, "Could not update qcow2 header");
1859af7b708dSStefan Hajnoczi goto fail;
1860af7b708dSStefan Hajnoczi }
1861af7b708dSStefan Hajnoczi }
1862af7b708dSStefan Hajnoczi
18633b650816SKevin Wolf bs->supported_zero_flags = header.version >= 3 ?
18643b650816SKevin Wolf BDRV_REQ_MAY_UNMAP | BDRV_REQ_NO_FALLBACK : 0;
1865f01643fbSKevin Wolf bs->supported_truncate_flags = BDRV_REQ_ZERO_WRITE;
186668d100e9SKevin Wolf
1867c61d0004SStefan Hajnoczi /* Repair image if dirty */
1868307261b2SVladimir Sementsov-Ogievskiy if (!(flags & BDRV_O_CHECK) && bdrv_is_writable(bs) &&
1869058f8f16SStefan Hajnoczi (s->incompatible_features & QCOW2_INCOMPAT_DIRTY)) {
1870c61d0004SStefan Hajnoczi BdrvCheckResult result = {0};
1871c61d0004SStefan Hajnoczi
18722fd61638SPaolo Bonzini ret = qcow2_co_check_locked(bs, &result,
18732fd61638SPaolo Bonzini BDRV_FIX_ERRORS | BDRV_FIX_LEAKS);
1874791fff50SMax Reitz if (ret < 0 || result.check_errors) {
1875791fff50SMax Reitz if (ret >= 0) {
1876791fff50SMax Reitz ret = -EIO;
1877791fff50SMax Reitz }
18783ef6c40aSMax Reitz error_setg_errno(errp, -ret, "Could not repair dirty image");
1879c61d0004SStefan Hajnoczi goto fail;
1880c61d0004SStefan Hajnoczi }
1881c61d0004SStefan Hajnoczi }
1882c61d0004SStefan Hajnoczi
1883585f8587Sbellard #ifdef DEBUG_ALLOC
18846cbc3031SPhilipp Hahn {
18856cbc3031SPhilipp Hahn BdrvCheckResult result = {0};
1886b35278f7SStefan Hajnoczi qcow2_check_refcounts(bs, &result, 0);
18876cbc3031SPhilipp Hahn }
1888585f8587Sbellard #endif
1889ceb029cdSVladimir Sementsov-Ogievskiy
18906f13a316SVladimir Sementsov-Ogievskiy qemu_co_queue_init(&s->thread_task_queue);
1891ceb029cdSVladimir Sementsov-Ogievskiy
18926d85a57eSJes Sorensen return ret;
1893585f8587Sbellard
1894585f8587Sbellard fail:
18959b890bdcSKevin Wolf g_free(s->image_data_file);
189606e9cd19SHanna Reitz if (open_data_file && has_data_file(bs)) {
1897e3e31dc8SKevin Wolf bdrv_graph_co_rdunlock();
1898*b13f5465SFiona Ebner bdrv_drain_all_begin();
189932a8aba3SKevin Wolf bdrv_co_unref_child(bs, s->data_file);
1900*b13f5465SFiona Ebner bdrv_drain_all_end();
1901e3e31dc8SKevin Wolf bdrv_graph_co_rdlock();
1902808cf3cbSVladimir Sementsov-Ogievskiy s->data_file = NULL;
19030e8c08beSKevin Wolf }
19046744cbabSKevin Wolf g_free(s->unknown_header_fields);
190575bab85cSKevin Wolf cleanup_unknown_header_ext(bs);
1906ed6ccf0fSKevin Wolf qcow2_free_snapshots(bs);
1907ed6ccf0fSKevin Wolf qcow2_refcount_close(bs);
1908de82815dSKevin Wolf qemu_vfree(s->l1_table);
1909cf93980eSMax Reitz /* else pre-write overlap checks in cache_destroy may crash */
1910cf93980eSMax Reitz s->l1_table = NULL;
1911279621c0SAlberto Garcia cache_clean_timer_del(bs);
191229c1a730SKevin Wolf if (s->l2_table_cache) {
1913e64d4072SAlberto Garcia qcow2_cache_destroy(s->l2_table_cache);
191429c1a730SKevin Wolf }
1915c5a33ee9SPrasad Joshi if (s->refcount_block_cache) {
1916e64d4072SAlberto Garcia qcow2_cache_destroy(s->refcount_block_cache);
1917c5a33ee9SPrasad Joshi }
1918b25b387fSDaniel P. Berrange qcrypto_block_free(s->crypto);
1919b25b387fSDaniel P. Berrange qapi_free_QCryptoBlockOpenOptions(s->crypto_opts);
19206d85a57eSJes Sorensen return ret;
1921585f8587Sbellard }
1922585f8587Sbellard
19231fafcd93SPaolo Bonzini typedef struct QCow2OpenCo {
19241fafcd93SPaolo Bonzini BlockDriverState *bs;
19251fafcd93SPaolo Bonzini QDict *options;
19261fafcd93SPaolo Bonzini int flags;
19271fafcd93SPaolo Bonzini Error **errp;
19281fafcd93SPaolo Bonzini int ret;
19291fafcd93SPaolo Bonzini } QCow2OpenCo;
19301fafcd93SPaolo Bonzini
qcow2_open_entry(void * opaque)19311fafcd93SPaolo Bonzini static void coroutine_fn qcow2_open_entry(void *opaque)
19321fafcd93SPaolo Bonzini {
19331fafcd93SPaolo Bonzini QCow2OpenCo *qoc = opaque;
19341fafcd93SPaolo Bonzini BDRVQcow2State *s = qoc->bs->opaque;
19351fafcd93SPaolo Bonzini
19361a30b0f5SKevin Wolf GRAPH_RDLOCK_GUARD();
1937b9b10c35SKevin Wolf
19381fafcd93SPaolo Bonzini qemu_co_mutex_lock(&s->lock);
193906e9cd19SHanna Reitz qoc->ret = qcow2_do_open(qoc->bs, qoc->options, qoc->flags, true,
194006e9cd19SHanna Reitz qoc->errp);
19411fafcd93SPaolo Bonzini qemu_co_mutex_unlock(&s->lock);
1942aa269ff8SKevin Wolf
1943aa269ff8SKevin Wolf aio_wait_kick();
19441fafcd93SPaolo Bonzini }
19451fafcd93SPaolo Bonzini
qcow2_open(BlockDriverState * bs,QDict * options,int flags,Error ** errp)19464e4bf5c4SKevin Wolf static int qcow2_open(BlockDriverState *bs, QDict *options, int flags,
19474e4bf5c4SKevin Wolf Error **errp)
19484e4bf5c4SKevin Wolf {
19491fafcd93SPaolo Bonzini BDRVQcow2State *s = bs->opaque;
19501fafcd93SPaolo Bonzini QCow2OpenCo qoc = {
19511fafcd93SPaolo Bonzini .bs = bs,
19521fafcd93SPaolo Bonzini .options = options,
19531fafcd93SPaolo Bonzini .flags = flags,
19541fafcd93SPaolo Bonzini .errp = errp,
19551fafcd93SPaolo Bonzini .ret = -EINPROGRESS
19561fafcd93SPaolo Bonzini };
195783930780SVladimir Sementsov-Ogievskiy int ret;
19581fafcd93SPaolo Bonzini
195983930780SVladimir Sementsov-Ogievskiy ret = bdrv_open_file_child(NULL, options, "file", bs, errp);
196083930780SVladimir Sementsov-Ogievskiy if (ret < 0) {
196183930780SVladimir Sementsov-Ogievskiy return ret;
19624e4bf5c4SKevin Wolf }
19634e4bf5c4SKevin Wolf
19641fafcd93SPaolo Bonzini /* Initialise locks */
19651fafcd93SPaolo Bonzini qemu_co_mutex_init(&s->lock);
19661fafcd93SPaolo Bonzini
19671a30b0f5SKevin Wolf assert(!qemu_in_coroutine());
19684720cbeeSKevin Wolf assert(qemu_get_current_aio_context() == qemu_get_aio_context());
1969aa269ff8SKevin Wolf
1970aa269ff8SKevin Wolf aio_co_enter(bdrv_get_aio_context(bs),
1971aa269ff8SKevin Wolf qemu_coroutine_create(qcow2_open_entry, &qoc));
1972aa269ff8SKevin Wolf AIO_WAIT_WHILE_UNLOCKED(NULL, qoc.ret == -EINPROGRESS);
19731a30b0f5SKevin Wolf
19741fafcd93SPaolo Bonzini return qoc.ret;
19754e4bf5c4SKevin Wolf }
19764e4bf5c4SKevin Wolf
qcow2_refresh_limits(BlockDriverState * bs,Error ** errp)19773baca891SKevin Wolf static void qcow2_refresh_limits(BlockDriverState *bs, Error **errp)
1978d34682cdSKevin Wolf {
1979ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque;
1980d34682cdSKevin Wolf
19818e4ffb4eSKevin Wolf if (s->crypto) {
1982a84178ccSEric Blake /* Encryption works on a sector granularity */
19836f8f015cSAlberto Garcia bs->bl.request_alignment = qcrypto_block_get_sector_size(s->crypto);
1984a84178ccSEric Blake }
1985a6841a2dSAlberto Garcia bs->bl.pwrite_zeroes_alignment = s->subcluster_size;
1986ecdbead6SEric Blake bs->bl.pdiscard_alignment = s->cluster_size;
1987d34682cdSKevin Wolf }
1988d34682cdSKevin Wolf
19890bb79c97SKevin Wolf static int GRAPH_UNLOCKED
qcow2_reopen_prepare(BDRVReopenState * state,BlockReopenQueue * queue,Error ** errp)19900bb79c97SKevin Wolf qcow2_reopen_prepare(BDRVReopenState *state,BlockReopenQueue *queue,
19910bb79c97SKevin Wolf Error **errp)
199221d82ac9SJeff Cody {
1993bcfd86d6SKevin Wolf BDRVQcow2State *s = state->bs->opaque;
19945b0959a7SKevin Wolf Qcow2ReopenState *r;
19954c2e5f8fSKevin Wolf int ret;
19964c2e5f8fSKevin Wolf
19970bb79c97SKevin Wolf GLOBAL_STATE_CODE();
19980bb79c97SKevin Wolf GRAPH_RDLOCK_GUARD_MAINLOOP();
19990bb79c97SKevin Wolf
20005b0959a7SKevin Wolf r = g_new0(Qcow2ReopenState, 1);
20015b0959a7SKevin Wolf state->opaque = r;
20025b0959a7SKevin Wolf
20035b0959a7SKevin Wolf ret = qcow2_update_options_prepare(state->bs, r, state->options,
20045b0959a7SKevin Wolf state->flags, errp);
20055b0959a7SKevin Wolf if (ret < 0) {
20065b0959a7SKevin Wolf goto fail;
20075b0959a7SKevin Wolf }
20085b0959a7SKevin Wolf
20095b0959a7SKevin Wolf /* We need to write out any unwritten data if we reopen read-only. */
20104c2e5f8fSKevin Wolf if ((state->flags & BDRV_O_RDWR) == 0) {
2011169b8793SVladimir Sementsov-Ogievskiy ret = qcow2_reopen_bitmaps_ro(state->bs, errp);
2012169b8793SVladimir Sementsov-Ogievskiy if (ret < 0) {
2013169b8793SVladimir Sementsov-Ogievskiy goto fail;
2014169b8793SVladimir Sementsov-Ogievskiy }
2015169b8793SVladimir Sementsov-Ogievskiy
20164c2e5f8fSKevin Wolf ret = bdrv_flush(state->bs);
20174c2e5f8fSKevin Wolf if (ret < 0) {
20185b0959a7SKevin Wolf goto fail;
20194c2e5f8fSKevin Wolf }
20204c2e5f8fSKevin Wolf
20214c2e5f8fSKevin Wolf ret = qcow2_mark_clean(state->bs);
20224c2e5f8fSKevin Wolf if (ret < 0) {
20235b0959a7SKevin Wolf goto fail;
20244c2e5f8fSKevin Wolf }
20254c2e5f8fSKevin Wolf }
20264c2e5f8fSKevin Wolf
2027bcfd86d6SKevin Wolf /*
2028bcfd86d6SKevin Wolf * Without an external data file, s->data_file points to the same BdrvChild
2029bcfd86d6SKevin Wolf * as bs->file. It needs to be resynced after reopen because bs->file may
2030bcfd86d6SKevin Wolf * be changed. We can't use it in the meantime.
2031bcfd86d6SKevin Wolf */
2032bcfd86d6SKevin Wolf if (!has_data_file(state->bs)) {
2033bcfd86d6SKevin Wolf assert(s->data_file == state->bs->file);
2034bcfd86d6SKevin Wolf s->data_file = NULL;
2035bcfd86d6SKevin Wolf }
2036bcfd86d6SKevin Wolf
203721d82ac9SJeff Cody return 0;
20385b0959a7SKevin Wolf
20395b0959a7SKevin Wolf fail:
20405b0959a7SKevin Wolf qcow2_update_options_abort(state->bs, r);
20415b0959a7SKevin Wolf g_free(r);
20425b0959a7SKevin Wolf return ret;
20435b0959a7SKevin Wolf }
20445b0959a7SKevin Wolf
qcow2_reopen_commit(BDRVReopenState * state)20455b0959a7SKevin Wolf static void qcow2_reopen_commit(BDRVReopenState *state)
20465b0959a7SKevin Wolf {
2047bcfd86d6SKevin Wolf BDRVQcow2State *s = state->bs->opaque;
2048bcfd86d6SKevin Wolf
20498f897341SKevin Wolf GRAPH_RDLOCK_GUARD_MAINLOOP();
20508f897341SKevin Wolf
20515b0959a7SKevin Wolf qcow2_update_options_commit(state->bs, state->opaque);
2052bcfd86d6SKevin Wolf if (!s->data_file) {
2053bcfd86d6SKevin Wolf /*
2054bcfd86d6SKevin Wolf * If we don't have an external data file, s->data_file was cleared by
2055bcfd86d6SKevin Wolf * qcow2_reopen_prepare() and needs to be updated.
2056bcfd86d6SKevin Wolf */
2057bcfd86d6SKevin Wolf s->data_file = state->bs->file;
2058bcfd86d6SKevin Wolf }
205965eb7c85SPeter Krempa g_free(state->opaque);
206065eb7c85SPeter Krempa }
206165eb7c85SPeter Krempa
qcow2_reopen_commit_post(BDRVReopenState * state)206265eb7c85SPeter Krempa static void qcow2_reopen_commit_post(BDRVReopenState *state)
206365eb7c85SPeter Krempa {
20640bb79c97SKevin Wolf GRAPH_RDLOCK_GUARD_MAINLOOP();
20650bb79c97SKevin Wolf
20664dd09f62SVladimir Sementsov-Ogievskiy if (state->flags & BDRV_O_RDWR) {
20674dd09f62SVladimir Sementsov-Ogievskiy Error *local_err = NULL;
20684dd09f62SVladimir Sementsov-Ogievskiy
20694dd09f62SVladimir Sementsov-Ogievskiy if (qcow2_reopen_bitmaps_rw(state->bs, &local_err) < 0) {
20704dd09f62SVladimir Sementsov-Ogievskiy /*
20714dd09f62SVladimir Sementsov-Ogievskiy * This is not fatal, bitmaps just left read-only, so all following
20724dd09f62SVladimir Sementsov-Ogievskiy * writes will fail. User can remove read-only bitmaps to unblock
20734dd09f62SVladimir Sementsov-Ogievskiy * writes or retry reopen.
20744dd09f62SVladimir Sementsov-Ogievskiy */
20754dd09f62SVladimir Sementsov-Ogievskiy error_reportf_err(local_err,
20764dd09f62SVladimir Sementsov-Ogievskiy "%s: Failed to make dirty bitmaps writable: ",
20774dd09f62SVladimir Sementsov-Ogievskiy bdrv_get_node_name(state->bs));
20784dd09f62SVladimir Sementsov-Ogievskiy }
20794dd09f62SVladimir Sementsov-Ogievskiy }
20805b0959a7SKevin Wolf }
20815b0959a7SKevin Wolf
qcow2_reopen_abort(BDRVReopenState * state)20825b0959a7SKevin Wolf static void qcow2_reopen_abort(BDRVReopenState *state)
20835b0959a7SKevin Wolf {
2084bcfd86d6SKevin Wolf BDRVQcow2State *s = state->bs->opaque;
2085bcfd86d6SKevin Wolf
20868f897341SKevin Wolf GRAPH_RDLOCK_GUARD_MAINLOOP();
20878f897341SKevin Wolf
2088bcfd86d6SKevin Wolf if (!s->data_file) {
2089bcfd86d6SKevin Wolf /*
2090bcfd86d6SKevin Wolf * If we don't have an external data file, s->data_file was cleared by
2091bcfd86d6SKevin Wolf * qcow2_reopen_prepare() and needs to be restored.
2092bcfd86d6SKevin Wolf */
2093bcfd86d6SKevin Wolf s->data_file = state->bs->file;
2094bcfd86d6SKevin Wolf }
20955b0959a7SKevin Wolf qcow2_update_options_abort(state->bs, state->opaque);
20965b0959a7SKevin Wolf g_free(state->opaque);
209721d82ac9SJeff Cody }
209821d82ac9SJeff Cody
qcow2_join_options(QDict * options,QDict * old_options)20995365f44dSKevin Wolf static void qcow2_join_options(QDict *options, QDict *old_options)
21005365f44dSKevin Wolf {
21015365f44dSKevin Wolf bool has_new_overlap_template =
21025365f44dSKevin Wolf qdict_haskey(options, QCOW2_OPT_OVERLAP) ||
21035365f44dSKevin Wolf qdict_haskey(options, QCOW2_OPT_OVERLAP_TEMPLATE);
21045365f44dSKevin Wolf bool has_new_total_cache_size =
21055365f44dSKevin Wolf qdict_haskey(options, QCOW2_OPT_CACHE_SIZE);
21065365f44dSKevin Wolf bool has_all_cache_options;
21075365f44dSKevin Wolf
21085365f44dSKevin Wolf /* New overlap template overrides all old overlap options */
21095365f44dSKevin Wolf if (has_new_overlap_template) {
21105365f44dSKevin Wolf qdict_del(old_options, QCOW2_OPT_OVERLAP);
21115365f44dSKevin Wolf qdict_del(old_options, QCOW2_OPT_OVERLAP_TEMPLATE);
21125365f44dSKevin Wolf qdict_del(old_options, QCOW2_OPT_OVERLAP_MAIN_HEADER);
21135365f44dSKevin Wolf qdict_del(old_options, QCOW2_OPT_OVERLAP_ACTIVE_L1);
21145365f44dSKevin Wolf qdict_del(old_options, QCOW2_OPT_OVERLAP_ACTIVE_L2);
21155365f44dSKevin Wolf qdict_del(old_options, QCOW2_OPT_OVERLAP_REFCOUNT_TABLE);
21165365f44dSKevin Wolf qdict_del(old_options, QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK);
21175365f44dSKevin Wolf qdict_del(old_options, QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE);
21185365f44dSKevin Wolf qdict_del(old_options, QCOW2_OPT_OVERLAP_INACTIVE_L1);
21195365f44dSKevin Wolf qdict_del(old_options, QCOW2_OPT_OVERLAP_INACTIVE_L2);
21205365f44dSKevin Wolf }
21215365f44dSKevin Wolf
21225365f44dSKevin Wolf /* New total cache size overrides all old options */
21235365f44dSKevin Wolf if (qdict_haskey(options, QCOW2_OPT_CACHE_SIZE)) {
21245365f44dSKevin Wolf qdict_del(old_options, QCOW2_OPT_L2_CACHE_SIZE);
21255365f44dSKevin Wolf qdict_del(old_options, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
21265365f44dSKevin Wolf }
21275365f44dSKevin Wolf
21285365f44dSKevin Wolf qdict_join(options, old_options, false);
21295365f44dSKevin Wolf
21305365f44dSKevin Wolf /*
21315365f44dSKevin Wolf * If after merging all cache size options are set, an old total size is
21325365f44dSKevin Wolf * overwritten. Do keep all options, however, if all three are new. The
21335365f44dSKevin Wolf * resulting error message is what we want to happen.
21345365f44dSKevin Wolf */
21355365f44dSKevin Wolf has_all_cache_options =
21365365f44dSKevin Wolf qdict_haskey(options, QCOW2_OPT_CACHE_SIZE) ||
21375365f44dSKevin Wolf qdict_haskey(options, QCOW2_OPT_L2_CACHE_SIZE) ||
21385365f44dSKevin Wolf qdict_haskey(options, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
21395365f44dSKevin Wolf
21405365f44dSKevin Wolf if (has_all_cache_options && !has_new_total_cache_size) {
21415365f44dSKevin Wolf qdict_del(options, QCOW2_OPT_CACHE_SIZE);
21425365f44dSKevin Wolf }
21435365f44dSKevin Wolf }
21445365f44dSKevin Wolf
21450050c163SKevin Wolf static int coroutine_fn GRAPH_RDLOCK
qcow2_co_block_status(BlockDriverState * bs,unsigned int mode,int64_t offset,int64_t count,int64_t * pnum,int64_t * map,BlockDriverState ** file)2146c33159deSEric Blake qcow2_co_block_status(BlockDriverState *bs, unsigned int mode,
2147c33159deSEric Blake int64_t offset, int64_t count, int64_t *pnum,
2148c33159deSEric Blake int64_t *map, BlockDriverState **file)
2149585f8587Sbellard {
2150ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque;
2151388e5816SAlberto Garcia uint64_t host_offset;
2152ecfe1863SKevin Wolf unsigned int bytes;
215310dabdc5SAlberto Garcia QCow2SubclusterType type;
215474e60fb5SAlberto Garcia int ret, status = 0;
2155585f8587Sbellard
21565e978550SKevin Wolf qemu_co_mutex_lock(&s->lock);
21575e978550SKevin Wolf
215869f47505SVladimir Sementsov-Ogievskiy if (!s->metadata_preallocation_checked) {
215969f47505SVladimir Sementsov-Ogievskiy ret = qcow2_detect_metadata_preallocation(bs);
216069f47505SVladimir Sementsov-Ogievskiy s->metadata_preallocation = (ret == 1);
216169f47505SVladimir Sementsov-Ogievskiy s->metadata_preallocation_checked = true;
216269f47505SVladimir Sementsov-Ogievskiy }
216369f47505SVladimir Sementsov-Ogievskiy
2164a320fb04SEric Blake bytes = MIN(INT_MAX, count);
2165ca4a0bb8SAlberto Garcia ret = qcow2_get_host_offset(bs, offset, &bytes, &host_offset, &type);
2166f8a2e5e3SStefan Hajnoczi qemu_co_mutex_unlock(&s->lock);
21671c46efaaSKevin Wolf if (ret < 0) {
2168d663640cSPaolo Bonzini return ret;
21691c46efaaSKevin Wolf }
2170095a9c58Saliguori
2171a320fb04SEric Blake *pnum = bytes;
2172ecfe1863SKevin Wolf
217310dabdc5SAlberto Garcia if ((type == QCOW2_SUBCLUSTER_NORMAL ||
217497490a14SAlberto Garcia type == QCOW2_SUBCLUSTER_ZERO_ALLOC ||
217597490a14SAlberto Garcia type == QCOW2_SUBCLUSTER_UNALLOCATED_ALLOC) && !s->crypto) {
2176388e5816SAlberto Garcia *map = host_offset;
217737be1403SKevin Wolf *file = s->data_file->bs;
2178a320fb04SEric Blake status |= BDRV_BLOCK_OFFSET_VALID;
21794bc74be9SPaolo Bonzini }
218010dabdc5SAlberto Garcia if (type == QCOW2_SUBCLUSTER_ZERO_PLAIN ||
218110dabdc5SAlberto Garcia type == QCOW2_SUBCLUSTER_ZERO_ALLOC) {
21824bc74be9SPaolo Bonzini status |= BDRV_BLOCK_ZERO;
218397490a14SAlberto Garcia } else if (type != QCOW2_SUBCLUSTER_UNALLOCATED_PLAIN &&
218497490a14SAlberto Garcia type != QCOW2_SUBCLUSTER_UNALLOCATED_ALLOC) {
21854bc74be9SPaolo Bonzini status |= BDRV_BLOCK_DATA;
21864bc74be9SPaolo Bonzini }
218769f47505SVladimir Sementsov-Ogievskiy if (s->metadata_preallocation && (status & BDRV_BLOCK_DATA) &&
218869f47505SVladimir Sementsov-Ogievskiy (status & BDRV_BLOCK_OFFSET_VALID))
218969f47505SVladimir Sementsov-Ogievskiy {
219069f47505SVladimir Sementsov-Ogievskiy status |= BDRV_BLOCK_RECURSE;
219169f47505SVladimir Sementsov-Ogievskiy }
219228482891SAndrey Drobyshev via if (type == QCOW2_SUBCLUSTER_COMPRESSED) {
219328482891SAndrey Drobyshev via status |= BDRV_BLOCK_COMPRESSED;
219428482891SAndrey Drobyshev via }
21954bc74be9SPaolo Bonzini return status;
2196585f8587Sbellard }
2197585f8587Sbellard
21987b1fb72eSKevin Wolf static int coroutine_fn GRAPH_RDLOCK
qcow2_handle_l2meta(BlockDriverState * bs,QCowL2Meta ** pl2meta,bool link_l2)21997b1fb72eSKevin Wolf qcow2_handle_l2meta(BlockDriverState *bs, QCowL2Meta **pl2meta, bool link_l2)
2200fd9fcd37SFam Zheng {
2201fd9fcd37SFam Zheng int ret = 0;
2202fd9fcd37SFam Zheng QCowL2Meta *l2meta = *pl2meta;
2203fd9fcd37SFam Zheng
2204fd9fcd37SFam Zheng while (l2meta != NULL) {
2205fd9fcd37SFam Zheng QCowL2Meta *next;
2206fd9fcd37SFam Zheng
2207354d930dSFam Zheng if (link_l2) {
2208fd9fcd37SFam Zheng ret = qcow2_alloc_cluster_link_l2(bs, l2meta);
2209fd9fcd37SFam Zheng if (ret) {
2210fd9fcd37SFam Zheng goto out;
2211fd9fcd37SFam Zheng }
22128b24cd14SKevin Wolf } else {
22138b24cd14SKevin Wolf qcow2_alloc_cluster_abort(bs, l2meta);
2214fd9fcd37SFam Zheng }
2215fd9fcd37SFam Zheng
2216fd9fcd37SFam Zheng /* Take the request off the list of running requests */
2217fd9fcd37SFam Zheng QLIST_REMOVE(l2meta, next_in_flight);
2218fd9fcd37SFam Zheng
2219fd9fcd37SFam Zheng qemu_co_queue_restart_all(&l2meta->dependent_requests);
2220fd9fcd37SFam Zheng
2221fd9fcd37SFam Zheng next = l2meta->next;
2222fd9fcd37SFam Zheng g_free(l2meta);
2223fd9fcd37SFam Zheng l2meta = next;
2224fd9fcd37SFam Zheng }
2225fd9fcd37SFam Zheng out:
2226fd9fcd37SFam Zheng *pl2meta = l2meta;
2227fd9fcd37SFam Zheng return ret;
2228fd9fcd37SFam Zheng }
2229fd9fcd37SFam Zheng
2230b9b10c35SKevin Wolf static int coroutine_fn GRAPH_RDLOCK
qcow2_co_preadv_encrypted(BlockDriverState * bs,uint64_t host_offset,uint64_t offset,uint64_t bytes,QEMUIOVector * qiov,uint64_t qiov_offset)223188f468e5SVladimir Sementsov-Ogievskiy qcow2_co_preadv_encrypted(BlockDriverState *bs,
22329c4269d5SAlberto Garcia uint64_t host_offset,
223388f468e5SVladimir Sementsov-Ogievskiy uint64_t offset,
223488f468e5SVladimir Sementsov-Ogievskiy uint64_t bytes,
223588f468e5SVladimir Sementsov-Ogievskiy QEMUIOVector *qiov,
223688f468e5SVladimir Sementsov-Ogievskiy uint64_t qiov_offset)
223788f468e5SVladimir Sementsov-Ogievskiy {
223888f468e5SVladimir Sementsov-Ogievskiy int ret;
223988f468e5SVladimir Sementsov-Ogievskiy BDRVQcow2State *s = bs->opaque;
224088f468e5SVladimir Sementsov-Ogievskiy uint8_t *buf;
224188f468e5SVladimir Sementsov-Ogievskiy
224288f468e5SVladimir Sementsov-Ogievskiy assert(bs->encrypted && s->crypto);
224388f468e5SVladimir Sementsov-Ogievskiy assert(bytes <= QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
224488f468e5SVladimir Sementsov-Ogievskiy
224588f468e5SVladimir Sementsov-Ogievskiy /*
224688f468e5SVladimir Sementsov-Ogievskiy * For encrypted images, read everything into a temporary
224788f468e5SVladimir Sementsov-Ogievskiy * contiguous buffer on which the AES functions can work.
224888f468e5SVladimir Sementsov-Ogievskiy * Also, decryption in a separate buffer is better as it
224988f468e5SVladimir Sementsov-Ogievskiy * prevents the guest from learning information about the
225088f468e5SVladimir Sementsov-Ogievskiy * encrypted nature of the virtual disk.
225188f468e5SVladimir Sementsov-Ogievskiy */
225288f468e5SVladimir Sementsov-Ogievskiy
225388f468e5SVladimir Sementsov-Ogievskiy buf = qemu_try_blockalign(s->data_file->bs, bytes);
225488f468e5SVladimir Sementsov-Ogievskiy if (buf == NULL) {
225588f468e5SVladimir Sementsov-Ogievskiy return -ENOMEM;
225688f468e5SVladimir Sementsov-Ogievskiy }
225788f468e5SVladimir Sementsov-Ogievskiy
225817362398SPaolo Bonzini BLKDBG_CO_EVENT(bs->file, BLKDBG_READ_AIO);
22599c4269d5SAlberto Garcia ret = bdrv_co_pread(s->data_file, host_offset, bytes, buf, 0);
226088f468e5SVladimir Sementsov-Ogievskiy if (ret < 0) {
226188f468e5SVladimir Sementsov-Ogievskiy goto fail;
226288f468e5SVladimir Sementsov-Ogievskiy }
226388f468e5SVladimir Sementsov-Ogievskiy
22649c4269d5SAlberto Garcia if (qcow2_co_decrypt(bs, host_offset, offset, buf, bytes) < 0)
226588f468e5SVladimir Sementsov-Ogievskiy {
226688f468e5SVladimir Sementsov-Ogievskiy ret = -EIO;
226788f468e5SVladimir Sementsov-Ogievskiy goto fail;
226888f468e5SVladimir Sementsov-Ogievskiy }
226988f468e5SVladimir Sementsov-Ogievskiy qemu_iovec_from_buf(qiov, qiov_offset, buf, bytes);
227088f468e5SVladimir Sementsov-Ogievskiy
227188f468e5SVladimir Sementsov-Ogievskiy fail:
227288f468e5SVladimir Sementsov-Ogievskiy qemu_vfree(buf);
227388f468e5SVladimir Sementsov-Ogievskiy
227488f468e5SVladimir Sementsov-Ogievskiy return ret;
227588f468e5SVladimir Sementsov-Ogievskiy }
227688f468e5SVladimir Sementsov-Ogievskiy
2277d710cf57SVladimir Sementsov-Ogievskiy typedef struct Qcow2AioTask {
2278d710cf57SVladimir Sementsov-Ogievskiy AioTask task;
2279d710cf57SVladimir Sementsov-Ogievskiy
2280d710cf57SVladimir Sementsov-Ogievskiy BlockDriverState *bs;
228110dabdc5SAlberto Garcia QCow2SubclusterType subcluster_type; /* only for read */
22829a3978a4SVladimir Sementsov-Ogievskiy uint64_t host_offset; /* or l2_entry for compressed read */
2283d710cf57SVladimir Sementsov-Ogievskiy uint64_t offset;
2284d710cf57SVladimir Sementsov-Ogievskiy uint64_t bytes;
2285d710cf57SVladimir Sementsov-Ogievskiy QEMUIOVector *qiov;
2286d710cf57SVladimir Sementsov-Ogievskiy uint64_t qiov_offset;
2287d710cf57SVladimir Sementsov-Ogievskiy QCowL2Meta *l2meta; /* only for write */
2288d710cf57SVladimir Sementsov-Ogievskiy } Qcow2AioTask;
2289d710cf57SVladimir Sementsov-Ogievskiy
2290d710cf57SVladimir Sementsov-Ogievskiy static coroutine_fn int qcow2_co_preadv_task_entry(AioTask *task);
qcow2_add_task(BlockDriverState * bs,AioTaskPool * pool,AioTaskFunc func,QCow2SubclusterType subcluster_type,uint64_t host_offset,uint64_t offset,uint64_t bytes,QEMUIOVector * qiov,size_t qiov_offset,QCowL2Meta * l2meta)2291d710cf57SVladimir Sementsov-Ogievskiy static coroutine_fn int qcow2_add_task(BlockDriverState *bs,
2292d710cf57SVladimir Sementsov-Ogievskiy AioTaskPool *pool,
2293d710cf57SVladimir Sementsov-Ogievskiy AioTaskFunc func,
229410dabdc5SAlberto Garcia QCow2SubclusterType subcluster_type,
22959c4269d5SAlberto Garcia uint64_t host_offset,
2296d710cf57SVladimir Sementsov-Ogievskiy uint64_t offset,
2297d710cf57SVladimir Sementsov-Ogievskiy uint64_t bytes,
2298d710cf57SVladimir Sementsov-Ogievskiy QEMUIOVector *qiov,
2299d710cf57SVladimir Sementsov-Ogievskiy size_t qiov_offset,
2300d710cf57SVladimir Sementsov-Ogievskiy QCowL2Meta *l2meta)
2301d710cf57SVladimir Sementsov-Ogievskiy {
2302d710cf57SVladimir Sementsov-Ogievskiy Qcow2AioTask local_task;
2303d710cf57SVladimir Sementsov-Ogievskiy Qcow2AioTask *task = pool ? g_new(Qcow2AioTask, 1) : &local_task;
2304d710cf57SVladimir Sementsov-Ogievskiy
2305d710cf57SVladimir Sementsov-Ogievskiy *task = (Qcow2AioTask) {
2306d710cf57SVladimir Sementsov-Ogievskiy .task.func = func,
2307d710cf57SVladimir Sementsov-Ogievskiy .bs = bs,
230810dabdc5SAlberto Garcia .subcluster_type = subcluster_type,
2309d710cf57SVladimir Sementsov-Ogievskiy .qiov = qiov,
23109c4269d5SAlberto Garcia .host_offset = host_offset,
2311d710cf57SVladimir Sementsov-Ogievskiy .offset = offset,
2312d710cf57SVladimir Sementsov-Ogievskiy .bytes = bytes,
2313d710cf57SVladimir Sementsov-Ogievskiy .qiov_offset = qiov_offset,
2314d710cf57SVladimir Sementsov-Ogievskiy .l2meta = l2meta,
2315d710cf57SVladimir Sementsov-Ogievskiy };
2316d710cf57SVladimir Sementsov-Ogievskiy
2317d710cf57SVladimir Sementsov-Ogievskiy trace_qcow2_add_task(qemu_coroutine_self(), bs, pool,
2318d710cf57SVladimir Sementsov-Ogievskiy func == qcow2_co_preadv_task_entry ? "read" : "write",
231910dabdc5SAlberto Garcia subcluster_type, host_offset, offset, bytes,
2320d710cf57SVladimir Sementsov-Ogievskiy qiov, qiov_offset);
2321d710cf57SVladimir Sementsov-Ogievskiy
2322d710cf57SVladimir Sementsov-Ogievskiy if (!pool) {
2323d710cf57SVladimir Sementsov-Ogievskiy return func(&task->task);
2324d710cf57SVladimir Sementsov-Ogievskiy }
2325d710cf57SVladimir Sementsov-Ogievskiy
2326d710cf57SVladimir Sementsov-Ogievskiy aio_task_pool_start_task(pool, &task->task);
2327d710cf57SVladimir Sementsov-Ogievskiy
2328d710cf57SVladimir Sementsov-Ogievskiy return 0;
2329d710cf57SVladimir Sementsov-Ogievskiy }
2330d710cf57SVladimir Sementsov-Ogievskiy
2331b9b10c35SKevin Wolf static int coroutine_fn GRAPH_RDLOCK
qcow2_co_preadv_task(BlockDriverState * bs,QCow2SubclusterType subc_type,uint64_t host_offset,uint64_t offset,uint64_t bytes,QEMUIOVector * qiov,size_t qiov_offset)2332b9b10c35SKevin Wolf qcow2_co_preadv_task(BlockDriverState *bs, QCow2SubclusterType subc_type,
2333b9b10c35SKevin Wolf uint64_t host_offset, uint64_t offset, uint64_t bytes,
2334b9b10c35SKevin Wolf QEMUIOVector *qiov, size_t qiov_offset)
233588f468e5SVladimir Sementsov-Ogievskiy {
233688f468e5SVladimir Sementsov-Ogievskiy BDRVQcow2State *s = bs->opaque;
233788f468e5SVladimir Sementsov-Ogievskiy
233810dabdc5SAlberto Garcia switch (subc_type) {
233910dabdc5SAlberto Garcia case QCOW2_SUBCLUSTER_ZERO_PLAIN:
234010dabdc5SAlberto Garcia case QCOW2_SUBCLUSTER_ZERO_ALLOC:
234188f468e5SVladimir Sementsov-Ogievskiy /* Both zero types are handled in qcow2_co_preadv_part */
234288f468e5SVladimir Sementsov-Ogievskiy g_assert_not_reached();
234388f468e5SVladimir Sementsov-Ogievskiy
234410dabdc5SAlberto Garcia case QCOW2_SUBCLUSTER_UNALLOCATED_PLAIN:
234597490a14SAlberto Garcia case QCOW2_SUBCLUSTER_UNALLOCATED_ALLOC:
234688f468e5SVladimir Sementsov-Ogievskiy assert(bs->backing); /* otherwise handled in qcow2_co_preadv_part */
234788f468e5SVladimir Sementsov-Ogievskiy
234817362398SPaolo Bonzini BLKDBG_CO_EVENT(bs->file, BLKDBG_READ_BACKING_AIO);
234988f468e5SVladimir Sementsov-Ogievskiy return bdrv_co_preadv_part(bs->backing, offset, bytes,
235088f468e5SVladimir Sementsov-Ogievskiy qiov, qiov_offset, 0);
235188f468e5SVladimir Sementsov-Ogievskiy
235210dabdc5SAlberto Garcia case QCOW2_SUBCLUSTER_COMPRESSED:
23539c4269d5SAlberto Garcia return qcow2_co_preadv_compressed(bs, host_offset,
235488f468e5SVladimir Sementsov-Ogievskiy offset, bytes, qiov, qiov_offset);
235588f468e5SVladimir Sementsov-Ogievskiy
235610dabdc5SAlberto Garcia case QCOW2_SUBCLUSTER_NORMAL:
235788f468e5SVladimir Sementsov-Ogievskiy if (bs->encrypted) {
23589c4269d5SAlberto Garcia return qcow2_co_preadv_encrypted(bs, host_offset,
235988f468e5SVladimir Sementsov-Ogievskiy offset, bytes, qiov, qiov_offset);
236088f468e5SVladimir Sementsov-Ogievskiy }
236188f468e5SVladimir Sementsov-Ogievskiy
236217362398SPaolo Bonzini BLKDBG_CO_EVENT(bs->file, BLKDBG_READ_AIO);
23639c4269d5SAlberto Garcia return bdrv_co_preadv_part(s->data_file, host_offset,
236488f468e5SVladimir Sementsov-Ogievskiy bytes, qiov, qiov_offset, 0);
236588f468e5SVladimir Sementsov-Ogievskiy
236688f468e5SVladimir Sementsov-Ogievskiy default:
236788f468e5SVladimir Sementsov-Ogievskiy g_assert_not_reached();
236888f468e5SVladimir Sementsov-Ogievskiy }
236988f468e5SVladimir Sementsov-Ogievskiy
237088f468e5SVladimir Sementsov-Ogievskiy g_assert_not_reached();
237188f468e5SVladimir Sementsov-Ogievskiy }
237288f468e5SVladimir Sementsov-Ogievskiy
2373b9b10c35SKevin Wolf /*
2374b9b10c35SKevin Wolf * This function can count as GRAPH_RDLOCK because qcow2_co_preadv_part() holds
2375b9b10c35SKevin Wolf * the graph lock and keeps it until this coroutine has terminated.
2376b9b10c35SKevin Wolf */
qcow2_co_preadv_task_entry(AioTask * task)2377b9b10c35SKevin Wolf static int coroutine_fn GRAPH_RDLOCK qcow2_co_preadv_task_entry(AioTask *task)
2378d710cf57SVladimir Sementsov-Ogievskiy {
2379d710cf57SVladimir Sementsov-Ogievskiy Qcow2AioTask *t = container_of(task, Qcow2AioTask, task);
2380d710cf57SVladimir Sementsov-Ogievskiy
2381d710cf57SVladimir Sementsov-Ogievskiy assert(!t->l2meta);
2382d710cf57SVladimir Sementsov-Ogievskiy
238310dabdc5SAlberto Garcia return qcow2_co_preadv_task(t->bs, t->subcluster_type,
238410dabdc5SAlberto Garcia t->host_offset, t->offset, t->bytes,
238510dabdc5SAlberto Garcia t->qiov, t->qiov_offset);
2386d710cf57SVladimir Sementsov-Ogievskiy }
2387d710cf57SVladimir Sementsov-Ogievskiy
2388b9b10c35SKevin Wolf static int coroutine_fn GRAPH_RDLOCK
qcow2_co_preadv_part(BlockDriverState * bs,int64_t offset,int64_t bytes,QEMUIOVector * qiov,size_t qiov_offset,BdrvRequestFlags flags)2389b9b10c35SKevin Wolf qcow2_co_preadv_part(BlockDriverState *bs, int64_t offset, int64_t bytes,
2390b9b10c35SKevin Wolf QEMUIOVector *qiov, size_t qiov_offset,
2391f7ef38ddSVladimir Sementsov-Ogievskiy BdrvRequestFlags flags)
23921490791fSaliguori {
2393ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque;
2394d710cf57SVladimir Sementsov-Ogievskiy int ret = 0;
2395ecfe1863SKevin Wolf unsigned int cur_bytes; /* number of bytes in current iteration */
2396388e5816SAlberto Garcia uint64_t host_offset = 0;
239710dabdc5SAlberto Garcia QCow2SubclusterType type;
2398d710cf57SVladimir Sementsov-Ogievskiy AioTaskPool *aio = NULL;
2399585f8587Sbellard
2400d710cf57SVladimir Sementsov-Ogievskiy while (bytes != 0 && aio_task_pool_status(aio) == 0) {
2401faf575c1SFrediano Ziglio /* prepare next request */
2402ecfe1863SKevin Wolf cur_bytes = MIN(bytes, INT_MAX);
2403b25b387fSDaniel P. Berrange if (s->crypto) {
2404ecfe1863SKevin Wolf cur_bytes = MIN(cur_bytes,
2405ecfe1863SKevin Wolf QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
2406bd28f835SKevin Wolf }
2407bd28f835SKevin Wolf
2408f24196d3SVladimir Sementsov-Ogievskiy qemu_co_mutex_lock(&s->lock);
2409ca4a0bb8SAlberto Garcia ret = qcow2_get_host_offset(bs, offset, &cur_bytes,
2410ca4a0bb8SAlberto Garcia &host_offset, &type);
2411f24196d3SVladimir Sementsov-Ogievskiy qemu_co_mutex_unlock(&s->lock);
24121c46efaaSKevin Wolf if (ret < 0) {
2413d710cf57SVladimir Sementsov-Ogievskiy goto out;
24141c46efaaSKevin Wolf }
24151c46efaaSKevin Wolf
241610dabdc5SAlberto Garcia if (type == QCOW2_SUBCLUSTER_ZERO_PLAIN ||
241710dabdc5SAlberto Garcia type == QCOW2_SUBCLUSTER_ZERO_ALLOC ||
241897490a14SAlberto Garcia (type == QCOW2_SUBCLUSTER_UNALLOCATED_PLAIN && !bs->backing) ||
241997490a14SAlberto Garcia (type == QCOW2_SUBCLUSTER_UNALLOCATED_ALLOC && !bs->backing))
242088f468e5SVladimir Sementsov-Ogievskiy {
242188f468e5SVladimir Sementsov-Ogievskiy qemu_iovec_memset(qiov, qiov_offset, 0, cur_bytes);
2422a9465922Sbellard } else {
2423d710cf57SVladimir Sementsov-Ogievskiy if (!aio && cur_bytes != bytes) {
2424d710cf57SVladimir Sementsov-Ogievskiy aio = aio_task_pool_new(QCOW2_MAX_WORKERS);
2425d710cf57SVladimir Sementsov-Ogievskiy }
2426ca4a0bb8SAlberto Garcia ret = qcow2_add_task(bs, aio, qcow2_co_preadv_task_entry, type,
24279c4269d5SAlberto Garcia host_offset, offset, cur_bytes,
2428d710cf57SVladimir Sementsov-Ogievskiy qiov, qiov_offset, NULL);
24298af36488SKevin Wolf if (ret < 0) {
2430d710cf57SVladimir Sementsov-Ogievskiy goto out;
24318af36488SKevin Wolf }
2432faf575c1SFrediano Ziglio }
2433faf575c1SFrediano Ziglio
2434ecfe1863SKevin Wolf bytes -= cur_bytes;
2435ecfe1863SKevin Wolf offset += cur_bytes;
2436df893d25SVladimir Sementsov-Ogievskiy qiov_offset += cur_bytes;
24375ebaa27eSFrediano Ziglio }
2438f141eafeSaliguori
2439d710cf57SVladimir Sementsov-Ogievskiy out:
2440d710cf57SVladimir Sementsov-Ogievskiy if (aio) {
2441d710cf57SVladimir Sementsov-Ogievskiy aio_task_pool_wait_all(aio);
2442d710cf57SVladimir Sementsov-Ogievskiy if (ret == 0) {
2443d710cf57SVladimir Sementsov-Ogievskiy ret = aio_task_pool_status(aio);
2444d710cf57SVladimir Sementsov-Ogievskiy }
2445d710cf57SVladimir Sementsov-Ogievskiy g_free(aio);
2446d710cf57SVladimir Sementsov-Ogievskiy }
2447d710cf57SVladimir Sementsov-Ogievskiy
2448d710cf57SVladimir Sementsov-Ogievskiy return ret;
2449585f8587Sbellard }
2450585f8587Sbellard
2451ee22a9d8SAlberto Garcia /* Check if it's possible to merge a write request with the writing of
2452ee22a9d8SAlberto Garcia * the data from the COW regions */
merge_cow(uint64_t offset,unsigned bytes,QEMUIOVector * qiov,size_t qiov_offset,QCowL2Meta * l2meta)2453ee22a9d8SAlberto Garcia static bool merge_cow(uint64_t offset, unsigned bytes,
24545396234bSVladimir Sementsov-Ogievskiy QEMUIOVector *qiov, size_t qiov_offset,
24555396234bSVladimir Sementsov-Ogievskiy QCowL2Meta *l2meta)
2456ee22a9d8SAlberto Garcia {
2457ee22a9d8SAlberto Garcia QCowL2Meta *m;
2458ee22a9d8SAlberto Garcia
2459ee22a9d8SAlberto Garcia for (m = l2meta; m != NULL; m = m->next) {
2460ee22a9d8SAlberto Garcia /* If both COW regions are empty then there's nothing to merge */
2461ee22a9d8SAlberto Garcia if (m->cow_start.nb_bytes == 0 && m->cow_end.nb_bytes == 0) {
2462ee22a9d8SAlberto Garcia continue;
2463ee22a9d8SAlberto Garcia }
2464ee22a9d8SAlberto Garcia
2465c8bb23cbSAnton Nefedov /* If COW regions are handled already, skip this too */
2466c8bb23cbSAnton Nefedov if (m->skip_cow) {
2467c8bb23cbSAnton Nefedov continue;
2468c8bb23cbSAnton Nefedov }
2469c8bb23cbSAnton Nefedov
24703441ad4bSAlberto Garcia /*
24713441ad4bSAlberto Garcia * The write request should start immediately after the first
24723441ad4bSAlberto Garcia * COW region. This does not always happen because the area
24733441ad4bSAlberto Garcia * touched by the request can be larger than the one defined
24743441ad4bSAlberto Garcia * by @m (a single request can span an area consisting of a
24753441ad4bSAlberto Garcia * mix of previously unallocated and allocated clusters, that
24763441ad4bSAlberto Garcia * is why @l2meta is a list).
24773441ad4bSAlberto Garcia */
2478ee22a9d8SAlberto Garcia if (l2meta_cow_start(m) + m->cow_start.nb_bytes != offset) {
24793441ad4bSAlberto Garcia /* In this case the request starts before this region */
24803441ad4bSAlberto Garcia assert(offset < l2meta_cow_start(m));
24813441ad4bSAlberto Garcia assert(m->cow_start.nb_bytes == 0);
2482ee22a9d8SAlberto Garcia continue;
2483ee22a9d8SAlberto Garcia }
2484ee22a9d8SAlberto Garcia
24853441ad4bSAlberto Garcia /* The write request should end immediately before the second
24863441ad4bSAlberto Garcia * COW region (see above for why it does not always happen) */
2487ee22a9d8SAlberto Garcia if (m->offset + m->cow_end.offset != offset + bytes) {
24883441ad4bSAlberto Garcia assert(offset + bytes > m->offset + m->cow_end.offset);
24893441ad4bSAlberto Garcia assert(m->cow_end.nb_bytes == 0);
2490ee22a9d8SAlberto Garcia continue;
2491ee22a9d8SAlberto Garcia }
2492ee22a9d8SAlberto Garcia
2493ee22a9d8SAlberto Garcia /* Make sure that adding both COW regions to the QEMUIOVector
2494ee22a9d8SAlberto Garcia * does not exceed IOV_MAX */
24955396234bSVladimir Sementsov-Ogievskiy if (qemu_iovec_subvec_niov(qiov, qiov_offset, bytes) > IOV_MAX - 2) {
2496ee22a9d8SAlberto Garcia continue;
2497ee22a9d8SAlberto Garcia }
2498ee22a9d8SAlberto Garcia
24995396234bSVladimir Sementsov-Ogievskiy m->data_qiov = qiov;
25005396234bSVladimir Sementsov-Ogievskiy m->data_qiov_offset = qiov_offset;
2501ee22a9d8SAlberto Garcia return true;
2502ee22a9d8SAlberto Garcia }
2503ee22a9d8SAlberto Garcia
2504ee22a9d8SAlberto Garcia return false;
2505ee22a9d8SAlberto Garcia }
2506ee22a9d8SAlberto Garcia
250746cd1e8aSAlberto Garcia /*
250846cd1e8aSAlberto Garcia * Return 1 if the COW regions read as zeroes, 0 if not, < 0 on error.
250946cd1e8aSAlberto Garcia * Note that returning 0 does not guarantee non-zero data.
251046cd1e8aSAlberto Garcia */
2511abaf8b75SKevin Wolf static int coroutine_fn GRAPH_RDLOCK
is_zero_cow(BlockDriverState * bs,QCowL2Meta * m)2512abaf8b75SKevin Wolf is_zero_cow(BlockDriverState *bs, QCowL2Meta *m)
2513c8bb23cbSAnton Nefedov {
2514c8bb23cbSAnton Nefedov /*
2515c8bb23cbSAnton Nefedov * This check is designed for optimization shortcut so it must be
2516c8bb23cbSAnton Nefedov * efficient.
251746cd1e8aSAlberto Garcia * Instead of is_zero(), use bdrv_co_is_zero_fast() as it is
251846cd1e8aSAlberto Garcia * faster (but not as accurate and can result in false negatives).
2519c8bb23cbSAnton Nefedov */
252046cd1e8aSAlberto Garcia int ret = bdrv_co_is_zero_fast(bs, m->offset + m->cow_start.offset,
252146cd1e8aSAlberto Garcia m->cow_start.nb_bytes);
252246cd1e8aSAlberto Garcia if (ret <= 0) {
252346cd1e8aSAlberto Garcia return ret;
252446cd1e8aSAlberto Garcia }
252546cd1e8aSAlberto Garcia
252646cd1e8aSAlberto Garcia return bdrv_co_is_zero_fast(bs, m->offset + m->cow_end.offset,
2527c8bb23cbSAnton Nefedov m->cow_end.nb_bytes);
2528c8bb23cbSAnton Nefedov }
2529c8bb23cbSAnton Nefedov
2530abaf8b75SKevin Wolf static int coroutine_fn GRAPH_RDLOCK
handle_alloc_space(BlockDriverState * bs,QCowL2Meta * l2meta)2531abaf8b75SKevin Wolf handle_alloc_space(BlockDriverState *bs, QCowL2Meta *l2meta)
2532c8bb23cbSAnton Nefedov {
2533c8bb23cbSAnton Nefedov BDRVQcow2State *s = bs->opaque;
2534c8bb23cbSAnton Nefedov QCowL2Meta *m;
2535c8bb23cbSAnton Nefedov
2536c8bb23cbSAnton Nefedov if (!(s->data_file->bs->supported_zero_flags & BDRV_REQ_NO_FALLBACK)) {
2537c8bb23cbSAnton Nefedov return 0;
2538c8bb23cbSAnton Nefedov }
2539c8bb23cbSAnton Nefedov
2540c8bb23cbSAnton Nefedov if (bs->encrypted) {
2541c8bb23cbSAnton Nefedov return 0;
2542c8bb23cbSAnton Nefedov }
2543c8bb23cbSAnton Nefedov
2544c8bb23cbSAnton Nefedov for (m = l2meta; m != NULL; m = m->next) {
2545c8bb23cbSAnton Nefedov int ret;
2546bf4a66eeSAlberto Garcia uint64_t start_offset = m->alloc_offset + m->cow_start.offset;
2547bf4a66eeSAlberto Garcia unsigned nb_bytes = m->cow_end.offset + m->cow_end.nb_bytes -
2548bf4a66eeSAlberto Garcia m->cow_start.offset;
2549c8bb23cbSAnton Nefedov
2550c8bb23cbSAnton Nefedov if (!m->cow_start.nb_bytes && !m->cow_end.nb_bytes) {
2551c8bb23cbSAnton Nefedov continue;
2552c8bb23cbSAnton Nefedov }
2553c8bb23cbSAnton Nefedov
255446cd1e8aSAlberto Garcia ret = is_zero_cow(bs, m);
255546cd1e8aSAlberto Garcia if (ret < 0) {
255646cd1e8aSAlberto Garcia return ret;
255746cd1e8aSAlberto Garcia } else if (ret == 0) {
2558c8bb23cbSAnton Nefedov continue;
2559c8bb23cbSAnton Nefedov }
2560c8bb23cbSAnton Nefedov
2561c8bb23cbSAnton Nefedov /*
2562c8bb23cbSAnton Nefedov * instead of writing zero COW buffers,
2563c8bb23cbSAnton Nefedov * efficiently zero out the whole clusters
2564c8bb23cbSAnton Nefedov */
2565c8bb23cbSAnton Nefedov
2566bf4a66eeSAlberto Garcia ret = qcow2_pre_write_overlap_check(bs, 0, start_offset, nb_bytes,
2567c8bb23cbSAnton Nefedov true);
2568c8bb23cbSAnton Nefedov if (ret < 0) {
2569c8bb23cbSAnton Nefedov return ret;
2570c8bb23cbSAnton Nefedov }
2571c8bb23cbSAnton Nefedov
257217362398SPaolo Bonzini BLKDBG_CO_EVENT(bs->file, BLKDBG_CLUSTER_ALLOC_SPACE);
2573bf4a66eeSAlberto Garcia ret = bdrv_co_pwrite_zeroes(s->data_file, start_offset, nb_bytes,
2574c8bb23cbSAnton Nefedov BDRV_REQ_NO_FALLBACK);
2575c8bb23cbSAnton Nefedov if (ret < 0) {
2576c8bb23cbSAnton Nefedov if (ret != -ENOTSUP && ret != -EAGAIN) {
2577c8bb23cbSAnton Nefedov return ret;
2578c8bb23cbSAnton Nefedov }
2579c8bb23cbSAnton Nefedov continue;
2580c8bb23cbSAnton Nefedov }
2581c8bb23cbSAnton Nefedov
2582c8bb23cbSAnton Nefedov trace_qcow2_skip_cow(qemu_coroutine_self(), m->offset, m->nb_clusters);
2583c8bb23cbSAnton Nefedov m->skip_cow = true;
2584c8bb23cbSAnton Nefedov }
2585c8bb23cbSAnton Nefedov return 0;
2586c8bb23cbSAnton Nefedov }
2587c8bb23cbSAnton Nefedov
25886aa7a263SVladimir Sementsov-Ogievskiy /*
25896aa7a263SVladimir Sementsov-Ogievskiy * qcow2_co_pwritev_task
25906aa7a263SVladimir Sementsov-Ogievskiy * Called with s->lock unlocked
25916aa7a263SVladimir Sementsov-Ogievskiy * l2meta - if not NULL, qcow2_co_pwritev_task() will consume it. Caller must
25926aa7a263SVladimir Sementsov-Ogievskiy * not use it somehow after qcow2_co_pwritev_task() call
25936aa7a263SVladimir Sementsov-Ogievskiy */
2594abaf8b75SKevin Wolf static coroutine_fn GRAPH_RDLOCK
qcow2_co_pwritev_task(BlockDriverState * bs,uint64_t host_offset,uint64_t offset,uint64_t bytes,QEMUIOVector * qiov,uint64_t qiov_offset,QCowL2Meta * l2meta)2595abaf8b75SKevin Wolf int qcow2_co_pwritev_task(BlockDriverState *bs, uint64_t host_offset,
2596abaf8b75SKevin Wolf uint64_t offset, uint64_t bytes, QEMUIOVector *qiov,
2597abaf8b75SKevin Wolf uint64_t qiov_offset, QCowL2Meta *l2meta)
25986aa7a263SVladimir Sementsov-Ogievskiy {
25996aa7a263SVladimir Sementsov-Ogievskiy int ret;
26006aa7a263SVladimir Sementsov-Ogievskiy BDRVQcow2State *s = bs->opaque;
26016aa7a263SVladimir Sementsov-Ogievskiy void *crypt_buf = NULL;
26026aa7a263SVladimir Sementsov-Ogievskiy QEMUIOVector encrypted_qiov;
26036aa7a263SVladimir Sementsov-Ogievskiy
26046aa7a263SVladimir Sementsov-Ogievskiy if (bs->encrypted) {
26056aa7a263SVladimir Sementsov-Ogievskiy assert(s->crypto);
26066aa7a263SVladimir Sementsov-Ogievskiy assert(bytes <= QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
26076aa7a263SVladimir Sementsov-Ogievskiy crypt_buf = qemu_try_blockalign(bs->file->bs, bytes);
26086aa7a263SVladimir Sementsov-Ogievskiy if (crypt_buf == NULL) {
26096aa7a263SVladimir Sementsov-Ogievskiy ret = -ENOMEM;
26106aa7a263SVladimir Sementsov-Ogievskiy goto out_unlocked;
26116aa7a263SVladimir Sementsov-Ogievskiy }
26126aa7a263SVladimir Sementsov-Ogievskiy qemu_iovec_to_buf(qiov, qiov_offset, crypt_buf, bytes);
26136aa7a263SVladimir Sementsov-Ogievskiy
26149c4269d5SAlberto Garcia if (qcow2_co_encrypt(bs, host_offset, offset, crypt_buf, bytes) < 0) {
26156aa7a263SVladimir Sementsov-Ogievskiy ret = -EIO;
26166aa7a263SVladimir Sementsov-Ogievskiy goto out_unlocked;
26176aa7a263SVladimir Sementsov-Ogievskiy }
26186aa7a263SVladimir Sementsov-Ogievskiy
26196aa7a263SVladimir Sementsov-Ogievskiy qemu_iovec_init_buf(&encrypted_qiov, crypt_buf, bytes);
26206aa7a263SVladimir Sementsov-Ogievskiy qiov = &encrypted_qiov;
26216aa7a263SVladimir Sementsov-Ogievskiy qiov_offset = 0;
26226aa7a263SVladimir Sementsov-Ogievskiy }
26236aa7a263SVladimir Sementsov-Ogievskiy
26246aa7a263SVladimir Sementsov-Ogievskiy /* Try to efficiently initialize the physical space with zeroes */
26256aa7a263SVladimir Sementsov-Ogievskiy ret = handle_alloc_space(bs, l2meta);
26266aa7a263SVladimir Sementsov-Ogievskiy if (ret < 0) {
26276aa7a263SVladimir Sementsov-Ogievskiy goto out_unlocked;
26286aa7a263SVladimir Sementsov-Ogievskiy }
26296aa7a263SVladimir Sementsov-Ogievskiy
26306aa7a263SVladimir Sementsov-Ogievskiy /*
26316aa7a263SVladimir Sementsov-Ogievskiy * If we need to do COW, check if it's possible to merge the
26326aa7a263SVladimir Sementsov-Ogievskiy * writing of the guest data together with that of the COW regions.
26336aa7a263SVladimir Sementsov-Ogievskiy * If it's not possible (or not necessary) then write the
26346aa7a263SVladimir Sementsov-Ogievskiy * guest data now.
26356aa7a263SVladimir Sementsov-Ogievskiy */
26366aa7a263SVladimir Sementsov-Ogievskiy if (!merge_cow(offset, bytes, qiov, qiov_offset, l2meta)) {
263717362398SPaolo Bonzini BLKDBG_CO_EVENT(bs->file, BLKDBG_WRITE_AIO);
26389c4269d5SAlberto Garcia trace_qcow2_writev_data(qemu_coroutine_self(), host_offset);
26399c4269d5SAlberto Garcia ret = bdrv_co_pwritev_part(s->data_file, host_offset,
26406aa7a263SVladimir Sementsov-Ogievskiy bytes, qiov, qiov_offset, 0);
26416aa7a263SVladimir Sementsov-Ogievskiy if (ret < 0) {
26426aa7a263SVladimir Sementsov-Ogievskiy goto out_unlocked;
26436aa7a263SVladimir Sementsov-Ogievskiy }
26446aa7a263SVladimir Sementsov-Ogievskiy }
26456aa7a263SVladimir Sementsov-Ogievskiy
26466aa7a263SVladimir Sementsov-Ogievskiy qemu_co_mutex_lock(&s->lock);
26476aa7a263SVladimir Sementsov-Ogievskiy
26486aa7a263SVladimir Sementsov-Ogievskiy ret = qcow2_handle_l2meta(bs, &l2meta, true);
26496aa7a263SVladimir Sementsov-Ogievskiy goto out_locked;
26506aa7a263SVladimir Sementsov-Ogievskiy
26516aa7a263SVladimir Sementsov-Ogievskiy out_unlocked:
26526aa7a263SVladimir Sementsov-Ogievskiy qemu_co_mutex_lock(&s->lock);
26536aa7a263SVladimir Sementsov-Ogievskiy
26546aa7a263SVladimir Sementsov-Ogievskiy out_locked:
26556aa7a263SVladimir Sementsov-Ogievskiy qcow2_handle_l2meta(bs, &l2meta, false);
26566aa7a263SVladimir Sementsov-Ogievskiy qemu_co_mutex_unlock(&s->lock);
26576aa7a263SVladimir Sementsov-Ogievskiy
26586aa7a263SVladimir Sementsov-Ogievskiy qemu_vfree(crypt_buf);
26596aa7a263SVladimir Sementsov-Ogievskiy
26606aa7a263SVladimir Sementsov-Ogievskiy return ret;
26616aa7a263SVladimir Sementsov-Ogievskiy }
26626aa7a263SVladimir Sementsov-Ogievskiy
2663abaf8b75SKevin Wolf /*
2664abaf8b75SKevin Wolf * This function can count as GRAPH_RDLOCK because qcow2_co_pwritev_part() holds
2665abaf8b75SKevin Wolf * the graph lock and keeps it until this coroutine has terminated.
2666abaf8b75SKevin Wolf */
qcow2_co_pwritev_task_entry(AioTask * task)2667abaf8b75SKevin Wolf static coroutine_fn GRAPH_RDLOCK int qcow2_co_pwritev_task_entry(AioTask *task)
2668d710cf57SVladimir Sementsov-Ogievskiy {
2669d710cf57SVladimir Sementsov-Ogievskiy Qcow2AioTask *t = container_of(task, Qcow2AioTask, task);
2670d710cf57SVladimir Sementsov-Ogievskiy
267110dabdc5SAlberto Garcia assert(!t->subcluster_type);
2672d710cf57SVladimir Sementsov-Ogievskiy
26739c4269d5SAlberto Garcia return qcow2_co_pwritev_task(t->bs, t->host_offset,
2674d710cf57SVladimir Sementsov-Ogievskiy t->offset, t->bytes, t->qiov, t->qiov_offset,
2675d710cf57SVladimir Sementsov-Ogievskiy t->l2meta);
2676d710cf57SVladimir Sementsov-Ogievskiy }
2677d710cf57SVladimir Sementsov-Ogievskiy
26787b1fb72eSKevin Wolf static int coroutine_fn GRAPH_RDLOCK
qcow2_co_pwritev_part(BlockDriverState * bs,int64_t offset,int64_t bytes,QEMUIOVector * qiov,size_t qiov_offset,BdrvRequestFlags flags)26797b1fb72eSKevin Wolf qcow2_co_pwritev_part(BlockDriverState *bs, int64_t offset, int64_t bytes,
26807b1fb72eSKevin Wolf QEMUIOVector *qiov, size_t qiov_offset,
26817b1fb72eSKevin Wolf BdrvRequestFlags flags)
2682585f8587Sbellard {
2683ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque;
2684d46a0bb2SKevin Wolf int offset_in_cluster;
268568d100e9SKevin Wolf int ret;
2686d46a0bb2SKevin Wolf unsigned int cur_bytes; /* number of sectors in current iteration */
2687bfd0989aSAlberto Garcia uint64_t host_offset;
26888d2497c3SKevin Wolf QCowL2Meta *l2meta = NULL;
2689d710cf57SVladimir Sementsov-Ogievskiy AioTaskPool *aio = NULL;
2690c2271403SFrediano Ziglio
2691d46a0bb2SKevin Wolf trace_qcow2_writev_start_req(qemu_coroutine_self(), offset, bytes);
26923cce16f4SKevin Wolf
2693d710cf57SVladimir Sementsov-Ogievskiy while (bytes != 0 && aio_task_pool_status(aio) == 0) {
26943fc48d09SFrediano Ziglio
2695f50f88b9SKevin Wolf l2meta = NULL;
2696cf5c1a23SKevin Wolf
26973cce16f4SKevin Wolf trace_qcow2_writev_start_part(qemu_coroutine_self());
2698d46a0bb2SKevin Wolf offset_in_cluster = offset_into_cluster(s, offset);
2699d46a0bb2SKevin Wolf cur_bytes = MIN(bytes, INT_MAX);
2700d46a0bb2SKevin Wolf if (bs->encrypted) {
2701d46a0bb2SKevin Wolf cur_bytes = MIN(cur_bytes,
2702d46a0bb2SKevin Wolf QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size
2703d46a0bb2SKevin Wolf - offset_in_cluster);
27045ebaa27eSFrediano Ziglio }
2705095a9c58Saliguori
27066aa7a263SVladimir Sementsov-Ogievskiy qemu_co_mutex_lock(&s->lock);
27076aa7a263SVladimir Sementsov-Ogievskiy
2708bfd0989aSAlberto Garcia ret = qcow2_alloc_host_offset(bs, offset, &cur_bytes,
2709bfd0989aSAlberto Garcia &host_offset, &l2meta);
2710148da7eaSKevin Wolf if (ret < 0) {
27115447c3a0SVladimir Sementsov-Ogievskiy goto out_locked;
2712148da7eaSKevin Wolf }
2713148da7eaSKevin Wolf
2714bfd0989aSAlberto Garcia ret = qcow2_pre_write_overlap_check(bs, 0, host_offset,
27155447c3a0SVladimir Sementsov-Ogievskiy cur_bytes, true);
27165447c3a0SVladimir Sementsov-Ogievskiy if (ret < 0) {
27175447c3a0SVladimir Sementsov-Ogievskiy goto out_locked;
27185447c3a0SVladimir Sementsov-Ogievskiy }
27195447c3a0SVladimir Sementsov-Ogievskiy
27205447c3a0SVladimir Sementsov-Ogievskiy qemu_co_mutex_unlock(&s->lock);
27215447c3a0SVladimir Sementsov-Ogievskiy
2722d710cf57SVladimir Sementsov-Ogievskiy if (!aio && cur_bytes != bytes) {
2723d710cf57SVladimir Sementsov-Ogievskiy aio = aio_task_pool_new(QCOW2_MAX_WORKERS);
2724d710cf57SVladimir Sementsov-Ogievskiy }
2725d710cf57SVladimir Sementsov-Ogievskiy ret = qcow2_add_task(bs, aio, qcow2_co_pwritev_task_entry, 0,
2726bfd0989aSAlberto Garcia host_offset, offset,
27279c4269d5SAlberto Garcia cur_bytes, qiov, qiov_offset, l2meta);
27286aa7a263SVladimir Sementsov-Ogievskiy l2meta = NULL; /* l2meta is consumed by qcow2_co_pwritev_task() */
2729c8bb23cbSAnton Nefedov if (ret < 0) {
27306aa7a263SVladimir Sementsov-Ogievskiy goto fail_nometa;
2731faf575c1SFrediano Ziglio }
2732faf575c1SFrediano Ziglio
2733d46a0bb2SKevin Wolf bytes -= cur_bytes;
2734d46a0bb2SKevin Wolf offset += cur_bytes;
27356aa7a263SVladimir Sementsov-Ogievskiy qiov_offset += cur_bytes;
2736d46a0bb2SKevin Wolf trace_qcow2_writev_done_part(qemu_coroutine_self(), cur_bytes);
27375ebaa27eSFrediano Ziglio }
27383fc48d09SFrediano Ziglio ret = 0;
2739faf575c1SFrediano Ziglio
27405447c3a0SVladimir Sementsov-Ogievskiy qemu_co_mutex_lock(&s->lock);
27415447c3a0SVladimir Sementsov-Ogievskiy
27425447c3a0SVladimir Sementsov-Ogievskiy out_locked:
2743fd9fcd37SFam Zheng qcow2_handle_l2meta(bs, &l2meta, false);
27440fa9131aSKevin Wolf
2745a8c57408SPaolo Bonzini qemu_co_mutex_unlock(&s->lock);
2746a8c57408SPaolo Bonzini
27476aa7a263SVladimir Sementsov-Ogievskiy fail_nometa:
2748d710cf57SVladimir Sementsov-Ogievskiy if (aio) {
2749d710cf57SVladimir Sementsov-Ogievskiy aio_task_pool_wait_all(aio);
2750d710cf57SVladimir Sementsov-Ogievskiy if (ret == 0) {
2751d710cf57SVladimir Sementsov-Ogievskiy ret = aio_task_pool_status(aio);
2752d710cf57SVladimir Sementsov-Ogievskiy }
2753d710cf57SVladimir Sementsov-Ogievskiy g_free(aio);
2754d710cf57SVladimir Sementsov-Ogievskiy }
2755d710cf57SVladimir Sementsov-Ogievskiy
27563cce16f4SKevin Wolf trace_qcow2_writev_done_req(qemu_coroutine_self(), ret);
275742496d62SKevin Wolf
275868d100e9SKevin Wolf return ret;
2759585f8587Sbellard }
2760585f8587Sbellard
qcow2_inactivate(BlockDriverState * bs)2761de4fed6fSKevin Wolf static int GRAPH_RDLOCK qcow2_inactivate(BlockDriverState *bs)
2762ec6d8912SKevin Wolf {
2763ec6d8912SKevin Wolf BDRVQcow2State *s = bs->opaque;
2764ec6d8912SKevin Wolf int ret, result = 0;
27655f72826eSVladimir Sementsov-Ogievskiy Error *local_err = NULL;
2766ec6d8912SKevin Wolf
2767644ddbb7SVladimir Sementsov-Ogievskiy qcow2_store_persistent_dirty_bitmaps(bs, true, &local_err);
276883a8c775SPavel Butsykin if (local_err != NULL) {
276983a8c775SPavel Butsykin result = -EINVAL;
2770132adb68SVladimir Sementsov-Ogievskiy error_reportf_err(local_err, "Lost persistent bitmaps during "
2771132adb68SVladimir Sementsov-Ogievskiy "inactivation of node '%s': ",
277283a8c775SPavel Butsykin bdrv_get_device_or_node_name(bs));
277383a8c775SPavel Butsykin }
277483a8c775SPavel Butsykin
2775ec6d8912SKevin Wolf ret = qcow2_cache_flush(bs, s->l2_table_cache);
2776ec6d8912SKevin Wolf if (ret) {
2777ec6d8912SKevin Wolf result = ret;
2778ec6d8912SKevin Wolf error_report("Failed to flush the L2 table cache: %s",
2779ec6d8912SKevin Wolf strerror(-ret));
2780ec6d8912SKevin Wolf }
2781ec6d8912SKevin Wolf
2782ec6d8912SKevin Wolf ret = qcow2_cache_flush(bs, s->refcount_block_cache);
2783ec6d8912SKevin Wolf if (ret) {
2784ec6d8912SKevin Wolf result = ret;
2785ec6d8912SKevin Wolf error_report("Failed to flush the refcount block cache: %s",
2786ec6d8912SKevin Wolf strerror(-ret));
2787ec6d8912SKevin Wolf }
2788ec6d8912SKevin Wolf
2789ec6d8912SKevin Wolf if (result == 0) {
2790ec6d8912SKevin Wolf qcow2_mark_clean(bs);
2791ec6d8912SKevin Wolf }
2792ec6d8912SKevin Wolf
2793ec6d8912SKevin Wolf return result;
2794ec6d8912SKevin Wolf }
2795ec6d8912SKevin Wolf
2796de4fed6fSKevin Wolf static void coroutine_mixed_fn GRAPH_RDLOCK
qcow2_do_close(BlockDriverState * bs,bool close_data_file)2797de4fed6fSKevin Wolf qcow2_do_close(BlockDriverState *bs, bool close_data_file)
2798585f8587Sbellard {
2799ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque;
2800de82815dSKevin Wolf qemu_vfree(s->l1_table);
2801cf93980eSMax Reitz /* else pre-write overlap checks in cache_destroy may crash */
2802cf93980eSMax Reitz s->l1_table = NULL;
280329c1a730SKevin Wolf
2804140fd5a6SKevin Wolf if (!(s->flags & BDRV_O_INACTIVE)) {
2805ec6d8912SKevin Wolf qcow2_inactivate(bs);
28063b5e14c7SMax Reitz }
2807c61d0004SStefan Hajnoczi
2808279621c0SAlberto Garcia cache_clean_timer_del(bs);
2809e64d4072SAlberto Garcia qcow2_cache_destroy(s->l2_table_cache);
2810e64d4072SAlberto Garcia qcow2_cache_destroy(s->refcount_block_cache);
281129c1a730SKevin Wolf
2812b25b387fSDaniel P. Berrange qcrypto_block_free(s->crypto);
2813b25b387fSDaniel P. Berrange s->crypto = NULL;
28144aebf0f0SPan Nengyuan qapi_free_QCryptoBlockOpenOptions(s->crypto_opts);
2815f6fa64f6SDaniel P. Berrange
28166744cbabSKevin Wolf g_free(s->unknown_header_fields);
281775bab85cSKevin Wolf cleanup_unknown_header_ext(bs);
28186744cbabSKevin Wolf
28199b890bdcSKevin Wolf g_free(s->image_data_file);
2820e4603fe1SKevin Wolf g_free(s->image_backing_file);
2821e4603fe1SKevin Wolf g_free(s->image_backing_format);
2822e4603fe1SKevin Wolf
282306e9cd19SHanna Reitz if (close_data_file && has_data_file(bs)) {
2824de4fed6fSKevin Wolf GLOBAL_STATE_CODE();
2825de4fed6fSKevin Wolf bdrv_graph_rdunlock_main_loop();
2826*b13f5465SFiona Ebner bdrv_drain_all_begin();
28276bc30f19SStefan Hajnoczi bdrv_graph_wrlock();
28280e8c08beSKevin Wolf bdrv_unref_child(bs, s->data_file);
28296bc30f19SStefan Hajnoczi bdrv_graph_wrunlock();
2830*b13f5465SFiona Ebner bdrv_drain_all_end();
2831808cf3cbSVladimir Sementsov-Ogievskiy s->data_file = NULL;
2832de4fed6fSKevin Wolf bdrv_graph_rdlock_main_loop();
28330e8c08beSKevin Wolf }
28340e8c08beSKevin Wolf
2835ed6ccf0fSKevin Wolf qcow2_refcount_close(bs);
283628c1202bSLi Zhi Hui qcow2_free_snapshots(bs);
2837585f8587Sbellard }
2838585f8587Sbellard
qcow2_close(BlockDriverState * bs)2839de4fed6fSKevin Wolf static void GRAPH_UNLOCKED qcow2_close(BlockDriverState *bs)
284006e9cd19SHanna Reitz {
2841de4fed6fSKevin Wolf GLOBAL_STATE_CODE();
2842de4fed6fSKevin Wolf GRAPH_RDLOCK_GUARD_MAINLOOP();
2843de4fed6fSKevin Wolf
284406e9cd19SHanna Reitz qcow2_do_close(bs, true);
284506e9cd19SHanna Reitz }
284606e9cd19SHanna Reitz
2847b9b10c35SKevin Wolf static void coroutine_fn GRAPH_RDLOCK
qcow2_co_invalidate_cache(BlockDriverState * bs,Error ** errp)2848b9b10c35SKevin Wolf qcow2_co_invalidate_cache(BlockDriverState *bs, Error **errp)
284906d9260fSAnthony Liguori {
2850e6247c9cSVladimir Sementsov-Ogievskiy ERRP_GUARD();
2851ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque;
285206e9cd19SHanna Reitz BdrvChild *data_file;
285306d9260fSAnthony Liguori int flags = s->flags;
2854b25b387fSDaniel P. Berrange QCryptoBlock *crypto = NULL;
2855acdfb480SKevin Wolf QDict *options;
28565a8a30dbSKevin Wolf int ret;
285706d9260fSAnthony Liguori
285806d9260fSAnthony Liguori /*
285906d9260fSAnthony Liguori * Backing files are read-only which makes all of their metadata immutable,
286006d9260fSAnthony Liguori * that means we don't have to worry about reopening them here.
286106d9260fSAnthony Liguori */
286206d9260fSAnthony Liguori
2863b25b387fSDaniel P. Berrange crypto = s->crypto;
2864b25b387fSDaniel P. Berrange s->crypto = NULL;
286506d9260fSAnthony Liguori
286606e9cd19SHanna Reitz /*
286706e9cd19SHanna Reitz * Do not reopen s->data_file (i.e., have qcow2_do_close() not close it,
286806e9cd19SHanna Reitz * and then prevent qcow2_do_open() from opening it), because this function
286906e9cd19SHanna Reitz * runs in the I/O path and as such we must not invoke global-state
287006e9cd19SHanna Reitz * functions like bdrv_unref_child() and bdrv_open_child().
287106e9cd19SHanna Reitz */
287206d9260fSAnthony Liguori
287306e9cd19SHanna Reitz qcow2_do_close(bs, false);
287406e9cd19SHanna Reitz
287506e9cd19SHanna Reitz data_file = s->data_file;
2876ff99129aSKevin Wolf memset(s, 0, sizeof(BDRVQcow2State));
287706e9cd19SHanna Reitz s->data_file = data_file;
287806e9cd19SHanna Reitz
2879d475e5acSKevin Wolf options = qdict_clone_shallow(bs->options);
28805a8a30dbSKevin Wolf
2881140fd5a6SKevin Wolf flags &= ~BDRV_O_INACTIVE;
28822b148f39SPaolo Bonzini qemu_co_mutex_lock(&s->lock);
288306e9cd19SHanna Reitz ret = qcow2_do_open(bs, options, flags, false, errp);
28842b148f39SPaolo Bonzini qemu_co_mutex_unlock(&s->lock);
2885cb3e7f08SMarc-André Lureau qobject_unref(options);
2886e6247c9cSVladimir Sementsov-Ogievskiy if (ret < 0) {
2887e6247c9cSVladimir Sementsov-Ogievskiy error_prepend(errp, "Could not reopen qcow2 layer: ");
2888191fb11bSKevin Wolf bs->drv = NULL;
28895a8a30dbSKevin Wolf return;
28905a8a30dbSKevin Wolf }
2891acdfb480SKevin Wolf
2892b25b387fSDaniel P. Berrange s->crypto = crypto;
289306d9260fSAnthony Liguori }
289406d9260fSAnthony Liguori
header_ext_add(char * buf,uint32_t magic,const void * s,size_t len,size_t buflen)2895e24e49e6SKevin Wolf static size_t header_ext_add(char *buf, uint32_t magic, const void *s,
2896e24e49e6SKevin Wolf size_t len, size_t buflen)
2897756e6736SKevin Wolf {
2898e24e49e6SKevin Wolf QCowExtension *ext_backing_fmt = (QCowExtension*) buf;
2899e24e49e6SKevin Wolf size_t ext_len = sizeof(QCowExtension) + ((len + 7) & ~7);
2900756e6736SKevin Wolf
2901e24e49e6SKevin Wolf if (buflen < ext_len) {
2902756e6736SKevin Wolf return -ENOSPC;
2903756e6736SKevin Wolf }
2904756e6736SKevin Wolf
2905e24e49e6SKevin Wolf *ext_backing_fmt = (QCowExtension) {
2906e24e49e6SKevin Wolf .magic = cpu_to_be32(magic),
2907e24e49e6SKevin Wolf .len = cpu_to_be32(len),
2908e24e49e6SKevin Wolf };
29090647d47cSStefan Hajnoczi
29100647d47cSStefan Hajnoczi if (len) {
2911e24e49e6SKevin Wolf memcpy(buf + sizeof(QCowExtension), s, len);
29120647d47cSStefan Hajnoczi }
2913756e6736SKevin Wolf
2914e24e49e6SKevin Wolf return ext_len;
2915756e6736SKevin Wolf }
2916756e6736SKevin Wolf
2917e24e49e6SKevin Wolf /*
2918e24e49e6SKevin Wolf * Updates the qcow2 header, including the variable length parts of it, i.e.
2919e24e49e6SKevin Wolf * the backing file name and all extensions. qcow2 was not designed to allow
2920e24e49e6SKevin Wolf * such changes, so if we run out of space (we can only use the first cluster)
2921e24e49e6SKevin Wolf * this function may fail.
2922e24e49e6SKevin Wolf *
2923e24e49e6SKevin Wolf * Returns 0 on success, -errno in error cases.
2924e24e49e6SKevin Wolf */
qcow2_update_header(BlockDriverState * bs)2925e24e49e6SKevin Wolf int qcow2_update_header(BlockDriverState *bs)
2926e24e49e6SKevin Wolf {
2927ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque;
2928e24e49e6SKevin Wolf QCowHeader *header;
2929e24e49e6SKevin Wolf char *buf;
2930e24e49e6SKevin Wolf size_t buflen = s->cluster_size;
2931e24e49e6SKevin Wolf int ret;
2932e24e49e6SKevin Wolf uint64_t total_size;
2933e24e49e6SKevin Wolf uint32_t refcount_table_clusters;
29346744cbabSKevin Wolf size_t header_length;
293575bab85cSKevin Wolf Qcow2UnknownHeaderExtension *uext;
2936e24e49e6SKevin Wolf
2937e24e49e6SKevin Wolf buf = qemu_blockalign(bs, buflen);
2938e24e49e6SKevin Wolf
2939e24e49e6SKevin Wolf /* Header structure */
2940e24e49e6SKevin Wolf header = (QCowHeader*) buf;
2941e24e49e6SKevin Wolf
2942e24e49e6SKevin Wolf if (buflen < sizeof(*header)) {
2943e24e49e6SKevin Wolf ret = -ENOSPC;
2944e24e49e6SKevin Wolf goto fail;
2945756e6736SKevin Wolf }
2946756e6736SKevin Wolf
29476744cbabSKevin Wolf header_length = sizeof(*header) + s->unknown_header_fields_size;
2948e24e49e6SKevin Wolf total_size = bs->total_sectors * BDRV_SECTOR_SIZE;
2949e24e49e6SKevin Wolf refcount_table_clusters = s->refcount_table_size >> (s->cluster_bits - 3);
2950e24e49e6SKevin Wolf
2951572ad978SDenis Plotnikov ret = validate_compression_type(s, NULL);
2952572ad978SDenis Plotnikov if (ret) {
2953572ad978SDenis Plotnikov goto fail;
2954572ad978SDenis Plotnikov }
2955572ad978SDenis Plotnikov
2956e24e49e6SKevin Wolf *header = (QCowHeader) {
29576744cbabSKevin Wolf /* Version 2 fields */
2958e24e49e6SKevin Wolf .magic = cpu_to_be32(QCOW_MAGIC),
29596744cbabSKevin Wolf .version = cpu_to_be32(s->qcow_version),
2960e24e49e6SKevin Wolf .backing_file_offset = 0,
2961e24e49e6SKevin Wolf .backing_file_size = 0,
2962e24e49e6SKevin Wolf .cluster_bits = cpu_to_be32(s->cluster_bits),
2963e24e49e6SKevin Wolf .size = cpu_to_be64(total_size),
2964e24e49e6SKevin Wolf .crypt_method = cpu_to_be32(s->crypt_method_header),
2965e24e49e6SKevin Wolf .l1_size = cpu_to_be32(s->l1_size),
2966e24e49e6SKevin Wolf .l1_table_offset = cpu_to_be64(s->l1_table_offset),
2967e24e49e6SKevin Wolf .refcount_table_offset = cpu_to_be64(s->refcount_table_offset),
2968e24e49e6SKevin Wolf .refcount_table_clusters = cpu_to_be32(refcount_table_clusters),
2969e24e49e6SKevin Wolf .nb_snapshots = cpu_to_be32(s->nb_snapshots),
2970e24e49e6SKevin Wolf .snapshots_offset = cpu_to_be64(s->snapshots_offset),
29716744cbabSKevin Wolf
29726744cbabSKevin Wolf /* Version 3 fields */
29736744cbabSKevin Wolf .incompatible_features = cpu_to_be64(s->incompatible_features),
29746744cbabSKevin Wolf .compatible_features = cpu_to_be64(s->compatible_features),
29756744cbabSKevin Wolf .autoclear_features = cpu_to_be64(s->autoclear_features),
2976b6481f37SMax Reitz .refcount_order = cpu_to_be32(s->refcount_order),
29776744cbabSKevin Wolf .header_length = cpu_to_be32(header_length),
2978572ad978SDenis Plotnikov .compression_type = s->compression_type,
2979e24e49e6SKevin Wolf };
2980e24e49e6SKevin Wolf
29816744cbabSKevin Wolf /* For older versions, write a shorter header */
29826744cbabSKevin Wolf switch (s->qcow_version) {
29836744cbabSKevin Wolf case 2:
29846744cbabSKevin Wolf ret = offsetof(QCowHeader, incompatible_features);
29856744cbabSKevin Wolf break;
29866744cbabSKevin Wolf case 3:
29876744cbabSKevin Wolf ret = sizeof(*header);
29886744cbabSKevin Wolf break;
29896744cbabSKevin Wolf default:
2990b6c14762SJim Meyering ret = -EINVAL;
2991b6c14762SJim Meyering goto fail;
29926744cbabSKevin Wolf }
29936744cbabSKevin Wolf
29946744cbabSKevin Wolf buf += ret;
29956744cbabSKevin Wolf buflen -= ret;
29966744cbabSKevin Wolf memset(buf, 0, buflen);
29976744cbabSKevin Wolf
29986744cbabSKevin Wolf /* Preserve any unknown field in the header */
29996744cbabSKevin Wolf if (s->unknown_header_fields_size) {
30006744cbabSKevin Wolf if (buflen < s->unknown_header_fields_size) {
30016744cbabSKevin Wolf ret = -ENOSPC;
30026744cbabSKevin Wolf goto fail;
30036744cbabSKevin Wolf }
30046744cbabSKevin Wolf
30056744cbabSKevin Wolf memcpy(buf, s->unknown_header_fields, s->unknown_header_fields_size);
30066744cbabSKevin Wolf buf += s->unknown_header_fields_size;
30076744cbabSKevin Wolf buflen -= s->unknown_header_fields_size;
30086744cbabSKevin Wolf }
3009e24e49e6SKevin Wolf
3010e24e49e6SKevin Wolf /* Backing file format header extension */
3011e4603fe1SKevin Wolf if (s->image_backing_format) {
3012e24e49e6SKevin Wolf ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BACKING_FORMAT,
3013e4603fe1SKevin Wolf s->image_backing_format,
3014e4603fe1SKevin Wolf strlen(s->image_backing_format),
3015e24e49e6SKevin Wolf buflen);
3016756e6736SKevin Wolf if (ret < 0) {
3017756e6736SKevin Wolf goto fail;
3018756e6736SKevin Wolf }
3019756e6736SKevin Wolf
3020e24e49e6SKevin Wolf buf += ret;
3021e24e49e6SKevin Wolf buflen -= ret;
3022e24e49e6SKevin Wolf }
3023756e6736SKevin Wolf
30249b890bdcSKevin Wolf /* External data file header extension */
30259b890bdcSKevin Wolf if (has_data_file(bs) && s->image_data_file) {
30269b890bdcSKevin Wolf ret = header_ext_add(buf, QCOW2_EXT_MAGIC_DATA_FILE,
30279b890bdcSKevin Wolf s->image_data_file, strlen(s->image_data_file),
30289b890bdcSKevin Wolf buflen);
30299b890bdcSKevin Wolf if (ret < 0) {
30309b890bdcSKevin Wolf goto fail;
30319b890bdcSKevin Wolf }
30329b890bdcSKevin Wolf
30339b890bdcSKevin Wolf buf += ret;
30349b890bdcSKevin Wolf buflen -= ret;
30359b890bdcSKevin Wolf }
30369b890bdcSKevin Wolf
30374652b8f3SDaniel P. Berrange /* Full disk encryption header pointer extension */
30384652b8f3SDaniel P. Berrange if (s->crypto_header.offset != 0) {
30393b698f52SPeter Maydell s->crypto_header.offset = cpu_to_be64(s->crypto_header.offset);
30403b698f52SPeter Maydell s->crypto_header.length = cpu_to_be64(s->crypto_header.length);
30414652b8f3SDaniel P. Berrange ret = header_ext_add(buf, QCOW2_EXT_MAGIC_CRYPTO_HEADER,
30424652b8f3SDaniel P. Berrange &s->crypto_header, sizeof(s->crypto_header),
30434652b8f3SDaniel P. Berrange buflen);
30443b698f52SPeter Maydell s->crypto_header.offset = be64_to_cpu(s->crypto_header.offset);
30453b698f52SPeter Maydell s->crypto_header.length = be64_to_cpu(s->crypto_header.length);
30464652b8f3SDaniel P. Berrange if (ret < 0) {
30474652b8f3SDaniel P. Berrange goto fail;
30484652b8f3SDaniel P. Berrange }
30494652b8f3SDaniel P. Berrange buf += ret;
30504652b8f3SDaniel P. Berrange buflen -= ret;
30514652b8f3SDaniel P. Berrange }
30524652b8f3SDaniel P. Berrange
3053e7be13adSEric Blake /*
3054e7be13adSEric Blake * Feature table. A mere 8 feature names occupies 392 bytes, and
3055e7be13adSEric Blake * when coupled with the v3 minimum header of 104 bytes plus the
3056e7be13adSEric Blake * 8-byte end-of-extension marker, that would leave only 8 bytes
3057e7be13adSEric Blake * for a backing file name in an image with 512-byte clusters.
3058e7be13adSEric Blake * Thus, we choose to omit this header for cluster sizes 4k and
3059e7be13adSEric Blake * smaller.
3060e7be13adSEric Blake */
3061e7be13adSEric Blake if (s->qcow_version >= 3 && s->cluster_size > 4096) {
3062bb40ebceSEric Blake static const Qcow2Feature features[] = {
3063c61d0004SStefan Hajnoczi {
3064c61d0004SStefan Hajnoczi .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
3065c61d0004SStefan Hajnoczi .bit = QCOW2_INCOMPAT_DIRTY_BITNR,
3066c61d0004SStefan Hajnoczi .name = "dirty bit",
3067c61d0004SStefan Hajnoczi },
3068bfe8043eSStefan Hajnoczi {
306969c98726SMax Reitz .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
307069c98726SMax Reitz .bit = QCOW2_INCOMPAT_CORRUPT_BITNR,
307169c98726SMax Reitz .name = "corrupt bit",
307269c98726SMax Reitz },
307369c98726SMax Reitz {
307493c24936SKevin Wolf .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
307593c24936SKevin Wolf .bit = QCOW2_INCOMPAT_DATA_FILE_BITNR,
307693c24936SKevin Wolf .name = "external data file",
307793c24936SKevin Wolf },
307893c24936SKevin Wolf {
3079572ad978SDenis Plotnikov .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
3080572ad978SDenis Plotnikov .bit = QCOW2_INCOMPAT_COMPRESSION_BITNR,
3081572ad978SDenis Plotnikov .name = "compression type",
3082572ad978SDenis Plotnikov },
3083572ad978SDenis Plotnikov {
30847be20252SAlberto Garcia .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
30857be20252SAlberto Garcia .bit = QCOW2_INCOMPAT_EXTL2_BITNR,
30867be20252SAlberto Garcia .name = "extended L2 entries",
30877be20252SAlberto Garcia },
30887be20252SAlberto Garcia {
3089bfe8043eSStefan Hajnoczi .type = QCOW2_FEAT_TYPE_COMPATIBLE,
3090bfe8043eSStefan Hajnoczi .bit = QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR,
3091bfe8043eSStefan Hajnoczi .name = "lazy refcounts",
3092bfe8043eSStefan Hajnoczi },
3093bb40ebceSEric Blake {
3094bb40ebceSEric Blake .type = QCOW2_FEAT_TYPE_AUTOCLEAR,
3095bb40ebceSEric Blake .bit = QCOW2_AUTOCLEAR_BITMAPS_BITNR,
3096bb40ebceSEric Blake .name = "bitmaps",
3097bb40ebceSEric Blake },
3098bb40ebceSEric Blake {
3099bb40ebceSEric Blake .type = QCOW2_FEAT_TYPE_AUTOCLEAR,
3100bb40ebceSEric Blake .bit = QCOW2_AUTOCLEAR_DATA_FILE_RAW_BITNR,
3101bb40ebceSEric Blake .name = "raw external data",
3102bb40ebceSEric Blake },
3103cfcc4c62SKevin Wolf };
3104cfcc4c62SKevin Wolf
3105cfcc4c62SKevin Wolf ret = header_ext_add(buf, QCOW2_EXT_MAGIC_FEATURE_TABLE,
3106cfcc4c62SKevin Wolf features, sizeof(features), buflen);
3107cfcc4c62SKevin Wolf if (ret < 0) {
3108cfcc4c62SKevin Wolf goto fail;
3109cfcc4c62SKevin Wolf }
3110cfcc4c62SKevin Wolf buf += ret;
3111cfcc4c62SKevin Wolf buflen -= ret;
31121a4828c7SKevin Wolf }
3113cfcc4c62SKevin Wolf
311488ddffaeSVladimir Sementsov-Ogievskiy /* Bitmap extension */
311588ddffaeSVladimir Sementsov-Ogievskiy if (s->nb_bitmaps > 0) {
311688ddffaeSVladimir Sementsov-Ogievskiy Qcow2BitmapHeaderExt bitmaps_header = {
311788ddffaeSVladimir Sementsov-Ogievskiy .nb_bitmaps = cpu_to_be32(s->nb_bitmaps),
311888ddffaeSVladimir Sementsov-Ogievskiy .bitmap_directory_size =
311988ddffaeSVladimir Sementsov-Ogievskiy cpu_to_be64(s->bitmap_directory_size),
312088ddffaeSVladimir Sementsov-Ogievskiy .bitmap_directory_offset =
312188ddffaeSVladimir Sementsov-Ogievskiy cpu_to_be64(s->bitmap_directory_offset)
312288ddffaeSVladimir Sementsov-Ogievskiy };
312388ddffaeSVladimir Sementsov-Ogievskiy ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BITMAPS,
312488ddffaeSVladimir Sementsov-Ogievskiy &bitmaps_header, sizeof(bitmaps_header),
312588ddffaeSVladimir Sementsov-Ogievskiy buflen);
312688ddffaeSVladimir Sementsov-Ogievskiy if (ret < 0) {
312788ddffaeSVladimir Sementsov-Ogievskiy goto fail;
312888ddffaeSVladimir Sementsov-Ogievskiy }
312988ddffaeSVladimir Sementsov-Ogievskiy buf += ret;
313088ddffaeSVladimir Sementsov-Ogievskiy buflen -= ret;
313188ddffaeSVladimir Sementsov-Ogievskiy }
313288ddffaeSVladimir Sementsov-Ogievskiy
313375bab85cSKevin Wolf /* Keep unknown header extensions */
313475bab85cSKevin Wolf QLIST_FOREACH(uext, &s->unknown_header_ext, next) {
313575bab85cSKevin Wolf ret = header_ext_add(buf, uext->magic, uext->data, uext->len, buflen);
313675bab85cSKevin Wolf if (ret < 0) {
313775bab85cSKevin Wolf goto fail;
313875bab85cSKevin Wolf }
313975bab85cSKevin Wolf
314075bab85cSKevin Wolf buf += ret;
314175bab85cSKevin Wolf buflen -= ret;
314275bab85cSKevin Wolf }
314375bab85cSKevin Wolf
3144e24e49e6SKevin Wolf /* End of header extensions */
3145e24e49e6SKevin Wolf ret = header_ext_add(buf, QCOW2_EXT_MAGIC_END, NULL, 0, buflen);
3146756e6736SKevin Wolf if (ret < 0) {
3147756e6736SKevin Wolf goto fail;
3148756e6736SKevin Wolf }
3149756e6736SKevin Wolf
3150e24e49e6SKevin Wolf buf += ret;
3151e24e49e6SKevin Wolf buflen -= ret;
3152e24e49e6SKevin Wolf
3153e24e49e6SKevin Wolf /* Backing file name */
3154e4603fe1SKevin Wolf if (s->image_backing_file) {
3155e4603fe1SKevin Wolf size_t backing_file_len = strlen(s->image_backing_file);
3156e24e49e6SKevin Wolf
3157e24e49e6SKevin Wolf if (buflen < backing_file_len) {
3158e24e49e6SKevin Wolf ret = -ENOSPC;
3159e24e49e6SKevin Wolf goto fail;
3160e24e49e6SKevin Wolf }
3161e24e49e6SKevin Wolf
316200ea1881SJim Meyering /* Using strncpy is ok here, since buf is not NUL-terminated. */
3163e4603fe1SKevin Wolf strncpy(buf, s->image_backing_file, buflen);
3164e24e49e6SKevin Wolf
3165e24e49e6SKevin Wolf header->backing_file_offset = cpu_to_be64(buf - ((char*) header));
3166e24e49e6SKevin Wolf header->backing_file_size = cpu_to_be32(backing_file_len);
3167e24e49e6SKevin Wolf }
3168e24e49e6SKevin Wolf
3169e24e49e6SKevin Wolf /* Write the new header */
317032cc71deSAlberto Faria ret = bdrv_pwrite(bs->file, 0, s->cluster_size, header, 0);
3171756e6736SKevin Wolf if (ret < 0) {
3172756e6736SKevin Wolf goto fail;
3173756e6736SKevin Wolf }
3174756e6736SKevin Wolf
3175756e6736SKevin Wolf ret = 0;
3176756e6736SKevin Wolf fail:
3177e24e49e6SKevin Wolf qemu_vfree(header);
3178756e6736SKevin Wolf return ret;
3179756e6736SKevin Wolf }
3180756e6736SKevin Wolf
3181e2dd2737SKevin Wolf static int coroutine_fn GRAPH_RDLOCK
qcow2_co_change_backing_file(BlockDriverState * bs,const char * backing_file,const char * backing_fmt)3182e2dd2737SKevin Wolf qcow2_co_change_backing_file(BlockDriverState *bs, const char *backing_file,
3183e2dd2737SKevin Wolf const char *backing_fmt)
3184756e6736SKevin Wolf {
3185ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque;
3186e4603fe1SKevin Wolf
31876c3944dcSKevin Wolf /* Adding a backing file means that the external data file alone won't be
31886c3944dcSKevin Wolf * enough to make sense of the content */
31896c3944dcSKevin Wolf if (backing_file && data_file_is_raw(bs)) {
31906c3944dcSKevin Wolf return -EINVAL;
31916c3944dcSKevin Wolf }
31926c3944dcSKevin Wolf
31934e876bcfSMax Reitz if (backing_file && strlen(backing_file) > 1023) {
31944e876bcfSMax Reitz return -EINVAL;
31954e876bcfSMax Reitz }
31964e876bcfSMax Reitz
3197998c2019SMax Reitz pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
3198998c2019SMax Reitz backing_file ?: "");
3199e24e49e6SKevin Wolf pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
3200e24e49e6SKevin Wolf pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
3201e24e49e6SKevin Wolf
3202e4603fe1SKevin Wolf g_free(s->image_backing_file);
3203e4603fe1SKevin Wolf g_free(s->image_backing_format);
3204e4603fe1SKevin Wolf
3205e4603fe1SKevin Wolf s->image_backing_file = backing_file ? g_strdup(bs->backing_file) : NULL;
3206e4603fe1SKevin Wolf s->image_backing_format = backing_fmt ? g_strdup(bs->backing_format) : NULL;
3207e4603fe1SKevin Wolf
3208e24e49e6SKevin Wolf return qcow2_update_header(bs);
3209756e6736SKevin Wolf }
3210756e6736SKevin Wolf
32114db7ba3bSKevin Wolf static int coroutine_fn GRAPH_RDLOCK
qcow2_set_up_encryption(BlockDriverState * bs,QCryptoBlockCreateOptions * cryptoopts,Error ** errp)32124db7ba3bSKevin Wolf qcow2_set_up_encryption(BlockDriverState *bs,
321360900b7bSKevin Wolf QCryptoBlockCreateOptions *cryptoopts,
321460900b7bSKevin Wolf Error **errp)
321560900b7bSKevin Wolf {
321660900b7bSKevin Wolf BDRVQcow2State *s = bs->opaque;
321760900b7bSKevin Wolf QCryptoBlock *crypto = NULL;
321860900b7bSKevin Wolf int fmt, ret;
321960900b7bSKevin Wolf
322060900b7bSKevin Wolf switch (cryptoopts->format) {
3221d23d2ef3SMarkus Armbruster case QCRYPTO_BLOCK_FORMAT_LUKS:
322260900b7bSKevin Wolf fmt = QCOW_CRYPT_LUKS;
322360900b7bSKevin Wolf break;
3224d23d2ef3SMarkus Armbruster case QCRYPTO_BLOCK_FORMAT_QCOW:
322560900b7bSKevin Wolf fmt = QCOW_CRYPT_AES;
322660900b7bSKevin Wolf break;
322760900b7bSKevin Wolf default:
322860900b7bSKevin Wolf error_setg(errp, "Crypto format not supported in qcow2");
322960900b7bSKevin Wolf return -EINVAL;
323060900b7bSKevin Wolf }
323160900b7bSKevin Wolf
32324652b8f3SDaniel P. Berrange s->crypt_method_header = fmt;
3233b25b387fSDaniel P. Berrange
32341cd9a787SDaniel P. Berrange crypto = qcrypto_block_create(cryptoopts, "encrypt.",
32354652b8f3SDaniel P. Berrange qcow2_crypto_hdr_init_func,
32364652b8f3SDaniel P. Berrange qcow2_crypto_hdr_write_func,
3237d74523a3SHyman Huang bs, 0, errp);
3238b25b387fSDaniel P. Berrange if (!crypto) {
323960900b7bSKevin Wolf return -EINVAL;
3240b25b387fSDaniel P. Berrange }
3241b25b387fSDaniel P. Berrange
3242b25b387fSDaniel P. Berrange ret = qcow2_update_header(bs);
3243b25b387fSDaniel P. Berrange if (ret < 0) {
3244b25b387fSDaniel P. Berrange error_setg_errno(errp, -ret, "Could not write encryption header");
3245b25b387fSDaniel P. Berrange goto out;
3246b25b387fSDaniel P. Berrange }
3247b25b387fSDaniel P. Berrange
324860900b7bSKevin Wolf ret = 0;
3249b25b387fSDaniel P. Berrange out:
3250b25b387fSDaniel P. Berrange qcrypto_block_free(crypto);
3251b25b387fSDaniel P. Berrange return ret;
3252b25b387fSDaniel P. Berrange }
3253b25b387fSDaniel P. Berrange
32547bc45dc1SMax Reitz /**
32557bc45dc1SMax Reitz * Preallocates metadata structures for data clusters between @offset (in the
32567bc45dc1SMax Reitz * guest disk) and @new_length (which is thus generally the new guest disk
32577bc45dc1SMax Reitz * size).
32587bc45dc1SMax Reitz *
32597bc45dc1SMax Reitz * Returns: 0 on success, -errno on failure.
32607bc45dc1SMax Reitz */
3261c2b8e315SKevin Wolf static int coroutine_fn GRAPH_RDLOCK
preallocate_co(BlockDriverState * bs,uint64_t offset,uint64_t new_length,PreallocMode mode,Error ** errp)3262c2b8e315SKevin Wolf preallocate_co(BlockDriverState *bs, uint64_t offset, uint64_t new_length,
3263c2b8e315SKevin Wolf PreallocMode mode, Error **errp)
3264a35e1c17SKevin Wolf {
326593e32b3eSKevin Wolf BDRVQcow2State *s = bs->opaque;
3266d46a0bb2SKevin Wolf uint64_t bytes;
3267060bee89SKevin Wolf uint64_t host_offset = 0;
3268718c0fceSKevin Wolf int64_t file_length;
3269d46a0bb2SKevin Wolf unsigned int cur_bytes;
3270148da7eaSKevin Wolf int ret;
32711a52b73dSAlberto Garcia QCowL2Meta *meta = NULL, *m;
3272a35e1c17SKevin Wolf
32737bc45dc1SMax Reitz assert(offset <= new_length);
32747bc45dc1SMax Reitz bytes = new_length - offset;
3275a35e1c17SKevin Wolf
3276d46a0bb2SKevin Wolf while (bytes) {
3277f29fbf7cSKevin Wolf cur_bytes = MIN(bytes, QEMU_ALIGN_DOWN(INT_MAX, s->cluster_size));
3278bfd0989aSAlberto Garcia ret = qcow2_alloc_host_offset(bs, offset, &cur_bytes,
3279060bee89SKevin Wolf &host_offset, &meta);
3280148da7eaSKevin Wolf if (ret < 0) {
3281360bd074SKevin Wolf error_setg_errno(errp, -ret, "Allocating clusters failed");
32821a52b73dSAlberto Garcia goto out;
3283a35e1c17SKevin Wolf }
3284a35e1c17SKevin Wolf
32851a52b73dSAlberto Garcia for (m = meta; m != NULL; m = m->next) {
32861a52b73dSAlberto Garcia m->prealloc = true;
32871a52b73dSAlberto Garcia }
3288c792707fSStefan Hajnoczi
32891a52b73dSAlberto Garcia ret = qcow2_handle_l2meta(bs, &meta, true);
329019dbcbf7SKevin Wolf if (ret < 0) {
3291360bd074SKevin Wolf error_setg_errno(errp, -ret, "Mapping clusters failed");
32921a52b73dSAlberto Garcia goto out;
3293f50f88b9SKevin Wolf }
3294f214978aSKevin Wolf
3295a35e1c17SKevin Wolf /* TODO Preallocate data if requested */
3296a35e1c17SKevin Wolf
3297d46a0bb2SKevin Wolf bytes -= cur_bytes;
3298d46a0bb2SKevin Wolf offset += cur_bytes;
3299a35e1c17SKevin Wolf }
3300a35e1c17SKevin Wolf
3301a35e1c17SKevin Wolf /*
3302a35e1c17SKevin Wolf * It is expected that the image file is large enough to actually contain
3303a35e1c17SKevin Wolf * all of the allocated clusters (otherwise we get failing reads after
3304a35e1c17SKevin Wolf * EOF). Extend the image to the last allocated sector.
3305a35e1c17SKevin Wolf */
33060050c163SKevin Wolf file_length = bdrv_co_getlength(s->data_file->bs);
3307718c0fceSKevin Wolf if (file_length < 0) {
3308718c0fceSKevin Wolf error_setg_errno(errp, -file_length, "Could not get file size");
33091a52b73dSAlberto Garcia ret = file_length;
33101a52b73dSAlberto Garcia goto out;
3311718c0fceSKevin Wolf }
3312718c0fceSKevin Wolf
3313718c0fceSKevin Wolf if (host_offset + cur_bytes > file_length) {
3314718c0fceSKevin Wolf if (mode == PREALLOC_MODE_METADATA) {
3315718c0fceSKevin Wolf mode = PREALLOC_MODE_OFF;
3316718c0fceSKevin Wolf }
3317c80d8b06SMax Reitz ret = bdrv_co_truncate(s->data_file, host_offset + cur_bytes, false,
33187b8e4857SKevin Wolf mode, 0, errp);
331919dbcbf7SKevin Wolf if (ret < 0) {
33201a52b73dSAlberto Garcia goto out;
332119dbcbf7SKevin Wolf }
3322a35e1c17SKevin Wolf }
3323a35e1c17SKevin Wolf
33241a52b73dSAlberto Garcia ret = 0;
33251a52b73dSAlberto Garcia
33261a52b73dSAlberto Garcia out:
33271a52b73dSAlberto Garcia qcow2_handle_l2meta(bs, &meta, false);
33281a52b73dSAlberto Garcia return ret;
3329a35e1c17SKevin Wolf }
3330a35e1c17SKevin Wolf
33317c5bcc42SStefan Hajnoczi /* qcow2_refcount_metadata_size:
33327c5bcc42SStefan Hajnoczi * @clusters: number of clusters to refcount (including data and L1/L2 tables)
33337c5bcc42SStefan Hajnoczi * @cluster_size: size of a cluster, in bytes
33347c5bcc42SStefan Hajnoczi * @refcount_order: refcount bits power-of-2 exponent
333512cc30a8SMax Reitz * @generous_increase: allow for the refcount table to be 1.5x as large as it
333612cc30a8SMax Reitz * needs to be
33377c5bcc42SStefan Hajnoczi *
33387c5bcc42SStefan Hajnoczi * Returns: Number of bytes required for refcount blocks and table metadata.
33397c5bcc42SStefan Hajnoczi */
qcow2_refcount_metadata_size(int64_t clusters,size_t cluster_size,int refcount_order,bool generous_increase,uint64_t * refblock_count)334012cc30a8SMax Reitz int64_t qcow2_refcount_metadata_size(int64_t clusters, size_t cluster_size,
334112cc30a8SMax Reitz int refcount_order, bool generous_increase,
334212cc30a8SMax Reitz uint64_t *refblock_count)
33437c5bcc42SStefan Hajnoczi {
33447c5bcc42SStefan Hajnoczi /*
33457c5bcc42SStefan Hajnoczi * Every host cluster is reference-counted, including metadata (even
33467c5bcc42SStefan Hajnoczi * refcount metadata is recursively included).
33477c5bcc42SStefan Hajnoczi *
33487c5bcc42SStefan Hajnoczi * An accurate formula for the size of refcount metadata size is difficult
33497c5bcc42SStefan Hajnoczi * to derive. An easier method of calculation is finding the fixed point
33507c5bcc42SStefan Hajnoczi * where no further refcount blocks or table clusters are required to
33517c5bcc42SStefan Hajnoczi * reference count every cluster.
33527c5bcc42SStefan Hajnoczi */
335302b1ecfaSAlberto Garcia int64_t blocks_per_table_cluster = cluster_size / REFTABLE_ENTRY_SIZE;
33547c5bcc42SStefan Hajnoczi int64_t refcounts_per_block = cluster_size * 8 / (1 << refcount_order);
33557c5bcc42SStefan Hajnoczi int64_t table = 0; /* number of refcount table clusters */
33567c5bcc42SStefan Hajnoczi int64_t blocks = 0; /* number of refcount block clusters */
33577c5bcc42SStefan Hajnoczi int64_t last;
33587c5bcc42SStefan Hajnoczi int64_t n = 0;
33597c5bcc42SStefan Hajnoczi
33607c5bcc42SStefan Hajnoczi do {
33617c5bcc42SStefan Hajnoczi last = n;
33627c5bcc42SStefan Hajnoczi blocks = DIV_ROUND_UP(clusters + table + blocks, refcounts_per_block);
33637c5bcc42SStefan Hajnoczi table = DIV_ROUND_UP(blocks, blocks_per_table_cluster);
33647c5bcc42SStefan Hajnoczi n = clusters + blocks + table;
336512cc30a8SMax Reitz
336612cc30a8SMax Reitz if (n == last && generous_increase) {
336712cc30a8SMax Reitz clusters += DIV_ROUND_UP(table, 2);
336812cc30a8SMax Reitz n = 0; /* force another loop */
336912cc30a8SMax Reitz generous_increase = false;
337012cc30a8SMax Reitz }
33717c5bcc42SStefan Hajnoczi } while (n != last);
33727c5bcc42SStefan Hajnoczi
337312cc30a8SMax Reitz if (refblock_count) {
337412cc30a8SMax Reitz *refblock_count = blocks;
337512cc30a8SMax Reitz }
337612cc30a8SMax Reitz
33777c5bcc42SStefan Hajnoczi return (blocks + table) * cluster_size;
33787c5bcc42SStefan Hajnoczi }
33797c5bcc42SStefan Hajnoczi
338095c67e3bSStefan Hajnoczi /**
338195c67e3bSStefan Hajnoczi * qcow2_calc_prealloc_size:
338295c67e3bSStefan Hajnoczi * @total_size: virtual disk size in bytes
338395c67e3bSStefan Hajnoczi * @cluster_size: cluster size in bytes
338495c67e3bSStefan Hajnoczi * @refcount_order: refcount bits power-of-2 exponent
33850dd07b29SAlberto Garcia * @extended_l2: true if the image has extended L2 entries
3386a9420734SKevin Wolf *
338795c67e3bSStefan Hajnoczi * Returns: Total number of bytes required for the fully allocated image
338895c67e3bSStefan Hajnoczi * (including metadata).
3389a9420734SKevin Wolf */
qcow2_calc_prealloc_size(int64_t total_size,size_t cluster_size,int refcount_order,bool extended_l2)339095c67e3bSStefan Hajnoczi static int64_t qcow2_calc_prealloc_size(int64_t total_size,
339195c67e3bSStefan Hajnoczi size_t cluster_size,
33920dd07b29SAlberto Garcia int refcount_order,
33930dd07b29SAlberto Garcia bool extended_l2)
339495c67e3bSStefan Hajnoczi {
33950e4271b7SHu Tao int64_t meta_size = 0;
33967c5bcc42SStefan Hajnoczi uint64_t nl1e, nl2e;
33979e029689SAlberto Garcia int64_t aligned_total_size = ROUND_UP(total_size, cluster_size);
33980dd07b29SAlberto Garcia size_t l2e_size = extended_l2 ? L2E_SIZE_EXTENDED : L2E_SIZE_NORMAL;
33990e4271b7SHu Tao
34000e4271b7SHu Tao /* header: 1 cluster */
34010e4271b7SHu Tao meta_size += cluster_size;
34020e4271b7SHu Tao
34030e4271b7SHu Tao /* total size of L2 tables */
34040e4271b7SHu Tao nl2e = aligned_total_size / cluster_size;
34050dd07b29SAlberto Garcia nl2e = ROUND_UP(nl2e, cluster_size / l2e_size);
34060dd07b29SAlberto Garcia meta_size += nl2e * l2e_size;
34070e4271b7SHu Tao
34080e4271b7SHu Tao /* total size of L1 tables */
34090dd07b29SAlberto Garcia nl1e = nl2e * l2e_size / cluster_size;
341002b1ecfaSAlberto Garcia nl1e = ROUND_UP(nl1e, cluster_size / L1E_SIZE);
341102b1ecfaSAlberto Garcia meta_size += nl1e * L1E_SIZE;
34120e4271b7SHu Tao
34137c5bcc42SStefan Hajnoczi /* total size of refcount table and blocks */
34147c5bcc42SStefan Hajnoczi meta_size += qcow2_refcount_metadata_size(
34157c5bcc42SStefan Hajnoczi (meta_size + aligned_total_size) / cluster_size,
341612cc30a8SMax Reitz cluster_size, refcount_order, false, NULL);
34170e4271b7SHu Tao
341895c67e3bSStefan Hajnoczi return meta_size + aligned_total_size;
341995c67e3bSStefan Hajnoczi }
342095c67e3bSStefan Hajnoczi
validate_cluster_size(size_t cluster_size,bool extended_l2,Error ** errp)34217be20252SAlberto Garcia static bool validate_cluster_size(size_t cluster_size, bool extended_l2,
34227be20252SAlberto Garcia Error **errp)
342395c67e3bSStefan Hajnoczi {
342429ca9e45SKevin Wolf int cluster_bits = ctz32(cluster_size);
342595c67e3bSStefan Hajnoczi if (cluster_bits < MIN_CLUSTER_BITS || cluster_bits > MAX_CLUSTER_BITS ||
342695c67e3bSStefan Hajnoczi (1 << cluster_bits) != cluster_size)
342795c67e3bSStefan Hajnoczi {
342895c67e3bSStefan Hajnoczi error_setg(errp, "Cluster size must be a power of two between %d and "
342995c67e3bSStefan Hajnoczi "%dk", 1 << MIN_CLUSTER_BITS, 1 << (MAX_CLUSTER_BITS - 10));
343029ca9e45SKevin Wolf return false;
343129ca9e45SKevin Wolf }
34327be20252SAlberto Garcia
34337be20252SAlberto Garcia if (extended_l2) {
34347be20252SAlberto Garcia unsigned min_cluster_size =
34357be20252SAlberto Garcia (1 << MIN_CLUSTER_BITS) * QCOW_EXTL2_SUBCLUSTERS_PER_CLUSTER;
34367be20252SAlberto Garcia if (cluster_size < min_cluster_size) {
34377be20252SAlberto Garcia error_setg(errp, "Extended L2 entries are only supported with "
34387be20252SAlberto Garcia "cluster sizes of at least %u bytes", min_cluster_size);
34397be20252SAlberto Garcia return false;
34407be20252SAlberto Garcia }
34417be20252SAlberto Garcia }
34427be20252SAlberto Garcia
344329ca9e45SKevin Wolf return true;
344429ca9e45SKevin Wolf }
344529ca9e45SKevin Wolf
qcow2_opt_get_cluster_size_del(QemuOpts * opts,bool extended_l2,Error ** errp)34467be20252SAlberto Garcia static size_t qcow2_opt_get_cluster_size_del(QemuOpts *opts, bool extended_l2,
34477be20252SAlberto Garcia Error **errp)
344829ca9e45SKevin Wolf {
344929ca9e45SKevin Wolf size_t cluster_size;
345029ca9e45SKevin Wolf
345129ca9e45SKevin Wolf cluster_size = qemu_opt_get_size_del(opts, BLOCK_OPT_CLUSTER_SIZE,
345229ca9e45SKevin Wolf DEFAULT_CLUSTER_SIZE);
34537be20252SAlberto Garcia if (!validate_cluster_size(cluster_size, extended_l2, errp)) {
34540eb4a8c1SStefan Hajnoczi return 0;
345595c67e3bSStefan Hajnoczi }
34560eb4a8c1SStefan Hajnoczi return cluster_size;
34570eb4a8c1SStefan Hajnoczi }
34580eb4a8c1SStefan Hajnoczi
qcow2_opt_get_version_del(QemuOpts * opts,Error ** errp)34590eb4a8c1SStefan Hajnoczi static int qcow2_opt_get_version_del(QemuOpts *opts, Error **errp)
34600eb4a8c1SStefan Hajnoczi {
34610eb4a8c1SStefan Hajnoczi char *buf;
34620eb4a8c1SStefan Hajnoczi int ret;
34630eb4a8c1SStefan Hajnoczi
34640eb4a8c1SStefan Hajnoczi buf = qemu_opt_get_del(opts, BLOCK_OPT_COMPAT_LEVEL);
34650eb4a8c1SStefan Hajnoczi if (!buf) {
34660eb4a8c1SStefan Hajnoczi ret = 3; /* default */
34670eb4a8c1SStefan Hajnoczi } else if (!strcmp(buf, "0.10")) {
34680eb4a8c1SStefan Hajnoczi ret = 2;
34690eb4a8c1SStefan Hajnoczi } else if (!strcmp(buf, "1.1")) {
34700eb4a8c1SStefan Hajnoczi ret = 3;
34710eb4a8c1SStefan Hajnoczi } else {
34720eb4a8c1SStefan Hajnoczi error_setg(errp, "Invalid compatibility level: '%s'", buf);
34730eb4a8c1SStefan Hajnoczi ret = -EINVAL;
34740eb4a8c1SStefan Hajnoczi }
34750eb4a8c1SStefan Hajnoczi g_free(buf);
34760eb4a8c1SStefan Hajnoczi return ret;
34770eb4a8c1SStefan Hajnoczi }
34780eb4a8c1SStefan Hajnoczi
qcow2_opt_get_refcount_bits_del(QemuOpts * opts,int version,Error ** errp)34790eb4a8c1SStefan Hajnoczi static uint64_t qcow2_opt_get_refcount_bits_del(QemuOpts *opts, int version,
34800eb4a8c1SStefan Hajnoczi Error **errp)
34810eb4a8c1SStefan Hajnoczi {
34820eb4a8c1SStefan Hajnoczi uint64_t refcount_bits;
34830eb4a8c1SStefan Hajnoczi
34840eb4a8c1SStefan Hajnoczi refcount_bits = qemu_opt_get_number_del(opts, BLOCK_OPT_REFCOUNT_BITS, 16);
34850eb4a8c1SStefan Hajnoczi if (refcount_bits > 64 || !is_power_of_2(refcount_bits)) {
34860eb4a8c1SStefan Hajnoczi error_setg(errp, "Refcount width must be a power of two and may not "
34870eb4a8c1SStefan Hajnoczi "exceed 64 bits");
34880eb4a8c1SStefan Hajnoczi return 0;
34890eb4a8c1SStefan Hajnoczi }
34900eb4a8c1SStefan Hajnoczi
34910eb4a8c1SStefan Hajnoczi if (version < 3 && refcount_bits != 16) {
34920eb4a8c1SStefan Hajnoczi error_setg(errp, "Different refcount widths than 16 bits require "
34930eb4a8c1SStefan Hajnoczi "compatibility level 1.1 or above (use compat=1.1 or "
34940eb4a8c1SStefan Hajnoczi "greater)");
34950eb4a8c1SStefan Hajnoczi return 0;
34960eb4a8c1SStefan Hajnoczi }
34970eb4a8c1SStefan Hajnoczi
34980eb4a8c1SStefan Hajnoczi return refcount_bits;
34990eb4a8c1SStefan Hajnoczi }
35000eb4a8c1SStefan Hajnoczi
35014db7ba3bSKevin Wolf static int coroutine_fn GRAPH_UNLOCKED
qcow2_co_create(BlockdevCreateOptions * create_options,Error ** errp)350260900b7bSKevin Wolf qcow2_co_create(BlockdevCreateOptions *create_options, Error **errp)
35030eb4a8c1SStefan Hajnoczi {
3504d13e3b46SZhao Liu ERRP_GUARD();
350529ca9e45SKevin Wolf BlockdevCreateOptionsQcow2 *qcow2_opts;
35060eb4a8c1SStefan Hajnoczi QDict *options;
350795c67e3bSStefan Hajnoczi
350895c67e3bSStefan Hajnoczi /*
350995c67e3bSStefan Hajnoczi * Open the image file and write a minimal qcow2 header.
351095c67e3bSStefan Hajnoczi *
351195c67e3bSStefan Hajnoczi * We keep things simple and start with a zero-sized image. We also
351295c67e3bSStefan Hajnoczi * do without refcount blocks or a L1 table for now. We'll fix the
351395c67e3bSStefan Hajnoczi * inconsistency later.
351495c67e3bSStefan Hajnoczi *
351595c67e3bSStefan Hajnoczi * We do need a refcount table because growing the refcount table means
3516a951a631SEric Blake * allocating two new refcount blocks - the second of which would be at
351795c67e3bSStefan Hajnoczi * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
351895c67e3bSStefan Hajnoczi * size for any qcow2 image.
351995c67e3bSStefan Hajnoczi */
3520e1d74bc6SKevin Wolf BlockBackend *blk = NULL;
3521e1d74bc6SKevin Wolf BlockDriverState *bs = NULL;
3522dcc98687SKevin Wolf BlockDriverState *data_bs = NULL;
352395c67e3bSStefan Hajnoczi QCowHeader *header;
352429ca9e45SKevin Wolf size_t cluster_size;
352529ca9e45SKevin Wolf int version;
352629ca9e45SKevin Wolf int refcount_order;
352795c67e3bSStefan Hajnoczi uint64_t *refcount_table;
352895c67e3bSStefan Hajnoczi int ret;
3529572ad978SDenis Plotnikov uint8_t compression_type = QCOW2_COMPRESSION_TYPE_ZLIB;
353095c67e3bSStefan Hajnoczi
353129ca9e45SKevin Wolf assert(create_options->driver == BLOCKDEV_DRIVER_QCOW2);
353229ca9e45SKevin Wolf qcow2_opts = &create_options->u.qcow2;
353329ca9e45SKevin Wolf
3534ecbc57caSKevin Wolf bs = bdrv_co_open_blockdev_ref(qcow2_opts->file, errp);
3535e1d74bc6SKevin Wolf if (bs == NULL) {
3536e1d74bc6SKevin Wolf return -EIO;
3537e1d74bc6SKevin Wolf }
3538e1d74bc6SKevin Wolf
3539e1d74bc6SKevin Wolf /* Validate options and set default values */
354029ca9e45SKevin Wolf if (!QEMU_IS_ALIGNED(qcow2_opts->size, BDRV_SECTOR_SIZE)) {
35413afea402SAlberto Garcia error_setg(errp, "Image size must be a multiple of %u bytes",
35423afea402SAlberto Garcia (unsigned) BDRV_SECTOR_SIZE);
354329ca9e45SKevin Wolf ret = -EINVAL;
354429ca9e45SKevin Wolf goto out;
354529ca9e45SKevin Wolf }
354629ca9e45SKevin Wolf
354729ca9e45SKevin Wolf if (qcow2_opts->has_version) {
354829ca9e45SKevin Wolf switch (qcow2_opts->version) {
354929ca9e45SKevin Wolf case BLOCKDEV_QCOW2_VERSION_V2:
355029ca9e45SKevin Wolf version = 2;
355129ca9e45SKevin Wolf break;
355229ca9e45SKevin Wolf case BLOCKDEV_QCOW2_VERSION_V3:
355329ca9e45SKevin Wolf version = 3;
355429ca9e45SKevin Wolf break;
355529ca9e45SKevin Wolf default:
355629ca9e45SKevin Wolf g_assert_not_reached();
355729ca9e45SKevin Wolf }
355829ca9e45SKevin Wolf } else {
355929ca9e45SKevin Wolf version = 3;
356029ca9e45SKevin Wolf }
356129ca9e45SKevin Wolf
356229ca9e45SKevin Wolf if (qcow2_opts->has_cluster_size) {
356329ca9e45SKevin Wolf cluster_size = qcow2_opts->cluster_size;
356429ca9e45SKevin Wolf } else {
356529ca9e45SKevin Wolf cluster_size = DEFAULT_CLUSTER_SIZE;
356629ca9e45SKevin Wolf }
356729ca9e45SKevin Wolf
35687be20252SAlberto Garcia if (!qcow2_opts->has_extended_l2) {
35697be20252SAlberto Garcia qcow2_opts->extended_l2 = false;
35707be20252SAlberto Garcia }
35717be20252SAlberto Garcia if (qcow2_opts->extended_l2) {
35727be20252SAlberto Garcia if (version < 3) {
35737be20252SAlberto Garcia error_setg(errp, "Extended L2 entries are only supported with "
35747be20252SAlberto Garcia "compatibility level 1.1 and above (use version=v3 or "
35757be20252SAlberto Garcia "greater)");
35767be20252SAlberto Garcia ret = -EINVAL;
35777be20252SAlberto Garcia goto out;
35787be20252SAlberto Garcia }
35797be20252SAlberto Garcia }
35807be20252SAlberto Garcia
35817be20252SAlberto Garcia if (!validate_cluster_size(cluster_size, qcow2_opts->extended_l2, errp)) {
3582e1d74bc6SKevin Wolf ret = -EINVAL;
3583e1d74bc6SKevin Wolf goto out;
358429ca9e45SKevin Wolf }
358529ca9e45SKevin Wolf
358629ca9e45SKevin Wolf if (!qcow2_opts->has_preallocation) {
358729ca9e45SKevin Wolf qcow2_opts->preallocation = PREALLOC_MODE_OFF;
358829ca9e45SKevin Wolf }
358954fde4ffSMarkus Armbruster if (qcow2_opts->backing_file &&
35902118771dSAlberto Garcia qcow2_opts->preallocation != PREALLOC_MODE_OFF &&
35912118771dSAlberto Garcia !qcow2_opts->extended_l2)
359229ca9e45SKevin Wolf {
35932118771dSAlberto Garcia error_setg(errp, "Backing file and preallocation can only be used at "
35942118771dSAlberto Garcia "the same time if extended_l2 is on");
3595e1d74bc6SKevin Wolf ret = -EINVAL;
3596e1d74bc6SKevin Wolf goto out;
359729ca9e45SKevin Wolf }
359854fde4ffSMarkus Armbruster if (qcow2_opts->has_backing_fmt && !qcow2_opts->backing_file) {
359929ca9e45SKevin Wolf error_setg(errp, "Backing format cannot be used without backing file");
3600e1d74bc6SKevin Wolf ret = -EINVAL;
3601e1d74bc6SKevin Wolf goto out;
360229ca9e45SKevin Wolf }
360329ca9e45SKevin Wolf
360429ca9e45SKevin Wolf if (!qcow2_opts->has_lazy_refcounts) {
360529ca9e45SKevin Wolf qcow2_opts->lazy_refcounts = false;
360629ca9e45SKevin Wolf }
360729ca9e45SKevin Wolf if (version < 3 && qcow2_opts->lazy_refcounts) {
360829ca9e45SKevin Wolf error_setg(errp, "Lazy refcounts only supported with compatibility "
3609b76b4f60SKevin Wolf "level 1.1 and above (use version=v3 or greater)");
3610e1d74bc6SKevin Wolf ret = -EINVAL;
3611e1d74bc6SKevin Wolf goto out;
361229ca9e45SKevin Wolf }
361329ca9e45SKevin Wolf
361429ca9e45SKevin Wolf if (!qcow2_opts->has_refcount_bits) {
361529ca9e45SKevin Wolf qcow2_opts->refcount_bits = 16;
361629ca9e45SKevin Wolf }
361729ca9e45SKevin Wolf if (qcow2_opts->refcount_bits > 64 ||
361829ca9e45SKevin Wolf !is_power_of_2(qcow2_opts->refcount_bits))
361929ca9e45SKevin Wolf {
362029ca9e45SKevin Wolf error_setg(errp, "Refcount width must be a power of two and may not "
362129ca9e45SKevin Wolf "exceed 64 bits");
3622e1d74bc6SKevin Wolf ret = -EINVAL;
3623e1d74bc6SKevin Wolf goto out;
362429ca9e45SKevin Wolf }
362529ca9e45SKevin Wolf if (version < 3 && qcow2_opts->refcount_bits != 16) {
362629ca9e45SKevin Wolf error_setg(errp, "Different refcount widths than 16 bits require "
3627b76b4f60SKevin Wolf "compatibility level 1.1 or above (use version=v3 or "
362829ca9e45SKevin Wolf "greater)");
3629e1d74bc6SKevin Wolf ret = -EINVAL;
3630e1d74bc6SKevin Wolf goto out;
363129ca9e45SKevin Wolf }
363229ca9e45SKevin Wolf refcount_order = ctz32(qcow2_opts->refcount_bits);
363329ca9e45SKevin Wolf
36346c3944dcSKevin Wolf if (qcow2_opts->data_file_raw && !qcow2_opts->data_file) {
36356c3944dcSKevin Wolf error_setg(errp, "data-file-raw requires data-file");
36366c3944dcSKevin Wolf ret = -EINVAL;
36376c3944dcSKevin Wolf goto out;
36386c3944dcSKevin Wolf }
363954fde4ffSMarkus Armbruster if (qcow2_opts->data_file_raw && qcow2_opts->backing_file) {
36406c3944dcSKevin Wolf error_setg(errp, "Backing file and data-file-raw cannot be used at "
36416c3944dcSKevin Wolf "the same time");
36426c3944dcSKevin Wolf ret = -EINVAL;
36436c3944dcSKevin Wolf goto out;
36446c3944dcSKevin Wolf }
364548410829SMax Reitz if (qcow2_opts->data_file_raw &&
364648410829SMax Reitz qcow2_opts->preallocation == PREALLOC_MODE_OFF)
364748410829SMax Reitz {
364848410829SMax Reitz /*
364948410829SMax Reitz * data-file-raw means that "the external data file can be
365048410829SMax Reitz * read as a consistent standalone raw image without looking
365148410829SMax Reitz * at the qcow2 metadata." It does not say that the metadata
365248410829SMax Reitz * must be ignored, though (and the qcow2 driver in fact does
365348410829SMax Reitz * not ignore it), so the L1/L2 tables must be present and
365448410829SMax Reitz * give a 1:1 mapping, so you get the same result regardless
365548410829SMax Reitz * of whether you look at the metadata or whether you ignore
365648410829SMax Reitz * it.
365748410829SMax Reitz */
365848410829SMax Reitz qcow2_opts->preallocation = PREALLOC_MODE_METADATA;
365948410829SMax Reitz
366048410829SMax Reitz /*
366148410829SMax Reitz * Cannot use preallocation with backing files, but giving a
366248410829SMax Reitz * backing file when specifying data_file_raw is an error
366348410829SMax Reitz * anyway.
366448410829SMax Reitz */
366554fde4ffSMarkus Armbruster assert(!qcow2_opts->backing_file);
366648410829SMax Reitz }
36676c3944dcSKevin Wolf
3668dcc98687SKevin Wolf if (qcow2_opts->data_file) {
3669dcc98687SKevin Wolf if (version < 3) {
3670dcc98687SKevin Wolf error_setg(errp, "External data files are only supported with "
3671dcc98687SKevin Wolf "compatibility level 1.1 and above (use version=v3 or "
3672dcc98687SKevin Wolf "greater)");
3673dcc98687SKevin Wolf ret = -EINVAL;
3674dcc98687SKevin Wolf goto out;
3675dcc98687SKevin Wolf }
3676ecbc57caSKevin Wolf data_bs = bdrv_co_open_blockdev_ref(qcow2_opts->data_file, errp);
3677a0cf8363SKevin Wolf if (data_bs == NULL) {
3678dcc98687SKevin Wolf ret = -EIO;
3679dcc98687SKevin Wolf goto out;
3680dcc98687SKevin Wolf }
3681dcc98687SKevin Wolf }
368229ca9e45SKevin Wolf
3683572ad978SDenis Plotnikov if (qcow2_opts->has_compression_type &&
3684572ad978SDenis Plotnikov qcow2_opts->compression_type != QCOW2_COMPRESSION_TYPE_ZLIB) {
3685572ad978SDenis Plotnikov
3686572ad978SDenis Plotnikov ret = -EINVAL;
3687572ad978SDenis Plotnikov
3688572ad978SDenis Plotnikov if (version < 3) {
3689572ad978SDenis Plotnikov error_setg(errp, "Non-zlib compression type is only supported with "
3690572ad978SDenis Plotnikov "compatibility level 1.1 and above (use version=v3 or "
3691572ad978SDenis Plotnikov "greater)");
3692572ad978SDenis Plotnikov goto out;
3693572ad978SDenis Plotnikov }
3694572ad978SDenis Plotnikov
3695572ad978SDenis Plotnikov switch (qcow2_opts->compression_type) {
3696d298ac10SDenis Plotnikov #ifdef CONFIG_ZSTD
3697d298ac10SDenis Plotnikov case QCOW2_COMPRESSION_TYPE_ZSTD:
3698d298ac10SDenis Plotnikov break;
3699d298ac10SDenis Plotnikov #endif
3700572ad978SDenis Plotnikov default:
3701572ad978SDenis Plotnikov error_setg(errp, "Unknown compression type");
3702572ad978SDenis Plotnikov goto out;
3703572ad978SDenis Plotnikov }
3704572ad978SDenis Plotnikov
3705572ad978SDenis Plotnikov compression_type = qcow2_opts->compression_type;
3706572ad978SDenis Plotnikov }
3707572ad978SDenis Plotnikov
370829ca9e45SKevin Wolf /* Create BlockBackend to write to the image */
3709ecbc57caSKevin Wolf blk = blk_co_new_with_bs(bs, BLK_PERM_WRITE | BLK_PERM_RESIZE, BLK_PERM_ALL,
3710a3aeeab5SEric Blake errp);
3711a3aeeab5SEric Blake if (!blk) {
3712a3aeeab5SEric Blake ret = -EPERM;
3713cbf2b7c4SKevin Wolf goto out;
3714a9420734SKevin Wolf }
371523588797SKevin Wolf blk_set_allow_write_beyond_eof(blk, true);
371623588797SKevin Wolf
3717a9420734SKevin Wolf /* Write the header */
3718f8413b3cSKevin Wolf QEMU_BUILD_BUG_ON((1 << MIN_CLUSTER_BITS) < sizeof(*header));
3719f8413b3cSKevin Wolf header = g_malloc0(cluster_size);
3720f8413b3cSKevin Wolf *header = (QCowHeader) {
3721f8413b3cSKevin Wolf .magic = cpu_to_be32(QCOW_MAGIC),
3722f8413b3cSKevin Wolf .version = cpu_to_be32(version),
37230eb4a8c1SStefan Hajnoczi .cluster_bits = cpu_to_be32(ctz32(cluster_size)),
3724f8413b3cSKevin Wolf .size = cpu_to_be64(0),
3725f8413b3cSKevin Wolf .l1_table_offset = cpu_to_be64(0),
3726f8413b3cSKevin Wolf .l1_size = cpu_to_be32(0),
3727f8413b3cSKevin Wolf .refcount_table_offset = cpu_to_be64(cluster_size),
3728f8413b3cSKevin Wolf .refcount_table_clusters = cpu_to_be32(1),
3729bd4b167fSMax Reitz .refcount_order = cpu_to_be32(refcount_order),
3730572ad978SDenis Plotnikov /* don't deal with endianness since compression_type is 1 byte long */
3731572ad978SDenis Plotnikov .compression_type = compression_type,
3732f8413b3cSKevin Wolf .header_length = cpu_to_be32(sizeof(*header)),
3733f8413b3cSKevin Wolf };
3734a9420734SKevin Wolf
3735b25b387fSDaniel P. Berrange /* We'll update this to correct value later */
3736f8413b3cSKevin Wolf header->crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
3737a9420734SKevin Wolf
373829ca9e45SKevin Wolf if (qcow2_opts->lazy_refcounts) {
3739f8413b3cSKevin Wolf header->compatible_features |=
3740bfe8043eSStefan Hajnoczi cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS);
3741bfe8043eSStefan Hajnoczi }
3742dcc98687SKevin Wolf if (data_bs) {
3743dcc98687SKevin Wolf header->incompatible_features |=
3744dcc98687SKevin Wolf cpu_to_be64(QCOW2_INCOMPAT_DATA_FILE);
3745dcc98687SKevin Wolf }
37466c3944dcSKevin Wolf if (qcow2_opts->data_file_raw) {
37476c3944dcSKevin Wolf header->autoclear_features |=
37486c3944dcSKevin Wolf cpu_to_be64(QCOW2_AUTOCLEAR_DATA_FILE_RAW);
37496c3944dcSKevin Wolf }
3750572ad978SDenis Plotnikov if (compression_type != QCOW2_COMPRESSION_TYPE_ZLIB) {
3751572ad978SDenis Plotnikov header->incompatible_features |=
3752572ad978SDenis Plotnikov cpu_to_be64(QCOW2_INCOMPAT_COMPRESSION);
3753572ad978SDenis Plotnikov }
3754bfe8043eSStefan Hajnoczi
37557be20252SAlberto Garcia if (qcow2_opts->extended_l2) {
37567be20252SAlberto Garcia header->incompatible_features |=
37577be20252SAlberto Garcia cpu_to_be64(QCOW2_INCOMPAT_EXTL2);
37587be20252SAlberto Garcia }
37597be20252SAlberto Garcia
376038505e2aSAlberto Faria ret = blk_co_pwrite(blk, 0, cluster_size, header, 0);
3761f8413b3cSKevin Wolf g_free(header);
3762a9420734SKevin Wolf if (ret < 0) {
37633ef6c40aSMax Reitz error_setg_errno(errp, -ret, "Could not write qcow2 header");
3764a9420734SKevin Wolf goto out;
3765a9420734SKevin Wolf }
3766a9420734SKevin Wolf
3767b106ad91SKevin Wolf /* Write a refcount table with one refcount block */
3768b106ad91SKevin Wolf refcount_table = g_malloc0(2 * cluster_size);
3769b106ad91SKevin Wolf refcount_table[0] = cpu_to_be64(2 * cluster_size);
377038505e2aSAlberto Faria ret = blk_co_pwrite(blk, cluster_size, 2 * cluster_size, refcount_table, 0);
37717267c094SAnthony Liguori g_free(refcount_table);
3772a9420734SKevin Wolf
3773a9420734SKevin Wolf if (ret < 0) {
37743ef6c40aSMax Reitz error_setg_errno(errp, -ret, "Could not write refcount table");
3775a9420734SKevin Wolf goto out;
3776a9420734SKevin Wolf }
3777a9420734SKevin Wolf
3778b2ab5f54SKevin Wolf blk_co_unref(blk);
377923588797SKevin Wolf blk = NULL;
3780a9420734SKevin Wolf
3781a9420734SKevin Wolf /*
3782a9420734SKevin Wolf * And now open the image and make it consistent first (i.e. increase the
3783a9420734SKevin Wolf * refcount of the cluster that is occupied by the header and the refcount
3784a9420734SKevin Wolf * table)
3785a9420734SKevin Wolf */
3786e6641719SMax Reitz options = qdict_new();
378746f5ac20SEric Blake qdict_put_str(options, "driver", "qcow2");
3788cbf2b7c4SKevin Wolf qdict_put_str(options, "file", bs->node_name);
3789dcc98687SKevin Wolf if (data_bs) {
3790dcc98687SKevin Wolf qdict_put_str(options, "data-file", data_bs->node_name);
3791dcc98687SKevin Wolf }
3792ecbc57caSKevin Wolf blk = blk_co_new_open(NULL, NULL, options,
379355880601SKevin Wolf BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_NO_FLUSH,
3794af175e85SMarkus Armbruster errp);
379523588797SKevin Wolf if (blk == NULL) {
379623588797SKevin Wolf ret = -EIO;
3797a9420734SKevin Wolf goto out;
3798a9420734SKevin Wolf }
3799a9420734SKevin Wolf
38004db7ba3bSKevin Wolf bdrv_graph_co_rdlock();
380123588797SKevin Wolf ret = qcow2_alloc_clusters(blk_bs(blk), 3 * cluster_size);
3802a9420734SKevin Wolf if (ret < 0) {
38034db7ba3bSKevin Wolf bdrv_graph_co_rdunlock();
38043ef6c40aSMax Reitz error_setg_errno(errp, -ret, "Could not allocate clusters for qcow2 "
38053ef6c40aSMax Reitz "header and refcount table");
3806a9420734SKevin Wolf goto out;
3807a9420734SKevin Wolf
3808a9420734SKevin Wolf } else if (ret != 0) {
3809a9420734SKevin Wolf error_report("Huh, first cluster in empty image is already in use?");
3810a9420734SKevin Wolf abort();
3811a9420734SKevin Wolf }
3812a9420734SKevin Wolf
38139b890bdcSKevin Wolf /* Set the external data file if necessary */
38149b890bdcSKevin Wolf if (data_bs) {
38159b890bdcSKevin Wolf BDRVQcow2State *s = blk_bs(blk)->opaque;
38169b890bdcSKevin Wolf s->image_data_file = g_strdup(data_bs->filename);
38179b890bdcSKevin Wolf }
38189b890bdcSKevin Wolf
3819b527c9b3SKevin Wolf /* Create a full header (including things like feature table) */
382023588797SKevin Wolf ret = qcow2_update_header(blk_bs(blk));
38214db7ba3bSKevin Wolf bdrv_graph_co_rdunlock();
38224db7ba3bSKevin Wolf
3823b527c9b3SKevin Wolf if (ret < 0) {
3824b527c9b3SKevin Wolf error_setg_errno(errp, -ret, "Could not update qcow2 header");
3825b527c9b3SKevin Wolf goto out;
3826b527c9b3SKevin Wolf }
3827b527c9b3SKevin Wolf
3828a9420734SKevin Wolf /* Okay, now that we have a valid image, let's give it the right size */
382938505e2aSAlberto Faria ret = blk_co_truncate(blk, qcow2_opts->size, false,
383038505e2aSAlberto Faria qcow2_opts->preallocation, 0, errp);
3831a9420734SKevin Wolf if (ret < 0) {
3832ed3d2ec9SMax Reitz error_prepend(errp, "Could not resize image: ");
3833a9420734SKevin Wolf goto out;
3834a9420734SKevin Wolf }
3835a9420734SKevin Wolf
3836a9420734SKevin Wolf /* Want a backing file? There you go. */
383754fde4ffSMarkus Armbruster if (qcow2_opts->backing_file) {
383829ca9e45SKevin Wolf const char *backing_format = NULL;
383929ca9e45SKevin Wolf
384029ca9e45SKevin Wolf if (qcow2_opts->has_backing_fmt) {
384129ca9e45SKevin Wolf backing_format = BlockdevDriver_str(qcow2_opts->backing_fmt);
384229ca9e45SKevin Wolf }
384329ca9e45SKevin Wolf
3844e2dd2737SKevin Wolf bdrv_graph_co_rdlock();
3845e2dd2737SKevin Wolf ret = bdrv_co_change_backing_file(blk_bs(blk), qcow2_opts->backing_file,
3846e54ee1b3SEric Blake backing_format, false);
3847e2dd2737SKevin Wolf bdrv_graph_co_rdunlock();
3848e2dd2737SKevin Wolf
3849a9420734SKevin Wolf if (ret < 0) {
38503ef6c40aSMax Reitz error_setg_errno(errp, -ret, "Could not assign backing file '%s' "
385129ca9e45SKevin Wolf "with format '%s'", qcow2_opts->backing_file,
385229ca9e45SKevin Wolf backing_format);
3853a9420734SKevin Wolf goto out;
3854a9420734SKevin Wolf }
3855a9420734SKevin Wolf }
3856a9420734SKevin Wolf
3857b25b387fSDaniel P. Berrange /* Want encryption? There you go. */
385854fde4ffSMarkus Armbruster if (qcow2_opts->encrypt) {
38594db7ba3bSKevin Wolf bdrv_graph_co_rdlock();
386060900b7bSKevin Wolf ret = qcow2_set_up_encryption(blk_bs(blk), qcow2_opts->encrypt, errp);
38614db7ba3bSKevin Wolf bdrv_graph_co_rdunlock();
38624db7ba3bSKevin Wolf
3863b25b387fSDaniel P. Berrange if (ret < 0) {
3864b25b387fSDaniel P. Berrange goto out;
3865b25b387fSDaniel P. Berrange }
3866b25b387fSDaniel P. Berrange }
3867b25b387fSDaniel P. Berrange
3868b2ab5f54SKevin Wolf blk_co_unref(blk);
386923588797SKevin Wolf blk = NULL;
3870ba2ab2f2SMax Reitz
3871b25b387fSDaniel P. Berrange /* Reopen the image without BDRV_O_NO_FLUSH to flush it before returning.
3872b25b387fSDaniel P. Berrange * Using BDRV_O_NO_IO, since encryption is now setup we don't want to
3873b25b387fSDaniel P. Berrange * have to setup decryption context. We're not doing any I/O on the top
3874b25b387fSDaniel P. Berrange * level BlockDriverState, only lower layers, where BDRV_O_NO_IO does
3875b25b387fSDaniel P. Berrange * not have effect.
3876b25b387fSDaniel P. Berrange */
3877e6641719SMax Reitz options = qdict_new();
387846f5ac20SEric Blake qdict_put_str(options, "driver", "qcow2");
3879cbf2b7c4SKevin Wolf qdict_put_str(options, "file", bs->node_name);
3880dcc98687SKevin Wolf if (data_bs) {
3881dcc98687SKevin Wolf qdict_put_str(options, "data-file", data_bs->node_name);
3882dcc98687SKevin Wolf }
3883ecbc57caSKevin Wolf blk = blk_co_new_open(NULL, NULL, options,
3884b25b387fSDaniel P. Berrange BDRV_O_RDWR | BDRV_O_NO_BACKING | BDRV_O_NO_IO,
3885af175e85SMarkus Armbruster errp);
388623588797SKevin Wolf if (blk == NULL) {
388723588797SKevin Wolf ret = -EIO;
3888ba2ab2f2SMax Reitz goto out;
3889ba2ab2f2SMax Reitz }
3890ba2ab2f2SMax Reitz
3891a9420734SKevin Wolf ret = 0;
3892a9420734SKevin Wolf out:
3893b2ab5f54SKevin Wolf blk_co_unref(blk);
3894b2ab5f54SKevin Wolf bdrv_co_unref(bs);
3895b2ab5f54SKevin Wolf bdrv_co_unref(data_bs);
3896a9420734SKevin Wolf return ret;
3897a9420734SKevin Wolf }
3898de5f3f40SKevin Wolf
38994db7ba3bSKevin Wolf static int coroutine_fn GRAPH_UNLOCKED
qcow2_co_create_opts(BlockDriver * drv,const char * filename,QemuOpts * opts,Error ** errp)39004ec8df01SKevin Wolf qcow2_co_create_opts(BlockDriver *drv, const char *filename, QemuOpts *opts,
3901efc75e2aSStefan Hajnoczi Error **errp)
3902de5f3f40SKevin Wolf {
3903b76b4f60SKevin Wolf BlockdevCreateOptions *create_options = NULL;
390492adf9dbSMarkus Armbruster QDict *qdict;
3905b76b4f60SKevin Wolf Visitor *v;
3906cbf2b7c4SKevin Wolf BlockDriverState *bs = NULL;
39079b890bdcSKevin Wolf BlockDriverState *data_bs = NULL;
3908b76b4f60SKevin Wolf const char *val;
39093ef6c40aSMax Reitz int ret;
3910de5f3f40SKevin Wolf
3911b76b4f60SKevin Wolf /* Only the keyval visitor supports the dotted syntax needed for
3912b76b4f60SKevin Wolf * encryption, so go through a QDict before getting a QAPI type. Ignore
3913b76b4f60SKevin Wolf * options meant for the protocol layer so that the visitor doesn't
3914b76b4f60SKevin Wolf * complain. */
3915b76b4f60SKevin Wolf qdict = qemu_opts_to_qdict_filtered(opts, NULL, bdrv_qcow2.create_opts,
3916b76b4f60SKevin Wolf true);
3917b76b4f60SKevin Wolf
3918b76b4f60SKevin Wolf /* Handle encryption options */
3919b76b4f60SKevin Wolf val = qdict_get_try_str(qdict, BLOCK_OPT_ENCRYPT);
3920b76b4f60SKevin Wolf if (val && !strcmp(val, "on")) {
3921b76b4f60SKevin Wolf qdict_put_str(qdict, BLOCK_OPT_ENCRYPT, "qcow");
3922b76b4f60SKevin Wolf } else if (val && !strcmp(val, "off")) {
3923b76b4f60SKevin Wolf qdict_del(qdict, BLOCK_OPT_ENCRYPT);
392429ca9e45SKevin Wolf }
392560900b7bSKevin Wolf
3926b76b4f60SKevin Wolf val = qdict_get_try_str(qdict, BLOCK_OPT_ENCRYPT_FORMAT);
3927b76b4f60SKevin Wolf if (val && !strcmp(val, "aes")) {
3928b76b4f60SKevin Wolf qdict_put_str(qdict, BLOCK_OPT_ENCRYPT_FORMAT, "qcow");
392960900b7bSKevin Wolf }
393060900b7bSKevin Wolf
3931b76b4f60SKevin Wolf /* Convert compat=0.10/1.1 into compat=v2/v3, to be renamed into
3932b76b4f60SKevin Wolf * version=v2/v3 below. */
3933b76b4f60SKevin Wolf val = qdict_get_try_str(qdict, BLOCK_OPT_COMPAT_LEVEL);
3934b76b4f60SKevin Wolf if (val && !strcmp(val, "0.10")) {
3935b76b4f60SKevin Wolf qdict_put_str(qdict, BLOCK_OPT_COMPAT_LEVEL, "v2");
3936b76b4f60SKevin Wolf } else if (val && !strcmp(val, "1.1")) {
3937b76b4f60SKevin Wolf qdict_put_str(qdict, BLOCK_OPT_COMPAT_LEVEL, "v3");
3938b76b4f60SKevin Wolf }
3939b76b4f60SKevin Wolf
3940b76b4f60SKevin Wolf /* Change legacy command line options into QMP ones */
3941b76b4f60SKevin Wolf static const QDictRenames opt_renames[] = {
3942b76b4f60SKevin Wolf { BLOCK_OPT_BACKING_FILE, "backing-file" },
3943b76b4f60SKevin Wolf { BLOCK_OPT_BACKING_FMT, "backing-fmt" },
3944b76b4f60SKevin Wolf { BLOCK_OPT_CLUSTER_SIZE, "cluster-size" },
3945b76b4f60SKevin Wolf { BLOCK_OPT_LAZY_REFCOUNTS, "lazy-refcounts" },
39467be20252SAlberto Garcia { BLOCK_OPT_EXTL2, "extended-l2" },
3947b76b4f60SKevin Wolf { BLOCK_OPT_REFCOUNT_BITS, "refcount-bits" },
3948b76b4f60SKevin Wolf { BLOCK_OPT_ENCRYPT, BLOCK_OPT_ENCRYPT_FORMAT },
3949b76b4f60SKevin Wolf { BLOCK_OPT_COMPAT_LEVEL, "version" },
39506c3944dcSKevin Wolf { BLOCK_OPT_DATA_FILE_RAW, "data-file-raw" },
3951572ad978SDenis Plotnikov { BLOCK_OPT_COMPRESSION_TYPE, "compression-type" },
3952b76b4f60SKevin Wolf { NULL, NULL },
3953b76b4f60SKevin Wolf };
3954b76b4f60SKevin Wolf
3955b76b4f60SKevin Wolf if (!qdict_rename_keys(qdict, opt_renames, errp)) {
39560eb4a8c1SStefan Hajnoczi ret = -EINVAL;
39570eb4a8c1SStefan Hajnoczi goto finish;
39580eb4a8c1SStefan Hajnoczi }
3959bd4b167fSMax Reitz
3960cbf2b7c4SKevin Wolf /* Create and open the file (protocol layer) */
39612475a0d0SEmanuele Giuseppe Esposito ret = bdrv_co_create_file(filename, opts, errp);
3962cbf2b7c4SKevin Wolf if (ret < 0) {
3963cbf2b7c4SKevin Wolf goto finish;
3964cbf2b7c4SKevin Wolf }
3965cbf2b7c4SKevin Wolf
3966ecbc57caSKevin Wolf bs = bdrv_co_open(filename, NULL, NULL,
3967cbf2b7c4SKevin Wolf BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_PROTOCOL, errp);
3968cbf2b7c4SKevin Wolf if (bs == NULL) {
3969cbf2b7c4SKevin Wolf ret = -EIO;
3970cbf2b7c4SKevin Wolf goto finish;
3971cbf2b7c4SKevin Wolf }
3972cbf2b7c4SKevin Wolf
39739b890bdcSKevin Wolf /* Create and open an external data file (protocol layer) */
39749b890bdcSKevin Wolf val = qdict_get_try_str(qdict, BLOCK_OPT_DATA_FILE);
39759b890bdcSKevin Wolf if (val) {
39762475a0d0SEmanuele Giuseppe Esposito ret = bdrv_co_create_file(val, opts, errp);
39779b890bdcSKevin Wolf if (ret < 0) {
39789b890bdcSKevin Wolf goto finish;
39799b890bdcSKevin Wolf }
39809b890bdcSKevin Wolf
3981ecbc57caSKevin Wolf data_bs = bdrv_co_open(val, NULL, NULL,
39829b890bdcSKevin Wolf BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_PROTOCOL,
39839b890bdcSKevin Wolf errp);
39849b890bdcSKevin Wolf if (data_bs == NULL) {
39859b890bdcSKevin Wolf ret = -EIO;
39869b890bdcSKevin Wolf goto finish;
39879b890bdcSKevin Wolf }
39889b890bdcSKevin Wolf
39899b890bdcSKevin Wolf qdict_del(qdict, BLOCK_OPT_DATA_FILE);
39909b890bdcSKevin Wolf qdict_put_str(qdict, "data-file", data_bs->node_name);
39919b890bdcSKevin Wolf }
39929b890bdcSKevin Wolf
3993b76b4f60SKevin Wolf /* Set 'driver' and 'node' options */
3994b76b4f60SKevin Wolf qdict_put_str(qdict, "driver", "qcow2");
3995b76b4f60SKevin Wolf qdict_put_str(qdict, "file", bs->node_name);
3996b76b4f60SKevin Wolf
3997b76b4f60SKevin Wolf /* Now get the QAPI type BlockdevCreateOptions */
3998af91062eSMarkus Armbruster v = qobject_input_visitor_new_flat_confused(qdict, errp);
3999af91062eSMarkus Armbruster if (!v) {
4000b76b4f60SKevin Wolf ret = -EINVAL;
4001b76b4f60SKevin Wolf goto finish;
4002b76b4f60SKevin Wolf }
4003b76b4f60SKevin Wolf
4004b11a093cSMarkus Armbruster visit_type_BlockdevCreateOptions(v, NULL, &create_options, errp);
4005b76b4f60SKevin Wolf visit_free(v);
4006b11a093cSMarkus Armbruster if (!create_options) {
4007b76b4f60SKevin Wolf ret = -EINVAL;
4008b76b4f60SKevin Wolf goto finish;
4009b76b4f60SKevin Wolf }
4010b76b4f60SKevin Wolf
4011b76b4f60SKevin Wolf /* Silently round up size */
4012b76b4f60SKevin Wolf create_options->u.qcow2.size = ROUND_UP(create_options->u.qcow2.size,
4013b76b4f60SKevin Wolf BDRV_SECTOR_SIZE);
4014b76b4f60SKevin Wolf
4015cbf2b7c4SKevin Wolf /* Create the qcow2 image (format layer) */
4016b76b4f60SKevin Wolf ret = qcow2_co_create(create_options, errp);
40176094cbebSMaxim Levitsky finish:
4018cbf2b7c4SKevin Wolf if (ret < 0) {
40194db7ba3bSKevin Wolf bdrv_graph_co_rdlock();
40206094cbebSMaxim Levitsky bdrv_co_delete_file_noerr(bs);
40216094cbebSMaxim Levitsky bdrv_co_delete_file_noerr(data_bs);
40224db7ba3bSKevin Wolf bdrv_graph_co_rdunlock();
40236094cbebSMaxim Levitsky } else {
40246094cbebSMaxim Levitsky ret = 0;
4025cbf2b7c4SKevin Wolf }
40261bd0e2d1SChunyan Liu
4027cb3e7f08SMarc-André Lureau qobject_unref(qdict);
4028b2ab5f54SKevin Wolf bdrv_co_unref(bs);
4029b2ab5f54SKevin Wolf bdrv_co_unref(data_bs);
4030b76b4f60SKevin Wolf qapi_free_BlockdevCreateOptions(create_options);
40313ef6c40aSMax Reitz return ret;
4032de5f3f40SKevin Wolf }
4033de5f3f40SKevin Wolf
40342928abceSDenis V. Lunev
4035cc323997SPaolo Bonzini static bool coroutine_fn GRAPH_RDLOCK
is_zero(BlockDriverState * bs,int64_t offset,int64_t bytes)4036cc323997SPaolo Bonzini is_zero(BlockDriverState *bs, int64_t offset, int64_t bytes)
40372928abceSDenis V. Lunev {
403831826642SEric Blake int64_t nr;
403931826642SEric Blake int res;
4040f06f6b66SEric Blake
4041f06f6b66SEric Blake /* Clamp to image length, before checking status of underlying sectors */
40428cbf74b2SEric Blake if (offset + bytes > bs->total_sectors * BDRV_SECTOR_SIZE) {
40438cbf74b2SEric Blake bytes = bs->total_sectors * BDRV_SECTOR_SIZE - offset;
4044fbaa6bb3SEric Blake }
4045fbaa6bb3SEric Blake
4046f06f6b66SEric Blake if (!bytes) {
4047ebb718a5SEric Blake return true;
40482928abceSDenis V. Lunev }
404967c095c8SVladimir Sementsov-Ogievskiy
405067c095c8SVladimir Sementsov-Ogievskiy /*
405167c095c8SVladimir Sementsov-Ogievskiy * bdrv_block_status_above doesn't merge different types of zeros, for
405267c095c8SVladimir Sementsov-Ogievskiy * example, zeros which come from the region which is unallocated in
405367c095c8SVladimir Sementsov-Ogievskiy * the whole backing chain, and zeros which come because of a short
405467c095c8SVladimir Sementsov-Ogievskiy * backing file. So, we need a loop.
405567c095c8SVladimir Sementsov-Ogievskiy */
405667c095c8SVladimir Sementsov-Ogievskiy do {
4057cc323997SPaolo Bonzini res = bdrv_co_block_status_above(bs, NULL, offset, bytes, &nr, NULL, NULL);
405867c095c8SVladimir Sementsov-Ogievskiy offset += nr;
405967c095c8SVladimir Sementsov-Ogievskiy bytes -= nr;
406067c095c8SVladimir Sementsov-Ogievskiy } while (res >= 0 && (res & BDRV_BLOCK_ZERO) && nr && bytes);
406167c095c8SVladimir Sementsov-Ogievskiy
406267c095c8SVladimir Sementsov-Ogievskiy return res >= 0 && (res & BDRV_BLOCK_ZERO) && bytes == 0;
40632928abceSDenis V. Lunev }
40642928abceSDenis V. Lunev
4065abaf8b75SKevin Wolf static int coroutine_fn GRAPH_RDLOCK
qcow2_co_pwrite_zeroes(BlockDriverState * bs,int64_t offset,int64_t bytes,BdrvRequestFlags flags)4066abaf8b75SKevin Wolf qcow2_co_pwrite_zeroes(BlockDriverState *bs, int64_t offset, int64_t bytes,
4067abaf8b75SKevin Wolf BdrvRequestFlags flags)
4068621f0589SKevin Wolf {
4069621f0589SKevin Wolf int ret;
4070ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque;
4071621f0589SKevin Wolf
4072a6841a2dSAlberto Garcia uint32_t head = offset_into_subcluster(s, offset);
4073a6841a2dSAlberto Garcia uint32_t tail = ROUND_UP(offset + bytes, s->subcluster_size) -
4074a6841a2dSAlberto Garcia (offset + bytes);
40752928abceSDenis V. Lunev
4076f5a5ca79SManos Pitsidianakis trace_qcow2_pwrite_zeroes_start_req(qemu_coroutine_self(), offset, bytes);
4077f5a5ca79SManos Pitsidianakis if (offset + bytes == bs->total_sectors * BDRV_SECTOR_SIZE) {
4078fbaa6bb3SEric Blake tail = 0;
4079fbaa6bb3SEric Blake }
40805a64e942SDenis V. Lunev
4081ebb718a5SEric Blake if (head || tail) {
4082ebb718a5SEric Blake uint64_t off;
4083ecfe1863SKevin Wolf unsigned int nr;
408410dabdc5SAlberto Garcia QCow2SubclusterType type;
40852928abceSDenis V. Lunev
4086a6841a2dSAlberto Garcia assert(head + bytes + tail <= s->subcluster_size);
40872928abceSDenis V. Lunev
4088ebb718a5SEric Blake /* check whether remainder of cluster already reads as zero */
4089f06f6b66SEric Blake if (!(is_zero(bs, offset - head, head) &&
4090a6841a2dSAlberto Garcia is_zero(bs, offset + bytes, tail))) {
4091621f0589SKevin Wolf return -ENOTSUP;
4092621f0589SKevin Wolf }
4093621f0589SKevin Wolf
4094621f0589SKevin Wolf qemu_co_mutex_lock(&s->lock);
40952928abceSDenis V. Lunev /* We can have new write after previous check */
4096a6841a2dSAlberto Garcia offset -= head;
4097a6841a2dSAlberto Garcia bytes = s->subcluster_size;
4098a6841a2dSAlberto Garcia nr = s->subcluster_size;
4099ca4a0bb8SAlberto Garcia ret = qcow2_get_host_offset(bs, offset, &nr, &off, &type);
4100ca4a0bb8SAlberto Garcia if (ret < 0 ||
410110dabdc5SAlberto Garcia (type != QCOW2_SUBCLUSTER_UNALLOCATED_PLAIN &&
410297490a14SAlberto Garcia type != QCOW2_SUBCLUSTER_UNALLOCATED_ALLOC &&
410310dabdc5SAlberto Garcia type != QCOW2_SUBCLUSTER_ZERO_PLAIN &&
410410dabdc5SAlberto Garcia type != QCOW2_SUBCLUSTER_ZERO_ALLOC)) {
41052928abceSDenis V. Lunev qemu_co_mutex_unlock(&s->lock);
4106580384d6SAlberto Garcia return ret < 0 ? ret : -ENOTSUP;
41072928abceSDenis V. Lunev }
41082928abceSDenis V. Lunev } else {
41092928abceSDenis V. Lunev qemu_co_mutex_lock(&s->lock);
41102928abceSDenis V. Lunev }
41112928abceSDenis V. Lunev
4112f5a5ca79SManos Pitsidianakis trace_qcow2_pwrite_zeroes(qemu_coroutine_self(), offset, bytes);
41135a64e942SDenis V. Lunev
4114a6841a2dSAlberto Garcia /* Whatever is left can use real zero subclusters */
4115a6841a2dSAlberto Garcia ret = qcow2_subcluster_zeroize(bs, offset, bytes, flags);
4116621f0589SKevin Wolf qemu_co_mutex_unlock(&s->lock);
4117621f0589SKevin Wolf
4118621f0589SKevin Wolf return ret;
4119621f0589SKevin Wolf }
4120621f0589SKevin Wolf
41210bb79c97SKevin Wolf static int coroutine_fn GRAPH_RDLOCK
qcow2_co_pdiscard(BlockDriverState * bs,int64_t offset,int64_t bytes)41220bb79c97SKevin Wolf qcow2_co_pdiscard(BlockDriverState *bs, int64_t offset, int64_t bytes)
41235ea929e3SKevin Wolf {
41246db39ae2SPaolo Bonzini int ret;
4125ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque;
41266db39ae2SPaolo Bonzini
412780f5c011SAlberto Garcia /* If the image does not support QCOW_OFLAG_ZERO then discarding
412880f5c011SAlberto Garcia * clusters could expose stale data from the backing file. */
412980f5c011SAlberto Garcia if (s->qcow_version < 3 && bs->backing) {
413080f5c011SAlberto Garcia return -ENOTSUP;
413180f5c011SAlberto Garcia }
413280f5c011SAlberto Garcia
4133f5a5ca79SManos Pitsidianakis if (!QEMU_IS_ALIGNED(offset | bytes, s->cluster_size)) {
4134f5a5ca79SManos Pitsidianakis assert(bytes < s->cluster_size);
4135048c5fd1SEric Blake /* Ignore partial clusters, except for the special case of the
4136048c5fd1SEric Blake * complete partial cluster at the end of an unaligned file */
4137048c5fd1SEric Blake if (!QEMU_IS_ALIGNED(offset, s->cluster_size) ||
4138f5a5ca79SManos Pitsidianakis offset + bytes != bs->total_sectors * BDRV_SECTOR_SIZE) {
413949228d1eSEric Blake return -ENOTSUP;
414049228d1eSEric Blake }
4141048c5fd1SEric Blake }
414249228d1eSEric Blake
41436db39ae2SPaolo Bonzini qemu_co_mutex_lock(&s->lock);
4144f5a5ca79SManos Pitsidianakis ret = qcow2_cluster_discard(bs, offset, bytes, QCOW2_DISCARD_REQUEST,
4145d2cb36afSEric Blake false);
41466db39ae2SPaolo Bonzini qemu_co_mutex_unlock(&s->lock);
41476db39ae2SPaolo Bonzini return ret;
41485ea929e3SKevin Wolf }
41495ea929e3SKevin Wolf
4150742bf09bSEmanuele Giuseppe Esposito static int coroutine_fn GRAPH_RDLOCK
qcow2_co_copy_range_from(BlockDriverState * bs,BdrvChild * src,int64_t src_offset,BdrvChild * dst,int64_t dst_offset,int64_t bytes,BdrvRequestFlags read_flags,BdrvRequestFlags write_flags)4151fd9fcd37SFam Zheng qcow2_co_copy_range_from(BlockDriverState *bs,
415248535049SVladimir Sementsov-Ogievskiy BdrvChild *src, int64_t src_offset,
415348535049SVladimir Sementsov-Ogievskiy BdrvChild *dst, int64_t dst_offset,
415448535049SVladimir Sementsov-Ogievskiy int64_t bytes, BdrvRequestFlags read_flags,
415567b51fb9SVladimir Sementsov-Ogievskiy BdrvRequestFlags write_flags)
4156fd9fcd37SFam Zheng {
4157fd9fcd37SFam Zheng BDRVQcow2State *s = bs->opaque;
4158fd9fcd37SFam Zheng int ret;
4159fd9fcd37SFam Zheng unsigned int cur_bytes; /* number of bytes in current iteration */
4160fd9fcd37SFam Zheng BdrvChild *child = NULL;
416167b51fb9SVladimir Sementsov-Ogievskiy BdrvRequestFlags cur_write_flags;
4162fd9fcd37SFam Zheng
4163fd9fcd37SFam Zheng assert(!bs->encrypted);
4164fd9fcd37SFam Zheng qemu_co_mutex_lock(&s->lock);
4165fd9fcd37SFam Zheng
4166fd9fcd37SFam Zheng while (bytes != 0) {
4167fd9fcd37SFam Zheng uint64_t copy_offset = 0;
416810dabdc5SAlberto Garcia QCow2SubclusterType type;
4169fd9fcd37SFam Zheng /* prepare next request */
4170fd9fcd37SFam Zheng cur_bytes = MIN(bytes, INT_MAX);
417167b51fb9SVladimir Sementsov-Ogievskiy cur_write_flags = write_flags;
4172fd9fcd37SFam Zheng
4173ca4a0bb8SAlberto Garcia ret = qcow2_get_host_offset(bs, src_offset, &cur_bytes,
4174ca4a0bb8SAlberto Garcia ©_offset, &type);
4175fd9fcd37SFam Zheng if (ret < 0) {
4176fd9fcd37SFam Zheng goto out;
4177fd9fcd37SFam Zheng }
4178fd9fcd37SFam Zheng
4179ca4a0bb8SAlberto Garcia switch (type) {
418010dabdc5SAlberto Garcia case QCOW2_SUBCLUSTER_UNALLOCATED_PLAIN:
418197490a14SAlberto Garcia case QCOW2_SUBCLUSTER_UNALLOCATED_ALLOC:
4182fd9fcd37SFam Zheng if (bs->backing && bs->backing->bs) {
41830050c163SKevin Wolf int64_t backing_length = bdrv_co_getlength(bs->backing->bs);
4184fd9fcd37SFam Zheng if (src_offset >= backing_length) {
418567b51fb9SVladimir Sementsov-Ogievskiy cur_write_flags |= BDRV_REQ_ZERO_WRITE;
4186fd9fcd37SFam Zheng } else {
4187fd9fcd37SFam Zheng child = bs->backing;
4188fd9fcd37SFam Zheng cur_bytes = MIN(cur_bytes, backing_length - src_offset);
4189fd9fcd37SFam Zheng copy_offset = src_offset;
4190fd9fcd37SFam Zheng }
4191fd9fcd37SFam Zheng } else {
419267b51fb9SVladimir Sementsov-Ogievskiy cur_write_flags |= BDRV_REQ_ZERO_WRITE;
4193fd9fcd37SFam Zheng }
4194fd9fcd37SFam Zheng break;
4195fd9fcd37SFam Zheng
419610dabdc5SAlberto Garcia case QCOW2_SUBCLUSTER_ZERO_PLAIN:
419710dabdc5SAlberto Garcia case QCOW2_SUBCLUSTER_ZERO_ALLOC:
419867b51fb9SVladimir Sementsov-Ogievskiy cur_write_flags |= BDRV_REQ_ZERO_WRITE;
4199fd9fcd37SFam Zheng break;
4200fd9fcd37SFam Zheng
420110dabdc5SAlberto Garcia case QCOW2_SUBCLUSTER_COMPRESSED:
4202fd9fcd37SFam Zheng ret = -ENOTSUP;
4203fd9fcd37SFam Zheng goto out;
4204fd9fcd37SFam Zheng
420510dabdc5SAlberto Garcia case QCOW2_SUBCLUSTER_NORMAL:
4206966b000fSKevin Wolf child = s->data_file;
4207fd9fcd37SFam Zheng break;
4208fd9fcd37SFam Zheng
4209fd9fcd37SFam Zheng default:
4210fd9fcd37SFam Zheng abort();
4211fd9fcd37SFam Zheng }
4212fd9fcd37SFam Zheng qemu_co_mutex_unlock(&s->lock);
4213fd9fcd37SFam Zheng ret = bdrv_co_copy_range_from(child,
4214fd9fcd37SFam Zheng copy_offset,
4215fd9fcd37SFam Zheng dst, dst_offset,
421667b51fb9SVladimir Sementsov-Ogievskiy cur_bytes, read_flags, cur_write_flags);
4217fd9fcd37SFam Zheng qemu_co_mutex_lock(&s->lock);
4218fd9fcd37SFam Zheng if (ret < 0) {
4219fd9fcd37SFam Zheng goto out;
4220fd9fcd37SFam Zheng }
4221fd9fcd37SFam Zheng
4222fd9fcd37SFam Zheng bytes -= cur_bytes;
4223fd9fcd37SFam Zheng src_offset += cur_bytes;
4224fd9fcd37SFam Zheng dst_offset += cur_bytes;
4225fd9fcd37SFam Zheng }
4226fd9fcd37SFam Zheng ret = 0;
4227fd9fcd37SFam Zheng
4228fd9fcd37SFam Zheng out:
4229fd9fcd37SFam Zheng qemu_co_mutex_unlock(&s->lock);
4230fd9fcd37SFam Zheng return ret;
4231fd9fcd37SFam Zheng }
4232fd9fcd37SFam Zheng
4233742bf09bSEmanuele Giuseppe Esposito static int coroutine_fn GRAPH_RDLOCK
qcow2_co_copy_range_to(BlockDriverState * bs,BdrvChild * src,int64_t src_offset,BdrvChild * dst,int64_t dst_offset,int64_t bytes,BdrvRequestFlags read_flags,BdrvRequestFlags write_flags)4234fd9fcd37SFam Zheng qcow2_co_copy_range_to(BlockDriverState *bs,
423548535049SVladimir Sementsov-Ogievskiy BdrvChild *src, int64_t src_offset,
423648535049SVladimir Sementsov-Ogievskiy BdrvChild *dst, int64_t dst_offset,
423748535049SVladimir Sementsov-Ogievskiy int64_t bytes, BdrvRequestFlags read_flags,
423867b51fb9SVladimir Sementsov-Ogievskiy BdrvRequestFlags write_flags)
4239fd9fcd37SFam Zheng {
4240fd9fcd37SFam Zheng BDRVQcow2State *s = bs->opaque;
4241fd9fcd37SFam Zheng int ret;
4242fd9fcd37SFam Zheng unsigned int cur_bytes; /* number of sectors in current iteration */
4243bfd0989aSAlberto Garcia uint64_t host_offset;
4244fd9fcd37SFam Zheng QCowL2Meta *l2meta = NULL;
4245fd9fcd37SFam Zheng
4246fd9fcd37SFam Zheng assert(!bs->encrypted);
4247fd9fcd37SFam Zheng
4248fd9fcd37SFam Zheng qemu_co_mutex_lock(&s->lock);
4249fd9fcd37SFam Zheng
4250fd9fcd37SFam Zheng while (bytes != 0) {
4251fd9fcd37SFam Zheng
4252fd9fcd37SFam Zheng l2meta = NULL;
4253fd9fcd37SFam Zheng
4254fd9fcd37SFam Zheng cur_bytes = MIN(bytes, INT_MAX);
4255fd9fcd37SFam Zheng
4256fd9fcd37SFam Zheng /* TODO:
4257fd9fcd37SFam Zheng * If src->bs == dst->bs, we could simply copy by incrementing
4258fd9fcd37SFam Zheng * the refcnt, without copying user data.
4259fd9fcd37SFam Zheng * Or if src->bs == dst->bs->backing->bs, we could copy by discarding. */
4260bfd0989aSAlberto Garcia ret = qcow2_alloc_host_offset(bs, dst_offset, &cur_bytes,
4261bfd0989aSAlberto Garcia &host_offset, &l2meta);
4262fd9fcd37SFam Zheng if (ret < 0) {
4263fd9fcd37SFam Zheng goto fail;
4264fd9fcd37SFam Zheng }
4265fd9fcd37SFam Zheng
4266bfd0989aSAlberto Garcia ret = qcow2_pre_write_overlap_check(bs, 0, host_offset, cur_bytes,
4267bfd0989aSAlberto Garcia true);
4268fd9fcd37SFam Zheng if (ret < 0) {
4269fd9fcd37SFam Zheng goto fail;
4270fd9fcd37SFam Zheng }
4271fd9fcd37SFam Zheng
4272fd9fcd37SFam Zheng qemu_co_mutex_unlock(&s->lock);
4273bfd0989aSAlberto Garcia ret = bdrv_co_copy_range_to(src, src_offset, s->data_file, host_offset,
427467b51fb9SVladimir Sementsov-Ogievskiy cur_bytes, read_flags, write_flags);
4275fd9fcd37SFam Zheng qemu_co_mutex_lock(&s->lock);
4276fd9fcd37SFam Zheng if (ret < 0) {
4277fd9fcd37SFam Zheng goto fail;
4278fd9fcd37SFam Zheng }
4279fd9fcd37SFam Zheng
4280fd9fcd37SFam Zheng ret = qcow2_handle_l2meta(bs, &l2meta, true);
4281fd9fcd37SFam Zheng if (ret) {
4282fd9fcd37SFam Zheng goto fail;
4283fd9fcd37SFam Zheng }
4284fd9fcd37SFam Zheng
4285fd9fcd37SFam Zheng bytes -= cur_bytes;
4286e06f4639SFam Zheng src_offset += cur_bytes;
4287fd9fcd37SFam Zheng dst_offset += cur_bytes;
4288fd9fcd37SFam Zheng }
4289fd9fcd37SFam Zheng ret = 0;
4290fd9fcd37SFam Zheng
4291fd9fcd37SFam Zheng fail:
4292fd9fcd37SFam Zheng qcow2_handle_l2meta(bs, &l2meta, false);
4293fd9fcd37SFam Zheng
4294fd9fcd37SFam Zheng qemu_co_mutex_unlock(&s->lock);
4295fd9fcd37SFam Zheng
4296fd9fcd37SFam Zheng trace_qcow2_writev_done_req(qemu_coroutine_self(), ret);
4297fd9fcd37SFam Zheng
4298fd9fcd37SFam Zheng return ret;
4299fd9fcd37SFam Zheng }
4300fd9fcd37SFam Zheng
4301c2b8e315SKevin Wolf static int coroutine_fn GRAPH_RDLOCK
qcow2_co_truncate(BlockDriverState * bs,int64_t offset,bool exact,PreallocMode prealloc,BdrvRequestFlags flags,Error ** errp)4302c2b8e315SKevin Wolf qcow2_co_truncate(BlockDriverState *bs, int64_t offset, bool exact,
4303c2b8e315SKevin Wolf PreallocMode prealloc, BdrvRequestFlags flags, Error **errp)
4304419b19d9SStefan Hajnoczi {
4305d13e3b46SZhao Liu ERRP_GUARD();
4306ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque;
430795b98f34SMax Reitz uint64_t old_length;
43082cf7cfa1SKevin Wolf int64_t new_l1_size;
43092cf7cfa1SKevin Wolf int ret;
431045b4949cSLeonid Bloch QDict *options;
4311419b19d9SStefan Hajnoczi
4312772d1f97SMax Reitz if (prealloc != PREALLOC_MODE_OFF && prealloc != PREALLOC_MODE_METADATA &&
4313772d1f97SMax Reitz prealloc != PREALLOC_MODE_FALLOC && prealloc != PREALLOC_MODE_FULL)
4314772d1f97SMax Reitz {
43158243ccb7SMax Reitz error_setg(errp, "Unsupported preallocation mode '%s'",
4316977c736fSMarkus Armbruster PreallocMode_str(prealloc));
43178243ccb7SMax Reitz return -ENOTSUP;
43188243ccb7SMax Reitz }
43198243ccb7SMax Reitz
43203afea402SAlberto Garcia if (!QEMU_IS_ALIGNED(offset, BDRV_SECTOR_SIZE)) {
43213afea402SAlberto Garcia error_setg(errp, "The new size must be a multiple of %u",
43223afea402SAlberto Garcia (unsigned) BDRV_SECTOR_SIZE);
4323419b19d9SStefan Hajnoczi return -EINVAL;
4324419b19d9SStefan Hajnoczi }
4325419b19d9SStefan Hajnoczi
4326061ca8a3SKevin Wolf qemu_co_mutex_lock(&s->lock);
4327061ca8a3SKevin Wolf
43287fa140abSEric Blake /*
43297fa140abSEric Blake * Even though we store snapshot size for all images, it was not
43307fa140abSEric Blake * required until v3, so it is not safe to proceed for v2.
43317fa140abSEric Blake */
43327fa140abSEric Blake if (s->nb_snapshots && s->qcow_version < 3) {
43337fa140abSEric Blake error_setg(errp, "Can't resize a v2 image which has snapshots");
4334061ca8a3SKevin Wolf ret = -ENOTSUP;
4335061ca8a3SKevin Wolf goto fail;
4336419b19d9SStefan Hajnoczi }
4337419b19d9SStefan Hajnoczi
4338ee1244a2SEric Blake /* See qcow2-bitmap.c for which bitmap scenarios prevent a resize. */
4339d19c6b36SJohn Snow if (qcow2_truncate_bitmaps_check(bs, errp)) {
4340061ca8a3SKevin Wolf ret = -ENOTSUP;
4341061ca8a3SKevin Wolf goto fail;
434288ddffaeSVladimir Sementsov-Ogievskiy }
434388ddffaeSVladimir Sementsov-Ogievskiy
4344bd016b91SLeonid Bloch old_length = bs->total_sectors * BDRV_SECTOR_SIZE;
434546b732cdSPavel Butsykin new_l1_size = size_to_l1(s, offset);
434695b98f34SMax Reitz
434795b98f34SMax Reitz if (offset < old_length) {
4348163bc39dSPavel Butsykin int64_t last_cluster, old_file_size;
434946b732cdSPavel Butsykin if (prealloc != PREALLOC_MODE_OFF) {
435046b732cdSPavel Butsykin error_setg(errp,
435146b732cdSPavel Butsykin "Preallocation can't be used for shrinking an image");
4352061ca8a3SKevin Wolf ret = -EINVAL;
4353061ca8a3SKevin Wolf goto fail;
4354419b19d9SStefan Hajnoczi }
4355419b19d9SStefan Hajnoczi
435646b732cdSPavel Butsykin ret = qcow2_cluster_discard(bs, ROUND_UP(offset, s->cluster_size),
435746b732cdSPavel Butsykin old_length - ROUND_UP(offset,
435846b732cdSPavel Butsykin s->cluster_size),
435946b732cdSPavel Butsykin QCOW2_DISCARD_ALWAYS, true);
436046b732cdSPavel Butsykin if (ret < 0) {
436146b732cdSPavel Butsykin error_setg_errno(errp, -ret, "Failed to discard cropped clusters");
4362061ca8a3SKevin Wolf goto fail;
436346b732cdSPavel Butsykin }
436446b732cdSPavel Butsykin
436546b732cdSPavel Butsykin ret = qcow2_shrink_l1_table(bs, new_l1_size);
436646b732cdSPavel Butsykin if (ret < 0) {
436746b732cdSPavel Butsykin error_setg_errno(errp, -ret,
436846b732cdSPavel Butsykin "Failed to reduce the number of L2 tables");
4369061ca8a3SKevin Wolf goto fail;
437046b732cdSPavel Butsykin }
437146b732cdSPavel Butsykin
437246b732cdSPavel Butsykin ret = qcow2_shrink_reftable(bs);
437346b732cdSPavel Butsykin if (ret < 0) {
437446b732cdSPavel Butsykin error_setg_errno(errp, -ret,
437546b732cdSPavel Butsykin "Failed to discard unused refblocks");
4376061ca8a3SKevin Wolf goto fail;
437746b732cdSPavel Butsykin }
4378163bc39dSPavel Butsykin
43790050c163SKevin Wolf old_file_size = bdrv_co_getlength(bs->file->bs);
4380163bc39dSPavel Butsykin if (old_file_size < 0) {
4381163bc39dSPavel Butsykin error_setg_errno(errp, -old_file_size,
4382163bc39dSPavel Butsykin "Failed to inquire current file length");
4383061ca8a3SKevin Wolf ret = old_file_size;
4384061ca8a3SKevin Wolf goto fail;
4385163bc39dSPavel Butsykin }
4386163bc39dSPavel Butsykin last_cluster = qcow2_get_last_cluster(bs, old_file_size);
4387163bc39dSPavel Butsykin if (last_cluster < 0) {
4388163bc39dSPavel Butsykin error_setg_errno(errp, -last_cluster,
4389163bc39dSPavel Butsykin "Failed to find the last cluster");
4390061ca8a3SKevin Wolf ret = last_cluster;
4391061ca8a3SKevin Wolf goto fail;
4392163bc39dSPavel Butsykin }
4393163bc39dSPavel Butsykin if ((last_cluster + 1) * s->cluster_size < old_file_size) {
4394233521b1SMax Reitz Error *local_err = NULL;
4395233521b1SMax Reitz
4396e61a28a9SMax Reitz /*
4397e61a28a9SMax Reitz * Do not pass @exact here: It will not help the user if
4398e61a28a9SMax Reitz * we get an error here just because they wanted to shrink
4399e61a28a9SMax Reitz * their qcow2 image (on a block device) with qemu-img.
4400e61a28a9SMax Reitz * (And on the qcow2 layer, the @exact requirement is
4401e61a28a9SMax Reitz * always fulfilled, so there is no need to pass it on.)
4402e61a28a9SMax Reitz */
4403061ca8a3SKevin Wolf bdrv_co_truncate(bs->file, (last_cluster + 1) * s->cluster_size,
44047b8e4857SKevin Wolf false, PREALLOC_MODE_OFF, 0, &local_err);
4405233521b1SMax Reitz if (local_err) {
4406233521b1SMax Reitz warn_reportf_err(local_err,
4407233521b1SMax Reitz "Failed to truncate the tail of the image: ");
4408163bc39dSPavel Butsykin }
4409163bc39dSPavel Butsykin }
441046b732cdSPavel Butsykin } else {
441172893756SStefan Hajnoczi ret = qcow2_grow_l1_table(bs, new_l1_size, true);
4412419b19d9SStefan Hajnoczi if (ret < 0) {
4413f59adb32SMax Reitz error_setg_errno(errp, -ret, "Failed to grow the L1 table");
4414061ca8a3SKevin Wolf goto fail;
4415419b19d9SStefan Hajnoczi }
441648410829SMax Reitz
441748410829SMax Reitz if (data_file_is_raw(bs) && prealloc == PREALLOC_MODE_OFF) {
441848410829SMax Reitz /*
441948410829SMax Reitz * When creating a qcow2 image with data-file-raw, we enforce
442048410829SMax Reitz * at least prealloc=metadata, so that the L1/L2 tables are
442148410829SMax Reitz * fully allocated and reading from the data file will return
442248410829SMax Reitz * the same data as reading from the qcow2 image. When the
442348410829SMax Reitz * image is grown, we must consequently preallocate the
442448410829SMax Reitz * metadata structures to cover the added area.
442548410829SMax Reitz */
442648410829SMax Reitz prealloc = PREALLOC_MODE_METADATA;
442748410829SMax Reitz }
442846b732cdSPavel Butsykin }
4429419b19d9SStefan Hajnoczi
443095b98f34SMax Reitz switch (prealloc) {
443195b98f34SMax Reitz case PREALLOC_MODE_OFF:
4432718c0fceSKevin Wolf if (has_data_file(bs)) {
4433e61a28a9SMax Reitz /*
4434e61a28a9SMax Reitz * If the caller wants an exact resize, the external data
4435e61a28a9SMax Reitz * file should be resized to the exact target size, too,
4436e61a28a9SMax Reitz * so we pass @exact here.
4437e61a28a9SMax Reitz */
44387b8e4857SKevin Wolf ret = bdrv_co_truncate(s->data_file, offset, exact, prealloc, 0,
44397b8e4857SKevin Wolf errp);
4440718c0fceSKevin Wolf if (ret < 0) {
4441718c0fceSKevin Wolf goto fail;
4442718c0fceSKevin Wolf }
4443718c0fceSKevin Wolf }
444495b98f34SMax Reitz break;
444595b98f34SMax Reitz
444695b98f34SMax Reitz case PREALLOC_MODE_METADATA:
4447718c0fceSKevin Wolf ret = preallocate_co(bs, old_length, offset, prealloc, errp);
444895b98f34SMax Reitz if (ret < 0) {
4449061ca8a3SKevin Wolf goto fail;
445095b98f34SMax Reitz }
445195b98f34SMax Reitz break;
445295b98f34SMax Reitz
4453772d1f97SMax Reitz case PREALLOC_MODE_FALLOC:
4454772d1f97SMax Reitz case PREALLOC_MODE_FULL:
4455772d1f97SMax Reitz {
4456772d1f97SMax Reitz int64_t allocation_start, host_offset, guest_offset;
4457772d1f97SMax Reitz int64_t clusters_allocated;
44584b96fa38SMax Reitz int64_t old_file_size, last_cluster, new_file_size;
4459772d1f97SMax Reitz uint64_t nb_new_data_clusters, nb_new_l2_tables;
446040dee943SAlberto Garcia bool subclusters_need_allocation = false;
4461772d1f97SMax Reitz
4462966b000fSKevin Wolf /* With a data file, preallocation means just allocating the metadata
4463966b000fSKevin Wolf * and forwarding the truncate request to the data file */
4464966b000fSKevin Wolf if (has_data_file(bs)) {
4465718c0fceSKevin Wolf ret = preallocate_co(bs, old_length, offset, prealloc, errp);
4466966b000fSKevin Wolf if (ret < 0) {
4467966b000fSKevin Wolf goto fail;
4468966b000fSKevin Wolf }
4469966b000fSKevin Wolf break;
4470966b000fSKevin Wolf }
4471966b000fSKevin Wolf
44720050c163SKevin Wolf old_file_size = bdrv_co_getlength(bs->file->bs);
4473772d1f97SMax Reitz if (old_file_size < 0) {
4474772d1f97SMax Reitz error_setg_errno(errp, -old_file_size,
4475772d1f97SMax Reitz "Failed to inquire current file length");
4476061ca8a3SKevin Wolf ret = old_file_size;
4477061ca8a3SKevin Wolf goto fail;
4478772d1f97SMax Reitz }
44794b96fa38SMax Reitz
44804b96fa38SMax Reitz last_cluster = qcow2_get_last_cluster(bs, old_file_size);
44814b96fa38SMax Reitz if (last_cluster >= 0) {
44824b96fa38SMax Reitz old_file_size = (last_cluster + 1) * s->cluster_size;
44834b96fa38SMax Reitz } else {
4484e400ad1eSMax Reitz old_file_size = ROUND_UP(old_file_size, s->cluster_size);
44854b96fa38SMax Reitz }
4486772d1f97SMax Reitz
4487a5675f39SAlberto Garcia nb_new_data_clusters = (ROUND_UP(offset, s->cluster_size) -
4488a5675f39SAlberto Garcia start_of_cluster(s, old_length)) >> s->cluster_bits;
4489772d1f97SMax Reitz
4490772d1f97SMax Reitz /* This is an overestimation; we will not actually allocate space for
4491772d1f97SMax Reitz * these in the file but just make sure the new refcount structures are
4492772d1f97SMax Reitz * able to cover them so we will not have to allocate new refblocks
4493772d1f97SMax Reitz * while entering the data blocks in the potentially new L2 tables.
4494772d1f97SMax Reitz * (We do not actually care where the L2 tables are placed. Maybe they
4495772d1f97SMax Reitz * are already allocated or they can be placed somewhere before
4496772d1f97SMax Reitz * @old_file_size. It does not matter because they will be fully
4497772d1f97SMax Reitz * allocated automatically, so they do not need to be covered by the
4498772d1f97SMax Reitz * preallocation. All that matters is that we will not have to allocate
4499772d1f97SMax Reitz * new refcount structures for them.) */
4500772d1f97SMax Reitz nb_new_l2_tables = DIV_ROUND_UP(nb_new_data_clusters,
4501c8fd8554SAlberto Garcia s->cluster_size / l2_entry_size(s));
4502772d1f97SMax Reitz /* The cluster range may not be aligned to L2 boundaries, so add one L2
4503772d1f97SMax Reitz * table for a potential head/tail */
4504772d1f97SMax Reitz nb_new_l2_tables++;
4505772d1f97SMax Reitz
4506772d1f97SMax Reitz allocation_start = qcow2_refcount_area(bs, old_file_size,
4507772d1f97SMax Reitz nb_new_data_clusters +
4508772d1f97SMax Reitz nb_new_l2_tables,
4509772d1f97SMax Reitz true, 0, 0);
4510772d1f97SMax Reitz if (allocation_start < 0) {
4511772d1f97SMax Reitz error_setg_errno(errp, -allocation_start,
4512772d1f97SMax Reitz "Failed to resize refcount structures");
4513061ca8a3SKevin Wolf ret = allocation_start;
4514061ca8a3SKevin Wolf goto fail;
4515772d1f97SMax Reitz }
4516772d1f97SMax Reitz
4517772d1f97SMax Reitz clusters_allocated = qcow2_alloc_clusters_at(bs, allocation_start,
4518772d1f97SMax Reitz nb_new_data_clusters);
4519772d1f97SMax Reitz if (clusters_allocated < 0) {
4520772d1f97SMax Reitz error_setg_errno(errp, -clusters_allocated,
4521772d1f97SMax Reitz "Failed to allocate data clusters");
4522061ca8a3SKevin Wolf ret = clusters_allocated;
4523061ca8a3SKevin Wolf goto fail;
4524772d1f97SMax Reitz }
4525772d1f97SMax Reitz
4526772d1f97SMax Reitz assert(clusters_allocated == nb_new_data_clusters);
4527772d1f97SMax Reitz
4528772d1f97SMax Reitz /* Allocate the data area */
4529772d1f97SMax Reitz new_file_size = allocation_start +
4530772d1f97SMax Reitz nb_new_data_clusters * s->cluster_size;
4531eb8a0cf3SKevin Wolf /*
4532eb8a0cf3SKevin Wolf * Image file grows, so @exact does not matter.
4533eb8a0cf3SKevin Wolf *
4534eb8a0cf3SKevin Wolf * If we need to zero out the new area, try first whether the protocol
4535eb8a0cf3SKevin Wolf * driver can already take care of this.
4536eb8a0cf3SKevin Wolf */
4537eb8a0cf3SKevin Wolf if (flags & BDRV_REQ_ZERO_WRITE) {
4538eb8a0cf3SKevin Wolf ret = bdrv_co_truncate(bs->file, new_file_size, false, prealloc,
4539eb8a0cf3SKevin Wolf BDRV_REQ_ZERO_WRITE, NULL);
4540eb8a0cf3SKevin Wolf if (ret >= 0) {
4541eb8a0cf3SKevin Wolf flags &= ~BDRV_REQ_ZERO_WRITE;
454240dee943SAlberto Garcia /* Ensure that we read zeroes and not backing file data */
454340dee943SAlberto Garcia subclusters_need_allocation = true;
4544eb8a0cf3SKevin Wolf }
4545eb8a0cf3SKevin Wolf } else {
4546eb8a0cf3SKevin Wolf ret = -1;
4547eb8a0cf3SKevin Wolf }
4548eb8a0cf3SKevin Wolf if (ret < 0) {
45497b8e4857SKevin Wolf ret = bdrv_co_truncate(bs->file, new_file_size, false, prealloc, 0,
45507b8e4857SKevin Wolf errp);
4551eb8a0cf3SKevin Wolf }
4552772d1f97SMax Reitz if (ret < 0) {
4553772d1f97SMax Reitz error_prepend(errp, "Failed to resize underlying file: ");
4554772d1f97SMax Reitz qcow2_free_clusters(bs, allocation_start,
4555772d1f97SMax Reitz nb_new_data_clusters * s->cluster_size,
4556772d1f97SMax Reitz QCOW2_DISCARD_OTHER);
4557061ca8a3SKevin Wolf goto fail;
4558772d1f97SMax Reitz }
4559772d1f97SMax Reitz
4560772d1f97SMax Reitz /* Create the necessary L2 entries */
4561772d1f97SMax Reitz host_offset = allocation_start;
4562772d1f97SMax Reitz guest_offset = old_length;
4563772d1f97SMax Reitz while (nb_new_data_clusters) {
456413bec229SAlberto Garcia int64_t nb_clusters = MIN(
456513bec229SAlberto Garcia nb_new_data_clusters,
456613bec229SAlberto Garcia s->l2_slice_size - offset_to_l2_slice_index(s, guest_offset));
4567a5675f39SAlberto Garcia unsigned cow_start_length = offset_into_cluster(s, guest_offset);
4568a5675f39SAlberto Garcia QCowL2Meta allocation;
4569a5675f39SAlberto Garcia guest_offset = start_of_cluster(s, guest_offset);
4570a5675f39SAlberto Garcia allocation = (QCowL2Meta) {
4571772d1f97SMax Reitz .offset = guest_offset,
4572772d1f97SMax Reitz .alloc_offset = host_offset,
4573772d1f97SMax Reitz .nb_clusters = nb_clusters,
4574a5675f39SAlberto Garcia .cow_start = {
4575a5675f39SAlberto Garcia .offset = 0,
4576a5675f39SAlberto Garcia .nb_bytes = cow_start_length,
4577a5675f39SAlberto Garcia },
4578a5675f39SAlberto Garcia .cow_end = {
4579a5675f39SAlberto Garcia .offset = nb_clusters << s->cluster_bits,
4580a5675f39SAlberto Garcia .nb_bytes = 0,
4581a5675f39SAlberto Garcia },
458240dee943SAlberto Garcia .prealloc = !subclusters_need_allocation,
4583772d1f97SMax Reitz };
4584772d1f97SMax Reitz qemu_co_queue_init(&allocation.dependent_requests);
4585772d1f97SMax Reitz
4586772d1f97SMax Reitz ret = qcow2_alloc_cluster_link_l2(bs, &allocation);
4587772d1f97SMax Reitz if (ret < 0) {
4588772d1f97SMax Reitz error_setg_errno(errp, -ret, "Failed to update L2 tables");
4589772d1f97SMax Reitz qcow2_free_clusters(bs, host_offset,
4590772d1f97SMax Reitz nb_new_data_clusters * s->cluster_size,
4591772d1f97SMax Reitz QCOW2_DISCARD_OTHER);
4592061ca8a3SKevin Wolf goto fail;
4593772d1f97SMax Reitz }
4594772d1f97SMax Reitz
4595772d1f97SMax Reitz guest_offset += nb_clusters * s->cluster_size;
4596772d1f97SMax Reitz host_offset += nb_clusters * s->cluster_size;
4597772d1f97SMax Reitz nb_new_data_clusters -= nb_clusters;
4598772d1f97SMax Reitz }
4599772d1f97SMax Reitz break;
4600772d1f97SMax Reitz }
4601772d1f97SMax Reitz
460295b98f34SMax Reitz default:
460395b98f34SMax Reitz g_assert_not_reached();
460495b98f34SMax Reitz }
460595b98f34SMax Reitz
4606f01643fbSKevin Wolf if ((flags & BDRV_REQ_ZERO_WRITE) && offset > old_length) {
4607a6841a2dSAlberto Garcia uint64_t zero_start = QEMU_ALIGN_UP(old_length, s->subcluster_size);
4608f01643fbSKevin Wolf
4609f01643fbSKevin Wolf /*
4610a6841a2dSAlberto Garcia * Use zero clusters as much as we can. qcow2_subcluster_zeroize()
4611a6841a2dSAlberto Garcia * requires a subcluster-aligned start. The end may be unaligned if
4612a6841a2dSAlberto Garcia * it is at the end of the image (which it is here).
4613f01643fbSKevin Wolf */
4614e4d7019eSAlberto Garcia if (offset > zero_start) {
4615a6841a2dSAlberto Garcia ret = qcow2_subcluster_zeroize(bs, zero_start, offset - zero_start,
4616a6841a2dSAlberto Garcia 0);
4617f01643fbSKevin Wolf if (ret < 0) {
4618f01643fbSKevin Wolf error_setg_errno(errp, -ret, "Failed to zero out new clusters");
4619f01643fbSKevin Wolf goto fail;
4620f01643fbSKevin Wolf }
4621e4d7019eSAlberto Garcia }
4622f01643fbSKevin Wolf
4623f01643fbSKevin Wolf /* Write explicit zeros for the unaligned head */
4624f01643fbSKevin Wolf if (zero_start > old_length) {
4625e4d7019eSAlberto Garcia uint64_t len = MIN(zero_start, offset) - old_length;
4626f01643fbSKevin Wolf uint8_t *buf = qemu_blockalign0(bs, len);
4627f01643fbSKevin Wolf QEMUIOVector qiov;
4628f01643fbSKevin Wolf qemu_iovec_init_buf(&qiov, buf, len);
4629f01643fbSKevin Wolf
4630f01643fbSKevin Wolf qemu_co_mutex_unlock(&s->lock);
4631f01643fbSKevin Wolf ret = qcow2_co_pwritev_part(bs, old_length, len, &qiov, 0, 0);
4632f01643fbSKevin Wolf qemu_co_mutex_lock(&s->lock);
4633f01643fbSKevin Wolf
4634f01643fbSKevin Wolf qemu_vfree(buf);
4635f01643fbSKevin Wolf if (ret < 0) {
4636f01643fbSKevin Wolf error_setg_errno(errp, -ret, "Failed to zero out the new area");
4637f01643fbSKevin Wolf goto fail;
4638f01643fbSKevin Wolf }
4639f01643fbSKevin Wolf }
4640f01643fbSKevin Wolf }
4641f01643fbSKevin Wolf
464295b98f34SMax Reitz if (prealloc != PREALLOC_MODE_OFF) {
464395b98f34SMax Reitz /* Flush metadata before actually changing the image size */
4644061ca8a3SKevin Wolf ret = qcow2_write_caches(bs);
464595b98f34SMax Reitz if (ret < 0) {
464695b98f34SMax Reitz error_setg_errno(errp, -ret,
464795b98f34SMax Reitz "Failed to flush the preallocated area to disk");
4648061ca8a3SKevin Wolf goto fail;
464995b98f34SMax Reitz }
465095b98f34SMax Reitz }
465195b98f34SMax Reitz
465245b4949cSLeonid Bloch bs->total_sectors = offset / BDRV_SECTOR_SIZE;
465345b4949cSLeonid Bloch
4654419b19d9SStefan Hajnoczi /* write updated header.size */
4655419b19d9SStefan Hajnoczi offset = cpu_to_be64(offset);
4656a8f0e83cSAlberto Faria ret = bdrv_co_pwrite_sync(bs->file, offsetof(QCowHeader, size),
465732cc71deSAlberto Faria sizeof(offset), &offset, 0);
4658419b19d9SStefan Hajnoczi if (ret < 0) {
4659f59adb32SMax Reitz error_setg_errno(errp, -ret, "Failed to update the image size");
4660061ca8a3SKevin Wolf goto fail;
4661419b19d9SStefan Hajnoczi }
4662419b19d9SStefan Hajnoczi
4663419b19d9SStefan Hajnoczi s->l1_vm_state_index = new_l1_size;
466445b4949cSLeonid Bloch
466545b4949cSLeonid Bloch /* Update cache sizes */
466645b4949cSLeonid Bloch options = qdict_clone_shallow(bs->options);
466745b4949cSLeonid Bloch ret = qcow2_update_options(bs, options, s->flags, errp);
466845b4949cSLeonid Bloch qobject_unref(options);
466945b4949cSLeonid Bloch if (ret < 0) {
467045b4949cSLeonid Bloch goto fail;
467145b4949cSLeonid Bloch }
4672061ca8a3SKevin Wolf ret = 0;
4673061ca8a3SKevin Wolf fail:
4674061ca8a3SKevin Wolf qemu_co_mutex_unlock(&s->lock);
4675061ca8a3SKevin Wolf return ret;
4676419b19d9SStefan Hajnoczi }
4677419b19d9SStefan Hajnoczi
46787b1fb72eSKevin Wolf static int coroutine_fn GRAPH_RDLOCK
qcow2_co_pwritev_compressed_task(BlockDriverState * bs,uint64_t offset,uint64_t bytes,QEMUIOVector * qiov,size_t qiov_offset)46790d483dceSAndrey Shinkevich qcow2_co_pwritev_compressed_task(BlockDriverState *bs,
46805396234bSVladimir Sementsov-Ogievskiy uint64_t offset, uint64_t bytes,
46815396234bSVladimir Sementsov-Ogievskiy QEMUIOVector *qiov, size_t qiov_offset)
468220d97356SBlue Swirl {
4683ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque;
46842714f13dSVladimir Sementsov-Ogievskiy int ret;
4685e1f4a37aSAlberto Garcia ssize_t out_len;
4686fcccefc5SPavel Butsykin uint8_t *buf, *out_buf;
468777e023ffSKevin Wolf uint64_t cluster_offset;
468820d97356SBlue Swirl
46890d483dceSAndrey Shinkevich assert(bytes == s->cluster_size || (bytes < s->cluster_size &&
46900d483dceSAndrey Shinkevich (offset + bytes == bs->total_sectors << BDRV_SECTOR_BITS)));
46913e3b838fSAnton Nefedov
4692fcccefc5SPavel Butsykin buf = qemu_blockalign(bs, s->cluster_size);
46930d483dceSAndrey Shinkevich if (bytes < s->cluster_size) {
4694a2c0ca6fSPavel Butsykin /* Zero-pad last write if image size is not cluster aligned */
4695a2c0ca6fSPavel Butsykin memset(buf + bytes, 0, s->cluster_size - bytes);
4696a2c0ca6fSPavel Butsykin }
46975396234bSVladimir Sementsov-Ogievskiy qemu_iovec_to_buf(qiov, qiov_offset, buf, bytes);
469820d97356SBlue Swirl
4699ebf7bba0SVladimir Sementsov-Ogievskiy out_buf = g_malloc(s->cluster_size);
470020d97356SBlue Swirl
47016994fd78SVladimir Sementsov-Ogievskiy out_len = qcow2_co_compress(bs, out_buf, s->cluster_size - 1,
47026994fd78SVladimir Sementsov-Ogievskiy buf, s->cluster_size);
4703e1f4a37aSAlberto Garcia if (out_len == -ENOMEM) {
470420d97356SBlue Swirl /* could not compress: write normal cluster */
47055396234bSVladimir Sementsov-Ogievskiy ret = qcow2_co_pwritev_part(bs, offset, bytes, qiov, qiov_offset, 0);
47068f1efd00SKevin Wolf if (ret < 0) {
47078f1efd00SKevin Wolf goto fail;
47088f1efd00SKevin Wolf }
4709fcccefc5SPavel Butsykin goto success;
4710e1f4a37aSAlberto Garcia } else if (out_len < 0) {
4711e1f4a37aSAlberto Garcia ret = -EINVAL;
4712e1f4a37aSAlberto Garcia goto fail;
4713fcccefc5SPavel Butsykin }
4714fcccefc5SPavel Butsykin
4715fcccefc5SPavel Butsykin qemu_co_mutex_lock(&s->lock);
471677e023ffSKevin Wolf ret = qcow2_alloc_compressed_cluster_offset(bs, offset, out_len,
471777e023ffSKevin Wolf &cluster_offset);
471877e023ffSKevin Wolf if (ret < 0) {
4719fcccefc5SPavel Butsykin qemu_co_mutex_unlock(&s->lock);
47208f1efd00SKevin Wolf goto fail;
47218f1efd00SKevin Wolf }
4722cf93980eSMax Reitz
4723966b000fSKevin Wolf ret = qcow2_pre_write_overlap_check(bs, 0, cluster_offset, out_len, true);
4724fcccefc5SPavel Butsykin qemu_co_mutex_unlock(&s->lock);
4725cf93980eSMax Reitz if (ret < 0) {
4726cf93980eSMax Reitz goto fail;
4727cf93980eSMax Reitz }
4728cf93980eSMax Reitz
472917362398SPaolo Bonzini BLKDBG_CO_EVENT(s->data_file, BLKDBG_WRITE_COMPRESSED);
4730b00cb15bSVladimir Sementsov-Ogievskiy ret = bdrv_co_pwrite(s->data_file, cluster_offset, out_len, out_buf, 0);
47318f1efd00SKevin Wolf if (ret < 0) {
47328f1efd00SKevin Wolf goto fail;
473320d97356SBlue Swirl }
4734fcccefc5SPavel Butsykin success:
47358f1efd00SKevin Wolf ret = 0;
47368f1efd00SKevin Wolf fail:
4737fcccefc5SPavel Butsykin qemu_vfree(buf);
47387267c094SAnthony Liguori g_free(out_buf);
47398f1efd00SKevin Wolf return ret;
474020d97356SBlue Swirl }
474120d97356SBlue Swirl
47427b1fb72eSKevin Wolf /*
47437b1fb72eSKevin Wolf * This function can count as GRAPH_RDLOCK because
47447b1fb72eSKevin Wolf * qcow2_co_pwritev_compressed_part() holds the graph lock and keeps it until
47457b1fb72eSKevin Wolf * this coroutine has terminated.
47467b1fb72eSKevin Wolf */
47477b1fb72eSKevin Wolf static int coroutine_fn GRAPH_RDLOCK
qcow2_co_pwritev_compressed_task_entry(AioTask * task)47487b1fb72eSKevin Wolf qcow2_co_pwritev_compressed_task_entry(AioTask *task)
47490d483dceSAndrey Shinkevich {
47500d483dceSAndrey Shinkevich Qcow2AioTask *t = container_of(task, Qcow2AioTask, task);
47510d483dceSAndrey Shinkevich
475210dabdc5SAlberto Garcia assert(!t->subcluster_type && !t->l2meta);
47530d483dceSAndrey Shinkevich
47540d483dceSAndrey Shinkevich return qcow2_co_pwritev_compressed_task(t->bs, t->offset, t->bytes, t->qiov,
47550d483dceSAndrey Shinkevich t->qiov_offset);
47560d483dceSAndrey Shinkevich }
47570d483dceSAndrey Shinkevich
47580d483dceSAndrey Shinkevich /*
47590d483dceSAndrey Shinkevich * XXX: put compressed sectors first, then all the cluster aligned
47600d483dceSAndrey Shinkevich * tables to avoid losing bytes in alignment
47610d483dceSAndrey Shinkevich */
47627b1fb72eSKevin Wolf static int coroutine_fn GRAPH_RDLOCK
qcow2_co_pwritev_compressed_part(BlockDriverState * bs,int64_t offset,int64_t bytes,QEMUIOVector * qiov,size_t qiov_offset)47630d483dceSAndrey Shinkevich qcow2_co_pwritev_compressed_part(BlockDriverState *bs,
4764e75abedaSVladimir Sementsov-Ogievskiy int64_t offset, int64_t bytes,
47650d483dceSAndrey Shinkevich QEMUIOVector *qiov, size_t qiov_offset)
47660d483dceSAndrey Shinkevich {
47670d483dceSAndrey Shinkevich BDRVQcow2State *s = bs->opaque;
47680d483dceSAndrey Shinkevich AioTaskPool *aio = NULL;
47690d483dceSAndrey Shinkevich int ret = 0;
47700d483dceSAndrey Shinkevich
47710d483dceSAndrey Shinkevich if (has_data_file(bs)) {
47720d483dceSAndrey Shinkevich return -ENOTSUP;
47730d483dceSAndrey Shinkevich }
47740d483dceSAndrey Shinkevich
47750d483dceSAndrey Shinkevich if (bytes == 0) {
47760d483dceSAndrey Shinkevich /*
47770d483dceSAndrey Shinkevich * align end of file to a sector boundary to ease reading with
47780d483dceSAndrey Shinkevich * sector based I/Os
47790d483dceSAndrey Shinkevich */
47800050c163SKevin Wolf int64_t len = bdrv_co_getlength(bs->file->bs);
47810d483dceSAndrey Shinkevich if (len < 0) {
47820d483dceSAndrey Shinkevich return len;
47830d483dceSAndrey Shinkevich }
47847b8e4857SKevin Wolf return bdrv_co_truncate(bs->file, len, false, PREALLOC_MODE_OFF, 0,
47857b8e4857SKevin Wolf NULL);
47860d483dceSAndrey Shinkevich }
47870d483dceSAndrey Shinkevich
47880d483dceSAndrey Shinkevich if (offset_into_cluster(s, offset)) {
47890d483dceSAndrey Shinkevich return -EINVAL;
47900d483dceSAndrey Shinkevich }
47910d483dceSAndrey Shinkevich
4792fb43d2d4SAlberto Garcia if (offset_into_cluster(s, bytes) &&
4793fb43d2d4SAlberto Garcia (offset + bytes) != (bs->total_sectors << BDRV_SECTOR_BITS)) {
4794fb43d2d4SAlberto Garcia return -EINVAL;
4795fb43d2d4SAlberto Garcia }
4796fb43d2d4SAlberto Garcia
47970d483dceSAndrey Shinkevich while (bytes && aio_task_pool_status(aio) == 0) {
47980d483dceSAndrey Shinkevich uint64_t chunk_size = MIN(bytes, s->cluster_size);
47990d483dceSAndrey Shinkevich
48000d483dceSAndrey Shinkevich if (!aio && chunk_size != bytes) {
48010d483dceSAndrey Shinkevich aio = aio_task_pool_new(QCOW2_MAX_WORKERS);
48020d483dceSAndrey Shinkevich }
48030d483dceSAndrey Shinkevich
48040d483dceSAndrey Shinkevich ret = qcow2_add_task(bs, aio, qcow2_co_pwritev_compressed_task_entry,
48050d483dceSAndrey Shinkevich 0, 0, offset, chunk_size, qiov, qiov_offset, NULL);
48060d483dceSAndrey Shinkevich if (ret < 0) {
48070d483dceSAndrey Shinkevich break;
48080d483dceSAndrey Shinkevich }
48090d483dceSAndrey Shinkevich qiov_offset += chunk_size;
48100d483dceSAndrey Shinkevich offset += chunk_size;
48110d483dceSAndrey Shinkevich bytes -= chunk_size;
48120d483dceSAndrey Shinkevich }
48130d483dceSAndrey Shinkevich
48140d483dceSAndrey Shinkevich if (aio) {
48150d483dceSAndrey Shinkevich aio_task_pool_wait_all(aio);
48160d483dceSAndrey Shinkevich if (ret == 0) {
48170d483dceSAndrey Shinkevich ret = aio_task_pool_status(aio);
48180d483dceSAndrey Shinkevich }
48190d483dceSAndrey Shinkevich g_free(aio);
48200d483dceSAndrey Shinkevich }
48210d483dceSAndrey Shinkevich
48220d483dceSAndrey Shinkevich return ret;
48230d483dceSAndrey Shinkevich }
48240d483dceSAndrey Shinkevich
4825b9b10c35SKevin Wolf static int coroutine_fn GRAPH_RDLOCK
qcow2_co_preadv_compressed(BlockDriverState * bs,uint64_t l2_entry,uint64_t offset,uint64_t bytes,QEMUIOVector * qiov,size_t qiov_offset)4826c3c10f72SVladimir Sementsov-Ogievskiy qcow2_co_preadv_compressed(BlockDriverState *bs,
48279a3978a4SVladimir Sementsov-Ogievskiy uint64_t l2_entry,
4828c3c10f72SVladimir Sementsov-Ogievskiy uint64_t offset,
4829c3c10f72SVladimir Sementsov-Ogievskiy uint64_t bytes,
4830df893d25SVladimir Sementsov-Ogievskiy QEMUIOVector *qiov,
4831df893d25SVladimir Sementsov-Ogievskiy size_t qiov_offset)
4832f4b3e2a9SVladimir Sementsov-Ogievskiy {
4833f4b3e2a9SVladimir Sementsov-Ogievskiy BDRVQcow2State *s = bs->opaque;
4834a6e09846SVladimir Sementsov-Ogievskiy int ret = 0, csize;
4835f4b3e2a9SVladimir Sementsov-Ogievskiy uint64_t coffset;
4836c3c10f72SVladimir Sementsov-Ogievskiy uint8_t *buf, *out_buf;
4837c3c10f72SVladimir Sementsov-Ogievskiy int offset_in_cluster = offset_into_cluster(s, offset);
4838f4b3e2a9SVladimir Sementsov-Ogievskiy
4839a6e09846SVladimir Sementsov-Ogievskiy qcow2_parse_compressed_l2_entry(bs, l2_entry, &coffset, &csize);
4840f4b3e2a9SVladimir Sementsov-Ogievskiy
4841c3c10f72SVladimir Sementsov-Ogievskiy buf = g_try_malloc(csize);
4842c3c10f72SVladimir Sementsov-Ogievskiy if (!buf) {
4843f4b3e2a9SVladimir Sementsov-Ogievskiy return -ENOMEM;
4844f4b3e2a9SVladimir Sementsov-Ogievskiy }
4845c068a1cdSVladimir Sementsov-Ogievskiy
4846c3c10f72SVladimir Sementsov-Ogievskiy out_buf = qemu_blockalign(bs, s->cluster_size);
4847c3c10f72SVladimir Sementsov-Ogievskiy
484817362398SPaolo Bonzini BLKDBG_CO_EVENT(bs->file, BLKDBG_READ_COMPRESSED);
4849b00cb15bSVladimir Sementsov-Ogievskiy ret = bdrv_co_pread(bs->file, coffset, csize, buf, 0);
4850f4b3e2a9SVladimir Sementsov-Ogievskiy if (ret < 0) {
4851c3c10f72SVladimir Sementsov-Ogievskiy goto fail;
4852c3c10f72SVladimir Sementsov-Ogievskiy }
4853c3c10f72SVladimir Sementsov-Ogievskiy
4854e23c9d7aSVladimir Sementsov-Ogievskiy if (qcow2_co_decompress(bs, out_buf, s->cluster_size, buf, csize) < 0) {
4855c3c10f72SVladimir Sementsov-Ogievskiy ret = -EIO;
4856c3c10f72SVladimir Sementsov-Ogievskiy goto fail;
4857c3c10f72SVladimir Sementsov-Ogievskiy }
4858c3c10f72SVladimir Sementsov-Ogievskiy
4859df893d25SVladimir Sementsov-Ogievskiy qemu_iovec_from_buf(qiov, qiov_offset, out_buf + offset_in_cluster, bytes);
4860c3c10f72SVladimir Sementsov-Ogievskiy
4861c3c10f72SVladimir Sementsov-Ogievskiy fail:
4862c3c10f72SVladimir Sementsov-Ogievskiy qemu_vfree(out_buf);
4863c3c10f72SVladimir Sementsov-Ogievskiy g_free(buf);
4864c3c10f72SVladimir Sementsov-Ogievskiy
4865f4b3e2a9SVladimir Sementsov-Ogievskiy return ret;
4866f4b3e2a9SVladimir Sementsov-Ogievskiy }
4867f4b3e2a9SVladimir Sementsov-Ogievskiy
make_completely_empty(BlockDriverState * bs)48680bb79c97SKevin Wolf static int GRAPH_RDLOCK make_completely_empty(BlockDriverState *bs)
486994054183SMax Reitz {
4870ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque;
4871ed3d2ec9SMax Reitz Error *local_err = NULL;
487294054183SMax Reitz int ret, l1_clusters;
487394054183SMax Reitz int64_t offset;
487494054183SMax Reitz uint64_t *new_reftable = NULL;
487594054183SMax Reitz uint64_t rt_entry, l1_size2;
487694054183SMax Reitz struct {
487794054183SMax Reitz uint64_t l1_offset;
487894054183SMax Reitz uint64_t reftable_offset;
487994054183SMax Reitz uint32_t reftable_clusters;
488094054183SMax Reitz } QEMU_PACKED l1_ofs_rt_ofs_cls;
488194054183SMax Reitz
488294054183SMax Reitz ret = qcow2_cache_empty(bs, s->l2_table_cache);
488394054183SMax Reitz if (ret < 0) {
488494054183SMax Reitz goto fail;
488594054183SMax Reitz }
488694054183SMax Reitz
488794054183SMax Reitz ret = qcow2_cache_empty(bs, s->refcount_block_cache);
488894054183SMax Reitz if (ret < 0) {
488994054183SMax Reitz goto fail;
489094054183SMax Reitz }
489194054183SMax Reitz
489294054183SMax Reitz /* Refcounts will be broken utterly */
489394054183SMax Reitz ret = qcow2_mark_dirty(bs);
489494054183SMax Reitz if (ret < 0) {
489594054183SMax Reitz goto fail;
489694054183SMax Reitz }
489794054183SMax Reitz
489894054183SMax Reitz BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
489994054183SMax Reitz
490002b1ecfaSAlberto Garcia l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / L1E_SIZE);
490102b1ecfaSAlberto Garcia l1_size2 = (uint64_t)s->l1_size * L1E_SIZE;
490294054183SMax Reitz
490394054183SMax Reitz /* After this call, neither the in-memory nor the on-disk refcount
490494054183SMax Reitz * information accurately describe the actual references */
490594054183SMax Reitz
4906720ff280SKevin Wolf ret = bdrv_pwrite_zeroes(bs->file, s->l1_table_offset,
490774021bc4SEric Blake l1_clusters * s->cluster_size, 0);
490894054183SMax Reitz if (ret < 0) {
490994054183SMax Reitz goto fail_broken_refcounts;
491094054183SMax Reitz }
491194054183SMax Reitz memset(s->l1_table, 0, l1_size2);
491294054183SMax Reitz
491394054183SMax Reitz BLKDBG_EVENT(bs->file, BLKDBG_EMPTY_IMAGE_PREPARE);
491494054183SMax Reitz
491594054183SMax Reitz /* Overwrite enough clusters at the beginning of the sectors to place
491694054183SMax Reitz * the refcount table, a refcount block and the L1 table in; this may
491794054183SMax Reitz * overwrite parts of the existing refcount and L1 table, which is not
491894054183SMax Reitz * an issue because the dirty flag is set, complete data loss is in fact
491994054183SMax Reitz * desired and partial data loss is consequently fine as well */
4920720ff280SKevin Wolf ret = bdrv_pwrite_zeroes(bs->file, s->cluster_size,
492174021bc4SEric Blake (2 + l1_clusters) * s->cluster_size, 0);
492294054183SMax Reitz /* This call (even if it failed overall) may have overwritten on-disk
492394054183SMax Reitz * refcount structures; in that case, the in-memory refcount information
492494054183SMax Reitz * will probably differ from the on-disk information which makes the BDS
492594054183SMax Reitz * unusable */
492694054183SMax Reitz if (ret < 0) {
492794054183SMax Reitz goto fail_broken_refcounts;
492894054183SMax Reitz }
492994054183SMax Reitz
493094054183SMax Reitz BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
493194054183SMax Reitz BLKDBG_EVENT(bs->file, BLKDBG_REFTABLE_UPDATE);
493294054183SMax Reitz
493394054183SMax Reitz /* "Create" an empty reftable (one cluster) directly after the image
493494054183SMax Reitz * header and an empty L1 table three clusters after the image header;
493594054183SMax Reitz * the cluster between those two will be used as the first refblock */
4936f1f7a1ddSPeter Maydell l1_ofs_rt_ofs_cls.l1_offset = cpu_to_be64(3 * s->cluster_size);
4937f1f7a1ddSPeter Maydell l1_ofs_rt_ofs_cls.reftable_offset = cpu_to_be64(s->cluster_size);
4938f1f7a1ddSPeter Maydell l1_ofs_rt_ofs_cls.reftable_clusters = cpu_to_be32(1);
4939d9ca2ea2SKevin Wolf ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, l1_table_offset),
494032cc71deSAlberto Faria sizeof(l1_ofs_rt_ofs_cls), &l1_ofs_rt_ofs_cls, 0);
494194054183SMax Reitz if (ret < 0) {
494294054183SMax Reitz goto fail_broken_refcounts;
494394054183SMax Reitz }
494494054183SMax Reitz
494594054183SMax Reitz s->l1_table_offset = 3 * s->cluster_size;
494694054183SMax Reitz
494702b1ecfaSAlberto Garcia new_reftable = g_try_new0(uint64_t, s->cluster_size / REFTABLE_ENTRY_SIZE);
494894054183SMax Reitz if (!new_reftable) {
494994054183SMax Reitz ret = -ENOMEM;
495094054183SMax Reitz goto fail_broken_refcounts;
495194054183SMax Reitz }
495294054183SMax Reitz
495394054183SMax Reitz s->refcount_table_offset = s->cluster_size;
495402b1ecfaSAlberto Garcia s->refcount_table_size = s->cluster_size / REFTABLE_ENTRY_SIZE;
49557061a078SAlberto Garcia s->max_refcount_table_index = 0;
495694054183SMax Reitz
495794054183SMax Reitz g_free(s->refcount_table);
495894054183SMax Reitz s->refcount_table = new_reftable;
495994054183SMax Reitz new_reftable = NULL;
496094054183SMax Reitz
496194054183SMax Reitz /* Now the in-memory refcount information again corresponds to the on-disk
496294054183SMax Reitz * information (reftable is empty and no refblocks (the refblock cache is
496394054183SMax Reitz * empty)); however, this means some clusters (e.g. the image header) are
496494054183SMax Reitz * referenced, but not refcounted, but the normal qcow2 code assumes that
496594054183SMax Reitz * the in-memory information is always correct */
496694054183SMax Reitz
496794054183SMax Reitz BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_ALLOC);
496894054183SMax Reitz
496994054183SMax Reitz /* Enter the first refblock into the reftable */
497094054183SMax Reitz rt_entry = cpu_to_be64(2 * s->cluster_size);
497132cc71deSAlberto Faria ret = bdrv_pwrite_sync(bs->file, s->cluster_size, sizeof(rt_entry),
497232cc71deSAlberto Faria &rt_entry, 0);
497394054183SMax Reitz if (ret < 0) {
497494054183SMax Reitz goto fail_broken_refcounts;
497594054183SMax Reitz }
497694054183SMax Reitz s->refcount_table[0] = 2 * s->cluster_size;
497794054183SMax Reitz
497894054183SMax Reitz s->free_cluster_index = 0;
497994054183SMax Reitz assert(3 + l1_clusters <= s->refcount_block_size);
498094054183SMax Reitz offset = qcow2_alloc_clusters(bs, 3 * s->cluster_size + l1_size2);
498194054183SMax Reitz if (offset < 0) {
498294054183SMax Reitz ret = offset;
498394054183SMax Reitz goto fail_broken_refcounts;
498494054183SMax Reitz } else if (offset > 0) {
498594054183SMax Reitz error_report("First cluster in emptied image is in use");
498694054183SMax Reitz abort();
498794054183SMax Reitz }
498894054183SMax Reitz
498994054183SMax Reitz /* Now finally the in-memory information corresponds to the on-disk
499094054183SMax Reitz * structures and is correct */
499194054183SMax Reitz ret = qcow2_mark_clean(bs);
499294054183SMax Reitz if (ret < 0) {
499394054183SMax Reitz goto fail;
499494054183SMax Reitz }
499594054183SMax Reitz
4996c80d8b06SMax Reitz ret = bdrv_truncate(bs->file, (3 + l1_clusters) * s->cluster_size, false,
49977b8e4857SKevin Wolf PREALLOC_MODE_OFF, 0, &local_err);
499894054183SMax Reitz if (ret < 0) {
4999ed3d2ec9SMax Reitz error_report_err(local_err);
500094054183SMax Reitz goto fail;
500194054183SMax Reitz }
500294054183SMax Reitz
500394054183SMax Reitz return 0;
500494054183SMax Reitz
500594054183SMax Reitz fail_broken_refcounts:
500694054183SMax Reitz /* The BDS is unusable at this point. If we wanted to make it usable, we
500794054183SMax Reitz * would have to call qcow2_refcount_close(), qcow2_refcount_init(),
500894054183SMax Reitz * qcow2_check_refcounts(), qcow2_refcount_close() and qcow2_refcount_init()
500994054183SMax Reitz * again. However, because the functions which could have caused this error
501094054183SMax Reitz * path to be taken are used by those functions as well, it's very likely
501194054183SMax Reitz * that that sequence will fail as well. Therefore, just eject the BDS. */
501294054183SMax Reitz bs->drv = NULL;
501394054183SMax Reitz
501494054183SMax Reitz fail:
501594054183SMax Reitz g_free(new_reftable);
501694054183SMax Reitz return ret;
501794054183SMax Reitz }
501894054183SMax Reitz
qcow2_make_empty(BlockDriverState * bs)50190bb79c97SKevin Wolf static int GRAPH_RDLOCK qcow2_make_empty(BlockDriverState *bs)
5020491d27e2SMax Reitz {
5021ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque;
5022d2cb36afSEric Blake uint64_t offset, end_offset;
5023d2cb36afSEric Blake int step = QEMU_ALIGN_DOWN(INT_MAX, s->cluster_size);
502494054183SMax Reitz int l1_clusters, ret = 0;
5025491d27e2SMax Reitz
502602b1ecfaSAlberto Garcia l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / L1E_SIZE);
502794054183SMax Reitz
50284096974eSEric Blake if (s->qcow_version >= 3 && !s->snapshots && !s->nb_bitmaps &&
5029f0603329SDaniel P. Berrange 3 + l1_clusters <= s->refcount_block_size &&
5030db04524fSKevin Wolf s->crypt_method_header != QCOW_CRYPT_LUKS &&
5031db04524fSKevin Wolf !has_data_file(bs)) {
50324096974eSEric Blake /* The following function only works for qcow2 v3 images (it
50334096974eSEric Blake * requires the dirty flag) and only as long as there are no
50344096974eSEric Blake * features that reserve extra clusters (such as snapshots,
50354096974eSEric Blake * LUKS header, or persistent bitmaps), because it completely
50364096974eSEric Blake * empties the image. Furthermore, the L1 table and three
50374096974eSEric Blake * additional clusters (image header, refcount table, one
5038db04524fSKevin Wolf * refcount block) have to fit inside one refcount block. It
5039db04524fSKevin Wolf * only resets the image file, i.e. does not work with an
5040db04524fSKevin Wolf * external data file. */
504194054183SMax Reitz return make_completely_empty(bs);
504294054183SMax Reitz }
504394054183SMax Reitz
504494054183SMax Reitz /* This fallback code simply discards every active cluster; this is slow,
504594054183SMax Reitz * but works in all cases */
5046d2cb36afSEric Blake end_offset = bs->total_sectors * BDRV_SECTOR_SIZE;
5047d2cb36afSEric Blake for (offset = 0; offset < end_offset; offset += step) {
5048491d27e2SMax Reitz /* As this function is generally used after committing an external
5049491d27e2SMax Reitz * snapshot, QCOW2_DISCARD_SNAPSHOT seems appropriate. Also, the
5050491d27e2SMax Reitz * default action for this kind of discard is to pass the discard,
5051491d27e2SMax Reitz * which will ideally result in an actually smaller image file, as
5052491d27e2SMax Reitz * is probably desired. */
5053d2cb36afSEric Blake ret = qcow2_cluster_discard(bs, offset, MIN(step, end_offset - offset),
5054491d27e2SMax Reitz QCOW2_DISCARD_SNAPSHOT, true);
5055491d27e2SMax Reitz if (ret < 0) {
5056491d27e2SMax Reitz break;
5057491d27e2SMax Reitz }
5058491d27e2SMax Reitz }
5059491d27e2SMax Reitz
5060491d27e2SMax Reitz return ret;
5061491d27e2SMax Reitz }
5062491d27e2SMax Reitz
qcow2_co_flush_to_os(BlockDriverState * bs)50630bb79c97SKevin Wolf static coroutine_fn GRAPH_RDLOCK int qcow2_co_flush_to_os(BlockDriverState *bs)
506420d97356SBlue Swirl {
5065ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque;
506629c1a730SKevin Wolf int ret;
506729c1a730SKevin Wolf
50688b94ff85SPaolo Bonzini qemu_co_mutex_lock(&s->lock);
50698b220eb7SPaolo Bonzini ret = qcow2_write_caches(bs);
50708b94ff85SPaolo Bonzini qemu_co_mutex_unlock(&s->lock);
507129c1a730SKevin Wolf
50728b220eb7SPaolo Bonzini return ret;
5073eb489bb1SKevin Wolf }
5074eb489bb1SKevin Wolf
qcow2_measure(QemuOpts * opts,BlockDriverState * in_bs,Error ** errp)5075c501c352SStefan Hajnoczi static BlockMeasureInfo *qcow2_measure(QemuOpts *opts, BlockDriverState *in_bs,
5076c501c352SStefan Hajnoczi Error **errp)
5077c501c352SStefan Hajnoczi {
5078c501c352SStefan Hajnoczi Error *local_err = NULL;
5079c501c352SStefan Hajnoczi BlockMeasureInfo *info;
5080c501c352SStefan Hajnoczi uint64_t required = 0; /* bytes that contribute to required size */
5081c501c352SStefan Hajnoczi uint64_t virtual_size; /* disk size as seen by guest */
5082c501c352SStefan Hajnoczi uint64_t refcount_bits;
5083c501c352SStefan Hajnoczi uint64_t l2_tables;
508461914f89SStefan Hajnoczi uint64_t luks_payload_size = 0;
5085c501c352SStefan Hajnoczi size_t cluster_size;
5086c501c352SStefan Hajnoczi int version;
5087c501c352SStefan Hajnoczi char *optstr;
5088c501c352SStefan Hajnoczi PreallocMode prealloc;
5089c501c352SStefan Hajnoczi bool has_backing_file;
509061914f89SStefan Hajnoczi bool has_luks;
50917be20252SAlberto Garcia bool extended_l2;
50920dd07b29SAlberto Garcia size_t l2e_size;
5093c501c352SStefan Hajnoczi
5094c501c352SStefan Hajnoczi /* Parse image creation options */
50957be20252SAlberto Garcia extended_l2 = qemu_opt_get_bool_del(opts, BLOCK_OPT_EXTL2, false);
50967be20252SAlberto Garcia
50977be20252SAlberto Garcia cluster_size = qcow2_opt_get_cluster_size_del(opts, extended_l2,
50987be20252SAlberto Garcia &local_err);
5099c501c352SStefan Hajnoczi if (local_err) {
5100c501c352SStefan Hajnoczi goto err;
5101c501c352SStefan Hajnoczi }
5102c501c352SStefan Hajnoczi
5103c501c352SStefan Hajnoczi version = qcow2_opt_get_version_del(opts, &local_err);
5104c501c352SStefan Hajnoczi if (local_err) {
5105c501c352SStefan Hajnoczi goto err;
5106c501c352SStefan Hajnoczi }
5107c501c352SStefan Hajnoczi
5108c501c352SStefan Hajnoczi refcount_bits = qcow2_opt_get_refcount_bits_del(opts, version, &local_err);
5109c501c352SStefan Hajnoczi if (local_err) {
5110c501c352SStefan Hajnoczi goto err;
5111c501c352SStefan Hajnoczi }
5112c501c352SStefan Hajnoczi
5113c501c352SStefan Hajnoczi optstr = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
5114f7abe0ecSMarc-André Lureau prealloc = qapi_enum_parse(&PreallocMode_lookup, optstr,
511506c60b6cSMarkus Armbruster PREALLOC_MODE_OFF, &local_err);
5116c501c352SStefan Hajnoczi g_free(optstr);
5117c501c352SStefan Hajnoczi if (local_err) {
5118c501c352SStefan Hajnoczi goto err;
5119c501c352SStefan Hajnoczi }
5120c501c352SStefan Hajnoczi
5121c501c352SStefan Hajnoczi optstr = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
5122c501c352SStefan Hajnoczi has_backing_file = !!optstr;
5123c501c352SStefan Hajnoczi g_free(optstr);
5124c501c352SStefan Hajnoczi
512561914f89SStefan Hajnoczi optstr = qemu_opt_get_del(opts, BLOCK_OPT_ENCRYPT_FORMAT);
512661914f89SStefan Hajnoczi has_luks = optstr && strcmp(optstr, "luks") == 0;
512761914f89SStefan Hajnoczi g_free(optstr);
512861914f89SStefan Hajnoczi
512961914f89SStefan Hajnoczi if (has_luks) {
51306d49d3a8SStefan Hajnoczi g_autoptr(QCryptoBlockCreateOptions) create_opts = NULL;
513190766d9dSMaxim Levitsky QDict *cryptoopts = qcow2_extract_crypto_opts(opts, "luks", errp);
513261914f89SStefan Hajnoczi size_t headerlen;
513361914f89SStefan Hajnoczi
51346d49d3a8SStefan Hajnoczi create_opts = block_crypto_create_opts_init(cryptoopts, errp);
51356d49d3a8SStefan Hajnoczi qobject_unref(cryptoopts);
51366d49d3a8SStefan Hajnoczi if (!create_opts) {
51376d49d3a8SStefan Hajnoczi goto err;
51386d49d3a8SStefan Hajnoczi }
51396d49d3a8SStefan Hajnoczi
51406d49d3a8SStefan Hajnoczi if (!qcrypto_block_calculate_payload_offset(create_opts,
51416d49d3a8SStefan Hajnoczi "encrypt.",
51426d49d3a8SStefan Hajnoczi &headerlen,
51436d49d3a8SStefan Hajnoczi &local_err)) {
514461914f89SStefan Hajnoczi goto err;
514561914f89SStefan Hajnoczi }
514661914f89SStefan Hajnoczi
514761914f89SStefan Hajnoczi luks_payload_size = ROUND_UP(headerlen, cluster_size);
514861914f89SStefan Hajnoczi }
514961914f89SStefan Hajnoczi
51509e029689SAlberto Garcia virtual_size = qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0);
51519e029689SAlberto Garcia virtual_size = ROUND_UP(virtual_size, cluster_size);
5152c501c352SStefan Hajnoczi
5153c501c352SStefan Hajnoczi /* Check that virtual disk size is valid */
51540dd07b29SAlberto Garcia l2e_size = extended_l2 ? L2E_SIZE_EXTENDED : L2E_SIZE_NORMAL;
5155c501c352SStefan Hajnoczi l2_tables = DIV_ROUND_UP(virtual_size / cluster_size,
51560dd07b29SAlberto Garcia cluster_size / l2e_size);
515702b1ecfaSAlberto Garcia if (l2_tables * L1E_SIZE > QCOW_MAX_L1_SIZE) {
5158c501c352SStefan Hajnoczi error_setg(&local_err, "The image size is too large "
5159c501c352SStefan Hajnoczi "(try using a larger cluster size)");
5160c501c352SStefan Hajnoczi goto err;
5161c501c352SStefan Hajnoczi }
5162c501c352SStefan Hajnoczi
5163c501c352SStefan Hajnoczi /* Account for input image */
5164c501c352SStefan Hajnoczi if (in_bs) {
5165c501c352SStefan Hajnoczi int64_t ssize = bdrv_getlength(in_bs);
5166c501c352SStefan Hajnoczi if (ssize < 0) {
5167c501c352SStefan Hajnoczi error_setg_errno(&local_err, -ssize,
5168c501c352SStefan Hajnoczi "Unable to get image virtual_size");
5169c501c352SStefan Hajnoczi goto err;
5170c501c352SStefan Hajnoczi }
5171c501c352SStefan Hajnoczi
51729e029689SAlberto Garcia virtual_size = ROUND_UP(ssize, cluster_size);
5173c501c352SStefan Hajnoczi
5174c501c352SStefan Hajnoczi if (has_backing_file) {
5175c501c352SStefan Hajnoczi /* We don't how much of the backing chain is shared by the input
5176c501c352SStefan Hajnoczi * image and the new image file. In the worst case the new image's
5177c501c352SStefan Hajnoczi * backing file has nothing in common with the input image. Be
5178c501c352SStefan Hajnoczi * conservative and assume all clusters need to be written.
5179c501c352SStefan Hajnoczi */
5180c501c352SStefan Hajnoczi required = virtual_size;
5181c501c352SStefan Hajnoczi } else {
5182b85ee453SEric Blake int64_t offset;
518331826642SEric Blake int64_t pnum = 0;
5184c501c352SStefan Hajnoczi
518531826642SEric Blake for (offset = 0; offset < ssize; offset += pnum) {
518631826642SEric Blake int ret;
5187c501c352SStefan Hajnoczi
518831826642SEric Blake ret = bdrv_block_status_above(in_bs, NULL, offset,
518931826642SEric Blake ssize - offset, &pnum, NULL,
519031826642SEric Blake NULL);
5191c501c352SStefan Hajnoczi if (ret < 0) {
5192c501c352SStefan Hajnoczi error_setg_errno(&local_err, -ret,
5193c501c352SStefan Hajnoczi "Unable to get block status");
5194c501c352SStefan Hajnoczi goto err;
5195c501c352SStefan Hajnoczi }
5196c501c352SStefan Hajnoczi
5197c501c352SStefan Hajnoczi if (ret & BDRV_BLOCK_ZERO) {
5198c501c352SStefan Hajnoczi /* Skip zero regions (safe with no backing file) */
5199c501c352SStefan Hajnoczi } else if ((ret & (BDRV_BLOCK_DATA | BDRV_BLOCK_ALLOCATED)) ==
5200c501c352SStefan Hajnoczi (BDRV_BLOCK_DATA | BDRV_BLOCK_ALLOCATED)) {
5201c501c352SStefan Hajnoczi /* Extend pnum to end of cluster for next iteration */
520231826642SEric Blake pnum = ROUND_UP(offset + pnum, cluster_size) - offset;
5203c501c352SStefan Hajnoczi
5204c501c352SStefan Hajnoczi /* Count clusters we've seen */
520531826642SEric Blake required += offset % cluster_size + pnum;
5206c501c352SStefan Hajnoczi }
5207c501c352SStefan Hajnoczi }
5208c501c352SStefan Hajnoczi }
5209c501c352SStefan Hajnoczi }
5210c501c352SStefan Hajnoczi
5211c501c352SStefan Hajnoczi /* Take into account preallocation. Nothing special is needed for
5212c501c352SStefan Hajnoczi * PREALLOC_MODE_METADATA since metadata is always counted.
5213c501c352SStefan Hajnoczi */
5214c501c352SStefan Hajnoczi if (prealloc == PREALLOC_MODE_FULL || prealloc == PREALLOC_MODE_FALLOC) {
5215c501c352SStefan Hajnoczi required = virtual_size;
5216c501c352SStefan Hajnoczi }
5217c501c352SStefan Hajnoczi
52185d72c68bSEric Blake info = g_new0(BlockMeasureInfo, 1);
52190dd07b29SAlberto Garcia info->fully_allocated = luks_payload_size +
5220c501c352SStefan Hajnoczi qcow2_calc_prealloc_size(virtual_size, cluster_size,
52210dd07b29SAlberto Garcia ctz32(refcount_bits), extended_l2);
5222c501c352SStefan Hajnoczi
52235d72c68bSEric Blake /*
52245d72c68bSEric Blake * Remove data clusters that are not required. This overestimates the
5225c501c352SStefan Hajnoczi * required size because metadata needed for the fully allocated file is
52265d72c68bSEric Blake * still counted. Show bitmaps only if both source and destination
52275d72c68bSEric Blake * would support them.
5228c501c352SStefan Hajnoczi */
5229c501c352SStefan Hajnoczi info->required = info->fully_allocated - virtual_size + required;
52305d72c68bSEric Blake info->has_bitmaps = version >= 3 && in_bs &&
52315d72c68bSEric Blake bdrv_supports_persistent_dirty_bitmap(in_bs);
52325d72c68bSEric Blake if (info->has_bitmaps) {
52335d72c68bSEric Blake info->bitmaps = qcow2_get_persistent_dirty_bitmap_size(in_bs,
52345d72c68bSEric Blake cluster_size);
52355d72c68bSEric Blake }
5236c501c352SStefan Hajnoczi return info;
5237c501c352SStefan Hajnoczi
5238c501c352SStefan Hajnoczi err:
5239c501c352SStefan Hajnoczi error_propagate(errp, local_err);
5240c501c352SStefan Hajnoczi return NULL;
5241c501c352SStefan Hajnoczi }
5242c501c352SStefan Hajnoczi
52433d47eb0aSEmanuele Giuseppe Esposito static int coroutine_fn
qcow2_co_get_info(BlockDriverState * bs,BlockDriverInfo * bdi)52443d47eb0aSEmanuele Giuseppe Esposito qcow2_co_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
524520d97356SBlue Swirl {
5246ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque;
524720d97356SBlue Swirl bdi->cluster_size = s->cluster_size;
5248c54483b6SAndrey Drobyshev bdi->subcluster_size = s->subcluster_size;
52497c80ab3fSJes Sorensen bdi->vm_state_offset = qcow2_vm_state_offset(s);
525038b44096SVladimir Sementsov-Ogievskiy bdi->is_dirty = s->incompatible_features & QCOW2_INCOMPAT_DIRTY;
525120d97356SBlue Swirl return 0;
525220d97356SBlue Swirl }
525320d97356SBlue Swirl
525479a55866SKevin Wolf static ImageInfoSpecific * GRAPH_RDLOCK
qcow2_get_specific_info(BlockDriverState * bs,Error ** errp)525579a55866SKevin Wolf qcow2_get_specific_info(BlockDriverState *bs, Error **errp)
525637764dfbSMax Reitz {
5257ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque;
52580a12f6f8SDaniel P. Berrange ImageInfoSpecific *spec_info;
52590a12f6f8SDaniel P. Berrange QCryptoBlockInfo *encrypt_info = NULL;
526037764dfbSMax Reitz
52610a12f6f8SDaniel P. Berrange if (s->crypto != NULL) {
526283bad8cbSVladimir Sementsov-Ogievskiy encrypt_info = qcrypto_block_get_info(s->crypto, errp);
526383bad8cbSVladimir Sementsov-Ogievskiy if (!encrypt_info) {
52641bf6e9caSAndrey Shinkevich return NULL;
52651bf6e9caSAndrey Shinkevich }
52660a12f6f8SDaniel P. Berrange }
52670a12f6f8SDaniel P. Berrange
52680a12f6f8SDaniel P. Berrange spec_info = g_new(ImageInfoSpecific, 1);
526937764dfbSMax Reitz *spec_info = (ImageInfoSpecific){
52706a8f9661SEric Blake .type = IMAGE_INFO_SPECIFIC_KIND_QCOW2,
5271b8968c87SAndrey Shinkevich .u.qcow2.data = g_new0(ImageInfoSpecificQCow2, 1),
527237764dfbSMax Reitz };
527337764dfbSMax Reitz if (s->qcow_version == 2) {
527432bafa8fSEric Blake *spec_info->u.qcow2.data = (ImageInfoSpecificQCow2){
527537764dfbSMax Reitz .compat = g_strdup("0.10"),
52760709c5a1SMax Reitz .refcount_bits = s->refcount_bits,
527737764dfbSMax Reitz };
527837764dfbSMax Reitz } else if (s->qcow_version == 3) {
5279b8968c87SAndrey Shinkevich Qcow2BitmapInfoList *bitmaps;
528083bad8cbSVladimir Sementsov-Ogievskiy if (!qcow2_get_bitmap_info_list(bs, &bitmaps, errp)) {
5281b8968c87SAndrey Shinkevich qapi_free_ImageInfoSpecific(spec_info);
528271eaec2eSEric Blake qapi_free_QCryptoBlockInfo(encrypt_info);
5283b8968c87SAndrey Shinkevich return NULL;
5284b8968c87SAndrey Shinkevich }
528532bafa8fSEric Blake *spec_info->u.qcow2.data = (ImageInfoSpecificQCow2){
528637764dfbSMax Reitz .compat = g_strdup("1.1"),
528737764dfbSMax Reitz .lazy_refcounts = s->compatible_features &
528837764dfbSMax Reitz QCOW2_COMPAT_LAZY_REFCOUNTS,
528937764dfbSMax Reitz .has_lazy_refcounts = true,
52909009b196SMax Reitz .corrupt = s->incompatible_features &
52919009b196SMax Reitz QCOW2_INCOMPAT_CORRUPT,
52929009b196SMax Reitz .has_corrupt = true,
52937be20252SAlberto Garcia .has_extended_l2 = true,
52947be20252SAlberto Garcia .extended_l2 = has_subclusters(s),
52950709c5a1SMax Reitz .refcount_bits = s->refcount_bits,
5296b8968c87SAndrey Shinkevich .has_bitmaps = !!bitmaps,
5297b8968c87SAndrey Shinkevich .bitmaps = bitmaps,
52989b890bdcSKevin Wolf .data_file = g_strdup(s->image_data_file),
52996c3944dcSKevin Wolf .has_data_file_raw = has_data_file(bs),
53006c3944dcSKevin Wolf .data_file_raw = data_file_is_raw(bs),
5301572ad978SDenis Plotnikov .compression_type = s->compression_type,
530237764dfbSMax Reitz };
5303b1fc8f93SDenis V. Lunev } else {
5304b1fc8f93SDenis V. Lunev /* if this assertion fails, this probably means a new version was
5305b1fc8f93SDenis V. Lunev * added without having it covered here */
5306d125e4afSPierrick Bouvier g_assert_not_reached();
530737764dfbSMax Reitz }
530837764dfbSMax Reitz
53090a12f6f8SDaniel P. Berrange if (encrypt_info) {
53100a12f6f8SDaniel P. Berrange ImageInfoSpecificQCow2Encryption *qencrypt =
53110a12f6f8SDaniel P. Berrange g_new(ImageInfoSpecificQCow2Encryption, 1);
53120a12f6f8SDaniel P. Berrange switch (encrypt_info->format) {
5313d23d2ef3SMarkus Armbruster case QCRYPTO_BLOCK_FORMAT_QCOW:
53140a12f6f8SDaniel P. Berrange qencrypt->format = BLOCKDEV_QCOW2_ENCRYPTION_FORMAT_AES;
53150a12f6f8SDaniel P. Berrange break;
5316d23d2ef3SMarkus Armbruster case QCRYPTO_BLOCK_FORMAT_LUKS:
53170a12f6f8SDaniel P. Berrange qencrypt->format = BLOCKDEV_QCOW2_ENCRYPTION_FORMAT_LUKS;
53180a12f6f8SDaniel P. Berrange qencrypt->u.luks = encrypt_info->u.luks;
53190a12f6f8SDaniel P. Berrange break;
53200a12f6f8SDaniel P. Berrange default:
53210a12f6f8SDaniel P. Berrange abort();
53220a12f6f8SDaniel P. Berrange }
53230a12f6f8SDaniel P. Berrange /* Since we did shallow copy above, erase any pointers
53240a12f6f8SDaniel P. Berrange * in the original info */
53250a12f6f8SDaniel P. Berrange memset(&encrypt_info->u, 0, sizeof(encrypt_info->u));
53260a12f6f8SDaniel P. Berrange qapi_free_QCryptoBlockInfo(encrypt_info);
53270a12f6f8SDaniel P. Berrange
53280a12f6f8SDaniel P. Berrange spec_info->u.qcow2.data->encrypt = qencrypt;
53290a12f6f8SDaniel P. Berrange }
53300a12f6f8SDaniel P. Berrange
533137764dfbSMax Reitz return spec_info;
533237764dfbSMax Reitz }
533337764dfbSMax Reitz
533406717986SKevin Wolf static int coroutine_mixed_fn GRAPH_RDLOCK
qcow2_has_zero_init(BlockDriverState * bs)533506717986SKevin Wolf qcow2_has_zero_init(BlockDriverState *bs)
533638841dcdSMax Reitz {
533738841dcdSMax Reitz BDRVQcow2State *s = bs->opaque;
533838841dcdSMax Reitz bool preallocated;
533938841dcdSMax Reitz
534038841dcdSMax Reitz if (qemu_in_coroutine()) {
534138841dcdSMax Reitz qemu_co_mutex_lock(&s->lock);
534238841dcdSMax Reitz }
534338841dcdSMax Reitz /*
534438841dcdSMax Reitz * Check preallocation status: Preallocated images have all L2
534538841dcdSMax Reitz * tables allocated, nonpreallocated images have none. It is
534638841dcdSMax Reitz * therefore enough to check the first one.
534738841dcdSMax Reitz */
534838841dcdSMax Reitz preallocated = s->l1_size > 0 && s->l1_table[0] != 0;
534938841dcdSMax Reitz if (qemu_in_coroutine()) {
535038841dcdSMax Reitz qemu_co_mutex_unlock(&s->lock);
535138841dcdSMax Reitz }
535238841dcdSMax Reitz
535338841dcdSMax Reitz if (!preallocated) {
535438841dcdSMax Reitz return 1;
535538841dcdSMax Reitz } else if (bs->encrypted) {
535638841dcdSMax Reitz return 0;
535738841dcdSMax Reitz } else {
535838841dcdSMax Reitz return bdrv_has_zero_init(s->data_file->bs);
535938841dcdSMax Reitz }
536038841dcdSMax Reitz }
536138841dcdSMax Reitz
5362558902ccSVladimir Sementsov-Ogievskiy /*
5363558902ccSVladimir Sementsov-Ogievskiy * Check the request to vmstate. On success return
5364558902ccSVladimir Sementsov-Ogievskiy * qcow2_vm_state_offset(bs) + @pos
5365558902ccSVladimir Sementsov-Ogievskiy */
qcow2_check_vmstate_request(BlockDriverState * bs,QEMUIOVector * qiov,int64_t pos)5366558902ccSVladimir Sementsov-Ogievskiy static int64_t qcow2_check_vmstate_request(BlockDriverState *bs,
5367558902ccSVladimir Sementsov-Ogievskiy QEMUIOVector *qiov, int64_t pos)
5368558902ccSVladimir Sementsov-Ogievskiy {
5369558902ccSVladimir Sementsov-Ogievskiy BDRVQcow2State *s = bs->opaque;
5370558902ccSVladimir Sementsov-Ogievskiy int64_t vmstate_offset = qcow2_vm_state_offset(s);
5371558902ccSVladimir Sementsov-Ogievskiy int ret;
5372558902ccSVladimir Sementsov-Ogievskiy
5373558902ccSVladimir Sementsov-Ogievskiy /* Incoming requests must be OK */
5374558902ccSVladimir Sementsov-Ogievskiy bdrv_check_qiov_request(pos, qiov->size, qiov, 0, &error_abort);
5375558902ccSVladimir Sementsov-Ogievskiy
5376558902ccSVladimir Sementsov-Ogievskiy if (INT64_MAX - pos < vmstate_offset) {
5377558902ccSVladimir Sementsov-Ogievskiy return -EIO;
5378558902ccSVladimir Sementsov-Ogievskiy }
5379558902ccSVladimir Sementsov-Ogievskiy
5380558902ccSVladimir Sementsov-Ogievskiy pos += vmstate_offset;
5381558902ccSVladimir Sementsov-Ogievskiy ret = bdrv_check_qiov_request(pos, qiov->size, qiov, 0, NULL);
5382558902ccSVladimir Sementsov-Ogievskiy if (ret < 0) {
5383558902ccSVladimir Sementsov-Ogievskiy return ret;
5384558902ccSVladimir Sementsov-Ogievskiy }
5385558902ccSVladimir Sementsov-Ogievskiy
5386558902ccSVladimir Sementsov-Ogievskiy return pos;
5387558902ccSVladimir Sementsov-Ogievskiy }
5388558902ccSVladimir Sementsov-Ogievskiy
53897b1fb72eSKevin Wolf static int coroutine_fn GRAPH_RDLOCK
qcow2_co_save_vmstate(BlockDriverState * bs,QEMUIOVector * qiov,int64_t pos)53907b1fb72eSKevin Wolf qcow2_co_save_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos)
539120d97356SBlue Swirl {
5392558902ccSVladimir Sementsov-Ogievskiy int64_t offset = qcow2_check_vmstate_request(bs, qiov, pos);
5393558902ccSVladimir Sementsov-Ogievskiy if (offset < 0) {
5394558902ccSVladimir Sementsov-Ogievskiy return offset;
5395558902ccSVladimir Sementsov-Ogievskiy }
539620d97356SBlue Swirl
539717362398SPaolo Bonzini BLKDBG_CO_EVENT(bs->file, BLKDBG_VMSTATE_SAVE);
5398558902ccSVladimir Sementsov-Ogievskiy return bs->drv->bdrv_co_pwritev_part(bs, offset, qiov->size, qiov, 0, 0);
539920d97356SBlue Swirl }
540020d97356SBlue Swirl
54017b1fb72eSKevin Wolf static int coroutine_fn GRAPH_RDLOCK
qcow2_co_load_vmstate(BlockDriverState * bs,QEMUIOVector * qiov,int64_t pos)54027b1fb72eSKevin Wolf qcow2_co_load_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos)
540320d97356SBlue Swirl {
5404558902ccSVladimir Sementsov-Ogievskiy int64_t offset = qcow2_check_vmstate_request(bs, qiov, pos);
5405558902ccSVladimir Sementsov-Ogievskiy if (offset < 0) {
5406558902ccSVladimir Sementsov-Ogievskiy return offset;
5407558902ccSVladimir Sementsov-Ogievskiy }
540820d97356SBlue Swirl
540917362398SPaolo Bonzini BLKDBG_CO_EVENT(bs->file, BLKDBG_VMSTATE_LOAD);
5410558902ccSVladimir Sementsov-Ogievskiy return bs->drv->bdrv_co_preadv_part(bs, offset, qiov->size, qiov, 0, 0);
541120d97356SBlue Swirl }
541220d97356SBlue Swirl
qcow2_has_compressed_clusters(BlockDriverState * bs)54130bb79c97SKevin Wolf static int GRAPH_RDLOCK qcow2_has_compressed_clusters(BlockDriverState *bs)
5414083c2456SVladimir Sementsov-Ogievskiy {
5415083c2456SVladimir Sementsov-Ogievskiy int64_t offset = 0;
5416083c2456SVladimir Sementsov-Ogievskiy int64_t bytes = bdrv_getlength(bs);
5417083c2456SVladimir Sementsov-Ogievskiy
5418083c2456SVladimir Sementsov-Ogievskiy if (bytes < 0) {
5419083c2456SVladimir Sementsov-Ogievskiy return bytes;
5420083c2456SVladimir Sementsov-Ogievskiy }
5421083c2456SVladimir Sementsov-Ogievskiy
5422083c2456SVladimir Sementsov-Ogievskiy while (bytes != 0) {
5423083c2456SVladimir Sementsov-Ogievskiy int ret;
5424083c2456SVladimir Sementsov-Ogievskiy QCow2SubclusterType type;
5425083c2456SVladimir Sementsov-Ogievskiy unsigned int cur_bytes = MIN(INT_MAX, bytes);
5426083c2456SVladimir Sementsov-Ogievskiy uint64_t host_offset;
5427083c2456SVladimir Sementsov-Ogievskiy
5428083c2456SVladimir Sementsov-Ogievskiy ret = qcow2_get_host_offset(bs, offset, &cur_bytes, &host_offset,
5429083c2456SVladimir Sementsov-Ogievskiy &type);
5430083c2456SVladimir Sementsov-Ogievskiy if (ret < 0) {
5431083c2456SVladimir Sementsov-Ogievskiy return ret;
5432083c2456SVladimir Sementsov-Ogievskiy }
5433083c2456SVladimir Sementsov-Ogievskiy
5434083c2456SVladimir Sementsov-Ogievskiy if (type == QCOW2_SUBCLUSTER_COMPRESSED) {
5435083c2456SVladimir Sementsov-Ogievskiy return 1;
5436083c2456SVladimir Sementsov-Ogievskiy }
5437083c2456SVladimir Sementsov-Ogievskiy
5438083c2456SVladimir Sementsov-Ogievskiy offset += cur_bytes;
5439083c2456SVladimir Sementsov-Ogievskiy bytes -= cur_bytes;
5440083c2456SVladimir Sementsov-Ogievskiy }
5441083c2456SVladimir Sementsov-Ogievskiy
5442083c2456SVladimir Sementsov-Ogievskiy return 0;
5443083c2456SVladimir Sementsov-Ogievskiy }
5444083c2456SVladimir Sementsov-Ogievskiy
54459296b3edSMax Reitz /*
54469296b3edSMax Reitz * Downgrades an image's version. To achieve this, any incompatible features
54479296b3edSMax Reitz * have to be removed.
54489296b3edSMax Reitz */
54490bb79c97SKevin Wolf static int GRAPH_RDLOCK
qcow2_downgrade(BlockDriverState * bs,int target_version,BlockDriverAmendStatusCB * status_cb,void * cb_opaque,Error ** errp)54500bb79c97SKevin Wolf qcow2_downgrade(BlockDriverState *bs, int target_version,
5451d1402b50SMax Reitz BlockDriverAmendStatusCB *status_cb, void *cb_opaque,
5452d1402b50SMax Reitz Error **errp)
54539296b3edSMax Reitz {
5454ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque;
54559296b3edSMax Reitz int current_version = s->qcow_version;
54569296b3edSMax Reitz int ret;
54577fa140abSEric Blake int i;
54589296b3edSMax Reitz
5459d1402b50SMax Reitz /* This is qcow2_downgrade(), not qcow2_upgrade() */
5460d1402b50SMax Reitz assert(target_version < current_version);
5461d1402b50SMax Reitz
5462d1402b50SMax Reitz /* There are no other versions (now) that you can downgrade to */
5463d1402b50SMax Reitz assert(target_version == 2);
54649296b3edSMax Reitz
54659296b3edSMax Reitz if (s->refcount_order != 4) {
5466d1402b50SMax Reitz error_setg(errp, "compat=0.10 requires refcount_bits=16");
54679296b3edSMax Reitz return -ENOTSUP;
54689296b3edSMax Reitz }
54699296b3edSMax Reitz
5470966b000fSKevin Wolf if (has_data_file(bs)) {
5471966b000fSKevin Wolf error_setg(errp, "Cannot downgrade an image with a data file");
5472966b000fSKevin Wolf return -ENOTSUP;
5473966b000fSKevin Wolf }
5474966b000fSKevin Wolf
54757fa140abSEric Blake /*
54767fa140abSEric Blake * If any internal snapshot has a different size than the current
54777fa140abSEric Blake * image size, or VM state size that exceeds 32 bits, downgrading
54787fa140abSEric Blake * is unsafe. Even though we would still use v3-compliant output
54797fa140abSEric Blake * to preserve that data, other v2 programs might not realize
54807fa140abSEric Blake * those optional fields are important.
54817fa140abSEric Blake */
54827fa140abSEric Blake for (i = 0; i < s->nb_snapshots; i++) {
54837fa140abSEric Blake if (s->snapshots[i].vm_state_size > UINT32_MAX ||
54847fa140abSEric Blake s->snapshots[i].disk_size != bs->total_sectors * BDRV_SECTOR_SIZE) {
54857fa140abSEric Blake error_setg(errp, "Internal snapshots prevent downgrade of image");
54867fa140abSEric Blake return -ENOTSUP;
54877fa140abSEric Blake }
54887fa140abSEric Blake }
54897fa140abSEric Blake
54909296b3edSMax Reitz /* clear incompatible features */
54919296b3edSMax Reitz if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
54929296b3edSMax Reitz ret = qcow2_mark_clean(bs);
54939296b3edSMax Reitz if (ret < 0) {
5494d1402b50SMax Reitz error_setg_errno(errp, -ret, "Failed to make the image clean");
54959296b3edSMax Reitz return ret;
54969296b3edSMax Reitz }
54979296b3edSMax Reitz }
54989296b3edSMax Reitz
54999296b3edSMax Reitz /* with QCOW2_INCOMPAT_CORRUPT, it is pretty much impossible to get here in
55009296b3edSMax Reitz * the first place; if that happens nonetheless, returning -ENOTSUP is the
55019296b3edSMax Reitz * best thing to do anyway */
55029296b3edSMax Reitz
5503083c2456SVladimir Sementsov-Ogievskiy if (s->incompatible_features & ~QCOW2_INCOMPAT_COMPRESSION) {
5504d1402b50SMax Reitz error_setg(errp, "Cannot downgrade an image with incompatible features "
5505083c2456SVladimir Sementsov-Ogievskiy "0x%" PRIx64 " set",
5506083c2456SVladimir Sementsov-Ogievskiy s->incompatible_features & ~QCOW2_INCOMPAT_COMPRESSION);
55079296b3edSMax Reitz return -ENOTSUP;
55089296b3edSMax Reitz }
55099296b3edSMax Reitz
55109296b3edSMax Reitz /* since we can ignore compatible features, we can set them to 0 as well */
55119296b3edSMax Reitz s->compatible_features = 0;
55129296b3edSMax Reitz /* if lazy refcounts have been used, they have already been fixed through
55139296b3edSMax Reitz * clearing the dirty flag */
55149296b3edSMax Reitz
55159296b3edSMax Reitz /* clearing autoclear features is trivial */
55169296b3edSMax Reitz s->autoclear_features = 0;
55179296b3edSMax Reitz
55188b13976dSMax Reitz ret = qcow2_expand_zero_clusters(bs, status_cb, cb_opaque);
55199296b3edSMax Reitz if (ret < 0) {
5520d1402b50SMax Reitz error_setg_errno(errp, -ret, "Failed to turn zero into data clusters");
55219296b3edSMax Reitz return ret;
55229296b3edSMax Reitz }
55239296b3edSMax Reitz
5524083c2456SVladimir Sementsov-Ogievskiy if (s->incompatible_features & QCOW2_INCOMPAT_COMPRESSION) {
5525083c2456SVladimir Sementsov-Ogievskiy ret = qcow2_has_compressed_clusters(bs);
5526083c2456SVladimir Sementsov-Ogievskiy if (ret < 0) {
5527083c2456SVladimir Sementsov-Ogievskiy error_setg(errp, "Failed to check block status");
5528083c2456SVladimir Sementsov-Ogievskiy return -EINVAL;
5529083c2456SVladimir Sementsov-Ogievskiy }
5530083c2456SVladimir Sementsov-Ogievskiy if (ret) {
5531083c2456SVladimir Sementsov-Ogievskiy error_setg(errp, "Cannot downgrade an image with zstd compression "
5532083c2456SVladimir Sementsov-Ogievskiy "type and existing compressed clusters");
5533083c2456SVladimir Sementsov-Ogievskiy return -ENOTSUP;
5534083c2456SVladimir Sementsov-Ogievskiy }
5535083c2456SVladimir Sementsov-Ogievskiy /*
5536083c2456SVladimir Sementsov-Ogievskiy * No compressed clusters for now, so just chose default zlib
5537083c2456SVladimir Sementsov-Ogievskiy * compression.
5538083c2456SVladimir Sementsov-Ogievskiy */
5539083c2456SVladimir Sementsov-Ogievskiy s->incompatible_features &= ~QCOW2_INCOMPAT_COMPRESSION;
5540083c2456SVladimir Sementsov-Ogievskiy s->compression_type = QCOW2_COMPRESSION_TYPE_ZLIB;
5541083c2456SVladimir Sementsov-Ogievskiy }
5542083c2456SVladimir Sementsov-Ogievskiy
5543083c2456SVladimir Sementsov-Ogievskiy assert(s->incompatible_features == 0);
5544083c2456SVladimir Sementsov-Ogievskiy
55459296b3edSMax Reitz s->qcow_version = target_version;
55469296b3edSMax Reitz ret = qcow2_update_header(bs);
55479296b3edSMax Reitz if (ret < 0) {
55489296b3edSMax Reitz s->qcow_version = current_version;
5549d1402b50SMax Reitz error_setg_errno(errp, -ret, "Failed to update the image header");
55509296b3edSMax Reitz return ret;
55519296b3edSMax Reitz }
55529296b3edSMax Reitz return 0;
55539296b3edSMax Reitz }
55549296b3edSMax Reitz
5555722efb0cSMax Reitz /*
5556722efb0cSMax Reitz * Upgrades an image's version. While newer versions encompass all
5557722efb0cSMax Reitz * features of older versions, some things may have to be presented
5558722efb0cSMax Reitz * differently.
5559722efb0cSMax Reitz */
55600bb79c97SKevin Wolf static int GRAPH_RDLOCK
qcow2_upgrade(BlockDriverState * bs,int target_version,BlockDriverAmendStatusCB * status_cb,void * cb_opaque,Error ** errp)55610bb79c97SKevin Wolf qcow2_upgrade(BlockDriverState *bs, int target_version,
5562722efb0cSMax Reitz BlockDriverAmendStatusCB *status_cb, void *cb_opaque,
5563722efb0cSMax Reitz Error **errp)
5564722efb0cSMax Reitz {
5565722efb0cSMax Reitz BDRVQcow2State *s = bs->opaque;
55660a85af35SMax Reitz bool need_snapshot_update;
5567722efb0cSMax Reitz int current_version = s->qcow_version;
55680a85af35SMax Reitz int i;
5569722efb0cSMax Reitz int ret;
5570722efb0cSMax Reitz
5571722efb0cSMax Reitz /* This is qcow2_upgrade(), not qcow2_downgrade() */
5572722efb0cSMax Reitz assert(target_version > current_version);
5573722efb0cSMax Reitz
5574722efb0cSMax Reitz /* There are no other versions (yet) that you can upgrade to */
5575722efb0cSMax Reitz assert(target_version == 3);
5576722efb0cSMax Reitz
55770a85af35SMax Reitz status_cb(bs, 0, 2, cb_opaque);
55780a85af35SMax Reitz
55790a85af35SMax Reitz /*
55800a85af35SMax Reitz * In v2, snapshots do not need to have extra data. v3 requires
55810a85af35SMax Reitz * the 64-bit VM state size and the virtual disk size to be
55820a85af35SMax Reitz * present.
55830a85af35SMax Reitz * qcow2_write_snapshots() will always write the list in the
55840a85af35SMax Reitz * v3-compliant format.
55850a85af35SMax Reitz */
55860a85af35SMax Reitz need_snapshot_update = false;
55870a85af35SMax Reitz for (i = 0; i < s->nb_snapshots; i++) {
55880a85af35SMax Reitz if (s->snapshots[i].extra_data_size <
55890a85af35SMax Reitz sizeof_field(QCowSnapshotExtraData, vm_state_size_large) +
55900a85af35SMax Reitz sizeof_field(QCowSnapshotExtraData, disk_size))
55910a85af35SMax Reitz {
55920a85af35SMax Reitz need_snapshot_update = true;
55930a85af35SMax Reitz break;
55940a85af35SMax Reitz }
55950a85af35SMax Reitz }
55960a85af35SMax Reitz if (need_snapshot_update) {
55970a85af35SMax Reitz ret = qcow2_write_snapshots(bs);
55980a85af35SMax Reitz if (ret < 0) {
55990a85af35SMax Reitz error_setg_errno(errp, -ret, "Failed to update the snapshot table");
56000a85af35SMax Reitz return ret;
56010a85af35SMax Reitz }
56020a85af35SMax Reitz }
56030a85af35SMax Reitz status_cb(bs, 1, 2, cb_opaque);
5604722efb0cSMax Reitz
5605722efb0cSMax Reitz s->qcow_version = target_version;
5606722efb0cSMax Reitz ret = qcow2_update_header(bs);
5607722efb0cSMax Reitz if (ret < 0) {
5608722efb0cSMax Reitz s->qcow_version = current_version;
5609722efb0cSMax Reitz error_setg_errno(errp, -ret, "Failed to update the image header");
5610722efb0cSMax Reitz return ret;
5611722efb0cSMax Reitz }
56120a85af35SMax Reitz status_cb(bs, 2, 2, cb_opaque);
5613722efb0cSMax Reitz
5614722efb0cSMax Reitz return 0;
5615722efb0cSMax Reitz }
5616722efb0cSMax Reitz
5617c293a809SMax Reitz typedef enum Qcow2AmendOperation {
5618c293a809SMax Reitz /* This is the value Qcow2AmendHelperCBInfo::last_operation will be
5619c293a809SMax Reitz * statically initialized to so that the helper CB can discern the first
5620c293a809SMax Reitz * invocation from an operation change */
5621c293a809SMax Reitz QCOW2_NO_OPERATION = 0,
5622c293a809SMax Reitz
5623722efb0cSMax Reitz QCOW2_UPGRADING,
562490766d9dSMaxim Levitsky QCOW2_UPDATING_ENCRYPTION,
562561ce55fcSMax Reitz QCOW2_CHANGING_REFCOUNT_ORDER,
5626c293a809SMax Reitz QCOW2_DOWNGRADING,
5627c293a809SMax Reitz } Qcow2AmendOperation;
5628c293a809SMax Reitz
5629c293a809SMax Reitz typedef struct Qcow2AmendHelperCBInfo {
5630c293a809SMax Reitz /* The code coordinating the amend operations should only modify
5631c293a809SMax Reitz * these four fields; the rest will be managed by the CB */
5632c293a809SMax Reitz BlockDriverAmendStatusCB *original_status_cb;
5633c293a809SMax Reitz void *original_cb_opaque;
5634c293a809SMax Reitz
5635c293a809SMax Reitz Qcow2AmendOperation current_operation;
5636c293a809SMax Reitz
5637c293a809SMax Reitz /* Total number of operations to perform (only set once) */
5638c293a809SMax Reitz int total_operations;
5639c293a809SMax Reitz
5640c293a809SMax Reitz /* The following fields are managed by the CB */
5641c293a809SMax Reitz
5642c293a809SMax Reitz /* Number of operations completed */
5643c293a809SMax Reitz int operations_completed;
5644c293a809SMax Reitz
5645c293a809SMax Reitz /* Cumulative offset of all completed operations */
5646c293a809SMax Reitz int64_t offset_completed;
5647c293a809SMax Reitz
5648c293a809SMax Reitz Qcow2AmendOperation last_operation;
5649c293a809SMax Reitz int64_t last_work_size;
5650c293a809SMax Reitz } Qcow2AmendHelperCBInfo;
5651c293a809SMax Reitz
qcow2_amend_helper_cb(BlockDriverState * bs,int64_t operation_offset,int64_t operation_work_size,void * opaque)5652c293a809SMax Reitz static void qcow2_amend_helper_cb(BlockDriverState *bs,
5653c293a809SMax Reitz int64_t operation_offset,
5654c293a809SMax Reitz int64_t operation_work_size, void *opaque)
5655c293a809SMax Reitz {
5656c293a809SMax Reitz Qcow2AmendHelperCBInfo *info = opaque;
5657c293a809SMax Reitz int64_t current_work_size;
5658c293a809SMax Reitz int64_t projected_work_size;
5659c293a809SMax Reitz
5660c293a809SMax Reitz if (info->current_operation != info->last_operation) {
5661c293a809SMax Reitz if (info->last_operation != QCOW2_NO_OPERATION) {
5662c293a809SMax Reitz info->offset_completed += info->last_work_size;
5663c293a809SMax Reitz info->operations_completed++;
5664c293a809SMax Reitz }
5665c293a809SMax Reitz
5666c293a809SMax Reitz info->last_operation = info->current_operation;
5667c293a809SMax Reitz }
5668c293a809SMax Reitz
5669c293a809SMax Reitz assert(info->total_operations > 0);
5670c293a809SMax Reitz assert(info->operations_completed < info->total_operations);
5671c293a809SMax Reitz
5672c293a809SMax Reitz info->last_work_size = operation_work_size;
5673c293a809SMax Reitz
5674c293a809SMax Reitz current_work_size = info->offset_completed + operation_work_size;
5675c293a809SMax Reitz
5676c293a809SMax Reitz /* current_work_size is the total work size for (operations_completed + 1)
5677c293a809SMax Reitz * operations (which includes this one), so multiply it by the number of
5678c293a809SMax Reitz * operations not covered and divide it by the number of operations
5679c293a809SMax Reitz * covered to get a projection for the operations not covered */
5680c293a809SMax Reitz projected_work_size = current_work_size * (info->total_operations -
5681c293a809SMax Reitz info->operations_completed - 1)
5682c293a809SMax Reitz / (info->operations_completed + 1);
5683c293a809SMax Reitz
5684c293a809SMax Reitz info->original_status_cb(bs, info->offset_completed + operation_offset,
5685c293a809SMax Reitz current_work_size + projected_work_size,
5686c293a809SMax Reitz info->original_cb_opaque);
5687c293a809SMax Reitz }
5688c293a809SMax Reitz
56890bb79c97SKevin Wolf static int GRAPH_RDLOCK
qcow2_amend_options(BlockDriverState * bs,QemuOpts * opts,BlockDriverAmendStatusCB * status_cb,void * cb_opaque,bool force,Error ** errp)56900bb79c97SKevin Wolf qcow2_amend_options(BlockDriverState *bs, QemuOpts *opts,
56910bb79c97SKevin Wolf BlockDriverAmendStatusCB *status_cb, void *cb_opaque,
56920bb79c97SKevin Wolf bool force, Error **errp)
56939296b3edSMax Reitz {
5694ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque;
56959296b3edSMax Reitz int old_version = s->qcow_version, new_version = old_version;
56969296b3edSMax Reitz uint64_t new_size = 0;
56979b890bdcSKevin Wolf const char *backing_file = NULL, *backing_format = NULL, *data_file = NULL;
56989296b3edSMax Reitz bool lazy_refcounts = s->use_lazy_refcounts;
56996c3944dcSKevin Wolf bool data_file_raw = data_file_is_raw(bs);
57001bd0e2d1SChunyan Liu const char *compat = NULL;
570161ce55fcSMax Reitz int refcount_bits = s->refcount_bits;
57029296b3edSMax Reitz int ret;
57031bd0e2d1SChunyan Liu QemuOptDesc *desc = opts->list->desc;
5704c293a809SMax Reitz Qcow2AmendHelperCBInfo helper_cb_info;
570590766d9dSMaxim Levitsky bool encryption_update = false;
57069296b3edSMax Reitz
57071bd0e2d1SChunyan Liu while (desc && desc->name) {
57081bd0e2d1SChunyan Liu if (!qemu_opt_find(opts, desc->name)) {
57099296b3edSMax Reitz /* only change explicitly defined options */
57101bd0e2d1SChunyan Liu desc++;
57119296b3edSMax Reitz continue;
57129296b3edSMax Reitz }
57139296b3edSMax Reitz
57148a17b83cSMax Reitz if (!strcmp(desc->name, BLOCK_OPT_COMPAT_LEVEL)) {
57158a17b83cSMax Reitz compat = qemu_opt_get(opts, BLOCK_OPT_COMPAT_LEVEL);
57161bd0e2d1SChunyan Liu if (!compat) {
57179296b3edSMax Reitz /* preserve default */
5718f7077c98SEric Blake } else if (!strcmp(compat, "0.10") || !strcmp(compat, "v2")) {
57199296b3edSMax Reitz new_version = 2;
5720f7077c98SEric Blake } else if (!strcmp(compat, "1.1") || !strcmp(compat, "v3")) {
57219296b3edSMax Reitz new_version = 3;
57229296b3edSMax Reitz } else {
5723d1402b50SMax Reitz error_setg(errp, "Unknown compatibility level %s", compat);
57249296b3edSMax Reitz return -EINVAL;
57259296b3edSMax Reitz }
57268a17b83cSMax Reitz } else if (!strcmp(desc->name, BLOCK_OPT_SIZE)) {
57278a17b83cSMax Reitz new_size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, 0);
57288a17b83cSMax Reitz } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FILE)) {
57298a17b83cSMax Reitz backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
57308a17b83cSMax Reitz } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FMT)) {
57318a17b83cSMax Reitz backing_format = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
573290766d9dSMaxim Levitsky } else if (g_str_has_prefix(desc->name, "encrypt.")) {
573390766d9dSMaxim Levitsky if (!s->crypto) {
573490766d9dSMaxim Levitsky error_setg(errp,
573590766d9dSMaxim Levitsky "Can't amend encryption options - encryption not present");
573690766d9dSMaxim Levitsky return -EINVAL;
573790766d9dSMaxim Levitsky }
573890766d9dSMaxim Levitsky if (s->crypt_method_header != QCOW_CRYPT_LUKS) {
573990766d9dSMaxim Levitsky error_setg(errp,
574090766d9dSMaxim Levitsky "Only LUKS encryption options can be amended");
574190766d9dSMaxim Levitsky return -ENOTSUP;
574290766d9dSMaxim Levitsky }
574390766d9dSMaxim Levitsky encryption_update = true;
57448a17b83cSMax Reitz } else if (!strcmp(desc->name, BLOCK_OPT_LAZY_REFCOUNTS)) {
57458a17b83cSMax Reitz lazy_refcounts = qemu_opt_get_bool(opts, BLOCK_OPT_LAZY_REFCOUNTS,
57461bd0e2d1SChunyan Liu lazy_refcounts);
574706d05fa7SMax Reitz } else if (!strcmp(desc->name, BLOCK_OPT_REFCOUNT_BITS)) {
574861ce55fcSMax Reitz refcount_bits = qemu_opt_get_number(opts, BLOCK_OPT_REFCOUNT_BITS,
574961ce55fcSMax Reitz refcount_bits);
575061ce55fcSMax Reitz
575161ce55fcSMax Reitz if (refcount_bits <= 0 || refcount_bits > 64 ||
575261ce55fcSMax Reitz !is_power_of_2(refcount_bits))
575361ce55fcSMax Reitz {
5754d1402b50SMax Reitz error_setg(errp, "Refcount width must be a power of two and "
5755d1402b50SMax Reitz "may not exceed 64 bits");
575661ce55fcSMax Reitz return -EINVAL;
575761ce55fcSMax Reitz }
57589b890bdcSKevin Wolf } else if (!strcmp(desc->name, BLOCK_OPT_DATA_FILE)) {
57599b890bdcSKevin Wolf data_file = qemu_opt_get(opts, BLOCK_OPT_DATA_FILE);
57609b890bdcSKevin Wolf if (data_file && !has_data_file(bs)) {
57619b890bdcSKevin Wolf error_setg(errp, "data-file can only be set for images that "
57629b890bdcSKevin Wolf "use an external data file");
57639b890bdcSKevin Wolf return -EINVAL;
57649b890bdcSKevin Wolf }
57656c3944dcSKevin Wolf } else if (!strcmp(desc->name, BLOCK_OPT_DATA_FILE_RAW)) {
57666c3944dcSKevin Wolf data_file_raw = qemu_opt_get_bool(opts, BLOCK_OPT_DATA_FILE_RAW,
57676c3944dcSKevin Wolf data_file_raw);
57686c3944dcSKevin Wolf if (data_file_raw && !data_file_is_raw(bs)) {
57696c3944dcSKevin Wolf error_setg(errp, "data-file-raw cannot be set on existing "
57706c3944dcSKevin Wolf "images");
57716c3944dcSKevin Wolf return -EINVAL;
57726c3944dcSKevin Wolf }
57739296b3edSMax Reitz } else {
5774164e0f89SMax Reitz /* if this point is reached, this probably means a new option was
57759296b3edSMax Reitz * added without having it covered here */
5776164e0f89SMax Reitz abort();
57779296b3edSMax Reitz }
57781bd0e2d1SChunyan Liu
57791bd0e2d1SChunyan Liu desc++;
57809296b3edSMax Reitz }
57819296b3edSMax Reitz
5782c293a809SMax Reitz helper_cb_info = (Qcow2AmendHelperCBInfo){
5783c293a809SMax Reitz .original_status_cb = status_cb,
5784c293a809SMax Reitz .original_cb_opaque = cb_opaque,
5785722efb0cSMax Reitz .total_operations = (new_version != old_version)
578690766d9dSMaxim Levitsky + (s->refcount_bits != refcount_bits) +
578790766d9dSMaxim Levitsky (encryption_update == true)
5788c293a809SMax Reitz };
5789c293a809SMax Reitz
57901038bbb8SMax Reitz /* Upgrade first (some features may require compat=1.1) */
57919296b3edSMax Reitz if (new_version > old_version) {
5792722efb0cSMax Reitz helper_cb_info.current_operation = QCOW2_UPGRADING;
5793722efb0cSMax Reitz ret = qcow2_upgrade(bs, new_version, &qcow2_amend_helper_cb,
5794722efb0cSMax Reitz &helper_cb_info, errp);
57959296b3edSMax Reitz if (ret < 0) {
57969296b3edSMax Reitz return ret;
57979296b3edSMax Reitz }
57989296b3edSMax Reitz }
57999296b3edSMax Reitz
580090766d9dSMaxim Levitsky if (encryption_update) {
580190766d9dSMaxim Levitsky QDict *amend_opts_dict;
580290766d9dSMaxim Levitsky QCryptoBlockAmendOptions *amend_opts;
580390766d9dSMaxim Levitsky
580490766d9dSMaxim Levitsky helper_cb_info.current_operation = QCOW2_UPDATING_ENCRYPTION;
580590766d9dSMaxim Levitsky amend_opts_dict = qcow2_extract_crypto_opts(opts, "luks", errp);
580690766d9dSMaxim Levitsky if (!amend_opts_dict) {
580790766d9dSMaxim Levitsky return -EINVAL;
580890766d9dSMaxim Levitsky }
580990766d9dSMaxim Levitsky amend_opts = block_crypto_amend_opts_init(amend_opts_dict, errp);
581090766d9dSMaxim Levitsky qobject_unref(amend_opts_dict);
581190766d9dSMaxim Levitsky if (!amend_opts) {
581290766d9dSMaxim Levitsky return -EINVAL;
581390766d9dSMaxim Levitsky }
581490766d9dSMaxim Levitsky ret = qcrypto_block_amend_options(s->crypto,
581590766d9dSMaxim Levitsky qcow2_crypto_hdr_read_func,
581690766d9dSMaxim Levitsky qcow2_crypto_hdr_write_func,
581790766d9dSMaxim Levitsky bs,
581890766d9dSMaxim Levitsky amend_opts,
581990766d9dSMaxim Levitsky force,
582090766d9dSMaxim Levitsky errp);
582190766d9dSMaxim Levitsky qapi_free_QCryptoBlockAmendOptions(amend_opts);
582290766d9dSMaxim Levitsky if (ret < 0) {
582390766d9dSMaxim Levitsky return ret;
582490766d9dSMaxim Levitsky }
582590766d9dSMaxim Levitsky }
582690766d9dSMaxim Levitsky
582761ce55fcSMax Reitz if (s->refcount_bits != refcount_bits) {
582861ce55fcSMax Reitz int refcount_order = ctz32(refcount_bits);
582961ce55fcSMax Reitz
583061ce55fcSMax Reitz if (new_version < 3 && refcount_bits != 16) {
5831d1402b50SMax Reitz error_setg(errp, "Refcount widths other than 16 bits require "
583261ce55fcSMax Reitz "compatibility level 1.1 or above (use compat=1.1 or "
583361ce55fcSMax Reitz "greater)");
583461ce55fcSMax Reitz return -EINVAL;
583561ce55fcSMax Reitz }
583661ce55fcSMax Reitz
583761ce55fcSMax Reitz helper_cb_info.current_operation = QCOW2_CHANGING_REFCOUNT_ORDER;
583861ce55fcSMax Reitz ret = qcow2_change_refcount_order(bs, refcount_order,
583961ce55fcSMax Reitz &qcow2_amend_helper_cb,
5840d1402b50SMax Reitz &helper_cb_info, errp);
584161ce55fcSMax Reitz if (ret < 0) {
584261ce55fcSMax Reitz return ret;
584361ce55fcSMax Reitz }
584461ce55fcSMax Reitz }
584561ce55fcSMax Reitz
58466c3944dcSKevin Wolf /* data-file-raw blocks backing files, so clear it first if requested */
58476c3944dcSKevin Wolf if (data_file_raw) {
58486c3944dcSKevin Wolf s->autoclear_features |= QCOW2_AUTOCLEAR_DATA_FILE_RAW;
58496c3944dcSKevin Wolf } else {
58506c3944dcSKevin Wolf s->autoclear_features &= ~QCOW2_AUTOCLEAR_DATA_FILE_RAW;
58516c3944dcSKevin Wolf }
58526c3944dcSKevin Wolf
58539b890bdcSKevin Wolf if (data_file) {
58549b890bdcSKevin Wolf g_free(s->image_data_file);
58559b890bdcSKevin Wolf s->image_data_file = *data_file ? g_strdup(data_file) : NULL;
58569b890bdcSKevin Wolf }
58579b890bdcSKevin Wolf
58589b890bdcSKevin Wolf ret = qcow2_update_header(bs);
58599b890bdcSKevin Wolf if (ret < 0) {
58609b890bdcSKevin Wolf error_setg_errno(errp, -ret, "Failed to update the image header");
58619b890bdcSKevin Wolf return ret;
58629b890bdcSKevin Wolf }
58639b890bdcSKevin Wolf
58649296b3edSMax Reitz if (backing_file || backing_format) {
5865bc5ee6daSEric Blake if (g_strcmp0(backing_file, s->image_backing_file) ||
5866bc5ee6daSEric Blake g_strcmp0(backing_format, s->image_backing_format)) {
58675a385bf5SEric Blake error_setg(errp, "Cannot amend the backing file");
58685a385bf5SEric Blake error_append_hint(errp,
58695a385bf5SEric Blake "You can use 'qemu-img rebase' instead.\n");
58705a385bf5SEric Blake return -EINVAL;
58719296b3edSMax Reitz }
58729296b3edSMax Reitz }
58739296b3edSMax Reitz
58749296b3edSMax Reitz if (s->use_lazy_refcounts != lazy_refcounts) {
58759296b3edSMax Reitz if (lazy_refcounts) {
58761038bbb8SMax Reitz if (new_version < 3) {
5877d1402b50SMax Reitz error_setg(errp, "Lazy refcounts only supported with "
5878d1402b50SMax Reitz "compatibility level 1.1 and above (use compat=1.1 "
5879d1402b50SMax Reitz "or greater)");
58809296b3edSMax Reitz return -EINVAL;
58819296b3edSMax Reitz }
58829296b3edSMax Reitz s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
58839296b3edSMax Reitz ret = qcow2_update_header(bs);
58849296b3edSMax Reitz if (ret < 0) {
58859296b3edSMax Reitz s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
5886d1402b50SMax Reitz error_setg_errno(errp, -ret, "Failed to update the image header");
58879296b3edSMax Reitz return ret;
58889296b3edSMax Reitz }
58899296b3edSMax Reitz s->use_lazy_refcounts = true;
58909296b3edSMax Reitz } else {
58919296b3edSMax Reitz /* make image clean first */
58929296b3edSMax Reitz ret = qcow2_mark_clean(bs);
58939296b3edSMax Reitz if (ret < 0) {
5894d1402b50SMax Reitz error_setg_errno(errp, -ret, "Failed to make the image clean");
58959296b3edSMax Reitz return ret;
58969296b3edSMax Reitz }
58979296b3edSMax Reitz /* now disallow lazy refcounts */
58989296b3edSMax Reitz s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
58999296b3edSMax Reitz ret = qcow2_update_header(bs);
59009296b3edSMax Reitz if (ret < 0) {
59019296b3edSMax Reitz s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
5902d1402b50SMax Reitz error_setg_errno(errp, -ret, "Failed to update the image header");
59039296b3edSMax Reitz return ret;
59049296b3edSMax Reitz }
59059296b3edSMax Reitz s->use_lazy_refcounts = false;
59069296b3edSMax Reitz }
59079296b3edSMax Reitz }
59089296b3edSMax Reitz
59099296b3edSMax Reitz if (new_size) {
5910a3aeeab5SEric Blake BlockBackend *blk = blk_new_with_bs(bs, BLK_PERM_RESIZE, BLK_PERM_ALL,
5911a3aeeab5SEric Blake errp);
5912a3aeeab5SEric Blake if (!blk) {
5913a3aeeab5SEric Blake return -EPERM;
5914d7086422SKevin Wolf }
5915d7086422SKevin Wolf
5916e8d04f92SMax Reitz /*
5917e8d04f92SMax Reitz * Amending image options should ensure that the image has
5918e8d04f92SMax Reitz * exactly the given new values, so pass exact=true here.
5919e8d04f92SMax Reitz */
59208c6242b6SKevin Wolf ret = blk_truncate(blk, new_size, true, PREALLOC_MODE_OFF, 0, errp);
592170b27f36SKevin Wolf blk_unref(blk);
59229296b3edSMax Reitz if (ret < 0) {
59239296b3edSMax Reitz return ret;
59249296b3edSMax Reitz }
59259296b3edSMax Reitz }
59269296b3edSMax Reitz
59271038bbb8SMax Reitz /* Downgrade last (so unsupported features can be removed before) */
59281038bbb8SMax Reitz if (new_version < old_version) {
5929c293a809SMax Reitz helper_cb_info.current_operation = QCOW2_DOWNGRADING;
5930c293a809SMax Reitz ret = qcow2_downgrade(bs, new_version, &qcow2_amend_helper_cb,
5931d1402b50SMax Reitz &helper_cb_info, errp);
59321038bbb8SMax Reitz if (ret < 0) {
59331038bbb8SMax Reitz return ret;
59341038bbb8SMax Reitz }
59351038bbb8SMax Reitz }
59361038bbb8SMax Reitz
59379296b3edSMax Reitz return 0;
59389296b3edSMax Reitz }
59399296b3edSMax Reitz
qcow2_co_amend(BlockDriverState * bs,BlockdevAmendOptions * opts,bool force,Error ** errp)59408ea1613dSMaxim Levitsky static int coroutine_fn qcow2_co_amend(BlockDriverState *bs,
59418ea1613dSMaxim Levitsky BlockdevAmendOptions *opts,
59428ea1613dSMaxim Levitsky bool force,
59438ea1613dSMaxim Levitsky Error **errp)
59448ea1613dSMaxim Levitsky {
59458ea1613dSMaxim Levitsky BlockdevAmendOptionsQcow2 *qopts = &opts->u.qcow2;
59468ea1613dSMaxim Levitsky BDRVQcow2State *s = bs->opaque;
59478ea1613dSMaxim Levitsky int ret = 0;
59488ea1613dSMaxim Levitsky
594954fde4ffSMarkus Armbruster if (qopts->encrypt) {
59508ea1613dSMaxim Levitsky if (!s->crypto) {
59518ea1613dSMaxim Levitsky error_setg(errp, "image is not encrypted, can't amend");
59528ea1613dSMaxim Levitsky return -EOPNOTSUPP;
59538ea1613dSMaxim Levitsky }
59548ea1613dSMaxim Levitsky
5955d23d2ef3SMarkus Armbruster if (qopts->encrypt->format != QCRYPTO_BLOCK_FORMAT_LUKS) {
59568ea1613dSMaxim Levitsky error_setg(errp,
59578ea1613dSMaxim Levitsky "Amend can't be used to change the qcow2 encryption format");
59588ea1613dSMaxim Levitsky return -EOPNOTSUPP;
59598ea1613dSMaxim Levitsky }
59608ea1613dSMaxim Levitsky
59618ea1613dSMaxim Levitsky if (s->crypt_method_header != QCOW_CRYPT_LUKS) {
59628ea1613dSMaxim Levitsky error_setg(errp,
59638ea1613dSMaxim Levitsky "Only LUKS encryption options can be amended for qcow2 with blockdev-amend");
59648ea1613dSMaxim Levitsky return -EOPNOTSUPP;
59658ea1613dSMaxim Levitsky }
59668ea1613dSMaxim Levitsky
59678ea1613dSMaxim Levitsky ret = qcrypto_block_amend_options(s->crypto,
59688ea1613dSMaxim Levitsky qcow2_crypto_hdr_read_func,
59698ea1613dSMaxim Levitsky qcow2_crypto_hdr_write_func,
59708ea1613dSMaxim Levitsky bs,
59718ea1613dSMaxim Levitsky qopts->encrypt,
59728ea1613dSMaxim Levitsky force,
59738ea1613dSMaxim Levitsky errp);
59748ea1613dSMaxim Levitsky }
59758ea1613dSMaxim Levitsky return ret;
59768ea1613dSMaxim Levitsky }
59778ea1613dSMaxim Levitsky
597885186ebdSMax Reitz /*
597985186ebdSMax Reitz * If offset or size are negative, respectively, they will not be included in
598085186ebdSMax Reitz * the BLOCK_IMAGE_CORRUPTED event emitted.
598185186ebdSMax Reitz * fatal will be ignored for read-only BDS; corruptions found there will always
598285186ebdSMax Reitz * be considered non-fatal.
598385186ebdSMax Reitz */
qcow2_signal_corruption(BlockDriverState * bs,bool fatal,int64_t offset,int64_t size,const char * message_format,...)598485186ebdSMax Reitz void qcow2_signal_corruption(BlockDriverState *bs, bool fatal, int64_t offset,
598585186ebdSMax Reitz int64_t size, const char *message_format, ...)
598685186ebdSMax Reitz {
5987ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque;
5988dc881b44SAlberto Garcia const char *node_name;
598985186ebdSMax Reitz char *message;
599085186ebdSMax Reitz va_list ap;
599185186ebdSMax Reitz
5992ddf3b47eSMax Reitz fatal = fatal && bdrv_is_writable(bs);
599385186ebdSMax Reitz
599485186ebdSMax Reitz if (s->signaled_corruption &&
599585186ebdSMax Reitz (!fatal || (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT)))
599685186ebdSMax Reitz {
599785186ebdSMax Reitz return;
599885186ebdSMax Reitz }
599985186ebdSMax Reitz
600085186ebdSMax Reitz va_start(ap, message_format);
600185186ebdSMax Reitz message = g_strdup_vprintf(message_format, ap);
600285186ebdSMax Reitz va_end(ap);
600385186ebdSMax Reitz
600485186ebdSMax Reitz if (fatal) {
600585186ebdSMax Reitz fprintf(stderr, "qcow2: Marking image as corrupt: %s; further "
600685186ebdSMax Reitz "corruption events will be suppressed\n", message);
600785186ebdSMax Reitz } else {
600885186ebdSMax Reitz fprintf(stderr, "qcow2: Image is corrupt: %s; further non-fatal "
600985186ebdSMax Reitz "corruption events will be suppressed\n", message);
601085186ebdSMax Reitz }
601185186ebdSMax Reitz
6012dc881b44SAlberto Garcia node_name = bdrv_get_node_name(bs);
6013dc881b44SAlberto Garcia qapi_event_send_block_image_corrupted(bdrv_get_device_name(bs),
601454fde4ffSMarkus Armbruster *node_name ? node_name : NULL,
6015dc881b44SAlberto Garcia message, offset >= 0, offset,
6016dc881b44SAlberto Garcia size >= 0, size,
60173ab72385SPeter Xu fatal);
601885186ebdSMax Reitz g_free(message);
601985186ebdSMax Reitz
602085186ebdSMax Reitz if (fatal) {
602185186ebdSMax Reitz qcow2_mark_corrupt(bs);
602285186ebdSMax Reitz bs->drv = NULL; /* make BDS unusable */
602385186ebdSMax Reitz }
602485186ebdSMax Reitz
602585186ebdSMax Reitz s->signaled_corruption = true;
602685186ebdSMax Reitz }
602785186ebdSMax Reitz
6028df373fb0SMaxim Levitsky #define QCOW_COMMON_OPTIONS \
6029df373fb0SMaxim Levitsky { \
6030df373fb0SMaxim Levitsky .name = BLOCK_OPT_SIZE, \
6031df373fb0SMaxim Levitsky .type = QEMU_OPT_SIZE, \
6032df373fb0SMaxim Levitsky .help = "Virtual disk size" \
6033df373fb0SMaxim Levitsky }, \
6034df373fb0SMaxim Levitsky { \
6035df373fb0SMaxim Levitsky .name = BLOCK_OPT_COMPAT_LEVEL, \
6036df373fb0SMaxim Levitsky .type = QEMU_OPT_STRING, \
6037df373fb0SMaxim Levitsky .help = "Compatibility level (v2 [0.10] or v3 [1.1])" \
6038df373fb0SMaxim Levitsky }, \
6039df373fb0SMaxim Levitsky { \
6040df373fb0SMaxim Levitsky .name = BLOCK_OPT_BACKING_FILE, \
6041df373fb0SMaxim Levitsky .type = QEMU_OPT_STRING, \
6042df373fb0SMaxim Levitsky .help = "File name of a base image" \
6043df373fb0SMaxim Levitsky }, \
6044df373fb0SMaxim Levitsky { \
6045df373fb0SMaxim Levitsky .name = BLOCK_OPT_BACKING_FMT, \
6046df373fb0SMaxim Levitsky .type = QEMU_OPT_STRING, \
6047df373fb0SMaxim Levitsky .help = "Image format of the base image" \
6048df373fb0SMaxim Levitsky }, \
6049df373fb0SMaxim Levitsky { \
6050df373fb0SMaxim Levitsky .name = BLOCK_OPT_DATA_FILE, \
6051df373fb0SMaxim Levitsky .type = QEMU_OPT_STRING, \
6052df373fb0SMaxim Levitsky .help = "File name of an external data file" \
6053df373fb0SMaxim Levitsky }, \
6054df373fb0SMaxim Levitsky { \
6055df373fb0SMaxim Levitsky .name = BLOCK_OPT_DATA_FILE_RAW, \
6056df373fb0SMaxim Levitsky .type = QEMU_OPT_BOOL, \
6057df373fb0SMaxim Levitsky .help = "The external data file must stay valid " \
6058df373fb0SMaxim Levitsky "as a raw image" \
6059df373fb0SMaxim Levitsky }, \
6060df373fb0SMaxim Levitsky { \
60610b6786a9SMaxim Levitsky .name = BLOCK_OPT_LAZY_REFCOUNTS, \
60620b6786a9SMaxim Levitsky .type = QEMU_OPT_BOOL, \
60630b6786a9SMaxim Levitsky .help = "Postpone refcount updates", \
60640b6786a9SMaxim Levitsky .def_value_str = "off" \
60650b6786a9SMaxim Levitsky }, \
60660b6786a9SMaxim Levitsky { \
60670b6786a9SMaxim Levitsky .name = BLOCK_OPT_REFCOUNT_BITS, \
60680b6786a9SMaxim Levitsky .type = QEMU_OPT_NUMBER, \
60690b6786a9SMaxim Levitsky .help = "Width of a reference count entry in bits", \
60700b6786a9SMaxim Levitsky .def_value_str = "16" \
60710b6786a9SMaxim Levitsky }
60720b6786a9SMaxim Levitsky
60730b6786a9SMaxim Levitsky static QemuOptsList qcow2_create_opts = {
60740b6786a9SMaxim Levitsky .name = "qcow2-create-opts",
60750b6786a9SMaxim Levitsky .head = QTAILQ_HEAD_INITIALIZER(qcow2_create_opts.head),
60760b6786a9SMaxim Levitsky .desc = {
60770b6786a9SMaxim Levitsky { \
6078df373fb0SMaxim Levitsky .name = BLOCK_OPT_ENCRYPT, \
6079df373fb0SMaxim Levitsky .type = QEMU_OPT_BOOL, \
6080df373fb0SMaxim Levitsky .help = "Encrypt the image with format 'aes'. (Deprecated " \
6081df373fb0SMaxim Levitsky "in favor of " BLOCK_OPT_ENCRYPT_FORMAT "=aes)", \
6082df373fb0SMaxim Levitsky }, \
6083df373fb0SMaxim Levitsky { \
6084df373fb0SMaxim Levitsky .name = BLOCK_OPT_ENCRYPT_FORMAT, \
6085df373fb0SMaxim Levitsky .type = QEMU_OPT_STRING, \
6086df373fb0SMaxim Levitsky .help = "Encrypt the image, format choices: 'aes', 'luks'", \
6087df373fb0SMaxim Levitsky }, \
6088df373fb0SMaxim Levitsky BLOCK_CRYPTO_OPT_DEF_KEY_SECRET("encrypt.", \
6089df373fb0SMaxim Levitsky "ID of secret providing qcow AES key or LUKS passphrase"), \
6090df373fb0SMaxim Levitsky BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_ALG("encrypt."), \
6091df373fb0SMaxim Levitsky BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_MODE("encrypt."), \
6092df373fb0SMaxim Levitsky BLOCK_CRYPTO_OPT_DEF_LUKS_IVGEN_ALG("encrypt."), \
6093df373fb0SMaxim Levitsky BLOCK_CRYPTO_OPT_DEF_LUKS_IVGEN_HASH_ALG("encrypt."), \
6094df373fb0SMaxim Levitsky BLOCK_CRYPTO_OPT_DEF_LUKS_HASH_ALG("encrypt."), \
6095df373fb0SMaxim Levitsky BLOCK_CRYPTO_OPT_DEF_LUKS_ITER_TIME("encrypt."), \
6096df373fb0SMaxim Levitsky { \
6097df373fb0SMaxim Levitsky .name = BLOCK_OPT_CLUSTER_SIZE, \
6098df373fb0SMaxim Levitsky .type = QEMU_OPT_SIZE, \
6099df373fb0SMaxim Levitsky .help = "qcow2 cluster size", \
6100df373fb0SMaxim Levitsky .def_value_str = stringify(DEFAULT_CLUSTER_SIZE) \
6101df373fb0SMaxim Levitsky }, \
6102df373fb0SMaxim Levitsky { \
61037be20252SAlberto Garcia .name = BLOCK_OPT_EXTL2, \
61047be20252SAlberto Garcia .type = QEMU_OPT_BOOL, \
61057be20252SAlberto Garcia .help = "Extended L2 tables", \
61067be20252SAlberto Garcia .def_value_str = "off" \
61077be20252SAlberto Garcia }, \
61087be20252SAlberto Garcia { \
6109df373fb0SMaxim Levitsky .name = BLOCK_OPT_PREALLOC, \
6110df373fb0SMaxim Levitsky .type = QEMU_OPT_STRING, \
6111df373fb0SMaxim Levitsky .help = "Preallocation mode (allowed values: off, " \
6112df373fb0SMaxim Levitsky "metadata, falloc, full)" \
6113df373fb0SMaxim Levitsky }, \
6114df373fb0SMaxim Levitsky { \
6115df373fb0SMaxim Levitsky .name = BLOCK_OPT_COMPRESSION_TYPE, \
6116df373fb0SMaxim Levitsky .type = QEMU_OPT_STRING, \
6117df373fb0SMaxim Levitsky .help = "Compression method used for image cluster " \
6118df373fb0SMaxim Levitsky "compression", \
6119df373fb0SMaxim Levitsky .def_value_str = "zlib" \
61200b6786a9SMaxim Levitsky },
6121df373fb0SMaxim Levitsky QCOW_COMMON_OPTIONS,
6122df373fb0SMaxim Levitsky { /* end of list */ }
6123df373fb0SMaxim Levitsky }
6124df373fb0SMaxim Levitsky };
6125df373fb0SMaxim Levitsky
6126df373fb0SMaxim Levitsky static QemuOptsList qcow2_amend_opts = {
6127df373fb0SMaxim Levitsky .name = "qcow2-amend-opts",
6128df373fb0SMaxim Levitsky .head = QTAILQ_HEAD_INITIALIZER(qcow2_amend_opts.head),
6129df373fb0SMaxim Levitsky .desc = {
613090766d9dSMaxim Levitsky BLOCK_CRYPTO_OPT_DEF_LUKS_STATE("encrypt."),
613190766d9dSMaxim Levitsky BLOCK_CRYPTO_OPT_DEF_LUKS_KEYSLOT("encrypt."),
613290766d9dSMaxim Levitsky BLOCK_CRYPTO_OPT_DEF_LUKS_OLD_SECRET("encrypt."),
613390766d9dSMaxim Levitsky BLOCK_CRYPTO_OPT_DEF_LUKS_NEW_SECRET("encrypt."),
613490766d9dSMaxim Levitsky BLOCK_CRYPTO_OPT_DEF_LUKS_ITER_TIME("encrypt."),
6135df373fb0SMaxim Levitsky QCOW_COMMON_OPTIONS,
61361bd0e2d1SChunyan Liu { /* end of list */ }
61371bd0e2d1SChunyan Liu }
613820d97356SBlue Swirl };
613920d97356SBlue Swirl
61402654267cSMax Reitz static const char *const qcow2_strong_runtime_opts[] = {
61412654267cSMax Reitz "encrypt." BLOCK_CRYPTO_OPT_QCOW_KEY_SECRET,
61422654267cSMax Reitz
61432654267cSMax Reitz NULL
61442654267cSMax Reitz };
61452654267cSMax Reitz
61465f535a94SMax Reitz BlockDriver bdrv_qcow2 = {
614720d97356SBlue Swirl .format_name = "qcow2",
6148ff99129aSKevin Wolf .instance_size = sizeof(BDRVQcow2State),
61497c80ab3fSJes Sorensen .bdrv_probe = qcow2_probe,
61507c80ab3fSJes Sorensen .bdrv_open = qcow2_open,
61517c80ab3fSJes Sorensen .bdrv_close = qcow2_close,
615221d82ac9SJeff Cody .bdrv_reopen_prepare = qcow2_reopen_prepare,
61535b0959a7SKevin Wolf .bdrv_reopen_commit = qcow2_reopen_commit,
615465eb7c85SPeter Krempa .bdrv_reopen_commit_post = qcow2_reopen_commit_post,
61555b0959a7SKevin Wolf .bdrv_reopen_abort = qcow2_reopen_abort,
61565365f44dSKevin Wolf .bdrv_join_options = qcow2_join_options,
615769dca43dSMax Reitz .bdrv_child_perm = bdrv_default_perms,
6158efc75e2aSStefan Hajnoczi .bdrv_co_create_opts = qcow2_co_create_opts,
6159b0292b85SKevin Wolf .bdrv_co_create = qcow2_co_create,
616038841dcdSMax Reitz .bdrv_has_zero_init = qcow2_has_zero_init,
6161a320fb04SEric Blake .bdrv_co_block_status = qcow2_co_block_status,
616220d97356SBlue Swirl
6163df893d25SVladimir Sementsov-Ogievskiy .bdrv_co_preadv_part = qcow2_co_preadv_part,
61645396234bSVladimir Sementsov-Ogievskiy .bdrv_co_pwritev_part = qcow2_co_pwritev_part,
6165eb489bb1SKevin Wolf .bdrv_co_flush_to_os = qcow2_co_flush_to_os,
6166419b19d9SStefan Hajnoczi
61675544b59fSEric Blake .bdrv_co_pwrite_zeroes = qcow2_co_pwrite_zeroes,
616882e8a788SEric Blake .bdrv_co_pdiscard = qcow2_co_pdiscard,
6169fd9fcd37SFam Zheng .bdrv_co_copy_range_from = qcow2_co_copy_range_from,
6170fd9fcd37SFam Zheng .bdrv_co_copy_range_to = qcow2_co_copy_range_to,
6171061ca8a3SKevin Wolf .bdrv_co_truncate = qcow2_co_truncate,
61725396234bSVladimir Sementsov-Ogievskiy .bdrv_co_pwritev_compressed_part = qcow2_co_pwritev_compressed_part,
6173491d27e2SMax Reitz .bdrv_make_empty = qcow2_make_empty,
617420d97356SBlue Swirl
617520d97356SBlue Swirl .bdrv_snapshot_create = qcow2_snapshot_create,
617620d97356SBlue Swirl .bdrv_snapshot_goto = qcow2_snapshot_goto,
617720d97356SBlue Swirl .bdrv_snapshot_delete = qcow2_snapshot_delete,
617820d97356SBlue Swirl .bdrv_snapshot_list = qcow2_snapshot_list,
617951ef6727Sedison .bdrv_snapshot_load_tmp = qcow2_snapshot_load_tmp,
6180c501c352SStefan Hajnoczi .bdrv_measure = qcow2_measure,
61813d47eb0aSEmanuele Giuseppe Esposito .bdrv_co_get_info = qcow2_co_get_info,
618237764dfbSMax Reitz .bdrv_get_specific_info = qcow2_get_specific_info,
618320d97356SBlue Swirl
6184ca5e2ad9SEmanuele Giuseppe Esposito .bdrv_co_save_vmstate = qcow2_co_save_vmstate,
6185ca5e2ad9SEmanuele Giuseppe Esposito .bdrv_co_load_vmstate = qcow2_co_load_vmstate,
618620d97356SBlue Swirl
6187d67066d8SMax Reitz .is_format = true,
61888ee79e70SKevin Wolf .supports_backing = true,
6189e2dd2737SKevin Wolf .bdrv_co_change_backing_file = qcow2_co_change_backing_file,
619020d97356SBlue Swirl
6191d34682cdSKevin Wolf .bdrv_refresh_limits = qcow2_refresh_limits,
61922b148f39SPaolo Bonzini .bdrv_co_invalidate_cache = qcow2_co_invalidate_cache,
6193ec6d8912SKevin Wolf .bdrv_inactivate = qcow2_inactivate,
619406d9260fSAnthony Liguori
61951bd0e2d1SChunyan Liu .create_opts = &qcow2_create_opts,
6196df373fb0SMaxim Levitsky .amend_opts = &qcow2_amend_opts,
61972654267cSMax Reitz .strong_runtime_opts = qcow2_strong_runtime_opts,
61988a2ce0bcSAlberto Garcia .mutable_opts = mutable_opts,
61992fd61638SPaolo Bonzini .bdrv_co_check = qcow2_co_check,
6200c282e1fdSChunyan Liu .bdrv_amend_options = qcow2_amend_options,
62018ea1613dSMaxim Levitsky .bdrv_co_amend = qcow2_co_amend,
6202279621c0SAlberto Garcia
6203279621c0SAlberto Garcia .bdrv_detach_aio_context = qcow2_detach_aio_context,
6204279621c0SAlberto Garcia .bdrv_attach_aio_context = qcow2_attach_aio_context,
62051b6b0562SVladimir Sementsov-Ogievskiy
6206ef893b5cSEric Blake .bdrv_supports_persistent_dirty_bitmap =
6207ef893b5cSEric Blake qcow2_supports_persistent_dirty_bitmap,
6208d2c3080eSVladimir Sementsov-Ogievskiy .bdrv_co_can_store_new_dirty_bitmap = qcow2_co_can_store_new_dirty_bitmap,
6209d2c3080eSVladimir Sementsov-Ogievskiy .bdrv_co_remove_persistent_dirty_bitmap =
6210d2c3080eSVladimir Sementsov-Ogievskiy qcow2_co_remove_persistent_dirty_bitmap,
621120d97356SBlue Swirl };
621220d97356SBlue Swirl
bdrv_qcow2_init(void)62135efa9d5aSAnthony Liguori static void bdrv_qcow2_init(void)
62145efa9d5aSAnthony Liguori {
62155efa9d5aSAnthony Liguori bdrv_register(&bdrv_qcow2);
62165efa9d5aSAnthony Liguori }
62175efa9d5aSAnthony Liguori
62185efa9d5aSAnthony Liguori block_init(bdrv_qcow2_init);
6219