xref: /qemu/block/qcow2.c (revision d6e9098e10e82feeddb824d7c3d0cf61aff96c29)
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"
30585f8587Sbellard 
31585f8587Sbellard /*
32585f8587Sbellard   Differences with QCOW:
33585f8587Sbellard 
34585f8587Sbellard   - Support for multiple incremental snapshots.
35585f8587Sbellard   - Memory management by reference counts.
36585f8587Sbellard   - Clusters which have a reference count of one have the bit
37585f8587Sbellard     QCOW_OFLAG_COPIED to optimize write performance.
38585f8587Sbellard   - Size of compressed clusters is stored in sectors to reduce bit usage
39585f8587Sbellard     in the cluster offsets.
40585f8587Sbellard   - Support for storing additional data (such as the VM state) in the
41585f8587Sbellard     snapshots.
42585f8587Sbellard   - If a backing store is used, the cluster size is not constrained
43585f8587Sbellard     (could be backported to QCOW).
44585f8587Sbellard   - L2 tables have always a size of one cluster.
45585f8587Sbellard */
46585f8587Sbellard 
479b80ddf3Saliguori 
489b80ddf3Saliguori typedef struct {
499b80ddf3Saliguori     uint32_t magic;
509b80ddf3Saliguori     uint32_t len;
519b80ddf3Saliguori } QCowExtension;
529b80ddf3Saliguori #define  QCOW_EXT_MAGIC_END 0
53f965509cSaliguori #define  QCOW_EXT_MAGIC_BACKING_FORMAT 0xE2792ACA
549b80ddf3Saliguori 
55*d6e9098eSKevin Wolf static BlockDriver bdrv_qcow2;
56585f8587Sbellard 
57585f8587Sbellard static int qcow_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 &&
63585f8587Sbellard         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  */
779b80ddf3Saliguori static int qcow_read_extensions(BlockDriverState *bs, uint64_t start_offset,
789b80ddf3Saliguori                                 uint64_t end_offset)
799b80ddf3Saliguori {
809b80ddf3Saliguori     BDRVQcowState *s = bs->opaque;
819b80ddf3Saliguori     QCowExtension ext;
829b80ddf3Saliguori     uint64_t offset;
839b80ddf3Saliguori 
849b80ddf3Saliguori #ifdef DEBUG_EXT
859b80ddf3Saliguori     printf("qcow_read_extensions: start=%ld end=%ld\n", start_offset, end_offset);
869b80ddf3Saliguori #endif
879b80ddf3Saliguori     offset = start_offset;
889b80ddf3Saliguori     while (offset < end_offset) {
899b80ddf3Saliguori 
909b80ddf3Saliguori #ifdef DEBUG_EXT
919b80ddf3Saliguori         /* Sanity check */
929b80ddf3Saliguori         if (offset > s->cluster_size)
939b80ddf3Saliguori             printf("qcow_handle_extension: suspicious offset %lu\n", offset);
949b80ddf3Saliguori 
959b80ddf3Saliguori         printf("attemting to read extended header in offset %lu\n", offset);
969b80ddf3Saliguori #endif
979b80ddf3Saliguori 
989b80ddf3Saliguori         if (bdrv_pread(s->hd, offset, &ext, sizeof(ext)) != sizeof(ext)) {
994c978075Saliguori             fprintf(stderr, "qcow_handle_extension: ERROR: pread fail from offset %llu\n",
1004c978075Saliguori                     (unsigned long long)offset);
1019b80ddf3Saliguori             return 1;
1029b80ddf3Saliguori         }
1039b80ddf3Saliguori         be32_to_cpus(&ext.magic);
1049b80ddf3Saliguori         be32_to_cpus(&ext.len);
1059b80ddf3Saliguori         offset += sizeof(ext);
1069b80ddf3Saliguori #ifdef DEBUG_EXT
1079b80ddf3Saliguori         printf("ext.magic = 0x%x\n", ext.magic);
1089b80ddf3Saliguori #endif
1099b80ddf3Saliguori         switch (ext.magic) {
1109b80ddf3Saliguori         case QCOW_EXT_MAGIC_END:
1119b80ddf3Saliguori             return 0;
112f965509cSaliguori 
113f965509cSaliguori         case QCOW_EXT_MAGIC_BACKING_FORMAT:
114f965509cSaliguori             if (ext.len >= sizeof(bs->backing_format)) {
115f965509cSaliguori                 fprintf(stderr, "ERROR: ext_backing_format: len=%u too large"
1164c978075Saliguori                         " (>=%zu)\n",
117f965509cSaliguori                         ext.len, sizeof(bs->backing_format));
118f965509cSaliguori                 return 2;
119f965509cSaliguori             }
120f965509cSaliguori             if (bdrv_pread(s->hd, offset , bs->backing_format,
121f965509cSaliguori                            ext.len) != ext.len)
122f965509cSaliguori                 return 3;
123f965509cSaliguori             bs->backing_format[ext.len] = '\0';
124f965509cSaliguori #ifdef DEBUG_EXT
125f965509cSaliguori             printf("Qcow2: Got format extension %s\n", bs->backing_format);
126f965509cSaliguori #endif
127e1c7f0e3SKevin Wolf             offset = ((offset + ext.len + 7) & ~7);
128f965509cSaliguori             break;
129f965509cSaliguori 
1309b80ddf3Saliguori         default:
1319b80ddf3Saliguori             /* unknown magic -- just skip it */
132e1c7f0e3SKevin Wolf             offset = ((offset + ext.len + 7) & ~7);
1339b80ddf3Saliguori             break;
1349b80ddf3Saliguori         }
1359b80ddf3Saliguori     }
1369b80ddf3Saliguori 
1379b80ddf3Saliguori     return 0;
1389b80ddf3Saliguori }
1399b80ddf3Saliguori 
1409b80ddf3Saliguori 
141585f8587Sbellard static int qcow_open(BlockDriverState *bs, const char *filename, int flags)
142585f8587Sbellard {
143585f8587Sbellard     BDRVQcowState *s = bs->opaque;
144585f8587Sbellard     int len, i, shift, ret;
145585f8587Sbellard     QCowHeader header;
1469b80ddf3Saliguori     uint64_t ext_end;
147585f8587Sbellard 
148b5eff355Saurel32     ret = bdrv_file_open(&s->hd, filename, flags);
149585f8587Sbellard     if (ret < 0)
150585f8587Sbellard         return ret;
151585f8587Sbellard     if (bdrv_pread(s->hd, 0, &header, sizeof(header)) != sizeof(header))
152585f8587Sbellard         goto fail;
153585f8587Sbellard     be32_to_cpus(&header.magic);
154585f8587Sbellard     be32_to_cpus(&header.version);
155585f8587Sbellard     be64_to_cpus(&header.backing_file_offset);
156585f8587Sbellard     be32_to_cpus(&header.backing_file_size);
157585f8587Sbellard     be64_to_cpus(&header.size);
158585f8587Sbellard     be32_to_cpus(&header.cluster_bits);
159585f8587Sbellard     be32_to_cpus(&header.crypt_method);
160585f8587Sbellard     be64_to_cpus(&header.l1_table_offset);
161585f8587Sbellard     be32_to_cpus(&header.l1_size);
162585f8587Sbellard     be64_to_cpus(&header.refcount_table_offset);
163585f8587Sbellard     be32_to_cpus(&header.refcount_table_clusters);
164585f8587Sbellard     be64_to_cpus(&header.snapshots_offset);
165585f8587Sbellard     be32_to_cpus(&header.nb_snapshots);
166585f8587Sbellard 
167585f8587Sbellard     if (header.magic != QCOW_MAGIC || header.version != QCOW_VERSION)
168585f8587Sbellard         goto fail;
169d191d12dSStefan Weil     if (header.cluster_bits < MIN_CLUSTER_BITS ||
17073c632edSKevin Wolf         header.cluster_bits > MAX_CLUSTER_BITS)
171585f8587Sbellard         goto fail;
172585f8587Sbellard     if (header.crypt_method > QCOW_CRYPT_AES)
173585f8587Sbellard         goto fail;
174585f8587Sbellard     s->crypt_method_header = header.crypt_method;
175585f8587Sbellard     if (s->crypt_method_header)
176585f8587Sbellard         bs->encrypted = 1;
177585f8587Sbellard     s->cluster_bits = header.cluster_bits;
178585f8587Sbellard     s->cluster_size = 1 << s->cluster_bits;
179585f8587Sbellard     s->cluster_sectors = 1 << (s->cluster_bits - 9);
180585f8587Sbellard     s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */
181585f8587Sbellard     s->l2_size = 1 << s->l2_bits;
182585f8587Sbellard     bs->total_sectors = header.size / 512;
183585f8587Sbellard     s->csize_shift = (62 - (s->cluster_bits - 8));
184585f8587Sbellard     s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;
185585f8587Sbellard     s->cluster_offset_mask = (1LL << s->csize_shift) - 1;
186585f8587Sbellard     s->refcount_table_offset = header.refcount_table_offset;
187585f8587Sbellard     s->refcount_table_size =
188585f8587Sbellard         header.refcount_table_clusters << (s->cluster_bits - 3);
189585f8587Sbellard 
190585f8587Sbellard     s->snapshots_offset = header.snapshots_offset;
191585f8587Sbellard     s->nb_snapshots = header.nb_snapshots;
192585f8587Sbellard 
193585f8587Sbellard     /* read the level 1 table */
194585f8587Sbellard     s->l1_size = header.l1_size;
195585f8587Sbellard     shift = s->cluster_bits + s->l2_bits;
196585f8587Sbellard     s->l1_vm_state_index = (header.size + (1LL << shift) - 1) >> shift;
197585f8587Sbellard     /* the L1 table must contain at least enough entries to put
198585f8587Sbellard        header.size bytes */
199585f8587Sbellard     if (s->l1_size < s->l1_vm_state_index)
200585f8587Sbellard         goto fail;
201585f8587Sbellard     s->l1_table_offset = header.l1_table_offset;
202d191d12dSStefan Weil     if (s->l1_size > 0) {
2033f6a3ee5SKevin Wolf         s->l1_table = qemu_mallocz(
2043f6a3ee5SKevin Wolf             align_offset(s->l1_size * sizeof(uint64_t), 512));
205585f8587Sbellard         if (bdrv_pread(s->hd, s->l1_table_offset, s->l1_table, s->l1_size * sizeof(uint64_t)) !=
206585f8587Sbellard             s->l1_size * sizeof(uint64_t))
207585f8587Sbellard             goto fail;
208585f8587Sbellard         for(i = 0;i < s->l1_size; i++) {
209585f8587Sbellard             be64_to_cpus(&s->l1_table[i]);
210585f8587Sbellard         }
211d191d12dSStefan Weil     }
212585f8587Sbellard     /* alloc L2 cache */
213585f8587Sbellard     s->l2_cache = qemu_malloc(s->l2_size * L2_CACHE_SIZE * sizeof(uint64_t));
214585f8587Sbellard     s->cluster_cache = qemu_malloc(s->cluster_size);
215585f8587Sbellard     /* one more sector for decompressed data alignment */
216095a9c58Saliguori     s->cluster_data = qemu_malloc(QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size
217095a9c58Saliguori                                   + 512);
218585f8587Sbellard     s->cluster_cache_offset = -1;
219585f8587Sbellard 
220ed6ccf0fSKevin Wolf     if (qcow2_refcount_init(bs) < 0)
221585f8587Sbellard         goto fail;
222585f8587Sbellard 
22372cf2d4fSBlue Swirl     QLIST_INIT(&s->cluster_allocs);
224f214978aSKevin Wolf 
2259b80ddf3Saliguori     /* read qcow2 extensions */
2269b80ddf3Saliguori     if (header.backing_file_offset)
2279b80ddf3Saliguori         ext_end = header.backing_file_offset;
2289b80ddf3Saliguori     else
2299b80ddf3Saliguori         ext_end = s->cluster_size;
2309b80ddf3Saliguori     if (qcow_read_extensions(bs, sizeof(header), ext_end))
2319b80ddf3Saliguori         goto fail;
2329b80ddf3Saliguori 
233585f8587Sbellard     /* read the backing file name */
234585f8587Sbellard     if (header.backing_file_offset != 0) {
235585f8587Sbellard         len = header.backing_file_size;
236585f8587Sbellard         if (len > 1023)
237585f8587Sbellard             len = 1023;
238585f8587Sbellard         if (bdrv_pread(s->hd, header.backing_file_offset, bs->backing_file, len) != len)
239585f8587Sbellard             goto fail;
240585f8587Sbellard         bs->backing_file[len] = '\0';
241585f8587Sbellard     }
242ed6ccf0fSKevin Wolf     if (qcow2_read_snapshots(bs) < 0)
243585f8587Sbellard         goto fail;
244585f8587Sbellard 
245585f8587Sbellard #ifdef DEBUG_ALLOC
24614899cdfSFilip Navara     qcow2_check_refcounts(bs);
247585f8587Sbellard #endif
248585f8587Sbellard     return 0;
249585f8587Sbellard 
250585f8587Sbellard  fail:
251ed6ccf0fSKevin Wolf     qcow2_free_snapshots(bs);
252ed6ccf0fSKevin Wolf     qcow2_refcount_close(bs);
253585f8587Sbellard     qemu_free(s->l1_table);
254585f8587Sbellard     qemu_free(s->l2_cache);
255585f8587Sbellard     qemu_free(s->cluster_cache);
256585f8587Sbellard     qemu_free(s->cluster_data);
257585f8587Sbellard     bdrv_delete(s->hd);
258585f8587Sbellard     return -1;
259585f8587Sbellard }
260585f8587Sbellard 
261585f8587Sbellard static int qcow_set_key(BlockDriverState *bs, const char *key)
262585f8587Sbellard {
263585f8587Sbellard     BDRVQcowState *s = bs->opaque;
264585f8587Sbellard     uint8_t keybuf[16];
265585f8587Sbellard     int len, i;
266585f8587Sbellard 
267585f8587Sbellard     memset(keybuf, 0, 16);
268585f8587Sbellard     len = strlen(key);
269585f8587Sbellard     if (len > 16)
270585f8587Sbellard         len = 16;
271585f8587Sbellard     /* XXX: we could compress the chars to 7 bits to increase
272585f8587Sbellard        entropy */
273585f8587Sbellard     for(i = 0;i < len;i++) {
274585f8587Sbellard         keybuf[i] = key[i];
275585f8587Sbellard     }
276585f8587Sbellard     s->crypt_method = s->crypt_method_header;
277585f8587Sbellard 
278585f8587Sbellard     if (AES_set_encrypt_key(keybuf, 128, &s->aes_encrypt_key) != 0)
279585f8587Sbellard         return -1;
280585f8587Sbellard     if (AES_set_decrypt_key(keybuf, 128, &s->aes_decrypt_key) != 0)
281585f8587Sbellard         return -1;
282585f8587Sbellard #if 0
283585f8587Sbellard     /* test */
284585f8587Sbellard     {
285585f8587Sbellard         uint8_t in[16];
286585f8587Sbellard         uint8_t out[16];
287585f8587Sbellard         uint8_t tmp[16];
288585f8587Sbellard         for(i=0;i<16;i++)
289585f8587Sbellard             in[i] = i;
290585f8587Sbellard         AES_encrypt(in, tmp, &s->aes_encrypt_key);
291585f8587Sbellard         AES_decrypt(tmp, out, &s->aes_decrypt_key);
292585f8587Sbellard         for(i = 0; i < 16; i++)
293585f8587Sbellard             printf(" %02x", tmp[i]);
294585f8587Sbellard         printf("\n");
295585f8587Sbellard         for(i = 0; i < 16; i++)
296585f8587Sbellard             printf(" %02x", out[i]);
297585f8587Sbellard         printf("\n");
298585f8587Sbellard     }
299585f8587Sbellard #endif
300585f8587Sbellard     return 0;
301585f8587Sbellard }
302585f8587Sbellard 
303585f8587Sbellard static int qcow_is_allocated(BlockDriverState *bs, int64_t sector_num,
304585f8587Sbellard                              int nb_sectors, int *pnum)
305585f8587Sbellard {
306585f8587Sbellard     uint64_t cluster_offset;
307585f8587Sbellard 
308095a9c58Saliguori     *pnum = nb_sectors;
309ed6ccf0fSKevin Wolf     cluster_offset = qcow2_get_cluster_offset(bs, sector_num << 9, pnum);
310095a9c58Saliguori 
311585f8587Sbellard     return (cluster_offset != 0);
312585f8587Sbellard }
313585f8587Sbellard 
314a9465922Sbellard /* handle reading after the end of the backing file */
315ed6ccf0fSKevin Wolf int qcow2_backing_read1(BlockDriverState *bs,
316a9465922Sbellard                   int64_t sector_num, uint8_t *buf, int nb_sectors)
317a9465922Sbellard {
318a9465922Sbellard     int n1;
319a9465922Sbellard     if ((sector_num + nb_sectors) <= bs->total_sectors)
320a9465922Sbellard         return nb_sectors;
321a9465922Sbellard     if (sector_num >= bs->total_sectors)
322a9465922Sbellard         n1 = 0;
323a9465922Sbellard     else
324a9465922Sbellard         n1 = bs->total_sectors - sector_num;
325a9465922Sbellard     memset(buf + n1 * 512, 0, 512 * (nb_sectors - n1));
326a9465922Sbellard     return n1;
327a9465922Sbellard }
328a9465922Sbellard 
329ce1a14dcSpbrook typedef struct QCowAIOCB {
330ce1a14dcSpbrook     BlockDriverAIOCB common;
331585f8587Sbellard     int64_t sector_num;
332f141eafeSaliguori     QEMUIOVector *qiov;
333585f8587Sbellard     uint8_t *buf;
334f141eafeSaliguori     void *orig_buf;
3357b88e48bSChristoph Hellwig     int remaining_sectors;
3367b88e48bSChristoph Hellwig     int cur_nr_sectors;	/* number of sectors in current iteration */
337585f8587Sbellard     uint64_t cluster_offset;
338585f8587Sbellard     uint8_t *cluster_data;
339585f8587Sbellard     BlockDriverAIOCB *hd_aiocb;
340c87c0672Saliguori     struct iovec hd_iov;
341c87c0672Saliguori     QEMUIOVector hd_qiov;
3421490791fSaliguori     QEMUBH *bh;
343e976c6a1Saliguori     QCowL2Meta l2meta;
34472cf2d4fSBlue Swirl     QLIST_ENTRY(QCowAIOCB) next_depend;
345585f8587Sbellard } QCowAIOCB;
346585f8587Sbellard 
347c16b5a2cSChristoph Hellwig static void qcow_aio_cancel(BlockDriverAIOCB *blockacb)
348c16b5a2cSChristoph Hellwig {
349c16b5a2cSChristoph Hellwig     QCowAIOCB *acb = (QCowAIOCB *)blockacb;
350c16b5a2cSChristoph Hellwig     if (acb->hd_aiocb)
351c16b5a2cSChristoph Hellwig         bdrv_aio_cancel(acb->hd_aiocb);
352c16b5a2cSChristoph Hellwig     qemu_aio_release(acb);
353c16b5a2cSChristoph Hellwig }
354c16b5a2cSChristoph Hellwig 
355c16b5a2cSChristoph Hellwig static AIOPool qcow_aio_pool = {
356c16b5a2cSChristoph Hellwig     .aiocb_size         = sizeof(QCowAIOCB),
357c16b5a2cSChristoph Hellwig     .cancel             = qcow_aio_cancel,
358c16b5a2cSChristoph Hellwig };
359c16b5a2cSChristoph Hellwig 
3601490791fSaliguori static void qcow_aio_read_cb(void *opaque, int ret);
3611490791fSaliguori static void qcow_aio_read_bh(void *opaque)
3621490791fSaliguori {
3631490791fSaliguori     QCowAIOCB *acb = opaque;
3641490791fSaliguori     qemu_bh_delete(acb->bh);
3651490791fSaliguori     acb->bh = NULL;
3661490791fSaliguori     qcow_aio_read_cb(opaque, 0);
3671490791fSaliguori }
3681490791fSaliguori 
369a32ef786Saliguori static int qcow_schedule_bh(QEMUBHFunc *cb, QCowAIOCB *acb)
370a32ef786Saliguori {
371a32ef786Saliguori     if (acb->bh)
372a32ef786Saliguori         return -EIO;
373a32ef786Saliguori 
374a32ef786Saliguori     acb->bh = qemu_bh_new(cb, acb);
375a32ef786Saliguori     if (!acb->bh)
376a32ef786Saliguori         return -EIO;
377a32ef786Saliguori 
378a32ef786Saliguori     qemu_bh_schedule(acb->bh);
379a32ef786Saliguori 
380a32ef786Saliguori     return 0;
381a32ef786Saliguori }
382a32ef786Saliguori 
383585f8587Sbellard static void qcow_aio_read_cb(void *opaque, int ret)
384585f8587Sbellard {
385ce1a14dcSpbrook     QCowAIOCB *acb = opaque;
386ce1a14dcSpbrook     BlockDriverState *bs = acb->common.bs;
387585f8587Sbellard     BDRVQcowState *s = bs->opaque;
388a9465922Sbellard     int index_in_cluster, n1;
389585f8587Sbellard 
390ce1a14dcSpbrook     acb->hd_aiocb = NULL;
391f141eafeSaliguori     if (ret < 0)
392f141eafeSaliguori         goto done;
393585f8587Sbellard 
394585f8587Sbellard     /* post process the read buffer */
395ce1a14dcSpbrook     if (!acb->cluster_offset) {
396585f8587Sbellard         /* nothing to do */
397ce1a14dcSpbrook     } else if (acb->cluster_offset & QCOW_OFLAG_COMPRESSED) {
398585f8587Sbellard         /* nothing to do */
399585f8587Sbellard     } else {
400585f8587Sbellard         if (s->crypt_method) {
401ed6ccf0fSKevin Wolf             qcow2_encrypt_sectors(s, acb->sector_num, acb->buf, acb->buf,
4027b88e48bSChristoph Hellwig                             acb->cur_nr_sectors, 0,
403585f8587Sbellard                             &s->aes_decrypt_key);
404585f8587Sbellard         }
405585f8587Sbellard     }
406585f8587Sbellard 
4077b88e48bSChristoph Hellwig     acb->remaining_sectors -= acb->cur_nr_sectors;
4087b88e48bSChristoph Hellwig     acb->sector_num += acb->cur_nr_sectors;
4097b88e48bSChristoph Hellwig     acb->buf += acb->cur_nr_sectors * 512;
410585f8587Sbellard 
4117b88e48bSChristoph Hellwig     if (acb->remaining_sectors == 0) {
412585f8587Sbellard         /* request completed */
413f141eafeSaliguori         ret = 0;
414f141eafeSaliguori         goto done;
415585f8587Sbellard     }
416585f8587Sbellard 
417585f8587Sbellard     /* prepare next AIO request */
4187b88e48bSChristoph Hellwig     acb->cur_nr_sectors = acb->remaining_sectors;
4197b88e48bSChristoph Hellwig     acb->cluster_offset = qcow2_get_cluster_offset(bs, acb->sector_num << 9,
4207b88e48bSChristoph Hellwig                                                    &acb->cur_nr_sectors);
421095a9c58Saliguori     index_in_cluster = acb->sector_num & (s->cluster_sectors - 1);
422585f8587Sbellard 
423ce1a14dcSpbrook     if (!acb->cluster_offset) {
424585f8587Sbellard         if (bs->backing_hd) {
425585f8587Sbellard             /* read from the base image */
426ed6ccf0fSKevin Wolf             n1 = qcow2_backing_read1(bs->backing_hd, acb->sector_num,
4277b88e48bSChristoph Hellwig                                acb->buf, acb->cur_nr_sectors);
428a9465922Sbellard             if (n1 > 0) {
4293f4cb3d3Sblueswir1                 acb->hd_iov.iov_base = (void *)acb->buf;
4307b88e48bSChristoph Hellwig                 acb->hd_iov.iov_len = acb->cur_nr_sectors * 512;
431c87c0672Saliguori                 qemu_iovec_init_external(&acb->hd_qiov, &acb->hd_iov, 1);
4328252278aSKevin Wolf                 BLKDBG_EVENT(s->hd, BLKDBG_READ_BACKING_AIO);
433c87c0672Saliguori                 acb->hd_aiocb = bdrv_aio_readv(bs->backing_hd, acb->sector_num,
4347b88e48bSChristoph Hellwig                                     &acb->hd_qiov, acb->cur_nr_sectors,
435c87c0672Saliguori 				    qcow_aio_read_cb, acb);
436ce1a14dcSpbrook                 if (acb->hd_aiocb == NULL)
437f141eafeSaliguori                     goto done;
438585f8587Sbellard             } else {
439a32ef786Saliguori                 ret = qcow_schedule_bh(qcow_aio_read_bh, acb);
440a32ef786Saliguori                 if (ret < 0)
441f141eafeSaliguori                     goto done;
4421490791fSaliguori             }
443a9465922Sbellard         } else {
444585f8587Sbellard             /* Note: in this case, no need to wait */
4457b88e48bSChristoph Hellwig             memset(acb->buf, 0, 512 * acb->cur_nr_sectors);
446a32ef786Saliguori             ret = qcow_schedule_bh(qcow_aio_read_bh, acb);
447a32ef786Saliguori             if (ret < 0)
448f141eafeSaliguori                 goto done;
4491490791fSaliguori         }
450ce1a14dcSpbrook     } else if (acb->cluster_offset & QCOW_OFLAG_COMPRESSED) {
451585f8587Sbellard         /* add AIO support for compressed blocks ? */
452ed6ccf0fSKevin Wolf         if (qcow2_decompress_cluster(s, acb->cluster_offset) < 0)
453f141eafeSaliguori             goto done;
4547b88e48bSChristoph Hellwig         memcpy(acb->buf, s->cluster_cache + index_in_cluster * 512,
4557b88e48bSChristoph Hellwig                512 * acb->cur_nr_sectors);
456a32ef786Saliguori         ret = qcow_schedule_bh(qcow_aio_read_bh, acb);
457a32ef786Saliguori         if (ret < 0)
458f141eafeSaliguori             goto done;
459585f8587Sbellard     } else {
460ce1a14dcSpbrook         if ((acb->cluster_offset & 511) != 0) {
461585f8587Sbellard             ret = -EIO;
462f141eafeSaliguori             goto done;
463585f8587Sbellard         }
464c87c0672Saliguori 
4653f4cb3d3Sblueswir1         acb->hd_iov.iov_base = (void *)acb->buf;
4667b88e48bSChristoph Hellwig         acb->hd_iov.iov_len = acb->cur_nr_sectors * 512;
467c87c0672Saliguori         qemu_iovec_init_external(&acb->hd_qiov, &acb->hd_iov, 1);
4688252278aSKevin Wolf         BLKDBG_EVENT(s->hd, BLKDBG_READ_AIO);
469c87c0672Saliguori         acb->hd_aiocb = bdrv_aio_readv(s->hd,
470ce1a14dcSpbrook                             (acb->cluster_offset >> 9) + index_in_cluster,
4717b88e48bSChristoph Hellwig                             &acb->hd_qiov, acb->cur_nr_sectors,
4727b88e48bSChristoph Hellwig                             qcow_aio_read_cb, acb);
473171e3d6bSKevin Wolf         if (acb->hd_aiocb == NULL) {
474171e3d6bSKevin Wolf             ret = -EIO;
475f141eafeSaliguori             goto done;
476585f8587Sbellard         }
477171e3d6bSKevin Wolf     }
478f141eafeSaliguori 
479f141eafeSaliguori     return;
480f141eafeSaliguori done:
481f141eafeSaliguori     if (acb->qiov->niov > 1) {
482f141eafeSaliguori         qemu_iovec_from_buffer(acb->qiov, acb->orig_buf, acb->qiov->size);
483f141eafeSaliguori         qemu_vfree(acb->orig_buf);
484f141eafeSaliguori     }
485f141eafeSaliguori     acb->common.cb(acb->common.opaque, ret);
486f141eafeSaliguori     qemu_aio_release(acb);
487585f8587Sbellard }
488585f8587Sbellard 
489ce1a14dcSpbrook static QCowAIOCB *qcow_aio_setup(BlockDriverState *bs,
490f141eafeSaliguori         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
491f141eafeSaliguori         BlockDriverCompletionFunc *cb, void *opaque, int is_write)
492585f8587Sbellard {
493ce1a14dcSpbrook     QCowAIOCB *acb;
494585f8587Sbellard 
495c16b5a2cSChristoph Hellwig     acb = qemu_aio_get(&qcow_aio_pool, bs, cb, opaque);
496ce1a14dcSpbrook     if (!acb)
497ce1a14dcSpbrook         return NULL;
498ce1a14dcSpbrook     acb->hd_aiocb = NULL;
499ce1a14dcSpbrook     acb->sector_num = sector_num;
500f141eafeSaliguori     acb->qiov = qiov;
501f141eafeSaliguori     if (qiov->niov > 1) {
502e268ca52Saliguori         acb->buf = acb->orig_buf = qemu_blockalign(bs, qiov->size);
503f141eafeSaliguori         if (is_write)
504f141eafeSaliguori             qemu_iovec_to_buffer(qiov, acb->buf);
5053f4cb3d3Sblueswir1     } else {
5063f4cb3d3Sblueswir1         acb->buf = (uint8_t *)qiov->iov->iov_base;
5073f4cb3d3Sblueswir1     }
5087b88e48bSChristoph Hellwig     acb->remaining_sectors = nb_sectors;
5097b88e48bSChristoph Hellwig     acb->cur_nr_sectors = 0;
510ce1a14dcSpbrook     acb->cluster_offset = 0;
511e976c6a1Saliguori     acb->l2meta.nb_clusters = 0;
51272cf2d4fSBlue Swirl     QLIST_INIT(&acb->l2meta.dependent_requests);
513ce1a14dcSpbrook     return acb;
514ce1a14dcSpbrook }
515ce1a14dcSpbrook 
516f141eafeSaliguori static BlockDriverAIOCB *qcow_aio_readv(BlockDriverState *bs,
517f141eafeSaliguori         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
518ce1a14dcSpbrook         BlockDriverCompletionFunc *cb, void *opaque)
519ce1a14dcSpbrook {
520ce1a14dcSpbrook     QCowAIOCB *acb;
521ce1a14dcSpbrook 
522f141eafeSaliguori     acb = qcow_aio_setup(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
523ce1a14dcSpbrook     if (!acb)
524ce1a14dcSpbrook         return NULL;
525585f8587Sbellard 
526585f8587Sbellard     qcow_aio_read_cb(acb, 0);
527ce1a14dcSpbrook     return &acb->common;
528585f8587Sbellard }
529585f8587Sbellard 
530f214978aSKevin Wolf static void qcow_aio_write_cb(void *opaque, int ret);
531f214978aSKevin Wolf 
532f214978aSKevin Wolf static void run_dependent_requests(QCowL2Meta *m)
533f214978aSKevin Wolf {
534f214978aSKevin Wolf     QCowAIOCB *req;
535f214978aSKevin Wolf     QCowAIOCB *next;
536f214978aSKevin Wolf 
537f214978aSKevin Wolf     /* Take the request off the list of running requests */
538f214978aSKevin Wolf     if (m->nb_clusters != 0) {
53972cf2d4fSBlue Swirl         QLIST_REMOVE(m, next_in_flight);
540f214978aSKevin Wolf     }
541f214978aSKevin Wolf 
542f214978aSKevin Wolf     /*
543f214978aSKevin Wolf      * Restart all dependent requests.
54472cf2d4fSBlue Swirl      * Can't use QLIST_FOREACH here - the next link might not be the same
545f214978aSKevin Wolf      * any more after the callback  (request could depend on a different
546f214978aSKevin Wolf      * request now)
547f214978aSKevin Wolf      */
548f214978aSKevin Wolf     for (req = m->dependent_requests.lh_first; req != NULL; req = next) {
549f214978aSKevin Wolf         next = req->next_depend.le_next;
550f214978aSKevin Wolf         qcow_aio_write_cb(req, 0);
551f214978aSKevin Wolf     }
552f214978aSKevin Wolf 
553f214978aSKevin Wolf     /* Empty the list for the next part of the request */
55472cf2d4fSBlue Swirl     QLIST_INIT(&m->dependent_requests);
555f214978aSKevin Wolf }
556f214978aSKevin Wolf 
557585f8587Sbellard static void qcow_aio_write_cb(void *opaque, int ret)
558585f8587Sbellard {
559ce1a14dcSpbrook     QCowAIOCB *acb = opaque;
560ce1a14dcSpbrook     BlockDriverState *bs = acb->common.bs;
561585f8587Sbellard     BDRVQcowState *s = bs->opaque;
562585f8587Sbellard     int index_in_cluster;
563585f8587Sbellard     const uint8_t *src_buf;
564095a9c58Saliguori     int n_end;
565585f8587Sbellard 
566ce1a14dcSpbrook     acb->hd_aiocb = NULL;
567ce1a14dcSpbrook 
568f214978aSKevin Wolf     if (ret >= 0) {
569148da7eaSKevin Wolf         ret = qcow2_alloc_cluster_link_l2(bs, &acb->l2meta);
570f214978aSKevin Wolf     }
571f214978aSKevin Wolf 
572f214978aSKevin Wolf     run_dependent_requests(&acb->l2meta);
573f214978aSKevin Wolf 
574f141eafeSaliguori     if (ret < 0)
575f141eafeSaliguori         goto done;
576585f8587Sbellard 
5777b88e48bSChristoph Hellwig     acb->remaining_sectors -= acb->cur_nr_sectors;
5787b88e48bSChristoph Hellwig     acb->sector_num += acb->cur_nr_sectors;
5797b88e48bSChristoph Hellwig     acb->buf += acb->cur_nr_sectors * 512;
580585f8587Sbellard 
5817b88e48bSChristoph Hellwig     if (acb->remaining_sectors == 0) {
582585f8587Sbellard         /* request completed */
583f141eafeSaliguori         ret = 0;
584f141eafeSaliguori         goto done;
585585f8587Sbellard     }
586585f8587Sbellard 
587ce1a14dcSpbrook     index_in_cluster = acb->sector_num & (s->cluster_sectors - 1);
5887b88e48bSChristoph Hellwig     n_end = index_in_cluster + acb->remaining_sectors;
589095a9c58Saliguori     if (s->crypt_method &&
590095a9c58Saliguori         n_end > QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors)
591095a9c58Saliguori         n_end = QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors;
592095a9c58Saliguori 
593148da7eaSKevin Wolf     ret = qcow2_alloc_cluster_offset(bs, acb->sector_num << 9,
5947b88e48bSChristoph Hellwig         index_in_cluster, n_end, &acb->cur_nr_sectors, &acb->l2meta);
595148da7eaSKevin Wolf     if (ret < 0) {
596148da7eaSKevin Wolf         goto done;
597148da7eaSKevin Wolf     }
598148da7eaSKevin Wolf 
599148da7eaSKevin Wolf     acb->cluster_offset = acb->l2meta.cluster_offset;
600f214978aSKevin Wolf 
601f214978aSKevin Wolf     /* Need to wait for another request? If so, we are done for now. */
602148da7eaSKevin Wolf     if (acb->l2meta.nb_clusters == 0 && acb->l2meta.depends_on != NULL) {
60372cf2d4fSBlue Swirl         QLIST_INSERT_HEAD(&acb->l2meta.depends_on->dependent_requests,
604f214978aSKevin Wolf             acb, next_depend);
605f214978aSKevin Wolf         return;
606f214978aSKevin Wolf     }
607f214978aSKevin Wolf 
608148da7eaSKevin Wolf     assert((acb->cluster_offset & 511) == 0);
609148da7eaSKevin Wolf 
610585f8587Sbellard     if (s->crypt_method) {
611ce1a14dcSpbrook         if (!acb->cluster_data) {
612095a9c58Saliguori             acb->cluster_data = qemu_mallocz(QCOW_MAX_CRYPT_CLUSTERS *
613095a9c58Saliguori                                              s->cluster_size);
614585f8587Sbellard         }
615ed6ccf0fSKevin Wolf         qcow2_encrypt_sectors(s, acb->sector_num, acb->cluster_data, acb->buf,
6167b88e48bSChristoph Hellwig                         acb->cur_nr_sectors, 1, &s->aes_encrypt_key);
617ce1a14dcSpbrook         src_buf = acb->cluster_data;
618585f8587Sbellard     } else {
619ce1a14dcSpbrook         src_buf = acb->buf;
620585f8587Sbellard     }
621c87c0672Saliguori     acb->hd_iov.iov_base = (void *)src_buf;
6227b88e48bSChristoph Hellwig     acb->hd_iov.iov_len = acb->cur_nr_sectors * 512;
623c87c0672Saliguori     qemu_iovec_init_external(&acb->hd_qiov, &acb->hd_iov, 1);
6248252278aSKevin Wolf     BLKDBG_EVENT(s->hd, BLKDBG_WRITE_AIO);
625c87c0672Saliguori     acb->hd_aiocb = bdrv_aio_writev(s->hd,
626e976c6a1Saliguori                                     (acb->cluster_offset >> 9) + index_in_cluster,
6277b88e48bSChristoph Hellwig                                     &acb->hd_qiov, acb->cur_nr_sectors,
628585f8587Sbellard                                     qcow_aio_write_cb, acb);
629171e3d6bSKevin Wolf     if (acb->hd_aiocb == NULL) {
630171e3d6bSKevin Wolf         ret = -EIO;
631c644db3dSKevin Wolf         goto fail;
632171e3d6bSKevin Wolf     }
633f141eafeSaliguori 
634f141eafeSaliguori     return;
635f141eafeSaliguori 
636c644db3dSKevin Wolf fail:
637c644db3dSKevin Wolf     if (acb->l2meta.nb_clusters != 0) {
638c644db3dSKevin Wolf         QLIST_REMOVE(&acb->l2meta, next_in_flight);
639c644db3dSKevin Wolf     }
640f141eafeSaliguori done:
641f141eafeSaliguori     if (acb->qiov->niov > 1)
642f141eafeSaliguori         qemu_vfree(acb->orig_buf);
643f141eafeSaliguori     acb->common.cb(acb->common.opaque, ret);
644f141eafeSaliguori     qemu_aio_release(acb);
645585f8587Sbellard }
646585f8587Sbellard 
647f141eafeSaliguori static BlockDriverAIOCB *qcow_aio_writev(BlockDriverState *bs,
648f141eafeSaliguori         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
649ce1a14dcSpbrook         BlockDriverCompletionFunc *cb, void *opaque)
650585f8587Sbellard {
651585f8587Sbellard     BDRVQcowState *s = bs->opaque;
652ce1a14dcSpbrook     QCowAIOCB *acb;
653585f8587Sbellard 
654585f8587Sbellard     s->cluster_cache_offset = -1; /* disable compressed cache */
655585f8587Sbellard 
656f141eafeSaliguori     acb = qcow_aio_setup(bs, sector_num, qiov, nb_sectors, cb, opaque, 1);
657ce1a14dcSpbrook     if (!acb)
658ce1a14dcSpbrook         return NULL;
659585f8587Sbellard 
660585f8587Sbellard     qcow_aio_write_cb(acb, 0);
661ce1a14dcSpbrook     return &acb->common;
662585f8587Sbellard }
663585f8587Sbellard 
664585f8587Sbellard static void qcow_close(BlockDriverState *bs)
665585f8587Sbellard {
666585f8587Sbellard     BDRVQcowState *s = bs->opaque;
667585f8587Sbellard     qemu_free(s->l1_table);
668585f8587Sbellard     qemu_free(s->l2_cache);
669585f8587Sbellard     qemu_free(s->cluster_cache);
670585f8587Sbellard     qemu_free(s->cluster_data);
671ed6ccf0fSKevin Wolf     qcow2_refcount_close(bs);
672585f8587Sbellard     bdrv_delete(s->hd);
673585f8587Sbellard }
674585f8587Sbellard 
675756e6736SKevin Wolf /*
676756e6736SKevin Wolf  * Updates the variable length parts of the qcow2 header, i.e. the backing file
677756e6736SKevin Wolf  * name and all extensions. qcow2 was not designed to allow such changes, so if
678756e6736SKevin Wolf  * we run out of space (we can only use the first cluster) this function may
679756e6736SKevin Wolf  * fail.
680756e6736SKevin Wolf  *
681756e6736SKevin Wolf  * Returns 0 on success, -errno in error cases.
682756e6736SKevin Wolf  */
683756e6736SKevin Wolf static int qcow2_update_ext_header(BlockDriverState *bs,
684756e6736SKevin Wolf     const char *backing_file, const char *backing_fmt)
685756e6736SKevin Wolf {
686756e6736SKevin Wolf     size_t backing_file_len = 0;
687756e6736SKevin Wolf     size_t backing_fmt_len = 0;
688756e6736SKevin Wolf     BDRVQcowState *s = bs->opaque;
689756e6736SKevin Wolf     QCowExtension ext_backing_fmt = {0, 0};
690756e6736SKevin Wolf     int ret;
691756e6736SKevin Wolf 
692756e6736SKevin Wolf     /* Backing file format doesn't make sense without a backing file */
693756e6736SKevin Wolf     if (backing_fmt && !backing_file) {
694756e6736SKevin Wolf         return -EINVAL;
695756e6736SKevin Wolf     }
696756e6736SKevin Wolf 
697756e6736SKevin Wolf     /* Prepare the backing file format extension if needed */
698756e6736SKevin Wolf     if (backing_fmt) {
699756e6736SKevin Wolf         ext_backing_fmt.len = cpu_to_be32(strlen(backing_fmt));
700756e6736SKevin Wolf         ext_backing_fmt.magic = cpu_to_be32(QCOW_EXT_MAGIC_BACKING_FORMAT);
701756e6736SKevin Wolf         backing_fmt_len = ((sizeof(ext_backing_fmt)
702756e6736SKevin Wolf             + strlen(backing_fmt) + 7) & ~7);
703756e6736SKevin Wolf     }
704756e6736SKevin Wolf 
705756e6736SKevin Wolf     /* Check if we can fit the new header into the first cluster */
706756e6736SKevin Wolf     if (backing_file) {
707756e6736SKevin Wolf         backing_file_len = strlen(backing_file);
708756e6736SKevin Wolf     }
709756e6736SKevin Wolf 
710756e6736SKevin Wolf     size_t header_size = sizeof(QCowHeader) + backing_file_len
711756e6736SKevin Wolf         + backing_fmt_len;
712756e6736SKevin Wolf 
713756e6736SKevin Wolf     if (header_size > s->cluster_size) {
714756e6736SKevin Wolf         return -ENOSPC;
715756e6736SKevin Wolf     }
716756e6736SKevin Wolf 
717756e6736SKevin Wolf     /* Rewrite backing file name and qcow2 extensions */
718756e6736SKevin Wolf     size_t ext_size = header_size - sizeof(QCowHeader);
719756e6736SKevin Wolf     uint8_t buf[ext_size];
720756e6736SKevin Wolf     size_t offset = 0;
721756e6736SKevin Wolf     size_t backing_file_offset = 0;
722756e6736SKevin Wolf 
723756e6736SKevin Wolf     if (backing_file) {
724756e6736SKevin Wolf         if (backing_fmt) {
725756e6736SKevin Wolf             int padding = backing_fmt_len -
726756e6736SKevin Wolf                 (sizeof(ext_backing_fmt) + strlen(backing_fmt));
727756e6736SKevin Wolf 
728756e6736SKevin Wolf             memcpy(buf + offset, &ext_backing_fmt, sizeof(ext_backing_fmt));
729756e6736SKevin Wolf             offset += sizeof(ext_backing_fmt);
730756e6736SKevin Wolf 
731756e6736SKevin Wolf             memcpy(buf + offset, backing_fmt, strlen(backing_fmt));
732756e6736SKevin Wolf             offset += strlen(backing_fmt);
733756e6736SKevin Wolf 
734756e6736SKevin Wolf             memset(buf + offset, 0, padding);
735756e6736SKevin Wolf             offset += padding;
736756e6736SKevin Wolf         }
737756e6736SKevin Wolf 
738756e6736SKevin Wolf         memcpy(buf + offset, backing_file, backing_file_len);
739756e6736SKevin Wolf         backing_file_offset = sizeof(QCowHeader) + offset;
740756e6736SKevin Wolf     }
741756e6736SKevin Wolf 
742756e6736SKevin Wolf     ret = bdrv_pwrite(s->hd, sizeof(QCowHeader), buf, ext_size);
743756e6736SKevin Wolf     if (ret < 0) {
744756e6736SKevin Wolf         goto fail;
745756e6736SKevin Wolf     }
746756e6736SKevin Wolf 
747756e6736SKevin Wolf     /* Update header fields */
748756e6736SKevin Wolf     uint64_t be_backing_file_offset = cpu_to_be64(backing_file_offset);
749756e6736SKevin Wolf     uint32_t be_backing_file_size = cpu_to_be32(backing_file_len);
750756e6736SKevin Wolf 
751756e6736SKevin Wolf     ret = bdrv_pwrite(s->hd, offsetof(QCowHeader, backing_file_offset),
752756e6736SKevin Wolf         &be_backing_file_offset, sizeof(uint64_t));
753756e6736SKevin Wolf     if (ret < 0) {
754756e6736SKevin Wolf         goto fail;
755756e6736SKevin Wolf     }
756756e6736SKevin Wolf 
757756e6736SKevin Wolf     ret = bdrv_pwrite(s->hd, offsetof(QCowHeader, backing_file_size),
758756e6736SKevin Wolf         &be_backing_file_size, sizeof(uint32_t));
759756e6736SKevin Wolf     if (ret < 0) {
760756e6736SKevin Wolf         goto fail;
761756e6736SKevin Wolf     }
762756e6736SKevin Wolf 
763756e6736SKevin Wolf     ret = 0;
764756e6736SKevin Wolf fail:
765756e6736SKevin Wolf     return ret;
766756e6736SKevin Wolf }
767756e6736SKevin Wolf 
768756e6736SKevin Wolf static int qcow2_change_backing_file(BlockDriverState *bs,
769756e6736SKevin Wolf     const char *backing_file, const char *backing_fmt)
770756e6736SKevin Wolf {
771756e6736SKevin Wolf     return qcow2_update_ext_header(bs, backing_file, backing_fmt);
772756e6736SKevin Wolf }
773756e6736SKevin Wolf 
77473c632edSKevin Wolf static int get_bits_from_size(size_t size)
77573c632edSKevin Wolf {
77673c632edSKevin Wolf     int res = 0;
77773c632edSKevin Wolf 
77873c632edSKevin Wolf     if (size == 0) {
77973c632edSKevin Wolf         return -1;
78073c632edSKevin Wolf     }
78173c632edSKevin Wolf 
78273c632edSKevin Wolf     while (size != 1) {
78373c632edSKevin Wolf         /* Not a power of two */
78473c632edSKevin Wolf         if (size & 1) {
78573c632edSKevin Wolf             return -1;
78673c632edSKevin Wolf         }
78773c632edSKevin Wolf 
78873c632edSKevin Wolf         size >>= 1;
78973c632edSKevin Wolf         res++;
79073c632edSKevin Wolf     }
79173c632edSKevin Wolf 
79273c632edSKevin Wolf     return res;
79373c632edSKevin Wolf }
79473c632edSKevin Wolf 
795a35e1c17SKevin Wolf 
796a35e1c17SKevin Wolf static int preallocate(BlockDriverState *bs)
797a35e1c17SKevin Wolf {
798a35e1c17SKevin Wolf     BDRVQcowState *s = bs->opaque;
799a35e1c17SKevin Wolf     uint64_t nb_sectors;
800a35e1c17SKevin Wolf     uint64_t offset;
801a35e1c17SKevin Wolf     int num;
802148da7eaSKevin Wolf     int ret;
803a35e1c17SKevin Wolf     QCowL2Meta meta;
804a35e1c17SKevin Wolf 
805a35e1c17SKevin Wolf     nb_sectors = bdrv_getlength(bs) >> 9;
806a35e1c17SKevin Wolf     offset = 0;
80772cf2d4fSBlue Swirl     QLIST_INIT(&meta.dependent_requests);
808148da7eaSKevin Wolf     meta.cluster_offset = 0;
809a35e1c17SKevin Wolf 
810a35e1c17SKevin Wolf     while (nb_sectors) {
811a35e1c17SKevin Wolf         num = MIN(nb_sectors, INT_MAX >> 9);
812148da7eaSKevin Wolf         ret = qcow2_alloc_cluster_offset(bs, offset, 0, num, &num, &meta);
813a35e1c17SKevin Wolf 
814148da7eaSKevin Wolf         if (ret < 0) {
815a35e1c17SKevin Wolf             return -1;
816a35e1c17SKevin Wolf         }
817a35e1c17SKevin Wolf 
818148da7eaSKevin Wolf         if (qcow2_alloc_cluster_link_l2(bs, &meta) < 0) {
819148da7eaSKevin Wolf             qcow2_free_any_clusters(bs, meta.cluster_offset, meta.nb_clusters);
820a35e1c17SKevin Wolf             return -1;
821a35e1c17SKevin Wolf         }
822a35e1c17SKevin Wolf 
823f214978aSKevin Wolf         /* There are no dependent requests, but we need to remove our request
824f214978aSKevin Wolf          * from the list of in-flight requests */
825f214978aSKevin Wolf         run_dependent_requests(&meta);
826f214978aSKevin Wolf 
827a35e1c17SKevin Wolf         /* TODO Preallocate data if requested */
828a35e1c17SKevin Wolf 
829a35e1c17SKevin Wolf         nb_sectors -= num;
830a35e1c17SKevin Wolf         offset += num << 9;
831a35e1c17SKevin Wolf     }
832a35e1c17SKevin Wolf 
833a35e1c17SKevin Wolf     /*
834a35e1c17SKevin Wolf      * It is expected that the image file is large enough to actually contain
835a35e1c17SKevin Wolf      * all of the allocated clusters (otherwise we get failing reads after
836a35e1c17SKevin Wolf      * EOF). Extend the image to the last allocated sector.
837a35e1c17SKevin Wolf      */
838148da7eaSKevin Wolf     if (meta.cluster_offset != 0) {
839ea80b906SKevin Wolf         uint8_t buf[512];
840ea80b906SKevin Wolf         memset(buf, 0, 512);
841148da7eaSKevin Wolf         bdrv_write(s->hd, (meta.cluster_offset >> 9) + num - 1, buf, 1);
842a35e1c17SKevin Wolf     }
843a35e1c17SKevin Wolf 
844a35e1c17SKevin Wolf     return 0;
845a35e1c17SKevin Wolf }
846a35e1c17SKevin Wolf 
847f965509cSaliguori static int qcow_create2(const char *filename, int64_t total_size,
848f965509cSaliguori                         const char *backing_file, const char *backing_format,
849a35e1c17SKevin Wolf                         int flags, size_t cluster_size, int prealloc)
850585f8587Sbellard {
851f965509cSaliguori 
852585f8587Sbellard     int fd, header_size, backing_filename_len, l1_size, i, shift, l2_bits;
8534768fa90SKevin Wolf     int ref_clusters, reftable_clusters, backing_format_len = 0;
854e1c7f0e3SKevin Wolf     int rounded_ext_bf_len = 0;
855585f8587Sbellard     QCowHeader header;
856585f8587Sbellard     uint64_t tmp, offset;
8574768fa90SKevin Wolf     uint64_t old_ref_clusters;
858585f8587Sbellard     QCowCreateState s1, *s = &s1;
859f965509cSaliguori     QCowExtension ext_bf = {0, 0};
860db89119dSKirill A. Shutemov     int ret;
861585f8587Sbellard 
862585f8587Sbellard     memset(s, 0, sizeof(*s));
863585f8587Sbellard 
864585f8587Sbellard     fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0644);
865585f8587Sbellard     if (fd < 0)
866bef57da5SJuan Quintela         return -errno;
867585f8587Sbellard     memset(&header, 0, sizeof(header));
868585f8587Sbellard     header.magic = cpu_to_be32(QCOW_MAGIC);
869585f8587Sbellard     header.version = cpu_to_be32(QCOW_VERSION);
870585f8587Sbellard     header.size = cpu_to_be64(total_size * 512);
871585f8587Sbellard     header_size = sizeof(header);
872585f8587Sbellard     backing_filename_len = 0;
873585f8587Sbellard     if (backing_file) {
874f965509cSaliguori         if (backing_format) {
875f965509cSaliguori             ext_bf.magic = QCOW_EXT_MAGIC_BACKING_FORMAT;
876f965509cSaliguori             backing_format_len = strlen(backing_format);
877e1c7f0e3SKevin Wolf             ext_bf.len = backing_format_len;
878e1c7f0e3SKevin Wolf             rounded_ext_bf_len = (sizeof(ext_bf) + ext_bf.len + 7) & ~7;
879e1c7f0e3SKevin Wolf             header_size += rounded_ext_bf_len;
880f965509cSaliguori         }
881585f8587Sbellard         header.backing_file_offset = cpu_to_be64(header_size);
882585f8587Sbellard         backing_filename_len = strlen(backing_file);
883585f8587Sbellard         header.backing_file_size = cpu_to_be32(backing_filename_len);
884585f8587Sbellard         header_size += backing_filename_len;
885585f8587Sbellard     }
88673c632edSKevin Wolf 
88773c632edSKevin Wolf     /* Cluster size */
88873c632edSKevin Wolf     s->cluster_bits = get_bits_from_size(cluster_size);
88973c632edSKevin Wolf     if (s->cluster_bits < MIN_CLUSTER_BITS ||
89073c632edSKevin Wolf         s->cluster_bits > MAX_CLUSTER_BITS)
89173c632edSKevin Wolf     {
89273c632edSKevin Wolf         fprintf(stderr, "Cluster size must be a power of two between "
89373c632edSKevin Wolf             "%d and %dk\n",
89473c632edSKevin Wolf             1 << MIN_CLUSTER_BITS,
89573c632edSKevin Wolf             1 << (MAX_CLUSTER_BITS - 10));
89673c632edSKevin Wolf         return -EINVAL;
89773c632edSKevin Wolf     }
898585f8587Sbellard     s->cluster_size = 1 << s->cluster_bits;
89973c632edSKevin Wolf 
900585f8587Sbellard     header.cluster_bits = cpu_to_be32(s->cluster_bits);
901585f8587Sbellard     header_size = (header_size + 7) & ~7;
902ec36ba14Sths     if (flags & BLOCK_FLAG_ENCRYPT) {
903585f8587Sbellard         header.crypt_method = cpu_to_be32(QCOW_CRYPT_AES);
904585f8587Sbellard     } else {
905585f8587Sbellard         header.crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
906585f8587Sbellard     }
907585f8587Sbellard     l2_bits = s->cluster_bits - 3;
908585f8587Sbellard     shift = s->cluster_bits + l2_bits;
909585f8587Sbellard     l1_size = (((total_size * 512) + (1LL << shift) - 1) >> shift);
910585f8587Sbellard     offset = align_offset(header_size, s->cluster_size);
911585f8587Sbellard     s->l1_table_offset = offset;
912585f8587Sbellard     header.l1_table_offset = cpu_to_be64(s->l1_table_offset);
913585f8587Sbellard     header.l1_size = cpu_to_be32(l1_size);
91415e6690aSbellard     offset += align_offset(l1_size * sizeof(uint64_t), s->cluster_size);
915585f8587Sbellard 
9164768fa90SKevin Wolf     /* count how many refcount blocks needed */
9174768fa90SKevin Wolf 
9184768fa90SKevin Wolf #define NUM_CLUSTERS(bytes) \
9194768fa90SKevin Wolf     (((bytes) + (s->cluster_size) - 1) / (s->cluster_size))
9204768fa90SKevin Wolf 
9214768fa90SKevin Wolf     ref_clusters = NUM_CLUSTERS(NUM_CLUSTERS(offset) * sizeof(uint16_t));
9224768fa90SKevin Wolf 
9234768fa90SKevin Wolf     do {
9244768fa90SKevin Wolf         uint64_t image_clusters;
9254768fa90SKevin Wolf         old_ref_clusters = ref_clusters;
9264768fa90SKevin Wolf 
9274768fa90SKevin Wolf         /* Number of clusters used for the refcount table */
9284768fa90SKevin Wolf         reftable_clusters = NUM_CLUSTERS(ref_clusters * sizeof(uint64_t));
9294768fa90SKevin Wolf 
9304768fa90SKevin Wolf         /* Number of clusters that the whole image will have */
9314768fa90SKevin Wolf         image_clusters = NUM_CLUSTERS(offset) + ref_clusters
9324768fa90SKevin Wolf             + reftable_clusters;
9334768fa90SKevin Wolf 
9344768fa90SKevin Wolf         /* Number of refcount blocks needed for the image */
9354768fa90SKevin Wolf         ref_clusters = NUM_CLUSTERS(image_clusters * sizeof(uint16_t));
9364768fa90SKevin Wolf 
9374768fa90SKevin Wolf     } while (ref_clusters != old_ref_clusters);
9384768fa90SKevin Wolf 
9394768fa90SKevin Wolf     s->refcount_table = qemu_mallocz(reftable_clusters * s->cluster_size);
940585f8587Sbellard 
941585f8587Sbellard     s->refcount_table_offset = offset;
942585f8587Sbellard     header.refcount_table_offset = cpu_to_be64(offset);
9434768fa90SKevin Wolf     header.refcount_table_clusters = cpu_to_be32(reftable_clusters);
9444768fa90SKevin Wolf     offset += (reftable_clusters * s->cluster_size);
945585f8587Sbellard     s->refcount_block_offset = offset;
9462d2431f0Saliguori 
9472d2431f0Saliguori     for (i=0; i < ref_clusters; i++) {
9482d2431f0Saliguori         s->refcount_table[i] = cpu_to_be64(offset);
949585f8587Sbellard         offset += s->cluster_size;
9502d2431f0Saliguori     }
9512d2431f0Saliguori 
9522d2431f0Saliguori     s->refcount_block = qemu_mallocz(ref_clusters * s->cluster_size);
953585f8587Sbellard 
954585f8587Sbellard     /* update refcounts */
955ed6ccf0fSKevin Wolf     qcow2_create_refcount_update(s, 0, header_size);
956ed6ccf0fSKevin Wolf     qcow2_create_refcount_update(s, s->l1_table_offset,
957ed6ccf0fSKevin Wolf         l1_size * sizeof(uint64_t));
9584768fa90SKevin Wolf     qcow2_create_refcount_update(s, s->refcount_table_offset,
9594768fa90SKevin Wolf         reftable_clusters * s->cluster_size);
960ed6ccf0fSKevin Wolf     qcow2_create_refcount_update(s, s->refcount_block_offset,
961ed6ccf0fSKevin Wolf         ref_clusters * s->cluster_size);
962585f8587Sbellard 
963585f8587Sbellard     /* write all the data */
964db89119dSKirill A. Shutemov     ret = qemu_write_full(fd, &header, sizeof(header));
965db89119dSKirill A. Shutemov     if (ret != sizeof(header)) {
966bef57da5SJuan Quintela         ret = -errno;
967db89119dSKirill A. Shutemov         goto exit;
968db89119dSKirill A. Shutemov     }
969585f8587Sbellard     if (backing_file) {
970f965509cSaliguori         if (backing_format_len) {
971f965509cSaliguori             char zero[16];
972e1c7f0e3SKevin Wolf             int padding = rounded_ext_bf_len - (ext_bf.len + sizeof(ext_bf));
973f965509cSaliguori 
974f965509cSaliguori             memset(zero, 0, sizeof(zero));
975f965509cSaliguori             cpu_to_be32s(&ext_bf.magic);
976f965509cSaliguori             cpu_to_be32s(&ext_bf.len);
977db89119dSKirill A. Shutemov             ret = qemu_write_full(fd, &ext_bf, sizeof(ext_bf));
978db89119dSKirill A. Shutemov             if (ret != sizeof(ext_bf)) {
979bef57da5SJuan Quintela                 ret = -errno;
980db89119dSKirill A. Shutemov                 goto exit;
981db89119dSKirill A. Shutemov             }
982db89119dSKirill A. Shutemov             ret = qemu_write_full(fd, backing_format, backing_format_len);
983db89119dSKirill A. Shutemov             if (ret != backing_format_len) {
984bef57da5SJuan Quintela                 ret = -errno;
985db89119dSKirill A. Shutemov                 goto exit;
986db89119dSKirill A. Shutemov             }
987e1c7f0e3SKevin Wolf             if (padding > 0) {
988db89119dSKirill A. Shutemov                 ret = qemu_write_full(fd, zero, padding);
989db89119dSKirill A. Shutemov                 if (ret != padding) {
990bef57da5SJuan Quintela                     ret = -errno;
991db89119dSKirill A. Shutemov                     goto exit;
992f965509cSaliguori                 }
993f965509cSaliguori             }
994db89119dSKirill A. Shutemov         }
995db89119dSKirill A. Shutemov         ret = qemu_write_full(fd, backing_file, backing_filename_len);
996db89119dSKirill A. Shutemov         if (ret != backing_filename_len) {
997bef57da5SJuan Quintela             ret = -errno;
998db89119dSKirill A. Shutemov             goto exit;
999db89119dSKirill A. Shutemov         }
1000585f8587Sbellard     }
1001585f8587Sbellard     lseek(fd, s->l1_table_offset, SEEK_SET);
1002585f8587Sbellard     tmp = 0;
1003585f8587Sbellard     for(i = 0;i < l1_size; i++) {
1004db89119dSKirill A. Shutemov         ret = qemu_write_full(fd, &tmp, sizeof(tmp));
1005db89119dSKirill A. Shutemov         if (ret != sizeof(tmp)) {
1006bef57da5SJuan Quintela             ret = -errno;
1007db89119dSKirill A. Shutemov             goto exit;
1008db89119dSKirill A. Shutemov         }
1009585f8587Sbellard     }
1010585f8587Sbellard     lseek(fd, s->refcount_table_offset, SEEK_SET);
10114768fa90SKevin Wolf     ret = qemu_write_full(fd, s->refcount_table,
10124768fa90SKevin Wolf         reftable_clusters * s->cluster_size);
10134768fa90SKevin Wolf     if (ret != reftable_clusters * s->cluster_size) {
1014bef57da5SJuan Quintela         ret = -errno;
1015db89119dSKirill A. Shutemov         goto exit;
1016db89119dSKirill A. Shutemov     }
1017585f8587Sbellard 
1018585f8587Sbellard     lseek(fd, s->refcount_block_offset, SEEK_SET);
1019db89119dSKirill A. Shutemov     ret = qemu_write_full(fd, s->refcount_block,
1020db89119dSKirill A. Shutemov 		    ref_clusters * s->cluster_size);
10216f745bdaSKevin Wolf     if (ret != ref_clusters * s->cluster_size) {
1022bef57da5SJuan Quintela         ret = -errno;
1023db89119dSKirill A. Shutemov         goto exit;
1024db89119dSKirill A. Shutemov     }
1025585f8587Sbellard 
1026db89119dSKirill A. Shutemov     ret = 0;
1027db89119dSKirill A. Shutemov exit:
1028585f8587Sbellard     qemu_free(s->refcount_table);
1029585f8587Sbellard     qemu_free(s->refcount_block);
1030585f8587Sbellard     close(fd);
1031a35e1c17SKevin Wolf 
1032a35e1c17SKevin Wolf     /* Preallocate metadata */
10336f745bdaSKevin Wolf     if (ret == 0 && prealloc) {
1034a35e1c17SKevin Wolf         BlockDriverState *bs;
1035a35e1c17SKevin Wolf         bs = bdrv_new("");
1036*d6e9098eSKevin Wolf         bdrv_open(bs, filename, BDRV_O_CACHE_WB | BDRV_O_RDWR, &bdrv_qcow2);
1037a35e1c17SKevin Wolf         preallocate(bs);
1038a35e1c17SKevin Wolf         bdrv_close(bs);
1039a35e1c17SKevin Wolf     }
1040a35e1c17SKevin Wolf 
1041db89119dSKirill A. Shutemov     return ret;
1042585f8587Sbellard }
1043585f8587Sbellard 
10440e7e1989SKevin Wolf static int qcow_create(const char *filename, QEMUOptionParameter *options)
1045f965509cSaliguori {
10460e7e1989SKevin Wolf     const char *backing_file = NULL;
10470e7e1989SKevin Wolf     const char *backing_fmt = NULL;
10480e7e1989SKevin Wolf     uint64_t sectors = 0;
10490e7e1989SKevin Wolf     int flags = 0;
10509ccb258eSKevin Wolf     size_t cluster_size = 65536;
1051a35e1c17SKevin Wolf     int prealloc = 0;
10520e7e1989SKevin Wolf 
10530e7e1989SKevin Wolf     /* Read out options */
10540e7e1989SKevin Wolf     while (options && options->name) {
10550e7e1989SKevin Wolf         if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
10560e7e1989SKevin Wolf             sectors = options->value.n / 512;
10570e7e1989SKevin Wolf         } else if (!strcmp(options->name, BLOCK_OPT_BACKING_FILE)) {
10580e7e1989SKevin Wolf             backing_file = options->value.s;
10590e7e1989SKevin Wolf         } else if (!strcmp(options->name, BLOCK_OPT_BACKING_FMT)) {
10600e7e1989SKevin Wolf             backing_fmt = options->value.s;
10610e7e1989SKevin Wolf         } else if (!strcmp(options->name, BLOCK_OPT_ENCRYPT)) {
10620e7e1989SKevin Wolf             flags |= options->value.n ? BLOCK_FLAG_ENCRYPT : 0;
106373c632edSKevin Wolf         } else if (!strcmp(options->name, BLOCK_OPT_CLUSTER_SIZE)) {
106473c632edSKevin Wolf             if (options->value.n) {
106573c632edSKevin Wolf                 cluster_size = options->value.n;
106673c632edSKevin Wolf             }
1067a35e1c17SKevin Wolf         } else if (!strcmp(options->name, BLOCK_OPT_PREALLOC)) {
1068a35e1c17SKevin Wolf             if (!options->value.s || !strcmp(options->value.s, "off")) {
1069a35e1c17SKevin Wolf                 prealloc = 0;
1070a35e1c17SKevin Wolf             } else if (!strcmp(options->value.s, "metadata")) {
1071a35e1c17SKevin Wolf                 prealloc = 1;
1072a35e1c17SKevin Wolf             } else {
1073a35e1c17SKevin Wolf                 fprintf(stderr, "Invalid preallocation mode: '%s'\n",
1074a35e1c17SKevin Wolf                     options->value.s);
1075a35e1c17SKevin Wolf                 return -EINVAL;
1076a35e1c17SKevin Wolf             }
10770e7e1989SKevin Wolf         }
10780e7e1989SKevin Wolf         options++;
10790e7e1989SKevin Wolf     }
10800e7e1989SKevin Wolf 
1081a35e1c17SKevin Wolf     if (backing_file && prealloc) {
1082a35e1c17SKevin Wolf         fprintf(stderr, "Backing file and preallocation cannot be used at "
1083a35e1c17SKevin Wolf             "the same time\n");
1084a35e1c17SKevin Wolf         return -EINVAL;
1085a35e1c17SKevin Wolf     }
1086a35e1c17SKevin Wolf 
108773c632edSKevin Wolf     return qcow_create2(filename, sectors, backing_file, backing_fmt, flags,
1088a35e1c17SKevin Wolf         cluster_size, prealloc);
1089f965509cSaliguori }
1090f965509cSaliguori 
1091585f8587Sbellard static int qcow_make_empty(BlockDriverState *bs)
1092585f8587Sbellard {
1093585f8587Sbellard #if 0
1094585f8587Sbellard     /* XXX: not correct */
1095585f8587Sbellard     BDRVQcowState *s = bs->opaque;
1096585f8587Sbellard     uint32_t l1_length = s->l1_size * sizeof(uint64_t);
1097585f8587Sbellard     int ret;
1098585f8587Sbellard 
1099585f8587Sbellard     memset(s->l1_table, 0, l1_length);
1100585f8587Sbellard     if (bdrv_pwrite(s->hd, s->l1_table_offset, s->l1_table, l1_length) < 0)
1101585f8587Sbellard         return -1;
1102585f8587Sbellard     ret = bdrv_truncate(s->hd, s->l1_table_offset + l1_length);
1103585f8587Sbellard     if (ret < 0)
1104585f8587Sbellard         return ret;
1105585f8587Sbellard 
1106585f8587Sbellard     l2_cache_reset(bs);
1107585f8587Sbellard #endif
1108585f8587Sbellard     return 0;
1109585f8587Sbellard }
1110585f8587Sbellard 
1111585f8587Sbellard /* XXX: put compressed sectors first, then all the cluster aligned
1112585f8587Sbellard    tables to avoid losing bytes in alignment */
1113585f8587Sbellard static int qcow_write_compressed(BlockDriverState *bs, int64_t sector_num,
1114585f8587Sbellard                                  const uint8_t *buf, int nb_sectors)
1115585f8587Sbellard {
1116585f8587Sbellard     BDRVQcowState *s = bs->opaque;
1117585f8587Sbellard     z_stream strm;
1118585f8587Sbellard     int ret, out_len;
1119585f8587Sbellard     uint8_t *out_buf;
1120585f8587Sbellard     uint64_t cluster_offset;
1121585f8587Sbellard 
1122585f8587Sbellard     if (nb_sectors == 0) {
1123585f8587Sbellard         /* align end of file to a sector boundary to ease reading with
1124585f8587Sbellard            sector based I/Os */
1125585f8587Sbellard         cluster_offset = bdrv_getlength(s->hd);
1126585f8587Sbellard         cluster_offset = (cluster_offset + 511) & ~511;
1127585f8587Sbellard         bdrv_truncate(s->hd, cluster_offset);
1128585f8587Sbellard         return 0;
1129585f8587Sbellard     }
1130585f8587Sbellard 
1131585f8587Sbellard     if (nb_sectors != s->cluster_sectors)
1132585f8587Sbellard         return -EINVAL;
1133585f8587Sbellard 
1134585f8587Sbellard     out_buf = qemu_malloc(s->cluster_size + (s->cluster_size / 1000) + 128);
1135585f8587Sbellard 
1136585f8587Sbellard     /* best compression, small window, no zlib header */
1137585f8587Sbellard     memset(&strm, 0, sizeof(strm));
1138585f8587Sbellard     ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
1139585f8587Sbellard                        Z_DEFLATED, -12,
1140585f8587Sbellard                        9, Z_DEFAULT_STRATEGY);
1141585f8587Sbellard     if (ret != 0) {
1142585f8587Sbellard         qemu_free(out_buf);
1143585f8587Sbellard         return -1;
1144585f8587Sbellard     }
1145585f8587Sbellard 
1146585f8587Sbellard     strm.avail_in = s->cluster_size;
1147585f8587Sbellard     strm.next_in = (uint8_t *)buf;
1148585f8587Sbellard     strm.avail_out = s->cluster_size;
1149585f8587Sbellard     strm.next_out = out_buf;
1150585f8587Sbellard 
1151585f8587Sbellard     ret = deflate(&strm, Z_FINISH);
1152585f8587Sbellard     if (ret != Z_STREAM_END && ret != Z_OK) {
1153585f8587Sbellard         qemu_free(out_buf);
1154585f8587Sbellard         deflateEnd(&strm);
1155585f8587Sbellard         return -1;
1156585f8587Sbellard     }
1157585f8587Sbellard     out_len = strm.next_out - out_buf;
1158585f8587Sbellard 
1159585f8587Sbellard     deflateEnd(&strm);
1160585f8587Sbellard 
1161585f8587Sbellard     if (ret != Z_STREAM_END || out_len >= s->cluster_size) {
1162585f8587Sbellard         /* could not compress: write normal cluster */
1163ade40677SKevin Wolf         bdrv_write(bs, sector_num, buf, s->cluster_sectors);
1164585f8587Sbellard     } else {
1165ed6ccf0fSKevin Wolf         cluster_offset = qcow2_alloc_compressed_cluster_offset(bs,
1166ed6ccf0fSKevin Wolf             sector_num << 9, out_len);
116752d893ecSaliguori         if (!cluster_offset)
116852d893ecSaliguori             return -1;
1169585f8587Sbellard         cluster_offset &= s->cluster_offset_mask;
11708252278aSKevin Wolf         BLKDBG_EVENT(s->hd, BLKDBG_WRITE_COMPRESSED);
1171585f8587Sbellard         if (bdrv_pwrite(s->hd, cluster_offset, out_buf, out_len) != out_len) {
1172585f8587Sbellard             qemu_free(out_buf);
1173585f8587Sbellard             return -1;
1174585f8587Sbellard         }
1175585f8587Sbellard     }
1176585f8587Sbellard 
1177585f8587Sbellard     qemu_free(out_buf);
1178585f8587Sbellard     return 0;
1179585f8587Sbellard }
1180585f8587Sbellard 
1181585f8587Sbellard static void qcow_flush(BlockDriverState *bs)
1182585f8587Sbellard {
1183585f8587Sbellard     BDRVQcowState *s = bs->opaque;
1184585f8587Sbellard     bdrv_flush(s->hd);
1185585f8587Sbellard }
1186585f8587Sbellard 
1187f8012c13SKevin Wolf static BlockDriverAIOCB *qcow_aio_flush(BlockDriverState *bs,
1188f8012c13SKevin Wolf          BlockDriverCompletionFunc *cb, void *opaque)
1189f8012c13SKevin Wolf {
1190f8012c13SKevin Wolf      BDRVQcowState *s = bs->opaque;
1191f8012c13SKevin Wolf 
1192f8012c13SKevin Wolf      return bdrv_aio_flush(s->hd, cb, opaque);
1193f8012c13SKevin Wolf }
1194f8012c13SKevin Wolf 
119545566e9cSChristoph Hellwig static int64_t qcow_vm_state_offset(BDRVQcowState *s)
119645566e9cSChristoph Hellwig {
119745566e9cSChristoph Hellwig 	return (int64_t)s->l1_vm_state_index << (s->cluster_bits + s->l2_bits);
119845566e9cSChristoph Hellwig }
119945566e9cSChristoph Hellwig 
1200585f8587Sbellard static int qcow_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1201585f8587Sbellard {
1202585f8587Sbellard     BDRVQcowState *s = bs->opaque;
1203585f8587Sbellard     bdi->cluster_size = s->cluster_size;
120445566e9cSChristoph Hellwig     bdi->vm_state_offset = qcow_vm_state_offset(s);
1205585f8587Sbellard     return 0;
1206585f8587Sbellard }
1207585f8587Sbellard 
1208585f8587Sbellard 
1209e97fc193Saliguori static int qcow_check(BlockDriverState *bs)
1210e97fc193Saliguori {
1211ed6ccf0fSKevin Wolf     return qcow2_check_refcounts(bs);
1212585f8587Sbellard }
1213585f8587Sbellard 
1214585f8587Sbellard #if 0
1215585f8587Sbellard static void dump_refcounts(BlockDriverState *bs)
1216585f8587Sbellard {
1217585f8587Sbellard     BDRVQcowState *s = bs->opaque;
1218585f8587Sbellard     int64_t nb_clusters, k, k1, size;
1219585f8587Sbellard     int refcount;
1220585f8587Sbellard 
1221585f8587Sbellard     size = bdrv_getlength(s->hd);
12226db6c638Saliguori     nb_clusters = size_to_clusters(s, size);
1223585f8587Sbellard     for(k = 0; k < nb_clusters;) {
1224585f8587Sbellard         k1 = k;
1225585f8587Sbellard         refcount = get_refcount(bs, k);
1226585f8587Sbellard         k++;
1227585f8587Sbellard         while (k < nb_clusters && get_refcount(bs, k) == refcount)
1228585f8587Sbellard             k++;
1229585f8587Sbellard         printf("%lld: refcount=%d nb=%lld\n", k, refcount, k - k1);
1230585f8587Sbellard     }
1231585f8587Sbellard }
1232585f8587Sbellard #endif
1233585f8587Sbellard 
123445566e9cSChristoph Hellwig static int qcow_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
1235178e08a5Saliguori                            int64_t pos, int size)
1236178e08a5Saliguori {
123745566e9cSChristoph Hellwig     BDRVQcowState *s = bs->opaque;
1238178e08a5Saliguori     int growable = bs->growable;
12391d36e3aaSKevin Wolf     int ret;
1240178e08a5Saliguori 
12418252278aSKevin Wolf     BLKDBG_EVENT(s->hd, BLKDBG_VMSTATE_SAVE);
1242178e08a5Saliguori     bs->growable = 1;
12431d36e3aaSKevin Wolf     ret = bdrv_pwrite(bs, qcow_vm_state_offset(s) + pos, buf, size);
1244178e08a5Saliguori     bs->growable = growable;
1245178e08a5Saliguori 
12461d36e3aaSKevin Wolf     return ret;
1247178e08a5Saliguori }
1248178e08a5Saliguori 
124945566e9cSChristoph Hellwig static int qcow_load_vmstate(BlockDriverState *bs, uint8_t *buf,
1250178e08a5Saliguori                            int64_t pos, int size)
1251178e08a5Saliguori {
125245566e9cSChristoph Hellwig     BDRVQcowState *s = bs->opaque;
1253178e08a5Saliguori     int growable = bs->growable;
1254178e08a5Saliguori     int ret;
1255178e08a5Saliguori 
12568252278aSKevin Wolf     BLKDBG_EVENT(s->hd, BLKDBG_VMSTATE_LOAD);
1257178e08a5Saliguori     bs->growable = 1;
125845566e9cSChristoph Hellwig     ret = bdrv_pread(bs, qcow_vm_state_offset(s) + pos, buf, size);
1259178e08a5Saliguori     bs->growable = growable;
1260178e08a5Saliguori 
1261178e08a5Saliguori     return ret;
1262178e08a5Saliguori }
1263178e08a5Saliguori 
12640e7e1989SKevin Wolf static QEMUOptionParameter qcow_create_options[] = {
1265db08adf5SKevin Wolf     {
1266db08adf5SKevin Wolf         .name = BLOCK_OPT_SIZE,
1267db08adf5SKevin Wolf         .type = OPT_SIZE,
1268db08adf5SKevin Wolf         .help = "Virtual disk size"
1269db08adf5SKevin Wolf     },
1270db08adf5SKevin Wolf     {
1271db08adf5SKevin Wolf         .name = BLOCK_OPT_BACKING_FILE,
1272db08adf5SKevin Wolf         .type = OPT_STRING,
1273db08adf5SKevin Wolf         .help = "File name of a base image"
1274db08adf5SKevin Wolf     },
1275db08adf5SKevin Wolf     {
1276db08adf5SKevin Wolf         .name = BLOCK_OPT_BACKING_FMT,
1277db08adf5SKevin Wolf         .type = OPT_STRING,
1278db08adf5SKevin Wolf         .help = "Image format of the base image"
1279db08adf5SKevin Wolf     },
1280db08adf5SKevin Wolf     {
1281db08adf5SKevin Wolf         .name = BLOCK_OPT_ENCRYPT,
1282db08adf5SKevin Wolf         .type = OPT_FLAG,
1283db08adf5SKevin Wolf         .help = "Encrypt the image"
1284db08adf5SKevin Wolf     },
1285db08adf5SKevin Wolf     {
1286db08adf5SKevin Wolf         .name = BLOCK_OPT_CLUSTER_SIZE,
1287db08adf5SKevin Wolf         .type = OPT_SIZE,
1288db08adf5SKevin Wolf         .help = "qcow2 cluster size"
1289db08adf5SKevin Wolf     },
1290a35e1c17SKevin Wolf     {
1291a35e1c17SKevin Wolf         .name = BLOCK_OPT_PREALLOC,
1292a35e1c17SKevin Wolf         .type = OPT_STRING,
1293a35e1c17SKevin Wolf         .help = "Preallocation mode (allowed values: off, metadata)"
1294a35e1c17SKevin Wolf     },
12950e7e1989SKevin Wolf     { NULL }
12960e7e1989SKevin Wolf };
12970e7e1989SKevin Wolf 
12985efa9d5aSAnthony Liguori static BlockDriver bdrv_qcow2 = {
1299e60f469cSaurel32     .format_name	= "qcow2",
1300e60f469cSaurel32     .instance_size	= sizeof(BDRVQcowState),
1301e60f469cSaurel32     .bdrv_probe		= qcow_probe,
1302e60f469cSaurel32     .bdrv_open		= qcow_open,
1303e60f469cSaurel32     .bdrv_close		= qcow_close,
1304e60f469cSaurel32     .bdrv_create	= qcow_create,
1305e60f469cSaurel32     .bdrv_flush		= qcow_flush,
1306e60f469cSaurel32     .bdrv_is_allocated	= qcow_is_allocated,
1307e60f469cSaurel32     .bdrv_set_key	= qcow_set_key,
1308e60f469cSaurel32     .bdrv_make_empty	= qcow_make_empty,
1309585f8587Sbellard 
1310f141eafeSaliguori     .bdrv_aio_readv	= qcow_aio_readv,
1311f141eafeSaliguori     .bdrv_aio_writev	= qcow_aio_writev,
1312f8012c13SKevin Wolf     .bdrv_aio_flush	= qcow_aio_flush,
1313585f8587Sbellard     .bdrv_write_compressed = qcow_write_compressed,
1314585f8587Sbellard 
1315ed6ccf0fSKevin Wolf     .bdrv_snapshot_create   = qcow2_snapshot_create,
1316ed6ccf0fSKevin Wolf     .bdrv_snapshot_goto     = qcow2_snapshot_goto,
1317ed6ccf0fSKevin Wolf     .bdrv_snapshot_delete   = qcow2_snapshot_delete,
1318ed6ccf0fSKevin Wolf     .bdrv_snapshot_list     = qcow2_snapshot_list,
1319585f8587Sbellard     .bdrv_get_info	= qcow_get_info,
1320f965509cSaliguori 
132145566e9cSChristoph Hellwig     .bdrv_save_vmstate    = qcow_save_vmstate,
132245566e9cSChristoph Hellwig     .bdrv_load_vmstate    = qcow_load_vmstate,
1323178e08a5Saliguori 
1324756e6736SKevin Wolf     .bdrv_change_backing_file   = qcow2_change_backing_file,
1325756e6736SKevin Wolf 
13260e7e1989SKevin Wolf     .create_options = qcow_create_options,
1327e97fc193Saliguori     .bdrv_check = qcow_check,
1328585f8587Sbellard };
13295efa9d5aSAnthony Liguori 
13305efa9d5aSAnthony Liguori static void bdrv_qcow2_init(void)
13315efa9d5aSAnthony Liguori {
13325efa9d5aSAnthony Liguori     bdrv_register(&bdrv_qcow2);
13335efa9d5aSAnthony Liguori }
13345efa9d5aSAnthony Liguori 
13355efa9d5aSAnthony Liguori block_init(bdrv_qcow2_init);
1336