]> Git Repo - qemu.git/blob - block/qcow2.c
qcow2: Allow lazy refcounts to be enabled on the command line
[qemu.git] / block / qcow2.c
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 "block/aes.h"
29 #include "block/qcow2.h"
30 #include "qemu/error-report.h"
31 #include "qapi/qmp/qerror.h"
32 #include "trace.h"
33
34 /*
35   Differences with QCOW:
36
37   - Support for multiple incremental snapshots.
38   - Memory management by reference counts.
39   - Clusters which have a reference count of one have the bit
40     QCOW_OFLAG_COPIED to optimize write performance.
41   - Size of compressed clusters is stored in sectors to reduce bit usage
42     in the cluster offsets.
43   - Support for storing additional data (such as the VM state) in the
44     snapshots.
45   - If a backing store is used, the cluster size is not constrained
46     (could be backported to QCOW).
47   - L2 tables have always a size of one cluster.
48 */
49
50
51 typedef struct {
52     uint32_t magic;
53     uint32_t len;
54 } QCowExtension;
55
56 #define  QCOW2_EXT_MAGIC_END 0
57 #define  QCOW2_EXT_MAGIC_BACKING_FORMAT 0xE2792ACA
58 #define  QCOW2_EXT_MAGIC_FEATURE_TABLE 0x6803f857
59
60 static int qcow2_probe(const uint8_t *buf, int buf_size, const char *filename)
61 {
62     const QCowHeader *cow_header = (const void *)buf;
63
64     if (buf_size >= sizeof(QCowHeader) &&
65         be32_to_cpu(cow_header->magic) == QCOW_MAGIC &&
66         be32_to_cpu(cow_header->version) >= 2)
67         return 100;
68     else
69         return 0;
70 }
71
72
73 /* 
74  * read qcow2 extension and fill bs
75  * start reading from start_offset
76  * finish reading upon magic of value 0 or when end_offset reached
77  * unknown magic is skipped (future extension this version knows nothing about)
78  * return 0 upon success, non-0 otherwise
79  */
80 static int qcow2_read_extensions(BlockDriverState *bs, uint64_t start_offset,
81                                  uint64_t end_offset, void **p_feature_table)
82 {
83     BDRVQcowState *s = bs->opaque;
84     QCowExtension ext;
85     uint64_t offset;
86     int ret;
87
88 #ifdef DEBUG_EXT
89     printf("qcow2_read_extensions: start=%ld end=%ld\n", start_offset, end_offset);
90 #endif
91     offset = start_offset;
92     while (offset < end_offset) {
93
94 #ifdef DEBUG_EXT
95         /* Sanity check */
96         if (offset > s->cluster_size)
97             printf("qcow2_read_extension: suspicious offset %lu\n", offset);
98
99         printf("attempting to read extended header in offset %lu\n", offset);
100 #endif
101
102         if (bdrv_pread(bs->file, offset, &ext, sizeof(ext)) != sizeof(ext)) {
103             fprintf(stderr, "qcow2_read_extension: ERROR: "
104                     "pread fail from offset %" PRIu64 "\n",
105                     offset);
106             return 1;
107         }
108         be32_to_cpus(&ext.magic);
109         be32_to_cpus(&ext.len);
110         offset += sizeof(ext);
111 #ifdef DEBUG_EXT
112         printf("ext.magic = 0x%x\n", ext.magic);
113 #endif
114         if (ext.len > end_offset - offset) {
115             error_report("Header extension too large");
116             return -EINVAL;
117         }
118
119         switch (ext.magic) {
120         case QCOW2_EXT_MAGIC_END:
121             return 0;
122
123         case QCOW2_EXT_MAGIC_BACKING_FORMAT:
124             if (ext.len >= sizeof(bs->backing_format)) {
125                 fprintf(stderr, "ERROR: ext_backing_format: len=%u too large"
126                         " (>=%zu)\n",
127                         ext.len, sizeof(bs->backing_format));
128                 return 2;
129             }
130             if (bdrv_pread(bs->file, offset , bs->backing_format,
131                            ext.len) != ext.len)
132                 return 3;
133             bs->backing_format[ext.len] = '\0';
134 #ifdef DEBUG_EXT
135             printf("Qcow2: Got format extension %s\n", bs->backing_format);
136 #endif
137             break;
138
139         case QCOW2_EXT_MAGIC_FEATURE_TABLE:
140             if (p_feature_table != NULL) {
141                 void* feature_table = g_malloc0(ext.len + 2 * sizeof(Qcow2Feature));
142                 ret = bdrv_pread(bs->file, offset , feature_table, ext.len);
143                 if (ret < 0) {
144                     return ret;
145                 }
146
147                 *p_feature_table = feature_table;
148             }
149             break;
150
151         default:
152             /* unknown magic - save it in case we need to rewrite the header */
153             {
154                 Qcow2UnknownHeaderExtension *uext;
155
156                 uext = g_malloc0(sizeof(*uext)  + ext.len);
157                 uext->magic = ext.magic;
158                 uext->len = ext.len;
159                 QLIST_INSERT_HEAD(&s->unknown_header_ext, uext, next);
160
161                 ret = bdrv_pread(bs->file, offset , uext->data, uext->len);
162                 if (ret < 0) {
163                     return ret;
164                 }
165             }
166             break;
167         }
168
169         offset += ((ext.len + 7) & ~7);
170     }
171
172     return 0;
173 }
174
175 static void cleanup_unknown_header_ext(BlockDriverState *bs)
176 {
177     BDRVQcowState *s = bs->opaque;
178     Qcow2UnknownHeaderExtension *uext, *next;
179
180     QLIST_FOREACH_SAFE(uext, &s->unknown_header_ext, next, next) {
181         QLIST_REMOVE(uext, next);
182         g_free(uext);
183     }
184 }
185
186 static void GCC_FMT_ATTR(2, 3) report_unsupported(BlockDriverState *bs,
187     const char *fmt, ...)
188 {
189     char msg[64];
190     va_list ap;
191
192     va_start(ap, fmt);
193     vsnprintf(msg, sizeof(msg), fmt, ap);
194     va_end(ap);
195
196     qerror_report(QERR_UNKNOWN_BLOCK_FORMAT_FEATURE,
197         bs->device_name, "qcow2", msg);
198 }
199
200 static void report_unsupported_feature(BlockDriverState *bs,
201     Qcow2Feature *table, uint64_t mask)
202 {
203     while (table && table->name[0] != '\0') {
204         if (table->type == QCOW2_FEAT_TYPE_INCOMPATIBLE) {
205             if (mask & (1 << table->bit)) {
206                 report_unsupported(bs, "%.46s",table->name);
207                 mask &= ~(1 << table->bit);
208             }
209         }
210         table++;
211     }
212
213     if (mask) {
214         report_unsupported(bs, "Unknown incompatible feature: %" PRIx64, mask);
215     }
216 }
217
218 /*
219  * Sets the dirty bit and flushes afterwards if necessary.
220  *
221  * The incompatible_features bit is only set if the image file header was
222  * updated successfully.  Therefore it is not required to check the return
223  * value of this function.
224  */
225 int qcow2_mark_dirty(BlockDriverState *bs)
226 {
227     BDRVQcowState *s = bs->opaque;
228     uint64_t val;
229     int ret;
230
231     assert(s->qcow_version >= 3);
232
233     if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
234         return 0; /* already dirty */
235     }
236
237     val = cpu_to_be64(s->incompatible_features | QCOW2_INCOMPAT_DIRTY);
238     ret = bdrv_pwrite(bs->file, offsetof(QCowHeader, incompatible_features),
239                       &val, sizeof(val));
240     if (ret < 0) {
241         return ret;
242     }
243     ret = bdrv_flush(bs->file);
244     if (ret < 0) {
245         return ret;
246     }
247
248     /* Only treat image as dirty if the header was updated successfully */
249     s->incompatible_features |= QCOW2_INCOMPAT_DIRTY;
250     return 0;
251 }
252
253 /*
254  * Clears the dirty bit and flushes before if necessary.  Only call this
255  * function when there are no pending requests, it does not guard against
256  * concurrent requests dirtying the image.
257  */
258 static int qcow2_mark_clean(BlockDriverState *bs)
259 {
260     BDRVQcowState *s = bs->opaque;
261
262     if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
263         int ret = bdrv_flush(bs);
264         if (ret < 0) {
265             return ret;
266         }
267
268         s->incompatible_features &= ~QCOW2_INCOMPAT_DIRTY;
269         return qcow2_update_header(bs);
270     }
271     return 0;
272 }
273
274 static int qcow2_check(BlockDriverState *bs, BdrvCheckResult *result,
275                        BdrvCheckMode fix)
276 {
277     int ret = qcow2_check_refcounts(bs, result, fix);
278     if (ret < 0) {
279         return ret;
280     }
281
282     if (fix && result->check_errors == 0 && result->corruptions == 0) {
283         return qcow2_mark_clean(bs);
284     }
285     return ret;
286 }
287
288 static QemuOptsList qcow2_runtime_opts = {
289     .name = "qcow2",
290     .head = QTAILQ_HEAD_INITIALIZER(qcow2_runtime_opts.head),
291     .desc = {
292         {
293             .name = "lazy_refcounts",
294             .type = QEMU_OPT_BOOL,
295             .help = "Postpone refcount updates",
296         },
297         { /* end of list */ }
298     },
299 };
300
301 static int qcow2_open(BlockDriverState *bs, QDict *options, int flags)
302 {
303     BDRVQcowState *s = bs->opaque;
304     int len, i, ret = 0;
305     QCowHeader header;
306     QemuOpts *opts;
307     Error *local_err = NULL;
308     uint64_t ext_end;
309
310     ret = bdrv_pread(bs->file, 0, &header, sizeof(header));
311     if (ret < 0) {
312         goto fail;
313     }
314     be32_to_cpus(&header.magic);
315     be32_to_cpus(&header.version);
316     be64_to_cpus(&header.backing_file_offset);
317     be32_to_cpus(&header.backing_file_size);
318     be64_to_cpus(&header.size);
319     be32_to_cpus(&header.cluster_bits);
320     be32_to_cpus(&header.crypt_method);
321     be64_to_cpus(&header.l1_table_offset);
322     be32_to_cpus(&header.l1_size);
323     be64_to_cpus(&header.refcount_table_offset);
324     be32_to_cpus(&header.refcount_table_clusters);
325     be64_to_cpus(&header.snapshots_offset);
326     be32_to_cpus(&header.nb_snapshots);
327
328     if (header.magic != QCOW_MAGIC) {
329         ret = -EMEDIUMTYPE;
330         goto fail;
331     }
332     if (header.version < 2 || header.version > 3) {
333         report_unsupported(bs, "QCOW version %d", header.version);
334         ret = -ENOTSUP;
335         goto fail;
336     }
337
338     s->qcow_version = header.version;
339
340     /* Initialise version 3 header fields */
341     if (header.version == 2) {
342         header.incompatible_features    = 0;
343         header.compatible_features      = 0;
344         header.autoclear_features       = 0;
345         header.refcount_order           = 4;
346         header.header_length            = 72;
347     } else {
348         be64_to_cpus(&header.incompatible_features);
349         be64_to_cpus(&header.compatible_features);
350         be64_to_cpus(&header.autoclear_features);
351         be32_to_cpus(&header.refcount_order);
352         be32_to_cpus(&header.header_length);
353     }
354
355     if (header.header_length > sizeof(header)) {
356         s->unknown_header_fields_size = header.header_length - sizeof(header);
357         s->unknown_header_fields = g_malloc(s->unknown_header_fields_size);
358         ret = bdrv_pread(bs->file, sizeof(header), s->unknown_header_fields,
359                          s->unknown_header_fields_size);
360         if (ret < 0) {
361             goto fail;
362         }
363     }
364
365     if (header.backing_file_offset) {
366         ext_end = header.backing_file_offset;
367     } else {
368         ext_end = 1 << header.cluster_bits;
369     }
370
371     /* Handle feature bits */
372     s->incompatible_features    = header.incompatible_features;
373     s->compatible_features      = header.compatible_features;
374     s->autoclear_features       = header.autoclear_features;
375
376     if (s->incompatible_features & ~QCOW2_INCOMPAT_MASK) {
377         void *feature_table = NULL;
378         qcow2_read_extensions(bs, header.header_length, ext_end,
379                               &feature_table);
380         report_unsupported_feature(bs, feature_table,
381                                    s->incompatible_features &
382                                    ~QCOW2_INCOMPAT_MASK);
383         ret = -ENOTSUP;
384         goto fail;
385     }
386
387     /* Check support for various header values */
388     if (header.refcount_order != 4) {
389         report_unsupported(bs, "%d bit reference counts",
390                            1 << header.refcount_order);
391         ret = -ENOTSUP;
392         goto fail;
393     }
394
395     if (header.cluster_bits < MIN_CLUSTER_BITS ||
396         header.cluster_bits > MAX_CLUSTER_BITS) {
397         ret = -EINVAL;
398         goto fail;
399     }
400     if (header.crypt_method > QCOW_CRYPT_AES) {
401         ret = -EINVAL;
402         goto fail;
403     }
404     s->crypt_method_header = header.crypt_method;
405     if (s->crypt_method_header) {
406         bs->encrypted = 1;
407     }
408     s->cluster_bits = header.cluster_bits;
409     s->cluster_size = 1 << s->cluster_bits;
410     s->cluster_sectors = 1 << (s->cluster_bits - 9);
411     s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */
412     s->l2_size = 1 << s->l2_bits;
413     bs->total_sectors = header.size / 512;
414     s->csize_shift = (62 - (s->cluster_bits - 8));
415     s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;
416     s->cluster_offset_mask = (1LL << s->csize_shift) - 1;
417     s->refcount_table_offset = header.refcount_table_offset;
418     s->refcount_table_size =
419         header.refcount_table_clusters << (s->cluster_bits - 3);
420
421     s->snapshots_offset = header.snapshots_offset;
422     s->nb_snapshots = header.nb_snapshots;
423
424     /* read the level 1 table */
425     s->l1_size = header.l1_size;
426     s->l1_vm_state_index = size_to_l1(s, header.size);
427     /* the L1 table must contain at least enough entries to put
428        header.size bytes */
429     if (s->l1_size < s->l1_vm_state_index) {
430         ret = -EINVAL;
431         goto fail;
432     }
433     s->l1_table_offset = header.l1_table_offset;
434     if (s->l1_size > 0) {
435         s->l1_table = g_malloc0(
436             align_offset(s->l1_size * sizeof(uint64_t), 512));
437         ret = bdrv_pread(bs->file, s->l1_table_offset, s->l1_table,
438                          s->l1_size * sizeof(uint64_t));
439         if (ret < 0) {
440             goto fail;
441         }
442         for(i = 0;i < s->l1_size; i++) {
443             be64_to_cpus(&s->l1_table[i]);
444         }
445     }
446
447     /* alloc L2 table/refcount block cache */
448     s->l2_table_cache = qcow2_cache_create(bs, L2_CACHE_SIZE);
449     s->refcount_block_cache = qcow2_cache_create(bs, REFCOUNT_CACHE_SIZE);
450
451     s->cluster_cache = g_malloc(s->cluster_size);
452     /* one more sector for decompressed data alignment */
453     s->cluster_data = qemu_blockalign(bs, QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size
454                                   + 512);
455     s->cluster_cache_offset = -1;
456     s->flags = flags;
457
458     ret = qcow2_refcount_init(bs);
459     if (ret != 0) {
460         goto fail;
461     }
462
463     QLIST_INIT(&s->cluster_allocs);
464
465     /* read qcow2 extensions */
466     if (qcow2_read_extensions(bs, header.header_length, ext_end, NULL)) {
467         ret = -EINVAL;
468         goto fail;
469     }
470
471     /* read the backing file name */
472     if (header.backing_file_offset != 0) {
473         len = header.backing_file_size;
474         if (len > 1023) {
475             len = 1023;
476         }
477         ret = bdrv_pread(bs->file, header.backing_file_offset,
478                          bs->backing_file, len);
479         if (ret < 0) {
480             goto fail;
481         }
482         bs->backing_file[len] = '\0';
483     }
484
485     ret = qcow2_read_snapshots(bs);
486     if (ret < 0) {
487         goto fail;
488     }
489
490     /* Clear unknown autoclear feature bits */
491     if (!bs->read_only && s->autoclear_features != 0) {
492         s->autoclear_features = 0;
493         ret = qcow2_update_header(bs);
494         if (ret < 0) {
495             goto fail;
496         }
497     }
498
499     /* Initialise locks */
500     qemu_co_mutex_init(&s->lock);
501
502     /* Repair image if dirty */
503     if (!(flags & BDRV_O_CHECK) && !bs->read_only &&
504         (s->incompatible_features & QCOW2_INCOMPAT_DIRTY)) {
505         BdrvCheckResult result = {0};
506
507         ret = qcow2_check(bs, &result, BDRV_FIX_ERRORS);
508         if (ret < 0) {
509             goto fail;
510         }
511     }
512
513     /* Enable lazy_refcounts according to image and command line options */
514     opts = qemu_opts_create_nofail(&qcow2_runtime_opts);
515     qemu_opts_absorb_qdict(opts, options, &local_err);
516     if (error_is_set(&local_err)) {
517         qerror_report_err(local_err);
518         error_free(local_err);
519         ret = -EINVAL;
520         goto fail;
521     }
522
523     s->use_lazy_refcounts = qemu_opt_get_bool(opts, "lazy_refcounts",
524         (s->compatible_features & QCOW2_COMPAT_LAZY_REFCOUNTS));
525
526     qemu_opts_del(opts);
527
528     if (s->use_lazy_refcounts && s->qcow_version < 3) {
529         qerror_report(ERROR_CLASS_GENERIC_ERROR, "Lazy refcounts require "
530             "a qcow2 image with at least qemu 1.1 compatibility level");
531         ret = -EINVAL;
532         goto fail;
533     }
534
535 #ifdef DEBUG_ALLOC
536     {
537         BdrvCheckResult result = {0};
538         qcow2_check_refcounts(bs, &result, 0);
539     }
540 #endif
541     return ret;
542
543  fail:
544     g_free(s->unknown_header_fields);
545     cleanup_unknown_header_ext(bs);
546     qcow2_free_snapshots(bs);
547     qcow2_refcount_close(bs);
548     g_free(s->l1_table);
549     if (s->l2_table_cache) {
550         qcow2_cache_destroy(bs, s->l2_table_cache);
551     }
552     g_free(s->cluster_cache);
553     qemu_vfree(s->cluster_data);
554     return ret;
555 }
556
557 static int qcow2_set_key(BlockDriverState *bs, const char *key)
558 {
559     BDRVQcowState *s = bs->opaque;
560     uint8_t keybuf[16];
561     int len, i;
562
563     memset(keybuf, 0, 16);
564     len = strlen(key);
565     if (len > 16)
566         len = 16;
567     /* XXX: we could compress the chars to 7 bits to increase
568        entropy */
569     for(i = 0;i < len;i++) {
570         keybuf[i] = key[i];
571     }
572     s->crypt_method = s->crypt_method_header;
573
574     if (AES_set_encrypt_key(keybuf, 128, &s->aes_encrypt_key) != 0)
575         return -1;
576     if (AES_set_decrypt_key(keybuf, 128, &s->aes_decrypt_key) != 0)
577         return -1;
578 #if 0
579     /* test */
580     {
581         uint8_t in[16];
582         uint8_t out[16];
583         uint8_t tmp[16];
584         for(i=0;i<16;i++)
585             in[i] = i;
586         AES_encrypt(in, tmp, &s->aes_encrypt_key);
587         AES_decrypt(tmp, out, &s->aes_decrypt_key);
588         for(i = 0; i < 16; i++)
589             printf(" %02x", tmp[i]);
590         printf("\n");
591         for(i = 0; i < 16; i++)
592             printf(" %02x", out[i]);
593         printf("\n");
594     }
595 #endif
596     return 0;
597 }
598
599 /* We have nothing to do for QCOW2 reopen, stubs just return
600  * success */
601 static int qcow2_reopen_prepare(BDRVReopenState *state,
602                                 BlockReopenQueue *queue, Error **errp)
603 {
604     return 0;
605 }
606
607 static int coroutine_fn qcow2_co_is_allocated(BlockDriverState *bs,
608         int64_t sector_num, int nb_sectors, int *pnum)
609 {
610     BDRVQcowState *s = bs->opaque;
611     uint64_t cluster_offset;
612     int ret;
613
614     *pnum = nb_sectors;
615     /* FIXME We can get errors here, but the bdrv_co_is_allocated interface
616      * can't pass them on today */
617     qemu_co_mutex_lock(&s->lock);
618     ret = qcow2_get_cluster_offset(bs, sector_num << 9, pnum, &cluster_offset);
619     qemu_co_mutex_unlock(&s->lock);
620     if (ret < 0) {
621         *pnum = 0;
622     }
623
624     return (cluster_offset != 0);
625 }
626
627 /* handle reading after the end of the backing file */
628 int qcow2_backing_read1(BlockDriverState *bs, QEMUIOVector *qiov,
629                   int64_t sector_num, int nb_sectors)
630 {
631     int n1;
632     if ((sector_num + nb_sectors) <= bs->total_sectors)
633         return nb_sectors;
634     if (sector_num >= bs->total_sectors)
635         n1 = 0;
636     else
637         n1 = bs->total_sectors - sector_num;
638
639     qemu_iovec_memset(qiov, 512 * n1, 0, 512 * (nb_sectors - n1));
640
641     return n1;
642 }
643
644 static coroutine_fn int qcow2_co_readv(BlockDriverState *bs, int64_t sector_num,
645                           int remaining_sectors, QEMUIOVector *qiov)
646 {
647     BDRVQcowState *s = bs->opaque;
648     int index_in_cluster, n1;
649     int ret;
650     int cur_nr_sectors; /* number of sectors in current iteration */
651     uint64_t cluster_offset = 0;
652     uint64_t bytes_done = 0;
653     QEMUIOVector hd_qiov;
654     uint8_t *cluster_data = NULL;
655
656     qemu_iovec_init(&hd_qiov, qiov->niov);
657
658     qemu_co_mutex_lock(&s->lock);
659
660     while (remaining_sectors != 0) {
661
662         /* prepare next request */
663         cur_nr_sectors = remaining_sectors;
664         if (s->crypt_method) {
665             cur_nr_sectors = MIN(cur_nr_sectors,
666                 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors);
667         }
668
669         ret = qcow2_get_cluster_offset(bs, sector_num << 9,
670             &cur_nr_sectors, &cluster_offset);
671         if (ret < 0) {
672             goto fail;
673         }
674
675         index_in_cluster = sector_num & (s->cluster_sectors - 1);
676
677         qemu_iovec_reset(&hd_qiov);
678         qemu_iovec_concat(&hd_qiov, qiov, bytes_done,
679             cur_nr_sectors * 512);
680
681         switch (ret) {
682         case QCOW2_CLUSTER_UNALLOCATED:
683
684             if (bs->backing_hd) {
685                 /* read from the base image */
686                 n1 = qcow2_backing_read1(bs->backing_hd, &hd_qiov,
687                     sector_num, cur_nr_sectors);
688                 if (n1 > 0) {
689                     BLKDBG_EVENT(bs->file, BLKDBG_READ_BACKING_AIO);
690                     qemu_co_mutex_unlock(&s->lock);
691                     ret = bdrv_co_readv(bs->backing_hd, sector_num,
692                                         n1, &hd_qiov);
693                     qemu_co_mutex_lock(&s->lock);
694                     if (ret < 0) {
695                         goto fail;
696                     }
697                 }
698             } else {
699                 /* Note: in this case, no need to wait */
700                 qemu_iovec_memset(&hd_qiov, 0, 0, 512 * cur_nr_sectors);
701             }
702             break;
703
704         case QCOW2_CLUSTER_ZERO:
705             if (s->qcow_version < 3) {
706                 ret = -EIO;
707                 goto fail;
708             }
709             qemu_iovec_memset(&hd_qiov, 0, 0, 512 * cur_nr_sectors);
710             break;
711
712         case QCOW2_CLUSTER_COMPRESSED:
713             /* add AIO support for compressed blocks ? */
714             ret = qcow2_decompress_cluster(bs, cluster_offset);
715             if (ret < 0) {
716                 goto fail;
717             }
718
719             qemu_iovec_from_buf(&hd_qiov, 0,
720                 s->cluster_cache + index_in_cluster * 512,
721                 512 * cur_nr_sectors);
722             break;
723
724         case QCOW2_CLUSTER_NORMAL:
725             if ((cluster_offset & 511) != 0) {
726                 ret = -EIO;
727                 goto fail;
728             }
729
730             if (s->crypt_method) {
731                 /*
732                  * For encrypted images, read everything into a temporary
733                  * contiguous buffer on which the AES functions can work.
734                  */
735                 if (!cluster_data) {
736                     cluster_data =
737                         qemu_blockalign(bs, QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
738                 }
739
740                 assert(cur_nr_sectors <=
741                     QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors);
742                 qemu_iovec_reset(&hd_qiov);
743                 qemu_iovec_add(&hd_qiov, cluster_data,
744                     512 * cur_nr_sectors);
745             }
746
747             BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);
748             qemu_co_mutex_unlock(&s->lock);
749             ret = bdrv_co_readv(bs->file,
750                                 (cluster_offset >> 9) + index_in_cluster,
751                                 cur_nr_sectors, &hd_qiov);
752             qemu_co_mutex_lock(&s->lock);
753             if (ret < 0) {
754                 goto fail;
755             }
756             if (s->crypt_method) {
757                 qcow2_encrypt_sectors(s, sector_num,  cluster_data,
758                     cluster_data, cur_nr_sectors, 0, &s->aes_decrypt_key);
759                 qemu_iovec_from_buf(qiov, bytes_done,
760                     cluster_data, 512 * cur_nr_sectors);
761             }
762             break;
763
764         default:
765             g_assert_not_reached();
766             ret = -EIO;
767             goto fail;
768         }
769
770         remaining_sectors -= cur_nr_sectors;
771         sector_num += cur_nr_sectors;
772         bytes_done += cur_nr_sectors * 512;
773     }
774     ret = 0;
775
776 fail:
777     qemu_co_mutex_unlock(&s->lock);
778
779     qemu_iovec_destroy(&hd_qiov);
780     qemu_vfree(cluster_data);
781
782     return ret;
783 }
784
785 static coroutine_fn int qcow2_co_writev(BlockDriverState *bs,
786                            int64_t sector_num,
787                            int remaining_sectors,
788                            QEMUIOVector *qiov)
789 {
790     BDRVQcowState *s = bs->opaque;
791     int index_in_cluster;
792     int n_end;
793     int ret;
794     int cur_nr_sectors; /* number of sectors in current iteration */
795     uint64_t cluster_offset;
796     QEMUIOVector hd_qiov;
797     uint64_t bytes_done = 0;
798     uint8_t *cluster_data = NULL;
799     QCowL2Meta *l2meta = NULL;
800
801     trace_qcow2_writev_start_req(qemu_coroutine_self(), sector_num,
802                                  remaining_sectors);
803
804     qemu_iovec_init(&hd_qiov, qiov->niov);
805
806     s->cluster_cache_offset = -1; /* disable compressed cache */
807
808     qemu_co_mutex_lock(&s->lock);
809
810     while (remaining_sectors != 0) {
811
812         l2meta = NULL;
813
814         trace_qcow2_writev_start_part(qemu_coroutine_self());
815         index_in_cluster = sector_num & (s->cluster_sectors - 1);
816         n_end = index_in_cluster + remaining_sectors;
817         if (s->crypt_method &&
818             n_end > QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors) {
819             n_end = QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors;
820         }
821
822         ret = qcow2_alloc_cluster_offset(bs, sector_num << 9,
823             index_in_cluster, n_end, &cur_nr_sectors, &cluster_offset, &l2meta);
824         if (ret < 0) {
825             goto fail;
826         }
827
828         assert((cluster_offset & 511) == 0);
829
830         qemu_iovec_reset(&hd_qiov);
831         qemu_iovec_concat(&hd_qiov, qiov, bytes_done,
832             cur_nr_sectors * 512);
833
834         if (s->crypt_method) {
835             if (!cluster_data) {
836                 cluster_data = qemu_blockalign(bs, QCOW_MAX_CRYPT_CLUSTERS *
837                                                  s->cluster_size);
838             }
839
840             assert(hd_qiov.size <=
841                    QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
842             qemu_iovec_to_buf(&hd_qiov, 0, cluster_data, hd_qiov.size);
843
844             qcow2_encrypt_sectors(s, sector_num, cluster_data,
845                 cluster_data, cur_nr_sectors, 1, &s->aes_encrypt_key);
846
847             qemu_iovec_reset(&hd_qiov);
848             qemu_iovec_add(&hd_qiov, cluster_data,
849                 cur_nr_sectors * 512);
850         }
851
852         qemu_co_mutex_unlock(&s->lock);
853         BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO);
854         trace_qcow2_writev_data(qemu_coroutine_self(),
855                                 (cluster_offset >> 9) + index_in_cluster);
856         ret = bdrv_co_writev(bs->file,
857                              (cluster_offset >> 9) + index_in_cluster,
858                              cur_nr_sectors, &hd_qiov);
859         qemu_co_mutex_lock(&s->lock);
860         if (ret < 0) {
861             goto fail;
862         }
863
864         if (l2meta != NULL) {
865             ret = qcow2_alloc_cluster_link_l2(bs, l2meta);
866             if (ret < 0) {
867                 goto fail;
868             }
869
870             /* Take the request off the list of running requests */
871             if (l2meta->nb_clusters != 0) {
872                 QLIST_REMOVE(l2meta, next_in_flight);
873             }
874
875             qemu_co_mutex_unlock(&s->lock);
876             qemu_co_queue_restart_all(&l2meta->dependent_requests);
877             qemu_co_mutex_lock(&s->lock);
878
879             g_free(l2meta);
880             l2meta = NULL;
881         }
882
883         remaining_sectors -= cur_nr_sectors;
884         sector_num += cur_nr_sectors;
885         bytes_done += cur_nr_sectors * 512;
886         trace_qcow2_writev_done_part(qemu_coroutine_self(), cur_nr_sectors);
887     }
888     ret = 0;
889
890 fail:
891     qemu_co_mutex_unlock(&s->lock);
892
893     if (l2meta != NULL) {
894         if (l2meta->nb_clusters != 0) {
895             QLIST_REMOVE(l2meta, next_in_flight);
896         }
897         qemu_co_queue_restart_all(&l2meta->dependent_requests);
898         g_free(l2meta);
899     }
900
901     qemu_iovec_destroy(&hd_qiov);
902     qemu_vfree(cluster_data);
903     trace_qcow2_writev_done_req(qemu_coroutine_self(), ret);
904
905     return ret;
906 }
907
908 static void qcow2_close(BlockDriverState *bs)
909 {
910     BDRVQcowState *s = bs->opaque;
911     g_free(s->l1_table);
912
913     qcow2_cache_flush(bs, s->l2_table_cache);
914     qcow2_cache_flush(bs, s->refcount_block_cache);
915
916     qcow2_mark_clean(bs);
917
918     qcow2_cache_destroy(bs, s->l2_table_cache);
919     qcow2_cache_destroy(bs, s->refcount_block_cache);
920
921     g_free(s->unknown_header_fields);
922     cleanup_unknown_header_ext(bs);
923
924     g_free(s->cluster_cache);
925     qemu_vfree(s->cluster_data);
926     qcow2_refcount_close(bs);
927     qcow2_free_snapshots(bs);
928 }
929
930 static void qcow2_invalidate_cache(BlockDriverState *bs)
931 {
932     BDRVQcowState *s = bs->opaque;
933     int flags = s->flags;
934     AES_KEY aes_encrypt_key;
935     AES_KEY aes_decrypt_key;
936     uint32_t crypt_method = 0;
937
938     /*
939      * Backing files are read-only which makes all of their metadata immutable,
940      * that means we don't have to worry about reopening them here.
941      */
942
943     if (s->crypt_method) {
944         crypt_method = s->crypt_method;
945         memcpy(&aes_encrypt_key, &s->aes_encrypt_key, sizeof(aes_encrypt_key));
946         memcpy(&aes_decrypt_key, &s->aes_decrypt_key, sizeof(aes_decrypt_key));
947     }
948
949     qcow2_close(bs);
950
951     memset(s, 0, sizeof(BDRVQcowState));
952     qcow2_open(bs, NULL, flags);
953
954     if (crypt_method) {
955         s->crypt_method = crypt_method;
956         memcpy(&s->aes_encrypt_key, &aes_encrypt_key, sizeof(aes_encrypt_key));
957         memcpy(&s->aes_decrypt_key, &aes_decrypt_key, sizeof(aes_decrypt_key));
958     }
959 }
960
961 static size_t header_ext_add(char *buf, uint32_t magic, const void *s,
962     size_t len, size_t buflen)
963 {
964     QCowExtension *ext_backing_fmt = (QCowExtension*) buf;
965     size_t ext_len = sizeof(QCowExtension) + ((len + 7) & ~7);
966
967     if (buflen < ext_len) {
968         return -ENOSPC;
969     }
970
971     *ext_backing_fmt = (QCowExtension) {
972         .magic  = cpu_to_be32(magic),
973         .len    = cpu_to_be32(len),
974     };
975     memcpy(buf + sizeof(QCowExtension), s, len);
976
977     return ext_len;
978 }
979
980 /*
981  * Updates the qcow2 header, including the variable length parts of it, i.e.
982  * the backing file name and all extensions. qcow2 was not designed to allow
983  * such changes, so if we run out of space (we can only use the first cluster)
984  * this function may fail.
985  *
986  * Returns 0 on success, -errno in error cases.
987  */
988 int qcow2_update_header(BlockDriverState *bs)
989 {
990     BDRVQcowState *s = bs->opaque;
991     QCowHeader *header;
992     char *buf;
993     size_t buflen = s->cluster_size;
994     int ret;
995     uint64_t total_size;
996     uint32_t refcount_table_clusters;
997     size_t header_length;
998     Qcow2UnknownHeaderExtension *uext;
999
1000     buf = qemu_blockalign(bs, buflen);
1001
1002     /* Header structure */
1003     header = (QCowHeader*) buf;
1004
1005     if (buflen < sizeof(*header)) {
1006         ret = -ENOSPC;
1007         goto fail;
1008     }
1009
1010     header_length = sizeof(*header) + s->unknown_header_fields_size;
1011     total_size = bs->total_sectors * BDRV_SECTOR_SIZE;
1012     refcount_table_clusters = s->refcount_table_size >> (s->cluster_bits - 3);
1013
1014     *header = (QCowHeader) {
1015         /* Version 2 fields */
1016         .magic                  = cpu_to_be32(QCOW_MAGIC),
1017         .version                = cpu_to_be32(s->qcow_version),
1018         .backing_file_offset    = 0,
1019         .backing_file_size      = 0,
1020         .cluster_bits           = cpu_to_be32(s->cluster_bits),
1021         .size                   = cpu_to_be64(total_size),
1022         .crypt_method           = cpu_to_be32(s->crypt_method_header),
1023         .l1_size                = cpu_to_be32(s->l1_size),
1024         .l1_table_offset        = cpu_to_be64(s->l1_table_offset),
1025         .refcount_table_offset  = cpu_to_be64(s->refcount_table_offset),
1026         .refcount_table_clusters = cpu_to_be32(refcount_table_clusters),
1027         .nb_snapshots           = cpu_to_be32(s->nb_snapshots),
1028         .snapshots_offset       = cpu_to_be64(s->snapshots_offset),
1029
1030         /* Version 3 fields */
1031         .incompatible_features  = cpu_to_be64(s->incompatible_features),
1032         .compatible_features    = cpu_to_be64(s->compatible_features),
1033         .autoclear_features     = cpu_to_be64(s->autoclear_features),
1034         .refcount_order         = cpu_to_be32(3 + REFCOUNT_SHIFT),
1035         .header_length          = cpu_to_be32(header_length),
1036     };
1037
1038     /* For older versions, write a shorter header */
1039     switch (s->qcow_version) {
1040     case 2:
1041         ret = offsetof(QCowHeader, incompatible_features);
1042         break;
1043     case 3:
1044         ret = sizeof(*header);
1045         break;
1046     default:
1047         ret = -EINVAL;
1048         goto fail;
1049     }
1050
1051     buf += ret;
1052     buflen -= ret;
1053     memset(buf, 0, buflen);
1054
1055     /* Preserve any unknown field in the header */
1056     if (s->unknown_header_fields_size) {
1057         if (buflen < s->unknown_header_fields_size) {
1058             ret = -ENOSPC;
1059             goto fail;
1060         }
1061
1062         memcpy(buf, s->unknown_header_fields, s->unknown_header_fields_size);
1063         buf += s->unknown_header_fields_size;
1064         buflen -= s->unknown_header_fields_size;
1065     }
1066
1067     /* Backing file format header extension */
1068     if (*bs->backing_format) {
1069         ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BACKING_FORMAT,
1070                              bs->backing_format, strlen(bs->backing_format),
1071                              buflen);
1072         if (ret < 0) {
1073             goto fail;
1074         }
1075
1076         buf += ret;
1077         buflen -= ret;
1078     }
1079
1080     /* Feature table */
1081     Qcow2Feature features[] = {
1082         {
1083             .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
1084             .bit  = QCOW2_INCOMPAT_DIRTY_BITNR,
1085             .name = "dirty bit",
1086         },
1087         {
1088             .type = QCOW2_FEAT_TYPE_COMPATIBLE,
1089             .bit  = QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR,
1090             .name = "lazy refcounts",
1091         },
1092     };
1093
1094     ret = header_ext_add(buf, QCOW2_EXT_MAGIC_FEATURE_TABLE,
1095                          features, sizeof(features), buflen);
1096     if (ret < 0) {
1097         goto fail;
1098     }
1099     buf += ret;
1100     buflen -= ret;
1101
1102     /* Keep unknown header extensions */
1103     QLIST_FOREACH(uext, &s->unknown_header_ext, next) {
1104         ret = header_ext_add(buf, uext->magic, uext->data, uext->len, buflen);
1105         if (ret < 0) {
1106             goto fail;
1107         }
1108
1109         buf += ret;
1110         buflen -= ret;
1111     }
1112
1113     /* End of header extensions */
1114     ret = header_ext_add(buf, QCOW2_EXT_MAGIC_END, NULL, 0, buflen);
1115     if (ret < 0) {
1116         goto fail;
1117     }
1118
1119     buf += ret;
1120     buflen -= ret;
1121
1122     /* Backing file name */
1123     if (*bs->backing_file) {
1124         size_t backing_file_len = strlen(bs->backing_file);
1125
1126         if (buflen < backing_file_len) {
1127             ret = -ENOSPC;
1128             goto fail;
1129         }
1130
1131         /* Using strncpy is ok here, since buf is not NUL-terminated. */
1132         strncpy(buf, bs->backing_file, buflen);
1133
1134         header->backing_file_offset = cpu_to_be64(buf - ((char*) header));
1135         header->backing_file_size   = cpu_to_be32(backing_file_len);
1136     }
1137
1138     /* Write the new header */
1139     ret = bdrv_pwrite(bs->file, 0, header, s->cluster_size);
1140     if (ret < 0) {
1141         goto fail;
1142     }
1143
1144     ret = 0;
1145 fail:
1146     qemu_vfree(header);
1147     return ret;
1148 }
1149
1150 static int qcow2_change_backing_file(BlockDriverState *bs,
1151     const char *backing_file, const char *backing_fmt)
1152 {
1153     pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
1154     pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
1155
1156     return qcow2_update_header(bs);
1157 }
1158
1159 static int preallocate(BlockDriverState *bs)
1160 {
1161     uint64_t nb_sectors;
1162     uint64_t offset;
1163     uint64_t host_offset = 0;
1164     int num;
1165     int ret;
1166     QCowL2Meta *meta;
1167
1168     nb_sectors = bdrv_getlength(bs) >> 9;
1169     offset = 0;
1170
1171     while (nb_sectors) {
1172         num = MIN(nb_sectors, INT_MAX >> 9);
1173         ret = qcow2_alloc_cluster_offset(bs, offset, 0, num, &num,
1174                                          &host_offset, &meta);
1175         if (ret < 0) {
1176             return ret;
1177         }
1178
1179         ret = qcow2_alloc_cluster_link_l2(bs, meta);
1180         if (ret < 0) {
1181             qcow2_free_any_clusters(bs, meta->alloc_offset, meta->nb_clusters);
1182             return ret;
1183         }
1184
1185         /* There are no dependent requests, but we need to remove our request
1186          * from the list of in-flight requests */
1187         if (meta != NULL) {
1188             QLIST_REMOVE(meta, next_in_flight);
1189         }
1190
1191         /* TODO Preallocate data if requested */
1192
1193         nb_sectors -= num;
1194         offset += num << 9;
1195     }
1196
1197     /*
1198      * It is expected that the image file is large enough to actually contain
1199      * all of the allocated clusters (otherwise we get failing reads after
1200      * EOF). Extend the image to the last allocated sector.
1201      */
1202     if (host_offset != 0) {
1203         uint8_t buf[512];
1204         memset(buf, 0, 512);
1205         ret = bdrv_write(bs->file, (host_offset >> 9) + num - 1, buf, 1);
1206         if (ret < 0) {
1207             return ret;
1208         }
1209     }
1210
1211     return 0;
1212 }
1213
1214 static int qcow2_create2(const char *filename, int64_t total_size,
1215                          const char *backing_file, const char *backing_format,
1216                          int flags, size_t cluster_size, int prealloc,
1217                          QEMUOptionParameter *options, int version)
1218 {
1219     /* Calculate cluster_bits */
1220     int cluster_bits;
1221     cluster_bits = ffs(cluster_size) - 1;
1222     if (cluster_bits < MIN_CLUSTER_BITS || cluster_bits > MAX_CLUSTER_BITS ||
1223         (1 << cluster_bits) != cluster_size)
1224     {
1225         error_report(
1226             "Cluster size must be a power of two between %d and %dk",
1227             1 << MIN_CLUSTER_BITS, 1 << (MAX_CLUSTER_BITS - 10));
1228         return -EINVAL;
1229     }
1230
1231     /*
1232      * Open the image file and write a minimal qcow2 header.
1233      *
1234      * We keep things simple and start with a zero-sized image. We also
1235      * do without refcount blocks or a L1 table for now. We'll fix the
1236      * inconsistency later.
1237      *
1238      * We do need a refcount table because growing the refcount table means
1239      * allocating two new refcount blocks - the seconds of which would be at
1240      * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
1241      * size for any qcow2 image.
1242      */
1243     BlockDriverState* bs;
1244     QCowHeader header;
1245     uint8_t* refcount_table;
1246     int ret;
1247
1248     ret = bdrv_create_file(filename, options);
1249     if (ret < 0) {
1250         return ret;
1251     }
1252
1253     ret = bdrv_file_open(&bs, filename, BDRV_O_RDWR);
1254     if (ret < 0) {
1255         return ret;
1256     }
1257
1258     /* Write the header */
1259     memset(&header, 0, sizeof(header));
1260     header.magic = cpu_to_be32(QCOW_MAGIC);
1261     header.version = cpu_to_be32(version);
1262     header.cluster_bits = cpu_to_be32(cluster_bits);
1263     header.size = cpu_to_be64(0);
1264     header.l1_table_offset = cpu_to_be64(0);
1265     header.l1_size = cpu_to_be32(0);
1266     header.refcount_table_offset = cpu_to_be64(cluster_size);
1267     header.refcount_table_clusters = cpu_to_be32(1);
1268     header.refcount_order = cpu_to_be32(3 + REFCOUNT_SHIFT);
1269     header.header_length = cpu_to_be32(sizeof(header));
1270
1271     if (flags & BLOCK_FLAG_ENCRYPT) {
1272         header.crypt_method = cpu_to_be32(QCOW_CRYPT_AES);
1273     } else {
1274         header.crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
1275     }
1276
1277     if (flags & BLOCK_FLAG_LAZY_REFCOUNTS) {
1278         header.compatible_features |=
1279             cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS);
1280     }
1281
1282     ret = bdrv_pwrite(bs, 0, &header, sizeof(header));
1283     if (ret < 0) {
1284         goto out;
1285     }
1286
1287     /* Write an empty refcount table */
1288     refcount_table = g_malloc0(cluster_size);
1289     ret = bdrv_pwrite(bs, cluster_size, refcount_table, cluster_size);
1290     g_free(refcount_table);
1291
1292     if (ret < 0) {
1293         goto out;
1294     }
1295
1296     bdrv_close(bs);
1297
1298     /*
1299      * And now open the image and make it consistent first (i.e. increase the
1300      * refcount of the cluster that is occupied by the header and the refcount
1301      * table)
1302      */
1303     BlockDriver* drv = bdrv_find_format("qcow2");
1304     assert(drv != NULL);
1305     ret = bdrv_open(bs, filename, NULL,
1306         BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_NO_FLUSH, drv);
1307     if (ret < 0) {
1308         goto out;
1309     }
1310
1311     ret = qcow2_alloc_clusters(bs, 2 * cluster_size);
1312     if (ret < 0) {
1313         goto out;
1314
1315     } else if (ret != 0) {
1316         error_report("Huh, first cluster in empty image is already in use?");
1317         abort();
1318     }
1319
1320     /* Okay, now that we have a valid image, let's give it the right size */
1321     ret = bdrv_truncate(bs, total_size * BDRV_SECTOR_SIZE);
1322     if (ret < 0) {
1323         goto out;
1324     }
1325
1326     /* Want a backing file? There you go.*/
1327     if (backing_file) {
1328         ret = bdrv_change_backing_file(bs, backing_file, backing_format);
1329         if (ret < 0) {
1330             goto out;
1331         }
1332     }
1333
1334     /* And if we're supposed to preallocate metadata, do that now */
1335     if (prealloc) {
1336         BDRVQcowState *s = bs->opaque;
1337         qemu_co_mutex_lock(&s->lock);
1338         ret = preallocate(bs);
1339         qemu_co_mutex_unlock(&s->lock);
1340         if (ret < 0) {
1341             goto out;
1342         }
1343     }
1344
1345     ret = 0;
1346 out:
1347     bdrv_delete(bs);
1348     return ret;
1349 }
1350
1351 static int qcow2_create(const char *filename, QEMUOptionParameter *options)
1352 {
1353     const char *backing_file = NULL;
1354     const char *backing_fmt = NULL;
1355     uint64_t sectors = 0;
1356     int flags = 0;
1357     size_t cluster_size = DEFAULT_CLUSTER_SIZE;
1358     int prealloc = 0;
1359     int version = 2;
1360
1361     /* Read out options */
1362     while (options && options->name) {
1363         if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
1364             sectors = options->value.n / 512;
1365         } else if (!strcmp(options->name, BLOCK_OPT_BACKING_FILE)) {
1366             backing_file = options->value.s;
1367         } else if (!strcmp(options->name, BLOCK_OPT_BACKING_FMT)) {
1368             backing_fmt = options->value.s;
1369         } else if (!strcmp(options->name, BLOCK_OPT_ENCRYPT)) {
1370             flags |= options->value.n ? BLOCK_FLAG_ENCRYPT : 0;
1371         } else if (!strcmp(options->name, BLOCK_OPT_CLUSTER_SIZE)) {
1372             if (options->value.n) {
1373                 cluster_size = options->value.n;
1374             }
1375         } else if (!strcmp(options->name, BLOCK_OPT_PREALLOC)) {
1376             if (!options->value.s || !strcmp(options->value.s, "off")) {
1377                 prealloc = 0;
1378             } else if (!strcmp(options->value.s, "metadata")) {
1379                 prealloc = 1;
1380             } else {
1381                 fprintf(stderr, "Invalid preallocation mode: '%s'\n",
1382                     options->value.s);
1383                 return -EINVAL;
1384             }
1385         } else if (!strcmp(options->name, BLOCK_OPT_COMPAT_LEVEL)) {
1386             if (!options->value.s || !strcmp(options->value.s, "0.10")) {
1387                 version = 2;
1388             } else if (!strcmp(options->value.s, "1.1")) {
1389                 version = 3;
1390             } else {
1391                 fprintf(stderr, "Invalid compatibility level: '%s'\n",
1392                     options->value.s);
1393                 return -EINVAL;
1394             }
1395         } else if (!strcmp(options->name, BLOCK_OPT_LAZY_REFCOUNTS)) {
1396             flags |= options->value.n ? BLOCK_FLAG_LAZY_REFCOUNTS : 0;
1397         }
1398         options++;
1399     }
1400
1401     if (backing_file && prealloc) {
1402         fprintf(stderr, "Backing file and preallocation cannot be used at "
1403             "the same time\n");
1404         return -EINVAL;
1405     }
1406
1407     if (version < 3 && (flags & BLOCK_FLAG_LAZY_REFCOUNTS)) {
1408         fprintf(stderr, "Lazy refcounts only supported with compatibility "
1409                 "level 1.1 and above (use compat=1.1 or greater)\n");
1410         return -EINVAL;
1411     }
1412
1413     return qcow2_create2(filename, sectors, backing_file, backing_fmt, flags,
1414                          cluster_size, prealloc, options, version);
1415 }
1416
1417 static int qcow2_make_empty(BlockDriverState *bs)
1418 {
1419 #if 0
1420     /* XXX: not correct */
1421     BDRVQcowState *s = bs->opaque;
1422     uint32_t l1_length = s->l1_size * sizeof(uint64_t);
1423     int ret;
1424
1425     memset(s->l1_table, 0, l1_length);
1426     if (bdrv_pwrite(bs->file, s->l1_table_offset, s->l1_table, l1_length) < 0)
1427         return -1;
1428     ret = bdrv_truncate(bs->file, s->l1_table_offset + l1_length);
1429     if (ret < 0)
1430         return ret;
1431
1432     l2_cache_reset(bs);
1433 #endif
1434     return 0;
1435 }
1436
1437 static coroutine_fn int qcow2_co_write_zeroes(BlockDriverState *bs,
1438     int64_t sector_num, int nb_sectors)
1439 {
1440     int ret;
1441     BDRVQcowState *s = bs->opaque;
1442
1443     /* Emulate misaligned zero writes */
1444     if (sector_num % s->cluster_sectors || nb_sectors % s->cluster_sectors) {
1445         return -ENOTSUP;
1446     }
1447
1448     /* Whatever is left can use real zero clusters */
1449     qemu_co_mutex_lock(&s->lock);
1450     ret = qcow2_zero_clusters(bs, sector_num << BDRV_SECTOR_BITS,
1451         nb_sectors);
1452     qemu_co_mutex_unlock(&s->lock);
1453
1454     return ret;
1455 }
1456
1457 static coroutine_fn int qcow2_co_discard(BlockDriverState *bs,
1458     int64_t sector_num, int nb_sectors)
1459 {
1460     int ret;
1461     BDRVQcowState *s = bs->opaque;
1462
1463     qemu_co_mutex_lock(&s->lock);
1464     ret = qcow2_discard_clusters(bs, sector_num << BDRV_SECTOR_BITS,
1465         nb_sectors);
1466     qemu_co_mutex_unlock(&s->lock);
1467     return ret;
1468 }
1469
1470 static int qcow2_truncate(BlockDriverState *bs, int64_t offset)
1471 {
1472     BDRVQcowState *s = bs->opaque;
1473     int ret, new_l1_size;
1474
1475     if (offset & 511) {
1476         error_report("The new size must be a multiple of 512");
1477         return -EINVAL;
1478     }
1479
1480     /* cannot proceed if image has snapshots */
1481     if (s->nb_snapshots) {
1482         error_report("Can't resize an image which has snapshots");
1483         return -ENOTSUP;
1484     }
1485
1486     /* shrinking is currently not supported */
1487     if (offset < bs->total_sectors * 512) {
1488         error_report("qcow2 doesn't support shrinking images yet");
1489         return -ENOTSUP;
1490     }
1491
1492     new_l1_size = size_to_l1(s, offset);
1493     ret = qcow2_grow_l1_table(bs, new_l1_size, true);
1494     if (ret < 0) {
1495         return ret;
1496     }
1497
1498     /* write updated header.size */
1499     offset = cpu_to_be64(offset);
1500     ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, size),
1501                            &offset, sizeof(uint64_t));
1502     if (ret < 0) {
1503         return ret;
1504     }
1505
1506     s->l1_vm_state_index = new_l1_size;
1507     return 0;
1508 }
1509
1510 /* XXX: put compressed sectors first, then all the cluster aligned
1511    tables to avoid losing bytes in alignment */
1512 static int qcow2_write_compressed(BlockDriverState *bs, int64_t sector_num,
1513                                   const uint8_t *buf, int nb_sectors)
1514 {
1515     BDRVQcowState *s = bs->opaque;
1516     z_stream strm;
1517     int ret, out_len;
1518     uint8_t *out_buf;
1519     uint64_t cluster_offset;
1520
1521     if (nb_sectors == 0) {
1522         /* align end of file to a sector boundary to ease reading with
1523            sector based I/Os */
1524         cluster_offset = bdrv_getlength(bs->file);
1525         cluster_offset = (cluster_offset + 511) & ~511;
1526         bdrv_truncate(bs->file, cluster_offset);
1527         return 0;
1528     }
1529
1530     if (nb_sectors != s->cluster_sectors)
1531         return -EINVAL;
1532
1533     out_buf = g_malloc(s->cluster_size + (s->cluster_size / 1000) + 128);
1534
1535     /* best compression, small window, no zlib header */
1536     memset(&strm, 0, sizeof(strm));
1537     ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
1538                        Z_DEFLATED, -12,
1539                        9, Z_DEFAULT_STRATEGY);
1540     if (ret != 0) {
1541         ret = -EINVAL;
1542         goto fail;
1543     }
1544
1545     strm.avail_in = s->cluster_size;
1546     strm.next_in = (uint8_t *)buf;
1547     strm.avail_out = s->cluster_size;
1548     strm.next_out = out_buf;
1549
1550     ret = deflate(&strm, Z_FINISH);
1551     if (ret != Z_STREAM_END && ret != Z_OK) {
1552         deflateEnd(&strm);
1553         ret = -EINVAL;
1554         goto fail;
1555     }
1556     out_len = strm.next_out - out_buf;
1557
1558     deflateEnd(&strm);
1559
1560     if (ret != Z_STREAM_END || out_len >= s->cluster_size) {
1561         /* could not compress: write normal cluster */
1562         ret = bdrv_write(bs, sector_num, buf, s->cluster_sectors);
1563         if (ret < 0) {
1564             goto fail;
1565         }
1566     } else {
1567         cluster_offset = qcow2_alloc_compressed_cluster_offset(bs,
1568             sector_num << 9, out_len);
1569         if (!cluster_offset) {
1570             ret = -EIO;
1571             goto fail;
1572         }
1573         cluster_offset &= s->cluster_offset_mask;
1574         BLKDBG_EVENT(bs->file, BLKDBG_WRITE_COMPRESSED);
1575         ret = bdrv_pwrite(bs->file, cluster_offset, out_buf, out_len);
1576         if (ret < 0) {
1577             goto fail;
1578         }
1579     }
1580
1581     ret = 0;
1582 fail:
1583     g_free(out_buf);
1584     return ret;
1585 }
1586
1587 static coroutine_fn int qcow2_co_flush_to_os(BlockDriverState *bs)
1588 {
1589     BDRVQcowState *s = bs->opaque;
1590     int ret;
1591
1592     qemu_co_mutex_lock(&s->lock);
1593     ret = qcow2_cache_flush(bs, s->l2_table_cache);
1594     if (ret < 0) {
1595         qemu_co_mutex_unlock(&s->lock);
1596         return ret;
1597     }
1598
1599     if (qcow2_need_accurate_refcounts(s)) {
1600         ret = qcow2_cache_flush(bs, s->refcount_block_cache);
1601         if (ret < 0) {
1602             qemu_co_mutex_unlock(&s->lock);
1603             return ret;
1604         }
1605     }
1606     qemu_co_mutex_unlock(&s->lock);
1607
1608     return 0;
1609 }
1610
1611 static int64_t qcow2_vm_state_offset(BDRVQcowState *s)
1612 {
1613         return (int64_t)s->l1_vm_state_index << (s->cluster_bits + s->l2_bits);
1614 }
1615
1616 static int qcow2_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1617 {
1618     BDRVQcowState *s = bs->opaque;
1619     bdi->cluster_size = s->cluster_size;
1620     bdi->vm_state_offset = qcow2_vm_state_offset(s);
1621     return 0;
1622 }
1623
1624 #if 0
1625 static void dump_refcounts(BlockDriverState *bs)
1626 {
1627     BDRVQcowState *s = bs->opaque;
1628     int64_t nb_clusters, k, k1, size;
1629     int refcount;
1630
1631     size = bdrv_getlength(bs->file);
1632     nb_clusters = size_to_clusters(s, size);
1633     for(k = 0; k < nb_clusters;) {
1634         k1 = k;
1635         refcount = get_refcount(bs, k);
1636         k++;
1637         while (k < nb_clusters && get_refcount(bs, k) == refcount)
1638             k++;
1639         printf("%" PRId64 ": refcount=%d nb=%" PRId64 "\n", k, refcount,
1640                k - k1);
1641     }
1642 }
1643 #endif
1644
1645 static int qcow2_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
1646                               int64_t pos, int size)
1647 {
1648     BDRVQcowState *s = bs->opaque;
1649     int growable = bs->growable;
1650     int ret;
1651
1652     BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_SAVE);
1653     bs->growable = 1;
1654     ret = bdrv_pwrite(bs, qcow2_vm_state_offset(s) + pos, buf, size);
1655     bs->growable = growable;
1656
1657     return ret;
1658 }
1659
1660 static int qcow2_load_vmstate(BlockDriverState *bs, uint8_t *buf,
1661                               int64_t pos, int size)
1662 {
1663     BDRVQcowState *s = bs->opaque;
1664     int growable = bs->growable;
1665     int ret;
1666
1667     BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_LOAD);
1668     bs->growable = 1;
1669     ret = bdrv_pread(bs, qcow2_vm_state_offset(s) + pos, buf, size);
1670     bs->growable = growable;
1671
1672     return ret;
1673 }
1674
1675 static QEMUOptionParameter qcow2_create_options[] = {
1676     {
1677         .name = BLOCK_OPT_SIZE,
1678         .type = OPT_SIZE,
1679         .help = "Virtual disk size"
1680     },
1681     {
1682         .name = BLOCK_OPT_COMPAT_LEVEL,
1683         .type = OPT_STRING,
1684         .help = "Compatibility level (0.10 or 1.1)"
1685     },
1686     {
1687         .name = BLOCK_OPT_BACKING_FILE,
1688         .type = OPT_STRING,
1689         .help = "File name of a base image"
1690     },
1691     {
1692         .name = BLOCK_OPT_BACKING_FMT,
1693         .type = OPT_STRING,
1694         .help = "Image format of the base image"
1695     },
1696     {
1697         .name = BLOCK_OPT_ENCRYPT,
1698         .type = OPT_FLAG,
1699         .help = "Encrypt the image"
1700     },
1701     {
1702         .name = BLOCK_OPT_CLUSTER_SIZE,
1703         .type = OPT_SIZE,
1704         .help = "qcow2 cluster size",
1705         .value = { .n = DEFAULT_CLUSTER_SIZE },
1706     },
1707     {
1708         .name = BLOCK_OPT_PREALLOC,
1709         .type = OPT_STRING,
1710         .help = "Preallocation mode (allowed values: off, metadata)"
1711     },
1712     {
1713         .name = BLOCK_OPT_LAZY_REFCOUNTS,
1714         .type = OPT_FLAG,
1715         .help = "Postpone refcount updates",
1716     },
1717     { NULL }
1718 };
1719
1720 static BlockDriver bdrv_qcow2 = {
1721     .format_name        = "qcow2",
1722     .instance_size      = sizeof(BDRVQcowState),
1723     .bdrv_probe         = qcow2_probe,
1724     .bdrv_open          = qcow2_open,
1725     .bdrv_close         = qcow2_close,
1726     .bdrv_reopen_prepare  = qcow2_reopen_prepare,
1727     .bdrv_create        = qcow2_create,
1728     .bdrv_co_is_allocated = qcow2_co_is_allocated,
1729     .bdrv_set_key       = qcow2_set_key,
1730     .bdrv_make_empty    = qcow2_make_empty,
1731
1732     .bdrv_co_readv          = qcow2_co_readv,
1733     .bdrv_co_writev         = qcow2_co_writev,
1734     .bdrv_co_flush_to_os    = qcow2_co_flush_to_os,
1735
1736     .bdrv_co_write_zeroes   = qcow2_co_write_zeroes,
1737     .bdrv_co_discard        = qcow2_co_discard,
1738     .bdrv_truncate          = qcow2_truncate,
1739     .bdrv_write_compressed  = qcow2_write_compressed,
1740
1741     .bdrv_snapshot_create   = qcow2_snapshot_create,
1742     .bdrv_snapshot_goto     = qcow2_snapshot_goto,
1743     .bdrv_snapshot_delete   = qcow2_snapshot_delete,
1744     .bdrv_snapshot_list     = qcow2_snapshot_list,
1745     .bdrv_snapshot_load_tmp     = qcow2_snapshot_load_tmp,
1746     .bdrv_get_info      = qcow2_get_info,
1747
1748     .bdrv_save_vmstate    = qcow2_save_vmstate,
1749     .bdrv_load_vmstate    = qcow2_load_vmstate,
1750
1751     .bdrv_change_backing_file   = qcow2_change_backing_file,
1752
1753     .bdrv_invalidate_cache      = qcow2_invalidate_cache,
1754
1755     .create_options = qcow2_create_options,
1756     .bdrv_check = qcow2_check,
1757 };
1758
1759 static void bdrv_qcow2_init(void)
1760 {
1761     bdrv_register(&bdrv_qcow2);
1762 }
1763
1764 block_init(bdrv_qcow2_init);
This page took 0.118825 seconds and 4 git commands to generate.