Statistics
| Branch: | Revision:

root / block / qcow2.c @ 34b5d2c6

History | View | Annotate | Download (62.9 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/block_int.h"
26
#include "qemu/module.h"
27
#include <zlib.h>
28
#include "qemu/aes.h"
29
#include "block/qcow2.h"
30
#include "qemu/error-report.h"
31
#include "qapi/qmp/qerror.h"
32
#include "qapi/qmp/qbool.h"
33
#include "trace.h"
34

    
35
/*
36
  Differences with QCOW:
37

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

    
51

    
52
typedef struct {
53
    uint32_t magic;
54
    uint32_t len;
55
} QCowExtension;
56

    
57
#define  QCOW2_EXT_MAGIC_END 0
58
#define  QCOW2_EXT_MAGIC_BACKING_FORMAT 0xE2792ACA
59
#define  QCOW2_EXT_MAGIC_FEATURE_TABLE 0x6803f857
60

    
61
static int qcow2_probe(const uint8_t *buf, int buf_size, const char *filename)
62
{
63
    const QCowHeader *cow_header = (const void *)buf;
64

    
65
    if (buf_size >= sizeof(QCowHeader) &&
66
        be32_to_cpu(cow_header->magic) == QCOW_MAGIC &&
67
        be32_to_cpu(cow_header->version) >= 2)
68
        return 100;
69
    else
70
        return 0;
71
}
72

    
73

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

    
89
#ifdef DEBUG_EXT
90
    printf("qcow2_read_extensions: start=%ld end=%ld\n", start_offset, end_offset);
91
#endif
92
    offset = start_offset;
93
    while (offset < end_offset) {
94

    
95
#ifdef DEBUG_EXT
96
        /* Sanity check */
97
        if (offset > s->cluster_size)
98
            printf("qcow2_read_extension: suspicious offset %lu\n", offset);
99

    
100
        printf("attempting to read extended header in offset %lu\n", offset);
101
#endif
102

    
103
        if (bdrv_pread(bs->file, offset, &ext, sizeof(ext)) != sizeof(ext)) {
104
            fprintf(stderr, "qcow2_read_extension: ERROR: "
105
                    "pread fail from offset %" PRIu64 "\n",
106
                    offset);
107
            return 1;
108
        }
109
        be32_to_cpus(&ext.magic);
110
        be32_to_cpus(&ext.len);
111
        offset += sizeof(ext);
112
#ifdef DEBUG_EXT
113
        printf("ext.magic = 0x%x\n", ext.magic);
114
#endif
115
        if (ext.len > end_offset - offset) {
116
            error_report("Header extension too large");
117
            return -EINVAL;
118
        }
119

    
120
        switch (ext.magic) {
121
        case QCOW2_EXT_MAGIC_END:
122
            return 0;
123

    
124
        case QCOW2_EXT_MAGIC_BACKING_FORMAT:
125
            if (ext.len >= sizeof(bs->backing_format)) {
126
                fprintf(stderr, "ERROR: ext_backing_format: len=%u too large"
127
                        " (>=%zu)\n",
128
                        ext.len, sizeof(bs->backing_format));
129
                return 2;
130
            }
131
            if (bdrv_pread(bs->file, offset , bs->backing_format,
132
                           ext.len) != ext.len)
133
                return 3;
134
            bs->backing_format[ext.len] = '\0';
135
#ifdef DEBUG_EXT
136
            printf("Qcow2: Got format extension %s\n", bs->backing_format);
137
#endif
138
            break;
139

    
140
        case QCOW2_EXT_MAGIC_FEATURE_TABLE:
141
            if (p_feature_table != NULL) {
142
                void* feature_table = g_malloc0(ext.len + 2 * sizeof(Qcow2Feature));
143
                ret = bdrv_pread(bs->file, offset , feature_table, ext.len);
144
                if (ret < 0) {
145
                    return ret;
146
                }
147

    
148
                *p_feature_table = feature_table;
149
            }
150
            break;
151

    
152
        default:
153
            /* unknown magic - save it in case we need to rewrite the header */
154
            {
155
                Qcow2UnknownHeaderExtension *uext;
156

    
157
                uext = g_malloc0(sizeof(*uext)  + ext.len);
158
                uext->magic = ext.magic;
159
                uext->len = ext.len;
160
                QLIST_INSERT_HEAD(&s->unknown_header_ext, uext, next);
161

    
162
                ret = bdrv_pread(bs->file, offset , uext->data, uext->len);
163
                if (ret < 0) {
164
                    return ret;
165
                }
166
            }
167
            break;
168
        }
169

    
170
        offset += ((ext.len + 7) & ~7);
171
    }
172

    
173
    return 0;
174
}
175

    
176
static void cleanup_unknown_header_ext(BlockDriverState *bs)
177
{
178
    BDRVQcowState *s = bs->opaque;
179
    Qcow2UnknownHeaderExtension *uext, *next;
180

    
181
    QLIST_FOREACH_SAFE(uext, &s->unknown_header_ext, next, next) {
182
        QLIST_REMOVE(uext, next);
183
        g_free(uext);
184
    }
185
}
186

    
187
static void GCC_FMT_ATTR(2, 3) report_unsupported(BlockDriverState *bs,
188
    const char *fmt, ...)
189
{
190
    char msg[64];
191
    va_list ap;
192

    
193
    va_start(ap, fmt);
194
    vsnprintf(msg, sizeof(msg), fmt, ap);
195
    va_end(ap);
196

    
197
    qerror_report(QERR_UNKNOWN_BLOCK_FORMAT_FEATURE,
198
        bs->device_name, "qcow2", msg);
199
}
200

    
201
static void report_unsupported_feature(BlockDriverState *bs,
202
    Qcow2Feature *table, uint64_t mask)
203
{
204
    while (table && table->name[0] != '\0') {
205
        if (table->type == QCOW2_FEAT_TYPE_INCOMPATIBLE) {
206
            if (mask & (1 << table->bit)) {
207
                report_unsupported(bs, "%.46s",table->name);
208
                mask &= ~(1 << table->bit);
209
            }
210
        }
211
        table++;
212
    }
213

    
214
    if (mask) {
215
        report_unsupported(bs, "Unknown incompatible feature: %" PRIx64, mask);
216
    }
217
}
218

    
219
/*
220
 * Sets the dirty bit and flushes afterwards if necessary.
221
 *
222
 * The incompatible_features bit is only set if the image file header was
223
 * updated successfully.  Therefore it is not required to check the return
224
 * value of this function.
225
 */
226
int qcow2_mark_dirty(BlockDriverState *bs)
227
{
228
    BDRVQcowState *s = bs->opaque;
229
    uint64_t val;
230
    int ret;
231

    
232
    assert(s->qcow_version >= 3);
233

    
234
    if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
235
        return 0; /* already dirty */
236
    }
237

    
238
    val = cpu_to_be64(s->incompatible_features | QCOW2_INCOMPAT_DIRTY);
239
    ret = bdrv_pwrite(bs->file, offsetof(QCowHeader, incompatible_features),
240
                      &val, sizeof(val));
241
    if (ret < 0) {
242
        return ret;
243
    }
244
    ret = bdrv_flush(bs->file);
245
    if (ret < 0) {
246
        return ret;
247
    }
248

    
249
    /* Only treat image as dirty if the header was updated successfully */
250
    s->incompatible_features |= QCOW2_INCOMPAT_DIRTY;
251
    return 0;
252
}
253

    
254
/*
255
 * Clears the dirty bit and flushes before if necessary.  Only call this
256
 * function when there are no pending requests, it does not guard against
257
 * concurrent requests dirtying the image.
258
 */
259
static int qcow2_mark_clean(BlockDriverState *bs)
260
{
261
    BDRVQcowState *s = bs->opaque;
262

    
263
    if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
264
        int ret = bdrv_flush(bs);
265
        if (ret < 0) {
266
            return ret;
267
        }
268

    
269
        s->incompatible_features &= ~QCOW2_INCOMPAT_DIRTY;
270
        return qcow2_update_header(bs);
271
    }
272
    return 0;
273
}
274

    
275
/*
276
 * Marks the image as corrupt.
277
 */
278
int qcow2_mark_corrupt(BlockDriverState *bs)
279
{
280
    BDRVQcowState *s = bs->opaque;
281

    
282
    s->incompatible_features |= QCOW2_INCOMPAT_CORRUPT;
283
    return qcow2_update_header(bs);
284
}
285

    
286
/*
287
 * Marks the image as consistent, i.e., unsets the corrupt bit, and flushes
288
 * before if necessary.
289
 */
290
int qcow2_mark_consistent(BlockDriverState *bs)
291
{
292
    BDRVQcowState *s = bs->opaque;
293

    
294
    if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
295
        int ret = bdrv_flush(bs);
296
        if (ret < 0) {
297
            return ret;
298
        }
299

    
300
        s->incompatible_features &= ~QCOW2_INCOMPAT_CORRUPT;
301
        return qcow2_update_header(bs);
302
    }
303
    return 0;
304
}
305

    
306
static int qcow2_check(BlockDriverState *bs, BdrvCheckResult *result,
307
                       BdrvCheckMode fix)
308
{
309
    int ret = qcow2_check_refcounts(bs, result, fix);
310
    if (ret < 0) {
311
        return ret;
312
    }
313

    
314
    if (fix && result->check_errors == 0 && result->corruptions == 0) {
315
        ret = qcow2_mark_clean(bs);
316
        if (ret < 0) {
317
            return ret;
318
        }
319
        return qcow2_mark_consistent(bs);
320
    }
321
    return ret;
322
}
323

    
324
static QemuOptsList qcow2_runtime_opts = {
325
    .name = "qcow2",
326
    .head = QTAILQ_HEAD_INITIALIZER(qcow2_runtime_opts.head),
327
    .desc = {
328
        {
329
            .name = QCOW2_OPT_LAZY_REFCOUNTS,
330
            .type = QEMU_OPT_BOOL,
331
            .help = "Postpone refcount updates",
332
        },
333
        {
334
            .name = QCOW2_OPT_DISCARD_REQUEST,
335
            .type = QEMU_OPT_BOOL,
336
            .help = "Pass guest discard requests to the layer below",
337
        },
338
        {
339
            .name = QCOW2_OPT_DISCARD_SNAPSHOT,
340
            .type = QEMU_OPT_BOOL,
341
            .help = "Generate discard requests when snapshot related space "
342
                    "is freed",
343
        },
344
        {
345
            .name = QCOW2_OPT_DISCARD_OTHER,
346
            .type = QEMU_OPT_BOOL,
347
            .help = "Generate discard requests when other clusters are freed",
348
        },
349
        { /* end of list */ }
350
    },
351
};
352

    
353
static int qcow2_open(BlockDriverState *bs, QDict *options, int flags,
354
                      Error **errp)
355
{
356
    BDRVQcowState *s = bs->opaque;
357
    int len, i, ret = 0;
358
    QCowHeader header;
359
    QemuOpts *opts;
360
    Error *local_err = NULL;
361
    uint64_t ext_end;
362
    uint64_t l1_vm_state_index;
363

    
364
    ret = bdrv_pread(bs->file, 0, &header, sizeof(header));
365
    if (ret < 0) {
366
        goto fail;
367
    }
368
    be32_to_cpus(&header.magic);
369
    be32_to_cpus(&header.version);
370
    be64_to_cpus(&header.backing_file_offset);
371
    be32_to_cpus(&header.backing_file_size);
372
    be64_to_cpus(&header.size);
373
    be32_to_cpus(&header.cluster_bits);
374
    be32_to_cpus(&header.crypt_method);
375
    be64_to_cpus(&header.l1_table_offset);
376
    be32_to_cpus(&header.l1_size);
377
    be64_to_cpus(&header.refcount_table_offset);
378
    be32_to_cpus(&header.refcount_table_clusters);
379
    be64_to_cpus(&header.snapshots_offset);
380
    be32_to_cpus(&header.nb_snapshots);
381

    
382
    if (header.magic != QCOW_MAGIC) {
383
        ret = -EMEDIUMTYPE;
384
        goto fail;
385
    }
386
    if (header.version < 2 || header.version > 3) {
387
        report_unsupported(bs, "QCOW version %d", header.version);
388
        ret = -ENOTSUP;
389
        goto fail;
390
    }
391

    
392
    s->qcow_version = header.version;
393

    
394
    /* Initialise version 3 header fields */
395
    if (header.version == 2) {
396
        header.incompatible_features    = 0;
397
        header.compatible_features      = 0;
398
        header.autoclear_features       = 0;
399
        header.refcount_order           = 4;
400
        header.header_length            = 72;
401
    } else {
402
        be64_to_cpus(&header.incompatible_features);
403
        be64_to_cpus(&header.compatible_features);
404
        be64_to_cpus(&header.autoclear_features);
405
        be32_to_cpus(&header.refcount_order);
406
        be32_to_cpus(&header.header_length);
407
    }
408

    
409
    if (header.header_length > sizeof(header)) {
410
        s->unknown_header_fields_size = header.header_length - sizeof(header);
411
        s->unknown_header_fields = g_malloc(s->unknown_header_fields_size);
412
        ret = bdrv_pread(bs->file, sizeof(header), s->unknown_header_fields,
413
                         s->unknown_header_fields_size);
414
        if (ret < 0) {
415
            goto fail;
416
        }
417
    }
418

    
419
    if (header.backing_file_offset) {
420
        ext_end = header.backing_file_offset;
421
    } else {
422
        ext_end = 1 << header.cluster_bits;
423
    }
424

    
425
    /* Handle feature bits */
426
    s->incompatible_features    = header.incompatible_features;
427
    s->compatible_features      = header.compatible_features;
428
    s->autoclear_features       = header.autoclear_features;
429

    
430
    if (s->incompatible_features & ~QCOW2_INCOMPAT_MASK) {
431
        void *feature_table = NULL;
432
        qcow2_read_extensions(bs, header.header_length, ext_end,
433
                              &feature_table);
434
        report_unsupported_feature(bs, feature_table,
435
                                   s->incompatible_features &
436
                                   ~QCOW2_INCOMPAT_MASK);
437
        ret = -ENOTSUP;
438
        goto fail;
439
    }
440

    
441
    if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
442
        /* Corrupt images may not be written to unless they are being repaired
443
         */
444
        if ((flags & BDRV_O_RDWR) && !(flags & BDRV_O_CHECK)) {
445
            error_report("qcow2: Image is corrupt; cannot be opened "
446
                    "read/write.");
447
            ret = -EACCES;
448
            goto fail;
449
        }
450
    }
451

    
452
    /* Check support for various header values */
453
    if (header.refcount_order != 4) {
454
        report_unsupported(bs, "%d bit reference counts",
455
                           1 << header.refcount_order);
456
        ret = -ENOTSUP;
457
        goto fail;
458
    }
459
    s->refcount_order = header.refcount_order;
460

    
461
    if (header.cluster_bits < MIN_CLUSTER_BITS ||
462
        header.cluster_bits > MAX_CLUSTER_BITS) {
463
        ret = -EINVAL;
464
        goto fail;
465
    }
466
    if (header.crypt_method > QCOW_CRYPT_AES) {
467
        ret = -EINVAL;
468
        goto fail;
469
    }
470
    s->crypt_method_header = header.crypt_method;
471
    if (s->crypt_method_header) {
472
        bs->encrypted = 1;
473
    }
474
    s->cluster_bits = header.cluster_bits;
475
    s->cluster_size = 1 << s->cluster_bits;
476
    s->cluster_sectors = 1 << (s->cluster_bits - 9);
477
    s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */
478
    s->l2_size = 1 << s->l2_bits;
479
    bs->total_sectors = header.size / 512;
480
    s->csize_shift = (62 - (s->cluster_bits - 8));
481
    s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;
482
    s->cluster_offset_mask = (1LL << s->csize_shift) - 1;
483
    s->refcount_table_offset = header.refcount_table_offset;
484
    s->refcount_table_size =
485
        header.refcount_table_clusters << (s->cluster_bits - 3);
486

    
487
    s->snapshots_offset = header.snapshots_offset;
488
    s->nb_snapshots = header.nb_snapshots;
489

    
490
    /* read the level 1 table */
491
    s->l1_size = header.l1_size;
492

    
493
    l1_vm_state_index = size_to_l1(s, header.size);
494
    if (l1_vm_state_index > INT_MAX) {
495
        ret = -EFBIG;
496
        goto fail;
497
    }
498
    s->l1_vm_state_index = l1_vm_state_index;
499

    
500
    /* the L1 table must contain at least enough entries to put
501
       header.size bytes */
502
    if (s->l1_size < s->l1_vm_state_index) {
503
        ret = -EINVAL;
504
        goto fail;
505
    }
506
    s->l1_table_offset = header.l1_table_offset;
507
    if (s->l1_size > 0) {
508
        s->l1_table = g_malloc0(
509
            align_offset(s->l1_size * sizeof(uint64_t), 512));
510
        ret = bdrv_pread(bs->file, s->l1_table_offset, s->l1_table,
511
                         s->l1_size * sizeof(uint64_t));
512
        if (ret < 0) {
513
            goto fail;
514
        }
515
        for(i = 0;i < s->l1_size; i++) {
516
            be64_to_cpus(&s->l1_table[i]);
517
        }
518
    }
519

    
520
    /* alloc L2 table/refcount block cache */
521
    s->l2_table_cache = qcow2_cache_create(bs, L2_CACHE_SIZE);
522
    s->refcount_block_cache = qcow2_cache_create(bs, REFCOUNT_CACHE_SIZE);
523

    
524
    s->cluster_cache = g_malloc(s->cluster_size);
525
    /* one more sector for decompressed data alignment */
526
    s->cluster_data = qemu_blockalign(bs, QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size
527
                                  + 512);
528
    s->cluster_cache_offset = -1;
529
    s->flags = flags;
530

    
531
    ret = qcow2_refcount_init(bs);
532
    if (ret != 0) {
533
        goto fail;
534
    }
535

    
536
    QLIST_INIT(&s->cluster_allocs);
537
    QTAILQ_INIT(&s->discards);
538

    
539
    /* read qcow2 extensions */
540
    if (qcow2_read_extensions(bs, header.header_length, ext_end, NULL)) {
541
        ret = -EINVAL;
542
        goto fail;
543
    }
544

    
545
    /* read the backing file name */
546
    if (header.backing_file_offset != 0) {
547
        len = header.backing_file_size;
548
        if (len > 1023) {
549
            len = 1023;
550
        }
551
        ret = bdrv_pread(bs->file, header.backing_file_offset,
552
                         bs->backing_file, len);
553
        if (ret < 0) {
554
            goto fail;
555
        }
556
        bs->backing_file[len] = '\0';
557
    }
558

    
559
    ret = qcow2_read_snapshots(bs);
560
    if (ret < 0) {
561
        goto fail;
562
    }
563

    
564
    /* Clear unknown autoclear feature bits */
565
    if (!bs->read_only && s->autoclear_features != 0) {
566
        s->autoclear_features = 0;
567
        ret = qcow2_update_header(bs);
568
        if (ret < 0) {
569
            goto fail;
570
        }
571
    }
572

    
573
    /* Initialise locks */
574
    qemu_co_mutex_init(&s->lock);
575

    
576
    /* Repair image if dirty */
577
    if (!(flags & BDRV_O_CHECK) && !bs->read_only &&
578
        (s->incompatible_features & QCOW2_INCOMPAT_DIRTY)) {
579
        BdrvCheckResult result = {0};
580

    
581
        ret = qcow2_check(bs, &result, BDRV_FIX_ERRORS);
582
        if (ret < 0) {
583
            goto fail;
584
        }
585
    }
586

    
587
    /* Enable lazy_refcounts according to image and command line options */
588
    opts = qemu_opts_create_nofail(&qcow2_runtime_opts);
589
    qemu_opts_absorb_qdict(opts, options, &local_err);
590
    if (error_is_set(&local_err)) {
591
        qerror_report_err(local_err);
592
        error_free(local_err);
593
        ret = -EINVAL;
594
        goto fail;
595
    }
596

    
597
    s->use_lazy_refcounts = qemu_opt_get_bool(opts, QCOW2_OPT_LAZY_REFCOUNTS,
598
        (s->compatible_features & QCOW2_COMPAT_LAZY_REFCOUNTS));
599

    
600
    s->discard_passthrough[QCOW2_DISCARD_NEVER] = false;
601
    s->discard_passthrough[QCOW2_DISCARD_ALWAYS] = true;
602
    s->discard_passthrough[QCOW2_DISCARD_REQUEST] =
603
        qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_REQUEST,
604
                          flags & BDRV_O_UNMAP);
605
    s->discard_passthrough[QCOW2_DISCARD_SNAPSHOT] =
606
        qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_SNAPSHOT, true);
607
    s->discard_passthrough[QCOW2_DISCARD_OTHER] =
608
        qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_OTHER, false);
609

    
610
    qemu_opts_del(opts);
611

    
612
    if (s->use_lazy_refcounts && s->qcow_version < 3) {
613
        qerror_report(ERROR_CLASS_GENERIC_ERROR, "Lazy refcounts require "
614
            "a qcow2 image with at least qemu 1.1 compatibility level");
615
        ret = -EINVAL;
616
        goto fail;
617
    }
618

    
619
#ifdef DEBUG_ALLOC
620
    {
621
        BdrvCheckResult result = {0};
622
        qcow2_check_refcounts(bs, &result, 0);
623
    }
624
#endif
625
    return ret;
626

    
627
 fail:
628
    g_free(s->unknown_header_fields);
629
    cleanup_unknown_header_ext(bs);
630
    qcow2_free_snapshots(bs);
631
    qcow2_refcount_close(bs);
632
    g_free(s->l1_table);
633
    /* else pre-write overlap checks in cache_destroy may crash */
634
    s->l1_table = NULL;
635
    if (s->l2_table_cache) {
636
        qcow2_cache_destroy(bs, s->l2_table_cache);
637
    }
638
    g_free(s->cluster_cache);
639
    qemu_vfree(s->cluster_data);
640
    return ret;
641
}
642

    
643
static int qcow2_set_key(BlockDriverState *bs, const char *key)
644
{
645
    BDRVQcowState *s = bs->opaque;
646
    uint8_t keybuf[16];
647
    int len, i;
648

    
649
    memset(keybuf, 0, 16);
650
    len = strlen(key);
651
    if (len > 16)
652
        len = 16;
653
    /* XXX: we could compress the chars to 7 bits to increase
654
       entropy */
655
    for(i = 0;i < len;i++) {
656
        keybuf[i] = key[i];
657
    }
658
    s->crypt_method = s->crypt_method_header;
659

    
660
    if (AES_set_encrypt_key(keybuf, 128, &s->aes_encrypt_key) != 0)
661
        return -1;
662
    if (AES_set_decrypt_key(keybuf, 128, &s->aes_decrypt_key) != 0)
663
        return -1;
664
#if 0
665
    /* test */
666
    {
667
        uint8_t in[16];
668
        uint8_t out[16];
669
        uint8_t tmp[16];
670
        for(i=0;i<16;i++)
671
            in[i] = i;
672
        AES_encrypt(in, tmp, &s->aes_encrypt_key);
673
        AES_decrypt(tmp, out, &s->aes_decrypt_key);
674
        for(i = 0; i < 16; i++)
675
            printf(" %02x", tmp[i]);
676
        printf("\n");
677
        for(i = 0; i < 16; i++)
678
            printf(" %02x", out[i]);
679
        printf("\n");
680
    }
681
#endif
682
    return 0;
683
}
684

    
685
/* We have nothing to do for QCOW2 reopen, stubs just return
686
 * success */
687
static int qcow2_reopen_prepare(BDRVReopenState *state,
688
                                BlockReopenQueue *queue, Error **errp)
689
{
690
    return 0;
691
}
692

    
693
static int64_t coroutine_fn qcow2_co_get_block_status(BlockDriverState *bs,
694
        int64_t sector_num, int nb_sectors, int *pnum)
695
{
696
    BDRVQcowState *s = bs->opaque;
697
    uint64_t cluster_offset;
698
    int index_in_cluster, ret;
699
    int64_t status = 0;
700

    
701
    *pnum = nb_sectors;
702
    qemu_co_mutex_lock(&s->lock);
703
    ret = qcow2_get_cluster_offset(bs, sector_num << 9, pnum, &cluster_offset);
704
    qemu_co_mutex_unlock(&s->lock);
705
    if (ret < 0) {
706
        return ret;
707
    }
708

    
709
    if (cluster_offset != 0 && ret != QCOW2_CLUSTER_COMPRESSED &&
710
        !s->crypt_method) {
711
        index_in_cluster = sector_num & (s->cluster_sectors - 1);
712
        cluster_offset |= (index_in_cluster << BDRV_SECTOR_BITS);
713
        status |= BDRV_BLOCK_OFFSET_VALID | cluster_offset;
714
    }
715
    if (ret == QCOW2_CLUSTER_ZERO) {
716
        status |= BDRV_BLOCK_ZERO;
717
    } else if (ret != QCOW2_CLUSTER_UNALLOCATED) {
718
        status |= BDRV_BLOCK_DATA;
719
    }
720
    return status;
721
}
722

    
723
/* handle reading after the end of the backing file */
724
int qcow2_backing_read1(BlockDriverState *bs, QEMUIOVector *qiov,
725
                  int64_t sector_num, int nb_sectors)
726
{
727
    int n1;
728
    if ((sector_num + nb_sectors) <= bs->total_sectors)
729
        return nb_sectors;
730
    if (sector_num >= bs->total_sectors)
731
        n1 = 0;
732
    else
733
        n1 = bs->total_sectors - sector_num;
734

    
735
    qemu_iovec_memset(qiov, 512 * n1, 0, 512 * (nb_sectors - n1));
736

    
737
    return n1;
738
}
739

    
740
static coroutine_fn int qcow2_co_readv(BlockDriverState *bs, int64_t sector_num,
741
                          int remaining_sectors, QEMUIOVector *qiov)
742
{
743
    BDRVQcowState *s = bs->opaque;
744
    int index_in_cluster, n1;
745
    int ret;
746
    int cur_nr_sectors; /* number of sectors in current iteration */
747
    uint64_t cluster_offset = 0;
748
    uint64_t bytes_done = 0;
749
    QEMUIOVector hd_qiov;
750
    uint8_t *cluster_data = NULL;
751

    
752
    qemu_iovec_init(&hd_qiov, qiov->niov);
753

    
754
    qemu_co_mutex_lock(&s->lock);
755

    
756
    while (remaining_sectors != 0) {
757

    
758
        /* prepare next request */
759
        cur_nr_sectors = remaining_sectors;
760
        if (s->crypt_method) {
761
            cur_nr_sectors = MIN(cur_nr_sectors,
762
                QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors);
763
        }
764

    
765
        ret = qcow2_get_cluster_offset(bs, sector_num << 9,
766
            &cur_nr_sectors, &cluster_offset);
767
        if (ret < 0) {
768
            goto fail;
769
        }
770

    
771
        index_in_cluster = sector_num & (s->cluster_sectors - 1);
772

    
773
        qemu_iovec_reset(&hd_qiov);
774
        qemu_iovec_concat(&hd_qiov, qiov, bytes_done,
775
            cur_nr_sectors * 512);
776

    
777
        switch (ret) {
778
        case QCOW2_CLUSTER_UNALLOCATED:
779

    
780
            if (bs->backing_hd) {
781
                /* read from the base image */
782
                n1 = qcow2_backing_read1(bs->backing_hd, &hd_qiov,
783
                    sector_num, cur_nr_sectors);
784
                if (n1 > 0) {
785
                    BLKDBG_EVENT(bs->file, BLKDBG_READ_BACKING_AIO);
786
                    qemu_co_mutex_unlock(&s->lock);
787
                    ret = bdrv_co_readv(bs->backing_hd, sector_num,
788
                                        n1, &hd_qiov);
789
                    qemu_co_mutex_lock(&s->lock);
790
                    if (ret < 0) {
791
                        goto fail;
792
                    }
793
                }
794
            } else {
795
                /* Note: in this case, no need to wait */
796
                qemu_iovec_memset(&hd_qiov, 0, 0, 512 * cur_nr_sectors);
797
            }
798
            break;
799

    
800
        case QCOW2_CLUSTER_ZERO:
801
            qemu_iovec_memset(&hd_qiov, 0, 0, 512 * cur_nr_sectors);
802
            break;
803

    
804
        case QCOW2_CLUSTER_COMPRESSED:
805
            /* add AIO support for compressed blocks ? */
806
            ret = qcow2_decompress_cluster(bs, cluster_offset);
807
            if (ret < 0) {
808
                goto fail;
809
            }
810

    
811
            qemu_iovec_from_buf(&hd_qiov, 0,
812
                s->cluster_cache + index_in_cluster * 512,
813
                512 * cur_nr_sectors);
814
            break;
815

    
816
        case QCOW2_CLUSTER_NORMAL:
817
            if ((cluster_offset & 511) != 0) {
818
                ret = -EIO;
819
                goto fail;
820
            }
821

    
822
            if (s->crypt_method) {
823
                /*
824
                 * For encrypted images, read everything into a temporary
825
                 * contiguous buffer on which the AES functions can work.
826
                 */
827
                if (!cluster_data) {
828
                    cluster_data =
829
                        qemu_blockalign(bs, QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
830
                }
831

    
832
                assert(cur_nr_sectors <=
833
                    QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors);
834
                qemu_iovec_reset(&hd_qiov);
835
                qemu_iovec_add(&hd_qiov, cluster_data,
836
                    512 * cur_nr_sectors);
837
            }
838

    
839
            BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);
840
            qemu_co_mutex_unlock(&s->lock);
841
            ret = bdrv_co_readv(bs->file,
842
                                (cluster_offset >> 9) + index_in_cluster,
843
                                cur_nr_sectors, &hd_qiov);
844
            qemu_co_mutex_lock(&s->lock);
845
            if (ret < 0) {
846
                goto fail;
847
            }
848
            if (s->crypt_method) {
849
                qcow2_encrypt_sectors(s, sector_num,  cluster_data,
850
                    cluster_data, cur_nr_sectors, 0, &s->aes_decrypt_key);
851
                qemu_iovec_from_buf(qiov, bytes_done,
852
                    cluster_data, 512 * cur_nr_sectors);
853
            }
854
            break;
855

    
856
        default:
857
            g_assert_not_reached();
858
            ret = -EIO;
859
            goto fail;
860
        }
861

    
862
        remaining_sectors -= cur_nr_sectors;
863
        sector_num += cur_nr_sectors;
864
        bytes_done += cur_nr_sectors * 512;
865
    }
866
    ret = 0;
867

    
868
fail:
869
    qemu_co_mutex_unlock(&s->lock);
870

    
871
    qemu_iovec_destroy(&hd_qiov);
872
    qemu_vfree(cluster_data);
873

    
874
    return ret;
875
}
876

    
877
static coroutine_fn int qcow2_co_writev(BlockDriverState *bs,
878
                           int64_t sector_num,
879
                           int remaining_sectors,
880
                           QEMUIOVector *qiov)
881
{
882
    BDRVQcowState *s = bs->opaque;
883
    int index_in_cluster;
884
    int n_end;
885
    int ret;
886
    int cur_nr_sectors; /* number of sectors in current iteration */
887
    uint64_t cluster_offset;
888
    QEMUIOVector hd_qiov;
889
    uint64_t bytes_done = 0;
890
    uint8_t *cluster_data = NULL;
891
    QCowL2Meta *l2meta = NULL;
892

    
893
    trace_qcow2_writev_start_req(qemu_coroutine_self(), sector_num,
894
                                 remaining_sectors);
895

    
896
    qemu_iovec_init(&hd_qiov, qiov->niov);
897

    
898
    s->cluster_cache_offset = -1; /* disable compressed cache */
899

    
900
    qemu_co_mutex_lock(&s->lock);
901

    
902
    while (remaining_sectors != 0) {
903

    
904
        l2meta = NULL;
905

    
906
        trace_qcow2_writev_start_part(qemu_coroutine_self());
907
        index_in_cluster = sector_num & (s->cluster_sectors - 1);
908
        n_end = index_in_cluster + remaining_sectors;
909
        if (s->crypt_method &&
910
            n_end > QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors) {
911
            n_end = QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors;
912
        }
913

    
914
        ret = qcow2_alloc_cluster_offset(bs, sector_num << 9,
915
            index_in_cluster, n_end, &cur_nr_sectors, &cluster_offset, &l2meta);
916
        if (ret < 0) {
917
            goto fail;
918
        }
919

    
920
        assert((cluster_offset & 511) == 0);
921

    
922
        qemu_iovec_reset(&hd_qiov);
923
        qemu_iovec_concat(&hd_qiov, qiov, bytes_done,
924
            cur_nr_sectors * 512);
925

    
926
        if (s->crypt_method) {
927
            if (!cluster_data) {
928
                cluster_data = qemu_blockalign(bs, QCOW_MAX_CRYPT_CLUSTERS *
929
                                                 s->cluster_size);
930
            }
931

    
932
            assert(hd_qiov.size <=
933
                   QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
934
            qemu_iovec_to_buf(&hd_qiov, 0, cluster_data, hd_qiov.size);
935

    
936
            qcow2_encrypt_sectors(s, sector_num, cluster_data,
937
                cluster_data, cur_nr_sectors, 1, &s->aes_encrypt_key);
938

    
939
            qemu_iovec_reset(&hd_qiov);
940
            qemu_iovec_add(&hd_qiov, cluster_data,
941
                cur_nr_sectors * 512);
942
        }
943

    
944
        ret = qcow2_pre_write_overlap_check(bs, QCOW2_OL_DEFAULT,
945
                cluster_offset + index_in_cluster * BDRV_SECTOR_SIZE,
946
                cur_nr_sectors * BDRV_SECTOR_SIZE);
947
        if (ret < 0) {
948
            goto fail;
949
        }
950

    
951
        qemu_co_mutex_unlock(&s->lock);
952
        BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO);
953
        trace_qcow2_writev_data(qemu_coroutine_self(),
954
                                (cluster_offset >> 9) + index_in_cluster);
955
        ret = bdrv_co_writev(bs->file,
956
                             (cluster_offset >> 9) + index_in_cluster,
957
                             cur_nr_sectors, &hd_qiov);
958
        qemu_co_mutex_lock(&s->lock);
959
        if (ret < 0) {
960
            goto fail;
961
        }
962

    
963
        while (l2meta != NULL) {
964
            QCowL2Meta *next;
965

    
966
            ret = qcow2_alloc_cluster_link_l2(bs, l2meta);
967
            if (ret < 0) {
968
                goto fail;
969
            }
970

    
971
            /* Take the request off the list of running requests */
972
            if (l2meta->nb_clusters != 0) {
973
                QLIST_REMOVE(l2meta, next_in_flight);
974
            }
975

    
976
            qemu_co_queue_restart_all(&l2meta->dependent_requests);
977

    
978
            next = l2meta->next;
979
            g_free(l2meta);
980
            l2meta = next;
981
        }
982

    
983
        remaining_sectors -= cur_nr_sectors;
984
        sector_num += cur_nr_sectors;
985
        bytes_done += cur_nr_sectors * 512;
986
        trace_qcow2_writev_done_part(qemu_coroutine_self(), cur_nr_sectors);
987
    }
988
    ret = 0;
989

    
990
fail:
991
    qemu_co_mutex_unlock(&s->lock);
992

    
993
    while (l2meta != NULL) {
994
        QCowL2Meta *next;
995

    
996
        if (l2meta->nb_clusters != 0) {
997
            QLIST_REMOVE(l2meta, next_in_flight);
998
        }
999
        qemu_co_queue_restart_all(&l2meta->dependent_requests);
1000

    
1001
        next = l2meta->next;
1002
        g_free(l2meta);
1003
        l2meta = next;
1004
    }
1005

    
1006
    qemu_iovec_destroy(&hd_qiov);
1007
    qemu_vfree(cluster_data);
1008
    trace_qcow2_writev_done_req(qemu_coroutine_self(), ret);
1009

    
1010
    return ret;
1011
}
1012

    
1013
static void qcow2_close(BlockDriverState *bs)
1014
{
1015
    BDRVQcowState *s = bs->opaque;
1016
    g_free(s->l1_table);
1017
    /* else pre-write overlap checks in cache_destroy may crash */
1018
    s->l1_table = NULL;
1019

    
1020
    qcow2_cache_flush(bs, s->l2_table_cache);
1021
    qcow2_cache_flush(bs, s->refcount_block_cache);
1022

    
1023
    qcow2_mark_clean(bs);
1024

    
1025
    qcow2_cache_destroy(bs, s->l2_table_cache);
1026
    qcow2_cache_destroy(bs, s->refcount_block_cache);
1027

    
1028
    g_free(s->unknown_header_fields);
1029
    cleanup_unknown_header_ext(bs);
1030

    
1031
    g_free(s->cluster_cache);
1032
    qemu_vfree(s->cluster_data);
1033
    qcow2_refcount_close(bs);
1034
    qcow2_free_snapshots(bs);
1035
}
1036

    
1037
static void qcow2_invalidate_cache(BlockDriverState *bs)
1038
{
1039
    BDRVQcowState *s = bs->opaque;
1040
    int flags = s->flags;
1041
    AES_KEY aes_encrypt_key;
1042
    AES_KEY aes_decrypt_key;
1043
    uint32_t crypt_method = 0;
1044
    QDict *options;
1045

    
1046
    /*
1047
     * Backing files are read-only which makes all of their metadata immutable,
1048
     * that means we don't have to worry about reopening them here.
1049
     */
1050

    
1051
    if (s->crypt_method) {
1052
        crypt_method = s->crypt_method;
1053
        memcpy(&aes_encrypt_key, &s->aes_encrypt_key, sizeof(aes_encrypt_key));
1054
        memcpy(&aes_decrypt_key, &s->aes_decrypt_key, sizeof(aes_decrypt_key));
1055
    }
1056

    
1057
    qcow2_close(bs);
1058

    
1059
    options = qdict_new();
1060
    qdict_put(options, QCOW2_OPT_LAZY_REFCOUNTS,
1061
              qbool_from_int(s->use_lazy_refcounts));
1062

    
1063
    memset(s, 0, sizeof(BDRVQcowState));
1064
    qcow2_open(bs, options, flags, NULL);
1065

    
1066
    QDECREF(options);
1067

    
1068
    if (crypt_method) {
1069
        s->crypt_method = crypt_method;
1070
        memcpy(&s->aes_encrypt_key, &aes_encrypt_key, sizeof(aes_encrypt_key));
1071
        memcpy(&s->aes_decrypt_key, &aes_decrypt_key, sizeof(aes_decrypt_key));
1072
    }
1073
}
1074

    
1075
static size_t header_ext_add(char *buf, uint32_t magic, const void *s,
1076
    size_t len, size_t buflen)
1077
{
1078
    QCowExtension *ext_backing_fmt = (QCowExtension*) buf;
1079
    size_t ext_len = sizeof(QCowExtension) + ((len + 7) & ~7);
1080

    
1081
    if (buflen < ext_len) {
1082
        return -ENOSPC;
1083
    }
1084

    
1085
    *ext_backing_fmt = (QCowExtension) {
1086
        .magic  = cpu_to_be32(magic),
1087
        .len    = cpu_to_be32(len),
1088
    };
1089
    memcpy(buf + sizeof(QCowExtension), s, len);
1090

    
1091
    return ext_len;
1092
}
1093

    
1094
/*
1095
 * Updates the qcow2 header, including the variable length parts of it, i.e.
1096
 * the backing file name and all extensions. qcow2 was not designed to allow
1097
 * such changes, so if we run out of space (we can only use the first cluster)
1098
 * this function may fail.
1099
 *
1100
 * Returns 0 on success, -errno in error cases.
1101
 */
1102
int qcow2_update_header(BlockDriverState *bs)
1103
{
1104
    BDRVQcowState *s = bs->opaque;
1105
    QCowHeader *header;
1106
    char *buf;
1107
    size_t buflen = s->cluster_size;
1108
    int ret;
1109
    uint64_t total_size;
1110
    uint32_t refcount_table_clusters;
1111
    size_t header_length;
1112
    Qcow2UnknownHeaderExtension *uext;
1113

    
1114
    buf = qemu_blockalign(bs, buflen);
1115

    
1116
    /* Header structure */
1117
    header = (QCowHeader*) buf;
1118

    
1119
    if (buflen < sizeof(*header)) {
1120
        ret = -ENOSPC;
1121
        goto fail;
1122
    }
1123

    
1124
    header_length = sizeof(*header) + s->unknown_header_fields_size;
1125
    total_size = bs->total_sectors * BDRV_SECTOR_SIZE;
1126
    refcount_table_clusters = s->refcount_table_size >> (s->cluster_bits - 3);
1127

    
1128
    *header = (QCowHeader) {
1129
        /* Version 2 fields */
1130
        .magic                  = cpu_to_be32(QCOW_MAGIC),
1131
        .version                = cpu_to_be32(s->qcow_version),
1132
        .backing_file_offset    = 0,
1133
        .backing_file_size      = 0,
1134
        .cluster_bits           = cpu_to_be32(s->cluster_bits),
1135
        .size                   = cpu_to_be64(total_size),
1136
        .crypt_method           = cpu_to_be32(s->crypt_method_header),
1137
        .l1_size                = cpu_to_be32(s->l1_size),
1138
        .l1_table_offset        = cpu_to_be64(s->l1_table_offset),
1139
        .refcount_table_offset  = cpu_to_be64(s->refcount_table_offset),
1140
        .refcount_table_clusters = cpu_to_be32(refcount_table_clusters),
1141
        .nb_snapshots           = cpu_to_be32(s->nb_snapshots),
1142
        .snapshots_offset       = cpu_to_be64(s->snapshots_offset),
1143

    
1144
        /* Version 3 fields */
1145
        .incompatible_features  = cpu_to_be64(s->incompatible_features),
1146
        .compatible_features    = cpu_to_be64(s->compatible_features),
1147
        .autoclear_features     = cpu_to_be64(s->autoclear_features),
1148
        .refcount_order         = cpu_to_be32(s->refcount_order),
1149
        .header_length          = cpu_to_be32(header_length),
1150
    };
1151

    
1152
    /* For older versions, write a shorter header */
1153
    switch (s->qcow_version) {
1154
    case 2:
1155
        ret = offsetof(QCowHeader, incompatible_features);
1156
        break;
1157
    case 3:
1158
        ret = sizeof(*header);
1159
        break;
1160
    default:
1161
        ret = -EINVAL;
1162
        goto fail;
1163
    }
1164

    
1165
    buf += ret;
1166
    buflen -= ret;
1167
    memset(buf, 0, buflen);
1168

    
1169
    /* Preserve any unknown field in the header */
1170
    if (s->unknown_header_fields_size) {
1171
        if (buflen < s->unknown_header_fields_size) {
1172
            ret = -ENOSPC;
1173
            goto fail;
1174
        }
1175

    
1176
        memcpy(buf, s->unknown_header_fields, s->unknown_header_fields_size);
1177
        buf += s->unknown_header_fields_size;
1178
        buflen -= s->unknown_header_fields_size;
1179
    }
1180

    
1181
    /* Backing file format header extension */
1182
    if (*bs->backing_format) {
1183
        ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BACKING_FORMAT,
1184
                             bs->backing_format, strlen(bs->backing_format),
1185
                             buflen);
1186
        if (ret < 0) {
1187
            goto fail;
1188
        }
1189

    
1190
        buf += ret;
1191
        buflen -= ret;
1192
    }
1193

    
1194
    /* Feature table */
1195
    Qcow2Feature features[] = {
1196
        {
1197
            .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
1198
            .bit  = QCOW2_INCOMPAT_DIRTY_BITNR,
1199
            .name = "dirty bit",
1200
        },
1201
        {
1202
            .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
1203
            .bit  = QCOW2_INCOMPAT_CORRUPT_BITNR,
1204
            .name = "corrupt bit",
1205
        },
1206
        {
1207
            .type = QCOW2_FEAT_TYPE_COMPATIBLE,
1208
            .bit  = QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR,
1209
            .name = "lazy refcounts",
1210
        },
1211
    };
1212

    
1213
    ret = header_ext_add(buf, QCOW2_EXT_MAGIC_FEATURE_TABLE,
1214
                         features, sizeof(features), buflen);
1215
    if (ret < 0) {
1216
        goto fail;
1217
    }
1218
    buf += ret;
1219
    buflen -= ret;
1220

    
1221
    /* Keep unknown header extensions */
1222
    QLIST_FOREACH(uext, &s->unknown_header_ext, next) {
1223
        ret = header_ext_add(buf, uext->magic, uext->data, uext->len, buflen);
1224
        if (ret < 0) {
1225
            goto fail;
1226
        }
1227

    
1228
        buf += ret;
1229
        buflen -= ret;
1230
    }
1231

    
1232
    /* End of header extensions */
1233
    ret = header_ext_add(buf, QCOW2_EXT_MAGIC_END, NULL, 0, buflen);
1234
    if (ret < 0) {
1235
        goto fail;
1236
    }
1237

    
1238
    buf += ret;
1239
    buflen -= ret;
1240

    
1241
    /* Backing file name */
1242
    if (*bs->backing_file) {
1243
        size_t backing_file_len = strlen(bs->backing_file);
1244

    
1245
        if (buflen < backing_file_len) {
1246
            ret = -ENOSPC;
1247
            goto fail;
1248
        }
1249

    
1250
        /* Using strncpy is ok here, since buf is not NUL-terminated. */
1251
        strncpy(buf, bs->backing_file, buflen);
1252

    
1253
        header->backing_file_offset = cpu_to_be64(buf - ((char*) header));
1254
        header->backing_file_size   = cpu_to_be32(backing_file_len);
1255
    }
1256

    
1257
    /* Write the new header */
1258
    ret = bdrv_pwrite(bs->file, 0, header, s->cluster_size);
1259
    if (ret < 0) {
1260
        goto fail;
1261
    }
1262

    
1263
    ret = 0;
1264
fail:
1265
    qemu_vfree(header);
1266
    return ret;
1267
}
1268

    
1269
static int qcow2_change_backing_file(BlockDriverState *bs,
1270
    const char *backing_file, const char *backing_fmt)
1271
{
1272
    pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
1273
    pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
1274

    
1275
    return qcow2_update_header(bs);
1276
}
1277

    
1278
static int preallocate(BlockDriverState *bs)
1279
{
1280
    uint64_t nb_sectors;
1281
    uint64_t offset;
1282
    uint64_t host_offset = 0;
1283
    int num;
1284
    int ret;
1285
    QCowL2Meta *meta;
1286

    
1287
    nb_sectors = bdrv_getlength(bs) >> 9;
1288
    offset = 0;
1289

    
1290
    while (nb_sectors) {
1291
        num = MIN(nb_sectors, INT_MAX >> 9);
1292
        ret = qcow2_alloc_cluster_offset(bs, offset, 0, num, &num,
1293
                                         &host_offset, &meta);
1294
        if (ret < 0) {
1295
            return ret;
1296
        }
1297

    
1298
        ret = qcow2_alloc_cluster_link_l2(bs, meta);
1299
        if (ret < 0) {
1300
            qcow2_free_any_clusters(bs, meta->alloc_offset, meta->nb_clusters,
1301
                                    QCOW2_DISCARD_NEVER);
1302
            return ret;
1303
        }
1304

    
1305
        /* There are no dependent requests, but we need to remove our request
1306
         * from the list of in-flight requests */
1307
        if (meta != NULL) {
1308
            QLIST_REMOVE(meta, next_in_flight);
1309
        }
1310

    
1311
        /* TODO Preallocate data if requested */
1312

    
1313
        nb_sectors -= num;
1314
        offset += num << 9;
1315
    }
1316

    
1317
    /*
1318
     * It is expected that the image file is large enough to actually contain
1319
     * all of the allocated clusters (otherwise we get failing reads after
1320
     * EOF). Extend the image to the last allocated sector.
1321
     */
1322
    if (host_offset != 0) {
1323
        uint8_t buf[512];
1324
        memset(buf, 0, 512);
1325
        ret = bdrv_write(bs->file, (host_offset >> 9) + num - 1, buf, 1);
1326
        if (ret < 0) {
1327
            return ret;
1328
        }
1329
    }
1330

    
1331
    return 0;
1332
}
1333

    
1334
static int qcow2_create2(const char *filename, int64_t total_size,
1335
                         const char *backing_file, const char *backing_format,
1336
                         int flags, size_t cluster_size, int prealloc,
1337
                         QEMUOptionParameter *options, int version)
1338
{
1339
    /* Calculate cluster_bits */
1340
    int cluster_bits;
1341
    cluster_bits = ffs(cluster_size) - 1;
1342
    if (cluster_bits < MIN_CLUSTER_BITS || cluster_bits > MAX_CLUSTER_BITS ||
1343
        (1 << cluster_bits) != cluster_size)
1344
    {
1345
        error_report(
1346
            "Cluster size must be a power of two between %d and %dk",
1347
            1 << MIN_CLUSTER_BITS, 1 << (MAX_CLUSTER_BITS - 10));
1348
        return -EINVAL;
1349
    }
1350

    
1351
    /*
1352
     * Open the image file and write a minimal qcow2 header.
1353
     *
1354
     * We keep things simple and start with a zero-sized image. We also
1355
     * do without refcount blocks or a L1 table for now. We'll fix the
1356
     * inconsistency later.
1357
     *
1358
     * We do need a refcount table because growing the refcount table means
1359
     * allocating two new refcount blocks - the seconds of which would be at
1360
     * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
1361
     * size for any qcow2 image.
1362
     */
1363
    BlockDriverState* bs;
1364
    QCowHeader header;
1365
    uint8_t* refcount_table;
1366
    int ret;
1367

    
1368
    ret = bdrv_create_file(filename, options);
1369
    if (ret < 0) {
1370
        return ret;
1371
    }
1372

    
1373
    ret = bdrv_file_open(&bs, filename, NULL, BDRV_O_RDWR, NULL);
1374
    if (ret < 0) {
1375
        return ret;
1376
    }
1377

    
1378
    /* Write the header */
1379
    memset(&header, 0, sizeof(header));
1380
    header.magic = cpu_to_be32(QCOW_MAGIC);
1381
    header.version = cpu_to_be32(version);
1382
    header.cluster_bits = cpu_to_be32(cluster_bits);
1383
    header.size = cpu_to_be64(0);
1384
    header.l1_table_offset = cpu_to_be64(0);
1385
    header.l1_size = cpu_to_be32(0);
1386
    header.refcount_table_offset = cpu_to_be64(cluster_size);
1387
    header.refcount_table_clusters = cpu_to_be32(1);
1388
    header.refcount_order = cpu_to_be32(3 + REFCOUNT_SHIFT);
1389
    header.header_length = cpu_to_be32(sizeof(header));
1390

    
1391
    if (flags & BLOCK_FLAG_ENCRYPT) {
1392
        header.crypt_method = cpu_to_be32(QCOW_CRYPT_AES);
1393
    } else {
1394
        header.crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
1395
    }
1396

    
1397
    if (flags & BLOCK_FLAG_LAZY_REFCOUNTS) {
1398
        header.compatible_features |=
1399
            cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS);
1400
    }
1401

    
1402
    ret = bdrv_pwrite(bs, 0, &header, sizeof(header));
1403
    if (ret < 0) {
1404
        goto out;
1405
    }
1406

    
1407
    /* Write an empty refcount table */
1408
    refcount_table = g_malloc0(cluster_size);
1409
    ret = bdrv_pwrite(bs, cluster_size, refcount_table, cluster_size);
1410
    g_free(refcount_table);
1411

    
1412
    if (ret < 0) {
1413
        goto out;
1414
    }
1415

    
1416
    bdrv_close(bs);
1417

    
1418
    /*
1419
     * And now open the image and make it consistent first (i.e. increase the
1420
     * refcount of the cluster that is occupied by the header and the refcount
1421
     * table)
1422
     */
1423
    BlockDriver* drv = bdrv_find_format("qcow2");
1424
    assert(drv != NULL);
1425
    ret = bdrv_open(bs, filename, NULL,
1426
        BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_NO_FLUSH, drv, NULL);
1427
    if (ret < 0) {
1428
        goto out;
1429
    }
1430

    
1431
    ret = qcow2_alloc_clusters(bs, 2 * cluster_size);
1432
    if (ret < 0) {
1433
        goto out;
1434

    
1435
    } else if (ret != 0) {
1436
        error_report("Huh, first cluster in empty image is already in use?");
1437
        abort();
1438
    }
1439

    
1440
    /* Okay, now that we have a valid image, let's give it the right size */
1441
    ret = bdrv_truncate(bs, total_size * BDRV_SECTOR_SIZE);
1442
    if (ret < 0) {
1443
        goto out;
1444
    }
1445

    
1446
    /* Want a backing file? There you go.*/
1447
    if (backing_file) {
1448
        ret = bdrv_change_backing_file(bs, backing_file, backing_format);
1449
        if (ret < 0) {
1450
            goto out;
1451
        }
1452
    }
1453

    
1454
    /* And if we're supposed to preallocate metadata, do that now */
1455
    if (prealloc) {
1456
        BDRVQcowState *s = bs->opaque;
1457
        qemu_co_mutex_lock(&s->lock);
1458
        ret = preallocate(bs);
1459
        qemu_co_mutex_unlock(&s->lock);
1460
        if (ret < 0) {
1461
            goto out;
1462
        }
1463
    }
1464

    
1465
    ret = 0;
1466
out:
1467
    bdrv_unref(bs);
1468
    return ret;
1469
}
1470

    
1471
static int qcow2_create(const char *filename, QEMUOptionParameter *options,
1472
                        Error **errp)
1473
{
1474
    const char *backing_file = NULL;
1475
    const char *backing_fmt = NULL;
1476
    uint64_t sectors = 0;
1477
    int flags = 0;
1478
    size_t cluster_size = DEFAULT_CLUSTER_SIZE;
1479
    int prealloc = 0;
1480
    int version = 3;
1481

    
1482
    /* Read out options */
1483
    while (options && options->name) {
1484
        if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
1485
            sectors = options->value.n / 512;
1486
        } else if (!strcmp(options->name, BLOCK_OPT_BACKING_FILE)) {
1487
            backing_file = options->value.s;
1488
        } else if (!strcmp(options->name, BLOCK_OPT_BACKING_FMT)) {
1489
            backing_fmt = options->value.s;
1490
        } else if (!strcmp(options->name, BLOCK_OPT_ENCRYPT)) {
1491
            flags |= options->value.n ? BLOCK_FLAG_ENCRYPT : 0;
1492
        } else if (!strcmp(options->name, BLOCK_OPT_CLUSTER_SIZE)) {
1493
            if (options->value.n) {
1494
                cluster_size = options->value.n;
1495
            }
1496
        } else if (!strcmp(options->name, BLOCK_OPT_PREALLOC)) {
1497
            if (!options->value.s || !strcmp(options->value.s, "off")) {
1498
                prealloc = 0;
1499
            } else if (!strcmp(options->value.s, "metadata")) {
1500
                prealloc = 1;
1501
            } else {
1502
                fprintf(stderr, "Invalid preallocation mode: '%s'\n",
1503
                    options->value.s);
1504
                return -EINVAL;
1505
            }
1506
        } else if (!strcmp(options->name, BLOCK_OPT_COMPAT_LEVEL)) {
1507
            if (!options->value.s) {
1508
                /* keep the default */
1509
            } else if (!strcmp(options->value.s, "0.10")) {
1510
                version = 2;
1511
            } else if (!strcmp(options->value.s, "1.1")) {
1512
                version = 3;
1513
            } else {
1514
                fprintf(stderr, "Invalid compatibility level: '%s'\n",
1515
                    options->value.s);
1516
                return -EINVAL;
1517
            }
1518
        } else if (!strcmp(options->name, BLOCK_OPT_LAZY_REFCOUNTS)) {
1519
            flags |= options->value.n ? BLOCK_FLAG_LAZY_REFCOUNTS : 0;
1520
        }
1521
        options++;
1522
    }
1523

    
1524
    if (backing_file && prealloc) {
1525
        fprintf(stderr, "Backing file and preallocation cannot be used at "
1526
            "the same time\n");
1527
        return -EINVAL;
1528
    }
1529

    
1530
    if (version < 3 && (flags & BLOCK_FLAG_LAZY_REFCOUNTS)) {
1531
        fprintf(stderr, "Lazy refcounts only supported with compatibility "
1532
                "level 1.1 and above (use compat=1.1 or greater)\n");
1533
        return -EINVAL;
1534
    }
1535

    
1536
    return qcow2_create2(filename, sectors, backing_file, backing_fmt, flags,
1537
                         cluster_size, prealloc, options, version);
1538
}
1539

    
1540
static int qcow2_make_empty(BlockDriverState *bs)
1541
{
1542
#if 0
1543
    /* XXX: not correct */
1544
    BDRVQcowState *s = bs->opaque;
1545
    uint32_t l1_length = s->l1_size * sizeof(uint64_t);
1546
    int ret;
1547

1548
    memset(s->l1_table, 0, l1_length);
1549
    if (bdrv_pwrite(bs->file, s->l1_table_offset, s->l1_table, l1_length) < 0)
1550
        return -1;
1551
    ret = bdrv_truncate(bs->file, s->l1_table_offset + l1_length);
1552
    if (ret < 0)
1553
        return ret;
1554

1555
    l2_cache_reset(bs);
1556
#endif
1557
    return 0;
1558
}
1559

    
1560
static coroutine_fn int qcow2_co_write_zeroes(BlockDriverState *bs,
1561
    int64_t sector_num, int nb_sectors)
1562
{
1563
    int ret;
1564
    BDRVQcowState *s = bs->opaque;
1565

    
1566
    /* Emulate misaligned zero writes */
1567
    if (sector_num % s->cluster_sectors || nb_sectors % s->cluster_sectors) {
1568
        return -ENOTSUP;
1569
    }
1570

    
1571
    /* Whatever is left can use real zero clusters */
1572
    qemu_co_mutex_lock(&s->lock);
1573
    ret = qcow2_zero_clusters(bs, sector_num << BDRV_SECTOR_BITS,
1574
        nb_sectors);
1575
    qemu_co_mutex_unlock(&s->lock);
1576

    
1577
    return ret;
1578
}
1579

    
1580
static coroutine_fn int qcow2_co_discard(BlockDriverState *bs,
1581
    int64_t sector_num, int nb_sectors)
1582
{
1583
    int ret;
1584
    BDRVQcowState *s = bs->opaque;
1585

    
1586
    qemu_co_mutex_lock(&s->lock);
1587
    ret = qcow2_discard_clusters(bs, sector_num << BDRV_SECTOR_BITS,
1588
        nb_sectors, QCOW2_DISCARD_REQUEST);
1589
    qemu_co_mutex_unlock(&s->lock);
1590
    return ret;
1591
}
1592

    
1593
static int qcow2_truncate(BlockDriverState *bs, int64_t offset)
1594
{
1595
    BDRVQcowState *s = bs->opaque;
1596
    int64_t new_l1_size;
1597
    int ret;
1598

    
1599
    if (offset & 511) {
1600
        error_report("The new size must be a multiple of 512");
1601
        return -EINVAL;
1602
    }
1603

    
1604
    /* cannot proceed if image has snapshots */
1605
    if (s->nb_snapshots) {
1606
        error_report("Can't resize an image which has snapshots");
1607
        return -ENOTSUP;
1608
    }
1609

    
1610
    /* shrinking is currently not supported */
1611
    if (offset < bs->total_sectors * 512) {
1612
        error_report("qcow2 doesn't support shrinking images yet");
1613
        return -ENOTSUP;
1614
    }
1615

    
1616
    new_l1_size = size_to_l1(s, offset);
1617
    ret = qcow2_grow_l1_table(bs, new_l1_size, true);
1618
    if (ret < 0) {
1619
        return ret;
1620
    }
1621

    
1622
    /* write updated header.size */
1623
    offset = cpu_to_be64(offset);
1624
    ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, size),
1625
                           &offset, sizeof(uint64_t));
1626
    if (ret < 0) {
1627
        return ret;
1628
    }
1629

    
1630
    s->l1_vm_state_index = new_l1_size;
1631
    return 0;
1632
}
1633

    
1634
/* XXX: put compressed sectors first, then all the cluster aligned
1635
   tables to avoid losing bytes in alignment */
1636
static int qcow2_write_compressed(BlockDriverState *bs, int64_t sector_num,
1637
                                  const uint8_t *buf, int nb_sectors)
1638
{
1639
    BDRVQcowState *s = bs->opaque;
1640
    z_stream strm;
1641
    int ret, out_len;
1642
    uint8_t *out_buf;
1643
    uint64_t cluster_offset;
1644

    
1645
    if (nb_sectors == 0) {
1646
        /* align end of file to a sector boundary to ease reading with
1647
           sector based I/Os */
1648
        cluster_offset = bdrv_getlength(bs->file);
1649
        cluster_offset = (cluster_offset + 511) & ~511;
1650
        bdrv_truncate(bs->file, cluster_offset);
1651
        return 0;
1652
    }
1653

    
1654
    if (nb_sectors != s->cluster_sectors) {
1655
        ret = -EINVAL;
1656

    
1657
        /* Zero-pad last write if image size is not cluster aligned */
1658
        if (sector_num + nb_sectors == bs->total_sectors &&
1659
            nb_sectors < s->cluster_sectors) {
1660
            uint8_t *pad_buf = qemu_blockalign(bs, s->cluster_size);
1661
            memset(pad_buf, 0, s->cluster_size);
1662
            memcpy(pad_buf, buf, nb_sectors * BDRV_SECTOR_SIZE);
1663
            ret = qcow2_write_compressed(bs, sector_num,
1664
                                         pad_buf, s->cluster_sectors);
1665
            qemu_vfree(pad_buf);
1666
        }
1667
        return ret;
1668
    }
1669

    
1670
    out_buf = g_malloc(s->cluster_size + (s->cluster_size / 1000) + 128);
1671

    
1672
    /* best compression, small window, no zlib header */
1673
    memset(&strm, 0, sizeof(strm));
1674
    ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
1675
                       Z_DEFLATED, -12,
1676
                       9, Z_DEFAULT_STRATEGY);
1677
    if (ret != 0) {
1678
        ret = -EINVAL;
1679
        goto fail;
1680
    }
1681

    
1682
    strm.avail_in = s->cluster_size;
1683
    strm.next_in = (uint8_t *)buf;
1684
    strm.avail_out = s->cluster_size;
1685
    strm.next_out = out_buf;
1686

    
1687
    ret = deflate(&strm, Z_FINISH);
1688
    if (ret != Z_STREAM_END && ret != Z_OK) {
1689
        deflateEnd(&strm);
1690
        ret = -EINVAL;
1691
        goto fail;
1692
    }
1693
    out_len = strm.next_out - out_buf;
1694

    
1695
    deflateEnd(&strm);
1696

    
1697
    if (ret != Z_STREAM_END || out_len >= s->cluster_size) {
1698
        /* could not compress: write normal cluster */
1699

    
1700
        ret = qcow2_pre_write_overlap_check(bs, QCOW2_OL_DEFAULT,
1701
                sector_num * BDRV_SECTOR_SIZE,
1702
                s->cluster_sectors * BDRV_SECTOR_SIZE);
1703
        if (ret < 0) {
1704
            goto fail;
1705
        }
1706

    
1707
        ret = bdrv_write(bs, sector_num, buf, s->cluster_sectors);
1708
        if (ret < 0) {
1709
            goto fail;
1710
        }
1711
    } else {
1712
        cluster_offset = qcow2_alloc_compressed_cluster_offset(bs,
1713
            sector_num << 9, out_len);
1714
        if (!cluster_offset) {
1715
            ret = -EIO;
1716
            goto fail;
1717
        }
1718
        cluster_offset &= s->cluster_offset_mask;
1719

    
1720
        ret = qcow2_pre_write_overlap_check(bs, QCOW2_OL_DEFAULT,
1721
                cluster_offset, out_len);
1722
        if (ret < 0) {
1723
            goto fail;
1724
        }
1725

    
1726
        BLKDBG_EVENT(bs->file, BLKDBG_WRITE_COMPRESSED);
1727
        ret = bdrv_pwrite(bs->file, cluster_offset, out_buf, out_len);
1728
        if (ret < 0) {
1729
            goto fail;
1730
        }
1731
    }
1732

    
1733
    ret = 0;
1734
fail:
1735
    g_free(out_buf);
1736
    return ret;
1737
}
1738

    
1739
static coroutine_fn int qcow2_co_flush_to_os(BlockDriverState *bs)
1740
{
1741
    BDRVQcowState *s = bs->opaque;
1742
    int ret;
1743

    
1744
    qemu_co_mutex_lock(&s->lock);
1745
    ret = qcow2_cache_flush(bs, s->l2_table_cache);
1746
    if (ret < 0) {
1747
        qemu_co_mutex_unlock(&s->lock);
1748
        return ret;
1749
    }
1750

    
1751
    if (qcow2_need_accurate_refcounts(s)) {
1752
        ret = qcow2_cache_flush(bs, s->refcount_block_cache);
1753
        if (ret < 0) {
1754
            qemu_co_mutex_unlock(&s->lock);
1755
            return ret;
1756
        }
1757
    }
1758
    qemu_co_mutex_unlock(&s->lock);
1759

    
1760
    return 0;
1761
}
1762

    
1763
static int qcow2_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1764
{
1765
    BDRVQcowState *s = bs->opaque;
1766
    bdi->cluster_size = s->cluster_size;
1767
    bdi->vm_state_offset = qcow2_vm_state_offset(s);
1768
    return 0;
1769
}
1770

    
1771
#if 0
1772
static void dump_refcounts(BlockDriverState *bs)
1773
{
1774
    BDRVQcowState *s = bs->opaque;
1775
    int64_t nb_clusters, k, k1, size;
1776
    int refcount;
1777

1778
    size = bdrv_getlength(bs->file);
1779
    nb_clusters = size_to_clusters(s, size);
1780
    for(k = 0; k < nb_clusters;) {
1781
        k1 = k;
1782
        refcount = get_refcount(bs, k);
1783
        k++;
1784
        while (k < nb_clusters && get_refcount(bs, k) == refcount)
1785
            k++;
1786
        printf("%" PRId64 ": refcount=%d nb=%" PRId64 "\n", k, refcount,
1787
               k - k1);
1788
    }
1789
}
1790
#endif
1791

    
1792
static int qcow2_save_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
1793
                              int64_t pos)
1794
{
1795
    BDRVQcowState *s = bs->opaque;
1796
    int growable = bs->growable;
1797
    int ret;
1798

    
1799
    BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_SAVE);
1800
    bs->growable = 1;
1801
    ret = bdrv_pwritev(bs, qcow2_vm_state_offset(s) + pos, qiov);
1802
    bs->growable = growable;
1803

    
1804
    return ret;
1805
}
1806

    
1807
static int qcow2_load_vmstate(BlockDriverState *bs, uint8_t *buf,
1808
                              int64_t pos, int size)
1809
{
1810
    BDRVQcowState *s = bs->opaque;
1811
    int growable = bs->growable;
1812
    bool zero_beyond_eof = bs->zero_beyond_eof;
1813
    int ret;
1814

    
1815
    BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_LOAD);
1816
    bs->growable = 1;
1817
    bs->zero_beyond_eof = false;
1818
    ret = bdrv_pread(bs, qcow2_vm_state_offset(s) + pos, buf, size);
1819
    bs->growable = growable;
1820
    bs->zero_beyond_eof = zero_beyond_eof;
1821

    
1822
    return ret;
1823
}
1824

    
1825
/*
1826
 * Downgrades an image's version. To achieve this, any incompatible features
1827
 * have to be removed.
1828
 */
1829
static int qcow2_downgrade(BlockDriverState *bs, int target_version)
1830
{
1831
    BDRVQcowState *s = bs->opaque;
1832
    int current_version = s->qcow_version;
1833
    int ret;
1834

    
1835
    if (target_version == current_version) {
1836
        return 0;
1837
    } else if (target_version > current_version) {
1838
        return -EINVAL;
1839
    } else if (target_version != 2) {
1840
        return -EINVAL;
1841
    }
1842

    
1843
    if (s->refcount_order != 4) {
1844
        /* we would have to convert the image to a refcount_order == 4 image
1845
         * here; however, since qemu (at the time of writing this) does not
1846
         * support anything different than 4 anyway, there is no point in doing
1847
         * so right now; however, we should error out (if qemu supports this in
1848
         * the future and this code has not been adapted) */
1849
        error_report("qcow2_downgrade: Image refcount orders other than 4 are"
1850
                     "currently not supported.");
1851
        return -ENOTSUP;
1852
    }
1853

    
1854
    /* clear incompatible features */
1855
    if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
1856
        ret = qcow2_mark_clean(bs);
1857
        if (ret < 0) {
1858
            return ret;
1859
        }
1860
    }
1861

    
1862
    /* with QCOW2_INCOMPAT_CORRUPT, it is pretty much impossible to get here in
1863
     * the first place; if that happens nonetheless, returning -ENOTSUP is the
1864
     * best thing to do anyway */
1865

    
1866
    if (s->incompatible_features) {
1867
        return -ENOTSUP;
1868
    }
1869

    
1870
    /* since we can ignore compatible features, we can set them to 0 as well */
1871
    s->compatible_features = 0;
1872
    /* if lazy refcounts have been used, they have already been fixed through
1873
     * clearing the dirty flag */
1874

    
1875
    /* clearing autoclear features is trivial */
1876
    s->autoclear_features = 0;
1877

    
1878
    ret = qcow2_expand_zero_clusters(bs);
1879
    if (ret < 0) {
1880
        return ret;
1881
    }
1882

    
1883
    s->qcow_version = target_version;
1884
    ret = qcow2_update_header(bs);
1885
    if (ret < 0) {
1886
        s->qcow_version = current_version;
1887
        return ret;
1888
    }
1889
    return 0;
1890
}
1891

    
1892
static int qcow2_amend_options(BlockDriverState *bs,
1893
                               QEMUOptionParameter *options)
1894
{
1895
    BDRVQcowState *s = bs->opaque;
1896
    int old_version = s->qcow_version, new_version = old_version;
1897
    uint64_t new_size = 0;
1898
    const char *backing_file = NULL, *backing_format = NULL;
1899
    bool lazy_refcounts = s->use_lazy_refcounts;
1900
    int ret;
1901
    int i;
1902

    
1903
    for (i = 0; options[i].name; i++)
1904
    {
1905
        if (!options[i].assigned) {
1906
            /* only change explicitly defined options */
1907
            continue;
1908
        }
1909

    
1910
        if (!strcmp(options[i].name, "compat")) {
1911
            if (!options[i].value.s) {
1912
                /* preserve default */
1913
            } else if (!strcmp(options[i].value.s, "0.10")) {
1914
                new_version = 2;
1915
            } else if (!strcmp(options[i].value.s, "1.1")) {
1916
                new_version = 3;
1917
            } else {
1918
                fprintf(stderr, "Unknown compatibility level %s.\n",
1919
                        options[i].value.s);
1920
                return -EINVAL;
1921
            }
1922
        } else if (!strcmp(options[i].name, "preallocation")) {
1923
            fprintf(stderr, "Cannot change preallocation mode.\n");
1924
            return -ENOTSUP;
1925
        } else if (!strcmp(options[i].name, "size")) {
1926
            new_size = options[i].value.n;
1927
        } else if (!strcmp(options[i].name, "backing_file")) {
1928
            backing_file = options[i].value.s;
1929
        } else if (!strcmp(options[i].name, "backing_fmt")) {
1930
            backing_format = options[i].value.s;
1931
        } else if (!strcmp(options[i].name, "encryption")) {
1932
            if ((options[i].value.n != !!s->crypt_method)) {
1933
                fprintf(stderr, "Changing the encryption flag is not "
1934
                        "supported.\n");
1935
                return -ENOTSUP;
1936
            }
1937
        } else if (!strcmp(options[i].name, "cluster_size")) {
1938
            if (options[i].value.n != s->cluster_size) {
1939
                fprintf(stderr, "Changing the cluster size is not "
1940
                        "supported.\n");
1941
                return -ENOTSUP;
1942
            }
1943
        } else if (!strcmp(options[i].name, "lazy_refcounts")) {
1944
            lazy_refcounts = options[i].value.n;
1945
        } else {
1946
            /* if this assertion fails, this probably means a new option was
1947
             * added without having it covered here */
1948
            assert(false);
1949
        }
1950
    }
1951

    
1952
    if (new_version != old_version) {
1953
        if (new_version > old_version) {
1954
            /* Upgrade */
1955
            s->qcow_version = new_version;
1956
            ret = qcow2_update_header(bs);
1957
            if (ret < 0) {
1958
                s->qcow_version = old_version;
1959
                return ret;
1960
            }
1961
        } else {
1962
            ret = qcow2_downgrade(bs, new_version);
1963
            if (ret < 0) {
1964
                return ret;
1965
            }
1966
        }
1967
    }
1968

    
1969
    if (backing_file || backing_format) {
1970
        ret = qcow2_change_backing_file(bs, backing_file ?: bs->backing_file,
1971
                                        backing_format ?: bs->backing_format);
1972
        if (ret < 0) {
1973
            return ret;
1974
        }
1975
    }
1976

    
1977
    if (s->use_lazy_refcounts != lazy_refcounts) {
1978
        if (lazy_refcounts) {
1979
            if (s->qcow_version < 3) {
1980
                fprintf(stderr, "Lazy refcounts only supported with compatibility "
1981
                        "level 1.1 and above (use compat=1.1 or greater)\n");
1982
                return -EINVAL;
1983
            }
1984
            s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
1985
            ret = qcow2_update_header(bs);
1986
            if (ret < 0) {
1987
                s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
1988
                return ret;
1989
            }
1990
            s->use_lazy_refcounts = true;
1991
        } else {
1992
            /* make image clean first */
1993
            ret = qcow2_mark_clean(bs);
1994
            if (ret < 0) {
1995
                return ret;
1996
            }
1997
            /* now disallow lazy refcounts */
1998
            s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
1999
            ret = qcow2_update_header(bs);
2000
            if (ret < 0) {
2001
                s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
2002
                return ret;
2003
            }
2004
            s->use_lazy_refcounts = false;
2005
        }
2006
    }
2007

    
2008
    if (new_size) {
2009
        ret = bdrv_truncate(bs, new_size);
2010
        if (ret < 0) {
2011
            return ret;
2012
        }
2013
    }
2014

    
2015
    return 0;
2016
}
2017

    
2018
static QEMUOptionParameter qcow2_create_options[] = {
2019
    {
2020
        .name = BLOCK_OPT_SIZE,
2021
        .type = OPT_SIZE,
2022
        .help = "Virtual disk size"
2023
    },
2024
    {
2025
        .name = BLOCK_OPT_COMPAT_LEVEL,
2026
        .type = OPT_STRING,
2027
        .help = "Compatibility level (0.10 or 1.1)"
2028
    },
2029
    {
2030
        .name = BLOCK_OPT_BACKING_FILE,
2031
        .type = OPT_STRING,
2032
        .help = "File name of a base image"
2033
    },
2034
    {
2035
        .name = BLOCK_OPT_BACKING_FMT,
2036
        .type = OPT_STRING,
2037
        .help = "Image format of the base image"
2038
    },
2039
    {
2040
        .name = BLOCK_OPT_ENCRYPT,
2041
        .type = OPT_FLAG,
2042
        .help = "Encrypt the image"
2043
    },
2044
    {
2045
        .name = BLOCK_OPT_CLUSTER_SIZE,
2046
        .type = OPT_SIZE,
2047
        .help = "qcow2 cluster size",
2048
        .value = { .n = DEFAULT_CLUSTER_SIZE },
2049
    },
2050
    {
2051
        .name = BLOCK_OPT_PREALLOC,
2052
        .type = OPT_STRING,
2053
        .help = "Preallocation mode (allowed values: off, metadata)"
2054
    },
2055
    {
2056
        .name = BLOCK_OPT_LAZY_REFCOUNTS,
2057
        .type = OPT_FLAG,
2058
        .help = "Postpone refcount updates",
2059
    },
2060
    { NULL }
2061
};
2062

    
2063
static BlockDriver bdrv_qcow2 = {
2064
    .format_name        = "qcow2",
2065
    .instance_size      = sizeof(BDRVQcowState),
2066
    .bdrv_probe         = qcow2_probe,
2067
    .bdrv_open          = qcow2_open,
2068
    .bdrv_close         = qcow2_close,
2069
    .bdrv_reopen_prepare  = qcow2_reopen_prepare,
2070
    .bdrv_create        = qcow2_create,
2071
    .bdrv_has_zero_init = bdrv_has_zero_init_1,
2072
    .bdrv_co_get_block_status = qcow2_co_get_block_status,
2073
    .bdrv_set_key       = qcow2_set_key,
2074
    .bdrv_make_empty    = qcow2_make_empty,
2075

    
2076
    .bdrv_co_readv          = qcow2_co_readv,
2077
    .bdrv_co_writev         = qcow2_co_writev,
2078
    .bdrv_co_flush_to_os    = qcow2_co_flush_to_os,
2079

    
2080
    .bdrv_co_write_zeroes   = qcow2_co_write_zeroes,
2081
    .bdrv_co_discard        = qcow2_co_discard,
2082
    .bdrv_truncate          = qcow2_truncate,
2083
    .bdrv_write_compressed  = qcow2_write_compressed,
2084

    
2085
    .bdrv_snapshot_create   = qcow2_snapshot_create,
2086
    .bdrv_snapshot_goto     = qcow2_snapshot_goto,
2087
    .bdrv_snapshot_delete   = qcow2_snapshot_delete,
2088
    .bdrv_snapshot_list     = qcow2_snapshot_list,
2089
    .bdrv_snapshot_load_tmp     = qcow2_snapshot_load_tmp,
2090
    .bdrv_get_info      = qcow2_get_info,
2091

    
2092
    .bdrv_save_vmstate    = qcow2_save_vmstate,
2093
    .bdrv_load_vmstate    = qcow2_load_vmstate,
2094

    
2095
    .bdrv_change_backing_file   = qcow2_change_backing_file,
2096

    
2097
    .bdrv_invalidate_cache      = qcow2_invalidate_cache,
2098

    
2099
    .create_options = qcow2_create_options,
2100
    .bdrv_check = qcow2_check,
2101
    .bdrv_amend_options = qcow2_amend_options,
2102
};
2103

    
2104
static void bdrv_qcow2_init(void)
2105
{
2106
    bdrv_register(&bdrv_qcow2);
2107
}
2108

    
2109
block_init(bdrv_qcow2_init);