Statistics
| Branch: | Revision:

root / block / qcow2.c @ 14899cdf

History | View | Annotate | Download (30.3 kB)

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

    
31
/*
32
  Differences with QCOW:
33

34
  - Support for multiple incremental snapshots.
35
  - Memory management by reference counts.
36
  - Clusters which have a reference count of one have the bit
37
    QCOW_OFLAG_COPIED to optimize write performance.
38
  - Size of compressed clusters is stored in sectors to reduce bit usage
39
    in the cluster offsets.
40
  - Support for storing additional data (such as the VM state) in the
41
    snapshots.
42
  - If a backing store is used, the cluster size is not constrained
43
    (could be backported to QCOW).
44
  - L2 tables have always a size of one cluster.
45
*/
46

    
47

    
48
typedef struct {
49
    uint32_t magic;
50
    uint32_t len;
51
} QCowExtension;
52
#define  QCOW_EXT_MAGIC_END 0
53
#define  QCOW_EXT_MAGIC_BACKING_FORMAT 0xE2792ACA
54

    
55

    
56

    
57
static int qcow_probe(const uint8_t *buf, int buf_size, const char *filename)
58
{
59
    const QCowHeader *cow_header = (const void *)buf;
60

    
61
    if (buf_size >= sizeof(QCowHeader) &&
62
        be32_to_cpu(cow_header->magic) == QCOW_MAGIC &&
63
        be32_to_cpu(cow_header->version) == QCOW_VERSION)
64
        return 100;
65
    else
66
        return 0;
67
}
68

    
69

    
70
/* 
71
 * read qcow2 extension and fill bs
72
 * start reading from start_offset
73
 * finish reading upon magic of value 0 or when end_offset reached
74
 * unknown magic is skipped (future extension this version knows nothing about)
75
 * return 0 upon success, non-0 otherwise
76
 */
77
static int qcow_read_extensions(BlockDriverState *bs, uint64_t start_offset,
78
                                uint64_t end_offset)
79
{
80
    BDRVQcowState *s = bs->opaque;
81
    QCowExtension ext;
82
    uint64_t offset;
83

    
84
#ifdef DEBUG_EXT
85
    printf("qcow_read_extensions: start=%ld end=%ld\n", start_offset, end_offset);
86
#endif
87
    offset = start_offset;
88
    while (offset < end_offset) {
89

    
90
#ifdef DEBUG_EXT
91
        /* Sanity check */
92
        if (offset > s->cluster_size)
93
            printf("qcow_handle_extension: suspicious offset %lu\n", offset);
94

    
95
        printf("attemting to read extended header in offset %lu\n", offset);
96
#endif
97

    
98
        if (bdrv_pread(s->hd, offset, &ext, sizeof(ext)) != sizeof(ext)) {
99
            fprintf(stderr, "qcow_handle_extension: ERROR: pread fail from offset %llu\n",
100
                    (unsigned long long)offset);
101
            return 1;
102
        }
103
        be32_to_cpus(&ext.magic);
104
        be32_to_cpus(&ext.len);
105
        offset += sizeof(ext);
106
#ifdef DEBUG_EXT
107
        printf("ext.magic = 0x%x\n", ext.magic);
108
#endif
109
        switch (ext.magic) {
110
        case QCOW_EXT_MAGIC_END:
111
            return 0;
112

    
113
        case QCOW_EXT_MAGIC_BACKING_FORMAT:
114
            if (ext.len >= sizeof(bs->backing_format)) {
115
                fprintf(stderr, "ERROR: ext_backing_format: len=%u too large"
116
                        " (>=%zu)\n",
117
                        ext.len, sizeof(bs->backing_format));
118
                return 2;
119
            }
120
            if (bdrv_pread(s->hd, offset , bs->backing_format,
121
                           ext.len) != ext.len)
122
                return 3;
123
            bs->backing_format[ext.len] = '\0';
124
#ifdef DEBUG_EXT
125
            printf("Qcow2: Got format extension %s\n", bs->backing_format);
126
#endif
127
            offset += ((ext.len + 7) & ~7);
128
            break;
129

    
130
        default:
131
            /* unknown magic -- just skip it */
132
            offset += ((ext.len + 7) & ~7);
133
            break;
134
        }
135
    }
136

    
137
    return 0;
138
}
139

    
140

    
141
static int qcow_open(BlockDriverState *bs, const char *filename, int flags)
142
{
143
    BDRVQcowState *s = bs->opaque;
144
    int len, i, shift, ret;
145
    QCowHeader header;
146
    uint64_t ext_end;
147

    
148
    /* Performance is terrible right now with cache=writethrough due mainly
149
     * to reference count updates.  If the user does not explicitly specify
150
     * a caching type, force to writeback caching.
151
     */
152
    if ((flags & BDRV_O_CACHE_DEF)) {
153
        flags |= BDRV_O_CACHE_WB;
154
        flags &= ~BDRV_O_CACHE_DEF;
155
    }
156
    ret = bdrv_file_open(&s->hd, filename, flags);
157
    if (ret < 0)
158
        return ret;
159
    if (bdrv_pread(s->hd, 0, &header, sizeof(header)) != sizeof(header))
160
        goto fail;
161
    be32_to_cpus(&header.magic);
162
    be32_to_cpus(&header.version);
163
    be64_to_cpus(&header.backing_file_offset);
164
    be32_to_cpus(&header.backing_file_size);
165
    be64_to_cpus(&header.size);
166
    be32_to_cpus(&header.cluster_bits);
167
    be32_to_cpus(&header.crypt_method);
168
    be64_to_cpus(&header.l1_table_offset);
169
    be32_to_cpus(&header.l1_size);
170
    be64_to_cpus(&header.refcount_table_offset);
171
    be32_to_cpus(&header.refcount_table_clusters);
172
    be64_to_cpus(&header.snapshots_offset);
173
    be32_to_cpus(&header.nb_snapshots);
174

    
175
    if (header.magic != QCOW_MAGIC || header.version != QCOW_VERSION)
176
        goto fail;
177
    if (header.size <= 1 ||
178
        header.cluster_bits < MIN_CLUSTER_BITS ||
179
        header.cluster_bits > MAX_CLUSTER_BITS)
180
        goto fail;
181
    if (header.crypt_method > QCOW_CRYPT_AES)
182
        goto fail;
183
    s->crypt_method_header = header.crypt_method;
184
    if (s->crypt_method_header)
185
        bs->encrypted = 1;
186
    s->cluster_bits = header.cluster_bits;
187
    s->cluster_size = 1 << s->cluster_bits;
188
    s->cluster_sectors = 1 << (s->cluster_bits - 9);
189
    s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */
190
    s->l2_size = 1 << s->l2_bits;
191
    bs->total_sectors = header.size / 512;
192
    s->csize_shift = (62 - (s->cluster_bits - 8));
193
    s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;
194
    s->cluster_offset_mask = (1LL << s->csize_shift) - 1;
195
    s->refcount_table_offset = header.refcount_table_offset;
196
    s->refcount_table_size =
197
        header.refcount_table_clusters << (s->cluster_bits - 3);
198

    
199
    s->snapshots_offset = header.snapshots_offset;
200
    s->nb_snapshots = header.nb_snapshots;
201

    
202
    /* read the level 1 table */
203
    s->l1_size = header.l1_size;
204
    shift = s->cluster_bits + s->l2_bits;
205
    s->l1_vm_state_index = (header.size + (1LL << shift) - 1) >> shift;
206
    /* the L1 table must contain at least enough entries to put
207
       header.size bytes */
208
    if (s->l1_size < s->l1_vm_state_index)
209
        goto fail;
210
    s->l1_table_offset = header.l1_table_offset;
211
    s->l1_table = qemu_malloc(s->l1_size * sizeof(uint64_t));
212
    if (bdrv_pread(s->hd, s->l1_table_offset, s->l1_table, s->l1_size * sizeof(uint64_t)) !=
213
        s->l1_size * sizeof(uint64_t))
214
        goto fail;
215
    for(i = 0;i < s->l1_size; i++) {
216
        be64_to_cpus(&s->l1_table[i]);
217
    }
218
    /* alloc L2 cache */
219
    s->l2_cache = qemu_malloc(s->l2_size * L2_CACHE_SIZE * sizeof(uint64_t));
220
    s->cluster_cache = qemu_malloc(s->cluster_size);
221
    /* one more sector for decompressed data alignment */
222
    s->cluster_data = qemu_malloc(QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size
223
                                  + 512);
224
    s->cluster_cache_offset = -1;
225

    
226
    if (qcow2_refcount_init(bs) < 0)
227
        goto fail;
228

    
229
    /* read qcow2 extensions */
230
    if (header.backing_file_offset)
231
        ext_end = header.backing_file_offset;
232
    else
233
        ext_end = s->cluster_size;
234
    if (qcow_read_extensions(bs, sizeof(header), ext_end))
235
        goto fail;
236

    
237
    /* read the backing file name */
238
    if (header.backing_file_offset != 0) {
239
        len = header.backing_file_size;
240
        if (len > 1023)
241
            len = 1023;
242
        if (bdrv_pread(s->hd, header.backing_file_offset, bs->backing_file, len) != len)
243
            goto fail;
244
        bs->backing_file[len] = '\0';
245
    }
246
    if (qcow2_read_snapshots(bs) < 0)
247
        goto fail;
248

    
249
#ifdef DEBUG_ALLOC
250
    qcow2_check_refcounts(bs);
251
#endif
252
    return 0;
253

    
254
 fail:
255
    qcow2_free_snapshots(bs);
256
    qcow2_refcount_close(bs);
257
    qemu_free(s->l1_table);
258
    qemu_free(s->l2_cache);
259
    qemu_free(s->cluster_cache);
260
    qemu_free(s->cluster_data);
261
    bdrv_delete(s->hd);
262
    return -1;
263
}
264

    
265
static int qcow_set_key(BlockDriverState *bs, const char *key)
266
{
267
    BDRVQcowState *s = bs->opaque;
268
    uint8_t keybuf[16];
269
    int len, i;
270

    
271
    memset(keybuf, 0, 16);
272
    len = strlen(key);
273
    if (len > 16)
274
        len = 16;
275
    /* XXX: we could compress the chars to 7 bits to increase
276
       entropy */
277
    for(i = 0;i < len;i++) {
278
        keybuf[i] = key[i];
279
    }
280
    s->crypt_method = s->crypt_method_header;
281

    
282
    if (AES_set_encrypt_key(keybuf, 128, &s->aes_encrypt_key) != 0)
283
        return -1;
284
    if (AES_set_decrypt_key(keybuf, 128, &s->aes_decrypt_key) != 0)
285
        return -1;
286
#if 0
287
    /* test */
288
    {
289
        uint8_t in[16];
290
        uint8_t out[16];
291
        uint8_t tmp[16];
292
        for(i=0;i<16;i++)
293
            in[i] = i;
294
        AES_encrypt(in, tmp, &s->aes_encrypt_key);
295
        AES_decrypt(tmp, out, &s->aes_decrypt_key);
296
        for(i = 0; i < 16; i++)
297
            printf(" %02x", tmp[i]);
298
        printf("\n");
299
        for(i = 0; i < 16; i++)
300
            printf(" %02x", out[i]);
301
        printf("\n");
302
    }
303
#endif
304
    return 0;
305
}
306

    
307
static int qcow_is_allocated(BlockDriverState *bs, int64_t sector_num,
308
                             int nb_sectors, int *pnum)
309
{
310
    uint64_t cluster_offset;
311

    
312
    *pnum = nb_sectors;
313
    cluster_offset = qcow2_get_cluster_offset(bs, sector_num << 9, pnum);
314

    
315
    return (cluster_offset != 0);
316
}
317

    
318
/* handle reading after the end of the backing file */
319
int qcow2_backing_read1(BlockDriverState *bs,
320
                  int64_t sector_num, uint8_t *buf, int nb_sectors)
321
{
322
    int n1;
323
    if ((sector_num + nb_sectors) <= bs->total_sectors)
324
        return nb_sectors;
325
    if (sector_num >= bs->total_sectors)
326
        n1 = 0;
327
    else
328
        n1 = bs->total_sectors - sector_num;
329
    memset(buf + n1 * 512, 0, 512 * (nb_sectors - n1));
330
    return n1;
331
}
332

    
333
typedef struct QCowAIOCB {
334
    BlockDriverAIOCB common;
335
    int64_t sector_num;
336
    QEMUIOVector *qiov;
337
    uint8_t *buf;
338
    void *orig_buf;
339
    int nb_sectors;
340
    int n;
341
    uint64_t cluster_offset;
342
    uint8_t *cluster_data;
343
    BlockDriverAIOCB *hd_aiocb;
344
    struct iovec hd_iov;
345
    QEMUIOVector hd_qiov;
346
    QEMUBH *bh;
347
    QCowL2Meta l2meta;
348
} QCowAIOCB;
349

    
350
static void qcow_aio_cancel(BlockDriverAIOCB *blockacb)
351
{
352
    QCowAIOCB *acb = (QCowAIOCB *)blockacb;
353
    if (acb->hd_aiocb)
354
        bdrv_aio_cancel(acb->hd_aiocb);
355
    qemu_aio_release(acb);
356
}
357

    
358
static AIOPool qcow_aio_pool = {
359
    .aiocb_size         = sizeof(QCowAIOCB),
360
    .cancel             = qcow_aio_cancel,
361
};
362

    
363
static void qcow_aio_read_cb(void *opaque, int ret);
364
static void qcow_aio_read_bh(void *opaque)
365
{
366
    QCowAIOCB *acb = opaque;
367
    qemu_bh_delete(acb->bh);
368
    acb->bh = NULL;
369
    qcow_aio_read_cb(opaque, 0);
370
}
371

    
372
static int qcow_schedule_bh(QEMUBHFunc *cb, QCowAIOCB *acb)
373
{
374
    if (acb->bh)
375
        return -EIO;
376

    
377
    acb->bh = qemu_bh_new(cb, acb);
378
    if (!acb->bh)
379
        return -EIO;
380

    
381
    qemu_bh_schedule(acb->bh);
382

    
383
    return 0;
384
}
385

    
386
static void qcow_aio_read_cb(void *opaque, int ret)
387
{
388
    QCowAIOCB *acb = opaque;
389
    BlockDriverState *bs = acb->common.bs;
390
    BDRVQcowState *s = bs->opaque;
391
    int index_in_cluster, n1;
392

    
393
    acb->hd_aiocb = NULL;
394
    if (ret < 0)
395
        goto done;
396

    
397
    /* post process the read buffer */
398
    if (!acb->cluster_offset) {
399
        /* nothing to do */
400
    } else if (acb->cluster_offset & QCOW_OFLAG_COMPRESSED) {
401
        /* nothing to do */
402
    } else {
403
        if (s->crypt_method) {
404
            qcow2_encrypt_sectors(s, acb->sector_num, acb->buf, acb->buf,
405
                            acb->n, 0,
406
                            &s->aes_decrypt_key);
407
        }
408
    }
409

    
410
    acb->nb_sectors -= acb->n;
411
    acb->sector_num += acb->n;
412
    acb->buf += acb->n * 512;
413

    
414
    if (acb->nb_sectors == 0) {
415
        /* request completed */
416
        ret = 0;
417
        goto done;
418
    }
419

    
420
    /* prepare next AIO request */
421
    acb->n = acb->nb_sectors;
422
    acb->cluster_offset =
423
        qcow2_get_cluster_offset(bs, acb->sector_num << 9, &acb->n);
424
    index_in_cluster = acb->sector_num & (s->cluster_sectors - 1);
425

    
426
    if (!acb->cluster_offset) {
427
        if (bs->backing_hd) {
428
            /* read from the base image */
429
            n1 = qcow2_backing_read1(bs->backing_hd, acb->sector_num,
430
                               acb->buf, acb->n);
431
            if (n1 > 0) {
432
                acb->hd_iov.iov_base = (void *)acb->buf;
433
                acb->hd_iov.iov_len = acb->n * 512;
434
                qemu_iovec_init_external(&acb->hd_qiov, &acb->hd_iov, 1);
435
                acb->hd_aiocb = bdrv_aio_readv(bs->backing_hd, acb->sector_num,
436
                                    &acb->hd_qiov, acb->n,
437
                                    qcow_aio_read_cb, acb);
438
                if (acb->hd_aiocb == NULL)
439
                    goto done;
440
            } else {
441
                ret = qcow_schedule_bh(qcow_aio_read_bh, acb);
442
                if (ret < 0)
443
                    goto done;
444
            }
445
        } else {
446
            /* Note: in this case, no need to wait */
447
            memset(acb->buf, 0, 512 * acb->n);
448
            ret = qcow_schedule_bh(qcow_aio_read_bh, acb);
449
            if (ret < 0)
450
                goto done;
451
        }
452
    } else if (acb->cluster_offset & QCOW_OFLAG_COMPRESSED) {
453
        /* add AIO support for compressed blocks ? */
454
        if (qcow2_decompress_cluster(s, acb->cluster_offset) < 0)
455
            goto done;
456
        memcpy(acb->buf,
457
               s->cluster_cache + index_in_cluster * 512, 512 * acb->n);
458
        ret = qcow_schedule_bh(qcow_aio_read_bh, acb);
459
        if (ret < 0)
460
            goto done;
461
    } else {
462
        if ((acb->cluster_offset & 511) != 0) {
463
            ret = -EIO;
464
            goto done;
465
        }
466

    
467
        acb->hd_iov.iov_base = (void *)acb->buf;
468
        acb->hd_iov.iov_len = acb->n * 512;
469
        qemu_iovec_init_external(&acb->hd_qiov, &acb->hd_iov, 1);
470
        acb->hd_aiocb = bdrv_aio_readv(s->hd,
471
                            (acb->cluster_offset >> 9) + index_in_cluster,
472
                            &acb->hd_qiov, acb->n, qcow_aio_read_cb, acb);
473
        if (acb->hd_aiocb == NULL)
474
            goto done;
475
    }
476

    
477
    return;
478
done:
479
    if (acb->qiov->niov > 1) {
480
        qemu_iovec_from_buffer(acb->qiov, acb->orig_buf, acb->qiov->size);
481
        qemu_vfree(acb->orig_buf);
482
    }
483
    acb->common.cb(acb->common.opaque, ret);
484
    qemu_aio_release(acb);
485
}
486

    
487
static QCowAIOCB *qcow_aio_setup(BlockDriverState *bs,
488
        int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
489
        BlockDriverCompletionFunc *cb, void *opaque, int is_write)
490
{
491
    QCowAIOCB *acb;
492

    
493
    acb = qemu_aio_get(&qcow_aio_pool, bs, cb, opaque);
494
    if (!acb)
495
        return NULL;
496
    acb->hd_aiocb = NULL;
497
    acb->sector_num = sector_num;
498
    acb->qiov = qiov;
499
    if (qiov->niov > 1) {
500
        acb->buf = acb->orig_buf = qemu_blockalign(bs, qiov->size);
501
        if (is_write)
502
            qemu_iovec_to_buffer(qiov, acb->buf);
503
    } else {
504
        acb->buf = (uint8_t *)qiov->iov->iov_base;
505
    }
506
    acb->nb_sectors = nb_sectors;
507
    acb->n = 0;
508
    acb->cluster_offset = 0;
509
    acb->l2meta.nb_clusters = 0;
510
    return acb;
511
}
512

    
513
static BlockDriverAIOCB *qcow_aio_readv(BlockDriverState *bs,
514
        int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
515
        BlockDriverCompletionFunc *cb, void *opaque)
516
{
517
    QCowAIOCB *acb;
518

    
519
    acb = qcow_aio_setup(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
520
    if (!acb)
521
        return NULL;
522

    
523
    qcow_aio_read_cb(acb, 0);
524
    return &acb->common;
525
}
526

    
527
static void qcow_aio_write_cb(void *opaque, int ret)
528
{
529
    QCowAIOCB *acb = opaque;
530
    BlockDriverState *bs = acb->common.bs;
531
    BDRVQcowState *s = bs->opaque;
532
    int index_in_cluster;
533
    const uint8_t *src_buf;
534
    int n_end;
535

    
536
    acb->hd_aiocb = NULL;
537

    
538
    if (ret < 0)
539
        goto done;
540

    
541
    if (qcow2_alloc_cluster_link_l2(bs, acb->cluster_offset, &acb->l2meta) < 0) {
542
        qcow2_free_any_clusters(bs, acb->cluster_offset, acb->l2meta.nb_clusters);
543
        goto done;
544
    }
545

    
546
    acb->nb_sectors -= acb->n;
547
    acb->sector_num += acb->n;
548
    acb->buf += acb->n * 512;
549

    
550
    if (acb->nb_sectors == 0) {
551
        /* request completed */
552
        ret = 0;
553
        goto done;
554
    }
555

    
556
    index_in_cluster = acb->sector_num & (s->cluster_sectors - 1);
557
    n_end = index_in_cluster + acb->nb_sectors;
558
    if (s->crypt_method &&
559
        n_end > QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors)
560
        n_end = QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors;
561

    
562
    acb->cluster_offset = qcow2_alloc_cluster_offset(bs, acb->sector_num << 9,
563
                                          index_in_cluster,
564
                                          n_end, &acb->n, &acb->l2meta);
565
    if (!acb->cluster_offset || (acb->cluster_offset & 511) != 0) {
566
        ret = -EIO;
567
        goto done;
568
    }
569
    if (s->crypt_method) {
570
        if (!acb->cluster_data) {
571
            acb->cluster_data = qemu_mallocz(QCOW_MAX_CRYPT_CLUSTERS *
572
                                             s->cluster_size);
573
        }
574
        qcow2_encrypt_sectors(s, acb->sector_num, acb->cluster_data, acb->buf,
575
                        acb->n, 1, &s->aes_encrypt_key);
576
        src_buf = acb->cluster_data;
577
    } else {
578
        src_buf = acb->buf;
579
    }
580
    acb->hd_iov.iov_base = (void *)src_buf;
581
    acb->hd_iov.iov_len = acb->n * 512;
582
    qemu_iovec_init_external(&acb->hd_qiov, &acb->hd_iov, 1);
583
    acb->hd_aiocb = bdrv_aio_writev(s->hd,
584
                                    (acb->cluster_offset >> 9) + index_in_cluster,
585
                                    &acb->hd_qiov, acb->n,
586
                                    qcow_aio_write_cb, acb);
587
    if (acb->hd_aiocb == NULL)
588
        goto done;
589

    
590
    return;
591

    
592
done:
593
    if (acb->qiov->niov > 1)
594
        qemu_vfree(acb->orig_buf);
595
    acb->common.cb(acb->common.opaque, ret);
596
    qemu_aio_release(acb);
597
}
598

    
599
static BlockDriverAIOCB *qcow_aio_writev(BlockDriverState *bs,
600
        int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
601
        BlockDriverCompletionFunc *cb, void *opaque)
602
{
603
    BDRVQcowState *s = bs->opaque;
604
    QCowAIOCB *acb;
605

    
606
    s->cluster_cache_offset = -1; /* disable compressed cache */
607

    
608
    acb = qcow_aio_setup(bs, sector_num, qiov, nb_sectors, cb, opaque, 1);
609
    if (!acb)
610
        return NULL;
611

    
612
    qcow_aio_write_cb(acb, 0);
613
    return &acb->common;
614
}
615

    
616
static void qcow_close(BlockDriverState *bs)
617
{
618
    BDRVQcowState *s = bs->opaque;
619
    qemu_free(s->l1_table);
620
    qemu_free(s->l2_cache);
621
    qemu_free(s->cluster_cache);
622
    qemu_free(s->cluster_data);
623
    qcow2_refcount_close(bs);
624
    bdrv_delete(s->hd);
625
}
626

    
627
static int get_bits_from_size(size_t size)
628
{
629
    int res = 0;
630

    
631
    if (size == 0) {
632
        return -1;
633
    }
634

    
635
    while (size != 1) {
636
        /* Not a power of two */
637
        if (size & 1) {
638
            return -1;
639
        }
640

    
641
        size >>= 1;
642
        res++;
643
    }
644

    
645
    return res;
646
}
647

    
648
static int qcow_create2(const char *filename, int64_t total_size,
649
                        const char *backing_file, const char *backing_format,
650
                        int flags, size_t cluster_size)
651
{
652

    
653
    int fd, header_size, backing_filename_len, l1_size, i, shift, l2_bits;
654
    int ref_clusters, backing_format_len = 0;
655
    QCowHeader header;
656
    uint64_t tmp, offset;
657
    QCowCreateState s1, *s = &s1;
658
    QCowExtension ext_bf = {0, 0};
659

    
660

    
661
    memset(s, 0, sizeof(*s));
662

    
663
    fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0644);
664
    if (fd < 0)
665
        return -1;
666
    memset(&header, 0, sizeof(header));
667
    header.magic = cpu_to_be32(QCOW_MAGIC);
668
    header.version = cpu_to_be32(QCOW_VERSION);
669
    header.size = cpu_to_be64(total_size * 512);
670
    header_size = sizeof(header);
671
    backing_filename_len = 0;
672
    if (backing_file) {
673
        if (backing_format) {
674
            ext_bf.magic = QCOW_EXT_MAGIC_BACKING_FORMAT;
675
            backing_format_len = strlen(backing_format);
676
            ext_bf.len = (backing_format_len + 7) & ~7;
677
            header_size += ((sizeof(ext_bf) + ext_bf.len + 7) & ~7);
678
        }
679
        header.backing_file_offset = cpu_to_be64(header_size);
680
        backing_filename_len = strlen(backing_file);
681
        header.backing_file_size = cpu_to_be32(backing_filename_len);
682
        header_size += backing_filename_len;
683
    }
684

    
685
    /* Cluster size */
686
    s->cluster_bits = get_bits_from_size(cluster_size);
687
    if (s->cluster_bits < MIN_CLUSTER_BITS ||
688
        s->cluster_bits > MAX_CLUSTER_BITS)
689
    {
690
        fprintf(stderr, "Cluster size must be a power of two between "
691
            "%d and %dk\n",
692
            1 << MIN_CLUSTER_BITS,
693
            1 << (MAX_CLUSTER_BITS - 10));
694
        return -EINVAL;
695
    }
696
    s->cluster_size = 1 << s->cluster_bits;
697

    
698
    header.cluster_bits = cpu_to_be32(s->cluster_bits);
699
    header_size = (header_size + 7) & ~7;
700
    if (flags & BLOCK_FLAG_ENCRYPT) {
701
        header.crypt_method = cpu_to_be32(QCOW_CRYPT_AES);
702
    } else {
703
        header.crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
704
    }
705
    l2_bits = s->cluster_bits - 3;
706
    shift = s->cluster_bits + l2_bits;
707
    l1_size = (((total_size * 512) + (1LL << shift) - 1) >> shift);
708
    offset = align_offset(header_size, s->cluster_size);
709
    s->l1_table_offset = offset;
710
    header.l1_table_offset = cpu_to_be64(s->l1_table_offset);
711
    header.l1_size = cpu_to_be32(l1_size);
712
    offset += align_offset(l1_size * sizeof(uint64_t), s->cluster_size);
713

    
714
    s->refcount_table = qemu_mallocz(s->cluster_size);
715

    
716
    s->refcount_table_offset = offset;
717
    header.refcount_table_offset = cpu_to_be64(offset);
718
    header.refcount_table_clusters = cpu_to_be32(1);
719
    offset += s->cluster_size;
720
    s->refcount_block_offset = offset;
721

    
722
    /* count how many refcount blocks needed */
723
    tmp = offset >> s->cluster_bits;
724
    ref_clusters = (tmp >> (s->cluster_bits - REFCOUNT_SHIFT)) + 1;
725
    for (i=0; i < ref_clusters; i++) {
726
        s->refcount_table[i] = cpu_to_be64(offset);
727
        offset += s->cluster_size;
728
    }
729

    
730
    s->refcount_block = qemu_mallocz(ref_clusters * s->cluster_size);
731

    
732
    /* update refcounts */
733
    qcow2_create_refcount_update(s, 0, header_size);
734
    qcow2_create_refcount_update(s, s->l1_table_offset,
735
        l1_size * sizeof(uint64_t));
736
    qcow2_create_refcount_update(s, s->refcount_table_offset, s->cluster_size);
737
    qcow2_create_refcount_update(s, s->refcount_block_offset,
738
        ref_clusters * s->cluster_size);
739

    
740
    /* write all the data */
741
    write(fd, &header, sizeof(header));
742
    if (backing_file) {
743
        if (backing_format_len) {
744
            char zero[16];
745
            int d = ext_bf.len - backing_format_len;
746

    
747
            memset(zero, 0, sizeof(zero));
748
            cpu_to_be32s(&ext_bf.magic);
749
            cpu_to_be32s(&ext_bf.len);
750
            write(fd, &ext_bf, sizeof(ext_bf));
751
            write(fd, backing_format, backing_format_len);
752
            if (d>0) {
753
                write(fd, zero, d);
754
            }
755
        }
756
        write(fd, backing_file, backing_filename_len);
757
    }
758
    lseek(fd, s->l1_table_offset, SEEK_SET);
759
    tmp = 0;
760
    for(i = 0;i < l1_size; i++) {
761
        write(fd, &tmp, sizeof(tmp));
762
    }
763
    lseek(fd, s->refcount_table_offset, SEEK_SET);
764
    write(fd, s->refcount_table, s->cluster_size);
765

    
766
    lseek(fd, s->refcount_block_offset, SEEK_SET);
767
    write(fd, s->refcount_block, ref_clusters * s->cluster_size);
768

    
769
    qemu_free(s->refcount_table);
770
    qemu_free(s->refcount_block);
771
    close(fd);
772
    return 0;
773
}
774

    
775
static int qcow_create(const char *filename, QEMUOptionParameter *options)
776
{
777
    const char *backing_file = NULL;
778
    const char *backing_fmt = NULL;
779
    uint64_t sectors = 0;
780
    int flags = 0;
781
    size_t cluster_size = 65536;
782

    
783
    /* Read out options */
784
    while (options && options->name) {
785
        if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
786
            sectors = options->value.n / 512;
787
        } else if (!strcmp(options->name, BLOCK_OPT_BACKING_FILE)) {
788
            backing_file = options->value.s;
789
        } else if (!strcmp(options->name, BLOCK_OPT_BACKING_FMT)) {
790
            backing_fmt = options->value.s;
791
        } else if (!strcmp(options->name, BLOCK_OPT_ENCRYPT)) {
792
            flags |= options->value.n ? BLOCK_FLAG_ENCRYPT : 0;
793
        } else if (!strcmp(options->name, BLOCK_OPT_CLUSTER_SIZE)) {
794
            if (options->value.n) {
795
                cluster_size = options->value.n;
796
            }
797
        }
798
        options++;
799
    }
800

    
801
    return qcow_create2(filename, sectors, backing_file, backing_fmt, flags,
802
        cluster_size);
803
}
804

    
805
static int qcow_make_empty(BlockDriverState *bs)
806
{
807
#if 0
808
    /* XXX: not correct */
809
    BDRVQcowState *s = bs->opaque;
810
    uint32_t l1_length = s->l1_size * sizeof(uint64_t);
811
    int ret;
812

813
    memset(s->l1_table, 0, l1_length);
814
    if (bdrv_pwrite(s->hd, s->l1_table_offset, s->l1_table, l1_length) < 0)
815
        return -1;
816
    ret = bdrv_truncate(s->hd, s->l1_table_offset + l1_length);
817
    if (ret < 0)
818
        return ret;
819

820
    l2_cache_reset(bs);
821
#endif
822
    return 0;
823
}
824

    
825
/* XXX: put compressed sectors first, then all the cluster aligned
826
   tables to avoid losing bytes in alignment */
827
static int qcow_write_compressed(BlockDriverState *bs, int64_t sector_num,
828
                                 const uint8_t *buf, int nb_sectors)
829
{
830
    BDRVQcowState *s = bs->opaque;
831
    z_stream strm;
832
    int ret, out_len;
833
    uint8_t *out_buf;
834
    uint64_t cluster_offset;
835

    
836
    if (nb_sectors == 0) {
837
        /* align end of file to a sector boundary to ease reading with
838
           sector based I/Os */
839
        cluster_offset = bdrv_getlength(s->hd);
840
        cluster_offset = (cluster_offset + 511) & ~511;
841
        bdrv_truncate(s->hd, cluster_offset);
842
        return 0;
843
    }
844

    
845
    if (nb_sectors != s->cluster_sectors)
846
        return -EINVAL;
847

    
848
    out_buf = qemu_malloc(s->cluster_size + (s->cluster_size / 1000) + 128);
849

    
850
    /* best compression, small window, no zlib header */
851
    memset(&strm, 0, sizeof(strm));
852
    ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
853
                       Z_DEFLATED, -12,
854
                       9, Z_DEFAULT_STRATEGY);
855
    if (ret != 0) {
856
        qemu_free(out_buf);
857
        return -1;
858
    }
859

    
860
    strm.avail_in = s->cluster_size;
861
    strm.next_in = (uint8_t *)buf;
862
    strm.avail_out = s->cluster_size;
863
    strm.next_out = out_buf;
864

    
865
    ret = deflate(&strm, Z_FINISH);
866
    if (ret != Z_STREAM_END && ret != Z_OK) {
867
        qemu_free(out_buf);
868
        deflateEnd(&strm);
869
        return -1;
870
    }
871
    out_len = strm.next_out - out_buf;
872

    
873
    deflateEnd(&strm);
874

    
875
    if (ret != Z_STREAM_END || out_len >= s->cluster_size) {
876
        /* could not compress: write normal cluster */
877
        bdrv_write(bs, sector_num, buf, s->cluster_sectors);
878
    } else {
879
        cluster_offset = qcow2_alloc_compressed_cluster_offset(bs,
880
            sector_num << 9, out_len);
881
        if (!cluster_offset)
882
            return -1;
883
        cluster_offset &= s->cluster_offset_mask;
884
        if (bdrv_pwrite(s->hd, cluster_offset, out_buf, out_len) != out_len) {
885
            qemu_free(out_buf);
886
            return -1;
887
        }
888
    }
889

    
890
    qemu_free(out_buf);
891
    return 0;
892
}
893

    
894
static void qcow_flush(BlockDriverState *bs)
895
{
896
    BDRVQcowState *s = bs->opaque;
897
    bdrv_flush(s->hd);
898
}
899

    
900
static int qcow_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
901
{
902
    BDRVQcowState *s = bs->opaque;
903
    bdi->cluster_size = s->cluster_size;
904
    bdi->vm_state_offset = (int64_t)s->l1_vm_state_index <<
905
        (s->cluster_bits + s->l2_bits);
906
    return 0;
907
}
908

    
909

    
910
static int qcow_check(BlockDriverState *bs)
911
{
912
    return qcow2_check_refcounts(bs);
913
}
914

    
915
#if 0
916
static void dump_refcounts(BlockDriverState *bs)
917
{
918
    BDRVQcowState *s = bs->opaque;
919
    int64_t nb_clusters, k, k1, size;
920
    int refcount;
921

922
    size = bdrv_getlength(s->hd);
923
    nb_clusters = size_to_clusters(s, size);
924
    for(k = 0; k < nb_clusters;) {
925
        k1 = k;
926
        refcount = get_refcount(bs, k);
927
        k++;
928
        while (k < nb_clusters && get_refcount(bs, k) == refcount)
929
            k++;
930
        printf("%lld: refcount=%d nb=%lld\n", k, refcount, k - k1);
931
    }
932
}
933
#endif
934

    
935
static int qcow_put_buffer(BlockDriverState *bs, const uint8_t *buf,
936
                           int64_t pos, int size)
937
{
938
    int growable = bs->growable;
939

    
940
    bs->growable = 1;
941
    bdrv_pwrite(bs, pos, buf, size);
942
    bs->growable = growable;
943

    
944
    return size;
945
}
946

    
947
static int qcow_get_buffer(BlockDriverState *bs, uint8_t *buf,
948
                           int64_t pos, int size)
949
{
950
    int growable = bs->growable;
951
    int ret;
952

    
953
    bs->growable = 1;
954
    ret = bdrv_pread(bs, pos, buf, size);
955
    bs->growable = growable;
956

    
957
    return ret;
958
}
959

    
960
static QEMUOptionParameter qcow_create_options[] = {
961
    {
962
        .name = BLOCK_OPT_SIZE,
963
        .type = OPT_SIZE,
964
        .help = "Virtual disk size"
965
    },
966
    {
967
        .name = BLOCK_OPT_BACKING_FILE,
968
        .type = OPT_STRING,
969
        .help = "File name of a base image"
970
    },
971
    {
972
        .name = BLOCK_OPT_BACKING_FMT,
973
        .type = OPT_STRING,
974
        .help = "Image format of the base image"
975
    },
976
    {
977
        .name = BLOCK_OPT_ENCRYPT,
978
        .type = OPT_FLAG,
979
        .help = "Encrypt the image"
980
    },
981
    {
982
        .name = BLOCK_OPT_CLUSTER_SIZE,
983
        .type = OPT_SIZE,
984
        .help = "qcow2 cluster size"
985
    },
986
    { NULL }
987
};
988

    
989
static BlockDriver bdrv_qcow2 = {
990
    .format_name        = "qcow2",
991
    .instance_size        = sizeof(BDRVQcowState),
992
    .bdrv_probe                = qcow_probe,
993
    .bdrv_open                = qcow_open,
994
    .bdrv_close                = qcow_close,
995
    .bdrv_create        = qcow_create,
996
    .bdrv_flush                = qcow_flush,
997
    .bdrv_is_allocated        = qcow_is_allocated,
998
    .bdrv_set_key        = qcow_set_key,
999
    .bdrv_make_empty        = qcow_make_empty,
1000

    
1001
    .bdrv_aio_readv        = qcow_aio_readv,
1002
    .bdrv_aio_writev        = qcow_aio_writev,
1003
    .bdrv_write_compressed = qcow_write_compressed,
1004

    
1005
    .bdrv_snapshot_create   = qcow2_snapshot_create,
1006
    .bdrv_snapshot_goto     = qcow2_snapshot_goto,
1007
    .bdrv_snapshot_delete   = qcow2_snapshot_delete,
1008
    .bdrv_snapshot_list     = qcow2_snapshot_list,
1009
    .bdrv_get_info        = qcow_get_info,
1010

    
1011
    .bdrv_put_buffer    = qcow_put_buffer,
1012
    .bdrv_get_buffer    = qcow_get_buffer,
1013

    
1014
    .create_options = qcow_create_options,
1015
    .bdrv_check = qcow_check,
1016
};
1017

    
1018
static void bdrv_qcow2_init(void)
1019
{
1020
    bdrv_register(&bdrv_qcow2);
1021
}
1022

    
1023
block_init(bdrv_qcow2_init);