xref: /qemu/block/qcow2.c (revision fd29b4bbef9f75bba64ad7c4db38babc397a4814)
1585f8587Sbellard /*
2585f8587Sbellard  * Block driver for the QCOW version 2 format
3585f8587Sbellard  *
4585f8587Sbellard  * Copyright (c) 2004-2006 Fabrice Bellard
5585f8587Sbellard  *
6585f8587Sbellard  * Permission is hereby granted, free of charge, to any person obtaining a copy
7585f8587Sbellard  * of this software and associated documentation files (the "Software"), to deal
8585f8587Sbellard  * in the Software without restriction, including without limitation the rights
9585f8587Sbellard  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10585f8587Sbellard  * copies of the Software, and to permit persons to whom the Software is
11585f8587Sbellard  * furnished to do so, subject to the following conditions:
12585f8587Sbellard  *
13585f8587Sbellard  * The above copyright notice and this permission notice shall be included in
14585f8587Sbellard  * all copies or substantial portions of the Software.
15585f8587Sbellard  *
16585f8587Sbellard  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17585f8587Sbellard  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18585f8587Sbellard  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19585f8587Sbellard  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20585f8587Sbellard  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21585f8587Sbellard  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22585f8587Sbellard  * THE SOFTWARE.
23585f8587Sbellard  */
24faf07963Spbrook #include "qemu-common.h"
25585f8587Sbellard #include "block_int.h"
265efa9d5aSAnthony Liguori #include "module.h"
27585f8587Sbellard #include <zlib.h>
28585f8587Sbellard #include "aes.h"
29f7d0fe02SKevin Wolf #include "block/qcow2.h"
30a9420734SKevin Wolf #include "qemu-error.h"
31e8cdcec1SKevin Wolf #include "qerror.h"
32585f8587Sbellard 
33585f8587Sbellard /*
34585f8587Sbellard   Differences with QCOW:
35585f8587Sbellard 
36585f8587Sbellard   - Support for multiple incremental snapshots.
37585f8587Sbellard   - Memory management by reference counts.
38585f8587Sbellard   - Clusters which have a reference count of one have the bit
39585f8587Sbellard     QCOW_OFLAG_COPIED to optimize write performance.
40585f8587Sbellard   - Size of compressed clusters is stored in sectors to reduce bit usage
41585f8587Sbellard     in the cluster offsets.
42585f8587Sbellard   - Support for storing additional data (such as the VM state) in the
43585f8587Sbellard     snapshots.
44585f8587Sbellard   - If a backing store is used, the cluster size is not constrained
45585f8587Sbellard     (could be backported to QCOW).
46585f8587Sbellard   - L2 tables have always a size of one cluster.
47585f8587Sbellard */
48585f8587Sbellard 
499b80ddf3Saliguori 
509b80ddf3Saliguori typedef struct {
519b80ddf3Saliguori     uint32_t magic;
529b80ddf3Saliguori     uint32_t len;
539b80ddf3Saliguori } QCowExtension;
547c80ab3fSJes Sorensen #define  QCOW2_EXT_MAGIC_END 0
557c80ab3fSJes Sorensen #define  QCOW2_EXT_MAGIC_BACKING_FORMAT 0xE2792ACA
569b80ddf3Saliguori 
577c80ab3fSJes Sorensen static int qcow2_probe(const uint8_t *buf, int buf_size, const char *filename)
58585f8587Sbellard {
59585f8587Sbellard     const QCowHeader *cow_header = (const void *)buf;
60585f8587Sbellard 
61585f8587Sbellard     if (buf_size >= sizeof(QCowHeader) &&
62585f8587Sbellard         be32_to_cpu(cow_header->magic) == QCOW_MAGIC &&
63e8cdcec1SKevin Wolf         be32_to_cpu(cow_header->version) >= QCOW_VERSION)
64585f8587Sbellard         return 100;
65585f8587Sbellard     else
66585f8587Sbellard         return 0;
67585f8587Sbellard }
68585f8587Sbellard 
699b80ddf3Saliguori 
709b80ddf3Saliguori /*
719b80ddf3Saliguori  * read qcow2 extension and fill bs
729b80ddf3Saliguori  * start reading from start_offset
739b80ddf3Saliguori  * finish reading upon magic of value 0 or when end_offset reached
749b80ddf3Saliguori  * unknown magic is skipped (future extension this version knows nothing about)
759b80ddf3Saliguori  * return 0 upon success, non-0 otherwise
769b80ddf3Saliguori  */
777c80ab3fSJes Sorensen static int qcow2_read_extensions(BlockDriverState *bs, uint64_t start_offset,
789b80ddf3Saliguori                                  uint64_t end_offset)
799b80ddf3Saliguori {
8075bab85cSKevin Wolf     BDRVQcowState *s = bs->opaque;
819b80ddf3Saliguori     QCowExtension ext;
829b80ddf3Saliguori     uint64_t offset;
8375bab85cSKevin Wolf     int ret;
849b80ddf3Saliguori 
859b80ddf3Saliguori #ifdef DEBUG_EXT
867c80ab3fSJes Sorensen     printf("qcow2_read_extensions: start=%ld end=%ld\n", start_offset, end_offset);
879b80ddf3Saliguori #endif
889b80ddf3Saliguori     offset = start_offset;
899b80ddf3Saliguori     while (offset < end_offset) {
909b80ddf3Saliguori 
919b80ddf3Saliguori #ifdef DEBUG_EXT
929b80ddf3Saliguori         /* Sanity check */
939b80ddf3Saliguori         if (offset > s->cluster_size)
947c80ab3fSJes Sorensen             printf("qcow2_read_extension: suspicious offset %lu\n", offset);
959b80ddf3Saliguori 
969b2260cbSDong Xu Wang         printf("attempting to read extended header in offset %lu\n", offset);
979b80ddf3Saliguori #endif
989b80ddf3Saliguori 
9966f82ceeSKevin Wolf         if (bdrv_pread(bs->file, offset, &ext, sizeof(ext)) != sizeof(ext)) {
1007c80ab3fSJes Sorensen             fprintf(stderr, "qcow2_read_extension: ERROR: "
1010bfcd599SBlue Swirl                     "pread fail from offset %" PRIu64 "\n",
1020bfcd599SBlue Swirl                     offset);
1039b80ddf3Saliguori             return 1;
1049b80ddf3Saliguori         }
1059b80ddf3Saliguori         be32_to_cpus(&ext.magic);
1069b80ddf3Saliguori         be32_to_cpus(&ext.len);
1079b80ddf3Saliguori         offset += sizeof(ext);
1089b80ddf3Saliguori #ifdef DEBUG_EXT
1099b80ddf3Saliguori         printf("ext.magic = 0x%x\n", ext.magic);
1109b80ddf3Saliguori #endif
1119b80ddf3Saliguori         switch (ext.magic) {
1127c80ab3fSJes Sorensen         case QCOW2_EXT_MAGIC_END:
1139b80ddf3Saliguori             return 0;
114f965509cSaliguori 
1157c80ab3fSJes Sorensen         case QCOW2_EXT_MAGIC_BACKING_FORMAT:
116f965509cSaliguori             if (ext.len >= sizeof(bs->backing_format)) {
117f965509cSaliguori                 fprintf(stderr, "ERROR: ext_backing_format: len=%u too large"
1184c978075Saliguori                         " (>=%zu)\n",
119f965509cSaliguori                         ext.len, sizeof(bs->backing_format));
120f965509cSaliguori                 return 2;
121f965509cSaliguori             }
12266f82ceeSKevin Wolf             if (bdrv_pread(bs->file, offset , bs->backing_format,
123f965509cSaliguori                            ext.len) != ext.len)
124f965509cSaliguori                 return 3;
125f965509cSaliguori             bs->backing_format[ext.len] = '\0';
126f965509cSaliguori #ifdef DEBUG_EXT
127f965509cSaliguori             printf("Qcow2: Got format extension %s\n", bs->backing_format);
128f965509cSaliguori #endif
129f965509cSaliguori             break;
130f965509cSaliguori 
1319b80ddf3Saliguori         default:
13275bab85cSKevin Wolf             /* unknown magic - save it in case we need to rewrite the header */
13375bab85cSKevin Wolf             {
13475bab85cSKevin Wolf                 Qcow2UnknownHeaderExtension *uext;
13575bab85cSKevin Wolf 
13675bab85cSKevin Wolf                 uext = g_malloc0(sizeof(*uext)  + ext.len);
13775bab85cSKevin Wolf                 uext->magic = ext.magic;
13875bab85cSKevin Wolf                 uext->len = ext.len;
13975bab85cSKevin Wolf                 QLIST_INSERT_HEAD(&s->unknown_header_ext, uext, next);
14075bab85cSKevin Wolf 
14175bab85cSKevin Wolf                 ret = bdrv_pread(bs->file, offset , uext->data, uext->len);
14275bab85cSKevin Wolf                 if (ret < 0) {
14375bab85cSKevin Wolf                     return ret;
14475bab85cSKevin Wolf                 }
14575bab85cSKevin Wolf             }
1469b80ddf3Saliguori             break;
1479b80ddf3Saliguori         }
148*fd29b4bbSKevin Wolf 
149*fd29b4bbSKevin Wolf         offset += ((ext.len + 7) & ~7);
1509b80ddf3Saliguori     }
1519b80ddf3Saliguori 
1529b80ddf3Saliguori     return 0;
1539b80ddf3Saliguori }
1549b80ddf3Saliguori 
15575bab85cSKevin Wolf static void cleanup_unknown_header_ext(BlockDriverState *bs)
15675bab85cSKevin Wolf {
15775bab85cSKevin Wolf     BDRVQcowState *s = bs->opaque;
15875bab85cSKevin Wolf     Qcow2UnknownHeaderExtension *uext, *next;
15975bab85cSKevin Wolf 
16075bab85cSKevin Wolf     QLIST_FOREACH_SAFE(uext, &s->unknown_header_ext, next, next) {
16175bab85cSKevin Wolf         QLIST_REMOVE(uext, next);
16275bab85cSKevin Wolf         g_free(uext);
16375bab85cSKevin Wolf     }
16475bab85cSKevin Wolf }
1659b80ddf3Saliguori 
1667c80ab3fSJes Sorensen static int qcow2_open(BlockDriverState *bs, int flags)
167585f8587Sbellard {
168585f8587Sbellard     BDRVQcowState *s = bs->opaque;
1696d85a57eSJes Sorensen     int len, i, ret = 0;
170585f8587Sbellard     QCowHeader header;
1719b80ddf3Saliguori     uint64_t ext_end;
17229c1a730SKevin Wolf     bool writethrough;
173585f8587Sbellard 
1746d85a57eSJes Sorensen     ret = bdrv_pread(bs->file, 0, &header, sizeof(header));
1756d85a57eSJes Sorensen     if (ret < 0) {
176585f8587Sbellard         goto fail;
1776d85a57eSJes Sorensen     }
178585f8587Sbellard     be32_to_cpus(&header.magic);
179585f8587Sbellard     be32_to_cpus(&header.version);
180585f8587Sbellard     be64_to_cpus(&header.backing_file_offset);
181585f8587Sbellard     be32_to_cpus(&header.backing_file_size);
182585f8587Sbellard     be64_to_cpus(&header.size);
183585f8587Sbellard     be32_to_cpus(&header.cluster_bits);
184585f8587Sbellard     be32_to_cpus(&header.crypt_method);
185585f8587Sbellard     be64_to_cpus(&header.l1_table_offset);
186585f8587Sbellard     be32_to_cpus(&header.l1_size);
187585f8587Sbellard     be64_to_cpus(&header.refcount_table_offset);
188585f8587Sbellard     be32_to_cpus(&header.refcount_table_clusters);
189585f8587Sbellard     be64_to_cpus(&header.snapshots_offset);
190585f8587Sbellard     be32_to_cpus(&header.nb_snapshots);
191585f8587Sbellard 
192e8cdcec1SKevin Wolf     if (header.magic != QCOW_MAGIC) {
1936d85a57eSJes Sorensen         ret = -EINVAL;
194585f8587Sbellard         goto fail;
1956d85a57eSJes Sorensen     }
196e8cdcec1SKevin Wolf     if (header.version != QCOW_VERSION) {
197e8cdcec1SKevin Wolf         char version[64];
198e8cdcec1SKevin Wolf         snprintf(version, sizeof(version), "QCOW version %d", header.version);
199e8cdcec1SKevin Wolf         qerror_report(QERR_UNKNOWN_BLOCK_FORMAT_FEATURE,
200e8cdcec1SKevin Wolf             bs->device_name, "qcow2", version);
201e8cdcec1SKevin Wolf         ret = -ENOTSUP;
202e8cdcec1SKevin Wolf         goto fail;
203e8cdcec1SKevin Wolf     }
204d191d12dSStefan Weil     if (header.cluster_bits < MIN_CLUSTER_BITS ||
2056d85a57eSJes Sorensen         header.cluster_bits > MAX_CLUSTER_BITS) {
2066d85a57eSJes Sorensen         ret = -EINVAL;
207585f8587Sbellard         goto fail;
2086d85a57eSJes Sorensen     }
2096d85a57eSJes Sorensen     if (header.crypt_method > QCOW_CRYPT_AES) {
2106d85a57eSJes Sorensen         ret = -EINVAL;
211585f8587Sbellard         goto fail;
2126d85a57eSJes Sorensen     }
213585f8587Sbellard     s->crypt_method_header = header.crypt_method;
2146d85a57eSJes Sorensen     if (s->crypt_method_header) {
215585f8587Sbellard         bs->encrypted = 1;
2166d85a57eSJes Sorensen     }
217585f8587Sbellard     s->cluster_bits = header.cluster_bits;
218585f8587Sbellard     s->cluster_size = 1 << s->cluster_bits;
219585f8587Sbellard     s->cluster_sectors = 1 << (s->cluster_bits - 9);
220585f8587Sbellard     s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */
221585f8587Sbellard     s->l2_size = 1 << s->l2_bits;
222585f8587Sbellard     bs->total_sectors = header.size / 512;
223585f8587Sbellard     s->csize_shift = (62 - (s->cluster_bits - 8));
224585f8587Sbellard     s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;
225585f8587Sbellard     s->cluster_offset_mask = (1LL << s->csize_shift) - 1;
226585f8587Sbellard     s->refcount_table_offset = header.refcount_table_offset;
227585f8587Sbellard     s->refcount_table_size =
228585f8587Sbellard         header.refcount_table_clusters << (s->cluster_bits - 3);
229585f8587Sbellard 
230585f8587Sbellard     s->snapshots_offset = header.snapshots_offset;
231585f8587Sbellard     s->nb_snapshots = header.nb_snapshots;
232585f8587Sbellard 
233585f8587Sbellard     /* read the level 1 table */
234585f8587Sbellard     s->l1_size = header.l1_size;
235419b19d9SStefan Hajnoczi     s->l1_vm_state_index = size_to_l1(s, header.size);
236585f8587Sbellard     /* the L1 table must contain at least enough entries to put
237585f8587Sbellard        header.size bytes */
2386d85a57eSJes Sorensen     if (s->l1_size < s->l1_vm_state_index) {
2396d85a57eSJes Sorensen         ret = -EINVAL;
240585f8587Sbellard         goto fail;
2416d85a57eSJes Sorensen     }
242585f8587Sbellard     s->l1_table_offset = header.l1_table_offset;
243d191d12dSStefan Weil     if (s->l1_size > 0) {
2447267c094SAnthony Liguori         s->l1_table = g_malloc0(
2453f6a3ee5SKevin Wolf             align_offset(s->l1_size * sizeof(uint64_t), 512));
2466d85a57eSJes Sorensen         ret = bdrv_pread(bs->file, s->l1_table_offset, s->l1_table,
2476d85a57eSJes Sorensen                          s->l1_size * sizeof(uint64_t));
2486d85a57eSJes Sorensen         if (ret < 0) {
249585f8587Sbellard             goto fail;
2506d85a57eSJes Sorensen         }
251585f8587Sbellard         for(i = 0;i < s->l1_size; i++) {
252585f8587Sbellard             be64_to_cpus(&s->l1_table[i]);
253585f8587Sbellard         }
254d191d12dSStefan Weil     }
25529c1a730SKevin Wolf 
25629c1a730SKevin Wolf     /* alloc L2 table/refcount block cache */
257a6599793SChristoph Hellwig     writethrough = ((flags & BDRV_O_CACHE_WB) == 0);
25829c1a730SKevin Wolf     s->l2_table_cache = qcow2_cache_create(bs, L2_CACHE_SIZE, writethrough);
25929c1a730SKevin Wolf     s->refcount_block_cache = qcow2_cache_create(bs, REFCOUNT_CACHE_SIZE,
26029c1a730SKevin Wolf         writethrough);
26129c1a730SKevin Wolf 
2627267c094SAnthony Liguori     s->cluster_cache = g_malloc(s->cluster_size);
263585f8587Sbellard     /* one more sector for decompressed data alignment */
264dea43a65SFrediano Ziglio     s->cluster_data = qemu_blockalign(bs, QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size
265095a9c58Saliguori                                   + 512);
266585f8587Sbellard     s->cluster_cache_offset = -1;
26706d9260fSAnthony Liguori     s->flags = flags;
268585f8587Sbellard 
2696d85a57eSJes Sorensen     ret = qcow2_refcount_init(bs);
2706d85a57eSJes Sorensen     if (ret != 0) {
271585f8587Sbellard         goto fail;
2726d85a57eSJes Sorensen     }
273585f8587Sbellard 
27472cf2d4fSBlue Swirl     QLIST_INIT(&s->cluster_allocs);
275f214978aSKevin Wolf 
2769b80ddf3Saliguori     /* read qcow2 extensions */
2776d85a57eSJes Sorensen     if (header.backing_file_offset) {
2789b80ddf3Saliguori         ext_end = header.backing_file_offset;
2796d85a57eSJes Sorensen     } else {
2809b80ddf3Saliguori         ext_end = s->cluster_size;
2816d85a57eSJes Sorensen     }
2826d85a57eSJes Sorensen     if (qcow2_read_extensions(bs, sizeof(header), ext_end)) {
2836d85a57eSJes Sorensen         ret = -EINVAL;
2849b80ddf3Saliguori         goto fail;
2856d85a57eSJes Sorensen     }
2869b80ddf3Saliguori 
287585f8587Sbellard     /* read the backing file name */
288585f8587Sbellard     if (header.backing_file_offset != 0) {
289585f8587Sbellard         len = header.backing_file_size;
2906d85a57eSJes Sorensen         if (len > 1023) {
291585f8587Sbellard             len = 1023;
2926d85a57eSJes Sorensen         }
2936d85a57eSJes Sorensen         ret = bdrv_pread(bs->file, header.backing_file_offset,
2946d85a57eSJes Sorensen                          bs->backing_file, len);
2956d85a57eSJes Sorensen         if (ret < 0) {
296585f8587Sbellard             goto fail;
2976d85a57eSJes Sorensen         }
298585f8587Sbellard         bs->backing_file[len] = '\0';
299585f8587Sbellard     }
30042deb29fSKevin Wolf 
30142deb29fSKevin Wolf     ret = qcow2_read_snapshots(bs);
30242deb29fSKevin Wolf     if (ret < 0) {
303585f8587Sbellard         goto fail;
3046d85a57eSJes Sorensen     }
305585f8587Sbellard 
30668d100e9SKevin Wolf     /* Initialise locks */
30768d100e9SKevin Wolf     qemu_co_mutex_init(&s->lock);
30868d100e9SKevin Wolf 
309585f8587Sbellard #ifdef DEBUG_ALLOC
3106cbc3031SPhilipp Hahn     {
3116cbc3031SPhilipp Hahn         BdrvCheckResult result = {0};
3126cbc3031SPhilipp Hahn         qcow2_check_refcounts(bs, &result);
3136cbc3031SPhilipp Hahn     }
314585f8587Sbellard #endif
3156d85a57eSJes Sorensen     return ret;
316585f8587Sbellard 
317585f8587Sbellard  fail:
31875bab85cSKevin Wolf     cleanup_unknown_header_ext(bs);
319ed6ccf0fSKevin Wolf     qcow2_free_snapshots(bs);
320ed6ccf0fSKevin Wolf     qcow2_refcount_close(bs);
3217267c094SAnthony Liguori     g_free(s->l1_table);
32229c1a730SKevin Wolf     if (s->l2_table_cache) {
32329c1a730SKevin Wolf         qcow2_cache_destroy(bs, s->l2_table_cache);
32429c1a730SKevin Wolf     }
3257267c094SAnthony Liguori     g_free(s->cluster_cache);
326dea43a65SFrediano Ziglio     qemu_vfree(s->cluster_data);
3276d85a57eSJes Sorensen     return ret;
328585f8587Sbellard }
329585f8587Sbellard 
3307c80ab3fSJes Sorensen static int qcow2_set_key(BlockDriverState *bs, const char *key)
331585f8587Sbellard {
332585f8587Sbellard     BDRVQcowState *s = bs->opaque;
333585f8587Sbellard     uint8_t keybuf[16];
334585f8587Sbellard     int len, i;
335585f8587Sbellard 
336585f8587Sbellard     memset(keybuf, 0, 16);
337585f8587Sbellard     len = strlen(key);
338585f8587Sbellard     if (len > 16)
339585f8587Sbellard         len = 16;
340585f8587Sbellard     /* XXX: we could compress the chars to 7 bits to increase
341585f8587Sbellard        entropy */
342585f8587Sbellard     for(i = 0;i < len;i++) {
343585f8587Sbellard         keybuf[i] = key[i];
344585f8587Sbellard     }
345585f8587Sbellard     s->crypt_method = s->crypt_method_header;
346585f8587Sbellard 
347585f8587Sbellard     if (AES_set_encrypt_key(keybuf, 128, &s->aes_encrypt_key) != 0)
348585f8587Sbellard         return -1;
349585f8587Sbellard     if (AES_set_decrypt_key(keybuf, 128, &s->aes_decrypt_key) != 0)
350585f8587Sbellard         return -1;
351585f8587Sbellard #if 0
352585f8587Sbellard     /* test */
353585f8587Sbellard     {
354585f8587Sbellard         uint8_t in[16];
355585f8587Sbellard         uint8_t out[16];
356585f8587Sbellard         uint8_t tmp[16];
357585f8587Sbellard         for(i=0;i<16;i++)
358585f8587Sbellard             in[i] = i;
359585f8587Sbellard         AES_encrypt(in, tmp, &s->aes_encrypt_key);
360585f8587Sbellard         AES_decrypt(tmp, out, &s->aes_decrypt_key);
361585f8587Sbellard         for(i = 0; i < 16; i++)
362585f8587Sbellard             printf(" %02x", tmp[i]);
363585f8587Sbellard         printf("\n");
364585f8587Sbellard         for(i = 0; i < 16; i++)
365585f8587Sbellard             printf(" %02x", out[i]);
366585f8587Sbellard         printf("\n");
367585f8587Sbellard     }
368585f8587Sbellard #endif
369585f8587Sbellard     return 0;
370585f8587Sbellard }
371585f8587Sbellard 
372f8a2e5e3SStefan Hajnoczi static int coroutine_fn qcow2_co_is_allocated(BlockDriverState *bs,
373f8a2e5e3SStefan Hajnoczi         int64_t sector_num, int nb_sectors, int *pnum)
374585f8587Sbellard {
375f8a2e5e3SStefan Hajnoczi     BDRVQcowState *s = bs->opaque;
376585f8587Sbellard     uint64_t cluster_offset;
3771c46efaaSKevin Wolf     int ret;
378585f8587Sbellard 
379095a9c58Saliguori     *pnum = nb_sectors;
380f8a2e5e3SStefan Hajnoczi     /* FIXME We can get errors here, but the bdrv_co_is_allocated interface
381f8a2e5e3SStefan Hajnoczi      * can't pass them on today */
382f8a2e5e3SStefan Hajnoczi     qemu_co_mutex_lock(&s->lock);
3831c46efaaSKevin Wolf     ret = qcow2_get_cluster_offset(bs, sector_num << 9, pnum, &cluster_offset);
384f8a2e5e3SStefan Hajnoczi     qemu_co_mutex_unlock(&s->lock);
3851c46efaaSKevin Wolf     if (ret < 0) {
3861c46efaaSKevin Wolf         *pnum = 0;
3871c46efaaSKevin Wolf     }
388095a9c58Saliguori 
389585f8587Sbellard     return (cluster_offset != 0);
390585f8587Sbellard }
391585f8587Sbellard 
392a9465922Sbellard /* handle reading after the end of the backing file */
393bd28f835SKevin Wolf int qcow2_backing_read1(BlockDriverState *bs, QEMUIOVector *qiov,
394bd28f835SKevin Wolf                   int64_t sector_num, int nb_sectors)
395a9465922Sbellard {
396a9465922Sbellard     int n1;
397a9465922Sbellard     if ((sector_num + nb_sectors) <= bs->total_sectors)
398a9465922Sbellard         return nb_sectors;
399a9465922Sbellard     if (sector_num >= bs->total_sectors)
400a9465922Sbellard         n1 = 0;
401a9465922Sbellard     else
402a9465922Sbellard         n1 = bs->total_sectors - sector_num;
403bd28f835SKevin Wolf 
404e0d9c6f9SChunqiang Tang     qemu_iovec_memset_skip(qiov, 0, 512 * (nb_sectors - n1), 512 * n1);
405bd28f835SKevin Wolf 
406a9465922Sbellard     return n1;
407a9465922Sbellard }
408a9465922Sbellard 
409a968168cSDong Xu Wang static coroutine_fn int qcow2_co_readv(BlockDriverState *bs, int64_t sector_num,
4103fc48d09SFrediano Ziglio                           int remaining_sectors, QEMUIOVector *qiov)
4111490791fSaliguori {
412585f8587Sbellard     BDRVQcowState *s = bs->opaque;
413a9465922Sbellard     int index_in_cluster, n1;
41468d100e9SKevin Wolf     int ret;
415faf575c1SFrediano Ziglio     int cur_nr_sectors; /* number of sectors in current iteration */
416c2bdd990SFrediano Ziglio     uint64_t cluster_offset = 0;
4173fc48d09SFrediano Ziglio     uint64_t bytes_done = 0;
4183fc48d09SFrediano Ziglio     QEMUIOVector hd_qiov;
4193fc48d09SFrediano Ziglio     uint8_t *cluster_data = NULL;
420585f8587Sbellard 
4213fc48d09SFrediano Ziglio     qemu_iovec_init(&hd_qiov, qiov->niov);
4223fc48d09SFrediano Ziglio 
4233fc48d09SFrediano Ziglio     qemu_co_mutex_lock(&s->lock);
4243fc48d09SFrediano Ziglio 
4253fc48d09SFrediano Ziglio     while (remaining_sectors != 0) {
426585f8587Sbellard 
427faf575c1SFrediano Ziglio         /* prepare next request */
4283fc48d09SFrediano Ziglio         cur_nr_sectors = remaining_sectors;
429bd28f835SKevin Wolf         if (s->crypt_method) {
430faf575c1SFrediano Ziglio             cur_nr_sectors = MIN(cur_nr_sectors,
431bd28f835SKevin Wolf                 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors);
432bd28f835SKevin Wolf         }
433bd28f835SKevin Wolf 
4343fc48d09SFrediano Ziglio         ret = qcow2_get_cluster_offset(bs, sector_num << 9,
435c2bdd990SFrediano Ziglio             &cur_nr_sectors, &cluster_offset);
4361c46efaaSKevin Wolf         if (ret < 0) {
4373fc48d09SFrediano Ziglio             goto fail;
4381c46efaaSKevin Wolf         }
4391c46efaaSKevin Wolf 
4403fc48d09SFrediano Ziglio         index_in_cluster = sector_num & (s->cluster_sectors - 1);
441585f8587Sbellard 
4423fc48d09SFrediano Ziglio         qemu_iovec_reset(&hd_qiov);
4433fc48d09SFrediano Ziglio         qemu_iovec_copy(&hd_qiov, qiov, bytes_done,
444faf575c1SFrediano Ziglio             cur_nr_sectors * 512);
445bd28f835SKevin Wolf 
446c2bdd990SFrediano Ziglio         if (!cluster_offset) {
447bd28f835SKevin Wolf 
448585f8587Sbellard             if (bs->backing_hd) {
449585f8587Sbellard                 /* read from the base image */
4503fc48d09SFrediano Ziglio                 n1 = qcow2_backing_read1(bs->backing_hd, &hd_qiov,
4513fc48d09SFrediano Ziglio                     sector_num, cur_nr_sectors);
452a9465922Sbellard                 if (n1 > 0) {
45366f82ceeSKevin Wolf                     BLKDBG_EVENT(bs->file, BLKDBG_READ_BACKING_AIO);
45468d100e9SKevin Wolf                     qemu_co_mutex_unlock(&s->lock);
4553fc48d09SFrediano Ziglio                     ret = bdrv_co_readv(bs->backing_hd, sector_num,
4563fc48d09SFrediano Ziglio                                         n1, &hd_qiov);
45768d100e9SKevin Wolf                     qemu_co_mutex_lock(&s->lock);
45868d100e9SKevin Wolf                     if (ret < 0) {
4593fc48d09SFrediano Ziglio                         goto fail;
4603ab4c7e9SKevin Wolf                     }
4611490791fSaliguori                 }
462a9465922Sbellard             } else {
463585f8587Sbellard                 /* Note: in this case, no need to wait */
4643fc48d09SFrediano Ziglio                 qemu_iovec_memset(&hd_qiov, 0, 512 * cur_nr_sectors);
4651490791fSaliguori             }
466c2bdd990SFrediano Ziglio         } else if (cluster_offset & QCOW_OFLAG_COMPRESSED) {
467585f8587Sbellard             /* add AIO support for compressed blocks ? */
468c2bdd990SFrediano Ziglio             ret = qcow2_decompress_cluster(bs, cluster_offset);
4698af36488SKevin Wolf             if (ret < 0) {
4703fc48d09SFrediano Ziglio                 goto fail;
4718af36488SKevin Wolf             }
472bd28f835SKevin Wolf 
4733fc48d09SFrediano Ziglio             qemu_iovec_from_buffer(&hd_qiov,
474bd28f835SKevin Wolf                 s->cluster_cache + index_in_cluster * 512,
475faf575c1SFrediano Ziglio                 512 * cur_nr_sectors);
476585f8587Sbellard         } else {
477c2bdd990SFrediano Ziglio             if ((cluster_offset & 511) != 0) {
4783fc48d09SFrediano Ziglio                 ret = -EIO;
4793fc48d09SFrediano Ziglio                 goto fail;
480585f8587Sbellard             }
481c87c0672Saliguori 
482bd28f835SKevin Wolf             if (s->crypt_method) {
483bd28f835SKevin Wolf                 /*
484bd28f835SKevin Wolf                  * For encrypted images, read everything into a temporary
485bd28f835SKevin Wolf                  * contiguous buffer on which the AES functions can work.
486bd28f835SKevin Wolf                  */
4873fc48d09SFrediano Ziglio                 if (!cluster_data) {
4883fc48d09SFrediano Ziglio                     cluster_data =
489dea43a65SFrediano Ziglio                         qemu_blockalign(bs, QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
490bd28f835SKevin Wolf                 }
491bd28f835SKevin Wolf 
492faf575c1SFrediano Ziglio                 assert(cur_nr_sectors <=
493bd28f835SKevin Wolf                     QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors);
4943fc48d09SFrediano Ziglio                 qemu_iovec_reset(&hd_qiov);
4953fc48d09SFrediano Ziglio                 qemu_iovec_add(&hd_qiov, cluster_data,
496faf575c1SFrediano Ziglio                     512 * cur_nr_sectors);
497bd28f835SKevin Wolf             }
498bd28f835SKevin Wolf 
49966f82ceeSKevin Wolf             BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);
50068d100e9SKevin Wolf             qemu_co_mutex_unlock(&s->lock);
50168d100e9SKevin Wolf             ret = bdrv_co_readv(bs->file,
502c2bdd990SFrediano Ziglio                                 (cluster_offset >> 9) + index_in_cluster,
5033fc48d09SFrediano Ziglio                                 cur_nr_sectors, &hd_qiov);
50468d100e9SKevin Wolf             qemu_co_mutex_lock(&s->lock);
50568d100e9SKevin Wolf             if (ret < 0) {
5063fc48d09SFrediano Ziglio                 goto fail;
507585f8587Sbellard             }
508faf575c1SFrediano Ziglio             if (s->crypt_method) {
5093fc48d09SFrediano Ziglio                 qcow2_encrypt_sectors(s, sector_num,  cluster_data,
5103fc48d09SFrediano Ziglio                     cluster_data, cur_nr_sectors, 0, &s->aes_decrypt_key);
5113fc48d09SFrediano Ziglio                 qemu_iovec_reset(&hd_qiov);
5123fc48d09SFrediano Ziglio                 qemu_iovec_copy(&hd_qiov, qiov, bytes_done,
513faf575c1SFrediano Ziglio                     cur_nr_sectors * 512);
5143fc48d09SFrediano Ziglio                 qemu_iovec_from_buffer(&hd_qiov, cluster_data,
515faf575c1SFrediano Ziglio                     512 * cur_nr_sectors);
516171e3d6bSKevin Wolf             }
517faf575c1SFrediano Ziglio         }
518faf575c1SFrediano Ziglio 
5193fc48d09SFrediano Ziglio         remaining_sectors -= cur_nr_sectors;
5203fc48d09SFrediano Ziglio         sector_num += cur_nr_sectors;
5213fc48d09SFrediano Ziglio         bytes_done += cur_nr_sectors * 512;
5225ebaa27eSFrediano Ziglio     }
5233fc48d09SFrediano Ziglio     ret = 0;
524f141eafeSaliguori 
5253fc48d09SFrediano Ziglio fail:
52668d100e9SKevin Wolf     qemu_co_mutex_unlock(&s->lock);
52768d100e9SKevin Wolf 
5283fc48d09SFrediano Ziglio     qemu_iovec_destroy(&hd_qiov);
529dea43a65SFrediano Ziglio     qemu_vfree(cluster_data);
53068d100e9SKevin Wolf 
53168d100e9SKevin Wolf     return ret;
532585f8587Sbellard }
533585f8587Sbellard 
53468d100e9SKevin Wolf static void run_dependent_requests(BDRVQcowState *s, QCowL2Meta *m)
535f214978aSKevin Wolf {
536f214978aSKevin Wolf     /* Take the request off the list of running requests */
537f214978aSKevin Wolf     if (m->nb_clusters != 0) {
53872cf2d4fSBlue Swirl         QLIST_REMOVE(m, next_in_flight);
539f214978aSKevin Wolf     }
540f214978aSKevin Wolf 
541d4c146f0SStefan Hajnoczi     /* Restart all dependent requests */
54268d100e9SKevin Wolf     if (!qemu_co_queue_empty(&m->dependent_requests)) {
54368d100e9SKevin Wolf         qemu_co_mutex_unlock(&s->lock);
544e8ee5e4cSStefan Hajnoczi         qemu_co_queue_restart_all(&m->dependent_requests);
54568d100e9SKevin Wolf         qemu_co_mutex_lock(&s->lock);
54668d100e9SKevin Wolf     }
547f214978aSKevin Wolf }
548f214978aSKevin Wolf 
549a968168cSDong Xu Wang static coroutine_fn int qcow2_co_writev(BlockDriverState *bs,
5503fc48d09SFrediano Ziglio                            int64_t sector_num,
5513fc48d09SFrediano Ziglio                            int remaining_sectors,
5523fc48d09SFrediano Ziglio                            QEMUIOVector *qiov)
553585f8587Sbellard {
554585f8587Sbellard     BDRVQcowState *s = bs->opaque;
555585f8587Sbellard     int index_in_cluster;
556095a9c58Saliguori     int n_end;
55768d100e9SKevin Wolf     int ret;
558faf575c1SFrediano Ziglio     int cur_nr_sectors; /* number of sectors in current iteration */
559c2bdd990SFrediano Ziglio     uint64_t cluster_offset;
5603fc48d09SFrediano Ziglio     QEMUIOVector hd_qiov;
5613fc48d09SFrediano Ziglio     uint64_t bytes_done = 0;
5623fc48d09SFrediano Ziglio     uint8_t *cluster_data = NULL;
5638e217d53SKevin Wolf     QCowL2Meta l2meta = {
5648e217d53SKevin Wolf         .nb_clusters = 0,
5658e217d53SKevin Wolf     };
566c2271403SFrediano Ziglio 
567c2271403SFrediano Ziglio     qemu_co_queue_init(&l2meta.dependent_requests);
568585f8587Sbellard 
5693fc48d09SFrediano Ziglio     qemu_iovec_init(&hd_qiov, qiov->niov);
570585f8587Sbellard 
5713fc48d09SFrediano Ziglio     s->cluster_cache_offset = -1; /* disable compressed cache */
5723fc48d09SFrediano Ziglio 
5733fc48d09SFrediano Ziglio     qemu_co_mutex_lock(&s->lock);
5743fc48d09SFrediano Ziglio 
5753fc48d09SFrediano Ziglio     while (remaining_sectors != 0) {
5763fc48d09SFrediano Ziglio 
5773fc48d09SFrediano Ziglio         index_in_cluster = sector_num & (s->cluster_sectors - 1);
5783fc48d09SFrediano Ziglio         n_end = index_in_cluster + remaining_sectors;
579095a9c58Saliguori         if (s->crypt_method &&
5805ebaa27eSFrediano Ziglio             n_end > QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors) {
581095a9c58Saliguori             n_end = QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors;
5825ebaa27eSFrediano Ziglio         }
583095a9c58Saliguori 
5843fc48d09SFrediano Ziglio         ret = qcow2_alloc_cluster_offset(bs, sector_num << 9,
585c2271403SFrediano Ziglio             index_in_cluster, n_end, &cur_nr_sectors, &l2meta);
586148da7eaSKevin Wolf         if (ret < 0) {
5873fc48d09SFrediano Ziglio             goto fail;
588148da7eaSKevin Wolf         }
589148da7eaSKevin Wolf 
590c2bdd990SFrediano Ziglio         cluster_offset = l2meta.cluster_offset;
591c2bdd990SFrediano Ziglio         assert((cluster_offset & 511) == 0);
592148da7eaSKevin Wolf 
5933fc48d09SFrediano Ziglio         qemu_iovec_reset(&hd_qiov);
5943fc48d09SFrediano Ziglio         qemu_iovec_copy(&hd_qiov, qiov, bytes_done,
595faf575c1SFrediano Ziglio             cur_nr_sectors * 512);
5966f5f060bSKevin Wolf 
597585f8587Sbellard         if (s->crypt_method) {
5983fc48d09SFrediano Ziglio             if (!cluster_data) {
599dea43a65SFrediano Ziglio                 cluster_data = qemu_blockalign(bs, QCOW_MAX_CRYPT_CLUSTERS *
600095a9c58Saliguori                                                  s->cluster_size);
601585f8587Sbellard             }
6026f5f060bSKevin Wolf 
6033fc48d09SFrediano Ziglio             assert(hd_qiov.size <=
6045ebaa27eSFrediano Ziglio                    QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
6053fc48d09SFrediano Ziglio             qemu_iovec_to_buffer(&hd_qiov, cluster_data);
6066f5f060bSKevin Wolf 
6073fc48d09SFrediano Ziglio             qcow2_encrypt_sectors(s, sector_num, cluster_data,
6083fc48d09SFrediano Ziglio                 cluster_data, cur_nr_sectors, 1, &s->aes_encrypt_key);
6096f5f060bSKevin Wolf 
6103fc48d09SFrediano Ziglio             qemu_iovec_reset(&hd_qiov);
6113fc48d09SFrediano Ziglio             qemu_iovec_add(&hd_qiov, cluster_data,
612faf575c1SFrediano Ziglio                 cur_nr_sectors * 512);
613585f8587Sbellard         }
6146f5f060bSKevin Wolf 
61566f82ceeSKevin Wolf         BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO);
61668d100e9SKevin Wolf         qemu_co_mutex_unlock(&s->lock);
61768d100e9SKevin Wolf         ret = bdrv_co_writev(bs->file,
618c2bdd990SFrediano Ziglio                              (cluster_offset >> 9) + index_in_cluster,
6193fc48d09SFrediano Ziglio                              cur_nr_sectors, &hd_qiov);
62068d100e9SKevin Wolf         qemu_co_mutex_lock(&s->lock);
62168d100e9SKevin Wolf         if (ret < 0) {
6223fc48d09SFrediano Ziglio             goto fail;
623171e3d6bSKevin Wolf         }
624f141eafeSaliguori 
625c2271403SFrediano Ziglio         ret = qcow2_alloc_cluster_link_l2(bs, &l2meta);
626faf575c1SFrediano Ziglio         if (ret < 0) {
6273fc48d09SFrediano Ziglio             goto fail;
628faf575c1SFrediano Ziglio         }
629faf575c1SFrediano Ziglio 
6300fa9131aSKevin Wolf         run_dependent_requests(s, &l2meta);
6310fa9131aSKevin Wolf 
6323fc48d09SFrediano Ziglio         remaining_sectors -= cur_nr_sectors;
6333fc48d09SFrediano Ziglio         sector_num += cur_nr_sectors;
6343fc48d09SFrediano Ziglio         bytes_done += cur_nr_sectors * 512;
6355ebaa27eSFrediano Ziglio     }
6363fc48d09SFrediano Ziglio     ret = 0;
637faf575c1SFrediano Ziglio 
6383fc48d09SFrediano Ziglio fail:
6390fa9131aSKevin Wolf     run_dependent_requests(s, &l2meta);
6400fa9131aSKevin Wolf 
64168d100e9SKevin Wolf     qemu_co_mutex_unlock(&s->lock);
642585f8587Sbellard 
6433fc48d09SFrediano Ziglio     qemu_iovec_destroy(&hd_qiov);
644dea43a65SFrediano Ziglio     qemu_vfree(cluster_data);
64542496d62SKevin Wolf 
64668d100e9SKevin Wolf     return ret;
647585f8587Sbellard }
648585f8587Sbellard 
6497c80ab3fSJes Sorensen static void qcow2_close(BlockDriverState *bs)
650585f8587Sbellard {
651585f8587Sbellard     BDRVQcowState *s = bs->opaque;
6527267c094SAnthony Liguori     g_free(s->l1_table);
65329c1a730SKevin Wolf 
65429c1a730SKevin Wolf     qcow2_cache_flush(bs, s->l2_table_cache);
65529c1a730SKevin Wolf     qcow2_cache_flush(bs, s->refcount_block_cache);
65629c1a730SKevin Wolf 
65729c1a730SKevin Wolf     qcow2_cache_destroy(bs, s->l2_table_cache);
65829c1a730SKevin Wolf     qcow2_cache_destroy(bs, s->refcount_block_cache);
65929c1a730SKevin Wolf 
66075bab85cSKevin Wolf     cleanup_unknown_header_ext(bs);
6617267c094SAnthony Liguori     g_free(s->cluster_cache);
662dea43a65SFrediano Ziglio     qemu_vfree(s->cluster_data);
663ed6ccf0fSKevin Wolf     qcow2_refcount_close(bs);
66428c1202bSLi Zhi Hui     qcow2_free_snapshots(bs);
665585f8587Sbellard }
666585f8587Sbellard 
66706d9260fSAnthony Liguori static void qcow2_invalidate_cache(BlockDriverState *bs)
66806d9260fSAnthony Liguori {
66906d9260fSAnthony Liguori     BDRVQcowState *s = bs->opaque;
67006d9260fSAnthony Liguori     int flags = s->flags;
67106d9260fSAnthony Liguori     AES_KEY aes_encrypt_key;
67206d9260fSAnthony Liguori     AES_KEY aes_decrypt_key;
67306d9260fSAnthony Liguori     uint32_t crypt_method = 0;
67406d9260fSAnthony Liguori 
67506d9260fSAnthony Liguori     /*
67606d9260fSAnthony Liguori      * Backing files are read-only which makes all of their metadata immutable,
67706d9260fSAnthony Liguori      * that means we don't have to worry about reopening them here.
67806d9260fSAnthony Liguori      */
67906d9260fSAnthony Liguori 
68006d9260fSAnthony Liguori     if (s->crypt_method) {
68106d9260fSAnthony Liguori         crypt_method = s->crypt_method;
68206d9260fSAnthony Liguori         memcpy(&aes_encrypt_key, &s->aes_encrypt_key, sizeof(aes_encrypt_key));
68306d9260fSAnthony Liguori         memcpy(&aes_decrypt_key, &s->aes_decrypt_key, sizeof(aes_decrypt_key));
68406d9260fSAnthony Liguori     }
68506d9260fSAnthony Liguori 
68606d9260fSAnthony Liguori     qcow2_close(bs);
68706d9260fSAnthony Liguori 
68806d9260fSAnthony Liguori     memset(s, 0, sizeof(BDRVQcowState));
68906d9260fSAnthony Liguori     qcow2_open(bs, flags);
69006d9260fSAnthony Liguori 
69106d9260fSAnthony Liguori     if (crypt_method) {
69206d9260fSAnthony Liguori         s->crypt_method = crypt_method;
69306d9260fSAnthony Liguori         memcpy(&s->aes_encrypt_key, &aes_encrypt_key, sizeof(aes_encrypt_key));
69406d9260fSAnthony Liguori         memcpy(&s->aes_decrypt_key, &aes_decrypt_key, sizeof(aes_decrypt_key));
69506d9260fSAnthony Liguori     }
69606d9260fSAnthony Liguori }
69706d9260fSAnthony Liguori 
698e24e49e6SKevin Wolf static size_t header_ext_add(char *buf, uint32_t magic, const void *s,
699e24e49e6SKevin Wolf     size_t len, size_t buflen)
700756e6736SKevin Wolf {
701e24e49e6SKevin Wolf     QCowExtension *ext_backing_fmt = (QCowExtension*) buf;
702e24e49e6SKevin Wolf     size_t ext_len = sizeof(QCowExtension) + ((len + 7) & ~7);
703756e6736SKevin Wolf 
704e24e49e6SKevin Wolf     if (buflen < ext_len) {
705756e6736SKevin Wolf         return -ENOSPC;
706756e6736SKevin Wolf     }
707756e6736SKevin Wolf 
708e24e49e6SKevin Wolf     *ext_backing_fmt = (QCowExtension) {
709e24e49e6SKevin Wolf         .magic  = cpu_to_be32(magic),
710e24e49e6SKevin Wolf         .len    = cpu_to_be32(len),
711e24e49e6SKevin Wolf     };
712e24e49e6SKevin Wolf     memcpy(buf + sizeof(QCowExtension), s, len);
713756e6736SKevin Wolf 
714e24e49e6SKevin Wolf     return ext_len;
715756e6736SKevin Wolf }
716756e6736SKevin Wolf 
717e24e49e6SKevin Wolf /*
718e24e49e6SKevin Wolf  * Updates the qcow2 header, including the variable length parts of it, i.e.
719e24e49e6SKevin Wolf  * the backing file name and all extensions. qcow2 was not designed to allow
720e24e49e6SKevin Wolf  * such changes, so if we run out of space (we can only use the first cluster)
721e24e49e6SKevin Wolf  * this function may fail.
722e24e49e6SKevin Wolf  *
723e24e49e6SKevin Wolf  * Returns 0 on success, -errno in error cases.
724e24e49e6SKevin Wolf  */
725e24e49e6SKevin Wolf int qcow2_update_header(BlockDriverState *bs)
726e24e49e6SKevin Wolf {
727e24e49e6SKevin Wolf     BDRVQcowState *s = bs->opaque;
728e24e49e6SKevin Wolf     QCowHeader *header;
729e24e49e6SKevin Wolf     char *buf;
730e24e49e6SKevin Wolf     size_t buflen = s->cluster_size;
731e24e49e6SKevin Wolf     int ret;
732e24e49e6SKevin Wolf     uint64_t total_size;
733e24e49e6SKevin Wolf     uint32_t refcount_table_clusters;
73475bab85cSKevin Wolf     Qcow2UnknownHeaderExtension *uext;
735e24e49e6SKevin Wolf 
736e24e49e6SKevin Wolf     buf = qemu_blockalign(bs, buflen);
737e24e49e6SKevin Wolf     memset(buf, 0, s->cluster_size);
738e24e49e6SKevin Wolf 
739e24e49e6SKevin Wolf     /* Header structure */
740e24e49e6SKevin Wolf     header = (QCowHeader*) buf;
741e24e49e6SKevin Wolf 
742e24e49e6SKevin Wolf     if (buflen < sizeof(*header)) {
743e24e49e6SKevin Wolf         ret = -ENOSPC;
744e24e49e6SKevin Wolf         goto fail;
745756e6736SKevin Wolf     }
746756e6736SKevin Wolf 
747e24e49e6SKevin Wolf     total_size = bs->total_sectors * BDRV_SECTOR_SIZE;
748e24e49e6SKevin Wolf     refcount_table_clusters = s->refcount_table_size >> (s->cluster_bits - 3);
749e24e49e6SKevin Wolf 
750e24e49e6SKevin Wolf     *header = (QCowHeader) {
751e24e49e6SKevin Wolf         .magic                  = cpu_to_be32(QCOW_MAGIC),
752e24e49e6SKevin Wolf         .version                = cpu_to_be32(QCOW_VERSION),
753e24e49e6SKevin Wolf         .backing_file_offset    = 0,
754e24e49e6SKevin Wolf         .backing_file_size      = 0,
755e24e49e6SKevin Wolf         .cluster_bits           = cpu_to_be32(s->cluster_bits),
756e24e49e6SKevin Wolf         .size                   = cpu_to_be64(total_size),
757e24e49e6SKevin Wolf         .crypt_method           = cpu_to_be32(s->crypt_method_header),
758e24e49e6SKevin Wolf         .l1_size                = cpu_to_be32(s->l1_size),
759e24e49e6SKevin Wolf         .l1_table_offset        = cpu_to_be64(s->l1_table_offset),
760e24e49e6SKevin Wolf         .refcount_table_offset  = cpu_to_be64(s->refcount_table_offset),
761e24e49e6SKevin Wolf         .refcount_table_clusters = cpu_to_be32(refcount_table_clusters),
762e24e49e6SKevin Wolf         .nb_snapshots           = cpu_to_be32(s->nb_snapshots),
763e24e49e6SKevin Wolf         .snapshots_offset       = cpu_to_be64(s->snapshots_offset),
764e24e49e6SKevin Wolf     };
765e24e49e6SKevin Wolf 
766e24e49e6SKevin Wolf     buf += sizeof(*header);
767e24e49e6SKevin Wolf     buflen -= sizeof(*header);
768e24e49e6SKevin Wolf 
769e24e49e6SKevin Wolf     /* Backing file format header extension */
770e24e49e6SKevin Wolf     if (*bs->backing_format) {
771e24e49e6SKevin Wolf         ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BACKING_FORMAT,
772e24e49e6SKevin Wolf                              bs->backing_format, strlen(bs->backing_format),
773e24e49e6SKevin Wolf                              buflen);
774756e6736SKevin Wolf         if (ret < 0) {
775756e6736SKevin Wolf             goto fail;
776756e6736SKevin Wolf         }
777756e6736SKevin Wolf 
778e24e49e6SKevin Wolf         buf += ret;
779e24e49e6SKevin Wolf         buflen -= ret;
780e24e49e6SKevin Wolf     }
781756e6736SKevin Wolf 
78275bab85cSKevin Wolf     /* Keep unknown header extensions */
78375bab85cSKevin Wolf     QLIST_FOREACH(uext, &s->unknown_header_ext, next) {
78475bab85cSKevin Wolf         ret = header_ext_add(buf, uext->magic, uext->data, uext->len, buflen);
78575bab85cSKevin Wolf         if (ret < 0) {
78675bab85cSKevin Wolf             goto fail;
78775bab85cSKevin Wolf         }
78875bab85cSKevin Wolf 
78975bab85cSKevin Wolf         buf += ret;
79075bab85cSKevin Wolf         buflen -= ret;
79175bab85cSKevin Wolf     }
79275bab85cSKevin Wolf 
793e24e49e6SKevin Wolf     /* End of header extensions */
794e24e49e6SKevin Wolf     ret = header_ext_add(buf, QCOW2_EXT_MAGIC_END, NULL, 0, buflen);
795756e6736SKevin Wolf     if (ret < 0) {
796756e6736SKevin Wolf         goto fail;
797756e6736SKevin Wolf     }
798756e6736SKevin Wolf 
799e24e49e6SKevin Wolf     buf += ret;
800e24e49e6SKevin Wolf     buflen -= ret;
801e24e49e6SKevin Wolf 
802e24e49e6SKevin Wolf     /* Backing file name */
803e24e49e6SKevin Wolf     if (*bs->backing_file) {
804e24e49e6SKevin Wolf         size_t backing_file_len = strlen(bs->backing_file);
805e24e49e6SKevin Wolf 
806e24e49e6SKevin Wolf         if (buflen < backing_file_len) {
807e24e49e6SKevin Wolf             ret = -ENOSPC;
808e24e49e6SKevin Wolf             goto fail;
809e24e49e6SKevin Wolf         }
810e24e49e6SKevin Wolf 
811e24e49e6SKevin Wolf         strncpy(buf, bs->backing_file, buflen);
812e24e49e6SKevin Wolf 
813e24e49e6SKevin Wolf         header->backing_file_offset = cpu_to_be64(buf - ((char*) header));
814e24e49e6SKevin Wolf         header->backing_file_size   = cpu_to_be32(backing_file_len);
815e24e49e6SKevin Wolf     }
816e24e49e6SKevin Wolf 
817e24e49e6SKevin Wolf     /* Write the new header */
818e24e49e6SKevin Wolf     ret = bdrv_pwrite(bs->file, 0, header, s->cluster_size);
819756e6736SKevin Wolf     if (ret < 0) {
820756e6736SKevin Wolf         goto fail;
821756e6736SKevin Wolf     }
822756e6736SKevin Wolf 
823756e6736SKevin Wolf     ret = 0;
824756e6736SKevin Wolf fail:
825e24e49e6SKevin Wolf     qemu_vfree(header);
826756e6736SKevin Wolf     return ret;
827756e6736SKevin Wolf }
828756e6736SKevin Wolf 
829756e6736SKevin Wolf static int qcow2_change_backing_file(BlockDriverState *bs,
830756e6736SKevin Wolf     const char *backing_file, const char *backing_fmt)
831756e6736SKevin Wolf {
832e24e49e6SKevin Wolf     /* Backing file format doesn't make sense without a backing file */
833e24e49e6SKevin Wolf     if (backing_fmt && !backing_file) {
834e24e49e6SKevin Wolf         return -EINVAL;
835e24e49e6SKevin Wolf     }
836e24e49e6SKevin Wolf 
837e24e49e6SKevin Wolf     pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
838e24e49e6SKevin Wolf     pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
839e24e49e6SKevin Wolf 
840e24e49e6SKevin Wolf     return qcow2_update_header(bs);
841756e6736SKevin Wolf }
842756e6736SKevin Wolf 
843a35e1c17SKevin Wolf static int preallocate(BlockDriverState *bs)
844a35e1c17SKevin Wolf {
845a35e1c17SKevin Wolf     uint64_t nb_sectors;
846a35e1c17SKevin Wolf     uint64_t offset;
847a35e1c17SKevin Wolf     int num;
848148da7eaSKevin Wolf     int ret;
849a35e1c17SKevin Wolf     QCowL2Meta meta;
850a35e1c17SKevin Wolf 
851a35e1c17SKevin Wolf     nb_sectors = bdrv_getlength(bs) >> 9;
852a35e1c17SKevin Wolf     offset = 0;
85368d100e9SKevin Wolf     qemu_co_queue_init(&meta.dependent_requests);
854148da7eaSKevin Wolf     meta.cluster_offset = 0;
855a35e1c17SKevin Wolf 
856a35e1c17SKevin Wolf     while (nb_sectors) {
857a35e1c17SKevin Wolf         num = MIN(nb_sectors, INT_MAX >> 9);
858148da7eaSKevin Wolf         ret = qcow2_alloc_cluster_offset(bs, offset, 0, num, &num, &meta);
859148da7eaSKevin Wolf         if (ret < 0) {
86019dbcbf7SKevin Wolf             return ret;
861a35e1c17SKevin Wolf         }
862a35e1c17SKevin Wolf 
86319dbcbf7SKevin Wolf         ret = qcow2_alloc_cluster_link_l2(bs, &meta);
86419dbcbf7SKevin Wolf         if (ret < 0) {
865148da7eaSKevin Wolf             qcow2_free_any_clusters(bs, meta.cluster_offset, meta.nb_clusters);
86619dbcbf7SKevin Wolf             return ret;
867a35e1c17SKevin Wolf         }
868a35e1c17SKevin Wolf 
869f214978aSKevin Wolf         /* There are no dependent requests, but we need to remove our request
870f214978aSKevin Wolf          * from the list of in-flight requests */
87168d100e9SKevin Wolf         run_dependent_requests(bs->opaque, &meta);
872f214978aSKevin Wolf 
873a35e1c17SKevin Wolf         /* TODO Preallocate data if requested */
874a35e1c17SKevin Wolf 
875a35e1c17SKevin Wolf         nb_sectors -= num;
876a35e1c17SKevin Wolf         offset += num << 9;
877a35e1c17SKevin Wolf     }
878a35e1c17SKevin Wolf 
879a35e1c17SKevin Wolf     /*
880a35e1c17SKevin Wolf      * It is expected that the image file is large enough to actually contain
881a35e1c17SKevin Wolf      * all of the allocated clusters (otherwise we get failing reads after
882a35e1c17SKevin Wolf      * EOF). Extend the image to the last allocated sector.
883a35e1c17SKevin Wolf      */
884148da7eaSKevin Wolf     if (meta.cluster_offset != 0) {
885ea80b906SKevin Wolf         uint8_t buf[512];
886ea80b906SKevin Wolf         memset(buf, 0, 512);
88719dbcbf7SKevin Wolf         ret = bdrv_write(bs->file, (meta.cluster_offset >> 9) + num - 1, buf, 1);
88819dbcbf7SKevin Wolf         if (ret < 0) {
88919dbcbf7SKevin Wolf             return ret;
89019dbcbf7SKevin Wolf         }
891a35e1c17SKevin Wolf     }
892a35e1c17SKevin Wolf 
893a35e1c17SKevin Wolf     return 0;
894a35e1c17SKevin Wolf }
895a35e1c17SKevin Wolf 
8967c80ab3fSJes Sorensen static int qcow2_create2(const char *filename, int64_t total_size,
897a9420734SKevin Wolf                          const char *backing_file, const char *backing_format,
898a9420734SKevin Wolf                          int flags, size_t cluster_size, int prealloc,
899a9420734SKevin Wolf                          QEMUOptionParameter *options)
900a9420734SKevin Wolf {
9019b2260cbSDong Xu Wang     /* Calculate cluster_bits */
902a9420734SKevin Wolf     int cluster_bits;
903a9420734SKevin Wolf     cluster_bits = ffs(cluster_size) - 1;
904a9420734SKevin Wolf     if (cluster_bits < MIN_CLUSTER_BITS || cluster_bits > MAX_CLUSTER_BITS ||
905a9420734SKevin Wolf         (1 << cluster_bits) != cluster_size)
906a9420734SKevin Wolf     {
907a9420734SKevin Wolf         error_report(
9086daf194dSMarkus Armbruster             "Cluster size must be a power of two between %d and %dk",
909a9420734SKevin Wolf             1 << MIN_CLUSTER_BITS, 1 << (MAX_CLUSTER_BITS - 10));
910a9420734SKevin Wolf         return -EINVAL;
911a9420734SKevin Wolf     }
912a9420734SKevin Wolf 
913a9420734SKevin Wolf     /*
914a9420734SKevin Wolf      * Open the image file and write a minimal qcow2 header.
915a9420734SKevin Wolf      *
916a9420734SKevin Wolf      * We keep things simple and start with a zero-sized image. We also
917a9420734SKevin Wolf      * do without refcount blocks or a L1 table for now. We'll fix the
918a9420734SKevin Wolf      * inconsistency later.
919a9420734SKevin Wolf      *
920a9420734SKevin Wolf      * We do need a refcount table because growing the refcount table means
921a9420734SKevin Wolf      * allocating two new refcount blocks - the seconds of which would be at
922a9420734SKevin Wolf      * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
923a9420734SKevin Wolf      * size for any qcow2 image.
924a9420734SKevin Wolf      */
925a9420734SKevin Wolf     BlockDriverState* bs;
926a9420734SKevin Wolf     QCowHeader header;
927a9420734SKevin Wolf     uint8_t* refcount_table;
928a9420734SKevin Wolf     int ret;
929a9420734SKevin Wolf 
930a9420734SKevin Wolf     ret = bdrv_create_file(filename, options);
931a9420734SKevin Wolf     if (ret < 0) {
932a9420734SKevin Wolf         return ret;
933a9420734SKevin Wolf     }
934a9420734SKevin Wolf 
935a9420734SKevin Wolf     ret = bdrv_file_open(&bs, filename, BDRV_O_RDWR);
936a9420734SKevin Wolf     if (ret < 0) {
937a9420734SKevin Wolf         return ret;
938a9420734SKevin Wolf     }
939a9420734SKevin Wolf 
940a9420734SKevin Wolf     /* Write the header */
941a9420734SKevin Wolf     memset(&header, 0, sizeof(header));
942a9420734SKevin Wolf     header.magic = cpu_to_be32(QCOW_MAGIC);
943a9420734SKevin Wolf     header.version = cpu_to_be32(QCOW_VERSION);
944a9420734SKevin Wolf     header.cluster_bits = cpu_to_be32(cluster_bits);
945a9420734SKevin Wolf     header.size = cpu_to_be64(0);
946a9420734SKevin Wolf     header.l1_table_offset = cpu_to_be64(0);
947a9420734SKevin Wolf     header.l1_size = cpu_to_be32(0);
948a9420734SKevin Wolf     header.refcount_table_offset = cpu_to_be64(cluster_size);
949a9420734SKevin Wolf     header.refcount_table_clusters = cpu_to_be32(1);
950a9420734SKevin Wolf 
951a9420734SKevin Wolf     if (flags & BLOCK_FLAG_ENCRYPT) {
952a9420734SKevin Wolf         header.crypt_method = cpu_to_be32(QCOW_CRYPT_AES);
953a9420734SKevin Wolf     } else {
954a9420734SKevin Wolf         header.crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
955a9420734SKevin Wolf     }
956a9420734SKevin Wolf 
957a9420734SKevin Wolf     ret = bdrv_pwrite(bs, 0, &header, sizeof(header));
958a9420734SKevin Wolf     if (ret < 0) {
959a9420734SKevin Wolf         goto out;
960a9420734SKevin Wolf     }
961a9420734SKevin Wolf 
962a9420734SKevin Wolf     /* Write an empty refcount table */
9637267c094SAnthony Liguori     refcount_table = g_malloc0(cluster_size);
964a9420734SKevin Wolf     ret = bdrv_pwrite(bs, cluster_size, refcount_table, cluster_size);
9657267c094SAnthony Liguori     g_free(refcount_table);
966a9420734SKevin Wolf 
967a9420734SKevin Wolf     if (ret < 0) {
968a9420734SKevin Wolf         goto out;
969a9420734SKevin Wolf     }
970a9420734SKevin Wolf 
971a9420734SKevin Wolf     bdrv_close(bs);
972a9420734SKevin Wolf 
973a9420734SKevin Wolf     /*
974a9420734SKevin Wolf      * And now open the image and make it consistent first (i.e. increase the
975a9420734SKevin Wolf      * refcount of the cluster that is occupied by the header and the refcount
976a9420734SKevin Wolf      * table)
977a9420734SKevin Wolf      */
978a9420734SKevin Wolf     BlockDriver* drv = bdrv_find_format("qcow2");
979a9420734SKevin Wolf     assert(drv != NULL);
980e1a7107fSKevin Wolf     ret = bdrv_open(bs, filename,
981e1a7107fSKevin Wolf         BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_NO_FLUSH, drv);
982a9420734SKevin Wolf     if (ret < 0) {
983a9420734SKevin Wolf         goto out;
984a9420734SKevin Wolf     }
985a9420734SKevin Wolf 
986a9420734SKevin Wolf     ret = qcow2_alloc_clusters(bs, 2 * cluster_size);
987a9420734SKevin Wolf     if (ret < 0) {
988a9420734SKevin Wolf         goto out;
989a9420734SKevin Wolf 
990a9420734SKevin Wolf     } else if (ret != 0) {
991a9420734SKevin Wolf         error_report("Huh, first cluster in empty image is already in use?");
992a9420734SKevin Wolf         abort();
993a9420734SKevin Wolf     }
994a9420734SKevin Wolf 
995a9420734SKevin Wolf     /* Okay, now that we have a valid image, let's give it the right size */
996a9420734SKevin Wolf     ret = bdrv_truncate(bs, total_size * BDRV_SECTOR_SIZE);
997a9420734SKevin Wolf     if (ret < 0) {
998a9420734SKevin Wolf         goto out;
999a9420734SKevin Wolf     }
1000a9420734SKevin Wolf 
1001a9420734SKevin Wolf     /* Want a backing file? There you go.*/
1002a9420734SKevin Wolf     if (backing_file) {
1003a9420734SKevin Wolf         ret = bdrv_change_backing_file(bs, backing_file, backing_format);
1004a9420734SKevin Wolf         if (ret < 0) {
1005a9420734SKevin Wolf             goto out;
1006a9420734SKevin Wolf         }
1007a9420734SKevin Wolf     }
1008a9420734SKevin Wolf 
1009a9420734SKevin Wolf     /* And if we're supposed to preallocate metadata, do that now */
1010a9420734SKevin Wolf     if (prealloc) {
1011a9420734SKevin Wolf         ret = preallocate(bs);
1012a9420734SKevin Wolf         if (ret < 0) {
1013a9420734SKevin Wolf             goto out;
1014a9420734SKevin Wolf         }
1015a9420734SKevin Wolf     }
1016a9420734SKevin Wolf 
1017a9420734SKevin Wolf     ret = 0;
1018a9420734SKevin Wolf out:
1019a9420734SKevin Wolf     bdrv_delete(bs);
1020a9420734SKevin Wolf     return ret;
1021a9420734SKevin Wolf }
1022de5f3f40SKevin Wolf 
10237c80ab3fSJes Sorensen static int qcow2_create(const char *filename, QEMUOptionParameter *options)
1024de5f3f40SKevin Wolf {
1025de5f3f40SKevin Wolf     const char *backing_file = NULL;
1026de5f3f40SKevin Wolf     const char *backing_fmt = NULL;
1027de5f3f40SKevin Wolf     uint64_t sectors = 0;
1028de5f3f40SKevin Wolf     int flags = 0;
102999cce9faSKevin Wolf     size_t cluster_size = DEFAULT_CLUSTER_SIZE;
1030de5f3f40SKevin Wolf     int prealloc = 0;
1031de5f3f40SKevin Wolf 
1032de5f3f40SKevin Wolf     /* Read out options */
1033de5f3f40SKevin Wolf     while (options && options->name) {
1034de5f3f40SKevin Wolf         if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
1035de5f3f40SKevin Wolf             sectors = options->value.n / 512;
1036de5f3f40SKevin Wolf         } else if (!strcmp(options->name, BLOCK_OPT_BACKING_FILE)) {
1037de5f3f40SKevin Wolf             backing_file = options->value.s;
1038de5f3f40SKevin Wolf         } else if (!strcmp(options->name, BLOCK_OPT_BACKING_FMT)) {
1039de5f3f40SKevin Wolf             backing_fmt = options->value.s;
1040de5f3f40SKevin Wolf         } else if (!strcmp(options->name, BLOCK_OPT_ENCRYPT)) {
1041de5f3f40SKevin Wolf             flags |= options->value.n ? BLOCK_FLAG_ENCRYPT : 0;
1042de5f3f40SKevin Wolf         } else if (!strcmp(options->name, BLOCK_OPT_CLUSTER_SIZE)) {
1043de5f3f40SKevin Wolf             if (options->value.n) {
1044de5f3f40SKevin Wolf                 cluster_size = options->value.n;
1045de5f3f40SKevin Wolf             }
1046de5f3f40SKevin Wolf         } else if (!strcmp(options->name, BLOCK_OPT_PREALLOC)) {
1047de5f3f40SKevin Wolf             if (!options->value.s || !strcmp(options->value.s, "off")) {
1048de5f3f40SKevin Wolf                 prealloc = 0;
1049de5f3f40SKevin Wolf             } else if (!strcmp(options->value.s, "metadata")) {
1050de5f3f40SKevin Wolf                 prealloc = 1;
1051de5f3f40SKevin Wolf             } else {
1052de5f3f40SKevin Wolf                 fprintf(stderr, "Invalid preallocation mode: '%s'\n",
1053de5f3f40SKevin Wolf                     options->value.s);
1054de5f3f40SKevin Wolf                 return -EINVAL;
1055de5f3f40SKevin Wolf             }
1056de5f3f40SKevin Wolf         }
1057de5f3f40SKevin Wolf         options++;
1058de5f3f40SKevin Wolf     }
1059de5f3f40SKevin Wolf 
1060de5f3f40SKevin Wolf     if (backing_file && prealloc) {
1061de5f3f40SKevin Wolf         fprintf(stderr, "Backing file and preallocation cannot be used at "
1062de5f3f40SKevin Wolf             "the same time\n");
1063de5f3f40SKevin Wolf         return -EINVAL;
1064de5f3f40SKevin Wolf     }
1065de5f3f40SKevin Wolf 
10667c80ab3fSJes Sorensen     return qcow2_create2(filename, sectors, backing_file, backing_fmt, flags,
1067a9420734SKevin Wolf                          cluster_size, prealloc, options);
1068de5f3f40SKevin Wolf }
1069de5f3f40SKevin Wolf 
10707c80ab3fSJes Sorensen static int qcow2_make_empty(BlockDriverState *bs)
107120d97356SBlue Swirl {
107220d97356SBlue Swirl #if 0
107320d97356SBlue Swirl     /* XXX: not correct */
107420d97356SBlue Swirl     BDRVQcowState *s = bs->opaque;
107520d97356SBlue Swirl     uint32_t l1_length = s->l1_size * sizeof(uint64_t);
107620d97356SBlue Swirl     int ret;
107720d97356SBlue Swirl 
107820d97356SBlue Swirl     memset(s->l1_table, 0, l1_length);
107966f82ceeSKevin Wolf     if (bdrv_pwrite(bs->file, s->l1_table_offset, s->l1_table, l1_length) < 0)
108020d97356SBlue Swirl         return -1;
108166f82ceeSKevin Wolf     ret = bdrv_truncate(bs->file, s->l1_table_offset + l1_length);
108220d97356SBlue Swirl     if (ret < 0)
108320d97356SBlue Swirl         return ret;
108420d97356SBlue Swirl 
108520d97356SBlue Swirl     l2_cache_reset(bs);
108620d97356SBlue Swirl #endif
108720d97356SBlue Swirl     return 0;
108820d97356SBlue Swirl }
108920d97356SBlue Swirl 
10906db39ae2SPaolo Bonzini static coroutine_fn int qcow2_co_discard(BlockDriverState *bs,
10916db39ae2SPaolo Bonzini     int64_t sector_num, int nb_sectors)
10925ea929e3SKevin Wolf {
10936db39ae2SPaolo Bonzini     int ret;
10946db39ae2SPaolo Bonzini     BDRVQcowState *s = bs->opaque;
10956db39ae2SPaolo Bonzini 
10966db39ae2SPaolo Bonzini     qemu_co_mutex_lock(&s->lock);
10976db39ae2SPaolo Bonzini     ret = qcow2_discard_clusters(bs, sector_num << BDRV_SECTOR_BITS,
10985ea929e3SKevin Wolf         nb_sectors);
10996db39ae2SPaolo Bonzini     qemu_co_mutex_unlock(&s->lock);
11006db39ae2SPaolo Bonzini     return ret;
11015ea929e3SKevin Wolf }
11025ea929e3SKevin Wolf 
1103419b19d9SStefan Hajnoczi static int qcow2_truncate(BlockDriverState *bs, int64_t offset)
1104419b19d9SStefan Hajnoczi {
1105419b19d9SStefan Hajnoczi     BDRVQcowState *s = bs->opaque;
1106419b19d9SStefan Hajnoczi     int ret, new_l1_size;
1107419b19d9SStefan Hajnoczi 
1108419b19d9SStefan Hajnoczi     if (offset & 511) {
1109419b19d9SStefan Hajnoczi         return -EINVAL;
1110419b19d9SStefan Hajnoczi     }
1111419b19d9SStefan Hajnoczi 
1112419b19d9SStefan Hajnoczi     /* cannot proceed if image has snapshots */
1113419b19d9SStefan Hajnoczi     if (s->nb_snapshots) {
1114419b19d9SStefan Hajnoczi         return -ENOTSUP;
1115419b19d9SStefan Hajnoczi     }
1116419b19d9SStefan Hajnoczi 
1117419b19d9SStefan Hajnoczi     /* shrinking is currently not supported */
1118419b19d9SStefan Hajnoczi     if (offset < bs->total_sectors * 512) {
1119419b19d9SStefan Hajnoczi         return -ENOTSUP;
1120419b19d9SStefan Hajnoczi     }
1121419b19d9SStefan Hajnoczi 
1122419b19d9SStefan Hajnoczi     new_l1_size = size_to_l1(s, offset);
112372893756SStefan Hajnoczi     ret = qcow2_grow_l1_table(bs, new_l1_size, true);
1124419b19d9SStefan Hajnoczi     if (ret < 0) {
1125419b19d9SStefan Hajnoczi         return ret;
1126419b19d9SStefan Hajnoczi     }
1127419b19d9SStefan Hajnoczi 
1128419b19d9SStefan Hajnoczi     /* write updated header.size */
1129419b19d9SStefan Hajnoczi     offset = cpu_to_be64(offset);
11308b3b7206SKevin Wolf     ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, size),
1131419b19d9SStefan Hajnoczi                            &offset, sizeof(uint64_t));
1132419b19d9SStefan Hajnoczi     if (ret < 0) {
1133419b19d9SStefan Hajnoczi         return ret;
1134419b19d9SStefan Hajnoczi     }
1135419b19d9SStefan Hajnoczi 
1136419b19d9SStefan Hajnoczi     s->l1_vm_state_index = new_l1_size;
1137419b19d9SStefan Hajnoczi     return 0;
1138419b19d9SStefan Hajnoczi }
1139419b19d9SStefan Hajnoczi 
114020d97356SBlue Swirl /* XXX: put compressed sectors first, then all the cluster aligned
114120d97356SBlue Swirl    tables to avoid losing bytes in alignment */
11427c80ab3fSJes Sorensen static int qcow2_write_compressed(BlockDriverState *bs, int64_t sector_num,
114320d97356SBlue Swirl                                   const uint8_t *buf, int nb_sectors)
114420d97356SBlue Swirl {
114520d97356SBlue Swirl     BDRVQcowState *s = bs->opaque;
114620d97356SBlue Swirl     z_stream strm;
114720d97356SBlue Swirl     int ret, out_len;
114820d97356SBlue Swirl     uint8_t *out_buf;
114920d97356SBlue Swirl     uint64_t cluster_offset;
115020d97356SBlue Swirl 
115120d97356SBlue Swirl     if (nb_sectors == 0) {
115220d97356SBlue Swirl         /* align end of file to a sector boundary to ease reading with
115320d97356SBlue Swirl            sector based I/Os */
115466f82ceeSKevin Wolf         cluster_offset = bdrv_getlength(bs->file);
115520d97356SBlue Swirl         cluster_offset = (cluster_offset + 511) & ~511;
115666f82ceeSKevin Wolf         bdrv_truncate(bs->file, cluster_offset);
115720d97356SBlue Swirl         return 0;
115820d97356SBlue Swirl     }
115920d97356SBlue Swirl 
116020d97356SBlue Swirl     if (nb_sectors != s->cluster_sectors)
116120d97356SBlue Swirl         return -EINVAL;
116220d97356SBlue Swirl 
11637267c094SAnthony Liguori     out_buf = g_malloc(s->cluster_size + (s->cluster_size / 1000) + 128);
116420d97356SBlue Swirl 
116520d97356SBlue Swirl     /* best compression, small window, no zlib header */
116620d97356SBlue Swirl     memset(&strm, 0, sizeof(strm));
116720d97356SBlue Swirl     ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
116820d97356SBlue Swirl                        Z_DEFLATED, -12,
116920d97356SBlue Swirl                        9, Z_DEFAULT_STRATEGY);
117020d97356SBlue Swirl     if (ret != 0) {
11718f1efd00SKevin Wolf         ret = -EINVAL;
11728f1efd00SKevin Wolf         goto fail;
117320d97356SBlue Swirl     }
117420d97356SBlue Swirl 
117520d97356SBlue Swirl     strm.avail_in = s->cluster_size;
117620d97356SBlue Swirl     strm.next_in = (uint8_t *)buf;
117720d97356SBlue Swirl     strm.avail_out = s->cluster_size;
117820d97356SBlue Swirl     strm.next_out = out_buf;
117920d97356SBlue Swirl 
118020d97356SBlue Swirl     ret = deflate(&strm, Z_FINISH);
118120d97356SBlue Swirl     if (ret != Z_STREAM_END && ret != Z_OK) {
118220d97356SBlue Swirl         deflateEnd(&strm);
11838f1efd00SKevin Wolf         ret = -EINVAL;
11848f1efd00SKevin Wolf         goto fail;
118520d97356SBlue Swirl     }
118620d97356SBlue Swirl     out_len = strm.next_out - out_buf;
118720d97356SBlue Swirl 
118820d97356SBlue Swirl     deflateEnd(&strm);
118920d97356SBlue Swirl 
119020d97356SBlue Swirl     if (ret != Z_STREAM_END || out_len >= s->cluster_size) {
119120d97356SBlue Swirl         /* could not compress: write normal cluster */
11928f1efd00SKevin Wolf         ret = bdrv_write(bs, sector_num, buf, s->cluster_sectors);
11938f1efd00SKevin Wolf         if (ret < 0) {
11948f1efd00SKevin Wolf             goto fail;
11958f1efd00SKevin Wolf         }
119620d97356SBlue Swirl     } else {
119720d97356SBlue Swirl         cluster_offset = qcow2_alloc_compressed_cluster_offset(bs,
119820d97356SBlue Swirl             sector_num << 9, out_len);
11998f1efd00SKevin Wolf         if (!cluster_offset) {
12008f1efd00SKevin Wolf             ret = -EIO;
12018f1efd00SKevin Wolf             goto fail;
12028f1efd00SKevin Wolf         }
120320d97356SBlue Swirl         cluster_offset &= s->cluster_offset_mask;
120466f82ceeSKevin Wolf         BLKDBG_EVENT(bs->file, BLKDBG_WRITE_COMPRESSED);
12058f1efd00SKevin Wolf         ret = bdrv_pwrite(bs->file, cluster_offset, out_buf, out_len);
12068f1efd00SKevin Wolf         if (ret < 0) {
12078f1efd00SKevin Wolf             goto fail;
120820d97356SBlue Swirl         }
120920d97356SBlue Swirl     }
121020d97356SBlue Swirl 
12118f1efd00SKevin Wolf     ret = 0;
12128f1efd00SKevin Wolf fail:
12137267c094SAnthony Liguori     g_free(out_buf);
12148f1efd00SKevin Wolf     return ret;
121520d97356SBlue Swirl }
121620d97356SBlue Swirl 
1217a968168cSDong Xu Wang static coroutine_fn int qcow2_co_flush_to_os(BlockDriverState *bs)
121820d97356SBlue Swirl {
121929c1a730SKevin Wolf     BDRVQcowState *s = bs->opaque;
122029c1a730SKevin Wolf     int ret;
122129c1a730SKevin Wolf 
12228b94ff85SPaolo Bonzini     qemu_co_mutex_lock(&s->lock);
122329c1a730SKevin Wolf     ret = qcow2_cache_flush(bs, s->l2_table_cache);
122429c1a730SKevin Wolf     if (ret < 0) {
1225c95de7e2SDong Xu Wang         qemu_co_mutex_unlock(&s->lock);
12268b94ff85SPaolo Bonzini         return ret;
122729c1a730SKevin Wolf     }
122829c1a730SKevin Wolf 
122929c1a730SKevin Wolf     ret = qcow2_cache_flush(bs, s->refcount_block_cache);
123029c1a730SKevin Wolf     if (ret < 0) {
1231c95de7e2SDong Xu Wang         qemu_co_mutex_unlock(&s->lock);
12328b94ff85SPaolo Bonzini         return ret;
123329c1a730SKevin Wolf     }
12348b94ff85SPaolo Bonzini     qemu_co_mutex_unlock(&s->lock);
123529c1a730SKevin Wolf 
1236eb489bb1SKevin Wolf     return 0;
1237eb489bb1SKevin Wolf }
1238eb489bb1SKevin Wolf 
1239a968168cSDong Xu Wang static coroutine_fn int qcow2_co_flush_to_disk(BlockDriverState *bs)
1240eb489bb1SKevin Wolf {
12418b94ff85SPaolo Bonzini     return bdrv_co_flush(bs->file);
124220d97356SBlue Swirl }
124320d97356SBlue Swirl 
12447c80ab3fSJes Sorensen static int64_t qcow2_vm_state_offset(BDRVQcowState *s)
124520d97356SBlue Swirl {
124620d97356SBlue Swirl 	return (int64_t)s->l1_vm_state_index << (s->cluster_bits + s->l2_bits);
124720d97356SBlue Swirl }
124820d97356SBlue Swirl 
12497c80ab3fSJes Sorensen static int qcow2_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
125020d97356SBlue Swirl {
125120d97356SBlue Swirl     BDRVQcowState *s = bs->opaque;
125220d97356SBlue Swirl     bdi->cluster_size = s->cluster_size;
12537c80ab3fSJes Sorensen     bdi->vm_state_offset = qcow2_vm_state_offset(s);
125420d97356SBlue Swirl     return 0;
125520d97356SBlue Swirl }
125620d97356SBlue Swirl 
125720d97356SBlue Swirl 
12587c80ab3fSJes Sorensen static int qcow2_check(BlockDriverState *bs, BdrvCheckResult *result)
125920d97356SBlue Swirl {
12609ac228e0SKevin Wolf     return qcow2_check_refcounts(bs, result);
126120d97356SBlue Swirl }
126220d97356SBlue Swirl 
126320d97356SBlue Swirl #if 0
126420d97356SBlue Swirl static void dump_refcounts(BlockDriverState *bs)
126520d97356SBlue Swirl {
126620d97356SBlue Swirl     BDRVQcowState *s = bs->opaque;
126720d97356SBlue Swirl     int64_t nb_clusters, k, k1, size;
126820d97356SBlue Swirl     int refcount;
126920d97356SBlue Swirl 
127066f82ceeSKevin Wolf     size = bdrv_getlength(bs->file);
127120d97356SBlue Swirl     nb_clusters = size_to_clusters(s, size);
127220d97356SBlue Swirl     for(k = 0; k < nb_clusters;) {
127320d97356SBlue Swirl         k1 = k;
127420d97356SBlue Swirl         refcount = get_refcount(bs, k);
127520d97356SBlue Swirl         k++;
127620d97356SBlue Swirl         while (k < nb_clusters && get_refcount(bs, k) == refcount)
127720d97356SBlue Swirl             k++;
12780bfcd599SBlue Swirl         printf("%" PRId64 ": refcount=%d nb=%" PRId64 "\n", k, refcount,
12790bfcd599SBlue Swirl                k - k1);
128020d97356SBlue Swirl     }
128120d97356SBlue Swirl }
128220d97356SBlue Swirl #endif
128320d97356SBlue Swirl 
12847c80ab3fSJes Sorensen static int qcow2_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
128520d97356SBlue Swirl                               int64_t pos, int size)
128620d97356SBlue Swirl {
128720d97356SBlue Swirl     BDRVQcowState *s = bs->opaque;
128820d97356SBlue Swirl     int growable = bs->growable;
128920d97356SBlue Swirl     int ret;
129020d97356SBlue Swirl 
129166f82ceeSKevin Wolf     BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_SAVE);
129220d97356SBlue Swirl     bs->growable = 1;
12937c80ab3fSJes Sorensen     ret = bdrv_pwrite(bs, qcow2_vm_state_offset(s) + pos, buf, size);
129420d97356SBlue Swirl     bs->growable = growable;
129520d97356SBlue Swirl 
129620d97356SBlue Swirl     return ret;
129720d97356SBlue Swirl }
129820d97356SBlue Swirl 
12997c80ab3fSJes Sorensen static int qcow2_load_vmstate(BlockDriverState *bs, uint8_t *buf,
130020d97356SBlue Swirl                               int64_t pos, int size)
130120d97356SBlue Swirl {
130220d97356SBlue Swirl     BDRVQcowState *s = bs->opaque;
130320d97356SBlue Swirl     int growable = bs->growable;
130420d97356SBlue Swirl     int ret;
130520d97356SBlue Swirl 
130666f82ceeSKevin Wolf     BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_LOAD);
130720d97356SBlue Swirl     bs->growable = 1;
13087c80ab3fSJes Sorensen     ret = bdrv_pread(bs, qcow2_vm_state_offset(s) + pos, buf, size);
130920d97356SBlue Swirl     bs->growable = growable;
131020d97356SBlue Swirl 
131120d97356SBlue Swirl     return ret;
131220d97356SBlue Swirl }
131320d97356SBlue Swirl 
13147c80ab3fSJes Sorensen static QEMUOptionParameter qcow2_create_options[] = {
131520d97356SBlue Swirl     {
131620d97356SBlue Swirl         .name = BLOCK_OPT_SIZE,
131720d97356SBlue Swirl         .type = OPT_SIZE,
131820d97356SBlue Swirl         .help = "Virtual disk size"
131920d97356SBlue Swirl     },
132020d97356SBlue Swirl     {
132120d97356SBlue Swirl         .name = BLOCK_OPT_BACKING_FILE,
132220d97356SBlue Swirl         .type = OPT_STRING,
132320d97356SBlue Swirl         .help = "File name of a base image"
132420d97356SBlue Swirl     },
132520d97356SBlue Swirl     {
132620d97356SBlue Swirl         .name = BLOCK_OPT_BACKING_FMT,
132720d97356SBlue Swirl         .type = OPT_STRING,
132820d97356SBlue Swirl         .help = "Image format of the base image"
132920d97356SBlue Swirl     },
133020d97356SBlue Swirl     {
133120d97356SBlue Swirl         .name = BLOCK_OPT_ENCRYPT,
133220d97356SBlue Swirl         .type = OPT_FLAG,
133320d97356SBlue Swirl         .help = "Encrypt the image"
133420d97356SBlue Swirl     },
133520d97356SBlue Swirl     {
133620d97356SBlue Swirl         .name = BLOCK_OPT_CLUSTER_SIZE,
133720d97356SBlue Swirl         .type = OPT_SIZE,
133899cce9faSKevin Wolf         .help = "qcow2 cluster size",
133999cce9faSKevin Wolf         .value = { .n = DEFAULT_CLUSTER_SIZE },
134020d97356SBlue Swirl     },
134120d97356SBlue Swirl     {
134220d97356SBlue Swirl         .name = BLOCK_OPT_PREALLOC,
134320d97356SBlue Swirl         .type = OPT_STRING,
134420d97356SBlue Swirl         .help = "Preallocation mode (allowed values: off, metadata)"
134520d97356SBlue Swirl     },
134620d97356SBlue Swirl     { NULL }
134720d97356SBlue Swirl };
134820d97356SBlue Swirl 
134920d97356SBlue Swirl static BlockDriver bdrv_qcow2 = {
135020d97356SBlue Swirl     .format_name        = "qcow2",
135120d97356SBlue Swirl     .instance_size      = sizeof(BDRVQcowState),
13527c80ab3fSJes Sorensen     .bdrv_probe         = qcow2_probe,
13537c80ab3fSJes Sorensen     .bdrv_open          = qcow2_open,
13547c80ab3fSJes Sorensen     .bdrv_close         = qcow2_close,
13557c80ab3fSJes Sorensen     .bdrv_create        = qcow2_create,
1356f8a2e5e3SStefan Hajnoczi     .bdrv_co_is_allocated = qcow2_co_is_allocated,
13577c80ab3fSJes Sorensen     .bdrv_set_key       = qcow2_set_key,
13587c80ab3fSJes Sorensen     .bdrv_make_empty    = qcow2_make_empty,
135920d97356SBlue Swirl 
136068d100e9SKevin Wolf     .bdrv_co_readv          = qcow2_co_readv,
136168d100e9SKevin Wolf     .bdrv_co_writev         = qcow2_co_writev,
1362eb489bb1SKevin Wolf     .bdrv_co_flush_to_os    = qcow2_co_flush_to_os,
1363eb489bb1SKevin Wolf     .bdrv_co_flush_to_disk  = qcow2_co_flush_to_disk,
1364419b19d9SStefan Hajnoczi 
13656db39ae2SPaolo Bonzini     .bdrv_co_discard        = qcow2_co_discard,
1366419b19d9SStefan Hajnoczi     .bdrv_truncate          = qcow2_truncate,
13677c80ab3fSJes Sorensen     .bdrv_write_compressed  = qcow2_write_compressed,
136820d97356SBlue Swirl 
136920d97356SBlue Swirl     .bdrv_snapshot_create   = qcow2_snapshot_create,
137020d97356SBlue Swirl     .bdrv_snapshot_goto     = qcow2_snapshot_goto,
137120d97356SBlue Swirl     .bdrv_snapshot_delete   = qcow2_snapshot_delete,
137220d97356SBlue Swirl     .bdrv_snapshot_list     = qcow2_snapshot_list,
137351ef6727Sedison     .bdrv_snapshot_load_tmp     = qcow2_snapshot_load_tmp,
13747c80ab3fSJes Sorensen     .bdrv_get_info      = qcow2_get_info,
137520d97356SBlue Swirl 
13767c80ab3fSJes Sorensen     .bdrv_save_vmstate    = qcow2_save_vmstate,
13777c80ab3fSJes Sorensen     .bdrv_load_vmstate    = qcow2_load_vmstate,
137820d97356SBlue Swirl 
137920d97356SBlue Swirl     .bdrv_change_backing_file   = qcow2_change_backing_file,
138020d97356SBlue Swirl 
138106d9260fSAnthony Liguori     .bdrv_invalidate_cache      = qcow2_invalidate_cache,
138206d9260fSAnthony Liguori 
13837c80ab3fSJes Sorensen     .create_options = qcow2_create_options,
13847c80ab3fSJes Sorensen     .bdrv_check = qcow2_check,
138520d97356SBlue Swirl };
138620d97356SBlue Swirl 
13875efa9d5aSAnthony Liguori static void bdrv_qcow2_init(void)
13885efa9d5aSAnthony Liguori {
13895efa9d5aSAnthony Liguori     bdrv_register(&bdrv_qcow2);
13905efa9d5aSAnthony Liguori }
13915efa9d5aSAnthony Liguori 
13925efa9d5aSAnthony Liguori block_init(bdrv_qcow2_init);
1393