Statistics
| Branch: | Revision:

root / block / qcow2.c @ 0a7fc983

History | View | Annotate | Download (37.9 kB)

1 585f8587 bellard
/*
2 585f8587 bellard
 * Block driver for the QCOW version 2 format
3 5fafdf24 ths
 *
4 585f8587 bellard
 * Copyright (c) 2004-2006 Fabrice Bellard
5 5fafdf24 ths
 *
6 585f8587 bellard
 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 585f8587 bellard
 * of this software and associated documentation files (the "Software"), to deal
8 585f8587 bellard
 * in the Software without restriction, including without limitation the rights
9 585f8587 bellard
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 585f8587 bellard
 * copies of the Software, and to permit persons to whom the Software is
11 585f8587 bellard
 * furnished to do so, subject to the following conditions:
12 585f8587 bellard
 *
13 585f8587 bellard
 * The above copyright notice and this permission notice shall be included in
14 585f8587 bellard
 * all copies or substantial portions of the Software.
15 585f8587 bellard
 *
16 585f8587 bellard
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 585f8587 bellard
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 585f8587 bellard
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 585f8587 bellard
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 585f8587 bellard
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 585f8587 bellard
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 585f8587 bellard
 * THE SOFTWARE.
23 585f8587 bellard
 */
24 faf07963 pbrook
#include "qemu-common.h"
25 585f8587 bellard
#include "block_int.h"
26 5efa9d5a Anthony Liguori
#include "module.h"
27 585f8587 bellard
#include <zlib.h>
28 585f8587 bellard
#include "aes.h"
29 f7d0fe02 Kevin Wolf
#include "block/qcow2.h"
30 585f8587 bellard
31 585f8587 bellard
/*
32 585f8587 bellard
  Differences with QCOW:
33 585f8587 bellard

34 585f8587 bellard
  - Support for multiple incremental snapshots.
35 585f8587 bellard
  - Memory management by reference counts.
36 585f8587 bellard
  - Clusters which have a reference count of one have the bit
37 585f8587 bellard
    QCOW_OFLAG_COPIED to optimize write performance.
38 5fafdf24 ths
  - Size of compressed clusters is stored in sectors to reduce bit usage
39 585f8587 bellard
    in the cluster offsets.
40 585f8587 bellard
  - Support for storing additional data (such as the VM state) in the
41 3b46e624 ths
    snapshots.
42 585f8587 bellard
  - If a backing store is used, the cluster size is not constrained
43 585f8587 bellard
    (could be backported to QCOW).
44 585f8587 bellard
  - L2 tables have always a size of one cluster.
45 585f8587 bellard
*/
46 585f8587 bellard
47 9b80ddf3 aliguori
48 9b80ddf3 aliguori
typedef struct {
49 9b80ddf3 aliguori
    uint32_t magic;
50 9b80ddf3 aliguori
    uint32_t len;
51 9b80ddf3 aliguori
} QCowExtension;
52 9b80ddf3 aliguori
#define  QCOW_EXT_MAGIC_END 0
53 f965509c aliguori
#define  QCOW_EXT_MAGIC_BACKING_FORMAT 0xE2792ACA
54 9b80ddf3 aliguori
55 9b80ddf3 aliguori
56 585f8587 bellard
57 585f8587 bellard
static int qcow_probe(const uint8_t *buf, int buf_size, const char *filename)
58 585f8587 bellard
{
59 585f8587 bellard
    const QCowHeader *cow_header = (const void *)buf;
60 3b46e624 ths
61 585f8587 bellard
    if (buf_size >= sizeof(QCowHeader) &&
62 585f8587 bellard
        be32_to_cpu(cow_header->magic) == QCOW_MAGIC &&
63 5fafdf24 ths
        be32_to_cpu(cow_header->version) == QCOW_VERSION)
64 585f8587 bellard
        return 100;
65 585f8587 bellard
    else
66 585f8587 bellard
        return 0;
67 585f8587 bellard
}
68 585f8587 bellard
69 9b80ddf3 aliguori
70 9b80ddf3 aliguori
/* 
71 9b80ddf3 aliguori
 * read qcow2 extension and fill bs
72 9b80ddf3 aliguori
 * start reading from start_offset
73 9b80ddf3 aliguori
 * finish reading upon magic of value 0 or when end_offset reached
74 9b80ddf3 aliguori
 * unknown magic is skipped (future extension this version knows nothing about)
75 9b80ddf3 aliguori
 * return 0 upon success, non-0 otherwise
76 9b80ddf3 aliguori
 */
77 9b80ddf3 aliguori
static int qcow_read_extensions(BlockDriverState *bs, uint64_t start_offset,
78 9b80ddf3 aliguori
                                uint64_t end_offset)
79 9b80ddf3 aliguori
{
80 9b80ddf3 aliguori
    BDRVQcowState *s = bs->opaque;
81 9b80ddf3 aliguori
    QCowExtension ext;
82 9b80ddf3 aliguori
    uint64_t offset;
83 9b80ddf3 aliguori
84 9b80ddf3 aliguori
#ifdef DEBUG_EXT
85 9b80ddf3 aliguori
    printf("qcow_read_extensions: start=%ld end=%ld\n", start_offset, end_offset);
86 9b80ddf3 aliguori
#endif
87 9b80ddf3 aliguori
    offset = start_offset;
88 9b80ddf3 aliguori
    while (offset < end_offset) {
89 9b80ddf3 aliguori
90 9b80ddf3 aliguori
#ifdef DEBUG_EXT
91 9b80ddf3 aliguori
        /* Sanity check */
92 9b80ddf3 aliguori
        if (offset > s->cluster_size)
93 9b80ddf3 aliguori
            printf("qcow_handle_extension: suspicious offset %lu\n", offset);
94 9b80ddf3 aliguori
95 9b80ddf3 aliguori
        printf("attemting to read extended header in offset %lu\n", offset);
96 9b80ddf3 aliguori
#endif
97 9b80ddf3 aliguori
98 9b80ddf3 aliguori
        if (bdrv_pread(s->hd, offset, &ext, sizeof(ext)) != sizeof(ext)) {
99 4c978075 aliguori
            fprintf(stderr, "qcow_handle_extension: ERROR: pread fail from offset %llu\n",
100 4c978075 aliguori
                    (unsigned long long)offset);
101 9b80ddf3 aliguori
            return 1;
102 9b80ddf3 aliguori
        }
103 9b80ddf3 aliguori
        be32_to_cpus(&ext.magic);
104 9b80ddf3 aliguori
        be32_to_cpus(&ext.len);
105 9b80ddf3 aliguori
        offset += sizeof(ext);
106 9b80ddf3 aliguori
#ifdef DEBUG_EXT
107 9b80ddf3 aliguori
        printf("ext.magic = 0x%x\n", ext.magic);
108 9b80ddf3 aliguori
#endif
109 9b80ddf3 aliguori
        switch (ext.magic) {
110 9b80ddf3 aliguori
        case QCOW_EXT_MAGIC_END:
111 9b80ddf3 aliguori
            return 0;
112 f965509c aliguori
113 f965509c aliguori
        case QCOW_EXT_MAGIC_BACKING_FORMAT:
114 f965509c aliguori
            if (ext.len >= sizeof(bs->backing_format)) {
115 f965509c aliguori
                fprintf(stderr, "ERROR: ext_backing_format: len=%u too large"
116 4c978075 aliguori
                        " (>=%zu)\n",
117 f965509c aliguori
                        ext.len, sizeof(bs->backing_format));
118 f965509c aliguori
                return 2;
119 f965509c aliguori
            }
120 f965509c aliguori
            if (bdrv_pread(s->hd, offset , bs->backing_format,
121 f965509c aliguori
                           ext.len) != ext.len)
122 f965509c aliguori
                return 3;
123 f965509c aliguori
            bs->backing_format[ext.len] = '\0';
124 f965509c aliguori
#ifdef DEBUG_EXT
125 f965509c aliguori
            printf("Qcow2: Got format extension %s\n", bs->backing_format);
126 f965509c aliguori
#endif
127 e1c7f0e3 Kevin Wolf
            offset = ((offset + ext.len + 7) & ~7);
128 f965509c aliguori
            break;
129 f965509c aliguori
130 9b80ddf3 aliguori
        default:
131 9b80ddf3 aliguori
            /* unknown magic -- just skip it */
132 e1c7f0e3 Kevin Wolf
            offset = ((offset + ext.len + 7) & ~7);
133 9b80ddf3 aliguori
            break;
134 9b80ddf3 aliguori
        }
135 9b80ddf3 aliguori
    }
136 9b80ddf3 aliguori
137 9b80ddf3 aliguori
    return 0;
138 9b80ddf3 aliguori
}
139 9b80ddf3 aliguori
140 9b80ddf3 aliguori
141 585f8587 bellard
static int qcow_open(BlockDriverState *bs, const char *filename, int flags)
142 585f8587 bellard
{
143 585f8587 bellard
    BDRVQcowState *s = bs->opaque;
144 585f8587 bellard
    int len, i, shift, ret;
145 585f8587 bellard
    QCowHeader header;
146 9b80ddf3 aliguori
    uint64_t ext_end;
147 585f8587 bellard
148 b5eff355 aurel32
    ret = bdrv_file_open(&s->hd, filename, flags);
149 585f8587 bellard
    if (ret < 0)
150 585f8587 bellard
        return ret;
151 585f8587 bellard
    if (bdrv_pread(s->hd, 0, &header, sizeof(header)) != sizeof(header))
152 585f8587 bellard
        goto fail;
153 585f8587 bellard
    be32_to_cpus(&header.magic);
154 585f8587 bellard
    be32_to_cpus(&header.version);
155 585f8587 bellard
    be64_to_cpus(&header.backing_file_offset);
156 585f8587 bellard
    be32_to_cpus(&header.backing_file_size);
157 585f8587 bellard
    be64_to_cpus(&header.size);
158 585f8587 bellard
    be32_to_cpus(&header.cluster_bits);
159 585f8587 bellard
    be32_to_cpus(&header.crypt_method);
160 585f8587 bellard
    be64_to_cpus(&header.l1_table_offset);
161 585f8587 bellard
    be32_to_cpus(&header.l1_size);
162 585f8587 bellard
    be64_to_cpus(&header.refcount_table_offset);
163 585f8587 bellard
    be32_to_cpus(&header.refcount_table_clusters);
164 585f8587 bellard
    be64_to_cpus(&header.snapshots_offset);
165 585f8587 bellard
    be32_to_cpus(&header.nb_snapshots);
166 3b46e624 ths
167 585f8587 bellard
    if (header.magic != QCOW_MAGIC || header.version != QCOW_VERSION)
168 585f8587 bellard
        goto fail;
169 d191d12d Stefan Weil
    if (header.cluster_bits < MIN_CLUSTER_BITS ||
170 73c632ed Kevin Wolf
        header.cluster_bits > MAX_CLUSTER_BITS)
171 585f8587 bellard
        goto fail;
172 585f8587 bellard
    if (header.crypt_method > QCOW_CRYPT_AES)
173 585f8587 bellard
        goto fail;
174 585f8587 bellard
    s->crypt_method_header = header.crypt_method;
175 585f8587 bellard
    if (s->crypt_method_header)
176 585f8587 bellard
        bs->encrypted = 1;
177 585f8587 bellard
    s->cluster_bits = header.cluster_bits;
178 585f8587 bellard
    s->cluster_size = 1 << s->cluster_bits;
179 585f8587 bellard
    s->cluster_sectors = 1 << (s->cluster_bits - 9);
180 585f8587 bellard
    s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */
181 585f8587 bellard
    s->l2_size = 1 << s->l2_bits;
182 585f8587 bellard
    bs->total_sectors = header.size / 512;
183 585f8587 bellard
    s->csize_shift = (62 - (s->cluster_bits - 8));
184 585f8587 bellard
    s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;
185 585f8587 bellard
    s->cluster_offset_mask = (1LL << s->csize_shift) - 1;
186 585f8587 bellard
    s->refcount_table_offset = header.refcount_table_offset;
187 5fafdf24 ths
    s->refcount_table_size =
188 585f8587 bellard
        header.refcount_table_clusters << (s->cluster_bits - 3);
189 585f8587 bellard
190 585f8587 bellard
    s->snapshots_offset = header.snapshots_offset;
191 585f8587 bellard
    s->nb_snapshots = header.nb_snapshots;
192 585f8587 bellard
193 585f8587 bellard
    /* read the level 1 table */
194 585f8587 bellard
    s->l1_size = header.l1_size;
195 585f8587 bellard
    shift = s->cluster_bits + s->l2_bits;
196 585f8587 bellard
    s->l1_vm_state_index = (header.size + (1LL << shift) - 1) >> shift;
197 585f8587 bellard
    /* the L1 table must contain at least enough entries to put
198 585f8587 bellard
       header.size bytes */
199 585f8587 bellard
    if (s->l1_size < s->l1_vm_state_index)
200 585f8587 bellard
        goto fail;
201 585f8587 bellard
    s->l1_table_offset = header.l1_table_offset;
202 d191d12d Stefan Weil
    if (s->l1_size > 0) {
203 d191d12d Stefan Weil
        s->l1_table = qemu_mallocz(
204 d191d12d Stefan Weil
            align_offset(s->l1_size * sizeof(uint64_t), 512));
205 d191d12d Stefan Weil
        if (bdrv_pread(s->hd, s->l1_table_offset, s->l1_table, s->l1_size * sizeof(uint64_t)) !=
206 d191d12d Stefan Weil
            s->l1_size * sizeof(uint64_t))
207 d191d12d Stefan Weil
            goto fail;
208 d191d12d Stefan Weil
        for(i = 0;i < s->l1_size; i++) {
209 d191d12d Stefan Weil
            be64_to_cpus(&s->l1_table[i]);
210 d191d12d Stefan Weil
        }
211 585f8587 bellard
    }
212 585f8587 bellard
    /* alloc L2 cache */
213 585f8587 bellard
    s->l2_cache = qemu_malloc(s->l2_size * L2_CACHE_SIZE * sizeof(uint64_t));
214 585f8587 bellard
    s->cluster_cache = qemu_malloc(s->cluster_size);
215 585f8587 bellard
    /* one more sector for decompressed data alignment */
216 095a9c58 aliguori
    s->cluster_data = qemu_malloc(QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size
217 095a9c58 aliguori
                                  + 512);
218 585f8587 bellard
    s->cluster_cache_offset = -1;
219 3b46e624 ths
220 ed6ccf0f Kevin Wolf
    if (qcow2_refcount_init(bs) < 0)
221 585f8587 bellard
        goto fail;
222 585f8587 bellard
223 72cf2d4f Blue Swirl
    QLIST_INIT(&s->cluster_allocs);
224 f214978a Kevin Wolf
225 9b80ddf3 aliguori
    /* read qcow2 extensions */
226 9b80ddf3 aliguori
    if (header.backing_file_offset)
227 9b80ddf3 aliguori
        ext_end = header.backing_file_offset;
228 9b80ddf3 aliguori
    else
229 9b80ddf3 aliguori
        ext_end = s->cluster_size;
230 9b80ddf3 aliguori
    if (qcow_read_extensions(bs, sizeof(header), ext_end))
231 9b80ddf3 aliguori
        goto fail;
232 9b80ddf3 aliguori
233 585f8587 bellard
    /* read the backing file name */
234 585f8587 bellard
    if (header.backing_file_offset != 0) {
235 585f8587 bellard
        len = header.backing_file_size;
236 585f8587 bellard
        if (len > 1023)
237 585f8587 bellard
            len = 1023;
238 585f8587 bellard
        if (bdrv_pread(s->hd, header.backing_file_offset, bs->backing_file, len) != len)
239 585f8587 bellard
            goto fail;
240 585f8587 bellard
        bs->backing_file[len] = '\0';
241 585f8587 bellard
    }
242 ed6ccf0f Kevin Wolf
    if (qcow2_read_snapshots(bs) < 0)
243 585f8587 bellard
        goto fail;
244 585f8587 bellard
245 585f8587 bellard
#ifdef DEBUG_ALLOC
246 14899cdf Filip Navara
    qcow2_check_refcounts(bs);
247 585f8587 bellard
#endif
248 585f8587 bellard
    return 0;
249 585f8587 bellard
250 585f8587 bellard
 fail:
251 ed6ccf0f Kevin Wolf
    qcow2_free_snapshots(bs);
252 ed6ccf0f Kevin Wolf
    qcow2_refcount_close(bs);
253 585f8587 bellard
    qemu_free(s->l1_table);
254 585f8587 bellard
    qemu_free(s->l2_cache);
255 585f8587 bellard
    qemu_free(s->cluster_cache);
256 585f8587 bellard
    qemu_free(s->cluster_data);
257 585f8587 bellard
    bdrv_delete(s->hd);
258 585f8587 bellard
    return -1;
259 585f8587 bellard
}
260 585f8587 bellard
261 585f8587 bellard
static int qcow_set_key(BlockDriverState *bs, const char *key)
262 585f8587 bellard
{
263 585f8587 bellard
    BDRVQcowState *s = bs->opaque;
264 585f8587 bellard
    uint8_t keybuf[16];
265 585f8587 bellard
    int len, i;
266 3b46e624 ths
267 585f8587 bellard
    memset(keybuf, 0, 16);
268 585f8587 bellard
    len = strlen(key);
269 585f8587 bellard
    if (len > 16)
270 585f8587 bellard
        len = 16;
271 585f8587 bellard
    /* XXX: we could compress the chars to 7 bits to increase
272 585f8587 bellard
       entropy */
273 585f8587 bellard
    for(i = 0;i < len;i++) {
274 585f8587 bellard
        keybuf[i] = key[i];
275 585f8587 bellard
    }
276 585f8587 bellard
    s->crypt_method = s->crypt_method_header;
277 585f8587 bellard
278 585f8587 bellard
    if (AES_set_encrypt_key(keybuf, 128, &s->aes_encrypt_key) != 0)
279 585f8587 bellard
        return -1;
280 585f8587 bellard
    if (AES_set_decrypt_key(keybuf, 128, &s->aes_decrypt_key) != 0)
281 585f8587 bellard
        return -1;
282 585f8587 bellard
#if 0
283 585f8587 bellard
    /* test */
284 585f8587 bellard
    {
285 585f8587 bellard
        uint8_t in[16];
286 585f8587 bellard
        uint8_t out[16];
287 585f8587 bellard
        uint8_t tmp[16];
288 585f8587 bellard
        for(i=0;i<16;i++)
289 585f8587 bellard
            in[i] = i;
290 585f8587 bellard
        AES_encrypt(in, tmp, &s->aes_encrypt_key);
291 585f8587 bellard
        AES_decrypt(tmp, out, &s->aes_decrypt_key);
292 585f8587 bellard
        for(i = 0; i < 16; i++)
293 585f8587 bellard
            printf(" %02x", tmp[i]);
294 585f8587 bellard
        printf("\n");
295 585f8587 bellard
        for(i = 0; i < 16; i++)
296 585f8587 bellard
            printf(" %02x", out[i]);
297 585f8587 bellard
        printf("\n");
298 585f8587 bellard
    }
299 585f8587 bellard
#endif
300 585f8587 bellard
    return 0;
301 585f8587 bellard
}
302 585f8587 bellard
303 5fafdf24 ths
static int qcow_is_allocated(BlockDriverState *bs, int64_t sector_num,
304 585f8587 bellard
                             int nb_sectors, int *pnum)
305 585f8587 bellard
{
306 585f8587 bellard
    uint64_t cluster_offset;
307 585f8587 bellard
308 095a9c58 aliguori
    *pnum = nb_sectors;
309 ed6ccf0f Kevin Wolf
    cluster_offset = qcow2_get_cluster_offset(bs, sector_num << 9, pnum);
310 095a9c58 aliguori
311 585f8587 bellard
    return (cluster_offset != 0);
312 585f8587 bellard
}
313 585f8587 bellard
314 a9465922 bellard
/* handle reading after the end of the backing file */
315 ed6ccf0f Kevin Wolf
int qcow2_backing_read1(BlockDriverState *bs,
316 45aba42f Kevin Wolf
                  int64_t sector_num, uint8_t *buf, int nb_sectors)
317 a9465922 bellard
{
318 a9465922 bellard
    int n1;
319 a9465922 bellard
    if ((sector_num + nb_sectors) <= bs->total_sectors)
320 a9465922 bellard
        return nb_sectors;
321 a9465922 bellard
    if (sector_num >= bs->total_sectors)
322 a9465922 bellard
        n1 = 0;
323 a9465922 bellard
    else
324 a9465922 bellard
        n1 = bs->total_sectors - sector_num;
325 a9465922 bellard
    memset(buf + n1 * 512, 0, 512 * (nb_sectors - n1));
326 a9465922 bellard
    return n1;
327 a9465922 bellard
}
328 a9465922 bellard
329 ce1a14dc pbrook
typedef struct QCowAIOCB {
330 ce1a14dc pbrook
    BlockDriverAIOCB common;
331 585f8587 bellard
    int64_t sector_num;
332 f141eafe aliguori
    QEMUIOVector *qiov;
333 585f8587 bellard
    uint8_t *buf;
334 f141eafe aliguori
    void *orig_buf;
335 585f8587 bellard
    int nb_sectors;
336 585f8587 bellard
    int n;
337 585f8587 bellard
    uint64_t cluster_offset;
338 5fafdf24 ths
    uint8_t *cluster_data;
339 585f8587 bellard
    BlockDriverAIOCB *hd_aiocb;
340 c87c0672 aliguori
    struct iovec hd_iov;
341 c87c0672 aliguori
    QEMUIOVector hd_qiov;
342 1490791f aliguori
    QEMUBH *bh;
343 e976c6a1 aliguori
    QCowL2Meta l2meta;
344 72cf2d4f Blue Swirl
    QLIST_ENTRY(QCowAIOCB) next_depend;
345 585f8587 bellard
} QCowAIOCB;
346 585f8587 bellard
347 c16b5a2c Christoph Hellwig
static void qcow_aio_cancel(BlockDriverAIOCB *blockacb)
348 c16b5a2c Christoph Hellwig
{
349 c16b5a2c Christoph Hellwig
    QCowAIOCB *acb = (QCowAIOCB *)blockacb;
350 c16b5a2c Christoph Hellwig
    if (acb->hd_aiocb)
351 c16b5a2c Christoph Hellwig
        bdrv_aio_cancel(acb->hd_aiocb);
352 c16b5a2c Christoph Hellwig
    qemu_aio_release(acb);
353 c16b5a2c Christoph Hellwig
}
354 c16b5a2c Christoph Hellwig
355 c16b5a2c Christoph Hellwig
static AIOPool qcow_aio_pool = {
356 c16b5a2c Christoph Hellwig
    .aiocb_size         = sizeof(QCowAIOCB),
357 c16b5a2c Christoph Hellwig
    .cancel             = qcow_aio_cancel,
358 c16b5a2c Christoph Hellwig
};
359 c16b5a2c Christoph Hellwig
360 1490791f aliguori
static void qcow_aio_read_cb(void *opaque, int ret);
361 1490791f aliguori
static void qcow_aio_read_bh(void *opaque)
362 1490791f aliguori
{
363 1490791f aliguori
    QCowAIOCB *acb = opaque;
364 1490791f aliguori
    qemu_bh_delete(acb->bh);
365 1490791f aliguori
    acb->bh = NULL;
366 1490791f aliguori
    qcow_aio_read_cb(opaque, 0);
367 1490791f aliguori
}
368 1490791f aliguori
369 a32ef786 aliguori
static int qcow_schedule_bh(QEMUBHFunc *cb, QCowAIOCB *acb)
370 a32ef786 aliguori
{
371 a32ef786 aliguori
    if (acb->bh)
372 a32ef786 aliguori
        return -EIO;
373 a32ef786 aliguori
374 a32ef786 aliguori
    acb->bh = qemu_bh_new(cb, acb);
375 a32ef786 aliguori
    if (!acb->bh)
376 a32ef786 aliguori
        return -EIO;
377 a32ef786 aliguori
378 a32ef786 aliguori
    qemu_bh_schedule(acb->bh);
379 a32ef786 aliguori
380 a32ef786 aliguori
    return 0;
381 a32ef786 aliguori
}
382 a32ef786 aliguori
383 585f8587 bellard
static void qcow_aio_read_cb(void *opaque, int ret)
384 585f8587 bellard
{
385 ce1a14dc pbrook
    QCowAIOCB *acb = opaque;
386 ce1a14dc pbrook
    BlockDriverState *bs = acb->common.bs;
387 585f8587 bellard
    BDRVQcowState *s = bs->opaque;
388 a9465922 bellard
    int index_in_cluster, n1;
389 585f8587 bellard
390 ce1a14dc pbrook
    acb->hd_aiocb = NULL;
391 f141eafe aliguori
    if (ret < 0)
392 f141eafe aliguori
        goto done;
393 585f8587 bellard
394 585f8587 bellard
    /* post process the read buffer */
395 ce1a14dc pbrook
    if (!acb->cluster_offset) {
396 585f8587 bellard
        /* nothing to do */
397 ce1a14dc pbrook
    } else if (acb->cluster_offset & QCOW_OFLAG_COMPRESSED) {
398 585f8587 bellard
        /* nothing to do */
399 585f8587 bellard
    } else {
400 585f8587 bellard
        if (s->crypt_method) {
401 ed6ccf0f Kevin Wolf
            qcow2_encrypt_sectors(s, acb->sector_num, acb->buf, acb->buf,
402 5fafdf24 ths
                            acb->n, 0,
403 585f8587 bellard
                            &s->aes_decrypt_key);
404 585f8587 bellard
        }
405 585f8587 bellard
    }
406 585f8587 bellard
407 ce1a14dc pbrook
    acb->nb_sectors -= acb->n;
408 ce1a14dc pbrook
    acb->sector_num += acb->n;
409 ce1a14dc pbrook
    acb->buf += acb->n * 512;
410 585f8587 bellard
411 ce1a14dc pbrook
    if (acb->nb_sectors == 0) {
412 585f8587 bellard
        /* request completed */
413 f141eafe aliguori
        ret = 0;
414 f141eafe aliguori
        goto done;
415 585f8587 bellard
    }
416 3b46e624 ths
417 585f8587 bellard
    /* prepare next AIO request */
418 095a9c58 aliguori
    acb->n = acb->nb_sectors;
419 ed6ccf0f Kevin Wolf
    acb->cluster_offset =
420 ed6ccf0f Kevin Wolf
        qcow2_get_cluster_offset(bs, acb->sector_num << 9, &acb->n);
421 ce1a14dc pbrook
    index_in_cluster = acb->sector_num & (s->cluster_sectors - 1);
422 ce1a14dc pbrook
423 ce1a14dc pbrook
    if (!acb->cluster_offset) {
424 585f8587 bellard
        if (bs->backing_hd) {
425 585f8587 bellard
            /* read from the base image */
426 ed6ccf0f Kevin Wolf
            n1 = qcow2_backing_read1(bs->backing_hd, acb->sector_num,
427 ce1a14dc pbrook
                               acb->buf, acb->n);
428 a9465922 bellard
            if (n1 > 0) {
429 3f4cb3d3 blueswir1
                acb->hd_iov.iov_base = (void *)acb->buf;
430 c87c0672 aliguori
                acb->hd_iov.iov_len = acb->n * 512;
431 c87c0672 aliguori
                qemu_iovec_init_external(&acb->hd_qiov, &acb->hd_iov, 1);
432 c87c0672 aliguori
                acb->hd_aiocb = bdrv_aio_readv(bs->backing_hd, acb->sector_num,
433 c87c0672 aliguori
                                    &acb->hd_qiov, acb->n,
434 c87c0672 aliguori
                                    qcow_aio_read_cb, acb);
435 ce1a14dc pbrook
                if (acb->hd_aiocb == NULL)
436 f141eafe aliguori
                    goto done;
437 a9465922 bellard
            } else {
438 a32ef786 aliguori
                ret = qcow_schedule_bh(qcow_aio_read_bh, acb);
439 a32ef786 aliguori
                if (ret < 0)
440 f141eafe aliguori
                    goto done;
441 a9465922 bellard
            }
442 585f8587 bellard
        } else {
443 585f8587 bellard
            /* Note: in this case, no need to wait */
444 ce1a14dc pbrook
            memset(acb->buf, 0, 512 * acb->n);
445 a32ef786 aliguori
            ret = qcow_schedule_bh(qcow_aio_read_bh, acb);
446 a32ef786 aliguori
            if (ret < 0)
447 f141eafe aliguori
                goto done;
448 585f8587 bellard
        }
449 ce1a14dc pbrook
    } else if (acb->cluster_offset & QCOW_OFLAG_COMPRESSED) {
450 585f8587 bellard
        /* add AIO support for compressed blocks ? */
451 ed6ccf0f Kevin Wolf
        if (qcow2_decompress_cluster(s, acb->cluster_offset) < 0)
452 f141eafe aliguori
            goto done;
453 5fafdf24 ths
        memcpy(acb->buf,
454 ce1a14dc pbrook
               s->cluster_cache + index_in_cluster * 512, 512 * acb->n);
455 a32ef786 aliguori
        ret = qcow_schedule_bh(qcow_aio_read_bh, acb);
456 a32ef786 aliguori
        if (ret < 0)
457 f141eafe aliguori
            goto done;
458 585f8587 bellard
    } else {
459 ce1a14dc pbrook
        if ((acb->cluster_offset & 511) != 0) {
460 585f8587 bellard
            ret = -EIO;
461 f141eafe aliguori
            goto done;
462 585f8587 bellard
        }
463 c87c0672 aliguori
464 3f4cb3d3 blueswir1
        acb->hd_iov.iov_base = (void *)acb->buf;
465 c87c0672 aliguori
        acb->hd_iov.iov_len = acb->n * 512;
466 c87c0672 aliguori
        qemu_iovec_init_external(&acb->hd_qiov, &acb->hd_iov, 1);
467 c87c0672 aliguori
        acb->hd_aiocb = bdrv_aio_readv(s->hd,
468 5fafdf24 ths
                            (acb->cluster_offset >> 9) + index_in_cluster,
469 c87c0672 aliguori
                            &acb->hd_qiov, acb->n, qcow_aio_read_cb, acb);
470 ce1a14dc pbrook
        if (acb->hd_aiocb == NULL)
471 f141eafe aliguori
            goto done;
472 f141eafe aliguori
    }
473 f141eafe aliguori
474 f141eafe aliguori
    return;
475 f141eafe aliguori
done:
476 f141eafe aliguori
    if (acb->qiov->niov > 1) {
477 f141eafe aliguori
        qemu_iovec_from_buffer(acb->qiov, acb->orig_buf, acb->qiov->size);
478 f141eafe aliguori
        qemu_vfree(acb->orig_buf);
479 585f8587 bellard
    }
480 f141eafe aliguori
    acb->common.cb(acb->common.opaque, ret);
481 f141eafe aliguori
    qemu_aio_release(acb);
482 585f8587 bellard
}
483 585f8587 bellard
484 ce1a14dc pbrook
static QCowAIOCB *qcow_aio_setup(BlockDriverState *bs,
485 f141eafe aliguori
        int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
486 f141eafe aliguori
        BlockDriverCompletionFunc *cb, void *opaque, int is_write)
487 585f8587 bellard
{
488 ce1a14dc pbrook
    QCowAIOCB *acb;
489 ce1a14dc pbrook
490 c16b5a2c Christoph Hellwig
    acb = qemu_aio_get(&qcow_aio_pool, bs, cb, opaque);
491 ce1a14dc pbrook
    if (!acb)
492 ce1a14dc pbrook
        return NULL;
493 ce1a14dc pbrook
    acb->hd_aiocb = NULL;
494 ce1a14dc pbrook
    acb->sector_num = sector_num;
495 f141eafe aliguori
    acb->qiov = qiov;
496 f141eafe aliguori
    if (qiov->niov > 1) {
497 e268ca52 aliguori
        acb->buf = acb->orig_buf = qemu_blockalign(bs, qiov->size);
498 f141eafe aliguori
        if (is_write)
499 f141eafe aliguori
            qemu_iovec_to_buffer(qiov, acb->buf);
500 3f4cb3d3 blueswir1
    } else {
501 3f4cb3d3 blueswir1
        acb->buf = (uint8_t *)qiov->iov->iov_base;
502 3f4cb3d3 blueswir1
    }
503 ce1a14dc pbrook
    acb->nb_sectors = nb_sectors;
504 ce1a14dc pbrook
    acb->n = 0;
505 ce1a14dc pbrook
    acb->cluster_offset = 0;
506 e976c6a1 aliguori
    acb->l2meta.nb_clusters = 0;
507 72cf2d4f Blue Swirl
    QLIST_INIT(&acb->l2meta.dependent_requests);
508 ce1a14dc pbrook
    return acb;
509 ce1a14dc pbrook
}
510 ce1a14dc pbrook
511 f141eafe aliguori
static BlockDriverAIOCB *qcow_aio_readv(BlockDriverState *bs,
512 f141eafe aliguori
        int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
513 ce1a14dc pbrook
        BlockDriverCompletionFunc *cb, void *opaque)
514 ce1a14dc pbrook
{
515 ce1a14dc pbrook
    QCowAIOCB *acb;
516 ce1a14dc pbrook
517 f141eafe aliguori
    acb = qcow_aio_setup(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
518 ce1a14dc pbrook
    if (!acb)
519 ce1a14dc pbrook
        return NULL;
520 585f8587 bellard
521 585f8587 bellard
    qcow_aio_read_cb(acb, 0);
522 ce1a14dc pbrook
    return &acb->common;
523 585f8587 bellard
}
524 585f8587 bellard
525 f214978a Kevin Wolf
static void qcow_aio_write_cb(void *opaque, int ret);
526 f214978a Kevin Wolf
527 f214978a Kevin Wolf
static void run_dependent_requests(QCowL2Meta *m)
528 f214978a Kevin Wolf
{
529 f214978a Kevin Wolf
    QCowAIOCB *req;
530 f214978a Kevin Wolf
    QCowAIOCB *next;
531 f214978a Kevin Wolf
532 f214978a Kevin Wolf
    /* Take the request off the list of running requests */
533 f214978a Kevin Wolf
    if (m->nb_clusters != 0) {
534 72cf2d4f Blue Swirl
        QLIST_REMOVE(m, next_in_flight);
535 f214978a Kevin Wolf
    }
536 f214978a Kevin Wolf
537 f214978a Kevin Wolf
    /*
538 f214978a Kevin Wolf
     * Restart all dependent requests.
539 72cf2d4f Blue Swirl
     * Can't use QLIST_FOREACH here - the next link might not be the same
540 f214978a Kevin Wolf
     * any more after the callback  (request could depend on a different
541 f214978a Kevin Wolf
     * request now)
542 f214978a Kevin Wolf
     */
543 f214978a Kevin Wolf
    for (req = m->dependent_requests.lh_first; req != NULL; req = next) {
544 f214978a Kevin Wolf
        next = req->next_depend.le_next;
545 f214978a Kevin Wolf
        qcow_aio_write_cb(req, 0);
546 f214978a Kevin Wolf
    }
547 f214978a Kevin Wolf
548 f214978a Kevin Wolf
    /* Empty the list for the next part of the request */
549 72cf2d4f Blue Swirl
    QLIST_INIT(&m->dependent_requests);
550 f214978a Kevin Wolf
}
551 f214978a Kevin Wolf
552 585f8587 bellard
static void qcow_aio_write_cb(void *opaque, int ret)
553 585f8587 bellard
{
554 ce1a14dc pbrook
    QCowAIOCB *acb = opaque;
555 ce1a14dc pbrook
    BlockDriverState *bs = acb->common.bs;
556 585f8587 bellard
    BDRVQcowState *s = bs->opaque;
557 585f8587 bellard
    int index_in_cluster;
558 585f8587 bellard
    const uint8_t *src_buf;
559 095a9c58 aliguori
    int n_end;
560 ce1a14dc pbrook
561 ce1a14dc pbrook
    acb->hd_aiocb = NULL;
562 ce1a14dc pbrook
563 f214978a Kevin Wolf
    if (ret >= 0) {
564 148da7ea Kevin Wolf
        ret = qcow2_alloc_cluster_link_l2(bs, &acb->l2meta);
565 f214978a Kevin Wolf
    }
566 f214978a Kevin Wolf
567 f214978a Kevin Wolf
    run_dependent_requests(&acb->l2meta);
568 f214978a Kevin Wolf
569 f141eafe aliguori
    if (ret < 0)
570 f141eafe aliguori
        goto done;
571 585f8587 bellard
572 ce1a14dc pbrook
    acb->nb_sectors -= acb->n;
573 ce1a14dc pbrook
    acb->sector_num += acb->n;
574 ce1a14dc pbrook
    acb->buf += acb->n * 512;
575 585f8587 bellard
576 ce1a14dc pbrook
    if (acb->nb_sectors == 0) {
577 585f8587 bellard
        /* request completed */
578 f141eafe aliguori
        ret = 0;
579 f141eafe aliguori
        goto done;
580 585f8587 bellard
    }
581 3b46e624 ths
582 ce1a14dc pbrook
    index_in_cluster = acb->sector_num & (s->cluster_sectors - 1);
583 095a9c58 aliguori
    n_end = index_in_cluster + acb->nb_sectors;
584 095a9c58 aliguori
    if (s->crypt_method &&
585 095a9c58 aliguori
        n_end > QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors)
586 095a9c58 aliguori
        n_end = QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors;
587 095a9c58 aliguori
588 148da7ea Kevin Wolf
    ret = qcow2_alloc_cluster_offset(bs, acb->sector_num << 9,
589 148da7ea Kevin Wolf
        index_in_cluster, n_end, &acb->n, &acb->l2meta);
590 148da7ea Kevin Wolf
    if (ret < 0) {
591 148da7ea Kevin Wolf
        goto done;
592 148da7ea Kevin Wolf
    }
593 148da7ea Kevin Wolf
594 148da7ea Kevin Wolf
    acb->cluster_offset = acb->l2meta.cluster_offset;
595 f214978a Kevin Wolf
596 f214978a Kevin Wolf
    /* Need to wait for another request? If so, we are done for now. */
597 148da7ea Kevin Wolf
    if (acb->l2meta.nb_clusters == 0 && acb->l2meta.depends_on != NULL) {
598 72cf2d4f Blue Swirl
        QLIST_INSERT_HEAD(&acb->l2meta.depends_on->dependent_requests,
599 f214978a Kevin Wolf
            acb, next_depend);
600 f214978a Kevin Wolf
        return;
601 f214978a Kevin Wolf
    }
602 f214978a Kevin Wolf
603 148da7ea Kevin Wolf
    assert((acb->cluster_offset & 511) == 0);
604 148da7ea Kevin Wolf
605 585f8587 bellard
    if (s->crypt_method) {
606 ce1a14dc pbrook
        if (!acb->cluster_data) {
607 095a9c58 aliguori
            acb->cluster_data = qemu_mallocz(QCOW_MAX_CRYPT_CLUSTERS *
608 095a9c58 aliguori
                                             s->cluster_size);
609 585f8587 bellard
        }
610 ed6ccf0f Kevin Wolf
        qcow2_encrypt_sectors(s, acb->sector_num, acb->cluster_data, acb->buf,
611 ce1a14dc pbrook
                        acb->n, 1, &s->aes_encrypt_key);
612 ce1a14dc pbrook
        src_buf = acb->cluster_data;
613 585f8587 bellard
    } else {
614 ce1a14dc pbrook
        src_buf = acb->buf;
615 585f8587 bellard
    }
616 c87c0672 aliguori
    acb->hd_iov.iov_base = (void *)src_buf;
617 c87c0672 aliguori
    acb->hd_iov.iov_len = acb->n * 512;
618 c87c0672 aliguori
    qemu_iovec_init_external(&acb->hd_qiov, &acb->hd_iov, 1);
619 c87c0672 aliguori
    acb->hd_aiocb = bdrv_aio_writev(s->hd,
620 c87c0672 aliguori
                                    (acb->cluster_offset >> 9) + index_in_cluster,
621 c87c0672 aliguori
                                    &acb->hd_qiov, acb->n,
622 c87c0672 aliguori
                                    qcow_aio_write_cb, acb);
623 ce1a14dc pbrook
    if (acb->hd_aiocb == NULL)
624 f141eafe aliguori
        goto done;
625 f141eafe aliguori
626 f141eafe aliguori
    return;
627 f141eafe aliguori
628 f141eafe aliguori
done:
629 f141eafe aliguori
    if (acb->qiov->niov > 1)
630 f141eafe aliguori
        qemu_vfree(acb->orig_buf);
631 f141eafe aliguori
    acb->common.cb(acb->common.opaque, ret);
632 f141eafe aliguori
    qemu_aio_release(acb);
633 585f8587 bellard
}
634 585f8587 bellard
635 f141eafe aliguori
static BlockDriverAIOCB *qcow_aio_writev(BlockDriverState *bs,
636 f141eafe aliguori
        int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
637 ce1a14dc pbrook
        BlockDriverCompletionFunc *cb, void *opaque)
638 585f8587 bellard
{
639 585f8587 bellard
    BDRVQcowState *s = bs->opaque;
640 ce1a14dc pbrook
    QCowAIOCB *acb;
641 3b46e624 ths
642 585f8587 bellard
    s->cluster_cache_offset = -1; /* disable compressed cache */
643 585f8587 bellard
644 f141eafe aliguori
    acb = qcow_aio_setup(bs, sector_num, qiov, nb_sectors, cb, opaque, 1);
645 ce1a14dc pbrook
    if (!acb)
646 ce1a14dc pbrook
        return NULL;
647 3b46e624 ths
648 585f8587 bellard
    qcow_aio_write_cb(acb, 0);
649 ce1a14dc pbrook
    return &acb->common;
650 585f8587 bellard
}
651 585f8587 bellard
652 585f8587 bellard
static void qcow_close(BlockDriverState *bs)
653 585f8587 bellard
{
654 585f8587 bellard
    BDRVQcowState *s = bs->opaque;
655 585f8587 bellard
    qemu_free(s->l1_table);
656 585f8587 bellard
    qemu_free(s->l2_cache);
657 585f8587 bellard
    qemu_free(s->cluster_cache);
658 585f8587 bellard
    qemu_free(s->cluster_data);
659 ed6ccf0f Kevin Wolf
    qcow2_refcount_close(bs);
660 585f8587 bellard
    bdrv_delete(s->hd);
661 585f8587 bellard
}
662 585f8587 bellard
663 756e6736 Kevin Wolf
/*
664 756e6736 Kevin Wolf
 * Updates the variable length parts of the qcow2 header, i.e. the backing file
665 756e6736 Kevin Wolf
 * name and all extensions. qcow2 was not designed to allow such changes, so if
666 756e6736 Kevin Wolf
 * we run out of space (we can only use the first cluster) this function may
667 756e6736 Kevin Wolf
 * fail.
668 756e6736 Kevin Wolf
 *
669 756e6736 Kevin Wolf
 * Returns 0 on success, -errno in error cases.
670 756e6736 Kevin Wolf
 */
671 756e6736 Kevin Wolf
static int qcow2_update_ext_header(BlockDriverState *bs,
672 756e6736 Kevin Wolf
    const char *backing_file, const char *backing_fmt)
673 756e6736 Kevin Wolf
{
674 756e6736 Kevin Wolf
    size_t backing_file_len = 0;
675 756e6736 Kevin Wolf
    size_t backing_fmt_len = 0;
676 756e6736 Kevin Wolf
    BDRVQcowState *s = bs->opaque;
677 756e6736 Kevin Wolf
    QCowExtension ext_backing_fmt = {0, 0};
678 756e6736 Kevin Wolf
    int ret;
679 756e6736 Kevin Wolf
680 756e6736 Kevin Wolf
    /* Backing file format doesn't make sense without a backing file */
681 756e6736 Kevin Wolf
    if (backing_fmt && !backing_file) {
682 756e6736 Kevin Wolf
        return -EINVAL;
683 756e6736 Kevin Wolf
    }
684 756e6736 Kevin Wolf
685 756e6736 Kevin Wolf
    /* Prepare the backing file format extension if needed */
686 756e6736 Kevin Wolf
    if (backing_fmt) {
687 756e6736 Kevin Wolf
        ext_backing_fmt.len = cpu_to_be32(strlen(backing_fmt));
688 756e6736 Kevin Wolf
        ext_backing_fmt.magic = cpu_to_be32(QCOW_EXT_MAGIC_BACKING_FORMAT);
689 756e6736 Kevin Wolf
        backing_fmt_len = ((sizeof(ext_backing_fmt)
690 756e6736 Kevin Wolf
            + strlen(backing_fmt) + 7) & ~7);
691 756e6736 Kevin Wolf
    }
692 756e6736 Kevin Wolf
693 756e6736 Kevin Wolf
    /* Check if we can fit the new header into the first cluster */
694 756e6736 Kevin Wolf
    if (backing_file) {
695 756e6736 Kevin Wolf
        backing_file_len = strlen(backing_file);
696 756e6736 Kevin Wolf
    }
697 756e6736 Kevin Wolf
698 756e6736 Kevin Wolf
    size_t header_size = sizeof(QCowHeader) + backing_file_len
699 756e6736 Kevin Wolf
        + backing_fmt_len;
700 756e6736 Kevin Wolf
701 756e6736 Kevin Wolf
    if (header_size > s->cluster_size) {
702 756e6736 Kevin Wolf
        return -ENOSPC;
703 756e6736 Kevin Wolf
    }
704 756e6736 Kevin Wolf
705 756e6736 Kevin Wolf
    /* Rewrite backing file name and qcow2 extensions */
706 756e6736 Kevin Wolf
    size_t ext_size = header_size - sizeof(QCowHeader);
707 756e6736 Kevin Wolf
    uint8_t buf[ext_size];
708 756e6736 Kevin Wolf
    size_t offset = 0;
709 756e6736 Kevin Wolf
    size_t backing_file_offset = 0;
710 756e6736 Kevin Wolf
711 756e6736 Kevin Wolf
    if (backing_file) {
712 756e6736 Kevin Wolf
        if (backing_fmt) {
713 756e6736 Kevin Wolf
            int padding = backing_fmt_len -
714 756e6736 Kevin Wolf
                (sizeof(ext_backing_fmt) + strlen(backing_fmt));
715 756e6736 Kevin Wolf
716 756e6736 Kevin Wolf
            memcpy(buf + offset, &ext_backing_fmt, sizeof(ext_backing_fmt));
717 756e6736 Kevin Wolf
            offset += sizeof(ext_backing_fmt);
718 756e6736 Kevin Wolf
719 756e6736 Kevin Wolf
            memcpy(buf + offset, backing_fmt, strlen(backing_fmt));
720 756e6736 Kevin Wolf
            offset += strlen(backing_fmt);
721 756e6736 Kevin Wolf
722 756e6736 Kevin Wolf
            memset(buf + offset, 0, padding);
723 756e6736 Kevin Wolf
            offset += padding;
724 756e6736 Kevin Wolf
        }
725 756e6736 Kevin Wolf
726 756e6736 Kevin Wolf
        memcpy(buf + offset, backing_file, backing_file_len);
727 756e6736 Kevin Wolf
        backing_file_offset = sizeof(QCowHeader) + offset;
728 756e6736 Kevin Wolf
    }
729 756e6736 Kevin Wolf
730 756e6736 Kevin Wolf
    ret = bdrv_pwrite(s->hd, sizeof(QCowHeader), buf, ext_size);
731 756e6736 Kevin Wolf
    if (ret < 0) {
732 756e6736 Kevin Wolf
        goto fail;
733 756e6736 Kevin Wolf
    }
734 756e6736 Kevin Wolf
735 756e6736 Kevin Wolf
    /* Update header fields */
736 756e6736 Kevin Wolf
    uint64_t be_backing_file_offset = cpu_to_be64(backing_file_offset);
737 756e6736 Kevin Wolf
    uint32_t be_backing_file_size = cpu_to_be32(backing_file_len);
738 756e6736 Kevin Wolf
739 756e6736 Kevin Wolf
    ret = bdrv_pwrite(s->hd, offsetof(QCowHeader, backing_file_offset),
740 756e6736 Kevin Wolf
        &be_backing_file_offset, sizeof(uint64_t));
741 756e6736 Kevin Wolf
    if (ret < 0) {
742 756e6736 Kevin Wolf
        goto fail;
743 756e6736 Kevin Wolf
    }
744 756e6736 Kevin Wolf
745 756e6736 Kevin Wolf
    ret = bdrv_pwrite(s->hd, offsetof(QCowHeader, backing_file_size),
746 756e6736 Kevin Wolf
        &be_backing_file_size, sizeof(uint32_t));
747 756e6736 Kevin Wolf
    if (ret < 0) {
748 756e6736 Kevin Wolf
        goto fail;
749 756e6736 Kevin Wolf
    }
750 756e6736 Kevin Wolf
751 756e6736 Kevin Wolf
    ret = 0;
752 756e6736 Kevin Wolf
fail:
753 756e6736 Kevin Wolf
    return ret;
754 756e6736 Kevin Wolf
}
755 756e6736 Kevin Wolf
756 756e6736 Kevin Wolf
static int qcow2_change_backing_file(BlockDriverState *bs,
757 756e6736 Kevin Wolf
    const char *backing_file, const char *backing_fmt)
758 756e6736 Kevin Wolf
{
759 756e6736 Kevin Wolf
    return qcow2_update_ext_header(bs, backing_file, backing_fmt);
760 756e6736 Kevin Wolf
}
761 756e6736 Kevin Wolf
762 73c632ed Kevin Wolf
static int get_bits_from_size(size_t size)
763 73c632ed Kevin Wolf
{
764 73c632ed Kevin Wolf
    int res = 0;
765 73c632ed Kevin Wolf
766 73c632ed Kevin Wolf
    if (size == 0) {
767 73c632ed Kevin Wolf
        return -1;
768 73c632ed Kevin Wolf
    }
769 73c632ed Kevin Wolf
770 73c632ed Kevin Wolf
    while (size != 1) {
771 73c632ed Kevin Wolf
        /* Not a power of two */
772 73c632ed Kevin Wolf
        if (size & 1) {
773 73c632ed Kevin Wolf
            return -1;
774 73c632ed Kevin Wolf
        }
775 73c632ed Kevin Wolf
776 73c632ed Kevin Wolf
        size >>= 1;
777 73c632ed Kevin Wolf
        res++;
778 73c632ed Kevin Wolf
    }
779 73c632ed Kevin Wolf
780 73c632ed Kevin Wolf
    return res;
781 73c632ed Kevin Wolf
}
782 73c632ed Kevin Wolf
783 a35e1c17 Kevin Wolf
784 a35e1c17 Kevin Wolf
static int preallocate(BlockDriverState *bs)
785 a35e1c17 Kevin Wolf
{
786 a35e1c17 Kevin Wolf
    BDRVQcowState *s = bs->opaque;
787 a35e1c17 Kevin Wolf
    uint64_t nb_sectors;
788 a35e1c17 Kevin Wolf
    uint64_t offset;
789 a35e1c17 Kevin Wolf
    int num;
790 148da7ea Kevin Wolf
    int ret;
791 a35e1c17 Kevin Wolf
    QCowL2Meta meta;
792 a35e1c17 Kevin Wolf
793 a35e1c17 Kevin Wolf
    nb_sectors = bdrv_getlength(bs) >> 9;
794 a35e1c17 Kevin Wolf
    offset = 0;
795 72cf2d4f Blue Swirl
    QLIST_INIT(&meta.dependent_requests);
796 148da7ea Kevin Wolf
    meta.cluster_offset = 0;
797 a35e1c17 Kevin Wolf
798 a35e1c17 Kevin Wolf
    while (nb_sectors) {
799 a35e1c17 Kevin Wolf
        num = MIN(nb_sectors, INT_MAX >> 9);
800 148da7ea Kevin Wolf
        ret = qcow2_alloc_cluster_offset(bs, offset, 0, num, &num, &meta);
801 a35e1c17 Kevin Wolf
802 148da7ea Kevin Wolf
        if (ret < 0) {
803 a35e1c17 Kevin Wolf
            return -1;
804 a35e1c17 Kevin Wolf
        }
805 a35e1c17 Kevin Wolf
806 148da7ea Kevin Wolf
        if (qcow2_alloc_cluster_link_l2(bs, &meta) < 0) {
807 148da7ea Kevin Wolf
            qcow2_free_any_clusters(bs, meta.cluster_offset, meta.nb_clusters);
808 a35e1c17 Kevin Wolf
            return -1;
809 a35e1c17 Kevin Wolf
        }
810 a35e1c17 Kevin Wolf
811 f214978a Kevin Wolf
        /* There are no dependent requests, but we need to remove our request
812 f214978a Kevin Wolf
         * from the list of in-flight requests */
813 f214978a Kevin Wolf
        run_dependent_requests(&meta);
814 f214978a Kevin Wolf
815 a35e1c17 Kevin Wolf
        /* TODO Preallocate data if requested */
816 a35e1c17 Kevin Wolf
817 a35e1c17 Kevin Wolf
        nb_sectors -= num;
818 a35e1c17 Kevin Wolf
        offset += num << 9;
819 a35e1c17 Kevin Wolf
    }
820 a35e1c17 Kevin Wolf
821 a35e1c17 Kevin Wolf
    /*
822 a35e1c17 Kevin Wolf
     * It is expected that the image file is large enough to actually contain
823 a35e1c17 Kevin Wolf
     * all of the allocated clusters (otherwise we get failing reads after
824 a35e1c17 Kevin Wolf
     * EOF). Extend the image to the last allocated sector.
825 a35e1c17 Kevin Wolf
     */
826 148da7ea Kevin Wolf
    if (meta.cluster_offset != 0) {
827 ea80b906 Kevin Wolf
        uint8_t buf[512];
828 ea80b906 Kevin Wolf
        memset(buf, 0, 512);
829 148da7ea Kevin Wolf
        bdrv_write(s->hd, (meta.cluster_offset >> 9) + num - 1, buf, 1);
830 a35e1c17 Kevin Wolf
    }
831 a35e1c17 Kevin Wolf
832 a35e1c17 Kevin Wolf
    return 0;
833 a35e1c17 Kevin Wolf
}
834 a35e1c17 Kevin Wolf
835 f965509c aliguori
static int qcow_create2(const char *filename, int64_t total_size,
836 f965509c aliguori
                        const char *backing_file, const char *backing_format,
837 a35e1c17 Kevin Wolf
                        int flags, size_t cluster_size, int prealloc)
838 585f8587 bellard
{
839 f965509c aliguori
840 585f8587 bellard
    int fd, header_size, backing_filename_len, l1_size, i, shift, l2_bits;
841 2d2431f0 aliguori
    int ref_clusters, backing_format_len = 0;
842 e1c7f0e3 Kevin Wolf
    int rounded_ext_bf_len = 0;
843 585f8587 bellard
    QCowHeader header;
844 585f8587 bellard
    uint64_t tmp, offset;
845 585f8587 bellard
    QCowCreateState s1, *s = &s1;
846 f965509c aliguori
    QCowExtension ext_bf = {0, 0};
847 db89119d Kirill A. Shutemov
    int ret;
848 3b46e624 ths
849 585f8587 bellard
    memset(s, 0, sizeof(*s));
850 585f8587 bellard
851 585f8587 bellard
    fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0644);
852 585f8587 bellard
    if (fd < 0)
853 585f8587 bellard
        return -1;
854 585f8587 bellard
    memset(&header, 0, sizeof(header));
855 585f8587 bellard
    header.magic = cpu_to_be32(QCOW_MAGIC);
856 585f8587 bellard
    header.version = cpu_to_be32(QCOW_VERSION);
857 585f8587 bellard
    header.size = cpu_to_be64(total_size * 512);
858 585f8587 bellard
    header_size = sizeof(header);
859 585f8587 bellard
    backing_filename_len = 0;
860 585f8587 bellard
    if (backing_file) {
861 f965509c aliguori
        if (backing_format) {
862 f965509c aliguori
            ext_bf.magic = QCOW_EXT_MAGIC_BACKING_FORMAT;
863 f965509c aliguori
            backing_format_len = strlen(backing_format);
864 e1c7f0e3 Kevin Wolf
            ext_bf.len = backing_format_len;
865 e1c7f0e3 Kevin Wolf
            rounded_ext_bf_len = (sizeof(ext_bf) + ext_bf.len + 7) & ~7;
866 e1c7f0e3 Kevin Wolf
            header_size += rounded_ext_bf_len;
867 f965509c aliguori
        }
868 585f8587 bellard
        header.backing_file_offset = cpu_to_be64(header_size);
869 585f8587 bellard
        backing_filename_len = strlen(backing_file);
870 585f8587 bellard
        header.backing_file_size = cpu_to_be32(backing_filename_len);
871 585f8587 bellard
        header_size += backing_filename_len;
872 585f8587 bellard
    }
873 73c632ed Kevin Wolf
874 73c632ed Kevin Wolf
    /* Cluster size */
875 73c632ed Kevin Wolf
    s->cluster_bits = get_bits_from_size(cluster_size);
876 73c632ed Kevin Wolf
    if (s->cluster_bits < MIN_CLUSTER_BITS ||
877 73c632ed Kevin Wolf
        s->cluster_bits > MAX_CLUSTER_BITS)
878 73c632ed Kevin Wolf
    {
879 73c632ed Kevin Wolf
        fprintf(stderr, "Cluster size must be a power of two between "
880 73c632ed Kevin Wolf
            "%d and %dk\n",
881 73c632ed Kevin Wolf
            1 << MIN_CLUSTER_BITS,
882 73c632ed Kevin Wolf
            1 << (MAX_CLUSTER_BITS - 10));
883 73c632ed Kevin Wolf
        return -EINVAL;
884 73c632ed Kevin Wolf
    }
885 585f8587 bellard
    s->cluster_size = 1 << s->cluster_bits;
886 73c632ed Kevin Wolf
887 585f8587 bellard
    header.cluster_bits = cpu_to_be32(s->cluster_bits);
888 585f8587 bellard
    header_size = (header_size + 7) & ~7;
889 ec36ba14 ths
    if (flags & BLOCK_FLAG_ENCRYPT) {
890 585f8587 bellard
        header.crypt_method = cpu_to_be32(QCOW_CRYPT_AES);
891 585f8587 bellard
    } else {
892 585f8587 bellard
        header.crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
893 585f8587 bellard
    }
894 585f8587 bellard
    l2_bits = s->cluster_bits - 3;
895 585f8587 bellard
    shift = s->cluster_bits + l2_bits;
896 585f8587 bellard
    l1_size = (((total_size * 512) + (1LL << shift) - 1) >> shift);
897 585f8587 bellard
    offset = align_offset(header_size, s->cluster_size);
898 585f8587 bellard
    s->l1_table_offset = offset;
899 585f8587 bellard
    header.l1_table_offset = cpu_to_be64(s->l1_table_offset);
900 585f8587 bellard
    header.l1_size = cpu_to_be32(l1_size);
901 15e6690a bellard
    offset += align_offset(l1_size * sizeof(uint64_t), s->cluster_size);
902 585f8587 bellard
903 585f8587 bellard
    s->refcount_table = qemu_mallocz(s->cluster_size);
904 3b46e624 ths
905 585f8587 bellard
    s->refcount_table_offset = offset;
906 585f8587 bellard
    header.refcount_table_offset = cpu_to_be64(offset);
907 585f8587 bellard
    header.refcount_table_clusters = cpu_to_be32(1);
908 585f8587 bellard
    offset += s->cluster_size;
909 585f8587 bellard
    s->refcount_block_offset = offset;
910 2d2431f0 aliguori
911 2d2431f0 aliguori
    /* count how many refcount blocks needed */
912 2d2431f0 aliguori
    tmp = offset >> s->cluster_bits;
913 2d2431f0 aliguori
    ref_clusters = (tmp >> (s->cluster_bits - REFCOUNT_SHIFT)) + 1;
914 2d2431f0 aliguori
    for (i=0; i < ref_clusters; i++) {
915 2d2431f0 aliguori
        s->refcount_table[i] = cpu_to_be64(offset);
916 2d2431f0 aliguori
        offset += s->cluster_size;
917 2d2431f0 aliguori
    }
918 2d2431f0 aliguori
919 2d2431f0 aliguori
    s->refcount_block = qemu_mallocz(ref_clusters * s->cluster_size);
920 585f8587 bellard
921 585f8587 bellard
    /* update refcounts */
922 ed6ccf0f Kevin Wolf
    qcow2_create_refcount_update(s, 0, header_size);
923 ed6ccf0f Kevin Wolf
    qcow2_create_refcount_update(s, s->l1_table_offset,
924 ed6ccf0f Kevin Wolf
        l1_size * sizeof(uint64_t));
925 ed6ccf0f Kevin Wolf
    qcow2_create_refcount_update(s, s->refcount_table_offset, s->cluster_size);
926 ed6ccf0f Kevin Wolf
    qcow2_create_refcount_update(s, s->refcount_block_offset,
927 ed6ccf0f Kevin Wolf
        ref_clusters * s->cluster_size);
928 3b46e624 ths
929 585f8587 bellard
    /* write all the data */
930 db89119d Kirill A. Shutemov
    ret = qemu_write_full(fd, &header, sizeof(header));
931 db89119d Kirill A. Shutemov
    if (ret != sizeof(header)) {
932 db89119d Kirill A. Shutemov
        ret = -1;
933 db89119d Kirill A. Shutemov
        goto exit;
934 db89119d Kirill A. Shutemov
    }
935 585f8587 bellard
    if (backing_file) {
936 f965509c aliguori
        if (backing_format_len) {
937 f965509c aliguori
            char zero[16];
938 e1c7f0e3 Kevin Wolf
            int padding = rounded_ext_bf_len - (ext_bf.len + sizeof(ext_bf));
939 f965509c aliguori
940 f965509c aliguori
            memset(zero, 0, sizeof(zero));
941 f965509c aliguori
            cpu_to_be32s(&ext_bf.magic);
942 f965509c aliguori
            cpu_to_be32s(&ext_bf.len);
943 db89119d Kirill A. Shutemov
            ret = qemu_write_full(fd, &ext_bf, sizeof(ext_bf));
944 db89119d Kirill A. Shutemov
            if (ret != sizeof(ext_bf)) {
945 db89119d Kirill A. Shutemov
                ret = -1;
946 db89119d Kirill A. Shutemov
                goto exit;
947 db89119d Kirill A. Shutemov
            }
948 db89119d Kirill A. Shutemov
            ret = qemu_write_full(fd, backing_format, backing_format_len);
949 db89119d Kirill A. Shutemov
            if (ret != backing_format_len) {
950 db89119d Kirill A. Shutemov
                ret = -1;
951 db89119d Kirill A. Shutemov
                goto exit;
952 db89119d Kirill A. Shutemov
            }
953 e1c7f0e3 Kevin Wolf
            if (padding > 0) {
954 db89119d Kirill A. Shutemov
                ret = qemu_write_full(fd, zero, padding);
955 db89119d Kirill A. Shutemov
                if (ret != padding) {
956 db89119d Kirill A. Shutemov
                    ret = -1;
957 db89119d Kirill A. Shutemov
                    goto exit;
958 db89119d Kirill A. Shutemov
                }
959 f965509c aliguori
            }
960 f965509c aliguori
        }
961 db89119d Kirill A. Shutemov
        ret = qemu_write_full(fd, backing_file, backing_filename_len);
962 db89119d Kirill A. Shutemov
        if (ret != backing_filename_len) {
963 db89119d Kirill A. Shutemov
            ret = -1;
964 db89119d Kirill A. Shutemov
            goto exit;
965 db89119d Kirill A. Shutemov
        }
966 585f8587 bellard
    }
967 585f8587 bellard
    lseek(fd, s->l1_table_offset, SEEK_SET);
968 585f8587 bellard
    tmp = 0;
969 585f8587 bellard
    for(i = 0;i < l1_size; i++) {
970 db89119d Kirill A. Shutemov
        ret = qemu_write_full(fd, &tmp, sizeof(tmp));
971 db89119d Kirill A. Shutemov
        if (ret != sizeof(tmp)) {
972 db89119d Kirill A. Shutemov
            ret = -1;
973 db89119d Kirill A. Shutemov
            goto exit;
974 db89119d Kirill A. Shutemov
        }
975 585f8587 bellard
    }
976 585f8587 bellard
    lseek(fd, s->refcount_table_offset, SEEK_SET);
977 db89119d Kirill A. Shutemov
    ret = qemu_write_full(fd, s->refcount_table, s->cluster_size);
978 db89119d Kirill A. Shutemov
    if (ret != s->cluster_size) {
979 db89119d Kirill A. Shutemov
        ret = -1;
980 db89119d Kirill A. Shutemov
        goto exit;
981 db89119d Kirill A. Shutemov
    }
982 3b46e624 ths
983 585f8587 bellard
    lseek(fd, s->refcount_block_offset, SEEK_SET);
984 db89119d Kirill A. Shutemov
    ret = qemu_write_full(fd, s->refcount_block,
985 db89119d Kirill A. Shutemov
                    ref_clusters * s->cluster_size);
986 db89119d Kirill A. Shutemov
    if (ret != s->cluster_size) {
987 db89119d Kirill A. Shutemov
        ret = -1;
988 db89119d Kirill A. Shutemov
        goto exit;
989 db89119d Kirill A. Shutemov
    }
990 585f8587 bellard
991 db89119d Kirill A. Shutemov
    ret = 0;
992 db89119d Kirill A. Shutemov
exit:
993 585f8587 bellard
    qemu_free(s->refcount_table);
994 585f8587 bellard
    qemu_free(s->refcount_block);
995 585f8587 bellard
    close(fd);
996 a35e1c17 Kevin Wolf
997 a35e1c17 Kevin Wolf
    /* Preallocate metadata */
998 a35e1c17 Kevin Wolf
    if (prealloc) {
999 a35e1c17 Kevin Wolf
        BlockDriverState *bs;
1000 a35e1c17 Kevin Wolf
        bs = bdrv_new("");
1001 058fc8c7 Naphtali Sprei
        bdrv_open(bs, filename, BDRV_O_CACHE_WB | BDRV_O_RDWR);
1002 a35e1c17 Kevin Wolf
        preallocate(bs);
1003 a35e1c17 Kevin Wolf
        bdrv_close(bs);
1004 a35e1c17 Kevin Wolf
    }
1005 a35e1c17 Kevin Wolf
1006 db89119d Kirill A. Shutemov
    return ret;
1007 585f8587 bellard
}
1008 585f8587 bellard
1009 0e7e1989 Kevin Wolf
static int qcow_create(const char *filename, QEMUOptionParameter *options)
1010 0e7e1989 Kevin Wolf
{
1011 0e7e1989 Kevin Wolf
    const char *backing_file = NULL;
1012 0e7e1989 Kevin Wolf
    const char *backing_fmt = NULL;
1013 0e7e1989 Kevin Wolf
    uint64_t sectors = 0;
1014 0e7e1989 Kevin Wolf
    int flags = 0;
1015 9ccb258e Kevin Wolf
    size_t cluster_size = 65536;
1016 a35e1c17 Kevin Wolf
    int prealloc = 0;
1017 0e7e1989 Kevin Wolf
1018 0e7e1989 Kevin Wolf
    /* Read out options */
1019 0e7e1989 Kevin Wolf
    while (options && options->name) {
1020 0e7e1989 Kevin Wolf
        if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
1021 0e7e1989 Kevin Wolf
            sectors = options->value.n / 512;
1022 0e7e1989 Kevin Wolf
        } else if (!strcmp(options->name, BLOCK_OPT_BACKING_FILE)) {
1023 0e7e1989 Kevin Wolf
            backing_file = options->value.s;
1024 0e7e1989 Kevin Wolf
        } else if (!strcmp(options->name, BLOCK_OPT_BACKING_FMT)) {
1025 0e7e1989 Kevin Wolf
            backing_fmt = options->value.s;
1026 0e7e1989 Kevin Wolf
        } else if (!strcmp(options->name, BLOCK_OPT_ENCRYPT)) {
1027 0e7e1989 Kevin Wolf
            flags |= options->value.n ? BLOCK_FLAG_ENCRYPT : 0;
1028 73c632ed Kevin Wolf
        } else if (!strcmp(options->name, BLOCK_OPT_CLUSTER_SIZE)) {
1029 73c632ed Kevin Wolf
            if (options->value.n) {
1030 73c632ed Kevin Wolf
                cluster_size = options->value.n;
1031 73c632ed Kevin Wolf
            }
1032 a35e1c17 Kevin Wolf
        } else if (!strcmp(options->name, BLOCK_OPT_PREALLOC)) {
1033 a35e1c17 Kevin Wolf
            if (!options->value.s || !strcmp(options->value.s, "off")) {
1034 a35e1c17 Kevin Wolf
                prealloc = 0;
1035 a35e1c17 Kevin Wolf
            } else if (!strcmp(options->value.s, "metadata")) {
1036 a35e1c17 Kevin Wolf
                prealloc = 1;
1037 a35e1c17 Kevin Wolf
            } else {
1038 a35e1c17 Kevin Wolf
                fprintf(stderr, "Invalid preallocation mode: '%s'\n",
1039 a35e1c17 Kevin Wolf
                    options->value.s);
1040 a35e1c17 Kevin Wolf
                return -EINVAL;
1041 a35e1c17 Kevin Wolf
            }
1042 0e7e1989 Kevin Wolf
        }
1043 0e7e1989 Kevin Wolf
        options++;
1044 0e7e1989 Kevin Wolf
    }
1045 0e7e1989 Kevin Wolf
1046 a35e1c17 Kevin Wolf
    if (backing_file && prealloc) {
1047 a35e1c17 Kevin Wolf
        fprintf(stderr, "Backing file and preallocation cannot be used at "
1048 a35e1c17 Kevin Wolf
            "the same time\n");
1049 a35e1c17 Kevin Wolf
        return -EINVAL;
1050 a35e1c17 Kevin Wolf
    }
1051 a35e1c17 Kevin Wolf
1052 73c632ed Kevin Wolf
    return qcow_create2(filename, sectors, backing_file, backing_fmt, flags,
1053 a35e1c17 Kevin Wolf
        cluster_size, prealloc);
1054 f965509c aliguori
}
1055 f965509c aliguori
1056 585f8587 bellard
static int qcow_make_empty(BlockDriverState *bs)
1057 585f8587 bellard
{
1058 585f8587 bellard
#if 0
1059 585f8587 bellard
    /* XXX: not correct */
1060 585f8587 bellard
    BDRVQcowState *s = bs->opaque;
1061 585f8587 bellard
    uint32_t l1_length = s->l1_size * sizeof(uint64_t);
1062 585f8587 bellard
    int ret;
1063 585f8587 bellard

1064 585f8587 bellard
    memset(s->l1_table, 0, l1_length);
1065 585f8587 bellard
    if (bdrv_pwrite(s->hd, s->l1_table_offset, s->l1_table, l1_length) < 0)
1066 ac674887 aliguori
        return -1;
1067 585f8587 bellard
    ret = bdrv_truncate(s->hd, s->l1_table_offset + l1_length);
1068 585f8587 bellard
    if (ret < 0)
1069 585f8587 bellard
        return ret;
1070 3b46e624 ths

1071 585f8587 bellard
    l2_cache_reset(bs);
1072 585f8587 bellard
#endif
1073 585f8587 bellard
    return 0;
1074 585f8587 bellard
}
1075 585f8587 bellard
1076 585f8587 bellard
/* XXX: put compressed sectors first, then all the cluster aligned
1077 585f8587 bellard
   tables to avoid losing bytes in alignment */
1078 5fafdf24 ths
static int qcow_write_compressed(BlockDriverState *bs, int64_t sector_num,
1079 585f8587 bellard
                                 const uint8_t *buf, int nb_sectors)
1080 585f8587 bellard
{
1081 585f8587 bellard
    BDRVQcowState *s = bs->opaque;
1082 585f8587 bellard
    z_stream strm;
1083 585f8587 bellard
    int ret, out_len;
1084 585f8587 bellard
    uint8_t *out_buf;
1085 585f8587 bellard
    uint64_t cluster_offset;
1086 585f8587 bellard
1087 585f8587 bellard
    if (nb_sectors == 0) {
1088 585f8587 bellard
        /* align end of file to a sector boundary to ease reading with
1089 585f8587 bellard
           sector based I/Os */
1090 585f8587 bellard
        cluster_offset = bdrv_getlength(s->hd);
1091 585f8587 bellard
        cluster_offset = (cluster_offset + 511) & ~511;
1092 585f8587 bellard
        bdrv_truncate(s->hd, cluster_offset);
1093 585f8587 bellard
        return 0;
1094 585f8587 bellard
    }
1095 585f8587 bellard
1096 585f8587 bellard
    if (nb_sectors != s->cluster_sectors)
1097 585f8587 bellard
        return -EINVAL;
1098 585f8587 bellard
1099 585f8587 bellard
    out_buf = qemu_malloc(s->cluster_size + (s->cluster_size / 1000) + 128);
1100 585f8587 bellard
1101 585f8587 bellard
    /* best compression, small window, no zlib header */
1102 585f8587 bellard
    memset(&strm, 0, sizeof(strm));
1103 585f8587 bellard
    ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
1104 5fafdf24 ths
                       Z_DEFLATED, -12,
1105 585f8587 bellard
                       9, Z_DEFAULT_STRATEGY);
1106 585f8587 bellard
    if (ret != 0) {
1107 585f8587 bellard
        qemu_free(out_buf);
1108 585f8587 bellard
        return -1;
1109 585f8587 bellard
    }
1110 585f8587 bellard
1111 585f8587 bellard
    strm.avail_in = s->cluster_size;
1112 585f8587 bellard
    strm.next_in = (uint8_t *)buf;
1113 585f8587 bellard
    strm.avail_out = s->cluster_size;
1114 585f8587 bellard
    strm.next_out = out_buf;
1115 585f8587 bellard
1116 585f8587 bellard
    ret = deflate(&strm, Z_FINISH);
1117 585f8587 bellard
    if (ret != Z_STREAM_END && ret != Z_OK) {
1118 585f8587 bellard
        qemu_free(out_buf);
1119 585f8587 bellard
        deflateEnd(&strm);
1120 585f8587 bellard
        return -1;
1121 585f8587 bellard
    }
1122 585f8587 bellard
    out_len = strm.next_out - out_buf;
1123 585f8587 bellard
1124 585f8587 bellard
    deflateEnd(&strm);
1125 585f8587 bellard
1126 585f8587 bellard
    if (ret != Z_STREAM_END || out_len >= s->cluster_size) {
1127 585f8587 bellard
        /* could not compress: write normal cluster */
1128 ade40677 Kevin Wolf
        bdrv_write(bs, sector_num, buf, s->cluster_sectors);
1129 585f8587 bellard
    } else {
1130 ed6ccf0f Kevin Wolf
        cluster_offset = qcow2_alloc_compressed_cluster_offset(bs,
1131 ed6ccf0f Kevin Wolf
            sector_num << 9, out_len);
1132 52d893ec aliguori
        if (!cluster_offset)
1133 52d893ec aliguori
            return -1;
1134 585f8587 bellard
        cluster_offset &= s->cluster_offset_mask;
1135 585f8587 bellard
        if (bdrv_pwrite(s->hd, cluster_offset, out_buf, out_len) != out_len) {
1136 585f8587 bellard
            qemu_free(out_buf);
1137 585f8587 bellard
            return -1;
1138 585f8587 bellard
        }
1139 585f8587 bellard
    }
1140 3b46e624 ths
1141 585f8587 bellard
    qemu_free(out_buf);
1142 585f8587 bellard
    return 0;
1143 585f8587 bellard
}
1144 585f8587 bellard
1145 585f8587 bellard
static void qcow_flush(BlockDriverState *bs)
1146 585f8587 bellard
{
1147 585f8587 bellard
    BDRVQcowState *s = bs->opaque;
1148 585f8587 bellard
    bdrv_flush(s->hd);
1149 585f8587 bellard
}
1150 585f8587 bellard
1151 f8012c13 Kevin Wolf
static BlockDriverAIOCB *qcow_aio_flush(BlockDriverState *bs,
1152 f8012c13 Kevin Wolf
         BlockDriverCompletionFunc *cb, void *opaque)
1153 f8012c13 Kevin Wolf
{
1154 f8012c13 Kevin Wolf
     BDRVQcowState *s = bs->opaque;
1155 f8012c13 Kevin Wolf
1156 f8012c13 Kevin Wolf
     return bdrv_aio_flush(s->hd, cb, opaque);
1157 f8012c13 Kevin Wolf
}
1158 f8012c13 Kevin Wolf
1159 45566e9c Christoph Hellwig
static int64_t qcow_vm_state_offset(BDRVQcowState *s)
1160 45566e9c Christoph Hellwig
{
1161 45566e9c Christoph Hellwig
        return (int64_t)s->l1_vm_state_index << (s->cluster_bits + s->l2_bits);
1162 45566e9c Christoph Hellwig
}
1163 45566e9c Christoph Hellwig
1164 585f8587 bellard
static int qcow_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1165 585f8587 bellard
{
1166 585f8587 bellard
    BDRVQcowState *s = bs->opaque;
1167 585f8587 bellard
    bdi->cluster_size = s->cluster_size;
1168 45566e9c Christoph Hellwig
    bdi->vm_state_offset = qcow_vm_state_offset(s);
1169 585f8587 bellard
    return 0;
1170 585f8587 bellard
}
1171 585f8587 bellard
1172 585f8587 bellard
1173 e97fc193 aliguori
static int qcow_check(BlockDriverState *bs)
1174 e97fc193 aliguori
{
1175 ed6ccf0f Kevin Wolf
    return qcow2_check_refcounts(bs);
1176 585f8587 bellard
}
1177 585f8587 bellard
1178 585f8587 bellard
#if 0
1179 585f8587 bellard
static void dump_refcounts(BlockDriverState *bs)
1180 585f8587 bellard
{
1181 585f8587 bellard
    BDRVQcowState *s = bs->opaque;
1182 585f8587 bellard
    int64_t nb_clusters, k, k1, size;
1183 585f8587 bellard
    int refcount;
1184 585f8587 bellard

1185 585f8587 bellard
    size = bdrv_getlength(s->hd);
1186 6db6c638 aliguori
    nb_clusters = size_to_clusters(s, size);
1187 585f8587 bellard
    for(k = 0; k < nb_clusters;) {
1188 585f8587 bellard
        k1 = k;
1189 585f8587 bellard
        refcount = get_refcount(bs, k);
1190 585f8587 bellard
        k++;
1191 585f8587 bellard
        while (k < nb_clusters && get_refcount(bs, k) == refcount)
1192 585f8587 bellard
            k++;
1193 585f8587 bellard
        printf("%lld: refcount=%d nb=%lld\n", k, refcount, k - k1);
1194 585f8587 bellard
    }
1195 585f8587 bellard
}
1196 585f8587 bellard
#endif
1197 585f8587 bellard
1198 45566e9c Christoph Hellwig
static int qcow_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
1199 178e08a5 aliguori
                           int64_t pos, int size)
1200 178e08a5 aliguori
{
1201 45566e9c Christoph Hellwig
    BDRVQcowState *s = bs->opaque;
1202 178e08a5 aliguori
    int growable = bs->growable;
1203 1d36e3aa Kevin Wolf
    int ret;
1204 178e08a5 aliguori
1205 178e08a5 aliguori
    bs->growable = 1;
1206 1d36e3aa Kevin Wolf
    ret = bdrv_pwrite(bs, qcow_vm_state_offset(s) + pos, buf, size);
1207 178e08a5 aliguori
    bs->growable = growable;
1208 178e08a5 aliguori
1209 1d36e3aa Kevin Wolf
    return ret;
1210 178e08a5 aliguori
}
1211 178e08a5 aliguori
1212 45566e9c Christoph Hellwig
static int qcow_load_vmstate(BlockDriverState *bs, uint8_t *buf,
1213 178e08a5 aliguori
                           int64_t pos, int size)
1214 178e08a5 aliguori
{
1215 45566e9c Christoph Hellwig
    BDRVQcowState *s = bs->opaque;
1216 178e08a5 aliguori
    int growable = bs->growable;
1217 178e08a5 aliguori
    int ret;
1218 178e08a5 aliguori
1219 178e08a5 aliguori
    bs->growable = 1;
1220 45566e9c Christoph Hellwig
    ret = bdrv_pread(bs, qcow_vm_state_offset(s) + pos, buf, size);
1221 178e08a5 aliguori
    bs->growable = growable;
1222 178e08a5 aliguori
1223 178e08a5 aliguori
    return ret;
1224 178e08a5 aliguori
}
1225 178e08a5 aliguori
1226 0e7e1989 Kevin Wolf
static QEMUOptionParameter qcow_create_options[] = {
1227 db08adf5 Kevin Wolf
    {
1228 db08adf5 Kevin Wolf
        .name = BLOCK_OPT_SIZE,
1229 db08adf5 Kevin Wolf
        .type = OPT_SIZE,
1230 db08adf5 Kevin Wolf
        .help = "Virtual disk size"
1231 db08adf5 Kevin Wolf
    },
1232 db08adf5 Kevin Wolf
    {
1233 db08adf5 Kevin Wolf
        .name = BLOCK_OPT_BACKING_FILE,
1234 db08adf5 Kevin Wolf
        .type = OPT_STRING,
1235 db08adf5 Kevin Wolf
        .help = "File name of a base image"
1236 db08adf5 Kevin Wolf
    },
1237 db08adf5 Kevin Wolf
    {
1238 db08adf5 Kevin Wolf
        .name = BLOCK_OPT_BACKING_FMT,
1239 db08adf5 Kevin Wolf
        .type = OPT_STRING,
1240 db08adf5 Kevin Wolf
        .help = "Image format of the base image"
1241 db08adf5 Kevin Wolf
    },
1242 db08adf5 Kevin Wolf
    {
1243 db08adf5 Kevin Wolf
        .name = BLOCK_OPT_ENCRYPT,
1244 db08adf5 Kevin Wolf
        .type = OPT_FLAG,
1245 db08adf5 Kevin Wolf
        .help = "Encrypt the image"
1246 db08adf5 Kevin Wolf
    },
1247 db08adf5 Kevin Wolf
    {
1248 db08adf5 Kevin Wolf
        .name = BLOCK_OPT_CLUSTER_SIZE,
1249 db08adf5 Kevin Wolf
        .type = OPT_SIZE,
1250 db08adf5 Kevin Wolf
        .help = "qcow2 cluster size"
1251 db08adf5 Kevin Wolf
    },
1252 a35e1c17 Kevin Wolf
    {
1253 a35e1c17 Kevin Wolf
        .name = BLOCK_OPT_PREALLOC,
1254 a35e1c17 Kevin Wolf
        .type = OPT_STRING,
1255 a35e1c17 Kevin Wolf
        .help = "Preallocation mode (allowed values: off, metadata)"
1256 a35e1c17 Kevin Wolf
    },
1257 0e7e1989 Kevin Wolf
    { NULL }
1258 0e7e1989 Kevin Wolf
};
1259 0e7e1989 Kevin Wolf
1260 5efa9d5a Anthony Liguori
static BlockDriver bdrv_qcow2 = {
1261 e60f469c aurel32
    .format_name        = "qcow2",
1262 e60f469c aurel32
    .instance_size        = sizeof(BDRVQcowState),
1263 e60f469c aurel32
    .bdrv_probe                = qcow_probe,
1264 e60f469c aurel32
    .bdrv_open                = qcow_open,
1265 e60f469c aurel32
    .bdrv_close                = qcow_close,
1266 e60f469c aurel32
    .bdrv_create        = qcow_create,
1267 e60f469c aurel32
    .bdrv_flush                = qcow_flush,
1268 e60f469c aurel32
    .bdrv_is_allocated        = qcow_is_allocated,
1269 e60f469c aurel32
    .bdrv_set_key        = qcow_set_key,
1270 e60f469c aurel32
    .bdrv_make_empty        = qcow_make_empty,
1271 e60f469c aurel32
1272 72ecf02d Kevin Wolf
    .bdrv_aio_readv        = qcow_aio_readv,
1273 72ecf02d Kevin Wolf
    .bdrv_aio_writev        = qcow_aio_writev,
1274 f8012c13 Kevin Wolf
    .bdrv_aio_flush        = qcow_aio_flush,
1275 585f8587 bellard
    .bdrv_write_compressed = qcow_write_compressed,
1276 585f8587 bellard
1277 ed6ccf0f Kevin Wolf
    .bdrv_snapshot_create   = qcow2_snapshot_create,
1278 ed6ccf0f Kevin Wolf
    .bdrv_snapshot_goto     = qcow2_snapshot_goto,
1279 ed6ccf0f Kevin Wolf
    .bdrv_snapshot_delete   = qcow2_snapshot_delete,
1280 ed6ccf0f Kevin Wolf
    .bdrv_snapshot_list     = qcow2_snapshot_list,
1281 e60f469c aurel32
    .bdrv_get_info        = qcow_get_info,
1282 f965509c aliguori
1283 45566e9c Christoph Hellwig
    .bdrv_save_vmstate    = qcow_save_vmstate,
1284 45566e9c Christoph Hellwig
    .bdrv_load_vmstate    = qcow_load_vmstate,
1285 178e08a5 aliguori
1286 756e6736 Kevin Wolf
    .bdrv_change_backing_file   = qcow2_change_backing_file,
1287 756e6736 Kevin Wolf
1288 0e7e1989 Kevin Wolf
    .create_options = qcow_create_options,
1289 e97fc193 aliguori
    .bdrv_check = qcow_check,
1290 585f8587 bellard
};
1291 5efa9d5a Anthony Liguori
1292 5efa9d5a Anthony Liguori
static void bdrv_qcow2_init(void)
1293 5efa9d5a Anthony Liguori
{
1294 5efa9d5a Anthony Liguori
    bdrv_register(&bdrv_qcow2);
1295 5efa9d5a Anthony Liguori
}
1296 5efa9d5a Anthony Liguori
1297 5efa9d5a Anthony Liguori
block_init(bdrv_qcow2_init);