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