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