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