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