xref: /qemu/block/qcow2.c (revision af7b708db2d03eb47f7ba44a050439ad9ee65e7a)
1585f8587Sbellard /*
2585f8587Sbellard  * Block driver for the QCOW version 2 format
3585f8587Sbellard  *
4585f8587Sbellard  * Copyright (c) 2004-2006 Fabrice Bellard
5585f8587Sbellard  *
6585f8587Sbellard  * Permission is hereby granted, free of charge, to any person obtaining a copy
7585f8587Sbellard  * of this software and associated documentation files (the "Software"), to deal
8585f8587Sbellard  * in the Software without restriction, including without limitation the rights
9585f8587Sbellard  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10585f8587Sbellard  * copies of the Software, and to permit persons to whom the Software is
11585f8587Sbellard  * furnished to do so, subject to the following conditions:
12585f8587Sbellard  *
13585f8587Sbellard  * The above copyright notice and this permission notice shall be included in
14585f8587Sbellard  * all copies or substantial portions of the Software.
15585f8587Sbellard  *
16585f8587Sbellard  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17585f8587Sbellard  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18585f8587Sbellard  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19585f8587Sbellard  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20585f8587Sbellard  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21585f8587Sbellard  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22585f8587Sbellard  * THE SOFTWARE.
23585f8587Sbellard  */
24faf07963Spbrook #include "qemu-common.h"
25585f8587Sbellard #include "block_int.h"
265efa9d5aSAnthony Liguori #include "module.h"
27585f8587Sbellard #include <zlib.h>
28585f8587Sbellard #include "aes.h"
29f7d0fe02SKevin Wolf #include "block/qcow2.h"
30a9420734SKevin Wolf #include "qemu-error.h"
31e8cdcec1SKevin Wolf #include "qerror.h"
323cce16f4SKevin Wolf #include "trace.h"
33585f8587Sbellard 
34585f8587Sbellard /*
35585f8587Sbellard   Differences with QCOW:
36585f8587Sbellard 
37585f8587Sbellard   - Support for multiple incremental snapshots.
38585f8587Sbellard   - Memory management by reference counts.
39585f8587Sbellard   - Clusters which have a reference count of one have the bit
40585f8587Sbellard     QCOW_OFLAG_COPIED to optimize write performance.
41585f8587Sbellard   - Size of compressed clusters is stored in sectors to reduce bit usage
42585f8587Sbellard     in the cluster offsets.
43585f8587Sbellard   - Support for storing additional data (such as the VM state) in the
44585f8587Sbellard     snapshots.
45585f8587Sbellard   - If a backing store is used, the cluster size is not constrained
46585f8587Sbellard     (could be backported to QCOW).
47585f8587Sbellard   - L2 tables have always a size of one cluster.
48585f8587Sbellard */
49585f8587Sbellard 
509b80ddf3Saliguori 
519b80ddf3Saliguori typedef struct {
529b80ddf3Saliguori     uint32_t magic;
539b80ddf3Saliguori     uint32_t len;
549b80ddf3Saliguori } QCowExtension;
557c80ab3fSJes Sorensen #define  QCOW2_EXT_MAGIC_END 0
567c80ab3fSJes Sorensen #define  QCOW2_EXT_MAGIC_BACKING_FORMAT 0xE2792ACA
57cfcc4c62SKevin Wolf #define  QCOW2_EXT_MAGIC_FEATURE_TABLE 0x6803f857
589b80ddf3Saliguori 
597c80ab3fSJes Sorensen static int qcow2_probe(const uint8_t *buf, int buf_size, const char *filename)
60585f8587Sbellard {
61585f8587Sbellard     const QCowHeader *cow_header = (const void *)buf;
62585f8587Sbellard 
63585f8587Sbellard     if (buf_size >= sizeof(QCowHeader) &&
64585f8587Sbellard         be32_to_cpu(cow_header->magic) == QCOW_MAGIC &&
656744cbabSKevin Wolf         be32_to_cpu(cow_header->version) >= 2)
66585f8587Sbellard         return 100;
67585f8587Sbellard     else
68585f8587Sbellard         return 0;
69585f8587Sbellard }
70585f8587Sbellard 
719b80ddf3Saliguori 
729b80ddf3Saliguori /*
739b80ddf3Saliguori  * read qcow2 extension and fill bs
749b80ddf3Saliguori  * start reading from start_offset
759b80ddf3Saliguori  * finish reading upon magic of value 0 or when end_offset reached
769b80ddf3Saliguori  * unknown magic is skipped (future extension this version knows nothing about)
779b80ddf3Saliguori  * return 0 upon success, non-0 otherwise
789b80ddf3Saliguori  */
797c80ab3fSJes Sorensen static int qcow2_read_extensions(BlockDriverState *bs, uint64_t start_offset,
80cfcc4c62SKevin Wolf                                  uint64_t end_offset, void **p_feature_table)
819b80ddf3Saliguori {
8275bab85cSKevin Wolf     BDRVQcowState *s = bs->opaque;
839b80ddf3Saliguori     QCowExtension ext;
849b80ddf3Saliguori     uint64_t offset;
8575bab85cSKevin Wolf     int ret;
869b80ddf3Saliguori 
879b80ddf3Saliguori #ifdef DEBUG_EXT
887c80ab3fSJes Sorensen     printf("qcow2_read_extensions: start=%ld end=%ld\n", start_offset, end_offset);
899b80ddf3Saliguori #endif
909b80ddf3Saliguori     offset = start_offset;
919b80ddf3Saliguori     while (offset < end_offset) {
929b80ddf3Saliguori 
939b80ddf3Saliguori #ifdef DEBUG_EXT
949b80ddf3Saliguori         /* Sanity check */
959b80ddf3Saliguori         if (offset > s->cluster_size)
967c80ab3fSJes Sorensen             printf("qcow2_read_extension: suspicious offset %lu\n", offset);
979b80ddf3Saliguori 
989b2260cbSDong Xu Wang         printf("attempting to read extended header in offset %lu\n", offset);
999b80ddf3Saliguori #endif
1009b80ddf3Saliguori 
10166f82ceeSKevin Wolf         if (bdrv_pread(bs->file, offset, &ext, sizeof(ext)) != sizeof(ext)) {
1027c80ab3fSJes Sorensen             fprintf(stderr, "qcow2_read_extension: ERROR: "
1030bfcd599SBlue Swirl                     "pread fail from offset %" PRIu64 "\n",
1040bfcd599SBlue Swirl                     offset);
1059b80ddf3Saliguori             return 1;
1069b80ddf3Saliguori         }
1079b80ddf3Saliguori         be32_to_cpus(&ext.magic);
1089b80ddf3Saliguori         be32_to_cpus(&ext.len);
1099b80ddf3Saliguori         offset += sizeof(ext);
1109b80ddf3Saliguori #ifdef DEBUG_EXT
1119b80ddf3Saliguori         printf("ext.magic = 0x%x\n", ext.magic);
1129b80ddf3Saliguori #endif
11364ca6aeeSKevin Wolf         if (ext.len > end_offset - offset) {
11464ca6aeeSKevin Wolf             error_report("Header extension too large");
11564ca6aeeSKevin Wolf             return -EINVAL;
11664ca6aeeSKevin Wolf         }
11764ca6aeeSKevin Wolf 
1189b80ddf3Saliguori         switch (ext.magic) {
1197c80ab3fSJes Sorensen         case QCOW2_EXT_MAGIC_END:
1209b80ddf3Saliguori             return 0;
121f965509cSaliguori 
1227c80ab3fSJes Sorensen         case QCOW2_EXT_MAGIC_BACKING_FORMAT:
123f965509cSaliguori             if (ext.len >= sizeof(bs->backing_format)) {
124f965509cSaliguori                 fprintf(stderr, "ERROR: ext_backing_format: len=%u too large"
1254c978075Saliguori                         " (>=%zu)\n",
126f965509cSaliguori                         ext.len, sizeof(bs->backing_format));
127f965509cSaliguori                 return 2;
128f965509cSaliguori             }
12966f82ceeSKevin Wolf             if (bdrv_pread(bs->file, offset , bs->backing_format,
130f965509cSaliguori                            ext.len) != ext.len)
131f965509cSaliguori                 return 3;
132f965509cSaliguori             bs->backing_format[ext.len] = '\0';
133f965509cSaliguori #ifdef DEBUG_EXT
134f965509cSaliguori             printf("Qcow2: Got format extension %s\n", bs->backing_format);
135f965509cSaliguori #endif
136f965509cSaliguori             break;
137f965509cSaliguori 
138cfcc4c62SKevin Wolf         case QCOW2_EXT_MAGIC_FEATURE_TABLE:
139cfcc4c62SKevin Wolf             if (p_feature_table != NULL) {
140cfcc4c62SKevin Wolf                 void* feature_table = g_malloc0(ext.len + 2 * sizeof(Qcow2Feature));
141cfcc4c62SKevin Wolf                 ret = bdrv_pread(bs->file, offset , feature_table, ext.len);
142cfcc4c62SKevin Wolf                 if (ret < 0) {
143cfcc4c62SKevin Wolf                     return ret;
144cfcc4c62SKevin Wolf                 }
145cfcc4c62SKevin Wolf 
146cfcc4c62SKevin Wolf                 *p_feature_table = feature_table;
147cfcc4c62SKevin Wolf             }
148cfcc4c62SKevin Wolf             break;
149cfcc4c62SKevin Wolf 
1509b80ddf3Saliguori         default:
15175bab85cSKevin Wolf             /* unknown magic - save it in case we need to rewrite the header */
15275bab85cSKevin Wolf             {
15375bab85cSKevin Wolf                 Qcow2UnknownHeaderExtension *uext;
15475bab85cSKevin Wolf 
15575bab85cSKevin Wolf                 uext = g_malloc0(sizeof(*uext)  + ext.len);
15675bab85cSKevin Wolf                 uext->magic = ext.magic;
15775bab85cSKevin Wolf                 uext->len = ext.len;
15875bab85cSKevin Wolf                 QLIST_INSERT_HEAD(&s->unknown_header_ext, uext, next);
15975bab85cSKevin Wolf 
16075bab85cSKevin Wolf                 ret = bdrv_pread(bs->file, offset , uext->data, uext->len);
16175bab85cSKevin Wolf                 if (ret < 0) {
16275bab85cSKevin Wolf                     return ret;
16375bab85cSKevin Wolf                 }
16475bab85cSKevin Wolf             }
1659b80ddf3Saliguori             break;
1669b80ddf3Saliguori         }
167fd29b4bbSKevin Wolf 
168fd29b4bbSKevin Wolf         offset += ((ext.len + 7) & ~7);
1699b80ddf3Saliguori     }
1709b80ddf3Saliguori 
1719b80ddf3Saliguori     return 0;
1729b80ddf3Saliguori }
1739b80ddf3Saliguori 
17475bab85cSKevin Wolf static void cleanup_unknown_header_ext(BlockDriverState *bs)
17575bab85cSKevin Wolf {
17675bab85cSKevin Wolf     BDRVQcowState *s = bs->opaque;
17775bab85cSKevin Wolf     Qcow2UnknownHeaderExtension *uext, *next;
17875bab85cSKevin Wolf 
17975bab85cSKevin Wolf     QLIST_FOREACH_SAFE(uext, &s->unknown_header_ext, next, next) {
18075bab85cSKevin Wolf         QLIST_REMOVE(uext, next);
18175bab85cSKevin Wolf         g_free(uext);
18275bab85cSKevin Wolf     }
18375bab85cSKevin Wolf }
1849b80ddf3Saliguori 
185b9531b6eSStefan Weil static void GCC_FMT_ATTR(2, 3) report_unsupported(BlockDriverState *bs,
186b9531b6eSStefan Weil     const char *fmt, ...)
1876744cbabSKevin Wolf {
1886744cbabSKevin Wolf     char msg[64];
1896744cbabSKevin Wolf     va_list ap;
1906744cbabSKevin Wolf 
1916744cbabSKevin Wolf     va_start(ap, fmt);
1926744cbabSKevin Wolf     vsnprintf(msg, sizeof(msg), fmt, ap);
1936744cbabSKevin Wolf     va_end(ap);
1946744cbabSKevin Wolf 
1956744cbabSKevin Wolf     qerror_report(QERR_UNKNOWN_BLOCK_FORMAT_FEATURE,
1966744cbabSKevin Wolf         bs->device_name, "qcow2", msg);
1976744cbabSKevin Wolf }
1986744cbabSKevin Wolf 
199cfcc4c62SKevin Wolf static void report_unsupported_feature(BlockDriverState *bs,
200cfcc4c62SKevin Wolf     Qcow2Feature *table, uint64_t mask)
201cfcc4c62SKevin Wolf {
202cfcc4c62SKevin Wolf     while (table && table->name[0] != '\0') {
203cfcc4c62SKevin Wolf         if (table->type == QCOW2_FEAT_TYPE_INCOMPATIBLE) {
204cfcc4c62SKevin Wolf             if (mask & (1 << table->bit)) {
205cfcc4c62SKevin Wolf                 report_unsupported(bs, "%.46s",table->name);
206cfcc4c62SKevin Wolf                 mask &= ~(1 << table->bit);
207cfcc4c62SKevin Wolf             }
208cfcc4c62SKevin Wolf         }
209cfcc4c62SKevin Wolf         table++;
210cfcc4c62SKevin Wolf     }
211cfcc4c62SKevin Wolf 
212cfcc4c62SKevin Wolf     if (mask) {
213cfcc4c62SKevin Wolf         report_unsupported(bs, "Unknown incompatible feature: %" PRIx64, mask);
214cfcc4c62SKevin Wolf     }
215cfcc4c62SKevin Wolf }
216cfcc4c62SKevin Wolf 
2177c80ab3fSJes Sorensen static int qcow2_open(BlockDriverState *bs, int flags)
218585f8587Sbellard {
219585f8587Sbellard     BDRVQcowState *s = bs->opaque;
2206d85a57eSJes Sorensen     int len, i, ret = 0;
221585f8587Sbellard     QCowHeader header;
2229b80ddf3Saliguori     uint64_t ext_end;
223585f8587Sbellard 
2246d85a57eSJes Sorensen     ret = bdrv_pread(bs->file, 0, &header, sizeof(header));
2256d85a57eSJes Sorensen     if (ret < 0) {
226585f8587Sbellard         goto fail;
2276d85a57eSJes Sorensen     }
228585f8587Sbellard     be32_to_cpus(&header.magic);
229585f8587Sbellard     be32_to_cpus(&header.version);
230585f8587Sbellard     be64_to_cpus(&header.backing_file_offset);
231585f8587Sbellard     be32_to_cpus(&header.backing_file_size);
232585f8587Sbellard     be64_to_cpus(&header.size);
233585f8587Sbellard     be32_to_cpus(&header.cluster_bits);
234585f8587Sbellard     be32_to_cpus(&header.crypt_method);
235585f8587Sbellard     be64_to_cpus(&header.l1_table_offset);
236585f8587Sbellard     be32_to_cpus(&header.l1_size);
237585f8587Sbellard     be64_to_cpus(&header.refcount_table_offset);
238585f8587Sbellard     be32_to_cpus(&header.refcount_table_clusters);
239585f8587Sbellard     be64_to_cpus(&header.snapshots_offset);
240585f8587Sbellard     be32_to_cpus(&header.nb_snapshots);
241585f8587Sbellard 
242e8cdcec1SKevin Wolf     if (header.magic != QCOW_MAGIC) {
2436d85a57eSJes Sorensen         ret = -EINVAL;
244585f8587Sbellard         goto fail;
2456d85a57eSJes Sorensen     }
2466744cbabSKevin Wolf     if (header.version < 2 || header.version > 3) {
2476744cbabSKevin Wolf         report_unsupported(bs, "QCOW version %d", header.version);
248e8cdcec1SKevin Wolf         ret = -ENOTSUP;
249e8cdcec1SKevin Wolf         goto fail;
250e8cdcec1SKevin Wolf     }
2516744cbabSKevin Wolf 
2526744cbabSKevin Wolf     s->qcow_version = header.version;
2536744cbabSKevin Wolf 
2546744cbabSKevin Wolf     /* Initialise version 3 header fields */
2556744cbabSKevin Wolf     if (header.version == 2) {
2566744cbabSKevin Wolf         header.incompatible_features    = 0;
2576744cbabSKevin Wolf         header.compatible_features      = 0;
2586744cbabSKevin Wolf         header.autoclear_features       = 0;
2596744cbabSKevin Wolf         header.refcount_order           = 4;
2606744cbabSKevin Wolf         header.header_length            = 72;
2616744cbabSKevin Wolf     } else {
2626744cbabSKevin Wolf         be64_to_cpus(&header.incompatible_features);
2636744cbabSKevin Wolf         be64_to_cpus(&header.compatible_features);
2646744cbabSKevin Wolf         be64_to_cpus(&header.autoclear_features);
2656744cbabSKevin Wolf         be32_to_cpus(&header.refcount_order);
2666744cbabSKevin Wolf         be32_to_cpus(&header.header_length);
2676744cbabSKevin Wolf     }
2686744cbabSKevin Wolf 
2696744cbabSKevin Wolf     if (header.header_length > sizeof(header)) {
2706744cbabSKevin Wolf         s->unknown_header_fields_size = header.header_length - sizeof(header);
2716744cbabSKevin Wolf         s->unknown_header_fields = g_malloc(s->unknown_header_fields_size);
2726744cbabSKevin Wolf         ret = bdrv_pread(bs->file, sizeof(header), s->unknown_header_fields,
2736744cbabSKevin Wolf                          s->unknown_header_fields_size);
2746744cbabSKevin Wolf         if (ret < 0) {
2756744cbabSKevin Wolf             goto fail;
2766744cbabSKevin Wolf         }
2776744cbabSKevin Wolf     }
2786744cbabSKevin Wolf 
279cfcc4c62SKevin Wolf     if (header.backing_file_offset) {
280cfcc4c62SKevin Wolf         ext_end = header.backing_file_offset;
281cfcc4c62SKevin Wolf     } else {
282cfcc4c62SKevin Wolf         ext_end = 1 << header.cluster_bits;
283cfcc4c62SKevin Wolf     }
284cfcc4c62SKevin Wolf 
2856744cbabSKevin Wolf     /* Handle feature bits */
2866744cbabSKevin Wolf     s->incompatible_features    = header.incompatible_features;
2876744cbabSKevin Wolf     s->compatible_features      = header.compatible_features;
2886744cbabSKevin Wolf     s->autoclear_features       = header.autoclear_features;
2896744cbabSKevin Wolf 
2906744cbabSKevin Wolf     if (s->incompatible_features != 0) {
291cfcc4c62SKevin Wolf         void *feature_table = NULL;
292cfcc4c62SKevin Wolf         qcow2_read_extensions(bs, header.header_length, ext_end,
293cfcc4c62SKevin Wolf                               &feature_table);
294cfcc4c62SKevin Wolf         report_unsupported_feature(bs, feature_table,
295cfcc4c62SKevin Wolf                                    s->incompatible_features);
2966744cbabSKevin Wolf         ret = -ENOTSUP;
2976744cbabSKevin Wolf         goto fail;
2986744cbabSKevin Wolf     }
2996744cbabSKevin Wolf 
3006744cbabSKevin Wolf     /* Check support for various header values */
3016744cbabSKevin Wolf     if (header.refcount_order != 4) {
3026744cbabSKevin Wolf         report_unsupported(bs, "%d bit reference counts",
3036744cbabSKevin Wolf                            1 << header.refcount_order);
3046744cbabSKevin Wolf         ret = -ENOTSUP;
3056744cbabSKevin Wolf         goto fail;
3066744cbabSKevin Wolf     }
3076744cbabSKevin Wolf 
308d191d12dSStefan Weil     if (header.cluster_bits < MIN_CLUSTER_BITS ||
3096d85a57eSJes Sorensen         header.cluster_bits > MAX_CLUSTER_BITS) {
3106d85a57eSJes Sorensen         ret = -EINVAL;
311585f8587Sbellard         goto fail;
3126d85a57eSJes Sorensen     }
3136d85a57eSJes Sorensen     if (header.crypt_method > QCOW_CRYPT_AES) {
3146d85a57eSJes Sorensen         ret = -EINVAL;
315585f8587Sbellard         goto fail;
3166d85a57eSJes Sorensen     }
317585f8587Sbellard     s->crypt_method_header = header.crypt_method;
3186d85a57eSJes Sorensen     if (s->crypt_method_header) {
319585f8587Sbellard         bs->encrypted = 1;
3206d85a57eSJes Sorensen     }
321585f8587Sbellard     s->cluster_bits = header.cluster_bits;
322585f8587Sbellard     s->cluster_size = 1 << s->cluster_bits;
323585f8587Sbellard     s->cluster_sectors = 1 << (s->cluster_bits - 9);
324585f8587Sbellard     s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */
325585f8587Sbellard     s->l2_size = 1 << s->l2_bits;
326585f8587Sbellard     bs->total_sectors = header.size / 512;
327585f8587Sbellard     s->csize_shift = (62 - (s->cluster_bits - 8));
328585f8587Sbellard     s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;
329585f8587Sbellard     s->cluster_offset_mask = (1LL << s->csize_shift) - 1;
330585f8587Sbellard     s->refcount_table_offset = header.refcount_table_offset;
331585f8587Sbellard     s->refcount_table_size =
332585f8587Sbellard         header.refcount_table_clusters << (s->cluster_bits - 3);
333585f8587Sbellard 
334585f8587Sbellard     s->snapshots_offset = header.snapshots_offset;
335585f8587Sbellard     s->nb_snapshots = header.nb_snapshots;
336585f8587Sbellard 
337585f8587Sbellard     /* read the level 1 table */
338585f8587Sbellard     s->l1_size = header.l1_size;
339419b19d9SStefan Hajnoczi     s->l1_vm_state_index = size_to_l1(s, header.size);
340585f8587Sbellard     /* the L1 table must contain at least enough entries to put
341585f8587Sbellard        header.size bytes */
3426d85a57eSJes Sorensen     if (s->l1_size < s->l1_vm_state_index) {
3436d85a57eSJes Sorensen         ret = -EINVAL;
344585f8587Sbellard         goto fail;
3456d85a57eSJes Sorensen     }
346585f8587Sbellard     s->l1_table_offset = header.l1_table_offset;
347d191d12dSStefan Weil     if (s->l1_size > 0) {
3487267c094SAnthony Liguori         s->l1_table = g_malloc0(
3493f6a3ee5SKevin Wolf             align_offset(s->l1_size * sizeof(uint64_t), 512));
3506d85a57eSJes Sorensen         ret = bdrv_pread(bs->file, s->l1_table_offset, s->l1_table,
3516d85a57eSJes Sorensen                          s->l1_size * sizeof(uint64_t));
3526d85a57eSJes Sorensen         if (ret < 0) {
353585f8587Sbellard             goto fail;
3546d85a57eSJes Sorensen         }
355585f8587Sbellard         for(i = 0;i < s->l1_size; i++) {
356585f8587Sbellard             be64_to_cpus(&s->l1_table[i]);
357585f8587Sbellard         }
358d191d12dSStefan Weil     }
35929c1a730SKevin Wolf 
36029c1a730SKevin Wolf     /* alloc L2 table/refcount block cache */
3616af4e9eaSPaolo Bonzini     s->l2_table_cache = qcow2_cache_create(bs, L2_CACHE_SIZE);
3626af4e9eaSPaolo Bonzini     s->refcount_block_cache = qcow2_cache_create(bs, REFCOUNT_CACHE_SIZE);
36329c1a730SKevin Wolf 
3647267c094SAnthony Liguori     s->cluster_cache = g_malloc(s->cluster_size);
365585f8587Sbellard     /* one more sector for decompressed data alignment */
366dea43a65SFrediano Ziglio     s->cluster_data = qemu_blockalign(bs, QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size
367095a9c58Saliguori                                   + 512);
368585f8587Sbellard     s->cluster_cache_offset = -1;
36906d9260fSAnthony Liguori     s->flags = flags;
370585f8587Sbellard 
3716d85a57eSJes Sorensen     ret = qcow2_refcount_init(bs);
3726d85a57eSJes Sorensen     if (ret != 0) {
373585f8587Sbellard         goto fail;
3746d85a57eSJes Sorensen     }
375585f8587Sbellard 
37672cf2d4fSBlue Swirl     QLIST_INIT(&s->cluster_allocs);
377f214978aSKevin Wolf 
3789b80ddf3Saliguori     /* read qcow2 extensions */
379cfcc4c62SKevin Wolf     if (qcow2_read_extensions(bs, header.header_length, ext_end, NULL)) {
3806d85a57eSJes Sorensen         ret = -EINVAL;
3819b80ddf3Saliguori         goto fail;
3826d85a57eSJes Sorensen     }
3839b80ddf3Saliguori 
384585f8587Sbellard     /* read the backing file name */
385585f8587Sbellard     if (header.backing_file_offset != 0) {
386585f8587Sbellard         len = header.backing_file_size;
3876d85a57eSJes Sorensen         if (len > 1023) {
388585f8587Sbellard             len = 1023;
3896d85a57eSJes Sorensen         }
3906d85a57eSJes Sorensen         ret = bdrv_pread(bs->file, header.backing_file_offset,
3916d85a57eSJes Sorensen                          bs->backing_file, len);
3926d85a57eSJes Sorensen         if (ret < 0) {
393585f8587Sbellard             goto fail;
3946d85a57eSJes Sorensen         }
395585f8587Sbellard         bs->backing_file[len] = '\0';
396585f8587Sbellard     }
39742deb29fSKevin Wolf 
39842deb29fSKevin Wolf     ret = qcow2_read_snapshots(bs);
39942deb29fSKevin Wolf     if (ret < 0) {
400585f8587Sbellard         goto fail;
4016d85a57eSJes Sorensen     }
402585f8587Sbellard 
403*af7b708dSStefan Hajnoczi     /* Clear unknown autoclear feature bits */
404*af7b708dSStefan Hajnoczi     if (!bs->read_only && s->autoclear_features != 0) {
405*af7b708dSStefan Hajnoczi         s->autoclear_features = 0;
406*af7b708dSStefan Hajnoczi         ret = qcow2_update_header(bs);
407*af7b708dSStefan Hajnoczi         if (ret < 0) {
408*af7b708dSStefan Hajnoczi             goto fail;
409*af7b708dSStefan Hajnoczi         }
410*af7b708dSStefan Hajnoczi     }
411*af7b708dSStefan Hajnoczi 
41268d100e9SKevin Wolf     /* Initialise locks */
41368d100e9SKevin Wolf     qemu_co_mutex_init(&s->lock);
41468d100e9SKevin Wolf 
415585f8587Sbellard #ifdef DEBUG_ALLOC
4166cbc3031SPhilipp Hahn     {
4176cbc3031SPhilipp Hahn         BdrvCheckResult result = {0};
4186cbc3031SPhilipp Hahn         qcow2_check_refcounts(bs, &result);
4196cbc3031SPhilipp Hahn     }
420585f8587Sbellard #endif
4216d85a57eSJes Sorensen     return ret;
422585f8587Sbellard 
423585f8587Sbellard  fail:
4246744cbabSKevin Wolf     g_free(s->unknown_header_fields);
42575bab85cSKevin Wolf     cleanup_unknown_header_ext(bs);
426ed6ccf0fSKevin Wolf     qcow2_free_snapshots(bs);
427ed6ccf0fSKevin Wolf     qcow2_refcount_close(bs);
4287267c094SAnthony Liguori     g_free(s->l1_table);
42929c1a730SKevin Wolf     if (s->l2_table_cache) {
43029c1a730SKevin Wolf         qcow2_cache_destroy(bs, s->l2_table_cache);
43129c1a730SKevin Wolf     }
4327267c094SAnthony Liguori     g_free(s->cluster_cache);
433dea43a65SFrediano Ziglio     qemu_vfree(s->cluster_data);
4346d85a57eSJes Sorensen     return ret;
435585f8587Sbellard }
436585f8587Sbellard 
4377c80ab3fSJes Sorensen static int qcow2_set_key(BlockDriverState *bs, const char *key)
438585f8587Sbellard {
439585f8587Sbellard     BDRVQcowState *s = bs->opaque;
440585f8587Sbellard     uint8_t keybuf[16];
441585f8587Sbellard     int len, i;
442585f8587Sbellard 
443585f8587Sbellard     memset(keybuf, 0, 16);
444585f8587Sbellard     len = strlen(key);
445585f8587Sbellard     if (len > 16)
446585f8587Sbellard         len = 16;
447585f8587Sbellard     /* XXX: we could compress the chars to 7 bits to increase
448585f8587Sbellard        entropy */
449585f8587Sbellard     for(i = 0;i < len;i++) {
450585f8587Sbellard         keybuf[i] = key[i];
451585f8587Sbellard     }
452585f8587Sbellard     s->crypt_method = s->crypt_method_header;
453585f8587Sbellard 
454585f8587Sbellard     if (AES_set_encrypt_key(keybuf, 128, &s->aes_encrypt_key) != 0)
455585f8587Sbellard         return -1;
456585f8587Sbellard     if (AES_set_decrypt_key(keybuf, 128, &s->aes_decrypt_key) != 0)
457585f8587Sbellard         return -1;
458585f8587Sbellard #if 0
459585f8587Sbellard     /* test */
460585f8587Sbellard     {
461585f8587Sbellard         uint8_t in[16];
462585f8587Sbellard         uint8_t out[16];
463585f8587Sbellard         uint8_t tmp[16];
464585f8587Sbellard         for(i=0;i<16;i++)
465585f8587Sbellard             in[i] = i;
466585f8587Sbellard         AES_encrypt(in, tmp, &s->aes_encrypt_key);
467585f8587Sbellard         AES_decrypt(tmp, out, &s->aes_decrypt_key);
468585f8587Sbellard         for(i = 0; i < 16; i++)
469585f8587Sbellard             printf(" %02x", tmp[i]);
470585f8587Sbellard         printf("\n");
471585f8587Sbellard         for(i = 0; i < 16; i++)
472585f8587Sbellard             printf(" %02x", out[i]);
473585f8587Sbellard         printf("\n");
474585f8587Sbellard     }
475585f8587Sbellard #endif
476585f8587Sbellard     return 0;
477585f8587Sbellard }
478585f8587Sbellard 
479f8a2e5e3SStefan Hajnoczi static int coroutine_fn qcow2_co_is_allocated(BlockDriverState *bs,
480f8a2e5e3SStefan Hajnoczi         int64_t sector_num, int nb_sectors, int *pnum)
481585f8587Sbellard {
482f8a2e5e3SStefan Hajnoczi     BDRVQcowState *s = bs->opaque;
483585f8587Sbellard     uint64_t cluster_offset;
4841c46efaaSKevin Wolf     int ret;
485585f8587Sbellard 
486095a9c58Saliguori     *pnum = nb_sectors;
487f8a2e5e3SStefan Hajnoczi     /* FIXME We can get errors here, but the bdrv_co_is_allocated interface
488f8a2e5e3SStefan Hajnoczi      * can't pass them on today */
489f8a2e5e3SStefan Hajnoczi     qemu_co_mutex_lock(&s->lock);
4901c46efaaSKevin Wolf     ret = qcow2_get_cluster_offset(bs, sector_num << 9, pnum, &cluster_offset);
491f8a2e5e3SStefan Hajnoczi     qemu_co_mutex_unlock(&s->lock);
4921c46efaaSKevin Wolf     if (ret < 0) {
4931c46efaaSKevin Wolf         *pnum = 0;
4941c46efaaSKevin Wolf     }
495095a9c58Saliguori 
496585f8587Sbellard     return (cluster_offset != 0);
497585f8587Sbellard }
498585f8587Sbellard 
499a9465922Sbellard /* handle reading after the end of the backing file */
500bd28f835SKevin Wolf int qcow2_backing_read1(BlockDriverState *bs, QEMUIOVector *qiov,
501bd28f835SKevin Wolf                   int64_t sector_num, int nb_sectors)
502a9465922Sbellard {
503a9465922Sbellard     int n1;
504a9465922Sbellard     if ((sector_num + nb_sectors) <= bs->total_sectors)
505a9465922Sbellard         return nb_sectors;
506a9465922Sbellard     if (sector_num >= bs->total_sectors)
507a9465922Sbellard         n1 = 0;
508a9465922Sbellard     else
509a9465922Sbellard         n1 = bs->total_sectors - sector_num;
510bd28f835SKevin Wolf 
511e0d9c6f9SChunqiang Tang     qemu_iovec_memset_skip(qiov, 0, 512 * (nb_sectors - n1), 512 * n1);
512bd28f835SKevin Wolf 
513a9465922Sbellard     return n1;
514a9465922Sbellard }
515a9465922Sbellard 
516a968168cSDong Xu Wang static coroutine_fn int qcow2_co_readv(BlockDriverState *bs, int64_t sector_num,
5173fc48d09SFrediano Ziglio                           int remaining_sectors, QEMUIOVector *qiov)
5181490791fSaliguori {
519585f8587Sbellard     BDRVQcowState *s = bs->opaque;
520a9465922Sbellard     int index_in_cluster, n1;
52168d100e9SKevin Wolf     int ret;
522faf575c1SFrediano Ziglio     int cur_nr_sectors; /* number of sectors in current iteration */
523c2bdd990SFrediano Ziglio     uint64_t cluster_offset = 0;
5243fc48d09SFrediano Ziglio     uint64_t bytes_done = 0;
5253fc48d09SFrediano Ziglio     QEMUIOVector hd_qiov;
5263fc48d09SFrediano Ziglio     uint8_t *cluster_data = NULL;
527585f8587Sbellard 
5283fc48d09SFrediano Ziglio     qemu_iovec_init(&hd_qiov, qiov->niov);
5293fc48d09SFrediano Ziglio 
5303fc48d09SFrediano Ziglio     qemu_co_mutex_lock(&s->lock);
5313fc48d09SFrediano Ziglio 
5323fc48d09SFrediano Ziglio     while (remaining_sectors != 0) {
533585f8587Sbellard 
534faf575c1SFrediano Ziglio         /* prepare next request */
5353fc48d09SFrediano Ziglio         cur_nr_sectors = remaining_sectors;
536bd28f835SKevin Wolf         if (s->crypt_method) {
537faf575c1SFrediano Ziglio             cur_nr_sectors = MIN(cur_nr_sectors,
538bd28f835SKevin Wolf                 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors);
539bd28f835SKevin Wolf         }
540bd28f835SKevin Wolf 
5413fc48d09SFrediano Ziglio         ret = qcow2_get_cluster_offset(bs, sector_num << 9,
542c2bdd990SFrediano Ziglio             &cur_nr_sectors, &cluster_offset);
5431c46efaaSKevin Wolf         if (ret < 0) {
5443fc48d09SFrediano Ziglio             goto fail;
5451c46efaaSKevin Wolf         }
5461c46efaaSKevin Wolf 
5473fc48d09SFrediano Ziglio         index_in_cluster = sector_num & (s->cluster_sectors - 1);
548585f8587Sbellard 
5493fc48d09SFrediano Ziglio         qemu_iovec_reset(&hd_qiov);
5503fc48d09SFrediano Ziglio         qemu_iovec_copy(&hd_qiov, qiov, bytes_done,
551faf575c1SFrediano Ziglio             cur_nr_sectors * 512);
552bd28f835SKevin Wolf 
55368d000a3SKevin Wolf         switch (ret) {
55468d000a3SKevin Wolf         case QCOW2_CLUSTER_UNALLOCATED:
555bd28f835SKevin Wolf 
556585f8587Sbellard             if (bs->backing_hd) {
557585f8587Sbellard                 /* read from the base image */
5583fc48d09SFrediano Ziglio                 n1 = qcow2_backing_read1(bs->backing_hd, &hd_qiov,
5593fc48d09SFrediano Ziglio                     sector_num, cur_nr_sectors);
560a9465922Sbellard                 if (n1 > 0) {
56166f82ceeSKevin Wolf                     BLKDBG_EVENT(bs->file, BLKDBG_READ_BACKING_AIO);
56268d100e9SKevin Wolf                     qemu_co_mutex_unlock(&s->lock);
5633fc48d09SFrediano Ziglio                     ret = bdrv_co_readv(bs->backing_hd, sector_num,
5643fc48d09SFrediano Ziglio                                         n1, &hd_qiov);
56568d100e9SKevin Wolf                     qemu_co_mutex_lock(&s->lock);
56668d100e9SKevin Wolf                     if (ret < 0) {
5673fc48d09SFrediano Ziglio                         goto fail;
5683ab4c7e9SKevin Wolf                     }
5691490791fSaliguori                 }
570a9465922Sbellard             } else {
571585f8587Sbellard                 /* Note: in this case, no need to wait */
5723fc48d09SFrediano Ziglio                 qemu_iovec_memset(&hd_qiov, 0, 512 * cur_nr_sectors);
5731490791fSaliguori             }
57468d000a3SKevin Wolf             break;
57568d000a3SKevin Wolf 
5766377af48SKevin Wolf         case QCOW2_CLUSTER_ZERO:
5776377af48SKevin Wolf             if (s->qcow_version < 3) {
5786377af48SKevin Wolf                 ret = -EIO;
5796377af48SKevin Wolf                 goto fail;
5806377af48SKevin Wolf             }
5816377af48SKevin Wolf             qemu_iovec_memset(&hd_qiov, 0, 512 * cur_nr_sectors);
5826377af48SKevin Wolf             break;
5836377af48SKevin Wolf 
58468d000a3SKevin Wolf         case QCOW2_CLUSTER_COMPRESSED:
585585f8587Sbellard             /* add AIO support for compressed blocks ? */
586c2bdd990SFrediano Ziglio             ret = qcow2_decompress_cluster(bs, cluster_offset);
5878af36488SKevin Wolf             if (ret < 0) {
5883fc48d09SFrediano Ziglio                 goto fail;
5898af36488SKevin Wolf             }
590bd28f835SKevin Wolf 
5913fc48d09SFrediano Ziglio             qemu_iovec_from_buffer(&hd_qiov,
592bd28f835SKevin Wolf                 s->cluster_cache + index_in_cluster * 512,
593faf575c1SFrediano Ziglio                 512 * cur_nr_sectors);
59468d000a3SKevin Wolf             break;
59568d000a3SKevin Wolf 
59668d000a3SKevin Wolf         case QCOW2_CLUSTER_NORMAL:
597c2bdd990SFrediano Ziglio             if ((cluster_offset & 511) != 0) {
5983fc48d09SFrediano Ziglio                 ret = -EIO;
5993fc48d09SFrediano Ziglio                 goto fail;
600585f8587Sbellard             }
601c87c0672Saliguori 
602bd28f835SKevin Wolf             if (s->crypt_method) {
603bd28f835SKevin Wolf                 /*
604bd28f835SKevin Wolf                  * For encrypted images, read everything into a temporary
605bd28f835SKevin Wolf                  * contiguous buffer on which the AES functions can work.
606bd28f835SKevin Wolf                  */
6073fc48d09SFrediano Ziglio                 if (!cluster_data) {
6083fc48d09SFrediano Ziglio                     cluster_data =
609dea43a65SFrediano Ziglio                         qemu_blockalign(bs, QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
610bd28f835SKevin Wolf                 }
611bd28f835SKevin Wolf 
612faf575c1SFrediano Ziglio                 assert(cur_nr_sectors <=
613bd28f835SKevin Wolf                     QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors);
6143fc48d09SFrediano Ziglio                 qemu_iovec_reset(&hd_qiov);
6153fc48d09SFrediano Ziglio                 qemu_iovec_add(&hd_qiov, cluster_data,
616faf575c1SFrediano Ziglio                     512 * cur_nr_sectors);
617bd28f835SKevin Wolf             }
618bd28f835SKevin Wolf 
61966f82ceeSKevin Wolf             BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);
62068d100e9SKevin Wolf             qemu_co_mutex_unlock(&s->lock);
62168d100e9SKevin Wolf             ret = bdrv_co_readv(bs->file,
622c2bdd990SFrediano Ziglio                                 (cluster_offset >> 9) + index_in_cluster,
6233fc48d09SFrediano Ziglio                                 cur_nr_sectors, &hd_qiov);
62468d100e9SKevin Wolf             qemu_co_mutex_lock(&s->lock);
62568d100e9SKevin Wolf             if (ret < 0) {
6263fc48d09SFrediano Ziglio                 goto fail;
627585f8587Sbellard             }
628faf575c1SFrediano Ziglio             if (s->crypt_method) {
6293fc48d09SFrediano Ziglio                 qcow2_encrypt_sectors(s, sector_num,  cluster_data,
6303fc48d09SFrediano Ziglio                     cluster_data, cur_nr_sectors, 0, &s->aes_decrypt_key);
6313fc48d09SFrediano Ziglio                 qemu_iovec_reset(&hd_qiov);
6323fc48d09SFrediano Ziglio                 qemu_iovec_copy(&hd_qiov, qiov, bytes_done,
633faf575c1SFrediano Ziglio                     cur_nr_sectors * 512);
6343fc48d09SFrediano Ziglio                 qemu_iovec_from_buffer(&hd_qiov, cluster_data,
635faf575c1SFrediano Ziglio                     512 * cur_nr_sectors);
636171e3d6bSKevin Wolf             }
63768d000a3SKevin Wolf             break;
63868d000a3SKevin Wolf 
63968d000a3SKevin Wolf         default:
64068d000a3SKevin Wolf             g_assert_not_reached();
64168d000a3SKevin Wolf             ret = -EIO;
64268d000a3SKevin Wolf             goto fail;
643faf575c1SFrediano Ziglio         }
644faf575c1SFrediano Ziglio 
6453fc48d09SFrediano Ziglio         remaining_sectors -= cur_nr_sectors;
6463fc48d09SFrediano Ziglio         sector_num += cur_nr_sectors;
6473fc48d09SFrediano Ziglio         bytes_done += cur_nr_sectors * 512;
6485ebaa27eSFrediano Ziglio     }
6493fc48d09SFrediano Ziglio     ret = 0;
650f141eafeSaliguori 
6513fc48d09SFrediano Ziglio fail:
65268d100e9SKevin Wolf     qemu_co_mutex_unlock(&s->lock);
65368d100e9SKevin Wolf 
6543fc48d09SFrediano Ziglio     qemu_iovec_destroy(&hd_qiov);
655dea43a65SFrediano Ziglio     qemu_vfree(cluster_data);
65668d100e9SKevin Wolf 
65768d100e9SKevin Wolf     return ret;
658585f8587Sbellard }
659585f8587Sbellard 
66068d100e9SKevin Wolf static void run_dependent_requests(BDRVQcowState *s, QCowL2Meta *m)
661f214978aSKevin Wolf {
662f214978aSKevin Wolf     /* Take the request off the list of running requests */
663f214978aSKevin Wolf     if (m->nb_clusters != 0) {
66472cf2d4fSBlue Swirl         QLIST_REMOVE(m, next_in_flight);
665f214978aSKevin Wolf     }
666f214978aSKevin Wolf 
667d4c146f0SStefan Hajnoczi     /* Restart all dependent requests */
66868d100e9SKevin Wolf     if (!qemu_co_queue_empty(&m->dependent_requests)) {
66968d100e9SKevin Wolf         qemu_co_mutex_unlock(&s->lock);
670e8ee5e4cSStefan Hajnoczi         qemu_co_queue_restart_all(&m->dependent_requests);
67168d100e9SKevin Wolf         qemu_co_mutex_lock(&s->lock);
67268d100e9SKevin Wolf     }
673f214978aSKevin Wolf }
674f214978aSKevin Wolf 
675a968168cSDong Xu Wang static coroutine_fn int qcow2_co_writev(BlockDriverState *bs,
6763fc48d09SFrediano Ziglio                            int64_t sector_num,
6773fc48d09SFrediano Ziglio                            int remaining_sectors,
6783fc48d09SFrediano Ziglio                            QEMUIOVector *qiov)
679585f8587Sbellard {
680585f8587Sbellard     BDRVQcowState *s = bs->opaque;
681585f8587Sbellard     int index_in_cluster;
682095a9c58Saliguori     int n_end;
68368d100e9SKevin Wolf     int ret;
684faf575c1SFrediano Ziglio     int cur_nr_sectors; /* number of sectors in current iteration */
685c2bdd990SFrediano Ziglio     uint64_t cluster_offset;
6863fc48d09SFrediano Ziglio     QEMUIOVector hd_qiov;
6873fc48d09SFrediano Ziglio     uint64_t bytes_done = 0;
6883fc48d09SFrediano Ziglio     uint8_t *cluster_data = NULL;
6898e217d53SKevin Wolf     QCowL2Meta l2meta = {
6908e217d53SKevin Wolf         .nb_clusters = 0,
6918e217d53SKevin Wolf     };
692c2271403SFrediano Ziglio 
6933cce16f4SKevin Wolf     trace_qcow2_writev_start_req(qemu_coroutine_self(), sector_num,
6943cce16f4SKevin Wolf                                  remaining_sectors);
6953cce16f4SKevin Wolf 
696c2271403SFrediano Ziglio     qemu_co_queue_init(&l2meta.dependent_requests);
697585f8587Sbellard 
6983fc48d09SFrediano Ziglio     qemu_iovec_init(&hd_qiov, qiov->niov);
699585f8587Sbellard 
7003fc48d09SFrediano Ziglio     s->cluster_cache_offset = -1; /* disable compressed cache */
7013fc48d09SFrediano Ziglio 
7023fc48d09SFrediano Ziglio     qemu_co_mutex_lock(&s->lock);
7033fc48d09SFrediano Ziglio 
7043fc48d09SFrediano Ziglio     while (remaining_sectors != 0) {
7053fc48d09SFrediano Ziglio 
7063cce16f4SKevin Wolf         trace_qcow2_writev_start_part(qemu_coroutine_self());
7073fc48d09SFrediano Ziglio         index_in_cluster = sector_num & (s->cluster_sectors - 1);
7083fc48d09SFrediano Ziglio         n_end = index_in_cluster + remaining_sectors;
709095a9c58Saliguori         if (s->crypt_method &&
7105ebaa27eSFrediano Ziglio             n_end > QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors) {
711095a9c58Saliguori             n_end = QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors;
7125ebaa27eSFrediano Ziglio         }
713095a9c58Saliguori 
7143fc48d09SFrediano Ziglio         ret = qcow2_alloc_cluster_offset(bs, sector_num << 9,
715c2271403SFrediano Ziglio             index_in_cluster, n_end, &cur_nr_sectors, &l2meta);
716148da7eaSKevin Wolf         if (ret < 0) {
7173fc48d09SFrediano Ziglio             goto fail;
718148da7eaSKevin Wolf         }
719148da7eaSKevin Wolf 
720c2bdd990SFrediano Ziglio         cluster_offset = l2meta.cluster_offset;
721c2bdd990SFrediano Ziglio         assert((cluster_offset & 511) == 0);
722148da7eaSKevin Wolf 
7233fc48d09SFrediano Ziglio         qemu_iovec_reset(&hd_qiov);
7243fc48d09SFrediano Ziglio         qemu_iovec_copy(&hd_qiov, qiov, bytes_done,
725faf575c1SFrediano Ziglio             cur_nr_sectors * 512);
7266f5f060bSKevin Wolf 
727585f8587Sbellard         if (s->crypt_method) {
7283fc48d09SFrediano Ziglio             if (!cluster_data) {
729dea43a65SFrediano Ziglio                 cluster_data = qemu_blockalign(bs, QCOW_MAX_CRYPT_CLUSTERS *
730095a9c58Saliguori                                                  s->cluster_size);
731585f8587Sbellard             }
7326f5f060bSKevin Wolf 
7333fc48d09SFrediano Ziglio             assert(hd_qiov.size <=
7345ebaa27eSFrediano Ziglio                    QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
7353fc48d09SFrediano Ziglio             qemu_iovec_to_buffer(&hd_qiov, cluster_data);
7366f5f060bSKevin Wolf 
7373fc48d09SFrediano Ziglio             qcow2_encrypt_sectors(s, sector_num, cluster_data,
7383fc48d09SFrediano Ziglio                 cluster_data, cur_nr_sectors, 1, &s->aes_encrypt_key);
7396f5f060bSKevin Wolf 
7403fc48d09SFrediano Ziglio             qemu_iovec_reset(&hd_qiov);
7413fc48d09SFrediano Ziglio             qemu_iovec_add(&hd_qiov, cluster_data,
742faf575c1SFrediano Ziglio                 cur_nr_sectors * 512);
743585f8587Sbellard         }
7446f5f060bSKevin Wolf 
74566f82ceeSKevin Wolf         BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO);
74668d100e9SKevin Wolf         qemu_co_mutex_unlock(&s->lock);
7473cce16f4SKevin Wolf         trace_qcow2_writev_data(qemu_coroutine_self(),
7483cce16f4SKevin Wolf                                 (cluster_offset >> 9) + index_in_cluster);
74968d100e9SKevin Wolf         ret = bdrv_co_writev(bs->file,
750c2bdd990SFrediano Ziglio                              (cluster_offset >> 9) + index_in_cluster,
7513fc48d09SFrediano Ziglio                              cur_nr_sectors, &hd_qiov);
75268d100e9SKevin Wolf         qemu_co_mutex_lock(&s->lock);
75368d100e9SKevin Wolf         if (ret < 0) {
7543fc48d09SFrediano Ziglio             goto fail;
755171e3d6bSKevin Wolf         }
756f141eafeSaliguori 
757c2271403SFrediano Ziglio         ret = qcow2_alloc_cluster_link_l2(bs, &l2meta);
758faf575c1SFrediano Ziglio         if (ret < 0) {
7593fc48d09SFrediano Ziglio             goto fail;
760faf575c1SFrediano Ziglio         }
761faf575c1SFrediano Ziglio 
7620fa9131aSKevin Wolf         run_dependent_requests(s, &l2meta);
7630fa9131aSKevin Wolf 
7643fc48d09SFrediano Ziglio         remaining_sectors -= cur_nr_sectors;
7653fc48d09SFrediano Ziglio         sector_num += cur_nr_sectors;
7663fc48d09SFrediano Ziglio         bytes_done += cur_nr_sectors * 512;
7673cce16f4SKevin Wolf         trace_qcow2_writev_done_part(qemu_coroutine_self(), cur_nr_sectors);
7685ebaa27eSFrediano Ziglio     }
7693fc48d09SFrediano Ziglio     ret = 0;
770faf575c1SFrediano Ziglio 
7713fc48d09SFrediano Ziglio fail:
7720fa9131aSKevin Wolf     run_dependent_requests(s, &l2meta);
7730fa9131aSKevin Wolf 
77468d100e9SKevin Wolf     qemu_co_mutex_unlock(&s->lock);
775585f8587Sbellard 
7763fc48d09SFrediano Ziglio     qemu_iovec_destroy(&hd_qiov);
777dea43a65SFrediano Ziglio     qemu_vfree(cluster_data);
7783cce16f4SKevin Wolf     trace_qcow2_writev_done_req(qemu_coroutine_self(), ret);
77942496d62SKevin Wolf 
78068d100e9SKevin Wolf     return ret;
781585f8587Sbellard }
782585f8587Sbellard 
7837c80ab3fSJes Sorensen static void qcow2_close(BlockDriverState *bs)
784585f8587Sbellard {
785585f8587Sbellard     BDRVQcowState *s = bs->opaque;
7867267c094SAnthony Liguori     g_free(s->l1_table);
78729c1a730SKevin Wolf 
78829c1a730SKevin Wolf     qcow2_cache_flush(bs, s->l2_table_cache);
78929c1a730SKevin Wolf     qcow2_cache_flush(bs, s->refcount_block_cache);
79029c1a730SKevin Wolf 
79129c1a730SKevin Wolf     qcow2_cache_destroy(bs, s->l2_table_cache);
79229c1a730SKevin Wolf     qcow2_cache_destroy(bs, s->refcount_block_cache);
79329c1a730SKevin Wolf 
7946744cbabSKevin Wolf     g_free(s->unknown_header_fields);
79575bab85cSKevin Wolf     cleanup_unknown_header_ext(bs);
7966744cbabSKevin Wolf 
7977267c094SAnthony Liguori     g_free(s->cluster_cache);
798dea43a65SFrediano Ziglio     qemu_vfree(s->cluster_data);
799ed6ccf0fSKevin Wolf     qcow2_refcount_close(bs);
80028c1202bSLi Zhi Hui     qcow2_free_snapshots(bs);
801585f8587Sbellard }
802585f8587Sbellard 
80306d9260fSAnthony Liguori static void qcow2_invalidate_cache(BlockDriverState *bs)
80406d9260fSAnthony Liguori {
80506d9260fSAnthony Liguori     BDRVQcowState *s = bs->opaque;
80606d9260fSAnthony Liguori     int flags = s->flags;
80706d9260fSAnthony Liguori     AES_KEY aes_encrypt_key;
80806d9260fSAnthony Liguori     AES_KEY aes_decrypt_key;
80906d9260fSAnthony Liguori     uint32_t crypt_method = 0;
81006d9260fSAnthony Liguori 
81106d9260fSAnthony Liguori     /*
81206d9260fSAnthony Liguori      * Backing files are read-only which makes all of their metadata immutable,
81306d9260fSAnthony Liguori      * that means we don't have to worry about reopening them here.
81406d9260fSAnthony Liguori      */
81506d9260fSAnthony Liguori 
81606d9260fSAnthony Liguori     if (s->crypt_method) {
81706d9260fSAnthony Liguori         crypt_method = s->crypt_method;
81806d9260fSAnthony Liguori         memcpy(&aes_encrypt_key, &s->aes_encrypt_key, sizeof(aes_encrypt_key));
81906d9260fSAnthony Liguori         memcpy(&aes_decrypt_key, &s->aes_decrypt_key, sizeof(aes_decrypt_key));
82006d9260fSAnthony Liguori     }
82106d9260fSAnthony Liguori 
82206d9260fSAnthony Liguori     qcow2_close(bs);
82306d9260fSAnthony Liguori 
82406d9260fSAnthony Liguori     memset(s, 0, sizeof(BDRVQcowState));
82506d9260fSAnthony Liguori     qcow2_open(bs, flags);
82606d9260fSAnthony Liguori 
82706d9260fSAnthony Liguori     if (crypt_method) {
82806d9260fSAnthony Liguori         s->crypt_method = crypt_method;
82906d9260fSAnthony Liguori         memcpy(&s->aes_encrypt_key, &aes_encrypt_key, sizeof(aes_encrypt_key));
83006d9260fSAnthony Liguori         memcpy(&s->aes_decrypt_key, &aes_decrypt_key, sizeof(aes_decrypt_key));
83106d9260fSAnthony Liguori     }
83206d9260fSAnthony Liguori }
83306d9260fSAnthony Liguori 
834e24e49e6SKevin Wolf static size_t header_ext_add(char *buf, uint32_t magic, const void *s,
835e24e49e6SKevin Wolf     size_t len, size_t buflen)
836756e6736SKevin Wolf {
837e24e49e6SKevin Wolf     QCowExtension *ext_backing_fmt = (QCowExtension*) buf;
838e24e49e6SKevin Wolf     size_t ext_len = sizeof(QCowExtension) + ((len + 7) & ~7);
839756e6736SKevin Wolf 
840e24e49e6SKevin Wolf     if (buflen < ext_len) {
841756e6736SKevin Wolf         return -ENOSPC;
842756e6736SKevin Wolf     }
843756e6736SKevin Wolf 
844e24e49e6SKevin Wolf     *ext_backing_fmt = (QCowExtension) {
845e24e49e6SKevin Wolf         .magic  = cpu_to_be32(magic),
846e24e49e6SKevin Wolf         .len    = cpu_to_be32(len),
847e24e49e6SKevin Wolf     };
848e24e49e6SKevin Wolf     memcpy(buf + sizeof(QCowExtension), s, len);
849756e6736SKevin Wolf 
850e24e49e6SKevin Wolf     return ext_len;
851756e6736SKevin Wolf }
852756e6736SKevin Wolf 
853e24e49e6SKevin Wolf /*
854e24e49e6SKevin Wolf  * Updates the qcow2 header, including the variable length parts of it, i.e.
855e24e49e6SKevin Wolf  * the backing file name and all extensions. qcow2 was not designed to allow
856e24e49e6SKevin Wolf  * such changes, so if we run out of space (we can only use the first cluster)
857e24e49e6SKevin Wolf  * this function may fail.
858e24e49e6SKevin Wolf  *
859e24e49e6SKevin Wolf  * Returns 0 on success, -errno in error cases.
860e24e49e6SKevin Wolf  */
861e24e49e6SKevin Wolf int qcow2_update_header(BlockDriverState *bs)
862e24e49e6SKevin Wolf {
863e24e49e6SKevin Wolf     BDRVQcowState *s = bs->opaque;
864e24e49e6SKevin Wolf     QCowHeader *header;
865e24e49e6SKevin Wolf     char *buf;
866e24e49e6SKevin Wolf     size_t buflen = s->cluster_size;
867e24e49e6SKevin Wolf     int ret;
868e24e49e6SKevin Wolf     uint64_t total_size;
869e24e49e6SKevin Wolf     uint32_t refcount_table_clusters;
8706744cbabSKevin Wolf     size_t header_length;
87175bab85cSKevin Wolf     Qcow2UnknownHeaderExtension *uext;
872e24e49e6SKevin Wolf 
873e24e49e6SKevin Wolf     buf = qemu_blockalign(bs, buflen);
874e24e49e6SKevin Wolf 
875e24e49e6SKevin Wolf     /* Header structure */
876e24e49e6SKevin Wolf     header = (QCowHeader*) buf;
877e24e49e6SKevin Wolf 
878e24e49e6SKevin Wolf     if (buflen < sizeof(*header)) {
879e24e49e6SKevin Wolf         ret = -ENOSPC;
880e24e49e6SKevin Wolf         goto fail;
881756e6736SKevin Wolf     }
882756e6736SKevin Wolf 
8836744cbabSKevin Wolf     header_length = sizeof(*header) + s->unknown_header_fields_size;
884e24e49e6SKevin Wolf     total_size = bs->total_sectors * BDRV_SECTOR_SIZE;
885e24e49e6SKevin Wolf     refcount_table_clusters = s->refcount_table_size >> (s->cluster_bits - 3);
886e24e49e6SKevin Wolf 
887e24e49e6SKevin Wolf     *header = (QCowHeader) {
8886744cbabSKevin Wolf         /* Version 2 fields */
889e24e49e6SKevin Wolf         .magic                  = cpu_to_be32(QCOW_MAGIC),
8906744cbabSKevin Wolf         .version                = cpu_to_be32(s->qcow_version),
891e24e49e6SKevin Wolf         .backing_file_offset    = 0,
892e24e49e6SKevin Wolf         .backing_file_size      = 0,
893e24e49e6SKevin Wolf         .cluster_bits           = cpu_to_be32(s->cluster_bits),
894e24e49e6SKevin Wolf         .size                   = cpu_to_be64(total_size),
895e24e49e6SKevin Wolf         .crypt_method           = cpu_to_be32(s->crypt_method_header),
896e24e49e6SKevin Wolf         .l1_size                = cpu_to_be32(s->l1_size),
897e24e49e6SKevin Wolf         .l1_table_offset        = cpu_to_be64(s->l1_table_offset),
898e24e49e6SKevin Wolf         .refcount_table_offset  = cpu_to_be64(s->refcount_table_offset),
899e24e49e6SKevin Wolf         .refcount_table_clusters = cpu_to_be32(refcount_table_clusters),
900e24e49e6SKevin Wolf         .nb_snapshots           = cpu_to_be32(s->nb_snapshots),
901e24e49e6SKevin Wolf         .snapshots_offset       = cpu_to_be64(s->snapshots_offset),
9026744cbabSKevin Wolf 
9036744cbabSKevin Wolf         /* Version 3 fields */
9046744cbabSKevin Wolf         .incompatible_features  = cpu_to_be64(s->incompatible_features),
9056744cbabSKevin Wolf         .compatible_features    = cpu_to_be64(s->compatible_features),
9066744cbabSKevin Wolf         .autoclear_features     = cpu_to_be64(s->autoclear_features),
9076744cbabSKevin Wolf         .refcount_order         = cpu_to_be32(3 + REFCOUNT_SHIFT),
9086744cbabSKevin Wolf         .header_length          = cpu_to_be32(header_length),
909e24e49e6SKevin Wolf     };
910e24e49e6SKevin Wolf 
9116744cbabSKevin Wolf     /* For older versions, write a shorter header */
9126744cbabSKevin Wolf     switch (s->qcow_version) {
9136744cbabSKevin Wolf     case 2:
9146744cbabSKevin Wolf         ret = offsetof(QCowHeader, incompatible_features);
9156744cbabSKevin Wolf         break;
9166744cbabSKevin Wolf     case 3:
9176744cbabSKevin Wolf         ret = sizeof(*header);
9186744cbabSKevin Wolf         break;
9196744cbabSKevin Wolf     default:
920b6c14762SJim Meyering         ret = -EINVAL;
921b6c14762SJim Meyering         goto fail;
9226744cbabSKevin Wolf     }
9236744cbabSKevin Wolf 
9246744cbabSKevin Wolf     buf += ret;
9256744cbabSKevin Wolf     buflen -= ret;
9266744cbabSKevin Wolf     memset(buf, 0, buflen);
9276744cbabSKevin Wolf 
9286744cbabSKevin Wolf     /* Preserve any unknown field in the header */
9296744cbabSKevin Wolf     if (s->unknown_header_fields_size) {
9306744cbabSKevin Wolf         if (buflen < s->unknown_header_fields_size) {
9316744cbabSKevin Wolf             ret = -ENOSPC;
9326744cbabSKevin Wolf             goto fail;
9336744cbabSKevin Wolf         }
9346744cbabSKevin Wolf 
9356744cbabSKevin Wolf         memcpy(buf, s->unknown_header_fields, s->unknown_header_fields_size);
9366744cbabSKevin Wolf         buf += s->unknown_header_fields_size;
9376744cbabSKevin Wolf         buflen -= s->unknown_header_fields_size;
9386744cbabSKevin Wolf     }
939e24e49e6SKevin Wolf 
940e24e49e6SKevin Wolf     /* Backing file format header extension */
941e24e49e6SKevin Wolf     if (*bs->backing_format) {
942e24e49e6SKevin Wolf         ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BACKING_FORMAT,
943e24e49e6SKevin Wolf                              bs->backing_format, strlen(bs->backing_format),
944e24e49e6SKevin Wolf                              buflen);
945756e6736SKevin Wolf         if (ret < 0) {
946756e6736SKevin Wolf             goto fail;
947756e6736SKevin Wolf         }
948756e6736SKevin Wolf 
949e24e49e6SKevin Wolf         buf += ret;
950e24e49e6SKevin Wolf         buflen -= ret;
951e24e49e6SKevin Wolf     }
952756e6736SKevin Wolf 
953cfcc4c62SKevin Wolf     /* Feature table */
954cfcc4c62SKevin Wolf     Qcow2Feature features[] = {
955cfcc4c62SKevin Wolf         /* no feature defined yet */
956cfcc4c62SKevin Wolf     };
957cfcc4c62SKevin Wolf 
958cfcc4c62SKevin Wolf     ret = header_ext_add(buf, QCOW2_EXT_MAGIC_FEATURE_TABLE,
959cfcc4c62SKevin Wolf                          features, sizeof(features), buflen);
960cfcc4c62SKevin Wolf     if (ret < 0) {
961cfcc4c62SKevin Wolf         goto fail;
962cfcc4c62SKevin Wolf     }
963cfcc4c62SKevin Wolf     buf += ret;
964cfcc4c62SKevin Wolf     buflen -= ret;
965cfcc4c62SKevin Wolf 
96675bab85cSKevin Wolf     /* Keep unknown header extensions */
96775bab85cSKevin Wolf     QLIST_FOREACH(uext, &s->unknown_header_ext, next) {
96875bab85cSKevin Wolf         ret = header_ext_add(buf, uext->magic, uext->data, uext->len, buflen);
96975bab85cSKevin Wolf         if (ret < 0) {
97075bab85cSKevin Wolf             goto fail;
97175bab85cSKevin Wolf         }
97275bab85cSKevin Wolf 
97375bab85cSKevin Wolf         buf += ret;
97475bab85cSKevin Wolf         buflen -= ret;
97575bab85cSKevin Wolf     }
97675bab85cSKevin Wolf 
977e24e49e6SKevin Wolf     /* End of header extensions */
978e24e49e6SKevin Wolf     ret = header_ext_add(buf, QCOW2_EXT_MAGIC_END, NULL, 0, buflen);
979756e6736SKevin Wolf     if (ret < 0) {
980756e6736SKevin Wolf         goto fail;
981756e6736SKevin Wolf     }
982756e6736SKevin Wolf 
983e24e49e6SKevin Wolf     buf += ret;
984e24e49e6SKevin Wolf     buflen -= ret;
985e24e49e6SKevin Wolf 
986e24e49e6SKevin Wolf     /* Backing file name */
987e24e49e6SKevin Wolf     if (*bs->backing_file) {
988e24e49e6SKevin Wolf         size_t backing_file_len = strlen(bs->backing_file);
989e24e49e6SKevin Wolf 
990e24e49e6SKevin Wolf         if (buflen < backing_file_len) {
991e24e49e6SKevin Wolf             ret = -ENOSPC;
992e24e49e6SKevin Wolf             goto fail;
993e24e49e6SKevin Wolf         }
994e24e49e6SKevin Wolf 
995e24e49e6SKevin Wolf         strncpy(buf, bs->backing_file, buflen);
996e24e49e6SKevin Wolf 
997e24e49e6SKevin Wolf         header->backing_file_offset = cpu_to_be64(buf - ((char*) header));
998e24e49e6SKevin Wolf         header->backing_file_size   = cpu_to_be32(backing_file_len);
999e24e49e6SKevin Wolf     }
1000e24e49e6SKevin Wolf 
1001e24e49e6SKevin Wolf     /* Write the new header */
1002e24e49e6SKevin Wolf     ret = bdrv_pwrite(bs->file, 0, header, s->cluster_size);
1003756e6736SKevin Wolf     if (ret < 0) {
1004756e6736SKevin Wolf         goto fail;
1005756e6736SKevin Wolf     }
1006756e6736SKevin Wolf 
1007756e6736SKevin Wolf     ret = 0;
1008756e6736SKevin Wolf fail:
1009e24e49e6SKevin Wolf     qemu_vfree(header);
1010756e6736SKevin Wolf     return ret;
1011756e6736SKevin Wolf }
1012756e6736SKevin Wolf 
1013756e6736SKevin Wolf static int qcow2_change_backing_file(BlockDriverState *bs,
1014756e6736SKevin Wolf     const char *backing_file, const char *backing_fmt)
1015756e6736SKevin Wolf {
1016e24e49e6SKevin Wolf     pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
1017e24e49e6SKevin Wolf     pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
1018e24e49e6SKevin Wolf 
1019e24e49e6SKevin Wolf     return qcow2_update_header(bs);
1020756e6736SKevin Wolf }
1021756e6736SKevin Wolf 
1022a35e1c17SKevin Wolf static int preallocate(BlockDriverState *bs)
1023a35e1c17SKevin Wolf {
1024a35e1c17SKevin Wolf     uint64_t nb_sectors;
1025a35e1c17SKevin Wolf     uint64_t offset;
1026a35e1c17SKevin Wolf     int num;
1027148da7eaSKevin Wolf     int ret;
1028a35e1c17SKevin Wolf     QCowL2Meta meta;
1029a35e1c17SKevin Wolf 
1030a35e1c17SKevin Wolf     nb_sectors = bdrv_getlength(bs) >> 9;
1031a35e1c17SKevin Wolf     offset = 0;
103268d100e9SKevin Wolf     qemu_co_queue_init(&meta.dependent_requests);
1033148da7eaSKevin Wolf     meta.cluster_offset = 0;
1034a35e1c17SKevin Wolf 
1035a35e1c17SKevin Wolf     while (nb_sectors) {
1036a35e1c17SKevin Wolf         num = MIN(nb_sectors, INT_MAX >> 9);
1037148da7eaSKevin Wolf         ret = qcow2_alloc_cluster_offset(bs, offset, 0, num, &num, &meta);
1038148da7eaSKevin Wolf         if (ret < 0) {
103919dbcbf7SKevin Wolf             return ret;
1040a35e1c17SKevin Wolf         }
1041a35e1c17SKevin Wolf 
104219dbcbf7SKevin Wolf         ret = qcow2_alloc_cluster_link_l2(bs, &meta);
104319dbcbf7SKevin Wolf         if (ret < 0) {
1044148da7eaSKevin Wolf             qcow2_free_any_clusters(bs, meta.cluster_offset, meta.nb_clusters);
104519dbcbf7SKevin Wolf             return ret;
1046a35e1c17SKevin Wolf         }
1047a35e1c17SKevin Wolf 
1048f214978aSKevin Wolf         /* There are no dependent requests, but we need to remove our request
1049f214978aSKevin Wolf          * from the list of in-flight requests */
105068d100e9SKevin Wolf         run_dependent_requests(bs->opaque, &meta);
1051f214978aSKevin Wolf 
1052a35e1c17SKevin Wolf         /* TODO Preallocate data if requested */
1053a35e1c17SKevin Wolf 
1054a35e1c17SKevin Wolf         nb_sectors -= num;
1055a35e1c17SKevin Wolf         offset += num << 9;
1056a35e1c17SKevin Wolf     }
1057a35e1c17SKevin Wolf 
1058a35e1c17SKevin Wolf     /*
1059a35e1c17SKevin Wolf      * It is expected that the image file is large enough to actually contain
1060a35e1c17SKevin Wolf      * all of the allocated clusters (otherwise we get failing reads after
1061a35e1c17SKevin Wolf      * EOF). Extend the image to the last allocated sector.
1062a35e1c17SKevin Wolf      */
1063148da7eaSKevin Wolf     if (meta.cluster_offset != 0) {
1064ea80b906SKevin Wolf         uint8_t buf[512];
1065ea80b906SKevin Wolf         memset(buf, 0, 512);
106619dbcbf7SKevin Wolf         ret = bdrv_write(bs->file, (meta.cluster_offset >> 9) + num - 1, buf, 1);
106719dbcbf7SKevin Wolf         if (ret < 0) {
106819dbcbf7SKevin Wolf             return ret;
106919dbcbf7SKevin Wolf         }
1070a35e1c17SKevin Wolf     }
1071a35e1c17SKevin Wolf 
1072a35e1c17SKevin Wolf     return 0;
1073a35e1c17SKevin Wolf }
1074a35e1c17SKevin Wolf 
10757c80ab3fSJes Sorensen static int qcow2_create2(const char *filename, int64_t total_size,
1076a9420734SKevin Wolf                          const char *backing_file, const char *backing_format,
1077a9420734SKevin Wolf                          int flags, size_t cluster_size, int prealloc,
10786744cbabSKevin Wolf                          QEMUOptionParameter *options, int version)
1079a9420734SKevin Wolf {
10809b2260cbSDong Xu Wang     /* Calculate cluster_bits */
1081a9420734SKevin Wolf     int cluster_bits;
1082a9420734SKevin Wolf     cluster_bits = ffs(cluster_size) - 1;
1083a9420734SKevin Wolf     if (cluster_bits < MIN_CLUSTER_BITS || cluster_bits > MAX_CLUSTER_BITS ||
1084a9420734SKevin Wolf         (1 << cluster_bits) != cluster_size)
1085a9420734SKevin Wolf     {
1086a9420734SKevin Wolf         error_report(
10876daf194dSMarkus Armbruster             "Cluster size must be a power of two between %d and %dk",
1088a9420734SKevin Wolf             1 << MIN_CLUSTER_BITS, 1 << (MAX_CLUSTER_BITS - 10));
1089a9420734SKevin Wolf         return -EINVAL;
1090a9420734SKevin Wolf     }
1091a9420734SKevin Wolf 
1092a9420734SKevin Wolf     /*
1093a9420734SKevin Wolf      * Open the image file and write a minimal qcow2 header.
1094a9420734SKevin Wolf      *
1095a9420734SKevin Wolf      * We keep things simple and start with a zero-sized image. We also
1096a9420734SKevin Wolf      * do without refcount blocks or a L1 table for now. We'll fix the
1097a9420734SKevin Wolf      * inconsistency later.
1098a9420734SKevin Wolf      *
1099a9420734SKevin Wolf      * We do need a refcount table because growing the refcount table means
1100a9420734SKevin Wolf      * allocating two new refcount blocks - the seconds of which would be at
1101a9420734SKevin Wolf      * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
1102a9420734SKevin Wolf      * size for any qcow2 image.
1103a9420734SKevin Wolf      */
1104a9420734SKevin Wolf     BlockDriverState* bs;
1105a9420734SKevin Wolf     QCowHeader header;
1106a9420734SKevin Wolf     uint8_t* refcount_table;
1107a9420734SKevin Wolf     int ret;
1108a9420734SKevin Wolf 
1109a9420734SKevin Wolf     ret = bdrv_create_file(filename, options);
1110a9420734SKevin Wolf     if (ret < 0) {
1111a9420734SKevin Wolf         return ret;
1112a9420734SKevin Wolf     }
1113a9420734SKevin Wolf 
1114a9420734SKevin Wolf     ret = bdrv_file_open(&bs, filename, BDRV_O_RDWR);
1115a9420734SKevin Wolf     if (ret < 0) {
1116a9420734SKevin Wolf         return ret;
1117a9420734SKevin Wolf     }
1118a9420734SKevin Wolf 
1119a9420734SKevin Wolf     /* Write the header */
1120a9420734SKevin Wolf     memset(&header, 0, sizeof(header));
1121a9420734SKevin Wolf     header.magic = cpu_to_be32(QCOW_MAGIC);
11226744cbabSKevin Wolf     header.version = cpu_to_be32(version);
1123a9420734SKevin Wolf     header.cluster_bits = cpu_to_be32(cluster_bits);
1124a9420734SKevin Wolf     header.size = cpu_to_be64(0);
1125a9420734SKevin Wolf     header.l1_table_offset = cpu_to_be64(0);
1126a9420734SKevin Wolf     header.l1_size = cpu_to_be32(0);
1127a9420734SKevin Wolf     header.refcount_table_offset = cpu_to_be64(cluster_size);
1128a9420734SKevin Wolf     header.refcount_table_clusters = cpu_to_be32(1);
11296744cbabSKevin Wolf     header.refcount_order = cpu_to_be32(3 + REFCOUNT_SHIFT);
11306744cbabSKevin Wolf     header.header_length = cpu_to_be32(sizeof(header));
1131a9420734SKevin Wolf 
1132a9420734SKevin Wolf     if (flags & BLOCK_FLAG_ENCRYPT) {
1133a9420734SKevin Wolf         header.crypt_method = cpu_to_be32(QCOW_CRYPT_AES);
1134a9420734SKevin Wolf     } else {
1135a9420734SKevin Wolf         header.crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
1136a9420734SKevin Wolf     }
1137a9420734SKevin Wolf 
1138a9420734SKevin Wolf     ret = bdrv_pwrite(bs, 0, &header, sizeof(header));
1139a9420734SKevin Wolf     if (ret < 0) {
1140a9420734SKevin Wolf         goto out;
1141a9420734SKevin Wolf     }
1142a9420734SKevin Wolf 
1143a9420734SKevin Wolf     /* Write an empty refcount table */
11447267c094SAnthony Liguori     refcount_table = g_malloc0(cluster_size);
1145a9420734SKevin Wolf     ret = bdrv_pwrite(bs, cluster_size, refcount_table, cluster_size);
11467267c094SAnthony Liguori     g_free(refcount_table);
1147a9420734SKevin Wolf 
1148a9420734SKevin Wolf     if (ret < 0) {
1149a9420734SKevin Wolf         goto out;
1150a9420734SKevin Wolf     }
1151a9420734SKevin Wolf 
1152a9420734SKevin Wolf     bdrv_close(bs);
1153a9420734SKevin Wolf 
1154a9420734SKevin Wolf     /*
1155a9420734SKevin Wolf      * And now open the image and make it consistent first (i.e. increase the
1156a9420734SKevin Wolf      * refcount of the cluster that is occupied by the header and the refcount
1157a9420734SKevin Wolf      * table)
1158a9420734SKevin Wolf      */
1159a9420734SKevin Wolf     BlockDriver* drv = bdrv_find_format("qcow2");
1160a9420734SKevin Wolf     assert(drv != NULL);
1161e1a7107fSKevin Wolf     ret = bdrv_open(bs, filename,
1162e1a7107fSKevin Wolf         BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_NO_FLUSH, drv);
1163a9420734SKevin Wolf     if (ret < 0) {
1164a9420734SKevin Wolf         goto out;
1165a9420734SKevin Wolf     }
1166a9420734SKevin Wolf 
1167a9420734SKevin Wolf     ret = qcow2_alloc_clusters(bs, 2 * cluster_size);
1168a9420734SKevin Wolf     if (ret < 0) {
1169a9420734SKevin Wolf         goto out;
1170a9420734SKevin Wolf 
1171a9420734SKevin Wolf     } else if (ret != 0) {
1172a9420734SKevin Wolf         error_report("Huh, first cluster in empty image is already in use?");
1173a9420734SKevin Wolf         abort();
1174a9420734SKevin Wolf     }
1175a9420734SKevin Wolf 
1176a9420734SKevin Wolf     /* Okay, now that we have a valid image, let's give it the right size */
1177a9420734SKevin Wolf     ret = bdrv_truncate(bs, total_size * BDRV_SECTOR_SIZE);
1178a9420734SKevin Wolf     if (ret < 0) {
1179a9420734SKevin Wolf         goto out;
1180a9420734SKevin Wolf     }
1181a9420734SKevin Wolf 
1182a9420734SKevin Wolf     /* Want a backing file? There you go.*/
1183a9420734SKevin Wolf     if (backing_file) {
1184a9420734SKevin Wolf         ret = bdrv_change_backing_file(bs, backing_file, backing_format);
1185a9420734SKevin Wolf         if (ret < 0) {
1186a9420734SKevin Wolf             goto out;
1187a9420734SKevin Wolf         }
1188a9420734SKevin Wolf     }
1189a9420734SKevin Wolf 
1190a9420734SKevin Wolf     /* And if we're supposed to preallocate metadata, do that now */
1191a9420734SKevin Wolf     if (prealloc) {
119215552c4aSZhi Yong Wu         BDRVQcowState *s = bs->opaque;
119315552c4aSZhi Yong Wu         qemu_co_mutex_lock(&s->lock);
1194a9420734SKevin Wolf         ret = preallocate(bs);
119515552c4aSZhi Yong Wu         qemu_co_mutex_unlock(&s->lock);
1196a9420734SKevin Wolf         if (ret < 0) {
1197a9420734SKevin Wolf             goto out;
1198a9420734SKevin Wolf         }
1199a9420734SKevin Wolf     }
1200a9420734SKevin Wolf 
1201a9420734SKevin Wolf     ret = 0;
1202a9420734SKevin Wolf out:
1203a9420734SKevin Wolf     bdrv_delete(bs);
1204a9420734SKevin Wolf     return ret;
1205a9420734SKevin Wolf }
1206de5f3f40SKevin Wolf 
12077c80ab3fSJes Sorensen static int qcow2_create(const char *filename, QEMUOptionParameter *options)
1208de5f3f40SKevin Wolf {
1209de5f3f40SKevin Wolf     const char *backing_file = NULL;
1210de5f3f40SKevin Wolf     const char *backing_fmt = NULL;
1211de5f3f40SKevin Wolf     uint64_t sectors = 0;
1212de5f3f40SKevin Wolf     int flags = 0;
121399cce9faSKevin Wolf     size_t cluster_size = DEFAULT_CLUSTER_SIZE;
1214de5f3f40SKevin Wolf     int prealloc = 0;
12156744cbabSKevin Wolf     int version = 2;
1216de5f3f40SKevin Wolf 
1217de5f3f40SKevin Wolf     /* Read out options */
1218de5f3f40SKevin Wolf     while (options && options->name) {
1219de5f3f40SKevin Wolf         if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
1220de5f3f40SKevin Wolf             sectors = options->value.n / 512;
1221de5f3f40SKevin Wolf         } else if (!strcmp(options->name, BLOCK_OPT_BACKING_FILE)) {
1222de5f3f40SKevin Wolf             backing_file = options->value.s;
1223de5f3f40SKevin Wolf         } else if (!strcmp(options->name, BLOCK_OPT_BACKING_FMT)) {
1224de5f3f40SKevin Wolf             backing_fmt = options->value.s;
1225de5f3f40SKevin Wolf         } else if (!strcmp(options->name, BLOCK_OPT_ENCRYPT)) {
1226de5f3f40SKevin Wolf             flags |= options->value.n ? BLOCK_FLAG_ENCRYPT : 0;
1227de5f3f40SKevin Wolf         } else if (!strcmp(options->name, BLOCK_OPT_CLUSTER_SIZE)) {
1228de5f3f40SKevin Wolf             if (options->value.n) {
1229de5f3f40SKevin Wolf                 cluster_size = options->value.n;
1230de5f3f40SKevin Wolf             }
1231de5f3f40SKevin Wolf         } else if (!strcmp(options->name, BLOCK_OPT_PREALLOC)) {
1232de5f3f40SKevin Wolf             if (!options->value.s || !strcmp(options->value.s, "off")) {
1233de5f3f40SKevin Wolf                 prealloc = 0;
1234de5f3f40SKevin Wolf             } else if (!strcmp(options->value.s, "metadata")) {
1235de5f3f40SKevin Wolf                 prealloc = 1;
1236de5f3f40SKevin Wolf             } else {
1237de5f3f40SKevin Wolf                 fprintf(stderr, "Invalid preallocation mode: '%s'\n",
1238de5f3f40SKevin Wolf                     options->value.s);
1239de5f3f40SKevin Wolf                 return -EINVAL;
1240de5f3f40SKevin Wolf             }
12416744cbabSKevin Wolf         } else if (!strcmp(options->name, BLOCK_OPT_COMPAT_LEVEL)) {
12426744cbabSKevin Wolf             if (!options->value.s || !strcmp(options->value.s, "0.10")) {
12436744cbabSKevin Wolf                 version = 2;
12446744cbabSKevin Wolf             } else if (!strcmp(options->value.s, "1.1")) {
12456744cbabSKevin Wolf                 version = 3;
12466744cbabSKevin Wolf             } else {
12476744cbabSKevin Wolf                 fprintf(stderr, "Invalid compatibility level: '%s'\n",
12486744cbabSKevin Wolf                     options->value.s);
12496744cbabSKevin Wolf                 return -EINVAL;
12506744cbabSKevin Wolf             }
1251de5f3f40SKevin Wolf         }
1252de5f3f40SKevin Wolf         options++;
1253de5f3f40SKevin Wolf     }
1254de5f3f40SKevin Wolf 
1255de5f3f40SKevin Wolf     if (backing_file && prealloc) {
1256de5f3f40SKevin Wolf         fprintf(stderr, "Backing file and preallocation cannot be used at "
1257de5f3f40SKevin Wolf             "the same time\n");
1258de5f3f40SKevin Wolf         return -EINVAL;
1259de5f3f40SKevin Wolf     }
1260de5f3f40SKevin Wolf 
12617c80ab3fSJes Sorensen     return qcow2_create2(filename, sectors, backing_file, backing_fmt, flags,
12626744cbabSKevin Wolf                          cluster_size, prealloc, options, version);
1263de5f3f40SKevin Wolf }
1264de5f3f40SKevin Wolf 
12657c80ab3fSJes Sorensen static int qcow2_make_empty(BlockDriverState *bs)
126620d97356SBlue Swirl {
126720d97356SBlue Swirl #if 0
126820d97356SBlue Swirl     /* XXX: not correct */
126920d97356SBlue Swirl     BDRVQcowState *s = bs->opaque;
127020d97356SBlue Swirl     uint32_t l1_length = s->l1_size * sizeof(uint64_t);
127120d97356SBlue Swirl     int ret;
127220d97356SBlue Swirl 
127320d97356SBlue Swirl     memset(s->l1_table, 0, l1_length);
127466f82ceeSKevin Wolf     if (bdrv_pwrite(bs->file, s->l1_table_offset, s->l1_table, l1_length) < 0)
127520d97356SBlue Swirl         return -1;
127666f82ceeSKevin Wolf     ret = bdrv_truncate(bs->file, s->l1_table_offset + l1_length);
127720d97356SBlue Swirl     if (ret < 0)
127820d97356SBlue Swirl         return ret;
127920d97356SBlue Swirl 
128020d97356SBlue Swirl     l2_cache_reset(bs);
128120d97356SBlue Swirl #endif
128220d97356SBlue Swirl     return 0;
128320d97356SBlue Swirl }
128420d97356SBlue Swirl 
1285621f0589SKevin Wolf static coroutine_fn int qcow2_co_write_zeroes(BlockDriverState *bs,
1286621f0589SKevin Wolf     int64_t sector_num, int nb_sectors)
1287621f0589SKevin Wolf {
1288621f0589SKevin Wolf     int ret;
1289621f0589SKevin Wolf     BDRVQcowState *s = bs->opaque;
1290621f0589SKevin Wolf 
1291621f0589SKevin Wolf     /* Emulate misaligned zero writes */
1292621f0589SKevin Wolf     if (sector_num % s->cluster_sectors || nb_sectors % s->cluster_sectors) {
1293621f0589SKevin Wolf         return -ENOTSUP;
1294621f0589SKevin Wolf     }
1295621f0589SKevin Wolf 
1296621f0589SKevin Wolf     /* Whatever is left can use real zero clusters */
1297621f0589SKevin Wolf     qemu_co_mutex_lock(&s->lock);
1298621f0589SKevin Wolf     ret = qcow2_zero_clusters(bs, sector_num << BDRV_SECTOR_BITS,
1299621f0589SKevin Wolf         nb_sectors);
1300621f0589SKevin Wolf     qemu_co_mutex_unlock(&s->lock);
1301621f0589SKevin Wolf 
1302621f0589SKevin Wolf     return ret;
1303621f0589SKevin Wolf }
1304621f0589SKevin Wolf 
13056db39ae2SPaolo Bonzini static coroutine_fn int qcow2_co_discard(BlockDriverState *bs,
13066db39ae2SPaolo Bonzini     int64_t sector_num, int nb_sectors)
13075ea929e3SKevin Wolf {
13086db39ae2SPaolo Bonzini     int ret;
13096db39ae2SPaolo Bonzini     BDRVQcowState *s = bs->opaque;
13106db39ae2SPaolo Bonzini 
13116db39ae2SPaolo Bonzini     qemu_co_mutex_lock(&s->lock);
13126db39ae2SPaolo Bonzini     ret = qcow2_discard_clusters(bs, sector_num << BDRV_SECTOR_BITS,
13135ea929e3SKevin Wolf         nb_sectors);
13146db39ae2SPaolo Bonzini     qemu_co_mutex_unlock(&s->lock);
13156db39ae2SPaolo Bonzini     return ret;
13165ea929e3SKevin Wolf }
13175ea929e3SKevin Wolf 
1318419b19d9SStefan Hajnoczi static int qcow2_truncate(BlockDriverState *bs, int64_t offset)
1319419b19d9SStefan Hajnoczi {
1320419b19d9SStefan Hajnoczi     BDRVQcowState *s = bs->opaque;
1321419b19d9SStefan Hajnoczi     int ret, new_l1_size;
1322419b19d9SStefan Hajnoczi 
1323419b19d9SStefan Hajnoczi     if (offset & 511) {
1324259b2173SKevin Wolf         error_report("The new size must be a multiple of 512");
1325419b19d9SStefan Hajnoczi         return -EINVAL;
1326419b19d9SStefan Hajnoczi     }
1327419b19d9SStefan Hajnoczi 
1328419b19d9SStefan Hajnoczi     /* cannot proceed if image has snapshots */
1329419b19d9SStefan Hajnoczi     if (s->nb_snapshots) {
1330259b2173SKevin Wolf         error_report("Can't resize an image which has snapshots");
1331419b19d9SStefan Hajnoczi         return -ENOTSUP;
1332419b19d9SStefan Hajnoczi     }
1333419b19d9SStefan Hajnoczi 
1334419b19d9SStefan Hajnoczi     /* shrinking is currently not supported */
1335419b19d9SStefan Hajnoczi     if (offset < bs->total_sectors * 512) {
1336259b2173SKevin Wolf         error_report("qcow2 doesn't support shrinking images yet");
1337419b19d9SStefan Hajnoczi         return -ENOTSUP;
1338419b19d9SStefan Hajnoczi     }
1339419b19d9SStefan Hajnoczi 
1340419b19d9SStefan Hajnoczi     new_l1_size = size_to_l1(s, offset);
134172893756SStefan Hajnoczi     ret = qcow2_grow_l1_table(bs, new_l1_size, true);
1342419b19d9SStefan Hajnoczi     if (ret < 0) {
1343419b19d9SStefan Hajnoczi         return ret;
1344419b19d9SStefan Hajnoczi     }
1345419b19d9SStefan Hajnoczi 
1346419b19d9SStefan Hajnoczi     /* write updated header.size */
1347419b19d9SStefan Hajnoczi     offset = cpu_to_be64(offset);
13488b3b7206SKevin Wolf     ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, size),
1349419b19d9SStefan Hajnoczi                            &offset, sizeof(uint64_t));
1350419b19d9SStefan Hajnoczi     if (ret < 0) {
1351419b19d9SStefan Hajnoczi         return ret;
1352419b19d9SStefan Hajnoczi     }
1353419b19d9SStefan Hajnoczi 
1354419b19d9SStefan Hajnoczi     s->l1_vm_state_index = new_l1_size;
1355419b19d9SStefan Hajnoczi     return 0;
1356419b19d9SStefan Hajnoczi }
1357419b19d9SStefan Hajnoczi 
135820d97356SBlue Swirl /* XXX: put compressed sectors first, then all the cluster aligned
135920d97356SBlue Swirl    tables to avoid losing bytes in alignment */
13607c80ab3fSJes Sorensen static int qcow2_write_compressed(BlockDriverState *bs, int64_t sector_num,
136120d97356SBlue Swirl                                   const uint8_t *buf, int nb_sectors)
136220d97356SBlue Swirl {
136320d97356SBlue Swirl     BDRVQcowState *s = bs->opaque;
136420d97356SBlue Swirl     z_stream strm;
136520d97356SBlue Swirl     int ret, out_len;
136620d97356SBlue Swirl     uint8_t *out_buf;
136720d97356SBlue Swirl     uint64_t cluster_offset;
136820d97356SBlue Swirl 
136920d97356SBlue Swirl     if (nb_sectors == 0) {
137020d97356SBlue Swirl         /* align end of file to a sector boundary to ease reading with
137120d97356SBlue Swirl            sector based I/Os */
137266f82ceeSKevin Wolf         cluster_offset = bdrv_getlength(bs->file);
137320d97356SBlue Swirl         cluster_offset = (cluster_offset + 511) & ~511;
137466f82ceeSKevin Wolf         bdrv_truncate(bs->file, cluster_offset);
137520d97356SBlue Swirl         return 0;
137620d97356SBlue Swirl     }
137720d97356SBlue Swirl 
137820d97356SBlue Swirl     if (nb_sectors != s->cluster_sectors)
137920d97356SBlue Swirl         return -EINVAL;
138020d97356SBlue Swirl 
13817267c094SAnthony Liguori     out_buf = g_malloc(s->cluster_size + (s->cluster_size / 1000) + 128);
138220d97356SBlue Swirl 
138320d97356SBlue Swirl     /* best compression, small window, no zlib header */
138420d97356SBlue Swirl     memset(&strm, 0, sizeof(strm));
138520d97356SBlue Swirl     ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
138620d97356SBlue Swirl                        Z_DEFLATED, -12,
138720d97356SBlue Swirl                        9, Z_DEFAULT_STRATEGY);
138820d97356SBlue Swirl     if (ret != 0) {
13898f1efd00SKevin Wolf         ret = -EINVAL;
13908f1efd00SKevin Wolf         goto fail;
139120d97356SBlue Swirl     }
139220d97356SBlue Swirl 
139320d97356SBlue Swirl     strm.avail_in = s->cluster_size;
139420d97356SBlue Swirl     strm.next_in = (uint8_t *)buf;
139520d97356SBlue Swirl     strm.avail_out = s->cluster_size;
139620d97356SBlue Swirl     strm.next_out = out_buf;
139720d97356SBlue Swirl 
139820d97356SBlue Swirl     ret = deflate(&strm, Z_FINISH);
139920d97356SBlue Swirl     if (ret != Z_STREAM_END && ret != Z_OK) {
140020d97356SBlue Swirl         deflateEnd(&strm);
14018f1efd00SKevin Wolf         ret = -EINVAL;
14028f1efd00SKevin Wolf         goto fail;
140320d97356SBlue Swirl     }
140420d97356SBlue Swirl     out_len = strm.next_out - out_buf;
140520d97356SBlue Swirl 
140620d97356SBlue Swirl     deflateEnd(&strm);
140720d97356SBlue Swirl 
140820d97356SBlue Swirl     if (ret != Z_STREAM_END || out_len >= s->cluster_size) {
140920d97356SBlue Swirl         /* could not compress: write normal cluster */
14108f1efd00SKevin Wolf         ret = bdrv_write(bs, sector_num, buf, s->cluster_sectors);
14118f1efd00SKevin Wolf         if (ret < 0) {
14128f1efd00SKevin Wolf             goto fail;
14138f1efd00SKevin Wolf         }
141420d97356SBlue Swirl     } else {
141520d97356SBlue Swirl         cluster_offset = qcow2_alloc_compressed_cluster_offset(bs,
141620d97356SBlue Swirl             sector_num << 9, out_len);
14178f1efd00SKevin Wolf         if (!cluster_offset) {
14188f1efd00SKevin Wolf             ret = -EIO;
14198f1efd00SKevin Wolf             goto fail;
14208f1efd00SKevin Wolf         }
142120d97356SBlue Swirl         cluster_offset &= s->cluster_offset_mask;
142266f82ceeSKevin Wolf         BLKDBG_EVENT(bs->file, BLKDBG_WRITE_COMPRESSED);
14238f1efd00SKevin Wolf         ret = bdrv_pwrite(bs->file, cluster_offset, out_buf, out_len);
14248f1efd00SKevin Wolf         if (ret < 0) {
14258f1efd00SKevin Wolf             goto fail;
142620d97356SBlue Swirl         }
142720d97356SBlue Swirl     }
142820d97356SBlue Swirl 
14298f1efd00SKevin Wolf     ret = 0;
14308f1efd00SKevin Wolf fail:
14317267c094SAnthony Liguori     g_free(out_buf);
14328f1efd00SKevin Wolf     return ret;
143320d97356SBlue Swirl }
143420d97356SBlue Swirl 
1435a968168cSDong Xu Wang static coroutine_fn int qcow2_co_flush_to_os(BlockDriverState *bs)
143620d97356SBlue Swirl {
143729c1a730SKevin Wolf     BDRVQcowState *s = bs->opaque;
143829c1a730SKevin Wolf     int ret;
143929c1a730SKevin Wolf 
14408b94ff85SPaolo Bonzini     qemu_co_mutex_lock(&s->lock);
144129c1a730SKevin Wolf     ret = qcow2_cache_flush(bs, s->l2_table_cache);
144229c1a730SKevin Wolf     if (ret < 0) {
1443c95de7e2SDong Xu Wang         qemu_co_mutex_unlock(&s->lock);
14448b94ff85SPaolo Bonzini         return ret;
144529c1a730SKevin Wolf     }
144629c1a730SKevin Wolf 
144729c1a730SKevin Wolf     ret = qcow2_cache_flush(bs, s->refcount_block_cache);
144829c1a730SKevin Wolf     if (ret < 0) {
1449c95de7e2SDong Xu Wang         qemu_co_mutex_unlock(&s->lock);
14508b94ff85SPaolo Bonzini         return ret;
145129c1a730SKevin Wolf     }
14528b94ff85SPaolo Bonzini     qemu_co_mutex_unlock(&s->lock);
145329c1a730SKevin Wolf 
1454eb489bb1SKevin Wolf     return 0;
1455eb489bb1SKevin Wolf }
1456eb489bb1SKevin Wolf 
14577c80ab3fSJes Sorensen static int64_t qcow2_vm_state_offset(BDRVQcowState *s)
145820d97356SBlue Swirl {
145920d97356SBlue Swirl 	return (int64_t)s->l1_vm_state_index << (s->cluster_bits + s->l2_bits);
146020d97356SBlue Swirl }
146120d97356SBlue Swirl 
14627c80ab3fSJes Sorensen static int qcow2_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
146320d97356SBlue Swirl {
146420d97356SBlue Swirl     BDRVQcowState *s = bs->opaque;
146520d97356SBlue Swirl     bdi->cluster_size = s->cluster_size;
14667c80ab3fSJes Sorensen     bdi->vm_state_offset = qcow2_vm_state_offset(s);
146720d97356SBlue Swirl     return 0;
146820d97356SBlue Swirl }
146920d97356SBlue Swirl 
147020d97356SBlue Swirl 
14714534ff54SKevin Wolf static int qcow2_check(BlockDriverState *bs, BdrvCheckResult *result,
14724534ff54SKevin Wolf                        BdrvCheckMode fix)
147320d97356SBlue Swirl {
1474166acf54SKevin Wolf     return qcow2_check_refcounts(bs, result, fix);
147520d97356SBlue Swirl }
147620d97356SBlue Swirl 
147720d97356SBlue Swirl #if 0
147820d97356SBlue Swirl static void dump_refcounts(BlockDriverState *bs)
147920d97356SBlue Swirl {
148020d97356SBlue Swirl     BDRVQcowState *s = bs->opaque;
148120d97356SBlue Swirl     int64_t nb_clusters, k, k1, size;
148220d97356SBlue Swirl     int refcount;
148320d97356SBlue Swirl 
148466f82ceeSKevin Wolf     size = bdrv_getlength(bs->file);
148520d97356SBlue Swirl     nb_clusters = size_to_clusters(s, size);
148620d97356SBlue Swirl     for(k = 0; k < nb_clusters;) {
148720d97356SBlue Swirl         k1 = k;
148820d97356SBlue Swirl         refcount = get_refcount(bs, k);
148920d97356SBlue Swirl         k++;
149020d97356SBlue Swirl         while (k < nb_clusters && get_refcount(bs, k) == refcount)
149120d97356SBlue Swirl             k++;
14920bfcd599SBlue Swirl         printf("%" PRId64 ": refcount=%d nb=%" PRId64 "\n", k, refcount,
14930bfcd599SBlue Swirl                k - k1);
149420d97356SBlue Swirl     }
149520d97356SBlue Swirl }
149620d97356SBlue Swirl #endif
149720d97356SBlue Swirl 
14987c80ab3fSJes Sorensen static int qcow2_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
149920d97356SBlue Swirl                               int64_t pos, int size)
150020d97356SBlue Swirl {
150120d97356SBlue Swirl     BDRVQcowState *s = bs->opaque;
150220d97356SBlue Swirl     int growable = bs->growable;
150320d97356SBlue Swirl     int ret;
150420d97356SBlue Swirl 
150566f82ceeSKevin Wolf     BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_SAVE);
150620d97356SBlue Swirl     bs->growable = 1;
15077c80ab3fSJes Sorensen     ret = bdrv_pwrite(bs, qcow2_vm_state_offset(s) + pos, buf, size);
150820d97356SBlue Swirl     bs->growable = growable;
150920d97356SBlue Swirl 
151020d97356SBlue Swirl     return ret;
151120d97356SBlue Swirl }
151220d97356SBlue Swirl 
15137c80ab3fSJes Sorensen static int qcow2_load_vmstate(BlockDriverState *bs, uint8_t *buf,
151420d97356SBlue Swirl                               int64_t pos, int size)
151520d97356SBlue Swirl {
151620d97356SBlue Swirl     BDRVQcowState *s = bs->opaque;
151720d97356SBlue Swirl     int growable = bs->growable;
151820d97356SBlue Swirl     int ret;
151920d97356SBlue Swirl 
152066f82ceeSKevin Wolf     BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_LOAD);
152120d97356SBlue Swirl     bs->growable = 1;
15227c80ab3fSJes Sorensen     ret = bdrv_pread(bs, qcow2_vm_state_offset(s) + pos, buf, size);
152320d97356SBlue Swirl     bs->growable = growable;
152420d97356SBlue Swirl 
152520d97356SBlue Swirl     return ret;
152620d97356SBlue Swirl }
152720d97356SBlue Swirl 
15287c80ab3fSJes Sorensen static QEMUOptionParameter qcow2_create_options[] = {
152920d97356SBlue Swirl     {
153020d97356SBlue Swirl         .name = BLOCK_OPT_SIZE,
153120d97356SBlue Swirl         .type = OPT_SIZE,
153220d97356SBlue Swirl         .help = "Virtual disk size"
153320d97356SBlue Swirl     },
153420d97356SBlue Swirl     {
15356744cbabSKevin Wolf         .name = BLOCK_OPT_COMPAT_LEVEL,
15366744cbabSKevin Wolf         .type = OPT_STRING,
15376744cbabSKevin Wolf         .help = "Compatibility level (0.10 or 1.1)"
15386744cbabSKevin Wolf     },
15396744cbabSKevin Wolf     {
154020d97356SBlue Swirl         .name = BLOCK_OPT_BACKING_FILE,
154120d97356SBlue Swirl         .type = OPT_STRING,
154220d97356SBlue Swirl         .help = "File name of a base image"
154320d97356SBlue Swirl     },
154420d97356SBlue Swirl     {
154520d97356SBlue Swirl         .name = BLOCK_OPT_BACKING_FMT,
154620d97356SBlue Swirl         .type = OPT_STRING,
154720d97356SBlue Swirl         .help = "Image format of the base image"
154820d97356SBlue Swirl     },
154920d97356SBlue Swirl     {
155020d97356SBlue Swirl         .name = BLOCK_OPT_ENCRYPT,
155120d97356SBlue Swirl         .type = OPT_FLAG,
155220d97356SBlue Swirl         .help = "Encrypt the image"
155320d97356SBlue Swirl     },
155420d97356SBlue Swirl     {
155520d97356SBlue Swirl         .name = BLOCK_OPT_CLUSTER_SIZE,
155620d97356SBlue Swirl         .type = OPT_SIZE,
155799cce9faSKevin Wolf         .help = "qcow2 cluster size",
155899cce9faSKevin Wolf         .value = { .n = DEFAULT_CLUSTER_SIZE },
155920d97356SBlue Swirl     },
156020d97356SBlue Swirl     {
156120d97356SBlue Swirl         .name = BLOCK_OPT_PREALLOC,
156220d97356SBlue Swirl         .type = OPT_STRING,
156320d97356SBlue Swirl         .help = "Preallocation mode (allowed values: off, metadata)"
156420d97356SBlue Swirl     },
156520d97356SBlue Swirl     { NULL }
156620d97356SBlue Swirl };
156720d97356SBlue Swirl 
156820d97356SBlue Swirl static BlockDriver bdrv_qcow2 = {
156920d97356SBlue Swirl     .format_name        = "qcow2",
157020d97356SBlue Swirl     .instance_size      = sizeof(BDRVQcowState),
15717c80ab3fSJes Sorensen     .bdrv_probe         = qcow2_probe,
15727c80ab3fSJes Sorensen     .bdrv_open          = qcow2_open,
15737c80ab3fSJes Sorensen     .bdrv_close         = qcow2_close,
15747c80ab3fSJes Sorensen     .bdrv_create        = qcow2_create,
1575f8a2e5e3SStefan Hajnoczi     .bdrv_co_is_allocated = qcow2_co_is_allocated,
15767c80ab3fSJes Sorensen     .bdrv_set_key       = qcow2_set_key,
15777c80ab3fSJes Sorensen     .bdrv_make_empty    = qcow2_make_empty,
157820d97356SBlue Swirl 
157968d100e9SKevin Wolf     .bdrv_co_readv          = qcow2_co_readv,
158068d100e9SKevin Wolf     .bdrv_co_writev         = qcow2_co_writev,
1581eb489bb1SKevin Wolf     .bdrv_co_flush_to_os    = qcow2_co_flush_to_os,
1582419b19d9SStefan Hajnoczi 
1583621f0589SKevin Wolf     .bdrv_co_write_zeroes   = qcow2_co_write_zeroes,
15846db39ae2SPaolo Bonzini     .bdrv_co_discard        = qcow2_co_discard,
1585419b19d9SStefan Hajnoczi     .bdrv_truncate          = qcow2_truncate,
15867c80ab3fSJes Sorensen     .bdrv_write_compressed  = qcow2_write_compressed,
158720d97356SBlue Swirl 
158820d97356SBlue Swirl     .bdrv_snapshot_create   = qcow2_snapshot_create,
158920d97356SBlue Swirl     .bdrv_snapshot_goto     = qcow2_snapshot_goto,
159020d97356SBlue Swirl     .bdrv_snapshot_delete   = qcow2_snapshot_delete,
159120d97356SBlue Swirl     .bdrv_snapshot_list     = qcow2_snapshot_list,
159251ef6727Sedison     .bdrv_snapshot_load_tmp     = qcow2_snapshot_load_tmp,
15937c80ab3fSJes Sorensen     .bdrv_get_info      = qcow2_get_info,
159420d97356SBlue Swirl 
15957c80ab3fSJes Sorensen     .bdrv_save_vmstate    = qcow2_save_vmstate,
15967c80ab3fSJes Sorensen     .bdrv_load_vmstate    = qcow2_load_vmstate,
159720d97356SBlue Swirl 
159820d97356SBlue Swirl     .bdrv_change_backing_file   = qcow2_change_backing_file,
159920d97356SBlue Swirl 
160006d9260fSAnthony Liguori     .bdrv_invalidate_cache      = qcow2_invalidate_cache,
160106d9260fSAnthony Liguori 
16027c80ab3fSJes Sorensen     .create_options = qcow2_create_options,
16037c80ab3fSJes Sorensen     .bdrv_check = qcow2_check,
160420d97356SBlue Swirl };
160520d97356SBlue Swirl 
16065efa9d5aSAnthony Liguori static void bdrv_qcow2_init(void)
16075efa9d5aSAnthony Liguori {
16085efa9d5aSAnthony Liguori     bdrv_register(&bdrv_qcow2);
16095efa9d5aSAnthony Liguori }
16105efa9d5aSAnthony Liguori 
16115efa9d5aSAnthony Liguori block_init(bdrv_qcow2_init);
1612