xref: /openbmc/qemu/block/qcow2.c (revision 0bdb12c7)
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, 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, 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, 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, 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, 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, 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, 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 = true;
984     }
985 
986     s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */
987     s->l2_size = 1 << s->l2_bits;
988     /* 2^(s->refcount_order - 3) is the refcount width in bytes */
989     s->refcount_block_bits = s->cluster_bits - (s->refcount_order - 3);
990     s->refcount_block_size = 1 << s->refcount_block_bits;
991     bs->total_sectors = header.size / 512;
992     s->csize_shift = (62 - (s->cluster_bits - 8));
993     s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;
994     s->cluster_offset_mask = (1LL << s->csize_shift) - 1;
995 
996     s->refcount_table_offset = header.refcount_table_offset;
997     s->refcount_table_size =
998         header.refcount_table_clusters << (s->cluster_bits - 3);
999 
1000     if (header.refcount_table_clusters > qcow2_max_refcount_clusters(s)) {
1001         error_setg(errp, "Reference count table too large");
1002         ret = -EINVAL;
1003         goto fail;
1004     }
1005 
1006     ret = validate_table_offset(bs, s->refcount_table_offset,
1007                                 s->refcount_table_size, sizeof(uint64_t));
1008     if (ret < 0) {
1009         error_setg(errp, "Invalid reference count table offset");
1010         goto fail;
1011     }
1012 
1013     /* Snapshot table offset/length */
1014     if (header.nb_snapshots > QCOW_MAX_SNAPSHOTS) {
1015         error_setg(errp, "Too many snapshots");
1016         ret = -EINVAL;
1017         goto fail;
1018     }
1019 
1020     ret = validate_table_offset(bs, header.snapshots_offset,
1021                                 header.nb_snapshots,
1022                                 sizeof(QCowSnapshotHeader));
1023     if (ret < 0) {
1024         error_setg(errp, "Invalid snapshot table offset");
1025         goto fail;
1026     }
1027 
1028     /* read the level 1 table */
1029     if (header.l1_size > QCOW_MAX_L1_SIZE / sizeof(uint64_t)) {
1030         error_setg(errp, "Active L1 table too large");
1031         ret = -EFBIG;
1032         goto fail;
1033     }
1034     s->l1_size = header.l1_size;
1035 
1036     l1_vm_state_index = size_to_l1(s, header.size);
1037     if (l1_vm_state_index > INT_MAX) {
1038         error_setg(errp, "Image is too big");
1039         ret = -EFBIG;
1040         goto fail;
1041     }
1042     s->l1_vm_state_index = l1_vm_state_index;
1043 
1044     /* the L1 table must contain at least enough entries to put
1045        header.size bytes */
1046     if (s->l1_size < s->l1_vm_state_index) {
1047         error_setg(errp, "L1 table is too small");
1048         ret = -EINVAL;
1049         goto fail;
1050     }
1051 
1052     ret = validate_table_offset(bs, header.l1_table_offset,
1053                                 header.l1_size, sizeof(uint64_t));
1054     if (ret < 0) {
1055         error_setg(errp, "Invalid L1 table offset");
1056         goto fail;
1057     }
1058     s->l1_table_offset = header.l1_table_offset;
1059 
1060 
1061     if (s->l1_size > 0) {
1062         s->l1_table = qemu_try_blockalign(bs->file->bs,
1063             align_offset(s->l1_size * sizeof(uint64_t), 512));
1064         if (s->l1_table == NULL) {
1065             error_setg(errp, "Could not allocate L1 table");
1066             ret = -ENOMEM;
1067             goto fail;
1068         }
1069         ret = bdrv_pread(bs->file, s->l1_table_offset, s->l1_table,
1070                          s->l1_size * sizeof(uint64_t));
1071         if (ret < 0) {
1072             error_setg_errno(errp, -ret, "Could not read L1 table");
1073             goto fail;
1074         }
1075         for(i = 0;i < s->l1_size; i++) {
1076             be64_to_cpus(&s->l1_table[i]);
1077         }
1078     }
1079 
1080     /* Parse driver-specific options */
1081     ret = qcow2_update_options(bs, options, flags, errp);
1082     if (ret < 0) {
1083         goto fail;
1084     }
1085 
1086     s->cluster_cache = g_malloc(s->cluster_size);
1087     /* one more sector for decompressed data alignment */
1088     s->cluster_data = qemu_try_blockalign(bs->file->bs, QCOW_MAX_CRYPT_CLUSTERS
1089                                                     * s->cluster_size + 512);
1090     if (s->cluster_data == NULL) {
1091         error_setg(errp, "Could not allocate temporary cluster buffer");
1092         ret = -ENOMEM;
1093         goto fail;
1094     }
1095 
1096     s->cluster_cache_offset = -1;
1097     s->flags = flags;
1098 
1099     ret = qcow2_refcount_init(bs);
1100     if (ret != 0) {
1101         error_setg_errno(errp, -ret, "Could not initialize refcount handling");
1102         goto fail;
1103     }
1104 
1105     QLIST_INIT(&s->cluster_allocs);
1106     QTAILQ_INIT(&s->discards);
1107 
1108     /* read qcow2 extensions */
1109     if (qcow2_read_extensions(bs, header.header_length, ext_end, NULL,
1110         &local_err)) {
1111         error_propagate(errp, local_err);
1112         ret = -EINVAL;
1113         goto fail;
1114     }
1115 
1116     /* read the backing file name */
1117     if (header.backing_file_offset != 0) {
1118         len = header.backing_file_size;
1119         if (len > MIN(1023, s->cluster_size - header.backing_file_offset) ||
1120             len >= sizeof(bs->backing_file)) {
1121             error_setg(errp, "Backing file name too long");
1122             ret = -EINVAL;
1123             goto fail;
1124         }
1125         ret = bdrv_pread(bs->file, header.backing_file_offset,
1126                          bs->backing_file, len);
1127         if (ret < 0) {
1128             error_setg_errno(errp, -ret, "Could not read backing file name");
1129             goto fail;
1130         }
1131         bs->backing_file[len] = '\0';
1132         s->image_backing_file = g_strdup(bs->backing_file);
1133     }
1134 
1135     /* Internal snapshots */
1136     s->snapshots_offset = header.snapshots_offset;
1137     s->nb_snapshots = header.nb_snapshots;
1138 
1139     ret = qcow2_read_snapshots(bs);
1140     if (ret < 0) {
1141         error_setg_errno(errp, -ret, "Could not read snapshots");
1142         goto fail;
1143     }
1144 
1145     /* Clear unknown autoclear feature bits */
1146     if (!bs->read_only && !(flags & BDRV_O_INACTIVE) && s->autoclear_features) {
1147         s->autoclear_features = 0;
1148         ret = qcow2_update_header(bs);
1149         if (ret < 0) {
1150             error_setg_errno(errp, -ret, "Could not update qcow2 header");
1151             goto fail;
1152         }
1153     }
1154 
1155     /* Initialise locks */
1156     qemu_co_mutex_init(&s->lock);
1157 
1158     /* Repair image if dirty */
1159     if (!(flags & (BDRV_O_CHECK | BDRV_O_INACTIVE)) && !bs->read_only &&
1160         (s->incompatible_features & QCOW2_INCOMPAT_DIRTY)) {
1161         BdrvCheckResult result = {0};
1162 
1163         ret = qcow2_check(bs, &result, BDRV_FIX_ERRORS | BDRV_FIX_LEAKS);
1164         if (ret < 0) {
1165             error_setg_errno(errp, -ret, "Could not repair dirty image");
1166             goto fail;
1167         }
1168     }
1169 
1170 #ifdef DEBUG_ALLOC
1171     {
1172         BdrvCheckResult result = {0};
1173         qcow2_check_refcounts(bs, &result, 0);
1174     }
1175 #endif
1176     return ret;
1177 
1178  fail:
1179     g_free(s->unknown_header_fields);
1180     cleanup_unknown_header_ext(bs);
1181     qcow2_free_snapshots(bs);
1182     qcow2_refcount_close(bs);
1183     qemu_vfree(s->l1_table);
1184     /* else pre-write overlap checks in cache_destroy may crash */
1185     s->l1_table = NULL;
1186     cache_clean_timer_del(bs);
1187     if (s->l2_table_cache) {
1188         qcow2_cache_destroy(bs, s->l2_table_cache);
1189     }
1190     if (s->refcount_block_cache) {
1191         qcow2_cache_destroy(bs, s->refcount_block_cache);
1192     }
1193     g_free(s->cluster_cache);
1194     qemu_vfree(s->cluster_data);
1195     return ret;
1196 }
1197 
1198 static void qcow2_refresh_limits(BlockDriverState *bs, Error **errp)
1199 {
1200     BDRVQcow2State *s = bs->opaque;
1201 
1202     if (bs->encrypted) {
1203         /* Encryption works on a sector granularity */
1204         bs->bl.request_alignment = BDRV_SECTOR_SIZE;
1205     }
1206     bs->bl.pwrite_zeroes_alignment = s->cluster_size;
1207 }
1208 
1209 static int qcow2_set_key(BlockDriverState *bs, const char *key)
1210 {
1211     BDRVQcow2State *s = bs->opaque;
1212     uint8_t keybuf[16];
1213     int len, i;
1214     Error *err = NULL;
1215 
1216     memset(keybuf, 0, 16);
1217     len = strlen(key);
1218     if (len > 16)
1219         len = 16;
1220     /* XXX: we could compress the chars to 7 bits to increase
1221        entropy */
1222     for(i = 0;i < len;i++) {
1223         keybuf[i] = key[i];
1224     }
1225     assert(bs->encrypted);
1226 
1227     qcrypto_cipher_free(s->cipher);
1228     s->cipher = qcrypto_cipher_new(
1229         QCRYPTO_CIPHER_ALG_AES_128,
1230         QCRYPTO_CIPHER_MODE_CBC,
1231         keybuf, G_N_ELEMENTS(keybuf),
1232         &err);
1233 
1234     if (!s->cipher) {
1235         /* XXX would be nice if errors in this method could
1236          * be properly propagate to the caller. Would need
1237          * the bdrv_set_key() API signature to be fixed. */
1238         error_free(err);
1239         return -1;
1240     }
1241     return 0;
1242 }
1243 
1244 static int qcow2_reopen_prepare(BDRVReopenState *state,
1245                                 BlockReopenQueue *queue, Error **errp)
1246 {
1247     Qcow2ReopenState *r;
1248     int ret;
1249 
1250     r = g_new0(Qcow2ReopenState, 1);
1251     state->opaque = r;
1252 
1253     ret = qcow2_update_options_prepare(state->bs, r, state->options,
1254                                        state->flags, errp);
1255     if (ret < 0) {
1256         goto fail;
1257     }
1258 
1259     /* We need to write out any unwritten data if we reopen read-only. */
1260     if ((state->flags & BDRV_O_RDWR) == 0) {
1261         ret = bdrv_flush(state->bs);
1262         if (ret < 0) {
1263             goto fail;
1264         }
1265 
1266         ret = qcow2_mark_clean(state->bs);
1267         if (ret < 0) {
1268             goto fail;
1269         }
1270     }
1271 
1272     return 0;
1273 
1274 fail:
1275     qcow2_update_options_abort(state->bs, r);
1276     g_free(r);
1277     return ret;
1278 }
1279 
1280 static void qcow2_reopen_commit(BDRVReopenState *state)
1281 {
1282     qcow2_update_options_commit(state->bs, state->opaque);
1283     g_free(state->opaque);
1284 }
1285 
1286 static void qcow2_reopen_abort(BDRVReopenState *state)
1287 {
1288     qcow2_update_options_abort(state->bs, state->opaque);
1289     g_free(state->opaque);
1290 }
1291 
1292 static void qcow2_join_options(QDict *options, QDict *old_options)
1293 {
1294     bool has_new_overlap_template =
1295         qdict_haskey(options, QCOW2_OPT_OVERLAP) ||
1296         qdict_haskey(options, QCOW2_OPT_OVERLAP_TEMPLATE);
1297     bool has_new_total_cache_size =
1298         qdict_haskey(options, QCOW2_OPT_CACHE_SIZE);
1299     bool has_all_cache_options;
1300 
1301     /* New overlap template overrides all old overlap options */
1302     if (has_new_overlap_template) {
1303         qdict_del(old_options, QCOW2_OPT_OVERLAP);
1304         qdict_del(old_options, QCOW2_OPT_OVERLAP_TEMPLATE);
1305         qdict_del(old_options, QCOW2_OPT_OVERLAP_MAIN_HEADER);
1306         qdict_del(old_options, QCOW2_OPT_OVERLAP_ACTIVE_L1);
1307         qdict_del(old_options, QCOW2_OPT_OVERLAP_ACTIVE_L2);
1308         qdict_del(old_options, QCOW2_OPT_OVERLAP_REFCOUNT_TABLE);
1309         qdict_del(old_options, QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK);
1310         qdict_del(old_options, QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE);
1311         qdict_del(old_options, QCOW2_OPT_OVERLAP_INACTIVE_L1);
1312         qdict_del(old_options, QCOW2_OPT_OVERLAP_INACTIVE_L2);
1313     }
1314 
1315     /* New total cache size overrides all old options */
1316     if (qdict_haskey(options, QCOW2_OPT_CACHE_SIZE)) {
1317         qdict_del(old_options, QCOW2_OPT_L2_CACHE_SIZE);
1318         qdict_del(old_options, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
1319     }
1320 
1321     qdict_join(options, old_options, false);
1322 
1323     /*
1324      * If after merging all cache size options are set, an old total size is
1325      * overwritten. Do keep all options, however, if all three are new. The
1326      * resulting error message is what we want to happen.
1327      */
1328     has_all_cache_options =
1329         qdict_haskey(options, QCOW2_OPT_CACHE_SIZE) ||
1330         qdict_haskey(options, QCOW2_OPT_L2_CACHE_SIZE) ||
1331         qdict_haskey(options, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
1332 
1333     if (has_all_cache_options && !has_new_total_cache_size) {
1334         qdict_del(options, QCOW2_OPT_CACHE_SIZE);
1335     }
1336 }
1337 
1338 static int64_t coroutine_fn qcow2_co_get_block_status(BlockDriverState *bs,
1339         int64_t sector_num, int nb_sectors, int *pnum, BlockDriverState **file)
1340 {
1341     BDRVQcow2State *s = bs->opaque;
1342     uint64_t cluster_offset;
1343     int index_in_cluster, ret;
1344     unsigned int bytes;
1345     int64_t status = 0;
1346 
1347     bytes = MIN(INT_MAX, nb_sectors * BDRV_SECTOR_SIZE);
1348     qemu_co_mutex_lock(&s->lock);
1349     ret = qcow2_get_cluster_offset(bs, sector_num << 9, &bytes,
1350                                    &cluster_offset);
1351     qemu_co_mutex_unlock(&s->lock);
1352     if (ret < 0) {
1353         return ret;
1354     }
1355 
1356     *pnum = bytes >> BDRV_SECTOR_BITS;
1357 
1358     if (cluster_offset != 0 && ret != QCOW2_CLUSTER_COMPRESSED &&
1359         !s->cipher) {
1360         index_in_cluster = sector_num & (s->cluster_sectors - 1);
1361         cluster_offset |= (index_in_cluster << BDRV_SECTOR_BITS);
1362         *file = bs->file->bs;
1363         status |= BDRV_BLOCK_OFFSET_VALID | cluster_offset;
1364     }
1365     if (ret == QCOW2_CLUSTER_ZERO) {
1366         status |= BDRV_BLOCK_ZERO;
1367     } else if (ret != QCOW2_CLUSTER_UNALLOCATED) {
1368         status |= BDRV_BLOCK_DATA;
1369     }
1370     return status;
1371 }
1372 
1373 /* handle reading after the end of the backing file */
1374 int qcow2_backing_read1(BlockDriverState *bs, QEMUIOVector *qiov,
1375                         int64_t offset, int bytes)
1376 {
1377     uint64_t bs_size = bs->total_sectors * BDRV_SECTOR_SIZE;
1378     int n1;
1379 
1380     if ((offset + bytes) <= bs_size) {
1381         return bytes;
1382     }
1383 
1384     if (offset >= bs_size) {
1385         n1 = 0;
1386     } else {
1387         n1 = bs_size - offset;
1388     }
1389 
1390     qemu_iovec_memset(qiov, n1, 0, bytes - n1);
1391 
1392     return n1;
1393 }
1394 
1395 static coroutine_fn int qcow2_co_preadv(BlockDriverState *bs, uint64_t offset,
1396                                         uint64_t bytes, QEMUIOVector *qiov,
1397                                         int flags)
1398 {
1399     BDRVQcow2State *s = bs->opaque;
1400     int offset_in_cluster, n1;
1401     int ret;
1402     unsigned int cur_bytes; /* number of bytes in current iteration */
1403     uint64_t cluster_offset = 0;
1404     uint64_t bytes_done = 0;
1405     QEMUIOVector hd_qiov;
1406     uint8_t *cluster_data = NULL;
1407 
1408     qemu_iovec_init(&hd_qiov, qiov->niov);
1409 
1410     qemu_co_mutex_lock(&s->lock);
1411 
1412     while (bytes != 0) {
1413 
1414         /* prepare next request */
1415         cur_bytes = MIN(bytes, INT_MAX);
1416         if (s->cipher) {
1417             cur_bytes = MIN(cur_bytes,
1418                             QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
1419         }
1420 
1421         ret = qcow2_get_cluster_offset(bs, offset, &cur_bytes, &cluster_offset);
1422         if (ret < 0) {
1423             goto fail;
1424         }
1425 
1426         offset_in_cluster = offset_into_cluster(s, offset);
1427 
1428         qemu_iovec_reset(&hd_qiov);
1429         qemu_iovec_concat(&hd_qiov, qiov, bytes_done, cur_bytes);
1430 
1431         switch (ret) {
1432         case QCOW2_CLUSTER_UNALLOCATED:
1433 
1434             if (bs->backing) {
1435                 /* read from the base image */
1436                 n1 = qcow2_backing_read1(bs->backing->bs, &hd_qiov,
1437                                          offset, cur_bytes);
1438                 if (n1 > 0) {
1439                     QEMUIOVector local_qiov;
1440 
1441                     qemu_iovec_init(&local_qiov, hd_qiov.niov);
1442                     qemu_iovec_concat(&local_qiov, &hd_qiov, 0, n1);
1443 
1444                     BLKDBG_EVENT(bs->file, BLKDBG_READ_BACKING_AIO);
1445                     qemu_co_mutex_unlock(&s->lock);
1446                     ret = bdrv_co_preadv(bs->backing, offset, n1,
1447                                          &local_qiov, 0);
1448                     qemu_co_mutex_lock(&s->lock);
1449 
1450                     qemu_iovec_destroy(&local_qiov);
1451 
1452                     if (ret < 0) {
1453                         goto fail;
1454                     }
1455                 }
1456             } else {
1457                 /* Note: in this case, no need to wait */
1458                 qemu_iovec_memset(&hd_qiov, 0, 0, cur_bytes);
1459             }
1460             break;
1461 
1462         case QCOW2_CLUSTER_ZERO:
1463             qemu_iovec_memset(&hd_qiov, 0, 0, cur_bytes);
1464             break;
1465 
1466         case QCOW2_CLUSTER_COMPRESSED:
1467             /* add AIO support for compressed blocks ? */
1468             ret = qcow2_decompress_cluster(bs, cluster_offset);
1469             if (ret < 0) {
1470                 goto fail;
1471             }
1472 
1473             qemu_iovec_from_buf(&hd_qiov, 0,
1474                                 s->cluster_cache + offset_in_cluster,
1475                                 cur_bytes);
1476             break;
1477 
1478         case QCOW2_CLUSTER_NORMAL:
1479             if ((cluster_offset & 511) != 0) {
1480                 ret = -EIO;
1481                 goto fail;
1482             }
1483 
1484             if (bs->encrypted) {
1485                 assert(s->cipher);
1486 
1487                 /*
1488                  * For encrypted images, read everything into a temporary
1489                  * contiguous buffer on which the AES functions can work.
1490                  */
1491                 if (!cluster_data) {
1492                     cluster_data =
1493                         qemu_try_blockalign(bs->file->bs,
1494                                             QCOW_MAX_CRYPT_CLUSTERS
1495                                             * s->cluster_size);
1496                     if (cluster_data == NULL) {
1497                         ret = -ENOMEM;
1498                         goto fail;
1499                     }
1500                 }
1501 
1502                 assert(cur_bytes <= QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
1503                 qemu_iovec_reset(&hd_qiov);
1504                 qemu_iovec_add(&hd_qiov, cluster_data, cur_bytes);
1505             }
1506 
1507             BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);
1508             qemu_co_mutex_unlock(&s->lock);
1509             ret = bdrv_co_preadv(bs->file,
1510                                  cluster_offset + offset_in_cluster,
1511                                  cur_bytes, &hd_qiov, 0);
1512             qemu_co_mutex_lock(&s->lock);
1513             if (ret < 0) {
1514                 goto fail;
1515             }
1516             if (bs->encrypted) {
1517                 assert(s->cipher);
1518                 assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);
1519                 assert((cur_bytes & (BDRV_SECTOR_SIZE - 1)) == 0);
1520                 Error *err = NULL;
1521                 if (qcow2_encrypt_sectors(s, offset >> BDRV_SECTOR_BITS,
1522                                           cluster_data, cluster_data,
1523                                           cur_bytes >> BDRV_SECTOR_BITS,
1524                                           false, &err) < 0) {
1525                     error_free(err);
1526                     ret = -EIO;
1527                     goto fail;
1528                 }
1529                 qemu_iovec_from_buf(qiov, bytes_done, cluster_data, cur_bytes);
1530             }
1531             break;
1532 
1533         default:
1534             g_assert_not_reached();
1535             ret = -EIO;
1536             goto fail;
1537         }
1538 
1539         bytes -= cur_bytes;
1540         offset += cur_bytes;
1541         bytes_done += cur_bytes;
1542     }
1543     ret = 0;
1544 
1545 fail:
1546     qemu_co_mutex_unlock(&s->lock);
1547 
1548     qemu_iovec_destroy(&hd_qiov);
1549     qemu_vfree(cluster_data);
1550 
1551     return ret;
1552 }
1553 
1554 static coroutine_fn int qcow2_co_pwritev(BlockDriverState *bs, uint64_t offset,
1555                                          uint64_t bytes, QEMUIOVector *qiov,
1556                                          int flags)
1557 {
1558     BDRVQcow2State *s = bs->opaque;
1559     int offset_in_cluster;
1560     int ret;
1561     unsigned int cur_bytes; /* number of sectors in current iteration */
1562     uint64_t cluster_offset;
1563     QEMUIOVector hd_qiov;
1564     uint64_t bytes_done = 0;
1565     uint8_t *cluster_data = NULL;
1566     QCowL2Meta *l2meta = NULL;
1567 
1568     trace_qcow2_writev_start_req(qemu_coroutine_self(), offset, bytes);
1569 
1570     qemu_iovec_init(&hd_qiov, qiov->niov);
1571 
1572     s->cluster_cache_offset = -1; /* disable compressed cache */
1573 
1574     qemu_co_mutex_lock(&s->lock);
1575 
1576     while (bytes != 0) {
1577 
1578         l2meta = NULL;
1579 
1580         trace_qcow2_writev_start_part(qemu_coroutine_self());
1581         offset_in_cluster = offset_into_cluster(s, offset);
1582         cur_bytes = MIN(bytes, INT_MAX);
1583         if (bs->encrypted) {
1584             cur_bytes = MIN(cur_bytes,
1585                             QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size
1586                             - offset_in_cluster);
1587         }
1588 
1589         ret = qcow2_alloc_cluster_offset(bs, offset, &cur_bytes,
1590                                          &cluster_offset, &l2meta);
1591         if (ret < 0) {
1592             goto fail;
1593         }
1594 
1595         assert((cluster_offset & 511) == 0);
1596 
1597         qemu_iovec_reset(&hd_qiov);
1598         qemu_iovec_concat(&hd_qiov, qiov, bytes_done, cur_bytes);
1599 
1600         if (bs->encrypted) {
1601             Error *err = NULL;
1602             assert(s->cipher);
1603             if (!cluster_data) {
1604                 cluster_data = qemu_try_blockalign(bs->file->bs,
1605                                                    QCOW_MAX_CRYPT_CLUSTERS
1606                                                    * s->cluster_size);
1607                 if (cluster_data == NULL) {
1608                     ret = -ENOMEM;
1609                     goto fail;
1610                 }
1611             }
1612 
1613             assert(hd_qiov.size <=
1614                    QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
1615             qemu_iovec_to_buf(&hd_qiov, 0, cluster_data, hd_qiov.size);
1616 
1617             if (qcow2_encrypt_sectors(s, offset >> BDRV_SECTOR_BITS,
1618                                       cluster_data, cluster_data,
1619                                       cur_bytes >>BDRV_SECTOR_BITS,
1620                                       true, &err) < 0) {
1621                 error_free(err);
1622                 ret = -EIO;
1623                 goto fail;
1624             }
1625 
1626             qemu_iovec_reset(&hd_qiov);
1627             qemu_iovec_add(&hd_qiov, cluster_data, cur_bytes);
1628         }
1629 
1630         ret = qcow2_pre_write_overlap_check(bs, 0,
1631                 cluster_offset + offset_in_cluster, cur_bytes);
1632         if (ret < 0) {
1633             goto fail;
1634         }
1635 
1636         qemu_co_mutex_unlock(&s->lock);
1637         BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO);
1638         trace_qcow2_writev_data(qemu_coroutine_self(),
1639                                 cluster_offset + offset_in_cluster);
1640         ret = bdrv_co_pwritev(bs->file,
1641                               cluster_offset + offset_in_cluster,
1642                               cur_bytes, &hd_qiov, 0);
1643         qemu_co_mutex_lock(&s->lock);
1644         if (ret < 0) {
1645             goto fail;
1646         }
1647 
1648         while (l2meta != NULL) {
1649             QCowL2Meta *next;
1650 
1651             ret = qcow2_alloc_cluster_link_l2(bs, l2meta);
1652             if (ret < 0) {
1653                 goto fail;
1654             }
1655 
1656             /* Take the request off the list of running requests */
1657             if (l2meta->nb_clusters != 0) {
1658                 QLIST_REMOVE(l2meta, next_in_flight);
1659             }
1660 
1661             qemu_co_queue_restart_all(&l2meta->dependent_requests);
1662 
1663             next = l2meta->next;
1664             g_free(l2meta);
1665             l2meta = next;
1666         }
1667 
1668         bytes -= cur_bytes;
1669         offset += cur_bytes;
1670         bytes_done += cur_bytes;
1671         trace_qcow2_writev_done_part(qemu_coroutine_self(), cur_bytes);
1672     }
1673     ret = 0;
1674 
1675 fail:
1676     qemu_co_mutex_unlock(&s->lock);
1677 
1678     while (l2meta != NULL) {
1679         QCowL2Meta *next;
1680 
1681         if (l2meta->nb_clusters != 0) {
1682             QLIST_REMOVE(l2meta, next_in_flight);
1683         }
1684         qemu_co_queue_restart_all(&l2meta->dependent_requests);
1685 
1686         next = l2meta->next;
1687         g_free(l2meta);
1688         l2meta = next;
1689     }
1690 
1691     qemu_iovec_destroy(&hd_qiov);
1692     qemu_vfree(cluster_data);
1693     trace_qcow2_writev_done_req(qemu_coroutine_self(), ret);
1694 
1695     return ret;
1696 }
1697 
1698 static int qcow2_inactivate(BlockDriverState *bs)
1699 {
1700     BDRVQcow2State *s = bs->opaque;
1701     int ret, result = 0;
1702 
1703     ret = qcow2_cache_flush(bs, s->l2_table_cache);
1704     if (ret) {
1705         result = ret;
1706         error_report("Failed to flush the L2 table cache: %s",
1707                      strerror(-ret));
1708     }
1709 
1710     ret = qcow2_cache_flush(bs, s->refcount_block_cache);
1711     if (ret) {
1712         result = ret;
1713         error_report("Failed to flush the refcount block cache: %s",
1714                      strerror(-ret));
1715     }
1716 
1717     if (result == 0) {
1718         qcow2_mark_clean(bs);
1719     }
1720 
1721     return result;
1722 }
1723 
1724 static void qcow2_close(BlockDriverState *bs)
1725 {
1726     BDRVQcow2State *s = bs->opaque;
1727     qemu_vfree(s->l1_table);
1728     /* else pre-write overlap checks in cache_destroy may crash */
1729     s->l1_table = NULL;
1730 
1731     if (!(s->flags & BDRV_O_INACTIVE)) {
1732         qcow2_inactivate(bs);
1733     }
1734 
1735     cache_clean_timer_del(bs);
1736     qcow2_cache_destroy(bs, s->l2_table_cache);
1737     qcow2_cache_destroy(bs, s->refcount_block_cache);
1738 
1739     qcrypto_cipher_free(s->cipher);
1740     s->cipher = NULL;
1741 
1742     g_free(s->unknown_header_fields);
1743     cleanup_unknown_header_ext(bs);
1744 
1745     g_free(s->image_backing_file);
1746     g_free(s->image_backing_format);
1747 
1748     g_free(s->cluster_cache);
1749     qemu_vfree(s->cluster_data);
1750     qcow2_refcount_close(bs);
1751     qcow2_free_snapshots(bs);
1752 }
1753 
1754 static void qcow2_invalidate_cache(BlockDriverState *bs, Error **errp)
1755 {
1756     BDRVQcow2State *s = bs->opaque;
1757     int flags = s->flags;
1758     QCryptoCipher *cipher = NULL;
1759     QDict *options;
1760     Error *local_err = NULL;
1761     int ret;
1762 
1763     /*
1764      * Backing files are read-only which makes all of their metadata immutable,
1765      * that means we don't have to worry about reopening them here.
1766      */
1767 
1768     cipher = s->cipher;
1769     s->cipher = NULL;
1770 
1771     qcow2_close(bs);
1772 
1773     memset(s, 0, sizeof(BDRVQcow2State));
1774     options = qdict_clone_shallow(bs->options);
1775 
1776     flags &= ~BDRV_O_INACTIVE;
1777     ret = qcow2_open(bs, options, flags, &local_err);
1778     QDECREF(options);
1779     if (local_err) {
1780         error_propagate(errp, local_err);
1781         error_prepend(errp, "Could not reopen qcow2 layer: ");
1782         bs->drv = NULL;
1783         return;
1784     } else if (ret < 0) {
1785         error_setg_errno(errp, -ret, "Could not reopen qcow2 layer");
1786         bs->drv = NULL;
1787         return;
1788     }
1789 
1790     s->cipher = cipher;
1791 }
1792 
1793 static size_t header_ext_add(char *buf, uint32_t magic, const void *s,
1794     size_t len, size_t buflen)
1795 {
1796     QCowExtension *ext_backing_fmt = (QCowExtension*) buf;
1797     size_t ext_len = sizeof(QCowExtension) + ((len + 7) & ~7);
1798 
1799     if (buflen < ext_len) {
1800         return -ENOSPC;
1801     }
1802 
1803     *ext_backing_fmt = (QCowExtension) {
1804         .magic  = cpu_to_be32(magic),
1805         .len    = cpu_to_be32(len),
1806     };
1807 
1808     if (len) {
1809         memcpy(buf + sizeof(QCowExtension), s, len);
1810     }
1811 
1812     return ext_len;
1813 }
1814 
1815 /*
1816  * Updates the qcow2 header, including the variable length parts of it, i.e.
1817  * the backing file name and all extensions. qcow2 was not designed to allow
1818  * such changes, so if we run out of space (we can only use the first cluster)
1819  * this function may fail.
1820  *
1821  * Returns 0 on success, -errno in error cases.
1822  */
1823 int qcow2_update_header(BlockDriverState *bs)
1824 {
1825     BDRVQcow2State *s = bs->opaque;
1826     QCowHeader *header;
1827     char *buf;
1828     size_t buflen = s->cluster_size;
1829     int ret;
1830     uint64_t total_size;
1831     uint32_t refcount_table_clusters;
1832     size_t header_length;
1833     Qcow2UnknownHeaderExtension *uext;
1834 
1835     buf = qemu_blockalign(bs, buflen);
1836 
1837     /* Header structure */
1838     header = (QCowHeader*) buf;
1839 
1840     if (buflen < sizeof(*header)) {
1841         ret = -ENOSPC;
1842         goto fail;
1843     }
1844 
1845     header_length = sizeof(*header) + s->unknown_header_fields_size;
1846     total_size = bs->total_sectors * BDRV_SECTOR_SIZE;
1847     refcount_table_clusters = s->refcount_table_size >> (s->cluster_bits - 3);
1848 
1849     *header = (QCowHeader) {
1850         /* Version 2 fields */
1851         .magic                  = cpu_to_be32(QCOW_MAGIC),
1852         .version                = cpu_to_be32(s->qcow_version),
1853         .backing_file_offset    = 0,
1854         .backing_file_size      = 0,
1855         .cluster_bits           = cpu_to_be32(s->cluster_bits),
1856         .size                   = cpu_to_be64(total_size),
1857         .crypt_method           = cpu_to_be32(s->crypt_method_header),
1858         .l1_size                = cpu_to_be32(s->l1_size),
1859         .l1_table_offset        = cpu_to_be64(s->l1_table_offset),
1860         .refcount_table_offset  = cpu_to_be64(s->refcount_table_offset),
1861         .refcount_table_clusters = cpu_to_be32(refcount_table_clusters),
1862         .nb_snapshots           = cpu_to_be32(s->nb_snapshots),
1863         .snapshots_offset       = cpu_to_be64(s->snapshots_offset),
1864 
1865         /* Version 3 fields */
1866         .incompatible_features  = cpu_to_be64(s->incompatible_features),
1867         .compatible_features    = cpu_to_be64(s->compatible_features),
1868         .autoclear_features     = cpu_to_be64(s->autoclear_features),
1869         .refcount_order         = cpu_to_be32(s->refcount_order),
1870         .header_length          = cpu_to_be32(header_length),
1871     };
1872 
1873     /* For older versions, write a shorter header */
1874     switch (s->qcow_version) {
1875     case 2:
1876         ret = offsetof(QCowHeader, incompatible_features);
1877         break;
1878     case 3:
1879         ret = sizeof(*header);
1880         break;
1881     default:
1882         ret = -EINVAL;
1883         goto fail;
1884     }
1885 
1886     buf += ret;
1887     buflen -= ret;
1888     memset(buf, 0, buflen);
1889 
1890     /* Preserve any unknown field in the header */
1891     if (s->unknown_header_fields_size) {
1892         if (buflen < s->unknown_header_fields_size) {
1893             ret = -ENOSPC;
1894             goto fail;
1895         }
1896 
1897         memcpy(buf, s->unknown_header_fields, s->unknown_header_fields_size);
1898         buf += s->unknown_header_fields_size;
1899         buflen -= s->unknown_header_fields_size;
1900     }
1901 
1902     /* Backing file format header extension */
1903     if (s->image_backing_format) {
1904         ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BACKING_FORMAT,
1905                              s->image_backing_format,
1906                              strlen(s->image_backing_format),
1907                              buflen);
1908         if (ret < 0) {
1909             goto fail;
1910         }
1911 
1912         buf += ret;
1913         buflen -= ret;
1914     }
1915 
1916     /* Feature table */
1917     if (s->qcow_version >= 3) {
1918         Qcow2Feature features[] = {
1919             {
1920                 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
1921                 .bit  = QCOW2_INCOMPAT_DIRTY_BITNR,
1922                 .name = "dirty bit",
1923             },
1924             {
1925                 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
1926                 .bit  = QCOW2_INCOMPAT_CORRUPT_BITNR,
1927                 .name = "corrupt bit",
1928             },
1929             {
1930                 .type = QCOW2_FEAT_TYPE_COMPATIBLE,
1931                 .bit  = QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR,
1932                 .name = "lazy refcounts",
1933             },
1934         };
1935 
1936         ret = header_ext_add(buf, QCOW2_EXT_MAGIC_FEATURE_TABLE,
1937                              features, sizeof(features), buflen);
1938         if (ret < 0) {
1939             goto fail;
1940         }
1941         buf += ret;
1942         buflen -= ret;
1943     }
1944 
1945     /* Keep unknown header extensions */
1946     QLIST_FOREACH(uext, &s->unknown_header_ext, next) {
1947         ret = header_ext_add(buf, uext->magic, uext->data, uext->len, buflen);
1948         if (ret < 0) {
1949             goto fail;
1950         }
1951 
1952         buf += ret;
1953         buflen -= ret;
1954     }
1955 
1956     /* End of header extensions */
1957     ret = header_ext_add(buf, QCOW2_EXT_MAGIC_END, NULL, 0, buflen);
1958     if (ret < 0) {
1959         goto fail;
1960     }
1961 
1962     buf += ret;
1963     buflen -= ret;
1964 
1965     /* Backing file name */
1966     if (s->image_backing_file) {
1967         size_t backing_file_len = strlen(s->image_backing_file);
1968 
1969         if (buflen < backing_file_len) {
1970             ret = -ENOSPC;
1971             goto fail;
1972         }
1973 
1974         /* Using strncpy is ok here, since buf is not NUL-terminated. */
1975         strncpy(buf, s->image_backing_file, buflen);
1976 
1977         header->backing_file_offset = cpu_to_be64(buf - ((char*) header));
1978         header->backing_file_size   = cpu_to_be32(backing_file_len);
1979     }
1980 
1981     /* Write the new header */
1982     ret = bdrv_pwrite(bs->file, 0, header, s->cluster_size);
1983     if (ret < 0) {
1984         goto fail;
1985     }
1986 
1987     ret = 0;
1988 fail:
1989     qemu_vfree(header);
1990     return ret;
1991 }
1992 
1993 static int qcow2_change_backing_file(BlockDriverState *bs,
1994     const char *backing_file, const char *backing_fmt)
1995 {
1996     BDRVQcow2State *s = bs->opaque;
1997 
1998     if (backing_file && strlen(backing_file) > 1023) {
1999         return -EINVAL;
2000     }
2001 
2002     pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
2003     pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
2004 
2005     g_free(s->image_backing_file);
2006     g_free(s->image_backing_format);
2007 
2008     s->image_backing_file = backing_file ? g_strdup(bs->backing_file) : NULL;
2009     s->image_backing_format = backing_fmt ? g_strdup(bs->backing_format) : NULL;
2010 
2011     return qcow2_update_header(bs);
2012 }
2013 
2014 static int preallocate(BlockDriverState *bs)
2015 {
2016     uint64_t bytes;
2017     uint64_t offset;
2018     uint64_t host_offset = 0;
2019     unsigned int cur_bytes;
2020     int ret;
2021     QCowL2Meta *meta;
2022 
2023     bytes = bdrv_getlength(bs);
2024     offset = 0;
2025 
2026     while (bytes) {
2027         cur_bytes = MIN(bytes, INT_MAX);
2028         ret = qcow2_alloc_cluster_offset(bs, offset, &cur_bytes,
2029                                          &host_offset, &meta);
2030         if (ret < 0) {
2031             return ret;
2032         }
2033 
2034         while (meta) {
2035             QCowL2Meta *next = meta->next;
2036 
2037             ret = qcow2_alloc_cluster_link_l2(bs, meta);
2038             if (ret < 0) {
2039                 qcow2_free_any_clusters(bs, meta->alloc_offset,
2040                                         meta->nb_clusters, QCOW2_DISCARD_NEVER);
2041                 return ret;
2042             }
2043 
2044             /* There are no dependent requests, but we need to remove our
2045              * request from the list of in-flight requests */
2046             QLIST_REMOVE(meta, next_in_flight);
2047 
2048             g_free(meta);
2049             meta = next;
2050         }
2051 
2052         /* TODO Preallocate data if requested */
2053 
2054         bytes -= cur_bytes;
2055         offset += cur_bytes;
2056     }
2057 
2058     /*
2059      * It is expected that the image file is large enough to actually contain
2060      * all of the allocated clusters (otherwise we get failing reads after
2061      * EOF). Extend the image to the last allocated sector.
2062      */
2063     if (host_offset != 0) {
2064         uint8_t data = 0;
2065         ret = bdrv_pwrite(bs->file, (host_offset + cur_bytes) - 1,
2066                           &data, 1);
2067         if (ret < 0) {
2068             return ret;
2069         }
2070     }
2071 
2072     return 0;
2073 }
2074 
2075 static int qcow2_create2(const char *filename, int64_t total_size,
2076                          const char *backing_file, const char *backing_format,
2077                          int flags, size_t cluster_size, PreallocMode prealloc,
2078                          QemuOpts *opts, int version, int refcount_order,
2079                          Error **errp)
2080 {
2081     int cluster_bits;
2082     QDict *options;
2083 
2084     /* Calculate cluster_bits */
2085     cluster_bits = ctz32(cluster_size);
2086     if (cluster_bits < MIN_CLUSTER_BITS || cluster_bits > MAX_CLUSTER_BITS ||
2087         (1 << cluster_bits) != cluster_size)
2088     {
2089         error_setg(errp, "Cluster size must be a power of two between %d and "
2090                    "%dk", 1 << MIN_CLUSTER_BITS, 1 << (MAX_CLUSTER_BITS - 10));
2091         return -EINVAL;
2092     }
2093 
2094     /*
2095      * Open the image file and write a minimal qcow2 header.
2096      *
2097      * We keep things simple and start with a zero-sized image. We also
2098      * do without refcount blocks or a L1 table for now. We'll fix the
2099      * inconsistency later.
2100      *
2101      * We do need a refcount table because growing the refcount table means
2102      * allocating two new refcount blocks - the seconds of which would be at
2103      * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
2104      * size for any qcow2 image.
2105      */
2106     BlockBackend *blk;
2107     QCowHeader *header;
2108     uint64_t* refcount_table;
2109     Error *local_err = NULL;
2110     int ret;
2111 
2112     if (prealloc == PREALLOC_MODE_FULL || prealloc == PREALLOC_MODE_FALLOC) {
2113         /* Note: The following calculation does not need to be exact; if it is a
2114          * bit off, either some bytes will be "leaked" (which is fine) or we
2115          * will need to increase the file size by some bytes (which is fine,
2116          * too, as long as the bulk is allocated here). Therefore, using
2117          * floating point arithmetic is fine. */
2118         int64_t meta_size = 0;
2119         uint64_t nreftablee, nrefblocke, nl1e, nl2e;
2120         int64_t aligned_total_size = align_offset(total_size, cluster_size);
2121         int refblock_bits, refblock_size;
2122         /* refcount entry size in bytes */
2123         double rces = (1 << refcount_order) / 8.;
2124 
2125         /* see qcow2_open() */
2126         refblock_bits = cluster_bits - (refcount_order - 3);
2127         refblock_size = 1 << refblock_bits;
2128 
2129         /* header: 1 cluster */
2130         meta_size += cluster_size;
2131 
2132         /* total size of L2 tables */
2133         nl2e = aligned_total_size / cluster_size;
2134         nl2e = align_offset(nl2e, cluster_size / sizeof(uint64_t));
2135         meta_size += nl2e * sizeof(uint64_t);
2136 
2137         /* total size of L1 tables */
2138         nl1e = nl2e * sizeof(uint64_t) / cluster_size;
2139         nl1e = align_offset(nl1e, cluster_size / sizeof(uint64_t));
2140         meta_size += nl1e * sizeof(uint64_t);
2141 
2142         /* total size of refcount blocks
2143          *
2144          * note: every host cluster is reference-counted, including metadata
2145          * (even refcount blocks are recursively included).
2146          * Let:
2147          *   a = total_size (this is the guest disk size)
2148          *   m = meta size not including refcount blocks and refcount tables
2149          *   c = cluster size
2150          *   y1 = number of refcount blocks entries
2151          *   y2 = meta size including everything
2152          *   rces = refcount entry size in bytes
2153          * then,
2154          *   y1 = (y2 + a)/c
2155          *   y2 = y1 * rces + y1 * rces * sizeof(u64) / c + m
2156          * we can get y1:
2157          *   y1 = (a + m) / (c - rces - rces * sizeof(u64) / c)
2158          */
2159         nrefblocke = (aligned_total_size + meta_size + cluster_size)
2160                    / (cluster_size - rces - rces * sizeof(uint64_t)
2161                                                  / cluster_size);
2162         meta_size += DIV_ROUND_UP(nrefblocke, refblock_size) * cluster_size;
2163 
2164         /* total size of refcount tables */
2165         nreftablee = nrefblocke / refblock_size;
2166         nreftablee = align_offset(nreftablee, cluster_size / sizeof(uint64_t));
2167         meta_size += nreftablee * sizeof(uint64_t);
2168 
2169         qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
2170                             aligned_total_size + meta_size, &error_abort);
2171         qemu_opt_set(opts, BLOCK_OPT_PREALLOC, PreallocMode_lookup[prealloc],
2172                      &error_abort);
2173     }
2174 
2175     ret = bdrv_create_file(filename, opts, &local_err);
2176     if (ret < 0) {
2177         error_propagate(errp, local_err);
2178         return ret;
2179     }
2180 
2181     blk = blk_new_open(filename, NULL, NULL,
2182                        BDRV_O_RDWR | BDRV_O_PROTOCOL, &local_err);
2183     if (blk == NULL) {
2184         error_propagate(errp, local_err);
2185         return -EIO;
2186     }
2187 
2188     blk_set_allow_write_beyond_eof(blk, true);
2189 
2190     /* Write the header */
2191     QEMU_BUILD_BUG_ON((1 << MIN_CLUSTER_BITS) < sizeof(*header));
2192     header = g_malloc0(cluster_size);
2193     *header = (QCowHeader) {
2194         .magic                      = cpu_to_be32(QCOW_MAGIC),
2195         .version                    = cpu_to_be32(version),
2196         .cluster_bits               = cpu_to_be32(cluster_bits),
2197         .size                       = cpu_to_be64(0),
2198         .l1_table_offset            = cpu_to_be64(0),
2199         .l1_size                    = cpu_to_be32(0),
2200         .refcount_table_offset      = cpu_to_be64(cluster_size),
2201         .refcount_table_clusters    = cpu_to_be32(1),
2202         .refcount_order             = cpu_to_be32(refcount_order),
2203         .header_length              = cpu_to_be32(sizeof(*header)),
2204     };
2205 
2206     if (flags & BLOCK_FLAG_ENCRYPT) {
2207         header->crypt_method = cpu_to_be32(QCOW_CRYPT_AES);
2208     } else {
2209         header->crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
2210     }
2211 
2212     if (flags & BLOCK_FLAG_LAZY_REFCOUNTS) {
2213         header->compatible_features |=
2214             cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS);
2215     }
2216 
2217     ret = blk_pwrite(blk, 0, header, cluster_size, 0);
2218     g_free(header);
2219     if (ret < 0) {
2220         error_setg_errno(errp, -ret, "Could not write qcow2 header");
2221         goto out;
2222     }
2223 
2224     /* Write a refcount table with one refcount block */
2225     refcount_table = g_malloc0(2 * cluster_size);
2226     refcount_table[0] = cpu_to_be64(2 * cluster_size);
2227     ret = blk_pwrite(blk, cluster_size, refcount_table, 2 * cluster_size, 0);
2228     g_free(refcount_table);
2229 
2230     if (ret < 0) {
2231         error_setg_errno(errp, -ret, "Could not write refcount table");
2232         goto out;
2233     }
2234 
2235     blk_unref(blk);
2236     blk = NULL;
2237 
2238     /*
2239      * And now open the image and make it consistent first (i.e. increase the
2240      * refcount of the cluster that is occupied by the header and the refcount
2241      * table)
2242      */
2243     options = qdict_new();
2244     qdict_put(options, "driver", qstring_from_str("qcow2"));
2245     blk = blk_new_open(filename, NULL, options,
2246                        BDRV_O_RDWR | BDRV_O_NO_FLUSH, &local_err);
2247     if (blk == NULL) {
2248         error_propagate(errp, local_err);
2249         ret = -EIO;
2250         goto out;
2251     }
2252 
2253     ret = qcow2_alloc_clusters(blk_bs(blk), 3 * cluster_size);
2254     if (ret < 0) {
2255         error_setg_errno(errp, -ret, "Could not allocate clusters for qcow2 "
2256                          "header and refcount table");
2257         goto out;
2258 
2259     } else if (ret != 0) {
2260         error_report("Huh, first cluster in empty image is already in use?");
2261         abort();
2262     }
2263 
2264     /* Create a full header (including things like feature table) */
2265     ret = qcow2_update_header(blk_bs(blk));
2266     if (ret < 0) {
2267         error_setg_errno(errp, -ret, "Could not update qcow2 header");
2268         goto out;
2269     }
2270 
2271     /* Okay, now that we have a valid image, let's give it the right size */
2272     ret = blk_truncate(blk, total_size);
2273     if (ret < 0) {
2274         error_setg_errno(errp, -ret, "Could not resize image");
2275         goto out;
2276     }
2277 
2278     /* Want a backing file? There you go.*/
2279     if (backing_file) {
2280         ret = bdrv_change_backing_file(blk_bs(blk), backing_file, backing_format);
2281         if (ret < 0) {
2282             error_setg_errno(errp, -ret, "Could not assign backing file '%s' "
2283                              "with format '%s'", backing_file, backing_format);
2284             goto out;
2285         }
2286     }
2287 
2288     /* And if we're supposed to preallocate metadata, do that now */
2289     if (prealloc != PREALLOC_MODE_OFF) {
2290         BDRVQcow2State *s = blk_bs(blk)->opaque;
2291         qemu_co_mutex_lock(&s->lock);
2292         ret = preallocate(blk_bs(blk));
2293         qemu_co_mutex_unlock(&s->lock);
2294         if (ret < 0) {
2295             error_setg_errno(errp, -ret, "Could not preallocate metadata");
2296             goto out;
2297         }
2298     }
2299 
2300     blk_unref(blk);
2301     blk = NULL;
2302 
2303     /* Reopen the image without BDRV_O_NO_FLUSH to flush it before returning */
2304     options = qdict_new();
2305     qdict_put(options, "driver", qstring_from_str("qcow2"));
2306     blk = blk_new_open(filename, NULL, options,
2307                        BDRV_O_RDWR | BDRV_O_NO_BACKING, &local_err);
2308     if (blk == NULL) {
2309         error_propagate(errp, local_err);
2310         ret = -EIO;
2311         goto out;
2312     }
2313 
2314     ret = 0;
2315 out:
2316     if (blk) {
2317         blk_unref(blk);
2318     }
2319     return ret;
2320 }
2321 
2322 static int qcow2_create(const char *filename, QemuOpts *opts, Error **errp)
2323 {
2324     char *backing_file = NULL;
2325     char *backing_fmt = NULL;
2326     char *buf = NULL;
2327     uint64_t size = 0;
2328     int flags = 0;
2329     size_t cluster_size = DEFAULT_CLUSTER_SIZE;
2330     PreallocMode prealloc;
2331     int version = 3;
2332     uint64_t refcount_bits = 16;
2333     int refcount_order;
2334     Error *local_err = NULL;
2335     int ret;
2336 
2337     /* Read out options */
2338     size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
2339                     BDRV_SECTOR_SIZE);
2340     backing_file = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
2341     backing_fmt = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FMT);
2342     if (qemu_opt_get_bool_del(opts, BLOCK_OPT_ENCRYPT, false)) {
2343         flags |= BLOCK_FLAG_ENCRYPT;
2344     }
2345     cluster_size = qemu_opt_get_size_del(opts, BLOCK_OPT_CLUSTER_SIZE,
2346                                          DEFAULT_CLUSTER_SIZE);
2347     buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
2348     prealloc = qapi_enum_parse(PreallocMode_lookup, buf,
2349                                PREALLOC_MODE__MAX, PREALLOC_MODE_OFF,
2350                                &local_err);
2351     if (local_err) {
2352         error_propagate(errp, local_err);
2353         ret = -EINVAL;
2354         goto finish;
2355     }
2356     g_free(buf);
2357     buf = qemu_opt_get_del(opts, BLOCK_OPT_COMPAT_LEVEL);
2358     if (!buf) {
2359         /* keep the default */
2360     } else if (!strcmp(buf, "0.10")) {
2361         version = 2;
2362     } else if (!strcmp(buf, "1.1")) {
2363         version = 3;
2364     } else {
2365         error_setg(errp, "Invalid compatibility level: '%s'", buf);
2366         ret = -EINVAL;
2367         goto finish;
2368     }
2369 
2370     if (qemu_opt_get_bool_del(opts, BLOCK_OPT_LAZY_REFCOUNTS, false)) {
2371         flags |= BLOCK_FLAG_LAZY_REFCOUNTS;
2372     }
2373 
2374     if (backing_file && prealloc != PREALLOC_MODE_OFF) {
2375         error_setg(errp, "Backing file and preallocation cannot be used at "
2376                    "the same time");
2377         ret = -EINVAL;
2378         goto finish;
2379     }
2380 
2381     if (version < 3 && (flags & BLOCK_FLAG_LAZY_REFCOUNTS)) {
2382         error_setg(errp, "Lazy refcounts only supported with compatibility "
2383                    "level 1.1 and above (use compat=1.1 or greater)");
2384         ret = -EINVAL;
2385         goto finish;
2386     }
2387 
2388     refcount_bits = qemu_opt_get_number_del(opts, BLOCK_OPT_REFCOUNT_BITS,
2389                                             refcount_bits);
2390     if (refcount_bits > 64 || !is_power_of_2(refcount_bits)) {
2391         error_setg(errp, "Refcount width must be a power of two and may not "
2392                    "exceed 64 bits");
2393         ret = -EINVAL;
2394         goto finish;
2395     }
2396 
2397     if (version < 3 && refcount_bits != 16) {
2398         error_setg(errp, "Different refcount widths than 16 bits require "
2399                    "compatibility level 1.1 or above (use compat=1.1 or "
2400                    "greater)");
2401         ret = -EINVAL;
2402         goto finish;
2403     }
2404 
2405     refcount_order = ctz32(refcount_bits);
2406 
2407     ret = qcow2_create2(filename, size, backing_file, backing_fmt, flags,
2408                         cluster_size, prealloc, opts, version, refcount_order,
2409                         &local_err);
2410     error_propagate(errp, local_err);
2411 
2412 finish:
2413     g_free(backing_file);
2414     g_free(backing_fmt);
2415     g_free(buf);
2416     return ret;
2417 }
2418 
2419 
2420 static bool is_zero_sectors(BlockDriverState *bs, int64_t start,
2421                             uint32_t count)
2422 {
2423     int nr;
2424     BlockDriverState *file;
2425     int64_t res;
2426 
2427     if (!count) {
2428         return true;
2429     }
2430     res = bdrv_get_block_status_above(bs, NULL, start, count,
2431                                       &nr, &file);
2432     return res >= 0 && (res & BDRV_BLOCK_ZERO) && nr == count;
2433 }
2434 
2435 static coroutine_fn int qcow2_co_pwrite_zeroes(BlockDriverState *bs,
2436     int64_t offset, int count, BdrvRequestFlags flags)
2437 {
2438     int ret;
2439     BDRVQcow2State *s = bs->opaque;
2440 
2441     uint32_t head = offset % s->cluster_size;
2442     uint32_t tail = (offset + count) % s->cluster_size;
2443 
2444     trace_qcow2_pwrite_zeroes_start_req(qemu_coroutine_self(), offset, count);
2445 
2446     if (head || tail) {
2447         int64_t cl_start = (offset - head) >> BDRV_SECTOR_BITS;
2448         uint64_t off;
2449         unsigned int nr;
2450 
2451         assert(head + count <= s->cluster_size);
2452 
2453         /* check whether remainder of cluster already reads as zero */
2454         if (!(is_zero_sectors(bs, cl_start,
2455                               DIV_ROUND_UP(head, BDRV_SECTOR_SIZE)) &&
2456               is_zero_sectors(bs, (offset + count) >> BDRV_SECTOR_BITS,
2457                               DIV_ROUND_UP(-tail & (s->cluster_size - 1),
2458                                            BDRV_SECTOR_SIZE)))) {
2459             return -ENOTSUP;
2460         }
2461 
2462         qemu_co_mutex_lock(&s->lock);
2463         /* We can have new write after previous check */
2464         offset = cl_start << BDRV_SECTOR_BITS;
2465         count = s->cluster_size;
2466         nr = s->cluster_size;
2467         ret = qcow2_get_cluster_offset(bs, offset, &nr, &off);
2468         if (ret != QCOW2_CLUSTER_UNALLOCATED && ret != QCOW2_CLUSTER_ZERO) {
2469             qemu_co_mutex_unlock(&s->lock);
2470             return -ENOTSUP;
2471         }
2472     } else {
2473         qemu_co_mutex_lock(&s->lock);
2474     }
2475 
2476     trace_qcow2_pwrite_zeroes(qemu_coroutine_self(), offset, count);
2477 
2478     /* Whatever is left can use real zero clusters */
2479     ret = qcow2_zero_clusters(bs, offset, count >> BDRV_SECTOR_BITS);
2480     qemu_co_mutex_unlock(&s->lock);
2481 
2482     return ret;
2483 }
2484 
2485 static coroutine_fn int qcow2_co_pdiscard(BlockDriverState *bs,
2486                                           int64_t offset, int count)
2487 {
2488     int ret;
2489     BDRVQcow2State *s = bs->opaque;
2490 
2491     qemu_co_mutex_lock(&s->lock);
2492     ret = qcow2_discard_clusters(bs, offset, count >> BDRV_SECTOR_BITS,
2493                                  QCOW2_DISCARD_REQUEST, false);
2494     qemu_co_mutex_unlock(&s->lock);
2495     return ret;
2496 }
2497 
2498 static int qcow2_truncate(BlockDriverState *bs, int64_t offset)
2499 {
2500     BDRVQcow2State *s = bs->opaque;
2501     int64_t new_l1_size;
2502     int ret;
2503 
2504     if (offset & 511) {
2505         error_report("The new size must be a multiple of 512");
2506         return -EINVAL;
2507     }
2508 
2509     /* cannot proceed if image has snapshots */
2510     if (s->nb_snapshots) {
2511         error_report("Can't resize an image which has snapshots");
2512         return -ENOTSUP;
2513     }
2514 
2515     /* shrinking is currently not supported */
2516     if (offset < bs->total_sectors * 512) {
2517         error_report("qcow2 doesn't support shrinking images yet");
2518         return -ENOTSUP;
2519     }
2520 
2521     new_l1_size = size_to_l1(s, offset);
2522     ret = qcow2_grow_l1_table(bs, new_l1_size, true);
2523     if (ret < 0) {
2524         return ret;
2525     }
2526 
2527     /* write updated header.size */
2528     offset = cpu_to_be64(offset);
2529     ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, size),
2530                            &offset, sizeof(uint64_t));
2531     if (ret < 0) {
2532         return ret;
2533     }
2534 
2535     s->l1_vm_state_index = new_l1_size;
2536     return 0;
2537 }
2538 
2539 /* XXX: put compressed sectors first, then all the cluster aligned
2540    tables to avoid losing bytes in alignment */
2541 static coroutine_fn int
2542 qcow2_co_pwritev_compressed(BlockDriverState *bs, uint64_t offset,
2543                             uint64_t bytes, QEMUIOVector *qiov)
2544 {
2545     BDRVQcow2State *s = bs->opaque;
2546     QEMUIOVector hd_qiov;
2547     struct iovec iov;
2548     z_stream strm;
2549     int ret, out_len;
2550     uint8_t *buf, *out_buf;
2551     uint64_t cluster_offset;
2552 
2553     if (bytes == 0) {
2554         /* align end of file to a sector boundary to ease reading with
2555            sector based I/Os */
2556         cluster_offset = bdrv_getlength(bs->file->bs);
2557         return bdrv_truncate(bs->file->bs, cluster_offset);
2558     }
2559 
2560     buf = qemu_blockalign(bs, s->cluster_size);
2561     if (bytes != s->cluster_size) {
2562         if (bytes > s->cluster_size ||
2563             offset + bytes != bs->total_sectors << BDRV_SECTOR_BITS)
2564         {
2565             qemu_vfree(buf);
2566             return -EINVAL;
2567         }
2568         /* Zero-pad last write if image size is not cluster aligned */
2569         memset(buf + bytes, 0, s->cluster_size - bytes);
2570     }
2571     qemu_iovec_to_buf(qiov, 0, buf, bytes);
2572 
2573     out_buf = g_malloc(s->cluster_size);
2574 
2575     /* best compression, small window, no zlib header */
2576     memset(&strm, 0, sizeof(strm));
2577     ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
2578                        Z_DEFLATED, -12,
2579                        9, Z_DEFAULT_STRATEGY);
2580     if (ret != 0) {
2581         ret = -EINVAL;
2582         goto fail;
2583     }
2584 
2585     strm.avail_in = s->cluster_size;
2586     strm.next_in = (uint8_t *)buf;
2587     strm.avail_out = s->cluster_size;
2588     strm.next_out = out_buf;
2589 
2590     ret = deflate(&strm, Z_FINISH);
2591     if (ret != Z_STREAM_END && ret != Z_OK) {
2592         deflateEnd(&strm);
2593         ret = -EINVAL;
2594         goto fail;
2595     }
2596     out_len = strm.next_out - out_buf;
2597 
2598     deflateEnd(&strm);
2599 
2600     if (ret != Z_STREAM_END || out_len >= s->cluster_size) {
2601         /* could not compress: write normal cluster */
2602         ret = qcow2_co_pwritev(bs, offset, bytes, qiov, 0);
2603         if (ret < 0) {
2604             goto fail;
2605         }
2606         goto success;
2607     }
2608 
2609     qemu_co_mutex_lock(&s->lock);
2610     cluster_offset =
2611         qcow2_alloc_compressed_cluster_offset(bs, offset, out_len);
2612     if (!cluster_offset) {
2613         qemu_co_mutex_unlock(&s->lock);
2614         ret = -EIO;
2615         goto fail;
2616     }
2617     cluster_offset &= s->cluster_offset_mask;
2618 
2619     ret = qcow2_pre_write_overlap_check(bs, 0, cluster_offset, out_len);
2620     qemu_co_mutex_unlock(&s->lock);
2621     if (ret < 0) {
2622         goto fail;
2623     }
2624 
2625     iov = (struct iovec) {
2626         .iov_base   = out_buf,
2627         .iov_len    = out_len,
2628     };
2629     qemu_iovec_init_external(&hd_qiov, &iov, 1);
2630 
2631     BLKDBG_EVENT(bs->file, BLKDBG_WRITE_COMPRESSED);
2632     ret = bdrv_co_pwritev(bs->file, cluster_offset, out_len, &hd_qiov, 0);
2633     if (ret < 0) {
2634         goto fail;
2635     }
2636 success:
2637     ret = 0;
2638 fail:
2639     qemu_vfree(buf);
2640     g_free(out_buf);
2641     return ret;
2642 }
2643 
2644 static int make_completely_empty(BlockDriverState *bs)
2645 {
2646     BDRVQcow2State *s = bs->opaque;
2647     int ret, l1_clusters;
2648     int64_t offset;
2649     uint64_t *new_reftable = NULL;
2650     uint64_t rt_entry, l1_size2;
2651     struct {
2652         uint64_t l1_offset;
2653         uint64_t reftable_offset;
2654         uint32_t reftable_clusters;
2655     } QEMU_PACKED l1_ofs_rt_ofs_cls;
2656 
2657     ret = qcow2_cache_empty(bs, s->l2_table_cache);
2658     if (ret < 0) {
2659         goto fail;
2660     }
2661 
2662     ret = qcow2_cache_empty(bs, s->refcount_block_cache);
2663     if (ret < 0) {
2664         goto fail;
2665     }
2666 
2667     /* Refcounts will be broken utterly */
2668     ret = qcow2_mark_dirty(bs);
2669     if (ret < 0) {
2670         goto fail;
2671     }
2672 
2673     BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
2674 
2675     l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / sizeof(uint64_t));
2676     l1_size2 = (uint64_t)s->l1_size * sizeof(uint64_t);
2677 
2678     /* After this call, neither the in-memory nor the on-disk refcount
2679      * information accurately describe the actual references */
2680 
2681     ret = bdrv_pwrite_zeroes(bs->file, s->l1_table_offset,
2682                              l1_clusters * s->cluster_size, 0);
2683     if (ret < 0) {
2684         goto fail_broken_refcounts;
2685     }
2686     memset(s->l1_table, 0, l1_size2);
2687 
2688     BLKDBG_EVENT(bs->file, BLKDBG_EMPTY_IMAGE_PREPARE);
2689 
2690     /* Overwrite enough clusters at the beginning of the sectors to place
2691      * the refcount table, a refcount block and the L1 table in; this may
2692      * overwrite parts of the existing refcount and L1 table, which is not
2693      * an issue because the dirty flag is set, complete data loss is in fact
2694      * desired and partial data loss is consequently fine as well */
2695     ret = bdrv_pwrite_zeroes(bs->file, s->cluster_size,
2696                              (2 + l1_clusters) * s->cluster_size, 0);
2697     /* This call (even if it failed overall) may have overwritten on-disk
2698      * refcount structures; in that case, the in-memory refcount information
2699      * will probably differ from the on-disk information which makes the BDS
2700      * unusable */
2701     if (ret < 0) {
2702         goto fail_broken_refcounts;
2703     }
2704 
2705     BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
2706     BLKDBG_EVENT(bs->file, BLKDBG_REFTABLE_UPDATE);
2707 
2708     /* "Create" an empty reftable (one cluster) directly after the image
2709      * header and an empty L1 table three clusters after the image header;
2710      * the cluster between those two will be used as the first refblock */
2711     l1_ofs_rt_ofs_cls.l1_offset = cpu_to_be64(3 * s->cluster_size);
2712     l1_ofs_rt_ofs_cls.reftable_offset = cpu_to_be64(s->cluster_size);
2713     l1_ofs_rt_ofs_cls.reftable_clusters = cpu_to_be32(1);
2714     ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, l1_table_offset),
2715                            &l1_ofs_rt_ofs_cls, sizeof(l1_ofs_rt_ofs_cls));
2716     if (ret < 0) {
2717         goto fail_broken_refcounts;
2718     }
2719 
2720     s->l1_table_offset = 3 * s->cluster_size;
2721 
2722     new_reftable = g_try_new0(uint64_t, s->cluster_size / sizeof(uint64_t));
2723     if (!new_reftable) {
2724         ret = -ENOMEM;
2725         goto fail_broken_refcounts;
2726     }
2727 
2728     s->refcount_table_offset = s->cluster_size;
2729     s->refcount_table_size   = s->cluster_size / sizeof(uint64_t);
2730 
2731     g_free(s->refcount_table);
2732     s->refcount_table = new_reftable;
2733     new_reftable = NULL;
2734 
2735     /* Now the in-memory refcount information again corresponds to the on-disk
2736      * information (reftable is empty and no refblocks (the refblock cache is
2737      * empty)); however, this means some clusters (e.g. the image header) are
2738      * referenced, but not refcounted, but the normal qcow2 code assumes that
2739      * the in-memory information is always correct */
2740 
2741     BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_ALLOC);
2742 
2743     /* Enter the first refblock into the reftable */
2744     rt_entry = cpu_to_be64(2 * s->cluster_size);
2745     ret = bdrv_pwrite_sync(bs->file, s->cluster_size,
2746                            &rt_entry, sizeof(rt_entry));
2747     if (ret < 0) {
2748         goto fail_broken_refcounts;
2749     }
2750     s->refcount_table[0] = 2 * s->cluster_size;
2751 
2752     s->free_cluster_index = 0;
2753     assert(3 + l1_clusters <= s->refcount_block_size);
2754     offset = qcow2_alloc_clusters(bs, 3 * s->cluster_size + l1_size2);
2755     if (offset < 0) {
2756         ret = offset;
2757         goto fail_broken_refcounts;
2758     } else if (offset > 0) {
2759         error_report("First cluster in emptied image is in use");
2760         abort();
2761     }
2762 
2763     /* Now finally the in-memory information corresponds to the on-disk
2764      * structures and is correct */
2765     ret = qcow2_mark_clean(bs);
2766     if (ret < 0) {
2767         goto fail;
2768     }
2769 
2770     ret = bdrv_truncate(bs->file->bs, (3 + l1_clusters) * s->cluster_size);
2771     if (ret < 0) {
2772         goto fail;
2773     }
2774 
2775     return 0;
2776 
2777 fail_broken_refcounts:
2778     /* The BDS is unusable at this point. If we wanted to make it usable, we
2779      * would have to call qcow2_refcount_close(), qcow2_refcount_init(),
2780      * qcow2_check_refcounts(), qcow2_refcount_close() and qcow2_refcount_init()
2781      * again. However, because the functions which could have caused this error
2782      * path to be taken are used by those functions as well, it's very likely
2783      * that that sequence will fail as well. Therefore, just eject the BDS. */
2784     bs->drv = NULL;
2785 
2786 fail:
2787     g_free(new_reftable);
2788     return ret;
2789 }
2790 
2791 static int qcow2_make_empty(BlockDriverState *bs)
2792 {
2793     BDRVQcow2State *s = bs->opaque;
2794     uint64_t start_sector;
2795     int sector_step = INT_MAX / BDRV_SECTOR_SIZE;
2796     int l1_clusters, ret = 0;
2797 
2798     l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / sizeof(uint64_t));
2799 
2800     if (s->qcow_version >= 3 && !s->snapshots &&
2801         3 + l1_clusters <= s->refcount_block_size) {
2802         /* The following function only works for qcow2 v3 images (it requires
2803          * the dirty flag) and only as long as there are no snapshots (because
2804          * it completely empties the image). Furthermore, the L1 table and three
2805          * additional clusters (image header, refcount table, one refcount
2806          * block) have to fit inside one refcount block. */
2807         return make_completely_empty(bs);
2808     }
2809 
2810     /* This fallback code simply discards every active cluster; this is slow,
2811      * but works in all cases */
2812     for (start_sector = 0; start_sector < bs->total_sectors;
2813          start_sector += sector_step)
2814     {
2815         /* As this function is generally used after committing an external
2816          * snapshot, QCOW2_DISCARD_SNAPSHOT seems appropriate. Also, the
2817          * default action for this kind of discard is to pass the discard,
2818          * which will ideally result in an actually smaller image file, as
2819          * is probably desired. */
2820         ret = qcow2_discard_clusters(bs, start_sector * BDRV_SECTOR_SIZE,
2821                                      MIN(sector_step,
2822                                          bs->total_sectors - start_sector),
2823                                      QCOW2_DISCARD_SNAPSHOT, true);
2824         if (ret < 0) {
2825             break;
2826         }
2827     }
2828 
2829     return ret;
2830 }
2831 
2832 static coroutine_fn int qcow2_co_flush_to_os(BlockDriverState *bs)
2833 {
2834     BDRVQcow2State *s = bs->opaque;
2835     int ret;
2836 
2837     qemu_co_mutex_lock(&s->lock);
2838     ret = qcow2_cache_write(bs, s->l2_table_cache);
2839     if (ret < 0) {
2840         qemu_co_mutex_unlock(&s->lock);
2841         return ret;
2842     }
2843 
2844     if (qcow2_need_accurate_refcounts(s)) {
2845         ret = qcow2_cache_write(bs, s->refcount_block_cache);
2846         if (ret < 0) {
2847             qemu_co_mutex_unlock(&s->lock);
2848             return ret;
2849         }
2850     }
2851     qemu_co_mutex_unlock(&s->lock);
2852 
2853     return 0;
2854 }
2855 
2856 static int qcow2_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
2857 {
2858     BDRVQcow2State *s = bs->opaque;
2859     bdi->unallocated_blocks_are_zero = true;
2860     bdi->can_write_zeroes_with_unmap = (s->qcow_version >= 3);
2861     bdi->cluster_size = s->cluster_size;
2862     bdi->vm_state_offset = qcow2_vm_state_offset(s);
2863     return 0;
2864 }
2865 
2866 static ImageInfoSpecific *qcow2_get_specific_info(BlockDriverState *bs)
2867 {
2868     BDRVQcow2State *s = bs->opaque;
2869     ImageInfoSpecific *spec_info = g_new(ImageInfoSpecific, 1);
2870 
2871     *spec_info = (ImageInfoSpecific){
2872         .type  = IMAGE_INFO_SPECIFIC_KIND_QCOW2,
2873         .u.qcow2.data = g_new(ImageInfoSpecificQCow2, 1),
2874     };
2875     if (s->qcow_version == 2) {
2876         *spec_info->u.qcow2.data = (ImageInfoSpecificQCow2){
2877             .compat             = g_strdup("0.10"),
2878             .refcount_bits      = s->refcount_bits,
2879         };
2880     } else if (s->qcow_version == 3) {
2881         *spec_info->u.qcow2.data = (ImageInfoSpecificQCow2){
2882             .compat             = g_strdup("1.1"),
2883             .lazy_refcounts     = s->compatible_features &
2884                                   QCOW2_COMPAT_LAZY_REFCOUNTS,
2885             .has_lazy_refcounts = true,
2886             .corrupt            = s->incompatible_features &
2887                                   QCOW2_INCOMPAT_CORRUPT,
2888             .has_corrupt        = true,
2889             .refcount_bits      = s->refcount_bits,
2890         };
2891     } else {
2892         /* if this assertion fails, this probably means a new version was
2893          * added without having it covered here */
2894         assert(false);
2895     }
2896 
2897     return spec_info;
2898 }
2899 
2900 #if 0
2901 static void dump_refcounts(BlockDriverState *bs)
2902 {
2903     BDRVQcow2State *s = bs->opaque;
2904     int64_t nb_clusters, k, k1, size;
2905     int refcount;
2906 
2907     size = bdrv_getlength(bs->file->bs);
2908     nb_clusters = size_to_clusters(s, size);
2909     for(k = 0; k < nb_clusters;) {
2910         k1 = k;
2911         refcount = get_refcount(bs, k);
2912         k++;
2913         while (k < nb_clusters && get_refcount(bs, k) == refcount)
2914             k++;
2915         printf("%" PRId64 ": refcount=%d nb=%" PRId64 "\n", k, refcount,
2916                k - k1);
2917     }
2918 }
2919 #endif
2920 
2921 static int qcow2_save_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
2922                               int64_t pos)
2923 {
2924     BDRVQcow2State *s = bs->opaque;
2925 
2926     BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_SAVE);
2927     return bs->drv->bdrv_co_pwritev(bs, qcow2_vm_state_offset(s) + pos,
2928                                     qiov->size, qiov, 0);
2929 }
2930 
2931 static int qcow2_load_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
2932                               int64_t pos)
2933 {
2934     BDRVQcow2State *s = bs->opaque;
2935 
2936     BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_LOAD);
2937     return bs->drv->bdrv_co_preadv(bs, qcow2_vm_state_offset(s) + pos,
2938                                    qiov->size, qiov, 0);
2939 }
2940 
2941 /*
2942  * Downgrades an image's version. To achieve this, any incompatible features
2943  * have to be removed.
2944  */
2945 static int qcow2_downgrade(BlockDriverState *bs, int target_version,
2946                            BlockDriverAmendStatusCB *status_cb, void *cb_opaque)
2947 {
2948     BDRVQcow2State *s = bs->opaque;
2949     int current_version = s->qcow_version;
2950     int ret;
2951 
2952     if (target_version == current_version) {
2953         return 0;
2954     } else if (target_version > current_version) {
2955         return -EINVAL;
2956     } else if (target_version != 2) {
2957         return -EINVAL;
2958     }
2959 
2960     if (s->refcount_order != 4) {
2961         error_report("compat=0.10 requires refcount_bits=16");
2962         return -ENOTSUP;
2963     }
2964 
2965     /* clear incompatible features */
2966     if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
2967         ret = qcow2_mark_clean(bs);
2968         if (ret < 0) {
2969             return ret;
2970         }
2971     }
2972 
2973     /* with QCOW2_INCOMPAT_CORRUPT, it is pretty much impossible to get here in
2974      * the first place; if that happens nonetheless, returning -ENOTSUP is the
2975      * best thing to do anyway */
2976 
2977     if (s->incompatible_features) {
2978         return -ENOTSUP;
2979     }
2980 
2981     /* since we can ignore compatible features, we can set them to 0 as well */
2982     s->compatible_features = 0;
2983     /* if lazy refcounts have been used, they have already been fixed through
2984      * clearing the dirty flag */
2985 
2986     /* clearing autoclear features is trivial */
2987     s->autoclear_features = 0;
2988 
2989     ret = qcow2_expand_zero_clusters(bs, status_cb, cb_opaque);
2990     if (ret < 0) {
2991         return ret;
2992     }
2993 
2994     s->qcow_version = target_version;
2995     ret = qcow2_update_header(bs);
2996     if (ret < 0) {
2997         s->qcow_version = current_version;
2998         return ret;
2999     }
3000     return 0;
3001 }
3002 
3003 typedef enum Qcow2AmendOperation {
3004     /* This is the value Qcow2AmendHelperCBInfo::last_operation will be
3005      * statically initialized to so that the helper CB can discern the first
3006      * invocation from an operation change */
3007     QCOW2_NO_OPERATION = 0,
3008 
3009     QCOW2_CHANGING_REFCOUNT_ORDER,
3010     QCOW2_DOWNGRADING,
3011 } Qcow2AmendOperation;
3012 
3013 typedef struct Qcow2AmendHelperCBInfo {
3014     /* The code coordinating the amend operations should only modify
3015      * these four fields; the rest will be managed by the CB */
3016     BlockDriverAmendStatusCB *original_status_cb;
3017     void *original_cb_opaque;
3018 
3019     Qcow2AmendOperation current_operation;
3020 
3021     /* Total number of operations to perform (only set once) */
3022     int total_operations;
3023 
3024     /* The following fields are managed by the CB */
3025 
3026     /* Number of operations completed */
3027     int operations_completed;
3028 
3029     /* Cumulative offset of all completed operations */
3030     int64_t offset_completed;
3031 
3032     Qcow2AmendOperation last_operation;
3033     int64_t last_work_size;
3034 } Qcow2AmendHelperCBInfo;
3035 
3036 static void qcow2_amend_helper_cb(BlockDriverState *bs,
3037                                   int64_t operation_offset,
3038                                   int64_t operation_work_size, void *opaque)
3039 {
3040     Qcow2AmendHelperCBInfo *info = opaque;
3041     int64_t current_work_size;
3042     int64_t projected_work_size;
3043 
3044     if (info->current_operation != info->last_operation) {
3045         if (info->last_operation != QCOW2_NO_OPERATION) {
3046             info->offset_completed += info->last_work_size;
3047             info->operations_completed++;
3048         }
3049 
3050         info->last_operation = info->current_operation;
3051     }
3052 
3053     assert(info->total_operations > 0);
3054     assert(info->operations_completed < info->total_operations);
3055 
3056     info->last_work_size = operation_work_size;
3057 
3058     current_work_size = info->offset_completed + operation_work_size;
3059 
3060     /* current_work_size is the total work size for (operations_completed + 1)
3061      * operations (which includes this one), so multiply it by the number of
3062      * operations not covered and divide it by the number of operations
3063      * covered to get a projection for the operations not covered */
3064     projected_work_size = current_work_size * (info->total_operations -
3065                                                info->operations_completed - 1)
3066                                             / (info->operations_completed + 1);
3067 
3068     info->original_status_cb(bs, info->offset_completed + operation_offset,
3069                              current_work_size + projected_work_size,
3070                              info->original_cb_opaque);
3071 }
3072 
3073 static int qcow2_amend_options(BlockDriverState *bs, QemuOpts *opts,
3074                                BlockDriverAmendStatusCB *status_cb,
3075                                void *cb_opaque)
3076 {
3077     BDRVQcow2State *s = bs->opaque;
3078     int old_version = s->qcow_version, new_version = old_version;
3079     uint64_t new_size = 0;
3080     const char *backing_file = NULL, *backing_format = NULL;
3081     bool lazy_refcounts = s->use_lazy_refcounts;
3082     const char *compat = NULL;
3083     uint64_t cluster_size = s->cluster_size;
3084     bool encrypt;
3085     int refcount_bits = s->refcount_bits;
3086     int ret;
3087     QemuOptDesc *desc = opts->list->desc;
3088     Qcow2AmendHelperCBInfo helper_cb_info;
3089 
3090     while (desc && desc->name) {
3091         if (!qemu_opt_find(opts, desc->name)) {
3092             /* only change explicitly defined options */
3093             desc++;
3094             continue;
3095         }
3096 
3097         if (!strcmp(desc->name, BLOCK_OPT_COMPAT_LEVEL)) {
3098             compat = qemu_opt_get(opts, BLOCK_OPT_COMPAT_LEVEL);
3099             if (!compat) {
3100                 /* preserve default */
3101             } else if (!strcmp(compat, "0.10")) {
3102                 new_version = 2;
3103             } else if (!strcmp(compat, "1.1")) {
3104                 new_version = 3;
3105             } else {
3106                 error_report("Unknown compatibility level %s", compat);
3107                 return -EINVAL;
3108             }
3109         } else if (!strcmp(desc->name, BLOCK_OPT_PREALLOC)) {
3110             error_report("Cannot change preallocation mode");
3111             return -ENOTSUP;
3112         } else if (!strcmp(desc->name, BLOCK_OPT_SIZE)) {
3113             new_size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, 0);
3114         } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FILE)) {
3115             backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
3116         } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FMT)) {
3117             backing_format = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
3118         } else if (!strcmp(desc->name, BLOCK_OPT_ENCRYPT)) {
3119             encrypt = qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT,
3120                                         !!s->cipher);
3121 
3122             if (encrypt != !!s->cipher) {
3123                 error_report("Changing the encryption flag is not supported");
3124                 return -ENOTSUP;
3125             }
3126         } else if (!strcmp(desc->name, BLOCK_OPT_CLUSTER_SIZE)) {
3127             cluster_size = qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE,
3128                                              cluster_size);
3129             if (cluster_size != s->cluster_size) {
3130                 error_report("Changing the cluster size is not supported");
3131                 return -ENOTSUP;
3132             }
3133         } else if (!strcmp(desc->name, BLOCK_OPT_LAZY_REFCOUNTS)) {
3134             lazy_refcounts = qemu_opt_get_bool(opts, BLOCK_OPT_LAZY_REFCOUNTS,
3135                                                lazy_refcounts);
3136         } else if (!strcmp(desc->name, BLOCK_OPT_REFCOUNT_BITS)) {
3137             refcount_bits = qemu_opt_get_number(opts, BLOCK_OPT_REFCOUNT_BITS,
3138                                                 refcount_bits);
3139 
3140             if (refcount_bits <= 0 || refcount_bits > 64 ||
3141                 !is_power_of_2(refcount_bits))
3142             {
3143                 error_report("Refcount width must be a power of two and may "
3144                              "not exceed 64 bits");
3145                 return -EINVAL;
3146             }
3147         } else {
3148             /* if this point is reached, this probably means a new option was
3149              * added without having it covered here */
3150             abort();
3151         }
3152 
3153         desc++;
3154     }
3155 
3156     helper_cb_info = (Qcow2AmendHelperCBInfo){
3157         .original_status_cb = status_cb,
3158         .original_cb_opaque = cb_opaque,
3159         .total_operations = (new_version < old_version)
3160                           + (s->refcount_bits != refcount_bits)
3161     };
3162 
3163     /* Upgrade first (some features may require compat=1.1) */
3164     if (new_version > old_version) {
3165         s->qcow_version = new_version;
3166         ret = qcow2_update_header(bs);
3167         if (ret < 0) {
3168             s->qcow_version = old_version;
3169             return ret;
3170         }
3171     }
3172 
3173     if (s->refcount_bits != refcount_bits) {
3174         int refcount_order = ctz32(refcount_bits);
3175         Error *local_error = NULL;
3176 
3177         if (new_version < 3 && refcount_bits != 16) {
3178             error_report("Different refcount widths than 16 bits require "
3179                          "compatibility level 1.1 or above (use compat=1.1 or "
3180                          "greater)");
3181             return -EINVAL;
3182         }
3183 
3184         helper_cb_info.current_operation = QCOW2_CHANGING_REFCOUNT_ORDER;
3185         ret = qcow2_change_refcount_order(bs, refcount_order,
3186                                           &qcow2_amend_helper_cb,
3187                                           &helper_cb_info, &local_error);
3188         if (ret < 0) {
3189             error_report_err(local_error);
3190             return ret;
3191         }
3192     }
3193 
3194     if (backing_file || backing_format) {
3195         ret = qcow2_change_backing_file(bs,
3196                     backing_file ?: s->image_backing_file,
3197                     backing_format ?: s->image_backing_format);
3198         if (ret < 0) {
3199             return ret;
3200         }
3201     }
3202 
3203     if (s->use_lazy_refcounts != lazy_refcounts) {
3204         if (lazy_refcounts) {
3205             if (new_version < 3) {
3206                 error_report("Lazy refcounts only supported with compatibility "
3207                              "level 1.1 and above (use compat=1.1 or greater)");
3208                 return -EINVAL;
3209             }
3210             s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
3211             ret = qcow2_update_header(bs);
3212             if (ret < 0) {
3213                 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
3214                 return ret;
3215             }
3216             s->use_lazy_refcounts = true;
3217         } else {
3218             /* make image clean first */
3219             ret = qcow2_mark_clean(bs);
3220             if (ret < 0) {
3221                 return ret;
3222             }
3223             /* now disallow lazy refcounts */
3224             s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
3225             ret = qcow2_update_header(bs);
3226             if (ret < 0) {
3227                 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
3228                 return ret;
3229             }
3230             s->use_lazy_refcounts = false;
3231         }
3232     }
3233 
3234     if (new_size) {
3235         ret = bdrv_truncate(bs, new_size);
3236         if (ret < 0) {
3237             return ret;
3238         }
3239     }
3240 
3241     /* Downgrade last (so unsupported features can be removed before) */
3242     if (new_version < old_version) {
3243         helper_cb_info.current_operation = QCOW2_DOWNGRADING;
3244         ret = qcow2_downgrade(bs, new_version, &qcow2_amend_helper_cb,
3245                               &helper_cb_info);
3246         if (ret < 0) {
3247             return ret;
3248         }
3249     }
3250 
3251     return 0;
3252 }
3253 
3254 /*
3255  * If offset or size are negative, respectively, they will not be included in
3256  * the BLOCK_IMAGE_CORRUPTED event emitted.
3257  * fatal will be ignored for read-only BDS; corruptions found there will always
3258  * be considered non-fatal.
3259  */
3260 void qcow2_signal_corruption(BlockDriverState *bs, bool fatal, int64_t offset,
3261                              int64_t size, const char *message_format, ...)
3262 {
3263     BDRVQcow2State *s = bs->opaque;
3264     const char *node_name;
3265     char *message;
3266     va_list ap;
3267 
3268     fatal = fatal && !bs->read_only;
3269 
3270     if (s->signaled_corruption &&
3271         (!fatal || (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT)))
3272     {
3273         return;
3274     }
3275 
3276     va_start(ap, message_format);
3277     message = g_strdup_vprintf(message_format, ap);
3278     va_end(ap);
3279 
3280     if (fatal) {
3281         fprintf(stderr, "qcow2: Marking image as corrupt: %s; further "
3282                 "corruption events will be suppressed\n", message);
3283     } else {
3284         fprintf(stderr, "qcow2: Image is corrupt: %s; further non-fatal "
3285                 "corruption events will be suppressed\n", message);
3286     }
3287 
3288     node_name = bdrv_get_node_name(bs);
3289     qapi_event_send_block_image_corrupted(bdrv_get_device_name(bs),
3290                                           *node_name != '\0', node_name,
3291                                           message, offset >= 0, offset,
3292                                           size >= 0, size,
3293                                           fatal, &error_abort);
3294     g_free(message);
3295 
3296     if (fatal) {
3297         qcow2_mark_corrupt(bs);
3298         bs->drv = NULL; /* make BDS unusable */
3299     }
3300 
3301     s->signaled_corruption = true;
3302 }
3303 
3304 static QemuOptsList qcow2_create_opts = {
3305     .name = "qcow2-create-opts",
3306     .head = QTAILQ_HEAD_INITIALIZER(qcow2_create_opts.head),
3307     .desc = {
3308         {
3309             .name = BLOCK_OPT_SIZE,
3310             .type = QEMU_OPT_SIZE,
3311             .help = "Virtual disk size"
3312         },
3313         {
3314             .name = BLOCK_OPT_COMPAT_LEVEL,
3315             .type = QEMU_OPT_STRING,
3316             .help = "Compatibility level (0.10 or 1.1)"
3317         },
3318         {
3319             .name = BLOCK_OPT_BACKING_FILE,
3320             .type = QEMU_OPT_STRING,
3321             .help = "File name of a base image"
3322         },
3323         {
3324             .name = BLOCK_OPT_BACKING_FMT,
3325             .type = QEMU_OPT_STRING,
3326             .help = "Image format of the base image"
3327         },
3328         {
3329             .name = BLOCK_OPT_ENCRYPT,
3330             .type = QEMU_OPT_BOOL,
3331             .help = "Encrypt the image",
3332             .def_value_str = "off"
3333         },
3334         {
3335             .name = BLOCK_OPT_CLUSTER_SIZE,
3336             .type = QEMU_OPT_SIZE,
3337             .help = "qcow2 cluster size",
3338             .def_value_str = stringify(DEFAULT_CLUSTER_SIZE)
3339         },
3340         {
3341             .name = BLOCK_OPT_PREALLOC,
3342             .type = QEMU_OPT_STRING,
3343             .help = "Preallocation mode (allowed values: off, metadata, "
3344                     "falloc, full)"
3345         },
3346         {
3347             .name = BLOCK_OPT_LAZY_REFCOUNTS,
3348             .type = QEMU_OPT_BOOL,
3349             .help = "Postpone refcount updates",
3350             .def_value_str = "off"
3351         },
3352         {
3353             .name = BLOCK_OPT_REFCOUNT_BITS,
3354             .type = QEMU_OPT_NUMBER,
3355             .help = "Width of a reference count entry in bits",
3356             .def_value_str = "16"
3357         },
3358         { /* end of list */ }
3359     }
3360 };
3361 
3362 BlockDriver bdrv_qcow2 = {
3363     .format_name        = "qcow2",
3364     .instance_size      = sizeof(BDRVQcow2State),
3365     .bdrv_probe         = qcow2_probe,
3366     .bdrv_open          = qcow2_open,
3367     .bdrv_close         = qcow2_close,
3368     .bdrv_reopen_prepare  = qcow2_reopen_prepare,
3369     .bdrv_reopen_commit   = qcow2_reopen_commit,
3370     .bdrv_reopen_abort    = qcow2_reopen_abort,
3371     .bdrv_join_options    = qcow2_join_options,
3372     .bdrv_create        = qcow2_create,
3373     .bdrv_has_zero_init = bdrv_has_zero_init_1,
3374     .bdrv_co_get_block_status = qcow2_co_get_block_status,
3375     .bdrv_set_key       = qcow2_set_key,
3376 
3377     .bdrv_co_preadv         = qcow2_co_preadv,
3378     .bdrv_co_pwritev        = qcow2_co_pwritev,
3379     .bdrv_co_flush_to_os    = qcow2_co_flush_to_os,
3380 
3381     .bdrv_co_pwrite_zeroes  = qcow2_co_pwrite_zeroes,
3382     .bdrv_co_pdiscard       = qcow2_co_pdiscard,
3383     .bdrv_truncate          = qcow2_truncate,
3384     .bdrv_co_pwritev_compressed = qcow2_co_pwritev_compressed,
3385     .bdrv_make_empty        = qcow2_make_empty,
3386 
3387     .bdrv_snapshot_create   = qcow2_snapshot_create,
3388     .bdrv_snapshot_goto     = qcow2_snapshot_goto,
3389     .bdrv_snapshot_delete   = qcow2_snapshot_delete,
3390     .bdrv_snapshot_list     = qcow2_snapshot_list,
3391     .bdrv_snapshot_load_tmp = qcow2_snapshot_load_tmp,
3392     .bdrv_get_info          = qcow2_get_info,
3393     .bdrv_get_specific_info = qcow2_get_specific_info,
3394 
3395     .bdrv_save_vmstate    = qcow2_save_vmstate,
3396     .bdrv_load_vmstate    = qcow2_load_vmstate,
3397 
3398     .supports_backing           = true,
3399     .bdrv_change_backing_file   = qcow2_change_backing_file,
3400 
3401     .bdrv_refresh_limits        = qcow2_refresh_limits,
3402     .bdrv_invalidate_cache      = qcow2_invalidate_cache,
3403     .bdrv_inactivate            = qcow2_inactivate,
3404 
3405     .create_opts         = &qcow2_create_opts,
3406     .bdrv_check          = qcow2_check,
3407     .bdrv_amend_options  = qcow2_amend_options,
3408 
3409     .bdrv_detach_aio_context  = qcow2_detach_aio_context,
3410     .bdrv_attach_aio_context  = qcow2_attach_aio_context,
3411 };
3412 
3413 static void bdrv_qcow2_init(void)
3414 {
3415     bdrv_register(&bdrv_qcow2);
3416 }
3417 
3418 block_init(bdrv_qcow2_init);
3419