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" 26737e150eSPaolo Bonzini #include "block/block_int.h" 2723588797SKevin Wolf #include "sysemu/block-backend.h" 281de7afc9SPaolo Bonzini #include "qemu/module.h" 29585f8587Sbellard #include <zlib.h> 30f7d0fe02SKevin Wolf #include "block/qcow2.h" 311de7afc9SPaolo Bonzini #include "qemu/error-report.h" 32e688df6bSMarkus Armbruster #include "qapi/error.h" 337b1b5d19SPaolo Bonzini #include "qapi/qmp/qerror.h" 346b673957SMarkus Armbruster #include "qapi/qmp/qdict.h" 356b673957SMarkus Armbruster #include "qapi/qmp/qstring.h" 3685186ebdSMax Reitz #include "qapi-event.h" 373cce16f4SKevin Wolf #include "trace.h" 381bd0e2d1SChunyan Liu #include "qemu/option_int.h" 39f348b6d1SVeronia Bahaa #include "qemu/cutils.h" 4058369e22SPaolo Bonzini #include "qemu/bswap.h" 41b25b387fSDaniel P. Berrange #include "qapi/opts-visitor.h" 42b25b387fSDaniel P. Berrange #include "qapi-visit.h" 43b25b387fSDaniel P. Berrange #include "block/crypto.h" 44585f8587Sbellard 45585f8587Sbellard /* 46585f8587Sbellard Differences with QCOW: 47585f8587Sbellard 48585f8587Sbellard - Support for multiple incremental snapshots. 49585f8587Sbellard - Memory management by reference counts. 50585f8587Sbellard - Clusters which have a reference count of one have the bit 51585f8587Sbellard QCOW_OFLAG_COPIED to optimize write performance. 52585f8587Sbellard - Size of compressed clusters is stored in sectors to reduce bit usage 53585f8587Sbellard in the cluster offsets. 54585f8587Sbellard - Support for storing additional data (such as the VM state) in the 55585f8587Sbellard snapshots. 56585f8587Sbellard - If a backing store is used, the cluster size is not constrained 57585f8587Sbellard (could be backported to QCOW). 58585f8587Sbellard - L2 tables have always a size of one cluster. 59585f8587Sbellard */ 60585f8587Sbellard 619b80ddf3Saliguori 629b80ddf3Saliguori typedef struct { 639b80ddf3Saliguori uint32_t magic; 649b80ddf3Saliguori uint32_t len; 65c4217f64SJeff Cody } QEMU_PACKED QCowExtension; 6621d82ac9SJeff Cody 677c80ab3fSJes Sorensen #define QCOW2_EXT_MAGIC_END 0 687c80ab3fSJes Sorensen #define QCOW2_EXT_MAGIC_BACKING_FORMAT 0xE2792ACA 69cfcc4c62SKevin Wolf #define QCOW2_EXT_MAGIC_FEATURE_TABLE 0x6803f857 704652b8f3SDaniel P. Berrange #define QCOW2_EXT_MAGIC_CRYPTO_HEADER 0x0537be77 7188ddffaeSVladimir Sementsov-Ogievskiy #define QCOW2_EXT_MAGIC_BITMAPS 0x23852875 729b80ddf3Saliguori 737c80ab3fSJes Sorensen static int qcow2_probe(const uint8_t *buf, int buf_size, const char *filename) 74585f8587Sbellard { 75585f8587Sbellard const QCowHeader *cow_header = (const void *)buf; 76585f8587Sbellard 77585f8587Sbellard if (buf_size >= sizeof(QCowHeader) && 78585f8587Sbellard be32_to_cpu(cow_header->magic) == QCOW_MAGIC && 796744cbabSKevin Wolf be32_to_cpu(cow_header->version) >= 2) 80585f8587Sbellard return 100; 81585f8587Sbellard else 82585f8587Sbellard return 0; 83585f8587Sbellard } 84585f8587Sbellard 859b80ddf3Saliguori 864652b8f3SDaniel P. Berrange static ssize_t qcow2_crypto_hdr_read_func(QCryptoBlock *block, size_t offset, 874652b8f3SDaniel P. Berrange uint8_t *buf, size_t buflen, 884652b8f3SDaniel P. Berrange void *opaque, Error **errp) 894652b8f3SDaniel P. Berrange { 904652b8f3SDaniel P. Berrange BlockDriverState *bs = opaque; 914652b8f3SDaniel P. Berrange BDRVQcow2State *s = bs->opaque; 924652b8f3SDaniel P. Berrange ssize_t ret; 934652b8f3SDaniel P. Berrange 944652b8f3SDaniel P. Berrange if ((offset + buflen) > s->crypto_header.length) { 954652b8f3SDaniel P. Berrange error_setg(errp, "Request for data outside of extension header"); 964652b8f3SDaniel P. Berrange return -1; 974652b8f3SDaniel P. Berrange } 984652b8f3SDaniel P. Berrange 994652b8f3SDaniel P. Berrange ret = bdrv_pread(bs->file, 1004652b8f3SDaniel P. Berrange s->crypto_header.offset + offset, buf, buflen); 1014652b8f3SDaniel P. Berrange if (ret < 0) { 1024652b8f3SDaniel P. Berrange error_setg_errno(errp, -ret, "Could not read encryption header"); 1034652b8f3SDaniel P. Berrange return -1; 1044652b8f3SDaniel P. Berrange } 1054652b8f3SDaniel P. Berrange return ret; 1064652b8f3SDaniel P. Berrange } 1074652b8f3SDaniel P. Berrange 1084652b8f3SDaniel P. Berrange 1094652b8f3SDaniel P. Berrange static ssize_t qcow2_crypto_hdr_init_func(QCryptoBlock *block, size_t headerlen, 1104652b8f3SDaniel P. Berrange void *opaque, Error **errp) 1114652b8f3SDaniel P. Berrange { 1124652b8f3SDaniel P. Berrange BlockDriverState *bs = opaque; 1134652b8f3SDaniel P. Berrange BDRVQcow2State *s = bs->opaque; 1144652b8f3SDaniel P. Berrange int64_t ret; 1154652b8f3SDaniel P. Berrange int64_t clusterlen; 1164652b8f3SDaniel P. Berrange 1174652b8f3SDaniel P. Berrange ret = qcow2_alloc_clusters(bs, headerlen); 1184652b8f3SDaniel P. Berrange if (ret < 0) { 1194652b8f3SDaniel P. Berrange error_setg_errno(errp, -ret, 1204652b8f3SDaniel P. Berrange "Cannot allocate cluster for LUKS header size %zu", 1214652b8f3SDaniel P. Berrange headerlen); 1224652b8f3SDaniel P. Berrange return -1; 1234652b8f3SDaniel P. Berrange } 1244652b8f3SDaniel P. Berrange 1254652b8f3SDaniel P. Berrange s->crypto_header.length = headerlen; 1264652b8f3SDaniel P. Berrange s->crypto_header.offset = ret; 1274652b8f3SDaniel P. Berrange 1284652b8f3SDaniel P. Berrange /* Zero fill remaining space in cluster so it has predictable 1294652b8f3SDaniel P. Berrange * content in case of future spec changes */ 1304652b8f3SDaniel P. Berrange clusterlen = size_to_clusters(s, headerlen) * s->cluster_size; 131c9b83e9cSAlberto Garcia assert(qcow2_pre_write_overlap_check(bs, 0, ret, clusterlen) == 0); 1324652b8f3SDaniel P. Berrange ret = bdrv_pwrite_zeroes(bs->file, 1334652b8f3SDaniel P. Berrange ret + headerlen, 1344652b8f3SDaniel P. Berrange clusterlen - headerlen, 0); 1354652b8f3SDaniel P. Berrange if (ret < 0) { 1364652b8f3SDaniel P. Berrange error_setg_errno(errp, -ret, "Could not zero fill encryption header"); 1374652b8f3SDaniel P. Berrange return -1; 1384652b8f3SDaniel P. Berrange } 1394652b8f3SDaniel P. Berrange 1404652b8f3SDaniel P. Berrange return ret; 1414652b8f3SDaniel P. Berrange } 1424652b8f3SDaniel P. Berrange 1434652b8f3SDaniel P. Berrange 1444652b8f3SDaniel P. Berrange static ssize_t qcow2_crypto_hdr_write_func(QCryptoBlock *block, size_t offset, 1454652b8f3SDaniel P. Berrange const uint8_t *buf, size_t buflen, 1464652b8f3SDaniel P. Berrange void *opaque, Error **errp) 1474652b8f3SDaniel P. Berrange { 1484652b8f3SDaniel P. Berrange BlockDriverState *bs = opaque; 1494652b8f3SDaniel P. Berrange BDRVQcow2State *s = bs->opaque; 1504652b8f3SDaniel P. Berrange ssize_t ret; 1514652b8f3SDaniel P. Berrange 1524652b8f3SDaniel P. Berrange if ((offset + buflen) > s->crypto_header.length) { 1534652b8f3SDaniel P. Berrange error_setg(errp, "Request for data outside of extension header"); 1544652b8f3SDaniel P. Berrange return -1; 1554652b8f3SDaniel P. Berrange } 1564652b8f3SDaniel P. Berrange 1574652b8f3SDaniel P. Berrange ret = bdrv_pwrite(bs->file, 1584652b8f3SDaniel P. Berrange s->crypto_header.offset + offset, buf, buflen); 1594652b8f3SDaniel P. Berrange if (ret < 0) { 1604652b8f3SDaniel P. Berrange error_setg_errno(errp, -ret, "Could not read encryption header"); 1614652b8f3SDaniel P. Berrange return -1; 1624652b8f3SDaniel P. Berrange } 1634652b8f3SDaniel P. Berrange return ret; 1644652b8f3SDaniel P. Berrange } 1654652b8f3SDaniel P. Berrange 1664652b8f3SDaniel P. Berrange 1679b80ddf3Saliguori /* 1689b80ddf3Saliguori * read qcow2 extension and fill bs 1699b80ddf3Saliguori * start reading from start_offset 1709b80ddf3Saliguori * finish reading upon magic of value 0 or when end_offset reached 1719b80ddf3Saliguori * unknown magic is skipped (future extension this version knows nothing about) 1729b80ddf3Saliguori * return 0 upon success, non-0 otherwise 1739b80ddf3Saliguori */ 1747c80ab3fSJes Sorensen static int qcow2_read_extensions(BlockDriverState *bs, uint64_t start_offset, 1753ef6c40aSMax Reitz uint64_t end_offset, void **p_feature_table, 17688ddffaeSVladimir Sementsov-Ogievskiy int flags, bool *need_update_header, 17788ddffaeSVladimir Sementsov-Ogievskiy Error **errp) 1789b80ddf3Saliguori { 179ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque; 1809b80ddf3Saliguori QCowExtension ext; 1819b80ddf3Saliguori uint64_t offset; 18275bab85cSKevin Wolf int ret; 18388ddffaeSVladimir Sementsov-Ogievskiy Qcow2BitmapHeaderExt bitmaps_ext; 18488ddffaeSVladimir Sementsov-Ogievskiy 18588ddffaeSVladimir Sementsov-Ogievskiy if (need_update_header != NULL) { 18688ddffaeSVladimir Sementsov-Ogievskiy *need_update_header = false; 18788ddffaeSVladimir Sementsov-Ogievskiy } 1889b80ddf3Saliguori 1899b80ddf3Saliguori #ifdef DEBUG_EXT 1907c80ab3fSJes Sorensen printf("qcow2_read_extensions: start=%ld end=%ld\n", start_offset, end_offset); 1919b80ddf3Saliguori #endif 1929b80ddf3Saliguori offset = start_offset; 1939b80ddf3Saliguori while (offset < end_offset) { 1949b80ddf3Saliguori 1959b80ddf3Saliguori #ifdef DEBUG_EXT 1969b80ddf3Saliguori /* Sanity check */ 1979b80ddf3Saliguori if (offset > s->cluster_size) 1987c80ab3fSJes Sorensen printf("qcow2_read_extension: suspicious offset %lu\n", offset); 1999b80ddf3Saliguori 2009b2260cbSDong Xu Wang printf("attempting to read extended header in offset %lu\n", offset); 2019b80ddf3Saliguori #endif 2029b80ddf3Saliguori 203cf2ab8fcSKevin Wolf ret = bdrv_pread(bs->file, offset, &ext, sizeof(ext)); 2043ef6c40aSMax Reitz if (ret < 0) { 2053ef6c40aSMax Reitz error_setg_errno(errp, -ret, "qcow2_read_extension: ERROR: " 2063ef6c40aSMax Reitz "pread fail from offset %" PRIu64, offset); 2079b80ddf3Saliguori return 1; 2089b80ddf3Saliguori } 2099b80ddf3Saliguori be32_to_cpus(&ext.magic); 2109b80ddf3Saliguori be32_to_cpus(&ext.len); 2119b80ddf3Saliguori offset += sizeof(ext); 2129b80ddf3Saliguori #ifdef DEBUG_EXT 2139b80ddf3Saliguori printf("ext.magic = 0x%x\n", ext.magic); 2149b80ddf3Saliguori #endif 2152ebafc85SKevin Wolf if (offset > end_offset || ext.len > end_offset - offset) { 2163ef6c40aSMax Reitz error_setg(errp, "Header extension too large"); 21764ca6aeeSKevin Wolf return -EINVAL; 21864ca6aeeSKevin Wolf } 21964ca6aeeSKevin Wolf 2209b80ddf3Saliguori switch (ext.magic) { 2217c80ab3fSJes Sorensen case QCOW2_EXT_MAGIC_END: 2229b80ddf3Saliguori return 0; 223f965509cSaliguori 2247c80ab3fSJes Sorensen case QCOW2_EXT_MAGIC_BACKING_FORMAT: 225f965509cSaliguori if (ext.len >= sizeof(bs->backing_format)) { 226521b2b5dSMax Reitz error_setg(errp, "ERROR: ext_backing_format: len=%" PRIu32 227521b2b5dSMax Reitz " too large (>=%zu)", ext.len, 228521b2b5dSMax Reitz sizeof(bs->backing_format)); 229f965509cSaliguori return 2; 230f965509cSaliguori } 231cf2ab8fcSKevin Wolf ret = bdrv_pread(bs->file, offset, bs->backing_format, ext.len); 2323ef6c40aSMax Reitz if (ret < 0) { 2333ef6c40aSMax Reitz error_setg_errno(errp, -ret, "ERROR: ext_backing_format: " 2343ef6c40aSMax Reitz "Could not read format name"); 235f965509cSaliguori return 3; 2363ef6c40aSMax Reitz } 237f965509cSaliguori bs->backing_format[ext.len] = '\0'; 238e4603fe1SKevin Wolf s->image_backing_format = g_strdup(bs->backing_format); 239f965509cSaliguori #ifdef DEBUG_EXT 240f965509cSaliguori printf("Qcow2: Got format extension %s\n", bs->backing_format); 241f965509cSaliguori #endif 242f965509cSaliguori break; 243f965509cSaliguori 244cfcc4c62SKevin Wolf case QCOW2_EXT_MAGIC_FEATURE_TABLE: 245cfcc4c62SKevin Wolf if (p_feature_table != NULL) { 246cfcc4c62SKevin Wolf void* feature_table = g_malloc0(ext.len + 2 * sizeof(Qcow2Feature)); 247cf2ab8fcSKevin Wolf ret = bdrv_pread(bs->file, offset , feature_table, ext.len); 248cfcc4c62SKevin Wolf if (ret < 0) { 2493ef6c40aSMax Reitz error_setg_errno(errp, -ret, "ERROR: ext_feature_table: " 2503ef6c40aSMax Reitz "Could not read table"); 251cfcc4c62SKevin Wolf return ret; 252cfcc4c62SKevin Wolf } 253cfcc4c62SKevin Wolf 254cfcc4c62SKevin Wolf *p_feature_table = feature_table; 255cfcc4c62SKevin Wolf } 256cfcc4c62SKevin Wolf break; 257cfcc4c62SKevin Wolf 2584652b8f3SDaniel P. Berrange case QCOW2_EXT_MAGIC_CRYPTO_HEADER: { 2594652b8f3SDaniel P. Berrange unsigned int cflags = 0; 2604652b8f3SDaniel P. Berrange if (s->crypt_method_header != QCOW_CRYPT_LUKS) { 2614652b8f3SDaniel P. Berrange error_setg(errp, "CRYPTO header extension only " 2624652b8f3SDaniel P. Berrange "expected with LUKS encryption method"); 2634652b8f3SDaniel P. Berrange return -EINVAL; 2644652b8f3SDaniel P. Berrange } 2654652b8f3SDaniel P. Berrange if (ext.len != sizeof(Qcow2CryptoHeaderExtension)) { 2664652b8f3SDaniel P. Berrange error_setg(errp, "CRYPTO header extension size %u, " 2674652b8f3SDaniel P. Berrange "but expected size %zu", ext.len, 2684652b8f3SDaniel P. Berrange sizeof(Qcow2CryptoHeaderExtension)); 2694652b8f3SDaniel P. Berrange return -EINVAL; 2704652b8f3SDaniel P. Berrange } 2714652b8f3SDaniel P. Berrange 2724652b8f3SDaniel P. Berrange ret = bdrv_pread(bs->file, offset, &s->crypto_header, ext.len); 2734652b8f3SDaniel P. Berrange if (ret < 0) { 2744652b8f3SDaniel P. Berrange error_setg_errno(errp, -ret, 2754652b8f3SDaniel P. Berrange "Unable to read CRYPTO header extension"); 2764652b8f3SDaniel P. Berrange return ret; 2774652b8f3SDaniel P. Berrange } 2784652b8f3SDaniel P. Berrange be64_to_cpus(&s->crypto_header.offset); 2794652b8f3SDaniel P. Berrange be64_to_cpus(&s->crypto_header.length); 2804652b8f3SDaniel P. Berrange 2814652b8f3SDaniel P. Berrange if ((s->crypto_header.offset % s->cluster_size) != 0) { 2824652b8f3SDaniel P. Berrange error_setg(errp, "Encryption header offset '%" PRIu64 "' is " 2834652b8f3SDaniel P. Berrange "not a multiple of cluster size '%u'", 2844652b8f3SDaniel P. Berrange s->crypto_header.offset, s->cluster_size); 2854652b8f3SDaniel P. Berrange return -EINVAL; 2864652b8f3SDaniel P. Berrange } 2874652b8f3SDaniel P. Berrange 2884652b8f3SDaniel P. Berrange if (flags & BDRV_O_NO_IO) { 2894652b8f3SDaniel P. Berrange cflags |= QCRYPTO_BLOCK_OPEN_NO_IO; 2904652b8f3SDaniel P. Berrange } 2911cd9a787SDaniel P. Berrange s->crypto = qcrypto_block_open(s->crypto_opts, "encrypt.", 2924652b8f3SDaniel P. Berrange qcow2_crypto_hdr_read_func, 2934652b8f3SDaniel P. Berrange bs, cflags, errp); 2944652b8f3SDaniel P. Berrange if (!s->crypto) { 2954652b8f3SDaniel P. Berrange return -EINVAL; 2964652b8f3SDaniel P. Berrange } 2974652b8f3SDaniel P. Berrange } break; 2984652b8f3SDaniel P. Berrange 29988ddffaeSVladimir Sementsov-Ogievskiy case QCOW2_EXT_MAGIC_BITMAPS: 30088ddffaeSVladimir Sementsov-Ogievskiy if (ext.len != sizeof(bitmaps_ext)) { 30188ddffaeSVladimir Sementsov-Ogievskiy error_setg_errno(errp, -ret, "bitmaps_ext: " 30288ddffaeSVladimir Sementsov-Ogievskiy "Invalid extension length"); 30388ddffaeSVladimir Sementsov-Ogievskiy return -EINVAL; 30488ddffaeSVladimir Sementsov-Ogievskiy } 30588ddffaeSVladimir Sementsov-Ogievskiy 30688ddffaeSVladimir Sementsov-Ogievskiy if (!(s->autoclear_features & QCOW2_AUTOCLEAR_BITMAPS)) { 307c9ceb3ecSMax Reitz if (s->qcow_version < 3) { 308c9ceb3ecSMax Reitz /* Let's be a bit more specific */ 309c9ceb3ecSMax Reitz warn_report("This qcow2 v2 image contains bitmaps, but " 310c9ceb3ecSMax Reitz "they may have been modified by a program " 311c9ceb3ecSMax Reitz "without persistent bitmap support; so now " 312c9ceb3ecSMax Reitz "they must all be considered inconsistent"); 313c9ceb3ecSMax Reitz } else { 31455d527a9SAlistair Francis warn_report("a program lacking bitmap support " 31588ddffaeSVladimir Sementsov-Ogievskiy "modified this file, so all bitmaps are now " 31655d527a9SAlistair Francis "considered inconsistent"); 317c9ceb3ecSMax Reitz } 31855d527a9SAlistair Francis error_printf("Some clusters may be leaked, " 31955d527a9SAlistair Francis "run 'qemu-img check -r' on the image " 32088ddffaeSVladimir Sementsov-Ogievskiy "file to fix."); 32188ddffaeSVladimir Sementsov-Ogievskiy if (need_update_header != NULL) { 32288ddffaeSVladimir Sementsov-Ogievskiy /* Updating is needed to drop invalid bitmap extension. */ 32388ddffaeSVladimir Sementsov-Ogievskiy *need_update_header = true; 32488ddffaeSVladimir Sementsov-Ogievskiy } 32588ddffaeSVladimir Sementsov-Ogievskiy break; 32688ddffaeSVladimir Sementsov-Ogievskiy } 32788ddffaeSVladimir Sementsov-Ogievskiy 32888ddffaeSVladimir Sementsov-Ogievskiy ret = bdrv_pread(bs->file, offset, &bitmaps_ext, ext.len); 32988ddffaeSVladimir Sementsov-Ogievskiy if (ret < 0) { 33088ddffaeSVladimir Sementsov-Ogievskiy error_setg_errno(errp, -ret, "bitmaps_ext: " 33188ddffaeSVladimir Sementsov-Ogievskiy "Could not read ext header"); 33288ddffaeSVladimir Sementsov-Ogievskiy return ret; 33388ddffaeSVladimir Sementsov-Ogievskiy } 33488ddffaeSVladimir Sementsov-Ogievskiy 33588ddffaeSVladimir Sementsov-Ogievskiy if (bitmaps_ext.reserved32 != 0) { 33688ddffaeSVladimir Sementsov-Ogievskiy error_setg_errno(errp, -ret, "bitmaps_ext: " 33788ddffaeSVladimir Sementsov-Ogievskiy "Reserved field is not zero"); 33888ddffaeSVladimir Sementsov-Ogievskiy return -EINVAL; 33988ddffaeSVladimir Sementsov-Ogievskiy } 34088ddffaeSVladimir Sementsov-Ogievskiy 34188ddffaeSVladimir Sementsov-Ogievskiy be32_to_cpus(&bitmaps_ext.nb_bitmaps); 34288ddffaeSVladimir Sementsov-Ogievskiy be64_to_cpus(&bitmaps_ext.bitmap_directory_size); 34388ddffaeSVladimir Sementsov-Ogievskiy be64_to_cpus(&bitmaps_ext.bitmap_directory_offset); 34488ddffaeSVladimir Sementsov-Ogievskiy 34588ddffaeSVladimir Sementsov-Ogievskiy if (bitmaps_ext.nb_bitmaps > QCOW2_MAX_BITMAPS) { 34688ddffaeSVladimir Sementsov-Ogievskiy error_setg(errp, 34788ddffaeSVladimir Sementsov-Ogievskiy "bitmaps_ext: Image has %" PRIu32 " bitmaps, " 34888ddffaeSVladimir Sementsov-Ogievskiy "exceeding the QEMU supported maximum of %d", 34988ddffaeSVladimir Sementsov-Ogievskiy bitmaps_ext.nb_bitmaps, QCOW2_MAX_BITMAPS); 35088ddffaeSVladimir Sementsov-Ogievskiy return -EINVAL; 35188ddffaeSVladimir Sementsov-Ogievskiy } 35288ddffaeSVladimir Sementsov-Ogievskiy 35388ddffaeSVladimir Sementsov-Ogievskiy if (bitmaps_ext.nb_bitmaps == 0) { 35488ddffaeSVladimir Sementsov-Ogievskiy error_setg(errp, "found bitmaps extension with zero bitmaps"); 35588ddffaeSVladimir Sementsov-Ogievskiy return -EINVAL; 35688ddffaeSVladimir Sementsov-Ogievskiy } 35788ddffaeSVladimir Sementsov-Ogievskiy 35888ddffaeSVladimir Sementsov-Ogievskiy if (bitmaps_ext.bitmap_directory_offset & (s->cluster_size - 1)) { 35988ddffaeSVladimir Sementsov-Ogievskiy error_setg(errp, "bitmaps_ext: " 36088ddffaeSVladimir Sementsov-Ogievskiy "invalid bitmap directory offset"); 36188ddffaeSVladimir Sementsov-Ogievskiy return -EINVAL; 36288ddffaeSVladimir Sementsov-Ogievskiy } 36388ddffaeSVladimir Sementsov-Ogievskiy 36488ddffaeSVladimir Sementsov-Ogievskiy if (bitmaps_ext.bitmap_directory_size > 36588ddffaeSVladimir Sementsov-Ogievskiy QCOW2_MAX_BITMAP_DIRECTORY_SIZE) { 36688ddffaeSVladimir Sementsov-Ogievskiy error_setg(errp, "bitmaps_ext: " 36788ddffaeSVladimir Sementsov-Ogievskiy "bitmap directory size (%" PRIu64 ") exceeds " 36888ddffaeSVladimir Sementsov-Ogievskiy "the maximum supported size (%d)", 36988ddffaeSVladimir Sementsov-Ogievskiy bitmaps_ext.bitmap_directory_size, 37088ddffaeSVladimir Sementsov-Ogievskiy QCOW2_MAX_BITMAP_DIRECTORY_SIZE); 37188ddffaeSVladimir Sementsov-Ogievskiy return -EINVAL; 37288ddffaeSVladimir Sementsov-Ogievskiy } 37388ddffaeSVladimir Sementsov-Ogievskiy 37488ddffaeSVladimir Sementsov-Ogievskiy s->nb_bitmaps = bitmaps_ext.nb_bitmaps; 37588ddffaeSVladimir Sementsov-Ogievskiy s->bitmap_directory_offset = 37688ddffaeSVladimir Sementsov-Ogievskiy bitmaps_ext.bitmap_directory_offset; 37788ddffaeSVladimir Sementsov-Ogievskiy s->bitmap_directory_size = 37888ddffaeSVladimir Sementsov-Ogievskiy bitmaps_ext.bitmap_directory_size; 37988ddffaeSVladimir Sementsov-Ogievskiy 38088ddffaeSVladimir Sementsov-Ogievskiy #ifdef DEBUG_EXT 38188ddffaeSVladimir Sementsov-Ogievskiy printf("Qcow2: Got bitmaps extension: " 38288ddffaeSVladimir Sementsov-Ogievskiy "offset=%" PRIu64 " nb_bitmaps=%" PRIu32 "\n", 38388ddffaeSVladimir Sementsov-Ogievskiy s->bitmap_directory_offset, s->nb_bitmaps); 38488ddffaeSVladimir Sementsov-Ogievskiy #endif 38588ddffaeSVladimir Sementsov-Ogievskiy break; 38688ddffaeSVladimir Sementsov-Ogievskiy 3879b80ddf3Saliguori default: 38875bab85cSKevin Wolf /* unknown magic - save it in case we need to rewrite the header */ 3894096974eSEric Blake /* If you add a new feature, make sure to also update the fast 3904096974eSEric Blake * path of qcow2_make_empty() to deal with it. */ 39175bab85cSKevin Wolf { 39275bab85cSKevin Wolf Qcow2UnknownHeaderExtension *uext; 39375bab85cSKevin Wolf 39475bab85cSKevin Wolf uext = g_malloc0(sizeof(*uext) + ext.len); 39575bab85cSKevin Wolf uext->magic = ext.magic; 39675bab85cSKevin Wolf uext->len = ext.len; 39775bab85cSKevin Wolf QLIST_INSERT_HEAD(&s->unknown_header_ext, uext, next); 39875bab85cSKevin Wolf 399cf2ab8fcSKevin Wolf ret = bdrv_pread(bs->file, offset , uext->data, uext->len); 40075bab85cSKevin Wolf if (ret < 0) { 4013ef6c40aSMax Reitz error_setg_errno(errp, -ret, "ERROR: unknown extension: " 4023ef6c40aSMax Reitz "Could not read data"); 40375bab85cSKevin Wolf return ret; 40475bab85cSKevin Wolf } 40575bab85cSKevin Wolf } 4069b80ddf3Saliguori break; 4079b80ddf3Saliguori } 408fd29b4bbSKevin Wolf 409fd29b4bbSKevin Wolf offset += ((ext.len + 7) & ~7); 4109b80ddf3Saliguori } 4119b80ddf3Saliguori 4129b80ddf3Saliguori return 0; 4139b80ddf3Saliguori } 4149b80ddf3Saliguori 41575bab85cSKevin Wolf static void cleanup_unknown_header_ext(BlockDriverState *bs) 41675bab85cSKevin Wolf { 417ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque; 41875bab85cSKevin Wolf Qcow2UnknownHeaderExtension *uext, *next; 41975bab85cSKevin Wolf 42075bab85cSKevin Wolf QLIST_FOREACH_SAFE(uext, &s->unknown_header_ext, next, next) { 42175bab85cSKevin Wolf QLIST_REMOVE(uext, next); 42275bab85cSKevin Wolf g_free(uext); 42375bab85cSKevin Wolf } 42475bab85cSKevin Wolf } 4259b80ddf3Saliguori 426a55448b3SMax Reitz static void report_unsupported_feature(Error **errp, Qcow2Feature *table, 427a55448b3SMax Reitz uint64_t mask) 428cfcc4c62SKevin Wolf { 42912ac6d3dSKevin Wolf char *features = g_strdup(""); 43012ac6d3dSKevin Wolf char *old; 43112ac6d3dSKevin Wolf 432cfcc4c62SKevin Wolf while (table && table->name[0] != '\0') { 433cfcc4c62SKevin Wolf if (table->type == QCOW2_FEAT_TYPE_INCOMPATIBLE) { 43412ac6d3dSKevin Wolf if (mask & (1ULL << table->bit)) { 43512ac6d3dSKevin Wolf old = features; 43612ac6d3dSKevin Wolf features = g_strdup_printf("%s%s%.46s", old, *old ? ", " : "", 43712ac6d3dSKevin Wolf table->name); 43812ac6d3dSKevin Wolf g_free(old); 43912ac6d3dSKevin Wolf mask &= ~(1ULL << table->bit); 440cfcc4c62SKevin Wolf } 441cfcc4c62SKevin Wolf } 442cfcc4c62SKevin Wolf table++; 443cfcc4c62SKevin Wolf } 444cfcc4c62SKevin Wolf 445cfcc4c62SKevin Wolf if (mask) { 44612ac6d3dSKevin Wolf old = features; 44712ac6d3dSKevin Wolf features = g_strdup_printf("%s%sUnknown incompatible feature: %" PRIx64, 44812ac6d3dSKevin Wolf old, *old ? ", " : "", mask); 44912ac6d3dSKevin Wolf g_free(old); 450cfcc4c62SKevin Wolf } 45112ac6d3dSKevin Wolf 452a55448b3SMax Reitz error_setg(errp, "Unsupported qcow2 feature(s): %s", features); 45312ac6d3dSKevin Wolf g_free(features); 454cfcc4c62SKevin Wolf } 455cfcc4c62SKevin Wolf 456c61d0004SStefan Hajnoczi /* 457bfe8043eSStefan Hajnoczi * Sets the dirty bit and flushes afterwards if necessary. 458bfe8043eSStefan Hajnoczi * 459bfe8043eSStefan Hajnoczi * The incompatible_features bit is only set if the image file header was 460bfe8043eSStefan Hajnoczi * updated successfully. Therefore it is not required to check the return 461bfe8043eSStefan Hajnoczi * value of this function. 462bfe8043eSStefan Hajnoczi */ 463280d3735SKevin Wolf int qcow2_mark_dirty(BlockDriverState *bs) 464bfe8043eSStefan Hajnoczi { 465ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque; 466bfe8043eSStefan Hajnoczi uint64_t val; 467bfe8043eSStefan Hajnoczi int ret; 468bfe8043eSStefan Hajnoczi 469bfe8043eSStefan Hajnoczi assert(s->qcow_version >= 3); 470bfe8043eSStefan Hajnoczi 471bfe8043eSStefan Hajnoczi if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) { 472bfe8043eSStefan Hajnoczi return 0; /* already dirty */ 473bfe8043eSStefan Hajnoczi } 474bfe8043eSStefan Hajnoczi 475bfe8043eSStefan Hajnoczi val = cpu_to_be64(s->incompatible_features | QCOW2_INCOMPAT_DIRTY); 476d9ca2ea2SKevin Wolf ret = bdrv_pwrite(bs->file, offsetof(QCowHeader, incompatible_features), 477bfe8043eSStefan Hajnoczi &val, sizeof(val)); 478bfe8043eSStefan Hajnoczi if (ret < 0) { 479bfe8043eSStefan Hajnoczi return ret; 480bfe8043eSStefan Hajnoczi } 4819a4f4c31SKevin Wolf ret = bdrv_flush(bs->file->bs); 482bfe8043eSStefan Hajnoczi if (ret < 0) { 483bfe8043eSStefan Hajnoczi return ret; 484bfe8043eSStefan Hajnoczi } 485bfe8043eSStefan Hajnoczi 486bfe8043eSStefan Hajnoczi /* Only treat image as dirty if the header was updated successfully */ 487bfe8043eSStefan Hajnoczi s->incompatible_features |= QCOW2_INCOMPAT_DIRTY; 488bfe8043eSStefan Hajnoczi return 0; 489bfe8043eSStefan Hajnoczi } 490bfe8043eSStefan Hajnoczi 491bfe8043eSStefan Hajnoczi /* 492c61d0004SStefan Hajnoczi * Clears the dirty bit and flushes before if necessary. Only call this 493c61d0004SStefan Hajnoczi * function when there are no pending requests, it does not guard against 494c61d0004SStefan Hajnoczi * concurrent requests dirtying the image. 495c61d0004SStefan Hajnoczi */ 496c61d0004SStefan Hajnoczi static int qcow2_mark_clean(BlockDriverState *bs) 497c61d0004SStefan Hajnoczi { 498ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque; 499c61d0004SStefan Hajnoczi 500c61d0004SStefan Hajnoczi if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) { 5014c2e5f8fSKevin Wolf int ret; 5024c2e5f8fSKevin Wolf 5034c2e5f8fSKevin Wolf s->incompatible_features &= ~QCOW2_INCOMPAT_DIRTY; 5044c2e5f8fSKevin Wolf 5054c2e5f8fSKevin Wolf ret = bdrv_flush(bs); 506c61d0004SStefan Hajnoczi if (ret < 0) { 507c61d0004SStefan Hajnoczi return ret; 508c61d0004SStefan Hajnoczi } 509c61d0004SStefan Hajnoczi 510c61d0004SStefan Hajnoczi return qcow2_update_header(bs); 511c61d0004SStefan Hajnoczi } 512c61d0004SStefan Hajnoczi return 0; 513c61d0004SStefan Hajnoczi } 514c61d0004SStefan Hajnoczi 51569c98726SMax Reitz /* 51669c98726SMax Reitz * Marks the image as corrupt. 51769c98726SMax Reitz */ 51869c98726SMax Reitz int qcow2_mark_corrupt(BlockDriverState *bs) 51969c98726SMax Reitz { 520ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque; 52169c98726SMax Reitz 52269c98726SMax Reitz s->incompatible_features |= QCOW2_INCOMPAT_CORRUPT; 52369c98726SMax Reitz return qcow2_update_header(bs); 52469c98726SMax Reitz } 52569c98726SMax Reitz 52669c98726SMax Reitz /* 52769c98726SMax Reitz * Marks the image as consistent, i.e., unsets the corrupt bit, and flushes 52869c98726SMax Reitz * before if necessary. 52969c98726SMax Reitz */ 53069c98726SMax Reitz int qcow2_mark_consistent(BlockDriverState *bs) 53169c98726SMax Reitz { 532ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque; 53369c98726SMax Reitz 53469c98726SMax Reitz if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) { 53569c98726SMax Reitz int ret = bdrv_flush(bs); 53669c98726SMax Reitz if (ret < 0) { 53769c98726SMax Reitz return ret; 53869c98726SMax Reitz } 53969c98726SMax Reitz 54069c98726SMax Reitz s->incompatible_features &= ~QCOW2_INCOMPAT_CORRUPT; 54169c98726SMax Reitz return qcow2_update_header(bs); 54269c98726SMax Reitz } 54369c98726SMax Reitz return 0; 54469c98726SMax Reitz } 54569c98726SMax Reitz 546acbe5982SStefan Hajnoczi static int qcow2_check(BlockDriverState *bs, BdrvCheckResult *result, 547acbe5982SStefan Hajnoczi BdrvCheckMode fix) 548acbe5982SStefan Hajnoczi { 549acbe5982SStefan Hajnoczi int ret = qcow2_check_refcounts(bs, result, fix); 550acbe5982SStefan Hajnoczi if (ret < 0) { 551acbe5982SStefan Hajnoczi return ret; 552acbe5982SStefan Hajnoczi } 553acbe5982SStefan Hajnoczi 554acbe5982SStefan Hajnoczi if (fix && result->check_errors == 0 && result->corruptions == 0) { 55524530f3eSMax Reitz ret = qcow2_mark_clean(bs); 55624530f3eSMax Reitz if (ret < 0) { 55724530f3eSMax Reitz return ret; 55824530f3eSMax Reitz } 55924530f3eSMax Reitz return qcow2_mark_consistent(bs); 560acbe5982SStefan Hajnoczi } 561acbe5982SStefan Hajnoczi return ret; 562acbe5982SStefan Hajnoczi } 563acbe5982SStefan Hajnoczi 5648c7de283SKevin Wolf static int validate_table_offset(BlockDriverState *bs, uint64_t offset, 5658c7de283SKevin Wolf uint64_t entries, size_t entry_len) 5668c7de283SKevin Wolf { 567ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque; 5688c7de283SKevin Wolf uint64_t size; 5698c7de283SKevin Wolf 5708c7de283SKevin Wolf /* Use signed INT64_MAX as the maximum even for uint64_t header fields, 5718c7de283SKevin Wolf * because values will be passed to qemu functions taking int64_t. */ 5728c7de283SKevin Wolf if (entries > INT64_MAX / entry_len) { 5738c7de283SKevin Wolf return -EINVAL; 5748c7de283SKevin Wolf } 5758c7de283SKevin Wolf 5768c7de283SKevin Wolf size = entries * entry_len; 5778c7de283SKevin Wolf 5788c7de283SKevin Wolf if (INT64_MAX - size < offset) { 5798c7de283SKevin Wolf return -EINVAL; 5808c7de283SKevin Wolf } 5818c7de283SKevin Wolf 5828c7de283SKevin Wolf /* Tables must be cluster aligned */ 58324990c5bSAlberto Garcia if (offset_into_cluster(s, offset) != 0) { 5848c7de283SKevin Wolf return -EINVAL; 5858c7de283SKevin Wolf } 5868c7de283SKevin Wolf 5878c7de283SKevin Wolf return 0; 5888c7de283SKevin Wolf } 5898c7de283SKevin Wolf 59074c4510aSKevin Wolf static QemuOptsList qcow2_runtime_opts = { 59174c4510aSKevin Wolf .name = "qcow2", 59274c4510aSKevin Wolf .head = QTAILQ_HEAD_INITIALIZER(qcow2_runtime_opts.head), 59374c4510aSKevin Wolf .desc = { 59474c4510aSKevin Wolf { 59564aa99d3SKevin Wolf .name = QCOW2_OPT_LAZY_REFCOUNTS, 59674c4510aSKevin Wolf .type = QEMU_OPT_BOOL, 59774c4510aSKevin Wolf .help = "Postpone refcount updates", 59874c4510aSKevin Wolf }, 59967af674eSKevin Wolf { 60067af674eSKevin Wolf .name = QCOW2_OPT_DISCARD_REQUEST, 60167af674eSKevin Wolf .type = QEMU_OPT_BOOL, 60267af674eSKevin Wolf .help = "Pass guest discard requests to the layer below", 60367af674eSKevin Wolf }, 60467af674eSKevin Wolf { 60567af674eSKevin Wolf .name = QCOW2_OPT_DISCARD_SNAPSHOT, 60667af674eSKevin Wolf .type = QEMU_OPT_BOOL, 60767af674eSKevin Wolf .help = "Generate discard requests when snapshot related space " 60867af674eSKevin Wolf "is freed", 60967af674eSKevin Wolf }, 61067af674eSKevin Wolf { 61167af674eSKevin Wolf .name = QCOW2_OPT_DISCARD_OTHER, 61267af674eSKevin Wolf .type = QEMU_OPT_BOOL, 61367af674eSKevin Wolf .help = "Generate discard requests when other clusters are freed", 61467af674eSKevin Wolf }, 61505de7e86SMax Reitz { 61605de7e86SMax Reitz .name = QCOW2_OPT_OVERLAP, 61705de7e86SMax Reitz .type = QEMU_OPT_STRING, 61805de7e86SMax Reitz .help = "Selects which overlap checks to perform from a range of " 61905de7e86SMax Reitz "templates (none, constant, cached, all)", 62005de7e86SMax Reitz }, 62105de7e86SMax Reitz { 622ee42b5ceSMax Reitz .name = QCOW2_OPT_OVERLAP_TEMPLATE, 623ee42b5ceSMax Reitz .type = QEMU_OPT_STRING, 624ee42b5ceSMax Reitz .help = "Selects which overlap checks to perform from a range of " 625ee42b5ceSMax Reitz "templates (none, constant, cached, all)", 626ee42b5ceSMax Reitz }, 627ee42b5ceSMax Reitz { 62805de7e86SMax Reitz .name = QCOW2_OPT_OVERLAP_MAIN_HEADER, 62905de7e86SMax Reitz .type = QEMU_OPT_BOOL, 63005de7e86SMax Reitz .help = "Check for unintended writes into the main qcow2 header", 63105de7e86SMax Reitz }, 63205de7e86SMax Reitz { 63305de7e86SMax Reitz .name = QCOW2_OPT_OVERLAP_ACTIVE_L1, 63405de7e86SMax Reitz .type = QEMU_OPT_BOOL, 63505de7e86SMax Reitz .help = "Check for unintended writes into the active L1 table", 63605de7e86SMax Reitz }, 63705de7e86SMax Reitz { 63805de7e86SMax Reitz .name = QCOW2_OPT_OVERLAP_ACTIVE_L2, 63905de7e86SMax Reitz .type = QEMU_OPT_BOOL, 64005de7e86SMax Reitz .help = "Check for unintended writes into an active L2 table", 64105de7e86SMax Reitz }, 64205de7e86SMax Reitz { 64305de7e86SMax Reitz .name = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE, 64405de7e86SMax Reitz .type = QEMU_OPT_BOOL, 64505de7e86SMax Reitz .help = "Check for unintended writes into the refcount table", 64605de7e86SMax Reitz }, 64705de7e86SMax Reitz { 64805de7e86SMax Reitz .name = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK, 64905de7e86SMax Reitz .type = QEMU_OPT_BOOL, 65005de7e86SMax Reitz .help = "Check for unintended writes into a refcount block", 65105de7e86SMax Reitz }, 65205de7e86SMax Reitz { 65305de7e86SMax Reitz .name = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE, 65405de7e86SMax Reitz .type = QEMU_OPT_BOOL, 65505de7e86SMax Reitz .help = "Check for unintended writes into the snapshot table", 65605de7e86SMax Reitz }, 65705de7e86SMax Reitz { 65805de7e86SMax Reitz .name = QCOW2_OPT_OVERLAP_INACTIVE_L1, 65905de7e86SMax Reitz .type = QEMU_OPT_BOOL, 66005de7e86SMax Reitz .help = "Check for unintended writes into an inactive L1 table", 66105de7e86SMax Reitz }, 66205de7e86SMax Reitz { 66305de7e86SMax Reitz .name = QCOW2_OPT_OVERLAP_INACTIVE_L2, 66405de7e86SMax Reitz .type = QEMU_OPT_BOOL, 66505de7e86SMax Reitz .help = "Check for unintended writes into an inactive L2 table", 66605de7e86SMax Reitz }, 6676c1c8d5dSMax Reitz { 6686c1c8d5dSMax Reitz .name = QCOW2_OPT_CACHE_SIZE, 6696c1c8d5dSMax Reitz .type = QEMU_OPT_SIZE, 6706c1c8d5dSMax Reitz .help = "Maximum combined metadata (L2 tables and refcount blocks) " 6716c1c8d5dSMax Reitz "cache size", 6726c1c8d5dSMax Reitz }, 6736c1c8d5dSMax Reitz { 6746c1c8d5dSMax Reitz .name = QCOW2_OPT_L2_CACHE_SIZE, 6756c1c8d5dSMax Reitz .type = QEMU_OPT_SIZE, 6766c1c8d5dSMax Reitz .help = "Maximum L2 table cache size", 6776c1c8d5dSMax Reitz }, 6786c1c8d5dSMax Reitz { 6791221fe6fSAlberto Garcia .name = QCOW2_OPT_L2_CACHE_ENTRY_SIZE, 6801221fe6fSAlberto Garcia .type = QEMU_OPT_SIZE, 6811221fe6fSAlberto Garcia .help = "Size of each entry in the L2 cache", 6821221fe6fSAlberto Garcia }, 6831221fe6fSAlberto Garcia { 6846c1c8d5dSMax Reitz .name = QCOW2_OPT_REFCOUNT_CACHE_SIZE, 6856c1c8d5dSMax Reitz .type = QEMU_OPT_SIZE, 6866c1c8d5dSMax Reitz .help = "Maximum refcount block cache size", 6876c1c8d5dSMax Reitz }, 688279621c0SAlberto Garcia { 689279621c0SAlberto Garcia .name = QCOW2_OPT_CACHE_CLEAN_INTERVAL, 690279621c0SAlberto Garcia .type = QEMU_OPT_NUMBER, 691279621c0SAlberto Garcia .help = "Clean unused cache entries after this time (in seconds)", 692279621c0SAlberto Garcia }, 6934652b8f3SDaniel P. Berrange BLOCK_CRYPTO_OPT_DEF_KEY_SECRET("encrypt.", 6944652b8f3SDaniel P. Berrange "ID of secret providing qcow2 AES key or LUKS passphrase"), 69574c4510aSKevin Wolf { /* end of list */ } 69674c4510aSKevin Wolf }, 69774c4510aSKevin Wolf }; 69874c4510aSKevin Wolf 6994092e99dSMax Reitz static const char *overlap_bool_option_names[QCOW2_OL_MAX_BITNR] = { 7004092e99dSMax Reitz [QCOW2_OL_MAIN_HEADER_BITNR] = QCOW2_OPT_OVERLAP_MAIN_HEADER, 7014092e99dSMax Reitz [QCOW2_OL_ACTIVE_L1_BITNR] = QCOW2_OPT_OVERLAP_ACTIVE_L1, 7024092e99dSMax Reitz [QCOW2_OL_ACTIVE_L2_BITNR] = QCOW2_OPT_OVERLAP_ACTIVE_L2, 7034092e99dSMax Reitz [QCOW2_OL_REFCOUNT_TABLE_BITNR] = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE, 7044092e99dSMax Reitz [QCOW2_OL_REFCOUNT_BLOCK_BITNR] = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK, 7054092e99dSMax Reitz [QCOW2_OL_SNAPSHOT_TABLE_BITNR] = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE, 7064092e99dSMax Reitz [QCOW2_OL_INACTIVE_L1_BITNR] = QCOW2_OPT_OVERLAP_INACTIVE_L1, 7074092e99dSMax Reitz [QCOW2_OL_INACTIVE_L2_BITNR] = QCOW2_OPT_OVERLAP_INACTIVE_L2, 7084092e99dSMax Reitz }; 7094092e99dSMax Reitz 710279621c0SAlberto Garcia static void cache_clean_timer_cb(void *opaque) 711279621c0SAlberto Garcia { 712279621c0SAlberto Garcia BlockDriverState *bs = opaque; 713ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque; 714b2f68bffSAlberto Garcia qcow2_cache_clean_unused(s->l2_table_cache); 715b2f68bffSAlberto Garcia qcow2_cache_clean_unused(s->refcount_block_cache); 716279621c0SAlberto Garcia timer_mod(s->cache_clean_timer, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) + 717279621c0SAlberto Garcia (int64_t) s->cache_clean_interval * 1000); 718279621c0SAlberto Garcia } 719279621c0SAlberto Garcia 720279621c0SAlberto Garcia static void cache_clean_timer_init(BlockDriverState *bs, AioContext *context) 721279621c0SAlberto Garcia { 722ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque; 723279621c0SAlberto Garcia if (s->cache_clean_interval > 0) { 724279621c0SAlberto Garcia s->cache_clean_timer = aio_timer_new(context, QEMU_CLOCK_VIRTUAL, 725279621c0SAlberto Garcia SCALE_MS, cache_clean_timer_cb, 726279621c0SAlberto Garcia bs); 727279621c0SAlberto Garcia timer_mod(s->cache_clean_timer, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) + 728279621c0SAlberto Garcia (int64_t) s->cache_clean_interval * 1000); 729279621c0SAlberto Garcia } 730279621c0SAlberto Garcia } 731279621c0SAlberto Garcia 732279621c0SAlberto Garcia static void cache_clean_timer_del(BlockDriverState *bs) 733279621c0SAlberto Garcia { 734ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque; 735279621c0SAlberto Garcia if (s->cache_clean_timer) { 736279621c0SAlberto Garcia timer_del(s->cache_clean_timer); 737279621c0SAlberto Garcia timer_free(s->cache_clean_timer); 738279621c0SAlberto Garcia s->cache_clean_timer = NULL; 739279621c0SAlberto Garcia } 740279621c0SAlberto Garcia } 741279621c0SAlberto Garcia 742279621c0SAlberto Garcia static void qcow2_detach_aio_context(BlockDriverState *bs) 743279621c0SAlberto Garcia { 744279621c0SAlberto Garcia cache_clean_timer_del(bs); 745279621c0SAlberto Garcia } 746279621c0SAlberto Garcia 747279621c0SAlberto Garcia static void qcow2_attach_aio_context(BlockDriverState *bs, 748279621c0SAlberto Garcia AioContext *new_context) 749279621c0SAlberto Garcia { 750279621c0SAlberto Garcia cache_clean_timer_init(bs, new_context); 751279621c0SAlberto Garcia } 752279621c0SAlberto Garcia 753bc85ef26SMax Reitz static void read_cache_sizes(BlockDriverState *bs, QemuOpts *opts, 754bc85ef26SMax Reitz uint64_t *l2_cache_size, 7551221fe6fSAlberto Garcia uint64_t *l2_cache_entry_size, 7566c1c8d5dSMax Reitz uint64_t *refcount_cache_size, Error **errp) 7576c1c8d5dSMax Reitz { 758ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque; 7596c1c8d5dSMax Reitz uint64_t combined_cache_size; 7606c1c8d5dSMax Reitz bool l2_cache_size_set, refcount_cache_size_set, combined_cache_size_set; 7616c1c8d5dSMax Reitz 7626c1c8d5dSMax Reitz combined_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_CACHE_SIZE); 7636c1c8d5dSMax Reitz l2_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_L2_CACHE_SIZE); 7646c1c8d5dSMax Reitz refcount_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_REFCOUNT_CACHE_SIZE); 7656c1c8d5dSMax Reitz 7666c1c8d5dSMax Reitz combined_cache_size = qemu_opt_get_size(opts, QCOW2_OPT_CACHE_SIZE, 0); 7676c1c8d5dSMax Reitz *l2_cache_size = qemu_opt_get_size(opts, QCOW2_OPT_L2_CACHE_SIZE, 0); 7686c1c8d5dSMax Reitz *refcount_cache_size = qemu_opt_get_size(opts, 7696c1c8d5dSMax Reitz QCOW2_OPT_REFCOUNT_CACHE_SIZE, 0); 7706c1c8d5dSMax Reitz 7711221fe6fSAlberto Garcia *l2_cache_entry_size = qemu_opt_get_size( 7721221fe6fSAlberto Garcia opts, QCOW2_OPT_L2_CACHE_ENTRY_SIZE, s->cluster_size); 7731221fe6fSAlberto Garcia 7746c1c8d5dSMax Reitz if (combined_cache_size_set) { 7756c1c8d5dSMax Reitz if (l2_cache_size_set && refcount_cache_size_set) { 7766c1c8d5dSMax Reitz error_setg(errp, QCOW2_OPT_CACHE_SIZE ", " QCOW2_OPT_L2_CACHE_SIZE 7776c1c8d5dSMax Reitz " and " QCOW2_OPT_REFCOUNT_CACHE_SIZE " may not be set " 7786c1c8d5dSMax Reitz "the same time"); 7796c1c8d5dSMax Reitz return; 7806c1c8d5dSMax Reitz } else if (*l2_cache_size > combined_cache_size) { 7816c1c8d5dSMax Reitz error_setg(errp, QCOW2_OPT_L2_CACHE_SIZE " may not exceed " 7826c1c8d5dSMax Reitz QCOW2_OPT_CACHE_SIZE); 7836c1c8d5dSMax Reitz return; 7846c1c8d5dSMax Reitz } else if (*refcount_cache_size > combined_cache_size) { 7856c1c8d5dSMax Reitz error_setg(errp, QCOW2_OPT_REFCOUNT_CACHE_SIZE " may not exceed " 7866c1c8d5dSMax Reitz QCOW2_OPT_CACHE_SIZE); 7876c1c8d5dSMax Reitz return; 7886c1c8d5dSMax Reitz } 7896c1c8d5dSMax Reitz 7906c1c8d5dSMax Reitz if (l2_cache_size_set) { 7916c1c8d5dSMax Reitz *refcount_cache_size = combined_cache_size - *l2_cache_size; 7926c1c8d5dSMax Reitz } else if (refcount_cache_size_set) { 7936c1c8d5dSMax Reitz *l2_cache_size = combined_cache_size - *refcount_cache_size; 7946c1c8d5dSMax Reitz } else { 7956c1c8d5dSMax Reitz *refcount_cache_size = combined_cache_size 7966c1c8d5dSMax Reitz / (DEFAULT_L2_REFCOUNT_SIZE_RATIO + 1); 7976c1c8d5dSMax Reitz *l2_cache_size = combined_cache_size - *refcount_cache_size; 7986c1c8d5dSMax Reitz } 7996c1c8d5dSMax Reitz } else { 8006c1c8d5dSMax Reitz if (!l2_cache_size_set && !refcount_cache_size_set) { 801bc85ef26SMax Reitz *l2_cache_size = MAX(DEFAULT_L2_CACHE_BYTE_SIZE, 802bc85ef26SMax Reitz (uint64_t)DEFAULT_L2_CACHE_CLUSTERS 803bc85ef26SMax Reitz * s->cluster_size); 8046c1c8d5dSMax Reitz *refcount_cache_size = *l2_cache_size 8056c1c8d5dSMax Reitz / DEFAULT_L2_REFCOUNT_SIZE_RATIO; 8066c1c8d5dSMax Reitz } else if (!l2_cache_size_set) { 8076c1c8d5dSMax Reitz *l2_cache_size = *refcount_cache_size 8086c1c8d5dSMax Reitz * DEFAULT_L2_REFCOUNT_SIZE_RATIO; 8096c1c8d5dSMax Reitz } else if (!refcount_cache_size_set) { 8106c1c8d5dSMax Reitz *refcount_cache_size = *l2_cache_size 8116c1c8d5dSMax Reitz / DEFAULT_L2_REFCOUNT_SIZE_RATIO; 8126c1c8d5dSMax Reitz } 8136c1c8d5dSMax Reitz } 8141221fe6fSAlberto Garcia 8151221fe6fSAlberto Garcia if (*l2_cache_entry_size < (1 << MIN_CLUSTER_BITS) || 8161221fe6fSAlberto Garcia *l2_cache_entry_size > s->cluster_size || 8171221fe6fSAlberto Garcia !is_power_of_2(*l2_cache_entry_size)) { 8181221fe6fSAlberto Garcia error_setg(errp, "L2 cache entry size must be a power of two " 8191221fe6fSAlberto Garcia "between %d and the cluster size (%d)", 8201221fe6fSAlberto Garcia 1 << MIN_CLUSTER_BITS, s->cluster_size); 8211221fe6fSAlberto Garcia return; 8221221fe6fSAlberto Garcia } 8236c1c8d5dSMax Reitz } 8246c1c8d5dSMax Reitz 825ee55b173SKevin Wolf typedef struct Qcow2ReopenState { 826ee55b173SKevin Wolf Qcow2Cache *l2_table_cache; 827ee55b173SKevin Wolf Qcow2Cache *refcount_block_cache; 8283c2e511aSAlberto Garcia int l2_slice_size; /* Number of entries in a slice of the L2 table */ 829ee55b173SKevin Wolf bool use_lazy_refcounts; 830ee55b173SKevin Wolf int overlap_check; 831ee55b173SKevin Wolf bool discard_passthrough[QCOW2_DISCARD_MAX]; 832ee55b173SKevin Wolf uint64_t cache_clean_interval; 833b25b387fSDaniel P. Berrange QCryptoBlockOpenOptions *crypto_opts; /* Disk encryption runtime options */ 834ee55b173SKevin Wolf } Qcow2ReopenState; 835ee55b173SKevin Wolf 836ee55b173SKevin Wolf static int qcow2_update_options_prepare(BlockDriverState *bs, 837ee55b173SKevin Wolf Qcow2ReopenState *r, 838ee55b173SKevin Wolf QDict *options, int flags, 839ee55b173SKevin Wolf Error **errp) 8404c75d1a1SKevin Wolf { 8414c75d1a1SKevin Wolf BDRVQcow2State *s = bs->opaque; 84294edf3fbSKevin Wolf QemuOpts *opts = NULL; 8434c75d1a1SKevin Wolf const char *opt_overlap_check, *opt_overlap_check_template; 8444c75d1a1SKevin Wolf int overlap_check_template = 0; 8451221fe6fSAlberto Garcia uint64_t l2_cache_size, l2_cache_entry_size, refcount_cache_size; 8464c75d1a1SKevin Wolf int i; 847b25b387fSDaniel P. Berrange const char *encryptfmt; 848b25b387fSDaniel P. Berrange QDict *encryptopts = NULL; 84994edf3fbSKevin Wolf Error *local_err = NULL; 8504c75d1a1SKevin Wolf int ret; 8514c75d1a1SKevin Wolf 852b25b387fSDaniel P. Berrange qdict_extract_subqdict(options, &encryptopts, "encrypt."); 853b25b387fSDaniel P. Berrange encryptfmt = qdict_get_try_str(encryptopts, "format"); 854b25b387fSDaniel P. Berrange 85594edf3fbSKevin Wolf opts = qemu_opts_create(&qcow2_runtime_opts, NULL, 0, &error_abort); 85694edf3fbSKevin Wolf qemu_opts_absorb_qdict(opts, options, &local_err); 85794edf3fbSKevin Wolf if (local_err) { 85894edf3fbSKevin Wolf error_propagate(errp, local_err); 85994edf3fbSKevin Wolf ret = -EINVAL; 86094edf3fbSKevin Wolf goto fail; 86194edf3fbSKevin Wolf } 86294edf3fbSKevin Wolf 86394edf3fbSKevin Wolf /* get L2 table/refcount block cache size from command line options */ 8641221fe6fSAlberto Garcia read_cache_sizes(bs, opts, &l2_cache_size, &l2_cache_entry_size, 8651221fe6fSAlberto Garcia &refcount_cache_size, &local_err); 86694edf3fbSKevin Wolf if (local_err) { 86794edf3fbSKevin Wolf error_propagate(errp, local_err); 86894edf3fbSKevin Wolf ret = -EINVAL; 86994edf3fbSKevin Wolf goto fail; 87094edf3fbSKevin Wolf } 87194edf3fbSKevin Wolf 8721221fe6fSAlberto Garcia l2_cache_size /= l2_cache_entry_size; 87394edf3fbSKevin Wolf if (l2_cache_size < MIN_L2_CACHE_SIZE) { 87494edf3fbSKevin Wolf l2_cache_size = MIN_L2_CACHE_SIZE; 87594edf3fbSKevin Wolf } 87694edf3fbSKevin Wolf if (l2_cache_size > INT_MAX) { 87794edf3fbSKevin Wolf error_setg(errp, "L2 cache size too big"); 87894edf3fbSKevin Wolf ret = -EINVAL; 87994edf3fbSKevin Wolf goto fail; 88094edf3fbSKevin Wolf } 88194edf3fbSKevin Wolf 88294edf3fbSKevin Wolf refcount_cache_size /= s->cluster_size; 88394edf3fbSKevin Wolf if (refcount_cache_size < MIN_REFCOUNT_CACHE_SIZE) { 88494edf3fbSKevin Wolf refcount_cache_size = MIN_REFCOUNT_CACHE_SIZE; 88594edf3fbSKevin Wolf } 88694edf3fbSKevin Wolf if (refcount_cache_size > INT_MAX) { 88794edf3fbSKevin Wolf error_setg(errp, "Refcount cache size too big"); 88894edf3fbSKevin Wolf ret = -EINVAL; 88994edf3fbSKevin Wolf goto fail; 89094edf3fbSKevin Wolf } 89194edf3fbSKevin Wolf 8925b0959a7SKevin Wolf /* alloc new L2 table/refcount block cache, flush old one */ 8935b0959a7SKevin Wolf if (s->l2_table_cache) { 8945b0959a7SKevin Wolf ret = qcow2_cache_flush(bs, s->l2_table_cache); 8955b0959a7SKevin Wolf if (ret) { 8965b0959a7SKevin Wolf error_setg_errno(errp, -ret, "Failed to flush the L2 table cache"); 8975b0959a7SKevin Wolf goto fail; 8985b0959a7SKevin Wolf } 8995b0959a7SKevin Wolf } 9005b0959a7SKevin Wolf 9015b0959a7SKevin Wolf if (s->refcount_block_cache) { 9025b0959a7SKevin Wolf ret = qcow2_cache_flush(bs, s->refcount_block_cache); 9035b0959a7SKevin Wolf if (ret) { 9045b0959a7SKevin Wolf error_setg_errno(errp, -ret, 9055b0959a7SKevin Wolf "Failed to flush the refcount block cache"); 9065b0959a7SKevin Wolf goto fail; 9075b0959a7SKevin Wolf } 9085b0959a7SKevin Wolf } 9095b0959a7SKevin Wolf 9101221fe6fSAlberto Garcia r->l2_slice_size = l2_cache_entry_size / sizeof(uint64_t); 9111221fe6fSAlberto Garcia r->l2_table_cache = qcow2_cache_create(bs, l2_cache_size, 9121221fe6fSAlberto Garcia l2_cache_entry_size); 9131221fe6fSAlberto Garcia r->refcount_block_cache = qcow2_cache_create(bs, refcount_cache_size, 9141221fe6fSAlberto Garcia s->cluster_size); 915ee55b173SKevin Wolf if (r->l2_table_cache == NULL || r->refcount_block_cache == NULL) { 91694edf3fbSKevin Wolf error_setg(errp, "Could not allocate metadata caches"); 91794edf3fbSKevin Wolf ret = -ENOMEM; 91894edf3fbSKevin Wolf goto fail; 91994edf3fbSKevin Wolf } 92094edf3fbSKevin Wolf 92194edf3fbSKevin Wolf /* New interval for cache cleanup timer */ 922ee55b173SKevin Wolf r->cache_clean_interval = 9235b0959a7SKevin Wolf qemu_opt_get_number(opts, QCOW2_OPT_CACHE_CLEAN_INTERVAL, 9245b0959a7SKevin Wolf s->cache_clean_interval); 92591203f08SAlberto Garcia #ifndef CONFIG_LINUX 92691203f08SAlberto Garcia if (r->cache_clean_interval != 0) { 92791203f08SAlberto Garcia error_setg(errp, QCOW2_OPT_CACHE_CLEAN_INTERVAL 92891203f08SAlberto Garcia " not supported on this host"); 92991203f08SAlberto Garcia ret = -EINVAL; 93091203f08SAlberto Garcia goto fail; 93191203f08SAlberto Garcia } 93291203f08SAlberto Garcia #endif 933ee55b173SKevin Wolf if (r->cache_clean_interval > UINT_MAX) { 93494edf3fbSKevin Wolf error_setg(errp, "Cache clean interval too big"); 93594edf3fbSKevin Wolf ret = -EINVAL; 93694edf3fbSKevin Wolf goto fail; 93794edf3fbSKevin Wolf } 93894edf3fbSKevin Wolf 9395b0959a7SKevin Wolf /* lazy-refcounts; flush if going from enabled to disabled */ 940ee55b173SKevin Wolf r->use_lazy_refcounts = qemu_opt_get_bool(opts, QCOW2_OPT_LAZY_REFCOUNTS, 9414c75d1a1SKevin Wolf (s->compatible_features & QCOW2_COMPAT_LAZY_REFCOUNTS)); 942ee55b173SKevin Wolf if (r->use_lazy_refcounts && s->qcow_version < 3) { 943007dbc39SKevin Wolf error_setg(errp, "Lazy refcounts require a qcow2 image with at least " 944007dbc39SKevin Wolf "qemu 1.1 compatibility level"); 945007dbc39SKevin Wolf ret = -EINVAL; 946007dbc39SKevin Wolf goto fail; 947007dbc39SKevin Wolf } 9484c75d1a1SKevin Wolf 9495b0959a7SKevin Wolf if (s->use_lazy_refcounts && !r->use_lazy_refcounts) { 9505b0959a7SKevin Wolf ret = qcow2_mark_clean(bs); 9515b0959a7SKevin Wolf if (ret < 0) { 9525b0959a7SKevin Wolf error_setg_errno(errp, -ret, "Failed to disable lazy refcounts"); 9535b0959a7SKevin Wolf goto fail; 9545b0959a7SKevin Wolf } 9555b0959a7SKevin Wolf } 9565b0959a7SKevin Wolf 957007dbc39SKevin Wolf /* Overlap check options */ 9584c75d1a1SKevin Wolf opt_overlap_check = qemu_opt_get(opts, QCOW2_OPT_OVERLAP); 9594c75d1a1SKevin Wolf opt_overlap_check_template = qemu_opt_get(opts, QCOW2_OPT_OVERLAP_TEMPLATE); 9604c75d1a1SKevin Wolf if (opt_overlap_check_template && opt_overlap_check && 9614c75d1a1SKevin Wolf strcmp(opt_overlap_check_template, opt_overlap_check)) 9624c75d1a1SKevin Wolf { 9634c75d1a1SKevin Wolf error_setg(errp, "Conflicting values for qcow2 options '" 9644c75d1a1SKevin Wolf QCOW2_OPT_OVERLAP "' ('%s') and '" QCOW2_OPT_OVERLAP_TEMPLATE 9654c75d1a1SKevin Wolf "' ('%s')", opt_overlap_check, opt_overlap_check_template); 9664c75d1a1SKevin Wolf ret = -EINVAL; 9674c75d1a1SKevin Wolf goto fail; 9684c75d1a1SKevin Wolf } 9694c75d1a1SKevin Wolf if (!opt_overlap_check) { 9704c75d1a1SKevin Wolf opt_overlap_check = opt_overlap_check_template ?: "cached"; 9714c75d1a1SKevin Wolf } 9724c75d1a1SKevin Wolf 9734c75d1a1SKevin Wolf if (!strcmp(opt_overlap_check, "none")) { 9744c75d1a1SKevin Wolf overlap_check_template = 0; 9754c75d1a1SKevin Wolf } else if (!strcmp(opt_overlap_check, "constant")) { 9764c75d1a1SKevin Wolf overlap_check_template = QCOW2_OL_CONSTANT; 9774c75d1a1SKevin Wolf } else if (!strcmp(opt_overlap_check, "cached")) { 9784c75d1a1SKevin Wolf overlap_check_template = QCOW2_OL_CACHED; 9794c75d1a1SKevin Wolf } else if (!strcmp(opt_overlap_check, "all")) { 9804c75d1a1SKevin Wolf overlap_check_template = QCOW2_OL_ALL; 9814c75d1a1SKevin Wolf } else { 9824c75d1a1SKevin Wolf error_setg(errp, "Unsupported value '%s' for qcow2 option " 9834c75d1a1SKevin Wolf "'overlap-check'. Allowed are any of the following: " 9844c75d1a1SKevin Wolf "none, constant, cached, all", opt_overlap_check); 9854c75d1a1SKevin Wolf ret = -EINVAL; 9864c75d1a1SKevin Wolf goto fail; 9874c75d1a1SKevin Wolf } 9884c75d1a1SKevin Wolf 989ee55b173SKevin Wolf r->overlap_check = 0; 9904c75d1a1SKevin Wolf for (i = 0; i < QCOW2_OL_MAX_BITNR; i++) { 9914c75d1a1SKevin Wolf /* overlap-check defines a template bitmask, but every flag may be 9924c75d1a1SKevin Wolf * overwritten through the associated boolean option */ 993ee55b173SKevin Wolf r->overlap_check |= 9944c75d1a1SKevin Wolf qemu_opt_get_bool(opts, overlap_bool_option_names[i], 9954c75d1a1SKevin Wolf overlap_check_template & (1 << i)) << i; 9964c75d1a1SKevin Wolf } 9974c75d1a1SKevin Wolf 998ee55b173SKevin Wolf r->discard_passthrough[QCOW2_DISCARD_NEVER] = false; 999ee55b173SKevin Wolf r->discard_passthrough[QCOW2_DISCARD_ALWAYS] = true; 1000ee55b173SKevin Wolf r->discard_passthrough[QCOW2_DISCARD_REQUEST] = 1001007dbc39SKevin Wolf qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_REQUEST, 1002007dbc39SKevin Wolf flags & BDRV_O_UNMAP); 1003ee55b173SKevin Wolf r->discard_passthrough[QCOW2_DISCARD_SNAPSHOT] = 1004007dbc39SKevin Wolf qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_SNAPSHOT, true); 1005ee55b173SKevin Wolf r->discard_passthrough[QCOW2_DISCARD_OTHER] = 1006007dbc39SKevin Wolf qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_OTHER, false); 1007007dbc39SKevin Wolf 1008b25b387fSDaniel P. Berrange switch (s->crypt_method_header) { 1009b25b387fSDaniel P. Berrange case QCOW_CRYPT_NONE: 1010b25b387fSDaniel P. Berrange if (encryptfmt) { 1011b25b387fSDaniel P. Berrange error_setg(errp, "No encryption in image header, but options " 1012b25b387fSDaniel P. Berrange "specified format '%s'", encryptfmt); 1013b25b387fSDaniel P. Berrange ret = -EINVAL; 1014b25b387fSDaniel P. Berrange goto fail; 1015b25b387fSDaniel P. Berrange } 1016b25b387fSDaniel P. Berrange break; 1017b25b387fSDaniel P. Berrange 1018b25b387fSDaniel P. Berrange case QCOW_CRYPT_AES: 1019b25b387fSDaniel P. Berrange if (encryptfmt && !g_str_equal(encryptfmt, "aes")) { 1020b25b387fSDaniel P. Berrange error_setg(errp, 1021b25b387fSDaniel P. Berrange "Header reported 'aes' encryption format but " 1022b25b387fSDaniel P. Berrange "options specify '%s'", encryptfmt); 1023b25b387fSDaniel P. Berrange ret = -EINVAL; 1024b25b387fSDaniel P. Berrange goto fail; 1025b25b387fSDaniel P. Berrange } 1026b25b387fSDaniel P. Berrange qdict_del(encryptopts, "format"); 1027b25b387fSDaniel P. Berrange r->crypto_opts = block_crypto_open_opts_init( 1028b25b387fSDaniel P. Berrange Q_CRYPTO_BLOCK_FORMAT_QCOW, encryptopts, errp); 1029b25b387fSDaniel P. Berrange break; 1030b25b387fSDaniel P. Berrange 10314652b8f3SDaniel P. Berrange case QCOW_CRYPT_LUKS: 10324652b8f3SDaniel P. Berrange if (encryptfmt && !g_str_equal(encryptfmt, "luks")) { 10334652b8f3SDaniel P. Berrange error_setg(errp, 10344652b8f3SDaniel P. Berrange "Header reported 'luks' encryption format but " 10354652b8f3SDaniel P. Berrange "options specify '%s'", encryptfmt); 10364652b8f3SDaniel P. Berrange ret = -EINVAL; 10374652b8f3SDaniel P. Berrange goto fail; 10384652b8f3SDaniel P. Berrange } 10394652b8f3SDaniel P. Berrange qdict_del(encryptopts, "format"); 10404652b8f3SDaniel P. Berrange r->crypto_opts = block_crypto_open_opts_init( 10414652b8f3SDaniel P. Berrange Q_CRYPTO_BLOCK_FORMAT_LUKS, encryptopts, errp); 10424652b8f3SDaniel P. Berrange break; 10434652b8f3SDaniel P. Berrange 1044b25b387fSDaniel P. Berrange default: 1045b25b387fSDaniel P. Berrange error_setg(errp, "Unsupported encryption method %d", 1046b25b387fSDaniel P. Berrange s->crypt_method_header); 1047b25b387fSDaniel P. Berrange break; 1048b25b387fSDaniel P. Berrange } 1049b25b387fSDaniel P. Berrange if (s->crypt_method_header != QCOW_CRYPT_NONE && !r->crypto_opts) { 1050b25b387fSDaniel P. Berrange ret = -EINVAL; 1051b25b387fSDaniel P. Berrange goto fail; 1052b25b387fSDaniel P. Berrange } 1053b25b387fSDaniel P. Berrange 10544c75d1a1SKevin Wolf ret = 0; 10554c75d1a1SKevin Wolf fail: 1056b25b387fSDaniel P. Berrange QDECREF(encryptopts); 105794edf3fbSKevin Wolf qemu_opts_del(opts); 105894edf3fbSKevin Wolf opts = NULL; 1059ee55b173SKevin Wolf return ret; 1060ee55b173SKevin Wolf } 1061ee55b173SKevin Wolf 1062ee55b173SKevin Wolf static void qcow2_update_options_commit(BlockDriverState *bs, 1063ee55b173SKevin Wolf Qcow2ReopenState *r) 1064ee55b173SKevin Wolf { 1065ee55b173SKevin Wolf BDRVQcow2State *s = bs->opaque; 1066ee55b173SKevin Wolf int i; 1067ee55b173SKevin Wolf 10685b0959a7SKevin Wolf if (s->l2_table_cache) { 1069e64d4072SAlberto Garcia qcow2_cache_destroy(s->l2_table_cache); 10705b0959a7SKevin Wolf } 10715b0959a7SKevin Wolf if (s->refcount_block_cache) { 1072e64d4072SAlberto Garcia qcow2_cache_destroy(s->refcount_block_cache); 10735b0959a7SKevin Wolf } 1074ee55b173SKevin Wolf s->l2_table_cache = r->l2_table_cache; 1075ee55b173SKevin Wolf s->refcount_block_cache = r->refcount_block_cache; 10763c2e511aSAlberto Garcia s->l2_slice_size = r->l2_slice_size; 1077ee55b173SKevin Wolf 1078ee55b173SKevin Wolf s->overlap_check = r->overlap_check; 1079ee55b173SKevin Wolf s->use_lazy_refcounts = r->use_lazy_refcounts; 1080ee55b173SKevin Wolf 1081ee55b173SKevin Wolf for (i = 0; i < QCOW2_DISCARD_MAX; i++) { 1082ee55b173SKevin Wolf s->discard_passthrough[i] = r->discard_passthrough[i]; 1083ee55b173SKevin Wolf } 1084ee55b173SKevin Wolf 10855b0959a7SKevin Wolf if (s->cache_clean_interval != r->cache_clean_interval) { 10865b0959a7SKevin Wolf cache_clean_timer_del(bs); 1087ee55b173SKevin Wolf s->cache_clean_interval = r->cache_clean_interval; 1088ee55b173SKevin Wolf cache_clean_timer_init(bs, bdrv_get_aio_context(bs)); 1089ee55b173SKevin Wolf } 1090b25b387fSDaniel P. Berrange 1091b25b387fSDaniel P. Berrange qapi_free_QCryptoBlockOpenOptions(s->crypto_opts); 1092b25b387fSDaniel P. Berrange s->crypto_opts = r->crypto_opts; 10935b0959a7SKevin Wolf } 1094ee55b173SKevin Wolf 1095ee55b173SKevin Wolf static void qcow2_update_options_abort(BlockDriverState *bs, 1096ee55b173SKevin Wolf Qcow2ReopenState *r) 1097ee55b173SKevin Wolf { 1098ee55b173SKevin Wolf if (r->l2_table_cache) { 1099e64d4072SAlberto Garcia qcow2_cache_destroy(r->l2_table_cache); 1100ee55b173SKevin Wolf } 1101ee55b173SKevin Wolf if (r->refcount_block_cache) { 1102e64d4072SAlberto Garcia qcow2_cache_destroy(r->refcount_block_cache); 1103ee55b173SKevin Wolf } 1104b25b387fSDaniel P. Berrange qapi_free_QCryptoBlockOpenOptions(r->crypto_opts); 1105ee55b173SKevin Wolf } 1106ee55b173SKevin Wolf 1107ee55b173SKevin Wolf static int qcow2_update_options(BlockDriverState *bs, QDict *options, 1108ee55b173SKevin Wolf int flags, Error **errp) 1109ee55b173SKevin Wolf { 1110ee55b173SKevin Wolf Qcow2ReopenState r = {}; 1111ee55b173SKevin Wolf int ret; 1112ee55b173SKevin Wolf 1113ee55b173SKevin Wolf ret = qcow2_update_options_prepare(bs, &r, options, flags, errp); 1114ee55b173SKevin Wolf if (ret >= 0) { 1115ee55b173SKevin Wolf qcow2_update_options_commit(bs, &r); 1116ee55b173SKevin Wolf } else { 1117ee55b173SKevin Wolf qcow2_update_options_abort(bs, &r); 1118ee55b173SKevin Wolf } 111994edf3fbSKevin Wolf 11204c75d1a1SKevin Wolf return ret; 11214c75d1a1SKevin Wolf } 11224c75d1a1SKevin Wolf 11234e4bf5c4SKevin Wolf static int qcow2_do_open(BlockDriverState *bs, QDict *options, int flags, 1124015a1036SMax Reitz Error **errp) 1125585f8587Sbellard { 1126ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque; 11276d33e8e7SKevin Wolf unsigned int len, i; 11286d33e8e7SKevin Wolf int ret = 0; 1129585f8587Sbellard QCowHeader header; 113074c4510aSKevin Wolf Error *local_err = NULL; 11319b80ddf3Saliguori uint64_t ext_end; 11322cf7cfa1SKevin Wolf uint64_t l1_vm_state_index; 113388ddffaeSVladimir Sementsov-Ogievskiy bool update_header = false; 1134585f8587Sbellard 1135cf2ab8fcSKevin Wolf ret = bdrv_pread(bs->file, 0, &header, sizeof(header)); 11366d85a57eSJes Sorensen if (ret < 0) { 11373ef6c40aSMax Reitz error_setg_errno(errp, -ret, "Could not read qcow2 header"); 1138585f8587Sbellard goto fail; 11396d85a57eSJes Sorensen } 1140585f8587Sbellard be32_to_cpus(&header.magic); 1141585f8587Sbellard be32_to_cpus(&header.version); 1142585f8587Sbellard be64_to_cpus(&header.backing_file_offset); 1143585f8587Sbellard be32_to_cpus(&header.backing_file_size); 1144585f8587Sbellard be64_to_cpus(&header.size); 1145585f8587Sbellard be32_to_cpus(&header.cluster_bits); 1146585f8587Sbellard be32_to_cpus(&header.crypt_method); 1147585f8587Sbellard be64_to_cpus(&header.l1_table_offset); 1148585f8587Sbellard be32_to_cpus(&header.l1_size); 1149585f8587Sbellard be64_to_cpus(&header.refcount_table_offset); 1150585f8587Sbellard be32_to_cpus(&header.refcount_table_clusters); 1151585f8587Sbellard be64_to_cpus(&header.snapshots_offset); 1152585f8587Sbellard be32_to_cpus(&header.nb_snapshots); 1153585f8587Sbellard 1154e8cdcec1SKevin Wolf if (header.magic != QCOW_MAGIC) { 11553ef6c40aSMax Reitz error_setg(errp, "Image is not in qcow2 format"); 115676abe407SPaolo Bonzini ret = -EINVAL; 1157585f8587Sbellard goto fail; 11586d85a57eSJes Sorensen } 11596744cbabSKevin Wolf if (header.version < 2 || header.version > 3) { 1160a55448b3SMax Reitz error_setg(errp, "Unsupported qcow2 version %" PRIu32, header.version); 1161e8cdcec1SKevin Wolf ret = -ENOTSUP; 1162e8cdcec1SKevin Wolf goto fail; 1163e8cdcec1SKevin Wolf } 11646744cbabSKevin Wolf 11656744cbabSKevin Wolf s->qcow_version = header.version; 11666744cbabSKevin Wolf 116724342f2cSKevin Wolf /* Initialise cluster size */ 116824342f2cSKevin Wolf if (header.cluster_bits < MIN_CLUSTER_BITS || 116924342f2cSKevin Wolf header.cluster_bits > MAX_CLUSTER_BITS) { 1170521b2b5dSMax Reitz error_setg(errp, "Unsupported cluster size: 2^%" PRIu32, 1171521b2b5dSMax Reitz header.cluster_bits); 117224342f2cSKevin Wolf ret = -EINVAL; 117324342f2cSKevin Wolf goto fail; 117424342f2cSKevin Wolf } 117524342f2cSKevin Wolf 117624342f2cSKevin Wolf s->cluster_bits = header.cluster_bits; 117724342f2cSKevin Wolf s->cluster_size = 1 << s->cluster_bits; 1178a35f87f5SAlberto Garcia s->cluster_sectors = 1 << (s->cluster_bits - BDRV_SECTOR_BITS); 117924342f2cSKevin Wolf 11806744cbabSKevin Wolf /* Initialise version 3 header fields */ 11816744cbabSKevin Wolf if (header.version == 2) { 11826744cbabSKevin Wolf header.incompatible_features = 0; 11836744cbabSKevin Wolf header.compatible_features = 0; 11846744cbabSKevin Wolf header.autoclear_features = 0; 11856744cbabSKevin Wolf header.refcount_order = 4; 11866744cbabSKevin Wolf header.header_length = 72; 11876744cbabSKevin Wolf } else { 11886744cbabSKevin Wolf be64_to_cpus(&header.incompatible_features); 11896744cbabSKevin Wolf be64_to_cpus(&header.compatible_features); 11906744cbabSKevin Wolf be64_to_cpus(&header.autoclear_features); 11916744cbabSKevin Wolf be32_to_cpus(&header.refcount_order); 11926744cbabSKevin Wolf be32_to_cpus(&header.header_length); 119324342f2cSKevin Wolf 119424342f2cSKevin Wolf if (header.header_length < 104) { 119524342f2cSKevin Wolf error_setg(errp, "qcow2 header too short"); 119624342f2cSKevin Wolf ret = -EINVAL; 119724342f2cSKevin Wolf goto fail; 119824342f2cSKevin Wolf } 119924342f2cSKevin Wolf } 120024342f2cSKevin Wolf 120124342f2cSKevin Wolf if (header.header_length > s->cluster_size) { 120224342f2cSKevin Wolf error_setg(errp, "qcow2 header exceeds cluster size"); 120324342f2cSKevin Wolf ret = -EINVAL; 120424342f2cSKevin Wolf goto fail; 12056744cbabSKevin Wolf } 12066744cbabSKevin Wolf 12076744cbabSKevin Wolf if (header.header_length > sizeof(header)) { 12086744cbabSKevin Wolf s->unknown_header_fields_size = header.header_length - sizeof(header); 12096744cbabSKevin Wolf s->unknown_header_fields = g_malloc(s->unknown_header_fields_size); 1210cf2ab8fcSKevin Wolf ret = bdrv_pread(bs->file, sizeof(header), s->unknown_header_fields, 12116744cbabSKevin Wolf s->unknown_header_fields_size); 12126744cbabSKevin Wolf if (ret < 0) { 12133ef6c40aSMax Reitz error_setg_errno(errp, -ret, "Could not read unknown qcow2 header " 12143ef6c40aSMax Reitz "fields"); 12156744cbabSKevin Wolf goto fail; 12166744cbabSKevin Wolf } 12176744cbabSKevin Wolf } 12186744cbabSKevin Wolf 1219a1b3955cSKevin Wolf if (header.backing_file_offset > s->cluster_size) { 1220a1b3955cSKevin Wolf error_setg(errp, "Invalid backing file offset"); 1221a1b3955cSKevin Wolf ret = -EINVAL; 1222a1b3955cSKevin Wolf goto fail; 1223a1b3955cSKevin Wolf } 1224a1b3955cSKevin Wolf 1225cfcc4c62SKevin Wolf if (header.backing_file_offset) { 1226cfcc4c62SKevin Wolf ext_end = header.backing_file_offset; 1227cfcc4c62SKevin Wolf } else { 1228cfcc4c62SKevin Wolf ext_end = 1 << header.cluster_bits; 1229cfcc4c62SKevin Wolf } 1230cfcc4c62SKevin Wolf 12316744cbabSKevin Wolf /* Handle feature bits */ 12326744cbabSKevin Wolf s->incompatible_features = header.incompatible_features; 12336744cbabSKevin Wolf s->compatible_features = header.compatible_features; 12346744cbabSKevin Wolf s->autoclear_features = header.autoclear_features; 12356744cbabSKevin Wolf 1236c61d0004SStefan Hajnoczi if (s->incompatible_features & ~QCOW2_INCOMPAT_MASK) { 1237cfcc4c62SKevin Wolf void *feature_table = NULL; 1238cfcc4c62SKevin Wolf qcow2_read_extensions(bs, header.header_length, ext_end, 123988ddffaeSVladimir Sementsov-Ogievskiy &feature_table, flags, NULL, NULL); 1240a55448b3SMax Reitz report_unsupported_feature(errp, feature_table, 1241c61d0004SStefan Hajnoczi s->incompatible_features & 1242c61d0004SStefan Hajnoczi ~QCOW2_INCOMPAT_MASK); 12436744cbabSKevin Wolf ret = -ENOTSUP; 1244c5a33ee9SPrasad Joshi g_free(feature_table); 12456744cbabSKevin Wolf goto fail; 12466744cbabSKevin Wolf } 12476744cbabSKevin Wolf 124869c98726SMax Reitz if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) { 124969c98726SMax Reitz /* Corrupt images may not be written to unless they are being repaired 125069c98726SMax Reitz */ 125169c98726SMax Reitz if ((flags & BDRV_O_RDWR) && !(flags & BDRV_O_CHECK)) { 12523ef6c40aSMax Reitz error_setg(errp, "qcow2: Image is corrupt; cannot be opened " 12533ef6c40aSMax Reitz "read/write"); 125469c98726SMax Reitz ret = -EACCES; 125569c98726SMax Reitz goto fail; 125669c98726SMax Reitz } 125769c98726SMax Reitz } 125869c98726SMax Reitz 12596744cbabSKevin Wolf /* Check support for various header values */ 1260b72faf9fSMax Reitz if (header.refcount_order > 6) { 1261b72faf9fSMax Reitz error_setg(errp, "Reference count entry width too large; may not " 1262b72faf9fSMax Reitz "exceed 64 bits"); 1263b72faf9fSMax Reitz ret = -EINVAL; 12646744cbabSKevin Wolf goto fail; 12656744cbabSKevin Wolf } 1266b6481f37SMax Reitz s->refcount_order = header.refcount_order; 1267346a53dfSMax Reitz s->refcount_bits = 1 << s->refcount_order; 1268346a53dfSMax Reitz s->refcount_max = UINT64_C(1) << (s->refcount_bits - 1); 1269346a53dfSMax Reitz s->refcount_max += s->refcount_max - 1; 12706744cbabSKevin Wolf 1271585f8587Sbellard s->crypt_method_header = header.crypt_method; 12726d85a57eSJes Sorensen if (s->crypt_method_header) { 1273e6ff69bfSDaniel P. Berrange if (bdrv_uses_whitelist() && 1274e6ff69bfSDaniel P. Berrange s->crypt_method_header == QCOW_CRYPT_AES) { 12758c0dcbc4SDaniel P. Berrange error_setg(errp, 12768c0dcbc4SDaniel P. Berrange "Use of AES-CBC encrypted qcow2 images is no longer " 12778c0dcbc4SDaniel P. Berrange "supported in system emulators"); 12788c0dcbc4SDaniel P. Berrange error_append_hint(errp, 12798c0dcbc4SDaniel P. Berrange "You can use 'qemu-img convert' to convert your " 12808c0dcbc4SDaniel P. Berrange "image to an alternative supported format, such " 12818c0dcbc4SDaniel P. Berrange "as unencrypted qcow2, or raw with the LUKS " 12828c0dcbc4SDaniel P. Berrange "format instead.\n"); 12838c0dcbc4SDaniel P. Berrange ret = -ENOSYS; 12848c0dcbc4SDaniel P. Berrange goto fail; 1285e6ff69bfSDaniel P. Berrange } 1286e6ff69bfSDaniel P. Berrange 12874652b8f3SDaniel P. Berrange if (s->crypt_method_header == QCOW_CRYPT_AES) { 12884652b8f3SDaniel P. Berrange s->crypt_physical_offset = false; 12894652b8f3SDaniel P. Berrange } else { 12904652b8f3SDaniel P. Berrange /* Assuming LUKS and any future crypt methods we 12914652b8f3SDaniel P. Berrange * add will all use physical offsets, due to the 12924652b8f3SDaniel P. Berrange * fact that the alternative is insecure... */ 12934652b8f3SDaniel P. Berrange s->crypt_physical_offset = true; 12944652b8f3SDaniel P. Berrange } 12954652b8f3SDaniel P. Berrange 129654115412SEric Blake bs->encrypted = true; 12976d85a57eSJes Sorensen } 129824342f2cSKevin Wolf 1299585f8587Sbellard s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */ 1300585f8587Sbellard s->l2_size = 1 << s->l2_bits; 13011d13d654SMax Reitz /* 2^(s->refcount_order - 3) is the refcount width in bytes */ 13021d13d654SMax Reitz s->refcount_block_bits = s->cluster_bits - (s->refcount_order - 3); 13031d13d654SMax Reitz s->refcount_block_size = 1 << s->refcount_block_bits; 1304585f8587Sbellard bs->total_sectors = header.size / 512; 1305585f8587Sbellard s->csize_shift = (62 - (s->cluster_bits - 8)); 1306585f8587Sbellard s->csize_mask = (1 << (s->cluster_bits - 8)) - 1; 1307585f8587Sbellard s->cluster_offset_mask = (1LL << s->csize_shift) - 1; 13085dab2fadSKevin Wolf 1309585f8587Sbellard s->refcount_table_offset = header.refcount_table_offset; 1310585f8587Sbellard s->refcount_table_size = 1311585f8587Sbellard header.refcount_table_clusters << (s->cluster_bits - 3); 1312585f8587Sbellard 13132b5d5953SKevin Wolf if (header.refcount_table_clusters > qcow2_max_refcount_clusters(s)) { 13145dab2fadSKevin Wolf error_setg(errp, "Reference count table too large"); 13155dab2fadSKevin Wolf ret = -EINVAL; 13165dab2fadSKevin Wolf goto fail; 13175dab2fadSKevin Wolf } 13185dab2fadSKevin Wolf 1319951053a9SAlberto Garcia if (header.refcount_table_clusters == 0 && !(flags & BDRV_O_CHECK)) { 1320951053a9SAlberto Garcia error_setg(errp, "Image does not contain a reference count table"); 1321951053a9SAlberto Garcia ret = -EINVAL; 1322951053a9SAlberto Garcia goto fail; 1323951053a9SAlberto Garcia } 1324951053a9SAlberto Garcia 13258c7de283SKevin Wolf ret = validate_table_offset(bs, s->refcount_table_offset, 13268c7de283SKevin Wolf s->refcount_table_size, sizeof(uint64_t)); 13278c7de283SKevin Wolf if (ret < 0) { 13288c7de283SKevin Wolf error_setg(errp, "Invalid reference count table offset"); 13298c7de283SKevin Wolf goto fail; 13308c7de283SKevin Wolf } 13318c7de283SKevin Wolf 1332ce48f2f4SKevin Wolf /* Snapshot table offset/length */ 1333ce48f2f4SKevin Wolf if (header.nb_snapshots > QCOW_MAX_SNAPSHOTS) { 1334ce48f2f4SKevin Wolf error_setg(errp, "Too many snapshots"); 1335ce48f2f4SKevin Wolf ret = -EINVAL; 1336ce48f2f4SKevin Wolf goto fail; 1337ce48f2f4SKevin Wolf } 1338ce48f2f4SKevin Wolf 1339ce48f2f4SKevin Wolf ret = validate_table_offset(bs, header.snapshots_offset, 1340ce48f2f4SKevin Wolf header.nb_snapshots, 1341ce48f2f4SKevin Wolf sizeof(QCowSnapshotHeader)); 1342ce48f2f4SKevin Wolf if (ret < 0) { 1343ce48f2f4SKevin Wolf error_setg(errp, "Invalid snapshot table offset"); 1344ce48f2f4SKevin Wolf goto fail; 1345ce48f2f4SKevin Wolf } 1346ce48f2f4SKevin Wolf 1347585f8587Sbellard /* read the level 1 table */ 134887b86e7eSWen Congyang if (header.l1_size > QCOW_MAX_L1_SIZE / sizeof(uint64_t)) { 13492d51c32cSKevin Wolf error_setg(errp, "Active L1 table too large"); 13502d51c32cSKevin Wolf ret = -EFBIG; 13512d51c32cSKevin Wolf goto fail; 13522d51c32cSKevin Wolf } 1353585f8587Sbellard s->l1_size = header.l1_size; 13542cf7cfa1SKevin Wolf 13552cf7cfa1SKevin Wolf l1_vm_state_index = size_to_l1(s, header.size); 13562cf7cfa1SKevin Wolf if (l1_vm_state_index > INT_MAX) { 13573ef6c40aSMax Reitz error_setg(errp, "Image is too big"); 13582cf7cfa1SKevin Wolf ret = -EFBIG; 13592cf7cfa1SKevin Wolf goto fail; 13602cf7cfa1SKevin Wolf } 13612cf7cfa1SKevin Wolf s->l1_vm_state_index = l1_vm_state_index; 13622cf7cfa1SKevin Wolf 1363585f8587Sbellard /* the L1 table must contain at least enough entries to put 1364585f8587Sbellard header.size bytes */ 13656d85a57eSJes Sorensen if (s->l1_size < s->l1_vm_state_index) { 13663ef6c40aSMax Reitz error_setg(errp, "L1 table is too small"); 13676d85a57eSJes Sorensen ret = -EINVAL; 1368585f8587Sbellard goto fail; 13696d85a57eSJes Sorensen } 13702d51c32cSKevin Wolf 13712d51c32cSKevin Wolf ret = validate_table_offset(bs, header.l1_table_offset, 13722d51c32cSKevin Wolf header.l1_size, sizeof(uint64_t)); 13732d51c32cSKevin Wolf if (ret < 0) { 13742d51c32cSKevin Wolf error_setg(errp, "Invalid L1 table offset"); 13752d51c32cSKevin Wolf goto fail; 13762d51c32cSKevin Wolf } 1377585f8587Sbellard s->l1_table_offset = header.l1_table_offset; 13782d51c32cSKevin Wolf 13792d51c32cSKevin Wolf 1380d191d12dSStefan Weil if (s->l1_size > 0) { 13819a4f4c31SKevin Wolf s->l1_table = qemu_try_blockalign(bs->file->bs, 13823f6a3ee5SKevin Wolf align_offset(s->l1_size * sizeof(uint64_t), 512)); 1383de82815dSKevin Wolf if (s->l1_table == NULL) { 1384de82815dSKevin Wolf error_setg(errp, "Could not allocate L1 table"); 1385de82815dSKevin Wolf ret = -ENOMEM; 1386de82815dSKevin Wolf goto fail; 1387de82815dSKevin Wolf } 1388cf2ab8fcSKevin Wolf ret = bdrv_pread(bs->file, s->l1_table_offset, s->l1_table, 13896d85a57eSJes Sorensen s->l1_size * sizeof(uint64_t)); 13906d85a57eSJes Sorensen if (ret < 0) { 13913ef6c40aSMax Reitz error_setg_errno(errp, -ret, "Could not read L1 table"); 1392585f8587Sbellard goto fail; 13936d85a57eSJes Sorensen } 1394585f8587Sbellard for(i = 0;i < s->l1_size; i++) { 1395585f8587Sbellard be64_to_cpus(&s->l1_table[i]); 1396585f8587Sbellard } 1397d191d12dSStefan Weil } 139829c1a730SKevin Wolf 139994edf3fbSKevin Wolf /* Parse driver-specific options */ 140094edf3fbSKevin Wolf ret = qcow2_update_options(bs, options, flags, errp); 140190efa0eaSKevin Wolf if (ret < 0) { 140290efa0eaSKevin Wolf goto fail; 140390efa0eaSKevin Wolf } 140490efa0eaSKevin Wolf 1405585f8587Sbellard s->cluster_cache_offset = -1; 140606d9260fSAnthony Liguori s->flags = flags; 1407585f8587Sbellard 14086d85a57eSJes Sorensen ret = qcow2_refcount_init(bs); 14096d85a57eSJes Sorensen if (ret != 0) { 14103ef6c40aSMax Reitz error_setg_errno(errp, -ret, "Could not initialize refcount handling"); 1411585f8587Sbellard goto fail; 14126d85a57eSJes Sorensen } 1413585f8587Sbellard 141472cf2d4fSBlue Swirl QLIST_INIT(&s->cluster_allocs); 14150b919faeSKevin Wolf QTAILQ_INIT(&s->discards); 1416f214978aSKevin Wolf 14179b80ddf3Saliguori /* read qcow2 extensions */ 14183ef6c40aSMax Reitz if (qcow2_read_extensions(bs, header.header_length, ext_end, NULL, 141988ddffaeSVladimir Sementsov-Ogievskiy flags, &update_header, &local_err)) { 14203ef6c40aSMax Reitz error_propagate(errp, local_err); 14216d85a57eSJes Sorensen ret = -EINVAL; 14229b80ddf3Saliguori goto fail; 14236d85a57eSJes Sorensen } 14249b80ddf3Saliguori 14254652b8f3SDaniel P. Berrange /* qcow2_read_extension may have set up the crypto context 14264652b8f3SDaniel P. Berrange * if the crypt method needs a header region, some methods 14274652b8f3SDaniel P. Berrange * don't need header extensions, so must check here 14284652b8f3SDaniel P. Berrange */ 14294652b8f3SDaniel P. Berrange if (s->crypt_method_header && !s->crypto) { 1430b25b387fSDaniel P. Berrange if (s->crypt_method_header == QCOW_CRYPT_AES) { 1431b25b387fSDaniel P. Berrange unsigned int cflags = 0; 1432b25b387fSDaniel P. Berrange if (flags & BDRV_O_NO_IO) { 1433b25b387fSDaniel P. Berrange cflags |= QCRYPTO_BLOCK_OPEN_NO_IO; 1434b25b387fSDaniel P. Berrange } 14351cd9a787SDaniel P. Berrange s->crypto = qcrypto_block_open(s->crypto_opts, "encrypt.", 14361cd9a787SDaniel P. Berrange NULL, NULL, cflags, errp); 1437b25b387fSDaniel P. Berrange if (!s->crypto) { 1438b25b387fSDaniel P. Berrange ret = -EINVAL; 1439b25b387fSDaniel P. Berrange goto fail; 1440b25b387fSDaniel P. Berrange } 14414652b8f3SDaniel P. Berrange } else if (!(flags & BDRV_O_NO_IO)) { 14424652b8f3SDaniel P. Berrange error_setg(errp, "Missing CRYPTO header for crypt method %d", 14434652b8f3SDaniel P. Berrange s->crypt_method_header); 14444652b8f3SDaniel P. Berrange ret = -EINVAL; 14454652b8f3SDaniel P. Berrange goto fail; 14464652b8f3SDaniel P. Berrange } 1447b25b387fSDaniel P. Berrange } 1448b25b387fSDaniel P. Berrange 1449585f8587Sbellard /* read the backing file name */ 1450585f8587Sbellard if (header.backing_file_offset != 0) { 1451585f8587Sbellard len = header.backing_file_size; 14529a29e18fSJeff Cody if (len > MIN(1023, s->cluster_size - header.backing_file_offset) || 1453e729fa6aSJeff Cody len >= sizeof(bs->backing_file)) { 14546d33e8e7SKevin Wolf error_setg(errp, "Backing file name too long"); 14556d33e8e7SKevin Wolf ret = -EINVAL; 14566d33e8e7SKevin Wolf goto fail; 14576d85a57eSJes Sorensen } 1458cf2ab8fcSKevin Wolf ret = bdrv_pread(bs->file, header.backing_file_offset, 14596d85a57eSJes Sorensen bs->backing_file, len); 14606d85a57eSJes Sorensen if (ret < 0) { 14613ef6c40aSMax Reitz error_setg_errno(errp, -ret, "Could not read backing file name"); 1462585f8587Sbellard goto fail; 14636d85a57eSJes Sorensen } 1464585f8587Sbellard bs->backing_file[len] = '\0'; 1465e4603fe1SKevin Wolf s->image_backing_file = g_strdup(bs->backing_file); 1466585f8587Sbellard } 146742deb29fSKevin Wolf 146811b128f4SKevin Wolf /* Internal snapshots */ 146911b128f4SKevin Wolf s->snapshots_offset = header.snapshots_offset; 147011b128f4SKevin Wolf s->nb_snapshots = header.nb_snapshots; 147111b128f4SKevin Wolf 147242deb29fSKevin Wolf ret = qcow2_read_snapshots(bs); 147342deb29fSKevin Wolf if (ret < 0) { 14743ef6c40aSMax Reitz error_setg_errno(errp, -ret, "Could not read snapshots"); 1475585f8587Sbellard goto fail; 14766d85a57eSJes Sorensen } 1477585f8587Sbellard 1478af7b708dSStefan Hajnoczi /* Clear unknown autoclear feature bits */ 147988ddffaeSVladimir Sementsov-Ogievskiy update_header |= s->autoclear_features & ~QCOW2_AUTOCLEAR_MASK; 1480d1258dd0SVladimir Sementsov-Ogievskiy update_header = 1481d1258dd0SVladimir Sementsov-Ogievskiy update_header && !bs->read_only && !(flags & BDRV_O_INACTIVE); 1482d1258dd0SVladimir Sementsov-Ogievskiy if (update_header) { 148388ddffaeSVladimir Sementsov-Ogievskiy s->autoclear_features &= QCOW2_AUTOCLEAR_MASK; 1484d1258dd0SVladimir Sementsov-Ogievskiy } 1485d1258dd0SVladimir Sementsov-Ogievskiy 14863e99da5eSVladimir Sementsov-Ogievskiy if (qcow2_load_dirty_bitmaps(bs, &local_err)) { 1487d1258dd0SVladimir Sementsov-Ogievskiy update_header = false; 1488d1258dd0SVladimir Sementsov-Ogievskiy } 1489d1258dd0SVladimir Sementsov-Ogievskiy if (local_err != NULL) { 1490d1258dd0SVladimir Sementsov-Ogievskiy error_propagate(errp, local_err); 1491d1258dd0SVladimir Sementsov-Ogievskiy ret = -EINVAL; 1492d1258dd0SVladimir Sementsov-Ogievskiy goto fail; 1493d1258dd0SVladimir Sementsov-Ogievskiy } 1494d1258dd0SVladimir Sementsov-Ogievskiy 1495d1258dd0SVladimir Sementsov-Ogievskiy if (update_header) { 1496af7b708dSStefan Hajnoczi ret = qcow2_update_header(bs); 1497af7b708dSStefan Hajnoczi if (ret < 0) { 14983ef6c40aSMax Reitz error_setg_errno(errp, -ret, "Could not update qcow2 header"); 1499af7b708dSStefan Hajnoczi goto fail; 1500af7b708dSStefan Hajnoczi } 1501af7b708dSStefan Hajnoczi } 1502af7b708dSStefan Hajnoczi 150368d100e9SKevin Wolf /* Initialise locks */ 150468d100e9SKevin Wolf qemu_co_mutex_init(&s->lock); 1505e24d813bSEric Blake bs->supported_zero_flags = header.version >= 3 ? BDRV_REQ_MAY_UNMAP : 0; 150668d100e9SKevin Wolf 1507c61d0004SStefan Hajnoczi /* Repair image if dirty */ 150804c01a5cSKevin Wolf if (!(flags & (BDRV_O_CHECK | BDRV_O_INACTIVE)) && !bs->read_only && 1509058f8f16SStefan Hajnoczi (s->incompatible_features & QCOW2_INCOMPAT_DIRTY)) { 1510c61d0004SStefan Hajnoczi BdrvCheckResult result = {0}; 1511c61d0004SStefan Hajnoczi 15125b84106bSMax Reitz ret = qcow2_check(bs, &result, BDRV_FIX_ERRORS | BDRV_FIX_LEAKS); 1513791fff50SMax Reitz if (ret < 0 || result.check_errors) { 1514791fff50SMax Reitz if (ret >= 0) { 1515791fff50SMax Reitz ret = -EIO; 1516791fff50SMax Reitz } 15173ef6c40aSMax Reitz error_setg_errno(errp, -ret, "Could not repair dirty image"); 1518c61d0004SStefan Hajnoczi goto fail; 1519c61d0004SStefan Hajnoczi } 1520c61d0004SStefan Hajnoczi } 1521c61d0004SStefan Hajnoczi 1522585f8587Sbellard #ifdef DEBUG_ALLOC 15236cbc3031SPhilipp Hahn { 15246cbc3031SPhilipp Hahn BdrvCheckResult result = {0}; 1525b35278f7SStefan Hajnoczi qcow2_check_refcounts(bs, &result, 0); 15266cbc3031SPhilipp Hahn } 1527585f8587Sbellard #endif 15286d85a57eSJes Sorensen return ret; 1529585f8587Sbellard 1530585f8587Sbellard fail: 15316744cbabSKevin Wolf g_free(s->unknown_header_fields); 153275bab85cSKevin Wolf cleanup_unknown_header_ext(bs); 1533ed6ccf0fSKevin Wolf qcow2_free_snapshots(bs); 1534ed6ccf0fSKevin Wolf qcow2_refcount_close(bs); 1535de82815dSKevin Wolf qemu_vfree(s->l1_table); 1536cf93980eSMax Reitz /* else pre-write overlap checks in cache_destroy may crash */ 1537cf93980eSMax Reitz s->l1_table = NULL; 1538279621c0SAlberto Garcia cache_clean_timer_del(bs); 153929c1a730SKevin Wolf if (s->l2_table_cache) { 1540e64d4072SAlberto Garcia qcow2_cache_destroy(s->l2_table_cache); 154129c1a730SKevin Wolf } 1542c5a33ee9SPrasad Joshi if (s->refcount_block_cache) { 1543e64d4072SAlberto Garcia qcow2_cache_destroy(s->refcount_block_cache); 1544c5a33ee9SPrasad Joshi } 1545b25b387fSDaniel P. Berrange qcrypto_block_free(s->crypto); 1546b25b387fSDaniel P. Berrange qapi_free_QCryptoBlockOpenOptions(s->crypto_opts); 15476d85a57eSJes Sorensen return ret; 1548585f8587Sbellard } 1549585f8587Sbellard 15504e4bf5c4SKevin Wolf static int qcow2_open(BlockDriverState *bs, QDict *options, int flags, 15514e4bf5c4SKevin Wolf Error **errp) 15524e4bf5c4SKevin Wolf { 15534e4bf5c4SKevin Wolf bs->file = bdrv_open_child(NULL, options, "file", bs, &child_file, 15544e4bf5c4SKevin Wolf false, errp); 15554e4bf5c4SKevin Wolf if (!bs->file) { 15564e4bf5c4SKevin Wolf return -EINVAL; 15574e4bf5c4SKevin Wolf } 15584e4bf5c4SKevin Wolf 15594e4bf5c4SKevin Wolf return qcow2_do_open(bs, options, flags, errp); 15604e4bf5c4SKevin Wolf } 15614e4bf5c4SKevin Wolf 15623baca891SKevin Wolf static void qcow2_refresh_limits(BlockDriverState *bs, Error **errp) 1563d34682cdSKevin Wolf { 1564ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque; 1565d34682cdSKevin Wolf 1566a84178ccSEric Blake if (bs->encrypted) { 1567a84178ccSEric Blake /* Encryption works on a sector granularity */ 1568a5b8dd2cSEric Blake bs->bl.request_alignment = BDRV_SECTOR_SIZE; 1569a84178ccSEric Blake } 1570cf081fcaSEric Blake bs->bl.pwrite_zeroes_alignment = s->cluster_size; 1571ecdbead6SEric Blake bs->bl.pdiscard_alignment = s->cluster_size; 1572d34682cdSKevin Wolf } 1573d34682cdSKevin Wolf 157421d82ac9SJeff Cody static int qcow2_reopen_prepare(BDRVReopenState *state, 157521d82ac9SJeff Cody BlockReopenQueue *queue, Error **errp) 157621d82ac9SJeff Cody { 15775b0959a7SKevin Wolf Qcow2ReopenState *r; 15784c2e5f8fSKevin Wolf int ret; 15794c2e5f8fSKevin Wolf 15805b0959a7SKevin Wolf r = g_new0(Qcow2ReopenState, 1); 15815b0959a7SKevin Wolf state->opaque = r; 15825b0959a7SKevin Wolf 15835b0959a7SKevin Wolf ret = qcow2_update_options_prepare(state->bs, r, state->options, 15845b0959a7SKevin Wolf state->flags, errp); 15855b0959a7SKevin Wolf if (ret < 0) { 15865b0959a7SKevin Wolf goto fail; 15875b0959a7SKevin Wolf } 15885b0959a7SKevin Wolf 15895b0959a7SKevin Wolf /* We need to write out any unwritten data if we reopen read-only. */ 15904c2e5f8fSKevin Wolf if ((state->flags & BDRV_O_RDWR) == 0) { 1591169b8793SVladimir Sementsov-Ogievskiy ret = qcow2_reopen_bitmaps_ro(state->bs, errp); 1592169b8793SVladimir Sementsov-Ogievskiy if (ret < 0) { 1593169b8793SVladimir Sementsov-Ogievskiy goto fail; 1594169b8793SVladimir Sementsov-Ogievskiy } 1595169b8793SVladimir Sementsov-Ogievskiy 15964c2e5f8fSKevin Wolf ret = bdrv_flush(state->bs); 15974c2e5f8fSKevin Wolf if (ret < 0) { 15985b0959a7SKevin Wolf goto fail; 15994c2e5f8fSKevin Wolf } 16004c2e5f8fSKevin Wolf 16014c2e5f8fSKevin Wolf ret = qcow2_mark_clean(state->bs); 16024c2e5f8fSKevin Wolf if (ret < 0) { 16035b0959a7SKevin Wolf goto fail; 16044c2e5f8fSKevin Wolf } 16054c2e5f8fSKevin Wolf } 16064c2e5f8fSKevin Wolf 160721d82ac9SJeff Cody return 0; 16085b0959a7SKevin Wolf 16095b0959a7SKevin Wolf fail: 16105b0959a7SKevin Wolf qcow2_update_options_abort(state->bs, r); 16115b0959a7SKevin Wolf g_free(r); 16125b0959a7SKevin Wolf return ret; 16135b0959a7SKevin Wolf } 16145b0959a7SKevin Wolf 16155b0959a7SKevin Wolf static void qcow2_reopen_commit(BDRVReopenState *state) 16165b0959a7SKevin Wolf { 16175b0959a7SKevin Wolf qcow2_update_options_commit(state->bs, state->opaque); 16185b0959a7SKevin Wolf g_free(state->opaque); 16195b0959a7SKevin Wolf } 16205b0959a7SKevin Wolf 16215b0959a7SKevin Wolf static void qcow2_reopen_abort(BDRVReopenState *state) 16225b0959a7SKevin Wolf { 16235b0959a7SKevin Wolf qcow2_update_options_abort(state->bs, state->opaque); 16245b0959a7SKevin Wolf g_free(state->opaque); 162521d82ac9SJeff Cody } 162621d82ac9SJeff Cody 16275365f44dSKevin Wolf static void qcow2_join_options(QDict *options, QDict *old_options) 16285365f44dSKevin Wolf { 16295365f44dSKevin Wolf bool has_new_overlap_template = 16305365f44dSKevin Wolf qdict_haskey(options, QCOW2_OPT_OVERLAP) || 16315365f44dSKevin Wolf qdict_haskey(options, QCOW2_OPT_OVERLAP_TEMPLATE); 16325365f44dSKevin Wolf bool has_new_total_cache_size = 16335365f44dSKevin Wolf qdict_haskey(options, QCOW2_OPT_CACHE_SIZE); 16345365f44dSKevin Wolf bool has_all_cache_options; 16355365f44dSKevin Wolf 16365365f44dSKevin Wolf /* New overlap template overrides all old overlap options */ 16375365f44dSKevin Wolf if (has_new_overlap_template) { 16385365f44dSKevin Wolf qdict_del(old_options, QCOW2_OPT_OVERLAP); 16395365f44dSKevin Wolf qdict_del(old_options, QCOW2_OPT_OVERLAP_TEMPLATE); 16405365f44dSKevin Wolf qdict_del(old_options, QCOW2_OPT_OVERLAP_MAIN_HEADER); 16415365f44dSKevin Wolf qdict_del(old_options, QCOW2_OPT_OVERLAP_ACTIVE_L1); 16425365f44dSKevin Wolf qdict_del(old_options, QCOW2_OPT_OVERLAP_ACTIVE_L2); 16435365f44dSKevin Wolf qdict_del(old_options, QCOW2_OPT_OVERLAP_REFCOUNT_TABLE); 16445365f44dSKevin Wolf qdict_del(old_options, QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK); 16455365f44dSKevin Wolf qdict_del(old_options, QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE); 16465365f44dSKevin Wolf qdict_del(old_options, QCOW2_OPT_OVERLAP_INACTIVE_L1); 16475365f44dSKevin Wolf qdict_del(old_options, QCOW2_OPT_OVERLAP_INACTIVE_L2); 16485365f44dSKevin Wolf } 16495365f44dSKevin Wolf 16505365f44dSKevin Wolf /* New total cache size overrides all old options */ 16515365f44dSKevin Wolf if (qdict_haskey(options, QCOW2_OPT_CACHE_SIZE)) { 16525365f44dSKevin Wolf qdict_del(old_options, QCOW2_OPT_L2_CACHE_SIZE); 16535365f44dSKevin Wolf qdict_del(old_options, QCOW2_OPT_REFCOUNT_CACHE_SIZE); 16545365f44dSKevin Wolf } 16555365f44dSKevin Wolf 16565365f44dSKevin Wolf qdict_join(options, old_options, false); 16575365f44dSKevin Wolf 16585365f44dSKevin Wolf /* 16595365f44dSKevin Wolf * If after merging all cache size options are set, an old total size is 16605365f44dSKevin Wolf * overwritten. Do keep all options, however, if all three are new. The 16615365f44dSKevin Wolf * resulting error message is what we want to happen. 16625365f44dSKevin Wolf */ 16635365f44dSKevin Wolf has_all_cache_options = 16645365f44dSKevin Wolf qdict_haskey(options, QCOW2_OPT_CACHE_SIZE) || 16655365f44dSKevin Wolf qdict_haskey(options, QCOW2_OPT_L2_CACHE_SIZE) || 16665365f44dSKevin Wolf qdict_haskey(options, QCOW2_OPT_REFCOUNT_CACHE_SIZE); 16675365f44dSKevin Wolf 16685365f44dSKevin Wolf if (has_all_cache_options && !has_new_total_cache_size) { 16695365f44dSKevin Wolf qdict_del(options, QCOW2_OPT_CACHE_SIZE); 16705365f44dSKevin Wolf } 16715365f44dSKevin Wolf } 16725365f44dSKevin Wolf 1673a320fb04SEric Blake static int coroutine_fn qcow2_co_block_status(BlockDriverState *bs, 1674a320fb04SEric Blake bool want_zero, 1675a320fb04SEric Blake int64_t offset, int64_t count, 1676a320fb04SEric Blake int64_t *pnum, int64_t *map, 1677a320fb04SEric Blake BlockDriverState **file) 1678585f8587Sbellard { 1679ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque; 1680585f8587Sbellard uint64_t cluster_offset; 16814bc74be9SPaolo Bonzini int index_in_cluster, ret; 1682ecfe1863SKevin Wolf unsigned int bytes; 1683a320fb04SEric Blake int status = 0; 1684585f8587Sbellard 1685a320fb04SEric Blake bytes = MIN(INT_MAX, count); 1686f8a2e5e3SStefan Hajnoczi qemu_co_mutex_lock(&s->lock); 1687a320fb04SEric Blake ret = qcow2_get_cluster_offset(bs, offset, &bytes, &cluster_offset); 1688f8a2e5e3SStefan Hajnoczi qemu_co_mutex_unlock(&s->lock); 16891c46efaaSKevin Wolf if (ret < 0) { 1690d663640cSPaolo Bonzini return ret; 16911c46efaaSKevin Wolf } 1692095a9c58Saliguori 1693a320fb04SEric Blake *pnum = bytes; 1694ecfe1863SKevin Wolf 16954bc74be9SPaolo Bonzini if (cluster_offset != 0 && ret != QCOW2_CLUSTER_COMPRESSED && 1696b25b387fSDaniel P. Berrange !s->crypto) { 1697a320fb04SEric Blake index_in_cluster = offset & (s->cluster_size - 1); 1698a320fb04SEric Blake *map = cluster_offset | index_in_cluster; 1699178b4db7SFam Zheng *file = bs->file->bs; 1700a320fb04SEric Blake status |= BDRV_BLOCK_OFFSET_VALID; 17014bc74be9SPaolo Bonzini } 1702fdfab37dSEric Blake if (ret == QCOW2_CLUSTER_ZERO_PLAIN || ret == QCOW2_CLUSTER_ZERO_ALLOC) { 17034bc74be9SPaolo Bonzini status |= BDRV_BLOCK_ZERO; 17044bc74be9SPaolo Bonzini } else if (ret != QCOW2_CLUSTER_UNALLOCATED) { 17054bc74be9SPaolo Bonzini status |= BDRV_BLOCK_DATA; 17064bc74be9SPaolo Bonzini } 17074bc74be9SPaolo Bonzini return status; 1708585f8587Sbellard } 1709585f8587Sbellard 1710ecfe1863SKevin Wolf static coroutine_fn int qcow2_co_preadv(BlockDriverState *bs, uint64_t offset, 1711ecfe1863SKevin Wolf uint64_t bytes, QEMUIOVector *qiov, 1712ecfe1863SKevin Wolf int flags) 17131490791fSaliguori { 1714ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque; 1715546a7dc4SEdgar Kaziakhmedov int offset_in_cluster; 171668d100e9SKevin Wolf int ret; 1717ecfe1863SKevin Wolf unsigned int cur_bytes; /* number of bytes in current iteration */ 1718c2bdd990SFrediano Ziglio uint64_t cluster_offset = 0; 17193fc48d09SFrediano Ziglio uint64_t bytes_done = 0; 17203fc48d09SFrediano Ziglio QEMUIOVector hd_qiov; 17213fc48d09SFrediano Ziglio uint8_t *cluster_data = NULL; 1722585f8587Sbellard 17233fc48d09SFrediano Ziglio qemu_iovec_init(&hd_qiov, qiov->niov); 17243fc48d09SFrediano Ziglio 17253fc48d09SFrediano Ziglio qemu_co_mutex_lock(&s->lock); 17263fc48d09SFrediano Ziglio 1727ecfe1863SKevin Wolf while (bytes != 0) { 1728585f8587Sbellard 1729faf575c1SFrediano Ziglio /* prepare next request */ 1730ecfe1863SKevin Wolf cur_bytes = MIN(bytes, INT_MAX); 1731b25b387fSDaniel P. Berrange if (s->crypto) { 1732ecfe1863SKevin Wolf cur_bytes = MIN(cur_bytes, 1733ecfe1863SKevin Wolf QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size); 1734bd28f835SKevin Wolf } 1735bd28f835SKevin Wolf 1736ecfe1863SKevin Wolf ret = qcow2_get_cluster_offset(bs, offset, &cur_bytes, &cluster_offset); 17371c46efaaSKevin Wolf if (ret < 0) { 17383fc48d09SFrediano Ziglio goto fail; 17391c46efaaSKevin Wolf } 17401c46efaaSKevin Wolf 1741ecfe1863SKevin Wolf offset_in_cluster = offset_into_cluster(s, offset); 1742585f8587Sbellard 17433fc48d09SFrediano Ziglio qemu_iovec_reset(&hd_qiov); 1744ecfe1863SKevin Wolf qemu_iovec_concat(&hd_qiov, qiov, bytes_done, cur_bytes); 1745bd28f835SKevin Wolf 174668d000a3SKevin Wolf switch (ret) { 174768d000a3SKevin Wolf case QCOW2_CLUSTER_UNALLOCATED: 1748bd28f835SKevin Wolf 1749760e0063SKevin Wolf if (bs->backing) { 175066f82ceeSKevin Wolf BLKDBG_EVENT(bs->file, BLKDBG_READ_BACKING_AIO); 175168d100e9SKevin Wolf qemu_co_mutex_unlock(&s->lock); 1752546a7dc4SEdgar Kaziakhmedov ret = bdrv_co_preadv(bs->backing, offset, cur_bytes, 1753546a7dc4SEdgar Kaziakhmedov &hd_qiov, 0); 175468d100e9SKevin Wolf qemu_co_mutex_lock(&s->lock); 175568d100e9SKevin Wolf if (ret < 0) { 17563fc48d09SFrediano Ziglio goto fail; 17573ab4c7e9SKevin Wolf } 1758a9465922Sbellard } else { 1759585f8587Sbellard /* Note: in this case, no need to wait */ 1760ecfe1863SKevin Wolf qemu_iovec_memset(&hd_qiov, 0, 0, cur_bytes); 17611490791fSaliguori } 176268d000a3SKevin Wolf break; 176368d000a3SKevin Wolf 1764fdfab37dSEric Blake case QCOW2_CLUSTER_ZERO_PLAIN: 1765fdfab37dSEric Blake case QCOW2_CLUSTER_ZERO_ALLOC: 1766ecfe1863SKevin Wolf qemu_iovec_memset(&hd_qiov, 0, 0, cur_bytes); 17676377af48SKevin Wolf break; 17686377af48SKevin Wolf 176968d000a3SKevin Wolf case QCOW2_CLUSTER_COMPRESSED: 1770585f8587Sbellard /* add AIO support for compressed blocks ? */ 1771c2bdd990SFrediano Ziglio ret = qcow2_decompress_cluster(bs, cluster_offset); 17728af36488SKevin Wolf if (ret < 0) { 17733fc48d09SFrediano Ziglio goto fail; 17748af36488SKevin Wolf } 1775bd28f835SKevin Wolf 177603396148SMichael Tokarev qemu_iovec_from_buf(&hd_qiov, 0, 1777ecfe1863SKevin Wolf s->cluster_cache + offset_in_cluster, 1778ecfe1863SKevin Wolf cur_bytes); 177968d000a3SKevin Wolf break; 178068d000a3SKevin Wolf 178168d000a3SKevin Wolf case QCOW2_CLUSTER_NORMAL: 1782c2bdd990SFrediano Ziglio if ((cluster_offset & 511) != 0) { 17833fc48d09SFrediano Ziglio ret = -EIO; 17843fc48d09SFrediano Ziglio goto fail; 1785585f8587Sbellard } 1786c87c0672Saliguori 17878336aafaSDaniel P. Berrange if (bs->encrypted) { 1788b25b387fSDaniel P. Berrange assert(s->crypto); 17898336aafaSDaniel P. Berrange 1790bd28f835SKevin Wolf /* 1791bd28f835SKevin Wolf * For encrypted images, read everything into a temporary 1792bd28f835SKevin Wolf * contiguous buffer on which the AES functions can work. 1793bd28f835SKevin Wolf */ 17943fc48d09SFrediano Ziglio if (!cluster_data) { 17953fc48d09SFrediano Ziglio cluster_data = 17969a4f4c31SKevin Wolf qemu_try_blockalign(bs->file->bs, 17979a4f4c31SKevin Wolf QCOW_MAX_CRYPT_CLUSTERS 1798de82815dSKevin Wolf * s->cluster_size); 1799de82815dSKevin Wolf if (cluster_data == NULL) { 1800de82815dSKevin Wolf ret = -ENOMEM; 1801de82815dSKevin Wolf goto fail; 1802de82815dSKevin Wolf } 1803bd28f835SKevin Wolf } 1804bd28f835SKevin Wolf 1805ecfe1863SKevin Wolf assert(cur_bytes <= QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size); 18063fc48d09SFrediano Ziglio qemu_iovec_reset(&hd_qiov); 1807ecfe1863SKevin Wolf qemu_iovec_add(&hd_qiov, cluster_data, cur_bytes); 1808bd28f835SKevin Wolf } 1809bd28f835SKevin Wolf 181066f82ceeSKevin Wolf BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO); 181168d100e9SKevin Wolf qemu_co_mutex_unlock(&s->lock); 1812a03ef88fSKevin Wolf ret = bdrv_co_preadv(bs->file, 1813ecfe1863SKevin Wolf cluster_offset + offset_in_cluster, 1814ecfe1863SKevin Wolf cur_bytes, &hd_qiov, 0); 181568d100e9SKevin Wolf qemu_co_mutex_lock(&s->lock); 181668d100e9SKevin Wolf if (ret < 0) { 18173fc48d09SFrediano Ziglio goto fail; 1818585f8587Sbellard } 18198336aafaSDaniel P. Berrange if (bs->encrypted) { 1820b25b387fSDaniel P. Berrange assert(s->crypto); 1821ecfe1863SKevin Wolf assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0); 1822ecfe1863SKevin Wolf assert((cur_bytes & (BDRV_SECTOR_SIZE - 1)) == 0); 1823b25b387fSDaniel P. Berrange if (qcrypto_block_decrypt(s->crypto, 18244652b8f3SDaniel P. Berrange (s->crypt_physical_offset ? 18254652b8f3SDaniel P. Berrange cluster_offset + offset_in_cluster : 18264609742aSDaniel P. Berrange offset), 1827446d306dSDaniel P. Berrange cluster_data, 1828b25b387fSDaniel P. Berrange cur_bytes, 1829c3a8fe33SAlberto Garcia NULL) < 0) { 1830f6fa64f6SDaniel P. Berrange ret = -EIO; 1831f6fa64f6SDaniel P. Berrange goto fail; 1832f6fa64f6SDaniel P. Berrange } 1833ecfe1863SKevin Wolf qemu_iovec_from_buf(qiov, bytes_done, cluster_data, cur_bytes); 1834171e3d6bSKevin Wolf } 183568d000a3SKevin Wolf break; 183668d000a3SKevin Wolf 183768d000a3SKevin Wolf default: 183868d000a3SKevin Wolf g_assert_not_reached(); 183968d000a3SKevin Wolf ret = -EIO; 184068d000a3SKevin Wolf goto fail; 1841faf575c1SFrediano Ziglio } 1842faf575c1SFrediano Ziglio 1843ecfe1863SKevin Wolf bytes -= cur_bytes; 1844ecfe1863SKevin Wolf offset += cur_bytes; 1845ecfe1863SKevin Wolf bytes_done += cur_bytes; 18465ebaa27eSFrediano Ziglio } 18473fc48d09SFrediano Ziglio ret = 0; 1848f141eafeSaliguori 18493fc48d09SFrediano Ziglio fail: 185068d100e9SKevin Wolf qemu_co_mutex_unlock(&s->lock); 185168d100e9SKevin Wolf 18523fc48d09SFrediano Ziglio qemu_iovec_destroy(&hd_qiov); 1853dea43a65SFrediano Ziglio qemu_vfree(cluster_data); 185468d100e9SKevin Wolf 185568d100e9SKevin Wolf return ret; 1856585f8587Sbellard } 1857585f8587Sbellard 1858ee22a9d8SAlberto Garcia /* Check if it's possible to merge a write request with the writing of 1859ee22a9d8SAlberto Garcia * the data from the COW regions */ 1860ee22a9d8SAlberto Garcia static bool merge_cow(uint64_t offset, unsigned bytes, 1861ee22a9d8SAlberto Garcia QEMUIOVector *hd_qiov, QCowL2Meta *l2meta) 1862ee22a9d8SAlberto Garcia { 1863ee22a9d8SAlberto Garcia QCowL2Meta *m; 1864ee22a9d8SAlberto Garcia 1865ee22a9d8SAlberto Garcia for (m = l2meta; m != NULL; m = m->next) { 1866ee22a9d8SAlberto Garcia /* If both COW regions are empty then there's nothing to merge */ 1867ee22a9d8SAlberto Garcia if (m->cow_start.nb_bytes == 0 && m->cow_end.nb_bytes == 0) { 1868ee22a9d8SAlberto Garcia continue; 1869ee22a9d8SAlberto Garcia } 1870ee22a9d8SAlberto Garcia 1871ee22a9d8SAlberto Garcia /* The data (middle) region must be immediately after the 1872ee22a9d8SAlberto Garcia * start region */ 1873ee22a9d8SAlberto Garcia if (l2meta_cow_start(m) + m->cow_start.nb_bytes != offset) { 1874ee22a9d8SAlberto Garcia continue; 1875ee22a9d8SAlberto Garcia } 1876ee22a9d8SAlberto Garcia 1877ee22a9d8SAlberto Garcia /* The end region must be immediately after the data (middle) 1878ee22a9d8SAlberto Garcia * region */ 1879ee22a9d8SAlberto Garcia if (m->offset + m->cow_end.offset != offset + bytes) { 1880ee22a9d8SAlberto Garcia continue; 1881ee22a9d8SAlberto Garcia } 1882ee22a9d8SAlberto Garcia 1883ee22a9d8SAlberto Garcia /* Make sure that adding both COW regions to the QEMUIOVector 1884ee22a9d8SAlberto Garcia * does not exceed IOV_MAX */ 1885ee22a9d8SAlberto Garcia if (hd_qiov->niov > IOV_MAX - 2) { 1886ee22a9d8SAlberto Garcia continue; 1887ee22a9d8SAlberto Garcia } 1888ee22a9d8SAlberto Garcia 1889ee22a9d8SAlberto Garcia m->data_qiov = hd_qiov; 1890ee22a9d8SAlberto Garcia return true; 1891ee22a9d8SAlberto Garcia } 1892ee22a9d8SAlberto Garcia 1893ee22a9d8SAlberto Garcia return false; 1894ee22a9d8SAlberto Garcia } 1895ee22a9d8SAlberto Garcia 1896d46a0bb2SKevin Wolf static coroutine_fn int qcow2_co_pwritev(BlockDriverState *bs, uint64_t offset, 1897d46a0bb2SKevin Wolf uint64_t bytes, QEMUIOVector *qiov, 1898d46a0bb2SKevin Wolf int flags) 1899585f8587Sbellard { 1900ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque; 1901d46a0bb2SKevin Wolf int offset_in_cluster; 190268d100e9SKevin Wolf int ret; 1903d46a0bb2SKevin Wolf unsigned int cur_bytes; /* number of sectors in current iteration */ 1904c2bdd990SFrediano Ziglio uint64_t cluster_offset; 19053fc48d09SFrediano Ziglio QEMUIOVector hd_qiov; 19063fc48d09SFrediano Ziglio uint64_t bytes_done = 0; 19073fc48d09SFrediano Ziglio uint8_t *cluster_data = NULL; 19088d2497c3SKevin Wolf QCowL2Meta *l2meta = NULL; 1909c2271403SFrediano Ziglio 1910d46a0bb2SKevin Wolf trace_qcow2_writev_start_req(qemu_coroutine_self(), offset, bytes); 19113cce16f4SKevin Wolf 19123fc48d09SFrediano Ziglio qemu_iovec_init(&hd_qiov, qiov->niov); 1913585f8587Sbellard 19143fc48d09SFrediano Ziglio s->cluster_cache_offset = -1; /* disable compressed cache */ 19153fc48d09SFrediano Ziglio 19163fc48d09SFrediano Ziglio qemu_co_mutex_lock(&s->lock); 19173fc48d09SFrediano Ziglio 1918d46a0bb2SKevin Wolf while (bytes != 0) { 19193fc48d09SFrediano Ziglio 1920f50f88b9SKevin Wolf l2meta = NULL; 1921cf5c1a23SKevin Wolf 19223cce16f4SKevin Wolf trace_qcow2_writev_start_part(qemu_coroutine_self()); 1923d46a0bb2SKevin Wolf offset_in_cluster = offset_into_cluster(s, offset); 1924d46a0bb2SKevin Wolf cur_bytes = MIN(bytes, INT_MAX); 1925d46a0bb2SKevin Wolf if (bs->encrypted) { 1926d46a0bb2SKevin Wolf cur_bytes = MIN(cur_bytes, 1927d46a0bb2SKevin Wolf QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size 1928d46a0bb2SKevin Wolf - offset_in_cluster); 19295ebaa27eSFrediano Ziglio } 1930095a9c58Saliguori 1931d46a0bb2SKevin Wolf ret = qcow2_alloc_cluster_offset(bs, offset, &cur_bytes, 1932d46a0bb2SKevin Wolf &cluster_offset, &l2meta); 1933148da7eaSKevin Wolf if (ret < 0) { 19343fc48d09SFrediano Ziglio goto fail; 1935148da7eaSKevin Wolf } 1936148da7eaSKevin Wolf 1937c2bdd990SFrediano Ziglio assert((cluster_offset & 511) == 0); 1938148da7eaSKevin Wolf 19393fc48d09SFrediano Ziglio qemu_iovec_reset(&hd_qiov); 1940d46a0bb2SKevin Wolf qemu_iovec_concat(&hd_qiov, qiov, bytes_done, cur_bytes); 19416f5f060bSKevin Wolf 19428336aafaSDaniel P. Berrange if (bs->encrypted) { 1943b25b387fSDaniel P. Berrange assert(s->crypto); 19443fc48d09SFrediano Ziglio if (!cluster_data) { 19459a4f4c31SKevin Wolf cluster_data = qemu_try_blockalign(bs->file->bs, 1946de82815dSKevin Wolf QCOW_MAX_CRYPT_CLUSTERS 1947de82815dSKevin Wolf * s->cluster_size); 1948de82815dSKevin Wolf if (cluster_data == NULL) { 1949de82815dSKevin Wolf ret = -ENOMEM; 1950de82815dSKevin Wolf goto fail; 1951de82815dSKevin Wolf } 1952585f8587Sbellard } 19536f5f060bSKevin Wolf 19543fc48d09SFrediano Ziglio assert(hd_qiov.size <= 19555ebaa27eSFrediano Ziglio QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size); 1956d5e6b161SMichael Tokarev qemu_iovec_to_buf(&hd_qiov, 0, cluster_data, hd_qiov.size); 19576f5f060bSKevin Wolf 19584652b8f3SDaniel P. Berrange if (qcrypto_block_encrypt(s->crypto, 19594652b8f3SDaniel P. Berrange (s->crypt_physical_offset ? 19604652b8f3SDaniel P. Berrange cluster_offset + offset_in_cluster : 19614609742aSDaniel P. Berrange offset), 1962446d306dSDaniel P. Berrange cluster_data, 1963c3a8fe33SAlberto Garcia cur_bytes, NULL) < 0) { 1964f6fa64f6SDaniel P. Berrange ret = -EIO; 1965f6fa64f6SDaniel P. Berrange goto fail; 1966f6fa64f6SDaniel P. Berrange } 19676f5f060bSKevin Wolf 19683fc48d09SFrediano Ziglio qemu_iovec_reset(&hd_qiov); 1969d46a0bb2SKevin Wolf qemu_iovec_add(&hd_qiov, cluster_data, cur_bytes); 1970585f8587Sbellard } 19716f5f060bSKevin Wolf 1972231bb267SMax Reitz ret = qcow2_pre_write_overlap_check(bs, 0, 1973d46a0bb2SKevin Wolf cluster_offset + offset_in_cluster, cur_bytes); 1974cf93980eSMax Reitz if (ret < 0) { 1975cf93980eSMax Reitz goto fail; 1976cf93980eSMax Reitz } 1977cf93980eSMax Reitz 1978ee22a9d8SAlberto Garcia /* If we need to do COW, check if it's possible to merge the 1979ee22a9d8SAlberto Garcia * writing of the guest data together with that of the COW regions. 1980ee22a9d8SAlberto Garcia * If it's not possible (or not necessary) then write the 1981ee22a9d8SAlberto Garcia * guest data now. */ 1982ee22a9d8SAlberto Garcia if (!merge_cow(offset, cur_bytes, &hd_qiov, l2meta)) { 198368d100e9SKevin Wolf qemu_co_mutex_unlock(&s->lock); 198467a7a0ebSKevin Wolf BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO); 19853cce16f4SKevin Wolf trace_qcow2_writev_data(qemu_coroutine_self(), 1986d46a0bb2SKevin Wolf cluster_offset + offset_in_cluster); 1987a03ef88fSKevin Wolf ret = bdrv_co_pwritev(bs->file, 1988d46a0bb2SKevin Wolf cluster_offset + offset_in_cluster, 1989d46a0bb2SKevin Wolf cur_bytes, &hd_qiov, 0); 199068d100e9SKevin Wolf qemu_co_mutex_lock(&s->lock); 199168d100e9SKevin Wolf if (ret < 0) { 19923fc48d09SFrediano Ziglio goto fail; 1993171e3d6bSKevin Wolf } 1994ee22a9d8SAlberto Garcia } 1995f141eafeSaliguori 199688c6588cSKevin Wolf while (l2meta != NULL) { 199788c6588cSKevin Wolf QCowL2Meta *next; 199888c6588cSKevin Wolf 1999cf5c1a23SKevin Wolf ret = qcow2_alloc_cluster_link_l2(bs, l2meta); 2000faf575c1SFrediano Ziglio if (ret < 0) { 20013fc48d09SFrediano Ziglio goto fail; 2002faf575c1SFrediano Ziglio } 2003faf575c1SFrediano Ziglio 20044e95314eSKevin Wolf /* Take the request off the list of running requests */ 20054e95314eSKevin Wolf if (l2meta->nb_clusters != 0) { 20064e95314eSKevin Wolf QLIST_REMOVE(l2meta, next_in_flight); 20074e95314eSKevin Wolf } 20084e95314eSKevin Wolf 20094e95314eSKevin Wolf qemu_co_queue_restart_all(&l2meta->dependent_requests); 20104e95314eSKevin Wolf 201188c6588cSKevin Wolf next = l2meta->next; 2012cf5c1a23SKevin Wolf g_free(l2meta); 201388c6588cSKevin Wolf l2meta = next; 2014f50f88b9SKevin Wolf } 20150fa9131aSKevin Wolf 2016d46a0bb2SKevin Wolf bytes -= cur_bytes; 2017d46a0bb2SKevin Wolf offset += cur_bytes; 2018d46a0bb2SKevin Wolf bytes_done += cur_bytes; 2019d46a0bb2SKevin Wolf trace_qcow2_writev_done_part(qemu_coroutine_self(), cur_bytes); 20205ebaa27eSFrediano Ziglio } 20213fc48d09SFrediano Ziglio ret = 0; 2022faf575c1SFrediano Ziglio 20233fc48d09SFrediano Ziglio fail: 202488c6588cSKevin Wolf while (l2meta != NULL) { 202588c6588cSKevin Wolf QCowL2Meta *next; 202688c6588cSKevin Wolf 20274e95314eSKevin Wolf if (l2meta->nb_clusters != 0) { 20284e95314eSKevin Wolf QLIST_REMOVE(l2meta, next_in_flight); 20294e95314eSKevin Wolf } 20304e95314eSKevin Wolf qemu_co_queue_restart_all(&l2meta->dependent_requests); 203188c6588cSKevin Wolf 203288c6588cSKevin Wolf next = l2meta->next; 2033cf5c1a23SKevin Wolf g_free(l2meta); 203488c6588cSKevin Wolf l2meta = next; 2035cf5c1a23SKevin Wolf } 20360fa9131aSKevin Wolf 2037a8c57408SPaolo Bonzini qemu_co_mutex_unlock(&s->lock); 2038a8c57408SPaolo Bonzini 20393fc48d09SFrediano Ziglio qemu_iovec_destroy(&hd_qiov); 2040dea43a65SFrediano Ziglio qemu_vfree(cluster_data); 20413cce16f4SKevin Wolf trace_qcow2_writev_done_req(qemu_coroutine_self(), ret); 204242496d62SKevin Wolf 204368d100e9SKevin Wolf return ret; 2044585f8587Sbellard } 2045585f8587Sbellard 2046ec6d8912SKevin Wolf static int qcow2_inactivate(BlockDriverState *bs) 2047ec6d8912SKevin Wolf { 2048ec6d8912SKevin Wolf BDRVQcow2State *s = bs->opaque; 2049ec6d8912SKevin Wolf int ret, result = 0; 20505f72826eSVladimir Sementsov-Ogievskiy Error *local_err = NULL; 2051ec6d8912SKevin Wolf 205283a8c775SPavel Butsykin qcow2_store_persistent_dirty_bitmaps(bs, &local_err); 205383a8c775SPavel Butsykin if (local_err != NULL) { 205483a8c775SPavel Butsykin result = -EINVAL; 205583a8c775SPavel Butsykin error_report_err(local_err); 205683a8c775SPavel Butsykin error_report("Persistent bitmaps are lost for node '%s'", 205783a8c775SPavel Butsykin bdrv_get_device_or_node_name(bs)); 205883a8c775SPavel Butsykin } 205983a8c775SPavel Butsykin 2060ec6d8912SKevin Wolf ret = qcow2_cache_flush(bs, s->l2_table_cache); 2061ec6d8912SKevin Wolf if (ret) { 2062ec6d8912SKevin Wolf result = ret; 2063ec6d8912SKevin Wolf error_report("Failed to flush the L2 table cache: %s", 2064ec6d8912SKevin Wolf strerror(-ret)); 2065ec6d8912SKevin Wolf } 2066ec6d8912SKevin Wolf 2067ec6d8912SKevin Wolf ret = qcow2_cache_flush(bs, s->refcount_block_cache); 2068ec6d8912SKevin Wolf if (ret) { 2069ec6d8912SKevin Wolf result = ret; 2070ec6d8912SKevin Wolf error_report("Failed to flush the refcount block cache: %s", 2071ec6d8912SKevin Wolf strerror(-ret)); 2072ec6d8912SKevin Wolf } 2073ec6d8912SKevin Wolf 2074ec6d8912SKevin Wolf if (result == 0) { 2075ec6d8912SKevin Wolf qcow2_mark_clean(bs); 2076ec6d8912SKevin Wolf } 2077ec6d8912SKevin Wolf 2078ec6d8912SKevin Wolf return result; 2079ec6d8912SKevin Wolf } 2080ec6d8912SKevin Wolf 20817c80ab3fSJes Sorensen static void qcow2_close(BlockDriverState *bs) 2082585f8587Sbellard { 2083ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque; 2084de82815dSKevin Wolf qemu_vfree(s->l1_table); 2085cf93980eSMax Reitz /* else pre-write overlap checks in cache_destroy may crash */ 2086cf93980eSMax Reitz s->l1_table = NULL; 208729c1a730SKevin Wolf 2088140fd5a6SKevin Wolf if (!(s->flags & BDRV_O_INACTIVE)) { 2089ec6d8912SKevin Wolf qcow2_inactivate(bs); 20903b5e14c7SMax Reitz } 2091c61d0004SStefan Hajnoczi 2092279621c0SAlberto Garcia cache_clean_timer_del(bs); 2093e64d4072SAlberto Garcia qcow2_cache_destroy(s->l2_table_cache); 2094e64d4072SAlberto Garcia qcow2_cache_destroy(s->refcount_block_cache); 209529c1a730SKevin Wolf 2096b25b387fSDaniel P. Berrange qcrypto_block_free(s->crypto); 2097b25b387fSDaniel P. Berrange s->crypto = NULL; 2098f6fa64f6SDaniel P. Berrange 20996744cbabSKevin Wolf g_free(s->unknown_header_fields); 210075bab85cSKevin Wolf cleanup_unknown_header_ext(bs); 21016744cbabSKevin Wolf 2102e4603fe1SKevin Wolf g_free(s->image_backing_file); 2103e4603fe1SKevin Wolf g_free(s->image_backing_format); 2104e4603fe1SKevin Wolf 21057267c094SAnthony Liguori g_free(s->cluster_cache); 2106dea43a65SFrediano Ziglio qemu_vfree(s->cluster_data); 2107ed6ccf0fSKevin Wolf qcow2_refcount_close(bs); 210828c1202bSLi Zhi Hui qcow2_free_snapshots(bs); 2109585f8587Sbellard } 2110585f8587Sbellard 21115a8a30dbSKevin Wolf static void qcow2_invalidate_cache(BlockDriverState *bs, Error **errp) 211206d9260fSAnthony Liguori { 2113ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque; 211406d9260fSAnthony Liguori int flags = s->flags; 2115b25b387fSDaniel P. Berrange QCryptoBlock *crypto = NULL; 2116acdfb480SKevin Wolf QDict *options; 21175a8a30dbSKevin Wolf Error *local_err = NULL; 21185a8a30dbSKevin Wolf int ret; 211906d9260fSAnthony Liguori 212006d9260fSAnthony Liguori /* 212106d9260fSAnthony Liguori * Backing files are read-only which makes all of their metadata immutable, 212206d9260fSAnthony Liguori * that means we don't have to worry about reopening them here. 212306d9260fSAnthony Liguori */ 212406d9260fSAnthony Liguori 2125b25b387fSDaniel P. Berrange crypto = s->crypto; 2126b25b387fSDaniel P. Berrange s->crypto = NULL; 212706d9260fSAnthony Liguori 212806d9260fSAnthony Liguori qcow2_close(bs); 212906d9260fSAnthony Liguori 2130ff99129aSKevin Wolf memset(s, 0, sizeof(BDRVQcow2State)); 2131d475e5acSKevin Wolf options = qdict_clone_shallow(bs->options); 21325a8a30dbSKevin Wolf 2133140fd5a6SKevin Wolf flags &= ~BDRV_O_INACTIVE; 21344e4bf5c4SKevin Wolf ret = qcow2_do_open(bs, options, flags, &local_err); 2135a1904e48SMarkus Armbruster QDECREF(options); 21365a8a30dbSKevin Wolf if (local_err) { 2137e43bfd9cSMarkus Armbruster error_propagate(errp, local_err); 2138e43bfd9cSMarkus Armbruster error_prepend(errp, "Could not reopen qcow2 layer: "); 2139191fb11bSKevin Wolf bs->drv = NULL; 21405a8a30dbSKevin Wolf return; 21415a8a30dbSKevin Wolf } else if (ret < 0) { 21425a8a30dbSKevin Wolf error_setg_errno(errp, -ret, "Could not reopen qcow2 layer"); 2143191fb11bSKevin Wolf bs->drv = NULL; 21445a8a30dbSKevin Wolf return; 21455a8a30dbSKevin Wolf } 2146acdfb480SKevin Wolf 2147b25b387fSDaniel P. Berrange s->crypto = crypto; 214806d9260fSAnthony Liguori } 214906d9260fSAnthony Liguori 2150e24e49e6SKevin Wolf static size_t header_ext_add(char *buf, uint32_t magic, const void *s, 2151e24e49e6SKevin Wolf size_t len, size_t buflen) 2152756e6736SKevin Wolf { 2153e24e49e6SKevin Wolf QCowExtension *ext_backing_fmt = (QCowExtension*) buf; 2154e24e49e6SKevin Wolf size_t ext_len = sizeof(QCowExtension) + ((len + 7) & ~7); 2155756e6736SKevin Wolf 2156e24e49e6SKevin Wolf if (buflen < ext_len) { 2157756e6736SKevin Wolf return -ENOSPC; 2158756e6736SKevin Wolf } 2159756e6736SKevin Wolf 2160e24e49e6SKevin Wolf *ext_backing_fmt = (QCowExtension) { 2161e24e49e6SKevin Wolf .magic = cpu_to_be32(magic), 2162e24e49e6SKevin Wolf .len = cpu_to_be32(len), 2163e24e49e6SKevin Wolf }; 21640647d47cSStefan Hajnoczi 21650647d47cSStefan Hajnoczi if (len) { 2166e24e49e6SKevin Wolf memcpy(buf + sizeof(QCowExtension), s, len); 21670647d47cSStefan Hajnoczi } 2168756e6736SKevin Wolf 2169e24e49e6SKevin Wolf return ext_len; 2170756e6736SKevin Wolf } 2171756e6736SKevin Wolf 2172e24e49e6SKevin Wolf /* 2173e24e49e6SKevin Wolf * Updates the qcow2 header, including the variable length parts of it, i.e. 2174e24e49e6SKevin Wolf * the backing file name and all extensions. qcow2 was not designed to allow 2175e24e49e6SKevin Wolf * such changes, so if we run out of space (we can only use the first cluster) 2176e24e49e6SKevin Wolf * this function may fail. 2177e24e49e6SKevin Wolf * 2178e24e49e6SKevin Wolf * Returns 0 on success, -errno in error cases. 2179e24e49e6SKevin Wolf */ 2180e24e49e6SKevin Wolf int qcow2_update_header(BlockDriverState *bs) 2181e24e49e6SKevin Wolf { 2182ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque; 2183e24e49e6SKevin Wolf QCowHeader *header; 2184e24e49e6SKevin Wolf char *buf; 2185e24e49e6SKevin Wolf size_t buflen = s->cluster_size; 2186e24e49e6SKevin Wolf int ret; 2187e24e49e6SKevin Wolf uint64_t total_size; 2188e24e49e6SKevin Wolf uint32_t refcount_table_clusters; 21896744cbabSKevin Wolf size_t header_length; 219075bab85cSKevin Wolf Qcow2UnknownHeaderExtension *uext; 2191e24e49e6SKevin Wolf 2192e24e49e6SKevin Wolf buf = qemu_blockalign(bs, buflen); 2193e24e49e6SKevin Wolf 2194e24e49e6SKevin Wolf /* Header structure */ 2195e24e49e6SKevin Wolf header = (QCowHeader*) buf; 2196e24e49e6SKevin Wolf 2197e24e49e6SKevin Wolf if (buflen < sizeof(*header)) { 2198e24e49e6SKevin Wolf ret = -ENOSPC; 2199e24e49e6SKevin Wolf goto fail; 2200756e6736SKevin Wolf } 2201756e6736SKevin Wolf 22026744cbabSKevin Wolf header_length = sizeof(*header) + s->unknown_header_fields_size; 2203e24e49e6SKevin Wolf total_size = bs->total_sectors * BDRV_SECTOR_SIZE; 2204e24e49e6SKevin Wolf refcount_table_clusters = s->refcount_table_size >> (s->cluster_bits - 3); 2205e24e49e6SKevin Wolf 2206e24e49e6SKevin Wolf *header = (QCowHeader) { 22076744cbabSKevin Wolf /* Version 2 fields */ 2208e24e49e6SKevin Wolf .magic = cpu_to_be32(QCOW_MAGIC), 22096744cbabSKevin Wolf .version = cpu_to_be32(s->qcow_version), 2210e24e49e6SKevin Wolf .backing_file_offset = 0, 2211e24e49e6SKevin Wolf .backing_file_size = 0, 2212e24e49e6SKevin Wolf .cluster_bits = cpu_to_be32(s->cluster_bits), 2213e24e49e6SKevin Wolf .size = cpu_to_be64(total_size), 2214e24e49e6SKevin Wolf .crypt_method = cpu_to_be32(s->crypt_method_header), 2215e24e49e6SKevin Wolf .l1_size = cpu_to_be32(s->l1_size), 2216e24e49e6SKevin Wolf .l1_table_offset = cpu_to_be64(s->l1_table_offset), 2217e24e49e6SKevin Wolf .refcount_table_offset = cpu_to_be64(s->refcount_table_offset), 2218e24e49e6SKevin Wolf .refcount_table_clusters = cpu_to_be32(refcount_table_clusters), 2219e24e49e6SKevin Wolf .nb_snapshots = cpu_to_be32(s->nb_snapshots), 2220e24e49e6SKevin Wolf .snapshots_offset = cpu_to_be64(s->snapshots_offset), 22216744cbabSKevin Wolf 22226744cbabSKevin Wolf /* Version 3 fields */ 22236744cbabSKevin Wolf .incompatible_features = cpu_to_be64(s->incompatible_features), 22246744cbabSKevin Wolf .compatible_features = cpu_to_be64(s->compatible_features), 22256744cbabSKevin Wolf .autoclear_features = cpu_to_be64(s->autoclear_features), 2226b6481f37SMax Reitz .refcount_order = cpu_to_be32(s->refcount_order), 22276744cbabSKevin Wolf .header_length = cpu_to_be32(header_length), 2228e24e49e6SKevin Wolf }; 2229e24e49e6SKevin Wolf 22306744cbabSKevin Wolf /* For older versions, write a shorter header */ 22316744cbabSKevin Wolf switch (s->qcow_version) { 22326744cbabSKevin Wolf case 2: 22336744cbabSKevin Wolf ret = offsetof(QCowHeader, incompatible_features); 22346744cbabSKevin Wolf break; 22356744cbabSKevin Wolf case 3: 22366744cbabSKevin Wolf ret = sizeof(*header); 22376744cbabSKevin Wolf break; 22386744cbabSKevin Wolf default: 2239b6c14762SJim Meyering ret = -EINVAL; 2240b6c14762SJim Meyering goto fail; 22416744cbabSKevin Wolf } 22426744cbabSKevin Wolf 22436744cbabSKevin Wolf buf += ret; 22446744cbabSKevin Wolf buflen -= ret; 22456744cbabSKevin Wolf memset(buf, 0, buflen); 22466744cbabSKevin Wolf 22476744cbabSKevin Wolf /* Preserve any unknown field in the header */ 22486744cbabSKevin Wolf if (s->unknown_header_fields_size) { 22496744cbabSKevin Wolf if (buflen < s->unknown_header_fields_size) { 22506744cbabSKevin Wolf ret = -ENOSPC; 22516744cbabSKevin Wolf goto fail; 22526744cbabSKevin Wolf } 22536744cbabSKevin Wolf 22546744cbabSKevin Wolf memcpy(buf, s->unknown_header_fields, s->unknown_header_fields_size); 22556744cbabSKevin Wolf buf += s->unknown_header_fields_size; 22566744cbabSKevin Wolf buflen -= s->unknown_header_fields_size; 22576744cbabSKevin Wolf } 2258e24e49e6SKevin Wolf 2259e24e49e6SKevin Wolf /* Backing file format header extension */ 2260e4603fe1SKevin Wolf if (s->image_backing_format) { 2261e24e49e6SKevin Wolf ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BACKING_FORMAT, 2262e4603fe1SKevin Wolf s->image_backing_format, 2263e4603fe1SKevin Wolf strlen(s->image_backing_format), 2264e24e49e6SKevin Wolf buflen); 2265756e6736SKevin Wolf if (ret < 0) { 2266756e6736SKevin Wolf goto fail; 2267756e6736SKevin Wolf } 2268756e6736SKevin Wolf 2269e24e49e6SKevin Wolf buf += ret; 2270e24e49e6SKevin Wolf buflen -= ret; 2271e24e49e6SKevin Wolf } 2272756e6736SKevin Wolf 22734652b8f3SDaniel P. Berrange /* Full disk encryption header pointer extension */ 22744652b8f3SDaniel P. Berrange if (s->crypto_header.offset != 0) { 22754652b8f3SDaniel P. Berrange cpu_to_be64s(&s->crypto_header.offset); 22764652b8f3SDaniel P. Berrange cpu_to_be64s(&s->crypto_header.length); 22774652b8f3SDaniel P. Berrange ret = header_ext_add(buf, QCOW2_EXT_MAGIC_CRYPTO_HEADER, 22784652b8f3SDaniel P. Berrange &s->crypto_header, sizeof(s->crypto_header), 22794652b8f3SDaniel P. Berrange buflen); 22804652b8f3SDaniel P. Berrange be64_to_cpus(&s->crypto_header.offset); 22814652b8f3SDaniel P. Berrange be64_to_cpus(&s->crypto_header.length); 22824652b8f3SDaniel P. Berrange if (ret < 0) { 22834652b8f3SDaniel P. Berrange goto fail; 22844652b8f3SDaniel P. Berrange } 22854652b8f3SDaniel P. Berrange buf += ret; 22864652b8f3SDaniel P. Berrange buflen -= ret; 22874652b8f3SDaniel P. Berrange } 22884652b8f3SDaniel P. Berrange 2289cfcc4c62SKevin Wolf /* Feature table */ 22901a4828c7SKevin Wolf if (s->qcow_version >= 3) { 2291cfcc4c62SKevin Wolf Qcow2Feature features[] = { 2292c61d0004SStefan Hajnoczi { 2293c61d0004SStefan Hajnoczi .type = QCOW2_FEAT_TYPE_INCOMPATIBLE, 2294c61d0004SStefan Hajnoczi .bit = QCOW2_INCOMPAT_DIRTY_BITNR, 2295c61d0004SStefan Hajnoczi .name = "dirty bit", 2296c61d0004SStefan Hajnoczi }, 2297bfe8043eSStefan Hajnoczi { 229869c98726SMax Reitz .type = QCOW2_FEAT_TYPE_INCOMPATIBLE, 229969c98726SMax Reitz .bit = QCOW2_INCOMPAT_CORRUPT_BITNR, 230069c98726SMax Reitz .name = "corrupt bit", 230169c98726SMax Reitz }, 230269c98726SMax Reitz { 2303bfe8043eSStefan Hajnoczi .type = QCOW2_FEAT_TYPE_COMPATIBLE, 2304bfe8043eSStefan Hajnoczi .bit = QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR, 2305bfe8043eSStefan Hajnoczi .name = "lazy refcounts", 2306bfe8043eSStefan Hajnoczi }, 2307cfcc4c62SKevin Wolf }; 2308cfcc4c62SKevin Wolf 2309cfcc4c62SKevin Wolf ret = header_ext_add(buf, QCOW2_EXT_MAGIC_FEATURE_TABLE, 2310cfcc4c62SKevin Wolf features, sizeof(features), buflen); 2311cfcc4c62SKevin Wolf if (ret < 0) { 2312cfcc4c62SKevin Wolf goto fail; 2313cfcc4c62SKevin Wolf } 2314cfcc4c62SKevin Wolf buf += ret; 2315cfcc4c62SKevin Wolf buflen -= ret; 23161a4828c7SKevin Wolf } 2317cfcc4c62SKevin Wolf 231888ddffaeSVladimir Sementsov-Ogievskiy /* Bitmap extension */ 231988ddffaeSVladimir Sementsov-Ogievskiy if (s->nb_bitmaps > 0) { 232088ddffaeSVladimir Sementsov-Ogievskiy Qcow2BitmapHeaderExt bitmaps_header = { 232188ddffaeSVladimir Sementsov-Ogievskiy .nb_bitmaps = cpu_to_be32(s->nb_bitmaps), 232288ddffaeSVladimir Sementsov-Ogievskiy .bitmap_directory_size = 232388ddffaeSVladimir Sementsov-Ogievskiy cpu_to_be64(s->bitmap_directory_size), 232488ddffaeSVladimir Sementsov-Ogievskiy .bitmap_directory_offset = 232588ddffaeSVladimir Sementsov-Ogievskiy cpu_to_be64(s->bitmap_directory_offset) 232688ddffaeSVladimir Sementsov-Ogievskiy }; 232788ddffaeSVladimir Sementsov-Ogievskiy ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BITMAPS, 232888ddffaeSVladimir Sementsov-Ogievskiy &bitmaps_header, sizeof(bitmaps_header), 232988ddffaeSVladimir Sementsov-Ogievskiy buflen); 233088ddffaeSVladimir Sementsov-Ogievskiy if (ret < 0) { 233188ddffaeSVladimir Sementsov-Ogievskiy goto fail; 233288ddffaeSVladimir Sementsov-Ogievskiy } 233388ddffaeSVladimir Sementsov-Ogievskiy buf += ret; 233488ddffaeSVladimir Sementsov-Ogievskiy buflen -= ret; 233588ddffaeSVladimir Sementsov-Ogievskiy } 233688ddffaeSVladimir Sementsov-Ogievskiy 233775bab85cSKevin Wolf /* Keep unknown header extensions */ 233875bab85cSKevin Wolf QLIST_FOREACH(uext, &s->unknown_header_ext, next) { 233975bab85cSKevin Wolf ret = header_ext_add(buf, uext->magic, uext->data, uext->len, buflen); 234075bab85cSKevin Wolf if (ret < 0) { 234175bab85cSKevin Wolf goto fail; 234275bab85cSKevin Wolf } 234375bab85cSKevin Wolf 234475bab85cSKevin Wolf buf += ret; 234575bab85cSKevin Wolf buflen -= ret; 234675bab85cSKevin Wolf } 234775bab85cSKevin Wolf 2348e24e49e6SKevin Wolf /* End of header extensions */ 2349e24e49e6SKevin Wolf ret = header_ext_add(buf, QCOW2_EXT_MAGIC_END, NULL, 0, buflen); 2350756e6736SKevin Wolf if (ret < 0) { 2351756e6736SKevin Wolf goto fail; 2352756e6736SKevin Wolf } 2353756e6736SKevin Wolf 2354e24e49e6SKevin Wolf buf += ret; 2355e24e49e6SKevin Wolf buflen -= ret; 2356e24e49e6SKevin Wolf 2357e24e49e6SKevin Wolf /* Backing file name */ 2358e4603fe1SKevin Wolf if (s->image_backing_file) { 2359e4603fe1SKevin Wolf size_t backing_file_len = strlen(s->image_backing_file); 2360e24e49e6SKevin Wolf 2361e24e49e6SKevin Wolf if (buflen < backing_file_len) { 2362e24e49e6SKevin Wolf ret = -ENOSPC; 2363e24e49e6SKevin Wolf goto fail; 2364e24e49e6SKevin Wolf } 2365e24e49e6SKevin Wolf 236600ea1881SJim Meyering /* Using strncpy is ok here, since buf is not NUL-terminated. */ 2367e4603fe1SKevin Wolf strncpy(buf, s->image_backing_file, buflen); 2368e24e49e6SKevin Wolf 2369e24e49e6SKevin Wolf header->backing_file_offset = cpu_to_be64(buf - ((char*) header)); 2370e24e49e6SKevin Wolf header->backing_file_size = cpu_to_be32(backing_file_len); 2371e24e49e6SKevin Wolf } 2372e24e49e6SKevin Wolf 2373e24e49e6SKevin Wolf /* Write the new header */ 2374d9ca2ea2SKevin Wolf ret = bdrv_pwrite(bs->file, 0, header, s->cluster_size); 2375756e6736SKevin Wolf if (ret < 0) { 2376756e6736SKevin Wolf goto fail; 2377756e6736SKevin Wolf } 2378756e6736SKevin Wolf 2379756e6736SKevin Wolf ret = 0; 2380756e6736SKevin Wolf fail: 2381e24e49e6SKevin Wolf qemu_vfree(header); 2382756e6736SKevin Wolf return ret; 2383756e6736SKevin Wolf } 2384756e6736SKevin Wolf 2385756e6736SKevin Wolf static int qcow2_change_backing_file(BlockDriverState *bs, 2386756e6736SKevin Wolf const char *backing_file, const char *backing_fmt) 2387756e6736SKevin Wolf { 2388ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque; 2389e4603fe1SKevin Wolf 23904e876bcfSMax Reitz if (backing_file && strlen(backing_file) > 1023) { 23914e876bcfSMax Reitz return -EINVAL; 23924e876bcfSMax Reitz } 23934e876bcfSMax Reitz 2394e24e49e6SKevin Wolf pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: ""); 2395e24e49e6SKevin Wolf pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: ""); 2396e24e49e6SKevin Wolf 2397e4603fe1SKevin Wolf g_free(s->image_backing_file); 2398e4603fe1SKevin Wolf g_free(s->image_backing_format); 2399e4603fe1SKevin Wolf 2400e4603fe1SKevin Wolf s->image_backing_file = backing_file ? g_strdup(bs->backing_file) : NULL; 2401e4603fe1SKevin Wolf s->image_backing_format = backing_fmt ? g_strdup(bs->backing_format) : NULL; 2402e4603fe1SKevin Wolf 2403e24e49e6SKevin Wolf return qcow2_update_header(bs); 2404756e6736SKevin Wolf } 2405756e6736SKevin Wolf 24064652b8f3SDaniel P. Berrange static int qcow2_crypt_method_from_format(const char *encryptfmt) 24074652b8f3SDaniel P. Berrange { 24084652b8f3SDaniel P. Berrange if (g_str_equal(encryptfmt, "luks")) { 24094652b8f3SDaniel P. Berrange return QCOW_CRYPT_LUKS; 24104652b8f3SDaniel P. Berrange } else if (g_str_equal(encryptfmt, "aes")) { 24114652b8f3SDaniel P. Berrange return QCOW_CRYPT_AES; 24124652b8f3SDaniel P. Berrange } else { 24134652b8f3SDaniel P. Berrange return -EINVAL; 24144652b8f3SDaniel P. Berrange } 24154652b8f3SDaniel P. Berrange } 2416b25b387fSDaniel P. Berrange 2417b25b387fSDaniel P. Berrange static int qcow2_set_up_encryption(BlockDriverState *bs, const char *encryptfmt, 2418b25b387fSDaniel P. Berrange QemuOpts *opts, Error **errp) 2419b25b387fSDaniel P. Berrange { 2420b25b387fSDaniel P. Berrange BDRVQcow2State *s = bs->opaque; 2421b25b387fSDaniel P. Berrange QCryptoBlockCreateOptions *cryptoopts = NULL; 2422b25b387fSDaniel P. Berrange QCryptoBlock *crypto = NULL; 2423b25b387fSDaniel P. Berrange int ret = -EINVAL; 2424b25b387fSDaniel P. Berrange QDict *options, *encryptopts; 24254652b8f3SDaniel P. Berrange int fmt; 2426b25b387fSDaniel P. Berrange 2427b25b387fSDaniel P. Berrange options = qemu_opts_to_qdict(opts, NULL); 2428b25b387fSDaniel P. Berrange qdict_extract_subqdict(options, &encryptopts, "encrypt."); 2429b25b387fSDaniel P. Berrange QDECREF(options); 2430b25b387fSDaniel P. Berrange 24314652b8f3SDaniel P. Berrange fmt = qcow2_crypt_method_from_format(encryptfmt); 24324652b8f3SDaniel P. Berrange 24334652b8f3SDaniel P. Berrange switch (fmt) { 24344652b8f3SDaniel P. Berrange case QCOW_CRYPT_LUKS: 24354652b8f3SDaniel P. Berrange cryptoopts = block_crypto_create_opts_init( 24364652b8f3SDaniel P. Berrange Q_CRYPTO_BLOCK_FORMAT_LUKS, encryptopts, errp); 24374652b8f3SDaniel P. Berrange break; 24384652b8f3SDaniel P. Berrange case QCOW_CRYPT_AES: 2439b25b387fSDaniel P. Berrange cryptoopts = block_crypto_create_opts_init( 2440b25b387fSDaniel P. Berrange Q_CRYPTO_BLOCK_FORMAT_QCOW, encryptopts, errp); 24414652b8f3SDaniel P. Berrange break; 24424652b8f3SDaniel P. Berrange default: 24434652b8f3SDaniel P. Berrange error_setg(errp, "Unknown encryption format '%s'", encryptfmt); 24444652b8f3SDaniel P. Berrange break; 24454652b8f3SDaniel P. Berrange } 2446b25b387fSDaniel P. Berrange if (!cryptoopts) { 2447b25b387fSDaniel P. Berrange ret = -EINVAL; 2448b25b387fSDaniel P. Berrange goto out; 2449b25b387fSDaniel P. Berrange } 24504652b8f3SDaniel P. Berrange s->crypt_method_header = fmt; 2451b25b387fSDaniel P. Berrange 24521cd9a787SDaniel P. Berrange crypto = qcrypto_block_create(cryptoopts, "encrypt.", 24534652b8f3SDaniel P. Berrange qcow2_crypto_hdr_init_func, 24544652b8f3SDaniel P. Berrange qcow2_crypto_hdr_write_func, 2455b25b387fSDaniel P. Berrange bs, errp); 2456b25b387fSDaniel P. Berrange if (!crypto) { 2457b25b387fSDaniel P. Berrange ret = -EINVAL; 2458b25b387fSDaniel P. Berrange goto out; 2459b25b387fSDaniel P. Berrange } 2460b25b387fSDaniel P. Berrange 2461b25b387fSDaniel P. Berrange ret = qcow2_update_header(bs); 2462b25b387fSDaniel P. Berrange if (ret < 0) { 2463b25b387fSDaniel P. Berrange error_setg_errno(errp, -ret, "Could not write encryption header"); 2464b25b387fSDaniel P. Berrange goto out; 2465b25b387fSDaniel P. Berrange } 2466b25b387fSDaniel P. Berrange 2467b25b387fSDaniel P. Berrange out: 2468b25b387fSDaniel P. Berrange QDECREF(encryptopts); 2469b25b387fSDaniel P. Berrange qcrypto_block_free(crypto); 2470b25b387fSDaniel P. Berrange qapi_free_QCryptoBlockCreateOptions(cryptoopts); 2471b25b387fSDaniel P. Berrange return ret; 2472b25b387fSDaniel P. Berrange } 2473b25b387fSDaniel P. Berrange 2474b25b387fSDaniel P. Berrange 2475572b07beSMax Reitz typedef struct PreallocCo { 2476572b07beSMax Reitz BlockDriverState *bs; 2477572b07beSMax Reitz uint64_t offset; 2478572b07beSMax Reitz uint64_t new_length; 2479572b07beSMax Reitz 2480572b07beSMax Reitz int ret; 2481572b07beSMax Reitz } PreallocCo; 2482572b07beSMax Reitz 24837bc45dc1SMax Reitz /** 24847bc45dc1SMax Reitz * Preallocates metadata structures for data clusters between @offset (in the 24857bc45dc1SMax Reitz * guest disk) and @new_length (which is thus generally the new guest disk 24867bc45dc1SMax Reitz * size). 24877bc45dc1SMax Reitz * 24887bc45dc1SMax Reitz * Returns: 0 on success, -errno on failure. 24897bc45dc1SMax Reitz */ 2490572b07beSMax Reitz static void coroutine_fn preallocate_co(void *opaque) 2491a35e1c17SKevin Wolf { 2492572b07beSMax Reitz PreallocCo *params = opaque; 2493572b07beSMax Reitz BlockDriverState *bs = params->bs; 2494572b07beSMax Reitz uint64_t offset = params->offset; 2495572b07beSMax Reitz uint64_t new_length = params->new_length; 2496652fecd0SMax Reitz BDRVQcow2State *s = bs->opaque; 2497d46a0bb2SKevin Wolf uint64_t bytes; 2498060bee89SKevin Wolf uint64_t host_offset = 0; 2499d46a0bb2SKevin Wolf unsigned int cur_bytes; 2500148da7eaSKevin Wolf int ret; 2501f50f88b9SKevin Wolf QCowL2Meta *meta; 2502a35e1c17SKevin Wolf 2503652fecd0SMax Reitz qemu_co_mutex_lock(&s->lock); 2504652fecd0SMax Reitz 25057bc45dc1SMax Reitz assert(offset <= new_length); 25067bc45dc1SMax Reitz bytes = new_length - offset; 2507a35e1c17SKevin Wolf 2508d46a0bb2SKevin Wolf while (bytes) { 2509d46a0bb2SKevin Wolf cur_bytes = MIN(bytes, INT_MAX); 2510d46a0bb2SKevin Wolf ret = qcow2_alloc_cluster_offset(bs, offset, &cur_bytes, 2511060bee89SKevin Wolf &host_offset, &meta); 2512148da7eaSKevin Wolf if (ret < 0) { 2513652fecd0SMax Reitz goto done; 2514a35e1c17SKevin Wolf } 2515a35e1c17SKevin Wolf 2516c792707fSStefan Hajnoczi while (meta) { 2517c792707fSStefan Hajnoczi QCowL2Meta *next = meta->next; 2518c792707fSStefan Hajnoczi 2519f50f88b9SKevin Wolf ret = qcow2_alloc_cluster_link_l2(bs, meta); 252019dbcbf7SKevin Wolf if (ret < 0) { 25217c2bbf4aSHu Tao qcow2_free_any_clusters(bs, meta->alloc_offset, 25227c2bbf4aSHu Tao meta->nb_clusters, QCOW2_DISCARD_NEVER); 2523652fecd0SMax Reitz goto done; 2524a35e1c17SKevin Wolf } 2525a35e1c17SKevin Wolf 25267c2bbf4aSHu Tao /* There are no dependent requests, but we need to remove our 25277c2bbf4aSHu Tao * request from the list of in-flight requests */ 25284e95314eSKevin Wolf QLIST_REMOVE(meta, next_in_flight); 2529c792707fSStefan Hajnoczi 2530c792707fSStefan Hajnoczi g_free(meta); 2531c792707fSStefan Hajnoczi meta = next; 2532f50f88b9SKevin Wolf } 2533f214978aSKevin Wolf 2534a35e1c17SKevin Wolf /* TODO Preallocate data if requested */ 2535a35e1c17SKevin Wolf 2536d46a0bb2SKevin Wolf bytes -= cur_bytes; 2537d46a0bb2SKevin Wolf offset += cur_bytes; 2538a35e1c17SKevin Wolf } 2539a35e1c17SKevin Wolf 2540a35e1c17SKevin Wolf /* 2541a35e1c17SKevin Wolf * It is expected that the image file is large enough to actually contain 2542a35e1c17SKevin Wolf * all of the allocated clusters (otherwise we get failing reads after 2543a35e1c17SKevin Wolf * EOF). Extend the image to the last allocated sector. 2544a35e1c17SKevin Wolf */ 2545060bee89SKevin Wolf if (host_offset != 0) { 2546d46a0bb2SKevin Wolf uint8_t data = 0; 2547d9ca2ea2SKevin Wolf ret = bdrv_pwrite(bs->file, (host_offset + cur_bytes) - 1, 2548d46a0bb2SKevin Wolf &data, 1); 254919dbcbf7SKevin Wolf if (ret < 0) { 2550652fecd0SMax Reitz goto done; 255119dbcbf7SKevin Wolf } 2552a35e1c17SKevin Wolf } 2553a35e1c17SKevin Wolf 2554652fecd0SMax Reitz ret = 0; 2555652fecd0SMax Reitz 2556652fecd0SMax Reitz done: 2557652fecd0SMax Reitz qemu_co_mutex_unlock(&s->lock); 2558572b07beSMax Reitz params->ret = ret; 2559652fecd0SMax Reitz } 2560572b07beSMax Reitz 2561572b07beSMax Reitz static int preallocate(BlockDriverState *bs, 2562572b07beSMax Reitz uint64_t offset, uint64_t new_length) 2563572b07beSMax Reitz { 2564572b07beSMax Reitz PreallocCo params = { 2565572b07beSMax Reitz .bs = bs, 2566572b07beSMax Reitz .offset = offset, 2567572b07beSMax Reitz .new_length = new_length, 2568572b07beSMax Reitz .ret = -EINPROGRESS, 2569572b07beSMax Reitz }; 2570572b07beSMax Reitz 2571572b07beSMax Reitz if (qemu_in_coroutine()) { 2572572b07beSMax Reitz preallocate_co(¶ms); 2573572b07beSMax Reitz } else { 2574572b07beSMax Reitz Coroutine *co = qemu_coroutine_create(preallocate_co, ¶ms); 2575572b07beSMax Reitz bdrv_coroutine_enter(bs, co); 2576572b07beSMax Reitz BDRV_POLL_WHILE(bs, params.ret == -EINPROGRESS); 2577572b07beSMax Reitz } 2578572b07beSMax Reitz return params.ret; 2579a35e1c17SKevin Wolf } 2580a35e1c17SKevin Wolf 25817c5bcc42SStefan Hajnoczi /* qcow2_refcount_metadata_size: 25827c5bcc42SStefan Hajnoczi * @clusters: number of clusters to refcount (including data and L1/L2 tables) 25837c5bcc42SStefan Hajnoczi * @cluster_size: size of a cluster, in bytes 25847c5bcc42SStefan Hajnoczi * @refcount_order: refcount bits power-of-2 exponent 258512cc30a8SMax Reitz * @generous_increase: allow for the refcount table to be 1.5x as large as it 258612cc30a8SMax Reitz * needs to be 25877c5bcc42SStefan Hajnoczi * 25887c5bcc42SStefan Hajnoczi * Returns: Number of bytes required for refcount blocks and table metadata. 25897c5bcc42SStefan Hajnoczi */ 259012cc30a8SMax Reitz int64_t qcow2_refcount_metadata_size(int64_t clusters, size_t cluster_size, 259112cc30a8SMax Reitz int refcount_order, bool generous_increase, 259212cc30a8SMax Reitz uint64_t *refblock_count) 25937c5bcc42SStefan Hajnoczi { 25947c5bcc42SStefan Hajnoczi /* 25957c5bcc42SStefan Hajnoczi * Every host cluster is reference-counted, including metadata (even 25967c5bcc42SStefan Hajnoczi * refcount metadata is recursively included). 25977c5bcc42SStefan Hajnoczi * 25987c5bcc42SStefan Hajnoczi * An accurate formula for the size of refcount metadata size is difficult 25997c5bcc42SStefan Hajnoczi * to derive. An easier method of calculation is finding the fixed point 26007c5bcc42SStefan Hajnoczi * where no further refcount blocks or table clusters are required to 26017c5bcc42SStefan Hajnoczi * reference count every cluster. 26027c5bcc42SStefan Hajnoczi */ 26037c5bcc42SStefan Hajnoczi int64_t blocks_per_table_cluster = cluster_size / sizeof(uint64_t); 26047c5bcc42SStefan Hajnoczi int64_t refcounts_per_block = cluster_size * 8 / (1 << refcount_order); 26057c5bcc42SStefan Hajnoczi int64_t table = 0; /* number of refcount table clusters */ 26067c5bcc42SStefan Hajnoczi int64_t blocks = 0; /* number of refcount block clusters */ 26077c5bcc42SStefan Hajnoczi int64_t last; 26087c5bcc42SStefan Hajnoczi int64_t n = 0; 26097c5bcc42SStefan Hajnoczi 26107c5bcc42SStefan Hajnoczi do { 26117c5bcc42SStefan Hajnoczi last = n; 26127c5bcc42SStefan Hajnoczi blocks = DIV_ROUND_UP(clusters + table + blocks, refcounts_per_block); 26137c5bcc42SStefan Hajnoczi table = DIV_ROUND_UP(blocks, blocks_per_table_cluster); 26147c5bcc42SStefan Hajnoczi n = clusters + blocks + table; 261512cc30a8SMax Reitz 261612cc30a8SMax Reitz if (n == last && generous_increase) { 261712cc30a8SMax Reitz clusters += DIV_ROUND_UP(table, 2); 261812cc30a8SMax Reitz n = 0; /* force another loop */ 261912cc30a8SMax Reitz generous_increase = false; 262012cc30a8SMax Reitz } 26217c5bcc42SStefan Hajnoczi } while (n != last); 26227c5bcc42SStefan Hajnoczi 262312cc30a8SMax Reitz if (refblock_count) { 262412cc30a8SMax Reitz *refblock_count = blocks; 262512cc30a8SMax Reitz } 262612cc30a8SMax Reitz 26277c5bcc42SStefan Hajnoczi return (blocks + table) * cluster_size; 26287c5bcc42SStefan Hajnoczi } 26297c5bcc42SStefan Hajnoczi 263095c67e3bSStefan Hajnoczi /** 263195c67e3bSStefan Hajnoczi * qcow2_calc_prealloc_size: 263295c67e3bSStefan Hajnoczi * @total_size: virtual disk size in bytes 263395c67e3bSStefan Hajnoczi * @cluster_size: cluster size in bytes 263495c67e3bSStefan Hajnoczi * @refcount_order: refcount bits power-of-2 exponent 2635a9420734SKevin Wolf * 263695c67e3bSStefan Hajnoczi * Returns: Total number of bytes required for the fully allocated image 263795c67e3bSStefan Hajnoczi * (including metadata). 2638a9420734SKevin Wolf */ 263995c67e3bSStefan Hajnoczi static int64_t qcow2_calc_prealloc_size(int64_t total_size, 264095c67e3bSStefan Hajnoczi size_t cluster_size, 264195c67e3bSStefan Hajnoczi int refcount_order) 264295c67e3bSStefan Hajnoczi { 26430e4271b7SHu Tao int64_t meta_size = 0; 26447c5bcc42SStefan Hajnoczi uint64_t nl1e, nl2e; 26450e4271b7SHu Tao int64_t aligned_total_size = align_offset(total_size, cluster_size); 26460e4271b7SHu Tao 26470e4271b7SHu Tao /* header: 1 cluster */ 26480e4271b7SHu Tao meta_size += cluster_size; 26490e4271b7SHu Tao 26500e4271b7SHu Tao /* total size of L2 tables */ 26510e4271b7SHu Tao nl2e = aligned_total_size / cluster_size; 26520e4271b7SHu Tao nl2e = align_offset(nl2e, cluster_size / sizeof(uint64_t)); 26530e4271b7SHu Tao meta_size += nl2e * sizeof(uint64_t); 26540e4271b7SHu Tao 26550e4271b7SHu Tao /* total size of L1 tables */ 26560e4271b7SHu Tao nl1e = nl2e * sizeof(uint64_t) / cluster_size; 26570e4271b7SHu Tao nl1e = align_offset(nl1e, cluster_size / sizeof(uint64_t)); 26580e4271b7SHu Tao meta_size += nl1e * sizeof(uint64_t); 26590e4271b7SHu Tao 26607c5bcc42SStefan Hajnoczi /* total size of refcount table and blocks */ 26617c5bcc42SStefan Hajnoczi meta_size += qcow2_refcount_metadata_size( 26627c5bcc42SStefan Hajnoczi (meta_size + aligned_total_size) / cluster_size, 266312cc30a8SMax Reitz cluster_size, refcount_order, false, NULL); 26640e4271b7SHu Tao 266595c67e3bSStefan Hajnoczi return meta_size + aligned_total_size; 266695c67e3bSStefan Hajnoczi } 266795c67e3bSStefan Hajnoczi 26680eb4a8c1SStefan Hajnoczi static size_t qcow2_opt_get_cluster_size_del(QemuOpts *opts, Error **errp) 266995c67e3bSStefan Hajnoczi { 26700eb4a8c1SStefan Hajnoczi size_t cluster_size; 267195c67e3bSStefan Hajnoczi int cluster_bits; 267295c67e3bSStefan Hajnoczi 26730eb4a8c1SStefan Hajnoczi cluster_size = qemu_opt_get_size_del(opts, BLOCK_OPT_CLUSTER_SIZE, 26740eb4a8c1SStefan Hajnoczi DEFAULT_CLUSTER_SIZE); 267595c67e3bSStefan Hajnoczi cluster_bits = ctz32(cluster_size); 267695c67e3bSStefan Hajnoczi if (cluster_bits < MIN_CLUSTER_BITS || cluster_bits > MAX_CLUSTER_BITS || 267795c67e3bSStefan Hajnoczi (1 << cluster_bits) != cluster_size) 267895c67e3bSStefan Hajnoczi { 267995c67e3bSStefan Hajnoczi error_setg(errp, "Cluster size must be a power of two between %d and " 268095c67e3bSStefan Hajnoczi "%dk", 1 << MIN_CLUSTER_BITS, 1 << (MAX_CLUSTER_BITS - 10)); 26810eb4a8c1SStefan Hajnoczi return 0; 268295c67e3bSStefan Hajnoczi } 26830eb4a8c1SStefan Hajnoczi return cluster_size; 26840eb4a8c1SStefan Hajnoczi } 26850eb4a8c1SStefan Hajnoczi 26860eb4a8c1SStefan Hajnoczi static int qcow2_opt_get_version_del(QemuOpts *opts, Error **errp) 26870eb4a8c1SStefan Hajnoczi { 26880eb4a8c1SStefan Hajnoczi char *buf; 26890eb4a8c1SStefan Hajnoczi int ret; 26900eb4a8c1SStefan Hajnoczi 26910eb4a8c1SStefan Hajnoczi buf = qemu_opt_get_del(opts, BLOCK_OPT_COMPAT_LEVEL); 26920eb4a8c1SStefan Hajnoczi if (!buf) { 26930eb4a8c1SStefan Hajnoczi ret = 3; /* default */ 26940eb4a8c1SStefan Hajnoczi } else if (!strcmp(buf, "0.10")) { 26950eb4a8c1SStefan Hajnoczi ret = 2; 26960eb4a8c1SStefan Hajnoczi } else if (!strcmp(buf, "1.1")) { 26970eb4a8c1SStefan Hajnoczi ret = 3; 26980eb4a8c1SStefan Hajnoczi } else { 26990eb4a8c1SStefan Hajnoczi error_setg(errp, "Invalid compatibility level: '%s'", buf); 27000eb4a8c1SStefan Hajnoczi ret = -EINVAL; 27010eb4a8c1SStefan Hajnoczi } 27020eb4a8c1SStefan Hajnoczi g_free(buf); 27030eb4a8c1SStefan Hajnoczi return ret; 27040eb4a8c1SStefan Hajnoczi } 27050eb4a8c1SStefan Hajnoczi 27060eb4a8c1SStefan Hajnoczi static uint64_t qcow2_opt_get_refcount_bits_del(QemuOpts *opts, int version, 27070eb4a8c1SStefan Hajnoczi Error **errp) 27080eb4a8c1SStefan Hajnoczi { 27090eb4a8c1SStefan Hajnoczi uint64_t refcount_bits; 27100eb4a8c1SStefan Hajnoczi 27110eb4a8c1SStefan Hajnoczi refcount_bits = qemu_opt_get_number_del(opts, BLOCK_OPT_REFCOUNT_BITS, 16); 27120eb4a8c1SStefan Hajnoczi if (refcount_bits > 64 || !is_power_of_2(refcount_bits)) { 27130eb4a8c1SStefan Hajnoczi error_setg(errp, "Refcount width must be a power of two and may not " 27140eb4a8c1SStefan Hajnoczi "exceed 64 bits"); 27150eb4a8c1SStefan Hajnoczi return 0; 27160eb4a8c1SStefan Hajnoczi } 27170eb4a8c1SStefan Hajnoczi 27180eb4a8c1SStefan Hajnoczi if (version < 3 && refcount_bits != 16) { 27190eb4a8c1SStefan Hajnoczi error_setg(errp, "Different refcount widths than 16 bits require " 27200eb4a8c1SStefan Hajnoczi "compatibility level 1.1 or above (use compat=1.1 or " 27210eb4a8c1SStefan Hajnoczi "greater)"); 27220eb4a8c1SStefan Hajnoczi return 0; 27230eb4a8c1SStefan Hajnoczi } 27240eb4a8c1SStefan Hajnoczi 27250eb4a8c1SStefan Hajnoczi return refcount_bits; 27260eb4a8c1SStefan Hajnoczi } 27270eb4a8c1SStefan Hajnoczi 27280eb4a8c1SStefan Hajnoczi static int qcow2_create2(const char *filename, int64_t total_size, 27290eb4a8c1SStefan Hajnoczi const char *backing_file, const char *backing_format, 27300eb4a8c1SStefan Hajnoczi int flags, size_t cluster_size, PreallocMode prealloc, 27310eb4a8c1SStefan Hajnoczi QemuOpts *opts, int version, int refcount_order, 27320eb4a8c1SStefan Hajnoczi const char *encryptfmt, Error **errp) 27330eb4a8c1SStefan Hajnoczi { 27340eb4a8c1SStefan Hajnoczi QDict *options; 273595c67e3bSStefan Hajnoczi 273695c67e3bSStefan Hajnoczi /* 273795c67e3bSStefan Hajnoczi * Open the image file and write a minimal qcow2 header. 273895c67e3bSStefan Hajnoczi * 273995c67e3bSStefan Hajnoczi * We keep things simple and start with a zero-sized image. We also 274095c67e3bSStefan Hajnoczi * do without refcount blocks or a L1 table for now. We'll fix the 274195c67e3bSStefan Hajnoczi * inconsistency later. 274295c67e3bSStefan Hajnoczi * 274395c67e3bSStefan Hajnoczi * We do need a refcount table because growing the refcount table means 274495c67e3bSStefan Hajnoczi * allocating two new refcount blocks - the seconds of which would be at 274595c67e3bSStefan Hajnoczi * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file 274695c67e3bSStefan Hajnoczi * size for any qcow2 image. 274795c67e3bSStefan Hajnoczi */ 274895c67e3bSStefan Hajnoczi BlockBackend *blk; 274995c67e3bSStefan Hajnoczi QCowHeader *header; 275095c67e3bSStefan Hajnoczi uint64_t* refcount_table; 275195c67e3bSStefan Hajnoczi Error *local_err = NULL; 275295c67e3bSStefan Hajnoczi int ret; 275395c67e3bSStefan Hajnoczi 275495c67e3bSStefan Hajnoczi if (prealloc == PREALLOC_MODE_FULL || prealloc == PREALLOC_MODE_FALLOC) { 275595c67e3bSStefan Hajnoczi int64_t prealloc_size = 275695c67e3bSStefan Hajnoczi qcow2_calc_prealloc_size(total_size, cluster_size, refcount_order); 275795c67e3bSStefan Hajnoczi qemu_opt_set_number(opts, BLOCK_OPT_SIZE, prealloc_size, &error_abort); 2758977c736fSMarkus Armbruster qemu_opt_set(opts, BLOCK_OPT_PREALLOC, PreallocMode_str(prealloc), 2759f43e47dbSMarkus Armbruster &error_abort); 27600e4271b7SHu Tao } 27610e4271b7SHu Tao 2762c282e1fdSChunyan Liu ret = bdrv_create_file(filename, opts, &local_err); 2763a9420734SKevin Wolf if (ret < 0) { 27643ef6c40aSMax Reitz error_propagate(errp, local_err); 2765a9420734SKevin Wolf return ret; 2766a9420734SKevin Wolf } 2767a9420734SKevin Wolf 2768efaa7c4eSMax Reitz blk = blk_new_open(filename, NULL, NULL, 276955880601SKevin Wolf BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_PROTOCOL, 277055880601SKevin Wolf &local_err); 277123588797SKevin Wolf if (blk == NULL) { 27723ef6c40aSMax Reitz error_propagate(errp, local_err); 277323588797SKevin Wolf return -EIO; 2774a9420734SKevin Wolf } 2775a9420734SKevin Wolf 277623588797SKevin Wolf blk_set_allow_write_beyond_eof(blk, true); 277723588797SKevin Wolf 2778a9420734SKevin Wolf /* Write the header */ 2779f8413b3cSKevin Wolf QEMU_BUILD_BUG_ON((1 << MIN_CLUSTER_BITS) < sizeof(*header)); 2780f8413b3cSKevin Wolf header = g_malloc0(cluster_size); 2781f8413b3cSKevin Wolf *header = (QCowHeader) { 2782f8413b3cSKevin Wolf .magic = cpu_to_be32(QCOW_MAGIC), 2783f8413b3cSKevin Wolf .version = cpu_to_be32(version), 27840eb4a8c1SStefan Hajnoczi .cluster_bits = cpu_to_be32(ctz32(cluster_size)), 2785f8413b3cSKevin Wolf .size = cpu_to_be64(0), 2786f8413b3cSKevin Wolf .l1_table_offset = cpu_to_be64(0), 2787f8413b3cSKevin Wolf .l1_size = cpu_to_be32(0), 2788f8413b3cSKevin Wolf .refcount_table_offset = cpu_to_be64(cluster_size), 2789f8413b3cSKevin Wolf .refcount_table_clusters = cpu_to_be32(1), 2790bd4b167fSMax Reitz .refcount_order = cpu_to_be32(refcount_order), 2791f8413b3cSKevin Wolf .header_length = cpu_to_be32(sizeof(*header)), 2792f8413b3cSKevin Wolf }; 2793a9420734SKevin Wolf 2794b25b387fSDaniel P. Berrange /* We'll update this to correct value later */ 2795f8413b3cSKevin Wolf header->crypt_method = cpu_to_be32(QCOW_CRYPT_NONE); 2796a9420734SKevin Wolf 2797bfe8043eSStefan Hajnoczi if (flags & BLOCK_FLAG_LAZY_REFCOUNTS) { 2798f8413b3cSKevin Wolf header->compatible_features |= 2799bfe8043eSStefan Hajnoczi cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS); 2800bfe8043eSStefan Hajnoczi } 2801bfe8043eSStefan Hajnoczi 28028341f00dSEric Blake ret = blk_pwrite(blk, 0, header, cluster_size, 0); 2803f8413b3cSKevin Wolf g_free(header); 2804a9420734SKevin Wolf if (ret < 0) { 28053ef6c40aSMax Reitz error_setg_errno(errp, -ret, "Could not write qcow2 header"); 2806a9420734SKevin Wolf goto out; 2807a9420734SKevin Wolf } 2808a9420734SKevin Wolf 2809b106ad91SKevin Wolf /* Write a refcount table with one refcount block */ 2810b106ad91SKevin Wolf refcount_table = g_malloc0(2 * cluster_size); 2811b106ad91SKevin Wolf refcount_table[0] = cpu_to_be64(2 * cluster_size); 28128341f00dSEric Blake ret = blk_pwrite(blk, cluster_size, refcount_table, 2 * cluster_size, 0); 28137267c094SAnthony Liguori g_free(refcount_table); 2814a9420734SKevin Wolf 2815a9420734SKevin Wolf if (ret < 0) { 28163ef6c40aSMax Reitz error_setg_errno(errp, -ret, "Could not write refcount table"); 2817a9420734SKevin Wolf goto out; 2818a9420734SKevin Wolf } 2819a9420734SKevin Wolf 282023588797SKevin Wolf blk_unref(blk); 282123588797SKevin Wolf blk = NULL; 2822a9420734SKevin Wolf 2823a9420734SKevin Wolf /* 2824a9420734SKevin Wolf * And now open the image and make it consistent first (i.e. increase the 2825a9420734SKevin Wolf * refcount of the cluster that is occupied by the header and the refcount 2826a9420734SKevin Wolf * table) 2827a9420734SKevin Wolf */ 2828e6641719SMax Reitz options = qdict_new(); 282946f5ac20SEric Blake qdict_put_str(options, "driver", "qcow2"); 2830efaa7c4eSMax Reitz blk = blk_new_open(filename, NULL, options, 283155880601SKevin Wolf BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_NO_FLUSH, 283255880601SKevin Wolf &local_err); 283323588797SKevin Wolf if (blk == NULL) { 28343ef6c40aSMax Reitz error_propagate(errp, local_err); 283523588797SKevin Wolf ret = -EIO; 2836a9420734SKevin Wolf goto out; 2837a9420734SKevin Wolf } 2838a9420734SKevin Wolf 283923588797SKevin Wolf ret = qcow2_alloc_clusters(blk_bs(blk), 3 * cluster_size); 2840a9420734SKevin Wolf if (ret < 0) { 28413ef6c40aSMax Reitz error_setg_errno(errp, -ret, "Could not allocate clusters for qcow2 " 28423ef6c40aSMax Reitz "header and refcount table"); 2843a9420734SKevin Wolf goto out; 2844a9420734SKevin Wolf 2845a9420734SKevin Wolf } else if (ret != 0) { 2846a9420734SKevin Wolf error_report("Huh, first cluster in empty image is already in use?"); 2847a9420734SKevin Wolf abort(); 2848a9420734SKevin Wolf } 2849a9420734SKevin Wolf 2850b527c9b3SKevin Wolf /* Create a full header (including things like feature table) */ 285123588797SKevin Wolf ret = qcow2_update_header(blk_bs(blk)); 2852b527c9b3SKevin Wolf if (ret < 0) { 2853b527c9b3SKevin Wolf error_setg_errno(errp, -ret, "Could not update qcow2 header"); 2854b527c9b3SKevin Wolf goto out; 2855b527c9b3SKevin Wolf } 2856b527c9b3SKevin Wolf 2857a9420734SKevin Wolf /* Okay, now that we have a valid image, let's give it the right size */ 28583a691c50SMax Reitz ret = blk_truncate(blk, total_size, PREALLOC_MODE_OFF, errp); 2859a9420734SKevin Wolf if (ret < 0) { 2860ed3d2ec9SMax Reitz error_prepend(errp, "Could not resize image: "); 2861a9420734SKevin Wolf goto out; 2862a9420734SKevin Wolf } 2863a9420734SKevin Wolf 2864a9420734SKevin Wolf /* Want a backing file? There you go.*/ 2865a9420734SKevin Wolf if (backing_file) { 286623588797SKevin Wolf ret = bdrv_change_backing_file(blk_bs(blk), backing_file, backing_format); 2867a9420734SKevin Wolf if (ret < 0) { 28683ef6c40aSMax Reitz error_setg_errno(errp, -ret, "Could not assign backing file '%s' " 28693ef6c40aSMax Reitz "with format '%s'", backing_file, backing_format); 2870a9420734SKevin Wolf goto out; 2871a9420734SKevin Wolf } 2872a9420734SKevin Wolf } 2873a9420734SKevin Wolf 2874b25b387fSDaniel P. Berrange /* Want encryption? There you go. */ 2875b25b387fSDaniel P. Berrange if (encryptfmt) { 2876b25b387fSDaniel P. Berrange ret = qcow2_set_up_encryption(blk_bs(blk), encryptfmt, opts, errp); 2877b25b387fSDaniel P. Berrange if (ret < 0) { 2878b25b387fSDaniel P. Berrange goto out; 2879b25b387fSDaniel P. Berrange } 2880b25b387fSDaniel P. Berrange } 2881b25b387fSDaniel P. Berrange 2882a9420734SKevin Wolf /* And if we're supposed to preallocate metadata, do that now */ 28830e4271b7SHu Tao if (prealloc != PREALLOC_MODE_OFF) { 28847bc45dc1SMax Reitz ret = preallocate(blk_bs(blk), 0, total_size); 2885a9420734SKevin Wolf if (ret < 0) { 28863ef6c40aSMax Reitz error_setg_errno(errp, -ret, "Could not preallocate metadata"); 2887a9420734SKevin Wolf goto out; 2888a9420734SKevin Wolf } 2889a9420734SKevin Wolf } 2890a9420734SKevin Wolf 289123588797SKevin Wolf blk_unref(blk); 289223588797SKevin Wolf blk = NULL; 2893ba2ab2f2SMax Reitz 2894b25b387fSDaniel P. Berrange /* Reopen the image without BDRV_O_NO_FLUSH to flush it before returning. 2895b25b387fSDaniel P. Berrange * Using BDRV_O_NO_IO, since encryption is now setup we don't want to 2896b25b387fSDaniel P. Berrange * have to setup decryption context. We're not doing any I/O on the top 2897b25b387fSDaniel P. Berrange * level BlockDriverState, only lower layers, where BDRV_O_NO_IO does 2898b25b387fSDaniel P. Berrange * not have effect. 2899b25b387fSDaniel P. Berrange */ 2900e6641719SMax Reitz options = qdict_new(); 290146f5ac20SEric Blake qdict_put_str(options, "driver", "qcow2"); 2902efaa7c4eSMax Reitz blk = blk_new_open(filename, NULL, options, 2903b25b387fSDaniel P. Berrange BDRV_O_RDWR | BDRV_O_NO_BACKING | BDRV_O_NO_IO, 2904b25b387fSDaniel P. Berrange &local_err); 290523588797SKevin Wolf if (blk == NULL) { 2906ba2ab2f2SMax Reitz error_propagate(errp, local_err); 290723588797SKevin Wolf ret = -EIO; 2908ba2ab2f2SMax Reitz goto out; 2909ba2ab2f2SMax Reitz } 2910ba2ab2f2SMax Reitz 2911a9420734SKevin Wolf ret = 0; 2912a9420734SKevin Wolf out: 291323588797SKevin Wolf if (blk) { 291423588797SKevin Wolf blk_unref(blk); 2915f67503e5SMax Reitz } 2916a9420734SKevin Wolf return ret; 2917a9420734SKevin Wolf } 2918de5f3f40SKevin Wolf 2919*efc75e2aSStefan Hajnoczi static int coroutine_fn qcow2_co_create_opts(const char *filename, QemuOpts *opts, 2920*efc75e2aSStefan Hajnoczi Error **errp) 2921de5f3f40SKevin Wolf { 29221bd0e2d1SChunyan Liu char *backing_file = NULL; 29231bd0e2d1SChunyan Liu char *backing_fmt = NULL; 29241bd0e2d1SChunyan Liu char *buf = NULL; 2925180e9526SHu Tao uint64_t size = 0; 2926de5f3f40SKevin Wolf int flags = 0; 292799cce9faSKevin Wolf size_t cluster_size = DEFAULT_CLUSTER_SIZE; 2928ffeaac9bSHu Tao PreallocMode prealloc; 29290eb4a8c1SStefan Hajnoczi int version; 29300eb4a8c1SStefan Hajnoczi uint64_t refcount_bits; 2931bd4b167fSMax Reitz int refcount_order; 29320696ae2cSDaniel P. Berrange char *encryptfmt = NULL; 29333ef6c40aSMax Reitz Error *local_err = NULL; 29343ef6c40aSMax Reitz int ret; 2935de5f3f40SKevin Wolf 2936de5f3f40SKevin Wolf /* Read out options */ 2937180e9526SHu Tao size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0), 2938c2eb918eSHu Tao BDRV_SECTOR_SIZE); 29391bd0e2d1SChunyan Liu backing_file = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE); 29401bd0e2d1SChunyan Liu backing_fmt = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FMT); 29410cb8d47bSDaniel P. Berrange encryptfmt = qemu_opt_get_del(opts, BLOCK_OPT_ENCRYPT_FORMAT); 29420cb8d47bSDaniel P. Berrange if (encryptfmt) { 29430696ae2cSDaniel P. Berrange if (qemu_opt_get(opts, BLOCK_OPT_ENCRYPT)) { 29440cb8d47bSDaniel P. Berrange error_setg(errp, "Options " BLOCK_OPT_ENCRYPT " and " 29450cb8d47bSDaniel P. Berrange BLOCK_OPT_ENCRYPT_FORMAT " are mutually exclusive"); 29460cb8d47bSDaniel P. Berrange ret = -EINVAL; 29470cb8d47bSDaniel P. Berrange goto finish; 29480cb8d47bSDaniel P. Berrange } 29490cb8d47bSDaniel P. Berrange } else if (qemu_opt_get_bool_del(opts, BLOCK_OPT_ENCRYPT, false)) { 29500696ae2cSDaniel P. Berrange encryptfmt = g_strdup("aes"); 2951de5f3f40SKevin Wolf } 29520eb4a8c1SStefan Hajnoczi cluster_size = qcow2_opt_get_cluster_size_del(opts, &local_err); 29530eb4a8c1SStefan Hajnoczi if (local_err) { 29540eb4a8c1SStefan Hajnoczi error_propagate(errp, local_err); 29550eb4a8c1SStefan Hajnoczi ret = -EINVAL; 29560eb4a8c1SStefan Hajnoczi goto finish; 29570eb4a8c1SStefan Hajnoczi } 29581bd0e2d1SChunyan Liu buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC); 2959f7abe0ecSMarc-André Lureau prealloc = qapi_enum_parse(&PreallocMode_lookup, buf, 296006c60b6cSMarkus Armbruster PREALLOC_MODE_OFF, &local_err); 2961ffeaac9bSHu Tao if (local_err) { 2962ffeaac9bSHu Tao error_propagate(errp, local_err); 29631bd0e2d1SChunyan Liu ret = -EINVAL; 29641bd0e2d1SChunyan Liu goto finish; 2965de5f3f40SKevin Wolf } 29660eb4a8c1SStefan Hajnoczi 29670eb4a8c1SStefan Hajnoczi version = qcow2_opt_get_version_del(opts, &local_err); 29680eb4a8c1SStefan Hajnoczi if (local_err) { 29690eb4a8c1SStefan Hajnoczi error_propagate(errp, local_err); 29701bd0e2d1SChunyan Liu ret = -EINVAL; 29711bd0e2d1SChunyan Liu goto finish; 29726744cbabSKevin Wolf } 29731bd0e2d1SChunyan Liu 29741bd0e2d1SChunyan Liu if (qemu_opt_get_bool_del(opts, BLOCK_OPT_LAZY_REFCOUNTS, false)) { 29751bd0e2d1SChunyan Liu flags |= BLOCK_FLAG_LAZY_REFCOUNTS; 2976de5f3f40SKevin Wolf } 2977de5f3f40SKevin Wolf 2978ffeaac9bSHu Tao if (backing_file && prealloc != PREALLOC_MODE_OFF) { 29793ef6c40aSMax Reitz error_setg(errp, "Backing file and preallocation cannot be used at " 29803ef6c40aSMax Reitz "the same time"); 29811bd0e2d1SChunyan Liu ret = -EINVAL; 29821bd0e2d1SChunyan Liu goto finish; 2983de5f3f40SKevin Wolf } 2984de5f3f40SKevin Wolf 2985bfe8043eSStefan Hajnoczi if (version < 3 && (flags & BLOCK_FLAG_LAZY_REFCOUNTS)) { 29863ef6c40aSMax Reitz error_setg(errp, "Lazy refcounts only supported with compatibility " 29873ef6c40aSMax Reitz "level 1.1 and above (use compat=1.1 or greater)"); 29881bd0e2d1SChunyan Liu ret = -EINVAL; 29891bd0e2d1SChunyan Liu goto finish; 2990bfe8043eSStefan Hajnoczi } 2991bfe8043eSStefan Hajnoczi 29920eb4a8c1SStefan Hajnoczi refcount_bits = qcow2_opt_get_refcount_bits_del(opts, version, &local_err); 29930eb4a8c1SStefan Hajnoczi if (local_err) { 29940eb4a8c1SStefan Hajnoczi error_propagate(errp, local_err); 2995bd4b167fSMax Reitz ret = -EINVAL; 2996bd4b167fSMax Reitz goto finish; 2997bd4b167fSMax Reitz } 2998bd4b167fSMax Reitz 2999786a4ea8SStefan Hajnoczi refcount_order = ctz32(refcount_bits); 3000bd4b167fSMax Reitz 3001180e9526SHu Tao ret = qcow2_create2(filename, size, backing_file, backing_fmt, flags, 3002bd4b167fSMax Reitz cluster_size, prealloc, opts, version, refcount_order, 30030cb8d47bSDaniel P. Berrange encryptfmt, &local_err); 30043ef6c40aSMax Reitz error_propagate(errp, local_err); 30051bd0e2d1SChunyan Liu 30061bd0e2d1SChunyan Liu finish: 30071bd0e2d1SChunyan Liu g_free(backing_file); 30081bd0e2d1SChunyan Liu g_free(backing_fmt); 30090696ae2cSDaniel P. Berrange g_free(encryptfmt); 30101bd0e2d1SChunyan Liu g_free(buf); 30113ef6c40aSMax Reitz return ret; 3012de5f3f40SKevin Wolf } 3013de5f3f40SKevin Wolf 30142928abceSDenis V. Lunev 3015f06f6b66SEric Blake static bool is_zero(BlockDriverState *bs, int64_t offset, int64_t bytes) 30162928abceSDenis V. Lunev { 301731826642SEric Blake int64_t nr; 301831826642SEric Blake int res; 3019f06f6b66SEric Blake 3020f06f6b66SEric Blake /* Clamp to image length, before checking status of underlying sectors */ 30218cbf74b2SEric Blake if (offset + bytes > bs->total_sectors * BDRV_SECTOR_SIZE) { 30228cbf74b2SEric Blake bytes = bs->total_sectors * BDRV_SECTOR_SIZE - offset; 3023fbaa6bb3SEric Blake } 3024fbaa6bb3SEric Blake 3025f06f6b66SEric Blake if (!bytes) { 3026ebb718a5SEric Blake return true; 30272928abceSDenis V. Lunev } 30288cbf74b2SEric Blake res = bdrv_block_status_above(bs, NULL, offset, bytes, &nr, NULL, NULL); 302931826642SEric Blake return res >= 0 && (res & BDRV_BLOCK_ZERO) && nr == bytes; 30302928abceSDenis V. Lunev } 30312928abceSDenis V. Lunev 30325544b59fSEric Blake static coroutine_fn int qcow2_co_pwrite_zeroes(BlockDriverState *bs, 3033f5a5ca79SManos Pitsidianakis int64_t offset, int bytes, BdrvRequestFlags flags) 3034621f0589SKevin Wolf { 3035621f0589SKevin Wolf int ret; 3036ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque; 3037621f0589SKevin Wolf 30385544b59fSEric Blake uint32_t head = offset % s->cluster_size; 3039f5a5ca79SManos Pitsidianakis uint32_t tail = (offset + bytes) % s->cluster_size; 30402928abceSDenis V. Lunev 3041f5a5ca79SManos Pitsidianakis trace_qcow2_pwrite_zeroes_start_req(qemu_coroutine_self(), offset, bytes); 3042f5a5ca79SManos Pitsidianakis if (offset + bytes == bs->total_sectors * BDRV_SECTOR_SIZE) { 3043fbaa6bb3SEric Blake tail = 0; 3044fbaa6bb3SEric Blake } 30455a64e942SDenis V. Lunev 3046ebb718a5SEric Blake if (head || tail) { 3047ebb718a5SEric Blake uint64_t off; 3048ecfe1863SKevin Wolf unsigned int nr; 30492928abceSDenis V. Lunev 3050f5a5ca79SManos Pitsidianakis assert(head + bytes <= s->cluster_size); 30512928abceSDenis V. Lunev 3052ebb718a5SEric Blake /* check whether remainder of cluster already reads as zero */ 3053f06f6b66SEric Blake if (!(is_zero(bs, offset - head, head) && 3054f06f6b66SEric Blake is_zero(bs, offset + bytes, 3055f06f6b66SEric Blake tail ? s->cluster_size - tail : 0))) { 3056621f0589SKevin Wolf return -ENOTSUP; 3057621f0589SKevin Wolf } 3058621f0589SKevin Wolf 3059621f0589SKevin Wolf qemu_co_mutex_lock(&s->lock); 30602928abceSDenis V. Lunev /* We can have new write after previous check */ 3061f06f6b66SEric Blake offset = QEMU_ALIGN_DOWN(offset, s->cluster_size); 3062f5a5ca79SManos Pitsidianakis bytes = s->cluster_size; 3063ecfe1863SKevin Wolf nr = s->cluster_size; 30645544b59fSEric Blake ret = qcow2_get_cluster_offset(bs, offset, &nr, &off); 3065fdfab37dSEric Blake if (ret != QCOW2_CLUSTER_UNALLOCATED && 3066fdfab37dSEric Blake ret != QCOW2_CLUSTER_ZERO_PLAIN && 3067fdfab37dSEric Blake ret != QCOW2_CLUSTER_ZERO_ALLOC) { 30682928abceSDenis V. Lunev qemu_co_mutex_unlock(&s->lock); 30692928abceSDenis V. Lunev return -ENOTSUP; 30702928abceSDenis V. Lunev } 30712928abceSDenis V. Lunev } else { 30722928abceSDenis V. Lunev qemu_co_mutex_lock(&s->lock); 30732928abceSDenis V. Lunev } 30742928abceSDenis V. Lunev 3075f5a5ca79SManos Pitsidianakis trace_qcow2_pwrite_zeroes(qemu_coroutine_self(), offset, bytes); 30765a64e942SDenis V. Lunev 30772928abceSDenis V. Lunev /* Whatever is left can use real zero clusters */ 3078f5a5ca79SManos Pitsidianakis ret = qcow2_cluster_zeroize(bs, offset, bytes, flags); 3079621f0589SKevin Wolf qemu_co_mutex_unlock(&s->lock); 3080621f0589SKevin Wolf 3081621f0589SKevin Wolf return ret; 3082621f0589SKevin Wolf } 3083621f0589SKevin Wolf 308482e8a788SEric Blake static coroutine_fn int qcow2_co_pdiscard(BlockDriverState *bs, 3085f5a5ca79SManos Pitsidianakis int64_t offset, int bytes) 30865ea929e3SKevin Wolf { 30876db39ae2SPaolo Bonzini int ret; 3088ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque; 30896db39ae2SPaolo Bonzini 3090f5a5ca79SManos Pitsidianakis if (!QEMU_IS_ALIGNED(offset | bytes, s->cluster_size)) { 3091f5a5ca79SManos Pitsidianakis assert(bytes < s->cluster_size); 3092048c5fd1SEric Blake /* Ignore partial clusters, except for the special case of the 3093048c5fd1SEric Blake * complete partial cluster at the end of an unaligned file */ 3094048c5fd1SEric Blake if (!QEMU_IS_ALIGNED(offset, s->cluster_size) || 3095f5a5ca79SManos Pitsidianakis offset + bytes != bs->total_sectors * BDRV_SECTOR_SIZE) { 309649228d1eSEric Blake return -ENOTSUP; 309749228d1eSEric Blake } 3098048c5fd1SEric Blake } 309949228d1eSEric Blake 31006db39ae2SPaolo Bonzini qemu_co_mutex_lock(&s->lock); 3101f5a5ca79SManos Pitsidianakis ret = qcow2_cluster_discard(bs, offset, bytes, QCOW2_DISCARD_REQUEST, 3102d2cb36afSEric Blake false); 31036db39ae2SPaolo Bonzini qemu_co_mutex_unlock(&s->lock); 31046db39ae2SPaolo Bonzini return ret; 31055ea929e3SKevin Wolf } 31065ea929e3SKevin Wolf 31078243ccb7SMax Reitz static int qcow2_truncate(BlockDriverState *bs, int64_t offset, 31088243ccb7SMax Reitz PreallocMode prealloc, Error **errp) 3109419b19d9SStefan Hajnoczi { 3110ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque; 311195b98f34SMax Reitz uint64_t old_length; 31122cf7cfa1SKevin Wolf int64_t new_l1_size; 31132cf7cfa1SKevin Wolf int ret; 3114419b19d9SStefan Hajnoczi 3115772d1f97SMax Reitz if (prealloc != PREALLOC_MODE_OFF && prealloc != PREALLOC_MODE_METADATA && 3116772d1f97SMax Reitz prealloc != PREALLOC_MODE_FALLOC && prealloc != PREALLOC_MODE_FULL) 3117772d1f97SMax Reitz { 31188243ccb7SMax Reitz error_setg(errp, "Unsupported preallocation mode '%s'", 3119977c736fSMarkus Armbruster PreallocMode_str(prealloc)); 31208243ccb7SMax Reitz return -ENOTSUP; 31218243ccb7SMax Reitz } 31228243ccb7SMax Reitz 3123419b19d9SStefan Hajnoczi if (offset & 511) { 31244bff28b8SMax Reitz error_setg(errp, "The new size must be a multiple of 512"); 3125419b19d9SStefan Hajnoczi return -EINVAL; 3126419b19d9SStefan Hajnoczi } 3127419b19d9SStefan Hajnoczi 3128419b19d9SStefan Hajnoczi /* cannot proceed if image has snapshots */ 3129419b19d9SStefan Hajnoczi if (s->nb_snapshots) { 31304bff28b8SMax Reitz error_setg(errp, "Can't resize an image which has snapshots"); 3131419b19d9SStefan Hajnoczi return -ENOTSUP; 3132419b19d9SStefan Hajnoczi } 3133419b19d9SStefan Hajnoczi 313488ddffaeSVladimir Sementsov-Ogievskiy /* cannot proceed if image has bitmaps */ 313588ddffaeSVladimir Sementsov-Ogievskiy if (s->nb_bitmaps) { 313688ddffaeSVladimir Sementsov-Ogievskiy /* TODO: resize bitmaps in the image */ 313788ddffaeSVladimir Sementsov-Ogievskiy error_setg(errp, "Can't resize an image which has bitmaps"); 313888ddffaeSVladimir Sementsov-Ogievskiy return -ENOTSUP; 313988ddffaeSVladimir Sementsov-Ogievskiy } 314088ddffaeSVladimir Sementsov-Ogievskiy 314195b98f34SMax Reitz old_length = bs->total_sectors * 512; 314246b732cdSPavel Butsykin new_l1_size = size_to_l1(s, offset); 314395b98f34SMax Reitz 314495b98f34SMax Reitz if (offset < old_length) { 3145163bc39dSPavel Butsykin int64_t last_cluster, old_file_size; 314646b732cdSPavel Butsykin if (prealloc != PREALLOC_MODE_OFF) { 314746b732cdSPavel Butsykin error_setg(errp, 314846b732cdSPavel Butsykin "Preallocation can't be used for shrinking an image"); 314946b732cdSPavel Butsykin return -EINVAL; 3150419b19d9SStefan Hajnoczi } 3151419b19d9SStefan Hajnoczi 315246b732cdSPavel Butsykin ret = qcow2_cluster_discard(bs, ROUND_UP(offset, s->cluster_size), 315346b732cdSPavel Butsykin old_length - ROUND_UP(offset, 315446b732cdSPavel Butsykin s->cluster_size), 315546b732cdSPavel Butsykin QCOW2_DISCARD_ALWAYS, true); 315646b732cdSPavel Butsykin if (ret < 0) { 315746b732cdSPavel Butsykin error_setg_errno(errp, -ret, "Failed to discard cropped clusters"); 315846b732cdSPavel Butsykin return ret; 315946b732cdSPavel Butsykin } 316046b732cdSPavel Butsykin 316146b732cdSPavel Butsykin ret = qcow2_shrink_l1_table(bs, new_l1_size); 316246b732cdSPavel Butsykin if (ret < 0) { 316346b732cdSPavel Butsykin error_setg_errno(errp, -ret, 316446b732cdSPavel Butsykin "Failed to reduce the number of L2 tables"); 316546b732cdSPavel Butsykin return ret; 316646b732cdSPavel Butsykin } 316746b732cdSPavel Butsykin 316846b732cdSPavel Butsykin ret = qcow2_shrink_reftable(bs); 316946b732cdSPavel Butsykin if (ret < 0) { 317046b732cdSPavel Butsykin error_setg_errno(errp, -ret, 317146b732cdSPavel Butsykin "Failed to discard unused refblocks"); 317246b732cdSPavel Butsykin return ret; 317346b732cdSPavel Butsykin } 3174163bc39dSPavel Butsykin 3175163bc39dSPavel Butsykin old_file_size = bdrv_getlength(bs->file->bs); 3176163bc39dSPavel Butsykin if (old_file_size < 0) { 3177163bc39dSPavel Butsykin error_setg_errno(errp, -old_file_size, 3178163bc39dSPavel Butsykin "Failed to inquire current file length"); 3179163bc39dSPavel Butsykin return old_file_size; 3180163bc39dSPavel Butsykin } 3181163bc39dSPavel Butsykin last_cluster = qcow2_get_last_cluster(bs, old_file_size); 3182163bc39dSPavel Butsykin if (last_cluster < 0) { 3183163bc39dSPavel Butsykin error_setg_errno(errp, -last_cluster, 3184163bc39dSPavel Butsykin "Failed to find the last cluster"); 3185163bc39dSPavel Butsykin return last_cluster; 3186163bc39dSPavel Butsykin } 3187163bc39dSPavel Butsykin if ((last_cluster + 1) * s->cluster_size < old_file_size) { 3188233521b1SMax Reitz Error *local_err = NULL; 3189233521b1SMax Reitz 3190233521b1SMax Reitz bdrv_truncate(bs->file, (last_cluster + 1) * s->cluster_size, 3191233521b1SMax Reitz PREALLOC_MODE_OFF, &local_err); 3192233521b1SMax Reitz if (local_err) { 3193233521b1SMax Reitz warn_reportf_err(local_err, 3194233521b1SMax Reitz "Failed to truncate the tail of the image: "); 3195163bc39dSPavel Butsykin } 3196163bc39dSPavel Butsykin } 319746b732cdSPavel Butsykin } else { 319872893756SStefan Hajnoczi ret = qcow2_grow_l1_table(bs, new_l1_size, true); 3199419b19d9SStefan Hajnoczi if (ret < 0) { 3200f59adb32SMax Reitz error_setg_errno(errp, -ret, "Failed to grow the L1 table"); 3201419b19d9SStefan Hajnoczi return ret; 3202419b19d9SStefan Hajnoczi } 320346b732cdSPavel Butsykin } 3204419b19d9SStefan Hajnoczi 320595b98f34SMax Reitz switch (prealloc) { 320695b98f34SMax Reitz case PREALLOC_MODE_OFF: 320795b98f34SMax Reitz break; 320895b98f34SMax Reitz 320995b98f34SMax Reitz case PREALLOC_MODE_METADATA: 321095b98f34SMax Reitz ret = preallocate(bs, old_length, offset); 321195b98f34SMax Reitz if (ret < 0) { 321295b98f34SMax Reitz error_setg_errno(errp, -ret, "Preallocation failed"); 321395b98f34SMax Reitz return ret; 321495b98f34SMax Reitz } 321595b98f34SMax Reitz break; 321695b98f34SMax Reitz 3217772d1f97SMax Reitz case PREALLOC_MODE_FALLOC: 3218772d1f97SMax Reitz case PREALLOC_MODE_FULL: 3219772d1f97SMax Reitz { 3220772d1f97SMax Reitz int64_t allocation_start, host_offset, guest_offset; 3221772d1f97SMax Reitz int64_t clusters_allocated; 3222772d1f97SMax Reitz int64_t old_file_size, new_file_size; 3223772d1f97SMax Reitz uint64_t nb_new_data_clusters, nb_new_l2_tables; 3224772d1f97SMax Reitz 3225772d1f97SMax Reitz old_file_size = bdrv_getlength(bs->file->bs); 3226772d1f97SMax Reitz if (old_file_size < 0) { 3227772d1f97SMax Reitz error_setg_errno(errp, -old_file_size, 3228772d1f97SMax Reitz "Failed to inquire current file length"); 322976a2a30aSPavel Butsykin return old_file_size; 3230772d1f97SMax Reitz } 3231e400ad1eSMax Reitz old_file_size = ROUND_UP(old_file_size, s->cluster_size); 3232772d1f97SMax Reitz 3233772d1f97SMax Reitz nb_new_data_clusters = DIV_ROUND_UP(offset - old_length, 3234772d1f97SMax Reitz s->cluster_size); 3235772d1f97SMax Reitz 3236772d1f97SMax Reitz /* This is an overestimation; we will not actually allocate space for 3237772d1f97SMax Reitz * these in the file but just make sure the new refcount structures are 3238772d1f97SMax Reitz * able to cover them so we will not have to allocate new refblocks 3239772d1f97SMax Reitz * while entering the data blocks in the potentially new L2 tables. 3240772d1f97SMax Reitz * (We do not actually care where the L2 tables are placed. Maybe they 3241772d1f97SMax Reitz * are already allocated or they can be placed somewhere before 3242772d1f97SMax Reitz * @old_file_size. It does not matter because they will be fully 3243772d1f97SMax Reitz * allocated automatically, so they do not need to be covered by the 3244772d1f97SMax Reitz * preallocation. All that matters is that we will not have to allocate 3245772d1f97SMax Reitz * new refcount structures for them.) */ 3246772d1f97SMax Reitz nb_new_l2_tables = DIV_ROUND_UP(nb_new_data_clusters, 3247772d1f97SMax Reitz s->cluster_size / sizeof(uint64_t)); 3248772d1f97SMax Reitz /* The cluster range may not be aligned to L2 boundaries, so add one L2 3249772d1f97SMax Reitz * table for a potential head/tail */ 3250772d1f97SMax Reitz nb_new_l2_tables++; 3251772d1f97SMax Reitz 3252772d1f97SMax Reitz allocation_start = qcow2_refcount_area(bs, old_file_size, 3253772d1f97SMax Reitz nb_new_data_clusters + 3254772d1f97SMax Reitz nb_new_l2_tables, 3255772d1f97SMax Reitz true, 0, 0); 3256772d1f97SMax Reitz if (allocation_start < 0) { 3257772d1f97SMax Reitz error_setg_errno(errp, -allocation_start, 3258772d1f97SMax Reitz "Failed to resize refcount structures"); 325976a2a30aSPavel Butsykin return allocation_start; 3260772d1f97SMax Reitz } 3261772d1f97SMax Reitz 3262772d1f97SMax Reitz clusters_allocated = qcow2_alloc_clusters_at(bs, allocation_start, 3263772d1f97SMax Reitz nb_new_data_clusters); 3264772d1f97SMax Reitz if (clusters_allocated < 0) { 3265772d1f97SMax Reitz error_setg_errno(errp, -clusters_allocated, 3266772d1f97SMax Reitz "Failed to allocate data clusters"); 3267772d1f97SMax Reitz return -clusters_allocated; 3268772d1f97SMax Reitz } 3269772d1f97SMax Reitz 3270772d1f97SMax Reitz assert(clusters_allocated == nb_new_data_clusters); 3271772d1f97SMax Reitz 3272772d1f97SMax Reitz /* Allocate the data area */ 3273772d1f97SMax Reitz new_file_size = allocation_start + 3274772d1f97SMax Reitz nb_new_data_clusters * s->cluster_size; 3275772d1f97SMax Reitz ret = bdrv_truncate(bs->file, new_file_size, prealloc, errp); 3276772d1f97SMax Reitz if (ret < 0) { 3277772d1f97SMax Reitz error_prepend(errp, "Failed to resize underlying file: "); 3278772d1f97SMax Reitz qcow2_free_clusters(bs, allocation_start, 3279772d1f97SMax Reitz nb_new_data_clusters * s->cluster_size, 3280772d1f97SMax Reitz QCOW2_DISCARD_OTHER); 3281772d1f97SMax Reitz return ret; 3282772d1f97SMax Reitz } 3283772d1f97SMax Reitz 3284772d1f97SMax Reitz /* Create the necessary L2 entries */ 3285772d1f97SMax Reitz host_offset = allocation_start; 3286772d1f97SMax Reitz guest_offset = old_length; 3287772d1f97SMax Reitz while (nb_new_data_clusters) { 328813bec229SAlberto Garcia int64_t nb_clusters = MIN( 328913bec229SAlberto Garcia nb_new_data_clusters, 329013bec229SAlberto Garcia s->l2_slice_size - offset_to_l2_slice_index(s, guest_offset)); 3291772d1f97SMax Reitz QCowL2Meta allocation = { 3292772d1f97SMax Reitz .offset = guest_offset, 3293772d1f97SMax Reitz .alloc_offset = host_offset, 3294772d1f97SMax Reitz .nb_clusters = nb_clusters, 3295772d1f97SMax Reitz }; 3296772d1f97SMax Reitz qemu_co_queue_init(&allocation.dependent_requests); 3297772d1f97SMax Reitz 3298772d1f97SMax Reitz ret = qcow2_alloc_cluster_link_l2(bs, &allocation); 3299772d1f97SMax Reitz if (ret < 0) { 3300772d1f97SMax Reitz error_setg_errno(errp, -ret, "Failed to update L2 tables"); 3301772d1f97SMax Reitz qcow2_free_clusters(bs, host_offset, 3302772d1f97SMax Reitz nb_new_data_clusters * s->cluster_size, 3303772d1f97SMax Reitz QCOW2_DISCARD_OTHER); 3304772d1f97SMax Reitz return ret; 3305772d1f97SMax Reitz } 3306772d1f97SMax Reitz 3307772d1f97SMax Reitz guest_offset += nb_clusters * s->cluster_size; 3308772d1f97SMax Reitz host_offset += nb_clusters * s->cluster_size; 3309772d1f97SMax Reitz nb_new_data_clusters -= nb_clusters; 3310772d1f97SMax Reitz } 3311772d1f97SMax Reitz break; 3312772d1f97SMax Reitz } 3313772d1f97SMax Reitz 331495b98f34SMax Reitz default: 331595b98f34SMax Reitz g_assert_not_reached(); 331695b98f34SMax Reitz } 331795b98f34SMax Reitz 331895b98f34SMax Reitz if (prealloc != PREALLOC_MODE_OFF) { 331995b98f34SMax Reitz /* Flush metadata before actually changing the image size */ 332095b98f34SMax Reitz ret = bdrv_flush(bs); 332195b98f34SMax Reitz if (ret < 0) { 332295b98f34SMax Reitz error_setg_errno(errp, -ret, 332395b98f34SMax Reitz "Failed to flush the preallocated area to disk"); 332495b98f34SMax Reitz return ret; 332595b98f34SMax Reitz } 332695b98f34SMax Reitz } 332795b98f34SMax Reitz 3328419b19d9SStefan Hajnoczi /* write updated header.size */ 3329419b19d9SStefan Hajnoczi offset = cpu_to_be64(offset); 3330d9ca2ea2SKevin Wolf ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, size), 3331419b19d9SStefan Hajnoczi &offset, sizeof(uint64_t)); 3332419b19d9SStefan Hajnoczi if (ret < 0) { 3333f59adb32SMax Reitz error_setg_errno(errp, -ret, "Failed to update the image size"); 3334419b19d9SStefan Hajnoczi return ret; 3335419b19d9SStefan Hajnoczi } 3336419b19d9SStefan Hajnoczi 3337419b19d9SStefan Hajnoczi s->l1_vm_state_index = new_l1_size; 3338419b19d9SStefan Hajnoczi return 0; 3339419b19d9SStefan Hajnoczi } 3340419b19d9SStefan Hajnoczi 334120d97356SBlue Swirl /* XXX: put compressed sectors first, then all the cluster aligned 334220d97356SBlue Swirl tables to avoid losing bytes in alignment */ 3343fcccefc5SPavel Butsykin static coroutine_fn int 3344fcccefc5SPavel Butsykin qcow2_co_pwritev_compressed(BlockDriverState *bs, uint64_t offset, 3345fcccefc5SPavel Butsykin uint64_t bytes, QEMUIOVector *qiov) 334620d97356SBlue Swirl { 3347ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque; 3348fcccefc5SPavel Butsykin QEMUIOVector hd_qiov; 3349fcccefc5SPavel Butsykin struct iovec iov; 335020d97356SBlue Swirl z_stream strm; 335120d97356SBlue Swirl int ret, out_len; 3352fcccefc5SPavel Butsykin uint8_t *buf, *out_buf; 3353d0d5d0e3SEric Blake int64_t cluster_offset; 335420d97356SBlue Swirl 3355fcccefc5SPavel Butsykin if (bytes == 0) { 335620d97356SBlue Swirl /* align end of file to a sector boundary to ease reading with 335720d97356SBlue Swirl sector based I/Os */ 33589a4f4c31SKevin Wolf cluster_offset = bdrv_getlength(bs->file->bs); 3359d0d5d0e3SEric Blake if (cluster_offset < 0) { 3360d0d5d0e3SEric Blake return cluster_offset; 3361d0d5d0e3SEric Blake } 33627ea37c30SMax Reitz return bdrv_truncate(bs->file, cluster_offset, PREALLOC_MODE_OFF, NULL); 336320d97356SBlue Swirl } 336420d97356SBlue Swirl 33653e3b838fSAnton Nefedov if (offset_into_cluster(s, offset)) { 33663e3b838fSAnton Nefedov return -EINVAL; 33673e3b838fSAnton Nefedov } 33683e3b838fSAnton Nefedov 3369fcccefc5SPavel Butsykin buf = qemu_blockalign(bs, s->cluster_size); 3370a2c0ca6fSPavel Butsykin if (bytes != s->cluster_size) { 3371a2c0ca6fSPavel Butsykin if (bytes > s->cluster_size || 3372a2c0ca6fSPavel Butsykin offset + bytes != bs->total_sectors << BDRV_SECTOR_BITS) 3373a2c0ca6fSPavel Butsykin { 3374a2c0ca6fSPavel Butsykin qemu_vfree(buf); 3375a2c0ca6fSPavel Butsykin return -EINVAL; 3376a2c0ca6fSPavel Butsykin } 3377a2c0ca6fSPavel Butsykin /* Zero-pad last write if image size is not cluster aligned */ 3378a2c0ca6fSPavel Butsykin memset(buf + bytes, 0, s->cluster_size - bytes); 3379a2c0ca6fSPavel Butsykin } 33808b2bd093SPavel Butsykin qemu_iovec_to_buf(qiov, 0, buf, bytes); 338120d97356SBlue Swirl 3382ebf7bba0SVladimir Sementsov-Ogievskiy out_buf = g_malloc(s->cluster_size); 338320d97356SBlue Swirl 338420d97356SBlue Swirl /* best compression, small window, no zlib header */ 338520d97356SBlue Swirl memset(&strm, 0, sizeof(strm)); 338620d97356SBlue Swirl ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION, 338720d97356SBlue Swirl Z_DEFLATED, -12, 338820d97356SBlue Swirl 9, Z_DEFAULT_STRATEGY); 338920d97356SBlue Swirl if (ret != 0) { 33908f1efd00SKevin Wolf ret = -EINVAL; 33918f1efd00SKevin Wolf goto fail; 339220d97356SBlue Swirl } 339320d97356SBlue Swirl 339420d97356SBlue Swirl strm.avail_in = s->cluster_size; 339520d97356SBlue Swirl strm.next_in = (uint8_t *)buf; 339620d97356SBlue Swirl strm.avail_out = s->cluster_size; 339720d97356SBlue Swirl strm.next_out = out_buf; 339820d97356SBlue Swirl 339920d97356SBlue Swirl ret = deflate(&strm, Z_FINISH); 340020d97356SBlue Swirl if (ret != Z_STREAM_END && ret != Z_OK) { 340120d97356SBlue Swirl deflateEnd(&strm); 34028f1efd00SKevin Wolf ret = -EINVAL; 34038f1efd00SKevin Wolf goto fail; 340420d97356SBlue Swirl } 340520d97356SBlue Swirl out_len = strm.next_out - out_buf; 340620d97356SBlue Swirl 340720d97356SBlue Swirl deflateEnd(&strm); 340820d97356SBlue Swirl 340920d97356SBlue Swirl if (ret != Z_STREAM_END || out_len >= s->cluster_size) { 341020d97356SBlue Swirl /* could not compress: write normal cluster */ 3411fcccefc5SPavel Butsykin ret = qcow2_co_pwritev(bs, offset, bytes, qiov, 0); 34128f1efd00SKevin Wolf if (ret < 0) { 34138f1efd00SKevin Wolf goto fail; 34148f1efd00SKevin Wolf } 3415fcccefc5SPavel Butsykin goto success; 3416fcccefc5SPavel Butsykin } 3417fcccefc5SPavel Butsykin 3418fcccefc5SPavel Butsykin qemu_co_mutex_lock(&s->lock); 3419fcccefc5SPavel Butsykin cluster_offset = 3420fcccefc5SPavel Butsykin qcow2_alloc_compressed_cluster_offset(bs, offset, out_len); 34218f1efd00SKevin Wolf if (!cluster_offset) { 3422fcccefc5SPavel Butsykin qemu_co_mutex_unlock(&s->lock); 34238f1efd00SKevin Wolf ret = -EIO; 34248f1efd00SKevin Wolf goto fail; 34258f1efd00SKevin Wolf } 342620d97356SBlue Swirl cluster_offset &= s->cluster_offset_mask; 3427cf93980eSMax Reitz 3428231bb267SMax Reitz ret = qcow2_pre_write_overlap_check(bs, 0, cluster_offset, out_len); 3429fcccefc5SPavel Butsykin qemu_co_mutex_unlock(&s->lock); 3430cf93980eSMax Reitz if (ret < 0) { 3431cf93980eSMax Reitz goto fail; 3432cf93980eSMax Reitz } 3433cf93980eSMax Reitz 3434fcccefc5SPavel Butsykin iov = (struct iovec) { 3435fcccefc5SPavel Butsykin .iov_base = out_buf, 3436fcccefc5SPavel Butsykin .iov_len = out_len, 3437fcccefc5SPavel Butsykin }; 3438fcccefc5SPavel Butsykin qemu_iovec_init_external(&hd_qiov, &iov, 1); 3439fcccefc5SPavel Butsykin 344066f82ceeSKevin Wolf BLKDBG_EVENT(bs->file, BLKDBG_WRITE_COMPRESSED); 3441fcccefc5SPavel Butsykin ret = bdrv_co_pwritev(bs->file, cluster_offset, out_len, &hd_qiov, 0); 34428f1efd00SKevin Wolf if (ret < 0) { 34438f1efd00SKevin Wolf goto fail; 344420d97356SBlue Swirl } 3445fcccefc5SPavel Butsykin success: 34468f1efd00SKevin Wolf ret = 0; 34478f1efd00SKevin Wolf fail: 3448fcccefc5SPavel Butsykin qemu_vfree(buf); 34497267c094SAnthony Liguori g_free(out_buf); 34508f1efd00SKevin Wolf return ret; 345120d97356SBlue Swirl } 345220d97356SBlue Swirl 345394054183SMax Reitz static int make_completely_empty(BlockDriverState *bs) 345494054183SMax Reitz { 3455ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque; 3456ed3d2ec9SMax Reitz Error *local_err = NULL; 345794054183SMax Reitz int ret, l1_clusters; 345894054183SMax Reitz int64_t offset; 345994054183SMax Reitz uint64_t *new_reftable = NULL; 346094054183SMax Reitz uint64_t rt_entry, l1_size2; 346194054183SMax Reitz struct { 346294054183SMax Reitz uint64_t l1_offset; 346394054183SMax Reitz uint64_t reftable_offset; 346494054183SMax Reitz uint32_t reftable_clusters; 346594054183SMax Reitz } QEMU_PACKED l1_ofs_rt_ofs_cls; 346694054183SMax Reitz 346794054183SMax Reitz ret = qcow2_cache_empty(bs, s->l2_table_cache); 346894054183SMax Reitz if (ret < 0) { 346994054183SMax Reitz goto fail; 347094054183SMax Reitz } 347194054183SMax Reitz 347294054183SMax Reitz ret = qcow2_cache_empty(bs, s->refcount_block_cache); 347394054183SMax Reitz if (ret < 0) { 347494054183SMax Reitz goto fail; 347594054183SMax Reitz } 347694054183SMax Reitz 347794054183SMax Reitz /* Refcounts will be broken utterly */ 347894054183SMax Reitz ret = qcow2_mark_dirty(bs); 347994054183SMax Reitz if (ret < 0) { 348094054183SMax Reitz goto fail; 348194054183SMax Reitz } 348294054183SMax Reitz 348394054183SMax Reitz BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE); 348494054183SMax Reitz 348594054183SMax Reitz l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / sizeof(uint64_t)); 348694054183SMax Reitz l1_size2 = (uint64_t)s->l1_size * sizeof(uint64_t); 348794054183SMax Reitz 348894054183SMax Reitz /* After this call, neither the in-memory nor the on-disk refcount 348994054183SMax Reitz * information accurately describe the actual references */ 349094054183SMax Reitz 3491720ff280SKevin Wolf ret = bdrv_pwrite_zeroes(bs->file, s->l1_table_offset, 349274021bc4SEric Blake l1_clusters * s->cluster_size, 0); 349394054183SMax Reitz if (ret < 0) { 349494054183SMax Reitz goto fail_broken_refcounts; 349594054183SMax Reitz } 349694054183SMax Reitz memset(s->l1_table, 0, l1_size2); 349794054183SMax Reitz 349894054183SMax Reitz BLKDBG_EVENT(bs->file, BLKDBG_EMPTY_IMAGE_PREPARE); 349994054183SMax Reitz 350094054183SMax Reitz /* Overwrite enough clusters at the beginning of the sectors to place 350194054183SMax Reitz * the refcount table, a refcount block and the L1 table in; this may 350294054183SMax Reitz * overwrite parts of the existing refcount and L1 table, which is not 350394054183SMax Reitz * an issue because the dirty flag is set, complete data loss is in fact 350494054183SMax Reitz * desired and partial data loss is consequently fine as well */ 3505720ff280SKevin Wolf ret = bdrv_pwrite_zeroes(bs->file, s->cluster_size, 350674021bc4SEric Blake (2 + l1_clusters) * s->cluster_size, 0); 350794054183SMax Reitz /* This call (even if it failed overall) may have overwritten on-disk 350894054183SMax Reitz * refcount structures; in that case, the in-memory refcount information 350994054183SMax Reitz * will probably differ from the on-disk information which makes the BDS 351094054183SMax Reitz * unusable */ 351194054183SMax Reitz if (ret < 0) { 351294054183SMax Reitz goto fail_broken_refcounts; 351394054183SMax Reitz } 351494054183SMax Reitz 351594054183SMax Reitz BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE); 351694054183SMax Reitz BLKDBG_EVENT(bs->file, BLKDBG_REFTABLE_UPDATE); 351794054183SMax Reitz 351894054183SMax Reitz /* "Create" an empty reftable (one cluster) directly after the image 351994054183SMax Reitz * header and an empty L1 table three clusters after the image header; 352094054183SMax Reitz * the cluster between those two will be used as the first refblock */ 3521f1f7a1ddSPeter Maydell l1_ofs_rt_ofs_cls.l1_offset = cpu_to_be64(3 * s->cluster_size); 3522f1f7a1ddSPeter Maydell l1_ofs_rt_ofs_cls.reftable_offset = cpu_to_be64(s->cluster_size); 3523f1f7a1ddSPeter Maydell l1_ofs_rt_ofs_cls.reftable_clusters = cpu_to_be32(1); 3524d9ca2ea2SKevin Wolf ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, l1_table_offset), 352594054183SMax Reitz &l1_ofs_rt_ofs_cls, sizeof(l1_ofs_rt_ofs_cls)); 352694054183SMax Reitz if (ret < 0) { 352794054183SMax Reitz goto fail_broken_refcounts; 352894054183SMax Reitz } 352994054183SMax Reitz 353094054183SMax Reitz s->l1_table_offset = 3 * s->cluster_size; 353194054183SMax Reitz 353294054183SMax Reitz new_reftable = g_try_new0(uint64_t, s->cluster_size / sizeof(uint64_t)); 353394054183SMax Reitz if (!new_reftable) { 353494054183SMax Reitz ret = -ENOMEM; 353594054183SMax Reitz goto fail_broken_refcounts; 353694054183SMax Reitz } 353794054183SMax Reitz 353894054183SMax Reitz s->refcount_table_offset = s->cluster_size; 353994054183SMax Reitz s->refcount_table_size = s->cluster_size / sizeof(uint64_t); 35407061a078SAlberto Garcia s->max_refcount_table_index = 0; 354194054183SMax Reitz 354294054183SMax Reitz g_free(s->refcount_table); 354394054183SMax Reitz s->refcount_table = new_reftable; 354494054183SMax Reitz new_reftable = NULL; 354594054183SMax Reitz 354694054183SMax Reitz /* Now the in-memory refcount information again corresponds to the on-disk 354794054183SMax Reitz * information (reftable is empty and no refblocks (the refblock cache is 354894054183SMax Reitz * empty)); however, this means some clusters (e.g. the image header) are 354994054183SMax Reitz * referenced, but not refcounted, but the normal qcow2 code assumes that 355094054183SMax Reitz * the in-memory information is always correct */ 355194054183SMax Reitz 355294054183SMax Reitz BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_ALLOC); 355394054183SMax Reitz 355494054183SMax Reitz /* Enter the first refblock into the reftable */ 355594054183SMax Reitz rt_entry = cpu_to_be64(2 * s->cluster_size); 3556d9ca2ea2SKevin Wolf ret = bdrv_pwrite_sync(bs->file, s->cluster_size, 355794054183SMax Reitz &rt_entry, sizeof(rt_entry)); 355894054183SMax Reitz if (ret < 0) { 355994054183SMax Reitz goto fail_broken_refcounts; 356094054183SMax Reitz } 356194054183SMax Reitz s->refcount_table[0] = 2 * s->cluster_size; 356294054183SMax Reitz 356394054183SMax Reitz s->free_cluster_index = 0; 356494054183SMax Reitz assert(3 + l1_clusters <= s->refcount_block_size); 356594054183SMax Reitz offset = qcow2_alloc_clusters(bs, 3 * s->cluster_size + l1_size2); 356694054183SMax Reitz if (offset < 0) { 356794054183SMax Reitz ret = offset; 356894054183SMax Reitz goto fail_broken_refcounts; 356994054183SMax Reitz } else if (offset > 0) { 357094054183SMax Reitz error_report("First cluster in emptied image is in use"); 357194054183SMax Reitz abort(); 357294054183SMax Reitz } 357394054183SMax Reitz 357494054183SMax Reitz /* Now finally the in-memory information corresponds to the on-disk 357594054183SMax Reitz * structures and is correct */ 357694054183SMax Reitz ret = qcow2_mark_clean(bs); 357794054183SMax Reitz if (ret < 0) { 357894054183SMax Reitz goto fail; 357994054183SMax Reitz } 358094054183SMax Reitz 3581ed3d2ec9SMax Reitz ret = bdrv_truncate(bs->file, (3 + l1_clusters) * s->cluster_size, 35827ea37c30SMax Reitz PREALLOC_MODE_OFF, &local_err); 358394054183SMax Reitz if (ret < 0) { 3584ed3d2ec9SMax Reitz error_report_err(local_err); 358594054183SMax Reitz goto fail; 358694054183SMax Reitz } 358794054183SMax Reitz 358894054183SMax Reitz return 0; 358994054183SMax Reitz 359094054183SMax Reitz fail_broken_refcounts: 359194054183SMax Reitz /* The BDS is unusable at this point. If we wanted to make it usable, we 359294054183SMax Reitz * would have to call qcow2_refcount_close(), qcow2_refcount_init(), 359394054183SMax Reitz * qcow2_check_refcounts(), qcow2_refcount_close() and qcow2_refcount_init() 359494054183SMax Reitz * again. However, because the functions which could have caused this error 359594054183SMax Reitz * path to be taken are used by those functions as well, it's very likely 359694054183SMax Reitz * that that sequence will fail as well. Therefore, just eject the BDS. */ 359794054183SMax Reitz bs->drv = NULL; 359894054183SMax Reitz 359994054183SMax Reitz fail: 360094054183SMax Reitz g_free(new_reftable); 360194054183SMax Reitz return ret; 360294054183SMax Reitz } 360394054183SMax Reitz 3604491d27e2SMax Reitz static int qcow2_make_empty(BlockDriverState *bs) 3605491d27e2SMax Reitz { 3606ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque; 3607d2cb36afSEric Blake uint64_t offset, end_offset; 3608d2cb36afSEric Blake int step = QEMU_ALIGN_DOWN(INT_MAX, s->cluster_size); 360994054183SMax Reitz int l1_clusters, ret = 0; 3610491d27e2SMax Reitz 361194054183SMax Reitz l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / sizeof(uint64_t)); 361294054183SMax Reitz 36134096974eSEric Blake if (s->qcow_version >= 3 && !s->snapshots && !s->nb_bitmaps && 3614f0603329SDaniel P. Berrange 3 + l1_clusters <= s->refcount_block_size && 3615f0603329SDaniel P. Berrange s->crypt_method_header != QCOW_CRYPT_LUKS) { 36164096974eSEric Blake /* The following function only works for qcow2 v3 images (it 36174096974eSEric Blake * requires the dirty flag) and only as long as there are no 36184096974eSEric Blake * features that reserve extra clusters (such as snapshots, 36194096974eSEric Blake * LUKS header, or persistent bitmaps), because it completely 36204096974eSEric Blake * empties the image. Furthermore, the L1 table and three 36214096974eSEric Blake * additional clusters (image header, refcount table, one 36224096974eSEric Blake * refcount block) have to fit inside one refcount block. */ 362394054183SMax Reitz return make_completely_empty(bs); 362494054183SMax Reitz } 362594054183SMax Reitz 362694054183SMax Reitz /* This fallback code simply discards every active cluster; this is slow, 362794054183SMax Reitz * but works in all cases */ 3628d2cb36afSEric Blake end_offset = bs->total_sectors * BDRV_SECTOR_SIZE; 3629d2cb36afSEric Blake for (offset = 0; offset < end_offset; offset += step) { 3630491d27e2SMax Reitz /* As this function is generally used after committing an external 3631491d27e2SMax Reitz * snapshot, QCOW2_DISCARD_SNAPSHOT seems appropriate. Also, the 3632491d27e2SMax Reitz * default action for this kind of discard is to pass the discard, 3633491d27e2SMax Reitz * which will ideally result in an actually smaller image file, as 3634491d27e2SMax Reitz * is probably desired. */ 3635d2cb36afSEric Blake ret = qcow2_cluster_discard(bs, offset, MIN(step, end_offset - offset), 3636491d27e2SMax Reitz QCOW2_DISCARD_SNAPSHOT, true); 3637491d27e2SMax Reitz if (ret < 0) { 3638491d27e2SMax Reitz break; 3639491d27e2SMax Reitz } 3640491d27e2SMax Reitz } 3641491d27e2SMax Reitz 3642491d27e2SMax Reitz return ret; 3643491d27e2SMax Reitz } 3644491d27e2SMax Reitz 3645a968168cSDong Xu Wang static coroutine_fn int qcow2_co_flush_to_os(BlockDriverState *bs) 364620d97356SBlue Swirl { 3647ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque; 364829c1a730SKevin Wolf int ret; 364929c1a730SKevin Wolf 36508b94ff85SPaolo Bonzini qemu_co_mutex_lock(&s->lock); 3651f3c3b87dSDenis V. Lunev ret = qcow2_cache_write(bs, s->l2_table_cache); 365229c1a730SKevin Wolf if (ret < 0) { 3653c95de7e2SDong Xu Wang qemu_co_mutex_unlock(&s->lock); 36548b94ff85SPaolo Bonzini return ret; 365529c1a730SKevin Wolf } 365629c1a730SKevin Wolf 3657bfe8043eSStefan Hajnoczi if (qcow2_need_accurate_refcounts(s)) { 3658f3c3b87dSDenis V. Lunev ret = qcow2_cache_write(bs, s->refcount_block_cache); 365929c1a730SKevin Wolf if (ret < 0) { 3660c95de7e2SDong Xu Wang qemu_co_mutex_unlock(&s->lock); 36618b94ff85SPaolo Bonzini return ret; 366229c1a730SKevin Wolf } 3663bfe8043eSStefan Hajnoczi } 36648b94ff85SPaolo Bonzini qemu_co_mutex_unlock(&s->lock); 366529c1a730SKevin Wolf 3666eb489bb1SKevin Wolf return 0; 3667eb489bb1SKevin Wolf } 3668eb489bb1SKevin Wolf 3669c501c352SStefan Hajnoczi static BlockMeasureInfo *qcow2_measure(QemuOpts *opts, BlockDriverState *in_bs, 3670c501c352SStefan Hajnoczi Error **errp) 3671c501c352SStefan Hajnoczi { 3672c501c352SStefan Hajnoczi Error *local_err = NULL; 3673c501c352SStefan Hajnoczi BlockMeasureInfo *info; 3674c501c352SStefan Hajnoczi uint64_t required = 0; /* bytes that contribute to required size */ 3675c501c352SStefan Hajnoczi uint64_t virtual_size; /* disk size as seen by guest */ 3676c501c352SStefan Hajnoczi uint64_t refcount_bits; 3677c501c352SStefan Hajnoczi uint64_t l2_tables; 3678c501c352SStefan Hajnoczi size_t cluster_size; 3679c501c352SStefan Hajnoczi int version; 3680c501c352SStefan Hajnoczi char *optstr; 3681c501c352SStefan Hajnoczi PreallocMode prealloc; 3682c501c352SStefan Hajnoczi bool has_backing_file; 3683c501c352SStefan Hajnoczi 3684c501c352SStefan Hajnoczi /* Parse image creation options */ 3685c501c352SStefan Hajnoczi cluster_size = qcow2_opt_get_cluster_size_del(opts, &local_err); 3686c501c352SStefan Hajnoczi if (local_err) { 3687c501c352SStefan Hajnoczi goto err; 3688c501c352SStefan Hajnoczi } 3689c501c352SStefan Hajnoczi 3690c501c352SStefan Hajnoczi version = qcow2_opt_get_version_del(opts, &local_err); 3691c501c352SStefan Hajnoczi if (local_err) { 3692c501c352SStefan Hajnoczi goto err; 3693c501c352SStefan Hajnoczi } 3694c501c352SStefan Hajnoczi 3695c501c352SStefan Hajnoczi refcount_bits = qcow2_opt_get_refcount_bits_del(opts, version, &local_err); 3696c501c352SStefan Hajnoczi if (local_err) { 3697c501c352SStefan Hajnoczi goto err; 3698c501c352SStefan Hajnoczi } 3699c501c352SStefan Hajnoczi 3700c501c352SStefan Hajnoczi optstr = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC); 3701f7abe0ecSMarc-André Lureau prealloc = qapi_enum_parse(&PreallocMode_lookup, optstr, 370206c60b6cSMarkus Armbruster PREALLOC_MODE_OFF, &local_err); 3703c501c352SStefan Hajnoczi g_free(optstr); 3704c501c352SStefan Hajnoczi if (local_err) { 3705c501c352SStefan Hajnoczi goto err; 3706c501c352SStefan Hajnoczi } 3707c501c352SStefan Hajnoczi 3708c501c352SStefan Hajnoczi optstr = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE); 3709c501c352SStefan Hajnoczi has_backing_file = !!optstr; 3710c501c352SStefan Hajnoczi g_free(optstr); 3711c501c352SStefan Hajnoczi 3712c501c352SStefan Hajnoczi virtual_size = align_offset(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0), 3713c501c352SStefan Hajnoczi cluster_size); 3714c501c352SStefan Hajnoczi 3715c501c352SStefan Hajnoczi /* Check that virtual disk size is valid */ 3716c501c352SStefan Hajnoczi l2_tables = DIV_ROUND_UP(virtual_size / cluster_size, 3717c501c352SStefan Hajnoczi cluster_size / sizeof(uint64_t)); 3718c501c352SStefan Hajnoczi if (l2_tables * sizeof(uint64_t) > QCOW_MAX_L1_SIZE) { 3719c501c352SStefan Hajnoczi error_setg(&local_err, "The image size is too large " 3720c501c352SStefan Hajnoczi "(try using a larger cluster size)"); 3721c501c352SStefan Hajnoczi goto err; 3722c501c352SStefan Hajnoczi } 3723c501c352SStefan Hajnoczi 3724c501c352SStefan Hajnoczi /* Account for input image */ 3725c501c352SStefan Hajnoczi if (in_bs) { 3726c501c352SStefan Hajnoczi int64_t ssize = bdrv_getlength(in_bs); 3727c501c352SStefan Hajnoczi if (ssize < 0) { 3728c501c352SStefan Hajnoczi error_setg_errno(&local_err, -ssize, 3729c501c352SStefan Hajnoczi "Unable to get image virtual_size"); 3730c501c352SStefan Hajnoczi goto err; 3731c501c352SStefan Hajnoczi } 3732c501c352SStefan Hajnoczi 3733c501c352SStefan Hajnoczi virtual_size = align_offset(ssize, cluster_size); 3734c501c352SStefan Hajnoczi 3735c501c352SStefan Hajnoczi if (has_backing_file) { 3736c501c352SStefan Hajnoczi /* We don't how much of the backing chain is shared by the input 3737c501c352SStefan Hajnoczi * image and the new image file. In the worst case the new image's 3738c501c352SStefan Hajnoczi * backing file has nothing in common with the input image. Be 3739c501c352SStefan Hajnoczi * conservative and assume all clusters need to be written. 3740c501c352SStefan Hajnoczi */ 3741c501c352SStefan Hajnoczi required = virtual_size; 3742c501c352SStefan Hajnoczi } else { 3743b85ee453SEric Blake int64_t offset; 374431826642SEric Blake int64_t pnum = 0; 3745c501c352SStefan Hajnoczi 374631826642SEric Blake for (offset = 0; offset < ssize; offset += pnum) { 374731826642SEric Blake int ret; 3748c501c352SStefan Hajnoczi 374931826642SEric Blake ret = bdrv_block_status_above(in_bs, NULL, offset, 375031826642SEric Blake ssize - offset, &pnum, NULL, 375131826642SEric Blake NULL); 3752c501c352SStefan Hajnoczi if (ret < 0) { 3753c501c352SStefan Hajnoczi error_setg_errno(&local_err, -ret, 3754c501c352SStefan Hajnoczi "Unable to get block status"); 3755c501c352SStefan Hajnoczi goto err; 3756c501c352SStefan Hajnoczi } 3757c501c352SStefan Hajnoczi 3758c501c352SStefan Hajnoczi if (ret & BDRV_BLOCK_ZERO) { 3759c501c352SStefan Hajnoczi /* Skip zero regions (safe with no backing file) */ 3760c501c352SStefan Hajnoczi } else if ((ret & (BDRV_BLOCK_DATA | BDRV_BLOCK_ALLOCATED)) == 3761c501c352SStefan Hajnoczi (BDRV_BLOCK_DATA | BDRV_BLOCK_ALLOCATED)) { 3762c501c352SStefan Hajnoczi /* Extend pnum to end of cluster for next iteration */ 376331826642SEric Blake pnum = ROUND_UP(offset + pnum, cluster_size) - offset; 3764c501c352SStefan Hajnoczi 3765c501c352SStefan Hajnoczi /* Count clusters we've seen */ 376631826642SEric Blake required += offset % cluster_size + pnum; 3767c501c352SStefan Hajnoczi } 3768c501c352SStefan Hajnoczi } 3769c501c352SStefan Hajnoczi } 3770c501c352SStefan Hajnoczi } 3771c501c352SStefan Hajnoczi 3772c501c352SStefan Hajnoczi /* Take into account preallocation. Nothing special is needed for 3773c501c352SStefan Hajnoczi * PREALLOC_MODE_METADATA since metadata is always counted. 3774c501c352SStefan Hajnoczi */ 3775c501c352SStefan Hajnoczi if (prealloc == PREALLOC_MODE_FULL || prealloc == PREALLOC_MODE_FALLOC) { 3776c501c352SStefan Hajnoczi required = virtual_size; 3777c501c352SStefan Hajnoczi } 3778c501c352SStefan Hajnoczi 3779c501c352SStefan Hajnoczi info = g_new(BlockMeasureInfo, 1); 3780c501c352SStefan Hajnoczi info->fully_allocated = 3781c501c352SStefan Hajnoczi qcow2_calc_prealloc_size(virtual_size, cluster_size, 3782c501c352SStefan Hajnoczi ctz32(refcount_bits)); 3783c501c352SStefan Hajnoczi 3784c501c352SStefan Hajnoczi /* Remove data clusters that are not required. This overestimates the 3785c501c352SStefan Hajnoczi * required size because metadata needed for the fully allocated file is 3786c501c352SStefan Hajnoczi * still counted. 3787c501c352SStefan Hajnoczi */ 3788c501c352SStefan Hajnoczi info->required = info->fully_allocated - virtual_size + required; 3789c501c352SStefan Hajnoczi return info; 3790c501c352SStefan Hajnoczi 3791c501c352SStefan Hajnoczi err: 3792c501c352SStefan Hajnoczi error_propagate(errp, local_err); 3793c501c352SStefan Hajnoczi return NULL; 3794c501c352SStefan Hajnoczi } 3795c501c352SStefan Hajnoczi 37967c80ab3fSJes Sorensen static int qcow2_get_info(BlockDriverState *bs, BlockDriverInfo *bdi) 379720d97356SBlue Swirl { 3798ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque; 379995de6d70SPaolo Bonzini bdi->unallocated_blocks_are_zero = true; 380020d97356SBlue Swirl bdi->cluster_size = s->cluster_size; 38017c80ab3fSJes Sorensen bdi->vm_state_offset = qcow2_vm_state_offset(s); 380220d97356SBlue Swirl return 0; 380320d97356SBlue Swirl } 380420d97356SBlue Swirl 380537764dfbSMax Reitz static ImageInfoSpecific *qcow2_get_specific_info(BlockDriverState *bs) 380637764dfbSMax Reitz { 3807ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque; 38080a12f6f8SDaniel P. Berrange ImageInfoSpecific *spec_info; 38090a12f6f8SDaniel P. Berrange QCryptoBlockInfo *encrypt_info = NULL; 381037764dfbSMax Reitz 38110a12f6f8SDaniel P. Berrange if (s->crypto != NULL) { 38120a12f6f8SDaniel P. Berrange encrypt_info = qcrypto_block_get_info(s->crypto, &error_abort); 38130a12f6f8SDaniel P. Berrange } 38140a12f6f8SDaniel P. Berrange 38150a12f6f8SDaniel P. Berrange spec_info = g_new(ImageInfoSpecific, 1); 381637764dfbSMax Reitz *spec_info = (ImageInfoSpecific){ 38176a8f9661SEric Blake .type = IMAGE_INFO_SPECIFIC_KIND_QCOW2, 381832bafa8fSEric Blake .u.qcow2.data = g_new(ImageInfoSpecificQCow2, 1), 381937764dfbSMax Reitz }; 382037764dfbSMax Reitz if (s->qcow_version == 2) { 382132bafa8fSEric Blake *spec_info->u.qcow2.data = (ImageInfoSpecificQCow2){ 382237764dfbSMax Reitz .compat = g_strdup("0.10"), 38230709c5a1SMax Reitz .refcount_bits = s->refcount_bits, 382437764dfbSMax Reitz }; 382537764dfbSMax Reitz } else if (s->qcow_version == 3) { 382632bafa8fSEric Blake *spec_info->u.qcow2.data = (ImageInfoSpecificQCow2){ 382737764dfbSMax Reitz .compat = g_strdup("1.1"), 382837764dfbSMax Reitz .lazy_refcounts = s->compatible_features & 382937764dfbSMax Reitz QCOW2_COMPAT_LAZY_REFCOUNTS, 383037764dfbSMax Reitz .has_lazy_refcounts = true, 38319009b196SMax Reitz .corrupt = s->incompatible_features & 38329009b196SMax Reitz QCOW2_INCOMPAT_CORRUPT, 38339009b196SMax Reitz .has_corrupt = true, 38340709c5a1SMax Reitz .refcount_bits = s->refcount_bits, 383537764dfbSMax Reitz }; 3836b1fc8f93SDenis V. Lunev } else { 3837b1fc8f93SDenis V. Lunev /* if this assertion fails, this probably means a new version was 3838b1fc8f93SDenis V. Lunev * added without having it covered here */ 3839b1fc8f93SDenis V. Lunev assert(false); 384037764dfbSMax Reitz } 384137764dfbSMax Reitz 38420a12f6f8SDaniel P. Berrange if (encrypt_info) { 38430a12f6f8SDaniel P. Berrange ImageInfoSpecificQCow2Encryption *qencrypt = 38440a12f6f8SDaniel P. Berrange g_new(ImageInfoSpecificQCow2Encryption, 1); 38450a12f6f8SDaniel P. Berrange switch (encrypt_info->format) { 38460a12f6f8SDaniel P. Berrange case Q_CRYPTO_BLOCK_FORMAT_QCOW: 38470a12f6f8SDaniel P. Berrange qencrypt->format = BLOCKDEV_QCOW2_ENCRYPTION_FORMAT_AES; 38480a12f6f8SDaniel P. Berrange qencrypt->u.aes = encrypt_info->u.qcow; 38490a12f6f8SDaniel P. Berrange break; 38500a12f6f8SDaniel P. Berrange case Q_CRYPTO_BLOCK_FORMAT_LUKS: 38510a12f6f8SDaniel P. Berrange qencrypt->format = BLOCKDEV_QCOW2_ENCRYPTION_FORMAT_LUKS; 38520a12f6f8SDaniel P. Berrange qencrypt->u.luks = encrypt_info->u.luks; 38530a12f6f8SDaniel P. Berrange break; 38540a12f6f8SDaniel P. Berrange default: 38550a12f6f8SDaniel P. Berrange abort(); 38560a12f6f8SDaniel P. Berrange } 38570a12f6f8SDaniel P. Berrange /* Since we did shallow copy above, erase any pointers 38580a12f6f8SDaniel P. Berrange * in the original info */ 38590a12f6f8SDaniel P. Berrange memset(&encrypt_info->u, 0, sizeof(encrypt_info->u)); 38600a12f6f8SDaniel P. Berrange qapi_free_QCryptoBlockInfo(encrypt_info); 38610a12f6f8SDaniel P. Berrange 38620a12f6f8SDaniel P. Berrange spec_info->u.qcow2.data->has_encrypt = true; 38630a12f6f8SDaniel P. Berrange spec_info->u.qcow2.data->encrypt = qencrypt; 38640a12f6f8SDaniel P. Berrange } 38650a12f6f8SDaniel P. Berrange 386637764dfbSMax Reitz return spec_info; 386737764dfbSMax Reitz } 386837764dfbSMax Reitz 3869cf8074b3SKevin Wolf static int qcow2_save_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, 3870cf8074b3SKevin Wolf int64_t pos) 387120d97356SBlue Swirl { 3872ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque; 387320d97356SBlue Swirl 387466f82ceeSKevin Wolf BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_SAVE); 3875734a7758SKevin Wolf return bs->drv->bdrv_co_pwritev(bs, qcow2_vm_state_offset(s) + pos, 3876734a7758SKevin Wolf qiov->size, qiov, 0); 387720d97356SBlue Swirl } 387820d97356SBlue Swirl 38795ddda0b8SKevin Wolf static int qcow2_load_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, 38805ddda0b8SKevin Wolf int64_t pos) 388120d97356SBlue Swirl { 3882ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque; 388320d97356SBlue Swirl 388466f82ceeSKevin Wolf BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_LOAD); 3885734a7758SKevin Wolf return bs->drv->bdrv_co_preadv(bs, qcow2_vm_state_offset(s) + pos, 3886734a7758SKevin Wolf qiov->size, qiov, 0); 388720d97356SBlue Swirl } 388820d97356SBlue Swirl 38899296b3edSMax Reitz /* 38909296b3edSMax Reitz * Downgrades an image's version. To achieve this, any incompatible features 38919296b3edSMax Reitz * have to be removed. 38929296b3edSMax Reitz */ 38934057a2b2SMax Reitz static int qcow2_downgrade(BlockDriverState *bs, int target_version, 38948b13976dSMax Reitz BlockDriverAmendStatusCB *status_cb, void *cb_opaque) 38959296b3edSMax Reitz { 3896ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque; 38979296b3edSMax Reitz int current_version = s->qcow_version; 38989296b3edSMax Reitz int ret; 38999296b3edSMax Reitz 39009296b3edSMax Reitz if (target_version == current_version) { 39019296b3edSMax Reitz return 0; 39029296b3edSMax Reitz } else if (target_version > current_version) { 39039296b3edSMax Reitz return -EINVAL; 39049296b3edSMax Reitz } else if (target_version != 2) { 39059296b3edSMax Reitz return -EINVAL; 39069296b3edSMax Reitz } 39079296b3edSMax Reitz 39089296b3edSMax Reitz if (s->refcount_order != 4) { 390961ce55fcSMax Reitz error_report("compat=0.10 requires refcount_bits=16"); 39109296b3edSMax Reitz return -ENOTSUP; 39119296b3edSMax Reitz } 39129296b3edSMax Reitz 39139296b3edSMax Reitz /* clear incompatible features */ 39149296b3edSMax Reitz if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) { 39159296b3edSMax Reitz ret = qcow2_mark_clean(bs); 39169296b3edSMax Reitz if (ret < 0) { 39179296b3edSMax Reitz return ret; 39189296b3edSMax Reitz } 39199296b3edSMax Reitz } 39209296b3edSMax Reitz 39219296b3edSMax Reitz /* with QCOW2_INCOMPAT_CORRUPT, it is pretty much impossible to get here in 39229296b3edSMax Reitz * the first place; if that happens nonetheless, returning -ENOTSUP is the 39239296b3edSMax Reitz * best thing to do anyway */ 39249296b3edSMax Reitz 39259296b3edSMax Reitz if (s->incompatible_features) { 39269296b3edSMax Reitz return -ENOTSUP; 39279296b3edSMax Reitz } 39289296b3edSMax Reitz 39299296b3edSMax Reitz /* since we can ignore compatible features, we can set them to 0 as well */ 39309296b3edSMax Reitz s->compatible_features = 0; 39319296b3edSMax Reitz /* if lazy refcounts have been used, they have already been fixed through 39329296b3edSMax Reitz * clearing the dirty flag */ 39339296b3edSMax Reitz 39349296b3edSMax Reitz /* clearing autoclear features is trivial */ 39359296b3edSMax Reitz s->autoclear_features = 0; 39369296b3edSMax Reitz 39378b13976dSMax Reitz ret = qcow2_expand_zero_clusters(bs, status_cb, cb_opaque); 39389296b3edSMax Reitz if (ret < 0) { 39399296b3edSMax Reitz return ret; 39409296b3edSMax Reitz } 39419296b3edSMax Reitz 39429296b3edSMax Reitz s->qcow_version = target_version; 39439296b3edSMax Reitz ret = qcow2_update_header(bs); 39449296b3edSMax Reitz if (ret < 0) { 39459296b3edSMax Reitz s->qcow_version = current_version; 39469296b3edSMax Reitz return ret; 39479296b3edSMax Reitz } 39489296b3edSMax Reitz return 0; 39499296b3edSMax Reitz } 39509296b3edSMax Reitz 3951c293a809SMax Reitz typedef enum Qcow2AmendOperation { 3952c293a809SMax Reitz /* This is the value Qcow2AmendHelperCBInfo::last_operation will be 3953c293a809SMax Reitz * statically initialized to so that the helper CB can discern the first 3954c293a809SMax Reitz * invocation from an operation change */ 3955c293a809SMax Reitz QCOW2_NO_OPERATION = 0, 3956c293a809SMax Reitz 395761ce55fcSMax Reitz QCOW2_CHANGING_REFCOUNT_ORDER, 3958c293a809SMax Reitz QCOW2_DOWNGRADING, 3959c293a809SMax Reitz } Qcow2AmendOperation; 3960c293a809SMax Reitz 3961c293a809SMax Reitz typedef struct Qcow2AmendHelperCBInfo { 3962c293a809SMax Reitz /* The code coordinating the amend operations should only modify 3963c293a809SMax Reitz * these four fields; the rest will be managed by the CB */ 3964c293a809SMax Reitz BlockDriverAmendStatusCB *original_status_cb; 3965c293a809SMax Reitz void *original_cb_opaque; 3966c293a809SMax Reitz 3967c293a809SMax Reitz Qcow2AmendOperation current_operation; 3968c293a809SMax Reitz 3969c293a809SMax Reitz /* Total number of operations to perform (only set once) */ 3970c293a809SMax Reitz int total_operations; 3971c293a809SMax Reitz 3972c293a809SMax Reitz /* The following fields are managed by the CB */ 3973c293a809SMax Reitz 3974c293a809SMax Reitz /* Number of operations completed */ 3975c293a809SMax Reitz int operations_completed; 3976c293a809SMax Reitz 3977c293a809SMax Reitz /* Cumulative offset of all completed operations */ 3978c293a809SMax Reitz int64_t offset_completed; 3979c293a809SMax Reitz 3980c293a809SMax Reitz Qcow2AmendOperation last_operation; 3981c293a809SMax Reitz int64_t last_work_size; 3982c293a809SMax Reitz } Qcow2AmendHelperCBInfo; 3983c293a809SMax Reitz 3984c293a809SMax Reitz static void qcow2_amend_helper_cb(BlockDriverState *bs, 3985c293a809SMax Reitz int64_t operation_offset, 3986c293a809SMax Reitz int64_t operation_work_size, void *opaque) 3987c293a809SMax Reitz { 3988c293a809SMax Reitz Qcow2AmendHelperCBInfo *info = opaque; 3989c293a809SMax Reitz int64_t current_work_size; 3990c293a809SMax Reitz int64_t projected_work_size; 3991c293a809SMax Reitz 3992c293a809SMax Reitz if (info->current_operation != info->last_operation) { 3993c293a809SMax Reitz if (info->last_operation != QCOW2_NO_OPERATION) { 3994c293a809SMax Reitz info->offset_completed += info->last_work_size; 3995c293a809SMax Reitz info->operations_completed++; 3996c293a809SMax Reitz } 3997c293a809SMax Reitz 3998c293a809SMax Reitz info->last_operation = info->current_operation; 3999c293a809SMax Reitz } 4000c293a809SMax Reitz 4001c293a809SMax Reitz assert(info->total_operations > 0); 4002c293a809SMax Reitz assert(info->operations_completed < info->total_operations); 4003c293a809SMax Reitz 4004c293a809SMax Reitz info->last_work_size = operation_work_size; 4005c293a809SMax Reitz 4006c293a809SMax Reitz current_work_size = info->offset_completed + operation_work_size; 4007c293a809SMax Reitz 4008c293a809SMax Reitz /* current_work_size is the total work size for (operations_completed + 1) 4009c293a809SMax Reitz * operations (which includes this one), so multiply it by the number of 4010c293a809SMax Reitz * operations not covered and divide it by the number of operations 4011c293a809SMax Reitz * covered to get a projection for the operations not covered */ 4012c293a809SMax Reitz projected_work_size = current_work_size * (info->total_operations - 4013c293a809SMax Reitz info->operations_completed - 1) 4014c293a809SMax Reitz / (info->operations_completed + 1); 4015c293a809SMax Reitz 4016c293a809SMax Reitz info->original_status_cb(bs, info->offset_completed + operation_offset, 4017c293a809SMax Reitz current_work_size + projected_work_size, 4018c293a809SMax Reitz info->original_cb_opaque); 4019c293a809SMax Reitz } 4020c293a809SMax Reitz 402177485434SMax Reitz static int qcow2_amend_options(BlockDriverState *bs, QemuOpts *opts, 40228b13976dSMax Reitz BlockDriverAmendStatusCB *status_cb, 40238b13976dSMax Reitz void *cb_opaque) 40249296b3edSMax Reitz { 4025ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque; 40269296b3edSMax Reitz int old_version = s->qcow_version, new_version = old_version; 40279296b3edSMax Reitz uint64_t new_size = 0; 40289296b3edSMax Reitz const char *backing_file = NULL, *backing_format = NULL; 40299296b3edSMax Reitz bool lazy_refcounts = s->use_lazy_refcounts; 40301bd0e2d1SChunyan Liu const char *compat = NULL; 40311bd0e2d1SChunyan Liu uint64_t cluster_size = s->cluster_size; 40321bd0e2d1SChunyan Liu bool encrypt; 40334652b8f3SDaniel P. Berrange int encformat; 403461ce55fcSMax Reitz int refcount_bits = s->refcount_bits; 4035d7086422SKevin Wolf Error *local_err = NULL; 40369296b3edSMax Reitz int ret; 40371bd0e2d1SChunyan Liu QemuOptDesc *desc = opts->list->desc; 4038c293a809SMax Reitz Qcow2AmendHelperCBInfo helper_cb_info; 40399296b3edSMax Reitz 40401bd0e2d1SChunyan Liu while (desc && desc->name) { 40411bd0e2d1SChunyan Liu if (!qemu_opt_find(opts, desc->name)) { 40429296b3edSMax Reitz /* only change explicitly defined options */ 40431bd0e2d1SChunyan Liu desc++; 40449296b3edSMax Reitz continue; 40459296b3edSMax Reitz } 40469296b3edSMax Reitz 40478a17b83cSMax Reitz if (!strcmp(desc->name, BLOCK_OPT_COMPAT_LEVEL)) { 40488a17b83cSMax Reitz compat = qemu_opt_get(opts, BLOCK_OPT_COMPAT_LEVEL); 40491bd0e2d1SChunyan Liu if (!compat) { 40509296b3edSMax Reitz /* preserve default */ 40511bd0e2d1SChunyan Liu } else if (!strcmp(compat, "0.10")) { 40529296b3edSMax Reitz new_version = 2; 40531bd0e2d1SChunyan Liu } else if (!strcmp(compat, "1.1")) { 40549296b3edSMax Reitz new_version = 3; 40559296b3edSMax Reitz } else { 405629d72431SMax Reitz error_report("Unknown compatibility level %s", compat); 40579296b3edSMax Reitz return -EINVAL; 40589296b3edSMax Reitz } 40598a17b83cSMax Reitz } else if (!strcmp(desc->name, BLOCK_OPT_PREALLOC)) { 406029d72431SMax Reitz error_report("Cannot change preallocation mode"); 40619296b3edSMax Reitz return -ENOTSUP; 40628a17b83cSMax Reitz } else if (!strcmp(desc->name, BLOCK_OPT_SIZE)) { 40638a17b83cSMax Reitz new_size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, 0); 40648a17b83cSMax Reitz } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FILE)) { 40658a17b83cSMax Reitz backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE); 40668a17b83cSMax Reitz } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FMT)) { 40678a17b83cSMax Reitz backing_format = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT); 40688a17b83cSMax Reitz } else if (!strcmp(desc->name, BLOCK_OPT_ENCRYPT)) { 40698a17b83cSMax Reitz encrypt = qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, 4070b25b387fSDaniel P. Berrange !!s->crypto); 4071f6fa64f6SDaniel P. Berrange 4072b25b387fSDaniel P. Berrange if (encrypt != !!s->crypto) { 407329d72431SMax Reitz error_report("Changing the encryption flag is not supported"); 40749296b3edSMax Reitz return -ENOTSUP; 40759296b3edSMax Reitz } 40764652b8f3SDaniel P. Berrange } else if (!strcmp(desc->name, BLOCK_OPT_ENCRYPT_FORMAT)) { 40774652b8f3SDaniel P. Berrange encformat = qcow2_crypt_method_from_format( 40784652b8f3SDaniel P. Berrange qemu_opt_get(opts, BLOCK_OPT_ENCRYPT_FORMAT)); 40794652b8f3SDaniel P. Berrange 40804652b8f3SDaniel P. Berrange if (encformat != s->crypt_method_header) { 40814652b8f3SDaniel P. Berrange error_report("Changing the encryption format is not supported"); 40824652b8f3SDaniel P. Berrange return -ENOTSUP; 40834652b8f3SDaniel P. Berrange } 4084f66afbe2SDaniel P. Berrange } else if (g_str_has_prefix(desc->name, "encrypt.")) { 4085f66afbe2SDaniel P. Berrange error_report("Changing the encryption parameters is not supported"); 4086f66afbe2SDaniel P. Berrange return -ENOTSUP; 40878a17b83cSMax Reitz } else if (!strcmp(desc->name, BLOCK_OPT_CLUSTER_SIZE)) { 40888a17b83cSMax Reitz cluster_size = qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE, 40891bd0e2d1SChunyan Liu cluster_size); 40901bd0e2d1SChunyan Liu if (cluster_size != s->cluster_size) { 409129d72431SMax Reitz error_report("Changing the cluster size is not supported"); 40929296b3edSMax Reitz return -ENOTSUP; 40939296b3edSMax Reitz } 40948a17b83cSMax Reitz } else if (!strcmp(desc->name, BLOCK_OPT_LAZY_REFCOUNTS)) { 40958a17b83cSMax Reitz lazy_refcounts = qemu_opt_get_bool(opts, BLOCK_OPT_LAZY_REFCOUNTS, 40961bd0e2d1SChunyan Liu lazy_refcounts); 409706d05fa7SMax Reitz } else if (!strcmp(desc->name, BLOCK_OPT_REFCOUNT_BITS)) { 409861ce55fcSMax Reitz refcount_bits = qemu_opt_get_number(opts, BLOCK_OPT_REFCOUNT_BITS, 409961ce55fcSMax Reitz refcount_bits); 410061ce55fcSMax Reitz 410161ce55fcSMax Reitz if (refcount_bits <= 0 || refcount_bits > 64 || 410261ce55fcSMax Reitz !is_power_of_2(refcount_bits)) 410361ce55fcSMax Reitz { 410461ce55fcSMax Reitz error_report("Refcount width must be a power of two and may " 410561ce55fcSMax Reitz "not exceed 64 bits"); 410661ce55fcSMax Reitz return -EINVAL; 410761ce55fcSMax Reitz } 41089296b3edSMax Reitz } else { 4109164e0f89SMax Reitz /* if this point is reached, this probably means a new option was 41109296b3edSMax Reitz * added without having it covered here */ 4111164e0f89SMax Reitz abort(); 41129296b3edSMax Reitz } 41131bd0e2d1SChunyan Liu 41141bd0e2d1SChunyan Liu desc++; 41159296b3edSMax Reitz } 41169296b3edSMax Reitz 4117c293a809SMax Reitz helper_cb_info = (Qcow2AmendHelperCBInfo){ 4118c293a809SMax Reitz .original_status_cb = status_cb, 4119c293a809SMax Reitz .original_cb_opaque = cb_opaque, 4120c293a809SMax Reitz .total_operations = (new_version < old_version) 412161ce55fcSMax Reitz + (s->refcount_bits != refcount_bits) 4122c293a809SMax Reitz }; 4123c293a809SMax Reitz 41241038bbb8SMax Reitz /* Upgrade first (some features may require compat=1.1) */ 41259296b3edSMax Reitz if (new_version > old_version) { 41269296b3edSMax Reitz s->qcow_version = new_version; 41279296b3edSMax Reitz ret = qcow2_update_header(bs); 41289296b3edSMax Reitz if (ret < 0) { 41299296b3edSMax Reitz s->qcow_version = old_version; 41309296b3edSMax Reitz return ret; 41319296b3edSMax Reitz } 41329296b3edSMax Reitz } 41339296b3edSMax Reitz 413461ce55fcSMax Reitz if (s->refcount_bits != refcount_bits) { 413561ce55fcSMax Reitz int refcount_order = ctz32(refcount_bits); 413661ce55fcSMax Reitz 413761ce55fcSMax Reitz if (new_version < 3 && refcount_bits != 16) { 413861ce55fcSMax Reitz error_report("Different refcount widths than 16 bits require " 413961ce55fcSMax Reitz "compatibility level 1.1 or above (use compat=1.1 or " 414061ce55fcSMax Reitz "greater)"); 414161ce55fcSMax Reitz return -EINVAL; 414261ce55fcSMax Reitz } 414361ce55fcSMax Reitz 414461ce55fcSMax Reitz helper_cb_info.current_operation = QCOW2_CHANGING_REFCOUNT_ORDER; 414561ce55fcSMax Reitz ret = qcow2_change_refcount_order(bs, refcount_order, 414661ce55fcSMax Reitz &qcow2_amend_helper_cb, 4147a7a6a2bfSAlberto Garcia &helper_cb_info, &local_err); 414861ce55fcSMax Reitz if (ret < 0) { 4149a7a6a2bfSAlberto Garcia error_report_err(local_err); 415061ce55fcSMax Reitz return ret; 415161ce55fcSMax Reitz } 415261ce55fcSMax Reitz } 415361ce55fcSMax Reitz 41549296b3edSMax Reitz if (backing_file || backing_format) { 4155e4603fe1SKevin Wolf ret = qcow2_change_backing_file(bs, 4156e4603fe1SKevin Wolf backing_file ?: s->image_backing_file, 4157e4603fe1SKevin Wolf backing_format ?: s->image_backing_format); 41589296b3edSMax Reitz if (ret < 0) { 41599296b3edSMax Reitz return ret; 41609296b3edSMax Reitz } 41619296b3edSMax Reitz } 41629296b3edSMax Reitz 41639296b3edSMax Reitz if (s->use_lazy_refcounts != lazy_refcounts) { 41649296b3edSMax Reitz if (lazy_refcounts) { 41651038bbb8SMax Reitz if (new_version < 3) { 416629d72431SMax Reitz error_report("Lazy refcounts only supported with compatibility " 416729d72431SMax Reitz "level 1.1 and above (use compat=1.1 or greater)"); 41689296b3edSMax Reitz return -EINVAL; 41699296b3edSMax Reitz } 41709296b3edSMax Reitz s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS; 41719296b3edSMax Reitz ret = qcow2_update_header(bs); 41729296b3edSMax Reitz if (ret < 0) { 41739296b3edSMax Reitz s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS; 41749296b3edSMax Reitz return ret; 41759296b3edSMax Reitz } 41769296b3edSMax Reitz s->use_lazy_refcounts = true; 41779296b3edSMax Reitz } else { 41789296b3edSMax Reitz /* make image clean first */ 41799296b3edSMax Reitz ret = qcow2_mark_clean(bs); 41809296b3edSMax Reitz if (ret < 0) { 41819296b3edSMax Reitz return ret; 41829296b3edSMax Reitz } 41839296b3edSMax Reitz /* now disallow lazy refcounts */ 41849296b3edSMax Reitz s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS; 41859296b3edSMax Reitz ret = qcow2_update_header(bs); 41869296b3edSMax Reitz if (ret < 0) { 41879296b3edSMax Reitz s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS; 41889296b3edSMax Reitz return ret; 41899296b3edSMax Reitz } 41909296b3edSMax Reitz s->use_lazy_refcounts = false; 41919296b3edSMax Reitz } 41929296b3edSMax Reitz } 41939296b3edSMax Reitz 41949296b3edSMax Reitz if (new_size) { 41956d0eb64dSKevin Wolf BlockBackend *blk = blk_new(BLK_PERM_RESIZE, BLK_PERM_ALL); 4196d7086422SKevin Wolf ret = blk_insert_bs(blk, bs, &local_err); 4197d7086422SKevin Wolf if (ret < 0) { 4198d7086422SKevin Wolf error_report_err(local_err); 4199d7086422SKevin Wolf blk_unref(blk); 4200d7086422SKevin Wolf return ret; 4201d7086422SKevin Wolf } 4202d7086422SKevin Wolf 42033a691c50SMax Reitz ret = blk_truncate(blk, new_size, PREALLOC_MODE_OFF, &local_err); 420470b27f36SKevin Wolf blk_unref(blk); 42059296b3edSMax Reitz if (ret < 0) { 4206ed3d2ec9SMax Reitz error_report_err(local_err); 42079296b3edSMax Reitz return ret; 42089296b3edSMax Reitz } 42099296b3edSMax Reitz } 42109296b3edSMax Reitz 42111038bbb8SMax Reitz /* Downgrade last (so unsupported features can be removed before) */ 42121038bbb8SMax Reitz if (new_version < old_version) { 4213c293a809SMax Reitz helper_cb_info.current_operation = QCOW2_DOWNGRADING; 4214c293a809SMax Reitz ret = qcow2_downgrade(bs, new_version, &qcow2_amend_helper_cb, 4215c293a809SMax Reitz &helper_cb_info); 42161038bbb8SMax Reitz if (ret < 0) { 42171038bbb8SMax Reitz return ret; 42181038bbb8SMax Reitz } 42191038bbb8SMax Reitz } 42201038bbb8SMax Reitz 42219296b3edSMax Reitz return 0; 42229296b3edSMax Reitz } 42239296b3edSMax Reitz 422485186ebdSMax Reitz /* 422585186ebdSMax Reitz * If offset or size are negative, respectively, they will not be included in 422685186ebdSMax Reitz * the BLOCK_IMAGE_CORRUPTED event emitted. 422785186ebdSMax Reitz * fatal will be ignored for read-only BDS; corruptions found there will always 422885186ebdSMax Reitz * be considered non-fatal. 422985186ebdSMax Reitz */ 423085186ebdSMax Reitz void qcow2_signal_corruption(BlockDriverState *bs, bool fatal, int64_t offset, 423185186ebdSMax Reitz int64_t size, const char *message_format, ...) 423285186ebdSMax Reitz { 4233ff99129aSKevin Wolf BDRVQcow2State *s = bs->opaque; 4234dc881b44SAlberto Garcia const char *node_name; 423585186ebdSMax Reitz char *message; 423685186ebdSMax Reitz va_list ap; 423785186ebdSMax Reitz 423885186ebdSMax Reitz fatal = fatal && !bs->read_only; 423985186ebdSMax Reitz 424085186ebdSMax Reitz if (s->signaled_corruption && 424185186ebdSMax Reitz (!fatal || (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT))) 424285186ebdSMax Reitz { 424385186ebdSMax Reitz return; 424485186ebdSMax Reitz } 424585186ebdSMax Reitz 424685186ebdSMax Reitz va_start(ap, message_format); 424785186ebdSMax Reitz message = g_strdup_vprintf(message_format, ap); 424885186ebdSMax Reitz va_end(ap); 424985186ebdSMax Reitz 425085186ebdSMax Reitz if (fatal) { 425185186ebdSMax Reitz fprintf(stderr, "qcow2: Marking image as corrupt: %s; further " 425285186ebdSMax Reitz "corruption events will be suppressed\n", message); 425385186ebdSMax Reitz } else { 425485186ebdSMax Reitz fprintf(stderr, "qcow2: Image is corrupt: %s; further non-fatal " 425585186ebdSMax Reitz "corruption events will be suppressed\n", message); 425685186ebdSMax Reitz } 425785186ebdSMax Reitz 4258dc881b44SAlberto Garcia node_name = bdrv_get_node_name(bs); 4259dc881b44SAlberto Garcia qapi_event_send_block_image_corrupted(bdrv_get_device_name(bs), 4260dc881b44SAlberto Garcia *node_name != '\0', node_name, 4261dc881b44SAlberto Garcia message, offset >= 0, offset, 4262dc881b44SAlberto Garcia size >= 0, size, 426385186ebdSMax Reitz fatal, &error_abort); 426485186ebdSMax Reitz g_free(message); 426585186ebdSMax Reitz 426685186ebdSMax Reitz if (fatal) { 426785186ebdSMax Reitz qcow2_mark_corrupt(bs); 426885186ebdSMax Reitz bs->drv = NULL; /* make BDS unusable */ 426985186ebdSMax Reitz } 427085186ebdSMax Reitz 427185186ebdSMax Reitz s->signaled_corruption = true; 427285186ebdSMax Reitz } 427385186ebdSMax Reitz 42741bd0e2d1SChunyan Liu static QemuOptsList qcow2_create_opts = { 42751bd0e2d1SChunyan Liu .name = "qcow2-create-opts", 42761bd0e2d1SChunyan Liu .head = QTAILQ_HEAD_INITIALIZER(qcow2_create_opts.head), 42771bd0e2d1SChunyan Liu .desc = { 427820d97356SBlue Swirl { 427920d97356SBlue Swirl .name = BLOCK_OPT_SIZE, 42801bd0e2d1SChunyan Liu .type = QEMU_OPT_SIZE, 428120d97356SBlue Swirl .help = "Virtual disk size" 428220d97356SBlue Swirl }, 428320d97356SBlue Swirl { 42846744cbabSKevin Wolf .name = BLOCK_OPT_COMPAT_LEVEL, 42851bd0e2d1SChunyan Liu .type = QEMU_OPT_STRING, 42866744cbabSKevin Wolf .help = "Compatibility level (0.10 or 1.1)" 42876744cbabSKevin Wolf }, 42886744cbabSKevin Wolf { 428920d97356SBlue Swirl .name = BLOCK_OPT_BACKING_FILE, 42901bd0e2d1SChunyan Liu .type = QEMU_OPT_STRING, 429120d97356SBlue Swirl .help = "File name of a base image" 429220d97356SBlue Swirl }, 429320d97356SBlue Swirl { 429420d97356SBlue Swirl .name = BLOCK_OPT_BACKING_FMT, 42951bd0e2d1SChunyan Liu .type = QEMU_OPT_STRING, 429620d97356SBlue Swirl .help = "Image format of the base image" 429720d97356SBlue Swirl }, 429820d97356SBlue Swirl { 429920d97356SBlue Swirl .name = BLOCK_OPT_ENCRYPT, 43001bd0e2d1SChunyan Liu .type = QEMU_OPT_BOOL, 43010cb8d47bSDaniel P. Berrange .help = "Encrypt the image with format 'aes'. (Deprecated " 43020cb8d47bSDaniel P. Berrange "in favor of " BLOCK_OPT_ENCRYPT_FORMAT "=aes)", 43030cb8d47bSDaniel P. Berrange }, 43040cb8d47bSDaniel P. Berrange { 43050cb8d47bSDaniel P. Berrange .name = BLOCK_OPT_ENCRYPT_FORMAT, 43060cb8d47bSDaniel P. Berrange .type = QEMU_OPT_STRING, 43074652b8f3SDaniel P. Berrange .help = "Encrypt the image, format choices: 'aes', 'luks'", 430820d97356SBlue Swirl }, 43094652b8f3SDaniel P. Berrange BLOCK_CRYPTO_OPT_DEF_KEY_SECRET("encrypt.", 43104652b8f3SDaniel P. Berrange "ID of secret providing qcow AES key or LUKS passphrase"), 43114652b8f3SDaniel P. Berrange BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_ALG("encrypt."), 43124652b8f3SDaniel P. Berrange BLOCK_CRYPTO_OPT_DEF_LUKS_CIPHER_MODE("encrypt."), 43134652b8f3SDaniel P. Berrange BLOCK_CRYPTO_OPT_DEF_LUKS_IVGEN_ALG("encrypt."), 43144652b8f3SDaniel P. Berrange BLOCK_CRYPTO_OPT_DEF_LUKS_IVGEN_HASH_ALG("encrypt."), 43154652b8f3SDaniel P. Berrange BLOCK_CRYPTO_OPT_DEF_LUKS_HASH_ALG("encrypt."), 43164652b8f3SDaniel P. Berrange BLOCK_CRYPTO_OPT_DEF_LUKS_ITER_TIME("encrypt."), 431720d97356SBlue Swirl { 431820d97356SBlue Swirl .name = BLOCK_OPT_CLUSTER_SIZE, 43191bd0e2d1SChunyan Liu .type = QEMU_OPT_SIZE, 432099cce9faSKevin Wolf .help = "qcow2 cluster size", 43211bd0e2d1SChunyan Liu .def_value_str = stringify(DEFAULT_CLUSTER_SIZE) 432220d97356SBlue Swirl }, 432320d97356SBlue Swirl { 432420d97356SBlue Swirl .name = BLOCK_OPT_PREALLOC, 43251bd0e2d1SChunyan Liu .type = QEMU_OPT_STRING, 43260e4271b7SHu Tao .help = "Preallocation mode (allowed values: off, metadata, " 43270e4271b7SHu Tao "falloc, full)" 432820d97356SBlue Swirl }, 4329bfe8043eSStefan Hajnoczi { 4330bfe8043eSStefan Hajnoczi .name = BLOCK_OPT_LAZY_REFCOUNTS, 43311bd0e2d1SChunyan Liu .type = QEMU_OPT_BOOL, 4332bfe8043eSStefan Hajnoczi .help = "Postpone refcount updates", 43331bd0e2d1SChunyan Liu .def_value_str = "off" 4334bfe8043eSStefan Hajnoczi }, 433506d05fa7SMax Reitz { 433606d05fa7SMax Reitz .name = BLOCK_OPT_REFCOUNT_BITS, 433706d05fa7SMax Reitz .type = QEMU_OPT_NUMBER, 433806d05fa7SMax Reitz .help = "Width of a reference count entry in bits", 433906d05fa7SMax Reitz .def_value_str = "16" 434006d05fa7SMax Reitz }, 43411bd0e2d1SChunyan Liu { /* end of list */ } 43421bd0e2d1SChunyan Liu } 434320d97356SBlue Swirl }; 434420d97356SBlue Swirl 43455f535a94SMax Reitz BlockDriver bdrv_qcow2 = { 434620d97356SBlue Swirl .format_name = "qcow2", 4347ff99129aSKevin Wolf .instance_size = sizeof(BDRVQcow2State), 43487c80ab3fSJes Sorensen .bdrv_probe = qcow2_probe, 43497c80ab3fSJes Sorensen .bdrv_open = qcow2_open, 43507c80ab3fSJes Sorensen .bdrv_close = qcow2_close, 435121d82ac9SJeff Cody .bdrv_reopen_prepare = qcow2_reopen_prepare, 43525b0959a7SKevin Wolf .bdrv_reopen_commit = qcow2_reopen_commit, 43535b0959a7SKevin Wolf .bdrv_reopen_abort = qcow2_reopen_abort, 43545365f44dSKevin Wolf .bdrv_join_options = qcow2_join_options, 4355862f215fSKevin Wolf .bdrv_child_perm = bdrv_format_default_perms, 4356*efc75e2aSStefan Hajnoczi .bdrv_co_create_opts = qcow2_co_create_opts, 43573ac21627SPeter Lieven .bdrv_has_zero_init = bdrv_has_zero_init_1, 4358a320fb04SEric Blake .bdrv_co_block_status = qcow2_co_block_status, 435920d97356SBlue Swirl 4360ecfe1863SKevin Wolf .bdrv_co_preadv = qcow2_co_preadv, 4361d46a0bb2SKevin Wolf .bdrv_co_pwritev = qcow2_co_pwritev, 4362eb489bb1SKevin Wolf .bdrv_co_flush_to_os = qcow2_co_flush_to_os, 4363419b19d9SStefan Hajnoczi 43645544b59fSEric Blake .bdrv_co_pwrite_zeroes = qcow2_co_pwrite_zeroes, 436582e8a788SEric Blake .bdrv_co_pdiscard = qcow2_co_pdiscard, 4366419b19d9SStefan Hajnoczi .bdrv_truncate = qcow2_truncate, 4367fcccefc5SPavel Butsykin .bdrv_co_pwritev_compressed = qcow2_co_pwritev_compressed, 4368491d27e2SMax Reitz .bdrv_make_empty = qcow2_make_empty, 436920d97356SBlue Swirl 437020d97356SBlue Swirl .bdrv_snapshot_create = qcow2_snapshot_create, 437120d97356SBlue Swirl .bdrv_snapshot_goto = qcow2_snapshot_goto, 437220d97356SBlue Swirl .bdrv_snapshot_delete = qcow2_snapshot_delete, 437320d97356SBlue Swirl .bdrv_snapshot_list = qcow2_snapshot_list, 437451ef6727Sedison .bdrv_snapshot_load_tmp = qcow2_snapshot_load_tmp, 4375c501c352SStefan Hajnoczi .bdrv_measure = qcow2_measure, 43767c80ab3fSJes Sorensen .bdrv_get_info = qcow2_get_info, 437737764dfbSMax Reitz .bdrv_get_specific_info = qcow2_get_specific_info, 437820d97356SBlue Swirl 43797c80ab3fSJes Sorensen .bdrv_save_vmstate = qcow2_save_vmstate, 43807c80ab3fSJes Sorensen .bdrv_load_vmstate = qcow2_load_vmstate, 438120d97356SBlue Swirl 43828ee79e70SKevin Wolf .supports_backing = true, 438320d97356SBlue Swirl .bdrv_change_backing_file = qcow2_change_backing_file, 438420d97356SBlue Swirl 4385d34682cdSKevin Wolf .bdrv_refresh_limits = qcow2_refresh_limits, 438606d9260fSAnthony Liguori .bdrv_invalidate_cache = qcow2_invalidate_cache, 4387ec6d8912SKevin Wolf .bdrv_inactivate = qcow2_inactivate, 438806d9260fSAnthony Liguori 43891bd0e2d1SChunyan Liu .create_opts = &qcow2_create_opts, 43907c80ab3fSJes Sorensen .bdrv_check = qcow2_check, 4391c282e1fdSChunyan Liu .bdrv_amend_options = qcow2_amend_options, 4392279621c0SAlberto Garcia 4393279621c0SAlberto Garcia .bdrv_detach_aio_context = qcow2_detach_aio_context, 4394279621c0SAlberto Garcia .bdrv_attach_aio_context = qcow2_attach_aio_context, 43951b6b0562SVladimir Sementsov-Ogievskiy 43961b6b0562SVladimir Sementsov-Ogievskiy .bdrv_reopen_bitmaps_rw = qcow2_reopen_bitmaps_rw, 4397da0eb242SVladimir Sementsov-Ogievskiy .bdrv_can_store_new_dirty_bitmap = qcow2_can_store_new_dirty_bitmap, 4398469c71edSVladimir Sementsov-Ogievskiy .bdrv_remove_persistent_dirty_bitmap = qcow2_remove_persistent_dirty_bitmap, 439920d97356SBlue Swirl }; 440020d97356SBlue Swirl 44015efa9d5aSAnthony Liguori static void bdrv_qcow2_init(void) 44025efa9d5aSAnthony Liguori { 44035efa9d5aSAnthony Liguori bdrv_register(&bdrv_qcow2); 44045efa9d5aSAnthony Liguori } 44055efa9d5aSAnthony Liguori 44065efa9d5aSAnthony Liguori block_init(bdrv_qcow2_init); 4407