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