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