xref: /qemu/block/qcow2.c (revision 1bf6e9ca9234e1dbcaa18baa06eca9d55cc2dbbb)
1585f8587Sbellard /*
2585f8587Sbellard  * Block driver for the QCOW version 2 format
3585f8587Sbellard  *
4585f8587Sbellard  * Copyright (c) 2004-2006 Fabrice Bellard
5585f8587Sbellard  *
6585f8587Sbellard  * Permission is hereby granted, free of charge, to any person obtaining a copy
7585f8587Sbellard  * of this software and associated documentation files (the "Software"), to deal
8585f8587Sbellard  * in the Software without restriction, including without limitation the rights
9585f8587Sbellard  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10585f8587Sbellard  * copies of the Software, and to permit persons to whom the Software is
11585f8587Sbellard  * furnished to do so, subject to the following conditions:
12585f8587Sbellard  *
13585f8587Sbellard  * The above copyright notice and this permission notice shall be included in
14585f8587Sbellard  * all copies or substantial portions of the Software.
15585f8587Sbellard  *
16585f8587Sbellard  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17585f8587Sbellard  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18585f8587Sbellard  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19585f8587Sbellard  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20585f8587Sbellard  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21585f8587Sbellard  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22585f8587Sbellard  * THE SOFTWARE.
23585f8587Sbellard  */
24e688df6bSMarkus Armbruster 
2580c71a24SPeter Maydell #include "qemu/osdep.h"
262714f13dSVladimir Sementsov-Ogievskiy 
272714f13dSVladimir Sementsov-Ogievskiy #define ZLIB_CONST
282714f13dSVladimir Sementsov-Ogievskiy #include <zlib.h>
292714f13dSVladimir Sementsov-Ogievskiy 
30737e150eSPaolo Bonzini #include "block/block_int.h"
31609f45eaSMax Reitz #include "block/qdict.h"
3223588797SKevin Wolf #include "sysemu/block-backend.h"
331de7afc9SPaolo Bonzini #include "qemu/module.h"
340d8c41daSMichael S. Tsirkin #include "qcow2.h"
351de7afc9SPaolo Bonzini #include "qemu/error-report.h"
36e688df6bSMarkus Armbruster #include "qapi/error.h"
379af23989SMarkus Armbruster #include "qapi/qapi-events-block-core.h"
386b673957SMarkus Armbruster #include "qapi/qmp/qdict.h"
396b673957SMarkus Armbruster #include "qapi/qmp/qstring.h"
403cce16f4SKevin Wolf #include "trace.h"
411bd0e2d1SChunyan Liu #include "qemu/option_int.h"
42f348b6d1SVeronia Bahaa #include "qemu/cutils.h"
4358369e22SPaolo Bonzini #include "qemu/bswap.h"
44b76b4f60SKevin Wolf #include "qapi/qobject-input-visitor.h"
45b76b4f60SKevin Wolf #include "qapi/qapi-visit-block-core.h"
460d8c41daSMichael S. Tsirkin #include "crypto.h"
47ceb029cdSVladimir Sementsov-Ogievskiy #include "block/thread-pool.h"
48585f8587Sbellard 
49585f8587Sbellard /*
50585f8587Sbellard   Differences with QCOW:
51585f8587Sbellard 
52585f8587Sbellard   - Support for multiple incremental snapshots.
53585f8587Sbellard   - Memory management by reference counts.
54585f8587Sbellard   - Clusters which have a reference count of one have the bit
55585f8587Sbellard     QCOW_OFLAG_COPIED to optimize write performance.
56585f8587Sbellard   - Size of compressed clusters is stored in sectors to reduce bit usage
57585f8587Sbellard     in the cluster offsets.
58585f8587Sbellard   - Support for storing additional data (such as the VM state) in the
59585f8587Sbellard     snapshots.
60585f8587Sbellard   - If a backing store is used, the cluster size is not constrained
61585f8587Sbellard     (could be backported to QCOW).
62585f8587Sbellard   - L2 tables have always a size of one cluster.
63585f8587Sbellard */
64585f8587Sbellard 
659b80ddf3Saliguori 
669b80ddf3Saliguori typedef struct {
679b80ddf3Saliguori     uint32_t magic;
689b80ddf3Saliguori     uint32_t len;
69c4217f64SJeff Cody } QEMU_PACKED QCowExtension;
7021d82ac9SJeff Cody 
717c80ab3fSJes Sorensen #define  QCOW2_EXT_MAGIC_END 0
727c80ab3fSJes Sorensen #define  QCOW2_EXT_MAGIC_BACKING_FORMAT 0xE2792ACA
73cfcc4c62SKevin Wolf #define  QCOW2_EXT_MAGIC_FEATURE_TABLE 0x6803f857
744652b8f3SDaniel P. Berrange #define  QCOW2_EXT_MAGIC_CRYPTO_HEADER 0x0537be77
7588ddffaeSVladimir Sementsov-Ogievskiy #define  QCOW2_EXT_MAGIC_BITMAPS 0x23852875
769b80ddf3Saliguori 
77c3c10f72SVladimir Sementsov-Ogievskiy static int coroutine_fn
78c3c10f72SVladimir Sementsov-Ogievskiy qcow2_co_preadv_compressed(BlockDriverState *bs,
79c3c10f72SVladimir Sementsov-Ogievskiy                            uint64_t file_cluster_offset,
80c3c10f72SVladimir Sementsov-Ogievskiy                            uint64_t offset,
81c3c10f72SVladimir Sementsov-Ogievskiy                            uint64_t bytes,
82c3c10f72SVladimir Sementsov-Ogievskiy                            QEMUIOVector *qiov);
83c3c10f72SVladimir Sementsov-Ogievskiy 
847c80ab3fSJes Sorensen static int qcow2_probe(const uint8_t *buf, int buf_size, const char *filename)
85585f8587Sbellard {
86585f8587Sbellard     const QCowHeader *cow_header = (const void *)buf;
87585f8587Sbellard 
88585f8587Sbellard     if (buf_size >= sizeof(QCowHeader) &&
89585f8587Sbellard         be32_to_cpu(cow_header->magic) == QCOW_MAGIC &&
906744cbabSKevin Wolf         be32_to_cpu(cow_header->version) >= 2)
91585f8587Sbellard         return 100;
92585f8587Sbellard     else
93585f8587Sbellard         return 0;
94585f8587Sbellard }
95585f8587Sbellard 
969b80ddf3Saliguori 
974652b8f3SDaniel P. Berrange static ssize_t qcow2_crypto_hdr_read_func(QCryptoBlock *block, size_t offset,
984652b8f3SDaniel P. Berrange                                           uint8_t *buf, size_t buflen,
994652b8f3SDaniel P. Berrange                                           void *opaque, Error **errp)
1004652b8f3SDaniel P. Berrange {
1014652b8f3SDaniel P. Berrange     BlockDriverState *bs = opaque;
1024652b8f3SDaniel P. Berrange     BDRVQcow2State *s = bs->opaque;
1034652b8f3SDaniel P. Berrange     ssize_t ret;
1044652b8f3SDaniel P. Berrange 
1054652b8f3SDaniel P. Berrange     if ((offset + buflen) > s->crypto_header.length) {
1064652b8f3SDaniel P. Berrange         error_setg(errp, "Request for data outside of extension header");
1074652b8f3SDaniel P. Berrange         return -1;
1084652b8f3SDaniel P. Berrange     }
1094652b8f3SDaniel P. Berrange 
1104652b8f3SDaniel P. Berrange     ret = bdrv_pread(bs->file,
1114652b8f3SDaniel P. Berrange                      s->crypto_header.offset + offset, buf, buflen);
1124652b8f3SDaniel P. Berrange     if (ret < 0) {
1134652b8f3SDaniel P. Berrange         error_setg_errno(errp, -ret, "Could not read encryption header");
1144652b8f3SDaniel P. Berrange         return -1;
1154652b8f3SDaniel P. Berrange     }
1164652b8f3SDaniel P. Berrange     return ret;
1174652b8f3SDaniel P. Berrange }
1184652b8f3SDaniel P. Berrange 
1194652b8f3SDaniel P. Berrange 
1204652b8f3SDaniel P. Berrange static ssize_t qcow2_crypto_hdr_init_func(QCryptoBlock *block, size_t headerlen,
1214652b8f3SDaniel P. Berrange                                           void *opaque, Error **errp)
1224652b8f3SDaniel P. Berrange {
1234652b8f3SDaniel P. Berrange     BlockDriverState *bs = opaque;
1244652b8f3SDaniel P. Berrange     BDRVQcow2State *s = bs->opaque;
1254652b8f3SDaniel P. Berrange     int64_t ret;
1264652b8f3SDaniel P. Berrange     int64_t clusterlen;
1274652b8f3SDaniel P. Berrange 
1284652b8f3SDaniel P. Berrange     ret = qcow2_alloc_clusters(bs, headerlen);
1294652b8f3SDaniel P. Berrange     if (ret < 0) {
1304652b8f3SDaniel P. Berrange         error_setg_errno(errp, -ret,
1314652b8f3SDaniel P. Berrange                          "Cannot allocate cluster for LUKS header size %zu",
1324652b8f3SDaniel P. Berrange                          headerlen);
1334652b8f3SDaniel P. Berrange         return -1;
1344652b8f3SDaniel P. Berrange     }
1354652b8f3SDaniel P. Berrange 
1364652b8f3SDaniel P. Berrange     s->crypto_header.length = headerlen;
1374652b8f3SDaniel P. Berrange     s->crypto_header.offset = ret;
1384652b8f3SDaniel P. Berrange 
1394652b8f3SDaniel P. Berrange     /* Zero fill remaining space in cluster so it has predictable
1404652b8f3SDaniel P. Berrange      * content in case of future spec changes */
1414652b8f3SDaniel P. Berrange     clusterlen = size_to_clusters(s, headerlen) * s->cluster_size;
142c9b83e9cSAlberto Garcia     assert(qcow2_pre_write_overlap_check(bs, 0, ret, clusterlen) == 0);
1434652b8f3SDaniel P. Berrange     ret = bdrv_pwrite_zeroes(bs->file,
1444652b8f3SDaniel P. Berrange                              ret + headerlen,
1454652b8f3SDaniel P. Berrange                              clusterlen - headerlen, 0);
1464652b8f3SDaniel P. Berrange     if (ret < 0) {
1474652b8f3SDaniel P. Berrange         error_setg_errno(errp, -ret, "Could not zero fill encryption header");
1484652b8f3SDaniel P. Berrange         return -1;
1494652b8f3SDaniel P. Berrange     }
1504652b8f3SDaniel P. Berrange 
1514652b8f3SDaniel P. Berrange     return ret;
1524652b8f3SDaniel P. Berrange }
1534652b8f3SDaniel P. Berrange 
1544652b8f3SDaniel P. Berrange 
1554652b8f3SDaniel P. Berrange static ssize_t qcow2_crypto_hdr_write_func(QCryptoBlock *block, size_t offset,
1564652b8f3SDaniel P. Berrange                                            const uint8_t *buf, size_t buflen,
1574652b8f3SDaniel P. Berrange                                            void *opaque, Error **errp)
1584652b8f3SDaniel P. Berrange {
1594652b8f3SDaniel P. Berrange     BlockDriverState *bs = opaque;
1604652b8f3SDaniel P. Berrange     BDRVQcow2State *s = bs->opaque;
1614652b8f3SDaniel P. Berrange     ssize_t ret;
1624652b8f3SDaniel P. Berrange 
1634652b8f3SDaniel P. Berrange     if ((offset + buflen) > s->crypto_header.length) {
1644652b8f3SDaniel P. Berrange         error_setg(errp, "Request for data outside of extension header");
1654652b8f3SDaniel P. Berrange         return -1;
1664652b8f3SDaniel P. Berrange     }
1674652b8f3SDaniel P. Berrange 
1684652b8f3SDaniel P. Berrange     ret = bdrv_pwrite(bs->file,
1694652b8f3SDaniel P. Berrange                       s->crypto_header.offset + offset, buf, buflen);
1704652b8f3SDaniel P. Berrange     if (ret < 0) {
1714652b8f3SDaniel P. Berrange         error_setg_errno(errp, -ret, "Could not read encryption header");
1724652b8f3SDaniel P. Berrange         return -1;
1734652b8f3SDaniel P. Berrange     }
1744652b8f3SDaniel P. Berrange     return ret;
1754652b8f3SDaniel P. Berrange }
1764652b8f3SDaniel P. Berrange 
1774652b8f3SDaniel P. Berrange 
1789b80ddf3Saliguori /*
1799b80ddf3Saliguori  * read qcow2 extension and fill bs
1809b80ddf3Saliguori  * start reading from start_offset
1819b80ddf3Saliguori  * finish reading upon magic of value 0 or when end_offset reached
1829b80ddf3Saliguori  * unknown magic is skipped (future extension this version knows nothing about)
1839b80ddf3Saliguori  * return 0 upon success, non-0 otherwise
1849b80ddf3Saliguori  */
1857c80ab3fSJes Sorensen static int qcow2_read_extensions(BlockDriverState *bs, uint64_t start_offset,
1863ef6c40aSMax Reitz                                  uint64_t end_offset, void **p_feature_table,
18788ddffaeSVladimir Sementsov-Ogievskiy                                  int flags, bool *need_update_header,
18888ddffaeSVladimir Sementsov-Ogievskiy                                  Error **errp)
1899b80ddf3Saliguori {
190ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
1919b80ddf3Saliguori     QCowExtension ext;
1929b80ddf3Saliguori     uint64_t offset;
19375bab85cSKevin Wolf     int ret;
19488ddffaeSVladimir Sementsov-Ogievskiy     Qcow2BitmapHeaderExt bitmaps_ext;
19588ddffaeSVladimir Sementsov-Ogievskiy 
19688ddffaeSVladimir Sementsov-Ogievskiy     if (need_update_header != NULL) {
19788ddffaeSVladimir Sementsov-Ogievskiy         *need_update_header = false;
19888ddffaeSVladimir Sementsov-Ogievskiy     }
1999b80ddf3Saliguori 
2009b80ddf3Saliguori #ifdef DEBUG_EXT
2017c80ab3fSJes Sorensen     printf("qcow2_read_extensions: start=%ld end=%ld\n", start_offset, end_offset);
2029b80ddf3Saliguori #endif
2039b80ddf3Saliguori     offset = start_offset;
2049b80ddf3Saliguori     while (offset < end_offset) {
2059b80ddf3Saliguori 
2069b80ddf3Saliguori #ifdef DEBUG_EXT
2079b80ddf3Saliguori         /* Sanity check */
2089b80ddf3Saliguori         if (offset > s->cluster_size)
2097c80ab3fSJes Sorensen             printf("qcow2_read_extension: suspicious offset %lu\n", offset);
2109b80ddf3Saliguori 
2119b2260cbSDong Xu Wang         printf("attempting to read extended header in offset %lu\n", offset);
2129b80ddf3Saliguori #endif
2139b80ddf3Saliguori 
214cf2ab8fcSKevin Wolf         ret = bdrv_pread(bs->file, offset, &ext, sizeof(ext));
2153ef6c40aSMax Reitz         if (ret < 0) {
2163ef6c40aSMax Reitz             error_setg_errno(errp, -ret, "qcow2_read_extension: ERROR: "
2173ef6c40aSMax Reitz                              "pread fail from offset %" PRIu64, offset);
2189b80ddf3Saliguori             return 1;
2199b80ddf3Saliguori         }
2203b698f52SPeter Maydell         ext.magic = be32_to_cpu(ext.magic);
2213b698f52SPeter Maydell         ext.len = be32_to_cpu(ext.len);
2229b80ddf3Saliguori         offset += sizeof(ext);
2239b80ddf3Saliguori #ifdef DEBUG_EXT
2249b80ddf3Saliguori         printf("ext.magic = 0x%x\n", ext.magic);
2259b80ddf3Saliguori #endif
2262ebafc85SKevin Wolf         if (offset > end_offset || ext.len > end_offset - offset) {
2273ef6c40aSMax Reitz             error_setg(errp, "Header extension too large");
22864ca6aeeSKevin Wolf             return -EINVAL;
22964ca6aeeSKevin Wolf         }
23064ca6aeeSKevin Wolf 
2319b80ddf3Saliguori         switch (ext.magic) {
2327c80ab3fSJes Sorensen         case QCOW2_EXT_MAGIC_END:
2339b80ddf3Saliguori             return 0;
234f965509cSaliguori 
2357c80ab3fSJes Sorensen         case QCOW2_EXT_MAGIC_BACKING_FORMAT:
236f965509cSaliguori             if (ext.len >= sizeof(bs->backing_format)) {
237521b2b5dSMax Reitz                 error_setg(errp, "ERROR: ext_backing_format: len=%" PRIu32
238521b2b5dSMax Reitz                            " too large (>=%zu)", ext.len,
239521b2b5dSMax Reitz                            sizeof(bs->backing_format));
240f965509cSaliguori                 return 2;
241f965509cSaliguori             }
242cf2ab8fcSKevin Wolf             ret = bdrv_pread(bs->file, offset, bs->backing_format, ext.len);
2433ef6c40aSMax Reitz             if (ret < 0) {
2443ef6c40aSMax Reitz                 error_setg_errno(errp, -ret, "ERROR: ext_backing_format: "
2453ef6c40aSMax Reitz                                  "Could not read format name");
246f965509cSaliguori                 return 3;
2473ef6c40aSMax Reitz             }
248f965509cSaliguori             bs->backing_format[ext.len] = '\0';
249e4603fe1SKevin Wolf             s->image_backing_format = g_strdup(bs->backing_format);
250f965509cSaliguori #ifdef DEBUG_EXT
251f965509cSaliguori             printf("Qcow2: Got format extension %s\n", bs->backing_format);
252f965509cSaliguori #endif
253f965509cSaliguori             break;
254f965509cSaliguori 
255cfcc4c62SKevin Wolf         case QCOW2_EXT_MAGIC_FEATURE_TABLE:
256cfcc4c62SKevin Wolf             if (p_feature_table != NULL) {
257cfcc4c62SKevin Wolf                 void* feature_table = g_malloc0(ext.len + 2 * sizeof(Qcow2Feature));
258cf2ab8fcSKevin Wolf                 ret = bdrv_pread(bs->file, offset , feature_table, ext.len);
259cfcc4c62SKevin Wolf                 if (ret < 0) {
2603ef6c40aSMax Reitz                     error_setg_errno(errp, -ret, "ERROR: ext_feature_table: "
2613ef6c40aSMax Reitz                                      "Could not read table");
262cfcc4c62SKevin Wolf                     return ret;
263cfcc4c62SKevin Wolf                 }
264cfcc4c62SKevin Wolf 
265cfcc4c62SKevin Wolf                 *p_feature_table = feature_table;
266cfcc4c62SKevin Wolf             }
267cfcc4c62SKevin Wolf             break;
268cfcc4c62SKevin Wolf 
2694652b8f3SDaniel P. Berrange         case QCOW2_EXT_MAGIC_CRYPTO_HEADER: {
2704652b8f3SDaniel P. Berrange             unsigned int cflags = 0;
2714652b8f3SDaniel P. Berrange             if (s->crypt_method_header != QCOW_CRYPT_LUKS) {
2724652b8f3SDaniel P. Berrange                 error_setg(errp, "CRYPTO header extension only "
2734652b8f3SDaniel P. Berrange                            "expected with LUKS encryption method");
2744652b8f3SDaniel P. Berrange                 return -EINVAL;
2754652b8f3SDaniel P. Berrange             }
2764652b8f3SDaniel P. Berrange             if (ext.len != sizeof(Qcow2CryptoHeaderExtension)) {
2774652b8f3SDaniel P. Berrange                 error_setg(errp, "CRYPTO header extension size %u, "
2784652b8f3SDaniel P. Berrange                            "but expected size %zu", ext.len,
2794652b8f3SDaniel P. Berrange                            sizeof(Qcow2CryptoHeaderExtension));
2804652b8f3SDaniel P. Berrange                 return -EINVAL;
2814652b8f3SDaniel P. Berrange             }
2824652b8f3SDaniel P. Berrange 
2834652b8f3SDaniel P. Berrange             ret = bdrv_pread(bs->file, offset, &s->crypto_header, ext.len);
2844652b8f3SDaniel P. Berrange             if (ret < 0) {
2854652b8f3SDaniel P. Berrange                 error_setg_errno(errp, -ret,
2864652b8f3SDaniel P. Berrange                                  "Unable to read CRYPTO header extension");
2874652b8f3SDaniel P. Berrange                 return ret;
2884652b8f3SDaniel P. Berrange             }
2893b698f52SPeter Maydell             s->crypto_header.offset = be64_to_cpu(s->crypto_header.offset);
2903b698f52SPeter Maydell             s->crypto_header.length = be64_to_cpu(s->crypto_header.length);
2914652b8f3SDaniel P. Berrange 
2924652b8f3SDaniel P. Berrange             if ((s->crypto_header.offset % s->cluster_size) != 0) {
2934652b8f3SDaniel P. Berrange                 error_setg(errp, "Encryption header offset '%" PRIu64 "' is "
2944652b8f3SDaniel P. Berrange                            "not a multiple of cluster size '%u'",
2954652b8f3SDaniel P. Berrange                            s->crypto_header.offset, s->cluster_size);
2964652b8f3SDaniel P. Berrange                 return -EINVAL;
2974652b8f3SDaniel P. Berrange             }
2984652b8f3SDaniel P. Berrange 
2994652b8f3SDaniel P. Berrange             if (flags & BDRV_O_NO_IO) {
3004652b8f3SDaniel P. Berrange                 cflags |= QCRYPTO_BLOCK_OPEN_NO_IO;
3014652b8f3SDaniel P. Berrange             }
3021cd9a787SDaniel P. Berrange             s->crypto = qcrypto_block_open(s->crypto_opts, "encrypt.",
3034652b8f3SDaniel P. Berrange                                            qcow2_crypto_hdr_read_func,
304c972fa12SVladimir Sementsov-Ogievskiy                                            bs, cflags, 1, errp);
3054652b8f3SDaniel P. Berrange             if (!s->crypto) {
3064652b8f3SDaniel P. Berrange                 return -EINVAL;
3074652b8f3SDaniel P. Berrange             }
3084652b8f3SDaniel P. Berrange         }   break;
3094652b8f3SDaniel P. Berrange 
31088ddffaeSVladimir Sementsov-Ogievskiy         case QCOW2_EXT_MAGIC_BITMAPS:
31188ddffaeSVladimir Sementsov-Ogievskiy             if (ext.len != sizeof(bitmaps_ext)) {
31288ddffaeSVladimir Sementsov-Ogievskiy                 error_setg_errno(errp, -ret, "bitmaps_ext: "
31388ddffaeSVladimir Sementsov-Ogievskiy                                  "Invalid extension length");
31488ddffaeSVladimir Sementsov-Ogievskiy                 return -EINVAL;
31588ddffaeSVladimir Sementsov-Ogievskiy             }
31688ddffaeSVladimir Sementsov-Ogievskiy 
31788ddffaeSVladimir Sementsov-Ogievskiy             if (!(s->autoclear_features & QCOW2_AUTOCLEAR_BITMAPS)) {
318c9ceb3ecSMax Reitz                 if (s->qcow_version < 3) {
319c9ceb3ecSMax Reitz                     /* Let's be a bit more specific */
320c9ceb3ecSMax Reitz                     warn_report("This qcow2 v2 image contains bitmaps, but "
321c9ceb3ecSMax Reitz                                 "they may have been modified by a program "
322c9ceb3ecSMax Reitz                                 "without persistent bitmap support; so now "
323c9ceb3ecSMax Reitz                                 "they must all be considered inconsistent");
324c9ceb3ecSMax Reitz                 } else {
32555d527a9SAlistair Francis                     warn_report("a program lacking bitmap support "
32688ddffaeSVladimir Sementsov-Ogievskiy                                 "modified this file, so all bitmaps are now "
32755d527a9SAlistair Francis                                 "considered inconsistent");
328c9ceb3ecSMax Reitz                 }
32955d527a9SAlistair Francis                 error_printf("Some clusters may be leaked, "
33055d527a9SAlistair Francis                              "run 'qemu-img check -r' on the image "
33188ddffaeSVladimir Sementsov-Ogievskiy                              "file to fix.");
33288ddffaeSVladimir Sementsov-Ogievskiy                 if (need_update_header != NULL) {
33388ddffaeSVladimir Sementsov-Ogievskiy                     /* Updating is needed to drop invalid bitmap extension. */
33488ddffaeSVladimir Sementsov-Ogievskiy                     *need_update_header = true;
33588ddffaeSVladimir Sementsov-Ogievskiy                 }
33688ddffaeSVladimir Sementsov-Ogievskiy                 break;
33788ddffaeSVladimir Sementsov-Ogievskiy             }
33888ddffaeSVladimir Sementsov-Ogievskiy 
33988ddffaeSVladimir Sementsov-Ogievskiy             ret = bdrv_pread(bs->file, offset, &bitmaps_ext, ext.len);
34088ddffaeSVladimir Sementsov-Ogievskiy             if (ret < 0) {
34188ddffaeSVladimir Sementsov-Ogievskiy                 error_setg_errno(errp, -ret, "bitmaps_ext: "
34288ddffaeSVladimir Sementsov-Ogievskiy                                  "Could not read ext header");
34388ddffaeSVladimir Sementsov-Ogievskiy                 return ret;
34488ddffaeSVladimir Sementsov-Ogievskiy             }
34588ddffaeSVladimir Sementsov-Ogievskiy 
34688ddffaeSVladimir Sementsov-Ogievskiy             if (bitmaps_ext.reserved32 != 0) {
34788ddffaeSVladimir Sementsov-Ogievskiy                 error_setg_errno(errp, -ret, "bitmaps_ext: "
34888ddffaeSVladimir Sementsov-Ogievskiy                                  "Reserved field is not zero");
34988ddffaeSVladimir Sementsov-Ogievskiy                 return -EINVAL;
35088ddffaeSVladimir Sementsov-Ogievskiy             }
35188ddffaeSVladimir Sementsov-Ogievskiy 
3523b698f52SPeter Maydell             bitmaps_ext.nb_bitmaps = be32_to_cpu(bitmaps_ext.nb_bitmaps);
3533b698f52SPeter Maydell             bitmaps_ext.bitmap_directory_size =
3543b698f52SPeter Maydell                 be64_to_cpu(bitmaps_ext.bitmap_directory_size);
3553b698f52SPeter Maydell             bitmaps_ext.bitmap_directory_offset =
3563b698f52SPeter Maydell                 be64_to_cpu(bitmaps_ext.bitmap_directory_offset);
35788ddffaeSVladimir Sementsov-Ogievskiy 
35888ddffaeSVladimir Sementsov-Ogievskiy             if (bitmaps_ext.nb_bitmaps > QCOW2_MAX_BITMAPS) {
35988ddffaeSVladimir Sementsov-Ogievskiy                 error_setg(errp,
36088ddffaeSVladimir Sementsov-Ogievskiy                            "bitmaps_ext: Image has %" PRIu32 " bitmaps, "
36188ddffaeSVladimir Sementsov-Ogievskiy                            "exceeding the QEMU supported maximum of %d",
36288ddffaeSVladimir Sementsov-Ogievskiy                            bitmaps_ext.nb_bitmaps, QCOW2_MAX_BITMAPS);
36388ddffaeSVladimir Sementsov-Ogievskiy                 return -EINVAL;
36488ddffaeSVladimir Sementsov-Ogievskiy             }
36588ddffaeSVladimir Sementsov-Ogievskiy 
36688ddffaeSVladimir Sementsov-Ogievskiy             if (bitmaps_ext.nb_bitmaps == 0) {
36788ddffaeSVladimir Sementsov-Ogievskiy                 error_setg(errp, "found bitmaps extension with zero bitmaps");
36888ddffaeSVladimir Sementsov-Ogievskiy                 return -EINVAL;
36988ddffaeSVladimir Sementsov-Ogievskiy             }
37088ddffaeSVladimir Sementsov-Ogievskiy 
37188ddffaeSVladimir Sementsov-Ogievskiy             if (bitmaps_ext.bitmap_directory_offset & (s->cluster_size - 1)) {
37288ddffaeSVladimir Sementsov-Ogievskiy                 error_setg(errp, "bitmaps_ext: "
37388ddffaeSVladimir Sementsov-Ogievskiy                                  "invalid bitmap directory offset");
37488ddffaeSVladimir Sementsov-Ogievskiy                 return -EINVAL;
37588ddffaeSVladimir Sementsov-Ogievskiy             }
37688ddffaeSVladimir Sementsov-Ogievskiy 
37788ddffaeSVladimir Sementsov-Ogievskiy             if (bitmaps_ext.bitmap_directory_size >
37888ddffaeSVladimir Sementsov-Ogievskiy                 QCOW2_MAX_BITMAP_DIRECTORY_SIZE) {
37988ddffaeSVladimir Sementsov-Ogievskiy                 error_setg(errp, "bitmaps_ext: "
38088ddffaeSVladimir Sementsov-Ogievskiy                                  "bitmap directory size (%" PRIu64 ") exceeds "
38188ddffaeSVladimir Sementsov-Ogievskiy                                  "the maximum supported size (%d)",
38288ddffaeSVladimir Sementsov-Ogievskiy                                  bitmaps_ext.bitmap_directory_size,
38388ddffaeSVladimir Sementsov-Ogievskiy                                  QCOW2_MAX_BITMAP_DIRECTORY_SIZE);
38488ddffaeSVladimir Sementsov-Ogievskiy                 return -EINVAL;
38588ddffaeSVladimir Sementsov-Ogievskiy             }
38688ddffaeSVladimir Sementsov-Ogievskiy 
38788ddffaeSVladimir Sementsov-Ogievskiy             s->nb_bitmaps = bitmaps_ext.nb_bitmaps;
38888ddffaeSVladimir Sementsov-Ogievskiy             s->bitmap_directory_offset =
38988ddffaeSVladimir Sementsov-Ogievskiy                     bitmaps_ext.bitmap_directory_offset;
39088ddffaeSVladimir Sementsov-Ogievskiy             s->bitmap_directory_size =
39188ddffaeSVladimir Sementsov-Ogievskiy                     bitmaps_ext.bitmap_directory_size;
39288ddffaeSVladimir Sementsov-Ogievskiy 
39388ddffaeSVladimir Sementsov-Ogievskiy #ifdef DEBUG_EXT
39488ddffaeSVladimir Sementsov-Ogievskiy             printf("Qcow2: Got bitmaps extension: "
39588ddffaeSVladimir Sementsov-Ogievskiy                    "offset=%" PRIu64 " nb_bitmaps=%" PRIu32 "\n",
39688ddffaeSVladimir Sementsov-Ogievskiy                    s->bitmap_directory_offset, s->nb_bitmaps);
39788ddffaeSVladimir Sementsov-Ogievskiy #endif
39888ddffaeSVladimir Sementsov-Ogievskiy             break;
39988ddffaeSVladimir Sementsov-Ogievskiy 
4009b80ddf3Saliguori         default:
40175bab85cSKevin Wolf             /* unknown magic - save it in case we need to rewrite the header */
4024096974eSEric Blake             /* If you add a new feature, make sure to also update the fast
4034096974eSEric Blake              * path of qcow2_make_empty() to deal with it. */
40475bab85cSKevin Wolf             {
40575bab85cSKevin Wolf                 Qcow2UnknownHeaderExtension *uext;
40675bab85cSKevin Wolf 
40775bab85cSKevin Wolf                 uext = g_malloc0(sizeof(*uext)  + ext.len);
40875bab85cSKevin Wolf                 uext->magic = ext.magic;
40975bab85cSKevin Wolf                 uext->len = ext.len;
41075bab85cSKevin Wolf                 QLIST_INSERT_HEAD(&s->unknown_header_ext, uext, next);
41175bab85cSKevin Wolf 
412cf2ab8fcSKevin Wolf                 ret = bdrv_pread(bs->file, offset , uext->data, uext->len);
41375bab85cSKevin Wolf                 if (ret < 0) {
4143ef6c40aSMax Reitz                     error_setg_errno(errp, -ret, "ERROR: unknown extension: "
4153ef6c40aSMax Reitz                                      "Could not read data");
41675bab85cSKevin Wolf                     return ret;
41775bab85cSKevin Wolf                 }
41875bab85cSKevin Wolf             }
4199b80ddf3Saliguori             break;
4209b80ddf3Saliguori         }
421fd29b4bbSKevin Wolf 
422fd29b4bbSKevin Wolf         offset += ((ext.len + 7) & ~7);
4239b80ddf3Saliguori     }
4249b80ddf3Saliguori 
4259b80ddf3Saliguori     return 0;
4269b80ddf3Saliguori }
4279b80ddf3Saliguori 
42875bab85cSKevin Wolf static void cleanup_unknown_header_ext(BlockDriverState *bs)
42975bab85cSKevin Wolf {
430ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
43175bab85cSKevin Wolf     Qcow2UnknownHeaderExtension *uext, *next;
43275bab85cSKevin Wolf 
43375bab85cSKevin Wolf     QLIST_FOREACH_SAFE(uext, &s->unknown_header_ext, next, next) {
43475bab85cSKevin Wolf         QLIST_REMOVE(uext, next);
43575bab85cSKevin Wolf         g_free(uext);
43675bab85cSKevin Wolf     }
43775bab85cSKevin Wolf }
4389b80ddf3Saliguori 
439a55448b3SMax Reitz static void report_unsupported_feature(Error **errp, Qcow2Feature *table,
440a55448b3SMax Reitz                                        uint64_t mask)
441cfcc4c62SKevin Wolf {
44212ac6d3dSKevin Wolf     char *features = g_strdup("");
44312ac6d3dSKevin Wolf     char *old;
44412ac6d3dSKevin Wolf 
445cfcc4c62SKevin Wolf     while (table && table->name[0] != '\0') {
446cfcc4c62SKevin Wolf         if (table->type == QCOW2_FEAT_TYPE_INCOMPATIBLE) {
44712ac6d3dSKevin Wolf             if (mask & (1ULL << table->bit)) {
44812ac6d3dSKevin Wolf                 old = features;
44912ac6d3dSKevin Wolf                 features = g_strdup_printf("%s%s%.46s", old, *old ? ", " : "",
45012ac6d3dSKevin Wolf                                            table->name);
45112ac6d3dSKevin Wolf                 g_free(old);
45212ac6d3dSKevin Wolf                 mask &= ~(1ULL << table->bit);
453cfcc4c62SKevin Wolf             }
454cfcc4c62SKevin Wolf         }
455cfcc4c62SKevin Wolf         table++;
456cfcc4c62SKevin Wolf     }
457cfcc4c62SKevin Wolf 
458cfcc4c62SKevin Wolf     if (mask) {
45912ac6d3dSKevin Wolf         old = features;
46012ac6d3dSKevin Wolf         features = g_strdup_printf("%s%sUnknown incompatible feature: %" PRIx64,
46112ac6d3dSKevin Wolf                                    old, *old ? ", " : "", mask);
46212ac6d3dSKevin Wolf         g_free(old);
463cfcc4c62SKevin Wolf     }
46412ac6d3dSKevin Wolf 
465a55448b3SMax Reitz     error_setg(errp, "Unsupported qcow2 feature(s): %s", features);
46612ac6d3dSKevin Wolf     g_free(features);
467cfcc4c62SKevin Wolf }
468cfcc4c62SKevin Wolf 
469c61d0004SStefan Hajnoczi /*
470bfe8043eSStefan Hajnoczi  * Sets the dirty bit and flushes afterwards if necessary.
471bfe8043eSStefan Hajnoczi  *
472bfe8043eSStefan Hajnoczi  * The incompatible_features bit is only set if the image file header was
473bfe8043eSStefan Hajnoczi  * updated successfully.  Therefore it is not required to check the return
474bfe8043eSStefan Hajnoczi  * value of this function.
475bfe8043eSStefan Hajnoczi  */
476280d3735SKevin Wolf int qcow2_mark_dirty(BlockDriverState *bs)
477bfe8043eSStefan Hajnoczi {
478ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
479bfe8043eSStefan Hajnoczi     uint64_t val;
480bfe8043eSStefan Hajnoczi     int ret;
481bfe8043eSStefan Hajnoczi 
482bfe8043eSStefan Hajnoczi     assert(s->qcow_version >= 3);
483bfe8043eSStefan Hajnoczi 
484bfe8043eSStefan Hajnoczi     if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
485bfe8043eSStefan Hajnoczi         return 0; /* already dirty */
486bfe8043eSStefan Hajnoczi     }
487bfe8043eSStefan Hajnoczi 
488bfe8043eSStefan Hajnoczi     val = cpu_to_be64(s->incompatible_features | QCOW2_INCOMPAT_DIRTY);
489d9ca2ea2SKevin Wolf     ret = bdrv_pwrite(bs->file, offsetof(QCowHeader, incompatible_features),
490bfe8043eSStefan Hajnoczi                       &val, sizeof(val));
491bfe8043eSStefan Hajnoczi     if (ret < 0) {
492bfe8043eSStefan Hajnoczi         return ret;
493bfe8043eSStefan Hajnoczi     }
4949a4f4c31SKevin Wolf     ret = bdrv_flush(bs->file->bs);
495bfe8043eSStefan Hajnoczi     if (ret < 0) {
496bfe8043eSStefan Hajnoczi         return ret;
497bfe8043eSStefan Hajnoczi     }
498bfe8043eSStefan Hajnoczi 
499bfe8043eSStefan Hajnoczi     /* Only treat image as dirty if the header was updated successfully */
500bfe8043eSStefan Hajnoczi     s->incompatible_features |= QCOW2_INCOMPAT_DIRTY;
501bfe8043eSStefan Hajnoczi     return 0;
502bfe8043eSStefan Hajnoczi }
503bfe8043eSStefan Hajnoczi 
504bfe8043eSStefan Hajnoczi /*
505c61d0004SStefan Hajnoczi  * Clears the dirty bit and flushes before if necessary.  Only call this
506c61d0004SStefan Hajnoczi  * function when there are no pending requests, it does not guard against
507c61d0004SStefan Hajnoczi  * concurrent requests dirtying the image.
508c61d0004SStefan Hajnoczi  */
509c61d0004SStefan Hajnoczi static int qcow2_mark_clean(BlockDriverState *bs)
510c61d0004SStefan Hajnoczi {
511ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
512c61d0004SStefan Hajnoczi 
513c61d0004SStefan Hajnoczi     if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
5144c2e5f8fSKevin Wolf         int ret;
5154c2e5f8fSKevin Wolf 
5164c2e5f8fSKevin Wolf         s->incompatible_features &= ~QCOW2_INCOMPAT_DIRTY;
5174c2e5f8fSKevin Wolf 
5188b220eb7SPaolo Bonzini         ret = qcow2_flush_caches(bs);
519c61d0004SStefan Hajnoczi         if (ret < 0) {
520c61d0004SStefan Hajnoczi             return ret;
521c61d0004SStefan Hajnoczi         }
522c61d0004SStefan Hajnoczi 
523c61d0004SStefan Hajnoczi         return qcow2_update_header(bs);
524c61d0004SStefan Hajnoczi     }
525c61d0004SStefan Hajnoczi     return 0;
526c61d0004SStefan Hajnoczi }
527c61d0004SStefan Hajnoczi 
52869c98726SMax Reitz /*
52969c98726SMax Reitz  * Marks the image as corrupt.
53069c98726SMax Reitz  */
53169c98726SMax Reitz int qcow2_mark_corrupt(BlockDriverState *bs)
53269c98726SMax Reitz {
533ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
53469c98726SMax Reitz 
53569c98726SMax Reitz     s->incompatible_features |= QCOW2_INCOMPAT_CORRUPT;
53669c98726SMax Reitz     return qcow2_update_header(bs);
53769c98726SMax Reitz }
53869c98726SMax Reitz 
53969c98726SMax Reitz /*
54069c98726SMax Reitz  * Marks the image as consistent, i.e., unsets the corrupt bit, and flushes
54169c98726SMax Reitz  * before if necessary.
54269c98726SMax Reitz  */
54369c98726SMax Reitz int qcow2_mark_consistent(BlockDriverState *bs)
54469c98726SMax Reitz {
545ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
54669c98726SMax Reitz 
54769c98726SMax Reitz     if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
5488b220eb7SPaolo Bonzini         int ret = qcow2_flush_caches(bs);
54969c98726SMax Reitz         if (ret < 0) {
55069c98726SMax Reitz             return ret;
55169c98726SMax Reitz         }
55269c98726SMax Reitz 
55369c98726SMax Reitz         s->incompatible_features &= ~QCOW2_INCOMPAT_CORRUPT;
55469c98726SMax Reitz         return qcow2_update_header(bs);
55569c98726SMax Reitz     }
55669c98726SMax Reitz     return 0;
55769c98726SMax Reitz }
55869c98726SMax Reitz 
5592fd61638SPaolo Bonzini static int coroutine_fn qcow2_co_check_locked(BlockDriverState *bs,
5602fd61638SPaolo Bonzini                                               BdrvCheckResult *result,
561acbe5982SStefan Hajnoczi                                               BdrvCheckMode fix)
562acbe5982SStefan Hajnoczi {
563acbe5982SStefan Hajnoczi     int ret = qcow2_check_refcounts(bs, result, fix);
564acbe5982SStefan Hajnoczi     if (ret < 0) {
565acbe5982SStefan Hajnoczi         return ret;
566acbe5982SStefan Hajnoczi     }
567acbe5982SStefan Hajnoczi 
568acbe5982SStefan Hajnoczi     if (fix && result->check_errors == 0 && result->corruptions == 0) {
56924530f3eSMax Reitz         ret = qcow2_mark_clean(bs);
57024530f3eSMax Reitz         if (ret < 0) {
57124530f3eSMax Reitz             return ret;
57224530f3eSMax Reitz         }
57324530f3eSMax Reitz         return qcow2_mark_consistent(bs);
574acbe5982SStefan Hajnoczi     }
575acbe5982SStefan Hajnoczi     return ret;
576acbe5982SStefan Hajnoczi }
577acbe5982SStefan Hajnoczi 
5782fd61638SPaolo Bonzini static int coroutine_fn qcow2_co_check(BlockDriverState *bs,
5792fd61638SPaolo Bonzini                                        BdrvCheckResult *result,
5802fd61638SPaolo Bonzini                                        BdrvCheckMode fix)
5812fd61638SPaolo Bonzini {
5822fd61638SPaolo Bonzini     BDRVQcow2State *s = bs->opaque;
5832fd61638SPaolo Bonzini     int ret;
5842fd61638SPaolo Bonzini 
5852fd61638SPaolo Bonzini     qemu_co_mutex_lock(&s->lock);
5862fd61638SPaolo Bonzini     ret = qcow2_co_check_locked(bs, result, fix);
5872fd61638SPaolo Bonzini     qemu_co_mutex_unlock(&s->lock);
5882fd61638SPaolo Bonzini     return ret;
5892fd61638SPaolo Bonzini }
5902fd61638SPaolo Bonzini 
5910cf0e598SAlberto Garcia int qcow2_validate_table(BlockDriverState *bs, uint64_t offset,
5920cf0e598SAlberto Garcia                          uint64_t entries, size_t entry_len,
5930cf0e598SAlberto Garcia                          int64_t max_size_bytes, const char *table_name,
5940cf0e598SAlberto Garcia                          Error **errp)
5958c7de283SKevin Wolf {
596ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
5970cf0e598SAlberto Garcia 
5980cf0e598SAlberto Garcia     if (entries > max_size_bytes / entry_len) {
5990cf0e598SAlberto Garcia         error_setg(errp, "%s too large", table_name);
6000cf0e598SAlberto Garcia         return -EFBIG;
6010cf0e598SAlberto Garcia     }
6028c7de283SKevin Wolf 
6038c7de283SKevin Wolf     /* Use signed INT64_MAX as the maximum even for uint64_t header fields,
6048c7de283SKevin Wolf      * because values will be passed to qemu functions taking int64_t. */
6050cf0e598SAlberto Garcia     if ((INT64_MAX - entries * entry_len < offset) ||
6060cf0e598SAlberto Garcia         (offset_into_cluster(s, offset) != 0)) {
6070cf0e598SAlberto Garcia         error_setg(errp, "%s offset invalid", table_name);
6088c7de283SKevin Wolf         return -EINVAL;
6098c7de283SKevin Wolf     }
6108c7de283SKevin Wolf 
6118c7de283SKevin Wolf     return 0;
6128c7de283SKevin Wolf }
6138c7de283SKevin Wolf 
61474c4510aSKevin Wolf static QemuOptsList qcow2_runtime_opts = {
61574c4510aSKevin Wolf     .name = "qcow2",
61674c4510aSKevin Wolf     .head = QTAILQ_HEAD_INITIALIZER(qcow2_runtime_opts.head),
61774c4510aSKevin Wolf     .desc = {
61874c4510aSKevin Wolf         {
61964aa99d3SKevin Wolf             .name = QCOW2_OPT_LAZY_REFCOUNTS,
62074c4510aSKevin Wolf             .type = QEMU_OPT_BOOL,
62174c4510aSKevin Wolf             .help = "Postpone refcount updates",
62274c4510aSKevin Wolf         },
62367af674eSKevin Wolf         {
62467af674eSKevin Wolf             .name = QCOW2_OPT_DISCARD_REQUEST,
62567af674eSKevin Wolf             .type = QEMU_OPT_BOOL,
62667af674eSKevin Wolf             .help = "Pass guest discard requests to the layer below",
62767af674eSKevin Wolf         },
62867af674eSKevin Wolf         {
62967af674eSKevin Wolf             .name = QCOW2_OPT_DISCARD_SNAPSHOT,
63067af674eSKevin Wolf             .type = QEMU_OPT_BOOL,
63167af674eSKevin Wolf             .help = "Generate discard requests when snapshot related space "
63267af674eSKevin Wolf                     "is freed",
63367af674eSKevin Wolf         },
63467af674eSKevin Wolf         {
63567af674eSKevin Wolf             .name = QCOW2_OPT_DISCARD_OTHER,
63667af674eSKevin Wolf             .type = QEMU_OPT_BOOL,
63767af674eSKevin Wolf             .help = "Generate discard requests when other clusters are freed",
63867af674eSKevin Wolf         },
63905de7e86SMax Reitz         {
64005de7e86SMax Reitz             .name = QCOW2_OPT_OVERLAP,
64105de7e86SMax Reitz             .type = QEMU_OPT_STRING,
64205de7e86SMax Reitz             .help = "Selects which overlap checks to perform from a range of "
64305de7e86SMax Reitz                     "templates (none, constant, cached, all)",
64405de7e86SMax Reitz         },
64505de7e86SMax Reitz         {
646ee42b5ceSMax Reitz             .name = QCOW2_OPT_OVERLAP_TEMPLATE,
647ee42b5ceSMax Reitz             .type = QEMU_OPT_STRING,
648ee42b5ceSMax Reitz             .help = "Selects which overlap checks to perform from a range of "
649ee42b5ceSMax Reitz                     "templates (none, constant, cached, all)",
650ee42b5ceSMax Reitz         },
651ee42b5ceSMax Reitz         {
65205de7e86SMax Reitz             .name = QCOW2_OPT_OVERLAP_MAIN_HEADER,
65305de7e86SMax Reitz             .type = QEMU_OPT_BOOL,
65405de7e86SMax Reitz             .help = "Check for unintended writes into the main qcow2 header",
65505de7e86SMax Reitz         },
65605de7e86SMax Reitz         {
65705de7e86SMax Reitz             .name = QCOW2_OPT_OVERLAP_ACTIVE_L1,
65805de7e86SMax Reitz             .type = QEMU_OPT_BOOL,
65905de7e86SMax Reitz             .help = "Check for unintended writes into the active L1 table",
66005de7e86SMax Reitz         },
66105de7e86SMax Reitz         {
66205de7e86SMax Reitz             .name = QCOW2_OPT_OVERLAP_ACTIVE_L2,
66305de7e86SMax Reitz             .type = QEMU_OPT_BOOL,
66405de7e86SMax Reitz             .help = "Check for unintended writes into an active L2 table",
66505de7e86SMax Reitz         },
66605de7e86SMax Reitz         {
66705de7e86SMax Reitz             .name = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
66805de7e86SMax Reitz             .type = QEMU_OPT_BOOL,
66905de7e86SMax Reitz             .help = "Check for unintended writes into the refcount table",
67005de7e86SMax Reitz         },
67105de7e86SMax Reitz         {
67205de7e86SMax Reitz             .name = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
67305de7e86SMax Reitz             .type = QEMU_OPT_BOOL,
67405de7e86SMax Reitz             .help = "Check for unintended writes into a refcount block",
67505de7e86SMax Reitz         },
67605de7e86SMax Reitz         {
67705de7e86SMax Reitz             .name = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
67805de7e86SMax Reitz             .type = QEMU_OPT_BOOL,
67905de7e86SMax Reitz             .help = "Check for unintended writes into the snapshot table",
68005de7e86SMax Reitz         },
68105de7e86SMax Reitz         {
68205de7e86SMax Reitz             .name = QCOW2_OPT_OVERLAP_INACTIVE_L1,
68305de7e86SMax Reitz             .type = QEMU_OPT_BOOL,
68405de7e86SMax Reitz             .help = "Check for unintended writes into an inactive L1 table",
68505de7e86SMax Reitz         },
68605de7e86SMax Reitz         {
68705de7e86SMax Reitz             .name = QCOW2_OPT_OVERLAP_INACTIVE_L2,
68805de7e86SMax Reitz             .type = QEMU_OPT_BOOL,
68905de7e86SMax Reitz             .help = "Check for unintended writes into an inactive L2 table",
69005de7e86SMax Reitz         },
6916c1c8d5dSMax Reitz         {
6920e4e4318SVladimir Sementsov-Ogievskiy             .name = QCOW2_OPT_OVERLAP_BITMAP_DIRECTORY,
6930e4e4318SVladimir Sementsov-Ogievskiy             .type = QEMU_OPT_BOOL,
6940e4e4318SVladimir Sementsov-Ogievskiy             .help = "Check for unintended writes into the bitmap directory",
6950e4e4318SVladimir Sementsov-Ogievskiy         },
6960e4e4318SVladimir Sementsov-Ogievskiy         {
6976c1c8d5dSMax Reitz             .name = QCOW2_OPT_CACHE_SIZE,
6986c1c8d5dSMax Reitz             .type = QEMU_OPT_SIZE,
6996c1c8d5dSMax Reitz             .help = "Maximum combined metadata (L2 tables and refcount blocks) "
7006c1c8d5dSMax Reitz                     "cache size",
7016c1c8d5dSMax Reitz         },
7026c1c8d5dSMax Reitz         {
7036c1c8d5dSMax Reitz             .name = QCOW2_OPT_L2_CACHE_SIZE,
7046c1c8d5dSMax Reitz             .type = QEMU_OPT_SIZE,
7056c1c8d5dSMax Reitz             .help = "Maximum L2 table cache size",
7066c1c8d5dSMax Reitz         },
7076c1c8d5dSMax Reitz         {
7081221fe6fSAlberto Garcia             .name = QCOW2_OPT_L2_CACHE_ENTRY_SIZE,
7091221fe6fSAlberto Garcia             .type = QEMU_OPT_SIZE,
7101221fe6fSAlberto Garcia             .help = "Size of each entry in the L2 cache",
7111221fe6fSAlberto Garcia         },
7121221fe6fSAlberto Garcia         {
7136c1c8d5dSMax Reitz             .name = QCOW2_OPT_REFCOUNT_CACHE_SIZE,
7146c1c8d5dSMax Reitz             .type = QEMU_OPT_SIZE,
7156c1c8d5dSMax Reitz             .help = "Maximum refcount block cache size",
7166c1c8d5dSMax Reitz         },
717279621c0SAlberto Garcia         {
718279621c0SAlberto Garcia             .name = QCOW2_OPT_CACHE_CLEAN_INTERVAL,
719279621c0SAlberto Garcia             .type = QEMU_OPT_NUMBER,
720279621c0SAlberto Garcia             .help = "Clean unused cache entries after this time (in seconds)",
721279621c0SAlberto Garcia         },
7224652b8f3SDaniel P. Berrange         BLOCK_CRYPTO_OPT_DEF_KEY_SECRET("encrypt.",
7234652b8f3SDaniel P. Berrange             "ID of secret providing qcow2 AES key or LUKS passphrase"),
72474c4510aSKevin Wolf         { /* end of list */ }
72574c4510aSKevin Wolf     },
72674c4510aSKevin Wolf };
72774c4510aSKevin Wolf 
7284092e99dSMax Reitz static const char *overlap_bool_option_names[QCOW2_OL_MAX_BITNR] = {
7294092e99dSMax Reitz     [QCOW2_OL_MAIN_HEADER_BITNR]      = QCOW2_OPT_OVERLAP_MAIN_HEADER,
7304092e99dSMax Reitz     [QCOW2_OL_ACTIVE_L1_BITNR]        = QCOW2_OPT_OVERLAP_ACTIVE_L1,
7314092e99dSMax Reitz     [QCOW2_OL_ACTIVE_L2_BITNR]        = QCOW2_OPT_OVERLAP_ACTIVE_L2,
7324092e99dSMax Reitz     [QCOW2_OL_REFCOUNT_TABLE_BITNR]   = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
7334092e99dSMax Reitz     [QCOW2_OL_REFCOUNT_BLOCK_BITNR]   = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
7344092e99dSMax Reitz     [QCOW2_OL_SNAPSHOT_TABLE_BITNR]   = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
7354092e99dSMax Reitz     [QCOW2_OL_INACTIVE_L1_BITNR]      = QCOW2_OPT_OVERLAP_INACTIVE_L1,
7364092e99dSMax Reitz     [QCOW2_OL_INACTIVE_L2_BITNR]      = QCOW2_OPT_OVERLAP_INACTIVE_L2,
7370e4e4318SVladimir Sementsov-Ogievskiy     [QCOW2_OL_BITMAP_DIRECTORY_BITNR] = QCOW2_OPT_OVERLAP_BITMAP_DIRECTORY,
7384092e99dSMax Reitz };
7394092e99dSMax Reitz 
740279621c0SAlberto Garcia static void cache_clean_timer_cb(void *opaque)
741279621c0SAlberto Garcia {
742279621c0SAlberto Garcia     BlockDriverState *bs = opaque;
743ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
744b2f68bffSAlberto Garcia     qcow2_cache_clean_unused(s->l2_table_cache);
745b2f68bffSAlberto Garcia     qcow2_cache_clean_unused(s->refcount_block_cache);
746279621c0SAlberto Garcia     timer_mod(s->cache_clean_timer, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) +
747279621c0SAlberto Garcia               (int64_t) s->cache_clean_interval * 1000);
748279621c0SAlberto Garcia }
749279621c0SAlberto Garcia 
750279621c0SAlberto Garcia static void cache_clean_timer_init(BlockDriverState *bs, AioContext *context)
751279621c0SAlberto Garcia {
752ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
753279621c0SAlberto Garcia     if (s->cache_clean_interval > 0) {
754279621c0SAlberto Garcia         s->cache_clean_timer = aio_timer_new(context, QEMU_CLOCK_VIRTUAL,
755279621c0SAlberto Garcia                                              SCALE_MS, cache_clean_timer_cb,
756279621c0SAlberto Garcia                                              bs);
757279621c0SAlberto Garcia         timer_mod(s->cache_clean_timer, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) +
758279621c0SAlberto Garcia                   (int64_t) s->cache_clean_interval * 1000);
759279621c0SAlberto Garcia     }
760279621c0SAlberto Garcia }
761279621c0SAlberto Garcia 
762279621c0SAlberto Garcia static void cache_clean_timer_del(BlockDriverState *bs)
763279621c0SAlberto Garcia {
764ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
765279621c0SAlberto Garcia     if (s->cache_clean_timer) {
766279621c0SAlberto Garcia         timer_del(s->cache_clean_timer);
767279621c0SAlberto Garcia         timer_free(s->cache_clean_timer);
768279621c0SAlberto Garcia         s->cache_clean_timer = NULL;
769279621c0SAlberto Garcia     }
770279621c0SAlberto Garcia }
771279621c0SAlberto Garcia 
772279621c0SAlberto Garcia static void qcow2_detach_aio_context(BlockDriverState *bs)
773279621c0SAlberto Garcia {
774279621c0SAlberto Garcia     cache_clean_timer_del(bs);
775279621c0SAlberto Garcia }
776279621c0SAlberto Garcia 
777279621c0SAlberto Garcia static void qcow2_attach_aio_context(BlockDriverState *bs,
778279621c0SAlberto Garcia                                      AioContext *new_context)
779279621c0SAlberto Garcia {
780279621c0SAlberto Garcia     cache_clean_timer_init(bs, new_context);
781279621c0SAlberto Garcia }
782279621c0SAlberto Garcia 
783bc85ef26SMax Reitz static void read_cache_sizes(BlockDriverState *bs, QemuOpts *opts,
784bc85ef26SMax Reitz                              uint64_t *l2_cache_size,
7851221fe6fSAlberto Garcia                              uint64_t *l2_cache_entry_size,
7866c1c8d5dSMax Reitz                              uint64_t *refcount_cache_size, Error **errp)
7876c1c8d5dSMax Reitz {
788ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
789b749562dSLeonid Bloch     uint64_t combined_cache_size, l2_cache_max_setting;
7906c1c8d5dSMax Reitz     bool l2_cache_size_set, refcount_cache_size_set, combined_cache_size_set;
7917af5eea9SAlberto Garcia     int min_refcount_cache = MIN_REFCOUNT_CACHE_SIZE * s->cluster_size;
792b749562dSLeonid Bloch     uint64_t virtual_disk_size = bs->total_sectors * BDRV_SECTOR_SIZE;
793b749562dSLeonid Bloch     uint64_t max_l2_cache = virtual_disk_size / (s->cluster_size / 8);
7946c1c8d5dSMax Reitz 
7956c1c8d5dSMax Reitz     combined_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_CACHE_SIZE);
7966c1c8d5dSMax Reitz     l2_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_L2_CACHE_SIZE);
7976c1c8d5dSMax Reitz     refcount_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
7986c1c8d5dSMax Reitz 
7996c1c8d5dSMax Reitz     combined_cache_size = qemu_opt_get_size(opts, QCOW2_OPT_CACHE_SIZE, 0);
800b749562dSLeonid Bloch     l2_cache_max_setting = qemu_opt_get_size(opts, QCOW2_OPT_L2_CACHE_SIZE,
801b749562dSLeonid Bloch                                              DEFAULT_L2_CACHE_MAX_SIZE);
8026c1c8d5dSMax Reitz     *refcount_cache_size = qemu_opt_get_size(opts,
8036c1c8d5dSMax Reitz                                              QCOW2_OPT_REFCOUNT_CACHE_SIZE, 0);
8046c1c8d5dSMax Reitz 
8051221fe6fSAlberto Garcia     *l2_cache_entry_size = qemu_opt_get_size(
8061221fe6fSAlberto Garcia         opts, QCOW2_OPT_L2_CACHE_ENTRY_SIZE, s->cluster_size);
8071221fe6fSAlberto Garcia 
808b749562dSLeonid Bloch     *l2_cache_size = MIN(max_l2_cache, l2_cache_max_setting);
809b749562dSLeonid Bloch 
8106c1c8d5dSMax Reitz     if (combined_cache_size_set) {
8116c1c8d5dSMax Reitz         if (l2_cache_size_set && refcount_cache_size_set) {
8126c1c8d5dSMax Reitz             error_setg(errp, QCOW2_OPT_CACHE_SIZE ", " QCOW2_OPT_L2_CACHE_SIZE
8136c1c8d5dSMax Reitz                        " and " QCOW2_OPT_REFCOUNT_CACHE_SIZE " may not be set "
814308999e9SLeonid Bloch                        "at the same time");
8156c1c8d5dSMax Reitz             return;
816b749562dSLeonid Bloch         } else if (l2_cache_size_set &&
817b749562dSLeonid Bloch                    (l2_cache_max_setting > combined_cache_size)) {
8186c1c8d5dSMax Reitz             error_setg(errp, QCOW2_OPT_L2_CACHE_SIZE " may not exceed "
8196c1c8d5dSMax Reitz                        QCOW2_OPT_CACHE_SIZE);
8206c1c8d5dSMax Reitz             return;
8216c1c8d5dSMax Reitz         } else if (*refcount_cache_size > combined_cache_size) {
8226c1c8d5dSMax Reitz             error_setg(errp, QCOW2_OPT_REFCOUNT_CACHE_SIZE " may not exceed "
8236c1c8d5dSMax Reitz                        QCOW2_OPT_CACHE_SIZE);
8246c1c8d5dSMax Reitz             return;
8256c1c8d5dSMax Reitz         }
8266c1c8d5dSMax Reitz 
8276c1c8d5dSMax Reitz         if (l2_cache_size_set) {
8286c1c8d5dSMax Reitz             *refcount_cache_size = combined_cache_size - *l2_cache_size;
8296c1c8d5dSMax Reitz         } else if (refcount_cache_size_set) {
8306c1c8d5dSMax Reitz             *l2_cache_size = combined_cache_size - *refcount_cache_size;
8316c1c8d5dSMax Reitz         } else {
83252253998SAlberto Garcia             /* Assign as much memory as possible to the L2 cache, and
83352253998SAlberto Garcia              * use the remainder for the refcount cache */
83452253998SAlberto Garcia             if (combined_cache_size >= max_l2_cache + min_refcount_cache) {
83552253998SAlberto Garcia                 *l2_cache_size = max_l2_cache;
83652253998SAlberto Garcia                 *refcount_cache_size = combined_cache_size - *l2_cache_size;
83752253998SAlberto Garcia             } else {
83852253998SAlberto Garcia                 *refcount_cache_size =
83952253998SAlberto Garcia                     MIN(combined_cache_size, min_refcount_cache);
8406c1c8d5dSMax Reitz                 *l2_cache_size = combined_cache_size - *refcount_cache_size;
8416c1c8d5dSMax Reitz             }
84252253998SAlberto Garcia         }
8436c1c8d5dSMax Reitz     }
844657ada52SLeonid Bloch     /* l2_cache_size and refcount_cache_size are ensured to have at least
845657ada52SLeonid Bloch      * their minimum values in qcow2_update_options_prepare() */
8461221fe6fSAlberto Garcia 
8471221fe6fSAlberto Garcia     if (*l2_cache_entry_size < (1 << MIN_CLUSTER_BITS) ||
8481221fe6fSAlberto Garcia         *l2_cache_entry_size > s->cluster_size ||
8491221fe6fSAlberto Garcia         !is_power_of_2(*l2_cache_entry_size)) {
8501221fe6fSAlberto Garcia         error_setg(errp, "L2 cache entry size must be a power of two "
8511221fe6fSAlberto Garcia                    "between %d and the cluster size (%d)",
8521221fe6fSAlberto Garcia                    1 << MIN_CLUSTER_BITS, s->cluster_size);
8531221fe6fSAlberto Garcia         return;
8541221fe6fSAlberto Garcia     }
8556c1c8d5dSMax Reitz }
8566c1c8d5dSMax Reitz 
857ee55b173SKevin Wolf typedef struct Qcow2ReopenState {
858ee55b173SKevin Wolf     Qcow2Cache *l2_table_cache;
859ee55b173SKevin Wolf     Qcow2Cache *refcount_block_cache;
8603c2e511aSAlberto Garcia     int l2_slice_size; /* Number of entries in a slice of the L2 table */
861ee55b173SKevin Wolf     bool use_lazy_refcounts;
862ee55b173SKevin Wolf     int overlap_check;
863ee55b173SKevin Wolf     bool discard_passthrough[QCOW2_DISCARD_MAX];
864ee55b173SKevin Wolf     uint64_t cache_clean_interval;
865b25b387fSDaniel P. Berrange     QCryptoBlockOpenOptions *crypto_opts; /* Disk encryption runtime options */
866ee55b173SKevin Wolf } Qcow2ReopenState;
867ee55b173SKevin Wolf 
868ee55b173SKevin Wolf static int qcow2_update_options_prepare(BlockDriverState *bs,
869ee55b173SKevin Wolf                                         Qcow2ReopenState *r,
870ee55b173SKevin Wolf                                         QDict *options, int flags,
871ee55b173SKevin Wolf                                         Error **errp)
8724c75d1a1SKevin Wolf {
8734c75d1a1SKevin Wolf     BDRVQcow2State *s = bs->opaque;
87494edf3fbSKevin Wolf     QemuOpts *opts = NULL;
8754c75d1a1SKevin Wolf     const char *opt_overlap_check, *opt_overlap_check_template;
8764c75d1a1SKevin Wolf     int overlap_check_template = 0;
8771221fe6fSAlberto Garcia     uint64_t l2_cache_size, l2_cache_entry_size, refcount_cache_size;
8784c75d1a1SKevin Wolf     int i;
879b25b387fSDaniel P. Berrange     const char *encryptfmt;
880b25b387fSDaniel P. Berrange     QDict *encryptopts = NULL;
88194edf3fbSKevin Wolf     Error *local_err = NULL;
8824c75d1a1SKevin Wolf     int ret;
8834c75d1a1SKevin Wolf 
884b25b387fSDaniel P. Berrange     qdict_extract_subqdict(options, &encryptopts, "encrypt.");
885b25b387fSDaniel P. Berrange     encryptfmt = qdict_get_try_str(encryptopts, "format");
886b25b387fSDaniel P. Berrange 
88794edf3fbSKevin Wolf     opts = qemu_opts_create(&qcow2_runtime_opts, NULL, 0, &error_abort);
88894edf3fbSKevin Wolf     qemu_opts_absorb_qdict(opts, options, &local_err);
88994edf3fbSKevin Wolf     if (local_err) {
89094edf3fbSKevin Wolf         error_propagate(errp, local_err);
89194edf3fbSKevin Wolf         ret = -EINVAL;
89294edf3fbSKevin Wolf         goto fail;
89394edf3fbSKevin Wolf     }
89494edf3fbSKevin Wolf 
89594edf3fbSKevin Wolf     /* get L2 table/refcount block cache size from command line options */
8961221fe6fSAlberto Garcia     read_cache_sizes(bs, opts, &l2_cache_size, &l2_cache_entry_size,
8971221fe6fSAlberto Garcia                      &refcount_cache_size, &local_err);
89894edf3fbSKevin Wolf     if (local_err) {
89994edf3fbSKevin Wolf         error_propagate(errp, local_err);
90094edf3fbSKevin Wolf         ret = -EINVAL;
90194edf3fbSKevin Wolf         goto fail;
90294edf3fbSKevin Wolf     }
90394edf3fbSKevin Wolf 
9041221fe6fSAlberto Garcia     l2_cache_size /= l2_cache_entry_size;
90594edf3fbSKevin Wolf     if (l2_cache_size < MIN_L2_CACHE_SIZE) {
90694edf3fbSKevin Wolf         l2_cache_size = MIN_L2_CACHE_SIZE;
90794edf3fbSKevin Wolf     }
90894edf3fbSKevin Wolf     if (l2_cache_size > INT_MAX) {
90994edf3fbSKevin Wolf         error_setg(errp, "L2 cache size too big");
91094edf3fbSKevin Wolf         ret = -EINVAL;
91194edf3fbSKevin Wolf         goto fail;
91294edf3fbSKevin Wolf     }
91394edf3fbSKevin Wolf 
91494edf3fbSKevin Wolf     refcount_cache_size /= s->cluster_size;
91594edf3fbSKevin Wolf     if (refcount_cache_size < MIN_REFCOUNT_CACHE_SIZE) {
91694edf3fbSKevin Wolf         refcount_cache_size = MIN_REFCOUNT_CACHE_SIZE;
91794edf3fbSKevin Wolf     }
91894edf3fbSKevin Wolf     if (refcount_cache_size > INT_MAX) {
91994edf3fbSKevin Wolf         error_setg(errp, "Refcount cache size too big");
92094edf3fbSKevin Wolf         ret = -EINVAL;
92194edf3fbSKevin Wolf         goto fail;
92294edf3fbSKevin Wolf     }
92394edf3fbSKevin Wolf 
9245b0959a7SKevin Wolf     /* alloc new L2 table/refcount block cache, flush old one */
9255b0959a7SKevin Wolf     if (s->l2_table_cache) {
9265b0959a7SKevin Wolf         ret = qcow2_cache_flush(bs, s->l2_table_cache);
9275b0959a7SKevin Wolf         if (ret) {
9285b0959a7SKevin Wolf             error_setg_errno(errp, -ret, "Failed to flush the L2 table cache");
9295b0959a7SKevin Wolf             goto fail;
9305b0959a7SKevin Wolf         }
9315b0959a7SKevin Wolf     }
9325b0959a7SKevin Wolf 
9335b0959a7SKevin Wolf     if (s->refcount_block_cache) {
9345b0959a7SKevin Wolf         ret = qcow2_cache_flush(bs, s->refcount_block_cache);
9355b0959a7SKevin Wolf         if (ret) {
9365b0959a7SKevin Wolf             error_setg_errno(errp, -ret,
9375b0959a7SKevin Wolf                              "Failed to flush the refcount block cache");
9385b0959a7SKevin Wolf             goto fail;
9395b0959a7SKevin Wolf         }
9405b0959a7SKevin Wolf     }
9415b0959a7SKevin Wolf 
9421221fe6fSAlberto Garcia     r->l2_slice_size = l2_cache_entry_size / sizeof(uint64_t);
9431221fe6fSAlberto Garcia     r->l2_table_cache = qcow2_cache_create(bs, l2_cache_size,
9441221fe6fSAlberto Garcia                                            l2_cache_entry_size);
9451221fe6fSAlberto Garcia     r->refcount_block_cache = qcow2_cache_create(bs, refcount_cache_size,
9461221fe6fSAlberto Garcia                                                  s->cluster_size);
947ee55b173SKevin Wolf     if (r->l2_table_cache == NULL || r->refcount_block_cache == NULL) {
94894edf3fbSKevin Wolf         error_setg(errp, "Could not allocate metadata caches");
94994edf3fbSKevin Wolf         ret = -ENOMEM;
95094edf3fbSKevin Wolf         goto fail;
95194edf3fbSKevin Wolf     }
95294edf3fbSKevin Wolf 
95394edf3fbSKevin Wolf     /* New interval for cache cleanup timer */
954ee55b173SKevin Wolf     r->cache_clean_interval =
9555b0959a7SKevin Wolf         qemu_opt_get_number(opts, QCOW2_OPT_CACHE_CLEAN_INTERVAL,
956e957b50bSLeonid Bloch                             DEFAULT_CACHE_CLEAN_INTERVAL);
95791203f08SAlberto Garcia #ifndef CONFIG_LINUX
95891203f08SAlberto Garcia     if (r->cache_clean_interval != 0) {
95991203f08SAlberto Garcia         error_setg(errp, QCOW2_OPT_CACHE_CLEAN_INTERVAL
96091203f08SAlberto Garcia                    " not supported on this host");
96191203f08SAlberto Garcia         ret = -EINVAL;
96291203f08SAlberto Garcia         goto fail;
96391203f08SAlberto Garcia     }
96491203f08SAlberto Garcia #endif
965ee55b173SKevin Wolf     if (r->cache_clean_interval > UINT_MAX) {
96694edf3fbSKevin Wolf         error_setg(errp, "Cache clean interval too big");
96794edf3fbSKevin Wolf         ret = -EINVAL;
96894edf3fbSKevin Wolf         goto fail;
96994edf3fbSKevin Wolf     }
97094edf3fbSKevin Wolf 
9715b0959a7SKevin Wolf     /* lazy-refcounts; flush if going from enabled to disabled */
972ee55b173SKevin Wolf     r->use_lazy_refcounts = qemu_opt_get_bool(opts, QCOW2_OPT_LAZY_REFCOUNTS,
9734c75d1a1SKevin Wolf         (s->compatible_features & QCOW2_COMPAT_LAZY_REFCOUNTS));
974ee55b173SKevin Wolf     if (r->use_lazy_refcounts && s->qcow_version < 3) {
975007dbc39SKevin Wolf         error_setg(errp, "Lazy refcounts require a qcow2 image with at least "
976007dbc39SKevin Wolf                    "qemu 1.1 compatibility level");
977007dbc39SKevin Wolf         ret = -EINVAL;
978007dbc39SKevin Wolf         goto fail;
979007dbc39SKevin Wolf     }
9804c75d1a1SKevin Wolf 
9815b0959a7SKevin Wolf     if (s->use_lazy_refcounts && !r->use_lazy_refcounts) {
9825b0959a7SKevin Wolf         ret = qcow2_mark_clean(bs);
9835b0959a7SKevin Wolf         if (ret < 0) {
9845b0959a7SKevin Wolf             error_setg_errno(errp, -ret, "Failed to disable lazy refcounts");
9855b0959a7SKevin Wolf             goto fail;
9865b0959a7SKevin Wolf         }
9875b0959a7SKevin Wolf     }
9885b0959a7SKevin Wolf 
989007dbc39SKevin Wolf     /* Overlap check options */
9904c75d1a1SKevin Wolf     opt_overlap_check = qemu_opt_get(opts, QCOW2_OPT_OVERLAP);
9914c75d1a1SKevin Wolf     opt_overlap_check_template = qemu_opt_get(opts, QCOW2_OPT_OVERLAP_TEMPLATE);
9924c75d1a1SKevin Wolf     if (opt_overlap_check_template && opt_overlap_check &&
9934c75d1a1SKevin Wolf         strcmp(opt_overlap_check_template, opt_overlap_check))
9944c75d1a1SKevin Wolf     {
9954c75d1a1SKevin Wolf         error_setg(errp, "Conflicting values for qcow2 options '"
9964c75d1a1SKevin Wolf                    QCOW2_OPT_OVERLAP "' ('%s') and '" QCOW2_OPT_OVERLAP_TEMPLATE
9974c75d1a1SKevin Wolf                    "' ('%s')", opt_overlap_check, opt_overlap_check_template);
9984c75d1a1SKevin Wolf         ret = -EINVAL;
9994c75d1a1SKevin Wolf         goto fail;
10004c75d1a1SKevin Wolf     }
10014c75d1a1SKevin Wolf     if (!opt_overlap_check) {
10024c75d1a1SKevin Wolf         opt_overlap_check = opt_overlap_check_template ?: "cached";
10034c75d1a1SKevin Wolf     }
10044c75d1a1SKevin Wolf 
10054c75d1a1SKevin Wolf     if (!strcmp(opt_overlap_check, "none")) {
10064c75d1a1SKevin Wolf         overlap_check_template = 0;
10074c75d1a1SKevin Wolf     } else if (!strcmp(opt_overlap_check, "constant")) {
10084c75d1a1SKevin Wolf         overlap_check_template = QCOW2_OL_CONSTANT;
10094c75d1a1SKevin Wolf     } else if (!strcmp(opt_overlap_check, "cached")) {
10104c75d1a1SKevin Wolf         overlap_check_template = QCOW2_OL_CACHED;
10114c75d1a1SKevin Wolf     } else if (!strcmp(opt_overlap_check, "all")) {
10124c75d1a1SKevin Wolf         overlap_check_template = QCOW2_OL_ALL;
10134c75d1a1SKevin Wolf     } else {
10144c75d1a1SKevin Wolf         error_setg(errp, "Unsupported value '%s' for qcow2 option "
10154c75d1a1SKevin Wolf                    "'overlap-check'. Allowed are any of the following: "
10164c75d1a1SKevin Wolf                    "none, constant, cached, all", opt_overlap_check);
10174c75d1a1SKevin Wolf         ret = -EINVAL;
10184c75d1a1SKevin Wolf         goto fail;
10194c75d1a1SKevin Wolf     }
10204c75d1a1SKevin Wolf 
1021ee55b173SKevin Wolf     r->overlap_check = 0;
10224c75d1a1SKevin Wolf     for (i = 0; i < QCOW2_OL_MAX_BITNR; i++) {
10234c75d1a1SKevin Wolf         /* overlap-check defines a template bitmask, but every flag may be
10244c75d1a1SKevin Wolf          * overwritten through the associated boolean option */
1025ee55b173SKevin Wolf         r->overlap_check |=
10264c75d1a1SKevin Wolf             qemu_opt_get_bool(opts, overlap_bool_option_names[i],
10274c75d1a1SKevin Wolf                               overlap_check_template & (1 << i)) << i;
10284c75d1a1SKevin Wolf     }
10294c75d1a1SKevin Wolf 
1030ee55b173SKevin Wolf     r->discard_passthrough[QCOW2_DISCARD_NEVER] = false;
1031ee55b173SKevin Wolf     r->discard_passthrough[QCOW2_DISCARD_ALWAYS] = true;
1032ee55b173SKevin Wolf     r->discard_passthrough[QCOW2_DISCARD_REQUEST] =
1033007dbc39SKevin Wolf         qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_REQUEST,
1034007dbc39SKevin Wolf                           flags & BDRV_O_UNMAP);
1035ee55b173SKevin Wolf     r->discard_passthrough[QCOW2_DISCARD_SNAPSHOT] =
1036007dbc39SKevin Wolf         qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_SNAPSHOT, true);
1037ee55b173SKevin Wolf     r->discard_passthrough[QCOW2_DISCARD_OTHER] =
1038007dbc39SKevin Wolf         qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_OTHER, false);
1039007dbc39SKevin Wolf 
1040b25b387fSDaniel P. Berrange     switch (s->crypt_method_header) {
1041b25b387fSDaniel P. Berrange     case QCOW_CRYPT_NONE:
1042b25b387fSDaniel P. Berrange         if (encryptfmt) {
1043b25b387fSDaniel P. Berrange             error_setg(errp, "No encryption in image header, but options "
1044b25b387fSDaniel P. Berrange                        "specified format '%s'", encryptfmt);
1045b25b387fSDaniel P. Berrange             ret = -EINVAL;
1046b25b387fSDaniel P. Berrange             goto fail;
1047b25b387fSDaniel P. Berrange         }
1048b25b387fSDaniel P. Berrange         break;
1049b25b387fSDaniel P. Berrange 
1050b25b387fSDaniel P. Berrange     case QCOW_CRYPT_AES:
1051b25b387fSDaniel P. Berrange         if (encryptfmt && !g_str_equal(encryptfmt, "aes")) {
1052b25b387fSDaniel P. Berrange             error_setg(errp,
1053b25b387fSDaniel P. Berrange                        "Header reported 'aes' encryption format but "
1054b25b387fSDaniel P. Berrange                        "options specify '%s'", encryptfmt);
1055b25b387fSDaniel P. Berrange             ret = -EINVAL;
1056b25b387fSDaniel P. Berrange             goto fail;
1057b25b387fSDaniel P. Berrange         }
1058796d3239SMarkus Armbruster         qdict_put_str(encryptopts, "format", "qcow");
1059796d3239SMarkus Armbruster         r->crypto_opts = block_crypto_open_opts_init(encryptopts, errp);
1060b25b387fSDaniel P. Berrange         break;
1061b25b387fSDaniel P. Berrange 
10624652b8f3SDaniel P. Berrange     case QCOW_CRYPT_LUKS:
10634652b8f3SDaniel P. Berrange         if (encryptfmt && !g_str_equal(encryptfmt, "luks")) {
10644652b8f3SDaniel P. Berrange             error_setg(errp,
10654652b8f3SDaniel P. Berrange                        "Header reported 'luks' encryption format but "
10664652b8f3SDaniel P. Berrange                        "options specify '%s'", encryptfmt);
10674652b8f3SDaniel P. Berrange             ret = -EINVAL;
10684652b8f3SDaniel P. Berrange             goto fail;
10694652b8f3SDaniel P. Berrange         }
1070796d3239SMarkus Armbruster         qdict_put_str(encryptopts, "format", "luks");
1071796d3239SMarkus Armbruster         r->crypto_opts = block_crypto_open_opts_init(encryptopts, errp);
10724652b8f3SDaniel P. Berrange         break;
10734652b8f3SDaniel P. Berrange 
1074b25b387fSDaniel P. Berrange     default:
1075b25b387fSDaniel P. Berrange         error_setg(errp, "Unsupported encryption method %d",
1076b25b387fSDaniel P. Berrange                    s->crypt_method_header);
1077b25b387fSDaniel P. Berrange         break;
1078b25b387fSDaniel P. Berrange     }
1079b25b387fSDaniel P. Berrange     if (s->crypt_method_header != QCOW_CRYPT_NONE && !r->crypto_opts) {
1080b25b387fSDaniel P. Berrange         ret = -EINVAL;
1081b25b387fSDaniel P. Berrange         goto fail;
1082b25b387fSDaniel P. Berrange     }
1083b25b387fSDaniel P. Berrange 
10844c75d1a1SKevin Wolf     ret = 0;
10854c75d1a1SKevin Wolf fail:
1086cb3e7f08SMarc-André Lureau     qobject_unref(encryptopts);
108794edf3fbSKevin Wolf     qemu_opts_del(opts);
108894edf3fbSKevin Wolf     opts = NULL;
1089ee55b173SKevin Wolf     return ret;
1090ee55b173SKevin Wolf }
1091ee55b173SKevin Wolf 
1092ee55b173SKevin Wolf static void qcow2_update_options_commit(BlockDriverState *bs,
1093ee55b173SKevin Wolf                                         Qcow2ReopenState *r)
1094ee55b173SKevin Wolf {
1095ee55b173SKevin Wolf     BDRVQcow2State *s = bs->opaque;
1096ee55b173SKevin Wolf     int i;
1097ee55b173SKevin Wolf 
10985b0959a7SKevin Wolf     if (s->l2_table_cache) {
1099e64d4072SAlberto Garcia         qcow2_cache_destroy(s->l2_table_cache);
11005b0959a7SKevin Wolf     }
11015b0959a7SKevin Wolf     if (s->refcount_block_cache) {
1102e64d4072SAlberto Garcia         qcow2_cache_destroy(s->refcount_block_cache);
11035b0959a7SKevin Wolf     }
1104ee55b173SKevin Wolf     s->l2_table_cache = r->l2_table_cache;
1105ee55b173SKevin Wolf     s->refcount_block_cache = r->refcount_block_cache;
11063c2e511aSAlberto Garcia     s->l2_slice_size = r->l2_slice_size;
1107ee55b173SKevin Wolf 
1108ee55b173SKevin Wolf     s->overlap_check = r->overlap_check;
1109ee55b173SKevin Wolf     s->use_lazy_refcounts = r->use_lazy_refcounts;
1110ee55b173SKevin Wolf 
1111ee55b173SKevin Wolf     for (i = 0; i < QCOW2_DISCARD_MAX; i++) {
1112ee55b173SKevin Wolf         s->discard_passthrough[i] = r->discard_passthrough[i];
1113ee55b173SKevin Wolf     }
1114ee55b173SKevin Wolf 
11155b0959a7SKevin Wolf     if (s->cache_clean_interval != r->cache_clean_interval) {
11165b0959a7SKevin Wolf         cache_clean_timer_del(bs);
1117ee55b173SKevin Wolf         s->cache_clean_interval = r->cache_clean_interval;
1118ee55b173SKevin Wolf         cache_clean_timer_init(bs, bdrv_get_aio_context(bs));
1119ee55b173SKevin Wolf     }
1120b25b387fSDaniel P. Berrange 
1121b25b387fSDaniel P. Berrange     qapi_free_QCryptoBlockOpenOptions(s->crypto_opts);
1122b25b387fSDaniel P. Berrange     s->crypto_opts = r->crypto_opts;
11235b0959a7SKevin Wolf }
1124ee55b173SKevin Wolf 
1125ee55b173SKevin Wolf static void qcow2_update_options_abort(BlockDriverState *bs,
1126ee55b173SKevin Wolf                                        Qcow2ReopenState *r)
1127ee55b173SKevin Wolf {
1128ee55b173SKevin Wolf     if (r->l2_table_cache) {
1129e64d4072SAlberto Garcia         qcow2_cache_destroy(r->l2_table_cache);
1130ee55b173SKevin Wolf     }
1131ee55b173SKevin Wolf     if (r->refcount_block_cache) {
1132e64d4072SAlberto Garcia         qcow2_cache_destroy(r->refcount_block_cache);
1133ee55b173SKevin Wolf     }
1134b25b387fSDaniel P. Berrange     qapi_free_QCryptoBlockOpenOptions(r->crypto_opts);
1135ee55b173SKevin Wolf }
1136ee55b173SKevin Wolf 
1137ee55b173SKevin Wolf static int qcow2_update_options(BlockDriverState *bs, QDict *options,
1138ee55b173SKevin Wolf                                 int flags, Error **errp)
1139ee55b173SKevin Wolf {
1140ee55b173SKevin Wolf     Qcow2ReopenState r = {};
1141ee55b173SKevin Wolf     int ret;
1142ee55b173SKevin Wolf 
1143ee55b173SKevin Wolf     ret = qcow2_update_options_prepare(bs, &r, options, flags, errp);
1144ee55b173SKevin Wolf     if (ret >= 0) {
1145ee55b173SKevin Wolf         qcow2_update_options_commit(bs, &r);
1146ee55b173SKevin Wolf     } else {
1147ee55b173SKevin Wolf         qcow2_update_options_abort(bs, &r);
1148ee55b173SKevin Wolf     }
114994edf3fbSKevin Wolf 
11504c75d1a1SKevin Wolf     return ret;
11514c75d1a1SKevin Wolf }
11524c75d1a1SKevin Wolf 
11531fafcd93SPaolo Bonzini /* Called with s->lock held.  */
11541fafcd93SPaolo Bonzini static int coroutine_fn qcow2_do_open(BlockDriverState *bs, QDict *options,
11551fafcd93SPaolo Bonzini                                       int flags, Error **errp)
1156585f8587Sbellard {
1157ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
11586d33e8e7SKevin Wolf     unsigned int len, i;
11596d33e8e7SKevin Wolf     int ret = 0;
1160585f8587Sbellard     QCowHeader header;
116174c4510aSKevin Wolf     Error *local_err = NULL;
11629b80ddf3Saliguori     uint64_t ext_end;
11632cf7cfa1SKevin Wolf     uint64_t l1_vm_state_index;
116488ddffaeSVladimir Sementsov-Ogievskiy     bool update_header = false;
1165585f8587Sbellard 
1166cf2ab8fcSKevin Wolf     ret = bdrv_pread(bs->file, 0, &header, sizeof(header));
11676d85a57eSJes Sorensen     if (ret < 0) {
11683ef6c40aSMax Reitz         error_setg_errno(errp, -ret, "Could not read qcow2 header");
1169585f8587Sbellard         goto fail;
11706d85a57eSJes Sorensen     }
11713b698f52SPeter Maydell     header.magic = be32_to_cpu(header.magic);
11723b698f52SPeter Maydell     header.version = be32_to_cpu(header.version);
11733b698f52SPeter Maydell     header.backing_file_offset = be64_to_cpu(header.backing_file_offset);
11743b698f52SPeter Maydell     header.backing_file_size = be32_to_cpu(header.backing_file_size);
11753b698f52SPeter Maydell     header.size = be64_to_cpu(header.size);
11763b698f52SPeter Maydell     header.cluster_bits = be32_to_cpu(header.cluster_bits);
11773b698f52SPeter Maydell     header.crypt_method = be32_to_cpu(header.crypt_method);
11783b698f52SPeter Maydell     header.l1_table_offset = be64_to_cpu(header.l1_table_offset);
11793b698f52SPeter Maydell     header.l1_size = be32_to_cpu(header.l1_size);
11803b698f52SPeter Maydell     header.refcount_table_offset = be64_to_cpu(header.refcount_table_offset);
11813b698f52SPeter Maydell     header.refcount_table_clusters =
11823b698f52SPeter Maydell         be32_to_cpu(header.refcount_table_clusters);
11833b698f52SPeter Maydell     header.snapshots_offset = be64_to_cpu(header.snapshots_offset);
11843b698f52SPeter Maydell     header.nb_snapshots = be32_to_cpu(header.nb_snapshots);
1185585f8587Sbellard 
1186e8cdcec1SKevin Wolf     if (header.magic != QCOW_MAGIC) {
11873ef6c40aSMax Reitz         error_setg(errp, "Image is not in qcow2 format");
118876abe407SPaolo Bonzini         ret = -EINVAL;
1189585f8587Sbellard         goto fail;
11906d85a57eSJes Sorensen     }
11916744cbabSKevin Wolf     if (header.version < 2 || header.version > 3) {
1192a55448b3SMax Reitz         error_setg(errp, "Unsupported qcow2 version %" PRIu32, header.version);
1193e8cdcec1SKevin Wolf         ret = -ENOTSUP;
1194e8cdcec1SKevin Wolf         goto fail;
1195e8cdcec1SKevin Wolf     }
11966744cbabSKevin Wolf 
11976744cbabSKevin Wolf     s->qcow_version = header.version;
11986744cbabSKevin Wolf 
119924342f2cSKevin Wolf     /* Initialise cluster size */
120024342f2cSKevin Wolf     if (header.cluster_bits < MIN_CLUSTER_BITS ||
120124342f2cSKevin Wolf         header.cluster_bits > MAX_CLUSTER_BITS) {
1202521b2b5dSMax Reitz         error_setg(errp, "Unsupported cluster size: 2^%" PRIu32,
1203521b2b5dSMax Reitz                    header.cluster_bits);
120424342f2cSKevin Wolf         ret = -EINVAL;
120524342f2cSKevin Wolf         goto fail;
120624342f2cSKevin Wolf     }
120724342f2cSKevin Wolf 
120824342f2cSKevin Wolf     s->cluster_bits = header.cluster_bits;
120924342f2cSKevin Wolf     s->cluster_size = 1 << s->cluster_bits;
1210a35f87f5SAlberto Garcia     s->cluster_sectors = 1 << (s->cluster_bits - BDRV_SECTOR_BITS);
121124342f2cSKevin Wolf 
12126744cbabSKevin Wolf     /* Initialise version 3 header fields */
12136744cbabSKevin Wolf     if (header.version == 2) {
12146744cbabSKevin Wolf         header.incompatible_features    = 0;
12156744cbabSKevin Wolf         header.compatible_features      = 0;
12166744cbabSKevin Wolf         header.autoclear_features       = 0;
12176744cbabSKevin Wolf         header.refcount_order           = 4;
12186744cbabSKevin Wolf         header.header_length            = 72;
12196744cbabSKevin Wolf     } else {
12203b698f52SPeter Maydell         header.incompatible_features =
12213b698f52SPeter Maydell             be64_to_cpu(header.incompatible_features);
12223b698f52SPeter Maydell         header.compatible_features = be64_to_cpu(header.compatible_features);
12233b698f52SPeter Maydell         header.autoclear_features = be64_to_cpu(header.autoclear_features);
12243b698f52SPeter Maydell         header.refcount_order = be32_to_cpu(header.refcount_order);
12253b698f52SPeter Maydell         header.header_length = be32_to_cpu(header.header_length);
122624342f2cSKevin Wolf 
122724342f2cSKevin Wolf         if (header.header_length < 104) {
122824342f2cSKevin Wolf             error_setg(errp, "qcow2 header too short");
122924342f2cSKevin Wolf             ret = -EINVAL;
123024342f2cSKevin Wolf             goto fail;
123124342f2cSKevin Wolf         }
123224342f2cSKevin Wolf     }
123324342f2cSKevin Wolf 
123424342f2cSKevin Wolf     if (header.header_length > s->cluster_size) {
123524342f2cSKevin Wolf         error_setg(errp, "qcow2 header exceeds cluster size");
123624342f2cSKevin Wolf         ret = -EINVAL;
123724342f2cSKevin Wolf         goto fail;
12386744cbabSKevin Wolf     }
12396744cbabSKevin Wolf 
12406744cbabSKevin Wolf     if (header.header_length > sizeof(header)) {
12416744cbabSKevin Wolf         s->unknown_header_fields_size = header.header_length - sizeof(header);
12426744cbabSKevin Wolf         s->unknown_header_fields = g_malloc(s->unknown_header_fields_size);
1243cf2ab8fcSKevin Wolf         ret = bdrv_pread(bs->file, sizeof(header), s->unknown_header_fields,
12446744cbabSKevin Wolf                          s->unknown_header_fields_size);
12456744cbabSKevin Wolf         if (ret < 0) {
12463ef6c40aSMax Reitz             error_setg_errno(errp, -ret, "Could not read unknown qcow2 header "
12473ef6c40aSMax Reitz                              "fields");
12486744cbabSKevin Wolf             goto fail;
12496744cbabSKevin Wolf         }
12506744cbabSKevin Wolf     }
12516744cbabSKevin Wolf 
1252a1b3955cSKevin Wolf     if (header.backing_file_offset > s->cluster_size) {
1253a1b3955cSKevin Wolf         error_setg(errp, "Invalid backing file offset");
1254a1b3955cSKevin Wolf         ret = -EINVAL;
1255a1b3955cSKevin Wolf         goto fail;
1256a1b3955cSKevin Wolf     }
1257a1b3955cSKevin Wolf 
1258cfcc4c62SKevin Wolf     if (header.backing_file_offset) {
1259cfcc4c62SKevin Wolf         ext_end = header.backing_file_offset;
1260cfcc4c62SKevin Wolf     } else {
1261cfcc4c62SKevin Wolf         ext_end = 1 << header.cluster_bits;
1262cfcc4c62SKevin Wolf     }
1263cfcc4c62SKevin Wolf 
12646744cbabSKevin Wolf     /* Handle feature bits */
12656744cbabSKevin Wolf     s->incompatible_features    = header.incompatible_features;
12666744cbabSKevin Wolf     s->compatible_features      = header.compatible_features;
12676744cbabSKevin Wolf     s->autoclear_features       = header.autoclear_features;
12686744cbabSKevin Wolf 
1269c61d0004SStefan Hajnoczi     if (s->incompatible_features & ~QCOW2_INCOMPAT_MASK) {
1270cfcc4c62SKevin Wolf         void *feature_table = NULL;
1271cfcc4c62SKevin Wolf         qcow2_read_extensions(bs, header.header_length, ext_end,
127288ddffaeSVladimir Sementsov-Ogievskiy                               &feature_table, flags, NULL, NULL);
1273a55448b3SMax Reitz         report_unsupported_feature(errp, feature_table,
1274c61d0004SStefan Hajnoczi                                    s->incompatible_features &
1275c61d0004SStefan Hajnoczi                                    ~QCOW2_INCOMPAT_MASK);
12766744cbabSKevin Wolf         ret = -ENOTSUP;
1277c5a33ee9SPrasad Joshi         g_free(feature_table);
12786744cbabSKevin Wolf         goto fail;
12796744cbabSKevin Wolf     }
12806744cbabSKevin Wolf 
128169c98726SMax Reitz     if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
128269c98726SMax Reitz         /* Corrupt images may not be written to unless they are being repaired
128369c98726SMax Reitz          */
128469c98726SMax Reitz         if ((flags & BDRV_O_RDWR) && !(flags & BDRV_O_CHECK)) {
12853ef6c40aSMax Reitz             error_setg(errp, "qcow2: Image is corrupt; cannot be opened "
12863ef6c40aSMax Reitz                        "read/write");
128769c98726SMax Reitz             ret = -EACCES;
128869c98726SMax Reitz             goto fail;
128969c98726SMax Reitz         }
129069c98726SMax Reitz     }
129169c98726SMax Reitz 
12926744cbabSKevin Wolf     /* Check support for various header values */
1293b72faf9fSMax Reitz     if (header.refcount_order > 6) {
1294b72faf9fSMax Reitz         error_setg(errp, "Reference count entry width too large; may not "
1295b72faf9fSMax Reitz                    "exceed 64 bits");
1296b72faf9fSMax Reitz         ret = -EINVAL;
12976744cbabSKevin Wolf         goto fail;
12986744cbabSKevin Wolf     }
1299b6481f37SMax Reitz     s->refcount_order = header.refcount_order;
1300346a53dfSMax Reitz     s->refcount_bits = 1 << s->refcount_order;
1301346a53dfSMax Reitz     s->refcount_max = UINT64_C(1) << (s->refcount_bits - 1);
1302346a53dfSMax Reitz     s->refcount_max += s->refcount_max - 1;
13036744cbabSKevin Wolf 
1304585f8587Sbellard     s->crypt_method_header = header.crypt_method;
13056d85a57eSJes Sorensen     if (s->crypt_method_header) {
1306e6ff69bfSDaniel P. Berrange         if (bdrv_uses_whitelist() &&
1307e6ff69bfSDaniel P. Berrange             s->crypt_method_header == QCOW_CRYPT_AES) {
13088c0dcbc4SDaniel P. Berrange             error_setg(errp,
13098c0dcbc4SDaniel P. Berrange                        "Use of AES-CBC encrypted qcow2 images is no longer "
13108c0dcbc4SDaniel P. Berrange                        "supported in system emulators");
13118c0dcbc4SDaniel P. Berrange             error_append_hint(errp,
13128c0dcbc4SDaniel P. Berrange                               "You can use 'qemu-img convert' to convert your "
13138c0dcbc4SDaniel P. Berrange                               "image to an alternative supported format, such "
13148c0dcbc4SDaniel P. Berrange                               "as unencrypted qcow2, or raw with the LUKS "
13158c0dcbc4SDaniel P. Berrange                               "format instead.\n");
13168c0dcbc4SDaniel P. Berrange             ret = -ENOSYS;
13178c0dcbc4SDaniel P. Berrange             goto fail;
1318e6ff69bfSDaniel P. Berrange         }
1319e6ff69bfSDaniel P. Berrange 
13204652b8f3SDaniel P. Berrange         if (s->crypt_method_header == QCOW_CRYPT_AES) {
13214652b8f3SDaniel P. Berrange             s->crypt_physical_offset = false;
13224652b8f3SDaniel P. Berrange         } else {
13234652b8f3SDaniel P. Berrange             /* Assuming LUKS and any future crypt methods we
13244652b8f3SDaniel P. Berrange              * add will all use physical offsets, due to the
13254652b8f3SDaniel P. Berrange              * fact that the alternative is insecure...  */
13264652b8f3SDaniel P. Berrange             s->crypt_physical_offset = true;
13274652b8f3SDaniel P. Berrange         }
13284652b8f3SDaniel P. Berrange 
132954115412SEric Blake         bs->encrypted = true;
13306d85a57eSJes Sorensen     }
133124342f2cSKevin Wolf 
1332585f8587Sbellard     s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */
1333585f8587Sbellard     s->l2_size = 1 << s->l2_bits;
13341d13d654SMax Reitz     /* 2^(s->refcount_order - 3) is the refcount width in bytes */
13351d13d654SMax Reitz     s->refcount_block_bits = s->cluster_bits - (s->refcount_order - 3);
13361d13d654SMax Reitz     s->refcount_block_size = 1 << s->refcount_block_bits;
1337bd016b91SLeonid Bloch     bs->total_sectors = header.size / BDRV_SECTOR_SIZE;
1338585f8587Sbellard     s->csize_shift = (62 - (s->cluster_bits - 8));
1339585f8587Sbellard     s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;
1340585f8587Sbellard     s->cluster_offset_mask = (1LL << s->csize_shift) - 1;
13415dab2fadSKevin Wolf 
1342585f8587Sbellard     s->refcount_table_offset = header.refcount_table_offset;
1343585f8587Sbellard     s->refcount_table_size =
1344585f8587Sbellard         header.refcount_table_clusters << (s->cluster_bits - 3);
1345585f8587Sbellard 
1346951053a9SAlberto Garcia     if (header.refcount_table_clusters == 0 && !(flags & BDRV_O_CHECK)) {
1347951053a9SAlberto Garcia         error_setg(errp, "Image does not contain a reference count table");
1348951053a9SAlberto Garcia         ret = -EINVAL;
1349951053a9SAlberto Garcia         goto fail;
1350951053a9SAlberto Garcia     }
1351951053a9SAlberto Garcia 
13520cf0e598SAlberto Garcia     ret = qcow2_validate_table(bs, s->refcount_table_offset,
13530cf0e598SAlberto Garcia                                header.refcount_table_clusters,
13540cf0e598SAlberto Garcia                                s->cluster_size, QCOW_MAX_REFTABLE_SIZE,
13550cf0e598SAlberto Garcia                                "Reference count table", errp);
13568c7de283SKevin Wolf     if (ret < 0) {
13578c7de283SKevin Wolf         goto fail;
13588c7de283SKevin Wolf     }
13598c7de283SKevin Wolf 
13600cf0e598SAlberto Garcia     /* The total size in bytes of the snapshot table is checked in
13610cf0e598SAlberto Garcia      * qcow2_read_snapshots() because the size of each snapshot is
13620cf0e598SAlberto Garcia      * variable and we don't know it yet.
13630cf0e598SAlberto Garcia      * Here we only check the offset and number of snapshots. */
13640cf0e598SAlberto Garcia     ret = qcow2_validate_table(bs, header.snapshots_offset,
1365ce48f2f4SKevin Wolf                                header.nb_snapshots,
13660cf0e598SAlberto Garcia                                sizeof(QCowSnapshotHeader),
13670cf0e598SAlberto Garcia                                sizeof(QCowSnapshotHeader) * QCOW_MAX_SNAPSHOTS,
13680cf0e598SAlberto Garcia                                "Snapshot table", errp);
1369ce48f2f4SKevin Wolf     if (ret < 0) {
1370ce48f2f4SKevin Wolf         goto fail;
1371ce48f2f4SKevin Wolf     }
1372ce48f2f4SKevin Wolf 
1373585f8587Sbellard     /* read the level 1 table */
13740cf0e598SAlberto Garcia     ret = qcow2_validate_table(bs, header.l1_table_offset,
13750cf0e598SAlberto Garcia                                header.l1_size, sizeof(uint64_t),
13760cf0e598SAlberto Garcia                                QCOW_MAX_L1_SIZE, "Active L1 table", errp);
13770cf0e598SAlberto Garcia     if (ret < 0) {
13782d51c32cSKevin Wolf         goto fail;
13792d51c32cSKevin Wolf     }
1380585f8587Sbellard     s->l1_size = header.l1_size;
13810cf0e598SAlberto Garcia     s->l1_table_offset = header.l1_table_offset;
13822cf7cfa1SKevin Wolf 
13832cf7cfa1SKevin Wolf     l1_vm_state_index = size_to_l1(s, header.size);
13842cf7cfa1SKevin Wolf     if (l1_vm_state_index > INT_MAX) {
13853ef6c40aSMax Reitz         error_setg(errp, "Image is too big");
13862cf7cfa1SKevin Wolf         ret = -EFBIG;
13872cf7cfa1SKevin Wolf         goto fail;
13882cf7cfa1SKevin Wolf     }
13892cf7cfa1SKevin Wolf     s->l1_vm_state_index = l1_vm_state_index;
13902cf7cfa1SKevin Wolf 
1391585f8587Sbellard     /* the L1 table must contain at least enough entries to put
1392585f8587Sbellard        header.size bytes */
13936d85a57eSJes Sorensen     if (s->l1_size < s->l1_vm_state_index) {
13943ef6c40aSMax Reitz         error_setg(errp, "L1 table is too small");
13956d85a57eSJes Sorensen         ret = -EINVAL;
1396585f8587Sbellard         goto fail;
13976d85a57eSJes Sorensen     }
13982d51c32cSKevin Wolf 
1399d191d12dSStefan Weil     if (s->l1_size > 0) {
14009a4f4c31SKevin Wolf         s->l1_table = qemu_try_blockalign(bs->file->bs,
14019e029689SAlberto Garcia             ROUND_UP(s->l1_size * sizeof(uint64_t), 512));
1402de82815dSKevin Wolf         if (s->l1_table == NULL) {
1403de82815dSKevin Wolf             error_setg(errp, "Could not allocate L1 table");
1404de82815dSKevin Wolf             ret = -ENOMEM;
1405de82815dSKevin Wolf             goto fail;
1406de82815dSKevin Wolf         }
1407cf2ab8fcSKevin Wolf         ret = bdrv_pread(bs->file, s->l1_table_offset, s->l1_table,
14086d85a57eSJes Sorensen                          s->l1_size * sizeof(uint64_t));
14096d85a57eSJes Sorensen         if (ret < 0) {
14103ef6c40aSMax Reitz             error_setg_errno(errp, -ret, "Could not read L1 table");
1411585f8587Sbellard             goto fail;
14126d85a57eSJes Sorensen         }
1413585f8587Sbellard         for(i = 0;i < s->l1_size; i++) {
14143b698f52SPeter Maydell             s->l1_table[i] = be64_to_cpu(s->l1_table[i]);
1415585f8587Sbellard         }
1416d191d12dSStefan Weil     }
141729c1a730SKevin Wolf 
141894edf3fbSKevin Wolf     /* Parse driver-specific options */
141994edf3fbSKevin Wolf     ret = qcow2_update_options(bs, options, flags, errp);
142090efa0eaSKevin Wolf     if (ret < 0) {
142190efa0eaSKevin Wolf         goto fail;
142290efa0eaSKevin Wolf     }
142390efa0eaSKevin Wolf 
142406d9260fSAnthony Liguori     s->flags = flags;
1425585f8587Sbellard 
14266d85a57eSJes Sorensen     ret = qcow2_refcount_init(bs);
14276d85a57eSJes Sorensen     if (ret != 0) {
14283ef6c40aSMax Reitz         error_setg_errno(errp, -ret, "Could not initialize refcount handling");
1429585f8587Sbellard         goto fail;
14306d85a57eSJes Sorensen     }
1431585f8587Sbellard 
143272cf2d4fSBlue Swirl     QLIST_INIT(&s->cluster_allocs);
14330b919faeSKevin Wolf     QTAILQ_INIT(&s->discards);
1434f214978aSKevin Wolf 
14359b80ddf3Saliguori     /* read qcow2 extensions */
14363ef6c40aSMax Reitz     if (qcow2_read_extensions(bs, header.header_length, ext_end, NULL,
143788ddffaeSVladimir Sementsov-Ogievskiy                               flags, &update_header, &local_err)) {
14383ef6c40aSMax Reitz         error_propagate(errp, local_err);
14396d85a57eSJes Sorensen         ret = -EINVAL;
14409b80ddf3Saliguori         goto fail;
14416d85a57eSJes Sorensen     }
14429b80ddf3Saliguori 
14434652b8f3SDaniel P. Berrange     /* qcow2_read_extension may have set up the crypto context
14444652b8f3SDaniel P. Berrange      * if the crypt method needs a header region, some methods
14454652b8f3SDaniel P. Berrange      * don't need header extensions, so must check here
14464652b8f3SDaniel P. Berrange      */
14474652b8f3SDaniel P. Berrange     if (s->crypt_method_header && !s->crypto) {
1448b25b387fSDaniel P. Berrange         if (s->crypt_method_header == QCOW_CRYPT_AES) {
1449b25b387fSDaniel P. Berrange             unsigned int cflags = 0;
1450b25b387fSDaniel P. Berrange             if (flags & BDRV_O_NO_IO) {
1451b25b387fSDaniel P. Berrange                 cflags |= QCRYPTO_BLOCK_OPEN_NO_IO;
1452b25b387fSDaniel P. Berrange             }
14531cd9a787SDaniel P. Berrange             s->crypto = qcrypto_block_open(s->crypto_opts, "encrypt.",
1454c972fa12SVladimir Sementsov-Ogievskiy                                            NULL, NULL, cflags, 1, errp);
1455b25b387fSDaniel P. Berrange             if (!s->crypto) {
1456b25b387fSDaniel P. Berrange                 ret = -EINVAL;
1457b25b387fSDaniel P. Berrange                 goto fail;
1458b25b387fSDaniel P. Berrange             }
14594652b8f3SDaniel P. Berrange         } else if (!(flags & BDRV_O_NO_IO)) {
14604652b8f3SDaniel P. Berrange             error_setg(errp, "Missing CRYPTO header for crypt method %d",
14614652b8f3SDaniel P. Berrange                        s->crypt_method_header);
14624652b8f3SDaniel P. Berrange             ret = -EINVAL;
14634652b8f3SDaniel P. Berrange             goto fail;
14644652b8f3SDaniel P. Berrange         }
1465b25b387fSDaniel P. Berrange     }
1466b25b387fSDaniel P. Berrange 
1467585f8587Sbellard     /* read the backing file name */
1468585f8587Sbellard     if (header.backing_file_offset != 0) {
1469585f8587Sbellard         len = header.backing_file_size;
14709a29e18fSJeff Cody         if (len > MIN(1023, s->cluster_size - header.backing_file_offset) ||
1471e729fa6aSJeff Cody             len >= sizeof(bs->backing_file)) {
14726d33e8e7SKevin Wolf             error_setg(errp, "Backing file name too long");
14736d33e8e7SKevin Wolf             ret = -EINVAL;
14746d33e8e7SKevin Wolf             goto fail;
14756d85a57eSJes Sorensen         }
1476cf2ab8fcSKevin Wolf         ret = bdrv_pread(bs->file, header.backing_file_offset,
14776d85a57eSJes Sorensen                          bs->backing_file, len);
14786d85a57eSJes Sorensen         if (ret < 0) {
14793ef6c40aSMax Reitz             error_setg_errno(errp, -ret, "Could not read backing file name");
1480585f8587Sbellard             goto fail;
14816d85a57eSJes Sorensen         }
1482585f8587Sbellard         bs->backing_file[len] = '\0';
1483e4603fe1SKevin Wolf         s->image_backing_file = g_strdup(bs->backing_file);
1484585f8587Sbellard     }
148542deb29fSKevin Wolf 
148611b128f4SKevin Wolf     /* Internal snapshots */
148711b128f4SKevin Wolf     s->snapshots_offset = header.snapshots_offset;
148811b128f4SKevin Wolf     s->nb_snapshots = header.nb_snapshots;
148911b128f4SKevin Wolf 
149042deb29fSKevin Wolf     ret = qcow2_read_snapshots(bs);
149142deb29fSKevin Wolf     if (ret < 0) {
14923ef6c40aSMax Reitz         error_setg_errno(errp, -ret, "Could not read snapshots");
1493585f8587Sbellard         goto fail;
14946d85a57eSJes Sorensen     }
1495585f8587Sbellard 
1496af7b708dSStefan Hajnoczi     /* Clear unknown autoclear feature bits */
149788ddffaeSVladimir Sementsov-Ogievskiy     update_header |= s->autoclear_features & ~QCOW2_AUTOCLEAR_MASK;
1498d1258dd0SVladimir Sementsov-Ogievskiy     update_header =
1499d1258dd0SVladimir Sementsov-Ogievskiy         update_header && !bs->read_only && !(flags & BDRV_O_INACTIVE);
1500d1258dd0SVladimir Sementsov-Ogievskiy     if (update_header) {
150188ddffaeSVladimir Sementsov-Ogievskiy         s->autoclear_features &= QCOW2_AUTOCLEAR_MASK;
1502d1258dd0SVladimir Sementsov-Ogievskiy     }
1503d1258dd0SVladimir Sementsov-Ogievskiy 
15049c98f145SVladimir Sementsov-Ogievskiy     /* == Handle persistent dirty bitmaps ==
15059c98f145SVladimir Sementsov-Ogievskiy      *
15069c98f145SVladimir Sementsov-Ogievskiy      * We want load dirty bitmaps in three cases:
15079c98f145SVladimir Sementsov-Ogievskiy      *
15089c98f145SVladimir Sementsov-Ogievskiy      * 1. Normal open of the disk in active mode, not related to invalidation
15099c98f145SVladimir Sementsov-Ogievskiy      *    after migration.
15109c98f145SVladimir Sementsov-Ogievskiy      *
15119c98f145SVladimir Sementsov-Ogievskiy      * 2. Invalidation of the target vm after pre-copy phase of migration, if
15129c98f145SVladimir Sementsov-Ogievskiy      *    bitmaps are _not_ migrating through migration channel, i.e.
15139c98f145SVladimir Sementsov-Ogievskiy      *    'dirty-bitmaps' capability is disabled.
15149c98f145SVladimir Sementsov-Ogievskiy      *
15159c98f145SVladimir Sementsov-Ogievskiy      * 3. Invalidation of source vm after failed or canceled migration.
15169c98f145SVladimir Sementsov-Ogievskiy      *    This is a very interesting case. There are two possible types of
15179c98f145SVladimir Sementsov-Ogievskiy      *    bitmaps:
15189c98f145SVladimir Sementsov-Ogievskiy      *
15199c98f145SVladimir Sementsov-Ogievskiy      *    A. Stored on inactivation and removed. They should be loaded from the
15209c98f145SVladimir Sementsov-Ogievskiy      *       image.
15219c98f145SVladimir Sementsov-Ogievskiy      *
15229c98f145SVladimir Sementsov-Ogievskiy      *    B. Not stored: not-persistent bitmaps and bitmaps, migrated through
15239c98f145SVladimir Sementsov-Ogievskiy      *       the migration channel (with dirty-bitmaps capability).
15249c98f145SVladimir Sementsov-Ogievskiy      *
15259c98f145SVladimir Sementsov-Ogievskiy      *    On the other hand, there are two possible sub-cases:
15269c98f145SVladimir Sementsov-Ogievskiy      *
15279c98f145SVladimir Sementsov-Ogievskiy      *    3.1 disk was changed by somebody else while were inactive. In this
15289c98f145SVladimir Sementsov-Ogievskiy      *        case all in-RAM dirty bitmaps (both persistent and not) are
15299c98f145SVladimir Sementsov-Ogievskiy      *        definitely invalid. And we don't have any method to determine
15309c98f145SVladimir Sementsov-Ogievskiy      *        this.
15319c98f145SVladimir Sementsov-Ogievskiy      *
15329c98f145SVladimir Sementsov-Ogievskiy      *        Simple and safe thing is to just drop all the bitmaps of type B on
15339c98f145SVladimir Sementsov-Ogievskiy      *        inactivation. But in this case we lose bitmaps in valid 4.2 case.
15349c98f145SVladimir Sementsov-Ogievskiy      *
15359c98f145SVladimir Sementsov-Ogievskiy      *        On the other hand, resuming source vm, if disk was already changed
15369c98f145SVladimir Sementsov-Ogievskiy      *        is a bad thing anyway: not only bitmaps, the whole vm state is
15379c98f145SVladimir Sementsov-Ogievskiy      *        out of sync with disk.
15389c98f145SVladimir Sementsov-Ogievskiy      *
15399c98f145SVladimir Sementsov-Ogievskiy      *        This means, that user or management tool, who for some reason
15409c98f145SVladimir Sementsov-Ogievskiy      *        decided to resume source vm, after disk was already changed by
15419c98f145SVladimir Sementsov-Ogievskiy      *        target vm, should at least drop all dirty bitmaps by hand.
15429c98f145SVladimir Sementsov-Ogievskiy      *
15439c98f145SVladimir Sementsov-Ogievskiy      *        So, we can ignore this case for now, but TODO: "generation"
15449c98f145SVladimir Sementsov-Ogievskiy      *        extension for qcow2, to determine, that image was changed after
15459c98f145SVladimir Sementsov-Ogievskiy      *        last inactivation. And if it is changed, we will drop (or at least
15469c98f145SVladimir Sementsov-Ogievskiy      *        mark as 'invalid' all the bitmaps of type B, both persistent
15479c98f145SVladimir Sementsov-Ogievskiy      *        and not).
15489c98f145SVladimir Sementsov-Ogievskiy      *
15499c98f145SVladimir Sementsov-Ogievskiy      *    3.2 disk was _not_ changed while were inactive. Bitmaps may be saved
15509c98f145SVladimir Sementsov-Ogievskiy      *        to disk ('dirty-bitmaps' capability disabled), or not saved
15519c98f145SVladimir Sementsov-Ogievskiy      *        ('dirty-bitmaps' capability enabled), but we don't need to care
15529c98f145SVladimir Sementsov-Ogievskiy      *        of: let's load bitmaps as always: stored bitmaps will be loaded,
15539c98f145SVladimir Sementsov-Ogievskiy      *        and not stored has flag IN_USE=1 in the image and will be skipped
15549c98f145SVladimir Sementsov-Ogievskiy      *        on loading.
15559c98f145SVladimir Sementsov-Ogievskiy      *
15569c98f145SVladimir Sementsov-Ogievskiy      * One remaining possible case when we don't want load bitmaps:
15579c98f145SVladimir Sementsov-Ogievskiy      *
15589c98f145SVladimir Sementsov-Ogievskiy      * 4. Open disk in inactive mode in target vm (bitmaps are migrating or
15599c98f145SVladimir Sementsov-Ogievskiy      *    will be loaded on invalidation, no needs try loading them before)
15609c98f145SVladimir Sementsov-Ogievskiy      */
15619c98f145SVladimir Sementsov-Ogievskiy 
15629c98f145SVladimir Sementsov-Ogievskiy     if (!(bdrv_get_flags(bs) & BDRV_O_INACTIVE)) {
15639c98f145SVladimir Sementsov-Ogievskiy         /* It's case 1, 2 or 3.2. Or 3.1 which is BUG in management layer. */
15649c98f145SVladimir Sementsov-Ogievskiy         bool header_updated = qcow2_load_dirty_bitmaps(bs, &local_err);
15659c98f145SVladimir Sementsov-Ogievskiy 
15669c98f145SVladimir Sementsov-Ogievskiy         update_header = update_header && !header_updated;
1567605bc8beSVladimir Sementsov-Ogievskiy     }
1568d1258dd0SVladimir Sementsov-Ogievskiy     if (local_err != NULL) {
1569d1258dd0SVladimir Sementsov-Ogievskiy         error_propagate(errp, local_err);
1570d1258dd0SVladimir Sementsov-Ogievskiy         ret = -EINVAL;
1571d1258dd0SVladimir Sementsov-Ogievskiy         goto fail;
1572d1258dd0SVladimir Sementsov-Ogievskiy     }
1573d1258dd0SVladimir Sementsov-Ogievskiy 
1574d1258dd0SVladimir Sementsov-Ogievskiy     if (update_header) {
1575af7b708dSStefan Hajnoczi         ret = qcow2_update_header(bs);
1576af7b708dSStefan Hajnoczi         if (ret < 0) {
15773ef6c40aSMax Reitz             error_setg_errno(errp, -ret, "Could not update qcow2 header");
1578af7b708dSStefan Hajnoczi             goto fail;
1579af7b708dSStefan Hajnoczi         }
1580af7b708dSStefan Hajnoczi     }
1581af7b708dSStefan Hajnoczi 
1582e24d813bSEric Blake     bs->supported_zero_flags = header.version >= 3 ? BDRV_REQ_MAY_UNMAP : 0;
158368d100e9SKevin Wolf 
1584c61d0004SStefan Hajnoczi     /* Repair image if dirty */
158504c01a5cSKevin Wolf     if (!(flags & (BDRV_O_CHECK | BDRV_O_INACTIVE)) && !bs->read_only &&
1586058f8f16SStefan Hajnoczi         (s->incompatible_features & QCOW2_INCOMPAT_DIRTY)) {
1587c61d0004SStefan Hajnoczi         BdrvCheckResult result = {0};
1588c61d0004SStefan Hajnoczi 
15892fd61638SPaolo Bonzini         ret = qcow2_co_check_locked(bs, &result,
15902fd61638SPaolo Bonzini                                     BDRV_FIX_ERRORS | BDRV_FIX_LEAKS);
1591791fff50SMax Reitz         if (ret < 0 || result.check_errors) {
1592791fff50SMax Reitz             if (ret >= 0) {
1593791fff50SMax Reitz                 ret = -EIO;
1594791fff50SMax Reitz             }
15953ef6c40aSMax Reitz             error_setg_errno(errp, -ret, "Could not repair dirty image");
1596c61d0004SStefan Hajnoczi             goto fail;
1597c61d0004SStefan Hajnoczi         }
1598c61d0004SStefan Hajnoczi     }
1599c61d0004SStefan Hajnoczi 
1600585f8587Sbellard #ifdef DEBUG_ALLOC
16016cbc3031SPhilipp Hahn     {
16026cbc3031SPhilipp Hahn         BdrvCheckResult result = {0};
1603b35278f7SStefan Hajnoczi         qcow2_check_refcounts(bs, &result, 0);
16046cbc3031SPhilipp Hahn     }
1605585f8587Sbellard #endif
1606ceb029cdSVladimir Sementsov-Ogievskiy 
1607ceb029cdSVladimir Sementsov-Ogievskiy     qemu_co_queue_init(&s->compress_wait_queue);
1608ceb029cdSVladimir Sementsov-Ogievskiy 
16096d85a57eSJes Sorensen     return ret;
1610585f8587Sbellard 
1611585f8587Sbellard  fail:
16126744cbabSKevin Wolf     g_free(s->unknown_header_fields);
161375bab85cSKevin Wolf     cleanup_unknown_header_ext(bs);
1614ed6ccf0fSKevin Wolf     qcow2_free_snapshots(bs);
1615ed6ccf0fSKevin Wolf     qcow2_refcount_close(bs);
1616de82815dSKevin Wolf     qemu_vfree(s->l1_table);
1617cf93980eSMax Reitz     /* else pre-write overlap checks in cache_destroy may crash */
1618cf93980eSMax Reitz     s->l1_table = NULL;
1619279621c0SAlberto Garcia     cache_clean_timer_del(bs);
162029c1a730SKevin Wolf     if (s->l2_table_cache) {
1621e64d4072SAlberto Garcia         qcow2_cache_destroy(s->l2_table_cache);
162229c1a730SKevin Wolf     }
1623c5a33ee9SPrasad Joshi     if (s->refcount_block_cache) {
1624e64d4072SAlberto Garcia         qcow2_cache_destroy(s->refcount_block_cache);
1625c5a33ee9SPrasad Joshi     }
1626b25b387fSDaniel P. Berrange     qcrypto_block_free(s->crypto);
1627b25b387fSDaniel P. Berrange     qapi_free_QCryptoBlockOpenOptions(s->crypto_opts);
16286d85a57eSJes Sorensen     return ret;
1629585f8587Sbellard }
1630585f8587Sbellard 
16311fafcd93SPaolo Bonzini typedef struct QCow2OpenCo {
16321fafcd93SPaolo Bonzini     BlockDriverState *bs;
16331fafcd93SPaolo Bonzini     QDict *options;
16341fafcd93SPaolo Bonzini     int flags;
16351fafcd93SPaolo Bonzini     Error **errp;
16361fafcd93SPaolo Bonzini     int ret;
16371fafcd93SPaolo Bonzini } QCow2OpenCo;
16381fafcd93SPaolo Bonzini 
16391fafcd93SPaolo Bonzini static void coroutine_fn qcow2_open_entry(void *opaque)
16401fafcd93SPaolo Bonzini {
16411fafcd93SPaolo Bonzini     QCow2OpenCo *qoc = opaque;
16421fafcd93SPaolo Bonzini     BDRVQcow2State *s = qoc->bs->opaque;
16431fafcd93SPaolo Bonzini 
16441fafcd93SPaolo Bonzini     qemu_co_mutex_lock(&s->lock);
16451fafcd93SPaolo Bonzini     qoc->ret = qcow2_do_open(qoc->bs, qoc->options, qoc->flags, qoc->errp);
16461fafcd93SPaolo Bonzini     qemu_co_mutex_unlock(&s->lock);
16471fafcd93SPaolo Bonzini }
16481fafcd93SPaolo Bonzini 
16494e4bf5c4SKevin Wolf static int qcow2_open(BlockDriverState *bs, QDict *options, int flags,
16504e4bf5c4SKevin Wolf                       Error **errp)
16514e4bf5c4SKevin Wolf {
16521fafcd93SPaolo Bonzini     BDRVQcow2State *s = bs->opaque;
16531fafcd93SPaolo Bonzini     QCow2OpenCo qoc = {
16541fafcd93SPaolo Bonzini         .bs = bs,
16551fafcd93SPaolo Bonzini         .options = options,
16561fafcd93SPaolo Bonzini         .flags = flags,
16571fafcd93SPaolo Bonzini         .errp = errp,
16581fafcd93SPaolo Bonzini         .ret = -EINPROGRESS
16591fafcd93SPaolo Bonzini     };
16601fafcd93SPaolo Bonzini 
16614e4bf5c4SKevin Wolf     bs->file = bdrv_open_child(NULL, options, "file", bs, &child_file,
16624e4bf5c4SKevin Wolf                                false, errp);
16634e4bf5c4SKevin Wolf     if (!bs->file) {
16644e4bf5c4SKevin Wolf         return -EINVAL;
16654e4bf5c4SKevin Wolf     }
16664e4bf5c4SKevin Wolf 
16671fafcd93SPaolo Bonzini     /* Initialise locks */
16681fafcd93SPaolo Bonzini     qemu_co_mutex_init(&s->lock);
16691fafcd93SPaolo Bonzini 
16701fafcd93SPaolo Bonzini     if (qemu_in_coroutine()) {
16711fafcd93SPaolo Bonzini         /* From bdrv_co_create.  */
16721fafcd93SPaolo Bonzini         qcow2_open_entry(&qoc);
16731fafcd93SPaolo Bonzini     } else {
16744720cbeeSKevin Wolf         assert(qemu_get_current_aio_context() == qemu_get_aio_context());
16751fafcd93SPaolo Bonzini         qemu_coroutine_enter(qemu_coroutine_create(qcow2_open_entry, &qoc));
16761fafcd93SPaolo Bonzini         BDRV_POLL_WHILE(bs, qoc.ret == -EINPROGRESS);
16771fafcd93SPaolo Bonzini     }
16781fafcd93SPaolo Bonzini     return qoc.ret;
16794e4bf5c4SKevin Wolf }
16804e4bf5c4SKevin Wolf 
16813baca891SKevin Wolf static void qcow2_refresh_limits(BlockDriverState *bs, Error **errp)
1682d34682cdSKevin Wolf {
1683ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
1684d34682cdSKevin Wolf 
1685a84178ccSEric Blake     if (bs->encrypted) {
1686a84178ccSEric Blake         /* Encryption works on a sector granularity */
16876f8f015cSAlberto Garcia         bs->bl.request_alignment = qcrypto_block_get_sector_size(s->crypto);
1688a84178ccSEric Blake     }
1689cf081fcaSEric Blake     bs->bl.pwrite_zeroes_alignment = s->cluster_size;
1690ecdbead6SEric Blake     bs->bl.pdiscard_alignment = s->cluster_size;
1691d34682cdSKevin Wolf }
1692d34682cdSKevin Wolf 
169321d82ac9SJeff Cody static int qcow2_reopen_prepare(BDRVReopenState *state,
169421d82ac9SJeff Cody                                 BlockReopenQueue *queue, Error **errp)
169521d82ac9SJeff Cody {
16965b0959a7SKevin Wolf     Qcow2ReopenState *r;
16974c2e5f8fSKevin Wolf     int ret;
16984c2e5f8fSKevin Wolf 
16995b0959a7SKevin Wolf     r = g_new0(Qcow2ReopenState, 1);
17005b0959a7SKevin Wolf     state->opaque = r;
17015b0959a7SKevin Wolf 
17025b0959a7SKevin Wolf     ret = qcow2_update_options_prepare(state->bs, r, state->options,
17035b0959a7SKevin Wolf                                        state->flags, errp);
17045b0959a7SKevin Wolf     if (ret < 0) {
17055b0959a7SKevin Wolf         goto fail;
17065b0959a7SKevin Wolf     }
17075b0959a7SKevin Wolf 
17085b0959a7SKevin Wolf     /* We need to write out any unwritten data if we reopen read-only. */
17094c2e5f8fSKevin Wolf     if ((state->flags & BDRV_O_RDWR) == 0) {
1710169b8793SVladimir Sementsov-Ogievskiy         ret = qcow2_reopen_bitmaps_ro(state->bs, errp);
1711169b8793SVladimir Sementsov-Ogievskiy         if (ret < 0) {
1712169b8793SVladimir Sementsov-Ogievskiy             goto fail;
1713169b8793SVladimir Sementsov-Ogievskiy         }
1714169b8793SVladimir Sementsov-Ogievskiy 
17154c2e5f8fSKevin Wolf         ret = bdrv_flush(state->bs);
17164c2e5f8fSKevin Wolf         if (ret < 0) {
17175b0959a7SKevin Wolf             goto fail;
17184c2e5f8fSKevin Wolf         }
17194c2e5f8fSKevin Wolf 
17204c2e5f8fSKevin Wolf         ret = qcow2_mark_clean(state->bs);
17214c2e5f8fSKevin Wolf         if (ret < 0) {
17225b0959a7SKevin Wolf             goto fail;
17234c2e5f8fSKevin Wolf         }
17244c2e5f8fSKevin Wolf     }
17254c2e5f8fSKevin Wolf 
172621d82ac9SJeff Cody     return 0;
17275b0959a7SKevin Wolf 
17285b0959a7SKevin Wolf fail:
17295b0959a7SKevin Wolf     qcow2_update_options_abort(state->bs, r);
17305b0959a7SKevin Wolf     g_free(r);
17315b0959a7SKevin Wolf     return ret;
17325b0959a7SKevin Wolf }
17335b0959a7SKevin Wolf 
17345b0959a7SKevin Wolf static void qcow2_reopen_commit(BDRVReopenState *state)
17355b0959a7SKevin Wolf {
17365b0959a7SKevin Wolf     qcow2_update_options_commit(state->bs, state->opaque);
17375b0959a7SKevin Wolf     g_free(state->opaque);
17385b0959a7SKevin Wolf }
17395b0959a7SKevin Wolf 
17405b0959a7SKevin Wolf static void qcow2_reopen_abort(BDRVReopenState *state)
17415b0959a7SKevin Wolf {
17425b0959a7SKevin Wolf     qcow2_update_options_abort(state->bs, state->opaque);
17435b0959a7SKevin Wolf     g_free(state->opaque);
174421d82ac9SJeff Cody }
174521d82ac9SJeff Cody 
17465365f44dSKevin Wolf static void qcow2_join_options(QDict *options, QDict *old_options)
17475365f44dSKevin Wolf {
17485365f44dSKevin Wolf     bool has_new_overlap_template =
17495365f44dSKevin Wolf         qdict_haskey(options, QCOW2_OPT_OVERLAP) ||
17505365f44dSKevin Wolf         qdict_haskey(options, QCOW2_OPT_OVERLAP_TEMPLATE);
17515365f44dSKevin Wolf     bool has_new_total_cache_size =
17525365f44dSKevin Wolf         qdict_haskey(options, QCOW2_OPT_CACHE_SIZE);
17535365f44dSKevin Wolf     bool has_all_cache_options;
17545365f44dSKevin Wolf 
17555365f44dSKevin Wolf     /* New overlap template overrides all old overlap options */
17565365f44dSKevin Wolf     if (has_new_overlap_template) {
17575365f44dSKevin Wolf         qdict_del(old_options, QCOW2_OPT_OVERLAP);
17585365f44dSKevin Wolf         qdict_del(old_options, QCOW2_OPT_OVERLAP_TEMPLATE);
17595365f44dSKevin Wolf         qdict_del(old_options, QCOW2_OPT_OVERLAP_MAIN_HEADER);
17605365f44dSKevin Wolf         qdict_del(old_options, QCOW2_OPT_OVERLAP_ACTIVE_L1);
17615365f44dSKevin Wolf         qdict_del(old_options, QCOW2_OPT_OVERLAP_ACTIVE_L2);
17625365f44dSKevin Wolf         qdict_del(old_options, QCOW2_OPT_OVERLAP_REFCOUNT_TABLE);
17635365f44dSKevin Wolf         qdict_del(old_options, QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK);
17645365f44dSKevin Wolf         qdict_del(old_options, QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE);
17655365f44dSKevin Wolf         qdict_del(old_options, QCOW2_OPT_OVERLAP_INACTIVE_L1);
17665365f44dSKevin Wolf         qdict_del(old_options, QCOW2_OPT_OVERLAP_INACTIVE_L2);
17675365f44dSKevin Wolf     }
17685365f44dSKevin Wolf 
17695365f44dSKevin Wolf     /* New total cache size overrides all old options */
17705365f44dSKevin Wolf     if (qdict_haskey(options, QCOW2_OPT_CACHE_SIZE)) {
17715365f44dSKevin Wolf         qdict_del(old_options, QCOW2_OPT_L2_CACHE_SIZE);
17725365f44dSKevin Wolf         qdict_del(old_options, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
17735365f44dSKevin Wolf     }
17745365f44dSKevin Wolf 
17755365f44dSKevin Wolf     qdict_join(options, old_options, false);
17765365f44dSKevin Wolf 
17775365f44dSKevin Wolf     /*
17785365f44dSKevin Wolf      * If after merging all cache size options are set, an old total size is
17795365f44dSKevin Wolf      * overwritten. Do keep all options, however, if all three are new. The
17805365f44dSKevin Wolf      * resulting error message is what we want to happen.
17815365f44dSKevin Wolf      */
17825365f44dSKevin Wolf     has_all_cache_options =
17835365f44dSKevin Wolf         qdict_haskey(options, QCOW2_OPT_CACHE_SIZE) ||
17845365f44dSKevin Wolf         qdict_haskey(options, QCOW2_OPT_L2_CACHE_SIZE) ||
17855365f44dSKevin Wolf         qdict_haskey(options, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
17865365f44dSKevin Wolf 
17875365f44dSKevin Wolf     if (has_all_cache_options && !has_new_total_cache_size) {
17885365f44dSKevin Wolf         qdict_del(options, QCOW2_OPT_CACHE_SIZE);
17895365f44dSKevin Wolf     }
17905365f44dSKevin Wolf }
17915365f44dSKevin Wolf 
1792a320fb04SEric Blake static int coroutine_fn qcow2_co_block_status(BlockDriverState *bs,
1793a320fb04SEric Blake                                               bool want_zero,
1794a320fb04SEric Blake                                               int64_t offset, int64_t count,
1795a320fb04SEric Blake                                               int64_t *pnum, int64_t *map,
1796a320fb04SEric Blake                                               BlockDriverState **file)
1797585f8587Sbellard {
1798ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
1799585f8587Sbellard     uint64_t cluster_offset;
18004bc74be9SPaolo Bonzini     int index_in_cluster, ret;
1801ecfe1863SKevin Wolf     unsigned int bytes;
1802a320fb04SEric Blake     int status = 0;
1803585f8587Sbellard 
1804a320fb04SEric Blake     bytes = MIN(INT_MAX, count);
1805f8a2e5e3SStefan Hajnoczi     qemu_co_mutex_lock(&s->lock);
1806a320fb04SEric Blake     ret = qcow2_get_cluster_offset(bs, offset, &bytes, &cluster_offset);
1807f8a2e5e3SStefan Hajnoczi     qemu_co_mutex_unlock(&s->lock);
18081c46efaaSKevin Wolf     if (ret < 0) {
1809d663640cSPaolo Bonzini         return ret;
18101c46efaaSKevin Wolf     }
1811095a9c58Saliguori 
1812a320fb04SEric Blake     *pnum = bytes;
1813ecfe1863SKevin Wolf 
18144bc74be9SPaolo Bonzini     if (cluster_offset != 0 && ret != QCOW2_CLUSTER_COMPRESSED &&
1815b25b387fSDaniel P. Berrange         !s->crypto) {
1816a320fb04SEric Blake         index_in_cluster = offset & (s->cluster_size - 1);
1817a320fb04SEric Blake         *map = cluster_offset | index_in_cluster;
1818178b4db7SFam Zheng         *file = bs->file->bs;
1819a320fb04SEric Blake         status |= BDRV_BLOCK_OFFSET_VALID;
18204bc74be9SPaolo Bonzini     }
1821fdfab37dSEric Blake     if (ret == QCOW2_CLUSTER_ZERO_PLAIN || ret == QCOW2_CLUSTER_ZERO_ALLOC) {
18224bc74be9SPaolo Bonzini         status |= BDRV_BLOCK_ZERO;
18234bc74be9SPaolo Bonzini     } else if (ret != QCOW2_CLUSTER_UNALLOCATED) {
18244bc74be9SPaolo Bonzini         status |= BDRV_BLOCK_DATA;
18254bc74be9SPaolo Bonzini     }
18264bc74be9SPaolo Bonzini     return status;
1827585f8587Sbellard }
1828585f8587Sbellard 
1829fd9fcd37SFam Zheng static coroutine_fn int qcow2_handle_l2meta(BlockDriverState *bs,
1830fd9fcd37SFam Zheng                                             QCowL2Meta **pl2meta,
1831fd9fcd37SFam Zheng                                             bool link_l2)
1832fd9fcd37SFam Zheng {
1833fd9fcd37SFam Zheng     int ret = 0;
1834fd9fcd37SFam Zheng     QCowL2Meta *l2meta = *pl2meta;
1835fd9fcd37SFam Zheng 
1836fd9fcd37SFam Zheng     while (l2meta != NULL) {
1837fd9fcd37SFam Zheng         QCowL2Meta *next;
1838fd9fcd37SFam Zheng 
1839354d930dSFam Zheng         if (link_l2) {
1840fd9fcd37SFam Zheng             ret = qcow2_alloc_cluster_link_l2(bs, l2meta);
1841fd9fcd37SFam Zheng             if (ret) {
1842fd9fcd37SFam Zheng                 goto out;
1843fd9fcd37SFam Zheng             }
18448b24cd14SKevin Wolf         } else {
18458b24cd14SKevin Wolf             qcow2_alloc_cluster_abort(bs, l2meta);
1846fd9fcd37SFam Zheng         }
1847fd9fcd37SFam Zheng 
1848fd9fcd37SFam Zheng         /* Take the request off the list of running requests */
1849fd9fcd37SFam Zheng         if (l2meta->nb_clusters != 0) {
1850fd9fcd37SFam Zheng             QLIST_REMOVE(l2meta, next_in_flight);
1851fd9fcd37SFam Zheng         }
1852fd9fcd37SFam Zheng 
1853fd9fcd37SFam Zheng         qemu_co_queue_restart_all(&l2meta->dependent_requests);
1854fd9fcd37SFam Zheng 
1855fd9fcd37SFam Zheng         next = l2meta->next;
1856fd9fcd37SFam Zheng         g_free(l2meta);
1857fd9fcd37SFam Zheng         l2meta = next;
1858fd9fcd37SFam Zheng     }
1859fd9fcd37SFam Zheng out:
1860fd9fcd37SFam Zheng     *pl2meta = l2meta;
1861fd9fcd37SFam Zheng     return ret;
1862fd9fcd37SFam Zheng }
1863fd9fcd37SFam Zheng 
1864ecfe1863SKevin Wolf static coroutine_fn int qcow2_co_preadv(BlockDriverState *bs, uint64_t offset,
1865ecfe1863SKevin Wolf                                         uint64_t bytes, QEMUIOVector *qiov,
1866ecfe1863SKevin Wolf                                         int flags)
18671490791fSaliguori {
1868ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
1869546a7dc4SEdgar Kaziakhmedov     int offset_in_cluster;
187068d100e9SKevin Wolf     int ret;
1871ecfe1863SKevin Wolf     unsigned int cur_bytes; /* number of bytes in current iteration */
1872c2bdd990SFrediano Ziglio     uint64_t cluster_offset = 0;
18733fc48d09SFrediano Ziglio     uint64_t bytes_done = 0;
18743fc48d09SFrediano Ziglio     QEMUIOVector hd_qiov;
18753fc48d09SFrediano Ziglio     uint8_t *cluster_data = NULL;
1876585f8587Sbellard 
18773fc48d09SFrediano Ziglio     qemu_iovec_init(&hd_qiov, qiov->niov);
18783fc48d09SFrediano Ziglio 
18793fc48d09SFrediano Ziglio     qemu_co_mutex_lock(&s->lock);
18803fc48d09SFrediano Ziglio 
1881ecfe1863SKevin Wolf     while (bytes != 0) {
1882585f8587Sbellard 
1883faf575c1SFrediano Ziglio         /* prepare next request */
1884ecfe1863SKevin Wolf         cur_bytes = MIN(bytes, INT_MAX);
1885b25b387fSDaniel P. Berrange         if (s->crypto) {
1886ecfe1863SKevin Wolf             cur_bytes = MIN(cur_bytes,
1887ecfe1863SKevin Wolf                             QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
1888bd28f835SKevin Wolf         }
1889bd28f835SKevin Wolf 
1890ecfe1863SKevin Wolf         ret = qcow2_get_cluster_offset(bs, offset, &cur_bytes, &cluster_offset);
18911c46efaaSKevin Wolf         if (ret < 0) {
18923fc48d09SFrediano Ziglio             goto fail;
18931c46efaaSKevin Wolf         }
18941c46efaaSKevin Wolf 
1895ecfe1863SKevin Wolf         offset_in_cluster = offset_into_cluster(s, offset);
1896585f8587Sbellard 
18973fc48d09SFrediano Ziglio         qemu_iovec_reset(&hd_qiov);
1898ecfe1863SKevin Wolf         qemu_iovec_concat(&hd_qiov, qiov, bytes_done, cur_bytes);
1899bd28f835SKevin Wolf 
190068d000a3SKevin Wolf         switch (ret) {
190168d000a3SKevin Wolf         case QCOW2_CLUSTER_UNALLOCATED:
1902bd28f835SKevin Wolf 
1903760e0063SKevin Wolf             if (bs->backing) {
190466f82ceeSKevin Wolf                 BLKDBG_EVENT(bs->file, BLKDBG_READ_BACKING_AIO);
190568d100e9SKevin Wolf                 qemu_co_mutex_unlock(&s->lock);
1906546a7dc4SEdgar Kaziakhmedov                 ret = bdrv_co_preadv(bs->backing, offset, cur_bytes,
1907546a7dc4SEdgar Kaziakhmedov                                      &hd_qiov, 0);
190868d100e9SKevin Wolf                 qemu_co_mutex_lock(&s->lock);
190968d100e9SKevin Wolf                 if (ret < 0) {
19103fc48d09SFrediano Ziglio                     goto fail;
19113ab4c7e9SKevin Wolf                 }
1912a9465922Sbellard             } else {
1913585f8587Sbellard                 /* Note: in this case, no need to wait */
1914ecfe1863SKevin Wolf                 qemu_iovec_memset(&hd_qiov, 0, 0, cur_bytes);
19151490791fSaliguori             }
191668d000a3SKevin Wolf             break;
191768d000a3SKevin Wolf 
1918fdfab37dSEric Blake         case QCOW2_CLUSTER_ZERO_PLAIN:
1919fdfab37dSEric Blake         case QCOW2_CLUSTER_ZERO_ALLOC:
1920ecfe1863SKevin Wolf             qemu_iovec_memset(&hd_qiov, 0, 0, cur_bytes);
19216377af48SKevin Wolf             break;
19226377af48SKevin Wolf 
192368d000a3SKevin Wolf         case QCOW2_CLUSTER_COMPRESSED:
1924c3c10f72SVladimir Sementsov-Ogievskiy             qemu_co_mutex_unlock(&s->lock);
1925c3c10f72SVladimir Sementsov-Ogievskiy             ret = qcow2_co_preadv_compressed(bs, cluster_offset,
1926c3c10f72SVladimir Sementsov-Ogievskiy                                              offset, cur_bytes,
1927c3c10f72SVladimir Sementsov-Ogievskiy                                              &hd_qiov);
1928c3c10f72SVladimir Sementsov-Ogievskiy             qemu_co_mutex_lock(&s->lock);
19298af36488SKevin Wolf             if (ret < 0) {
19303fc48d09SFrediano Ziglio                 goto fail;
19318af36488SKevin Wolf             }
1932bd28f835SKevin Wolf 
193368d000a3SKevin Wolf             break;
193468d000a3SKevin Wolf 
193568d000a3SKevin Wolf         case QCOW2_CLUSTER_NORMAL:
1936c2bdd990SFrediano Ziglio             if ((cluster_offset & 511) != 0) {
19373fc48d09SFrediano Ziglio                 ret = -EIO;
19383fc48d09SFrediano Ziglio                 goto fail;
1939585f8587Sbellard             }
1940c87c0672Saliguori 
19418336aafaSDaniel P. Berrange             if (bs->encrypted) {
1942b25b387fSDaniel P. Berrange                 assert(s->crypto);
19438336aafaSDaniel P. Berrange 
1944bd28f835SKevin Wolf                 /*
1945bd28f835SKevin Wolf                  * For encrypted images, read everything into a temporary
1946bd28f835SKevin Wolf                  * contiguous buffer on which the AES functions can work.
1947bd28f835SKevin Wolf                  */
19483fc48d09SFrediano Ziglio                 if (!cluster_data) {
19493fc48d09SFrediano Ziglio                     cluster_data =
19509a4f4c31SKevin Wolf                         qemu_try_blockalign(bs->file->bs,
19519a4f4c31SKevin Wolf                                             QCOW_MAX_CRYPT_CLUSTERS
1952de82815dSKevin Wolf                                             * s->cluster_size);
1953de82815dSKevin Wolf                     if (cluster_data == NULL) {
1954de82815dSKevin Wolf                         ret = -ENOMEM;
1955de82815dSKevin Wolf                         goto fail;
1956de82815dSKevin Wolf                     }
1957bd28f835SKevin Wolf                 }
1958bd28f835SKevin Wolf 
1959ecfe1863SKevin Wolf                 assert(cur_bytes <= QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
19603fc48d09SFrediano Ziglio                 qemu_iovec_reset(&hd_qiov);
1961ecfe1863SKevin Wolf                 qemu_iovec_add(&hd_qiov, cluster_data, cur_bytes);
1962bd28f835SKevin Wolf             }
1963bd28f835SKevin Wolf 
196466f82ceeSKevin Wolf             BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);
196568d100e9SKevin Wolf             qemu_co_mutex_unlock(&s->lock);
1966a03ef88fSKevin Wolf             ret = bdrv_co_preadv(bs->file,
1967ecfe1863SKevin Wolf                                  cluster_offset + offset_in_cluster,
1968ecfe1863SKevin Wolf                                  cur_bytes, &hd_qiov, 0);
196968d100e9SKevin Wolf             qemu_co_mutex_lock(&s->lock);
197068d100e9SKevin Wolf             if (ret < 0) {
19713fc48d09SFrediano Ziglio                 goto fail;
1972585f8587Sbellard             }
19738336aafaSDaniel P. Berrange             if (bs->encrypted) {
1974b25b387fSDaniel P. Berrange                 assert(s->crypto);
1975ecfe1863SKevin Wolf                 assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);
1976ecfe1863SKevin Wolf                 assert((cur_bytes & (BDRV_SECTOR_SIZE - 1)) == 0);
1977b25b387fSDaniel P. Berrange                 if (qcrypto_block_decrypt(s->crypto,
19784652b8f3SDaniel P. Berrange                                           (s->crypt_physical_offset ?
19794652b8f3SDaniel P. Berrange                                            cluster_offset + offset_in_cluster :
19804609742aSDaniel P. Berrange                                            offset),
1981446d306dSDaniel P. Berrange                                           cluster_data,
1982b25b387fSDaniel P. Berrange                                           cur_bytes,
1983c3a8fe33SAlberto Garcia                                           NULL) < 0) {
1984f6fa64f6SDaniel P. Berrange                     ret = -EIO;
1985f6fa64f6SDaniel P. Berrange                     goto fail;
1986f6fa64f6SDaniel P. Berrange                 }
1987ecfe1863SKevin Wolf                 qemu_iovec_from_buf(qiov, bytes_done, cluster_data, cur_bytes);
1988171e3d6bSKevin Wolf             }
198968d000a3SKevin Wolf             break;
199068d000a3SKevin Wolf 
199168d000a3SKevin Wolf         default:
199268d000a3SKevin Wolf             g_assert_not_reached();
199368d000a3SKevin Wolf             ret = -EIO;
199468d000a3SKevin Wolf             goto fail;
1995faf575c1SFrediano Ziglio         }
1996faf575c1SFrediano Ziglio 
1997ecfe1863SKevin Wolf         bytes -= cur_bytes;
1998ecfe1863SKevin Wolf         offset += cur_bytes;
1999ecfe1863SKevin Wolf         bytes_done += cur_bytes;
20005ebaa27eSFrediano Ziglio     }
20013fc48d09SFrediano Ziglio     ret = 0;
2002f141eafeSaliguori 
20033fc48d09SFrediano Ziglio fail:
200468d100e9SKevin Wolf     qemu_co_mutex_unlock(&s->lock);
200568d100e9SKevin Wolf 
20063fc48d09SFrediano Ziglio     qemu_iovec_destroy(&hd_qiov);
2007dea43a65SFrediano Ziglio     qemu_vfree(cluster_data);
200868d100e9SKevin Wolf 
200968d100e9SKevin Wolf     return ret;
2010585f8587Sbellard }
2011585f8587Sbellard 
2012ee22a9d8SAlberto Garcia /* Check if it's possible to merge a write request with the writing of
2013ee22a9d8SAlberto Garcia  * the data from the COW regions */
2014ee22a9d8SAlberto Garcia static bool merge_cow(uint64_t offset, unsigned bytes,
2015ee22a9d8SAlberto Garcia                       QEMUIOVector *hd_qiov, QCowL2Meta *l2meta)
2016ee22a9d8SAlberto Garcia {
2017ee22a9d8SAlberto Garcia     QCowL2Meta *m;
2018ee22a9d8SAlberto Garcia 
2019ee22a9d8SAlberto Garcia     for (m = l2meta; m != NULL; m = m->next) {
2020ee22a9d8SAlberto Garcia         /* If both COW regions are empty then there's nothing to merge */
2021ee22a9d8SAlberto Garcia         if (m->cow_start.nb_bytes == 0 && m->cow_end.nb_bytes == 0) {
2022ee22a9d8SAlberto Garcia             continue;
2023ee22a9d8SAlberto Garcia         }
2024ee22a9d8SAlberto Garcia 
2025ee22a9d8SAlberto Garcia         /* The data (middle) region must be immediately after the
2026ee22a9d8SAlberto Garcia          * start region */
2027ee22a9d8SAlberto Garcia         if (l2meta_cow_start(m) + m->cow_start.nb_bytes != offset) {
2028ee22a9d8SAlberto Garcia             continue;
2029ee22a9d8SAlberto Garcia         }
2030ee22a9d8SAlberto Garcia 
2031ee22a9d8SAlberto Garcia         /* The end region must be immediately after the data (middle)
2032ee22a9d8SAlberto Garcia          * region */
2033ee22a9d8SAlberto Garcia         if (m->offset + m->cow_end.offset != offset + bytes) {
2034ee22a9d8SAlberto Garcia             continue;
2035ee22a9d8SAlberto Garcia         }
2036ee22a9d8SAlberto Garcia 
2037ee22a9d8SAlberto Garcia         /* Make sure that adding both COW regions to the QEMUIOVector
2038ee22a9d8SAlberto Garcia          * does not exceed IOV_MAX */
2039ee22a9d8SAlberto Garcia         if (hd_qiov->niov > IOV_MAX - 2) {
2040ee22a9d8SAlberto Garcia             continue;
2041ee22a9d8SAlberto Garcia         }
2042ee22a9d8SAlberto Garcia 
2043ee22a9d8SAlberto Garcia         m->data_qiov = hd_qiov;
2044ee22a9d8SAlberto Garcia         return true;
2045ee22a9d8SAlberto Garcia     }
2046ee22a9d8SAlberto Garcia 
2047ee22a9d8SAlberto Garcia     return false;
2048ee22a9d8SAlberto Garcia }
2049ee22a9d8SAlberto Garcia 
2050d46a0bb2SKevin Wolf static coroutine_fn int qcow2_co_pwritev(BlockDriverState *bs, uint64_t offset,
2051d46a0bb2SKevin Wolf                                          uint64_t bytes, QEMUIOVector *qiov,
2052d46a0bb2SKevin Wolf                                          int flags)
2053585f8587Sbellard {
2054ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
2055d46a0bb2SKevin Wolf     int offset_in_cluster;
205668d100e9SKevin Wolf     int ret;
2057d46a0bb2SKevin Wolf     unsigned int cur_bytes; /* number of sectors in current iteration */
2058c2bdd990SFrediano Ziglio     uint64_t cluster_offset;
20593fc48d09SFrediano Ziglio     QEMUIOVector hd_qiov;
20603fc48d09SFrediano Ziglio     uint64_t bytes_done = 0;
20613fc48d09SFrediano Ziglio     uint8_t *cluster_data = NULL;
20628d2497c3SKevin Wolf     QCowL2Meta *l2meta = NULL;
2063c2271403SFrediano Ziglio 
2064d46a0bb2SKevin Wolf     trace_qcow2_writev_start_req(qemu_coroutine_self(), offset, bytes);
20653cce16f4SKevin Wolf 
20663fc48d09SFrediano Ziglio     qemu_iovec_init(&hd_qiov, qiov->niov);
2067585f8587Sbellard 
20683fc48d09SFrediano Ziglio     qemu_co_mutex_lock(&s->lock);
20693fc48d09SFrediano Ziglio 
2070d46a0bb2SKevin Wolf     while (bytes != 0) {
20713fc48d09SFrediano Ziglio 
2072f50f88b9SKevin Wolf         l2meta = NULL;
2073cf5c1a23SKevin Wolf 
20743cce16f4SKevin Wolf         trace_qcow2_writev_start_part(qemu_coroutine_self());
2075d46a0bb2SKevin Wolf         offset_in_cluster = offset_into_cluster(s, offset);
2076d46a0bb2SKevin Wolf         cur_bytes = MIN(bytes, INT_MAX);
2077d46a0bb2SKevin Wolf         if (bs->encrypted) {
2078d46a0bb2SKevin Wolf             cur_bytes = MIN(cur_bytes,
2079d46a0bb2SKevin Wolf                             QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size
2080d46a0bb2SKevin Wolf                             - offset_in_cluster);
20815ebaa27eSFrediano Ziglio         }
2082095a9c58Saliguori 
2083d46a0bb2SKevin Wolf         ret = qcow2_alloc_cluster_offset(bs, offset, &cur_bytes,
2084d46a0bb2SKevin Wolf                                          &cluster_offset, &l2meta);
2085148da7eaSKevin Wolf         if (ret < 0) {
20863fc48d09SFrediano Ziglio             goto fail;
2087148da7eaSKevin Wolf         }
2088148da7eaSKevin Wolf 
2089c2bdd990SFrediano Ziglio         assert((cluster_offset & 511) == 0);
2090148da7eaSKevin Wolf 
20913fc48d09SFrediano Ziglio         qemu_iovec_reset(&hd_qiov);
2092d46a0bb2SKevin Wolf         qemu_iovec_concat(&hd_qiov, qiov, bytes_done, cur_bytes);
20936f5f060bSKevin Wolf 
20948336aafaSDaniel P. Berrange         if (bs->encrypted) {
2095b25b387fSDaniel P. Berrange             assert(s->crypto);
20963fc48d09SFrediano Ziglio             if (!cluster_data) {
20979a4f4c31SKevin Wolf                 cluster_data = qemu_try_blockalign(bs->file->bs,
2098de82815dSKevin Wolf                                                    QCOW_MAX_CRYPT_CLUSTERS
2099de82815dSKevin Wolf                                                    * s->cluster_size);
2100de82815dSKevin Wolf                 if (cluster_data == NULL) {
2101de82815dSKevin Wolf                     ret = -ENOMEM;
2102de82815dSKevin Wolf                     goto fail;
2103de82815dSKevin Wolf                 }
2104585f8587Sbellard             }
21056f5f060bSKevin Wolf 
21063fc48d09SFrediano Ziglio             assert(hd_qiov.size <=
21075ebaa27eSFrediano Ziglio                    QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
2108d5e6b161SMichael Tokarev             qemu_iovec_to_buf(&hd_qiov, 0, cluster_data, hd_qiov.size);
21096f5f060bSKevin Wolf 
21104652b8f3SDaniel P. Berrange             if (qcrypto_block_encrypt(s->crypto,
21114652b8f3SDaniel P. Berrange                                       (s->crypt_physical_offset ?
21124652b8f3SDaniel P. Berrange                                        cluster_offset + offset_in_cluster :
21134609742aSDaniel P. Berrange                                        offset),
2114446d306dSDaniel P. Berrange                                       cluster_data,
2115c3a8fe33SAlberto Garcia                                       cur_bytes, NULL) < 0) {
2116f6fa64f6SDaniel P. Berrange                 ret = -EIO;
2117f6fa64f6SDaniel P. Berrange                 goto fail;
2118f6fa64f6SDaniel P. Berrange             }
21196f5f060bSKevin Wolf 
21203fc48d09SFrediano Ziglio             qemu_iovec_reset(&hd_qiov);
2121d46a0bb2SKevin Wolf             qemu_iovec_add(&hd_qiov, cluster_data, cur_bytes);
2122585f8587Sbellard         }
21236f5f060bSKevin Wolf 
2124231bb267SMax Reitz         ret = qcow2_pre_write_overlap_check(bs, 0,
2125d46a0bb2SKevin Wolf                 cluster_offset + offset_in_cluster, cur_bytes);
2126cf93980eSMax Reitz         if (ret < 0) {
2127cf93980eSMax Reitz             goto fail;
2128cf93980eSMax Reitz         }
2129cf93980eSMax Reitz 
2130ee22a9d8SAlberto Garcia         /* If we need to do COW, check if it's possible to merge the
2131ee22a9d8SAlberto Garcia          * writing of the guest data together with that of the COW regions.
2132ee22a9d8SAlberto Garcia          * If it's not possible (or not necessary) then write the
2133ee22a9d8SAlberto Garcia          * guest data now. */
2134ee22a9d8SAlberto Garcia         if (!merge_cow(offset, cur_bytes, &hd_qiov, l2meta)) {
213568d100e9SKevin Wolf             qemu_co_mutex_unlock(&s->lock);
213667a7a0ebSKevin Wolf             BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO);
21373cce16f4SKevin Wolf             trace_qcow2_writev_data(qemu_coroutine_self(),
2138d46a0bb2SKevin Wolf                                     cluster_offset + offset_in_cluster);
2139a03ef88fSKevin Wolf             ret = bdrv_co_pwritev(bs->file,
2140d46a0bb2SKevin Wolf                                   cluster_offset + offset_in_cluster,
2141d46a0bb2SKevin Wolf                                   cur_bytes, &hd_qiov, 0);
214268d100e9SKevin Wolf             qemu_co_mutex_lock(&s->lock);
214368d100e9SKevin Wolf             if (ret < 0) {
21443fc48d09SFrediano Ziglio                 goto fail;
2145171e3d6bSKevin Wolf             }
2146ee22a9d8SAlberto Garcia         }
2147f141eafeSaliguori 
2148fd9fcd37SFam Zheng         ret = qcow2_handle_l2meta(bs, &l2meta, true);
2149fd9fcd37SFam Zheng         if (ret) {
21503fc48d09SFrediano Ziglio             goto fail;
2151faf575c1SFrediano Ziglio         }
2152faf575c1SFrediano Ziglio 
2153d46a0bb2SKevin Wolf         bytes -= cur_bytes;
2154d46a0bb2SKevin Wolf         offset += cur_bytes;
2155d46a0bb2SKevin Wolf         bytes_done += cur_bytes;
2156d46a0bb2SKevin Wolf         trace_qcow2_writev_done_part(qemu_coroutine_self(), cur_bytes);
21575ebaa27eSFrediano Ziglio     }
21583fc48d09SFrediano Ziglio     ret = 0;
2159faf575c1SFrediano Ziglio 
21603fc48d09SFrediano Ziglio fail:
2161fd9fcd37SFam Zheng     qcow2_handle_l2meta(bs, &l2meta, false);
21620fa9131aSKevin Wolf 
2163a8c57408SPaolo Bonzini     qemu_co_mutex_unlock(&s->lock);
2164a8c57408SPaolo Bonzini 
21653fc48d09SFrediano Ziglio     qemu_iovec_destroy(&hd_qiov);
2166dea43a65SFrediano Ziglio     qemu_vfree(cluster_data);
21673cce16f4SKevin Wolf     trace_qcow2_writev_done_req(qemu_coroutine_self(), ret);
216842496d62SKevin Wolf 
216968d100e9SKevin Wolf     return ret;
2170585f8587Sbellard }
2171585f8587Sbellard 
2172ec6d8912SKevin Wolf static int qcow2_inactivate(BlockDriverState *bs)
2173ec6d8912SKevin Wolf {
2174ec6d8912SKevin Wolf     BDRVQcow2State *s = bs->opaque;
2175ec6d8912SKevin Wolf     int ret, result = 0;
21765f72826eSVladimir Sementsov-Ogievskiy     Error *local_err = NULL;
2177ec6d8912SKevin Wolf 
217883a8c775SPavel Butsykin     qcow2_store_persistent_dirty_bitmaps(bs, &local_err);
217983a8c775SPavel Butsykin     if (local_err != NULL) {
218083a8c775SPavel Butsykin         result = -EINVAL;
2181132adb68SVladimir Sementsov-Ogievskiy         error_reportf_err(local_err, "Lost persistent bitmaps during "
2182132adb68SVladimir Sementsov-Ogievskiy                           "inactivation of node '%s': ",
218383a8c775SPavel Butsykin                           bdrv_get_device_or_node_name(bs));
218483a8c775SPavel Butsykin     }
218583a8c775SPavel Butsykin 
2186ec6d8912SKevin Wolf     ret = qcow2_cache_flush(bs, s->l2_table_cache);
2187ec6d8912SKevin Wolf     if (ret) {
2188ec6d8912SKevin Wolf         result = ret;
2189ec6d8912SKevin Wolf         error_report("Failed to flush the L2 table cache: %s",
2190ec6d8912SKevin Wolf                      strerror(-ret));
2191ec6d8912SKevin Wolf     }
2192ec6d8912SKevin Wolf 
2193ec6d8912SKevin Wolf     ret = qcow2_cache_flush(bs, s->refcount_block_cache);
2194ec6d8912SKevin Wolf     if (ret) {
2195ec6d8912SKevin Wolf         result = ret;
2196ec6d8912SKevin Wolf         error_report("Failed to flush the refcount block cache: %s",
2197ec6d8912SKevin Wolf                      strerror(-ret));
2198ec6d8912SKevin Wolf     }
2199ec6d8912SKevin Wolf 
2200ec6d8912SKevin Wolf     if (result == 0) {
2201ec6d8912SKevin Wolf         qcow2_mark_clean(bs);
2202ec6d8912SKevin Wolf     }
2203ec6d8912SKevin Wolf 
2204ec6d8912SKevin Wolf     return result;
2205ec6d8912SKevin Wolf }
2206ec6d8912SKevin Wolf 
22077c80ab3fSJes Sorensen static void qcow2_close(BlockDriverState *bs)
2208585f8587Sbellard {
2209ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
2210de82815dSKevin Wolf     qemu_vfree(s->l1_table);
2211cf93980eSMax Reitz     /* else pre-write overlap checks in cache_destroy may crash */
2212cf93980eSMax Reitz     s->l1_table = NULL;
221329c1a730SKevin Wolf 
2214140fd5a6SKevin Wolf     if (!(s->flags & BDRV_O_INACTIVE)) {
2215ec6d8912SKevin Wolf         qcow2_inactivate(bs);
22163b5e14c7SMax Reitz     }
2217c61d0004SStefan Hajnoczi 
2218279621c0SAlberto Garcia     cache_clean_timer_del(bs);
2219e64d4072SAlberto Garcia     qcow2_cache_destroy(s->l2_table_cache);
2220e64d4072SAlberto Garcia     qcow2_cache_destroy(s->refcount_block_cache);
222129c1a730SKevin Wolf 
2222b25b387fSDaniel P. Berrange     qcrypto_block_free(s->crypto);
2223b25b387fSDaniel P. Berrange     s->crypto = NULL;
2224f6fa64f6SDaniel P. Berrange 
22256744cbabSKevin Wolf     g_free(s->unknown_header_fields);
222675bab85cSKevin Wolf     cleanup_unknown_header_ext(bs);
22276744cbabSKevin Wolf 
2228e4603fe1SKevin Wolf     g_free(s->image_backing_file);
2229e4603fe1SKevin Wolf     g_free(s->image_backing_format);
2230e4603fe1SKevin Wolf 
2231ed6ccf0fSKevin Wolf     qcow2_refcount_close(bs);
223228c1202bSLi Zhi Hui     qcow2_free_snapshots(bs);
2233585f8587Sbellard }
2234585f8587Sbellard 
22352b148f39SPaolo Bonzini static void coroutine_fn qcow2_co_invalidate_cache(BlockDriverState *bs,
22362b148f39SPaolo Bonzini                                                    Error **errp)
223706d9260fSAnthony Liguori {
2238ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
223906d9260fSAnthony Liguori     int flags = s->flags;
2240b25b387fSDaniel P. Berrange     QCryptoBlock *crypto = NULL;
2241acdfb480SKevin Wolf     QDict *options;
22425a8a30dbSKevin Wolf     Error *local_err = NULL;
22435a8a30dbSKevin Wolf     int ret;
224406d9260fSAnthony Liguori 
224506d9260fSAnthony Liguori     /*
224606d9260fSAnthony Liguori      * Backing files are read-only which makes all of their metadata immutable,
224706d9260fSAnthony Liguori      * that means we don't have to worry about reopening them here.
224806d9260fSAnthony Liguori      */
224906d9260fSAnthony Liguori 
2250b25b387fSDaniel P. Berrange     crypto = s->crypto;
2251b25b387fSDaniel P. Berrange     s->crypto = NULL;
225206d9260fSAnthony Liguori 
225306d9260fSAnthony Liguori     qcow2_close(bs);
225406d9260fSAnthony Liguori 
2255ff99129aSKevin Wolf     memset(s, 0, sizeof(BDRVQcow2State));
2256d475e5acSKevin Wolf     options = qdict_clone_shallow(bs->options);
22575a8a30dbSKevin Wolf 
2258140fd5a6SKevin Wolf     flags &= ~BDRV_O_INACTIVE;
22592b148f39SPaolo Bonzini     qemu_co_mutex_lock(&s->lock);
22604e4bf5c4SKevin Wolf     ret = qcow2_do_open(bs, options, flags, &local_err);
22612b148f39SPaolo Bonzini     qemu_co_mutex_unlock(&s->lock);
2262cb3e7f08SMarc-André Lureau     qobject_unref(options);
22635a8a30dbSKevin Wolf     if (local_err) {
22644b576648SMarkus Armbruster         error_propagate_prepend(errp, local_err,
22654b576648SMarkus Armbruster                                 "Could not reopen qcow2 layer: ");
2266191fb11bSKevin Wolf         bs->drv = NULL;
22675a8a30dbSKevin Wolf         return;
22685a8a30dbSKevin Wolf     } else if (ret < 0) {
22695a8a30dbSKevin Wolf         error_setg_errno(errp, -ret, "Could not reopen qcow2 layer");
2270191fb11bSKevin Wolf         bs->drv = NULL;
22715a8a30dbSKevin Wolf         return;
22725a8a30dbSKevin Wolf     }
2273acdfb480SKevin Wolf 
2274b25b387fSDaniel P. Berrange     s->crypto = crypto;
227506d9260fSAnthony Liguori }
227606d9260fSAnthony Liguori 
2277e24e49e6SKevin Wolf static size_t header_ext_add(char *buf, uint32_t magic, const void *s,
2278e24e49e6SKevin Wolf     size_t len, size_t buflen)
2279756e6736SKevin Wolf {
2280e24e49e6SKevin Wolf     QCowExtension *ext_backing_fmt = (QCowExtension*) buf;
2281e24e49e6SKevin Wolf     size_t ext_len = sizeof(QCowExtension) + ((len + 7) & ~7);
2282756e6736SKevin Wolf 
2283e24e49e6SKevin Wolf     if (buflen < ext_len) {
2284756e6736SKevin Wolf         return -ENOSPC;
2285756e6736SKevin Wolf     }
2286756e6736SKevin Wolf 
2287e24e49e6SKevin Wolf     *ext_backing_fmt = (QCowExtension) {
2288e24e49e6SKevin Wolf         .magic  = cpu_to_be32(magic),
2289e24e49e6SKevin Wolf         .len    = cpu_to_be32(len),
2290e24e49e6SKevin Wolf     };
22910647d47cSStefan Hajnoczi 
22920647d47cSStefan Hajnoczi     if (len) {
2293e24e49e6SKevin Wolf         memcpy(buf + sizeof(QCowExtension), s, len);
22940647d47cSStefan Hajnoczi     }
2295756e6736SKevin Wolf 
2296e24e49e6SKevin Wolf     return ext_len;
2297756e6736SKevin Wolf }
2298756e6736SKevin Wolf 
2299e24e49e6SKevin Wolf /*
2300e24e49e6SKevin Wolf  * Updates the qcow2 header, including the variable length parts of it, i.e.
2301e24e49e6SKevin Wolf  * the backing file name and all extensions. qcow2 was not designed to allow
2302e24e49e6SKevin Wolf  * such changes, so if we run out of space (we can only use the first cluster)
2303e24e49e6SKevin Wolf  * this function may fail.
2304e24e49e6SKevin Wolf  *
2305e24e49e6SKevin Wolf  * Returns 0 on success, -errno in error cases.
2306e24e49e6SKevin Wolf  */
2307e24e49e6SKevin Wolf int qcow2_update_header(BlockDriverState *bs)
2308e24e49e6SKevin Wolf {
2309ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
2310e24e49e6SKevin Wolf     QCowHeader *header;
2311e24e49e6SKevin Wolf     char *buf;
2312e24e49e6SKevin Wolf     size_t buflen = s->cluster_size;
2313e24e49e6SKevin Wolf     int ret;
2314e24e49e6SKevin Wolf     uint64_t total_size;
2315e24e49e6SKevin Wolf     uint32_t refcount_table_clusters;
23166744cbabSKevin Wolf     size_t header_length;
231775bab85cSKevin Wolf     Qcow2UnknownHeaderExtension *uext;
2318e24e49e6SKevin Wolf 
2319e24e49e6SKevin Wolf     buf = qemu_blockalign(bs, buflen);
2320e24e49e6SKevin Wolf 
2321e24e49e6SKevin Wolf     /* Header structure */
2322e24e49e6SKevin Wolf     header = (QCowHeader*) buf;
2323e24e49e6SKevin Wolf 
2324e24e49e6SKevin Wolf     if (buflen < sizeof(*header)) {
2325e24e49e6SKevin Wolf         ret = -ENOSPC;
2326e24e49e6SKevin Wolf         goto fail;
2327756e6736SKevin Wolf     }
2328756e6736SKevin Wolf 
23296744cbabSKevin Wolf     header_length = sizeof(*header) + s->unknown_header_fields_size;
2330e24e49e6SKevin Wolf     total_size = bs->total_sectors * BDRV_SECTOR_SIZE;
2331e24e49e6SKevin Wolf     refcount_table_clusters = s->refcount_table_size >> (s->cluster_bits - 3);
2332e24e49e6SKevin Wolf 
2333e24e49e6SKevin Wolf     *header = (QCowHeader) {
23346744cbabSKevin Wolf         /* Version 2 fields */
2335e24e49e6SKevin Wolf         .magic                  = cpu_to_be32(QCOW_MAGIC),
23366744cbabSKevin Wolf         .version                = cpu_to_be32(s->qcow_version),
2337e24e49e6SKevin Wolf         .backing_file_offset    = 0,
2338e24e49e6SKevin Wolf         .backing_file_size      = 0,
2339e24e49e6SKevin Wolf         .cluster_bits           = cpu_to_be32(s->cluster_bits),
2340e24e49e6SKevin Wolf         .size                   = cpu_to_be64(total_size),
2341e24e49e6SKevin Wolf         .crypt_method           = cpu_to_be32(s->crypt_method_header),
2342e24e49e6SKevin Wolf         .l1_size                = cpu_to_be32(s->l1_size),
2343e24e49e6SKevin Wolf         .l1_table_offset        = cpu_to_be64(s->l1_table_offset),
2344e24e49e6SKevin Wolf         .refcount_table_offset  = cpu_to_be64(s->refcount_table_offset),
2345e24e49e6SKevin Wolf         .refcount_table_clusters = cpu_to_be32(refcount_table_clusters),
2346e24e49e6SKevin Wolf         .nb_snapshots           = cpu_to_be32(s->nb_snapshots),
2347e24e49e6SKevin Wolf         .snapshots_offset       = cpu_to_be64(s->snapshots_offset),
23486744cbabSKevin Wolf 
23496744cbabSKevin Wolf         /* Version 3 fields */
23506744cbabSKevin Wolf         .incompatible_features  = cpu_to_be64(s->incompatible_features),
23516744cbabSKevin Wolf         .compatible_features    = cpu_to_be64(s->compatible_features),
23526744cbabSKevin Wolf         .autoclear_features     = cpu_to_be64(s->autoclear_features),
2353b6481f37SMax Reitz         .refcount_order         = cpu_to_be32(s->refcount_order),
23546744cbabSKevin Wolf         .header_length          = cpu_to_be32(header_length),
2355e24e49e6SKevin Wolf     };
2356e24e49e6SKevin Wolf 
23576744cbabSKevin Wolf     /* For older versions, write a shorter header */
23586744cbabSKevin Wolf     switch (s->qcow_version) {
23596744cbabSKevin Wolf     case 2:
23606744cbabSKevin Wolf         ret = offsetof(QCowHeader, incompatible_features);
23616744cbabSKevin Wolf         break;
23626744cbabSKevin Wolf     case 3:
23636744cbabSKevin Wolf         ret = sizeof(*header);
23646744cbabSKevin Wolf         break;
23656744cbabSKevin Wolf     default:
2366b6c14762SJim Meyering         ret = -EINVAL;
2367b6c14762SJim Meyering         goto fail;
23686744cbabSKevin Wolf     }
23696744cbabSKevin Wolf 
23706744cbabSKevin Wolf     buf += ret;
23716744cbabSKevin Wolf     buflen -= ret;
23726744cbabSKevin Wolf     memset(buf, 0, buflen);
23736744cbabSKevin Wolf 
23746744cbabSKevin Wolf     /* Preserve any unknown field in the header */
23756744cbabSKevin Wolf     if (s->unknown_header_fields_size) {
23766744cbabSKevin Wolf         if (buflen < s->unknown_header_fields_size) {
23776744cbabSKevin Wolf             ret = -ENOSPC;
23786744cbabSKevin Wolf             goto fail;
23796744cbabSKevin Wolf         }
23806744cbabSKevin Wolf 
23816744cbabSKevin Wolf         memcpy(buf, s->unknown_header_fields, s->unknown_header_fields_size);
23826744cbabSKevin Wolf         buf += s->unknown_header_fields_size;
23836744cbabSKevin Wolf         buflen -= s->unknown_header_fields_size;
23846744cbabSKevin Wolf     }
2385e24e49e6SKevin Wolf 
2386e24e49e6SKevin Wolf     /* Backing file format header extension */
2387e4603fe1SKevin Wolf     if (s->image_backing_format) {
2388e24e49e6SKevin Wolf         ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BACKING_FORMAT,
2389e4603fe1SKevin Wolf                              s->image_backing_format,
2390e4603fe1SKevin Wolf                              strlen(s->image_backing_format),
2391e24e49e6SKevin Wolf                              buflen);
2392756e6736SKevin Wolf         if (ret < 0) {
2393756e6736SKevin Wolf             goto fail;
2394756e6736SKevin Wolf         }
2395756e6736SKevin Wolf 
2396e24e49e6SKevin Wolf         buf += ret;
2397e24e49e6SKevin Wolf         buflen -= ret;
2398e24e49e6SKevin Wolf     }
2399756e6736SKevin Wolf 
24004652b8f3SDaniel P. Berrange     /* Full disk encryption header pointer extension */
24014652b8f3SDaniel P. Berrange     if (s->crypto_header.offset != 0) {
24023b698f52SPeter Maydell         s->crypto_header.offset = cpu_to_be64(s->crypto_header.offset);
24033b698f52SPeter Maydell         s->crypto_header.length = cpu_to_be64(s->crypto_header.length);
24044652b8f3SDaniel P. Berrange         ret = header_ext_add(buf, QCOW2_EXT_MAGIC_CRYPTO_HEADER,
24054652b8f3SDaniel P. Berrange                              &s->crypto_header, sizeof(s->crypto_header),
24064652b8f3SDaniel P. Berrange                              buflen);
24073b698f52SPeter Maydell         s->crypto_header.offset = be64_to_cpu(s->crypto_header.offset);
24083b698f52SPeter Maydell         s->crypto_header.length = be64_to_cpu(s->crypto_header.length);
24094652b8f3SDaniel P. Berrange         if (ret < 0) {
24104652b8f3SDaniel P. Berrange             goto fail;
24114652b8f3SDaniel P. Berrange         }
24124652b8f3SDaniel P. Berrange         buf += ret;
24134652b8f3SDaniel P. Berrange         buflen -= ret;
24144652b8f3SDaniel P. Berrange     }
24154652b8f3SDaniel P. Berrange 
2416cfcc4c62SKevin Wolf     /* Feature table */
24171a4828c7SKevin Wolf     if (s->qcow_version >= 3) {
2418cfcc4c62SKevin Wolf         Qcow2Feature features[] = {
2419c61d0004SStefan Hajnoczi             {
2420c61d0004SStefan Hajnoczi                 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
2421c61d0004SStefan Hajnoczi                 .bit  = QCOW2_INCOMPAT_DIRTY_BITNR,
2422c61d0004SStefan Hajnoczi                 .name = "dirty bit",
2423c61d0004SStefan Hajnoczi             },
2424bfe8043eSStefan Hajnoczi             {
242569c98726SMax Reitz                 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
242669c98726SMax Reitz                 .bit  = QCOW2_INCOMPAT_CORRUPT_BITNR,
242769c98726SMax Reitz                 .name = "corrupt bit",
242869c98726SMax Reitz             },
242969c98726SMax Reitz             {
2430bfe8043eSStefan Hajnoczi                 .type = QCOW2_FEAT_TYPE_COMPATIBLE,
2431bfe8043eSStefan Hajnoczi                 .bit  = QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR,
2432bfe8043eSStefan Hajnoczi                 .name = "lazy refcounts",
2433bfe8043eSStefan Hajnoczi             },
2434cfcc4c62SKevin Wolf         };
2435cfcc4c62SKevin Wolf 
2436cfcc4c62SKevin Wolf         ret = header_ext_add(buf, QCOW2_EXT_MAGIC_FEATURE_TABLE,
2437cfcc4c62SKevin Wolf                              features, sizeof(features), buflen);
2438cfcc4c62SKevin Wolf         if (ret < 0) {
2439cfcc4c62SKevin Wolf             goto fail;
2440cfcc4c62SKevin Wolf         }
2441cfcc4c62SKevin Wolf         buf += ret;
2442cfcc4c62SKevin Wolf         buflen -= ret;
24431a4828c7SKevin Wolf     }
2444cfcc4c62SKevin Wolf 
244588ddffaeSVladimir Sementsov-Ogievskiy     /* Bitmap extension */
244688ddffaeSVladimir Sementsov-Ogievskiy     if (s->nb_bitmaps > 0) {
244788ddffaeSVladimir Sementsov-Ogievskiy         Qcow2BitmapHeaderExt bitmaps_header = {
244888ddffaeSVladimir Sementsov-Ogievskiy             .nb_bitmaps = cpu_to_be32(s->nb_bitmaps),
244988ddffaeSVladimir Sementsov-Ogievskiy             .bitmap_directory_size =
245088ddffaeSVladimir Sementsov-Ogievskiy                     cpu_to_be64(s->bitmap_directory_size),
245188ddffaeSVladimir Sementsov-Ogievskiy             .bitmap_directory_offset =
245288ddffaeSVladimir Sementsov-Ogievskiy                     cpu_to_be64(s->bitmap_directory_offset)
245388ddffaeSVladimir Sementsov-Ogievskiy         };
245488ddffaeSVladimir Sementsov-Ogievskiy         ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BITMAPS,
245588ddffaeSVladimir Sementsov-Ogievskiy                              &bitmaps_header, sizeof(bitmaps_header),
245688ddffaeSVladimir Sementsov-Ogievskiy                              buflen);
245788ddffaeSVladimir Sementsov-Ogievskiy         if (ret < 0) {
245888ddffaeSVladimir Sementsov-Ogievskiy             goto fail;
245988ddffaeSVladimir Sementsov-Ogievskiy         }
246088ddffaeSVladimir Sementsov-Ogievskiy         buf += ret;
246188ddffaeSVladimir Sementsov-Ogievskiy         buflen -= ret;
246288ddffaeSVladimir Sementsov-Ogievskiy     }
246388ddffaeSVladimir Sementsov-Ogievskiy 
246475bab85cSKevin Wolf     /* Keep unknown header extensions */
246575bab85cSKevin Wolf     QLIST_FOREACH(uext, &s->unknown_header_ext, next) {
246675bab85cSKevin Wolf         ret = header_ext_add(buf, uext->magic, uext->data, uext->len, buflen);
246775bab85cSKevin Wolf         if (ret < 0) {
246875bab85cSKevin Wolf             goto fail;
246975bab85cSKevin Wolf         }
247075bab85cSKevin Wolf 
247175bab85cSKevin Wolf         buf += ret;
247275bab85cSKevin Wolf         buflen -= ret;
247375bab85cSKevin Wolf     }
247475bab85cSKevin Wolf 
2475e24e49e6SKevin Wolf     /* End of header extensions */
2476e24e49e6SKevin Wolf     ret = header_ext_add(buf, QCOW2_EXT_MAGIC_END, NULL, 0, buflen);
2477756e6736SKevin Wolf     if (ret < 0) {
2478756e6736SKevin Wolf         goto fail;
2479756e6736SKevin Wolf     }
2480756e6736SKevin Wolf 
2481e24e49e6SKevin Wolf     buf += ret;
2482e24e49e6SKevin Wolf     buflen -= ret;
2483e24e49e6SKevin Wolf 
2484e24e49e6SKevin Wolf     /* Backing file name */
2485e4603fe1SKevin Wolf     if (s->image_backing_file) {
2486e4603fe1SKevin Wolf         size_t backing_file_len = strlen(s->image_backing_file);
2487e24e49e6SKevin Wolf 
2488e24e49e6SKevin Wolf         if (buflen < backing_file_len) {
2489e24e49e6SKevin Wolf             ret = -ENOSPC;
2490e24e49e6SKevin Wolf             goto fail;
2491e24e49e6SKevin Wolf         }
2492e24e49e6SKevin Wolf 
249300ea1881SJim Meyering         /* Using strncpy is ok here, since buf is not NUL-terminated. */
2494e4603fe1SKevin Wolf         strncpy(buf, s->image_backing_file, buflen);
2495e24e49e6SKevin Wolf 
2496e24e49e6SKevin Wolf         header->backing_file_offset = cpu_to_be64(buf - ((char*) header));
2497e24e49e6SKevin Wolf         header->backing_file_size   = cpu_to_be32(backing_file_len);
2498e24e49e6SKevin Wolf     }
2499e24e49e6SKevin Wolf 
2500e24e49e6SKevin Wolf     /* Write the new header */
2501d9ca2ea2SKevin Wolf     ret = bdrv_pwrite(bs->file, 0, header, s->cluster_size);
2502756e6736SKevin Wolf     if (ret < 0) {
2503756e6736SKevin Wolf         goto fail;
2504756e6736SKevin Wolf     }
2505756e6736SKevin Wolf 
2506756e6736SKevin Wolf     ret = 0;
2507756e6736SKevin Wolf fail:
2508e24e49e6SKevin Wolf     qemu_vfree(header);
2509756e6736SKevin Wolf     return ret;
2510756e6736SKevin Wolf }
2511756e6736SKevin Wolf 
2512756e6736SKevin Wolf static int qcow2_change_backing_file(BlockDriverState *bs,
2513756e6736SKevin Wolf     const char *backing_file, const char *backing_fmt)
2514756e6736SKevin Wolf {
2515ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
2516e4603fe1SKevin Wolf 
25174e876bcfSMax Reitz     if (backing_file && strlen(backing_file) > 1023) {
25184e876bcfSMax Reitz         return -EINVAL;
25194e876bcfSMax Reitz     }
25204e876bcfSMax Reitz 
2521e24e49e6SKevin Wolf     pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
2522e24e49e6SKevin Wolf     pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
2523e24e49e6SKevin Wolf 
2524e4603fe1SKevin Wolf     g_free(s->image_backing_file);
2525e4603fe1SKevin Wolf     g_free(s->image_backing_format);
2526e4603fe1SKevin Wolf 
2527e4603fe1SKevin Wolf     s->image_backing_file = backing_file ? g_strdup(bs->backing_file) : NULL;
2528e4603fe1SKevin Wolf     s->image_backing_format = backing_fmt ? g_strdup(bs->backing_format) : NULL;
2529e4603fe1SKevin Wolf 
2530e24e49e6SKevin Wolf     return qcow2_update_header(bs);
2531756e6736SKevin Wolf }
2532756e6736SKevin Wolf 
25334652b8f3SDaniel P. Berrange static int qcow2_crypt_method_from_format(const char *encryptfmt)
25344652b8f3SDaniel P. Berrange {
25354652b8f3SDaniel P. Berrange     if (g_str_equal(encryptfmt, "luks")) {
25364652b8f3SDaniel P. Berrange         return QCOW_CRYPT_LUKS;
25374652b8f3SDaniel P. Berrange     } else if (g_str_equal(encryptfmt, "aes")) {
25384652b8f3SDaniel P. Berrange         return QCOW_CRYPT_AES;
25394652b8f3SDaniel P. Berrange     } else {
25404652b8f3SDaniel P. Berrange         return -EINVAL;
25414652b8f3SDaniel P. Berrange     }
25424652b8f3SDaniel P. Berrange }
2543b25b387fSDaniel P. Berrange 
254460900b7bSKevin Wolf static int qcow2_set_up_encryption(BlockDriverState *bs,
254560900b7bSKevin Wolf                                    QCryptoBlockCreateOptions *cryptoopts,
254660900b7bSKevin Wolf                                    Error **errp)
254760900b7bSKevin Wolf {
254860900b7bSKevin Wolf     BDRVQcow2State *s = bs->opaque;
254960900b7bSKevin Wolf     QCryptoBlock *crypto = NULL;
255060900b7bSKevin Wolf     int fmt, ret;
255160900b7bSKevin Wolf 
255260900b7bSKevin Wolf     switch (cryptoopts->format) {
255360900b7bSKevin Wolf     case Q_CRYPTO_BLOCK_FORMAT_LUKS:
255460900b7bSKevin Wolf         fmt = QCOW_CRYPT_LUKS;
255560900b7bSKevin Wolf         break;
255660900b7bSKevin Wolf     case Q_CRYPTO_BLOCK_FORMAT_QCOW:
255760900b7bSKevin Wolf         fmt = QCOW_CRYPT_AES;
255860900b7bSKevin Wolf         break;
255960900b7bSKevin Wolf     default:
256060900b7bSKevin Wolf         error_setg(errp, "Crypto format not supported in qcow2");
256160900b7bSKevin Wolf         return -EINVAL;
256260900b7bSKevin Wolf     }
256360900b7bSKevin Wolf 
25644652b8f3SDaniel P. Berrange     s->crypt_method_header = fmt;
2565b25b387fSDaniel P. Berrange 
25661cd9a787SDaniel P. Berrange     crypto = qcrypto_block_create(cryptoopts, "encrypt.",
25674652b8f3SDaniel P. Berrange                                   qcow2_crypto_hdr_init_func,
25684652b8f3SDaniel P. Berrange                                   qcow2_crypto_hdr_write_func,
2569b25b387fSDaniel P. Berrange                                   bs, errp);
2570b25b387fSDaniel P. Berrange     if (!crypto) {
257160900b7bSKevin Wolf         return -EINVAL;
2572b25b387fSDaniel P. Berrange     }
2573b25b387fSDaniel P. Berrange 
2574b25b387fSDaniel P. Berrange     ret = qcow2_update_header(bs);
2575b25b387fSDaniel P. Berrange     if (ret < 0) {
2576b25b387fSDaniel P. Berrange         error_setg_errno(errp, -ret, "Could not write encryption header");
2577b25b387fSDaniel P. Berrange         goto out;
2578b25b387fSDaniel P. Berrange     }
2579b25b387fSDaniel P. Berrange 
258060900b7bSKevin Wolf     ret = 0;
2581b25b387fSDaniel P. Berrange  out:
2582b25b387fSDaniel P. Berrange     qcrypto_block_free(crypto);
2583b25b387fSDaniel P. Berrange     return ret;
2584b25b387fSDaniel P. Berrange }
2585b25b387fSDaniel P. Berrange 
25867bc45dc1SMax Reitz /**
25877bc45dc1SMax Reitz  * Preallocates metadata structures for data clusters between @offset (in the
25887bc45dc1SMax Reitz  * guest disk) and @new_length (which is thus generally the new guest disk
25897bc45dc1SMax Reitz  * size).
25907bc45dc1SMax Reitz  *
25917bc45dc1SMax Reitz  * Returns: 0 on success, -errno on failure.
25927bc45dc1SMax Reitz  */
259347e86b86SKevin Wolf static int coroutine_fn preallocate_co(BlockDriverState *bs, uint64_t offset,
259447e86b86SKevin Wolf                                        uint64_t new_length)
2595a35e1c17SKevin Wolf {
2596d46a0bb2SKevin Wolf     uint64_t bytes;
2597060bee89SKevin Wolf     uint64_t host_offset = 0;
2598d46a0bb2SKevin Wolf     unsigned int cur_bytes;
2599148da7eaSKevin Wolf     int ret;
2600f50f88b9SKevin Wolf     QCowL2Meta *meta;
2601a35e1c17SKevin Wolf 
26027bc45dc1SMax Reitz     assert(offset <= new_length);
26037bc45dc1SMax Reitz     bytes = new_length - offset;
2604a35e1c17SKevin Wolf 
2605d46a0bb2SKevin Wolf     while (bytes) {
2606d46a0bb2SKevin Wolf         cur_bytes = MIN(bytes, INT_MAX);
2607d46a0bb2SKevin Wolf         ret = qcow2_alloc_cluster_offset(bs, offset, &cur_bytes,
2608060bee89SKevin Wolf                                          &host_offset, &meta);
2609148da7eaSKevin Wolf         if (ret < 0) {
261047e86b86SKevin Wolf             return ret;
2611a35e1c17SKevin Wolf         }
2612a35e1c17SKevin Wolf 
2613c792707fSStefan Hajnoczi         while (meta) {
2614c792707fSStefan Hajnoczi             QCowL2Meta *next = meta->next;
2615c792707fSStefan Hajnoczi 
2616f50f88b9SKevin Wolf             ret = qcow2_alloc_cluster_link_l2(bs, meta);
261719dbcbf7SKevin Wolf             if (ret < 0) {
26187c2bbf4aSHu Tao                 qcow2_free_any_clusters(bs, meta->alloc_offset,
26197c2bbf4aSHu Tao                                         meta->nb_clusters, QCOW2_DISCARD_NEVER);
262047e86b86SKevin Wolf                 return ret;
2621a35e1c17SKevin Wolf             }
2622a35e1c17SKevin Wolf 
26237c2bbf4aSHu Tao             /* There are no dependent requests, but we need to remove our
26247c2bbf4aSHu Tao              * request from the list of in-flight requests */
26254e95314eSKevin Wolf             QLIST_REMOVE(meta, next_in_flight);
2626c792707fSStefan Hajnoczi 
2627c792707fSStefan Hajnoczi             g_free(meta);
2628c792707fSStefan Hajnoczi             meta = next;
2629f50f88b9SKevin Wolf         }
2630f214978aSKevin Wolf 
2631a35e1c17SKevin Wolf         /* TODO Preallocate data if requested */
2632a35e1c17SKevin Wolf 
2633d46a0bb2SKevin Wolf         bytes -= cur_bytes;
2634d46a0bb2SKevin Wolf         offset += cur_bytes;
2635a35e1c17SKevin Wolf     }
2636a35e1c17SKevin Wolf 
2637a35e1c17SKevin Wolf     /*
2638a35e1c17SKevin Wolf      * It is expected that the image file is large enough to actually contain
2639a35e1c17SKevin Wolf      * all of the allocated clusters (otherwise we get failing reads after
2640a35e1c17SKevin Wolf      * EOF). Extend the image to the last allocated sector.
2641a35e1c17SKevin Wolf      */
2642060bee89SKevin Wolf     if (host_offset != 0) {
2643d46a0bb2SKevin Wolf         uint8_t data = 0;
2644d9ca2ea2SKevin Wolf         ret = bdrv_pwrite(bs->file, (host_offset + cur_bytes) - 1,
2645d46a0bb2SKevin Wolf                           &data, 1);
264619dbcbf7SKevin Wolf         if (ret < 0) {
264747e86b86SKevin Wolf             return ret;
264819dbcbf7SKevin Wolf         }
2649a35e1c17SKevin Wolf     }
2650a35e1c17SKevin Wolf 
265147e86b86SKevin Wolf     return 0;
2652a35e1c17SKevin Wolf }
2653a35e1c17SKevin Wolf 
26547c5bcc42SStefan Hajnoczi /* qcow2_refcount_metadata_size:
26557c5bcc42SStefan Hajnoczi  * @clusters: number of clusters to refcount (including data and L1/L2 tables)
26567c5bcc42SStefan Hajnoczi  * @cluster_size: size of a cluster, in bytes
26577c5bcc42SStefan Hajnoczi  * @refcount_order: refcount bits power-of-2 exponent
265812cc30a8SMax Reitz  * @generous_increase: allow for the refcount table to be 1.5x as large as it
265912cc30a8SMax Reitz  *                     needs to be
26607c5bcc42SStefan Hajnoczi  *
26617c5bcc42SStefan Hajnoczi  * Returns: Number of bytes required for refcount blocks and table metadata.
26627c5bcc42SStefan Hajnoczi  */
266312cc30a8SMax Reitz int64_t qcow2_refcount_metadata_size(int64_t clusters, size_t cluster_size,
266412cc30a8SMax Reitz                                      int refcount_order, bool generous_increase,
266512cc30a8SMax Reitz                                      uint64_t *refblock_count)
26667c5bcc42SStefan Hajnoczi {
26677c5bcc42SStefan Hajnoczi     /*
26687c5bcc42SStefan Hajnoczi      * Every host cluster is reference-counted, including metadata (even
26697c5bcc42SStefan Hajnoczi      * refcount metadata is recursively included).
26707c5bcc42SStefan Hajnoczi      *
26717c5bcc42SStefan Hajnoczi      * An accurate formula for the size of refcount metadata size is difficult
26727c5bcc42SStefan Hajnoczi      * to derive.  An easier method of calculation is finding the fixed point
26737c5bcc42SStefan Hajnoczi      * where no further refcount blocks or table clusters are required to
26747c5bcc42SStefan Hajnoczi      * reference count every cluster.
26757c5bcc42SStefan Hajnoczi      */
26767c5bcc42SStefan Hajnoczi     int64_t blocks_per_table_cluster = cluster_size / sizeof(uint64_t);
26777c5bcc42SStefan Hajnoczi     int64_t refcounts_per_block = cluster_size * 8 / (1 << refcount_order);
26787c5bcc42SStefan Hajnoczi     int64_t table = 0;  /* number of refcount table clusters */
26797c5bcc42SStefan Hajnoczi     int64_t blocks = 0; /* number of refcount block clusters */
26807c5bcc42SStefan Hajnoczi     int64_t last;
26817c5bcc42SStefan Hajnoczi     int64_t n = 0;
26827c5bcc42SStefan Hajnoczi 
26837c5bcc42SStefan Hajnoczi     do {
26847c5bcc42SStefan Hajnoczi         last = n;
26857c5bcc42SStefan Hajnoczi         blocks = DIV_ROUND_UP(clusters + table + blocks, refcounts_per_block);
26867c5bcc42SStefan Hajnoczi         table = DIV_ROUND_UP(blocks, blocks_per_table_cluster);
26877c5bcc42SStefan Hajnoczi         n = clusters + blocks + table;
268812cc30a8SMax Reitz 
268912cc30a8SMax Reitz         if (n == last && generous_increase) {
269012cc30a8SMax Reitz             clusters += DIV_ROUND_UP(table, 2);
269112cc30a8SMax Reitz             n = 0; /* force another loop */
269212cc30a8SMax Reitz             generous_increase = false;
269312cc30a8SMax Reitz         }
26947c5bcc42SStefan Hajnoczi     } while (n != last);
26957c5bcc42SStefan Hajnoczi 
269612cc30a8SMax Reitz     if (refblock_count) {
269712cc30a8SMax Reitz         *refblock_count = blocks;
269812cc30a8SMax Reitz     }
269912cc30a8SMax Reitz 
27007c5bcc42SStefan Hajnoczi     return (blocks + table) * cluster_size;
27017c5bcc42SStefan Hajnoczi }
27027c5bcc42SStefan Hajnoczi 
270395c67e3bSStefan Hajnoczi /**
270495c67e3bSStefan Hajnoczi  * qcow2_calc_prealloc_size:
270595c67e3bSStefan Hajnoczi  * @total_size: virtual disk size in bytes
270695c67e3bSStefan Hajnoczi  * @cluster_size: cluster size in bytes
270795c67e3bSStefan Hajnoczi  * @refcount_order: refcount bits power-of-2 exponent
2708a9420734SKevin Wolf  *
270995c67e3bSStefan Hajnoczi  * Returns: Total number of bytes required for the fully allocated image
271095c67e3bSStefan Hajnoczi  * (including metadata).
2711a9420734SKevin Wolf  */
271295c67e3bSStefan Hajnoczi static int64_t qcow2_calc_prealloc_size(int64_t total_size,
271395c67e3bSStefan Hajnoczi                                         size_t cluster_size,
271495c67e3bSStefan Hajnoczi                                         int refcount_order)
271595c67e3bSStefan Hajnoczi {
27160e4271b7SHu Tao     int64_t meta_size = 0;
27177c5bcc42SStefan Hajnoczi     uint64_t nl1e, nl2e;
27189e029689SAlberto Garcia     int64_t aligned_total_size = ROUND_UP(total_size, cluster_size);
27190e4271b7SHu Tao 
27200e4271b7SHu Tao     /* header: 1 cluster */
27210e4271b7SHu Tao     meta_size += cluster_size;
27220e4271b7SHu Tao 
27230e4271b7SHu Tao     /* total size of L2 tables */
27240e4271b7SHu Tao     nl2e = aligned_total_size / cluster_size;
27259e029689SAlberto Garcia     nl2e = ROUND_UP(nl2e, cluster_size / sizeof(uint64_t));
27260e4271b7SHu Tao     meta_size += nl2e * sizeof(uint64_t);
27270e4271b7SHu Tao 
27280e4271b7SHu Tao     /* total size of L1 tables */
27290e4271b7SHu Tao     nl1e = nl2e * sizeof(uint64_t) / cluster_size;
27309e029689SAlberto Garcia     nl1e = ROUND_UP(nl1e, cluster_size / sizeof(uint64_t));
27310e4271b7SHu Tao     meta_size += nl1e * sizeof(uint64_t);
27320e4271b7SHu Tao 
27337c5bcc42SStefan Hajnoczi     /* total size of refcount table and blocks */
27347c5bcc42SStefan Hajnoczi     meta_size += qcow2_refcount_metadata_size(
27357c5bcc42SStefan Hajnoczi             (meta_size + aligned_total_size) / cluster_size,
273612cc30a8SMax Reitz             cluster_size, refcount_order, false, NULL);
27370e4271b7SHu Tao 
273895c67e3bSStefan Hajnoczi     return meta_size + aligned_total_size;
273995c67e3bSStefan Hajnoczi }
274095c67e3bSStefan Hajnoczi 
274129ca9e45SKevin Wolf static bool validate_cluster_size(size_t cluster_size, Error **errp)
274295c67e3bSStefan Hajnoczi {
274329ca9e45SKevin Wolf     int cluster_bits = ctz32(cluster_size);
274495c67e3bSStefan Hajnoczi     if (cluster_bits < MIN_CLUSTER_BITS || cluster_bits > MAX_CLUSTER_BITS ||
274595c67e3bSStefan Hajnoczi         (1 << cluster_bits) != cluster_size)
274695c67e3bSStefan Hajnoczi     {
274795c67e3bSStefan Hajnoczi         error_setg(errp, "Cluster size must be a power of two between %d and "
274895c67e3bSStefan Hajnoczi                    "%dk", 1 << MIN_CLUSTER_BITS, 1 << (MAX_CLUSTER_BITS - 10));
274929ca9e45SKevin Wolf         return false;
275029ca9e45SKevin Wolf     }
275129ca9e45SKevin Wolf     return true;
275229ca9e45SKevin Wolf }
275329ca9e45SKevin Wolf 
275429ca9e45SKevin Wolf static size_t qcow2_opt_get_cluster_size_del(QemuOpts *opts, Error **errp)
275529ca9e45SKevin Wolf {
275629ca9e45SKevin Wolf     size_t cluster_size;
275729ca9e45SKevin Wolf 
275829ca9e45SKevin Wolf     cluster_size = qemu_opt_get_size_del(opts, BLOCK_OPT_CLUSTER_SIZE,
275929ca9e45SKevin Wolf                                          DEFAULT_CLUSTER_SIZE);
276029ca9e45SKevin Wolf     if (!validate_cluster_size(cluster_size, errp)) {
27610eb4a8c1SStefan Hajnoczi         return 0;
276295c67e3bSStefan Hajnoczi     }
27630eb4a8c1SStefan Hajnoczi     return cluster_size;
27640eb4a8c1SStefan Hajnoczi }
27650eb4a8c1SStefan Hajnoczi 
27660eb4a8c1SStefan Hajnoczi static int qcow2_opt_get_version_del(QemuOpts *opts, Error **errp)
27670eb4a8c1SStefan Hajnoczi {
27680eb4a8c1SStefan Hajnoczi     char *buf;
27690eb4a8c1SStefan Hajnoczi     int ret;
27700eb4a8c1SStefan Hajnoczi 
27710eb4a8c1SStefan Hajnoczi     buf = qemu_opt_get_del(opts, BLOCK_OPT_COMPAT_LEVEL);
27720eb4a8c1SStefan Hajnoczi     if (!buf) {
27730eb4a8c1SStefan Hajnoczi         ret = 3; /* default */
27740eb4a8c1SStefan Hajnoczi     } else if (!strcmp(buf, "0.10")) {
27750eb4a8c1SStefan Hajnoczi         ret = 2;
27760eb4a8c1SStefan Hajnoczi     } else if (!strcmp(buf, "1.1")) {
27770eb4a8c1SStefan Hajnoczi         ret = 3;
27780eb4a8c1SStefan Hajnoczi     } else {
27790eb4a8c1SStefan Hajnoczi         error_setg(errp, "Invalid compatibility level: '%s'", buf);
27800eb4a8c1SStefan Hajnoczi         ret = -EINVAL;
27810eb4a8c1SStefan Hajnoczi     }
27820eb4a8c1SStefan Hajnoczi     g_free(buf);
27830eb4a8c1SStefan Hajnoczi     return ret;
27840eb4a8c1SStefan Hajnoczi }
27850eb4a8c1SStefan Hajnoczi 
27860eb4a8c1SStefan Hajnoczi static uint64_t qcow2_opt_get_refcount_bits_del(QemuOpts *opts, int version,
27870eb4a8c1SStefan Hajnoczi                                                 Error **errp)
27880eb4a8c1SStefan Hajnoczi {
27890eb4a8c1SStefan Hajnoczi     uint64_t refcount_bits;
27900eb4a8c1SStefan Hajnoczi 
27910eb4a8c1SStefan Hajnoczi     refcount_bits = qemu_opt_get_number_del(opts, BLOCK_OPT_REFCOUNT_BITS, 16);
27920eb4a8c1SStefan Hajnoczi     if (refcount_bits > 64 || !is_power_of_2(refcount_bits)) {
27930eb4a8c1SStefan Hajnoczi         error_setg(errp, "Refcount width must be a power of two and may not "
27940eb4a8c1SStefan Hajnoczi                    "exceed 64 bits");
27950eb4a8c1SStefan Hajnoczi         return 0;
27960eb4a8c1SStefan Hajnoczi     }
27970eb4a8c1SStefan Hajnoczi 
27980eb4a8c1SStefan Hajnoczi     if (version < 3 && refcount_bits != 16) {
27990eb4a8c1SStefan Hajnoczi         error_setg(errp, "Different refcount widths than 16 bits require "
28000eb4a8c1SStefan Hajnoczi                    "compatibility level 1.1 or above (use compat=1.1 or "
28010eb4a8c1SStefan Hajnoczi                    "greater)");
28020eb4a8c1SStefan Hajnoczi         return 0;
28030eb4a8c1SStefan Hajnoczi     }
28040eb4a8c1SStefan Hajnoczi 
28050eb4a8c1SStefan Hajnoczi     return refcount_bits;
28060eb4a8c1SStefan Hajnoczi }
28070eb4a8c1SStefan Hajnoczi 
2808c274393aSStefan Hajnoczi static int coroutine_fn
280960900b7bSKevin Wolf qcow2_co_create(BlockdevCreateOptions *create_options, Error **errp)
28100eb4a8c1SStefan Hajnoczi {
281129ca9e45SKevin Wolf     BlockdevCreateOptionsQcow2 *qcow2_opts;
28120eb4a8c1SStefan Hajnoczi     QDict *options;
281395c67e3bSStefan Hajnoczi 
281495c67e3bSStefan Hajnoczi     /*
281595c67e3bSStefan Hajnoczi      * Open the image file and write a minimal qcow2 header.
281695c67e3bSStefan Hajnoczi      *
281795c67e3bSStefan Hajnoczi      * We keep things simple and start with a zero-sized image. We also
281895c67e3bSStefan Hajnoczi      * do without refcount blocks or a L1 table for now. We'll fix the
281995c67e3bSStefan Hajnoczi      * inconsistency later.
282095c67e3bSStefan Hajnoczi      *
282195c67e3bSStefan Hajnoczi      * We do need a refcount table because growing the refcount table means
282295c67e3bSStefan Hajnoczi      * allocating two new refcount blocks - the seconds of which would be at
282395c67e3bSStefan Hajnoczi      * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
282495c67e3bSStefan Hajnoczi      * size for any qcow2 image.
282595c67e3bSStefan Hajnoczi      */
2826e1d74bc6SKevin Wolf     BlockBackend *blk = NULL;
2827e1d74bc6SKevin Wolf     BlockDriverState *bs = NULL;
282895c67e3bSStefan Hajnoczi     QCowHeader *header;
282929ca9e45SKevin Wolf     size_t cluster_size;
283029ca9e45SKevin Wolf     int version;
283129ca9e45SKevin Wolf     int refcount_order;
283295c67e3bSStefan Hajnoczi     uint64_t* refcount_table;
283395c67e3bSStefan Hajnoczi     Error *local_err = NULL;
283495c67e3bSStefan Hajnoczi     int ret;
283595c67e3bSStefan Hajnoczi 
283629ca9e45SKevin Wolf     assert(create_options->driver == BLOCKDEV_DRIVER_QCOW2);
283729ca9e45SKevin Wolf     qcow2_opts = &create_options->u.qcow2;
283829ca9e45SKevin Wolf 
2839e1d74bc6SKevin Wolf     bs = bdrv_open_blockdev_ref(qcow2_opts->file, errp);
2840e1d74bc6SKevin Wolf     if (bs == NULL) {
2841e1d74bc6SKevin Wolf         return -EIO;
2842e1d74bc6SKevin Wolf     }
2843e1d74bc6SKevin Wolf 
2844e1d74bc6SKevin Wolf     /* Validate options and set default values */
284529ca9e45SKevin Wolf     if (!QEMU_IS_ALIGNED(qcow2_opts->size, BDRV_SECTOR_SIZE)) {
284629ca9e45SKevin Wolf         error_setg(errp, "Image size must be a multiple of 512 bytes");
284729ca9e45SKevin Wolf         ret = -EINVAL;
284829ca9e45SKevin Wolf         goto out;
284929ca9e45SKevin Wolf     }
285029ca9e45SKevin Wolf 
285129ca9e45SKevin Wolf     if (qcow2_opts->has_version) {
285229ca9e45SKevin Wolf         switch (qcow2_opts->version) {
285329ca9e45SKevin Wolf         case BLOCKDEV_QCOW2_VERSION_V2:
285429ca9e45SKevin Wolf             version = 2;
285529ca9e45SKevin Wolf             break;
285629ca9e45SKevin Wolf         case BLOCKDEV_QCOW2_VERSION_V3:
285729ca9e45SKevin Wolf             version = 3;
285829ca9e45SKevin Wolf             break;
285929ca9e45SKevin Wolf         default:
286029ca9e45SKevin Wolf             g_assert_not_reached();
286129ca9e45SKevin Wolf         }
286229ca9e45SKevin Wolf     } else {
286329ca9e45SKevin Wolf         version = 3;
286429ca9e45SKevin Wolf     }
286529ca9e45SKevin Wolf 
286629ca9e45SKevin Wolf     if (qcow2_opts->has_cluster_size) {
286729ca9e45SKevin Wolf         cluster_size = qcow2_opts->cluster_size;
286829ca9e45SKevin Wolf     } else {
286929ca9e45SKevin Wolf         cluster_size = DEFAULT_CLUSTER_SIZE;
287029ca9e45SKevin Wolf     }
287129ca9e45SKevin Wolf 
287229ca9e45SKevin Wolf     if (!validate_cluster_size(cluster_size, errp)) {
2873e1d74bc6SKevin Wolf         ret = -EINVAL;
2874e1d74bc6SKevin Wolf         goto out;
287529ca9e45SKevin Wolf     }
287629ca9e45SKevin Wolf 
287729ca9e45SKevin Wolf     if (!qcow2_opts->has_preallocation) {
287829ca9e45SKevin Wolf         qcow2_opts->preallocation = PREALLOC_MODE_OFF;
287929ca9e45SKevin Wolf     }
288029ca9e45SKevin Wolf     if (qcow2_opts->has_backing_file &&
288129ca9e45SKevin Wolf         qcow2_opts->preallocation != PREALLOC_MODE_OFF)
288229ca9e45SKevin Wolf     {
288329ca9e45SKevin Wolf         error_setg(errp, "Backing file and preallocation cannot be used at "
288429ca9e45SKevin Wolf                    "the same time");
2885e1d74bc6SKevin Wolf         ret = -EINVAL;
2886e1d74bc6SKevin Wolf         goto out;
288729ca9e45SKevin Wolf     }
288829ca9e45SKevin Wolf     if (qcow2_opts->has_backing_fmt && !qcow2_opts->has_backing_file) {
288929ca9e45SKevin Wolf         error_setg(errp, "Backing format cannot be used without backing file");
2890e1d74bc6SKevin Wolf         ret = -EINVAL;
2891e1d74bc6SKevin Wolf         goto out;
289229ca9e45SKevin Wolf     }
289329ca9e45SKevin Wolf 
289429ca9e45SKevin Wolf     if (!qcow2_opts->has_lazy_refcounts) {
289529ca9e45SKevin Wolf         qcow2_opts->lazy_refcounts = false;
289629ca9e45SKevin Wolf     }
289729ca9e45SKevin Wolf     if (version < 3 && qcow2_opts->lazy_refcounts) {
289829ca9e45SKevin Wolf         error_setg(errp, "Lazy refcounts only supported with compatibility "
2899b76b4f60SKevin Wolf                    "level 1.1 and above (use version=v3 or greater)");
2900e1d74bc6SKevin Wolf         ret = -EINVAL;
2901e1d74bc6SKevin Wolf         goto out;
290229ca9e45SKevin Wolf     }
290329ca9e45SKevin Wolf 
290429ca9e45SKevin Wolf     if (!qcow2_opts->has_refcount_bits) {
290529ca9e45SKevin Wolf         qcow2_opts->refcount_bits = 16;
290629ca9e45SKevin Wolf     }
290729ca9e45SKevin Wolf     if (qcow2_opts->refcount_bits > 64 ||
290829ca9e45SKevin Wolf         !is_power_of_2(qcow2_opts->refcount_bits))
290929ca9e45SKevin Wolf     {
291029ca9e45SKevin Wolf         error_setg(errp, "Refcount width must be a power of two and may not "
291129ca9e45SKevin Wolf                    "exceed 64 bits");
2912e1d74bc6SKevin Wolf         ret = -EINVAL;
2913e1d74bc6SKevin Wolf         goto out;
291429ca9e45SKevin Wolf     }
291529ca9e45SKevin Wolf     if (version < 3 && qcow2_opts->refcount_bits != 16) {
291629ca9e45SKevin Wolf         error_setg(errp, "Different refcount widths than 16 bits require "
2917b76b4f60SKevin Wolf                    "compatibility level 1.1 or above (use version=v3 or "
291829ca9e45SKevin Wolf                    "greater)");
2919e1d74bc6SKevin Wolf         ret = -EINVAL;
2920e1d74bc6SKevin Wolf         goto out;
292129ca9e45SKevin Wolf     }
292229ca9e45SKevin Wolf     refcount_order = ctz32(qcow2_opts->refcount_bits);
292329ca9e45SKevin Wolf 
292429ca9e45SKevin Wolf 
292529ca9e45SKevin Wolf     /* Create BlockBackend to write to the image */
2926cbf2b7c4SKevin Wolf     blk = blk_new(BLK_PERM_WRITE | BLK_PERM_RESIZE, BLK_PERM_ALL);
2927cbf2b7c4SKevin Wolf     ret = blk_insert_bs(blk, bs, errp);
2928a9420734SKevin Wolf     if (ret < 0) {
2929cbf2b7c4SKevin Wolf         goto out;
2930a9420734SKevin Wolf     }
293123588797SKevin Wolf     blk_set_allow_write_beyond_eof(blk, true);
293223588797SKevin Wolf 
2933e4b5dad8SKevin Wolf     /* Clear the protocol layer and preallocate it if necessary */
2934e4b5dad8SKevin Wolf     ret = blk_truncate(blk, 0, PREALLOC_MODE_OFF, errp);
2935e4b5dad8SKevin Wolf     if (ret < 0) {
2936e4b5dad8SKevin Wolf         goto out;
2937e4b5dad8SKevin Wolf     }
2938e4b5dad8SKevin Wolf 
2939e4b5dad8SKevin Wolf     if (qcow2_opts->preallocation == PREALLOC_MODE_FULL ||
2940e4b5dad8SKevin Wolf         qcow2_opts->preallocation == PREALLOC_MODE_FALLOC)
2941e4b5dad8SKevin Wolf     {
2942e4b5dad8SKevin Wolf         int64_t prealloc_size =
2943e4b5dad8SKevin Wolf             qcow2_calc_prealloc_size(qcow2_opts->size, cluster_size,
2944e4b5dad8SKevin Wolf                                      refcount_order);
2945e4b5dad8SKevin Wolf 
2946e4b5dad8SKevin Wolf         ret = blk_truncate(blk, prealloc_size, qcow2_opts->preallocation, errp);
2947e4b5dad8SKevin Wolf         if (ret < 0) {
2948e4b5dad8SKevin Wolf             goto out;
2949e4b5dad8SKevin Wolf         }
2950e4b5dad8SKevin Wolf     }
2951e4b5dad8SKevin Wolf 
2952a9420734SKevin Wolf     /* Write the header */
2953f8413b3cSKevin Wolf     QEMU_BUILD_BUG_ON((1 << MIN_CLUSTER_BITS) < sizeof(*header));
2954f8413b3cSKevin Wolf     header = g_malloc0(cluster_size);
2955f8413b3cSKevin Wolf     *header = (QCowHeader) {
2956f8413b3cSKevin Wolf         .magic                      = cpu_to_be32(QCOW_MAGIC),
2957f8413b3cSKevin Wolf         .version                    = cpu_to_be32(version),
29580eb4a8c1SStefan Hajnoczi         .cluster_bits               = cpu_to_be32(ctz32(cluster_size)),
2959f8413b3cSKevin Wolf         .size                       = cpu_to_be64(0),
2960f8413b3cSKevin Wolf         .l1_table_offset            = cpu_to_be64(0),
2961f8413b3cSKevin Wolf         .l1_size                    = cpu_to_be32(0),
2962f8413b3cSKevin Wolf         .refcount_table_offset      = cpu_to_be64(cluster_size),
2963f8413b3cSKevin Wolf         .refcount_table_clusters    = cpu_to_be32(1),
2964bd4b167fSMax Reitz         .refcount_order             = cpu_to_be32(refcount_order),
2965f8413b3cSKevin Wolf         .header_length              = cpu_to_be32(sizeof(*header)),
2966f8413b3cSKevin Wolf     };
2967a9420734SKevin Wolf 
2968b25b387fSDaniel P. Berrange     /* We'll update this to correct value later */
2969f8413b3cSKevin Wolf     header->crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
2970a9420734SKevin Wolf 
297129ca9e45SKevin Wolf     if (qcow2_opts->lazy_refcounts) {
2972f8413b3cSKevin Wolf         header->compatible_features |=
2973bfe8043eSStefan Hajnoczi             cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS);
2974bfe8043eSStefan Hajnoczi     }
2975bfe8043eSStefan Hajnoczi 
29768341f00dSEric Blake     ret = blk_pwrite(blk, 0, header, cluster_size, 0);
2977f8413b3cSKevin Wolf     g_free(header);
2978a9420734SKevin Wolf     if (ret < 0) {
29793ef6c40aSMax Reitz         error_setg_errno(errp, -ret, "Could not write qcow2 header");
2980a9420734SKevin Wolf         goto out;
2981a9420734SKevin Wolf     }
2982a9420734SKevin Wolf 
2983b106ad91SKevin Wolf     /* Write a refcount table with one refcount block */
2984b106ad91SKevin Wolf     refcount_table = g_malloc0(2 * cluster_size);
2985b106ad91SKevin Wolf     refcount_table[0] = cpu_to_be64(2 * cluster_size);
29868341f00dSEric Blake     ret = blk_pwrite(blk, cluster_size, refcount_table, 2 * cluster_size, 0);
29877267c094SAnthony Liguori     g_free(refcount_table);
2988a9420734SKevin Wolf 
2989a9420734SKevin Wolf     if (ret < 0) {
29903ef6c40aSMax Reitz         error_setg_errno(errp, -ret, "Could not write refcount table");
2991a9420734SKevin Wolf         goto out;
2992a9420734SKevin Wolf     }
2993a9420734SKevin Wolf 
299423588797SKevin Wolf     blk_unref(blk);
299523588797SKevin Wolf     blk = NULL;
2996a9420734SKevin Wolf 
2997a9420734SKevin Wolf     /*
2998a9420734SKevin Wolf      * And now open the image and make it consistent first (i.e. increase the
2999a9420734SKevin Wolf      * refcount of the cluster that is occupied by the header and the refcount
3000a9420734SKevin Wolf      * table)
3001a9420734SKevin Wolf      */
3002e6641719SMax Reitz     options = qdict_new();
300346f5ac20SEric Blake     qdict_put_str(options, "driver", "qcow2");
3004cbf2b7c4SKevin Wolf     qdict_put_str(options, "file", bs->node_name);
3005cbf2b7c4SKevin Wolf     blk = blk_new_open(NULL, NULL, options,
300655880601SKevin Wolf                        BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_NO_FLUSH,
300755880601SKevin Wolf                        &local_err);
300823588797SKevin Wolf     if (blk == NULL) {
30093ef6c40aSMax Reitz         error_propagate(errp, local_err);
301023588797SKevin Wolf         ret = -EIO;
3011a9420734SKevin Wolf         goto out;
3012a9420734SKevin Wolf     }
3013a9420734SKevin Wolf 
301423588797SKevin Wolf     ret = qcow2_alloc_clusters(blk_bs(blk), 3 * cluster_size);
3015a9420734SKevin Wolf     if (ret < 0) {
30163ef6c40aSMax Reitz         error_setg_errno(errp, -ret, "Could not allocate clusters for qcow2 "
30173ef6c40aSMax Reitz                          "header and refcount table");
3018a9420734SKevin Wolf         goto out;
3019a9420734SKevin Wolf 
3020a9420734SKevin Wolf     } else if (ret != 0) {
3021a9420734SKevin Wolf         error_report("Huh, first cluster in empty image is already in use?");
3022a9420734SKevin Wolf         abort();
3023a9420734SKevin Wolf     }
3024a9420734SKevin Wolf 
3025b527c9b3SKevin Wolf     /* Create a full header (including things like feature table) */
302623588797SKevin Wolf     ret = qcow2_update_header(blk_bs(blk));
3027b527c9b3SKevin Wolf     if (ret < 0) {
3028b527c9b3SKevin Wolf         error_setg_errno(errp, -ret, "Could not update qcow2 header");
3029b527c9b3SKevin Wolf         goto out;
3030b527c9b3SKevin Wolf     }
3031b527c9b3SKevin Wolf 
3032a9420734SKevin Wolf     /* Okay, now that we have a valid image, let's give it the right size */
303329ca9e45SKevin Wolf     ret = blk_truncate(blk, qcow2_opts->size, PREALLOC_MODE_OFF, errp);
3034a9420734SKevin Wolf     if (ret < 0) {
3035ed3d2ec9SMax Reitz         error_prepend(errp, "Could not resize image: ");
3036a9420734SKevin Wolf         goto out;
3037a9420734SKevin Wolf     }
3038a9420734SKevin Wolf 
3039a9420734SKevin Wolf     /* Want a backing file? There you go.*/
304029ca9e45SKevin Wolf     if (qcow2_opts->has_backing_file) {
304129ca9e45SKevin Wolf         const char *backing_format = NULL;
304229ca9e45SKevin Wolf 
304329ca9e45SKevin Wolf         if (qcow2_opts->has_backing_fmt) {
304429ca9e45SKevin Wolf             backing_format = BlockdevDriver_str(qcow2_opts->backing_fmt);
304529ca9e45SKevin Wolf         }
304629ca9e45SKevin Wolf 
304729ca9e45SKevin Wolf         ret = bdrv_change_backing_file(blk_bs(blk), qcow2_opts->backing_file,
304829ca9e45SKevin Wolf                                        backing_format);
3049a9420734SKevin Wolf         if (ret < 0) {
30503ef6c40aSMax Reitz             error_setg_errno(errp, -ret, "Could not assign backing file '%s' "
305129ca9e45SKevin Wolf                              "with format '%s'", qcow2_opts->backing_file,
305229ca9e45SKevin Wolf                              backing_format);
3053a9420734SKevin Wolf             goto out;
3054a9420734SKevin Wolf         }
3055a9420734SKevin Wolf     }
3056a9420734SKevin Wolf 
3057b25b387fSDaniel P. Berrange     /* Want encryption? There you go. */
305860900b7bSKevin Wolf     if (qcow2_opts->has_encrypt) {
305960900b7bSKevin Wolf         ret = qcow2_set_up_encryption(blk_bs(blk), qcow2_opts->encrypt, errp);
3060b25b387fSDaniel P. Berrange         if (ret < 0) {
3061b25b387fSDaniel P. Berrange             goto out;
3062b25b387fSDaniel P. Berrange         }
3063b25b387fSDaniel P. Berrange     }
3064b25b387fSDaniel P. Berrange 
3065a9420734SKevin Wolf     /* And if we're supposed to preallocate metadata, do that now */
306629ca9e45SKevin Wolf     if (qcow2_opts->preallocation != PREALLOC_MODE_OFF) {
3067061ca8a3SKevin Wolf         BDRVQcow2State *s = blk_bs(blk)->opaque;
3068061ca8a3SKevin Wolf         qemu_co_mutex_lock(&s->lock);
306947e86b86SKevin Wolf         ret = preallocate_co(blk_bs(blk), 0, qcow2_opts->size);
3070061ca8a3SKevin Wolf         qemu_co_mutex_unlock(&s->lock);
3071061ca8a3SKevin Wolf 
3072a9420734SKevin Wolf         if (ret < 0) {
30733ef6c40aSMax Reitz             error_setg_errno(errp, -ret, "Could not preallocate metadata");
3074a9420734SKevin Wolf             goto out;
3075a9420734SKevin Wolf         }
3076a9420734SKevin Wolf     }
3077a9420734SKevin Wolf 
307823588797SKevin Wolf     blk_unref(blk);
307923588797SKevin Wolf     blk = NULL;
3080ba2ab2f2SMax Reitz 
3081b25b387fSDaniel P. Berrange     /* Reopen the image without BDRV_O_NO_FLUSH to flush it before returning.
3082b25b387fSDaniel P. Berrange      * Using BDRV_O_NO_IO, since encryption is now setup we don't want to
3083b25b387fSDaniel P. Berrange      * have to setup decryption context. We're not doing any I/O on the top
3084b25b387fSDaniel P. Berrange      * level BlockDriverState, only lower layers, where BDRV_O_NO_IO does
3085b25b387fSDaniel P. Berrange      * not have effect.
3086b25b387fSDaniel P. Berrange      */
3087e6641719SMax Reitz     options = qdict_new();
308846f5ac20SEric Blake     qdict_put_str(options, "driver", "qcow2");
3089cbf2b7c4SKevin Wolf     qdict_put_str(options, "file", bs->node_name);
3090cbf2b7c4SKevin Wolf     blk = blk_new_open(NULL, NULL, options,
3091b25b387fSDaniel P. Berrange                        BDRV_O_RDWR | BDRV_O_NO_BACKING | BDRV_O_NO_IO,
3092b25b387fSDaniel P. Berrange                        &local_err);
309323588797SKevin Wolf     if (blk == NULL) {
3094ba2ab2f2SMax Reitz         error_propagate(errp, local_err);
309523588797SKevin Wolf         ret = -EIO;
3096ba2ab2f2SMax Reitz         goto out;
3097ba2ab2f2SMax Reitz     }
3098ba2ab2f2SMax Reitz 
3099a9420734SKevin Wolf     ret = 0;
3100a9420734SKevin Wolf out:
310123588797SKevin Wolf     blk_unref(blk);
3102e1d74bc6SKevin Wolf     bdrv_unref(bs);
3103a9420734SKevin Wolf     return ret;
3104a9420734SKevin Wolf }
3105de5f3f40SKevin Wolf 
3106efc75e2aSStefan Hajnoczi static int coroutine_fn qcow2_co_create_opts(const char *filename, QemuOpts *opts,
3107efc75e2aSStefan Hajnoczi                                              Error **errp)
3108de5f3f40SKevin Wolf {
3109b76b4f60SKevin Wolf     BlockdevCreateOptions *create_options = NULL;
311092adf9dbSMarkus Armbruster     QDict *qdict;
3111b76b4f60SKevin Wolf     Visitor *v;
3112cbf2b7c4SKevin Wolf     BlockDriverState *bs = NULL;
31133ef6c40aSMax Reitz     Error *local_err = NULL;
3114b76b4f60SKevin Wolf     const char *val;
31153ef6c40aSMax Reitz     int ret;
3116de5f3f40SKevin Wolf 
3117b76b4f60SKevin Wolf     /* Only the keyval visitor supports the dotted syntax needed for
3118b76b4f60SKevin Wolf      * encryption, so go through a QDict before getting a QAPI type. Ignore
3119b76b4f60SKevin Wolf      * options meant for the protocol layer so that the visitor doesn't
3120b76b4f60SKevin Wolf      * complain. */
3121b76b4f60SKevin Wolf     qdict = qemu_opts_to_qdict_filtered(opts, NULL, bdrv_qcow2.create_opts,
3122b76b4f60SKevin Wolf                                         true);
3123b76b4f60SKevin Wolf 
3124b76b4f60SKevin Wolf     /* Handle encryption options */
3125b76b4f60SKevin Wolf     val = qdict_get_try_str(qdict, BLOCK_OPT_ENCRYPT);
3126b76b4f60SKevin Wolf     if (val && !strcmp(val, "on")) {
3127b76b4f60SKevin Wolf         qdict_put_str(qdict, BLOCK_OPT_ENCRYPT, "qcow");
3128b76b4f60SKevin Wolf     } else if (val && !strcmp(val, "off")) {
3129b76b4f60SKevin Wolf         qdict_del(qdict, BLOCK_OPT_ENCRYPT);
313029ca9e45SKevin Wolf     }
313160900b7bSKevin Wolf 
3132b76b4f60SKevin Wolf     val = qdict_get_try_str(qdict, BLOCK_OPT_ENCRYPT_FORMAT);
3133b76b4f60SKevin Wolf     if (val && !strcmp(val, "aes")) {
3134b76b4f60SKevin Wolf         qdict_put_str(qdict, BLOCK_OPT_ENCRYPT_FORMAT, "qcow");
313560900b7bSKevin Wolf     }
313660900b7bSKevin Wolf 
3137b76b4f60SKevin Wolf     /* Convert compat=0.10/1.1 into compat=v2/v3, to be renamed into
3138b76b4f60SKevin Wolf      * version=v2/v3 below. */
3139b76b4f60SKevin Wolf     val = qdict_get_try_str(qdict, BLOCK_OPT_COMPAT_LEVEL);
3140b76b4f60SKevin Wolf     if (val && !strcmp(val, "0.10")) {
3141b76b4f60SKevin Wolf         qdict_put_str(qdict, BLOCK_OPT_COMPAT_LEVEL, "v2");
3142b76b4f60SKevin Wolf     } else if (val && !strcmp(val, "1.1")) {
3143b76b4f60SKevin Wolf         qdict_put_str(qdict, BLOCK_OPT_COMPAT_LEVEL, "v3");
3144b76b4f60SKevin Wolf     }
3145b76b4f60SKevin Wolf 
3146b76b4f60SKevin Wolf     /* Change legacy command line options into QMP ones */
3147b76b4f60SKevin Wolf     static const QDictRenames opt_renames[] = {
3148b76b4f60SKevin Wolf         { BLOCK_OPT_BACKING_FILE,       "backing-file" },
3149b76b4f60SKevin Wolf         { BLOCK_OPT_BACKING_FMT,        "backing-fmt" },
3150b76b4f60SKevin Wolf         { BLOCK_OPT_CLUSTER_SIZE,       "cluster-size" },
3151b76b4f60SKevin Wolf         { BLOCK_OPT_LAZY_REFCOUNTS,     "lazy-refcounts" },
3152b76b4f60SKevin Wolf         { BLOCK_OPT_REFCOUNT_BITS,      "refcount-bits" },
3153b76b4f60SKevin Wolf         { BLOCK_OPT_ENCRYPT,            BLOCK_OPT_ENCRYPT_FORMAT },
3154b76b4f60SKevin Wolf         { BLOCK_OPT_COMPAT_LEVEL,       "version" },
3155b76b4f60SKevin Wolf         { NULL, NULL },
3156b76b4f60SKevin Wolf     };
3157b76b4f60SKevin Wolf 
3158b76b4f60SKevin Wolf     if (!qdict_rename_keys(qdict, opt_renames, errp)) {
31590eb4a8c1SStefan Hajnoczi         ret = -EINVAL;
31600eb4a8c1SStefan Hajnoczi         goto finish;
31610eb4a8c1SStefan Hajnoczi     }
3162bd4b167fSMax Reitz 
3163cbf2b7c4SKevin Wolf     /* Create and open the file (protocol layer) */
3164cbf2b7c4SKevin Wolf     ret = bdrv_create_file(filename, opts, errp);
3165cbf2b7c4SKevin Wolf     if (ret < 0) {
3166cbf2b7c4SKevin Wolf         goto finish;
3167cbf2b7c4SKevin Wolf     }
3168cbf2b7c4SKevin Wolf 
3169cbf2b7c4SKevin Wolf     bs = bdrv_open(filename, NULL, NULL,
3170cbf2b7c4SKevin Wolf                    BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_PROTOCOL, errp);
3171cbf2b7c4SKevin Wolf     if (bs == NULL) {
3172cbf2b7c4SKevin Wolf         ret = -EIO;
3173cbf2b7c4SKevin Wolf         goto finish;
3174cbf2b7c4SKevin Wolf     }
3175cbf2b7c4SKevin Wolf 
3176b76b4f60SKevin Wolf     /* Set 'driver' and 'node' options */
3177b76b4f60SKevin Wolf     qdict_put_str(qdict, "driver", "qcow2");
3178b76b4f60SKevin Wolf     qdict_put_str(qdict, "file", bs->node_name);
3179b76b4f60SKevin Wolf 
3180b76b4f60SKevin Wolf     /* Now get the QAPI type BlockdevCreateOptions */
3181af91062eSMarkus Armbruster     v = qobject_input_visitor_new_flat_confused(qdict, errp);
3182af91062eSMarkus Armbruster     if (!v) {
3183b76b4f60SKevin Wolf         ret = -EINVAL;
3184b76b4f60SKevin Wolf         goto finish;
3185b76b4f60SKevin Wolf     }
3186b76b4f60SKevin Wolf 
3187b76b4f60SKevin Wolf     visit_type_BlockdevCreateOptions(v, NULL, &create_options, &local_err);
3188b76b4f60SKevin Wolf     visit_free(v);
3189b76b4f60SKevin Wolf 
3190b76b4f60SKevin Wolf     if (local_err) {
3191b76b4f60SKevin Wolf         error_propagate(errp, local_err);
3192b76b4f60SKevin Wolf         ret = -EINVAL;
3193b76b4f60SKevin Wolf         goto finish;
3194b76b4f60SKevin Wolf     }
3195b76b4f60SKevin Wolf 
3196b76b4f60SKevin Wolf     /* Silently round up size */
3197b76b4f60SKevin Wolf     create_options->u.qcow2.size = ROUND_UP(create_options->u.qcow2.size,
3198b76b4f60SKevin Wolf                                             BDRV_SECTOR_SIZE);
3199b76b4f60SKevin Wolf 
3200cbf2b7c4SKevin Wolf     /* Create the qcow2 image (format layer) */
3201b76b4f60SKevin Wolf     ret = qcow2_co_create(create_options, errp);
3202cbf2b7c4SKevin Wolf     if (ret < 0) {
3203cbf2b7c4SKevin Wolf         goto finish;
3204cbf2b7c4SKevin Wolf     }
32051bd0e2d1SChunyan Liu 
3206b76b4f60SKevin Wolf     ret = 0;
32071bd0e2d1SChunyan Liu finish:
3208cb3e7f08SMarc-André Lureau     qobject_unref(qdict);
3209cbf2b7c4SKevin Wolf     bdrv_unref(bs);
3210b76b4f60SKevin Wolf     qapi_free_BlockdevCreateOptions(create_options);
32113ef6c40aSMax Reitz     return ret;
3212de5f3f40SKevin Wolf }
3213de5f3f40SKevin Wolf 
32142928abceSDenis V. Lunev 
3215f06f6b66SEric Blake static bool is_zero(BlockDriverState *bs, int64_t offset, int64_t bytes)
32162928abceSDenis V. Lunev {
321731826642SEric Blake     int64_t nr;
321831826642SEric Blake     int res;
3219f06f6b66SEric Blake 
3220f06f6b66SEric Blake     /* Clamp to image length, before checking status of underlying sectors */
32218cbf74b2SEric Blake     if (offset + bytes > bs->total_sectors * BDRV_SECTOR_SIZE) {
32228cbf74b2SEric Blake         bytes = bs->total_sectors * BDRV_SECTOR_SIZE - offset;
3223fbaa6bb3SEric Blake     }
3224fbaa6bb3SEric Blake 
3225f06f6b66SEric Blake     if (!bytes) {
3226ebb718a5SEric Blake         return true;
32272928abceSDenis V. Lunev     }
32288cbf74b2SEric Blake     res = bdrv_block_status_above(bs, NULL, offset, bytes, &nr, NULL, NULL);
322931826642SEric Blake     return res >= 0 && (res & BDRV_BLOCK_ZERO) && nr == bytes;
32302928abceSDenis V. Lunev }
32312928abceSDenis V. Lunev 
32325544b59fSEric Blake static coroutine_fn int qcow2_co_pwrite_zeroes(BlockDriverState *bs,
3233f5a5ca79SManos Pitsidianakis     int64_t offset, int bytes, BdrvRequestFlags flags)
3234621f0589SKevin Wolf {
3235621f0589SKevin Wolf     int ret;
3236ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
3237621f0589SKevin Wolf 
32385544b59fSEric Blake     uint32_t head = offset % s->cluster_size;
3239f5a5ca79SManos Pitsidianakis     uint32_t tail = (offset + bytes) % s->cluster_size;
32402928abceSDenis V. Lunev 
3241f5a5ca79SManos Pitsidianakis     trace_qcow2_pwrite_zeroes_start_req(qemu_coroutine_self(), offset, bytes);
3242f5a5ca79SManos Pitsidianakis     if (offset + bytes == bs->total_sectors * BDRV_SECTOR_SIZE) {
3243fbaa6bb3SEric Blake         tail = 0;
3244fbaa6bb3SEric Blake     }
32455a64e942SDenis V. Lunev 
3246ebb718a5SEric Blake     if (head || tail) {
3247ebb718a5SEric Blake         uint64_t off;
3248ecfe1863SKevin Wolf         unsigned int nr;
32492928abceSDenis V. Lunev 
3250f5a5ca79SManos Pitsidianakis         assert(head + bytes <= s->cluster_size);
32512928abceSDenis V. Lunev 
3252ebb718a5SEric Blake         /* check whether remainder of cluster already reads as zero */
3253f06f6b66SEric Blake         if (!(is_zero(bs, offset - head, head) &&
3254f06f6b66SEric Blake               is_zero(bs, offset + bytes,
3255f06f6b66SEric Blake                       tail ? s->cluster_size - tail : 0))) {
3256621f0589SKevin Wolf             return -ENOTSUP;
3257621f0589SKevin Wolf         }
3258621f0589SKevin Wolf 
3259621f0589SKevin Wolf         qemu_co_mutex_lock(&s->lock);
32602928abceSDenis V. Lunev         /* We can have new write after previous check */
3261f06f6b66SEric Blake         offset = QEMU_ALIGN_DOWN(offset, s->cluster_size);
3262f5a5ca79SManos Pitsidianakis         bytes = s->cluster_size;
3263ecfe1863SKevin Wolf         nr = s->cluster_size;
32645544b59fSEric Blake         ret = qcow2_get_cluster_offset(bs, offset, &nr, &off);
3265fdfab37dSEric Blake         if (ret != QCOW2_CLUSTER_UNALLOCATED &&
3266fdfab37dSEric Blake             ret != QCOW2_CLUSTER_ZERO_PLAIN &&
3267fdfab37dSEric Blake             ret != QCOW2_CLUSTER_ZERO_ALLOC) {
32682928abceSDenis V. Lunev             qemu_co_mutex_unlock(&s->lock);
32692928abceSDenis V. Lunev             return -ENOTSUP;
32702928abceSDenis V. Lunev         }
32712928abceSDenis V. Lunev     } else {
32722928abceSDenis V. Lunev         qemu_co_mutex_lock(&s->lock);
32732928abceSDenis V. Lunev     }
32742928abceSDenis V. Lunev 
3275f5a5ca79SManos Pitsidianakis     trace_qcow2_pwrite_zeroes(qemu_coroutine_self(), offset, bytes);
32765a64e942SDenis V. Lunev 
32772928abceSDenis V. Lunev     /* Whatever is left can use real zero clusters */
3278f5a5ca79SManos Pitsidianakis     ret = qcow2_cluster_zeroize(bs, offset, bytes, flags);
3279621f0589SKevin Wolf     qemu_co_mutex_unlock(&s->lock);
3280621f0589SKevin Wolf 
3281621f0589SKevin Wolf     return ret;
3282621f0589SKevin Wolf }
3283621f0589SKevin Wolf 
328482e8a788SEric Blake static coroutine_fn int qcow2_co_pdiscard(BlockDriverState *bs,
3285f5a5ca79SManos Pitsidianakis                                           int64_t offset, int bytes)
32865ea929e3SKevin Wolf {
32876db39ae2SPaolo Bonzini     int ret;
3288ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
32896db39ae2SPaolo Bonzini 
3290f5a5ca79SManos Pitsidianakis     if (!QEMU_IS_ALIGNED(offset | bytes, s->cluster_size)) {
3291f5a5ca79SManos Pitsidianakis         assert(bytes < s->cluster_size);
3292048c5fd1SEric Blake         /* Ignore partial clusters, except for the special case of the
3293048c5fd1SEric Blake          * complete partial cluster at the end of an unaligned file */
3294048c5fd1SEric Blake         if (!QEMU_IS_ALIGNED(offset, s->cluster_size) ||
3295f5a5ca79SManos Pitsidianakis             offset + bytes != bs->total_sectors * BDRV_SECTOR_SIZE) {
329649228d1eSEric Blake             return -ENOTSUP;
329749228d1eSEric Blake         }
3298048c5fd1SEric Blake     }
329949228d1eSEric Blake 
33006db39ae2SPaolo Bonzini     qemu_co_mutex_lock(&s->lock);
3301f5a5ca79SManos Pitsidianakis     ret = qcow2_cluster_discard(bs, offset, bytes, QCOW2_DISCARD_REQUEST,
3302d2cb36afSEric Blake                                 false);
33036db39ae2SPaolo Bonzini     qemu_co_mutex_unlock(&s->lock);
33046db39ae2SPaolo Bonzini     return ret;
33055ea929e3SKevin Wolf }
33065ea929e3SKevin Wolf 
3307fd9fcd37SFam Zheng static int coroutine_fn
3308fd9fcd37SFam Zheng qcow2_co_copy_range_from(BlockDriverState *bs,
3309fd9fcd37SFam Zheng                          BdrvChild *src, uint64_t src_offset,
3310fd9fcd37SFam Zheng                          BdrvChild *dst, uint64_t dst_offset,
331167b51fb9SVladimir Sementsov-Ogievskiy                          uint64_t bytes, BdrvRequestFlags read_flags,
331267b51fb9SVladimir Sementsov-Ogievskiy                          BdrvRequestFlags write_flags)
3313fd9fcd37SFam Zheng {
3314fd9fcd37SFam Zheng     BDRVQcow2State *s = bs->opaque;
3315fd9fcd37SFam Zheng     int ret;
3316fd9fcd37SFam Zheng     unsigned int cur_bytes; /* number of bytes in current iteration */
3317fd9fcd37SFam Zheng     BdrvChild *child = NULL;
331867b51fb9SVladimir Sementsov-Ogievskiy     BdrvRequestFlags cur_write_flags;
3319fd9fcd37SFam Zheng 
3320fd9fcd37SFam Zheng     assert(!bs->encrypted);
3321fd9fcd37SFam Zheng     qemu_co_mutex_lock(&s->lock);
3322fd9fcd37SFam Zheng 
3323fd9fcd37SFam Zheng     while (bytes != 0) {
3324fd9fcd37SFam Zheng         uint64_t copy_offset = 0;
3325fd9fcd37SFam Zheng         /* prepare next request */
3326fd9fcd37SFam Zheng         cur_bytes = MIN(bytes, INT_MAX);
332767b51fb9SVladimir Sementsov-Ogievskiy         cur_write_flags = write_flags;
3328fd9fcd37SFam Zheng 
3329fd9fcd37SFam Zheng         ret = qcow2_get_cluster_offset(bs, src_offset, &cur_bytes, &copy_offset);
3330fd9fcd37SFam Zheng         if (ret < 0) {
3331fd9fcd37SFam Zheng             goto out;
3332fd9fcd37SFam Zheng         }
3333fd9fcd37SFam Zheng 
3334fd9fcd37SFam Zheng         switch (ret) {
3335fd9fcd37SFam Zheng         case QCOW2_CLUSTER_UNALLOCATED:
3336fd9fcd37SFam Zheng             if (bs->backing && bs->backing->bs) {
3337fd9fcd37SFam Zheng                 int64_t backing_length = bdrv_getlength(bs->backing->bs);
3338fd9fcd37SFam Zheng                 if (src_offset >= backing_length) {
333967b51fb9SVladimir Sementsov-Ogievskiy                     cur_write_flags |= BDRV_REQ_ZERO_WRITE;
3340fd9fcd37SFam Zheng                 } else {
3341fd9fcd37SFam Zheng                     child = bs->backing;
3342fd9fcd37SFam Zheng                     cur_bytes = MIN(cur_bytes, backing_length - src_offset);
3343fd9fcd37SFam Zheng                     copy_offset = src_offset;
3344fd9fcd37SFam Zheng                 }
3345fd9fcd37SFam Zheng             } else {
334667b51fb9SVladimir Sementsov-Ogievskiy                 cur_write_flags |= BDRV_REQ_ZERO_WRITE;
3347fd9fcd37SFam Zheng             }
3348fd9fcd37SFam Zheng             break;
3349fd9fcd37SFam Zheng 
3350fd9fcd37SFam Zheng         case QCOW2_CLUSTER_ZERO_PLAIN:
3351fd9fcd37SFam Zheng         case QCOW2_CLUSTER_ZERO_ALLOC:
335267b51fb9SVladimir Sementsov-Ogievskiy             cur_write_flags |= BDRV_REQ_ZERO_WRITE;
3353fd9fcd37SFam Zheng             break;
3354fd9fcd37SFam Zheng 
3355fd9fcd37SFam Zheng         case QCOW2_CLUSTER_COMPRESSED:
3356fd9fcd37SFam Zheng             ret = -ENOTSUP;
3357fd9fcd37SFam Zheng             goto out;
3358fd9fcd37SFam Zheng 
3359fd9fcd37SFam Zheng         case QCOW2_CLUSTER_NORMAL:
3360fd9fcd37SFam Zheng             child = bs->file;
3361fd9fcd37SFam Zheng             copy_offset += offset_into_cluster(s, src_offset);
3362fd9fcd37SFam Zheng             if ((copy_offset & 511) != 0) {
3363fd9fcd37SFam Zheng                 ret = -EIO;
3364fd9fcd37SFam Zheng                 goto out;
3365fd9fcd37SFam Zheng             }
3366fd9fcd37SFam Zheng             break;
3367fd9fcd37SFam Zheng 
3368fd9fcd37SFam Zheng         default:
3369fd9fcd37SFam Zheng             abort();
3370fd9fcd37SFam Zheng         }
3371fd9fcd37SFam Zheng         qemu_co_mutex_unlock(&s->lock);
3372fd9fcd37SFam Zheng         ret = bdrv_co_copy_range_from(child,
3373fd9fcd37SFam Zheng                                       copy_offset,
3374fd9fcd37SFam Zheng                                       dst, dst_offset,
337567b51fb9SVladimir Sementsov-Ogievskiy                                       cur_bytes, read_flags, cur_write_flags);
3376fd9fcd37SFam Zheng         qemu_co_mutex_lock(&s->lock);
3377fd9fcd37SFam Zheng         if (ret < 0) {
3378fd9fcd37SFam Zheng             goto out;
3379fd9fcd37SFam Zheng         }
3380fd9fcd37SFam Zheng 
3381fd9fcd37SFam Zheng         bytes -= cur_bytes;
3382fd9fcd37SFam Zheng         src_offset += cur_bytes;
3383fd9fcd37SFam Zheng         dst_offset += cur_bytes;
3384fd9fcd37SFam Zheng     }
3385fd9fcd37SFam Zheng     ret = 0;
3386fd9fcd37SFam Zheng 
3387fd9fcd37SFam Zheng out:
3388fd9fcd37SFam Zheng     qemu_co_mutex_unlock(&s->lock);
3389fd9fcd37SFam Zheng     return ret;
3390fd9fcd37SFam Zheng }
3391fd9fcd37SFam Zheng 
3392fd9fcd37SFam Zheng static int coroutine_fn
3393fd9fcd37SFam Zheng qcow2_co_copy_range_to(BlockDriverState *bs,
3394fd9fcd37SFam Zheng                        BdrvChild *src, uint64_t src_offset,
3395fd9fcd37SFam Zheng                        BdrvChild *dst, uint64_t dst_offset,
339667b51fb9SVladimir Sementsov-Ogievskiy                        uint64_t bytes, BdrvRequestFlags read_flags,
339767b51fb9SVladimir Sementsov-Ogievskiy                        BdrvRequestFlags write_flags)
3398fd9fcd37SFam Zheng {
3399fd9fcd37SFam Zheng     BDRVQcow2State *s = bs->opaque;
3400fd9fcd37SFam Zheng     int offset_in_cluster;
3401fd9fcd37SFam Zheng     int ret;
3402fd9fcd37SFam Zheng     unsigned int cur_bytes; /* number of sectors in current iteration */
3403fd9fcd37SFam Zheng     uint64_t cluster_offset;
3404fd9fcd37SFam Zheng     QCowL2Meta *l2meta = NULL;
3405fd9fcd37SFam Zheng 
3406fd9fcd37SFam Zheng     assert(!bs->encrypted);
3407fd9fcd37SFam Zheng 
3408fd9fcd37SFam Zheng     qemu_co_mutex_lock(&s->lock);
3409fd9fcd37SFam Zheng 
3410fd9fcd37SFam Zheng     while (bytes != 0) {
3411fd9fcd37SFam Zheng 
3412fd9fcd37SFam Zheng         l2meta = NULL;
3413fd9fcd37SFam Zheng 
3414fd9fcd37SFam Zheng         offset_in_cluster = offset_into_cluster(s, dst_offset);
3415fd9fcd37SFam Zheng         cur_bytes = MIN(bytes, INT_MAX);
3416fd9fcd37SFam Zheng 
3417fd9fcd37SFam Zheng         /* TODO:
3418fd9fcd37SFam Zheng          * If src->bs == dst->bs, we could simply copy by incrementing
3419fd9fcd37SFam Zheng          * the refcnt, without copying user data.
3420fd9fcd37SFam Zheng          * Or if src->bs == dst->bs->backing->bs, we could copy by discarding. */
3421fd9fcd37SFam Zheng         ret = qcow2_alloc_cluster_offset(bs, dst_offset, &cur_bytes,
3422fd9fcd37SFam Zheng                                          &cluster_offset, &l2meta);
3423fd9fcd37SFam Zheng         if (ret < 0) {
3424fd9fcd37SFam Zheng             goto fail;
3425fd9fcd37SFam Zheng         }
3426fd9fcd37SFam Zheng 
3427fd9fcd37SFam Zheng         assert((cluster_offset & 511) == 0);
3428fd9fcd37SFam Zheng 
3429fd9fcd37SFam Zheng         ret = qcow2_pre_write_overlap_check(bs, 0,
3430fd9fcd37SFam Zheng                 cluster_offset + offset_in_cluster, cur_bytes);
3431fd9fcd37SFam Zheng         if (ret < 0) {
3432fd9fcd37SFam Zheng             goto fail;
3433fd9fcd37SFam Zheng         }
3434fd9fcd37SFam Zheng 
3435fd9fcd37SFam Zheng         qemu_co_mutex_unlock(&s->lock);
3436fd9fcd37SFam Zheng         ret = bdrv_co_copy_range_to(src, src_offset,
3437fd9fcd37SFam Zheng                                     bs->file,
3438fd9fcd37SFam Zheng                                     cluster_offset + offset_in_cluster,
343967b51fb9SVladimir Sementsov-Ogievskiy                                     cur_bytes, read_flags, write_flags);
3440fd9fcd37SFam Zheng         qemu_co_mutex_lock(&s->lock);
3441fd9fcd37SFam Zheng         if (ret < 0) {
3442fd9fcd37SFam Zheng             goto fail;
3443fd9fcd37SFam Zheng         }
3444fd9fcd37SFam Zheng 
3445fd9fcd37SFam Zheng         ret = qcow2_handle_l2meta(bs, &l2meta, true);
3446fd9fcd37SFam Zheng         if (ret) {
3447fd9fcd37SFam Zheng             goto fail;
3448fd9fcd37SFam Zheng         }
3449fd9fcd37SFam Zheng 
3450fd9fcd37SFam Zheng         bytes -= cur_bytes;
3451e06f4639SFam Zheng         src_offset += cur_bytes;
3452fd9fcd37SFam Zheng         dst_offset += cur_bytes;
3453fd9fcd37SFam Zheng     }
3454fd9fcd37SFam Zheng     ret = 0;
3455fd9fcd37SFam Zheng 
3456fd9fcd37SFam Zheng fail:
3457fd9fcd37SFam Zheng     qcow2_handle_l2meta(bs, &l2meta, false);
3458fd9fcd37SFam Zheng 
3459fd9fcd37SFam Zheng     qemu_co_mutex_unlock(&s->lock);
3460fd9fcd37SFam Zheng 
3461fd9fcd37SFam Zheng     trace_qcow2_writev_done_req(qemu_coroutine_self(), ret);
3462fd9fcd37SFam Zheng 
3463fd9fcd37SFam Zheng     return ret;
3464fd9fcd37SFam Zheng }
3465fd9fcd37SFam Zheng 
3466061ca8a3SKevin Wolf static int coroutine_fn qcow2_co_truncate(BlockDriverState *bs, int64_t offset,
34678243ccb7SMax Reitz                                           PreallocMode prealloc, Error **errp)
3468419b19d9SStefan Hajnoczi {
3469ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
347095b98f34SMax Reitz     uint64_t old_length;
34712cf7cfa1SKevin Wolf     int64_t new_l1_size;
34722cf7cfa1SKevin Wolf     int ret;
347345b4949cSLeonid Bloch     QDict *options;
3474419b19d9SStefan Hajnoczi 
3475772d1f97SMax Reitz     if (prealloc != PREALLOC_MODE_OFF && prealloc != PREALLOC_MODE_METADATA &&
3476772d1f97SMax Reitz         prealloc != PREALLOC_MODE_FALLOC && prealloc != PREALLOC_MODE_FULL)
3477772d1f97SMax Reitz     {
34788243ccb7SMax Reitz         error_setg(errp, "Unsupported preallocation mode '%s'",
3479977c736fSMarkus Armbruster                    PreallocMode_str(prealloc));
34808243ccb7SMax Reitz         return -ENOTSUP;
34818243ccb7SMax Reitz     }
34828243ccb7SMax Reitz 
3483419b19d9SStefan Hajnoczi     if (offset & 511) {
34844bff28b8SMax Reitz         error_setg(errp, "The new size must be a multiple of 512");
3485419b19d9SStefan Hajnoczi         return -EINVAL;
3486419b19d9SStefan Hajnoczi     }
3487419b19d9SStefan Hajnoczi 
3488061ca8a3SKevin Wolf     qemu_co_mutex_lock(&s->lock);
3489061ca8a3SKevin Wolf 
3490419b19d9SStefan Hajnoczi     /* cannot proceed if image has snapshots */
3491419b19d9SStefan Hajnoczi     if (s->nb_snapshots) {
34924bff28b8SMax Reitz         error_setg(errp, "Can't resize an image which has snapshots");
3493061ca8a3SKevin Wolf         ret = -ENOTSUP;
3494061ca8a3SKevin Wolf         goto fail;
3495419b19d9SStefan Hajnoczi     }
3496419b19d9SStefan Hajnoczi 
349788ddffaeSVladimir Sementsov-Ogievskiy     /* cannot proceed if image has bitmaps */
349888ddffaeSVladimir Sementsov-Ogievskiy     if (s->nb_bitmaps) {
349988ddffaeSVladimir Sementsov-Ogievskiy         /* TODO: resize bitmaps in the image */
350088ddffaeSVladimir Sementsov-Ogievskiy         error_setg(errp, "Can't resize an image which has bitmaps");
3501061ca8a3SKevin Wolf         ret = -ENOTSUP;
3502061ca8a3SKevin Wolf         goto fail;
350388ddffaeSVladimir Sementsov-Ogievskiy     }
350488ddffaeSVladimir Sementsov-Ogievskiy 
3505bd016b91SLeonid Bloch     old_length = bs->total_sectors * BDRV_SECTOR_SIZE;
350646b732cdSPavel Butsykin     new_l1_size = size_to_l1(s, offset);
350795b98f34SMax Reitz 
350895b98f34SMax Reitz     if (offset < old_length) {
3509163bc39dSPavel Butsykin         int64_t last_cluster, old_file_size;
351046b732cdSPavel Butsykin         if (prealloc != PREALLOC_MODE_OFF) {
351146b732cdSPavel Butsykin             error_setg(errp,
351246b732cdSPavel Butsykin                        "Preallocation can't be used for shrinking an image");
3513061ca8a3SKevin Wolf             ret = -EINVAL;
3514061ca8a3SKevin Wolf             goto fail;
3515419b19d9SStefan Hajnoczi         }
3516419b19d9SStefan Hajnoczi 
351746b732cdSPavel Butsykin         ret = qcow2_cluster_discard(bs, ROUND_UP(offset, s->cluster_size),
351846b732cdSPavel Butsykin                                     old_length - ROUND_UP(offset,
351946b732cdSPavel Butsykin                                                           s->cluster_size),
352046b732cdSPavel Butsykin                                     QCOW2_DISCARD_ALWAYS, true);
352146b732cdSPavel Butsykin         if (ret < 0) {
352246b732cdSPavel Butsykin             error_setg_errno(errp, -ret, "Failed to discard cropped clusters");
3523061ca8a3SKevin Wolf             goto fail;
352446b732cdSPavel Butsykin         }
352546b732cdSPavel Butsykin 
352646b732cdSPavel Butsykin         ret = qcow2_shrink_l1_table(bs, new_l1_size);
352746b732cdSPavel Butsykin         if (ret < 0) {
352846b732cdSPavel Butsykin             error_setg_errno(errp, -ret,
352946b732cdSPavel Butsykin                              "Failed to reduce the number of L2 tables");
3530061ca8a3SKevin Wolf             goto fail;
353146b732cdSPavel Butsykin         }
353246b732cdSPavel Butsykin 
353346b732cdSPavel Butsykin         ret = qcow2_shrink_reftable(bs);
353446b732cdSPavel Butsykin         if (ret < 0) {
353546b732cdSPavel Butsykin             error_setg_errno(errp, -ret,
353646b732cdSPavel Butsykin                              "Failed to discard unused refblocks");
3537061ca8a3SKevin Wolf             goto fail;
353846b732cdSPavel Butsykin         }
3539163bc39dSPavel Butsykin 
3540163bc39dSPavel Butsykin         old_file_size = bdrv_getlength(bs->file->bs);
3541163bc39dSPavel Butsykin         if (old_file_size < 0) {
3542163bc39dSPavel Butsykin             error_setg_errno(errp, -old_file_size,
3543163bc39dSPavel Butsykin                              "Failed to inquire current file length");
3544061ca8a3SKevin Wolf             ret = old_file_size;
3545061ca8a3SKevin Wolf             goto fail;
3546163bc39dSPavel Butsykin         }
3547163bc39dSPavel Butsykin         last_cluster = qcow2_get_last_cluster(bs, old_file_size);
3548163bc39dSPavel Butsykin         if (last_cluster < 0) {
3549163bc39dSPavel Butsykin             error_setg_errno(errp, -last_cluster,
3550163bc39dSPavel Butsykin                              "Failed to find the last cluster");
3551061ca8a3SKevin Wolf             ret = last_cluster;
3552061ca8a3SKevin Wolf             goto fail;
3553163bc39dSPavel Butsykin         }
3554163bc39dSPavel Butsykin         if ((last_cluster + 1) * s->cluster_size < old_file_size) {
3555233521b1SMax Reitz             Error *local_err = NULL;
3556233521b1SMax Reitz 
3557061ca8a3SKevin Wolf             bdrv_co_truncate(bs->file, (last_cluster + 1) * s->cluster_size,
3558233521b1SMax Reitz                              PREALLOC_MODE_OFF, &local_err);
3559233521b1SMax Reitz             if (local_err) {
3560233521b1SMax Reitz                 warn_reportf_err(local_err,
3561233521b1SMax Reitz                                  "Failed to truncate the tail of the image: ");
3562163bc39dSPavel Butsykin             }
3563163bc39dSPavel Butsykin         }
356446b732cdSPavel Butsykin     } else {
356572893756SStefan Hajnoczi         ret = qcow2_grow_l1_table(bs, new_l1_size, true);
3566419b19d9SStefan Hajnoczi         if (ret < 0) {
3567f59adb32SMax Reitz             error_setg_errno(errp, -ret, "Failed to grow the L1 table");
3568061ca8a3SKevin Wolf             goto fail;
3569419b19d9SStefan Hajnoczi         }
357046b732cdSPavel Butsykin     }
3571419b19d9SStefan Hajnoczi 
357295b98f34SMax Reitz     switch (prealloc) {
357395b98f34SMax Reitz     case PREALLOC_MODE_OFF:
357495b98f34SMax Reitz         break;
357595b98f34SMax Reitz 
357695b98f34SMax Reitz     case PREALLOC_MODE_METADATA:
357747e86b86SKevin Wolf         ret = preallocate_co(bs, old_length, offset);
357895b98f34SMax Reitz         if (ret < 0) {
357995b98f34SMax Reitz             error_setg_errno(errp, -ret, "Preallocation failed");
3580061ca8a3SKevin Wolf             goto fail;
358195b98f34SMax Reitz         }
358295b98f34SMax Reitz         break;
358395b98f34SMax Reitz 
3584772d1f97SMax Reitz     case PREALLOC_MODE_FALLOC:
3585772d1f97SMax Reitz     case PREALLOC_MODE_FULL:
3586772d1f97SMax Reitz     {
3587772d1f97SMax Reitz         int64_t allocation_start, host_offset, guest_offset;
3588772d1f97SMax Reitz         int64_t clusters_allocated;
3589772d1f97SMax Reitz         int64_t old_file_size, new_file_size;
3590772d1f97SMax Reitz         uint64_t nb_new_data_clusters, nb_new_l2_tables;
3591772d1f97SMax Reitz 
3592772d1f97SMax Reitz         old_file_size = bdrv_getlength(bs->file->bs);
3593772d1f97SMax Reitz         if (old_file_size < 0) {
3594772d1f97SMax Reitz             error_setg_errno(errp, -old_file_size,
3595772d1f97SMax Reitz                              "Failed to inquire current file length");
3596061ca8a3SKevin Wolf             ret = old_file_size;
3597061ca8a3SKevin Wolf             goto fail;
3598772d1f97SMax Reitz         }
3599e400ad1eSMax Reitz         old_file_size = ROUND_UP(old_file_size, s->cluster_size);
3600772d1f97SMax Reitz 
3601772d1f97SMax Reitz         nb_new_data_clusters = DIV_ROUND_UP(offset - old_length,
3602772d1f97SMax Reitz                                             s->cluster_size);
3603772d1f97SMax Reitz 
3604772d1f97SMax Reitz         /* This is an overestimation; we will not actually allocate space for
3605772d1f97SMax Reitz          * these in the file but just make sure the new refcount structures are
3606772d1f97SMax Reitz          * able to cover them so we will not have to allocate new refblocks
3607772d1f97SMax Reitz          * while entering the data blocks in the potentially new L2 tables.
3608772d1f97SMax Reitz          * (We do not actually care where the L2 tables are placed. Maybe they
3609772d1f97SMax Reitz          *  are already allocated or they can be placed somewhere before
3610772d1f97SMax Reitz          *  @old_file_size. It does not matter because they will be fully
3611772d1f97SMax Reitz          *  allocated automatically, so they do not need to be covered by the
3612772d1f97SMax Reitz          *  preallocation. All that matters is that we will not have to allocate
3613772d1f97SMax Reitz          *  new refcount structures for them.) */
3614772d1f97SMax Reitz         nb_new_l2_tables = DIV_ROUND_UP(nb_new_data_clusters,
3615772d1f97SMax Reitz                                         s->cluster_size / sizeof(uint64_t));
3616772d1f97SMax Reitz         /* The cluster range may not be aligned to L2 boundaries, so add one L2
3617772d1f97SMax Reitz          * table for a potential head/tail */
3618772d1f97SMax Reitz         nb_new_l2_tables++;
3619772d1f97SMax Reitz 
3620772d1f97SMax Reitz         allocation_start = qcow2_refcount_area(bs, old_file_size,
3621772d1f97SMax Reitz                                                nb_new_data_clusters +
3622772d1f97SMax Reitz                                                nb_new_l2_tables,
3623772d1f97SMax Reitz                                                true, 0, 0);
3624772d1f97SMax Reitz         if (allocation_start < 0) {
3625772d1f97SMax Reitz             error_setg_errno(errp, -allocation_start,
3626772d1f97SMax Reitz                              "Failed to resize refcount structures");
3627061ca8a3SKevin Wolf             ret = allocation_start;
3628061ca8a3SKevin Wolf             goto fail;
3629772d1f97SMax Reitz         }
3630772d1f97SMax Reitz 
3631772d1f97SMax Reitz         clusters_allocated = qcow2_alloc_clusters_at(bs, allocation_start,
3632772d1f97SMax Reitz                                                      nb_new_data_clusters);
3633772d1f97SMax Reitz         if (clusters_allocated < 0) {
3634772d1f97SMax Reitz             error_setg_errno(errp, -clusters_allocated,
3635772d1f97SMax Reitz                              "Failed to allocate data clusters");
3636061ca8a3SKevin Wolf             ret = clusters_allocated;
3637061ca8a3SKevin Wolf             goto fail;
3638772d1f97SMax Reitz         }
3639772d1f97SMax Reitz 
3640772d1f97SMax Reitz         assert(clusters_allocated == nb_new_data_clusters);
3641772d1f97SMax Reitz 
3642772d1f97SMax Reitz         /* Allocate the data area */
3643772d1f97SMax Reitz         new_file_size = allocation_start +
3644772d1f97SMax Reitz                         nb_new_data_clusters * s->cluster_size;
3645061ca8a3SKevin Wolf         ret = bdrv_co_truncate(bs->file, new_file_size, prealloc, errp);
3646772d1f97SMax Reitz         if (ret < 0) {
3647772d1f97SMax Reitz             error_prepend(errp, "Failed to resize underlying file: ");
3648772d1f97SMax Reitz             qcow2_free_clusters(bs, allocation_start,
3649772d1f97SMax Reitz                                 nb_new_data_clusters * s->cluster_size,
3650772d1f97SMax Reitz                                 QCOW2_DISCARD_OTHER);
3651061ca8a3SKevin Wolf             goto fail;
3652772d1f97SMax Reitz         }
3653772d1f97SMax Reitz 
3654772d1f97SMax Reitz         /* Create the necessary L2 entries */
3655772d1f97SMax Reitz         host_offset = allocation_start;
3656772d1f97SMax Reitz         guest_offset = old_length;
3657772d1f97SMax Reitz         while (nb_new_data_clusters) {
365813bec229SAlberto Garcia             int64_t nb_clusters = MIN(
365913bec229SAlberto Garcia                 nb_new_data_clusters,
366013bec229SAlberto Garcia                 s->l2_slice_size - offset_to_l2_slice_index(s, guest_offset));
3661772d1f97SMax Reitz             QCowL2Meta allocation = {
3662772d1f97SMax Reitz                 .offset       = guest_offset,
3663772d1f97SMax Reitz                 .alloc_offset = host_offset,
3664772d1f97SMax Reitz                 .nb_clusters  = nb_clusters,
3665772d1f97SMax Reitz             };
3666772d1f97SMax Reitz             qemu_co_queue_init(&allocation.dependent_requests);
3667772d1f97SMax Reitz 
3668772d1f97SMax Reitz             ret = qcow2_alloc_cluster_link_l2(bs, &allocation);
3669772d1f97SMax Reitz             if (ret < 0) {
3670772d1f97SMax Reitz                 error_setg_errno(errp, -ret, "Failed to update L2 tables");
3671772d1f97SMax Reitz                 qcow2_free_clusters(bs, host_offset,
3672772d1f97SMax Reitz                                     nb_new_data_clusters * s->cluster_size,
3673772d1f97SMax Reitz                                     QCOW2_DISCARD_OTHER);
3674061ca8a3SKevin Wolf                 goto fail;
3675772d1f97SMax Reitz             }
3676772d1f97SMax Reitz 
3677772d1f97SMax Reitz             guest_offset += nb_clusters * s->cluster_size;
3678772d1f97SMax Reitz             host_offset += nb_clusters * s->cluster_size;
3679772d1f97SMax Reitz             nb_new_data_clusters -= nb_clusters;
3680772d1f97SMax Reitz         }
3681772d1f97SMax Reitz         break;
3682772d1f97SMax Reitz     }
3683772d1f97SMax Reitz 
368495b98f34SMax Reitz     default:
368595b98f34SMax Reitz         g_assert_not_reached();
368695b98f34SMax Reitz     }
368795b98f34SMax Reitz 
368895b98f34SMax Reitz     if (prealloc != PREALLOC_MODE_OFF) {
368995b98f34SMax Reitz         /* Flush metadata before actually changing the image size */
3690061ca8a3SKevin Wolf         ret = qcow2_write_caches(bs);
369195b98f34SMax Reitz         if (ret < 0) {
369295b98f34SMax Reitz             error_setg_errno(errp, -ret,
369395b98f34SMax Reitz                              "Failed to flush the preallocated area to disk");
3694061ca8a3SKevin Wolf             goto fail;
369595b98f34SMax Reitz         }
369695b98f34SMax Reitz     }
369795b98f34SMax Reitz 
369845b4949cSLeonid Bloch     bs->total_sectors = offset / BDRV_SECTOR_SIZE;
369945b4949cSLeonid Bloch 
3700419b19d9SStefan Hajnoczi     /* write updated header.size */
3701419b19d9SStefan Hajnoczi     offset = cpu_to_be64(offset);
3702d9ca2ea2SKevin Wolf     ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, size),
3703419b19d9SStefan Hajnoczi                            &offset, sizeof(uint64_t));
3704419b19d9SStefan Hajnoczi     if (ret < 0) {
3705f59adb32SMax Reitz         error_setg_errno(errp, -ret, "Failed to update the image size");
3706061ca8a3SKevin Wolf         goto fail;
3707419b19d9SStefan Hajnoczi     }
3708419b19d9SStefan Hajnoczi 
3709419b19d9SStefan Hajnoczi     s->l1_vm_state_index = new_l1_size;
371045b4949cSLeonid Bloch 
371145b4949cSLeonid Bloch     /* Update cache sizes */
371245b4949cSLeonid Bloch     options = qdict_clone_shallow(bs->options);
371345b4949cSLeonid Bloch     ret = qcow2_update_options(bs, options, s->flags, errp);
371445b4949cSLeonid Bloch     qobject_unref(options);
371545b4949cSLeonid Bloch     if (ret < 0) {
371645b4949cSLeonid Bloch         goto fail;
371745b4949cSLeonid Bloch     }
3718061ca8a3SKevin Wolf     ret = 0;
3719061ca8a3SKevin Wolf fail:
3720061ca8a3SKevin Wolf     qemu_co_mutex_unlock(&s->lock);
3721061ca8a3SKevin Wolf     return ret;
3722419b19d9SStefan Hajnoczi }
3723419b19d9SStefan Hajnoczi 
37242714f13dSVladimir Sementsov-Ogievskiy /*
37252714f13dSVladimir Sementsov-Ogievskiy  * qcow2_compress()
37262714f13dSVladimir Sementsov-Ogievskiy  *
37276994fd78SVladimir Sementsov-Ogievskiy  * @dest - destination buffer, @dest_size bytes
37286994fd78SVladimir Sementsov-Ogievskiy  * @src - source buffer, @src_size bytes
37292714f13dSVladimir Sementsov-Ogievskiy  *
37302714f13dSVladimir Sementsov-Ogievskiy  * Returns: compressed size on success
37316994fd78SVladimir Sementsov-Ogievskiy  *          -1 destination buffer is not enough to store compressed data
37322714f13dSVladimir Sementsov-Ogievskiy  *          -2 on any other error
37332714f13dSVladimir Sementsov-Ogievskiy  */
37346994fd78SVladimir Sementsov-Ogievskiy static ssize_t qcow2_compress(void *dest, size_t dest_size,
37356994fd78SVladimir Sementsov-Ogievskiy                               const void *src, size_t src_size)
37362714f13dSVladimir Sementsov-Ogievskiy {
37372714f13dSVladimir Sementsov-Ogievskiy     ssize_t ret;
37382714f13dSVladimir Sementsov-Ogievskiy     z_stream strm;
37392714f13dSVladimir Sementsov-Ogievskiy 
37402714f13dSVladimir Sementsov-Ogievskiy     /* best compression, small window, no zlib header */
37412714f13dSVladimir Sementsov-Ogievskiy     memset(&strm, 0, sizeof(strm));
37422714f13dSVladimir Sementsov-Ogievskiy     ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION, Z_DEFLATED,
37432714f13dSVladimir Sementsov-Ogievskiy                        -12, 9, Z_DEFAULT_STRATEGY);
374419a44488SVladimir Sementsov-Ogievskiy     if (ret != Z_OK) {
37452714f13dSVladimir Sementsov-Ogievskiy         return -2;
37462714f13dSVladimir Sementsov-Ogievskiy     }
37472714f13dSVladimir Sementsov-Ogievskiy 
37482714f13dSVladimir Sementsov-Ogievskiy     /* strm.next_in is not const in old zlib versions, such as those used on
37492714f13dSVladimir Sementsov-Ogievskiy      * OpenBSD/NetBSD, so cast the const away */
37506994fd78SVladimir Sementsov-Ogievskiy     strm.avail_in = src_size;
37512714f13dSVladimir Sementsov-Ogievskiy     strm.next_in = (void *) src;
37526994fd78SVladimir Sementsov-Ogievskiy     strm.avail_out = dest_size;
37532714f13dSVladimir Sementsov-Ogievskiy     strm.next_out = dest;
37542714f13dSVladimir Sementsov-Ogievskiy 
37552714f13dSVladimir Sementsov-Ogievskiy     ret = deflate(&strm, Z_FINISH);
37562714f13dSVladimir Sementsov-Ogievskiy     if (ret == Z_STREAM_END) {
37576994fd78SVladimir Sementsov-Ogievskiy         ret = dest_size - strm.avail_out;
37582714f13dSVladimir Sementsov-Ogievskiy     } else {
37592714f13dSVladimir Sementsov-Ogievskiy         ret = (ret == Z_OK ? -1 : -2);
37602714f13dSVladimir Sementsov-Ogievskiy     }
37612714f13dSVladimir Sementsov-Ogievskiy 
37622714f13dSVladimir Sementsov-Ogievskiy     deflateEnd(&strm);
37632714f13dSVladimir Sementsov-Ogievskiy 
37642714f13dSVladimir Sementsov-Ogievskiy     return ret;
37652714f13dSVladimir Sementsov-Ogievskiy }
37662714f13dSVladimir Sementsov-Ogievskiy 
3767341926abSVladimir Sementsov-Ogievskiy /*
3768341926abSVladimir Sementsov-Ogievskiy  * qcow2_decompress()
3769341926abSVladimir Sementsov-Ogievskiy  *
3770341926abSVladimir Sementsov-Ogievskiy  * Decompress some data (not more than @src_size bytes) to produce exactly
3771341926abSVladimir Sementsov-Ogievskiy  * @dest_size bytes.
3772341926abSVladimir Sementsov-Ogievskiy  *
3773341926abSVladimir Sementsov-Ogievskiy  * @dest - destination buffer, @dest_size bytes
3774341926abSVladimir Sementsov-Ogievskiy  * @src - source buffer, @src_size bytes
3775341926abSVladimir Sementsov-Ogievskiy  *
3776341926abSVladimir Sementsov-Ogievskiy  * Returns: 0 on success
3777341926abSVladimir Sementsov-Ogievskiy  *          -1 on fail
3778341926abSVladimir Sementsov-Ogievskiy  */
3779341926abSVladimir Sementsov-Ogievskiy static ssize_t qcow2_decompress(void *dest, size_t dest_size,
3780341926abSVladimir Sementsov-Ogievskiy                                 const void *src, size_t src_size)
3781f4b3e2a9SVladimir Sementsov-Ogievskiy {
3782341926abSVladimir Sementsov-Ogievskiy     int ret = 0;
3783341926abSVladimir Sementsov-Ogievskiy     z_stream strm;
3784f4b3e2a9SVladimir Sementsov-Ogievskiy 
3785341926abSVladimir Sementsov-Ogievskiy     memset(&strm, 0, sizeof(strm));
3786341926abSVladimir Sementsov-Ogievskiy     strm.avail_in = src_size;
3787341926abSVladimir Sementsov-Ogievskiy     strm.next_in = (void *) src;
3788341926abSVladimir Sementsov-Ogievskiy     strm.avail_out = dest_size;
3789341926abSVladimir Sementsov-Ogievskiy     strm.next_out = dest;
3790f4b3e2a9SVladimir Sementsov-Ogievskiy 
3791341926abSVladimir Sementsov-Ogievskiy     ret = inflateInit2(&strm, -12);
3792f4b3e2a9SVladimir Sementsov-Ogievskiy     if (ret != Z_OK) {
3793f4b3e2a9SVladimir Sementsov-Ogievskiy         return -1;
3794f4b3e2a9SVladimir Sementsov-Ogievskiy     }
3795341926abSVladimir Sementsov-Ogievskiy 
3796341926abSVladimir Sementsov-Ogievskiy     ret = inflate(&strm, Z_FINISH);
3797341926abSVladimir Sementsov-Ogievskiy     if ((ret != Z_STREAM_END && ret != Z_BUF_ERROR) || strm.avail_out != 0) {
3798341926abSVladimir Sementsov-Ogievskiy         /* We approve Z_BUF_ERROR because we need @dest buffer to be filled, but
3799341926abSVladimir Sementsov-Ogievskiy          * @src buffer may be processed partly (because in qcow2 we know size of
3800341926abSVladimir Sementsov-Ogievskiy          * compressed data with precision of one sector) */
3801341926abSVladimir Sementsov-Ogievskiy         ret = -1;
3802f4b3e2a9SVladimir Sementsov-Ogievskiy     }
3803341926abSVladimir Sementsov-Ogievskiy 
3804341926abSVladimir Sementsov-Ogievskiy     inflateEnd(&strm);
3805341926abSVladimir Sementsov-Ogievskiy 
3806341926abSVladimir Sementsov-Ogievskiy     return ret;
3807f4b3e2a9SVladimir Sementsov-Ogievskiy }
3808f4b3e2a9SVladimir Sementsov-Ogievskiy 
3809ceb029cdSVladimir Sementsov-Ogievskiy #define MAX_COMPRESS_THREADS 4
3810ceb029cdSVladimir Sementsov-Ogievskiy 
3811e23c9d7aSVladimir Sementsov-Ogievskiy typedef ssize_t (*Qcow2CompressFunc)(void *dest, size_t dest_size,
3812e23c9d7aSVladimir Sementsov-Ogievskiy                                      const void *src, size_t src_size);
3813ceb029cdSVladimir Sementsov-Ogievskiy typedef struct Qcow2CompressData {
3814ceb029cdSVladimir Sementsov-Ogievskiy     void *dest;
38156994fd78SVladimir Sementsov-Ogievskiy     size_t dest_size;
3816ceb029cdSVladimir Sementsov-Ogievskiy     const void *src;
38176994fd78SVladimir Sementsov-Ogievskiy     size_t src_size;
3818ceb029cdSVladimir Sementsov-Ogievskiy     ssize_t ret;
3819e23c9d7aSVladimir Sementsov-Ogievskiy 
3820e23c9d7aSVladimir Sementsov-Ogievskiy     Qcow2CompressFunc func;
3821ceb029cdSVladimir Sementsov-Ogievskiy } Qcow2CompressData;
3822ceb029cdSVladimir Sementsov-Ogievskiy 
3823ceb029cdSVladimir Sementsov-Ogievskiy static int qcow2_compress_pool_func(void *opaque)
3824ceb029cdSVladimir Sementsov-Ogievskiy {
3825ceb029cdSVladimir Sementsov-Ogievskiy     Qcow2CompressData *data = opaque;
3826ceb029cdSVladimir Sementsov-Ogievskiy 
3827e23c9d7aSVladimir Sementsov-Ogievskiy     data->ret = data->func(data->dest, data->dest_size,
38286994fd78SVladimir Sementsov-Ogievskiy                            data->src, data->src_size);
3829ceb029cdSVladimir Sementsov-Ogievskiy 
3830ceb029cdSVladimir Sementsov-Ogievskiy     return 0;
3831ceb029cdSVladimir Sementsov-Ogievskiy }
3832ceb029cdSVladimir Sementsov-Ogievskiy 
3833ceb029cdSVladimir Sementsov-Ogievskiy static void qcow2_compress_complete(void *opaque, int ret)
3834ceb029cdSVladimir Sementsov-Ogievskiy {
3835ceb029cdSVladimir Sementsov-Ogievskiy     qemu_coroutine_enter(opaque);
3836ceb029cdSVladimir Sementsov-Ogievskiy }
3837ceb029cdSVladimir Sementsov-Ogievskiy 
3838e23c9d7aSVladimir Sementsov-Ogievskiy static ssize_t coroutine_fn
3839e23c9d7aSVladimir Sementsov-Ogievskiy qcow2_co_do_compress(BlockDriverState *bs, void *dest, size_t dest_size,
3840e23c9d7aSVladimir Sementsov-Ogievskiy                      const void *src, size_t src_size, Qcow2CompressFunc func)
3841ceb029cdSVladimir Sementsov-Ogievskiy {
3842ceb029cdSVladimir Sementsov-Ogievskiy     BDRVQcow2State *s = bs->opaque;
3843ceb029cdSVladimir Sementsov-Ogievskiy     BlockAIOCB *acb;
3844ceb029cdSVladimir Sementsov-Ogievskiy     ThreadPool *pool = aio_get_thread_pool(bdrv_get_aio_context(bs));
3845ceb029cdSVladimir Sementsov-Ogievskiy     Qcow2CompressData arg = {
3846ceb029cdSVladimir Sementsov-Ogievskiy         .dest = dest,
38476994fd78SVladimir Sementsov-Ogievskiy         .dest_size = dest_size,
3848ceb029cdSVladimir Sementsov-Ogievskiy         .src = src,
38496994fd78SVladimir Sementsov-Ogievskiy         .src_size = src_size,
3850e23c9d7aSVladimir Sementsov-Ogievskiy         .func = func,
3851ceb029cdSVladimir Sementsov-Ogievskiy     };
3852ceb029cdSVladimir Sementsov-Ogievskiy 
3853ceb029cdSVladimir Sementsov-Ogievskiy     while (s->nb_compress_threads >= MAX_COMPRESS_THREADS) {
3854ceb029cdSVladimir Sementsov-Ogievskiy         qemu_co_queue_wait(&s->compress_wait_queue, NULL);
3855ceb029cdSVladimir Sementsov-Ogievskiy     }
3856ceb029cdSVladimir Sementsov-Ogievskiy 
3857ceb029cdSVladimir Sementsov-Ogievskiy     s->nb_compress_threads++;
3858ceb029cdSVladimir Sementsov-Ogievskiy     acb = thread_pool_submit_aio(pool, qcow2_compress_pool_func, &arg,
3859ceb029cdSVladimir Sementsov-Ogievskiy                                  qcow2_compress_complete,
3860ceb029cdSVladimir Sementsov-Ogievskiy                                  qemu_coroutine_self());
3861ceb029cdSVladimir Sementsov-Ogievskiy 
3862ceb029cdSVladimir Sementsov-Ogievskiy     if (!acb) {
3863ceb029cdSVladimir Sementsov-Ogievskiy         s->nb_compress_threads--;
3864ceb029cdSVladimir Sementsov-Ogievskiy         return -EINVAL;
3865ceb029cdSVladimir Sementsov-Ogievskiy     }
3866ceb029cdSVladimir Sementsov-Ogievskiy     qemu_coroutine_yield();
3867ceb029cdSVladimir Sementsov-Ogievskiy     s->nb_compress_threads--;
3868ceb029cdSVladimir Sementsov-Ogievskiy     qemu_co_queue_next(&s->compress_wait_queue);
3869ceb029cdSVladimir Sementsov-Ogievskiy 
3870ceb029cdSVladimir Sementsov-Ogievskiy     return arg.ret;
3871ceb029cdSVladimir Sementsov-Ogievskiy }
3872ceb029cdSVladimir Sementsov-Ogievskiy 
3873e23c9d7aSVladimir Sementsov-Ogievskiy static ssize_t coroutine_fn
3874e23c9d7aSVladimir Sementsov-Ogievskiy qcow2_co_compress(BlockDriverState *bs, void *dest, size_t dest_size,
3875e23c9d7aSVladimir Sementsov-Ogievskiy                   const void *src, size_t src_size)
3876e23c9d7aSVladimir Sementsov-Ogievskiy {
3877e23c9d7aSVladimir Sementsov-Ogievskiy     return qcow2_co_do_compress(bs, dest, dest_size, src, src_size,
3878e23c9d7aSVladimir Sementsov-Ogievskiy                                 qcow2_compress);
3879e23c9d7aSVladimir Sementsov-Ogievskiy }
3880e23c9d7aSVladimir Sementsov-Ogievskiy 
3881e23c9d7aSVladimir Sementsov-Ogievskiy static ssize_t coroutine_fn
3882e23c9d7aSVladimir Sementsov-Ogievskiy qcow2_co_decompress(BlockDriverState *bs, void *dest, size_t dest_size,
3883e23c9d7aSVladimir Sementsov-Ogievskiy                     const void *src, size_t src_size)
3884e23c9d7aSVladimir Sementsov-Ogievskiy {
3885e23c9d7aSVladimir Sementsov-Ogievskiy     return qcow2_co_do_compress(bs, dest, dest_size, src, src_size,
3886e23c9d7aSVladimir Sementsov-Ogievskiy                                 qcow2_decompress);
3887e23c9d7aSVladimir Sementsov-Ogievskiy }
3888e23c9d7aSVladimir Sementsov-Ogievskiy 
388920d97356SBlue Swirl /* XXX: put compressed sectors first, then all the cluster aligned
389020d97356SBlue Swirl    tables to avoid losing bytes in alignment */
3891fcccefc5SPavel Butsykin static coroutine_fn int
3892fcccefc5SPavel Butsykin qcow2_co_pwritev_compressed(BlockDriverState *bs, uint64_t offset,
3893fcccefc5SPavel Butsykin                             uint64_t bytes, QEMUIOVector *qiov)
389420d97356SBlue Swirl {
3895ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
3896fcccefc5SPavel Butsykin     QEMUIOVector hd_qiov;
3897fcccefc5SPavel Butsykin     struct iovec iov;
38982714f13dSVladimir Sementsov-Ogievskiy     int ret;
38992714f13dSVladimir Sementsov-Ogievskiy     size_t out_len;
3900fcccefc5SPavel Butsykin     uint8_t *buf, *out_buf;
3901d0d5d0e3SEric Blake     int64_t cluster_offset;
390220d97356SBlue Swirl 
3903fcccefc5SPavel Butsykin     if (bytes == 0) {
390420d97356SBlue Swirl         /* align end of file to a sector boundary to ease reading with
390520d97356SBlue Swirl            sector based I/Os */
39069a4f4c31SKevin Wolf         cluster_offset = bdrv_getlength(bs->file->bs);
3907d0d5d0e3SEric Blake         if (cluster_offset < 0) {
3908d0d5d0e3SEric Blake             return cluster_offset;
3909d0d5d0e3SEric Blake         }
3910061ca8a3SKevin Wolf         return bdrv_co_truncate(bs->file, cluster_offset, PREALLOC_MODE_OFF,
3911061ca8a3SKevin Wolf                                 NULL);
391220d97356SBlue Swirl     }
391320d97356SBlue Swirl 
39143e3b838fSAnton Nefedov     if (offset_into_cluster(s, offset)) {
39153e3b838fSAnton Nefedov         return -EINVAL;
39163e3b838fSAnton Nefedov     }
39173e3b838fSAnton Nefedov 
3918fcccefc5SPavel Butsykin     buf = qemu_blockalign(bs, s->cluster_size);
3919a2c0ca6fSPavel Butsykin     if (bytes != s->cluster_size) {
3920a2c0ca6fSPavel Butsykin         if (bytes > s->cluster_size ||
3921a2c0ca6fSPavel Butsykin             offset + bytes != bs->total_sectors << BDRV_SECTOR_BITS)
3922a2c0ca6fSPavel Butsykin         {
3923a2c0ca6fSPavel Butsykin             qemu_vfree(buf);
3924a2c0ca6fSPavel Butsykin             return -EINVAL;
3925a2c0ca6fSPavel Butsykin         }
3926a2c0ca6fSPavel Butsykin         /* Zero-pad last write if image size is not cluster aligned */
3927a2c0ca6fSPavel Butsykin         memset(buf + bytes, 0, s->cluster_size - bytes);
3928a2c0ca6fSPavel Butsykin     }
39298b2bd093SPavel Butsykin     qemu_iovec_to_buf(qiov, 0, buf, bytes);
393020d97356SBlue Swirl 
3931ebf7bba0SVladimir Sementsov-Ogievskiy     out_buf = g_malloc(s->cluster_size);
393220d97356SBlue Swirl 
39336994fd78SVladimir Sementsov-Ogievskiy     out_len = qcow2_co_compress(bs, out_buf, s->cluster_size - 1,
39346994fd78SVladimir Sementsov-Ogievskiy                                 buf, s->cluster_size);
39352714f13dSVladimir Sementsov-Ogievskiy     if (out_len == -2) {
39368f1efd00SKevin Wolf         ret = -EINVAL;
39378f1efd00SKevin Wolf         goto fail;
39382714f13dSVladimir Sementsov-Ogievskiy     } else if (out_len == -1) {
393920d97356SBlue Swirl         /* could not compress: write normal cluster */
3940fcccefc5SPavel Butsykin         ret = qcow2_co_pwritev(bs, offset, bytes, qiov, 0);
39418f1efd00SKevin Wolf         if (ret < 0) {
39428f1efd00SKevin Wolf             goto fail;
39438f1efd00SKevin Wolf         }
3944fcccefc5SPavel Butsykin         goto success;
3945fcccefc5SPavel Butsykin     }
3946fcccefc5SPavel Butsykin 
3947fcccefc5SPavel Butsykin     qemu_co_mutex_lock(&s->lock);
3948fcccefc5SPavel Butsykin     cluster_offset =
3949fcccefc5SPavel Butsykin         qcow2_alloc_compressed_cluster_offset(bs, offset, out_len);
39508f1efd00SKevin Wolf     if (!cluster_offset) {
3951fcccefc5SPavel Butsykin         qemu_co_mutex_unlock(&s->lock);
39528f1efd00SKevin Wolf         ret = -EIO;
39538f1efd00SKevin Wolf         goto fail;
39548f1efd00SKevin Wolf     }
395520d97356SBlue Swirl     cluster_offset &= s->cluster_offset_mask;
3956cf93980eSMax Reitz 
3957231bb267SMax Reitz     ret = qcow2_pre_write_overlap_check(bs, 0, cluster_offset, out_len);
3958fcccefc5SPavel Butsykin     qemu_co_mutex_unlock(&s->lock);
3959cf93980eSMax Reitz     if (ret < 0) {
3960cf93980eSMax Reitz         goto fail;
3961cf93980eSMax Reitz     }
3962cf93980eSMax Reitz 
3963fcccefc5SPavel Butsykin     iov = (struct iovec) {
3964fcccefc5SPavel Butsykin         .iov_base   = out_buf,
3965fcccefc5SPavel Butsykin         .iov_len    = out_len,
3966fcccefc5SPavel Butsykin     };
3967fcccefc5SPavel Butsykin     qemu_iovec_init_external(&hd_qiov, &iov, 1);
3968fcccefc5SPavel Butsykin 
396966f82ceeSKevin Wolf     BLKDBG_EVENT(bs->file, BLKDBG_WRITE_COMPRESSED);
3970fcccefc5SPavel Butsykin     ret = bdrv_co_pwritev(bs->file, cluster_offset, out_len, &hd_qiov, 0);
39718f1efd00SKevin Wolf     if (ret < 0) {
39728f1efd00SKevin Wolf         goto fail;
397320d97356SBlue Swirl     }
3974fcccefc5SPavel Butsykin success:
39758f1efd00SKevin Wolf     ret = 0;
39768f1efd00SKevin Wolf fail:
3977fcccefc5SPavel Butsykin     qemu_vfree(buf);
39787267c094SAnthony Liguori     g_free(out_buf);
39798f1efd00SKevin Wolf     return ret;
398020d97356SBlue Swirl }
398120d97356SBlue Swirl 
3982c3c10f72SVladimir Sementsov-Ogievskiy static int coroutine_fn
3983c3c10f72SVladimir Sementsov-Ogievskiy qcow2_co_preadv_compressed(BlockDriverState *bs,
3984c3c10f72SVladimir Sementsov-Ogievskiy                            uint64_t file_cluster_offset,
3985c3c10f72SVladimir Sementsov-Ogievskiy                            uint64_t offset,
3986c3c10f72SVladimir Sementsov-Ogievskiy                            uint64_t bytes,
3987c3c10f72SVladimir Sementsov-Ogievskiy                            QEMUIOVector *qiov)
3988f4b3e2a9SVladimir Sementsov-Ogievskiy {
3989f4b3e2a9SVladimir Sementsov-Ogievskiy     BDRVQcow2State *s = bs->opaque;
3990c3c10f72SVladimir Sementsov-Ogievskiy     int ret = 0, csize, nb_csectors;
3991f4b3e2a9SVladimir Sementsov-Ogievskiy     uint64_t coffset;
3992c3c10f72SVladimir Sementsov-Ogievskiy     uint8_t *buf, *out_buf;
3993c068a1cdSVladimir Sementsov-Ogievskiy     struct iovec iov;
3994c068a1cdSVladimir Sementsov-Ogievskiy     QEMUIOVector local_qiov;
3995c3c10f72SVladimir Sementsov-Ogievskiy     int offset_in_cluster = offset_into_cluster(s, offset);
3996f4b3e2a9SVladimir Sementsov-Ogievskiy 
3997c3c10f72SVladimir Sementsov-Ogievskiy     coffset = file_cluster_offset & s->cluster_offset_mask;
3998c3c10f72SVladimir Sementsov-Ogievskiy     nb_csectors = ((file_cluster_offset >> s->csize_shift) & s->csize_mask) + 1;
3999c068a1cdSVladimir Sementsov-Ogievskiy     csize = nb_csectors * 512 - (coffset & 511);
4000f4b3e2a9SVladimir Sementsov-Ogievskiy 
4001c3c10f72SVladimir Sementsov-Ogievskiy     buf = g_try_malloc(csize);
4002c3c10f72SVladimir Sementsov-Ogievskiy     if (!buf) {
4003f4b3e2a9SVladimir Sementsov-Ogievskiy         return -ENOMEM;
4004f4b3e2a9SVladimir Sementsov-Ogievskiy     }
4005c3c10f72SVladimir Sementsov-Ogievskiy     iov.iov_base = buf;
4006c068a1cdSVladimir Sementsov-Ogievskiy     iov.iov_len = csize;
4007c068a1cdSVladimir Sementsov-Ogievskiy     qemu_iovec_init_external(&local_qiov, &iov, 1);
4008c068a1cdSVladimir Sementsov-Ogievskiy 
4009c3c10f72SVladimir Sementsov-Ogievskiy     out_buf = qemu_blockalign(bs, s->cluster_size);
4010c3c10f72SVladimir Sementsov-Ogievskiy 
4011f4b3e2a9SVladimir Sementsov-Ogievskiy     BLKDBG_EVENT(bs->file, BLKDBG_READ_COMPRESSED);
4012c068a1cdSVladimir Sementsov-Ogievskiy     ret = bdrv_co_preadv(bs->file, coffset, csize, &local_qiov, 0);
4013f4b3e2a9SVladimir Sementsov-Ogievskiy     if (ret < 0) {
4014c3c10f72SVladimir Sementsov-Ogievskiy         goto fail;
4015c3c10f72SVladimir Sementsov-Ogievskiy     }
4016c3c10f72SVladimir Sementsov-Ogievskiy 
4017e23c9d7aSVladimir Sementsov-Ogievskiy     if (qcow2_co_decompress(bs, out_buf, s->cluster_size, buf, csize) < 0) {
4018c3c10f72SVladimir Sementsov-Ogievskiy         ret = -EIO;
4019c3c10f72SVladimir Sementsov-Ogievskiy         goto fail;
4020c3c10f72SVladimir Sementsov-Ogievskiy     }
4021c3c10f72SVladimir Sementsov-Ogievskiy 
4022c3c10f72SVladimir Sementsov-Ogievskiy     qemu_iovec_from_buf(qiov, 0, out_buf + offset_in_cluster, bytes);
4023c3c10f72SVladimir Sementsov-Ogievskiy 
4024c3c10f72SVladimir Sementsov-Ogievskiy fail:
4025c3c10f72SVladimir Sementsov-Ogievskiy     qemu_vfree(out_buf);
4026c3c10f72SVladimir Sementsov-Ogievskiy     g_free(buf);
4027c3c10f72SVladimir Sementsov-Ogievskiy 
4028f4b3e2a9SVladimir Sementsov-Ogievskiy     return ret;
4029f4b3e2a9SVladimir Sementsov-Ogievskiy }
4030f4b3e2a9SVladimir Sementsov-Ogievskiy 
403194054183SMax Reitz static int make_completely_empty(BlockDriverState *bs)
403294054183SMax Reitz {
4033ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
4034ed3d2ec9SMax Reitz     Error *local_err = NULL;
403594054183SMax Reitz     int ret, l1_clusters;
403694054183SMax Reitz     int64_t offset;
403794054183SMax Reitz     uint64_t *new_reftable = NULL;
403894054183SMax Reitz     uint64_t rt_entry, l1_size2;
403994054183SMax Reitz     struct {
404094054183SMax Reitz         uint64_t l1_offset;
404194054183SMax Reitz         uint64_t reftable_offset;
404294054183SMax Reitz         uint32_t reftable_clusters;
404394054183SMax Reitz     } QEMU_PACKED l1_ofs_rt_ofs_cls;
404494054183SMax Reitz 
404594054183SMax Reitz     ret = qcow2_cache_empty(bs, s->l2_table_cache);
404694054183SMax Reitz     if (ret < 0) {
404794054183SMax Reitz         goto fail;
404894054183SMax Reitz     }
404994054183SMax Reitz 
405094054183SMax Reitz     ret = qcow2_cache_empty(bs, s->refcount_block_cache);
405194054183SMax Reitz     if (ret < 0) {
405294054183SMax Reitz         goto fail;
405394054183SMax Reitz     }
405494054183SMax Reitz 
405594054183SMax Reitz     /* Refcounts will be broken utterly */
405694054183SMax Reitz     ret = qcow2_mark_dirty(bs);
405794054183SMax Reitz     if (ret < 0) {
405894054183SMax Reitz         goto fail;
405994054183SMax Reitz     }
406094054183SMax Reitz 
406194054183SMax Reitz     BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
406294054183SMax Reitz 
406394054183SMax Reitz     l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / sizeof(uint64_t));
406494054183SMax Reitz     l1_size2 = (uint64_t)s->l1_size * sizeof(uint64_t);
406594054183SMax Reitz 
406694054183SMax Reitz     /* After this call, neither the in-memory nor the on-disk refcount
406794054183SMax Reitz      * information accurately describe the actual references */
406894054183SMax Reitz 
4069720ff280SKevin Wolf     ret = bdrv_pwrite_zeroes(bs->file, s->l1_table_offset,
407074021bc4SEric Blake                              l1_clusters * s->cluster_size, 0);
407194054183SMax Reitz     if (ret < 0) {
407294054183SMax Reitz         goto fail_broken_refcounts;
407394054183SMax Reitz     }
407494054183SMax Reitz     memset(s->l1_table, 0, l1_size2);
407594054183SMax Reitz 
407694054183SMax Reitz     BLKDBG_EVENT(bs->file, BLKDBG_EMPTY_IMAGE_PREPARE);
407794054183SMax Reitz 
407894054183SMax Reitz     /* Overwrite enough clusters at the beginning of the sectors to place
407994054183SMax Reitz      * the refcount table, a refcount block and the L1 table in; this may
408094054183SMax Reitz      * overwrite parts of the existing refcount and L1 table, which is not
408194054183SMax Reitz      * an issue because the dirty flag is set, complete data loss is in fact
408294054183SMax Reitz      * desired and partial data loss is consequently fine as well */
4083720ff280SKevin Wolf     ret = bdrv_pwrite_zeroes(bs->file, s->cluster_size,
408474021bc4SEric Blake                              (2 + l1_clusters) * s->cluster_size, 0);
408594054183SMax Reitz     /* This call (even if it failed overall) may have overwritten on-disk
408694054183SMax Reitz      * refcount structures; in that case, the in-memory refcount information
408794054183SMax Reitz      * will probably differ from the on-disk information which makes the BDS
408894054183SMax Reitz      * unusable */
408994054183SMax Reitz     if (ret < 0) {
409094054183SMax Reitz         goto fail_broken_refcounts;
409194054183SMax Reitz     }
409294054183SMax Reitz 
409394054183SMax Reitz     BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
409494054183SMax Reitz     BLKDBG_EVENT(bs->file, BLKDBG_REFTABLE_UPDATE);
409594054183SMax Reitz 
409694054183SMax Reitz     /* "Create" an empty reftable (one cluster) directly after the image
409794054183SMax Reitz      * header and an empty L1 table three clusters after the image header;
409894054183SMax Reitz      * the cluster between those two will be used as the first refblock */
4099f1f7a1ddSPeter Maydell     l1_ofs_rt_ofs_cls.l1_offset = cpu_to_be64(3 * s->cluster_size);
4100f1f7a1ddSPeter Maydell     l1_ofs_rt_ofs_cls.reftable_offset = cpu_to_be64(s->cluster_size);
4101f1f7a1ddSPeter Maydell     l1_ofs_rt_ofs_cls.reftable_clusters = cpu_to_be32(1);
4102d9ca2ea2SKevin Wolf     ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, l1_table_offset),
410394054183SMax Reitz                            &l1_ofs_rt_ofs_cls, sizeof(l1_ofs_rt_ofs_cls));
410494054183SMax Reitz     if (ret < 0) {
410594054183SMax Reitz         goto fail_broken_refcounts;
410694054183SMax Reitz     }
410794054183SMax Reitz 
410894054183SMax Reitz     s->l1_table_offset = 3 * s->cluster_size;
410994054183SMax Reitz 
411094054183SMax Reitz     new_reftable = g_try_new0(uint64_t, s->cluster_size / sizeof(uint64_t));
411194054183SMax Reitz     if (!new_reftable) {
411294054183SMax Reitz         ret = -ENOMEM;
411394054183SMax Reitz         goto fail_broken_refcounts;
411494054183SMax Reitz     }
411594054183SMax Reitz 
411694054183SMax Reitz     s->refcount_table_offset = s->cluster_size;
411794054183SMax Reitz     s->refcount_table_size   = s->cluster_size / sizeof(uint64_t);
41187061a078SAlberto Garcia     s->max_refcount_table_index = 0;
411994054183SMax Reitz 
412094054183SMax Reitz     g_free(s->refcount_table);
412194054183SMax Reitz     s->refcount_table = new_reftable;
412294054183SMax Reitz     new_reftable = NULL;
412394054183SMax Reitz 
412494054183SMax Reitz     /* Now the in-memory refcount information again corresponds to the on-disk
412594054183SMax Reitz      * information (reftable is empty and no refblocks (the refblock cache is
412694054183SMax Reitz      * empty)); however, this means some clusters (e.g. the image header) are
412794054183SMax Reitz      * referenced, but not refcounted, but the normal qcow2 code assumes that
412894054183SMax Reitz      * the in-memory information is always correct */
412994054183SMax Reitz 
413094054183SMax Reitz     BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_ALLOC);
413194054183SMax Reitz 
413294054183SMax Reitz     /* Enter the first refblock into the reftable */
413394054183SMax Reitz     rt_entry = cpu_to_be64(2 * s->cluster_size);
4134d9ca2ea2SKevin Wolf     ret = bdrv_pwrite_sync(bs->file, s->cluster_size,
413594054183SMax Reitz                            &rt_entry, sizeof(rt_entry));
413694054183SMax Reitz     if (ret < 0) {
413794054183SMax Reitz         goto fail_broken_refcounts;
413894054183SMax Reitz     }
413994054183SMax Reitz     s->refcount_table[0] = 2 * s->cluster_size;
414094054183SMax Reitz 
414194054183SMax Reitz     s->free_cluster_index = 0;
414294054183SMax Reitz     assert(3 + l1_clusters <= s->refcount_block_size);
414394054183SMax Reitz     offset = qcow2_alloc_clusters(bs, 3 * s->cluster_size + l1_size2);
414494054183SMax Reitz     if (offset < 0) {
414594054183SMax Reitz         ret = offset;
414694054183SMax Reitz         goto fail_broken_refcounts;
414794054183SMax Reitz     } else if (offset > 0) {
414894054183SMax Reitz         error_report("First cluster in emptied image is in use");
414994054183SMax Reitz         abort();
415094054183SMax Reitz     }
415194054183SMax Reitz 
415294054183SMax Reitz     /* Now finally the in-memory information corresponds to the on-disk
415394054183SMax Reitz      * structures and is correct */
415494054183SMax Reitz     ret = qcow2_mark_clean(bs);
415594054183SMax Reitz     if (ret < 0) {
415694054183SMax Reitz         goto fail;
415794054183SMax Reitz     }
415894054183SMax Reitz 
4159ed3d2ec9SMax Reitz     ret = bdrv_truncate(bs->file, (3 + l1_clusters) * s->cluster_size,
41607ea37c30SMax Reitz                         PREALLOC_MODE_OFF, &local_err);
416194054183SMax Reitz     if (ret < 0) {
4162ed3d2ec9SMax Reitz         error_report_err(local_err);
416394054183SMax Reitz         goto fail;
416494054183SMax Reitz     }
416594054183SMax Reitz 
416694054183SMax Reitz     return 0;
416794054183SMax Reitz 
416894054183SMax Reitz fail_broken_refcounts:
416994054183SMax Reitz     /* The BDS is unusable at this point. If we wanted to make it usable, we
417094054183SMax Reitz      * would have to call qcow2_refcount_close(), qcow2_refcount_init(),
417194054183SMax Reitz      * qcow2_check_refcounts(), qcow2_refcount_close() and qcow2_refcount_init()
417294054183SMax Reitz      * again. However, because the functions which could have caused this error
417394054183SMax Reitz      * path to be taken are used by those functions as well, it's very likely
417494054183SMax Reitz      * that that sequence will fail as well. Therefore, just eject the BDS. */
417594054183SMax Reitz     bs->drv = NULL;
417694054183SMax Reitz 
417794054183SMax Reitz fail:
417894054183SMax Reitz     g_free(new_reftable);
417994054183SMax Reitz     return ret;
418094054183SMax Reitz }
418194054183SMax Reitz 
4182491d27e2SMax Reitz static int qcow2_make_empty(BlockDriverState *bs)
4183491d27e2SMax Reitz {
4184ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
4185d2cb36afSEric Blake     uint64_t offset, end_offset;
4186d2cb36afSEric Blake     int step = QEMU_ALIGN_DOWN(INT_MAX, s->cluster_size);
418794054183SMax Reitz     int l1_clusters, ret = 0;
4188491d27e2SMax Reitz 
418994054183SMax Reitz     l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / sizeof(uint64_t));
419094054183SMax Reitz 
41914096974eSEric Blake     if (s->qcow_version >= 3 && !s->snapshots && !s->nb_bitmaps &&
4192f0603329SDaniel P. Berrange         3 + l1_clusters <= s->refcount_block_size &&
4193f0603329SDaniel P. Berrange         s->crypt_method_header != QCOW_CRYPT_LUKS) {
41944096974eSEric Blake         /* The following function only works for qcow2 v3 images (it
41954096974eSEric Blake          * requires the dirty flag) and only as long as there are no
41964096974eSEric Blake          * features that reserve extra clusters (such as snapshots,
41974096974eSEric Blake          * LUKS header, or persistent bitmaps), because it completely
41984096974eSEric Blake          * empties the image.  Furthermore, the L1 table and three
41994096974eSEric Blake          * additional clusters (image header, refcount table, one
42004096974eSEric Blake          * refcount block) have to fit inside one refcount block. */
420194054183SMax Reitz         return make_completely_empty(bs);
420294054183SMax Reitz     }
420394054183SMax Reitz 
420494054183SMax Reitz     /* This fallback code simply discards every active cluster; this is slow,
420594054183SMax Reitz      * but works in all cases */
4206d2cb36afSEric Blake     end_offset = bs->total_sectors * BDRV_SECTOR_SIZE;
4207d2cb36afSEric Blake     for (offset = 0; offset < end_offset; offset += step) {
4208491d27e2SMax Reitz         /* As this function is generally used after committing an external
4209491d27e2SMax Reitz          * snapshot, QCOW2_DISCARD_SNAPSHOT seems appropriate. Also, the
4210491d27e2SMax Reitz          * default action for this kind of discard is to pass the discard,
4211491d27e2SMax Reitz          * which will ideally result in an actually smaller image file, as
4212491d27e2SMax Reitz          * is probably desired. */
4213d2cb36afSEric Blake         ret = qcow2_cluster_discard(bs, offset, MIN(step, end_offset - offset),
4214491d27e2SMax Reitz                                     QCOW2_DISCARD_SNAPSHOT, true);
4215491d27e2SMax Reitz         if (ret < 0) {
4216491d27e2SMax Reitz             break;
4217491d27e2SMax Reitz         }
4218491d27e2SMax Reitz     }
4219491d27e2SMax Reitz 
4220491d27e2SMax Reitz     return ret;
4221491d27e2SMax Reitz }
4222491d27e2SMax Reitz 
4223a968168cSDong Xu Wang static coroutine_fn int qcow2_co_flush_to_os(BlockDriverState *bs)
422420d97356SBlue Swirl {
4225ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
422629c1a730SKevin Wolf     int ret;
422729c1a730SKevin Wolf 
42288b94ff85SPaolo Bonzini     qemu_co_mutex_lock(&s->lock);
42298b220eb7SPaolo Bonzini     ret = qcow2_write_caches(bs);
42308b94ff85SPaolo Bonzini     qemu_co_mutex_unlock(&s->lock);
423129c1a730SKevin Wolf 
42328b220eb7SPaolo Bonzini     return ret;
4233eb489bb1SKevin Wolf }
4234eb489bb1SKevin Wolf 
4235c501c352SStefan Hajnoczi static BlockMeasureInfo *qcow2_measure(QemuOpts *opts, BlockDriverState *in_bs,
4236c501c352SStefan Hajnoczi                                        Error **errp)
4237c501c352SStefan Hajnoczi {
4238c501c352SStefan Hajnoczi     Error *local_err = NULL;
4239c501c352SStefan Hajnoczi     BlockMeasureInfo *info;
4240c501c352SStefan Hajnoczi     uint64_t required = 0; /* bytes that contribute to required size */
4241c501c352SStefan Hajnoczi     uint64_t virtual_size; /* disk size as seen by guest */
4242c501c352SStefan Hajnoczi     uint64_t refcount_bits;
4243c501c352SStefan Hajnoczi     uint64_t l2_tables;
4244c501c352SStefan Hajnoczi     size_t cluster_size;
4245c501c352SStefan Hajnoczi     int version;
4246c501c352SStefan Hajnoczi     char *optstr;
4247c501c352SStefan Hajnoczi     PreallocMode prealloc;
4248c501c352SStefan Hajnoczi     bool has_backing_file;
4249c501c352SStefan Hajnoczi 
4250c501c352SStefan Hajnoczi     /* Parse image creation options */
4251c501c352SStefan Hajnoczi     cluster_size = qcow2_opt_get_cluster_size_del(opts, &local_err);
4252c501c352SStefan Hajnoczi     if (local_err) {
4253c501c352SStefan Hajnoczi         goto err;
4254c501c352SStefan Hajnoczi     }
4255c501c352SStefan Hajnoczi 
4256c501c352SStefan Hajnoczi     version = qcow2_opt_get_version_del(opts, &local_err);
4257c501c352SStefan Hajnoczi     if (local_err) {
4258c501c352SStefan Hajnoczi         goto err;
4259c501c352SStefan Hajnoczi     }
4260c501c352SStefan Hajnoczi 
4261c501c352SStefan Hajnoczi     refcount_bits = qcow2_opt_get_refcount_bits_del(opts, version, &local_err);
4262c501c352SStefan Hajnoczi     if (local_err) {
4263c501c352SStefan Hajnoczi         goto err;
4264c501c352SStefan Hajnoczi     }
4265c501c352SStefan Hajnoczi 
4266c501c352SStefan Hajnoczi     optstr = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
4267f7abe0ecSMarc-André Lureau     prealloc = qapi_enum_parse(&PreallocMode_lookup, optstr,
426806c60b6cSMarkus Armbruster                                PREALLOC_MODE_OFF, &local_err);
4269c501c352SStefan Hajnoczi     g_free(optstr);
4270c501c352SStefan Hajnoczi     if (local_err) {
4271c501c352SStefan Hajnoczi         goto err;
4272c501c352SStefan Hajnoczi     }
4273c501c352SStefan Hajnoczi 
4274c501c352SStefan Hajnoczi     optstr = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
4275c501c352SStefan Hajnoczi     has_backing_file = !!optstr;
4276c501c352SStefan Hajnoczi     g_free(optstr);
4277c501c352SStefan Hajnoczi 
42789e029689SAlberto Garcia     virtual_size = qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0);
42799e029689SAlberto Garcia     virtual_size = ROUND_UP(virtual_size, cluster_size);
4280c501c352SStefan Hajnoczi 
4281c501c352SStefan Hajnoczi     /* Check that virtual disk size is valid */
4282c501c352SStefan Hajnoczi     l2_tables = DIV_ROUND_UP(virtual_size / cluster_size,
4283c501c352SStefan Hajnoczi                              cluster_size / sizeof(uint64_t));
4284c501c352SStefan Hajnoczi     if (l2_tables * sizeof(uint64_t) > QCOW_MAX_L1_SIZE) {
4285c501c352SStefan Hajnoczi         error_setg(&local_err, "The image size is too large "
4286c501c352SStefan Hajnoczi                                "(try using a larger cluster size)");
4287c501c352SStefan Hajnoczi         goto err;
4288c501c352SStefan Hajnoczi     }
4289c501c352SStefan Hajnoczi 
4290c501c352SStefan Hajnoczi     /* Account for input image */
4291c501c352SStefan Hajnoczi     if (in_bs) {
4292c501c352SStefan Hajnoczi         int64_t ssize = bdrv_getlength(in_bs);
4293c501c352SStefan Hajnoczi         if (ssize < 0) {
4294c501c352SStefan Hajnoczi             error_setg_errno(&local_err, -ssize,
4295c501c352SStefan Hajnoczi                              "Unable to get image virtual_size");
4296c501c352SStefan Hajnoczi             goto err;
4297c501c352SStefan Hajnoczi         }
4298c501c352SStefan Hajnoczi 
42999e029689SAlberto Garcia         virtual_size = ROUND_UP(ssize, cluster_size);
4300c501c352SStefan Hajnoczi 
4301c501c352SStefan Hajnoczi         if (has_backing_file) {
4302c501c352SStefan Hajnoczi             /* We don't how much of the backing chain is shared by the input
4303c501c352SStefan Hajnoczi              * image and the new image file.  In the worst case the new image's
4304c501c352SStefan Hajnoczi              * backing file has nothing in common with the input image.  Be
4305c501c352SStefan Hajnoczi              * conservative and assume all clusters need to be written.
4306c501c352SStefan Hajnoczi              */
4307c501c352SStefan Hajnoczi             required = virtual_size;
4308c501c352SStefan Hajnoczi         } else {
4309b85ee453SEric Blake             int64_t offset;
431031826642SEric Blake             int64_t pnum = 0;
4311c501c352SStefan Hajnoczi 
431231826642SEric Blake             for (offset = 0; offset < ssize; offset += pnum) {
431331826642SEric Blake                 int ret;
4314c501c352SStefan Hajnoczi 
431531826642SEric Blake                 ret = bdrv_block_status_above(in_bs, NULL, offset,
431631826642SEric Blake                                               ssize - offset, &pnum, NULL,
431731826642SEric Blake                                               NULL);
4318c501c352SStefan Hajnoczi                 if (ret < 0) {
4319c501c352SStefan Hajnoczi                     error_setg_errno(&local_err, -ret,
4320c501c352SStefan Hajnoczi                                      "Unable to get block status");
4321c501c352SStefan Hajnoczi                     goto err;
4322c501c352SStefan Hajnoczi                 }
4323c501c352SStefan Hajnoczi 
4324c501c352SStefan Hajnoczi                 if (ret & BDRV_BLOCK_ZERO) {
4325c501c352SStefan Hajnoczi                     /* Skip zero regions (safe with no backing file) */
4326c501c352SStefan Hajnoczi                 } else if ((ret & (BDRV_BLOCK_DATA | BDRV_BLOCK_ALLOCATED)) ==
4327c501c352SStefan Hajnoczi                            (BDRV_BLOCK_DATA | BDRV_BLOCK_ALLOCATED)) {
4328c501c352SStefan Hajnoczi                     /* Extend pnum to end of cluster for next iteration */
432931826642SEric Blake                     pnum = ROUND_UP(offset + pnum, cluster_size) - offset;
4330c501c352SStefan Hajnoczi 
4331c501c352SStefan Hajnoczi                     /* Count clusters we've seen */
433231826642SEric Blake                     required += offset % cluster_size + pnum;
4333c501c352SStefan Hajnoczi                 }
4334c501c352SStefan Hajnoczi             }
4335c501c352SStefan Hajnoczi         }
4336c501c352SStefan Hajnoczi     }
4337c501c352SStefan Hajnoczi 
4338c501c352SStefan Hajnoczi     /* Take into account preallocation.  Nothing special is needed for
4339c501c352SStefan Hajnoczi      * PREALLOC_MODE_METADATA since metadata is always counted.
4340c501c352SStefan Hajnoczi      */
4341c501c352SStefan Hajnoczi     if (prealloc == PREALLOC_MODE_FULL || prealloc == PREALLOC_MODE_FALLOC) {
4342c501c352SStefan Hajnoczi         required = virtual_size;
4343c501c352SStefan Hajnoczi     }
4344c501c352SStefan Hajnoczi 
4345c501c352SStefan Hajnoczi     info = g_new(BlockMeasureInfo, 1);
4346c501c352SStefan Hajnoczi     info->fully_allocated =
4347c501c352SStefan Hajnoczi         qcow2_calc_prealloc_size(virtual_size, cluster_size,
4348c501c352SStefan Hajnoczi                                  ctz32(refcount_bits));
4349c501c352SStefan Hajnoczi 
4350c501c352SStefan Hajnoczi     /* Remove data clusters that are not required.  This overestimates the
4351c501c352SStefan Hajnoczi      * required size because metadata needed for the fully allocated file is
4352c501c352SStefan Hajnoczi      * still counted.
4353c501c352SStefan Hajnoczi      */
4354c501c352SStefan Hajnoczi     info->required = info->fully_allocated - virtual_size + required;
4355c501c352SStefan Hajnoczi     return info;
4356c501c352SStefan Hajnoczi 
4357c501c352SStefan Hajnoczi err:
4358c501c352SStefan Hajnoczi     error_propagate(errp, local_err);
4359c501c352SStefan Hajnoczi     return NULL;
4360c501c352SStefan Hajnoczi }
4361c501c352SStefan Hajnoczi 
43627c80ab3fSJes Sorensen static int qcow2_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
436320d97356SBlue Swirl {
4364ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
436595de6d70SPaolo Bonzini     bdi->unallocated_blocks_are_zero = true;
436620d97356SBlue Swirl     bdi->cluster_size = s->cluster_size;
43677c80ab3fSJes Sorensen     bdi->vm_state_offset = qcow2_vm_state_offset(s);
436820d97356SBlue Swirl     return 0;
436920d97356SBlue Swirl }
437020d97356SBlue Swirl 
4371*1bf6e9caSAndrey Shinkevich static ImageInfoSpecific *qcow2_get_specific_info(BlockDriverState *bs,
4372*1bf6e9caSAndrey Shinkevich                                                   Error **errp)
437337764dfbSMax Reitz {
4374ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
43750a12f6f8SDaniel P. Berrange     ImageInfoSpecific *spec_info;
43760a12f6f8SDaniel P. Berrange     QCryptoBlockInfo *encrypt_info = NULL;
4377*1bf6e9caSAndrey Shinkevich     Error *local_err = NULL;
437837764dfbSMax Reitz 
43790a12f6f8SDaniel P. Berrange     if (s->crypto != NULL) {
4380*1bf6e9caSAndrey Shinkevich         encrypt_info = qcrypto_block_get_info(s->crypto, &local_err);
4381*1bf6e9caSAndrey Shinkevich         if (local_err) {
4382*1bf6e9caSAndrey Shinkevich             error_propagate(errp, local_err);
4383*1bf6e9caSAndrey Shinkevich             return NULL;
4384*1bf6e9caSAndrey Shinkevich         }
43850a12f6f8SDaniel P. Berrange     }
43860a12f6f8SDaniel P. Berrange 
43870a12f6f8SDaniel P. Berrange     spec_info = g_new(ImageInfoSpecific, 1);
438837764dfbSMax Reitz     *spec_info = (ImageInfoSpecific){
43896a8f9661SEric Blake         .type  = IMAGE_INFO_SPECIFIC_KIND_QCOW2,
439032bafa8fSEric Blake         .u.qcow2.data = g_new(ImageInfoSpecificQCow2, 1),
439137764dfbSMax Reitz     };
439237764dfbSMax Reitz     if (s->qcow_version == 2) {
439332bafa8fSEric Blake         *spec_info->u.qcow2.data = (ImageInfoSpecificQCow2){
439437764dfbSMax Reitz             .compat             = g_strdup("0.10"),
43950709c5a1SMax Reitz             .refcount_bits      = s->refcount_bits,
439637764dfbSMax Reitz         };
439737764dfbSMax Reitz     } else if (s->qcow_version == 3) {
439832bafa8fSEric Blake         *spec_info->u.qcow2.data = (ImageInfoSpecificQCow2){
439937764dfbSMax Reitz             .compat             = g_strdup("1.1"),
440037764dfbSMax Reitz             .lazy_refcounts     = s->compatible_features &
440137764dfbSMax Reitz                                   QCOW2_COMPAT_LAZY_REFCOUNTS,
440237764dfbSMax Reitz             .has_lazy_refcounts = true,
44039009b196SMax Reitz             .corrupt            = s->incompatible_features &
44049009b196SMax Reitz                                   QCOW2_INCOMPAT_CORRUPT,
44059009b196SMax Reitz             .has_corrupt        = true,
44060709c5a1SMax Reitz             .refcount_bits      = s->refcount_bits,
440737764dfbSMax Reitz         };
4408b1fc8f93SDenis V. Lunev     } else {
4409b1fc8f93SDenis V. Lunev         /* if this assertion fails, this probably means a new version was
4410b1fc8f93SDenis V. Lunev          * added without having it covered here */
4411b1fc8f93SDenis V. Lunev         assert(false);
441237764dfbSMax Reitz     }
441337764dfbSMax Reitz 
44140a12f6f8SDaniel P. Berrange     if (encrypt_info) {
44150a12f6f8SDaniel P. Berrange         ImageInfoSpecificQCow2Encryption *qencrypt =
44160a12f6f8SDaniel P. Berrange             g_new(ImageInfoSpecificQCow2Encryption, 1);
44170a12f6f8SDaniel P. Berrange         switch (encrypt_info->format) {
44180a12f6f8SDaniel P. Berrange         case Q_CRYPTO_BLOCK_FORMAT_QCOW:
44190a12f6f8SDaniel P. Berrange             qencrypt->format = BLOCKDEV_QCOW2_ENCRYPTION_FORMAT_AES;
44200a12f6f8SDaniel P. Berrange             break;
44210a12f6f8SDaniel P. Berrange         case Q_CRYPTO_BLOCK_FORMAT_LUKS:
44220a12f6f8SDaniel P. Berrange             qencrypt->format = BLOCKDEV_QCOW2_ENCRYPTION_FORMAT_LUKS;
44230a12f6f8SDaniel P. Berrange             qencrypt->u.luks = encrypt_info->u.luks;
44240a12f6f8SDaniel P. Berrange             break;
44250a12f6f8SDaniel P. Berrange         default:
44260a12f6f8SDaniel P. Berrange             abort();
44270a12f6f8SDaniel P. Berrange         }
44280a12f6f8SDaniel P. Berrange         /* Since we did shallow copy above, erase any pointers
44290a12f6f8SDaniel P. Berrange          * in the original info */
44300a12f6f8SDaniel P. Berrange         memset(&encrypt_info->u, 0, sizeof(encrypt_info->u));
44310a12f6f8SDaniel P. Berrange         qapi_free_QCryptoBlockInfo(encrypt_info);
44320a12f6f8SDaniel P. Berrange 
44330a12f6f8SDaniel P. Berrange         spec_info->u.qcow2.data->has_encrypt = true;
44340a12f6f8SDaniel P. Berrange         spec_info->u.qcow2.data->encrypt = qencrypt;
44350a12f6f8SDaniel P. Berrange     }
44360a12f6f8SDaniel P. Berrange 
443737764dfbSMax Reitz     return spec_info;
443837764dfbSMax Reitz }
443937764dfbSMax Reitz 
4440cf8074b3SKevin Wolf static int qcow2_save_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
4441cf8074b3SKevin Wolf                               int64_t pos)
444220d97356SBlue Swirl {
4443ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
444420d97356SBlue Swirl 
444566f82ceeSKevin Wolf     BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_SAVE);
4446734a7758SKevin Wolf     return bs->drv->bdrv_co_pwritev(bs, qcow2_vm_state_offset(s) + pos,
4447734a7758SKevin Wolf                                     qiov->size, qiov, 0);
444820d97356SBlue Swirl }
444920d97356SBlue Swirl 
44505ddda0b8SKevin Wolf static int qcow2_load_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
44515ddda0b8SKevin Wolf                               int64_t pos)
445220d97356SBlue Swirl {
4453ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
445420d97356SBlue Swirl 
445566f82ceeSKevin Wolf     BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_LOAD);
4456734a7758SKevin Wolf     return bs->drv->bdrv_co_preadv(bs, qcow2_vm_state_offset(s) + pos,
4457734a7758SKevin Wolf                                    qiov->size, qiov, 0);
445820d97356SBlue Swirl }
445920d97356SBlue Swirl 
44609296b3edSMax Reitz /*
44619296b3edSMax Reitz  * Downgrades an image's version. To achieve this, any incompatible features
44629296b3edSMax Reitz  * have to be removed.
44639296b3edSMax Reitz  */
44644057a2b2SMax Reitz static int qcow2_downgrade(BlockDriverState *bs, int target_version,
4465d1402b50SMax Reitz                            BlockDriverAmendStatusCB *status_cb, void *cb_opaque,
4466d1402b50SMax Reitz                            Error **errp)
44679296b3edSMax Reitz {
4468ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
44699296b3edSMax Reitz     int current_version = s->qcow_version;
44709296b3edSMax Reitz     int ret;
44719296b3edSMax Reitz 
4472d1402b50SMax Reitz     /* This is qcow2_downgrade(), not qcow2_upgrade() */
4473d1402b50SMax Reitz     assert(target_version < current_version);
4474d1402b50SMax Reitz 
4475d1402b50SMax Reitz     /* There are no other versions (now) that you can downgrade to */
4476d1402b50SMax Reitz     assert(target_version == 2);
44779296b3edSMax Reitz 
44789296b3edSMax Reitz     if (s->refcount_order != 4) {
4479d1402b50SMax Reitz         error_setg(errp, "compat=0.10 requires refcount_bits=16");
44809296b3edSMax Reitz         return -ENOTSUP;
44819296b3edSMax Reitz     }
44829296b3edSMax Reitz 
44839296b3edSMax Reitz     /* clear incompatible features */
44849296b3edSMax Reitz     if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
44859296b3edSMax Reitz         ret = qcow2_mark_clean(bs);
44869296b3edSMax Reitz         if (ret < 0) {
4487d1402b50SMax Reitz             error_setg_errno(errp, -ret, "Failed to make the image clean");
44889296b3edSMax Reitz             return ret;
44899296b3edSMax Reitz         }
44909296b3edSMax Reitz     }
44919296b3edSMax Reitz 
44929296b3edSMax Reitz     /* with QCOW2_INCOMPAT_CORRUPT, it is pretty much impossible to get here in
44939296b3edSMax Reitz      * the first place; if that happens nonetheless, returning -ENOTSUP is the
44949296b3edSMax Reitz      * best thing to do anyway */
44959296b3edSMax Reitz 
44969296b3edSMax Reitz     if (s->incompatible_features) {
4497d1402b50SMax Reitz         error_setg(errp, "Cannot downgrade an image with incompatible features "
4498d1402b50SMax Reitz                    "%#" PRIx64 " set", s->incompatible_features);
44999296b3edSMax Reitz         return -ENOTSUP;
45009296b3edSMax Reitz     }
45019296b3edSMax Reitz 
45029296b3edSMax Reitz     /* since we can ignore compatible features, we can set them to 0 as well */
45039296b3edSMax Reitz     s->compatible_features = 0;
45049296b3edSMax Reitz     /* if lazy refcounts have been used, they have already been fixed through
45059296b3edSMax Reitz      * clearing the dirty flag */
45069296b3edSMax Reitz 
45079296b3edSMax Reitz     /* clearing autoclear features is trivial */
45089296b3edSMax Reitz     s->autoclear_features = 0;
45099296b3edSMax Reitz 
45108b13976dSMax Reitz     ret = qcow2_expand_zero_clusters(bs, status_cb, cb_opaque);
45119296b3edSMax Reitz     if (ret < 0) {
4512d1402b50SMax Reitz         error_setg_errno(errp, -ret, "Failed to turn zero into data clusters");
45139296b3edSMax Reitz         return ret;
45149296b3edSMax Reitz     }
45159296b3edSMax Reitz 
45169296b3edSMax Reitz     s->qcow_version = target_version;
45179296b3edSMax Reitz     ret = qcow2_update_header(bs);
45189296b3edSMax Reitz     if (ret < 0) {
45199296b3edSMax Reitz         s->qcow_version = current_version;
4520d1402b50SMax Reitz         error_setg_errno(errp, -ret, "Failed to update the image header");
45219296b3edSMax Reitz         return ret;
45229296b3edSMax Reitz     }
45239296b3edSMax Reitz     return 0;
45249296b3edSMax Reitz }
45259296b3edSMax Reitz 
4526c293a809SMax Reitz typedef enum Qcow2AmendOperation {
4527c293a809SMax Reitz     /* This is the value Qcow2AmendHelperCBInfo::last_operation will be
4528c293a809SMax Reitz      * statically initialized to so that the helper CB can discern the first
4529c293a809SMax Reitz      * invocation from an operation change */
4530c293a809SMax Reitz     QCOW2_NO_OPERATION = 0,
4531c293a809SMax Reitz 
453261ce55fcSMax Reitz     QCOW2_CHANGING_REFCOUNT_ORDER,
4533c293a809SMax Reitz     QCOW2_DOWNGRADING,
4534c293a809SMax Reitz } Qcow2AmendOperation;
4535c293a809SMax Reitz 
4536c293a809SMax Reitz typedef struct Qcow2AmendHelperCBInfo {
4537c293a809SMax Reitz     /* The code coordinating the amend operations should only modify
4538c293a809SMax Reitz      * these four fields; the rest will be managed by the CB */
4539c293a809SMax Reitz     BlockDriverAmendStatusCB *original_status_cb;
4540c293a809SMax Reitz     void *original_cb_opaque;
4541c293a809SMax Reitz 
4542c293a809SMax Reitz     Qcow2AmendOperation current_operation;
4543c293a809SMax Reitz 
4544c293a809SMax Reitz     /* Total number of operations to perform (only set once) */
4545c293a809SMax Reitz     int total_operations;
4546c293a809SMax Reitz 
4547c293a809SMax Reitz     /* The following fields are managed by the CB */
4548c293a809SMax Reitz 
4549c293a809SMax Reitz     /* Number of operations completed */
4550c293a809SMax Reitz     int operations_completed;
4551c293a809SMax Reitz 
4552c293a809SMax Reitz     /* Cumulative offset of all completed operations */
4553c293a809SMax Reitz     int64_t offset_completed;
4554c293a809SMax Reitz 
4555c293a809SMax Reitz     Qcow2AmendOperation last_operation;
4556c293a809SMax Reitz     int64_t last_work_size;
4557c293a809SMax Reitz } Qcow2AmendHelperCBInfo;
4558c293a809SMax Reitz 
4559c293a809SMax Reitz static void qcow2_amend_helper_cb(BlockDriverState *bs,
4560c293a809SMax Reitz                                   int64_t operation_offset,
4561c293a809SMax Reitz                                   int64_t operation_work_size, void *opaque)
4562c293a809SMax Reitz {
4563c293a809SMax Reitz     Qcow2AmendHelperCBInfo *info = opaque;
4564c293a809SMax Reitz     int64_t current_work_size;
4565c293a809SMax Reitz     int64_t projected_work_size;
4566c293a809SMax Reitz 
4567c293a809SMax Reitz     if (info->current_operation != info->last_operation) {
4568c293a809SMax Reitz         if (info->last_operation != QCOW2_NO_OPERATION) {
4569c293a809SMax Reitz             info->offset_completed += info->last_work_size;
4570c293a809SMax Reitz             info->operations_completed++;
4571c293a809SMax Reitz         }
4572c293a809SMax Reitz 
4573c293a809SMax Reitz         info->last_operation = info->current_operation;
4574c293a809SMax Reitz     }
4575c293a809SMax Reitz 
4576c293a809SMax Reitz     assert(info->total_operations > 0);
4577c293a809SMax Reitz     assert(info->operations_completed < info->total_operations);
4578c293a809SMax Reitz 
4579c293a809SMax Reitz     info->last_work_size = operation_work_size;
4580c293a809SMax Reitz 
4581c293a809SMax Reitz     current_work_size = info->offset_completed + operation_work_size;
4582c293a809SMax Reitz 
4583c293a809SMax Reitz     /* current_work_size is the total work size for (operations_completed + 1)
4584c293a809SMax Reitz      * operations (which includes this one), so multiply it by the number of
4585c293a809SMax Reitz      * operations not covered and divide it by the number of operations
4586c293a809SMax Reitz      * covered to get a projection for the operations not covered */
4587c293a809SMax Reitz     projected_work_size = current_work_size * (info->total_operations -
4588c293a809SMax Reitz                                                info->operations_completed - 1)
4589c293a809SMax Reitz                                             / (info->operations_completed + 1);
4590c293a809SMax Reitz 
4591c293a809SMax Reitz     info->original_status_cb(bs, info->offset_completed + operation_offset,
4592c293a809SMax Reitz                              current_work_size + projected_work_size,
4593c293a809SMax Reitz                              info->original_cb_opaque);
4594c293a809SMax Reitz }
4595c293a809SMax Reitz 
459677485434SMax Reitz static int qcow2_amend_options(BlockDriverState *bs, QemuOpts *opts,
45978b13976dSMax Reitz                                BlockDriverAmendStatusCB *status_cb,
4598d1402b50SMax Reitz                                void *cb_opaque,
4599d1402b50SMax Reitz                                Error **errp)
46009296b3edSMax Reitz {
4601ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
46029296b3edSMax Reitz     int old_version = s->qcow_version, new_version = old_version;
46039296b3edSMax Reitz     uint64_t new_size = 0;
46049296b3edSMax Reitz     const char *backing_file = NULL, *backing_format = NULL;
46059296b3edSMax Reitz     bool lazy_refcounts = s->use_lazy_refcounts;
46061bd0e2d1SChunyan Liu     const char *compat = NULL;
46071bd0e2d1SChunyan Liu     uint64_t cluster_size = s->cluster_size;
46081bd0e2d1SChunyan Liu     bool encrypt;
46094652b8f3SDaniel P. Berrange     int encformat;
461061ce55fcSMax Reitz     int refcount_bits = s->refcount_bits;
46119296b3edSMax Reitz     int ret;
46121bd0e2d1SChunyan Liu     QemuOptDesc *desc = opts->list->desc;
4613c293a809SMax Reitz     Qcow2AmendHelperCBInfo helper_cb_info;
46149296b3edSMax Reitz 
46151bd0e2d1SChunyan Liu     while (desc && desc->name) {
46161bd0e2d1SChunyan Liu         if (!qemu_opt_find(opts, desc->name)) {
46179296b3edSMax Reitz             /* only change explicitly defined options */
46181bd0e2d1SChunyan Liu             desc++;
46199296b3edSMax Reitz             continue;
46209296b3edSMax Reitz         }
46219296b3edSMax Reitz 
46228a17b83cSMax Reitz         if (!strcmp(desc->name, BLOCK_OPT_COMPAT_LEVEL)) {
46238a17b83cSMax Reitz             compat = qemu_opt_get(opts, BLOCK_OPT_COMPAT_LEVEL);
46241bd0e2d1SChunyan Liu             if (!compat) {
46259296b3edSMax Reitz                 /* preserve default */
46261bd0e2d1SChunyan Liu             } else if (!strcmp(compat, "0.10")) {
46279296b3edSMax Reitz                 new_version = 2;
46281bd0e2d1SChunyan Liu             } else if (!strcmp(compat, "1.1")) {
46299296b3edSMax Reitz                 new_version = 3;
46309296b3edSMax Reitz             } else {
4631d1402b50SMax Reitz                 error_setg(errp, "Unknown compatibility level %s", compat);
46329296b3edSMax Reitz                 return -EINVAL;
46339296b3edSMax Reitz             }
46348a17b83cSMax Reitz         } else if (!strcmp(desc->name, BLOCK_OPT_PREALLOC)) {
4635d1402b50SMax Reitz             error_setg(errp, "Cannot change preallocation mode");
46369296b3edSMax Reitz             return -ENOTSUP;
46378a17b83cSMax Reitz         } else if (!strcmp(desc->name, BLOCK_OPT_SIZE)) {
46388a17b83cSMax Reitz             new_size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, 0);
46398a17b83cSMax Reitz         } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FILE)) {
46408a17b83cSMax Reitz             backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
46418a17b83cSMax Reitz         } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FMT)) {
46428a17b83cSMax Reitz             backing_format = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
46438a17b83cSMax Reitz         } else if (!strcmp(desc->name, BLOCK_OPT_ENCRYPT)) {
46448a17b83cSMax Reitz             encrypt = qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT,
4645b25b387fSDaniel P. Berrange                                         !!s->crypto);
4646f6fa64f6SDaniel P. Berrange 
4647b25b387fSDaniel P. Berrange             if (encrypt != !!s->crypto) {
4648d1402b50SMax Reitz                 error_setg(errp,
4649d1402b50SMax Reitz                            "Changing the encryption flag is not supported");
46509296b3edSMax Reitz                 return -ENOTSUP;
46519296b3edSMax Reitz             }
46524652b8f3SDaniel P. Berrange         } else if (!strcmp(desc->name, BLOCK_OPT_ENCRYPT_FORMAT)) {
46534652b8f3SDaniel P. Berrange             encformat = qcow2_crypt_method_from_format(
46544652b8f3SDaniel P. Berrange                 qemu_opt_get(opts, BLOCK_OPT_ENCRYPT_FORMAT));
46554652b8f3SDaniel P. Berrange 
46564652b8f3SDaniel P. Berrange             if (encformat != s->crypt_method_header) {
4657d1402b50SMax Reitz                 error_setg(errp,
4658d1402b50SMax Reitz                            "Changing the encryption format is not supported");
46594652b8f3SDaniel P. Berrange                 return -ENOTSUP;
46604652b8f3SDaniel P. Berrange             }
4661f66afbe2SDaniel P. Berrange         } else if (g_str_has_prefix(desc->name, "encrypt.")) {
4662d1402b50SMax Reitz             error_setg(errp,
4663d1402b50SMax Reitz                        "Changing the encryption parameters is not supported");
4664f66afbe2SDaniel P. Berrange             return -ENOTSUP;
46658a17b83cSMax Reitz         } else if (!strcmp(desc->name, BLOCK_OPT_CLUSTER_SIZE)) {
46668a17b83cSMax Reitz             cluster_size = qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE,
46671bd0e2d1SChunyan Liu                                              cluster_size);
46681bd0e2d1SChunyan Liu             if (cluster_size != s->cluster_size) {
4669d1402b50SMax Reitz                 error_setg(errp, "Changing the cluster size is not supported");
46709296b3edSMax Reitz                 return -ENOTSUP;
46719296b3edSMax Reitz             }
46728a17b83cSMax Reitz         } else if (!strcmp(desc->name, BLOCK_OPT_LAZY_REFCOUNTS)) {
46738a17b83cSMax Reitz             lazy_refcounts = qemu_opt_get_bool(opts, BLOCK_OPT_LAZY_REFCOUNTS,
46741bd0e2d1SChunyan Liu                                                lazy_refcounts);
467506d05fa7SMax Reitz         } else if (!strcmp(desc->name, BLOCK_OPT_REFCOUNT_BITS)) {
467661ce55fcSMax Reitz             refcount_bits = qemu_opt_get_number(opts, BLOCK_OPT_REFCOUNT_BITS,
467761ce55fcSMax Reitz                                                 refcount_bits);
467861ce55fcSMax Reitz 
467961ce55fcSMax Reitz             if (refcount_bits <= 0 || refcount_bits > 64 ||
468061ce55fcSMax Reitz                 !is_power_of_2(refcount_bits))
468161ce55fcSMax Reitz             {
4682d1402b50SMax Reitz                 error_setg(errp, "Refcount width must be a power of two and "
4683d1402b50SMax Reitz                            "may not exceed 64 bits");
468461ce55fcSMax Reitz                 return -EINVAL;
468561ce55fcSMax Reitz             }
46869296b3edSMax Reitz         } else {
4687164e0f89SMax Reitz             /* if this point is reached, this probably means a new option was
46889296b3edSMax Reitz              * added without having it covered here */
4689164e0f89SMax Reitz             abort();
46909296b3edSMax Reitz         }
46911bd0e2d1SChunyan Liu 
46921bd0e2d1SChunyan Liu         desc++;
46939296b3edSMax Reitz     }
46949296b3edSMax Reitz 
4695c293a809SMax Reitz     helper_cb_info = (Qcow2AmendHelperCBInfo){
4696c293a809SMax Reitz         .original_status_cb = status_cb,
4697c293a809SMax Reitz         .original_cb_opaque = cb_opaque,
4698c293a809SMax Reitz         .total_operations = (new_version < old_version)
469961ce55fcSMax Reitz                           + (s->refcount_bits != refcount_bits)
4700c293a809SMax Reitz     };
4701c293a809SMax Reitz 
47021038bbb8SMax Reitz     /* Upgrade first (some features may require compat=1.1) */
47039296b3edSMax Reitz     if (new_version > old_version) {
47049296b3edSMax Reitz         s->qcow_version = new_version;
47059296b3edSMax Reitz         ret = qcow2_update_header(bs);
47069296b3edSMax Reitz         if (ret < 0) {
47079296b3edSMax Reitz             s->qcow_version = old_version;
4708d1402b50SMax Reitz             error_setg_errno(errp, -ret, "Failed to update the image header");
47099296b3edSMax Reitz             return ret;
47109296b3edSMax Reitz         }
47119296b3edSMax Reitz     }
47129296b3edSMax Reitz 
471361ce55fcSMax Reitz     if (s->refcount_bits != refcount_bits) {
471461ce55fcSMax Reitz         int refcount_order = ctz32(refcount_bits);
471561ce55fcSMax Reitz 
471661ce55fcSMax Reitz         if (new_version < 3 && refcount_bits != 16) {
4717d1402b50SMax Reitz             error_setg(errp, "Refcount widths other than 16 bits require "
471861ce55fcSMax Reitz                        "compatibility level 1.1 or above (use compat=1.1 or "
471961ce55fcSMax Reitz                        "greater)");
472061ce55fcSMax Reitz             return -EINVAL;
472161ce55fcSMax Reitz         }
472261ce55fcSMax Reitz 
472361ce55fcSMax Reitz         helper_cb_info.current_operation = QCOW2_CHANGING_REFCOUNT_ORDER;
472461ce55fcSMax Reitz         ret = qcow2_change_refcount_order(bs, refcount_order,
472561ce55fcSMax Reitz                                           &qcow2_amend_helper_cb,
4726d1402b50SMax Reitz                                           &helper_cb_info, errp);
472761ce55fcSMax Reitz         if (ret < 0) {
472861ce55fcSMax Reitz             return ret;
472961ce55fcSMax Reitz         }
473061ce55fcSMax Reitz     }
473161ce55fcSMax Reitz 
47329296b3edSMax Reitz     if (backing_file || backing_format) {
4733e4603fe1SKevin Wolf         ret = qcow2_change_backing_file(bs,
4734e4603fe1SKevin Wolf                     backing_file ?: s->image_backing_file,
4735e4603fe1SKevin Wolf                     backing_format ?: s->image_backing_format);
47369296b3edSMax Reitz         if (ret < 0) {
4737d1402b50SMax Reitz             error_setg_errno(errp, -ret, "Failed to change the backing file");
47389296b3edSMax Reitz             return ret;
47399296b3edSMax Reitz         }
47409296b3edSMax Reitz     }
47419296b3edSMax Reitz 
47429296b3edSMax Reitz     if (s->use_lazy_refcounts != lazy_refcounts) {
47439296b3edSMax Reitz         if (lazy_refcounts) {
47441038bbb8SMax Reitz             if (new_version < 3) {
4745d1402b50SMax Reitz                 error_setg(errp, "Lazy refcounts only supported with "
4746d1402b50SMax Reitz                            "compatibility level 1.1 and above (use compat=1.1 "
4747d1402b50SMax Reitz                            "or greater)");
47489296b3edSMax Reitz                 return -EINVAL;
47499296b3edSMax Reitz             }
47509296b3edSMax Reitz             s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
47519296b3edSMax Reitz             ret = qcow2_update_header(bs);
47529296b3edSMax Reitz             if (ret < 0) {
47539296b3edSMax Reitz                 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
4754d1402b50SMax Reitz                 error_setg_errno(errp, -ret, "Failed to update the image header");
47559296b3edSMax Reitz                 return ret;
47569296b3edSMax Reitz             }
47579296b3edSMax Reitz             s->use_lazy_refcounts = true;
47589296b3edSMax Reitz         } else {
47599296b3edSMax Reitz             /* make image clean first */
47609296b3edSMax Reitz             ret = qcow2_mark_clean(bs);
47619296b3edSMax Reitz             if (ret < 0) {
4762d1402b50SMax Reitz                 error_setg_errno(errp, -ret, "Failed to make the image clean");
47639296b3edSMax Reitz                 return ret;
47649296b3edSMax Reitz             }
47659296b3edSMax Reitz             /* now disallow lazy refcounts */
47669296b3edSMax Reitz             s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
47679296b3edSMax Reitz             ret = qcow2_update_header(bs);
47689296b3edSMax Reitz             if (ret < 0) {
47699296b3edSMax Reitz                 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
4770d1402b50SMax Reitz                 error_setg_errno(errp, -ret, "Failed to update the image header");
47719296b3edSMax Reitz                 return ret;
47729296b3edSMax Reitz             }
47739296b3edSMax Reitz             s->use_lazy_refcounts = false;
47749296b3edSMax Reitz         }
47759296b3edSMax Reitz     }
47769296b3edSMax Reitz 
47779296b3edSMax Reitz     if (new_size) {
47786d0eb64dSKevin Wolf         BlockBackend *blk = blk_new(BLK_PERM_RESIZE, BLK_PERM_ALL);
4779d1402b50SMax Reitz         ret = blk_insert_bs(blk, bs, errp);
4780d7086422SKevin Wolf         if (ret < 0) {
4781d7086422SKevin Wolf             blk_unref(blk);
4782d7086422SKevin Wolf             return ret;
4783d7086422SKevin Wolf         }
4784d7086422SKevin Wolf 
4785d1402b50SMax Reitz         ret = blk_truncate(blk, new_size, PREALLOC_MODE_OFF, errp);
478670b27f36SKevin Wolf         blk_unref(blk);
47879296b3edSMax Reitz         if (ret < 0) {
47889296b3edSMax Reitz             return ret;
47899296b3edSMax Reitz         }
47909296b3edSMax Reitz     }
47919296b3edSMax Reitz 
47921038bbb8SMax Reitz     /* Downgrade last (so unsupported features can be removed before) */
47931038bbb8SMax Reitz     if (new_version < old_version) {
4794c293a809SMax Reitz         helper_cb_info.current_operation = QCOW2_DOWNGRADING;
4795c293a809SMax Reitz         ret = qcow2_downgrade(bs, new_version, &qcow2_amend_helper_cb,
4796d1402b50SMax Reitz                               &helper_cb_info, errp);
47971038bbb8SMax Reitz         if (ret < 0) {
47981038bbb8SMax Reitz             return ret;
47991038bbb8SMax Reitz         }
48001038bbb8SMax Reitz     }
48011038bbb8SMax Reitz 
48029296b3edSMax Reitz     return 0;
48039296b3edSMax Reitz }
48049296b3edSMax Reitz 
480585186ebdSMax Reitz /*
480685186ebdSMax Reitz  * If offset or size are negative, respectively, they will not be included in
480785186ebdSMax Reitz  * the BLOCK_IMAGE_CORRUPTED event emitted.
480885186ebdSMax Reitz  * fatal will be ignored for read-only BDS; corruptions found there will always
480985186ebdSMax Reitz  * be considered non-fatal.
481085186ebdSMax Reitz  */
481185186ebdSMax Reitz void qcow2_signal_corruption(BlockDriverState *bs, bool fatal, int64_t offset,
481285186ebdSMax Reitz                              int64_t size, const char *message_format, ...)
481385186ebdSMax Reitz {
4814ff99129aSKevin Wolf     BDRVQcow2State *s = bs->opaque;
4815dc881b44SAlberto Garcia     const char *node_name;
481685186ebdSMax Reitz     char *message;
481785186ebdSMax Reitz     va_list ap;
481885186ebdSMax Reitz 
4819ddf3b47eSMax Reitz     fatal = fatal && bdrv_is_writable(bs);
482085186ebdSMax Reitz 
482185186ebdSMax Reitz     if (s->signaled_corruption &&
482285186ebdSMax Reitz         (!fatal || (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT)))
482385186ebdSMax Reitz     {
482485186ebdSMax Reitz         return;
482585186ebdSMax Reitz     }
482685186ebdSMax Reitz 
482785186ebdSMax Reitz     va_start(ap, message_format);
482885186ebdSMax Reitz     message = g_strdup_vprintf(message_format, ap);
482985186ebdSMax Reitz     va_end(ap);
483085186ebdSMax Reitz 
483185186ebdSMax Reitz     if (fatal) {
483285186ebdSMax Reitz         fprintf(stderr, "qcow2: Marking image as corrupt: %s; further "
483385186ebdSMax Reitz                 "corruption events will be suppressed\n", message);
483485186ebdSMax Reitz     } else {
483585186ebdSMax Reitz         fprintf(stderr, "qcow2: Image is corrupt: %s; further non-fatal "
483685186ebdSMax Reitz                 "corruption events will be suppressed\n", message);
483785186ebdSMax Reitz     }
483885186ebdSMax Reitz 
4839dc881b44SAlberto Garcia     node_name = bdrv_get_node_name(bs);
4840dc881b44SAlberto Garcia     qapi_event_send_block_image_corrupted(bdrv_get_device_name(bs),
4841dc881b44SAlberto Garcia                                           *node_name != '\0', node_name,
4842dc881b44SAlberto Garcia                                           message, offset >= 0, offset,
4843dc881b44SAlberto Garcia                                           size >= 0, size,
48443ab72385SPeter Xu                                           fatal);
484585186ebdSMax Reitz     g_free(message);
484685186ebdSMax Reitz 
484785186ebdSMax Reitz     if (fatal) {
484885186ebdSMax Reitz         qcow2_mark_corrupt(bs);
484985186ebdSMax Reitz         bs->drv = NULL; /* make BDS unusable */
485085186ebdSMax Reitz     }
485185186ebdSMax Reitz 
485285186ebdSMax Reitz     s->signaled_corruption = true;
485385186ebdSMax Reitz }
485485186ebdSMax Reitz 
48551bd0e2d1SChunyan Liu static QemuOptsList qcow2_create_opts = {
48561bd0e2d1SChunyan Liu     .name = "qcow2-create-opts",
48571bd0e2d1SChunyan Liu     .head = QTAILQ_HEAD_INITIALIZER(qcow2_create_opts.head),
48581bd0e2d1SChunyan Liu     .desc = {
485920d97356SBlue Swirl         {
486020d97356SBlue Swirl             .name = BLOCK_OPT_SIZE,
48611bd0e2d1SChunyan Liu             .type = QEMU_OPT_SIZE,
486220d97356SBlue Swirl             .help = "Virtual disk size"
486320d97356SBlue Swirl         },
486420d97356SBlue Swirl         {
48656744cbabSKevin Wolf             .name = BLOCK_OPT_COMPAT_LEVEL,
48661bd0e2d1SChunyan Liu             .type = QEMU_OPT_STRING,
48676744cbabSKevin Wolf             .help = "Compatibility level (0.10 or 1.1)"
48686744cbabSKevin Wolf         },
48696744cbabSKevin Wolf         {
487020d97356SBlue Swirl             .name = BLOCK_OPT_BACKING_FILE,
48711bd0e2d1SChunyan Liu             .type = QEMU_OPT_STRING,
487220d97356SBlue Swirl             .help = "File name of a base image"
487320d97356SBlue Swirl         },
487420d97356SBlue Swirl         {
487520d97356SBlue Swirl             .name = BLOCK_OPT_BACKING_FMT,
48761bd0e2d1SChunyan Liu             .type = QEMU_OPT_STRING,
487720d97356SBlue Swirl             .help = "Image format of the base image"
487820d97356SBlue Swirl         },
487920d97356SBlue Swirl         {
488020d97356SBlue Swirl             .name = BLOCK_OPT_ENCRYPT,
48811bd0e2d1SChunyan Liu             .type = QEMU_OPT_BOOL,
48820cb8d47bSDaniel P. Berrange             .help = "Encrypt the image with format 'aes'. (Deprecated "
48830cb8d47bSDaniel P. Berrange                     "in favor of " BLOCK_OPT_ENCRYPT_FORMAT "=aes)",
48840cb8d47bSDaniel P. Berrange         },
48850cb8d47bSDaniel P. Berrange         {
48860cb8d47bSDaniel P. Berrange             .name = BLOCK_OPT_ENCRYPT_FORMAT,
48870cb8d47bSDaniel P. Berrange             .type = QEMU_OPT_STRING,
48884652b8f3SDaniel P. Berrange             .help = "Encrypt the image, format choices: 'aes', 'luks'",
488920d97356SBlue Swirl         },
48904652b8f3SDaniel P. Berrange         BLOCK_CRYPTO_OPT_DEF_KEY_SECRET("encrypt.",
48914652b8f3SDaniel P. Berrange             "ID of secret providing qcow AES key or LUKS passphrase"),
48924652b8f3SDaniel P. Berrange         BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_ALG("encrypt."),
48934652b8f3SDaniel P. Berrange         BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_MODE("encrypt."),
48944652b8f3SDaniel P. Berrange         BLOCK_CRYPTO_OPT_DEF_LUKS_IVGEN_ALG("encrypt."),
48954652b8f3SDaniel P. Berrange         BLOCK_CRYPTO_OPT_DEF_LUKS_IVGEN_HASH_ALG("encrypt."),
48964652b8f3SDaniel P. Berrange         BLOCK_CRYPTO_OPT_DEF_LUKS_HASH_ALG("encrypt."),
48974652b8f3SDaniel P. Berrange         BLOCK_CRYPTO_OPT_DEF_LUKS_ITER_TIME("encrypt."),
489820d97356SBlue Swirl         {
489920d97356SBlue Swirl             .name = BLOCK_OPT_CLUSTER_SIZE,
49001bd0e2d1SChunyan Liu             .type = QEMU_OPT_SIZE,
490199cce9faSKevin Wolf             .help = "qcow2 cluster size",
49021bd0e2d1SChunyan Liu             .def_value_str = stringify(DEFAULT_CLUSTER_SIZE)
490320d97356SBlue Swirl         },
490420d97356SBlue Swirl         {
490520d97356SBlue Swirl             .name = BLOCK_OPT_PREALLOC,
49061bd0e2d1SChunyan Liu             .type = QEMU_OPT_STRING,
49070e4271b7SHu Tao             .help = "Preallocation mode (allowed values: off, metadata, "
49080e4271b7SHu Tao                     "falloc, full)"
490920d97356SBlue Swirl         },
4910bfe8043eSStefan Hajnoczi         {
4911bfe8043eSStefan Hajnoczi             .name = BLOCK_OPT_LAZY_REFCOUNTS,
49121bd0e2d1SChunyan Liu             .type = QEMU_OPT_BOOL,
4913bfe8043eSStefan Hajnoczi             .help = "Postpone refcount updates",
49141bd0e2d1SChunyan Liu             .def_value_str = "off"
4915bfe8043eSStefan Hajnoczi         },
491606d05fa7SMax Reitz         {
491706d05fa7SMax Reitz             .name = BLOCK_OPT_REFCOUNT_BITS,
491806d05fa7SMax Reitz             .type = QEMU_OPT_NUMBER,
491906d05fa7SMax Reitz             .help = "Width of a reference count entry in bits",
492006d05fa7SMax Reitz             .def_value_str = "16"
492106d05fa7SMax Reitz         },
49221bd0e2d1SChunyan Liu         { /* end of list */ }
49231bd0e2d1SChunyan Liu     }
492420d97356SBlue Swirl };
492520d97356SBlue Swirl 
49265f535a94SMax Reitz BlockDriver bdrv_qcow2 = {
492720d97356SBlue Swirl     .format_name        = "qcow2",
4928ff99129aSKevin Wolf     .instance_size      = sizeof(BDRVQcow2State),
49297c80ab3fSJes Sorensen     .bdrv_probe         = qcow2_probe,
49307c80ab3fSJes Sorensen     .bdrv_open          = qcow2_open,
49317c80ab3fSJes Sorensen     .bdrv_close         = qcow2_close,
493221d82ac9SJeff Cody     .bdrv_reopen_prepare  = qcow2_reopen_prepare,
49335b0959a7SKevin Wolf     .bdrv_reopen_commit   = qcow2_reopen_commit,
49345b0959a7SKevin Wolf     .bdrv_reopen_abort    = qcow2_reopen_abort,
49355365f44dSKevin Wolf     .bdrv_join_options    = qcow2_join_options,
4936862f215fSKevin Wolf     .bdrv_child_perm      = bdrv_format_default_perms,
4937efc75e2aSStefan Hajnoczi     .bdrv_co_create_opts  = qcow2_co_create_opts,
4938b0292b85SKevin Wolf     .bdrv_co_create       = qcow2_co_create,
49393ac21627SPeter Lieven     .bdrv_has_zero_init = bdrv_has_zero_init_1,
4940a320fb04SEric Blake     .bdrv_co_block_status = qcow2_co_block_status,
494120d97356SBlue Swirl 
4942ecfe1863SKevin Wolf     .bdrv_co_preadv         = qcow2_co_preadv,
4943d46a0bb2SKevin Wolf     .bdrv_co_pwritev        = qcow2_co_pwritev,
4944eb489bb1SKevin Wolf     .bdrv_co_flush_to_os    = qcow2_co_flush_to_os,
4945419b19d9SStefan Hajnoczi 
49465544b59fSEric Blake     .bdrv_co_pwrite_zeroes  = qcow2_co_pwrite_zeroes,
494782e8a788SEric Blake     .bdrv_co_pdiscard       = qcow2_co_pdiscard,
4948fd9fcd37SFam Zheng     .bdrv_co_copy_range_from = qcow2_co_copy_range_from,
4949fd9fcd37SFam Zheng     .bdrv_co_copy_range_to  = qcow2_co_copy_range_to,
4950061ca8a3SKevin Wolf     .bdrv_co_truncate       = qcow2_co_truncate,
4951fcccefc5SPavel Butsykin     .bdrv_co_pwritev_compressed = qcow2_co_pwritev_compressed,
4952491d27e2SMax Reitz     .bdrv_make_empty        = qcow2_make_empty,
495320d97356SBlue Swirl 
495420d97356SBlue Swirl     .bdrv_snapshot_create   = qcow2_snapshot_create,
495520d97356SBlue Swirl     .bdrv_snapshot_goto     = qcow2_snapshot_goto,
495620d97356SBlue Swirl     .bdrv_snapshot_delete   = qcow2_snapshot_delete,
495720d97356SBlue Swirl     .bdrv_snapshot_list     = qcow2_snapshot_list,
495851ef6727Sedison     .bdrv_snapshot_load_tmp = qcow2_snapshot_load_tmp,
4959c501c352SStefan Hajnoczi     .bdrv_measure           = qcow2_measure,
49607c80ab3fSJes Sorensen     .bdrv_get_info          = qcow2_get_info,
496137764dfbSMax Reitz     .bdrv_get_specific_info = qcow2_get_specific_info,
496220d97356SBlue Swirl 
49637c80ab3fSJes Sorensen     .bdrv_save_vmstate    = qcow2_save_vmstate,
49647c80ab3fSJes Sorensen     .bdrv_load_vmstate    = qcow2_load_vmstate,
496520d97356SBlue Swirl 
49668ee79e70SKevin Wolf     .supports_backing           = true,
496720d97356SBlue Swirl     .bdrv_change_backing_file   = qcow2_change_backing_file,
496820d97356SBlue Swirl 
4969d34682cdSKevin Wolf     .bdrv_refresh_limits        = qcow2_refresh_limits,
49702b148f39SPaolo Bonzini     .bdrv_co_invalidate_cache   = qcow2_co_invalidate_cache,
4971ec6d8912SKevin Wolf     .bdrv_inactivate            = qcow2_inactivate,
497206d9260fSAnthony Liguori 
49731bd0e2d1SChunyan Liu     .create_opts         = &qcow2_create_opts,
49742fd61638SPaolo Bonzini     .bdrv_co_check       = qcow2_co_check,
4975c282e1fdSChunyan Liu     .bdrv_amend_options  = qcow2_amend_options,
4976279621c0SAlberto Garcia 
4977279621c0SAlberto Garcia     .bdrv_detach_aio_context  = qcow2_detach_aio_context,
4978279621c0SAlberto Garcia     .bdrv_attach_aio_context  = qcow2_attach_aio_context,
49791b6b0562SVladimir Sementsov-Ogievskiy 
49801b6b0562SVladimir Sementsov-Ogievskiy     .bdrv_reopen_bitmaps_rw = qcow2_reopen_bitmaps_rw,
4981da0eb242SVladimir Sementsov-Ogievskiy     .bdrv_can_store_new_dirty_bitmap = qcow2_can_store_new_dirty_bitmap,
4982469c71edSVladimir Sementsov-Ogievskiy     .bdrv_remove_persistent_dirty_bitmap = qcow2_remove_persistent_dirty_bitmap,
498320d97356SBlue Swirl };
498420d97356SBlue Swirl 
49855efa9d5aSAnthony Liguori static void bdrv_qcow2_init(void)
49865efa9d5aSAnthony Liguori {
49875efa9d5aSAnthony Liguori     bdrv_register(&bdrv_qcow2);
49885efa9d5aSAnthony Liguori }
49895efa9d5aSAnthony Liguori 
49905efa9d5aSAnthony Liguori block_init(bdrv_qcow2_init);
4991