Statistics
| Branch: | Revision:

root / block / qcow2.c @ 57e69b7d

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

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

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

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