Add qemu 2.4.0
[kvmfornfv.git] / qemu / block / qcow2.c
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 "block/qcow2.h"
29 #include "qemu/error-report.h"
30 #include "qapi/qmp/qerror.h"
31 #include "qapi/qmp/qbool.h"
32 #include "qapi/util.h"
33 #include "qapi/qmp/types.h"
34 #include "qapi-event.h"
35 #include "trace.h"
36 #include "qemu/option_int.h"
37
38 /*
39   Differences with QCOW:
40
41   - Support for multiple incremental snapshots.
42   - Memory management by reference counts.
43   - Clusters which have a reference count of one have the bit
44     QCOW_OFLAG_COPIED to optimize write performance.
45   - Size of compressed clusters is stored in sectors to reduce bit usage
46     in the cluster offsets.
47   - Support for storing additional data (such as the VM state) in the
48     snapshots.
49   - If a backing store is used, the cluster size is not constrained
50     (could be backported to QCOW).
51   - L2 tables have always a size of one cluster.
52 */
53
54
55 typedef struct {
56     uint32_t magic;
57     uint32_t len;
58 } QEMU_PACKED QCowExtension;
59
60 #define  QCOW2_EXT_MAGIC_END 0
61 #define  QCOW2_EXT_MAGIC_BACKING_FORMAT 0xE2792ACA
62 #define  QCOW2_EXT_MAGIC_FEATURE_TABLE 0x6803f857
63
64 static int qcow2_probe(const uint8_t *buf, int buf_size, const char *filename)
65 {
66     const QCowHeader *cow_header = (const void *)buf;
67
68     if (buf_size >= sizeof(QCowHeader) &&
69         be32_to_cpu(cow_header->magic) == QCOW_MAGIC &&
70         be32_to_cpu(cow_header->version) >= 2)
71         return 100;
72     else
73         return 0;
74 }
75
76
77 /* 
78  * read qcow2 extension and fill bs
79  * start reading from start_offset
80  * finish reading upon magic of value 0 or when end_offset reached
81  * unknown magic is skipped (future extension this version knows nothing about)
82  * return 0 upon success, non-0 otherwise
83  */
84 static int qcow2_read_extensions(BlockDriverState *bs, uint64_t start_offset,
85                                  uint64_t end_offset, void **p_feature_table,
86                                  Error **errp)
87 {
88     BDRVQcowState *s = bs->opaque;
89     QCowExtension ext;
90     uint64_t offset;
91     int ret;
92
93 #ifdef DEBUG_EXT
94     printf("qcow2_read_extensions: start=%ld end=%ld\n", start_offset, end_offset);
95 #endif
96     offset = start_offset;
97     while (offset < end_offset) {
98
99 #ifdef DEBUG_EXT
100         /* Sanity check */
101         if (offset > s->cluster_size)
102             printf("qcow2_read_extension: suspicious offset %lu\n", offset);
103
104         printf("attempting to read extended header in offset %lu\n", offset);
105 #endif
106
107         ret = bdrv_pread(bs->file, offset, &ext, sizeof(ext));
108         if (ret < 0) {
109             error_setg_errno(errp, -ret, "qcow2_read_extension: ERROR: "
110                              "pread fail from offset %" PRIu64, offset);
111             return 1;
112         }
113         be32_to_cpus(&ext.magic);
114         be32_to_cpus(&ext.len);
115         offset += sizeof(ext);
116 #ifdef DEBUG_EXT
117         printf("ext.magic = 0x%x\n", ext.magic);
118 #endif
119         if (offset > end_offset || ext.len > end_offset - offset) {
120             error_setg(errp, "Header extension too large");
121             return -EINVAL;
122         }
123
124         switch (ext.magic) {
125         case QCOW2_EXT_MAGIC_END:
126             return 0;
127
128         case QCOW2_EXT_MAGIC_BACKING_FORMAT:
129             if (ext.len >= sizeof(bs->backing_format)) {
130                 error_setg(errp, "ERROR: ext_backing_format: len=%" PRIu32
131                            " too large (>=%zu)", ext.len,
132                            sizeof(bs->backing_format));
133                 return 2;
134             }
135             ret = bdrv_pread(bs->file, offset, bs->backing_format, ext.len);
136             if (ret < 0) {
137                 error_setg_errno(errp, -ret, "ERROR: ext_backing_format: "
138                                  "Could not read format name");
139                 return 3;
140             }
141             bs->backing_format[ext.len] = '\0';
142             s->image_backing_format = g_strdup(bs->backing_format);
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_setg(errp, QERR_UNKNOWN_BLOCK_FORMAT_FEATURE,
210                bdrv_get_device_or_node_name(bs), "qcow2", 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(BlockDriverState *bs, QemuOpts *opts,
486                              uint64_t *l2_cache_size,
487                              uint64_t *refcount_cache_size, Error **errp)
488 {
489     BDRVQcowState *s = bs->opaque;
490     uint64_t combined_cache_size;
491     bool l2_cache_size_set, refcount_cache_size_set, combined_cache_size_set;
492
493     combined_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_CACHE_SIZE);
494     l2_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_L2_CACHE_SIZE);
495     refcount_cache_size_set = qemu_opt_get(opts, QCOW2_OPT_REFCOUNT_CACHE_SIZE);
496
497     combined_cache_size = qemu_opt_get_size(opts, QCOW2_OPT_CACHE_SIZE, 0);
498     *l2_cache_size = qemu_opt_get_size(opts, QCOW2_OPT_L2_CACHE_SIZE, 0);
499     *refcount_cache_size = qemu_opt_get_size(opts,
500                                              QCOW2_OPT_REFCOUNT_CACHE_SIZE, 0);
501
502     if (combined_cache_size_set) {
503         if (l2_cache_size_set && refcount_cache_size_set) {
504             error_setg(errp, QCOW2_OPT_CACHE_SIZE ", " QCOW2_OPT_L2_CACHE_SIZE
505                        " and " QCOW2_OPT_REFCOUNT_CACHE_SIZE " may not be set "
506                        "the same time");
507             return;
508         } else if (*l2_cache_size > combined_cache_size) {
509             error_setg(errp, QCOW2_OPT_L2_CACHE_SIZE " may not exceed "
510                        QCOW2_OPT_CACHE_SIZE);
511             return;
512         } else if (*refcount_cache_size > combined_cache_size) {
513             error_setg(errp, QCOW2_OPT_REFCOUNT_CACHE_SIZE " may not exceed "
514                        QCOW2_OPT_CACHE_SIZE);
515             return;
516         }
517
518         if (l2_cache_size_set) {
519             *refcount_cache_size = combined_cache_size - *l2_cache_size;
520         } else if (refcount_cache_size_set) {
521             *l2_cache_size = combined_cache_size - *refcount_cache_size;
522         } else {
523             *refcount_cache_size = combined_cache_size
524                                  / (DEFAULT_L2_REFCOUNT_SIZE_RATIO + 1);
525             *l2_cache_size = combined_cache_size - *refcount_cache_size;
526         }
527     } else {
528         if (!l2_cache_size_set && !refcount_cache_size_set) {
529             *l2_cache_size = MAX(DEFAULT_L2_CACHE_BYTE_SIZE,
530                                  (uint64_t)DEFAULT_L2_CACHE_CLUSTERS
531                                  * s->cluster_size);
532             *refcount_cache_size = *l2_cache_size
533                                  / DEFAULT_L2_REFCOUNT_SIZE_RATIO;
534         } else if (!l2_cache_size_set) {
535             *l2_cache_size = *refcount_cache_size
536                            * DEFAULT_L2_REFCOUNT_SIZE_RATIO;
537         } else if (!refcount_cache_size_set) {
538             *refcount_cache_size = *l2_cache_size
539                                  / DEFAULT_L2_REFCOUNT_SIZE_RATIO;
540         }
541     }
542 }
543
544 static int qcow2_open(BlockDriverState *bs, QDict *options, int flags,
545                       Error **errp)
546 {
547     BDRVQcowState *s = bs->opaque;
548     unsigned int len, i;
549     int ret = 0;
550     QCowHeader header;
551     QemuOpts *opts = NULL;
552     Error *local_err = NULL;
553     uint64_t ext_end;
554     uint64_t l1_vm_state_index;
555     const char *opt_overlap_check, *opt_overlap_check_template;
556     int overlap_check_template = 0;
557     uint64_t l2_cache_size, refcount_cache_size;
558
559     ret = bdrv_pread(bs->file, 0, &header, sizeof(header));
560     if (ret < 0) {
561         error_setg_errno(errp, -ret, "Could not read qcow2 header");
562         goto fail;
563     }
564     be32_to_cpus(&header.magic);
565     be32_to_cpus(&header.version);
566     be64_to_cpus(&header.backing_file_offset);
567     be32_to_cpus(&header.backing_file_size);
568     be64_to_cpus(&header.size);
569     be32_to_cpus(&header.cluster_bits);
570     be32_to_cpus(&header.crypt_method);
571     be64_to_cpus(&header.l1_table_offset);
572     be32_to_cpus(&header.l1_size);
573     be64_to_cpus(&header.refcount_table_offset);
574     be32_to_cpus(&header.refcount_table_clusters);
575     be64_to_cpus(&header.snapshots_offset);
576     be32_to_cpus(&header.nb_snapshots);
577
578     if (header.magic != QCOW_MAGIC) {
579         error_setg(errp, "Image is not in qcow2 format");
580         ret = -EINVAL;
581         goto fail;
582     }
583     if (header.version < 2 || header.version > 3) {
584         report_unsupported(bs, errp, "QCOW version %" PRIu32, header.version);
585         ret = -ENOTSUP;
586         goto fail;
587     }
588
589     s->qcow_version = header.version;
590
591     /* Initialise cluster size */
592     if (header.cluster_bits < MIN_CLUSTER_BITS ||
593         header.cluster_bits > MAX_CLUSTER_BITS) {
594         error_setg(errp, "Unsupported cluster size: 2^%" PRIu32,
595                    header.cluster_bits);
596         ret = -EINVAL;
597         goto fail;
598     }
599
600     s->cluster_bits = header.cluster_bits;
601     s->cluster_size = 1 << s->cluster_bits;
602     s->cluster_sectors = 1 << (s->cluster_bits - 9);
603
604     /* Initialise version 3 header fields */
605     if (header.version == 2) {
606         header.incompatible_features    = 0;
607         header.compatible_features      = 0;
608         header.autoclear_features       = 0;
609         header.refcount_order           = 4;
610         header.header_length            = 72;
611     } else {
612         be64_to_cpus(&header.incompatible_features);
613         be64_to_cpus(&header.compatible_features);
614         be64_to_cpus(&header.autoclear_features);
615         be32_to_cpus(&header.refcount_order);
616         be32_to_cpus(&header.header_length);
617
618         if (header.header_length < 104) {
619             error_setg(errp, "qcow2 header too short");
620             ret = -EINVAL;
621             goto fail;
622         }
623     }
624
625     if (header.header_length > s->cluster_size) {
626         error_setg(errp, "qcow2 header exceeds cluster size");
627         ret = -EINVAL;
628         goto fail;
629     }
630
631     if (header.header_length > sizeof(header)) {
632         s->unknown_header_fields_size = header.header_length - sizeof(header);
633         s->unknown_header_fields = g_malloc(s->unknown_header_fields_size);
634         ret = bdrv_pread(bs->file, sizeof(header), s->unknown_header_fields,
635                          s->unknown_header_fields_size);
636         if (ret < 0) {
637             error_setg_errno(errp, -ret, "Could not read unknown qcow2 header "
638                              "fields");
639             goto fail;
640         }
641     }
642
643     if (header.backing_file_offset > s->cluster_size) {
644         error_setg(errp, "Invalid backing file offset");
645         ret = -EINVAL;
646         goto fail;
647     }
648
649     if (header.backing_file_offset) {
650         ext_end = header.backing_file_offset;
651     } else {
652         ext_end = 1 << header.cluster_bits;
653     }
654
655     /* Handle feature bits */
656     s->incompatible_features    = header.incompatible_features;
657     s->compatible_features      = header.compatible_features;
658     s->autoclear_features       = header.autoclear_features;
659
660     if (s->incompatible_features & ~QCOW2_INCOMPAT_MASK) {
661         void *feature_table = NULL;
662         qcow2_read_extensions(bs, header.header_length, ext_end,
663                               &feature_table, NULL);
664         report_unsupported_feature(bs, errp, feature_table,
665                                    s->incompatible_features &
666                                    ~QCOW2_INCOMPAT_MASK);
667         ret = -ENOTSUP;
668         g_free(feature_table);
669         goto fail;
670     }
671
672     if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
673         /* Corrupt images may not be written to unless they are being repaired
674          */
675         if ((flags & BDRV_O_RDWR) && !(flags & BDRV_O_CHECK)) {
676             error_setg(errp, "qcow2: Image is corrupt; cannot be opened "
677                        "read/write");
678             ret = -EACCES;
679             goto fail;
680         }
681     }
682
683     /* Check support for various header values */
684     if (header.refcount_order > 6) {
685         error_setg(errp, "Reference count entry width too large; may not "
686                    "exceed 64 bits");
687         ret = -EINVAL;
688         goto fail;
689     }
690     s->refcount_order = header.refcount_order;
691     s->refcount_bits = 1 << s->refcount_order;
692     s->refcount_max = UINT64_C(1) << (s->refcount_bits - 1);
693     s->refcount_max += s->refcount_max - 1;
694
695     if (header.crypt_method > QCOW_CRYPT_AES) {
696         error_setg(errp, "Unsupported encryption method: %" PRIu32,
697                    header.crypt_method);
698         ret = -EINVAL;
699         goto fail;
700     }
701     if (!qcrypto_cipher_supports(QCRYPTO_CIPHER_ALG_AES_128)) {
702         error_setg(errp, "AES cipher not available");
703         ret = -EINVAL;
704         goto fail;
705     }
706     s->crypt_method_header = header.crypt_method;
707     if (s->crypt_method_header) {
708         bs->encrypted = 1;
709     }
710
711     s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */
712     s->l2_size = 1 << s->l2_bits;
713     /* 2^(s->refcount_order - 3) is the refcount width in bytes */
714     s->refcount_block_bits = s->cluster_bits - (s->refcount_order - 3);
715     s->refcount_block_size = 1 << s->refcount_block_bits;
716     bs->total_sectors = header.size / 512;
717     s->csize_shift = (62 - (s->cluster_bits - 8));
718     s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;
719     s->cluster_offset_mask = (1LL << s->csize_shift) - 1;
720
721     s->refcount_table_offset = header.refcount_table_offset;
722     s->refcount_table_size =
723         header.refcount_table_clusters << (s->cluster_bits - 3);
724
725     if (header.refcount_table_clusters > qcow2_max_refcount_clusters(s)) {
726         error_setg(errp, "Reference count table too large");
727         ret = -EINVAL;
728         goto fail;
729     }
730
731     ret = validate_table_offset(bs, s->refcount_table_offset,
732                                 s->refcount_table_size, sizeof(uint64_t));
733     if (ret < 0) {
734         error_setg(errp, "Invalid reference count table offset");
735         goto fail;
736     }
737
738     /* Snapshot table offset/length */
739     if (header.nb_snapshots > QCOW_MAX_SNAPSHOTS) {
740         error_setg(errp, "Too many snapshots");
741         ret = -EINVAL;
742         goto fail;
743     }
744
745     ret = validate_table_offset(bs, header.snapshots_offset,
746                                 header.nb_snapshots,
747                                 sizeof(QCowSnapshotHeader));
748     if (ret < 0) {
749         error_setg(errp, "Invalid snapshot table offset");
750         goto fail;
751     }
752
753     /* read the level 1 table */
754     if (header.l1_size > QCOW_MAX_L1_SIZE / sizeof(uint64_t)) {
755         error_setg(errp, "Active L1 table too large");
756         ret = -EFBIG;
757         goto fail;
758     }
759     s->l1_size = header.l1_size;
760
761     l1_vm_state_index = size_to_l1(s, header.size);
762     if (l1_vm_state_index > INT_MAX) {
763         error_setg(errp, "Image is too big");
764         ret = -EFBIG;
765         goto fail;
766     }
767     s->l1_vm_state_index = l1_vm_state_index;
768
769     /* the L1 table must contain at least enough entries to put
770        header.size bytes */
771     if (s->l1_size < s->l1_vm_state_index) {
772         error_setg(errp, "L1 table is too small");
773         ret = -EINVAL;
774         goto fail;
775     }
776
777     ret = validate_table_offset(bs, header.l1_table_offset,
778                                 header.l1_size, sizeof(uint64_t));
779     if (ret < 0) {
780         error_setg(errp, "Invalid L1 table offset");
781         goto fail;
782     }
783     s->l1_table_offset = header.l1_table_offset;
784
785
786     if (s->l1_size > 0) {
787         s->l1_table = qemu_try_blockalign(bs->file,
788             align_offset(s->l1_size * sizeof(uint64_t), 512));
789         if (s->l1_table == NULL) {
790             error_setg(errp, "Could not allocate L1 table");
791             ret = -ENOMEM;
792             goto fail;
793         }
794         ret = bdrv_pread(bs->file, s->l1_table_offset, s->l1_table,
795                          s->l1_size * sizeof(uint64_t));
796         if (ret < 0) {
797             error_setg_errno(errp, -ret, "Could not read L1 table");
798             goto fail;
799         }
800         for(i = 0;i < s->l1_size; i++) {
801             be64_to_cpus(&s->l1_table[i]);
802         }
803     }
804
805     /* get L2 table/refcount block cache size from command line options */
806     opts = qemu_opts_create(&qcow2_runtime_opts, NULL, 0, &error_abort);
807     qemu_opts_absorb_qdict(opts, options, &local_err);
808     if (local_err) {
809         error_propagate(errp, local_err);
810         ret = -EINVAL;
811         goto fail;
812     }
813
814     read_cache_sizes(bs, opts, &l2_cache_size, &refcount_cache_size,
815                      &local_err);
816     if (local_err) {
817         error_propagate(errp, local_err);
818         ret = -EINVAL;
819         goto fail;
820     }
821
822     l2_cache_size /= s->cluster_size;
823     if (l2_cache_size < MIN_L2_CACHE_SIZE) {
824         l2_cache_size = MIN_L2_CACHE_SIZE;
825     }
826     if (l2_cache_size > INT_MAX) {
827         error_setg(errp, "L2 cache size too big");
828         ret = -EINVAL;
829         goto fail;
830     }
831
832     refcount_cache_size /= s->cluster_size;
833     if (refcount_cache_size < MIN_REFCOUNT_CACHE_SIZE) {
834         refcount_cache_size = MIN_REFCOUNT_CACHE_SIZE;
835     }
836     if (refcount_cache_size > INT_MAX) {
837         error_setg(errp, "Refcount cache size too big");
838         ret = -EINVAL;
839         goto fail;
840     }
841
842     /* alloc L2 table/refcount block cache */
843     s->l2_table_cache = qcow2_cache_create(bs, l2_cache_size);
844     s->refcount_block_cache = qcow2_cache_create(bs, refcount_cache_size);
845     if (s->l2_table_cache == NULL || s->refcount_block_cache == NULL) {
846         error_setg(errp, "Could not allocate metadata caches");
847         ret = -ENOMEM;
848         goto fail;
849     }
850
851     s->cluster_cache = g_malloc(s->cluster_size);
852     /* one more sector for decompressed data alignment */
853     s->cluster_data = qemu_try_blockalign(bs->file, QCOW_MAX_CRYPT_CLUSTERS
854                                                     * s->cluster_size + 512);
855     if (s->cluster_data == NULL) {
856         error_setg(errp, "Could not allocate temporary cluster buffer");
857         ret = -ENOMEM;
858         goto fail;
859     }
860
861     s->cluster_cache_offset = -1;
862     s->flags = flags;
863
864     ret = qcow2_refcount_init(bs);
865     if (ret != 0) {
866         error_setg_errno(errp, -ret, "Could not initialize refcount handling");
867         goto fail;
868     }
869
870     QLIST_INIT(&s->cluster_allocs);
871     QTAILQ_INIT(&s->discards);
872
873     /* read qcow2 extensions */
874     if (qcow2_read_extensions(bs, header.header_length, ext_end, NULL,
875         &local_err)) {
876         error_propagate(errp, local_err);
877         ret = -EINVAL;
878         goto fail;
879     }
880
881     /* read the backing file name */
882     if (header.backing_file_offset != 0) {
883         len = header.backing_file_size;
884         if (len > MIN(1023, s->cluster_size - header.backing_file_offset) ||
885             len >= sizeof(bs->backing_file)) {
886             error_setg(errp, "Backing file name too long");
887             ret = -EINVAL;
888             goto fail;
889         }
890         ret = bdrv_pread(bs->file, header.backing_file_offset,
891                          bs->backing_file, len);
892         if (ret < 0) {
893             error_setg_errno(errp, -ret, "Could not read backing file name");
894             goto fail;
895         }
896         bs->backing_file[len] = '\0';
897         s->image_backing_file = g_strdup(bs->backing_file);
898     }
899
900     /* Internal snapshots */
901     s->snapshots_offset = header.snapshots_offset;
902     s->nb_snapshots = header.nb_snapshots;
903
904     ret = qcow2_read_snapshots(bs);
905     if (ret < 0) {
906         error_setg_errno(errp, -ret, "Could not read snapshots");
907         goto fail;
908     }
909
910     /* Clear unknown autoclear feature bits */
911     if (!bs->read_only && !(flags & BDRV_O_INCOMING) && s->autoclear_features) {
912         s->autoclear_features = 0;
913         ret = qcow2_update_header(bs);
914         if (ret < 0) {
915             error_setg_errno(errp, -ret, "Could not update qcow2 header");
916             goto fail;
917         }
918     }
919
920     /* Initialise locks */
921     qemu_co_mutex_init(&s->lock);
922
923     /* Repair image if dirty */
924     if (!(flags & (BDRV_O_CHECK | BDRV_O_INCOMING)) && !bs->read_only &&
925         (s->incompatible_features & QCOW2_INCOMPAT_DIRTY)) {
926         BdrvCheckResult result = {0};
927
928         ret = qcow2_check(bs, &result, BDRV_FIX_ERRORS | BDRV_FIX_LEAKS);
929         if (ret < 0) {
930             error_setg_errno(errp, -ret, "Could not repair dirty image");
931             goto fail;
932         }
933     }
934
935     /* Enable lazy_refcounts according to image and command line options */
936     s->use_lazy_refcounts = qemu_opt_get_bool(opts, QCOW2_OPT_LAZY_REFCOUNTS,
937         (s->compatible_features & QCOW2_COMPAT_LAZY_REFCOUNTS));
938
939     s->discard_passthrough[QCOW2_DISCARD_NEVER] = false;
940     s->discard_passthrough[QCOW2_DISCARD_ALWAYS] = true;
941     s->discard_passthrough[QCOW2_DISCARD_REQUEST] =
942         qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_REQUEST,
943                           flags & BDRV_O_UNMAP);
944     s->discard_passthrough[QCOW2_DISCARD_SNAPSHOT] =
945         qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_SNAPSHOT, true);
946     s->discard_passthrough[QCOW2_DISCARD_OTHER] =
947         qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_OTHER, false);
948
949     opt_overlap_check = qemu_opt_get(opts, QCOW2_OPT_OVERLAP);
950     opt_overlap_check_template = qemu_opt_get(opts, QCOW2_OPT_OVERLAP_TEMPLATE);
951     if (opt_overlap_check_template && opt_overlap_check &&
952         strcmp(opt_overlap_check_template, opt_overlap_check))
953     {
954         error_setg(errp, "Conflicting values for qcow2 options '"
955                    QCOW2_OPT_OVERLAP "' ('%s') and '" QCOW2_OPT_OVERLAP_TEMPLATE
956                    "' ('%s')", opt_overlap_check, opt_overlap_check_template);
957         ret = -EINVAL;
958         goto fail;
959     }
960     if (!opt_overlap_check) {
961         opt_overlap_check = opt_overlap_check_template ?: "cached";
962     }
963
964     if (!strcmp(opt_overlap_check, "none")) {
965         overlap_check_template = 0;
966     } else if (!strcmp(opt_overlap_check, "constant")) {
967         overlap_check_template = QCOW2_OL_CONSTANT;
968     } else if (!strcmp(opt_overlap_check, "cached")) {
969         overlap_check_template = QCOW2_OL_CACHED;
970     } else if (!strcmp(opt_overlap_check, "all")) {
971         overlap_check_template = QCOW2_OL_ALL;
972     } else {
973         error_setg(errp, "Unsupported value '%s' for qcow2 option "
974                    "'overlap-check'. Allowed are either of the following: "
975                    "none, constant, cached, all", opt_overlap_check);
976         ret = -EINVAL;
977         goto fail;
978     }
979
980     s->overlap_check = 0;
981     for (i = 0; i < QCOW2_OL_MAX_BITNR; i++) {
982         /* overlap-check defines a template bitmask, but every flag may be
983          * overwritten through the associated boolean option */
984         s->overlap_check |=
985             qemu_opt_get_bool(opts, overlap_bool_option_names[i],
986                               overlap_check_template & (1 << i)) << i;
987     }
988
989     qemu_opts_del(opts);
990     opts = NULL;
991
992     if (s->use_lazy_refcounts && s->qcow_version < 3) {
993         error_setg(errp, "Lazy refcounts require a qcow2 image with at least "
994                    "qemu 1.1 compatibility level");
995         ret = -EINVAL;
996         goto fail;
997     }
998
999 #ifdef DEBUG_ALLOC
1000     {
1001         BdrvCheckResult result = {0};
1002         qcow2_check_refcounts(bs, &result, 0);
1003     }
1004 #endif
1005     return ret;
1006
1007  fail:
1008     qemu_opts_del(opts);
1009     g_free(s->unknown_header_fields);
1010     cleanup_unknown_header_ext(bs);
1011     qcow2_free_snapshots(bs);
1012     qcow2_refcount_close(bs);
1013     qemu_vfree(s->l1_table);
1014     /* else pre-write overlap checks in cache_destroy may crash */
1015     s->l1_table = NULL;
1016     if (s->l2_table_cache) {
1017         qcow2_cache_destroy(bs, s->l2_table_cache);
1018     }
1019     if (s->refcount_block_cache) {
1020         qcow2_cache_destroy(bs, s->refcount_block_cache);
1021     }
1022     g_free(s->cluster_cache);
1023     qemu_vfree(s->cluster_data);
1024     return ret;
1025 }
1026
1027 static void qcow2_refresh_limits(BlockDriverState *bs, Error **errp)
1028 {
1029     BDRVQcowState *s = bs->opaque;
1030
1031     bs->bl.write_zeroes_alignment = s->cluster_sectors;
1032 }
1033
1034 static int qcow2_set_key(BlockDriverState *bs, const char *key)
1035 {
1036     BDRVQcowState *s = bs->opaque;
1037     uint8_t keybuf[16];
1038     int len, i;
1039     Error *err = NULL;
1040
1041     memset(keybuf, 0, 16);
1042     len = strlen(key);
1043     if (len > 16)
1044         len = 16;
1045     /* XXX: we could compress the chars to 7 bits to increase
1046        entropy */
1047     for(i = 0;i < len;i++) {
1048         keybuf[i] = key[i];
1049     }
1050     assert(bs->encrypted);
1051
1052     qcrypto_cipher_free(s->cipher);
1053     s->cipher = qcrypto_cipher_new(
1054         QCRYPTO_CIPHER_ALG_AES_128,
1055         QCRYPTO_CIPHER_MODE_CBC,
1056         keybuf, G_N_ELEMENTS(keybuf),
1057         &err);
1058
1059     if (!s->cipher) {
1060         /* XXX would be nice if errors in this method could
1061          * be properly propagate to the caller. Would need
1062          * the bdrv_set_key() API signature to be fixed. */
1063         error_free(err);
1064         return -1;
1065     }
1066     return 0;
1067 }
1068
1069 /* We have no actual commit/abort logic for qcow2, but we need to write out any
1070  * unwritten data if we reopen read-only. */
1071 static int qcow2_reopen_prepare(BDRVReopenState *state,
1072                                 BlockReopenQueue *queue, Error **errp)
1073 {
1074     int ret;
1075
1076     if ((state->flags & BDRV_O_RDWR) == 0) {
1077         ret = bdrv_flush(state->bs);
1078         if (ret < 0) {
1079             return ret;
1080         }
1081
1082         ret = qcow2_mark_clean(state->bs);
1083         if (ret < 0) {
1084             return ret;
1085         }
1086     }
1087
1088     return 0;
1089 }
1090
1091 static int64_t coroutine_fn qcow2_co_get_block_status(BlockDriverState *bs,
1092         int64_t sector_num, int nb_sectors, int *pnum)
1093 {
1094     BDRVQcowState *s = bs->opaque;
1095     uint64_t cluster_offset;
1096     int index_in_cluster, ret;
1097     int64_t status = 0;
1098
1099     *pnum = nb_sectors;
1100     qemu_co_mutex_lock(&s->lock);
1101     ret = qcow2_get_cluster_offset(bs, sector_num << 9, pnum, &cluster_offset);
1102     qemu_co_mutex_unlock(&s->lock);
1103     if (ret < 0) {
1104         return ret;
1105     }
1106
1107     if (cluster_offset != 0 && ret != QCOW2_CLUSTER_COMPRESSED &&
1108         !s->cipher) {
1109         index_in_cluster = sector_num & (s->cluster_sectors - 1);
1110         cluster_offset |= (index_in_cluster << BDRV_SECTOR_BITS);
1111         status |= BDRV_BLOCK_OFFSET_VALID | cluster_offset;
1112     }
1113     if (ret == QCOW2_CLUSTER_ZERO) {
1114         status |= BDRV_BLOCK_ZERO;
1115     } else if (ret != QCOW2_CLUSTER_UNALLOCATED) {
1116         status |= BDRV_BLOCK_DATA;
1117     }
1118     return status;
1119 }
1120
1121 /* handle reading after the end of the backing file */
1122 int qcow2_backing_read1(BlockDriverState *bs, QEMUIOVector *qiov,
1123                   int64_t sector_num, int nb_sectors)
1124 {
1125     int n1;
1126     if ((sector_num + nb_sectors) <= bs->total_sectors)
1127         return nb_sectors;
1128     if (sector_num >= bs->total_sectors)
1129         n1 = 0;
1130     else
1131         n1 = bs->total_sectors - sector_num;
1132
1133     qemu_iovec_memset(qiov, 512 * n1, 0, 512 * (nb_sectors - n1));
1134
1135     return n1;
1136 }
1137
1138 static coroutine_fn int qcow2_co_readv(BlockDriverState *bs, int64_t sector_num,
1139                           int remaining_sectors, QEMUIOVector *qiov)
1140 {
1141     BDRVQcowState *s = bs->opaque;
1142     int index_in_cluster, n1;
1143     int ret;
1144     int cur_nr_sectors; /* number of sectors in current iteration */
1145     uint64_t cluster_offset = 0;
1146     uint64_t bytes_done = 0;
1147     QEMUIOVector hd_qiov;
1148     uint8_t *cluster_data = NULL;
1149
1150     qemu_iovec_init(&hd_qiov, qiov->niov);
1151
1152     qemu_co_mutex_lock(&s->lock);
1153
1154     while (remaining_sectors != 0) {
1155
1156         /* prepare next request */
1157         cur_nr_sectors = remaining_sectors;
1158         if (s->cipher) {
1159             cur_nr_sectors = MIN(cur_nr_sectors,
1160                 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors);
1161         }
1162
1163         ret = qcow2_get_cluster_offset(bs, sector_num << 9,
1164             &cur_nr_sectors, &cluster_offset);
1165         if (ret < 0) {
1166             goto fail;
1167         }
1168
1169         index_in_cluster = sector_num & (s->cluster_sectors - 1);
1170
1171         qemu_iovec_reset(&hd_qiov);
1172         qemu_iovec_concat(&hd_qiov, qiov, bytes_done,
1173             cur_nr_sectors * 512);
1174
1175         switch (ret) {
1176         case QCOW2_CLUSTER_UNALLOCATED:
1177
1178             if (bs->backing_hd) {
1179                 /* read from the base image */
1180                 n1 = qcow2_backing_read1(bs->backing_hd, &hd_qiov,
1181                     sector_num, cur_nr_sectors);
1182                 if (n1 > 0) {
1183                     QEMUIOVector local_qiov;
1184
1185                     qemu_iovec_init(&local_qiov, hd_qiov.niov);
1186                     qemu_iovec_concat(&local_qiov, &hd_qiov, 0,
1187                                       n1 * BDRV_SECTOR_SIZE);
1188
1189                     BLKDBG_EVENT(bs->file, BLKDBG_READ_BACKING_AIO);
1190                     qemu_co_mutex_unlock(&s->lock);
1191                     ret = bdrv_co_readv(bs->backing_hd, sector_num,
1192                                         n1, &local_qiov);
1193                     qemu_co_mutex_lock(&s->lock);
1194
1195                     qemu_iovec_destroy(&local_qiov);
1196
1197                     if (ret < 0) {
1198                         goto fail;
1199                     }
1200                 }
1201             } else {
1202                 /* Note: in this case, no need to wait */
1203                 qemu_iovec_memset(&hd_qiov, 0, 0, 512 * cur_nr_sectors);
1204             }
1205             break;
1206
1207         case QCOW2_CLUSTER_ZERO:
1208             qemu_iovec_memset(&hd_qiov, 0, 0, 512 * cur_nr_sectors);
1209             break;
1210
1211         case QCOW2_CLUSTER_COMPRESSED:
1212             /* add AIO support for compressed blocks ? */
1213             ret = qcow2_decompress_cluster(bs, cluster_offset);
1214             if (ret < 0) {
1215                 goto fail;
1216             }
1217
1218             qemu_iovec_from_buf(&hd_qiov, 0,
1219                 s->cluster_cache + index_in_cluster * 512,
1220                 512 * cur_nr_sectors);
1221             break;
1222
1223         case QCOW2_CLUSTER_NORMAL:
1224             if ((cluster_offset & 511) != 0) {
1225                 ret = -EIO;
1226                 goto fail;
1227             }
1228
1229             if (bs->encrypted) {
1230                 assert(s->cipher);
1231
1232                 /*
1233                  * For encrypted images, read everything into a temporary
1234                  * contiguous buffer on which the AES functions can work.
1235                  */
1236                 if (!cluster_data) {
1237                     cluster_data =
1238                         qemu_try_blockalign(bs->file, QCOW_MAX_CRYPT_CLUSTERS
1239                                                       * s->cluster_size);
1240                     if (cluster_data == NULL) {
1241                         ret = -ENOMEM;
1242                         goto fail;
1243                     }
1244                 }
1245
1246                 assert(cur_nr_sectors <=
1247                     QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors);
1248                 qemu_iovec_reset(&hd_qiov);
1249                 qemu_iovec_add(&hd_qiov, cluster_data,
1250                     512 * cur_nr_sectors);
1251             }
1252
1253             BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);
1254             qemu_co_mutex_unlock(&s->lock);
1255             ret = bdrv_co_readv(bs->file,
1256                                 (cluster_offset >> 9) + index_in_cluster,
1257                                 cur_nr_sectors, &hd_qiov);
1258             qemu_co_mutex_lock(&s->lock);
1259             if (ret < 0) {
1260                 goto fail;
1261             }
1262             if (bs->encrypted) {
1263                 assert(s->cipher);
1264                 Error *err = NULL;
1265                 if (qcow2_encrypt_sectors(s, sector_num,  cluster_data,
1266                                           cluster_data, cur_nr_sectors, false,
1267                                           &err) < 0) {
1268                     error_free(err);
1269                     ret = -EIO;
1270                     goto fail;
1271                 }
1272                 qemu_iovec_from_buf(qiov, bytes_done,
1273                     cluster_data, 512 * cur_nr_sectors);
1274             }
1275             break;
1276
1277         default:
1278             g_assert_not_reached();
1279             ret = -EIO;
1280             goto fail;
1281         }
1282
1283         remaining_sectors -= cur_nr_sectors;
1284         sector_num += cur_nr_sectors;
1285         bytes_done += cur_nr_sectors * 512;
1286     }
1287     ret = 0;
1288
1289 fail:
1290     qemu_co_mutex_unlock(&s->lock);
1291
1292     qemu_iovec_destroy(&hd_qiov);
1293     qemu_vfree(cluster_data);
1294
1295     return ret;
1296 }
1297
1298 static coroutine_fn int qcow2_co_writev(BlockDriverState *bs,
1299                            int64_t sector_num,
1300                            int remaining_sectors,
1301                            QEMUIOVector *qiov)
1302 {
1303     BDRVQcowState *s = bs->opaque;
1304     int index_in_cluster;
1305     int ret;
1306     int cur_nr_sectors; /* number of sectors in current iteration */
1307     uint64_t cluster_offset;
1308     QEMUIOVector hd_qiov;
1309     uint64_t bytes_done = 0;
1310     uint8_t *cluster_data = NULL;
1311     QCowL2Meta *l2meta = NULL;
1312
1313     trace_qcow2_writev_start_req(qemu_coroutine_self(), sector_num,
1314                                  remaining_sectors);
1315
1316     qemu_iovec_init(&hd_qiov, qiov->niov);
1317
1318     s->cluster_cache_offset = -1; /* disable compressed cache */
1319
1320     qemu_co_mutex_lock(&s->lock);
1321
1322     while (remaining_sectors != 0) {
1323
1324         l2meta = NULL;
1325
1326         trace_qcow2_writev_start_part(qemu_coroutine_self());
1327         index_in_cluster = sector_num & (s->cluster_sectors - 1);
1328         cur_nr_sectors = remaining_sectors;
1329         if (bs->encrypted &&
1330             cur_nr_sectors >
1331             QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors - index_in_cluster) {
1332             cur_nr_sectors =
1333                 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors - index_in_cluster;
1334         }
1335
1336         ret = qcow2_alloc_cluster_offset(bs, sector_num << 9,
1337             &cur_nr_sectors, &cluster_offset, &l2meta);
1338         if (ret < 0) {
1339             goto fail;
1340         }
1341
1342         assert((cluster_offset & 511) == 0);
1343
1344         qemu_iovec_reset(&hd_qiov);
1345         qemu_iovec_concat(&hd_qiov, qiov, bytes_done,
1346             cur_nr_sectors * 512);
1347
1348         if (bs->encrypted) {
1349             Error *err = NULL;
1350             assert(s->cipher);
1351             if (!cluster_data) {
1352                 cluster_data = qemu_try_blockalign(bs->file,
1353                                                    QCOW_MAX_CRYPT_CLUSTERS
1354                                                    * s->cluster_size);
1355                 if (cluster_data == NULL) {
1356                     ret = -ENOMEM;
1357                     goto fail;
1358                 }
1359             }
1360
1361             assert(hd_qiov.size <=
1362                    QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
1363             qemu_iovec_to_buf(&hd_qiov, 0, cluster_data, hd_qiov.size);
1364
1365             if (qcow2_encrypt_sectors(s, sector_num, cluster_data,
1366                                       cluster_data, cur_nr_sectors,
1367                                       true, &err) < 0) {
1368                 error_free(err);
1369                 ret = -EIO;
1370                 goto fail;
1371             }
1372
1373             qemu_iovec_reset(&hd_qiov);
1374             qemu_iovec_add(&hd_qiov, cluster_data,
1375                 cur_nr_sectors * 512);
1376         }
1377
1378         ret = qcow2_pre_write_overlap_check(bs, 0,
1379                 cluster_offset + index_in_cluster * BDRV_SECTOR_SIZE,
1380                 cur_nr_sectors * BDRV_SECTOR_SIZE);
1381         if (ret < 0) {
1382             goto fail;
1383         }
1384
1385         qemu_co_mutex_unlock(&s->lock);
1386         BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO);
1387         trace_qcow2_writev_data(qemu_coroutine_self(),
1388                                 (cluster_offset >> 9) + index_in_cluster);
1389         ret = bdrv_co_writev(bs->file,
1390                              (cluster_offset >> 9) + index_in_cluster,
1391                              cur_nr_sectors, &hd_qiov);
1392         qemu_co_mutex_lock(&s->lock);
1393         if (ret < 0) {
1394             goto fail;
1395         }
1396
1397         while (l2meta != NULL) {
1398             QCowL2Meta *next;
1399
1400             ret = qcow2_alloc_cluster_link_l2(bs, l2meta);
1401             if (ret < 0) {
1402                 goto fail;
1403             }
1404
1405             /* Take the request off the list of running requests */
1406             if (l2meta->nb_clusters != 0) {
1407                 QLIST_REMOVE(l2meta, next_in_flight);
1408             }
1409
1410             qemu_co_queue_restart_all(&l2meta->dependent_requests);
1411
1412             next = l2meta->next;
1413             g_free(l2meta);
1414             l2meta = next;
1415         }
1416
1417         remaining_sectors -= cur_nr_sectors;
1418         sector_num += cur_nr_sectors;
1419         bytes_done += cur_nr_sectors * 512;
1420         trace_qcow2_writev_done_part(qemu_coroutine_self(), cur_nr_sectors);
1421     }
1422     ret = 0;
1423
1424 fail:
1425     qemu_co_mutex_unlock(&s->lock);
1426
1427     while (l2meta != NULL) {
1428         QCowL2Meta *next;
1429
1430         if (l2meta->nb_clusters != 0) {
1431             QLIST_REMOVE(l2meta, next_in_flight);
1432         }
1433         qemu_co_queue_restart_all(&l2meta->dependent_requests);
1434
1435         next = l2meta->next;
1436         g_free(l2meta);
1437         l2meta = next;
1438     }
1439
1440     qemu_iovec_destroy(&hd_qiov);
1441     qemu_vfree(cluster_data);
1442     trace_qcow2_writev_done_req(qemu_coroutine_self(), ret);
1443
1444     return ret;
1445 }
1446
1447 static void qcow2_close(BlockDriverState *bs)
1448 {
1449     BDRVQcowState *s = bs->opaque;
1450     qemu_vfree(s->l1_table);
1451     /* else pre-write overlap checks in cache_destroy may crash */
1452     s->l1_table = NULL;
1453
1454     if (!(bs->open_flags & BDRV_O_INCOMING)) {
1455         int ret1, ret2;
1456
1457         ret1 = qcow2_cache_flush(bs, s->l2_table_cache);
1458         ret2 = qcow2_cache_flush(bs, s->refcount_block_cache);
1459
1460         if (ret1) {
1461             error_report("Failed to flush the L2 table cache: %s",
1462                          strerror(-ret1));
1463         }
1464         if (ret2) {
1465             error_report("Failed to flush the refcount block cache: %s",
1466                          strerror(-ret2));
1467         }
1468
1469         if (!ret1 && !ret2) {
1470             qcow2_mark_clean(bs);
1471         }
1472     }
1473
1474     qcow2_cache_destroy(bs, s->l2_table_cache);
1475     qcow2_cache_destroy(bs, s->refcount_block_cache);
1476
1477     qcrypto_cipher_free(s->cipher);
1478     s->cipher = NULL;
1479
1480     g_free(s->unknown_header_fields);
1481     cleanup_unknown_header_ext(bs);
1482
1483     g_free(s->image_backing_file);
1484     g_free(s->image_backing_format);
1485
1486     g_free(s->cluster_cache);
1487     qemu_vfree(s->cluster_data);
1488     qcow2_refcount_close(bs);
1489     qcow2_free_snapshots(bs);
1490 }
1491
1492 static void qcow2_invalidate_cache(BlockDriverState *bs, Error **errp)
1493 {
1494     BDRVQcowState *s = bs->opaque;
1495     int flags = s->flags;
1496     QCryptoCipher *cipher = NULL;
1497     QDict *options;
1498     Error *local_err = NULL;
1499     int ret;
1500
1501     /*
1502      * Backing files are read-only which makes all of their metadata immutable,
1503      * that means we don't have to worry about reopening them here.
1504      */
1505
1506     cipher = s->cipher;
1507     s->cipher = NULL;
1508
1509     qcow2_close(bs);
1510
1511     bdrv_invalidate_cache(bs->file, &local_err);
1512     if (local_err) {
1513         error_propagate(errp, local_err);
1514         return;
1515     }
1516
1517     memset(s, 0, sizeof(BDRVQcowState));
1518     options = qdict_clone_shallow(bs->options);
1519
1520     ret = qcow2_open(bs, options, flags, &local_err);
1521     QDECREF(options);
1522     if (local_err) {
1523         error_setg(errp, "Could not reopen qcow2 layer: %s",
1524                    error_get_pretty(local_err));
1525         error_free(local_err);
1526         return;
1527     } else if (ret < 0) {
1528         error_setg_errno(errp, -ret, "Could not reopen qcow2 layer");
1529         return;
1530     }
1531
1532     s->cipher = cipher;
1533 }
1534
1535 static size_t header_ext_add(char *buf, uint32_t magic, const void *s,
1536     size_t len, size_t buflen)
1537 {
1538     QCowExtension *ext_backing_fmt = (QCowExtension*) buf;
1539     size_t ext_len = sizeof(QCowExtension) + ((len + 7) & ~7);
1540
1541     if (buflen < ext_len) {
1542         return -ENOSPC;
1543     }
1544
1545     *ext_backing_fmt = (QCowExtension) {
1546         .magic  = cpu_to_be32(magic),
1547         .len    = cpu_to_be32(len),
1548     };
1549     memcpy(buf + sizeof(QCowExtension), s, len);
1550
1551     return ext_len;
1552 }
1553
1554 /*
1555  * Updates the qcow2 header, including the variable length parts of it, i.e.
1556  * the backing file name and all extensions. qcow2 was not designed to allow
1557  * such changes, so if we run out of space (we can only use the first cluster)
1558  * this function may fail.
1559  *
1560  * Returns 0 on success, -errno in error cases.
1561  */
1562 int qcow2_update_header(BlockDriverState *bs)
1563 {
1564     BDRVQcowState *s = bs->opaque;
1565     QCowHeader *header;
1566     char *buf;
1567     size_t buflen = s->cluster_size;
1568     int ret;
1569     uint64_t total_size;
1570     uint32_t refcount_table_clusters;
1571     size_t header_length;
1572     Qcow2UnknownHeaderExtension *uext;
1573
1574     buf = qemu_blockalign(bs, buflen);
1575
1576     /* Header structure */
1577     header = (QCowHeader*) buf;
1578
1579     if (buflen < sizeof(*header)) {
1580         ret = -ENOSPC;
1581         goto fail;
1582     }
1583
1584     header_length = sizeof(*header) + s->unknown_header_fields_size;
1585     total_size = bs->total_sectors * BDRV_SECTOR_SIZE;
1586     refcount_table_clusters = s->refcount_table_size >> (s->cluster_bits - 3);
1587
1588     *header = (QCowHeader) {
1589         /* Version 2 fields */
1590         .magic                  = cpu_to_be32(QCOW_MAGIC),
1591         .version                = cpu_to_be32(s->qcow_version),
1592         .backing_file_offset    = 0,
1593         .backing_file_size      = 0,
1594         .cluster_bits           = cpu_to_be32(s->cluster_bits),
1595         .size                   = cpu_to_be64(total_size),
1596         .crypt_method           = cpu_to_be32(s->crypt_method_header),
1597         .l1_size                = cpu_to_be32(s->l1_size),
1598         .l1_table_offset        = cpu_to_be64(s->l1_table_offset),
1599         .refcount_table_offset  = cpu_to_be64(s->refcount_table_offset),
1600         .refcount_table_clusters = cpu_to_be32(refcount_table_clusters),
1601         .nb_snapshots           = cpu_to_be32(s->nb_snapshots),
1602         .snapshots_offset       = cpu_to_be64(s->snapshots_offset),
1603
1604         /* Version 3 fields */
1605         .incompatible_features  = cpu_to_be64(s->incompatible_features),
1606         .compatible_features    = cpu_to_be64(s->compatible_features),
1607         .autoclear_features     = cpu_to_be64(s->autoclear_features),
1608         .refcount_order         = cpu_to_be32(s->refcount_order),
1609         .header_length          = cpu_to_be32(header_length),
1610     };
1611
1612     /* For older versions, write a shorter header */
1613     switch (s->qcow_version) {
1614     case 2:
1615         ret = offsetof(QCowHeader, incompatible_features);
1616         break;
1617     case 3:
1618         ret = sizeof(*header);
1619         break;
1620     default:
1621         ret = -EINVAL;
1622         goto fail;
1623     }
1624
1625     buf += ret;
1626     buflen -= ret;
1627     memset(buf, 0, buflen);
1628
1629     /* Preserve any unknown field in the header */
1630     if (s->unknown_header_fields_size) {
1631         if (buflen < s->unknown_header_fields_size) {
1632             ret = -ENOSPC;
1633             goto fail;
1634         }
1635
1636         memcpy(buf, s->unknown_header_fields, s->unknown_header_fields_size);
1637         buf += s->unknown_header_fields_size;
1638         buflen -= s->unknown_header_fields_size;
1639     }
1640
1641     /* Backing file format header extension */
1642     if (s->image_backing_format) {
1643         ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BACKING_FORMAT,
1644                              s->image_backing_format,
1645                              strlen(s->image_backing_format),
1646                              buflen);
1647         if (ret < 0) {
1648             goto fail;
1649         }
1650
1651         buf += ret;
1652         buflen -= ret;
1653     }
1654
1655     /* Feature table */
1656     Qcow2Feature features[] = {
1657         {
1658             .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
1659             .bit  = QCOW2_INCOMPAT_DIRTY_BITNR,
1660             .name = "dirty bit",
1661         },
1662         {
1663             .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
1664             .bit  = QCOW2_INCOMPAT_CORRUPT_BITNR,
1665             .name = "corrupt bit",
1666         },
1667         {
1668             .type = QCOW2_FEAT_TYPE_COMPATIBLE,
1669             .bit  = QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR,
1670             .name = "lazy refcounts",
1671         },
1672     };
1673
1674     ret = header_ext_add(buf, QCOW2_EXT_MAGIC_FEATURE_TABLE,
1675                          features, sizeof(features), buflen);
1676     if (ret < 0) {
1677         goto fail;
1678     }
1679     buf += ret;
1680     buflen -= ret;
1681
1682     /* Keep unknown header extensions */
1683     QLIST_FOREACH(uext, &s->unknown_header_ext, next) {
1684         ret = header_ext_add(buf, uext->magic, uext->data, uext->len, buflen);
1685         if (ret < 0) {
1686             goto fail;
1687         }
1688
1689         buf += ret;
1690         buflen -= ret;
1691     }
1692
1693     /* End of header extensions */
1694     ret = header_ext_add(buf, QCOW2_EXT_MAGIC_END, NULL, 0, buflen);
1695     if (ret < 0) {
1696         goto fail;
1697     }
1698
1699     buf += ret;
1700     buflen -= ret;
1701
1702     /* Backing file name */
1703     if (s->image_backing_file) {
1704         size_t backing_file_len = strlen(s->image_backing_file);
1705
1706         if (buflen < backing_file_len) {
1707             ret = -ENOSPC;
1708             goto fail;
1709         }
1710
1711         /* Using strncpy is ok here, since buf is not NUL-terminated. */
1712         strncpy(buf, s->image_backing_file, buflen);
1713
1714         header->backing_file_offset = cpu_to_be64(buf - ((char*) header));
1715         header->backing_file_size   = cpu_to_be32(backing_file_len);
1716     }
1717
1718     /* Write the new header */
1719     ret = bdrv_pwrite(bs->file, 0, header, s->cluster_size);
1720     if (ret < 0) {
1721         goto fail;
1722     }
1723
1724     ret = 0;
1725 fail:
1726     qemu_vfree(header);
1727     return ret;
1728 }
1729
1730 static int qcow2_change_backing_file(BlockDriverState *bs,
1731     const char *backing_file, const char *backing_fmt)
1732 {
1733     BDRVQcowState *s = bs->opaque;
1734
1735     pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
1736     pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
1737
1738     g_free(s->image_backing_file);
1739     g_free(s->image_backing_format);
1740
1741     s->image_backing_file = backing_file ? g_strdup(bs->backing_file) : NULL;
1742     s->image_backing_format = backing_fmt ? g_strdup(bs->backing_format) : NULL;
1743
1744     return qcow2_update_header(bs);
1745 }
1746
1747 static int preallocate(BlockDriverState *bs)
1748 {
1749     uint64_t nb_sectors;
1750     uint64_t offset;
1751     uint64_t host_offset = 0;
1752     int num;
1753     int ret;
1754     QCowL2Meta *meta;
1755
1756     nb_sectors = bdrv_nb_sectors(bs);
1757     offset = 0;
1758
1759     while (nb_sectors) {
1760         num = MIN(nb_sectors, INT_MAX >> BDRV_SECTOR_BITS);
1761         ret = qcow2_alloc_cluster_offset(bs, offset, &num,
1762                                          &host_offset, &meta);
1763         if (ret < 0) {
1764             return ret;
1765         }
1766
1767         while (meta) {
1768             QCowL2Meta *next = meta->next;
1769
1770             ret = qcow2_alloc_cluster_link_l2(bs, meta);
1771             if (ret < 0) {
1772                 qcow2_free_any_clusters(bs, meta->alloc_offset,
1773                                         meta->nb_clusters, QCOW2_DISCARD_NEVER);
1774                 return ret;
1775             }
1776
1777             /* There are no dependent requests, but we need to remove our
1778              * request from the list of in-flight requests */
1779             QLIST_REMOVE(meta, next_in_flight);
1780
1781             g_free(meta);
1782             meta = next;
1783         }
1784
1785         /* TODO Preallocate data if requested */
1786
1787         nb_sectors -= num;
1788         offset += num << BDRV_SECTOR_BITS;
1789     }
1790
1791     /*
1792      * It is expected that the image file is large enough to actually contain
1793      * all of the allocated clusters (otherwise we get failing reads after
1794      * EOF). Extend the image to the last allocated sector.
1795      */
1796     if (host_offset != 0) {
1797         uint8_t buf[BDRV_SECTOR_SIZE];
1798         memset(buf, 0, BDRV_SECTOR_SIZE);
1799         ret = bdrv_write(bs->file, (host_offset >> BDRV_SECTOR_BITS) + num - 1,
1800                          buf, 1);
1801         if (ret < 0) {
1802             return ret;
1803         }
1804     }
1805
1806     return 0;
1807 }
1808
1809 static int qcow2_create2(const char *filename, int64_t total_size,
1810                          const char *backing_file, const char *backing_format,
1811                          int flags, size_t cluster_size, PreallocMode prealloc,
1812                          QemuOpts *opts, int version, int refcount_order,
1813                          Error **errp)
1814 {
1815     /* Calculate cluster_bits */
1816     int cluster_bits;
1817     cluster_bits = ctz32(cluster_size);
1818     if (cluster_bits < MIN_CLUSTER_BITS || cluster_bits > MAX_CLUSTER_BITS ||
1819         (1 << cluster_bits) != cluster_size)
1820     {
1821         error_setg(errp, "Cluster size must be a power of two between %d and "
1822                    "%dk", 1 << MIN_CLUSTER_BITS, 1 << (MAX_CLUSTER_BITS - 10));
1823         return -EINVAL;
1824     }
1825
1826     /*
1827      * Open the image file and write a minimal qcow2 header.
1828      *
1829      * We keep things simple and start with a zero-sized image. We also
1830      * do without refcount blocks or a L1 table for now. We'll fix the
1831      * inconsistency later.
1832      *
1833      * We do need a refcount table because growing the refcount table means
1834      * allocating two new refcount blocks - the seconds of which would be at
1835      * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
1836      * size for any qcow2 image.
1837      */
1838     BlockDriverState* bs;
1839     QCowHeader *header;
1840     uint64_t* refcount_table;
1841     Error *local_err = NULL;
1842     int ret;
1843
1844     if (prealloc == PREALLOC_MODE_FULL || prealloc == PREALLOC_MODE_FALLOC) {
1845         /* Note: The following calculation does not need to be exact; if it is a
1846          * bit off, either some bytes will be "leaked" (which is fine) or we
1847          * will need to increase the file size by some bytes (which is fine,
1848          * too, as long as the bulk is allocated here). Therefore, using
1849          * floating point arithmetic is fine. */
1850         int64_t meta_size = 0;
1851         uint64_t nreftablee, nrefblocke, nl1e, nl2e;
1852         int64_t aligned_total_size = align_offset(total_size, cluster_size);
1853         int refblock_bits, refblock_size;
1854         /* refcount entry size in bytes */
1855         double rces = (1 << refcount_order) / 8.;
1856
1857         /* see qcow2_open() */
1858         refblock_bits = cluster_bits - (refcount_order - 3);
1859         refblock_size = 1 << refblock_bits;
1860
1861         /* header: 1 cluster */
1862         meta_size += cluster_size;
1863
1864         /* total size of L2 tables */
1865         nl2e = aligned_total_size / cluster_size;
1866         nl2e = align_offset(nl2e, cluster_size / sizeof(uint64_t));
1867         meta_size += nl2e * sizeof(uint64_t);
1868
1869         /* total size of L1 tables */
1870         nl1e = nl2e * sizeof(uint64_t) / cluster_size;
1871         nl1e = align_offset(nl1e, cluster_size / sizeof(uint64_t));
1872         meta_size += nl1e * sizeof(uint64_t);
1873
1874         /* total size of refcount blocks
1875          *
1876          * note: every host cluster is reference-counted, including metadata
1877          * (even refcount blocks are recursively included).
1878          * Let:
1879          *   a = total_size (this is the guest disk size)
1880          *   m = meta size not including refcount blocks and refcount tables
1881          *   c = cluster size
1882          *   y1 = number of refcount blocks entries
1883          *   y2 = meta size including everything
1884          *   rces = refcount entry size in bytes
1885          * then,
1886          *   y1 = (y2 + a)/c
1887          *   y2 = y1 * rces + y1 * rces * sizeof(u64) / c + m
1888          * we can get y1:
1889          *   y1 = (a + m) / (c - rces - rces * sizeof(u64) / c)
1890          */
1891         nrefblocke = (aligned_total_size + meta_size + cluster_size)
1892                    / (cluster_size - rces - rces * sizeof(uint64_t)
1893                                                  / cluster_size);
1894         meta_size += DIV_ROUND_UP(nrefblocke, refblock_size) * cluster_size;
1895
1896         /* total size of refcount tables */
1897         nreftablee = nrefblocke / refblock_size;
1898         nreftablee = align_offset(nreftablee, cluster_size / sizeof(uint64_t));
1899         meta_size += nreftablee * sizeof(uint64_t);
1900
1901         qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
1902                             aligned_total_size + meta_size, &error_abort);
1903         qemu_opt_set(opts, BLOCK_OPT_PREALLOC, PreallocMode_lookup[prealloc],
1904                      &error_abort);
1905     }
1906
1907     ret = bdrv_create_file(filename, opts, &local_err);
1908     if (ret < 0) {
1909         error_propagate(errp, local_err);
1910         return ret;
1911     }
1912
1913     bs = NULL;
1914     ret = bdrv_open(&bs, filename, NULL, NULL, BDRV_O_RDWR | BDRV_O_PROTOCOL,
1915                     NULL, &local_err);
1916     if (ret < 0) {
1917         error_propagate(errp, local_err);
1918         return ret;
1919     }
1920
1921     /* Write the header */
1922     QEMU_BUILD_BUG_ON((1 << MIN_CLUSTER_BITS) < sizeof(*header));
1923     header = g_malloc0(cluster_size);
1924     *header = (QCowHeader) {
1925         .magic                      = cpu_to_be32(QCOW_MAGIC),
1926         .version                    = cpu_to_be32(version),
1927         .cluster_bits               = cpu_to_be32(cluster_bits),
1928         .size                       = cpu_to_be64(0),
1929         .l1_table_offset            = cpu_to_be64(0),
1930         .l1_size                    = cpu_to_be32(0),
1931         .refcount_table_offset      = cpu_to_be64(cluster_size),
1932         .refcount_table_clusters    = cpu_to_be32(1),
1933         .refcount_order             = cpu_to_be32(refcount_order),
1934         .header_length              = cpu_to_be32(sizeof(*header)),
1935     };
1936
1937     if (flags & BLOCK_FLAG_ENCRYPT) {
1938         header->crypt_method = cpu_to_be32(QCOW_CRYPT_AES);
1939     } else {
1940         header->crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
1941     }
1942
1943     if (flags & BLOCK_FLAG_LAZY_REFCOUNTS) {
1944         header->compatible_features |=
1945             cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS);
1946     }
1947
1948     ret = bdrv_pwrite(bs, 0, header, cluster_size);
1949     g_free(header);
1950     if (ret < 0) {
1951         error_setg_errno(errp, -ret, "Could not write qcow2 header");
1952         goto out;
1953     }
1954
1955     /* Write a refcount table with one refcount block */
1956     refcount_table = g_malloc0(2 * cluster_size);
1957     refcount_table[0] = cpu_to_be64(2 * cluster_size);
1958     ret = bdrv_pwrite(bs, cluster_size, refcount_table, 2 * cluster_size);
1959     g_free(refcount_table);
1960
1961     if (ret < 0) {
1962         error_setg_errno(errp, -ret, "Could not write refcount table");
1963         goto out;
1964     }
1965
1966     bdrv_unref(bs);
1967     bs = NULL;
1968
1969     /*
1970      * And now open the image and make it consistent first (i.e. increase the
1971      * refcount of the cluster that is occupied by the header and the refcount
1972      * table)
1973      */
1974     ret = bdrv_open(&bs, filename, NULL, NULL,
1975                     BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_NO_FLUSH,
1976                     &bdrv_qcow2, &local_err);
1977     if (ret < 0) {
1978         error_propagate(errp, local_err);
1979         goto out;
1980     }
1981
1982     ret = qcow2_alloc_clusters(bs, 3 * cluster_size);
1983     if (ret < 0) {
1984         error_setg_errno(errp, -ret, "Could not allocate clusters for qcow2 "
1985                          "header and refcount table");
1986         goto out;
1987
1988     } else if (ret != 0) {
1989         error_report("Huh, first cluster in empty image is already in use?");
1990         abort();
1991     }
1992
1993     /* Okay, now that we have a valid image, let's give it the right size */
1994     ret = bdrv_truncate(bs, total_size);
1995     if (ret < 0) {
1996         error_setg_errno(errp, -ret, "Could not resize image");
1997         goto out;
1998     }
1999
2000     /* Want a backing file? There you go.*/
2001     if (backing_file) {
2002         ret = bdrv_change_backing_file(bs, backing_file, backing_format);
2003         if (ret < 0) {
2004             error_setg_errno(errp, -ret, "Could not assign backing file '%s' "
2005                              "with format '%s'", backing_file, backing_format);
2006             goto out;
2007         }
2008     }
2009
2010     /* And if we're supposed to preallocate metadata, do that now */
2011     if (prealloc != PREALLOC_MODE_OFF) {
2012         BDRVQcowState *s = bs->opaque;
2013         qemu_co_mutex_lock(&s->lock);
2014         ret = preallocate(bs);
2015         qemu_co_mutex_unlock(&s->lock);
2016         if (ret < 0) {
2017             error_setg_errno(errp, -ret, "Could not preallocate metadata");
2018             goto out;
2019         }
2020     }
2021
2022     bdrv_unref(bs);
2023     bs = NULL;
2024
2025     /* Reopen the image without BDRV_O_NO_FLUSH to flush it before returning */
2026     ret = bdrv_open(&bs, filename, NULL, NULL,
2027                     BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_NO_BACKING,
2028                     &bdrv_qcow2, &local_err);
2029     if (local_err) {
2030         error_propagate(errp, local_err);
2031         goto out;
2032     }
2033
2034     ret = 0;
2035 out:
2036     if (bs) {
2037         bdrv_unref(bs);
2038     }
2039     return ret;
2040 }
2041
2042 static int qcow2_create(const char *filename, QemuOpts *opts, Error **errp)
2043 {
2044     char *backing_file = NULL;
2045     char *backing_fmt = NULL;
2046     char *buf = NULL;
2047     uint64_t size = 0;
2048     int flags = 0;
2049     size_t cluster_size = DEFAULT_CLUSTER_SIZE;
2050     PreallocMode prealloc;
2051     int version = 3;
2052     uint64_t refcount_bits = 16;
2053     int refcount_order;
2054     Error *local_err = NULL;
2055     int ret;
2056
2057     /* Read out options */
2058     size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
2059                     BDRV_SECTOR_SIZE);
2060     backing_file = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
2061     backing_fmt = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FMT);
2062     if (qemu_opt_get_bool_del(opts, BLOCK_OPT_ENCRYPT, false)) {
2063         flags |= BLOCK_FLAG_ENCRYPT;
2064     }
2065     cluster_size = qemu_opt_get_size_del(opts, BLOCK_OPT_CLUSTER_SIZE,
2066                                          DEFAULT_CLUSTER_SIZE);
2067     buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
2068     prealloc = qapi_enum_parse(PreallocMode_lookup, buf,
2069                                PREALLOC_MODE_MAX, PREALLOC_MODE_OFF,
2070                                &local_err);
2071     if (local_err) {
2072         error_propagate(errp, local_err);
2073         ret = -EINVAL;
2074         goto finish;
2075     }
2076     g_free(buf);
2077     buf = qemu_opt_get_del(opts, BLOCK_OPT_COMPAT_LEVEL);
2078     if (!buf) {
2079         /* keep the default */
2080     } else if (!strcmp(buf, "0.10")) {
2081         version = 2;
2082     } else if (!strcmp(buf, "1.1")) {
2083         version = 3;
2084     } else {
2085         error_setg(errp, "Invalid compatibility level: '%s'", buf);
2086         ret = -EINVAL;
2087         goto finish;
2088     }
2089
2090     if (qemu_opt_get_bool_del(opts, BLOCK_OPT_LAZY_REFCOUNTS, false)) {
2091         flags |= BLOCK_FLAG_LAZY_REFCOUNTS;
2092     }
2093
2094     if (backing_file && prealloc != PREALLOC_MODE_OFF) {
2095         error_setg(errp, "Backing file and preallocation cannot be used at "
2096                    "the same time");
2097         ret = -EINVAL;
2098         goto finish;
2099     }
2100
2101     if (version < 3 && (flags & BLOCK_FLAG_LAZY_REFCOUNTS)) {
2102         error_setg(errp, "Lazy refcounts only supported with compatibility "
2103                    "level 1.1 and above (use compat=1.1 or greater)");
2104         ret = -EINVAL;
2105         goto finish;
2106     }
2107
2108     refcount_bits = qemu_opt_get_number_del(opts, BLOCK_OPT_REFCOUNT_BITS,
2109                                             refcount_bits);
2110     if (refcount_bits > 64 || !is_power_of_2(refcount_bits)) {
2111         error_setg(errp, "Refcount width must be a power of two and may not "
2112                    "exceed 64 bits");
2113         ret = -EINVAL;
2114         goto finish;
2115     }
2116
2117     if (version < 3 && refcount_bits != 16) {
2118         error_setg(errp, "Different refcount widths than 16 bits require "
2119                    "compatibility level 1.1 or above (use compat=1.1 or "
2120                    "greater)");
2121         ret = -EINVAL;
2122         goto finish;
2123     }
2124
2125     refcount_order = ctz32(refcount_bits);
2126
2127     ret = qcow2_create2(filename, size, backing_file, backing_fmt, flags,
2128                         cluster_size, prealloc, opts, version, refcount_order,
2129                         &local_err);
2130     if (local_err) {
2131         error_propagate(errp, local_err);
2132     }
2133
2134 finish:
2135     g_free(backing_file);
2136     g_free(backing_fmt);
2137     g_free(buf);
2138     return ret;
2139 }
2140
2141 static coroutine_fn int qcow2_co_write_zeroes(BlockDriverState *bs,
2142     int64_t sector_num, int nb_sectors, BdrvRequestFlags flags)
2143 {
2144     int ret;
2145     BDRVQcowState *s = bs->opaque;
2146
2147     /* Emulate misaligned zero writes */
2148     if (sector_num % s->cluster_sectors || nb_sectors % s->cluster_sectors) {
2149         return -ENOTSUP;
2150     }
2151
2152     /* Whatever is left can use real zero clusters */
2153     qemu_co_mutex_lock(&s->lock);
2154     ret = qcow2_zero_clusters(bs, sector_num << BDRV_SECTOR_BITS,
2155         nb_sectors);
2156     qemu_co_mutex_unlock(&s->lock);
2157
2158     return ret;
2159 }
2160
2161 static coroutine_fn int qcow2_co_discard(BlockDriverState *bs,
2162     int64_t sector_num, int nb_sectors)
2163 {
2164     int ret;
2165     BDRVQcowState *s = bs->opaque;
2166
2167     qemu_co_mutex_lock(&s->lock);
2168     ret = qcow2_discard_clusters(bs, sector_num << BDRV_SECTOR_BITS,
2169         nb_sectors, QCOW2_DISCARD_REQUEST, false);
2170     qemu_co_mutex_unlock(&s->lock);
2171     return ret;
2172 }
2173
2174 static int qcow2_truncate(BlockDriverState *bs, int64_t offset)
2175 {
2176     BDRVQcowState *s = bs->opaque;
2177     int64_t new_l1_size;
2178     int ret;
2179
2180     if (offset & 511) {
2181         error_report("The new size must be a multiple of 512");
2182         return -EINVAL;
2183     }
2184
2185     /* cannot proceed if image has snapshots */
2186     if (s->nb_snapshots) {
2187         error_report("Can't resize an image which has snapshots");
2188         return -ENOTSUP;
2189     }
2190
2191     /* shrinking is currently not supported */
2192     if (offset < bs->total_sectors * 512) {
2193         error_report("qcow2 doesn't support shrinking images yet");
2194         return -ENOTSUP;
2195     }
2196
2197     new_l1_size = size_to_l1(s, offset);
2198     ret = qcow2_grow_l1_table(bs, new_l1_size, true);
2199     if (ret < 0) {
2200         return ret;
2201     }
2202
2203     /* write updated header.size */
2204     offset = cpu_to_be64(offset);
2205     ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, size),
2206                            &offset, sizeof(uint64_t));
2207     if (ret < 0) {
2208         return ret;
2209     }
2210
2211     s->l1_vm_state_index = new_l1_size;
2212     return 0;
2213 }
2214
2215 /* XXX: put compressed sectors first, then all the cluster aligned
2216    tables to avoid losing bytes in alignment */
2217 static int qcow2_write_compressed(BlockDriverState *bs, int64_t sector_num,
2218                                   const uint8_t *buf, int nb_sectors)
2219 {
2220     BDRVQcowState *s = bs->opaque;
2221     z_stream strm;
2222     int ret, out_len;
2223     uint8_t *out_buf;
2224     uint64_t cluster_offset;
2225
2226     if (nb_sectors == 0) {
2227         /* align end of file to a sector boundary to ease reading with
2228            sector based I/Os */
2229         cluster_offset = bdrv_getlength(bs->file);
2230         return bdrv_truncate(bs->file, cluster_offset);
2231     }
2232
2233     if (nb_sectors != s->cluster_sectors) {
2234         ret = -EINVAL;
2235
2236         /* Zero-pad last write if image size is not cluster aligned */
2237         if (sector_num + nb_sectors == bs->total_sectors &&
2238             nb_sectors < s->cluster_sectors) {
2239             uint8_t *pad_buf = qemu_blockalign(bs, s->cluster_size);
2240             memset(pad_buf, 0, s->cluster_size);
2241             memcpy(pad_buf, buf, nb_sectors * BDRV_SECTOR_SIZE);
2242             ret = qcow2_write_compressed(bs, sector_num,
2243                                          pad_buf, s->cluster_sectors);
2244             qemu_vfree(pad_buf);
2245         }
2246         return ret;
2247     }
2248
2249     out_buf = g_malloc(s->cluster_size + (s->cluster_size / 1000) + 128);
2250
2251     /* best compression, small window, no zlib header */
2252     memset(&strm, 0, sizeof(strm));
2253     ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
2254                        Z_DEFLATED, -12,
2255                        9, Z_DEFAULT_STRATEGY);
2256     if (ret != 0) {
2257         ret = -EINVAL;
2258         goto fail;
2259     }
2260
2261     strm.avail_in = s->cluster_size;
2262     strm.next_in = (uint8_t *)buf;
2263     strm.avail_out = s->cluster_size;
2264     strm.next_out = out_buf;
2265
2266     ret = deflate(&strm, Z_FINISH);
2267     if (ret != Z_STREAM_END && ret != Z_OK) {
2268         deflateEnd(&strm);
2269         ret = -EINVAL;
2270         goto fail;
2271     }
2272     out_len = strm.next_out - out_buf;
2273
2274     deflateEnd(&strm);
2275
2276     if (ret != Z_STREAM_END || out_len >= s->cluster_size) {
2277         /* could not compress: write normal cluster */
2278         ret = bdrv_write(bs, sector_num, buf, s->cluster_sectors);
2279         if (ret < 0) {
2280             goto fail;
2281         }
2282     } else {
2283         cluster_offset = qcow2_alloc_compressed_cluster_offset(bs,
2284             sector_num << 9, out_len);
2285         if (!cluster_offset) {
2286             ret = -EIO;
2287             goto fail;
2288         }
2289         cluster_offset &= s->cluster_offset_mask;
2290
2291         ret = qcow2_pre_write_overlap_check(bs, 0, cluster_offset, out_len);
2292         if (ret < 0) {
2293             goto fail;
2294         }
2295
2296         BLKDBG_EVENT(bs->file, BLKDBG_WRITE_COMPRESSED);
2297         ret = bdrv_pwrite(bs->file, cluster_offset, out_buf, out_len);
2298         if (ret < 0) {
2299             goto fail;
2300         }
2301     }
2302
2303     ret = 0;
2304 fail:
2305     g_free(out_buf);
2306     return ret;
2307 }
2308
2309 static int make_completely_empty(BlockDriverState *bs)
2310 {
2311     BDRVQcowState *s = bs->opaque;
2312     int ret, l1_clusters;
2313     int64_t offset;
2314     uint64_t *new_reftable = NULL;
2315     uint64_t rt_entry, l1_size2;
2316     struct {
2317         uint64_t l1_offset;
2318         uint64_t reftable_offset;
2319         uint32_t reftable_clusters;
2320     } QEMU_PACKED l1_ofs_rt_ofs_cls;
2321
2322     ret = qcow2_cache_empty(bs, s->l2_table_cache);
2323     if (ret < 0) {
2324         goto fail;
2325     }
2326
2327     ret = qcow2_cache_empty(bs, s->refcount_block_cache);
2328     if (ret < 0) {
2329         goto fail;
2330     }
2331
2332     /* Refcounts will be broken utterly */
2333     ret = qcow2_mark_dirty(bs);
2334     if (ret < 0) {
2335         goto fail;
2336     }
2337
2338     BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
2339
2340     l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / sizeof(uint64_t));
2341     l1_size2 = (uint64_t)s->l1_size * sizeof(uint64_t);
2342
2343     /* After this call, neither the in-memory nor the on-disk refcount
2344      * information accurately describe the actual references */
2345
2346     ret = bdrv_write_zeroes(bs->file, s->l1_table_offset / BDRV_SECTOR_SIZE,
2347                             l1_clusters * s->cluster_sectors, 0);
2348     if (ret < 0) {
2349         goto fail_broken_refcounts;
2350     }
2351     memset(s->l1_table, 0, l1_size2);
2352
2353     BLKDBG_EVENT(bs->file, BLKDBG_EMPTY_IMAGE_PREPARE);
2354
2355     /* Overwrite enough clusters at the beginning of the sectors to place
2356      * the refcount table, a refcount block and the L1 table in; this may
2357      * overwrite parts of the existing refcount and L1 table, which is not
2358      * an issue because the dirty flag is set, complete data loss is in fact
2359      * desired and partial data loss is consequently fine as well */
2360     ret = bdrv_write_zeroes(bs->file, s->cluster_size / BDRV_SECTOR_SIZE,
2361                             (2 + l1_clusters) * s->cluster_size /
2362                             BDRV_SECTOR_SIZE, 0);
2363     /* This call (even if it failed overall) may have overwritten on-disk
2364      * refcount structures; in that case, the in-memory refcount information
2365      * will probably differ from the on-disk information which makes the BDS
2366      * unusable */
2367     if (ret < 0) {
2368         goto fail_broken_refcounts;
2369     }
2370
2371     BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
2372     BLKDBG_EVENT(bs->file, BLKDBG_REFTABLE_UPDATE);
2373
2374     /* "Create" an empty reftable (one cluster) directly after the image
2375      * header and an empty L1 table three clusters after the image header;
2376      * the cluster between those two will be used as the first refblock */
2377     cpu_to_be64w(&l1_ofs_rt_ofs_cls.l1_offset, 3 * s->cluster_size);
2378     cpu_to_be64w(&l1_ofs_rt_ofs_cls.reftable_offset, s->cluster_size);
2379     cpu_to_be32w(&l1_ofs_rt_ofs_cls.reftable_clusters, 1);
2380     ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, l1_table_offset),
2381                            &l1_ofs_rt_ofs_cls, sizeof(l1_ofs_rt_ofs_cls));
2382     if (ret < 0) {
2383         goto fail_broken_refcounts;
2384     }
2385
2386     s->l1_table_offset = 3 * s->cluster_size;
2387
2388     new_reftable = g_try_new0(uint64_t, s->cluster_size / sizeof(uint64_t));
2389     if (!new_reftable) {
2390         ret = -ENOMEM;
2391         goto fail_broken_refcounts;
2392     }
2393
2394     s->refcount_table_offset = s->cluster_size;
2395     s->refcount_table_size   = s->cluster_size / sizeof(uint64_t);
2396
2397     g_free(s->refcount_table);
2398     s->refcount_table = new_reftable;
2399     new_reftable = NULL;
2400
2401     /* Now the in-memory refcount information again corresponds to the on-disk
2402      * information (reftable is empty and no refblocks (the refblock cache is
2403      * empty)); however, this means some clusters (e.g. the image header) are
2404      * referenced, but not refcounted, but the normal qcow2 code assumes that
2405      * the in-memory information is always correct */
2406
2407     BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_ALLOC);
2408
2409     /* Enter the first refblock into the reftable */
2410     rt_entry = cpu_to_be64(2 * s->cluster_size);
2411     ret = bdrv_pwrite_sync(bs->file, s->cluster_size,
2412                            &rt_entry, sizeof(rt_entry));
2413     if (ret < 0) {
2414         goto fail_broken_refcounts;
2415     }
2416     s->refcount_table[0] = 2 * s->cluster_size;
2417
2418     s->free_cluster_index = 0;
2419     assert(3 + l1_clusters <= s->refcount_block_size);
2420     offset = qcow2_alloc_clusters(bs, 3 * s->cluster_size + l1_size2);
2421     if (offset < 0) {
2422         ret = offset;
2423         goto fail_broken_refcounts;
2424     } else if (offset > 0) {
2425         error_report("First cluster in emptied image is in use");
2426         abort();
2427     }
2428
2429     /* Now finally the in-memory information corresponds to the on-disk
2430      * structures and is correct */
2431     ret = qcow2_mark_clean(bs);
2432     if (ret < 0) {
2433         goto fail;
2434     }
2435
2436     ret = bdrv_truncate(bs->file, (3 + l1_clusters) * s->cluster_size);
2437     if (ret < 0) {
2438         goto fail;
2439     }
2440
2441     return 0;
2442
2443 fail_broken_refcounts:
2444     /* The BDS is unusable at this point. If we wanted to make it usable, we
2445      * would have to call qcow2_refcount_close(), qcow2_refcount_init(),
2446      * qcow2_check_refcounts(), qcow2_refcount_close() and qcow2_refcount_init()
2447      * again. However, because the functions which could have caused this error
2448      * path to be taken are used by those functions as well, it's very likely
2449      * that that sequence will fail as well. Therefore, just eject the BDS. */
2450     bs->drv = NULL;
2451
2452 fail:
2453     g_free(new_reftable);
2454     return ret;
2455 }
2456
2457 static int qcow2_make_empty(BlockDriverState *bs)
2458 {
2459     BDRVQcowState *s = bs->opaque;
2460     uint64_t start_sector;
2461     int sector_step = INT_MAX / BDRV_SECTOR_SIZE;
2462     int l1_clusters, ret = 0;
2463
2464     l1_clusters = DIV_ROUND_UP(s->l1_size, s->cluster_size / sizeof(uint64_t));
2465
2466     if (s->qcow_version >= 3 && !s->snapshots &&
2467         3 + l1_clusters <= s->refcount_block_size) {
2468         /* The following function only works for qcow2 v3 images (it requires
2469          * the dirty flag) and only as long as there are no snapshots (because
2470          * it completely empties the image). Furthermore, the L1 table and three
2471          * additional clusters (image header, refcount table, one refcount
2472          * block) have to fit inside one refcount block. */
2473         return make_completely_empty(bs);
2474     }
2475
2476     /* This fallback code simply discards every active cluster; this is slow,
2477      * but works in all cases */
2478     for (start_sector = 0; start_sector < bs->total_sectors;
2479          start_sector += sector_step)
2480     {
2481         /* As this function is generally used after committing an external
2482          * snapshot, QCOW2_DISCARD_SNAPSHOT seems appropriate. Also, the
2483          * default action for this kind of discard is to pass the discard,
2484          * which will ideally result in an actually smaller image file, as
2485          * is probably desired. */
2486         ret = qcow2_discard_clusters(bs, start_sector * BDRV_SECTOR_SIZE,
2487                                      MIN(sector_step,
2488                                          bs->total_sectors - start_sector),
2489                                      QCOW2_DISCARD_SNAPSHOT, true);
2490         if (ret < 0) {
2491             break;
2492         }
2493     }
2494
2495     return ret;
2496 }
2497
2498 static coroutine_fn int qcow2_co_flush_to_os(BlockDriverState *bs)
2499 {
2500     BDRVQcowState *s = bs->opaque;
2501     int ret;
2502
2503     qemu_co_mutex_lock(&s->lock);
2504     ret = qcow2_cache_flush(bs, s->l2_table_cache);
2505     if (ret < 0) {
2506         qemu_co_mutex_unlock(&s->lock);
2507         return ret;
2508     }
2509
2510     if (qcow2_need_accurate_refcounts(s)) {
2511         ret = qcow2_cache_flush(bs, s->refcount_block_cache);
2512         if (ret < 0) {
2513             qemu_co_mutex_unlock(&s->lock);
2514             return ret;
2515         }
2516     }
2517     qemu_co_mutex_unlock(&s->lock);
2518
2519     return 0;
2520 }
2521
2522 static int qcow2_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
2523 {
2524     BDRVQcowState *s = bs->opaque;
2525     bdi->unallocated_blocks_are_zero = true;
2526     bdi->can_write_zeroes_with_unmap = (s->qcow_version >= 3);
2527     bdi->cluster_size = s->cluster_size;
2528     bdi->vm_state_offset = qcow2_vm_state_offset(s);
2529     return 0;
2530 }
2531
2532 static ImageInfoSpecific *qcow2_get_specific_info(BlockDriverState *bs)
2533 {
2534     BDRVQcowState *s = bs->opaque;
2535     ImageInfoSpecific *spec_info = g_new(ImageInfoSpecific, 1);
2536
2537     *spec_info = (ImageInfoSpecific){
2538         .kind  = IMAGE_INFO_SPECIFIC_KIND_QCOW2,
2539         {
2540             .qcow2 = g_new(ImageInfoSpecificQCow2, 1),
2541         },
2542     };
2543     if (s->qcow_version == 2) {
2544         *spec_info->qcow2 = (ImageInfoSpecificQCow2){
2545             .compat             = g_strdup("0.10"),
2546             .refcount_bits      = s->refcount_bits,
2547         };
2548     } else if (s->qcow_version == 3) {
2549         *spec_info->qcow2 = (ImageInfoSpecificQCow2){
2550             .compat             = g_strdup("1.1"),
2551             .lazy_refcounts     = s->compatible_features &
2552                                   QCOW2_COMPAT_LAZY_REFCOUNTS,
2553             .has_lazy_refcounts = true,
2554             .corrupt            = s->incompatible_features &
2555                                   QCOW2_INCOMPAT_CORRUPT,
2556             .has_corrupt        = true,
2557             .refcount_bits      = s->refcount_bits,
2558         };
2559     }
2560
2561     return spec_info;
2562 }
2563
2564 #if 0
2565 static void dump_refcounts(BlockDriverState *bs)
2566 {
2567     BDRVQcowState *s = bs->opaque;
2568     int64_t nb_clusters, k, k1, size;
2569     int refcount;
2570
2571     size = bdrv_getlength(bs->file);
2572     nb_clusters = size_to_clusters(s, size);
2573     for(k = 0; k < nb_clusters;) {
2574         k1 = k;
2575         refcount = get_refcount(bs, k);
2576         k++;
2577         while (k < nb_clusters && get_refcount(bs, k) == refcount)
2578             k++;
2579         printf("%" PRId64 ": refcount=%d nb=%" PRId64 "\n", k, refcount,
2580                k - k1);
2581     }
2582 }
2583 #endif
2584
2585 static int qcow2_save_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,
2586                               int64_t pos)
2587 {
2588     BDRVQcowState *s = bs->opaque;
2589     int64_t total_sectors = bs->total_sectors;
2590     bool zero_beyond_eof = bs->zero_beyond_eof;
2591     int ret;
2592
2593     BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_SAVE);
2594     bs->zero_beyond_eof = false;
2595     ret = bdrv_pwritev(bs, qcow2_vm_state_offset(s) + pos, qiov);
2596     bs->zero_beyond_eof = zero_beyond_eof;
2597
2598     /* bdrv_co_do_writev will have increased the total_sectors value to include
2599      * the VM state - the VM state is however not an actual part of the block
2600      * device, therefore, we need to restore the old value. */
2601     bs->total_sectors = total_sectors;
2602
2603     return ret;
2604 }
2605
2606 static int qcow2_load_vmstate(BlockDriverState *bs, uint8_t *buf,
2607                               int64_t pos, int size)
2608 {
2609     BDRVQcowState *s = bs->opaque;
2610     bool zero_beyond_eof = bs->zero_beyond_eof;
2611     int ret;
2612
2613     BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_LOAD);
2614     bs->zero_beyond_eof = false;
2615     ret = bdrv_pread(bs, qcow2_vm_state_offset(s) + pos, buf, size);
2616     bs->zero_beyond_eof = zero_beyond_eof;
2617
2618     return ret;
2619 }
2620
2621 /*
2622  * Downgrades an image's version. To achieve this, any incompatible features
2623  * have to be removed.
2624  */
2625 static int qcow2_downgrade(BlockDriverState *bs, int target_version,
2626                            BlockDriverAmendStatusCB *status_cb)
2627 {
2628     BDRVQcowState *s = bs->opaque;
2629     int current_version = s->qcow_version;
2630     int ret;
2631
2632     if (target_version == current_version) {
2633         return 0;
2634     } else if (target_version > current_version) {
2635         return -EINVAL;
2636     } else if (target_version != 2) {
2637         return -EINVAL;
2638     }
2639
2640     if (s->refcount_order != 4) {
2641         /* we would have to convert the image to a refcount_order == 4 image
2642          * here; however, since qemu (at the time of writing this) does not
2643          * support anything different than 4 anyway, there is no point in doing
2644          * so right now; however, we should error out (if qemu supports this in
2645          * the future and this code has not been adapted) */
2646         error_report("qcow2_downgrade: Image refcount orders other than 4 are "
2647                      "currently not supported.");
2648         return -ENOTSUP;
2649     }
2650
2651     /* clear incompatible features */
2652     if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
2653         ret = qcow2_mark_clean(bs);
2654         if (ret < 0) {
2655             return ret;
2656         }
2657     }
2658
2659     /* with QCOW2_INCOMPAT_CORRUPT, it is pretty much impossible to get here in
2660      * the first place; if that happens nonetheless, returning -ENOTSUP is the
2661      * best thing to do anyway */
2662
2663     if (s->incompatible_features) {
2664         return -ENOTSUP;
2665     }
2666
2667     /* since we can ignore compatible features, we can set them to 0 as well */
2668     s->compatible_features = 0;
2669     /* if lazy refcounts have been used, they have already been fixed through
2670      * clearing the dirty flag */
2671
2672     /* clearing autoclear features is trivial */
2673     s->autoclear_features = 0;
2674
2675     ret = qcow2_expand_zero_clusters(bs, status_cb);
2676     if (ret < 0) {
2677         return ret;
2678     }
2679
2680     s->qcow_version = target_version;
2681     ret = qcow2_update_header(bs);
2682     if (ret < 0) {
2683         s->qcow_version = current_version;
2684         return ret;
2685     }
2686     return 0;
2687 }
2688
2689 static int qcow2_amend_options(BlockDriverState *bs, QemuOpts *opts,
2690                                BlockDriverAmendStatusCB *status_cb)
2691 {
2692     BDRVQcowState *s = bs->opaque;
2693     int old_version = s->qcow_version, new_version = old_version;
2694     uint64_t new_size = 0;
2695     const char *backing_file = NULL, *backing_format = NULL;
2696     bool lazy_refcounts = s->use_lazy_refcounts;
2697     const char *compat = NULL;
2698     uint64_t cluster_size = s->cluster_size;
2699     bool encrypt;
2700     int ret;
2701     QemuOptDesc *desc = opts->list->desc;
2702
2703     while (desc && desc->name) {
2704         if (!qemu_opt_find(opts, desc->name)) {
2705             /* only change explicitly defined options */
2706             desc++;
2707             continue;
2708         }
2709
2710         if (!strcmp(desc->name, BLOCK_OPT_COMPAT_LEVEL)) {
2711             compat = qemu_opt_get(opts, BLOCK_OPT_COMPAT_LEVEL);
2712             if (!compat) {
2713                 /* preserve default */
2714             } else if (!strcmp(compat, "0.10")) {
2715                 new_version = 2;
2716             } else if (!strcmp(compat, "1.1")) {
2717                 new_version = 3;
2718             } else {
2719                 fprintf(stderr, "Unknown compatibility level %s.\n", compat);
2720                 return -EINVAL;
2721             }
2722         } else if (!strcmp(desc->name, BLOCK_OPT_PREALLOC)) {
2723             fprintf(stderr, "Cannot change preallocation mode.\n");
2724             return -ENOTSUP;
2725         } else if (!strcmp(desc->name, BLOCK_OPT_SIZE)) {
2726             new_size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, 0);
2727         } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FILE)) {
2728             backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
2729         } else if (!strcmp(desc->name, BLOCK_OPT_BACKING_FMT)) {
2730             backing_format = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
2731         } else if (!strcmp(desc->name, BLOCK_OPT_ENCRYPT)) {
2732             encrypt = qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT,
2733                                         !!s->cipher);
2734
2735             if (encrypt != !!s->cipher) {
2736                 fprintf(stderr, "Changing the encryption flag is not "
2737                         "supported.\n");
2738                 return -ENOTSUP;
2739             }
2740         } else if (!strcmp(desc->name, BLOCK_OPT_CLUSTER_SIZE)) {
2741             cluster_size = qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE,
2742                                              cluster_size);
2743             if (cluster_size != s->cluster_size) {
2744                 fprintf(stderr, "Changing the cluster size is not "
2745                         "supported.\n");
2746                 return -ENOTSUP;
2747             }
2748         } else if (!strcmp(desc->name, BLOCK_OPT_LAZY_REFCOUNTS)) {
2749             lazy_refcounts = qemu_opt_get_bool(opts, BLOCK_OPT_LAZY_REFCOUNTS,
2750                                                lazy_refcounts);
2751         } else if (!strcmp(desc->name, BLOCK_OPT_REFCOUNT_BITS)) {
2752             error_report("Cannot change refcount entry width");
2753             return -ENOTSUP;
2754         } else {
2755             /* if this assertion fails, this probably means a new option was
2756              * added without having it covered here */
2757             assert(false);
2758         }
2759
2760         desc++;
2761     }
2762
2763     if (new_version != old_version) {
2764         if (new_version > old_version) {
2765             /* Upgrade */
2766             s->qcow_version = new_version;
2767             ret = qcow2_update_header(bs);
2768             if (ret < 0) {
2769                 s->qcow_version = old_version;
2770                 return ret;
2771             }
2772         } else {
2773             ret = qcow2_downgrade(bs, new_version, status_cb);
2774             if (ret < 0) {
2775                 return ret;
2776             }
2777         }
2778     }
2779
2780     if (backing_file || backing_format) {
2781         ret = qcow2_change_backing_file(bs,
2782                     backing_file ?: s->image_backing_file,
2783                     backing_format ?: s->image_backing_format);
2784         if (ret < 0) {
2785             return ret;
2786         }
2787     }
2788
2789     if (s->use_lazy_refcounts != lazy_refcounts) {
2790         if (lazy_refcounts) {
2791             if (s->qcow_version < 3) {
2792                 fprintf(stderr, "Lazy refcounts only supported with compatibility "
2793                         "level 1.1 and above (use compat=1.1 or greater)\n");
2794                 return -EINVAL;
2795             }
2796             s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
2797             ret = qcow2_update_header(bs);
2798             if (ret < 0) {
2799                 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
2800                 return ret;
2801             }
2802             s->use_lazy_refcounts = true;
2803         } else {
2804             /* make image clean first */
2805             ret = qcow2_mark_clean(bs);
2806             if (ret < 0) {
2807                 return ret;
2808             }
2809             /* now disallow lazy refcounts */
2810             s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS;
2811             ret = qcow2_update_header(bs);
2812             if (ret < 0) {
2813                 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS;
2814                 return ret;
2815             }
2816             s->use_lazy_refcounts = false;
2817         }
2818     }
2819
2820     if (new_size) {
2821         ret = bdrv_truncate(bs, new_size);
2822         if (ret < 0) {
2823             return ret;
2824         }
2825     }
2826
2827     return 0;
2828 }
2829
2830 /*
2831  * If offset or size are negative, respectively, they will not be included in
2832  * the BLOCK_IMAGE_CORRUPTED event emitted.
2833  * fatal will be ignored for read-only BDS; corruptions found there will always
2834  * be considered non-fatal.
2835  */
2836 void qcow2_signal_corruption(BlockDriverState *bs, bool fatal, int64_t offset,
2837                              int64_t size, const char *message_format, ...)
2838 {
2839     BDRVQcowState *s = bs->opaque;
2840     const char *node_name;
2841     char *message;
2842     va_list ap;
2843
2844     fatal = fatal && !bs->read_only;
2845
2846     if (s->signaled_corruption &&
2847         (!fatal || (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT)))
2848     {
2849         return;
2850     }
2851
2852     va_start(ap, message_format);
2853     message = g_strdup_vprintf(message_format, ap);
2854     va_end(ap);
2855
2856     if (fatal) {
2857         fprintf(stderr, "qcow2: Marking image as corrupt: %s; further "
2858                 "corruption events will be suppressed\n", message);
2859     } else {
2860         fprintf(stderr, "qcow2: Image is corrupt: %s; further non-fatal "
2861                 "corruption events will be suppressed\n", message);
2862     }
2863
2864     node_name = bdrv_get_node_name(bs);
2865     qapi_event_send_block_image_corrupted(bdrv_get_device_name(bs),
2866                                           *node_name != '\0', node_name,
2867                                           message, offset >= 0, offset,
2868                                           size >= 0, size,
2869                                           fatal, &error_abort);
2870     g_free(message);
2871
2872     if (fatal) {
2873         qcow2_mark_corrupt(bs);
2874         bs->drv = NULL; /* make BDS unusable */
2875     }
2876
2877     s->signaled_corruption = true;
2878 }
2879
2880 static QemuOptsList qcow2_create_opts = {
2881     .name = "qcow2-create-opts",
2882     .head = QTAILQ_HEAD_INITIALIZER(qcow2_create_opts.head),
2883     .desc = {
2884         {
2885             .name = BLOCK_OPT_SIZE,
2886             .type = QEMU_OPT_SIZE,
2887             .help = "Virtual disk size"
2888         },
2889         {
2890             .name = BLOCK_OPT_COMPAT_LEVEL,
2891             .type = QEMU_OPT_STRING,
2892             .help = "Compatibility level (0.10 or 1.1)"
2893         },
2894         {
2895             .name = BLOCK_OPT_BACKING_FILE,
2896             .type = QEMU_OPT_STRING,
2897             .help = "File name of a base image"
2898         },
2899         {
2900             .name = BLOCK_OPT_BACKING_FMT,
2901             .type = QEMU_OPT_STRING,
2902             .help = "Image format of the base image"
2903         },
2904         {
2905             .name = BLOCK_OPT_ENCRYPT,
2906             .type = QEMU_OPT_BOOL,
2907             .help = "Encrypt the image",
2908             .def_value_str = "off"
2909         },
2910         {
2911             .name = BLOCK_OPT_CLUSTER_SIZE,
2912             .type = QEMU_OPT_SIZE,
2913             .help = "qcow2 cluster size",
2914             .def_value_str = stringify(DEFAULT_CLUSTER_SIZE)
2915         },
2916         {
2917             .name = BLOCK_OPT_PREALLOC,
2918             .type = QEMU_OPT_STRING,
2919             .help = "Preallocation mode (allowed values: off, metadata, "
2920                     "falloc, full)"
2921         },
2922         {
2923             .name = BLOCK_OPT_LAZY_REFCOUNTS,
2924             .type = QEMU_OPT_BOOL,
2925             .help = "Postpone refcount updates",
2926             .def_value_str = "off"
2927         },
2928         {
2929             .name = BLOCK_OPT_REFCOUNT_BITS,
2930             .type = QEMU_OPT_NUMBER,
2931             .help = "Width of a reference count entry in bits",
2932             .def_value_str = "16"
2933         },
2934         { /* end of list */ }
2935     }
2936 };
2937
2938 BlockDriver bdrv_qcow2 = {
2939     .format_name        = "qcow2",
2940     .instance_size      = sizeof(BDRVQcowState),
2941     .bdrv_probe         = qcow2_probe,
2942     .bdrv_open          = qcow2_open,
2943     .bdrv_close         = qcow2_close,
2944     .bdrv_reopen_prepare  = qcow2_reopen_prepare,
2945     .bdrv_create        = qcow2_create,
2946     .bdrv_has_zero_init = bdrv_has_zero_init_1,
2947     .bdrv_co_get_block_status = qcow2_co_get_block_status,
2948     .bdrv_set_key       = qcow2_set_key,
2949
2950     .bdrv_co_readv          = qcow2_co_readv,
2951     .bdrv_co_writev         = qcow2_co_writev,
2952     .bdrv_co_flush_to_os    = qcow2_co_flush_to_os,
2953
2954     .bdrv_co_write_zeroes   = qcow2_co_write_zeroes,
2955     .bdrv_co_discard        = qcow2_co_discard,
2956     .bdrv_truncate          = qcow2_truncate,
2957     .bdrv_write_compressed  = qcow2_write_compressed,
2958     .bdrv_make_empty        = qcow2_make_empty,
2959
2960     .bdrv_snapshot_create   = qcow2_snapshot_create,
2961     .bdrv_snapshot_goto     = qcow2_snapshot_goto,
2962     .bdrv_snapshot_delete   = qcow2_snapshot_delete,
2963     .bdrv_snapshot_list     = qcow2_snapshot_list,
2964     .bdrv_snapshot_load_tmp = qcow2_snapshot_load_tmp,
2965     .bdrv_get_info          = qcow2_get_info,
2966     .bdrv_get_specific_info = qcow2_get_specific_info,
2967
2968     .bdrv_save_vmstate    = qcow2_save_vmstate,
2969     .bdrv_load_vmstate    = qcow2_load_vmstate,
2970
2971     .supports_backing           = true,
2972     .bdrv_change_backing_file   = qcow2_change_backing_file,
2973
2974     .bdrv_refresh_limits        = qcow2_refresh_limits,
2975     .bdrv_invalidate_cache      = qcow2_invalidate_cache,
2976
2977     .create_opts         = &qcow2_create_opts,
2978     .bdrv_check          = qcow2_check,
2979     .bdrv_amend_options  = qcow2_amend_options,
2980 };
2981
2982 static void bdrv_qcow2_init(void)
2983 {
2984     bdrv_register(&bdrv_qcow2);
2985 }
2986
2987 block_init(bdrv_qcow2_init);