Statistics
| Branch: | Revision:

root / block / qcow2.c @ 528f7663

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

1098 20d97356 Blue Swirl
    memset(s->l1_table, 0, l1_length);
1099 66f82cee Kevin Wolf
    if (bdrv_pwrite(bs->file, s->l1_table_offset, s->l1_table, l1_length) < 0)
1100 20d97356 Blue Swirl
        return -1;
1101 66f82cee Kevin Wolf
    ret = bdrv_truncate(bs->file, s->l1_table_offset + l1_length);
1102 20d97356 Blue Swirl
    if (ret < 0)
1103 20d97356 Blue Swirl
        return ret;
1104 20d97356 Blue Swirl

1105 20d97356 Blue Swirl
    l2_cache_reset(bs);
1106 20d97356 Blue Swirl
#endif
1107 20d97356 Blue Swirl
    return 0;
1108 20d97356 Blue Swirl
}
1109 20d97356 Blue Swirl
1110 419b19d9 Stefan Hajnoczi
static int qcow2_truncate(BlockDriverState *bs, int64_t offset)
1111 419b19d9 Stefan Hajnoczi
{
1112 419b19d9 Stefan Hajnoczi
    BDRVQcowState *s = bs->opaque;
1113 419b19d9 Stefan Hajnoczi
    int ret, new_l1_size;
1114 419b19d9 Stefan Hajnoczi
1115 419b19d9 Stefan Hajnoczi
    if (offset & 511) {
1116 419b19d9 Stefan Hajnoczi
        return -EINVAL;
1117 419b19d9 Stefan Hajnoczi
    }
1118 419b19d9 Stefan Hajnoczi
1119 419b19d9 Stefan Hajnoczi
    /* cannot proceed if image has snapshots */
1120 419b19d9 Stefan Hajnoczi
    if (s->nb_snapshots) {
1121 419b19d9 Stefan Hajnoczi
        return -ENOTSUP;
1122 419b19d9 Stefan Hajnoczi
    }
1123 419b19d9 Stefan Hajnoczi
1124 419b19d9 Stefan Hajnoczi
    /* shrinking is currently not supported */
1125 419b19d9 Stefan Hajnoczi
    if (offset < bs->total_sectors * 512) {
1126 419b19d9 Stefan Hajnoczi
        return -ENOTSUP;
1127 419b19d9 Stefan Hajnoczi
    }
1128 419b19d9 Stefan Hajnoczi
1129 419b19d9 Stefan Hajnoczi
    new_l1_size = size_to_l1(s, offset);
1130 419b19d9 Stefan Hajnoczi
    ret = qcow2_grow_l1_table(bs, new_l1_size);
1131 419b19d9 Stefan Hajnoczi
    if (ret < 0) {
1132 419b19d9 Stefan Hajnoczi
        return ret;
1133 419b19d9 Stefan Hajnoczi
    }
1134 419b19d9 Stefan Hajnoczi
1135 419b19d9 Stefan Hajnoczi
    /* write updated header.size */
1136 419b19d9 Stefan Hajnoczi
    offset = cpu_to_be64(offset);
1137 8b3b7206 Kevin Wolf
    ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, size),
1138 8b3b7206 Kevin Wolf
                           &offset, sizeof(uint64_t));
1139 419b19d9 Stefan Hajnoczi
    if (ret < 0) {
1140 419b19d9 Stefan Hajnoczi
        return ret;
1141 419b19d9 Stefan Hajnoczi
    }
1142 419b19d9 Stefan Hajnoczi
1143 419b19d9 Stefan Hajnoczi
    s->l1_vm_state_index = new_l1_size;
1144 419b19d9 Stefan Hajnoczi
    return 0;
1145 419b19d9 Stefan Hajnoczi
}
1146 419b19d9 Stefan Hajnoczi
1147 20d97356 Blue Swirl
/* XXX: put compressed sectors first, then all the cluster aligned
1148 20d97356 Blue Swirl
   tables to avoid losing bytes in alignment */
1149 20d97356 Blue Swirl
static int qcow_write_compressed(BlockDriverState *bs, int64_t sector_num,
1150 20d97356 Blue Swirl
                                 const uint8_t *buf, int nb_sectors)
1151 20d97356 Blue Swirl
{
1152 20d97356 Blue Swirl
    BDRVQcowState *s = bs->opaque;
1153 20d97356 Blue Swirl
    z_stream strm;
1154 20d97356 Blue Swirl
    int ret, out_len;
1155 20d97356 Blue Swirl
    uint8_t *out_buf;
1156 20d97356 Blue Swirl
    uint64_t cluster_offset;
1157 20d97356 Blue Swirl
1158 20d97356 Blue Swirl
    if (nb_sectors == 0) {
1159 20d97356 Blue Swirl
        /* align end of file to a sector boundary to ease reading with
1160 20d97356 Blue Swirl
           sector based I/Os */
1161 66f82cee Kevin Wolf
        cluster_offset = bdrv_getlength(bs->file);
1162 20d97356 Blue Swirl
        cluster_offset = (cluster_offset + 511) & ~511;
1163 66f82cee Kevin Wolf
        bdrv_truncate(bs->file, cluster_offset);
1164 20d97356 Blue Swirl
        return 0;
1165 20d97356 Blue Swirl
    }
1166 20d97356 Blue Swirl
1167 20d97356 Blue Swirl
    if (nb_sectors != s->cluster_sectors)
1168 20d97356 Blue Swirl
        return -EINVAL;
1169 20d97356 Blue Swirl
1170 20d97356 Blue Swirl
    out_buf = qemu_malloc(s->cluster_size + (s->cluster_size / 1000) + 128);
1171 20d97356 Blue Swirl
1172 20d97356 Blue Swirl
    /* best compression, small window, no zlib header */
1173 20d97356 Blue Swirl
    memset(&strm, 0, sizeof(strm));
1174 20d97356 Blue Swirl
    ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
1175 20d97356 Blue Swirl
                       Z_DEFLATED, -12,
1176 20d97356 Blue Swirl
                       9, Z_DEFAULT_STRATEGY);
1177 20d97356 Blue Swirl
    if (ret != 0) {
1178 20d97356 Blue Swirl
        qemu_free(out_buf);
1179 20d97356 Blue Swirl
        return -1;
1180 20d97356 Blue Swirl
    }
1181 20d97356 Blue Swirl
1182 20d97356 Blue Swirl
    strm.avail_in = s->cluster_size;
1183 20d97356 Blue Swirl
    strm.next_in = (uint8_t *)buf;
1184 20d97356 Blue Swirl
    strm.avail_out = s->cluster_size;
1185 20d97356 Blue Swirl
    strm.next_out = out_buf;
1186 20d97356 Blue Swirl
1187 20d97356 Blue Swirl
    ret = deflate(&strm, Z_FINISH);
1188 20d97356 Blue Swirl
    if (ret != Z_STREAM_END && ret != Z_OK) {
1189 20d97356 Blue Swirl
        qemu_free(out_buf);
1190 20d97356 Blue Swirl
        deflateEnd(&strm);
1191 20d97356 Blue Swirl
        return -1;
1192 20d97356 Blue Swirl
    }
1193 20d97356 Blue Swirl
    out_len = strm.next_out - out_buf;
1194 20d97356 Blue Swirl
1195 20d97356 Blue Swirl
    deflateEnd(&strm);
1196 20d97356 Blue Swirl
1197 20d97356 Blue Swirl
    if (ret != Z_STREAM_END || out_len >= s->cluster_size) {
1198 20d97356 Blue Swirl
        /* could not compress: write normal cluster */
1199 20d97356 Blue Swirl
        bdrv_write(bs, sector_num, buf, s->cluster_sectors);
1200 20d97356 Blue Swirl
    } else {
1201 20d97356 Blue Swirl
        cluster_offset = qcow2_alloc_compressed_cluster_offset(bs,
1202 20d97356 Blue Swirl
            sector_num << 9, out_len);
1203 20d97356 Blue Swirl
        if (!cluster_offset)
1204 20d97356 Blue Swirl
            return -1;
1205 20d97356 Blue Swirl
        cluster_offset &= s->cluster_offset_mask;
1206 66f82cee Kevin Wolf
        BLKDBG_EVENT(bs->file, BLKDBG_WRITE_COMPRESSED);
1207 66f82cee Kevin Wolf
        if (bdrv_pwrite(bs->file, cluster_offset, out_buf, out_len) != out_len) {
1208 20d97356 Blue Swirl
            qemu_free(out_buf);
1209 20d97356 Blue Swirl
            return -1;
1210 20d97356 Blue Swirl
        }
1211 20d97356 Blue Swirl
    }
1212 20d97356 Blue Swirl
1213 20d97356 Blue Swirl
    qemu_free(out_buf);
1214 20d97356 Blue Swirl
    return 0;
1215 20d97356 Blue Swirl
}
1216 20d97356 Blue Swirl
1217 20d97356 Blue Swirl
static void qcow_flush(BlockDriverState *bs)
1218 20d97356 Blue Swirl
{
1219 66f82cee Kevin Wolf
    bdrv_flush(bs->file);
1220 20d97356 Blue Swirl
}
1221 20d97356 Blue Swirl
1222 20d97356 Blue Swirl
static BlockDriverAIOCB *qcow_aio_flush(BlockDriverState *bs,
1223 20d97356 Blue Swirl
         BlockDriverCompletionFunc *cb, void *opaque)
1224 20d97356 Blue Swirl
{
1225 66f82cee Kevin Wolf
    return bdrv_aio_flush(bs->file, cb, opaque);
1226 20d97356 Blue Swirl
}
1227 20d97356 Blue Swirl
1228 20d97356 Blue Swirl
static int64_t qcow_vm_state_offset(BDRVQcowState *s)
1229 20d97356 Blue Swirl
{
1230 20d97356 Blue Swirl
        return (int64_t)s->l1_vm_state_index << (s->cluster_bits + s->l2_bits);
1231 20d97356 Blue Swirl
}
1232 20d97356 Blue Swirl
1233 20d97356 Blue Swirl
static int qcow_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1234 20d97356 Blue Swirl
{
1235 20d97356 Blue Swirl
    BDRVQcowState *s = bs->opaque;
1236 20d97356 Blue Swirl
    bdi->cluster_size = s->cluster_size;
1237 20d97356 Blue Swirl
    bdi->vm_state_offset = qcow_vm_state_offset(s);
1238 20d97356 Blue Swirl
    return 0;
1239 20d97356 Blue Swirl
}
1240 20d97356 Blue Swirl
1241 20d97356 Blue Swirl
1242 9ac228e0 Kevin Wolf
static int qcow_check(BlockDriverState *bs, BdrvCheckResult *result)
1243 20d97356 Blue Swirl
{
1244 9ac228e0 Kevin Wolf
    return qcow2_check_refcounts(bs, result);
1245 20d97356 Blue Swirl
}
1246 20d97356 Blue Swirl
1247 20d97356 Blue Swirl
#if 0
1248 20d97356 Blue Swirl
static void dump_refcounts(BlockDriverState *bs)
1249 20d97356 Blue Swirl
{
1250 20d97356 Blue Swirl
    BDRVQcowState *s = bs->opaque;
1251 20d97356 Blue Swirl
    int64_t nb_clusters, k, k1, size;
1252 20d97356 Blue Swirl
    int refcount;
1253 20d97356 Blue Swirl

1254 66f82cee Kevin Wolf
    size = bdrv_getlength(bs->file);
1255 20d97356 Blue Swirl
    nb_clusters = size_to_clusters(s, size);
1256 20d97356 Blue Swirl
    for(k = 0; k < nb_clusters;) {
1257 20d97356 Blue Swirl
        k1 = k;
1258 20d97356 Blue Swirl
        refcount = get_refcount(bs, k);
1259 20d97356 Blue Swirl
        k++;
1260 20d97356 Blue Swirl
        while (k < nb_clusters && get_refcount(bs, k) == refcount)
1261 20d97356 Blue Swirl
            k++;
1262 0bfcd599 Blue Swirl
        printf("%" PRId64 ": refcount=%d nb=%" PRId64 "\n", k, refcount,
1263 0bfcd599 Blue Swirl
               k - k1);
1264 20d97356 Blue Swirl
    }
1265 20d97356 Blue Swirl
}
1266 20d97356 Blue Swirl
#endif
1267 20d97356 Blue Swirl
1268 20d97356 Blue Swirl
static int qcow_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
1269 20d97356 Blue Swirl
                           int64_t pos, int size)
1270 20d97356 Blue Swirl
{
1271 20d97356 Blue Swirl
    BDRVQcowState *s = bs->opaque;
1272 20d97356 Blue Swirl
    int growable = bs->growable;
1273 20d97356 Blue Swirl
    int ret;
1274 20d97356 Blue Swirl
1275 66f82cee Kevin Wolf
    BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_SAVE);
1276 20d97356 Blue Swirl
    bs->growable = 1;
1277 20d97356 Blue Swirl
    ret = bdrv_pwrite(bs, qcow_vm_state_offset(s) + pos, buf, size);
1278 20d97356 Blue Swirl
    bs->growable = growable;
1279 20d97356 Blue Swirl
1280 20d97356 Blue Swirl
    return ret;
1281 20d97356 Blue Swirl
}
1282 20d97356 Blue Swirl
1283 20d97356 Blue Swirl
static int qcow_load_vmstate(BlockDriverState *bs, uint8_t *buf,
1284 20d97356 Blue Swirl
                           int64_t pos, int size)
1285 20d97356 Blue Swirl
{
1286 20d97356 Blue Swirl
    BDRVQcowState *s = bs->opaque;
1287 20d97356 Blue Swirl
    int growable = bs->growable;
1288 20d97356 Blue Swirl
    int ret;
1289 20d97356 Blue Swirl
1290 66f82cee Kevin Wolf
    BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_LOAD);
1291 20d97356 Blue Swirl
    bs->growable = 1;
1292 20d97356 Blue Swirl
    ret = bdrv_pread(bs, qcow_vm_state_offset(s) + pos, buf, size);
1293 20d97356 Blue Swirl
    bs->growable = growable;
1294 20d97356 Blue Swirl
1295 20d97356 Blue Swirl
    return ret;
1296 20d97356 Blue Swirl
}
1297 20d97356 Blue Swirl
1298 20d97356 Blue Swirl
static QEMUOptionParameter qcow_create_options[] = {
1299 20d97356 Blue Swirl
    {
1300 20d97356 Blue Swirl
        .name = BLOCK_OPT_SIZE,
1301 20d97356 Blue Swirl
        .type = OPT_SIZE,
1302 20d97356 Blue Swirl
        .help = "Virtual disk size"
1303 20d97356 Blue Swirl
    },
1304 20d97356 Blue Swirl
    {
1305 20d97356 Blue Swirl
        .name = BLOCK_OPT_BACKING_FILE,
1306 20d97356 Blue Swirl
        .type = OPT_STRING,
1307 20d97356 Blue Swirl
        .help = "File name of a base image"
1308 20d97356 Blue Swirl
    },
1309 20d97356 Blue Swirl
    {
1310 20d97356 Blue Swirl
        .name = BLOCK_OPT_BACKING_FMT,
1311 20d97356 Blue Swirl
        .type = OPT_STRING,
1312 20d97356 Blue Swirl
        .help = "Image format of the base image"
1313 20d97356 Blue Swirl
    },
1314 20d97356 Blue Swirl
    {
1315 20d97356 Blue Swirl
        .name = BLOCK_OPT_ENCRYPT,
1316 20d97356 Blue Swirl
        .type = OPT_FLAG,
1317 20d97356 Blue Swirl
        .help = "Encrypt the image"
1318 20d97356 Blue Swirl
    },
1319 20d97356 Blue Swirl
    {
1320 20d97356 Blue Swirl
        .name = BLOCK_OPT_CLUSTER_SIZE,
1321 20d97356 Blue Swirl
        .type = OPT_SIZE,
1322 20d97356 Blue Swirl
        .help = "qcow2 cluster size"
1323 20d97356 Blue Swirl
    },
1324 20d97356 Blue Swirl
    {
1325 20d97356 Blue Swirl
        .name = BLOCK_OPT_PREALLOC,
1326 20d97356 Blue Swirl
        .type = OPT_STRING,
1327 20d97356 Blue Swirl
        .help = "Preallocation mode (allowed values: off, metadata)"
1328 20d97356 Blue Swirl
    },
1329 20d97356 Blue Swirl
    { NULL }
1330 20d97356 Blue Swirl
};
1331 20d97356 Blue Swirl
1332 20d97356 Blue Swirl
static BlockDriver bdrv_qcow2 = {
1333 20d97356 Blue Swirl
    .format_name        = "qcow2",
1334 20d97356 Blue Swirl
    .instance_size        = sizeof(BDRVQcowState),
1335 20d97356 Blue Swirl
    .bdrv_probe                = qcow_probe,
1336 20d97356 Blue Swirl
    .bdrv_open                = qcow_open,
1337 20d97356 Blue Swirl
    .bdrv_close                = qcow_close,
1338 20d97356 Blue Swirl
    .bdrv_create        = qcow_create,
1339 20d97356 Blue Swirl
    .bdrv_flush                = qcow_flush,
1340 20d97356 Blue Swirl
    .bdrv_is_allocated        = qcow_is_allocated,
1341 20d97356 Blue Swirl
    .bdrv_set_key        = qcow_set_key,
1342 20d97356 Blue Swirl
    .bdrv_make_empty        = qcow_make_empty,
1343 20d97356 Blue Swirl
1344 20d97356 Blue Swirl
    .bdrv_aio_readv        = qcow_aio_readv,
1345 20d97356 Blue Swirl
    .bdrv_aio_writev        = qcow_aio_writev,
1346 20d97356 Blue Swirl
    .bdrv_aio_flush        = qcow_aio_flush,
1347 419b19d9 Stefan Hajnoczi
1348 419b19d9 Stefan Hajnoczi
    .bdrv_truncate          = qcow2_truncate,
1349 419b19d9 Stefan Hajnoczi
    .bdrv_write_compressed  = qcow_write_compressed,
1350 20d97356 Blue Swirl
1351 20d97356 Blue Swirl
    .bdrv_snapshot_create   = qcow2_snapshot_create,
1352 20d97356 Blue Swirl
    .bdrv_snapshot_goto     = qcow2_snapshot_goto,
1353 20d97356 Blue Swirl
    .bdrv_snapshot_delete   = qcow2_snapshot_delete,
1354 20d97356 Blue Swirl
    .bdrv_snapshot_list     = qcow2_snapshot_list,
1355 20d97356 Blue Swirl
    .bdrv_get_info        = qcow_get_info,
1356 20d97356 Blue Swirl
1357 20d97356 Blue Swirl
    .bdrv_save_vmstate    = qcow_save_vmstate,
1358 20d97356 Blue Swirl
    .bdrv_load_vmstate    = qcow_load_vmstate,
1359 20d97356 Blue Swirl
1360 20d97356 Blue Swirl
    .bdrv_change_backing_file   = qcow2_change_backing_file,
1361 20d97356 Blue Swirl
1362 20d97356 Blue Swirl
    .create_options = qcow_create_options,
1363 20d97356 Blue Swirl
    .bdrv_check = qcow_check,
1364 20d97356 Blue Swirl
};
1365 20d97356 Blue Swirl
1366 5efa9d5a Anthony Liguori
static void bdrv_qcow2_init(void)
1367 5efa9d5a Anthony Liguori
{
1368 5efa9d5a Anthony Liguori
    bdrv_register(&bdrv_qcow2);
1369 5efa9d5a Anthony Liguori
}
1370 5efa9d5a Anthony Liguori
1371 5efa9d5a Anthony Liguori
block_init(bdrv_qcow2_init);