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