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