xref: /openbmc/qemu/block/qcow2.c (revision 01c22f2c)
1 /*
2  * Block driver for the QCOW version 2 format
3  *
4  * Copyright (c) 2004-2006 Fabrice Bellard
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to deal
8  * in the Software without restriction, including without limitation the rights
9  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10  * copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22  * THE SOFTWARE.
23  */
24 #include "qemu-common.h"
25 #include "block/block_int.h"
26 #include "qemu/module.h"
27 #include <zlib.h>
28 #include "qemu/aes.h"
29 #include "block/qcow2.h"
30 #include "qemu/error-report.h"
31 #include "qapi/qmp/qerror.h"
32 #include "qapi/qmp/qbool.h"
33 #include "trace.h"
34 
35 /*
36   Differences with QCOW:
37 
38   - Support for multiple incremental snapshots.
39   - Memory management by reference counts.
40   - Clusters which have a reference count of one have the bit
41     QCOW_OFLAG_COPIED to optimize write performance.
42   - Size of compressed clusters is stored in sectors to reduce bit usage
43     in the cluster offsets.
44   - Support for storing additional data (such as the VM state) in the
45     snapshots.
46   - If a backing store is used, the cluster size is not constrained
47     (could be backported to QCOW).
48   - L2 tables have always a size of one cluster.
49 */
50 
51 
52 typedef struct {
53     uint32_t magic;
54     uint32_t len;
55 } QEMU_PACKED QCowExtension;
56 
57 #define  QCOW2_EXT_MAGIC_END 0
58 #define  QCOW2_EXT_MAGIC_BACKING_FORMAT 0xE2792ACA
59 #define  QCOW2_EXT_MAGIC_FEATURE_TABLE 0x6803f857
60 
61 static int qcow2_probe(const uint8_t *buf, int buf_size, const char *filename)
62 {
63     const QCowHeader *cow_header = (const void *)buf;
64 
65     if (buf_size >= sizeof(QCowHeader) &&
66         be32_to_cpu(cow_header->magic) == QCOW_MAGIC &&
67         be32_to_cpu(cow_header->version) >= 2)
68         return 100;
69     else
70         return 0;
71 }
72 
73 
74 /*
75  * read qcow2 extension and fill bs
76  * start reading from start_offset
77  * finish reading upon magic of value 0 or when end_offset reached
78  * unknown magic is skipped (future extension this version knows nothing about)
79  * return 0 upon success, non-0 otherwise
80  */
81 static int qcow2_read_extensions(BlockDriverState *bs, uint64_t start_offset,
82                                  uint64_t end_offset, void **p_feature_table,
83                                  Error **errp)
84 {
85     BDRVQcowState *s = bs->opaque;
86     QCowExtension ext;
87     uint64_t offset;
88     int ret;
89 
90 #ifdef DEBUG_EXT
91     printf("qcow2_read_extensions: start=%ld end=%ld\n", start_offset, end_offset);
92 #endif
93     offset = start_offset;
94     while (offset < end_offset) {
95 
96 #ifdef DEBUG_EXT
97         /* Sanity check */
98         if (offset > s->cluster_size)
99             printf("qcow2_read_extension: suspicious offset %lu\n", offset);
100 
101         printf("attempting to read extended header in offset %lu\n", offset);
102 #endif
103 
104         ret = bdrv_pread(bs->file, offset, &ext, sizeof(ext));
105         if (ret < 0) {
106             error_setg_errno(errp, -ret, "qcow2_read_extension: ERROR: "
107                              "pread fail from offset %" PRIu64, offset);
108             return 1;
109         }
110         be32_to_cpus(&ext.magic);
111         be32_to_cpus(&ext.len);
112         offset += sizeof(ext);
113 #ifdef DEBUG_EXT
114         printf("ext.magic = 0x%x\n", ext.magic);
115 #endif
116         if (ext.len > end_offset - offset) {
117             error_setg(errp, "Header extension too large");
118             return -EINVAL;
119         }
120 
121         switch (ext.magic) {
122         case QCOW2_EXT_MAGIC_END:
123             return 0;
124 
125         case QCOW2_EXT_MAGIC_BACKING_FORMAT:
126             if (ext.len >= sizeof(bs->backing_format)) {
127                 error_setg(errp, "ERROR: ext_backing_format: len=%u too large"
128                            " (>=%zu)", ext.len, sizeof(bs->backing_format));
129                 return 2;
130             }
131             ret = bdrv_pread(bs->file, offset, bs->backing_format, ext.len);
132             if (ret < 0) {
133                 error_setg_errno(errp, -ret, "ERROR: ext_backing_format: "
134                                  "Could not read format name");
135                 return 3;
136             }
137             bs->backing_format[ext.len] = '\0';
138 #ifdef DEBUG_EXT
139             printf("Qcow2: Got format extension %s\n", bs->backing_format);
140 #endif
141             break;
142 
143         case QCOW2_EXT_MAGIC_FEATURE_TABLE:
144             if (p_feature_table != NULL) {
145                 void* feature_table = g_malloc0(ext.len + 2 * sizeof(Qcow2Feature));
146                 ret = bdrv_pread(bs->file, offset , feature_table, ext.len);
147                 if (ret < 0) {
148                     error_setg_errno(errp, -ret, "ERROR: ext_feature_table: "
149                                      "Could not read table");
150                     return ret;
151                 }
152 
153                 *p_feature_table = feature_table;
154             }
155             break;
156 
157         default:
158             /* unknown magic - save it in case we need to rewrite the header */
159             {
160                 Qcow2UnknownHeaderExtension *uext;
161 
162                 uext = g_malloc0(sizeof(*uext)  + ext.len);
163                 uext->magic = ext.magic;
164                 uext->len = ext.len;
165                 QLIST_INSERT_HEAD(&s->unknown_header_ext, uext, next);
166 
167                 ret = bdrv_pread(bs->file, offset , uext->data, uext->len);
168                 if (ret < 0) {
169                     error_setg_errno(errp, -ret, "ERROR: unknown extension: "
170                                      "Could not read data");
171                     return ret;
172                 }
173             }
174             break;
175         }
176 
177         offset += ((ext.len + 7) & ~7);
178     }
179 
180     return 0;
181 }
182 
183 static void cleanup_unknown_header_ext(BlockDriverState *bs)
184 {
185     BDRVQcowState *s = bs->opaque;
186     Qcow2UnknownHeaderExtension *uext, *next;
187 
188     QLIST_FOREACH_SAFE(uext, &s->unknown_header_ext, next, next) {
189         QLIST_REMOVE(uext, next);
190         g_free(uext);
191     }
192 }
193 
194 static void GCC_FMT_ATTR(3, 4) report_unsupported(BlockDriverState *bs,
195     Error **errp, const char *fmt, ...)
196 {
197     char msg[64];
198     va_list ap;
199 
200     va_start(ap, fmt);
201     vsnprintf(msg, sizeof(msg), fmt, ap);
202     va_end(ap);
203 
204     error_set(errp, QERR_UNKNOWN_BLOCK_FORMAT_FEATURE, bs->device_name, "qcow2",
205               msg);
206 }
207 
208 static void report_unsupported_feature(BlockDriverState *bs,
209     Error **errp, Qcow2Feature *table, uint64_t mask)
210 {
211     while (table && table->name[0] != '\0') {
212         if (table->type == QCOW2_FEAT_TYPE_INCOMPATIBLE) {
213             if (mask & (1 << table->bit)) {
214                 report_unsupported(bs, errp, "%.46s", table->name);
215                 mask &= ~(1 << table->bit);
216             }
217         }
218         table++;
219     }
220 
221     if (mask) {
222         report_unsupported(bs, errp, "Unknown incompatible feature: %" PRIx64,
223                            mask);
224     }
225 }
226 
227 /*
228  * Sets the dirty bit and flushes afterwards if necessary.
229  *
230  * The incompatible_features bit is only set if the image file header was
231  * updated successfully.  Therefore it is not required to check the return
232  * value of this function.
233  */
234 int qcow2_mark_dirty(BlockDriverState *bs)
235 {
236     BDRVQcowState *s = bs->opaque;
237     uint64_t val;
238     int ret;
239 
240     assert(s->qcow_version >= 3);
241 
242     if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
243         return 0; /* already dirty */
244     }
245 
246     val = cpu_to_be64(s->incompatible_features | QCOW2_INCOMPAT_DIRTY);
247     ret = bdrv_pwrite(bs->file, offsetof(QCowHeader, incompatible_features),
248                       &val, sizeof(val));
249     if (ret < 0) {
250         return ret;
251     }
252     ret = bdrv_flush(bs->file);
253     if (ret < 0) {
254         return ret;
255     }
256 
257     /* Only treat image as dirty if the header was updated successfully */
258     s->incompatible_features |= QCOW2_INCOMPAT_DIRTY;
259     return 0;
260 }
261 
262 /*
263  * Clears the dirty bit and flushes before if necessary.  Only call this
264  * function when there are no pending requests, it does not guard against
265  * concurrent requests dirtying the image.
266  */
267 static int qcow2_mark_clean(BlockDriverState *bs)
268 {
269     BDRVQcowState *s = bs->opaque;
270 
271     if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
272         int ret = bdrv_flush(bs);
273         if (ret < 0) {
274             return ret;
275         }
276 
277         s->incompatible_features &= ~QCOW2_INCOMPAT_DIRTY;
278         return qcow2_update_header(bs);
279     }
280     return 0;
281 }
282 
283 /*
284  * Marks the image as corrupt.
285  */
286 int qcow2_mark_corrupt(BlockDriverState *bs)
287 {
288     BDRVQcowState *s = bs->opaque;
289 
290     s->incompatible_features |= QCOW2_INCOMPAT_CORRUPT;
291     return qcow2_update_header(bs);
292 }
293 
294 /*
295  * Marks the image as consistent, i.e., unsets the corrupt bit, and flushes
296  * before if necessary.
297  */
298 int qcow2_mark_consistent(BlockDriverState *bs)
299 {
300     BDRVQcowState *s = bs->opaque;
301 
302     if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
303         int ret = bdrv_flush(bs);
304         if (ret < 0) {
305             return ret;
306         }
307 
308         s->incompatible_features &= ~QCOW2_INCOMPAT_CORRUPT;
309         return qcow2_update_header(bs);
310     }
311     return 0;
312 }
313 
314 static int qcow2_check(BlockDriverState *bs, BdrvCheckResult *result,
315                        BdrvCheckMode fix)
316 {
317     int ret = qcow2_check_refcounts(bs, result, fix);
318     if (ret < 0) {
319         return ret;
320     }
321 
322     if (fix && result->check_errors == 0 && result->corruptions == 0) {
323         ret = qcow2_mark_clean(bs);
324         if (ret < 0) {
325             return ret;
326         }
327         return qcow2_mark_consistent(bs);
328     }
329     return ret;
330 }
331 
332 static QemuOptsList qcow2_runtime_opts = {
333     .name = "qcow2",
334     .head = QTAILQ_HEAD_INITIALIZER(qcow2_runtime_opts.head),
335     .desc = {
336         {
337             .name = QCOW2_OPT_LAZY_REFCOUNTS,
338             .type = QEMU_OPT_BOOL,
339             .help = "Postpone refcount updates",
340         },
341         {
342             .name = QCOW2_OPT_DISCARD_REQUEST,
343             .type = QEMU_OPT_BOOL,
344             .help = "Pass guest discard requests to the layer below",
345         },
346         {
347             .name = QCOW2_OPT_DISCARD_SNAPSHOT,
348             .type = QEMU_OPT_BOOL,
349             .help = "Generate discard requests when snapshot related space "
350                     "is freed",
351         },
352         {
353             .name = QCOW2_OPT_DISCARD_OTHER,
354             .type = QEMU_OPT_BOOL,
355             .help = "Generate discard requests when other clusters are freed",
356         },
357         {
358             .name = QCOW2_OPT_OVERLAP,
359             .type = QEMU_OPT_STRING,
360             .help = "Selects which overlap checks to perform from a range of "
361                     "templates (none, constant, cached, all)",
362         },
363         {
364             .name = QCOW2_OPT_OVERLAP_MAIN_HEADER,
365             .type = QEMU_OPT_BOOL,
366             .help = "Check for unintended writes into the main qcow2 header",
367         },
368         {
369             .name = QCOW2_OPT_OVERLAP_ACTIVE_L1,
370             .type = QEMU_OPT_BOOL,
371             .help = "Check for unintended writes into the active L1 table",
372         },
373         {
374             .name = QCOW2_OPT_OVERLAP_ACTIVE_L2,
375             .type = QEMU_OPT_BOOL,
376             .help = "Check for unintended writes into an active L2 table",
377         },
378         {
379             .name = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
380             .type = QEMU_OPT_BOOL,
381             .help = "Check for unintended writes into the refcount table",
382         },
383         {
384             .name = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
385             .type = QEMU_OPT_BOOL,
386             .help = "Check for unintended writes into a refcount block",
387         },
388         {
389             .name = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
390             .type = QEMU_OPT_BOOL,
391             .help = "Check for unintended writes into the snapshot table",
392         },
393         {
394             .name = QCOW2_OPT_OVERLAP_INACTIVE_L1,
395             .type = QEMU_OPT_BOOL,
396             .help = "Check for unintended writes into an inactive L1 table",
397         },
398         {
399             .name = QCOW2_OPT_OVERLAP_INACTIVE_L2,
400             .type = QEMU_OPT_BOOL,
401             .help = "Check for unintended writes into an inactive L2 table",
402         },
403         { /* end of list */ }
404     },
405 };
406 
407 static const char *overlap_bool_option_names[QCOW2_OL_MAX_BITNR] = {
408     [QCOW2_OL_MAIN_HEADER_BITNR]    = QCOW2_OPT_OVERLAP_MAIN_HEADER,
409     [QCOW2_OL_ACTIVE_L1_BITNR]      = QCOW2_OPT_OVERLAP_ACTIVE_L1,
410     [QCOW2_OL_ACTIVE_L2_BITNR]      = QCOW2_OPT_OVERLAP_ACTIVE_L2,
411     [QCOW2_OL_REFCOUNT_TABLE_BITNR] = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE,
412     [QCOW2_OL_REFCOUNT_BLOCK_BITNR] = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK,
413     [QCOW2_OL_SNAPSHOT_TABLE_BITNR] = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE,
414     [QCOW2_OL_INACTIVE_L1_BITNR]    = QCOW2_OPT_OVERLAP_INACTIVE_L1,
415     [QCOW2_OL_INACTIVE_L2_BITNR]    = QCOW2_OPT_OVERLAP_INACTIVE_L2,
416 };
417 
418 static int qcow2_open(BlockDriverState *bs, QDict *options, int flags,
419                       Error **errp)
420 {
421     BDRVQcowState *s = bs->opaque;
422     int len, i, ret = 0;
423     QCowHeader header;
424     QemuOpts *opts;
425     Error *local_err = NULL;
426     uint64_t ext_end;
427     uint64_t l1_vm_state_index;
428     const char *opt_overlap_check;
429     int overlap_check_template = 0;
430 
431     ret = bdrv_pread(bs->file, 0, &header, sizeof(header));
432     if (ret < 0) {
433         error_setg_errno(errp, -ret, "Could not read qcow2 header");
434         goto fail;
435     }
436     be32_to_cpus(&header.magic);
437     be32_to_cpus(&header.version);
438     be64_to_cpus(&header.backing_file_offset);
439     be32_to_cpus(&header.backing_file_size);
440     be64_to_cpus(&header.size);
441     be32_to_cpus(&header.cluster_bits);
442     be32_to_cpus(&header.crypt_method);
443     be64_to_cpus(&header.l1_table_offset);
444     be32_to_cpus(&header.l1_size);
445     be64_to_cpus(&header.refcount_table_offset);
446     be32_to_cpus(&header.refcount_table_clusters);
447     be64_to_cpus(&header.snapshots_offset);
448     be32_to_cpus(&header.nb_snapshots);
449 
450     if (header.magic != QCOW_MAGIC) {
451         error_setg(errp, "Image is not in qcow2 format");
452         ret = -EINVAL;
453         goto fail;
454     }
455     if (header.version < 2 || header.version > 3) {
456         report_unsupported(bs, errp, "QCOW version %d", header.version);
457         ret = -ENOTSUP;
458         goto fail;
459     }
460 
461     s->qcow_version = header.version;
462 
463     /* Initialise version 3 header fields */
464     if (header.version == 2) {
465         header.incompatible_features    = 0;
466         header.compatible_features      = 0;
467         header.autoclear_features       = 0;
468         header.refcount_order           = 4;
469         header.header_length            = 72;
470     } else {
471         be64_to_cpus(&header.incompatible_features);
472         be64_to_cpus(&header.compatible_features);
473         be64_to_cpus(&header.autoclear_features);
474         be32_to_cpus(&header.refcount_order);
475         be32_to_cpus(&header.header_length);
476     }
477 
478     if (header.header_length > sizeof(header)) {
479         s->unknown_header_fields_size = header.header_length - sizeof(header);
480         s->unknown_header_fields = g_malloc(s->unknown_header_fields_size);
481         ret = bdrv_pread(bs->file, sizeof(header), s->unknown_header_fields,
482                          s->unknown_header_fields_size);
483         if (ret < 0) {
484             error_setg_errno(errp, -ret, "Could not read unknown qcow2 header "
485                              "fields");
486             goto fail;
487         }
488     }
489 
490     if (header.backing_file_offset) {
491         ext_end = header.backing_file_offset;
492     } else {
493         ext_end = 1 << header.cluster_bits;
494     }
495 
496     /* Handle feature bits */
497     s->incompatible_features    = header.incompatible_features;
498     s->compatible_features      = header.compatible_features;
499     s->autoclear_features       = header.autoclear_features;
500 
501     if (s->incompatible_features & ~QCOW2_INCOMPAT_MASK) {
502         void *feature_table = NULL;
503         qcow2_read_extensions(bs, header.header_length, ext_end,
504                               &feature_table, NULL);
505         report_unsupported_feature(bs, errp, feature_table,
506                                    s->incompatible_features &
507                                    ~QCOW2_INCOMPAT_MASK);
508         ret = -ENOTSUP;
509         goto fail;
510     }
511 
512     if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
513         /* Corrupt images may not be written to unless they are being repaired
514          */
515         if ((flags & BDRV_O_RDWR) && !(flags & BDRV_O_CHECK)) {
516             error_setg(errp, "qcow2: Image is corrupt; cannot be opened "
517                        "read/write");
518             ret = -EACCES;
519             goto fail;
520         }
521     }
522 
523     /* Check support for various header values */
524     if (header.refcount_order != 4) {
525         report_unsupported(bs, errp, "%d bit reference counts",
526                            1 << header.refcount_order);
527         ret = -ENOTSUP;
528         goto fail;
529     }
530     s->refcount_order = header.refcount_order;
531 
532     if (header.cluster_bits < MIN_CLUSTER_BITS ||
533         header.cluster_bits > MAX_CLUSTER_BITS) {
534         error_setg(errp, "Unsupported cluster size: 2^%i", header.cluster_bits);
535         ret = -EINVAL;
536         goto fail;
537     }
538     if (header.crypt_method > QCOW_CRYPT_AES) {
539         error_setg(errp, "Unsupported encryption method: %i",
540                    header.crypt_method);
541         ret = -EINVAL;
542         goto fail;
543     }
544     s->crypt_method_header = header.crypt_method;
545     if (s->crypt_method_header) {
546         bs->encrypted = 1;
547     }
548     s->cluster_bits = header.cluster_bits;
549     s->cluster_size = 1 << s->cluster_bits;
550     s->cluster_sectors = 1 << (s->cluster_bits - 9);
551     s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */
552     s->l2_size = 1 << s->l2_bits;
553     bs->total_sectors = header.size / 512;
554     s->csize_shift = (62 - (s->cluster_bits - 8));
555     s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;
556     s->cluster_offset_mask = (1LL << s->csize_shift) - 1;
557     s->refcount_table_offset = header.refcount_table_offset;
558     s->refcount_table_size =
559         header.refcount_table_clusters << (s->cluster_bits - 3);
560 
561     s->snapshots_offset = header.snapshots_offset;
562     s->nb_snapshots = header.nb_snapshots;
563 
564     /* read the level 1 table */
565     s->l1_size = header.l1_size;
566 
567     l1_vm_state_index = size_to_l1(s, header.size);
568     if (l1_vm_state_index > INT_MAX) {
569         error_setg(errp, "Image is too big");
570         ret = -EFBIG;
571         goto fail;
572     }
573     s->l1_vm_state_index = l1_vm_state_index;
574 
575     /* the L1 table must contain at least enough entries to put
576        header.size bytes */
577     if (s->l1_size < s->l1_vm_state_index) {
578         error_setg(errp, "L1 table is too small");
579         ret = -EINVAL;
580         goto fail;
581     }
582     s->l1_table_offset = header.l1_table_offset;
583     if (s->l1_size > 0) {
584         s->l1_table = g_malloc0(
585             align_offset(s->l1_size * sizeof(uint64_t), 512));
586         ret = bdrv_pread(bs->file, s->l1_table_offset, s->l1_table,
587                          s->l1_size * sizeof(uint64_t));
588         if (ret < 0) {
589             error_setg_errno(errp, -ret, "Could not read L1 table");
590             goto fail;
591         }
592         for(i = 0;i < s->l1_size; i++) {
593             be64_to_cpus(&s->l1_table[i]);
594         }
595     }
596 
597     /* alloc L2 table/refcount block cache */
598     s->l2_table_cache = qcow2_cache_create(bs, L2_CACHE_SIZE);
599     s->refcount_block_cache = qcow2_cache_create(bs, REFCOUNT_CACHE_SIZE);
600 
601     s->cluster_cache = g_malloc(s->cluster_size);
602     /* one more sector for decompressed data alignment */
603     s->cluster_data = qemu_blockalign(bs, QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size
604                                   + 512);
605     s->cluster_cache_offset = -1;
606     s->flags = flags;
607 
608     ret = qcow2_refcount_init(bs);
609     if (ret != 0) {
610         error_setg_errno(errp, -ret, "Could not initialize refcount handling");
611         goto fail;
612     }
613 
614     QLIST_INIT(&s->cluster_allocs);
615     QTAILQ_INIT(&s->discards);
616 
617     /* read qcow2 extensions */
618     if (qcow2_read_extensions(bs, header.header_length, ext_end, NULL,
619         &local_err)) {
620         error_propagate(errp, local_err);
621         ret = -EINVAL;
622         goto fail;
623     }
624 
625     /* read the backing file name */
626     if (header.backing_file_offset != 0) {
627         len = header.backing_file_size;
628         if (len > 1023) {
629             len = 1023;
630         }
631         ret = bdrv_pread(bs->file, header.backing_file_offset,
632                          bs->backing_file, len);
633         if (ret < 0) {
634             error_setg_errno(errp, -ret, "Could not read backing file name");
635             goto fail;
636         }
637         bs->backing_file[len] = '\0';
638     }
639 
640     ret = qcow2_read_snapshots(bs);
641     if (ret < 0) {
642         error_setg_errno(errp, -ret, "Could not read snapshots");
643         goto fail;
644     }
645 
646     /* Clear unknown autoclear feature bits */
647     if (!bs->read_only && !(flags & BDRV_O_INCOMING) && s->autoclear_features) {
648         s->autoclear_features = 0;
649         ret = qcow2_update_header(bs);
650         if (ret < 0) {
651             error_setg_errno(errp, -ret, "Could not update qcow2 header");
652             goto fail;
653         }
654     }
655 
656     /* Initialise locks */
657     qemu_co_mutex_init(&s->lock);
658 
659     /* Repair image if dirty */
660     if (!(flags & (BDRV_O_CHECK | BDRV_O_INCOMING)) && !bs->read_only &&
661         (s->incompatible_features & QCOW2_INCOMPAT_DIRTY)) {
662         BdrvCheckResult result = {0};
663 
664         ret = qcow2_check(bs, &result, BDRV_FIX_ERRORS);
665         if (ret < 0) {
666             error_setg_errno(errp, -ret, "Could not repair dirty image");
667             goto fail;
668         }
669     }
670 
671     /* Enable lazy_refcounts according to image and command line options */
672     opts = qemu_opts_create(&qcow2_runtime_opts, NULL, 0, &error_abort);
673     qemu_opts_absorb_qdict(opts, options, &local_err);
674     if (local_err) {
675         error_propagate(errp, local_err);
676         ret = -EINVAL;
677         goto fail;
678     }
679 
680     s->use_lazy_refcounts = qemu_opt_get_bool(opts, QCOW2_OPT_LAZY_REFCOUNTS,
681         (s->compatible_features & QCOW2_COMPAT_LAZY_REFCOUNTS));
682 
683     s->discard_passthrough[QCOW2_DISCARD_NEVER] = false;
684     s->discard_passthrough[QCOW2_DISCARD_ALWAYS] = true;
685     s->discard_passthrough[QCOW2_DISCARD_REQUEST] =
686         qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_REQUEST,
687                           flags & BDRV_O_UNMAP);
688     s->discard_passthrough[QCOW2_DISCARD_SNAPSHOT] =
689         qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_SNAPSHOT, true);
690     s->discard_passthrough[QCOW2_DISCARD_OTHER] =
691         qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_OTHER, false);
692 
693     opt_overlap_check = qemu_opt_get(opts, "overlap-check") ?: "cached";
694     if (!strcmp(opt_overlap_check, "none")) {
695         overlap_check_template = 0;
696     } else if (!strcmp(opt_overlap_check, "constant")) {
697         overlap_check_template = QCOW2_OL_CONSTANT;
698     } else if (!strcmp(opt_overlap_check, "cached")) {
699         overlap_check_template = QCOW2_OL_CACHED;
700     } else if (!strcmp(opt_overlap_check, "all")) {
701         overlap_check_template = QCOW2_OL_ALL;
702     } else {
703         error_setg(errp, "Unsupported value '%s' for qcow2 option "
704                    "'overlap-check'. Allowed are either of the following: "
705                    "none, constant, cached, all", opt_overlap_check);
706         qemu_opts_del(opts);
707         ret = -EINVAL;
708         goto fail;
709     }
710 
711     s->overlap_check = 0;
712     for (i = 0; i < QCOW2_OL_MAX_BITNR; i++) {
713         /* overlap-check defines a template bitmask, but every flag may be
714          * overwritten through the associated boolean option */
715         s->overlap_check |=
716             qemu_opt_get_bool(opts, overlap_bool_option_names[i],
717                               overlap_check_template & (1 << i)) << i;
718     }
719 
720     qemu_opts_del(opts);
721 
722     if (s->use_lazy_refcounts && s->qcow_version < 3) {
723         error_setg(errp, "Lazy refcounts require a qcow2 image with at least "
724                    "qemu 1.1 compatibility level");
725         ret = -EINVAL;
726         goto fail;
727     }
728 
729 #ifdef DEBUG_ALLOC
730     {
731         BdrvCheckResult result = {0};
732         qcow2_check_refcounts(bs, &result, 0);
733     }
734 #endif
735     return ret;
736 
737  fail:
738     g_free(s->unknown_header_fields);
739     cleanup_unknown_header_ext(bs);
740     qcow2_free_snapshots(bs);
741     qcow2_refcount_close(bs);
742     g_free(s->l1_table);
743     /* else pre-write overlap checks in cache_destroy may crash */
744     s->l1_table = NULL;
745     if (s->l2_table_cache) {
746         qcow2_cache_destroy(bs, s->l2_table_cache);
747     }
748     g_free(s->cluster_cache);
749     qemu_vfree(s->cluster_data);
750     return ret;
751 }
752 
753 static int qcow2_refresh_limits(BlockDriverState *bs)
754 {
755     BDRVQcowState *s = bs->opaque;
756 
757     bs->bl.write_zeroes_alignment = s->cluster_sectors;
758 
759     return 0;
760 }
761 
762 static int qcow2_set_key(BlockDriverState *bs, const char *key)
763 {
764     BDRVQcowState *s = bs->opaque;
765     uint8_t keybuf[16];
766     int len, i;
767 
768     memset(keybuf, 0, 16);
769     len = strlen(key);
770     if (len > 16)
771         len = 16;
772     /* XXX: we could compress the chars to 7 bits to increase
773        entropy */
774     for(i = 0;i < len;i++) {
775         keybuf[i] = key[i];
776     }
777     s->crypt_method = s->crypt_method_header;
778 
779     if (AES_set_encrypt_key(keybuf, 128, &s->aes_encrypt_key) != 0)
780         return -1;
781     if (AES_set_decrypt_key(keybuf, 128, &s->aes_decrypt_key) != 0)
782         return -1;
783 #if 0
784     /* test */
785     {
786         uint8_t in[16];
787         uint8_t out[16];
788         uint8_t tmp[16];
789         for(i=0;i<16;i++)
790             in[i] = i;
791         AES_encrypt(in, tmp, &s->aes_encrypt_key);
792         AES_decrypt(tmp, out, &s->aes_decrypt_key);
793         for(i = 0; i < 16; i++)
794             printf(" %02x", tmp[i]);
795         printf("\n");
796         for(i = 0; i < 16; i++)
797             printf(" %02x", out[i]);
798         printf("\n");
799     }
800 #endif
801     return 0;
802 }
803 
804 /* We have nothing to do for QCOW2 reopen, stubs just return
805  * success */
806 static int qcow2_reopen_prepare(BDRVReopenState *state,
807                                 BlockReopenQueue *queue, Error **errp)
808 {
809     return 0;
810 }
811 
812 static int64_t coroutine_fn qcow2_co_get_block_status(BlockDriverState *bs,
813         int64_t sector_num, int nb_sectors, int *pnum)
814 {
815     BDRVQcowState *s = bs->opaque;
816     uint64_t cluster_offset;
817     int index_in_cluster, ret;
818     int64_t status = 0;
819 
820     *pnum = nb_sectors;
821     qemu_co_mutex_lock(&s->lock);
822     ret = qcow2_get_cluster_offset(bs, sector_num << 9, pnum, &cluster_offset);
823     qemu_co_mutex_unlock(&s->lock);
824     if (ret < 0) {
825         return ret;
826     }
827 
828     if (cluster_offset != 0 && ret != QCOW2_CLUSTER_COMPRESSED &&
829         !s->crypt_method) {
830         index_in_cluster = sector_num & (s->cluster_sectors - 1);
831         cluster_offset |= (index_in_cluster << BDRV_SECTOR_BITS);
832         status |= BDRV_BLOCK_OFFSET_VALID | cluster_offset;
833     }
834     if (ret == QCOW2_CLUSTER_ZERO) {
835         status |= BDRV_BLOCK_ZERO;
836     } else if (ret != QCOW2_CLUSTER_UNALLOCATED) {
837         status |= BDRV_BLOCK_DATA;
838     }
839     return status;
840 }
841 
842 /* handle reading after the end of the backing file */
843 int qcow2_backing_read1(BlockDriverState *bs, QEMUIOVector *qiov,
844                   int64_t sector_num, int nb_sectors)
845 {
846     int n1;
847     if ((sector_num + nb_sectors) <= bs->total_sectors)
848         return nb_sectors;
849     if (sector_num >= bs->total_sectors)
850         n1 = 0;
851     else
852         n1 = bs->total_sectors - sector_num;
853 
854     qemu_iovec_memset(qiov, 512 * n1, 0, 512 * (nb_sectors - n1));
855 
856     return n1;
857 }
858 
859 static coroutine_fn int qcow2_co_readv(BlockDriverState *bs, int64_t sector_num,
860                           int remaining_sectors, QEMUIOVector *qiov)
861 {
862     BDRVQcowState *s = bs->opaque;
863     int index_in_cluster, n1;
864     int ret;
865     int cur_nr_sectors; /* number of sectors in current iteration */
866     uint64_t cluster_offset = 0;
867     uint64_t bytes_done = 0;
868     QEMUIOVector hd_qiov;
869     uint8_t *cluster_data = NULL;
870 
871     qemu_iovec_init(&hd_qiov, qiov->niov);
872 
873     qemu_co_mutex_lock(&s->lock);
874 
875     while (remaining_sectors != 0) {
876 
877         /* prepare next request */
878         cur_nr_sectors = remaining_sectors;
879         if (s->crypt_method) {
880             cur_nr_sectors = MIN(cur_nr_sectors,
881                 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors);
882         }
883 
884         ret = qcow2_get_cluster_offset(bs, sector_num << 9,
885             &cur_nr_sectors, &cluster_offset);
886         if (ret < 0) {
887             goto fail;
888         }
889 
890         index_in_cluster = sector_num & (s->cluster_sectors - 1);
891 
892         qemu_iovec_reset(&hd_qiov);
893         qemu_iovec_concat(&hd_qiov, qiov, bytes_done,
894             cur_nr_sectors * 512);
895 
896         switch (ret) {
897         case QCOW2_CLUSTER_UNALLOCATED:
898 
899             if (bs->backing_hd) {
900                 /* read from the base image */
901                 n1 = qcow2_backing_read1(bs->backing_hd, &hd_qiov,
902                     sector_num, cur_nr_sectors);
903                 if (n1 > 0) {
904                     BLKDBG_EVENT(bs->file, BLKDBG_READ_BACKING_AIO);
905                     qemu_co_mutex_unlock(&s->lock);
906                     ret = bdrv_co_readv(bs->backing_hd, sector_num,
907                                         n1, &hd_qiov);
908                     qemu_co_mutex_lock(&s->lock);
909                     if (ret < 0) {
910                         goto fail;
911                     }
912                 }
913             } else {
914                 /* Note: in this case, no need to wait */
915                 qemu_iovec_memset(&hd_qiov, 0, 0, 512 * cur_nr_sectors);
916             }
917             break;
918 
919         case QCOW2_CLUSTER_ZERO:
920             qemu_iovec_memset(&hd_qiov, 0, 0, 512 * cur_nr_sectors);
921             break;
922 
923         case QCOW2_CLUSTER_COMPRESSED:
924             /* add AIO support for compressed blocks ? */
925             ret = qcow2_decompress_cluster(bs, cluster_offset);
926             if (ret < 0) {
927                 goto fail;
928             }
929 
930             qemu_iovec_from_buf(&hd_qiov, 0,
931                 s->cluster_cache + index_in_cluster * 512,
932                 512 * cur_nr_sectors);
933             break;
934 
935         case QCOW2_CLUSTER_NORMAL:
936             if ((cluster_offset & 511) != 0) {
937                 ret = -EIO;
938                 goto fail;
939             }
940 
941             if (s->crypt_method) {
942                 /*
943                  * For encrypted images, read everything into a temporary
944                  * contiguous buffer on which the AES functions can work.
945                  */
946                 if (!cluster_data) {
947                     cluster_data =
948                         qemu_blockalign(bs, QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
949                 }
950 
951                 assert(cur_nr_sectors <=
952                     QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors);
953                 qemu_iovec_reset(&hd_qiov);
954                 qemu_iovec_add(&hd_qiov, cluster_data,
955                     512 * cur_nr_sectors);
956             }
957 
958             BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);
959             qemu_co_mutex_unlock(&s->lock);
960             ret = bdrv_co_readv(bs->file,
961                                 (cluster_offset >> 9) + index_in_cluster,
962                                 cur_nr_sectors, &hd_qiov);
963             qemu_co_mutex_lock(&s->lock);
964             if (ret < 0) {
965                 goto fail;
966             }
967             if (s->crypt_method) {
968                 qcow2_encrypt_sectors(s, sector_num,  cluster_data,
969                     cluster_data, cur_nr_sectors, 0, &s->aes_decrypt_key);
970                 qemu_iovec_from_buf(qiov, bytes_done,
971                     cluster_data, 512 * cur_nr_sectors);
972             }
973             break;
974 
975         default:
976             g_assert_not_reached();
977             ret = -EIO;
978             goto fail;
979         }
980 
981         remaining_sectors -= cur_nr_sectors;
982         sector_num += cur_nr_sectors;
983         bytes_done += cur_nr_sectors * 512;
984     }
985     ret = 0;
986 
987 fail:
988     qemu_co_mutex_unlock(&s->lock);
989 
990     qemu_iovec_destroy(&hd_qiov);
991     qemu_vfree(cluster_data);
992 
993     return ret;
994 }
995 
996 static coroutine_fn int qcow2_co_writev(BlockDriverState *bs,
997                            int64_t sector_num,
998                            int remaining_sectors,
999                            QEMUIOVector *qiov)
1000 {
1001     BDRVQcowState *s = bs->opaque;
1002     int index_in_cluster;
1003     int ret;
1004     int cur_nr_sectors; /* number of sectors in current iteration */
1005     uint64_t cluster_offset;
1006     QEMUIOVector hd_qiov;
1007     uint64_t bytes_done = 0;
1008     uint8_t *cluster_data = NULL;
1009     QCowL2Meta *l2meta = NULL;
1010 
1011     trace_qcow2_writev_start_req(qemu_coroutine_self(), sector_num,
1012                                  remaining_sectors);
1013 
1014     qemu_iovec_init(&hd_qiov, qiov->niov);
1015 
1016     s->cluster_cache_offset = -1; /* disable compressed cache */
1017 
1018     qemu_co_mutex_lock(&s->lock);
1019 
1020     while (remaining_sectors != 0) {
1021 
1022         l2meta = NULL;
1023 
1024         trace_qcow2_writev_start_part(qemu_coroutine_self());
1025         index_in_cluster = sector_num & (s->cluster_sectors - 1);
1026         cur_nr_sectors = remaining_sectors;
1027         if (s->crypt_method &&
1028             cur_nr_sectors >
1029             QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors - index_in_cluster) {
1030             cur_nr_sectors =
1031                 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors - index_in_cluster;
1032         }
1033 
1034         ret = qcow2_alloc_cluster_offset(bs, sector_num << 9,
1035             &cur_nr_sectors, &cluster_offset, &l2meta);
1036         if (ret < 0) {
1037             goto fail;
1038         }
1039 
1040         assert((cluster_offset & 511) == 0);
1041 
1042         qemu_iovec_reset(&hd_qiov);
1043         qemu_iovec_concat(&hd_qiov, qiov, bytes_done,
1044             cur_nr_sectors * 512);
1045 
1046         if (s->crypt_method) {
1047             if (!cluster_data) {
1048                 cluster_data = qemu_blockalign(bs, QCOW_MAX_CRYPT_CLUSTERS *
1049                                                  s->cluster_size);
1050             }
1051 
1052             assert(hd_qiov.size <=
1053                    QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
1054             qemu_iovec_to_buf(&hd_qiov, 0, cluster_data, hd_qiov.size);
1055 
1056             qcow2_encrypt_sectors(s, sector_num, cluster_data,
1057                 cluster_data, cur_nr_sectors, 1, &s->aes_encrypt_key);
1058 
1059             qemu_iovec_reset(&hd_qiov);
1060             qemu_iovec_add(&hd_qiov, cluster_data,
1061                 cur_nr_sectors * 512);
1062         }
1063 
1064         ret = qcow2_pre_write_overlap_check(bs, 0,
1065                 cluster_offset + index_in_cluster * BDRV_SECTOR_SIZE,
1066                 cur_nr_sectors * BDRV_SECTOR_SIZE);
1067         if (ret < 0) {
1068             goto fail;
1069         }
1070 
1071         qemu_co_mutex_unlock(&s->lock);
1072         BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO);
1073         trace_qcow2_writev_data(qemu_coroutine_self(),
1074                                 (cluster_offset >> 9) + index_in_cluster);
1075         ret = bdrv_co_writev(bs->file,
1076                              (cluster_offset >> 9) + index_in_cluster,
1077                              cur_nr_sectors, &hd_qiov);
1078         qemu_co_mutex_lock(&s->lock);
1079         if (ret < 0) {
1080             goto fail;
1081         }
1082 
1083         while (l2meta != NULL) {
1084             QCowL2Meta *next;
1085 
1086             ret = qcow2_alloc_cluster_link_l2(bs, l2meta);
1087             if (ret < 0) {
1088                 goto fail;
1089             }
1090 
1091             /* Take the request off the list of running requests */
1092             if (l2meta->nb_clusters != 0) {
1093                 QLIST_REMOVE(l2meta, next_in_flight);
1094             }
1095 
1096             qemu_co_queue_restart_all(&l2meta->dependent_requests);
1097 
1098             next = l2meta->next;
1099             g_free(l2meta);
1100             l2meta = next;
1101         }
1102 
1103         remaining_sectors -= cur_nr_sectors;
1104         sector_num += cur_nr_sectors;
1105         bytes_done += cur_nr_sectors * 512;
1106         trace_qcow2_writev_done_part(qemu_coroutine_self(), cur_nr_sectors);
1107     }
1108     ret = 0;
1109 
1110 fail:
1111     qemu_co_mutex_unlock(&s->lock);
1112 
1113     while (l2meta != NULL) {
1114         QCowL2Meta *next;
1115 
1116         if (l2meta->nb_clusters != 0) {
1117             QLIST_REMOVE(l2meta, next_in_flight);
1118         }
1119         qemu_co_queue_restart_all(&l2meta->dependent_requests);
1120 
1121         next = l2meta->next;
1122         g_free(l2meta);
1123         l2meta = next;
1124     }
1125 
1126     qemu_iovec_destroy(&hd_qiov);
1127     qemu_vfree(cluster_data);
1128     trace_qcow2_writev_done_req(qemu_coroutine_self(), ret);
1129 
1130     return ret;
1131 }
1132 
1133 static void qcow2_close(BlockDriverState *bs)
1134 {
1135     BDRVQcowState *s = bs->opaque;
1136     g_free(s->l1_table);
1137     /* else pre-write overlap checks in cache_destroy may crash */
1138     s->l1_table = NULL;
1139 
1140     if (!(bs->open_flags & BDRV_O_INCOMING)) {
1141         qcow2_cache_flush(bs, s->l2_table_cache);
1142         qcow2_cache_flush(bs, s->refcount_block_cache);
1143 
1144         qcow2_mark_clean(bs);
1145     }
1146 
1147     qcow2_cache_destroy(bs, s->l2_table_cache);
1148     qcow2_cache_destroy(bs, s->refcount_block_cache);
1149 
1150     g_free(s->unknown_header_fields);
1151     cleanup_unknown_header_ext(bs);
1152 
1153     g_free(s->cluster_cache);
1154     qemu_vfree(s->cluster_data);
1155     qcow2_refcount_close(bs);
1156     qcow2_free_snapshots(bs);
1157 }
1158 
1159 static void qcow2_invalidate_cache(BlockDriverState *bs)
1160 {
1161     BDRVQcowState *s = bs->opaque;
1162     int flags = s->flags;
1163     AES_KEY aes_encrypt_key;
1164     AES_KEY aes_decrypt_key;
1165     uint32_t crypt_method = 0;
1166     QDict *options;
1167 
1168     /*
1169      * Backing files are read-only which makes all of their metadata immutable,
1170      * that means we don't have to worry about reopening them here.
1171      */
1172 
1173     if (s->crypt_method) {
1174         crypt_method = s->crypt_method;
1175         memcpy(&aes_encrypt_key, &s->aes_encrypt_key, sizeof(aes_encrypt_key));
1176         memcpy(&aes_decrypt_key, &s->aes_decrypt_key, sizeof(aes_decrypt_key));
1177     }
1178 
1179     qcow2_close(bs);
1180 
1181     bdrv_invalidate_cache(bs->file);
1182 
1183     memset(s, 0, sizeof(BDRVQcowState));
1184     options = qdict_clone_shallow(bs->options);
1185     qcow2_open(bs, options, flags, NULL);
1186 
1187     QDECREF(options);
1188 
1189     if (crypt_method) {
1190         s->crypt_method = crypt_method;
1191         memcpy(&s->aes_encrypt_key, &aes_encrypt_key, sizeof(aes_encrypt_key));
1192         memcpy(&s->aes_decrypt_key, &aes_decrypt_key, sizeof(aes_decrypt_key));
1193     }
1194 }
1195 
1196 static size_t header_ext_add(char *buf, uint32_t magic, const void *s,
1197     size_t len, size_t buflen)
1198 {
1199     QCowExtension *ext_backing_fmt = (QCowExtension*) buf;
1200     size_t ext_len = sizeof(QCowExtension) + ((len + 7) & ~7);
1201 
1202     if (buflen < ext_len) {
1203         return -ENOSPC;
1204     }
1205 
1206     *ext_backing_fmt = (QCowExtension) {
1207         .magic  = cpu_to_be32(magic),
1208         .len    = cpu_to_be32(len),
1209     };
1210     memcpy(buf + sizeof(QCowExtension), s, len);
1211 
1212     return ext_len;
1213 }
1214 
1215 /*
1216  * Updates the qcow2 header, including the variable length parts of it, i.e.
1217  * the backing file name and all extensions. qcow2 was not designed to allow
1218  * such changes, so if we run out of space (we can only use the first cluster)
1219  * this function may fail.
1220  *
1221  * Returns 0 on success, -errno in error cases.
1222  */
1223 int qcow2_update_header(BlockDriverState *bs)
1224 {
1225     BDRVQcowState *s = bs->opaque;
1226     QCowHeader *header;
1227     char *buf;
1228     size_t buflen = s->cluster_size;
1229     int ret;
1230     uint64_t total_size;
1231     uint32_t refcount_table_clusters;
1232     size_t header_length;
1233     Qcow2UnknownHeaderExtension *uext;
1234 
1235     buf = qemu_blockalign(bs, buflen);
1236 
1237     /* Header structure */
1238     header = (QCowHeader*) buf;
1239 
1240     if (buflen < sizeof(*header)) {
1241         ret = -ENOSPC;
1242         goto fail;
1243     }
1244 
1245     header_length = sizeof(*header) + s->unknown_header_fields_size;
1246     total_size = bs->total_sectors * BDRV_SECTOR_SIZE;
1247     refcount_table_clusters = s->refcount_table_size >> (s->cluster_bits - 3);
1248 
1249     *header = (QCowHeader) {
1250         /* Version 2 fields */
1251         .magic                  = cpu_to_be32(QCOW_MAGIC),
1252         .version                = cpu_to_be32(s->qcow_version),
1253         .backing_file_offset    = 0,
1254         .backing_file_size      = 0,
1255         .cluster_bits           = cpu_to_be32(s->cluster_bits),
1256         .size                   = cpu_to_be64(total_size),
1257         .crypt_method           = cpu_to_be32(s->crypt_method_header),
1258         .l1_size                = cpu_to_be32(s->l1_size),
1259         .l1_table_offset        = cpu_to_be64(s->l1_table_offset),
1260         .refcount_table_offset  = cpu_to_be64(s->refcount_table_offset),
1261         .refcount_table_clusters = cpu_to_be32(refcount_table_clusters),
1262         .nb_snapshots           = cpu_to_be32(s->nb_snapshots),
1263         .snapshots_offset       = cpu_to_be64(s->snapshots_offset),
1264 
1265         /* Version 3 fields */
1266         .incompatible_features  = cpu_to_be64(s->incompatible_features),
1267         .compatible_features    = cpu_to_be64(s->compatible_features),
1268         .autoclear_features     = cpu_to_be64(s->autoclear_features),
1269         .refcount_order         = cpu_to_be32(s->refcount_order),
1270         .header_length          = cpu_to_be32(header_length),
1271     };
1272 
1273     /* For older versions, write a shorter header */
1274     switch (s->qcow_version) {
1275     case 2:
1276         ret = offsetof(QCowHeader, incompatible_features);
1277         break;
1278     case 3:
1279         ret = sizeof(*header);
1280         break;
1281     default:
1282         ret = -EINVAL;
1283         goto fail;
1284     }
1285 
1286     buf += ret;
1287     buflen -= ret;
1288     memset(buf, 0, buflen);
1289 
1290     /* Preserve any unknown field in the header */
1291     if (s->unknown_header_fields_size) {
1292         if (buflen < s->unknown_header_fields_size) {
1293             ret = -ENOSPC;
1294             goto fail;
1295         }
1296 
1297         memcpy(buf, s->unknown_header_fields, s->unknown_header_fields_size);
1298         buf += s->unknown_header_fields_size;
1299         buflen -= s->unknown_header_fields_size;
1300     }
1301 
1302     /* Backing file format header extension */
1303     if (*bs->backing_format) {
1304         ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BACKING_FORMAT,
1305                              bs->backing_format, strlen(bs->backing_format),
1306                              buflen);
1307         if (ret < 0) {
1308             goto fail;
1309         }
1310 
1311         buf += ret;
1312         buflen -= ret;
1313     }
1314 
1315     /* Feature table */
1316     Qcow2Feature features[] = {
1317         {
1318             .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
1319             .bit  = QCOW2_INCOMPAT_DIRTY_BITNR,
1320             .name = "dirty bit",
1321         },
1322         {
1323             .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
1324             .bit  = QCOW2_INCOMPAT_CORRUPT_BITNR,
1325             .name = "corrupt bit",
1326         },
1327         {
1328             .type = QCOW2_FEAT_TYPE_COMPATIBLE,
1329             .bit  = QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR,
1330             .name = "lazy refcounts",
1331         },
1332     };
1333 
1334     ret = header_ext_add(buf, QCOW2_EXT_MAGIC_FEATURE_TABLE,
1335                          features, sizeof(features), buflen);
1336     if (ret < 0) {
1337         goto fail;
1338     }
1339     buf += ret;
1340     buflen -= ret;
1341 
1342     /* Keep unknown header extensions */
1343     QLIST_FOREACH(uext, &s->unknown_header_ext, next) {
1344         ret = header_ext_add(buf, uext->magic, uext->data, uext->len, buflen);
1345         if (ret < 0) {
1346             goto fail;
1347         }
1348 
1349         buf += ret;
1350         buflen -= ret;
1351     }
1352 
1353     /* End of header extensions */
1354     ret = header_ext_add(buf, QCOW2_EXT_MAGIC_END, NULL, 0, buflen);
1355     if (ret < 0) {
1356         goto fail;
1357     }
1358 
1359     buf += ret;
1360     buflen -= ret;
1361 
1362     /* Backing file name */
1363     if (*bs->backing_file) {
1364         size_t backing_file_len = strlen(bs->backing_file);
1365 
1366         if (buflen < backing_file_len) {
1367             ret = -ENOSPC;
1368             goto fail;
1369         }
1370 
1371         /* Using strncpy is ok here, since buf is not NUL-terminated. */
1372         strncpy(buf, bs->backing_file, buflen);
1373 
1374         header->backing_file_offset = cpu_to_be64(buf - ((char*) header));
1375         header->backing_file_size   = cpu_to_be32(backing_file_len);
1376     }
1377 
1378     /* Write the new header */
1379     ret = bdrv_pwrite(bs->file, 0, header, s->cluster_size);
1380     if (ret < 0) {
1381         goto fail;
1382     }
1383 
1384     ret = 0;
1385 fail:
1386     qemu_vfree(header);
1387     return ret;
1388 }
1389 
1390 static int qcow2_change_backing_file(BlockDriverState *bs,
1391     const char *backing_file, const char *backing_fmt)
1392 {
1393     pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
1394     pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
1395 
1396     return qcow2_update_header(bs);
1397 }
1398 
1399 static int preallocate(BlockDriverState *bs)
1400 {
1401     uint64_t nb_sectors;
1402     uint64_t offset;
1403     uint64_t host_offset = 0;
1404     int num;
1405     int ret;
1406     QCowL2Meta *meta;
1407 
1408     nb_sectors = bdrv_getlength(bs) >> BDRV_SECTOR_BITS;
1409     offset = 0;
1410 
1411     while (nb_sectors) {
1412         num = MIN(nb_sectors, INT_MAX >> BDRV_SECTOR_BITS);
1413         ret = qcow2_alloc_cluster_offset(bs, offset, &num,
1414                                          &host_offset, &meta);
1415         if (ret < 0) {
1416             return ret;
1417         }
1418 
1419         if (meta != NULL) {
1420             ret = qcow2_alloc_cluster_link_l2(bs, meta);
1421             if (ret < 0) {
1422                 qcow2_free_any_clusters(bs, meta->alloc_offset,
1423                                         meta->nb_clusters, QCOW2_DISCARD_NEVER);
1424                 return ret;
1425             }
1426 
1427             /* There are no dependent requests, but we need to remove our
1428              * request from the list of in-flight requests */
1429             QLIST_REMOVE(meta, next_in_flight);
1430         }
1431 
1432         /* TODO Preallocate data if requested */
1433 
1434         nb_sectors -= num;
1435         offset += num << BDRV_SECTOR_BITS;
1436     }
1437 
1438     /*
1439      * It is expected that the image file is large enough to actually contain
1440      * all of the allocated clusters (otherwise we get failing reads after
1441      * EOF). Extend the image to the last allocated sector.
1442      */
1443     if (host_offset != 0) {
1444         uint8_t buf[BDRV_SECTOR_SIZE];
1445         memset(buf, 0, BDRV_SECTOR_SIZE);
1446         ret = bdrv_write(bs->file, (host_offset >> BDRV_SECTOR_BITS) + num - 1,
1447                          buf, 1);
1448         if (ret < 0) {
1449             return ret;
1450         }
1451     }
1452 
1453     return 0;
1454 }
1455 
1456 static int qcow2_create2(const char *filename, int64_t total_size,
1457                          const char *backing_file, const char *backing_format,
1458                          int flags, size_t cluster_size, int prealloc,
1459                          QEMUOptionParameter *options, int version,
1460                          Error **errp)
1461 {
1462     /* Calculate cluster_bits */
1463     int cluster_bits;
1464     cluster_bits = ffs(cluster_size) - 1;
1465     if (cluster_bits < MIN_CLUSTER_BITS || cluster_bits > MAX_CLUSTER_BITS ||
1466         (1 << cluster_bits) != cluster_size)
1467     {
1468         error_setg(errp, "Cluster size must be a power of two between %d and "
1469                    "%dk", 1 << MIN_CLUSTER_BITS, 1 << (MAX_CLUSTER_BITS - 10));
1470         return -EINVAL;
1471     }
1472 
1473     /*
1474      * Open the image file and write a minimal qcow2 header.
1475      *
1476      * We keep things simple and start with a zero-sized image. We also
1477      * do without refcount blocks or a L1 table for now. We'll fix the
1478      * inconsistency later.
1479      *
1480      * We do need a refcount table because growing the refcount table means
1481      * allocating two new refcount blocks - the seconds of which would be at
1482      * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
1483      * size for any qcow2 image.
1484      */
1485     BlockDriverState* bs;
1486     QCowHeader *header;
1487     uint8_t* refcount_table;
1488     Error *local_err = NULL;
1489     int ret;
1490 
1491     ret = bdrv_create_file(filename, options, &local_err);
1492     if (ret < 0) {
1493         error_propagate(errp, local_err);
1494         return ret;
1495     }
1496 
1497     bs = NULL;
1498     ret = bdrv_open(&bs, filename, NULL, NULL, BDRV_O_RDWR | BDRV_O_PROTOCOL,
1499                     NULL, &local_err);
1500     if (ret < 0) {
1501         error_propagate(errp, local_err);
1502         return ret;
1503     }
1504 
1505     /* Write the header */
1506     QEMU_BUILD_BUG_ON((1 << MIN_CLUSTER_BITS) < sizeof(*header));
1507     header = g_malloc0(cluster_size);
1508     *header = (QCowHeader) {
1509         .magic                      = cpu_to_be32(QCOW_MAGIC),
1510         .version                    = cpu_to_be32(version),
1511         .cluster_bits               = cpu_to_be32(cluster_bits),
1512         .size                       = cpu_to_be64(0),
1513         .l1_table_offset            = cpu_to_be64(0),
1514         .l1_size                    = cpu_to_be32(0),
1515         .refcount_table_offset      = cpu_to_be64(cluster_size),
1516         .refcount_table_clusters    = cpu_to_be32(1),
1517         .refcount_order             = cpu_to_be32(3 + REFCOUNT_SHIFT),
1518         .header_length              = cpu_to_be32(sizeof(*header)),
1519     };
1520 
1521     if (flags & BLOCK_FLAG_ENCRYPT) {
1522         header->crypt_method = cpu_to_be32(QCOW_CRYPT_AES);
1523     } else {
1524         header->crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
1525     }
1526 
1527     if (flags & BLOCK_FLAG_LAZY_REFCOUNTS) {
1528         header->compatible_features |=
1529             cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS);
1530     }
1531 
1532     ret = bdrv_pwrite(bs, 0, header, cluster_size);
1533     g_free(header);
1534     if (ret < 0) {
1535         error_setg_errno(errp, -ret, "Could not write qcow2 header");
1536         goto out;
1537     }
1538 
1539     /* Write an empty refcount table */
1540     refcount_table = g_malloc0(cluster_size);
1541     ret = bdrv_pwrite(bs, cluster_size, refcount_table, cluster_size);
1542     g_free(refcount_table);
1543 
1544     if (ret < 0) {
1545         error_setg_errno(errp, -ret, "Could not write refcount table");
1546         goto out;
1547     }
1548 
1549     bdrv_unref(bs);
1550     bs = NULL;
1551 
1552     /*
1553      * And now open the image and make it consistent first (i.e. increase the
1554      * refcount of the cluster that is occupied by the header and the refcount
1555      * table)
1556      */
1557     BlockDriver* drv = bdrv_find_format("qcow2");
1558     assert(drv != NULL);
1559     ret = bdrv_open(&bs, filename, NULL, NULL,
1560         BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_NO_FLUSH, drv, &local_err);
1561     if (ret < 0) {
1562         error_propagate(errp, local_err);
1563         goto out;
1564     }
1565 
1566     ret = qcow2_alloc_clusters(bs, 2 * cluster_size);
1567     if (ret < 0) {
1568         error_setg_errno(errp, -ret, "Could not allocate clusters for qcow2 "
1569                          "header and refcount table");
1570         goto out;
1571 
1572     } else if (ret != 0) {
1573         error_report("Huh, first cluster in empty image is already in use?");
1574         abort();
1575     }
1576 
1577     /* Okay, now that we have a valid image, let's give it the right size */
1578     ret = bdrv_truncate(bs, total_size * BDRV_SECTOR_SIZE);
1579     if (ret < 0) {
1580         error_setg_errno(errp, -ret, "Could not resize image");
1581         goto out;
1582     }
1583 
1584     /* Want a backing file? There you go.*/
1585     if (backing_file) {
1586         ret = bdrv_change_backing_file(bs, backing_file, backing_format);
1587         if (ret < 0) {
1588             error_setg_errno(errp, -ret, "Could not assign backing file '%s' "
1589                              "with format '%s'", backing_file, backing_format);
1590             goto out;
1591         }
1592     }
1593 
1594     /* And if we're supposed to preallocate metadata, do that now */
1595     if (prealloc) {
1596         BDRVQcowState *s = bs->opaque;
1597         qemu_co_mutex_lock(&s->lock);
1598         ret = preallocate(bs);
1599         qemu_co_mutex_unlock(&s->lock);
1600         if (ret < 0) {
1601             error_setg_errno(errp, -ret, "Could not preallocate metadata");
1602             goto out;
1603         }
1604     }
1605 
1606     bdrv_unref(bs);
1607     bs = NULL;
1608 
1609     /* Reopen the image without BDRV_O_NO_FLUSH to flush it before returning */
1610     ret = bdrv_open(&bs, filename, NULL, NULL,
1611                     BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_NO_BACKING,
1612                     drv, &local_err);
1613     if (local_err) {
1614         error_propagate(errp, local_err);
1615         goto out;
1616     }
1617 
1618     ret = 0;
1619 out:
1620     if (bs) {
1621         bdrv_unref(bs);
1622     }
1623     return ret;
1624 }
1625 
1626 static int qcow2_create(const char *filename, QEMUOptionParameter *options,
1627                         Error **errp)
1628 {
1629     const char *backing_file = NULL;
1630     const char *backing_fmt = NULL;
1631     uint64_t sectors = 0;
1632     int flags = 0;
1633     size_t cluster_size = DEFAULT_CLUSTER_SIZE;
1634     int prealloc = 0;
1635     int version = 3;
1636     Error *local_err = NULL;
1637     int ret;
1638 
1639     /* Read out options */
1640     while (options && options->name) {
1641         if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
1642             sectors = options->value.n / 512;
1643         } else if (!strcmp(options->name, BLOCK_OPT_BACKING_FILE)) {
1644             backing_file = options->value.s;
1645         } else if (!strcmp(options->name, BLOCK_OPT_BACKING_FMT)) {
1646             backing_fmt = options->value.s;
1647         } else if (!strcmp(options->name, BLOCK_OPT_ENCRYPT)) {
1648             flags |= options->value.n ? BLOCK_FLAG_ENCRYPT : 0;
1649         } else if (!strcmp(options->name, BLOCK_OPT_CLUSTER_SIZE)) {
1650             if (options->value.n) {
1651                 cluster_size = options->value.n;
1652             }
1653         } else if (!strcmp(options->name, BLOCK_OPT_PREALLOC)) {
1654             if (!options->value.s || !strcmp(options->value.s, "off")) {
1655                 prealloc = 0;
1656             } else if (!strcmp(options->value.s, "metadata")) {
1657                 prealloc = 1;
1658             } else {
1659                 error_setg(errp, "Invalid preallocation mode: '%s'",
1660                            options->value.s);
1661                 return -EINVAL;
1662             }
1663         } else if (!strcmp(options->name, BLOCK_OPT_COMPAT_LEVEL)) {
1664             if (!options->value.s) {
1665                 /* keep the default */
1666             } else if (!strcmp(options->value.s, "0.10")) {
1667                 version = 2;
1668             } else if (!strcmp(options->value.s, "1.1")) {
1669                 version = 3;
1670             } else {
1671                 error_setg(errp, "Invalid compatibility level: '%s'",
1672                            options->value.s);
1673                 return -EINVAL;
1674             }
1675         } else if (!strcmp(options->name, BLOCK_OPT_LAZY_REFCOUNTS)) {
1676             flags |= options->value.n ? BLOCK_FLAG_LAZY_REFCOUNTS : 0;
1677         }
1678         options++;
1679     }
1680 
1681     if (backing_file && prealloc) {
1682         error_setg(errp, "Backing file and preallocation cannot be used at "
1683                    "the same time");
1684         return -EINVAL;
1685     }
1686 
1687     if (version < 3 && (flags & BLOCK_FLAG_LAZY_REFCOUNTS)) {
1688         error_setg(errp, "Lazy refcounts only supported with compatibility "
1689                    "level 1.1 and above (use compat=1.1 or greater)");
1690         return -EINVAL;
1691     }
1692 
1693     ret = qcow2_create2(filename, sectors, backing_file, backing_fmt, flags,
1694                         cluster_size, prealloc, options, version, &local_err);
1695     if (local_err) {
1696         error_propagate(errp, local_err);
1697     }
1698     return ret;
1699 }
1700 
1701 static coroutine_fn int qcow2_co_write_zeroes(BlockDriverState *bs,
1702     int64_t sector_num, int nb_sectors, BdrvRequestFlags flags)
1703 {
1704     int ret;
1705     BDRVQcowState *s = bs->opaque;
1706 
1707     /* Emulate misaligned zero writes */
1708     if (sector_num % s->cluster_sectors || nb_sectors % s->cluster_sectors) {
1709         return -ENOTSUP;
1710     }
1711 
1712     /* Whatever is left can use real zero clusters */
1713     qemu_co_mutex_lock(&s->lock);
1714     ret = qcow2_zero_clusters(bs, sector_num << BDRV_SECTOR_BITS,
1715         nb_sectors);
1716     qemu_co_mutex_unlock(&s->lock);
1717 
1718     return ret;
1719 }
1720 
1721 static coroutine_fn int qcow2_co_discard(BlockDriverState *bs,
1722     int64_t sector_num, int nb_sectors)
1723 {
1724     int ret;
1725     BDRVQcowState *s = bs->opaque;
1726 
1727     qemu_co_mutex_lock(&s->lock);
1728     ret = qcow2_discard_clusters(bs, sector_num << BDRV_SECTOR_BITS,
1729         nb_sectors, QCOW2_DISCARD_REQUEST);
1730     qemu_co_mutex_unlock(&s->lock);
1731     return ret;
1732 }
1733 
1734 static int qcow2_truncate(BlockDriverState *bs, int64_t offset)
1735 {
1736     BDRVQcowState *s = bs->opaque;
1737     int64_t new_l1_size;
1738     int ret;
1739 
1740     if (offset & 511) {
1741         error_report("The new size must be a multiple of 512");
1742         return -EINVAL;
1743     }
1744 
1745     /* cannot proceed if image has snapshots */
1746     if (s->nb_snapshots) {
1747         error_report("Can't resize an image which has snapshots");
1748         return -ENOTSUP;
1749     }
1750 
1751     /* shrinking is currently not supported */
1752     if (offset < bs->total_sectors * 512) {
1753         error_report("qcow2 doesn't support shrinking images yet");
1754         return -ENOTSUP;
1755     }
1756 
1757     new_l1_size = size_to_l1(s, offset);
1758     ret = qcow2_grow_l1_table(bs, new_l1_size, true);
1759     if (ret < 0) {
1760         return ret;
1761     }
1762 
1763     /* write updated header.size */
1764     offset = cpu_to_be64(offset);
1765     ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, size),
1766                            &offset, sizeof(uint64_t));
1767     if (ret < 0) {
1768         return ret;
1769     }
1770 
1771     s->l1_vm_state_index = new_l1_size;
1772     return 0;
1773 }
1774 
1775 /* XXX: put compressed sectors first, then all the cluster aligned
1776    tables to avoid losing bytes in alignment */
1777 static int qcow2_write_compressed(BlockDriverState *bs, int64_t sector_num,
1778                                   const uint8_t *buf, int nb_sectors)
1779 {
1780     BDRVQcowState *s = bs->opaque;
1781     z_stream strm;
1782     int ret, out_len;
1783     uint8_t *out_buf;
1784     uint64_t cluster_offset;
1785 
1786     if (nb_sectors == 0) {
1787         /* align end of file to a sector boundary to ease reading with
1788            sector based I/Os */
1789         cluster_offset = bdrv_getlength(bs->file);
1790         cluster_offset = (cluster_offset + 511) & ~511;
1791         bdrv_truncate(bs->file, cluster_offset);
1792         return 0;
1793     }
1794 
1795     if (nb_sectors != s->cluster_sectors) {
1796         ret = -EINVAL;
1797 
1798         /* Zero-pad last write if image size is not cluster aligned */
1799         if (sector_num + nb_sectors == bs->total_sectors &&
1800             nb_sectors < s->cluster_sectors) {
1801             uint8_t *pad_buf = qemu_blockalign(bs, s->cluster_size);
1802             memset(pad_buf, 0, s->cluster_size);
1803             memcpy(pad_buf, buf, nb_sectors * BDRV_SECTOR_SIZE);
1804             ret = qcow2_write_compressed(bs, sector_num,
1805                                          pad_buf, s->cluster_sectors);
1806             qemu_vfree(pad_buf);
1807         }
1808         return ret;
1809     }
1810 
1811     out_buf = g_malloc(s->cluster_size + (s->cluster_size / 1000) + 128);
1812 
1813     /* best compression, small window, no zlib header */
1814     memset(&strm, 0, sizeof(strm));
1815     ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
1816                        Z_DEFLATED, -12,
1817                        9, Z_DEFAULT_STRATEGY);
1818     if (ret != 0) {
1819         ret = -EINVAL;
1820         goto fail;
1821     }
1822 
1823     strm.avail_in = s->cluster_size;
1824     strm.next_in = (uint8_t *)buf;
1825     strm.avail_out = s->cluster_size;
1826     strm.next_out = out_buf;
1827 
1828     ret = deflate(&strm, Z_FINISH);
1829     if (ret != Z_STREAM_END && ret != Z_OK) {
1830         deflateEnd(&strm);
1831         ret = -EINVAL;
1832         goto fail;
1833     }
1834     out_len = strm.next_out - out_buf;
1835 
1836     deflateEnd(&strm);
1837 
1838     if (ret != Z_STREAM_END || out_len >= s->cluster_size) {
1839         /* could not compress: write normal cluster */
1840         ret = bdrv_write(bs, sector_num, buf, s->cluster_sectors);
1841         if (ret < 0) {
1842             goto fail;
1843         }
1844     } else {
1845         cluster_offset = qcow2_alloc_compressed_cluster_offset(bs,
1846             sector_num << 9, out_len);
1847         if (!cluster_offset) {
1848             ret = -EIO;
1849             goto fail;
1850         }
1851         cluster_offset &= s->cluster_offset_mask;
1852 
1853         ret = qcow2_pre_write_overlap_check(bs, 0, cluster_offset, out_len);
1854         if (ret < 0) {
1855             goto fail;
1856         }
1857 
1858         BLKDBG_EVENT(bs->file, BLKDBG_WRITE_COMPRESSED);
1859         ret = bdrv_pwrite(bs->file, cluster_offset, out_buf, out_len);
1860         if (ret < 0) {
1861             goto fail;
1862         }
1863     }
1864 
1865     ret = 0;
1866 fail:
1867     g_free(out_buf);
1868     return ret;
1869 }
1870 
1871 static coroutine_fn int qcow2_co_flush_to_os(BlockDriverState *bs)
1872 {
1873     BDRVQcowState *s = bs->opaque;
1874     int ret;
1875 
1876     qemu_co_mutex_lock(&s->lock);
1877     ret = qcow2_cache_flush(bs, s->l2_table_cache);
1878     if (ret < 0) {
1879         qemu_co_mutex_unlock(&s->lock);
1880         return ret;
1881     }
1882 
1883     if (qcow2_need_accurate_refcounts(s)) {
1884         ret = qcow2_cache_flush(bs, s->refcount_block_cache);
1885         if (ret < 0) {
1886             qemu_co_mutex_unlock(&s->lock);
1887             return ret;
1888         }
1889     }
1890     qemu_co_mutex_unlock(&s->lock);
1891 
1892     return 0;
1893 }
1894 
1895 static int qcow2_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1896 {
1897     BDRVQcowState *s = bs->opaque;
1898     bdi->unallocated_blocks_are_zero = true;
1899     bdi->can_write_zeroes_with_unmap = (s->qcow_version >= 3);
1900     bdi->cluster_size = s->cluster_size;
1901     bdi->vm_state_offset = qcow2_vm_state_offset(s);
1902     return 0;
1903 }
1904 
1905 static ImageInfoSpecific *qcow2_get_specific_info(BlockDriverState *bs)
1906 {
1907     BDRVQcowState *s = bs->opaque;
1908     ImageInfoSpecific *spec_info = g_new(ImageInfoSpecific, 1);
1909 
1910     *spec_info = (ImageInfoSpecific){
1911         .kind  = IMAGE_INFO_SPECIFIC_KIND_QCOW2,
1912         {
1913             .qcow2 = g_new(ImageInfoSpecificQCow2, 1),
1914         },
1915     };
1916     if (s->qcow_version == 2) {
1917         *spec_info->qcow2 = (ImageInfoSpecificQCow2){
1918             .compat = g_strdup("0.10"),
1919         };
1920     } else if (s->qcow_version == 3) {
1921         *spec_info->qcow2 = (ImageInfoSpecificQCow2){
1922             .compat             = g_strdup("1.1"),
1923             .lazy_refcounts     = s->compatible_features &
1924                                   QCOW2_COMPAT_LAZY_REFCOUNTS,
1925             .has_lazy_refcounts = true,
1926         };
1927     }
1928 
1929     return spec_info;
1930 }
1931 
1932 #if 0
1933 static void dump_refcounts(BlockDriverState *bs)
1934 {
1935     BDRVQcowState *s = bs->opaque;
1936     int64_t nb_clusters, k, k1, size;
1937     int refcount;
1938 
1939     size = bdrv_getlength(bs->file);
1940     nb_clusters = size_to_clusters(s, size);
1941     for(k = 0; k < nb_clusters;) {
1942         k1 = k;
1943         refcount = get_refcount(bs, k);
1944         k++;
1945         while (k < nb_clusters && get_refcount(bs, k) == refcount)
1946             k++;
1947         printf("%" PRId64 ": refcount=%d nb=%" PRId64 "\n", k, refcount,
1948                k - k1);
1949     }
1950 }
1951 #endif
1952 
1953 static int qcow2_save_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
1954                               int64_t pos)
1955 {
1956     BDRVQcowState *s = bs->opaque;
1957     int64_t total_sectors = bs->total_sectors;
1958     int growable = bs->growable;
1959     bool zero_beyond_eof = bs->zero_beyond_eof;
1960     int ret;
1961 
1962     BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_SAVE);
1963     bs->growable = 1;
1964     bs->zero_beyond_eof = false;
1965     ret = bdrv_pwritev(bs, qcow2_vm_state_offset(s) + pos, qiov);
1966     bs->growable = growable;
1967     bs->zero_beyond_eof = zero_beyond_eof;
1968 
1969     /* bdrv_co_do_writev will have increased the total_sectors value to include
1970      * the VM state - the VM state is however not an actual part of the block
1971      * device, therefore, we need to restore the old value. */
1972     bs->total_sectors = total_sectors;
1973 
1974     return ret;
1975 }
1976 
1977 static int qcow2_load_vmstate(BlockDriverState *bs, uint8_t *buf,
1978                               int64_t pos, int size)
1979 {
1980     BDRVQcowState *s = bs->opaque;
1981     int growable = bs->growable;
1982     bool zero_beyond_eof = bs->zero_beyond_eof;
1983     int ret;
1984 
1985     BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_LOAD);
1986     bs->growable = 1;
1987     bs->zero_beyond_eof = false;
1988     ret = bdrv_pread(bs, qcow2_vm_state_offset(s) + pos, buf, size);
1989     bs->growable = growable;
1990     bs->zero_beyond_eof = zero_beyond_eof;
1991 
1992     return ret;
1993 }
1994 
1995 /*
1996  * Downgrades an image's version. To achieve this, any incompatible features
1997  * have to be removed.
1998  */
1999 static int qcow2_downgrade(BlockDriverState *bs, int target_version)
2000 {
2001     BDRVQcowState *s = bs->opaque;
2002     int current_version = s->qcow_version;
2003     int ret;
2004 
2005     if (target_version == current_version) {
2006         return 0;
2007     } else if (target_version > current_version) {
2008         return -EINVAL;
2009     } else if (target_version != 2) {
2010         return -EINVAL;
2011     }
2012 
2013     if (s->refcount_order != 4) {
2014         /* we would have to convert the image to a refcount_order == 4 image
2015          * here; however, since qemu (at the time of writing this) does not
2016          * support anything different than 4 anyway, there is no point in doing
2017          * so right now; however, we should error out (if qemu supports this in
2018          * the future and this code has not been adapted) */
2019         error_report("qcow2_downgrade: Image refcount orders other than 4 are "
2020                      "currently not supported.");
2021         return -ENOTSUP;
2022     }
2023 
2024     /* clear incompatible features */
2025     if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
2026         ret = qcow2_mark_clean(bs);
2027         if (ret < 0) {
2028             return ret;
2029         }
2030     }
2031 
2032     /* with QCOW2_INCOMPAT_CORRUPT, it is pretty much impossible to get here in
2033      * the first place; if that happens nonetheless, returning -ENOTSUP is the
2034      * best thing to do anyway */
2035 
2036     if (s->incompatible_features) {
2037         return -ENOTSUP;
2038     }
2039 
2040     /* since we can ignore compatible features, we can set them to 0 as well */
2041     s->compatible_features = 0;
2042     /* if lazy refcounts have been used, they have already been fixed through
2043      * clearing the dirty flag */
2044 
2045     /* clearing autoclear features is trivial */
2046     s->autoclear_features = 0;
2047 
2048     ret = qcow2_expand_zero_clusters(bs);
2049     if (ret < 0) {
2050         return ret;
2051     }
2052 
2053     s->qcow_version = target_version;
2054     ret = qcow2_update_header(bs);
2055     if (ret < 0) {
2056         s->qcow_version = current_version;
2057         return ret;
2058     }
2059     return 0;
2060 }
2061 
2062 static int qcow2_amend_options(BlockDriverState *bs,
2063                                QEMUOptionParameter *options)
2064 {
2065     BDRVQcowState *s = bs->opaque;
2066     int old_version = s->qcow_version, new_version = old_version;
2067     uint64_t new_size = 0;
2068     const char *backing_file = NULL, *backing_format = NULL;
2069     bool lazy_refcounts = s->use_lazy_refcounts;
2070     int ret;
2071     int i;
2072 
2073     for (i = 0; options[i].name; i++)
2074     {
2075         if (!options[i].assigned) {
2076             /* only change explicitly defined options */
2077             continue;
2078         }
2079 
2080         if (!strcmp(options[i].name, "compat")) {
2081             if (!options[i].value.s) {
2082                 /* preserve default */
2083             } else if (!strcmp(options[i].value.s, "0.10")) {
2084                 new_version = 2;
2085             } else if (!strcmp(options[i].value.s, "1.1")) {
2086                 new_version = 3;
2087             } else {
2088                 fprintf(stderr, "Unknown compatibility level %s.\n",
2089                         options[i].value.s);
2090                 return -EINVAL;
2091             }
2092         } else if (!strcmp(options[i].name, "preallocation")) {
2093             fprintf(stderr, "Cannot change preallocation mode.\n");
2094             return -ENOTSUP;
2095         } else if (!strcmp(options[i].name, "size")) {
2096             new_size = options[i].value.n;
2097         } else if (!strcmp(options[i].name, "backing_file")) {
2098             backing_file = options[i].value.s;
2099         } else if (!strcmp(options[i].name, "backing_fmt")) {
2100             backing_format = options[i].value.s;
2101         } else if (!strcmp(options[i].name, "encryption")) {
2102             if ((options[i].value.n != !!s->crypt_method)) {
2103                 fprintf(stderr, "Changing the encryption flag is not "
2104                         "supported.\n");
2105                 return -ENOTSUP;
2106             }
2107         } else if (!strcmp(options[i].name, "cluster_size")) {
2108             if (options[i].value.n != s->cluster_size) {
2109                 fprintf(stderr, "Changing the cluster size is not "
2110                         "supported.\n");
2111                 return -ENOTSUP;
2112             }
2113         } else if (!strcmp(options[i].name, "lazy_refcounts")) {
2114             lazy_refcounts = options[i].value.n;
2115         } else {
2116             /* if this assertion fails, this probably means a new option was
2117              * added without having it covered here */
2118             assert(false);
2119         }
2120     }
2121 
2122     if (new_version != old_version) {
2123         if (new_version > old_version) {
2124             /* Upgrade */
2125             s->qcow_version = new_version;
2126             ret = qcow2_update_header(bs);
2127             if (ret < 0) {
2128                 s->qcow_version = old_version;
2129                 return ret;
2130             }
2131         } else {
2132             ret = qcow2_downgrade(bs, new_version);
2133             if (ret < 0) {
2134                 return ret;
2135             }
2136         }
2137     }
2138 
2139     if (backing_file || backing_format) {
2140         ret = qcow2_change_backing_file(bs, backing_file ?: bs->backing_file,
2141                                         backing_format ?: bs->backing_format);
2142         if (ret < 0) {
2143             return ret;
2144         }
2145     }
2146 
2147     if (s->use_lazy_refcounts != lazy_refcounts) {
2148         if (lazy_refcounts) {
2149             if (s->qcow_version < 3) {
2150                 fprintf(stderr, "Lazy refcounts only supported with compatibility "
2151                         "level 1.1 and above (use compat=1.1 or greater)\n");
2152                 return -EINVAL;
2153             }
2154             s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
2155             ret = qcow2_update_header(bs);
2156             if (ret < 0) {
2157                 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
2158                 return ret;
2159             }
2160             s->use_lazy_refcounts = true;
2161         } else {
2162             /* make image clean first */
2163             ret = qcow2_mark_clean(bs);
2164             if (ret < 0) {
2165                 return ret;
2166             }
2167             /* now disallow lazy refcounts */
2168             s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
2169             ret = qcow2_update_header(bs);
2170             if (ret < 0) {
2171                 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
2172                 return ret;
2173             }
2174             s->use_lazy_refcounts = false;
2175         }
2176     }
2177 
2178     if (new_size) {
2179         ret = bdrv_truncate(bs, new_size);
2180         if (ret < 0) {
2181             return ret;
2182         }
2183     }
2184 
2185     return 0;
2186 }
2187 
2188 static QEMUOptionParameter qcow2_create_options[] = {
2189     {
2190         .name = BLOCK_OPT_SIZE,
2191         .type = OPT_SIZE,
2192         .help = "Virtual disk size"
2193     },
2194     {
2195         .name = BLOCK_OPT_COMPAT_LEVEL,
2196         .type = OPT_STRING,
2197         .help = "Compatibility level (0.10 or 1.1)"
2198     },
2199     {
2200         .name = BLOCK_OPT_BACKING_FILE,
2201         .type = OPT_STRING,
2202         .help = "File name of a base image"
2203     },
2204     {
2205         .name = BLOCK_OPT_BACKING_FMT,
2206         .type = OPT_STRING,
2207         .help = "Image format of the base image"
2208     },
2209     {
2210         .name = BLOCK_OPT_ENCRYPT,
2211         .type = OPT_FLAG,
2212         .help = "Encrypt the image"
2213     },
2214     {
2215         .name = BLOCK_OPT_CLUSTER_SIZE,
2216         .type = OPT_SIZE,
2217         .help = "qcow2 cluster size",
2218         .value = { .n = DEFAULT_CLUSTER_SIZE },
2219     },
2220     {
2221         .name = BLOCK_OPT_PREALLOC,
2222         .type = OPT_STRING,
2223         .help = "Preallocation mode (allowed values: off, metadata)"
2224     },
2225     {
2226         .name = BLOCK_OPT_LAZY_REFCOUNTS,
2227         .type = OPT_FLAG,
2228         .help = "Postpone refcount updates",
2229     },
2230     { NULL }
2231 };
2232 
2233 static BlockDriver bdrv_qcow2 = {
2234     .format_name        = "qcow2",
2235     .instance_size      = sizeof(BDRVQcowState),
2236     .bdrv_probe         = qcow2_probe,
2237     .bdrv_open          = qcow2_open,
2238     .bdrv_close         = qcow2_close,
2239     .bdrv_reopen_prepare  = qcow2_reopen_prepare,
2240     .bdrv_create        = qcow2_create,
2241     .bdrv_has_zero_init = bdrv_has_zero_init_1,
2242     .bdrv_co_get_block_status = qcow2_co_get_block_status,
2243     .bdrv_set_key       = qcow2_set_key,
2244 
2245     .bdrv_co_readv          = qcow2_co_readv,
2246     .bdrv_co_writev         = qcow2_co_writev,
2247     .bdrv_co_flush_to_os    = qcow2_co_flush_to_os,
2248 
2249     .bdrv_co_write_zeroes   = qcow2_co_write_zeroes,
2250     .bdrv_co_discard        = qcow2_co_discard,
2251     .bdrv_truncate          = qcow2_truncate,
2252     .bdrv_write_compressed  = qcow2_write_compressed,
2253 
2254     .bdrv_snapshot_create   = qcow2_snapshot_create,
2255     .bdrv_snapshot_goto     = qcow2_snapshot_goto,
2256     .bdrv_snapshot_delete   = qcow2_snapshot_delete,
2257     .bdrv_snapshot_list     = qcow2_snapshot_list,
2258     .bdrv_snapshot_load_tmp     = qcow2_snapshot_load_tmp,
2259     .bdrv_get_info      = qcow2_get_info,
2260     .bdrv_get_specific_info = qcow2_get_specific_info,
2261 
2262     .bdrv_save_vmstate    = qcow2_save_vmstate,
2263     .bdrv_load_vmstate    = qcow2_load_vmstate,
2264 
2265     .bdrv_change_backing_file   = qcow2_change_backing_file,
2266 
2267     .bdrv_refresh_limits        = qcow2_refresh_limits,
2268     .bdrv_invalidate_cache      = qcow2_invalidate_cache,
2269 
2270     .create_options = qcow2_create_options,
2271     .bdrv_check = qcow2_check,
2272     .bdrv_amend_options = qcow2_amend_options,
2273 };
2274 
2275 static void bdrv_qcow2_init(void)
2276 {
2277     bdrv_register(&bdrv_qcow2);
2278 }
2279 
2280 block_init(bdrv_qcow2_init);
2281