xref: /qemu/block/qcow2.c (revision 3fc48d0983a989d2227668bbcaae1681ea37fddd)
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 {
809b80ddf3Saliguori     QCowExtension ext;
819b80ddf3Saliguori     uint64_t offset;
829b80ddf3Saliguori 
839b80ddf3Saliguori #ifdef DEBUG_EXT
847c80ab3fSJes Sorensen     printf("qcow2_read_extensions: start=%ld end=%ld\n", start_offset, end_offset);
859b80ddf3Saliguori #endif
869b80ddf3Saliguori     offset = start_offset;
879b80ddf3Saliguori     while (offset < end_offset) {
889b80ddf3Saliguori 
899b80ddf3Saliguori #ifdef DEBUG_EXT
906cbc3031SPhilipp Hahn         BDRVQcowState *s = bs->opaque;
919b80ddf3Saliguori         /* Sanity check */
929b80ddf3Saliguori         if (offset > s->cluster_size)
937c80ab3fSJes Sorensen             printf("qcow2_read_extension: suspicious offset %lu\n", offset);
949b80ddf3Saliguori 
959b80ddf3Saliguori         printf("attemting to read extended header in offset %lu\n", offset);
969b80ddf3Saliguori #endif
979b80ddf3Saliguori 
9866f82ceeSKevin Wolf         if (bdrv_pread(bs->file, offset, &ext, sizeof(ext)) != sizeof(ext)) {
997c80ab3fSJes Sorensen             fprintf(stderr, "qcow2_read_extension: ERROR: "
1000bfcd599SBlue Swirl                     "pread fail from offset %" PRIu64 "\n",
1010bfcd599SBlue Swirl                     offset);
1029b80ddf3Saliguori             return 1;
1039b80ddf3Saliguori         }
1049b80ddf3Saliguori         be32_to_cpus(&ext.magic);
1059b80ddf3Saliguori         be32_to_cpus(&ext.len);
1069b80ddf3Saliguori         offset += sizeof(ext);
1079b80ddf3Saliguori #ifdef DEBUG_EXT
1089b80ddf3Saliguori         printf("ext.magic = 0x%x\n", ext.magic);
1099b80ddf3Saliguori #endif
1109b80ddf3Saliguori         switch (ext.magic) {
1117c80ab3fSJes Sorensen         case QCOW2_EXT_MAGIC_END:
1129b80ddf3Saliguori             return 0;
113f965509cSaliguori 
1147c80ab3fSJes Sorensen         case QCOW2_EXT_MAGIC_BACKING_FORMAT:
115f965509cSaliguori             if (ext.len >= sizeof(bs->backing_format)) {
116f965509cSaliguori                 fprintf(stderr, "ERROR: ext_backing_format: len=%u too large"
1174c978075Saliguori                         " (>=%zu)\n",
118f965509cSaliguori                         ext.len, sizeof(bs->backing_format));
119f965509cSaliguori                 return 2;
120f965509cSaliguori             }
12166f82ceeSKevin Wolf             if (bdrv_pread(bs->file, offset , bs->backing_format,
122f965509cSaliguori                            ext.len) != ext.len)
123f965509cSaliguori                 return 3;
124f965509cSaliguori             bs->backing_format[ext.len] = '\0';
125f965509cSaliguori #ifdef DEBUG_EXT
126f965509cSaliguori             printf("Qcow2: Got format extension %s\n", bs->backing_format);
127f965509cSaliguori #endif
128e1c7f0e3SKevin Wolf             offset = ((offset + ext.len + 7) & ~7);
129f965509cSaliguori             break;
130f965509cSaliguori 
1319b80ddf3Saliguori         default:
1329b80ddf3Saliguori             /* unknown magic -- just skip it */
133e1c7f0e3SKevin Wolf             offset = ((offset + ext.len + 7) & ~7);
1349b80ddf3Saliguori             break;
1359b80ddf3Saliguori         }
1369b80ddf3Saliguori     }
1379b80ddf3Saliguori 
1389b80ddf3Saliguori     return 0;
1399b80ddf3Saliguori }
1409b80ddf3Saliguori 
1419b80ddf3Saliguori 
1427c80ab3fSJes Sorensen static int qcow2_open(BlockDriverState *bs, int flags)
143585f8587Sbellard {
144585f8587Sbellard     BDRVQcowState *s = bs->opaque;
1456d85a57eSJes Sorensen     int len, i, ret = 0;
146585f8587Sbellard     QCowHeader header;
1479b80ddf3Saliguori     uint64_t ext_end;
14829c1a730SKevin Wolf     bool writethrough;
149585f8587Sbellard 
1506d85a57eSJes Sorensen     ret = bdrv_pread(bs->file, 0, &header, sizeof(header));
1516d85a57eSJes Sorensen     if (ret < 0) {
152585f8587Sbellard         goto fail;
1536d85a57eSJes Sorensen     }
154585f8587Sbellard     be32_to_cpus(&header.magic);
155585f8587Sbellard     be32_to_cpus(&header.version);
156585f8587Sbellard     be64_to_cpus(&header.backing_file_offset);
157585f8587Sbellard     be32_to_cpus(&header.backing_file_size);
158585f8587Sbellard     be64_to_cpus(&header.size);
159585f8587Sbellard     be32_to_cpus(&header.cluster_bits);
160585f8587Sbellard     be32_to_cpus(&header.crypt_method);
161585f8587Sbellard     be64_to_cpus(&header.l1_table_offset);
162585f8587Sbellard     be32_to_cpus(&header.l1_size);
163585f8587Sbellard     be64_to_cpus(&header.refcount_table_offset);
164585f8587Sbellard     be32_to_cpus(&header.refcount_table_clusters);
165585f8587Sbellard     be64_to_cpus(&header.snapshots_offset);
166585f8587Sbellard     be32_to_cpus(&header.nb_snapshots);
167585f8587Sbellard 
168e8cdcec1SKevin Wolf     if (header.magic != QCOW_MAGIC) {
1696d85a57eSJes Sorensen         ret = -EINVAL;
170585f8587Sbellard         goto fail;
1716d85a57eSJes Sorensen     }
172e8cdcec1SKevin Wolf     if (header.version != QCOW_VERSION) {
173e8cdcec1SKevin Wolf         char version[64];
174e8cdcec1SKevin Wolf         snprintf(version, sizeof(version), "QCOW version %d", header.version);
175e8cdcec1SKevin Wolf         qerror_report(QERR_UNKNOWN_BLOCK_FORMAT_FEATURE,
176e8cdcec1SKevin Wolf             bs->device_name, "qcow2", version);
177e8cdcec1SKevin Wolf         ret = -ENOTSUP;
178e8cdcec1SKevin Wolf         goto fail;
179e8cdcec1SKevin Wolf     }
180d191d12dSStefan Weil     if (header.cluster_bits < MIN_CLUSTER_BITS ||
1816d85a57eSJes Sorensen         header.cluster_bits > MAX_CLUSTER_BITS) {
1826d85a57eSJes Sorensen         ret = -EINVAL;
183585f8587Sbellard         goto fail;
1846d85a57eSJes Sorensen     }
1856d85a57eSJes Sorensen     if (header.crypt_method > QCOW_CRYPT_AES) {
1866d85a57eSJes Sorensen         ret = -EINVAL;
187585f8587Sbellard         goto fail;
1886d85a57eSJes Sorensen     }
189585f8587Sbellard     s->crypt_method_header = header.crypt_method;
1906d85a57eSJes Sorensen     if (s->crypt_method_header) {
191585f8587Sbellard         bs->encrypted = 1;
1926d85a57eSJes Sorensen     }
193585f8587Sbellard     s->cluster_bits = header.cluster_bits;
194585f8587Sbellard     s->cluster_size = 1 << s->cluster_bits;
195585f8587Sbellard     s->cluster_sectors = 1 << (s->cluster_bits - 9);
196585f8587Sbellard     s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */
197585f8587Sbellard     s->l2_size = 1 << s->l2_bits;
198585f8587Sbellard     bs->total_sectors = header.size / 512;
199585f8587Sbellard     s->csize_shift = (62 - (s->cluster_bits - 8));
200585f8587Sbellard     s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;
201585f8587Sbellard     s->cluster_offset_mask = (1LL << s->csize_shift) - 1;
202585f8587Sbellard     s->refcount_table_offset = header.refcount_table_offset;
203585f8587Sbellard     s->refcount_table_size =
204585f8587Sbellard         header.refcount_table_clusters << (s->cluster_bits - 3);
205585f8587Sbellard 
206585f8587Sbellard     s->snapshots_offset = header.snapshots_offset;
207585f8587Sbellard     s->nb_snapshots = header.nb_snapshots;
208585f8587Sbellard 
209585f8587Sbellard     /* read the level 1 table */
210585f8587Sbellard     s->l1_size = header.l1_size;
211419b19d9SStefan Hajnoczi     s->l1_vm_state_index = size_to_l1(s, header.size);
212585f8587Sbellard     /* the L1 table must contain at least enough entries to put
213585f8587Sbellard        header.size bytes */
2146d85a57eSJes Sorensen     if (s->l1_size < s->l1_vm_state_index) {
2156d85a57eSJes Sorensen         ret = -EINVAL;
216585f8587Sbellard         goto fail;
2176d85a57eSJes Sorensen     }
218585f8587Sbellard     s->l1_table_offset = header.l1_table_offset;
219d191d12dSStefan Weil     if (s->l1_size > 0) {
2207267c094SAnthony Liguori         s->l1_table = g_malloc0(
2213f6a3ee5SKevin Wolf             align_offset(s->l1_size * sizeof(uint64_t), 512));
2226d85a57eSJes Sorensen         ret = bdrv_pread(bs->file, s->l1_table_offset, s->l1_table,
2236d85a57eSJes Sorensen                          s->l1_size * sizeof(uint64_t));
2246d85a57eSJes Sorensen         if (ret < 0) {
225585f8587Sbellard             goto fail;
2266d85a57eSJes Sorensen         }
227585f8587Sbellard         for(i = 0;i < s->l1_size; i++) {
228585f8587Sbellard             be64_to_cpus(&s->l1_table[i]);
229585f8587Sbellard         }
230d191d12dSStefan Weil     }
23129c1a730SKevin Wolf 
23229c1a730SKevin Wolf     /* alloc L2 table/refcount block cache */
233a6599793SChristoph Hellwig     writethrough = ((flags & BDRV_O_CACHE_WB) == 0);
23429c1a730SKevin Wolf     s->l2_table_cache = qcow2_cache_create(bs, L2_CACHE_SIZE, writethrough);
23529c1a730SKevin Wolf     s->refcount_block_cache = qcow2_cache_create(bs, REFCOUNT_CACHE_SIZE,
23629c1a730SKevin Wolf         writethrough);
23729c1a730SKevin Wolf 
2387267c094SAnthony Liguori     s->cluster_cache = g_malloc(s->cluster_size);
239585f8587Sbellard     /* one more sector for decompressed data alignment */
2407267c094SAnthony Liguori     s->cluster_data = g_malloc(QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size
241095a9c58Saliguori                                   + 512);
242585f8587Sbellard     s->cluster_cache_offset = -1;
243585f8587Sbellard 
2446d85a57eSJes Sorensen     ret = qcow2_refcount_init(bs);
2456d85a57eSJes Sorensen     if (ret != 0) {
246585f8587Sbellard         goto fail;
2476d85a57eSJes Sorensen     }
248585f8587Sbellard 
24972cf2d4fSBlue Swirl     QLIST_INIT(&s->cluster_allocs);
250f214978aSKevin Wolf 
2519b80ddf3Saliguori     /* read qcow2 extensions */
2526d85a57eSJes Sorensen     if (header.backing_file_offset) {
2539b80ddf3Saliguori         ext_end = header.backing_file_offset;
2546d85a57eSJes Sorensen     } else {
2559b80ddf3Saliguori         ext_end = s->cluster_size;
2566d85a57eSJes Sorensen     }
2576d85a57eSJes Sorensen     if (qcow2_read_extensions(bs, sizeof(header), ext_end)) {
2586d85a57eSJes Sorensen         ret = -EINVAL;
2599b80ddf3Saliguori         goto fail;
2606d85a57eSJes Sorensen     }
2619b80ddf3Saliguori 
262585f8587Sbellard     /* read the backing file name */
263585f8587Sbellard     if (header.backing_file_offset != 0) {
264585f8587Sbellard         len = header.backing_file_size;
2656d85a57eSJes Sorensen         if (len > 1023) {
266585f8587Sbellard             len = 1023;
2676d85a57eSJes Sorensen         }
2686d85a57eSJes Sorensen         ret = bdrv_pread(bs->file, header.backing_file_offset,
2696d85a57eSJes Sorensen                          bs->backing_file, len);
2706d85a57eSJes Sorensen         if (ret < 0) {
271585f8587Sbellard             goto fail;
2726d85a57eSJes Sorensen         }
273585f8587Sbellard         bs->backing_file[len] = '\0';
274585f8587Sbellard     }
2756d85a57eSJes Sorensen     if (qcow2_read_snapshots(bs) < 0) {
2766d85a57eSJes Sorensen         ret = -EINVAL;
277585f8587Sbellard         goto fail;
2786d85a57eSJes Sorensen     }
279585f8587Sbellard 
28068d100e9SKevin Wolf     /* Initialise locks */
28168d100e9SKevin Wolf     qemu_co_mutex_init(&s->lock);
28268d100e9SKevin Wolf 
283585f8587Sbellard #ifdef DEBUG_ALLOC
2846cbc3031SPhilipp Hahn     {
2856cbc3031SPhilipp Hahn         BdrvCheckResult result = {0};
2866cbc3031SPhilipp Hahn         qcow2_check_refcounts(bs, &result);
2876cbc3031SPhilipp Hahn     }
288585f8587Sbellard #endif
2896d85a57eSJes Sorensen     return ret;
290585f8587Sbellard 
291585f8587Sbellard  fail:
292ed6ccf0fSKevin Wolf     qcow2_free_snapshots(bs);
293ed6ccf0fSKevin Wolf     qcow2_refcount_close(bs);
2947267c094SAnthony Liguori     g_free(s->l1_table);
29529c1a730SKevin Wolf     if (s->l2_table_cache) {
29629c1a730SKevin Wolf         qcow2_cache_destroy(bs, s->l2_table_cache);
29729c1a730SKevin Wolf     }
2987267c094SAnthony Liguori     g_free(s->cluster_cache);
2997267c094SAnthony Liguori     g_free(s->cluster_data);
3006d85a57eSJes Sorensen     return ret;
301585f8587Sbellard }
302585f8587Sbellard 
3037c80ab3fSJes Sorensen static int qcow2_set_key(BlockDriverState *bs, const char *key)
304585f8587Sbellard {
305585f8587Sbellard     BDRVQcowState *s = bs->opaque;
306585f8587Sbellard     uint8_t keybuf[16];
307585f8587Sbellard     int len, i;
308585f8587Sbellard 
309585f8587Sbellard     memset(keybuf, 0, 16);
310585f8587Sbellard     len = strlen(key);
311585f8587Sbellard     if (len > 16)
312585f8587Sbellard         len = 16;
313585f8587Sbellard     /* XXX: we could compress the chars to 7 bits to increase
314585f8587Sbellard        entropy */
315585f8587Sbellard     for(i = 0;i < len;i++) {
316585f8587Sbellard         keybuf[i] = key[i];
317585f8587Sbellard     }
318585f8587Sbellard     s->crypt_method = s->crypt_method_header;
319585f8587Sbellard 
320585f8587Sbellard     if (AES_set_encrypt_key(keybuf, 128, &s->aes_encrypt_key) != 0)
321585f8587Sbellard         return -1;
322585f8587Sbellard     if (AES_set_decrypt_key(keybuf, 128, &s->aes_decrypt_key) != 0)
323585f8587Sbellard         return -1;
324585f8587Sbellard #if 0
325585f8587Sbellard     /* test */
326585f8587Sbellard     {
327585f8587Sbellard         uint8_t in[16];
328585f8587Sbellard         uint8_t out[16];
329585f8587Sbellard         uint8_t tmp[16];
330585f8587Sbellard         for(i=0;i<16;i++)
331585f8587Sbellard             in[i] = i;
332585f8587Sbellard         AES_encrypt(in, tmp, &s->aes_encrypt_key);
333585f8587Sbellard         AES_decrypt(tmp, out, &s->aes_decrypt_key);
334585f8587Sbellard         for(i = 0; i < 16; i++)
335585f8587Sbellard             printf(" %02x", tmp[i]);
336585f8587Sbellard         printf("\n");
337585f8587Sbellard         for(i = 0; i < 16; i++)
338585f8587Sbellard             printf(" %02x", out[i]);
339585f8587Sbellard         printf("\n");
340585f8587Sbellard     }
341585f8587Sbellard #endif
342585f8587Sbellard     return 0;
343585f8587Sbellard }
344585f8587Sbellard 
3457c80ab3fSJes Sorensen static int qcow2_is_allocated(BlockDriverState *bs, int64_t sector_num,
346585f8587Sbellard                               int nb_sectors, int *pnum)
347585f8587Sbellard {
348585f8587Sbellard     uint64_t cluster_offset;
3491c46efaaSKevin Wolf     int ret;
350585f8587Sbellard 
351095a9c58Saliguori     *pnum = nb_sectors;
3521c46efaaSKevin Wolf     /* FIXME We can get errors here, but the bdrv_is_allocated interface can't
3531c46efaaSKevin Wolf      * pass them on today */
3541c46efaaSKevin Wolf     ret = qcow2_get_cluster_offset(bs, sector_num << 9, pnum, &cluster_offset);
3551c46efaaSKevin Wolf     if (ret < 0) {
3561c46efaaSKevin Wolf         *pnum = 0;
3571c46efaaSKevin Wolf     }
358095a9c58Saliguori 
359585f8587Sbellard     return (cluster_offset != 0);
360585f8587Sbellard }
361585f8587Sbellard 
362a9465922Sbellard /* handle reading after the end of the backing file */
363bd28f835SKevin Wolf int qcow2_backing_read1(BlockDriverState *bs, QEMUIOVector *qiov,
364bd28f835SKevin Wolf                   int64_t sector_num, int nb_sectors)
365a9465922Sbellard {
366a9465922Sbellard     int n1;
367a9465922Sbellard     if ((sector_num + nb_sectors) <= bs->total_sectors)
368a9465922Sbellard         return nb_sectors;
369a9465922Sbellard     if (sector_num >= bs->total_sectors)
370a9465922Sbellard         n1 = 0;
371a9465922Sbellard     else
372a9465922Sbellard         n1 = bs->total_sectors - sector_num;
373bd28f835SKevin Wolf 
374e0d9c6f9SChunqiang Tang     qemu_iovec_memset_skip(qiov, 0, 512 * (nb_sectors - n1), 512 * n1);
375bd28f835SKevin Wolf 
376a9465922Sbellard     return n1;
377a9465922Sbellard }
378a9465922Sbellard 
379*3fc48d09SFrediano Ziglio static int qcow2_co_readv(BlockDriverState *bs, int64_t sector_num,
380*3fc48d09SFrediano Ziglio                           int remaining_sectors, QEMUIOVector *qiov)
3811490791fSaliguori {
382585f8587Sbellard     BDRVQcowState *s = bs->opaque;
383a9465922Sbellard     int index_in_cluster, n1;
38468d100e9SKevin Wolf     int ret;
385faf575c1SFrediano Ziglio     int cur_nr_sectors; /* number of sectors in current iteration */
386c2bdd990SFrediano Ziglio     uint64_t cluster_offset = 0;
387*3fc48d09SFrediano Ziglio     uint64_t bytes_done = 0;
388*3fc48d09SFrediano Ziglio     QEMUIOVector hd_qiov;
389*3fc48d09SFrediano Ziglio     uint8_t *cluster_data = NULL;
390585f8587Sbellard 
391*3fc48d09SFrediano Ziglio     qemu_iovec_init(&hd_qiov, qiov->niov);
392*3fc48d09SFrediano Ziglio 
393*3fc48d09SFrediano Ziglio     qemu_co_mutex_lock(&s->lock);
394*3fc48d09SFrediano Ziglio 
395*3fc48d09SFrediano Ziglio     while (remaining_sectors != 0) {
396585f8587Sbellard 
397faf575c1SFrediano Ziglio         /* prepare next request */
398*3fc48d09SFrediano Ziglio         cur_nr_sectors = remaining_sectors;
399bd28f835SKevin Wolf         if (s->crypt_method) {
400faf575c1SFrediano Ziglio             cur_nr_sectors = MIN(cur_nr_sectors,
401bd28f835SKevin Wolf                 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors);
402bd28f835SKevin Wolf         }
403bd28f835SKevin Wolf 
404*3fc48d09SFrediano Ziglio         ret = qcow2_get_cluster_offset(bs, sector_num << 9,
405c2bdd990SFrediano Ziglio             &cur_nr_sectors, &cluster_offset);
4061c46efaaSKevin Wolf         if (ret < 0) {
407*3fc48d09SFrediano Ziglio             goto fail;
4081c46efaaSKevin Wolf         }
4091c46efaaSKevin Wolf 
410*3fc48d09SFrediano Ziglio         index_in_cluster = sector_num & (s->cluster_sectors - 1);
411585f8587Sbellard 
412*3fc48d09SFrediano Ziglio         qemu_iovec_reset(&hd_qiov);
413*3fc48d09SFrediano Ziglio         qemu_iovec_copy(&hd_qiov, qiov, bytes_done,
414faf575c1SFrediano Ziglio             cur_nr_sectors * 512);
415bd28f835SKevin Wolf 
416c2bdd990SFrediano Ziglio         if (!cluster_offset) {
417bd28f835SKevin Wolf 
418585f8587Sbellard             if (bs->backing_hd) {
419585f8587Sbellard                 /* read from the base image */
420*3fc48d09SFrediano Ziglio                 n1 = qcow2_backing_read1(bs->backing_hd, &hd_qiov,
421*3fc48d09SFrediano Ziglio                     sector_num, cur_nr_sectors);
422a9465922Sbellard                 if (n1 > 0) {
42366f82ceeSKevin Wolf                     BLKDBG_EVENT(bs->file, BLKDBG_READ_BACKING_AIO);
42468d100e9SKevin Wolf                     qemu_co_mutex_unlock(&s->lock);
425*3fc48d09SFrediano Ziglio                     ret = bdrv_co_readv(bs->backing_hd, sector_num,
426*3fc48d09SFrediano Ziglio                                         n1, &hd_qiov);
42768d100e9SKevin Wolf                     qemu_co_mutex_lock(&s->lock);
42868d100e9SKevin Wolf                     if (ret < 0) {
429*3fc48d09SFrediano Ziglio                         goto fail;
4303ab4c7e9SKevin Wolf                     }
4311490791fSaliguori                 }
432a9465922Sbellard             } else {
433585f8587Sbellard                 /* Note: in this case, no need to wait */
434*3fc48d09SFrediano Ziglio                 qemu_iovec_memset(&hd_qiov, 0, 512 * cur_nr_sectors);
4351490791fSaliguori             }
436c2bdd990SFrediano Ziglio         } else if (cluster_offset & QCOW_OFLAG_COMPRESSED) {
437585f8587Sbellard             /* add AIO support for compressed blocks ? */
438c2bdd990SFrediano Ziglio             ret = qcow2_decompress_cluster(bs, cluster_offset);
4398af36488SKevin Wolf             if (ret < 0) {
440*3fc48d09SFrediano Ziglio                 goto fail;
4418af36488SKevin Wolf             }
442bd28f835SKevin Wolf 
443*3fc48d09SFrediano Ziglio             qemu_iovec_from_buffer(&hd_qiov,
444bd28f835SKevin Wolf                 s->cluster_cache + index_in_cluster * 512,
445faf575c1SFrediano Ziglio                 512 * cur_nr_sectors);
446585f8587Sbellard         } else {
447c2bdd990SFrediano Ziglio             if ((cluster_offset & 511) != 0) {
448*3fc48d09SFrediano Ziglio                 ret = -EIO;
449*3fc48d09SFrediano Ziglio                 goto fail;
450585f8587Sbellard             }
451c87c0672Saliguori 
452bd28f835SKevin Wolf             if (s->crypt_method) {
453bd28f835SKevin Wolf                 /*
454bd28f835SKevin Wolf                  * For encrypted images, read everything into a temporary
455bd28f835SKevin Wolf                  * contiguous buffer on which the AES functions can work.
456bd28f835SKevin Wolf                  */
457*3fc48d09SFrediano Ziglio                 if (!cluster_data) {
458*3fc48d09SFrediano Ziglio                     cluster_data =
4597267c094SAnthony Liguori                         g_malloc0(QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
460bd28f835SKevin Wolf                 }
461bd28f835SKevin Wolf 
462faf575c1SFrediano Ziglio                 assert(cur_nr_sectors <=
463bd28f835SKevin Wolf                     QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors);
464*3fc48d09SFrediano Ziglio                 qemu_iovec_reset(&hd_qiov);
465*3fc48d09SFrediano Ziglio                 qemu_iovec_add(&hd_qiov, cluster_data,
466faf575c1SFrediano Ziglio                     512 * cur_nr_sectors);
467bd28f835SKevin Wolf             }
468bd28f835SKevin Wolf 
46966f82ceeSKevin Wolf             BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);
47068d100e9SKevin Wolf             qemu_co_mutex_unlock(&s->lock);
47168d100e9SKevin Wolf             ret = bdrv_co_readv(bs->file,
472c2bdd990SFrediano Ziglio                                 (cluster_offset >> 9) + index_in_cluster,
473*3fc48d09SFrediano Ziglio                                 cur_nr_sectors, &hd_qiov);
47468d100e9SKevin Wolf             qemu_co_mutex_lock(&s->lock);
47568d100e9SKevin Wolf             if (ret < 0) {
476*3fc48d09SFrediano Ziglio                 goto fail;
477585f8587Sbellard             }
478faf575c1SFrediano Ziglio             if (s->crypt_method) {
479*3fc48d09SFrediano Ziglio                 qcow2_encrypt_sectors(s, sector_num,  cluster_data,
480*3fc48d09SFrediano Ziglio                     cluster_data, cur_nr_sectors, 0, &s->aes_decrypt_key);
481*3fc48d09SFrediano Ziglio                 qemu_iovec_reset(&hd_qiov);
482*3fc48d09SFrediano Ziglio                 qemu_iovec_copy(&hd_qiov, qiov, bytes_done,
483faf575c1SFrediano Ziglio                     cur_nr_sectors * 512);
484*3fc48d09SFrediano Ziglio                 qemu_iovec_from_buffer(&hd_qiov, cluster_data,
485faf575c1SFrediano Ziglio                     512 * cur_nr_sectors);
486171e3d6bSKevin Wolf             }
487faf575c1SFrediano Ziglio         }
488faf575c1SFrediano Ziglio 
489*3fc48d09SFrediano Ziglio         remaining_sectors -= cur_nr_sectors;
490*3fc48d09SFrediano Ziglio         sector_num += cur_nr_sectors;
491*3fc48d09SFrediano Ziglio         bytes_done += cur_nr_sectors * 512;
4925ebaa27eSFrediano Ziglio     }
493*3fc48d09SFrediano Ziglio     ret = 0;
494f141eafeSaliguori 
495*3fc48d09SFrediano Ziglio fail:
49668d100e9SKevin Wolf     qemu_co_mutex_unlock(&s->lock);
49768d100e9SKevin Wolf 
498*3fc48d09SFrediano Ziglio     qemu_iovec_destroy(&hd_qiov);
49968d100e9SKevin Wolf 
50068d100e9SKevin Wolf     return ret;
501585f8587Sbellard }
502585f8587Sbellard 
50368d100e9SKevin Wolf static void run_dependent_requests(BDRVQcowState *s, QCowL2Meta *m)
504f214978aSKevin Wolf {
505f214978aSKevin Wolf     /* Take the request off the list of running requests */
506f214978aSKevin Wolf     if (m->nb_clusters != 0) {
50772cf2d4fSBlue Swirl         QLIST_REMOVE(m, next_in_flight);
508f214978aSKevin Wolf     }
509f214978aSKevin Wolf 
510d4c146f0SStefan Hajnoczi     /* Restart all dependent requests */
51168d100e9SKevin Wolf     if (!qemu_co_queue_empty(&m->dependent_requests)) {
51268d100e9SKevin Wolf         qemu_co_mutex_unlock(&s->lock);
51368d100e9SKevin Wolf         while(qemu_co_queue_next(&m->dependent_requests));
51468d100e9SKevin Wolf         qemu_co_mutex_lock(&s->lock);
51568d100e9SKevin Wolf     }
516f214978aSKevin Wolf }
517f214978aSKevin Wolf 
518*3fc48d09SFrediano Ziglio static int qcow2_co_writev(BlockDriverState *bs,
519*3fc48d09SFrediano Ziglio                            int64_t sector_num,
520*3fc48d09SFrediano Ziglio                            int remaining_sectors,
521*3fc48d09SFrediano Ziglio                            QEMUIOVector *qiov)
522585f8587Sbellard {
523585f8587Sbellard     BDRVQcowState *s = bs->opaque;
524585f8587Sbellard     int index_in_cluster;
525095a9c58Saliguori     int n_end;
52668d100e9SKevin Wolf     int ret;
527faf575c1SFrediano Ziglio     int cur_nr_sectors; /* number of sectors in current iteration */
528c2271403SFrediano Ziglio     QCowL2Meta l2meta;
529c2bdd990SFrediano Ziglio     uint64_t cluster_offset;
530*3fc48d09SFrediano Ziglio     QEMUIOVector hd_qiov;
531*3fc48d09SFrediano Ziglio     uint64_t bytes_done = 0;
532*3fc48d09SFrediano Ziglio     uint8_t *cluster_data = NULL;
533c2271403SFrediano Ziglio 
534c2271403SFrediano Ziglio     l2meta.nb_clusters = 0;
535c2271403SFrediano Ziglio     qemu_co_queue_init(&l2meta.dependent_requests);
536585f8587Sbellard 
537*3fc48d09SFrediano Ziglio     qemu_iovec_init(&hd_qiov, qiov->niov);
538585f8587Sbellard 
539*3fc48d09SFrediano Ziglio     s->cluster_cache_offset = -1; /* disable compressed cache */
540*3fc48d09SFrediano Ziglio 
541*3fc48d09SFrediano Ziglio     qemu_co_mutex_lock(&s->lock);
542*3fc48d09SFrediano Ziglio 
543*3fc48d09SFrediano Ziglio     while (remaining_sectors != 0) {
544*3fc48d09SFrediano Ziglio 
545*3fc48d09SFrediano Ziglio         index_in_cluster = sector_num & (s->cluster_sectors - 1);
546*3fc48d09SFrediano Ziglio         n_end = index_in_cluster + remaining_sectors;
547095a9c58Saliguori         if (s->crypt_method &&
5485ebaa27eSFrediano Ziglio             n_end > QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors) {
549095a9c58Saliguori             n_end = QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors;
5505ebaa27eSFrediano Ziglio         }
551095a9c58Saliguori 
552*3fc48d09SFrediano Ziglio         ret = qcow2_alloc_cluster_offset(bs, sector_num << 9,
553c2271403SFrediano Ziglio             index_in_cluster, n_end, &cur_nr_sectors, &l2meta);
554148da7eaSKevin Wolf         if (ret < 0) {
555*3fc48d09SFrediano Ziglio             goto fail;
556148da7eaSKevin Wolf         }
557148da7eaSKevin Wolf 
558c2bdd990SFrediano Ziglio         cluster_offset = l2meta.cluster_offset;
559c2bdd990SFrediano Ziglio         assert((cluster_offset & 511) == 0);
560148da7eaSKevin Wolf 
561*3fc48d09SFrediano Ziglio         qemu_iovec_reset(&hd_qiov);
562*3fc48d09SFrediano Ziglio         qemu_iovec_copy(&hd_qiov, qiov, bytes_done,
563faf575c1SFrediano Ziglio             cur_nr_sectors * 512);
5646f5f060bSKevin Wolf 
565585f8587Sbellard         if (s->crypt_method) {
566*3fc48d09SFrediano Ziglio             if (!cluster_data) {
567*3fc48d09SFrediano Ziglio                 cluster_data = g_malloc0(QCOW_MAX_CRYPT_CLUSTERS *
568095a9c58Saliguori                                                  s->cluster_size);
569585f8587Sbellard             }
5706f5f060bSKevin Wolf 
571*3fc48d09SFrediano Ziglio             assert(hd_qiov.size <=
5725ebaa27eSFrediano Ziglio                    QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
573*3fc48d09SFrediano Ziglio             qemu_iovec_to_buffer(&hd_qiov, cluster_data);
5746f5f060bSKevin Wolf 
575*3fc48d09SFrediano Ziglio             qcow2_encrypt_sectors(s, sector_num, cluster_data,
576*3fc48d09SFrediano Ziglio                 cluster_data, cur_nr_sectors, 1, &s->aes_encrypt_key);
5776f5f060bSKevin Wolf 
578*3fc48d09SFrediano Ziglio             qemu_iovec_reset(&hd_qiov);
579*3fc48d09SFrediano Ziglio             qemu_iovec_add(&hd_qiov, cluster_data,
580faf575c1SFrediano Ziglio                 cur_nr_sectors * 512);
581585f8587Sbellard         }
5826f5f060bSKevin Wolf 
58366f82ceeSKevin Wolf         BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO);
58468d100e9SKevin Wolf         qemu_co_mutex_unlock(&s->lock);
58568d100e9SKevin Wolf         ret = bdrv_co_writev(bs->file,
586c2bdd990SFrediano Ziglio                              (cluster_offset >> 9) + index_in_cluster,
587*3fc48d09SFrediano Ziglio                              cur_nr_sectors, &hd_qiov);
58868d100e9SKevin Wolf         qemu_co_mutex_lock(&s->lock);
58968d100e9SKevin Wolf         if (ret < 0) {
590*3fc48d09SFrediano Ziglio             goto fail;
591171e3d6bSKevin Wolf         }
592f141eafeSaliguori 
593c2271403SFrediano Ziglio         ret = qcow2_alloc_cluster_link_l2(bs, &l2meta);
594faf575c1SFrediano Ziglio 
595c2271403SFrediano Ziglio         run_dependent_requests(s, &l2meta);
596faf575c1SFrediano Ziglio 
597faf575c1SFrediano Ziglio         if (ret < 0) {
598*3fc48d09SFrediano Ziglio             goto fail;
599faf575c1SFrediano Ziglio         }
600faf575c1SFrediano Ziglio 
601*3fc48d09SFrediano Ziglio         remaining_sectors -= cur_nr_sectors;
602*3fc48d09SFrediano Ziglio         sector_num += cur_nr_sectors;
603*3fc48d09SFrediano Ziglio         bytes_done += cur_nr_sectors * 512;
6045ebaa27eSFrediano Ziglio     }
605*3fc48d09SFrediano Ziglio     ret = 0;
606faf575c1SFrediano Ziglio 
607*3fc48d09SFrediano Ziglio fail:
60868d100e9SKevin Wolf     qemu_co_mutex_unlock(&s->lock);
609585f8587Sbellard 
610*3fc48d09SFrediano Ziglio     qemu_iovec_destroy(&hd_qiov);
61142496d62SKevin Wolf 
61268d100e9SKevin Wolf     return ret;
613585f8587Sbellard }
614585f8587Sbellard 
6157c80ab3fSJes Sorensen static void qcow2_close(BlockDriverState *bs)
616585f8587Sbellard {
617585f8587Sbellard     BDRVQcowState *s = bs->opaque;
6187267c094SAnthony Liguori     g_free(s->l1_table);
61929c1a730SKevin Wolf 
62029c1a730SKevin Wolf     qcow2_cache_flush(bs, s->l2_table_cache);
62129c1a730SKevin Wolf     qcow2_cache_flush(bs, s->refcount_block_cache);
62229c1a730SKevin Wolf 
62329c1a730SKevin Wolf     qcow2_cache_destroy(bs, s->l2_table_cache);
62429c1a730SKevin Wolf     qcow2_cache_destroy(bs, s->refcount_block_cache);
62529c1a730SKevin Wolf 
6267267c094SAnthony Liguori     g_free(s->cluster_cache);
6277267c094SAnthony Liguori     g_free(s->cluster_data);
628ed6ccf0fSKevin Wolf     qcow2_refcount_close(bs);
629585f8587Sbellard }
630585f8587Sbellard 
631756e6736SKevin Wolf /*
632756e6736SKevin Wolf  * Updates the variable length parts of the qcow2 header, i.e. the backing file
633756e6736SKevin Wolf  * name and all extensions. qcow2 was not designed to allow such changes, so if
634756e6736SKevin Wolf  * we run out of space (we can only use the first cluster) this function may
635756e6736SKevin Wolf  * fail.
636756e6736SKevin Wolf  *
637756e6736SKevin Wolf  * Returns 0 on success, -errno in error cases.
638756e6736SKevin Wolf  */
639756e6736SKevin Wolf static int qcow2_update_ext_header(BlockDriverState *bs,
640756e6736SKevin Wolf     const char *backing_file, const char *backing_fmt)
641756e6736SKevin Wolf {
642756e6736SKevin Wolf     size_t backing_file_len = 0;
643756e6736SKevin Wolf     size_t backing_fmt_len = 0;
644756e6736SKevin Wolf     BDRVQcowState *s = bs->opaque;
645756e6736SKevin Wolf     QCowExtension ext_backing_fmt = {0, 0};
646756e6736SKevin Wolf     int ret;
647756e6736SKevin Wolf 
648756e6736SKevin Wolf     /* Backing file format doesn't make sense without a backing file */
649756e6736SKevin Wolf     if (backing_fmt && !backing_file) {
650756e6736SKevin Wolf         return -EINVAL;
651756e6736SKevin Wolf     }
652756e6736SKevin Wolf 
653756e6736SKevin Wolf     /* Prepare the backing file format extension if needed */
654756e6736SKevin Wolf     if (backing_fmt) {
655756e6736SKevin Wolf         ext_backing_fmt.len = cpu_to_be32(strlen(backing_fmt));
6567c80ab3fSJes Sorensen         ext_backing_fmt.magic = cpu_to_be32(QCOW2_EXT_MAGIC_BACKING_FORMAT);
657756e6736SKevin Wolf         backing_fmt_len = ((sizeof(ext_backing_fmt)
658756e6736SKevin Wolf             + strlen(backing_fmt) + 7) & ~7);
659756e6736SKevin Wolf     }
660756e6736SKevin Wolf 
661756e6736SKevin Wolf     /* Check if we can fit the new header into the first cluster */
662756e6736SKevin Wolf     if (backing_file) {
663756e6736SKevin Wolf         backing_file_len = strlen(backing_file);
664756e6736SKevin Wolf     }
665756e6736SKevin Wolf 
666756e6736SKevin Wolf     size_t header_size = sizeof(QCowHeader) + backing_file_len
667756e6736SKevin Wolf         + backing_fmt_len;
668756e6736SKevin Wolf 
669756e6736SKevin Wolf     if (header_size > s->cluster_size) {
670756e6736SKevin Wolf         return -ENOSPC;
671756e6736SKevin Wolf     }
672756e6736SKevin Wolf 
673756e6736SKevin Wolf     /* Rewrite backing file name and qcow2 extensions */
674756e6736SKevin Wolf     size_t ext_size = header_size - sizeof(QCowHeader);
675756e6736SKevin Wolf     uint8_t buf[ext_size];
676756e6736SKevin Wolf     size_t offset = 0;
677756e6736SKevin Wolf     size_t backing_file_offset = 0;
678756e6736SKevin Wolf 
679756e6736SKevin Wolf     if (backing_file) {
680756e6736SKevin Wolf         if (backing_fmt) {
681756e6736SKevin Wolf             int padding = backing_fmt_len -
682756e6736SKevin Wolf                 (sizeof(ext_backing_fmt) + strlen(backing_fmt));
683756e6736SKevin Wolf 
684756e6736SKevin Wolf             memcpy(buf + offset, &ext_backing_fmt, sizeof(ext_backing_fmt));
685756e6736SKevin Wolf             offset += sizeof(ext_backing_fmt);
686756e6736SKevin Wolf 
687756e6736SKevin Wolf             memcpy(buf + offset, backing_fmt, strlen(backing_fmt));
688756e6736SKevin Wolf             offset += strlen(backing_fmt);
689756e6736SKevin Wolf 
690756e6736SKevin Wolf             memset(buf + offset, 0, padding);
691756e6736SKevin Wolf             offset += padding;
692756e6736SKevin Wolf         }
693756e6736SKevin Wolf 
694756e6736SKevin Wolf         memcpy(buf + offset, backing_file, backing_file_len);
695756e6736SKevin Wolf         backing_file_offset = sizeof(QCowHeader) + offset;
696756e6736SKevin Wolf     }
697756e6736SKevin Wolf 
6988b3b7206SKevin Wolf     ret = bdrv_pwrite_sync(bs->file, sizeof(QCowHeader), buf, ext_size);
699756e6736SKevin Wolf     if (ret < 0) {
700756e6736SKevin Wolf         goto fail;
701756e6736SKevin Wolf     }
702756e6736SKevin Wolf 
703756e6736SKevin Wolf     /* Update header fields */
704756e6736SKevin Wolf     uint64_t be_backing_file_offset = cpu_to_be64(backing_file_offset);
705756e6736SKevin Wolf     uint32_t be_backing_file_size = cpu_to_be32(backing_file_len);
706756e6736SKevin Wolf 
7078b3b7206SKevin Wolf     ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, backing_file_offset),
708756e6736SKevin Wolf         &be_backing_file_offset, sizeof(uint64_t));
709756e6736SKevin Wolf     if (ret < 0) {
710756e6736SKevin Wolf         goto fail;
711756e6736SKevin Wolf     }
712756e6736SKevin Wolf 
7138b3b7206SKevin Wolf     ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, backing_file_size),
714756e6736SKevin Wolf         &be_backing_file_size, sizeof(uint32_t));
715756e6736SKevin Wolf     if (ret < 0) {
716756e6736SKevin Wolf         goto fail;
717756e6736SKevin Wolf     }
718756e6736SKevin Wolf 
719756e6736SKevin Wolf     ret = 0;
720756e6736SKevin Wolf fail:
721756e6736SKevin Wolf     return ret;
722756e6736SKevin Wolf }
723756e6736SKevin Wolf 
724756e6736SKevin Wolf static int qcow2_change_backing_file(BlockDriverState *bs,
725756e6736SKevin Wolf     const char *backing_file, const char *backing_fmt)
726756e6736SKevin Wolf {
727756e6736SKevin Wolf     return qcow2_update_ext_header(bs, backing_file, backing_fmt);
728756e6736SKevin Wolf }
729756e6736SKevin Wolf 
730a35e1c17SKevin Wolf static int preallocate(BlockDriverState *bs)
731a35e1c17SKevin Wolf {
732a35e1c17SKevin Wolf     uint64_t nb_sectors;
733a35e1c17SKevin Wolf     uint64_t offset;
734a35e1c17SKevin Wolf     int num;
735148da7eaSKevin Wolf     int ret;
736a35e1c17SKevin Wolf     QCowL2Meta meta;
737a35e1c17SKevin Wolf 
738a35e1c17SKevin Wolf     nb_sectors = bdrv_getlength(bs) >> 9;
739a35e1c17SKevin Wolf     offset = 0;
74068d100e9SKevin Wolf     qemu_co_queue_init(&meta.dependent_requests);
741148da7eaSKevin Wolf     meta.cluster_offset = 0;
742a35e1c17SKevin Wolf 
743a35e1c17SKevin Wolf     while (nb_sectors) {
744a35e1c17SKevin Wolf         num = MIN(nb_sectors, INT_MAX >> 9);
745148da7eaSKevin Wolf         ret = qcow2_alloc_cluster_offset(bs, offset, 0, num, &num, &meta);
746148da7eaSKevin Wolf         if (ret < 0) {
74719dbcbf7SKevin Wolf             return ret;
748a35e1c17SKevin Wolf         }
749a35e1c17SKevin Wolf 
75019dbcbf7SKevin Wolf         ret = qcow2_alloc_cluster_link_l2(bs, &meta);
75119dbcbf7SKevin Wolf         if (ret < 0) {
752148da7eaSKevin Wolf             qcow2_free_any_clusters(bs, meta.cluster_offset, meta.nb_clusters);
75319dbcbf7SKevin Wolf             return ret;
754a35e1c17SKevin Wolf         }
755a35e1c17SKevin Wolf 
756f214978aSKevin Wolf         /* There are no dependent requests, but we need to remove our request
757f214978aSKevin Wolf          * from the list of in-flight requests */
75868d100e9SKevin Wolf         run_dependent_requests(bs->opaque, &meta);
759f214978aSKevin Wolf 
760a35e1c17SKevin Wolf         /* TODO Preallocate data if requested */
761a35e1c17SKevin Wolf 
762a35e1c17SKevin Wolf         nb_sectors -= num;
763a35e1c17SKevin Wolf         offset += num << 9;
764a35e1c17SKevin Wolf     }
765a35e1c17SKevin Wolf 
766a35e1c17SKevin Wolf     /*
767a35e1c17SKevin Wolf      * It is expected that the image file is large enough to actually contain
768a35e1c17SKevin Wolf      * all of the allocated clusters (otherwise we get failing reads after
769a35e1c17SKevin Wolf      * EOF). Extend the image to the last allocated sector.
770a35e1c17SKevin Wolf      */
771148da7eaSKevin Wolf     if (meta.cluster_offset != 0) {
772ea80b906SKevin Wolf         uint8_t buf[512];
773ea80b906SKevin Wolf         memset(buf, 0, 512);
77419dbcbf7SKevin Wolf         ret = bdrv_write(bs->file, (meta.cluster_offset >> 9) + num - 1, buf, 1);
77519dbcbf7SKevin Wolf         if (ret < 0) {
77619dbcbf7SKevin Wolf             return ret;
77719dbcbf7SKevin Wolf         }
778a35e1c17SKevin Wolf     }
779a35e1c17SKevin Wolf 
780a35e1c17SKevin Wolf     return 0;
781a35e1c17SKevin Wolf }
782a35e1c17SKevin Wolf 
7837c80ab3fSJes Sorensen static int qcow2_create2(const char *filename, int64_t total_size,
784a9420734SKevin Wolf                          const char *backing_file, const char *backing_format,
785a9420734SKevin Wolf                          int flags, size_t cluster_size, int prealloc,
786a9420734SKevin Wolf                          QEMUOptionParameter *options)
787a9420734SKevin Wolf {
788a9420734SKevin Wolf     /* Calulate cluster_bits */
789a9420734SKevin Wolf     int cluster_bits;
790a9420734SKevin Wolf     cluster_bits = ffs(cluster_size) - 1;
791a9420734SKevin Wolf     if (cluster_bits < MIN_CLUSTER_BITS || cluster_bits > MAX_CLUSTER_BITS ||
792a9420734SKevin Wolf         (1 << cluster_bits) != cluster_size)
793a9420734SKevin Wolf     {
794a9420734SKevin Wolf         error_report(
7956daf194dSMarkus Armbruster             "Cluster size must be a power of two between %d and %dk",
796a9420734SKevin Wolf             1 << MIN_CLUSTER_BITS, 1 << (MAX_CLUSTER_BITS - 10));
797a9420734SKevin Wolf         return -EINVAL;
798a9420734SKevin Wolf     }
799a9420734SKevin Wolf 
800a9420734SKevin Wolf     /*
801a9420734SKevin Wolf      * Open the image file and write a minimal qcow2 header.
802a9420734SKevin Wolf      *
803a9420734SKevin Wolf      * We keep things simple and start with a zero-sized image. We also
804a9420734SKevin Wolf      * do without refcount blocks or a L1 table for now. We'll fix the
805a9420734SKevin Wolf      * inconsistency later.
806a9420734SKevin Wolf      *
807a9420734SKevin Wolf      * We do need a refcount table because growing the refcount table means
808a9420734SKevin Wolf      * allocating two new refcount blocks - the seconds of which would be at
809a9420734SKevin Wolf      * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
810a9420734SKevin Wolf      * size for any qcow2 image.
811a9420734SKevin Wolf      */
812a9420734SKevin Wolf     BlockDriverState* bs;
813a9420734SKevin Wolf     QCowHeader header;
814a9420734SKevin Wolf     uint8_t* refcount_table;
815a9420734SKevin Wolf     int ret;
816a9420734SKevin Wolf 
817a9420734SKevin Wolf     ret = bdrv_create_file(filename, options);
818a9420734SKevin Wolf     if (ret < 0) {
819a9420734SKevin Wolf         return ret;
820a9420734SKevin Wolf     }
821a9420734SKevin Wolf 
822a9420734SKevin Wolf     ret = bdrv_file_open(&bs, filename, BDRV_O_RDWR);
823a9420734SKevin Wolf     if (ret < 0) {
824a9420734SKevin Wolf         return ret;
825a9420734SKevin Wolf     }
826a9420734SKevin Wolf 
827a9420734SKevin Wolf     /* Write the header */
828a9420734SKevin Wolf     memset(&header, 0, sizeof(header));
829a9420734SKevin Wolf     header.magic = cpu_to_be32(QCOW_MAGIC);
830a9420734SKevin Wolf     header.version = cpu_to_be32(QCOW_VERSION);
831a9420734SKevin Wolf     header.cluster_bits = cpu_to_be32(cluster_bits);
832a9420734SKevin Wolf     header.size = cpu_to_be64(0);
833a9420734SKevin Wolf     header.l1_table_offset = cpu_to_be64(0);
834a9420734SKevin Wolf     header.l1_size = cpu_to_be32(0);
835a9420734SKevin Wolf     header.refcount_table_offset = cpu_to_be64(cluster_size);
836a9420734SKevin Wolf     header.refcount_table_clusters = cpu_to_be32(1);
837a9420734SKevin Wolf 
838a9420734SKevin Wolf     if (flags & BLOCK_FLAG_ENCRYPT) {
839a9420734SKevin Wolf         header.crypt_method = cpu_to_be32(QCOW_CRYPT_AES);
840a9420734SKevin Wolf     } else {
841a9420734SKevin Wolf         header.crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
842a9420734SKevin Wolf     }
843a9420734SKevin Wolf 
844a9420734SKevin Wolf     ret = bdrv_pwrite(bs, 0, &header, sizeof(header));
845a9420734SKevin Wolf     if (ret < 0) {
846a9420734SKevin Wolf         goto out;
847a9420734SKevin Wolf     }
848a9420734SKevin Wolf 
849a9420734SKevin Wolf     /* Write an empty refcount table */
8507267c094SAnthony Liguori     refcount_table = g_malloc0(cluster_size);
851a9420734SKevin Wolf     ret = bdrv_pwrite(bs, cluster_size, refcount_table, cluster_size);
8527267c094SAnthony Liguori     g_free(refcount_table);
853a9420734SKevin Wolf 
854a9420734SKevin Wolf     if (ret < 0) {
855a9420734SKevin Wolf         goto out;
856a9420734SKevin Wolf     }
857a9420734SKevin Wolf 
858a9420734SKevin Wolf     bdrv_close(bs);
859a9420734SKevin Wolf 
860a9420734SKevin Wolf     /*
861a9420734SKevin Wolf      * And now open the image and make it consistent first (i.e. increase the
862a9420734SKevin Wolf      * refcount of the cluster that is occupied by the header and the refcount
863a9420734SKevin Wolf      * table)
864a9420734SKevin Wolf      */
865a9420734SKevin Wolf     BlockDriver* drv = bdrv_find_format("qcow2");
866a9420734SKevin Wolf     assert(drv != NULL);
867e1a7107fSKevin Wolf     ret = bdrv_open(bs, filename,
868e1a7107fSKevin Wolf         BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_NO_FLUSH, drv);
869a9420734SKevin Wolf     if (ret < 0) {
870a9420734SKevin Wolf         goto out;
871a9420734SKevin Wolf     }
872a9420734SKevin Wolf 
873a9420734SKevin Wolf     ret = qcow2_alloc_clusters(bs, 2 * cluster_size);
874a9420734SKevin Wolf     if (ret < 0) {
875a9420734SKevin Wolf         goto out;
876a9420734SKevin Wolf 
877a9420734SKevin Wolf     } else if (ret != 0) {
878a9420734SKevin Wolf         error_report("Huh, first cluster in empty image is already in use?");
879a9420734SKevin Wolf         abort();
880a9420734SKevin Wolf     }
881a9420734SKevin Wolf 
882a9420734SKevin Wolf     /* Okay, now that we have a valid image, let's give it the right size */
883a9420734SKevin Wolf     ret = bdrv_truncate(bs, total_size * BDRV_SECTOR_SIZE);
884a9420734SKevin Wolf     if (ret < 0) {
885a9420734SKevin Wolf         goto out;
886a9420734SKevin Wolf     }
887a9420734SKevin Wolf 
888a9420734SKevin Wolf     /* Want a backing file? There you go.*/
889a9420734SKevin Wolf     if (backing_file) {
890a9420734SKevin Wolf         ret = bdrv_change_backing_file(bs, backing_file, backing_format);
891a9420734SKevin Wolf         if (ret < 0) {
892a9420734SKevin Wolf             goto out;
893a9420734SKevin Wolf         }
894a9420734SKevin Wolf     }
895a9420734SKevin Wolf 
896a9420734SKevin Wolf     /* And if we're supposed to preallocate metadata, do that now */
897a9420734SKevin Wolf     if (prealloc) {
898a9420734SKevin Wolf         ret = preallocate(bs);
899a9420734SKevin Wolf         if (ret < 0) {
900a9420734SKevin Wolf             goto out;
901a9420734SKevin Wolf         }
902a9420734SKevin Wolf     }
903a9420734SKevin Wolf 
904a9420734SKevin Wolf     ret = 0;
905a9420734SKevin Wolf out:
906a9420734SKevin Wolf     bdrv_delete(bs);
907a9420734SKevin Wolf     return ret;
908a9420734SKevin Wolf }
909de5f3f40SKevin Wolf 
9107c80ab3fSJes Sorensen static int qcow2_create(const char *filename, QEMUOptionParameter *options)
911de5f3f40SKevin Wolf {
912de5f3f40SKevin Wolf     const char *backing_file = NULL;
913de5f3f40SKevin Wolf     const char *backing_fmt = NULL;
914de5f3f40SKevin Wolf     uint64_t sectors = 0;
915de5f3f40SKevin Wolf     int flags = 0;
91699cce9faSKevin Wolf     size_t cluster_size = DEFAULT_CLUSTER_SIZE;
917de5f3f40SKevin Wolf     int prealloc = 0;
918de5f3f40SKevin Wolf 
919de5f3f40SKevin Wolf     /* Read out options */
920de5f3f40SKevin Wolf     while (options && options->name) {
921de5f3f40SKevin Wolf         if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
922de5f3f40SKevin Wolf             sectors = options->value.n / 512;
923de5f3f40SKevin Wolf         } else if (!strcmp(options->name, BLOCK_OPT_BACKING_FILE)) {
924de5f3f40SKevin Wolf             backing_file = options->value.s;
925de5f3f40SKevin Wolf         } else if (!strcmp(options->name, BLOCK_OPT_BACKING_FMT)) {
926de5f3f40SKevin Wolf             backing_fmt = options->value.s;
927de5f3f40SKevin Wolf         } else if (!strcmp(options->name, BLOCK_OPT_ENCRYPT)) {
928de5f3f40SKevin Wolf             flags |= options->value.n ? BLOCK_FLAG_ENCRYPT : 0;
929de5f3f40SKevin Wolf         } else if (!strcmp(options->name, BLOCK_OPT_CLUSTER_SIZE)) {
930de5f3f40SKevin Wolf             if (options->value.n) {
931de5f3f40SKevin Wolf                 cluster_size = options->value.n;
932de5f3f40SKevin Wolf             }
933de5f3f40SKevin Wolf         } else if (!strcmp(options->name, BLOCK_OPT_PREALLOC)) {
934de5f3f40SKevin Wolf             if (!options->value.s || !strcmp(options->value.s, "off")) {
935de5f3f40SKevin Wolf                 prealloc = 0;
936de5f3f40SKevin Wolf             } else if (!strcmp(options->value.s, "metadata")) {
937de5f3f40SKevin Wolf                 prealloc = 1;
938de5f3f40SKevin Wolf             } else {
939de5f3f40SKevin Wolf                 fprintf(stderr, "Invalid preallocation mode: '%s'\n",
940de5f3f40SKevin Wolf                     options->value.s);
941de5f3f40SKevin Wolf                 return -EINVAL;
942de5f3f40SKevin Wolf             }
943de5f3f40SKevin Wolf         }
944de5f3f40SKevin Wolf         options++;
945de5f3f40SKevin Wolf     }
946de5f3f40SKevin Wolf 
947de5f3f40SKevin Wolf     if (backing_file && prealloc) {
948de5f3f40SKevin Wolf         fprintf(stderr, "Backing file and preallocation cannot be used at "
949de5f3f40SKevin Wolf             "the same time\n");
950de5f3f40SKevin Wolf         return -EINVAL;
951de5f3f40SKevin Wolf     }
952de5f3f40SKevin Wolf 
9537c80ab3fSJes Sorensen     return qcow2_create2(filename, sectors, backing_file, backing_fmt, flags,
954a9420734SKevin Wolf                          cluster_size, prealloc, options);
955de5f3f40SKevin Wolf }
956de5f3f40SKevin Wolf 
9577c80ab3fSJes Sorensen static int qcow2_make_empty(BlockDriverState *bs)
95820d97356SBlue Swirl {
95920d97356SBlue Swirl #if 0
96020d97356SBlue Swirl     /* XXX: not correct */
96120d97356SBlue Swirl     BDRVQcowState *s = bs->opaque;
96220d97356SBlue Swirl     uint32_t l1_length = s->l1_size * sizeof(uint64_t);
96320d97356SBlue Swirl     int ret;
96420d97356SBlue Swirl 
96520d97356SBlue Swirl     memset(s->l1_table, 0, l1_length);
96666f82ceeSKevin Wolf     if (bdrv_pwrite(bs->file, s->l1_table_offset, s->l1_table, l1_length) < 0)
96720d97356SBlue Swirl         return -1;
96866f82ceeSKevin Wolf     ret = bdrv_truncate(bs->file, s->l1_table_offset + l1_length);
96920d97356SBlue Swirl     if (ret < 0)
97020d97356SBlue Swirl         return ret;
97120d97356SBlue Swirl 
97220d97356SBlue Swirl     l2_cache_reset(bs);
97320d97356SBlue Swirl #endif
97420d97356SBlue Swirl     return 0;
97520d97356SBlue Swirl }
97620d97356SBlue Swirl 
9775ea929e3SKevin Wolf static int qcow2_discard(BlockDriverState *bs, int64_t sector_num,
9785ea929e3SKevin Wolf     int nb_sectors)
9795ea929e3SKevin Wolf {
9805ea929e3SKevin Wolf     return qcow2_discard_clusters(bs, sector_num << BDRV_SECTOR_BITS,
9815ea929e3SKevin Wolf         nb_sectors);
9825ea929e3SKevin Wolf }
9835ea929e3SKevin Wolf 
984419b19d9SStefan Hajnoczi static int qcow2_truncate(BlockDriverState *bs, int64_t offset)
985419b19d9SStefan Hajnoczi {
986419b19d9SStefan Hajnoczi     BDRVQcowState *s = bs->opaque;
987419b19d9SStefan Hajnoczi     int ret, new_l1_size;
988419b19d9SStefan Hajnoczi 
989419b19d9SStefan Hajnoczi     if (offset & 511) {
990419b19d9SStefan Hajnoczi         return -EINVAL;
991419b19d9SStefan Hajnoczi     }
992419b19d9SStefan Hajnoczi 
993419b19d9SStefan Hajnoczi     /* cannot proceed if image has snapshots */
994419b19d9SStefan Hajnoczi     if (s->nb_snapshots) {
995419b19d9SStefan Hajnoczi         return -ENOTSUP;
996419b19d9SStefan Hajnoczi     }
997419b19d9SStefan Hajnoczi 
998419b19d9SStefan Hajnoczi     /* shrinking is currently not supported */
999419b19d9SStefan Hajnoczi     if (offset < bs->total_sectors * 512) {
1000419b19d9SStefan Hajnoczi         return -ENOTSUP;
1001419b19d9SStefan Hajnoczi     }
1002419b19d9SStefan Hajnoczi 
1003419b19d9SStefan Hajnoczi     new_l1_size = size_to_l1(s, offset);
100472893756SStefan Hajnoczi     ret = qcow2_grow_l1_table(bs, new_l1_size, true);
1005419b19d9SStefan Hajnoczi     if (ret < 0) {
1006419b19d9SStefan Hajnoczi         return ret;
1007419b19d9SStefan Hajnoczi     }
1008419b19d9SStefan Hajnoczi 
1009419b19d9SStefan Hajnoczi     /* write updated header.size */
1010419b19d9SStefan Hajnoczi     offset = cpu_to_be64(offset);
10118b3b7206SKevin Wolf     ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, size),
1012419b19d9SStefan Hajnoczi                            &offset, sizeof(uint64_t));
1013419b19d9SStefan Hajnoczi     if (ret < 0) {
1014419b19d9SStefan Hajnoczi         return ret;
1015419b19d9SStefan Hajnoczi     }
1016419b19d9SStefan Hajnoczi 
1017419b19d9SStefan Hajnoczi     s->l1_vm_state_index = new_l1_size;
1018419b19d9SStefan Hajnoczi     return 0;
1019419b19d9SStefan Hajnoczi }
1020419b19d9SStefan Hajnoczi 
102120d97356SBlue Swirl /* XXX: put compressed sectors first, then all the cluster aligned
102220d97356SBlue Swirl    tables to avoid losing bytes in alignment */
10237c80ab3fSJes Sorensen static int qcow2_write_compressed(BlockDriverState *bs, int64_t sector_num,
102420d97356SBlue Swirl                                   const uint8_t *buf, int nb_sectors)
102520d97356SBlue Swirl {
102620d97356SBlue Swirl     BDRVQcowState *s = bs->opaque;
102720d97356SBlue Swirl     z_stream strm;
102820d97356SBlue Swirl     int ret, out_len;
102920d97356SBlue Swirl     uint8_t *out_buf;
103020d97356SBlue Swirl     uint64_t cluster_offset;
103120d97356SBlue Swirl 
103220d97356SBlue Swirl     if (nb_sectors == 0) {
103320d97356SBlue Swirl         /* align end of file to a sector boundary to ease reading with
103420d97356SBlue Swirl            sector based I/Os */
103566f82ceeSKevin Wolf         cluster_offset = bdrv_getlength(bs->file);
103620d97356SBlue Swirl         cluster_offset = (cluster_offset + 511) & ~511;
103766f82ceeSKevin Wolf         bdrv_truncate(bs->file, cluster_offset);
103820d97356SBlue Swirl         return 0;
103920d97356SBlue Swirl     }
104020d97356SBlue Swirl 
104120d97356SBlue Swirl     if (nb_sectors != s->cluster_sectors)
104220d97356SBlue Swirl         return -EINVAL;
104320d97356SBlue Swirl 
10447267c094SAnthony Liguori     out_buf = g_malloc(s->cluster_size + (s->cluster_size / 1000) + 128);
104520d97356SBlue Swirl 
104620d97356SBlue Swirl     /* best compression, small window, no zlib header */
104720d97356SBlue Swirl     memset(&strm, 0, sizeof(strm));
104820d97356SBlue Swirl     ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
104920d97356SBlue Swirl                        Z_DEFLATED, -12,
105020d97356SBlue Swirl                        9, Z_DEFAULT_STRATEGY);
105120d97356SBlue Swirl     if (ret != 0) {
10527267c094SAnthony Liguori         g_free(out_buf);
105320d97356SBlue Swirl         return -1;
105420d97356SBlue Swirl     }
105520d97356SBlue Swirl 
105620d97356SBlue Swirl     strm.avail_in = s->cluster_size;
105720d97356SBlue Swirl     strm.next_in = (uint8_t *)buf;
105820d97356SBlue Swirl     strm.avail_out = s->cluster_size;
105920d97356SBlue Swirl     strm.next_out = out_buf;
106020d97356SBlue Swirl 
106120d97356SBlue Swirl     ret = deflate(&strm, Z_FINISH);
106220d97356SBlue Swirl     if (ret != Z_STREAM_END && ret != Z_OK) {
10637267c094SAnthony Liguori         g_free(out_buf);
106420d97356SBlue Swirl         deflateEnd(&strm);
106520d97356SBlue Swirl         return -1;
106620d97356SBlue Swirl     }
106720d97356SBlue Swirl     out_len = strm.next_out - out_buf;
106820d97356SBlue Swirl 
106920d97356SBlue Swirl     deflateEnd(&strm);
107020d97356SBlue Swirl 
107120d97356SBlue Swirl     if (ret != Z_STREAM_END || out_len >= s->cluster_size) {
107220d97356SBlue Swirl         /* could not compress: write normal cluster */
107320d97356SBlue Swirl         bdrv_write(bs, sector_num, buf, s->cluster_sectors);
107420d97356SBlue Swirl     } else {
107520d97356SBlue Swirl         cluster_offset = qcow2_alloc_compressed_cluster_offset(bs,
107620d97356SBlue Swirl             sector_num << 9, out_len);
107720d97356SBlue Swirl         if (!cluster_offset)
107820d97356SBlue Swirl             return -1;
107920d97356SBlue Swirl         cluster_offset &= s->cluster_offset_mask;
108066f82ceeSKevin Wolf         BLKDBG_EVENT(bs->file, BLKDBG_WRITE_COMPRESSED);
108166f82ceeSKevin Wolf         if (bdrv_pwrite(bs->file, cluster_offset, out_buf, out_len) != out_len) {
10827267c094SAnthony Liguori             g_free(out_buf);
108320d97356SBlue Swirl             return -1;
108420d97356SBlue Swirl         }
108520d97356SBlue Swirl     }
108620d97356SBlue Swirl 
10877267c094SAnthony Liguori     g_free(out_buf);
108820d97356SBlue Swirl     return 0;
108920d97356SBlue Swirl }
109020d97356SBlue Swirl 
10917c80ab3fSJes Sorensen static int qcow2_flush(BlockDriverState *bs)
109220d97356SBlue Swirl {
109329c1a730SKevin Wolf     BDRVQcowState *s = bs->opaque;
109429c1a730SKevin Wolf     int ret;
109529c1a730SKevin Wolf 
109629c1a730SKevin Wolf     ret = qcow2_cache_flush(bs, s->l2_table_cache);
109729c1a730SKevin Wolf     if (ret < 0) {
109829c1a730SKevin Wolf         return ret;
109929c1a730SKevin Wolf     }
110029c1a730SKevin Wolf 
110129c1a730SKevin Wolf     ret = qcow2_cache_flush(bs, s->refcount_block_cache);
110229c1a730SKevin Wolf     if (ret < 0) {
110329c1a730SKevin Wolf         return ret;
110429c1a730SKevin Wolf     }
110529c1a730SKevin Wolf 
1106205ef796SKevin Wolf     return bdrv_flush(bs->file);
110720d97356SBlue Swirl }
110820d97356SBlue Swirl 
11097c80ab3fSJes Sorensen static BlockDriverAIOCB *qcow2_aio_flush(BlockDriverState *bs,
11107c80ab3fSJes Sorensen                                          BlockDriverCompletionFunc *cb,
11117c80ab3fSJes Sorensen                                          void *opaque)
111220d97356SBlue Swirl {
111329c1a730SKevin Wolf     BDRVQcowState *s = bs->opaque;
111429c1a730SKevin Wolf     int ret;
111529c1a730SKevin Wolf 
111629c1a730SKevin Wolf     ret = qcow2_cache_flush(bs, s->l2_table_cache);
111729c1a730SKevin Wolf     if (ret < 0) {
111829c1a730SKevin Wolf         return NULL;
111929c1a730SKevin Wolf     }
112029c1a730SKevin Wolf 
112129c1a730SKevin Wolf     ret = qcow2_cache_flush(bs, s->refcount_block_cache);
112229c1a730SKevin Wolf     if (ret < 0) {
112329c1a730SKevin Wolf         return NULL;
112429c1a730SKevin Wolf     }
112529c1a730SKevin Wolf 
112666f82ceeSKevin Wolf     return bdrv_aio_flush(bs->file, cb, opaque);
112720d97356SBlue Swirl }
112820d97356SBlue Swirl 
11297c80ab3fSJes Sorensen static int64_t qcow2_vm_state_offset(BDRVQcowState *s)
113020d97356SBlue Swirl {
113120d97356SBlue Swirl 	return (int64_t)s->l1_vm_state_index << (s->cluster_bits + s->l2_bits);
113220d97356SBlue Swirl }
113320d97356SBlue Swirl 
11347c80ab3fSJes Sorensen static int qcow2_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
113520d97356SBlue Swirl {
113620d97356SBlue Swirl     BDRVQcowState *s = bs->opaque;
113720d97356SBlue Swirl     bdi->cluster_size = s->cluster_size;
11387c80ab3fSJes Sorensen     bdi->vm_state_offset = qcow2_vm_state_offset(s);
113920d97356SBlue Swirl     return 0;
114020d97356SBlue Swirl }
114120d97356SBlue Swirl 
114220d97356SBlue Swirl 
11437c80ab3fSJes Sorensen static int qcow2_check(BlockDriverState *bs, BdrvCheckResult *result)
114420d97356SBlue Swirl {
11459ac228e0SKevin Wolf     return qcow2_check_refcounts(bs, result);
114620d97356SBlue Swirl }
114720d97356SBlue Swirl 
114820d97356SBlue Swirl #if 0
114920d97356SBlue Swirl static void dump_refcounts(BlockDriverState *bs)
115020d97356SBlue Swirl {
115120d97356SBlue Swirl     BDRVQcowState *s = bs->opaque;
115220d97356SBlue Swirl     int64_t nb_clusters, k, k1, size;
115320d97356SBlue Swirl     int refcount;
115420d97356SBlue Swirl 
115566f82ceeSKevin Wolf     size = bdrv_getlength(bs->file);
115620d97356SBlue Swirl     nb_clusters = size_to_clusters(s, size);
115720d97356SBlue Swirl     for(k = 0; k < nb_clusters;) {
115820d97356SBlue Swirl         k1 = k;
115920d97356SBlue Swirl         refcount = get_refcount(bs, k);
116020d97356SBlue Swirl         k++;
116120d97356SBlue Swirl         while (k < nb_clusters && get_refcount(bs, k) == refcount)
116220d97356SBlue Swirl             k++;
11630bfcd599SBlue Swirl         printf("%" PRId64 ": refcount=%d nb=%" PRId64 "\n", k, refcount,
11640bfcd599SBlue Swirl                k - k1);
116520d97356SBlue Swirl     }
116620d97356SBlue Swirl }
116720d97356SBlue Swirl #endif
116820d97356SBlue Swirl 
11697c80ab3fSJes Sorensen static int qcow2_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
117020d97356SBlue Swirl                               int64_t pos, int size)
117120d97356SBlue Swirl {
117220d97356SBlue Swirl     BDRVQcowState *s = bs->opaque;
117320d97356SBlue Swirl     int growable = bs->growable;
117420d97356SBlue Swirl     int ret;
117520d97356SBlue Swirl 
117666f82ceeSKevin Wolf     BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_SAVE);
117720d97356SBlue Swirl     bs->growable = 1;
11787c80ab3fSJes Sorensen     ret = bdrv_pwrite(bs, qcow2_vm_state_offset(s) + pos, buf, size);
117920d97356SBlue Swirl     bs->growable = growable;
118020d97356SBlue Swirl 
118120d97356SBlue Swirl     return ret;
118220d97356SBlue Swirl }
118320d97356SBlue Swirl 
11847c80ab3fSJes Sorensen static int qcow2_load_vmstate(BlockDriverState *bs, uint8_t *buf,
118520d97356SBlue Swirl                               int64_t pos, int size)
118620d97356SBlue Swirl {
118720d97356SBlue Swirl     BDRVQcowState *s = bs->opaque;
118820d97356SBlue Swirl     int growable = bs->growable;
118920d97356SBlue Swirl     int ret;
119020d97356SBlue Swirl 
119166f82ceeSKevin Wolf     BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_LOAD);
119220d97356SBlue Swirl     bs->growable = 1;
11937c80ab3fSJes Sorensen     ret = bdrv_pread(bs, qcow2_vm_state_offset(s) + pos, buf, size);
119420d97356SBlue Swirl     bs->growable = growable;
119520d97356SBlue Swirl 
119620d97356SBlue Swirl     return ret;
119720d97356SBlue Swirl }
119820d97356SBlue Swirl 
11997c80ab3fSJes Sorensen static QEMUOptionParameter qcow2_create_options[] = {
120020d97356SBlue Swirl     {
120120d97356SBlue Swirl         .name = BLOCK_OPT_SIZE,
120220d97356SBlue Swirl         .type = OPT_SIZE,
120320d97356SBlue Swirl         .help = "Virtual disk size"
120420d97356SBlue Swirl     },
120520d97356SBlue Swirl     {
120620d97356SBlue Swirl         .name = BLOCK_OPT_BACKING_FILE,
120720d97356SBlue Swirl         .type = OPT_STRING,
120820d97356SBlue Swirl         .help = "File name of a base image"
120920d97356SBlue Swirl     },
121020d97356SBlue Swirl     {
121120d97356SBlue Swirl         .name = BLOCK_OPT_BACKING_FMT,
121220d97356SBlue Swirl         .type = OPT_STRING,
121320d97356SBlue Swirl         .help = "Image format of the base image"
121420d97356SBlue Swirl     },
121520d97356SBlue Swirl     {
121620d97356SBlue Swirl         .name = BLOCK_OPT_ENCRYPT,
121720d97356SBlue Swirl         .type = OPT_FLAG,
121820d97356SBlue Swirl         .help = "Encrypt the image"
121920d97356SBlue Swirl     },
122020d97356SBlue Swirl     {
122120d97356SBlue Swirl         .name = BLOCK_OPT_CLUSTER_SIZE,
122220d97356SBlue Swirl         .type = OPT_SIZE,
122399cce9faSKevin Wolf         .help = "qcow2 cluster size",
122499cce9faSKevin Wolf         .value = { .n = DEFAULT_CLUSTER_SIZE },
122520d97356SBlue Swirl     },
122620d97356SBlue Swirl     {
122720d97356SBlue Swirl         .name = BLOCK_OPT_PREALLOC,
122820d97356SBlue Swirl         .type = OPT_STRING,
122920d97356SBlue Swirl         .help = "Preallocation mode (allowed values: off, metadata)"
123020d97356SBlue Swirl     },
123120d97356SBlue Swirl     { NULL }
123220d97356SBlue Swirl };
123320d97356SBlue Swirl 
123420d97356SBlue Swirl static BlockDriver bdrv_qcow2 = {
123520d97356SBlue Swirl     .format_name        = "qcow2",
123620d97356SBlue Swirl     .instance_size      = sizeof(BDRVQcowState),
12377c80ab3fSJes Sorensen     .bdrv_probe         = qcow2_probe,
12387c80ab3fSJes Sorensen     .bdrv_open          = qcow2_open,
12397c80ab3fSJes Sorensen     .bdrv_close         = qcow2_close,
12407c80ab3fSJes Sorensen     .bdrv_create        = qcow2_create,
12417c80ab3fSJes Sorensen     .bdrv_flush         = qcow2_flush,
12427c80ab3fSJes Sorensen     .bdrv_is_allocated  = qcow2_is_allocated,
12437c80ab3fSJes Sorensen     .bdrv_set_key       = qcow2_set_key,
12447c80ab3fSJes Sorensen     .bdrv_make_empty    = qcow2_make_empty,
124520d97356SBlue Swirl 
124668d100e9SKevin Wolf     .bdrv_co_readv      = qcow2_co_readv,
124768d100e9SKevin Wolf     .bdrv_co_writev     = qcow2_co_writev,
12487c80ab3fSJes Sorensen     .bdrv_aio_flush     = qcow2_aio_flush,
1249419b19d9SStefan Hajnoczi 
12505ea929e3SKevin Wolf     .bdrv_discard           = qcow2_discard,
1251419b19d9SStefan Hajnoczi     .bdrv_truncate          = qcow2_truncate,
12527c80ab3fSJes Sorensen     .bdrv_write_compressed  = qcow2_write_compressed,
125320d97356SBlue Swirl 
125420d97356SBlue Swirl     .bdrv_snapshot_create   = qcow2_snapshot_create,
125520d97356SBlue Swirl     .bdrv_snapshot_goto     = qcow2_snapshot_goto,
125620d97356SBlue Swirl     .bdrv_snapshot_delete   = qcow2_snapshot_delete,
125720d97356SBlue Swirl     .bdrv_snapshot_list     = qcow2_snapshot_list,
125851ef6727Sedison     .bdrv_snapshot_load_tmp     = qcow2_snapshot_load_tmp,
12597c80ab3fSJes Sorensen     .bdrv_get_info      = qcow2_get_info,
126020d97356SBlue Swirl 
12617c80ab3fSJes Sorensen     .bdrv_save_vmstate    = qcow2_save_vmstate,
12627c80ab3fSJes Sorensen     .bdrv_load_vmstate    = qcow2_load_vmstate,
126320d97356SBlue Swirl 
126420d97356SBlue Swirl     .bdrv_change_backing_file   = qcow2_change_backing_file,
126520d97356SBlue Swirl 
12667c80ab3fSJes Sorensen     .create_options = qcow2_create_options,
12677c80ab3fSJes Sorensen     .bdrv_check = qcow2_check,
126820d97356SBlue Swirl };
126920d97356SBlue Swirl 
12705efa9d5aSAnthony Liguori static void bdrv_qcow2_init(void)
12715efa9d5aSAnthony Liguori {
12725efa9d5aSAnthony Liguori     bdrv_register(&bdrv_qcow2);
12735efa9d5aSAnthony Liguori }
12745efa9d5aSAnthony Liguori 
12755efa9d5aSAnthony Liguori block_init(bdrv_qcow2_init);
1276