1019d6b8fSAnthony Liguori /*
2019d6b8fSAnthony Liguori * Block driver for the QCOW version 2 format
3019d6b8fSAnthony Liguori *
4019d6b8fSAnthony Liguori * Copyright (c) 2004-2006 Fabrice Bellard
5019d6b8fSAnthony Liguori *
6019d6b8fSAnthony Liguori * Permission is hereby granted, free of charge, to any person obtaining a copy
7019d6b8fSAnthony Liguori * of this software and associated documentation files (the "Software"), to deal
8019d6b8fSAnthony Liguori * in the Software without restriction, including without limitation the rights
9019d6b8fSAnthony Liguori * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10019d6b8fSAnthony Liguori * copies of the Software, and to permit persons to whom the Software is
11019d6b8fSAnthony Liguori * furnished to do so, subject to the following conditions:
12019d6b8fSAnthony Liguori *
13019d6b8fSAnthony Liguori * The above copyright notice and this permission notice shall be included in
14019d6b8fSAnthony Liguori * all copies or substantial portions of the Software.
15019d6b8fSAnthony Liguori *
16019d6b8fSAnthony Liguori * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17019d6b8fSAnthony Liguori * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18019d6b8fSAnthony Liguori * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19019d6b8fSAnthony Liguori * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20019d6b8fSAnthony Liguori * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21019d6b8fSAnthony Liguori * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22019d6b8fSAnthony Liguori * THE SOFTWARE.
23019d6b8fSAnthony Liguori */
24e688df6bSMarkus Armbruster
2580c71a24SPeter Maydell #include "qemu/osdep.h"
262714f13dSVladimir Sementsov-Ogievskiy
27609f45eaSMax Reitz #include "block/qdict.h"
2823588797SKevin Wolf #include "sysemu/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"
356b673957SMarkus Armbruster #include "qapi/qmp/qdict.h"
366b673957SMarkus Armbruster #include "qapi/qmp/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"
47019d6b8fSAnthony Liguori
48019d6b8fSAnthony Liguori /*
49019d6b8fSAnthony Liguori Differences with QCOW:
50019d6b8fSAnthony Liguori
51019d6b8fSAnthony Liguori - Support for multiple incremental snapshots.
52019d6b8fSAnthony Liguori - Memory management by reference counts.
53019d6b8fSAnthony Liguori - Clusters which have a reference count of one have the bit
54019d6b8fSAnthony Liguori QCOW_OFLAG_COPIED to optimize write performance.
55019d6b8fSAnthony Liguori - Size of compressed clusters is stored in sectors to reduce bit usage
56019d6b8fSAnthony Liguori in the cluster offsets.
57019d6b8fSAnthony Liguori - Support for storing additional data (such as the VM state) in the
58019d6b8fSAnthony Liguori snapshots.
59019d6b8fSAnthony Liguori - If a backing store is used, the cluster size is not constrained
60019d6b8fSAnthony Liguori (could be backported to QCOW).
61019d6b8fSAnthony Liguori - L2 tables have always a size of one cluster.
62019d6b8fSAnthony Liguori */
63019d6b8fSAnthony Liguori
64019d6b8fSAnthony Liguori
65019d6b8fSAnthony Liguori typedef struct {
66019d6b8fSAnthony Liguori uint32_t magic;
67019d6b8fSAnthony Liguori 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
76019d6b8fSAnthony Liguori
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)
86019d6b8fSAnthony Liguori {
87019d6b8fSAnthony Liguori const QCowHeader *cow_header = (const void *)buf;
88019d6b8fSAnthony Liguori
89019d6b8fSAnthony Liguori if (buf_size >= sizeof(QCowHeader) &&
90019d6b8fSAnthony Liguori be32_to_cpu(cow_header->magic) == QCOW_MAGIC &&
916744cbabSKevin Wolf be32_to_cpu(cow_header->version) >= 2)
92019d6b8fSAnthony Liguori return 100;
93019d6b8fSAnthony Liguori else
94019d6b8fSAnthony Liguori return 0;
95019d6b8fSAnthony Liguori }
96019d6b8fSAnthony Liguori
97019d6b8fSAnthony Liguori
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
197019d6b8fSAnthony Liguori /*
198019d6b8fSAnthony Liguori * read qcow2 extension and fill bs
199019d6b8fSAnthony Liguori * start reading from start_offset
200019d6b8fSAnthony Liguori * finish reading upon magic of value 0 or when end_offset reached
201019d6b8fSAnthony Liguori * unknown magic is skipped (future extension this version knows nothing about)
202019d6b8fSAnthony Liguori * return 0 upon success, non-0 otherwise
203019d6b8fSAnthony Liguori */
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)
208019d6b8fSAnthony Liguori {
209ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque;
210019d6b8fSAnthony Liguori QCowExtension ext;
211019d6b8fSAnthony Liguori 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 }
218019d6b8fSAnthony Liguori
219019d6b8fSAnthony Liguori #ifdef DEBUG_EXT
2207c80ab3fSJes Sorensen printf("qcow2_read_extensions: start=%ld end=%ld\n", start_offset, end_offset);
221019d6b8fSAnthony Liguori #endif
222019d6b8fSAnthony Liguori offset = start_offset;
223019d6b8fSAnthony Liguori while (offset < end_offset) {
224019d6b8fSAnthony Liguori
225019d6b8fSAnthony Liguori #ifdef DEBUG_EXT
226019d6b8fSAnthony Liguori /* Sanity check */
227019d6b8fSAnthony Liguori if (offset > s->cluster_size)
2287c80ab3fSJes Sorensen printf("qcow2_read_extension: suspicious offset %lu\n", offset);
229019d6b8fSAnthony Liguori
2309b2260cbSDong Xu Wang printf("attempting to read extended header in offset %lu\n", offset);
231019d6b8fSAnthony Liguori #endif
232019d6b8fSAnthony Liguori
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);
237019d6b8fSAnthony Liguori return 1;
238019d6b8fSAnthony Liguori }
2393b698f52SPeter Maydell ext.magic = be32_to_cpu(ext.magic);
2403b698f52SPeter Maydell ext.len = be32_to_cpu(ext.len);
241019d6b8fSAnthony Liguori offset += sizeof(ext);
242019d6b8fSAnthony Liguori #ifdef DEBUG_EXT
243019d6b8fSAnthony Liguori printf("ext.magic = 0x%x\n", ext.magic);
244019d6b8fSAnthony Liguori #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
250019d6b8fSAnthony Liguori switch (ext.magic) {
2517c80ab3fSJes Sorensen case QCOW2_EXT_MAGIC_END:
252019d6b8fSAnthony Liguori return 0;
253019d6b8fSAnthony Liguori
2547c80ab3fSJes Sorensen case QCOW2_EXT_MAGIC_BACKING_FORMAT:
255019d6b8fSAnthony Liguori 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));
259019d6b8fSAnthony Liguori return 2;
260019d6b8fSAnthony Liguori }
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");
265019d6b8fSAnthony Liguori return 3;
2663ef6c40aSMax Reitz }
267019d6b8fSAnthony Liguori bs->backing_format[ext.len] = '\0';
268e4603fe1SKevin Wolf s->image_backing_format = g_strdup(bs->backing_format);
269019d6b8fSAnthony Liguori #ifdef DEBUG_EXT
270019d6b8fSAnthony Liguori printf("Qcow2: Got format extension %s\n", bs->backing_format);
271019d6b8fSAnthony Liguori #endif
272019d6b8fSAnthony Liguori break;
273019d6b8fSAnthony Liguori
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
435019d6b8fSAnthony Liguori 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 }
454019d6b8fSAnthony Liguori break;
455019d6b8fSAnthony Liguori }
456fd29b4bbSKevin Wolf
457fd29b4bbSKevin Wolf offset += ((ext.len + 7) & ~7);
458019d6b8fSAnthony Liguori }
459019d6b8fSAnthony Liguori
460019d6b8fSAnthony Liguori return 0;
461019d6b8fSAnthony Liguori }
462019d6b8fSAnthony Liguori
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 }
473019d6b8fSAnthony Liguori
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)
1321019d6b8fSAnthony Liguori {
1322bc520249SVladimir Sementsov-Ogievskiy ERRP_GUARD();
1323ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque;
13246d33e8e7SKevin Wolf unsigned int len, i;
13256d33e8e7SKevin Wolf int ret = 0;
1326019d6b8fSAnthony Liguori QCowHeader header;
1327019d6b8fSAnthony Liguori uint64_t ext_end;
13282cf7cfa1SKevin Wolf uint64_t l1_vm_state_index;
132988ddffaeSVladimir Sementsov-Ogievskiy bool update_header = false;
1330019d6b8fSAnthony Liguori
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");
1334019d6b8fSAnthony Liguori 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);
1350019d6b8fSAnthony Liguori
1351e8cdcec1SKevin Wolf if (header.magic != QCOW_MAGIC) {
13523ef6c40aSMax Reitz error_setg(errp, "Image is not in qcow2 format");
135376abe407SPaolo Bonzini ret = -EINVAL;
1354019d6b8fSAnthony Liguori 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
1497019d6b8fSAnthony Liguori 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));
1526019d6b8fSAnthony Liguori 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;
1531019d6b8fSAnthony Liguori s->csize_shift = (62 - (s->cluster_bits - 8));
1532019d6b8fSAnthony Liguori s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;
1533019d6b8fSAnthony Liguori s->cluster_offset_mask = (1LL << s->csize_shift) - 1;
15345dab2fadSKevin Wolf
1535019d6b8fSAnthony Liguori s->refcount_table_offset = header.refcount_table_offset;
1536019d6b8fSAnthony Liguori s->refcount_table_size =
1537019d6b8fSAnthony Liguori header.refcount_table_clusters << (s->cluster_bits - 3);
1538019d6b8fSAnthony Liguori
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
1571019d6b8fSAnthony Liguori /* 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 }
1578019d6b8fSAnthony Liguori 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
1589019d6b8fSAnthony Liguori /* the L1 table must contain at least enough entries to put
1590019d6b8fSAnthony Liguori 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;
1594019d6b8fSAnthony Liguori 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");
1608019d6b8fSAnthony Liguori goto fail;
16096d85a57eSJes Sorensen }
1610019d6b8fSAnthony Liguori for(i = 0;i < s->l1_size; i++) {
16113b698f52SPeter Maydell s->l1_table[i] = be64_to_cpu(s->l1_table[i]);
1612019d6b8fSAnthony Liguori }
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;
1622019d6b8fSAnthony Liguori
16236d85a57eSJes Sorensen ret = qcow2_refcount_init(bs);
16246d85a57eSJes Sorensen if (ret != 0) {
16253ef6c40aSMax Reitz error_setg_errno(errp, -ret, "Could not initialize refcount handling");
1626019d6b8fSAnthony Liguori goto fail;
16276d85a57eSJes Sorensen }
1628019d6b8fSAnthony Liguori
162972cf2d4fSBlue Swirl QLIST_INIT(&s->cluster_allocs);
16300b919faeSKevin Wolf QTAILQ_INIT(&s->discards);
1631f214978aSKevin Wolf
1632019d6b8fSAnthony Liguori /* 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;
1636019d6b8fSAnthony Liguori goto fail;
16376d85a57eSJes Sorensen }
1638019d6b8fSAnthony Liguori
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 }
17244652b8f3SDaniel P. Berrange } else if (!(flags & BDRV_O_NO_IO)) {
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
1732019d6b8fSAnthony Liguori /* read the backing file name */
1733019d6b8fSAnthony Liguori if (header.backing_file_offset != 0) {
1734019d6b8fSAnthony Liguori 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");
1747019d6b8fSAnthony Liguori 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 }
1762019d6b8fSAnthony Liguori }
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) {
1775019d6b8fSAnthony Liguori goto fail;
17766d85a57eSJes Sorensen }
17778bc584feSMax Reitz }
1778019d6b8fSAnthony Liguori
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
1883019d6b8fSAnthony Liguori #ifdef DEBUG_ALLOC
18846cbc3031SPhilipp Hahn {
18856cbc3031SPhilipp Hahn BdrvCheckResult result = {0};
1886b35278f7SStefan Hajnoczi qcow2_check_refcounts(bs, &result, 0);
18876cbc3031SPhilipp Hahn }
1888019d6b8fSAnthony Liguori #endif
1889ceb029cdSVladimir Sementsov-Ogievskiy
18906f13a316SVladimir Sementsov-Ogievskiy qemu_co_queue_init(&s->thread_task_queue);
1891ceb029cdSVladimir Sementsov-Ogievskiy
18926d85a57eSJes Sorensen return ret;
1893019d6b8fSAnthony Liguori
1894019d6b8fSAnthony Liguori 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();
189832a8aba3SKevin Wolf bdrv_co_unref_child(bs, s->data_file);
1899e3e31dc8SKevin Wolf bdrv_graph_co_rdlock();
1900808cf3cbSVladimir Sementsov-Ogievskiy s->data_file = NULL;
19010e8c08beSKevin Wolf }
19026744cbabSKevin Wolf g_free(s->unknown_header_fields);
190375bab85cSKevin Wolf cleanup_unknown_header_ext(bs);
1904ed6ccf0fSKevin Wolf qcow2_free_snapshots(bs);
1905ed6ccf0fSKevin Wolf qcow2_refcount_close(bs);
1906de82815dSKevin Wolf qemu_vfree(s->l1_table);
1907cf93980eSMax Reitz /* else pre-write overlap checks in cache_destroy may crash */
1908cf93980eSMax Reitz s->l1_table = NULL;
1909279621c0SAlberto Garcia cache_clean_timer_del(bs);
191029c1a730SKevin Wolf if (s->l2_table_cache) {
1911e64d4072SAlberto Garcia qcow2_cache_destroy(s->l2_table_cache);
191229c1a730SKevin Wolf }
1913c5a33ee9SPrasad Joshi if (s->refcount_block_cache) {
1914e64d4072SAlberto Garcia qcow2_cache_destroy(s->refcount_block_cache);
1915c5a33ee9SPrasad Joshi }
1916b25b387fSDaniel P. Berrange qcrypto_block_free(s->crypto);
1917b25b387fSDaniel P. Berrange qapi_free_QCryptoBlockOpenOptions(s->crypto_opts);
19186d85a57eSJes Sorensen return ret;
1919019d6b8fSAnthony Liguori }
1920019d6b8fSAnthony Liguori
19211fafcd93SPaolo Bonzini typedef struct QCow2OpenCo {
19221fafcd93SPaolo Bonzini BlockDriverState *bs;
19231fafcd93SPaolo Bonzini QDict *options;
19241fafcd93SPaolo Bonzini int flags;
19251fafcd93SPaolo Bonzini Error **errp;
19261fafcd93SPaolo Bonzini int ret;
19271fafcd93SPaolo Bonzini } QCow2OpenCo;
19281fafcd93SPaolo Bonzini
qcow2_open_entry(void * opaque)19291fafcd93SPaolo Bonzini static void coroutine_fn qcow2_open_entry(void *opaque)
19301fafcd93SPaolo Bonzini {
19311fafcd93SPaolo Bonzini QCow2OpenCo *qoc = opaque;
19321fafcd93SPaolo Bonzini BDRVQcow2State *s = qoc->bs->opaque;
19331fafcd93SPaolo Bonzini
19341a30b0f5SKevin Wolf GRAPH_RDLOCK_GUARD();
1935b9b10c35SKevin Wolf
19361fafcd93SPaolo Bonzini qemu_co_mutex_lock(&s->lock);
193706e9cd19SHanna Reitz qoc->ret = qcow2_do_open(qoc->bs, qoc->options, qoc->flags, true,
193806e9cd19SHanna Reitz qoc->errp);
19391fafcd93SPaolo Bonzini qemu_co_mutex_unlock(&s->lock);
1940aa269ff8SKevin Wolf
1941aa269ff8SKevin Wolf aio_wait_kick();
19421fafcd93SPaolo Bonzini }
19431fafcd93SPaolo Bonzini
qcow2_open(BlockDriverState * bs,QDict * options,int flags,Error ** errp)19444e4bf5c4SKevin Wolf static int qcow2_open(BlockDriverState *bs, QDict *options, int flags,
19454e4bf5c4SKevin Wolf Error **errp)
19464e4bf5c4SKevin Wolf {
19471fafcd93SPaolo Bonzini BDRVQcow2State *s = bs->opaque;
19481fafcd93SPaolo Bonzini QCow2OpenCo qoc = {
19491fafcd93SPaolo Bonzini .bs = bs,
19501fafcd93SPaolo Bonzini .options = options,
19511fafcd93SPaolo Bonzini .flags = flags,
19521fafcd93SPaolo Bonzini .errp = errp,
19531fafcd93SPaolo Bonzini .ret = -EINPROGRESS
19541fafcd93SPaolo Bonzini };
195583930780SVladimir Sementsov-Ogievskiy int ret;
19561fafcd93SPaolo Bonzini
195783930780SVladimir Sementsov-Ogievskiy ret = bdrv_open_file_child(NULL, options, "file", bs, errp);
195883930780SVladimir Sementsov-Ogievskiy if (ret < 0) {
195983930780SVladimir Sementsov-Ogievskiy return ret;
19604e4bf5c4SKevin Wolf }
19614e4bf5c4SKevin Wolf
19621fafcd93SPaolo Bonzini /* Initialise locks */
19631fafcd93SPaolo Bonzini qemu_co_mutex_init(&s->lock);
19641fafcd93SPaolo Bonzini
19651a30b0f5SKevin Wolf assert(!qemu_in_coroutine());
19664720cbeeSKevin Wolf assert(qemu_get_current_aio_context() == qemu_get_aio_context());
1967aa269ff8SKevin Wolf
1968aa269ff8SKevin Wolf aio_co_enter(bdrv_get_aio_context(bs),
1969aa269ff8SKevin Wolf qemu_coroutine_create(qcow2_open_entry, &qoc));
1970aa269ff8SKevin Wolf AIO_WAIT_WHILE_UNLOCKED(NULL, qoc.ret == -EINPROGRESS);
19711a30b0f5SKevin Wolf
19721fafcd93SPaolo Bonzini return qoc.ret;
19734e4bf5c4SKevin Wolf }
19744e4bf5c4SKevin Wolf
qcow2_refresh_limits(BlockDriverState * bs,Error ** errp)19753baca891SKevin Wolf static void qcow2_refresh_limits(BlockDriverState *bs, Error **errp)
1976d34682cdSKevin Wolf {
1977ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque;
1978d34682cdSKevin Wolf
1979a84178ccSEric Blake if (bs->encrypted) {
1980a84178ccSEric Blake /* Encryption works on a sector granularity */
19816f8f015cSAlberto Garcia bs->bl.request_alignment = qcrypto_block_get_sector_size(s->crypto);
1982a84178ccSEric Blake }
1983a6841a2dSAlberto Garcia bs->bl.pwrite_zeroes_alignment = s->subcluster_size;
1984ecdbead6SEric Blake bs->bl.pdiscard_alignment = s->cluster_size;
1985d34682cdSKevin Wolf }
1986d34682cdSKevin Wolf
19870bb79c97SKevin Wolf static int GRAPH_UNLOCKED
qcow2_reopen_prepare(BDRVReopenState * state,BlockReopenQueue * queue,Error ** errp)19880bb79c97SKevin Wolf qcow2_reopen_prepare(BDRVReopenState *state,BlockReopenQueue *queue,
19890bb79c97SKevin Wolf Error **errp)
199021d82ac9SJeff Cody {
1991bcfd86d6SKevin Wolf BDRVQcow2State *s = state->bs->opaque;
19925b0959a7SKevin Wolf Qcow2ReopenState *r;
19934c2e5f8fSKevin Wolf int ret;
19944c2e5f8fSKevin Wolf
19950bb79c97SKevin Wolf GLOBAL_STATE_CODE();
19960bb79c97SKevin Wolf GRAPH_RDLOCK_GUARD_MAINLOOP();
19970bb79c97SKevin Wolf
19985b0959a7SKevin Wolf r = g_new0(Qcow2ReopenState, 1);
19995b0959a7SKevin Wolf state->opaque = r;
20005b0959a7SKevin Wolf
20015b0959a7SKevin Wolf ret = qcow2_update_options_prepare(state->bs, r, state->options,
20025b0959a7SKevin Wolf state->flags, errp);
20035b0959a7SKevin Wolf if (ret < 0) {
20045b0959a7SKevin Wolf goto fail;
20055b0959a7SKevin Wolf }
20065b0959a7SKevin Wolf
20075b0959a7SKevin Wolf /* We need to write out any unwritten data if we reopen read-only. */
20084c2e5f8fSKevin Wolf if ((state->flags & BDRV_O_RDWR) == 0) {
2009169b8793SVladimir Sementsov-Ogievskiy ret = qcow2_reopen_bitmaps_ro(state->bs, errp);
2010169b8793SVladimir Sementsov-Ogievskiy if (ret < 0) {
2011169b8793SVladimir Sementsov-Ogievskiy goto fail;
2012169b8793SVladimir Sementsov-Ogievskiy }
2013169b8793SVladimir Sementsov-Ogievskiy
20144c2e5f8fSKevin Wolf ret = bdrv_flush(state->bs);
20154c2e5f8fSKevin Wolf if (ret < 0) {
20165b0959a7SKevin Wolf goto fail;
20174c2e5f8fSKevin Wolf }
20184c2e5f8fSKevin Wolf
20194c2e5f8fSKevin Wolf ret = qcow2_mark_clean(state->bs);
20204c2e5f8fSKevin Wolf if (ret < 0) {
20215b0959a7SKevin Wolf goto fail;
20224c2e5f8fSKevin Wolf }
20234c2e5f8fSKevin Wolf }
20244c2e5f8fSKevin Wolf
2025bcfd86d6SKevin Wolf /*
2026bcfd86d6SKevin Wolf * Without an external data file, s->data_file points to the same BdrvChild
2027bcfd86d6SKevin Wolf * as bs->file. It needs to be resynced after reopen because bs->file may
2028bcfd86d6SKevin Wolf * be changed. We can't use it in the meantime.
2029bcfd86d6SKevin Wolf */
2030bcfd86d6SKevin Wolf if (!has_data_file(state->bs)) {
2031bcfd86d6SKevin Wolf assert(s->data_file == state->bs->file);
2032bcfd86d6SKevin Wolf s->data_file = NULL;
2033bcfd86d6SKevin Wolf }
2034bcfd86d6SKevin Wolf
203521d82ac9SJeff Cody return 0;
20365b0959a7SKevin Wolf
20375b0959a7SKevin Wolf fail:
20385b0959a7SKevin Wolf qcow2_update_options_abort(state->bs, r);
20395b0959a7SKevin Wolf g_free(r);
20405b0959a7SKevin Wolf return ret;
20415b0959a7SKevin Wolf }
20425b0959a7SKevin Wolf
qcow2_reopen_commit(BDRVReopenState * state)20435b0959a7SKevin Wolf static void qcow2_reopen_commit(BDRVReopenState *state)
20445b0959a7SKevin Wolf {
2045bcfd86d6SKevin Wolf BDRVQcow2State *s = state->bs->opaque;
2046bcfd86d6SKevin Wolf
20478f897341SKevin Wolf GRAPH_RDLOCK_GUARD_MAINLOOP();
20488f897341SKevin Wolf
20495b0959a7SKevin Wolf qcow2_update_options_commit(state->bs, state->opaque);
2050bcfd86d6SKevin Wolf if (!s->data_file) {
2051bcfd86d6SKevin Wolf /*
2052bcfd86d6SKevin Wolf * If we don't have an external data file, s->data_file was cleared by
2053bcfd86d6SKevin Wolf * qcow2_reopen_prepare() and needs to be updated.
2054bcfd86d6SKevin Wolf */
2055bcfd86d6SKevin Wolf s->data_file = state->bs->file;
2056bcfd86d6SKevin Wolf }
205765eb7c85SPeter Krempa g_free(state->opaque);
205865eb7c85SPeter Krempa }
205965eb7c85SPeter Krempa
qcow2_reopen_commit_post(BDRVReopenState * state)206065eb7c85SPeter Krempa static void qcow2_reopen_commit_post(BDRVReopenState *state)
206165eb7c85SPeter Krempa {
20620bb79c97SKevin Wolf GRAPH_RDLOCK_GUARD_MAINLOOP();
20630bb79c97SKevin Wolf
20644dd09f62SVladimir Sementsov-Ogievskiy if (state->flags & BDRV_O_RDWR) {
20654dd09f62SVladimir Sementsov-Ogievskiy Error *local_err = NULL;
20664dd09f62SVladimir Sementsov-Ogievskiy
20674dd09f62SVladimir Sementsov-Ogievskiy if (qcow2_reopen_bitmaps_rw(state->bs, &local_err) < 0) {
20684dd09f62SVladimir Sementsov-Ogievskiy /*
20694dd09f62SVladimir Sementsov-Ogievskiy * This is not fatal, bitmaps just left read-only, so all following
20704dd09f62SVladimir Sementsov-Ogievskiy * writes will fail. User can remove read-only bitmaps to unblock
20714dd09f62SVladimir Sementsov-Ogievskiy * writes or retry reopen.
20724dd09f62SVladimir Sementsov-Ogievskiy */
20734dd09f62SVladimir Sementsov-Ogievskiy error_reportf_err(local_err,
20744dd09f62SVladimir Sementsov-Ogievskiy "%s: Failed to make dirty bitmaps writable: ",
20754dd09f62SVladimir Sementsov-Ogievskiy bdrv_get_node_name(state->bs));
20764dd09f62SVladimir Sementsov-Ogievskiy }
20774dd09f62SVladimir Sementsov-Ogievskiy }
20785b0959a7SKevin Wolf }
20795b0959a7SKevin Wolf
qcow2_reopen_abort(BDRVReopenState * state)20805b0959a7SKevin Wolf static void qcow2_reopen_abort(BDRVReopenState *state)
20815b0959a7SKevin Wolf {
2082bcfd86d6SKevin Wolf BDRVQcow2State *s = state->bs->opaque;
2083bcfd86d6SKevin Wolf
20848f897341SKevin Wolf GRAPH_RDLOCK_GUARD_MAINLOOP();
20858f897341SKevin Wolf
2086bcfd86d6SKevin Wolf if (!s->data_file) {
2087bcfd86d6SKevin Wolf /*
2088bcfd86d6SKevin Wolf * If we don't have an external data file, s->data_file was cleared by
2089bcfd86d6SKevin Wolf * qcow2_reopen_prepare() and needs to be restored.
2090bcfd86d6SKevin Wolf */
2091bcfd86d6SKevin Wolf s->data_file = state->bs->file;
2092bcfd86d6SKevin Wolf }
20935b0959a7SKevin Wolf qcow2_update_options_abort(state->bs, state->opaque);
20945b0959a7SKevin Wolf g_free(state->opaque);
209521d82ac9SJeff Cody }
209621d82ac9SJeff Cody
qcow2_join_options(QDict * options,QDict * old_options)20975365f44dSKevin Wolf static void qcow2_join_options(QDict *options, QDict *old_options)
20985365f44dSKevin Wolf {
20995365f44dSKevin Wolf bool has_new_overlap_template =
21005365f44dSKevin Wolf qdict_haskey(options, QCOW2_OPT_OVERLAP) ||
21015365f44dSKevin Wolf qdict_haskey(options, QCOW2_OPT_OVERLAP_TEMPLATE);
21025365f44dSKevin Wolf bool has_new_total_cache_size =
21035365f44dSKevin Wolf qdict_haskey(options, QCOW2_OPT_CACHE_SIZE);
21045365f44dSKevin Wolf bool has_all_cache_options;
21055365f44dSKevin Wolf
21065365f44dSKevin Wolf /* New overlap template overrides all old overlap options */
21075365f44dSKevin Wolf if (has_new_overlap_template) {
21085365f44dSKevin Wolf qdict_del(old_options, QCOW2_OPT_OVERLAP);
21095365f44dSKevin Wolf qdict_del(old_options, QCOW2_OPT_OVERLAP_TEMPLATE);
21105365f44dSKevin Wolf qdict_del(old_options, QCOW2_OPT_OVERLAP_MAIN_HEADER);
21115365f44dSKevin Wolf qdict_del(old_options, QCOW2_OPT_OVERLAP_ACTIVE_L1);
21125365f44dSKevin Wolf qdict_del(old_options, QCOW2_OPT_OVERLAP_ACTIVE_L2);
21135365f44dSKevin Wolf qdict_del(old_options, QCOW2_OPT_OVERLAP_REFCOUNT_TABLE);
21145365f44dSKevin Wolf qdict_del(old_options, QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK);
21155365f44dSKevin Wolf qdict_del(old_options, QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE);
21165365f44dSKevin Wolf qdict_del(old_options, QCOW2_OPT_OVERLAP_INACTIVE_L1);
21175365f44dSKevin Wolf qdict_del(old_options, QCOW2_OPT_OVERLAP_INACTIVE_L2);
21185365f44dSKevin Wolf }
21195365f44dSKevin Wolf
21205365f44dSKevin Wolf /* New total cache size overrides all old options */
21215365f44dSKevin Wolf if (qdict_haskey(options, QCOW2_OPT_CACHE_SIZE)) {
21225365f44dSKevin Wolf qdict_del(old_options, QCOW2_OPT_L2_CACHE_SIZE);
21235365f44dSKevin Wolf qdict_del(old_options, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
21245365f44dSKevin Wolf }
21255365f44dSKevin Wolf
21265365f44dSKevin Wolf qdict_join(options, old_options, false);
21275365f44dSKevin Wolf
21285365f44dSKevin Wolf /*
21295365f44dSKevin Wolf * If after merging all cache size options are set, an old total size is
21305365f44dSKevin Wolf * overwritten. Do keep all options, however, if all three are new. The
21315365f44dSKevin Wolf * resulting error message is what we want to happen.
21325365f44dSKevin Wolf */
21335365f44dSKevin Wolf has_all_cache_options =
21345365f44dSKevin Wolf qdict_haskey(options, QCOW2_OPT_CACHE_SIZE) ||
21355365f44dSKevin Wolf qdict_haskey(options, QCOW2_OPT_L2_CACHE_SIZE) ||
21365365f44dSKevin Wolf qdict_haskey(options, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
21375365f44dSKevin Wolf
21385365f44dSKevin Wolf if (has_all_cache_options && !has_new_total_cache_size) {
21395365f44dSKevin Wolf qdict_del(options, QCOW2_OPT_CACHE_SIZE);
21405365f44dSKevin Wolf }
21415365f44dSKevin Wolf }
21425365f44dSKevin Wolf
21430050c163SKevin Wolf static int coroutine_fn GRAPH_RDLOCK
qcow2_co_block_status(BlockDriverState * bs,bool want_zero,int64_t offset,int64_t count,int64_t * pnum,int64_t * map,BlockDriverState ** file)21440050c163SKevin Wolf qcow2_co_block_status(BlockDriverState *bs, bool want_zero, int64_t offset,
21450050c163SKevin Wolf int64_t count, int64_t *pnum, int64_t *map,
2146a320fb04SEric Blake BlockDriverState **file)
2147019d6b8fSAnthony Liguori {
2148ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque;
2149388e5816SAlberto Garcia uint64_t host_offset;
2150ecfe1863SKevin Wolf unsigned int bytes;
215110dabdc5SAlberto Garcia QCow2SubclusterType type;
215274e60fb5SAlberto Garcia int ret, status = 0;
2153019d6b8fSAnthony Liguori
21545e978550SKevin Wolf qemu_co_mutex_lock(&s->lock);
21555e978550SKevin Wolf
215669f47505SVladimir Sementsov-Ogievskiy if (!s->metadata_preallocation_checked) {
215769f47505SVladimir Sementsov-Ogievskiy ret = qcow2_detect_metadata_preallocation(bs);
215869f47505SVladimir Sementsov-Ogievskiy s->metadata_preallocation = (ret == 1);
215969f47505SVladimir Sementsov-Ogievskiy s->metadata_preallocation_checked = true;
216069f47505SVladimir Sementsov-Ogievskiy }
216169f47505SVladimir Sementsov-Ogievskiy
2162a320fb04SEric Blake bytes = MIN(INT_MAX, count);
2163ca4a0bb8SAlberto Garcia ret = qcow2_get_host_offset(bs, offset, &bytes, &host_offset, &type);
2164f8a2e5e3SStefan Hajnoczi qemu_co_mutex_unlock(&s->lock);
21651c46efaaSKevin Wolf if (ret < 0) {
2166d663640cSPaolo Bonzini return ret;
21671c46efaaSKevin Wolf }
2168019d6b8fSAnthony Liguori
2169a320fb04SEric Blake *pnum = bytes;
2170ecfe1863SKevin Wolf
217110dabdc5SAlberto Garcia if ((type == QCOW2_SUBCLUSTER_NORMAL ||
217297490a14SAlberto Garcia type == QCOW2_SUBCLUSTER_ZERO_ALLOC ||
217397490a14SAlberto Garcia type == QCOW2_SUBCLUSTER_UNALLOCATED_ALLOC) && !s->crypto) {
2174388e5816SAlberto Garcia *map = host_offset;
217537be1403SKevin Wolf *file = s->data_file->bs;
2176a320fb04SEric Blake status |= BDRV_BLOCK_OFFSET_VALID;
21774bc74be9SPaolo Bonzini }
217810dabdc5SAlberto Garcia if (type == QCOW2_SUBCLUSTER_ZERO_PLAIN ||
217910dabdc5SAlberto Garcia type == QCOW2_SUBCLUSTER_ZERO_ALLOC) {
21804bc74be9SPaolo Bonzini status |= BDRV_BLOCK_ZERO;
218197490a14SAlberto Garcia } else if (type != QCOW2_SUBCLUSTER_UNALLOCATED_PLAIN &&
218297490a14SAlberto Garcia type != QCOW2_SUBCLUSTER_UNALLOCATED_ALLOC) {
21834bc74be9SPaolo Bonzini status |= BDRV_BLOCK_DATA;
21844bc74be9SPaolo Bonzini }
218569f47505SVladimir Sementsov-Ogievskiy if (s->metadata_preallocation && (status & BDRV_BLOCK_DATA) &&
218669f47505SVladimir Sementsov-Ogievskiy (status & BDRV_BLOCK_OFFSET_VALID))
218769f47505SVladimir Sementsov-Ogievskiy {
218869f47505SVladimir Sementsov-Ogievskiy status |= BDRV_BLOCK_RECURSE;
218969f47505SVladimir Sementsov-Ogievskiy }
219028482891SAndrey Drobyshev via if (type == QCOW2_SUBCLUSTER_COMPRESSED) {
219128482891SAndrey Drobyshev via status |= BDRV_BLOCK_COMPRESSED;
219228482891SAndrey Drobyshev via }
21934bc74be9SPaolo Bonzini return status;
2194019d6b8fSAnthony Liguori }
2195019d6b8fSAnthony Liguori
21967b1fb72eSKevin Wolf static int coroutine_fn GRAPH_RDLOCK
qcow2_handle_l2meta(BlockDriverState * bs,QCowL2Meta ** pl2meta,bool link_l2)21977b1fb72eSKevin Wolf qcow2_handle_l2meta(BlockDriverState *bs, QCowL2Meta **pl2meta, bool link_l2)
2198fd9fcd37SFam Zheng {
2199fd9fcd37SFam Zheng int ret = 0;
2200fd9fcd37SFam Zheng QCowL2Meta *l2meta = *pl2meta;
2201fd9fcd37SFam Zheng
2202fd9fcd37SFam Zheng while (l2meta != NULL) {
2203fd9fcd37SFam Zheng QCowL2Meta *next;
2204fd9fcd37SFam Zheng
2205354d930dSFam Zheng if (link_l2) {
2206fd9fcd37SFam Zheng ret = qcow2_alloc_cluster_link_l2(bs, l2meta);
2207fd9fcd37SFam Zheng if (ret) {
2208fd9fcd37SFam Zheng goto out;
2209fd9fcd37SFam Zheng }
22108b24cd14SKevin Wolf } else {
22118b24cd14SKevin Wolf qcow2_alloc_cluster_abort(bs, l2meta);
2212fd9fcd37SFam Zheng }
2213fd9fcd37SFam Zheng
2214fd9fcd37SFam Zheng /* Take the request off the list of running requests */
2215fd9fcd37SFam Zheng QLIST_REMOVE(l2meta, next_in_flight);
2216fd9fcd37SFam Zheng
2217fd9fcd37SFam Zheng qemu_co_queue_restart_all(&l2meta->dependent_requests);
2218fd9fcd37SFam Zheng
2219fd9fcd37SFam Zheng next = l2meta->next;
2220fd9fcd37SFam Zheng g_free(l2meta);
2221fd9fcd37SFam Zheng l2meta = next;
2222fd9fcd37SFam Zheng }
2223fd9fcd37SFam Zheng out:
2224fd9fcd37SFam Zheng *pl2meta = l2meta;
2225fd9fcd37SFam Zheng return ret;
2226fd9fcd37SFam Zheng }
2227fd9fcd37SFam Zheng
2228b9b10c35SKevin 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)222988f468e5SVladimir Sementsov-Ogievskiy qcow2_co_preadv_encrypted(BlockDriverState *bs,
22309c4269d5SAlberto Garcia uint64_t host_offset,
223188f468e5SVladimir Sementsov-Ogievskiy uint64_t offset,
223288f468e5SVladimir Sementsov-Ogievskiy uint64_t bytes,
223388f468e5SVladimir Sementsov-Ogievskiy QEMUIOVector *qiov,
223488f468e5SVladimir Sementsov-Ogievskiy uint64_t qiov_offset)
223588f468e5SVladimir Sementsov-Ogievskiy {
223688f468e5SVladimir Sementsov-Ogievskiy int ret;
223788f468e5SVladimir Sementsov-Ogievskiy BDRVQcow2State *s = bs->opaque;
223888f468e5SVladimir Sementsov-Ogievskiy uint8_t *buf;
223988f468e5SVladimir Sementsov-Ogievskiy
224088f468e5SVladimir Sementsov-Ogievskiy assert(bs->encrypted && s->crypto);
224188f468e5SVladimir Sementsov-Ogievskiy assert(bytes <= QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
224288f468e5SVladimir Sementsov-Ogievskiy
224388f468e5SVladimir Sementsov-Ogievskiy /*
224488f468e5SVladimir Sementsov-Ogievskiy * For encrypted images, read everything into a temporary
224588f468e5SVladimir Sementsov-Ogievskiy * contiguous buffer on which the AES functions can work.
224688f468e5SVladimir Sementsov-Ogievskiy * Also, decryption in a separate buffer is better as it
224788f468e5SVladimir Sementsov-Ogievskiy * prevents the guest from learning information about the
224888f468e5SVladimir Sementsov-Ogievskiy * encrypted nature of the virtual disk.
224988f468e5SVladimir Sementsov-Ogievskiy */
225088f468e5SVladimir Sementsov-Ogievskiy
225188f468e5SVladimir Sementsov-Ogievskiy buf = qemu_try_blockalign(s->data_file->bs, bytes);
225288f468e5SVladimir Sementsov-Ogievskiy if (buf == NULL) {
225388f468e5SVladimir Sementsov-Ogievskiy return -ENOMEM;
225488f468e5SVladimir Sementsov-Ogievskiy }
225588f468e5SVladimir Sementsov-Ogievskiy
225617362398SPaolo Bonzini BLKDBG_CO_EVENT(bs->file, BLKDBG_READ_AIO);
22579c4269d5SAlberto Garcia ret = bdrv_co_pread(s->data_file, host_offset, bytes, buf, 0);
225888f468e5SVladimir Sementsov-Ogievskiy if (ret < 0) {
225988f468e5SVladimir Sementsov-Ogievskiy goto fail;
226088f468e5SVladimir Sementsov-Ogievskiy }
226188f468e5SVladimir Sementsov-Ogievskiy
22629c4269d5SAlberto Garcia if (qcow2_co_decrypt(bs, host_offset, offset, buf, bytes) < 0)
226388f468e5SVladimir Sementsov-Ogievskiy {
226488f468e5SVladimir Sementsov-Ogievskiy ret = -EIO;
226588f468e5SVladimir Sementsov-Ogievskiy goto fail;
226688f468e5SVladimir Sementsov-Ogievskiy }
226788f468e5SVladimir Sementsov-Ogievskiy qemu_iovec_from_buf(qiov, qiov_offset, buf, bytes);
226888f468e5SVladimir Sementsov-Ogievskiy
226988f468e5SVladimir Sementsov-Ogievskiy fail:
227088f468e5SVladimir Sementsov-Ogievskiy qemu_vfree(buf);
227188f468e5SVladimir Sementsov-Ogievskiy
227288f468e5SVladimir Sementsov-Ogievskiy return ret;
227388f468e5SVladimir Sementsov-Ogievskiy }
227488f468e5SVladimir Sementsov-Ogievskiy
2275d710cf57SVladimir Sementsov-Ogievskiy typedef struct Qcow2AioTask {
2276d710cf57SVladimir Sementsov-Ogievskiy AioTask task;
2277d710cf57SVladimir Sementsov-Ogievskiy
2278d710cf57SVladimir Sementsov-Ogievskiy BlockDriverState *bs;
227910dabdc5SAlberto Garcia QCow2SubclusterType subcluster_type; /* only for read */
22809a3978a4SVladimir Sementsov-Ogievskiy uint64_t host_offset; /* or l2_entry for compressed read */
2281d710cf57SVladimir Sementsov-Ogievskiy uint64_t offset;
2282d710cf57SVladimir Sementsov-Ogievskiy uint64_t bytes;
2283d710cf57SVladimir Sementsov-Ogievskiy QEMUIOVector *qiov;
2284d710cf57SVladimir Sementsov-Ogievskiy uint64_t qiov_offset;
2285d710cf57SVladimir Sementsov-Ogievskiy QCowL2Meta *l2meta; /* only for write */
2286d710cf57SVladimir Sementsov-Ogievskiy } Qcow2AioTask;
2287d710cf57SVladimir Sementsov-Ogievskiy
2288d710cf57SVladimir 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)2289d710cf57SVladimir Sementsov-Ogievskiy static coroutine_fn int qcow2_add_task(BlockDriverState *bs,
2290d710cf57SVladimir Sementsov-Ogievskiy AioTaskPool *pool,
2291d710cf57SVladimir Sementsov-Ogievskiy AioTaskFunc func,
229210dabdc5SAlberto Garcia QCow2SubclusterType subcluster_type,
22939c4269d5SAlberto Garcia uint64_t host_offset,
2294d710cf57SVladimir Sementsov-Ogievskiy uint64_t offset,
2295d710cf57SVladimir Sementsov-Ogievskiy uint64_t bytes,
2296d710cf57SVladimir Sementsov-Ogievskiy QEMUIOVector *qiov,
2297d710cf57SVladimir Sementsov-Ogievskiy size_t qiov_offset,
2298d710cf57SVladimir Sementsov-Ogievskiy QCowL2Meta *l2meta)
2299d710cf57SVladimir Sementsov-Ogievskiy {
2300d710cf57SVladimir Sementsov-Ogievskiy Qcow2AioTask local_task;
2301d710cf57SVladimir Sementsov-Ogievskiy Qcow2AioTask *task = pool ? g_new(Qcow2AioTask, 1) : &local_task;
2302d710cf57SVladimir Sementsov-Ogievskiy
2303d710cf57SVladimir Sementsov-Ogievskiy *task = (Qcow2AioTask) {
2304d710cf57SVladimir Sementsov-Ogievskiy .task.func = func,
2305d710cf57SVladimir Sementsov-Ogievskiy .bs = bs,
230610dabdc5SAlberto Garcia .subcluster_type = subcluster_type,
2307d710cf57SVladimir Sementsov-Ogievskiy .qiov = qiov,
23089c4269d5SAlberto Garcia .host_offset = host_offset,
2309d710cf57SVladimir Sementsov-Ogievskiy .offset = offset,
2310d710cf57SVladimir Sementsov-Ogievskiy .bytes = bytes,
2311d710cf57SVladimir Sementsov-Ogievskiy .qiov_offset = qiov_offset,
2312d710cf57SVladimir Sementsov-Ogievskiy .l2meta = l2meta,
2313d710cf57SVladimir Sementsov-Ogievskiy };
2314d710cf57SVladimir Sementsov-Ogievskiy
2315d710cf57SVladimir Sementsov-Ogievskiy trace_qcow2_add_task(qemu_coroutine_self(), bs, pool,
2316d710cf57SVladimir Sementsov-Ogievskiy func == qcow2_co_preadv_task_entry ? "read" : "write",
231710dabdc5SAlberto Garcia subcluster_type, host_offset, offset, bytes,
2318d710cf57SVladimir Sementsov-Ogievskiy qiov, qiov_offset);
2319d710cf57SVladimir Sementsov-Ogievskiy
2320d710cf57SVladimir Sementsov-Ogievskiy if (!pool) {
2321d710cf57SVladimir Sementsov-Ogievskiy return func(&task->task);
2322d710cf57SVladimir Sementsov-Ogievskiy }
2323d710cf57SVladimir Sementsov-Ogievskiy
2324d710cf57SVladimir Sementsov-Ogievskiy aio_task_pool_start_task(pool, &task->task);
2325d710cf57SVladimir Sementsov-Ogievskiy
2326d710cf57SVladimir Sementsov-Ogievskiy return 0;
2327d710cf57SVladimir Sementsov-Ogievskiy }
2328d710cf57SVladimir Sementsov-Ogievskiy
2329b9b10c35SKevin 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)2330b9b10c35SKevin Wolf qcow2_co_preadv_task(BlockDriverState *bs, QCow2SubclusterType subc_type,
2331b9b10c35SKevin Wolf uint64_t host_offset, uint64_t offset, uint64_t bytes,
2332b9b10c35SKevin Wolf QEMUIOVector *qiov, size_t qiov_offset)
233388f468e5SVladimir Sementsov-Ogievskiy {
233488f468e5SVladimir Sementsov-Ogievskiy BDRVQcow2State *s = bs->opaque;
233588f468e5SVladimir Sementsov-Ogievskiy
233610dabdc5SAlberto Garcia switch (subc_type) {
233710dabdc5SAlberto Garcia case QCOW2_SUBCLUSTER_ZERO_PLAIN:
233810dabdc5SAlberto Garcia case QCOW2_SUBCLUSTER_ZERO_ALLOC:
233988f468e5SVladimir Sementsov-Ogievskiy /* Both zero types are handled in qcow2_co_preadv_part */
234088f468e5SVladimir Sementsov-Ogievskiy g_assert_not_reached();
234188f468e5SVladimir Sementsov-Ogievskiy
234210dabdc5SAlberto Garcia case QCOW2_SUBCLUSTER_UNALLOCATED_PLAIN:
234397490a14SAlberto Garcia case QCOW2_SUBCLUSTER_UNALLOCATED_ALLOC:
234488f468e5SVladimir Sementsov-Ogievskiy assert(bs->backing); /* otherwise handled in qcow2_co_preadv_part */
234588f468e5SVladimir Sementsov-Ogievskiy
234617362398SPaolo Bonzini BLKDBG_CO_EVENT(bs->file, BLKDBG_READ_BACKING_AIO);
234788f468e5SVladimir Sementsov-Ogievskiy return bdrv_co_preadv_part(bs->backing, offset, bytes,
234888f468e5SVladimir Sementsov-Ogievskiy qiov, qiov_offset, 0);
234988f468e5SVladimir Sementsov-Ogievskiy
235010dabdc5SAlberto Garcia case QCOW2_SUBCLUSTER_COMPRESSED:
23519c4269d5SAlberto Garcia return qcow2_co_preadv_compressed(bs, host_offset,
235288f468e5SVladimir Sementsov-Ogievskiy offset, bytes, qiov, qiov_offset);
235388f468e5SVladimir Sementsov-Ogievskiy
235410dabdc5SAlberto Garcia case QCOW2_SUBCLUSTER_NORMAL:
235588f468e5SVladimir Sementsov-Ogievskiy if (bs->encrypted) {
23569c4269d5SAlberto Garcia return qcow2_co_preadv_encrypted(bs, host_offset,
235788f468e5SVladimir Sementsov-Ogievskiy offset, bytes, qiov, qiov_offset);
235888f468e5SVladimir Sementsov-Ogievskiy }
235988f468e5SVladimir Sementsov-Ogievskiy
236017362398SPaolo Bonzini BLKDBG_CO_EVENT(bs->file, BLKDBG_READ_AIO);
23619c4269d5SAlberto Garcia return bdrv_co_preadv_part(s->data_file, host_offset,
236288f468e5SVladimir Sementsov-Ogievskiy bytes, qiov, qiov_offset, 0);
236388f468e5SVladimir Sementsov-Ogievskiy
236488f468e5SVladimir Sementsov-Ogievskiy default:
236588f468e5SVladimir Sementsov-Ogievskiy g_assert_not_reached();
236688f468e5SVladimir Sementsov-Ogievskiy }
236788f468e5SVladimir Sementsov-Ogievskiy
236888f468e5SVladimir Sementsov-Ogievskiy g_assert_not_reached();
236988f468e5SVladimir Sementsov-Ogievskiy }
237088f468e5SVladimir Sementsov-Ogievskiy
2371b9b10c35SKevin Wolf /*
2372b9b10c35SKevin Wolf * This function can count as GRAPH_RDLOCK because qcow2_co_preadv_part() holds
2373b9b10c35SKevin Wolf * the graph lock and keeps it until this coroutine has terminated.
2374b9b10c35SKevin Wolf */
qcow2_co_preadv_task_entry(AioTask * task)2375b9b10c35SKevin Wolf static int coroutine_fn GRAPH_RDLOCK qcow2_co_preadv_task_entry(AioTask *task)
2376d710cf57SVladimir Sementsov-Ogievskiy {
2377d710cf57SVladimir Sementsov-Ogievskiy Qcow2AioTask *t = container_of(task, Qcow2AioTask, task);
2378d710cf57SVladimir Sementsov-Ogievskiy
2379d710cf57SVladimir Sementsov-Ogievskiy assert(!t->l2meta);
2380d710cf57SVladimir Sementsov-Ogievskiy
238110dabdc5SAlberto Garcia return qcow2_co_preadv_task(t->bs, t->subcluster_type,
238210dabdc5SAlberto Garcia t->host_offset, t->offset, t->bytes,
238310dabdc5SAlberto Garcia t->qiov, t->qiov_offset);
2384d710cf57SVladimir Sementsov-Ogievskiy }
2385d710cf57SVladimir Sementsov-Ogievskiy
2386b9b10c35SKevin 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)2387b9b10c35SKevin Wolf qcow2_co_preadv_part(BlockDriverState *bs, int64_t offset, int64_t bytes,
2388b9b10c35SKevin Wolf QEMUIOVector *qiov, size_t qiov_offset,
2389f7ef38ddSVladimir Sementsov-Ogievskiy BdrvRequestFlags flags)
2390019d6b8fSAnthony Liguori {
2391ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque;
2392d710cf57SVladimir Sementsov-Ogievskiy int ret = 0;
2393ecfe1863SKevin Wolf unsigned int cur_bytes; /* number of bytes in current iteration */
2394388e5816SAlberto Garcia uint64_t host_offset = 0;
239510dabdc5SAlberto Garcia QCow2SubclusterType type;
2396d710cf57SVladimir Sementsov-Ogievskiy AioTaskPool *aio = NULL;
2397019d6b8fSAnthony Liguori
2398d710cf57SVladimir Sementsov-Ogievskiy while (bytes != 0 && aio_task_pool_status(aio) == 0) {
2399faf575c1SFrediano Ziglio /* prepare next request */
2400ecfe1863SKevin Wolf cur_bytes = MIN(bytes, INT_MAX);
2401b25b387fSDaniel P. Berrange if (s->crypto) {
2402ecfe1863SKevin Wolf cur_bytes = MIN(cur_bytes,
2403ecfe1863SKevin Wolf QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
2404bd28f835SKevin Wolf }
2405bd28f835SKevin Wolf
2406f24196d3SVladimir Sementsov-Ogievskiy qemu_co_mutex_lock(&s->lock);
2407ca4a0bb8SAlberto Garcia ret = qcow2_get_host_offset(bs, offset, &cur_bytes,
2408ca4a0bb8SAlberto Garcia &host_offset, &type);
2409f24196d3SVladimir Sementsov-Ogievskiy qemu_co_mutex_unlock(&s->lock);
24101c46efaaSKevin Wolf if (ret < 0) {
2411d710cf57SVladimir Sementsov-Ogievskiy goto out;
24121c46efaaSKevin Wolf }
24131c46efaaSKevin Wolf
241410dabdc5SAlberto Garcia if (type == QCOW2_SUBCLUSTER_ZERO_PLAIN ||
241510dabdc5SAlberto Garcia type == QCOW2_SUBCLUSTER_ZERO_ALLOC ||
241697490a14SAlberto Garcia (type == QCOW2_SUBCLUSTER_UNALLOCATED_PLAIN && !bs->backing) ||
241797490a14SAlberto Garcia (type == QCOW2_SUBCLUSTER_UNALLOCATED_ALLOC && !bs->backing))
241888f468e5SVladimir Sementsov-Ogievskiy {
241988f468e5SVladimir Sementsov-Ogievskiy qemu_iovec_memset(qiov, qiov_offset, 0, cur_bytes);
2420019d6b8fSAnthony Liguori } else {
2421d710cf57SVladimir Sementsov-Ogievskiy if (!aio && cur_bytes != bytes) {
2422d710cf57SVladimir Sementsov-Ogievskiy aio = aio_task_pool_new(QCOW2_MAX_WORKERS);
2423d710cf57SVladimir Sementsov-Ogievskiy }
2424ca4a0bb8SAlberto Garcia ret = qcow2_add_task(bs, aio, qcow2_co_preadv_task_entry, type,
24259c4269d5SAlberto Garcia host_offset, offset, cur_bytes,
2426d710cf57SVladimir Sementsov-Ogievskiy qiov, qiov_offset, NULL);
24278af36488SKevin Wolf if (ret < 0) {
2428d710cf57SVladimir Sementsov-Ogievskiy goto out;
24298af36488SKevin Wolf }
2430faf575c1SFrediano Ziglio }
2431faf575c1SFrediano Ziglio
2432ecfe1863SKevin Wolf bytes -= cur_bytes;
2433ecfe1863SKevin Wolf offset += cur_bytes;
2434df893d25SVladimir Sementsov-Ogievskiy qiov_offset += cur_bytes;
24355ebaa27eSFrediano Ziglio }
2436019d6b8fSAnthony Liguori
2437d710cf57SVladimir Sementsov-Ogievskiy out:
2438d710cf57SVladimir Sementsov-Ogievskiy if (aio) {
2439d710cf57SVladimir Sementsov-Ogievskiy aio_task_pool_wait_all(aio);
2440d710cf57SVladimir Sementsov-Ogievskiy if (ret == 0) {
2441d710cf57SVladimir Sementsov-Ogievskiy ret = aio_task_pool_status(aio);
2442d710cf57SVladimir Sementsov-Ogievskiy }
2443d710cf57SVladimir Sementsov-Ogievskiy g_free(aio);
2444d710cf57SVladimir Sementsov-Ogievskiy }
2445d710cf57SVladimir Sementsov-Ogievskiy
2446d710cf57SVladimir Sementsov-Ogievskiy return ret;
2447019d6b8fSAnthony Liguori }
2448019d6b8fSAnthony Liguori
2449ee22a9d8SAlberto Garcia /* Check if it's possible to merge a write request with the writing of
2450ee22a9d8SAlberto Garcia * the data from the COW regions */
merge_cow(uint64_t offset,unsigned bytes,QEMUIOVector * qiov,size_t qiov_offset,QCowL2Meta * l2meta)2451ee22a9d8SAlberto Garcia static bool merge_cow(uint64_t offset, unsigned bytes,
24525396234bSVladimir Sementsov-Ogievskiy QEMUIOVector *qiov, size_t qiov_offset,
24535396234bSVladimir Sementsov-Ogievskiy QCowL2Meta *l2meta)
2454ee22a9d8SAlberto Garcia {
2455ee22a9d8SAlberto Garcia QCowL2Meta *m;
2456ee22a9d8SAlberto Garcia
2457ee22a9d8SAlberto Garcia for (m = l2meta; m != NULL; m = m->next) {
2458ee22a9d8SAlberto Garcia /* If both COW regions are empty then there's nothing to merge */
2459ee22a9d8SAlberto Garcia if (m->cow_start.nb_bytes == 0 && m->cow_end.nb_bytes == 0) {
2460ee22a9d8SAlberto Garcia continue;
2461ee22a9d8SAlberto Garcia }
2462ee22a9d8SAlberto Garcia
2463c8bb23cbSAnton Nefedov /* If COW regions are handled already, skip this too */
2464c8bb23cbSAnton Nefedov if (m->skip_cow) {
2465c8bb23cbSAnton Nefedov continue;
2466c8bb23cbSAnton Nefedov }
2467c8bb23cbSAnton Nefedov
24683441ad4bSAlberto Garcia /*
24693441ad4bSAlberto Garcia * The write request should start immediately after the first
24703441ad4bSAlberto Garcia * COW region. This does not always happen because the area
24713441ad4bSAlberto Garcia * touched by the request can be larger than the one defined
24723441ad4bSAlberto Garcia * by @m (a single request can span an area consisting of a
24733441ad4bSAlberto Garcia * mix of previously unallocated and allocated clusters, that
24743441ad4bSAlberto Garcia * is why @l2meta is a list).
24753441ad4bSAlberto Garcia */
2476ee22a9d8SAlberto Garcia if (l2meta_cow_start(m) + m->cow_start.nb_bytes != offset) {
24773441ad4bSAlberto Garcia /* In this case the request starts before this region */
24783441ad4bSAlberto Garcia assert(offset < l2meta_cow_start(m));
24793441ad4bSAlberto Garcia assert(m->cow_start.nb_bytes == 0);
2480ee22a9d8SAlberto Garcia continue;
2481ee22a9d8SAlberto Garcia }
2482ee22a9d8SAlberto Garcia
24833441ad4bSAlberto Garcia /* The write request should end immediately before the second
24843441ad4bSAlberto Garcia * COW region (see above for why it does not always happen) */
2485ee22a9d8SAlberto Garcia if (m->offset + m->cow_end.offset != offset + bytes) {
24863441ad4bSAlberto Garcia assert(offset + bytes > m->offset + m->cow_end.offset);
24873441ad4bSAlberto Garcia assert(m->cow_end.nb_bytes == 0);
2488ee22a9d8SAlberto Garcia continue;
2489ee22a9d8SAlberto Garcia }
2490ee22a9d8SAlberto Garcia
2491ee22a9d8SAlberto Garcia /* Make sure that adding both COW regions to the QEMUIOVector
2492ee22a9d8SAlberto Garcia * does not exceed IOV_MAX */
24935396234bSVladimir Sementsov-Ogievskiy if (qemu_iovec_subvec_niov(qiov, qiov_offset, bytes) > IOV_MAX - 2) {
2494ee22a9d8SAlberto Garcia continue;
2495ee22a9d8SAlberto Garcia }
2496ee22a9d8SAlberto Garcia
24975396234bSVladimir Sementsov-Ogievskiy m->data_qiov = qiov;
24985396234bSVladimir Sementsov-Ogievskiy m->data_qiov_offset = qiov_offset;
2499ee22a9d8SAlberto Garcia return true;
2500ee22a9d8SAlberto Garcia }
2501ee22a9d8SAlberto Garcia
2502ee22a9d8SAlberto Garcia return false;
2503ee22a9d8SAlberto Garcia }
2504ee22a9d8SAlberto Garcia
250546cd1e8aSAlberto Garcia /*
250646cd1e8aSAlberto Garcia * Return 1 if the COW regions read as zeroes, 0 if not, < 0 on error.
250746cd1e8aSAlberto Garcia * Note that returning 0 does not guarantee non-zero data.
250846cd1e8aSAlberto Garcia */
2509abaf8b75SKevin Wolf static int coroutine_fn GRAPH_RDLOCK
is_zero_cow(BlockDriverState * bs,QCowL2Meta * m)2510abaf8b75SKevin Wolf is_zero_cow(BlockDriverState *bs, QCowL2Meta *m)
2511c8bb23cbSAnton Nefedov {
2512c8bb23cbSAnton Nefedov /*
2513c8bb23cbSAnton Nefedov * This check is designed for optimization shortcut so it must be
2514c8bb23cbSAnton Nefedov * efficient.
251546cd1e8aSAlberto Garcia * Instead of is_zero(), use bdrv_co_is_zero_fast() as it is
251646cd1e8aSAlberto Garcia * faster (but not as accurate and can result in false negatives).
2517c8bb23cbSAnton Nefedov */
251846cd1e8aSAlberto Garcia int ret = bdrv_co_is_zero_fast(bs, m->offset + m->cow_start.offset,
251946cd1e8aSAlberto Garcia m->cow_start.nb_bytes);
252046cd1e8aSAlberto Garcia if (ret <= 0) {
252146cd1e8aSAlberto Garcia return ret;
252246cd1e8aSAlberto Garcia }
252346cd1e8aSAlberto Garcia
252446cd1e8aSAlberto Garcia return bdrv_co_is_zero_fast(bs, m->offset + m->cow_end.offset,
2525c8bb23cbSAnton Nefedov m->cow_end.nb_bytes);
2526c8bb23cbSAnton Nefedov }
2527c8bb23cbSAnton Nefedov
2528abaf8b75SKevin Wolf static int coroutine_fn GRAPH_RDLOCK
handle_alloc_space(BlockDriverState * bs,QCowL2Meta * l2meta)2529abaf8b75SKevin Wolf handle_alloc_space(BlockDriverState *bs, QCowL2Meta *l2meta)
2530c8bb23cbSAnton Nefedov {
2531c8bb23cbSAnton Nefedov BDRVQcow2State *s = bs->opaque;
2532c8bb23cbSAnton Nefedov QCowL2Meta *m;
2533c8bb23cbSAnton Nefedov
2534c8bb23cbSAnton Nefedov if (!(s->data_file->bs->supported_zero_flags & BDRV_REQ_NO_FALLBACK)) {
2535c8bb23cbSAnton Nefedov return 0;
2536c8bb23cbSAnton Nefedov }
2537c8bb23cbSAnton Nefedov
2538c8bb23cbSAnton Nefedov if (bs->encrypted) {
2539c8bb23cbSAnton Nefedov return 0;
2540c8bb23cbSAnton Nefedov }
2541c8bb23cbSAnton Nefedov
2542c8bb23cbSAnton Nefedov for (m = l2meta; m != NULL; m = m->next) {
2543c8bb23cbSAnton Nefedov int ret;
2544bf4a66eeSAlberto Garcia uint64_t start_offset = m->alloc_offset + m->cow_start.offset;
2545bf4a66eeSAlberto Garcia unsigned nb_bytes = m->cow_end.offset + m->cow_end.nb_bytes -
2546bf4a66eeSAlberto Garcia m->cow_start.offset;
2547c8bb23cbSAnton Nefedov
2548c8bb23cbSAnton Nefedov if (!m->cow_start.nb_bytes && !m->cow_end.nb_bytes) {
2549c8bb23cbSAnton Nefedov continue;
2550c8bb23cbSAnton Nefedov }
2551c8bb23cbSAnton Nefedov
255246cd1e8aSAlberto Garcia ret = is_zero_cow(bs, m);
255346cd1e8aSAlberto Garcia if (ret < 0) {
255446cd1e8aSAlberto Garcia return ret;
255546cd1e8aSAlberto Garcia } else if (ret == 0) {
2556c8bb23cbSAnton Nefedov continue;
2557c8bb23cbSAnton Nefedov }
2558c8bb23cbSAnton Nefedov
2559c8bb23cbSAnton Nefedov /*
2560c8bb23cbSAnton Nefedov * instead of writing zero COW buffers,
2561c8bb23cbSAnton Nefedov * efficiently zero out the whole clusters
2562c8bb23cbSAnton Nefedov */
2563c8bb23cbSAnton Nefedov
2564bf4a66eeSAlberto Garcia ret = qcow2_pre_write_overlap_check(bs, 0, start_offset, nb_bytes,
2565c8bb23cbSAnton Nefedov true);
2566c8bb23cbSAnton Nefedov if (ret < 0) {
2567c8bb23cbSAnton Nefedov return ret;
2568c8bb23cbSAnton Nefedov }
2569c8bb23cbSAnton Nefedov
257017362398SPaolo Bonzini BLKDBG_CO_EVENT(bs->file, BLKDBG_CLUSTER_ALLOC_SPACE);
2571bf4a66eeSAlberto Garcia ret = bdrv_co_pwrite_zeroes(s->data_file, start_offset, nb_bytes,
2572c8bb23cbSAnton Nefedov BDRV_REQ_NO_FALLBACK);
2573c8bb23cbSAnton Nefedov if (ret < 0) {
2574c8bb23cbSAnton Nefedov if (ret != -ENOTSUP && ret != -EAGAIN) {
2575c8bb23cbSAnton Nefedov return ret;
2576c8bb23cbSAnton Nefedov }
2577c8bb23cbSAnton Nefedov continue;
2578c8bb23cbSAnton Nefedov }
2579c8bb23cbSAnton Nefedov
2580c8bb23cbSAnton Nefedov trace_qcow2_skip_cow(qemu_coroutine_self(), m->offset, m->nb_clusters);
2581c8bb23cbSAnton Nefedov m->skip_cow = true;
2582c8bb23cbSAnton Nefedov }
2583c8bb23cbSAnton Nefedov return 0;
2584c8bb23cbSAnton Nefedov }
2585c8bb23cbSAnton Nefedov
25866aa7a263SVladimir Sementsov-Ogievskiy /*
25876aa7a263SVladimir Sementsov-Ogievskiy * qcow2_co_pwritev_task
25886aa7a263SVladimir Sementsov-Ogievskiy * Called with s->lock unlocked
25896aa7a263SVladimir Sementsov-Ogievskiy * l2meta - if not NULL, qcow2_co_pwritev_task() will consume it. Caller must
25906aa7a263SVladimir Sementsov-Ogievskiy * not use it somehow after qcow2_co_pwritev_task() call
25916aa7a263SVladimir Sementsov-Ogievskiy */
2592abaf8b75SKevin 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)2593abaf8b75SKevin Wolf int qcow2_co_pwritev_task(BlockDriverState *bs, uint64_t host_offset,
2594abaf8b75SKevin Wolf uint64_t offset, uint64_t bytes, QEMUIOVector *qiov,
2595abaf8b75SKevin Wolf uint64_t qiov_offset, QCowL2Meta *l2meta)
25966aa7a263SVladimir Sementsov-Ogievskiy {
25976aa7a263SVladimir Sementsov-Ogievskiy int ret;
25986aa7a263SVladimir Sementsov-Ogievskiy BDRVQcow2State *s = bs->opaque;
25996aa7a263SVladimir Sementsov-Ogievskiy void *crypt_buf = NULL;
26006aa7a263SVladimir Sementsov-Ogievskiy QEMUIOVector encrypted_qiov;
26016aa7a263SVladimir Sementsov-Ogievskiy
26026aa7a263SVladimir Sementsov-Ogievskiy if (bs->encrypted) {
26036aa7a263SVladimir Sementsov-Ogievskiy assert(s->crypto);
26046aa7a263SVladimir Sementsov-Ogievskiy assert(bytes <= QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
26056aa7a263SVladimir Sementsov-Ogievskiy crypt_buf = qemu_try_blockalign(bs->file->bs, bytes);
26066aa7a263SVladimir Sementsov-Ogievskiy if (crypt_buf == NULL) {
26076aa7a263SVladimir Sementsov-Ogievskiy ret = -ENOMEM;
26086aa7a263SVladimir Sementsov-Ogievskiy goto out_unlocked;
26096aa7a263SVladimir Sementsov-Ogievskiy }
26106aa7a263SVladimir Sementsov-Ogievskiy qemu_iovec_to_buf(qiov, qiov_offset, crypt_buf, bytes);
26116aa7a263SVladimir Sementsov-Ogievskiy
26129c4269d5SAlberto Garcia if (qcow2_co_encrypt(bs, host_offset, offset, crypt_buf, bytes) < 0) {
26136aa7a263SVladimir Sementsov-Ogievskiy ret = -EIO;
26146aa7a263SVladimir Sementsov-Ogievskiy goto out_unlocked;
26156aa7a263SVladimir Sementsov-Ogievskiy }
26166aa7a263SVladimir Sementsov-Ogievskiy
26176aa7a263SVladimir Sementsov-Ogievskiy qemu_iovec_init_buf(&encrypted_qiov, crypt_buf, bytes);
26186aa7a263SVladimir Sementsov-Ogievskiy qiov = &encrypted_qiov;
26196aa7a263SVladimir Sementsov-Ogievskiy qiov_offset = 0;
26206aa7a263SVladimir Sementsov-Ogievskiy }
26216aa7a263SVladimir Sementsov-Ogievskiy
26226aa7a263SVladimir Sementsov-Ogievskiy /* Try to efficiently initialize the physical space with zeroes */
26236aa7a263SVladimir Sementsov-Ogievskiy ret = handle_alloc_space(bs, l2meta);
26246aa7a263SVladimir Sementsov-Ogievskiy if (ret < 0) {
26256aa7a263SVladimir Sementsov-Ogievskiy goto out_unlocked;
26266aa7a263SVladimir Sementsov-Ogievskiy }
26276aa7a263SVladimir Sementsov-Ogievskiy
26286aa7a263SVladimir Sementsov-Ogievskiy /*
26296aa7a263SVladimir Sementsov-Ogievskiy * If we need to do COW, check if it's possible to merge the
26306aa7a263SVladimir Sementsov-Ogievskiy * writing of the guest data together with that of the COW regions.
26316aa7a263SVladimir Sementsov-Ogievskiy * If it's not possible (or not necessary) then write the
26326aa7a263SVladimir Sementsov-Ogievskiy * guest data now.
26336aa7a263SVladimir Sementsov-Ogievskiy */
26346aa7a263SVladimir Sementsov-Ogievskiy if (!merge_cow(offset, bytes, qiov, qiov_offset, l2meta)) {
263517362398SPaolo Bonzini BLKDBG_CO_EVENT(bs->file, BLKDBG_WRITE_AIO);
26369c4269d5SAlberto Garcia trace_qcow2_writev_data(qemu_coroutine_self(), host_offset);
26379c4269d5SAlberto Garcia ret = bdrv_co_pwritev_part(s->data_file, host_offset,
26386aa7a263SVladimir Sementsov-Ogievskiy bytes, qiov, qiov_offset, 0);
26396aa7a263SVladimir Sementsov-Ogievskiy if (ret < 0) {
26406aa7a263SVladimir Sementsov-Ogievskiy goto out_unlocked;
26416aa7a263SVladimir Sementsov-Ogievskiy }
26426aa7a263SVladimir Sementsov-Ogievskiy }
26436aa7a263SVladimir Sementsov-Ogievskiy
26446aa7a263SVladimir Sementsov-Ogievskiy qemu_co_mutex_lock(&s->lock);
26456aa7a263SVladimir Sementsov-Ogievskiy
26466aa7a263SVladimir Sementsov-Ogievskiy ret = qcow2_handle_l2meta(bs, &l2meta, true);
26476aa7a263SVladimir Sementsov-Ogievskiy goto out_locked;
26486aa7a263SVladimir Sementsov-Ogievskiy
26496aa7a263SVladimir Sementsov-Ogievskiy out_unlocked:
26506aa7a263SVladimir Sementsov-Ogievskiy qemu_co_mutex_lock(&s->lock);
26516aa7a263SVladimir Sementsov-Ogievskiy
26526aa7a263SVladimir Sementsov-Ogievskiy out_locked:
26536aa7a263SVladimir Sementsov-Ogievskiy qcow2_handle_l2meta(bs, &l2meta, false);
26546aa7a263SVladimir Sementsov-Ogievskiy qemu_co_mutex_unlock(&s->lock);
26556aa7a263SVladimir Sementsov-Ogievskiy
26566aa7a263SVladimir Sementsov-Ogievskiy qemu_vfree(crypt_buf);
26576aa7a263SVladimir Sementsov-Ogievskiy
26586aa7a263SVladimir Sementsov-Ogievskiy return ret;
26596aa7a263SVladimir Sementsov-Ogievskiy }
26606aa7a263SVladimir Sementsov-Ogievskiy
2661abaf8b75SKevin Wolf /*
2662abaf8b75SKevin Wolf * This function can count as GRAPH_RDLOCK because qcow2_co_pwritev_part() holds
2663abaf8b75SKevin Wolf * the graph lock and keeps it until this coroutine has terminated.
2664abaf8b75SKevin Wolf */
qcow2_co_pwritev_task_entry(AioTask * task)2665abaf8b75SKevin Wolf static coroutine_fn GRAPH_RDLOCK int qcow2_co_pwritev_task_entry(AioTask *task)
2666d710cf57SVladimir Sementsov-Ogievskiy {
2667d710cf57SVladimir Sementsov-Ogievskiy Qcow2AioTask *t = container_of(task, Qcow2AioTask, task);
2668d710cf57SVladimir Sementsov-Ogievskiy
266910dabdc5SAlberto Garcia assert(!t->subcluster_type);
2670d710cf57SVladimir Sementsov-Ogievskiy
26719c4269d5SAlberto Garcia return qcow2_co_pwritev_task(t->bs, t->host_offset,
2672d710cf57SVladimir Sementsov-Ogievskiy t->offset, t->bytes, t->qiov, t->qiov_offset,
2673d710cf57SVladimir Sementsov-Ogievskiy t->l2meta);
2674d710cf57SVladimir Sementsov-Ogievskiy }
2675d710cf57SVladimir Sementsov-Ogievskiy
26767b1fb72eSKevin 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)26777b1fb72eSKevin Wolf qcow2_co_pwritev_part(BlockDriverState *bs, int64_t offset, int64_t bytes,
26787b1fb72eSKevin Wolf QEMUIOVector *qiov, size_t qiov_offset,
26797b1fb72eSKevin Wolf BdrvRequestFlags flags)
2680019d6b8fSAnthony Liguori {
2681ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque;
2682d46a0bb2SKevin Wolf int offset_in_cluster;
268368d100e9SKevin Wolf int ret;
2684d46a0bb2SKevin Wolf unsigned int cur_bytes; /* number of sectors in current iteration */
2685bfd0989aSAlberto Garcia uint64_t host_offset;
26868d2497c3SKevin Wolf QCowL2Meta *l2meta = NULL;
2687d710cf57SVladimir Sementsov-Ogievskiy AioTaskPool *aio = NULL;
2688c2271403SFrediano Ziglio
2689d46a0bb2SKevin Wolf trace_qcow2_writev_start_req(qemu_coroutine_self(), offset, bytes);
26903cce16f4SKevin Wolf
2691d710cf57SVladimir Sementsov-Ogievskiy while (bytes != 0 && aio_task_pool_status(aio) == 0) {
26923fc48d09SFrediano Ziglio
2693f50f88b9SKevin Wolf l2meta = NULL;
2694cf5c1a23SKevin Wolf
26953cce16f4SKevin Wolf trace_qcow2_writev_start_part(qemu_coroutine_self());
2696d46a0bb2SKevin Wolf offset_in_cluster = offset_into_cluster(s, offset);
2697d46a0bb2SKevin Wolf cur_bytes = MIN(bytes, INT_MAX);
2698d46a0bb2SKevin Wolf if (bs->encrypted) {
2699d46a0bb2SKevin Wolf cur_bytes = MIN(cur_bytes,
2700d46a0bb2SKevin Wolf QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size
2701d46a0bb2SKevin Wolf - offset_in_cluster);
27025ebaa27eSFrediano Ziglio }
2703019d6b8fSAnthony Liguori
27046aa7a263SVladimir Sementsov-Ogievskiy qemu_co_mutex_lock(&s->lock);
27056aa7a263SVladimir Sementsov-Ogievskiy
2706bfd0989aSAlberto Garcia ret = qcow2_alloc_host_offset(bs, offset, &cur_bytes,
2707bfd0989aSAlberto Garcia &host_offset, &l2meta);
2708148da7eaSKevin Wolf if (ret < 0) {
27095447c3a0SVladimir Sementsov-Ogievskiy goto out_locked;
2710148da7eaSKevin Wolf }
2711148da7eaSKevin Wolf
2712bfd0989aSAlberto Garcia ret = qcow2_pre_write_overlap_check(bs, 0, host_offset,
27135447c3a0SVladimir Sementsov-Ogievskiy cur_bytes, true);
27145447c3a0SVladimir Sementsov-Ogievskiy if (ret < 0) {
27155447c3a0SVladimir Sementsov-Ogievskiy goto out_locked;
27165447c3a0SVladimir Sementsov-Ogievskiy }
27175447c3a0SVladimir Sementsov-Ogievskiy
27185447c3a0SVladimir Sementsov-Ogievskiy qemu_co_mutex_unlock(&s->lock);
27195447c3a0SVladimir Sementsov-Ogievskiy
2720d710cf57SVladimir Sementsov-Ogievskiy if (!aio && cur_bytes != bytes) {
2721d710cf57SVladimir Sementsov-Ogievskiy aio = aio_task_pool_new(QCOW2_MAX_WORKERS);
2722d710cf57SVladimir Sementsov-Ogievskiy }
2723d710cf57SVladimir Sementsov-Ogievskiy ret = qcow2_add_task(bs, aio, qcow2_co_pwritev_task_entry, 0,
2724bfd0989aSAlberto Garcia host_offset, offset,
27259c4269d5SAlberto Garcia cur_bytes, qiov, qiov_offset, l2meta);
27266aa7a263SVladimir Sementsov-Ogievskiy l2meta = NULL; /* l2meta is consumed by qcow2_co_pwritev_task() */
2727c8bb23cbSAnton Nefedov if (ret < 0) {
27286aa7a263SVladimir Sementsov-Ogievskiy goto fail_nometa;
2729faf575c1SFrediano Ziglio }
2730faf575c1SFrediano Ziglio
2731d46a0bb2SKevin Wolf bytes -= cur_bytes;
2732d46a0bb2SKevin Wolf offset += cur_bytes;
27336aa7a263SVladimir Sementsov-Ogievskiy qiov_offset += cur_bytes;
2734d46a0bb2SKevin Wolf trace_qcow2_writev_done_part(qemu_coroutine_self(), cur_bytes);
27355ebaa27eSFrediano Ziglio }
27363fc48d09SFrediano Ziglio ret = 0;
2737faf575c1SFrediano Ziglio
27385447c3a0SVladimir Sementsov-Ogievskiy qemu_co_mutex_lock(&s->lock);
27395447c3a0SVladimir Sementsov-Ogievskiy
27405447c3a0SVladimir Sementsov-Ogievskiy out_locked:
2741fd9fcd37SFam Zheng qcow2_handle_l2meta(bs, &l2meta, false);
27420fa9131aSKevin Wolf
2743a8c57408SPaolo Bonzini qemu_co_mutex_unlock(&s->lock);
2744a8c57408SPaolo Bonzini
27456aa7a263SVladimir Sementsov-Ogievskiy fail_nometa:
2746d710cf57SVladimir Sementsov-Ogievskiy if (aio) {
2747d710cf57SVladimir Sementsov-Ogievskiy aio_task_pool_wait_all(aio);
2748d710cf57SVladimir Sementsov-Ogievskiy if (ret == 0) {
2749d710cf57SVladimir Sementsov-Ogievskiy ret = aio_task_pool_status(aio);
2750d710cf57SVladimir Sementsov-Ogievskiy }
2751d710cf57SVladimir Sementsov-Ogievskiy g_free(aio);
2752d710cf57SVladimir Sementsov-Ogievskiy }
2753d710cf57SVladimir Sementsov-Ogievskiy
27543cce16f4SKevin Wolf trace_qcow2_writev_done_req(qemu_coroutine_self(), ret);
275542496d62SKevin Wolf
275668d100e9SKevin Wolf return ret;
2757019d6b8fSAnthony Liguori }
2758019d6b8fSAnthony Liguori
qcow2_inactivate(BlockDriverState * bs)2759de4fed6fSKevin Wolf static int GRAPH_RDLOCK qcow2_inactivate(BlockDriverState *bs)
2760ec6d8912SKevin Wolf {
2761ec6d8912SKevin Wolf BDRVQcow2State *s = bs->opaque;
2762ec6d8912SKevin Wolf int ret, result = 0;
27635f72826eSVladimir Sementsov-Ogievskiy Error *local_err = NULL;
2764ec6d8912SKevin Wolf
2765644ddbb7SVladimir Sementsov-Ogievskiy qcow2_store_persistent_dirty_bitmaps(bs, true, &local_err);
276683a8c775SPavel Butsykin if (local_err != NULL) {
276783a8c775SPavel Butsykin result = -EINVAL;
2768132adb68SVladimir Sementsov-Ogievskiy error_reportf_err(local_err, "Lost persistent bitmaps during "
2769132adb68SVladimir Sementsov-Ogievskiy "inactivation of node '%s': ",
277083a8c775SPavel Butsykin bdrv_get_device_or_node_name(bs));
277183a8c775SPavel Butsykin }
277283a8c775SPavel Butsykin
2773ec6d8912SKevin Wolf ret = qcow2_cache_flush(bs, s->l2_table_cache);
2774ec6d8912SKevin Wolf if (ret) {
2775ec6d8912SKevin Wolf result = ret;
2776ec6d8912SKevin Wolf error_report("Failed to flush the L2 table cache: %s",
2777ec6d8912SKevin Wolf strerror(-ret));
2778ec6d8912SKevin Wolf }
2779ec6d8912SKevin Wolf
2780ec6d8912SKevin Wolf ret = qcow2_cache_flush(bs, s->refcount_block_cache);
2781ec6d8912SKevin Wolf if (ret) {
2782ec6d8912SKevin Wolf result = ret;
2783ec6d8912SKevin Wolf error_report("Failed to flush the refcount block cache: %s",
2784ec6d8912SKevin Wolf strerror(-ret));
2785ec6d8912SKevin Wolf }
2786ec6d8912SKevin Wolf
2787ec6d8912SKevin Wolf if (result == 0) {
2788ec6d8912SKevin Wolf qcow2_mark_clean(bs);
2789ec6d8912SKevin Wolf }
2790ec6d8912SKevin Wolf
2791ec6d8912SKevin Wolf return result;
2792ec6d8912SKevin Wolf }
2793ec6d8912SKevin Wolf
2794de4fed6fSKevin Wolf static void coroutine_mixed_fn GRAPH_RDLOCK
qcow2_do_close(BlockDriverState * bs,bool close_data_file)2795de4fed6fSKevin Wolf qcow2_do_close(BlockDriverState *bs, bool close_data_file)
2796019d6b8fSAnthony Liguori {
2797ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque;
2798de82815dSKevin Wolf qemu_vfree(s->l1_table);
2799cf93980eSMax Reitz /* else pre-write overlap checks in cache_destroy may crash */
2800cf93980eSMax Reitz s->l1_table = NULL;
280129c1a730SKevin Wolf
2802140fd5a6SKevin Wolf if (!(s->flags & BDRV_O_INACTIVE)) {
2803ec6d8912SKevin Wolf qcow2_inactivate(bs);
28043b5e14c7SMax Reitz }
2805c61d0004SStefan Hajnoczi
2806279621c0SAlberto Garcia cache_clean_timer_del(bs);
2807e64d4072SAlberto Garcia qcow2_cache_destroy(s->l2_table_cache);
2808e64d4072SAlberto Garcia qcow2_cache_destroy(s->refcount_block_cache);
280929c1a730SKevin Wolf
2810b25b387fSDaniel P. Berrange qcrypto_block_free(s->crypto);
2811b25b387fSDaniel P. Berrange s->crypto = NULL;
28124aebf0f0SPan Nengyuan qapi_free_QCryptoBlockOpenOptions(s->crypto_opts);
2813f6fa64f6SDaniel P. Berrange
28146744cbabSKevin Wolf g_free(s->unknown_header_fields);
281575bab85cSKevin Wolf cleanup_unknown_header_ext(bs);
28166744cbabSKevin Wolf
28179b890bdcSKevin Wolf g_free(s->image_data_file);
2818e4603fe1SKevin Wolf g_free(s->image_backing_file);
2819e4603fe1SKevin Wolf g_free(s->image_backing_format);
2820e4603fe1SKevin Wolf
282106e9cd19SHanna Reitz if (close_data_file && has_data_file(bs)) {
2822de4fed6fSKevin Wolf GLOBAL_STATE_CODE();
2823de4fed6fSKevin Wolf bdrv_graph_rdunlock_main_loop();
28246bc30f19SStefan Hajnoczi bdrv_graph_wrlock();
28250e8c08beSKevin Wolf bdrv_unref_child(bs, s->data_file);
28266bc30f19SStefan Hajnoczi bdrv_graph_wrunlock();
2827808cf3cbSVladimir Sementsov-Ogievskiy s->data_file = NULL;
2828de4fed6fSKevin Wolf bdrv_graph_rdlock_main_loop();
28290e8c08beSKevin Wolf }
28300e8c08beSKevin Wolf
2831ed6ccf0fSKevin Wolf qcow2_refcount_close(bs);
283228c1202bSLi Zhi Hui qcow2_free_snapshots(bs);
2833019d6b8fSAnthony Liguori }
2834019d6b8fSAnthony Liguori
qcow2_close(BlockDriverState * bs)2835de4fed6fSKevin Wolf static void GRAPH_UNLOCKED qcow2_close(BlockDriverState *bs)
283606e9cd19SHanna Reitz {
2837de4fed6fSKevin Wolf GLOBAL_STATE_CODE();
2838de4fed6fSKevin Wolf GRAPH_RDLOCK_GUARD_MAINLOOP();
2839de4fed6fSKevin Wolf
284006e9cd19SHanna Reitz qcow2_do_close(bs, true);
284106e9cd19SHanna Reitz }
284206e9cd19SHanna Reitz
2843b9b10c35SKevin Wolf static void coroutine_fn GRAPH_RDLOCK
qcow2_co_invalidate_cache(BlockDriverState * bs,Error ** errp)2844b9b10c35SKevin Wolf qcow2_co_invalidate_cache(BlockDriverState *bs, Error **errp)
284506d9260fSAnthony Liguori {
2846e6247c9cSVladimir Sementsov-Ogievskiy ERRP_GUARD();
2847ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque;
284806e9cd19SHanna Reitz BdrvChild *data_file;
284906d9260fSAnthony Liguori int flags = s->flags;
2850b25b387fSDaniel P. Berrange QCryptoBlock *crypto = NULL;
2851acdfb480SKevin Wolf QDict *options;
28525a8a30dbSKevin Wolf int ret;
285306d9260fSAnthony Liguori
285406d9260fSAnthony Liguori /*
285506d9260fSAnthony Liguori * Backing files are read-only which makes all of their metadata immutable,
285606d9260fSAnthony Liguori * that means we don't have to worry about reopening them here.
285706d9260fSAnthony Liguori */
285806d9260fSAnthony Liguori
2859b25b387fSDaniel P. Berrange crypto = s->crypto;
2860b25b387fSDaniel P. Berrange s->crypto = NULL;
286106d9260fSAnthony Liguori
286206e9cd19SHanna Reitz /*
286306e9cd19SHanna Reitz * Do not reopen s->data_file (i.e., have qcow2_do_close() not close it,
286406e9cd19SHanna Reitz * and then prevent qcow2_do_open() from opening it), because this function
286506e9cd19SHanna Reitz * runs in the I/O path and as such we must not invoke global-state
286606e9cd19SHanna Reitz * functions like bdrv_unref_child() and bdrv_open_child().
286706e9cd19SHanna Reitz */
286806d9260fSAnthony Liguori
286906e9cd19SHanna Reitz qcow2_do_close(bs, false);
287006e9cd19SHanna Reitz
287106e9cd19SHanna Reitz data_file = s->data_file;
2872ff99129aSKevin Wolf memset(s, 0, sizeof(BDRVQcow2State));
287306e9cd19SHanna Reitz s->data_file = data_file;
287406e9cd19SHanna Reitz
2875d475e5acSKevin Wolf options = qdict_clone_shallow(bs->options);
28765a8a30dbSKevin Wolf
2877140fd5a6SKevin Wolf flags &= ~BDRV_O_INACTIVE;
28782b148f39SPaolo Bonzini qemu_co_mutex_lock(&s->lock);
287906e9cd19SHanna Reitz ret = qcow2_do_open(bs, options, flags, false, errp);
28802b148f39SPaolo Bonzini qemu_co_mutex_unlock(&s->lock);
2881cb3e7f08SMarc-André Lureau qobject_unref(options);
2882e6247c9cSVladimir Sementsov-Ogievskiy if (ret < 0) {
2883e6247c9cSVladimir Sementsov-Ogievskiy error_prepend(errp, "Could not reopen qcow2 layer: ");
2884191fb11bSKevin Wolf bs->drv = NULL;
28855a8a30dbSKevin Wolf return;
28865a8a30dbSKevin Wolf }
2887acdfb480SKevin Wolf
2888b25b387fSDaniel P. Berrange s->crypto = crypto;
288906d9260fSAnthony Liguori }
289006d9260fSAnthony Liguori
header_ext_add(char * buf,uint32_t magic,const void * s,size_t len,size_t buflen)2891e24e49e6SKevin Wolf static size_t header_ext_add(char *buf, uint32_t magic, const void *s,
2892e24e49e6SKevin Wolf size_t len, size_t buflen)
2893756e6736SKevin Wolf {
2894e24e49e6SKevin Wolf QCowExtension *ext_backing_fmt = (QCowExtension*) buf;
2895e24e49e6SKevin Wolf size_t ext_len = sizeof(QCowExtension) + ((len + 7) & ~7);
2896756e6736SKevin Wolf
2897e24e49e6SKevin Wolf if (buflen < ext_len) {
2898756e6736SKevin Wolf return -ENOSPC;
2899756e6736SKevin Wolf }
2900756e6736SKevin Wolf
2901e24e49e6SKevin Wolf *ext_backing_fmt = (QCowExtension) {
2902e24e49e6SKevin Wolf .magic = cpu_to_be32(magic),
2903e24e49e6SKevin Wolf .len = cpu_to_be32(len),
2904e24e49e6SKevin Wolf };
29050647d47cSStefan Hajnoczi
29060647d47cSStefan Hajnoczi if (len) {
2907e24e49e6SKevin Wolf memcpy(buf + sizeof(QCowExtension), s, len);
29080647d47cSStefan Hajnoczi }
2909756e6736SKevin Wolf
2910e24e49e6SKevin Wolf return ext_len;
2911756e6736SKevin Wolf }
2912756e6736SKevin Wolf
2913e24e49e6SKevin Wolf /*
2914e24e49e6SKevin Wolf * Updates the qcow2 header, including the variable length parts of it, i.e.
2915e24e49e6SKevin Wolf * the backing file name and all extensions. qcow2 was not designed to allow
2916e24e49e6SKevin Wolf * such changes, so if we run out of space (we can only use the first cluster)
2917e24e49e6SKevin Wolf * this function may fail.
2918e24e49e6SKevin Wolf *
2919e24e49e6SKevin Wolf * Returns 0 on success, -errno in error cases.
2920e24e49e6SKevin Wolf */
qcow2_update_header(BlockDriverState * bs)2921e24e49e6SKevin Wolf int qcow2_update_header(BlockDriverState *bs)
2922e24e49e6SKevin Wolf {
2923ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque;
2924e24e49e6SKevin Wolf QCowHeader *header;
2925e24e49e6SKevin Wolf char *buf;
2926e24e49e6SKevin Wolf size_t buflen = s->cluster_size;
2927e24e49e6SKevin Wolf int ret;
2928e24e49e6SKevin Wolf uint64_t total_size;
2929e24e49e6SKevin Wolf uint32_t refcount_table_clusters;
29306744cbabSKevin Wolf size_t header_length;
293175bab85cSKevin Wolf Qcow2UnknownHeaderExtension *uext;
2932e24e49e6SKevin Wolf
2933e24e49e6SKevin Wolf buf = qemu_blockalign(bs, buflen);
2934e24e49e6SKevin Wolf
2935e24e49e6SKevin Wolf /* Header structure */
2936e24e49e6SKevin Wolf header = (QCowHeader*) buf;
2937e24e49e6SKevin Wolf
2938e24e49e6SKevin Wolf if (buflen < sizeof(*header)) {
2939e24e49e6SKevin Wolf ret = -ENOSPC;
2940e24e49e6SKevin Wolf goto fail;
2941756e6736SKevin Wolf }
2942756e6736SKevin Wolf
29436744cbabSKevin Wolf header_length = sizeof(*header) + s->unknown_header_fields_size;
2944e24e49e6SKevin Wolf total_size = bs->total_sectors * BDRV_SECTOR_SIZE;
2945e24e49e6SKevin Wolf refcount_table_clusters = s->refcount_table_size >> (s->cluster_bits - 3);
2946e24e49e6SKevin Wolf
2947572ad978SDenis Plotnikov ret = validate_compression_type(s, NULL);
2948572ad978SDenis Plotnikov if (ret) {
2949572ad978SDenis Plotnikov goto fail;
2950572ad978SDenis Plotnikov }
2951572ad978SDenis Plotnikov
2952e24e49e6SKevin Wolf *header = (QCowHeader) {
29536744cbabSKevin Wolf /* Version 2 fields */
2954e24e49e6SKevin Wolf .magic = cpu_to_be32(QCOW_MAGIC),
29556744cbabSKevin Wolf .version = cpu_to_be32(s->qcow_version),
2956e24e49e6SKevin Wolf .backing_file_offset = 0,
2957e24e49e6SKevin Wolf .backing_file_size = 0,
2958e24e49e6SKevin Wolf .cluster_bits = cpu_to_be32(s->cluster_bits),
2959e24e49e6SKevin Wolf .size = cpu_to_be64(total_size),
2960e24e49e6SKevin Wolf .crypt_method = cpu_to_be32(s->crypt_method_header),
2961e24e49e6SKevin Wolf .l1_size = cpu_to_be32(s->l1_size),
2962e24e49e6SKevin Wolf .l1_table_offset = cpu_to_be64(s->l1_table_offset),
2963e24e49e6SKevin Wolf .refcount_table_offset = cpu_to_be64(s->refcount_table_offset),
2964e24e49e6SKevin Wolf .refcount_table_clusters = cpu_to_be32(refcount_table_clusters),
2965e24e49e6SKevin Wolf .nb_snapshots = cpu_to_be32(s->nb_snapshots),
2966e24e49e6SKevin Wolf .snapshots_offset = cpu_to_be64(s->snapshots_offset),
29676744cbabSKevin Wolf
29686744cbabSKevin Wolf /* Version 3 fields */
29696744cbabSKevin Wolf .incompatible_features = cpu_to_be64(s->incompatible_features),
29706744cbabSKevin Wolf .compatible_features = cpu_to_be64(s->compatible_features),
29716744cbabSKevin Wolf .autoclear_features = cpu_to_be64(s->autoclear_features),
2972b6481f37SMax Reitz .refcount_order = cpu_to_be32(s->refcount_order),
29736744cbabSKevin Wolf .header_length = cpu_to_be32(header_length),
2974572ad978SDenis Plotnikov .compression_type = s->compression_type,
2975e24e49e6SKevin Wolf };
2976e24e49e6SKevin Wolf
29776744cbabSKevin Wolf /* For older versions, write a shorter header */
29786744cbabSKevin Wolf switch (s->qcow_version) {
29796744cbabSKevin Wolf case 2:
29806744cbabSKevin Wolf ret = offsetof(QCowHeader, incompatible_features);
29816744cbabSKevin Wolf break;
29826744cbabSKevin Wolf case 3:
29836744cbabSKevin Wolf ret = sizeof(*header);
29846744cbabSKevin Wolf break;
29856744cbabSKevin Wolf default:
2986b6c14762SJim Meyering ret = -EINVAL;
2987b6c14762SJim Meyering goto fail;
29886744cbabSKevin Wolf }
29896744cbabSKevin Wolf
29906744cbabSKevin Wolf buf += ret;
29916744cbabSKevin Wolf buflen -= ret;
29926744cbabSKevin Wolf memset(buf, 0, buflen);
29936744cbabSKevin Wolf
29946744cbabSKevin Wolf /* Preserve any unknown field in the header */
29956744cbabSKevin Wolf if (s->unknown_header_fields_size) {
29966744cbabSKevin Wolf if (buflen < s->unknown_header_fields_size) {
29976744cbabSKevin Wolf ret = -ENOSPC;
29986744cbabSKevin Wolf goto fail;
29996744cbabSKevin Wolf }
30006744cbabSKevin Wolf
30016744cbabSKevin Wolf memcpy(buf, s->unknown_header_fields, s->unknown_header_fields_size);
30026744cbabSKevin Wolf buf += s->unknown_header_fields_size;
30036744cbabSKevin Wolf buflen -= s->unknown_header_fields_size;
30046744cbabSKevin Wolf }
3005e24e49e6SKevin Wolf
3006e24e49e6SKevin Wolf /* Backing file format header extension */
3007e4603fe1SKevin Wolf if (s->image_backing_format) {
3008e24e49e6SKevin Wolf ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BACKING_FORMAT,
3009e4603fe1SKevin Wolf s->image_backing_format,
3010e4603fe1SKevin Wolf strlen(s->image_backing_format),
3011e24e49e6SKevin Wolf buflen);
3012756e6736SKevin Wolf if (ret < 0) {
3013756e6736SKevin Wolf goto fail;
3014756e6736SKevin Wolf }
3015756e6736SKevin Wolf
3016e24e49e6SKevin Wolf buf += ret;
3017e24e49e6SKevin Wolf buflen -= ret;
3018e24e49e6SKevin Wolf }
3019756e6736SKevin Wolf
30209b890bdcSKevin Wolf /* External data file header extension */
30219b890bdcSKevin Wolf if (has_data_file(bs) && s->image_data_file) {
30229b890bdcSKevin Wolf ret = header_ext_add(buf, QCOW2_EXT_MAGIC_DATA_FILE,
30239b890bdcSKevin Wolf s->image_data_file, strlen(s->image_data_file),
30249b890bdcSKevin Wolf buflen);
30259b890bdcSKevin Wolf if (ret < 0) {
30269b890bdcSKevin Wolf goto fail;
30279b890bdcSKevin Wolf }
30289b890bdcSKevin Wolf
30299b890bdcSKevin Wolf buf += ret;
30309b890bdcSKevin Wolf buflen -= ret;
30319b890bdcSKevin Wolf }
30329b890bdcSKevin Wolf
30334652b8f3SDaniel P. Berrange /* Full disk encryption header pointer extension */
30344652b8f3SDaniel P. Berrange if (s->crypto_header.offset != 0) {
30353b698f52SPeter Maydell s->crypto_header.offset = cpu_to_be64(s->crypto_header.offset);
30363b698f52SPeter Maydell s->crypto_header.length = cpu_to_be64(s->crypto_header.length);
30374652b8f3SDaniel P. Berrange ret = header_ext_add(buf, QCOW2_EXT_MAGIC_CRYPTO_HEADER,
30384652b8f3SDaniel P. Berrange &s->crypto_header, sizeof(s->crypto_header),
30394652b8f3SDaniel P. Berrange buflen);
30403b698f52SPeter Maydell s->crypto_header.offset = be64_to_cpu(s->crypto_header.offset);
30413b698f52SPeter Maydell s->crypto_header.length = be64_to_cpu(s->crypto_header.length);
30424652b8f3SDaniel P. Berrange if (ret < 0) {
30434652b8f3SDaniel P. Berrange goto fail;
30444652b8f3SDaniel P. Berrange }
30454652b8f3SDaniel P. Berrange buf += ret;
30464652b8f3SDaniel P. Berrange buflen -= ret;
30474652b8f3SDaniel P. Berrange }
30484652b8f3SDaniel P. Berrange
3049e7be13adSEric Blake /*
3050e7be13adSEric Blake * Feature table. A mere 8 feature names occupies 392 bytes, and
3051e7be13adSEric Blake * when coupled with the v3 minimum header of 104 bytes plus the
3052e7be13adSEric Blake * 8-byte end-of-extension marker, that would leave only 8 bytes
3053e7be13adSEric Blake * for a backing file name in an image with 512-byte clusters.
3054e7be13adSEric Blake * Thus, we choose to omit this header for cluster sizes 4k and
3055e7be13adSEric Blake * smaller.
3056e7be13adSEric Blake */
3057e7be13adSEric Blake if (s->qcow_version >= 3 && s->cluster_size > 4096) {
3058bb40ebceSEric Blake static const Qcow2Feature features[] = {
3059c61d0004SStefan Hajnoczi {
3060c61d0004SStefan Hajnoczi .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
3061c61d0004SStefan Hajnoczi .bit = QCOW2_INCOMPAT_DIRTY_BITNR,
3062c61d0004SStefan Hajnoczi .name = "dirty bit",
3063c61d0004SStefan Hajnoczi },
3064bfe8043eSStefan Hajnoczi {
306569c98726SMax Reitz .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
306669c98726SMax Reitz .bit = QCOW2_INCOMPAT_CORRUPT_BITNR,
306769c98726SMax Reitz .name = "corrupt bit",
306869c98726SMax Reitz },
306969c98726SMax Reitz {
307093c24936SKevin Wolf .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
307193c24936SKevin Wolf .bit = QCOW2_INCOMPAT_DATA_FILE_BITNR,
307293c24936SKevin Wolf .name = "external data file",
307393c24936SKevin Wolf },
307493c24936SKevin Wolf {
3075572ad978SDenis Plotnikov .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
3076572ad978SDenis Plotnikov .bit = QCOW2_INCOMPAT_COMPRESSION_BITNR,
3077572ad978SDenis Plotnikov .name = "compression type",
3078572ad978SDenis Plotnikov },
3079572ad978SDenis Plotnikov {
30807be20252SAlberto Garcia .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
30817be20252SAlberto Garcia .bit = QCOW2_INCOMPAT_EXTL2_BITNR,
30827be20252SAlberto Garcia .name = "extended L2 entries",
30837be20252SAlberto Garcia },
30847be20252SAlberto Garcia {
3085bfe8043eSStefan Hajnoczi .type = QCOW2_FEAT_TYPE_COMPATIBLE,
3086bfe8043eSStefan Hajnoczi .bit = QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR,
3087bfe8043eSStefan Hajnoczi .name = "lazy refcounts",
3088bfe8043eSStefan Hajnoczi },
3089bb40ebceSEric Blake {
3090bb40ebceSEric Blake .type = QCOW2_FEAT_TYPE_AUTOCLEAR,
3091bb40ebceSEric Blake .bit = QCOW2_AUTOCLEAR_BITMAPS_BITNR,
3092bb40ebceSEric Blake .name = "bitmaps",
3093bb40ebceSEric Blake },
3094bb40ebceSEric Blake {
3095bb40ebceSEric Blake .type = QCOW2_FEAT_TYPE_AUTOCLEAR,
3096bb40ebceSEric Blake .bit = QCOW2_AUTOCLEAR_DATA_FILE_RAW_BITNR,
3097bb40ebceSEric Blake .name = "raw external data",
3098bb40ebceSEric Blake },
3099cfcc4c62SKevin Wolf };
3100cfcc4c62SKevin Wolf
3101cfcc4c62SKevin Wolf ret = header_ext_add(buf, QCOW2_EXT_MAGIC_FEATURE_TABLE,
3102cfcc4c62SKevin Wolf features, sizeof(features), buflen);
3103cfcc4c62SKevin Wolf if (ret < 0) {
3104cfcc4c62SKevin Wolf goto fail;
3105cfcc4c62SKevin Wolf }
3106cfcc4c62SKevin Wolf buf += ret;
3107cfcc4c62SKevin Wolf buflen -= ret;
31081a4828c7SKevin Wolf }
3109cfcc4c62SKevin Wolf
311088ddffaeSVladimir Sementsov-Ogievskiy /* Bitmap extension */
311188ddffaeSVladimir Sementsov-Ogievskiy if (s->nb_bitmaps > 0) {
311288ddffaeSVladimir Sementsov-Ogievskiy Qcow2BitmapHeaderExt bitmaps_header = {
311388ddffaeSVladimir Sementsov-Ogievskiy .nb_bitmaps = cpu_to_be32(s->nb_bitmaps),
311488ddffaeSVladimir Sementsov-Ogievskiy .bitmap_directory_size =
311588ddffaeSVladimir Sementsov-Ogievskiy cpu_to_be64(s->bitmap_directory_size),
311688ddffaeSVladimir Sementsov-Ogievskiy .bitmap_directory_offset =
311788ddffaeSVladimir Sementsov-Ogievskiy cpu_to_be64(s->bitmap_directory_offset)
311888ddffaeSVladimir Sementsov-Ogievskiy };
311988ddffaeSVladimir Sementsov-Ogievskiy ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BITMAPS,
312088ddffaeSVladimir Sementsov-Ogievskiy &bitmaps_header, sizeof(bitmaps_header),
312188ddffaeSVladimir Sementsov-Ogievskiy buflen);
312288ddffaeSVladimir Sementsov-Ogievskiy if (ret < 0) {
312388ddffaeSVladimir Sementsov-Ogievskiy goto fail;
312488ddffaeSVladimir Sementsov-Ogievskiy }
312588ddffaeSVladimir Sementsov-Ogievskiy buf += ret;
312688ddffaeSVladimir Sementsov-Ogievskiy buflen -= ret;
312788ddffaeSVladimir Sementsov-Ogievskiy }
312888ddffaeSVladimir Sementsov-Ogievskiy
312975bab85cSKevin Wolf /* Keep unknown header extensions */
313075bab85cSKevin Wolf QLIST_FOREACH(uext, &s->unknown_header_ext, next) {
313175bab85cSKevin Wolf ret = header_ext_add(buf, uext->magic, uext->data, uext->len, buflen);
313275bab85cSKevin Wolf if (ret < 0) {
313375bab85cSKevin Wolf goto fail;
313475bab85cSKevin Wolf }
313575bab85cSKevin Wolf
313675bab85cSKevin Wolf buf += ret;
313775bab85cSKevin Wolf buflen -= ret;
313875bab85cSKevin Wolf }
313975bab85cSKevin Wolf
3140e24e49e6SKevin Wolf /* End of header extensions */
3141e24e49e6SKevin Wolf ret = header_ext_add(buf, QCOW2_EXT_MAGIC_END, NULL, 0, buflen);
3142756e6736SKevin Wolf if (ret < 0) {
3143756e6736SKevin Wolf goto fail;
3144756e6736SKevin Wolf }
3145756e6736SKevin Wolf
3146e24e49e6SKevin Wolf buf += ret;
3147e24e49e6SKevin Wolf buflen -= ret;
3148e24e49e6SKevin Wolf
3149e24e49e6SKevin Wolf /* Backing file name */
3150e4603fe1SKevin Wolf if (s->image_backing_file) {
3151e4603fe1SKevin Wolf size_t backing_file_len = strlen(s->image_backing_file);
3152e24e49e6SKevin Wolf
3153e24e49e6SKevin Wolf if (buflen < backing_file_len) {
3154e24e49e6SKevin Wolf ret = -ENOSPC;
3155e24e49e6SKevin Wolf goto fail;
3156e24e49e6SKevin Wolf }
3157e24e49e6SKevin Wolf
315800ea1881SJim Meyering /* Using strncpy is ok here, since buf is not NUL-terminated. */
3159e4603fe1SKevin Wolf strncpy(buf, s->image_backing_file, buflen);
3160e24e49e6SKevin Wolf
3161e24e49e6SKevin Wolf header->backing_file_offset = cpu_to_be64(buf - ((char*) header));
3162e24e49e6SKevin Wolf header->backing_file_size = cpu_to_be32(backing_file_len);
3163e24e49e6SKevin Wolf }
3164e24e49e6SKevin Wolf
3165e24e49e6SKevin Wolf /* Write the new header */
316632cc71deSAlberto Faria ret = bdrv_pwrite(bs->file, 0, s->cluster_size, header, 0);
3167756e6736SKevin Wolf if (ret < 0) {
3168756e6736SKevin Wolf goto fail;
3169756e6736SKevin Wolf }
3170756e6736SKevin Wolf
3171756e6736SKevin Wolf ret = 0;
3172756e6736SKevin Wolf fail:
3173e24e49e6SKevin Wolf qemu_vfree(header);
3174756e6736SKevin Wolf return ret;
3175756e6736SKevin Wolf }
3176756e6736SKevin Wolf
3177e2dd2737SKevin Wolf static int coroutine_fn GRAPH_RDLOCK
qcow2_co_change_backing_file(BlockDriverState * bs,const char * backing_file,const char * backing_fmt)3178e2dd2737SKevin Wolf qcow2_co_change_backing_file(BlockDriverState *bs, const char *backing_file,
3179e2dd2737SKevin Wolf const char *backing_fmt)
3180756e6736SKevin Wolf {
3181ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque;
3182e4603fe1SKevin Wolf
31836c3944dcSKevin Wolf /* Adding a backing file means that the external data file alone won't be
31846c3944dcSKevin Wolf * enough to make sense of the content */
31856c3944dcSKevin Wolf if (backing_file && data_file_is_raw(bs)) {
31866c3944dcSKevin Wolf return -EINVAL;
31876c3944dcSKevin Wolf }
31886c3944dcSKevin Wolf
31894e876bcfSMax Reitz if (backing_file && strlen(backing_file) > 1023) {
31904e876bcfSMax Reitz return -EINVAL;
31914e876bcfSMax Reitz }
31924e876bcfSMax Reitz
3193998c2019SMax Reitz pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
3194998c2019SMax Reitz backing_file ?: "");
3195e24e49e6SKevin Wolf pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
3196e24e49e6SKevin Wolf pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
3197e24e49e6SKevin Wolf
3198e4603fe1SKevin Wolf g_free(s->image_backing_file);
3199e4603fe1SKevin Wolf g_free(s->image_backing_format);
3200e4603fe1SKevin Wolf
3201e4603fe1SKevin Wolf s->image_backing_file = backing_file ? g_strdup(bs->backing_file) : NULL;
3202e4603fe1SKevin Wolf s->image_backing_format = backing_fmt ? g_strdup(bs->backing_format) : NULL;
3203e4603fe1SKevin Wolf
3204e24e49e6SKevin Wolf return qcow2_update_header(bs);
3205756e6736SKevin Wolf }
3206756e6736SKevin Wolf
32074db7ba3bSKevin Wolf static int coroutine_fn GRAPH_RDLOCK
qcow2_set_up_encryption(BlockDriverState * bs,QCryptoBlockCreateOptions * cryptoopts,Error ** errp)32084db7ba3bSKevin Wolf qcow2_set_up_encryption(BlockDriverState *bs,
320960900b7bSKevin Wolf QCryptoBlockCreateOptions *cryptoopts,
321060900b7bSKevin Wolf Error **errp)
321160900b7bSKevin Wolf {
321260900b7bSKevin Wolf BDRVQcow2State *s = bs->opaque;
321360900b7bSKevin Wolf QCryptoBlock *crypto = NULL;
321460900b7bSKevin Wolf int fmt, ret;
321560900b7bSKevin Wolf
321660900b7bSKevin Wolf switch (cryptoopts->format) {
3217d23d2ef3SMarkus Armbruster case QCRYPTO_BLOCK_FORMAT_LUKS:
321860900b7bSKevin Wolf fmt = QCOW_CRYPT_LUKS;
321960900b7bSKevin Wolf break;
3220d23d2ef3SMarkus Armbruster case QCRYPTO_BLOCK_FORMAT_QCOW:
322160900b7bSKevin Wolf fmt = QCOW_CRYPT_AES;
322260900b7bSKevin Wolf break;
322360900b7bSKevin Wolf default:
322460900b7bSKevin Wolf error_setg(errp, "Crypto format not supported in qcow2");
322560900b7bSKevin Wolf return -EINVAL;
322660900b7bSKevin Wolf }
322760900b7bSKevin Wolf
32284652b8f3SDaniel P. Berrange s->crypt_method_header = fmt;
3229b25b387fSDaniel P. Berrange
32301cd9a787SDaniel P. Berrange crypto = qcrypto_block_create(cryptoopts, "encrypt.",
32314652b8f3SDaniel P. Berrange qcow2_crypto_hdr_init_func,
32324652b8f3SDaniel P. Berrange qcow2_crypto_hdr_write_func,
3233d74523a3SHyman Huang bs, 0, errp);
3234b25b387fSDaniel P. Berrange if (!crypto) {
323560900b7bSKevin Wolf return -EINVAL;
3236b25b387fSDaniel P. Berrange }
3237b25b387fSDaniel P. Berrange
3238b25b387fSDaniel P. Berrange ret = qcow2_update_header(bs);
3239b25b387fSDaniel P. Berrange if (ret < 0) {
3240b25b387fSDaniel P. Berrange error_setg_errno(errp, -ret, "Could not write encryption header");
3241b25b387fSDaniel P. Berrange goto out;
3242b25b387fSDaniel P. Berrange }
3243b25b387fSDaniel P. Berrange
324460900b7bSKevin Wolf ret = 0;
3245b25b387fSDaniel P. Berrange out:
3246b25b387fSDaniel P. Berrange qcrypto_block_free(crypto);
3247b25b387fSDaniel P. Berrange return ret;
3248b25b387fSDaniel P. Berrange }
3249b25b387fSDaniel P. Berrange
32507bc45dc1SMax Reitz /**
32517bc45dc1SMax Reitz * Preallocates metadata structures for data clusters between @offset (in the
32527bc45dc1SMax Reitz * guest disk) and @new_length (which is thus generally the new guest disk
32537bc45dc1SMax Reitz * size).
32547bc45dc1SMax Reitz *
32557bc45dc1SMax Reitz * Returns: 0 on success, -errno on failure.
32567bc45dc1SMax Reitz */
3257c2b8e315SKevin Wolf static int coroutine_fn GRAPH_RDLOCK
preallocate_co(BlockDriverState * bs,uint64_t offset,uint64_t new_length,PreallocMode mode,Error ** errp)3258c2b8e315SKevin Wolf preallocate_co(BlockDriverState *bs, uint64_t offset, uint64_t new_length,
3259c2b8e315SKevin Wolf PreallocMode mode, Error **errp)
3260a35e1c17SKevin Wolf {
326193e32b3eSKevin Wolf BDRVQcow2State *s = bs->opaque;
3262d46a0bb2SKevin Wolf uint64_t bytes;
3263060bee89SKevin Wolf uint64_t host_offset = 0;
3264718c0fceSKevin Wolf int64_t file_length;
3265d46a0bb2SKevin Wolf unsigned int cur_bytes;
3266148da7eaSKevin Wolf int ret;
32671a52b73dSAlberto Garcia QCowL2Meta *meta = NULL, *m;
3268a35e1c17SKevin Wolf
32697bc45dc1SMax Reitz assert(offset <= new_length);
32707bc45dc1SMax Reitz bytes = new_length - offset;
3271a35e1c17SKevin Wolf
3272d46a0bb2SKevin Wolf while (bytes) {
3273f29fbf7cSKevin Wolf cur_bytes = MIN(bytes, QEMU_ALIGN_DOWN(INT_MAX, s->cluster_size));
3274bfd0989aSAlberto Garcia ret = qcow2_alloc_host_offset(bs, offset, &cur_bytes,
3275060bee89SKevin Wolf &host_offset, &meta);
3276148da7eaSKevin Wolf if (ret < 0) {
3277360bd074SKevin Wolf error_setg_errno(errp, -ret, "Allocating clusters failed");
32781a52b73dSAlberto Garcia goto out;
3279a35e1c17SKevin Wolf }
3280a35e1c17SKevin Wolf
32811a52b73dSAlberto Garcia for (m = meta; m != NULL; m = m->next) {
32821a52b73dSAlberto Garcia m->prealloc = true;
32831a52b73dSAlberto Garcia }
3284c792707fSStefan Hajnoczi
32851a52b73dSAlberto Garcia ret = qcow2_handle_l2meta(bs, &meta, true);
328619dbcbf7SKevin Wolf if (ret < 0) {
3287360bd074SKevin Wolf error_setg_errno(errp, -ret, "Mapping clusters failed");
32881a52b73dSAlberto Garcia goto out;
3289f50f88b9SKevin Wolf }
3290f214978aSKevin Wolf
3291a35e1c17SKevin Wolf /* TODO Preallocate data if requested */
3292a35e1c17SKevin Wolf
3293d46a0bb2SKevin Wolf bytes -= cur_bytes;
3294d46a0bb2SKevin Wolf offset += cur_bytes;
3295a35e1c17SKevin Wolf }
3296a35e1c17SKevin Wolf
3297a35e1c17SKevin Wolf /*
3298a35e1c17SKevin Wolf * It is expected that the image file is large enough to actually contain
3299a35e1c17SKevin Wolf * all of the allocated clusters (otherwise we get failing reads after
3300a35e1c17SKevin Wolf * EOF). Extend the image to the last allocated sector.
3301a35e1c17SKevin Wolf */
33020050c163SKevin Wolf file_length = bdrv_co_getlength(s->data_file->bs);
3303718c0fceSKevin Wolf if (file_length < 0) {
3304718c0fceSKevin Wolf error_setg_errno(errp, -file_length, "Could not get file size");
33051a52b73dSAlberto Garcia ret = file_length;
33061a52b73dSAlberto Garcia goto out;
3307718c0fceSKevin Wolf }
3308718c0fceSKevin Wolf
3309718c0fceSKevin Wolf if (host_offset + cur_bytes > file_length) {
3310718c0fceSKevin Wolf if (mode == PREALLOC_MODE_METADATA) {
3311718c0fceSKevin Wolf mode = PREALLOC_MODE_OFF;
3312718c0fceSKevin Wolf }
3313c80d8b06SMax Reitz ret = bdrv_co_truncate(s->data_file, host_offset + cur_bytes, false,
33147b8e4857SKevin Wolf mode, 0, errp);
331519dbcbf7SKevin Wolf if (ret < 0) {
33161a52b73dSAlberto Garcia goto out;
331719dbcbf7SKevin Wolf }
3318a35e1c17SKevin Wolf }
3319a35e1c17SKevin Wolf
33201a52b73dSAlberto Garcia ret = 0;
33211a52b73dSAlberto Garcia
33221a52b73dSAlberto Garcia out:
33231a52b73dSAlberto Garcia qcow2_handle_l2meta(bs, &meta, false);
33241a52b73dSAlberto Garcia return ret;
3325a35e1c17SKevin Wolf }
3326a35e1c17SKevin Wolf
33277c5bcc42SStefan Hajnoczi /* qcow2_refcount_metadata_size:
33287c5bcc42SStefan Hajnoczi * @clusters: number of clusters to refcount (including data and L1/L2 tables)
33297c5bcc42SStefan Hajnoczi * @cluster_size: size of a cluster, in bytes
33307c5bcc42SStefan Hajnoczi * @refcount_order: refcount bits power-of-2 exponent
333112cc30a8SMax Reitz * @generous_increase: allow for the refcount table to be 1.5x as large as it
333212cc30a8SMax Reitz * needs to be
33337c5bcc42SStefan Hajnoczi *
33347c5bcc42SStefan Hajnoczi * Returns: Number of bytes required for refcount blocks and table metadata.
33357c5bcc42SStefan Hajnoczi */
qcow2_refcount_metadata_size(int64_t clusters,size_t cluster_size,int refcount_order,bool generous_increase,uint64_t * refblock_count)333612cc30a8SMax Reitz int64_t qcow2_refcount_metadata_size(int64_t clusters, size_t cluster_size,
333712cc30a8SMax Reitz int refcount_order, bool generous_increase,
333812cc30a8SMax Reitz uint64_t *refblock_count)
33397c5bcc42SStefan Hajnoczi {
33407c5bcc42SStefan Hajnoczi /*
33417c5bcc42SStefan Hajnoczi * Every host cluster is reference-counted, including metadata (even
33427c5bcc42SStefan Hajnoczi * refcount metadata is recursively included).
33437c5bcc42SStefan Hajnoczi *
33447c5bcc42SStefan Hajnoczi * An accurate formula for the size of refcount metadata size is difficult
33457c5bcc42SStefan Hajnoczi * to derive. An easier method of calculation is finding the fixed point
33467c5bcc42SStefan Hajnoczi * where no further refcount blocks or table clusters are required to
33477c5bcc42SStefan Hajnoczi * reference count every cluster.
33487c5bcc42SStefan Hajnoczi */
334902b1ecfaSAlberto Garcia int64_t blocks_per_table_cluster = cluster_size / REFTABLE_ENTRY_SIZE;
33507c5bcc42SStefan Hajnoczi int64_t refcounts_per_block = cluster_size * 8 / (1 << refcount_order);
33517c5bcc42SStefan Hajnoczi int64_t table = 0; /* number of refcount table clusters */
33527c5bcc42SStefan Hajnoczi int64_t blocks = 0; /* number of refcount block clusters */
33537c5bcc42SStefan Hajnoczi int64_t last;
33547c5bcc42SStefan Hajnoczi int64_t n = 0;
33557c5bcc42SStefan Hajnoczi
33567c5bcc42SStefan Hajnoczi do {
33577c5bcc42SStefan Hajnoczi last = n;
33587c5bcc42SStefan Hajnoczi blocks = DIV_ROUND_UP(clusters + table + blocks, refcounts_per_block);
33597c5bcc42SStefan Hajnoczi table = DIV_ROUND_UP(blocks, blocks_per_table_cluster);
33607c5bcc42SStefan Hajnoczi n = clusters + blocks + table;
336112cc30a8SMax Reitz
336212cc30a8SMax Reitz if (n == last && generous_increase) {
336312cc30a8SMax Reitz clusters += DIV_ROUND_UP(table, 2);
336412cc30a8SMax Reitz n = 0; /* force another loop */
336512cc30a8SMax Reitz generous_increase = false;
336612cc30a8SMax Reitz }
33677c5bcc42SStefan Hajnoczi } while (n != last);
33687c5bcc42SStefan Hajnoczi
336912cc30a8SMax Reitz if (refblock_count) {
337012cc30a8SMax Reitz *refblock_count = blocks;
337112cc30a8SMax Reitz }
337212cc30a8SMax Reitz
33737c5bcc42SStefan Hajnoczi return (blocks + table) * cluster_size;
33747c5bcc42SStefan Hajnoczi }
33757c5bcc42SStefan Hajnoczi
337695c67e3bSStefan Hajnoczi /**
337795c67e3bSStefan Hajnoczi * qcow2_calc_prealloc_size:
337895c67e3bSStefan Hajnoczi * @total_size: virtual disk size in bytes
337995c67e3bSStefan Hajnoczi * @cluster_size: cluster size in bytes
338095c67e3bSStefan Hajnoczi * @refcount_order: refcount bits power-of-2 exponent
33810dd07b29SAlberto Garcia * @extended_l2: true if the image has extended L2 entries
3382a9420734SKevin Wolf *
338395c67e3bSStefan Hajnoczi * Returns: Total number of bytes required for the fully allocated image
338495c67e3bSStefan Hajnoczi * (including metadata).
3385a9420734SKevin Wolf */
qcow2_calc_prealloc_size(int64_t total_size,size_t cluster_size,int refcount_order,bool extended_l2)338695c67e3bSStefan Hajnoczi static int64_t qcow2_calc_prealloc_size(int64_t total_size,
338795c67e3bSStefan Hajnoczi size_t cluster_size,
33880dd07b29SAlberto Garcia int refcount_order,
33890dd07b29SAlberto Garcia bool extended_l2)
339095c67e3bSStefan Hajnoczi {
33910e4271b7SHu Tao int64_t meta_size = 0;
33927c5bcc42SStefan Hajnoczi uint64_t nl1e, nl2e;
33939e029689SAlberto Garcia int64_t aligned_total_size = ROUND_UP(total_size, cluster_size);
33940dd07b29SAlberto Garcia size_t l2e_size = extended_l2 ? L2E_SIZE_EXTENDED : L2E_SIZE_NORMAL;
33950e4271b7SHu Tao
33960e4271b7SHu Tao /* header: 1 cluster */
33970e4271b7SHu Tao meta_size += cluster_size;
33980e4271b7SHu Tao
33990e4271b7SHu Tao /* total size of L2 tables */
34000e4271b7SHu Tao nl2e = aligned_total_size / cluster_size;
34010dd07b29SAlberto Garcia nl2e = ROUND_UP(nl2e, cluster_size / l2e_size);
34020dd07b29SAlberto Garcia meta_size += nl2e * l2e_size;
34030e4271b7SHu Tao
34040e4271b7SHu Tao /* total size of L1 tables */
34050dd07b29SAlberto Garcia nl1e = nl2e * l2e_size / cluster_size;
340602b1ecfaSAlberto Garcia nl1e = ROUND_UP(nl1e, cluster_size / L1E_SIZE);
340702b1ecfaSAlberto Garcia meta_size += nl1e * L1E_SIZE;
34080e4271b7SHu Tao
34097c5bcc42SStefan Hajnoczi /* total size of refcount table and blocks */
34107c5bcc42SStefan Hajnoczi meta_size += qcow2_refcount_metadata_size(
34117c5bcc42SStefan Hajnoczi (meta_size + aligned_total_size) / cluster_size,
341212cc30a8SMax Reitz cluster_size, refcount_order, false, NULL);
34130e4271b7SHu Tao
341495c67e3bSStefan Hajnoczi return meta_size + aligned_total_size;
341595c67e3bSStefan Hajnoczi }
341695c67e3bSStefan Hajnoczi
validate_cluster_size(size_t cluster_size,bool extended_l2,Error ** errp)34177be20252SAlberto Garcia static bool validate_cluster_size(size_t cluster_size, bool extended_l2,
34187be20252SAlberto Garcia Error **errp)
341995c67e3bSStefan Hajnoczi {
342029ca9e45SKevin Wolf int cluster_bits = ctz32(cluster_size);
342195c67e3bSStefan Hajnoczi if (cluster_bits < MIN_CLUSTER_BITS || cluster_bits > MAX_CLUSTER_BITS ||
342295c67e3bSStefan Hajnoczi (1 << cluster_bits) != cluster_size)
342395c67e3bSStefan Hajnoczi {
342495c67e3bSStefan Hajnoczi error_setg(errp, "Cluster size must be a power of two between %d and "
342595c67e3bSStefan Hajnoczi "%dk", 1 << MIN_CLUSTER_BITS, 1 << (MAX_CLUSTER_BITS - 10));
342629ca9e45SKevin Wolf return false;
342729ca9e45SKevin Wolf }
34287be20252SAlberto Garcia
34297be20252SAlberto Garcia if (extended_l2) {
34307be20252SAlberto Garcia unsigned min_cluster_size =
34317be20252SAlberto Garcia (1 << MIN_CLUSTER_BITS) * QCOW_EXTL2_SUBCLUSTERS_PER_CLUSTER;
34327be20252SAlberto Garcia if (cluster_size < min_cluster_size) {
34337be20252SAlberto Garcia error_setg(errp, "Extended L2 entries are only supported with "
34347be20252SAlberto Garcia "cluster sizes of at least %u bytes", min_cluster_size);
34357be20252SAlberto Garcia return false;
34367be20252SAlberto Garcia }
34377be20252SAlberto Garcia }
34387be20252SAlberto Garcia
343929ca9e45SKevin Wolf return true;
344029ca9e45SKevin Wolf }
344129ca9e45SKevin Wolf
qcow2_opt_get_cluster_size_del(QemuOpts * opts,bool extended_l2,Error ** errp)34427be20252SAlberto Garcia static size_t qcow2_opt_get_cluster_size_del(QemuOpts *opts, bool extended_l2,
34437be20252SAlberto Garcia Error **errp)
344429ca9e45SKevin Wolf {
344529ca9e45SKevin Wolf size_t cluster_size;
344629ca9e45SKevin Wolf
344729ca9e45SKevin Wolf cluster_size = qemu_opt_get_size_del(opts, BLOCK_OPT_CLUSTER_SIZE,
344829ca9e45SKevin Wolf DEFAULT_CLUSTER_SIZE);
34497be20252SAlberto Garcia if (!validate_cluster_size(cluster_size, extended_l2, errp)) {
34500eb4a8c1SStefan Hajnoczi return 0;
345195c67e3bSStefan Hajnoczi }
34520eb4a8c1SStefan Hajnoczi return cluster_size;
34530eb4a8c1SStefan Hajnoczi }
34540eb4a8c1SStefan Hajnoczi
qcow2_opt_get_version_del(QemuOpts * opts,Error ** errp)34550eb4a8c1SStefan Hajnoczi static int qcow2_opt_get_version_del(QemuOpts *opts, Error **errp)
34560eb4a8c1SStefan Hajnoczi {
34570eb4a8c1SStefan Hajnoczi char *buf;
34580eb4a8c1SStefan Hajnoczi int ret;
34590eb4a8c1SStefan Hajnoczi
34600eb4a8c1SStefan Hajnoczi buf = qemu_opt_get_del(opts, BLOCK_OPT_COMPAT_LEVEL);
34610eb4a8c1SStefan Hajnoczi if (!buf) {
34620eb4a8c1SStefan Hajnoczi ret = 3; /* default */
34630eb4a8c1SStefan Hajnoczi } else if (!strcmp(buf, "0.10")) {
34640eb4a8c1SStefan Hajnoczi ret = 2;
34650eb4a8c1SStefan Hajnoczi } else if (!strcmp(buf, "1.1")) {
34660eb4a8c1SStefan Hajnoczi ret = 3;
34670eb4a8c1SStefan Hajnoczi } else {
34680eb4a8c1SStefan Hajnoczi error_setg(errp, "Invalid compatibility level: '%s'", buf);
34690eb4a8c1SStefan Hajnoczi ret = -EINVAL;
34700eb4a8c1SStefan Hajnoczi }
34710eb4a8c1SStefan Hajnoczi g_free(buf);
34720eb4a8c1SStefan Hajnoczi return ret;
34730eb4a8c1SStefan Hajnoczi }
34740eb4a8c1SStefan Hajnoczi
qcow2_opt_get_refcount_bits_del(QemuOpts * opts,int version,Error ** errp)34750eb4a8c1SStefan Hajnoczi static uint64_t qcow2_opt_get_refcount_bits_del(QemuOpts *opts, int version,
34760eb4a8c1SStefan Hajnoczi Error **errp)
34770eb4a8c1SStefan Hajnoczi {
34780eb4a8c1SStefan Hajnoczi uint64_t refcount_bits;
34790eb4a8c1SStefan Hajnoczi
34800eb4a8c1SStefan Hajnoczi refcount_bits = qemu_opt_get_number_del(opts, BLOCK_OPT_REFCOUNT_BITS, 16);
34810eb4a8c1SStefan Hajnoczi if (refcount_bits > 64 || !is_power_of_2(refcount_bits)) {
34820eb4a8c1SStefan Hajnoczi error_setg(errp, "Refcount width must be a power of two and may not "
34830eb4a8c1SStefan Hajnoczi "exceed 64 bits");
34840eb4a8c1SStefan Hajnoczi return 0;
34850eb4a8c1SStefan Hajnoczi }
34860eb4a8c1SStefan Hajnoczi
34870eb4a8c1SStefan Hajnoczi if (version < 3 && refcount_bits != 16) {
34880eb4a8c1SStefan Hajnoczi error_setg(errp, "Different refcount widths than 16 bits require "
34890eb4a8c1SStefan Hajnoczi "compatibility level 1.1 or above (use compat=1.1 or "
34900eb4a8c1SStefan Hajnoczi "greater)");
34910eb4a8c1SStefan Hajnoczi return 0;
34920eb4a8c1SStefan Hajnoczi }
34930eb4a8c1SStefan Hajnoczi
34940eb4a8c1SStefan Hajnoczi return refcount_bits;
34950eb4a8c1SStefan Hajnoczi }
34960eb4a8c1SStefan Hajnoczi
34974db7ba3bSKevin Wolf static int coroutine_fn GRAPH_UNLOCKED
qcow2_co_create(BlockdevCreateOptions * create_options,Error ** errp)349860900b7bSKevin Wolf qcow2_co_create(BlockdevCreateOptions *create_options, Error **errp)
34990eb4a8c1SStefan Hajnoczi {
3500d13e3b46SZhao Liu ERRP_GUARD();
350129ca9e45SKevin Wolf BlockdevCreateOptionsQcow2 *qcow2_opts;
35020eb4a8c1SStefan Hajnoczi QDict *options;
350395c67e3bSStefan Hajnoczi
350495c67e3bSStefan Hajnoczi /*
350595c67e3bSStefan Hajnoczi * Open the image file and write a minimal qcow2 header.
350695c67e3bSStefan Hajnoczi *
350795c67e3bSStefan Hajnoczi * We keep things simple and start with a zero-sized image. We also
350895c67e3bSStefan Hajnoczi * do without refcount blocks or a L1 table for now. We'll fix the
350995c67e3bSStefan Hajnoczi * inconsistency later.
351095c67e3bSStefan Hajnoczi *
351195c67e3bSStefan Hajnoczi * We do need a refcount table because growing the refcount table means
3512a951a631SEric Blake * allocating two new refcount blocks - the second of which would be at
351395c67e3bSStefan Hajnoczi * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
351495c67e3bSStefan Hajnoczi * size for any qcow2 image.
351595c67e3bSStefan Hajnoczi */
3516e1d74bc6SKevin Wolf BlockBackend *blk = NULL;
3517e1d74bc6SKevin Wolf BlockDriverState *bs = NULL;
3518dcc98687SKevin Wolf BlockDriverState *data_bs = NULL;
351995c67e3bSStefan Hajnoczi QCowHeader *header;
352029ca9e45SKevin Wolf size_t cluster_size;
352129ca9e45SKevin Wolf int version;
352229ca9e45SKevin Wolf int refcount_order;
352395c67e3bSStefan Hajnoczi uint64_t *refcount_table;
352495c67e3bSStefan Hajnoczi int ret;
3525572ad978SDenis Plotnikov uint8_t compression_type = QCOW2_COMPRESSION_TYPE_ZLIB;
352695c67e3bSStefan Hajnoczi
352729ca9e45SKevin Wolf assert(create_options->driver == BLOCKDEV_DRIVER_QCOW2);
352829ca9e45SKevin Wolf qcow2_opts = &create_options->u.qcow2;
352929ca9e45SKevin Wolf
3530ecbc57caSKevin Wolf bs = bdrv_co_open_blockdev_ref(qcow2_opts->file, errp);
3531e1d74bc6SKevin Wolf if (bs == NULL) {
3532e1d74bc6SKevin Wolf return -EIO;
3533e1d74bc6SKevin Wolf }
3534e1d74bc6SKevin Wolf
3535e1d74bc6SKevin Wolf /* Validate options and set default values */
353629ca9e45SKevin Wolf if (!QEMU_IS_ALIGNED(qcow2_opts->size, BDRV_SECTOR_SIZE)) {
35373afea402SAlberto Garcia error_setg(errp, "Image size must be a multiple of %u bytes",
35383afea402SAlberto Garcia (unsigned) BDRV_SECTOR_SIZE);
353929ca9e45SKevin Wolf ret = -EINVAL;
354029ca9e45SKevin Wolf goto out;
354129ca9e45SKevin Wolf }
354229ca9e45SKevin Wolf
354329ca9e45SKevin Wolf if (qcow2_opts->has_version) {
354429ca9e45SKevin Wolf switch (qcow2_opts->version) {
354529ca9e45SKevin Wolf case BLOCKDEV_QCOW2_VERSION_V2:
354629ca9e45SKevin Wolf version = 2;
354729ca9e45SKevin Wolf break;
354829ca9e45SKevin Wolf case BLOCKDEV_QCOW2_VERSION_V3:
354929ca9e45SKevin Wolf version = 3;
355029ca9e45SKevin Wolf break;
355129ca9e45SKevin Wolf default:
355229ca9e45SKevin Wolf g_assert_not_reached();
355329ca9e45SKevin Wolf }
355429ca9e45SKevin Wolf } else {
355529ca9e45SKevin Wolf version = 3;
355629ca9e45SKevin Wolf }
355729ca9e45SKevin Wolf
355829ca9e45SKevin Wolf if (qcow2_opts->has_cluster_size) {
355929ca9e45SKevin Wolf cluster_size = qcow2_opts->cluster_size;
356029ca9e45SKevin Wolf } else {
356129ca9e45SKevin Wolf cluster_size = DEFAULT_CLUSTER_SIZE;
356229ca9e45SKevin Wolf }
356329ca9e45SKevin Wolf
35647be20252SAlberto Garcia if (!qcow2_opts->has_extended_l2) {
35657be20252SAlberto Garcia qcow2_opts->extended_l2 = false;
35667be20252SAlberto Garcia }
35677be20252SAlberto Garcia if (qcow2_opts->extended_l2) {
35687be20252SAlberto Garcia if (version < 3) {
35697be20252SAlberto Garcia error_setg(errp, "Extended L2 entries are only supported with "
35707be20252SAlberto Garcia "compatibility level 1.1 and above (use version=v3 or "
35717be20252SAlberto Garcia "greater)");
35727be20252SAlberto Garcia ret = -EINVAL;
35737be20252SAlberto Garcia goto out;
35747be20252SAlberto Garcia }
35757be20252SAlberto Garcia }
35767be20252SAlberto Garcia
35777be20252SAlberto Garcia if (!validate_cluster_size(cluster_size, qcow2_opts->extended_l2, errp)) {
3578e1d74bc6SKevin Wolf ret = -EINVAL;
3579e1d74bc6SKevin Wolf goto out;
358029ca9e45SKevin Wolf }
358129ca9e45SKevin Wolf
358229ca9e45SKevin Wolf if (!qcow2_opts->has_preallocation) {
358329ca9e45SKevin Wolf qcow2_opts->preallocation = PREALLOC_MODE_OFF;
358429ca9e45SKevin Wolf }
358554fde4ffSMarkus Armbruster if (qcow2_opts->backing_file &&
35862118771dSAlberto Garcia qcow2_opts->preallocation != PREALLOC_MODE_OFF &&
35872118771dSAlberto Garcia !qcow2_opts->extended_l2)
358829ca9e45SKevin Wolf {
35892118771dSAlberto Garcia error_setg(errp, "Backing file and preallocation can only be used at "
35902118771dSAlberto Garcia "the same time if extended_l2 is on");
3591e1d74bc6SKevin Wolf ret = -EINVAL;
3592e1d74bc6SKevin Wolf goto out;
359329ca9e45SKevin Wolf }
359454fde4ffSMarkus Armbruster if (qcow2_opts->has_backing_fmt && !qcow2_opts->backing_file) {
359529ca9e45SKevin Wolf error_setg(errp, "Backing format cannot be used without backing file");
3596e1d74bc6SKevin Wolf ret = -EINVAL;
3597e1d74bc6SKevin Wolf goto out;
359829ca9e45SKevin Wolf }
359929ca9e45SKevin Wolf
360029ca9e45SKevin Wolf if (!qcow2_opts->has_lazy_refcounts) {
360129ca9e45SKevin Wolf qcow2_opts->lazy_refcounts = false;
360229ca9e45SKevin Wolf }
360329ca9e45SKevin Wolf if (version < 3 && qcow2_opts->lazy_refcounts) {
360429ca9e45SKevin Wolf error_setg(errp, "Lazy refcounts only supported with compatibility "
3605b76b4f60SKevin Wolf "level 1.1 and above (use version=v3 or greater)");
3606e1d74bc6SKevin Wolf ret = -EINVAL;
3607e1d74bc6SKevin Wolf goto out;
360829ca9e45SKevin Wolf }
360929ca9e45SKevin Wolf
361029ca9e45SKevin Wolf if (!qcow2_opts->has_refcount_bits) {
361129ca9e45SKevin Wolf qcow2_opts->refcount_bits = 16;
361229ca9e45SKevin Wolf }
361329ca9e45SKevin Wolf if (qcow2_opts->refcount_bits > 64 ||
361429ca9e45SKevin Wolf !is_power_of_2(qcow2_opts->refcount_bits))
361529ca9e45SKevin Wolf {
361629ca9e45SKevin Wolf error_setg(errp, "Refcount width must be a power of two and may not "
361729ca9e45SKevin Wolf "exceed 64 bits");
3618e1d74bc6SKevin Wolf ret = -EINVAL;
3619e1d74bc6SKevin Wolf goto out;
362029ca9e45SKevin Wolf }
362129ca9e45SKevin Wolf if (version < 3 && qcow2_opts->refcount_bits != 16) {
362229ca9e45SKevin Wolf error_setg(errp, "Different refcount widths than 16 bits require "
3623b76b4f60SKevin Wolf "compatibility level 1.1 or above (use version=v3 or "
362429ca9e45SKevin Wolf "greater)");
3625e1d74bc6SKevin Wolf ret = -EINVAL;
3626e1d74bc6SKevin Wolf goto out;
362729ca9e45SKevin Wolf }
362829ca9e45SKevin Wolf refcount_order = ctz32(qcow2_opts->refcount_bits);
362929ca9e45SKevin Wolf
36306c3944dcSKevin Wolf if (qcow2_opts->data_file_raw && !qcow2_opts->data_file) {
36316c3944dcSKevin Wolf error_setg(errp, "data-file-raw requires data-file");
36326c3944dcSKevin Wolf ret = -EINVAL;
36336c3944dcSKevin Wolf goto out;
36346c3944dcSKevin Wolf }
363554fde4ffSMarkus Armbruster if (qcow2_opts->data_file_raw && qcow2_opts->backing_file) {
36366c3944dcSKevin Wolf error_setg(errp, "Backing file and data-file-raw cannot be used at "
36376c3944dcSKevin Wolf "the same time");
36386c3944dcSKevin Wolf ret = -EINVAL;
36396c3944dcSKevin Wolf goto out;
36406c3944dcSKevin Wolf }
364148410829SMax Reitz if (qcow2_opts->data_file_raw &&
364248410829SMax Reitz qcow2_opts->preallocation == PREALLOC_MODE_OFF)
364348410829SMax Reitz {
364448410829SMax Reitz /*
364548410829SMax Reitz * data-file-raw means that "the external data file can be
364648410829SMax Reitz * read as a consistent standalone raw image without looking
364748410829SMax Reitz * at the qcow2 metadata." It does not say that the metadata
364848410829SMax Reitz * must be ignored, though (and the qcow2 driver in fact does
364948410829SMax Reitz * not ignore it), so the L1/L2 tables must be present and
365048410829SMax Reitz * give a 1:1 mapping, so you get the same result regardless
365148410829SMax Reitz * of whether you look at the metadata or whether you ignore
365248410829SMax Reitz * it.
365348410829SMax Reitz */
365448410829SMax Reitz qcow2_opts->preallocation = PREALLOC_MODE_METADATA;
365548410829SMax Reitz
365648410829SMax Reitz /*
365748410829SMax Reitz * Cannot use preallocation with backing files, but giving a
365848410829SMax Reitz * backing file when specifying data_file_raw is an error
365948410829SMax Reitz * anyway.
366048410829SMax Reitz */
366154fde4ffSMarkus Armbruster assert(!qcow2_opts->backing_file);
366248410829SMax Reitz }
36636c3944dcSKevin Wolf
3664dcc98687SKevin Wolf if (qcow2_opts->data_file) {
3665dcc98687SKevin Wolf if (version < 3) {
3666dcc98687SKevin Wolf error_setg(errp, "External data files are only supported with "
3667dcc98687SKevin Wolf "compatibility level 1.1 and above (use version=v3 or "
3668dcc98687SKevin Wolf "greater)");
3669dcc98687SKevin Wolf ret = -EINVAL;
3670dcc98687SKevin Wolf goto out;
3671dcc98687SKevin Wolf }
3672ecbc57caSKevin Wolf data_bs = bdrv_co_open_blockdev_ref(qcow2_opts->data_file, errp);
3673a0cf8363SKevin Wolf if (data_bs == NULL) {
3674dcc98687SKevin Wolf ret = -EIO;
3675dcc98687SKevin Wolf goto out;
3676dcc98687SKevin Wolf }
3677dcc98687SKevin Wolf }
367829ca9e45SKevin Wolf
3679572ad978SDenis Plotnikov if (qcow2_opts->has_compression_type &&
3680572ad978SDenis Plotnikov qcow2_opts->compression_type != QCOW2_COMPRESSION_TYPE_ZLIB) {
3681572ad978SDenis Plotnikov
3682572ad978SDenis Plotnikov ret = -EINVAL;
3683572ad978SDenis Plotnikov
3684572ad978SDenis Plotnikov if (version < 3) {
3685572ad978SDenis Plotnikov error_setg(errp, "Non-zlib compression type is only supported with "
3686572ad978SDenis Plotnikov "compatibility level 1.1 and above (use version=v3 or "
3687572ad978SDenis Plotnikov "greater)");
3688572ad978SDenis Plotnikov goto out;
3689572ad978SDenis Plotnikov }
3690572ad978SDenis Plotnikov
3691572ad978SDenis Plotnikov switch (qcow2_opts->compression_type) {
3692d298ac10SDenis Plotnikov #ifdef CONFIG_ZSTD
3693d298ac10SDenis Plotnikov case QCOW2_COMPRESSION_TYPE_ZSTD:
3694d298ac10SDenis Plotnikov break;
3695d298ac10SDenis Plotnikov #endif
3696572ad978SDenis Plotnikov default:
3697572ad978SDenis Plotnikov error_setg(errp, "Unknown compression type");
3698572ad978SDenis Plotnikov goto out;
3699572ad978SDenis Plotnikov }
3700572ad978SDenis Plotnikov
3701572ad978SDenis Plotnikov compression_type = qcow2_opts->compression_type;
3702572ad978SDenis Plotnikov }
3703572ad978SDenis Plotnikov
370429ca9e45SKevin Wolf /* Create BlockBackend to write to the image */
3705ecbc57caSKevin Wolf blk = blk_co_new_with_bs(bs, BLK_PERM_WRITE | BLK_PERM_RESIZE, BLK_PERM_ALL,
3706a3aeeab5SEric Blake errp);
3707a3aeeab5SEric Blake if (!blk) {
3708a3aeeab5SEric Blake ret = -EPERM;
3709cbf2b7c4SKevin Wolf goto out;
3710a9420734SKevin Wolf }
371123588797SKevin Wolf blk_set_allow_write_beyond_eof(blk, true);
371223588797SKevin Wolf
3713a9420734SKevin Wolf /* Write the header */
3714f8413b3cSKevin Wolf QEMU_BUILD_BUG_ON((1 << MIN_CLUSTER_BITS) < sizeof(*header));
3715f8413b3cSKevin Wolf header = g_malloc0(cluster_size);
3716f8413b3cSKevin Wolf *header = (QCowHeader) {
3717f8413b3cSKevin Wolf .magic = cpu_to_be32(QCOW_MAGIC),
3718f8413b3cSKevin Wolf .version = cpu_to_be32(version),
37190eb4a8c1SStefan Hajnoczi .cluster_bits = cpu_to_be32(ctz32(cluster_size)),
3720f8413b3cSKevin Wolf .size = cpu_to_be64(0),
3721f8413b3cSKevin Wolf .l1_table_offset = cpu_to_be64(0),
3722f8413b3cSKevin Wolf .l1_size = cpu_to_be32(0),
3723f8413b3cSKevin Wolf .refcount_table_offset = cpu_to_be64(cluster_size),
3724f8413b3cSKevin Wolf .refcount_table_clusters = cpu_to_be32(1),
3725bd4b167fSMax Reitz .refcount_order = cpu_to_be32(refcount_order),
3726572ad978SDenis Plotnikov /* don't deal with endianness since compression_type is 1 byte long */
3727572ad978SDenis Plotnikov .compression_type = compression_type,
3728f8413b3cSKevin Wolf .header_length = cpu_to_be32(sizeof(*header)),
3729f8413b3cSKevin Wolf };
3730a9420734SKevin Wolf
3731b25b387fSDaniel P. Berrange /* We'll update this to correct value later */
3732f8413b3cSKevin Wolf header->crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
3733a9420734SKevin Wolf
373429ca9e45SKevin Wolf if (qcow2_opts->lazy_refcounts) {
3735f8413b3cSKevin Wolf header->compatible_features |=
3736bfe8043eSStefan Hajnoczi cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS);
3737bfe8043eSStefan Hajnoczi }
3738dcc98687SKevin Wolf if (data_bs) {
3739dcc98687SKevin Wolf header->incompatible_features |=
3740dcc98687SKevin Wolf cpu_to_be64(QCOW2_INCOMPAT_DATA_FILE);
3741dcc98687SKevin Wolf }
37426c3944dcSKevin Wolf if (qcow2_opts->data_file_raw) {
37436c3944dcSKevin Wolf header->autoclear_features |=
37446c3944dcSKevin Wolf cpu_to_be64(QCOW2_AUTOCLEAR_DATA_FILE_RAW);
37456c3944dcSKevin Wolf }
3746572ad978SDenis Plotnikov if (compression_type != QCOW2_COMPRESSION_TYPE_ZLIB) {
3747572ad978SDenis Plotnikov header->incompatible_features |=
3748572ad978SDenis Plotnikov cpu_to_be64(QCOW2_INCOMPAT_COMPRESSION);
3749572ad978SDenis Plotnikov }
3750bfe8043eSStefan Hajnoczi
37517be20252SAlberto Garcia if (qcow2_opts->extended_l2) {
37527be20252SAlberto Garcia header->incompatible_features |=
37537be20252SAlberto Garcia cpu_to_be64(QCOW2_INCOMPAT_EXTL2);
37547be20252SAlberto Garcia }
37557be20252SAlberto Garcia
375638505e2aSAlberto Faria ret = blk_co_pwrite(blk, 0, cluster_size, header, 0);
3757f8413b3cSKevin Wolf g_free(header);
3758a9420734SKevin Wolf if (ret < 0) {
37593ef6c40aSMax Reitz error_setg_errno(errp, -ret, "Could not write qcow2 header");
3760a9420734SKevin Wolf goto out;
3761a9420734SKevin Wolf }
3762a9420734SKevin Wolf
3763b106ad91SKevin Wolf /* Write a refcount table with one refcount block */
3764b106ad91SKevin Wolf refcount_table = g_malloc0(2 * cluster_size);
3765b106ad91SKevin Wolf refcount_table[0] = cpu_to_be64(2 * cluster_size);
376638505e2aSAlberto Faria ret = blk_co_pwrite(blk, cluster_size, 2 * cluster_size, refcount_table, 0);
37677267c094SAnthony Liguori g_free(refcount_table);
3768a9420734SKevin Wolf
3769a9420734SKevin Wolf if (ret < 0) {
37703ef6c40aSMax Reitz error_setg_errno(errp, -ret, "Could not write refcount table");
3771a9420734SKevin Wolf goto out;
3772a9420734SKevin Wolf }
3773a9420734SKevin Wolf
3774b2ab5f54SKevin Wolf blk_co_unref(blk);
377523588797SKevin Wolf blk = NULL;
3776a9420734SKevin Wolf
3777a9420734SKevin Wolf /*
3778a9420734SKevin Wolf * And now open the image and make it consistent first (i.e. increase the
3779a9420734SKevin Wolf * refcount of the cluster that is occupied by the header and the refcount
3780a9420734SKevin Wolf * table)
3781a9420734SKevin Wolf */
3782e6641719SMax Reitz options = qdict_new();
378346f5ac20SEric Blake qdict_put_str(options, "driver", "qcow2");
3784cbf2b7c4SKevin Wolf qdict_put_str(options, "file", bs->node_name);
3785dcc98687SKevin Wolf if (data_bs) {
3786dcc98687SKevin Wolf qdict_put_str(options, "data-file", data_bs->node_name);
3787dcc98687SKevin Wolf }
3788ecbc57caSKevin Wolf blk = blk_co_new_open(NULL, NULL, options,
378955880601SKevin Wolf BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_NO_FLUSH,
3790af175e85SMarkus Armbruster errp);
379123588797SKevin Wolf if (blk == NULL) {
379223588797SKevin Wolf ret = -EIO;
3793a9420734SKevin Wolf goto out;
3794a9420734SKevin Wolf }
3795a9420734SKevin Wolf
37964db7ba3bSKevin Wolf bdrv_graph_co_rdlock();
379723588797SKevin Wolf ret = qcow2_alloc_clusters(blk_bs(blk), 3 * cluster_size);
3798a9420734SKevin Wolf if (ret < 0) {
37994db7ba3bSKevin Wolf bdrv_graph_co_rdunlock();
38003ef6c40aSMax Reitz error_setg_errno(errp, -ret, "Could not allocate clusters for qcow2 "
38013ef6c40aSMax Reitz "header and refcount table");
3802a9420734SKevin Wolf goto out;
3803a9420734SKevin Wolf
3804a9420734SKevin Wolf } else if (ret != 0) {
3805a9420734SKevin Wolf error_report("Huh, first cluster in empty image is already in use?");
3806a9420734SKevin Wolf abort();
3807a9420734SKevin Wolf }
3808a9420734SKevin Wolf
38099b890bdcSKevin Wolf /* Set the external data file if necessary */
38109b890bdcSKevin Wolf if (data_bs) {
38119b890bdcSKevin Wolf BDRVQcow2State *s = blk_bs(blk)->opaque;
38129b890bdcSKevin Wolf s->image_data_file = g_strdup(data_bs->filename);
38139b890bdcSKevin Wolf }
38149b890bdcSKevin Wolf
3815b527c9b3SKevin Wolf /* Create a full header (including things like feature table) */
381623588797SKevin Wolf ret = qcow2_update_header(blk_bs(blk));
38174db7ba3bSKevin Wolf bdrv_graph_co_rdunlock();
38184db7ba3bSKevin Wolf
3819b527c9b3SKevin Wolf if (ret < 0) {
3820b527c9b3SKevin Wolf error_setg_errno(errp, -ret, "Could not update qcow2 header");
3821b527c9b3SKevin Wolf goto out;
3822b527c9b3SKevin Wolf }
3823b527c9b3SKevin Wolf
3824a9420734SKevin Wolf /* Okay, now that we have a valid image, let's give it the right size */
382538505e2aSAlberto Faria ret = blk_co_truncate(blk, qcow2_opts->size, false,
382638505e2aSAlberto Faria qcow2_opts->preallocation, 0, errp);
3827a9420734SKevin Wolf if (ret < 0) {
3828ed3d2ec9SMax Reitz error_prepend(errp, "Could not resize image: ");
3829a9420734SKevin Wolf goto out;
3830a9420734SKevin Wolf }
3831a9420734SKevin Wolf
3832a9420734SKevin Wolf /* Want a backing file? There you go. */
383354fde4ffSMarkus Armbruster if (qcow2_opts->backing_file) {
383429ca9e45SKevin Wolf const char *backing_format = NULL;
383529ca9e45SKevin Wolf
383629ca9e45SKevin Wolf if (qcow2_opts->has_backing_fmt) {
383729ca9e45SKevin Wolf backing_format = BlockdevDriver_str(qcow2_opts->backing_fmt);
383829ca9e45SKevin Wolf }
383929ca9e45SKevin Wolf
3840e2dd2737SKevin Wolf bdrv_graph_co_rdlock();
3841e2dd2737SKevin Wolf ret = bdrv_co_change_backing_file(blk_bs(blk), qcow2_opts->backing_file,
3842e54ee1b3SEric Blake backing_format, false);
3843e2dd2737SKevin Wolf bdrv_graph_co_rdunlock();
3844e2dd2737SKevin Wolf
3845a9420734SKevin Wolf if (ret < 0) {
38463ef6c40aSMax Reitz error_setg_errno(errp, -ret, "Could not assign backing file '%s' "
384729ca9e45SKevin Wolf "with format '%s'", qcow2_opts->backing_file,
384829ca9e45SKevin Wolf backing_format);
3849a9420734SKevin Wolf goto out;
3850a9420734SKevin Wolf }
3851a9420734SKevin Wolf }
3852a9420734SKevin Wolf
3853b25b387fSDaniel P. Berrange /* Want encryption? There you go. */
385454fde4ffSMarkus Armbruster if (qcow2_opts->encrypt) {
38554db7ba3bSKevin Wolf bdrv_graph_co_rdlock();
385660900b7bSKevin Wolf ret = qcow2_set_up_encryption(blk_bs(blk), qcow2_opts->encrypt, errp);
38574db7ba3bSKevin Wolf bdrv_graph_co_rdunlock();
38584db7ba3bSKevin Wolf
3859b25b387fSDaniel P. Berrange if (ret < 0) {
3860b25b387fSDaniel P. Berrange goto out;
3861b25b387fSDaniel P. Berrange }
3862b25b387fSDaniel P. Berrange }
3863b25b387fSDaniel P. Berrange
3864b2ab5f54SKevin Wolf blk_co_unref(blk);
386523588797SKevin Wolf blk = NULL;
3866ba2ab2f2SMax Reitz
3867b25b387fSDaniel P. Berrange /* Reopen the image without BDRV_O_NO_FLUSH to flush it before returning.
3868b25b387fSDaniel P. Berrange * Using BDRV_O_NO_IO, since encryption is now setup we don't want to
3869b25b387fSDaniel P. Berrange * have to setup decryption context. We're not doing any I/O on the top
3870b25b387fSDaniel P. Berrange * level BlockDriverState, only lower layers, where BDRV_O_NO_IO does
3871b25b387fSDaniel P. Berrange * not have effect.
3872b25b387fSDaniel P. Berrange */
3873e6641719SMax Reitz options = qdict_new();
387446f5ac20SEric Blake qdict_put_str(options, "driver", "qcow2");
3875cbf2b7c4SKevin Wolf qdict_put_str(options, "file", bs->node_name);
3876dcc98687SKevin Wolf if (data_bs) {
3877dcc98687SKevin Wolf qdict_put_str(options, "data-file", data_bs->node_name);
3878dcc98687SKevin Wolf }
3879ecbc57caSKevin Wolf blk = blk_co_new_open(NULL, NULL, options,
3880b25b387fSDaniel P. Berrange BDRV_O_RDWR | BDRV_O_NO_BACKING | BDRV_O_NO_IO,
3881af175e85SMarkus Armbruster errp);
388223588797SKevin Wolf if (blk == NULL) {
388323588797SKevin Wolf ret = -EIO;
3884ba2ab2f2SMax Reitz goto out;
3885ba2ab2f2SMax Reitz }
3886ba2ab2f2SMax Reitz
3887a9420734SKevin Wolf ret = 0;
3888a9420734SKevin Wolf out:
3889b2ab5f54SKevin Wolf blk_co_unref(blk);
3890b2ab5f54SKevin Wolf bdrv_co_unref(bs);
3891b2ab5f54SKevin Wolf bdrv_co_unref(data_bs);
3892a9420734SKevin Wolf return ret;
3893a9420734SKevin Wolf }
3894de5f3f40SKevin Wolf
38954db7ba3bSKevin Wolf static int coroutine_fn GRAPH_UNLOCKED
qcow2_co_create_opts(BlockDriver * drv,const char * filename,QemuOpts * opts,Error ** errp)38964ec8df01SKevin Wolf qcow2_co_create_opts(BlockDriver *drv, const char *filename, QemuOpts *opts,
3897efc75e2aSStefan Hajnoczi Error **errp)
3898de5f3f40SKevin Wolf {
3899b76b4f60SKevin Wolf BlockdevCreateOptions *create_options = NULL;
390092adf9dbSMarkus Armbruster QDict *qdict;
3901b76b4f60SKevin Wolf Visitor *v;
3902cbf2b7c4SKevin Wolf BlockDriverState *bs = NULL;
39039b890bdcSKevin Wolf BlockDriverState *data_bs = NULL;
3904b76b4f60SKevin Wolf const char *val;
39053ef6c40aSMax Reitz int ret;
3906de5f3f40SKevin Wolf
3907b76b4f60SKevin Wolf /* Only the keyval visitor supports the dotted syntax needed for
3908b76b4f60SKevin Wolf * encryption, so go through a QDict before getting a QAPI type. Ignore
3909b76b4f60SKevin Wolf * options meant for the protocol layer so that the visitor doesn't
3910b76b4f60SKevin Wolf * complain. */
3911b76b4f60SKevin Wolf qdict = qemu_opts_to_qdict_filtered(opts, NULL, bdrv_qcow2.create_opts,
3912b76b4f60SKevin Wolf true);
3913b76b4f60SKevin Wolf
3914b76b4f60SKevin Wolf /* Handle encryption options */
3915b76b4f60SKevin Wolf val = qdict_get_try_str(qdict, BLOCK_OPT_ENCRYPT);
3916b76b4f60SKevin Wolf if (val && !strcmp(val, "on")) {
3917b76b4f60SKevin Wolf qdict_put_str(qdict, BLOCK_OPT_ENCRYPT, "qcow");
3918b76b4f60SKevin Wolf } else if (val && !strcmp(val, "off")) {
3919b76b4f60SKevin Wolf qdict_del(qdict, BLOCK_OPT_ENCRYPT);
392029ca9e45SKevin Wolf }
392160900b7bSKevin Wolf
3922b76b4f60SKevin Wolf val = qdict_get_try_str(qdict, BLOCK_OPT_ENCRYPT_FORMAT);
3923b76b4f60SKevin Wolf if (val && !strcmp(val, "aes")) {
3924b76b4f60SKevin Wolf qdict_put_str(qdict, BLOCK_OPT_ENCRYPT_FORMAT, "qcow");
392560900b7bSKevin Wolf }
392660900b7bSKevin Wolf
3927b76b4f60SKevin Wolf /* Convert compat=0.10/1.1 into compat=v2/v3, to be renamed into
3928b76b4f60SKevin Wolf * version=v2/v3 below. */
3929b76b4f60SKevin Wolf val = qdict_get_try_str(qdict, BLOCK_OPT_COMPAT_LEVEL);
3930b76b4f60SKevin Wolf if (val && !strcmp(val, "0.10")) {
3931b76b4f60SKevin Wolf qdict_put_str(qdict, BLOCK_OPT_COMPAT_LEVEL, "v2");
3932b76b4f60SKevin Wolf } else if (val && !strcmp(val, "1.1")) {
3933b76b4f60SKevin Wolf qdict_put_str(qdict, BLOCK_OPT_COMPAT_LEVEL, "v3");
3934b76b4f60SKevin Wolf }
3935b76b4f60SKevin Wolf
3936b76b4f60SKevin Wolf /* Change legacy command line options into QMP ones */
3937b76b4f60SKevin Wolf static const QDictRenames opt_renames[] = {
3938b76b4f60SKevin Wolf { BLOCK_OPT_BACKING_FILE, "backing-file" },
3939b76b4f60SKevin Wolf { BLOCK_OPT_BACKING_FMT, "backing-fmt" },
3940b76b4f60SKevin Wolf { BLOCK_OPT_CLUSTER_SIZE, "cluster-size" },
3941b76b4f60SKevin Wolf { BLOCK_OPT_LAZY_REFCOUNTS, "lazy-refcounts" },
39427be20252SAlberto Garcia { BLOCK_OPT_EXTL2, "extended-l2" },
3943b76b4f60SKevin Wolf { BLOCK_OPT_REFCOUNT_BITS, "refcount-bits" },
3944b76b4f60SKevin Wolf { BLOCK_OPT_ENCRYPT, BLOCK_OPT_ENCRYPT_FORMAT },
3945b76b4f60SKevin Wolf { BLOCK_OPT_COMPAT_LEVEL, "version" },
39466c3944dcSKevin Wolf { BLOCK_OPT_DATA_FILE_RAW, "data-file-raw" },
3947572ad978SDenis Plotnikov { BLOCK_OPT_COMPRESSION_TYPE, "compression-type" },
3948b76b4f60SKevin Wolf { NULL, NULL },
3949b76b4f60SKevin Wolf };
3950b76b4f60SKevin Wolf
3951b76b4f60SKevin Wolf if (!qdict_rename_keys(qdict, opt_renames, errp)) {
39520eb4a8c1SStefan Hajnoczi ret = -EINVAL;
39530eb4a8c1SStefan Hajnoczi goto finish;
39540eb4a8c1SStefan Hajnoczi }
3955bd4b167fSMax Reitz
3956cbf2b7c4SKevin Wolf /* Create and open the file (protocol layer) */
39572475a0d0SEmanuele Giuseppe Esposito ret = bdrv_co_create_file(filename, opts, errp);
3958cbf2b7c4SKevin Wolf if (ret < 0) {
3959cbf2b7c4SKevin Wolf goto finish;
3960cbf2b7c4SKevin Wolf }
3961cbf2b7c4SKevin Wolf
3962ecbc57caSKevin Wolf bs = bdrv_co_open(filename, NULL, NULL,
3963cbf2b7c4SKevin Wolf BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_PROTOCOL, errp);
3964cbf2b7c4SKevin Wolf if (bs == NULL) {
3965cbf2b7c4SKevin Wolf ret = -EIO;
3966cbf2b7c4SKevin Wolf goto finish;
3967cbf2b7c4SKevin Wolf }
3968cbf2b7c4SKevin Wolf
39699b890bdcSKevin Wolf /* Create and open an external data file (protocol layer) */
39709b890bdcSKevin Wolf val = qdict_get_try_str(qdict, BLOCK_OPT_DATA_FILE);
39719b890bdcSKevin Wolf if (val) {
39722475a0d0SEmanuele Giuseppe Esposito ret = bdrv_co_create_file(val, opts, errp);
39739b890bdcSKevin Wolf if (ret < 0) {
39749b890bdcSKevin Wolf goto finish;
39759b890bdcSKevin Wolf }
39769b890bdcSKevin Wolf
3977ecbc57caSKevin Wolf data_bs = bdrv_co_open(val, NULL, NULL,
39789b890bdcSKevin Wolf BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_PROTOCOL,
39799b890bdcSKevin Wolf errp);
39809b890bdcSKevin Wolf if (data_bs == NULL) {
39819b890bdcSKevin Wolf ret = -EIO;
39829b890bdcSKevin Wolf goto finish;
39839b890bdcSKevin Wolf }
39849b890bdcSKevin Wolf
39859b890bdcSKevin Wolf qdict_del(qdict, BLOCK_OPT_DATA_FILE);
39869b890bdcSKevin Wolf qdict_put_str(qdict, "data-file", data_bs->node_name);
39879b890bdcSKevin Wolf }
39889b890bdcSKevin Wolf
3989b76b4f60SKevin Wolf /* Set 'driver' and 'node' options */
3990b76b4f60SKevin Wolf qdict_put_str(qdict, "driver", "qcow2");
3991b76b4f60SKevin Wolf qdict_put_str(qdict, "file", bs->node_name);
3992b76b4f60SKevin Wolf
3993b76b4f60SKevin Wolf /* Now get the QAPI type BlockdevCreateOptions */
3994af91062eSMarkus Armbruster v = qobject_input_visitor_new_flat_confused(qdict, errp);
3995af91062eSMarkus Armbruster if (!v) {
3996b76b4f60SKevin Wolf ret = -EINVAL;
3997b76b4f60SKevin Wolf goto finish;
3998b76b4f60SKevin Wolf }
3999b76b4f60SKevin Wolf
4000b11a093cSMarkus Armbruster visit_type_BlockdevCreateOptions(v, NULL, &create_options, errp);
4001b76b4f60SKevin Wolf visit_free(v);
4002b11a093cSMarkus Armbruster if (!create_options) {
4003b76b4f60SKevin Wolf ret = -EINVAL;
4004b76b4f60SKevin Wolf goto finish;
4005b76b4f60SKevin Wolf }
4006b76b4f60SKevin Wolf
4007b76b4f60SKevin Wolf /* Silently round up size */
4008b76b4f60SKevin Wolf create_options->u.qcow2.size = ROUND_UP(create_options->u.qcow2.size,
4009b76b4f60SKevin Wolf BDRV_SECTOR_SIZE);
4010b76b4f60SKevin Wolf
4011cbf2b7c4SKevin Wolf /* Create the qcow2 image (format layer) */
4012b76b4f60SKevin Wolf ret = qcow2_co_create(create_options, errp);
40136094cbebSMaxim Levitsky finish:
4014cbf2b7c4SKevin Wolf if (ret < 0) {
40154db7ba3bSKevin Wolf bdrv_graph_co_rdlock();
40166094cbebSMaxim Levitsky bdrv_co_delete_file_noerr(bs);
40176094cbebSMaxim Levitsky bdrv_co_delete_file_noerr(data_bs);
40184db7ba3bSKevin Wolf bdrv_graph_co_rdunlock();
40196094cbebSMaxim Levitsky } else {
40206094cbebSMaxim Levitsky ret = 0;
4021cbf2b7c4SKevin Wolf }
40221bd0e2d1SChunyan Liu
4023cb3e7f08SMarc-André Lureau qobject_unref(qdict);
4024b2ab5f54SKevin Wolf bdrv_co_unref(bs);
4025b2ab5f54SKevin Wolf bdrv_co_unref(data_bs);
4026b76b4f60SKevin Wolf qapi_free_BlockdevCreateOptions(create_options);
40273ef6c40aSMax Reitz return ret;
4028de5f3f40SKevin Wolf }
4029de5f3f40SKevin Wolf
40302928abceSDenis V. Lunev
4031cc323997SPaolo Bonzini static bool coroutine_fn GRAPH_RDLOCK
is_zero(BlockDriverState * bs,int64_t offset,int64_t bytes)4032cc323997SPaolo Bonzini is_zero(BlockDriverState *bs, int64_t offset, int64_t bytes)
40332928abceSDenis V. Lunev {
403431826642SEric Blake int64_t nr;
403531826642SEric Blake int res;
4036f06f6b66SEric Blake
4037f06f6b66SEric Blake /* Clamp to image length, before checking status of underlying sectors */
40388cbf74b2SEric Blake if (offset + bytes > bs->total_sectors * BDRV_SECTOR_SIZE) {
40398cbf74b2SEric Blake bytes = bs->total_sectors * BDRV_SECTOR_SIZE - offset;
4040fbaa6bb3SEric Blake }
4041fbaa6bb3SEric Blake
4042f06f6b66SEric Blake if (!bytes) {
4043ebb718a5SEric Blake return true;
40442928abceSDenis V. Lunev }
404567c095c8SVladimir Sementsov-Ogievskiy
404667c095c8SVladimir Sementsov-Ogievskiy /*
404767c095c8SVladimir Sementsov-Ogievskiy * bdrv_block_status_above doesn't merge different types of zeros, for
404867c095c8SVladimir Sementsov-Ogievskiy * example, zeros which come from the region which is unallocated in
404967c095c8SVladimir Sementsov-Ogievskiy * the whole backing chain, and zeros which come because of a short
405067c095c8SVladimir Sementsov-Ogievskiy * backing file. So, we need a loop.
405167c095c8SVladimir Sementsov-Ogievskiy */
405267c095c8SVladimir Sementsov-Ogievskiy do {
4053cc323997SPaolo Bonzini res = bdrv_co_block_status_above(bs, NULL, offset, bytes, &nr, NULL, NULL);
405467c095c8SVladimir Sementsov-Ogievskiy offset += nr;
405567c095c8SVladimir Sementsov-Ogievskiy bytes -= nr;
405667c095c8SVladimir Sementsov-Ogievskiy } while (res >= 0 && (res & BDRV_BLOCK_ZERO) && nr && bytes);
405767c095c8SVladimir Sementsov-Ogievskiy
405867c095c8SVladimir Sementsov-Ogievskiy return res >= 0 && (res & BDRV_BLOCK_ZERO) && bytes == 0;
40592928abceSDenis V. Lunev }
40602928abceSDenis V. Lunev
4061abaf8b75SKevin Wolf static int coroutine_fn GRAPH_RDLOCK
qcow2_co_pwrite_zeroes(BlockDriverState * bs,int64_t offset,int64_t bytes,BdrvRequestFlags flags)4062abaf8b75SKevin Wolf qcow2_co_pwrite_zeroes(BlockDriverState *bs, int64_t offset, int64_t bytes,
4063abaf8b75SKevin Wolf BdrvRequestFlags flags)
4064621f0589SKevin Wolf {
4065621f0589SKevin Wolf int ret;
4066ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque;
4067621f0589SKevin Wolf
4068a6841a2dSAlberto Garcia uint32_t head = offset_into_subcluster(s, offset);
4069a6841a2dSAlberto Garcia uint32_t tail = ROUND_UP(offset + bytes, s->subcluster_size) -
4070a6841a2dSAlberto Garcia (offset + bytes);
40712928abceSDenis V. Lunev
4072f5a5ca79SManos Pitsidianakis trace_qcow2_pwrite_zeroes_start_req(qemu_coroutine_self(), offset, bytes);
4073f5a5ca79SManos Pitsidianakis if (offset + bytes == bs->total_sectors * BDRV_SECTOR_SIZE) {
4074fbaa6bb3SEric Blake tail = 0;
4075fbaa6bb3SEric Blake }
40765a64e942SDenis V. Lunev
4077ebb718a5SEric Blake if (head || tail) {
4078ebb718a5SEric Blake uint64_t off;
4079ecfe1863SKevin Wolf unsigned int nr;
408010dabdc5SAlberto Garcia QCow2SubclusterType type;
40812928abceSDenis V. Lunev
4082a6841a2dSAlberto Garcia assert(head + bytes + tail <= s->subcluster_size);
40832928abceSDenis V. Lunev
4084ebb718a5SEric Blake /* check whether remainder of cluster already reads as zero */
4085f06f6b66SEric Blake if (!(is_zero(bs, offset - head, head) &&
4086a6841a2dSAlberto Garcia is_zero(bs, offset + bytes, tail))) {
4087621f0589SKevin Wolf return -ENOTSUP;
4088621f0589SKevin Wolf }
4089621f0589SKevin Wolf
4090621f0589SKevin Wolf qemu_co_mutex_lock(&s->lock);
40912928abceSDenis V. Lunev /* We can have new write after previous check */
4092a6841a2dSAlberto Garcia offset -= head;
4093a6841a2dSAlberto Garcia bytes = s->subcluster_size;
4094a6841a2dSAlberto Garcia nr = s->subcluster_size;
4095ca4a0bb8SAlberto Garcia ret = qcow2_get_host_offset(bs, offset, &nr, &off, &type);
4096ca4a0bb8SAlberto Garcia if (ret < 0 ||
409710dabdc5SAlberto Garcia (type != QCOW2_SUBCLUSTER_UNALLOCATED_PLAIN &&
409897490a14SAlberto Garcia type != QCOW2_SUBCLUSTER_UNALLOCATED_ALLOC &&
409910dabdc5SAlberto Garcia type != QCOW2_SUBCLUSTER_ZERO_PLAIN &&
410010dabdc5SAlberto Garcia type != QCOW2_SUBCLUSTER_ZERO_ALLOC)) {
41012928abceSDenis V. Lunev qemu_co_mutex_unlock(&s->lock);
4102580384d6SAlberto Garcia return ret < 0 ? ret : -ENOTSUP;
41032928abceSDenis V. Lunev }
41042928abceSDenis V. Lunev } else {
41052928abceSDenis V. Lunev qemu_co_mutex_lock(&s->lock);
41062928abceSDenis V. Lunev }
41072928abceSDenis V. Lunev
4108f5a5ca79SManos Pitsidianakis trace_qcow2_pwrite_zeroes(qemu_coroutine_self(), offset, bytes);
41095a64e942SDenis V. Lunev
4110a6841a2dSAlberto Garcia /* Whatever is left can use real zero subclusters */
4111a6841a2dSAlberto Garcia ret = qcow2_subcluster_zeroize(bs, offset, bytes, flags);
4112621f0589SKevin Wolf qemu_co_mutex_unlock(&s->lock);
4113621f0589SKevin Wolf
4114621f0589SKevin Wolf return ret;
4115621f0589SKevin Wolf }
4116621f0589SKevin Wolf
41170bb79c97SKevin Wolf static int coroutine_fn GRAPH_RDLOCK
qcow2_co_pdiscard(BlockDriverState * bs,int64_t offset,int64_t bytes)41180bb79c97SKevin Wolf qcow2_co_pdiscard(BlockDriverState *bs, int64_t offset, int64_t bytes)
41195ea929e3SKevin Wolf {
41206db39ae2SPaolo Bonzini int ret;
4121ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque;
41226db39ae2SPaolo Bonzini
412380f5c011SAlberto Garcia /* If the image does not support QCOW_OFLAG_ZERO then discarding
412480f5c011SAlberto Garcia * clusters could expose stale data from the backing file. */
412580f5c011SAlberto Garcia if (s->qcow_version < 3 && bs->backing) {
412680f5c011SAlberto Garcia return -ENOTSUP;
412780f5c011SAlberto Garcia }
412880f5c011SAlberto Garcia
4129f5a5ca79SManos Pitsidianakis if (!QEMU_IS_ALIGNED(offset | bytes, s->cluster_size)) {
4130f5a5ca79SManos Pitsidianakis assert(bytes < s->cluster_size);
4131048c5fd1SEric Blake /* Ignore partial clusters, except for the special case of the
4132048c5fd1SEric Blake * complete partial cluster at the end of an unaligned file */
4133048c5fd1SEric Blake if (!QEMU_IS_ALIGNED(offset, s->cluster_size) ||
4134f5a5ca79SManos Pitsidianakis offset + bytes != bs->total_sectors * BDRV_SECTOR_SIZE) {
413549228d1eSEric Blake return -ENOTSUP;
413649228d1eSEric Blake }
4137048c5fd1SEric Blake }
413849228d1eSEric Blake
41396db39ae2SPaolo Bonzini qemu_co_mutex_lock(&s->lock);
4140f5a5ca79SManos Pitsidianakis ret = qcow2_cluster_discard(bs, offset, bytes, QCOW2_DISCARD_REQUEST,
4141d2cb36afSEric Blake false);
41426db39ae2SPaolo Bonzini qemu_co_mutex_unlock(&s->lock);
41436db39ae2SPaolo Bonzini return ret;
41445ea929e3SKevin Wolf }
41455ea929e3SKevin Wolf
4146742bf09bSEmanuele 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)4147fd9fcd37SFam Zheng qcow2_co_copy_range_from(BlockDriverState *bs,
414848535049SVladimir Sementsov-Ogievskiy BdrvChild *src, int64_t src_offset,
414948535049SVladimir Sementsov-Ogievskiy BdrvChild *dst, int64_t dst_offset,
415048535049SVladimir Sementsov-Ogievskiy int64_t bytes, BdrvRequestFlags read_flags,
415167b51fb9SVladimir Sementsov-Ogievskiy BdrvRequestFlags write_flags)
4152fd9fcd37SFam Zheng {
4153fd9fcd37SFam Zheng BDRVQcow2State *s = bs->opaque;
4154fd9fcd37SFam Zheng int ret;
4155fd9fcd37SFam Zheng unsigned int cur_bytes; /* number of bytes in current iteration */
4156fd9fcd37SFam Zheng BdrvChild *child = NULL;
415767b51fb9SVladimir Sementsov-Ogievskiy BdrvRequestFlags cur_write_flags;
4158fd9fcd37SFam Zheng
4159fd9fcd37SFam Zheng assert(!bs->encrypted);
4160fd9fcd37SFam Zheng qemu_co_mutex_lock(&s->lock);
4161fd9fcd37SFam Zheng
4162fd9fcd37SFam Zheng while (bytes != 0) {
4163fd9fcd37SFam Zheng uint64_t copy_offset = 0;
416410dabdc5SAlberto Garcia QCow2SubclusterType type;
4165fd9fcd37SFam Zheng /* prepare next request */
4166fd9fcd37SFam Zheng cur_bytes = MIN(bytes, INT_MAX);
416767b51fb9SVladimir Sementsov-Ogievskiy cur_write_flags = write_flags;
4168fd9fcd37SFam Zheng
4169ca4a0bb8SAlberto Garcia ret = qcow2_get_host_offset(bs, src_offset, &cur_bytes,
4170ca4a0bb8SAlberto Garcia ©_offset, &type);
4171fd9fcd37SFam Zheng if (ret < 0) {
4172fd9fcd37SFam Zheng goto out;
4173fd9fcd37SFam Zheng }
4174fd9fcd37SFam Zheng
4175ca4a0bb8SAlberto Garcia switch (type) {
417610dabdc5SAlberto Garcia case QCOW2_SUBCLUSTER_UNALLOCATED_PLAIN:
417797490a14SAlberto Garcia case QCOW2_SUBCLUSTER_UNALLOCATED_ALLOC:
4178fd9fcd37SFam Zheng if (bs->backing && bs->backing->bs) {
41790050c163SKevin Wolf int64_t backing_length = bdrv_co_getlength(bs->backing->bs);
4180fd9fcd37SFam Zheng if (src_offset >= backing_length) {
418167b51fb9SVladimir Sementsov-Ogievskiy cur_write_flags |= BDRV_REQ_ZERO_WRITE;
4182fd9fcd37SFam Zheng } else {
4183fd9fcd37SFam Zheng child = bs->backing;
4184fd9fcd37SFam Zheng cur_bytes = MIN(cur_bytes, backing_length - src_offset);
4185fd9fcd37SFam Zheng copy_offset = src_offset;
4186fd9fcd37SFam Zheng }
4187fd9fcd37SFam Zheng } else {
418867b51fb9SVladimir Sementsov-Ogievskiy cur_write_flags |= BDRV_REQ_ZERO_WRITE;
4189fd9fcd37SFam Zheng }
4190fd9fcd37SFam Zheng break;
4191fd9fcd37SFam Zheng
419210dabdc5SAlberto Garcia case QCOW2_SUBCLUSTER_ZERO_PLAIN:
419310dabdc5SAlberto Garcia case QCOW2_SUBCLUSTER_ZERO_ALLOC:
419467b51fb9SVladimir Sementsov-Ogievskiy cur_write_flags |= BDRV_REQ_ZERO_WRITE;
4195fd9fcd37SFam Zheng break;
4196fd9fcd37SFam Zheng
419710dabdc5SAlberto Garcia case QCOW2_SUBCLUSTER_COMPRESSED:
4198fd9fcd37SFam Zheng ret = -ENOTSUP;
4199fd9fcd37SFam Zheng goto out;
4200fd9fcd37SFam Zheng
420110dabdc5SAlberto Garcia case QCOW2_SUBCLUSTER_NORMAL:
4202966b000fSKevin Wolf child = s->data_file;
4203fd9fcd37SFam Zheng break;
4204fd9fcd37SFam Zheng
4205fd9fcd37SFam Zheng default:
4206fd9fcd37SFam Zheng abort();
4207fd9fcd37SFam Zheng }
4208fd9fcd37SFam Zheng qemu_co_mutex_unlock(&s->lock);
4209fd9fcd37SFam Zheng ret = bdrv_co_copy_range_from(child,
4210fd9fcd37SFam Zheng copy_offset,
4211fd9fcd37SFam Zheng dst, dst_offset,
421267b51fb9SVladimir Sementsov-Ogievskiy cur_bytes, read_flags, cur_write_flags);
4213fd9fcd37SFam Zheng qemu_co_mutex_lock(&s->lock);
4214fd9fcd37SFam Zheng if (ret < 0) {
4215fd9fcd37SFam Zheng goto out;
4216fd9fcd37SFam Zheng }
4217fd9fcd37SFam Zheng
4218fd9fcd37SFam Zheng bytes -= cur_bytes;
4219fd9fcd37SFam Zheng src_offset += cur_bytes;
4220fd9fcd37SFam Zheng dst_offset += cur_bytes;
4221fd9fcd37SFam Zheng }
4222fd9fcd37SFam Zheng ret = 0;
4223fd9fcd37SFam Zheng
4224fd9fcd37SFam Zheng out:
4225fd9fcd37SFam Zheng qemu_co_mutex_unlock(&s->lock);
4226fd9fcd37SFam Zheng return ret;
4227fd9fcd37SFam Zheng }
4228fd9fcd37SFam Zheng
4229742bf09bSEmanuele 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)4230fd9fcd37SFam Zheng qcow2_co_copy_range_to(BlockDriverState *bs,
423148535049SVladimir Sementsov-Ogievskiy BdrvChild *src, int64_t src_offset,
423248535049SVladimir Sementsov-Ogievskiy BdrvChild *dst, int64_t dst_offset,
423348535049SVladimir Sementsov-Ogievskiy int64_t bytes, BdrvRequestFlags read_flags,
423467b51fb9SVladimir Sementsov-Ogievskiy BdrvRequestFlags write_flags)
4235fd9fcd37SFam Zheng {
4236fd9fcd37SFam Zheng BDRVQcow2State *s = bs->opaque;
4237fd9fcd37SFam Zheng int ret;
4238fd9fcd37SFam Zheng unsigned int cur_bytes; /* number of sectors in current iteration */
4239bfd0989aSAlberto Garcia uint64_t host_offset;
4240fd9fcd37SFam Zheng QCowL2Meta *l2meta = NULL;
4241fd9fcd37SFam Zheng
4242fd9fcd37SFam Zheng assert(!bs->encrypted);
4243fd9fcd37SFam Zheng
4244fd9fcd37SFam Zheng qemu_co_mutex_lock(&s->lock);
4245fd9fcd37SFam Zheng
4246fd9fcd37SFam Zheng while (bytes != 0) {
4247fd9fcd37SFam Zheng
4248fd9fcd37SFam Zheng l2meta = NULL;
4249fd9fcd37SFam Zheng
4250fd9fcd37SFam Zheng cur_bytes = MIN(bytes, INT_MAX);
4251fd9fcd37SFam Zheng
4252fd9fcd37SFam Zheng /* TODO:
4253fd9fcd37SFam Zheng * If src->bs == dst->bs, we could simply copy by incrementing
4254fd9fcd37SFam Zheng * the refcnt, without copying user data.
4255fd9fcd37SFam Zheng * Or if src->bs == dst->bs->backing->bs, we could copy by discarding. */
4256bfd0989aSAlberto Garcia ret = qcow2_alloc_host_offset(bs, dst_offset, &cur_bytes,
4257bfd0989aSAlberto Garcia &host_offset, &l2meta);
4258fd9fcd37SFam Zheng if (ret < 0) {
4259fd9fcd37SFam Zheng goto fail;
4260fd9fcd37SFam Zheng }
4261fd9fcd37SFam Zheng
4262bfd0989aSAlberto Garcia ret = qcow2_pre_write_overlap_check(bs, 0, host_offset, cur_bytes,
4263bfd0989aSAlberto Garcia true);
4264fd9fcd37SFam Zheng if (ret < 0) {
4265fd9fcd37SFam Zheng goto fail;
4266fd9fcd37SFam Zheng }
4267fd9fcd37SFam Zheng
4268fd9fcd37SFam Zheng qemu_co_mutex_unlock(&s->lock);
4269bfd0989aSAlberto Garcia ret = bdrv_co_copy_range_to(src, src_offset, s->data_file, host_offset,
427067b51fb9SVladimir Sementsov-Ogievskiy cur_bytes, read_flags, write_flags);
4271fd9fcd37SFam Zheng qemu_co_mutex_lock(&s->lock);
4272fd9fcd37SFam Zheng if (ret < 0) {
4273fd9fcd37SFam Zheng goto fail;
4274fd9fcd37SFam Zheng }
4275fd9fcd37SFam Zheng
4276fd9fcd37SFam Zheng ret = qcow2_handle_l2meta(bs, &l2meta, true);
4277fd9fcd37SFam Zheng if (ret) {
4278fd9fcd37SFam Zheng goto fail;
4279fd9fcd37SFam Zheng }
4280fd9fcd37SFam Zheng
4281fd9fcd37SFam Zheng bytes -= cur_bytes;
4282e06f4639SFam Zheng src_offset += cur_bytes;
4283fd9fcd37SFam Zheng dst_offset += cur_bytes;
4284fd9fcd37SFam Zheng }
4285fd9fcd37SFam Zheng ret = 0;
4286fd9fcd37SFam Zheng
4287fd9fcd37SFam Zheng fail:
4288fd9fcd37SFam Zheng qcow2_handle_l2meta(bs, &l2meta, false);
4289fd9fcd37SFam Zheng
4290fd9fcd37SFam Zheng qemu_co_mutex_unlock(&s->lock);
4291fd9fcd37SFam Zheng
4292fd9fcd37SFam Zheng trace_qcow2_writev_done_req(qemu_coroutine_self(), ret);
4293fd9fcd37SFam Zheng
4294fd9fcd37SFam Zheng return ret;
4295fd9fcd37SFam Zheng }
4296fd9fcd37SFam Zheng
4297c2b8e315SKevin Wolf static int coroutine_fn GRAPH_RDLOCK
qcow2_co_truncate(BlockDriverState * bs,int64_t offset,bool exact,PreallocMode prealloc,BdrvRequestFlags flags,Error ** errp)4298c2b8e315SKevin Wolf qcow2_co_truncate(BlockDriverState *bs, int64_t offset, bool exact,
4299c2b8e315SKevin Wolf PreallocMode prealloc, BdrvRequestFlags flags, Error **errp)
4300419b19d9SStefan Hajnoczi {
4301d13e3b46SZhao Liu ERRP_GUARD();
4302ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque;
430395b98f34SMax Reitz uint64_t old_length;
43042cf7cfa1SKevin Wolf int64_t new_l1_size;
43052cf7cfa1SKevin Wolf int ret;
430645b4949cSLeonid Bloch QDict *options;
4307419b19d9SStefan Hajnoczi
4308772d1f97SMax Reitz if (prealloc != PREALLOC_MODE_OFF && prealloc != PREALLOC_MODE_METADATA &&
4309772d1f97SMax Reitz prealloc != PREALLOC_MODE_FALLOC && prealloc != PREALLOC_MODE_FULL)
4310772d1f97SMax Reitz {
43118243ccb7SMax Reitz error_setg(errp, "Unsupported preallocation mode '%s'",
4312977c736fSMarkus Armbruster PreallocMode_str(prealloc));
43138243ccb7SMax Reitz return -ENOTSUP;
43148243ccb7SMax Reitz }
43158243ccb7SMax Reitz
43163afea402SAlberto Garcia if (!QEMU_IS_ALIGNED(offset, BDRV_SECTOR_SIZE)) {
43173afea402SAlberto Garcia error_setg(errp, "The new size must be a multiple of %u",
43183afea402SAlberto Garcia (unsigned) BDRV_SECTOR_SIZE);
4319419b19d9SStefan Hajnoczi return -EINVAL;
4320419b19d9SStefan Hajnoczi }
4321419b19d9SStefan Hajnoczi
4322061ca8a3SKevin Wolf qemu_co_mutex_lock(&s->lock);
4323061ca8a3SKevin Wolf
43247fa140abSEric Blake /*
43257fa140abSEric Blake * Even though we store snapshot size for all images, it was not
43267fa140abSEric Blake * required until v3, so it is not safe to proceed for v2.
43277fa140abSEric Blake */
43287fa140abSEric Blake if (s->nb_snapshots && s->qcow_version < 3) {
43297fa140abSEric Blake error_setg(errp, "Can't resize a v2 image which has snapshots");
4330061ca8a3SKevin Wolf ret = -ENOTSUP;
4331061ca8a3SKevin Wolf goto fail;
4332419b19d9SStefan Hajnoczi }
4333419b19d9SStefan Hajnoczi
4334ee1244a2SEric Blake /* See qcow2-bitmap.c for which bitmap scenarios prevent a resize. */
4335d19c6b36SJohn Snow if (qcow2_truncate_bitmaps_check(bs, errp)) {
4336061ca8a3SKevin Wolf ret = -ENOTSUP;
4337061ca8a3SKevin Wolf goto fail;
433888ddffaeSVladimir Sementsov-Ogievskiy }
433988ddffaeSVladimir Sementsov-Ogievskiy
4340bd016b91SLeonid Bloch old_length = bs->total_sectors * BDRV_SECTOR_SIZE;
434146b732cdSPavel Butsykin new_l1_size = size_to_l1(s, offset);
434295b98f34SMax Reitz
434395b98f34SMax Reitz if (offset < old_length) {
4344163bc39dSPavel Butsykin int64_t last_cluster, old_file_size;
434546b732cdSPavel Butsykin if (prealloc != PREALLOC_MODE_OFF) {
434646b732cdSPavel Butsykin error_setg(errp,
434746b732cdSPavel Butsykin "Preallocation can't be used for shrinking an image");
4348061ca8a3SKevin Wolf ret = -EINVAL;
4349061ca8a3SKevin Wolf goto fail;
4350419b19d9SStefan Hajnoczi }
4351419b19d9SStefan Hajnoczi
435246b732cdSPavel Butsykin ret = qcow2_cluster_discard(bs, ROUND_UP(offset, s->cluster_size),
435346b732cdSPavel Butsykin old_length - ROUND_UP(offset,
435446b732cdSPavel Butsykin s->cluster_size),
435546b732cdSPavel Butsykin QCOW2_DISCARD_ALWAYS, true);
435646b732cdSPavel Butsykin if (ret < 0) {
435746b732cdSPavel Butsykin error_setg_errno(errp, -ret, "Failed to discard cropped clusters");
4358061ca8a3SKevin Wolf goto fail;
435946b732cdSPavel Butsykin }
436046b732cdSPavel Butsykin
436146b732cdSPavel Butsykin ret = qcow2_shrink_l1_table(bs, new_l1_size);
436246b732cdSPavel Butsykin if (ret < 0) {
436346b732cdSPavel Butsykin error_setg_errno(errp, -ret,
436446b732cdSPavel Butsykin "Failed to reduce the number of L2 tables");
4365061ca8a3SKevin Wolf goto fail;
436646b732cdSPavel Butsykin }
436746b732cdSPavel Butsykin
436846b732cdSPavel Butsykin ret = qcow2_shrink_reftable(bs);
436946b732cdSPavel Butsykin if (ret < 0) {
437046b732cdSPavel Butsykin error_setg_errno(errp, -ret,
437146b732cdSPavel Butsykin "Failed to discard unused refblocks");
4372061ca8a3SKevin Wolf goto fail;
437346b732cdSPavel Butsykin }
4374163bc39dSPavel Butsykin
43750050c163SKevin Wolf old_file_size = bdrv_co_getlength(bs->file->bs);
4376163bc39dSPavel Butsykin if (old_file_size < 0) {
4377163bc39dSPavel Butsykin error_setg_errno(errp, -old_file_size,
4378163bc39dSPavel Butsykin "Failed to inquire current file length");
4379061ca8a3SKevin Wolf ret = old_file_size;
4380061ca8a3SKevin Wolf goto fail;
4381163bc39dSPavel Butsykin }
4382163bc39dSPavel Butsykin last_cluster = qcow2_get_last_cluster(bs, old_file_size);
4383163bc39dSPavel Butsykin if (last_cluster < 0) {
4384163bc39dSPavel Butsykin error_setg_errno(errp, -last_cluster,
4385163bc39dSPavel Butsykin "Failed to find the last cluster");
4386061ca8a3SKevin Wolf ret = last_cluster;
4387061ca8a3SKevin Wolf goto fail;
4388163bc39dSPavel Butsykin }
4389163bc39dSPavel Butsykin if ((last_cluster + 1) * s->cluster_size < old_file_size) {
4390233521b1SMax Reitz Error *local_err = NULL;
4391233521b1SMax Reitz
4392e61a28a9SMax Reitz /*
4393e61a28a9SMax Reitz * Do not pass @exact here: It will not help the user if
4394e61a28a9SMax Reitz * we get an error here just because they wanted to shrink
4395e61a28a9SMax Reitz * their qcow2 image (on a block device) with qemu-img.
4396e61a28a9SMax Reitz * (And on the qcow2 layer, the @exact requirement is
4397e61a28a9SMax Reitz * always fulfilled, so there is no need to pass it on.)
4398e61a28a9SMax Reitz */
4399061ca8a3SKevin Wolf bdrv_co_truncate(bs->file, (last_cluster + 1) * s->cluster_size,
44007b8e4857SKevin Wolf false, PREALLOC_MODE_OFF, 0, &local_err);
4401233521b1SMax Reitz if (local_err) {
4402233521b1SMax Reitz warn_reportf_err(local_err,
4403233521b1SMax Reitz "Failed to truncate the tail of the image: ");
4404163bc39dSPavel Butsykin }
4405163bc39dSPavel Butsykin }
440646b732cdSPavel Butsykin } else {
440772893756SStefan Hajnoczi ret = qcow2_grow_l1_table(bs, new_l1_size, true);
4408419b19d9SStefan Hajnoczi if (ret < 0) {
4409f59adb32SMax Reitz error_setg_errno(errp, -ret, "Failed to grow the L1 table");
4410061ca8a3SKevin Wolf goto fail;
4411419b19d9SStefan Hajnoczi }
441248410829SMax Reitz
441348410829SMax Reitz if (data_file_is_raw(bs) && prealloc == PREALLOC_MODE_OFF) {
441448410829SMax Reitz /*
441548410829SMax Reitz * When creating a qcow2 image with data-file-raw, we enforce
441648410829SMax Reitz * at least prealloc=metadata, so that the L1/L2 tables are
441748410829SMax Reitz * fully allocated and reading from the data file will return
441848410829SMax Reitz * the same data as reading from the qcow2 image. When the
441948410829SMax Reitz * image is grown, we must consequently preallocate the
442048410829SMax Reitz * metadata structures to cover the added area.
442148410829SMax Reitz */
442248410829SMax Reitz prealloc = PREALLOC_MODE_METADATA;
442348410829SMax Reitz }
442446b732cdSPavel Butsykin }
4425419b19d9SStefan Hajnoczi
442695b98f34SMax Reitz switch (prealloc) {
442795b98f34SMax Reitz case PREALLOC_MODE_OFF:
4428718c0fceSKevin Wolf if (has_data_file(bs)) {
4429e61a28a9SMax Reitz /*
4430e61a28a9SMax Reitz * If the caller wants an exact resize, the external data
4431e61a28a9SMax Reitz * file should be resized to the exact target size, too,
4432e61a28a9SMax Reitz * so we pass @exact here.
4433e61a28a9SMax Reitz */
44347b8e4857SKevin Wolf ret = bdrv_co_truncate(s->data_file, offset, exact, prealloc, 0,
44357b8e4857SKevin Wolf errp);
4436718c0fceSKevin Wolf if (ret < 0) {
4437718c0fceSKevin Wolf goto fail;
4438718c0fceSKevin Wolf }
4439718c0fceSKevin Wolf }
444095b98f34SMax Reitz break;
444195b98f34SMax Reitz
444295b98f34SMax Reitz case PREALLOC_MODE_METADATA:
4443718c0fceSKevin Wolf ret = preallocate_co(bs, old_length, offset, prealloc, errp);
444495b98f34SMax Reitz if (ret < 0) {
4445061ca8a3SKevin Wolf goto fail;
444695b98f34SMax Reitz }
444795b98f34SMax Reitz break;
444895b98f34SMax Reitz
4449772d1f97SMax Reitz case PREALLOC_MODE_FALLOC:
4450772d1f97SMax Reitz case PREALLOC_MODE_FULL:
4451772d1f97SMax Reitz {
4452772d1f97SMax Reitz int64_t allocation_start, host_offset, guest_offset;
4453772d1f97SMax Reitz int64_t clusters_allocated;
44544b96fa38SMax Reitz int64_t old_file_size, last_cluster, new_file_size;
4455772d1f97SMax Reitz uint64_t nb_new_data_clusters, nb_new_l2_tables;
445640dee943SAlberto Garcia bool subclusters_need_allocation = false;
4457772d1f97SMax Reitz
4458966b000fSKevin Wolf /* With a data file, preallocation means just allocating the metadata
4459966b000fSKevin Wolf * and forwarding the truncate request to the data file */
4460966b000fSKevin Wolf if (has_data_file(bs)) {
4461718c0fceSKevin Wolf ret = preallocate_co(bs, old_length, offset, prealloc, errp);
4462966b000fSKevin Wolf if (ret < 0) {
4463966b000fSKevin Wolf goto fail;
4464966b000fSKevin Wolf }
4465966b000fSKevin Wolf break;
4466966b000fSKevin Wolf }
4467966b000fSKevin Wolf
44680050c163SKevin Wolf old_file_size = bdrv_co_getlength(bs->file->bs);
4469772d1f97SMax Reitz if (old_file_size < 0) {
4470772d1f97SMax Reitz error_setg_errno(errp, -old_file_size,
4471772d1f97SMax Reitz "Failed to inquire current file length");
4472061ca8a3SKevin Wolf ret = old_file_size;
4473061ca8a3SKevin Wolf goto fail;
4474772d1f97SMax Reitz }
44754b96fa38SMax Reitz
44764b96fa38SMax Reitz last_cluster = qcow2_get_last_cluster(bs, old_file_size);
44774b96fa38SMax Reitz if (last_cluster >= 0) {
44784b96fa38SMax Reitz old_file_size = (last_cluster + 1) * s->cluster_size;
44794b96fa38SMax Reitz } else {
4480e400ad1eSMax Reitz old_file_size = ROUND_UP(old_file_size, s->cluster_size);
44814b96fa38SMax Reitz }
4482772d1f97SMax Reitz
4483a5675f39SAlberto Garcia nb_new_data_clusters = (ROUND_UP(offset, s->cluster_size) -
4484a5675f39SAlberto Garcia start_of_cluster(s, old_length)) >> s->cluster_bits;
4485772d1f97SMax Reitz
4486772d1f97SMax Reitz /* This is an overestimation; we will not actually allocate space for
4487772d1f97SMax Reitz * these in the file but just make sure the new refcount structures are
4488772d1f97SMax Reitz * able to cover them so we will not have to allocate new refblocks
4489772d1f97SMax Reitz * while entering the data blocks in the potentially new L2 tables.
4490772d1f97SMax Reitz * (We do not actually care where the L2 tables are placed. Maybe they
4491772d1f97SMax Reitz * are already allocated or they can be placed somewhere before
4492772d1f97SMax Reitz * @old_file_size. It does not matter because they will be fully
4493772d1f97SMax Reitz * allocated automatically, so they do not need to be covered by the
4494772d1f97SMax Reitz * preallocation. All that matters is that we will not have to allocate
4495772d1f97SMax Reitz * new refcount structures for them.) */
4496772d1f97SMax Reitz nb_new_l2_tables = DIV_ROUND_UP(nb_new_data_clusters,
4497c8fd8554SAlberto Garcia s->cluster_size / l2_entry_size(s));
4498772d1f97SMax Reitz /* The cluster range may not be aligned to L2 boundaries, so add one L2
4499772d1f97SMax Reitz * table for a potential head/tail */
4500772d1f97SMax Reitz nb_new_l2_tables++;
4501772d1f97SMax Reitz
4502772d1f97SMax Reitz allocation_start = qcow2_refcount_area(bs, old_file_size,
4503772d1f97SMax Reitz nb_new_data_clusters +
4504772d1f97SMax Reitz nb_new_l2_tables,
4505772d1f97SMax Reitz true, 0, 0);
4506772d1f97SMax Reitz if (allocation_start < 0) {
4507772d1f97SMax Reitz error_setg_errno(errp, -allocation_start,
4508772d1f97SMax Reitz "Failed to resize refcount structures");
4509061ca8a3SKevin Wolf ret = allocation_start;
4510061ca8a3SKevin Wolf goto fail;
4511772d1f97SMax Reitz }
4512772d1f97SMax Reitz
4513772d1f97SMax Reitz clusters_allocated = qcow2_alloc_clusters_at(bs, allocation_start,
4514772d1f97SMax Reitz nb_new_data_clusters);
4515772d1f97SMax Reitz if (clusters_allocated < 0) {
4516772d1f97SMax Reitz error_setg_errno(errp, -clusters_allocated,
4517772d1f97SMax Reitz "Failed to allocate data clusters");
4518061ca8a3SKevin Wolf ret = clusters_allocated;
4519061ca8a3SKevin Wolf goto fail;
4520772d1f97SMax Reitz }
4521772d1f97SMax Reitz
4522772d1f97SMax Reitz assert(clusters_allocated == nb_new_data_clusters);
4523772d1f97SMax Reitz
4524772d1f97SMax Reitz /* Allocate the data area */
4525772d1f97SMax Reitz new_file_size = allocation_start +
4526772d1f97SMax Reitz nb_new_data_clusters * s->cluster_size;
4527eb8a0cf3SKevin Wolf /*
4528eb8a0cf3SKevin Wolf * Image file grows, so @exact does not matter.
4529eb8a0cf3SKevin Wolf *
4530eb8a0cf3SKevin Wolf * If we need to zero out the new area, try first whether the protocol
4531eb8a0cf3SKevin Wolf * driver can already take care of this.
4532eb8a0cf3SKevin Wolf */
4533eb8a0cf3SKevin Wolf if (flags & BDRV_REQ_ZERO_WRITE) {
4534eb8a0cf3SKevin Wolf ret = bdrv_co_truncate(bs->file, new_file_size, false, prealloc,
4535eb8a0cf3SKevin Wolf BDRV_REQ_ZERO_WRITE, NULL);
4536eb8a0cf3SKevin Wolf if (ret >= 0) {
4537eb8a0cf3SKevin Wolf flags &= ~BDRV_REQ_ZERO_WRITE;
453840dee943SAlberto Garcia /* Ensure that we read zeroes and not backing file data */
453940dee943SAlberto Garcia subclusters_need_allocation = true;
4540eb8a0cf3SKevin Wolf }
4541eb8a0cf3SKevin Wolf } else {
4542eb8a0cf3SKevin Wolf ret = -1;
4543eb8a0cf3SKevin Wolf }
4544eb8a0cf3SKevin Wolf if (ret < 0) {
45457b8e4857SKevin Wolf ret = bdrv_co_truncate(bs->file, new_file_size, false, prealloc, 0,
45467b8e4857SKevin Wolf errp);
4547eb8a0cf3SKevin Wolf }
4548772d1f97SMax Reitz if (ret < 0) {
4549772d1f97SMax Reitz error_prepend(errp, "Failed to resize underlying file: ");
4550772d1f97SMax Reitz qcow2_free_clusters(bs, allocation_start,
4551772d1f97SMax Reitz nb_new_data_clusters * s->cluster_size,
4552772d1f97SMax Reitz QCOW2_DISCARD_OTHER);
4553061ca8a3SKevin Wolf goto fail;
4554772d1f97SMax Reitz }
4555772d1f97SMax Reitz
4556772d1f97SMax Reitz /* Create the necessary L2 entries */
4557772d1f97SMax Reitz host_offset = allocation_start;
4558772d1f97SMax Reitz guest_offset = old_length;
4559772d1f97SMax Reitz while (nb_new_data_clusters) {
456013bec229SAlberto Garcia int64_t nb_clusters = MIN(
456113bec229SAlberto Garcia nb_new_data_clusters,
456213bec229SAlberto Garcia s->l2_slice_size - offset_to_l2_slice_index(s, guest_offset));
4563a5675f39SAlberto Garcia unsigned cow_start_length = offset_into_cluster(s, guest_offset);
4564a5675f39SAlberto Garcia QCowL2Meta allocation;
4565a5675f39SAlberto Garcia guest_offset = start_of_cluster(s, guest_offset);
4566a5675f39SAlberto Garcia allocation = (QCowL2Meta) {
4567772d1f97SMax Reitz .offset = guest_offset,
4568772d1f97SMax Reitz .alloc_offset = host_offset,
4569772d1f97SMax Reitz .nb_clusters = nb_clusters,
4570a5675f39SAlberto Garcia .cow_start = {
4571a5675f39SAlberto Garcia .offset = 0,
4572a5675f39SAlberto Garcia .nb_bytes = cow_start_length,
4573a5675f39SAlberto Garcia },
4574a5675f39SAlberto Garcia .cow_end = {
4575a5675f39SAlberto Garcia .offset = nb_clusters << s->cluster_bits,
4576a5675f39SAlberto Garcia .nb_bytes = 0,
4577a5675f39SAlberto Garcia },
457840dee943SAlberto Garcia .prealloc = !subclusters_need_allocation,
4579772d1f97SMax Reitz };
4580772d1f97SMax Reitz qemu_co_queue_init(&allocation.dependent_requests);
4581772d1f97SMax Reitz
4582772d1f97SMax Reitz ret = qcow2_alloc_cluster_link_l2(bs, &allocation);
4583772d1f97SMax Reitz if (ret < 0) {
4584772d1f97SMax Reitz error_setg_errno(errp, -ret, "Failed to update L2 tables");
4585772d1f97SMax Reitz qcow2_free_clusters(bs, host_offset,
4586772d1f97SMax Reitz nb_new_data_clusters * s->cluster_size,
4587772d1f97SMax Reitz QCOW2_DISCARD_OTHER);
4588061ca8a3SKevin Wolf goto fail;
4589772d1f97SMax Reitz }
4590772d1f97SMax Reitz
4591772d1f97SMax Reitz guest_offset += nb_clusters * s->cluster_size;
4592772d1f97SMax Reitz host_offset += nb_clusters * s->cluster_size;
4593772d1f97SMax Reitz nb_new_data_clusters -= nb_clusters;
4594772d1f97SMax Reitz }
4595772d1f97SMax Reitz break;
4596772d1f97SMax Reitz }
4597772d1f97SMax Reitz
459895b98f34SMax Reitz default:
459995b98f34SMax Reitz g_assert_not_reached();
460095b98f34SMax Reitz }
460195b98f34SMax Reitz
4602f01643fbSKevin Wolf if ((flags & BDRV_REQ_ZERO_WRITE) && offset > old_length) {
4603a6841a2dSAlberto Garcia uint64_t zero_start = QEMU_ALIGN_UP(old_length, s->subcluster_size);
4604f01643fbSKevin Wolf
4605f01643fbSKevin Wolf /*
4606a6841a2dSAlberto Garcia * Use zero clusters as much as we can. qcow2_subcluster_zeroize()
4607a6841a2dSAlberto Garcia * requires a subcluster-aligned start. The end may be unaligned if
4608a6841a2dSAlberto Garcia * it is at the end of the image (which it is here).
4609f01643fbSKevin Wolf */
4610e4d7019eSAlberto Garcia if (offset > zero_start) {
4611a6841a2dSAlberto Garcia ret = qcow2_subcluster_zeroize(bs, zero_start, offset - zero_start,
4612a6841a2dSAlberto Garcia 0);
4613f01643fbSKevin Wolf if (ret < 0) {
4614f01643fbSKevin Wolf error_setg_errno(errp, -ret, "Failed to zero out new clusters");
4615f01643fbSKevin Wolf goto fail;
4616f01643fbSKevin Wolf }
4617e4d7019eSAlberto Garcia }
4618f01643fbSKevin Wolf
4619f01643fbSKevin Wolf /* Write explicit zeros for the unaligned head */
4620f01643fbSKevin Wolf if (zero_start > old_length) {
4621e4d7019eSAlberto Garcia uint64_t len = MIN(zero_start, offset) - old_length;
4622f01643fbSKevin Wolf uint8_t *buf = qemu_blockalign0(bs, len);
4623f01643fbSKevin Wolf QEMUIOVector qiov;
4624f01643fbSKevin Wolf qemu_iovec_init_buf(&qiov, buf, len);
4625f01643fbSKevin Wolf
4626f01643fbSKevin Wolf qemu_co_mutex_unlock(&s->lock);
4627f01643fbSKevin Wolf ret = qcow2_co_pwritev_part(bs, old_length, len, &qiov, 0, 0);
4628f01643fbSKevin Wolf qemu_co_mutex_lock(&s->lock);
4629f01643fbSKevin Wolf
4630f01643fbSKevin Wolf qemu_vfree(buf);
4631f01643fbSKevin Wolf if (ret < 0) {
4632f01643fbSKevin Wolf error_setg_errno(errp, -ret, "Failed to zero out the new area");
4633f01643fbSKevin Wolf goto fail;
4634f01643fbSKevin Wolf }
4635f01643fbSKevin Wolf }
4636f01643fbSKevin Wolf }
4637f01643fbSKevin Wolf
463895b98f34SMax Reitz if (prealloc != PREALLOC_MODE_OFF) {
463995b98f34SMax Reitz /* Flush metadata before actually changing the image size */
4640061ca8a3SKevin Wolf ret = qcow2_write_caches(bs);
464195b98f34SMax Reitz if (ret < 0) {
464295b98f34SMax Reitz error_setg_errno(errp, -ret,
464395b98f34SMax Reitz "Failed to flush the preallocated area to disk");
4644061ca8a3SKevin Wolf goto fail;
464595b98f34SMax Reitz }
464695b98f34SMax Reitz }
464795b98f34SMax Reitz
464845b4949cSLeonid Bloch bs->total_sectors = offset / BDRV_SECTOR_SIZE;
464945b4949cSLeonid Bloch
4650419b19d9SStefan Hajnoczi /* write updated header.size */
4651419b19d9SStefan Hajnoczi offset = cpu_to_be64(offset);
4652a8f0e83cSAlberto Faria ret = bdrv_co_pwrite_sync(bs->file, offsetof(QCowHeader, size),
465332cc71deSAlberto Faria sizeof(offset), &offset, 0);
4654419b19d9SStefan Hajnoczi if (ret < 0) {
4655f59adb32SMax Reitz error_setg_errno(errp, -ret, "Failed to update the image size");
4656061ca8a3SKevin Wolf goto fail;
4657419b19d9SStefan Hajnoczi }
4658419b19d9SStefan Hajnoczi
4659419b19d9SStefan Hajnoczi s->l1_vm_state_index = new_l1_size;
466045b4949cSLeonid Bloch
466145b4949cSLeonid Bloch /* Update cache sizes */
466245b4949cSLeonid Bloch options = qdict_clone_shallow(bs->options);
466345b4949cSLeonid Bloch ret = qcow2_update_options(bs, options, s->flags, errp);
466445b4949cSLeonid Bloch qobject_unref(options);
466545b4949cSLeonid Bloch if (ret < 0) {
466645b4949cSLeonid Bloch goto fail;
466745b4949cSLeonid Bloch }
4668061ca8a3SKevin Wolf ret = 0;
4669061ca8a3SKevin Wolf fail:
4670061ca8a3SKevin Wolf qemu_co_mutex_unlock(&s->lock);
4671061ca8a3SKevin Wolf return ret;
4672419b19d9SStefan Hajnoczi }
4673419b19d9SStefan Hajnoczi
46747b1fb72eSKevin 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)46750d483dceSAndrey Shinkevich qcow2_co_pwritev_compressed_task(BlockDriverState *bs,
46765396234bSVladimir Sementsov-Ogievskiy uint64_t offset, uint64_t bytes,
46775396234bSVladimir Sementsov-Ogievskiy QEMUIOVector *qiov, size_t qiov_offset)
467820d97356SBlue Swirl {
4679ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque;
46802714f13dSVladimir Sementsov-Ogievskiy int ret;
4681e1f4a37aSAlberto Garcia ssize_t out_len;
4682fcccefc5SPavel Butsykin uint8_t *buf, *out_buf;
468377e023ffSKevin Wolf uint64_t cluster_offset;
468420d97356SBlue Swirl
46850d483dceSAndrey Shinkevich assert(bytes == s->cluster_size || (bytes < s->cluster_size &&
46860d483dceSAndrey Shinkevich (offset + bytes == bs->total_sectors << BDRV_SECTOR_BITS)));
46873e3b838fSAnton Nefedov
4688fcccefc5SPavel Butsykin buf = qemu_blockalign(bs, s->cluster_size);
46890d483dceSAndrey Shinkevich if (bytes < s->cluster_size) {
4690a2c0ca6fSPavel Butsykin /* Zero-pad last write if image size is not cluster aligned */
4691a2c0ca6fSPavel Butsykin memset(buf + bytes, 0, s->cluster_size - bytes);
4692a2c0ca6fSPavel Butsykin }
46935396234bSVladimir Sementsov-Ogievskiy qemu_iovec_to_buf(qiov, qiov_offset, buf, bytes);
469420d97356SBlue Swirl
4695ebf7bba0SVladimir Sementsov-Ogievskiy out_buf = g_malloc(s->cluster_size);
469620d97356SBlue Swirl
46976994fd78SVladimir Sementsov-Ogievskiy out_len = qcow2_co_compress(bs, out_buf, s->cluster_size - 1,
46986994fd78SVladimir Sementsov-Ogievskiy buf, s->cluster_size);
4699e1f4a37aSAlberto Garcia if (out_len == -ENOMEM) {
470020d97356SBlue Swirl /* could not compress: write normal cluster */
47015396234bSVladimir Sementsov-Ogievskiy ret = qcow2_co_pwritev_part(bs, offset, bytes, qiov, qiov_offset, 0);
47028f1efd00SKevin Wolf if (ret < 0) {
47038f1efd00SKevin Wolf goto fail;
47048f1efd00SKevin Wolf }
4705fcccefc5SPavel Butsykin goto success;
4706e1f4a37aSAlberto Garcia } else if (out_len < 0) {
4707e1f4a37aSAlberto Garcia ret = -EINVAL;
4708e1f4a37aSAlberto Garcia goto fail;
4709fcccefc5SPavel Butsykin }
4710fcccefc5SPavel Butsykin
4711fcccefc5SPavel Butsykin qemu_co_mutex_lock(&s->lock);
471277e023ffSKevin Wolf ret = qcow2_alloc_compressed_cluster_offset(bs, offset, out_len,
471377e023ffSKevin Wolf &cluster_offset);
471477e023ffSKevin Wolf if (ret < 0) {
4715fcccefc5SPavel Butsykin qemu_co_mutex_unlock(&s->lock);
47168f1efd00SKevin Wolf goto fail;
47178f1efd00SKevin Wolf }
4718cf93980eSMax Reitz
4719966b000fSKevin Wolf ret = qcow2_pre_write_overlap_check(bs, 0, cluster_offset, out_len, true);
4720fcccefc5SPavel Butsykin qemu_co_mutex_unlock(&s->lock);
4721cf93980eSMax Reitz if (ret < 0) {
4722cf93980eSMax Reitz goto fail;
4723cf93980eSMax Reitz }
4724cf93980eSMax Reitz
472517362398SPaolo Bonzini BLKDBG_CO_EVENT(s->data_file, BLKDBG_WRITE_COMPRESSED);
4726b00cb15bSVladimir Sementsov-Ogievskiy ret = bdrv_co_pwrite(s->data_file, cluster_offset, out_len, out_buf, 0);
47278f1efd00SKevin Wolf if (ret < 0) {
47288f1efd00SKevin Wolf goto fail;
472920d97356SBlue Swirl }
4730fcccefc5SPavel Butsykin success:
47318f1efd00SKevin Wolf ret = 0;
47328f1efd00SKevin Wolf fail:
4733fcccefc5SPavel Butsykin qemu_vfree(buf);
47347267c094SAnthony Liguori g_free(out_buf);
47358f1efd00SKevin Wolf return ret;
473620d97356SBlue Swirl }
473720d97356SBlue Swirl
47387b1fb72eSKevin Wolf /*
47397b1fb72eSKevin Wolf * This function can count as GRAPH_RDLOCK because
47407b1fb72eSKevin Wolf * qcow2_co_pwritev_compressed_part() holds the graph lock and keeps it until
47417b1fb72eSKevin Wolf * this coroutine has terminated.
47427b1fb72eSKevin Wolf */
47437b1fb72eSKevin Wolf static int coroutine_fn GRAPH_RDLOCK
qcow2_co_pwritev_compressed_task_entry(AioTask * task)47447b1fb72eSKevin Wolf qcow2_co_pwritev_compressed_task_entry(AioTask *task)
47450d483dceSAndrey Shinkevich {
47460d483dceSAndrey Shinkevich Qcow2AioTask *t = container_of(task, Qcow2AioTask, task);
47470d483dceSAndrey Shinkevich
474810dabdc5SAlberto Garcia assert(!t->subcluster_type && !t->l2meta);
47490d483dceSAndrey Shinkevich
47500d483dceSAndrey Shinkevich return qcow2_co_pwritev_compressed_task(t->bs, t->offset, t->bytes, t->qiov,
47510d483dceSAndrey Shinkevich t->qiov_offset);
47520d483dceSAndrey Shinkevich }
47530d483dceSAndrey Shinkevich
47540d483dceSAndrey Shinkevich /*
47550d483dceSAndrey Shinkevich * XXX: put compressed sectors first, then all the cluster aligned
47560d483dceSAndrey Shinkevich * tables to avoid losing bytes in alignment
47570d483dceSAndrey Shinkevich */
47587b1fb72eSKevin 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)47590d483dceSAndrey Shinkevich qcow2_co_pwritev_compressed_part(BlockDriverState *bs,
4760e75abedaSVladimir Sementsov-Ogievskiy int64_t offset, int64_t bytes,
47610d483dceSAndrey Shinkevich QEMUIOVector *qiov, size_t qiov_offset)
47620d483dceSAndrey Shinkevich {
47630d483dceSAndrey Shinkevich BDRVQcow2State *s = bs->opaque;
47640d483dceSAndrey Shinkevich AioTaskPool *aio = NULL;
47650d483dceSAndrey Shinkevich int ret = 0;
47660d483dceSAndrey Shinkevich
47670d483dceSAndrey Shinkevich if (has_data_file(bs)) {
47680d483dceSAndrey Shinkevich return -ENOTSUP;
47690d483dceSAndrey Shinkevich }
47700d483dceSAndrey Shinkevich
47710d483dceSAndrey Shinkevich if (bytes == 0) {
47720d483dceSAndrey Shinkevich /*
47730d483dceSAndrey Shinkevich * align end of file to a sector boundary to ease reading with
47740d483dceSAndrey Shinkevich * sector based I/Os
47750d483dceSAndrey Shinkevich */
47760050c163SKevin Wolf int64_t len = bdrv_co_getlength(bs->file->bs);
47770d483dceSAndrey Shinkevich if (len < 0) {
47780d483dceSAndrey Shinkevich return len;
47790d483dceSAndrey Shinkevich }
47807b8e4857SKevin Wolf return bdrv_co_truncate(bs->file, len, false, PREALLOC_MODE_OFF, 0,
47817b8e4857SKevin Wolf NULL);
47820d483dceSAndrey Shinkevich }
47830d483dceSAndrey Shinkevich
47840d483dceSAndrey Shinkevich if (offset_into_cluster(s, offset)) {
47850d483dceSAndrey Shinkevich return -EINVAL;
47860d483dceSAndrey Shinkevich }
47870d483dceSAndrey Shinkevich
4788fb43d2d4SAlberto Garcia if (offset_into_cluster(s, bytes) &&
4789fb43d2d4SAlberto Garcia (offset + bytes) != (bs->total_sectors << BDRV_SECTOR_BITS)) {
4790fb43d2d4SAlberto Garcia return -EINVAL;
4791fb43d2d4SAlberto Garcia }
4792fb43d2d4SAlberto Garcia
47930d483dceSAndrey Shinkevich while (bytes && aio_task_pool_status(aio) == 0) {
47940d483dceSAndrey Shinkevich uint64_t chunk_size = MIN(bytes, s->cluster_size);
47950d483dceSAndrey Shinkevich
47960d483dceSAndrey Shinkevich if (!aio && chunk_size != bytes) {
47970d483dceSAndrey Shinkevich aio = aio_task_pool_new(QCOW2_MAX_WORKERS);
47980d483dceSAndrey Shinkevich }
47990d483dceSAndrey Shinkevich
48000d483dceSAndrey Shinkevich ret = qcow2_add_task(bs, aio, qcow2_co_pwritev_compressed_task_entry,
48010d483dceSAndrey Shinkevich 0, 0, offset, chunk_size, qiov, qiov_offset, NULL);
48020d483dceSAndrey Shinkevich if (ret < 0) {
48030d483dceSAndrey Shinkevich break;
48040d483dceSAndrey Shinkevich }
48050d483dceSAndrey Shinkevich qiov_offset += chunk_size;
48060d483dceSAndrey Shinkevich offset += chunk_size;
48070d483dceSAndrey Shinkevich bytes -= chunk_size;
48080d483dceSAndrey Shinkevich }
48090d483dceSAndrey Shinkevich
48100d483dceSAndrey Shinkevich if (aio) {
48110d483dceSAndrey Shinkevich aio_task_pool_wait_all(aio);
48120d483dceSAndrey Shinkevich if (ret == 0) {
48130d483dceSAndrey Shinkevich ret = aio_task_pool_status(aio);
48140d483dceSAndrey Shinkevich }
48150d483dceSAndrey Shinkevich g_free(aio);
48160d483dceSAndrey Shinkevich }
48170d483dceSAndrey Shinkevich
48180d483dceSAndrey Shinkevich return ret;
48190d483dceSAndrey Shinkevich }
48200d483dceSAndrey Shinkevich
4821b9b10c35SKevin 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)4822c3c10f72SVladimir Sementsov-Ogievskiy qcow2_co_preadv_compressed(BlockDriverState *bs,
48239a3978a4SVladimir Sementsov-Ogievskiy uint64_t l2_entry,
4824c3c10f72SVladimir Sementsov-Ogievskiy uint64_t offset,
4825c3c10f72SVladimir Sementsov-Ogievskiy uint64_t bytes,
4826df893d25SVladimir Sementsov-Ogievskiy QEMUIOVector *qiov,
4827df893d25SVladimir Sementsov-Ogievskiy size_t qiov_offset)
4828f4b3e2a9SVladimir Sementsov-Ogievskiy {
4829f4b3e2a9SVladimir Sementsov-Ogievskiy BDRVQcow2State *s = bs->opaque;
4830a6e09846SVladimir Sementsov-Ogievskiy int ret = 0, csize;
4831f4b3e2a9SVladimir Sementsov-Ogievskiy uint64_t coffset;
4832c3c10f72SVladimir Sementsov-Ogievskiy uint8_t *buf, *out_buf;
4833c3c10f72SVladimir Sementsov-Ogievskiy int offset_in_cluster = offset_into_cluster(s, offset);
4834f4b3e2a9SVladimir Sementsov-Ogievskiy
4835a6e09846SVladimir Sementsov-Ogievskiy qcow2_parse_compressed_l2_entry(bs, l2_entry, &coffset, &csize);
4836f4b3e2a9SVladimir Sementsov-Ogievskiy
4837c3c10f72SVladimir Sementsov-Ogievskiy buf = g_try_malloc(csize);
4838c3c10f72SVladimir Sementsov-Ogievskiy if (!buf) {
4839f4b3e2a9SVladimir Sementsov-Ogievskiy return -ENOMEM;
4840f4b3e2a9SVladimir Sementsov-Ogievskiy }
4841c068a1cdSVladimir Sementsov-Ogievskiy
4842c3c10f72SVladimir Sementsov-Ogievskiy out_buf = qemu_blockalign(bs, s->cluster_size);
4843c3c10f72SVladimir Sementsov-Ogievskiy
484417362398SPaolo Bonzini BLKDBG_CO_EVENT(bs->file, BLKDBG_READ_COMPRESSED);
4845b00cb15bSVladimir Sementsov-Ogievskiy ret = bdrv_co_pread(bs->file, coffset, csize, buf, 0);
4846f4b3e2a9SVladimir Sementsov-Ogievskiy if (ret < 0) {
4847c3c10f72SVladimir Sementsov-Ogievskiy goto fail;
4848c3c10f72SVladimir Sementsov-Ogievskiy }
4849c3c10f72SVladimir Sementsov-Ogievskiy
4850e23c9d7aSVladimir Sementsov-Ogievskiy if (qcow2_co_decompress(bs, out_buf, s->cluster_size, buf, csize) < 0) {
4851c3c10f72SVladimir Sementsov-Ogievskiy ret = -EIO;
4852c3c10f72SVladimir Sementsov-Ogievskiy goto fail;
4853c3c10f72SVladimir Sementsov-Ogievskiy }
4854c3c10f72SVladimir Sementsov-Ogievskiy
4855df893d25SVladimir Sementsov-Ogievskiy qemu_iovec_from_buf(qiov, qiov_offset, out_buf + offset_in_cluster, bytes);
4856c3c10f72SVladimir Sementsov-Ogievskiy
4857c3c10f72SVladimir Sementsov-Ogievskiy fail:
4858c3c10f72SVladimir Sementsov-Ogievskiy qemu_vfree(out_buf);
4859c3c10f72SVladimir Sementsov-Ogievskiy g_free(buf);
4860c3c10f72SVladimir Sementsov-Ogievskiy
4861f4b3e2a9SVladimir Sementsov-Ogievskiy return ret;
4862f4b3e2a9SVladimir Sementsov-Ogievskiy }
4863f4b3e2a9SVladimir Sementsov-Ogievskiy
make_completely_empty(BlockDriverState * bs)48640bb79c97SKevin Wolf static int GRAPH_RDLOCK make_completely_empty(BlockDriverState *bs)
486594054183SMax Reitz {
4866ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque;
4867ed3d2ec9SMax Reitz Error *local_err = NULL;
486894054183SMax Reitz int ret, l1_clusters;
486994054183SMax Reitz int64_t offset;
487094054183SMax Reitz uint64_t *new_reftable = NULL;
487194054183SMax Reitz uint64_t rt_entry, l1_size2;
487294054183SMax Reitz struct {
487394054183SMax Reitz uint64_t l1_offset;
487494054183SMax Reitz uint64_t reftable_offset;
487594054183SMax Reitz uint32_t reftable_clusters;
487694054183SMax Reitz } QEMU_PACKED l1_ofs_rt_ofs_cls;
487794054183SMax Reitz
487894054183SMax Reitz ret = qcow2_cache_empty(bs, s->l2_table_cache);
487994054183SMax Reitz if (ret < 0) {
488094054183SMax Reitz goto fail;
488194054183SMax Reitz }
488294054183SMax Reitz
488394054183SMax Reitz ret = qcow2_cache_empty(bs, s->refcount_block_cache);
488494054183SMax Reitz if (ret < 0) {
488594054183SMax Reitz goto fail;
488694054183SMax Reitz }
488794054183SMax Reitz
488894054183SMax Reitz /* Refcounts will be broken utterly */
488994054183SMax Reitz ret = qcow2_mark_dirty(bs);
489094054183SMax Reitz if (ret < 0) {
489194054183SMax Reitz goto fail;
489294054183SMax Reitz }
489394054183SMax Reitz
489494054183SMax Reitz BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
489594054183SMax Reitz
489602b1ecfaSAlberto Garcia l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / L1E_SIZE);
489702b1ecfaSAlberto Garcia l1_size2 = (uint64_t)s->l1_size * L1E_SIZE;
489894054183SMax Reitz
489994054183SMax Reitz /* After this call, neither the in-memory nor the on-disk refcount
490094054183SMax Reitz * information accurately describe the actual references */
490194054183SMax Reitz
4902720ff280SKevin Wolf ret = bdrv_pwrite_zeroes(bs->file, s->l1_table_offset,
490374021bc4SEric Blake l1_clusters * s->cluster_size, 0);
490494054183SMax Reitz if (ret < 0) {
490594054183SMax Reitz goto fail_broken_refcounts;
490694054183SMax Reitz }
490794054183SMax Reitz memset(s->l1_table, 0, l1_size2);
490894054183SMax Reitz
490994054183SMax Reitz BLKDBG_EVENT(bs->file, BLKDBG_EMPTY_IMAGE_PREPARE);
491094054183SMax Reitz
491194054183SMax Reitz /* Overwrite enough clusters at the beginning of the sectors to place
491294054183SMax Reitz * the refcount table, a refcount block and the L1 table in; this may
491394054183SMax Reitz * overwrite parts of the existing refcount and L1 table, which is not
491494054183SMax Reitz * an issue because the dirty flag is set, complete data loss is in fact
491594054183SMax Reitz * desired and partial data loss is consequently fine as well */
4916720ff280SKevin Wolf ret = bdrv_pwrite_zeroes(bs->file, s->cluster_size,
491774021bc4SEric Blake (2 + l1_clusters) * s->cluster_size, 0);
491894054183SMax Reitz /* This call (even if it failed overall) may have overwritten on-disk
491994054183SMax Reitz * refcount structures; in that case, the in-memory refcount information
492094054183SMax Reitz * will probably differ from the on-disk information which makes the BDS
492194054183SMax Reitz * unusable */
492294054183SMax Reitz if (ret < 0) {
492394054183SMax Reitz goto fail_broken_refcounts;
492494054183SMax Reitz }
492594054183SMax Reitz
492694054183SMax Reitz BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
492794054183SMax Reitz BLKDBG_EVENT(bs->file, BLKDBG_REFTABLE_UPDATE);
492894054183SMax Reitz
492994054183SMax Reitz /* "Create" an empty reftable (one cluster) directly after the image
493094054183SMax Reitz * header and an empty L1 table three clusters after the image header;
493194054183SMax Reitz * the cluster between those two will be used as the first refblock */
4932f1f7a1ddSPeter Maydell l1_ofs_rt_ofs_cls.l1_offset = cpu_to_be64(3 * s->cluster_size);
4933f1f7a1ddSPeter Maydell l1_ofs_rt_ofs_cls.reftable_offset = cpu_to_be64(s->cluster_size);
4934f1f7a1ddSPeter Maydell l1_ofs_rt_ofs_cls.reftable_clusters = cpu_to_be32(1);
4935d9ca2ea2SKevin Wolf ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, l1_table_offset),
493632cc71deSAlberto Faria sizeof(l1_ofs_rt_ofs_cls), &l1_ofs_rt_ofs_cls, 0);
493794054183SMax Reitz if (ret < 0) {
493894054183SMax Reitz goto fail_broken_refcounts;
493994054183SMax Reitz }
494094054183SMax Reitz
494194054183SMax Reitz s->l1_table_offset = 3 * s->cluster_size;
494294054183SMax Reitz
494302b1ecfaSAlberto Garcia new_reftable = g_try_new0(uint64_t, s->cluster_size / REFTABLE_ENTRY_SIZE);
494494054183SMax Reitz if (!new_reftable) {
494594054183SMax Reitz ret = -ENOMEM;
494694054183SMax Reitz goto fail_broken_refcounts;
494794054183SMax Reitz }
494894054183SMax Reitz
494994054183SMax Reitz s->refcount_table_offset = s->cluster_size;
495002b1ecfaSAlberto Garcia s->refcount_table_size = s->cluster_size / REFTABLE_ENTRY_SIZE;
49517061a078SAlberto Garcia s->max_refcount_table_index = 0;
495294054183SMax Reitz
495394054183SMax Reitz g_free(s->refcount_table);
495494054183SMax Reitz s->refcount_table = new_reftable;
495594054183SMax Reitz new_reftable = NULL;
495694054183SMax Reitz
495794054183SMax Reitz /* Now the in-memory refcount information again corresponds to the on-disk
495894054183SMax Reitz * information (reftable is empty and no refblocks (the refblock cache is
495994054183SMax Reitz * empty)); however, this means some clusters (e.g. the image header) are
496094054183SMax Reitz * referenced, but not refcounted, but the normal qcow2 code assumes that
496194054183SMax Reitz * the in-memory information is always correct */
496294054183SMax Reitz
496394054183SMax Reitz BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_ALLOC);
496494054183SMax Reitz
496594054183SMax Reitz /* Enter the first refblock into the reftable */
496694054183SMax Reitz rt_entry = cpu_to_be64(2 * s->cluster_size);
496732cc71deSAlberto Faria ret = bdrv_pwrite_sync(bs->file, s->cluster_size, sizeof(rt_entry),
496832cc71deSAlberto Faria &rt_entry, 0);
496994054183SMax Reitz if (ret < 0) {
497094054183SMax Reitz goto fail_broken_refcounts;
497194054183SMax Reitz }
497294054183SMax Reitz s->refcount_table[0] = 2 * s->cluster_size;
497394054183SMax Reitz
497494054183SMax Reitz s->free_cluster_index = 0;
497594054183SMax Reitz assert(3 + l1_clusters <= s->refcount_block_size);
497694054183SMax Reitz offset = qcow2_alloc_clusters(bs, 3 * s->cluster_size + l1_size2);
497794054183SMax Reitz if (offset < 0) {
497894054183SMax Reitz ret = offset;
497994054183SMax Reitz goto fail_broken_refcounts;
498094054183SMax Reitz } else if (offset > 0) {
498194054183SMax Reitz error_report("First cluster in emptied image is in use");
498294054183SMax Reitz abort();
498394054183SMax Reitz }
498494054183SMax Reitz
498594054183SMax Reitz /* Now finally the in-memory information corresponds to the on-disk
498694054183SMax Reitz * structures and is correct */
498794054183SMax Reitz ret = qcow2_mark_clean(bs);
498894054183SMax Reitz if (ret < 0) {
498994054183SMax Reitz goto fail;
499094054183SMax Reitz }
499194054183SMax Reitz
4992c80d8b06SMax Reitz ret = bdrv_truncate(bs->file, (3 + l1_clusters) * s->cluster_size, false,
49937b8e4857SKevin Wolf PREALLOC_MODE_OFF, 0, &local_err);
499494054183SMax Reitz if (ret < 0) {
4995ed3d2ec9SMax Reitz error_report_err(local_err);
499694054183SMax Reitz goto fail;
499794054183SMax Reitz }
499894054183SMax Reitz
499994054183SMax Reitz return 0;
500094054183SMax Reitz
500194054183SMax Reitz fail_broken_refcounts:
500294054183SMax Reitz /* The BDS is unusable at this point. If we wanted to make it usable, we
500394054183SMax Reitz * would have to call qcow2_refcount_close(), qcow2_refcount_init(),
500494054183SMax Reitz * qcow2_check_refcounts(), qcow2_refcount_close() and qcow2_refcount_init()
500594054183SMax Reitz * again. However, because the functions which could have caused this error
500694054183SMax Reitz * path to be taken are used by those functions as well, it's very likely
500794054183SMax Reitz * that that sequence will fail as well. Therefore, just eject the BDS. */
500894054183SMax Reitz bs->drv = NULL;
500994054183SMax Reitz
501094054183SMax Reitz fail:
501194054183SMax Reitz g_free(new_reftable);
501294054183SMax Reitz return ret;
501394054183SMax Reitz }
501494054183SMax Reitz
qcow2_make_empty(BlockDriverState * bs)50150bb79c97SKevin Wolf static int GRAPH_RDLOCK qcow2_make_empty(BlockDriverState *bs)
5016491d27e2SMax Reitz {
5017ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque;
5018d2cb36afSEric Blake uint64_t offset, end_offset;
5019d2cb36afSEric Blake int step = QEMU_ALIGN_DOWN(INT_MAX, s->cluster_size);
502094054183SMax Reitz int l1_clusters, ret = 0;
5021491d27e2SMax Reitz
502202b1ecfaSAlberto Garcia l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / L1E_SIZE);
502394054183SMax Reitz
50244096974eSEric Blake if (s->qcow_version >= 3 && !s->snapshots && !s->nb_bitmaps &&
5025f0603329SDaniel P. Berrange 3 + l1_clusters <= s->refcount_block_size &&
5026db04524fSKevin Wolf s->crypt_method_header != QCOW_CRYPT_LUKS &&
5027db04524fSKevin Wolf !has_data_file(bs)) {
50284096974eSEric Blake /* The following function only works for qcow2 v3 images (it
50294096974eSEric Blake * requires the dirty flag) and only as long as there are no
50304096974eSEric Blake * features that reserve extra clusters (such as snapshots,
50314096974eSEric Blake * LUKS header, or persistent bitmaps), because it completely
50324096974eSEric Blake * empties the image. Furthermore, the L1 table and three
50334096974eSEric Blake * additional clusters (image header, refcount table, one
5034db04524fSKevin Wolf * refcount block) have to fit inside one refcount block. It
5035db04524fSKevin Wolf * only resets the image file, i.e. does not work with an
5036db04524fSKevin Wolf * external data file. */
503794054183SMax Reitz return make_completely_empty(bs);
503894054183SMax Reitz }
503994054183SMax Reitz
504094054183SMax Reitz /* This fallback code simply discards every active cluster; this is slow,
504194054183SMax Reitz * but works in all cases */
5042d2cb36afSEric Blake end_offset = bs->total_sectors * BDRV_SECTOR_SIZE;
5043d2cb36afSEric Blake for (offset = 0; offset < end_offset; offset += step) {
5044491d27e2SMax Reitz /* As this function is generally used after committing an external
5045491d27e2SMax Reitz * snapshot, QCOW2_DISCARD_SNAPSHOT seems appropriate. Also, the
5046491d27e2SMax Reitz * default action for this kind of discard is to pass the discard,
5047491d27e2SMax Reitz * which will ideally result in an actually smaller image file, as
5048491d27e2SMax Reitz * is probably desired. */
5049d2cb36afSEric Blake ret = qcow2_cluster_discard(bs, offset, MIN(step, end_offset - offset),
5050491d27e2SMax Reitz QCOW2_DISCARD_SNAPSHOT, true);
5051491d27e2SMax Reitz if (ret < 0) {
5052491d27e2SMax Reitz break;
5053491d27e2SMax Reitz }
5054491d27e2SMax Reitz }
5055491d27e2SMax Reitz
5056491d27e2SMax Reitz return ret;
5057491d27e2SMax Reitz }
5058491d27e2SMax Reitz
qcow2_co_flush_to_os(BlockDriverState * bs)50590bb79c97SKevin Wolf static coroutine_fn GRAPH_RDLOCK int qcow2_co_flush_to_os(BlockDriverState *bs)
506020d97356SBlue Swirl {
5061ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque;
506229c1a730SKevin Wolf int ret;
506329c1a730SKevin Wolf
50648b94ff85SPaolo Bonzini qemu_co_mutex_lock(&s->lock);
50658b220eb7SPaolo Bonzini ret = qcow2_write_caches(bs);
50668b94ff85SPaolo Bonzini qemu_co_mutex_unlock(&s->lock);
506729c1a730SKevin Wolf
50688b220eb7SPaolo Bonzini return ret;
5069eb489bb1SKevin Wolf }
5070eb489bb1SKevin Wolf
qcow2_measure(QemuOpts * opts,BlockDriverState * in_bs,Error ** errp)5071c501c352SStefan Hajnoczi static BlockMeasureInfo *qcow2_measure(QemuOpts *opts, BlockDriverState *in_bs,
5072c501c352SStefan Hajnoczi Error **errp)
5073c501c352SStefan Hajnoczi {
5074c501c352SStefan Hajnoczi Error *local_err = NULL;
5075c501c352SStefan Hajnoczi BlockMeasureInfo *info;
5076c501c352SStefan Hajnoczi uint64_t required = 0; /* bytes that contribute to required size */
5077c501c352SStefan Hajnoczi uint64_t virtual_size; /* disk size as seen by guest */
5078c501c352SStefan Hajnoczi uint64_t refcount_bits;
5079c501c352SStefan Hajnoczi uint64_t l2_tables;
508061914f89SStefan Hajnoczi uint64_t luks_payload_size = 0;
5081c501c352SStefan Hajnoczi size_t cluster_size;
5082c501c352SStefan Hajnoczi int version;
5083c501c352SStefan Hajnoczi char *optstr;
5084c501c352SStefan Hajnoczi PreallocMode prealloc;
5085c501c352SStefan Hajnoczi bool has_backing_file;
508661914f89SStefan Hajnoczi bool has_luks;
50877be20252SAlberto Garcia bool extended_l2;
50880dd07b29SAlberto Garcia size_t l2e_size;
5089c501c352SStefan Hajnoczi
5090c501c352SStefan Hajnoczi /* Parse image creation options */
50917be20252SAlberto Garcia extended_l2 = qemu_opt_get_bool_del(opts, BLOCK_OPT_EXTL2, false);
50927be20252SAlberto Garcia
50937be20252SAlberto Garcia cluster_size = qcow2_opt_get_cluster_size_del(opts, extended_l2,
50947be20252SAlberto Garcia &local_err);
5095c501c352SStefan Hajnoczi if (local_err) {
5096c501c352SStefan Hajnoczi goto err;
5097c501c352SStefan Hajnoczi }
5098c501c352SStefan Hajnoczi
5099c501c352SStefan Hajnoczi version = qcow2_opt_get_version_del(opts, &local_err);
5100c501c352SStefan Hajnoczi if (local_err) {
5101c501c352SStefan Hajnoczi goto err;
5102c501c352SStefan Hajnoczi }
5103c501c352SStefan Hajnoczi
5104c501c352SStefan Hajnoczi refcount_bits = qcow2_opt_get_refcount_bits_del(opts, version, &local_err);
5105c501c352SStefan Hajnoczi if (local_err) {
5106c501c352SStefan Hajnoczi goto err;
5107c501c352SStefan Hajnoczi }
5108c501c352SStefan Hajnoczi
5109c501c352SStefan Hajnoczi optstr = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
5110f7abe0ecSMarc-André Lureau prealloc = qapi_enum_parse(&PreallocMode_lookup, optstr,
511106c60b6cSMarkus Armbruster PREALLOC_MODE_OFF, &local_err);
5112c501c352SStefan Hajnoczi g_free(optstr);
5113c501c352SStefan Hajnoczi if (local_err) {
5114c501c352SStefan Hajnoczi goto err;
5115c501c352SStefan Hajnoczi }
5116c501c352SStefan Hajnoczi
5117c501c352SStefan Hajnoczi optstr = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
5118c501c352SStefan Hajnoczi has_backing_file = !!optstr;
5119c501c352SStefan Hajnoczi g_free(optstr);
5120c501c352SStefan Hajnoczi
512161914f89SStefan Hajnoczi optstr = qemu_opt_get_del(opts, BLOCK_OPT_ENCRYPT_FORMAT);
512261914f89SStefan Hajnoczi has_luks = optstr && strcmp(optstr, "luks") == 0;
512361914f89SStefan Hajnoczi g_free(optstr);
512461914f89SStefan Hajnoczi
512561914f89SStefan Hajnoczi if (has_luks) {
51266d49d3a8SStefan Hajnoczi g_autoptr(QCryptoBlockCreateOptions) create_opts = NULL;
512790766d9dSMaxim Levitsky QDict *cryptoopts = qcow2_extract_crypto_opts(opts, "luks", errp);
512861914f89SStefan Hajnoczi size_t headerlen;
512961914f89SStefan Hajnoczi
51306d49d3a8SStefan Hajnoczi create_opts = block_crypto_create_opts_init(cryptoopts, errp);
51316d49d3a8SStefan Hajnoczi qobject_unref(cryptoopts);
51326d49d3a8SStefan Hajnoczi if (!create_opts) {
51336d49d3a8SStefan Hajnoczi goto err;
51346d49d3a8SStefan Hajnoczi }
51356d49d3a8SStefan Hajnoczi
51366d49d3a8SStefan Hajnoczi if (!qcrypto_block_calculate_payload_offset(create_opts,
51376d49d3a8SStefan Hajnoczi "encrypt.",
51386d49d3a8SStefan Hajnoczi &headerlen,
51396d49d3a8SStefan Hajnoczi &local_err)) {
514061914f89SStefan Hajnoczi goto err;
514161914f89SStefan Hajnoczi }
514261914f89SStefan Hajnoczi
514361914f89SStefan Hajnoczi luks_payload_size = ROUND_UP(headerlen, cluster_size);
514461914f89SStefan Hajnoczi }
514561914f89SStefan Hajnoczi
51469e029689SAlberto Garcia virtual_size = qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0);
51479e029689SAlberto Garcia virtual_size = ROUND_UP(virtual_size, cluster_size);
5148c501c352SStefan Hajnoczi
5149c501c352SStefan Hajnoczi /* Check that virtual disk size is valid */
51500dd07b29SAlberto Garcia l2e_size = extended_l2 ? L2E_SIZE_EXTENDED : L2E_SIZE_NORMAL;
5151c501c352SStefan Hajnoczi l2_tables = DIV_ROUND_UP(virtual_size / cluster_size,
51520dd07b29SAlberto Garcia cluster_size / l2e_size);
515302b1ecfaSAlberto Garcia if (l2_tables * L1E_SIZE > QCOW_MAX_L1_SIZE) {
5154c501c352SStefan Hajnoczi error_setg(&local_err, "The image size is too large "
5155c501c352SStefan Hajnoczi "(try using a larger cluster size)");
5156c501c352SStefan Hajnoczi goto err;
5157c501c352SStefan Hajnoczi }
5158c501c352SStefan Hajnoczi
5159c501c352SStefan Hajnoczi /* Account for input image */
5160c501c352SStefan Hajnoczi if (in_bs) {
5161c501c352SStefan Hajnoczi int64_t ssize = bdrv_getlength(in_bs);
5162c501c352SStefan Hajnoczi if (ssize < 0) {
5163c501c352SStefan Hajnoczi error_setg_errno(&local_err, -ssize,
5164c501c352SStefan Hajnoczi "Unable to get image virtual_size");
5165c501c352SStefan Hajnoczi goto err;
5166c501c352SStefan Hajnoczi }
5167c501c352SStefan Hajnoczi
51689e029689SAlberto Garcia virtual_size = ROUND_UP(ssize, cluster_size);
5169c501c352SStefan Hajnoczi
5170c501c352SStefan Hajnoczi if (has_backing_file) {
5171c501c352SStefan Hajnoczi /* We don't how much of the backing chain is shared by the input
5172c501c352SStefan Hajnoczi * image and the new image file. In the worst case the new image's
5173c501c352SStefan Hajnoczi * backing file has nothing in common with the input image. Be
5174c501c352SStefan Hajnoczi * conservative and assume all clusters need to be written.
5175c501c352SStefan Hajnoczi */
5176c501c352SStefan Hajnoczi required = virtual_size;
5177c501c352SStefan Hajnoczi } else {
5178b85ee453SEric Blake int64_t offset;
517931826642SEric Blake int64_t pnum = 0;
5180c501c352SStefan Hajnoczi
518131826642SEric Blake for (offset = 0; offset < ssize; offset += pnum) {
518231826642SEric Blake int ret;
5183c501c352SStefan Hajnoczi
518431826642SEric Blake ret = bdrv_block_status_above(in_bs, NULL, offset,
518531826642SEric Blake ssize - offset, &pnum, NULL,
518631826642SEric Blake NULL);
5187c501c352SStefan Hajnoczi if (ret < 0) {
5188c501c352SStefan Hajnoczi error_setg_errno(&local_err, -ret,
5189c501c352SStefan Hajnoczi "Unable to get block status");
5190c501c352SStefan Hajnoczi goto err;
5191c501c352SStefan Hajnoczi }
5192c501c352SStefan Hajnoczi
5193c501c352SStefan Hajnoczi if (ret & BDRV_BLOCK_ZERO) {
5194c501c352SStefan Hajnoczi /* Skip zero regions (safe with no backing file) */
5195c501c352SStefan Hajnoczi } else if ((ret & (BDRV_BLOCK_DATA | BDRV_BLOCK_ALLOCATED)) ==
5196c501c352SStefan Hajnoczi (BDRV_BLOCK_DATA | BDRV_BLOCK_ALLOCATED)) {
5197c501c352SStefan Hajnoczi /* Extend pnum to end of cluster for next iteration */
519831826642SEric Blake pnum = ROUND_UP(offset + pnum, cluster_size) - offset;
5199c501c352SStefan Hajnoczi
5200c501c352SStefan Hajnoczi /* Count clusters we've seen */
520131826642SEric Blake required += offset % cluster_size + pnum;
5202c501c352SStefan Hajnoczi }
5203c501c352SStefan Hajnoczi }
5204c501c352SStefan Hajnoczi }
5205c501c352SStefan Hajnoczi }
5206c501c352SStefan Hajnoczi
5207c501c352SStefan Hajnoczi /* Take into account preallocation. Nothing special is needed for
5208c501c352SStefan Hajnoczi * PREALLOC_MODE_METADATA since metadata is always counted.
5209c501c352SStefan Hajnoczi */
5210c501c352SStefan Hajnoczi if (prealloc == PREALLOC_MODE_FULL || prealloc == PREALLOC_MODE_FALLOC) {
5211c501c352SStefan Hajnoczi required = virtual_size;
5212c501c352SStefan Hajnoczi }
5213c501c352SStefan Hajnoczi
52145d72c68bSEric Blake info = g_new0(BlockMeasureInfo, 1);
52150dd07b29SAlberto Garcia info->fully_allocated = luks_payload_size +
5216c501c352SStefan Hajnoczi qcow2_calc_prealloc_size(virtual_size, cluster_size,
52170dd07b29SAlberto Garcia ctz32(refcount_bits), extended_l2);
5218c501c352SStefan Hajnoczi
52195d72c68bSEric Blake /*
52205d72c68bSEric Blake * Remove data clusters that are not required. This overestimates the
5221c501c352SStefan Hajnoczi * required size because metadata needed for the fully allocated file is
52225d72c68bSEric Blake * still counted. Show bitmaps only if both source and destination
52235d72c68bSEric Blake * would support them.
5224c501c352SStefan Hajnoczi */
5225c501c352SStefan Hajnoczi info->required = info->fully_allocated - virtual_size + required;
52265d72c68bSEric Blake info->has_bitmaps = version >= 3 && in_bs &&
52275d72c68bSEric Blake bdrv_supports_persistent_dirty_bitmap(in_bs);
52285d72c68bSEric Blake if (info->has_bitmaps) {
52295d72c68bSEric Blake info->bitmaps = qcow2_get_persistent_dirty_bitmap_size(in_bs,
52305d72c68bSEric Blake cluster_size);
52315d72c68bSEric Blake }
5232c501c352SStefan Hajnoczi return info;
5233c501c352SStefan Hajnoczi
5234c501c352SStefan Hajnoczi err:
5235c501c352SStefan Hajnoczi error_propagate(errp, local_err);
5236c501c352SStefan Hajnoczi return NULL;
5237c501c352SStefan Hajnoczi }
5238c501c352SStefan Hajnoczi
52393d47eb0aSEmanuele Giuseppe Esposito static int coroutine_fn
qcow2_co_get_info(BlockDriverState * bs,BlockDriverInfo * bdi)52403d47eb0aSEmanuele Giuseppe Esposito qcow2_co_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
524120d97356SBlue Swirl {
5242ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque;
524320d97356SBlue Swirl bdi->cluster_size = s->cluster_size;
5244c54483b6SAndrey Drobyshev bdi->subcluster_size = s->subcluster_size;
52457c80ab3fSJes Sorensen bdi->vm_state_offset = qcow2_vm_state_offset(s);
524638b44096SVladimir Sementsov-Ogievskiy bdi->is_dirty = s->incompatible_features & QCOW2_INCOMPAT_DIRTY;
524720d97356SBlue Swirl return 0;
524820d97356SBlue Swirl }
524920d97356SBlue Swirl
525079a55866SKevin Wolf static ImageInfoSpecific * GRAPH_RDLOCK
qcow2_get_specific_info(BlockDriverState * bs,Error ** errp)525179a55866SKevin Wolf qcow2_get_specific_info(BlockDriverState *bs, Error **errp)
525237764dfbSMax Reitz {
5253ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque;
52540a12f6f8SDaniel P. Berrange ImageInfoSpecific *spec_info;
52550a12f6f8SDaniel P. Berrange QCryptoBlockInfo *encrypt_info = NULL;
525637764dfbSMax Reitz
52570a12f6f8SDaniel P. Berrange if (s->crypto != NULL) {
525883bad8cbSVladimir Sementsov-Ogievskiy encrypt_info = qcrypto_block_get_info(s->crypto, errp);
525983bad8cbSVladimir Sementsov-Ogievskiy if (!encrypt_info) {
52601bf6e9caSAndrey Shinkevich return NULL;
52611bf6e9caSAndrey Shinkevich }
52620a12f6f8SDaniel P. Berrange }
52630a12f6f8SDaniel P. Berrange
52640a12f6f8SDaniel P. Berrange spec_info = g_new(ImageInfoSpecific, 1);
526537764dfbSMax Reitz *spec_info = (ImageInfoSpecific){
52666a8f9661SEric Blake .type = IMAGE_INFO_SPECIFIC_KIND_QCOW2,
5267b8968c87SAndrey Shinkevich .u.qcow2.data = g_new0(ImageInfoSpecificQCow2, 1),
526837764dfbSMax Reitz };
526937764dfbSMax Reitz if (s->qcow_version == 2) {
527032bafa8fSEric Blake *spec_info->u.qcow2.data = (ImageInfoSpecificQCow2){
527137764dfbSMax Reitz .compat = g_strdup("0.10"),
52720709c5a1SMax Reitz .refcount_bits = s->refcount_bits,
527337764dfbSMax Reitz };
527437764dfbSMax Reitz } else if (s->qcow_version == 3) {
5275b8968c87SAndrey Shinkevich Qcow2BitmapInfoList *bitmaps;
527683bad8cbSVladimir Sementsov-Ogievskiy if (!qcow2_get_bitmap_info_list(bs, &bitmaps, errp)) {
5277b8968c87SAndrey Shinkevich qapi_free_ImageInfoSpecific(spec_info);
527871eaec2eSEric Blake qapi_free_QCryptoBlockInfo(encrypt_info);
5279b8968c87SAndrey Shinkevich return NULL;
5280b8968c87SAndrey Shinkevich }
528132bafa8fSEric Blake *spec_info->u.qcow2.data = (ImageInfoSpecificQCow2){
528237764dfbSMax Reitz .compat = g_strdup("1.1"),
528337764dfbSMax Reitz .lazy_refcounts = s->compatible_features &
528437764dfbSMax Reitz QCOW2_COMPAT_LAZY_REFCOUNTS,
528537764dfbSMax Reitz .has_lazy_refcounts = true,
52869009b196SMax Reitz .corrupt = s->incompatible_features &
52879009b196SMax Reitz QCOW2_INCOMPAT_CORRUPT,
52889009b196SMax Reitz .has_corrupt = true,
52897be20252SAlberto Garcia .has_extended_l2 = true,
52907be20252SAlberto Garcia .extended_l2 = has_subclusters(s),
52910709c5a1SMax Reitz .refcount_bits = s->refcount_bits,
5292b8968c87SAndrey Shinkevich .has_bitmaps = !!bitmaps,
5293b8968c87SAndrey Shinkevich .bitmaps = bitmaps,
52949b890bdcSKevin Wolf .data_file = g_strdup(s->image_data_file),
52956c3944dcSKevin Wolf .has_data_file_raw = has_data_file(bs),
52966c3944dcSKevin Wolf .data_file_raw = data_file_is_raw(bs),
5297572ad978SDenis Plotnikov .compression_type = s->compression_type,
529837764dfbSMax Reitz };
5299b1fc8f93SDenis V. Lunev } else {
5300b1fc8f93SDenis V. Lunev /* if this assertion fails, this probably means a new version was
5301b1fc8f93SDenis V. Lunev * added without having it covered here */
5302*d125e4afSPierrick Bouvier g_assert_not_reached();
530337764dfbSMax Reitz }
530437764dfbSMax Reitz
53050a12f6f8SDaniel P. Berrange if (encrypt_info) {
53060a12f6f8SDaniel P. Berrange ImageInfoSpecificQCow2Encryption *qencrypt =
53070a12f6f8SDaniel P. Berrange g_new(ImageInfoSpecificQCow2Encryption, 1);
53080a12f6f8SDaniel P. Berrange switch (encrypt_info->format) {
5309d23d2ef3SMarkus Armbruster case QCRYPTO_BLOCK_FORMAT_QCOW:
53100a12f6f8SDaniel P. Berrange qencrypt->format = BLOCKDEV_QCOW2_ENCRYPTION_FORMAT_AES;
53110a12f6f8SDaniel P. Berrange break;
5312d23d2ef3SMarkus Armbruster case QCRYPTO_BLOCK_FORMAT_LUKS:
53130a12f6f8SDaniel P. Berrange qencrypt->format = BLOCKDEV_QCOW2_ENCRYPTION_FORMAT_LUKS;
53140a12f6f8SDaniel P. Berrange qencrypt->u.luks = encrypt_info->u.luks;
53150a12f6f8SDaniel P. Berrange break;
53160a12f6f8SDaniel P. Berrange default:
53170a12f6f8SDaniel P. Berrange abort();
53180a12f6f8SDaniel P. Berrange }
53190a12f6f8SDaniel P. Berrange /* Since we did shallow copy above, erase any pointers
53200a12f6f8SDaniel P. Berrange * in the original info */
53210a12f6f8SDaniel P. Berrange memset(&encrypt_info->u, 0, sizeof(encrypt_info->u));
53220a12f6f8SDaniel P. Berrange qapi_free_QCryptoBlockInfo(encrypt_info);
53230a12f6f8SDaniel P. Berrange
53240a12f6f8SDaniel P. Berrange spec_info->u.qcow2.data->encrypt = qencrypt;
53250a12f6f8SDaniel P. Berrange }
53260a12f6f8SDaniel P. Berrange
532737764dfbSMax Reitz return spec_info;
532837764dfbSMax Reitz }
532937764dfbSMax Reitz
533006717986SKevin Wolf static int coroutine_mixed_fn GRAPH_RDLOCK
qcow2_has_zero_init(BlockDriverState * bs)533106717986SKevin Wolf qcow2_has_zero_init(BlockDriverState *bs)
533238841dcdSMax Reitz {
533338841dcdSMax Reitz BDRVQcow2State *s = bs->opaque;
533438841dcdSMax Reitz bool preallocated;
533538841dcdSMax Reitz
533638841dcdSMax Reitz if (qemu_in_coroutine()) {
533738841dcdSMax Reitz qemu_co_mutex_lock(&s->lock);
533838841dcdSMax Reitz }
533938841dcdSMax Reitz /*
534038841dcdSMax Reitz * Check preallocation status: Preallocated images have all L2
534138841dcdSMax Reitz * tables allocated, nonpreallocated images have none. It is
534238841dcdSMax Reitz * therefore enough to check the first one.
534338841dcdSMax Reitz */
534438841dcdSMax Reitz preallocated = s->l1_size > 0 && s->l1_table[0] != 0;
534538841dcdSMax Reitz if (qemu_in_coroutine()) {
534638841dcdSMax Reitz qemu_co_mutex_unlock(&s->lock);
534738841dcdSMax Reitz }
534838841dcdSMax Reitz
534938841dcdSMax Reitz if (!preallocated) {
535038841dcdSMax Reitz return 1;
535138841dcdSMax Reitz } else if (bs->encrypted) {
535238841dcdSMax Reitz return 0;
535338841dcdSMax Reitz } else {
535438841dcdSMax Reitz return bdrv_has_zero_init(s->data_file->bs);
535538841dcdSMax Reitz }
535638841dcdSMax Reitz }
535738841dcdSMax Reitz
5358558902ccSVladimir Sementsov-Ogievskiy /*
5359558902ccSVladimir Sementsov-Ogievskiy * Check the request to vmstate. On success return
5360558902ccSVladimir Sementsov-Ogievskiy * qcow2_vm_state_offset(bs) + @pos
5361558902ccSVladimir Sementsov-Ogievskiy */
qcow2_check_vmstate_request(BlockDriverState * bs,QEMUIOVector * qiov,int64_t pos)5362558902ccSVladimir Sementsov-Ogievskiy static int64_t qcow2_check_vmstate_request(BlockDriverState *bs,
5363558902ccSVladimir Sementsov-Ogievskiy QEMUIOVector *qiov, int64_t pos)
5364558902ccSVladimir Sementsov-Ogievskiy {
5365558902ccSVladimir Sementsov-Ogievskiy BDRVQcow2State *s = bs->opaque;
5366558902ccSVladimir Sementsov-Ogievskiy int64_t vmstate_offset = qcow2_vm_state_offset(s);
5367558902ccSVladimir Sementsov-Ogievskiy int ret;
5368558902ccSVladimir Sementsov-Ogievskiy
5369558902ccSVladimir Sementsov-Ogievskiy /* Incoming requests must be OK */
5370558902ccSVladimir Sementsov-Ogievskiy bdrv_check_qiov_request(pos, qiov->size, qiov, 0, &error_abort);
5371558902ccSVladimir Sementsov-Ogievskiy
5372558902ccSVladimir Sementsov-Ogievskiy if (INT64_MAX - pos < vmstate_offset) {
5373558902ccSVladimir Sementsov-Ogievskiy return -EIO;
5374558902ccSVladimir Sementsov-Ogievskiy }
5375558902ccSVladimir Sementsov-Ogievskiy
5376558902ccSVladimir Sementsov-Ogievskiy pos += vmstate_offset;
5377558902ccSVladimir Sementsov-Ogievskiy ret = bdrv_check_qiov_request(pos, qiov->size, qiov, 0, NULL);
5378558902ccSVladimir Sementsov-Ogievskiy if (ret < 0) {
5379558902ccSVladimir Sementsov-Ogievskiy return ret;
5380558902ccSVladimir Sementsov-Ogievskiy }
5381558902ccSVladimir Sementsov-Ogievskiy
5382558902ccSVladimir Sementsov-Ogievskiy return pos;
5383558902ccSVladimir Sementsov-Ogievskiy }
5384558902ccSVladimir Sementsov-Ogievskiy
53857b1fb72eSKevin Wolf static int coroutine_fn GRAPH_RDLOCK
qcow2_co_save_vmstate(BlockDriverState * bs,QEMUIOVector * qiov,int64_t pos)53867b1fb72eSKevin Wolf qcow2_co_save_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos)
538720d97356SBlue Swirl {
5388558902ccSVladimir Sementsov-Ogievskiy int64_t offset = qcow2_check_vmstate_request(bs, qiov, pos);
5389558902ccSVladimir Sementsov-Ogievskiy if (offset < 0) {
5390558902ccSVladimir Sementsov-Ogievskiy return offset;
5391558902ccSVladimir Sementsov-Ogievskiy }
539220d97356SBlue Swirl
539317362398SPaolo Bonzini BLKDBG_CO_EVENT(bs->file, BLKDBG_VMSTATE_SAVE);
5394558902ccSVladimir Sementsov-Ogievskiy return bs->drv->bdrv_co_pwritev_part(bs, offset, qiov->size, qiov, 0, 0);
539520d97356SBlue Swirl }
539620d97356SBlue Swirl
53977b1fb72eSKevin Wolf static int coroutine_fn GRAPH_RDLOCK
qcow2_co_load_vmstate(BlockDriverState * bs,QEMUIOVector * qiov,int64_t pos)53987b1fb72eSKevin Wolf qcow2_co_load_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos)
539920d97356SBlue Swirl {
5400558902ccSVladimir Sementsov-Ogievskiy int64_t offset = qcow2_check_vmstate_request(bs, qiov, pos);
5401558902ccSVladimir Sementsov-Ogievskiy if (offset < 0) {
5402558902ccSVladimir Sementsov-Ogievskiy return offset;
5403558902ccSVladimir Sementsov-Ogievskiy }
540420d97356SBlue Swirl
540517362398SPaolo Bonzini BLKDBG_CO_EVENT(bs->file, BLKDBG_VMSTATE_LOAD);
5406558902ccSVladimir Sementsov-Ogievskiy return bs->drv->bdrv_co_preadv_part(bs, offset, qiov->size, qiov, 0, 0);
540720d97356SBlue Swirl }
540820d97356SBlue Swirl
qcow2_has_compressed_clusters(BlockDriverState * bs)54090bb79c97SKevin Wolf static int GRAPH_RDLOCK qcow2_has_compressed_clusters(BlockDriverState *bs)
5410083c2456SVladimir Sementsov-Ogievskiy {
5411083c2456SVladimir Sementsov-Ogievskiy int64_t offset = 0;
5412083c2456SVladimir Sementsov-Ogievskiy int64_t bytes = bdrv_getlength(bs);
5413083c2456SVladimir Sementsov-Ogievskiy
5414083c2456SVladimir Sementsov-Ogievskiy if (bytes < 0) {
5415083c2456SVladimir Sementsov-Ogievskiy return bytes;
5416083c2456SVladimir Sementsov-Ogievskiy }
5417083c2456SVladimir Sementsov-Ogievskiy
5418083c2456SVladimir Sementsov-Ogievskiy while (bytes != 0) {
5419083c2456SVladimir Sementsov-Ogievskiy int ret;
5420083c2456SVladimir Sementsov-Ogievskiy QCow2SubclusterType type;
5421083c2456SVladimir Sementsov-Ogievskiy unsigned int cur_bytes = MIN(INT_MAX, bytes);
5422083c2456SVladimir Sementsov-Ogievskiy uint64_t host_offset;
5423083c2456SVladimir Sementsov-Ogievskiy
5424083c2456SVladimir Sementsov-Ogievskiy ret = qcow2_get_host_offset(bs, offset, &cur_bytes, &host_offset,
5425083c2456SVladimir Sementsov-Ogievskiy &type);
5426083c2456SVladimir Sementsov-Ogievskiy if (ret < 0) {
5427083c2456SVladimir Sementsov-Ogievskiy return ret;
5428083c2456SVladimir Sementsov-Ogievskiy }
5429083c2456SVladimir Sementsov-Ogievskiy
5430083c2456SVladimir Sementsov-Ogievskiy if (type == QCOW2_SUBCLUSTER_COMPRESSED) {
5431083c2456SVladimir Sementsov-Ogievskiy return 1;
5432083c2456SVladimir Sementsov-Ogievskiy }
5433083c2456SVladimir Sementsov-Ogievskiy
5434083c2456SVladimir Sementsov-Ogievskiy offset += cur_bytes;
5435083c2456SVladimir Sementsov-Ogievskiy bytes -= cur_bytes;
5436083c2456SVladimir Sementsov-Ogievskiy }
5437083c2456SVladimir Sementsov-Ogievskiy
5438083c2456SVladimir Sementsov-Ogievskiy return 0;
5439083c2456SVladimir Sementsov-Ogievskiy }
5440083c2456SVladimir Sementsov-Ogievskiy
54419296b3edSMax Reitz /*
54429296b3edSMax Reitz * Downgrades an image's version. To achieve this, any incompatible features
54439296b3edSMax Reitz * have to be removed.
54449296b3edSMax Reitz */
54450bb79c97SKevin Wolf static int GRAPH_RDLOCK
qcow2_downgrade(BlockDriverState * bs,int target_version,BlockDriverAmendStatusCB * status_cb,void * cb_opaque,Error ** errp)54460bb79c97SKevin Wolf qcow2_downgrade(BlockDriverState *bs, int target_version,
5447d1402b50SMax Reitz BlockDriverAmendStatusCB *status_cb, void *cb_opaque,
5448d1402b50SMax Reitz Error **errp)
54499296b3edSMax Reitz {
5450ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque;
54519296b3edSMax Reitz int current_version = s->qcow_version;
54529296b3edSMax Reitz int ret;
54537fa140abSEric Blake int i;
54549296b3edSMax Reitz
5455d1402b50SMax Reitz /* This is qcow2_downgrade(), not qcow2_upgrade() */
5456d1402b50SMax Reitz assert(target_version < current_version);
5457d1402b50SMax Reitz
5458d1402b50SMax Reitz /* There are no other versions (now) that you can downgrade to */
5459d1402b50SMax Reitz assert(target_version == 2);
54609296b3edSMax Reitz
54619296b3edSMax Reitz if (s->refcount_order != 4) {
5462d1402b50SMax Reitz error_setg(errp, "compat=0.10 requires refcount_bits=16");
54639296b3edSMax Reitz return -ENOTSUP;
54649296b3edSMax Reitz }
54659296b3edSMax Reitz
5466966b000fSKevin Wolf if (has_data_file(bs)) {
5467966b000fSKevin Wolf error_setg(errp, "Cannot downgrade an image with a data file");
5468966b000fSKevin Wolf return -ENOTSUP;
5469966b000fSKevin Wolf }
5470966b000fSKevin Wolf
54717fa140abSEric Blake /*
54727fa140abSEric Blake * If any internal snapshot has a different size than the current
54737fa140abSEric Blake * image size, or VM state size that exceeds 32 bits, downgrading
54747fa140abSEric Blake * is unsafe. Even though we would still use v3-compliant output
54757fa140abSEric Blake * to preserve that data, other v2 programs might not realize
54767fa140abSEric Blake * those optional fields are important.
54777fa140abSEric Blake */
54787fa140abSEric Blake for (i = 0; i < s->nb_snapshots; i++) {
54797fa140abSEric Blake if (s->snapshots[i].vm_state_size > UINT32_MAX ||
54807fa140abSEric Blake s->snapshots[i].disk_size != bs->total_sectors * BDRV_SECTOR_SIZE) {
54817fa140abSEric Blake error_setg(errp, "Internal snapshots prevent downgrade of image");
54827fa140abSEric Blake return -ENOTSUP;
54837fa140abSEric Blake }
54847fa140abSEric Blake }
54857fa140abSEric Blake
54869296b3edSMax Reitz /* clear incompatible features */
54879296b3edSMax Reitz if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
54889296b3edSMax Reitz ret = qcow2_mark_clean(bs);
54899296b3edSMax Reitz if (ret < 0) {
5490d1402b50SMax Reitz error_setg_errno(errp, -ret, "Failed to make the image clean");
54919296b3edSMax Reitz return ret;
54929296b3edSMax Reitz }
54939296b3edSMax Reitz }
54949296b3edSMax Reitz
54959296b3edSMax Reitz /* with QCOW2_INCOMPAT_CORRUPT, it is pretty much impossible to get here in
54969296b3edSMax Reitz * the first place; if that happens nonetheless, returning -ENOTSUP is the
54979296b3edSMax Reitz * best thing to do anyway */
54989296b3edSMax Reitz
5499083c2456SVladimir Sementsov-Ogievskiy if (s->incompatible_features & ~QCOW2_INCOMPAT_COMPRESSION) {
5500d1402b50SMax Reitz error_setg(errp, "Cannot downgrade an image with incompatible features "
5501083c2456SVladimir Sementsov-Ogievskiy "0x%" PRIx64 " set",
5502083c2456SVladimir Sementsov-Ogievskiy s->incompatible_features & ~QCOW2_INCOMPAT_COMPRESSION);
55039296b3edSMax Reitz return -ENOTSUP;
55049296b3edSMax Reitz }
55059296b3edSMax Reitz
55069296b3edSMax Reitz /* since we can ignore compatible features, we can set them to 0 as well */
55079296b3edSMax Reitz s->compatible_features = 0;
55089296b3edSMax Reitz /* if lazy refcounts have been used, they have already been fixed through
55099296b3edSMax Reitz * clearing the dirty flag */
55109296b3edSMax Reitz
55119296b3edSMax Reitz /* clearing autoclear features is trivial */
55129296b3edSMax Reitz s->autoclear_features = 0;
55139296b3edSMax Reitz
55148b13976dSMax Reitz ret = qcow2_expand_zero_clusters(bs, status_cb, cb_opaque);
55159296b3edSMax Reitz if (ret < 0) {
5516d1402b50SMax Reitz error_setg_errno(errp, -ret, "Failed to turn zero into data clusters");
55179296b3edSMax Reitz return ret;
55189296b3edSMax Reitz }
55199296b3edSMax Reitz
5520083c2456SVladimir Sementsov-Ogievskiy if (s->incompatible_features & QCOW2_INCOMPAT_COMPRESSION) {
5521083c2456SVladimir Sementsov-Ogievskiy ret = qcow2_has_compressed_clusters(bs);
5522083c2456SVladimir Sementsov-Ogievskiy if (ret < 0) {
5523083c2456SVladimir Sementsov-Ogievskiy error_setg(errp, "Failed to check block status");
5524083c2456SVladimir Sementsov-Ogievskiy return -EINVAL;
5525083c2456SVladimir Sementsov-Ogievskiy }
5526083c2456SVladimir Sementsov-Ogievskiy if (ret) {
5527083c2456SVladimir Sementsov-Ogievskiy error_setg(errp, "Cannot downgrade an image with zstd compression "
5528083c2456SVladimir Sementsov-Ogievskiy "type and existing compressed clusters");
5529083c2456SVladimir Sementsov-Ogievskiy return -ENOTSUP;
5530083c2456SVladimir Sementsov-Ogievskiy }
5531083c2456SVladimir Sementsov-Ogievskiy /*
5532083c2456SVladimir Sementsov-Ogievskiy * No compressed clusters for now, so just chose default zlib
5533083c2456SVladimir Sementsov-Ogievskiy * compression.
5534083c2456SVladimir Sementsov-Ogievskiy */
5535083c2456SVladimir Sementsov-Ogievskiy s->incompatible_features &= ~QCOW2_INCOMPAT_COMPRESSION;
5536083c2456SVladimir Sementsov-Ogievskiy s->compression_type = QCOW2_COMPRESSION_TYPE_ZLIB;
5537083c2456SVladimir Sementsov-Ogievskiy }
5538083c2456SVladimir Sementsov-Ogievskiy
5539083c2456SVladimir Sementsov-Ogievskiy assert(s->incompatible_features == 0);
5540083c2456SVladimir Sementsov-Ogievskiy
55419296b3edSMax Reitz s->qcow_version = target_version;
55429296b3edSMax Reitz ret = qcow2_update_header(bs);
55439296b3edSMax Reitz if (ret < 0) {
55449296b3edSMax Reitz s->qcow_version = current_version;
5545d1402b50SMax Reitz error_setg_errno(errp, -ret, "Failed to update the image header");
55469296b3edSMax Reitz return ret;
55479296b3edSMax Reitz }
55489296b3edSMax Reitz return 0;
55499296b3edSMax Reitz }
55509296b3edSMax Reitz
5551722efb0cSMax Reitz /*
5552722efb0cSMax Reitz * Upgrades an image's version. While newer versions encompass all
5553722efb0cSMax Reitz * features of older versions, some things may have to be presented
5554722efb0cSMax Reitz * differently.
5555722efb0cSMax Reitz */
55560bb79c97SKevin Wolf static int GRAPH_RDLOCK
qcow2_upgrade(BlockDriverState * bs,int target_version,BlockDriverAmendStatusCB * status_cb,void * cb_opaque,Error ** errp)55570bb79c97SKevin Wolf qcow2_upgrade(BlockDriverState *bs, int target_version,
5558722efb0cSMax Reitz BlockDriverAmendStatusCB *status_cb, void *cb_opaque,
5559722efb0cSMax Reitz Error **errp)
5560722efb0cSMax Reitz {
5561722efb0cSMax Reitz BDRVQcow2State *s = bs->opaque;
55620a85af35SMax Reitz bool need_snapshot_update;
5563722efb0cSMax Reitz int current_version = s->qcow_version;
55640a85af35SMax Reitz int i;
5565722efb0cSMax Reitz int ret;
5566722efb0cSMax Reitz
5567722efb0cSMax Reitz /* This is qcow2_upgrade(), not qcow2_downgrade() */
5568722efb0cSMax Reitz assert(target_version > current_version);
5569722efb0cSMax Reitz
5570722efb0cSMax Reitz /* There are no other versions (yet) that you can upgrade to */
5571722efb0cSMax Reitz assert(target_version == 3);
5572722efb0cSMax Reitz
55730a85af35SMax Reitz status_cb(bs, 0, 2, cb_opaque);
55740a85af35SMax Reitz
55750a85af35SMax Reitz /*
55760a85af35SMax Reitz * In v2, snapshots do not need to have extra data. v3 requires
55770a85af35SMax Reitz * the 64-bit VM state size and the virtual disk size to be
55780a85af35SMax Reitz * present.
55790a85af35SMax Reitz * qcow2_write_snapshots() will always write the list in the
55800a85af35SMax Reitz * v3-compliant format.
55810a85af35SMax Reitz */
55820a85af35SMax Reitz need_snapshot_update = false;
55830a85af35SMax Reitz for (i = 0; i < s->nb_snapshots; i++) {
55840a85af35SMax Reitz if (s->snapshots[i].extra_data_size <
55850a85af35SMax Reitz sizeof_field(QCowSnapshotExtraData, vm_state_size_large) +
55860a85af35SMax Reitz sizeof_field(QCowSnapshotExtraData, disk_size))
55870a85af35SMax Reitz {
55880a85af35SMax Reitz need_snapshot_update = true;
55890a85af35SMax Reitz break;
55900a85af35SMax Reitz }
55910a85af35SMax Reitz }
55920a85af35SMax Reitz if (need_snapshot_update) {
55930a85af35SMax Reitz ret = qcow2_write_snapshots(bs);
55940a85af35SMax Reitz if (ret < 0) {
55950a85af35SMax Reitz error_setg_errno(errp, -ret, "Failed to update the snapshot table");
55960a85af35SMax Reitz return ret;
55970a85af35SMax Reitz }
55980a85af35SMax Reitz }
55990a85af35SMax Reitz status_cb(bs, 1, 2, cb_opaque);
5600722efb0cSMax Reitz
5601722efb0cSMax Reitz s->qcow_version = target_version;
5602722efb0cSMax Reitz ret = qcow2_update_header(bs);
5603722efb0cSMax Reitz if (ret < 0) {
5604722efb0cSMax Reitz s->qcow_version = current_version;
5605722efb0cSMax Reitz error_setg_errno(errp, -ret, "Failed to update the image header");
5606722efb0cSMax Reitz return ret;
5607722efb0cSMax Reitz }
56080a85af35SMax Reitz status_cb(bs, 2, 2, cb_opaque);
5609722efb0cSMax Reitz
5610722efb0cSMax Reitz return 0;
5611722efb0cSMax Reitz }
5612722efb0cSMax Reitz
5613c293a809SMax Reitz typedef enum Qcow2AmendOperation {
5614c293a809SMax Reitz /* This is the value Qcow2AmendHelperCBInfo::last_operation will be
5615c293a809SMax Reitz * statically initialized to so that the helper CB can discern the first
5616c293a809SMax Reitz * invocation from an operation change */
5617c293a809SMax Reitz QCOW2_NO_OPERATION = 0,
5618c293a809SMax Reitz
5619722efb0cSMax Reitz QCOW2_UPGRADING,
562090766d9dSMaxim Levitsky QCOW2_UPDATING_ENCRYPTION,
562161ce55fcSMax Reitz QCOW2_CHANGING_REFCOUNT_ORDER,
5622c293a809SMax Reitz QCOW2_DOWNGRADING,
5623c293a809SMax Reitz } Qcow2AmendOperation;
5624c293a809SMax Reitz
5625c293a809SMax Reitz typedef struct Qcow2AmendHelperCBInfo {
5626c293a809SMax Reitz /* The code coordinating the amend operations should only modify
5627c293a809SMax Reitz * these four fields; the rest will be managed by the CB */
5628c293a809SMax Reitz BlockDriverAmendStatusCB *original_status_cb;
5629c293a809SMax Reitz void *original_cb_opaque;
5630c293a809SMax Reitz
5631c293a809SMax Reitz Qcow2AmendOperation current_operation;
5632c293a809SMax Reitz
5633c293a809SMax Reitz /* Total number of operations to perform (only set once) */
5634c293a809SMax Reitz int total_operations;
5635c293a809SMax Reitz
5636c293a809SMax Reitz /* The following fields are managed by the CB */
5637c293a809SMax Reitz
5638c293a809SMax Reitz /* Number of operations completed */
5639c293a809SMax Reitz int operations_completed;
5640c293a809SMax Reitz
5641c293a809SMax Reitz /* Cumulative offset of all completed operations */
5642c293a809SMax Reitz int64_t offset_completed;
5643c293a809SMax Reitz
5644c293a809SMax Reitz Qcow2AmendOperation last_operation;
5645c293a809SMax Reitz int64_t last_work_size;
5646c293a809SMax Reitz } Qcow2AmendHelperCBInfo;
5647c293a809SMax Reitz
qcow2_amend_helper_cb(BlockDriverState * bs,int64_t operation_offset,int64_t operation_work_size,void * opaque)5648c293a809SMax Reitz static void qcow2_amend_helper_cb(BlockDriverState *bs,
5649c293a809SMax Reitz int64_t operation_offset,
5650c293a809SMax Reitz int64_t operation_work_size, void *opaque)
5651c293a809SMax Reitz {
5652c293a809SMax Reitz Qcow2AmendHelperCBInfo *info = opaque;
5653c293a809SMax Reitz int64_t current_work_size;
5654c293a809SMax Reitz int64_t projected_work_size;
5655c293a809SMax Reitz
5656c293a809SMax Reitz if (info->current_operation != info->last_operation) {
5657c293a809SMax Reitz if (info->last_operation != QCOW2_NO_OPERATION) {
5658c293a809SMax Reitz info->offset_completed += info->last_work_size;
5659c293a809SMax Reitz info->operations_completed++;
5660c293a809SMax Reitz }
5661c293a809SMax Reitz
5662c293a809SMax Reitz info->last_operation = info->current_operation;
5663c293a809SMax Reitz }
5664c293a809SMax Reitz
5665c293a809SMax Reitz assert(info->total_operations > 0);
5666c293a809SMax Reitz assert(info->operations_completed < info->total_operations);
5667c293a809SMax Reitz
5668c293a809SMax Reitz info->last_work_size = operation_work_size;
5669c293a809SMax Reitz
5670c293a809SMax Reitz current_work_size = info->offset_completed + operation_work_size;
5671c293a809SMax Reitz
5672c293a809SMax Reitz /* current_work_size is the total work size for (operations_completed + 1)
5673c293a809SMax Reitz * operations (which includes this one), so multiply it by the number of
5674c293a809SMax Reitz * operations not covered and divide it by the number of operations
5675c293a809SMax Reitz * covered to get a projection for the operations not covered */
5676c293a809SMax Reitz projected_work_size = current_work_size * (info->total_operations -
5677c293a809SMax Reitz info->operations_completed - 1)
5678c293a809SMax Reitz / (info->operations_completed + 1);
5679c293a809SMax Reitz
5680c293a809SMax Reitz info->original_status_cb(bs, info->offset_completed + operation_offset,
5681c293a809SMax Reitz current_work_size + projected_work_size,
5682c293a809SMax Reitz info->original_cb_opaque);
5683c293a809SMax Reitz }
5684c293a809SMax Reitz
56850bb79c97SKevin Wolf static int GRAPH_RDLOCK
qcow2_amend_options(BlockDriverState * bs,QemuOpts * opts,BlockDriverAmendStatusCB * status_cb,void * cb_opaque,bool force,Error ** errp)56860bb79c97SKevin Wolf qcow2_amend_options(BlockDriverState *bs, QemuOpts *opts,
56870bb79c97SKevin Wolf BlockDriverAmendStatusCB *status_cb, void *cb_opaque,
56880bb79c97SKevin Wolf bool force, Error **errp)
56899296b3edSMax Reitz {
5690ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque;
56919296b3edSMax Reitz int old_version = s->qcow_version, new_version = old_version;
56929296b3edSMax Reitz uint64_t new_size = 0;
56939b890bdcSKevin Wolf const char *backing_file = NULL, *backing_format = NULL, *data_file = NULL;
56949296b3edSMax Reitz bool lazy_refcounts = s->use_lazy_refcounts;
56956c3944dcSKevin Wolf bool data_file_raw = data_file_is_raw(bs);
56961bd0e2d1SChunyan Liu const char *compat = NULL;
569761ce55fcSMax Reitz int refcount_bits = s->refcount_bits;
56989296b3edSMax Reitz int ret;
56991bd0e2d1SChunyan Liu QemuOptDesc *desc = opts->list->desc;
5700c293a809SMax Reitz Qcow2AmendHelperCBInfo helper_cb_info;
570190766d9dSMaxim Levitsky bool encryption_update = false;
57029296b3edSMax Reitz
57031bd0e2d1SChunyan Liu while (desc && desc->name) {
57041bd0e2d1SChunyan Liu if (!qemu_opt_find(opts, desc->name)) {
57059296b3edSMax Reitz /* only change explicitly defined options */
57061bd0e2d1SChunyan Liu desc++;
57079296b3edSMax Reitz continue;
57089296b3edSMax Reitz }
57099296b3edSMax Reitz
57108a17b83cSMax Reitz if (!strcmp(desc->name, BLOCK_OPT_COMPAT_LEVEL)) {
57118a17b83cSMax Reitz compat = qemu_opt_get(opts, BLOCK_OPT_COMPAT_LEVEL);
57121bd0e2d1SChunyan Liu if (!compat) {
57139296b3edSMax Reitz /* preserve default */
5714f7077c98SEric Blake } else if (!strcmp(compat, "0.10") || !strcmp(compat, "v2")) {
57159296b3edSMax Reitz new_version = 2;
5716f7077c98SEric Blake } else if (!strcmp(compat, "1.1") || !strcmp(compat, "v3")) {
57179296b3edSMax Reitz new_version = 3;
57189296b3edSMax Reitz } else {
5719d1402b50SMax Reitz error_setg(errp, "Unknown compatibility level %s", compat);
57209296b3edSMax Reitz return -EINVAL;
57219296b3edSMax Reitz }
57228a17b83cSMax Reitz } else if (!strcmp(desc->name, BLOCK_OPT_SIZE)) {
57238a17b83cSMax Reitz new_size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, 0);
57248a17b83cSMax Reitz } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FILE)) {
57258a17b83cSMax Reitz backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
57268a17b83cSMax Reitz } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FMT)) {
57278a17b83cSMax Reitz backing_format = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
572890766d9dSMaxim Levitsky } else if (g_str_has_prefix(desc->name, "encrypt.")) {
572990766d9dSMaxim Levitsky if (!s->crypto) {
573090766d9dSMaxim Levitsky error_setg(errp,
573190766d9dSMaxim Levitsky "Can't amend encryption options - encryption not present");
573290766d9dSMaxim Levitsky return -EINVAL;
573390766d9dSMaxim Levitsky }
573490766d9dSMaxim Levitsky if (s->crypt_method_header != QCOW_CRYPT_LUKS) {
573590766d9dSMaxim Levitsky error_setg(errp,
573690766d9dSMaxim Levitsky "Only LUKS encryption options can be amended");
573790766d9dSMaxim Levitsky return -ENOTSUP;
573890766d9dSMaxim Levitsky }
573990766d9dSMaxim Levitsky encryption_update = true;
57408a17b83cSMax Reitz } else if (!strcmp(desc->name, BLOCK_OPT_LAZY_REFCOUNTS)) {
57418a17b83cSMax Reitz lazy_refcounts = qemu_opt_get_bool(opts, BLOCK_OPT_LAZY_REFCOUNTS,
57421bd0e2d1SChunyan Liu lazy_refcounts);
574306d05fa7SMax Reitz } else if (!strcmp(desc->name, BLOCK_OPT_REFCOUNT_BITS)) {
574461ce55fcSMax Reitz refcount_bits = qemu_opt_get_number(opts, BLOCK_OPT_REFCOUNT_BITS,
574561ce55fcSMax Reitz refcount_bits);
574661ce55fcSMax Reitz
574761ce55fcSMax Reitz if (refcount_bits <= 0 || refcount_bits > 64 ||
574861ce55fcSMax Reitz !is_power_of_2(refcount_bits))
574961ce55fcSMax Reitz {
5750d1402b50SMax Reitz error_setg(errp, "Refcount width must be a power of two and "
5751d1402b50SMax Reitz "may not exceed 64 bits");
575261ce55fcSMax Reitz return -EINVAL;
575361ce55fcSMax Reitz }
57549b890bdcSKevin Wolf } else if (!strcmp(desc->name, BLOCK_OPT_DATA_FILE)) {
57559b890bdcSKevin Wolf data_file = qemu_opt_get(opts, BLOCK_OPT_DATA_FILE);
57569b890bdcSKevin Wolf if (data_file && !has_data_file(bs)) {
57579b890bdcSKevin Wolf error_setg(errp, "data-file can only be set for images that "
57589b890bdcSKevin Wolf "use an external data file");
57599b890bdcSKevin Wolf return -EINVAL;
57609b890bdcSKevin Wolf }
57616c3944dcSKevin Wolf } else if (!strcmp(desc->name, BLOCK_OPT_DATA_FILE_RAW)) {
57626c3944dcSKevin Wolf data_file_raw = qemu_opt_get_bool(opts, BLOCK_OPT_DATA_FILE_RAW,
57636c3944dcSKevin Wolf data_file_raw);
57646c3944dcSKevin Wolf if (data_file_raw && !data_file_is_raw(bs)) {
57656c3944dcSKevin Wolf error_setg(errp, "data-file-raw cannot be set on existing "
57666c3944dcSKevin Wolf "images");
57676c3944dcSKevin Wolf return -EINVAL;
57686c3944dcSKevin Wolf }
57699296b3edSMax Reitz } else {
5770164e0f89SMax Reitz /* if this point is reached, this probably means a new option was
57719296b3edSMax Reitz * added without having it covered here */
5772164e0f89SMax Reitz abort();
57739296b3edSMax Reitz }
57741bd0e2d1SChunyan Liu
57751bd0e2d1SChunyan Liu desc++;
57769296b3edSMax Reitz }
57779296b3edSMax Reitz
5778c293a809SMax Reitz helper_cb_info = (Qcow2AmendHelperCBInfo){
5779c293a809SMax Reitz .original_status_cb = status_cb,
5780c293a809SMax Reitz .original_cb_opaque = cb_opaque,
5781722efb0cSMax Reitz .total_operations = (new_version != old_version)
578290766d9dSMaxim Levitsky + (s->refcount_bits != refcount_bits) +
578390766d9dSMaxim Levitsky (encryption_update == true)
5784c293a809SMax Reitz };
5785c293a809SMax Reitz
57861038bbb8SMax Reitz /* Upgrade first (some features may require compat=1.1) */
57879296b3edSMax Reitz if (new_version > old_version) {
5788722efb0cSMax Reitz helper_cb_info.current_operation = QCOW2_UPGRADING;
5789722efb0cSMax Reitz ret = qcow2_upgrade(bs, new_version, &qcow2_amend_helper_cb,
5790722efb0cSMax Reitz &helper_cb_info, errp);
57919296b3edSMax Reitz if (ret < 0) {
57929296b3edSMax Reitz return ret;
57939296b3edSMax Reitz }
57949296b3edSMax Reitz }
57959296b3edSMax Reitz
579690766d9dSMaxim Levitsky if (encryption_update) {
579790766d9dSMaxim Levitsky QDict *amend_opts_dict;
579890766d9dSMaxim Levitsky QCryptoBlockAmendOptions *amend_opts;
579990766d9dSMaxim Levitsky
580090766d9dSMaxim Levitsky helper_cb_info.current_operation = QCOW2_UPDATING_ENCRYPTION;
580190766d9dSMaxim Levitsky amend_opts_dict = qcow2_extract_crypto_opts(opts, "luks", errp);
580290766d9dSMaxim Levitsky if (!amend_opts_dict) {
580390766d9dSMaxim Levitsky return -EINVAL;
580490766d9dSMaxim Levitsky }
580590766d9dSMaxim Levitsky amend_opts = block_crypto_amend_opts_init(amend_opts_dict, errp);
580690766d9dSMaxim Levitsky qobject_unref(amend_opts_dict);
580790766d9dSMaxim Levitsky if (!amend_opts) {
580890766d9dSMaxim Levitsky return -EINVAL;
580990766d9dSMaxim Levitsky }
581090766d9dSMaxim Levitsky ret = qcrypto_block_amend_options(s->crypto,
581190766d9dSMaxim Levitsky qcow2_crypto_hdr_read_func,
581290766d9dSMaxim Levitsky qcow2_crypto_hdr_write_func,
581390766d9dSMaxim Levitsky bs,
581490766d9dSMaxim Levitsky amend_opts,
581590766d9dSMaxim Levitsky force,
581690766d9dSMaxim Levitsky errp);
581790766d9dSMaxim Levitsky qapi_free_QCryptoBlockAmendOptions(amend_opts);
581890766d9dSMaxim Levitsky if (ret < 0) {
581990766d9dSMaxim Levitsky return ret;
582090766d9dSMaxim Levitsky }
582190766d9dSMaxim Levitsky }
582290766d9dSMaxim Levitsky
582361ce55fcSMax Reitz if (s->refcount_bits != refcount_bits) {
582461ce55fcSMax Reitz int refcount_order = ctz32(refcount_bits);
582561ce55fcSMax Reitz
582661ce55fcSMax Reitz if (new_version < 3 && refcount_bits != 16) {
5827d1402b50SMax Reitz error_setg(errp, "Refcount widths other than 16 bits require "
582861ce55fcSMax Reitz "compatibility level 1.1 or above (use compat=1.1 or "
582961ce55fcSMax Reitz "greater)");
583061ce55fcSMax Reitz return -EINVAL;
583161ce55fcSMax Reitz }
583261ce55fcSMax Reitz
583361ce55fcSMax Reitz helper_cb_info.current_operation = QCOW2_CHANGING_REFCOUNT_ORDER;
583461ce55fcSMax Reitz ret = qcow2_change_refcount_order(bs, refcount_order,
583561ce55fcSMax Reitz &qcow2_amend_helper_cb,
5836d1402b50SMax Reitz &helper_cb_info, errp);
583761ce55fcSMax Reitz if (ret < 0) {
583861ce55fcSMax Reitz return ret;
583961ce55fcSMax Reitz }
584061ce55fcSMax Reitz }
584161ce55fcSMax Reitz
58426c3944dcSKevin Wolf /* data-file-raw blocks backing files, so clear it first if requested */
58436c3944dcSKevin Wolf if (data_file_raw) {
58446c3944dcSKevin Wolf s->autoclear_features |= QCOW2_AUTOCLEAR_DATA_FILE_RAW;
58456c3944dcSKevin Wolf } else {
58466c3944dcSKevin Wolf s->autoclear_features &= ~QCOW2_AUTOCLEAR_DATA_FILE_RAW;
58476c3944dcSKevin Wolf }
58486c3944dcSKevin Wolf
58499b890bdcSKevin Wolf if (data_file) {
58509b890bdcSKevin Wolf g_free(s->image_data_file);
58519b890bdcSKevin Wolf s->image_data_file = *data_file ? g_strdup(data_file) : NULL;
58529b890bdcSKevin Wolf }
58539b890bdcSKevin Wolf
58549b890bdcSKevin Wolf ret = qcow2_update_header(bs);
58559b890bdcSKevin Wolf if (ret < 0) {
58569b890bdcSKevin Wolf error_setg_errno(errp, -ret, "Failed to update the image header");
58579b890bdcSKevin Wolf return ret;
58589b890bdcSKevin Wolf }
58599b890bdcSKevin Wolf
58609296b3edSMax Reitz if (backing_file || backing_format) {
5861bc5ee6daSEric Blake if (g_strcmp0(backing_file, s->image_backing_file) ||
5862bc5ee6daSEric Blake g_strcmp0(backing_format, s->image_backing_format)) {
58635a385bf5SEric Blake error_setg(errp, "Cannot amend the backing file");
58645a385bf5SEric Blake error_append_hint(errp,
58655a385bf5SEric Blake "You can use 'qemu-img rebase' instead.\n");
58665a385bf5SEric Blake return -EINVAL;
58679296b3edSMax Reitz }
58689296b3edSMax Reitz }
58699296b3edSMax Reitz
58709296b3edSMax Reitz if (s->use_lazy_refcounts != lazy_refcounts) {
58719296b3edSMax Reitz if (lazy_refcounts) {
58721038bbb8SMax Reitz if (new_version < 3) {
5873d1402b50SMax Reitz error_setg(errp, "Lazy refcounts only supported with "
5874d1402b50SMax Reitz "compatibility level 1.1 and above (use compat=1.1 "
5875d1402b50SMax Reitz "or greater)");
58769296b3edSMax Reitz return -EINVAL;
58779296b3edSMax Reitz }
58789296b3edSMax Reitz s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
58799296b3edSMax Reitz ret = qcow2_update_header(bs);
58809296b3edSMax Reitz if (ret < 0) {
58819296b3edSMax Reitz s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
5882d1402b50SMax Reitz error_setg_errno(errp, -ret, "Failed to update the image header");
58839296b3edSMax Reitz return ret;
58849296b3edSMax Reitz }
58859296b3edSMax Reitz s->use_lazy_refcounts = true;
58869296b3edSMax Reitz } else {
58879296b3edSMax Reitz /* make image clean first */
58889296b3edSMax Reitz ret = qcow2_mark_clean(bs);
58899296b3edSMax Reitz if (ret < 0) {
5890d1402b50SMax Reitz error_setg_errno(errp, -ret, "Failed to make the image clean");
58919296b3edSMax Reitz return ret;
58929296b3edSMax Reitz }
58939296b3edSMax Reitz /* now disallow lazy refcounts */
58949296b3edSMax Reitz s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
58959296b3edSMax Reitz ret = qcow2_update_header(bs);
58969296b3edSMax Reitz if (ret < 0) {
58979296b3edSMax Reitz s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
5898d1402b50SMax Reitz error_setg_errno(errp, -ret, "Failed to update the image header");
58999296b3edSMax Reitz return ret;
59009296b3edSMax Reitz }
59019296b3edSMax Reitz s->use_lazy_refcounts = false;
59029296b3edSMax Reitz }
59039296b3edSMax Reitz }
59049296b3edSMax Reitz
59059296b3edSMax Reitz if (new_size) {
5906a3aeeab5SEric Blake BlockBackend *blk = blk_new_with_bs(bs, BLK_PERM_RESIZE, BLK_PERM_ALL,
5907a3aeeab5SEric Blake errp);
5908a3aeeab5SEric Blake if (!blk) {
5909a3aeeab5SEric Blake return -EPERM;
5910d7086422SKevin Wolf }
5911d7086422SKevin Wolf
5912e8d04f92SMax Reitz /*
5913e8d04f92SMax Reitz * Amending image options should ensure that the image has
5914e8d04f92SMax Reitz * exactly the given new values, so pass exact=true here.
5915e8d04f92SMax Reitz */
59168c6242b6SKevin Wolf ret = blk_truncate(blk, new_size, true, PREALLOC_MODE_OFF, 0, errp);
591770b27f36SKevin Wolf blk_unref(blk);
59189296b3edSMax Reitz if (ret < 0) {
59199296b3edSMax Reitz return ret;
59209296b3edSMax Reitz }
59219296b3edSMax Reitz }
59229296b3edSMax Reitz
59231038bbb8SMax Reitz /* Downgrade last (so unsupported features can be removed before) */
59241038bbb8SMax Reitz if (new_version < old_version) {
5925c293a809SMax Reitz helper_cb_info.current_operation = QCOW2_DOWNGRADING;
5926c293a809SMax Reitz ret = qcow2_downgrade(bs, new_version, &qcow2_amend_helper_cb,
5927d1402b50SMax Reitz &helper_cb_info, errp);
59281038bbb8SMax Reitz if (ret < 0) {
59291038bbb8SMax Reitz return ret;
59301038bbb8SMax Reitz }
59311038bbb8SMax Reitz }
59321038bbb8SMax Reitz
59339296b3edSMax Reitz return 0;
59349296b3edSMax Reitz }
59359296b3edSMax Reitz
qcow2_co_amend(BlockDriverState * bs,BlockdevAmendOptions * opts,bool force,Error ** errp)59368ea1613dSMaxim Levitsky static int coroutine_fn qcow2_co_amend(BlockDriverState *bs,
59378ea1613dSMaxim Levitsky BlockdevAmendOptions *opts,
59388ea1613dSMaxim Levitsky bool force,
59398ea1613dSMaxim Levitsky Error **errp)
59408ea1613dSMaxim Levitsky {
59418ea1613dSMaxim Levitsky BlockdevAmendOptionsQcow2 *qopts = &opts->u.qcow2;
59428ea1613dSMaxim Levitsky BDRVQcow2State *s = bs->opaque;
59438ea1613dSMaxim Levitsky int ret = 0;
59448ea1613dSMaxim Levitsky
594554fde4ffSMarkus Armbruster if (qopts->encrypt) {
59468ea1613dSMaxim Levitsky if (!s->crypto) {
59478ea1613dSMaxim Levitsky error_setg(errp, "image is not encrypted, can't amend");
59488ea1613dSMaxim Levitsky return -EOPNOTSUPP;
59498ea1613dSMaxim Levitsky }
59508ea1613dSMaxim Levitsky
5951d23d2ef3SMarkus Armbruster if (qopts->encrypt->format != QCRYPTO_BLOCK_FORMAT_LUKS) {
59528ea1613dSMaxim Levitsky error_setg(errp,
59538ea1613dSMaxim Levitsky "Amend can't be used to change the qcow2 encryption format");
59548ea1613dSMaxim Levitsky return -EOPNOTSUPP;
59558ea1613dSMaxim Levitsky }
59568ea1613dSMaxim Levitsky
59578ea1613dSMaxim Levitsky if (s->crypt_method_header != QCOW_CRYPT_LUKS) {
59588ea1613dSMaxim Levitsky error_setg(errp,
59598ea1613dSMaxim Levitsky "Only LUKS encryption options can be amended for qcow2 with blockdev-amend");
59608ea1613dSMaxim Levitsky return -EOPNOTSUPP;
59618ea1613dSMaxim Levitsky }
59628ea1613dSMaxim Levitsky
59638ea1613dSMaxim Levitsky ret = qcrypto_block_amend_options(s->crypto,
59648ea1613dSMaxim Levitsky qcow2_crypto_hdr_read_func,
59658ea1613dSMaxim Levitsky qcow2_crypto_hdr_write_func,
59668ea1613dSMaxim Levitsky bs,
59678ea1613dSMaxim Levitsky qopts->encrypt,
59688ea1613dSMaxim Levitsky force,
59698ea1613dSMaxim Levitsky errp);
59708ea1613dSMaxim Levitsky }
59718ea1613dSMaxim Levitsky return ret;
59728ea1613dSMaxim Levitsky }
59738ea1613dSMaxim Levitsky
597485186ebdSMax Reitz /*
597585186ebdSMax Reitz * If offset or size are negative, respectively, they will not be included in
597685186ebdSMax Reitz * the BLOCK_IMAGE_CORRUPTED event emitted.
597785186ebdSMax Reitz * fatal will be ignored for read-only BDS; corruptions found there will always
597885186ebdSMax Reitz * be considered non-fatal.
597985186ebdSMax Reitz */
qcow2_signal_corruption(BlockDriverState * bs,bool fatal,int64_t offset,int64_t size,const char * message_format,...)598085186ebdSMax Reitz void qcow2_signal_corruption(BlockDriverState *bs, bool fatal, int64_t offset,
598185186ebdSMax Reitz int64_t size, const char *message_format, ...)
598285186ebdSMax Reitz {
5983ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque;
5984dc881b44SAlberto Garcia const char *node_name;
598585186ebdSMax Reitz char *message;
598685186ebdSMax Reitz va_list ap;
598785186ebdSMax Reitz
5988ddf3b47eSMax Reitz fatal = fatal && bdrv_is_writable(bs);
598985186ebdSMax Reitz
599085186ebdSMax Reitz if (s->signaled_corruption &&
599185186ebdSMax Reitz (!fatal || (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT)))
599285186ebdSMax Reitz {
599385186ebdSMax Reitz return;
599485186ebdSMax Reitz }
599585186ebdSMax Reitz
599685186ebdSMax Reitz va_start(ap, message_format);
599785186ebdSMax Reitz message = g_strdup_vprintf(message_format, ap);
599885186ebdSMax Reitz va_end(ap);
599985186ebdSMax Reitz
600085186ebdSMax Reitz if (fatal) {
600185186ebdSMax Reitz fprintf(stderr, "qcow2: Marking image as corrupt: %s; further "
600285186ebdSMax Reitz "corruption events will be suppressed\n", message);
600385186ebdSMax Reitz } else {
600485186ebdSMax Reitz fprintf(stderr, "qcow2: Image is corrupt: %s; further non-fatal "
600585186ebdSMax Reitz "corruption events will be suppressed\n", message);
600685186ebdSMax Reitz }
600785186ebdSMax Reitz
6008dc881b44SAlberto Garcia node_name = bdrv_get_node_name(bs);
6009dc881b44SAlberto Garcia qapi_event_send_block_image_corrupted(bdrv_get_device_name(bs),
601054fde4ffSMarkus Armbruster *node_name ? node_name : NULL,
6011dc881b44SAlberto Garcia message, offset >= 0, offset,
6012dc881b44SAlberto Garcia size >= 0, size,
60133ab72385SPeter Xu fatal);
601485186ebdSMax Reitz g_free(message);
601585186ebdSMax Reitz
601685186ebdSMax Reitz if (fatal) {
601785186ebdSMax Reitz qcow2_mark_corrupt(bs);
601885186ebdSMax Reitz bs->drv = NULL; /* make BDS unusable */
601985186ebdSMax Reitz }
602085186ebdSMax Reitz
602185186ebdSMax Reitz s->signaled_corruption = true;
602285186ebdSMax Reitz }
602385186ebdSMax Reitz
6024df373fb0SMaxim Levitsky #define QCOW_COMMON_OPTIONS \
6025df373fb0SMaxim Levitsky { \
6026df373fb0SMaxim Levitsky .name = BLOCK_OPT_SIZE, \
6027df373fb0SMaxim Levitsky .type = QEMU_OPT_SIZE, \
6028df373fb0SMaxim Levitsky .help = "Virtual disk size" \
6029df373fb0SMaxim Levitsky }, \
6030df373fb0SMaxim Levitsky { \
6031df373fb0SMaxim Levitsky .name = BLOCK_OPT_COMPAT_LEVEL, \
6032df373fb0SMaxim Levitsky .type = QEMU_OPT_STRING, \
6033df373fb0SMaxim Levitsky .help = "Compatibility level (v2 [0.10] or v3 [1.1])" \
6034df373fb0SMaxim Levitsky }, \
6035df373fb0SMaxim Levitsky { \
6036df373fb0SMaxim Levitsky .name = BLOCK_OPT_BACKING_FILE, \
6037df373fb0SMaxim Levitsky .type = QEMU_OPT_STRING, \
6038df373fb0SMaxim Levitsky .help = "File name of a base image" \
6039df373fb0SMaxim Levitsky }, \
6040df373fb0SMaxim Levitsky { \
6041df373fb0SMaxim Levitsky .name = BLOCK_OPT_BACKING_FMT, \
6042df373fb0SMaxim Levitsky .type = QEMU_OPT_STRING, \
6043df373fb0SMaxim Levitsky .help = "Image format of the base image" \
6044df373fb0SMaxim Levitsky }, \
6045df373fb0SMaxim Levitsky { \
6046df373fb0SMaxim Levitsky .name = BLOCK_OPT_DATA_FILE, \
6047df373fb0SMaxim Levitsky .type = QEMU_OPT_STRING, \
6048df373fb0SMaxim Levitsky .help = "File name of an external data file" \
6049df373fb0SMaxim Levitsky }, \
6050df373fb0SMaxim Levitsky { \
6051df373fb0SMaxim Levitsky .name = BLOCK_OPT_DATA_FILE_RAW, \
6052df373fb0SMaxim Levitsky .type = QEMU_OPT_BOOL, \
6053df373fb0SMaxim Levitsky .help = "The external data file must stay valid " \
6054df373fb0SMaxim Levitsky "as a raw image" \
6055df373fb0SMaxim Levitsky }, \
6056df373fb0SMaxim Levitsky { \
60570b6786a9SMaxim Levitsky .name = BLOCK_OPT_LAZY_REFCOUNTS, \
60580b6786a9SMaxim Levitsky .type = QEMU_OPT_BOOL, \
60590b6786a9SMaxim Levitsky .help = "Postpone refcount updates", \
60600b6786a9SMaxim Levitsky .def_value_str = "off" \
60610b6786a9SMaxim Levitsky }, \
60620b6786a9SMaxim Levitsky { \
60630b6786a9SMaxim Levitsky .name = BLOCK_OPT_REFCOUNT_BITS, \
60640b6786a9SMaxim Levitsky .type = QEMU_OPT_NUMBER, \
60650b6786a9SMaxim Levitsky .help = "Width of a reference count entry in bits", \
60660b6786a9SMaxim Levitsky .def_value_str = "16" \
60670b6786a9SMaxim Levitsky }
60680b6786a9SMaxim Levitsky
60690b6786a9SMaxim Levitsky static QemuOptsList qcow2_create_opts = {
60700b6786a9SMaxim Levitsky .name = "qcow2-create-opts",
60710b6786a9SMaxim Levitsky .head = QTAILQ_HEAD_INITIALIZER(qcow2_create_opts.head),
60720b6786a9SMaxim Levitsky .desc = {
60730b6786a9SMaxim Levitsky { \
6074df373fb0SMaxim Levitsky .name = BLOCK_OPT_ENCRYPT, \
6075df373fb0SMaxim Levitsky .type = QEMU_OPT_BOOL, \
6076df373fb0SMaxim Levitsky .help = "Encrypt the image with format 'aes'. (Deprecated " \
6077df373fb0SMaxim Levitsky "in favor of " BLOCK_OPT_ENCRYPT_FORMAT "=aes)", \
6078df373fb0SMaxim Levitsky }, \
6079df373fb0SMaxim Levitsky { \
6080df373fb0SMaxim Levitsky .name = BLOCK_OPT_ENCRYPT_FORMAT, \
6081df373fb0SMaxim Levitsky .type = QEMU_OPT_STRING, \
6082df373fb0SMaxim Levitsky .help = "Encrypt the image, format choices: 'aes', 'luks'", \
6083df373fb0SMaxim Levitsky }, \
6084df373fb0SMaxim Levitsky BLOCK_CRYPTO_OPT_DEF_KEY_SECRET("encrypt.", \
6085df373fb0SMaxim Levitsky "ID of secret providing qcow AES key or LUKS passphrase"), \
6086df373fb0SMaxim Levitsky BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_ALG("encrypt."), \
6087df373fb0SMaxim Levitsky BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_MODE("encrypt."), \
6088df373fb0SMaxim Levitsky BLOCK_CRYPTO_OPT_DEF_LUKS_IVGEN_ALG("encrypt."), \
6089df373fb0SMaxim Levitsky BLOCK_CRYPTO_OPT_DEF_LUKS_IVGEN_HASH_ALG("encrypt."), \
6090df373fb0SMaxim Levitsky BLOCK_CRYPTO_OPT_DEF_LUKS_HASH_ALG("encrypt."), \
6091df373fb0SMaxim Levitsky BLOCK_CRYPTO_OPT_DEF_LUKS_ITER_TIME("encrypt."), \
6092df373fb0SMaxim Levitsky { \
6093df373fb0SMaxim Levitsky .name = BLOCK_OPT_CLUSTER_SIZE, \
6094df373fb0SMaxim Levitsky .type = QEMU_OPT_SIZE, \
6095df373fb0SMaxim Levitsky .help = "qcow2 cluster size", \
6096df373fb0SMaxim Levitsky .def_value_str = stringify(DEFAULT_CLUSTER_SIZE) \
6097df373fb0SMaxim Levitsky }, \
6098df373fb0SMaxim Levitsky { \
60997be20252SAlberto Garcia .name = BLOCK_OPT_EXTL2, \
61007be20252SAlberto Garcia .type = QEMU_OPT_BOOL, \
61017be20252SAlberto Garcia .help = "Extended L2 tables", \
61027be20252SAlberto Garcia .def_value_str = "off" \
61037be20252SAlberto Garcia }, \
61047be20252SAlberto Garcia { \
6105df373fb0SMaxim Levitsky .name = BLOCK_OPT_PREALLOC, \
6106df373fb0SMaxim Levitsky .type = QEMU_OPT_STRING, \
6107df373fb0SMaxim Levitsky .help = "Preallocation mode (allowed values: off, " \
6108df373fb0SMaxim Levitsky "metadata, falloc, full)" \
6109df373fb0SMaxim Levitsky }, \
6110df373fb0SMaxim Levitsky { \
6111df373fb0SMaxim Levitsky .name = BLOCK_OPT_COMPRESSION_TYPE, \
6112df373fb0SMaxim Levitsky .type = QEMU_OPT_STRING, \
6113df373fb0SMaxim Levitsky .help = "Compression method used for image cluster " \
6114df373fb0SMaxim Levitsky "compression", \
6115df373fb0SMaxim Levitsky .def_value_str = "zlib" \
61160b6786a9SMaxim Levitsky },
6117df373fb0SMaxim Levitsky QCOW_COMMON_OPTIONS,
6118df373fb0SMaxim Levitsky { /* end of list */ }
6119df373fb0SMaxim Levitsky }
6120df373fb0SMaxim Levitsky };
6121df373fb0SMaxim Levitsky
6122df373fb0SMaxim Levitsky static QemuOptsList qcow2_amend_opts = {
6123df373fb0SMaxim Levitsky .name = "qcow2-amend-opts",
6124df373fb0SMaxim Levitsky .head = QTAILQ_HEAD_INITIALIZER(qcow2_amend_opts.head),
6125df373fb0SMaxim Levitsky .desc = {
612690766d9dSMaxim Levitsky BLOCK_CRYPTO_OPT_DEF_LUKS_STATE("encrypt."),
612790766d9dSMaxim Levitsky BLOCK_CRYPTO_OPT_DEF_LUKS_KEYSLOT("encrypt."),
612890766d9dSMaxim Levitsky BLOCK_CRYPTO_OPT_DEF_LUKS_OLD_SECRET("encrypt."),
612990766d9dSMaxim Levitsky BLOCK_CRYPTO_OPT_DEF_LUKS_NEW_SECRET("encrypt."),
613090766d9dSMaxim Levitsky BLOCK_CRYPTO_OPT_DEF_LUKS_ITER_TIME("encrypt."),
6131df373fb0SMaxim Levitsky QCOW_COMMON_OPTIONS,
61321bd0e2d1SChunyan Liu { /* end of list */ }
61331bd0e2d1SChunyan Liu }
613420d97356SBlue Swirl };
613520d97356SBlue Swirl
61362654267cSMax Reitz static const char *const qcow2_strong_runtime_opts[] = {
61372654267cSMax Reitz "encrypt." BLOCK_CRYPTO_OPT_QCOW_KEY_SECRET,
61382654267cSMax Reitz
61392654267cSMax Reitz NULL
61402654267cSMax Reitz };
61412654267cSMax Reitz
61425f535a94SMax Reitz BlockDriver bdrv_qcow2 = {
614320d97356SBlue Swirl .format_name = "qcow2",
6144ff99129aSKevin Wolf .instance_size = sizeof(BDRVQcow2State),
61457c80ab3fSJes Sorensen .bdrv_probe = qcow2_probe,
61467c80ab3fSJes Sorensen .bdrv_open = qcow2_open,
61477c80ab3fSJes Sorensen .bdrv_close = qcow2_close,
614821d82ac9SJeff Cody .bdrv_reopen_prepare = qcow2_reopen_prepare,
61495b0959a7SKevin Wolf .bdrv_reopen_commit = qcow2_reopen_commit,
615065eb7c85SPeter Krempa .bdrv_reopen_commit_post = qcow2_reopen_commit_post,
61515b0959a7SKevin Wolf .bdrv_reopen_abort = qcow2_reopen_abort,
61525365f44dSKevin Wolf .bdrv_join_options = qcow2_join_options,
615369dca43dSMax Reitz .bdrv_child_perm = bdrv_default_perms,
6154efc75e2aSStefan Hajnoczi .bdrv_co_create_opts = qcow2_co_create_opts,
6155b0292b85SKevin Wolf .bdrv_co_create = qcow2_co_create,
615638841dcdSMax Reitz .bdrv_has_zero_init = qcow2_has_zero_init,
6157a320fb04SEric Blake .bdrv_co_block_status = qcow2_co_block_status,
615820d97356SBlue Swirl
6159df893d25SVladimir Sementsov-Ogievskiy .bdrv_co_preadv_part = qcow2_co_preadv_part,
61605396234bSVladimir Sementsov-Ogievskiy .bdrv_co_pwritev_part = qcow2_co_pwritev_part,
6161eb489bb1SKevin Wolf .bdrv_co_flush_to_os = qcow2_co_flush_to_os,
6162419b19d9SStefan Hajnoczi
61635544b59fSEric Blake .bdrv_co_pwrite_zeroes = qcow2_co_pwrite_zeroes,
616482e8a788SEric Blake .bdrv_co_pdiscard = qcow2_co_pdiscard,
6165fd9fcd37SFam Zheng .bdrv_co_copy_range_from = qcow2_co_copy_range_from,
6166fd9fcd37SFam Zheng .bdrv_co_copy_range_to = qcow2_co_copy_range_to,
6167061ca8a3SKevin Wolf .bdrv_co_truncate = qcow2_co_truncate,
61685396234bSVladimir Sementsov-Ogievskiy .bdrv_co_pwritev_compressed_part = qcow2_co_pwritev_compressed_part,
6169491d27e2SMax Reitz .bdrv_make_empty = qcow2_make_empty,
617020d97356SBlue Swirl
617120d97356SBlue Swirl .bdrv_snapshot_create = qcow2_snapshot_create,
617220d97356SBlue Swirl .bdrv_snapshot_goto = qcow2_snapshot_goto,
617320d97356SBlue Swirl .bdrv_snapshot_delete = qcow2_snapshot_delete,
617420d97356SBlue Swirl .bdrv_snapshot_list = qcow2_snapshot_list,
617551ef6727Sedison .bdrv_snapshot_load_tmp = qcow2_snapshot_load_tmp,
6176c501c352SStefan Hajnoczi .bdrv_measure = qcow2_measure,
61773d47eb0aSEmanuele Giuseppe Esposito .bdrv_co_get_info = qcow2_co_get_info,
617837764dfbSMax Reitz .bdrv_get_specific_info = qcow2_get_specific_info,
617920d97356SBlue Swirl
6180ca5e2ad9SEmanuele Giuseppe Esposito .bdrv_co_save_vmstate = qcow2_co_save_vmstate,
6181ca5e2ad9SEmanuele Giuseppe Esposito .bdrv_co_load_vmstate = qcow2_co_load_vmstate,
618220d97356SBlue Swirl
6183d67066d8SMax Reitz .is_format = true,
61848ee79e70SKevin Wolf .supports_backing = true,
6185e2dd2737SKevin Wolf .bdrv_co_change_backing_file = qcow2_co_change_backing_file,
618620d97356SBlue Swirl
6187d34682cdSKevin Wolf .bdrv_refresh_limits = qcow2_refresh_limits,
61882b148f39SPaolo Bonzini .bdrv_co_invalidate_cache = qcow2_co_invalidate_cache,
6189ec6d8912SKevin Wolf .bdrv_inactivate = qcow2_inactivate,
619006d9260fSAnthony Liguori
61911bd0e2d1SChunyan Liu .create_opts = &qcow2_create_opts,
6192df373fb0SMaxim Levitsky .amend_opts = &qcow2_amend_opts,
61932654267cSMax Reitz .strong_runtime_opts = qcow2_strong_runtime_opts,
61948a2ce0bcSAlberto Garcia .mutable_opts = mutable_opts,
61952fd61638SPaolo Bonzini .bdrv_co_check = qcow2_co_check,
6196c282e1fdSChunyan Liu .bdrv_amend_options = qcow2_amend_options,
61978ea1613dSMaxim Levitsky .bdrv_co_amend = qcow2_co_amend,
6198279621c0SAlberto Garcia
6199279621c0SAlberto Garcia .bdrv_detach_aio_context = qcow2_detach_aio_context,
6200279621c0SAlberto Garcia .bdrv_attach_aio_context = qcow2_attach_aio_context,
62011b6b0562SVladimir Sementsov-Ogievskiy
6202ef893b5cSEric Blake .bdrv_supports_persistent_dirty_bitmap =
6203ef893b5cSEric Blake qcow2_supports_persistent_dirty_bitmap,
6204d2c3080eSVladimir Sementsov-Ogievskiy .bdrv_co_can_store_new_dirty_bitmap = qcow2_co_can_store_new_dirty_bitmap,
6205d2c3080eSVladimir Sementsov-Ogievskiy .bdrv_co_remove_persistent_dirty_bitmap =
6206d2c3080eSVladimir Sementsov-Ogievskiy qcow2_co_remove_persistent_dirty_bitmap,
620720d97356SBlue Swirl };
620820d97356SBlue Swirl
bdrv_qcow2_init(void)6209019d6b8fSAnthony Liguori static void bdrv_qcow2_init(void)
6210019d6b8fSAnthony Liguori {
6211019d6b8fSAnthony Liguori bdrv_register(&bdrv_qcow2);
6212019d6b8fSAnthony Liguori }
6213019d6b8fSAnthony Liguori
6214019d6b8fSAnthony Liguori block_init(bdrv_qcow2_init);
6215