Statistics
| Branch: | Revision:

root / block / qcow2.c @ 6d85a57e

History | View | Annotate | Download (38.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 a9420734 Kevin Wolf
#include "qemu-error.h"
31 585f8587 bellard
32 585f8587 bellard
/*
33 585f8587 bellard
  Differences with QCOW:
34 585f8587 bellard

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

1061 20d97356 Blue Swirl
    memset(s->l1_table, 0, l1_length);
1062 66f82cee Kevin Wolf
    if (bdrv_pwrite(bs->file, s->l1_table_offset, s->l1_table, l1_length) < 0)
1063 20d97356 Blue Swirl
        return -1;
1064 66f82cee Kevin Wolf
    ret = bdrv_truncate(bs->file, s->l1_table_offset + l1_length);
1065 20d97356 Blue Swirl
    if (ret < 0)
1066 20d97356 Blue Swirl
        return ret;
1067 20d97356 Blue Swirl

1068 20d97356 Blue Swirl
    l2_cache_reset(bs);
1069 20d97356 Blue Swirl
#endif
1070 20d97356 Blue Swirl
    return 0;
1071 20d97356 Blue Swirl
}
1072 20d97356 Blue Swirl
1073 419b19d9 Stefan Hajnoczi
static int qcow2_truncate(BlockDriverState *bs, int64_t offset)
1074 419b19d9 Stefan Hajnoczi
{
1075 419b19d9 Stefan Hajnoczi
    BDRVQcowState *s = bs->opaque;
1076 419b19d9 Stefan Hajnoczi
    int ret, new_l1_size;
1077 419b19d9 Stefan Hajnoczi
1078 419b19d9 Stefan Hajnoczi
    if (offset & 511) {
1079 419b19d9 Stefan Hajnoczi
        return -EINVAL;
1080 419b19d9 Stefan Hajnoczi
    }
1081 419b19d9 Stefan Hajnoczi
1082 419b19d9 Stefan Hajnoczi
    /* cannot proceed if image has snapshots */
1083 419b19d9 Stefan Hajnoczi
    if (s->nb_snapshots) {
1084 419b19d9 Stefan Hajnoczi
        return -ENOTSUP;
1085 419b19d9 Stefan Hajnoczi
    }
1086 419b19d9 Stefan Hajnoczi
1087 419b19d9 Stefan Hajnoczi
    /* shrinking is currently not supported */
1088 419b19d9 Stefan Hajnoczi
    if (offset < bs->total_sectors * 512) {
1089 419b19d9 Stefan Hajnoczi
        return -ENOTSUP;
1090 419b19d9 Stefan Hajnoczi
    }
1091 419b19d9 Stefan Hajnoczi
1092 419b19d9 Stefan Hajnoczi
    new_l1_size = size_to_l1(s, offset);
1093 72893756 Stefan Hajnoczi
    ret = qcow2_grow_l1_table(bs, new_l1_size, true);
1094 419b19d9 Stefan Hajnoczi
    if (ret < 0) {
1095 419b19d9 Stefan Hajnoczi
        return ret;
1096 419b19d9 Stefan Hajnoczi
    }
1097 419b19d9 Stefan Hajnoczi
1098 419b19d9 Stefan Hajnoczi
    /* write updated header.size */
1099 419b19d9 Stefan Hajnoczi
    offset = cpu_to_be64(offset);
1100 8b3b7206 Kevin Wolf
    ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, size),
1101 8b3b7206 Kevin Wolf
                           &offset, sizeof(uint64_t));
1102 419b19d9 Stefan Hajnoczi
    if (ret < 0) {
1103 419b19d9 Stefan Hajnoczi
        return ret;
1104 419b19d9 Stefan Hajnoczi
    }
1105 419b19d9 Stefan Hajnoczi
1106 419b19d9 Stefan Hajnoczi
    s->l1_vm_state_index = new_l1_size;
1107 419b19d9 Stefan Hajnoczi
    return 0;
1108 419b19d9 Stefan Hajnoczi
}
1109 419b19d9 Stefan Hajnoczi
1110 20d97356 Blue Swirl
/* XXX: put compressed sectors first, then all the cluster aligned
1111 20d97356 Blue Swirl
   tables to avoid losing bytes in alignment */
1112 7c80ab3f Jes Sorensen
static int qcow2_write_compressed(BlockDriverState *bs, int64_t sector_num,
1113 7c80ab3f Jes Sorensen
                                  const uint8_t *buf, int nb_sectors)
1114 20d97356 Blue Swirl
{
1115 20d97356 Blue Swirl
    BDRVQcowState *s = bs->opaque;
1116 20d97356 Blue Swirl
    z_stream strm;
1117 20d97356 Blue Swirl
    int ret, out_len;
1118 20d97356 Blue Swirl
    uint8_t *out_buf;
1119 20d97356 Blue Swirl
    uint64_t cluster_offset;
1120 20d97356 Blue Swirl
1121 20d97356 Blue Swirl
    if (nb_sectors == 0) {
1122 20d97356 Blue Swirl
        /* align end of file to a sector boundary to ease reading with
1123 20d97356 Blue Swirl
           sector based I/Os */
1124 66f82cee Kevin Wolf
        cluster_offset = bdrv_getlength(bs->file);
1125 20d97356 Blue Swirl
        cluster_offset = (cluster_offset + 511) & ~511;
1126 66f82cee Kevin Wolf
        bdrv_truncate(bs->file, cluster_offset);
1127 20d97356 Blue Swirl
        return 0;
1128 20d97356 Blue Swirl
    }
1129 20d97356 Blue Swirl
1130 20d97356 Blue Swirl
    if (nb_sectors != s->cluster_sectors)
1131 20d97356 Blue Swirl
        return -EINVAL;
1132 20d97356 Blue Swirl
1133 20d97356 Blue Swirl
    out_buf = qemu_malloc(s->cluster_size + (s->cluster_size / 1000) + 128);
1134 20d97356 Blue Swirl
1135 20d97356 Blue Swirl
    /* best compression, small window, no zlib header */
1136 20d97356 Blue Swirl
    memset(&strm, 0, sizeof(strm));
1137 20d97356 Blue Swirl
    ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
1138 20d97356 Blue Swirl
                       Z_DEFLATED, -12,
1139 20d97356 Blue Swirl
                       9, Z_DEFAULT_STRATEGY);
1140 20d97356 Blue Swirl
    if (ret != 0) {
1141 20d97356 Blue Swirl
        qemu_free(out_buf);
1142 20d97356 Blue Swirl
        return -1;
1143 20d97356 Blue Swirl
    }
1144 20d97356 Blue Swirl
1145 20d97356 Blue Swirl
    strm.avail_in = s->cluster_size;
1146 20d97356 Blue Swirl
    strm.next_in = (uint8_t *)buf;
1147 20d97356 Blue Swirl
    strm.avail_out = s->cluster_size;
1148 20d97356 Blue Swirl
    strm.next_out = out_buf;
1149 20d97356 Blue Swirl
1150 20d97356 Blue Swirl
    ret = deflate(&strm, Z_FINISH);
1151 20d97356 Blue Swirl
    if (ret != Z_STREAM_END && ret != Z_OK) {
1152 20d97356 Blue Swirl
        qemu_free(out_buf);
1153 20d97356 Blue Swirl
        deflateEnd(&strm);
1154 20d97356 Blue Swirl
        return -1;
1155 20d97356 Blue Swirl
    }
1156 20d97356 Blue Swirl
    out_len = strm.next_out - out_buf;
1157 20d97356 Blue Swirl
1158 20d97356 Blue Swirl
    deflateEnd(&strm);
1159 20d97356 Blue Swirl
1160 20d97356 Blue Swirl
    if (ret != Z_STREAM_END || out_len >= s->cluster_size) {
1161 20d97356 Blue Swirl
        /* could not compress: write normal cluster */
1162 20d97356 Blue Swirl
        bdrv_write(bs, sector_num, buf, s->cluster_sectors);
1163 20d97356 Blue Swirl
    } else {
1164 20d97356 Blue Swirl
        cluster_offset = qcow2_alloc_compressed_cluster_offset(bs,
1165 20d97356 Blue Swirl
            sector_num << 9, out_len);
1166 20d97356 Blue Swirl
        if (!cluster_offset)
1167 20d97356 Blue Swirl
            return -1;
1168 20d97356 Blue Swirl
        cluster_offset &= s->cluster_offset_mask;
1169 66f82cee Kevin Wolf
        BLKDBG_EVENT(bs->file, BLKDBG_WRITE_COMPRESSED);
1170 66f82cee Kevin Wolf
        if (bdrv_pwrite(bs->file, cluster_offset, out_buf, out_len) != out_len) {
1171 20d97356 Blue Swirl
            qemu_free(out_buf);
1172 20d97356 Blue Swirl
            return -1;
1173 20d97356 Blue Swirl
        }
1174 20d97356 Blue Swirl
    }
1175 20d97356 Blue Swirl
1176 20d97356 Blue Swirl
    qemu_free(out_buf);
1177 20d97356 Blue Swirl
    return 0;
1178 20d97356 Blue Swirl
}
1179 20d97356 Blue Swirl
1180 7c80ab3f Jes Sorensen
static int qcow2_flush(BlockDriverState *bs)
1181 20d97356 Blue Swirl
{
1182 205ef796 Kevin Wolf
    return bdrv_flush(bs->file);
1183 20d97356 Blue Swirl
}
1184 20d97356 Blue Swirl
1185 7c80ab3f Jes Sorensen
static BlockDriverAIOCB *qcow2_aio_flush(BlockDriverState *bs,
1186 7c80ab3f Jes Sorensen
                                         BlockDriverCompletionFunc *cb,
1187 7c80ab3f Jes Sorensen
                                         void *opaque)
1188 20d97356 Blue Swirl
{
1189 66f82cee Kevin Wolf
    return bdrv_aio_flush(bs->file, cb, opaque);
1190 20d97356 Blue Swirl
}
1191 20d97356 Blue Swirl
1192 7c80ab3f Jes Sorensen
static int64_t qcow2_vm_state_offset(BDRVQcowState *s)
1193 20d97356 Blue Swirl
{
1194 20d97356 Blue Swirl
        return (int64_t)s->l1_vm_state_index << (s->cluster_bits + s->l2_bits);
1195 20d97356 Blue Swirl
}
1196 20d97356 Blue Swirl
1197 7c80ab3f Jes Sorensen
static int qcow2_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1198 20d97356 Blue Swirl
{
1199 20d97356 Blue Swirl
    BDRVQcowState *s = bs->opaque;
1200 20d97356 Blue Swirl
    bdi->cluster_size = s->cluster_size;
1201 7c80ab3f Jes Sorensen
    bdi->vm_state_offset = qcow2_vm_state_offset(s);
1202 20d97356 Blue Swirl
    return 0;
1203 20d97356 Blue Swirl
}
1204 20d97356 Blue Swirl
1205 20d97356 Blue Swirl
1206 7c80ab3f Jes Sorensen
static int qcow2_check(BlockDriverState *bs, BdrvCheckResult *result)
1207 20d97356 Blue Swirl
{
1208 9ac228e0 Kevin Wolf
    return qcow2_check_refcounts(bs, result);
1209 20d97356 Blue Swirl
}
1210 20d97356 Blue Swirl
1211 20d97356 Blue Swirl
#if 0
1212 20d97356 Blue Swirl
static void dump_refcounts(BlockDriverState *bs)
1213 20d97356 Blue Swirl
{
1214 20d97356 Blue Swirl
    BDRVQcowState *s = bs->opaque;
1215 20d97356 Blue Swirl
    int64_t nb_clusters, k, k1, size;
1216 20d97356 Blue Swirl
    int refcount;
1217 20d97356 Blue Swirl

1218 66f82cee Kevin Wolf
    size = bdrv_getlength(bs->file);
1219 20d97356 Blue Swirl
    nb_clusters = size_to_clusters(s, size);
1220 20d97356 Blue Swirl
    for(k = 0; k < nb_clusters;) {
1221 20d97356 Blue Swirl
        k1 = k;
1222 20d97356 Blue Swirl
        refcount = get_refcount(bs, k);
1223 20d97356 Blue Swirl
        k++;
1224 20d97356 Blue Swirl
        while (k < nb_clusters && get_refcount(bs, k) == refcount)
1225 20d97356 Blue Swirl
            k++;
1226 0bfcd599 Blue Swirl
        printf("%" PRId64 ": refcount=%d nb=%" PRId64 "\n", k, refcount,
1227 0bfcd599 Blue Swirl
               k - k1);
1228 20d97356 Blue Swirl
    }
1229 20d97356 Blue Swirl
}
1230 20d97356 Blue Swirl
#endif
1231 20d97356 Blue Swirl
1232 7c80ab3f Jes Sorensen
static int qcow2_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
1233 7c80ab3f Jes Sorensen
                              int64_t pos, int size)
1234 20d97356 Blue Swirl
{
1235 20d97356 Blue Swirl
    BDRVQcowState *s = bs->opaque;
1236 20d97356 Blue Swirl
    int growable = bs->growable;
1237 20d97356 Blue Swirl
    int ret;
1238 20d97356 Blue Swirl
1239 66f82cee Kevin Wolf
    BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_SAVE);
1240 20d97356 Blue Swirl
    bs->growable = 1;
1241 7c80ab3f Jes Sorensen
    ret = bdrv_pwrite(bs, qcow2_vm_state_offset(s) + pos, buf, size);
1242 20d97356 Blue Swirl
    bs->growable = growable;
1243 20d97356 Blue Swirl
1244 20d97356 Blue Swirl
    return ret;
1245 20d97356 Blue Swirl
}
1246 20d97356 Blue Swirl
1247 7c80ab3f Jes Sorensen
static int qcow2_load_vmstate(BlockDriverState *bs, uint8_t *buf,
1248 7c80ab3f Jes Sorensen
                              int64_t pos, int size)
1249 20d97356 Blue Swirl
{
1250 20d97356 Blue Swirl
    BDRVQcowState *s = bs->opaque;
1251 20d97356 Blue Swirl
    int growable = bs->growable;
1252 20d97356 Blue Swirl
    int ret;
1253 20d97356 Blue Swirl
1254 66f82cee Kevin Wolf
    BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_LOAD);
1255 20d97356 Blue Swirl
    bs->growable = 1;
1256 7c80ab3f Jes Sorensen
    ret = bdrv_pread(bs, qcow2_vm_state_offset(s) + pos, buf, size);
1257 20d97356 Blue Swirl
    bs->growable = growable;
1258 20d97356 Blue Swirl
1259 20d97356 Blue Swirl
    return ret;
1260 20d97356 Blue Swirl
}
1261 20d97356 Blue Swirl
1262 7c80ab3f Jes Sorensen
static QEMUOptionParameter qcow2_create_options[] = {
1263 20d97356 Blue Swirl
    {
1264 20d97356 Blue Swirl
        .name = BLOCK_OPT_SIZE,
1265 20d97356 Blue Swirl
        .type = OPT_SIZE,
1266 20d97356 Blue Swirl
        .help = "Virtual disk size"
1267 20d97356 Blue Swirl
    },
1268 20d97356 Blue Swirl
    {
1269 20d97356 Blue Swirl
        .name = BLOCK_OPT_BACKING_FILE,
1270 20d97356 Blue Swirl
        .type = OPT_STRING,
1271 20d97356 Blue Swirl
        .help = "File name of a base image"
1272 20d97356 Blue Swirl
    },
1273 20d97356 Blue Swirl
    {
1274 20d97356 Blue Swirl
        .name = BLOCK_OPT_BACKING_FMT,
1275 20d97356 Blue Swirl
        .type = OPT_STRING,
1276 20d97356 Blue Swirl
        .help = "Image format of the base image"
1277 20d97356 Blue Swirl
    },
1278 20d97356 Blue Swirl
    {
1279 20d97356 Blue Swirl
        .name = BLOCK_OPT_ENCRYPT,
1280 20d97356 Blue Swirl
        .type = OPT_FLAG,
1281 20d97356 Blue Swirl
        .help = "Encrypt the image"
1282 20d97356 Blue Swirl
    },
1283 20d97356 Blue Swirl
    {
1284 20d97356 Blue Swirl
        .name = BLOCK_OPT_CLUSTER_SIZE,
1285 20d97356 Blue Swirl
        .type = OPT_SIZE,
1286 20d97356 Blue Swirl
        .help = "qcow2 cluster size"
1287 20d97356 Blue Swirl
    },
1288 20d97356 Blue Swirl
    {
1289 20d97356 Blue Swirl
        .name = BLOCK_OPT_PREALLOC,
1290 20d97356 Blue Swirl
        .type = OPT_STRING,
1291 20d97356 Blue Swirl
        .help = "Preallocation mode (allowed values: off, metadata)"
1292 20d97356 Blue Swirl
    },
1293 20d97356 Blue Swirl
    { NULL }
1294 20d97356 Blue Swirl
};
1295 20d97356 Blue Swirl
1296 20d97356 Blue Swirl
static BlockDriver bdrv_qcow2 = {
1297 7c80ab3f Jes Sorensen
    .format_name        = "qcow2",
1298 7c80ab3f Jes Sorensen
    .instance_size      = sizeof(BDRVQcowState),
1299 7c80ab3f Jes Sorensen
    .bdrv_probe         = qcow2_probe,
1300 7c80ab3f Jes Sorensen
    .bdrv_open          = qcow2_open,
1301 7c80ab3f Jes Sorensen
    .bdrv_close         = qcow2_close,
1302 7c80ab3f Jes Sorensen
    .bdrv_create        = qcow2_create,
1303 7c80ab3f Jes Sorensen
    .bdrv_flush         = qcow2_flush,
1304 7c80ab3f Jes Sorensen
    .bdrv_is_allocated  = qcow2_is_allocated,
1305 7c80ab3f Jes Sorensen
    .bdrv_set_key       = qcow2_set_key,
1306 7c80ab3f Jes Sorensen
    .bdrv_make_empty    = qcow2_make_empty,
1307 7c80ab3f Jes Sorensen
1308 7c80ab3f Jes Sorensen
    .bdrv_aio_readv     = qcow2_aio_readv,
1309 7c80ab3f Jes Sorensen
    .bdrv_aio_writev    = qcow2_aio_writev,
1310 7c80ab3f Jes Sorensen
    .bdrv_aio_flush     = qcow2_aio_flush,
1311 419b19d9 Stefan Hajnoczi
1312 419b19d9 Stefan Hajnoczi
    .bdrv_truncate          = qcow2_truncate,
1313 7c80ab3f Jes Sorensen
    .bdrv_write_compressed  = qcow2_write_compressed,
1314 20d97356 Blue Swirl
1315 20d97356 Blue Swirl
    .bdrv_snapshot_create   = qcow2_snapshot_create,
1316 20d97356 Blue Swirl
    .bdrv_snapshot_goto     = qcow2_snapshot_goto,
1317 20d97356 Blue Swirl
    .bdrv_snapshot_delete   = qcow2_snapshot_delete,
1318 20d97356 Blue Swirl
    .bdrv_snapshot_list     = qcow2_snapshot_list,
1319 51ef6727 edison
    .bdrv_snapshot_load_tmp     = qcow2_snapshot_load_tmp,
1320 7c80ab3f Jes Sorensen
    .bdrv_get_info      = qcow2_get_info,
1321 20d97356 Blue Swirl
1322 7c80ab3f Jes Sorensen
    .bdrv_save_vmstate    = qcow2_save_vmstate,
1323 7c80ab3f Jes Sorensen
    .bdrv_load_vmstate    = qcow2_load_vmstate,
1324 20d97356 Blue Swirl
1325 20d97356 Blue Swirl
    .bdrv_change_backing_file   = qcow2_change_backing_file,
1326 20d97356 Blue Swirl
1327 7c80ab3f Jes Sorensen
    .create_options = qcow2_create_options,
1328 7c80ab3f Jes Sorensen
    .bdrv_check = qcow2_check,
1329 20d97356 Blue Swirl
};
1330 20d97356 Blue Swirl
1331 5efa9d5a Anthony Liguori
static void bdrv_qcow2_init(void)
1332 5efa9d5a Anthony Liguori
{
1333 5efa9d5a Anthony Liguori
    bdrv_register(&bdrv_qcow2);
1334 5efa9d5a Anthony Liguori
}
1335 5efa9d5a Anthony Liguori
1336 5efa9d5a Anthony Liguori
block_init(bdrv_qcow2_init);